qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
sequencelengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
8,964,461
I would like to create a subclass of python's unittest.Testcase called BasicTest. I would like each subclass of BasicTest to run the same routine in main. How can I accomplish this? Example: ``` in basic_test.py: class BasicTest(unittest.TestCase): ... if __name__ == '__main__': # Do optparse stuff unittest.main() in some_basic_test.py: class SomeBasicTest(BasicTest): ... if __name__ == '__main__': #call the main in basic_test.py ```
2012/01/22
[ "https://Stackoverflow.com/questions/8964461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/766953/" ]
``` # basic_test.py class BasicTest(unittest.TestCase): @staticmethod def main(): # Do optparse stuff unittest.main() if __name__ == '__main__': BasicTest.main() # some_basic_test.py class SomeBasicTest(BasicTest): ... if __name__ == '__main__': BasicTest.main() ```
You cannot (re)import a module as a new **main**, thus the `if __name__=="__main__"` code is kind of unreachable. Dor’s suggestion or something similar seems most reasonable. However if you have no access to the module in question, you might consider looking at the [runpy.run\_module()](http://docs.python.org/library/runpy.html#runpy.run_module) that executes a module as main.
8,964,461
I would like to create a subclass of python's unittest.Testcase called BasicTest. I would like each subclass of BasicTest to run the same routine in main. How can I accomplish this? Example: ``` in basic_test.py: class BasicTest(unittest.TestCase): ... if __name__ == '__main__': # Do optparse stuff unittest.main() in some_basic_test.py: class SomeBasicTest(BasicTest): ... if __name__ == '__main__': #call the main in basic_test.py ```
2012/01/22
[ "https://Stackoverflow.com/questions/8964461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/766953/" ]
``` # basic_test.py class BasicTest(unittest.TestCase): @staticmethod def main(): # Do optparse stuff unittest.main() if __name__ == '__main__': BasicTest.main() # some_basic_test.py class SomeBasicTest(BasicTest): ... if __name__ == '__main__': BasicTest.main() ```
> > I would like each subclass of BasicTest to run the same routine in main > > > I guess what you want is to run some setup/initialization code before running tests from any test case. In this case you might be interested in [`setUpClass`](http://docs.python.org/library/unittest.html#class-and-module-fixtures) class method. testA.py ``` import unittest class BasicTest(unittest.TestCase): @classmethod def setUpClass(cls): print 'Preparing to run tests' class TestA(BasicTest): def test1(self): print 'testA: test1' def test2(self): print 'testA: test2' if __name__ == '__main__': unittest.main() ``` testB.py ``` import unittest from testA import BasicTest class TestB(BasicTest): def test1(self): print 'testB: test1' def test2(self): print 'testB: test2' if __name__ == '__main__': unittest.main() ``` Output from testA.py: ``` Preparing to run tests testA: test1 testA: test2 .. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK ``` Output from testB.py: ``` Preparing to run tests testB: test1 testB: test2 .. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK ```
4,879,324
Suppose I want to include a library: ``` #include <library.h> ``` but I'm not sure it's installed in the system. The usual way is to use tool like autotools. Is there a simpler way in C++? For example in python you can handle it with exceptions.
2011/02/02
[ "https://Stackoverflow.com/questions/4879324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238671/" ]
autotools is the best way to detect at *compile* time. It's very platform-specific, but assuming you're on Linux or similar, [dlopen](http://linux.die.net/man/3/dlopen) is how you check at *runtime*.
As far as I know, there's no way of checking whether a library is installed using code. However, you could create a bash script that could look for the library in the usual places, like /usr/lib or /usr/local/lib. Also, you could check /etc/ld.so.conf for the folders and then look for the libraries. Or something like that.
14,983,015
I'm trying to write a large python/bash script which converts my html/css mockups to Shopify themes. One step in this process is changing out all the script sources. For instance: ``` <script type="text/javascript" src="./js/jquery.bxslider.min.js"></script> ``` becomes ``` <script type="text/javascript" src="{{ 'jquery.bxslider.min.js' | asset_url }}"></script> ``` Here is what I have so far: ``` import re test = """ <script type="text/javascript" src="./js/jquery-1.8.3.min.js"></script> <!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>--> <script type="text/javascript" src="./js/ie-amendments.js"></script> <script type="text/javascript" src="./js/jquery.bxslider.min.js"></script> <script type="text/javascript" src="./js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="./js/main.js"></script> """ out = re.sub( 'src=\"(.+)\"', 'src="{{ \'\\1\' | asset_url }}"', test, flags=re.MULTILINE ) out ``` prints out ``` '\n <script type="text/javascript" src="{{ \'./js/jquery-1.8.3.min.js\' | asset_url }}"></script>\n <!--<script src="{{ \'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript\' | asset_url }}"></script>-->\n <script type="text/javascript" src="{{ \'./js/ie-amendments.js\' | asset_url }}"></script>\n <script type="text/javascript" src="{{ \'./js/jquery.bxslider.min.js\' | asset_url }}"></script>\n <script type="text/javascript" src="{{ \'./js/jquery.colorbox-min.js\' | asset_url }}"></script>\n <script type="text/javascript" src="{{ \'./js/main.js\' | asset_url }}"></script>\n' ``` I have two problems so far: 1. Some of the backslash characters I'm using to escape the single quotes within my regexes are showing up in the output. 2. My capture group is capturing the entire original source string, but I just need what comes after the last "/" **ANSWER**: Per Martijn Pieters helpful suggestion, I checked out the ? regular expression operator, and came up with this solution, which perfectly solved my problem. Also, for the replacement expression, I encapsulated it in double-quotes as opposed to singles, and escaped the doubles, which ended up removing the unnecessary backslashes. Thanks guys! ``` re.sub( r'src=".+?([^/]+?\.js)"', "src=\"{{ '\\1' | asset_url }}\"", test, flags=re.MULTILINE ) ```
2013/02/20
[ "https://Stackoverflow.com/questions/14983015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1623223/" ]
You can just go to azure's control panel and add in a virtual directory path. Please visit this MDSN blog to see how its done. <http://blogs.msdn.com/b/kaushal/archive/2014/04/19/microsoft-azure-web-sites-deploying-wordpress-to-a-virtual-directory-within-the-azure-web-site.aspx>
If you use Web deploy publish method you can set in Site name `mydomain/mymvcsite` instead of `mydomain`. At least it works for me for default windows azure site `http://mydomain.azurewebsites.net/mymvcsite`. Or you can use FTP publish method.
14,983,015
I'm trying to write a large python/bash script which converts my html/css mockups to Shopify themes. One step in this process is changing out all the script sources. For instance: ``` <script type="text/javascript" src="./js/jquery.bxslider.min.js"></script> ``` becomes ``` <script type="text/javascript" src="{{ 'jquery.bxslider.min.js' | asset_url }}"></script> ``` Here is what I have so far: ``` import re test = """ <script type="text/javascript" src="./js/jquery-1.8.3.min.js"></script> <!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>--> <script type="text/javascript" src="./js/ie-amendments.js"></script> <script type="text/javascript" src="./js/jquery.bxslider.min.js"></script> <script type="text/javascript" src="./js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="./js/main.js"></script> """ out = re.sub( 'src=\"(.+)\"', 'src="{{ \'\\1\' | asset_url }}"', test, flags=re.MULTILINE ) out ``` prints out ``` '\n <script type="text/javascript" src="{{ \'./js/jquery-1.8.3.min.js\' | asset_url }}"></script>\n <!--<script src="{{ \'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript\' | asset_url }}"></script>-->\n <script type="text/javascript" src="{{ \'./js/ie-amendments.js\' | asset_url }}"></script>\n <script type="text/javascript" src="{{ \'./js/jquery.bxslider.min.js\' | asset_url }}"></script>\n <script type="text/javascript" src="{{ \'./js/jquery.colorbox-min.js\' | asset_url }}"></script>\n <script type="text/javascript" src="{{ \'./js/main.js\' | asset_url }}"></script>\n' ``` I have two problems so far: 1. Some of the backslash characters I'm using to escape the single quotes within my regexes are showing up in the output. 2. My capture group is capturing the entire original source string, but I just need what comes after the last "/" **ANSWER**: Per Martijn Pieters helpful suggestion, I checked out the ? regular expression operator, and came up with this solution, which perfectly solved my problem. Also, for the replacement expression, I encapsulated it in double-quotes as opposed to singles, and escaped the doubles, which ended up removing the unnecessary backslashes. Thanks guys! ``` re.sub( r'src=".+?([^/]+?\.js)"', "src=\"{{ '\\1' | asset_url }}\"", test, flags=re.MULTILINE ) ```
2013/02/20
[ "https://Stackoverflow.com/questions/14983015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1623223/" ]
If you use Web deploy publish method you can set in Site name `mydomain/mymvcsite` instead of `mydomain`. At least it works for me for default windows azure site `http://mydomain.azurewebsites.net/mymvcsite`. Or you can use FTP publish method.
**Basically this needs following steps to be done to make it working.** Solution contains i) sampleApp.API(.Net Core Web API) ii)sampleApp.UI( Angular App) Setting up Azure portal for two applications 1) Go to your web app in azure portal -> Settings->configurations 2) Select Path Mappings and here create new mapping entry for subsite .While adding this entry don't select directory checkbox to keep this as virtual application type.Click save ``` **Virtual Path:** /{folderName} **physicalPath:** /site/wwwroot/{folderName} ``` 3) Now go to VS2017 right click your API project and click publish 4) In publish settings window make paths as ``` site name : existing + "/{folderName} " DestinationUrl : existing + "/{folderName} " ``` 5) Now ng-build --prod your angular app and deploy dist/clientApp folder and publish with root paths. so now both should work as ``` angular app https://{AzureAppName}.azurewebsites.net Web API https://{AzureAppName}.azurewebsites.net/{folderName}/api/{controllerName}/{action} ``` If still user face "cant read configuration data from web.config" issue while accessing api project For this in your API project go to startup.cs and change configure function to have following line of code ``` app.Map('/{folderName}', app1 => Configure1(app1, loggerFactory); ``` and create in blank copy of configure function with name configure1 and redeploy your API project as mentioned above. ``` public void Configure1(IApplicationBuilder app, ILoggerFactory loggerFactory) { //keep it blank } ```
14,983,015
I'm trying to write a large python/bash script which converts my html/css mockups to Shopify themes. One step in this process is changing out all the script sources. For instance: ``` <script type="text/javascript" src="./js/jquery.bxslider.min.js"></script> ``` becomes ``` <script type="text/javascript" src="{{ 'jquery.bxslider.min.js' | asset_url }}"></script> ``` Here is what I have so far: ``` import re test = """ <script type="text/javascript" src="./js/jquery-1.8.3.min.js"></script> <!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>--> <script type="text/javascript" src="./js/ie-amendments.js"></script> <script type="text/javascript" src="./js/jquery.bxslider.min.js"></script> <script type="text/javascript" src="./js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="./js/main.js"></script> """ out = re.sub( 'src=\"(.+)\"', 'src="{{ \'\\1\' | asset_url }}"', test, flags=re.MULTILINE ) out ``` prints out ``` '\n <script type="text/javascript" src="{{ \'./js/jquery-1.8.3.min.js\' | asset_url }}"></script>\n <!--<script src="{{ \'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript\' | asset_url }}"></script>-->\n <script type="text/javascript" src="{{ \'./js/ie-amendments.js\' | asset_url }}"></script>\n <script type="text/javascript" src="{{ \'./js/jquery.bxslider.min.js\' | asset_url }}"></script>\n <script type="text/javascript" src="{{ \'./js/jquery.colorbox-min.js\' | asset_url }}"></script>\n <script type="text/javascript" src="{{ \'./js/main.js\' | asset_url }}"></script>\n' ``` I have two problems so far: 1. Some of the backslash characters I'm using to escape the single quotes within my regexes are showing up in the output. 2. My capture group is capturing the entire original source string, but I just need what comes after the last "/" **ANSWER**: Per Martijn Pieters helpful suggestion, I checked out the ? regular expression operator, and came up with this solution, which perfectly solved my problem. Also, for the replacement expression, I encapsulated it in double-quotes as opposed to singles, and escaped the doubles, which ended up removing the unnecessary backslashes. Thanks guys! ``` re.sub( r'src=".+?([^/]+?\.js)"', "src=\"{{ '\\1' | asset_url }}\"", test, flags=re.MULTILINE ) ```
2013/02/20
[ "https://Stackoverflow.com/questions/14983015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1623223/" ]
You can just go to azure's control panel and add in a virtual directory path. Please visit this MDSN blog to see how its done. <http://blogs.msdn.com/b/kaushal/archive/2014/04/19/microsoft-azure-web-sites-deploying-wordpress-to-a-virtual-directory-within-the-azure-web-site.aspx>
**Basically this needs following steps to be done to make it working.** Solution contains i) sampleApp.API(.Net Core Web API) ii)sampleApp.UI( Angular App) Setting up Azure portal for two applications 1) Go to your web app in azure portal -> Settings->configurations 2) Select Path Mappings and here create new mapping entry for subsite .While adding this entry don't select directory checkbox to keep this as virtual application type.Click save ``` **Virtual Path:** /{folderName} **physicalPath:** /site/wwwroot/{folderName} ``` 3) Now go to VS2017 right click your API project and click publish 4) In publish settings window make paths as ``` site name : existing + "/{folderName} " DestinationUrl : existing + "/{folderName} " ``` 5) Now ng-build --prod your angular app and deploy dist/clientApp folder and publish with root paths. so now both should work as ``` angular app https://{AzureAppName}.azurewebsites.net Web API https://{AzureAppName}.azurewebsites.net/{folderName}/api/{controllerName}/{action} ``` If still user face "cant read configuration data from web.config" issue while accessing api project For this in your API project go to startup.cs and change configure function to have following line of code ``` app.Map('/{folderName}', app1 => Configure1(app1, loggerFactory); ``` and create in blank copy of configure function with name configure1 and redeploy your API project as mentioned above. ``` public void Configure1(IApplicationBuilder app, ILoggerFactory loggerFactory) { //keep it blank } ```
52,241,986
I have the following code to add a table of contents to the beginning of my ipython notebooks. When I run the cell on jupyter on my computer I get [![enter image description here](https://i.stack.imgur.com/ESBlz.png)](https://i.stack.imgur.com/ESBlz.png) But when I upload the notebook to github and choose to view the notebook, I see this for the first cell. [![enter image description here](https://i.stack.imgur.com/RSk4Z.png)](https://i.stack.imgur.com/RSk4Z.png) Is there a way to enforce that this javascript line runs like the first picture when on github?
2018/09/09
[ "https://Stackoverflow.com/questions/52241986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10171138/" ]
Attachments (and rich text) are not yet supported by the POST /chatthreads API. The only way to post messages with attachments today is with our bot APIs. We are working on write APIs to match our recently-released read APIs but they aren't ready yet. There's no need to put anything on UserVoice though. Unfortunately I don't have a date to share, but we are actively working on them.
> > APIs under the /beta version in Microsoft Graph are in preview and are subject to change. Use of these APIs in production applications is not supported. > > > The returned value of **attachment** in the document is the embodiment of the product group design, and we cannot get the value should be the product group is still developing and improvementing the API. So there are no other workground at this moment. For adding, no official docs have announced we can add attachments by Graph API. And based on my test, the try all failed too. So we need to submit a feature request in [UserVocie](https://officespdev.uservoice.com/) for directly way or research by ourselves for a none-official workaround.
22,521,912
I'm in the directory `/backbone/` which has a `main.js` file within scripts. I run `python -m SimpleHTTPServer` from the `backbone` directory and display it in the browser and the console reads the error `$ is not defined` and references a completely different `main.js` file from something I was working on days ago with a local python server. I am new to this and don't have an idea what's going on. Would love some suggestions if you have time.
2014/03/20
[ "https://Stackoverflow.com/questions/22521912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066353/" ]
i have the same problem and solved it by (( Go to Setting >> Locations> mode>> Battery savings >> then restart your device and set up again your app ))
Google map now uses this to enable the My Location layer on the Map. ``` mMap.setMyLocationEnabled(true); ``` You can view the documentation for Google Maps Android API v2 [here](https://developers.google.com/maps/documentation/android/location). They're using Location Client now to Making Your App Location-Aware, you can also refer here for more information from these [tutorial](http://developer.android.com/training/location/index.html).
7,033,192
``` #!/usr/bin/python import os,sys from os import path input = open('/home/XXXXXX/ERR001268_1', 'r').read().split('\n') at = 1 for lines in range(0, len(input)): line1 = input[lines] line4 = input[lines+3] num1 = line1.split(':')[4].split()[0] num4 = line4.split(':')[4].split()[0] print num1,num4 at += 1 ``` However I got the error: list index out of range What's the problem here? btw, besides `"at +=1"`, is there any other way to finish this cycle loop? thx
2011/08/11
[ "https://Stackoverflow.com/questions/7033192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815408/" ]
The problem is that `lines` has a maximum value of `len(input)-1` but then you let `line4` be `lines + 3`. So, when you're at your last couple of lines, `lines + 3` will be larger than the length of the list. ``` for lines in range(0, len(input)): line1 = input[lines] line4 = input[lines+3] num1 = line1.split(':')[4].split()[0] num4 = line4.split(':')[4].split()[0] print num1,num4 ```
It seems that you want to read a file and get some info from it every 3 lines. I would recommend something simpler: ``` def get_num(line): return line.split(':')[4].split()[0] nums1 = [get_num(l) for l in open(fn, "r").readlines()] nums2 = nums1[3:] for i in range(len(nums2)): print nums1[i],nums2[i] ``` The last 3 numbers of nums1 won't be written. The variable at does not do anything in your code.
7,033,192
``` #!/usr/bin/python import os,sys from os import path input = open('/home/XXXXXX/ERR001268_1', 'r').read().split('\n') at = 1 for lines in range(0, len(input)): line1 = input[lines] line4 = input[lines+3] num1 = line1.split(':')[4].split()[0] num4 = line4.split(':')[4].split()[0] print num1,num4 at += 1 ``` However I got the error: list index out of range What's the problem here? btw, besides `"at +=1"`, is there any other way to finish this cycle loop? thx
2011/08/11
[ "https://Stackoverflow.com/questions/7033192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815408/" ]
The problem is that `lines` has a maximum value of `len(input)-1` but then you let `line4` be `lines + 3`. So, when you're at your last couple of lines, `lines + 3` will be larger than the length of the list. ``` for lines in range(0, len(input)): line1 = input[lines] line4 = input[lines+3] num1 = line1.split(':')[4].split()[0] num4 = line4.split(':')[4].split()[0] print num1,num4 ```
I had a similar problem and here is the solution I came up with: ``` tuple = (1,2,3) dogs = [ ] cats = [ ] one_two = [ ] cats.apend(tuple) dogs.apend(tuple) file.apend(one_two) file.apend("/") print file print cats print dogs ``` Have an excellent day.
7,033,192
``` #!/usr/bin/python import os,sys from os import path input = open('/home/XXXXXX/ERR001268_1', 'r').read().split('\n') at = 1 for lines in range(0, len(input)): line1 = input[lines] line4 = input[lines+3] num1 = line1.split(':')[4].split()[0] num4 = line4.split(':')[4].split()[0] print num1,num4 at += 1 ``` However I got the error: list index out of range What's the problem here? btw, besides `"at +=1"`, is there any other way to finish this cycle loop? thx
2011/08/11
[ "https://Stackoverflow.com/questions/7033192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815408/" ]
Lets say `len(input) == 10`. `range(0, len(input))` iterates `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`. And when lines > 6 and you're trying to access `input[lines+3`], it clearly an IndexError, because there is no `index[10]`, `[11]` etc . And `line1.split(':')[4]` can also raise an IndexError if `line1.count(":") < 4`. I didn't understand the last `at` part, it seems not doing anything, but you can break the loop easily with `break` statement. Also, naming a variable `input` is a bad idea because it conflicts with builtin `input` function. And `range(0, len(input)) == range(len(input))`, so 0 as range's first argument is unnecessary.
It seems that you want to read a file and get some info from it every 3 lines. I would recommend something simpler: ``` def get_num(line): return line.split(':')[4].split()[0] nums1 = [get_num(l) for l in open(fn, "r").readlines()] nums2 = nums1[3:] for i in range(len(nums2)): print nums1[i],nums2[i] ``` The last 3 numbers of nums1 won't be written. The variable at does not do anything in your code.
7,033,192
``` #!/usr/bin/python import os,sys from os import path input = open('/home/XXXXXX/ERR001268_1', 'r').read().split('\n') at = 1 for lines in range(0, len(input)): line1 = input[lines] line4 = input[lines+3] num1 = line1.split(':')[4].split()[0] num4 = line4.split(':')[4].split()[0] print num1,num4 at += 1 ``` However I got the error: list index out of range What's the problem here? btw, besides `"at +=1"`, is there any other way to finish this cycle loop? thx
2011/08/11
[ "https://Stackoverflow.com/questions/7033192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815408/" ]
Lets say `len(input) == 10`. `range(0, len(input))` iterates `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`. And when lines > 6 and you're trying to access `input[lines+3`], it clearly an IndexError, because there is no `index[10]`, `[11]` etc . And `line1.split(':')[4]` can also raise an IndexError if `line1.count(":") < 4`. I didn't understand the last `at` part, it seems not doing anything, but you can break the loop easily with `break` statement. Also, naming a variable `input` is a bad idea because it conflicts with builtin `input` function. And `range(0, len(input)) == range(len(input))`, so 0 as range's first argument is unnecessary.
I had a similar problem and here is the solution I came up with: ``` tuple = (1,2,3) dogs = [ ] cats = [ ] one_two = [ ] cats.apend(tuple) dogs.apend(tuple) file.apend(one_two) file.apend("/") print file print cats print dogs ``` Have an excellent day.
34,406,393
I try to make a script allowing to loop through a list (*tmpList = openFiles(cop\_node)*). This list contains 5 other sublists of 206 components. The last 200 components of the sublists are string numbers ( a line of 200 string numbers for each component separated with a space character). I need to loop through the main list and create a new list of 5 components, each new component containing the 200\*200 values in float. My actual code is try to add a second loop to an older code working with the equivalent of one sublist. But python return an error *"Index out of range"* ``` def valuesFiles(cop_node): tmpList = openFiles(cop_node) valueList = [] valueListStr = []*len(tmpList) for j in range (len(tmpList)): tmpList = openFiles(cop_node)[j][6:] tmpList.reverse() for i in range (len(tmpList)): splitList = tmpList[i].split(' ') valueListStr[j].extend(splitList) #valueList.append(float(valueListStr[j][i])) return(valueList) ```
2015/12/21
[ "https://Stackoverflow.com/questions/34406393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5698216/" ]
`valueListStr = []*len(tmpList)` does not do what you think it does, if you want a list of lists use a *list comp* with range: ``` valueListStr = [[] for _ in range(len(tmpList))] ``` That will create a list of lists: ``` In [9]: valueListStr = [] * i In [10]: valueListStr Out[10]: [] In [11]: valueListStr = [[] for _ in range(i)] In [12]: valueListStr Out[12]: [[], [], [], []] ``` So why you get an error is because of `valueListStr[j].extend(splitList)`, you cannot index an empty list. You don't actually seem to return the list anywhere so I presume you actually want to actually return it, you can also just create lists inside the loop as needed, you can also just loop over `tmpList` and `openFiles(cop_node)`: ``` def valuesFiles(cop_node): valueListStr = [] for j in openFiles(cop_node): tmpList = j[6:] tmpList.reverse() tmp = [] for s in tmpList: tmp.extend(s.split(' ')) valueListStr.append(tmp) return valueListStr ``` Which using `itertools.chain` can become: ``` from itertools import chain def values_files(cop_node): return [list(chain(*(s.split(' ') for s in reversed(sub[6:])))) for sub in openFiles(cop_node)] ```
``` def valuesFiles(cop_node): valueListStr = [] for j in openFiles(cop_node): tmpList = j[6:] tmpList.reverse() tmp = [] for s in tmpList: tmp.extend(s.split(' ')) valueListStr.append(tmp) return valueListStr ``` After little modification I get it to work as excepted : ``` def valuesFiles(cop_node): valueList = [] for j in range (len(openFiles(cop_node))): tmpList = openFiles(cop_node)[j][6:] tmpList.reverse() tmpStr =[] for s in tmpList: tmpStr.extend(s.split(' ')) tmp = [] for t in tmpStr: tmp.append(float(t)) valueList.append(tmp) return(valueList) ``` I don't understand why but the first loop statement didn't work. At the end the I had empty lists like so : [[],[],[],[],[]] . That's why I changed the beginning. Finally I converted the strings to floats.
2,063,124
I am trying to read a \*.wav file using scipy. I do it in the following way: ``` import scipy.io x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav') ``` As a result I get the following error message: ``` Traceback (most recent call last): File "test3.py", line 1, in <module> import scipy.io File "/usr/lib/python2.5/site-packages/scipy/io/__init__.py", line 23, in <module> from numpy.testing import NumpyTest ImportError: cannot import name NumpyTest ``` Does anybody know why scipy cannot import NumpyTest and how it can be fixed?
2010/01/14
[ "https://Stackoverflow.com/questions/2063124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
Looks like you have upgraded your numpy version but haven't installed a [corresponding scipy version](http://projects.scipy.org/scipy/ticket/916).
Do you have numpy installed? The package is most likely called `numpy` or `python-numpy` if you are running Linux If your OS package manager does not have numpy package, download it from [here](http://sourceforge.net/projects/numpy/files/)
49,016,216
Is there a way to know which element has failed the `any` built-in function? I was trying to solve [Euler 5](https://projecteuler.net/problem=5) and I want to find for which numbers my product isn't evenly divisible. Using the for loop it's easy to figure it out, but is it possible with `any` also? ``` from operator import mul primes_under_20 = [2,3,5,7,11,13,17,19] product = reduce(mul, primes_under_20, 1) if any((product % i != 0 for i in range(1,21))): print "not evenly divisible" # how can I find out that 4 was the element that failed? # must I use this for loop? for i in range(1,21): if product % i != 0: print i # prints 4 break ``` I read [here](https://docs.python.org/2/library/functions.html#any) that `any` is equivalent to: ``` def any(iterable): for element in iterable: if element: return True return False ``` but is this the exact implementation, or is there a hiding `yield` there, or something like this that can help lock on the element?
2018/02/27
[ "https://Stackoverflow.com/questions/49016216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3512538/" ]
Is there any good reason to use `any`? If you want an one-liner to find out which numbers are not evenly divisible : ``` not_divisible = [i for i in range(1, 21) if product % i != 0] if len(not_divisible) > 0: print(not_divisible) ``` You can't really get all the non-divisible numbers with `any`, since it stops when it finds the first `False` in the iterable
I probably wouldn't recommend actually doing this, as it feels a bit hacky (and uglier than just scrapping the `any()` for a `for` loop). That disclaimer aside, this could technically be accomplished by exploiting an iterator and `any()`'s property of stopping once it's found a truthy value: ``` rangemax = 21 rng = iter(range(1,rangemax)) if any(product % i != 0 for i in rng): print "not evenly divisible" try: print next(rng) - 1 except StopIteration: print rangemax - 1 ``` This creates an iterator based on the `range()`, then runs `any()`, and if it evaluates `True`, you check the next item in the iterator (or the max number if you're at the end of the iterator) and subtract one.
6,712,051
I'm trying to do something that seems very simple, and falls within the range of standard python. The following function takes a collection of sets, and returns all of the items that are contained in two or more sets. To do this, while the collection of sets is not empty, it simply pops one set out of the collection, intersects it with the remaining sets, and updates a set of items that fall in one of these intersections. ``` def cross_intersections(sets): in_two = set() sets_copy = copy(sets) while sets_copy: comp = sets_copy.pop() for each in sets_copy: new = comp & each print new, # Print statements to show that these references exist print in_two in_two |= new #This is where the error occurs in IronPython return in_two ``` Above is the function I'm using. To test it, in CPython, the following works: ``` >>> a = set([1,2,3,4]) >>> b = set([3,4,5,6]) >>> c = set([2,4,6,8]) >>> cross = cross_intersections([a,b,c]) set([2, 4]) set([]) set([4, 6]) set([2, 4]) set([3, 4]) set([2, 4, 6]) >>> cross set([2, 3, 4, 6]) ``` However, when I try to use IronPython: ``` >>> b = cross_intersections([a,b,c]) set([2, 4]) set([]) set([4, 6]) set([2, 4]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:/path/to/code.py", line 10, in cross_intersections SystemError: Object reference not set to an instance of an object. ``` In the title I said this was a mysterious null pointer exception. I probably have no idea how .NET handles null pointers (I've never worked with a C-like language, and have only been using IronPython for a month or so), but if my understanding is correct, it occurs when you attempt to access some property of an object that points to `null`. In this case, the error occurs at line 10 of my function: `in_two |= new`. However, I've put `print` statements right before this line that (at least to me) indicate that neither of these objects point to `null`. Where am I going wrong?
2011/07/15
[ "https://Stackoverflow.com/questions/6712051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173292/" ]
[It's a bug](http://ironpython.codeplex.com/workitem/30386). It will be fixed in 2.7.1, but I don't think the fix is in the 2.7.1 Beta 1 release.
This is a [bug](http://ironpython.codeplex.com/workitem/30386) still present in the 2.7.1 Beta 1 release. It has been fixed in [master](https://github.com/IronLanguages/main), and the fix will be included in the next release. ``` IronPython 3.0 (3.0.0.0) on .NET 4.0.30319.235 Type "help", "copyright", "credits" or "license" for more information. >>> import copy >>> >>> def cross_intersections(sets): ... in_two = set() ... sets_copy = copy.copy(sets) ... while sets_copy: ... comp = sets_copy.pop() ... for each in sets_copy: ... new = comp & each ... print new, # Print statements to show that these references exist ... print in_two ... in_two |= new # This is where the error occurs in IronPython ... return in_two ... >>> >>> a = set([1,2,3,4]) >>> b = set([3,4,5,6]) >>> c = set([2,4,6,8]) >>> >>> cross = cross_intersections([a,b,c]) set([2, 4]) set([]) set([4, 6]) set([2, 4]) set([3, 4]) set([2, 4, 6]) ```
3,400,847
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: * main.py * callback.py * helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: * main.py * callback.py * helper.py * parameters.py and all scripts have: `import parameters` and use: `parameters.foo` or `parameters.bar`. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav
2010/08/03
[ "https://Stackoverflow.com/questions/3400847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216547/" ]
Uhm, i think it does not make sence if this happens: "realized that helper.py needed to reference variables from main", your helper functions should be independent from your "main code", otherwise i think its ugly and more like a design failure.
I'm not too sure about if that's good practice but if you use classes, I don't see why there should be a problem. Or am I missing something? If you want to be able to just run each script independently too, and that's what is keeping you from going object oriented then you could do something like the following at the end of your script. ``` if __name__ == '__main__': # Code that you want to run when the script is executed. # This block will not be executed if the script is imported. ``` Read more about classes in Python [here](http://docs.python.org/tutorial/classes.html).
3,400,847
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: * main.py * callback.py * helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: * main.py * callback.py * helper.py * parameters.py and all scripts have: `import parameters` and use: `parameters.foo` or `parameters.bar`. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav
2010/08/03
[ "https://Stackoverflow.com/questions/3400847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216547/" ]
Uhm, i think it does not make sence if this happens: "realized that helper.py needed to reference variables from main", your helper functions should be independent from your "main code", otherwise i think its ugly and more like a design failure.
You should probably read up on [Dependency Inversion](http://www.c2.com/cgi/wiki?DependencyInversionPrinciple).
3,400,847
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: * main.py * callback.py * helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: * main.py * callback.py * helper.py * parameters.py and all scripts have: `import parameters` and use: `parameters.foo` or `parameters.bar`. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav
2010/08/03
[ "https://Stackoverflow.com/questions/3400847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216547/" ]
Uhm, i think it does not make sence if this happens: "realized that helper.py needed to reference variables from main", your helper functions should be independent from your "main code", otherwise i think its ugly and more like a design failure.
Seems like what you want is to organize various dependencies between components. You will be better off expressing these dependencies in an object-oriented manner. Rather than doing it by importing modules and global states, encode these states in *objects* and pass those around. Read up on objects and classes and how to write them in Python; I'd probably start there.
3,400,847
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: * main.py * callback.py * helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: * main.py * callback.py * helper.py * parameters.py and all scripts have: `import parameters` and use: `parameters.foo` or `parameters.bar`. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav
2010/08/03
[ "https://Stackoverflow.com/questions/3400847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216547/" ]
Separate 'global' files for constants, configurations, and includes needed everywhere are fine. But when they contain actual mutable variables then they're not such a good idea. Consider having the files communicate with function return values and arguments instead. This promotes encapsulation and will keep your code from becoming a tangled mess. Clear communication between files makes them easier to understand and makes what's going on more obvious. When you're using variables and nobody knows where they came from, things can get pretty annoying. :)
I'm not too sure about if that's good practice but if you use classes, I don't see why there should be a problem. Or am I missing something? If you want to be able to just run each script independently too, and that's what is keeping you from going object oriented then you could do something like the following at the end of your script. ``` if __name__ == '__main__': # Code that you want to run when the script is executed. # This block will not be executed if the script is imported. ``` Read more about classes in Python [here](http://docs.python.org/tutorial/classes.html).
3,400,847
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: * main.py * callback.py * helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: * main.py * callback.py * helper.py * parameters.py and all scripts have: `import parameters` and use: `parameters.foo` or `parameters.bar`. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav
2010/08/03
[ "https://Stackoverflow.com/questions/3400847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216547/" ]
I try to design my code so that it looks much like a pyramid. That, I have found, leads to cleaner code.
I'm not too sure about if that's good practice but if you use classes, I don't see why there should be a problem. Or am I missing something? If you want to be able to just run each script independently too, and that's what is keeping you from going object oriented then you could do something like the following at the end of your script. ``` if __name__ == '__main__': # Code that you want to run when the script is executed. # This block will not be executed if the script is imported. ``` Read more about classes in Python [here](http://docs.python.org/tutorial/classes.html).
3,400,847
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: * main.py * callback.py * helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: * main.py * callback.py * helper.py * parameters.py and all scripts have: `import parameters` and use: `parameters.foo` or `parameters.bar`. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav
2010/08/03
[ "https://Stackoverflow.com/questions/3400847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216547/" ]
Separate 'global' files for constants, configurations, and includes needed everywhere are fine. But when they contain actual mutable variables then they're not such a good idea. Consider having the files communicate with function return values and arguments instead. This promotes encapsulation and will keep your code from becoming a tangled mess. Clear communication between files makes them easier to understand and makes what's going on more obvious. When you're using variables and nobody knows where they came from, things can get pretty annoying. :)
You should probably read up on [Dependency Inversion](http://www.c2.com/cgi/wiki?DependencyInversionPrinciple).
3,400,847
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: * main.py * callback.py * helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: * main.py * callback.py * helper.py * parameters.py and all scripts have: `import parameters` and use: `parameters.foo` or `parameters.bar`. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav
2010/08/03
[ "https://Stackoverflow.com/questions/3400847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216547/" ]
Separate 'global' files for constants, configurations, and includes needed everywhere are fine. But when they contain actual mutable variables then they're not such a good idea. Consider having the files communicate with function return values and arguments instead. This promotes encapsulation and will keep your code from becoming a tangled mess. Clear communication between files makes them easier to understand and makes what's going on more obvious. When you're using variables and nobody knows where they came from, things can get pretty annoying. :)
Seems like what you want is to organize various dependencies between components. You will be better off expressing these dependencies in an object-oriented manner. Rather than doing it by importing modules and global states, encode these states in *objects* and pass those around. Read up on objects and classes and how to write them in Python; I'd probably start there.
3,400,847
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: * main.py * callback.py * helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: * main.py * callback.py * helper.py * parameters.py and all scripts have: `import parameters` and use: `parameters.foo` or `parameters.bar`. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav
2010/08/03
[ "https://Stackoverflow.com/questions/3400847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216547/" ]
I try to design my code so that it looks much like a pyramid. That, I have found, leads to cleaner code.
You should probably read up on [Dependency Inversion](http://www.c2.com/cgi/wiki?DependencyInversionPrinciple).
3,400,847
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: * main.py * callback.py * helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: * main.py * callback.py * helper.py * parameters.py and all scripts have: `import parameters` and use: `parameters.foo` or `parameters.bar`. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav
2010/08/03
[ "https://Stackoverflow.com/questions/3400847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216547/" ]
I try to design my code so that it looks much like a pyramid. That, I have found, leads to cleaner code.
Seems like what you want is to organize various dependencies between components. You will be better off expressing these dependencies in an object-oriented manner. Rather than doing it by importing modules and global states, encode these states in *objects* and pass those around. Read up on objects and classes and how to write them in Python; I'd probably start there.
42,292,272
How to identify the link, I have inspected the elements which are as below : ``` <div class="vmKOT" role="navigation"> <a class="Ml68il" href="https://www.google.com" aria-label="Search" data-track-as="Welcome Header Search"></a> <a class="WaidDw" href="https://mail.google.com" aria-label="Mail" data-track-as="Welcome Header Mail"></a> <a class="a4KP9d" href="https://maps.google.com" aria-label="Maps" data-track-as="Welcome Header Maps"></a> <a class="QJOPee" href="https://www.youtube.com" aria-label="YouTube" data-track-as="Welcome Header YouTube"></a> </div> ``` I want to identify the class `WaidDw` or `href` and `click` it using `python`.
2017/02/17
[ "https://Stackoverflow.com/questions/42292272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7579389/" ]
You can try ``` driver.find_element_by_class_name('WaidDw').click() ``` or ``` driver.find_element_by_xpath('//a[@href="https://mail.google.com" and @aria-label="Mail"]').click() ```
In your provided HTML all attribute's values are unique, you can locate easily that element by using their attribute value. As your question points to locate this `<a class="WaidDw" href="https://mail.google.com" aria-label="Mail" data-track-as="Welcome Header Mail"></a>` element. I'm providing you multiple `cssSelectors` which can work easily to identify the same element as below :- * `a.WaidDw` * `a.WaidDw[href='https://mail.google.com']` * `a.WaidDw[aria-label='Mail']` * `a.WaidDw[data-track-as='Welcome Header Mail']` * `a.WaidDw[href='https://mail.google.com'][aria-label='Mail']` * `a.WaidDw[href='https://mail.google.com'][aria-label='Mail'][data-track-as='Welcome Header Mail']` --- **Note :-** Keep in practice (priority) to use `cssSelector` instead `xpath` if possible, because [`cssSelectors` perform far better than `xpath`](https://stackoverflow.com/questions/16788310/what-is-the-difference-between-css-selector-xpath-which-is-betteraccording-t) --- [Locating Element by CSS Selectors using python](http://selenium-python.readthedocs.io/locating-elements.html#locating-elements-by-css-selectors) :- ``` element = driver.find_element_by_css_selector('use any one of the given above css selector') ``` [Clicks the element :-](http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.click) ``` element.click() ``` --- **Reference link :-** * <https://www.w3schools.com/cssref/css_selectors.asp> * <https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors>
36,244,077
So here is a breakdown of the task: 1) I have a 197x10 2D numpy array. I scan through this and identify specific cells that are of interest (criteria that goes into choosing these cells is not important.) These cells are not restricted to one specific area of the matrix. 2) I have 3247 other 2D Numpy arrays with the same dimension. For a single one of these other arrays, I need to take the cell locations of interest specified by step 1) and take the average of all of these (sum them all together and divide by the number of cell locations of interest.) 3) I need to repeat 2) for each of the other 3246 remaining arrays. What is the best/most efficient way to "mark" the cells of interest and look at them quickly in the 3247 arrays? **--sample on smaller set--** Let's say given a 2x2 array: [1, 2] [3, 4] Perhaps the cells of interest are the ones that contain 1 and 4. Therefore, for the following arrays: [5, 6] [7, 8] and [9, 10] [11, 12] I would want to take (5+8)/2 and record that somewhere. I would also want to take (9+12)/2 and record that somewhere. **EDIT** Now if I wanted to find these cells of interest in a pythonic way (using Numpy) with the following criteria: -start at the first row and check the first element -continue to go down rows in that column marking elements that satisfy condition -Stop on the first element that does not satisfy the condition and then go to the next column. So basically now I want to just keep the row-wise (for a specific column) contiguous cells that are of interest. So for 1), if the array looks like: ``` [1 2 3] [4 5 6] [7 8 9] ``` And 1,4, 2, 8, and 3 were of interest, I'd only mark 1, 4, 2, 3, since 5 disqualifies 8 as being included.
2016/03/27
[ "https://Stackoverflow.com/questions/36244077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3973851/" ]
Pythonic way: ``` answers = [] # this generates index matrix where the condition is met. idx = np.argwhere( your condition of (1) matrix comes here) for array2d in your_3247_arrays: answer = array2d[idx].mean() answers.append() print(answers) ```
Here is an example: ``` import numpy as np A = np.random.rand(197, 10) B = np.random.rand(3247, 197, 10) loc = np.where(A > 0.9) B[:, loc[0], loc[1]].mean(axis=1) ```
47,540,186
I want to dynamically start clusters from my Jupyter notebook for specific functions. While I can start the cluster and get the engines running, I am having two issues: (1) I am unable to run the ipcluster command in the background. When I run the command through notebook, the cell is running till the the time the clusters are running, i.e. I can't run further cells in the same notebook. I can use the engines once they are fired in a different notebook. How can I run ipcluster in the background? (2) My code is always starting 8 engines, regardless of the setting in ipcluster\_config.py. Code: ``` server_num = 3 ip_new = '10.0.1.' + str(10+server_num) cluster_profile = "ssh" + str(server_num) import commands import time commands.getstatusoutput("ipython profile create --parallel --profile=" + cluster_profile) text = """ c.SSHEngineSetLauncher.engines = {'""" +ip_new + """' : 12} c.LocalControllerLauncher.controller_args = ["--ip=10.0.1.163"] c.SSHEngineSetLauncher.engine_cmd = ['/home/ubuntu/anaconda2/pkgs/ipyparallel-6.0.2-py27_0/bin/ipengine'] """ with open("/home/ubuntu/.ipython/profile_" + cluster_profile + "/ipcluster_config.py", "a") as myfile: myfile.write(text) result = commands.getstatusoutput("(ipcluster start --profile='"+ cluster_profile+"' &)") time.sleep(120) print(result[1]) ```
2017/11/28
[ "https://Stackoverflow.com/questions/47540186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4059923/" ]
When I saw your answer unanswered on StackOverflow, I almost had a heart attack because I had the same problem. But running the ``` ipcluster start --help ``` command showed this: ``` --daemonize ``` This makes it run in the background. So in your notebook you can do this: ``` no_engines = 6 !ipcluster start -n {no_engines} --daemonize ``` **Note:** This does not work on Windows according to ``` ipcluster start --help ```
I am not familiar with the details of the `commands` module (it's been deprecated since 2.6, according to <https://docs.python.org/2/library/commands.html>) but I know that with the `subprocess` module capturing output will make the make the interpreter block until the system call completes. Also, the number of engines can be set from the command line if you're using the `ipcluster` command, even without adjusting the configuration files. So, something like this worked for me: ``` from ipyparallel import Client import subprocess nengines = 3 # or whatever subprocess.Popen(["ipcluster", "start", "-n={:d}".format(nengines)]) rc = Client() # send your jobs to the engines; when done do subprocess.Popen(["ipcluster", "stop"]) ``` This doesn't, of course, address the issue of adding or removing hosts dynamically (which from your code it looks like you may be trying to do), but if you only care how many hosts are available, and not which ones, you can make a default ipcluster configuration which includes all of the possible hosts, and allocate them as needed via code similar to the above. Note also that it can take a second or two for ipcluster to spin up, so you may want to add a `time.sleep` call between your first `subprocess.Popen` call and trying to spawn the client.
40,839,114
I tried to fine-tune VGG16 on my dataset, but stuck on trouble of opening h5py file of VGG16-weights. I don't understand what does this error mean about: ``` OSError: Unable to open file (Truncated file: eof = 221184, sblock->base_addr = 0, stored_eoa = 58889256) ``` Does anyone know how to fix it? thanks ``` --------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-3-6059faca8ed7> in <module>() 9 K.set_session(sess) 10 input_tensor=Input(shape=(h,w,ch)) ---> 11 base_model=VGG16(input_tensor=input_tensor, include_top=False) 12 x_img=base_model.output 13 x_img=AveragePooling2D((7,7))(x_img) /Users/simin/anaconda/envs/IntroToTensorFlow/lib/python3.5/site-packages/keras/applications/vgg16.py in VGG16(include_top, weights, input_tensor) 144 TF_WEIGHTS_PATH_NO_TOP, 145 cache_subdir='models') --> 146 model.load_weights(weights_path) 147 if K.backend() == 'theano': 148 convert_all_kernels_in_model(model) /Users/simin/anaconda/envs/IntroToTensorFlow/lib/python3.5/site-packages/keras/engine/topology.py in load_weights(self, filepath, by_name) 2492 ''' 2493 import h5py -> 2494 f = h5py.File(filepath, mode='r') 2495 if 'layer_names' not in f.attrs and 'model_weights' in f: 2496 f = f['model_weights'] /Users/simin/anaconda/envs/IntroToTensorFlow/lib/python3.5/site-packages/h5py/_hl/files.py in __init__(self, name, mode, driver, libver, userblock_size, swmr, **kwds) 270 271 fapl = make_fapl(driver, libver, **kwds) --> 272 fid = make_fid(name, mode, userblock_size, fapl, swmr=swmr) 273 274 if swmr_support: /Users/simin/anaconda/envs/IntroToTensorFlow/lib/python3.5/site-packages/h5py/_hl/files.py in make_fid(name, mode, userblock_size, fapl, fcpl, swmr) 90 if swmr and swmr_support: 91 flags |= h5f.ACC_SWMR_READ ---> 92 fid = h5f.open(name, flags, fapl=fapl) 93 elif mode == 'r+': 94 fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl) h5py/_objects.pyx in h5py._objects.with_phil.wrapper (/Users/ilan/minonda/conda-bld/work/h5py/_objects.c:2696)() h5py/_objects.pyx in h5py._objects.with_phil.wrapper (/Users/ilan/minonda/conda-bld/work/h5py/_objects.c:2654)() h5py/h5f.pyx in h5py.h5f.open (/Users/ilan/minonda/conda-bld/work/h5py/h5f.c:1942)() OSError: Unable to open file (Truncated file: eof = 221184, sblock->base_addr = 0, stored_eoa = 58889256) ```
2016/11/28
[ "https://Stackoverflow.com/questions/40839114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7218907/" ]
There is a possibility that the download of the file has failed. Replacing a file that failed to open with the following file may resolve it. <https://github.com/fchollet/deep-learning-models/releases> My situation, That file was in the following path. C:\Users\MyName\.keras\models\vgg16\_weights\_tf\_dim\_ordering\_tf\_kernels.h5 I replaced it and solved it.
because the last time you file download is failed.but the bad file remains in the filepath. so you have to find the bad file. maybe u can use “find / -name 'vgg16\_weights\_tf\_dim\_ordering\_tf\_kernels\_notop.h5'” to find the path in unix-system. then delete it try agian!good luck!!
40,839,114
I tried to fine-tune VGG16 on my dataset, but stuck on trouble of opening h5py file of VGG16-weights. I don't understand what does this error mean about: ``` OSError: Unable to open file (Truncated file: eof = 221184, sblock->base_addr = 0, stored_eoa = 58889256) ``` Does anyone know how to fix it? thanks ``` --------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-3-6059faca8ed7> in <module>() 9 K.set_session(sess) 10 input_tensor=Input(shape=(h,w,ch)) ---> 11 base_model=VGG16(input_tensor=input_tensor, include_top=False) 12 x_img=base_model.output 13 x_img=AveragePooling2D((7,7))(x_img) /Users/simin/anaconda/envs/IntroToTensorFlow/lib/python3.5/site-packages/keras/applications/vgg16.py in VGG16(include_top, weights, input_tensor) 144 TF_WEIGHTS_PATH_NO_TOP, 145 cache_subdir='models') --> 146 model.load_weights(weights_path) 147 if K.backend() == 'theano': 148 convert_all_kernels_in_model(model) /Users/simin/anaconda/envs/IntroToTensorFlow/lib/python3.5/site-packages/keras/engine/topology.py in load_weights(self, filepath, by_name) 2492 ''' 2493 import h5py -> 2494 f = h5py.File(filepath, mode='r') 2495 if 'layer_names' not in f.attrs and 'model_weights' in f: 2496 f = f['model_weights'] /Users/simin/anaconda/envs/IntroToTensorFlow/lib/python3.5/site-packages/h5py/_hl/files.py in __init__(self, name, mode, driver, libver, userblock_size, swmr, **kwds) 270 271 fapl = make_fapl(driver, libver, **kwds) --> 272 fid = make_fid(name, mode, userblock_size, fapl, swmr=swmr) 273 274 if swmr_support: /Users/simin/anaconda/envs/IntroToTensorFlow/lib/python3.5/site-packages/h5py/_hl/files.py in make_fid(name, mode, userblock_size, fapl, fcpl, swmr) 90 if swmr and swmr_support: 91 flags |= h5f.ACC_SWMR_READ ---> 92 fid = h5f.open(name, flags, fapl=fapl) 93 elif mode == 'r+': 94 fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl) h5py/_objects.pyx in h5py._objects.with_phil.wrapper (/Users/ilan/minonda/conda-bld/work/h5py/_objects.c:2696)() h5py/_objects.pyx in h5py._objects.with_phil.wrapper (/Users/ilan/minonda/conda-bld/work/h5py/_objects.c:2654)() h5py/h5f.pyx in h5py.h5f.open (/Users/ilan/minonda/conda-bld/work/h5py/h5f.c:1942)() OSError: Unable to open file (Truncated file: eof = 221184, sblock->base_addr = 0, stored_eoa = 58889256) ```
2016/11/28
[ "https://Stackoverflow.com/questions/40839114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7218907/" ]
There is a possibility that the download of the file has failed. Replacing a file that failed to open with the following file may resolve it. <https://github.com/fchollet/deep-learning-models/releases> My situation, That file was in the following path. C:\Users\MyName\.keras\models\vgg16\_weights\_tf\_dim\_ordering\_tf\_kernels.h5 I replaced it and solved it.
It is probably because the file download failed or the file is corrupt. I found those corrupted files in `/tmp/.keras/models/vggface/`. My system is Ubuntu 20.04.
73,336,040
I'm calling `subprocess.Popen` on an `exe` file in [this script](https://github.com/PolicyEngine/openfisca-us/blob/6ae4e65f6883be598f342c445de1d52430db6b28/openfisca_us/tools/dev/taxsim/generate_taxsim_tests.py#L146), and it [throws](https://gist.github.com/MaxGhenis/b0eb890232363ed30efc1be505e1f257#file-gistfile1-txt-L249): > > OSError: [Errno 8] Exec format error: '/Users/maxghenis/PolicyEngine/openfisca-us/openfisca\_us/tools/dev/taxsim/taxsim35.exe' > > > The [answer](https://stackoverflow.com/a/30551364/1840471) to [subprocess.Popen(): OSError: [Errno 8] Exec format error in python?](https://stackoverflow.com/q/26807937/1840471) suggests adding `#!/bin/sh` to the top of the shell script. What's an analog to that for calling an exe instead of a shell script? I'm on a Mac, and the file it's running is <https://taxsim.nber.org/stata/taxsim35/taxsim35-unix.exe>.
2022/08/12
[ "https://Stackoverflow.com/questions/73336040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1840471/" ]
`subprocess` can only start programs that your operating system knows how to execute. Your `taxsim35-unix.exe` is a Linux executable. MacOS cannot run them. You'll need to either use a Linux machine to run this executable (real or virtual), or get a version compiled for Mac. <https://back.nber.org/stata//taxsim35/taxsim35-osx.exe> is likely to be the latter.
I worked with the developers of taxsim for a while. I believe that the .exe files generated by taxsim were originally msdos only and then moved to Linux. They're not intended to be run by MacOS. I don't know if they ever released the FORTRAN code that generates them so that they can be run on MacOS. Your best bet for running taxsim (since there's no close open-source substitute) is to spin up an AWS or other Linux server.
48,590,488
Beginner with python - I'm looking to create a dictionary mapping of strings, and the associated value. I have a dataframe and would like create a new column where if the string matches, it tags the column as x. ``` df = pd.DataFrame({'comp':['dell notebook', 'dell notebook S3', 'dell notepad', 'apple ipad', 'apple ipad2', 'acer chromebook', 'acer chromebookx', 'mac air', 'mac pro', 'lenovo x4'], 'price':range(10)}) ``` For Example I would like to take the above `df` and create a new column `df['company']` and set it to a mapping of strings. I was thinking of doing something like ``` product_map = {'dell':'Dell Inc.', 'apple':'Apple Inc.', 'acer': 'Acer Inc.', 'mac': 'Apple Inc.', 'lenovo': 'Dell Inc.'} ``` Then I wanted to iterate through it to check the `df.comp` column and see if each entry contained one of those strings, and to set the `df.company` column to the value in the dictionary. Not sure how to do this correctly though.
2018/02/02
[ "https://Stackoverflow.com/questions/48590488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7237997/" ]
There are many ways to do this. One way to do it would be the following: ``` def like_function(x): group = "unknown" for key in product_map: if key in x: group = product_map[key] break return group df['company'] = df.comp.apply(like_function) ```
A vectorized solution inspired by [MaxU](https://stackoverflow.com/users/5741205/maxu)'s solution to a [similar problem](https://stackoverflow.com/questions/48510405/pandas-python-datafame-update-a-column/48510563). ``` x = df.comp.str.split(expand=True) df['company'] = None df['company'] = df['company'].fillna(x[x.isin(product_map.keys())]\ .ffill(axis=1).bfill(axis=1).iloc[:, 0]) df['company'].replace(product_map, inplace=True) print(df) # comp price company #0 dell notebook 0 Dell Inc. #1 dell notebook S3 1 Dell Inc. #2 dell notepad 2 Dell Inc. #3 apple ipad 3 Apple Inc. #4 apple ipad2 4 Apple Inc. #5 acer chromebook 5 Acer Inc. #6 acer chromebookx 6 Acer Inc. #7 mac air 7 Apple Inc. #8 mac pro 8 Apple Inc. #9 lenovo x4 9 Dell Inc. ```
48,590,488
Beginner with python - I'm looking to create a dictionary mapping of strings, and the associated value. I have a dataframe and would like create a new column where if the string matches, it tags the column as x. ``` df = pd.DataFrame({'comp':['dell notebook', 'dell notebook S3', 'dell notepad', 'apple ipad', 'apple ipad2', 'acer chromebook', 'acer chromebookx', 'mac air', 'mac pro', 'lenovo x4'], 'price':range(10)}) ``` For Example I would like to take the above `df` and create a new column `df['company']` and set it to a mapping of strings. I was thinking of doing something like ``` product_map = {'dell':'Dell Inc.', 'apple':'Apple Inc.', 'acer': 'Acer Inc.', 'mac': 'Apple Inc.', 'lenovo': 'Dell Inc.'} ``` Then I wanted to iterate through it to check the `df.comp` column and see if each entry contained one of those strings, and to set the `df.company` column to the value in the dictionary. Not sure how to do this correctly though.
2018/02/02
[ "https://Stackoverflow.com/questions/48590488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7237997/" ]
There are many ways to do this. One way to do it would be the following: ``` def like_function(x): group = "unknown" for key in product_map: if key in x: group = product_map[key] break return group df['company'] = df.comp.apply(like_function) ```
Here is an interesting way, especially if you are learning about python. You can subclass `dict` and override `__getitem__` to look for partial strings. ``` class dict_partial(dict): def __getitem__(self, value): for k in self.keys(): if k in value: return self.get(k) else: return self.get(None) product_map = dict_partial({'dell':'Dell Inc.', 'apple':'Apple Inc.', 'acer': 'Acer Inc.', 'mac': 'Apple Inc.', 'lenovo': 'Dell Inc.'}) df['company'] = df['comp'].apply(lambda x: product_map[x]) comp price company # 0 dell notebook 0 Dell Inc. # 1 dell notebook S3 1 Dell Inc. # 2 dell notepad 2 Dell Inc. # 3 apple ipad 3 Apple Inc. # 4 apple ipad2 4 Apple Inc. # 5 acer chromebook 5 Acer Inc. # 6 acer chromebookx 6 Acer Inc. # 7 mac air 7 Apple Inc. # 8 mac pro 8 Apple Inc. # 9 lenovo x4 9 Dell Inc. ``` My only annoyance with this method is that subclassing `dict` does't override `dict.get` at the same time as `[]` syntax. If this were possible, we could get rid of the `lambda` and use `df['comp'].map(product_map.get)`. There doesn't seem to be an obvious solution to this.
48,590,488
Beginner with python - I'm looking to create a dictionary mapping of strings, and the associated value. I have a dataframe and would like create a new column where if the string matches, it tags the column as x. ``` df = pd.DataFrame({'comp':['dell notebook', 'dell notebook S3', 'dell notepad', 'apple ipad', 'apple ipad2', 'acer chromebook', 'acer chromebookx', 'mac air', 'mac pro', 'lenovo x4'], 'price':range(10)}) ``` For Example I would like to take the above `df` and create a new column `df['company']` and set it to a mapping of strings. I was thinking of doing something like ``` product_map = {'dell':'Dell Inc.', 'apple':'Apple Inc.', 'acer': 'Acer Inc.', 'mac': 'Apple Inc.', 'lenovo': 'Dell Inc.'} ``` Then I wanted to iterate through it to check the `df.comp` column and see if each entry contained one of those strings, and to set the `df.company` column to the value in the dictionary. Not sure how to do this correctly though.
2018/02/02
[ "https://Stackoverflow.com/questions/48590488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7237997/" ]
There are many ways to do this. One way to do it would be the following: ``` def like_function(x): group = "unknown" for key in product_map: if key in x: group = product_map[key] break return group df['company'] = df.comp.apply(like_function) ```
To my knowledge, pandas does not come with a "substring mapping" method. The [`.map()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html) method does not support substrings, and the [`.str.contains()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html) method only works with regular expressions (which does not scale well). You can achieve the result you are after by writing a simple function. You can then use [`.apply()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) with a [`lambda function`](https://www.w3schools.com/python/python_lambda.asp) to generate your desired 'company' column. The added benefits are that it keeps your code readable and you can reuse the functionality. Hope that helps. This should give you the 'company' column you need: ```py def map_substring(s, dict_map): for key in dict_map.keys(): if key in s: return dict_map[key] return np.nan df['company'] = df['product'].apply(lambda x: map_substring(x, product_map)) ```
57,404,906
I have created an executable via pyinstaller. While running the exe found the error from pandas. ``` Traceback (most recent call last): File "score_python.py", line 3, in <module> import pandas as pd, numpy as np File "d:\virtual\sc\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module exec(bytecode, module.__dict__) File "site-packages\pandas\__init__.py", line 23, in <module> File "d:\virtual\sc\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module exec(bytecode, module.__dict__) File "site-packages\pandas\compat\__init__.py", line 32, in <module> ImportError: No module named 'distutils' ``` Has anyone found the same?
2019/08/08
[ "https://Stackoverflow.com/questions/57404906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4949165/" ]
This is an issue with virtualenv from version 16.4.0 onward, as indicated in the following issue on github: <https://github.com/pyinstaller/pyinstaller/issues/4064> These workarounds were suggested: 1. In the .spec file, at the line “hiddenimports=[]”, change to "hiddenimports=['distutils']", then run pyinstaller using the spec file. Tried this, but it didn't work in my case, now distutils module could be found, but it threw an error while importing the module. 2. Downgrade virtualenv to an earlier version. I downgraded virtualenv to version 16.1.0 and and recreated the execution bundle. The new execution file worked alright in my case.
Found the solution, it's because of the virtual environment. The error occurred because of the creation of a new virtual environment while creating the project. I have deleted my existing virtual and created new virtual by setting up the python interpreter and opting the `pre-existing interpreter` option. The IDE will create a virtual named `venv` and copies all the python files from Python/bin to this folder and then import modules from here, by activating the same solved my issue.
32,007,199
Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists. So for python I was thinking of using OOP and using an iterator. ``` >>> You have a list (1, 3, 3, 3, 5) Return the list (1, 3, 5) ``` This is what I was thinking I'm not sure though. ``` Class Unique: def __init__(self, s): self.s = iter(s) def __iter__(self): return self def __next__(self): ``` I'm not sure what do for the next function of this though. I'm also curious to see how to create a function that does the same method as above but in scheme. Thanks in advance for any comments or help.
2015/08/14
[ "https://Stackoverflow.com/questions/32007199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5101470/" ]
Probably the most straight forward way to do this is using Python's `set` builtin. ``` def unique(*args): result = set() # A set guarantees the uniqueness of elements result = result.union(*args) # Include elements from all args result = list(result) # Convert the set object to a list return result ```
Not necessary but you wanted to make classes. ``` class Unique: def __init__(self): self._list = self.user_input() def user_input(self): _list = raw_input() _list = _list.split(' ') [int(i) for i in _list] return _list def get_unique(self): self._set = set(self._list) return list(self._set) obj = Unique() print obj.get_unique() ```
32,007,199
Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists. So for python I was thinking of using OOP and using an iterator. ``` >>> You have a list (1, 3, 3, 3, 5) Return the list (1, 3, 5) ``` This is what I was thinking I'm not sure though. ``` Class Unique: def __init__(self, s): self.s = iter(s) def __iter__(self): return self def __next__(self): ``` I'm not sure what do for the next function of this though. I'm also curious to see how to create a function that does the same method as above but in scheme. Thanks in advance for any comments or help.
2015/08/14
[ "https://Stackoverflow.com/questions/32007199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5101470/" ]
Probably the most straight forward way to do this is using Python's `set` builtin. ``` def unique(*args): result = set() # A set guarantees the uniqueness of elements result = result.union(*args) # Include elements from all args result = list(result) # Convert the set object to a list return result ```
In scheme, using a `union` function like that defined for instance in [How to write a scheme function that takes two lists and returns four lists](https://stackoverflow.com/questions/765484/how-to-write-a-scheme-function-that-takes-two-lists-and-returns-four-lists) , you could write something like this: ```lisp (define (unique lists) (if (null lists) '() (union (unique (cdr lists)) (car lists)))) ```
32,007,199
Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists. So for python I was thinking of using OOP and using an iterator. ``` >>> You have a list (1, 3, 3, 3, 5) Return the list (1, 3, 5) ``` This is what I was thinking I'm not sure though. ``` Class Unique: def __init__(self, s): self.s = iter(s) def __iter__(self): return self def __next__(self): ``` I'm not sure what do for the next function of this though. I'm also curious to see how to create a function that does the same method as above but in scheme. Thanks in advance for any comments or help.
2015/08/14
[ "https://Stackoverflow.com/questions/32007199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5101470/" ]
Probably the most straight forward way to do this is using Python's `set` builtin. ``` def unique(*args): result = set() # A set guarantees the uniqueness of elements result = result.union(*args) # Include elements from all args result = list(result) # Convert the set object to a list return result ```
Here is a solution in Racket: ``` (define (unique xs) (set->list (list->set xs))) ``` An explanation: ``` > (list->set '(1 2 2 4 7)) (set 1 2 4 7) ``` The function `list->set` turns a list into a set. If we want a list of the elements rather than a set, we can use `set->list` to convert the set back to a list. ``` > (set->list (list->set '(1 2 2 4 7))) '(7 4 2 1) ``` A general function can thus be defined as: ``` > (define (unique xs) (set->list (list->set xs))) ``` Let's test it: ``` > (unique '(1 1 1 2 2 4 8 2)) '(8 4 2 1) ```
32,007,199
Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists. So for python I was thinking of using OOP and using an iterator. ``` >>> You have a list (1, 3, 3, 3, 5) Return the list (1, 3, 5) ``` This is what I was thinking I'm not sure though. ``` Class Unique: def __init__(self, s): self.s = iter(s) def __iter__(self): return self def __next__(self): ``` I'm not sure what do for the next function of this though. I'm also curious to see how to create a function that does the same method as above but in scheme. Thanks in advance for any comments or help.
2015/08/14
[ "https://Stackoverflow.com/questions/32007199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5101470/" ]
In scheme, using a `union` function like that defined for instance in [How to write a scheme function that takes two lists and returns four lists](https://stackoverflow.com/questions/765484/how-to-write-a-scheme-function-that-takes-two-lists-and-returns-four-lists) , you could write something like this: ```lisp (define (unique lists) (if (null lists) '() (union (unique (cdr lists)) (car lists)))) ```
Not necessary but you wanted to make classes. ``` class Unique: def __init__(self): self._list = self.user_input() def user_input(self): _list = raw_input() _list = _list.split(' ') [int(i) for i in _list] return _list def get_unique(self): self._set = set(self._list) return list(self._set) obj = Unique() print obj.get_unique() ```
32,007,199
Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists. So for python I was thinking of using OOP and using an iterator. ``` >>> You have a list (1, 3, 3, 3, 5) Return the list (1, 3, 5) ``` This is what I was thinking I'm not sure though. ``` Class Unique: def __init__(self, s): self.s = iter(s) def __iter__(self): return self def __next__(self): ``` I'm not sure what do for the next function of this though. I'm also curious to see how to create a function that does the same method as above but in scheme. Thanks in advance for any comments or help.
2015/08/14
[ "https://Stackoverflow.com/questions/32007199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5101470/" ]
In scheme, using a `union` function like that defined for instance in [How to write a scheme function that takes two lists and returns four lists](https://stackoverflow.com/questions/765484/how-to-write-a-scheme-function-that-takes-two-lists-and-returns-four-lists) , you could write something like this: ```lisp (define (unique lists) (if (null lists) '() (union (unique (cdr lists)) (car lists)))) ```
Here is a solution in Racket: ``` (define (unique xs) (set->list (list->set xs))) ``` An explanation: ``` > (list->set '(1 2 2 4 7)) (set 1 2 4 7) ``` The function `list->set` turns a list into a set. If we want a list of the elements rather than a set, we can use `set->list` to convert the set back to a list. ``` > (set->list (list->set '(1 2 2 4 7))) '(7 4 2 1) ``` A general function can thus be defined as: ``` > (define (unique xs) (set->list (list->set xs))) ``` Let's test it: ``` > (unique '(1 1 1 2 2 4 8 2)) '(8 4 2 1) ```
9,882,358
I'm writing a quick and dirty maintenace script to delete some rows and would like to avoid having to bring my ORM classes/mappings over from the main project. I have a query that looks similar to: ``` address_table = Table('address',metadata,autoload=True) addresses = session.query(addresses_table).filter(addresses_table.c.retired == 1) ``` According to everything I've read, if I was using the ORM (not 'just' tables) and passed in something like: ``` addresses = session.query(Addresses).filter(addresses_table.c.retired == 1) ``` I could add a `.delete()` to the query, but when I try to do this using only tables I get a complaint: ``` File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/query.py", line 2146, in delete target_cls = self._mapper_zero().class_ AttributeError: 'NoneType' object has no attribute 'class_' ``` Which makes sense as its a table, not a class. I'm quite green when it comes to SQLAlchemy, how should I be going about this?
2012/03/27
[ "https://Stackoverflow.com/questions/9882358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459082/" ]
Looking through some code where I did something similar, I believe this will do what you want. ``` d = addresses_table.delete().where(addresses_table.c.retired == 1) d.execute() ``` Calling `delete()` on a table object gives you a `sql.expression` (if memory serves), that you then execute. I've assumed above that the table is bound to a connection, which means you can just call `execute()` on it. If not, you can pass the `d` to `execute(d)` on a connection. See docs [here](https://docs.sqlalchemy.org/en/latest/core/selectable.html#sqlalchemy.sql.expression.TableClause.delete).
When you call `delete()` from a query object, SQLAlchemy performs a *bulk deletion*. And you need to choose a **strategy for the removal of matched objects from the session**. See the documentation [here](https://docs.sqlalchemy.org/en/14/orm/query.html#sqlalchemy.orm.Query.delete). If you do not choose a strategy for the removal of matched objects from the session, then SQLAlchemy will try to evaluate the query’s criteria in Python straight on the objects in the session. **If evaluation of the criteria isn’t implemented, an error is raised.** This is what is happening with your deletion. If you only want to delete the records and do not care about the records in the session after the deletion, you can choose the strategy that ignores the session synchronization: ``` address_table = Table('address', metadata, autoload=True) addresses = session.query(address_table).filter(address_table.c.retired == 1) addresses.delete(synchronize_session=False) ```
32,255,039
In ubuntu ubuntu-desktop needs python3-requsts package. But this package contain out-dated requests lib (2.4, current - 2.7). I need fresh version of requests, but i cant install him. ``` $ sudo pip3 install requests --upgrade Downloading/unpacking requests from https://pypi.python.org/packages/2.7/r/requests/requests-2.7.0-py2.py3-none-any.whl#md5=564fb256f865a79f977e57b79d31659a Downloading requests-2.7.0-py2.py3-none-any.whl (470kB): 470kB downloaded Installing collected packages: requests Found existing installation: requests 2.4.3 Not uninstalling requests at /usr/lib/python3/dist-packages, owned by OS Successfully installed requests Cleaning up... ``` Is exist way to install fresh requests in ubuntu 15.04 without virtualenv?
2015/08/27
[ "https://Stackoverflow.com/questions/32255039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1064115/" ]
Finally, i solved this problem by manually installing requests. Just download archive with package and run: ``` python3 setup.py install ``` This will remove apt-get files and install fresh version.
You'd better be using virtualenv :-). The clean way to do what you are asking is creating an OS package (a ".deb") with the newer version and installing it with dpkg. The "unclean" way would be to delete the system-package using apt-get, synaptic, etc... and then use pip to install it on the system Python. That is bad even when the Python package does not conflict with a system created one. Again: virtualenvs are your friend. (Note that you can create a virtualenv that does not hide your other system-packages - with the `--system-site-packages` option)
62,273,175
I have a python dictionary as below: ``` wordCountMap = {'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10} ``` I want to sort the dictionary such that it is the decreasing order of its values, followed by lexicographically increasing order for keys with same values. ``` result = {'zzz':10, 'bbb':2. 'bbz':2. 'aaa':1} ``` Here, 'bbb' is lexicographically smaller than 'bbz'. I know that in Python 2.x we could use a compare function. How do I do this in Python 3.x ?
2020/06/09
[ "https://Stackoverflow.com/questions/62273175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2846878/" ]
You can convert it to the sorted `list` by keying on the negation of the value, and the original key: ``` resultlist = sorted({'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10}.items(), key=lambda x: (-x[1], x[0])) ``` If it must be converted back to a `dict`, just wrap that in the `dict` constructor: ``` resultdict = dict(sorted({'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10}.items(), key=lambda x: (-x[1], x[0]))) ``` You could also do the work in two steps to simplify the `key` function; first sort without a `key` (which will sort on the keys of the `dict`): ``` sortedlist = sorted({'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10}.items()) ``` then sort by the values only (since Python's sort is stable, the key order will remain the same when the values are the same). ``` import operator # At top of script sortedlist.sort(key=operator.itemgetter(1), reverse=True) ``` then convert to a `dict`: ``` result = dict(sortedlist) ``` This *probably* won't be any faster (since it has to sort twice), but it does make each step simpler, and it works even when there is no reasonable way to "negate" the value being sorted (e.g. when the values are also strings).
I got this answer from [here](https://stackoverflow.com/questions/9919342/sorting-a-dictionary-by-value-then-key). Assuming your dictionary is d, you can get it sorted with: ``` d = {'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10} newD = [v[0] for v in sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))] ``` newD's value: ``` ['zzz', 'bbb', 'bbz', 'aaa'] ```
71,883,326
I'm having trouble figuring out how to do the opposite of the answer to this question (and in R not python). [Count the amount of times value A occurs with value B](https://stackoverflow.com/questions/47834225/count-the-amount-of-times-value-a-occurs-with-value-b) Basically I have a dataframe with a lot of combinations of pairs of columns like so: ``` df <- data.frame(id1 = c("1","1","1","1","2","2","2","3","3","4","4"), id2 = c("2","2","3","4","1","3","4","1","4","2","1")) ``` I want to count, how often all the values in column A occur in the whole dataframe without the values from column B. So the results for this small example would be the output of: ``` df_result <- data.frame(id1 = c("1","1","1","2","2","2","3","3","4","4"), id2 = c("2","3","4","1","3","4","1","4","2","1"), count = c("4","5","5","3","5","4","2","3","3","3")) ``` The important criteria for this, is that the final results dataframe is collapsed by the pairs (so in my example rows 1 and 2 are duplicates, and they are collapsed and summed by the total frequency 1 is observed without 2). For tallying the count of occurances, it's important that both columns are examined. I.e. order of columns doesn't matter for calculating the frequency - if column A has 1 and B has 2, this counts the same as if column A has 2 and B has 1. I can do this very slowly by filtering for each pair, but it's not really feasible for my real data where I have many many different pairs. Any guidance is greatly appreciated.
2022/04/15
[ "https://Stackoverflow.com/questions/71883326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7257777/" ]
First `paste` the two id columns together to `id12` for later matching. Then use `sapply` to go through all rows to see the records where `id1` appears in `id12` but `id2` doesn't. `sum` that value and only output the `distinct` records. Finally, remove the `id12` column. ``` library(dplyr) df %>% mutate(id12 = paste0(id1, id2), count = sapply(1:nrow(.), function(x) sum(grepl(id1[x], id12) & !grepl(id2[x], id12)))) %>% distinct() %>% select(-id12) ``` Or in base R completely: ``` id12 <- paste0(df$id1, df$id2) df$count <- sapply(1:nrow(df), function(x) sum(grepl(df$id1[x], id12) & !grepl(df$id2[x], id12))) df <- df[!duplicated(df),] ``` ### Output ``` id1 id2 count 1 1 2 4 2 1 3 5 3 1 4 5 4 2 1 3 5 2 3 5 6 2 4 4 7 3 1 2 8 3 4 3 9 4 2 3 10 4 1 3 ```
A full `tidyverse` version: ```r library(tidyverse) df %>% mutate(id = paste(id1, id2), count = map(cur_group_rows(), ~ sum(str_detect(id, id1[.x]) & str_detect(id, id2[.x], negate = T)))) ```
71,883,326
I'm having trouble figuring out how to do the opposite of the answer to this question (and in R not python). [Count the amount of times value A occurs with value B](https://stackoverflow.com/questions/47834225/count-the-amount-of-times-value-a-occurs-with-value-b) Basically I have a dataframe with a lot of combinations of pairs of columns like so: ``` df <- data.frame(id1 = c("1","1","1","1","2","2","2","3","3","4","4"), id2 = c("2","2","3","4","1","3","4","1","4","2","1")) ``` I want to count, how often all the values in column A occur in the whole dataframe without the values from column B. So the results for this small example would be the output of: ``` df_result <- data.frame(id1 = c("1","1","1","2","2","2","3","3","4","4"), id2 = c("2","3","4","1","3","4","1","4","2","1"), count = c("4","5","5","3","5","4","2","3","3","3")) ``` The important criteria for this, is that the final results dataframe is collapsed by the pairs (so in my example rows 1 and 2 are duplicates, and they are collapsed and summed by the total frequency 1 is observed without 2). For tallying the count of occurances, it's important that both columns are examined. I.e. order of columns doesn't matter for calculating the frequency - if column A has 1 and B has 2, this counts the same as if column A has 2 and B has 1. I can do this very slowly by filtering for each pair, but it's not really feasible for my real data where I have many many different pairs. Any guidance is greatly appreciated.
2022/04/15
[ "https://Stackoverflow.com/questions/71883326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7257777/" ]
First `paste` the two id columns together to `id12` for later matching. Then use `sapply` to go through all rows to see the records where `id1` appears in `id12` but `id2` doesn't. `sum` that value and only output the `distinct` records. Finally, remove the `id12` column. ``` library(dplyr) df %>% mutate(id12 = paste0(id1, id2), count = sapply(1:nrow(.), function(x) sum(grepl(id1[x], id12) & !grepl(id2[x], id12)))) %>% distinct() %>% select(-id12) ``` Or in base R completely: ``` id12 <- paste0(df$id1, df$id2) df$count <- sapply(1:nrow(df), function(x) sum(grepl(df$id1[x], id12) & !grepl(df$id2[x], id12))) df <- df[!duplicated(df),] ``` ### Output ``` id1 id2 count 1 1 2 4 2 1 3 5 3 1 4 5 4 2 1 3 5 2 3 5 6 2 4 4 7 3 1 2 8 3 4 3 9 4 2 3 10 4 1 3 ```
A more efficient approach would be to work on a tabulation format: ``` tab = crossprod(table(rep(seq_len(nrow(df)), ncol(df)), c(df$id1, df$id2))) #tab # # 1 2 3 4 # 1 7 3 2 2 # 2 3 6 1 2 # 3 2 1 4 1 # 4 2 2 1 5 ``` So, now, we have the times each value appears with another (irrespectively of their order in the two columns). Here on, we need a way to subset the above table by each pair and subtract the value of their cooccurence from the value of each id's total appearance. Make a grid of all combinations: ``` gr = expand.grid(id1 = colnames(tab), id2 = rownames(tab), stringsAsFactors = FALSE) ``` Create 2-column matrices to subset the table: ``` id1.ij = cbind(match(gr$id1, colnames(tab)), match(gr$id1, rownames(tab))) id2.ij = cbind(match(gr$id1, colnames(tab)), match(gr$id2, rownames(tab))) ``` Subtract the respective values: ``` cbind(gr, count = tab[id1.ij] - tab[id2.ij]) # id1 id2 count #1 1 1 0 #2 2 1 3 #3 3 1 2 #4 4 1 3 #5 1 2 4 #6 2 2 0 #7 3 2 3 #8 4 2 3 #9 1 3 5 #10 2 3 5 #11 3 3 0 #12 4 3 4 #13 1 4 5 #14 2 4 4 #15 3 4 3 #16 4 4 0 ``` Of course, if we do not need the full grid of values, we can set: ``` gr = unique(df) ``` which results in: ``` # id1 id2 count #1 1 2 4 #3 1 3 5 #4 1 4 5 #5 2 1 3 #6 2 3 5 #7 2 4 4 #8 3 1 2 #9 3 4 3 #10 4 2 3 #11 4 1 3 ```
52,056,004
I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2) * <https://nicolewhite.github.io/neo4j-flask/> * <https://github.com/nicolewhite/neo4j-flask> * <https://neo4j.com/blog/building-python-web-application-using-flask-neo4j/> My setup: * Ubuntu 18.04 * Python 3.6.5 * Neo4j Server version: 3.4.6 (community) Requirements.txt (the rest of the code is from github repository by Nicole White): ``` atomicwrites==1.2.0 attrs==18.1.0 backcall==0.1.0 bcrypt==3.1.4 certifi==2018.8.24 cffi==1.11.5 click==6.7 colorama==0.3.9 decorator==4.3.0 Flask==1.0.2 ipykernel==4.8.2 ipython==6.5.0 ipython-genutils==0.2.0 itsdangerous==0.24 jedi==0.12.1 Jinja2==2.10 jupyter-client==5.2.3 jupyter-console==5.2.0 jupyter-core==4.4.0 MarkupSafe==1.0 more-itertools==4.3.0 neo4j-driver==1.6.1 neotime==1.0.0 parso==0.3.1 passlib==1.7.1 pexpect==4.6.0 pickleshare==0.7.4 pkg-resources==0.0.0 pluggy==0.7.1 prompt-toolkit==1.0.15 ptyprocess==0.6.0 py==1.6.0 py2neo==4.1.0 pycparser==2.18 Pygments==2.2.0 pytest==3.7.3 python-dateutil==2.7.3 pytz==2018.5 pyzmq==17.1.2 simplegeneric==0.8.1 six==1.11.0 tornado==5.1 traitlets==4.3.2 urllib3==1.22 wcwidth==0.1.7 Werkzeug==0.14.1 ``` Error i received when register user: > > AttributeError: 'Graph' object has no attribute 'find\_one' > > > "The User.find() method uses py2neo’s Graph.find\_one() method to find > a node in the database with label :User and the given username, > returning a py2neo.Node object. " > > > In Py2Neo V3 the function `find_one` -> <https://py2neo.org/v3/database.html?highlight=find#py2neo.database.Graph.find_one> is available. In Py2Neo V4 <https://py2neo.org/v4/matching.html> there is not find function anymore. Someone got an idea on how to solve it in V4 or is downgrading here the way to go?
2018/08/28
[ "https://Stackoverflow.com/questions/52056004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4606342/" ]
py2neo v4 has a `first` function that can be used with a `NodeMatcher`. See: <https://py2neo.org/v4/matching.html#py2neo.matching.NodeMatch.first> That said... v4 has introduced GraphObjects which (so far at least) I've found pretty neat. In the linked github example Users are created with: ``` user = Node('User', username=self.username, password=bcrypt.encrypt(password)) graph.create(user) ``` and found with ``` user = graph.find_one('User', 'username', self.username) ``` In py2neo v4 I would do this with ``` class User(GraphObject): __primarykey__ = "username" username = Property() password = Property() lukas = User() lukas.username = "lukasott" lukas.password = bcrypt.encrypt('somepassword') graph.push(lukas) ``` and ``` user = User.match(graph, "lukasott").first() ``` The `first` function, as I understand it, provides the same guarantees that `find_one`, as quoted from the v3 docs "and does not fail if more than one matching node is found."
Building on the [answer above](https://stackoverflow.com/a/52058563), here is a minimal example showing the use of `self.match().first()` instead of `find_one()`. The attributes are set with `Property()` to provide an accessor to the property of the underlying node. (Documentation here: <https://py2neo.org/v4/ogm.html#py2neo.ogm.Property>) ```py from py2neo import Graph, Node from passlib.hash import bcrypt from py2neo.ogm import GraphObject, Property graph = Graph() class User(GraphObject): __primarykey__ = 'username' username = Property() password = Property() def __init__(self, username): self.username = username def find(self): user = self.match(graph, self.username).first() return user def register(self, password): if not self.find(): user = Node('User', username=self.username, password=bcrypt.encrypt(password)) graph.create(user) return True else: return False ```
52,056,004
I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2) * <https://nicolewhite.github.io/neo4j-flask/> * <https://github.com/nicolewhite/neo4j-flask> * <https://neo4j.com/blog/building-python-web-application-using-flask-neo4j/> My setup: * Ubuntu 18.04 * Python 3.6.5 * Neo4j Server version: 3.4.6 (community) Requirements.txt (the rest of the code is from github repository by Nicole White): ``` atomicwrites==1.2.0 attrs==18.1.0 backcall==0.1.0 bcrypt==3.1.4 certifi==2018.8.24 cffi==1.11.5 click==6.7 colorama==0.3.9 decorator==4.3.0 Flask==1.0.2 ipykernel==4.8.2 ipython==6.5.0 ipython-genutils==0.2.0 itsdangerous==0.24 jedi==0.12.1 Jinja2==2.10 jupyter-client==5.2.3 jupyter-console==5.2.0 jupyter-core==4.4.0 MarkupSafe==1.0 more-itertools==4.3.0 neo4j-driver==1.6.1 neotime==1.0.0 parso==0.3.1 passlib==1.7.1 pexpect==4.6.0 pickleshare==0.7.4 pkg-resources==0.0.0 pluggy==0.7.1 prompt-toolkit==1.0.15 ptyprocess==0.6.0 py==1.6.0 py2neo==4.1.0 pycparser==2.18 Pygments==2.2.0 pytest==3.7.3 python-dateutil==2.7.3 pytz==2018.5 pyzmq==17.1.2 simplegeneric==0.8.1 six==1.11.0 tornado==5.1 traitlets==4.3.2 urllib3==1.22 wcwidth==0.1.7 Werkzeug==0.14.1 ``` Error i received when register user: > > AttributeError: 'Graph' object has no attribute 'find\_one' > > > "The User.find() method uses py2neo’s Graph.find\_one() method to find > a node in the database with label :User and the given username, > returning a py2neo.Node object. " > > > In Py2Neo V3 the function `find_one` -> <https://py2neo.org/v3/database.html?highlight=find#py2neo.database.Graph.find_one> is available. In Py2Neo V4 <https://py2neo.org/v4/matching.html> there is not find function anymore. Someone got an idea on how to solve it in V4 or is downgrading here the way to go?
2018/08/28
[ "https://Stackoverflow.com/questions/52056004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4606342/" ]
py2neo v4 has a `first` function that can be used with a `NodeMatcher`. See: <https://py2neo.org/v4/matching.html#py2neo.matching.NodeMatch.first> That said... v4 has introduced GraphObjects which (so far at least) I've found pretty neat. In the linked github example Users are created with: ``` user = Node('User', username=self.username, password=bcrypt.encrypt(password)) graph.create(user) ``` and found with ``` user = graph.find_one('User', 'username', self.username) ``` In py2neo v4 I would do this with ``` class User(GraphObject): __primarykey__ = "username" username = Property() password = Property() lukas = User() lukas.username = "lukasott" lukas.password = bcrypt.encrypt('somepassword') graph.push(lukas) ``` and ``` user = User.match(graph, "lukasott").first() ``` The `first` function, as I understand it, provides the same guarantees that `find_one`, as quoted from the v3 docs "and does not fail if more than one matching node is found."
This worked for me instead. reference the link below ```py def find(self): user = graph.nodes.match("User", self.username).first() return user ``` <https://py2neo.org/v5/_modules/py2neo/database.html>
52,056,004
I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2) * <https://nicolewhite.github.io/neo4j-flask/> * <https://github.com/nicolewhite/neo4j-flask> * <https://neo4j.com/blog/building-python-web-application-using-flask-neo4j/> My setup: * Ubuntu 18.04 * Python 3.6.5 * Neo4j Server version: 3.4.6 (community) Requirements.txt (the rest of the code is from github repository by Nicole White): ``` atomicwrites==1.2.0 attrs==18.1.0 backcall==0.1.0 bcrypt==3.1.4 certifi==2018.8.24 cffi==1.11.5 click==6.7 colorama==0.3.9 decorator==4.3.0 Flask==1.0.2 ipykernel==4.8.2 ipython==6.5.0 ipython-genutils==0.2.0 itsdangerous==0.24 jedi==0.12.1 Jinja2==2.10 jupyter-client==5.2.3 jupyter-console==5.2.0 jupyter-core==4.4.0 MarkupSafe==1.0 more-itertools==4.3.0 neo4j-driver==1.6.1 neotime==1.0.0 parso==0.3.1 passlib==1.7.1 pexpect==4.6.0 pickleshare==0.7.4 pkg-resources==0.0.0 pluggy==0.7.1 prompt-toolkit==1.0.15 ptyprocess==0.6.0 py==1.6.0 py2neo==4.1.0 pycparser==2.18 Pygments==2.2.0 pytest==3.7.3 python-dateutil==2.7.3 pytz==2018.5 pyzmq==17.1.2 simplegeneric==0.8.1 six==1.11.0 tornado==5.1 traitlets==4.3.2 urllib3==1.22 wcwidth==0.1.7 Werkzeug==0.14.1 ``` Error i received when register user: > > AttributeError: 'Graph' object has no attribute 'find\_one' > > > "The User.find() method uses py2neo’s Graph.find\_one() method to find > a node in the database with label :User and the given username, > returning a py2neo.Node object. " > > > In Py2Neo V3 the function `find_one` -> <https://py2neo.org/v3/database.html?highlight=find#py2neo.database.Graph.find_one> is available. In Py2Neo V4 <https://py2neo.org/v4/matching.html> there is not find function anymore. Someone got an idea on how to solve it in V4 or is downgrading here the way to go?
2018/08/28
[ "https://Stackoverflow.com/questions/52056004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4606342/" ]
py2neo v4 has a `first` function that can be used with a `NodeMatcher`. See: <https://py2neo.org/v4/matching.html#py2neo.matching.NodeMatch.first> That said... v4 has introduced GraphObjects which (so far at least) I've found pretty neat. In the linked github example Users are created with: ``` user = Node('User', username=self.username, password=bcrypt.encrypt(password)) graph.create(user) ``` and found with ``` user = graph.find_one('User', 'username', self.username) ``` In py2neo v4 I would do this with ``` class User(GraphObject): __primarykey__ = "username" username = Property() password = Property() lukas = User() lukas.username = "lukasott" lukas.password = bcrypt.encrypt('somepassword') graph.push(lukas) ``` and ``` user = User.match(graph, "lukasott").first() ``` The `first` function, as I understand it, provides the same guarantees that `find_one`, as quoted from the v3 docs "and does not fail if more than one matching node is found."
Another simpler way to solve this would be to replace `find_one` with the below: ``` from py2neo import Graph, NodeMatcher matcher = NodeMatcher(graph) user = matcher.match('user', name='name').first() ```
52,056,004
I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2) * <https://nicolewhite.github.io/neo4j-flask/> * <https://github.com/nicolewhite/neo4j-flask> * <https://neo4j.com/blog/building-python-web-application-using-flask-neo4j/> My setup: * Ubuntu 18.04 * Python 3.6.5 * Neo4j Server version: 3.4.6 (community) Requirements.txt (the rest of the code is from github repository by Nicole White): ``` atomicwrites==1.2.0 attrs==18.1.0 backcall==0.1.0 bcrypt==3.1.4 certifi==2018.8.24 cffi==1.11.5 click==6.7 colorama==0.3.9 decorator==4.3.0 Flask==1.0.2 ipykernel==4.8.2 ipython==6.5.0 ipython-genutils==0.2.0 itsdangerous==0.24 jedi==0.12.1 Jinja2==2.10 jupyter-client==5.2.3 jupyter-console==5.2.0 jupyter-core==4.4.0 MarkupSafe==1.0 more-itertools==4.3.0 neo4j-driver==1.6.1 neotime==1.0.0 parso==0.3.1 passlib==1.7.1 pexpect==4.6.0 pickleshare==0.7.4 pkg-resources==0.0.0 pluggy==0.7.1 prompt-toolkit==1.0.15 ptyprocess==0.6.0 py==1.6.0 py2neo==4.1.0 pycparser==2.18 Pygments==2.2.0 pytest==3.7.3 python-dateutil==2.7.3 pytz==2018.5 pyzmq==17.1.2 simplegeneric==0.8.1 six==1.11.0 tornado==5.1 traitlets==4.3.2 urllib3==1.22 wcwidth==0.1.7 Werkzeug==0.14.1 ``` Error i received when register user: > > AttributeError: 'Graph' object has no attribute 'find\_one' > > > "The User.find() method uses py2neo’s Graph.find\_one() method to find > a node in the database with label :User and the given username, > returning a py2neo.Node object. " > > > In Py2Neo V3 the function `find_one` -> <https://py2neo.org/v3/database.html?highlight=find#py2neo.database.Graph.find_one> is available. In Py2Neo V4 <https://py2neo.org/v4/matching.html> there is not find function anymore. Someone got an idea on how to solve it in V4 or is downgrading here the way to go?
2018/08/28
[ "https://Stackoverflow.com/questions/52056004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4606342/" ]
This worked for me instead. reference the link below ```py def find(self): user = graph.nodes.match("User", self.username).first() return user ``` <https://py2neo.org/v5/_modules/py2neo/database.html>
Building on the [answer above](https://stackoverflow.com/a/52058563), here is a minimal example showing the use of `self.match().first()` instead of `find_one()`. The attributes are set with `Property()` to provide an accessor to the property of the underlying node. (Documentation here: <https://py2neo.org/v4/ogm.html#py2neo.ogm.Property>) ```py from py2neo import Graph, Node from passlib.hash import bcrypt from py2neo.ogm import GraphObject, Property graph = Graph() class User(GraphObject): __primarykey__ = 'username' username = Property() password = Property() def __init__(self, username): self.username = username def find(self): user = self.match(graph, self.username).first() return user def register(self, password): if not self.find(): user = Node('User', username=self.username, password=bcrypt.encrypt(password)) graph.create(user) return True else: return False ```
52,056,004
I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2) * <https://nicolewhite.github.io/neo4j-flask/> * <https://github.com/nicolewhite/neo4j-flask> * <https://neo4j.com/blog/building-python-web-application-using-flask-neo4j/> My setup: * Ubuntu 18.04 * Python 3.6.5 * Neo4j Server version: 3.4.6 (community) Requirements.txt (the rest of the code is from github repository by Nicole White): ``` atomicwrites==1.2.0 attrs==18.1.0 backcall==0.1.0 bcrypt==3.1.4 certifi==2018.8.24 cffi==1.11.5 click==6.7 colorama==0.3.9 decorator==4.3.0 Flask==1.0.2 ipykernel==4.8.2 ipython==6.5.0 ipython-genutils==0.2.0 itsdangerous==0.24 jedi==0.12.1 Jinja2==2.10 jupyter-client==5.2.3 jupyter-console==5.2.0 jupyter-core==4.4.0 MarkupSafe==1.0 more-itertools==4.3.0 neo4j-driver==1.6.1 neotime==1.0.0 parso==0.3.1 passlib==1.7.1 pexpect==4.6.0 pickleshare==0.7.4 pkg-resources==0.0.0 pluggy==0.7.1 prompt-toolkit==1.0.15 ptyprocess==0.6.0 py==1.6.0 py2neo==4.1.0 pycparser==2.18 Pygments==2.2.0 pytest==3.7.3 python-dateutil==2.7.3 pytz==2018.5 pyzmq==17.1.2 simplegeneric==0.8.1 six==1.11.0 tornado==5.1 traitlets==4.3.2 urllib3==1.22 wcwidth==0.1.7 Werkzeug==0.14.1 ``` Error i received when register user: > > AttributeError: 'Graph' object has no attribute 'find\_one' > > > "The User.find() method uses py2neo’s Graph.find\_one() method to find > a node in the database with label :User and the given username, > returning a py2neo.Node object. " > > > In Py2Neo V3 the function `find_one` -> <https://py2neo.org/v3/database.html?highlight=find#py2neo.database.Graph.find_one> is available. In Py2Neo V4 <https://py2neo.org/v4/matching.html> there is not find function anymore. Someone got an idea on how to solve it in V4 or is downgrading here the way to go?
2018/08/28
[ "https://Stackoverflow.com/questions/52056004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4606342/" ]
Another simpler way to solve this would be to replace `find_one` with the below: ``` from py2neo import Graph, NodeMatcher matcher = NodeMatcher(graph) user = matcher.match('user', name='name').first() ```
Building on the [answer above](https://stackoverflow.com/a/52058563), here is a minimal example showing the use of `self.match().first()` instead of `find_one()`. The attributes are set with `Property()` to provide an accessor to the property of the underlying node. (Documentation here: <https://py2neo.org/v4/ogm.html#py2neo.ogm.Property>) ```py from py2neo import Graph, Node from passlib.hash import bcrypt from py2neo.ogm import GraphObject, Property graph = Graph() class User(GraphObject): __primarykey__ = 'username' username = Property() password = Property() def __init__(self, username): self.username = username def find(self): user = self.match(graph, self.username).first() return user def register(self, password): if not self.find(): user = Node('User', username=self.username, password=bcrypt.encrypt(password)) graph.create(user) return True else: return False ```
32,681,203
I use iPython mostly via notebooks but also in the terminal. I just created my default profile by running `ipython profile create`. I can't seem to figure out how to have the profile run several magic commands that I use every time. I tried to look this up online and in a book I'm reading but can't get it to work. For example, if I want `%debug` activated for every new notebook I tried adding these lines to my config file: ``` c.InteractiveShellApp.extensions = ['debug'] ``` or ``` c.TerminalPythonApp.extensions = ['debug'] ``` and I either get import errors or nothing. My (closely related) questions are the following: 1. What line to do I add to my ipython config file to activate magic commands? Some require parameters, e.g. `%reload_ext autoreload` and `%autoreload 2`. How do I also pass these parameters in the config file? 2. Can I separate which get added for terminal vs. notebooks in a single config file or must I set up separate profiles if I want different magic's activated? (e.g., `matplotlib` inline or not). Do the two lines above affect notebooks vs. terminal settings (i.e., `c.InteractiveShellApp` vs. `c.TerminalPythonApp`)? Thank you!
2015/09/20
[ "https://Stackoverflow.com/questions/32681203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238779/" ]
Execute magics as follows: ``` get_ipython().magic(u"%reload_ext autoreload") get_ipython().magic(u"%autoreload 2") ``` You can put those lines in your startup script here: ``` ~/.ipython/profile_default/startup/00-first.py ```
To start for example the %pylab magic command on startup do the following: ``` ipython profile create pylab ``` Add the following code to your .ipython\profile\_pylab\ipython\_config.py ``` c.InteractiveShellApp.exec_lines = ['%pylab'] ``` and start ipython ``` ipython --profile=pylab ```
29,658,335
I'm curious to know if it makes a difference where the '&' operator is used in code when a process has input/output redirection to run a process in the background What are the differences/are there any differences between these lines of code in terms of running the process in the background. If there are, how can I determine what the differences are going to be? ``` setsid python script.py < /dev/zero &> log.txt & setsid python script.py < /dev/zero & > log.txt & setsid python script.py < /dev/zero > log.txt & setsid python script.py & < /dev/zero > log.txt ```
2015/04/15
[ "https://Stackoverflow.com/questions/29658335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
### Control operator There are two uses of `&` here. One is as a so-called **control operator**. Every command is terminated by a control operator such as `&`, `;` or `<newline>` . The difference between them is that `;` and `<newline>` run the command in the foreground and `&` does it in the background. ``` setsid python script.py < /dev/zero & > log.txt & setsid python script.py & < /dev/zero > log.txt ``` These two lines, therefore, actually execute two commands each. The first is equivalent to the two commands: ``` setsid python script.py < /dev/zero & > log.txt & ``` And the second is equivalent to: ``` setsid python script.py & < /dev/zero > log.txt ``` If you're wondering, yes, `> log.txt` and `< /dev/zero > log.txt` are both legal commands. Lacking a command name, they simply process the redirections: each one creates an empty file called `log.txt`. ### Redirection ``` setsid python script.py < /dev/zero &> log.txt & ``` This version with `&>` is different from the one with `& >`. `&>` without a space is a special **redirection operator** in bash that redirects both stdout and stderr. ``` setsid python script.py < /dev/zero > log.txt & ``` This final version is similar to the previous one except it only redirects stdout to `log.txt`. stderr continues to go to the terminal.
It makes a difference. `&` doubles as a command separator (just like `;` is command separator). What you're really doing in something like ``` setsid python script.py & < /dev/zero > log.txt ``` is running `setsid python script.py` in the background and also running a "null" command (which comes after the `&`) in the foreground (an additional `&` at the end would run it in the background). That "null" command has its stdin redirected to */dev/zero* and its stdout redirected to *log.txt*. Also, `&>` is a special operator in Bash. `foo &>out` redirects both stdout and stderr to *out* while running `foo`. It is not the same as `foo & >out`, which runs `foo` in the background also redirects the output of a null command to *out*. (This support for "null" commands is why idioms like `>foo` on a separate line, which you sometimes see in shell scripts, work for truncating a file.)
29,658,335
I'm curious to know if it makes a difference where the '&' operator is used in code when a process has input/output redirection to run a process in the background What are the differences/are there any differences between these lines of code in terms of running the process in the background. If there are, how can I determine what the differences are going to be? ``` setsid python script.py < /dev/zero &> log.txt & setsid python script.py < /dev/zero & > log.txt & setsid python script.py < /dev/zero > log.txt & setsid python script.py & < /dev/zero > log.txt ```
2015/04/15
[ "https://Stackoverflow.com/questions/29658335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
So the `&` means different things, depending on the context. In the first case: ``` setsid python script.py < /dev/zero &> log.txt & ``` the first `&` is used together with a `>` as `&>` which means redirect both stderr and stdout. The last `&` means run in the background In the second case: ``` setsid python script.py < /dev/zero & > log.txt & ``` You have the first `&` alone, which as above, means but the process in the background, in this case it's `setsid python script.py < /dev/zero`, which gets put in the background. Then the rest of the line says, redirect no process to log.txt and background it, a bit of nonsense really. In the third case: ``` setsid python script.py < /dev/zero > log.txt & ``` You have the `&` at the end, so the whole thing gets put in the background, however your redirection only redirect stdout to log.txt, and not stderr, like in the first case. In the final case: ``` setsid python script.py & < /dev/zero > log.txt ``` You put `setsid python script.py` in the background, and redirect stdout of nothing into log.txt, and puts `/dev/zero` into stdin of nothing.
It makes a difference. `&` doubles as a command separator (just like `;` is command separator). What you're really doing in something like ``` setsid python script.py & < /dev/zero > log.txt ``` is running `setsid python script.py` in the background and also running a "null" command (which comes after the `&`) in the foreground (an additional `&` at the end would run it in the background). That "null" command has its stdin redirected to */dev/zero* and its stdout redirected to *log.txt*. Also, `&>` is a special operator in Bash. `foo &>out` redirects both stdout and stderr to *out* while running `foo`. It is not the same as `foo & >out`, which runs `foo` in the background also redirects the output of a null command to *out*. (This support for "null" commands is why idioms like `>foo` on a separate line, which you sometimes see in shell scripts, work for truncating a file.)
29,658,335
I'm curious to know if it makes a difference where the '&' operator is used in code when a process has input/output redirection to run a process in the background What are the differences/are there any differences between these lines of code in terms of running the process in the background. If there are, how can I determine what the differences are going to be? ``` setsid python script.py < /dev/zero &> log.txt & setsid python script.py < /dev/zero & > log.txt & setsid python script.py < /dev/zero > log.txt & setsid python script.py & < /dev/zero > log.txt ```
2015/04/15
[ "https://Stackoverflow.com/questions/29658335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
### Control operator There are two uses of `&` here. One is as a so-called **control operator**. Every command is terminated by a control operator such as `&`, `;` or `<newline>` . The difference between them is that `;` and `<newline>` run the command in the foreground and `&` does it in the background. ``` setsid python script.py < /dev/zero & > log.txt & setsid python script.py & < /dev/zero > log.txt ``` These two lines, therefore, actually execute two commands each. The first is equivalent to the two commands: ``` setsid python script.py < /dev/zero & > log.txt & ``` And the second is equivalent to: ``` setsid python script.py & < /dev/zero > log.txt ``` If you're wondering, yes, `> log.txt` and `< /dev/zero > log.txt` are both legal commands. Lacking a command name, they simply process the redirections: each one creates an empty file called `log.txt`. ### Redirection ``` setsid python script.py < /dev/zero &> log.txt & ``` This version with `&>` is different from the one with `& >`. `&>` without a space is a special **redirection operator** in bash that redirects both stdout and stderr. ``` setsid python script.py < /dev/zero > log.txt & ``` This final version is similar to the previous one except it only redirects stdout to `log.txt`. stderr continues to go to the terminal.
So the `&` means different things, depending on the context. In the first case: ``` setsid python script.py < /dev/zero &> log.txt & ``` the first `&` is used together with a `>` as `&>` which means redirect both stderr and stdout. The last `&` means run in the background In the second case: ``` setsid python script.py < /dev/zero & > log.txt & ``` You have the first `&` alone, which as above, means but the process in the background, in this case it's `setsid python script.py < /dev/zero`, which gets put in the background. Then the rest of the line says, redirect no process to log.txt and background it, a bit of nonsense really. In the third case: ``` setsid python script.py < /dev/zero > log.txt & ``` You have the `&` at the end, so the whole thing gets put in the background, however your redirection only redirect stdout to log.txt, and not stderr, like in the first case. In the final case: ``` setsid python script.py & < /dev/zero > log.txt ``` You put `setsid python script.py` in the background, and redirect stdout of nothing into log.txt, and puts `/dev/zero` into stdin of nothing.
9,343,498
I'm implementing the component labelling algorithm as in [this paper](http://www.iis.sinica.edu.tw/papers/fchang/1362-F.pdf) using python and opencv. It requires checking the input image pixel-by-pixel and perform the so-called contour tracing subroutine to assign label to the blobs of a binary image. I manage to have it running, but it seems very slow. Profiling the code shows that the for-loop to access the pixels seems to be the bottleneck. It takes about 200ms for a 256px\*256px image. Here's roughly what I do: ``` for i in image.height: for j in image.width: p = image[i, j] pa = image[i - 1, j] pb = image[i + 1, j] # etc... ``` where "image" is a binary opencv image. I wonder if there's a faster way of doing it so that it's usable also for video applications. I'm targeting something like 40-50ms running time for the same problem size, to get 20-25fps. 10-15fps would probably be acceptable as well (66-100ms running time). Any hints, ideas what I can do is much appreciated.
2012/02/18
[ "https://Stackoverflow.com/questions/9343498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567989/" ]
I'm not sure if I understand your question, but each key can have only one object associated with it. In your case, you're using an NSString object. If you replaced the NSString with some object that you create, say AnObjectWithAThingAndAPersonAndAPlace, you could have multiple attributes associated with each key. --- I think I understand what you want now. What you want is not an object with arrays associated to it, but an array of objects. You can do it with NSDictionary objects. ``` - (void)setupArray { NSMutableArray *objectArray = [[NSMutableArray alloc] init]; NSMutableDictionary *object1 = [[NSMutableDictionary alloc] init]; [object1 setObject:@"Apple" forKey:@"thing"]; [object1 setObject:@"Alex" forKey:@"person"]; [object1 setObject:@"Alabama" forKey:@"place"]; [object1 setObject:@"Azure" forKey:@"color"]; [objectArray addObject:object1]; NSMutableDictionary *object2 = [[NSMutableDictionary alloc] init]; [object2 setObject:@"Banana" forKey:@"thing"]; [object2 setObject:@"Bill" forKey:@"person"]; [object2 setObject:@"Boston" forKey:@"place"]; [object2 setObject:@"Blue" forKey:@"color"]; [objectArray addObject:object2]; datasource = [NSArray arrayWithArray:objectArray]; } ``` Then in your UITableViewDataSource method ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSInteger row = [indexPath row]; NSDictionary *object = [datasouce objectAtIndex:row]; ... } ``` and you can retrieve all the strings for that object. If I were to do something like this, I would probably create a plist file containing the array. Then your setupArray method could look like this: ``` - (void)setupArray { NSString *filePath = [[NSBundle mainBundle] pathForResource:@"YourFileName" ofType:@"plist"]; NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:filePath]; datasource = (NSArray*)[plistData objectForKey:@"ObjectsForTableView"]; } ``` --- I though I would add a few more comments...In case it isn't obvious, the objects you add to your dictionary don't have to be NSStrings, they can be any object, such as an NSNumber, which may be useful for you in the case of your baseball players. Also, you may wish to create a custom player object instead of using an NSDictionary. And you may want to have something like a Core Data database where the players are stored and retrieved (instead of hard coding them or getting them from a plist file). I hope my answer can get you started on the right path though.
RIght now your `datasource` object is an NSArray. You need to make it an NSMutableArray. Declare it as an NSMutableArray in your header file and then you can do this: ``` datasource = [[states allKeys] mutableCopy]; [datasource addObject:whatever]; ``` But, it sounds like the structure you are actually looking for is an NSMutableArray of NSDictionary objects. Like this: ``` NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:@"object1", @"key1", @"object2", @"key2", nil]; [datasource addObject:item] ``` ;
9,343,498
I'm implementing the component labelling algorithm as in [this paper](http://www.iis.sinica.edu.tw/papers/fchang/1362-F.pdf) using python and opencv. It requires checking the input image pixel-by-pixel and perform the so-called contour tracing subroutine to assign label to the blobs of a binary image. I manage to have it running, but it seems very slow. Profiling the code shows that the for-loop to access the pixels seems to be the bottleneck. It takes about 200ms for a 256px\*256px image. Here's roughly what I do: ``` for i in image.height: for j in image.width: p = image[i, j] pa = image[i - 1, j] pb = image[i + 1, j] # etc... ``` where "image" is a binary opencv image. I wonder if there's a faster way of doing it so that it's usable also for video applications. I'm targeting something like 40-50ms running time for the same problem size, to get 20-25fps. 10-15fps would probably be acceptable as well (66-100ms running time). Any hints, ideas what I can do is much appreciated.
2012/02/18
[ "https://Stackoverflow.com/questions/9343498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567989/" ]
I'm not sure if I understand your question, but each key can have only one object associated with it. In your case, you're using an NSString object. If you replaced the NSString with some object that you create, say AnObjectWithAThingAndAPersonAndAPlace, you could have multiple attributes associated with each key. --- I think I understand what you want now. What you want is not an object with arrays associated to it, but an array of objects. You can do it with NSDictionary objects. ``` - (void)setupArray { NSMutableArray *objectArray = [[NSMutableArray alloc] init]; NSMutableDictionary *object1 = [[NSMutableDictionary alloc] init]; [object1 setObject:@"Apple" forKey:@"thing"]; [object1 setObject:@"Alex" forKey:@"person"]; [object1 setObject:@"Alabama" forKey:@"place"]; [object1 setObject:@"Azure" forKey:@"color"]; [objectArray addObject:object1]; NSMutableDictionary *object2 = [[NSMutableDictionary alloc] init]; [object2 setObject:@"Banana" forKey:@"thing"]; [object2 setObject:@"Bill" forKey:@"person"]; [object2 setObject:@"Boston" forKey:@"place"]; [object2 setObject:@"Blue" forKey:@"color"]; [objectArray addObject:object2]; datasource = [NSArray arrayWithArray:objectArray]; } ``` Then in your UITableViewDataSource method ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSInteger row = [indexPath row]; NSDictionary *object = [datasouce objectAtIndex:row]; ... } ``` and you can retrieve all the strings for that object. If I were to do something like this, I would probably create a plist file containing the array. Then your setupArray method could look like this: ``` - (void)setupArray { NSString *filePath = [[NSBundle mainBundle] pathForResource:@"YourFileName" ofType:@"plist"]; NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:filePath]; datasource = (NSArray*)[plistData objectForKey:@"ObjectsForTableView"]; } ``` --- I though I would add a few more comments...In case it isn't obvious, the objects you add to your dictionary don't have to be NSStrings, they can be any object, such as an NSNumber, which may be useful for you in the case of your baseball players. Also, you may wish to create a custom player object instead of using an NSDictionary. And you may want to have something like a Core Data database where the players are stored and retrieved (instead of hard coding them or getting them from a plist file). I hope my answer can get you started on the right path though.
There are numerous ways (better than your given example) to do this. But I'll follow your example. You are assigning an **NSString Object** to your keys. What you can do is create a class **Thing** that contains all your attributes. and assign an instance of that class to your keys. ie. ``` [states setObject:myThingObject forKey:@"Subject 4"]; ``` Then pass the **myThingObject** to your Detail View. UPDATE: **Thing** class contains the following properties: ``` - person - place - color - thingName ``` So, ``` [states setObject:@"Thing 1" forKey:@"Subject 1"]; ``` becomes ``` [states setObject:firstObject forKey:@"Subject 1"]; [states setObject:secondObject forKey:@"Subject 2"]; ``` Note firstObject & secondObject are instances of your **Thing** class To read more about classes in Objective-c visit: > > <https://developer.apple.com/library/ios/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/_index.html> > > >
51,100,224
I've written a script in python to get different links leading to different articles from a webpage. Upon running my script I can get them flawlessly. However, the problem I'm facing is that the article links traverse multiple pages as they are of big numbers to fit within a single page. if I click on the next page button, the attached information i can see in the developer tools which in reality produce an ajax call through post request. As there are no links attached to that next page button, I can't find any way to go on to the next page and parse links from there. I've tried with a `post request` with that `formdata` but it doesn't seem to work. Where am I going wrong? [Link to the landing page containing articles](https://www.ncbi.nlm.nih.gov/pubmed/?term=%222015%22%5BDate+-+Publication%5D+%3A+%223000%22%5BDate+-+Publication%5D) This is the information I get using chrome dev tools when I click on the next page button: ``` GENERAL ======================================================= Request URL: https://www.ncbi.nlm.nih.gov/pubmed/ Request Method: POST Status Code: 200 OK Remote Address: 130.14.29.110:443 Referrer Policy: origin-when-cross-origin RESPONSE HEADERS ======================================================= Cache-Control: private Connection: Keep-Alive Content-Encoding: gzip Content-Security-Policy: upgrade-insecure-requests Content-Type: text/html; charset=UTF-8 Date: Fri, 29 Jun 2018 10:27:42 GMT Keep-Alive: timeout=1, max=9 NCBI-PHID: 396E3400B36089610000000000C6005E.m_12.03.m_8 NCBI-SID: CE8C479DB3510951_0083SID Referrer-Policy: origin-when-cross-origin Server: Apache Set-Cookie: ncbi_sid=CE8C479DB3510951_0083SID; domain=.nih.gov; path=/; expires=Sat, 29 Jun 2019 10:27:42 GMT Set-Cookie: WebEnv=1Jqk9ZOlyZSMGjHikFxNDsJ_ObuK0OxHkidgMrx8vWy2g9zqu8wopb8_D9qXGsLJQ9mdylAaDMA_T-tvHJ40Sq_FODOo33__T-tAH%40CE8C479DB3510951_0083SID; domain=.nlm.nih.gov; path=/; expires=Fri, 29 Jun 2018 18:27:42 GMT Strict-Transport-Security: max-age=31536000; includeSubDomains; preload Transfer-Encoding: chunked Vary: Accept-Encoding X-UA-Compatible: IE=Edge X-XSS-Protection: 1; mode=block REQUEST HEADERS ======================================================== Accept: text/html, */*; q=0.01 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Connection: keep-alive Content-Length: 395 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Cookie: ncbi_sid=CE8C479DB3510951_0083SID; _ga=GA1.2.1222765292.1530204312; _gid=GA1.2.739858891.1530204312; _gat=1; WebEnv=18Kcapkr72VVldfGaODQIbB2bzuU50uUwU7wrUi-x-bNDgwH73vW0M9dVXA_JOyukBSscTE8Qmd1BmLAi2nDUz7DRBZpKj1wuA_QB%40CE8C479DB3510951_0083SID; starnext=MYGwlsDWB2CmAeAXAXAbgA4CdYDcDOsAhpsABZoCu0IA9oQCZxLJA=== Host: www.ncbi.nlm.nih.gov NCBI-PHID: 396E3400B36089610000000000C6005E.m_12.03 Origin: https://www.ncbi.nlm.nih.gov Referer: https://www.ncbi.nlm.nih.gov/pubmed User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36 X-Requested-With: XMLHttpRequest FORM DATA ======================================================== p$l: AjaxServer portlets: id=relevancesortad:sort=;id=timelinead:blobid=NCID_1_120519284_130.14.22.215_9001_1530267709_1070655576_0MetA0_S_MegaStore_F_1:yr=:term=%222015%22%5BDate%20-%20Publication%5D%20%3A%20%223000%22%5BDate%20-%20Publication%5D;id=reldata:db=pubmed:querykey=1;id=searchdetails;id=recentactivity load: yes ``` This is my script so far (the get request is working flawlessly if uncommented, but for the first page): ``` import requests from urllib.parse import urljoin from bs4 import BeautifulSoup geturl = "https://www.ncbi.nlm.nih.gov/pubmed/?term=%222015%22%5BDate+-+Publication%5D+%3A+%223000%22%5BDate+-+Publication%5D" posturl = "https://www.ncbi.nlm.nih.gov/pubmed/" # res = requests.get(geturl,headers={"User-Agent":"Mozilla/5.0"}) # soup = BeautifulSoup(res.text,"lxml") # for items in soup.select("div.rslt p.title a"): # print(items.get("href")) FormData={ 'p$l': 'AjaxServer', 'portlets': 'id=relevancesortad:sort=;id=timelinead:blobid=NCID_1_120519284_130.14.22.215_9001_1530267709_1070655576_0MetA0_S_MegaStore_F_1:yr=:term=%222015%22%5BDate%20-%20Publication%5D%20%3A%20%223000%22%5BDate%20-%20Publication%5D;id=reldata:db=pubmed:querykey=1;id=searchdetails;id=recentactivity', 'load': 'yes' } req = requests.post(posturl,data=FormData,headers={"User-Agent":"Mozilla/5.0"}) soup = BeautifulSoup(req.text,"lxml") for items in soup.select("div.rslt p.title a"): print(items.get("href")) ``` Btw, the url in the browser becomes "<https://www.ncbi.nlm.nih.gov/pubmed>" when I click on the next page link. I don't wish to go for any solution related to any browser simulator. Thanks in advance.
2018/06/29
[ "https://Stackoverflow.com/questions/51100224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9189799/" ]
The content is heavily dynamic, so it would be best to use `selenium` or similar clients, but I realize that this wouldn't be practical as the number of results is so large. So, we'll have to analyse the HTTP requests submitted by the browser and simulate them with `requests`. The contents of next page are loaded by POST request to `/pubmed`, and the post data are the input fields of the `EntrezForm` form. The form submission is controlled by js (triggered when 'next page' button is clicked), and is preformed with the `.submit()` method. After some examination I discovered some interesting fields: * `EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_Pager.CurrPage` and `EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_Pager.cPage` indicate the current and next page. * `EntrezSystem2.PEntrez.DbConnector.Cmd` seems to preform a database query. If we don't submit this field the results won't change. * `EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_DisplayBar.PageSize` and `EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_DisplayBar.PrevPageSize` indicate the number of results per page. With that information I was able to get multiple pages with the script below. ``` import requests from urllib.parse import urljoin from bs4 import BeautifulSoup geturl = "https://www.ncbi.nlm.nih.gov/pubmed/?term=%222015%22%5BDate+-+Publication%5D+%3A+%223000%22%5BDate+-+Publication%5D" posturl = "https://www.ncbi.nlm.nih.gov/pubmed/" s = requests.session() s.headers["User-Agent"] = "Mozilla/5.0" soup = BeautifulSoup(s.get(geturl).text,"lxml") inputs = {i['name']: i.get('value', '') for i in soup.select('form#EntrezForm input[name]')} results = int(inputs['EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_ResultsController.ResultCount']) items_per_page = 100 pages = results // items_per_page + int(bool(results % items_per_page)) inputs['EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_DisplayBar.PageSize'] = items_per_page inputs['EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_DisplayBar.PrevPageSize'] = items_per_page inputs['EntrezSystem2.PEntrez.DbConnector.Cmd'] = 'PageChanged' links = [] for page in range(pages): inputs['EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_Pager.CurrPage'] = page + 1 inputs['EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_Pager.cPage'] = page res = s.post(posturl, inputs) soup = BeautifulSoup(res.text, "lxml") items = [i['href'] for i in soup.select("div.rslt p.title a[href]")] links += items for i in items: print(i) ``` I'm requesting 100 items per page because higher numbers seem to 'break' the server, but you should be able to adjust that number with some error checking. Finally, the links are displayed in descending order (`/29960282`, `/29960281`, ...), so I thought we could calculate the links without preforming any POST requests: ``` geturl = "https://www.ncbi.nlm.nih.gov/pubmed/?term=%222015%22%5BDate+-+Publication%5D+%3A+%223000%22%5BDate+-+Publication%5D" posturl = "https://www.ncbi.nlm.nih.gov/pubmed/" s = requests.session() s.headers["User-Agent"] = "Mozilla/5.0" soup = BeautifulSoup(s.get(geturl).text,"lxml") results = int(soup.select_one('[name$=ResultCount]')['value']) first_link = int(soup.select_one("div.rslt p.title a[href]")['href'].split('/')[-1]) last_link = first_link - results links = [posturl + str(i) for i in range(first_link, last_link, -1)] ``` But unfortunately the results are not accurate.
Not to treat this question as an XY problem, as, if solved, should pose a very interesting solution BUT I have found a solution for this *specific* issue that is much more efficient: Using the [NCBI's Entrez Programming Utilities](https://www.ncbi.nlm.nih.gov/books/NBK25497/) and a handy, [opensource, unofficial Entrez repo](https://github.com/jordibc/entrez). With the `entrez.py` script from the Entrez repo in my `PATH`, I've created this script that prints out the links just as you want them: ``` from entrez import on_search import re db = 'pubmed' term = '"2015"[Date - Publication] : "3000"[Date - Publication]' link_base = f'https://www.ncbi.nlm.nih.gov/{db}/' def links_generator(db, term): for line in on_search(db=db, term=term, tool='link'): match = re.search(r'<Id>([0-9]+)</Id>', line) if match: yield (link_base + match.group(1)) for link in links_generator(db, term): print(link) ``` Output: ``` https://www.ncbi.nlm.nih.gov/pubmed/29980165 https://www.ncbi.nlm.nih.gov/pubmed/29980164 https://www.ncbi.nlm.nih.gov/pubmed/29980163 https://www.ncbi.nlm.nih.gov/pubmed/29980162 https://www.ncbi.nlm.nih.gov/pubmed/29980161 https://www.ncbi.nlm.nih.gov/pubmed/29980160 https://www.ncbi.nlm.nih.gov/pubmed/29980159 https://www.ncbi.nlm.nih.gov/pubmed/29980158 https://www.ncbi.nlm.nih.gov/pubmed/29980157 https://www.ncbi.nlm.nih.gov/pubmed/29980156 https://www.ncbi.nlm.nih.gov/pubmed/29980155 https://www.ncbi.nlm.nih.gov/pubmed/29980154 https://www.ncbi.nlm.nih.gov/pubmed/29980153 https://www.ncbi.nlm.nih.gov/pubmed/29980152 https://www.ncbi.nlm.nih.gov/pubmed/29980151 https://www.ncbi.nlm.nih.gov/pubmed/29980150 https://www.ncbi.nlm.nih.gov/pubmed/29980149 https://www.ncbi.nlm.nih.gov/pubmed/29980148 ... ``` Which, if compared to the [frontend page](https://www.ncbi.nlm.nih.gov/pubmed/?term=%222015%22%5BDate+-+Publication%5D+%3A+%223000%22%5BDate+-+Publication%5D), are in the same order. :-)
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned that there are too many routes in `test.py` and would like to make it such that I can run `python test.py`, which will also pick up the routes on `test.py` as if it were part of the same file. What changes to I have to make in `test.py` and/or include in `test2.py` to get this to work?
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
I would like to recommend [flask-empty](https://github.com/italomaia/flask-empty/) at GitHub. It provides an easy way to understand [Blueprints](http://flask.pocoo.org/docs/blueprints/), multiple views and [extensions](http://flask.pocoo.org/docs/extensiondev/).
Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files. I created a Gist with the code for doing this: <https://gist.github.com/Jaza/61f879f577bc9d06029e> As far as I'm aware, this is the only feasible way to divide up a Blueprint at the moment. It's not possible to create "sub-blueprints" in Flask, although there's an issue open with a lot of discussion about this: <https://github.com/mitsuhiko/flask/issues/593> Also, even if it were possible (and it's probably do-able using some of the snippets from that issue thread), sub-blueprints may be too restrictive for your use case anyway - e.g. if you don't want all the routes in a sub-module to have the same URL sub-prefix.
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned that there are too many routes in `test.py` and would like to make it such that I can run `python test.py`, which will also pick up the routes on `test.py` as if it were part of the same file. What changes to I have to make in `test.py` and/or include in `test2.py` to get this to work?
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
You can use the usual Python package structure to divide your App into multiple modules, [see the Flask docs.](http://flask.pocoo.org/docs/patterns/packages/) However, > > Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. > > > You can create a sub-component of your app as a Blueprint in a separate file: ``` simple_page = Blueprint('simple_page', __name__, template_folder='templates') @simple_page.route('/<page>') def show(page): # stuff ``` And then use it in the main part: ``` from yourapplication.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page) ``` Blueprints can also bundle specific resources: templates or static files. Please refer to the [Flask docs](http://flask.pocoo.org/docs/blueprints/#blueprints) for all the details.
I would like to recommend [flask-empty](https://github.com/italomaia/flask-empty/) at GitHub. It provides an easy way to understand [Blueprints](http://flask.pocoo.org/docs/blueprints/), multiple views and [extensions](http://flask.pocoo.org/docs/extensiondev/).
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned that there are too many routes in `test.py` and would like to make it such that I can run `python test.py`, which will also pick up the routes on `test.py` as if it were part of the same file. What changes to I have to make in `test.py` and/or include in `test2.py` to get this to work?
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
You can use the usual Python package structure to divide your App into multiple modules, [see the Flask docs.](http://flask.pocoo.org/docs/patterns/packages/) However, > > Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. > > > You can create a sub-component of your app as a Blueprint in a separate file: ``` simple_page = Blueprint('simple_page', __name__, template_folder='templates') @simple_page.route('/<page>') def show(page): # stuff ``` And then use it in the main part: ``` from yourapplication.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page) ``` Blueprints can also bundle specific resources: templates or static files. Please refer to the [Flask docs](http://flask.pocoo.org/docs/blueprints/#blueprints) for all the details.
If you need split blueprint to separate files you can use snippet: ``` # app.py from blueprint_module import blueprint app = Flask(__name__) app.register_blueprint(blueprint) ``` ``` # blueprint_module\__init__.py from flask import Blueprint blueprint = Blueprint('my_blueprint', __name__) from . import page ``` ``` # blueprint_module\page.py from . import blueprint @blueprint.route("/url", methods=['GET']) def hello(): return 'hello world' ```
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned that there are too many routes in `test.py` and would like to make it such that I can run `python test.py`, which will also pick up the routes on `test.py` as if it were part of the same file. What changes to I have to make in `test.py` and/or include in `test2.py` to get this to work?
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
You can use the usual Python package structure to divide your App into multiple modules, [see the Flask docs.](http://flask.pocoo.org/docs/patterns/packages/) However, > > Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. > > > You can create a sub-component of your app as a Blueprint in a separate file: ``` simple_page = Blueprint('simple_page', __name__, template_folder='templates') @simple_page.route('/<page>') def show(page): # stuff ``` And then use it in the main part: ``` from yourapplication.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page) ``` Blueprints can also bundle specific resources: templates or static files. Please refer to the [Flask docs](http://flask.pocoo.org/docs/blueprints/#blueprints) for all the details.
This task can be accomplished without blueprints and tricky imports using [Centralized URL Map](https://flask.palletsprojects.com/en/1.1.x/patterns/lazyloading/#converting-to-centralized-url-map) **app.py** ```py import views from flask import Flask app = Flask(__name__) app.add_url_rule('/', view_func=views.index) app.add_url_rule('/other', view_func=views.other) if __name__ == '__main__': app.run(debug=True, use_reloader=True) ``` **views.py** ```py from flask import render_template def index(): return render_template('index.html') def other(): return render_template('other.html') ```
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned that there are too many routes in `test.py` and would like to make it such that I can run `python test.py`, which will also pick up the routes on `test.py` as if it were part of the same file. What changes to I have to make in `test.py` and/or include in `test2.py` to get this to work?
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
This task can be accomplished without blueprints and tricky imports using [Centralized URL Map](https://flask.palletsprojects.com/en/1.1.x/patterns/lazyloading/#converting-to-centralized-url-map) **app.py** ```py import views from flask import Flask app = Flask(__name__) app.add_url_rule('/', view_func=views.index) app.add_url_rule('/other', view_func=views.other) if __name__ == '__main__': app.run(debug=True, use_reloader=True) ``` **views.py** ```py from flask import render_template def index(): return render_template('index.html') def other(): return render_template('other.html') ```
If you need split blueprint to separate files you can use snippet: ``` # app.py from blueprint_module import blueprint app = Flask(__name__) app.register_blueprint(blueprint) ``` ``` # blueprint_module\__init__.py from flask import Blueprint blueprint = Blueprint('my_blueprint', __name__) from . import page ``` ``` # blueprint_module\page.py from . import blueprint @blueprint.route("/url", methods=['GET']) def hello(): return 'hello world' ```
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned that there are too many routes in `test.py` and would like to make it such that I can run `python test.py`, which will also pick up the routes on `test.py` as if it were part of the same file. What changes to I have to make in `test.py` and/or include in `test2.py` to get this to work?
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
You can use simple trick which is import flask app variable from main inside another file, like: **test\_routes.py** ``` from __main__ import app @app.route('/test', methods=['GET']) def test(): return 'it works!' ``` and in your main files, where you declared flask app, import test-routes, like: **app.py** ``` from flask import Flask, request, abort app = Flask(__name__) # import declared routes import test_routes ``` It works from my side.
Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files. I created a Gist with the code for doing this: <https://gist.github.com/Jaza/61f879f577bc9d06029e> As far as I'm aware, this is the only feasible way to divide up a Blueprint at the moment. It's not possible to create "sub-blueprints" in Flask, although there's an issue open with a lot of discussion about this: <https://github.com/mitsuhiko/flask/issues/593> Also, even if it were possible (and it's probably do-able using some of the snippets from that issue thread), sub-blueprints may be too restrictive for your use case anyway - e.g. if you don't want all the routes in a sub-module to have the same URL sub-prefix.
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned that there are too many routes in `test.py` and would like to make it such that I can run `python test.py`, which will also pick up the routes on `test.py` as if it were part of the same file. What changes to I have to make in `test.py` and/or include in `test2.py` to get this to work?
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
You can use the usual Python package structure to divide your App into multiple modules, [see the Flask docs.](http://flask.pocoo.org/docs/patterns/packages/) However, > > Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. > > > You can create a sub-component of your app as a Blueprint in a separate file: ``` simple_page = Blueprint('simple_page', __name__, template_folder='templates') @simple_page.route('/<page>') def show(page): # stuff ``` And then use it in the main part: ``` from yourapplication.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page) ``` Blueprints can also bundle specific resources: templates or static files. Please refer to the [Flask docs](http://flask.pocoo.org/docs/blueprints/#blueprints) for all the details.
You can use simple trick which is import flask app variable from main inside another file, like: **test\_routes.py** ``` from __main__ import app @app.route('/test', methods=['GET']) def test(): return 'it works!' ``` and in your main files, where you declared flask app, import test-routes, like: **app.py** ``` from flask import Flask, request, abort app = Flask(__name__) # import declared routes import test_routes ``` It works from my side.
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned that there are too many routes in `test.py` and would like to make it such that I can run `python test.py`, which will also pick up the routes on `test.py` as if it were part of the same file. What changes to I have to make in `test.py` and/or include in `test2.py` to get this to work?
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
You can use simple trick which is import flask app variable from main inside another file, like: **test\_routes.py** ``` from __main__ import app @app.route('/test', methods=['GET']) def test(): return 'it works!' ``` and in your main files, where you declared flask app, import test-routes, like: **app.py** ``` from flask import Flask, request, abort app = Flask(__name__) # import declared routes import test_routes ``` It works from my side.
If you need split blueprint to separate files you can use snippet: ``` # app.py from blueprint_module import blueprint app = Flask(__name__) app.register_blueprint(blueprint) ``` ``` # blueprint_module\__init__.py from flask import Blueprint blueprint = Blueprint('my_blueprint', __name__) from . import page ``` ``` # blueprint_module\page.py from . import blueprint @blueprint.route("/url", methods=['GET']) def hello(): return 'hello world' ```
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned that there are too many routes in `test.py` and would like to make it such that I can run `python test.py`, which will also pick up the routes on `test.py` as if it were part of the same file. What changes to I have to make in `test.py` and/or include in `test2.py` to get this to work?
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
You can use simple trick which is import flask app variable from main inside another file, like: **test\_routes.py** ``` from __main__ import app @app.route('/test', methods=['GET']) def test(): return 'it works!' ``` and in your main files, where you declared flask app, import test-routes, like: **app.py** ``` from flask import Flask, request, abort app = Flask(__name__) # import declared routes import test_routes ``` It works from my side.
I would like to recommend [flask-empty](https://github.com/italomaia/flask-empty/) at GitHub. It provides an easy way to understand [Blueprints](http://flask.pocoo.org/docs/blueprints/), multiple views and [extensions](http://flask.pocoo.org/docs/extensiondev/).
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned that there are too many routes in `test.py` and would like to make it such that I can run `python test.py`, which will also pick up the routes on `test.py` as if it were part of the same file. What changes to I have to make in `test.py` and/or include in `test2.py` to get this to work?
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
You can use simple trick which is import flask app variable from main inside another file, like: **test\_routes.py** ``` from __main__ import app @app.route('/test', methods=['GET']) def test(): return 'it works!' ``` and in your main files, where you declared flask app, import test-routes, like: **app.py** ``` from flask import Flask, request, abort app = Flask(__name__) # import declared routes import test_routes ``` It works from my side.
This task can be accomplished without blueprints and tricky imports using [Centralized URL Map](https://flask.palletsprojects.com/en/1.1.x/patterns/lazyloading/#converting-to-centralized-url-map) **app.py** ```py import views from flask import Flask app = Flask(__name__) app.add_url_rule('/', view_func=views.index) app.add_url_rule('/other', view_func=views.other) if __name__ == '__main__': app.run(debug=True, use_reloader=True) ``` **views.py** ```py from flask import render_template def index(): return render_template('index.html') def other(): return render_template('other.html') ```
45,776,460
What I'm trying to do is search StackOverflow for answers. I know it's probably been done before, but I'd like to do it again. With a GUI. Anyway that is a little bit down the road as right now i'm just trying to get to the page with the most votes for a question. I noticed while trying to see how to get into a nested div to get the link for the first answer that my search was off and taking me to the wrong place. I am using BeautifulSoup and Requests and python3 to do this. ``` #!/usr/bin/env python3 import requests from bs4 import BeautifulSoup payload = {'q': 'open GL cube'} page = requests.get("https://stackoverflow.com/search",params=payload) print(" URL IS ", page.url) data = page.content soup = BeautifulSoup(data, 'lxml') top = soup.find('a', {'title':'Highest voted search results'})['href'] print(top) page2 = requests.get("https://stackoverflow.com",params=top) print(page2.url) data2 = page2.content topSoup = BeautifulSoup(data2, 'lxml') for div in topSoup.find_all('div', {'class':'result-link'}): print(div.text) ``` i get the link and it outputs /search?tab=votes&q=open%GL%20cube but when I pass it in with the params it does <https://stackoverflow.com/?/search?tab=votes&q=open%GL%20cube> I would like to get rid of the /?/
2017/08/19
[ "https://Stackoverflow.com/questions/45776460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/977034/" ]
Don't pass it as parameters, just add it to the URL: ``` page2 = requests.get("https://stackoverflow.com" + top) ``` Once you pass `requests` parameters it adds a `?` to the link before concatenating the new parameters to the link. [Requests - Passing Parameters In URLs](http://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls) Also, as stated, you should really use the API.
Why not use the [API](https://api.stackexchange.com/docs)? There are plenty of search options (<https://api.stackexchange.com/docs/advanced-search>), and you get the response in JSON, no need for ugly HTML parsing.
55,318,093
i am learning and trying to make a snake game in Python3 i am importing turtle i am using: Linux mint 19, PyCharm, python37, python3-tk ``` Traceback (most recent call last): File "/home/buszter/PycharmProjects/untitled1/snake.py", line 2, in <module> import turtle ModuleNotFoundError: No module named 'turtle' ``` everywhere i am reading turtle should be preinstalled, but i still dont have it :( i tried `pip install turtle` and says ``` pip install turtle Collecting turtle Using cached https://files.pythonhosted.org/packages/ff/f0/21a42e9e424d24bdd0e509d5ed3c7dfb8f47d962d9c044dba903b0b4a26f/turtle-0.0.2.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-kvf9on0y/turtle/setup.py", line 40 except ValueError, ve: ^ SyntaxError: invalid syntax ------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-kvf9on0y/turtle/ ``` EDIT screenshot of settings of the project in pycharm [![screenshot of settings of the project in pycharm](https://i.stack.imgur.com/d52jy.png)](https://i.stack.imgur.com/d52jy.png)
2019/03/23
[ "https://Stackoverflow.com/questions/55318093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10909285/" ]
I know that it's kinda old topic, but I had the same problem right now on my Fedora 31. Reinstalling packages didn't work. What worked was installing IDLE programming tool (that's just Python IDE for kids), which installs also tkinter module. I think that installing just `python3-tkinter` (that's how this package is named in Fedora repo) package would work as well, because `turtle` is inside Tk module.
Most probably the python your `Pycharm` is using is not `Python3.7`. Try opening a Python prompt and running import turtle, because it should be packaged into `python` already. (<https://docs.python.org/3/library/turtle.html>)
55,318,093
i am learning and trying to make a snake game in Python3 i am importing turtle i am using: Linux mint 19, PyCharm, python37, python3-tk ``` Traceback (most recent call last): File "/home/buszter/PycharmProjects/untitled1/snake.py", line 2, in <module> import turtle ModuleNotFoundError: No module named 'turtle' ``` everywhere i am reading turtle should be preinstalled, but i still dont have it :( i tried `pip install turtle` and says ``` pip install turtle Collecting turtle Using cached https://files.pythonhosted.org/packages/ff/f0/21a42e9e424d24bdd0e509d5ed3c7dfb8f47d962d9c044dba903b0b4a26f/turtle-0.0.2.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-kvf9on0y/turtle/setup.py", line 40 except ValueError, ve: ^ SyntaxError: invalid syntax ------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-kvf9on0y/turtle/ ``` EDIT screenshot of settings of the project in pycharm [![screenshot of settings of the project in pycharm](https://i.stack.imgur.com/d52jy.png)](https://i.stack.imgur.com/d52jy.png)
2019/03/23
[ "https://Stackoverflow.com/questions/55318093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10909285/" ]
I know that it's kinda old topic, but I had the same problem right now on my Fedora 31. Reinstalling packages didn't work. What worked was installing IDLE programming tool (that's just Python IDE for kids), which installs also tkinter module. I think that installing just `python3-tkinter` (that's how this package is named in Fedora repo) package would work as well, because `turtle` is inside Tk module.
You can't install turtle library via pip, it must be in the standart library. `pip install turtle` installs [this 3rd party](https://pypi.org/project/turtle/) library. You can look at download file ([this](https://pypi.org/project/turtle/#files) tar.gz file) link of above library and link in the output of pip. They are same. For the solution, I think you can just copy [this](https://github.com/python/cpython/blob/master/Lib/turtle.py) and write in a file.
55,318,093
i am learning and trying to make a snake game in Python3 i am importing turtle i am using: Linux mint 19, PyCharm, python37, python3-tk ``` Traceback (most recent call last): File "/home/buszter/PycharmProjects/untitled1/snake.py", line 2, in <module> import turtle ModuleNotFoundError: No module named 'turtle' ``` everywhere i am reading turtle should be preinstalled, but i still dont have it :( i tried `pip install turtle` and says ``` pip install turtle Collecting turtle Using cached https://files.pythonhosted.org/packages/ff/f0/21a42e9e424d24bdd0e509d5ed3c7dfb8f47d962d9c044dba903b0b4a26f/turtle-0.0.2.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-kvf9on0y/turtle/setup.py", line 40 except ValueError, ve: ^ SyntaxError: invalid syntax ------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-kvf9on0y/turtle/ ``` EDIT screenshot of settings of the project in pycharm [![screenshot of settings of the project in pycharm](https://i.stack.imgur.com/d52jy.png)](https://i.stack.imgur.com/d52jy.png)
2019/03/23
[ "https://Stackoverflow.com/questions/55318093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10909285/" ]
I know that it's kinda old topic, but I had the same problem right now on my Fedora 31. Reinstalling packages didn't work. What worked was installing IDLE programming tool (that's just Python IDE for kids), which installs also tkinter module. I think that installing just `python3-tkinter` (that's how this package is named in Fedora repo) package would work as well, because `turtle` is inside Tk module.
The screenshot of your settings shows no PythonTurtle package. Simply click on + and find the package named "PythonTurtle" click install package.
56,305,416
Hi I am following this tutorial <https://stackabuse.com/association-rule-mining-via-apriori-algorithm-in-python/> and am getting the following error when I run the below code. I am honestly not sure what to try as I am following the tutorial verbatim. I don't see what the issue is. ``` #import numpy as np #import matplotlib as plt import pandas as pd from apyori import apriori store_data = pd.read_csv('C:\\Users\\eyaze\\Downloads\\store_data.csv', header=None) print(store_data.head()) records = [] for i in range(0, 7501): records.append([str(store_data.values[i,j]) for j in range(0, 20)]) association_rules = apriori(records, min_support=0.0045, min_confidence=0.2, min_lift=3, min_length=2) association_results = list(association_rules) print(len(association_rules)) ``` I am expecting to get 48 as per the tutorial but I instead get the error: ``` TypeError: object of type 'generator' has no len() ``` What is going on?
2019/05/25
[ "https://Stackoverflow.com/questions/56305416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11554788/" ]
Your code is very similar to this one I found on medium: <https://medium.com/@deepak.r.poojari/apriori-algorithm-in-python-recommendation-engine-5ba89bd1a6da> I guess you wanted to do `print(len(association_results))` instead of association\_rules, as is done in the linked article?
it's a generator, and it only point's to the first block of your code list, if u want to find length , then iterate over it first and then use length ie `print(len(list(association_rules)))`
14,669,990
How can I write this complete code in python in just one line or may be I must say something which uses least space or least no of characters? ``` t=int(input()) while t>0: n=int(input()) s=sum(1/(2.0*i+1) for i in range(n)) print "%.15f"%s t-=1 ```
2013/02/03
[ "https://Stackoverflow.com/questions/14669990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1440140/" ]
You're welcome ``` for t in range(int(input()), 0, -1): print '%.15f' % sum(1/(2.0*i+1) for i in range(int(input()))) ``` **EDIT** (explanation): Firstly, instead of a while loop you can use a [for loop](http://docs.python.org/2/reference/compound_stmts.html#for) in a [range](http://docs.python.org/2/library/functions.html#range). The last argument in the for loop is a -1 to subtract 1 every time instead of the default of plus 1 every time. If there is only one statement in an if statement, or loop, you can keep the one statement in the same line without going to the next line. Instead of creating the variable of n, you can simply plug it in since it's only being used once. Same goes for s.
`exec"print sum((-1.)**i/(i-~i)for i in range(input()));"*input()` I know I am too late for answering this question.but above code gives same result. It will get even more shorter. I am also finding ways to shorten it. #CodeGolf #Python2.4
14,669,990
How can I write this complete code in python in just one line or may be I must say something which uses least space or least no of characters? ``` t=int(input()) while t>0: n=int(input()) s=sum(1/(2.0*i+1) for i in range(n)) print "%.15f"%s t-=1 ```
2013/02/03
[ "https://Stackoverflow.com/questions/14669990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1440140/" ]
``` for _ in range(input()):print"%.15f"%sum(1/(2.0*i+1)for i in range(input())) ```
`exec"print sum((-1.)**i/(i-~i)for i in range(input()));"*input()` I know I am too late for answering this question.but above code gives same result. It will get even more shorter. I am also finding ways to shorten it. #CodeGolf #Python2.4
58,599,829
I have a python script called "server.py" and inside it I have a function `def calcFunction(arg1): ... return output` How can I call the function calcFunction with arguments and use the return value in autohotkey? This is what I want to do in autohotkey: ``` ToSend = someString ; a string output = Run server.py, calcFunction(ToSend) ; get the returned value from the function with ToSend as argument Send, output ; use the returned value in autohotkey ``` I have looked online but nothing seems to fully answer my question. Can it even be done?
2019/10/28
[ "https://Stackoverflow.com/questions/58599829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11340003/" ]
You can define a custom GHCi command using `:def` in this way: ``` > :def foo (\_ -> return "print 100\nprint 200\n:t length") > :foo 100 200 length :: Foldable t => t a -> Int ``` In the returned string, `:`-commands can be included as well, like `:t` above.
One way I've found is creating a separate file: ``` myfunction 0 100 myfunction 0 200 myfunction 0 300 :r ``` and then using: `:script path/to/file`
58,599,829
I have a python script called "server.py" and inside it I have a function `def calcFunction(arg1): ... return output` How can I call the function calcFunction with arguments and use the return value in autohotkey? This is what I want to do in autohotkey: ``` ToSend = someString ; a string output = Run server.py, calcFunction(ToSend) ; get the returned value from the function with ToSend as argument Send, output ; use the returned value in autohotkey ``` I have looked online but nothing seems to fully answer my question. Can it even be done?
2019/10/28
[ "https://Stackoverflow.com/questions/58599829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11340003/" ]
You can define a custom GHCi command using `:def` in this way: ``` > :def foo (\_ -> return "print 100\nprint 200\n:t length") > :foo 100 200 length :: Foldable t => t a -> Int ``` In the returned string, `:`-commands can be included as well, like `:t` above.
One way of doing it is to create a testing suite in your Cabal file in which you place your function calls as tests, then use `stack test --file-watch`. That recompiles and reruns the tests every time you save a file.
58,736,009
I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here: <https://github.com/puckel/docker-airflow> I am not able to get airflow to send me emails on failure or retry. I've tried the following: 1. Editing the config file with the smtp host name ``` [smtp] # If you want airflow to send emails on retries, failure, and you want to use # the airflow.utils.email.send_email_smtp function, you have to configure an # smtp server here smtp_host = smtp@mycompany.com smtp_starttls = True smtp_ssl = False # Uncomment and set the user/pass settings if you want to use SMTP AUTH # smtp_user = airflow # smtp_password = airflow smtp_port = 25 smtp_mail_from = myname@mycompany.com ``` 2. Editing environment variables in the entrypoint.sh script included in the repo: ``` : "${AIRFLOW__SMTP__SMTP_HOST:="smtp-host"}" : "${AIRFLOW__SMTP__SMTP_PORT:="25"}" # Defaults and back-compat : "${AIRFLOW_HOME:="/usr/local/airflow"}" : "${AIRFLOW__CORE__FERNET_KEY:=${FERNET_KEY:=$(python -c "from cryptography.fernet import Fernet; FERNET_KEY = Fernet.generate_key().decode(); print(FERNET_KEY)")}}" : "${AIRFLOW__CORE__EXECUTOR:=${EXECUTOR:-Sequential}Executor}" export \ AIRFLOW_HOME \ AIRFLOW__CELERY__BROKER_URL \ AIRFLOW__CELERY__RESULT_BACKEND \ AIRFLOW__CORE__EXECUTOR \ AIRFLOW__CORE__FERNET_KEY \ AIRFLOW__CORE__LOAD_EXAMPLES \ AIRFLOW__CORE__SQL_ALCHEMY_CONN \ AIRFLOW__SMTP__SMTP_HOST \ AIRFLOW__SMTP__SMTP_PORT \ if [ "$AIRFLOW__SMTP__SMTP_HOST" != "smtp-host" ]; then AIRFLOW__SMTP__SMTP_HOST="smtp-host" AIRFLOW__SMTP__SMTP_PORT=25 fi ``` I currently have a dag running that intentionally fails, but I am never alerted for retries or failures.
2019/11/06
[ "https://Stackoverflow.com/questions/58736009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7470072/" ]
You can groupby and transform for idxmax, eg: ``` dfx['MAXIDX'] = dfx.groupby('NAME').transform('idxmax') ```
Given your example, you can use reset\_index() together with groupby and then merge it into the original dataframe: ``` import pandas as pd data = [['AAA','2019-01-01', 10], ['AAA','2019-01-02', 21], ['AAA','2019-02-01', 30], ['AAA','2019-02-02', 45], ['BBB','2019-01-01', 50], ['BBB','2019-01-02', 60], ['BBB','2019-02-01', 70],['BBB','2019-02-02', 80]] dfx = pd.DataFrame(data, columns = ['NAME', 'TIMESTAMP','VALUE']) dfx = dfx.reset_index(drop=False) dfx = dfx.merge(dfx.groupby('NAME',as_index=False).agg({'index':'max'}),how='left',on='NAME').rename(columns={'index_y':'max_index'}).drop(columns='index_x') ``` Output: ``` NAME TIMESTAMP VALUE max_index AAA 2019-01-01 10 3 AAA 2019-01-02 21 3 AAA 2019-02-01 30 3 AAA 2019-02-02 45 3 BBB 2019-01-01 50 7 BBB 2019-01-02 60 7 BBB 2019-02-01 70 7 BBB 2019-02-02 80 7 ```
58,736,009
I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here: <https://github.com/puckel/docker-airflow> I am not able to get airflow to send me emails on failure or retry. I've tried the following: 1. Editing the config file with the smtp host name ``` [smtp] # If you want airflow to send emails on retries, failure, and you want to use # the airflow.utils.email.send_email_smtp function, you have to configure an # smtp server here smtp_host = smtp@mycompany.com smtp_starttls = True smtp_ssl = False # Uncomment and set the user/pass settings if you want to use SMTP AUTH # smtp_user = airflow # smtp_password = airflow smtp_port = 25 smtp_mail_from = myname@mycompany.com ``` 2. Editing environment variables in the entrypoint.sh script included in the repo: ``` : "${AIRFLOW__SMTP__SMTP_HOST:="smtp-host"}" : "${AIRFLOW__SMTP__SMTP_PORT:="25"}" # Defaults and back-compat : "${AIRFLOW_HOME:="/usr/local/airflow"}" : "${AIRFLOW__CORE__FERNET_KEY:=${FERNET_KEY:=$(python -c "from cryptography.fernet import Fernet; FERNET_KEY = Fernet.generate_key().decode(); print(FERNET_KEY)")}}" : "${AIRFLOW__CORE__EXECUTOR:=${EXECUTOR:-Sequential}Executor}" export \ AIRFLOW_HOME \ AIRFLOW__CELERY__BROKER_URL \ AIRFLOW__CELERY__RESULT_BACKEND \ AIRFLOW__CORE__EXECUTOR \ AIRFLOW__CORE__FERNET_KEY \ AIRFLOW__CORE__LOAD_EXAMPLES \ AIRFLOW__CORE__SQL_ALCHEMY_CONN \ AIRFLOW__SMTP__SMTP_HOST \ AIRFLOW__SMTP__SMTP_PORT \ if [ "$AIRFLOW__SMTP__SMTP_HOST" != "smtp-host" ]; then AIRFLOW__SMTP__SMTP_HOST="smtp-host" AIRFLOW__SMTP__SMTP_PORT=25 fi ``` I currently have a dag running that intentionally fails, but I am never alerted for retries or failures.
2019/11/06
[ "https://Stackoverflow.com/questions/58736009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7470072/" ]
Given your example, you can use reset\_index() together with groupby and then merge it into the original dataframe: ``` import pandas as pd data = [['AAA','2019-01-01', 10], ['AAA','2019-01-02', 21], ['AAA','2019-02-01', 30], ['AAA','2019-02-02', 45], ['BBB','2019-01-01', 50], ['BBB','2019-01-02', 60], ['BBB','2019-02-01', 70],['BBB','2019-02-02', 80]] dfx = pd.DataFrame(data, columns = ['NAME', 'TIMESTAMP','VALUE']) dfx = dfx.reset_index(drop=False) dfx = dfx.merge(dfx.groupby('NAME',as_index=False).agg({'index':'max'}),how='left',on='NAME').rename(columns={'index_y':'max_index'}).drop(columns='index_x') ``` Output: ``` NAME TIMESTAMP VALUE max_index AAA 2019-01-01 10 3 AAA 2019-01-02 21 3 AAA 2019-02-01 30 3 AAA 2019-02-02 45 3 BBB 2019-01-01 50 7 BBB 2019-01-02 60 7 BBB 2019-02-01 70 7 BBB 2019-02-02 80 7 ```
I will do `sort_values` + `drop_duplicates` + `merge` ``` df.merge(df.sort_values('VALUE'). drop_duplicates('NAME',keep='last')['NAME']. reset_index(),on='NAME') Out[73]: NAME TIMESTAMP VALUE index 0 AAA 2019-01-01 10 3 1 AAA 2019-01-02 21 3 2 AAA 2019-02-01 30 3 3 AAA 2019-02-02 45 3 4 BBB 2019-01-01 50 7 5 BBB 2019-01-02 60 7 6 BBB 2019-02-01 70 7 7 BBB 2019-02-02 80 7 ```
58,736,009
I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here: <https://github.com/puckel/docker-airflow> I am not able to get airflow to send me emails on failure or retry. I've tried the following: 1. Editing the config file with the smtp host name ``` [smtp] # If you want airflow to send emails on retries, failure, and you want to use # the airflow.utils.email.send_email_smtp function, you have to configure an # smtp server here smtp_host = smtp@mycompany.com smtp_starttls = True smtp_ssl = False # Uncomment and set the user/pass settings if you want to use SMTP AUTH # smtp_user = airflow # smtp_password = airflow smtp_port = 25 smtp_mail_from = myname@mycompany.com ``` 2. Editing environment variables in the entrypoint.sh script included in the repo: ``` : "${AIRFLOW__SMTP__SMTP_HOST:="smtp-host"}" : "${AIRFLOW__SMTP__SMTP_PORT:="25"}" # Defaults and back-compat : "${AIRFLOW_HOME:="/usr/local/airflow"}" : "${AIRFLOW__CORE__FERNET_KEY:=${FERNET_KEY:=$(python -c "from cryptography.fernet import Fernet; FERNET_KEY = Fernet.generate_key().decode(); print(FERNET_KEY)")}}" : "${AIRFLOW__CORE__EXECUTOR:=${EXECUTOR:-Sequential}Executor}" export \ AIRFLOW_HOME \ AIRFLOW__CELERY__BROKER_URL \ AIRFLOW__CELERY__RESULT_BACKEND \ AIRFLOW__CORE__EXECUTOR \ AIRFLOW__CORE__FERNET_KEY \ AIRFLOW__CORE__LOAD_EXAMPLES \ AIRFLOW__CORE__SQL_ALCHEMY_CONN \ AIRFLOW__SMTP__SMTP_HOST \ AIRFLOW__SMTP__SMTP_PORT \ if [ "$AIRFLOW__SMTP__SMTP_HOST" != "smtp-host" ]; then AIRFLOW__SMTP__SMTP_HOST="smtp-host" AIRFLOW__SMTP__SMTP_PORT=25 fi ``` I currently have a dag running that intentionally fails, but I am never alerted for retries or failures.
2019/11/06
[ "https://Stackoverflow.com/questions/58736009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7470072/" ]
You can groupby and transform for idxmax, eg: ``` dfx['MAXIDX'] = dfx.groupby('NAME').transform('idxmax') ```
The following code solved my problem for me, thanks to @Jon and @Celius. ``` dfx.reset_index(drop=False) dfx['MAXIDX'] = dfx.groupby('NAME')['index'].transform(max) ```
58,736,009
I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here: <https://github.com/puckel/docker-airflow> I am not able to get airflow to send me emails on failure or retry. I've tried the following: 1. Editing the config file with the smtp host name ``` [smtp] # If you want airflow to send emails on retries, failure, and you want to use # the airflow.utils.email.send_email_smtp function, you have to configure an # smtp server here smtp_host = smtp@mycompany.com smtp_starttls = True smtp_ssl = False # Uncomment and set the user/pass settings if you want to use SMTP AUTH # smtp_user = airflow # smtp_password = airflow smtp_port = 25 smtp_mail_from = myname@mycompany.com ``` 2. Editing environment variables in the entrypoint.sh script included in the repo: ``` : "${AIRFLOW__SMTP__SMTP_HOST:="smtp-host"}" : "${AIRFLOW__SMTP__SMTP_PORT:="25"}" # Defaults and back-compat : "${AIRFLOW_HOME:="/usr/local/airflow"}" : "${AIRFLOW__CORE__FERNET_KEY:=${FERNET_KEY:=$(python -c "from cryptography.fernet import Fernet; FERNET_KEY = Fernet.generate_key().decode(); print(FERNET_KEY)")}}" : "${AIRFLOW__CORE__EXECUTOR:=${EXECUTOR:-Sequential}Executor}" export \ AIRFLOW_HOME \ AIRFLOW__CELERY__BROKER_URL \ AIRFLOW__CELERY__RESULT_BACKEND \ AIRFLOW__CORE__EXECUTOR \ AIRFLOW__CORE__FERNET_KEY \ AIRFLOW__CORE__LOAD_EXAMPLES \ AIRFLOW__CORE__SQL_ALCHEMY_CONN \ AIRFLOW__SMTP__SMTP_HOST \ AIRFLOW__SMTP__SMTP_PORT \ if [ "$AIRFLOW__SMTP__SMTP_HOST" != "smtp-host" ]; then AIRFLOW__SMTP__SMTP_HOST="smtp-host" AIRFLOW__SMTP__SMTP_PORT=25 fi ``` I currently have a dag running that intentionally fails, but I am never alerted for retries or failures.
2019/11/06
[ "https://Stackoverflow.com/questions/58736009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7470072/" ]
You can groupby and transform for idxmax, eg: ``` dfx['MAXIDX'] = dfx.groupby('NAME').transform('idxmax') ```
I will do `sort_values` + `drop_duplicates` + `merge` ``` df.merge(df.sort_values('VALUE'). drop_duplicates('NAME',keep='last')['NAME']. reset_index(),on='NAME') Out[73]: NAME TIMESTAMP VALUE index 0 AAA 2019-01-01 10 3 1 AAA 2019-01-02 21 3 2 AAA 2019-02-01 30 3 3 AAA 2019-02-02 45 3 4 BBB 2019-01-01 50 7 5 BBB 2019-01-02 60 7 6 BBB 2019-02-01 70 7 7 BBB 2019-02-02 80 7 ```
58,736,009
I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here: <https://github.com/puckel/docker-airflow> I am not able to get airflow to send me emails on failure or retry. I've tried the following: 1. Editing the config file with the smtp host name ``` [smtp] # If you want airflow to send emails on retries, failure, and you want to use # the airflow.utils.email.send_email_smtp function, you have to configure an # smtp server here smtp_host = smtp@mycompany.com smtp_starttls = True smtp_ssl = False # Uncomment and set the user/pass settings if you want to use SMTP AUTH # smtp_user = airflow # smtp_password = airflow smtp_port = 25 smtp_mail_from = myname@mycompany.com ``` 2. Editing environment variables in the entrypoint.sh script included in the repo: ``` : "${AIRFLOW__SMTP__SMTP_HOST:="smtp-host"}" : "${AIRFLOW__SMTP__SMTP_PORT:="25"}" # Defaults and back-compat : "${AIRFLOW_HOME:="/usr/local/airflow"}" : "${AIRFLOW__CORE__FERNET_KEY:=${FERNET_KEY:=$(python -c "from cryptography.fernet import Fernet; FERNET_KEY = Fernet.generate_key().decode(); print(FERNET_KEY)")}}" : "${AIRFLOW__CORE__EXECUTOR:=${EXECUTOR:-Sequential}Executor}" export \ AIRFLOW_HOME \ AIRFLOW__CELERY__BROKER_URL \ AIRFLOW__CELERY__RESULT_BACKEND \ AIRFLOW__CORE__EXECUTOR \ AIRFLOW__CORE__FERNET_KEY \ AIRFLOW__CORE__LOAD_EXAMPLES \ AIRFLOW__CORE__SQL_ALCHEMY_CONN \ AIRFLOW__SMTP__SMTP_HOST \ AIRFLOW__SMTP__SMTP_PORT \ if [ "$AIRFLOW__SMTP__SMTP_HOST" != "smtp-host" ]; then AIRFLOW__SMTP__SMTP_HOST="smtp-host" AIRFLOW__SMTP__SMTP_PORT=25 fi ``` I currently have a dag running that intentionally fails, but I am never alerted for retries or failures.
2019/11/06
[ "https://Stackoverflow.com/questions/58736009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7470072/" ]
The following code solved my problem for me, thanks to @Jon and @Celius. ``` dfx.reset_index(drop=False) dfx['MAXIDX'] = dfx.groupby('NAME')['index'].transform(max) ```
I will do `sort_values` + `drop_duplicates` + `merge` ``` df.merge(df.sort_values('VALUE'). drop_duplicates('NAME',keep='last')['NAME']. reset_index(),on='NAME') Out[73]: NAME TIMESTAMP VALUE index 0 AAA 2019-01-01 10 3 1 AAA 2019-01-02 21 3 2 AAA 2019-02-01 30 3 3 AAA 2019-02-02 45 3 4 BBB 2019-01-01 50 7 5 BBB 2019-01-02 60 7 6 BBB 2019-02-01 70 7 7 BBB 2019-02-02 80 7 ```
44,424,308
C++ part I have a class `a` with a **public** variable 2d int array `b` that I want to print out in python.(The way I want to access it is `a.b`) I have been able to wrap the most part of the code and I can call most of the functions in class a in python now. So how can I read b in python? How to read it into an numpy array with numpy.i(I find some solution on how to work with a function not variable)? Is there a way I can read any array in the c++ library? Or I have to deal with each of the variables in the interface file. for now b is `<Swig Object of type 'int (*)[24]' at 0x02F65158>` when I try to use it in python ps: 1. If possible I don't want to modify the cpp part. 2. I'm trying to access a variable, not a function. So don't refer me to links that doesn't really answer my question, thanks.
2017/06/07
[ "https://Stackoverflow.com/questions/44424308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7967265/" ]
There's some relevant information in the Fetch specification. As per <https://fetch.spec.whatwg.org/#forbidden-response-header-name>: > > A forbidden response-header name is a header name that is a > byte-case-insensitive match for one of: > > > * `Set-Cookie` > * `Set-Cookie2` > > > And then as per item 6 in <https://fetch.spec.whatwg.org/#concept-headers-append>: > > Otherwise, if guard is "response" and name is a forbidden response-header name, return. > > > This restriction on adding in the `Set-Cookie` header applies to either constructing new `Response` objects with an initial set of headers, or adding in headers after the fact to an existing `Response` object. There is a plan to add in support for reading and writing cookies inside of a service worker, but that will use a mechanism other than the `Set-Cookie` header in a `Response` object. There's more information about the plans in [this GitHub issue](https://github.com/w3c/ServiceWorker/issues/707).
You may try following: ``` async function handleRequest(request) { let response = await fetch(request.url, request); // Copy the response so that we can modify headers. response = new Response(response.body, response) response.headers.set("Set-Cookie", "test=1234"); return response; } ```
38,722,340
Let's consider the code below code: ``` #!/usr/bin/env python class Foo(): def __init__(self, b): self.a = 0.0 self.b = b def count_a(self): self.a += 0.1 foo = Foo(1) for i in range(0, 15): foo.count_a() print "a =", foo.a, "b =", foo.b, '"a == b" ->', foo.a == foo.b ``` Output: ``` a = 0.2 b = 1 "a == b" -> False a = 0.4 b = 1 "a == b" -> False a = 0.6 b = 1 "a == b" -> False a = 0.8 b = 1 "a == b" -> False a = 1.0 b = 1 "a == b" -> True a = 1.2 b = 1 "a == b" -> False a = 1.4 b = 1 "a == b" -> False a = 1.6 b = 1 "a == b" -> False a = 1.8 b = 1 "a == b" -> False a = 2.0 b = 1 "a == b" -> False a = 2.2 b = 1 "a == b" -> False a = 2.4 b = 1 "a == b" -> False a = 2.6 b = 1 "a == b" -> False a = 2.8 b = 1 "a == b" -> False a = 3.0 b = 1 "a == b" -> False ``` But if I change code on line `11` to `foo = Foo(2)`, the output is turned to be: ``` a = 0.2 b = 2 "a == b" -> False a = 0.4 b = 2 "a == b" -> False a = 0.6 b = 2 "a == b" -> False a = 0.8 b = 2 "a == b" -> False a = 1.0 b = 2 "a == b" -> False a = 1.2 b = 2 "a == b" -> False a = 1.4 b = 2 "a == b" -> False a = 1.6 b = 2 "a == b" -> False a = 1.8 b = 2 "a == b" -> False a = 2.0 b = 2 "a == b" -> False * a = 2.2 b = 2 "a == b" -> False a = 2.4 b = 2 "a == b" -> False a = 2.6 b = 2 "a == b" -> False a = 2.8 b = 2 "a == b" -> False a = 3.0 b = 2 "a == b" -> False ``` You will see that the output `a = 2.0 b = 2 "a == b" -> False` is totally weird. I think I might misunderstand some concept of OOP in Python. Please explain to me why this unexpected output is happened and how to solve this problem.
2016/08/02
[ "https://Stackoverflow.com/questions/38722340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/829496/" ]
This has nothing to do with Object Orientation - it has to do with the way computers represent floating point numbers internally, and rounding errors. <http://floating-point-gui.de/basic/> The Python specificity here is the default string representation of floating point numbers, which will round them at less decimal places than the internal representation for pretty printing. Although, for people needing correct comparisons, respecting the scale of floating point numbers, Python has introduced a nice mechanism with [PEP 485](https://www.python.org/dev/peps/pep-0485/), which added the `math.isclose` function to the standard library.
Aside from the, correct, explanation by jsbueno, remember that Python often allows casting of "basic types" to themselves. i.e. str("a") == "a" So, if you need a workaround in addition to the reason, just convert your int/float mix to all floats and test those. ``` a = 2.0 b = 2 print "a == b", float(a) == float(b) ``` output: ``` a == b True ```
58,721,480
I have a python/flask/html project I'm currently working on. I'm using bootstrap 4 for a grid system with multiple rows and columns. When I try to run my project, it cuts off a few pixels on the left side of the screen. I've looked all over my code and I'm still not sure as to why this is. [Here](https://jsfiddle.net/mk78ebo2/) is a jsfiddle with my code, as well as a hard copy of it. Thank you for any help! ``` <!DOCTYPE html> ``` ``` <!-- Link to css file --> <link rel="stylesheet" type="text/css" href="/static/main.css" mesdia="screen"/> <!-- Bootstrap CDN--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <meta charset="UTF-8"> <title>Layout</title> <!--<h1>Welcome to the layout</h1> <p>Where would you like to navigate to?</p>--> ``` ``` <div class="row" id="navcols"> <div class="col"> <div class="row h-50">Row</div> <div class="row h-50">Row</div> </div> <div class="col-sm-6"> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> </div> <div class="col"> <div class="row">Row</div> </div> </div> <!-- <div class="container-fluid"> <h1 id="test">Welcome to my page! Where do you want to navigate to?</h1> </div>--> ``` ``` html,body { height: 100%; width: 100%; } .col { background-color:red; } ```
2019/11/06
[ "https://Stackoverflow.com/questions/58721480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11757353/" ]
As far as Bootstrap layout is concerned, you always need to put your row and col elements within a div with the class of **container** or **container-fluid**. If you want full width column then use **container-fluid**. **container** has a max width pixel value, whereas .**container-fluid** is max-width 100%. .**container-fluid** continuously resizes as you change the width of your window/browser by any amount. : ```css html, body { height: 100%; width: 100%; } .col { background-color: red; } ``` ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <div class="container-fluid"> <div class="row" id="navcols"> <div class="col"> <div class="row h-50">Row</div> <div class="row h-50">Row</div> </div> <div class="col-sm-6"> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> </div> <div class="col"> <div class="row">Row</div> </div> </div> </div> ```
wrap your row class div inside of a container or container-fluid class div ```html <div class='container'> <div class='row'> <!--your grid--> </div> </div> ```
58,721,480
I have a python/flask/html project I'm currently working on. I'm using bootstrap 4 for a grid system with multiple rows and columns. When I try to run my project, it cuts off a few pixels on the left side of the screen. I've looked all over my code and I'm still not sure as to why this is. [Here](https://jsfiddle.net/mk78ebo2/) is a jsfiddle with my code, as well as a hard copy of it. Thank you for any help! ``` <!DOCTYPE html> ``` ``` <!-- Link to css file --> <link rel="stylesheet" type="text/css" href="/static/main.css" mesdia="screen"/> <!-- Bootstrap CDN--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <meta charset="UTF-8"> <title>Layout</title> <!--<h1>Welcome to the layout</h1> <p>Where would you like to navigate to?</p>--> ``` ``` <div class="row" id="navcols"> <div class="col"> <div class="row h-50">Row</div> <div class="row h-50">Row</div> </div> <div class="col-sm-6"> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> </div> <div class="col"> <div class="row">Row</div> </div> </div> <!-- <div class="container-fluid"> <h1 id="test">Welcome to my page! Where do you want to navigate to?</h1> </div>--> ``` ``` html,body { height: 100%; width: 100%; } .col { background-color:red; } ```
2019/11/06
[ "https://Stackoverflow.com/questions/58721480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11757353/" ]
As far as Bootstrap layout is concerned, you always need to put your row and col elements within a div with the class of **container** or **container-fluid**. If you want full width column then use **container-fluid**. **container** has a max width pixel value, whereas .**container-fluid** is max-width 100%. .**container-fluid** continuously resizes as you change the width of your window/browser by any amount. : ```css html, body { height: 100%; width: 100%; } .col { background-color: red; } ``` ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <div class="container-fluid"> <div class="row" id="navcols"> <div class="col"> <div class="row h-50">Row</div> <div class="row h-50">Row</div> </div> <div class="col-sm-6"> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> </div> <div class="col"> <div class="row">Row</div> </div> </div> </div> ```
Try add .container OR .container-fluid class in parent div in your HTML. ``` <div class="container"> <div class="row" id="navcols"> <div class="col"> <div class="row h-50">Row</div> <div class="row h-50">Row</div> </div> <div class="col-sm-6"> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> </div> <div class="col"> <div class="row">Row</div> </div> </div> </div> ```
58,721,480
I have a python/flask/html project I'm currently working on. I'm using bootstrap 4 for a grid system with multiple rows and columns. When I try to run my project, it cuts off a few pixels on the left side of the screen. I've looked all over my code and I'm still not sure as to why this is. [Here](https://jsfiddle.net/mk78ebo2/) is a jsfiddle with my code, as well as a hard copy of it. Thank you for any help! ``` <!DOCTYPE html> ``` ``` <!-- Link to css file --> <link rel="stylesheet" type="text/css" href="/static/main.css" mesdia="screen"/> <!-- Bootstrap CDN--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <meta charset="UTF-8"> <title>Layout</title> <!--<h1>Welcome to the layout</h1> <p>Where would you like to navigate to?</p>--> ``` ``` <div class="row" id="navcols"> <div class="col"> <div class="row h-50">Row</div> <div class="row h-50">Row</div> </div> <div class="col-sm-6"> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> </div> <div class="col"> <div class="row">Row</div> </div> </div> <!-- <div class="container-fluid"> <h1 id="test">Welcome to my page! Where do you want to navigate to?</h1> </div>--> ``` ``` html,body { height: 100%; width: 100%; } .col { background-color:red; } ```
2019/11/06
[ "https://Stackoverflow.com/questions/58721480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11757353/" ]
As far as Bootstrap layout is concerned, you always need to put your row and col elements within a div with the class of **container** or **container-fluid**. If you want full width column then use **container-fluid**. **container** has a max width pixel value, whereas .**container-fluid** is max-width 100%. .**container-fluid** continuously resizes as you change the width of your window/browser by any amount. : ```css html, body { height: 100%; width: 100%; } .col { background-color: red; } ``` ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <div class="container-fluid"> <div class="row" id="navcols"> <div class="col"> <div class="row h-50">Row</div> <div class="row h-50">Row</div> </div> <div class="col-sm-6"> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> </div> <div class="col"> <div class="row">Row</div> </div> </div> </div> ```
Your Bootstrap class contains -15px margin from left and right; that's why it is cutting your screen. So, you can fix it by making it 0. ``` <div class="row" id="navcols" style="margin-left:0; margin-right:0;"> <div class="col"> <div class="row h-50">Row</div> <div class="row h-50">Row</div> </div> <div class="col-sm-6"> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> <div class="row h-100">Row</div> </div> <div class="col"> <div class="row">Row</div> </div> </div> ``` ![Screen shot](https://i.stack.imgur.com/fuUaTl.png)
5,159,351
urllib fetches data from urls right? is there a python library that can do the reverse of that and send data to urls instead (for example, to a site you are managing)? and if so, is that library compatible with apache? thanks.
2011/03/01
[ "https://Stackoverflow.com/questions/5159351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/582485/" ]
What does sending data to a URL mean? The usual way to do that is just via an HTTP POST, and `urllib` (and `urllib2`) handle that just fine.
urllib can send data associated with a request by using GET or POST. `urllib2.urlopen(url, data)` where data is a dict of key-values representing the data you're sending. See [this link on usage](http://www.java2s.com/Code/Python/Network/SubmitPOSTData.htm). Then process that data on the server-side. If you want to send data any other way, you should use some other protocol such as FTP (see [ftplib](http://docs.python.org/library/ftplib.html)).
63,894,354
i'm very much a newbie to python. I've read a csv file correctly, and if i do a print(row[0]) in a for loop it prints the first column. But now within the loop, i'd like to do a conditional. Obviously using row[0] in it doesn't work. what's the correct syntax? here's my code ``` video_choice = input("What movie would you like to look up? ") # read the rows for row in netflix_reader: If video_choice == row[0]: print(row[0]) ```
2020/09/15
[ "https://Stackoverflow.com/questions/63894354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8628471/" ]
you could do ``` if video_choice in row[0]: ... ```
nvm, I have the if as "If". I'm def a newb
28,176,866
I have a list in python like this: ``` myList = [1,14,2,5,3,7,8,12] ``` How can I easily find the first unused value? (in this case '4')
2015/01/27
[ "https://Stackoverflow.com/questions/28176866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506998/" ]
Don't know how efficient, but why not use an xrange as a mask and use set minus? ``` >>> myList = [1,14,2,5,3,7,8,12] >>> min(set(xrange(1, len(myList) + 1)) - set(myList)) 4 ``` You're only creating a set as big as `myList`, so it can't be that bad :) This won't work for "full" lists: ``` >>> myList = range(1, 5) >>> min(set(xrange(1, len(myList) + 1)) - set(myList)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: min() arg is an empty sequence ``` But the fix to return the next value is simple (add one more to the masked set): ``` >>> min(set(xrange(1, len(myList) + 2)) - set(myList)) 5 ```
I just solved this in a probably non pythonic way ``` def solution(A): # Const-ish to improve readability MIN = 1 if not A: return MIN # Save re-computing MAX MAX = max(A) # Loop over all entries with minimum of 1 starting at 1 for num in range(1, MAX): # going for greatest missing number return optimistically (minimum) # If order needs to switch, then use max as start and count backwards if num not in A: return num # In case the max is < 0 double wrap max with minimum return value return max(MIN, MAX+1) ``` I think it reads quite well
28,176,866
I have a list in python like this: ``` myList = [1,14,2,5,3,7,8,12] ``` How can I easily find the first unused value? (in this case '4')
2015/01/27
[ "https://Stackoverflow.com/questions/28176866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506998/" ]
you can try this ``` for i in range(1,max(arr1)+2): if i not in arr1: print(i) break ```
Keep incrementing a counter in a loop until you find the first positive integer that's not in the list. ``` def getSmallestIntNotInList(number_list): """Returns the smallest positive integer that is not in a given list""" i = 0 while True: i += 1 if i not in number_list: return i print(getSmallestIntNotInList([1,14,2,5,3,7,8,12])) # 4 ``` I found that this had the fastest performance compared to other answers on this post. I tested using `timeit` in Python 3.10.8. My performance results can be seen below: ``` import timeit def findSmallestIntNotInList(number_list): # Infinite while-loop until first number is found i = 0 while True: i += 1 if i not in number_list: return i t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.038100800011307 seconds ``` ``` import timeit def findSmallestIntNotInList(number_list): # Loop with a range to len(number_list)+1 for i in range (1, len(number_list)+1): if i not in number_list: return i t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.05068870005197823 seconds ``` ``` import timeit def findSmallestIntNotInList(number_list): # Loop with a range to max(number_list) (by silgon) # https://stackoverflow.com/a/49649558/3357935 for i in range (1, max(number_list)): if i not in number_list: return i t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.06317249999847263 seconds ``` ``` import timeit from itertools import count, filterfalse def findSmallestIntNotInList(number_list): # iterate the first number not in set (by Antti Haapala -- Слава Україні) # https://stackoverflow.com/a/28178803/3357935 return(next(filterfalse(set(number_list).__contains__, count(1)))) t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.06515420007053763 seconds ``` ``` import timeit def findSmallestIntNotInList(number_list): # Use property of sets (by Bhargav Rao) # https://stackoverflow.com/a/28176962/3357935 m = range(1, len(number_list)) return min(set(m)-set(number_list)) t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.08586219989228994 seconds ```
28,176,866
I have a list in python like this: ``` myList = [1,14,2,5,3,7,8,12] ``` How can I easily find the first unused value? (in this case '4')
2015/01/27
[ "https://Stackoverflow.com/questions/28176866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506998/" ]
I just solved this in a probably non pythonic way ``` def solution(A): # Const-ish to improve readability MIN = 1 if not A: return MIN # Save re-computing MAX MAX = max(A) # Loop over all entries with minimum of 1 starting at 1 for num in range(1, MAX): # going for greatest missing number return optimistically (minimum) # If order needs to switch, then use max as start and count backwards if num not in A: return num # In case the max is < 0 double wrap max with minimum return value return max(MIN, MAX+1) ``` I think it reads quite well
you can try this ``` for i in range(1,max(arr1)+2): if i not in arr1: print(i) break ```
28,176,866
I have a list in python like this: ``` myList = [1,14,2,5,3,7,8,12] ``` How can I easily find the first unused value? (in this case '4')
2015/01/27
[ "https://Stackoverflow.com/questions/28176866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506998/" ]
A for loop with the list will do it. ``` l = [1,14,2,5,3,7,8,12] for i in range(1, max(l)): if i not in l: break print(i) # result 4 ```
My effort, no itertools. Sets "current" to be the one less than the value you are expecting. ``` list = [1,2,3,4,5,7,8] current = list[0]-1 for i in list: if i != current+1: print current+1 break current = i ```
28,176,866
I have a list in python like this: ``` myList = [1,14,2,5,3,7,8,12] ``` How can I easily find the first unused value? (in this case '4')
2015/01/27
[ "https://Stackoverflow.com/questions/28176866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506998/" ]
I would suggest you to use a generator and use enumerate to determine the missing element ``` >>> next(a for a, b in enumerate(myList, myList[0]) if a != b) 4 ``` [enumerate](https://docs.python.org/2/library/functions.html#enumerate) maps the index with the element so your goal is to determine that element which differs from its index. Note, I am also assuming that the elements may not start with a definite value, in this case which is `1`, and if it is so, you can simplify the expression further as ``` >>> next(a for a, b in enumerate(myList, 1) if a != b) 4 ```
A solution that returns all those values is ``` free_values = set(range(1, max(L))) - set(L) ``` it does a full scan, but those loops are implemented in C and unless the list or its maximum value are huge this will be a win over more sophisticated algorithms performing the looping in Python. Note that if this search is needed to implement "reuse" of IDs then keeping a free list around and maintaining it up-to-date (i.e. adding numbers to it when deleting entries and picking from it when reusing entries) is a often a good idea.
28,176,866
I have a list in python like this: ``` myList = [1,14,2,5,3,7,8,12] ``` How can I easily find the first unused value? (in this case '4')
2015/01/27
[ "https://Stackoverflow.com/questions/28176866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506998/" ]
A for loop with the list will do it. ``` l = [1,14,2,5,3,7,8,12] for i in range(1, max(l)): if i not in l: break print(i) # result 4 ```
Easy to read, easy to understand, gets the job done: ``` def solution(A): smallest = 1 unique = set(A) for int in unique: if int == smallest: smallest += 1 return smallest ```
28,176,866
I have a list in python like this: ``` myList = [1,14,2,5,3,7,8,12] ``` How can I easily find the first unused value? (in this case '4')
2015/01/27
[ "https://Stackoverflow.com/questions/28176866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506998/" ]
Easy to read, easy to understand, gets the job done: ``` def solution(A): smallest = 1 unique = set(A) for int in unique: if int == smallest: smallest += 1 return smallest ```
Keep incrementing a counter in a loop until you find the first positive integer that's not in the list. ``` def getSmallestIntNotInList(number_list): """Returns the smallest positive integer that is not in a given list""" i = 0 while True: i += 1 if i not in number_list: return i print(getSmallestIntNotInList([1,14,2,5,3,7,8,12])) # 4 ``` I found that this had the fastest performance compared to other answers on this post. I tested using `timeit` in Python 3.10.8. My performance results can be seen below: ``` import timeit def findSmallestIntNotInList(number_list): # Infinite while-loop until first number is found i = 0 while True: i += 1 if i not in number_list: return i t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.038100800011307 seconds ``` ``` import timeit def findSmallestIntNotInList(number_list): # Loop with a range to len(number_list)+1 for i in range (1, len(number_list)+1): if i not in number_list: return i t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.05068870005197823 seconds ``` ``` import timeit def findSmallestIntNotInList(number_list): # Loop with a range to max(number_list) (by silgon) # https://stackoverflow.com/a/49649558/3357935 for i in range (1, max(number_list)): if i not in number_list: return i t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.06317249999847263 seconds ``` ``` import timeit from itertools import count, filterfalse def findSmallestIntNotInList(number_list): # iterate the first number not in set (by Antti Haapala -- Слава Україні) # https://stackoverflow.com/a/28178803/3357935 return(next(filterfalse(set(number_list).__contains__, count(1)))) t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.06515420007053763 seconds ``` ``` import timeit def findSmallestIntNotInList(number_list): # Use property of sets (by Bhargav Rao) # https://stackoverflow.com/a/28176962/3357935 m = range(1, len(number_list)) return min(set(m)-set(number_list)) t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.08586219989228994 seconds ```
28,176,866
I have a list in python like this: ``` myList = [1,14,2,5,3,7,8,12] ``` How can I easily find the first unused value? (in this case '4')
2015/01/27
[ "https://Stackoverflow.com/questions/28176866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506998/" ]
This makes use of the property of sets ``` >>> l = [1,2,3,5,7,8,12,14] >>> m = range(1,len(l)) >>> min(set(m)-set(l)) 4 ```
The naive way is to traverse the list which is an O(n) solution. However, since the list is sorted, you can use this feature to perform binary search (a modified version for it). Basically, you are looking for the last occurance of A[i] = i. The pseudo algorithm will be something like: ``` binarysearch(A): start = 0 end = len(A) - 1 while(start <= end ): mid = (start + end) / 2 if(A[mid] == mid): result = A[mid] start = mid + 1 else: #A[mid] > mid since there is no way A[mid] is less than mid end = mid - 1 return (result + 1) ``` This is an O(log n) solution. I assumed lists are one indexed. You can modify the indices accordingly EDIT: if the list is not sorted, you can use the heapq python library and store the list in a min-heap and then pop the elements one by one pseudo code ``` H = heapify(A) //Assuming A is the list count = 1 for i in range(len(A)): if(H.pop() != count): return count count += 1 ```
28,176,866
I have a list in python like this: ``` myList = [1,14,2,5,3,7,8,12] ``` How can I easily find the first unused value? (in this case '4')
2015/01/27
[ "https://Stackoverflow.com/questions/28176866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506998/" ]
I just solved this in a probably non pythonic way ``` def solution(A): # Const-ish to improve readability MIN = 1 if not A: return MIN # Save re-computing MAX MAX = max(A) # Loop over all entries with minimum of 1 starting at 1 for num in range(1, MAX): # going for greatest missing number return optimistically (minimum) # If order needs to switch, then use max as start and count backwards if num not in A: return num # In case the max is < 0 double wrap max with minimum return value return max(MIN, MAX+1) ``` I think it reads quite well
The following solution loops all numbers in between 1 and the length of the input list and breaks the loop whenever a number is not found inside it. Otherwise the result is the length of the list plus one. ``` listOfNumbers=[1,14,2,5,3,7,8,12] for i in range(1, len(listOfNumbers)+1): if not i in listOfNumbers: nextNumber=i break else: nextNumber=len(listOfNumbers)+1 ```
28,176,866
I have a list in python like this: ``` myList = [1,14,2,5,3,7,8,12] ``` How can I easily find the first unused value? (in this case '4')
2015/01/27
[ "https://Stackoverflow.com/questions/28176866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506998/" ]
The naive way is to traverse the list which is an O(n) solution. However, since the list is sorted, you can use this feature to perform binary search (a modified version for it). Basically, you are looking for the last occurance of A[i] = i. The pseudo algorithm will be something like: ``` binarysearch(A): start = 0 end = len(A) - 1 while(start <= end ): mid = (start + end) / 2 if(A[mid] == mid): result = A[mid] start = mid + 1 else: #A[mid] > mid since there is no way A[mid] is less than mid end = mid - 1 return (result + 1) ``` This is an O(log n) solution. I assumed lists are one indexed. You can modify the indices accordingly EDIT: if the list is not sorted, you can use the heapq python library and store the list in a min-heap and then pop the elements one by one pseudo code ``` H = heapify(A) //Assuming A is the list count = 1 for i in range(len(A)): if(H.pop() != count): return count count += 1 ```
Keep incrementing a counter in a loop until you find the first positive integer that's not in the list. ``` def getSmallestIntNotInList(number_list): """Returns the smallest positive integer that is not in a given list""" i = 0 while True: i += 1 if i not in number_list: return i print(getSmallestIntNotInList([1,14,2,5,3,7,8,12])) # 4 ``` I found that this had the fastest performance compared to other answers on this post. I tested using `timeit` in Python 3.10.8. My performance results can be seen below: ``` import timeit def findSmallestIntNotInList(number_list): # Infinite while-loop until first number is found i = 0 while True: i += 1 if i not in number_list: return i t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.038100800011307 seconds ``` ``` import timeit def findSmallestIntNotInList(number_list): # Loop with a range to len(number_list)+1 for i in range (1, len(number_list)+1): if i not in number_list: return i t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.05068870005197823 seconds ``` ``` import timeit def findSmallestIntNotInList(number_list): # Loop with a range to max(number_list) (by silgon) # https://stackoverflow.com/a/49649558/3357935 for i in range (1, max(number_list)): if i not in number_list: return i t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.06317249999847263 seconds ``` ``` import timeit from itertools import count, filterfalse def findSmallestIntNotInList(number_list): # iterate the first number not in set (by Antti Haapala -- Слава Україні) # https://stackoverflow.com/a/28178803/3357935 return(next(filterfalse(set(number_list).__contains__, count(1)))) t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.06515420007053763 seconds ``` ``` import timeit def findSmallestIntNotInList(number_list): # Use property of sets (by Bhargav Rao) # https://stackoverflow.com/a/28176962/3357935 m = range(1, len(number_list)) return min(set(m)-set(number_list)) t = timeit.Timer(lambda: findSmallestIntNotInList([1,14,2,5,3,7,8,12])) print('Execution time:', t.timeit(100000), 'seconds') # Execution time: 0.08586219989228994 seconds ```
8,616,617
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'Hello Exception!',) gm.setLevel(logging.ERROR) logger.addHandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0 ``` It took more than 1sec to complete, blocking the python script for this whole time. How come? How can I make it not block the script?
2011/12/23
[ "https://Stackoverflow.com/questions/8616617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348545/" ]
The simplest form of asynchronous smtp handler for me is just to override `emit` method and use the original method in a new thread. GIL is not a problem in this case because there is an I/O call to SMTP server which releases GIL. The code is as follows ``` class ThreadedSMTPHandler(SMTPHandler): def emit(self, record): thread = Thread(target=SMTPHandler.emit, args=(self, record)) thread.start() ```
Here's the implementation I'm using, which I based on Jonathan Livni code. ``` import logging.handlers import smtplib from threading import Thread # File with my configuration import credentials as cr host = cr.set_logSMTP["host"] port = cr.set_logSMTP["port"] user = cr.set_logSMTP["user"] pwd = cr.set_logSMTP["pwd"] to = cr.set_logSMTP["to"] def smtp_at_your_own_leasure( mailhost, port, username, password, fromaddr, toaddrs, msg ): smtp = smtplib.SMTP(mailhost, port) if username: smtp.ehlo() # for tls add this line smtp.starttls() # for tls add this line smtp.ehlo() # for tls add this line smtp.login(username, password) smtp.sendmail(fromaddr, toaddrs, msg) smtp.quit() class ThreadedTlsSMTPHandler(logging.handlers.SMTPHandler): def emit(self, record): try: # import string # <<<CHANGE THIS>>> try: from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport if not port: port = smtplib.SMTP_PORT msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, ",".join(self.toaddrs), # <<<CHANGE THIS>>> self.getSubject(record), formatdate(), msg, ) thread = Thread( target=smtp_at_your_own_leasure, args=( self.mailhost, port, self.username, self.password, self.fromaddr, self.toaddrs, msg, ), ) thread.start() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) # Test if __name__ == "__main__": logger = logging.getLogger() gm = ThreadedTlsSMTPHandler((host, port), user, to, "Error!:", (user, pwd)) gm.setLevel(logging.ERROR) logger.addHandler(gm) try: 1 / 0 except: logger.exception("Test ZeroDivisionError: division by zero") ```
8,616,617
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'Hello Exception!',) gm.setLevel(logging.ERROR) logger.addHandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0 ``` It took more than 1sec to complete, blocking the python script for this whole time. How come? How can I make it not block the script?
2011/12/23
[ "https://Stackoverflow.com/questions/8616617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348545/" ]
Here's the implementation I'm using, which I based on [this Gmail adapted SMTPHandler](http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt). I took the part that sends to SMTP and placed it in a different thread. ``` import logging.handlers import smtplib from threading import Thread def smtp_at_your_own_leasure(mailhost, port, username, password, fromaddr, toaddrs, msg): smtp = smtplib.SMTP(mailhost, port) if username: smtp.ehlo() # for tls add this line smtp.starttls() # for tls add this line smtp.ehlo() # for tls add this line smtp.login(username, password) smtp.sendmail(fromaddr, toaddrs, msg) smtp.quit() class ThreadedTlsSMTPHandler(logging.handlers.SMTPHandler): def emit(self, record): try: import string # for tls add this line try: from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport if not port: port = smtplib.SMTP_PORT msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, string.join(self.toaddrs, ","), self.getSubject(record), formatdate(), msg) thread = Thread(target=smtp_at_your_own_leasure, args=(self.mailhost, port, self.username, self.password, self.fromaddr, self.toaddrs, msg)) thread.start() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) ``` Usage example: ``` logger = logging.getLogger() gm = ThreadedTlsSMTPHandler(("smtp.gmail.com", 587), 'bugs@my_company.com', ['admin@my_company.com'], 'Error found!', ('my_company_account@gmail.com', 'top_secret_gmail_password')) gm.setLevel(logging.ERROR) logger.addHandler(gm) try: 1/0 except: logger.exception('FFFFFFFFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUU-') ```
Most probably you need to write your own logging handler that would do the sending of the email in the background.