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 |
|---|---|---|---|---|---|---|---|---|---|
How to write a test to verify using Selenium Web Browser Automation | 37,494,906 | <p>I'm very new to Selenium Web Browser Automation.
I'm trying to write a test to verify a that the menu item for About actually goes to the About page in "<a href="http://www.seleniumhq.org/" rel="nofollow">http://www.seleniumhq.org/</a>"
Do you guys have an idea of how to achieve this by using Selenium Web Browser A... | 0 | 2016-05-28T03:30:36Z | 37,494,977 | <p>Locate the <code>About</code> link by <em>link text</em>, click it and check what the value of <code>driver.title</code> is:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.seleniumhq.org/")
driver.find_element_by_link_text("About").click()
assert driver.title =... | 1 | 2016-05-28T03:44:00Z | [
"python",
"selenium"
] |
How to write a test to verify using Selenium Web Browser Automation | 37,494,906 | <p>I'm very new to Selenium Web Browser Automation.
I'm trying to write a test to verify a that the menu item for About actually goes to the About page in "<a href="http://www.seleniumhq.org/" rel="nofollow">http://www.seleniumhq.org/</a>"
Do you guys have an idea of how to achieve this by using Selenium Web Browser A... | 0 | 2016-05-28T03:30:36Z | 37,495,042 | <p>First, determine what(element,text,link,img etc) in the loaded about page you will use to validate that you are in correct(about) page.
Then construct your code like this-</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.implicitly_w... | 0 | 2016-05-28T04:00:20Z | [
"python",
"selenium"
] |
Python if, elif, else problems when an if is not true skip | 37,494,966 | <p>I'm trying to write a program that will calculates that prompts the user to enter both the value and weight of an order and displays the shipping cost.</p>
<p>Shipping charges for online orders are based on the value of the order and the shipping weight. $100+ there is no shipping and on orders less than $100 ship... | 0 | 2016-05-28T03:40:50Z | 37,495,033 | <p>You should not use <code>else</code>, just <code>print</code>. Or you can use this:</p>
<pre><code>if total >= 100.00:
print()
else:
</code></pre>
| 0 | 2016-05-28T03:58:28Z | [
"python"
] |
Python if, elif, else problems when an if is not true skip | 37,494,966 | <p>I'm trying to write a program that will calculates that prompts the user to enter both the value and weight of an order and displays the shipping cost.</p>
<p>Shipping charges for online orders are based on the value of the order and the shipping weight. $100+ there is no shipping and on orders less than $100 ship... | 0 | 2016-05-28T03:40:50Z | 37,495,227 | <p>I guess you code have to be like this:</p>
<pre><code>price = int(input('Enter the price of your order: '))
total = price
if (price < 100):
weight = int(input('Enter the weight of your order: '))
if weight > 40: total += weight * 1.09
elif weight > 20: total += weight * 0.99
else: total += ... | 0 | 2016-05-28T04:38:18Z | [
"python"
] |
Python if, elif, else problems when an if is not true skip | 37,494,966 | <p>I'm trying to write a program that will calculates that prompts the user to enter both the value and weight of an order and displays the shipping cost.</p>
<p>Shipping charges for online orders are based on the value of the order and the shipping weight. $100+ there is no shipping and on orders less than $100 ship... | 0 | 2016-05-28T03:40:50Z | 37,496,100 | <p>You should start by checking the value of the order. As you said, if it's over $100, then weight isn't important because it's free shipping anyway. You probably already have that number from elsewhere in your program, so just check the value. Then you can move on to checking weight if necessary.</p>
<pre><code>#... | 0 | 2016-05-28T06:48:58Z | [
"python"
] |
Python fromtimestamp OSError | 37,494,983 | <p>For some reason when constructing datetimes using fromtimestamp, I get a "OSError [Errno22] Invalid Argument" when I use negative times less than -43200 (-12hrs).
I am on Win7 64-bit and python 3.5.1. Here's code that produces the error.</p>
<pre><code>>>> import datetime
>>> import pytz
>>&... | 0 | 2016-05-28T03:44:16Z | 37,531,867 | <p>It seems that you do not know what a timestamp is. A timestamp is the number of seconds since January 1st 1970, and this is always a positive value.</p>
| 1 | 2016-05-30T18:35:58Z | [
"python"
] |
No value returned when range of tested values extended | 37,495,031 | <p>I made a program to find Mersenne primes, and it works fine except when I extend the range of tested values above 61.</p>
<p>For example, if I wanted to test 100 numbers to see if they're primes, Idle only shows a blank screen. I can manually put larger values into the middle block, so I don't know if it's just a l... | 0 | 2016-05-28T03:57:52Z | 37,495,961 | <p>The problem with your program is that it uses a bad algorithm. Given enough time it should eventually produce the result for p = 61. However, that number is 2305843009213693951 and your primality check is inefficient as it's checking every divisor from 2 to n instead of only odd numbers to sqrt(n). However that's... | 1 | 2016-05-28T06:28:43Z | [
"python",
"python-3.x",
"primes"
] |
No Output with Beautiful Soup find_all | 37,495,035 | <pre><code>import requests
from bs4 import BeautifulSoup
urla = 'https://www.tumblr.com/search/hello'
r = requests.get(urla)
soupa = BeautifulSoup(r.content, 'html.parser')
links = soupa.find_all("div", {"class": "header_mage_wrapper has_avatar"})
for link in links:
print link
</code></pre>
<p>So after I run... | -1 | 2016-05-28T03:58:36Z | 37,496,022 | <p>This fetches you no output :</p>
<pre><code>import requests
from bs4 import BeautifulSoup
urla = 'https://www.tumblr.com/search/hello'
r = requests.get(urla)
soup = BeautifulSoup(r.text)
for link in soup.find_all('div', class_="header_image_wrapper has_avatar"):
print(link.get('class'))
</code></pre>
<p>This ... | 0 | 2016-05-28T06:39:17Z | [
"python",
"beautifulsoup"
] |
Python -- IndexError: list index out of range (sudoku solver program) | 37,495,099 | <p>I'm sorry if this code is not the easiest to follow. So I have a two dimensional list <code>board</code> with 9x9 dimensions (a sudoku board). In one of the lines in the <code>solve</code> function I check to see <code>if row <= 8 and column <=8:</code> and then call the <code>add1</code> function. When I use ... | 2 | 2016-05-28T04:10:23Z | 37,495,182 | <p>I can reproduce your traceback easily:</p>
<pre><code>>>> row, column = 8, 8
>>> board[row][column].isPermanent = True
>>> add1(board, row, column)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in add1
IndexError: list... | 1 | 2016-05-28T04:28:32Z | [
"python",
"list",
"indexing",
"sudoku",
"solver"
] |
JSON in post request works in HttpRequester but not in python Requests | 37,495,304 | <p>I'm stuck in web scraping a page using Python. Basically, the following is the request from HttpRequester (in Mozilla) and it gives me the right response.</p>
<pre><code>POST https://www.hpe.com/h20195/v2/Library.aspx/LoadMore
Content-Type: application/json
{"sort": "csdisplayorder", "hdnOffset": "1", "uniqueReques... | 1 | 2016-05-28T04:52:10Z | 37,506,620 | <p>If both Postman and <code>requests</code> are receiving an error, then there is <em>more context</em> than what <code>HttpRequester</code> is showing. There are a number of headers that I'd expect to be set almost always, including <code>User-Agent</code> and <code>Content-Length</code>, that are missing here.</p>
... | 0 | 2016-05-29T05:44:26Z | [
"python",
"json",
"post",
"web-scraping",
"python-requests"
] |
Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int' | 37,495,375 | <p>Using <code>pip install</code> for any module apparently on my Ubuntu 16.04 system with python 2.7.11+ throws this error:</p>
<pre><code>TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
</code></pre>
<p>What is wrong with pip? How could I reinstall it, if necessary?</p>
<p>Update: Full traceback i... | 4 | 2016-05-28T05:03:51Z | 37,531,821 | <p>Ubuntu comes with a version of PIP from precambrian and that's how you have to upgrade it if you do not want to spend hours and hours debugging pip related issues.</p>
<pre><code>apt-get remove python-pip python3-pip
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
python3 get-pip.py
</code></pre>
<p>As... | 5 | 2016-05-30T18:32:53Z | [
"python",
"pip"
] |
Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int' | 37,495,375 | <p>Using <code>pip install</code> for any module apparently on my Ubuntu 16.04 system with python 2.7.11+ throws this error:</p>
<pre><code>TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
</code></pre>
<p>What is wrong with pip? How could I reinstall it, if necessary?</p>
<p>Update: Full traceback i... | 4 | 2016-05-28T05:03:51Z | 39,484,683 | <p>If you are behind a proxy, you must do some extra configuration steps before starting the installation. You must set the environment variable http_proxy to the proxy address. Using bash this is accomplished with the command </p>
<pre><code>export http_proxy="http://user:pass@my.site:port/"
</code></pre>
<p>You ca... | 2 | 2016-09-14T07:23:01Z | [
"python",
"pip"
] |
Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int' | 37,495,375 | <p>Using <code>pip install</code> for any module apparently on my Ubuntu 16.04 system with python 2.7.11+ throws this error:</p>
<pre><code>TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
</code></pre>
<p>What is wrong with pip? How could I reinstall it, if necessary?</p>
<p>Update: Full traceback i... | 4 | 2016-05-28T05:03:51Z | 40,059,839 | <p>I also had this issue. Initially, a proxy was set and work fine. Then I connected to a network where it doesn't go through a proxy. After unsetting proxy pip again get works.</p>
<pre><code>unset http_proxy, unset http_proxy, unset HTTP_PROXY, unset HTTPS_PROXY
</code></pre>
| 0 | 2016-10-15T13:49:45Z | [
"python",
"pip"
] |
How to search for items in a list in python | 37,495,394 | <p>Basically I have two lists of items, and I want to check if an item from the second list is in the first list. Then if that item is in the first list, I want to assign a value to a variable, if it is not in that list, I want to assign a different value to the same variable. (As below)
Can this be done?</p>
<pre><co... | 0 | 2016-05-28T05:06:22Z | 37,495,402 | <p>Use <a href="https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset" rel="nofollow">set operations</a>:</p>
<pre><code>if not set(list1).isdisjoint(list2):
</code></pre>
<p>Two sets are disjoint if they have no elements in common.</p>
<p>Or use the <a href="https://docs.python.org/2/library/funct... | 0 | 2016-05-28T05:07:31Z | [
"python",
"list",
"python-3.x",
"variables",
"if-statement"
] |
How to search for items in a list in python | 37,495,394 | <p>Basically I have two lists of items, and I want to check if an item from the second list is in the first list. Then if that item is in the first list, I want to assign a value to a variable, if it is not in that list, I want to assign a different value to the same variable. (As below)
Can this be done?</p>
<pre><co... | 0 | 2016-05-28T05:06:22Z | 37,495,429 | <p>To answer the question you asked:</p>
<pre><code>list1 = ['dog','cat','mouse']
list2 = ['dog','tutle','bird']
for elem in list2:
if elem in list1:
square = 77
else:
square = 55
print(elem, "square=", square)
</code></pre>
<p>But searching a list takes a lot of time. You can get some spe... | -1 | 2016-05-28T05:10:41Z | [
"python",
"list",
"python-3.x",
"variables",
"if-statement"
] |
Append/Write with values of an instance | 37,495,401 | <p>So I'm new to working with classes in python, but this project Euler(q 81) I have is done using classes just to be a bit more tricky? I guess?</p>
<p>I can get the values of a (2n+1 * 2n+1) grid, but I can't work with them to append to another list or even write to a file.</p>
<pre><code>def minSum(matrix):
fi... | 0 | 2016-05-28T05:07:29Z | 37,495,599 | <p>Looks like you have another error when you try to write an instance to the text file but here's a way to print the values instead of the instance:</p>
<p>The <code>__repr__</code> method lets you define what the object looks like when it is printed.</p>
<p>Add a <code>__repr__</code> method to the <code>Supplies</... | 1 | 2016-05-28T05:37:21Z | [
"python",
"class",
"instance"
] |
Python :: Iteration vs Recursion on string manipulation | 37,495,437 | <p>In the examples below, both functions have roughly the same number of procedures.</p>
<pre><code>def lenIter(aStr):
count = 0
for c in aStr:
count += 1
return count
</code></pre>
<p>or</p>
<pre><code>def lenRecur(aStr):
if aStr == '':
return 0
return 1 + lenRecur(aStr[1:])
</co... | 0 | 2016-05-28T05:12:51Z | 37,495,473 | <p>Surely the first approach is more optimized, as python doesn't have to do a lot of function call and string slicing, which each of these operations are contain some other operations that cost much for python interpreter, and may be cause a lot of problems in future and in dealing with log strings.</p>
<p>As a more ... | 0 | 2016-05-28T05:17:42Z | [
"python",
"recursion",
"iteration"
] |
Python :: Iteration vs Recursion on string manipulation | 37,495,437 | <p>In the examples below, both functions have roughly the same number of procedures.</p>
<pre><code>def lenIter(aStr):
count = 0
for c in aStr:
count += 1
return count
</code></pre>
<p>or</p>
<pre><code>def lenRecur(aStr):
if aStr == '':
return 0
return 1 + lenRecur(aStr[1:])
</co... | 0 | 2016-05-28T05:12:51Z | 37,495,476 | <p>Python <a href="http://stackoverflow.com/questions/13591970/does-python-optimize-tail-recursion">does not perform tail call optimization</a>, so the recursive solution can hit a stack overflow on long strings. The iterative method does not have this flaw.</p>
<p>That said, <code>len(str)</code> is faster than both ... | 2 | 2016-05-28T05:18:11Z | [
"python",
"recursion",
"iteration"
] |
Python :: Iteration vs Recursion on string manipulation | 37,495,437 | <p>In the examples below, both functions have roughly the same number of procedures.</p>
<pre><code>def lenIter(aStr):
count = 0
for c in aStr:
count += 1
return count
</code></pre>
<p>or</p>
<pre><code>def lenRecur(aStr):
if aStr == '':
return 0
return 1 + lenRecur(aStr[1:])
</co... | 0 | 2016-05-28T05:12:51Z | 37,495,495 | <ol>
<li>This is not correct: 'functions have roughly the same number of procedures'. You probably mean that: 'these procedures require the same number of operations', or, more formally 'they have the same computational time complexity'.</li>
<li>While both <strong>have the same computational time complexity</strong>, ... | 2 | 2016-05-28T05:20:27Z | [
"python",
"recursion",
"iteration"
] |
how to click on the link using python selenium? | 37,495,616 | <p>I am trying to log in into my linkedin using python selenium. I am able to open my homepage but after that I want to open the following link present on my homepage</p>
<pre><code><a href="/profile/edit?trk=nav_responsive_sub_nav_edit_profile">
Edit Profile
</a>
</code></pre>
<p>I used the following cod... | 2 | 2016-05-28T05:39:52Z | 37,496,034 | <p>Seems that "Edit Profile" is just an option for "Profile" drop-down menu, so it's not visible initialy. You should click on "Profile" first to open drop-down menu. Try:</p>
<pre><code>driver.find_element_by_link_text("Profile").click()
driver.find_element_by_link_text("Edit Profile").click()
</code></pre>
<p><stro... | 0 | 2016-05-28T06:39:59Z | [
"python",
"selenium",
"web-crawler",
"linkedin"
] |
How to extract and change a sequence of bytes from a serial packet to the correct integer representation in python? | 37,495,676 | <p><code>374c4f4f00000800ff74**d102**29190300006f00fffffffffffffffffffff</code></p>
<p>This is the serial packet I am processing using pyserial. The two bytes in bold actually correspond to a real world measurement which corresponds to <code>721</code>(decimal) or <code>02d1</code>(hex). How do I extract those bytes i... | 2 | 2016-05-28T05:49:38Z | 37,495,830 | <p>Processing to and from such byte strings is quickly and easily done with the <code>struct</code> library functions <code>pack</code>/<code>pack_to</code> and <code>unpack</code>/<code>unpack_from</code>:</p>
<p>While it is normally best practice to unpack/unpack the entire packet you can use the _from & _to ve... | 2 | 2016-05-28T06:10:38Z | [
"python",
"int",
"hex",
"pyserial"
] |
How to extract and change a sequence of bytes from a serial packet to the correct integer representation in python? | 37,495,676 | <p><code>374c4f4f00000800ff74**d102**29190300006f00fffffffffffffffffffff</code></p>
<p>This is the serial packet I am processing using pyserial. The two bytes in bold actually correspond to a real world measurement which corresponds to <code>721</code>(decimal) or <code>02d1</code>(hex). How do I extract those bytes i... | 2 | 2016-05-28T05:49:38Z | 37,495,932 | <p>Your hex-encoded string is of odd length, so I don't know where the padding's missing from, see below</p>
<pre><code>In [18]: s = '374c4f4f00000800ff74d10229190300006f00fffffffffffffffffffff0' # a nibble of padding at the end
In [19]: buffer = binascii.unhexlify(s)
In [20]: buffer
Out[20]: b'7LOO\x00\x00\x08\x00\... | 0 | 2016-05-28T06:25:09Z | [
"python",
"int",
"hex",
"pyserial"
] |
How to extract and change a sequence of bytes from a serial packet to the correct integer representation in python? | 37,495,676 | <p><code>374c4f4f00000800ff74**d102**29190300006f00fffffffffffffffffffff</code></p>
<p>This is the serial packet I am processing using pyserial. The two bytes in bold actually correspond to a real world measurement which corresponds to <code>721</code>(decimal) or <code>02d1</code>(hex). How do I extract those bytes i... | 2 | 2016-05-28T05:49:38Z | 37,495,965 | <p>Since the actual format strings are somewhat strange at first sight, I have given you a solution based on the above answer: </p>
<ul>
<li>The command unhexlify will convert the 4 byte ascii representation back to a two byte binary representation of your integer.</li>
<li>the '<' takes care of your reversed byte ... | 0 | 2016-05-28T06:29:26Z | [
"python",
"int",
"hex",
"pyserial"
] |
Beautiful Soup - hyphenated keyword, Error :: keyword can't be an expression | 37,495,686 | <p>I'm using Selenium and then Beautiful Soup to try an scrape a webpage, the page uses JavaScript to load certain content. Selenium has given me the plain html, I have checked this, using print and found that it does contain the part that im trying to scrape. But my problem is with Beautiful Soup. </p>
<p>I want to ... | 0 | 2016-05-28T05:52:07Z | 37,496,316 | <p>The problem stems from the URL, you have an extra forward slash at the end which returns a 404 page rather than the page you actually want. Just remove that and your code works fine.</p>
<p>Here's the code I used just in case:</p>
<pre><code>from selenium import webdriver
from selenium.common.exceptions import N... | 0 | 2016-05-28T07:16:43Z | [
"python",
"beautifulsoup",
"keyword"
] |
How to know a file exists in the Desktop using Python on Mac OS? | 37,495,727 | <p>I would like to see whether a file is on the desktop in Mac OS and I write the code:</p>
<pre><code>if path.exists('~/Desktop/AZDif.png'):
print 'Yes'
else:
print 'No, the file is not there'
</code></pre>
<p>I see the file is not in the Desktop while it was actually there. How to write the code properly ?<... | 2 | 2016-05-28T05:58:11Z | 37,497,546 | <p>Here is the solution I find for Mac OS using Python:</p>
<pre><code>if path.exists(path.expanduser('~/Desktop/AZDif.png')):
print 'Yes'
</code></pre>
<p>There should also be a way to use absolute path as well. I will check and improve the answer. </p>
| 0 | 2016-05-28T09:51:38Z | [
"python",
"osx"
] |
Script arguments not parsed correctly when script called from Popen() | 37,495,788 | <p>Bit about the setup and goal first; I have <a href="http://www.nrl.navy.mil/itd/ncs/products/core" rel="nofollow">Core</a> installed and a session running that I wish to run a few commands on from a python script. Since there are only a few commands and they are fairly simple commands, figured I'd just use <code>sub... | 0 | 2016-05-28T06:04:29Z | 37,496,214 | <p>To clarify what @HaiVu says, your first example fails because of <code>-s 47854</code>, not the <code>cmd</code> parameter. In your example a single parameter of <code>"-s 47854"</code> was being passed. Depending on how arguments in the program are parsed, it could well take <code>node=2</code> as the value for t... | 1 | 2016-05-28T07:04:46Z | [
"python",
"subprocess",
"popen"
] |
ImageDataGenerator error | 37,495,878 | <p>I need help trying to fix this code for a simple autoencoder in Keras. I was trying to add some image preprocessing for the autoencoder tutorial on the Keras blog. This is what I've done</p>
<pre><code>input_image = Input(shape=(1,256,256,))
flattened = Flatten()(input_image)
encoded = Dense(128,activation='relu',n... | 1 | 2016-05-28T06:16:52Z | 37,496,012 | <p>I think you have forgotten to fit the datagen model. Please add <code>datagen.fit(train_imgs)</code> before <code>autoencoder.fit_generator</code> and try to train your model.</p>
| -1 | 2016-05-28T06:36:14Z | [
"python",
"keras"
] |
ImageDataGenerator error | 37,495,878 | <p>I need help trying to fix this code for a simple autoencoder in Keras. I was trying to add some image preprocessing for the autoencoder tutorial on the Keras blog. This is what I've done</p>
<pre><code>input_image = Input(shape=(1,256,256,))
flattened = Flatten()(input_image)
encoded = Dense(128,activation='relu',n... | 1 | 2016-05-28T06:16:52Z | 37,498,914 | <p>Figured this thing out myself. Turns out that ImageDataGenerator assumes that the input is in the shape (number_of_samples,number_of_channels,width,height).
Reshaping <code>train_imgs</code> and <code>test_imgs</code> did the trick. I have modified the code in the question to include this extra dimension. </p>
| 3 | 2016-05-28T12:21:09Z | [
"python",
"keras"
] |
homebrew-services, password store, and python | 37,495,908 | <p>I'm trying to use <code>homebrew-services</code> to grab some passwords from <a href="https://www.passwordstore.org/" rel="nofollow"><code>pass</code></a>. So far I have this. But it doesn't work if I ran it through <a href="https://github.com/Homebrew/homebrew-services" rel="nofollow"><code>homebrew-services</code>... | 0 | 2016-05-28T06:21:57Z | 37,531,602 | <p>On OS X users are not allowed to use <code>/tmp</code>, you need to use <code>mktemp</code> in order to get a path to a temporary files.</p>
<p>Yep, your user temp directory is not under /tmp on OS X. </p>
<p>Do not ever assume that <code>/tmp</code> can be used, that's why mktemp exists.</p>
| 0 | 2016-05-30T18:16:23Z | [
"python",
"homebrew"
] |
Having a hard time finding a Segmentation Fault in Python on code proven to work on other computers | 37,495,989 | <p>Edit: literally as soon as I posted it I found a way for it to work on my this PC. I had to do all my calculations individually like this:</p>
<pre><code> self.vel.x += self.acc.x
self.pos.x += self.vel.x + (0.5 * self.acc.x)
self.vel.y += ........
</code></pre>
<p>keeping the question up in case someo... | 1 | 2016-05-28T06:31:51Z | 37,496,550 | <p>My guess would be that there's a reference to a Vector2 object that isn't being counted. The key is in how the <a href="https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements" rel="nofollow"><code>+=</code> augmented assignment</a> behaves; it isn't guaranteed to operate in-place (it o... | 0 | 2016-05-28T07:44:40Z | [
"python",
"pygame"
] |
python - invalid value encountered in log | 37,496,299 | <p>I have the following expression:
<code>log = np.sum(np.nan_to_num(-y*np.log(a+ 1e-7)-(1-y)*np.log(1-a+ 1e-7)))</code></p>
<p>it is giving me the following warning:</p>
<pre><code>RuntimeWarning: invalid value encountered in log
log = np.sum(np.nan_to_num(-y*np.log(a+ 1e-7)-(1-y)*np.log(1-a+ 1e-7)))
</code></pre>... | 0 | 2016-05-28T07:14:59Z | 37,496,353 | <p>You probably still have negative values inside the log, which gives nan with real numbers.</p>
<p><code>a</code> and <code>y</code> should represent probability between 0 to 1, So you need to check why do you have smaller/larger values there. Adding 1e-7 shows there is something fishy, because <code>np.log(0)</code... | 1 | 2016-05-28T07:21:29Z | [
"python",
"numpy",
"math",
"cross-entropy"
] |
python - invalid value encountered in log | 37,496,299 | <p>I have the following expression:
<code>log = np.sum(np.nan_to_num(-y*np.log(a+ 1e-7)-(1-y)*np.log(1-a+ 1e-7)))</code></p>
<p>it is giving me the following warning:</p>
<pre><code>RuntimeWarning: invalid value encountered in log
log = np.sum(np.nan_to_num(-y*np.log(a+ 1e-7)-(1-y)*np.log(1-a+ 1e-7)))
</code></pre>... | 0 | 2016-05-28T07:14:59Z | 37,581,340 | <p>you can use math.log() replacing numpy.log(),which could raise error</p>
<blockquote>
<blockquote>
<blockquote>
<p>import numpy
numpy.log(0)
-inf
numpy.<strong>version</strong>
'1.3.0'
import math
math.log(0)
Traceback (most recent call last):
File "", l... | 0 | 2016-06-02T01:39:47Z | [
"python",
"numpy",
"math",
"cross-entropy"
] |
PyQt: Dragging item from list view and dropping to table view, the drop index is always -1 | 37,496,320 | <p>In my code I have successfully implemented Drag n Drop from one QListView to another QListView and internal move is also working fine.
Now, due to a necessity, I have modified view that accepts drops i.e. I am trying to Drag from QListView to QTableView instead. </p>
<p>The issue is, when I dropped on QTableView, ... | 0 | 2016-05-28T07:17:05Z | 37,496,919 | <p>This was resolved after replacing: </p>
<pre><code>index = self.indexAt(event.pos()).row()
</code></pre>
<p>with</p>
<pre><code>index = self.rowAt(event.pos().y())
</code></pre>
<p>in dropEvent() method.</p>
| 0 | 2016-05-28T08:35:04Z | [
"python",
"qt",
"drag-and-drop",
"pyqt",
"pyqt4"
] |
Python - Retrieve and replace based on a regex | 37,496,480 | <p>Basically I've imported a csv of about 17000 rows into a pandas dataframe. There is a date column that has been imported as <code>int64</code> because data quality is very poor. Examples of dates include <code>11969</code>, <code>12132001</code>, <code>1022013</code>, etc. So I figure what I want to do is retrieve j... | 0 | 2016-05-28T07:37:07Z | 37,496,924 | <p>It seems like your method actually does work (at least for the examples you gave):</p>
<pre><code>import pandas as pd
rng = pd.Series([11969, 12132001, 1022013, 1022013])
test_str = str(rng)
flags = re.MULTILINE
p = r'\d{4}$'
result = re.findall(p, test_str, flags)
print(result)
# ['1969', '2001', '2013', '2013'] #... | 1 | 2016-05-28T08:35:43Z | [
"python",
"python-2.7",
"pandas",
"jupyter-notebook"
] |
Issue when importing matplotlib | 37,496,685 | <p>I've setted up a virtual enviroment for playing around with machine learning using <code>pyenv</code>. When i run <code>import matplotlib.pyplot as plt</code> this i what i get:</p>
<pre><code>ImportError Traceback (most recent call last)
<ipython-input-1-eff513f636fd> in <mod... | 0 | 2016-05-28T08:00:54Z | 37,509,011 | <p>I've figured out the solution! It seems that the python version (<code>2.7.11</code>) that i was using in my virtual environment was configured in order to use <code>unicode=ucs4</code>, so simply uninstalling virtualenv/python version and running</p>
<pre><code>PYTHON_CONFIGURE_OPTS="--enable-unicode=ucs2" pyenv i... | 1 | 2016-05-29T10:53:39Z | [
"python",
"matplotlib",
"homebrew",
"osx-yosemite",
"pyenv"
] |
django cms error in migrate - Found wrong number (0) of constraints | 37,496,734 | <p>I installed application in AWS and made a new databse.</p>
<p>I ran python manage.py migrate</p>
<p>But below error's occurred. </p>
<p>I use mysql. I don't know what change things in schema.</p>
<p>Please, help me out.</p>
<pre><code>INSTALLED_APPS = [
'cms',
'treebeard',
'menus',
'sekizai',
... | 0 | 2016-05-28T08:08:22Z | 37,497,131 | <p>I did like "python manage.py migrate --fake"</p>
<p>So far, it seems to be finished in migrations.</p>
<p>It seems --fake option is to pass old actions in modules so that new installation is not effected by old ones, just install new one.</p>
<p>But, in this case, schema is not created for cms. --fake option is n... | 0 | 2016-05-28T09:01:57Z | [
"python",
"mysql",
"django",
"content-management-system"
] |
Python , Separation days and made avarage in queryset for chart | 37,496,743 | <p>I just have a queryset that return collection of records that have amount , I wanna show chart by avarage in everyday . this is my code but I think it's really aweful for performance .
any advice to make it better ?</p>
<pre><code>month_query = table.objects.filter(time__gt=datetime.now() - timedelta(30))
for day i... | 0 | 2016-05-28T08:09:57Z | 37,497,068 | <p>You can use <code>values</code> and <code>annotate</code> to let django to do that:</p>
<pre><code>from django.db.models import Avg
month_days_avg = MyModel.objects.filter(time__gt=datetime.now() - timedelta(30)).values('time').annotate(average_amount=Avg('amount'))
</code></pre>
<p>The above query will result a l... | 0 | 2016-05-28T08:53:54Z | [
"python",
"loops",
"django-queryset"
] |
Combining discrete and/or overlapping time sequences from lists | 37,496,759 | <p>I have 2 lists of ordered times which are the start/stop times for ServiceA and ServiceB, respectively. I want to combine the lists in one list containing the start and stop times (in order) of when at least 1 of the services was running. (Both services always start after 00:01:00 and stop before 23:59:00.)</p>
<pr... | 3 | 2016-05-28T08:11:40Z | 37,497,364 | <p>You could do this without a single for-loop by using <a href="https://docs.python.org/3/library/functools.html#functools.reduce" rel="nofollow"><code>itertools.reduce</code></a> from the standard library to do the heavy lifting. Some consider this to be more idiomatic (except Guido of course who doesn't like the <co... | 1 | 2016-05-28T09:29:13Z | [
"python",
"python-2.7",
"time",
"set-intersection"
] |
Combining discrete and/or overlapping time sequences from lists | 37,496,759 | <p>I have 2 lists of ordered times which are the start/stop times for ServiceA and ServiceB, respectively. I want to combine the lists in one list containing the start and stop times (in order) of when at least 1 of the services was running. (Both services always start after 00:01:00 and stop before 23:59:00.)</p>
<pr... | 3 | 2016-05-28T08:11:40Z | 37,499,952 | <h2>Breaking down the problem</h2>
<p>Your code can be more readable if you break it down into functions and plan before coding.</p>
<p>Your problem can be broken down into smaller manageable parts:</p>
<ol>
<li>Create a function that returns the total uptime of two timings.</li>
<li>Sort the timings in <code>aList<... | 0 | 2016-05-28T14:06:00Z | [
"python",
"python-2.7",
"time",
"set-intersection"
] |
Why is datetime(1970, 1, 1).timestamp() affected by timezone? (or, what is "timezone naive"?) | 37,496,773 | <p>datetime object in Python is timezone naive by default. I was thinking this means if you construct a datetime object as below, you would always get 0 (but not):</p>
<pre><code>from datetime import datetime
print(datetime(1970, 1, 1).timestamp())
# -32400.0 on my machine
</code></pre>
<p>As you can see, the datetim... | 0 | 2016-05-28T08:13:25Z | 37,496,845 | <p>Timezone naive objects don't mean that they aren't affected by the timezone, just that they don't have enough information to distinguish where that time refers to. From this <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">datetime documentation</a>, it says: </p>
<blockquote>
<p>A naive o... | 2 | 2016-05-28T08:23:31Z | [
"python",
"datetime"
] |
what can be the item in "import item" in python? | 37,496,828 | <p>I have following hierarchy.</p>
<pre><code>A\
B\
__init__.py
testB.py
C\
__init__.py
test1.py
test2.py
</code></pre>
<p>when I write following in testB.py</p>
<pre><code>import C
test1.func1()
test2.func2()
</code></pre>
<p>Why I am unable to call the functions defined inside test... | 2 | 2016-05-28T08:21:38Z | 37,496,882 | <p>You probably think about Python imports in a C way. But Python imports work like this:</p>
<pre><code>import C.test1
import C.test2
C.test1.func1()
C.test2.func2()
</code></pre>
<p>or </p>
<pre><code>from C import test1, test2
test1.func1()
test2.func2()
</code></pre>
| 3 | 2016-05-28T08:29:58Z | [
"python",
"import"
] |
what can be the item in "import item" in python? | 37,496,828 | <p>I have following hierarchy.</p>
<pre><code>A\
B\
__init__.py
testB.py
C\
__init__.py
test1.py
test2.py
</code></pre>
<p>when I write following in testB.py</p>
<pre><code>import C
test1.func1()
test2.func2()
</code></pre>
<p>Why I am unable to call the functions defined inside test... | 2 | 2016-05-28T08:21:38Z | 37,496,884 | <p>When you <code>import C</code>, the Python import mechanism doesn't look through your <code>C</code> directory and automatically import every ".py" file from that directory. This saves on memory and time - suppose that directory <code>C</code> was a huge package; it wouldn't optimize memory space to import everythi... | 1 | 2016-05-28T08:30:20Z | [
"python",
"import"
] |
what can be the item in "import item" in python? | 37,496,828 | <p>I have following hierarchy.</p>
<pre><code>A\
B\
__init__.py
testB.py
C\
__init__.py
test1.py
test2.py
</code></pre>
<p>when I write following in testB.py</p>
<pre><code>import C
test1.func1()
test2.func2()
</code></pre>
<p>Why I am unable to call the functions defined inside test... | 2 | 2016-05-28T08:21:38Z | 37,497,903 | <p>First option: You could add a</p>
<pre class="lang-python prettyprint-override"><code>from test1 import *
from test2 import *
</code></pre>
<p>or</p>
<pre class="lang-python prettyprint-override"><code>from test1 import func1
from test2 import func2
</code></pre>
<p>(the second option is clearly better, <code>fr... | 0 | 2016-05-28T10:30:07Z | [
"python",
"import"
] |
What's wrong with Python datetime.now() in this piece of codes? | 37,496,865 | <p>here is the codes:</p>
<pre><code>>>> from datetime import datetime
>>> t=datetime.now()
>>> print(t)
</code></pre>
<p>And I got such a result:</p>
<pre><code>2016-05-28 16:17:56.192505
</code></pre>
<p>How does the float number come? How could I solve it?</p>
<p>Environment: Python 3... | -4 | 2016-05-28T08:26:14Z | 37,496,879 | <p>The floating-point figure represents the seconds with microseconds. There is no need to "solve" it because it is working correctly. If you don't want to show it, format the date into a string with a custom format string that excludes the microseconds. For example:</p>
<pre><code>>>> datetime.datetime.now()... | 2 | 2016-05-28T08:29:35Z | [
"python",
"datetime"
] |
How to "Crop" a Rotated Image In Pygame | 37,496,866 | <p><strong>Problem:</strong></p>
<p>I'm trying to draw a rotating image in Pygame but I only want the top half of the image to be displayed. I have managed to rotate the image so that it is centered correctly but I am unable to crop it to only display the top half. </p>
<p>I think that this is due to the rect being r... | 2 | 2016-05-28T08:26:39Z | 37,504,408 | <p>You have to put crop variable in brackets, so:</p>
<p>Your code:</p>
<pre><code>crop = (0, 0, 120, 60)
cropped = newcircle.subsurface(crop)
</code></pre>
<p>Right code:</p>
<pre><code>crop = (0, 0, 120, 60)
cropped = newcircle.subsurface((crop))
</code></pre>
<p>Notice me if that works.</p>
| 1 | 2016-05-28T22:44:09Z | [
"python",
"python-3.x",
"rotation",
"pygame"
] |
How to "Crop" a Rotated Image In Pygame | 37,496,866 | <p><strong>Problem:</strong></p>
<p>I'm trying to draw a rotating image in Pygame but I only want the top half of the image to be displayed. I have managed to rotate the image so that it is centered correctly but I am unable to crop it to only display the top half. </p>
<p>I think that this is due to the rect being r... | 2 | 2016-05-28T08:26:39Z | 37,505,041 | <p>Is this the effect that you want to achieve? You have to calculate the new crop position after each rotation, because the size of the rotated image changes all the time. In the upper left corner you see how the parent image/surface changes.</p>
<pre><code>import sys
import pygame as pg
def main():
pg.init()
... | 1 | 2016-05-29T00:35:39Z | [
"python",
"python-3.x",
"rotation",
"pygame"
] |
Population Monte Carlo implementation | 37,496,969 | <p>I am trying to implement the Population Monte Carlo algorithm as described in <a href="http://www.sciencedirect.com/science/article/pii/S0022249612000272" rel="nofollow">this</a> paper (see page 78 Fig.3) for a simple model (see function <code>model()</code>) with one parameter using Python. Unfortunately, the algor... | 2 | 2016-05-28T08:40:53Z | 37,753,870 | <p>I stumbled upon this question as I was looking for pythonic implementations of PMC algorithms, since, quite coincidentally, I'm currently in the process of applying the techniques in this exact paper to my own research.</p>
<p>Can you post the results you're getting? My guess is that 1) you're using a poor choice o... | 2 | 2016-06-10T17:17:02Z | [
"python",
"montecarlo",
"approximation",
"mcmc"
] |
Access the row number by its index | 37,497,094 | <p>I'm trying to access the row number with an index value corresponding to that row.</p>
<pre><code>mydata = [{'name': 'John', 'age': 75, 'height':1.78},
{'name': 'Paul', 'age': 22, 'height':1.71}]
df = pandas.DataFrame(mydata)
df = df.set_index('name')
</code></pre>
<p>Get index value of row number 1</p>
<p... | 2 | 2016-05-28T08:57:32Z | 37,497,181 | <p>You can also use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html" rel="nofollow"><code>get_loc</code></a>:</p>
<pre><code>df.index.get_loc(index_value)
Out[67]: 1
</code></pre>
| 3 | 2016-05-28T09:07:30Z | [
"python",
"pandas"
] |
import matplotlib graph in a tkinter GUI. Error in show() | 37,497,214 | <p>I'm trying to embed a matplotlib graph in my tkinter GUI. After many attempts of trying examples posted on the matplotlib site, none of them seem to work.</p>
<p>For example:</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
import matplotlib
matplotlib.use('TkAgg')
from numpy import aran... | 4 | 2016-05-28T09:10:45Z | 37,650,622 | <p>I had similar problem so this worked for me,
If you are using windows I suggest uninstall <code>pillow</code> and <code>matplotlib</code> and reinstall from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">here</a></p>
| 1 | 2016-06-06T06:13:21Z | [
"python",
"user-interface",
"matplotlib",
"tkinter",
"show"
] |
How to store data from Tweepy's user_Lookup method into csv file? | 37,497,246 | <p>I was able to print out the specific user_info using Tweepy but I would like to store the data into csv file. As is, I am getting an encoding error. How can I store the data in csv file?</p>
<pre><code>import tweepy
import csv
access_token = ""
access_token_secret = ""
consumer_key = ""
consumer_secret = ""
auth ... | 1 | 2016-05-28T09:14:26Z | 37,505,040 | <p>You sould be able to create your .csv file using tweepy and csv as follows, </p>
<pre><code>api = tweepy.API(auth)
csvFile = open('filename.csv', 'w')
csvWriter = csv.writer(csvFile)
for user in api.lookup_users(user_ids=["id"]):
t=user.description
csvWriter.writerow(t) #will print in comma separated v... | 0 | 2016-05-29T00:35:38Z | [
"python",
"csv",
"user",
"lookup",
"tweepy"
] |
Theano gradient with function on tensors | 37,497,349 | <p>I have a function that calculates a value of a scalar field on a 3D space, so I feed it 3D tensors for x, y and z coordinates (obtained by numpy.meshgrid) and use elementwise operations everywhere. This works as expected.</p>
<p>Now I need to calculate a gradient of the scalar field. I've been playing around with <... | 3 | 2016-05-28T09:27:32Z | 37,501,354 | <p>The first element <code>expr[0,0]</code> as a cost with respect to <code>x</code> only relates to the first element of <code>x</code> thus the result you are receiving is correct.</p>
<p>The result you expect is produced if you sum the whole <code>expr</code> array. Theano will take care of backward propagating the... | 2 | 2016-05-28T16:26:19Z | [
"python",
"theano",
"differentiation"
] |
socket.makefile issues in python 3 while creating a http proxy | 37,497,461 | <pre><code>from socket import *
import sys
# Create a server socket, bind it to a port and start listening
tcpSerSock = socket(AF_INET, SOCK_STREAM)
serverPort = 12000
tcpSerSock.bind(('', serverPort))
tcpSerSock.listen(1)
print ("Server ready")
while 1==1:
# Start receiving data from the client. e.g. request = "GE... | 0 | 2016-05-28T09:41:29Z | 37,503,043 | <p>This is a python2.7 vs python3 issue. While <code>makefile('r',0)</code> works in python 2.7, you need <code>makefile('r',None)</code> in python3.</p>
<p>From the documentation for python2.7:
<code>socket.makefile([mode[, bufsize]])</code></p>
<p>From the documentation for python3:
<code>socket.makefile(mode='r', ... | 0 | 2016-05-28T19:28:17Z | [
"python",
"python-3.x",
"proxy",
"makefile"
] |
Regex matching the end of a line correctly | 37,497,472 | <p>I'm looking for a way to <code>re.sub</code> lines ending with <code>\n</code> and <code>\r\n</code> while preserving the line ending.</p>
<pre><code>import re
data = "Foo\r\nFoo\nFoo"
regex = r"^Foo$"
re.sub(regex, "Bar", data, flags=re.MULTILINE)
</code></pre>
<p>leaves me with</p>
<pre><code>Foo\r\nBar\nBar
</... | 0 | 2016-05-28T09:42:32Z | 37,497,512 | <p>Make the <code>\r</code> and <code>\n</code> optional with <code>?</code>, and specify them as a capture group so you can refer to them in the callback function for the replacement:</p>
<pre><code>>>> re.sub('^Foo(\r?\n?)$', r'Bar\1', 'Foo\r\nFoo\nFoo', flags=re.MULTILINE)
'Bar\r\nBar\nBar'
</code></pre>
... | 1 | 2016-05-28T09:47:30Z | [
"python",
"regex"
] |
Regex matching the end of a line correctly | 37,497,472 | <p>I'm looking for a way to <code>re.sub</code> lines ending with <code>\n</code> and <code>\r\n</code> while preserving the line ending.</p>
<pre><code>import re
data = "Foo\r\nFoo\nFoo"
regex = r"^Foo$"
re.sub(regex, "Bar", data, flags=re.MULTILINE)
</code></pre>
<p>leaves me with</p>
<pre><code>Foo\r\nBar\nBar
</... | 0 | 2016-05-28T09:42:32Z | 37,497,529 | <p>Use <a href="https://docs.python.org/2/howto/regex.html#lookahead-assertions" rel="nofollow">positive lookahead assertion</a></p>
<pre><code>import re
data = "Foo\r\nFoo\nFoo"
regex = r"^Foo(?=\r?\n?$)"
re.sub(regex, "Bar", data, flags=re.MULTILINE)
</code></pre>
<p>Output :</p>
<pre><code>'Bar\r\nBar\nBar'
</cod... | 1 | 2016-05-28T09:49:43Z | [
"python",
"regex"
] |
Python Scraping - Selenium - Element is not clickable at point | 37,497,527 | <p>I'm trying to click the next button on a webpage multiple times, I need scrape the page after each click. The following code is shortened but illustrates my situation. I am able to scrape the required tag after the first click, but then the second click fails. Here is the code</p>
<pre><code>from selenium import we... | 0 | 2016-05-28T09:49:35Z | 37,497,851 | <p>The first time you click the next page starts to load, you can't click on a link that is on a page that is still loading or on a link on a page that is about to be replaced by another page! So the message is quite correct. So you just have to wait for the next page to appear before you can click on the next link. Yo... | 1 | 2016-05-28T10:24:33Z | [
"python",
"selenium",
"screen-scraping",
"clickable"
] |
Python Pandas Identify Duplicated rows with Additional Column | 37,497,559 | <p>I have the following <code>Dataframe</code>:</p>
<pre><code>df
Out[23]:
PplNum RoomNum Value
0 1 0 265
1 1 12 170
2 2 0 297
3 2 12 85
4 2 0 41
5 2 12 144
</code></pre>
<p>Generally the <code>PplNum</code> and <code... | 4 | 2016-05-28T09:53:07Z | 37,497,576 | <p>you can do it using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby()</a> together with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow">cumcount()</a> function:</p>
<pre><cod... | 4 | 2016-05-28T09:55:39Z | [
"python",
"pandas",
"dataframe"
] |
Python Pandas Identify Duplicated rows with Additional Column | 37,497,559 | <p>I have the following <code>Dataframe</code>:</p>
<pre><code>df
Out[23]:
PplNum RoomNum Value
0 1 0 265
1 1 12 170
2 2 0 297
3 2 12 85
4 2 0 41
5 2 12 144
</code></pre>
<p>Generally the <code>PplNum</code> and <code... | 4 | 2016-05-28T09:53:07Z | 37,497,630 | <p>Here is my approach with a recursive function:</p>
<pre><code>dfnondup = df.drop_duplicates(['PplNum', 'RoomNum'])
def rename_dup(df):
def rename_dup(df, c, dfnew):
dfnondup = df.drop_duplicates(['PplNum', 'RoomNum'])
dfnondup['C'] = pd.Series([c] * len(dfnondup), index=dfnondup.index)
... | 2 | 2016-05-28T10:01:40Z | [
"python",
"pandas",
"dataframe"
] |
How to sum numbers in Dataframe based on length of keywords? | 37,497,569 | <p>I have a sample of search engine DataFrame which has 2 columns: entered keyword to search and number of searches of this keyword.
Example:</p>
<pre><code> df = pd.DataFrame({'keyword': ['one','one two','2','two 34 45', 'ab', 'long 1 4 ab'],
'number of searches': ['4', '9', '1', '2', '7', '1']})
</code></pre>
<p>I ... | -1 | 2016-05-28T09:54:06Z | 37,497,884 | <p>you can do it this way:</p>
<p>first, make sure that your <code>number of searches</code> column is of integer data type:</p>
<pre><code>df['number of searches'] = df['number of searches'].astype(int)
(df.groupby(df.keyword.str.split().apply(len))['number of searches']
.sum()
.to_frame()
.reset_index()
... | 1 | 2016-05-28T10:28:39Z | [
"python",
"pandas",
"dataframe"
] |
Regex - Python: Capture three (3) words after a specific word | 37,497,634 | <p>Hello everyone I have the following code:</p>
<pre><code>str1 = "Hello, I would like to meet you at the train station of Berlin after 6 o' clock"
match = re.compile(r' at \w+ \w+ \w+')
match.findall(str1)
</code></pre>
<p>Is there a better way than "\w+ \w+ \w" so for example to capture specific number of words?<... | -2 | 2016-05-28T10:01:56Z | 37,498,893 | <p>Yes. To specify a particular count for the match, use curly-braces. E.g.,:</p>
<pre><code>match = re.compile(r'at ((\w+ ){3})')
</code></pre>
<p>Which gives:</p>
<pre><code>>>> print match.findall(str1)
[('the train station ', 'station ')]
</code></pre>
<p>In general, to capture just the <code>n</code> ... | 0 | 2016-05-28T12:18:20Z | [
"python",
"regex"
] |
Square root calculation using bisection | 37,497,733 | <p>I have the following code which should find the square root using bisection, but for some reason it won't. When I want to find the square root of 9 I get 4.5. </p>
<pre><code>y = float(input('Enter the number that you want to find the square root of: '))
z = y
x = 0
ans = 0
while abs(ans**2 - abs(y)) > 0.0001 a... | -1 | 2016-05-28T10:11:50Z | 37,497,768 | <p>Square root of a number x: <code>sqrt=x**(1.0/2)</code></p>
<p>Alternative :</p>
<pre><code>import math
math.sqrt(x)
</code></pre>
<p>Using bisection algorithm:</p>
<pre><code>y = float(input('Enter the number that you want to find the square root of: '))
num = y
x = 0
ans = 0
while abs(ans**2 - abs(num)) > ... | 0 | 2016-05-28T10:16:13Z | [
"python"
] |
Square root calculation using bisection | 37,497,733 | <p>I have the following code which should find the square root using bisection, but for some reason it won't. When I want to find the square root of 9 I get 4.5. </p>
<pre><code>y = float(input('Enter the number that you want to find the square root of: '))
z = y
x = 0
ans = 0
while abs(ans**2 - abs(y)) > 0.0001 a... | -1 | 2016-05-28T10:11:50Z | 37,497,810 | <p>You need to check if <code>ans <= y</code>, because <code>y</code> is your right border in this case. Also you need to compare <code>ans**2</code> to the absolute value of <code>z</code>, not <code>y</code>, because you are changing <code>y</code> inside the loop:</p>
<pre><code>while abs(ans**2 - abs(z)) > 0... | 1 | 2016-05-28T10:20:32Z | [
"python"
] |
Square root calculation using bisection | 37,497,733 | <p>I have the following code which should find the square root using bisection, but for some reason it won't. When I want to find the square root of 9 I get 4.5. </p>
<pre><code>y = float(input('Enter the number that you want to find the square root of: '))
z = y
x = 0
ans = 0
while abs(ans**2 - abs(y)) > 0.0001 a... | -1 | 2016-05-28T10:11:50Z | 37,498,444 | <p>Keiwan has explained what was wrong with your script, but here's a slightly different way to organize the logic. I've changed some of the variable names to make the code more readable, and I've put it into a function to make it easier to use. The code below works on Python 2 or Python 3, although there are minor dif... | 0 | 2016-05-28T11:31:03Z | [
"python"
] |
How to get data from youtube api automaticly when you add item on django | 37,497,789 | <p>I have model class in Django such as</p>
<pre><code>class YoutubeVideo(models.Model):
title = models.CharField(max_length=200,blank=True,null=True)
video_id = models.CharField(max_length=2000, unique=True)
duration = models.CharField(blank=True,null=True,max_length=200)
def __unicode__(self):
... | 0 | 2016-05-28T10:18:42Z | 37,503,661 | <p>Extend the save method of your model:</p>
<pre><code>def save(self, **kwargs):
if self.video_id is not None and self.duration is None:
self.duration = call_youtube_to_get_duration()
return super(YoutubeVideo, self).save(**kwargs)
</code></pre>
| 1 | 2016-05-28T20:56:36Z | [
"python",
"django",
"youtube-api"
] |
Classification of sparse data | 37,497,795 | <p>I am struggling with the best choice for a classification/prediction problem. Let me explain the task - I have a database of keywords from abstracts for different research papers, also I have a list of journals with specified impact factors. I want to build a model for article classification based on their keywords,... | 0 | 2016-05-28T10:19:04Z | 37,499,607 | <p>There is nothing wrong with using this coding strategy for text and support vector machines.</p>
<p>For your actual objective:</p>
<ul>
<li>support vector <em>regression</em> (SVR) may be more appropriate</li>
<li>beware of the journal impact factor. It is very crude. You need to take temporal aspects into account... | 0 | 2016-05-28T13:29:03Z | [
"python",
"classification",
"data-mining",
"text-classification"
] |
file opening dialog & drag and drop in pygame | 37,497,815 | <p>I want to build a little application; and it has to have some sort of possibility to load files. Right now I am just copying the path into the application, but I do want to build a possibility to</p>
<ul>
<li>drop a file from outside into the GUI and</li>
<li>have a file opening dialog.</li>
</ul>
<p>Is there a wa... | 0 | 2016-05-28T10:21:16Z | 37,574,564 | <p>You can use an file opening dialog from tkinter. </p>
<p>To get a filename the code will be:</p>
<pre><code>from tkinter.filedialog import askopenfilename
## OR from tkinter.filedialog import *
from tkinter import *
root = Tk()
foo = askopenfilename()
root.destroy()
print(foo)
</code></pre>
| 1 | 2016-06-01T16:51:29Z | [
"python",
"python-3.x",
"pygame"
] |
I can't connect mongodb with django | 37,497,857 | <p>I use mongoengine. and below is my settings:</p>
<pre><code> _MONGODB_USER = 'user1'
_MONGODB_PASSWD = '12345678'
_MONGODB_HOST = 'mongodb://user1:damian123@ds99999.mlab.com:23932/projekt_dkjp'
_MONGODB_NAME = 'baza1'
_MONGODB_DATABASE_HOST = \
'mongodb://%s:%s@%s/%s' \
% (_MONGOD... | 0 | 2016-05-28T10:25:21Z | 37,499,271 | <p>Basically, DATABASES should look something like this:</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}
</code></pre>
<p>Source: <a href="https://docs.djangoproject.com/en/dev/ref/settings/#databases" rel="nofollow">Link</a></p>
<p>Easy to un... | 0 | 2016-05-28T12:56:40Z | [
"python",
"django",
"database",
"mongodb",
"mongoengine"
] |
psycopg2 set PRIMARY KEY from tuple with placeholder | 37,497,861 | <p>How can I set a primary key in psycopg2 from a tuple of values being looped in from a tuple?</p>
<p>for example i have my tuple</p>
<pre><code>meetattrs = ('id', 'venue', 'date', 'rail', 'weather', 'trackcondition')
</code></pre>
<p>and then I want to create the table and extract and insert values. From the meeta... | 1 | 2016-05-28T10:26:06Z | 37,525,976 | <p>In that kind of problem, you should first try to build and control the sql string.</p>
<pre><code>("create table meetings (id integer PRIMARY KEY, " +
", ".join("%s varchar" % fld for fld in meetattrs)
+ ")")
</code></pre>
<p>gives: </p>
<pre><code>'create table meetings (id integer PRIMAR... | 1 | 2016-05-30T12:42:54Z | [
"python",
"psycopg2"
] |
psycopg2 set PRIMARY KEY from tuple with placeholder | 37,497,861 | <p>How can I set a primary key in psycopg2 from a tuple of values being looped in from a tuple?</p>
<p>for example i have my tuple</p>
<pre><code>meetattrs = ('id', 'venue', 'date', 'rail', 'weather', 'trackcondition')
</code></pre>
<p>and then I want to create the table and extract and insert values. From the meeta... | 1 | 2016-05-28T10:26:06Z | 37,526,032 | <p>Your current sql query after the <code>join</code> is performed and the placeholders take their values is:</p>
<pre><code>'create table meetings (id integer PRIMARY KEY, id varchar, venue varchar, date varchar, rail varchar, weather varchar, trackcondition varchar)'
</code></pre>
<p><code>id</code> is specified tw... | 1 | 2016-05-30T12:45:19Z | [
"python",
"psycopg2"
] |
Filter information of a txt file by regular expressions | 37,497,894 | <p>I have a file with information, this is how it looks like:</p>
<pre><code>****ALIGNMENT****
Sequence: gi|86755972|gb|ABD15130.1| cold acclimation protein COR413-PM1 [Chimonanthus praecox]
Length: 201
E-value: 2.66576e-82
KYLAMKTDQLAVANMIDSDINELKMATMRLINDASMLGHYGFGTHFLKWLACLAAIYLLILDRTNWRTNMLTSLL...
+YLAMKTD+ + ... | 1 | 2016-05-28T10:29:23Z | 37,504,604 | <p>Use a regex like</p>
<pre><code>^Sequence:[^|]*\|(?P<hitsid>[^|]*)\|\S*\s*(?P<protein>[^][]*?)\s*\[(?P<organism>[^][]*)][\s\S]*?\nE-value:\s*(?P<evalue>.*)
</code></pre>
<p>See the <a href="https://regex101.com/r/zG8xM4/2" rel="nofollow">regex demo</a></p>
<p>A <a href="http://ideone.com/P... | 0 | 2016-05-28T23:15:20Z | [
"python",
"regex",
"expression"
] |
Python - FOR loop not writing correct values in nested dictionaries | 37,497,905 | <p>Hopefully someone can help me with this as none of my research has helped me. I have a simple dictionary:</p>
<pre><code>mydict = {
1: {1: 'Foo'},
2: {1: 'Bar'}
}
</code></pre>
<p>I'm duplicating each of the key / value pairs assigning new key values:</p>
<pre><code>nextKey = len(mydict) + 1
for currK... | 1 | 2016-05-28T10:30:23Z | 37,498,027 | <p>This happens because in your first loop you are not copying the nested dictionaries but rather just adding a new reference to the same dictionaries.</p>
<p>To maybe give a clearer example: If you were to break out of the second loop after two loops (with your original code) your output would be:</p>
<pre><code>{1:... | 0 | 2016-05-28T10:43:17Z | [
"python",
"for-loop",
"dictionary",
"nested"
] |
Python - FOR loop not writing correct values in nested dictionaries | 37,497,905 | <p>Hopefully someone can help me with this as none of my research has helped me. I have a simple dictionary:</p>
<pre><code>mydict = {
1: {1: 'Foo'},
2: {1: 'Bar'}
}
</code></pre>
<p>I'm duplicating each of the key / value pairs assigning new key values:</p>
<pre><code>nextKey = len(mydict) + 1
for currK... | 1 | 2016-05-28T10:30:23Z | 37,498,051 | <p>Your assumption is right. Minimal example:</p>
<pre><code>>>> a = {1: {"a": "A"}, 2:{"b": "B"}}
>>> a[3] = a[1]
>>> a
{1: {'a': 'A'}, 2: {'b': 'B'}, 3: {'a': 'A'}}
>>> id(a[3]) # a[1] and a[3] are the same object
140510365203264
>>> id(a[1])
140... | 0 | 2016-05-28T10:45:48Z | [
"python",
"for-loop",
"dictionary",
"nested"
] |
RFID reading using python via usb SyntaxError: invalid token | 37,497,933 | <p>I have two rfid card the values are 0004518403 and 000452738 after reading their value in python terminal. I want to give them name like 0004518403 is "javed" and 000452738 as "aquib". So when next time when I use the card it must not show me the value but it must show me the name which I've defined to them.</p>
<p... | 0 | 2016-05-28T10:33:15Z | 37,498,005 | <p>You should compare read results with strings, not numbers, like </p>
<pre><code>read_result=='0004520738'
</code></pre>
<p>0004520738 without quotes is a number. As it starts with a <code>0</code> sign, it is interpreted as number of base 8. Numbers of base 8 cannot contain digits <code>8</code> and <code>9</code>... | 2 | 2016-05-28T10:41:49Z | [
"python",
"rfid"
] |
Time out on lost connection in Paramiko | 37,497,945 | <p>I need to handle connectivity problems correctly while executing long-running commands over SSH with Paramiko.</p>
<p>The <code>exec_command</code> has a <code>timeout</code> argument but it throws an exception if there is no response. So it raises when the connection is lost as well as when a command you execute w... | 0 | 2016-05-28T10:34:12Z | 37,531,654 | <p>Both cases are network failures, one is that it didn't work from start, the other one because it failed later. In the end there is no much difference between them.</p>
<p>It is up to you to decide how your code behaves in this case. The usual approach is to retry by inserting a growing timeout.</p>
<p>The most fam... | 0 | 2016-05-30T18:19:51Z | [
"python",
"ssh",
"paramiko"
] |
Can't figure out Web2py Ticket error its odd | 37,497,962 | <p>I'm new to Web2py and am unable to understand the error that the ticket is throwing up. Can someone explain the error and why it is occurring?</p>
<pre><code>Ticket ID
127.0.0.1.2016-05-28.15-45-10.493c5f3c-e5f2-4034-8e82-69637b1fcc35
<type 'exceptions.SyntaxError'> invalid table/column name "size" is a "ALL... | 0 | 2016-05-28T10:36:21Z | 37,501,474 | <p>In <code>db.define_table()</code>, it appears you have attempted to create a field named "size", which is not allowed because it is a SQL reserved word. You should either change the field name or use the "rname" argument to specify a different name for the database to use:</p>
<pre><code> Field('size', rname='ob... | 0 | 2016-05-28T16:40:12Z | [
"python",
"sqlite",
"web2py"
] |
Make variable from Python file available on command line | 37,497,999 | <p>I have a small Python file from a third-party package with</p>
<pre><code>$ cat a.py
a = 3.14
</code></pre>
<p>I would now like to make the value of <code>a</code> available on the command line. I initially thought that I just <code>grep</code>/<code>sed</code>/<code>awk</code> my way out of this, but perhaps ther... | 0 | 2016-05-28T10:41:20Z | 37,498,403 | <p>Here's a simple crude solution:</p>
<pre><code>$ cat a.py
a = 3.14
a *= 2
$ python <(cat a.py && echo '\nprint(a)')
6.28
</code></pre>
<p>There are various ways this might not work, but the constraints of your situation are not clear.</p>
<p>The <code>\n</code> is there to prevent a syntax error in th... | 3 | 2016-05-28T11:26:48Z | [
"python",
"shell"
] |
Replacing complex-valued arguments of generic function object by two real-valued arguments | 37,498,049 | <p>Curve fitting tools such as those in <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow">scipy</a> tend to assume that the parameters of the model functions are real-valued.
When fitting a model that depends on complex-valued parameters to a complex-valued data ... | 0 | 2016-05-28T10:45:34Z | 37,498,258 | <p>You do not have to do any nasty string based generation, you can simply use basic function closures to create a wrapper:</p>
<pre><code>def complex_unroll(f, are_complex):
# This function will have access to are_complex and f through python closure
# *args give us access to all parameters as a list
def... | 0 | 2016-05-28T11:11:28Z | [
"python",
"generics"
] |
Compare each pair of dates in two columns in python efficiently | 37,498,071 | <p>I have a data frame with a column of start dates and a column of end dates. I want to check the integrity of the dates by ensuring that the start date is before the end date (i.e. start_date < end_date).I have over 14,000 observations to run through.</p>
<p>I have data in the form of:</p>
<pre><code> Start ... | 1 | 2016-05-28T10:47:41Z | 37,498,118 | <p>Since the list doesn't need to be compared sequentially, you can gain performance by splitting your dataset and then using multiple processes to perform the comparison simultaneously. Take a look at the <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module for hel... | 1 | 2016-05-28T10:53:13Z | [
"python",
"date",
"for-loop",
"data-cleansing",
"data-cleaning"
] |
Compare each pair of dates in two columns in python efficiently | 37,498,071 | <p>I have a data frame with a column of start dates and a column of end dates. I want to check the integrity of the dates by ensuring that the start date is before the end date (i.e. start_date < end_date).I have over 14,000 observations to run through.</p>
<p>I have data in the form of:</p>
<pre><code> Start ... | 1 | 2016-05-28T10:47:41Z | 37,498,239 | <p>Something like the following may be quicker:</p>
<pre><code>import pandas as pd
import datetime
df = pd.DataFrame({
'start': ["2008-10-01", "2006-07-01", "2000-05-01"],
'end': ["2008-10-31", "2006-12-31", "2002-12-31"],
})
def comparison_check(df):
start = datetime.datetime.strptime(df['start'], "%Y-... | 0 | 2016-05-28T11:09:07Z | [
"python",
"date",
"for-loop",
"data-cleansing",
"data-cleaning"
] |
Compare each pair of dates in two columns in python efficiently | 37,498,071 | <p>I have a data frame with a column of start dates and a column of end dates. I want to check the integrity of the dates by ensuring that the start date is before the end date (i.e. start_date < end_date).I have over 14,000 observations to run through.</p>
<p>I have data in the form of:</p>
<pre><code> Start ... | 1 | 2016-05-28T10:47:41Z | 37,498,563 | <p>Why not just do it in a vectorized way:</p>
<pre class="lang-py prettyprint-override"><code>is_correct = dates['Start'] < dates['End']
is_incorrect = dates['Start'] > dates['End']
is_same = ~is_correct & ~is_incorrect
</code></pre>
| 2 | 2016-05-28T11:43:00Z | [
"python",
"date",
"for-loop",
"data-cleansing",
"data-cleaning"
] |
Apply formula with two different lists | 37,498,127 | <p>I have two lists like this:</p>
<pre><code>listA = [51, 988, 1336, 2067, 1857, 3160]
listB = [1, 2, 3, 4, 5, 6]
</code></pre>
<p>I have to apply this formula in the lists:</p>
<pre><code>n / pi * ((x*0.1)+1)**2 - pi * (x*0.1)**2
</code></pre>
<p>The 'n' is the elements of listA, 'x' is the elements that correspo... | 4 | 2016-05-28T10:53:57Z | 37,498,163 | <p>This code for first formula:</p>
<pre><code>from math import pi
def func(l1, l2):
l = list()
for x,n in zip(l1, l2):
l.append(n / pi * ((x*0.1)+1)**2 - pi * (x*0.1)**2)
return l
listA = [51, 988, 1336, 2067, 1857, 3160]
listB = [1, 2, 3, 4, 5, 6]
print func(listA, listB)
</code></pre>
<p>Out... | 1 | 2016-05-28T10:58:54Z | [
"python",
"list",
"python-2.7",
"math",
"formula"
] |
Apply formula with two different lists | 37,498,127 | <p>I have two lists like this:</p>
<pre><code>listA = [51, 988, 1336, 2067, 1857, 3160]
listB = [1, 2, 3, 4, 5, 6]
</code></pre>
<p>I have to apply this formula in the lists:</p>
<pre><code>n / pi * ((x*0.1)+1)**2 - pi * (x*0.1)**2
</code></pre>
<p>The 'n' is the elements of listA, 'x' is the elements that correspo... | 4 | 2016-05-28T10:53:57Z | 37,498,166 | <p>You can <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip()</code></a> them:</p>
<pre><code>for a, b in zip([1,2,3], [4,5,6]):
print a, b
</code></pre>
<p>will yield</p>
<pre><code>1 4
2 5
3 6
</code></pre>
| 1 | 2016-05-28T10:59:36Z | [
"python",
"list",
"python-2.7",
"math",
"formula"
] |
Apply formula with two different lists | 37,498,127 | <p>I have two lists like this:</p>
<pre><code>listA = [51, 988, 1336, 2067, 1857, 3160]
listB = [1, 2, 3, 4, 5, 6]
</code></pre>
<p>I have to apply this formula in the lists:</p>
<pre><code>n / pi * ((x*0.1)+1)**2 - pi * (x*0.1)**2
</code></pre>
<p>The 'n' is the elements of listA, 'x' is the elements that correspo... | 4 | 2016-05-28T10:53:57Z | 37,498,186 | <p>I assume both lists have the same size all the time, most pythonic way is to use lambda and list comprehensions:</p>
<pre><code>listA = [51, 988, 1336, 2067, 1857, 3160]
listB = [1, 2, 3, 4, 5, 6]
from math import pi
formula = lambda n,x: n / pi * ((x*0.1)+1)**2 - pi * (x*0.1)**2
res = [ formula(a,b) for a,b in ... | 4 | 2016-05-28T11:02:56Z | [
"python",
"list",
"python-2.7",
"math",
"formula"
] |
Apply formula with two different lists | 37,498,127 | <p>I have two lists like this:</p>
<pre><code>listA = [51, 988, 1336, 2067, 1857, 3160]
listB = [1, 2, 3, 4, 5, 6]
</code></pre>
<p>I have to apply this formula in the lists:</p>
<pre><code>n / pi * ((x*0.1)+1)**2 - pi * (x*0.1)**2
</code></pre>
<p>The 'n' is the elements of listA, 'x' is the elements that correspo... | 4 | 2016-05-28T10:53:57Z | 37,498,236 | <p>numpy <strong>vectorized</strong> approach will be <strong>much</strong> faster compared to regular for/list comprehension/etc. especially on big lists:</p>
<pre><code>import numpy as np
listA = np.array([51, 988, 1336, 2067, 1857, 3160])
listB = np.array([1, 2, 3, 4, 5, 6])
result = listA / np.pi * ((listB*0.1)+1... | 1 | 2016-05-28T11:08:59Z | [
"python",
"list",
"python-2.7",
"math",
"formula"
] |
Django template - get matching foreign key objects in a template? | 37,498,267 | <p>I have a model named circuits and each circuit may have many files associated to it.</p>
<p>so in my view i am getting all the circuits and all the files, then i am trying to get the files to match the circuits in my template using an if statement.</p>
<p>i have tried, the below but all come back empty, how do i t... | 0 | 2016-05-28T11:12:20Z | 37,498,763 | <p>Looping through and comparing the objects is inefficient and unnecessary because you can <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward" rel="nofollow">query the foreign key relationship backwards</a> like so:</p>
<pre><code>{% for item in Circuits %}
<tr c... | 4 | 2016-05-28T12:04:12Z | [
"python",
"django"
] |
Construct an example where the KMP algorithm has to backtrack multiple times | 37,498,272 | <p>I'm trying to construct an example where the <a href="http://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/" rel="nofollow">kmp algorithm</a> <code>computeLPSArray</code> phase will have to backtrack (see comment below) multiple times for a certain i (cell in the LPS array).</p>
<p>e.g. for <code... | 1 | 2016-05-28T11:12:42Z | 37,499,075 | <p>With <code>'AAAACAA'</code> it visits the backtrack section 3 times for <code>i = 4</code>.</p>
<p>With <code>'AAAAACA'</code> it visits the backtrack section 4 times for <code>i = 5</code>.</p>
| 2 | 2016-05-28T12:36:18Z | [
"python",
"string",
"algorithm"
] |
Construct an example where the KMP algorithm has to backtrack multiple times | 37,498,272 | <p>I'm trying to construct an example where the <a href="http://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/" rel="nofollow">kmp algorithm</a> <code>computeLPSArray</code> phase will have to backtrack (see comment below) multiple times for a certain i (cell in the LPS array).</p>
<p>e.g. for <code... | 1 | 2016-05-28T11:12:42Z | 37,499,084 | <p>As you already mentioned: your example string <code>AAACAAA</code> already visited the backtrack section 2 times when <code>i = 3</code>.</p>
<p>If you want to increase the number of visits, increase the numbers of <code>A</code> in the prefix, e.g.</p>
<pre><code>AAAAC
</code></pre>
<p>will visit the backtrack s... | 1 | 2016-05-28T12:37:11Z | [
"python",
"string",
"algorithm"
] |
How do I create a list from a column of a file? | 37,498,317 | <p>I want to create a list from a specific column of a file, for example a csv file. How would I append each value in a column without knowing the index?</p>
<p>I created a for loop to find the index of the specific column I want to append to the list, but it does not seem to be correct. I need to somehow make use of ... | 1 | 2016-05-28T11:18:32Z | 37,498,364 | <p>Suppose you want to add first column value of the csv file only to the list, then you can do this:</p>
<pre><code>import csv
lst=[]
with open('fl.csv', 'rb') as csvfile:
... reader = csv.reader(csvfile)
... for row in reader:
... lst.add(row[1]);
</code></pre>
<p>Since you have to use split, do thi... | 2 | 2016-05-28T11:22:48Z | [
"python"
] |
Distributing Python script which depends on a package | 37,498,322 | <p>I wrote a script which makes use of Selenium, I installed Selenium through pip. Is there a way that I can distribute this script to others without having them to install Selenium through pip?</p>
<p>I was looking at:</p>
<p><a href="https://pypi.python.org/pypi/selenium#downloads" rel="nofollow">https://pypi.pytho... | 3 | 2016-05-28T11:18:53Z | 37,498,361 | <p>You can use <code>setuptools</code> and use the <code>install_requires</code> keyword.</p>
<p>Like this:</p>
<pre><code>from setuptools import setup
setup(
# options
install_requires = ['selenium'],
)
</code></pre>
<p>See the tutorial <a href="https://pythonhosted.org/an_example_pypi_project/setuptools.h... | 4 | 2016-05-28T11:22:20Z | [
"python",
"python-2.7",
"python-3.x",
"selenium",
"pip"
] |
Distributing Python script which depends on a package | 37,498,322 | <p>I wrote a script which makes use of Selenium, I installed Selenium through pip. Is there a way that I can distribute this script to others without having them to install Selenium through pip?</p>
<p>I was looking at:</p>
<p><a href="https://pypi.python.org/pypi/selenium#downloads" rel="nofollow">https://pypi.pytho... | 3 | 2016-05-28T11:18:53Z | 37,509,153 | <p>I wasn't able to find a real answer to this problem:</p>
<pre><code>import os
import sys
os.system("python get-pip.py")
try:
import pip
except ImportError:
input('Could not install pip, please enter any key to quit this window.')
sys.exit()
def install(package):
pip.main(['install', package])
i... | 0 | 2016-05-29T11:10:41Z | [
"python",
"python-2.7",
"python-3.x",
"selenium",
"pip"
] |
How can I write on new lines in a text file while preserving old ones | 37,498,374 | <p>When I open a text file and write in it and at the end of the program close it, the lines stay in the text file. When i reopen that program, rather than writing on a new set of lines, it overwrites what is already there. I want to keep both pieces of text, it is for data logging. Any ideas on how to fix this.</p>
| 0 | 2016-05-28T11:23:25Z | 37,498,389 | <p>You need append file:</p>
<pre><code>with open("test.txt", "a") as myfile:
myfile.write("appended text")
</code></pre>
| 0 | 2016-05-28T11:25:00Z | [
"python",
"text-files"
] |
How can I write on new lines in a text file while preserving old ones | 37,498,374 | <p>When I open a text file and write in it and at the end of the program close it, the lines stay in the text file. When i reopen that program, rather than writing on a new set of lines, it overwrites what is already there. I want to keep both pieces of text, it is for data logging. Any ideas on how to fix this.</p>
| 0 | 2016-05-28T11:23:25Z | 37,498,391 | <p>You should use the <code>a</code> mode, like this:</p>
<pre><code>with open("file","a") as f:
f.write("Something")
</code></pre>
<p>This will append to the file instead of overwriting it.</p>
| 0 | 2016-05-28T11:25:20Z | [
"python",
"text-files"
] |
Assign two variables with ternary operator | 37,498,392 | <p>Is there a way to do variable assignments(as shown below) using ternary operators in python:</p>
<pre><code>if(x>1):
y="yes"
else:
z="yes"
</code></pre>
<p>Something like <code>(x='yes') if(x>1) else (z='yes')</code>, but this gives an error. Is there any other way to do this?</p>
<p><em>I know sing... | 1 | 2016-05-28T11:25:24Z | 37,498,420 | <p>No, you can't do that. You can only have expressions, not statements, inside the ternary. <code>print</code> works because (in Python 3 at least) it is a function call, therefore an expression; but assignment is always a statement.</p>
| 2 | 2016-05-28T11:28:39Z | [
"python",
"variable-assignment",
"ternary-operator"
] |
Assign two variables with ternary operator | 37,498,392 | <p>Is there a way to do variable assignments(as shown below) using ternary operators in python:</p>
<pre><code>if(x>1):
y="yes"
else:
z="yes"
</code></pre>
<p>Something like <code>(x='yes') if(x>1) else (z='yes')</code>, but this gives an error. Is there any other way to do this?</p>
<p><em>I know sing... | 1 | 2016-05-28T11:25:24Z | 37,498,543 | <p>You can use the following hack, which employs tuple unpacking:</p>
<pre><code>y, z = ('yes', z) if x > 1 else (y, 'yes')
</code></pre>
<p>Don't miss those parentheses.</p>
<p>I wouldn't really recommend using this as it is harder to understand, has one redundant assignment statements, and uses unpacking unnece... | 4 | 2016-05-28T11:41:35Z | [
"python",
"variable-assignment",
"ternary-operator"
] |
Assign two variables with ternary operator | 37,498,392 | <p>Is there a way to do variable assignments(as shown below) using ternary operators in python:</p>
<pre><code>if(x>1):
y="yes"
else:
z="yes"
</code></pre>
<p>Something like <code>(x='yes') if(x>1) else (z='yes')</code>, but this gives an error. Is there any other way to do this?</p>
<p><em>I know sing... | 1 | 2016-05-28T11:25:24Z | 37,498,598 | <pre><code>varname = 'y' if x > 1 else 'z'
</code></pre>
<p>If you want to assign a global variable:</p>
<pre><code>globals()[varname] = 'yes'
</code></pre>
<p>If you want to set an attribute on an object:</p>
<pre><code>setattr(obj, varname, 'yes')
</code></pre>
<p>If it's a local variable inside a function, y... | 2 | 2016-05-28T11:47:50Z | [
"python",
"variable-assignment",
"ternary-operator"
] |
Assign two variables with ternary operator | 37,498,392 | <p>Is there a way to do variable assignments(as shown below) using ternary operators in python:</p>
<pre><code>if(x>1):
y="yes"
else:
z="yes"
</code></pre>
<p>Something like <code>(x='yes') if(x>1) else (z='yes')</code>, but this gives an error. Is there any other way to do this?</p>
<p><em>I know sing... | 1 | 2016-05-28T11:25:24Z | 37,498,621 | <p>You can use <code>exec</code> function like this:</p>
<pre><code>exec("y='yes'" if x > 1 else "z='yes'")
</code></pre>
| 2 | 2016-05-28T11:50:18Z | [
"python",
"variable-assignment",
"ternary-operator"
] |
How to remove everything after the last occurence of a character in a Dataframe? | 37,498,537 | <p>I have a dataframe <code>DF</code> that looks like this (This is a sample): </p>
<pre><code> EQ1 EQ2 EQ3
0 Apple.fruit Oranage.eatable.fruit NaN
1 Pear.eatable.fruit Banana.fruit NaN
2 Orange.fruit Tomato.eatable ... | 2 | 2016-05-28T11:40:51Z | 37,499,720 | <p>You could do:</p>
<pre><code>df_temp = df.apply(lambda x: x.str.split('.').str[:-1].str.join('.'))
</code></pre>
<p>output:</p>
<pre><code> EQ1 EQ2 EQ3
0 Apple Oranage.eatable NaN
1 Pear.eatable Banana NaN
2 Orange To... | 5 | 2016-05-28T13:39:44Z | [
"python",
"python-3.x",
"pandas"
] |
How to remove everything after the last occurence of a character in a Dataframe? | 37,498,537 | <p>I have a dataframe <code>DF</code> that looks like this (This is a sample): </p>
<pre><code> EQ1 EQ2 EQ3
0 Apple.fruit Oranage.eatable.fruit NaN
1 Pear.eatable.fruit Banana.fruit NaN
2 Orange.fruit Tomato.eatable ... | 2 | 2016-05-28T11:40:51Z | 37,499,745 | <p>You could use extract.</p>
<pre><code>df_temp = df.apply(lambda x: x.str.extract(r'.*\.([^\.]*)', expand=False))
df_new = df.apply(lambda x: x.str.extract(r'(.*)\.[^\.]*', expand=False))
</code></pre>
<p><code>df_temp</code> looks like:</p>
<pre><code> EQ1 EQ2 EQ3
0 fruit fruit NaN... | 1 | 2016-05-28T13:42:29Z | [
"python",
"python-3.x",
"pandas"
] |
Send data processed from one window to mainwindow in pyqt | 37,498,557 | <p>I am using pyqt to build a gui, using the .UI file from qt Designer, and then convert by pyuic4.</p>
<p>I have two windows,<br>
1st - mainwindow (which has some label and buttons)<br>
2nd - Window is a numeric keypad input window.</p>
<p>I have the .py of the UI file seperate and load it in main program by </p>
... | 0 | 2016-05-28T11:42:34Z | 37,822,019 | <p>What you want, is to define a new method to <em>handle</em> your return value.</p>
<p>In your <strong>mainwaindow</strong> you define the handler:</p>
<pre><code>class mainwindow(QtGui.QWidget):
def __init__(self, parent = None):
super(mainwindow, self).__init__(parent)
self.ui = Ui_main()
sel... | 1 | 2016-06-14T21:01:53Z | [
"python",
"class",
"pyqt"
] |
Should my unit tests also test third-party library/package features? | 37,498,562 | <p>I've just started using unit tests and I'm trying to figure out how comprehensive my tests should be. One particular thing that comes up is when I use packages/libraries whose components are already subject to tests of their own. Should I be carrying out similar tests on those components myself, or should I only b... | 1 | 2016-05-28T11:42:53Z | 37,498,675 | <p>I think you can trust your gut here. If you are confident in the tests that come with WTForms and don't need to change its behavior, you don't need to add more.</p>
<p>That being said, if you plan on updating a library your project is depending on, having tests against it <em>can</em> be beneficial. Testing the beh... | 0 | 2016-05-28T11:55:23Z | [
"python",
"unit-testing",
"wtforms"
] |
Should my unit tests also test third-party library/package features? | 37,498,562 | <p>I've just started using unit tests and I'm trying to figure out how comprehensive my tests should be. One particular thing that comes up is when I use packages/libraries whose components are already subject to tests of their own. Should I be carrying out similar tests on those components myself, or should I only b... | 1 | 2016-05-28T11:42:53Z | 37,498,815 | <p>By <em>definition</em> the unit's test responsability is to control the behaviour of one single piece of code. So your responsability as a developper is to consistenly write unit test for what <strong>you</strong> (or your team) develop.</p>
<p>When you speak of testing WTForms, you normally have no reason to write... | 1 | 2016-05-28T12:10:01Z | [
"python",
"unit-testing",
"wtforms"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.