title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python - Creating a text file converting Fahrenheit to Degrees | 40,092,290 | <p>I'm new to Python and I've been given the task to create a program which uses a text file which contains figures in Fahrenheit, and then I need to change them into a text file which gives the figures in Degrees... Only problem is, I have no idea where to start.
Any advice?</p>
| 0 | 2016-10-17T17:26:25Z | 40,092,506 | <p>I'd start making a python script file (a text file with *.py), and write an expression that <a href="https://docs.python.org/3/tutorial/inputoutput.html" rel="nofollow">opens</a> your text file. You'll need to do some operations on <a href="https://www.tutorialspoint.com/python/python_strings.htm" rel="nofollow">str... | 1 | 2016-10-17T17:39:56Z | [
"python"
] |
FileNotFoundError When file exists (when created in current script) | 40,092,293 | <p>I am trying to create a secure (e.g., SSL/HTTPS) XML-RPC Client Server. The client-server part works perfectly when the required certificates are present on my system; however, when I try to <strong>create</strong> the certificates during execution, I receive a <strong>FileNotFoundError</strong> when opening the ssl... | 0 | 2016-10-17T17:26:34Z | 40,121,138 | <p>The problem contained in the above stems from the use of <code>os.chdir(rootdir)</code> as suggested by John; however, the specifics are slightly different than the created files being in the wrong location. The problem is the current working directory (cwd) of the running program being changed by <code>gencert()</c... | 0 | 2016-10-19T02:34:58Z | [
"python",
"file-not-found"
] |
Creating a matplotlib or seaborn histogram which uses percent rather than count? | 40,092,294 | <p>Specifically I'm dealing with the Kaggle Titanic dataset. I've plotted a stacked histogram which shows ages that survived and died upon the titanic. Code below.</p>
<pre><code>figure = plt.figure(figsize=(15,8))
plt.hist([data[data['Survived']==1]['Age'], data[data['Survived']==0]['Age']], stacked=True, bins=30, la... | 2 | 2016-10-17T17:26:37Z | 40,092,428 | <p><code>pd.Series.hist</code> uses <code>np.histogram</code> underneath.</p>
<p>Let's explore that</p>
<pre><code>np.random.seed([3,1415])
s = pd.Series(np.random.randn(100))
d = np.histogram(s, normed=True)
print('\nthese are the normalized counts\n')
print(d[0])
print('\nthese are the bin values, or average of the... | 2 | 2016-10-17T17:35:30Z | [
"python",
"pandas",
"matplotlib",
"dataset",
"histogram"
] |
Creating a matplotlib or seaborn histogram which uses percent rather than count? | 40,092,294 | <p>Specifically I'm dealing with the Kaggle Titanic dataset. I've plotted a stacked histogram which shows ages that survived and died upon the titanic. Code below.</p>
<pre><code>figure = plt.figure(figsize=(15,8))
plt.hist([data[data['Survived']==1]['Age'], data[data['Survived']==0]['Age']], stacked=True, bins=30, la... | 2 | 2016-10-17T17:26:37Z | 40,101,292 | <p>First of all it would be better if you create a function that splits your data in age groups</p>
<pre><code># This function splits our data frame in predifined age groups
def cutDF(df):
return pd.cut(
df,[0, 10, 20, 30, 40, 50, 60, 70, 80],
labels=['0-10', '11-20', '21-30', '31-40', '41-50', '5... | 0 | 2016-10-18T06:45:07Z | [
"python",
"pandas",
"matplotlib",
"dataset",
"histogram"
] |
Im trying to write a program that reverses the order of values in an input file using a stack and saves the result to a file | 40,092,295 | <pre><code>def main():
fname = input("Please input file name: ")
# open input file
fin = open(fname, "r")
# open output file
fout = open("output.txt", "w")
for line in fin:
token = Stack()
if token:
token.pop()
fout.write(items)
fout.write("\n")
fin.close()
fout.close()
</code><... | -6 | 2016-10-17T17:26:37Z | 40,093,000 | <p>Instead of <code>if token:</code> try using <code>if !token.isEmpty():</code></p>
| 0 | 2016-10-17T18:11:55Z | [
"python",
"python-3.x"
] |
Python - Making text files | 40,092,304 | <p>I seem to be having various problems with my code. Firstly I cannot split the text that the user inputs. </p>
<p>E.g. if they type <code>bob</code> for their name, <code>ha8 9qy</code> for their postcode and <code>17/03/10</code> for their date of birth, the program will return <code>"bobha8 9qy17/03/10"</code>. </... | -1 | 2016-10-17T17:27:19Z | 40,140,759 | <p>You have to add the <code>.txt</code> afther the filename. Also be sure that the file is in the same folder of the <code>.py</code> file. Pay attention to caps and spaces.</p>
<p><code>pythonfile = open("User details.txt","w")</code></p>
<p>If this does'nt work, try adding <code>os.chdir(os.path.dirname(os.path.ab... | 0 | 2016-10-19T20:17:13Z | [
"python",
"tkinter"
] |
Python Tkinter Canvas Many create_window() Items Not Scrolling with Scrollbar | 40,092,309 | <p>Why doesn't the scrollbar initiate when <code>create_window</code> frame objects start to exceed the bottom <code>self.container</code> window?</p>
<p>My understanding is that widgets are scrollable if they are embedded on the canvas using <code>create_window</code>. For context, I don't want to create a scrolling ... | 0 | 2016-10-17T17:27:32Z | 40,093,373 | <p>You must re-configure <code>scrollregion</code> when you add items to the canvas.</p>
| 0 | 2016-10-17T18:36:17Z | [
"python",
"tkinter",
"scrollbar",
"tkinter-canvas"
] |
Updating transformer parameters after grid search on Pipeline | 40,092,437 | <p>I have a simple Pipeline for text analysis and classification consisting of a CountVectorizer, a TfidfTransformer, and finally a Multinomial Naive Bayes classifier. </p>
<pre><code>from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklear... | 0 | 2016-10-17T17:36:01Z | 40,096,149 | <p>The Pipeline with the best parameters can be found with <code>grid_clf.best_estimator_</code></p>
<pre><code>grid_clf.best_estimator_
Pipeline(steps=[('vect', CountVectorizer(analyzer='word', binary=False, decode_error='strict',
dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',
lowercas... | 0 | 2016-10-17T21:42:00Z | [
"python",
"scikit-learn",
"pipeline",
"grid-search"
] |
What is the fastest way to get all pairwise combinations in an array in python? | 40,092,474 | <p>For example, if the array is [1,2,3,4]
I want the output to be [1,2],[1,3],[1,4],[2,3],[2,4],[3,4]
I want a solution which is better than the brute force method of using two for loops.</p>
| 0 | 2016-10-17T17:38:06Z | 40,092,500 | <pre><code>import itertools
x = [1,2,3,4]
for each in itertools.permutations(x,2):
print(each)
</code></pre>
<p>Note that itertools is a generator object, meaning you need to iterate through it to get all you want. The '2' is optional, but it tells the function whats the number per combonation you want. </p>
<... | 4 | 2016-10-17T17:39:21Z | [
"python",
"arrays"
] |
What is the fastest way to get all pairwise combinations in an array in python? | 40,092,474 | <p>For example, if the array is [1,2,3,4]
I want the output to be [1,2],[1,3],[1,4],[2,3],[2,4],[3,4]
I want a solution which is better than the brute force method of using two for loops.</p>
| 0 | 2016-10-17T17:38:06Z | 40,092,582 | <p>Though the previous answer will give you all pairwise orderings, the example expected result seems to imply that you want all <em>unordered</em> pairs. </p>
<p>This can be done with <code>itertools.combinations</code>:</p>
<pre><code>>>> import itertools
>>> x = [1,2,3,4]
>>> list(iterto... | 3 | 2016-10-17T17:44:49Z | [
"python",
"arrays"
] |
Maintaining Data Associations in a Dictionary with Multiple Lines per Key | 40,092,497 | <p>I have a data set from a baseball team that I want to analyze in one of my first Python programming experiences (coming from C++). However, the dataset has a more complex structure than my previous simple examples that I'd like to know the best (most pythonic) way to capture. The main difficulty is that the each pla... | 0 | 2016-10-17T17:39:13Z | 40,092,690 | <p>Seems like you want a dictionary of dictionaries. Something like:</p>
<pre><code>playerData = {
'JimBob01': {
'2009': ... // player data here
'2010': ...
}
}
</code></pre>
<p>You can then look up the data for a particular year as you want by doing <code>playerData['JimBob01']['2009']</code></p>
<p>Dep... | 1 | 2016-10-17T17:52:02Z | [
"python",
"dictionary"
] |
Unsupported operand type(s) for %: 'NoneType' and 'tuple' | 40,092,556 | <p>I am getting this error:</p>
<blockquote>
<p>TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'</p>
</blockquote>
<p>What do I need to change to fix this?</p>
<pre><code>string_1 = "Sean";
string_2 = "beginner programmer";
print("Hi my name is %s, I\'m a %s.") % (string_1,string_2);
</code></... | 0 | 2016-10-17T17:43:23Z | 40,092,584 | <p><code>print</code> returns <code>None</code>, you must format the string <em>before</em> printing it</p>
<pre><code>print("Hi my name is %s, I\'m a %s." % (string_1, string_2))
</code></pre>
| 3 | 2016-10-17T17:44:54Z | [
"python"
] |
Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? | 40,092,570 | <p>so I'm on Python 3.5.2, I'm trying to install scrapy, it throws an error saying</p>
<blockquote>
<p>Failed building wheel for lxml <br> Could not find function
xmlCheckVersion in library libxml2. Is libxml2 installed?</p>
</blockquote>
<p>So I try installing lxml, it throws the same error. I try installing it ... | 1 | 2016-10-17T17:44:12Z | 40,093,274 | <p>try this first</p>
<p>pip install lxml==3.6.0</p>
| 0 | 2016-10-17T18:30:04Z | [
"python",
"scrapy"
] |
String being mutated to a dictionary but can't figure out where | 40,092,681 | <p>I'm trying to implement a scrabble type game and the function playHand is returning an AttributeError: 'str' object has no attribute 'copy'. The error comes from updateHand Hand = Hand.copy(), but I've tested updateHand individually and works just fine on its ow. I've tried looking it up, but never really found any... | 1 | 2016-10-17T17:51:06Z | 40,092,843 | <p>Your passed-in arguments to <code>updateHand()</code> are reversed from the expected arguments:</p>
<p>line 161:</p>
<pre><code>hand_copy = updateHand(word, hand_copy)
</code></pre>
<p>Line 49:</p>
<pre><code>def updateHand(hand, word):
</code></pre>
<p>Notice that <code>updateHand</code> expects a hand to be t... | 2 | 2016-10-17T18:02:15Z | [
"python",
"string",
"dictionary",
"semantics"
] |
Slicing a range of elements in each sublist? | 40,092,686 | <p>I suspect there are more than one ways to do this in Python 2.7, but I'd like to be able to print the first three elements of each sublist in combos. Is there a way to do this without a loop? </p>
<pre><code>combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ]
</code></pre>
<p>such that the output of ... | 0 | 2016-10-17T17:51:21Z | 40,092,694 | <pre><code>[sublist[:3] for sublist in combos]
</code></pre>
| 2 | 2016-10-17T17:52:23Z | [
"python",
"list",
"list-comprehension",
"slice"
] |
Slicing a range of elements in each sublist? | 40,092,686 | <p>I suspect there are more than one ways to do this in Python 2.7, but I'd like to be able to print the first three elements of each sublist in combos. Is there a way to do this without a loop? </p>
<pre><code>combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ]
</code></pre>
<p>such that the output of ... | 0 | 2016-10-17T17:51:21Z | 40,092,698 | <pre><code>print [temp_list[:3] for temp_list in combos]
</code></pre>
| 2 | 2016-10-17T17:52:39Z | [
"python",
"list",
"list-comprehension",
"slice"
] |
Slicing a range of elements in each sublist? | 40,092,686 | <p>I suspect there are more than one ways to do this in Python 2.7, but I'd like to be able to print the first three elements of each sublist in combos. Is there a way to do this without a loop? </p>
<pre><code>combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ]
</code></pre>
<p>such that the output of ... | 0 | 2016-10-17T17:51:21Z | 40,093,354 | <blockquote>
<p>I suspect there are more than one ways to do this in Python 2.7</p>
</blockquote>
<p>Yes and you can be quite creative with it. This is another alternative</p>
<pre><code>from operator import itemgetter
map(itemgetter(slice(3)), combos)
Out[192]: [[1, 2, 3], [5, 6, 7], [9, 10, 11], [1, 2, 3]]
</cod... | 0 | 2016-10-17T18:35:03Z | [
"python",
"list",
"list-comprehension",
"slice"
] |
How I order behavior IDublinCore in Dexterity Type? | 40,092,789 | <p>I'm writing a product using Python Dexterity Type, and I have <code>Title</code> and <code>Description</code>, this fields come from a behavior <code>plone.app.dexterity.behaviors.metadata.IDublinCore</code>, but I neeed reorder this fields with my fields.</p>
<p>Example:</p>
<p>My fields: document, collage, age, ... | 5 | 2016-10-17T17:58:45Z | 40,110,683 | <p>How about using Jquery? (Since the fieldsets are using Jquery anyway)</p>
<p>For example to move Tags under Summary....</p>
<pre><code>$('body.template-edit.portaltype-document #formfield-form-widgets-IDublinCore-subjects').insertAfter('#formfield-form-widgets-IDublinCore-description')
</code></pre>
<p>Note: This... | -1 | 2016-10-18T14:16:44Z | [
"python",
"plone",
"zope",
"dexterity",
"plone-4.x"
] |
How I order behavior IDublinCore in Dexterity Type? | 40,092,789 | <p>I'm writing a product using Python Dexterity Type, and I have <code>Title</code> and <code>Description</code>, this fields come from a behavior <code>plone.app.dexterity.behaviors.metadata.IDublinCore</code>, but I neeed reorder this fields with my fields.</p>
<p>Example:</p>
<p>My fields: document, collage, age, ... | 5 | 2016-10-17T17:58:45Z | 40,125,462 | <p>Since you got your own Dexterity Type you can handle with <code>form directives</code> aka <code>setting taggedValues</code> on the interface.</p>
<pre><code>from plone.autoform import directives
class IYourSchema(model.Schema):
directives.order_before(collage='IDublinCore.title')
collage = schema.TextLi... | 3 | 2016-10-19T08:00:35Z | [
"python",
"plone",
"zope",
"dexterity",
"plone-4.x"
] |
How to clear dump (AndroidViewClient/Culebra) data from memory? | 40,092,797 | <p>I'm running an automated test script using AndroidViewClient. I do several dumps in the script. The script is used for a speed/response time test on an android device and the test is run for n>300. I get the following error at run #150.</p>
<p><strong>raise ValueError("received does not contain valid XML: " + recei... | 0 | 2016-10-17T17:59:09Z | 40,099,745 | <p>What you describe seems like an issue with <code>uiautomator dump</code> (probably your device implementation) which is what <strong>AndroidViewClient</strong> uses as the default backend for API >= 19.</p>
<p>However, to be absolutely sure you should remove AndroidViewClient from the picture and run the same comma... | 1 | 2016-10-18T04:49:22Z | [
"android",
"python",
"dump",
"androidviewclient"
] |
Compute sum of the elements in a chunk of a dask array | 40,092,808 | <p>I'd like to apply a function to each block and return a single element, for example, from a 10x10 matrix I'd like to sum each 2x2 block.</p>
<p>I've tried some combinations of what you see below but I always get an <code>IndexError</code>.</p>
<pre><code>m = da.from_array(np.ones((10,10)), chunks=(2,2))
def comput... | 1 | 2016-10-17T18:00:01Z | 40,092,963 | <p>Using the default settings <code>map_blocks</code> assumes that the user-provided function returns a numpy array of the same number of dimensions as the input. So you can get your example above to work by adding in a second empty dimension to your <code>compute_block_sum</code> function using numpy slicing with <co... | 1 | 2016-10-17T18:09:02Z | [
"python",
"dask"
] |
Python Ctypes memory allocation for c function | 40,092,818 | <p>I currently have a python callback function that calls a c function using ctypes library. The c function requires a pointer to a structure for example animal_info_s. I instantiate the structure and pass it as a pointer to the c function and it works. The issue I'm having is when I have multiple threads calling the c... | 0 | 2016-10-17T18:00:46Z | 40,098,908 | <p>The following line should be removed. It redefines the name <code>animal_info_s</code> as a <code>class animal_info_s</code> instance, which then hides the class.</p>
<pre><code>animal_info_s = animal_info_s()
</code></pre>
<p>The following line should be changed from:</p>
<pre><code>animal_info_p = animal_info... | 2 | 2016-10-18T03:12:32Z | [
"python",
"memory-management",
"ctypes"
] |
How do I make the combobox update? | 40,092,890 | <pre><code># IMPORT MODULES -----------------------------------------------------------
from tkinter import *
from tkinter import Tk, StringVar, ttk
#---------------------------------------------------------------------------
# LISTS
</code></pre>
<p><strong>Here are the lists which are used in the comboboxes</strong... | 0 | 2016-10-17T18:04:35Z | 40,100,458 | <p>You have to add function name to bind</p>
<pre><code>CarBrandBox.bind("<<ComboboxSelected>>", ModelSelectionFunction)
</code></pre>
<p>and tkinter executes it when you select in combobox.</p>
<p>Because <code>tkinter</code> sends extra argument to binded function so you need to receive it in your func... | 0 | 2016-10-18T05:47:49Z | [
"python",
"python-3.x",
"user-interface",
"tkinter",
"combobox"
] |
Adding a column which increment for every index which meets a criteria on another column | 40,092,894 | <p>I am trying to generate a column from a DataFrame to base my grouping on. I know that every NaN column under a non NaN one belong to the same group. So I wrote this loop (cf below) but I was wondering if there was a more pandas/pythonic way to write it with apply or a comprehension list.</p>
<pre><code>import panda... | 0 | 2016-10-17T18:04:49Z | 40,092,932 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.notnull.html" rel="nofollow"><code>pd.notnull</code></a> to identify non-NaN values. Then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.cumsum.html" rel="nofollow"><code>cumsum</code></a> to create the <co... | 2 | 2016-10-17T18:07:17Z | [
"python",
"pandas"
] |
AH00112: Warning - Centos 6 / Apache 2.4 / Django 1.9 / mod_wsgi 3.5 / python 2.7 | 40,092,913 | <p>I have a dedicated server with GoDaddy. I seem to have successfully set up everything properly but I can't seem to figure out why I'm getting this issue:</p>
<p>When I restart apache:</p>
<pre><code>[root@sXXX-XXX-XXX-XXX /]# /scripts/restartsrv httpd
</code></pre>
<p>I get this:</p>
<pre><code>AH00112: Warning... | 0 | 2016-10-17T18:06:04Z | 40,094,703 | <p>This would indicate you have set <code>DocumentRoot</code> directive somewhere in your Apache configuration files to a path that does not have a leading slash. When that occurs Apache will append the path to the end of the <code>ServerRoot</code> directory which in your case is <code>/usr/local/apache</code>. Make s... | 0 | 2016-10-17T20:01:59Z | [
"python",
"django",
"apache",
"python-2.7",
"mod-wsgi"
] |
Error when converting string to date object from command line in Python | 40,093,046 | <p>When I run the following code, I don't see any problems:</p>
<pre><code>as_of_date = '10-16-17'
today = datetime.datetime.strptime(as_of_date, '%m-%d-%y').date()
type(today)
print(today)
Out: datetime.date
Out: 2017-10-16
</code></pre>
<p>However, when I run a script named <code>GetStats.py</code> that takes se... | -1 | 2016-10-17T18:15:31Z | 40,093,150 | <p>The problem is with your import:</p>
<p><code>from datetime import datetime</code> and then you try to call <code>datatime.datetime.strptime</code></p>
<p>By doing this, you're trying to call the function <code>datetime.datetime.datetime.strptime</code> which doesn't exist.</p>
<p>Therefore, to fix this change <c... | 2 | 2016-10-17T18:22:06Z | [
"python",
"datetime"
] |
How to write sumation in IBM CPLEX Python API | 40,093,162 | <p>I am new to Cplex Python APIs, but I worked with Cplex OPL, in OPL, you can easily write this objective function Max [sum C_ij*X_ij] as:</p>
<p>Maximize
sum(i in set1,j in set2) C_ij*X_ij</p>
<p>if we want to use python API, we have to define it in vector format Max C*X, which C and X are both vectors of coefficie... | 0 | 2016-10-17T18:22:47Z | 40,094,014 | <p>The <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.6.3/ilog.odms.cplex.help/refpythoncplex/html/help.html?pos=2" rel="nofollow">CPLEX Python API</a> does not support this, but the <a href="https://developer.ibm.com/docloud/documentation/optimization-modeling/modeling-for-python/" rel="nofollow">DOcple... | 0 | 2016-10-17T19:17:00Z | [
"python",
"cplex"
] |
Updating missing letters in hangman game | 40,093,203 | <p>I'm making a hangman game and have found a problem with my methodology for updating the answer. I have a variable that adds underscores equal to the amount of letters in the word the player needs to guess. However I can't figure out how to effectively update that when the player guesses a correct letter.</p>
<p>Her... | 0 | 2016-10-17T18:25:09Z | 40,093,261 | <p>You probably need to reword your question as it's not clear what you are asking. But you should look into string splicing. If they guessed the letter "a" and it goes in the third slot then you could do something like</p>
<pre><code>underscores[:2] + 'a' + underscores[3:]
</code></pre>
<p>adapt for your code but ... | 2 | 2016-10-17T18:29:20Z | [
"python",
"set"
] |
Updating missing letters in hangman game | 40,093,203 | <p>I'm making a hangman game and have found a problem with my methodology for updating the answer. I have a variable that adds underscores equal to the amount of letters in the word the player needs to guess. However I can't figure out how to effectively update that when the player guesses a correct letter.</p>
<p>Her... | 0 | 2016-10-17T18:25:09Z | 40,093,719 | <p>Another possible approach (in Python 2.7, see below for 3):</p>
<pre><code>trueword = "shipping"
guesses = ""
def progress():
for i in range(len(trueword)):
if trueword[i] in guesses:
print trueword[i],
else:
print "-",
print ""
</code></pre>
<p>This works by checki... | 1 | 2016-10-17T18:59:14Z | [
"python",
"set"
] |
Reading through a bunch of .gz files error: Error -3 while decompressing: invalid code lengths set | 40,093,369 | <p>I am trying to parse a bunch of .gz json files (the files are text files) by using the same function using multiprocessing in Python 2.7.10. However, almost at the very end of parsing each line in these files, it produces this error:</p>
<p><code>error: Error -3 while decompressing: invalid code lengths set</code><... | 0 | 2016-10-17T18:36:10Z | 40,093,543 | <p>Read in binary mode:</p>
<pre><code>gzip.open(file_name, "rb")
</code></pre>
<p>Reading in text mode may mangle the data (as it is not text) on some platforms, and will cause odd errors such as this.</p>
| 0 | 2016-10-17T18:47:44Z | [
"python",
"json",
"python-2.7",
"multiprocessing",
"gzip"
] |
Reading through a bunch of .gz files error: Error -3 while decompressing: invalid code lengths set | 40,093,369 | <p>I am trying to parse a bunch of .gz json files (the files are text files) by using the same function using multiprocessing in Python 2.7.10. However, almost at the very end of parsing each line in these files, it produces this error:</p>
<p><code>error: Error -3 while decompressing: invalid code lengths set</code><... | 0 | 2016-10-17T18:36:10Z | 40,133,859 | <p>I ended up using a try block that checks the integrity of every line in the pointer when reading. So the final code looks like this:</p>
<pre><code>def build_list(file_name):
count = 0
try:
json_file = gzip.open(file_name, "r")
except Exception as e:
print e
else:
try:
... | 0 | 2016-10-19T14:12:19Z | [
"python",
"json",
"python-2.7",
"multiprocessing",
"gzip"
] |
Python Script locked for debug in VS 2015 | 40,093,463 | <p>I'm doing the nucleai courses. Exercises are based on python scripts and I'm using Visual Studio 2015. At some point, we have to use the library nltk. I was trying to debug some code I'm calling (I have the source) and something really weird happens: breakpoints work, but I can't use F10 to jump line to line. It jus... | 0 | 2016-10-17T18:42:45Z | 40,120,240 | <p>Other members also got the similar issue, my suggestion is that you can use the PyCharm instead of PTVS as a workaround. Of course, you could also start a discussion(Q AND A) from this site for PTVS tool:</p>
<p><a href="https://visualstudiogallery.msdn.microsoft.com/9ea113de-a009-46cd-99f5-65ef0595f937" rel="nofol... | 1 | 2016-10-19T00:40:50Z | [
"python",
"python-3.x",
"visual-studio-2015",
"visual-studio-debugging"
] |
Only show value of n*n matrix if value from another n*n has a certain value (Python) | 40,093,475 | <p>So I'm currently trying to calculate the Pearson's R and p-value for some data I have. This is done by this code:</p>
<pre><code>import numpy as np
from scipy.stats import pearsonr, betai
from pandas import DataFrame
import seaborn as sns
import matplotlib.pyplot as plt
def corrcoef(matrix): #function that calcula... | 0 | 2016-10-17T18:43:39Z | 40,093,665 | <p>I think what you're saying is this:</p>
<pre><code>p_mat[r_mat < 0.95] = np.nan
</code></pre>
<p>This works because <code>p</code> and <code>r</code> are the same shape. It would go into your code instead of:</p>
<pre><code>if r_mat[abs(r_mat) <= .90] == np.nan:
p_mat = np.nan
</code></pre>
<p>Note if... | 2 | 2016-10-17T18:55:37Z | [
"python",
"numpy",
"matplotlib",
"scipy",
"seaborn"
] |
find a number is between which range in a list of list | 40,093,530 | <p>Need some python help, I have a list: </p>
<pre><code>[[sql1, 1, 10], [sql2, 12, 16]...]
</code></pre>
<p>I want to know if 15 is in the sql2, please let me know in python the easy way. </p>
<p>I have tried in the loop. </p>
| -2 | 2016-10-17T18:47:03Z | 40,093,634 | <p>You're going to have to give a few more details about your desired implementation, but this was too fun not to answer. </p>
<p>My answer assumes:</p>
<ol>
<li>You want a list of the beginning strings (<code>index == 0</code>) of the sublists whose:</li>
<li>2nd and 3rd elements contain <code>15</code> in the range... | 2 | 2016-10-17T18:53:58Z | [
"python"
] |
find a number is between which range in a list of list | 40,093,530 | <p>Need some python help, I have a list: </p>
<pre><code>[[sql1, 1, 10], [sql2, 12, 16]...]
</code></pre>
<p>I want to know if 15 is in the sql2, please let me know in python the easy way. </p>
<p>I have tried in the loop. </p>
| -2 | 2016-10-17T18:47:03Z | 40,093,638 | <p>First, lest solve for the simplest solution and then look into making something generic out of it.</p>
<pre><code>test_data = [['sql', 1, 10],['sql2', 12, 16, 15]]
print(15 in test_data[1]) # True
</code></pre>
<p>We can even generalize it into a function </p>
<pre><code>def in_data(data_sets, data, check_in):
... | 1 | 2016-10-17T18:54:09Z | [
"python"
] |
find a number is between which range in a list of list | 40,093,530 | <p>Need some python help, I have a list: </p>
<pre><code>[[sql1, 1, 10], [sql2, 12, 16]...]
</code></pre>
<p>I want to know if 15 is in the sql2, please let me know in python the easy way. </p>
<p>I have tried in the loop. </p>
| -2 | 2016-10-17T18:47:03Z | 40,093,658 | <p>I have hard coded the data to meet the question requirements but the
answer can be modified as required</p>
<pre><code>my_list = [['sql1', 1, 10], ['sql2', 12, 16]]
for i in range(len(my_list)):
print(my_list[i])
if my_list[i][0] == 'sql1':
if '15' in my_list[i][0]:
print("found")
... | 1 | 2016-10-17T18:55:11Z | [
"python"
] |
PyQt5 : how to Sort a QTableView when you click on the headers of a QHeaderView? | 40,093,561 | <p>I want to sort a QTableView when I click on the headers of my QHeaderView. I've found a several code sample on the internet like this one: <a href="http://stackoverflow.com/questions/28660287/sort-qtableview-in-pyqt5">Sort QTableView in pyqt5</a>
but it doesn't work for me. I also look in the Rapid Gui programming ... | 0 | 2016-10-17T18:48:44Z | 40,104,722 | <p>Your sort function is the problem, you are not using the pandas <code>DataFrame</code> sorting functions, and <code>self.data</code> become a python <code>list</code>, then other functions fail and the program crash.</p>
<p>To correctly sort the <code>DataFrame</code> use the <a href="http://pandas.pydata.org/panda... | 0 | 2016-10-18T09:38:42Z | [
"python",
"sorting",
"pyqt5",
"qtableview",
"qheaderview"
] |
My program doesn't check if there's a duplicate inside a string correctly | 40,093,614 | <p>I have to do a program that check if there's a duplicate digit inside a 4 number string.
The problem is that like 80% of the times the program classifies as not valid also number which aren't wrong.</p>
<pre><code>import random
def extraction():
random_number = str(random.randint(1000,9999))
print(random_nu... | -2 | 2016-10-17T18:52:44Z | 40,093,708 | <p>Why don't you make a <code>set()</code> out of the number string and evaluate the length of the set? If there are duplicate digits, only one entry will be stored in the set</p>
<pre><code>if len(set(str(random_number))) == 4:
pass #you have 4 unique digits
</code></pre>
<p>Example of working principle:</p>
<pr... | 4 | 2016-10-17T18:58:34Z | [
"python"
] |
My program doesn't check if there's a duplicate inside a string correctly | 40,093,614 | <p>I have to do a program that check if there's a duplicate digit inside a 4 number string.
The problem is that like 80% of the times the program classifies as not valid also number which aren't wrong.</p>
<pre><code>import random
def extraction():
random_number = str(random.randint(1000,9999))
print(random_nu... | -2 | 2016-10-17T18:52:44Z | 40,093,718 | <p>Why not use the <code>str.count()</code> function?</p>
<pre><code>def extraction():
random_number = str(random.randint(1000,9999))
print(random_number)
if any([random_number.count(i)>1 for i in random_number]):
print("The extracted number is not valid.\n")
extraction()
</code></pre>
| 0 | 2016-10-17T18:59:05Z | [
"python"
] |
Align image columns by max value | 40,093,627 | <p>I have an image where I would like to offset each column so that the maximum value of each column is vertically centered in the image. Here's some toy data:</p>
<pre><code>unaligned = np.array([[0,0,1,2,3,2,1,0,0,0],
[0,0,0,1,2,3,2,1,0,0],
[0,1,2,3,4,3,2,1,0,0],
... | 0 | 2016-10-17T18:53:42Z | 40,094,191 | <p>Here's an approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p>
<pre><code>m,n = unaligned.shape
col_shifts = m//2 - unaligned.argmax(0)
row_idx = np.mod(np.arange(m)[:,None]-col_shifts,m)
aligned_out = unaligned[row_idx,np.arange(n... | 1 | 2016-10-17T19:28:40Z | [
"python",
"numpy",
"image-processing"
] |
Python matplotlib: How can I draw an errorbar graph without lines and points? | 40,093,641 | <p>I am currently using the following code to plot errorbar graphs.</p>
<pre><code>plt.errorbar(log_I_mean_, log_V2_mean_, xerr, yerr, '.')
</code></pre>
<p>However the end result shows a circular point in the centre of each errorbar intersection point. How can I plot just the errorbars without the central point, as ... | 0 | 2016-10-17T18:54:14Z | 40,110,158 | <p>use <code>'none'</code> instead of <code>'.'</code>:</p>
<pre><code>import matplotlib.pyplot as plt
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
yerr = 0.1 + 0.2*np.sqrt(x)
xerr = 0.1 + yerr
plt.figure()
plt.errorbar(x, y, 0.2, 0.4,'none')
plt.title("Simplest errorbars, 0.2 in x, 0.4 in y")
</code></pre>
<p>result... | 2 | 2016-10-18T13:52:43Z | [
"python",
"matplotlib"
] |
Python split lines from read file and write them with another format in another file | 40,093,696 | <p>I read the lines from a file which containing two columns with values in that style:</p>
<pre><code> 100.E-03 5.65581E-06
110.E-03 11.222E-06
120.E-03 18.3487E-06
130.E-03 15.6892E-06
</code></pre>
<p>I need to write them in antoher file as:</... | -1 | 2016-10-17T18:57:21Z | 40,093,820 | <p><code>split</code> will automatically deal with any number of spaces. </p>
<pre><code>' 100.E-03 5.65581E-06'.split() == ['100.E-03', '5.65581E-06']
</code></pre>
| 1 | 2016-10-17T19:04:47Z | [
"python",
"csv",
"split",
"pick"
] |
Python split lines from read file and write them with another format in another file | 40,093,696 | <p>I read the lines from a file which containing two columns with values in that style:</p>
<pre><code> 100.E-03 5.65581E-06
110.E-03 11.222E-06
120.E-03 18.3487E-06
130.E-03 15.6892E-06
</code></pre>
<p>I need to write them in antoher file as:</... | -1 | 2016-10-17T18:57:21Z | 40,093,849 | <p>I'm not sure why you want that many spaces between your columns but you can just split on whitespace:</p>
<pre><code>with open('file1.txt') as f1, open('file2.txt', 'w') as f2:
for line in f1:
f2.write(line.split()[0] + ',' + line.split()[1] + '\n')
</code></pre>
<p>If you really want a bunch of spaces... | 2 | 2016-10-17T19:06:41Z | [
"python",
"csv",
"split",
"pick"
] |
Python writing to terminal for no apparent reason? | 40,093,816 | <p>I have a fairly straightforward python (3.5.2) script, which reads from a file, and if the line meets certain criteria, then it copies the line into another one. The original file looks like this (this is one line, many more follow, in the same format but different numbers):</p>
<blockquote>
<p>2.9133 1 1 157.657... | -1 | 2016-10-17T19:04:38Z | 40,093,883 | <p>This is a normal behavior when you do <code>.write</code> on a file like that. It's the number of bytes written to the file.</p>
<pre><code>>>> a = open("new.txt", 'w')
>>> a.write("hello")
5
</code></pre>
<p>There's probably a more elegant solution, but you could suppress this by setting a varia... | 1 | 2016-10-17T19:09:11Z | [
"python"
] |
Python Error: Not all arguments converted during string formatting | 40,093,895 | <pre><code>def process_cars(text_file):
total_cmpg = 0
for line in text_file:
if((line % 2) == 0):
city_mpg = (line[52:54])
print(city_mpg)
city_mpg = int(city_mpg)
total_cmpg += city_mpg
print ("Total miles per gallon in the city:", total_cmpg)
</code... | 0 | 2016-10-17T19:09:58Z | 40,094,159 | <pre><code>def process_cars(text_file):
total_cmpg = 0
for file_line_number, line in enumerate(text_file):
if((file_line_number % 2) == 0):
city_mpg = (line[52:54])
print(city_mpg)
city_mpg = int(city_mpg)
total_cmpg += city_mpg
print ("Total miles per... | 0 | 2016-10-17T19:26:55Z | [
"python",
"python-3.x"
] |
Basic Python functions. beginner | 40,093,939 | <p>This is all I have so far : </p>
<pre><code>def anagram(str1, str2):
print("String 1 : %s" %str1)
print("String 2 : %s" %str2)
s1 = sorted(str1.lower())
s2 = sorted(str2.lower())
if s1 == s2:
print("This is an anagram")
return True
def test_anagram():
print( "\n** Testin... | -4 | 2016-10-17T19:12:28Z | 40,093,992 | <p>You're treating <code>str1</code> and <code>str2</code> like functions, when you're really just passing <code>str</code> objects, which, according to your error, are not callable (i.e. don't work as functions).</p>
<p>Are you trying to accept input? If so, use <code>str1 = input("String 1 : ")</code> and so on.</p>... | 4 | 2016-10-17T19:15:05Z | [
"python",
"function",
"basic"
] |
Basic Python functions. beginner | 40,093,939 | <p>This is all I have so far : </p>
<pre><code>def anagram(str1, str2):
print("String 1 : %s" %str1)
print("String 2 : %s" %str2)
s1 = sorted(str1.lower())
s2 = sorted(str2.lower())
if s1 == s2:
print("This is an anagram")
return True
def test_anagram():
print( "\n** Testin... | -4 | 2016-10-17T19:12:28Z | 40,094,067 | <p>Fixed your code based on what I thought you wanted to do with some comments on what was changed and why:</p>
<pre><code>def anagrams(str1, str2):
print("String 1 : %s" %str1) #you wanted to print it right this is how you can format the string with variables
print("String 2 : %s" %str2) #you wanted to print ... | 3 | 2016-10-17T19:20:55Z | [
"python",
"function",
"basic"
] |
Pandas DataFrame insert / fill missing rows from previous dates | 40,093,971 | <p>I have a <code>DataFrame</code> consisting of <code>date</code>s, other columns and a numerical value, where some value combinations in "other columns" could be missing, and I want to populate them from previous <code>date</code>s.</p>
<p>Example. Say the <code>DataFrame</code> is like below. You can see on <code>2... | 0 | 2016-10-17T19:13:59Z | 40,094,956 | <p>You can use a <code>unstack</code>/<code>stack</code> method to get all missing values, followed by a forward fill:</p>
<pre><code># Use unstack/stack to add missing locations.
df = df.set_index(['date', 'location', 'band']) \
.unstack(level=['location', 'band']) \
.stack(level=['location', 'band'], d... | 0 | 2016-10-17T20:18:23Z | [
"python",
"pandas",
"dataframe"
] |
Pandas DataFrame insert / fill missing rows from previous dates | 40,093,971 | <p>I have a <code>DataFrame</code> consisting of <code>date</code>s, other columns and a numerical value, where some value combinations in "other columns" could be missing, and I want to populate them from previous <code>date</code>s.</p>
<p>Example. Say the <code>DataFrame</code> is like below. You can see on <code>2... | 0 | 2016-10-17T19:13:59Z | 40,094,965 | <p>My solution, in summary using the product operation to get all the combinations in a multi index, then some stacking and ffill().</p>
<pre><code>df =pd.DataFrame({'date': {0: '2016-01-01', 1: '2016-01-01', 2: '2016-01-01', 3: '2016-01-01', 4: '2016-01-02', 5: '2016-01-02', 6: '2016-01-03'}, 'band': {0: 'A', 1: 'B',... | 0 | 2016-10-17T20:19:04Z | [
"python",
"pandas",
"dataframe"
] |
How do "de-embed" words in TensorFlow | 40,094,097 | <p>I am trying to follow the tutorial for <a href="https://www.tensorflow.org/versions/r0.11/tutorials/recurrent/index.html#language-modeling" rel="nofollow">Language Modeling</a> on the TensorFlow site. I see it runs and the cost goes down and it is working great, but I do not see any way to actually get the predicti... | 0 | 2016-10-17T19:22:37Z | 40,094,226 | <p>The tensor you are mentioning is the <code>loss</code>, which defines how the network is training. For prediction, you need to access the tensor <code>probabilities</code> which contain the probabilities for the next word. If this was classification problem, you'd just do <code>argmax</code> to get the top probabili... | 0 | 2016-10-17T19:31:19Z | [
"python",
"tensorflow",
"word2vec"
] |
How do "de-embed" words in TensorFlow | 40,094,097 | <p>I am trying to follow the tutorial for <a href="https://www.tensorflow.org/versions/r0.11/tutorials/recurrent/index.html#language-modeling" rel="nofollow">Language Modeling</a> on the TensorFlow site. I see it runs and the cost goes down and it is working great, but I do not see any way to actually get the predicti... | 0 | 2016-10-17T19:22:37Z | 40,114,823 | <p>So after going through a bunch of other similar posts I figured this out. First, the code explained in the documentation is not the same as the code on the GitHub repository. The current code works by initializing models with data inside instead of passing data to the model as it goes along.</p>
<p>So basically t... | 0 | 2016-10-18T17:47:11Z | [
"python",
"tensorflow",
"word2vec"
] |
I have a RSA public key exponent and modulus. How can I encrypt a string using Python? | 40,094,108 | <p>Given a public key exponent and modulus like the following, how can I encrypt a string and send it to a server as text?</p>
<pre><code>publicKey: 10001,
modulus: 'd0eeaf178015d0418170055351711be1e4ed1dbab956603ac04a6e7a0dca1179cf33f90294782e9db4dc24a2b1d1f2717c357f32373fb3d9fd7dce91c40b6602'
</code></pre>
<p>I am ... | 0 | 2016-10-17T19:23:25Z | 40,095,575 | <p>With PyCrypto, you can use the <a href="https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA-module.html#construct" rel="nofollow">Crypto.PublicKey.RSA.construct()</a> function. You'll need to convert the modulus to an <code>int</code>. Here's an example (assuming big-endian):</p>
<pre><code>fro... | 2 | 2016-10-17T21:01:21Z | [
"python",
"public-key-encryption"
] |
Python: [Errno 2] No such file or directory - weird issue | 40,094,120 | <p>I'm learning with a tutorial <a href="https://hackercollider.com/articles/2016/07/05/create-your-own-shell-in-python-part-1/" rel="nofollow">Create your own shell in Python</a> and I have some weird issue. I wrote following code:</p>
<pre><code>import sys
import shlex
import os
SHELL_STATUS_RUN = 1
SHELL_STATUS_ST... | 1 | 2016-10-17T19:24:18Z | 40,094,312 | <p>Copy-paste from comments in my link (thanks for <a href="http://stackoverflow.com/users/3009212/ari-gold">Ari Gold</a>)</p>
<p>Hi tyh, it seems like you tried it on Windows. (I forgot to note that it works on Linux and Mac or Unix-like emulator like Cygwin only)</p>
<p>For the first problem, it seems like it canno... | 0 | 2016-10-17T19:37:22Z | [
"python",
"python-3.x"
] |
How can I find out the number of outputs in a loop? | 40,094,153 | <p>I am a beginner at python and I'm struggling with one of my (simple) college assignments. I have been given the following instructions:</p>
<p><strong>A bank is offering a savings account where a yearly fee is charged. Write
a program that lets the user enter</strong></p>
<ol>
<li><p>An initial investment.</p></li... | -1 | 2016-10-17T19:26:25Z | 40,096,285 | <p>I tried to write this in a way that was very easy to follow and understand. I edited it with comments to explain what is happening line by line. I would recommend using more descriptive variables. t/p/a/m/f may make a lot of sense to you, but going back to this program 6 months from now, you may have issues trying t... | 0 | 2016-10-17T21:53:45Z | [
"python",
"loops",
"while-loop"
] |
URL query parameters are not processed in django rest | 40,094,156 | <p>Here is my <code>views.py</code>:</p>
<pre><code>class my4appCompanyData(generics.ListAPIView):
serializer_class = my4appSerializer
def get_queryset(self,request):
"""Optionally restricts the returned data to ofa company,
by filtering against a `id` query parameter in the URL. """
q... | 0 | 2016-10-17T19:26:36Z | 40,097,324 | <pre><code>class my4appCompanyData(generics.ListAPIView):
serializer_class = my4appSerializer
def get_queryset(self,request):
"""Optionally restricts the returned data to ofa company,
by filtering against a `id` query parameter in the URL. """
queryset = companies_csrhub.objects.all()
... | 0 | 2016-10-17T23:41:35Z | [
"python",
"django",
"django-views",
"django-rest-framework"
] |
URL query parameters are not processed in django rest | 40,094,156 | <p>Here is my <code>views.py</code>:</p>
<pre><code>class my4appCompanyData(generics.ListAPIView):
serializer_class = my4appSerializer
def get_queryset(self,request):
"""Optionally restricts the returned data to ofa company,
by filtering against a `id` query parameter in the URL. """
q... | 0 | 2016-10-17T19:26:36Z | 40,123,440 | <p>According the official docs (<a href="http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters" rel="nofollow">http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters</a>)</p>
<p>I think your code is not working because you are using:</p>
<pr... | 0 | 2016-10-19T06:06:11Z | [
"python",
"django",
"django-views",
"django-rest-framework"
] |
Crontab: Using Python and sending email attachment | 40,094,162 | <p>I currently have a python file that is executed by the below crontab. It is currently working where it will run the Python file and it will email the output in the body of the email and also have an attachment with the same data. If I am trying to only have the attachment ( and not show the output of the data in the... | 0 | 2016-10-17T19:27:07Z | 40,094,831 | <p>I have a different version of <code>mailx</code> than you so I can't test this, but I suspect you'll get what you want if you replace the command with the following:</p>
<pre><code>/root/python/osversion_weekly.py > /root/python/osversion`date +\%Y-\%m-\%d-\%H:\%M`-cron.csv; echo "" | mailx -s "Daily Report" -a ... | 0 | 2016-10-17T20:09:19Z | [
"python",
"linux",
"crontab"
] |
git,curl,wget redirect to locahost | 40,094,180 | <p>Git gives me this error:</p>
<pre class="lang-none prettyprint-override"><code>$ git clone How people build software · GitHub
Cloning into 'xxxx'... fatal: unable to access 'xxx (Michael Dungan) · GitHub': Failed to connect to 127.0.0.1 port 443: Connection refused
</code></pre>
<p><code>curl</code> also gives... | -1 | 2016-10-17T19:27:58Z | 40,098,293 | <p>i have solved this problem, i hava missed the http_proxy,https_proxy system environment variable in <code>/.bash_profile</code>. remove them, it is okay now.</p>
| 0 | 2016-10-18T01:51:39Z | [
"python",
"sockets"
] |
Parsing xml tree attributes (file has no elements) | 40,094,201 | <p>I have been trying to use minidom but have no real preference. For some reason lxml will not install on my machine. </p>
<p>I would like to parse an xml file:</p>
<pre><code><?xml version="1.
-<transfer frmt="1" vtl="0" serial_number="E5XX-0822" date="2016-10-03 16:34:53.000" style="startstop">
... | 0 | 2016-10-17T19:29:15Z | 40,095,571 | <p>With minidom you can access the attributes of a particular element using the method attributes which can then be treated as dictionary; this example iterates and print the attributes of the element transfer[0]:</p>
<pre><code>from xml.dom.minidom import parse, parseString
xml_file='''<?xml version="1.0" encoding... | 0 | 2016-10-17T21:01:04Z | [
"python",
"xml",
"minidom"
] |
What is a delimiter? | 40,094,221 | <p>I am new to making CSV files with Python, and I am doing it to work with LDA (Latent Dirichlet Allocation). It says in a tutorial video </p>
<pre><code>with open('test.csv', 'w') as fp:
a = csv.writer(fp,delimiter=',')
</code></pre>
<p>I know <code>fp</code> means file pointer, yet I don't know how that relate... | -12 | 2016-10-17T19:30:49Z | 40,094,289 | <p>A delimiter is what separates values from each other. So the csv writer will separate values using a comma since the delimiter keyword argument is set to a comma mark <code>delimiter=','</code>.</p>
| 3 | 2016-10-17T19:35:18Z | [
"python",
"csv"
] |
What is a delimiter? | 40,094,221 | <p>I am new to making CSV files with Python, and I am doing it to work with LDA (Latent Dirichlet Allocation). It says in a tutorial video </p>
<pre><code>with open('test.csv', 'w') as fp:
a = csv.writer(fp,delimiter=',')
</code></pre>
<p>I know <code>fp</code> means file pointer, yet I don't know how that relate... | -12 | 2016-10-17T19:30:49Z | 40,094,310 | <p>Let's say I have a csv file with lines like:</p>
<pre><code>123ab,3748 jk89, 9ijkl
</code></pre>
<p>What are the values in this file? With delimiter <code>,</code></p>
<pre><code>['123ab', '3748 jk89', ' 9ijkl']
</code></pre>
<p>But with delimiter <code></code> (space character)</p>
<pre><code>['123ab,3748', '... | 2 | 2016-10-17T19:37:03Z | [
"python",
"csv"
] |
Displaying unique name with total of column value in a group with additional variables in python | 40,094,260 | <p>I'm learning Python and thought working on a project might be the best way to learn it. I have about 200,000 rows of data in which the data shows list of medication for the patient. Here's a sample of the data. </p>
<pre><code>PTID PTNAME MME DRNAME DRUGNAME SPLY STR QTY FACTOR
1 P... | 1 | 2016-10-17T19:33:28Z | 40,094,536 | <p>Have another look at the documentation for the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">pandas groupby methods</a>. </p>
<p>Here's something that could work for you:</p>
<pre><code>#first get the total MME for each patient and drug combination
total_mme=semp.groupby(['PTNAM... | 1 | 2016-10-17T19:50:25Z | [
"python",
"pandas"
] |
Displaying unique name with total of column value in a group with additional variables in python | 40,094,260 | <p>I'm learning Python and thought working on a project might be the best way to learn it. I have about 200,000 rows of data in which the data shows list of medication for the patient. Here's a sample of the data. </p>
<pre><code>PTID PTNAME MME DRNAME DRUGNAME SPLY STR QTY FACTOR
1 P... | 1 | 2016-10-17T19:33:28Z | 40,095,388 | <p>IIUC you can do it this way:</p>
<pre><code>In [62]: df.sort_values('MME').groupby('PTNAME').agg({'MME':'sum', 'DRUGNAME':'last'})
Out[62]:
DRUGNAME MME
PTNAME
PATIENT, A OXYCODONE HCL 15 MG 5400
PATIENT, B MORPHINE SULFATE ER 15 MG 10290
PATIENT, C OXYCODO... | 1 | 2016-10-17T20:47:24Z | [
"python",
"pandas"
] |
Finding pointer arguments with GnuCParser? | 40,094,339 | <p>I'm trying to parse this fragment of C code:</p>
<pre><code>void foo(const int *bar, int * const baz);
</code></pre>
<p>using <code>GnuCParser</code>, part of <a href="https://github.com/inducer/pycparserext" rel="nofollow">pycparserext</a>.</p>
<p>Based on <a href="http://stackoverflow.com/a/21872138/28169">this... | 0 | 2016-10-17T19:39:37Z | 40,099,163 | <p>I'm not sure what the issue with pycparserext here, but if I run it through the vanilla <a href="https://github.com/eliben/pycparser" rel="nofollow">pycparser</a> I get:</p>
<pre><code>FileAST:
Decl: foo, [], [], []
FuncDecl:
ParamList:
Decl: bar, ['const'], [], []
PtrDecl: []
... | 0 | 2016-10-18T03:46:00Z | [
"python",
"gcc",
"pycparser"
] |
Finding pointer arguments with GnuCParser? | 40,094,339 | <p>I'm trying to parse this fragment of C code:</p>
<pre><code>void foo(const int *bar, int * const baz);
</code></pre>
<p>using <code>GnuCParser</code>, part of <a href="https://github.com/inducer/pycparserext" rel="nofollow">pycparserext</a>.</p>
<p>Based on <a href="http://stackoverflow.com/a/21872138/28169">this... | 0 | 2016-10-17T19:39:37Z | 40,125,514 | <p>This was due to a bug in pycparserext, it has been fixed now by the maintainer and the issue mentioned in the question has been closed. The fix is in release 2016.2.</p>
<p>The output is now:</p>
<pre><code>>>> from pycparserext.ext_c_parser import GnuCParser
>>> p=GnuCParser()
>>> ast=p... | 0 | 2016-10-19T08:03:05Z | [
"python",
"gcc",
"pycparser"
] |
How is it possible to use a while loop to print even numbers 2 through 100? | 40,094,424 | <p>I am a beginner and I am stuck on this problem, "Write a python code that uses a while loop to print even numbers from 2 through 100. Hint ConsecutiveEven differ by 2."</p>
<p>Here is what I came up with so far: </p>
<pre><code> while num in range(22,101,2):
print(num)
</code></pre>
| -6 | 2016-10-17T19:44:08Z | 40,094,469 | <p>Here is how to use the while loop</p>
<pre><code> while [condition]:
logic here
</code></pre>
<p>using while in range is incorrect. </p>
<pre><code>num = 0
while num <=100:
if num % 2 == 0:
print(num)
num += 1
</code></pre>
| 0 | 2016-10-17T19:47:07Z | [
"python",
"loops",
"while-loop"
] |
How is it possible to use a while loop to print even numbers 2 through 100? | 40,094,424 | <p>I am a beginner and I am stuck on this problem, "Write a python code that uses a while loop to print even numbers from 2 through 100. Hint ConsecutiveEven differ by 2."</p>
<p>Here is what I came up with so far: </p>
<pre><code> while num in range(22,101,2):
print(num)
</code></pre>
| -6 | 2016-10-17T19:44:08Z | 40,094,508 | <p>Use either <code>for</code> with <code>range()</code>, or use <code>while</code> and explicitly increment the number. For example:</p>
<pre><code>>>> i = 2
>>> while i <=10: # Using while
... print(i)
... i += 2
...
2
4
6
8
10
>>> for i in range(2, 11, 2): # Using for
... pri... | 1 | 2016-10-17T19:49:01Z | [
"python",
"loops",
"while-loop"
] |
How is it possible to use a while loop to print even numbers 2 through 100? | 40,094,424 | <p>I am a beginner and I am stuck on this problem, "Write a python code that uses a while loop to print even numbers from 2 through 100. Hint ConsecutiveEven differ by 2."</p>
<p>Here is what I came up with so far: </p>
<pre><code> while num in range(22,101,2):
print(num)
</code></pre>
| -6 | 2016-10-17T19:44:08Z | 40,094,527 | <p>Your code has several problems:</p>
<ul>
<li>Substituting <code>while</code> for a statement with <code>for</code> syntax. <code>while</code> takes a bool, not an iterable.</li>
<li>Using incorrect values for <code>range</code>: you will start at 22.</li>
</ul>
<p>With minimal changes, this should work:</p>
<pre>... | 0 | 2016-10-17T19:49:41Z | [
"python",
"loops",
"while-loop"
] |
Paramiko capturing command output | 40,094,461 | <p>I have an issue that has been giving me a headache for a few days. I am using the Paramiko module with Python 2.7.10 and I'd like to issue multiple commands to a Brocade router, but only return output from one of the given commands like so:</p>
<pre><code>#!/usr/bin/env python
import paramiko, time
router = 'r1.te... | -1 | 2016-10-17T19:46:46Z | 40,095,024 | <p>For your second question: Though I am not specialist of paramiko, I see that function recv, <a href="http://docs.paramiko.org/en/2.0/api/channel.html" rel="nofollow">according to the doc</a>, returns a string. If you apply a <strong>for</strong> loop on a string, you will get characters (and not lines as one might p... | 1 | 2016-10-17T20:22:56Z | [
"python",
"python-2.7",
"ssh",
"paramiko"
] |
Paramiko capturing command output | 40,094,461 | <p>I have an issue that has been giving me a headache for a few days. I am using the Paramiko module with Python 2.7.10 and I'd like to issue multiple commands to a Brocade router, but only return output from one of the given commands like so:</p>
<pre><code>#!/usr/bin/env python
import paramiko, time
router = 'r1.te... | -1 | 2016-10-17T19:46:46Z | 40,095,135 | <p>If you can, the <code>exec_command()</code> call provides a simpler mechanism to invoke a command. I have seen Cisco switches abruptly drop connections that try <code>exec_command()</code>, so that may not be usable with Brocade devices.</p>
<p>If you must go the <code>invoke_shell()</code> route, be sure to clear ... | 0 | 2016-10-17T20:30:23Z | [
"python",
"python-2.7",
"ssh",
"paramiko"
] |
Paramiko capturing command output | 40,094,461 | <p>I have an issue that has been giving me a headache for a few days. I am using the Paramiko module with Python 2.7.10 and I'd like to issue multiple commands to a Brocade router, but only return output from one of the given commands like so:</p>
<pre><code>#!/usr/bin/env python
import paramiko, time
router = 'r1.te... | -1 | 2016-10-17T19:46:46Z | 40,095,538 | <p>After reading all of the comment I have made the following changes:</p>
<pre><code>#!/usr/bin/env python
import paramiko, time
router = 'r2.test.example.com'
password = 'password'
username = 'testuser'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(router, usernam... | 0 | 2016-10-17T20:58:41Z | [
"python",
"python-2.7",
"ssh",
"paramiko"
] |
Why does adding parenthesis around a yield call in a generator allow it to compile/run? | 40,094,470 | <p>I have a method:</p>
<pre><code>@gen.coroutine
def my_func(x):
return 2 * x
</code></pre>
<p>basically, a tornado coroutine.</p>
<p>I am making a list such as:</p>
<pre><code>my_funcs = []
for x in range(0, 10):
f = yield my_func(x)
my_funcs.append(x)
</code></pre>
<p>In trying to make this a list c... | 5 | 2016-10-17T19:47:19Z | 40,094,628 | <p><code>yield</code> expressions must be parenthesized in any context except as an entire statement or as the right-hand side of an assignment:</p>
<pre><code># If your code doesn't look like this, you need parentheses:
yield x
y = yield x
</code></pre>
<p>This is stated in the <a href="https://www.python.org/dev/pe... | 5 | 2016-10-17T19:57:18Z | [
"python",
"python-2.7",
"tornado",
"coroutine"
] |
Provisioning CoreOS with Ansible pip error | 40,094,550 | <p>I am trying to provision a coreOS box using Ansible. First a bootstapped the box using <a href="https://github.com/defunctzombie/ansible-coreos-bootstrap" rel="nofollow">https://github.com/defunctzombie/ansible-coreos-bootstrap</a></p>
<p>This seems to work ad all but pip (located in /home/core/bin) is not added to... | 0 | 2016-10-17T19:51:27Z | 40,096,277 | <p>You can't use shell-style variable expansion when setting Ansible variables. In this statement...</p>
<pre><code>environment:
PATH: /home/core/bin:$PATH
</code></pre>
<p>...you are setting your <code>PATH</code> environment variable to the <em>literal</em> value <code>/home/core/bin:$PATH</code>. In other word... | 1 | 2016-10-17T21:52:56Z | [
"python",
"pip",
"ansible",
"ansible-playbook",
"coreos"
] |
Connection Refused When Connecting to Elasticsearch Remotely | 40,094,586 | <p>I'm trying to use elasticsearch-py to connect to my server, but I'm having some serious issues. For whatever reason, when I pass in the credentials through python my connection is being refused.</p>
<p>Initially, I thought it could be a result of nginx configurations or bad certificates, but updating these did not ... | 1 | 2016-10-17T19:54:14Z | 40,094,646 | <p>In <code>config/elasticsearch.yml</code> put</p>
<pre><code>network.host: 0.0.0.0
</code></pre>
<p>to allow access from remote system. OR, replace <code>0.0.0.0</code> with the IP of the network/sub-network you would be using for accessing the Elastic Search.</p>
| 1 | 2016-10-17T19:58:24Z | [
"python",
"elasticsearch",
"connection"
] |
How to get a list of matchable characters from a regex class | 40,094,588 | <p>Given a regex character class/set, how can i get a list of all matchable characters (in python 3). E.g.:</p>
<pre><code>[\dA-C]
</code></pre>
<p>should give</p>
<pre><code>['0','1','2','3','4','5','6','7','8','9','A','B','C']
</code></pre>
| 3 | 2016-10-17T19:54:32Z | 40,094,676 | <pre><code>import re
x = '123456789ABCDE'
pattern = r'[\dA-C]'
print(re.findall(pattern,x))
#prints ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C']
</code></pre>
<p>Is this what you are looking for? </p>
<p>If you don't have <code>x</code> and just want to match ascii characters you can use :</p>
<... | 2 | 2016-10-17T19:59:57Z | [
"python",
"regex",
"python-3.x"
] |
How to get a list of matchable characters from a regex class | 40,094,588 | <p>Given a regex character class/set, how can i get a list of all matchable characters (in python 3). E.g.:</p>
<pre><code>[\dA-C]
</code></pre>
<p>should give</p>
<pre><code>['0','1','2','3','4','5','6','7','8','9','A','B','C']
</code></pre>
| 3 | 2016-10-17T19:54:32Z | 40,094,825 | <p>I think what you are looking for is <a href="https://docs.python.org/2/library/string.html#string.printable" rel="nofollow"><code>string.printable</code></a> which returns all the printable characters in Python. For example:</p>
<pre><code>>>> import string
>>> string.printable
'0123456789abcdefgh... | 7 | 2016-10-17T20:08:55Z | [
"python",
"regex",
"python-3.x"
] |
How to get a list of matchable characters from a regex class | 40,094,588 | <p>Given a regex character class/set, how can i get a list of all matchable characters (in python 3). E.g.:</p>
<pre><code>[\dA-C]
</code></pre>
<p>should give</p>
<pre><code>['0','1','2','3','4','5','6','7','8','9','A','B','C']
</code></pre>
| 3 | 2016-10-17T19:54:32Z | 40,095,866 | <p>You probably hoped to just extract them from the regexp itself, but it's not that easy: Consider specifications like <code>\S</code>, which doesn't match a contiguous range of characters, negated specifications like <code>[^abc\d]</code>, and of course goodies like <code>(?![aeiou])\w</code> (which matches any singl... | 3 | 2016-10-17T21:22:36Z | [
"python",
"regex",
"python-3.x"
] |
python dice rolling restart script | 40,094,671 | <p>i want to restart my script automatically i have a dice rolling script and i don't want to have to reset my script manually between each roll this is my script. </p>
<pre><code>import random
from random import randrange
from random import randint
r = randint
min = 1
max = 6
rolls = int(float(input('how menny times... | -3 | 2016-10-17T19:59:43Z | 40,096,792 | <p>I'm not 100% sure what you were actually trying to do, but here is a program that I wrote that will roll 2 die at a time, and will generate however many rolls you would like to roll. -not the best practice to use recursive (main calls main from within itself), but it's not really an issue with something this basic.<... | 0 | 2016-10-17T22:42:06Z | [
"python"
] |
Concating CSV files but Filtering Duplicates by 2 Columns | 40,094,735 | <p>I have a csv I want to update based on certain criteria. Example: </p>
<pre><code>csv:
Name UniqueID Status
Apple 1121 Full
Orange 1122 Eaten
Apple 1123 Rotten
</code></pre>
<p>New values (also in a csv):</p>
<pre><code>csv1:
Apple 1121 Eaten
orange 1122 Eat... | 0 | 2016-10-17T20:03:22Z | 40,095,557 | <pre>
cat csv csv1 | awk '{if (!status[$2] || status[$2]!=$3) {print $0; status[$2]=$3} }'
</pre>
<p><strong>explanation</strong></p>
<p>print these files in sequence and iterete line by line</p>
<p><code>cat csv csv1 | awk '{</code> </p>
<p>Keep second column (<code>unique id</code>) in an array key and the third ... | 0 | 2016-10-17T20:59:47Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Concating CSV files but Filtering Duplicates by 2 Columns | 40,094,735 | <p>I have a csv I want to update based on certain criteria. Example: </p>
<pre><code>csv:
Name UniqueID Status
Apple 1121 Full
Orange 1122 Eaten
Apple 1123 Rotten
</code></pre>
<p>New values (also in a csv):</p>
<pre><code>csv1:
Apple 1121 Eaten
orange 1122 Eat... | 0 | 2016-10-17T20:03:22Z | 40,096,924 | <p><strong><em>setup</em></strong> </p>
<pre><code>import pandas as pd
from StringIO import StringIO
csv = """Name UniqueID Status
Apple 1121 Full
Orange 1122 Eaten
Apple 1123 Rotten"""
csv1 = """Name UniqueID Status
Apple 1121 Eaten
Orange 1122 Eaten
Pe... | 0 | 2016-10-17T22:56:11Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Python equivalent of Perl Digest::MD5 functions | 40,094,746 | <p>As part of a work project I am porting a Perl library to Python. I'm comfortable with Python, much (much) less so with Perl.</p>
<p>The perl code uses <a href="https://metacpan.org/pod/Digest::MD5" rel="nofollow">Digest::MD5</a>. This module has three functions:</p>
<ul>
<li><code>md5($data)</code> takes in dat... | 0 | 2016-10-17T20:03:41Z | 40,094,887 | <p>The first one would simply be calling <code>.digest</code> method on the <code>md5</code>:</p>
<pre><code>>>> from hashlib import md5
>>> s = 'abcdefg'
>>> md5(s.encode()).digest()
b'z\xc6l\x0f\x14\x8d\xe9Q\x9b\x8b\xd2d1,Md'
</code></pre>
<p>And <code>md5_base64</code> is the digest but ... | 3 | 2016-10-17T20:13:37Z | [
"python",
"string",
"perl",
"encoding",
"md5"
] |
Python equivalent of Perl Digest::MD5 functions | 40,094,746 | <p>As part of a work project I am porting a Perl library to Python. I'm comfortable with Python, much (much) less so with Perl.</p>
<p>The perl code uses <a href="https://metacpan.org/pod/Digest::MD5" rel="nofollow">Digest::MD5</a>. This module has three functions:</p>
<ul>
<li><code>md5($data)</code> takes in dat... | 0 | 2016-10-17T20:03:41Z | 40,094,894 | <p>First, note <a href="https://metacpan.org/pod/Digest::MD5" rel="nofollow">Digest::MD5</a> documentation:</p>
<blockquote>
<p>Note that the base64 encoded string returned is not padded to be a multiple of 4 bytes long. If you want interoperability with other base64 encoded md5 digests you might want to append the ... | 0 | 2016-10-17T20:14:03Z | [
"python",
"string",
"perl",
"encoding",
"md5"
] |
Matplotlib Add Space Betwen Lines and left and right axes | 40,094,762 | <p>Given the following line graph:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, MaxNLocator
fig = plt.figure()
ax = fig.add_subplot(111)
xs = range(26)
ys = range(26)
labels = list('abcdefghijklmnopqrstuvwxyz')
def format_fn(tick_val, tick_pos):
if int(tick_val) in ... | 0 | 2016-10-17T20:05:07Z | 40,104,812 | <p>I guess the easiest would be to add a <code>ax.margins(margin)</code> call, where <code>margin</code> is a float between <code>0</code> and <code>1</code> that multiplied by the plot dimensions (width and height) gives the margin size it will be added.</p>
<p>Not sure how it fares with non trivial layouts (subplots... | 0 | 2016-10-18T09:42:50Z | [
"python",
"matplotlib"
] |
Error while trying to port a repo from github | 40,094,800 | <p>There is a github code I am trying to use that is located <a href="https://github.com/PX4/pyulog" rel="nofollow">here</a>.</p>
<p>I am trying to run <code>params.py</code> which is a code that will take a binary file and converts it so that I can plot it (or so I think).</p>
<p>I tried to run:</p>
<pre><code>pip ... | 0 | 2016-10-17T20:07:15Z | 40,094,908 | <p>Pip install tries to install the module from :</p>
<ul>
<li>PyPI (and other indexes) using requirement specifiers. </li>
<li>VCS project urls. </li>
<li>Local project directories. </li>
<li>Local or remote source archives.</li>
</ul>
<p>When looking at the items to be installed, pip checks what type of item each i... | 1 | 2016-10-17T20:15:13Z | [
"python"
] |
Django Rest Framework invalid username/password | 40,094,823 | <p>Trying to do a simple '<strong>GET</strong>' wih admin credentials returns</p>
<blockquote>
<p>"detail": "Invalid username/password."</p>
</blockquote>
<p>I have a <em>custom user model</em> where I deleted the <strong>username</strong>, instead I use <strong>facebook_id</strong> :</p>
<pre><code>USERNAME_FIELD... | 2 | 2016-10-17T20:08:47Z | 40,094,986 | <p>You have the default, and then you have per view. You can set the default to <code>IsAuthenticated</code>, and then you override your view's particular <code>permission_classes</code>. e.g.</p>
<pre><code>class ObtainJSONWebLogin(APIView):
permission_classes = ()
</code></pre>
<p>or </p>
<pre><code>class Foo... | 0 | 2016-10-17T20:20:19Z | [
"python",
"django",
"api",
"django-rest-framework"
] |
Find all cycles in directed and undirected graph | 40,094,835 | <p>I want to be able to find all cycles in a directed and an undirected graph. </p>
<p>The below code returns True or False if a cycle exists or not in a directed graph:</p>
<pre><code>def cycle_exists(G):
color = { u : "white" for u in G }
found_cycle = [False]
for... | 0 | 2016-10-17T20:09:30Z | 40,095,367 | <p>If I understand well, your problem is to use one unique algorithm for directed and undirected graph. </p>
<p>Why can't you use the algorithm to check for directed cycles on undirected graph? <strong>Non-directed graphs are a special case of directed graphs</strong>. You can just consider that a undirected edge is m... | 0 | 2016-10-17T20:45:07Z | [
"python",
"graph",
"graph-theory",
"dfs"
] |
Exception Value: object of type 'PolymorphicModelBase' has no len() | 40,094,839 | <p>I am converting existing models/admin over to django-polymorphic. I think I have the models and migrations done successfully (at least, it's working in the shell) but I can't get the admin to work. I'm finding the <a href="http://django-polymorphic.readthedocs.io/en/stable/admin.html#setup" rel="nofollow">document... | 0 | 2016-10-17T20:09:46Z | 40,095,187 | <p>Documentation is out of date. Bad docs. Bad.</p>
<p>child_models should be an iterable of (Model, ModelAdmin) tuples.</p>
<p><a href="https://github.com/django-polymorphic/django-polymorphic/issues/227" rel="nofollow">https://github.com/django-polymorphic/django-polymorphic/issues/227</a></p>
| 0 | 2016-10-17T20:33:58Z | [
"python",
"django",
"django-polymorphic"
] |
Numpy: how I can determine if all elements of numpy array are equal to a number | 40,094,938 | <p>I need to know if all the elements of an array of <code>numpy</code> are equal to a number</p>
<p>It would be like:</p>
<pre><code>numbers = np.zeros(5) # array[0,0,0,0,0]
print numbers.allEqual(0) # return True because all elements are 0
</code></pre>
<p>I can make an algorithm but, there is some method implemen... | 0 | 2016-10-17T20:17:10Z | 40,094,955 | <p>You can break that down into <code>np.all()</code>, which takes a boolean array and checks it's all <code>True</code>, and an equality comparison:</p>
<pre><code>np.all(numbers == 0)
# or equivalently
(numbers == 0).all()
</code></pre>
| 5 | 2016-10-17T20:18:22Z | [
"python",
"arrays",
"numpy"
] |
Categorical variables in pipeline | 40,095,008 | <p>I want to apply a pipeline with numeric & categorical variables as below</p>
<pre><code>import numpy as np
import pandas as pd
from sklearn import linear_model, pipeline, preprocessing
from sklearn.feature_extraction import DictVectorizer
df = pd.DataFrame({'a':range(12), 'b':[1,2,3,1,2,3,1,2,3,3,1,2], 'c':[... | 0 | 2016-10-17T20:21:34Z | 40,116,881 | <p>I see just this way</p>
<pre><code>import numpy as np
import pandas as pd
from sklearn import linear_model, metrics, pipeline, preprocessing
df = pd.DataFrame({'a':range(12), 'b':[1,2,3,1,2,3,1,2,3,3,1,2], 'c':['a', 'b', 'c']*4, 'd': ['m', 'f']*6})
y = df.a
num = df[['b']]
cat = df[['c', 'd']]
from sklearn.feature_... | 0 | 2016-10-18T19:50:54Z | [
"python",
"pipeline",
"categorical-data",
"dictvectorizer"
] |
Asana SQL API Asana2sql missing followers data | 40,095,013 | <p>I am able to successfully create and synchronize to a sqlite db using asana2sql.py. All the tables are populated, including the followers table. However, the followers table has no data. </p>
<p>I haven't seen any issues in the code. Has this happened to anyone else using the asana2sql api? What could be the i... | 0 | 2016-10-17T20:21:49Z | 40,116,218 | <p>It looks like that didn't make it into the library initially. There's a pull request to add it which should be resolved soon. You can work off of that branch in the meantime.</p>
<p><a href="https://github.com/Asana/asana2sql/pull/3" rel="nofollow">https://github.com/Asana/asana2sql/pull/3</a></p>
| 0 | 2016-10-18T19:11:46Z | [
"python",
"sqlite",
"asana"
] |
Fetch particular text from another file (python) | 40,095,113 | <p>I have a file of the following pattern:</p>
<pre><code>"abcd.asxs." "alphabets"
"wedf.345.po&%12." "numbers"
"xyhd.iu*u." "characters"
"megaten4.koryaku-memo.xyz." "alphabets"
"adwdbk.uyequ." "alphabets"
"233432.2321." "numbers"
"tytqyw.sdfhgwq." "alphabets"
</code></pre>
<p>I want something like:</p>
<pre><c... | -3 | 2016-10-17T20:28:44Z | 40,095,358 | <p><strong>Points for your code:</strong></p>
<ul>
<li>You can iterate line by line using file handle directly. No need to save file data using <code>fp.readlines()</code> in list and then iterating.</li>
<li>Once needed_category is found, you are directly appending complete line. That's why you are getting wrong outp... | 0 | 2016-10-17T20:44:26Z | [
"python"
] |
Fetch particular text from another file (python) | 40,095,113 | <p>I have a file of the following pattern:</p>
<pre><code>"abcd.asxs." "alphabets"
"wedf.345.po&%12." "numbers"
"xyhd.iu*u." "characters"
"megaten4.koryaku-memo.xyz." "alphabets"
"adwdbk.uyequ." "alphabets"
"233432.2321." "numbers"
"tytqyw.sdfhgwq." "alphabets"
</code></pre>
<p>I want something like:</p>
<pre><c... | -3 | 2016-10-17T20:28:44Z | 40,095,426 | <p>change <code>important.append(line)</code> to:</p>
<p><code>
if line.strip().endswith('"alphabets"'):
important.append(line.split(' ')[0].strip('"').strip('''))
</code></p>
| 0 | 2016-10-17T20:50:28Z | [
"python"
] |
'str' object has no attribute 'sort' | 40,095,127 | <p>I am quite new to python and was wondering if someone could help me fix a problem. Im making an anagram checker and have run into an issue. </p>
<pre><code>def anagram():
worda = input("Please choose your first word:")
wordb = input("Please choose your second word:")
if worda.isalpha():
pri... | -4 | 2016-10-17T20:29:52Z | 40,095,156 | <p>strings in Python are immutable, so it would make no sense for them to have a <code>sort</code> method, what you can do is use <code>sorted(worda)</code>, which returns a sorted list made out of the characters of the string.</p>
<p>Then to get a string back again, you can use <code>''.join(sorted(worda))</code></p>... | 4 | 2016-10-17T20:32:09Z | [
"python"
] |
'str' object has no attribute 'sort' | 40,095,127 | <p>I am quite new to python and was wondering if someone could help me fix a problem. Im making an anagram checker and have run into an issue. </p>
<pre><code>def anagram():
worda = input("Please choose your first word:")
wordb = input("Please choose your second word:")
if worda.isalpha():
pri... | -4 | 2016-10-17T20:29:52Z | 40,095,162 | <p>In Python, it is not possible to sort strings in lexicographic order, since strings are immutable. Instead, you must use the <code>sorted</code> function, which takes the string, converts it to a list, and then sorts that. Once you have done that, you can use the <code>join</code> function to convert your result bac... | 1 | 2016-10-17T20:32:29Z | [
"python"
] |
'str' object has no attribute 'sort' | 40,095,127 | <p>I am quite new to python and was wondering if someone could help me fix a problem. Im making an anagram checker and have run into an issue. </p>
<pre><code>def anagram():
worda = input("Please choose your first word:")
wordb = input("Please choose your second word:")
if worda.isalpha():
pri... | -4 | 2016-10-17T20:29:52Z | 40,095,164 | <p>There is no property as <code>sort</code> or any <code>sort()</code> function with <code>str</code> in Python. For sorting the <code>str</code> you can use <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow"><code>sorted()</code></a> as:</p>
<pre><code>>>> x = 'abcsd123ab'
>... | 0 | 2016-10-17T20:32:34Z | [
"python"
] |
finding an amount of variable in a text file by python | 40,095,133 | <p>I have a variable which its amount is changing every time. I like to know how can I find the line which contained the amount of my variable.
I am looking something like this:
but in this way it looks for the letter of "A"
how can I write a command which look for its amount("100")?
I tried this before</p>
<pre><code... | 2 | 2016-10-17T20:30:17Z | 40,096,392 | <p>Putting quotes around something makes it a String. You want to actually reference the variable which contains your number, i.e. <code>A</code> instead of <code>"A"</code></p>
<pre><code>A = 100
with open('my_file') as f:
for line in f:
# str() converts an integer into a string for searching.
if ... | 1 | 2016-10-17T22:02:04Z | [
"python",
"variables",
"text"
] |
Python regular expression search text file count substring | 40,095,306 | <p>I am attempting to use a regular expression statement in python to search a text file and count the number of times a user defined word appears. When I run my code though, instead of getting a sum of the number of times that unique word appears in the file, I am getting a count for the number lines within that file ... | 0 | 2016-10-17T20:41:12Z | 40,095,364 | <p>You're just adding 1 if it matches, I guess you don't want the search to go over lines, so you can do this:</p>
<pre><code>words = sum(len(re.findall(user_search_value, w, re.M|re.I)) for w in f)
</code></pre>
| 0 | 2016-10-17T20:44:53Z | [
"python",
"regex",
"full-text-search"
] |
Covariance matrix from np.polyfit() has negative diagonal? | 40,095,325 | <p><strong>Problem:</strong> the <code>cov=True</code> option of <code>np.polyfit()</code> produces a diagonal with non-sensical negative values.</p>
<p><strong>UPDATE:</strong> after playing with this some more, I am <em>really starting to suspect a bug in numpy</em>? Is that possible? Deleting any pair of 13 values ... | 0 | 2016-10-17T20:42:24Z | 40,104,022 | <p>It looks like it's related to your x values: they have a total range of about 3, with an offset of about 1.5 billion.</p>
<p>In your code</p>
<pre><code>np.asarray(x)
</code></pre>
<p>converts the x values in a ndarray of float64. While this is fine to correctly represent the x values themselves, it might not be ... | 1 | 2016-10-18T09:07:22Z | [
"python",
"python-2.7",
"numpy",
"statistics",
"linear-regression"
] |
graphene django relay: Relay transform error | 40,095,362 | <p>Being very new to GraphQL, I have a graphene django implementation of a server with two models, following rather closely the <a href="http://docs.graphene-python.org/projects/django/en/latest/tutorial.html" rel="nofollow">graphene docs' example</a>.</p>
<p>In graphiql, I can do this, and get a result back.</p>
<p>... | 0 | 2016-10-17T20:44:47Z | 40,108,241 | <p>Thanks @stubailo for pointing me in the right direction. I made some adjustments, and now have a minimum example running like this:</p>
<pre><code>NoteList = Relay.createContainer(NoteList, {
fragments: {
store: () => Relay.QL`
fragment N on NoteNodeConnection {
edges {
node{
... | 0 | 2016-10-18T12:26:26Z | [
"python",
"django",
"reactjs",
"graphql",
"relay"
] |
Replacing values in a column for a subset of rows | 40,095,632 | <p>I have a <code>dataframe</code> having multiple columns. I would like to replace the value in a column called <code>Discriminant</code>. Now this value needs to only be replaced for a few rows, whenever a condition is met in another column called <code>ids</code>. I tried various methods; The most common method seem... | 0 | 2016-10-17T21:04:46Z | 40,095,736 | <p>you are slicing too much. try something like this:</p>
<pre><code>indexer = df[df.ids == encodedid].index
df.loc[indexer, 'Discriminant'] = 'Y'
</code></pre>
<p><code>.loc[]</code> needs an index list and a column list. you can set the value of that slice easily using <code>=</code> 'what you need'</p>
<p>looking... | 1 | 2016-10-17T21:12:21Z | [
"python",
"pandas",
"dataframe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.