qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
3,987,732
I have following python code: ``` def scrapeSite(urlToCheck): html = urllib2.urlopen(urlToCheck).read() from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(html) tdtags = soup.findAll('td', { "class" : "c" }) for t in tdtags: print t.encode('latin1') ``` This will return me f...
2010/10/21
[ "https://Stackoverflow.com/questions/3987732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123172/" ]
In this case, you can use `t.contents[1].contents[0]` to get FOO and BAR. The thing is that contents returns a list with all elements (Tags and NavigableStrings), if you print contents, you can see it's something like `[u'\n', <a href="more.asp">FOO</a>, u'\n']` So, to get to the actual tag you need to access `cont...
For your specific example, pyparsing's makeHTMLTags can be useful, since they are tolerant of many HTML variabilities in HTML tags, but provide a handy structure to the results: ``` html = """ <td class="c"> <a href="more.asp">FOO</a> </td> <td class="c"> <a href="alotmore.asp">BAR</a> </td> <td class="d"> <a h...
68,269,165
I have a problem. I've created model called "Flower", everything works fine, i can create new "Flowers", i can get data from them etc. The problem is when I want to use column "owner\_id" in SQL query I got an error that this column don't exist, despite I can use it to get data from objects (for example flower1.owner\_...
2021/07/06
[ "https://Stackoverflow.com/questions/68269165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16390472/" ]
Since `owner_id` is declared as a `ForeignKey`, it will be available in the actual SQL database as `owner_id_id`. The additional prefix `_id` is automatically appended by Django for that relational field. When using Django ORM, you would just access it via `owner_id` then Django will automatically handle things for you...
The problem is in field "owner\_id" of Flower model. When you define a Foreign Key in model, is not necessary to add "\_id" at the end since Django add it automatically in this case, should be enough replace ``` owner_id = models.ForeignKey(User, on_delete=models.CASCADE, default=1) ``` with ``` owner = models.For...
54,085,972
I am trying to run a playbook locally but I want all the vars in the role's task/main.yml file to refer to a group\_var in a specific inventory file. Unfortunately the playbook is unable to access to the group\_vars directory as if fail to recognize the vars specified in the role. The command ran is the following: `...
2019/01/08
[ "https://Stackoverflow.com/questions/54085972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3130919/" ]
So, theoretically adding localhost in the inventory would have been a good solution, but in my specific case (and in general for large deployments) was not an option. I also added `--extra-vars "myvar.json"` but did not work either. Turns out (evil detail...) that the right way to add a var file via command line is: ...
As per the error, your ansible is not able to read the group\_vars, Can you please make sure that your group\_vars have the same folder called localhost. Example Playbook host is localhost `- hosts: localhost become: true roles: - { role: common, tags: [ 'common' ] } - { role: docker, tags: [ 'docker' ] }` So in...
61,976,842
So i look into text recognition of licensplates. Im using google cloude service for this. it returns me a list of possible stuff. But also text on the image not containing the license plates get recognized. So i thought i could just tell python to take from the list the one text that matches the pattern of the licens...
2020/05/23
[ "https://Stackoverflow.com/questions/61976842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685847/" ]
You could use a regex for this: ``` ^[A-Z]{1,3}\s[A-Z]{1,2}\s\d{1,4}$ ``` An explanation: ``` ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- [A-Z]{1,2} ...
Here's a way: ``` import re string='frg3453453HHH AB 1234e456 2sf 3245 yKDEH A 4 554YFDN' print(re.findall('[A-Z]{1,3}\s[A-Z]{1,2}\s\d{1,4}',string)) ``` Output: ``` ['HHH AB 1234', 'DEH A 4'] ```
34,677,230
Given a list below: ``` snplist = [[1786, 0.0126525], [2463, 0.0126525], [2907, 0.0126525], [3068, 0.0126525], [3086, 0.0126525], [3398, 0.0126525], [5468,0.012654], [5531,0.0127005], [5564,0.0127005], [5580,0.0127005]] ``` I want to do a pairwise comparison of the second element in each sublist of the list, i.e. co...
2016/01/08
[ "https://Stackoverflow.com/questions/34677230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945881/" ]
You can `zip` the `snplist` with the same list excluding the first element, and do the comparison, like this ``` for l1, l2 in zip(snplist, snplist[1:]): if l1[1] == l2[1]: print l1[0], l2[0], l1[1] ``` Since you are comparing floating point numbers, I would recommend using [`math.isclose`](https://docs.py...
I suggest that you use `izip` for this to create a generator of item-neighbor pairs. Leaving the problem of comparing floating points aside, the code would look like this: ``` >>> from itertools import izip >>> lst = [[1,2], [3,4], [5,4], [7,8], [9,10], [11, 10]] >>> for item, next in izip(lst, lst[1:]): ... if it...
73,675,665
I know there are three thread mapping model in operating system. 1. One to One 2. Many to One 3. Many to Many In this question I assume we use **One to One model**. Let's say, right now I restart my computer, and there are **10** kernel-level threads already running. After a while, I decide to run a python program ...
2022/09/10
[ "https://Stackoverflow.com/questions/73675665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16030398/" ]
Kernel threads are like a specialized task responsible for doing a specific operation (not meant to last long). They are not threads waiting for incoming request from user-land threads. Moreover, a system call does not systematically create a kernel thread (see [this post](https://stackoverflow.com/questions/17683067/u...
To answer this question directly. You have mixed kernel threads and threading. They are not completely different concepts, but a little different at the OS level. Also, kernel threads may last indefinitely in many cases. There are at least three types of data, 1. `thread_info` - specific schedulable entity; always ex...
65,175,268
The formula below is a special case of the Wasserstein distance/optimal transport when the source and target distributions, `x` and `y` (also called marginal distributions) are 1D, that is, are vectors. [![enter image description here](https://i.stack.imgur.com/aKURS.jpg)](https://i.stack.imgur.com/aKURS.jpg) where *...
2020/12/07
[ "https://Stackoverflow.com/questions/65175268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11637005/" ]
Note that when *n* gets large we have that a sorted set of *n* samples approaches the inverse CDF sampled at 1/n, 2/n, ..., n/n. E.g.: ```py import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm plt.plot(norm.ppf(np.linspace(0, 1, 1000)), label="invcdf") plt.plot(np.sort(np.random.normal(size...
I guess I am a bit late but, but this is what I would do for an exact solution (using only numpy): ``` import numpy as np from numpy.random import randn n = 100 m = 80 p = 2 x = np.sort(randn(n)) y = np.sort(randn(m)) a = np.ones(n)/n b = np.ones(m)/m # cdfs ca = np.cumsum(a) cb = np.cumsum(b) # points on which we ne...
31,357,459
I try to understand the non-greedy regex in python, but I don't understand why the following examples have this results: ``` print(re.search('a??b','aaab').group()) ab print(re.search('a*?b','aaab').group()) aaab ``` I thought it would be 'b' for the first and 'ab' for the second. Can anyone explain that?
2015/07/11
[ "https://Stackoverflow.com/questions/31357459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5105884/" ]
This happens because the matches you are asking match *afterwards*. If you try to follow how the matching for `a??b` happens from left to right you'll see something like this: * Try 0 `a` plus `b` vs `aaab`: no match (`b != a`) * Try 1 `a` plus `b` vs `aaab` : no match (`ab != aa`) * Try 0 `a` plus `b` vs `aab`: no ma...
Its because of that `??` is [*lazy*](http://www.rexegg.com/regex-quantifiers.html#lazy_solution) while `?` is greedy.and a lazy quantifier will match zero or one (its left token), zero if that still allows the overall pattern to match.for example all the following will returns an empty string : ``` >>> print(re.search...
31,357,459
I try to understand the non-greedy regex in python, but I don't understand why the following examples have this results: ``` print(re.search('a??b','aaab').group()) ab print(re.search('a*?b','aaab').group()) aaab ``` I thought it would be 'b' for the first and 'ab' for the second. Can anyone explain that?
2015/07/11
[ "https://Stackoverflow.com/questions/31357459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5105884/" ]
This happens because the matches you are asking match *afterwards*. If you try to follow how the matching for `a??b` happens from left to right you'll see something like this: * Try 0 `a` plus `b` vs `aaab`: no match (`b != a`) * Try 1 `a` plus `b` vs `aaab` : no match (`ab != aa`) * Try 0 `a` plus `b` vs `aab`: no ma...
Explanation for the Pattern - `/a??b/` `a??` matches the character `a` literally (case sensitive), Then the quantifier `??` means Between zero and one time, as few times as possible, expanding as needed [lazy], then character `b` should match, literally (case sensitive) So It will match last `'ab'` characters in the ...
40,762,671
I want to run a process on a remote machine and I want it to get terminated when my host program exits. I have a small test script which looks like this: ``` import time while True: print('hello') time.sleep(1) ``` and I start this process on a remote machine via a script like this one: import paramiko ``...
2016/11/23
[ "https://Stackoverflow.com/questions/40762671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1668622/" ]
When the SSH connection is closed it'll not kill the running command on remote host. The easiest solution is: ``` ssh.exec_command('python /home/me/loop.py', get_pty=True) # ... do something ... ssh.close() ``` Then when the SSH connection is closed, the pty (on remote host) will also be closed and the kernel (on r...
Try [`closer`](https://haarcuba.github.io/closer/) - a library I've written specifically for this sort of thing. Doesn't use Paramiko, but perhaps it will work for you anyway.
44,354,394
how do I get a canvas to actually have a size? ``` root = Tk() canv = Canvas(root, width=600, height=600) canv.pack(fill = BOTH, expand = True) root.after(1, draw) mainloop() ``` just creates a window with a 1px canvas in the top left corner edit: I omitted draw, because it didn’t throw anything, thus didn’t seem ...
2017/06/04
[ "https://Stackoverflow.com/questions/44354394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4690599/" ]
Your canvas is not staying minimized. If you were to give the canvas a distinct background color you would see that it immediately fills the whole window, and stays that way. You are getting `1` for the window width and height because you aren't giving tkinter enough time to draw it before asking for the size. `winfo...
I was able to get your canvas to show up and work fine. It looks like your `init` function was the problem. You don't need to define a time to wait when calling your init() function just call it directly and the program will do the rest. Also I have looked over the tkinter documentation for canvas and I do not see any...
34,035,270
My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists). Input example: [6,4,6,2,3,6,9,6,1,6,5] Output example: [4,2,3,9,1,5,6,6,6,6,6] So far, I have been a...
2015/12/02
[ "https://Stackoverflow.com/questions/34035270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476661/" ]
Iterating the list reverse way, [pop](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) the element if it's 6, then [append](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) it. ``` xs = [6,4,6,2,3,6,9,6,1,6,5] for i in range(len(xs)-1, -1, -1): # 10 to 0 if xs[i] ==...
Why not try something like this? Basically, the approach is to first count the number of values. If 0, then returns (since Python produces a ValueError if the list.index method is called for an element not in the list). We can then set the first acceptable index for the value to be the length of the list minus the nu...
34,035,270
My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists). Input example: [6,4,6,2,3,6,9,6,1,6,5] Output example: [4,2,3,9,1,5,6,6,6,6,6] So far, I have been a...
2015/12/02
[ "https://Stackoverflow.com/questions/34035270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476661/" ]
Iterating the list reverse way, [pop](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) the element if it's 6, then [append](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) it. ``` xs = [6,4,6,2,3,6,9,6,1,6,5] for i in range(len(xs)-1, -1, -1): # 10 to 0 if xs[i] ==...
The key term here is "In Line". The way you do that is move `num[i] = num[i+1]` for each `i` to the end of the list. ``` def shift_sixes(num): for i, val in enumerate(num): if val == 6: # shift remaining items down for j in range(i,len(num)-1): num[j] = num[j+1] ...
34,035,270
My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists). Input example: [6,4,6,2,3,6,9,6,1,6,5] Output example: [4,2,3,9,1,5,6,6,6,6,6] So far, I have been a...
2015/12/02
[ "https://Stackoverflow.com/questions/34035270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476661/" ]
Iterating the list reverse way, [pop](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) the element if it's 6, then [append](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) it. ``` xs = [6,4,6,2,3,6,9,6,1,6,5] for i in range(len(xs)-1, -1, -1): # 10 to 0 if xs[i] ==...
Use two runners. First from front to end checking for 6s, second from end to front pointing to last item that's not a 6. Keep swapping (`a[i+1], a[i] = a[i], a[i+1]`) until they meet. **Catch:** this is not stable like in a stable sort. But I don't see that as a requirement. *Will try to write working code when in fr...
34,035,270
My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists). Input example: [6,4,6,2,3,6,9,6,1,6,5] Output example: [4,2,3,9,1,5,6,6,6,6,6] So far, I have been a...
2015/12/02
[ "https://Stackoverflow.com/questions/34035270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476661/" ]
Iterating the list reverse way, [pop](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) the element if it's 6, then [append](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) it. ``` xs = [6,4,6,2,3,6,9,6,1,6,5] for i in range(len(xs)-1, -1, -1): # 10 to 0 if xs[i] ==...
In case you need a stable sort (i.e. order of elements that are not 6 should remain the same), then the solution is: ``` def move_to_end(data, value): current = 0 # Instead of iterating with for, we iterate with index processed = 0 # How many elements we already found and moved to end of list length = len(...
34,035,270
My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists). Input example: [6,4,6,2,3,6,9,6,1,6,5] Output example: [4,2,3,9,1,5,6,6,6,6,6] So far, I have been a...
2015/12/02
[ "https://Stackoverflow.com/questions/34035270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476661/" ]
Iterating the list reverse way, [pop](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) the element if it's 6, then [append](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) it. ``` xs = [6,4,6,2,3,6,9,6,1,6,5] for i in range(len(xs)-1, -1, -1): # 10 to 0 if xs[i] ==...
Why not keep it simple? ``` a = [6,4,6,2,3,6,9,6,1,6,5] def shift_sixes(nums): for i in range(0,len(nums)): if nums[i] == 6: nums.append(nums.pop(i)) >>> shift_sixes(a) >>> a [3, 9, 1, 5, 2, 4, 6, 6, 6, 6] ```
34,035,270
My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists). Input example: [6,4,6,2,3,6,9,6,1,6,5] Output example: [4,2,3,9,1,5,6,6,6,6,6] So far, I have been a...
2015/12/02
[ "https://Stackoverflow.com/questions/34035270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476661/" ]
It is a bad idea to modify list while traverse. You can either make a copy to traverse, or generate a new list during traverse. In fact, the question can be done in many ways, such as: ``` >>> a.sort(key = lambda i: i == 6) >>> a [4, 2, 3, 9, 1, 5, 6, 6, 6, 6, 6] ```
Why not try something like this? Basically, the approach is to first count the number of values. If 0, then returns (since Python produces a ValueError if the list.index method is called for an element not in the list). We can then set the first acceptable index for the value to be the length of the list minus the nu...
34,035,270
My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists). Input example: [6,4,6,2,3,6,9,6,1,6,5] Output example: [4,2,3,9,1,5,6,6,6,6,6] So far, I have been a...
2015/12/02
[ "https://Stackoverflow.com/questions/34035270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476661/" ]
It is a bad idea to modify list while traverse. You can either make a copy to traverse, or generate a new list during traverse. In fact, the question can be done in many ways, such as: ``` >>> a.sort(key = lambda i: i == 6) >>> a [4, 2, 3, 9, 1, 5, 6, 6, 6, 6, 6] ```
The key term here is "In Line". The way you do that is move `num[i] = num[i+1]` for each `i` to the end of the list. ``` def shift_sixes(num): for i, val in enumerate(num): if val == 6: # shift remaining items down for j in range(i,len(num)-1): num[j] = num[j+1] ...
34,035,270
My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists). Input example: [6,4,6,2,3,6,9,6,1,6,5] Output example: [4,2,3,9,1,5,6,6,6,6,6] So far, I have been a...
2015/12/02
[ "https://Stackoverflow.com/questions/34035270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476661/" ]
It is a bad idea to modify list while traverse. You can either make a copy to traverse, or generate a new list during traverse. In fact, the question can be done in many ways, such as: ``` >>> a.sort(key = lambda i: i == 6) >>> a [4, 2, 3, 9, 1, 5, 6, 6, 6, 6, 6] ```
Use two runners. First from front to end checking for 6s, second from end to front pointing to last item that's not a 6. Keep swapping (`a[i+1], a[i] = a[i], a[i+1]`) until they meet. **Catch:** this is not stable like in a stable sort. But I don't see that as a requirement. *Will try to write working code when in fr...
34,035,270
My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists). Input example: [6,4,6,2,3,6,9,6,1,6,5] Output example: [4,2,3,9,1,5,6,6,6,6,6] So far, I have been a...
2015/12/02
[ "https://Stackoverflow.com/questions/34035270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476661/" ]
It is a bad idea to modify list while traverse. You can either make a copy to traverse, or generate a new list during traverse. In fact, the question can be done in many ways, such as: ``` >>> a.sort(key = lambda i: i == 6) >>> a [4, 2, 3, 9, 1, 5, 6, 6, 6, 6, 6] ```
In case you need a stable sort (i.e. order of elements that are not 6 should remain the same), then the solution is: ``` def move_to_end(data, value): current = 0 # Instead of iterating with for, we iterate with index processed = 0 # How many elements we already found and moved to end of list length = len(...
34,035,270
My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists). Input example: [6,4,6,2,3,6,9,6,1,6,5] Output example: [4,2,3,9,1,5,6,6,6,6,6] So far, I have been a...
2015/12/02
[ "https://Stackoverflow.com/questions/34035270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476661/" ]
It is a bad idea to modify list while traverse. You can either make a copy to traverse, or generate a new list during traverse. In fact, the question can be done in many ways, such as: ``` >>> a.sort(key = lambda i: i == 6) >>> a [4, 2, 3, 9, 1, 5, 6, 6, 6, 6, 6] ```
Why not keep it simple? ``` a = [6,4,6,2,3,6,9,6,1,6,5] def shift_sixes(nums): for i in range(0,len(nums)): if nums[i] == 6: nums.append(nums.pop(i)) >>> shift_sixes(a) >>> a [3, 9, 1, 5, 2, 4, 6, 6, 6, 6] ```
2,769,516
I'm trying to learn OpenGL ES quickly (I know, I know, but these are the pressures that have been thrusted upon me) and I have been read around a fair bit, which lots of success at rendering basic models, some basic lighting and 'some' texturing success too. But this is CONSTANTLY the point at which all OpenGL ES tuto...
2010/05/04
[ "https://Stackoverflow.com/questions/2769516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26310/" ]
1. something many people are surprised with when starting OpenGL development is that there's no such thing as a "OpenGL file format" for models, let alone animated ones. (DirectX for example comes with a .x file format supported right away). This is because OpenGL acts somewhat at a lower level. Of course, as tm1rbrt m...
1. Write or use a model loading library. Or use an existing graphics library; this will have routines to load models/textures already. 2. Animating models is done with bones in the 3d model editor. Graphics library will take care of moving the vertices etc for you. 3. No, artists create art and programmers create engin...
2,769,516
I'm trying to learn OpenGL ES quickly (I know, I know, but these are the pressures that have been thrusted upon me) and I have been read around a fair bit, which lots of success at rendering basic models, some basic lighting and 'some' texturing success too. But this is CONSTANTLY the point at which all OpenGL ES tuto...
2010/05/04
[ "https://Stackoverflow.com/questions/2769516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26310/" ]
Trying to explain why the answer to this question always will be vague. OpenGLES is very low level. Its all about pushing triangles to the screen and filling pixels and nothing else basicly. What you need to create a game is, as you've realised, a lot of code for managing assets, loading objects and worlds, managing ...
1. Write or use a model loading library. Or use an existing graphics library; this will have routines to load models/textures already. 2. Animating models is done with bones in the 3d model editor. Graphics library will take care of moving the vertices etc for you. 3. No, artists create art and programmers create engin...
2,769,516
I'm trying to learn OpenGL ES quickly (I know, I know, but these are the pressures that have been thrusted upon me) and I have been read around a fair bit, which lots of success at rendering basic models, some basic lighting and 'some' texturing success too. But this is CONSTANTLY the point at which all OpenGL ES tuto...
2010/05/04
[ "https://Stackoverflow.com/questions/2769516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26310/" ]
Trying to explain why the answer to this question always will be vague. OpenGLES is very low level. Its all about pushing triangles to the screen and filling pixels and nothing else basicly. What you need to create a game is, as you've realised, a lot of code for managing assets, loading objects and worlds, managing ...
1. something many people are surprised with when starting OpenGL development is that there's no such thing as a "OpenGL file format" for models, let alone animated ones. (DirectX for example comes with a .x file format supported right away). This is because OpenGL acts somewhat at a lower level. Of course, as tm1rbrt m...
71,868,469
I'm trying to save an object using cbv's im new to using it, and I'm trying to save an object using create view but is getting this error: "NOT NULL constraint failed: forum\_question.user\_id" I would appreciate beginner friendly explanation on how to fix this and maybe tips as well, thank you! models.py: ``` clas...
2022/04/14
[ "https://Stackoverflow.com/questions/71868469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17130619/" ]
A forum question instance must have a non null user field, but you are not specifying the user related to the object you're creating. In the case you dont want to add the user, update your model's user field to be: ``` user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) ...
I'm not sure if this is still useful, however, I ran into the same error. You can fix the error by deleting your migration files and the database. The error is due to the sending of NULL data(no data) to an already existing field in the database, usually after that field have been modified or deleted.
58,711,540
What is the equivalent of C++ STL set<> in python 3? If there is not an implementation what should I use in python to: 1) Store a list of numbers 2) Find a not less than element in that list? like lower\_bound<> of stl`s set
2019/11/05
[ "https://Stackoverflow.com/questions/58711540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6138473/" ]
The content scripts run in an "isolated world" which is a different context. By default devtools works in the page context so you need to [switch the context selector](https://developers.google.com/web/tools/chrome-devtools/console/reference#context) in devtools console toolbar to your extension: ![enter image descrip...
You can access your extension's console by right click on the extension popup and then selecting "Inspect".
7,943,751
What is the Python 3 equivalent of `python -m SimpleHTTPServer`?
2011/10/30
[ "https://Stackoverflow.com/questions/7943751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845948/" ]
Using 2to3 utility. ``` $ cat try.py import SimpleHTTPServer $ 2to3 try.py RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored try.py --- t...
In one of my projects I run tests against Python 2 and 3. For that I wrote a small script which starts a local server independently: ``` $ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")') Serving HTTP on 0.0.0.0 port 8000 ... ``` As an alias: ``` $ al...
7,943,751
What is the Python 3 equivalent of `python -m SimpleHTTPServer`?
2011/10/30
[ "https://Stackoverflow.com/questions/7943751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845948/" ]
From [the docs](https://docs.python.org/2/library/simplehttpserver.html): > > The `SimpleHTTPServer` module has been merged into `http.server` in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0. > > > So, your command is `python -m http.server`, or depending on your ...
The equivalent is: ``` python3 -m http.server ```
7,943,751
What is the Python 3 equivalent of `python -m SimpleHTTPServer`?
2011/10/30
[ "https://Stackoverflow.com/questions/7943751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845948/" ]
Using 2to3 utility. ``` $ cat try.py import SimpleHTTPServer $ 2to3 try.py RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored try.py --- t...
As everyone has mentioned [http.server](https://docs.python.org/3/library/http.server.html#module-http.server) module is equivalent to `python -m SimpleHTTPServer`. But as a warning from <https://docs.python.org/3/library/http.server.html#module-http.server> > > **Warning**: `http.server` is not recommended for prod...
7,943,751
What is the Python 3 equivalent of `python -m SimpleHTTPServer`?
2011/10/30
[ "https://Stackoverflow.com/questions/7943751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845948/" ]
The equivalent is: ``` python3 -m http.server ```
Using 2to3 utility. ``` $ cat try.py import SimpleHTTPServer $ 2to3 try.py RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored try.py --- t...
7,943,751
What is the Python 3 equivalent of `python -m SimpleHTTPServer`?
2011/10/30
[ "https://Stackoverflow.com/questions/7943751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845948/" ]
From [the docs](https://docs.python.org/2/library/simplehttpserver.html): > > The `SimpleHTTPServer` module has been merged into `http.server` in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0. > > > So, your command is `python -m http.server`, or depending on your ...
In addition to Petr's answer, if you want to bind to a specific interface instead of all the interfaces you can use `-b` or `--bind` flag. ``` python -m http.server 8000 --bind 127.0.0.1 ``` The above snippet should do the trick. 8000 is the port number. 80 is used as the standard port for HTTP communications.
7,943,751
What is the Python 3 equivalent of `python -m SimpleHTTPServer`?
2011/10/30
[ "https://Stackoverflow.com/questions/7943751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845948/" ]
In addition to Petr's answer, if you want to bind to a specific interface instead of all the interfaces you can use `-b` or `--bind` flag. ``` python -m http.server 8000 --bind 127.0.0.1 ``` The above snippet should do the trick. 8000 is the port number. 80 is used as the standard port for HTTP communications.
Just wanted to add what worked for me: `python3 -m http.server 8000` (you can use any port number here except the ones which are currently in use)
7,943,751
What is the Python 3 equivalent of `python -m SimpleHTTPServer`?
2011/10/30
[ "https://Stackoverflow.com/questions/7943751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845948/" ]
Using 2to3 utility. ``` $ cat try.py import SimpleHTTPServer $ 2to3 try.py RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored try.py --- t...
Just wanted to add what worked for me: `python3 -m http.server 8000` (you can use any port number here except the ones which are currently in use)
7,943,751
What is the Python 3 equivalent of `python -m SimpleHTTPServer`?
2011/10/30
[ "https://Stackoverflow.com/questions/7943751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845948/" ]
In addition to Petr's answer, if you want to bind to a specific interface instead of all the interfaces you can use `-b` or `--bind` flag. ``` python -m http.server 8000 --bind 127.0.0.1 ``` The above snippet should do the trick. 8000 is the port number. 80 is used as the standard port for HTTP communications.
As everyone has mentioned [http.server](https://docs.python.org/3/library/http.server.html#module-http.server) module is equivalent to `python -m SimpleHTTPServer`. But as a warning from <https://docs.python.org/3/library/http.server.html#module-http.server> > > **Warning**: `http.server` is not recommended for prod...
7,943,751
What is the Python 3 equivalent of `python -m SimpleHTTPServer`?
2011/10/30
[ "https://Stackoverflow.com/questions/7943751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845948/" ]
As everyone has mentioned [http.server](https://docs.python.org/3/library/http.server.html#module-http.server) module is equivalent to `python -m SimpleHTTPServer`. But as a warning from <https://docs.python.org/3/library/http.server.html#module-http.server> > > **Warning**: `http.server` is not recommended for prod...
In one of my projects I run tests against Python 2 and 3. For that I wrote a small script which starts a local server independently: ``` $ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")') Serving HTTP on 0.0.0.0 port 8000 ... ``` As an alias: ``` $ al...
7,943,751
What is the Python 3 equivalent of `python -m SimpleHTTPServer`?
2011/10/30
[ "https://Stackoverflow.com/questions/7943751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845948/" ]
The equivalent is: ``` python3 -m http.server ```
As everyone has mentioned [http.server](https://docs.python.org/3/library/http.server.html#module-http.server) module is equivalent to `python -m SimpleHTTPServer`. But as a warning from <https://docs.python.org/3/library/http.server.html#module-http.server> > > **Warning**: `http.server` is not recommended for prod...
7,976,733
I am relaying the output of my script to a local port in my system viz - $python script.py | nc 127.0.0.1 8033 Let's assume that my computer has ip 10.0.0.3 Now, Is it possible that some other computer (say IP 10.0.0.4) can listen to this port via nc or anything else. Please suggest.
2011/11/02
[ "https://Stackoverflow.com/questions/7976733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/270216/" ]
Not directly. The program listening on the port must be on the local machine (meaning 10.0.0.3 in your example). You could arrange for a program on the local machine to listen and send the information to another machine, but the socket connection can only be established on the host.
I use Perl to do exactly this - you could use python, of course. In Perl, I use the `IO::Socket::INET` library. I instantiate a new instance of `INET` with the `IP`, `port` and `Protocol`, and a time out for the `comms`. I then use the `recv` method to read data from that socket. It's not as simple as nc; I wish NC...
21,535,061
Is it possible to create a python program, that can interact with Google's Translate? I'm thinking of a way that firstly opens a .txt file, then reads the first line, then interacts with google translate and translates the word from a spesific language to a spesific language, then logs it into a different txt file. M...
2014/02/03
[ "https://Stackoverflow.com/questions/21535061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2802035/" ]
Oh, the mind-bending horror of weak memory ordering... The first snippet is your basic atomic read-modify-write - if someone else touches whatever address `x1` points to, the store-exclusive will fail and it will try again until it succeeds. So far so good. However, this only applies to the address (or more rightly re...
I would guess that this is simply a way of reproducing existing architecture-independent semantics for this operation. With the `ldaxr`/`stlxr` pair, the above sequence will assure correct ordering if the AtomicAdd32 is used as a synchronization mechanism (mutex/semaphore) - regardless of whether the resulting higher-...
21,535,061
Is it possible to create a python program, that can interact with Google's Translate? I'm thinking of a way that firstly opens a .txt file, then reads the first line, then interacts with google translate and translates the word from a spesific language to a spesific language, then logs it into a different txt file. M...
2014/02/03
[ "https://Stackoverflow.com/questions/21535061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2802035/" ]
`OSAtomicAdd32Barrier()` exists for people that are using `OSAtomicAdd()` for something beyond just atomic increment. Specifically, they are implementing their own multi-processing synchronization primitives based on `OSAtomicAdd()`. For example, creating their own mutex library. `OSAtomicAdd32Barrier()` uses heavy bar...
I would guess that this is simply a way of reproducing existing architecture-independent semantics for this operation. With the `ldaxr`/`stlxr` pair, the above sequence will assure correct ordering if the AtomicAdd32 is used as a synchronization mechanism (mutex/semaphore) - regardless of whether the resulting higher-...
66,357,772
django+gunicorn+nginx gives 404 while serving static files I am trying to deploy a Django project using nginx + gunicorn + postgresql. All the configuration is done, my admin panel project static file will serve , but other static files; it returns a 404 error.(iam use run python manage.py collectstatic) ``` my error...
2021/02/24
[ "https://Stackoverflow.com/questions/66357772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14751614/" ]
Try In ---- nginx.conf: ``` location /static/ { autoindex off; alias /home/ubuntu/blogpy/static/; #add full path of static file directry } ```
To get /blogpy/home/static/ files been copied into /blogpy/static/ by collectstatic command, you need to specify STATICFILES\_DIRS setting <https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-STATICFILES_DIRS> ``` STATICFILES_DIRS = [ BASE_DIR / 'home' / 'static', ] ```
66,357,772
django+gunicorn+nginx gives 404 while serving static files I am trying to deploy a Django project using nginx + gunicorn + postgresql. All the configuration is done, my admin panel project static file will serve , but other static files; it returns a 404 error.(iam use run python manage.py collectstatic) ``` my error...
2021/02/24
[ "https://Stackoverflow.com/questions/66357772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14751614/" ]
Try In ---- nginx.conf: ``` location /static/ { autoindex off; alias /home/ubuntu/blogpy/static/; #add full path of static file directry } ```
It is recommended to serve static files directly from `nginx`. Add the following to your nginx site config. ``` location /static/ { alias /path/to/static/directory/; } ```
59,802,608
I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it? ``` import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95): print(...
2020/01/18
[ "https://Stackoverflow.com/questions/59802608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11214617/" ]
Tensorflow 2.0 ============== ``` DESIRED_ACCURACY = 0.979 class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epochs, logs={}) : if(logs.get('acc') is not None and logs.get('acc') >= DESIRED_ACCURACY) : print('\nReached 99.9% accuracy so cancelling training!') se...
I had the same problem and instead of using 'acc', I changed it to 'accuracy' everywhere. So it seems that maybe it is better to try changing 'acc' to 'accuracy'.
59,802,608
I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it? ``` import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95): print(...
2020/01/18
[ "https://Stackoverflow.com/questions/59802608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11214617/" ]
we are in the same boat from Coursera Course So, this is my code ``` # GRADED FUNCTION: train_mnist def train_mnist(): # Please write your code only where you are indicated. # please do not remove # model fitting inline comments. # YOUR CODE SHOULD START HERE class myCallback(tf.keras.callbacks.Callb...
I had the same problem and instead of using 'acc', I changed it to 'accuracy' everywhere. So it seems that maybe it is better to try changing 'acc' to 'accuracy'.
59,802,608
I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it? ``` import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95): print(...
2020/01/18
[ "https://Stackoverflow.com/questions/59802608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11214617/" ]
Inside your callback try this : ``` class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): print("---",logs,"---") ''' if(logs.get('acc')>=0.99): print("Reached 99% accuracy so cancelling training!") ''' ``` It gave me this **`--- {'loss...
we are in the same boat from Coursera Course So, this is my code ``` # GRADED FUNCTION: train_mnist def train_mnist(): # Please write your code only where you are indicated. # please do not remove # model fitting inline comments. # YOUR CODE SHOULD START HERE class myCallback(tf.keras.callbacks.Callb...
59,802,608
I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it? ``` import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95): print(...
2020/01/18
[ "https://Stackoverflow.com/questions/59802608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11214617/" ]
Do not use `accuracy` use `acc` instead in this particular case since `logs.get()` is not working on `accuracy` but normally both works for common callback blocks in `TF`. If someone is looking for this issue while doing the Coursera course, this is the simplest answer to get around this problem.
I had the same problem and instead of using 'acc', I changed it to 'accuracy' everywhere. So it seems that maybe it is better to try changing 'acc' to 'accuracy'.
59,802,608
I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it? ``` import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95): print(...
2020/01/18
[ "https://Stackoverflow.com/questions/59802608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11214617/" ]
Try using try-except ``` class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs = {}): try: if(logs.get('acc')>0.95): print("\nReached") self.model.stop_training = True except: if(logs.get('accuracy')>0.95): print("Reached!!!") self.model...
I had the same problem and instead of using 'acc', I changed it to 'accuracy' everywhere. So it seems that maybe it is better to try changing 'acc' to 'accuracy'.
59,802,608
I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it? ``` import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95): print(...
2020/01/18
[ "https://Stackoverflow.com/questions/59802608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11214617/" ]
it seems that your error is similar to [Exception with Callback in Keras - Tensorflow 2.0 - Python](https://stackoverflow.com/questions/56423505/exception-with-callback-in-keras-tensorflow-2-0-python) try replacing `logs.get('acc')` with `logs.get('accuracy')`
we are in the same boat from Coursera Course So, this is my code ``` # GRADED FUNCTION: train_mnist def train_mnist(): # Please write your code only where you are indicated. # please do not remove # model fitting inline comments. # YOUR CODE SHOULD START HERE class myCallback(tf.keras.callbacks.Callb...
59,802,608
I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it? ``` import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95): print(...
2020/01/18
[ "https://Stackoverflow.com/questions/59802608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11214617/" ]
Tensorflow 2.0 ============== ``` DESIRED_ACCURACY = 0.979 class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epochs, logs={}) : if(logs.get('acc') is not None and logs.get('acc') >= DESIRED_ACCURACY) : print('\nReached 99.9% accuracy so cancelling training!') se...
Use 'acc' instead of 'accuracy' and you don't need to change.
59,802,608
I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it? ``` import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95): print(...
2020/01/18
[ "https://Stackoverflow.com/questions/59802608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11214617/" ]
It works in Python2 because in Python2 you can compare `None` with `float` but this is not possible in Python3. This line ``` logs.get('acc') ``` returns `None` and there is your problem. Quick solution would be to replace the condition with ``` if logs.get('acc') is not None and logs.get('acc') > 0.95: ``` If...
I had the same problem and instead of using 'acc', I changed it to 'accuracy' everywhere. So it seems that maybe it is better to try changing 'acc' to 'accuracy'.
59,802,608
I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it? ``` import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95): print(...
2020/01/18
[ "https://Stackoverflow.com/questions/59802608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11214617/" ]
we are in the same boat from Coursera Course So, this is my code ``` # GRADED FUNCTION: train_mnist def train_mnist(): # Please write your code only where you are indicated. # please do not remove # model fitting inline comments. # YOUR CODE SHOULD START HERE class myCallback(tf.keras.callbacks.Callb...
Do not use `accuracy` use `acc` instead in this particular case since `logs.get()` is not working on `accuracy` but normally both works for common callback blocks in `TF`. If someone is looking for this issue while doing the Coursera course, this is the simplest answer to get around this problem.
59,802,608
I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it? ``` import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95): print(...
2020/01/18
[ "https://Stackoverflow.com/questions/59802608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11214617/" ]
It works in Python2 because in Python2 you can compare `None` with `float` but this is not possible in Python3. This line ``` logs.get('acc') ``` returns `None` and there is your problem. Quick solution would be to replace the condition with ``` if logs.get('acc') is not None and logs.get('acc') > 0.95: ``` If...
Do not use `accuracy` use `acc` instead in this particular case since `logs.get()` is not working on `accuracy` but normally both works for common callback blocks in `TF`. If someone is looking for this issue while doing the Coursera course, this is the simplest answer to get around this problem.
32,991,119
I am writing C extensions for python. I am just experimenting for the time being and I have written a hello world extension that looks like this : ``` #include <Python2.7/Python.h> static PyObject* helloworld(PyObject* self) { return Py_BuildValue("s", "Hello, Python extensions!!"); } static char helloworld_doc...
2015/10/07
[ "https://Stackoverflow.com/questions/32991119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5414031/" ]
You can simply compile the extension without installing (usually something like `python setup.py build`). Then you have to make sure the interpreter can find the compiled module (for example by copying it next to a script that imports it, or setting `PYTHONPATH`).
You can create your "own interpreter" by not extending python, but embedding it into your application. In that way, your objects will be always available for the users who are running your program. This is a pretty common thing to do in certain cases, for example look at the Blender project where all the `bpy`, `bmesh`...
31,962,569
I am working on MQTT and using python paho-mqtt <https://pypi.python.org/pypi/paho-mqtt> I am unable to understand how can I publish msg to a specific client or list of clients? I'll appreciate your help.
2015/08/12
[ "https://Stackoverflow.com/questions/31962569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073780/" ]
This isn't directly possible with strict MQTT, although some brokers may offer that functionality, or you can construct your application so that the topic design works to do what you need.
Although I do agree that in some cases it would be useful to send a message to a particular client (or list of clients) that's simply not how the publish/subscribe messaging paradigm works. [Read more on the publish-subscribe pattern on Wikipedia.](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) If all...
61,581,612
i am in the process of converting some cython code to python, and it went well until i came to the bitwise operations. Here is a snippet of the code: ``` in_buf_word = b'\xff\xff\xff\xff\x00' bits = 8 in_buf_word >>= bits ``` If i run this it will spit out this error: ``` TypeError: unsupported operand type(s) for ...
2020/05/03
[ "https://Stackoverflow.com/questions/61581612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13462790/" ]
``` import bitstring in_buf_word = b'\xff\xff\xff\xff\x00' bits = 8 in_buf_word = bitstring.BitArray(in_buf_word ) >> bits ``` If you dont have it. Go to your terminal ``` pip3 install bitstring --> python 3 pip install bitstring --> python 2 ``` To covert it back into bytes use the tobytes() method: ``` print(...
Shifting to the right by 8 bits just means cutting off the rightmost byte. Since you already have a `bytes` object, this can be done more easily: ``` in_buf_word = in_buf_word[:-1] ```
61,581,612
i am in the process of converting some cython code to python, and it went well until i came to the bitwise operations. Here is a snippet of the code: ``` in_buf_word = b'\xff\xff\xff\xff\x00' bits = 8 in_buf_word >>= bits ``` If i run this it will spit out this error: ``` TypeError: unsupported operand type(s) for ...
2020/05/03
[ "https://Stackoverflow.com/questions/61581612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13462790/" ]
``` import bitstring in_buf_word = b'\xff\xff\xff\xff\x00' bits = 8 in_buf_word = bitstring.BitArray(in_buf_word ) >> bits ``` If you dont have it. Go to your terminal ``` pip3 install bitstring --> python 3 pip install bitstring --> python 2 ``` To covert it back into bytes use the tobytes() method: ``` print(...
You can do it by converting the bytes into an integer, shifting that, and then converting the result back into a byte string. ``` in_buf_word = b'\xff\xff\xff\xff\x00' bits = 8 print(in_buf_word) # -> b'\xff\xff\xff\xff\x00' temp = int.from_bytes(in_buf_word, byteorder='big') >> bits in_buf_word = temp.to_bytes(len(...
10,331,413
I am working on the exel parsing using python. till now I have worked with english language but when I encounter the regional languages, I am getting the error. example : ``` IR05 měsíční (monthly) ``` It gives me the error as ``` UnicodeEncodeError: 'ascii' codec can't encode character u'\u011b' in position...
2012/04/26
[ "https://Stackoverflow.com/questions/10331413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
``` >>> "IR05 měsíční (monthly)".decode('utf8') u'IR05 m\u011bs\xed\u010dn\xed (monthly)' ``` which is a unicode version of your original string (which was encoded in utf8). Now you can compare it to your other string (from the file), which you decode (from utf8 or latin2 or a different format) and you can compare t...
the error may be caused by str(j), try this: ``` for j in val: print 'j is - ', j j.replace("'", "") ```
16,269,396
I know I've seen clean examples on the proper way to do this, and could even swear it was in one of the standard python libraries. I can't seem to find it now. Could you please point me in the right direction. Iterator for a list of lists that only returns arbitrary values from the sub-list. The idea is to have this i...
2013/04/29
[ "https://Stackoverflow.com/questions/16269396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2097818/" ]
Perhaps you were thinking of `itemgetter`? ``` >>> from operator import itemgetter >>> map(itemgetter(2), alist) [3, 6, 9] ``` But that doesn't leave the elements in sublists ``` only_some_values = [[x[2]] for x in alist] ``` Gives your desired output
Here is what I had in mind: ``` from operator import itemgetter alist = [ [1,2,3,4,5], [2,4,6,8,10], [3,6,9,12,15] ] [list(x) for x in zip(map(itemgetter(2),alist), map(itemgetter(0),alist)) ] [[3,1], [6,2], [9,3]] ``` The idea is that you keep the left sid...
48,252,967
I'm currently doing a system that scrap data from foursquare. Right now i have scrap the review from the website using python and beautiful soup and have a json file like below ``` {"review": "From sunset too variety food u cant liked it.."}{"review": "Byk motor laju2"}{"review": "Good place to chill"}{"review": "If y...
2018/01/14
[ "https://Stackoverflow.com/questions/48252967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9216577/" ]
It depends on your usages. Basically, MongoDB is suitable for JSON document so, you will be able to insert your Python object "directly". If you want/need to use MySQL, you will probably need to perform some transformations before inserting. Check this post for more information: [Inserting JSON into MySQL using Python]...
You can convert your json into a string (json.dumps()) and store in a character field. Or, Django has support for JSONField when using Postgres ([docs](https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#jsonfield)), this has some additional features like querying inside the json
44,060,080
The subject of the study was taken from [Text processing and detection from a specific dictionary in python](https://stackoverflow.com/questions/43988958/text-processing-and-detection-from-a-specific-dictionary-in-python/43989724#43989724) topic. Perhaps i misunderstood the OP's problem but i have tried to improve the ...
2017/05/19
[ "https://Stackoverflow.com/questions/44060080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8016168/" ]
If I understood correctly, you want to find the number of times a "keyword" appears in a text. You can use the "re" module for this. ``` import re dict_1={"Liquid Biopsy":"Blood for analysis","cfDNA":"Blood for analysis", "asfdafaf":"dunno"} list_1=[u'Liquid', u'biopsy',u'based', u'on', u'circulating', u'cell-free', ...
Recently i have learned a new method about counting how many times does a dictionary key repeat in a plain text without importing "re" module. Perhaps it's suitable to put another method in this topic. ``` dict_1={"Liquid Biopsy":"Blood for analysis","cfDNA":"Blood for analysis"} list_1=[u'Liquid', u'biopsy', u'liquid...
54,830,602
Preface ======= I understand that `dict`s/`set`s should be created/updated with hashable objects only due to their implementation, so when this kind of code fails ``` >>> {{}} # empty dict of empty dict Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: unhashable type: 'dict' ``` ...
2019/02/22
[ "https://Stackoverflow.com/questions/54830602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5997596/" ]
I have found a solution and want to share it here so it helps someone else looking to do the same thing. The user running the docker command (without sudo) needs to have the docker group. So I tried adding the service account as a user and gave it the docker group and that's it. `docker login` to gcr worked and so did ...
As stated in this [article](https://docs.docker.com/install/linux/linux-postinstall/), the steps you taken are the correct way to do it. Adding users to the "docker" group will allow the users to run docker commands as non root. If you create a new service account and would like to have that service account run docker ...
32,834,419
I received this message: ``` --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-23-60bbe78150c2> in <module>() 17 men_only_stats=data[0::4]!="male" 18 ---> 19 women_onboard = data[women_onl...
2015/09/29
[ "https://Stackoverflow.com/questions/32834419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5386822/" ]
You need to use `getChildFragmentManager()` instead of `getFragmentManager()` for placing and managing Fragments inside of a Fragment. So ``` public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); view = inflater.inflate(R.layou...
Try calling `getChildFragmentManager()` instead of `getFragmentManager()` and see if that helps.
72,590,538
I have 2 models 1) patientprofile and 2) medInfo. In the first model patientprofile, I am trying to get patients informations like (name and other personal information) and 2nd model I want to add patients Medical information data.. when I am trying check is there a existing medical information for the patient then sho...
2022/06/12
[ "https://Stackoverflow.com/questions/72590538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15837741/" ]
You have to make sure to understand the difference between string literals [1] and references to exported attribute(s) from the resources [2]. The way you are currently trying to get the output means it will output `aws_subnet.main.availability_zone[*]` as a string literal. To make sure you get the values you just need...
If your goal is to display all the Availability Zones in a region, you don't necessary need to iterate over your subnets you have created. You simply display the names from the `data.aws_availability_zones`: ```hcl data "aws_availability_zones" "available" { state = "available" } output "list_of_az" { value = dat...
32,833,575
I a new to python and am stuck on this one exercise. I am supposed to enter a sentence and find the longest word. If there are two or more words that have the same longest length, then it is to return the first word. This is what I have so far: ``` def find_longest_word(word_list): longest_word = '' for wo...
2015/09/28
[ "https://Stackoverflow.com/questions/32833575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5386649/" ]
Use `max` python built-in function, using as `key` parameter the `len` function. It would iterate over `word_list` applying `len` function and then returning the longest one. ``` def find_longest_word(word_list): longest_word = max(word_list, key=len) return longest_word ```
You shouldn't print out the length of each word. Instead, compare the length of the current `word` and the length of `longest_word`. If `word` is longer, you update `longest_word` to `word`. When you have been through all words, the longest world will be stored in `longest_word`. Then you can print or return it. ``` ...
32,833,575
I a new to python and am stuck on this one exercise. I am supposed to enter a sentence and find the longest word. If there are two or more words that have the same longest length, then it is to return the first word. This is what I have so far: ``` def find_longest_word(word_list): longest_word = '' for wo...
2015/09/28
[ "https://Stackoverflow.com/questions/32833575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5386649/" ]
Use `max` python built-in function, using as `key` parameter the `len` function. It would iterate over `word_list` applying `len` function and then returning the longest one. ``` def find_longest_word(word_list): longest_word = max(word_list, key=len) return longest_word ```
Compare each word to the longest one yet, starting with the length of 0. If the word is longer than the longest yet, update the word and the longest\_size. Should look similar to this: ``` def find_longest_word(word_list): longest_word = '' longest_size = 0 for word in word_list: if len(word) >...
32,833,575
I a new to python and am stuck on this one exercise. I am supposed to enter a sentence and find the longest word. If there are two or more words that have the same longest length, then it is to return the first word. This is what I have so far: ``` def find_longest_word(word_list): longest_word = '' for wo...
2015/09/28
[ "https://Stackoverflow.com/questions/32833575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5386649/" ]
You shouldn't print out the length of each word. Instead, compare the length of the current `word` and the length of `longest_word`. If `word` is longer, you update `longest_word` to `word`. When you have been through all words, the longest world will be stored in `longest_word`. Then you can print or return it. ``` ...
Compare each word to the longest one yet, starting with the length of 0. If the word is longer than the longest yet, update the word and the longest\_size. Should look similar to this: ``` def find_longest_word(word_list): longest_word = '' longest_size = 0 for word in word_list: if len(word) >...
14,369,739
I'm used to using dicts to represent graphs in python, but I'm running into some serious performance issues with large graphs and complex calculations, so I think I should cross over to using adjacency matrixes to bypass the overhead of hash tables. My question is, if I have a graph of the form g: {node: {vertex: weigh...
2013/01/16
[ "https://Stackoverflow.com/questions/14369739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1427661/" ]
Probably not the most efficient, but a simple way to convert your format to an adjacency matrix on a list-basis could look like this: ``` g = {1:{2:.5, 3:.2}, 2:{4:.7}, 4:{5:.6, 3:.3}} hubs = g.items() # list of nodes and outgoing vertices size=max(map(lambda hub: max(hub[0], max(hub[1].keys())), hubs))+1 # matrix dim...
Well to implement in a adjacency list, you can create two classes, one for storing the information about the vertex's. ``` # Vertex, which will represent each vertex in the graph.Each Vertex uses a dictionary # to keep track of the vertices to which it is connected, and the weight of each edge. class Vertex: # Initi...
48,266,643
I have the 2d list mainlist ``` mainlist = [['John','Doe',True],['Mary','Jane',False],['James','Smith',False]] slist1 = ['John', 'Doe'] slist2 = ['John', 'Smith'] slist3 = ['Doe', 'John'] slist4 = ['John', True] ``` How to determine if a sublist of a sublist exists in a list where if slist1 is tested against mainlis...
2018/01/15
[ "https://Stackoverflow.com/questions/48266643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8573372/" ]
You could take an array with references to the wanted arrays and as index for the array for pusing the remainder value of the actual index and the length of the temporary array. ```js var array = ['fruit', 'vegetables', 'sugars', 'bread', 'fruit', 'vegetables', 'sugars', 'bread'], fruits = [], // final array...
Not super elegant but it will do the job.. ```js var a = ['bread_1','fruit_1','vegetable_1','sugars_1', 'bread_2','fruit_2','vegetable_2','sugars_2', 'bread_3','fruit_3','vegetable_3','sugars_3']; var i=0; a = a.reduce(function(ac, va, id, ar){ if(i==ac.length) i=0; ac[i].push(va); i++; retur...
48,266,643
I have the 2d list mainlist ``` mainlist = [['John','Doe',True],['Mary','Jane',False],['James','Smith',False]] slist1 = ['John', 'Doe'] slist2 = ['John', 'Smith'] slist3 = ['Doe', 'John'] slist4 = ['John', True] ``` How to determine if a sublist of a sublist exists in a list where if slist1 is tested against mainlis...
2018/01/15
[ "https://Stackoverflow.com/questions/48266643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8573372/" ]
You could take an array with references to the wanted arrays and as index for the array for pusing the remainder value of the actual index and the length of the temporary array. ```js var array = ['fruit', 'vegetables', 'sugars', 'bread', 'fruit', 'vegetables', 'sugars', 'bread'], fruits = [], // final array...
I suggest (since the pattern may vary) to create an array with categories and what elements those categories include, thus creating an object with keys identifying your categories. The variables are not 'declared' outside the object but you can access the object keys the same way you'd have different variables: ``` /...
34,898,525
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: ``` date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',...
2016/01/20
[ "https://Stackoverflow.com/questions/34898525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480116/" ]
With pandas, you can have a one liner like this: ``` import pandas as pd date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = [i.strftime("%b-%y") for i in pd.date_range(start=date1, end=date2, freq='MS')] ```
Here is my solution with a simple list comprehension which uses `range` to know where months must start and end ``` from datetime import datetime as dt sd = dt.strptime('2014-10-10', "%Y-%m-%d") ed = dt.strptime('2016-01-07', "%Y-%m-%d") lst = [dt.strptime('%2.2d-%2.2d' % (y, m), '%Y-%m').strftime('%b-%y') \ ...
34,898,525
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: ``` date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',...
2016/01/20
[ "https://Stackoverflow.com/questions/34898525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480116/" ]
If you want a dictionary that contains pair of month's starting date and ending date between your desired years, then here's how to get that. ``` start_year = int(input("Enter Starting Year: ")) end_year = int(input("Enter Ending Year: ")) import calendar month_dict = {} for x in range(start_year, end_year): for y...
here is the similar version of what Pynchia suggestioned, the below implementation is for python 3.8 the one he implemented is for python 2.x ``` import datetime st="2020-06-24" ed="2020-11-24" start_date = datetime.datetime.strptime(st.strip(), '%Y-%m-%d') end_date = datetime.datetime.strptime(ed.strip(), '%Y-%m-%d')...
34,898,525
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: ``` date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',...
2016/01/20
[ "https://Stackoverflow.com/questions/34898525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480116/" ]
Here is my solution with a simple list comprehension which uses `range` to know where months must start and end ``` from datetime import datetime as dt sd = dt.strptime('2014-10-10', "%Y-%m-%d") ed = dt.strptime('2016-01-07', "%Y-%m-%d") lst = [dt.strptime('%2.2d-%2.2d' % (y, m), '%Y-%m').strftime('%b-%y') \ ...
Having done similar stuff previously, I took a stab at solving this. Using distinct components for doing this is more flexible and enables you to mix and match them for different use-cases. They also can be tested more easily this way, as you can see by the doctests in `iterate_months`. Also I suggest to use `datetime...
34,898,525
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: ``` date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',...
2016/01/20
[ "https://Stackoverflow.com/questions/34898525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480116/" ]
``` >>> from datetime import datetime, timedelta >>> from collections import OrderedDict >>> dates = ["2014-10-10", "2016-01-07"] >>> start, end = [datetime.strptime(_, "%Y-%m-%d") for _ in dates] >>> OrderedDict(((start + timedelta(_)).strftime(r"%b-%y"), None) for _ in xrange((end - start).days)).keys() ['Oct-14', 'N...
Try this out, it will list down all the month from start to end as a continuous chain starting from the start date. ``` import datetime a='2021-12-1' b='2022-1-2' d1=datetime.datetime.strptime(a,'%Y-%m-%d') d2=datetime.datetime.strptime(b,'%Y-%m-%d') months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'S...
34,898,525
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: ``` date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',...
2016/01/20
[ "https://Stackoverflow.com/questions/34898525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480116/" ]
Here is my solution with a simple list comprehension which uses `range` to know where months must start and end ``` from datetime import datetime as dt sd = dt.strptime('2014-10-10', "%Y-%m-%d") ed = dt.strptime('2016-01-07', "%Y-%m-%d") lst = [dt.strptime('%2.2d-%2.2d' % (y, m), '%Y-%m').strftime('%b-%y') \ ...
I came to a solution that uses `python-dateutil` and works with Python 3.8+: <https://gist.github.com/anatoly-scherbakov/593770d446a06f109438a134863ba969> ``` def month_range( start: datetime.date, end: datetime.date, ) -> Iterator[datetime.date]: """Yields the 1st day of each month in the given date rang...
34,898,525
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: ``` date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',...
2016/01/20
[ "https://Stackoverflow.com/questions/34898525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480116/" ]
You have to use [Calendar](https://docs.python.org/2/library/calendar.html#module-calendar) and [Datetime](https://docs.python.org/2/library/datetime.html) ``` import calendar from datetime import * date1 = datetime.strptime("2014-10-10", "%Y-%m-%d") date2 = datetime.strptime("2016-01-07", "%Y-%m-%d") date1 = date1.r...
here is the similar version of what Pynchia suggestioned, the below implementation is for python 3.8 the one he implemented is for python 2.x ``` import datetime st="2020-06-24" ed="2020-11-24" start_date = datetime.datetime.strptime(st.strip(), '%Y-%m-%d') end_date = datetime.datetime.strptime(ed.strip(), '%Y-%m-%d')...
34,898,525
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: ``` date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',...
2016/01/20
[ "https://Stackoverflow.com/questions/34898525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480116/" ]
With pandas, you can have a one liner like this: ``` import pandas as pd date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = [i.strftime("%b-%y") for i in pd.date_range(start=date1, end=date2, freq='MS')] ```
Having done similar stuff previously, I took a stab at solving this. Using distinct components for doing this is more flexible and enables you to mix and match them for different use-cases. They also can be tested more easily this way, as you can see by the doctests in `iterate_months`. Also I suggest to use `datetime...
34,898,525
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: ``` date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',...
2016/01/20
[ "https://Stackoverflow.com/questions/34898525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480116/" ]
Having done similar stuff previously, I took a stab at solving this. Using distinct components for doing this is more flexible and enables you to mix and match them for different use-cases. They also can be tested more easily this way, as you can see by the doctests in `iterate_months`. Also I suggest to use `datetime...
here is the similar version of what Pynchia suggestioned, the below implementation is for python 3.8 the one he implemented is for python 2.x ``` import datetime st="2020-06-24" ed="2020-11-24" start_date = datetime.datetime.strptime(st.strip(), '%Y-%m-%d') end_date = datetime.datetime.strptime(ed.strip(), '%Y-%m-%d')...
34,898,525
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: ``` date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',...
2016/01/20
[ "https://Stackoverflow.com/questions/34898525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480116/" ]
I found a very succinct way to do this with Pandas, sharing in case it helps anybody: --- **UPDATE:** I've got it down to a one-liner with the help of [this post](https://stackoverflow.com/questions/37890391/how-to-include-end-date-in-pandas-date-range-method) :) ``` pd.date_range('2014-10-10','2016-01-07', ...
I came to a solution that uses `python-dateutil` and works with Python 3.8+: <https://gist.github.com/anatoly-scherbakov/593770d446a06f109438a134863ba969> ``` def month_range( start: datetime.date, end: datetime.date, ) -> Iterator[datetime.date]: """Yields the 1st day of each month in the given date rang...
34,898,525
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: ``` date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',...
2016/01/20
[ "https://Stackoverflow.com/questions/34898525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480116/" ]
Here is my solution with a simple list comprehension which uses `range` to know where months must start and end ``` from datetime import datetime as dt sd = dt.strptime('2014-10-10', "%Y-%m-%d") ed = dt.strptime('2016-01-07', "%Y-%m-%d") lst = [dt.strptime('%2.2d-%2.2d' % (y, m), '%Y-%m').strftime('%b-%y') \ ...
Find below my approach to this problem using **split** and simple **modulo-based** iterations without importing any special module. ``` date1 = "2014-10-10" date2 = "2016-01-07" y0 = int( date1.split('-')[0] ) # 2014 y1 = int( date2.split('-')[0] ) # 2016 m0 = int( date1.split('-')[1] ) - 1 # 10-1 --> 9 because will...
58,872,437
I launched `Jupyter Notebook`, created a new notebook in `python`, imported the necessary `libraries` and tried to access a `.xlsx` file on the desktop with this `code`: `haber = pd.read_csv('filename.xlsx')` but error keeps popping up. Want a reliable way of accessing this file on my desktop without incurring any e...
2019/11/15
[ "https://Stackoverflow.com/questions/58872437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11003573/" ]
If you open the developer console, you'll see there's an error in one of the templates (DishDetailComponent.html@75:9): [![Error in template DishDetailComponent.html@75:9](https://i.stack.imgur.com/iH8LI.png)](https://i.stack.imgur.com/iH8LI.png) As you can see, it complains about there's no `dividerColor` property i...
I found a changes log here: <https://www.reddit.com/r/Angular2/comments/86ta8k/angular_material_600beta5_changelog/> and replaced all `dividerColor`s with `color` in my project and it worked! Thanks for @Fel's help.
49,488,989
I'm looking into the Twitter Search API, and apparently, it has a count parameter that determines "The number of tweets to return per page, up to a maximum of 100." What does "per page" mean, if I'm for example running a python script like this: ``` import twitter #python-twitter package api = twitter.Api(consumer_key...
2018/03/26
[ "https://Stackoverflow.com/questions/49488989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3128156/" ]
Tweepy has a `Cursor` object that works like this: ``` for tweet in tweepy.Cursor(api.search, q="#myHashtag&geocode=59.347937,18.072433,5km", lang='en', tweet_mode='extended').items(): # handle tweets here ``` You can find more info in the [Tweepy Cursor docs](http://tweepy.readthedocs.io/en/v3.5.0/cursor_tutori...
With [TwitterAPI](https://github.com/geduldig/TwitterAPI) you would access pages this way: ``` pager = TwitterPager(api, 'search/tweets', {'q':'#myHashtag', 'geocode':'59.347937,18.072433,5km'}) for item in pager.get_iterator(): print(item['text'] if 'text' in item else ...
50,195,029
today I have encountered a strange problem where python ide would not scale the font correctly on my 1920\*1080 screen. So i fixed it. Kinda I knew that there was an option in windows where one could toggle the "Override high DPI scaling behavior". Problem is that this tab is only available for application e.g ".exe"....
2018/05/05
[ "https://Stackoverflow.com/questions/50195029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4102180/" ]
This is what I was looking for: sort -t ';' -k 2,2 < some-csv.log Big thanks to @dmadic
If your input.txt is something like: ``` Any ANA Bill BOB Ana ``` and you want your output to be: ``` Ana Any Bill ANA BOB ``` then, maybe your could try something like: ``` grep -E "[a-z]+" input.txt | sort > lower.txt grep -wE "[A-Z]+" input.txt | sort > upper.txt cat lower.txt upper.txt ```
50,195,029
today I have encountered a strange problem where python ide would not scale the font correctly on my 1920\*1080 screen. So i fixed it. Kinda I knew that there was an option in windows where one could toggle the "Override high DPI scaling behavior". Problem is that this tab is only available for application e.g ".exe"....
2018/05/05
[ "https://Stackoverflow.com/questions/50195029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4102180/" ]
This is what I was looking for: sort -t ';' -k 2,2 < some-csv.log Big thanks to @dmadic
With Perl you could say: ``` perl -e ' print sort { ($ka = (split(/;/, $a))[1]) =~ tr/a-zA-Z/A-Za-z/; ($kb = (split(/;/, $b))[1]) =~ tr/a-zA-Z/A-Za-z/; $ka cmp $kb; } <>' input.txt ```
4,011,705
I've tried lots of solution that posted on the net, they don't work. ``` >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> ``` So the system can find the \_imaging but still can't use truetype font ``` from PIL import Image, ImageDraw, ImageFilter, ImageFont im = I...
2010/10/25
[ "https://Stackoverflow.com/questions/4011705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483144/" ]
The following worked for me on Ubuntu 14.04.1 64 bit: ``` sudo apt-get install libfreetype6-dev ``` Then, in the virtualenv: ``` pip uninstall pillow pip install --no-cache-dir pillow ```
Worked for Ubuntu 12.10: ``` sudo pip uninstall PIL sudo apt-get install libfreetype6-dev sudo apt-get install python-imaging ```
4,011,705
I've tried lots of solution that posted on the net, they don't work. ``` >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> ``` So the system can find the \_imaging but still can't use truetype font ``` from PIL import Image, ImageDraw, ImageFilter, ImageFont im = I...
2010/10/25
[ "https://Stackoverflow.com/questions/4011705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483144/" ]
For OS X (I'm running 10.6 but should work for others) I was able to get around this error using the advice from [this post](https://stackoverflow.com/questions/9070074/how-to-install-pil-on-mac-os-x-10-7-2-lion/11368029#11368029). Basically you need to install a couple of the dependencies then reinstall PIL.
Instead of running: `pip install Pillow` Run: `pip install Image` darwin Big Sur pyenv
4,011,705
I've tried lots of solution that posted on the net, they don't work. ``` >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> ``` So the system can find the \_imaging but still can't use truetype font ``` from PIL import Image, ImageDraw, ImageFilter, ImageFont im = I...
2010/10/25
[ "https://Stackoverflow.com/questions/4011705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483144/" ]
Worked for Ubuntu 12.10: ``` sudo pip uninstall PIL sudo apt-get install libfreetype6-dev sudo apt-get install python-imaging ```
In Windows 11 we need to solve this problem 'pip install --upgrade pip' 'pip install --upgrade Pillow' *pip install --upgrade Pillow*
4,011,705
I've tried lots of solution that posted on the net, they don't work. ``` >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> ``` So the system can find the \_imaging but still can't use truetype font ``` from PIL import Image, ImageDraw, ImageFilter, ImageFont im = I...
2010/10/25
[ "https://Stackoverflow.com/questions/4011705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483144/" ]
Your installed PIL was compiled without libfreetype. You can get precompiled installer of PIL (compiled with libfreetype) here (and many other precompiled Python C Modules): <http://www.lfd.uci.edu/~gohlke/pythonlibs/>
Instead of running: `pip install Pillow` Run: `pip install Image` darwin Big Sur pyenv
4,011,705
I've tried lots of solution that posted on the net, they don't work. ``` >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> ``` So the system can find the \_imaging but still can't use truetype font ``` from PIL import Image, ImageDraw, ImageFilter, ImageFont im = I...
2010/10/25
[ "https://Stackoverflow.com/questions/4011705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483144/" ]
For me none of the solutions posted here so far has worked. I found another solution here: <http://codeinthehole.com/writing/how-to-install-pil-on-64-bit-ubuntu-1204/> First install the dev packages: ``` $ sudo apt-get install python-dev libjpeg-dev libfreetype6-dev zlib1g-dev ``` Then create some symlinks: ``` $ ...
In my Mac, the following steps in terminal works: ``` $ brew install freetype $ sudo pip uninstall pil $ sudo pip install pillow ``` hopes it works for you. Good luck!
4,011,705
I've tried lots of solution that posted on the net, they don't work. ``` >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> ``` So the system can find the \_imaging but still can't use truetype font ``` from PIL import Image, ImageDraw, ImageFilter, ImageFont im = I...
2010/10/25
[ "https://Stackoverflow.com/questions/4011705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483144/" ]
The following worked for me on Ubuntu 14.04.1 64 bit: ``` sudo apt-get install libfreetype6-dev ``` Then, in the virtualenv: ``` pip uninstall pillow pip install --no-cache-dir pillow ```
For me none of the solutions posted here so far has worked. I found another solution here: <http://codeinthehole.com/writing/how-to-install-pil-on-64-bit-ubuntu-1204/> First install the dev packages: ``` $ sudo apt-get install python-dev libjpeg-dev libfreetype6-dev zlib1g-dev ``` Then create some symlinks: ``` $ ...
4,011,705
I've tried lots of solution that posted on the net, they don't work. ``` >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> ``` So the system can find the \_imaging but still can't use truetype font ``` from PIL import Image, ImageDraw, ImageFilter, ImageFont im = I...
2010/10/25
[ "https://Stackoverflow.com/questions/4011705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483144/" ]
The following worked for me on Ubuntu 14.04.1 64 bit: ``` sudo apt-get install libfreetype6-dev ``` Then, in the virtualenv: ``` pip uninstall pillow pip install --no-cache-dir pillow ```
The followed works on ubuntu 12.04: ``` pip uninstall PIL apt-get install libjpeg-dev apt-get install libfreetype6-dev apt-get install zlib1g-dev apt-get install libpng12-dev pip install PIL --upgrade ``` when your see "-- JPEG support avaliable" that means it works. But, if it still doesn't work when your edit you...
4,011,705
I've tried lots of solution that posted on the net, they don't work. ``` >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> ``` So the system can find the \_imaging but still can't use truetype font ``` from PIL import Image, ImageDraw, ImageFilter, ImageFont im = I...
2010/10/25
[ "https://Stackoverflow.com/questions/4011705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483144/" ]
The following worked for me on Ubuntu 14.04.1 64 bit: ``` sudo apt-get install libfreetype6-dev ``` Then, in the virtualenv: ``` pip uninstall pillow pip install --no-cache-dir pillow ```
solution for CentOS 6 (and probably other rpm based): ``` yum install freetype-devel libjpeg-devel libpng-devel pip uninstall pil Pillow pip install pil Pillow ```
4,011,705
I've tried lots of solution that posted on the net, they don't work. ``` >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> ``` So the system can find the \_imaging but still can't use truetype font ``` from PIL import Image, ImageDraw, ImageFilter, ImageFont im = I...
2010/10/25
[ "https://Stackoverflow.com/questions/4011705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483144/" ]
Basically, you need to install freetype before installing PIL. If you're using [Homebrew](https://brew.sh/) on OS X it's just a matter of: ``` brew remove pil brew install freetype brew install pil ```
I used homebrew to install freetype and I have the following in /usr/local/lib: libfreetype.6.dylib libfreetype.a libfreetype.dylib But the usual: > > pip install pil > > > Does not work for me, so I used: > > pip install <http://effbot.org/downloads/Imaging-1.1.6.tar.gz> > > >
4,011,705
I've tried lots of solution that posted on the net, they don't work. ``` >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> ``` So the system can find the \_imaging but still can't use truetype font ``` from PIL import Image, ImageDraw, ImageFilter, ImageFont im = I...
2010/10/25
[ "https://Stackoverflow.com/questions/4011705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483144/" ]
solution for CentOS 6 (and probably other rpm based): ``` yum install freetype-devel libjpeg-devel libpng-devel pip uninstall pil Pillow pip install pil Pillow ```
Instead of running: `pip install Pillow` Run: `pip install Image` darwin Big Sur pyenv
10,059,497
Code is much more precise than English; Here's what I'd like to do: ``` import sys fileName = sys.argv[1] className = sys.argv[2] # open py file here and import the class # ??? # Instantiante new object of type "className" a = eval(className + "()") # I don't know if this is the way to do that. # I "know" that cla...
2012/04/08
[ "https://Stackoverflow.com/questions/10059497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/569302/" ]
Use [`importlib.import_module`](http://localhost/pythondocs/library/importlib.html#importlib.import_module) and the built in function [`getattr`](http://localhost/pythondocs/library/functions.html#getattr). No need for `eval`. ``` import sys import importlib module_name = sys.argv[1] class_name = sys.argv[2] module ...
As aaronasterling mentions, you can take advantage of the import machinery if the file in question happens to be on the python path (somewhere under the directories listed in `sys.path`), but if that's not the case, use the built in [`exec()`](http://docs.python.org/dev/library/functions.html#exec) function: ``` fileV...
6,095,818
Just curious to know is there any document utility available in PHP which can perform something like docutils in python ? A libary which can be very user friendly in terms of converting restructured text into HTML ?
2011/05/23
[ "https://Stackoverflow.com/questions/6095818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239670/" ]
phpDocumentor is quite outdated. Have a look at [DocBlox (Github Repository)](https://github.com/mvriel/Docblox) or [DocBlox-project.org](http://www.docblox-project.org/) edit: docblox merged with phpdocumentor and they now maintain phpdocumentor 2. links that take you directly to the project: [phpdoc.org](http://www....
Try [phpDocumentor](http://www.phpdoc.org/).
9,966,250
I am trying to understand eval(), but am not having much luck. I am writing my own math library and am trying to include integration into the library. I need help getting python to recognize the function as a series of variables, constants, and operators. I was told that eval would do the trick but how would i go abou...
2012/04/01
[ "https://Stackoverflow.com/questions/9966250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1044726/" ]
The documentation for [`eval()`](http://docs.python.org/library/functions.html#eval) is pretty clear in my view and gives a reasonable example of what you need. Basically you want to hold an expression to be evaluated in a string: ``` >>> f = 'x**2 + 2*x' ``` Then you can define a value for `x`: ``` >>> x = 3 ```...
Perhaps you might be thinking of the 'eval' mode of the abstract syntax tree module which allows you to constuct a syntax tree for a single expression. For example the code below will take an expression in a string and modify it such that 'x\*\*2+3\*x\*\* 4+2' changes to 'x\*\*3+3\*x\*\* 5+2'. (Note that this is not t...
46,207,299
On Windows when I execute: c:\python35\scripts\tensorboard --logdir=C:\Users\Kevin\Documents\dev\Deadpool\Tensorflow-SegNet\logs and I web browse to <http://localhost:6006> the first time I am redirected to <http://localhost:6006/[[_traceDataUrl]]> and I get the command prompt messages: ``` W0913 14:32:25.401402 Rel...
2017/09/13
[ "https://Stackoverflow.com/questions/46207299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1637126/" ]
i'am having the exact same error. Maybe it is because of [this](https://github.com/tensorflow/tensorflow/issues/7856) issue. So try to Change the env-variable to --logdir=foo:C:\Users\Kevin\Documents\dev\Deadpool\Tensorflow-SegNet\logs. Hope it helps.
Could it be that you try to access the webpage with IE? Apparently IE is not supported by Tensorboard yet(<https://github.com/tensorflow/tensorflow/issues/9372>). Maybe use another Browser.
46,207,299
On Windows when I execute: c:\python35\scripts\tensorboard --logdir=C:\Users\Kevin\Documents\dev\Deadpool\Tensorflow-SegNet\logs and I web browse to <http://localhost:6006> the first time I am redirected to <http://localhost:6006/[[_traceDataUrl]]> and I get the command prompt messages: ``` W0913 14:32:25.401402 Rel...
2017/09/13
[ "https://Stackoverflow.com/questions/46207299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1637126/" ]
i'am having the exact same error. Maybe it is because of [this](https://github.com/tensorflow/tensorflow/issues/7856) issue. So try to Change the env-variable to --logdir=foo:C:\Users\Kevin\Documents\dev\Deadpool\Tensorflow-SegNet\logs. Hope it helps.
I encountered the same error before, and found that it was due to internet setting problem. On Internet Explorer, Go to **Tools** -> **Internet Options** -> **Connections**, click **LAN settings**, and then click **Automatic detect settings**.
7,093,121
Recently, reading Python ["Functional Programming HOWTO"](http://docs.python.org/howto/functional.html), I came across a mentioned there `test_generators.py` standard module, where I found the following generator: ``` # conjoin is a simple backtracking generator, named in honor of Icon's # "conjunction" control struct...
2011/08/17
[ "https://Stackoverflow.com/questions/7093121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/862380/" ]
This seems to work, and it's still lazy: ``` def conjoin(gs): return [()] if not gs else ( (val,) + suffix for val in gs[0]() for suffix in conjoin(gs[1:]) ) def range3(): return range(3) print list(conjoin([range3, range3])) ``` Output: ``` [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2,...
`simple_conjoin` uses the same basic building blocks -- loops, conditions, and `yield` -- as the building blocks of the `itertools` recipes. It also treats functions as data, a hallmark of functional programming. > > Of course this is most useful when the > iterators have side-effects, so that which values *can* be ...
11,915,432
Why raise UnicodeDecodeError? I try to deploy my django app using apache to copy static files, typing ``` $python manage.py collectstatic ``` and I got error message like below. ``` You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing fi...
2012/08/11
[ "https://Stackoverflow.com/questions/11915432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1559347/" ]
Looks like one or more paths to your static files that are going to be copied contains non ASCII characters. It has nothing to do with the path to the desctination directory. **One way to find out would be** to put ``` try: print path except: pass try: print entry except: pass ``` just before lin...
I had the same error when I used **django-pipeline** inside docker container. It turned out that for some reason the system used POSIX locale. I used the solution proposed here and exported locale setting in system shell: ``` export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 ``` You can check that afterwards your lo...
46,564,730
I am trying to read a table from a Google spanner database, and write it to a text file to do a backup, using google dataflow with the python sdk. I have written the following script: ``` from __future__ import absolute_import import argparse import itertools import logging import re import time import datetime ...
2017/10/04
[ "https://Stackoverflow.com/questions/46564730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6837292/" ]
Google currently added support of Backup Spanner with Dataflow, you can choose related template when creating DataFlow job. For more: <https://cloud.google.com/blog/products/gcp/cloud-spanner-adds-import-export-functionality-to-ease-data-movement>
I have reworked my code following the suggestion to simply use a ParDo, instead of using the BoundedSource class. As a reference, here is my solution; I am sure there are many ways to improve on it, and I would be happy to to hear opinions. In particular I am surprised that I have to a create a dummy PColl when startin...