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 |
|---|---|---|---|---|---|---|---|---|---|
Pass python results to a C++ listbox | 38,218,408 | <p>I'm going to code in C++ and Python. I want Python to do a web crawling task and return the results to a C++ listbox. How can I grab the results from Python and pass them to the C++ part of my application? Only thing i see differences from <a href="http://stackoverflow.com/questions/2613497/how-to-pass-a-value-to-c-... | 0 | 2016-07-06T07:28:13Z | 38,222,169 | <p>As said Pavel Pája Halbich and msw in the other post, the proper solution is using PyObject.
If you want to have a two-way communication between C++ & Python, Boost Python would be interesting for you. Take a look at website <a href="http://www.boost.org/doc/libs/1_61_0/libs/python/doc/html/index.html" rel="nof... | 0 | 2016-07-06T10:48:40Z | [
"python",
"c++",
"listbox"
] |
How to prompt user to enter a hostname which then gathers it from a large list | 38,218,472 | <p>Using python through ansible I gathered a list of 7000 hostnames from DNS, but I want to prompt the user to enter a hostname and in return, the hostname will appear if present.</p>
<p>But it should be optional whether to look at the whole list or just one specified hostname. </p>
<p>The script is executed in xshel... | 0 | 2016-07-06T07:31:46Z | 38,218,849 | <p>One way you could do this would be using <code>input</code>(python3) (or <code>raw_input</code>(python2)) or specifying hostname as an argument to your script. You could get output from all by not specifying any hostname.</p>
<p>Assuming your hostnames are in a python list <code>dnshostnames</code>:</p>
<p><code>i... | 0 | 2016-07-06T07:52:21Z | [
"python",
"linux",
"dns",
"ansible",
"xshell"
] |
How to prompt user to enter a hostname which then gathers it from a large list | 38,218,472 | <p>Using python through ansible I gathered a list of 7000 hostnames from DNS, but I want to prompt the user to enter a hostname and in return, the hostname will appear if present.</p>
<p>But it should be optional whether to look at the whole list or just one specified hostname. </p>
<p>The script is executed in xshel... | 0 | 2016-07-06T07:31:46Z | 38,239,153 | <blockquote>
<p>Using <strong>python through ansible</strong></p>
</blockquote>
<p>I assume this means you use a <a href="http://docs.ansible.com/ansible/developing_inventory.html" rel="nofollow">dynamic inventory script</a>. The not satisfying but common approach seen in most inventory scripts is to use environment... | 0 | 2016-07-07T06:52:04Z | [
"python",
"linux",
"dns",
"ansible",
"xshell"
] |
Mocking member variable of an object in python | 38,218,489 | <p>I have the following python code to test</p>
<pre><code>class Foo(object):
def __init__(self):
self.__fb_access_tokens = PropertiesReader('path/to/authentication_details/file')
self.__fb_post_write_path = PropertiesReader('path/to/write_properties/file')
def write_information(self):
... | 0 | 2016-07-06T07:32:44Z | 38,218,588 | <pre><code>foo = Foo()
foo.__fb_access_tokens = new CustomPropertiesReader('mock/path/to/authentication_details/file')
class CustomPropertiesReader(PropertiesReader):
# your own implementation
def __init__(path):
# custom code, store data in memory instead of actual file
end
end
</code></pre>
<p>I... | -2 | 2016-07-06T07:38:29Z | [
"python",
"unit-testing"
] |
Mocking member variable of an object in python | 38,218,489 | <p>I have the following python code to test</p>
<pre><code>class Foo(object):
def __init__(self):
self.__fb_access_tokens = PropertiesReader('path/to/authentication_details/file')
self.__fb_post_write_path = PropertiesReader('path/to/write_properties/file')
def write_information(self):
... | 0 | 2016-07-06T07:32:44Z | 38,218,696 | <p>Just set a new value for the attribute once you've created an instance of the class. You'll have to manually 'mangle' the attribute name as you've chosen to use double-underscore names:</p>
<pre><code>instance = Foo()
instance._Foo__fb_post_write_path = 'mocked value
</code></pre>
<p>Consider using <em>single</em>... | 2 | 2016-07-06T07:43:19Z | [
"python",
"unit-testing"
] |
Python: Get top n key's with Value as dictionary | 38,218,501 | <p>I have a dictionary like:</p>
<pre><code>data = {'sachin': {'score': 15000, 'out': 100},
'Dhoni': {'score': 8000, out: 80},
'Shewag': {'score': 12000, 'out': 150}}
</code></pre>
<p>I want to get two players whose score are in top.</p>
<p>So I tried like: <code>key = (key for key,value in dd.items(... | 1 | 2016-07-06T07:33:26Z | 38,218,564 | <p>Yes, You can easily do it by the help of <code>lambda</code> and <code>key</code> param of the <code>sorted</code> method. Refer to this <a href="https://wiki.python.org/moin/HowTo/Sorting" rel="nofollow">link</a> for more clarity</p>
<pre><code>data = {'sachin':{'score':15000,'out':100},'Dhoni':{'score':8000,'out'... | 0 | 2016-07-06T07:37:05Z | [
"python",
"dictionary"
] |
Python: Get top n key's with Value as dictionary | 38,218,501 | <p>I have a dictionary like:</p>
<pre><code>data = {'sachin': {'score': 15000, 'out': 100},
'Dhoni': {'score': 8000, out: 80},
'Shewag': {'score': 12000, 'out': 150}}
</code></pre>
<p>I want to get two players whose score are in top.</p>
<p>So I tried like: <code>key = (key for key,value in dd.items(... | 1 | 2016-07-06T07:33:26Z | 38,218,662 | <p>Your link is right. You must modify it to use it for your case.</p>
<p>The method is:</p>
<ol>
<li>Sort descending</li>
<li>Get the n first</li>
</ol>
<p>You can do it with the library <code>heapq</code></p>
<pre><code>>>> import heapq
>>> heapq.nlargest(2, data.keys(), key=lambda k: data[k]['s... | 1 | 2016-07-06T07:41:55Z | [
"python",
"dictionary"
] |
Python: Get top n key's with Value as dictionary | 38,218,501 | <p>I have a dictionary like:</p>
<pre><code>data = {'sachin': {'score': 15000, 'out': 100},
'Dhoni': {'score': 8000, out: 80},
'Shewag': {'score': 12000, 'out': 150}}
</code></pre>
<p>I want to get two players whose score are in top.</p>
<p>So I tried like: <code>key = (key for key,value in dd.items(... | 1 | 2016-07-06T07:33:26Z | 38,218,745 | <h2>Quick Answer</h2>
<p>Sorting works:</p>
<pre><code>>>> dict(sorted(data.items(), key=lambda x: x[1]['score'], reverse=True)[:2])
{'Shewag': {'out': 150, 'score': 12000},
'sachin': {'out': 100, 'score': 15000}}
</code></pre>
<h2>In Steps</h2>
<p>You sort the items:</p>
<pre><code>>>> sorted(d... | 2 | 2016-07-06T07:46:00Z | [
"python",
"dictionary"
] |
Python: Get top n key's with Value as dictionary | 38,218,501 | <p>I have a dictionary like:</p>
<pre><code>data = {'sachin': {'score': 15000, 'out': 100},
'Dhoni': {'score': 8000, out: 80},
'Shewag': {'score': 12000, 'out': 150}}
</code></pre>
<p>I want to get two players whose score are in top.</p>
<p>So I tried like: <code>key = (key for key,value in dd.items(... | 1 | 2016-07-06T07:33:26Z | 38,218,894 | <p>You can try this:</p>
<pre><code>from collections import OrderedDict
from operator import getitem
data = {'sachin':{'score':15000,'out':100},'Dhoni':{'score':8000,'out':80},'Shewag':{'score':12000,'out':150}}
print(OrderedDict(sorted(data.items(), key = lambda x:getitem(x[1], "score"), reverse = True)[:2]))
</cod... | 0 | 2016-07-06T07:55:28Z | [
"python",
"dictionary"
] |
Issue with Subprocess and popen | 38,218,695 | <p>Recently , i wrote the following code to run a python file 'file1.py' from another python code. I am working on raspberry pi (with raspian )</p>
<p>Python code:</p>
<pre><code> import subprocess
subprocess.Popen(['python','./file1.py'])
print 'Done'
</code></pre>
<p>Output:</p>
<pre><code> Done
</c... | 1 | 2016-07-06T07:43:18Z | 38,218,829 | <p><code>Popen</code> forks the current process, which means you won't see its output simply by printing in the executed script.</p>
<p>You will need to redirect its output:</p>
<pre><code>p = subprocess.Popen(['python','./file1.py'], stdout=subprocess.PIPE)
print(p.stdout.read())
</code></pre>
| 1 | 2016-07-06T07:50:35Z | [
"python",
"subprocess"
] |
Issue with Subprocess and popen | 38,218,695 | <p>Recently , i wrote the following code to run a python file 'file1.py' from another python code. I am working on raspberry pi (with raspian )</p>
<p>Python code:</p>
<pre><code> import subprocess
subprocess.Popen(['python','./file1.py'])
print 'Done'
</code></pre>
<p>Output:</p>
<pre><code> Done
</c... | 1 | 2016-07-06T07:43:18Z | 38,219,003 | <pre><code>p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)
print p.communicate()[0]
</code></pre>
<p>OR</p>
<pre><code>print(p.stdout.read())
</code></pre>
<p>Communicate() will retrieve the last processed process output that will help to see the results</p>
| 0 | 2016-07-06T08:01:18Z | [
"python",
"subprocess"
] |
How to apply one-hot encoding to big files? | 38,218,796 | <p>I have 3 Gb train file and 350 Mb test file, 6 Gb RAM. That files seem to be not too big to hold them in the memory, but I can't even append them (memory error occurs).</p>
<p>My current aproach looks this way:</p>
<pre><code># reading files
dtypes = {'Semana' : 'int32',
'Agencia_I... | 2 | 2016-07-06T07:47:48Z | 38,220,589 | <p>How about specifying the data type when loading:</p>
<pre><code>types = {'col1': np.dtype(type),
'col2': np.dtype(type),
'col3' : np.dtype(type),
'col4': np.dtype(type),
'col5': np.dtype(type) }
train = pd.read_csv('train.csv', dtype=types)
</code></pre>
<p>run <code>train.info()</code> if you... | 1 | 2016-07-06T09:28:01Z | [
"python",
"python-2.7",
"csv",
"pandas",
"machine-learning"
] |
how to resolve the Memory Error | 38,218,806 | <p>This is for my python code</p>
<p><code>enter code here</code>fileName = open(flename,"r")
dccount = 0
dcCycles = []
ccCycles = []
temp=0
ccCY = []
dcCY = []
for line in fileName:
length = len(line)
for i in range(length):
if i >=4:
x = line[i-... | -3 | 2016-07-06T07:48:40Z | 38,218,962 | <p>It looks like dccount was not yet defined at that point. You should have gotten a NameError</p>
| 0 | 2016-07-06T07:59:13Z | [
"python"
] |
Add l1 or l2 regularization to crossentropy() function | 38,218,827 | <p>The following command is the cross entropy function in <a href="https://github.com/Newmu/Theano-Tutorials" rel="nofollow">5_convolutional_net.py</a>.
I want to add L1 or L2 regularization to this cost function. I do not know why the <code>TypeError: bad operand type for abs(): 'list'</code> comes up ?</p>
<pre><cod... | 0 | 2016-07-06T07:50:24Z | 38,232,401 | <p>You can't apply a abs() to a list but to each element of a list:</p>
<pre><code>cost+=T.sum([abs(p) for p in params])
</code></pre>
| 0 | 2016-07-06T19:38:54Z | [
"python",
"theano"
] |
Mongo aggregate $sum behavior | 38,218,909 | <p>I have this query in Motor (looks almost exactly as CLI query):</p>
<pre><code>response = yield self.db.orders.aggregate([
{'$match': {'reader.uid': reader.get('uid'), 'status': {'$in': statuses}}},
{'$sort': {'create_datetime': -1}},
{'$project': {'_id': 1, 'status': 1, 'create_datetime': 1... | 0 | 2016-07-06T07:56:22Z | 38,219,683 | <p><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/group/" rel="nofollow">$group</a> groups/aggregate all documents together based on a certain <code>_id</code>. </p>
<p>When you are grouping documents by <code>_id=0</code>, all documents will be in the same group because all have the same <cod... | 1 | 2016-07-06T08:41:42Z | [
"python",
"mongodb",
"aggregation-framework",
"tornado-motor"
] |
Bisection or Hashtable Method in Python | 38,218,910 | <p>I'd like to speed up the execution time of my function in python. I read that a good way to do this is using a Bisection or Hashtable method.
Do you know how I can do this with this function?</p>
<pre><code>from time import time
import csv
f = open('file.csv')
reader = csv.reader(f, delimiter=';')
def old(abi):
... | 0 | 2016-07-06T07:56:27Z | 38,220,956 | <p>I suspect that your problem is I/O (rather than CPU) bound. </p>
<p>If it is indeed CPU bound, there is one thing you could try to improve performance: replace a forloop with a generator. This way the iteration would happen on the C side on CPython.</p>
<pre><code>def old(path, abi):
with open(path) as handle:... | 0 | 2016-07-06T09:45:00Z | [
"python",
"hashtable",
"bisect"
] |
Subtract seconds from date pymongo aggregation | 38,218,911 | <p>This is my python code: </p>
<pre><code>date1=datetime.datetime(2016,2,3)
cursor = collection.aggregate([
{"$match":{"EndTime":{"$gte":date1}}},
{"$project": { "EndTime":"$EndTime","StartTime":{ "$subtract": [ "$EndTime", "$TimeSpent"*1000]},"TimeSpent":"$TimeSpent"}},
{"$sort":{"StartTime":1}}
])
</code></pre>... | 1 | 2016-07-06T07:56:30Z | 38,219,258 | <p>Your pipeline should use the available <a href="https://docs.mongodb.com/manual/reference/operator/aggregation-arithmetic/" rel="nofollow">arithmetic operators</a> to do the computation; you are supposedly "multiplying" a string literal instead of using the <strong><a href="https://docs.mongodb.com/manual/reference/... | 0 | 2016-07-06T08:16:09Z | [
"python",
"mongodb",
"pymongo",
"aggregation-framework"
] |
How can I get a Django-Rest Framework with a sub-query on child related items working? | 38,218,996 | <p>I've got a model that looks a bit like this:</p>
<p>Dataset</p>
<pre class="lang-py prettyprint-override"><code>class Dataset(ClusterableModel):
group = models.ForeignKey(DataGroup, on_delete=models.CASCADE, related_name='datasets')
is_public = models.BooleanField(default=False)
title = models.Char... | 0 | 2016-07-06T08:01:02Z | 38,219,631 | <p>You want something similar to <a href="https://medium.com/django-rest-framework/limit-related-data-choices-with-django-rest-framework-c54e96f5815e" rel="nofollow">https://medium.com/django-rest-framework/limit-related-data-choices-with-django-rest-framework-c54e96f5815e</a> using <code>HyperlinkedRelatedField</code>... | 0 | 2016-07-06T08:38:42Z | [
"python",
"django",
"django-rest-framework"
] |
How can I get a Django-Rest Framework with a sub-query on child related items working? | 38,218,996 | <p>I've got a model that looks a bit like this:</p>
<p>Dataset</p>
<pre class="lang-py prettyprint-override"><code>class Dataset(ClusterableModel):
group = models.ForeignKey(DataGroup, on_delete=models.CASCADE, related_name='datasets')
is_public = models.BooleanField(default=False)
title = models.Char... | 0 | 2016-07-06T08:01:02Z | 38,236,493 | <p>This is how I solved it in the end. Works pretty well.</p>
<pre class="lang-py prettyprint-override"><code>class DatasetInGroupSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='dataset-detail', lookup_field='name')
class Meta:
model = Dataset
... | 0 | 2016-07-07T01:51:22Z | [
"python",
"django",
"django-rest-framework"
] |
Search for a character within a Python string and then modify subsequent character | 38,219,028 | <p>I need to be able to find an asterisk in a Python string, and then run the <code>upper</code> method on the <em>subsequent</em> character in that string. So suppose I have:</p>
<pre><code>s*tring
</code></pre>
<p>I need to turn it into:</p>
<pre><code>sTring
</code></pre>
| 0 | 2016-07-06T08:02:47Z | 38,219,380 | <p>Though iteration over the characters of the String and replace is possible it is more efficient to make use of pattern matching. You can do this by <code>re</code> module's <code>sub()</code> method. Start by defining a lambda function to carry out the conversion process and then match and replace using <code>re.sub... | 1 | 2016-07-06T08:24:15Z | [
"python",
"string",
"replace",
"split"
] |
Search for a character within a Python string and then modify subsequent character | 38,219,028 | <p>I need to be able to find an asterisk in a Python string, and then run the <code>upper</code> method on the <em>subsequent</em> character in that string. So suppose I have:</p>
<pre><code>s*tring
</code></pre>
<p>I need to turn it into:</p>
<pre><code>sTring
</code></pre>
| 0 | 2016-07-06T08:02:47Z | 38,219,426 | <p>You can do it a brute force way like this:</p>
<pre><code>def str_upper(string):
my_list = list(string)
indexes = []
for char in my_list:
if char is "*":
indexes.append(my_list.index(char))
my_list.remove(char)
result = []
for i, letter in enumerate(my_list):
... | 1 | 2016-07-06T08:26:32Z | [
"python",
"string",
"replace",
"split"
] |
TextCtrl aren't alligning correctly in Python | 38,219,046 | <p>This is my code:</p>
<pre><code> label_1 = wx.StaticText(self,-1,_("xxxxxxxxxxxxxxxxx"))
label_2 = wx.StaticText(self,-1,_("xxxxxxx: "))
self.item1= wx.TextCtrl(self,-1,"",style=wx.TE_PROCESS_ENTER)
self.item2= wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_ENTER)
self.item1.SetMinSize((20... | 0 | 2016-07-06T08:04:03Z | 38,271,099 | <p>wxPython defaults will make widgets fit to their best size. The best way to get pairs of static text controls and text controls to line up is to set both of the StaticText widgets to a specific size via their size parameter. Something like this should suffice:</p>
<pre><code>size = (150, -1)
label_1 = wx.StaticText... | 1 | 2016-07-08T16:05:58Z | [
"python",
"wxpython"
] |
TextCtrl aren't alligning correctly in Python | 38,219,046 | <p>This is my code:</p>
<pre><code> label_1 = wx.StaticText(self,-1,_("xxxxxxxxxxxxxxxxx"))
label_2 = wx.StaticText(self,-1,_("xxxxxxx: "))
self.item1= wx.TextCtrl(self,-1,"",style=wx.TE_PROCESS_ENTER)
self.item2= wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_ENTER)
self.item1.SetMinSize((20... | 0 | 2016-07-06T08:04:03Z | 38,312,124 | <p>In addition to the other answer and commentary about making it work with <code>BoxSizer</code>, in my mind this example is crying out for a grid sizer. It will automatically align columns due to the nature of the grid, rather than needing the programmer to pound box sizers into submission. Here is your example por... | 1 | 2016-07-11T16:45:22Z | [
"python",
"wxpython"
] |
Python how to make an exception for non positive numbers | 38,219,057 | <p>How can I raise an exception here to catch nonpositive inputs? Right now nothing gets printed if I input a negative number</p>
<pre><code>"""
Generate fibonacci sequence to the nth digit
"""
def fib(n):
try:
if n <= 0:
raise Exception
prev = 0
curr = 1
for terms in... | 0 | 2016-07-06T08:04:59Z | 38,219,119 | <p><code>except ValueError or Exception</code></p>
<p>The correct syntax for that is <code>except (ValueError, Exception)</code>, but note that since all exceptions inherit from <code>Exception</code>, this might misbehave.</p>
<p>You better not raise and try to catch a general exception.
Instead, raise the already ... | 1 | 2016-07-06T08:08:04Z | [
"python",
"exception",
"numbers",
"try-catch",
"except"
] |
Python how to make an exception for non positive numbers | 38,219,057 | <p>How can I raise an exception here to catch nonpositive inputs? Right now nothing gets printed if I input a negative number</p>
<pre><code>"""
Generate fibonacci sequence to the nth digit
"""
def fib(n):
try:
if n <= 0:
raise Exception
prev = 0
curr = 1
for terms in... | 0 | 2016-07-06T08:04:59Z | 38,219,131 | <p>To catch multiple exception types, put them in a tuple. <code>ValueError or Exception</code> is a boolean expression that evaluates to ValueError.</p>
<p>Also you should never raise Exception, and you should never ever catch it. Define your own custom exception class. </p>
<pre><code>class NonNegativeNumber(Error)... | 0 | 2016-07-06T08:08:51Z | [
"python",
"exception",
"numbers",
"try-catch",
"except"
] |
Python how to make an exception for non positive numbers | 38,219,057 | <p>How can I raise an exception here to catch nonpositive inputs? Right now nothing gets printed if I input a negative number</p>
<pre><code>"""
Generate fibonacci sequence to the nth digit
"""
def fib(n):
try:
if n <= 0:
raise Exception
prev = 0
curr = 1
for terms in... | 0 | 2016-07-06T08:04:59Z | 38,219,224 | <p>I think the core problem here is that your <code>fib</code> function has two entirely separate responsibilities:</p>
<ol>
<li>Handling user input and validation; and</li>
<li>Calculating Fibonacci numbers.</li>
</ol>
<p>From the name, I'd say it should only be doing #2!</p>
<p>Instead, structure your program like... | 1 | 2016-07-06T08:14:35Z | [
"python",
"exception",
"numbers",
"try-catch",
"except"
] |
Python how to make an exception for non positive numbers | 38,219,057 | <p>How can I raise an exception here to catch nonpositive inputs? Right now nothing gets printed if I input a negative number</p>
<pre><code>"""
Generate fibonacci sequence to the nth digit
"""
def fib(n):
try:
if n <= 0:
raise Exception
prev = 0
curr = 1
for terms in... | 0 | 2016-07-06T08:04:59Z | 38,219,470 | <p>As Jon says, it's a much better design strategy to separate the input gathering from the core Fibonacci calculation. Also, it's generally better to use a simple loop than to use a recursive call (calling a function inside itself) unless you <em>really</em> need recursion (eg, when processing a recursive data structu... | 1 | 2016-07-06T08:29:03Z | [
"python",
"exception",
"numbers",
"try-catch",
"except"
] |
Saved web pages when opened shows nothing | 38,219,216 | <p>I'm using <code>python</code> to crawl a webpage and save it. And the code works properly. But when I open the web page it just shows the website name i.e., <strong><a href="http://www.indiabix.com" rel="nofollow">http://www.indiabix.com</a></strong> and not the actual content.</p>
<p>You can just go the website an... | 1 | 2016-07-06T08:14:11Z | 38,219,371 | <p>You can simplify something like this. <a href="http://docs.python-requests.org/en/master/user/install/" rel="nofollow">Install</a> <code>requests</code>.</p>
<pre><code>import os
import requests
def write_to_file(link, name, title):
with open(os.path.join(name, title), "w") as fp:
fp.write(requests.ge... | 0 | 2016-07-06T08:23:40Z | [
"python",
"html",
"save",
"web-crawler"
] |
Saved web pages when opened shows nothing | 38,219,216 | <p>I'm using <code>python</code> to crawl a webpage and save it. And the code works properly. But when I open the web page it just shows the website name i.e., <strong><a href="http://www.indiabix.com" rel="nofollow">http://www.indiabix.com</a></strong> and not the actual content.</p>
<p>You can just go the website an... | 1 | 2016-07-06T08:14:11Z | 38,219,481 | <p>It's not possible. You can do an experiment by right-clicking the webpage and save the complete web files. And then use your browser to open the <code>.htm</code> file, you will get the same result. And when you inspect the page you can see there are some errors(files not found). So I think there are some errors wit... | 0 | 2016-07-06T08:29:48Z | [
"python",
"html",
"save",
"web-crawler"
] |
Saved web pages when opened shows nothing | 38,219,216 | <p>I'm using <code>python</code> to crawl a webpage and save it. And the code works properly. But when I open the web page it just shows the website name i.e., <strong><a href="http://www.indiabix.com" rel="nofollow">http://www.indiabix.com</a></strong> and not the actual content.</p>
<p>You can just go the website an... | 1 | 2016-07-06T08:14:11Z | 38,458,889 | <p>Disable the Javascript in your browser and open it.</p>
| 0 | 2016-07-19T12:40:09Z | [
"python",
"html",
"save",
"web-crawler"
] |
How to stop pandas trying to convert strings to floats? | 38,219,249 | <p>I am reading an excel file and want to depricate a datetime column to the 1st of each month.
The deprication works fine but pandas try to covert the strings to floats and throws an error when adding it as a coulmn of an existing dataframe.</p>
<p>How can I disable this, and just get a column with type of string or... | 1 | 2016-07-06T08:15:30Z | 38,219,315 | <p>You can do this by accessing the <code>day</code> attribute and subtracting a <code>TimedeltaIndex</code> from your datetime and casting to str:</p>
<pre><code>In [138]:
df = pd.DataFrame({'date':pd.date_range(dt.datetime(2016,1,1), periods=4)})
df
Out[138]:
date
0 2016-01-01
1 2016-01-02
2 2016-01-03
3 20... | 0 | 2016-07-06T08:19:56Z | [
"python",
"pandas",
"types",
"data-type-conversion"
] |
How to correctly use python libraries under Windows? | 38,219,310 | <p>I am using Windows 10 and I would like to import a library from some place <code>P:\_Testing\Tools\Selenium\Basic</code> (which I added to <code>PYTHONPATH</code>). I have the following script:</p>
<pre><code>print(os.environ['PYTHONPATH'])
from Basic import basic
</code></pre>
<p>and the path <code>P:\_Testing\To... | 0 | 2016-07-06T08:19:40Z | 38,219,646 | <p>You can import basic directly, because the Basic folder is right in your PYTHONPATH.
Just like search files right in this folder, you can get result include:
basic.py
<strong>init</strong>.py
But can not find Basic folder itself.</p>
| 0 | 2016-07-06T08:39:14Z | [
"python",
"selenium"
] |
Downloading Outlook attachments with REST API? | 38,219,479 | <p>Im working on a project that is related to the Outlook Mail API. I want to download the attachments an email has.
The documantation says that i can "get" the attachments, and they return different parameters in a json response, but im curious to know which one i have to convert to what, to get the actual attachment ... | 0 | 2016-07-06T08:29:42Z | 38,271,888 | <p>As per the documentation, <code>https://outlook.office.com/api/v2.0/me/messages/{message_id}/attachments</code> returns a collection of attachments which contains an identifier for the individual attachment:</p>
<pre><code>{
"@odata.context": "https://outlook.office.com/api/v2.0/$metadata#Me/Messages('AAMkAGI2T... | 1 | 2016-07-08T16:51:00Z | [
"python",
"api",
"email",
"outlook",
"hotmail"
] |
Output to two different consoles using python | 38,219,491 | <p>I am writing a script and I have two different kinds of output, say Op1 and Op2. I want to output Op1 to the terminal where the python process was called from while Op2 should be dumped to a different terminal instance. Can I do that?</p>
<p>Even if the answer is Linux-specific it's okay, I need a temporary solutio... | 3 | 2016-07-06T08:30:29Z | 38,219,625 | <p>You can make the Python script write to a file, or pipe its output to a file <code>python script.py >> output.log</code>, then you can <code>tail</code> the file with <code>-f</code> which makes it continuously update the view on your console.</p>
<h2>Example snippet</h2>
<pre><code># logmaker.py
import time... | 1 | 2016-07-06T08:38:33Z | [
"python",
"terminal",
"console",
"output"
] |
Output to two different consoles using python | 38,219,491 | <p>I am writing a script and I have two different kinds of output, say Op1 and Op2. I want to output Op1 to the terminal where the python process was called from while Op2 should be dumped to a different terminal instance. Can I do that?</p>
<p>Even if the answer is Linux-specific it's okay, I need a temporary solutio... | 3 | 2016-07-06T08:30:29Z | 38,219,807 | <p>Here are some common solutions in Linux.</p>
<p>To achieve this, you usually need two programs.</p>
<p><code>File i/o + Loop</code>: </p>
<ol>
<li>main program + file writer (print Op1 and write Op2 into file A)</li>
<li>file reader (keep fetching A file until it be modified and print the content of file A)</li>
... | 1 | 2016-07-06T08:48:58Z | [
"python",
"terminal",
"console",
"output"
] |
What happens if I log into the same file from multiple different processes in python? | 38,219,512 | <p>I spent hours to dig the behavior, first about those questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/10650861/atomicity-of-write2-to-a-local-filesystem">Atomicity of `write(2)` to a local filesystem</a></li>
<li><a href="http://stackoverflow.com/questions/6896011/how-can-i-synchronize-make-atomi... | 0 | 2016-07-06T08:32:19Z | 38,220,336 | <p>I would not rely on tests here. Weird things can only happen in race conditions, and exhibiting a race condition by test is almost non sense because the race condition is unlikely to occur. So it can work nicely for 1000 test runs and randomly break later in prod... The page you cite says:</p>
<blockquote>
<p>log... | 1 | 2016-07-06T09:15:22Z | [
"python",
"logging",
"multiprocessing",
"atomic",
"atomicity"
] |
What happens if I log into the same file from multiple different processes in python? | 38,219,512 | <p>I spent hours to dig the behavior, first about those questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/10650861/atomicity-of-write2-to-a-local-filesystem">Atomicity of `write(2)` to a local filesystem</a></li>
<li><a href="http://stackoverflow.com/questions/6896011/how-can-i-synchronize-make-atomi... | 0 | 2016-07-06T08:32:19Z | 38,240,738 | <p>I digged deeper and deeper. Now I think it's clear about these facts:</p>
<ol>
<li><p>With O_APPEND, parallel write(2) from multiple processes is ok. It's just order of lines are undetermined, but lines don't interleave or overwrite each other. And the size of data is by any amount, according to Niall Douglas's an... | 0 | 2016-07-07T08:24:13Z | [
"python",
"logging",
"multiprocessing",
"atomic",
"atomicity"
] |
Optimal way to run a python script multiple time with different argument values | 38,219,531 | <p>I have a python script that takes as input ~20 arguments.
I want to run this script multiple times with different values for the arguments each time.
At the moment I use a basic bash script like the following (with more parameters and more different values for each parameter)</p>
<pre><code>for com_adv_par18 in 0.2... | 0 | 2016-07-06T08:33:37Z | 38,219,565 | <p>Why not use another python script to process args and call the initial script as you want?
See such threads as <a href="http://stackoverflow.com/questions/3781851/run-a-python-script-from-another-python-script-passing-in-args">Run a python script from another python script, passing in args</a></p>
| 0 | 2016-07-06T08:36:03Z | [
"python",
"bash"
] |
Optimal way to run a python script multiple time with different argument values | 38,219,531 | <p>I have a python script that takes as input ~20 arguments.
I want to run this script multiple times with different values for the arguments each time.
At the moment I use a basic bash script like the following (with more parameters and more different values for each parameter)</p>
<pre><code>for com_adv_par18 in 0.2... | 0 | 2016-07-06T08:33:37Z | 38,219,964 | <p>The answer to your question depends on a lot of things - a significant factor is the length of time each execution takes.</p>
<p>If you can refactor the <code>alpha2.py</code> script so that you can <code>import</code> it, then you could use a python wrapper script along these lines:</p>
<pre><code>from alpha2 imp... | 0 | 2016-07-06T08:56:52Z | [
"python",
"bash"
] |
Is it possible to initialize a bool with True? | 38,219,553 | <p>I am defining a variable through an empty declaration:</p>
<pre><code>In [1]: a = bool()
In [2]: a
Out[2]: False
</code></pre>
<p>Is it possible to force an initialization of <code>True</code>?</p>
<hr>
<p>Note: I know I can simply have <code>a = True</code> or <code>a = bool(True)</code> but I will be initiali... | 2 | 2016-07-06T08:34:59Z | 38,219,622 | <p>You can use <a href="https://docs.python.org/3/library/functools.html#functools.partial" rel="nofollow"><code>functools.partial</code></a> to customize your <code>bool</code>:</p>
<pre><code>from functools import partial
my_bool = partial(bool, 1)
print(my_bool())
# True
</code></pre>
<p>And you can use it in yo... | 4 | 2016-07-06T08:38:29Z | [
"python",
"python-3.x",
"types"
] |
Is it possible to initialize a bool with True? | 38,219,553 | <p>I am defining a variable through an empty declaration:</p>
<pre><code>In [1]: a = bool()
In [2]: a
Out[2]: False
</code></pre>
<p>Is it possible to force an initialization of <code>True</code>?</p>
<hr>
<p>Note: I know I can simply have <code>a = True</code> or <code>a = bool(True)</code> but I will be initiali... | 2 | 2016-07-06T08:34:59Z | 38,219,728 | <p>Maybe a possible solution for you with the flexibility for other special default values</p>
<pre><code>typeDefaults = {bool: True}
for v in [('a', int), ('b', float), ('c', bool)]:
x[v[0]] = typeDefaults[v[1]] if v[1] in typeDefaults else v[1]()
</code></pre>
| 2 | 2016-07-06T08:44:02Z | [
"python",
"python-3.x",
"types"
] |
Is it possible to initialize a bool with True? | 38,219,553 | <p>I am defining a variable through an empty declaration:</p>
<pre><code>In [1]: a = bool()
In [2]: a
Out[2]: False
</code></pre>
<p>Is it possible to force an initialization of <code>True</code>?</p>
<hr>
<p>Note: I know I can simply have <code>a = True</code> or <code>a = bool(True)</code> but I will be initiali... | 2 | 2016-07-06T08:34:59Z | 38,220,052 | <p>You could map the types you want to change the default values for to your own functions:</p>
<pre><code>>>> defaults = {bool: lambda: True}
>>> x = {}
>>> for k, v in [('a', int), ('b', float), ('c', bool)]:
... x[k] = defaults.get(v, v)()
...
>>> x
{'a': 0, 'c': True, 'b': ... | 1 | 2016-07-06T09:01:38Z | [
"python",
"python-3.x",
"types"
] |
Django model is present, says not defined when running code | 38,219,557 | <p>i have the following model:</p>
<pre><code>class Basestationreport(models.Model):
...
gpstimeanddate = models.DateTimeField(db_column='GPSTimeAndDate') # Field name made lowercase.
...
</code></pre>
<p>And code:</p>
<pre><code>from .models import Basestationreport
@login_required(login_url="login/")... | 0 | 2016-07-06T08:35:36Z | 38,219,602 | <p>The error is because its looking for a local variable called <code>gpstimeanddate</code> which you obviously haven't defined, nor are trying to use. </p>
<p>Since you're trying to use it as a field to filter results on you need to use it as a keyword in fiter, as well as use <a href="https://docs.djangoproject.com/... | 1 | 2016-07-06T08:37:35Z | [
"python",
"django"
] |
Django model is present, says not defined when running code | 38,219,557 | <p>i have the following model:</p>
<pre><code>class Basestationreport(models.Model):
...
gpstimeanddate = models.DateTimeField(db_column='GPSTimeAndDate') # Field name made lowercase.
...
</code></pre>
<p>And code:</p>
<pre><code>from .models import Basestationreport
@login_required(login_url="login/")... | 0 | 2016-07-06T08:35:36Z | 38,219,632 | <p><code>_gt</code> should be used instead of <code>></code>. You can read more from this <a href="https://docs.djangoproject.com/en/1.9/topics/db/queries/" rel="nofollow">documentation</a>.</p>
<pre><code>result = Basestationreport.objects.filter(gpstimeanddate__gt = datetime.date(2005, 1, 1))
</code></pre>
| 1 | 2016-07-06T08:38:43Z | [
"python",
"django"
] |
Django model is present, says not defined when running code | 38,219,557 | <p>i have the following model:</p>
<pre><code>class Basestationreport(models.Model):
...
gpstimeanddate = models.DateTimeField(db_column='GPSTimeAndDate') # Field name made lowercase.
...
</code></pre>
<p>And code:</p>
<pre><code>from .models import Basestationreport
@login_required(login_url="login/")... | 0 | 2016-07-06T08:35:36Z | 38,219,654 | <p>This line:</p>
<pre><code>result = Basestationreport.objects.filter(gpstimeanddate > datetime.date(2005, 1, 1))
</code></pre>
<p>Should be</p>
<pre><code>result = Basestationreport.objects.filter(gpstimeanddate__gt=datetime.date(2005, 1, 1))
</code></pre>
<p>Django queries like filter only accept keyword argu... | 1 | 2016-07-06T08:39:34Z | [
"python",
"django"
] |
Python for Each Json Element | 38,219,558 | <p>Having a little trouble parsing JSON with Python and I'm not really sure what the syntax is I'd need.</p>
<p>The structure looks like this</p>
<pre><code>name = (json_data['JsonResultTitle']['Loc']['List'][0]['Events'][0]['Name'])
</code></pre>
<p>The numbers after <code>List</code> and <code>Events</code> can bo... | 0 | 2016-07-06T08:35:38Z | 38,219,635 | <p>Seems like you just want a nested loop.</p>
<pre><code>for item in json_data['JsonResultTitle']['Loc']['List']:
for event in item['Events']:
print event['Name']
</code></pre>
| 3 | 2016-07-06T08:38:48Z | [
"python",
"json"
] |
Local development of Google App Engine not importing built-in library | 38,219,564 | <p>I followed the <a href="https://cloud.google.com/appengine/docs/python/quickstart" rel="nofollow">quickstart</a> then I simply clone <code>hello_world</code> from <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/appengine/standard/hello_world/" rel="nofollow">here</a>. I already downlo... | 0 | 2016-07-06T08:35:59Z | 38,220,474 | <p>Seems like this is <a href="https://code.google.com/p/googleappengine/issues/detail?id=12963" rel="nofollow">acknowledged</a> bug in app engine SDK. As a temporary workaround, you may try this steps:</p>
<blockquote>
<p>Uninstalling the following PIP packages resolved this issue for me.</p>
<p><code>sudo pip... | 1 | 2016-07-06T09:22:08Z | [
"python",
"google-app-engine",
"google-app-engine-python"
] |
Local development of Google App Engine not importing built-in library | 38,219,564 | <p>I followed the <a href="https://cloud.google.com/appengine/docs/python/quickstart" rel="nofollow">quickstart</a> then I simply clone <code>hello_world</code> from <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/appengine/standard/hello_world/" rel="nofollow">here</a>. I already downlo... | 0 | 2016-07-06T08:35:59Z | 38,221,674 | <p>Thanks to @Dmytro Sadovnychyi for the answer. It doesn't work for me to uninstall those packages because I never installed it before, But that makes me think maybe built-in library conflict with other package so I decide to create <code>Virtual Environment</code>. just fresh environment no need to install any packag... | 1 | 2016-07-06T10:21:18Z | [
"python",
"google-app-engine",
"google-app-engine-python"
] |
Printing a sentence involving a function | 38,219,605 | <p>How can I print out the following sentence</p>
<blockquote>
<p>"The temperature is 30"</p>
</blockquote>
<p>such that 30 is changeable? In other word, I wrote: </p>
<pre><code>temp = 30
print (The temperature is "+ repr(temp)")
print "The temperature is "+ repr (temp)"
</code></pre>
<p>But the system says s... | 0 | 2016-07-06T08:37:52Z | 38,220,186 | <p><strong>Note</strong>: I am assuming you are writing a python program here, as your code does not look like basic code at all. The following has been tested using Python3 but might also work on Python2. </p>
<hr>
<p>Your string delimiters are all over the place. Everything between the double quotes (<code>"</code>... | 2 | 2016-07-06T09:08:17Z | [
"python"
] |
I need help to cluster my data set | 38,219,856 | <p>I am trying to do clustering on Facebook's data set.(data set from snap.stanford.edu). I have 4039 nodes and some features like education, location, name and etc. I am trying to run k means on my data set! Do you think it is a good clustering algorithm for my data?
I need visualization from my clustering so What sho... | -2 | 2016-07-06T08:51:19Z | 38,220,608 | <p>The best way would be looking at all the relationship between the variable. But you need to fix the response variable and other explanatory variables.
Let us consider a case :
'education' can be a response variable. 'location' may be the explanatory variable. But location being categorical data, you need to represe... | 0 | 2016-07-06T09:28:47Z | [
"python",
"cluster-analysis",
"social-networking",
"k-means"
] |
How to convert result of tweepy search to a JSON form | 38,219,889 | <p>I want to fetch tweets from twitter and save to my MongoDB database for which I am trying to convert the result to JSON.<br>
This is my code</p>
<pre><code>import tweepy
import json
import pymongo
from pymongo import MongoClient
client=MongoClient()
db=client.scholarship
APP_KEY = app key here
APP_SECRET = app sec... | 0 | 2016-07-06T08:52:59Z | 38,220,547 | <p>Got it
Because your cursor doesn't return you a JSON. It returns instances of tweepy.models.Status model. And it obviously can't be parsed as JSON.</p>
<p>To get parsed JSON from the model you can use </p>
<pre><code>tweet._json
</code></pre>
| 0 | 2016-07-06T09:26:07Z | [
"python",
"json",
"mongodb",
"twitter"
] |
Find the first index in a list A where the value is in a list B | 38,220,117 | <p>I want to find the first index in <code>A</code> that contains a value from <code>B</code>. For example: </p>
<pre><code>A = [1, 'Q', 3, 6, 'R']
B = ['Z', 'I', 'O', 3]
A.function(B) # would return 2
</code></pre>
<p>Is there a simple way of doing this? Obviously you can search through <code>A</code> for each item... | 1 | 2016-07-06T09:05:33Z | 38,220,228 | <p>I think there are two broad approaches, depending on which list is longer:</p>
<ol>
<li><p><strong><code>A</code> is longer than <code>B</code></strong>:</p>
<p>Take one item in <code>A</code> at a time and see if it's in <code>B</code>. Repeat until you find the first one that is.</p>
<pre><code>next(index for i... | 4 | 2016-07-06T09:10:11Z | [
"python",
"list",
"python-2.7"
] |
How to replace pip with conda? | 38,220,127 | <p>My package on PyPI depends on numpy, which is notorious for failing after <code>pip install mypackage</code>. I would like to replace <code>pip</code> with <code>conda</code> as a tool for installing my package. What are the steps for preparing a package to be deployed from Anaconda instead of PyPI?</p>
<p>I imag... | 0 | 2016-07-06T09:05:51Z | 38,247,028 | <p>You will need to build your package as a conda package and then upload it to the anaconda cloud.</p>
<p><a href="http://conda.pydata.org/docs/building/bpp.html?highlight=conda%20build" rel="nofollow">This</a> is the official documentation on how to build a conda package. You will need a meta.yaml (describing your ... | 2 | 2016-07-07T13:40:04Z | [
"python",
"numpy",
"pip",
"anaconda",
"conda"
] |
reshaping 3D matrix into 2D matrix using tensorflow | 38,220,133 | <p>I have a 3D matrix of dimensions, <code>549x19x50</code> I need to create a 2D matrix which gets me a <code>549x950</code> matrix.</p>
<p>What i did so far is using tensorflow;</p>
<pre><code>#data_3d is the 3D matrix
data_2d = tf.reshape(data_3d,[549,-1])
</code></pre>
<p>This prints out all the values of data_... | 1 | 2016-07-06T09:06:06Z | 38,221,932 | <p>There is a simple way to do so using <code>numpy</code>:<br></p>
<pre><code>import numpy as np
data_3d = np.arange(27).reshape((3,3,3))
data_2d = data_3d.swapaxes(1,2).reshape(3,-1)
</code></pre>
<p><strong>Ouput:</strong></p>
<pre><code>data_2d
</code></pre>
<p>[[ 0 3 6 1 4 7 2 5 8]<br>
[ 9 12 15 10 1... | 1 | 2016-07-06T10:35:23Z | [
"python",
"tensorflow",
"reshape"
] |
Is there a resize function in Python to resize an image as the tf.image.resize_images function of TensorFlow? | 38,220,143 | <p>I have a 4D ndarray of image data, which is organized as [NumberOfImages, <strong>RowsOfImage</strong>, <strong>ColumnsOfImage</strong>, ChannelsOfImage].</p>
<p>Now I want to resize the images in the 4D ndarray to the new size, which is with the size of [NumberOfImages, <strong>NewRowsOfImage</strong>, <strong>New... | 0 | 2016-07-06T09:06:34Z | 38,222,777 | <p>use <code>numpy.resize</code>. See below example. All images has the same shape (in this case 768 x 1024 x 3). In this example, I switched the row number with the column number. <code>im_all</code> is your 4d array.</p>
<pre><code>from scipy.misc import imread
import numpy as np
import matplotlib.pyplot as plt
f = ... | 1 | 2016-07-06T11:20:35Z | [
"python",
"image",
"numpy",
"tensorflow",
"skimage"
] |
Finding elements with selenium using Starts with and ends functions in xpath | 38,220,287 | <p>I am trying to extract all those tags whose class name fits the regex pattern frag-0-0, frag-1-0, etc. from this <a href="http://de.vroniplag.wikia.com/wiki/Aak/002" rel="nofollow">enter link description here</a></p>
<p>I am trying the following code</p>
<pre><code>driver = webdriver.PhantomJS()
for frg in frg... | 1 | 2016-07-06T09:13:29Z | 38,220,875 | <p>You can try to replace </p>
<pre><code>"//*[starts-with(@id, 'frag-') and ends-with(@id, '-0')]"
</code></pre>
<p>with</p>
<pre><code>"//*[starts-with(@id, 'frag-') and contains(@id, '-0')]"
</code></pre>
<p>as <code>Selenium</code> doesn't support <code>ends-with</code> option</p>
| 1 | 2016-07-06T09:41:14Z | [
"python",
"selenium",
"xpath"
] |
Is there a way to execute jq from python | 38,220,370 | <p>I'm trying to execute a jq command from my python script. Currently the jq command is working fine when I execute from the terminal (MacOs).</p>
<pre><code>cat filename.json |jq '{Name:.name, address:.address[0][1].street}'
</code></pre>
<p>Basically I'm trying to extract data from a JSON using jq. As the JSON con... | 1 | 2016-07-06T09:16:54Z | 38,223,211 | <p>From the jq <a href="https://github.com/stedolan/jq/wiki/FAQ" rel="nofollow">FAQ</a>:</p>
<blockquote>
<p>Q: What bindings are available for Python?</p>
<p>A:</p>
<p>pip install jq # For details, see <a href="https://pypi.python.org/pypi/jq" rel="nofollow">https://pypi.python.org/pypi/jq</a></p>
<p... | 2 | 2016-07-06T11:44:47Z | [
"python",
"arrays",
"json",
"jq"
] |
Is there a way to execute jq from python | 38,220,370 | <p>I'm trying to execute a jq command from my python script. Currently the jq command is working fine when I execute from the terminal (MacOs).</p>
<pre><code>cat filename.json |jq '{Name:.name, address:.address[0][1].street}'
</code></pre>
<p>Basically I'm trying to extract data from a JSON using jq. As the JSON con... | 1 | 2016-07-06T09:16:54Z | 38,229,564 | <p>Well, I'm a big fan of jq, but it doesn't seem like you're doing something that can't be easily done in Python too. Consider:</p>
<pre><code>import json
with open("filename.json", "r") as f:
data = json.load(f)
{"Name": data["name"], "address": data["address"][0][1]["street"]}
</code></pre>
| 1 | 2016-07-06T16:58:12Z | [
"python",
"arrays",
"json",
"jq"
] |
Is there a way to execute jq from python | 38,220,370 | <p>I'm trying to execute a jq command from my python script. Currently the jq command is working fine when I execute from the terminal (MacOs).</p>
<pre><code>cat filename.json |jq '{Name:.name, address:.address[0][1].street}'
</code></pre>
<p>Basically I'm trying to extract data from a JSON using jq. As the JSON con... | 1 | 2016-07-06T09:16:54Z | 38,678,013 | <ol>
<li>Can I execute this command from a python script</li>
</ol>
<p>Yes, using subprocess. Example:</p>
<pre><code>jsonFile = '/path/to/your/filename.json'
jq_cmd = "/bin/jq '{Name:.name, address:.address[0][1].street}' " + jsonFile
jq_proc = subprocess.Popen(jq_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE... | 1 | 2016-07-30T20:03:52Z | [
"python",
"arrays",
"json",
"jq"
] |
Wrap a timeseries to generate daywise grouped rolling statistics | 38,220,382 | <p>I am currently in the process of refactoring an algorithm that does analysis on a timeseries, because the implementation is too slow for anything but prototyping use.</p>
<p>The algorithm generates a <code>DataFrame</code> by slicing the timeseries into 24h chunks and arranges them side by side, so that each column... | 0 | 2016-07-06T09:17:18Z | 38,230,698 | <p>Turns out this was way easier than i thought initially. Looking at the second example, one can see that each column is simply a copy of the original timeseries shifted by one more day.</p>
<p>What i came up with:</p>
<pre><code># duplicate timeseries
refFrame = pd.concat([data] * refLen, axis=1)
# shift each colu... | 0 | 2016-07-06T17:59:05Z | [
"python",
"pandas"
] |
How to add a production config when deploying a docker container? | 38,220,530 | <p>I used to deploy Python web applications on AWS EC2 instances with Ansible.</p>
<p>In my development environment, I use config from a module <code>local_config.py</code>, but in the deployment process, I use an Ansible task to replace this file with a production-ready config.</p>
<p>How do I do something similar w... | 0 | 2016-07-06T09:25:13Z | 38,221,268 | <p>You should copy your production-ready config file into the docker container as part of your image-building process (COPY directive in your dockerfile), and then proceed with the same deployment steps you would normally use.</p>
| 0 | 2016-07-06T10:00:47Z | [
"python",
"docker"
] |
Login to Admin in Django | 38,220,569 | <p>I'd appreciate help with a custom user modul. I set it up analog to this example in the django <a href="https://docs.djangoproject.com/ja/1.9/topics/auth/customizing/#a-full-example" rel="nofollow">documentation</a>. I have the following problems:</p>
<ol>
<li>Login to the admin interface does not work. The login p... | 1 | 2016-07-06T09:27:04Z | 38,220,927 | <p>The problem is that you are creating a user using <code>self.model()</code> in your <code>create_user</code> method. This leads to the password being saved as plain text.</p>
<p>You should use the <code>create_user</code> method, as in the <a href="https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#a-fu... | 1 | 2016-07-06T09:43:52Z | [
"python",
"django",
"authentication",
"django-admin"
] |
render_template from Flask blueprint uses other blueprint's template | 38,220,574 | <p>I have a Flask app with blueprints. Each blueprint provides some templates. When I try to render the <code>index.html</code> template from the second blueprint, the first blueprint's template is rendered instead. Why is blueprint2 overriding blueprint1's templates? How can I render each blueprint's templates?</p... | 2 | 2016-07-06T09:27:17Z | 38,221,495 | <p>I vaguely remember having trouble with something like this early on. You haven't posted all of your code, but I have four suggestions based on what you've written. Try the first, test it, and then if it still is not working, try the next ones, but independently test them to see if they work:</p>
<p>First, I cant'... | -1 | 2016-07-06T10:13:16Z | [
"python",
"flask"
] |
render_template from Flask blueprint uses other blueprint's template | 38,220,574 | <p>I have a Flask app with blueprints. Each blueprint provides some templates. When I try to render the <code>index.html</code> template from the second blueprint, the first blueprint's template is rendered instead. Why is blueprint2 overriding blueprint1's templates? How can I render each blueprint's templates?</p... | 2 | 2016-07-06T09:27:17Z | 38,228,894 | <p>This is working exactly as intended, although not as you expect.</p>
<p>Defining a template folder for a blueprint only adds the folder to the template search path. It does <em>not</em> mean that a call to <code>render_template</code> from a blueprint's view will only check that folder.</p>
<p>Templates are looke... | 3 | 2016-07-06T16:19:49Z | [
"python",
"flask"
] |
How to write data to excel without overwriting | 38,220,619 | <p>I use some condition to <code>df</code> and all of variants I try write to one excel file(and to one Sheet).
I use code <a href="http://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data">from question</a>, my df is</p>
<pre><code>for i, (id, date, url, id1, date1) ... | -1 | 2016-07-06T09:29:29Z | 38,221,132 | <p>I dont think you can update cell contents. You can open a file to read, or open a new file to write to. I think you have to create a new workbook, and every cell that you read, if you choose to not modify it, write it out to your new workbook. In your sample code, you are overwriting wb (used to read) with the wb (u... | 0 | 2016-07-06T09:53:38Z | [
"python",
"excel",
"pandas"
] |
AttributeError: 'list' object has no attribute 'text' | 38,220,624 | <p>I am working with Vader from the nltk package.
I've imported my dataset following the vader tutorial: </p>
<pre><code> list = []
for line in open("C:\Users\Luca\Desktop\Uni\Tesi\PythonTest\paolo.txt","r").readlines():
for value in line.split(","):
list.append(value)
</code></pre>
<p>Th... | 0 | 2016-07-06T09:29:40Z | 38,220,898 | <p>You don't show where/how you created the function <code>_words_only()</code>, but the <code>self</code> argument indicates that you patterned it on a class method. You're evidently using it as a stand-alone function, like this:</p>
<pre><code>_words_only(list)
</code></pre>
<p>I would advise you not to tackle clas... | 1 | 2016-07-06T09:42:29Z | [
"python",
"attributes",
"nltk"
] |
Seaborn stripplot and errorbars | 38,220,653 | <p>I have a pandas data frame containing categorical data that looks like this:</p>
<pre><code> cat DM3_r DM3_r_err
133 stuff 9.908949 0.442363
1347 foo 1.156828 0.130174
132 bar 0.818709 0.593341
1350 stack 0.798348 0.089866
977 over 0.724274 0.462868
1054 flow 0.546665 0.538208
1... | 1 | 2016-07-06T09:31:01Z | 38,224,235 | <p>There might be smarter ways to select the data from the <code>Pandas.DataFrame</code>, but something like this works:</p>
<pre><code>import pandas as pd
import matplotlib.pylab as pl
import seaborn
import numpy as np
pl.close('all')
data = [['hsdM', 3.908949, 1.442363],
['lolD', 1.156828, 0.456434],
... | 1 | 2016-07-06T12:38:56Z | [
"python",
"matplotlib",
"seaborn",
"subplot"
] |
Error when creating DataFrame from RDD | 38,220,666 | <p>I have the following code where I am trying to create a <code>DataFrame</code> from a PipelinedRDD`:</p>
<pre><code> print type(simulation)
sqlContext.createDataFrame(simulation)
</code></pre>
<p>The <code>print</code> statement prints this:</p>
<pre><code><class 'pyspark.rdd.PipelinedRDD'>
</code></pre>... | 0 | 2016-07-06T09:31:20Z | 38,221,209 | <p>It seems that the schema cannot be inferred from your data.
If you don't specify the samplingRatio, only the first row will be used to determine the types.
You should either try a non zero sampling ratio or specify a schema as follows:</p>
<pre><code>schema = StructType([StructField("int_field", IntegerType()),
... | 2 | 2016-07-06T09:57:41Z | [
"python",
"apache-spark",
"pyspark"
] |
Flask Sql-alchemy not dropping tables created by alembic | 38,220,745 | <p>I have flask application with Flask-migrate. Running <code>db upgrade</code> creates following tables:</p>
<pre><code> List of relations
Schema | Name | Type | Owner
-------+-----------------+-------+----------
public | alembic_version | table | postgres
public | operations | table... | 1 | 2016-07-06T09:35:11Z | 38,221,083 | <blockquote>
<p>I want to start from empty database</p>
</blockquote>
<p>In that case do it at the database level (as opposed to the application level), e.g. delete the <code>.db</code> file for SQLite, <code>DROP DATABASE</code> for PostgreSQL etc.</p>
<p>You could make a script to drop and then recreate the DB (a... | 1 | 2016-07-06T09:51:10Z | [
"python",
"flask",
"flask-sqlalchemy",
"alembic",
"flask-migrate"
] |
Flask Sql-alchemy not dropping tables created by alembic | 38,220,745 | <p>I have flask application with Flask-migrate. Running <code>db upgrade</code> creates following tables:</p>
<pre><code> List of relations
Schema | Name | Type | Owner
-------+-----------------+-------+----------
public | alembic_version | table | postgres
public | operations | table... | 1 | 2016-07-06T09:35:11Z | 38,222,832 | <p>I found answer- it is not to drop database but to downgrade it to base migration via:</p>
<pre><code>db downgrade base
</code></pre>
| 0 | 2016-07-06T11:23:55Z | [
"python",
"flask",
"flask-sqlalchemy",
"alembic",
"flask-migrate"
] |
Regex replace conditional character | 38,220,821 | <p>I need to remove any 'h' in a string if it comes after a vowel.</p>
<pre><code>E.g.
John -> Jon
Baht -> Bat
Hot -> Hot (no change)
Rhythm -> Rhythm (no change)
</code></pre>
<p>Finding the words isnt a problem, but removing the 'h' is as I still need the original vowel. Can this be done... | 0 | 2016-07-06T09:38:38Z | 38,221,269 | <p>The regex for matching <code>h</code> after a vowel would be a positive lookbehind one</p>
<pre><code>(?<=a|e|y|u|o|a)h
</code></pre>
<p>And you can do</p>
<pre><code>re.sub(r"([a-zA-Z]*?)(?<=a|e|y|u|o|a)h([a-zA-Z]*)",r"\1\2",s)
</code></pre>
<p>However, if you can have more than one <code>h</code> after a... | 2 | 2016-07-06T10:00:56Z | [
"java",
"python",
"regex"
] |
How to get input and give an output after calculation | 38,220,826 | <p>I'm beginner for python and I tried to make a BMI calculator
but i have some problems with the input and output</p>
<p>I want to get input from <code>self.Heighttype</code>and <code>self.Weighttype</code>and give a output at <code>self.BMI</code></p>
<p>And some tips to simply my coding?</p>
<pre><code>from tkint... | 0 | 2016-07-06T09:38:49Z | 38,220,955 | <p>Use <code>.get()</code> and <code>.set()</code> on the <code>IntVar</code>s to get the parameters and set the result:</p>
<pre><code>def calculation(self):
m = self.we.get()
l = self.he.get()
bmi = # calculate the bmi here
self.ans.set(bmi)
</code></pre>
<p>Also, while it seems to work with an <c... | 0 | 2016-07-06T09:45:00Z | [
"python"
] |
Minidom - check if tag is present in XML | 38,220,895 | <p>I have a script that goes through all the XML files in directory and then parses those XML files to get the data in element <code>IS</code> tag <code>ICP</code>. However, there are several thousands of those XML files and some of them may not have tag <code>ICP</code> in <code>IS</code>. Is there a way to do it via ... | 1 | 2016-07-06T09:42:01Z | 38,221,327 | <p>You can check presence of <code>icp</code> by useing <code>in</code> operator</p>
<pre><code>for item in itemlist:
if( 'icp' in item.attributes ):
SeznamICP_all.write(item.attributes['icp'].value + '\n')
break;
</code></pre>
| 0 | 2016-07-06T10:04:22Z | [
"python",
"xml",
"python-3.x",
"xml-parsing",
"minidom"
] |
Minidom - check if tag is present in XML | 38,220,895 | <p>I have a script that goes through all the XML files in directory and then parses those XML files to get the data in element <code>IS</code> tag <code>ICP</code>. However, there are several thousands of those XML files and some of them may not have tag <code>ICP</code> in <code>IS</code>. Is there a way to do it via ... | 1 | 2016-07-06T09:42:01Z | 38,221,329 | <p>You can use <a href="https://docs.python.org/2/library/xml.dom.html#xml.dom.Element.hasAttribute" rel="nofollow"><code>hasAttribute(attributeName)</code></a> method :</p>
<pre><code>....
itemlist = xmldoc.getElementsByTagName('is')
if itemlist[0].hasAttribute("icp"):
SeznamICP_all.write(itemlist[0].attributes['... | 2 | 2016-07-06T10:04:25Z | [
"python",
"xml",
"python-3.x",
"xml-parsing",
"minidom"
] |
How to click on a button with Selenium? | 38,220,902 | <p>I am trying to use the Python Selenium API in order to click on a button. The HTML code is as follows: </p>
<pre><code><button class="btn wizard-next btn-primary" type="button">Weiter</button>
</code></pre>
<p>How to best identify this element? I was trying the following code</p>
<pre><code>driver.fin... | 1 | 2016-07-06T09:42:42Z | 38,220,977 | <p>You cannot use <code>find_element_by_class_name()</code> if class name value contains spaces.
Try:</p>
<pre><code>driver.find_element_by_xpath("//button[@class='btn wizard-next btn-primary']").click()
</code></pre>
| 3 | 2016-07-06T09:46:15Z | [
"python",
"selenium"
] |
How to click on a button with Selenium? | 38,220,902 | <p>I am trying to use the Python Selenium API in order to click on a button. The HTML code is as follows: </p>
<pre><code><button class="btn wizard-next btn-primary" type="button">Weiter</button>
</code></pre>
<p>How to best identify this element? I was trying the following code</p>
<pre><code>driver.fin... | 1 | 2016-07-06T09:42:42Z | 38,221,024 | <p>You can use css selector also </p>
<pre><code>driver.find_element_by_css_selector("btn").click()
</code></pre>
| 0 | 2016-07-06T09:48:29Z | [
"python",
"selenium"
] |
How to use itertools to pass the returned values from one function to another? | 38,220,924 | <p>I have a list being returned as </p>
<pre><code>[('10.12.250.29', 'pdx02-he-trial-ansible01', 'us-west-2a', 'vol-e7775a10'), ('10.12.32.22', 'pdx02-cloud-prod-ansible01 Clone ', 'us-west-2b', 'vol-b0607d70'), ('10.12.0.20', 'pdx02-cloud-trial/dev-ansible01', 'us-west-2a', 'vol-b32e5c46'), ('10.12.250.7', 'pdx02-he-... | 0 | 2016-07-06T09:43:49Z | 38,221,188 | <p>You are not using <code>chain</code> and <em>unpacking</em> correctly. All you are trying to do, can be done with <code>zip</code> and <em>unpacking</em> viz. <code>zip(*...)</code>:</p>
<pre><code>>>> l = [('10.12.250.29', 'pdx02-he-trial-ansible01', 'us-west-2a', 'vol-e7775a10'), ('10.12.32.22', 'pdx02-c... | 2 | 2016-07-06T09:56:43Z | [
"python",
"itertools"
] |
How to use itertools to pass the returned values from one function to another? | 38,220,924 | <p>I have a list being returned as </p>
<pre><code>[('10.12.250.29', 'pdx02-he-trial-ansible01', 'us-west-2a', 'vol-e7775a10'), ('10.12.32.22', 'pdx02-cloud-prod-ansible01 Clone ', 'us-west-2b', 'vol-b0607d70'), ('10.12.0.20', 'pdx02-cloud-trial/dev-ansible01', 'us-west-2a', 'vol-b32e5c46'), ('10.12.250.7', 'pdx02-he-... | 0 | 2016-07-06T09:43:49Z | 38,221,199 | <p>with <code>[[j[0] for j in i] for i in data]</code> you are going through the list, and calculate <code>[j[0] for j in i]</code>, where <code>i</code> is the current tuple. So you iterate through the tuple, where <code>j</code> is the current string, and you get the first character of that string.</p>
<p>What you w... | 3 | 2016-07-06T09:57:10Z | [
"python",
"itertools"
] |
How to relative urls in Django URLField | 38,220,926 | <p>How i can get relative urls in my field after serialize? now i get abolute.
My model:</p>
<pre><code>class Article(models.Model):
title = models.CharField(max_length=120)
image = models.ImageField()
text = models.TextField()
link = models.URLField()
</code></pre>
<p>And serializer:</p>
<pre><code... | -1 | 2016-07-06T09:43:50Z | 38,221,789 | <p>Actually, without the <code>http://...</code> prefix, the url will not be a valid url. If you want to link somewhere inside your app, you can take the output of something like django's reverse and store it in a CharField (or just do some string manipulation by declaring a method, prior to inserting to the database o... | 0 | 2016-07-06T10:27:35Z | [
"python",
"django",
"django-rest-framework"
] |
Functions and Loops in Python | 38,220,958 | <p>I cannot see what I have done wrong below. I am new to Python. </p>
<p>INSTRUCTIONS </p>
<p>Define a function compute_bill that takes one argument food as input.</p>
<p>In the function, create a variable total with an initial value of zero.</p>
<p>For each item in the food list, add the price of that item to tot... | -4 | 2016-07-06T09:45:05Z | 38,221,131 | <pre><code>def compute_bill(food): return sum([prices[item] for item in food])
</code></pre>
<p>This is probably cleaner</p>
| 0 | 2016-07-06T09:53:33Z | [
"python"
] |
How to do write onto this script validation for the end "if they want to exit this program" | 38,221,015 | <pre><code>problem = False
while problem == False:
foo = open("solutions.txt","r")
print("What is wrong with your device?")
issue=input()
if (('wet' in issue) and ('water' in issue)):
solutions = foo.readlines()
print(solutions[0]+solutions[1])
problem = True
# (and so o... | -1 | 2016-07-06T09:48:13Z | 38,221,143 | <p>Write it more pythonic :</p>
<pre><code>while True:
with open("solutions.txt") as foo:
issue = input("What is wrong with your device?")
if 'wet' in issue and 'water' in issue:
print(foo.readline() + foo.readline())
question = input("Do you want to continue? (Y/N)")
if... | 0 | 2016-07-06T09:54:07Z | [
"python",
"validation"
] |
How to do write onto this script validation for the end "if they want to exit this program" | 38,221,015 | <pre><code>problem = False
while problem == False:
foo = open("solutions.txt","r")
print("What is wrong with your device?")
issue=input()
if (('wet' in issue) and ('water' in issue)):
solutions = foo.readlines()
print(solutions[0]+solutions[1])
problem = True
# (and so o... | -1 | 2016-07-06T09:48:13Z | 38,221,246 | <p>The next lines WITHIN your loop would be:</p>
<pre><code> answer = raw_input("Would you like to exit? Enter 'Yes' or 'No': ")
while answer not in ["Yes","No"]:
answer = raw_input("Would you like to exit? Enter 'Yes' or 'No': ")
if answer == "Yes"
problem = True # This will cause you to exit the loo... | 0 | 2016-07-06T09:59:18Z | [
"python",
"validation"
] |
Python 2.7 Mathematical operations on output | 38,221,017 | <p>I'm quite new to python and currently I'm stuck with one problem. I could do this in BASH, but I'd like to learn python.<br>
I need to do math operations on output from command executed on remote server.</p>
<pre><code>if argument == "hosts":
output = []
output.append(os.popen("ssh -q -o ConnectTimeout=40 -... | -2 | 2016-07-06T09:48:15Z | 38,221,194 | <p>To get the sum of these inputs, you'd just (a) replace <code>read()</code> in your <code>popen</code> call with <code>deadlines()</code>, so that each input line becomes an element in your list; and (b) calculate the sum with <code>sum(int(x) for x in output)</code>. </p>
<pre><code>if argument == "hosts":
line... | 0 | 2016-07-06T09:57:02Z | [
"python",
"python-2.7"
] |
How To Access The Request Object in Django's GenericStackedInline Admin | 38,221,020 | <p>Using <strong>GenericStackedInline</strong> in Django 1.9 <em>(Python 3.4)</em> I want to access the <strong>request</strong> object before <strong>saving my model</strong> in the Django <strong>Admin</strong>. </p>
<p>When using <code>MediaItemAdmin</code> I can intercept the save function before <code>obj.save()<... | 1 | 2016-07-06T09:48:19Z | 38,221,541 | <p>The method that saves the "inlines" is part of <code>ModelAdmin</code>, not <code>InlineModelAdmin</code>.</p>
<pre><code>class BarInline(GenericStackedInline):
model = Bar
class FooModelAdmin(ModelAdmin):
model = Foo
inlines = [BarInline]
def save_formset(self, request, form, formset, change):
... | 1 | 2016-07-06T10:15:19Z | [
"python",
"django",
"python-3.x",
"django-forms",
"django-admin"
] |
How To Access The Request Object in Django's GenericStackedInline Admin | 38,221,020 | <p>Using <strong>GenericStackedInline</strong> in Django 1.9 <em>(Python 3.4)</em> I want to access the <strong>request</strong> object before <strong>saving my model</strong> in the Django <strong>Admin</strong>. </p>
<p>When using <code>MediaItemAdmin</code> I can intercept the save function before <code>obj.save()<... | 1 | 2016-07-06T09:48:19Z | 38,221,667 | <p>Admin classes don't inherit from forms; they <em>include</em> forms. And ModelForms don't have either <code>save_model</code> or <code>save_form</code> methods, they just have a <code>save</code> method. It's perfectly possible to override that method, but it doesn't accept <code>request</code>; you'd need to also o... | 1 | 2016-07-06T10:21:11Z | [
"python",
"django",
"python-3.x",
"django-forms",
"django-admin"
] |
How to fit parametric equations to data points in Python | 38,221,050 | <p>I am looking for a way to fit
<a href="https://en.wikipedia.org/wiki/Parametric_equation" rel="nofollow">parametric equations</a> to a set of data points, using Python.</p>
<p>As a simple example, given is the following set of data points:</p>
<pre><code>import numpy as np
x_data = np.array([1, 2, 3, 4, 5])
y_data... | 0 | 2016-07-06T09:49:54Z | 38,222,817 | <p>Since the relation between <code>x</code> and <code>y</code> is a quadratic one, you can use <code>np.polyfit</code> to get the coefficients.
According to your equations, your <code>x</code> and <code>y</code> relation is:</p>
<p><code>y = a2*((x-b1)/a1)**2 + b2*((x-b1)/a1) + c2</code></p>
<p>Using polyfit, we get... | 0 | 2016-07-06T11:23:08Z | [
"python",
"curve-fitting"
] |
How to fit parametric equations to data points in Python | 38,221,050 | <p>I am looking for a way to fit
<a href="https://en.wikipedia.org/wiki/Parametric_equation" rel="nofollow">parametric equations</a> to a set of data points, using Python.</p>
<p>As a simple example, given is the following set of data points:</p>
<pre><code>import numpy as np
x_data = np.array([1, 2, 3, 4, 5])
y_data... | 0 | 2016-07-06T09:49:54Z | 38,223,640 | <p>You can use polyfit, but please take care that the length of t must match the length of data points</p>
<pre><code>import numpy as np
tt = np.linspace(0, 5, len(x_data))
x_params = np.polyfit(tt, x_data, 1)
y_params = np.polyfit(tt, y_data, 2)
</code></pre>
<p>Change the third parameter to the degree that you th... | 0 | 2016-07-06T12:08:40Z | [
"python",
"curve-fitting"
] |
Python:Can anybody explain me this one line code? | 38,221,059 | <pre><code>print(''.join(map(str,range(1,n+1))))
</code></pre>
<p>Like what is str doing here ? and how is this outputting in the single line ?i know what map and join does but still i'm not clear with this whole code</p>
| -2 | 2016-07-06T09:50:22Z | 38,221,186 | <pre><code>numbers_one_to_n = range(1,n+1)
numbers_as_strings = map(str, numbers_one_to_n)
numbers_joined_to_single_string = ''.join(numbers_as_strings)
print(numbers_joined_to_single_string)
</code></pre>
| 4 | 2016-07-06T09:56:35Z | [
"python"
] |
Python:Can anybody explain me this one line code? | 38,221,059 | <pre><code>print(''.join(map(str,range(1,n+1))))
</code></pre>
<p>Like what is str doing here ? and how is this outputting in the single line ?i know what map and join does but still i'm not clear with this whole code</p>
| -2 | 2016-07-06T09:50:22Z | 38,221,196 | <p>Let's solve this from inner to outer level:</p>
<p><code>str</code> is a built-in function which takes an object, calls its magic method <code>__str__</code> and delivers the return of that function back. The standard result will simply be the number as string.</p>
<pre><code>n = 10
print(type(n)) # <type ... | 0 | 2016-07-06T09:57:06Z | [
"python"
] |
Python:Can anybody explain me this one line code? | 38,221,059 | <pre><code>print(''.join(map(str,range(1,n+1))))
</code></pre>
<p>Like what is str doing here ? and how is this outputting in the single line ?i know what map and join does but still i'm not clear with this whole code</p>
| -2 | 2016-07-06T09:50:22Z | 38,221,301 | <pre><code>print(''.join(map(str,range(1,n+1))))
</code></pre>
<p>You say you know what <code>map</code> does? The documentation says:</p>
<pre><code>map(function, iterable, ...)
Return an iterator that applies function to every item of iterable, yielding the result.
</code></pre>
<p>So <code>str</code> is the func... | 1 | 2016-07-06T10:02:45Z | [
"python"
] |
Python:Can anybody explain me this one line code? | 38,221,059 | <pre><code>print(''.join(map(str,range(1,n+1))))
</code></pre>
<p>Like what is str doing here ? and how is this outputting in the single line ?i know what map and join does but still i'm not clear with this whole code</p>
| -2 | 2016-07-06T09:50:22Z | 38,221,345 | <p><code>''</code> is a separator, that used between the concatenating elements (strings in a string sequence or characters in a string). For instance:</p>
<pre><code>>>> '-'.join(('foo', 'bar'))
'foo-bar'
>>> '-'.join('bar')
'b-a-r'
</code></pre>
<p><code>str</code> is a type and the function to co... | 0 | 2016-07-06T10:05:09Z | [
"python"
] |
How to solve the issue of the conflict of anaconda and virtualenv | 38,221,144 | <p>I was using virtualenv all the time and then I had also installed anaconda. Just now I tried to activate a virtual environment using the way of anaconda like <code>source activate helloworld</code>. (Indeed I don't remember if this is exactly the command I typed in). And then the environment had been activated. But ... | 0 | 2016-07-06T09:54:08Z | 38,226,816 | <p>It's not clear from your question what you expect "activate" to do. Is it activating a virtualenv, or is it activating a conda environment.</p>
<p>When you install miniconda or anaconda, you are given an option to add it to PATH. If you do so, then it probably always comes before your virtualenv activate script. ... | 1 | 2016-07-06T14:39:28Z | [
"python",
"ubuntu-14.04",
"virtualenv",
"anaconda"
] |
NLTK Relation Extraction - custom corpus in relextract.extract_rels | 38,221,147 | <p>I learnt that there is a built-in function in NLTK which could extract relations from NER-tagged sentences according the following:</p>
<pre><code> import re
IN = re.compile(r'.*\bin\b(?!\b.+ing\b)')
for fileid in ieer.fileids():
for doc in ieer.parsed_docs(fileid):
for rel in relextract... | 0 | 2016-07-06T09:54:17Z | 38,222,017 | <p>This should be more of a comment but I don't have enough reputation.</p>
<p>You can pass your custom corpus as the <code>doc</code> argument after it's been pos-tagged and converted to a list of chunked trees. For a custom corpus, you should use the <code>corpus='ace'</code>.</p>
<p>For example, in <a href="http:/... | 0 | 2016-07-06T10:39:14Z | [
"python",
"nlp",
"nltk"
] |
NLTK Relation Extraction - custom corpus in relextract.extract_rels | 38,221,147 | <p>I learnt that there is a built-in function in NLTK which could extract relations from NER-tagged sentences according the following:</p>
<pre><code> import re
IN = re.compile(r'.*\bin\b(?!\b.+ing\b)')
for fileid in ieer.fileids():
for doc in ieer.parsed_docs(fileid):
for rel in relextract... | 0 | 2016-07-06T09:54:17Z | 38,223,921 | <p>What does the <code>r'.*\bin\b(?!\b.+ing\b)'</code> regular expression stands here for exactly? I cannot dechiper.</p>
| 0 | 2016-07-06T12:23:55Z | [
"python",
"nlp",
"nltk"
] |
No module named tensorflow in jupyter | 38,221,181 | <p>I have some imports in my jupyter notebook and among them is tensorflow:</p>
<pre><code>ImportError Traceback (most recent call last)
<ipython-input-2-482704985f85> in <module>()
4 import numpy as np
5 import six.moves.copyreg as copyreg
----> 6 import tensor... | 0 | 2016-07-06T09:56:05Z | 39,028,927 | <p>If you installed a TensorFlow as it said in official documentation: <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#overview" rel="nofollow">https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#overview</a></p>
<p>I mean creating an environment called <em>tensorflow</em> ... | 0 | 2016-08-18T23:19:10Z | [
"python",
"tensorflow",
"jupyter-notebook"
] |
Python regular expression to replace everything but specific words | 38,221,224 | <p>I am trying to do the following <strong>with a regular expression</strong>:</p>
<pre><code>import re
x = re.compile('[^(going)|^(you)]') # words to replace
s = 'I am going home now, thank you.' # string to modify
print re.sub(x, '_', s)
</code></pre>
<p>The result I get is:</p>
<pre><code>'_____going__o___no__... | 6 | 2016-07-06T09:58:32Z | 38,221,513 | <p>Not quite as easy as it first appears, since there is no "not" in REs except <code>^</code> inside <code>[ ]</code> which only matches one character (as you found). Here is my solution:</p>
<pre><code>import re
def subit(m):
stuff, word = m.groups()
return ("_" * len(stuff)) + word
s = 'I am going home n... | 5 | 2016-07-06T10:13:39Z | [
"python",
"regex"
] |
Python regular expression to replace everything but specific words | 38,221,224 | <p>I am trying to do the following <strong>with a regular expression</strong>:</p>
<pre><code>import re
x = re.compile('[^(going)|^(you)]') # words to replace
s = 'I am going home now, thank you.' # string to modify
print re.sub(x, '_', s)
</code></pre>
<p>The result I get is:</p>
<pre><code>'_____going__o___no__... | 6 | 2016-07-06T09:58:32Z | 38,221,695 | <p>Here is a one regex approach:</p>
<pre><code>>>> re.sub(r'(?!going|you)\b([\S\s]+?)(\b|$)', lambda x: (x.end() - x.start())*'_', s)
'_____going_________________you_'
</code></pre>
<p>The idea is that when you are dealing with words and you want to exclude them or etc. you need to remember that most of the... | 3 | 2016-07-06T10:22:37Z | [
"python",
"regex"
] |
how to pass argument to autoIT script from python script | 38,221,335 | <p>In my python scripting, I need to pass the command line arguments to AutoIt script. Because in my AutoIt script I am getting command line arguments and processing it. The below AutoIt script I am using to get command line arguments and it is working fine:</p>
<pre><code>#include <Array.au3>
#include <WinAP... | 0 | 2016-07-06T10:04:37Z | 38,248,872 | <p>This should work for you. </p>
<p><strong>In your AutoIT script, put this piece of code in</strong></p>
<p>AutoIT's variable $CMDLINE contains the parameters provided. And the variable $PAR (feel free to change its name) will be storing the parameter for later use.</p>
<pre><code>$PAR = ''
If $CmdLine[0] > 0 T... | 0 | 2016-07-07T15:00:52Z | [
"python",
"autoit"
] |
How to count occurrence of elements in a single column of Pandas Dataframe | 38,221,348 | <p>I have the following DF:</p>
<pre><code>import pandas as pd
data = pd.DataFrame({'name' : ['a', 'a', 'b', 'd']})
In [7]: data
Out[7]:
name
0 a
1 a
2 b
3 d
</code></pre>
<p>What I want to do is to summarize</p>
<pre><code>a 2
b 1
d 1
</code></pre>
<p>How can I do it?
Tried this but not good:</p>
<p... | 1 | 2016-07-06T10:05:15Z | 38,221,373 | <p>hope this helps use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow">value_counts</a>:</p>
<pre><code>data = pd.DataFrame({'name' : ['a', 'a', 'b', 'd']})
In [14]: data['name'].value_counts()
Out[14]:
a 2
b 1
d 1
dtype: int64
</code></pre>
<p... | 1 | 2016-07-06T10:06:28Z | [
"python",
"pandas"
] |
How can I find where files are used as links in html pages? | 38,221,403 | <p>I have a static website where versions of old pages are still stored in the root. I want to find these pages and look if they are used in some link somewhere in the root's files. <br>
So I made a list of all the files inside the root using powershell's command <code>ls -R -Name</code> and store it on a file 'filelis... | 1 | 2016-07-06T10:08:30Z | 38,222,010 | <p>Try this one:</p>
<pre><code>([\d+\w+\.\\\-])+
</code></pre>
| 0 | 2016-07-06T10:38:56Z | [
"python",
"html",
"regex"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.