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
7,550,823
I've caught myself using this in place of a traditional for loop: ``` _.each(_.range(count), function(i){ ... }); ``` The disadvantage being creating an unnecessary array of size count. Still, i prefer the semantics of, for example, *.each(*.range(10,0,-1), ...); when iterating backwards. Is there any way to do a lazy iteration over range, as with pythons xrange?
2011/09/26
[ "https://Stackoverflow.com/questions/7550823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374943/" ]
Considering the [source of underscore.js](http://documentcloud.github.com/underscore/underscore.js) says the following about `range`: > > Generate an integer Array containing an arithmetic progression > > > I doubt there is a way to do lazy iteration without modifying the source.
If you don't mind getting your hands dirty, dig into the sources of the older but stable and feature-complete [MochiKit](http://mochi.github.com/mochikit/)'s [Iter](http://mochi.github.com/mochikit/doc/html/MochiKit/Iter.html) module. It tries to create something along the lines of Python's [itertools](http://docs.python.org/library/itertools.html#module-itertools).
7,550,823
I've caught myself using this in place of a traditional for loop: ``` _.each(_.range(count), function(i){ ... }); ``` The disadvantage being creating an unnecessary array of size count. Still, i prefer the semantics of, for example, *.each(*.range(10,0,-1), ...); when iterating backwards. Is there any way to do a lazy iteration over range, as with pythons xrange?
2011/09/26
[ "https://Stackoverflow.com/questions/7550823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374943/" ]
Considering the [source of underscore.js](http://documentcloud.github.com/underscore/underscore.js) says the following about `range`: > > Generate an integer Array containing an arithmetic progression > > > I doubt there is a way to do lazy iteration without modifying the source.
Just a note: ``` _.each(_.range(count), function(i){ ... }); ``` is equivalent to ``` _.times(count, function(i){ ... }); ``` small is beautiful...
23,175,165
In python, I am trying to check if a given list of values is currently sorted in increasing order and if there are adjacent duplicates in the list. If there are, the code should return True. I am not sure why this code does not work. Any ideas? Thanks in advance!! ``` def main(): values = [1, 4, 9, 16, 25] print("Return true if list is currently sorted in increasing order: ", increasingorder(values)) print("Return true if list contains two adjacent duplicate elements: ", twoadjacentduplicates(values)) def increasingorder(values): hlist = values a = hlist.sort() if a == hlist: return True else: return False def twoadjacentduplicates(values): ilist = values true = 0 for i in range(1, len(ilist)-1): if ilist[i] == ilist[i - 1] or ilist[i] == ilist[i + 1] : true = true + 1 if true == 0: return False if true > 0: return True main() ```
2014/04/19
[ "https://Stackoverflow.com/questions/23175165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3495872/" ]
Your `increasingorder` function will almost certainly not work, because Python uses references, and the `sort` function modifies a list in-place and returns `None`. That means that after your call `a = hlist.sort()`, both `hlist` will be sorted and `a` will be `None`. so they will not compare equal. You probably meant to do the following, which will return a sorted list instead. ``` a = sorted(hlist) ``` This function works: ``` def increasingorder(values): hlist = values a = sorted(hlist) if a == hlist: return True else: return False ``` You can of course simplify this down to a single line. ``` def increasingorder(values): return sorted(values) == values ``` Your second function looks logically correct, but can be simplified down to the following. ``` def twoadjacentduplicates(values): for i in range(0, len(values)-1): if values[i] == values[i + 1] : return True return False ```
Try creating a True False function for each value check operation you want done taking the list as a parameter. then call each function like "if 1 and 2 print 3" format. That may make thinking through the flow a little easier. Is this kind of what you were wanting? ``` def isincreasing(values): if values==sorted(values): return True return False def has2adjdup(values): for x in range(len(values)-1): if values[x]==values[x+1]: return True return False if isincreasing(values) and has2adjdup(values): print "True" ```
20,529,457
Please excuse this naive question of mine. I am trying to monitor memory usage of my python code, and have come across the promising [`memory_profiler`](https://pypi.python.org/pypi/memory_profiler) package. I have a question about interpreting the output generated by @profile decorator. Here is a sample output that I get by running my dummy code below: **dummy.py** ``` from memory_profiler import profile @profile def my_func(): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7) del b return a if __name__ == '__main__': my_func() ``` Calling dummy.py by "python dummy.py" returns the table below. Line # Mem usage Increment Line Contents ======================================== ``` 3 8.2 MiB 0.0 MiB @profile 4 def my_func(): 5 15.8 MiB 7.6 MiB a = [1] * (10 ** 6) 6 168.4 MiB 152.6 MiB b = [2] * (2 * 10 ** 7) 7 15.8 MiB -152.6 MiB del b 8 15.8 MiB 0.0 MiB return a ``` My question is what does the 8.2 MiB in the first line of the table correspond to. My guess is that it is the initial memory usage by the python interpreter itself; but I am not sure. If that is the case, is there a way to have this baseline usage automatically subtracted from the memory usage of the script? Many thanks for your time and consideration! Noushin
2013/12/11
[ "https://Stackoverflow.com/questions/20529457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1146372/" ]
According to [the docs](https://pypi.python.org/pypi/memory_profiler): > > The first column represents the line number of the code that has been profiled, the second column (Mem usage) the memory usage of the Python interpreter after that line has been executed. The third column (Increment) represents the difference in memory of the current line with respect to the last one. > > > So, that 8.2 MiB is the memory usage after the first line has been executed. That includes the memory needed to start up Python, load your script and all of its imports (including `memory_profiler` itself), and so on. There don't appear to be any documented options for removing that from each entry. But it wouldn't be too hard to post-process the results. Alternatively, do you really need to do that? The third column shows how much additional memory has been used after each line, and either that, or the sum of that across a range of lines, seems more interesting than the difference between each line's second column and the start.
The difference in memory between lines is given in the second column or you could write a small script to process the output.
67,395,047
I have written several python scripts that will backtest trading strategies. I am attempting to deploy these through docker compose. The feeder container copies test files to a working directory where the backtester containers will pick them up and process them. The processed test files are then sent to a "completed work" folder. Some CSV files that the backtester outputs are then written to an NFS share on another computer. I should mention that this is all running on Ubuntu 20.04. As far as I can tell everything should be working, but for some reason the "docker-compose up" command hangs up on "Attaching to". There should be further output with print statements (I've unbuffered the Dockerfiles so those should show up). I've also left it running for a while to see if anything was getting processed and it looks like the containers never started up. I've looked at all the other threads dealing with this and have not found a solution that has worked to resolve this. Any insight is very very appreciated. Thanks. Here is the docker-compose file: ``` version: '3.4' services: feeder: image: feeder build: context: . dockerfile: ./Dockerfile.feeder volumes: - /home/danny/io:/var/lib/io worker1: image: backtester build: context: . dockerfile: ./Dockerfile volumes: - /home/danny/io/input/workers/worker1:/var/lib/io/input - /home/danny/io/input/completedwork:/var/lib/io/archive - /nfs/tests:/var/lib/tests worker2: image: backtester build: context: . dockerfile: ./Dockerfile volumes: - /home/danny/io/input/workers/worker2:/var/lib/io/input - /home/danny/io/input/completedwork:/var/lib/io/archive - /nfs/tests:/var/lib/tests worker3: image: backtester build: context: . dockerfile: ./Dockerfile volumes: - /home/danny/io/input/workers/worker3:/var/lib/io/input - /home/danny/io/input/completedwork:/var/lib/io/archive - /nfs/tests:/var/lib/tests ``` Here is the Dockerfile for the backtester: ``` # For more information, please refer to https://aka.ms/vscode-docker-python FROM python:3.8-slim-buster # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # Install pip requirements COPY requirements.txt . RUN python -m pip install -r requirements.txt WORKDIR /app COPY . /app # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers # RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app # USER appuser # During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug CMD ["python", "backtester5.py"] ``` Here is the Dockerfile for the feeder: ``` # For more information, please refer to https://aka.ms/vscode-docker-python FROM python:3.8-slim-buster # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # Install pip requirements COPY requirements.txt . RUN python -m pip install -r requirements.txt WORKDIR /app COPY . /app # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers # RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app # USER appuser # During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug CMD ["python", "feeder.py"] ``` Here is the last message that shows up: ``` Attaching to project4_feeder_1, project4_worker1_1, project4_worker2_1, project4_worker3_1 ```
2021/05/05
[ "https://Stackoverflow.com/questions/67395047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15838493/" ]
It's been three weeks with no responses, but I just wanted to update with what I've found. In all cases where I've left "docker-compose up" running it eventually started. At times it took 30 minutes, but it started every time.
I faced the same problem and fix it with this tip: > > resolved It turns out if I run my docker command with "python3 -u" it will force python to run unbuffered. It was a buffering issue. > > > source: <https://www.reddit.com/r/docker/comments/gk262t/comment/fqos8j8/?utm_source=share&utm_medium=web2x&context=3>
15,152,174
I am using python version 3. For homework, I am trying to allow five digits of input from the user, then find the average of those digits. I have figured that part out (spent an hour learning about the map function, very cool). The second part of the problem is to compare each individual element of the list to the average, then return the ones greater than the average. I think the "if any" at the bottom will compare the numbers in the list to the Average, but I have no idea how to pull that value out to print it. You guys rock for all the help. ``` #Creating a list my_numbers = [input("Enter a number: ") for i in range(5)] #Finding sum Total = sum(map(int, my_numbers)) #Finding the average Average = Total/5 print ("The average is: ") print (Average) print ("The numbers greater than the average are: ") if any in my_numbers > Average: ```
2013/03/01
[ "https://Stackoverflow.com/questions/15152174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2121886/" ]
you can add your custom class with your own css property like below ``` $this->addElement(new Zend_Form_Element_Button( 'send', array( 'label' => 'registrieren', 'class' => 'button-red', 'type' => 'submit', 'escape' => false, 'required' => false, 'ignore' => false, ) )); ```
Yes just apply the appropriate CSS to the 'div', 'tag' or 'class' as required. [22 CSS Button Styling Tutorials and Techniques](http://speckyboy.com/2009/05/27/22-css-button-styling-tutorials-and-techniques/) may help.
2,683,810
I'd ideally like a vim answer to this: I want to change ``` [*, 1, *, *] to [*, 2, *, *] ``` Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example ``` [0, 1, 0, 1] to [0, 2, 0, 1] [1, 1, 1, 1] to [1, 2, 1, 1] ``` If people know how to do this in perl or python or whatever, that would be equally good. Cheers
2010/04/21
[ "https://Stackoverflow.com/questions/2683810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194675/" ]
The following should do what you want: ``` :%s/\(\[[^,]*, *\)\(\d\)\([^]]*\]\)/\=submatch(1) . (submatch(2)+1) . submatch(3)/ ``` In Vim, that is.
If those are strings in Python ``` >>> a = "[0, 1, 0, 1]" >>> b = a[:4] + '2' + a[5:] >>> b '[0, 2, 0, 1]' ``` Lists are a little more trivial: ``` >>> c = [0, 1, 0, 1] >>> c[1] = 2 >>> c [0, 2, 0, 1] >>> ```
2,683,810
I'd ideally like a vim answer to this: I want to change ``` [*, 1, *, *] to [*, 2, *, *] ``` Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example ``` [0, 1, 0, 1] to [0, 2, 0, 1] [1, 1, 1, 1] to [1, 2, 1, 1] ``` If people know how to do this in perl or python or whatever, that would be equally good. Cheers
2010/04/21
[ "https://Stackoverflow.com/questions/2683810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194675/" ]
This works :) ``` 1,$s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/g ``` or ``` %s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/ ```
The following should do what you want: ``` :%s/\(\[[^,]*, *\)\(\d\)\([^]]*\]\)/\=submatch(1) . (submatch(2)+1) . submatch(3)/ ``` In Vim, that is.
2,683,810
I'd ideally like a vim answer to this: I want to change ``` [*, 1, *, *] to [*, 2, *, *] ``` Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example ``` [0, 1, 0, 1] to [0, 2, 0, 1] [1, 1, 1, 1] to [1, 2, 1, 1] ``` If people know how to do this in perl or python or whatever, that would be equally good. Cheers
2010/04/21
[ "https://Stackoverflow.com/questions/2683810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194675/" ]
The following should do what you want: ``` :%s/\(\[[^,]*, *\)\(\d\)\([^]]*\]\)/\=submatch(1) . (submatch(2)+1) . submatch(3)/ ``` In Vim, that is.
This one is shorter and a little more general purpose. ``` :%s/\(\[[^,],\s*\)1,/\12,/ ``` The pattern doesn't care what is in the first slot of the list, and doesn't look at the rest of the list. This may be better, or worse, depending on what exactly you're trying to do.
2,683,810
I'd ideally like a vim answer to this: I want to change ``` [*, 1, *, *] to [*, 2, *, *] ``` Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example ``` [0, 1, 0, 1] to [0, 2, 0, 1] [1, 1, 1, 1] to [1, 2, 1, 1] ``` If people know how to do this in perl or python or whatever, that would be equally good. Cheers
2010/04/21
[ "https://Stackoverflow.com/questions/2683810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194675/" ]
The following should do what you want: ``` :%s/\(\[[^,]*, *\)\(\d\)\([^]]*\]\)/\=submatch(1) . (submatch(2)+1) . submatch(3)/ ``` In Vim, that is.
Note while using regexes for substitutions/modifications it is important to focus around the portion of the string you want to modify. Here is a short regex to do what you want (in perl), that illustrates this idea with your data. Assuming $line contains the line you want to modify ``` my $two=2; $line =~ s/(,\s+)\d+/\1$two/; ``` The regex looks for the first comma, matches that and a arbitary number of spaces following the comma. This is remembered in the first back reference. After that it matches a arbitary number of digits. Finally it replaces what was matched by the string in the first backreference followed by 2. Applying this on your sample data gives [0, 1, 0, 1] becomes [0, 2, 0, 1] [1, 1, 1, 1] becomes [1, 2, 1, 1]
2,683,810
I'd ideally like a vim answer to this: I want to change ``` [*, 1, *, *] to [*, 2, *, *] ``` Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example ``` [0, 1, 0, 1] to [0, 2, 0, 1] [1, 1, 1, 1] to [1, 2, 1, 1] ``` If people know how to do this in perl or python or whatever, that would be equally good. Cheers
2010/04/21
[ "https://Stackoverflow.com/questions/2683810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194675/" ]
This works :) ``` 1,$s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/g ``` or ``` %s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/ ```
If those are strings in Python ``` >>> a = "[0, 1, 0, 1]" >>> b = a[:4] + '2' + a[5:] >>> b '[0, 2, 0, 1]' ``` Lists are a little more trivial: ``` >>> c = [0, 1, 0, 1] >>> c[1] = 2 >>> c [0, 2, 0, 1] >>> ```
2,683,810
I'd ideally like a vim answer to this: I want to change ``` [*, 1, *, *] to [*, 2, *, *] ``` Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example ``` [0, 1, 0, 1] to [0, 2, 0, 1] [1, 1, 1, 1] to [1, 2, 1, 1] ``` If people know how to do this in perl or python or whatever, that would be equally good. Cheers
2010/04/21
[ "https://Stackoverflow.com/questions/2683810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194675/" ]
This works :) ``` 1,$s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/g ``` or ``` %s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/ ```
This one is shorter and a little more general purpose. ``` :%s/\(\[[^,],\s*\)1,/\12,/ ``` The pattern doesn't care what is in the first slot of the list, and doesn't look at the rest of the list. This may be better, or worse, depending on what exactly you're trying to do.
2,683,810
I'd ideally like a vim answer to this: I want to change ``` [*, 1, *, *] to [*, 2, *, *] ``` Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example ``` [0, 1, 0, 1] to [0, 2, 0, 1] [1, 1, 1, 1] to [1, 2, 1, 1] ``` If people know how to do this in perl or python or whatever, that would be equally good. Cheers
2010/04/21
[ "https://Stackoverflow.com/questions/2683810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194675/" ]
This works :) ``` 1,$s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/g ``` or ``` %s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/ ```
Note while using regexes for substitutions/modifications it is important to focus around the portion of the string you want to modify. Here is a short regex to do what you want (in perl), that illustrates this idea with your data. Assuming $line contains the line you want to modify ``` my $two=2; $line =~ s/(,\s+)\d+/\1$two/; ``` The regex looks for the first comma, matches that and a arbitary number of spaces following the comma. This is remembered in the first back reference. After that it matches a arbitary number of digits. Finally it replaces what was matched by the string in the first backreference followed by 2. Applying this on your sample data gives [0, 1, 0, 1] becomes [0, 2, 0, 1] [1, 1, 1, 1] becomes [1, 2, 1, 1]
30,083,603
Alright here's a question that's eating me from inside so any help is appreciated. I have a web service that returns a list of items. The number of items returned is governed by two variables 'page' and 'per\_page'. So a URL like ``` abc.com?page=10&per_page=100 ``` Will show the 10th page with 100 items in it. I have to query this service efficiently and only get items that were added after the last fetch. So say I have cached all the items upto #1024 and then 12 more items were added to it making the count 1036. How do I calculate the page and per\_page value so that I get all the added items in a single page while keeping the per\_page qunatity to be as close to the newly added items as possible. For eg: in this case the per\_page should be as close to but no less than 12. I already know the last count of cache and the current total number of items. Its okay if the fetched page has the previously cached items. I am trying to find the most optimum response and not the most accurate. The language I am using is python but just an algorithm or psuedo-code would be very welcome. Note: the service gives me the earliest items first. So the latest entries are always added to the last page
2015/05/06
[ "https://Stackoverflow.com/questions/30083603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4484709/" ]
Is there a compelling reason to not over-request? `abc.com?page=2&per_page=1024` Just always set `page=2` and `per_page` = number of items cached. The only weird case is when the number of added elements is greater than the number of items cached, in which case you have to `abc.com?page=1&per_page=99999`
Here's the code with a small bug-fix to give the most optimal page size (the suggested code wouldn't return a page size that exactly divides the total count). ``` def items_per_page(total_item_count,new_item_count): for i in itertools.count(new_item_count): if total_items % i>= new_item_count or total_items %i == 0: return i total_count = 136 #including the new items new_count = 12 ct_per_page = items_per_page(total_count,new_count) page_num = total_count//ct_per_page + 1 # the last page print my_url+"?page="+page_num+"&per_page="+ct_per_page ```
30,083,603
Alright here's a question that's eating me from inside so any help is appreciated. I have a web service that returns a list of items. The number of items returned is governed by two variables 'page' and 'per\_page'. So a URL like ``` abc.com?page=10&per_page=100 ``` Will show the 10th page with 100 items in it. I have to query this service efficiently and only get items that were added after the last fetch. So say I have cached all the items upto #1024 and then 12 more items were added to it making the count 1036. How do I calculate the page and per\_page value so that I get all the added items in a single page while keeping the per\_page qunatity to be as close to the newly added items as possible. For eg: in this case the per\_page should be as close to but no less than 12. I already know the last count of cache and the current total number of items. Its okay if the fetched page has the previously cached items. I am trying to find the most optimum response and not the most accurate. The language I am using is python but just an algorithm or psuedo-code would be very welcome. Note: the service gives me the earliest items first. So the latest entries are always added to the last page
2015/05/06
[ "https://Stackoverflow.com/questions/30083603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4484709/" ]
so start with the knowledge that you need to have `per_page` at least equal to the number of new items (assuming you want them all on the same page) ``` def items_per_page(total_item_count,new_item_count): for i in itertools.count(new_item_count): if total_items % i>= new_item_count: return i total_count = 136 #including the new items new_count = 12 ct_per_page = items_per_page(total_count,new_count) page_num = total_count//ct_per_page + 1 # the last page print my_url+"?page="+page_num+"&per_page="+ct_per_page ``` at least im pretty sure that will always give you an optimal result :) by optimal I mean the minimal value for `per_page`
Here's the code with a small bug-fix to give the most optimal page size (the suggested code wouldn't return a page size that exactly divides the total count). ``` def items_per_page(total_item_count,new_item_count): for i in itertools.count(new_item_count): if total_items % i>= new_item_count or total_items %i == 0: return i total_count = 136 #including the new items new_count = 12 ct_per_page = items_per_page(total_count,new_count) page_num = total_count//ct_per_page + 1 # the last page print my_url+"?page="+page_num+"&per_page="+ct_per_page ```
44,967,366
Working in python with ESRI's arcpy, I'm trying to sum values across multiple fields with an arcpy updateCursor . I'm trying to convert the None items to an 0. However, I can't figure out a way to convert the None items. I'm open to anything. ``` with arcpy.da.UpdateCursor(feature_class, score_fields) as cursor: for row in cursor: [0 if x==None else x+4 for x in row] print row row[len(score_fields)-1] = sum(row[i] for i in range(len(score_fields))) cursor.updateRow(row) ``` Returns: ``` [-4, -4, None, None, -4, None, -4, -4] ``` with error: ``` TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' ``` Thanks!
2017/07/07
[ "https://Stackoverflow.com/questions/44967366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8269863/" ]
You should update `row` by assigning the result of the list comprehension to `row`: ``` for row in cursor: row = [0 if x is None else x+4 for x in row] ``` Also, note that since there is only one `None` object, better to test with `is` than use `==`; more Pythonic, more performant.
You can use an if statement to filter the `None` values in your list: ``` sum(row[i] for i in range(len(score_fields)) if row[i] is not None) ```
7,720,435
What is the best way to implement a tree structure (generic - not binary) in python? My intuition would have the following skeleton: ``` class TNode(self, data): #enter things for each individual node class TStructure(self): #enter code for implementing nodes that reference each other. ```
2011/10/11
[ "https://Stackoverflow.com/questions/7720435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/382906/" ]
Any function which is going to be inlined must have its full source in the .di file. Any function which is going to be used in CTFE must not only have its full source in the .di file, but the full source of every function that it uses - directly or indirectly - must be available to the compiler. Also, because of how templates work, their full source must be in the .di file as well (which is the same as how templates must be in header files in C++). So, there are a number of cases where you *need* stuff to be in a .di file. Under exactly what circumstances the compiler chooses to strip stuff or not, I don't know (aside from the fact that templates automatically end up in .di files in their entirety because they *have* to). It could change depending on the compiler's current implementation and what optimizations it does. But at minimum, it's going to have to leave in small function bodies if it's going to do any inlining. Large function bodies and the bodies of small virtual functions (which can't be inlined anyway) will likely be stripped out however. But your example gives a small, non-virtual function, so dmd likely left it in so that it could inline any calls to it. If you want to see dmd strip a lot of stuff when generating a .di file, then you probably need to have large functions and/or use classes.
> > Hardly a paragon of optimization. > > > No, that **is** an optimization. The compiler will leave the implementation in the interface file if the implementation is small enough that it can later be inlined.
69,255,736
`TypeError: unsupported operand type(s) for /: 'str' and 'float'` I'm making a football game, and I get this whenever I try to run the following code to determine how far a play will go. `playdistance = round(random.uniform(float(rbs.get(possession)[-2:]/float(30.0))-2.5,float(rbs.get(possession)[-2:]/float(30.0))+5.5))` "rbs" is a dictionary containing all of the teams' running backs and overall stored like `'NYG':'Saquon Barkley 99'` where it contains the name and then how good that player is on a scale from 0-99. I stored it like this so that I can use [-2:] to get how good the player is, and [:-2] to get the name of the player. "possession" is the team that has the ball, so that I can pull the running back's name and skill from the dictionary previously mentioned. What I'm confused about is how I'm getting the previously mentioned error when both of the arguments in the division are floats, and neither are strings. I've tried converting the 30 divisor into a string, a float, and I've also done that for the first argument. I'm sure this is a pretty dumb question as I am pretty new to coding and python, but if someone could help me out that would be awesome.
2021/09/20
[ "https://Stackoverflow.com/questions/69255736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16957998/" ]
You can't combine strings and numbers like that in Python. `rbs.get(possession)[-2:]` gives you a string, e.g. `'99'`, and `float(30.0)` gives you a number. The division of strings by numbers is not defined. You must convert the '99' to a number first before you can divide it by anything. Technically speaking, you only need to switch the parentheses around in your expression. Broken: ``` round(random.uniform(float(rbs.get(possession)[-2:]/float(30.0))-2.5,float(rbs.get(possession)[-2:]/float(30.0))+5.5)) ``` Working: ``` round(random.uniform(float(rbs.get(possession)[-2:])/float(30.0)-2.5,float(rbs.get(possession)[-2:])/float(30.0)+5.5)) ``` but practically speaking, use variables. The stuff above is all but unreadable. ``` player_rating = float(rbs.get(possession)[-2:]) low = player_rating / 30 - 2.5 high = player_rating / 30 + 5.5 playdistance = round(random.uniform(low, high)) ``` Also, once a variable in a calculation is a float, such as `player_rating` here, the *entire calculation* will yield a float. Things like `float(30.0)` are completely unnecessary.
When I indent your code to make it more readable, the problem becomes evident ``` playdistance = round( random.uniform( float( rbs.get(possession)[-2:] / float(30.0) # error 1 ) - 2.5, float( rbs.get(possession)[-2:] / float(30.0) # error 2 ) + 5.5 ) ) ``` `rbs.get(possession)[-2:]` is a string. I see you're *trying* to convert it to a float, but that needs to be done with ``` float(rbs.get(possession)[-2:]) / float(30.0) - 2.5 # ^ ``` not ``` float(rbs.get(possession)[-2:] / float(30.0)) - 2.5 # ^ ``` There's no need to parenthesize the division, because `/` has higher precedence than `-` (remember your order of operations)
69,255,736
`TypeError: unsupported operand type(s) for /: 'str' and 'float'` I'm making a football game, and I get this whenever I try to run the following code to determine how far a play will go. `playdistance = round(random.uniform(float(rbs.get(possession)[-2:]/float(30.0))-2.5,float(rbs.get(possession)[-2:]/float(30.0))+5.5))` "rbs" is a dictionary containing all of the teams' running backs and overall stored like `'NYG':'Saquon Barkley 99'` where it contains the name and then how good that player is on a scale from 0-99. I stored it like this so that I can use [-2:] to get how good the player is, and [:-2] to get the name of the player. "possession" is the team that has the ball, so that I can pull the running back's name and skill from the dictionary previously mentioned. What I'm confused about is how I'm getting the previously mentioned error when both of the arguments in the division are floats, and neither are strings. I've tried converting the 30 divisor into a string, a float, and I've also done that for the first argument. I'm sure this is a pretty dumb question as I am pretty new to coding and python, but if someone could help me out that would be awesome.
2021/09/20
[ "https://Stackoverflow.com/questions/69255736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16957998/" ]
When I indent your code to make it more readable, the problem becomes evident ``` playdistance = round( random.uniform( float( rbs.get(possession)[-2:] / float(30.0) # error 1 ) - 2.5, float( rbs.get(possession)[-2:] / float(30.0) # error 2 ) + 5.5 ) ) ``` `rbs.get(possession)[-2:]` is a string. I see you're *trying* to convert it to a float, but that needs to be done with ``` float(rbs.get(possession)[-2:]) / float(30.0) - 2.5 # ^ ``` not ``` float(rbs.get(possession)[-2:] / float(30.0)) - 2.5 # ^ ``` There's no need to parenthesize the division, because `/` has higher precedence than `-` (remember your order of operations)
That fixes your problem where you need to convert to `float` before your divided ``` import numpy rbs={'NYG':'Saquon Barkley 99' } playdistance = float(round(numpy.random.uniform(float(rbs.get(possession)[-2:])/float(30.0)-2.5,float(rbs.get(possession)[-2:])/float(30.0))+5.5)) print(playdistance) ```
69,255,736
`TypeError: unsupported operand type(s) for /: 'str' and 'float'` I'm making a football game, and I get this whenever I try to run the following code to determine how far a play will go. `playdistance = round(random.uniform(float(rbs.get(possession)[-2:]/float(30.0))-2.5,float(rbs.get(possession)[-2:]/float(30.0))+5.5))` "rbs" is a dictionary containing all of the teams' running backs and overall stored like `'NYG':'Saquon Barkley 99'` where it contains the name and then how good that player is on a scale from 0-99. I stored it like this so that I can use [-2:] to get how good the player is, and [:-2] to get the name of the player. "possession" is the team that has the ball, so that I can pull the running back's name and skill from the dictionary previously mentioned. What I'm confused about is how I'm getting the previously mentioned error when both of the arguments in the division are floats, and neither are strings. I've tried converting the 30 divisor into a string, a float, and I've also done that for the first argument. I'm sure this is a pretty dumb question as I am pretty new to coding and python, but if someone could help me out that would be awesome.
2021/09/20
[ "https://Stackoverflow.com/questions/69255736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16957998/" ]
You can't combine strings and numbers like that in Python. `rbs.get(possession)[-2:]` gives you a string, e.g. `'99'`, and `float(30.0)` gives you a number. The division of strings by numbers is not defined. You must convert the '99' to a number first before you can divide it by anything. Technically speaking, you only need to switch the parentheses around in your expression. Broken: ``` round(random.uniform(float(rbs.get(possession)[-2:]/float(30.0))-2.5,float(rbs.get(possession)[-2:]/float(30.0))+5.5)) ``` Working: ``` round(random.uniform(float(rbs.get(possession)[-2:])/float(30.0)-2.5,float(rbs.get(possession)[-2:])/float(30.0)+5.5)) ``` but practically speaking, use variables. The stuff above is all but unreadable. ``` player_rating = float(rbs.get(possession)[-2:]) low = player_rating / 30 - 2.5 high = player_rating / 30 + 5.5 playdistance = round(random.uniform(low, high)) ``` Also, once a variable in a calculation is a float, such as `player_rating` here, the *entire calculation* will yield a float. Things like `float(30.0)` are completely unnecessary.
That fixes your problem where you need to convert to `float` before your divided ``` import numpy rbs={'NYG':'Saquon Barkley 99' } playdistance = float(round(numpy.random.uniform(float(rbs.get(possession)[-2:])/float(30.0)-2.5,float(rbs.get(possession)[-2:])/float(30.0))+5.5)) print(playdistance) ```
12,948,935
``` $ ps aux | grep file1.py xyz 6103 0.0 0.1 33476 6480 pts/1 S+ 12:00 0:00 python file1.py xyz 6188 0.0 0.1 33476 6472 pts/2 S+ 12:05 0:00 python file1.py xyz 7294 0.0 0.0 8956 872 pts/4 S+ 12:49 0:00 grep --color=auto file1.py ``` process 6103 has started at 12:00 and after 5 minutes process 6188 started. I need to find out both the processes 6103,6188 pid\_finder.py ============== ``` import psutil PROCNAME = "file1.py" process = [] for proc in psutil.process_iter(): if proc.name == PROCNAME: print proc ``` But the above script printed out nothing. can "psutil" module have other option to find pid of the process of a script. psutil.test() gave following o/p... ``` xyz 6103 0.0 0.2 33476 6480 /dev/pts/1 13:23 30:00 python xyz 6188 0.0 0.2 33476 6480 /dev/pts/2 13:23 30:00 python xyz 8831 0.0 1.0 430612 39796 ? 13:31 30:03 gedit xyz 8833 0.0 ? 14540 808 ? 13:31 30:00 gnome-pty-helper xyz 8835 0.0 0.1 23636 5008 /dev/pts/5 13:31 30:00 bash xyz 9367 0.0 0.2 51580 7740 /dev/pts/4 13:42 30:00 python ```
2012/10/18
[ "https://Stackoverflow.com/questions/12948935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1051068/" ]
What about something like this, if you are not worried of the **os.popen()** ``` #!/usr/bin/python import os PROCNAME = "file1.py" pids = [] for proc_data in os.popen('/bin/ps -eo pid,comm,args'): bits = proc_data.strip().split() (pid, comm ) = bits[0:2] args = " ".join( bits[3:] ) if args == PROCNAME: pids.append( pid ) print pids ``` This should let you find things base on the args of the process. You could change it so that comm and args where the one string if required. ``` pid = bits[0] comm_and_args = " ".join( bits[1:] ) ```
please read up on `pidof`: ``` man pidof ```
58,461,785
While studying data types in Python, I encountered a data type range and used a variable to define it. However using type function to know about this still tells that it's a list data types. Am I missing something here? Please guide. Thank you so much. ``` x = range(3) print(type(x)) ``` Output is as shown below: ``` C:\Python27>python.exe learn.py <type 'list'> ```
2019/10/19
[ "https://Stackoverflow.com/questions/58461785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8808220/" ]
It seems you are mixing up Python 3 and 2. These are two major versions of Python. Python 3000 introduced many intentionally backwards incompatible changes including in the workings of the range function. In Python 2, the range function immediately expanded out to a list `list_range = list(range(3))` In Python 3 it is just a mapping to the range data type. Check the official docs here [<https://docs.python.org/3.0/whatsnew/3.0.html]> It is something to do with memory.
With Python2, range returned the list. If you try to run your code with python3, it returns the 'range' type as a output of your code.
2,913,626
I need to parse a string `'Open URN: 100000 LA: '` and get 100000 from it. on python regexp `(?<=Open URN: )[0-9]+(?= LA:)` works fine but in php it gives following error: ``` preg_match(): Unknown modifier '[' ``` I need it working php, so please help me to solve this problem and tell about difference in python and php regexps.
2010/05/26
[ "https://Stackoverflow.com/questions/2913626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/350981/" ]
You have to use [delimiters](http://www.php.net/manual/en/regexp.reference.delimiters.php) when you are using the [*Perl Compatible Regular Expressions* (PCRE) functions](http://www.php.net/manual/en/book.pcre.php) in PHP (to which [`preg_match()`](http://php.net/manual/en/function.preg-match.php) belongs). From the [documentation](http://www.php.net/manual/en/regexp.reference.delimiters.php): > > When using the PCRE functions, it is required that the pattern is enclosed by ***delimiters***. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. > > > The reason for using delimiters is that you can add [**pattern modifiers**](http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php) after the last delimiter, e.g. to make an case-insensitive match: ``` #[a-z]#i // # is the delimiter. ``` --- **Back to your problem:** In your case, PHP thinks the brackets `()` are your delimiters (yes, opening and closing brackets are valid delimiters, see the [documentation](http://www.php.net/manual/en/regexp.reference.delimiters.php)) and `?<=Open URN:` is your pattern . Then it encounters `[` and treats it as [pattern modifier](http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php), but it is not a valid one. Your pattern with delimiter `%`: ``` preg_match('%(?<=Open URN: )[0-9]+(?= LA:)%', 'Open URN: 100000 LA: '); ``` There are a lot examples in the [documentation of `preg_match()`](http://php.net/manual/en/function.preg-match.php) --- **Python vs PHP** The only thing I found regarding regular expressions in Python is, that [Perl syntax is used](http://docs.python.org/howto/regex.html#regex-howto) but I don't know if the full syntax is supported. As already mentioned, PHP uses PCRE. [Description of the differences between PCRE and Perl regex.](http://www.php.net/manual/en/reference.pcre.pattern.differences.php)
Except of mentioned differences I found one more. re.match(r"\s", "a b") in python with preg\_match("/\s/", "a b"), the first doesn't return matches in python while the second will find space symbol. I didn't find why in official docs, it's hard to understand but it's a fact.
22,286,332
I am parsing log files in size of 1 to 10GB using python3.2, need to search for line with specific regex (some kind of timestamp), and I want to find the last occurance. I have tried to use: ``` for line in reversed(list(open("filename"))) ``` which resulted in very bad performance (in the good cases) and MemoryError in the bad cases. In thread: [Read a file in reverse order using python](https://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python) i did not find any good answer. I have found the following solution: [python head, tail and backward read by lines of a text file](https://stackoverflow.com/questions/5896079/python-head-tail-and-backward-read-by-lines-of-a-text-file/5896210#5896210) very promising, however it does not work for python3.2 for error: ``` NameError: name 'file' is not defined ``` I had later tried to replace `File(file)` with `File(TextIOWrapper)` as this is the object builtin function `open()` returns, however that had resulted in several more errors (i can elaborate if someone suggest this is the right way:))
2014/03/09
[ "https://Stackoverflow.com/questions/22286332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3399166/" ]
Looks like you have mistake in code: ``` echo $row['PersonnelD']; ``` shouldn't it be following? ``` echo $row['PersonnelID']; ```
check the mysql\_fetch\_assoc() function may be its parameter is empty so it can't enter the while loop
22,286,332
I am parsing log files in size of 1 to 10GB using python3.2, need to search for line with specific regex (some kind of timestamp), and I want to find the last occurance. I have tried to use: ``` for line in reversed(list(open("filename"))) ``` which resulted in very bad performance (in the good cases) and MemoryError in the bad cases. In thread: [Read a file in reverse order using python](https://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python) i did not find any good answer. I have found the following solution: [python head, tail and backward read by lines of a text file](https://stackoverflow.com/questions/5896079/python-head-tail-and-backward-read-by-lines-of-a-text-file/5896210#5896210) very promising, however it does not work for python3.2 for error: ``` NameError: name 'file' is not defined ``` I had later tried to replace `File(file)` with `File(TextIOWrapper)` as this is the object builtin function `open()` returns, however that had resulted in several more errors (i can elaborate if someone suggest this is the right way:))
2014/03/09
[ "https://Stackoverflow.com/questions/22286332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3399166/" ]
check the mysql\_fetch\_assoc() function may be its parameter is empty so it can't enter the while loop
In both your querys, you have ``` "SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'" ``` It should be: ``` "SELECT * FROM validPersonnel WHERE Passkey = '".$password."' and Name = '".$name."';" ``` PHP doesn't recognize the $var unless you close the quotes. The period adds the $var to the string.
22,286,332
I am parsing log files in size of 1 to 10GB using python3.2, need to search for line with specific regex (some kind of timestamp), and I want to find the last occurance. I have tried to use: ``` for line in reversed(list(open("filename"))) ``` which resulted in very bad performance (in the good cases) and MemoryError in the bad cases. In thread: [Read a file in reverse order using python](https://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python) i did not find any good answer. I have found the following solution: [python head, tail and backward read by lines of a text file](https://stackoverflow.com/questions/5896079/python-head-tail-and-backward-read-by-lines-of-a-text-file/5896210#5896210) very promising, however it does not work for python3.2 for error: ``` NameError: name 'file' is not defined ``` I had later tried to replace `File(file)` with `File(TextIOWrapper)` as this is the object builtin function `open()` returns, however that had resulted in several more errors (i can elaborate if someone suggest this is the right way:))
2014/03/09
[ "https://Stackoverflow.com/questions/22286332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3399166/" ]
check the mysql\_fetch\_assoc() function may be its parameter is empty so it can't enter the while loop
Try to debug and check the values came in the variables using `var_dump()` function. Ex: `var_dump($row);` in while loop.
22,286,332
I am parsing log files in size of 1 to 10GB using python3.2, need to search for line with specific regex (some kind of timestamp), and I want to find the last occurance. I have tried to use: ``` for line in reversed(list(open("filename"))) ``` which resulted in very bad performance (in the good cases) and MemoryError in the bad cases. In thread: [Read a file in reverse order using python](https://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python) i did not find any good answer. I have found the following solution: [python head, tail and backward read by lines of a text file](https://stackoverflow.com/questions/5896079/python-head-tail-and-backward-read-by-lines-of-a-text-file/5896210#5896210) very promising, however it does not work for python3.2 for error: ``` NameError: name 'file' is not defined ``` I had later tried to replace `File(file)` with `File(TextIOWrapper)` as this is the object builtin function `open()` returns, however that had resulted in several more errors (i can elaborate if someone suggest this is the right way:))
2014/03/09
[ "https://Stackoverflow.com/questions/22286332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3399166/" ]
Looks like you have mistake in code: ``` echo $row['PersonnelD']; ``` shouldn't it be following? ``` echo $row['PersonnelID']; ```
In both your querys, you have ``` "SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'" ``` It should be: ``` "SELECT * FROM validPersonnel WHERE Passkey = '".$password."' and Name = '".$name."';" ``` PHP doesn't recognize the $var unless you close the quotes. The period adds the $var to the string.
22,286,332
I am parsing log files in size of 1 to 10GB using python3.2, need to search for line with specific regex (some kind of timestamp), and I want to find the last occurance. I have tried to use: ``` for line in reversed(list(open("filename"))) ``` which resulted in very bad performance (in the good cases) and MemoryError in the bad cases. In thread: [Read a file in reverse order using python](https://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python) i did not find any good answer. I have found the following solution: [python head, tail and backward read by lines of a text file](https://stackoverflow.com/questions/5896079/python-head-tail-and-backward-read-by-lines-of-a-text-file/5896210#5896210) very promising, however it does not work for python3.2 for error: ``` NameError: name 'file' is not defined ``` I had later tried to replace `File(file)` with `File(TextIOWrapper)` as this is the object builtin function `open()` returns, however that had resulted in several more errors (i can elaborate if someone suggest this is the right way:))
2014/03/09
[ "https://Stackoverflow.com/questions/22286332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3399166/" ]
Looks like you have mistake in code: ``` echo $row['PersonnelD']; ``` shouldn't it be following? ``` echo $row['PersonnelID']; ```
Try to debug and check the values came in the variables using `var_dump()` function. Ex: `var_dump($row);` in while loop.
38,092,236
(windows 7, python 2.7.3) Here is my code: ``` from Tkinter import * root = Tk() root.geometry('400x400') Frame(root, width=20, height=20, bg='red').pack(expand=NO, fill=None, side=LEFT) Label(root, width=20, height=20, bg='black').pack(expand=NO, fill=None, side=LEFT) root.mainloop() ``` And the result is like this: [![enter image description here](https://i.stack.imgur.com/VuQoV.png)](https://i.stack.imgur.com/VuQoV.png) I set same width and height to the Frame and Label, but they show different size. What's more, the Label is even not a square.Please explain it for me, and show me the way to make them same size.
2016/06/29
[ "https://Stackoverflow.com/questions/38092236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6032273/" ]
**Short answer:** 20 is the same as 20, but 20 meters is not the same as 20 kilometers. **Long answer:** The result you got is not as weird as you may think because the `width` and `height` options of `Tkinter.Frame()` are measured in terms of **pixels** whereas in `Tkinter.Label()`: * `width`: defines the width of the label in **characters** * `height`: defines the height of the label in **lines** [Reference.](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/label.html)
As I know Label is used for text. Label() definition and Frame() might work differently for width and height parameters, correct me if am wrong. example: change width and height inside Label() to 1. you will see space for one character filled with black color in tk window. like `Label(root, width=1, height=1, bg='black').pack(expand=NO, fill=None, side=LEFT)`
59,028,392
I have my docker containers up and running. There is one container running some python code and I found that it is causing some bug. I want to add some lines of code (mainly more logs) to a python script within that particular container. I want to just go into the container by `docker exec -ti container_name bash` and start to edit code by `nano my_python_script.py`. Does the running container pick up these changes automatically, on-the-fly? Or do I need to do something for these changes to come into effect, i.e. to print the new logging information?
2019/11/25
[ "https://Stackoverflow.com/questions/59028392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3703783/" ]
A couple of facts about docker containers: 1. Docker container lives as long as the process it runs lives usually. 2. Docker container is immutable, so whatever changes you do in filesystem of the container itself won't survive the restart of container (I'm not talking about volumes, its more advanced stuff) Based on these facts: The question basically boils down to whether the changes in `my_python_script.py` that you do "on-the-fly" requires the restart of python process. And this really depends on what/how exactly do you run the python. If it requires the restart - then no, you won't be able to see the logs. The restart won't help either, because of fact "2" - you'll lost the changes (additional log prints in this case). If Python is able to dynamically reload the script and run it **within the same process** (without the restart of the container) then you can do that.
Answering because there's some misinformation in other answers here. The correct answer is in the comment from [MyTwoCents](https://stackoverflow.com/questions/59028392/do-docker-containers-pick-up-code-changes-on-the-fly#comment104300981_59028392): > > It will behave same way as it would when you do it on your system. So if you edit nano my\_python\_script.py will it do change automatically on your system? > > > Put quite simply, if your application dynamically updates itself when the files on the filesystem change, then the same will happen when you modify those files inside of a container. --- The misinformation in Mark's answer concerns me: > > Docker container is immutable, so whatever changes you do in filesystem of the container itself won't survive the restart of container > > > **That is not accurate**. Docker images are stored as a collection of filesystem layers that are immutable. Containers are ephemeral, files changed inside the container will revert when the container is deleted and replaced with a new container. However, restarting a container effectily stops and restarts the process inside the container with the same filesystem state of that container. Any changes that happen to the container's filesystem are maintained for the life of the container. Volumes are used when you want changes to survive beyond the life of a single container. --- The correct answer is that you most likely need to restart the python process inside the container to see the filesystem changes, and stopping the python process will stop the container. It becomes an awkward process to keep `exec`'ing into a container to make changes and then exit to restart the container for the changes to appear. Therefore, a more typical developer workflow is to mount the filesystem of code into the container so you can make changes directly on your host, where those changes will not be logs, and then restart the container. Since python does not require compiling your code into a binary, you'll see your changes on every restart. If your Dockerfile contained lines like: ``` FROM python COPY . /code CMD python /code/my_python_script.py ``` You could make that a volume with: ``` docker run --name container_name -v "$(pwd):/code" image_name ``` And then to restart with changes: ``` docker restart container_name ```
17,771,131
While following a tutorial for python, I got to know that we can use *print* for a variable name, and it works fine. But after assigning the print variable, how do we get back the original print function? ``` >>> print("Hello World!!") Hello World!!! >>> print = 5 >>> print("Hi") ``` Now, the last call gives the error **TypeError: 'int' object is not callable**, since now print has the integer value 5. But, how do we get back the original functionality of print now? Should we use the class name for the print function or something? As in, `SomeClass.print("Hi")`? Thanks in advance.
2013/07/21
[ "https://Stackoverflow.com/questions/17771131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1936532/" ]
``` >>> print = 5 >>> print = __builtins__.print >>> print("hello") hello ```
You can actually delete the variable so the built-in function will work again: ``` >>> print = 5 >>> print('cabbage') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable >>> del print >>> print('cabbage') cabbage ```
17,771,131
While following a tutorial for python, I got to know that we can use *print* for a variable name, and it works fine. But after assigning the print variable, how do we get back the original print function? ``` >>> print("Hello World!!") Hello World!!! >>> print = 5 >>> print("Hi") ``` Now, the last call gives the error **TypeError: 'int' object is not callable**, since now print has the integer value 5. But, how do we get back the original functionality of print now? Should we use the class name for the print function or something? As in, `SomeClass.print("Hi")`? Thanks in advance.
2013/07/21
[ "https://Stackoverflow.com/questions/17771131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1936532/" ]
``` >>> print = 5 >>> print = __builtins__.print >>> print("hello") hello ```
If you want to use as a temp way, do them but after that, apply `print` function to `print` variable: ``` print = __builtins__.print ```
66,730,834
I have created a conda environment and activated it already. Then inside the `use_cases/` directory I execute: `pip install -e use_case_b` (<https://github.com/geoHeil/dagster-demo/tree/master/use_cases>): ``` ... ... Installing collected packages: use-case-b Attempting uninstall: use-case-b Found existing installation: use-case-b 0.0.0 Uninstalling use-case-b-0.0.0: Successfully uninstalled use-case-b-0.0.0 Running setup.py develop for use-case-b Successfully installed use-case-b ``` Now when inside the `use_cases/` directory: ``` python import use_case_b ``` works fine. When switching to a different directory like: `/` (= the root of the repository I get an error message of: ``` ModuleNotFoundError: No module named 'use_case_b' ``` Why is it working once and failing in the second place? Could it be that it is not even working in the first place and only importing the sub\_directory due to the `__init__.py` file? How can I get the python package properly install into the virtual environment? FYI: here you can find the full project <https://github.com/geoHeil/dagster-demo>
2021/03/21
[ "https://Stackoverflow.com/questions/66730834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2587904/" ]
When you get an error, please post it along with your question. When you are getting an error, it means that something is wrong with your code,and most likely not the flutter engine. Both are important for debugging, the error+your code. Try changing this ``` QuerySnapshot _getPost = await _firestore .collection('post') .doc(widget.currentUser) .collection('userPost') .orderBy('timeStamp', descending: true) .get(); setState(() { pleaseWait = true; postLenght = _getPost.docs.length; post = _getPost.docs.map((e) => Post.fromDocument(e)).toList(); print(postLenght); }); ``` into this: ``` QuerySnapshot _getPost = await _firestore .collection('post') .doc(widget.currentUser) .collection('userPost') .orderBy('timeStamp', descending: true) .get(); if(_getPost.docs.isNotEmpty){ List<Post> tempPost = _getPost.docs.map((e) => Post.fromDocument(e)).toList(); setState(() { pleaseWait = true; post =tempPost print(postLenght); }); }else{ print('The List is empty);} ``` You are not checking if the Query result has data or not. If it's empty, you will pass an empty List post down your tree, and you will get the error you are having.
For people facing similar issues, let me tell what I found in my code: ***The error says that the children is null, not empty !*** So if you are getting the children for the parent widget like Row or Column from a separate method, ***just check if you are returning the constructed child widget from the method***. ``` Row( children: getMyRowChildren() ) . . . getMyRowChildren(){ Widget childWidget = ... //constructed return childWidget; //don't forget to return! } ``` Else it would return null, which results in the children being null and we get the mentioned above error!
55,355,504
I have a txt file that contains "blocks of consecutive lines", each block representing one observation whereas the different lines within each block represent the value of one variable of the corresponding observation. I worked my way to here using python and I would like to read the .txt file into Stata. Therefore, I would like to remove the line breaks within each block to get one single line containing all the information for one block/observation (delimited by commas). The linebreaks between blocks/observations, however, should persist. The order of the information on variables are in the same order for all blocks/observations, but number of variables per observation varies (at the lower end). my .txt (encoding = 'ascii') file looks like this: obs1\_var1, obs1\_var2, obs1\_var3, obs2\_var1, obs2\_var2, obs2\_var3, obs2\_var4, obs3\_var1, obs3\_var2, obs3\_var3,
2019/03/26
[ "https://Stackoverflow.com/questions/55355504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11259841/" ]
Try ``` with open('my_file.txt','r') as f: # lines should hold the data with no new lines lines = [l.strip() for l in f.readlines()] ```
you can extend the balderman's answer: ``` with open('filename.txt','r') as f: lines = [l.strip() for l in f.readlines()] ``` This part will create the list of lines of whole file. To create a single line for variables in each block you can just use dictionary to store variables in each block. Example: ``` block_vars = {} for line in lines: block_name = line[:4] if block_name not in block_vars.keys(): block_vars[block_name] = [] #declaring as list store the lines in that block block_vars[block_name].append(line) #append the line to list with same block name ``` block\_vars dictionary contains list of lines associated with particular block. You can use *'delimiter'.join(list\_name)* to get single line output.
45,715,062
I try to create a domain filter what should look like this: ``` (Followup date < today) AND (customer = TRUE OR user_id = user.id) ``` I did it like following: ``` [('follow_up_date', '&lt;=', datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')),['|', ('customer', '=', 'False'),('user_id', '=', 'user.id')]] ``` The first part (the time filter) works great if it stands alone, but when I connect it with the second part like I did in the example above it gives me this error: ``` File "/usr/lib/python2.7/dist-packages/openerp/osv/expression.py", line 308, in distribute_not elif token in DOMAIN_OPERATORS_NEGATION: TypeError: unhashable type: 'list' ``` What's wrong, how can I express what I want as a correct domain filter? Thank you for your help in advance :)
2017/08/16
[ "https://Stackoverflow.com/questions/45715062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7126858/" ]
Odoo uses the [polish notation](https://en.wikipedia.org/wiki/Polish_notation). If you'd like to use the logical expression `(A) AND (B OR C)` as a domain, that means you will have to use: `AND A OR B C`. If you'd like more information about polish notation please check the link. This means that, if I understand the question correctly, you will need this: ``` ['&', ('follow_up_date', '&lt;=', datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')),'|', ('customer', '=', 'False'),('user_id', '=', 'user.id')] ```
Try without brackets in the second expression: ``` [('follow_up_date', '&lt;=', datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')),'|', ('customer', '=', 'False'),('user_id', '=', 'user.id')'] ``` I hope this help you.
66,029,297
I parsed a function from python which converts for ex. "5m" to 300 seconds (integer). My question is about the regex expression I did, because I know it's slow compared to anything else. What is the best way to get the integer part of the `timeframe` and the string part as well into a separate string? Basically, what I did, but efficiently. Not like it really matters in my situation, but I like it to be strict. ```py def parse_timeframe(timeframe): amount = int(timeframe[0:-1]) unit = timeframe[-1] if 'y' == unit: scale = 60 * 60 * 24 * 365 elif 'M' == unit: scale = 60 * 60 * 24 * 30 elif 'w' == unit: scale = 60 * 60 * 24 * 7 elif 'd' == unit: scale = 60 * 60 * 24 elif 'h' == unit: scale = 60 * 60 elif 'm' == unit: scale = 60 elif 's' == unit: scale = 1 else: raise NotSupported('timeframe unit {} is not supported'.format(unit)) return amount * scale ``` ```cs public static int ParseTimeFrameToSeconds(this string timeframe) { var amount = Convert.ToInt32(Regex.Match(timeframe, @"\d+").Value); var unit = Regex.Match(timeframe, @"[a-zA-Z]+").Value; int scale; if (unit == "y") scale = 60 * 60 * 24 * 365; else if (unit == "M") scale = 60 * 60 * 24 * 30; else if (unit == "w") scale = 60 * 60 * 24 * 7; else if (unit == "d") scale = 60 * 60 * 24; else if (unit == "h") scale = 60 * 60; else if (unit == "m") scale = 60; else if (unit == "s") scale = 1; else throw new NotSupportedException($"Timeframe unit {unit} is not supported."); return amount * scale; } ```
2021/02/03
[ "https://Stackoverflow.com/questions/66029297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13677853/" ]
there's no need to use [regexes](https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/) for this. just translate *what the existing python code does*: accessing substrings of your input. ``` var amount = int.Parse(timeframe.Substring(0, timeframe.Length - 1)); var unit = timeframe.Substring(timeframe.Length - 1); ```
Alternatively, if you have a proper TimeSpan, you can cast your string to `TimeSpan` and then use the `TotalSeconds` prop. That will also get rid of all the if-else ifs that you have. ``` if (TimeSpan.TryParse(timeframe, out var timeSpan)) { Console.WriteLine(timeSpan.TotalSeconds); } ``` \*Edit: As is, you assume every year is 365, every month is 30 days. Your calculation might be misleading anyway.
8,296,617
i hope the title itself was quite clear , i am solving 2D lid-driven cavity(square domain) problem using fractional step method , finite difference formulation (Navier-Stokes primitive variable form) , i have got u and v components of velocity over the entire domain , without manually calculating streamlines , is there a command or plotting tool which does the job for me? i hope this question is relevant enough to programming , as i need a tool for plotting streamlines without explicitly calculating them. I have solved the same problem in stream-vorticity NS form , i just had to take contour plot of stream function to get the streamlines. I hope that tool or plotter is a python library, and morevover installable in fedora (i can compromise and use mint)without much fuss!! i would be grateful if someone points out the library and relevant command (would save a lot of time)
2011/11/28
[ "https://Stackoverflow.com/questions/8296617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616809/" ]
Have a look at [Tom Flannaghan's `streamplot` function](http://www.atm.damtp.cam.ac.uk/people/tjf37/streamplot.py). The [relevant thread on the user's list is here](http://old.nabble.com/Any-update-on-streamline-plot-td30902670.html), and there's also another [similar code snippet by Ray Speth](http://web.mit.edu/speth/Public/streamlines.py) that does things slightly differently. If you have problems with speed, it might be more efficient to use some of scipy's integration functionality instead of the pure-`numpy` integration functions used in both of these examples. I haven't tried it, though, and these deliberately avoid a dependency on `scipy`. (`scipy` is a rather heavy dependency compared to `numpy`) From it's example plot: ``` import matplotlib.pyplot as plt import numpy as np from streamplot import streamplot x = np.linspace(-3,3,100) y = np.linspace(-3,3,100) u = -1-x**2+y[:,np.newaxis] v = 1+x-y[:,np.newaxis]**2 speed = np.sqrt(u*u + v*v) plt.figure() plt.subplot(121) streamplot(x, y, u, v, density=1, INTEGRATOR='RK4', color='b') plt.subplot(122) streamplot(x, y, u, v, density=(1,1), INTEGRATOR='RK4', color=u, linewidth=5*speed/speed.max()) plt.show() ``` ![enter image description here](https://i.stack.imgur.com/lay5c.png) Another option is to use `VTK`. It's accelerated 3D plotting, so making a 2D plot will require setting the camera properly (which isn't too hard), and you won't be able to get vector output. Mayavi, tvtk, and mlab provide pythonic wrappers for VTK. It has lots of functionality along these lines. The easiest way to use VTK to plot streamlines from numpy arrays is to use [`mayavi.mlab.flow`](http://github.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#mayavi.mlab.flow). I'll skip an example for the moment, but if you want to explore using VTK to do this, I can add one.
Have a look at `matplotlib`'s `quiver`: <http://matplotlib.sourceforge.net/examples/pylab_examples/quiver_demo.html>
8,296,617
i hope the title itself was quite clear , i am solving 2D lid-driven cavity(square domain) problem using fractional step method , finite difference formulation (Navier-Stokes primitive variable form) , i have got u and v components of velocity over the entire domain , without manually calculating streamlines , is there a command or plotting tool which does the job for me? i hope this question is relevant enough to programming , as i need a tool for plotting streamlines without explicitly calculating them. I have solved the same problem in stream-vorticity NS form , i just had to take contour plot of stream function to get the streamlines. I hope that tool or plotter is a python library, and morevover installable in fedora (i can compromise and use mint)without much fuss!! i would be grateful if someone points out the library and relevant command (would save a lot of time)
2011/11/28
[ "https://Stackoverflow.com/questions/8296617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616809/" ]
Have a look at [Tom Flannaghan's `streamplot` function](http://www.atm.damtp.cam.ac.uk/people/tjf37/streamplot.py). The [relevant thread on the user's list is here](http://old.nabble.com/Any-update-on-streamline-plot-td30902670.html), and there's also another [similar code snippet by Ray Speth](http://web.mit.edu/speth/Public/streamlines.py) that does things slightly differently. If you have problems with speed, it might be more efficient to use some of scipy's integration functionality instead of the pure-`numpy` integration functions used in both of these examples. I haven't tried it, though, and these deliberately avoid a dependency on `scipy`. (`scipy` is a rather heavy dependency compared to `numpy`) From it's example plot: ``` import matplotlib.pyplot as plt import numpy as np from streamplot import streamplot x = np.linspace(-3,3,100) y = np.linspace(-3,3,100) u = -1-x**2+y[:,np.newaxis] v = 1+x-y[:,np.newaxis]**2 speed = np.sqrt(u*u + v*v) plt.figure() plt.subplot(121) streamplot(x, y, u, v, density=1, INTEGRATOR='RK4', color='b') plt.subplot(122) streamplot(x, y, u, v, density=(1,1), INTEGRATOR='RK4', color=u, linewidth=5*speed/speed.max()) plt.show() ``` ![enter image description here](https://i.stack.imgur.com/lay5c.png) Another option is to use `VTK`. It's accelerated 3D plotting, so making a 2D plot will require setting the camera properly (which isn't too hard), and you won't be able to get vector output. Mayavi, tvtk, and mlab provide pythonic wrappers for VTK. It has lots of functionality along these lines. The easiest way to use VTK to plot streamlines from numpy arrays is to use [`mayavi.mlab.flow`](http://github.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#mayavi.mlab.flow). I'll skip an example for the moment, but if you want to explore using VTK to do this, I can add one.
In version 1.2 of Matplotlib, there is now a [streamplot](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.streamplot) function.
71,825,406
I try to search the answer in stackoverflow and try to find something in the github [issues](https://github.com/googleapis/python-logging/issues) but nothing I found. Can anyone give me some tip to solve the problem? I get the following error when trying to install Google Cloud Logging by pip with docker: ``` test_web | import google.cloud.logging test_web | File "/root/site/lib/python3.8/site-packages/google/cloud/logging/__init__.py", line 18, in <module> test_web | from google.cloud.logging_v2 import __version__ test_web | File "/root/site/lib/python3.8/site-packages/google/cloud/logging_v2/__init__.py", line 25, in <module> test_web | from google.cloud.logging_v2.client import Client test_web | File "/root/site/lib/python3.8/site-packages/google/cloud/logging_v2/client.py", line 25, in <module> test_web | from google.cloud.logging_v2._helpers import _add_defaults_to_filter test_web | File "/root/site/lib/python3.8/site-packages/google/cloud/logging_v2/_helpers.py", line 25, in <module> test_web | from google.cloud.logging_v2.entries import LogEntry test_web | File "/root/site/lib/python3.8/site-packages/google/cloud/logging_v2/entries.py", line 33, in <module> test_web | from google.iam.v1.logging import audit_data_pb2 # noqa: F401 test_web | File "/root/site/lib/python3.8/site-packages/google/iam/v1/logging/audit_data_pb2.py", line 32, in <module> test_web | from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 test_web | File "/root/site/lib/python3.8/site-packages/google/iam/v1/policy_pb2.py", line 39, in <module> test_web | _POLICY = DESCRIPTOR.message_types_by_name["Policy"] test_web | AttributeError: 'NoneType' object has no attribute 'message_types_by_name' ``` I have it running in a virtual environment with this in requirements.txt: `google-cloud-logging==3.0.0`
2022/04/11
[ "https://Stackoverflow.com/questions/71825406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11296376/" ]
Upgrade your protobuf to 3.20.1. Unsure why its happening. Here's the git issue: <https://github.com/googleapis/python-iam/issues/185>
I had the same error while using `google-cloud-secret-manager` and `poetry`. Removing unused `gcloud` dependency as well as `google-cloud-secret-manager` and reinstalling `google-cloud-secret-manager` solved it. ``` poetry remove gcloud poetry remove google-cloud-secret-manager poetry add google-cloud-secret-manager ```
8,618,984
The server only allows access to the videos if the useragent is QT, how to add it to this script ? ``` #!/usr/bin/env python from os import pardir, rename, listdir, getcwd from os.path import join from urllib import urlopen, urlretrieve, FancyURLopener class MyOpener(FancyURLopener): version = 'QuickTime/7.6.2 (verqt=7.6.2;cpu=IA32;so=Mac 10.5.8)' def main(): # Set up file paths. data_dir = 'data' ft_path = join(data_dir, 'titles.txt') fu_path = join(data_dir, 'urls.txt') # Open the files try: f_titles = open(ft_path, 'r') f_urls = open(fu_path, 'r') except: print "Make sure titles.txt and urls.txt are in the data directory." exit() # Read file contents into lists. titles = [] urls = [] for l in f_titles: titles.append(l) for l in f_urls: urls.append(l) # Create a dictionary and download the files. downloads = dict(zip(titles, urls)) for title, url in downloads.iteritems(): fpath = join(data_dir, title.strip().replace('\t',"").replace(" ", "_")) fpath += ".mov" urlretrieve(url, fpath) if __name__ == "__main__": main() ``` *Ignore this, text to fill the posting restriction. blablablabla*
2011/12/23
[ "https://Stackoverflow.com/questions/8618984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/891489/" ]
I found the solution. Practically I needed to set the Layout\_width of each container with the weight property to 0px.
From what I can tell, it seems your weightSum should be 12, not 10. First LinearLayout has weight=2, the second weight=8 and the third weight=2. It might solve your problem!
8,618,984
The server only allows access to the videos if the useragent is QT, how to add it to this script ? ``` #!/usr/bin/env python from os import pardir, rename, listdir, getcwd from os.path import join from urllib import urlopen, urlretrieve, FancyURLopener class MyOpener(FancyURLopener): version = 'QuickTime/7.6.2 (verqt=7.6.2;cpu=IA32;so=Mac 10.5.8)' def main(): # Set up file paths. data_dir = 'data' ft_path = join(data_dir, 'titles.txt') fu_path = join(data_dir, 'urls.txt') # Open the files try: f_titles = open(ft_path, 'r') f_urls = open(fu_path, 'r') except: print "Make sure titles.txt and urls.txt are in the data directory." exit() # Read file contents into lists. titles = [] urls = [] for l in f_titles: titles.append(l) for l in f_urls: urls.append(l) # Create a dictionary and download the files. downloads = dict(zip(titles, urls)) for title, url in downloads.iteritems(): fpath = join(data_dir, title.strip().replace('\t',"").replace(" ", "_")) fpath += ".mov" urlretrieve(url, fpath) if __name__ == "__main__": main() ``` *Ignore this, text to fill the posting restriction. blablablabla*
2011/12/23
[ "https://Stackoverflow.com/questions/8618984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/891489/" ]
I found the solution. Practically I needed to set the Layout\_width of each container with the weight property to 0px.
AFAIK, weight in linear layout is not so linear. Component with a biggest weights wins all the extra space. For playing around with layouts I highly recommend latest IntelliJ Idea - even free comminity edition has android plugin with really usefull layout preview.
29,985,453
I am getting this strange to me error when installing Keras on an Ubuntu server: ``` Cythonizing /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/utils.pyx In file included from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1804:0, from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:17, from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4, from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/api_compat.h:26, from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/defs.c:287: /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp] #warning "Using deprecated NumPy API, disable it by " \ ^ In file included from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/defs.c:287:0: /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/api_compat.h:27:18: fatal error: hdf5.h: No such file or directory #include "hdf5.h" ^ compilation terminated. error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ``` Any ideas how to fix this issue? I've downloaded Keras repository from <https://github.com/fchollet/keras>, and used this command to install it: ``` sudo python setup.py install ``` My Linux specifications are: * *Distributor ID:* Ubuntu * *Description:* Ubuntu 14.04.2 LTS * *Release:* 14.04 * *Codename:* trusty
2015/05/01
[ "https://Stackoverflow.com/questions/29985453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4262897/" ]
you can use sparql query to Dbpedia to get result for you particular resource, which here is [Vienna](http://dbpedia.org/page/Vienna). To get all property and their value of resource Vienna use can use ``` select ?property ?value where { <http://dbpedia.org/resource/Vienna> ?property ?value } ``` [Check here](http://dbpedia.org/sparql/?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=select%20%3Fproperty%20%3Fvalue%20where%20%7B%20%0D%0A%20%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FVienna%3E%20%3Fproperty%20%3Fvalue%0D%0A%20filter%28langmatches%28lang%28%3Fvalue%29%2C%22en%22%29%29%0D%0A%7D&format=text%2Fhtml&timeout=30000&debug=on) You can choose specific properties of resource using sparql query like this . ``` select ?country ?density ?timezone ?thumbnail where { <http://dbpedia.org/resource/Vienna> dbpedia-owl:country ?country; dbpedia-owl:populationDensity ?density; dbpedia-owl:timeZone ?timezone; dbpedia-owl:thumbnail ?thumbnail. } ``` [Check](http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=select%20%3Fcountry%20%3Fdensity%20%3Ftimezone%20%3Fthumbnail%20where%20%7B%20%0D%0A%20%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FVienna%3E%20dbpedia-owl%3Acountry%20%3Fcountry%3B%0D%0Adbpedia-owl%3ApopulationDensity%20%3Fdensity%3B%0D%0Adbpedia-owl%3AtimeZone%20%3Ftimezone%3B%0D%0Adbpedia-owl%3Athumbnail%20%3Fthumbnail.%0D%0A%0D%0A%7D&format=text%2Fhtml&timeout=30000&debug=on)
> > *But what I want is something … to get all items where any property fits "Vienna"[.]* > > > In SPARQL this is very easy. E.g., on [DBpedia's SPARQL endpoint](http://dbpedia.org/sparql/): ``` select ?resource where { ?resource ?property dbpedia:Vienna } ``` [SPARQL results (limited to 100)](http://dbpedia.org/sparql/?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=select%20%3Fresource%20where%20%7B%0D%0A%20%20%3Fresource%20%3Fproperty%20dbpedia%3AVienna%20%0D%0Afilter%28%20%3Fproperty%20!%3D%20owl%3AsameAs%20%29%0D%0A%7D%0D%0Alimit%20100&format=text%2Fhtml&timeout=30000&debug=on)
29,985,453
I am getting this strange to me error when installing Keras on an Ubuntu server: ``` Cythonizing /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/utils.pyx In file included from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1804:0, from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:17, from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4, from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/api_compat.h:26, from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/defs.c:287: /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp] #warning "Using deprecated NumPy API, disable it by " \ ^ In file included from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/defs.c:287:0: /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/api_compat.h:27:18: fatal error: hdf5.h: No such file or directory #include "hdf5.h" ^ compilation terminated. error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ``` Any ideas how to fix this issue? I've downloaded Keras repository from <https://github.com/fchollet/keras>, and used this command to install it: ``` sudo python setup.py install ``` My Linux specifications are: * *Distributor ID:* Ubuntu * *Description:* Ubuntu 14.04.2 LTS * *Release:* 14.04 * *Codename:* trusty
2015/05/01
[ "https://Stackoverflow.com/questions/29985453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4262897/" ]
maybe something like this: ``` SELECT ?node WHERE {?node ?pred wd:Q1741} ``` see on [Wikidata Query Service](https://query.wikidata.org/#SELECT%20%3Fnode%20WHERE%20%7B%3Fnode%20%3Fpred%20wd%3AQ1741%7D%20%20%20%20%0A)
> > *But what I want is something … to get all items where any property fits "Vienna"[.]* > > > In SPARQL this is very easy. E.g., on [DBpedia's SPARQL endpoint](http://dbpedia.org/sparql/): ``` select ?resource where { ?resource ?property dbpedia:Vienna } ``` [SPARQL results (limited to 100)](http://dbpedia.org/sparql/?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=select%20%3Fresource%20where%20%7B%0D%0A%20%20%3Fresource%20%3Fproperty%20dbpedia%3AVienna%20%0D%0Afilter%28%20%3Fproperty%20!%3D%20owl%3AsameAs%20%29%0D%0A%7D%0D%0Alimit%20100&format=text%2Fhtml&timeout=30000&debug=on)
29,985,453
I am getting this strange to me error when installing Keras on an Ubuntu server: ``` Cythonizing /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/utils.pyx In file included from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1804:0, from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:17, from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4, from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/api_compat.h:26, from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/defs.c:287: /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp] #warning "Using deprecated NumPy API, disable it by " \ ^ In file included from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/defs.c:287:0: /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/api_compat.h:27:18: fatal error: hdf5.h: No such file or directory #include "hdf5.h" ^ compilation terminated. error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ``` Any ideas how to fix this issue? I've downloaded Keras repository from <https://github.com/fchollet/keras>, and used this command to install it: ``` sudo python setup.py install ``` My Linux specifications are: * *Distributor ID:* Ubuntu * *Description:* Ubuntu 14.04.2 LTS * *Release:* 14.04 * *Codename:* trusty
2015/05/01
[ "https://Stackoverflow.com/questions/29985453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4262897/" ]
you can use sparql query to Dbpedia to get result for you particular resource, which here is [Vienna](http://dbpedia.org/page/Vienna). To get all property and their value of resource Vienna use can use ``` select ?property ?value where { <http://dbpedia.org/resource/Vienna> ?property ?value } ``` [Check here](http://dbpedia.org/sparql/?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=select%20%3Fproperty%20%3Fvalue%20where%20%7B%20%0D%0A%20%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FVienna%3E%20%3Fproperty%20%3Fvalue%0D%0A%20filter%28langmatches%28lang%28%3Fvalue%29%2C%22en%22%29%29%0D%0A%7D&format=text%2Fhtml&timeout=30000&debug=on) You can choose specific properties of resource using sparql query like this . ``` select ?country ?density ?timezone ?thumbnail where { <http://dbpedia.org/resource/Vienna> dbpedia-owl:country ?country; dbpedia-owl:populationDensity ?density; dbpedia-owl:timeZone ?timezone; dbpedia-owl:thumbnail ?thumbnail. } ``` [Check](http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=select%20%3Fcountry%20%3Fdensity%20%3Ftimezone%20%3Fthumbnail%20where%20%7B%20%0D%0A%20%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FVienna%3E%20dbpedia-owl%3Acountry%20%3Fcountry%3B%0D%0Adbpedia-owl%3ApopulationDensity%20%3Fdensity%3B%0D%0Adbpedia-owl%3AtimeZone%20%3Ftimezone%3B%0D%0Adbpedia-owl%3Athumbnail%20%3Fthumbnail.%0D%0A%0D%0A%7D&format=text%2Fhtml&timeout=30000&debug=on)
There are already some SPARQL endpoints for Wikidata available. However, they are still beta and only reflect the data from the last dump. Your query would be [this one](http://wikisparql.org/sparql?showquery=SELECT%20%3Fresource%0D%0AWHERE%20%7B%0D%0A%3Fresource%20%3Fproperty%20%3Chttp%3A%2F%2Fwww.wikidata.org%2Fentity%2FQ1741%3E%20.%0D%0A%3Fresource%20rdf%3Atype%20%3Chttp%3A%2F%2Fwww.wikidata.org%2Fontology%23Item%3E%0D%0A%7D) See also [this help page on Wikidata](https://www.wikidata.org/wiki/Wikidata:Data_access)
29,985,453
I am getting this strange to me error when installing Keras on an Ubuntu server: ``` Cythonizing /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/utils.pyx In file included from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1804:0, from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:17, from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4, from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/api_compat.h:26, from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/defs.c:287: /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp] #warning "Using deprecated NumPy API, disable it by " \ ^ In file included from /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/defs.c:287:0: /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/api_compat.h:27:18: fatal error: hdf5.h: No such file or directory #include "hdf5.h" ^ compilation terminated. error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ``` Any ideas how to fix this issue? I've downloaded Keras repository from <https://github.com/fchollet/keras>, and used this command to install it: ``` sudo python setup.py install ``` My Linux specifications are: * *Distributor ID:* Ubuntu * *Description:* Ubuntu 14.04.2 LTS * *Release:* 14.04 * *Codename:* trusty
2015/05/01
[ "https://Stackoverflow.com/questions/29985453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4262897/" ]
maybe something like this: ``` SELECT ?node WHERE {?node ?pred wd:Q1741} ``` see on [Wikidata Query Service](https://query.wikidata.org/#SELECT%20%3Fnode%20WHERE%20%7B%3Fnode%20%3Fpred%20wd%3AQ1741%7D%20%20%20%20%0A)
There are already some SPARQL endpoints for Wikidata available. However, they are still beta and only reflect the data from the last dump. Your query would be [this one](http://wikisparql.org/sparql?showquery=SELECT%20%3Fresource%0D%0AWHERE%20%7B%0D%0A%3Fresource%20%3Fproperty%20%3Chttp%3A%2F%2Fwww.wikidata.org%2Fentity%2FQ1741%3E%20.%0D%0A%3Fresource%20rdf%3Atype%20%3Chttp%3A%2F%2Fwww.wikidata.org%2Fontology%23Item%3E%0D%0A%7D) See also [this help page on Wikidata](https://www.wikidata.org/wiki/Wikidata:Data_access)
31,466,769
Similar to this question [How to add an empty column to a dataframe?](https://stackoverflow.com/questions/16327055/how-to-add-an-empty-column-to-a-dataframe), I am interested in knowing the best way to add a column of empty lists to a DataFrame. What I am trying to do is basically initialize a column and as I iterate over the rows to process some of them, then add a filled list in this new column to replace the initialized value. For example, if below is my initial DataFrame: ``` df = pd.DataFrame(d = {'a': [1,2,3], 'b': [5,6,7]}) # Sample DataFrame >>> df a b 0 1 5 1 2 6 2 3 7 ``` Then I want to ultimately end up with something like this, where each row has been processed separately (sample results shown): ``` >>> df a b c 0 1 5 [5, 6] 1 2 6 [9, 0] 2 3 7 [1, 2, 3] ``` Of course, if I try to initialize like `df['e'] = []` as I would with any other constant, it thinks I am trying to add a sequence of items with length 0, and hence fails. If I try initializing a new column as `None` or `NaN`, I run in to the following issues when trying to assign a list to a location. ``` df['d'] = None >>> df a b d 0 1 5 None 1 2 6 None 2 3 7 None ``` Issue 1 (it would be perfect if I can get this approach to work! Maybe something trivial I am missing): ``` >>> df.loc[0,'d'] = [1,3] ... ValueError: Must have equal len keys and value when setting with an iterable ``` Issue 2 (this one works, but not without a warning because it is not guaranteed to work as intended): ``` >>> df['d'][0] = [1,3] C:\Python27\Scripts\ipython:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame ``` Hence I resort to initializing with empty lists and extending them as needed. There are a couple of methods I can think of to initialize this way, but is there a more straightforward way? Method 1: ``` df['empty_lists1'] = [list() for x in range(len(df.index))] >>> df a b empty_lists1 0 1 5 [] 1 2 6 [] 2 3 7 [] ``` Method 2: ``` df['empty_lists2'] = df.apply(lambda x: [], axis=1) >>> df a b empty_lists1 empty_lists2 0 1 5 [] [] 1 2 6 [] [] 2 3 7 [] [] ``` **Summary of questions:** Is there any minor syntax change that can be addressed in Issue 1 that can allow a list to be assigned to a `None`/`NaN` initialized field? If not, then what is the best way to initialize a new column with empty lists?
2015/07/17
[ "https://Stackoverflow.com/questions/31466769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403872/" ]
One more way is to use [`np.empty`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html): ``` df['empty_list'] = np.empty((len(df), 0)).tolist() ``` --- You could also knock off `.index` in your "Method 1" when trying to find `len` of `df`. ``` df['empty_list'] = [[] for _ in range(len(df))] ``` --- Turns out, `np.empty` is faster... ``` In [1]: import pandas as pd In [2]: df = pd.DataFrame(pd.np.random.rand(1000000, 5)) In [3]: timeit df['empty1'] = pd.np.empty((len(df), 0)).tolist() 10 loops, best of 3: 127 ms per loop In [4]: timeit df['empty2'] = [[] for _ in range(len(df))] 10 loops, best of 3: 193 ms per loop In [5]: timeit df['empty3'] = df.apply(lambda x: [], axis=1) 1 loops, best of 3: 5.89 s per loop ```
EDIT: the commenters caught the bug in my answer ``` s = pd.Series([[]] * 3) s.iloc[0].append(1) #adding an item only to the first element >s # unintended consequences: 0 [1] 1 [1] 2 [1] ``` So, the correct solution is ``` s = pd.Series([[] for i in range(3)]) s.iloc[0].append(1) >s 0 [1] 1 [] 2 [] ``` OLD: I timed all the three methods in the accepted answer, the fastest one took 216 ms on my machine. However, this took only 28 ms: ``` df['empty4'] = [[]] * len(df) ``` Note: Similarly, `df['e5'] = [set()] * len(df)` also took 28ms.
31,466,769
Similar to this question [How to add an empty column to a dataframe?](https://stackoverflow.com/questions/16327055/how-to-add-an-empty-column-to-a-dataframe), I am interested in knowing the best way to add a column of empty lists to a DataFrame. What I am trying to do is basically initialize a column and as I iterate over the rows to process some of them, then add a filled list in this new column to replace the initialized value. For example, if below is my initial DataFrame: ``` df = pd.DataFrame(d = {'a': [1,2,3], 'b': [5,6,7]}) # Sample DataFrame >>> df a b 0 1 5 1 2 6 2 3 7 ``` Then I want to ultimately end up with something like this, where each row has been processed separately (sample results shown): ``` >>> df a b c 0 1 5 [5, 6] 1 2 6 [9, 0] 2 3 7 [1, 2, 3] ``` Of course, if I try to initialize like `df['e'] = []` as I would with any other constant, it thinks I am trying to add a sequence of items with length 0, and hence fails. If I try initializing a new column as `None` or `NaN`, I run in to the following issues when trying to assign a list to a location. ``` df['d'] = None >>> df a b d 0 1 5 None 1 2 6 None 2 3 7 None ``` Issue 1 (it would be perfect if I can get this approach to work! Maybe something trivial I am missing): ``` >>> df.loc[0,'d'] = [1,3] ... ValueError: Must have equal len keys and value when setting with an iterable ``` Issue 2 (this one works, but not without a warning because it is not guaranteed to work as intended): ``` >>> df['d'][0] = [1,3] C:\Python27\Scripts\ipython:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame ``` Hence I resort to initializing with empty lists and extending them as needed. There are a couple of methods I can think of to initialize this way, but is there a more straightforward way? Method 1: ``` df['empty_lists1'] = [list() for x in range(len(df.index))] >>> df a b empty_lists1 0 1 5 [] 1 2 6 [] 2 3 7 [] ``` Method 2: ``` df['empty_lists2'] = df.apply(lambda x: [], axis=1) >>> df a b empty_lists1 empty_lists2 0 1 5 [] [] 1 2 6 [] [] 2 3 7 [] [] ``` **Summary of questions:** Is there any minor syntax change that can be addressed in Issue 1 that can allow a list to be assigned to a `None`/`NaN` initialized field? If not, then what is the best way to initialize a new column with empty lists?
2015/07/17
[ "https://Stackoverflow.com/questions/31466769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403872/" ]
One more way is to use [`np.empty`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html): ``` df['empty_list'] = np.empty((len(df), 0)).tolist() ``` --- You could also knock off `.index` in your "Method 1" when trying to find `len` of `df`. ``` df['empty_list'] = [[] for _ in range(len(df))] ``` --- Turns out, `np.empty` is faster... ``` In [1]: import pandas as pd In [2]: df = pd.DataFrame(pd.np.random.rand(1000000, 5)) In [3]: timeit df['empty1'] = pd.np.empty((len(df), 0)).tolist() 10 loops, best of 3: 127 ms per loop In [4]: timeit df['empty2'] = [[] for _ in range(len(df))] 10 loops, best of 3: 193 ms per loop In [5]: timeit df['empty3'] = df.apply(lambda x: [], axis=1) 1 loops, best of 3: 5.89 s per loop ```
Canonical solutions: List comprehension, `map` and `apply` ========================================================== Obligatory disclaimer: avoid using lists in pandas columns where possible, list columns are slow to work with because they are objects and those are inherently hard to vectorize. With that out of the way, here are the canonical methods of introducing a column of empty lists: ``` # List comprehension df['c'] = [[] for _ in range(df.shape[0])] df a b c 0 1 5 [] 1 2 6 [] 2 3 7 [] ``` There's also these shorthands involving `apply` and `map`: ``` from collections import defaultdict # map any column with defaultdict df['c'] = df.iloc[:,0].map(defaultdict(list)) # same as, df['c'] = df.iloc[:,0].map(lambda _: []) # apply with defaultdict df['c'] = df.apply(defaultdict(list), axis=1) # same as, df['c'] = df.apply(lambda _: [], axis=1) df a b c 0 1 5 [] 1 2 6 [] 2 3 7 [] ``` --- ### Things you should NOT do Some folks believe multiplying an empty list is the way to go, unfortunately this is wrong and will usually lead to hard-to-debug issues. Here's an MVP: ``` # WRONG df['c'] = [[]] * len(df) df.at[0, 'c'].append('abc') df.at[1, 'c'].append('def') df a b c 0 1 5 [abc, def] 1 2 6 [abc, def] 2 3 7 [abc, def] ``` ``` # RIGHT df['c'] = [[] for _ in range(df.shape[0])] df.at[0, 'c'].append('abc') df.at[1, 'c'].append('def') df a b c 0 1 5 [abc] 1 2 6 [def] 2 3 7 [] ``` In the first case, a single empty list is created and its *reference* is replicated across all the rows, so you see updates to one reflected to all of them. In the latter case each row is assigned its own empty list, so this is not a concern.
31,466,769
Similar to this question [How to add an empty column to a dataframe?](https://stackoverflow.com/questions/16327055/how-to-add-an-empty-column-to-a-dataframe), I am interested in knowing the best way to add a column of empty lists to a DataFrame. What I am trying to do is basically initialize a column and as I iterate over the rows to process some of them, then add a filled list in this new column to replace the initialized value. For example, if below is my initial DataFrame: ``` df = pd.DataFrame(d = {'a': [1,2,3], 'b': [5,6,7]}) # Sample DataFrame >>> df a b 0 1 5 1 2 6 2 3 7 ``` Then I want to ultimately end up with something like this, where each row has been processed separately (sample results shown): ``` >>> df a b c 0 1 5 [5, 6] 1 2 6 [9, 0] 2 3 7 [1, 2, 3] ``` Of course, if I try to initialize like `df['e'] = []` as I would with any other constant, it thinks I am trying to add a sequence of items with length 0, and hence fails. If I try initializing a new column as `None` or `NaN`, I run in to the following issues when trying to assign a list to a location. ``` df['d'] = None >>> df a b d 0 1 5 None 1 2 6 None 2 3 7 None ``` Issue 1 (it would be perfect if I can get this approach to work! Maybe something trivial I am missing): ``` >>> df.loc[0,'d'] = [1,3] ... ValueError: Must have equal len keys and value when setting with an iterable ``` Issue 2 (this one works, but not without a warning because it is not guaranteed to work as intended): ``` >>> df['d'][0] = [1,3] C:\Python27\Scripts\ipython:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame ``` Hence I resort to initializing with empty lists and extending them as needed. There are a couple of methods I can think of to initialize this way, but is there a more straightforward way? Method 1: ``` df['empty_lists1'] = [list() for x in range(len(df.index))] >>> df a b empty_lists1 0 1 5 [] 1 2 6 [] 2 3 7 [] ``` Method 2: ``` df['empty_lists2'] = df.apply(lambda x: [], axis=1) >>> df a b empty_lists1 empty_lists2 0 1 5 [] [] 1 2 6 [] [] 2 3 7 [] [] ``` **Summary of questions:** Is there any minor syntax change that can be addressed in Issue 1 that can allow a list to be assigned to a `None`/`NaN` initialized field? If not, then what is the best way to initialize a new column with empty lists?
2015/07/17
[ "https://Stackoverflow.com/questions/31466769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403872/" ]
EDIT: the commenters caught the bug in my answer ``` s = pd.Series([[]] * 3) s.iloc[0].append(1) #adding an item only to the first element >s # unintended consequences: 0 [1] 1 [1] 2 [1] ``` So, the correct solution is ``` s = pd.Series([[] for i in range(3)]) s.iloc[0].append(1) >s 0 [1] 1 [] 2 [] ``` OLD: I timed all the three methods in the accepted answer, the fastest one took 216 ms on my machine. However, this took only 28 ms: ``` df['empty4'] = [[]] * len(df) ``` Note: Similarly, `df['e5'] = [set()] * len(df)` also took 28ms.
Canonical solutions: List comprehension, `map` and `apply` ========================================================== Obligatory disclaimer: avoid using lists in pandas columns where possible, list columns are slow to work with because they are objects and those are inherently hard to vectorize. With that out of the way, here are the canonical methods of introducing a column of empty lists: ``` # List comprehension df['c'] = [[] for _ in range(df.shape[0])] df a b c 0 1 5 [] 1 2 6 [] 2 3 7 [] ``` There's also these shorthands involving `apply` and `map`: ``` from collections import defaultdict # map any column with defaultdict df['c'] = df.iloc[:,0].map(defaultdict(list)) # same as, df['c'] = df.iloc[:,0].map(lambda _: []) # apply with defaultdict df['c'] = df.apply(defaultdict(list), axis=1) # same as, df['c'] = df.apply(lambda _: [], axis=1) df a b c 0 1 5 [] 1 2 6 [] 2 3 7 [] ``` --- ### Things you should NOT do Some folks believe multiplying an empty list is the way to go, unfortunately this is wrong and will usually lead to hard-to-debug issues. Here's an MVP: ``` # WRONG df['c'] = [[]] * len(df) df.at[0, 'c'].append('abc') df.at[1, 'c'].append('def') df a b c 0 1 5 [abc, def] 1 2 6 [abc, def] 2 3 7 [abc, def] ``` ``` # RIGHT df['c'] = [[] for _ in range(df.shape[0])] df.at[0, 'c'].append('abc') df.at[1, 'c'].append('def') df a b c 0 1 5 [abc] 1 2 6 [def] 2 3 7 [] ``` In the first case, a single empty list is created and its *reference* is replicated across all the rows, so you see updates to one reflected to all of them. In the latter case each row is assigned its own empty list, so this is not a concern.
27,138,716
I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days. I saw this tutorial: <http://www.codecademy.com/courses/a-simple-counter/0/1> I completed the tutorial and thought: "I should learn how to do this with Jquery". So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript). Here is my code: **HTML** ``` <body> <label for="qty">Quantity</label> <input id="qty" type = "number" value = 0 /> <button class = "botton">-1</button> <button class = "botton">+1</button> <script type="text/javascript" src="jquery-1.11.1.min.js"></script> <script type="text/javascript" src="test.js"></script> </body> ``` **Jquery/Javascript:** ``` //create a function that adds or subtracts based on the button pressed function modify_qty(x) { //on click add or subtract $('.botton').click(function(){ //get the value of input field id-'qty' var qty = $('#qty').val(); var new_qty = qty + x; //i don't want to go below 0 if (new_qty < 0) { new_qty = 0; } //put new value into input box id-'qty' $('#qty').html(new_qty) }) }; $(document).ready(modify_qty); ``` How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}). Thank you
2014/11/25
[ "https://Stackoverflow.com/questions/27138716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4293758/" ]
If you want to read the whole file with the spaces removed, `f.read()` is on the right track—unlike your other attempts, that gives you the whole file as a single string, not one line at a time. But you still need to replace the spaces. Which you need to do explicitly. For example: ``` f.read().replace(' ', '') ``` Or, if you want to replace all whitespace, not just spaces: ``` ''.join(f.read().split()) ```
This line: ``` f = open("clues.txt") ``` will open the file - that is, it returns a filehandle that you can read from This line: ``` open("clues.txt").read().replace(" ", "") ``` will open the file and return its contents, with all spaces removed.
27,138,716
I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days. I saw this tutorial: <http://www.codecademy.com/courses/a-simple-counter/0/1> I completed the tutorial and thought: "I should learn how to do this with Jquery". So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript). Here is my code: **HTML** ``` <body> <label for="qty">Quantity</label> <input id="qty" type = "number" value = 0 /> <button class = "botton">-1</button> <button class = "botton">+1</button> <script type="text/javascript" src="jquery-1.11.1.min.js"></script> <script type="text/javascript" src="test.js"></script> </body> ``` **Jquery/Javascript:** ``` //create a function that adds or subtracts based on the button pressed function modify_qty(x) { //on click add or subtract $('.botton').click(function(){ //get the value of input field id-'qty' var qty = $('#qty').val(); var new_qty = qty + x; //i don't want to go below 0 if (new_qty < 0) { new_qty = 0; } //put new value into input box id-'qty' $('#qty').html(new_qty) }) }; $(document).ready(modify_qty); ``` How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}). Thank you
2014/11/25
[ "https://Stackoverflow.com/questions/27138716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4293758/" ]
Building upon @JonKiparsky It would be safer for you to use the python `with` statement: ``` with open("clues.txt") as f: f.read().replace(" ", "") ```
If you want to read the whole file with the spaces removed, `f.read()` is on the right track—unlike your other attempts, that gives you the whole file as a single string, not one line at a time. But you still need to replace the spaces. Which you need to do explicitly. For example: ``` f.read().replace(' ', '') ``` Or, if you want to replace all whitespace, not just spaces: ``` ''.join(f.read().split()) ```
27,138,716
I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days. I saw this tutorial: <http://www.codecademy.com/courses/a-simple-counter/0/1> I completed the tutorial and thought: "I should learn how to do this with Jquery". So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript). Here is my code: **HTML** ``` <body> <label for="qty">Quantity</label> <input id="qty" type = "number" value = 0 /> <button class = "botton">-1</button> <button class = "botton">+1</button> <script type="text/javascript" src="jquery-1.11.1.min.js"></script> <script type="text/javascript" src="test.js"></script> </body> ``` **Jquery/Javascript:** ``` //create a function that adds or subtracts based on the button pressed function modify_qty(x) { //on click add or subtract $('.botton').click(function(){ //get the value of input field id-'qty' var qty = $('#qty').val(); var new_qty = qty + x; //i don't want to go below 0 if (new_qty < 0) { new_qty = 0; } //put new value into input box id-'qty' $('#qty').html(new_qty) }) }; $(document).ready(modify_qty); ``` How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}). Thank you
2014/11/25
[ "https://Stackoverflow.com/questions/27138716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4293758/" ]
Building upon @JonKiparsky It would be safer for you to use the python `with` statement: ``` with open("clues.txt") as f: f.read().replace(" ", "") ```
This line: ``` f = open("clues.txt") ``` will open the file - that is, it returns a filehandle that you can read from This line: ``` open("clues.txt").read().replace(" ", "") ``` will open the file and return its contents, with all spaces removed.
65,682,339
This is not working, Cant figure it out... i want it to print either error sentence or break.. I wanted to do it in a try/except, but that was not so good. And I'm new to python :-) ```py while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") list = ["Fahrenheit" , "Celsius" , "Kelvin"] if unitFrom.lower() in list: break else: print ("Wrong unit, try again") break ```
2021/01/12
[ "https://Stackoverflow.com/questions/65682339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14990031/" ]
1. Never use the built-in keywords to define new variables. 2. Take the list outside the loop to avoid initializing it on each iteration. 3. You need to have the list in lowercase since you're checking the lower-cased input in the list: Hence: ``` x_units = ["fahrenheit" , "celsius" , "kelvin"] # or x_units = [x.lower() for x in x_units] if you do not wish to change the original list while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") if unitFrom.lower() in x_units: break else: print ("Wrong unit, try again") break ```
Do you want to print break or want to execute `break` ? and `list = ["Fahrenheit" , "Celsius" , "Kelvin"]` is created new everytime execute it before `while True:` and use something other than list as array name as `list` is a keyword ``` answer_list = ["Fahrenheit" , "Celsius" , "Kelvin"] while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") if unitFrom.lower() in answer_list: break else: print ("Wrong unit, try again") break ```
65,682,339
This is not working, Cant figure it out... i want it to print either error sentence or break.. I wanted to do it in a try/except, but that was not so good. And I'm new to python :-) ```py while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") list = ["Fahrenheit" , "Celsius" , "Kelvin"] if unitFrom.lower() in list: break else: print ("Wrong unit, try again") break ```
2021/01/12
[ "https://Stackoverflow.com/questions/65682339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14990031/" ]
1. Never use the built-in keywords to define new variables. 2. Take the list outside the loop to avoid initializing it on each iteration. 3. You need to have the list in lowercase since you're checking the lower-cased input in the list: Hence: ``` x_units = ["fahrenheit" , "celsius" , "kelvin"] # or x_units = [x.lower() for x in x_units] if you do not wish to change the original list while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") if unitFrom.lower() in x_units: break else: print ("Wrong unit, try again") break ```
The problem is that you're not using lowercase units. And then checking if `"Kelvin" =="kelvin"`, which is never `True`. Replace your list of units with lowercase or just use this code: ``` while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") myList = ["Fahrenheit" , "Celsius" , "Kelvin"] myList = [unit.lower() for unit in myList] #transform all strings inside list to lowercase if unitFrom.lower() in myList: break else: print ("Wrong unit, try again") break ``` Also never use `list` as a variable name.
65,682,339
This is not working, Cant figure it out... i want it to print either error sentence or break.. I wanted to do it in a try/except, but that was not so good. And I'm new to python :-) ```py while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") list = ["Fahrenheit" , "Celsius" , "Kelvin"] if unitFrom.lower() in list: break else: print ("Wrong unit, try again") break ```
2021/01/12
[ "https://Stackoverflow.com/questions/65682339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14990031/" ]
1. Never use the built-in keywords to define new variables. 2. Take the list outside the loop to avoid initializing it on each iteration. 3. You need to have the list in lowercase since you're checking the lower-cased input in the list: Hence: ``` x_units = ["fahrenheit" , "celsius" , "kelvin"] # or x_units = [x.lower() for x in x_units] if you do not wish to change the original list while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") if unitFrom.lower() in x_units: break else: print ("Wrong unit, try again") break ```
As pointed by @dirtybit, you should take care of those points. Set Access is faster than list, if list is of big size, you can try `set` to compare with input. ### Solution : ```py units_set = set("fahrenheit" , "felsius" , "kelvin") # initializing it only once, the lower case values. while True: unit_from = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") if unit_from.lower() in units_set: # do something here. break else: print ("Wrong unit, try again") ```
65,682,339
This is not working, Cant figure it out... i want it to print either error sentence or break.. I wanted to do it in a try/except, but that was not so good. And I'm new to python :-) ```py while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") list = ["Fahrenheit" , "Celsius" , "Kelvin"] if unitFrom.lower() in list: break else: print ("Wrong unit, try again") break ```
2021/01/12
[ "https://Stackoverflow.com/questions/65682339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14990031/" ]
1. Never use the built-in keywords to define new variables. 2. Take the list outside the loop to avoid initializing it on each iteration. 3. You need to have the list in lowercase since you're checking the lower-cased input in the list: Hence: ``` x_units = ["fahrenheit" , "celsius" , "kelvin"] # or x_units = [x.lower() for x in x_units] if you do not wish to change the original list while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") if unitFrom.lower() in x_units: break else: print ("Wrong unit, try again") break ```
You can try this, ``` loopBool = True while loopBool: unitList = ["fahrenheit", "celsius", "kelvin"] try: unitFrom = raw_input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") if unitFrom in unitList: inBool = True if inBool == True: print("Success") loopBool = False else: raise Exception except: print ("Wrong unit, try again") ``` The problem might be input() function you use. I do not want to change your code to much (You should think about lower in my case) ``` while True: unitFrom = raw_input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") unitList = ["Fahrenheit", "Celsius", "Kelvin"] if unitFrom in unitList: break else: print ("Wrong unit, try again") break ``` You can read further about it : [NameError from Python input() function](https://stackoverflow.com/questions/16457441/nameerror-from-python-input-function)
68,179,964
I am trying to check if all the objects in a specified bucket are public or not, using the boto3 module in python. I have tried using the `client.get_object()` and `client.list_objects()` methods, but I am unable to figure out what exactly I should search for as I am new to boto3 and AWS in general. Also, since my organization prefers using `client` over `resource`, so I'm preferably looking for a way to do it using `client`.
2021/06/29
[ "https://Stackoverflow.com/questions/68179964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16081945/" ]
I think the best way to test if an object is public or not is to make an anonymous request to that object URL. ```py import boto3 import botocore import requests bucket_name = 'example-bucket' object_key = 'example-key' config = botocore.client.Config(signature_version=botocore.UNSIGNED) object_url = boto3.client('s3', config=config).generate_presigned_url('get_object', Params={'Bucket': bucket_name, 'Key': object_key}) resp = requests.get(object_url) if resp.status_code == 200: print('The object is public.') else: print('Nope! The object is private or inaccessible.') ``` Note: You can use `requests.head` instead of `requests.get` to save some data transfer.
may be a combination of these to tell the full story for each object ``` client = boto3.client('s3') bucket = 'my-bucket' key = 'my-key' client.get_object_acl(Bucket=bucket, Key=key) client.get_bucket_acl(Bucket=bucket) client.get_bucket_policy(Bucket=bucket) ```
68,179,964
I am trying to check if all the objects in a specified bucket are public or not, using the boto3 module in python. I have tried using the `client.get_object()` and `client.list_objects()` methods, but I am unable to figure out what exactly I should search for as I am new to boto3 and AWS in general. Also, since my organization prefers using `client` over `resource`, so I'm preferably looking for a way to do it using `client`.
2021/06/29
[ "https://Stackoverflow.com/questions/68179964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16081945/" ]
I think the best way to test if an object is public or not is to make an anonymous request to that object URL. ```py import boto3 import botocore import requests bucket_name = 'example-bucket' object_key = 'example-key' config = botocore.client.Config(signature_version=botocore.UNSIGNED) object_url = boto3.client('s3', config=config).generate_presigned_url('get_object', Params={'Bucket': bucket_name, 'Key': object_key}) resp = requests.get(object_url) if resp.status_code == 200: print('The object is public.') else: print('Nope! The object is private or inaccessible.') ``` Note: You can use `requests.head` instead of `requests.get` to save some data transfer.
This function should do the trick. It gets the ACL and then loops through the `Grants` looking for `AllUsers` with `READ` or `FULL_CONTROL` permissions. ``` import boto3 def is_public(key, bucket): """Returns true if key has public access. Args: key (str): key to check bucket (str, optional): Bucket name. Returns: (bool) Public object ACL example: { ... "Grants": [ { "Grantee": { "Type": "Group", "URI": "http://acs.amazonaws.com/groups/global/AllUsers", }, "Permission": "READ", }, { "Grantee": { "ID": "somecrypticidstring", "Type": "CanonicalUser", }, "Permission": "FULL_CONTROL", }, ], } Private object ACL example: { ... "Grants": [ { "Grantee": { "ID": "somecrypticidstring", "Type": "CanonicalUser", }, "Permission": "FULL_CONTROL", } ], } """ client = boto3.client( "s3", aws_access_key_id=YOUR_AWS_ACCESS_KEY_ID, aws_secret_access_key=YOUR_AWS_SECRET_ACCESS_KEY, ) d = client.get_object_acl(Bucket=bucket, Key=key) try: for grant in d["Grants"]: if ( "URI" in grant["Grantee"] and grant["Grantee"]["URI"].endswith("AllUsers") and grant["Permission"] in ["READ", "FULL_CONTROL"] ): return True return False except Exception: # Cannot determine if s3 object is public. return False ```
70,222,086
Well, I would like to get a calendars data from outlook. My purpose is making small service in Python which can read & write in someones calendar in outlook account of course I suppose that I was provided access to it in Azure Active Directory. Before writing this, I read a lot of guides on how to do this. Also I tried to find similar issues on [github](https://github.com/O365/python-o365/issues), some things I've learned from this. So I've made following steps. I wish you pointed on my mistakes and told how to fix them. * [![enter image description here](https://i.stack.imgur.com/lLamL.png)](https://i.stack.imgur.com/lLamL.png) * [![enter image description here](https://i.stack.imgur.com/H0usv.png)](https://i.stack.imgur.com/H0usv.png) * [![enter image description here](https://i.stack.imgur.com/uaO99.png)](https://i.stack.imgur.com/uaO99.png) * [![enter image description here](https://i.stack.imgur.com/fmzVc.png)](https://i.stack.imgur.com/fmzVc.png) * [![enter image description here](https://i.stack.imgur.com/BxIIF.png)](https://i.stack.imgur.com/BxIIF.png) * [![enter image description here](https://i.stack.imgur.com/1WFgi.png)](https://i.stack.imgur.com/1WFgi.png) Then I've written this code in Python with O365 ``` from O365 import Account CLIENT_ID = 'xxxx' SECRET_ID = 'xxxx' TENANT_ID = 'xxxx' credentials = (CLIENT_ID, SECRET_ID) account = Account(credentials, auth_flow_type='credentials', tenant_id=TENANT_ID) if account.authenticate(): print('Authenticated!') schedule = account.schedule(resource='user@domain') calendar = schedule.get_default_calendar() events = calendar.get_events(include_recurring=False) for event in events: print(event) ``` Then if I use email which is shown in user contact info in my directory as a resourse. I get this error: ``` requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://graph.microsoft.com/v1.0/users/user@domain/calendar | Error Message: The tenant for tenant guid 'xxxx' does not exist. ``` Then if I use 'User Principal Name', which is shown in user identity in my directory as a resourse. I get this error: ``` requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://graph.microsoft.com/v1.0/users/xxxx#EXT%23@xxxx.onmicrosoft.com/calendar | Error Message: Insufficient privileges to complete the operation. ``` Then if I use 'me' as a resource I also get an error: ``` requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://graph.microsoft.com/v1.0/me/calendar | Error Message: /me request is only valid with delegated authentication flow. ``` Could you tell me what should i provide as a resource to get someones calendar or maybe what should i fix?
2021/12/04
[ "https://Stackoverflow.com/questions/70222086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12961561/" ]
let's best go through the error messages: 1. `Error Message: The tenant for tenant guid 'xxxx' does not exist.` I am assuming that this is an Office 365 Business. Also that you are logged into Azure with your company address. Then you should see under: "App registrations>test feature> Overview" you should find the valid TenantID. [![Tenant ID](https://i.stack.imgur.com/f0U0y.png)](https://i.stack.imgur.com/f0U0y.png) 2. `Error Message: Insufficient privileges to complete the operation.` I cant find a Scope in your example e.g: ``` from O365 import Account CLIENT_ID = 'xxxx' SECRET_ID = 'xxxx' TENANT_ID = 'xxxx' credentials = (CLIENT_ID, SECRET_ID) scopes = ['https://graph.microsoft.com/Calendar.ReadWrite', 'https://graph.microsoft.com/User.Read', 'https://graph.microsoft.com/offline_access'] account = Account(credentials, tenant_id=TENANT_ID) if account.authenticate(scopes=scopes): print('Authenticated!') ``` you can [check all Scopes here](https://learn.microsoft.com/en-us/graph/api/user-list-calendars?view=graph-rest-1.0&tabs=http) 3 . `Error Message: /me request is only valid with delegated authentication flow.` I also assume a scope error here. General recommendations: * Add "offline\_access" as a scope - this way you don't need to log in for each run. * Set each scope as delegated - this limits the rights on user level - which is a reduced security risk for a company.
For me, joining [Microsoft Developer Program](https://developer.microsoft.com/en-us/microsoft-365/dev-program) and using its azure directory fixed issues.
45,402,049
I've been working on a website for the past year and used python and flask to built it. Recently I encountered a lot of errors and problems and decided to start a new project (pyCharm). I figured I could copy pieces of code into the new project until I encountered a problem and then I'll know what the problem is. I created three new files as follows: **init**.py ``` from flask import Flask app = Flask(__name__) app.config.from_object('config') ``` config.py ``` SECRET_KEY = 'you-will-never-guess' ``` run.py ``` from app import app app.run() ``` If I run this however, the old website shows up (I expected it to be an empty page). How do I start a clean new flask project?
2017/07/30
[ "https://Stackoverflow.com/questions/45402049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8380994/" ]
Move the `if` outside the `echo` and assign it to a variable, then use the variable in the `echo`. I'd also use ternary operator for this. It also looks like you are comparing the full array, not the index you want to be comparing. Try: ``` while ($row = $result->fetch_assoc()) { $style = $row['move'] > 0 ? ' style="color:green;"' : ''; $row['move'] = $row['move'] == 0 ? '-' : $row['move']; echo "<tr><td style='text-align:left'>".$row["rank"]."</td><td style='text-align:left'>".$row["team_name"]."</td><td>".$row["record"]."</td><td>".$row["average"]."</td><td{$style}>".$row["move"]."</td><td>".$row["hi"]."/".$row["lo"]."</td></tr>"; } ``` The `?:` is known as [`ternary operator`](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary) it is a shorthand conditional. You can read more here, <https://en.wikipedia.org/wiki/%3F:#PHP>.
Untested, but I think this will work: ``` while ($row = $result->fetch_assoc()) { echo "<tr><td style='text-align:left'>".$row["rank"]."</td><td style='text-align:left'>".$row["team_name"]."</td><td>".$row["record"]."</td><td>".$row["average"]."</td><td ".($row["move"] > 0 ? 'style="color:green;"' : '').">".$row["move"]."</td><td>".$row["hi"]."/".$row["lo"]."</td></tr>"; } ``` This expression: ``` ($row["move"] > 0 ? 'style="color:green;"' : '') ``` returns `'style="color:green"'` if `$row["move"] > 0` and `''` otherwise. (It uses the "ternary operator.") **EDIT** Changed to `$row["move"]` above per @chris85's comment.
45,402,049
I've been working on a website for the past year and used python and flask to built it. Recently I encountered a lot of errors and problems and decided to start a new project (pyCharm). I figured I could copy pieces of code into the new project until I encountered a problem and then I'll know what the problem is. I created three new files as follows: **init**.py ``` from flask import Flask app = Flask(__name__) app.config.from_object('config') ``` config.py ``` SECRET_KEY = 'you-will-never-guess' ``` run.py ``` from app import app app.run() ``` If I run this however, the old website shows up (I expected it to be an empty page). How do I start a clean new flask project?
2017/07/30
[ "https://Stackoverflow.com/questions/45402049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8380994/" ]
Untested, but I think this will work: ``` while ($row = $result->fetch_assoc()) { echo "<tr><td style='text-align:left'>".$row["rank"]."</td><td style='text-align:left'>".$row["team_name"]."</td><td>".$row["record"]."</td><td>".$row["average"]."</td><td ".($row["move"] > 0 ? 'style="color:green;"' : '').">".$row["move"]."</td><td>".$row["hi"]."/".$row["lo"]."</td></tr>"; } ``` This expression: ``` ($row["move"] > 0 ? 'style="color:green;"' : '') ``` returns `'style="color:green"'` if `$row["move"] > 0` and `''` otherwise. (It uses the "ternary operator.") **EDIT** Changed to `$row["move"]` above per @chris85's comment.
Try instead of: ``` if($row > 0) {echo 'style="color:green;"';} ``` a shorter if statement: ``` $Color = ($row > 0 )? "green" : "red"; echo 'style="color:'.$Color.';"'; ```
45,402,049
I've been working on a website for the past year and used python and flask to built it. Recently I encountered a lot of errors and problems and decided to start a new project (pyCharm). I figured I could copy pieces of code into the new project until I encountered a problem and then I'll know what the problem is. I created three new files as follows: **init**.py ``` from flask import Flask app = Flask(__name__) app.config.from_object('config') ``` config.py ``` SECRET_KEY = 'you-will-never-guess' ``` run.py ``` from app import app app.run() ``` If I run this however, the old website shows up (I expected it to be an empty page). How do I start a clean new flask project?
2017/07/30
[ "https://Stackoverflow.com/questions/45402049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8380994/" ]
Move the `if` outside the `echo` and assign it to a variable, then use the variable in the `echo`. I'd also use ternary operator for this. It also looks like you are comparing the full array, not the index you want to be comparing. Try: ``` while ($row = $result->fetch_assoc()) { $style = $row['move'] > 0 ? ' style="color:green;"' : ''; $row['move'] = $row['move'] == 0 ? '-' : $row['move']; echo "<tr><td style='text-align:left'>".$row["rank"]."</td><td style='text-align:left'>".$row["team_name"]."</td><td>".$row["record"]."</td><td>".$row["average"]."</td><td{$style}>".$row["move"]."</td><td>".$row["hi"]."/".$row["lo"]."</td></tr>"; } ``` The `?:` is known as [`ternary operator`](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary) it is a shorthand conditional. You can read more here, <https://en.wikipedia.org/wiki/%3F:#PHP>.
Try instead of: ``` if($row > 0) {echo 'style="color:green;"';} ``` a shorter if statement: ``` $Color = ($row > 0 )? "green" : "red"; echo 'style="color:'.$Color.';"'; ```
53,178,013
I have a project for which I'd now like to use pipenv. I want to symlink this from my main bin directory, so I can run it from another directory (where it interacts with local files) but nevertheless run it in the pipenv with the appropriately installed files. Can I do something like ``` pipenv run python /PATH/TO/MY/CODE/foo.py localfile.conf ``` Or is that not going to pick up the pipenv defined in /PATH/TO/MY/CODE/Pipenv ?
2018/11/06
[ "https://Stackoverflow.com/questions/53178013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8482/" ]
Not sure if this was relevant with the version of pipenv you used in 2018, but as of current versions you can use the [PIPENV\_PIPFILE](https://pipenv.kennethreitz.org/en/latest/advanced/#pipenv.environments.PIPENV_PIPFILE) environment variable. You will end up with a wrapper shell script that looks something like: ```sh export PIPENV_PIPFILE=/my/project/dir/Pipfile exec pipenv run command ... ``` (Answering even though I'm half a year late because this was the first relevant search result, so I can find it again next time.)
pipenv is a wrapper for virtualenv which keeps the virtualenv-files in some folder in your home directory. I found them in `/home/MYUSERNAME/.local/share/virtualenvs`. So i wrote a `small_script.sh`: ``` #!/bin/bash source /home/MYUSERNAME/.local/share/virtualenvs/MYCODE-9as8Da87/bin/activate python /PATH/TO/MY/CODE/foo.py localfile.conf deactivate ``` It activates the virtualenv for itself, then runs your python code in your local directory and finally deactivates the virtualenv. You can replace `localfile.conf` by `$@` which allows you to run `./small_script.sh localfile.conf`.
1,976,622
I'm using python-dbus and cherrypy to monitor USB devices and provide a REST service that will maintain status on the inserted USB devices. I have written and debugged these services independently, and they work as expected. Now, I'm merging the services into a single application. My problem is: I cannot seem to get both services ( cherrypy and dbus ) to start together. One or the other blocks or goes out of scope, or doesn't get initialized. I've tried encapsulating each in its own thread, and just call start on them. This has some bizarre issues. ``` class RESTThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) cherrypy.quickstart(USBRest()) class DBUSThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): DBusGMainLoop(set_as_default=True) loop = gobject.MainLoop() DeviceAddedListener() print 'Starting DBus' loop.run() print 'DBus Python Started' if __name__ == '__main__': # Start up REST print 'Starting REST' rs = RESTThread() rs.start() db = DBUSThread() db.start() #cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) #cherrypy.quickstart(USBRest()) while True: x = 1 ``` When this code is run, the cherrypy code doesn't fully initialize. When a USB device is inserted, cherrypy continues to initialize ( as if the threads are linked somehow ), but doesn't work ( doesn't serve up data or even make connections on the port ) I've looked at cherrypys wiki pages but haven't found a way to startup cherrypy in such a way that it inits, and returns, so I can init the DBus stuff an be able to get this out the door. My ultimate question is: Is there a way to get cherrypy to start and not block but continue working? I want to get rid of the threads in this example and init both cherrypy and dbus in the main thread.
2009/12/29
[ "https://Stackoverflow.com/questions/1976622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179157/" ]
You should be able to use .NET's Reflection to analyze your application AppDomain(s) and dump a list of loaded assemblies and locations. ``` var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in loadedAssemblies) { Console.WriteLine(assembly.GetName().Name); Console.WriteLine(assembly.Location); } ```
Check out [`AppDomain.GetAssemblies`](http://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx) ``` For Each Ass As Reflection.Assembly In CurrentDomain.GetAssemblies() Console.WriteLine(Ass.ToString()) Next ```
1,976,622
I'm using python-dbus and cherrypy to monitor USB devices and provide a REST service that will maintain status on the inserted USB devices. I have written and debugged these services independently, and they work as expected. Now, I'm merging the services into a single application. My problem is: I cannot seem to get both services ( cherrypy and dbus ) to start together. One or the other blocks or goes out of scope, or doesn't get initialized. I've tried encapsulating each in its own thread, and just call start on them. This has some bizarre issues. ``` class RESTThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) cherrypy.quickstart(USBRest()) class DBUSThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): DBusGMainLoop(set_as_default=True) loop = gobject.MainLoop() DeviceAddedListener() print 'Starting DBus' loop.run() print 'DBus Python Started' if __name__ == '__main__': # Start up REST print 'Starting REST' rs = RESTThread() rs.start() db = DBUSThread() db.start() #cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) #cherrypy.quickstart(USBRest()) while True: x = 1 ``` When this code is run, the cherrypy code doesn't fully initialize. When a USB device is inserted, cherrypy continues to initialize ( as if the threads are linked somehow ), but doesn't work ( doesn't serve up data or even make connections on the port ) I've looked at cherrypys wiki pages but haven't found a way to startup cherrypy in such a way that it inits, and returns, so I can init the DBus stuff an be able to get this out the door. My ultimate question is: Is there a way to get cherrypy to start and not block but continue working? I want to get rid of the threads in this example and init both cherrypy and dbus in the main thread.
2009/12/29
[ "https://Stackoverflow.com/questions/1976622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179157/" ]
You should be able to use .NET's Reflection to analyze your application AppDomain(s) and dump a list of loaded assemblies and locations. ``` var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in loadedAssemblies) { Console.WriteLine(assembly.GetName().Name); Console.WriteLine(assembly.Location); } ```
This is answered in another [question](https://stackoverflow.com/questions/458362/how-do-i-list-all-loaded-assemblies) already. The gist of it is use current appdomain to get a list of assemblies and loop through their loader location.
1,976,622
I'm using python-dbus and cherrypy to monitor USB devices and provide a REST service that will maintain status on the inserted USB devices. I have written and debugged these services independently, and they work as expected. Now, I'm merging the services into a single application. My problem is: I cannot seem to get both services ( cherrypy and dbus ) to start together. One or the other blocks or goes out of scope, or doesn't get initialized. I've tried encapsulating each in its own thread, and just call start on them. This has some bizarre issues. ``` class RESTThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) cherrypy.quickstart(USBRest()) class DBUSThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): DBusGMainLoop(set_as_default=True) loop = gobject.MainLoop() DeviceAddedListener() print 'Starting DBus' loop.run() print 'DBus Python Started' if __name__ == '__main__': # Start up REST print 'Starting REST' rs = RESTThread() rs.start() db = DBUSThread() db.start() #cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) #cherrypy.quickstart(USBRest()) while True: x = 1 ``` When this code is run, the cherrypy code doesn't fully initialize. When a USB device is inserted, cherrypy continues to initialize ( as if the threads are linked somehow ), but doesn't work ( doesn't serve up data or even make connections on the port ) I've looked at cherrypys wiki pages but haven't found a way to startup cherrypy in such a way that it inits, and returns, so I can init the DBus stuff an be able to get this out the door. My ultimate question is: Is there a way to get cherrypy to start and not block but continue working? I want to get rid of the threads in this example and init both cherrypy and dbus in the main thread.
2009/12/29
[ "https://Stackoverflow.com/questions/1976622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179157/" ]
You should be able to use .NET's Reflection to analyze your application AppDomain(s) and dump a list of loaded assemblies and locations. ``` var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in loadedAssemblies) { Console.WriteLine(assembly.GetName().Name); Console.WriteLine(assembly.Location); } ```
If I have understood your question, to do a fast deployment you can set in all the references of your project but the Framework ones the setting "Copy Local" to true. This way when you build your application you will have all the needed DLLs at your output directory (well, almost all, references needed by your references won't be copied automatically, so it's best to add them as a local reference too). Hope this helps. If not, just say why, I will try to continue on this.
1,976,622
I'm using python-dbus and cherrypy to monitor USB devices and provide a REST service that will maintain status on the inserted USB devices. I have written and debugged these services independently, and they work as expected. Now, I'm merging the services into a single application. My problem is: I cannot seem to get both services ( cherrypy and dbus ) to start together. One or the other blocks or goes out of scope, or doesn't get initialized. I've tried encapsulating each in its own thread, and just call start on them. This has some bizarre issues. ``` class RESTThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) cherrypy.quickstart(USBRest()) class DBUSThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): DBusGMainLoop(set_as_default=True) loop = gobject.MainLoop() DeviceAddedListener() print 'Starting DBus' loop.run() print 'DBus Python Started' if __name__ == '__main__': # Start up REST print 'Starting REST' rs = RESTThread() rs.start() db = DBUSThread() db.start() #cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) #cherrypy.quickstart(USBRest()) while True: x = 1 ``` When this code is run, the cherrypy code doesn't fully initialize. When a USB device is inserted, cherrypy continues to initialize ( as if the threads are linked somehow ), but doesn't work ( doesn't serve up data or even make connections on the port ) I've looked at cherrypys wiki pages but haven't found a way to startup cherrypy in such a way that it inits, and returns, so I can init the DBus stuff an be able to get this out the door. My ultimate question is: Is there a way to get cherrypy to start and not block but continue working? I want to get rid of the threads in this example and init both cherrypy and dbus in the main thread.
2009/12/29
[ "https://Stackoverflow.com/questions/1976622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179157/" ]
Process Explorer?
Check out [`AppDomain.GetAssemblies`](http://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx) ``` For Each Ass As Reflection.Assembly In CurrentDomain.GetAssemblies() Console.WriteLine(Ass.ToString()) Next ```
1,976,622
I'm using python-dbus and cherrypy to monitor USB devices and provide a REST service that will maintain status on the inserted USB devices. I have written and debugged these services independently, and they work as expected. Now, I'm merging the services into a single application. My problem is: I cannot seem to get both services ( cherrypy and dbus ) to start together. One or the other blocks or goes out of scope, or doesn't get initialized. I've tried encapsulating each in its own thread, and just call start on them. This has some bizarre issues. ``` class RESTThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) cherrypy.quickstart(USBRest()) class DBUSThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): DBusGMainLoop(set_as_default=True) loop = gobject.MainLoop() DeviceAddedListener() print 'Starting DBus' loop.run() print 'DBus Python Started' if __name__ == '__main__': # Start up REST print 'Starting REST' rs = RESTThread() rs.start() db = DBUSThread() db.start() #cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) #cherrypy.quickstart(USBRest()) while True: x = 1 ``` When this code is run, the cherrypy code doesn't fully initialize. When a USB device is inserted, cherrypy continues to initialize ( as if the threads are linked somehow ), but doesn't work ( doesn't serve up data or even make connections on the port ) I've looked at cherrypys wiki pages but haven't found a way to startup cherrypy in such a way that it inits, and returns, so I can init the DBus stuff an be able to get this out the door. My ultimate question is: Is there a way to get cherrypy to start and not block but continue working? I want to get rid of the threads in this example and init both cherrypy and dbus in the main thread.
2009/12/29
[ "https://Stackoverflow.com/questions/1976622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179157/" ]
Process Explorer?
This is answered in another [question](https://stackoverflow.com/questions/458362/how-do-i-list-all-loaded-assemblies) already. The gist of it is use current appdomain to get a list of assemblies and loop through their loader location.
1,976,622
I'm using python-dbus and cherrypy to monitor USB devices and provide a REST service that will maintain status on the inserted USB devices. I have written and debugged these services independently, and they work as expected. Now, I'm merging the services into a single application. My problem is: I cannot seem to get both services ( cherrypy and dbus ) to start together. One or the other blocks or goes out of scope, or doesn't get initialized. I've tried encapsulating each in its own thread, and just call start on them. This has some bizarre issues. ``` class RESTThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) cherrypy.quickstart(USBRest()) class DBUSThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): DBusGMainLoop(set_as_default=True) loop = gobject.MainLoop() DeviceAddedListener() print 'Starting DBus' loop.run() print 'DBus Python Started' if __name__ == '__main__': # Start up REST print 'Starting REST' rs = RESTThread() rs.start() db = DBUSThread() db.start() #cherrypy.config.update({ 'server.socket_host': HVR_Common.DBUS_SERVER_ADDR, 'server.socket_port': HVR_Common.DBUS_SERVER_PORT, }) #cherrypy.quickstart(USBRest()) while True: x = 1 ``` When this code is run, the cherrypy code doesn't fully initialize. When a USB device is inserted, cherrypy continues to initialize ( as if the threads are linked somehow ), but doesn't work ( doesn't serve up data or even make connections on the port ) I've looked at cherrypys wiki pages but haven't found a way to startup cherrypy in such a way that it inits, and returns, so I can init the DBus stuff an be able to get this out the door. My ultimate question is: Is there a way to get cherrypy to start and not block but continue working? I want to get rid of the threads in this example and init both cherrypy and dbus in the main thread.
2009/12/29
[ "https://Stackoverflow.com/questions/1976622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179157/" ]
Process Explorer?
If I have understood your question, to do a fast deployment you can set in all the references of your project but the Framework ones the setting "Copy Local" to true. This way when you build your application you will have all the needed DLLs at your output directory (well, almost all, references needed by your references won't be copied automatically, so it's best to add them as a local reference too). Hope this helps. If not, just say why, I will try to continue on this.
1,777,862
I am trying to rewrite the following program in C instead of C# (which is less portable). It is obvious that "int system ( const char \* command )" will be necessary to complete the program. Starting it with "int main ( int argc, char \* argv[] )" will allow getting the command-line arguments, but there is still a problem that is difficult to understand. How do you successfully escape arguments with spaces in them? In the program below, arguments with spaces in them (example: screensaver.scr "this is a test") will be passed to the script as separate arguments (example: screensaver.scr this is a test) and could easily cause problems. ``` namespace Boids_Screensaver { static class Program { [STAThread] static void Main(string[] args) { System.Diagnostics.Process python = new System.Diagnostics.Process(); python.EnableRaisingEvents = false; python.StartInfo.FileName = "C:\\Python31\\pythonw.exe"; python.StartInfo.Arguments = "boids.pyw"; foreach (string arg in args) { python.StartInfo.Arguments += " " + arg; } python.Start(); } } } ```
2009/11/22
[ "https://Stackoverflow.com/questions/1777862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216356/" ]
Windows is all messed up. Every program has its own rules.
``` screensaver.scr "spaced argument" nonspaced_argument argc = 2 argv[0] = "screensaver.scr" argv[1] = "spaced argument" argv[2] = "nonspaced_argument" ``` Sorry my English :).
1,777,862
I am trying to rewrite the following program in C instead of C# (which is less portable). It is obvious that "int system ( const char \* command )" will be necessary to complete the program. Starting it with "int main ( int argc, char \* argv[] )" will allow getting the command-line arguments, but there is still a problem that is difficult to understand. How do you successfully escape arguments with spaces in them? In the program below, arguments with spaces in them (example: screensaver.scr "this is a test") will be passed to the script as separate arguments (example: screensaver.scr this is a test) and could easily cause problems. ``` namespace Boids_Screensaver { static class Program { [STAThread] static void Main(string[] args) { System.Diagnostics.Process python = new System.Diagnostics.Process(); python.EnableRaisingEvents = false; python.StartInfo.FileName = "C:\\Python31\\pythonw.exe"; python.StartInfo.Arguments = "boids.pyw"; foreach (string arg in args) { python.StartInfo.Arguments += " " + arg; } python.Start(); } } } ```
2009/11/22
[ "https://Stackoverflow.com/questions/1777862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216356/" ]
The correct way to do this under windows is to use [\_spawnv](http://msdn.microsoft.com/en-us/library/7zt1y878(VS.80).aspx) Its equivalent under unix like OSes is `fork()` followed by `execv`.
``` screensaver.scr "spaced argument" nonspaced_argument argc = 2 argv[0] = "screensaver.scr" argv[1] = "spaced argument" argv[2] = "nonspaced_argument" ``` Sorry my English :).
17,161,552
I have read that while writing functions it is good practice to copy the arguments into other variables because it is not always clear whether the variable is immutable or not. [I don't remember where so don't ask]. I have been writing functions according to this. As I understand creating a new variable takes some overhead. It may be small but it is there. So what should be done? Should I be creating new variables or not to hold the arguments? I have read [this](https://stackoverflow.com/questions/8056130/immutable-vs-mutable-types-python) and [this](https://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference). I have confusion regarding as to why float's and int's are immutable if they can be changed this easily? EDIT: I am writing simple functions. I'll post example. I wrote the first one when after I read that in Python arguments should be copied and the second one after I realized by hit-and-trial that it wasn't needed. ``` #When I copied arguments into another variable def zeros_in_fact(num): '''Returns the number of zeros at the end of factorial of num''' temp = num if temp < 0: return 0 fives = 0 while temp: temp /= 5 fives += temp return fives #When I did not copy arguments into another variable def zeros_in_fact(num): '''Returns the number of zeros at the end of factorial of num''' if num < 0: return 0 fives = 0 while num: num /= 5 fives += num return fives ```
2013/06/18
[ "https://Stackoverflow.com/questions/17161552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2235567/" ]
I think it's best to keep it simple in questions like these. The second link in your question is a really good explanation; in summary: Methods take parameters which, as pointed out in that explanation, are passed "by value". The parameters in functions take the value of variables passed in. For primitive types like strings, ints, and floats, the value of the variable is a pointer (the arrows in the following diagram) to a space in memory that represents the number or string. ``` code | memory | an_int = 1 | an_int ----> 1 | ^ another_int = 1 | another_int / ``` When you reassign within the method, you change where the arrow points. ``` an_int = 2 | an_int -------> 2 | another_int --> 1 ``` The numbers themselves don't change, and since those variables have scope only inside the functions, outside the function, the variables passed in remain the same as they were before: 1 and 1. But when you pass in a list or object, for example, you can change the values they point to *outside of the function*. ``` a_list = [1, 2, 3] | 1 2 3 | a_list ->| ^ | ^ | ^ | | 0 2 3 a_list[0] = 0 | a_list ->| ^ | ^ | ^ | ``` Now, you can change where the arrows in the list, or object, point to, but the list's pointer still points to the same list as before. (There should probably actually only be one 2 and 3 in the diagram above for both sets of arrows, but the arrows would have gotten difficult to draw.) So what does the actual code look like? ``` a = 5 def not_change(a): a = 6 not_change(a) print(a) # a is still 5 outside the function b = [1, 2, 3] def change(b): b[0] = 0 print(b) # b is now [0, 2, 3] outside the function ``` Whether you make a copy of the lists and objects you're given (ints and strings don't matter) and thus return new variables or change the ones passed in depends on what functionality you need to provide.
If you are **rebinding** the name then mutability of the object it contains is irrelevant. Only if you perform **mutating** operations must you create a copy. (And if you read between the lines, that indirectly says "don't mutate objects passed to you".)
17,161,552
I have read that while writing functions it is good practice to copy the arguments into other variables because it is not always clear whether the variable is immutable or not. [I don't remember where so don't ask]. I have been writing functions according to this. As I understand creating a new variable takes some overhead. It may be small but it is there. So what should be done? Should I be creating new variables or not to hold the arguments? I have read [this](https://stackoverflow.com/questions/8056130/immutable-vs-mutable-types-python) and [this](https://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference). I have confusion regarding as to why float's and int's are immutable if they can be changed this easily? EDIT: I am writing simple functions. I'll post example. I wrote the first one when after I read that in Python arguments should be copied and the second one after I realized by hit-and-trial that it wasn't needed. ``` #When I copied arguments into another variable def zeros_in_fact(num): '''Returns the number of zeros at the end of factorial of num''' temp = num if temp < 0: return 0 fives = 0 while temp: temp /= 5 fives += temp return fives #When I did not copy arguments into another variable def zeros_in_fact(num): '''Returns the number of zeros at the end of factorial of num''' if num < 0: return 0 fives = 0 while num: num /= 5 fives += num return fives ```
2013/06/18
[ "https://Stackoverflow.com/questions/17161552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2235567/" ]
What you are doing in your code examples involves no noticeable overhead, but it also doesn't accomplish anything because it won't protect you from mutable/immutable problems. The way to think about this is that there are two kinds of things in Python: names and objects. When you do `x = y` you are operating on a name, attaching that name to the object `y`. When you do `x += y` or other augmented assignment operators, you also are binding a name (in addition to doing the operation you use, `+` in this case). Anything else that you do is operating on objects. If the objects are mutable, that may involve changing their state. Ints and floats cannot be changed. What you can do is change what int or float a *name* refers to. If you do ``` x = 3 x = x + 4 ``` You are not changing the int. You are changing the name `x` so that it now is attached to the number 7 instead of the number 3. On the other hand when you do this: ``` x = [] x.append(2) ``` You are changing the list, not just pointing the name at a new object. The difference can be seen when you have multiple names for the same object. ``` >>> x = 2 >>> y = x >>> x = x + 3 # changing the name >>> print x 5 >>> print y # y is not affected 2 >>> x = [] >>> y = x >>> x.append(2) # changing the object >>> print x [2] >>> print y # y is affected [2] ``` Mutating an object means that you alter the object itself, so that *all* names that point to it see the changes. If you just change a name, other names are not affected. The second question you linked to provides more information about how this works in the context of function arguments. The augmented assignment operators (`+=`, `*=`, etc.) are a bit trickier since they operate on names but may also mutate objects at the same time. You can find other questions on StackOverflow about how this works.
If you are **rebinding** the name then mutability of the object it contains is irrelevant. Only if you perform **mutating** operations must you create a copy. (And if you read between the lines, that indirectly says "don't mutate objects passed to you".)
17,161,552
I have read that while writing functions it is good practice to copy the arguments into other variables because it is not always clear whether the variable is immutable or not. [I don't remember where so don't ask]. I have been writing functions according to this. As I understand creating a new variable takes some overhead. It may be small but it is there. So what should be done? Should I be creating new variables or not to hold the arguments? I have read [this](https://stackoverflow.com/questions/8056130/immutable-vs-mutable-types-python) and [this](https://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference). I have confusion regarding as to why float's and int's are immutable if they can be changed this easily? EDIT: I am writing simple functions. I'll post example. I wrote the first one when after I read that in Python arguments should be copied and the second one after I realized by hit-and-trial that it wasn't needed. ``` #When I copied arguments into another variable def zeros_in_fact(num): '''Returns the number of zeros at the end of factorial of num''' temp = num if temp < 0: return 0 fives = 0 while temp: temp /= 5 fives += temp return fives #When I did not copy arguments into another variable def zeros_in_fact(num): '''Returns the number of zeros at the end of factorial of num''' if num < 0: return 0 fives = 0 while num: num /= 5 fives += num return fives ```
2013/06/18
[ "https://Stackoverflow.com/questions/17161552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2235567/" ]
I think it's best to keep it simple in questions like these. The second link in your question is a really good explanation; in summary: Methods take parameters which, as pointed out in that explanation, are passed "by value". The parameters in functions take the value of variables passed in. For primitive types like strings, ints, and floats, the value of the variable is a pointer (the arrows in the following diagram) to a space in memory that represents the number or string. ``` code | memory | an_int = 1 | an_int ----> 1 | ^ another_int = 1 | another_int / ``` When you reassign within the method, you change where the arrow points. ``` an_int = 2 | an_int -------> 2 | another_int --> 1 ``` The numbers themselves don't change, and since those variables have scope only inside the functions, outside the function, the variables passed in remain the same as they were before: 1 and 1. But when you pass in a list or object, for example, you can change the values they point to *outside of the function*. ``` a_list = [1, 2, 3] | 1 2 3 | a_list ->| ^ | ^ | ^ | | 0 2 3 a_list[0] = 0 | a_list ->| ^ | ^ | ^ | ``` Now, you can change where the arrows in the list, or object, point to, but the list's pointer still points to the same list as before. (There should probably actually only be one 2 and 3 in the diagram above for both sets of arrows, but the arrows would have gotten difficult to draw.) So what does the actual code look like? ``` a = 5 def not_change(a): a = 6 not_change(a) print(a) # a is still 5 outside the function b = [1, 2, 3] def change(b): b[0] = 0 print(b) # b is now [0, 2, 3] outside the function ``` Whether you make a copy of the lists and objects you're given (ints and strings don't matter) and thus return new variables or change the ones passed in depends on what functionality you need to provide.
What you are doing in your code examples involves no noticeable overhead, but it also doesn't accomplish anything because it won't protect you from mutable/immutable problems. The way to think about this is that there are two kinds of things in Python: names and objects. When you do `x = y` you are operating on a name, attaching that name to the object `y`. When you do `x += y` or other augmented assignment operators, you also are binding a name (in addition to doing the operation you use, `+` in this case). Anything else that you do is operating on objects. If the objects are mutable, that may involve changing their state. Ints and floats cannot be changed. What you can do is change what int or float a *name* refers to. If you do ``` x = 3 x = x + 4 ``` You are not changing the int. You are changing the name `x` so that it now is attached to the number 7 instead of the number 3. On the other hand when you do this: ``` x = [] x.append(2) ``` You are changing the list, not just pointing the name at a new object. The difference can be seen when you have multiple names for the same object. ``` >>> x = 2 >>> y = x >>> x = x + 3 # changing the name >>> print x 5 >>> print y # y is not affected 2 >>> x = [] >>> y = x >>> x.append(2) # changing the object >>> print x [2] >>> print y # y is affected [2] ``` Mutating an object means that you alter the object itself, so that *all* names that point to it see the changes. If you just change a name, other names are not affected. The second question you linked to provides more information about how this works in the context of function arguments. The augmented assignment operators (`+=`, `*=`, etc.) are a bit trickier since they operate on names but may also mutate objects at the same time. You can find other questions on StackOverflow about how this works.
73,419,189
I am learning continue statement in python while loop. If I run a following code, the output shows from 2 instead of 1. ``` a = 1 while a <= 8: a += 1 if a == 5: continue print(a) ```
2022/08/19
[ "https://Stackoverflow.com/questions/73419189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507620/" ]
You can use the HPA (Horizontal Pod Autoscaler). Here is what the typical yaml configuration looks like. ``` apiVersion: autoscaling/v1 kind: HorizontalPodAutoscaler metadata: name: hpa_name spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: deployment_name_to_autoscale minReplicas: 1 maxReplicas: 3 targetCPUUtilizationPercentage: 80 ``` You can monitor the scaling using *kubectl get hpa*
In GKE, you can achieve this with [Horizontal Pod Autoscaler (HPA)](https://cloud.google.com/kubernetes-engine/docs/concepts/horizontalpodautoscaler). The autoscaling event can be configured to be triggered by system (eg. cpu or memory) or custom metrics (eg. pubsub queued messages count). You can also set the minimum and maximum number of pods to scale up to. Here is a link from GCP for a [sample HPA yaml file](https://cloud.google.com/kubernetes-engine/docs/how-to/horizontal-pod-autoscaling#kubectl-apply)
73,419,189
I am learning continue statement in python while loop. If I run a following code, the output shows from 2 instead of 1. ``` a = 1 while a <= 8: a += 1 if a == 5: continue print(a) ```
2022/08/19
[ "https://Stackoverflow.com/questions/73419189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507620/" ]
In GKE, you can achieve this with [Horizontal Pod Autoscaler (HPA)](https://cloud.google.com/kubernetes-engine/docs/concepts/horizontalpodautoscaler). The autoscaling event can be configured to be triggered by system (eg. cpu or memory) or custom metrics (eg. pubsub queued messages count). You can also set the minimum and maximum number of pods to scale up to. Here is a link from GCP for a [sample HPA yaml file](https://cloud.google.com/kubernetes-engine/docs/how-to/horizontal-pod-autoscaling#kubectl-apply)
Here is another example for using HPA with external metric (e.g cloud pub/sub): ``` apiVersion: autoscaling/v2beta2 kind: HorizontalPodAutoscaler metadata: name: your-hpa-name spec: minReplicas: 1 maxReplicas: 4 metrics: - external: metric: name: pubsub.googleapis.com|subscription|num_undelivered_messages selector: matchLabels: resource.labels.subscription_id: your-pubsub-subscirbtion-name target: type: AverageValue averageValue: 200 type: External scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: your-deployment-name ```
73,419,189
I am learning continue statement in python while loop. If I run a following code, the output shows from 2 instead of 1. ``` a = 1 while a <= 8: a += 1 if a == 5: continue print(a) ```
2022/08/19
[ "https://Stackoverflow.com/questions/73419189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507620/" ]
You can use the HPA (Horizontal Pod Autoscaler). Here is what the typical yaml configuration looks like. ``` apiVersion: autoscaling/v1 kind: HorizontalPodAutoscaler metadata: name: hpa_name spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: deployment_name_to_autoscale minReplicas: 1 maxReplicas: 3 targetCPUUtilizationPercentage: 80 ``` You can monitor the scaling using *kubectl get hpa*
> > Menu > GKE > Workloads > click on your deployment > 3 dots (more > actions) > Actions > Autoscale > set metrics > Save > > >
73,419,189
I am learning continue statement in python while loop. If I run a following code, the output shows from 2 instead of 1. ``` a = 1 while a <= 8: a += 1 if a == 5: continue print(a) ```
2022/08/19
[ "https://Stackoverflow.com/questions/73419189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507620/" ]
> > Menu > GKE > Workloads > click on your deployment > 3 dots (more > actions) > Actions > Autoscale > set metrics > Save > > >
Here is another example for using HPA with external metric (e.g cloud pub/sub): ``` apiVersion: autoscaling/v2beta2 kind: HorizontalPodAutoscaler metadata: name: your-hpa-name spec: minReplicas: 1 maxReplicas: 4 metrics: - external: metric: name: pubsub.googleapis.com|subscription|num_undelivered_messages selector: matchLabels: resource.labels.subscription_id: your-pubsub-subscirbtion-name target: type: AverageValue averageValue: 200 type: External scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: your-deployment-name ```
73,419,189
I am learning continue statement in python while loop. If I run a following code, the output shows from 2 instead of 1. ``` a = 1 while a <= 8: a += 1 if a == 5: continue print(a) ```
2022/08/19
[ "https://Stackoverflow.com/questions/73419189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507620/" ]
You can use the HPA (Horizontal Pod Autoscaler). Here is what the typical yaml configuration looks like. ``` apiVersion: autoscaling/v1 kind: HorizontalPodAutoscaler metadata: name: hpa_name spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: deployment_name_to_autoscale minReplicas: 1 maxReplicas: 3 targetCPUUtilizationPercentage: 80 ``` You can monitor the scaling using *kubectl get hpa*
Here is another example for using HPA with external metric (e.g cloud pub/sub): ``` apiVersion: autoscaling/v2beta2 kind: HorizontalPodAutoscaler metadata: name: your-hpa-name spec: minReplicas: 1 maxReplicas: 4 metrics: - external: metric: name: pubsub.googleapis.com|subscription|num_undelivered_messages selector: matchLabels: resource.labels.subscription_id: your-pubsub-subscirbtion-name target: type: AverageValue averageValue: 200 type: External scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: your-deployment-name ```
55,599,993
I want to write a program in Python which takes a C program as input, executes it against the test cases which are also as inputs and print the output for each test case. I am using Windows I tried with subprocess.run but it is not accepting inputs at runtime (i.e dynamically) ```py from subprocess import * p1=run("rah.exe",input=input(),stdout=PIPE,stderr=STDOUT,universal_newlines=True) print(p1.stdout) ``` C code: ```c #include<stdio.h> void main() { printf("Enter a number"); int a; scanf("%d",&a); for(int i=0;i<a;i++) { printf("%d",i); } } ``` Expected Output on python idle: ``` Enter a number 5 01234 ``` Actual Output: ``` 5 Enter a number 01234 ```
2019/04/09
[ "https://Stackoverflow.com/questions/55599993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11315221/" ]
I agree with @juanpa.arrivillaga's suggestion. You can use `subprocess.Popen` and `communicate()` for that: ``` import subprocess import sys p = subprocess.Popen('rah.exe', stdout=sys.stdout, stderr=sys.stderr) p.communicate() ``` **Update:** The script above won't work on IDLE because IDLE changes the IO objects `sys.stdout, sys.stderr` which breaks the `fileno()` function. If possible, you should put the code into the a python file (for example `script.py`) and then run it from the Windows command line using the command: ``` python script.py ``` or if not, you can do something similar to IDLE on the command line on Windows by entering the command: ``` python ``` which will start a console similar to IDLE but without the changed IO objects. There you should enter the following lines to get the similar result: ``` import subprocess import sys _ = subprocess.Popen('rah.exe', stdout=sys.stdout,stderr=sys.stderr).communicate() ```
> > I tried with subprocess.run but it is not accepting inputs at runtime (i.e dynamically) > > > If you don't do anything, the subprocess will simply inherit their parent's stdin. That aside, because you're intercepting the output of the subprocess and printing it afterwards you won't get the interleaving you're writing in your "expected output": the input is not going to echo back, so you just get what's being written to the subprocess's stdout, which is both printfs. If you want to dynamically interact with the subprocess, you'll have to create a proper Popen object, pipe everything, and use stdin.write() and stdout.read(). And because you'll have to deal with pipe buffering it's going to be painful. If you're going to do that a lot, you may want to take a look at [pexpect](https://pexpect.readthedocs.io/en/stable/): "interactive" subprocesses is pretty much its bread and butter. This about works: ```py from subprocess import Popen, PIPE from fcntl import fcntl, F_GETFL, F_SETFL from os import O_NONBLOCK import select p = Popen(['./a.out'], stdin=PIPE, stdout=PIPE) fcntl(p.stdout, F_SETFL, fcntl(p.stdout, F_GETFL) | O_NONBLOCK) select.select([p.stdout], [], []) print(p.stdout.read().decode()) d = input() p.stdin.write(d.encode() + b'\n') p.stdin.flush() select.select([p.stdout], [], []) print(p.stdout.read().decode()) ``` ```c #include<stdio.h> int main() { printf("Enter a number"); fflush(stdout); int a; scanf("%d",&a); for(int i=0;i<a;i++) { printf("%d",i); } fflush(stdout); return 0; } ``` Note that it requires explicitly flushing the subprocess's stdout and the writing *and* configuring the stdout to be non-blocking in the caller *and* explicitly select()ing for data on the pipe. Alternatively you could create the subprocess with unbuffered pipes (bufsize=0) then select() and read bytes one by one.
54,371,847
I'm trying to install tensorflow but python 3.7 does not support that, so I want to get python 3.6 instead without using anaconda. So any suggestion please ?
2019/01/25
[ "https://Stackoverflow.com/questions/54371847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10968495/" ]
I have done this multiple times. My first tip is use [virtual environments](https://realpython.com/python-virtual-environments-a-primer/). That way you can use python 3.6 for what ever project requires that version of python, and python 3.7 for other projects that need that version. However on windows these are the best steps: 1.) Uninstall python 3.7 from your computer using command prompt 2.) Double check in your program files folder to see if there are any lingering python 3.7 folders you need to delete. Do not delete any site-packages folders or you will need to reinstall the packages you have deleted. 3.) Go to <https://www.python.org/downloads/> and download and install python 3.6 and make sure you add it to your path when installing 4.) Open command prompt and type `python -V` or simply `python` and check what version you have installed. If you type just `python` you can use the command `exit()` after to exit. But I suggest starting to use [Virtual Environments](https://realpython.com/python-virtual-environments-a-primer/) to avoid this issue or downloading different python versions based on specific library needs. **UPDATE** Regarding the point of not deleting site-packages folders. Some of your packages may not be compatible with lower versions of python. This may not be a huge issue for some people, but it is best to check your most commonly used packages to see their compatible python versions before continuing with the downgrade
Consider using [pyenv-win](https://github.com/pyenv-win/pyenv-win) in order to manage your global and (per-project) local Python versions. However, it only works with the Windows Subsystem for Linux.
54,371,847
I'm trying to install tensorflow but python 3.7 does not support that, so I want to get python 3.6 instead without using anaconda. So any suggestion please ?
2019/01/25
[ "https://Stackoverflow.com/questions/54371847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10968495/" ]
Consider using [pyenv-win](https://github.com/pyenv-win/pyenv-win) in order to manage your global and (per-project) local Python versions. However, it only works with the Windows Subsystem for Linux.
This solved it for me. Run the following via anaconda prompt 1. conda create -n py36 python=3.6 2. activate py36 3. Select py36 on Anaconda navigator and launch spyder
54,371,847
I'm trying to install tensorflow but python 3.7 does not support that, so I want to get python 3.6 instead without using anaconda. So any suggestion please ?
2019/01/25
[ "https://Stackoverflow.com/questions/54371847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10968495/" ]
I have done this multiple times. My first tip is use [virtual environments](https://realpython.com/python-virtual-environments-a-primer/). That way you can use python 3.6 for what ever project requires that version of python, and python 3.7 for other projects that need that version. However on windows these are the best steps: 1.) Uninstall python 3.7 from your computer using command prompt 2.) Double check in your program files folder to see if there are any lingering python 3.7 folders you need to delete. Do not delete any site-packages folders or you will need to reinstall the packages you have deleted. 3.) Go to <https://www.python.org/downloads/> and download and install python 3.6 and make sure you add it to your path when installing 4.) Open command prompt and type `python -V` or simply `python` and check what version you have installed. If you type just `python` you can use the command `exit()` after to exit. But I suggest starting to use [Virtual Environments](https://realpython.com/python-virtual-environments-a-primer/) to avoid this issue or downloading different python versions based on specific library needs. **UPDATE** Regarding the point of not deleting site-packages folders. Some of your packages may not be compatible with lower versions of python. This may not be a huge issue for some people, but it is best to check your most commonly used packages to see their compatible python versions before continuing with the downgrade
This solved it for me. Run the following via anaconda prompt 1. conda create -n py36 python=3.6 2. activate py36 3. Select py36 on Anaconda navigator and launch spyder
66,975,127
I'm trying to install a simple Django package in a Docker container. Here is my dockerfile ``` FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY Pipfile Pipfile.lock /app/ RUN pip install pipenv && pipenv install --system COPY . /app/ ``` And here is my docker-compose: ``` version: '3.7' services: web: build: . command: python /app/manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - /Users/ruslaniv/Documents/Docker/djangoapp:/var/lib/postgresql/data/ environment: - POSTGRES_USER=XXX - POSTGRES_PASSWORD=XXX - POSTGRES_DB=djangoapp volumes: djangoapp: ``` So, I start my container with ``` docker-compose up ``` then install a package and rebuild an image ``` docker-compose exec web pipenv install django-crispy-forms docker-compose down docker-compose up -d --build ``` Then I add `'crispy_forms'` into local `settings.py` and register crispy forms tags in a local html file with `{% load crispy_forms_tags %}` and then use them for the form with `{{ form|crispy }}` But the form is not rendered properly. Since the package itself and its usage are very simple I think there is a problem with installing the package in a container. So the question is how to properly install a Django package in a Docker container and am I doing it properly?
2021/04/06
[ "https://Stackoverflow.com/questions/66975127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3678257/" ]
you can use [present](https://laravel.com/docs/8.x/validation#rule-present) validation The field under validation must be present in the input data but can be empty. ``` 'topics' => 'present|array' ```
Validating array based form input fields doesn't have to be a pain. You may use "dot notation" to validate attributes within an array. For example, if the incoming HTTP request contains a `photos[profile]` field, you may validate it like so: ``` use Illuminate\Support\Facades\Validator; $validator = Validator::make($request->all(), [ 'photos.profile' => 'required|image', ]); ``` You may also validate each element of an array. For example, to validate that each email in a given array input field is unique, you may do the following: ``` $validator = Validator::make($request->all(), [ 'person.*.email' => 'email|unique:users', 'person.*.first_name' => 'required_with:person.*.last_name', ]); ``` In your case, if you want to validate that the elements inside your array are not empty, the following would suffice: ``` 'topics' => 'required|array', 'topics.*' => 'sometimes|integer', // <- for example. ```
47,370,718
Suppose we have * an n-dimensional numpy.array A * a numpy.array B with dtype=int and shape of (n, m) How do I index A by B so that the result is an array of shape (m,), with values taken from the positions indicated by the columns of B? For example, consider this code that does what I want when B is a python list: ``` >>> a = np.arange(27).reshape(3,3,3) >>> a[[0, 1, 2], [0, 0, 0], [1, 1, 2]] array([ 1, 10, 20]) # the result we're after >>> bl = [[0, 1, 2], [0, 0, 0], [1, 1, 2]] >>> a[bl] array([ 1, 10, 20]) # also works when indexing with a python list >>> a[bl].shape (3,) ``` However, when B is a numpy array, the result is different: ``` >>> b = np.array(bl) >>> a[b].shape (3, 3, 3, 3) ``` Now, I can get the desired result by casting B into a tuple, but surely that cannot be the proper/idiomatic way to do it? ``` >>> a[tuple(b)] array([ 1, 10, 20]) ``` Is there a numpy function to achieve the same without casting B to a tuple?
2017/11/18
[ "https://Stackoverflow.com/questions/47370718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073784/" ]
One alternative would be converting to linear indices and then index with `np.take` or index into its flattened version - ``` np.take(a,np.ravel_multi_index(b, a.shape)) a.flat[np.ravel_multi_index(b, a.shape)] ``` **Custom `np.ravel_multi_index` for performance boost** We could implement a custom version to simulate the behaviour of `np.ravel_multi_index` to boost the performance, like so - ``` def ravel_index(b, shp): return np.concatenate((np.asarray(shp[1:])[::-1].cumprod()[::-1],[1])).dot(b) ``` Using it, the desired output would be found in two ways - ``` np.take(a,ravel_index(b, a.shape)) a.flat[ravel_index(b, a.shape)] ``` ### Benchmarking Additionall incorporating `tuple` based method from the question and `map` based one from @Kanak's post. Case #1 : dims = 3 ``` In [23]: a = np.random.randint(0,9,([20]*3)) In [24]: b = np.random.randint(0,20,(a.ndim,1000000)) In [25]: %timeit a[tuple(b)] ...: %timeit a[map(np.ravel, b)] ...: %timeit np.take(a,np.ravel_multi_index(b, a.shape)) ...: %timeit a.flat[np.ravel_multi_index(b, a.shape)] ...: %timeit np.take(a,ravel_index(b, a.shape)) ...: %timeit a.flat[ravel_index(b, a.shape)] 100 loops, best of 3: 6.56 ms per loop 100 loops, best of 3: 6.58 ms per loop 100 loops, best of 3: 6.95 ms per loop 100 loops, best of 3: 9.17 ms per loop 100 loops, best of 3: 6.31 ms per loop 100 loops, best of 3: 8.52 ms per loop ``` Case #2 : dims = 6 ``` In [29]: a = np.random.randint(0,9,([10]*6)) In [30]: b = np.random.randint(0,10,(a.ndim,1000000)) In [31]: %timeit a[tuple(b)] ...: %timeit a[map(np.ravel, b)] ...: %timeit np.take(a,np.ravel_multi_index(b, a.shape)) ...: %timeit a.flat[np.ravel_multi_index(b, a.shape)] ...: %timeit np.take(a,ravel_index(b, a.shape)) ...: %timeit a.flat[ravel_index(b, a.shape)] 10 loops, best of 3: 40.9 ms per loop 10 loops, best of 3: 40 ms per loop 10 loops, best of 3: 20 ms per loop 10 loops, best of 3: 29.9 ms per loop 100 loops, best of 3: 15.7 ms per loop 10 loops, best of 3: 25.8 ms per loop ``` Case #3 : dims = 10 ``` In [32]: a = np.random.randint(0,9,([4]*10)) In [33]: b = np.random.randint(0,4,(a.ndim,1000000)) In [34]: %timeit a[tuple(b)] ...: %timeit a[map(np.ravel, b)] ...: %timeit np.take(a,np.ravel_multi_index(b, a.shape)) ...: %timeit a.flat[np.ravel_multi_index(b, a.shape)] ...: %timeit np.take(a,ravel_index(b, a.shape)) ...: %timeit a.flat[ravel_index(b, a.shape)] 10 loops, best of 3: 60.7 ms per loop 10 loops, best of 3: 60.1 ms per loop 10 loops, best of 3: 27.8 ms per loop 10 loops, best of 3: 38 ms per loop 100 loops, best of 3: 18.7 ms per loop 10 loops, best of 3: 29.3 ms per loop ``` So, it makes sense to look for alternatives when working with higher-dimensional inputs and with large data.
Another alternative that fits your need involves the use of [`np.ravel`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html) ``` >>> a[map(np.ravel, b)] array([ 1, 10, 20]) ``` However not fully [`numpy`](http://www.numpy.org/)-based. --- ***Performance-concerns.*** *Updated following the comments below.* Be that as it may, your approach is better than mine, but not better than any of @Divakar's. ``` import numpy as np import timeit a = np.arange(27).reshape(3,3,3) bl = [[0, 1, 2], [0, 0, 0], [1, 1, 2]] b = np.array(bl) imps = "from __main__ import np,a,b" reps = 100000 tup_cas_t = timeit.Timer("a[tuple(b)]", imps).timeit(reps) map_rav_t = timeit.Timer("a[map(np.ravel, b)]", imps).timeit(reps) fla_rp1_t = timeit.Timer("np.take(a,np.ravel_multi_index(b, a.shape))", imps).timeit(reps) fla_rp2_t = timeit.Timer("a.flat[np.ravel_multi_index(b, a.shape)]", imps).timeit(reps) print tup_cas_t/map_rav_t ## 0.505382211881 print tup_cas_t/fla_rp1_t ## 1.18185817386 print tup_cas_t/fla_rp2_t ## 1.71288705886 ```
47,370,718
Suppose we have * an n-dimensional numpy.array A * a numpy.array B with dtype=int and shape of (n, m) How do I index A by B so that the result is an array of shape (m,), with values taken from the positions indicated by the columns of B? For example, consider this code that does what I want when B is a python list: ``` >>> a = np.arange(27).reshape(3,3,3) >>> a[[0, 1, 2], [0, 0, 0], [1, 1, 2]] array([ 1, 10, 20]) # the result we're after >>> bl = [[0, 1, 2], [0, 0, 0], [1, 1, 2]] >>> a[bl] array([ 1, 10, 20]) # also works when indexing with a python list >>> a[bl].shape (3,) ``` However, when B is a numpy array, the result is different: ``` >>> b = np.array(bl) >>> a[b].shape (3, 3, 3, 3) ``` Now, I can get the desired result by casting B into a tuple, but surely that cannot be the proper/idiomatic way to do it? ``` >>> a[tuple(b)] array([ 1, 10, 20]) ``` Is there a numpy function to achieve the same without casting B to a tuple?
2017/11/18
[ "https://Stackoverflow.com/questions/47370718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073784/" ]
One alternative would be converting to linear indices and then index with `np.take` or index into its flattened version - ``` np.take(a,np.ravel_multi_index(b, a.shape)) a.flat[np.ravel_multi_index(b, a.shape)] ``` **Custom `np.ravel_multi_index` for performance boost** We could implement a custom version to simulate the behaviour of `np.ravel_multi_index` to boost the performance, like so - ``` def ravel_index(b, shp): return np.concatenate((np.asarray(shp[1:])[::-1].cumprod()[::-1],[1])).dot(b) ``` Using it, the desired output would be found in two ways - ``` np.take(a,ravel_index(b, a.shape)) a.flat[ravel_index(b, a.shape)] ``` ### Benchmarking Additionall incorporating `tuple` based method from the question and `map` based one from @Kanak's post. Case #1 : dims = 3 ``` In [23]: a = np.random.randint(0,9,([20]*3)) In [24]: b = np.random.randint(0,20,(a.ndim,1000000)) In [25]: %timeit a[tuple(b)] ...: %timeit a[map(np.ravel, b)] ...: %timeit np.take(a,np.ravel_multi_index(b, a.shape)) ...: %timeit a.flat[np.ravel_multi_index(b, a.shape)] ...: %timeit np.take(a,ravel_index(b, a.shape)) ...: %timeit a.flat[ravel_index(b, a.shape)] 100 loops, best of 3: 6.56 ms per loop 100 loops, best of 3: 6.58 ms per loop 100 loops, best of 3: 6.95 ms per loop 100 loops, best of 3: 9.17 ms per loop 100 loops, best of 3: 6.31 ms per loop 100 loops, best of 3: 8.52 ms per loop ``` Case #2 : dims = 6 ``` In [29]: a = np.random.randint(0,9,([10]*6)) In [30]: b = np.random.randint(0,10,(a.ndim,1000000)) In [31]: %timeit a[tuple(b)] ...: %timeit a[map(np.ravel, b)] ...: %timeit np.take(a,np.ravel_multi_index(b, a.shape)) ...: %timeit a.flat[np.ravel_multi_index(b, a.shape)] ...: %timeit np.take(a,ravel_index(b, a.shape)) ...: %timeit a.flat[ravel_index(b, a.shape)] 10 loops, best of 3: 40.9 ms per loop 10 loops, best of 3: 40 ms per loop 10 loops, best of 3: 20 ms per loop 10 loops, best of 3: 29.9 ms per loop 100 loops, best of 3: 15.7 ms per loop 10 loops, best of 3: 25.8 ms per loop ``` Case #3 : dims = 10 ``` In [32]: a = np.random.randint(0,9,([4]*10)) In [33]: b = np.random.randint(0,4,(a.ndim,1000000)) In [34]: %timeit a[tuple(b)] ...: %timeit a[map(np.ravel, b)] ...: %timeit np.take(a,np.ravel_multi_index(b, a.shape)) ...: %timeit a.flat[np.ravel_multi_index(b, a.shape)] ...: %timeit np.take(a,ravel_index(b, a.shape)) ...: %timeit a.flat[ravel_index(b, a.shape)] 10 loops, best of 3: 60.7 ms per loop 10 loops, best of 3: 60.1 ms per loop 10 loops, best of 3: 27.8 ms per loop 10 loops, best of 3: 38 ms per loop 100 loops, best of 3: 18.7 ms per loop 10 loops, best of 3: 29.3 ms per loop ``` So, it makes sense to look for alternatives when working with higher-dimensional inputs and with large data.
Are you looking for [`numpy.ndarray.tolist()`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.tolist.html) ? ``` >>> a = np.arange(27).reshape(3,3,3) >>> bl = [[0, 1, 2], [0, 0, 0], [1, 1, 2]] >>> b = np.array(bl) >>> a[b.tolist()] array([ 1, 10, 20]) ``` Or for [arrays indexing arrays](https://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#indexing-multi-dimensional-arrays) which is quite similar to list indexing : ``` >>> a[np.array([0, 1, 2]), np.array([0, 0, 0]), np.array([1, 1, 2])] array([ 1, 10, 20]) ``` However as you can from the previous link, indexing an array a with an array b directly means you are indexing the first index of a only with your whole b array which can lead to confusing output.
5,373,195
When I tried to parse a csv which was exported by MS SQL 2005 express edition's query, the string python gives me is totally unexpected. For example if the line in the csv file is :" aaa,bbb,ccc,dddd", then when python parsed it as string, it becomes :" a a a a , b b b , c c c, d d d d" something like that.....What happens??? I tried to remove the space in the code but don't work. ``` import os import random f1 = open('a.txt', 'r') f2 = open('dec_sql.txt', 'w') text = 'abc' while(text != ''): text = f1.readline() if(text==''): break splited = text.split(',') for i in range (0, 32): splited[i] = splited[i].replace(' ', '') sql = 'insert into dbo.INBOUND_RATED_DEC2010 values (' sql += '\'' + splited[0] + '\', ' sql += '\'' + splited[1] + '\', ' sql += '\'' + splited[2] + '\', ' sql += '\'' + splited[3] + '\', ' sql += '\'' + splited[4] + '\', ' sql += '\'' + splited[5] + '\', ' sql += '\'' + splited[6] + '\', ' sql += '\'' + splited[7] + '\', ' sql += '\'' + splited[8] + '\', ' sql += '\'' + splited[9] + '\', ' sql += '\'' + splited[10] + '\', ' sql += '\'' + splited[11] + '\', ' sql += '\'' + splited[12] + '\', ' sql += '\'' + splited[13] + '\', ' sql += '\'' + splited[14] + '\', ' sql += '\'' + splited[15] + '\', ' sql += '\'' + splited[16] + '\', ' sql += '\'' + splited[17] + '\', ' sql += '\'' + splited[18] + '\', ' sql += '\'' + splited[19] + '\', ' sql += '\'' + splited[20] + '\', ' sql += '\'' + splited[21] + '\', ' sql += '\'' + splited[22] + '\', ' sql += '\'' + splited[23] + '\', ' sql += '\'' + splited[24] + '\', ' sql += '\'' + splited[25] + '\', ' sql += '\'' + splited[26] + '\', ' sql += '\'' + splited[27] + '\', ' sql += '\'' + splited[28] + '\', ' sql += '\'' + splited[29] + '\', ' sql += '\'' + splited[30] + '\', ' sql += '\'' + splited[31] + '\', ' sql += '\'' + splited[32] + '\' ' sql += ')' print sql f2.write(sql+'\n') f2.close() f1.close() ```
2011/03/21
[ "https://Stackoverflow.com/questions/5373195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/612678/" ]
Sounds to me like the output of the MS SQL 2005 query is a unicode file. The python [csv module](http://docs.python.org/library/csv.html) cannot handle unicode files, but there is some [sample code](http://docs.python.org/library/csv.html#csv-examples) in the documentation for the csv module describing how to work around the problem. Alternately, some text editors allow you to save a file with a different encoding. For example, I opened the results of a MS SQL 2005 query in Notepad++ and it told me the file was UCS-2 encoded and I was able to convert it to UTF-8 from the Encoding menu.
Try to open the file in notepad and use the replace all function to replace `' '` with `''`
5,373,195
When I tried to parse a csv which was exported by MS SQL 2005 express edition's query, the string python gives me is totally unexpected. For example if the line in the csv file is :" aaa,bbb,ccc,dddd", then when python parsed it as string, it becomes :" a a a a , b b b , c c c, d d d d" something like that.....What happens??? I tried to remove the space in the code but don't work. ``` import os import random f1 = open('a.txt', 'r') f2 = open('dec_sql.txt', 'w') text = 'abc' while(text != ''): text = f1.readline() if(text==''): break splited = text.split(',') for i in range (0, 32): splited[i] = splited[i].replace(' ', '') sql = 'insert into dbo.INBOUND_RATED_DEC2010 values (' sql += '\'' + splited[0] + '\', ' sql += '\'' + splited[1] + '\', ' sql += '\'' + splited[2] + '\', ' sql += '\'' + splited[3] + '\', ' sql += '\'' + splited[4] + '\', ' sql += '\'' + splited[5] + '\', ' sql += '\'' + splited[6] + '\', ' sql += '\'' + splited[7] + '\', ' sql += '\'' + splited[8] + '\', ' sql += '\'' + splited[9] + '\', ' sql += '\'' + splited[10] + '\', ' sql += '\'' + splited[11] + '\', ' sql += '\'' + splited[12] + '\', ' sql += '\'' + splited[13] + '\', ' sql += '\'' + splited[14] + '\', ' sql += '\'' + splited[15] + '\', ' sql += '\'' + splited[16] + '\', ' sql += '\'' + splited[17] + '\', ' sql += '\'' + splited[18] + '\', ' sql += '\'' + splited[19] + '\', ' sql += '\'' + splited[20] + '\', ' sql += '\'' + splited[21] + '\', ' sql += '\'' + splited[22] + '\', ' sql += '\'' + splited[23] + '\', ' sql += '\'' + splited[24] + '\', ' sql += '\'' + splited[25] + '\', ' sql += '\'' + splited[26] + '\', ' sql += '\'' + splited[27] + '\', ' sql += '\'' + splited[28] + '\', ' sql += '\'' + splited[29] + '\', ' sql += '\'' + splited[30] + '\', ' sql += '\'' + splited[31] + '\', ' sql += '\'' + splited[32] + '\' ' sql += ')' print sql f2.write(sql+'\n') f2.close() f1.close() ```
2011/03/21
[ "https://Stackoverflow.com/questions/5373195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/612678/" ]
Sounds to me like the output of the MS SQL 2005 query is a unicode file. The python [csv module](http://docs.python.org/library/csv.html) cannot handle unicode files, but there is some [sample code](http://docs.python.org/library/csv.html#csv-examples) in the documentation for the csv module describing how to work around the problem. Alternately, some text editors allow you to save a file with a different encoding. For example, I opened the results of a MS SQL 2005 query in Notepad++ and it told me the file was UCS-2 encoded and I was able to convert it to UTF-8 from the Encoding menu.
It may help to use Python's built in CSV reader. Looks like an issue with unicode, a problem that frustrated me a lot. ``` import tkFileDialog import csv ENCODING_REGEX_REPLACEMENT_LIST = [(re.compile('\xe2\x80\x99'), "'"), (re.compile('\xe2\x80\x94'), "--"), (re.compile('\xe2\x80\x9c'), '"'), (re.compile('\xe2\x80\x9d'), '"'), (re.compile('\xe2\x80\xa6'), '...')] def correct_encoding(csv_row): for key in csv_row.keys(): # if there is a value for the current key if csv_row[key]: try: csv_row[key] = unicode(csv_row[key], errors='strict') except ValueError: # we have a bad encoding, try iterating through all the known # bad encodings in the ENCODING_REGEX_REPLACEMENT and replace # everything and then try again for (regex, replacement) in ENCODING_REGEX_REPLACEMENT_LIST: csv_row[key] = regex.sub(replacement,csv_row[key]) print(csv_row) csv_row[key] = unicode(csv_row[key]) # if there is NOT a value for the current key else: csv_row[key] = unicode('') return csv_row filename = tkFileDialog.askopenfilename() csv_reader = csv.DictReader(open(filename, "rb"), dialect='excel') # assuming similar dialect for csv_row in csv_reader: csv_row = correct_encoding(csv_row) # your application logic here ```
5,373,195
When I tried to parse a csv which was exported by MS SQL 2005 express edition's query, the string python gives me is totally unexpected. For example if the line in the csv file is :" aaa,bbb,ccc,dddd", then when python parsed it as string, it becomes :" a a a a , b b b , c c c, d d d d" something like that.....What happens??? I tried to remove the space in the code but don't work. ``` import os import random f1 = open('a.txt', 'r') f2 = open('dec_sql.txt', 'w') text = 'abc' while(text != ''): text = f1.readline() if(text==''): break splited = text.split(',') for i in range (0, 32): splited[i] = splited[i].replace(' ', '') sql = 'insert into dbo.INBOUND_RATED_DEC2010 values (' sql += '\'' + splited[0] + '\', ' sql += '\'' + splited[1] + '\', ' sql += '\'' + splited[2] + '\', ' sql += '\'' + splited[3] + '\', ' sql += '\'' + splited[4] + '\', ' sql += '\'' + splited[5] + '\', ' sql += '\'' + splited[6] + '\', ' sql += '\'' + splited[7] + '\', ' sql += '\'' + splited[8] + '\', ' sql += '\'' + splited[9] + '\', ' sql += '\'' + splited[10] + '\', ' sql += '\'' + splited[11] + '\', ' sql += '\'' + splited[12] + '\', ' sql += '\'' + splited[13] + '\', ' sql += '\'' + splited[14] + '\', ' sql += '\'' + splited[15] + '\', ' sql += '\'' + splited[16] + '\', ' sql += '\'' + splited[17] + '\', ' sql += '\'' + splited[18] + '\', ' sql += '\'' + splited[19] + '\', ' sql += '\'' + splited[20] + '\', ' sql += '\'' + splited[21] + '\', ' sql += '\'' + splited[22] + '\', ' sql += '\'' + splited[23] + '\', ' sql += '\'' + splited[24] + '\', ' sql += '\'' + splited[25] + '\', ' sql += '\'' + splited[26] + '\', ' sql += '\'' + splited[27] + '\', ' sql += '\'' + splited[28] + '\', ' sql += '\'' + splited[29] + '\', ' sql += '\'' + splited[30] + '\', ' sql += '\'' + splited[31] + '\', ' sql += '\'' + splited[32] + '\' ' sql += ')' print sql f2.write(sql+'\n') f2.close() f1.close() ```
2011/03/21
[ "https://Stackoverflow.com/questions/5373195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/612678/" ]
Sounds to me like the output of the MS SQL 2005 query is a unicode file. The python [csv module](http://docs.python.org/library/csv.html) cannot handle unicode files, but there is some [sample code](http://docs.python.org/library/csv.html#csv-examples) in the documentation for the csv module describing how to work around the problem. Alternately, some text editors allow you to save a file with a different encoding. For example, I opened the results of a MS SQL 2005 query in Notepad++ and it told me the file was UCS-2 encoded and I was able to convert it to UTF-8 from the Encoding menu.
Your file is most likely encoded with a 2byte character encoding - most likely utf-16 (but it culd be some other encoding. To get the CSV proper reading it, you'd open it with a codec so that it is decoded as its read - doing that you have Unicode objects (not string objects) inside your python program. So, instead of opening the file with ``` my_file = open ("data.dat", "rt") ``` Use: import codecs ``` my_file = codecs.open("data.dat", "rt", "utf-16") ``` And then feed this to the CSV module, with: import csv reader = csv.reader(my\_file) first\_line = False for line in reader: if first\_line: #skips header line first\_line = True continue #assemble sql query and issue it Another thing is that your "query" being constructed into 32 lines of repetitive code is a nice thing to do when programing. Even in languages that lack rich string processing facilities, there are better ways to do it, but in Python, you can simply do: ``` sql = 'insert into dbo.INBOUND_RATED_DEC2010 values (%s);' % ", ".join("'%s'" % value for value in splited ) ``` Instead of those 33 lines assembling your query. (I am telling it to insert a string inside the parentheses on the first string. After the `%`operator, the string ", " is used with the "join" method so that it is used to paste together all elements on the sequence passed as a parameter to join. This sequence is made of a string, containing a value enclosed inside single quotes for each value in your splited array.
47,544,183
I'm trying to use multiprocessing, but I keep getting this error: ``` AttributeError: Can't get attribute 'processLine' on <module '__main__' ``` (The processLine function returns word, so I guess the problem is here, but I don't know how to get around it) ``` import multiprocessing as mp pool = mp.Pool(4) jobs = [] Types =[] def processLine(line): line = line.split() word = line[0].strip() return word with open("1.txt", "r", encoding = "utf-8") as f: for line in f: word = (jobs.append(pool.apply_async(processLine,(line)))) Types.append(word) filtered_words=[] with open("2.txt", "r", encoding = "utf-8") as f: for line in f: word = jobs.append(pool.apply_async(processLine,(line))) if word in Types: filtered_words = "".join(line) print(filtered_words) for job in jobs: job.get() pool.close() ``` And this is what I get: Process ForkPoolWorker-1: Process ForkPoolWorker-2: Process ForkPoolWorker-3: Process ForkPoolWorker-4: Traceback (most recent call last): File "/Users/user/anaconda/lib/python3.6/multiprocessing/process.py", line 249, in \_bootstrap ``` self.run() ``` File "/Users/user/anaconda/lib/python3.6/multiprocessing/process.py", line 93, in run ``` self._target(*self._args, **self._kwargs) ``` File "/Users/user/anaconda/lib/python3.6/multiprocessing/pool.py", line 108, in worker ``` task = get() ``` File "/Users/user/anaconda/lib/python3.6/multiprocessing/queues.py", line 345, in get return \_ForkingPickler.loads(res) AttributeError: Can't get attribute 'processLine' on Traceback (most recent call last): Traceback (most recent call last): Traceback (most recent call last): File "/Users/user/anaconda/lib/python3.6/multiprocessing/process.py", line 249, in \_bootstrap self.run() File "/Users/user/anaconda/lib/python3.6/multiprocessing/process.py", line 249, in \_bootstrap ``` self.run() ``` File "/Users/user/anaconda/lib/python3.6/multiprocessing/process.py", line 93, in run ``` self._target(*self._args, **self._kwargs) ``` File "/Users/user/anaconda/lib/python3.6/multiprocessing/process.py", line 93, in run ``` self._target(*self._args, **self._kwargs) ``` File "/Users/user/anaconda/lib/python3.6/multiprocessing/pool.py", line 108, in worker ``` task = get() ``` File "/Users/user/anaconda/lib/python3.6/multiprocessing/pool.py", line 108, in worker task = get() File "/Users/user/anaconda/lib/python3.6/multiprocessing/queues.py", line 345, in get return \_ForkingPickler.loads(res) File "/Users/user/anaconda/lib/python3.6/multiprocessing/process.py", line 249, in \_bootstrap self.run() File "/Users/user/anaconda/lib/python3.6/multiprocessing/queues.py", line 345, in get return \_ForkingPickler.loads(res) File "/Users/user/anaconda/lib/python3.6/multiprocessing/process.py", line 93, in run self.\_target(\*self.\_args, \*\*self.\_kwargs) AttributeError: Can't get attribute 'processLine' on AttributeError: Can't get attribute 'processLine' on File "/Users/user/anaconda/lib/python3.6/multiprocessing/pool.py", line 108, in worker task = get() File "/Users/user/anaconda/lib/python3.6/multiprocessing/queues.py", line 345, in get ``` return _ForkingPickler.loads(res) ``` AttributeError: Can't get attribute 'processLine' on
2017/11/29
[ "https://Stackoverflow.com/questions/47544183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8138305/" ]
The `multiprocessing` module needs to be able to import your module safely. Any code not inside a function or class should be protected by the standard Python import guard: ``` if __name__ == '__main__': ...code goes here... ``` But there are other problems with your code. For example, you've got: ``` word = jobs.append(pool.apply_async(processLine,(line))) ``` ...but `append` doesn't return a value, so this will always assign `None` to `word`. Rather than using a `for` loop to repeatedly call `pool.apply_async`, you may want to consider using `pool.map_async` instead, or just `pool.map` if you don't actually need the asynchronous behavior.
I worked around the AttributeError issue by using VS Code in administrator mode to run it instead of Anaconda Spyder.
10,688,389
I have a ever growing csv file that looks like: ``` 143100, 2012-05-21 09:52:54.165852 125820, 2012-05-21 09:53:54.666780 109260, 2012-05-21 09:54:55.144712 116340, 2012-05-21 09:55:55.642197 125640, 2012-05-21 09:56:56.094999 122820, 2012-05-21 09:57:56.546567 124770, 2012-05-21 09:58:57.046050 103830, 2012-05-21 09:59:57.497299 114120, 2012-05-21 10:00:58.000978 -31549410, 2012-05-21 10:01:58.063470 90390, 2012-05-21 10:02:58.108794 81690, 2012-05-21 10:03:58.161329 80940, 2012-05-21 10:04:58.227664 102180, 2012-05-21 10:05:58.289882 99750, 2012-05-21 10:06:58.322063 87000, 2012-05-21 10:07:58.391256 92160, 2012-05-21 10:08:58.442438 80130, 2012-05-21 10:09:58.506494 ``` The negative numbers occur when the service that generates the file has an API connection failure. I'm already using matplotlib to graph the data, however the artificial negative numbers screw the graph greatly. I would like to locate all negative entries and remove the corresponding lines. At no point is a negative number actually representative of any real data. In Bash I would do something like: ``` awk '{print $1}' original.csv | sed '/-/d' > new.csv ``` but that's messy and tends to be slow, and I don't really want to embed bash commands in my python graphing script if I can help it. Can anyone point me in the right direction? Edit: Here's the code I'm using to read/plot the data: ``` import matplotlib matplotlib.use('Agg') from matplotlib.mlab import csv2rec import matplotlib.pyplot as plt import matplotlib.dates as mdates from pylab import * output_image_name='tpm.png' data = csv2rec('counter.log', names=['packets', 'time']) rcParams['figure.figsize'] = 10, 5 rcParams['font.size'] = 8 fig = plt.figure() plt.plot(data['packets'], data['time']) ax = fig.add_subplot(111) ax.plot(data['time'], data['tweets']) hours = mdates.HourLocator() fmt = mdates.DateFormatter('%D - %H:%M') ax.xaxis.set_major_locator(hours) ax.xaxis.set_major_formatter(fmt) ax.grid() plt.ylabel("packets") plt.title("Packet Log: Packets Per Minute") fig.autofmt_xdate(bottom=0.2, rotation=90, ha='left') plt.savefig(output_image_name) ```
2012/05/21
[ "https://Stackoverflow.com/questions/10688389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672387/" ]
The Python idiom would be to use a generator expression to filter the lines: ``` sys.stdout.writelines(line for line in sys.stdin if not line.startswith('-')) ``` Or in a processing context: ``` filtered = (line for line in sys.stdin if not line.startswith('-')) for line in filtered: # ... ```
Instead of rewriting the files, I would filter the data on read, i.e. just before plotting.
10,688,389
I have a ever growing csv file that looks like: ``` 143100, 2012-05-21 09:52:54.165852 125820, 2012-05-21 09:53:54.666780 109260, 2012-05-21 09:54:55.144712 116340, 2012-05-21 09:55:55.642197 125640, 2012-05-21 09:56:56.094999 122820, 2012-05-21 09:57:56.546567 124770, 2012-05-21 09:58:57.046050 103830, 2012-05-21 09:59:57.497299 114120, 2012-05-21 10:00:58.000978 -31549410, 2012-05-21 10:01:58.063470 90390, 2012-05-21 10:02:58.108794 81690, 2012-05-21 10:03:58.161329 80940, 2012-05-21 10:04:58.227664 102180, 2012-05-21 10:05:58.289882 99750, 2012-05-21 10:06:58.322063 87000, 2012-05-21 10:07:58.391256 92160, 2012-05-21 10:08:58.442438 80130, 2012-05-21 10:09:58.506494 ``` The negative numbers occur when the service that generates the file has an API connection failure. I'm already using matplotlib to graph the data, however the artificial negative numbers screw the graph greatly. I would like to locate all negative entries and remove the corresponding lines. At no point is a negative number actually representative of any real data. In Bash I would do something like: ``` awk '{print $1}' original.csv | sed '/-/d' > new.csv ``` but that's messy and tends to be slow, and I don't really want to embed bash commands in my python graphing script if I can help it. Can anyone point me in the right direction? Edit: Here's the code I'm using to read/plot the data: ``` import matplotlib matplotlib.use('Agg') from matplotlib.mlab import csv2rec import matplotlib.pyplot as plt import matplotlib.dates as mdates from pylab import * output_image_name='tpm.png' data = csv2rec('counter.log', names=['packets', 'time']) rcParams['figure.figsize'] = 10, 5 rcParams['font.size'] = 8 fig = plt.figure() plt.plot(data['packets'], data['time']) ax = fig.add_subplot(111) ax.plot(data['time'], data['tweets']) hours = mdates.HourLocator() fmt = mdates.DateFormatter('%D - %H:%M') ax.xaxis.set_major_locator(hours) ax.xaxis.set_major_formatter(fmt) ax.grid() plt.ylabel("packets") plt.title("Packet Log: Packets Per Minute") fig.autofmt_xdate(bottom=0.2, rotation=90, ha='left') plt.savefig(output_image_name) ```
2012/05/21
[ "https://Stackoverflow.com/questions/10688389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672387/" ]
The Python idiom would be to use a generator expression to filter the lines: ``` sys.stdout.writelines(line for line in sys.stdin if not line.startswith('-')) ``` Or in a processing context: ``` filtered = (line for line in sys.stdin if not line.startswith('-')) for line in filtered: # ... ```
This program opens your csv file, removes the lines starting with negative integers, and saves it to a different file. If you want, you can overwrite this on the same file with slight modification. ``` with open('data.csv', 'r') as f: with open('data2.csv', 'w') as g: for row in f: if row[0] != '-': g.write(row) ```
10,688,389
I have a ever growing csv file that looks like: ``` 143100, 2012-05-21 09:52:54.165852 125820, 2012-05-21 09:53:54.666780 109260, 2012-05-21 09:54:55.144712 116340, 2012-05-21 09:55:55.642197 125640, 2012-05-21 09:56:56.094999 122820, 2012-05-21 09:57:56.546567 124770, 2012-05-21 09:58:57.046050 103830, 2012-05-21 09:59:57.497299 114120, 2012-05-21 10:00:58.000978 -31549410, 2012-05-21 10:01:58.063470 90390, 2012-05-21 10:02:58.108794 81690, 2012-05-21 10:03:58.161329 80940, 2012-05-21 10:04:58.227664 102180, 2012-05-21 10:05:58.289882 99750, 2012-05-21 10:06:58.322063 87000, 2012-05-21 10:07:58.391256 92160, 2012-05-21 10:08:58.442438 80130, 2012-05-21 10:09:58.506494 ``` The negative numbers occur when the service that generates the file has an API connection failure. I'm already using matplotlib to graph the data, however the artificial negative numbers screw the graph greatly. I would like to locate all negative entries and remove the corresponding lines. At no point is a negative number actually representative of any real data. In Bash I would do something like: ``` awk '{print $1}' original.csv | sed '/-/d' > new.csv ``` but that's messy and tends to be slow, and I don't really want to embed bash commands in my python graphing script if I can help it. Can anyone point me in the right direction? Edit: Here's the code I'm using to read/plot the data: ``` import matplotlib matplotlib.use('Agg') from matplotlib.mlab import csv2rec import matplotlib.pyplot as plt import matplotlib.dates as mdates from pylab import * output_image_name='tpm.png' data = csv2rec('counter.log', names=['packets', 'time']) rcParams['figure.figsize'] = 10, 5 rcParams['font.size'] = 8 fig = plt.figure() plt.plot(data['packets'], data['time']) ax = fig.add_subplot(111) ax.plot(data['time'], data['tweets']) hours = mdates.HourLocator() fmt = mdates.DateFormatter('%D - %H:%M') ax.xaxis.set_major_locator(hours) ax.xaxis.set_major_formatter(fmt) ax.grid() plt.ylabel("packets") plt.title("Packet Log: Packets Per Minute") fig.autofmt_xdate(bottom=0.2, rotation=90, ha='left') plt.savefig(output_image_name) ```
2012/05/21
[ "https://Stackoverflow.com/questions/10688389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672387/" ]
Instead of rewriting the files, I would filter the data on read, i.e. just before plotting.
This program opens your csv file, removes the lines starting with negative integers, and saves it to a different file. If you want, you can overwrite this on the same file with slight modification. ``` with open('data.csv', 'r') as f: with open('data2.csv', 'w') as g: for row in f: if row[0] != '-': g.write(row) ```
16,881,955
I am trying to learn python and for that purpose i made a simple addition program using python 2.7.3 ``` print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) ``` i saved the file as *add.py* and when i double click and run it;the program run and exits instantenously without showing answer. Then i tried code of this question [Simple addition calculator in python](https://stackoverflow.com/questions/4665558/simple-addition-calculator-in-python) it accepts user inputs but after entering both numbers the python exits with out showing answer. Any suggestions for the above code. Advance thanks for the help
2013/06/02
[ "https://Stackoverflow.com/questions/16881955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/996366/" ]
add an empty `raw_input()` at the end to pause until you press `Enter` ``` print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) raw_input() # waits for you to press enter ``` Alternatively run it from `IDLE`, command line, or whichever editor you use.
Run your file from the command line. This way you can see exceptions. Execute `cmd` than in the "dos box" type: ``` python myfile.py ``` Or on Windows likley just: ``` myfile.py ```
16,881,955
I am trying to learn python and for that purpose i made a simple addition program using python 2.7.3 ``` print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) ``` i saved the file as *add.py* and when i double click and run it;the program run and exits instantenously without showing answer. Then i tried code of this question [Simple addition calculator in python](https://stackoverflow.com/questions/4665558/simple-addition-calculator-in-python) it accepts user inputs but after entering both numbers the python exits with out showing answer. Any suggestions for the above code. Advance thanks for the help
2013/06/02
[ "https://Stackoverflow.com/questions/16881955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/996366/" ]
add an empty `raw_input()` at the end to pause until you press `Enter` ``` print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) raw_input() # waits for you to press enter ``` Alternatively run it from `IDLE`, command line, or whichever editor you use.
It's exiting because you're not telling the interpreter to pause at any moment after printing the results. The program itself works. I recommend running it directly in the terminal/command line window like so: ![screenshot of it working](https://i.stack.imgur.com/fFTGm.png) Alternatively, you could write: ``` import time print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) time.sleep(3.0) #pause for 3 seconds ``` Or you can just add another `raw_input()` at the end of your code so that it waits for input (at which point the user will type something and nothing will happen to their input data). ---
16,881,955
I am trying to learn python and for that purpose i made a simple addition program using python 2.7.3 ``` print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) ``` i saved the file as *add.py* and when i double click and run it;the program run and exits instantenously without showing answer. Then i tried code of this question [Simple addition calculator in python](https://stackoverflow.com/questions/4665558/simple-addition-calculator-in-python) it accepts user inputs but after entering both numbers the python exits with out showing answer. Any suggestions for the above code. Advance thanks for the help
2013/06/02
[ "https://Stackoverflow.com/questions/16881955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/996366/" ]
It's exiting because you're not telling the interpreter to pause at any moment after printing the results. The program itself works. I recommend running it directly in the terminal/command line window like so: ![screenshot of it working](https://i.stack.imgur.com/fFTGm.png) Alternatively, you could write: ``` import time print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) time.sleep(3.0) #pause for 3 seconds ``` Or you can just add another `raw_input()` at the end of your code so that it waits for input (at which point the user will type something and nothing will happen to their input data). ---
Run your file from the command line. This way you can see exceptions. Execute `cmd` than in the "dos box" type: ``` python myfile.py ``` Or on Windows likley just: ``` myfile.py ```
34,777,676
So I have created a function in my program that allows the user to save whatever he/she draws on the Turtle canvas as a Postscript file with his/her own name. However, there have been issues with some colors not appearing in the output as per the nature of Postscript files, and also, Postscript files just won't open on some other platforms. So I have decided to save the postscript file as a JPEG image since the JPEG file should be able to be opened on many platforms, can hopefully display all the colors of the canvas, and it should have a higher resolution than the postscript file. So, to do that, I have tried, using the PIL, the following in my save function: ``` def savefirst(): cnv = getscreen().getcanvas() global hen fev = cnv.postscript(file = 'InitialFile.ps', colormode = 'color') hen = filedialog.asksaveasfilename(defaultextension = '.jpg') im = Image.open(fev) print(im) im.save(hen + '.jpg') ``` However, whenever I run this, I get this error: ``` line 2391, in savefirst im = Image.open(fev) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 2263, in open fp = io.BytesIO(fp.read()) AttributeError: 'str' object has no attribute 'read' ``` Apparently it cannot read the postscript file since it's **not**, according to what I know, an image in itself, so it has to first be converted into an image, THEN read as an image, and then finally converted and saved as a JPEG file. **The question is, how would I be able to first *convert the postscript file* to an *image file* INSIDE the program possibly using the Python Imaging Library?** Looking around SO and Google has been no help, so any help from the SO users is greatly appreciated! **EDIT:** Following `unubuntu's` advice, I have now have this for my save function: ``` def savefirst(): cnv = getscreen().getcanvas() global hen ps = cnv.postscript(colormode = 'color') hen = filedialog.asksaveasfilename(defaultextension = '.jpg') im = Image.open(io.BytesIO(ps.encode('utf-8'))) im.save(hen + '.jpg') ``` However, now whenever I run that, I get this error: ``` line 2395, in savefirst im.save(hen + '.jpg') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 1646, in save self.load() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/EpsImagePlugin.py", line 337, in load self.im = Ghostscript(self.tile, self.size, self.fp, scale) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/EpsImagePlugin.py", line 143, in Ghostscript stdout=subprocess.PIPE) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 950, in __init__ restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 1544, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'gs' ``` **What is `'gs'` and why am I getting this error now?**
2016/01/13
[ "https://Stackoverflow.com/questions/34777676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5661257/" ]
[If you don't supply the file parameter](https://www.tcl.tk/man/tcl8.4/TkCmd/canvas.htm#M60) in the call to `cnv.postscript`, then a `cnv.postscript` returns the PostScript as a (unicode) string. You can then convert the unicode to bytes and feed that to `io.BytesIO` and feed that to `Image.open`. [`Image.open`](http://pillow.readthedocs.org/en/3.0.x/reference/Image.html#PIL.Image.open) can accept as its first argument any file-like object that implements `read`, `seek` and `tell` methods. ``` import io def savefirst(): cnv = getscreen().getcanvas() global hen ps = cnv.postscript(colormode = 'color') hen = filedialog.asksaveasfilename(defaultextension = '.jpg') im = Image.open(io.BytesIO(ps.encode('utf-8'))) im.save(hen + '.jpg') ``` --- For example, borrowing heavily from [A. Rodas' code](https://stackoverflow.com/a/17885207/190597), ``` import Tkinter as tk import subprocess import os import io from PIL import Image class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.line_start = None self.canvas = tk.Canvas(self, width=300, height=300, bg="white") self.canvas.bind("<Button-1>", lambda e: self.draw(e.x, e.y)) self.button = tk.Button(self, text="save", command=self.save) self.canvas.pack() self.button.pack(pady=10) def draw(self, x, y): if self.line_start: x_origin, y_origin = self.line_start self.canvas.create_line(x_origin, y_origin, x, y) self.line_start = x, y def save(self): ps = self.canvas.postscript(colormode='color') img = Image.open(io.BytesIO(ps.encode('utf-8'))) img.save('/tmp/test.jpg') app = App() app.mainloop() ```
Adding to unutbu's answer, you can also write the data again to a BytesIO object, but you have to seek to the beginning of the buffer after doing so. Here's a flask example that displays the image in browser: ```python @app.route('/image.png', methods=['GET']) def image(): """Return png of current canvas""" ps = tkapp.canvas.postscript(colormode='color') out = BytesIO() Image.open(BytesIO(ps.encode('utf-8'))).save(out, format="PNG") out.seek(0) return send_file(out, mimetype='image/png') ```
73,025,430
I am currently running a function using python's concurrent.futures library. It looks like this (I am using Python 3.10.1 ): ``` with concurrent.futures.ThreadPoolExecutor() as executor: future_results = [executor.submit(f.get_pdf_multi_thread, ssn) for ssn in ssns] for future in concurrent.futures.as_completed(future_results): try: future.result() except Exception as exc: # If there is one exception in a thread stop all threads for future in future_results: future.cancel() raise exc ``` **The aim of this is that, if there is any exception in one of the threads, stop the remaining ones and throw exception**. However I don't know if this is doing what it's supposed to do (sometimes it takes a lot of time to throw the exception that I desire and some other times it throws it quickly). Could you help me with this? Thank you
2022/07/18
[ "https://Stackoverflow.com/questions/73025430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8972132/" ]
to find the functions and procedures where a table is referenced, you can scan the `routine_definition` column of the `sysibm.routines` view for the table name. Use `regexp_instr` function to look for the pattern FROM|UPDATE|INSERT INTO followed by the table name. ``` with t1 as ( SELECT char(ROUTINE_SCHEMA,10) libname, char(ROUTINE_NAME,30) routine_name, cast(a.routine_definition as varchar(9999)) routine_defn FROM sysibm.routines a where routine_schema = 'YOURLIB' ), t2 as ( select a.routine_name, regexp_instr(a.routine_defn, '(FROM|UPDATE|INSERT INTO)\s+YOUR_TABLE',1,1) pos, a.routine_defn from t1 a ) select a.routine_name, a.pos, substr(a.routine_defn,pos,20) text from t2 a where a.pos > 0 ```
you can use ibm function RELATED\_OBJECTS SQL <https://www.ibm.com/docs/en/i/7.3?topic=services-related-objects-table-function>
26,129,650
I am a beginner in python. I want to ask the user to input his first name. The name should only contain letters A-Z,if not, I want to display an error and request the user to enter the name again until the name is correct. Here is the code am trying. However, The string is not checked even when it contains numbers and special characters. Where am I going wrong?? ``` def get_first_name(): try_again = True while(try_again==True): first_name = raw_input("Please enter your first name.") if (re.match("^[A-Za-z]+$", first_name)==False): try_again = True else: try_again = False return first_name ```
2014/09/30
[ "https://Stackoverflow.com/questions/26129650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1671718/" ]
You don't need `re`, just use [str.isalpha](http://www.tutorialspoint.com/python/string_isalpha.htm) ``` def get_first_name(): while True: first_name = raw_input("Please enter your first name.") if not first_name.isalpha(): # if not all letters, ask for input again print "Invalid entry" continue else: # else all is good, return first_name return first_name In [12]: "foo".isalpha() Out[12]: True In [13]: "foo1".isalpha() Out[13]: False ```
``` if (re.match("^[A-Za-z]+$", first_name)==False): ``` re.match is returning None when there is no match. None does not equal False. You could write it like this: ``` if not re.match("^[A-Za-z]+$", first_name): ```
63,498,826
[![Image of cone](https://i.stack.imgur.com/NuZNp.jpg)](https://i.stack.imgur.com/NuZNp.jpg) How do I make it so everything in the image is in gray-scale except the orange cone. Using opencv python.
2020/08/20
[ "https://Stackoverflow.com/questions/63498826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13991355/" ]
You can achieve your goal by using `bitwise_and()` function and `thresholding`. Steps: * generate `mask` for the required region.(here `thresholding` is used but other methods can also be used) * extract required `regions` using `bitwise_and` (image & mask). * Add `masked regions` to get output. Here's sample code: ``` import cv2 import numpy as np img = cv2.imread('input.jpg') # creating mask using thresholding over `red` channel (use better use histogram to get threshoding value) # I have used 200 as thershoding value it can be different for different images ret, mask = cv2.threshold(img[:, :,2], 200, 255, cv2.THRESH_BINARY) mask3 = np.zeros_like(img) mask3[:, :, 0] = mask mask3[:, :, 1] = mask mask3[:, :, 2] = mask # extracting `orange` region using `biteise_and` orange = cv2.bitwise_and(img, mask3) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) # extracting non-orange region gray = cv2.bitwise_and(img, 255 - mask3) # orange masked output out = gray + orange cv2.imwrite('orange.png', orange) cv2.imwrite('gray.png', gray) cv2.imwrite("output.png", out) ``` Results: ### masked orange image [![masked orange image](https://i.stack.imgur.com/8G34M.png)](https://i.stack.imgur.com/8G34M.png) ### masked gray image [![enter image description here](https://i.stack.imgur.com/QieOO.png)](https://i.stack.imgur.com/QieOO.png) ### output image [![enter image description here](https://i.stack.imgur.com/dEU4K.png)](https://i.stack.imgur.com/dEU4K.png)
Here is an alternate way to do that in Python/OpenCV. * Read the input * Threshold on color using cv2.inRange() * Apply morphology to clean it up and fill in holes as a mask * Create a grayscale version of the input * Merge the input and grayscale versions using the mask via np.where() * Save the results Input: [![enter image description here](https://i.stack.imgur.com/VVO1L.jpg)](https://i.stack.imgur.com/VVO1L.jpg) ``` import cv2 import numpy as np img = cv2.imread("orange_cone.jpg") # threshold on orange lower = (0,60,200) upper = (110,160,255) thresh = cv2.inRange(img, lower, upper) # apply morphology and make 3 channels as mask kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)) mask = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) mask = cv2.merge([mask,mask,mask]) # create 3-channel grayscale version gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) # blend img with gray using mask result = np.where(mask==255, img, gray) # save images cv2.imwrite('orange_cone_thresh.jpg', thresh) cv2.imwrite('orange_cone_mask.jpg', mask) cv2.imwrite('orange_cone_result.jpg', result) # Display images cv2.imshow("thresh", thresh) cv2.imshow("mask", mask) cv2.imshow("result", result) cv2.waitKey(0) ``` Threshold image: [![enter image description here](https://i.stack.imgur.com/wPag1.jpg)](https://i.stack.imgur.com/wPag1.jpg) Mask image: [![enter image description here](https://i.stack.imgur.com/eOrJA.jpg)](https://i.stack.imgur.com/eOrJA.jpg) Merged result: [![enter image description here](https://i.stack.imgur.com/TtVXP.jpg)](https://i.stack.imgur.com/TtVXP.jpg)
54,450,504
I was looking for this information for a while, but as additional packages and python versions can be installed through `homebrew` and `pip` I have the feeling that my environment is messed up. Furthermore a long time ago, I had installed some stuff with `sudo pip install` and as well `sudo python ~/get-pip.py`. Is there a trivial way of removing all danging dependencies and have python as it was when I first got the machine, or at least with only the packages that are delivered with the Mac distro?
2019/01/30
[ "https://Stackoverflow.com/questions/54450504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1767754/" ]
Technically inline JavaScript with a `<script>` tag could do what you are asking. You could even look into the many templating solutions available via JavaScript libraries. That would not actually provide any benefit, though. JavaScript changes what is ultimately displayed, not the file itself. Since your use case does not change the display it wouldn't actually be useful. It would be more efficient to consider why `&nbsp;` is appearing in the first place and fix that.
This … > > My html file contains in many places the code `&nbsp;&nbsp;&nbsp;` > > > … is actually what is wrong in your file! `&nbsp;` is not meant to use for layout purpose, you should fix that and use CSS instead to layout it correctly. `&nbsp;` is meant to stop breaking words at the end of a line that are seperated by a space. For example numbers and their unit: `5 liters` can end up with `5` at the end of the line and `liters` in the next line ([Example](http://jsfiddle.net/fL564sa0/)). To keep that together you would use `5&nbsp;liters`. That's what you use `&nbsp;` for and nothing else, especially **not** for layout purpose. --- To still answer your question: HTML is a *markup language* not a *programming language*. That means it is descriptive/static and not functional/dynamic. If you try to generate HTML dynamically you would need to use something like PHP or JavaScript.