title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Line colour of 3D curve from an array with matplotlib | 37,856,209 | <p>I want to draw a 3D line of points with different color in the Z turn.
I use the Visual Studio 2013 with Python and I have to read an .json (XML-Style) file and draw it (X,Y,Z) to a 3D Diagram.
So I got a curve with one color:
<a href="http://i.stack.imgur.com/PVVur.png" rel="nofollow"><img src="http://i.stack.imgur... | 3 | 2016-06-16T10:12:15Z | 37,857,562 | <p>Look at the example and comments in it:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
N = 100 # number of points
x = np.arange(N, dtype=float) # x,y,z = 1d arrays
y = x * x
z = np.random.rand(N)
fig = plt.figure()
ax = fig.gca(projection='3d')
# you hav... | 0 | 2016-06-16T11:15:59Z | [
"python",
"numpy",
"matplotlib",
"3d"
] |
Python: argsort in descending order for 2d array? | 37,856,290 | <p>I need to sort by the first column in descending order an array. To be specific my code is:</p>
<pre><code>>>> x = np.array([[2, 3], [1998,5], [1998,7]])
>>> x = x[np.argsort(x[:,0])]
</code></pre>
<p>but the output is </p>
<pre><code>array([[ 2, 3],
[1998, 5],
[1998, 7]... | 4 | 2016-06-16T10:15:55Z | 37,858,024 | <p>in this particular requirement you can use python's <code>sorted</code> which is <a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability" rel="nofollow">stable</a>:</p>
<pre><code>a = np.array([[2, 3], [1998,5], [1998,7]])
res = np.array(sorted(a, key= lambda x: -x[0]))
</code></pre>
<p>it does: use th... | 2 | 2016-06-16T11:35:44Z | [
"python",
"arrays"
] |
sort rows of array to match order of another array using an identifier column | 37,856,463 | <p>I have two arrays like this:</p>
<pre><code>A = [[111, ...], B = [[222, ...],
[222, ...], [111, ...],
[333, ...], [333, ...],
[555, ...]] [444, ...],
[555, ...]]
</code></pre>
<p>Where the first column contains identif... | 3 | 2016-06-16T10:24:37Z | 37,856,634 | <p>The simple approach is to build a <code>dict</code> from <code>A</code> and then use it to map identifiers found in <code>B</code> to the new array.</p>
<p>Constructing <code>dict</code>:</p>
<pre><code>>>> A = [[1,"a"], [2,"b"], [3,"c"]]
>>> A_dict = {x[0]: x for x in A}
>>> A_dict
{1: ... | 0 | 2016-06-16T10:32:02Z | [
"python",
"performance",
"numpy"
] |
sort rows of array to match order of another array using an identifier column | 37,856,463 | <p>I have two arrays like this:</p>
<pre><code>A = [[111, ...], B = [[222, ...],
[222, ...], [111, ...],
[333, ...], [333, ...],
[555, ...]] [444, ...],
[555, ...]]
</code></pre>
<p>Where the first column contains identif... | 3 | 2016-06-16T10:24:37Z | 37,856,992 | <p>Its not clear if you wish to concatenate the values in <code>B</code> onto <code>A</code>. Lets assume not ... then the simplest way is probably to just build a dictionary of identifier to row and then reorder <code>A</code>:</p>
<pre><code>def match_order(A, B):
# identifier -> row
by_id = {A[i, 0]: A[... | 0 | 2016-06-16T10:47:40Z | [
"python",
"performance",
"numpy"
] |
sort rows of array to match order of another array using an identifier column | 37,856,463 | <p>I have two arrays like this:</p>
<pre><code>A = [[111, ...], B = [[222, ...],
[222, ...], [111, ...],
[333, ...], [333, ...],
[555, ...]] [444, ...],
[555, ...]]
</code></pre>
<p>Where the first column contains identif... | 3 | 2016-06-16T10:24:37Z | 37,857,049 | <pre><code>>>> A = [[3,'d', 'e', 'f'], [1,'a','b','c'], [2,'n','n','n']]
>>> B = [[1,'a','b','c'], [3,'d','e','f']]
>>> A_dict = {x[0]:x[1:] for x in A}
>>> A_dict
{1: ['a', 'b', 'c'], 2: ['n', 'n', 'n'], 3: ['d', 'e', 'f']}
>>> B_dict = {x[0]:x[1:] for x in B}
>>&... | 0 | 2016-06-16T10:50:33Z | [
"python",
"performance",
"numpy"
] |
sort rows of array to match order of another array using an identifier column | 37,856,463 | <p>I have two arrays like this:</p>
<pre><code>A = [[111, ...], B = [[222, ...],
[222, ...], [111, ...],
[333, ...], [333, ...],
[555, ...]] [444, ...],
[555, ...]]
</code></pre>
<p>Where the first column contains identif... | 3 | 2016-06-16T10:24:37Z | 37,857,226 | <p>Here's a vectorized approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> -</p>
<pre><code># Store the sorted indices of A
sidx = A[:,0].argsort()
# Find the indices of col-0 of B in col-0 of sorted A
l_idx = np.searchso... | 2 | 2016-06-16T10:58:49Z | [
"python",
"performance",
"numpy"
] |
Mac reinstall Python | 37,856,509 | <p>I tried to use the Coursera course downloader from <a href="https://github.com/coursera-dl/coursera-dl" rel="nofollow">here</a> and it worked for few courses but not all. They have recommended to use Python3.X. So I uninstalled Anaconda (version 2) from my Mac and installed Python3.5.1 from Python's website but stil... | 1 | 2016-06-16T10:26:33Z | 37,860,152 | <p>try Homebrew <a href="http://brew.sh/" rel="nofollow">http://brew.sh/</a></p>
<pre><code>brew install python3
curl bootstrap.pypa.io/get-pip.py | python3
</code></pre>
| 0 | 2016-06-16T13:05:26Z | [
"python",
"osx",
"python-2.7",
"python-3.x"
] |
Mac reinstall Python | 37,856,509 | <p>I tried to use the Coursera course downloader from <a href="https://github.com/coursera-dl/coursera-dl" rel="nofollow">here</a> and it worked for few courses but not all. They have recommended to use Python3.X. So I uninstalled Anaconda (version 2) from my Mac and installed Python3.5.1 from Python's website but stil... | 1 | 2016-06-16T10:26:33Z | 37,886,334 | <p>Your Mac should have Python 2 and Python 3 installed by default. in the terminal "python" will launch Python2, "python3" will launch Python3. With Anaconda you could have just kept the Python 2 version and created an environment for Python 3, <a href="http://conda.pydata.org/docs/using/envs.html#managing-environment... | 0 | 2016-06-17T16:31:33Z | [
"python",
"osx",
"python-2.7",
"python-3.x"
] |
Moving sprites by vectors | 37,856,511 | <p>I want to move some sprites for my Pygame over the display. Its a given route and I want to move them with vectors. So I got the positions of my route and so I got the magnitude and the heading. You can see the formulas and how I want to change the way of the spirts (with "if"). I put the vectors in tuples and I thi... | -2 | 2016-06-16T10:26:36Z | 37,858,418 | <p>You don't want to use tuples, as you've seen that tuples cannot be simply multiplied by a scalar. (Cf. <a href="http://stackoverflow.com/questions/1781970/multiplying-a-tuple-by-a-scalar">Multiplying a tuple by a scalar</a>)</p>
<p>There are workarounds, but the easiest solution would be to use <code>numpy</code>, ... | 0 | 2016-06-16T11:52:48Z | [
"python",
"vector",
"pygame"
] |
Python: Design classes with same methods and different but equivalent | 37,856,524 | <p>I have an algorithm that performs the same tasks on different datasets. Essentially the methods are the same but the parameters are different. I'm trying to create classes for this but since I'm not familiar with OOP design principles I'm a bit confused how to do this. </p>
<p>Since, the algorithm is the same I fig... | 2 | 2016-06-16T10:27:28Z | 37,856,728 | <p>Why not pass different datasets to your algorithms class, instead of creating two classes for different algorithms.</p>
<pre><code>class Algorithm:
def __init__(self, dataset):
self.dataset = dataset
def method_1():
"""this is your algo implementation"""
# perform action here on your dataset us... | 0 | 2016-06-16T10:35:41Z | [
"python",
"class",
"python-3.x",
"oop",
"design-patterns"
] |
Python: Design classes with same methods and different but equivalent | 37,856,524 | <p>I have an algorithm that performs the same tasks on different datasets. Essentially the methods are the same but the parameters are different. I'm trying to create classes for this but since I'm not familiar with OOP design principles I'm a bit confused how to do this. </p>
<p>Since, the algorithm is the same I fig... | 2 | 2016-06-16T10:27:28Z | 37,857,018 | <p>The example, as shown, does not require inheritance at all.</p>
<p>Assuming that the data sets provide the same interface, e.g. a list of tuples, or a list of dictionaries, class <code>MyAlgorithm</code> is sufficient to process both data sets.</p>
<p>If the data formats differ, e.g. different number of fields, or... | 0 | 2016-06-16T10:49:01Z | [
"python",
"class",
"python-3.x",
"oop",
"design-patterns"
] |
pip uninstall working but giving error | 37,856,569 | <p>I have downloaded, built and installed the sample pypi project. The project is supposed to be used to give an insight to python packaging and is referenced in <a href="https://packaging.python.org/en/latest/" rel="nofollow">Python Packaging User Guide</a> and <a href="https://packaging.python.org/en/latest/distribut... | 1 | 2016-06-16T10:29:09Z | 37,857,042 | <p>This is documented:</p>
<pre><code>$ pip help uninstall
Usage:
pip uninstall [options] <package> ...
pip uninstall [options] -r <requirements file> ...
Description:
Uninstall packages.
pip is able to uninstall most installed packages. Known exceptions are:
- Pure distutils packages install... | 3 | 2016-06-16T10:50:19Z | [
"python",
"python-3.x",
"pip",
"virtualenv",
"pypi"
] |
Sum over parametric function | 37,856,680 | <p>I am dealing with a parametric function like this:</p>
<p><a href="http://i.stack.imgur.com/RA0Dy.png" rel="nofollow"><img src="http://i.stack.imgur.com/RA0Dy.png" alt="Parametric function"></a></p>
<p>and Ideally I would like to sum over the repeated x axis, as shown in the example. It is to say, for x~4.75, I se... | 1 | 2016-06-16T10:33:51Z | 37,858,109 | <p>Look at the example:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
# set x, y
x = np.arange(-3.,3.,.1)
N = x.size
x[10:13] = x[10]
y = x ** 3 + np.random.rand(N)
# plot curve
fig, ax = plt.subplots()
plt.plot(x,y,'b-')
curve = ax.lines[0]
# get data of plotted curve
xvalues = curve.get_xdata(... | 1 | 2016-06-16T11:39:25Z | [
"python",
"function",
"numpy",
"matplotlib"
] |
How to set all values in a row in matrix to a specific value if that value already exists in row python | 37,856,695 | <p>How can you change all elements in a row in a matrix to a certain value, if that same value exists in a random place in the row?
I want to find all elements '-3' in all rows and set all elements to that value.
Here's what I've got so far, but my loop doesn't seem to work.
Afterwords I'm sorting all rows and deletin... | 0 | 2016-06-16T10:34:18Z | 37,857,115 | <p>np.any(grades[i,:]) always returns true so its obviously the wrong function to use. Why use numpy at all? </p>
<p>Also you should include the import line for people to test your code:</p>
<blockquote>
<pre><code> #!/usr/bin/env python
import numpy as np
</code></pre>
</blockquote>
| 0 | 2016-06-16T10:54:02Z | [
"python",
"matrix"
] |
How to set all values in a row in matrix to a specific value if that value already exists in row python | 37,856,695 | <p>How can you change all elements in a row in a matrix to a certain value, if that same value exists in a random place in the row?
I want to find all elements '-3' in all rows and set all elements to that value.
Here's what I've got so far, but my loop doesn't seem to work.
Afterwords I'm sorting all rows and deletin... | 0 | 2016-06-16T10:34:18Z | 37,857,178 | <p>Check this:</p>
<pre><code>for i in range(grades.shape[0]):
if any(j == -3 for j in grades[i,:]):
grades[i,:] = -3
</code></pre>
| 1 | 2016-06-16T10:56:50Z | [
"python",
"matrix"
] |
creating unit test for sys.exit | 37,856,733 | <p>I have a simple python function.</p>
<pre><code>def test():
print "test"
sys.exit(1)
</code></pre>
<p>I am using python 2.6. How can I create unittest for this function? This is because sys.exit can be handled in unit test cases after python 2.7.</p>
<p>can anyone let me know how to create unittest for th... | 0 | 2016-06-16T10:35:45Z | 37,857,579 | <p>According to what I can see there's been little change in <code>sys.exit</code> during the <code>2.x</code>. The only difference I can see is that earlier the <code>sys.exit</code> didn't check it's argument, but rather raised <code>SystemExit</code> exception anyway (now it only raises it if you supply a proper arg... | 2 | 2016-06-16T11:17:03Z | [
"python",
"unit-testing"
] |
'makemigrations' asks for a default with none-abstract model inheritance | 37,856,747 | <p>I'm trying a simple model inheritance:</p>
<pre><code>class Product(models.Model):
creation_date = models.DateTimeField(auto_now_add=True)
class Application(Product):
name = models.CharField(max_length=200)
</code></pre>
<p>'makemigrations' asks for a default:</p>
<blockquote>
<p>You are trying to add ... | 2 | 2016-06-16T10:36:44Z | 37,857,402 | <p>You haven't explained what exactly is the change that you have made, it seems that you have changed your <code>Application</code> model to inherit from <code>Product</code> where it previously inherited from models.Model. That causes django to create a 1 to 1 mapping behind the scenes. The addition of the product_pt... | 2 | 2016-06-16T11:07:50Z | [
"python",
"django",
"inheritance",
"model",
"makemigrations"
] |
Simple Flask app - can't connect to database on localhost? | 37,856,772 | <p>I am trying to follow this tutorial:<br>
<a href="http://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972" rel="nofollow">http://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972</a></p>
<p>I have the web app appear... | -1 | 2016-06-16T10:37:55Z | 37,857,193 | <p>You may try to avoid connecting again in finally clause. Simply, write conn.close() and cursor.close(). It should resolve your problem.</p>
| 1 | 2016-06-16T10:57:21Z | [
"python",
"mysql",
"sqlite",
"flask"
] |
Simple Flask app - can't connect to database on localhost? | 37,856,772 | <p>I am trying to follow this tutorial:<br>
<a href="http://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972" rel="nofollow">http://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972</a></p>
<p>I have the web app appear... | -1 | 2016-06-16T10:37:55Z | 37,860,785 | <p>Here is the code I got to work using the Sqlite implementation suggested by scrineym. It works to the point where you have an app that enters and commits to the database. </p>
<p>Now my only issue is the json parts arent working when I submit/get an error/no field data is written! At least theres one solution that ... | 0 | 2016-06-16T13:31:02Z | [
"python",
"mysql",
"sqlite",
"flask"
] |
difference when using dot syntax with ClassName or self | 37,856,785 | <p>When accessing class attributes, what is the difference when using the class name <code>Foo</code> or <code>self</code> within that classes methods?</p>
<pre><code>>>> class Foo(object):
... class_attribute = "Oh Hai"
... def bar(self):
... print(Foo.class_attribute)
... print(self.... | 1 | 2016-06-16T10:38:40Z | 37,856,857 | <pre><code>class Baz(Foo):
class_attribute = "Hello, World!"
Baz().bar()
</code></pre>
<p>And now they have completely different behavior. Program for results, not for efficiency.</p>
| 0 | 2016-06-16T10:41:38Z | [
"python"
] |
Element is no longer valid | 37,856,791 | <p>I face a problem with Python and Selenium.</p>
<p>I want to click a link, this is my Py code:</p>
<pre><code>toubao_luru_xpath='//div[87]/xml/items/item[2]/item[@path=policynewbiz/inputapplication/chooseproduct.jsp]'
#url=policynewbiz/inputapplication/chooseproduct.jsp
print WebDriverWait(browser,10).until(EC.pres... | 1 | 2016-06-16T10:38:57Z | 37,857,169 | <p>Use below <code>xPath</code> :-</p>
<pre><code>toubao_luru_xpath= "//items/item[@name = 'application']/item[@path='policynewbiz/inputapplication/chooseproduct.jsp']"
</code></pre>
<p>or</p>
<pre><code>toubao_luru_xpath= "//item[@path='policynewbiz/inputapplication/chooseproduct.jsp']"
</code></pre>
<p>or you can... | 0 | 2016-06-16T10:56:29Z | [
"python",
"selenium"
] |
Element is no longer valid | 37,856,791 | <p>I face a problem with Python and Selenium.</p>
<p>I want to click a link, this is my Py code:</p>
<pre><code>toubao_luru_xpath='//div[87]/xml/items/item[2]/item[@path=policynewbiz/inputapplication/chooseproduct.jsp]'
#url=policynewbiz/inputapplication/chooseproduct.jsp
print WebDriverWait(browser,10).until(EC.pres... | 1 | 2016-06-16T10:38:57Z | 38,135,735 | <p>This should work. It's unique given the HTML you provided and I'm assuming that there aren't two links to the same URL so it should be good.</p>
<pre><code>driver.find_element_by_css_selector("item[path='policynewbiz/inputapplication/chooseproduct.jsp']").click()
</code></pre>
| 0 | 2016-07-01T01:34:42Z | [
"python",
"selenium"
] |
Python ssh read image | 37,856,848 | <p>I am using Python 2.7 and OpenCV 2.4. I want to read and show the image from the remote machine. Then, I try to use the library <strong><code>paramiko</code></strong>. However, I cannot read the file.</p>
<p>Here is my code. First, I import all libraries and setup connection:</p>
<pre><code>import paramiko
import ... | 2 | 2016-06-16T10:41:13Z | 37,867,391 | <p>Here a solution:</p>
<pre><code>import numpy as np
...
sftp = s.open_sftp()
with sftp.open('/home/frame/image.jpg') as f:
img = cv2.imdecode(np.fromstring(f.read(), np.uint8), 1)
cv2.imshow("image", img)
cv2.waitKey(0)
</code></pre>
| 2 | 2016-06-16T19:00:32Z | [
"python",
"opencv",
"ssh",
"sftp",
"paramiko"
] |
Updating correctly keys in dictionary in Python? | 37,856,917 | <p>I have a dictionary (d2) and I have to create a new dictionary (new_dict) containing only keys that satisfy a condition.</p>
<p>This is my code:</p>
<pre><code>d2 = dict((y,x) for x,y in d.iteritems())
new_dict={}
for name in list:
for keyx in d2:
if name in keyx:
new_dict=dict((keyx,... | -1 | 2016-06-16T10:44:03Z | 37,857,050 | <p>Here's how to do it with an example. </p>
<pre><code>>>> f={'c':1,'d':2,'e':3}
>>> l=['c','d']
>>> {i:f[i] for i in f if any([k in i for k in l])}
{'c': 1, 'd': 2}
</code></pre>
<p>For your use case it will simply be. </p>
<pre><code>new_dict = {i:d2[i] for i in d2 if any([k in i for ... | 3 | 2016-06-16T10:50:33Z | [
"python",
"dictionary",
"key"
] |
Updating correctly keys in dictionary in Python? | 37,856,917 | <p>I have a dictionary (d2) and I have to create a new dictionary (new_dict) containing only keys that satisfy a condition.</p>
<p>This is my code:</p>
<pre><code>d2 = dict((y,x) for x,y in d.iteritems())
new_dict={}
for name in list:
for keyx in d2:
if name in keyx:
new_dict=dict((keyx,... | -1 | 2016-06-16T10:44:03Z | 37,857,060 | <p>Just update your code like -</p>
<pre><code>d2 = dict((y,x) for x,y in d.iteritems())
new_dict={}
for name in list:
for keyx in d2:
if name in keyx:
new_dict[keyx] = d2[keyx]
print new_dict
</code></pre>
<p>What you were doing wrong is making a dictionary again and again in... | 1 | 2016-06-16T10:51:22Z | [
"python",
"dictionary",
"key"
] |
Updating correctly keys in dictionary in Python? | 37,856,917 | <p>I have a dictionary (d2) and I have to create a new dictionary (new_dict) containing only keys that satisfy a condition.</p>
<p>This is my code:</p>
<pre><code>d2 = dict((y,x) for x,y in d.iteritems())
new_dict={}
for name in list:
for keyx in d2:
if name in keyx:
new_dict=dict((keyx,... | -1 | 2016-06-16T10:44:03Z | 37,857,114 | <p>You need to update <code>new_dict</code> with the new items you find instead of recreating a new dictionary each time. Here's an example:</p>
<pre><code>d2 = {'a': 1, 'b': 2, 'ab': 3}
l = ['a']
new_dict = dict([(k, v) for k, v in d2.items() if any(x in k for x in l)])
print new_dict
</code></pre>
<p>this will outp... | 1 | 2016-06-16T10:53:57Z | [
"python",
"dictionary",
"key"
] |
How to call a variabe of an inner class correctly | 37,856,988 | <p>I would like to set the value of an inner class and call it from out of any class. I use the same thing for the (outer)class, the value gets changed in the set def, but outside of that function it ooks like is hasnt changed.</p>
<p>my code looks like this</p>
<pre><code>class car(vehicle):
__vehicle_kind = "ca... | 1 | 2016-06-16T10:47:36Z | 37,858,277 | <p>Your example has a few issues. The main issue is that you're confusing class and instance variables/members. The <code>wheel_color = "grey"</code> is a class variable that applies to all instances of <code>wheel</code>, while the <code>self.wheel_color = color</code> refers to an instance variable that only applies ... | 0 | 2016-06-16T11:47:12Z | [
"python",
"variables",
"inner-classes"
] |
How to prevent logging code from cluttering real code? | 37,856,995 | <p>I am working on some code where half the code seems to be logging and timing various things. I find this clutters up the real code. I was wondering what are the approaches to still logging everything but cleanly separating the logging and real code?</p>
<p>e.g. some block of code could do something as simple as:</p... | 4 | 2016-06-16T10:47:47Z | 37,857,338 | <p>Definition of some logger class (as in your context manager example) seems sensible to me - that way you separate log-dedicated analysis from the code itself.</p>
<p>I would also split the code into many functions/methods doing exactly one (at least from the perspective of logging) thing, then use decorator(s) to l... | 0 | 2016-06-16T11:04:14Z | [
"python",
"logging",
"coding-style"
] |
How to prevent logging code from cluttering real code? | 37,856,995 | <p>I am working on some code where half the code seems to be logging and timing various things. I find this clutters up the real code. I was wondering what are the approaches to still logging everything but cleanly separating the logging and real code?</p>
<p>e.g. some block of code could do something as simple as:</p... | 4 | 2016-06-16T10:47:47Z | 37,861,251 | <p>You could take advantage of the fact that loggers can be passed some other object than a string, and that object's return value from <code>str(object)</code> is used to determine the message. Hence:</p>
<pre><code>class ParsedItemInfo(object):
def __init__(self):
self.folders = self.files = self.paid_us... | 1 | 2016-06-16T13:50:42Z | [
"python",
"logging",
"coding-style"
] |
Django-admin validation on ManyToMany Field | 37,857,003 | <p>I have a django model where I have a Module class which can have a field 'sort' set to one of 4 values (Video, Article, Quiz, Test). If Video or Article are selected then I have validation in place to ensure the field 'textfile' (which is an uploaded file) is not null. I want validation that if Quiz or Test is sel... | 2 | 2016-06-16T10:48:18Z | 37,865,151 | <p><a href="https://groups.google.com/d/msg/django-users/f_MKyPg_C4w/0WMJol1atOoJ" rel="nofollow">https://groups.google.com/d/msg/django-users/f_MKyPg_C4w/0WMJol1atOoJ</a></p>
<blockquote>
<p>Basically, you can't. M2m fields are saved after the model is saved,
so you either get objects that are not yet ready for t... | 0 | 2016-06-16T16:54:14Z | [
"python",
"django",
"validation",
"django-models",
"django-admin"
] |
Using Split function | 37,857,038 | <p>How can I take a dictionary having one key-value pair and split the value as follows-</p>
<pre><code>a={"description":"hello,hi,hey,hola"}
</code></pre>
<p>Now I would like to split the value through second comma and store the two values as(creating a new key-value pair in the dictionary)--</p>
<pre><code>a={"des... | 0 | 2016-06-16T10:50:08Z | 37,857,145 | <p>Something like,</p>
<pre><code>>>> a_split = a['description'].split(',')
>>> a_list = { 'description' : ','.join(a_split[:2]), 'kkajan' : ','.join(a_split[2:]) }
>>> a_list
{'kkajan': 'hey,hola', 'description': 'hello,hi'}
</code></pre>
| 1 | 2016-06-16T10:55:11Z | [
"python",
"split"
] |
python socketserver MyRequestHandller call a function | 37,857,067 | <p>In python,I created a socketserver using socketserver, when I want to call a function in the handle method, it shows that the function is not defined,why is that?</p>
<p>Here is the code:</p>
<pre><code>from socketserver import (TCPServer as TCP, StreamRequestHandler as SRH)
HOST = ''
PORT = 21567
ADDR = (HOST,PO... | 0 | 2016-06-16T10:51:34Z | 37,857,475 | <p>That's because</p>
<pre><code>tcpServ.serve_forever()
</code></pre>
<p>blocks and </p>
<pre><code>def check():
print('success')
</code></pre>
<p>is never reached. Move <code>tcpServ.serve_forever()</code> call to the bottom of the file (or more generally make it a last command to run).</p>
| 0 | 2016-06-16T11:10:48Z | [
"python",
"socketserver"
] |
Cassandra data import time using shell and python driver | 37,857,078 | <p>At a particular instance, I used <code>CQL Shell</code> to import 100k rows from a csv file using <code>COPY</code>. It took about 5.695 seconds at Avg. rate: 17559 rows/s. </p>
<p>If I inserted the same data using <code>Cassandra Python driver</code>, <code>execute_async</code> will take about 13 secs. so why is... | 2 | 2016-06-16T10:51:56Z | 37,859,810 | <p>Cqlsh uses the Cassandra Python driver and ultimately is calling execute_async, can view source:</p>
<p><a href="https://github.com/apache/cassandra/blob/trunk/pylib/cqlshlib/copyutil.py" rel="nofollow">https://github.com/apache/cassandra/blob/trunk/pylib/cqlshlib/copyutil.py</a>
<a href="https://github.com/apache/... | 2 | 2016-06-16T12:51:25Z | [
"python",
"python-3.x",
"cassandra",
"cql",
"cqlsh"
] |
Add unique words from a text file to a list in python | 37,857,080 | <p>suppose I have the following text file:</p>
<blockquote>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
</blockquote>
<p>I want to add all unique words in this file to a ... | 0 | 2016-06-16T10:52:00Z | 37,857,159 | <p>Use <code>word</code> instead of <code>words</code> (also simplified the loop)</p>
<pre><code>fname = open("romeo.txt")
lst = list()
for line in fname:
line = line.rstrip()
words = line.split(' ')
for word in words:
if word not in lst:
lst.append(word)
lst.sort()
print lst
</code... | 0 | 2016-06-16T10:56:14Z | [
"python",
"python-2.7"
] |
Add unique words from a text file to a list in python | 37,857,080 | <p>suppose I have the following text file:</p>
<blockquote>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
</blockquote>
<p>I want to add all unique words in this file to a ... | 0 | 2016-06-16T10:52:00Z | 37,857,177 | <p>If you want to get a set of unique words, you better use <code>set</code>, not <code>list</code>, since <code>in lst</code> may be highly inefficient.</p>
<p>For counting words you better use <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code> object<... | 1 | 2016-06-16T10:56:48Z | [
"python",
"python-2.7"
] |
Add unique words from a text file to a list in python | 37,857,080 | <p>suppose I have the following text file:</p>
<blockquote>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
</blockquote>
<p>I want to add all unique words in this file to a ... | 0 | 2016-06-16T10:52:00Z | 37,857,192 | <p>I would do:</p>
<pre><code>with open('romeo.txt') as fname:
text = fname.read()
lst = list(set(text.split()))
print lst
>> ['and', 'envious', 'already', 'fair', 'is', 'through', 'pale', 'yonder', 'what', 'sun', 'Who', 'But', 'moon', 'window', 'sick', 'east', 'breaks', 'grief', 'with', 'light', '... | 1 | 2016-06-16T10:57:20Z | [
"python",
"python-2.7"
] |
Add unique words from a text file to a list in python | 37,857,080 | <p>suppose I have the following text file:</p>
<blockquote>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
</blockquote>
<p>I want to add all unique words in this file to a ... | 0 | 2016-06-16T10:52:00Z | 37,857,210 | <p>There are a few ways to achieve what you want.<br>
1) Using lists:</p>
<pre><code>fname = open("romeo.txt")
lst = list()
for word in fname.read().split(): # This will split by all whitespace, meaning that it will spilt by ' ' and '\n'
if word not in lst:
lst.append(word)
lst.sort()
print lst
</code></pr... | 1 | 2016-06-16T10:58:07Z | [
"python",
"python-2.7"
] |
Add unique words from a text file to a list in python | 37,857,080 | <p>suppose I have the following text file:</p>
<blockquote>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
</blockquote>
<p>I want to add all unique words in this file to a ... | 0 | 2016-06-16T10:52:00Z | 37,857,310 | <p>This is much easier in python using sets:</p>
<pre><code>with open("romeo.txt") as f:
unique_words = set(f.read().split())
</code></pre>
<p>If you want to have a list, convert it afterwards:</p>
<pre><code> unique_words = list(unique_words)
</code></pre>
<p>Might be nice to have them in alphabeitcal order... | 3 | 2016-06-16T11:03:00Z | [
"python",
"python-2.7"
] |
Add unique words from a text file to a list in python | 37,857,080 | <p>suppose I have the following text file:</p>
<blockquote>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
</blockquote>
<p>I want to add all unique words in this file to a ... | 0 | 2016-06-16T10:52:00Z | 37,858,130 | <p>Here are the problems with your code and a corrected version follows:</p>
<pre><code>fname = open("romeo.txt") # better to open files in a `with` statement
lst = list() # lst = [] is more Pythonic
for line in fname:
line = line.rstrip() # not required, `split()` will do this anyway
... | 2 | 2016-06-16T11:40:13Z | [
"python",
"python-2.7"
] |
Add unique words from a text file to a list in python | 37,857,080 | <p>suppose I have the following text file:</p>
<blockquote>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
</blockquote>
<p>I want to add all unique words in this file to a ... | 0 | 2016-06-16T10:52:00Z | 37,859,303 | <p>You need to change </p>
<p><code>lst = lst + words</code> to <code>lst.append(word)</code></p>
<p>If you want unique words you need to add <code>word</code> and not <code>words</code> ( which is all words in line) to the list.</p>
| -1 | 2016-06-16T12:30:30Z | [
"python",
"python-2.7"
] |
Does ComputeBandStats take nodata into account? | 37,857,254 | <p>I am trying to compute the stats for an image which is only partly covered by data. I would like to know if ComputeBandStats ignores the pixels with the same value as the files nodata.</p>
<p>Here is my code:</p>
<pre><code>inIMG = gdal.Open(infile)
# getting stats for the first 3 bands
# Using ComputeBandStats i... | 1 | 2016-06-16T11:00:09Z | 37,859,989 | <p>Setting the NoData value has no effect on the data itself. You can try it this way:</p>
<pre><code># First image, all valid data
data = numpy.random.randint(1,10,(10,10))
driver = gdal.GetDriverByName('GTIFF')
ds = driver.Create("stats1.tif", 10, 10, 1, gdal.GDT_Byte)
ds.GetRasterBand(1).WriteArray(data)
print ds.G... | 0 | 2016-06-16T12:58:52Z | [
"python",
"python-2.7",
"python-3.x",
"numpy",
"gdal"
] |
Generate data Frame from JSON | 37,857,365 | <p>I am trying to generate a data frame from JSON.the json I am having is in below format</p>
<pre><code> {
eventId: "9668383e-ec96-4d6a-b873-2312dd008e7b",
eventType: "PlannedCustomerChoiceWasUpdated",
publishedDate: "2016-05-31T18:52:29.219Z",
payload: {
plannedCustomerChoiceId: "e9301a6e-7ccf-4c89-bd... | 2 | 2016-06-16T11:05:53Z | 37,858,202 | <p>I think you can first change ordering of columns and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow"><code>to_csv</code></a>:</p>
<pre><code>import pandas as pd
from pandas.io.json import json_normalize
a = { "eventId": "9668383e-ec96-4d6a-b873-2312d... | 1 | 2016-06-16T11:44:00Z | [
"python",
"json",
"string",
"pandas",
"dataframe"
] |
Use of dependent variables in `with` statement | 37,857,415 | <p>Can one use multiple variables in a <code>with</code> block in a situation where variable depend on one another? Intuitively it should be the case although it sometimes doesn't work.</p>
<p>For example:</p>
<pre><code>with MongoClient() as client, client['my_dbp'] as db:
</code></pre>
| -4 | 2016-06-16T11:08:15Z | 37,857,701 | <p>Yes, but all your objects must conform to the <code>__enter__</code>/<code>__exit__</code> protocol to be usable within the <code>with</code> statement. (see <a href="https://www.python.org/dev/peps/pep-0343/" rel="nofollow">PEP 343</a>)</p>
| 1 | 2016-06-16T11:21:34Z | [
"python",
"python-3.x"
] |
How to find particular column unique values count in python pandas? | 37,857,531 | <p>I have following dataframe.,</p>
<pre><code>company,sector,marks
a,b1,21
b,b2,27
c,b2,20
a,b3,70
</code></pre>
<p>I have to display no of company,sector and sum of marks
how do we take unique column value length in pandas </p>
| 1 | 2016-06-16T11:14:16Z | 37,858,022 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nunique.html" rel="nofollow"><code>nunique</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html" rel="nofollow"><code>sum</code></a>:</p>
<pre><code>print (pd.Series([df.c... | 1 | 2016-06-16T11:35:38Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Unable to access module inside the django project | 37,857,543 | <p>I have a django project like:</p>
<pre><code>virt_env_name/
project/
scripts_api/
__init__.py
scripts/
__init__.py
orders.py
api/
__init__.py
api.py
project/
settings.py
</code></pre>
... | 0 | 2016-06-16T11:15:20Z | 37,868,987 | <p>Go to <strong><em>setting.py</em></strong> and print the value of <strong>BASE_DIR</strong></p>
<p>Runserver and check the <em>terminal</em> if the <strong>directory</strong> is the same as your working directory.</p>
<p>Because sometimes "No Module Found" error is raised due to <strong>BASE_DIR</strong> not being... | 0 | 2016-06-16T20:42:26Z | [
"python",
"django"
] |
Scrapy: Do not crawl links on other domains page | 37,857,554 | <p>Below id my spider I created to get all links on NecToday.com for example. </p>
<pre><code>import socket
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
class PropertiesItem(scrapy.Ite... | 1 | 2016-06-16T11:15:40Z | 37,864,961 | <p>Why not try something along the lines of this: </p>
<pre><code>start_urls=["http://nectoday.com"]
def parse(self, response):
#parse whatever you need
for url in response.selector.xpath('//@href').extract():
if 'youtube.com' in url:
yield scrapy.Request(url, callback=self.parse_no_fol... | 2 | 2016-06-16T16:45:06Z | [
"python",
"python-2.7",
"scrapy",
"scrapy-spider"
] |
Passing optional argument in python | 37,857,567 | <p>I am trying to append a url by passing the parameters by commandline argument. Here is how I am trying:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='Arguments')
parser.add_argument('input', metavar='input', type=str)
parser.add_argument('output', metavar='text', type=str)
args = pars... | 0 | 2016-06-16T11:16:15Z | 37,858,101 | <p>As I see it, you have two options. Either you avoid using <code>argparse</code>altogether and go for something like:</p>
<pre class="lang-py prettyprint-override"><code>import sys
args_input = sys.argv[1]
args_output = sys.argv[2] if len(sys.argv) > 2 else ''
url = 'https://example.com/?z=12&text='+args_out... | 1 | 2016-06-16T11:39:08Z | [
"python",
"argparse"
] |
Passing optional argument in python | 37,857,567 | <p>I am trying to append a url by passing the parameters by commandline argument. Here is how I am trying:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='Arguments')
parser.add_argument('input', metavar='input', type=str)
parser.add_argument('output', metavar='text', type=str)
args = pars... | 0 | 2016-06-16T11:16:15Z | 37,864,035 | <p>Try <code>nargs='?'</code> and define a <code>default</code>:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='Arguments')
parser.add_argument('input', metavar='input')
parser.add_argument('output', metavar='text', nargs='?', default='')
args = parser.parse_args()
url = 'https://example.... | 2 | 2016-06-16T15:57:04Z | [
"python",
"argparse"
] |
Sort list of strings alphabetically | 37,857,613 | <p>So i have a question, how can i sort this list:</p>
<p><code>['Pera','mela','arancia','UVA']</code></p>
<p>to be like this:</p>
<p><code>['arancia','mela','Pera','UVA']</code></p>
<p>In the exercise it said to use the <code>sorted()</code> function with the cmp argument.</p>
| 0 | 2016-06-16T11:18:15Z | 37,857,741 | <p>You need to sort your elements based lowercase representation of the strings:</p>
<pre><code>sorted(['Pera','mela','arancia','UVA'], key=str.lower)
</code></pre>
<p>this will output:</p>
<pre><code>['arancia', 'mela', 'Pera', 'UVA']
</code></pre>
| 0 | 2016-06-16T11:23:12Z | [
"python",
"list",
"sorted",
"cmp",
"alphabetical-sort"
] |
Sort list of strings alphabetically | 37,857,613 | <p>So i have a question, how can i sort this list:</p>
<p><code>['Pera','mela','arancia','UVA']</code></p>
<p>to be like this:</p>
<p><code>['arancia','mela','Pera','UVA']</code></p>
<p>In the exercise it said to use the <code>sorted()</code> function with the cmp argument.</p>
| 0 | 2016-06-16T11:18:15Z | 37,857,754 | <p>You can easily do that, using the <code>key</code> argument:</p>
<pre><code>my_list = ['Pera','mela','arancia','UVA']
my_list.sort(key=str.lower)
</code></pre>
<p>Which will get your lowercases chars first.</p>
<p>This will change the object in-place and <code>my_list</code> will be sorted.</p>
<p>You can use <c... | 2 | 2016-06-16T11:23:35Z | [
"python",
"list",
"sorted",
"cmp",
"alphabetical-sort"
] |
Sort list of strings alphabetically | 37,857,613 | <p>So i have a question, how can i sort this list:</p>
<p><code>['Pera','mela','arancia','UVA']</code></p>
<p>to be like this:</p>
<p><code>['arancia','mela','Pera','UVA']</code></p>
<p>In the exercise it said to use the <code>sorted()</code> function with the cmp argument.</p>
| 0 | 2016-06-16T11:18:15Z | 37,857,896 | <p>Use <code>sorted()</code> with a key. </p>
<pre><code>>>> mc = ['Pera','mela','arancia','UVA']
>>> sorted(mc, key=str.lower)
['arancia', 'mela', 'Pera', 'UVA']
</code></pre>
| 0 | 2016-06-16T11:30:11Z | [
"python",
"list",
"sorted",
"cmp",
"alphabetical-sort"
] |
Sort list of strings alphabetically | 37,857,613 | <p>So i have a question, how can i sort this list:</p>
<p><code>['Pera','mela','arancia','UVA']</code></p>
<p>to be like this:</p>
<p><code>['arancia','mela','Pera','UVA']</code></p>
<p>In the exercise it said to use the <code>sorted()</code> function with the cmp argument.</p>
| 0 | 2016-06-16T11:18:15Z | 37,858,013 | <p>This will help you:</p>
<pre><code>>>> words = ['Pera','mela','arancia','UVA']
>>> sorted(words)
['Pera', 'UVA', 'arancia', 'mela']
>>> sorted(words, key=str.swapcase)
['arancia', 'mela', 'Pera', 'UVA']
</code></pre>
<p>Hope this helps</p>
| 1 | 2016-06-16T11:35:05Z | [
"python",
"list",
"sorted",
"cmp",
"alphabetical-sort"
] |
Mathematical function inside user-defined function in Python 2.7 | 37,857,680 | <p>I am trying to write a function that accepts a list of integers as one argument and a simple mathematical function as a second. Then I want to run the math function on the integers and put the results into a second function. Here is the outline for what I am looking for:</p>
<pre><code>def func(test_cases, function... | 0 | 2016-06-16T11:20:49Z | 37,857,749 | <p>What?</p>
<pre><code>func(test_cases, lambda x: x / 10)
func(test_cases, lambda x: x ** 2)
func(test_cases, numpy.sqrt)
</code></pre>
| 2 | 2016-06-16T11:23:24Z | [
"python",
"python-2.7"
] |
Mathematical function inside user-defined function in Python 2.7 | 37,857,680 | <p>I am trying to write a function that accepts a list of integers as one argument and a simple mathematical function as a second. Then I want to run the math function on the integers and put the results into a second function. Here is the outline for what I am looking for:</p>
<pre><code>def func(test_cases, function... | 0 | 2016-06-16T11:20:49Z | 37,858,692 | <p>You can pass functions as arguments just like you would pass variables: </p>
<pre><code>def second_function(x, y):
print x, y
def multi(x):
return x*10
def func(test_cases, function_of_n):
for n in test_cases:
a = function_of_n(n)
second_function(n, a)
func([1,2,3,4], multi)
</code><... | 0 | 2016-06-16T12:05:21Z | [
"python",
"python-2.7"
] |
pandas histogram with logarithmic axes | 37,857,689 | <p>I have a pandas DataFrame with time length data in seconds. The length varies from seconds to months so taking a histogram after taking log is convenient as it covers the range better. Here is a sample code</p>
<pre><code>%matplotlib inline
import numpy as np
import pandas as pd
x=np.random.lognormal(mean=10, sigm... | 5 | 2016-06-16T11:21:13Z | 37,859,047 | <p>If you want to use custom bins, you may want to combine <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>pd.cut</code></a> with <code>.groupby().count()</code> and use a <code>bar</code> chart:</p>
<pre><code>x=np.random.lognormal(mean=10, sigma=1, size=10000)
df=... | 2 | 2016-06-16T12:20:08Z | [
"python",
"numpy",
"pandas",
"histogram"
] |
pandas histogram with logarithmic axes | 37,857,689 | <p>I have a pandas DataFrame with time length data in seconds. The length varies from seconds to months so taking a histogram after taking log is convenient as it covers the range better. Here is a sample code</p>
<pre><code>%matplotlib inline
import numpy as np
import pandas as pd
x=np.random.lognormal(mean=10, sigm... | 5 | 2016-06-16T11:21:13Z | 37,859,127 | <h1>Non-Uniform Bin Histogram</h1>
<p>Instead of logging the values,</p>
<blockquote>
<pre><code>np.log10(df.timeLength)
</code></pre>
</blockquote>
<p>try creating a non-uniform binning when computing the histogram. This can be accomplished with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.hi... | 3 | 2016-06-16T12:23:23Z | [
"python",
"numpy",
"pandas",
"histogram"
] |
Printing real-time SSH output using Python 3.x | 37,857,859 | <p>I have a script that SSH connects from Windows7 to a remote ubuntu server and executes a command. The script returns Ubuntu command output to the Windows cmd window in one go after the command has executed and finished. I am just wondering if there is anyway to return real-time SSH output in my script below, or do... | 2 | 2016-06-16T11:28:37Z | 37,862,205 | <p>The output of your command seems to less than the default buffer size because of which it is getting flushed once the command completes.</p>
<p>By default the <code>bufsize</code> is -1 which means that the system default buffer size is used. If <code>bufsize</code> is set to 1 then it is line buffered. </p>
<p>Us... | 0 | 2016-06-16T14:32:13Z | [
"python",
"python-3.x",
"ssh"
] |
Printing real-time SSH output using Python 3.x | 37,857,859 | <p>I have a script that SSH connects from Windows7 to a remote ubuntu server and executes a command. The script returns Ubuntu command output to the Windows cmd window in one go after the command has executed and finished. I am just wondering if there is anyway to return real-time SSH output in my script below, or do... | 2 | 2016-06-16T11:28:37Z | 37,876,122 | <p>Figured it out in the end, I used 'iter' method in the following line:</p>
<pre><code>for line in iter(stdout.readline,""):
print(line)
</code></pre>
| 0 | 2016-06-17T07:56:34Z | [
"python",
"python-3.x",
"ssh"
] |
How can I change data to json serializable | 37,857,872 | <p>I'm student learning flask rest web server.</p>
<p>I insert into mydatabase name : new.
If I use post mehtod, data insert into database table.
I want to load the data
There is a error. like this "TypeError: <<strong>main</strong>.User object at 0x104225cd0> is not JSON serializable "
How can I change my data jso... | 0 | 2016-06-16T11:29:21Z | 37,859,926 | <p>In general jsonify needs a CustomEncoder for custom objects such as your user.
This is also true for the flask jsonify. Take a look at <a href="http://flask.pocoo.org/snippets/119/" rel="nofollow">their documentation for an example of this</a>. </p>
<p>I'd say a similar approach for your user class should work for... | 0 | 2016-06-16T12:56:33Z | [
"python",
"json",
"flask-sqlalchemy"
] |
Webdriver without window popup | 37,857,927 | <p>I'm currently writinng a script to interact with a live stream, mainly taking <code>screenshots</code>. </p>
<p>I'm using <code>Selenium Webdriver</code> for Python to open <code>Chromedriver</code> and go from there. </p>
<p>However, I want to build this behavior into a bigger program and hide the whole process o... | 1 | 2016-06-16T11:31:30Z | 37,858,990 | <p>You can use a headless browser like htmlunit to run your tests without a browser popup: <a href="https://github.com/SeleniumHQ/htmlunit-driver" rel="nofollow">https://github.com/SeleniumHQ/htmlunit-driver</a></p>
| 3 | 2016-06-16T12:18:01Z | [
"python",
"selenium",
"webdriver",
"video-streaming",
"selenium-chromedriver"
] |
Webdriver without window popup | 37,857,927 | <p>I'm currently writinng a script to interact with a live stream, mainly taking <code>screenshots</code>. </p>
<p>I'm using <code>Selenium Webdriver</code> for Python to open <code>Chromedriver</code> and go from there. </p>
<p>However, I want to build this behavior into a bigger program and hide the whole process o... | 1 | 2016-06-16T11:31:30Z | 37,862,602 | <p>You need to create a script with vb or python which will close the popups on the basis of their titles.</p>
<p>Even you can minimise them also.
Code in vb
Set wshShell = CreateObject("WScript.Shell") </p>
<p>Do
ret = wshShell.AppActivate("title of the popup")
If ret = True Then
wshShell.SendKeys... | 0 | 2016-06-16T14:50:39Z | [
"python",
"selenium",
"webdriver",
"video-streaming",
"selenium-chromedriver"
] |
Format string syntax with several field specifications and conditional statement; value error | 37,857,953 | <p>I have a list <code>mylist = [1, 2, 3]</code> and a number <code>n</code> which I want to print in a specific way:</p>
<blockquote>
<p>{n} {book or books} read ok: {mylist elements one by one separated by commas)</p>
</blockquote>
<p>for example:</p>
<blockquote>
<p>1 book read ok: 1 , 2, 3</p>
<p>2 book... | 1 | 2016-06-16T11:32:33Z | 37,858,187 | <p>Dissected call to <code>print()</code>:</p>
<pre><code>print(
"{0} {:s} read ok: {1}".format(
n, # 1st argument to format
*mylist, # mylist unpacked as positional arguments to format
sep=' , ' # a keyword argument to format
), # Formatted string, the 1st argument to print
"bo... | 3 | 2016-06-16T11:43:25Z | [
"python",
"python-3.x",
"formatting"
] |
Find Customer from shopify with the particular range of date using shopify python api | 37,857,960 | <p>How to import the customers from shopify with the particular range of date i.e importing the customers with the date filter ?</p>
<p>Please refer the code below for importing customers without filter:</p>
<pre><code>shop_url = "https://%s:%s@%s.myshopify.com/admin/" % (self.api_key_shopify,
... | 1 | 2016-06-16T11:32:55Z | 38,928,394 | <p><a href="https://help.shopify.com/api/reference/customer#index" rel="nofollow">As you can see from the documentation</a>, the parameters you need to pass with the request in order to obtain customers created within a specific range are <code>created_at_min</code> and <code>created_at_max</code>. Unless you want to t... | 0 | 2016-08-13T01:38:40Z | [
"python",
"openerp",
"odoo-8",
"odoo-9"
] |
Replace every space after x chars with a "\n" | 37,858,345 | <p>The goals of the function is to split one single string into multiple lines to make it more readable. The goal is to replace the first space found after at least n characters (since the beginning of the string, or since the last "\n" dropped in the string)</p>
<p><strong>Hp</strong>: </p>
<ul>
<li>you can assume n... | 0 | 2016-06-16T11:49:39Z | 37,858,526 | <p>Try replacing</p>
<pre><code>(.{10}.*?)\s
</code></pre>
<p>with</p>
<pre><code>$1\n
</code></pre>
<p><a href="https://regex101.com/r/zX5lZ0/1" rel="nofollow">Check it out here</a>.</p>
<p>Example:</p>
<pre><code>>>> import re
>>> s = 'Marcus plays soccer in the afternoo
>>> re.sub(r'... | 2 | 2016-06-16T11:57:21Z | [
"python",
"regex"
] |
sort a string array using numpy | 37,858,477 | <p>I want to sort a string array using numpy by the length of the elements. </p>
<pre><code>>>> arr = ["year","month","eye","i","stream","key","house"]
>>> x = np.sort(arr, axis=-1, kind='mergesort')
>>> print(x)
['eye' 'house' 'i' 'key' 'month' 'stream' 'year']
</code></pre>
<p>But it sort... | 0 | 2016-06-16T11:55:15Z | 37,858,581 | <p>Add a helper array containing the lenghts of the strings, then use numpy's argsort which gives you the indices which would sort according to these lengths. Index the original data with these indices:</p>
<pre><code>import numpy as np
arr = np.array(["year","month","eye","i","stream","key","house"]) # np-array need... | 3 | 2016-06-16T11:59:49Z | [
"python",
"sorting",
"numpy"
] |
sort a string array using numpy | 37,858,477 | <p>I want to sort a string array using numpy by the length of the elements. </p>
<pre><code>>>> arr = ["year","month","eye","i","stream","key","house"]
>>> x = np.sort(arr, axis=-1, kind='mergesort')
>>> print(x)
['eye' 'house' 'i' 'key' 'month' 'stream' 'year']
</code></pre>
<p>But it sort... | 0 | 2016-06-16T11:55:15Z | 37,863,960 | <p>If I expand your list to <code>arr1=arr*1000</code>, the Python list sort using <code>len</code> as the <code>key</code> function is fastest.</p>
<pre><code>In [77]: len(arr1)
Out[77]: 7000
In [78]: timeit sarr=sorted(arr1,key=len)
100 loops, best of 3: 3.03 ms per loop
In [79]: %%timeit
arrA=np.array(arr1)
larr=... | 1 | 2016-06-16T15:53:55Z | [
"python",
"sorting",
"numpy"
] |
Scikit-learn multi-label classification | 37,858,697 | <p>I am trying to learn about multi-label classification of texts using Scikit-learn, I am attempting to adapt one of the initial example tutorials which comes with scikit for the classification of languages using wikipedia articles as training data. I am trying to implement this below but the code still returns a sing... | 1 | 2016-06-16T12:05:25Z | 38,217,104 | <p>You can use <a href="http://scikit.ml" rel="nofollow">scikit-multilearn</a> for multi-label classification, it is a library built on top of scikit-learn. With languages, the correlations between labels are not that important so a Binary Classifier should be well suited. You can find examples of how to do the classif... | 0 | 2016-07-06T05:52:36Z | [
"python",
"scikit-learn",
"multilabel-classification"
] |
mocking of url for unittesting | 37,858,872 | <p>I want to mock urllib.urlopen for creating unit test</p>
<pre><code>def url_test(self):
response = urllib2.urlopen(test_url)
body = response.read()
if body:
return body.split(':')[0]
</code></pre>
<p>config.py</p>
<pre><code> test_url = "localhost"
</code></pre>
<p>I want to mock the url_test() functio... | 0 | 2016-06-16T12:11:56Z | 37,858,916 | <p>You would mock <em>any external system</em>, which here is <code>urllib2</code>. Assuming you are using the <a href="https://docs.python.org/3/library/unittest.mock.html" rel="nofollow"><code>unittest.mock</code> library</a> (backported to Python 2 as the <a href="https://pypi.python.org/pypi/mock" rel="nofollow"><c... | 1 | 2016-06-16T12:14:04Z | [
"python",
"unit-testing"
] |
mocking of url for unittesting | 37,858,872 | <p>I want to mock urllib.urlopen for creating unit test</p>
<pre><code>def url_test(self):
response = urllib2.urlopen(test_url)
body = response.read()
if body:
return body.split(':')[0]
</code></pre>
<p>config.py</p>
<pre><code> test_url = "localhost"
</code></pre>
<p>I want to mock the url_test() functio... | 0 | 2016-06-16T12:11:56Z | 37,864,739 | <p>For mocking web requests in Python, I highly recommend <a href="https://github.com/gabrielfalcao/HTTPretty" rel="nofollow">HTTPretty</a>.</p>
<p>A simple example for what you want to do would look something like:</p>
<pre><code>@httpretty.activate
def test_url():
httpretty.register_uri(httpretty.GET, test_url,... | 0 | 2016-06-16T16:31:30Z | [
"python",
"unit-testing"
] |
Find, round and replace numbers in a string with regexp | 37,858,953 | <p>I have a string with a number of coordinates each of them having a <strong>15(and 16)-digit</strong> precision. The string looks like this:</p>
<p><code>POLYGON ((63.3143749208534741 58.716055226046571,63.406105383130274 58.6706773671378561,63.4052744833828112 58.670392586236112, ...))</code></p>
<p>My goal is to ... | -1 | 2016-06-16T12:16:06Z | 37,859,143 | <p>You could use lambda func inside re.sub</p>
<pre><code>>>> s = 'POLYGON ((63.3143749208534741 58.716055226046571,63.406105383130274 58.6706773671378561,63.4052744833828112 58.670392586236112'
>>> re.sub(r'\d+\.\d{13,}', lambda m: format(float(m.group(0)), '.13f'), s)
'POLYGON ((63.3143749208535 58... | 4 | 2016-06-16T12:24:01Z | [
"python",
"regex",
"python-2.7",
"python-3.x"
] |
Python Pandas : Convert multiple rows into single row, ignoring NaN's | 37,859,014 | <p>I have a <code>DataFrame</code> similar to the one mentioned below,</p>
<pre><code> Age Sex Name ....
12 NaN NaN
NaN Male NaN
NaN NaN David
</code></pre>
<p>I want to convert it into a dataframe with one row, ignoring the NaN's and merging them</p>
<pre><code> Age Sex Name
12 ... | 1 | 2016-06-16T12:18:48Z | 37,859,103 | <p>You can use <code>pd.concat</code> to combine all <code>columns</code> after <code>.dropna()</code> and <code>.reset_index()</code> like so:</p>
<pre><code>pd.concat([df[col].dropna().reset_index(drop=True) for col in df], axis=1)
</code></pre>
<p>to get:</p>
<pre><code> Age Sex Name
0 12.0 Male David
<... | 3 | 2016-06-16T12:22:16Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Python Pandas : Convert multiple rows into single row, ignoring NaN's | 37,859,014 | <p>I have a <code>DataFrame</code> similar to the one mentioned below,</p>
<pre><code> Age Sex Name ....
12 NaN NaN
NaN Male NaN
NaN NaN David
</code></pre>
<p>I want to convert it into a dataframe with one row, ignoring the NaN's and merging them</p>
<pre><code> Age Sex Name
12 ... | 1 | 2016-06-16T12:18:48Z | 37,859,219 | <p>Another method is to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> a lambda that calls <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.first_valid_index.html#pandas.Series.first_valid_index" rel="nofollow... | 1 | 2016-06-16T12:27:01Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Python Pandas : Convert multiple rows into single row, ignoring NaN's | 37,859,014 | <p>I have a <code>DataFrame</code> similar to the one mentioned below,</p>
<pre><code> Age Sex Name ....
12 NaN NaN
NaN Male NaN
NaN NaN David
</code></pre>
<p>I want to convert it into a dataframe with one row, ignoring the NaN's and merging them</p>
<pre><code> Age Sex Name
12 ... | 1 | 2016-06-16T12:18:48Z | 37,861,593 | <p>This is nasty. Pandas wont do automatic reshape of index ;/. So You have to do in with few operations. Dunno which one is best:</p>
<pre><code>import numpy as np,pandas as pd
df= '''
12 NaN NaN
NaN Male NaN
NaN NaN David'''
df = np.array(df.split())
df.shape=(3,3)
df = pd.DataFrame(df,colum... | 0 | 2016-06-16T14:06:18Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Python Pillow lowering image quality doesnt change file size | 37,859,042 | <p>I am trying to lower the file size of an image using pillow (pil) however lowering the image quality doesn't lower the size of the saves image.
The saved images 'image2' and 'image3' are the same size.</p>
<pre><code>import PIL from Image
im = Image.open('image.png')
im.save('image2.png', quality=100)
im.save('im... | 1 | 2016-06-16T12:19:55Z | 37,859,149 | <p>You have to use image compression to reduce sizes - pngquant or similar
<a href="https://pngquant.org/" rel="nofollow">https://pngquant.org/</a> </p>
| 0 | 2016-06-16T12:24:12Z | [
"python",
"python-imaging-library",
"pillow"
] |
Python Pillow lowering image quality doesnt change file size | 37,859,042 | <p>I am trying to lower the file size of an image using pillow (pil) however lowering the image quality doesn't lower the size of the saves image.
The saved images 'image2' and 'image3' are the same size.</p>
<pre><code>import PIL from Image
im = Image.open('image.png')
im.save('image2.png', quality=100)
im.save('im... | 1 | 2016-06-16T12:19:55Z | 37,859,175 | <p>The PNG format only supports lossless compression, for which the compression ratio is usually limited and not freely adjustable.</p>
<p>If I am right, there is a variable parameter that tells the compressor to spend more or less time finding a better compression scheme. But without a guarantee to succeed.</p>
| 1 | 2016-06-16T12:25:06Z | [
"python",
"python-imaging-library",
"pillow"
] |
How to execute the mysql statement in my python code? | 37,859,050 | <p>I can run the following sql in my my-sql client and return the right result :</p>
<pre><code>mysql> select cj.name job_name , cb.build_result build_result, count(*) total , GROUP_CONCAT(cb.id) id_list
from ci_build as cb INNER JOIN ci_job as cj
ON cb.job_id = cj.id
where cb.build_time >... | 0 | 2016-06-16T12:20:18Z | 37,859,252 | <p>You have to double the percentage signs you do not want to interpolate with argumewnts of the <code>%</code>operator and some things in addition ;-)</p>
<pre><code>sql_query = "select cj.name job_name , cb.build_result build_result, count(*) total , GROUP_CONCAT(cb.id) id_list from ci_build as cb INNER JOIN ci_job... | 0 | 2016-06-16T12:28:20Z | [
"python",
"mysql-python"
] |
How to execute the mysql statement in my python code? | 37,859,050 | <p>I can run the following sql in my my-sql client and return the right result :</p>
<pre><code>mysql> select cj.name job_name , cb.build_result build_result, count(*) total , GROUP_CONCAT(cb.id) id_list
from ci_build as cb INNER JOIN ci_job as cj
ON cb.job_id = cj.id
where cb.build_time >... | 0 | 2016-06-16T12:20:18Z | 37,859,301 | <p>You are using string interpolation to replace the <code>%s</code> in your two <code>date_format()</code>s, however, as <code>%</code> is a special character wrt to string interpolation, Python thinks that the <code>%Y</code> is also a string formatting operation. But it <code>Y</code> not a valid format specifier.</... | 2 | 2016-06-16T12:30:29Z | [
"python",
"mysql-python"
] |
When subtracting date columns in pandas and dividing the result by np.timedelta64(1, 'D'), why do I get an error? | 37,859,151 | <p>I've seen on several questions, such as
<a href="http://stackoverflow.com/questions/22923775/calculate-pandas-dataframe-time-difference-between-two-columns-in-hours-and-minu">Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes</a>, the tactic of dividing differences of date columns b... | 1 | 2016-06-16T12:24:16Z | 37,860,011 | <p>use .astype instead of dividing by np.timedelta64</p>
<pre><code>df['time_since_last_change'] = (df['date'] - df['date_of_last_change']).astype('timedelta64[D]')
</code></pre>
| 1 | 2016-06-16T12:59:43Z | [
"python",
"datetime",
"timedelta"
] |
Search for strings in a for loop without referencing each string individually in the loop | 37,859,323 | <p>I have text data to categorise. Using a for loop in which I specify individual strings, I'm identifying if particular words or phrases are present in rows of another column. Where true, the loop appends a specific value to a new list. The new list is then added to the <code>DataFrame</code>. However this approach is... | 3 | 2016-06-16T12:31:25Z | 37,859,528 | <p>This should work:</p>
<pre><code>test_strings = ['too expensive', 'too costly', 'too much money']
for row in df['opinion']:
for tester in test_strings:
if tester in row:
new_col.append("Too Expensive")
break
</code></pre>
| 1 | 2016-06-16T12:39:17Z | [
"python",
"string",
"pandas",
"search",
"dataframe"
] |
Search for strings in a for loop without referencing each string individually in the loop | 37,859,323 | <p>I have text data to categorise. Using a for loop in which I specify individual strings, I'm identifying if particular words or phrases are present in rows of another column. Where true, the loop appends a specific value to a new list. The new list is then added to the <code>DataFrame</code>. However this approach is... | 3 | 2016-06-16T12:31:25Z | 37,859,551 | <p>i think using RegEx would be more convinient in this case:</p>
<pre><code>df['reason'] = ''
df.ix[df.opinion.str.lower().str.contains(r'too\s+(?:expensive|costly|much money)'), 'reason'] = 'Too Expensive'
df.ix[df.opinion.str.lower().str.contains(r'(?:not fast enough|too slow)'), 'reason'] = 'Too Slow'
In [309]:... | 0 | 2016-06-16T12:40:29Z | [
"python",
"string",
"pandas",
"search",
"dataframe"
] |
Search for strings in a for loop without referencing each string individually in the loop | 37,859,323 | <p>I have text data to categorise. Using a for loop in which I specify individual strings, I'm identifying if particular words or phrases are present in rows of another column. Where true, the loop appends a specific value to a new list. The new list is then added to the <code>DataFrame</code>. However this approach is... | 3 | 2016-06-16T12:31:25Z | 37,859,668 | <p>Pandas has a fast solution for applying a function to rows, so .apply is pretty much designed for this. Ideally, vectorizing is the fastest but I can't think of a way to do that. .apply is after that and iterating on the rows is the slowest so its best to avoid it if possible. </p>
<p>Also, you probably want to use... | 0 | 2016-06-16T12:45:55Z | [
"python",
"string",
"pandas",
"search",
"dataframe"
] |
Search for strings in a for loop without referencing each string individually in the loop | 37,859,323 | <p>I have text data to categorise. Using a for loop in which I specify individual strings, I'm identifying if particular words or phrases are present in rows of another column. Where true, the loop appends a specific value to a new list. The new list is then added to the <code>DataFrame</code>. However this approach is... | 3 | 2016-06-16T12:31:25Z | 37,859,731 | <p>You could keep your terms in a <code>list</code> of <code>dictionaries</code>, where the <code>keys</code> are the <code>replacement</code> and the <code>values</code> contain <code>lists</code> with the words <code>to_replace</code>. </p>
<pre><code>words = [{'Too Expensive': ['too expensive', 'too costly', 'too m... | 2 | 2016-06-16T12:48:39Z | [
"python",
"string",
"pandas",
"search",
"dataframe"
] |
Segmentation fault while importing sklearn | 37,859,389 | <p>When I try to import scikit-learn in python, I get a segmentation fault</p>
<pre><code>>>>import sklearn as sk
Segmentation fault (core dumped)
</code></pre>
<p>How do I fix this?
I am running python 2.7.11 on Fedora.
I installed sklearn using pip
I tried the same using Anaconda on a virtual environment, ... | 3 | 2016-06-16T12:33:40Z | 37,896,792 | <p>Do you have to use pip?
Take a look at the anaconda method</p>
<pre><code>conda install scikit-learn
</code></pre>
| 0 | 2016-06-18T12:12:55Z | [
"python",
"scikit-learn"
] |
Segmentation fault while importing sklearn | 37,859,389 | <p>When I try to import scikit-learn in python, I get a segmentation fault</p>
<pre><code>>>>import sklearn as sk
Segmentation fault (core dumped)
</code></pre>
<p>How do I fix this?
I am running python 2.7.11 on Fedora.
I installed sklearn using pip
I tried the same using Anaconda on a virtual environment, ... | 3 | 2016-06-16T12:33:40Z | 37,896,922 | <p>Try to fully delete it from pip. </p>
<p>Then try to do the following:</p>
<p>Create a virtual environment with virtualenv for python 2.7 and install sklearn with pip again. Is the error still occuring now? </p>
| 0 | 2016-06-18T12:25:50Z | [
"python",
"scikit-learn"
] |
pyqt: add clicked event for a Qlabel | 37,859,597 | <p>I've created label: <code>self.labelOnlineHelp = QLabel('<a href="http://example.com">Online Help</a>')</code> and want to make it clickable. Ideally it should open firefox (but not a default browser) and also change mouse to pointer (in a nutshell: just to create an usual hyperlink). I see that there is... | 1 | 2016-06-16T12:42:38Z | 37,865,172 | <p>You can do this using <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qlabel.html#setOpenExternalLinks" rel="nofollow"><code>setOpenExternalLinks</code></a></p>
<pre><code>self.labelOnlineHellp.setOpenExternalLinks(True)
</code></pre>
<p>If you want to do something different than the default behavior (ie. open lin... | 1 | 2016-06-16T16:55:34Z | [
"python",
"pyqt"
] |
pyqt: add clicked event for a Qlabel | 37,859,597 | <p>I've created label: <code>self.labelOnlineHelp = QLabel('<a href="http://example.com">Online Help</a>')</code> and want to make it clickable. Ideally it should open firefox (but not a default browser) and also change mouse to pointer (in a nutshell: just to create an usual hyperlink). I see that there is... | 1 | 2016-06-16T12:42:38Z | 37,875,888 | <p>You need to reimplement QLabel class and override the mousePressEvent or mouseReleaseEvent. Here is a simple example:</p>
<pre><code>MyLabel(QLabel):
def __init(self, parent):
QLabel.__init(self, parent)
self.link = "http://www.example.com"
def mousePressEvent(self, event):
# open t... | 1 | 2016-06-17T07:44:41Z | [
"python",
"pyqt"
] |
Get start and end indices of longest streak of repetitions in a list | 37,859,623 | <p>I'm putting together something where I want to show the longest streak of wins of a team and the start and end date of this particular streak. So for example, if I have the following two lists:</p>
<pre><code>streak = ["W", "W", "W", "L","W", "W", "W", "W", "W", "L"]
dates = ["2016-06-15", "2016-06-14", "2016-06-1... | 1 | 2016-06-16T12:43:48Z | 37,860,181 | <p>Taking into account your code, you can still go ahead with <code>itertools</code> and use the underdog <code>takewhile</code>:</p>
<pre><code>from itertools import takewhile, groupby
import itertools
L = [list(y) for x, y in groupby(streak)]
l = sorted(L, key=len)[-1]
ix = len(list(itertools.chain.from_iterable(t... | 2 | 2016-06-16T13:06:40Z | [
"python",
"list",
"itertools"
] |
Get start and end indices of longest streak of repetitions in a list | 37,859,623 | <p>I'm putting together something where I want to show the longest streak of wins of a team and the start and end date of this particular streak. So for example, if I have the following two lists:</p>
<pre><code>streak = ["W", "W", "W", "L","W", "W", "W", "W", "W", "L"]
dates = ["2016-06-15", "2016-06-14", "2016-06-1... | 1 | 2016-06-16T12:43:48Z | 37,862,868 | <p>Alternate solutions that reduce temporaries (but note, unless seriously RAM constrained or generating unreasonably huge streaks, generating the temporaries is faster than minimal temporary alternatives). Not necessary, just illustrating other way to combine iterator related tools to achieve the same result:</p>
<pr... | 1 | 2016-06-16T15:02:55Z | [
"python",
"list",
"itertools"
] |
matplotlib x-axis tick label formatting with power of 10 | 37,859,818 | <p>I have been trying to find a proper formatting for the xaxis the half day without success. I want the xaxis tick labels as (10^-4, 10^-3,10^-2, 0.1, 1, 10), and possibly without scaling (the distance between two lables same or almost same). Any help please. My code so far is given below.</p>
<pre><code>import matp... | 0 | 2016-06-16T12:52:05Z | 37,865,413 | <p>You can change the labels of the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xlabel" rel="nofollow">xticks</a> by passing a <a href="http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html" rel="nofollow">labels</a> argument to plt.xticks.</p>
<pre><code>x = [1,2,3,4,5... | 0 | 2016-06-16T17:08:50Z | [
"python",
"matplotlib"
] |
Created nested json using python dictionaries | 37,859,823 | <p>i have for loops running on the multiple levels . Each level of loop returns a json which needs to be put in a hierarchy . </p>
<pre><code>output = {}
for a in alist:
aid, ajson = hit_api(url1)
output[aid] = ajson
for b in blist:
bid, bjson = hit_api(url2)
output[aid][bid] = bjson -- this is where we ... | 1 | 2016-06-16T12:52:14Z | 37,859,999 | <p>It seems like <code>ajson</code> is a string. You might want to parse this. You can use python standard library <a href="https://docs.python.org/2/library/json.html" rel="nofollow"><code>json</code></a> and call <code>json.loads(ajson)</code></p>
<p>Example:</p>
<pre><code>import json
output = {}
for a in alist:
... | 1 | 2016-06-16T12:59:16Z | [
"python"
] |
Comparing csv files with pySpark | 37,859,865 | <p>i'm brand new to pyspark, but i need to digg into it very fast.
I want to compare two (huge) csv files in pyspark and managed so far quite okay (I'm pretty sure, my code is way not fancy)
In the end i'd like to count the records which are matching and those which are not matching.</p>
<p>What i was able to achive i... | 0 | 2016-06-16T12:54:41Z | 37,862,522 | <p>Remove the .collect() from notCompRecords = raw_exp.subtract(raw_act).collect(). After that you can use notCompRecords.count().</p>
| 0 | 2016-06-16T14:46:23Z | [
"python",
"apache-spark",
"pyspark",
"export-to-csv"
] |
datetime.datetime format does not match | 37,859,923 | <p>I have created bellow script to compare date and time in a log file,
basically the purpose of the script is :</p>
<p>it will go through a log file, it will compare the date of the log line with current time stamp. if any log line one hour old then current time, it will show the line.</p>
<p>sample log line is :
... | 0 | 2016-06-16T12:56:26Z | 37,860,106 | <p>The problem is with your regex. </p>
<p>Instead of capturing <code>26/Apr/2016:14:38</code> (in the example in your commented code) it captures <code>6/Apr/2016:14:38</code>. As you can see, this raises an exception when the day is <code>10</code>, <code>20</code> or <code>30</code>, and introduces a bug otherwise.... | 0 | 2016-06-16T13:03:39Z | [
"python",
"python-2.7"
] |
Combine trigram with ranked searchin in django 1.10 | 37,859,960 | <p>We working with searching in django 1.10 and we need user ranked searching with trigram searching.</p>
<p>Our code is this:</p>
<pre><code>def get_queryset(self):
search = self.request.GET.get('text', '')
vector = SearchVector('name',weight='A',
config=settings.SEARCH_LANGS[
... | 1 | 2016-06-16T12:57:48Z | 37,893,382 | <p>We investigated more thoroughly understood how search works weights.</p>
<p>According to <a href="https://docs.djangoproject.com/en/dev/ref/contrib/postgres/search/#weighting-queries" rel="nofollow">documents</a> you can be assigned weights according to the fields and they can even be assigned weights, and similarl... | 1 | 2016-06-18T04:52:11Z | [
"python",
"django",
"postgresql"
] |
How do I check for the same words in two different lists? | 37,859,983 | <p>How can I check for the same words in two different lists if the words have different lower and uppercase letters?
I wrote this:</p>
<pre><code>current_users=["michael", "peta", "jennifer", "clark", "tony"]
new_users=["jeffry", "PETA", "shuff", "TOny", "guy"]
for new_user in new_users:
if new_user.lower() in ... | 2 | 2016-06-16T12:58:45Z | 37,860,109 | <p>You can use <a href="https://docs.python.org/2.7/tutorial/datastructures.html#list-comprehensions" rel="nofollow"><code>list comprehensions</code></a>.</p>
<p><strong>Example</strong></p>
<pre><code> if new_user.lower() in [user.lower() for user in current_users]:
</code></pre>
| 4 | 2016-06-16T13:03:50Z | [
"python",
"words"
] |
How do I check for the same words in two different lists? | 37,859,983 | <p>How can I check for the same words in two different lists if the words have different lower and uppercase letters?
I wrote this:</p>
<pre><code>current_users=["michael", "peta", "jennifer", "clark", "tony"]
new_users=["jeffry", "PETA", "shuff", "TOny", "guy"]
for new_user in new_users:
if new_user.lower() in ... | 2 | 2016-06-16T12:58:45Z | 37,862,649 | <pre><code>if any(new_user.lower() == user.lower() for user in current_users)
</code></pre>
| 1 | 2016-06-16T14:52:46Z | [
"python",
"words"
] |
Basemap Shapefile visualizing | 37,859,994 | <p>After creating some maps with Basemap I got enthusiastic. I want to integrate shapefile information, let's say a polygon, but there are some problems. I downloaded the boarders of bavarian villages here:</p>
<p><a href="https://www.arcgis.com/home/item.html?id=b752861d1a08489b9a40337668d4367e" rel="nofollow">https:... | 1 | 2016-06-16T12:58:56Z | 38,033,633 | <p>I recently wrote a blog post on making maps with Basemap and in it I use a shapefile to draw and colour in postcode areas in England and Wales. It might be of some help. <a href="http://www.jamalmoir.com/2016/06/creating-map-visualisations-in-python.html" rel="nofollow">http://www.jamalmoir.com/2016/06/creating-map-... | 1 | 2016-06-25T22:51:57Z | [
"python",
"matplotlib-basemap"
] |
Is it possible use one loop ouput as an input for another loop? | 37,860,016 | <p>I have a two lists as follows:</p>
<pre><code>NumberandLetter1=['1 E\n', '2 K\n']
NumberandLetter2=['1 E,L,K\n', '2 K,L\n']
</code></pre>
<p>From the first List I try to make dictionary of NUMBERS:LETTERS and I didn't have any issue for making dictionary for list1: </p>
<pre><code>NumberandLetter1=['1 E\n', '2 K\... | 0 | 2016-06-16T13:00:01Z | 37,860,504 | <p>I think you are overcomplicating things with this additional writes to a file. You don't need that at all. You don't even need to distinguish between these cases, since case1 is a <strong>special case</strong> of case2. Have a look at this:</p>
<pre><code>def process(iterator):
result = {}
for line in itera... | 1 | 2016-06-16T13:19:46Z | [
"python",
"list",
"loops",
"dictionary",
"file-handling"
] |
Is it possible use one loop ouput as an input for another loop? | 37,860,016 | <p>I have a two lists as follows:</p>
<pre><code>NumberandLetter1=['1 E\n', '2 K\n']
NumberandLetter2=['1 E,L,K\n', '2 K,L\n']
</code></pre>
<p>From the first List I try to make dictionary of NUMBERS:LETTERS and I didn't have any issue for making dictionary for list1: </p>
<pre><code>NumberandLetter1=['1 E\n', '2 K\... | 0 | 2016-06-16T13:00:01Z | 37,860,542 | <p>You can rewrite your for-loop in the following way</p>
<pre><code>for i in fh:
s = i.strip().split(" ")
value = int(s[0])
keys = s[1].split(",")
for key in keys:
Mutant_dict[key] = value
</code></pre>
<p>string.split() works wonder here.</p>
<p>However, the code still probably does not do... | 1 | 2016-06-16T13:21:14Z | [
"python",
"list",
"loops",
"dictionary",
"file-handling"
] |
Is it possible use one loop ouput as an input for another loop? | 37,860,016 | <p>I have a two lists as follows:</p>
<pre><code>NumberandLetter1=['1 E\n', '2 K\n']
NumberandLetter2=['1 E,L,K\n', '2 K,L\n']
</code></pre>
<p>From the first List I try to make dictionary of NUMBERS:LETTERS and I didn't have any issue for making dictionary for list1: </p>
<pre><code>NumberandLetter1=['1 E\n', '2 K\... | 0 | 2016-06-16T13:00:01Z | 37,860,581 | <p>You can use this function to convert a case2 input to a case1:</p>
<pre><code>NumberandLetter2 = ['1 E,L,B,A,K\n', '2 K,L\n']
def convert_list(alist):
for i_list, items in enumerate(alist):
print(items)
if "," in items:
slices = items.split(",")
no_id = slices[0][0]
... | 1 | 2016-06-16T13:22:36Z | [
"python",
"list",
"loops",
"dictionary",
"file-handling"
] |
Print specific line (Beautifulsoup) | 37,860,039 | <p>Currently, my code is parsing through the link and printing all of the information from the website. I only want to print <strong><em>a single specific line from the website</em></strong>. How can I go about doing that?</p>
<p>Here's my code:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib.request
r = ... | 0 | 2016-06-16T13:01:12Z | 37,860,279 | <pre><code>li = soup.prettify().split('\n')
print str(li[line_number-1])
</code></pre>
| -1 | 2016-06-16T13:09:52Z | [
"python",
"beautifulsoup"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.