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
sequence
Convert python abbreviated month name to full name
40,076,887
<p>How can I convert an abbreviated month anme e.g. <code>Apr</code> in python to the full name?</p>
3
2016-10-17T00:13:27Z
40,076,933
<p>One quick and dirty way:</p> <pre><code>conversions = {"Apr": "April", "May": "May", "Dec": "December"} date = "Apr" if date in conversions: converted_date = conversions[date] </code></pre>
1
2016-10-17T00:21:45Z
[ "python", "datetime" ]
Convert python abbreviated month name to full name
40,076,887
<p>How can I convert an abbreviated month anme e.g. <code>Apr</code> in python to the full name?</p>
3
2016-10-17T00:13:27Z
40,077,286
<p>Here is a method to use <em>calendar</em> library.</p> <pre><code>&gt;&gt;&gt; import calendar &gt;&gt;&gt; calendar.month_name [list(calendar.month_abbr).index('Apr')] 'April' &gt;&gt;&gt; </code></pre>
2
2016-10-17T01:26:50Z
[ "python", "datetime" ]
Median of three, pivot
40,076,890
<p>I'm looking for the <strong>median of three</strong>, using this for a pivot in a QuickSort. I would not like to import any statistics library because I believe it creates a bit of overhead which I would like to reduce as much as possible.</p> <pre><code>def median(num_list): if (num_list[0] &gt; num_list[len(num_list) - 1]) and (num_list[0] &lt; num_list[int(len(num_list)//2)]): return num_list[0] elif (num_list[int(len(num_list)//2)] &gt; num_list[len(num_list) - 1]) and (num_list[0] &gt; num_list[int(len(num_list)//2)]): return num_list[int(len(num_list)//2)] else: return num_list[len(num_list) - 1] </code></pre> <p>this seems to be returning the last else statement every time, I'm stumped...</p>
0
2016-10-17T00:13:46Z
40,076,989
<p>Let Python do the work for you. Sort the three elements, then return the middle one.</p> <pre><code>def median(num_list): return sorted([num_list[0], num_list[len(num_list) // 2], num_list[-1]])[1] </code></pre>
1
2016-10-17T00:31:02Z
[ "python", "quicksort" ]
Median of three, pivot
40,076,890
<p>I'm looking for the <strong>median of three</strong>, using this for a pivot in a QuickSort. I would not like to import any statistics library because I believe it creates a bit of overhead which I would like to reduce as much as possible.</p> <pre><code>def median(num_list): if (num_list[0] &gt; num_list[len(num_list) - 1]) and (num_list[0] &lt; num_list[int(len(num_list)//2)]): return num_list[0] elif (num_list[int(len(num_list)//2)] &gt; num_list[len(num_list) - 1]) and (num_list[0] &gt; num_list[int(len(num_list)//2)]): return num_list[int(len(num_list)//2)] else: return num_list[len(num_list) - 1] </code></pre> <p>this seems to be returning the last else statement every time, I'm stumped...</p>
0
2016-10-17T00:13:46Z
40,076,999
<p>In Quicksort you do not usually want just to know the median of three, you want to arrange the three values so the smallest is in one spot, the median in another, and the maximum in yet another. But if you really just want the median of three, here are two ways, plus another that rearranges.</p> <p>Here's a short way to find the median of <code>a</code>, <code>b</code>, and <code>c</code>.</p> <pre><code>return a + b + c - min(a, b, c) - max(a, b, c) </code></pre> <p>If you want only comparisons, and to get what may be the quickest code, realize that three comparisons may need to be executed but you want to try for only two. (Two comparisons can handle four cases, but there are six arrangements of three objects.) Try</p> <pre><code>if a &lt; b: if b &lt; c: return b elif a &lt; c: return c else: return a else: if a &lt; c: return a elif b &lt; c: return c else: return b </code></pre> <p>If you want to rearrange the values so <code>a &lt;= b &lt;= c</code>,</p> <pre><code>if a &gt; b: a, b = b, a if b &gt; c: b, c = c, b if a &gt; b a, b = b, a return b </code></pre>
1
2016-10-17T00:32:39Z
[ "python", "quicksort" ]
Median of three, pivot
40,076,890
<p>I'm looking for the <strong>median of three</strong>, using this for a pivot in a QuickSort. I would not like to import any statistics library because I believe it creates a bit of overhead which I would like to reduce as much as possible.</p> <pre><code>def median(num_list): if (num_list[0] &gt; num_list[len(num_list) - 1]) and (num_list[0] &lt; num_list[int(len(num_list)//2)]): return num_list[0] elif (num_list[int(len(num_list)//2)] &gt; num_list[len(num_list) - 1]) and (num_list[0] &gt; num_list[int(len(num_list)//2)]): return num_list[int(len(num_list)//2)] else: return num_list[len(num_list) - 1] </code></pre> <p>this seems to be returning the last else statement every time, I'm stumped...</p>
0
2016-10-17T00:13:46Z
40,078,280
<p>Using <code>min</code> and <code>max</code>:</p> <pre><code>&gt;&gt;&gt; numlist = [21, 12, 16] &gt;&gt;&gt; a, b, c = numlist &gt;&gt;&gt; max(min(a,b), min(b,c), min(a,c)) 16 &gt;&gt;&gt; </code></pre> <hr> <p>Going out on a limb - I have a functional streak so here is the itertools equivalent, even though it means importing a module</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; numlist = [21, 12, 16] &gt;&gt;&gt; z = itertools.combinations(numlist, 2) &gt;&gt;&gt; y = itertools.imap(min, z) &gt;&gt;&gt; max(y) 16 </code></pre>
1
2016-10-17T03:58:08Z
[ "python", "quicksort" ]
Python regex to replace a double newline delimited paragraph containing a string
40,076,903
<p>Define a paragraph as a multi-line string delimited on both side with double new lines ('\n\n'). if there exist a paragraph which contains a certain string ('BAD'), i want to replace that paragraph (i.e. any text containing BAD up to the closest preceding and following double newlines) with some other token ('GOOD'). this should be with a python 3 regex.</p> <p>i have text such as:</p> <pre><code>dfsdf\n sdfdf\n \n blablabla\n blaBAD\n bla\n \n dsfsdf\n sdfdf </code></pre> <p>should be:</p> <pre><code>dfsdf\n sdfdf\n \n GOOD\n \n dsfsdf\n sdfdf </code></pre>
-2
2016-10-17T00:16:51Z
40,076,973
<p>Here you are:</p> <pre><code>/\n\n(?:[^\n]|\n(?!\n))*BAD(?:[^\n]|\n(?!\n))*/g </code></pre> <p>OK, to break it down a little (because it's nasty looking):</p> <ul> <li><code>\n\n</code> matches two literal line breaks.</li> <li><code>(?:[^\n]|\n(?!\n))*</code> is a non-capturing group that matches either a single non-line break character, or a line break character that isn't followed by another. We repeat the entire group 0 or more times (in case <code>BAD</code> appears at the beginning of the paragraph).</li> <li><code>BAD</code> will match the literal text you want. Simple enough.</li> <li>Then we use the same construction as above, to match the rest of the paragraph.</li> </ul> <p>Then, you just replace it with <code>\n\nGOOD</code>, and you're off to the races.</p> <p><a href="https://regex101.com/r/alaJMF/3" rel="nofollow">Demo on Regex101</a></p>
4
2016-10-17T00:28:57Z
[ "python", "regex" ]
Python regex to replace a double newline delimited paragraph containing a string
40,076,903
<p>Define a paragraph as a multi-line string delimited on both side with double new lines ('\n\n'). if there exist a paragraph which contains a certain string ('BAD'), i want to replace that paragraph (i.e. any text containing BAD up to the closest preceding and following double newlines) with some other token ('GOOD'). this should be with a python 3 regex.</p> <p>i have text such as:</p> <pre><code>dfsdf\n sdfdf\n \n blablabla\n blaBAD\n bla\n \n dsfsdf\n sdfdf </code></pre> <p>should be:</p> <pre><code>dfsdf\n sdfdf\n \n GOOD\n \n dsfsdf\n sdfdf </code></pre>
-2
2016-10-17T00:16:51Z
40,076,977
<p>Firstly, you're mixing actual newlines and <code>'\n'</code> characters in your example, I assume that you only meant either. Secondly, let me challenge your assumption that you need regex for this:</p> <pre><code>inp = '''dfsdf sdadf blablabla blaBAD bla dsfsdf sdfdf''' replaced = '\n\n'.join(['GOOD' if 'BAD' in k else k for k in inp.split('\n\n')]) </code></pre> <p>The result is</p> <pre><code>print(replaced) 'dfsdf\nsdadf\n\nGOOD\n\ndsfsdf\nsdfdf' </code></pre>
4
2016-10-17T00:29:30Z
[ "python", "regex" ]
shapely is_valid for polygons in 3D
40,076,962
<p>I'm trying to validate some polygons that are on planes with <code>is_valid</code>, but I get <code>Too few points in geometry component at or near point</code> for polygons where the z is not constant.</p> <p>Is there a way to validate these other polygons?</p> <p>Here's an example:</p> <pre><code>from shapely.geometry import Polygon poly1 = Polygon([(0,0), (1,1), (1,0)]) print(poly1.is_valid) # True # z=1 poly2 = Polygon([(0,0,1), (1,1,1), (1,0,1)]) print(poly2.is_valid) # True # x=1 poly3 = Polygon([(1,0,0), (1,1,1), (1,1,0)]) print(poly3.is_valid) # Too few points in geometry component at or near point 1 0 0 # False </code></pre>
0
2016-10-17T00:27:19Z
40,138,876
<p>The problem is that <code>shapely</code> in fact ignores the z coordinate. So, as far as shapely can tell you are building a polygon with the points <code>[(1,0),(1,1), (1,1)]</code> that aren't enough to build a polygon.</p> <p>See this other SO question for more information: <a href="http://stackoverflow.com/questions/39317261/python-polygon-does-not-close-shapely/39347117#39347117">python-polygon-does-not-close-shapely</a>.</p> <p>IMHO, shapely shouldn't allow three dimension coordinates, because it brings this kind of confusions. </p>
1
2016-10-19T18:21:42Z
[ "python", "gis", "shapely" ]
Can't pass random variable to tf.image.central_crop() in Tensorflow
40,077,010
<p>In Tensorflow I am training from a set of PNG files and I wish to apply data augmentation. I have successfully used <code>tf.image.random_flip_left_right()</code></p> <p>But I get an error when I try to use <code>tf.image.central_crop()</code>. basically I would like the central_fraction to be drawn from a uniform distribution (0.8,1.0].</p> <p>Here is my code. Where did I go wrong? Should <code>frac</code> be a <code>tf.random_uniform()</code>?</p> <pre><code>filename_queue = tf.train.string_input_producer( tf.train.match_filenames_once("./images/*.png")) image_reader = tf.WholeFileReader() # Read an entire image file _, image_file = image_reader.read(filename_queue) image = tf.image.decode_png(image_file, channels=3, dtype=tf.uint8, name="PNGDecompressor") image.set_shape([800,400,3]) frac = random.uniform(0.8,1.0) image = tf.image.central_crop(image, central_fraction = frac) # THIS FAILS # image = tf.image.central_crop(image, central_fraction = 0.8) # THIS WORKS image = tf.image.resize_images(image, [256, 128]) image.set_shape([256,128,3]) image = tf.cast(image, tf.float32) * (1. / 255) - 0.5 # Convert from [0, 255] -&gt; [-0.5, 0.5] floats. image = tf.image.per_image_whitening(image) image = tf.image.random_flip_left_right(image, seed=42) # Start a new session to show example output. with tf.Session() as sess: tf.initialize_all_variables().run() coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) t_image= sess.run([image]) [...] coord.request_stop() coord.join(threads) </code></pre> <p>Fails with error:</p> <pre><code>TypeError: Fetch argument 0.9832154064713503 has invalid type &lt;class 'float'&gt;, must be a string or Tensor. (Can not convert a float into a Tensor or Operation.) </code></pre>
2
2016-10-17T00:33:51Z
40,143,349
<p>I solved my own problem defining the following function. I adjusted the code provided in tf.image.central_crop(image, central_fraction). The function RandomCrop will crop an image taking a central_fraction drawn from a uniform distribution. You can just specify the min and max fraction you want. You can replace random_uniform distribution to a different one obviously.</p> <pre><code>def RandomCrop(image,fMin, fMax): from tensorflow.python.ops import math_ops from tensorflow.python.ops import array_ops from tensorflow.python.framework import ops image = ops.convert_to_tensor(image, name='image') if fMin &lt;= 0.0 or fMin &gt; 1.0: raise ValueError('fMin must be within (0, 1]') if fMax &lt;= 0.0 or fMax &gt; 1.0: raise ValueError('fMin must be within (0, 1]') img_shape = array_ops.shape(image) depth = image.get_shape()[2] my_frac2 = tf.random_uniform([1], minval=fMin, maxval=fMax, dtype=tf.float32, seed=42, name="uniform_dist") fraction_offset = tf.cast(math_ops.div(1.0 , math_ops.div(math_ops.sub(1.0,my_frac2[0]), 2.0)),tf.int32) bbox_h_start = math_ops.div(img_shape[0], fraction_offset) bbox_w_start = math_ops.div(img_shape[1], fraction_offset) bbox_h_size = img_shape[0] - bbox_h_start * 2 bbox_w_size = img_shape[1] - bbox_w_start * 2 bbox_begin = array_ops.pack([bbox_h_start, bbox_w_start, 0]) bbox_size = array_ops.pack([bbox_h_size, bbox_w_size, -1]) image = array_ops.slice(image, bbox_begin, bbox_size) # The first two dimensions are dynamic and unknown. image.set_shape([None, None, depth]) return(image) </code></pre>
0
2016-10-19T23:54:02Z
[ "python", "tensorflow" ]
scikit-learn CountVectorizer UnicodeDecodeError
40,077,084
<p>I have the following code snippet where I'm trying to list the term frequencies, where <code>first_text</code> and <code>second_text</code> are <code>.tex</code> documents:</p> <pre><code>from sklearn.feature_extraction.text import CountVectorizer training_documents = (first_text, second_text) vectorizer = CountVectorizer() vectorizer.fit_transform(training_documents) print "Vocabulary:", vectorizer.vocabulary </code></pre> <p>When I run the script, I get the following:</p> <pre><code>File "test.py", line 19, in &lt;module&gt; vectorizer.fit_transform(training_documents) File "/usr/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 817, in fit_transform self.fixed_vocabulary_) File "/usr/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 752, in _count_vocab for feature in analyze(doc): File "/usr/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 238, in &lt;lambda&gt; tokenize(preprocess(self.decode(doc))), stop_words) File "/usr/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 115, in decode doc = doc.decode(self.encoding, self.decode_error) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0xa2 in position 200086: invalid start byte </code></pre> <p>How can I fix this issue?</p> <p>Thanks.</p>
0
2016-10-17T00:47:55Z
40,077,782
<p>If you can work out what the encoding of your documents is (maybe they are <code>latin-1</code>) you can pass this to <code>CountVectorizer</code> with</p> <pre><code>vectorizer = CountVectorizer(encoding='latin-1') </code></pre> <p>Otherwise you can just skip the tokens containing the problematic bytes with</p> <pre><code>vectorizer = CountVectorizer(decode_error='ignore') </code></pre>
1
2016-10-17T02:45:59Z
[ "python", "scikit-learn" ]
Counting/Print Unique Words in Directory up to x instances
40,077,089
<p>I am attempting to take all unique words in tale4653, count their instances, and then read off the top 100 mentioned unique words. </p> <p>My struggle is sorting the directory so that I can print both the unique word and its' respected instances. </p> <h2>My code thus far:</h2> <pre><code>import string fhand = open('tale4653.txt') counts = dict() for line in fhand: line = line.translate(None, string.punctuation) line = line.lower() words = line.split() for word in words: if word not in counts: counts[word] = 1 else: counts[word] += 1 fhand.close() rangedValue = sorted(counts.values(), reverse=True) i =0 while i&lt;100: print rangedValue[i] i=i+1 </code></pre> <p>Thank you community, </p>
0
2016-10-17T00:48:28Z
40,077,193
<p>you loose the word (the key in your dictionary) when you do <code>counts.values()</code>)</p> <p>you can do this instead</p> <pre><code>rangedValue = sorted(counts.items(), reverse=True, key=lambda x: x[1]) for word, count in rangedValue: print word + ': ' + str(rangedValue) </code></pre> <p>when you do counts.items() it will return a list of tuples of key and value like this:</p> <pre><code>[('the', 1), ('end', 2)] </code></pre> <p>and when we sort it we tell it to take the second value as the "key" to sort with</p>
0
2016-10-17T01:07:54Z
[ "python", "sorting", "while-loop", "directory" ]
Counting/Print Unique Words in Directory up to x instances
40,077,089
<p>I am attempting to take all unique words in tale4653, count their instances, and then read off the top 100 mentioned unique words. </p> <p>My struggle is sorting the directory so that I can print both the unique word and its' respected instances. </p> <h2>My code thus far:</h2> <pre><code>import string fhand = open('tale4653.txt') counts = dict() for line in fhand: line = line.translate(None, string.punctuation) line = line.lower() words = line.split() for word in words: if word not in counts: counts[word] = 1 else: counts[word] += 1 fhand.close() rangedValue = sorted(counts.values(), reverse=True) i =0 while i&lt;100: print rangedValue[i] i=i+1 </code></pre> <p>Thank you community, </p>
0
2016-10-17T00:48:28Z
40,078,587
<p>DorElias is correct in the initial problem: you need to use <code>count.items()</code> with <code>key=lambda x: x[1]</code> or <code>key=operator.itemgetter(1)</code>, latter of which would be faster.</p> <hr> <p>However, I'd like to show how I'd do it, completely avoiding <code>sorted</code> in your code. <code>collections.Counter</code> is an optimal data structure for this code. I also prefer the logic of reading words in a file be wrapped in a generator</p> <pre><code>import string from collections import Counter def read_words(filename): with open(filename) as fhand: for line in fhand: line = line.translate(None, string.punctuation) line = line.lower() words = line.split() for word in words: # in Python 3 one can use `yield from words` yield word counts = Counter(read_words('tale4653.txt')) for word, count in counts.most_common(100): print('{}: {}'.format(word, count)) </code></pre>
0
2016-10-17T04:38:53Z
[ "python", "sorting", "while-loop", "directory" ]
Some help in my moment of stupidness
40,077,119
<p>so I have this project that's due and for one of the questions, after doing all the calculations, you compare two different booleans. So, if both booleans are true the answer will return false, and if both booleans are false it will return false, and it will only return true if one of the booleans are true and the other is false (doesn't matter which)</p> <p>So lets say the two booleans are A and B</p> <p>My code looks like this return A != B</p> <p>His code looks like this return ((A and not B) or (B and not A))</p> <p>Who is right? Are we both right? Hes like a lot smarter than me so im just wondering if I did some stupid mistake</p>
0
2016-10-17T00:52:16Z
40,077,149
<p>You are both right, the result is the same. Just one option is shorter than the other or simpler.</p> <p>There isn't only one way to solve a problem, as long as the result is right. Here I offer yet another solution.</p> <p>You also can use XOR ^ </p> <pre><code>t = False f = False result = t ^ f print result &gt;&gt; False t = True f = False result = t ^ f print result &gt;&gt; True t = False f = True result = t ^ f print result &gt;&gt; True t = True f = True result = t ^ f print result &gt;&gt; False </code></pre>
0
2016-10-17T00:58:12Z
[ "python", "boolean", "logic" ]
Some help in my moment of stupidness
40,077,119
<p>so I have this project that's due and for one of the questions, after doing all the calculations, you compare two different booleans. So, if both booleans are true the answer will return false, and if both booleans are false it will return false, and it will only return true if one of the booleans are true and the other is false (doesn't matter which)</p> <p>So lets say the two booleans are A and B</p> <p>My code looks like this return A != B</p> <p>His code looks like this return ((A and not B) or (B and not A))</p> <p>Who is right? Are we both right? Hes like a lot smarter than me so im just wondering if I did some stupid mistake</p>
0
2016-10-17T00:52:16Z
40,077,267
<p><a href="https://i.stack.imgur.com/W405E.png" rel="nofollow">True False Table</a></p> <p>See the above true false table.</p> <p>XOR => ^</p> <p>So, in this case you can use A ^ B. However, A != B also works here.</p> <p>You are both right. But, your code is more concise. </p>
-1
2016-10-17T01:23:19Z
[ "python", "boolean", "logic" ]
Some help in my moment of stupidness
40,077,119
<p>so I have this project that's due and for one of the questions, after doing all the calculations, you compare two different booleans. So, if both booleans are true the answer will return false, and if both booleans are false it will return false, and it will only return true if one of the booleans are true and the other is false (doesn't matter which)</p> <p>So lets say the two booleans are A and B</p> <p>My code looks like this return A != B</p> <p>His code looks like this return ((A and not B) or (B and not A))</p> <p>Who is right? Are we both right? Hes like a lot smarter than me so im just wondering if I did some stupid mistake</p>
0
2016-10-17T00:52:16Z
40,077,271
<p>In my opinion, both of you are right. But I think your answer is more simple. </p> <pre><code>def fun(a,b): result = a ^ b #your code resultA= a!=b #your friend's code resultB= (a and not b) or (b and not a) print result print resultA print resultB print '-'*20 a = False b = False fun(a,b) a = True b = False fun(a,b) a = False b = True fun(a,b) a = True b = True fun(a,b) </code></pre> <p>OUTPUT:</p> <pre><code>False False False -------------------- True True True -------------------- True True True -------------------- False False False -------------------- </code></pre>
0
2016-10-17T01:24:02Z
[ "python", "boolean", "logic" ]
File Access in python
40,077,180
<p>Whenever I go to load a text file for my program it displays the info in the text file yet when I input the roster function it does not display the text file and show it is available to be modified. Is it something with how I created the text file in the first place or is my coding for <code>loadData</code> not written correctly i think i may be confused on the difference between just setting up a function just to read back the file instead of actually opening the text file to be able to modify it.</p> <pre><code>dict_member = {} players = dict_member class Players: def __init__(self, name, number, jersey): self.name = name self.number = number self.jersey = jersey def display(self): print('Printing current members\n') for number, player in dict_member.items(): print(player.name + ', ' + player.number + ', ' + player.jersey) def add(self): nam = input("Enter Player Name\n ") numb = input("Enter Player Number\n ") jers = input("Enter Jersey Number\n ") dict_member[nam] = Players(nam, numb, jers) def remove(self, name): if name in dict_member: del dict_member[name] def edit(self, name): if name in dict_member: nam = input("Enter Different Name\n") num = input("Enter New Number\n ") jers = input("Enter New Jersey Number\n ") del dict_member[name] dict_member[name] = Players(nam, num, jers) else: print("No such player exists") def saveData(self): roster = input("Filename to save: ") print("Saving data...") with open(roster, "r+") as rstr: for number, player in dict_member.items(): rstr.write(player.name + ', ' + player.number + ', ' + player.jersey) print("Data saved.") rstr.close() def loadData(self): dict_member = {} roster = input("Filename to load: ") file = open(roster, "r") while True: inLine = file.readline() if not inLine: 'break' inLine = inLine[:-1] name, number, jersey = inLine.split(",") dict_member[name] = (name, number, jersey) print("Data Loaded Successfully.") file.close() return dict_member def display_menu(): print("") print("1. Roster ") print("2. Add") print("3. Remove ") print("4. Edit ") print("5. Save") print("6. Load") print("9. Exit ") print("") return int(input("Selection&gt; ")) print("Welcome to the Team Manager") player_instance = Players(None, None, None) menu_item = display_menu() while menu_item != 9: if menu_item == 1: player_instance.display() elif menu_item == 2: player_instance.add() elif menu_item == 3: m = input("Enter Player to Remove\n") player_instance.remove(m) elif menu_item == 4: m = input("Enter Player to Edit\n") player_instance.edit(m) elif menu_item == 5: player_instance.saveData() elif menu_item == 6: player_instance.loadData() menu_item = display_menu() print("Exiting Program...") </code></pre>
2
2016-10-17T01:03:53Z
40,077,241
<p>you didnt load your data into <code>dict_member</code> before displaying the roster </p> <p>when you load your data in the loadData function you redefine <code>dict_member</code> so it will "shadow" the outer <code>dict_member</code> so when the <code>display</code> function is called <code>dict_member</code> will always be empty</p> <p>so you probably want to remove this line </p> <pre><code>def loadData(self): # **remove this line ---&gt;** dict_member = {} roster = input("Filename to load: ") file = open(roster, "r") while True: inLine = file.readline() if not inLine: break inLine = inLine[:-1] name, number, jersey = inLine.split(",") dict_member[name] = (name, number, jersey) print("Data Loaded Successfully.") file.close() return dict_member </code></pre>
-1
2016-10-17T01:17:32Z
[ "python" ]
File Access in python
40,077,180
<p>Whenever I go to load a text file for my program it displays the info in the text file yet when I input the roster function it does not display the text file and show it is available to be modified. Is it something with how I created the text file in the first place or is my coding for <code>loadData</code> not written correctly i think i may be confused on the difference between just setting up a function just to read back the file instead of actually opening the text file to be able to modify it.</p> <pre><code>dict_member = {} players = dict_member class Players: def __init__(self, name, number, jersey): self.name = name self.number = number self.jersey = jersey def display(self): print('Printing current members\n') for number, player in dict_member.items(): print(player.name + ', ' + player.number + ', ' + player.jersey) def add(self): nam = input("Enter Player Name\n ") numb = input("Enter Player Number\n ") jers = input("Enter Jersey Number\n ") dict_member[nam] = Players(nam, numb, jers) def remove(self, name): if name in dict_member: del dict_member[name] def edit(self, name): if name in dict_member: nam = input("Enter Different Name\n") num = input("Enter New Number\n ") jers = input("Enter New Jersey Number\n ") del dict_member[name] dict_member[name] = Players(nam, num, jers) else: print("No such player exists") def saveData(self): roster = input("Filename to save: ") print("Saving data...") with open(roster, "r+") as rstr: for number, player in dict_member.items(): rstr.write(player.name + ', ' + player.number + ', ' + player.jersey) print("Data saved.") rstr.close() def loadData(self): dict_member = {} roster = input("Filename to load: ") file = open(roster, "r") while True: inLine = file.readline() if not inLine: 'break' inLine = inLine[:-1] name, number, jersey = inLine.split(",") dict_member[name] = (name, number, jersey) print("Data Loaded Successfully.") file.close() return dict_member def display_menu(): print("") print("1. Roster ") print("2. Add") print("3. Remove ") print("4. Edit ") print("5. Save") print("6. Load") print("9. Exit ") print("") return int(input("Selection&gt; ")) print("Welcome to the Team Manager") player_instance = Players(None, None, None) menu_item = display_menu() while menu_item != 9: if menu_item == 1: player_instance.display() elif menu_item == 2: player_instance.add() elif menu_item == 3: m = input("Enter Player to Remove\n") player_instance.remove(m) elif menu_item == 4: m = input("Enter Player to Edit\n") player_instance.edit(m) elif menu_item == 5: player_instance.saveData() elif menu_item == 6: player_instance.loadData() menu_item = display_menu() print("Exiting Program...") </code></pre>
2
2016-10-17T01:03:53Z
40,077,242
<p>Try this:</p> <pre><code>def loadData(self): file = open(input("Filename to load: "), "r") text = file.read() file.close() for line in text: name, number, jersey = (line.rstrip()).split(',') dict_member[name] = (name, number, jersey) print("Data Loaded Successfully.") return dict_member def saveData(self, dict_member): file = open(input("Filename to save: "), "a") for number, player in dict_member.items(): rstr.write(player.name + ', ' + player.number + ', ' + player.jersey) print("Data saved.") file.close() </code></pre> <p>What I think was the error was you using <code>"break"</code> in string from instead of the command, <code>break</code> (no quotes required). I optimized the code a little so maybe it will work now? If not, what exactly happens? Try debugging as well as checking your file.</p>
-1
2016-10-17T01:17:36Z
[ "python" ]
Pandas - Data Frame - Reshaping Values in Data Frame
40,077,188
<p>I am new to Pandas and have a data frame with a team's score in 2 separate columns. This is what I have.</p> <pre><code>Game_ID Teams Score 1 Team A 95 1 Team B 85 2 Team C 90 2 Team D 72 </code></pre> <p>This is where I would like to get to and then ideally to.</p> <pre><code>1 Team A 95 Team B 94 2 Team C 90 Team B 72 </code></pre>
4
2016-10-17T01:07:02Z
40,077,293
<p>You can try something as follows: Create a <code>row_id</code> within each group by the <code>Game_ID</code> and then unstack by the <code>row_id</code> which will transform your data to wide format:</p> <pre><code>import pandas as pd df['row_id'] = df.groupby('Game_ID').Game_ID.transform(lambda g: pd.Series(range(g.size))) df.set_index(['row_id', 'Game_ID']).unstack(level=0).sortlevel(level = 1, axis = 1) </code></pre> <p><a href="https://i.stack.imgur.com/Lsl0a.png" rel="nofollow"><img src="https://i.stack.imgur.com/Lsl0a.png" alt="enter image description here"></a></p> <p><em>Update</em>:</p> <p>If the <code>row_id</code> is preferred to be dropped, you can drop the level from the columns:</p> <pre><code>df1 = df.set_index(['row_id', 'Game_ID']).unstack(level=0).sortlevel(level = 1, axis = 1) df1.columns = df1.columns.droplevel(level = 1) df1 </code></pre> <p><a href="https://i.stack.imgur.com/aF5Gc.png" rel="nofollow"><img src="https://i.stack.imgur.com/aF5Gc.png" alt="enter image description here"></a></p>
4
2016-10-17T01:27:35Z
[ "python", "pandas", "dataframe" ]
Pandas - Data Frame - Reshaping Values in Data Frame
40,077,188
<p>I am new to Pandas and have a data frame with a team's score in 2 separate columns. This is what I have.</p> <pre><code>Game_ID Teams Score 1 Team A 95 1 Team B 85 2 Team C 90 2 Team D 72 </code></pre> <p>This is where I would like to get to and then ideally to.</p> <pre><code>1 Team A 95 Team B 94 2 Team C 90 Team B 72 </code></pre>
4
2016-10-17T01:07:02Z
40,077,933
<p>Knowing that games always involve exactly 2 teams, we can manipulate the underlying numpy array.</p> <pre><code>pd.DataFrame(df.values[:, 1:].reshape(-1, 4), pd.Index(df.values[::2, 0], name='Game_ID'), ['Team', 'Score'] * 2) </code></pre> <p><a href="https://i.stack.imgur.com/YZPPL.png" rel="nofollow"><img src="https://i.stack.imgur.com/YZPPL.png" alt="enter image description here"></a></p>
1
2016-10-17T03:09:13Z
[ "python", "pandas", "dataframe" ]
How to extract and divide values from dictionary with another in Python?
40,077,209
<pre><code>sample = [['CGG','ATT'],['GCGC','TAAA']] #Frequencies of each base in the pair d1 = [[{'G': 0.66, 'C': 0.33}, {'A': 0.33, 'T': 0.66}], [{'G': 0.5, 'C': 0.5}, {'A': 0.75, 'T': 0.25}]] #Frequencies of each pair occurring together d2 = [{('C', 'A'): 0.33, ('G', 'T'): 0.66}, {('G', 'T'): 0.25, ('C', 'A'): 0.5, ('G', 'A'): 0.25}] </code></pre> <p>The Problem:</p> <p>Consider the first pair : ['CGG','ATT']</p> <p>How to calculate a, where a is :</p> <pre><code>float(a) = (freq of pairs) - ((freq of C in CGG) * (freq of A in ATT)) eg. in CA pairs, float (a) = (freq of CA pairs) - ((freq of C in CGG) * (freq of A in ATT)) Output a = (0.33) - ((0.33) * (0.33)) = 0.222222 </code></pre> <p>Calculating "a" for any one combination (either CA pair or GT pair)</p> <pre><code>Final Output for sample : a = [0.2222, - 0.125] </code></pre> <p>How to calculate b, where b is :</p> <pre><code>float (b) = (float(a)^2)/ (freq of C in CGG) * (freq G in CGG) * (freq A in ATT) * (freq of T in ATT) Output b = 1 </code></pre> <p>Do this for the entire list</p> <pre><code>Final Output for sample : b = [1, 0.3333] </code></pre> <p>I do not know how to extract the required values from d1 and d2 and perform the mathematical operations. </p> <p>I tried to write the following code for value of a</p> <pre><code>float a = {k: float(d1[k][0]) - d2[k][0] * d2[k][1]for k in d1.viewkeys() &amp; d2.viewkeys()} </code></pre> <p>But, it does not work. Also, I prefer a for loop instead of comprehensions</p> <p>My attempt to write (a pretty flawed) for-loop for the above:</p> <pre><code>float_a = [] for pair,i in enumerate(d2): for base,j in enumerate(d1): float (a) = pair[i][0] - base[j][] * base[j+1][] float_a.append(a) float_b = [] for floata in enumerate(float_a): for base,j in enumerate(d1): float (b) = (float(a) * float(a)) - (base[j] * base[j+1]*base[j+2]*base[j+3]) float_b.append(b) </code></pre>
4
2016-10-17T01:10:11Z
40,091,556
<p>Usually when there is a tricky problem like this with multiple formulas and intermediate steps, I like to modularize it by splitting the work into several functions. Here is the resulting commented code which handles the cases in the original question and in the comments:</p> <pre><code>from collections import Counter def get_base_freq(seq): """ Returns the normalized frequency of each base in a given sequence as a dictionary. A dictionary comprehension converts the Counter object into a "normalized" dictionary. """ seq_len = len(seq) base_counts = Counter(seq) base_freqs = {base: float(count)/seq_len for base, count in base_counts.items()} return base_freqs def get_pair_freq(seq1, seq2): """ Uses zip to merge two sequence strings together. Then performs same counting and normalization as in get_base_freq. """ seq_len = len(seq1) pair_counts = Counter(zip(seq1, seq2)) pair_freqs = {pair: float(count)/seq_len for pair, count in pair_counts.items()} return pair_freqs def calc_a(d1, d2): """ Arbitrarily takes the first pair in d2 and calculates the a-value from it. """ first_pair, pair_freq = d2.items()[0] base1, base2 = first_pair a = pair_freq - (d1[0][base1]*d1[1][base2]) return a def calc_b(a, d1): """ For this calculation, we need to use all of the values from d1 and multiply them together. This is done by merging the two sequence half-results together and multiplying in a for loop. """ denom_ACGT = d1[0].values() + d1[1].values() denom = 1 for val in denom_ACGT: denom *= val b = a*a/float(denom) return b if __name__ == "__main__": sample = [['CGG','ATT'], ['GCGC','TAAA'], ['ACAA','CAAC']] b_result = [] for seq_pair in sample: d1 = [get_base_freq(seq) for seq in seq_pair] d2 = get_pair_freq(*seq_pair) a = calc_a(d1, d2) b = calc_b(a, d1) b_result.append(b) print b_result </code></pre> <p>Let me know if anything needs to be cleared up or if it fails for a case which I have not considered!</p>
1
2016-10-17T16:41:00Z
[ "python", "list", "dictionary", "counter" ]
Luhn's Algorithm Pseudocode to code
40,077,230
<p>Hey guys I'm fairly new to the programming world. For a school practice question I was given the following text and I'm suppose to convert this into code. I've spent hours on it and still can't seem to figure it out but I'm determine to learn this. I'm currently getting the error</p> <pre><code> line 7, in &lt;module&gt; if i % 2 == 0: TypeError: not all arguments converted during string formatting </code></pre> <p>What does this mean? I'm still learning loops and I'm not sure if it's in the correct format or not. Thanks for your time. </p> <pre><code># GET user's credit card number # SET total to 0 # LOOP backwards from the last digit to the first one at a time # IF the position of the current digit is even THEN # DOUBLE the value of the current digit # IF the doubled value is more than 9 THEN # SUM the digits of the doubled value # ENDIF # SUM the calculated value and the total # ELSE # SUM the current digit and the total # ENDIF # END loop # IF total % 10 == 0 THEN # SHOW Number is valid # ELSE # SHOW number is invalid # ENDIF creditCard = input("What is your creditcard?") total = 0 for i in creditCard[-1]: if i % 2 == 0: i = i * 2 if i &gt; 9: i += i total = total + i else: total = total + i if total % 10 == 0: print("Valid") else: print("Invalid") </code></pre>
2
2016-10-17T01:14:49Z
40,077,285
<p>well, i can see 2 problems:</p> <p>1)when you do:</p> <pre><code>for i in creditCard[-1] </code></pre> <p>you dont iterate on the creditCard you simply take the last digit. you probably meant to do </p> <pre><code>for i in creditCard[::-1] </code></pre> <p>this will iterate the digits from the last one to the first one</p> <p>2) the pseudocode said to double the number if its POSITION is even, not if the digit itself is even</p> <p>so you can do this:</p> <pre><code>digit_count = len(creditCard) for i in range(digit_count -1, -1, -1): digit = creditCard[i] </code></pre> <p>or have a look at the <code>enumerate</code> built-in function</p> <p>edit:</p> <p>complete sample:</p> <pre><code>creditCard = input("What is your creditcard?") total = 0 digit_count = len(creditCard) for i in range(0, digit_count, -1): digit = creditCard[i] if i % 2 == 0: digit = digit * 2 if digit &gt; 9: digit = digit / 10 + digit % 10 # also noticed you didnt sum the digits of the number total = total + digit if total % 10 == 0: print("Valid") else: print("Invalid") </code></pre>
1
2016-10-17T01:26:23Z
[ "python" ]
How to display images inside the new tab in Python
40,077,278
<p>Suppose that I have 10 images in a directory, and need them to be displayed inside a newly created tab once the user presses a push-button. The images must be displayed according to a 5x5 grid with a proper image label. </p> <p>I have designed a GUI using Qt Designer containing three different tabs (tab1, tab2 and tab3), but it seems like this will not work for me - the images wouldn't display inside tab3. How can I make it done by using command-line coding rather than using Qt Designer in order to display all the images?</p> <p>Below is the function to display the images:</p> <pre><code># Display image at 'Tab 3' once user press button 'Display' def display_result(self): # Get wafer qty qty = int(self.qty_selected) print('qty -&gt; ' + str(qty)) # Get lot id name = str(self.lotId) print ('lotId -&gt; ' + str(name)) for index in range(int(qty)): pixmap = QtGui.QPixmap() path = r'c:\Users\mohd_faizal4\Desktop\Python\Testing\%s\%s_%d.jpeg' % (name, name, index + 1) print('load (%s) %r' % (pixmap.load(path), path)) item = QtGui.QListWidgetItem(os.path.basename(path)) item.setIcon(QtGui.QIcon(path)) self.viewer.addItem(item) contents = QtGui.QWidget(self.tabWidget) layout = QtGui.QVBoxLayout(contents) self.tabWidget.addTab(contents, 'Tab 4') </code></pre> <p>I would like to display all the images inside 'Tab 4', instead of opening a another window.</p> <p><a href="https://i.stack.imgur.com/TcMm3.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/TcMm3.jpg" alt="tab 3"></a> </p>
-1
2016-10-17T01:24:53Z
40,083,504
<p>You can easly display an image inside the tab by creating a label in the tab, here is an example for that : ( the tab in my example is tab_3)</p> <p><code>def setupUi(self, MainWindow): self.label = QtWidgets.QLabel(self.tab_3) self.label.setGeometry(QtCore.QRect(340, 30, 241, 171)) self.label.setText("") self.label_181.setPixmap(QtGui.QPixmap("images/A_01.png")) self.label.setScaledContents(True) self.label.setObjectName("label")</code></p> <p>so here you will get the image inside the tab.I hope that will help you.</p>
0
2016-10-17T10:03:31Z
[ "python", "image", "user-interface", "tabs", "pyqt" ]
How to display images inside the new tab in Python
40,077,278
<p>Suppose that I have 10 images in a directory, and need them to be displayed inside a newly created tab once the user presses a push-button. The images must be displayed according to a 5x5 grid with a proper image label. </p> <p>I have designed a GUI using Qt Designer containing three different tabs (tab1, tab2 and tab3), but it seems like this will not work for me - the images wouldn't display inside tab3. How can I make it done by using command-line coding rather than using Qt Designer in order to display all the images?</p> <p>Below is the function to display the images:</p> <pre><code># Display image at 'Tab 3' once user press button 'Display' def display_result(self): # Get wafer qty qty = int(self.qty_selected) print('qty -&gt; ' + str(qty)) # Get lot id name = str(self.lotId) print ('lotId -&gt; ' + str(name)) for index in range(int(qty)): pixmap = QtGui.QPixmap() path = r'c:\Users\mohd_faizal4\Desktop\Python\Testing\%s\%s_%d.jpeg' % (name, name, index + 1) print('load (%s) %r' % (pixmap.load(path), path)) item = QtGui.QListWidgetItem(os.path.basename(path)) item.setIcon(QtGui.QIcon(path)) self.viewer.addItem(item) contents = QtGui.QWidget(self.tabWidget) layout = QtGui.QVBoxLayout(contents) self.tabWidget.addTab(contents, 'Tab 4') </code></pre> <p>I would like to display all the images inside 'Tab 4', instead of opening a another window.</p> <p><a href="https://i.stack.imgur.com/TcMm3.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/TcMm3.jpg" alt="tab 3"></a> </p>
-1
2016-10-17T01:24:53Z
40,091,238
<p>You need to create a new list-widget for each tab. Here's a demo:</p> <pre><code>import sys, os from PyQt4 import QtCore, QtGui class Window(QtGui.QWidget): def __init__(self): super(Window, self).__init__() self.tabs = QtGui.QTabWidget(self) self.edit = QtGui.QLineEdit(self) self.button = QtGui.QPushButton('New Tab', self) self.button.clicked.connect(self.createNewTab) layout = QtGui.QGridLayout(self) layout.addWidget(self.tabs, 0, 0, 1, 2) layout.addWidget(self.edit, 1, 0) layout.addWidget(self.button, 1, 1) def createNewTab(self): viewer = QtGui.QListWidget(self) viewer.setViewMode(QtGui.QListView.IconMode) viewer.setIconSize(QtCore.QSize(256, 256)) viewer.setResizeMode(QtGui.QListView.Adjust) viewer.setSpacing(10) name = self.edit.text() for index in range(5): pixmap = QtGui.QPixmap() path = r'c:\Users\mohd_faizal4\Desktop\Python\Testing\%s\%s_%d.jpeg' % (name, name, index + 1) print('load (%s) %r' % (pixmap.load(path), path)) item = QtGui.QListWidgetItem(os.path.basename(path)) item.setIcon(QtGui.QIcon(path)) viewer.addItem(item) index = self.tabs.count() self.tabs.addTab(viewer, 'Tab%d' % (index + 1)) self.tabs.setCurrentIndex(index) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) window = Window() window.setGeometry(800, 150, 650, 500) window.show() sys.exit(app.exec_()) </code></pre>
0
2016-10-17T16:21:21Z
[ "python", "image", "user-interface", "tabs", "pyqt" ]
Trying to rewrite variables
40,077,284
<pre><code> print("Please enter some integers to average. Enter 0 to indicate you are done.") #part (a) -- what are the initial values for these variables? #incomplete done = 0 mySum = 0 count = 0 while not done: valid = False #don't yet have a valid input while not valid: #this loop keeps attempting to get input until the user enters an integer try: num = int(input()) valid = True #now the input is valid, and can use it except ValueError: print("Input must be an integer.") if num == 0: break mySum = sum(num) count = len(num) #part (b) -- fill in the inside of this if statement #incomplete else: print num #part (c) -- if num is not zero, then... fill in the code #incomplete avg = mySum / count #calculates average print("The average is", avg) #prints average </code></pre> <p>Excuse the comments as this is an assignment from an instructor. As you can see, line 28 of the code shows a divide by zero error for variable mySum. In the while loop I overwrote(or at least tried to) mySum, but still got the division error. Am I going about this correctly or is there some syntax I'm not following? </p> <p>EDIT: New attempt:</p> <pre><code>#part (a) -- what are the initial values for these variables? #incomplete done = 0 mySum = [] count = len(mySum) while not done: valid = False #don't yet have a valid input while not valid: #this loop keeps attempting to get input until the user enters an integer try: num = int(input()) valid = True #now the input is valid, and can use it except ValueError: print("Input must be an integer.") if num == 0: break #part (b) -- fill in the inside of this if statement #incomplete else: mySum.append(num) count +=1#part (c) -- if num is not zero, then... fill in the code #incomplete avg = sum(mySum) / count #calculates average if len(mySum) == 0: print "You haven't entered any number" else: print ("The average is", avg) </code></pre>
-1
2016-10-17T01:25:57Z
40,077,336
<p>Denominator cannot be zero. In this case, count is zero.</p> <p>You may need to use count += 1 instead of count = len(num).</p> <p>You should check whether the denominator is zero before you do the division.</p> <p>Suggestion: study python 3 instead of python 2.7. Python 2 will be finally replaced by python 3.</p> <pre><code> mySum = 0 count = 0 while True: # this loop keeps attempting to get input until the user enters an integer try: num = int(input("input a num ")) except ValueError: print("Input must be an integer.") continue if num == 0: break else: mySum += num count += 1 print(num) avg = mySum / count if count else 0 print("The average is", avg) # prints average </code></pre>
0
2016-10-17T01:33:58Z
[ "python", "python-2.7" ]
Trying to rewrite variables
40,077,284
<pre><code> print("Please enter some integers to average. Enter 0 to indicate you are done.") #part (a) -- what are the initial values for these variables? #incomplete done = 0 mySum = 0 count = 0 while not done: valid = False #don't yet have a valid input while not valid: #this loop keeps attempting to get input until the user enters an integer try: num = int(input()) valid = True #now the input is valid, and can use it except ValueError: print("Input must be an integer.") if num == 0: break mySum = sum(num) count = len(num) #part (b) -- fill in the inside of this if statement #incomplete else: print num #part (c) -- if num is not zero, then... fill in the code #incomplete avg = mySum / count #calculates average print("The average is", avg) #prints average </code></pre> <p>Excuse the comments as this is an assignment from an instructor. As you can see, line 28 of the code shows a divide by zero error for variable mySum. In the while loop I overwrote(or at least tried to) mySum, but still got the division error. Am I going about this correctly or is there some syntax I'm not following? </p> <p>EDIT: New attempt:</p> <pre><code>#part (a) -- what are the initial values for these variables? #incomplete done = 0 mySum = [] count = len(mySum) while not done: valid = False #don't yet have a valid input while not valid: #this loop keeps attempting to get input until the user enters an integer try: num = int(input()) valid = True #now the input is valid, and can use it except ValueError: print("Input must be an integer.") if num == 0: break #part (b) -- fill in the inside of this if statement #incomplete else: mySum.append(num) count +=1#part (c) -- if num is not zero, then... fill in the code #incomplete avg = sum(mySum) / count #calculates average if len(mySum) == 0: print "You haven't entered any number" else: print ("The average is", avg) </code></pre>
-1
2016-10-17T01:25:57Z
40,077,358
<p>The "divide by zero" is a consequence of other problems in your code (or incompleteness of it). The proximate cause can be understood from the message: you are dividing by <code>0</code>, which means <code>count</code> is <code>0</code> at that point, which means you haven't actually tracked the numbers you put in. This, in turn, is - because you don't do anything with the numbers you put in.</p> <ul> <li><p>In case <code>num == 0</code>, you immediately <code>break</code> the loop; the two statements below do not execute.</p></li> <li><p>In case of not <code>num == 0</code>, you just print the number; there is not storing of a number into an array that you can <code>sum</code> later, there is no <code>+=</code> summing in an interim variable, and there is certainly no incrementing of <code>count</code>.</p></li> </ul> <p>There is two basic ways to do this, hinted to by the above:</p> <p>List: Make an empty list outside the loop, when 0 is entered just break, otherwise add the new number to the list. After the loop, check the length: if it's zero, complain that no numbers have been entered, otherwise divide the sum by the length. No <code>count</code> required.</p> <p>Running total: Initialize <code>total</code> and <code>count</code> variables to <code>0</code> outside the loop; again, just break on a <code>0</code>, otherwise add one to the count and the number to the total. After the loop, do the same, just with <code>total</code> and <code>count</code> instead of with <code>sum</code> and <code>len</code>.</p>
0
2016-10-17T01:37:46Z
[ "python", "python-2.7" ]
scikit-learn SVM.SVC() is extremely slow
40,077,432
<p>i try to use the SVM classifier to train the data which is around 100k, but I find it is extremely slow and there is no any response when I run the code after 2 hr. when dataset is around 1k, i can get the result immediately, I also try the SGDClassifier and naïve bayes which is quite fast and get result within couple of mins.</p>
3
2016-10-17T01:49:36Z
40,077,679
<h3>General remarks about SVM-learning</h3> <p>SVM-training (with nonlinear-kernels; default in sklearn's SVC) is complexity-wise approximately (depends on the data and parameters) <strong>using the widely used SMO-algorithm (don't compare it with SGD-based approaches)</strong>: <code>O(n_samples^2 * n_features)</code> <a href="https://www.quora.com/What-is-the-computational-complexity-of-an-SVM" rel="nofollow">link to some question with this approximation given by one of sklearn's devs</a>.</p> <p>So we can do some math to approximate the time-difference between 1k and 100k samples:</p> <pre><code>1k = 1000^2 = 1.000.000 steps = Time X 100k = 100.000^2 = 10.000.000.000 steps = Time X * 10000 !!! </code></pre> <p>This is only an approximation and can be even worse or less worse (e.g. setting cache-size; trading-off memory for speed-gains)!</p> <h3>Scikit-learn specific remarks</h3> <p>The situation could also be much more complex because of all that nice stuff scikit-learn is doing for us behind the bars. The above is valid for the classic 2-class SVM. If you are by any chance trying to learn some multi-class data; scikit-learn will automatically use OneVsRest or OneVsAll approaches to do this (as the core SVM-algorithm does not support this). Read up scikit-learns docs to understand this part.</p> <p>The same warning applies to generating probabilities: SVM's do not naturally produce probabilities for final-predictions. So to use these (activated by parameter) scikit-learn uses a heavy cross-validation procedure called <strong>Platt-scaling</strong> which will take a lot of time too!</p> <h3>Scikit-learn documentation</h3> <p>Because sklearn has one of the best docs, there is often a good part within these docs to explain something like that (<a href="http://scikit-learn.org/stable/modules/svm.html#complexity" rel="nofollow">link</a>):</p> <p><a href="https://i.stack.imgur.com/gQlv9.png" rel="nofollow"><img src="https://i.stack.imgur.com/gQlv9.png" alt="enter image description here"></a></p>
3
2016-10-17T02:31:27Z
[ "python", "scikit-learn", "svm" ]
Generate Sample dataframes with constraints
40,077,508
<p>I have a dataframe of records that looks like:</p> <pre><code> 'Location' 'Rec ID' 'Duration' 'Rec-X' 0 Houston 126 17 [0.2, 0.34, 0.45, ..., 0.28] 1 Chicago 126 19.3 [0.12, 0.3, 0.41, ..., 0.39] 2 Boston 348 17.3 [0.12, 0.3, 0.41, ..., 0.39] 3 Chicago 138 12.3 [0.12, 0.3, 0.41, ..., 0.39] 4 New York 238 11.3 [0.12, 0.3, 0.41, ..., 0.39] ... 500 Chicago 126 19.3 [0.12, 0.3, 0.41, ..., 0.39] </code></pre> <p>And as part of a genetic algorithm process, I want to initialize a population (10) of records. I want each of my subset to contain 10 records, however I want NOT to contain the same 'Rec-ID' two times.</p> <p>Any idea on how to generate those 10 different dataframes?</p> <p>Thanks,</p>
0
2016-10-17T02:01:45Z
40,077,899
<p>you can drop duplicates based on your column from the dataframe and then access the 10 elements</p> <pre><code>df2 = df.drop_duplicates('Rec ID') df2.head(10) </code></pre> <p><strong>EDIT</strong> If you want to select randomly 10 unique elements Then something like this will work</p> <pre><code>def selectRandomUnique(df) : d2 = df.sample(n=3).drop_duplicates('ID') while len(d2) != 3 : d2 = df.sample(n=3).drop_duplicates('ID') return d2 </code></pre> <p>In this first you randomly select the rows and then drop any duplicates that may exist.</p>
1
2016-10-17T03:04:41Z
[ "python", "dataframe", "genetic" ]
How to draw onscreen controls in panda 3d?
40,077,546
<p>I want to make a game in panda3d with support for touch because I want it to be playable on my windows tablet also without attaching a keyboard. What I want to do is, find a way to draw 2d shapes that don't change when the camera is rotated. I want to add a dynamic analog pad so I must be able to animate it when the d-pad is used with mouse/touch.</p> <p>Any help will be appreciated</p>
1
2016-10-17T02:09:39Z
40,102,063
<p>Make those objects children of <code>base.render2d</code>, <code>base.aspect2d</code> or <code>base.pixel2d</code>. For proper GUI elements take a look at <code>DirectGUI</code>, for "I just want to throw these images up on the screen" at <code>CardMaker</code>.</p>
0
2016-10-18T07:26:26Z
[ "python", "panda3d" ]
Remote command does not return python
40,077,580
<p>I am rebooting a remote machine through Python, as it is a reboot, the current ssh session is killed. The request is not returned. I am not interested in the return though.</p> <p>os.command('sshpass -p password ssh user@host reboot')</p> <p>The code is performing the reboot, however the current session is killed and the script never returns.</p> <p>I can do an async and just ignore the thread, any other easy options?</p>
1
2016-10-17T02:15:22Z
40,077,696
<p>I'm surprised that the script doesn't return. The connection should be reset by the remote before it reboots. You can run the process asyc, the one problem is that subprocesses not cleaned up up by their parents become zombies (still take up space in the process table). You can add a Timer to give the script time to do its dirty work and then clean it up in the background.</p> <p>Notice that I switched that command to a list of parameters and skipped setting <code>shell=True</code>. It just means that no intermediate shell process is executed.</p> <pre><code>import sys import subprocess as subp import threading import timing def kill_process(proc): # kill process if alive if proc.poll() is None: proc.kill() time.sleep(.1) if proc.poll() is None: sys.stderr.write("Proc won't die\n") return # clean up dead process proc.wait() proc = subp.Popen(['sshpass', '-p', password, 'ssh', 'user@host', 'reboot') threading.Timer(5, kill_process, args=(proc,)) # continue on your busy day... </code></pre>
1
2016-10-17T02:33:51Z
[ "python", "python-2.7", "ssh" ]
Output random number between 30-35 using Random.seed(), 'for' and multiplication in Python
40,077,591
<p>I am new to programming. I had an assignment to write a code that will output a random number between 30 and 35. This code needs to use <code>random.seed()</code>, a FOR statement and a multiplication. I understand the <code>random.seed([x])</code> generates an initial value that could be used in the proceeding section of the code. However, I cant figure out how to proceed after obtaining the value of the random:</p> <pre><code>import random random.seed(70) print(random.random()) # This returns a value of 0.909769237923872 </code></pre> <p>How do i use this value to generate a random value between 30 and 35?</p> <p>Note: Without the specific directions above, I have been able to write two codes that functions as desired, so please I am not looking for alternative ways of writing the code. </p>
2
2016-10-17T02:16:34Z
40,077,752
<p>I'm not exactly sure how the <code>for</code> loop is relevant here, but you can use the formula that follows (based off Java's random number in range equation, mentioned <a href="http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range">here</a>) and in particular <a href="http://stackoverflow.com/a/363732/5647260">this</a> answer, which is as follows:</p> <pre><code>minimum + int(random.random() * (maximum - minimum)) </code></pre> <p>The above will generate a number in the interval <code>[minimum, maximum)</code>. This is because multiplying the random number in <code>[0, 1)</code> by <code>maximum - minimum</code> will give you a range of values, from <code>maximum</code> (inclusive) to <code>maximum</code> exclusive. Then you just add the <code>minimum</code> to that range to achieve the range of random values.</p> <p>We can nerf it to fit your needs of <code>[30, 35]</code> by setting minimum to 31 (inclusive) and 35 (exclusive):</p> <pre><code>31 + int(random.random() * (35 - 31)) </code></pre> <p>The above will generate <code>(30, 35)</code>, or a number between 30 and 35 exclusive:</p> <pre><code>&gt;&gt;&gt; print(31 + int(random.random() * (35 - 31))) 34 &gt;&gt;&gt; print(31 + int(random.random() * (35 - 31))) 32 &gt;&gt;&gt; print(31 + int(random.random() * (35 - 31))) 32 ... </code></pre> <p>This would most optimally be applied into a function, like so:</p> <pre><code>def random_in_range(minimum, maximum): #exclusive to exclusive return (minimum + 1) + int(random.random() * (maximum - (minimum + 1))) </code></pre> <p>And called like:</p> <pre><code>&gt;&gt;&gt; print(random_in_range(30, 35)) 33 </code></pre>
0
2016-10-17T02:42:09Z
[ "python", "python-3.x", "random" ]
Output random number between 30-35 using Random.seed(), 'for' and multiplication in Python
40,077,591
<p>I am new to programming. I had an assignment to write a code that will output a random number between 30 and 35. This code needs to use <code>random.seed()</code>, a FOR statement and a multiplication. I understand the <code>random.seed([x])</code> generates an initial value that could be used in the proceeding section of the code. However, I cant figure out how to proceed after obtaining the value of the random:</p> <pre><code>import random random.seed(70) print(random.random()) # This returns a value of 0.909769237923872 </code></pre> <p>How do i use this value to generate a random value between 30 and 35?</p> <p>Note: Without the specific directions above, I have been able to write two codes that functions as desired, so please I am not looking for alternative ways of writing the code. </p>
2
2016-10-17T02:16:34Z
40,077,830
<p>Here is another way to do it:</p> <pre><code>import random #initial random seed based on current system time #https://docs.python.org/2/library/random.html#random.seed random.seed(9) #We set this so random is repeatable in testing random_range = [30, 31, 32, 33, 34, 35] while True: num = int(round(random.random(),1)*100) if num in random_range: print num break </code></pre> <p>The seed is set to 9, so if you run this over and over again you will get the same random value...thus setting a seed. Note that multiple iterations are run because it was mentioned to not use a choice like random.choice </p>
0
2016-10-17T02:55:54Z
[ "python", "python-3.x", "random" ]
How do I import a CSV into an have each line be an object?
40,077,694
<p>I have a csv file with 8-12 values per line, this is spending data with categories, payment method, date, amount etc. Each line is a single purchase with these details. I want to import the file into python into a list that I can then iterate through easily to find for example, how much was spent on a given category in a given month. Is there a good method to create an object for a single purchase that has all of the attributes that I want and then do an import from a csv into a list of these objects? </p>
0
2016-10-17T02:33:37Z
40,077,760
<p>One tricky/hacky thing you can do with objects is programatically create them with <strong>dict</strong>. Here is an example:</p> <pre><code>In [1]: vals = {"one":1, "two":2} In [2]: class Csv():pass In [3]: c = Csv() In [4]: c.__dict__ = vals In [5]: c.one Out[5]: 1 </code></pre> <p>So, yes, you could create an empty object, create a dict, then insert it into the empty object so you can use it like an object with set attributes.</p>
0
2016-10-17T02:42:43Z
[ "python", "csv", "import" ]
How do I import a CSV into an have each line be an object?
40,077,694
<p>I have a csv file with 8-12 values per line, this is spending data with categories, payment method, date, amount etc. Each line is a single purchase with these details. I want to import the file into python into a list that I can then iterate through easily to find for example, how much was spent on a given category in a given month. Is there a good method to create an object for a single purchase that has all of the attributes that I want and then do an import from a csv into a list of these objects? </p>
0
2016-10-17T02:33:37Z
40,077,835
<p>Python brings its own CSV reader in <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">the csv module</a>. You can use it to read your CSV file and convert the lines to objects like this:</p> <pre><code>import csv # Read values from csv file. values = [] with open('file.csv', 'r') as csv_file: # Replace the delimiter with the one used in your CSV file. csv_reader = csv.reader(csv_file, delimiter=',') for row_values in csv_reader: # If a line in your CSV file looks like this: a,b,c # Then row_values looks something like this: ['a', 'b', 'c'] values.append(row_values) # Convert the list of lists (which represent the CSV values) to objects. column_names = ['first_column', 'second_column', 'third_column'] objects = [] for row_values in values: objects.append({key: value for key, value in zip(column_names, row_values)}) # objects is now a list of dicts with one dict per line of the CSV file. # The dicts could e.g. be converted to objects with this: class MyObject: def __init__(self, first_column, second_column, third_column): self.first_column = first_column self.second_column = second_column self.third_column = third_column print(objects) objects = [MyObject(**object) for object in objects] # Alternative: alternative_objects = [] for object in objects: new_object = object() new_object.__dict__ = object alternative_objects.append(new_object) </code></pre> <p>Please refer to the Python 2.7 or 3.x documentation for further details on the CSV module.</p>
0
2016-10-17T02:56:52Z
[ "python", "csv", "import" ]
how to remove host from ip address?
40,077,854
<p>Currently, I created a method to generate random ip(IPv4) address as below:</p> <pre><code>def rand_ip(mask=False): """This uses the TEST-NET-3 range of reserved IP addresses. """ test_net_3 = '203.0.113.' address = test_net_3 + six.text_type(random.randint(0, 255)) if mask: address = '/'.join((address, six.text_type(random.randrange(24, 32)))) return address </code></pre> <p>And now, I need enhance the method with the ability to remove host address when I had the mask enabled, the case is below</p> <pre><code>1.1.2.23/24(before) =&gt; 1.1.2.0/24(after host address removed) 1.1.2.23/16 =&gt; 1.1.0.0 (the same as above) </code></pre> <p>actually the change is just replace the left part(32-mask, right to left) with 0 in hexadecimal, Is there any simple way or existed libs can do this(python 2.7x and 3.x's compatibility should be considered)?</p>
0
2016-10-17T02:58:49Z
40,078,492
<p>Is this something that you were looking for?</p> <pre><code>&gt;&gt;&gt; from netaddr import * &gt;&gt;&gt; ip = IPNetwork('1.1.2.23/16') &gt;&gt;&gt; ip.ip IPAddress('1.1.2.23') &gt;&gt;&gt; ip.network (IPAddress('1.1.0.0') &gt;&gt;&gt; ip.netmask (IPAddress('255.255.0.0') </code></pre> <p>To randomly generate an IP and netmask you can use this code. This can be done better though. </p> <pre><code>import random def get_random_ip(): def ip(): return random.randint(0, 255) value = str(ip()) for i in range(3): value = value + "." + str(ip()) return value def get_random_cidr(): return random.randrange(24, 32) </code></pre>
1
2016-10-17T04:27:16Z
[ "python", "ip", "openstack" ]
Framing an indefinite horizon MDP, cost minimization with must-visit states
40,077,864
<p>Looking for some help in framing a problem of the indefinite horizon, cost minimization, with some must visit states.</p> <p>We are given a budget b and a cost matrix M which represents the deduction for travel between states ( Mij represents the cost for traveling from i to j ), similar to a classic traveling salesman problem. In this case the time may be negative representing additions to the budget, Mij may not necessarily be equal to Mji. Also in this case M is 4x4, but this may not be the case, generally lets say that 3 &lt;= len(M) &lt;= 5, as I assume this may require some brute force methods with lots of operations...</p> <pre><code>0 1 -3 1 6 0 2 2 4 2 0 3 1 2 3 0 </code></pre> <p>Each row represents a given state i and each column then represents the cost of traveling toward j. </p> <p>The problem is thus: given b and M, excluding state=0 and state=len(M) what is the maximum number of unique states we can travel to and end up at state=len(M) with b >= 0. </p> <p>Given the above M, and b=0, then I think the ouput would be [2], the path is [0] -> [2] -> [3] and the full rollout looks like this:</p> <pre><code>state nextstate deduction time -- 0 --- 0 0 2 -3 3 2 3 3 0 </code></pre> <p>I have attempted to solve this problem as a reinforcement learning problem with a e-greedy solution and a heuristic policy to select a next state, I have also thought of this like a TSP and looked at a solution using Floyd-Warshall but I am not quite sure how to fit the constraints within the problem set up. </p> <p>I think that there is a way to find a direct solution, and my intuition seems to be able to look at a general M and a given b and come up with a solution, but I am not able to cleanly phrase the algorithm...</p> <p>Some direction is appreciated on how to frame this cleanly and come up with a direct solution.</p>
0
2016-10-17T03:00:57Z
40,078,636
<p>In case your cost matrix contains negative cycles then all the states can be eventually visited. You can use <a href="https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm" rel="nofollow">Bellman-Ford</a> to detect the cycles so rest of the answer assumes that no such cycle exists.</p> <p>The algorithm consists of three parts. First it finds all the paths with cost less than budget from start state to end state. For every such path the states visited and total cost is tracked. Then it finds all the loops originating from (and terminating to) end state and tracks the visited states &amp; total costs.</p> <p>After all the paths and loops are known the algorithm starts to add loops to the paths. In case that loop adds new state and total cost is within the budget the addition is successful. Addition continues until there's no way to add a loop to existing paths. Finally the path containing most visited states is picked as a result.</p> <p>Here's non-refined implementation of the above:</p> <pre><code>M = [ [0, 2, 2, 2, -1], [6, 0, 2, 2, -1], [6, 3, 0, 2, -1], [6, 3, 2, 0, -1], [6, 3, 2, 2, 0] ] BUDGET = 1 SOURCE = 0 DEST = len(M) - 1 def all_paths_step(source, dest, visited, cost): for i in range(len(M)): if i in visited: continue new_cost = cost + M[source][i] new_set = visited | {i} if i == dest: yield new_set, new_cost elif i not in visited: yield from all_paths_step(i, dest, new_set, new_cost) def all_paths(source, dest, cost=0): result = {} for states, cost in all_paths_step(source, dest, frozenset([source]), cost): result[states] = min(result.get(states, float('inf')), cost) return result to_dest = all_paths(SOURCE, DEST) loops = {} for i in range(len(M)): if i == DEST: continue for states, cost in all_paths(i, len(M) - 1, M[len(M) - 1][i]).items(): loops[states] = min(loops.get(states, float('inf')), cost) possible = {visited: cost for visited, cost in to_dest.items() if cost &lt;= BUDGET} process = set(possible.keys()) while process: process_next = set() while process: states = process.pop() for path, cost in loops.items(): cost += possible[states] new_states = states | path if path &lt;= states or cost &gt;= possible.get(new_states, BUDGET + 1): continue possible[new_states] = cost process_next.add(new_states) process = process_next print('result: {}'.format(max(possible, key=len)) if possible else 'none') </code></pre> <p>Output, visited states in no particular order:</p> <pre><code>result: frozenset({0, 2, 3, 4}) </code></pre>
1
2016-10-17T04:45:10Z
[ "java", "python", "algorithm" ]
Bootstrap accordion with Django: How to only load the data for the open accordion section?
40,077,880
<p>I'm trying to make a webpage that will display recipes in the format of a bootstrap accordion like so (<a href="https://i.stack.imgur.com/1QEbG.png" rel="nofollow">see here</a>). This is how I'm doing it as of now:</p> <pre><code>&lt;div class="panel-group" id="accordion"&gt; {% for recipe in recipes %} &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h4 class="panel-title"&gt; &lt;a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ forloop.counter }}"&gt; {{ recipe }} &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;div id="collapse{{ forloop.counter }}" class="panel-collapse collapse"&gt; &lt;div class="panel-body"&gt; &lt;table class="table table-hover"&gt; {% for ingredient in foodtype|ingredients_in_recipe:recipe %} &lt;tr&gt; &lt;td&gt; {{ ingredient.ingredient_name }} &lt;/td&gt; &lt;td&gt; {{ ingredient.ingredient_quantity }} &lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;p&gt;{{ recipe.details }}&lt;/p&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; </code></pre> <p>I have made a custom template tag for this like so:</p> <pre><code>@register.filter def ingredients_in_recipe(foodtype, recipe): return foodtype.ingredient_set.filter(recipe=recipe).order_by("ingredient_name") </code></pre> <p>The problem is that I have 200+ recipes and loading all this data is way too slow. Ideally the template tag function ingredients_in_recipe should only be called when the user clicks on the recipe. However from my understanding this isn't possible because Django runs it all then sends the rendered HTML to the user.</p> <p>Is there anyway I could circumvent this issue whilst still keeping the accordion style like in the picture?</p> <p>Thanks in advance, Max</p> <p><strong>EDIT:</strong> Here's my view as well</p> <pre><code>def detail(request, foodtype_id): foodtype = get_object_or_404(foodtype, id=foodtype_id) recipe = foodtype.recipe_set.values_list('recipe').order_by('recipe').distinct() context = { 'foodtype': foodtype, 'recipe': recipe, } return render(request, 'main/detail.html', context) </code></pre>
2
2016-10-17T03:02:22Z
40,077,981
<p>Always better to do that logic before it gets to the template. What if you set the ordering on ingredients so then you won't have to order them in the template? Does that work and improve the performance?</p> <pre><code>class Ingredient(models.Model): ... class Meta: ordering = ['ingredient_name'] &lt;div class="panel-group" id="accordion"&gt; {% for recipe in recipes %} &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h4 class="panel-title"&gt; &lt;a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ forloop.counter }}"&gt; {{ recipe }} &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;div id="collapse{{ forloop.counter }}" class="panel-collapse collapse"&gt; &lt;div class="panel-body"&gt; &lt;table class="table table-hover"&gt; {% for ingredient in recipe.ingredient_set.all %} &lt;tr&gt; &lt;td&gt; {{ ingredient.ingredient_name }} &lt;/td&gt; &lt;td&gt; {{ ingredient.ingredient_quantity }} &lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;p&gt;{{ recipe.details }}&lt;/p&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; </code></pre>
1
2016-10-17T03:15:35Z
[ "python", "django", "twitter-bootstrap", "django-templates", "templatetags" ]
Guessinggame (replace variable issue)
40,077,881
<p>so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to</p> <p>1) prompt the user to enter a guess and store the value in the "guess" variable,<br> 2) if guess is greater than goal print...<br> 3) if guess is lower than goal... print...<br> 4) if guess is same as goal, print... </p> <p>Unsure how to fix this. Any help will be greatly appreciated. Code as below.</p> <pre><code>#Author: Anuj Saluja #Date: 17 October 2016 import random goal = random.randint(1,100) guess = 0 print ("The object of this game is to") print ("guess a number between 1 and 100") print() inputguess = int(input("Please guess the number: ") while (guess != goal): if inputguess &gt; goal print ("Too high, try again.") if inputguess &lt; goal print ("Too low, try again.") if inputguess == goal: break if inputguess == goal: print ("Well done!") print ("See you later.") </code></pre>
0
2016-10-17T03:02:35Z
40,077,928
<p>The code is only asking for a guess once before the while loop. You need to update the guess variable inside the while loop by asking for input again.</p>
1
2016-10-17T03:08:43Z
[ "python", "python-3.x" ]
Guessinggame (replace variable issue)
40,077,881
<p>so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to</p> <p>1) prompt the user to enter a guess and store the value in the "guess" variable,<br> 2) if guess is greater than goal print...<br> 3) if guess is lower than goal... print...<br> 4) if guess is same as goal, print... </p> <p>Unsure how to fix this. Any help will be greatly appreciated. Code as below.</p> <pre><code>#Author: Anuj Saluja #Date: 17 October 2016 import random goal = random.randint(1,100) guess = 0 print ("The object of this game is to") print ("guess a number between 1 and 100") print() inputguess = int(input("Please guess the number: ") while (guess != goal): if inputguess &gt; goal print ("Too high, try again.") if inputguess &lt; goal print ("Too low, try again.") if inputguess == goal: break if inputguess == goal: print ("Well done!") print ("See you later.") </code></pre>
0
2016-10-17T03:02:35Z
40,078,067
<p>Put this line : </p> <pre><code>inputguess = int(input("Please guess the number: ") </code></pre> <p>inside the while loop. The code is only asking the user input once, user input must be in the loop.</p>
0
2016-10-17T03:26:59Z
[ "python", "python-3.x" ]
Guessinggame (replace variable issue)
40,077,881
<p>so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to</p> <p>1) prompt the user to enter a guess and store the value in the "guess" variable,<br> 2) if guess is greater than goal print...<br> 3) if guess is lower than goal... print...<br> 4) if guess is same as goal, print... </p> <p>Unsure how to fix this. Any help will be greatly appreciated. Code as below.</p> <pre><code>#Author: Anuj Saluja #Date: 17 October 2016 import random goal = random.randint(1,100) guess = 0 print ("The object of this game is to") print ("guess a number between 1 and 100") print() inputguess = int(input("Please guess the number: ") while (guess != goal): if inputguess &gt; goal print ("Too high, try again.") if inputguess &lt; goal print ("Too low, try again.") if inputguess == goal: break if inputguess == goal: print ("Well done!") print ("See you later.") </code></pre>
0
2016-10-17T03:02:35Z
40,078,151
<p>Have you read your stack trace in detail? It's very easy to just skim over them, but stack traces can actually provide a lot of very useful information. For instance, the message is probably complaining that it was expecting a closing parenthesis. The line:</p> <pre><code>inputguess = int(input("Please guess the number: ") </code></pre> <p>should actually be</p> <pre><code>inputguess = int(input("Please guess the number: ")) </code></pre> <p>The stack trace says the error is on line 16 because that's where the interpreter realized something was wrong. More often than not, the buggy code will be in the last line of code before the line it gives you.</p> <p>also as other people stated, you need to put the input statement within the while loop in order to update the variable.</p> <p>You should also consider replacing tab characters with 4 spaces so it displays consistently no matter where you read it. Usually the text editor or IDE will have tab settings that you can change when you hit tab, it will type 4 spaces. A quick Google search along the lines of "{text editor} change tab settings" will usually bring up results on how to change it, where {text editor} is the name of the editor/IDE you're using.</p> <p>You should also consider indenting the code within your if statements as it improves readability</p>
0
2016-10-17T03:37:51Z
[ "python", "python-3.x" ]
Guessinggame (replace variable issue)
40,077,881
<p>so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to</p> <p>1) prompt the user to enter a guess and store the value in the "guess" variable,<br> 2) if guess is greater than goal print...<br> 3) if guess is lower than goal... print...<br> 4) if guess is same as goal, print... </p> <p>Unsure how to fix this. Any help will be greatly appreciated. Code as below.</p> <pre><code>#Author: Anuj Saluja #Date: 17 October 2016 import random goal = random.randint(1,100) guess = 0 print ("The object of this game is to") print ("guess a number between 1 and 100") print() inputguess = int(input("Please guess the number: ") while (guess != goal): if inputguess &gt; goal print ("Too high, try again.") if inputguess &lt; goal print ("Too low, try again.") if inputguess == goal: break if inputguess == goal: print ("Well done!") print ("See you later.") </code></pre>
0
2016-10-17T03:02:35Z
40,078,450
<p>I think you are looking for this. hope this will work. </p> <pre><code>import random goal = random.randint(1,100) guess = 0 print ("The object of this game is to") print ("guess a number between 1 and 100") inputguess = int(input("Please guess the number: ")) while True: if inputguess &gt; goal: inputguess = int(input("Too high, try again: ")) elif inputguess &lt; goal: inputguess = int(input("Too low, try again: ")) elif inputguess == goal: print ("Well done!") print ("See you later.") break </code></pre>
1
2016-10-17T04:21:47Z
[ "python", "python-3.x" ]
Guessinggame (replace variable issue)
40,077,881
<p>so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to</p> <p>1) prompt the user to enter a guess and store the value in the "guess" variable,<br> 2) if guess is greater than goal print...<br> 3) if guess is lower than goal... print...<br> 4) if guess is same as goal, print... </p> <p>Unsure how to fix this. Any help will be greatly appreciated. Code as below.</p> <pre><code>#Author: Anuj Saluja #Date: 17 October 2016 import random goal = random.randint(1,100) guess = 0 print ("The object of this game is to") print ("guess a number between 1 and 100") print() inputguess = int(input("Please guess the number: ") while (guess != goal): if inputguess &gt; goal print ("Too high, try again.") if inputguess &lt; goal print ("Too low, try again.") if inputguess == goal: break if inputguess == goal: print ("Well done!") print ("See you later.") </code></pre>
0
2016-10-17T03:02:35Z
40,081,285
<p>So I had someone help me irl and this works perfectly for anyone interested. Thanks everyone for help. :) Appreciate it.</p> <pre><code>goal = random.randint(1,100) guess = 0 print ("The object of this game is to") print ("guess a number between 1 and 100") print() while guess != goal: guess = int(input("Please guess the number: ")) if guess &gt; goal: print ("Too high, try again.") if guess &lt; goal: print ("Too low, try again.") if guess == goal: break if guess == goal: print ("Well done!") print ("See you later.") </code></pre>
0
2016-10-17T08:03:36Z
[ "python", "python-3.x" ]
Can I use PyQt for both C++ and Python?
40,077,940
<p>I'd like to learn Qt both on Python and C++. I am on Windows.</p> <p>Is instaling PyQT5 with <code>pip3 install pyqt5</code> enough for C++ development or do I still have to install both Qt and PyQt?</p> <p>How do I do the second option?</p>
0
2016-10-17T03:09:59Z
40,078,130
<p>For C++ development you're going to need a C++ compiler. On Windows Qt supports both the Mingw and Visual Studio toolchains. From there, I don't believe pyqt includes the header files you're going to need for C++ development and I cannot say for certain what toolchain it was compiled with. </p> <p>Your best bet is either install the official Qt binaries for your compiler, or build the binaries from source (the later will take some time and effort.)</p> <p>If you want to mix both C++ and Python in a single Qt project, check out <a href="https://www.riverbankcomputing.com/software/sip/intro" rel="nofollow">SIP bindings</a>.</p> <p>Another thing to keep in mind is that pyqt5 comes with the LGPL licensed version of Qt by default. This may or may not be appropriate for your project(s), but StackOverflow isn't intended to discuss licensing issues.</p>
0
2016-10-17T03:35:33Z
[ "python", "c++", "pyqt" ]
Can I use PyQt for both C++ and Python?
40,077,940
<p>I'd like to learn Qt both on Python and C++. I am on Windows.</p> <p>Is instaling PyQT5 with <code>pip3 install pyqt5</code> enough for C++ development or do I still have to install both Qt and PyQt?</p> <p>How do I do the second option?</p>
0
2016-10-17T03:09:59Z
40,140,451
<p>PyQt5 is for developing with Python.</p> <p>If you want to code in C++ the best you do is to download Qt5 and code inside QtCreator.</p> <p>Here is a link for <a href="https://www.qt.io/download-open-source/" rel="nofollow">Qt5 Opensource</a></p>
0
2016-10-19T19:58:59Z
[ "python", "c++", "pyqt" ]
Cropping Python lists by value instead of by index
40,077,966
<p>Good evening, StackOverflow. Lately, I've been wrestling with a Python program which I'll try to outline as briefly as possible. </p> <p>In essence, my program plots (and then fits a function to) graphs. Consider <a href="https://i.stack.imgur.com/axth1.png" rel="nofollow">this graph.</a> The graph plots just fine, but I'd like it to do a little more than that: since the data is periodic over an interval <strong>OrbitalPeriod</strong> (1.76358757), I'd like it to start with our <em>first x value</em> and then iteratively plot all of the points <strong>OrbitalPeriod</strong> away from it, and then do the same exact thing over the next region of length <strong>OrbitalPeriod</strong>. </p> <p>I know that there is a way to slice lists in Python of the form</p> <pre><code>croppedList = List[a:b] </code></pre> <p>where <em>a</em> and <em>b</em> are the indices of the first and last elements you'd like to include in the new list, respectively. However, I have no idea what the indices are going to be for each of the values, or how many values fall between each <strong>OrbitalPeriod</strong>-sized interval. </p> <p>What I want to do in pseudo-code looks something like this.</p> <blockquote> <p>croppedList = fullList on the domain [a + (N * <strong>OrbitalPeriod</strong>), a + (N+1 * <strong>OrbitalPeriod</strong>)] </p> </blockquote> <p>where <strong>a</strong> is the x-value of the first meaningful data point.</p> <p>If you have a workaround for this or a cropping method that would accept values instead of indices as arguments, please let me know. Thanks!</p>
2
2016-10-17T03:13:38Z
40,080,720
<p>If you are working with <code>numpy</code>, you can use it inside the brackets</p> <pre><code>m = x M = x + OrbitalPeriod croppedList = List[m &lt;= List] croppedList = croppedList[croppedList &lt; M] </code></pre>
0
2016-10-17T07:30:33Z
[ "python", "list", "plot", "crop", "slice" ]
TypeErrpr is raised when using `abort(404)`
40,077,971
<p>When I use <code>abort(status_code=404, detail='No such user', passthrough='json')</code> This exception is raised:</p> <p><code>TypeError: 'NoneType' object is not iterable</code> This is the traceback:</p> <pre><code>File "/home/jugger/.virtualenvs/ave/lib/python3.5/site-packages/tg/appwrappers/identity.py", line 47, in __call__ return self.next_handler(controller, environ, context) File "/home/jugger/.virtualenvs/ave/lib/python3.5/site-packages/tg/appwrappers/i18n.py", line 71, in __call__ return self.next_handler(controller, environ, context) File "/home/jugger/.virtualenvs/ave/lib/python3.5/site-packages/tg/wsgiapp.py", line 285, in _dispatch return controller(environ, context) File "/home/jugger/workspace/web/ave/ave/lib/base.py", line 27, in __call__ return TGController.__call__(self, environ, context) File "/home/jugger/.virtualenvs/ave/lib/python3.5/site-packages/tg/controllers/dispatcher.py", line 119, in __call__ response = self._perform_call(context) File "/home/jugger/.virtualenvs/ave/lib/python3.5/site-packages/tg/controllers/dispatcher.py", line 108, in _perform_call r = self._call(action, params, remainder=remainder, context=context) File "/home/jugger/.virtualenvs/ave/lib/python3.5/site-packages/tg/controllers/decoratedcontroller.py", line 125, in _call response = self._render_response(context, controller, output) File "/home/jugger/.virtualenvs/ave/lib/python3.5/site-packages/tg/controllers/decoratedcontroller.py", line 220, in _render_response for name in exclude_names: TypeError: 'NoneType' object is not iterable --------------------- &gt;&gt; end captured logging &lt;&lt; --------------------- </code></pre> <p>This is my code: I try to get an account that doesn't exist, so <code>NoResultFound</code> is caught and as the result <code>abort</code> must be done. but it raises the exception I mentioned above.</p> <pre><code>@expose('json') def get_one(self, account_id): """ Get an account :param account_id :type: str :return Account :type: dict """ try: _id = int(account_id) except ValueError: abort(status_code=400, detail='account_id must be int', passthrough='json') try: account = DBSession.query(Account).filter(Account.id == _id).one() except NoResultFound: abort(status_code=404, detail='No such user', passthrough='json') return dict( id=account.id, username=account.username, reputation=account.reputation, badges=account.badges, created=account.created, bio=account.bio ) </code></pre>
1
2016-10-17T03:13:56Z
40,094,197
<p>That's something the authentication layer does, whenever is signaled back to the user that authentication is needed the challenger will intervene and force the user to login ( <a href="http://turbogears.readthedocs.io/en/latest/turbogears/authentication.html?highlight=challenger#how-it-works-in-turbogears" rel="nofollow">http://turbogears.readthedocs.io/en/latest/turbogears/authentication.html?highlight=challenger#how-it-works-in-turbogears</a> )</p> <p>If you want to avoid that behaviour the easiest way is to use <code>tg.abort(401, passthrough=True)</code> which will skip such step, as you are talking about an API you probably want to use <code>passthrough='json'</code> which will provide a JSON response. See <a href="http://turbogears.readthedocs.io/en/latest/reference/classes.html#tg.controllers.util.abort" rel="nofollow">http://turbogears.readthedocs.io/en/latest/reference/classes.html#tg.controllers.util.abort</a></p> <p>Your response might then get caught by the <code>ErrorPageApplicationWrapper</code> depending on TurboGears version in such case make sure <code>ErrorController.document</code> has <code>@expose('json')</code> or you will face the crash you mentioned.</p>
3
2016-10-17T19:29:06Z
[ "python", "testing", "nose", "turbogears2" ]
python receive image over socket
40,077,980
<p>I'm trying to send an image over a socket - I'm capturing an image on my raspberry pi using pycam, sending to a remote machine for processing, and sending a response back.</p> <p>On the server (the pi), I'm capturing the image, transforming to an array, rearranging to a 1D array and using the tostring() method.</p> <p>On the server, the string received is not the same length. Any thoughts on what is going wrong here? Attached is the code I'm running, as well as the output on both the server and the client</p> <p>SERVER CODE:</p> <pre><code>from picamera.array import PiRGBArray from picamera import PiCamera import socket import numpy as np from time import sleep import sys camera = PiCamera() camera.resolution = (640,480) rawCapture = PiRGBArray(camera) s = socket.socket() host = 'myHost' port = 12345 s.bind((host,port)) s.listen(1) while True: c,addr = s.accept() signal = c.recv(1024) print 'received signal: ' + signal if signal == '1': camera.start_preview() sleep(2) camera.capture(rawCapture, format = 'bgr') image = rawCapture.array print np.shape(image) out = np.reshape(image,640*480*3) print out.dtype print 'sending file length: ' + str(len(out)) c.send(str(len(out))) print 'sending file' c.send(out.tostring()) print 'sent' c.close() break </code></pre> <p>CLIENT CODE:</p> <pre><code>import socket, pickle import cv2 import numpy as np host = '192.168.1.87' port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s.send('1') #while true: x = long(s.recv(1024)) rawPic = s.recv(x) print 'Received' print x print len(rawPic) type(rawPic) #EDITED TO INCLUDE DTYPE image = np.fromstring(rawPic,np.uint8) s.close() </code></pre> <p>SERVER OUTPUT:</p> <pre><code>received signal: 1 (480, 640, 3) uint8 sending file length: 921600 sending file </code></pre> <p>CLIENT OUTPUT:</p> <pre><code>Received 921600 27740 str ValueError Traceback (most recent call last) &lt;ipython-input-15-9c39eaa92454&gt; in &lt;module&gt;() ----&gt; 1 image = np.fromstring(rawPic) ValueError: string size must be a multiple of element size </code></pre> <p>I'm wondering if the issue is i'm calling tostring() on a uint8, and if the fromstring() is assuming it's a uint32? I can't figure out why the received string is so much smaller than what is sent. </p> <p><strong>EDIT</strong> It seems for some reason the server is not fully sending the file. It never prints 'sent', which it should do at completion. If I change the send line to:</p> <pre><code>c.send(str(len(out[0:100]))) print 'sending file' c.send(out[0:100].tostring()) </code></pre> <p>Everything works fine. Thoughts on what could be cutting off my sent file midway through?</p>
0
2016-10-17T03:15:25Z
40,078,395
<h1>Decoding to the Proper Type</h1> <p>When you call <code>tostring()</code>, datatype (and shape) information is lost. You must supply numpy with the datatype you expect.</p> <p>Ex:</p> <pre><code>import numpy as np image = np.random.random((50, 50)).astype(np.uint8) image_str = image.tostring() # Works image_decoded = np.fromstring(image_str, np.uint8) # Error (dtype defaults to float) image_decoded = np.fromstring(image_str) </code></pre> <h1>Recovering Shape</h1> <p>If shape is always fixed, you can do</p> <pre><code>image_with_proper_shape = np.reshape(image_decoded, (480, 640, 3)) </code></pre> <p>In the client.</p> <p>Otherwise, you'll have to include shape information in your message, to be decoded in the client.</p>
1
2016-10-17T04:13:43Z
[ "python", "sockets", "opencv", "raspberry-pi" ]
Global Variable Python
40,077,992
<pre><code>A=[] def main(): global A A=[1,2,3,4,5] b() def b(): if(len(A)&gt;0): A=[7,8,9] else: if(A[3]==4): A.remove(2) main() </code></pre> <p>This code gives error in line A.remove(2) giving reason:"UnboundLocalError: local variable 'A' referenced before assignment"</p> <p>but A list is global and for sure it has been initialized in main() function.Please explain why this is giving error?</p> <p>As A has been initialized again in b function, will this cause error?</p>
0
2016-10-17T03:17:12Z
40,078,083
<p>You must declare a variable <code>global</code> in any function that assigns to it.</p> <pre><code>def b(): global A if some_condition: A.append(6) else: A.remove(2) </code></pre> <p>Without declaring <code>A</code> <code>global</code> within the scope of <code>b()</code>, Python assumes that <code>A</code> belongs in the b() namespace. You can read it, but cannot edit it (any changes made will not persist to the <em>true</em> <code>A</code>.</p> <p>You're allowed to set A to something inside the function <code>A = ...</code> will work, but <strong>only</strong> within the scope of the function.</p> <p>If you try to mutate A inside of the function without defining A in your function's namespace, then Python will tell you that you are trying to mutate a variable outside of your purview with <code>UnboundLocalError</code></p> <p>By declaring <code>A</code> <code>global</code>, the interpreter knows that you mean to edit the global variable. </p> <p>I'm assuming that you meant for your code to look something like this (Otherwise, it runs fine)</p> <pre><code>A=[] if __name__ == '__main__': def main(): global A A=[1,2,3,4,5] b() def b(): global A if some_condition: A=[7,8,9] else: A.remove(2) print A main() print A print A </code></pre>
0
2016-10-17T03:28:54Z
[ "python", "list", "python-2.7", "python-3.x", "global-variables" ]
Global Variable Python
40,077,992
<pre><code>A=[] def main(): global A A=[1,2,3,4,5] b() def b(): if(len(A)&gt;0): A=[7,8,9] else: if(A[3]==4): A.remove(2) main() </code></pre> <p>This code gives error in line A.remove(2) giving reason:"UnboundLocalError: local variable 'A' referenced before assignment"</p> <p>but A list is global and for sure it has been initialized in main() function.Please explain why this is giving error?</p> <p>As A has been initialized again in b function, will this cause error?</p>
0
2016-10-17T03:17:12Z
40,078,154
<p>The reason you are getting this is because when you performed this assignment in your function: </p> <pre><code>A = [7, 8, 9] </code></pre> <p>The interpreter will now see <code>A</code> as a locally bound variable. So, what will happen now, looking at this condition:</p> <pre><code>if(len(A)&gt;0): </code></pre> <p>Will actually throw your first <code>UnboundLocalError</code> exception, because, due to the fact, as mentioned, you never declared <code>global A</code> in your <code>b</code> function <em>and</em> you also created a locally bound variable <code>A = [7, 8, 9]</code>, you are trying to use a local <code>A</code> before you ever declared it.</p> <p>You actually face the same issue when you try to do this:</p> <pre><code>A.remove(2) </code></pre> <p>To solve this problem with respect to your code, simply declare the <code>global A</code> back in your <code>b()</code> function.</p> <pre><code>def b(): global A if(len(A)&gt;0): A=[7,8,9] else: if(A[3]==4): A.remove(2) </code></pre> <p>However, the better, ideal and recommended way to do this is to not use global and just pass the arguments to your function</p> <pre><code>A = [1, 2, 3, 4] def main(list_of_things): # do whatever operations you want to do here b(list_of_things) def b(list_of_things): # do things with list_of_things main(A) </code></pre>
2
2016-10-17T03:38:17Z
[ "python", "list", "python-2.7", "python-3.x", "global-variables" ]
Flask restful - Exception handling traceback?
40,078,015
<p>I am using Flask Restful to build an API. I have a number of model classes with methods that may raise custom exceptions (for example: AuthFailed exception on my User model class). I am using the custom error handling, documented <a href="http://flask-restful-cn.readthedocs.io/en/0.3.4/extending.html#custom-error-handlers" rel="nofollow">here</a>, to handle this (so that when auth fails, an appropriate response is sent). So far so good. However, I notice that when the exception is raised although the correct response JSON and status is sent back, I still get a traceback which is not ideal. Usually, if I handle an error (outside of flask) with a try-except block, the except can catch the error and handle it (preventing the traceback). So what is the correct approach here? Am I misunderstanding how to use the errors feature?</p>
2
2016-10-17T03:19:43Z
40,078,263
<p>Unfortunately for you, it is handled this way "by design" of the Flask-RESTful APIs <code>errors</code> functionality. The exceptions which are thrown are logged and the corresponding response defined in the <code>errors</code> dict is returned.</p> <p>However, you can change the level of log output by modifying the log level of Flask's logger like this:</p> <pre><code>app = Flask(__name__) app.logger.setLevel(logging.CRITICAL) </code></pre> <p>I think you would actually have to set it to <code>CRITICAL</code> because these errors are still getting logged even on log level <code>ERROR</code> as far as I know.</p> <p>Furthermore, both Flask and Flask-RESTful are open-source. That being said, after looking at the code I found <a href="https://github.com/pallets/flask/blob/0.11.1/flask/app.py#L1576" rel="nofollow">the function of a Flask app that is responsible for adding the exception traceback to the log</a> (Flask version 0.11.1). Of course you could just create your own <code>App</code> class (extending the original class of Flask) which overrides this method (or a caller of it) and does something else instead. However, you should be careful when updating your Flask version if you make use of undocumented stuff like this.</p>
1
2016-10-17T03:55:14Z
[ "python", "flask", "flask-restful" ]
python pandas dataframe - can't figure out how to lookup an index given a value from a df
40,078,107
<p>I have 2 dataframes of numerical data. Given a value from one of the columns in the second df, I would like to look up the index for the value in the first df. More specifically, I would like to create a third df, which contains only index labels - using values from the second to look up its coordinates from the first.</p> <pre><code>listso = [[21,101],[22,110],[25,113],[24,112],[21,109],[28,108],[30,102],[26,106],[25,111],[24,110]] data = pd.DataFrame(listso,index=list('abcdefghij'), columns=list('AB')) rollmax = pd.DataFrame(data.rolling(center=False,window=5).max()) </code></pre> <p>So for the third df, I hope to use the values from <code>rollmax</code> and figure out which row they showed up in <code>data</code>. We can call this third df <code>indexlookup</code>.</p> <p>For example, <code>rollmax.ix['j','A'] = 30</code>, so <code>indexlookup.ix['j','A'] = 'g'</code>.</p> <p>Thanks!</p>
0
2016-10-17T03:31:45Z
40,078,203
<p>You can build a Series with the indexing the other way around:</p> <pre><code>mapA = pd.Series(data.index, index=data.A) </code></pre> <p>Then <code>mapA[rollmax.ix['j','A']]</code> gives <code>'g'</code>.</p>
1
2016-10-17T03:46:29Z
[ "python", "pandas", "indexing", "dataframe", "lookup" ]
How can I ensure a write has completed in PostgreSQL before releasing a lock?
40,078,164
<p>I have a function on a Django model that calculates a value from a PostgreSQL 9.5 database and, based on the result, determines whether to add data in another row. The function must know the value before adding the row, and future values of the calculation will be dependent on the new row.</p> <p>To enforce these rules, I'm trying to use <a href="https://www.postgresql.org/docs/9.5/static/explicit-locking.html#ADVISORY-LOCKS" rel="nofollow">advisory locks</a>. A simplified version of what I'm trying to do is below:</p> <pre class="lang-python prettyprint-override"><code>from django.db import connection, models, transaction ... def create_usage(self, num_credits): LOCK_SQL = '''SELECT pg_advisory_lock(1) FROM %s WHERE id = %s''' UNLOCK_SQL = '''SELECT pg_advisory_unlock(1) FROM %s WHERE id = %s''' cursor = connection.cursor() try: # Create an advisory lock on the instance's row print('obtaining lock for object {}'.format(id(self)) cursor.execute(LOCK_SQL, [self._meta.db_table, self.id]) print('obtained lock for object {}'.format(id(self)) # Perform some read and update when the lock is obtained with transaction.atomic(): # -- SELECT SUM(...) FROM table WHERE ... sum_credits = self.credits_used.aggregate( sum_credits=models.Sum('num_credits'))['sum_credits'] print('existing credits: {}'.format(sum_credits)) if sum_credits &lt; 100 - num_credits: print('inserting') # -- INSERT INTO table VALUE (...) self.credits_used.add(CreditUsage(num_credits=num_credits)) else: print('not inserting') finally: # Release the lock when done, or when an exception occurs print('releasing lock for object {}'.format(id(self)) cursor.execute(UNLOCK_SQL, [self._meta.db_table, self.id]) print('released lock for object {}'.format(id(self)) </code></pre> <p>(this is loosely inspired by <a href="https://www.caktusgroup.com/blog/2009/05/26/explicit-table-locking-with-postgresql-and-django/" rel="nofollow">this Caktus Group post</a>)</p> <p>I have this code running in several processes connected to the same database. In the console, the order of the <code>'obtaining'</code> and <code>'releasing'</code> print statements are what I expect them to be (i.e., no lock is obtained before some other process releases it), but the data that I get from the database doesn't appear to update like I expect. For example, when running a view (that calls <code>obj.create_usage(5)</code>) in quick succession from different threads I'll get:</p> <pre class="lang-none prettyprint-override"><code>obtaining lock for object A obtained lock for object A existing credits: 90 inserting releasing lock for object A obtaining lock for object B released lock for object A obtained lock for object B existing credits: 90 inserting obtaining lock for object C releasing lock for object B released lock for object B obtained lock for object C existing credits: 90 inserting releasing lock for object C released lock for object C obtaining lock for object D obtained lock for object D existing credits: 95 obtaining lock for object E inserting releasing lock for object D obtained lock for object E released lock for object D existing credits: 100 not inserting releasing lock for object E released lock for object E </code></pre> <p><em>NOTE: I used <code>A</code>, <code>B</code>, <code>C</code>, <code>D</code>, <code>E</code> instead of the objects' numeric IDs for readability.</em></p> <p>Why wouldn't the writes register before the reads, given the DB locks? I tried without the <code>transaction.atomic</code> at first, but added it thinking that it would make a difference. It did not. Is there a way to enforce the insert to <em><strong>really</strong></em> complete before releasing the advisory lock?</p>
2
2016-10-17T03:39:47Z
40,084,268
<p>I assume it's because of Django's (or middleware's) transaction management , I'm not completely sure, it's better to test it on your code, but it looks for me like: when you try to acquire a lock, Django might start a new transaction, so when you're actually getting lock at <code>cursor.execute(LOCK_SQL, [self._meta.db_table, self.id])</code> you are already isolated. </p> <p>While you waiting for lock, another process (with acquired lock) does insert to the database and commits its transaction, but the first process won't see this change when it actually acquires the lock, because transaction has started before.</p> <p>You could check your application settings for <code>ATOMIC_REQUESTS</code> or any middleware that could enable transactions per request.</p>
1
2016-10-17T10:40:33Z
[ "python", "django", "postgresql", "transactions", "locking" ]
Subtracting two cloumns in pandas with lists to create a cummalative column
40,078,181
<p>dataframe conists of set x which is a universal set and subset columm contains of some subsets. I want to choose the subsets with the highest ratios until I covered the full set x. uncovered = setx - subset This is how my dataframe look like in pandas :</p> <pre><code> ratio set x subset uncovered 2 2.00 [1, 3, 6, 8, 9, 0, 7] [8, 3, 6, 1] [0, 9, 7] 0 1.50 [1, 3, 6, 8, 9, 0, 7] [1, 3, 6] [0, 8, 9, 7] 1 1.00 [1, 3, 6, 8, 9, 0, 7] [9, 0] [8, 1, 3, 6, 7] 3 0.75 [1, 3, 6, 8, 9, 0, 7] [1, 3, 7] [0, 8, 6, 9] </code></pre> <p>I want to create another column with the subtraction of set x with cummalative of uncovered column until i get a empty list. </p> <p>I tried the below code</p> <pre><code>p['tt']=list(p['set x']-p['subset']) </code></pre> <p>Error Message :</p> <blockquote> <p>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Applications/anaconda/lib/python3.5/site-packages/pandas/core/ops.py in na_op(x, y) 581 result = expressions.evaluate(op, str_rep, x, y, --> 582 raise_on_error=True, **eval_kwargs) 583 except TypeError:</p> <p>/Applications/anaconda/lib/python3.5/site-packages/pandas/computation/expressions.py in evaluate(op, op_str, a, b, raise_on_error, use_numexpr, **eval_kwargs) 208 return _evaluate(op, op_str, a, b, raise_on_error=raise_on_error, --> 209 **eval_kwargs) 210 return _evaluate_standard(op, op_str, a, b, raise_on_error=raise_on_error)</p> <p>/Applications/anaconda/lib/python3.5/site-packages/pandas/computation/expressions.py in _evaluate_numexpr(op, op_str, a, b, raise_on_error, truediv, reversed, **eval_kwargs) 119 if result is None: --> 120 result = _evaluate_standard(op, op_str, a, b, raise_on_error) 121 </p> <p>/Applications/anaconda/lib/python3.5/site-packages/pandas/computation/expressions.py in _evaluate_standard(op, op_str, a, b, raise_on_error, **eval_kwargs) 61 _store_test_result(False) ---> 62 return op(a, b) 63 </p> <p>TypeError: unsupported operand type(s) for -: 'list' and 'list'</p> <p>During handling of the above exception, another exception occurred:</p> <p>TypeError Traceback (most recent call last) in () ----> 1 p['tt']=list(p['set x']-p['subset'])</p> <p>/Applications/anaconda/lib/python3.5/site-packages/pandas/core/ops.py in wrapper(left, right, name, na_op) 639 rvalues = algos.take_1d(rvalues, ridx) 640 --> 641 arr = na_op(lvalues, rvalues) 642 643 return left._constructor(wrap_results(arr), index=index,</p> <p>/Applications/anaconda/lib/python3.5/site-packages/pandas/core/ops.py in na_op(x, y) 586 result = np.empty(x.size, dtype=dtype) 587 mask = notnull(x) &amp; notnull(y) --> 588 result[mask] = op(x[mask], _values_from_object(y[mask])) 589 elif isinstance(x, np.ndarray): 590 result = np.empty(len(x), dtype=x.dtype)</p> <p>TypeError: unsupported operand type(s) for -: 'list' and 'list'</p> </blockquote>
0
2016-10-17T03:42:28Z
40,079,246
<p>This should work for you:</p> <pre><code>import pandas as pd # ratio set x subset uncovered # 2 2.00 [1, 3, 6, 8, 9, 0, 7] [8, 3, 6, 1] [0, 9, 7] # 0 1.50 [1, 3, 6, 8, 9, 0, 7] [1, 3, 6] [0, 8, 9, 7] # 1 1.00 [1, 3, 6, 8, 9, 0, 7] [9, 0] [8, 1, 3, 6, 7] # 3 0.75 [1, 3, 6, 8, 9, 0, 7] [1, 3, 7] [0, 8, 6, 9] p = pd.DataFrame( [ {'set x': [1, 3, 6, 8, 9, 0, 7], 'subset': [1, 3, 6]}, {'set x': [1, 3, 6, 8, 9, 0, 7], 'subset': [9, 0]}, {'set x': [1, 3, 6, 8, 9, 0, 7], 'subset': [8, 3, 6, 1]}, {'set x': [1, 3, 6, 8, 9, 0, 7], 'subset': [1, 3, 7]}, ]) def set_operation(x): return list(set(x['set x']) - set(x['subset'])) p['tt'] = p.apply(set_operation, axis=1) </code></pre> <p>Result is:</p> <pre><code> set x subset tt 0 [1, 3, 6, 8, 9, 0, 7] [1, 3, 6] [0, 8, 9, 7] 1 [1, 3, 6, 8, 9, 0, 7] [9, 0] [8, 1, 3, 6, 7] 2 [1, 3, 6, 8, 9, 0, 7] [8, 3, 6, 1] [0, 9, 7] 3 [1, 3, 6, 8, 9, 0, 7] [1, 3, 7] [0, 8, 9, 6] </code></pre>
0
2016-10-17T05:45:10Z
[ "python", "pandas" ]
Not sure how to fix this error Luhn Algorithm PYTHON
40,078,265
<p>Alright, So I think i'm almost there, my first/second part work perfect when they are on their own, but i'm having trouble combining the two this is what I have so far I'm thinking the error is in the last bit, sorry, im new with python, so i'm hoping to get the hang of it soon</p> <p>Edit3: i've gotten it to work (with the help of you guys) but now when i input 3782822463100050, its suppose to be invalid american express, but its showing up as valid american express...</p> <p>Edit1: Okay, for example when i post <code>0378282246310005</code> (a fake american express) it says </p> <pre><code>Traceback (most recent call last): File "C:/Users/Nat/Desktop/attempt.py", line 39, in &lt;module&gt; print((cardType)+"Valid") NameError: name 'cardType' is not defined </code></pre> <p>but when i insert a random number like <code>0378282246310005</code> it works</p> <p>Please enter your credit card number 0378282246310005</p> <p>We do not accept that kind of card</p> <p>Edit2: in the end you should be able to type in a credit card number and it'll say "Your "type of credit card" is valid (or invalid)</p> <p>or say that "we dont support the card"</p> <pre><code>#GET number that will be tested CreditNumber = input("Please enter your credit card number") #SET total to 0 total=0 #LOOP backwards from the last digit to the first, one at a time CreditCount = len(CreditNumber) for i in range(0, CreditCount, -1): LastDigit=CreditCard[i] #IF the position of the current digit is even THEN DOUBLE the value of the current digit if i % 2 ==0: LastDigit=LastDigit*2 #IF the doubled value is more than 9 THEN SUM the digits of the doubled value if LastDigit&gt;9: LastDigit=LastDigit/10+LastDigit%10 total=total + digit #Figure out what credit card the user has if ( CreditNumber[0:2]=="34" or CreditNumber[ 0:2 ] == "37"): cardType = "Your American Express is" elif ( CreditNumber[ 0 :4 ] =="6011"): cardType = "Your Discover card is" elif ( CreditNumber[0 :2 ] in [ "51", "52", "53", "54", "55"]): cardType = "Your Mastercard is" elif ( CreditNumber == "4" ): cardType = "Your VISA card is" else: print( "We do not accept that kind of card") if total % 10 == 0: print((cardType)+"Valid") else: print((cardType)+"Invalid") </code></pre>
2
2016-10-17T03:55:42Z
40,078,374
<p>in the control statements under the comment <code>#Figure out what credit card the user has</code>, the variable <code>cardType</code> is defined in every branch except <code>else</code>. Since the name was never defined outside the scope of the control statement, the interpreter gives you a NameError when you try to access the variable when the code followed the else branch of the if statement.</p> <p>to fix this you can do a couple of different things. you can create a a special value for <code>cardType</code> when <code>CardNumber</code> is invalid and check for it in the next control statement:</p> <pre><code>if ...: ... else: cardType = "some special value" if cardType == "some special value": ... </code></pre> <p>or you could use a try/except statement:</p> <pre><code>try: print(cardType) except NameError: print("invalid card number") </code></pre> <p><strong>EDIT</strong>: Also you should note that currently the <code>total</code> variable will always be <code>0</code> as the for loop doesn't actually run. If you want to decrement a range, the first argument should be greater than the second, or the range function will just create an empty list.</p>
1
2016-10-17T04:10:18Z
[ "python", "luhn" ]
Pandas dataframe output formatting
40,078,447
<p>I'm importing a trade list and trying to consolidate it into a position file with summed quantities and average prices. I'm grouping based on (ticker, type, expiration and strike). Two questions:</p> <ol> <li>Output has the index group (ticker, type, expiration and strike) in the first column. How can I change this so that each index column outputs to its own column so the output csv is formatted the same way as the input data?</li> <li>I currently force the stock trades to have values ("1") because leaving the cells blank will cause an error, but this adds bad data since "1" is not meaningful. Is there a way to preserve "" without causing a problem?</li> </ol> <p>Dataframe:</p> <pre><code> GM stock 1 1 32 100 AAPL call 201612 120 3.5 1000 AAPL call 201612 120 3.25 1000 AAPL call 201611 120 2.5 2000 AAPL put 201612 115 2.5 500 AAPL stock 1 1 117 100 </code></pre> <p>Code:</p> <pre><code> import pandas as pd import numpy as np df = pd.read_csv(input_file, index_col=['ticker', 'type', 'expiration', 'strike'], names=['ticker', 'type', 'expiration', 'strike', 'price', 'quantity']) df_output = df.groupy(df.index).agg({'price':np.mean, 'quantity':np.sum}) df_output.to_csv(output_file, sep=',') </code></pre> <p>csv output comes out in this format:</p> <pre><code>(ticker, type, expiration, strike), price, quantity </code></pre> <p>desired format:</p> <pre><code>ticker, type, expiration, strike, price, quantity </code></pre>
0
2016-10-17T04:21:30Z
40,078,574
<p>For the first question, you should use groupby(df.index_col) instead of groupby(df.index)</p> <p>For the second, I am not sure why you couldn't preserve "", is that numeric?</p> <p>I mock some data like below:</p> <pre><code>import pandas as pd import numpy as np d = [ {'ticker':'A', 'type':'M', 'strike':'','price':32}, {'ticker':'B', 'type':'F', 'strike':100,'price':3.5}, {'ticker':'C', 'type':'F', 'strike':'', 'price':2.5} ] df = pd.DataFrame(d) print df #dgroup = df.groupby(['ticker', 'type']).agg({'price':np.mean}) df.index_col = ['ticker', 'type', 'strike'] dgroup = df.groupby(df.index_col).agg({'price':np.mean}) #dgroup = df.groupby(df.index).agg({'price':np.mean}) print dgroup print type(dgroup) dgroup.to_csv('check.csv') </code></pre> <p>output in check.csv:</p> <pre><code>ticker,type,strike,price A,M,,32.0 B,F,100,3.5 C,F,,2.5 </code></pre>
0
2016-10-17T04:37:06Z
[ "python", "pandas", "format", "export-to-csv" ]
Combine String in a Dictionary with Similar Key
40,078,508
<p>I am trying to create a new Dictionary based on 3 others dictionary in my python data processing.</p> <p>I have 3 Dictionaries, each with similar ID representing different section in the document.</p> <p>For example</p> <pre><code>dict1 = {'001': 'Dog', '002': 'Cat', '003': 'Mouse'} dict2 = {'001': 'Dog2', '002': 'Cat2', '003': 'Mouse2'} dict3 = {'001': 'Dog3', '002': 'Cat3', '003': 'Mouse3'} </code></pre> <p>I wanted to combine all the values of similar key, therefore my desire output would like similar to this.</p> <pre><code>combineDict = {'001' : 'Dog Dog2 Dog3', '002' : 'Cat Cat2 Cat3', '003' : 'Mouse Mouse2 Mouse3'} </code></pre> <p>I did this</p> <pre><code>combineDict = {} for k in dict1.keys(): combineDict[k] = dict1[k] + " " + dict2[k] + " " + dict3[k] </code></pre> <p>However, the method above is super slow when dealing with large amount of text.</p> <p>Is there anyway to write this function professionally to give the same result and lowered down the time it takes to process.</p> <p>Thank you very much :)</p>
0
2016-10-17T04:29:21Z
40,078,684
<p>To keep in line with your current approach, and specifically binding the following solution to the fact that you always have three equally length dictionaries, the approach is as such: </p> <p>Iterate using one of the dictionaries, and create a new dictionary that will hold the values as a space separated string. The easiest way to do this is to collect them in a <code>list</code> and then use <code>" ".join</code>, which will give you the space separated list:</p> <pre><code>dict1 = {'001': 'Dog', '002': 'Cat', '003': 'Mouse'} dict2 = {'001': 'Dog2', '002': 'Cat2', '003': 'Mouse2'} dict3 = {'001': 'Dog3', '002': 'Cat3', '003': 'Mouse3'} new_dict = {} for key in dict1: new_dict[key] = " ".join([dict1[key], dict2[key], dict3[key]]) </code></pre> <p>Output:</p> <pre><code>{'001': 'Dog Dog2 Dog3', '003': 'Mouse Mouse2 Mouse3', '002': 'Cat Cat2 Cat3'} </code></pre> <p>Or simply as a dictionary comprehension:</p> <pre><code>res = {k: " ".join([dict1[key], dict2[key], dict3[key]]) for k in dict1} </code></pre>
1
2016-10-17T04:51:37Z
[ "python" ]
docopt fails with docopt.DocoptLanguageError: unmatched '['
40,078,516
<p>Why does this code fail with the following exception?</p> <pre><code>"""my_program - for doing awesome stuff Usage: my_program [--foo] Options: --foo - this will do foo """ import docopt args = docopt.docopt(doc=__doc__) </code></pre> <p>Exception:</p> <pre><code>Traceback (most recent call last): File "/tmp/post.py", line 10, in &lt;module&gt; args = docopt.docopt(doc=__doc__) File "/Users/rbednark/.virtualenvs/docopt-python2/lib/python3.5/site-packages/docopt.py", line 560, in docopt pattern = parse_pattern(formal_usage(DocoptExit.usage), options) File "/Users/rbednark/.virtualenvs/docopt-python2/lib/python3.5/site-packages/docopt.py", line 373, in parse_pattern result = parse_expr(tokens, options) File "/Users/rbednark/.virtualenvs/docopt-python2/lib/python3.5/site-packages/docopt.py", line 381, in parse_expr seq = parse_seq(tokens, options) File "/Users/rbednark/.virtualenvs/docopt-python2/lib/python3.5/site-packages/docopt.py", line 396, in parse_seq atom = parse_atom(tokens, options) File "/Users/rbednark/.virtualenvs/docopt-python2/lib/python3.5/site-packages/docopt.py", line 413, in parse_atom result = pattern(*parse_expr(tokens, options)) File "/Users/rbednark/.virtualenvs/docopt-python2/lib/python3.5/site-packages/docopt.py", line 381, in parse_expr seq = parse_seq(tokens, options) File "/Users/rbednark/.virtualenvs/docopt-python2/lib/python3.5/site-packages/docopt.py", line 396, in parse_seq atom = parse_atom(tokens, options) File "/Users/rbednark/.virtualenvs/docopt-python2/lib/python3.5/site-packages/docopt.py", line 415, in parse_atom raise tokens.error("unmatched '%s'" % token) docopt.DocoptLanguageError: unmatched '[' </code></pre> <p>docopt version: <code>0.6.2</code><br> python versions: <code>2.7.10</code>, <code>3.5.1</code></p>
1
2016-10-17T04:30:22Z
40,078,517
<p>It fails because of only a single space after <code>--foo</code> on this line:</p> <pre><code> --foo - this will do foo </code></pre> <p>Fix it by adding another space after <code>--foo</code>:</p> <pre><code> --foo - this will do foo </code></pre> <p><br/> <br/> Per <a href="https://docopt.readthedocs.io/en/latest/#option-descriptions-format" rel="nofollow">the documentation:</a></p> <blockquote> <p>Use two spaces to separate options with their informal description:</p> </blockquote> <pre><code>--verbose More text. # BAD, will be treated as if verbose option had # an argument "More", so use 2 spaces instead -q Quit. # GOOD -o FILE Output file. # GOOD --stdout Use stdout. # GOOD, 2 spaces </code></pre> <p><br/> <br/> Additional reference: <a href="https://github.com/docopt/docopt" rel="nofollow">docopt source code</a></p>
2
2016-10-17T04:30:22Z
[ "python", "docopt" ]
How to get the key value output from RDD in pyspark
40,078,530
<p>Following is the RDD:</p> <pre><code>[(8, [u'darkness']), (2, [u'in', u'of', u'of', u'of']), (4, [u'book', u'form', u'void', u'upon', u'face', u'deep', u'upon', u'face'])] </code></pre> <p>How do i print the keys and the value length for the above.</p> <p>The output for above should be: (key, no of words in the list) </p> <blockquote> <p>(8,1) (2,4) (4,8)</p> </blockquote>
-1
2016-10-17T04:31:53Z
40,083,820
<p>You can use a <code>map</code> function to create a tuple of the key and number of words in the list:</p> <pre><code>data = sc.parallelize([(8, [u'darkness']), (2, [u'in', u'of', u'of', u'of']), (4, [u'book', u'form', u'void', u'upon', u'face', u'deep', u'upon', u'face'])]) data.map(lambda x:tuple([x[0],len(x[1])])).collect() </code></pre>
0
2016-10-17T10:19:44Z
[ "python", "pyspark", "rdd" ]
Python - Why are some test cases failing?
40,078,532
<p>So I'm working through problems on hackerrank, I am a beginner in python.</p> <p>The information about what I'm trying to dois found here: <a href="https://www.hackerrank.com/challenges/compare-the-triplets?h_r=next-challenge&amp;h_v=zen" rel="nofollow">https://www.hackerrank.com/challenges/compare-the-triplets?h_r=next-challenge&amp;h_v=zen</a></p> <pre><code>a0,a1,a2 = input().strip().split(' ') a0,a1,a2 = [int(a0),int(a1),int(a2)] b0,b1,b2 = input().strip().split(' ') b0,b1,b2 = [int(b0),int(b1),int(b2)] a1 = 0 b1 = 0 lst1 = a0,a1,a2 lst2 = b0,b1,b2 for x, y in zip(lst1, lst2): if x &gt; y: a1 += 1 if x &lt;y: b1 += 1 else: pass print(a1, b1) </code></pre> <p>So this works perfectly well.</p> <p>However, in one of the test cases, the input is </p> <pre><code>6 8 12 7 9 15 </code></pre> <p>and output should be </p> <pre><code>0 3 </code></pre> <p><strong>However my code keeps failing it. Why is this so?</strong></p>
4
2016-10-17T04:32:08Z
40,078,682
<p>Maybe you need to change varibale name of a1,b1 in your code to some other names.</p> <pre><code>.... a1 = 0 b1 = 0 ... </code></pre> <p>They will remove input a1/b1 as the same name, I don't see why that needed :)</p> <pre><code>a0,a1,a2 = [int(a0),int(a1),int(a2)] b0,b1,b2 = [int(b0),int(b1),int(b2)] </code></pre>
3
2016-10-17T04:51:15Z
[ "python" ]
Python - Why are some test cases failing?
40,078,532
<p>So I'm working through problems on hackerrank, I am a beginner in python.</p> <p>The information about what I'm trying to dois found here: <a href="https://www.hackerrank.com/challenges/compare-the-triplets?h_r=next-challenge&amp;h_v=zen" rel="nofollow">https://www.hackerrank.com/challenges/compare-the-triplets?h_r=next-challenge&amp;h_v=zen</a></p> <pre><code>a0,a1,a2 = input().strip().split(' ') a0,a1,a2 = [int(a0),int(a1),int(a2)] b0,b1,b2 = input().strip().split(' ') b0,b1,b2 = [int(b0),int(b1),int(b2)] a1 = 0 b1 = 0 lst1 = a0,a1,a2 lst2 = b0,b1,b2 for x, y in zip(lst1, lst2): if x &gt; y: a1 += 1 if x &lt;y: b1 += 1 else: pass print(a1, b1) </code></pre> <p>So this works perfectly well.</p> <p>However, in one of the test cases, the input is </p> <pre><code>6 8 12 7 9 15 </code></pre> <p>and output should be </p> <pre><code>0 3 </code></pre> <p><strong>However my code keeps failing it. Why is this so?</strong></p>
4
2016-10-17T04:32:08Z
40,078,722
<p>I find 2 issues in this. 1. variable names are same. Notice a1 in list and and a1 as a separate Variable. 2. Instead of print you can use '{0} {1}'.format(a1,b1) Also I would suggest using raw_input() instead of input(), that will help your input treated as a string.</p>
4
2016-10-17T04:56:31Z
[ "python" ]
Webscraping with Python ( beginner)
40,078,536
<p>I'm doing the first example of the webscrapping tutorial from the book "Automate the Boring Tasks with Python". The project consists of typing a search term on the command line and have my computer automatically open a browser with all the top search results in new tabs</p> <p>It mentions that I need to locate the </p> <pre><code>&lt;h3 class="r"&gt; </code></pre> <p>element from the page source, which are the links to each search results. The r class is used only for search result links.</p> <p>But the problem is that I can't find it anywhere, even using Chrome Devtools. Any help as to where is it would be greatly appreciated.</p> <p>Note: Just for reference this is the complete program as seen on the book.</p> <pre><code># lucky.py - Opens several Google search results. import requests, sys, webbrowser, bs4 print('Googling..') # display text while downloading the Google page res= requests.get('http://google.com/search?q=' + ' '.join(sys.argv[1:])) res.raise_for_status() #Retrieve top searh result links. soup = bs4.BeautifulSoup(res.text) #Open a browser tab for each result. linkElems = soup.select('.r a') numOpen = min(5,len(linkElems)) for i in range(numOpen): webbrowser.open('http://google.com' + linkElems[i].get('href')) </code></pre>
2
2016-10-17T04:32:19Z
40,078,640
<p>This will work for you : </p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; from lxml import html &gt;&gt;&gt; r = requests.get("https://www.google.co.uk/search?q=how+to+do+web+scraping&amp;num=10") &gt;&gt;&gt; source = html.fromstring((r.text).encode('utf-8')) &gt;&gt;&gt; links = source.xpath('//h3[@class="r"]//a//@href') &gt;&gt;&gt; for link in links: print link.replace("/url?q=","").split("&amp;sa=")[0] </code></pre> <p>Output :</p> <pre><code>http://newcoder.io/scrape/intro/ https://www.analyticsvidhya.com/blog/2015/10/beginner-guide-web-scraping-beautiful-soup-python/ http://docs.python-guide.org/en/latest/scenarios/scrape/ http://webscraper.io/ https://blog.hartleybrody.com/web-scraping/ https://first-web-scraper.readthedocs.io/ https://www.youtube.com/watch%3Fv%3DE7wB__M9fdw http://www.gregreda.com/2013/03/03/web-scraping-101-with-python/ http://analystcave.com/web-scraping-tutorial/ https://en.wikipedia.org/wiki/Web_scraping </code></pre> <p><strong>Note</strong>: <em>I am using Python 2.7.X , for Python 3.X you just have to surround the print output like this</em> <strong>print (link.replace("/url?q=","").split("&amp;sa=")[0])</strong></p>
1
2016-10-17T04:45:49Z
[ "python", "web-scraping" ]
Print string without a certain word?
40,078,569
<p>So, if I have code like this:</p> <pre><code>a = ["a", "b", "c", "null"] print a </code></pre> <p>The number of <code>"null"</code>s varies in the output quite a lot for some reason. How could I print <code>a</code> without the <code>"null"</code>?</p>
0
2016-10-17T04:36:22Z
40,078,597
<p>A simple way to filter your list is using list comprehension:</p> <pre><code>print([x for x in a if x != "null"]) </code></pre>
2
2016-10-17T04:39:56Z
[ "python", "python-2.7", "printing" ]
Print string without a certain word?
40,078,569
<p>So, if I have code like this:</p> <pre><code>a = ["a", "b", "c", "null"] print a </code></pre> <p>The number of <code>"null"</code>s varies in the output quite a lot for some reason. How could I print <code>a</code> without the <code>"null"</code>?</p>
0
2016-10-17T04:36:22Z
40,078,600
<p>Just iterate through your list to print out everything that does not equal to "null"</p> <pre><code>a = ["a", "b", "c", "null"] for data in a: if data != "null": print(data) </code></pre> <p>If you were looking to filter out data you don't want in your data structure, however, then, the easiest way to do this is to do this in a list comprehension that will remove unwanted "null"</p> <pre><code>res = [data for data in a if data != "null"] </code></pre>
2
2016-10-17T04:40:22Z
[ "python", "python-2.7", "printing" ]
Print string without a certain word?
40,078,569
<p>So, if I have code like this:</p> <pre><code>a = ["a", "b", "c", "null"] print a </code></pre> <p>The number of <code>"null"</code>s varies in the output quite a lot for some reason. How could I print <code>a</code> without the <code>"null"</code>?</p>
0
2016-10-17T04:36:22Z
40,078,802
<p>@m1ksu , I just saw above you asking for a function : see below</p> <pre><code>a = ["a", "b", "c", "null"] def remove_null(self): return [x for x in self if x != "null"] asd = remove_null(a) print asd </code></pre> <p>output </p> <pre><code>['a', 'b', 'c'] </code></pre>
0
2016-10-17T05:04:55Z
[ "python", "python-2.7", "printing" ]
Print string without a certain word?
40,078,569
<p>So, if I have code like this:</p> <pre><code>a = ["a", "b", "c", "null"] print a </code></pre> <p>The number of <code>"null"</code>s varies in the output quite a lot for some reason. How could I print <code>a</code> without the <code>"null"</code>?</p>
0
2016-10-17T04:36:22Z
40,081,791
<p>I get the impression that you wish to convert the list to a string with a function and display each data element on a separate line without null being included. So, here's what I suggest:</p> <pre><code># remove null and convert list to string with function # and display results on separate lines a = ["a", "b", "c", "null"] def str(A): a = [data for data in A if data != "null"] aSTR = '\n'.join(a) return aSTR print str(a) </code></pre> <p>Run code <a href="http://www.tutorialspoint.com/execute_python_online.php?PID=0Bw_CjBb95KQMRllvRExHa3pjM2M" rel="nofollow">here</a></p>
0
2016-10-17T08:35:16Z
[ "python", "python-2.7", "printing" ]
Grouping by almost similar strings
40,078,596
<p>I have a dataset with city names and counts of crimes. The data is dirty such that a name of a city for example 'new york', is written as 'newyork', 'new york us', 'new york city', 'manhattan new york' etc. How can I group all these cities together and sum their crimes?</p> <p>I tried the 'difflib' package in python that matches strings and gives you a score. It doesn't work well. I also tried the geocode package in python. It has limits on number of times you can access the api, and doesnt work well either. Any suggestions? </p>
1
2016-10-17T04:39:28Z
40,078,773
<p>Maybe this might help:</p> <p><a href="http://chairnerd.seatgeek.com/fuzzywuzzy-fuzzy-string-matching-in-python/" rel="nofollow">http://chairnerd.seatgeek.com/fuzzywuzzy-fuzzy-string-matching-in-python/</a></p> <p>Another way: if a string contains 'new' and 'york', then label it 'new york city'. </p> <p>Another way: Create a dictionary of all the possible fuzzy words that occur and label each of them manually. And use that labelling to replace each of these fuzzy words with the label.</p>
1
2016-10-17T05:01:46Z
[ "python", "pandas" ]
Grouping by almost similar strings
40,078,596
<p>I have a dataset with city names and counts of crimes. The data is dirty such that a name of a city for example 'new york', is written as 'newyork', 'new york us', 'new york city', 'manhattan new york' etc. How can I group all these cities together and sum their crimes?</p> <p>I tried the 'difflib' package in python that matches strings and gives you a score. It doesn't work well. I also tried the geocode package in python. It has limits on number of times you can access the api, and doesnt work well either. Any suggestions? </p>
1
2016-10-17T04:39:28Z
40,080,818
<p>Another approach is to go through each entry and strip the white space and see if they contain a base city name. For example 'newyork', 'new york us', 'new york city', 'manhattan new york' when stripped of white space would be 'newyork', 'newyorkus', 'newyorkcity', 'manhattannewyork', which all contain the word 'newyork'.</p> <p>There are two approaches with this method, you can go through and replace the all the 'new york' strings with ones that have no white space and are just 'newyork' or you can just check them on the fly.</p> <p>I wrote down an example below, but since I don't know how your data is formatted, I'm not sure how helpful it is.</p> <pre><code>crime_count = 0 for (key, val) in dataset: if 'newyork' in key.replace(" ", ""): crime_count = crime_count + val </code></pre>
0
2016-10-17T07:36:22Z
[ "python", "pandas" ]
Finding and extracting multiple substrings in a string?
40,078,607
<p>After looking <a href="http://stackoverflow.com/questions/11886815/pull-a-specific-substring-out-of-a-line-in-python">a</a> <a href="http://gis.stackexchange.com/questions/4748/python-question-how-do-i-extract-a-part-of-a-string">few</a> <a href="http://stackoverflow.com/questions/6633678/finding-words-after-keyword-in-python">similar</a> <a href="http://stackoverflow.com/questions/11472442/grab-first-word-in-string-after-id">questions</a>, I have not been able to successfully implement a substring split on my data. For my specific case, I have a bunch of strings, and each string has a substring I need to extract. The strings are grouped together in a list and my data is NBA positions. I need to pull out the positions (either 'PG', 'SG', 'SF', 'PF', or 'C') from each string. Some strings will have more than one position. Here is the data.</p> <pre><code>text = ['Chi\xa0SG, SF\xa0\xa0DTD','Cle\xa0PF'] </code></pre> <p>The code should ideally look at the first string, <code>'Chi\xa0SG, SF\xa0\xa0DTD'</code>, and return <code>['SG','SF']</code> the two positions. The code should look at the second string and return <code>['PF']</code>.</p>
1
2016-10-17T04:41:15Z
40,078,659
<p>Leverage (zero width) lookarounds:</p> <pre><code>(?&lt;!\w)PG|SG|SF|PF|C(?!\w) </code></pre> <ul> <li><p><code>(?&lt;!\w)</code> is zero width negative lookbehind pattern, making sure the desired match is not preceded by any alphanumerics</p></li> <li><p><code>PG|SG|SF|PF|C</code> matches any of the desired patterns</p></li> <li><p><code>(?!\w)</code> is zero width negative lookahead pattern making sure the match is not followed by any alphanumerics</p></li> </ul> <p><strong>Example:</strong></p> <pre><code>In [7]: s = 'Chi\xa0SG, SF\xa0\xa0DTD' In [8]: re.findall(r'(?&lt;!\w)PG|SG|SF|PF|C(?!\w)', s) Out[8]: ['SG', 'SF'] </code></pre>
2
2016-10-17T04:48:29Z
[ "python", "regex", "string", "substring" ]
Finding and extracting multiple substrings in a string?
40,078,607
<p>After looking <a href="http://stackoverflow.com/questions/11886815/pull-a-specific-substring-out-of-a-line-in-python">a</a> <a href="http://gis.stackexchange.com/questions/4748/python-question-how-do-i-extract-a-part-of-a-string">few</a> <a href="http://stackoverflow.com/questions/6633678/finding-words-after-keyword-in-python">similar</a> <a href="http://stackoverflow.com/questions/11472442/grab-first-word-in-string-after-id">questions</a>, I have not been able to successfully implement a substring split on my data. For my specific case, I have a bunch of strings, and each string has a substring I need to extract. The strings are grouped together in a list and my data is NBA positions. I need to pull out the positions (either 'PG', 'SG', 'SF', 'PF', or 'C') from each string. Some strings will have more than one position. Here is the data.</p> <pre><code>text = ['Chi\xa0SG, SF\xa0\xa0DTD','Cle\xa0PF'] </code></pre> <p>The code should ideally look at the first string, <code>'Chi\xa0SG, SF\xa0\xa0DTD'</code>, and return <code>['SG','SF']</code> the two positions. The code should look at the second string and return <code>['PF']</code>.</p>
1
2016-10-17T04:41:15Z
40,078,687
<p>heemayl's response is the most correct, but you could probably get away with splitting on commas and keeping only the last two (or in the case of 'C', the last) characters in each substring.</p> <pre><code>s = 'Chi\xa0SG, SF\xa0\xa0DTD' fin = list(map(lambda x: x[-2:] if x != 'C' else x[-1:],s.split(','))) </code></pre> <p>I can't test this at the moment as I'm on a chromebook but it should work.</p>
0
2016-10-17T04:52:03Z
[ "python", "regex", "string", "substring" ]
Playing video in Gtk in a window with a menubar
40,078,718
<p>I have created a video player in Gtk3 using Gstreamer in Python3. It works except when I add a GtkMenuBar (place 2). It will then either show a black screen, or fail with an exception. The exception references the <code>XInitThreads</code>, which I am calling (Place 1) (I took this from the pitivi project) but this does not seem to make a diffrence.</p> <p>Question: How do I make this work?</p> <p>Other things I would like to know: </p> <ol> <li>Why would the menubar break this?</li> <li>This will clearly break on anything not X, is there some prebuilt component the abstracts this logic and is crossplatform that I am missing?</li> </ol> <p>System:</p> <ul> <li>python3</li> <li>Gtk3</li> <li>Ubuntu 16.04</li> </ul> <p>The exception:</p> <pre><code>[xcb] Unknown request in queue while dequeuing [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called [xcb] Aborting, sorry about that. python3: ../../src/xcb_io.c:179: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed. </code></pre> <p>The code (in as small a form as possible to demonstrate the concept): </p> <pre><code>import gi gi.require_version('Gtk', '3.0') gi.require_version('Gst', '1.0') gi.require_version('GstVideo', '1.0') from gi.repository import Gtk, xlib from gi.repository import Gst, Gdk, GdkX11, GstVideo Gst.init(None) Gst.init_check(None) # Place 1 from ctypes import cdll x11 = cdll.LoadLibrary('libX11.so') x11.XInitThreads() # [xcb] Unknown request in queue while dequeuing # [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called # [xcb] Aborting, sorry about that. # python3: ../../src/xcb_io.c:179: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed. # (foo.py:31933): Gdk-WARNING **: foo.py: Fatal IO error 11 (Resource temporarily unavailable) on X server :1. class PipelineManager(object): def __init__(self, window, pipeline): self.window = window if isinstance(pipeline, str): pipeline = Gst.parse_launch(pipeline) self.pipeline = pipeline bus = pipeline.get_bus() bus.set_sync_handler(self.bus_callback) pipeline.set_state(Gst.State.PLAYING) def bus_callback(self, bus, message): if message.type is Gst.MessageType.ELEMENT: if GstVideo.is_video_overlay_prepare_window_handle_message(message): Gdk.threads_enter() Gdk.Display.get_default().sync() win = self.window.get_property('window') if isinstance(win, GdkX11.X11Window): message.src.set_window_handle(win.get_xid()) else: print('Nope') Gdk.threads_leave() return Gst.BusSyncReply.PASS pipeline = Gst.parse_launch('videotestsrc ! xvimagesink sync=false') window = Gtk.ApplicationWindow() header_bar = Gtk.HeaderBar() header_bar.set_show_close_button(True) # window.set_titlebar(header_bar) # Place 2 drawing_area = Gtk.DrawingArea() drawing_area.connect('realize', lambda widget: PipelineManager(widget, pipeline)) window.add(drawing_area) window.show_all() def on_destroy(win): try: Gtk.main_quit() except KeyboardInterrupt: pass window.connect('destroy', on_destroy) Gtk.main() </code></pre>
2
2016-10-17T04:56:23Z
40,099,230
<p>When searching through documentation on a separate issue, I came across a reference to the <code>gtksink</code> widget. This seems to be the correct way to put video in a gtk window, but unfortunately none of the tutorials on this use it.</p> <p>Using the <code>gtksink</code> widget fixes all the problems and greatly reduces code complexity. </p> <p>The revised code:</p> <pre><code>from pprint import pprint import gi gi.require_version('Gtk', '3.0') gi.require_version('Gst', '1.0') gi.require_version('GstVideo', '1.0') from gi.repository import Gtk, Gst Gst.init(None) Gst.init_check(None) class GstWidget(Gtk.Box): def __init__(self, pipeline): super().__init__() self.connect('realize', self._on_realize) self._bin = Gst.parse_bin_from_description('videotestsrc', True) def _on_realize(self, widget): pipeline = Gst.Pipeline() factory = pipeline.get_factory() gtksink = factory.make('gtksink') pipeline.add(gtksink) pipeline.add(self._bin) self._bin.link(gtksink) self.pack_start(gtksink.props.widget, True, True, 0) gtksink.props.widget.show() pipeline.set_state(Gst.State.PLAYING) window = Gtk.ApplicationWindow() header_bar = Gtk.HeaderBar() header_bar.set_show_close_button(True) window.set_titlebar(header_bar) # Place 2 widget = GstWidget('videotestsrc') widget.set_size_request(200, 200) window.add(widget) window.show_all() def on_destroy(win): try: Gtk.main_quit() except KeyboardInterrupt: pass window.connect('destroy', on_destroy) Gtk.main() </code></pre>
0
2016-10-18T03:55:21Z
[ "python", "gstreamer", "gtk3", "xlib" ]
Tkinter - Grid elements next to each other
40,078,748
<p>I'm trying to make some UI in python with tkinter.</p> <p>This is a sample of the code I'm using:</p> <pre><code>root = Tk() root.geometry("1000x700x0x0") canvas = Canvas(root, width = 700, height = 700, bg ='white').grid(row = 0, column = 0) button1 = Button(root, text = "w/e", command = w/e).grid(row = 0, column = 1) button2 = Button(root, text = "w/e", command = w/e).grid(row = 1, column = 1) </code></pre> <p>This is what i'm getting:<a href="https://i.stack.imgur.com/TF65P.png" rel="nofollow"><img src="https://i.stack.imgur.com/TF65P.png" alt="enter image description here"></a></p> <p>and this is what I want:<a href="https://i.stack.imgur.com/S6x7B.png" rel="nofollow"><img src="https://i.stack.imgur.com/S6x7B.png" alt="enter image description here"></a></p> <p>Any help on how can I do it?</p> <p>Thanks!</p>
1
2016-10-17T04:59:29Z
40,089,035
<p>Since your GUI seems to have two logical groups of widgets, I would organize it as such. Start by placing the canvas on the left and a frame on the right. You can use <code>pack</code>, <code>place</code>, <code>grid</code>, or a paned window to manage them. For a left-to-right orientation, <code>pack</code> is a good choice due to its simplicity</p> <p>Note that you don't have to do it this way, but experience has taught me it makes layout problems much easier to solve.</p> <p>In the following example I set <code>expand</code> to <code>False</code> for the button frame, which means that the canvas will grow and shrink when the user resizes (because it has <code>expand=True</code>), but the buttons will only take up exactly as much space as they need. </p> <pre><code>canvas = Canvas(root, ...) buttonframe = Frame(root, ...) canvas.pack(side="left", fill="both", expand=True) buttonframe.pack(side="right", fill="both", expand=False) </code></pre> <p>Next, you can put all of the buttons in the right side without having to worry how their placement might affect objects on the left.</p> <p>The important thing to remember when using <code>grid</code> is that you should designate at least one row and at least one column to be given any extra space. This can be a row and/or column that contains widgets, or it can be an empty row and column on an edge.</p> <pre><code>button1 = Button(buttonframe, ...) button2 = Button(buttonframe, ...) button3 = Button(buttonframe, ...) ... button1.grid(row=0, column=0) button2.grid(row=0, column=1) button3.grid(row=1, column=0) ... buttonframe.grid_rowconfigure(100, weight=1) buttonframe.grid_columnconfigure(2, weight=1) </code></pre> <hr> <p>note: if you need to keep a reference to a widget, you must create the widget and call <code>grid</code> (or <code>pack</code> or <code>place</code>) on two separate lines. This is because <code>Button(...).grid(...)</code> returns the value of the last function call, and <code>grid(...)</code> returns <code>None</code></p>
2
2016-10-17T14:27:27Z
[ "python", "tkinter" ]
How to display equation and R2 of a best fit 3D plane?
40,078,921
<p>I have created a 3D plane as the best fit on 3D plot using python. Can someone help me to display the equation of the plane and the R2 of the plane?</p>
-1
2016-10-17T05:16:31Z
40,092,705
<p>r2 is 1.0 - [(absolute error variance] / [dependent data variance])</p> <p>With numpy this is simple, like so:</p> <p>err = numpy.array(absolute error)</p> <p>Z = numpy.array(Z of "XYZ" data)</p> <p>r2 = 1.0 - (err.var() / Z.var())</p> <p>To draw the surface you have to calculate a grid to display. Matplotlib has an example here, just scroll down a bit until you see the colored surface plot:</p> <p><a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html" rel="nofollow">http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html</a></p>
0
2016-10-17T17:52:57Z
[ "python", "curve-fitting" ]
Regex for capital letters followed be a space folllowed by numbers 'ABC 123' or 'BLZ 420'
40,079,232
<p>So I have this script that identifies <code>ABC-123</code></p> <pre><code>e = r'[A-Z]+-\d+' </code></pre> <p>shouldn't this identify <code>ABC 123</code></p> <pre><code>e = r'[A-Z]+/s\d+' </code></pre> <p>Or am I missing something blindingly obvious. Thanks. This is in Python as well. </p>
0
2016-10-17T05:44:05Z
40,079,249
<p>You have the wrong slash, you need a backslash:</p> <pre><code>e = r'[A-Z]+\s\d+' </code></pre> <p><code>/s</code> will match <code>/</code> followed by a <code>s</code> literally, whereas <code>\s</code> is a Regex token that indicates a whitespace.</p>
5
2016-10-17T05:45:21Z
[ "python", "regex" ]
How do I pass in an argument to a list of lambdas?
40,079,240
<p>Intent: I'm trying to return each dictionary that contains the passed in matching keywords and values within a list of dictionaries. For example, <code>a='woot', e='1', c='duh'</code> would return only</p> <pre><code>{'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'} </code></pre> <p>This is what I have so far, but I don't know how to pass in an argument to a list of lambda expression which act as the filter for each dictionary in the list.</p> <pre><code>sample_dict = [ {'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'}, {'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'}, {'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'}, {'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'}, {'a': 'toot', 'b': 'nope', 'c': 'cuh', 'd': 'rough', 'e': '1'} ] def get_matched_lines(input_dict, **param): filters = [lambda input_dict_elem, input_key=param_key, input_value=param_value: input_dict_elem[input_key] == input_value for param_key, param_value in param.items()] return [dict_elem for dict_elem in input_dict if(all(filters))] print(get_matched_lines(sample_dict, a='woot', e='1', c='duh')) </code></pre>
0
2016-10-17T05:44:27Z
40,079,423
<pre><code>def get_matched_lines(input_dict, array): output=[] keys=[] values=[] for a in array: keyvalue = a.split("=") keys.append(keyvalue[0]) values.append(keyvalue[1]) for dict in input_dict: bool=1 for i in range(0,len(keys)): if keys[i] in dict.keys(): # print values[i] if dict[keys[i]] != values[i]: bool=0 if bool==1: output.append(dict) return output sample_dict = [ {'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'}, {'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'}, {'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'}, {'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'}, {'a': 'toot', 'b': 'nope', 'c': 'cuh', 'd': 'rough', 'e': '1'} ] array = ["a=woot", "e=1", "c=duh"] print get_matched_lines(sample_dict, array) </code></pre> <p>output:</p> <pre><code>[{'a': 'woot', 'c': 'duh', 'b': 'nope', 'e': '1', 'd': 'rough'}] </code></pre>
0
2016-10-17T06:00:48Z
[ "python", "lambda", "filtering", "list-comprehension" ]
How do I pass in an argument to a list of lambdas?
40,079,240
<p>Intent: I'm trying to return each dictionary that contains the passed in matching keywords and values within a list of dictionaries. For example, <code>a='woot', e='1', c='duh'</code> would return only</p> <pre><code>{'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'} </code></pre> <p>This is what I have so far, but I don't know how to pass in an argument to a list of lambda expression which act as the filter for each dictionary in the list.</p> <pre><code>sample_dict = [ {'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'}, {'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'}, {'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'}, {'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'}, {'a': 'toot', 'b': 'nope', 'c': 'cuh', 'd': 'rough', 'e': '1'} ] def get_matched_lines(input_dict, **param): filters = [lambda input_dict_elem, input_key=param_key, input_value=param_value: input_dict_elem[input_key] == input_value for param_key, param_value in param.items()] return [dict_elem for dict_elem in input_dict if(all(filters))] print(get_matched_lines(sample_dict, a='woot', e='1', c='duh')) </code></pre>
0
2016-10-17T05:44:27Z
40,079,502
<p>You can do this (in Python 2.7):</p> <pre><code>def get_matched_lines(input_dict, **param): return [dic for dic in input_dict if all([key in dic and dic[key] == val for key, val in param.iteritems()])] </code></pre> <p>The same code in Python 3 is</p> <pre><code>def get_matched_lines(input_dict, **param): return [dic for dic in input_dict if all([key in dic and dic[key] == val for key, val in param.items()])] </code></pre>
3
2016-10-17T06:08:09Z
[ "python", "lambda", "filtering", "list-comprehension" ]
How do I pass in an argument to a list of lambdas?
40,079,240
<p>Intent: I'm trying to return each dictionary that contains the passed in matching keywords and values within a list of dictionaries. For example, <code>a='woot', e='1', c='duh'</code> would return only</p> <pre><code>{'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'} </code></pre> <p>This is what I have so far, but I don't know how to pass in an argument to a list of lambda expression which act as the filter for each dictionary in the list.</p> <pre><code>sample_dict = [ {'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'}, {'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'}, {'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'}, {'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'}, {'a': 'toot', 'b': 'nope', 'c': 'cuh', 'd': 'rough', 'e': '1'} ] def get_matched_lines(input_dict, **param): filters = [lambda input_dict_elem, input_key=param_key, input_value=param_value: input_dict_elem[input_key] == input_value for param_key, param_value in param.items()] return [dict_elem for dict_elem in input_dict if(all(filters))] print(get_matched_lines(sample_dict, a='woot', e='1', c='duh')) </code></pre>
0
2016-10-17T05:44:27Z
40,079,924
<p>I think you don't have to use lambda here... basic for loop is enough...</p> <p>Concept is simple as the following: If all the keys and values in param belongs and equals to the input_dict, it returns the whole dictionary row which you want to return. If at least a key can't be found or a value isn't the same, return nothing.</p> <pre><code>sample_dict = [ {'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'}, {'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'}, {'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'}, {'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'}, {'a': 'toot', 'b': 'nope', 'c': 'cuh', 'd': 'rough', 'e': '1'} ] def get_matched_lines(input_dict, **param): return [d_ for d_ in sample_dict if all([False for k in param if not k in d_ or d_[k]!=param[k]])] print(get_matched_lines(sample_dict, a='woot', e='1', c='duh')) </code></pre> <p>More question, then let me know.</p>
0
2016-10-17T06:38:18Z
[ "python", "lambda", "filtering", "list-comprehension" ]
How to add an unspecified amount of variables together?
40,079,400
<p>I'm trying to add in python 3.5.2 but I have an unspecified amount of variables. I have to use very basic functions; I can't use <code>list</code>. I can't figure out how I'm supposed to add each new variable together without a <code>list</code>. When I run the code it adds the last entered <code>price1</code> which is <code>-1</code>. I need to use the <code>-1</code> to tell the program to total all the variables. </p> <pre><code>count = 0 while (True): price1 = int( input("Enter the price of item, or enter -1 to get total: ")) count += 1 if (price1 ==-1): subtotal = (price1 + ) #this is where I"m having trouble #at least I think this is the problem tax = (subtotal*0.05) total = (subtotal + tax) print("Subtotal: . . . . . ", subtotal) print("Tax: . . . . . . . . ", tax) print("Total: . . . . . . . .", total) break </code></pre>
0
2016-10-17T05:59:41Z
40,079,477
<p>Keep another variable around and sum than up, also, <code>count</code> isn't used for anything so no real reason to keep it around. </p> <p>For example, initialize a <code>price</code> name to <code>0</code>:</p> <pre><code>price = 0 </code></pre> <p>then, check if the value is <code>-1</code> and, if not, simply increment (<code>+=</code>) the <code>price</code> variable with the value obtained for <code>price1</code>:</p> <pre><code>if price1 == -1: subtotal = price tax = subtotal*0.05 total = subtotal + tax print("Subtotal: . . . . . ", subtotal) print("Tax: . . . . . . . . ", tax) print("Total: . . . . . . . .", total) break else: price += price1 </code></pre>
3
2016-10-17T06:05:09Z
[ "python", "python-2.7", "python-3.x" ]
How to add an unspecified amount of variables together?
40,079,400
<p>I'm trying to add in python 3.5.2 but I have an unspecified amount of variables. I have to use very basic functions; I can't use <code>list</code>. I can't figure out how I'm supposed to add each new variable together without a <code>list</code>. When I run the code it adds the last entered <code>price1</code> which is <code>-1</code>. I need to use the <code>-1</code> to tell the program to total all the variables. </p> <pre><code>count = 0 while (True): price1 = int( input("Enter the price of item, or enter -1 to get total: ")) count += 1 if (price1 ==-1): subtotal = (price1 + ) #this is where I"m having trouble #at least I think this is the problem tax = (subtotal*0.05) total = (subtotal + tax) print("Subtotal: . . . . . ", subtotal) print("Tax: . . . . . . . . ", tax) print("Total: . . . . . . . .", total) break </code></pre>
0
2016-10-17T05:59:41Z
40,079,515
<p>You almost had it. Looking at your code, what I would suggest you do is create a <code>subtotal</code> variable just outside of your loop and initialize it to <code>0</code>. Furthermore, you are not using <code>count</code> for anything, so get rid of that.</p> <p>When you get your <code>price</code> input, check it right after for the <code>-1</code> condition. If you have a <code>-1</code> value, then proceed with your <em>math</em>, otherwise your <code>else</code> will start running the <code>subtotal</code> with the <code>subtotal += price</code>.</p> <p>So, you should have something like:</p> <pre><code>subtotal = 0 while (True): price = int( input("Enter the price of item, or enter -1 to get total: ")) if price == -1: tax = subtotal*0.05 total = subtotal + tax print("Subtotal: . . . . . ", subtotal) print("Tax: . . . . . . . . ", tax) print("Total: . . . . . . . .", total) break else: subtotal += price </code></pre>
2
2016-10-17T06:09:27Z
[ "python", "python-2.7", "python-3.x" ]
No JSON object could be decoded - Django request.body
40,079,504
<p>I am making web service for posting comments from smart phone, Below is my code </p> <pre><code>@api_view(['POST']) def comment_post(request,newsId=None): data = json.loads(request.body) responseData= dict({ "result": list() }) if(newsId): commentNews = models.Comments.objects.create() commentNews.comment_description = data.get('comment_description').strip() commentNews.like_count = int(data.get('like_count')) commentNews.user_name = data.get('user_name').strip() commentNews.user_email_id = data.get('user_email_id').strip() commentNews.parent_comment = data.get('parent_comment').strip() commentNews.save() subscribed_user = models.SubscribedUsers.objects.create(username=data.get('user_name').strip(),email=data.get('user_email_id').strip()) news = models.News.objects.get(id=int(newsId)) news.comments.add(commentNews) data ={ 'status':'success' } else: data ={ 'status':'failure' } responseData['result'].append(data) return Response(responseData,status=status.HTTP_200_OK) </code></pre> <p>Whenever i check it on local it works, but on server side it gives me below error</p> <pre><code>ValueError at /service/comment_post/369 No JSON object could be decoded Request Method: POST Request URL: http://dev.newskhabari.com/service/comment_post/369 Django Version: 1.9.5 Exception Type: ValueError Exception Value: No JSON object could be decoded Exception Location: /usr/local/lib/python2.7/json/decoder.py in raw_decode, line 383 Python Executable: /var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/bin/python Python Version: 2.7.6 Python Path: ['/var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/lib/python2.7/site-packages', '/var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/lib/python2.7/site-packages/django', '/var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/bin', '/var/www/vhosts/newskhabari.com/newskhabari_dev', '/usr/local/rvm/gems/ruby-2.2.2/gems/passenger-5.0.30/src/helper-scripts', '/var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/lib/python27.zip', '/var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/lib/python2.7', '/var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/lib/python2.7/plat-linux2', '/var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/lib/python2.7/lib-tk', '/var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/lib/python2.7/lib-old', '/var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/var/www/vhosts/newskhabari.com/newskhabari_dev/newskhabari-app-venv/lib/python2.7/site-packages', '/var/www/vhosts/newskhabari.com/newskhabari_dev', '/var/www/vhosts/newskhabari.com/newskhabari_dev/app'] Server time: Mon, 17 Oct 2016 11:35:36 +0530 </code></pre> <p>I am unable to figure out why it give Exception Value: No JSON object could be decoded</p>
0
2016-10-17T06:08:15Z
40,079,738
<p>I guess, You are using <code>django-rest-framework</code>. So, You don't have to do <code>json.loads()</code>, becasue <code>django-rest-framework</code> provides <code>request.data</code> for <code>POST</code> requests and <code>request.query_params</code> for <code>GET</code> requests, <strong>already parsed in json format</strong>.</p> <p>So I think this should work for you. </p> <pre><code>@api_view(['POST']) def comment_post(request,newsId=None): responseData= dict({ "result": list() }) if(newsId): commentNews = models.Comments.objects.create() commentNews.comment_description = request.data.get('comment_description').strip() commentNews.like_count = int(request.data.get('like_count')) commentNews.user_name = request.data.get('user_name').strip() commentNews.user_email_id = request.data.get('user_email_id').strip() commentNews.parent_comment = request.data.get('parent_comment').strip() commentNews.save() subscribed_user = models.SubscribedUsers.objects.create(username=request.data.get('user_name').strip(),email=request.data.get('user_email_id').strip()) news = models.News.objects.get(id=int(newsId)) news.comments.add(commentNews) data ={ 'status':'success' } else: data ={ 'status':'failure' } responseData['result'].append(data) return Response(responseData,status=status.HTTP_200_OK) </code></pre> <p>For further info read the the <a href="http://www.django-rest-framework.org/api-guide/requests/" rel="nofollow">docs here</a></p>
2
2016-10-17T06:24:46Z
[ "python", "json", "django", "python-2.7" ]
Process data from several text files
40,079,612
<p>Any recommendation on how I can grab data from several text files and process them (compute totals for example). I have been trying to do it in Python but keep on encountering dead ends.</p> <p>A machine generates a summary file in text format each time you do an operation, for this example, screening good apples from batches. First you load the apples, then good is separated from bad, and then you can reload the bad apples again to retest them and some are recovered. so at least 2 summary file is generated per batch, depending on how many times you load the apples to recover good.</p> <p>This is an example of the text file:</p> <p>file1:</p> <pre><code>general Info: Batch No. : A2J3 Operation : Test Fruit : Apple Operation Number : A5500 Quantity In : 10 yield info: S1 S2 Total Bin Name 5 2 7 good 1 2 3 bad </code></pre> <p>file2:</p> <pre><code>general Info: Batch No. : A2J3 Operation : Test Fruit : Apple Operation Number : A5500 Quantity In : 3 yield info: S1 S2 Total Bin Name 1 1 2 good 0 0 1 bad </code></pre> <p>I want to get the data in a folder full of these txt files and merge the testing results with the following criteria:</p> <ol> <li><p>process the same batch by identifying which txt files are coming from the same Batch No., same operation (based on the txt file's content not filename)</p></li> <li><p>merge the 2 (or more summary file) data into the following format csv:</p> <pre><code>Lot: Operation: Bin First Pass Second Pass Final Yield %Yield Good 7 2 9 90% Bad 3 1 1 10% </code></pre></li> </ol> <p>S1, S2 is variable, it can go from 1 to 14 but never less than 1. The bins can also have several types on different text files (not only limited to good and bad. but there will always be only 1 good bin)</p> <pre><code>Bins: Good Semi-bad Bad Worst ... </code></pre> <p>I'm new to Python and I only used this scripting language at school, I only know the very basics, nothing more. So this task I want to do is a bit overwhelming to me so I started to process a single text file and get the data I wanted, eg: Batch Number</p> <pre><code>with open('R0.txt') as fh_d10SunFile: fh_d10SumFile_perline = fh_d10SunFile.read().splitlines() #print fh_d10SumFile_perline TestProgramName_str = fh_d10SumFile_perline[CONST.TestProgram_field].split(':')[1] LotNumber_str = fh_d10SumFile_perline[CONST.LotNumber_field].split(':')[1] QtyIn_int = int( fh_d10SumFile_perline[CONST.UnitsIn_field].split(':')[1] ) TestIteration_str = fh_d10SumFile_perline[CONST.TestIteration_field].split(':')[1] TestType_str = fh_d10SumFile_perline[CONST.TestType_field].split(':')[1] </code></pre> <p>then grab all the bins in that summary file:</p> <pre><code>SoftBins_str = filter( lambda x: re.search(r'bin',x),fh_d10SumFile_perline) for index in range( len(SoftBins_str) ): SoftBins_data_str = [l.strip() for l in SoftBins_str[index].split(' ') if l.strip()] SoftBins_data_str.reverse() bin2bin[SoftBins_data_str[0]] = SoftBins_data_str[2] </code></pre> <p>then i got stuck because i'm not sure how to do this reading and parsing with several n number of text files containing n number of sites (S1, S2). How do I grab these information from n number of text files, process them in memory (is this even possible with python) and then write the output with computation on the csv output file.</p>
-2
2016-10-17T06:16:45Z
40,082,963
<p>The following should help get you started. As your text files are fixed format, it is relatively simple to read them in and parse them. This script searches for all text files in the current folder, reads each file in and stores the batches in a dictionary based on the batch name so that all batches of the same name area grouped together.</p> <p>After all files are processed, it creates summaries for each batch and writes them to a single csv output file.</p> <pre><code>from collections import defaultdict import glob import csv batches = defaultdict(list) for text_file in glob.glob('*.txt'): with open(text_file) as f_input: rows = [row.strip() for row in f_input] header = [rows[x].split(':')[1].strip() for x in range(1, 6)] bins = {} for yield_info in rows[8:]: s1, s2, total, bin_name = yield_info.split() bins[bin_name] = [int(s1), int(s2), int(total)] batches[header[0]].append(header + [bins]) with open('output.csv', 'wb') as f_output: csv_output = csv.writer(f_output, delimiter='\t') for batch, passes in batches.items(): bins_output = defaultdict(lambda: [[], 0]) total_yield = 0 for lot, operation, fruit, op_num, quantity, bins in passes: for bin_name, (s1, s2, total) in bins.iteritems(): bins_output[bin_name][0].append(total) bins_output[bin_name][1] += total total_yield += total csv_output.writerows([['Lot:', lot], ['Operation:', operation]]) csv_header = ["Bin"] + ['Pass {}'.format(x) for x in range(1, 1 + len(passes))] + ["Final Yield", "%Yield"] csv_output.writerow(csv_header) for bin_name in sorted(bins_output.keys()): entries, total = bins_output[bin_name] percentage_yield = '{:.1f}%'.format((100.0 * total) / total_yield) csv_output.writerow([bin_name] + entries + [total, percentage_yield]) csv_output.writerow([]) # empty row to separate batches </code></pre> <p>Giving you a tab delimited <code>csv</code> file as follows:</p> <pre class="lang-none prettyprint-override"><code>Lot: A2J3 Operation: Test Bin Pass 1 Pass 2 Final Yield %Yield Bad 3 1 4 30.8% Good 7 2 9 69.2% </code></pre> <p>Note, script has been updated to deal with any number of bin types.</p>
1
2016-10-17T09:36:35Z
[ "python", "scripting" ]
Get models ordered by an attribute that belongs to its OneToOne model
40,079,728
<p>Let's say there is one model named <code>User</code> and the other named <code>Pet</code> which has a <code>OneToOne</code> relationship with <code>User</code>, the <code>Pet</code> model has an attribute <code>age</code>, how to get the ten <code>User</code> that owns the top ten <code>oldest</code> dog?</p> <pre><code>class User(models.Model): name = models.CharField(max_length=50, null=False, blank=False) class Pet(models.Model): name = models.CharField(max_length=50, null=False, blank=False) owner = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField(null=False) </code></pre> <hr> <p>In <code>User</code>, there is an attribute <code>friends</code> that has a <code>ManyToMany</code> relationship with <code>User</code>, how to get the ten <code>friends</code> of <code>User Tom</code> that owns the top ten <code>oldest</code> dog?</p> <pre><code>class User(models.Model): name = models.CharField(max_length=50, null=False, blank=False) friends = models.ManyToManyField(self, ...) class Pet(models.Model): name = models.CharField(max_length=50, null=False, blank=False) owner = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField(null=False) </code></pre>
3
2016-10-17T06:24:09Z
40,079,772
<p>Use the double-underscore syntax.</p> <pre><code>User.objects.order_by('-pet__age')[:10] </code></pre> <p><strong>Edit</strong></p> <p>To get the ten friends of Tom, you can get the instance and filter:</p> <pre><code>User.objects.get(name='Tom').friends.order_by('-pet__age')[:10] </code></pre> <p>or if you already have Tom:</p> <pre><code>tom.friends.order_by('-pet__age')[:10] </code></pre>
6
2016-10-17T06:27:14Z
[ "python", "django", "python-3.x" ]
Get models ordered by an attribute that belongs to its OneToOne model
40,079,728
<p>Let's say there is one model named <code>User</code> and the other named <code>Pet</code> which has a <code>OneToOne</code> relationship with <code>User</code>, the <code>Pet</code> model has an attribute <code>age</code>, how to get the ten <code>User</code> that owns the top ten <code>oldest</code> dog?</p> <pre><code>class User(models.Model): name = models.CharField(max_length=50, null=False, blank=False) class Pet(models.Model): name = models.CharField(max_length=50, null=False, blank=False) owner = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField(null=False) </code></pre> <hr> <p>In <code>User</code>, there is an attribute <code>friends</code> that has a <code>ManyToMany</code> relationship with <code>User</code>, how to get the ten <code>friends</code> of <code>User Tom</code> that owns the top ten <code>oldest</code> dog?</p> <pre><code>class User(models.Model): name = models.CharField(max_length=50, null=False, blank=False) friends = models.ManyToManyField(self, ...) class Pet(models.Model): name = models.CharField(max_length=50, null=False, blank=False) owner = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField(null=False) </code></pre>
3
2016-10-17T06:24:09Z
40,080,190
<p>Try this : First define <strong>unicode</strong> in model User like this: By this,User model objects will always return name field of the user records.</p> <pre><code> class User(models.Model): name = models.CharField(max_length=50, null=False, blank=False) friends = models.ManyToManyField(self, ...) def __unicode__(self): return self.name </code></pre> <p>Then use this query:</p> <pre><code> User.objects.filter(friends='Tom').order_by('-pet__age')[:10] </code></pre>
0
2016-10-17T06:56:41Z
[ "python", "django", "python-3.x" ]
Get models ordered by an attribute that belongs to its OneToOne model
40,079,728
<p>Let's say there is one model named <code>User</code> and the other named <code>Pet</code> which has a <code>OneToOne</code> relationship with <code>User</code>, the <code>Pet</code> model has an attribute <code>age</code>, how to get the ten <code>User</code> that owns the top ten <code>oldest</code> dog?</p> <pre><code>class User(models.Model): name = models.CharField(max_length=50, null=False, blank=False) class Pet(models.Model): name = models.CharField(max_length=50, null=False, blank=False) owner = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField(null=False) </code></pre> <hr> <p>In <code>User</code>, there is an attribute <code>friends</code> that has a <code>ManyToMany</code> relationship with <code>User</code>, how to get the ten <code>friends</code> of <code>User Tom</code> that owns the top ten <code>oldest</code> dog?</p> <pre><code>class User(models.Model): name = models.CharField(max_length=50, null=False, blank=False) friends = models.ManyToManyField(self, ...) class Pet(models.Model): name = models.CharField(max_length=50, null=False, blank=False) owner = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField(null=False) </code></pre>
3
2016-10-17T06:24:09Z
40,082,910
<p>Another solution (alternative to <code>order_by</code>) is using <code>nlargest</code> function of <code>heapq</code> module, this might be better if you already have <code>friends</code> list (tom's friends in this case) with a large number of items (I mean from performance perspective).</p> <pre><code>import heapq heapq.nlargest( 10, User.objects.get(name='Tom').friends.all(), key=lambda f: f.pet.age ) </code></pre> <p><strong>Note:</strong> You have also <code>nsmallest</code> function that you can use to get the youngest pets.</p>
0
2016-10-17T09:33:38Z
[ "python", "django", "python-3.x" ]
Adding multiple key,value pair using dictionary comprehension
40,079,792
<p>for a list of dictionaries</p> <pre><code>sample_dict = [ {'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'}, {'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'}, {'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'}, {'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'}, {'a': 'toot', 'b': 'nope', 'c': 'cuh', 'd': 'rough', 'e': '1'} ] </code></pre> <p>How do I make a separate dictionary that contains all the key,value pair that match to a certain key. With list comprehension I created a list of all the key,value pairs like this:</p> <pre><code>container = [[key,val] for s in sample_dict for key,val in s.iteritems() if key == 'a'] </code></pre> <p>Now the container gave me</p> <pre><code>[['a', 'woot'], ['a', 'coot'], ['a', 'doot'], ['a', 'soot'], ['a', 'toot']] </code></pre> <p>Which is all fine... but if I want to do the same with dictionaries, I get only a singe key,value pair. Why does this happen ?</p> <pre><code>container = {key : val for s in sample_dict for key,val in s.iteritems() if key == 'a'} </code></pre> <p>The container gives only a single element</p> <pre><code>{'a': 'toot'} </code></pre> <p>I want the something like </p> <pre><code>{'a': ['woot','coot','doot','soot','toot']} </code></pre> <p>How do I do this with minimal change to the code above ? </p>
1
2016-10-17T06:28:48Z
40,079,875
<p>You are generating multiple key-value pairs with the same key, and a dictionary will only ever store <em>unique</em> keys.</p> <p>If you wanted just <em>one</em> key, you'd use a dictionary with a list comprehension:</p> <pre><code>container = {'a': [s['a'] for s in sample_dict if 'a' in s]} </code></pre> <p>Note that there is <em>no need</em> to iterate over the nested dictionaries in <code>sample_dict</code> if all you wanted was a specific key; in the above I simply test if the key exists (<code>'a' in s</code>) and extract the value for that key with <code>s['a']</code>. This is <em>much faster</em> than looping over all the keys.</p>
4
2016-10-17T06:35:13Z
[ "python" ]
Adding multiple key,value pair using dictionary comprehension
40,079,792
<p>for a list of dictionaries</p> <pre><code>sample_dict = [ {'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'}, {'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'}, {'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'}, {'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'}, {'a': 'toot', 'b': 'nope', 'c': 'cuh', 'd': 'rough', 'e': '1'} ] </code></pre> <p>How do I make a separate dictionary that contains all the key,value pair that match to a certain key. With list comprehension I created a list of all the key,value pairs like this:</p> <pre><code>container = [[key,val] for s in sample_dict for key,val in s.iteritems() if key == 'a'] </code></pre> <p>Now the container gave me</p> <pre><code>[['a', 'woot'], ['a', 'coot'], ['a', 'doot'], ['a', 'soot'], ['a', 'toot']] </code></pre> <p>Which is all fine... but if I want to do the same with dictionaries, I get only a singe key,value pair. Why does this happen ?</p> <pre><code>container = {key : val for s in sample_dict for key,val in s.iteritems() if key == 'a'} </code></pre> <p>The container gives only a single element</p> <pre><code>{'a': 'toot'} </code></pre> <p>I want the something like </p> <pre><code>{'a': ['woot','coot','doot','soot','toot']} </code></pre> <p>How do I do this with minimal change to the code above ? </p>
1
2016-10-17T06:28:48Z
40,080,007
<p>Another option:</p> <pre><code>filter = lambda arr, x: { x: [ e.get(x) for e in arr] } </code></pre> <p>So, from here, you can construct the dict based on the original array and the key </p> <pre><code> filter(sample_dict, 'a') # {'a': ['woot', 'coot', 'doot', 'soot', 'toot']} </code></pre>
-1
2016-10-17T06:44:08Z
[ "python" ]
django 3.5 makemessages refers to previous virtual env
40,079,837
<p>I am running django 1.10 with python 3.5 on windows 7 and I am trying to translate my test files.</p> <p>I have created the es language directory in the locale directory.</p> <p>In the virtual environment, at the command prompt I enter: <code>python manage.py makemessages --locale=es</code></p> <p>I get the following error message:</p> <pre><code>.... .\manage.py .\requirements.txt.py .\requirements\base.txt.py .\requirements\deployment.txt.py .\requirements\development.txt.py .\requirements\production.txt.py .\runtime.txt.py xgettext: Non-ASCII string at .\env\Lib\sitepackages\compressor\filters\cssmin\rcssmin.py:70. Please specify the source encoding through --from-code. </code></pre> <p>I have seen this <a href="http://stackoverflow.com/questions/20955811/localization-with-django-and-xgettext">post</a> and changed the <code>ascii</code> to <code>utf-8</code> and even tried <code>utf8</code>. I get the same error message.</p> <p>When I open the file <code>.\env\Lib\sitepackages\compressor\filters\cssmin\rcssmin.py</code>, there is no code on line 70. Here is the relevant portion of the file:</p> <pre><code>Both python 2 (&gt;= 2.4) and python 3 are supported. .. _YUI compressor: https://github.com/yui/yuicompressor/ .. _the rule list by Isaac Schlueter: https://github.com/isaacs/cssmin/ """ if __doc__: # pylint: disable = W0622 __doc__ = __doc__.encode('ascii').decode('unicode_escape') __author__ = r"Andr\xe9 Malo".encode('ascii').decode('unicode_escape') __docformat__ = "restructuredtext en" __license__ = "Apache License, Version 2.0" __version__ = '1.0.6' __all__ = ['cssmin'] import re as _re </code></pre> <p><strong>I have run out of ideas. Does anyone have any suggestions?</strong></p>
0
2016-10-17T06:32:03Z
40,083,793
<p>Maybe there is a character even if you don't see it. Try pasteing in notepad++ the text (sometimes it helps to detect wrong chars) or try to delete/rewrite close newlines, tabs, or similar symbols just in case they came from a copy/paste from a file with different coding.</p>
0
2016-10-17T10:18:16Z
[ "python", "django", "translation" ]
django 3.5 makemessages refers to previous virtual env
40,079,837
<p>I am running django 1.10 with python 3.5 on windows 7 and I am trying to translate my test files.</p> <p>I have created the es language directory in the locale directory.</p> <p>In the virtual environment, at the command prompt I enter: <code>python manage.py makemessages --locale=es</code></p> <p>I get the following error message:</p> <pre><code>.... .\manage.py .\requirements.txt.py .\requirements\base.txt.py .\requirements\deployment.txt.py .\requirements\development.txt.py .\requirements\production.txt.py .\runtime.txt.py xgettext: Non-ASCII string at .\env\Lib\sitepackages\compressor\filters\cssmin\rcssmin.py:70. Please specify the source encoding through --from-code. </code></pre> <p>I have seen this <a href="http://stackoverflow.com/questions/20955811/localization-with-django-and-xgettext">post</a> and changed the <code>ascii</code> to <code>utf-8</code> and even tried <code>utf8</code>. I get the same error message.</p> <p>When I open the file <code>.\env\Lib\sitepackages\compressor\filters\cssmin\rcssmin.py</code>, there is no code on line 70. Here is the relevant portion of the file:</p> <pre><code>Both python 2 (&gt;= 2.4) and python 3 are supported. .. _YUI compressor: https://github.com/yui/yuicompressor/ .. _the rule list by Isaac Schlueter: https://github.com/isaacs/cssmin/ """ if __doc__: # pylint: disable = W0622 __doc__ = __doc__.encode('ascii').decode('unicode_escape') __author__ = r"Andr\xe9 Malo".encode('ascii').decode('unicode_escape') __docformat__ = "restructuredtext en" __license__ = "Apache License, Version 2.0" __version__ = '1.0.6' __all__ = ['cssmin'] import re as _re </code></pre> <p><strong>I have run out of ideas. Does anyone have any suggestions?</strong></p>
0
2016-10-17T06:32:03Z
40,095,167
<p>This error was due to an old virtual environment folder that was on my system. I have deleted this folder, and a new error now displays. I have posted a different thread for the new error.</p>
0
2016-10-17T20:33:07Z
[ "python", "django", "translation" ]
inheritance using parent class method without calling parent class
40,079,985
<p>Is there any way to access parent class method, without actually calling the class?</p> <p>e.g.:</p> <p>1)</p> <pre><code>class A(): def __init__(self): print('A class') def name(): print('name from A class') </code></pre> <p>2)</p> <pre><code>class B(A): # I want to make use of name without actually calling or running A. # Is there any way to do that? </code></pre>
1
2016-10-17T06:42:29Z
40,080,038
<p>Yeah, you can just call it directly. This works fine:</p> <pre><code>class A(): def __init__(self): print('A class') def name(self): print('name from A class') class B(A): pass B().name() &gt; A class &gt; name from A class </code></pre> <p>You can also use it inside of the class, like </p> <pre><code>class B(A): def b_name(self): print('I am B!') self.name() </code></pre> <p>If what you're trying to get around is calling A's <code>init</code>, then maybe you should turn <code>name</code> into a classmethod:</p> <pre><code>class A(): def __init__(self): print('A class') @classmethod def name(self): print('name from A class') A.name() &gt; name from A class </code></pre> <p>Alternatively, you can give B an <code>init</code> which doesn't call its super class, thus instantiating it without calling A's init. I don't particularly recommend this method:</p> <pre><code>class A(): def __init__(self): print('A class') def name(self): print('name from A class') class B(A): def __init__(self): print('B class') def b_name(self): print('b_name from B class') self.name() B().b_name() &gt; B class &gt; b_name from B class &gt; name from A class </code></pre>
2
2016-10-17T06:46:12Z
[ "python", "inheritance" ]
I have two text files which contains same data but in different columns and different rows
40,080,102
<p>Example: First file.txt:</p> <pre><code>a | b | c | d 0 | 1 | 2 | 3 4 | 5 | 6 | 7 </code></pre> <p>Second file.txt</p> <pre><code>c | b | d | a 6 | 5 | 7 | 4 2 | 1 | 3 | 0 </code></pre> <p>Suggest me some easy way to populate and compare the values.</p>
-2
2016-10-17T06:50:51Z
40,081,494
<p>I would suggest saving them as <code>csv</code> files but text will work as well as long as you specify the correct separator. </p> <pre><code>import pandas as pd df1 = pd.read_csv('text1.csv', sep=',') df2 = pd.read_csv('text2.csv', sep=',') </code></pre> <p>you can then sort the columns</p> <pre><code>df1 = df1.sort_index(axis=1) df2 = df2.sort_index(axis=1) </code></pre> <p>all the columns will now be in the same order.</p> <p>you can aslo append the 2 DataFrames</p> <pre><code>df1 = df1.append(df2) </code></pre> <p>The <code>pandas</code> has several methods for comparing <code>DataFrames</code></p>
0
2016-10-17T08:16:37Z
[ "python" ]
Adding a seed to my program (Word Letter Scramble)
40,080,156
<p>I am having trouble figuring out how to add a seed to my program. It is supposed to be able take a given seed value and return a scrambled sentence. The first and last letters in a words should stay the same as well as ending punctuation. Any punctuation within a word is allowed to be scrambled. </p> <pre><code>import random import string original_text = input("Enter your text: ").split(' ') seed = int(input("Enter a seed (0 for random): ")) if seed is not 0: random.seed(seed) randomized_list = [] def scramble_word(word): alpha = word[0] if word[-1] == "," or "." or "!" or "?" or ":" or ";": omega = word[-2] middle = word[1:-2] else: omega = word[-1] middle = word[1:-1] reorders_text = random.sample(middle, len(middle)) shuffled_text = "".join(reorders_text) new_words = alpha + shuffled_text + omega return new_words for item in original_text: if len(item) &lt;= 3: randomized_list.append(item) else: randomized_list.append(scramble_word(item)) new_words = " ".join(randomized_list) print(new_words) </code></pre>
0
2016-10-17T06:54:05Z
40,080,275
<p>To add a seed to the program, with 0 being a random seed, you would need to call <code>random.seed()</code> to your program as so:</p> <pre><code>seed = int(input("Enter a seed (0 for random): ")) if seed is not 0: random.seed(seed) </code></pre> <p>Pretty simple.</p> <p>See the Python docs for more info: <a href="https://docs.python.org/3.5/library/random.html" rel="nofollow">https://docs.python.org/3.5/library/random.html</a></p> <p>In the future, it is always worth turning to the documentation before posting here. For basic things like this, the docs will probably answer your question.</p>
2
2016-10-17T07:02:31Z
[ "python", "python-3.x" ]
Change RGB color in matplotlib animation
40,080,248
<p>I seems that it is not possible to change colors of a Matplotlib scatter plot through a RGB definition. Am I wrong?</p> <p>Here is a code (already given in stack overflow) which work with colors indexed in float:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation def main(): numframes = 100 numpoints = 10 color_data = np.random.random((numframes, numpoints)) x, y, c = np.random.random((3, numpoints)) fig = plt.figure() scat = plt.scatter(x, y, c=c, s=100) ani = animation.FuncAnimation(fig, update_plot, frames=range(numframes), fargs=(color_data, scat)) plt.show() def update_plot(i, data, scat): scat.set_array(data[i]) return scat, main() </code></pre> <p>But if <code>color_data</code> is defined through RGB colors, I get an error: </p> <blockquote> <p>ValueError: Collections can only map rank 1 arrays</p> </blockquote> <p>The related code is the following (in this code, I just change the color of one sample each time):</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation def main(): numframes = 100 numpoints = 10 rgb_color_data = np.random.random((numpoints, 3)) x, y = np.random.random((2, numpoints)) fig = plt.figure() scat = plt.scatter(x, y, c=rgb_color_data, s=100) #this work well at this level ani = animation.FuncAnimation(fig, update_plot2, frames=range(numframes), fargs=(rgb_color_data, scat)) plt.show() def update_plot2(i,data,scat): data[ i%10 ] = np.random.random((3)) scat.set_array(data) # this fails return scat, main() </code></pre> <p>Is there a means to use <code>set_array</code> with RGB color array?</p>
0
2016-10-17T07:00:59Z
40,083,831
<p>Not sure what you are trying to achieve. But if you are trying to change the color, why not use the <code>set_color()</code> function of <code>Collection</code>?</p> <pre><code>def update_plot2(i,data,scat): data[ i%10 ] = np.random.random((3)) scat.set_color(data) # &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; return scat, </code></pre>
0
2016-10-17T10:20:14Z
[ "python", "matplotlib", "colors" ]
Find combinations with arrays and a combination pattern
40,080,263
<p>I have arrays such as these, and each pattern designates a combination shape with each number representing the size of the combination.</p> <ul> <li>pattern 0: <code>[1, 1, 1, 1]</code></li> <li>pattern 1: <code>[2, 1, 1]</code></li> <li>pattern 2: <code>[3, 1]</code></li> <li>pattern 3: <code>[4]</code></li> <li>...</li> </ul> <p>I also have a char-valued list like below. len(chars) equals the sum of the upper array's value.</p> <p><code>chars = ['A', 'B', 'C', 'D']</code></p> <p>I want to find all combinations of chars following a given pattern. For example, for pattern 1, 4C2 * 2C1 * 1C1 is the number of combinations.</p> <pre><code>[['A', 'B'], ['C'], ['D']] [['A', 'B'], ['D'], ['C']] [['A', 'C'], ['B'], ['D']] [['A', 'C'], ['D'], ['B']] [['A', 'D'], ['B'], ['C']] [['A', 'D'], ['C'], ['B']] ... </code></pre> <p>But I don't know how to create such combination arrays. Of course I know there are a lot of useful functions for combinations in python. But I don't know how to use them to create a combination array of combinations.</p> <p><strong>EDITED</strong></p> <p>I'm so sorry my explanation is confusing. I show a simple example.</p> <ul> <li>pattern 0: <code>[1, 1]</code></li> <li>pattern 1: <code>[2]</code></li> <li><code>chars = ['A', 'B']</code></li> </ul> <p>Then, the result should be like below. So first dimension should be permutation, but second dimension should be combination.</p> <ul> <li>pat0: <code>[['A'], ['B']]</code></li> <li>pat0: <code>[['B'], ['A']]</code></li> <li>pat1: <code>[['A', 'B']] # NOTE: [['B', 'A']] is same in my problem</code></li> </ul>
2
2016-10-17T07:01:50Z
40,083,720
<p>You can use recursive function that takes the first number in pattern and generates all the combinations of that length from remaining items. Then recurse with remaining pattern &amp; items and generated prefix. Once you have consumed all the numbers in pattern just <code>yield</code> the prefix all the way to caller:</p> <pre><code>from itertools import combinations pattern = [2, 1, 1] chars = ['A', 'B', 'C', 'D'] def patterns(shape, items, prefix=None): if not shape: yield prefix return prefix = prefix or [] for comb in combinations(items, shape[0]): child_items = items[:] for char in comb: child_items.remove(char) yield from patterns(shape[1:], child_items, prefix + [comb]) for pat in patterns(pattern, chars): print(pat) </code></pre> <p>Output:</p> <pre><code>[('A', 'B'), ('C',), ('D',)] [('A', 'B'), ('D',), ('C',)] [('A', 'C'), ('B',), ('D',)] [('A', 'C'), ('D',), ('B',)] [('A', 'D'), ('B',), ('C',)] [('A', 'D'), ('C',), ('B',)] [('B', 'C'), ('A',), ('D',)] [('B', 'C'), ('D',), ('A',)] [('B', 'D'), ('A',), ('C',)] [('B', 'D'), ('C',), ('A',)] [('C', 'D'), ('A',), ('B',)] [('C', 'D'), ('B',), ('A',)] </code></pre> <p>Note that above works only with Python 3 since it's using <code>yield from</code>.</p>
1
2016-10-17T10:14:25Z
[ "python", "combinations", "permutation" ]
Get column names (title) from a Vertica data base?
40,080,375
<p>I'm trying to extract the column names when pulling data from a vertica data base in python via an sql query. I am using vertica-python 0.6.8. So far I am creating a dictionary of the first line, but I was wondering if there is an easier way of doing it. This is how I am doing it right now:</p> <pre><code>import vertica_python import csv import sys import ssl import psycopg2 conn_info = {'host': '****', 'port': 5433, 'user': '****', 'password': '****', 'database': '****', # 10 minutes timeout on queries 'read_timeout': 600, # default throw error on invalid UTF-8 results 'unicode_error': 'strict', # SSL is disabled by default 'ssl': False} connection = vertica_python.connect(**conn_info) cur = connection.cursor('dict') str = "SELECT * FROM something WHERE something_happens LIMIT 1" cur.execute(str) temp = cur.fetchall() ColumnList = [] for column in temp[0]: ColumnList.append(column) </code></pre> <p>cheers</p>
1
2016-10-17T07:08:41Z
40,084,238
<p>If I am not wrong you are asking about the title of each column. You can do that by using data descriptors of "class hp_vertica_client.cursor". It can be found here : <a href="https://my.vertica.com/docs/7.2.x/HTML/Content/python_client/cursor.html" rel="nofollow">https://my.vertica.com/docs/7.2.x/HTML/Content/python_client/cursor.html</a></p>
0
2016-10-17T10:39:11Z
[ "python", "vertica" ]
Get column names (title) from a Vertica data base?
40,080,375
<p>I'm trying to extract the column names when pulling data from a vertica data base in python via an sql query. I am using vertica-python 0.6.8. So far I am creating a dictionary of the first line, but I was wondering if there is an easier way of doing it. This is how I am doing it right now:</p> <pre><code>import vertica_python import csv import sys import ssl import psycopg2 conn_info = {'host': '****', 'port': 5433, 'user': '****', 'password': '****', 'database': '****', # 10 minutes timeout on queries 'read_timeout': 600, # default throw error on invalid UTF-8 results 'unicode_error': 'strict', # SSL is disabled by default 'ssl': False} connection = vertica_python.connect(**conn_info) cur = connection.cursor('dict') str = "SELECT * FROM something WHERE something_happens LIMIT 1" cur.execute(str) temp = cur.fetchall() ColumnList = [] for column in temp[0]: ColumnList.append(column) </code></pre> <p>cheers</p>
1
2016-10-17T07:08:41Z
40,091,918
<p>Two ways: </p> <p>First, you can just access the dict's keys if you want the column list, this is basically like what you have, but shorter:</p> <pre><code>ColumnList = temp[0].keys() </code></pre> <p>Second, you can access the cursor's field list, which I think is what you are really looking for: </p> <pre><code>ColumnList = [d.name for d in cur.description] </code></pre> <p>The second one is better because it'll let you see the columns even if the result is empty. </p>
1
2016-10-17T17:02:04Z
[ "python", "vertica" ]
How can I select the "Sort By" element through Selenium Webdriver Python
40,080,506
<p>I was trying to automate one task using Selenium Webdriver with Python 2.7.The task goes as follows: 1. Open "<a href="https://www.flipkart.com" rel="nofollow">https://www.flipkart.com</a>". 2. Search for 'laptop'. 3. Hit search button. 4. Whatever is the answer of the search query, sort them "By Popularity" using the sort button.</p> <p>Code</p> <pre><code>from selenium import webdriver url="https://www.flipkart.com" xpaths={'submitButton' : "//button[@type='submit']", 'searchBox' : "//input[@type='text']"} driver=webdriver.Chrome() driver.maxmimize_window() driver.get(url) #to search for laptops driver.find_element_by_xpath(xpaths['searchBox']).clear() driver.find_element_by_xpath(xpaths['searchBox']).send_keys('laptop') driver.find_element_by_xpath(xpaths['submitButton']).click() #to sort them by popularity driver.find_element_by_xpath("////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]").click() </code></pre> <p>The last statement throws an error:</p> <pre><code>raise exception_class(message, screen, stacktrace) InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression ////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]' is not a valid XPath expression. (Session info: chrome=53.0.2785.143) (Driver info: chromedriver=2.9.248315,platform=Windows NT 6.3 x86_64) </code></pre> <p>Given I copied the xpath for that particular element "Sort By - Popularity" using the Chrome developer tools(ctrl+shift+I).</p> <p>And also, it highlights the same element when I try to search for that xpath in the console window of developer tools.</p> <p>What's wrong with the xpath? Help!</p>
0
2016-10-17T07:17:46Z
40,080,695
<p>As far as syntax error goes replace <code>////</code> with <code>//</code> in your xpath</p> <p><code>driver.find_element_by_xpath("//*@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]").click() </code></p> <p>This will resolve your syntax error and will do the required job Though In my opinion a better XPATH would be <code>driver.find_element_by_xpath("//li[text()='Popularity']").click()</code></p>
1
2016-10-17T07:29:05Z
[ "python", "selenium", "xpath" ]
How can I select the "Sort By" element through Selenium Webdriver Python
40,080,506
<p>I was trying to automate one task using Selenium Webdriver with Python 2.7.The task goes as follows: 1. Open "<a href="https://www.flipkart.com" rel="nofollow">https://www.flipkart.com</a>". 2. Search for 'laptop'. 3. Hit search button. 4. Whatever is the answer of the search query, sort them "By Popularity" using the sort button.</p> <p>Code</p> <pre><code>from selenium import webdriver url="https://www.flipkart.com" xpaths={'submitButton' : "//button[@type='submit']", 'searchBox' : "//input[@type='text']"} driver=webdriver.Chrome() driver.maxmimize_window() driver.get(url) #to search for laptops driver.find_element_by_xpath(xpaths['searchBox']).clear() driver.find_element_by_xpath(xpaths['searchBox']).send_keys('laptop') driver.find_element_by_xpath(xpaths['submitButton']).click() #to sort them by popularity driver.find_element_by_xpath("////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]").click() </code></pre> <p>The last statement throws an error:</p> <pre><code>raise exception_class(message, screen, stacktrace) InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression ////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]' is not a valid XPath expression. (Session info: chrome=53.0.2785.143) (Driver info: chromedriver=2.9.248315,platform=Windows NT 6.3 x86_64) </code></pre> <p>Given I copied the xpath for that particular element "Sort By - Popularity" using the Chrome developer tools(ctrl+shift+I).</p> <p>And also, it highlights the same element when I try to search for that xpath in the console window of developer tools.</p> <p>What's wrong with the xpath? Help!</p>
0
2016-10-17T07:17:46Z
40,080,716
<p>you can use following code.</p> <pre><code>from selenium import webdriver import time url="https://www.flipkart.com" xpaths={'submitButton' : "//button[@type='submit']", 'searchBox' : "//input[@type='text']"} driver=webdriver.Chrome() # driver.maxmimize_window() driver.get(url) #to search for laptops driver.find_element_by_xpath(xpaths['searchBox']).clear() driver.find_element_by_xpath(xpaths['searchBox']).send_keys('laptop') driver.find_element_by_xpath(xpaths['submitButton']).click() #to sort them by popularity time.sleep(5) driver.find_element_by_xpath("//li[text()='Popularity']").click() </code></pre>
0
2016-10-17T07:30:21Z
[ "python", "selenium", "xpath" ]
How can I select the "Sort By" element through Selenium Webdriver Python
40,080,506
<p>I was trying to automate one task using Selenium Webdriver with Python 2.7.The task goes as follows: 1. Open "<a href="https://www.flipkart.com" rel="nofollow">https://www.flipkart.com</a>". 2. Search for 'laptop'. 3. Hit search button. 4. Whatever is the answer of the search query, sort them "By Popularity" using the sort button.</p> <p>Code</p> <pre><code>from selenium import webdriver url="https://www.flipkart.com" xpaths={'submitButton' : "//button[@type='submit']", 'searchBox' : "//input[@type='text']"} driver=webdriver.Chrome() driver.maxmimize_window() driver.get(url) #to search for laptops driver.find_element_by_xpath(xpaths['searchBox']).clear() driver.find_element_by_xpath(xpaths['searchBox']).send_keys('laptop') driver.find_element_by_xpath(xpaths['submitButton']).click() #to sort them by popularity driver.find_element_by_xpath("////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]").click() </code></pre> <p>The last statement throws an error:</p> <pre><code>raise exception_class(message, screen, stacktrace) InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression ////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]' is not a valid XPath expression. (Session info: chrome=53.0.2785.143) (Driver info: chromedriver=2.9.248315,platform=Windows NT 6.3 x86_64) </code></pre> <p>Given I copied the xpath for that particular element "Sort By - Popularity" using the Chrome developer tools(ctrl+shift+I).</p> <p>And also, it highlights the same element when I try to search for that xpath in the console window of developer tools.</p> <p>What's wrong with the xpath? Help!</p>
0
2016-10-17T07:17:46Z
40,080,774
<p>You may try with this css selector too:</p> <pre><code>#container &gt; div &gt; div:nth-child(2) &gt; div:nth-child(2) &gt; div &gt; div:nth-child(2) &gt; div:nth-child(2) &gt; div &gt; section &gt; ul &gt; li:nth-child(2) </code></pre> <p>To me, cssSelector is better than xpath for browser compatibility too.</p>
0
2016-10-17T07:33:49Z
[ "python", "selenium", "xpath" ]
For-loop with range is only taking the last element
40,080,593
<p>I have a 2D array of strings from which I delete certain elements (those containing the '#' char). When I print <code>lista</code> from inside the loop, it prints this: </p> <pre><code>['call', '_imprimirArray'] ['movl', '24', '%2', '%3'] ['movl', '%1', '%2'] ['call', '_buscarMayor'] ['movl', '%1', '4', '%3'] ['movl', '$LC1', '%2'] ['call', '_printf'] ['movl', '$LC2', '%2'] ['call', '_system'] ['movl', '$0', '%2'] ['movl', '-4', '%2', '%3'] </code></pre> <p>But when I append each row to another 2D array, only the last element is assigned:</p> <pre><code>['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'] </code></pre> <p>Here's the loop:</p> <pre><code>def quitarEtiquetas(labels, programa): lista = [] temp = [] for i in range(0, len(programa)): del lista[:] for j in range(0, len(programa[i])): if(programa[i][j].find('#') != -1): labels.append([programa[i][j].replace('#', ''), i]) else: lista.append(programa[i][j]) print(lista) temp.append(lista) </code></pre>
1
2016-10-17T07:22:56Z
40,080,736
<p>You're appending the same row many times to <code>temp</code> while just removing items from it on each iteration. Instead of <code>del lista[:]</code> just assign a new list to the variable: <code>lista = []</code> so that content in previously added rows doesn't get overwritten.</p> <p>Effectively you're doing following:</p> <pre><code>&gt;&gt;&gt; lista = [] &gt;&gt;&gt; temp = [] &gt;&gt;&gt; lista.append('foo') &gt;&gt;&gt; temp.append(lista) &gt;&gt;&gt; temp [['foo']] &gt;&gt;&gt; del lista[:] &gt;&gt;&gt; temp [[]] &gt;&gt;&gt; lista.append('bar') &gt;&gt;&gt; temp.append(lista) &gt;&gt;&gt; temp [['bar'], ['bar']] </code></pre>
4
2016-10-17T07:31:16Z
[ "python", "arrays", "list", "python-3.x", "multidimensional-array" ]
For-loop with range is only taking the last element
40,080,593
<p>I have a 2D array of strings from which I delete certain elements (those containing the '#' char). When I print <code>lista</code> from inside the loop, it prints this: </p> <pre><code>['call', '_imprimirArray'] ['movl', '24', '%2', '%3'] ['movl', '%1', '%2'] ['call', '_buscarMayor'] ['movl', '%1', '4', '%3'] ['movl', '$LC1', '%2'] ['call', '_printf'] ['movl', '$LC2', '%2'] ['call', '_system'] ['movl', '$0', '%2'] ['movl', '-4', '%2', '%3'] </code></pre> <p>But when I append each row to another 2D array, only the last element is assigned:</p> <pre><code>['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'], ['movl', '-4', '%2', '%3'] </code></pre> <p>Here's the loop:</p> <pre><code>def quitarEtiquetas(labels, programa): lista = [] temp = [] for i in range(0, len(programa)): del lista[:] for j in range(0, len(programa[i])): if(programa[i][j].find('#') != -1): labels.append([programa[i][j].replace('#', ''), i]) else: lista.append(programa[i][j]) print(lista) temp.append(lista) </code></pre>
1
2016-10-17T07:22:56Z
40,080,839
<p>Adding to niemmi's answer, what you need to do is:</p> <pre><code> for i in range(0, len(programa)): lista = [] # creates a new empty list object alltogether ... </code></pre> <p>instead of</p> <pre><code> for i in range(0, len(programa)): del lista[:]; # only clears the content, the list object stays the same </code></pre> <p>BTW, no <code>;</code> needed in python.</p>
1
2016-10-17T07:37:35Z
[ "python", "arrays", "list", "python-3.x", "multidimensional-array" ]
How can I transfer a compiled tuple(rawly taken from Sql) in to a array, series, or a dataframe?
40,080,636
<ol> <li><p>What I have is like this:</p> <pre><code>(('3177000000000053', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 36, 42)), ('3177000000000035', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 37, 6 ))) </code></pre></li> </ol> <p>It is exactly the way it looks in mysql database.</p> <ol start="2"> <li><p>What I want is like this:</p> <pre><code>[[1,2,3], [4,5,6]] </code></pre></li> </ol> <p>It's okay to have a series, dataframe, array, list.etc. I just want it to be managable for further analysing process. I've tried several ways to deal with this such as dataframe(),list(),even pandas.replace(and it gives me a tuple-cant-be-replaced error). I'm new to python, thanks for your answers!:)))))))))</p>
1
2016-10-17T07:25:48Z
40,081,054
<p>In case you have tuple of tuples you may try the following list comprehension</p> <pre><code>import datetime input_tuple = (('3177000000000053', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 36, 42)), ('3177000000000035', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 37, 6 ))) output_list = [[i for i in j] for j in input_tuple] print(output_list) </code></pre>
0
2016-10-17T07:51:04Z
[ "python", "mysql" ]
Understanding Inheritance in python
40,080,783
<p>I am learning OOP in python.</p> <p>I am struggling why this is not working as I intended?</p> <pre><code>class Patent(object): """An object to hold patent information in Specific format""" def __init__(self, CC, PN, KC=""): self.cc = CC self.pn = PN self.kc = KC class USPatent(Patent): """"Class for holding information of uspto patents in Specific format""" def __init__(self, CC, PN, KC=""): Patent.__init__(self, CC, PN, KC="") pt1 = Patent("US", "20160243185", "A1") pt2 = USPatent("US", "20160243185", "A1") pt1.kc Out[168]: 'A1' pt2.kc Out[169]: '' </code></pre> <p>What obvious mistake I am making so that I am not able to get kc in USPatent instance?</p>
2
2016-10-17T07:34:11Z
40,080,877
<pre><code>class USPatent(Patent): """"Class for holding information of uspto patents in Specific format""" def __init__(self, CC, PN, KC=""): Patent.__init__(self, CC, PN, KC="") </code></pre> <p>Here you pass <code>KC</code>as <code>""</code> by coding <code>KC=""</code>, instead of <code>KC=KC</code></p> <p>To pass the inputted <code>KC</code>: </p> <pre><code>class USPatent(Patent): """"Class for holding information of uspto patents in Specific format""" def __init__(self, CC, PN, KC=""): Patent.__init__(self, CC, PN, KC) </code></pre>
1
2016-10-17T07:39:42Z
[ "python", "inheritance" ]