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 match every word in the list having single sentence using python | 39,226,172 | <p>how to match the below case 1 in python.. i want each and every word in the sentence to be matched with the list. </p>
<pre><code>l1=['there is a list of contents available in the fields']
>>> 'there' in l1
False
>>> 'there is a list of contents available in the fields' in l1
True
</code></pre>
| -1 | 2016-08-30T11:23:21Z | 39,226,568 | <p>If you just want to know if any of the string in the list contains a word no matter which string it is you can do this:</p>
<pre><code>if any('there' in element for element in li):
pass
</code></pre>
<p>Now if you want to filter the ones which matches the string you can simply:</p>
<pre><code>li = filter(lamb... | 0 | 2016-08-30T11:41:51Z | [
"python"
] |
replace xml child element text with value from a list python | 39,226,215 | <p>I want to replace the text element of a child with a value held in a list. </p>
<pre><code><weighting name="weighting">
<aWeight>false</aWeight>
<cWeight>true</cWeight>
</weighting>
</code></pre>
<p>I am trying to change the text value for aWeight to true. I have... | 0 | 2016-08-30T11:24:52Z | 39,226,592 | <p>As your code stands it's not accessing the <code>elem</code> variable to change the node value, you need to tell the operation "where" it needs to operate.</p>
<pre><code>import xml.etree.ElementTree as ET
elems = ET.fromstring('<weighting><aWeight>false</aWeight><cWeight>true</cWeight>... | 0 | 2016-08-30T11:43:02Z | [
"python",
"xml",
"list"
] |
Python - kivy issues | 39,226,279 | <p>im new with kivy and Python.
I try fix this problem on my own, but i still end on same problem.
I try reinstall and update components, but no different result.</p>
<p>Im using Linux Mint, heres the problem what i get when i try run program under Python 2.x (using in terminal <em>python '/home/user/Desktop/first_kiv... | 0 | 2016-08-30T11:27:40Z | 39,230,072 | <p>First of all, I suggest working in a virtual environment, <a href="https://virtualenvwrapper.readthedocs.io/en/latest/" rel="nofollow">https://virtualenvwrapper.readthedocs.io/en/latest/</a>
and make sure you have all the requirements installed. try following this link
<a href="https://kivy.org/docs/installation/ins... | 0 | 2016-08-30T14:20:16Z | [
"python",
"linux",
"module",
"warnings",
"kivy"
] |
Python - kivy issues | 39,226,279 | <p>im new with kivy and Python.
I try fix this problem on my own, but i still end on same problem.
I try reinstall and update components, but no different result.</p>
<p>Im using Linux Mint, heres the problem what i get when i try run program under Python 2.x (using in terminal <em>python '/home/user/Desktop/first_kiv... | 0 | 2016-08-30T11:27:40Z | 39,242,925 | <p>Thank you for answer.
Yes, im using VMware Workstation.
I installed all requirements, but result is the same. :(
Also i try create new VM (Ubuntu 16.x) and run same program.
In this VM i dont have a problem, everything works fine.</p>
<p>Is it possible that Linux Mint Cinnam do not support python kivy?</p>
| 0 | 2016-08-31T07:08:28Z | [
"python",
"linux",
"module",
"warnings",
"kivy"
] |
python of xlwings, I don't understand one of rule | 39,226,421 | <p>I could understand clearly the <code>rng[0, 0]</code> and <code>rng[1]</code>, but why? Why <code>rng[:, 3:]</code> slicing to be <code>$D$1:$D$5</code>? And why <code>rng[1:3, 1:3]</code> to be <code>$B$2:$C$3</code>, I cannot understand the rule of slicing. </p>
<pre><code>Range indexing/slicing
Range objects sup... | 1 | 2016-08-30T11:33:55Z | 39,227,046 | <p>I'll give it a go. Because in square brackets, indexing starts at <code>0</code> *. So for a 1-based indexing system, consider [1:3, 1:3] as (2:4, 2:4). Also bear in mind that the value after <code>:</code> is not included, so inclusively (2:4, 2:4) is (2:3, 2:3). The second Excel Column is B, the third C, and the s... | 0 | 2016-08-30T12:05:57Z | [
"python",
"excel",
"xlwings"
] |
Python regex findall with all specific substrings | 39,226,455 | <p>I'm trying to get the output of the following matching regex as </p>
<p>all the Sectors for eg. ['Sector-34, Noida', 'Sec 434 Gurgaon', 'sec100']</p>
<p>P.S - sec47, \n gurgaon is the special case</p>
<p>But I suspect the output is quite weird as [('', 'tor')]</p>
<pre><code>import re
string = "Sector-34, Noida... | -2 | 2016-08-30T11:35:38Z | 39,226,722 | <p>Here is one way that will give the expected output, but is not a general way (because you didn't provide us with general conditions):</p>
<pre><code>>>> re.findall(r'(?:[sS]ec(?:tor)?(?:-|\s+)?\d+\W?\s+[A-Z][a-z]+)|[sS]ec(?:tor)?\d+', string)
['Sector-34, Noida', 'Sec 434 Gurgoan', 'sec100']
</code></pre>
... | 0 | 2016-08-30T11:49:33Z | [
"python",
"regex",
"python-2.7"
] |
Python regex findall with all specific substrings | 39,226,455 | <p>I'm trying to get the output of the following matching regex as </p>
<p>all the Sectors for eg. ['Sector-34, Noida', 'Sec 434 Gurgaon', 'sec100']</p>
<p>P.S - sec47, \n gurgaon is the special case</p>
<p>But I suspect the output is quite weird as [('', 'tor')]</p>
<pre><code>import re
string = "Sector-34, Noida... | -2 | 2016-08-30T11:35:38Z | 39,227,862 | <p>You could go for:</p>
<pre><code>import re
rx = re.compile(r'(\b[Ss]ec(?:tor)?[- ]?\d+\b[,\s]*\b\w+\b)')
string = """
Sector-34, Noida is found to be awesome place I went to eat burgers there and Sec 434 Gurgoan is also good sec47,
gurgaon is one the finest places for outing.
"""
sectors = [match.group(1).repla... | 0 | 2016-08-30T12:42:55Z | [
"python",
"regex",
"python-2.7"
] |
Authentication while scraping via BeautifulSoup in python | 39,226,585 | <p>I have created a piece of code to scrape an article off the ft.com website. </p>
<pre><code>url = ""
r = requests.get(url)
soup = bs4.BeautifulSoup(r.content, "html.parser")
for a in soup.find_all('div', {"id":"storyContent"}):
print a
</code></pre>
<p><strong>1) On the website, there is a div tag with id:sto... | 0 | 2016-08-30T11:42:38Z | 39,226,905 | <p>Rather start with this.</p>
<pre><code>url = "http://www.ft.com"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
for a in soup:
print a
</code></pre>
<p>Then add a requests when you find the key:value pair required</p>
<pre><code>r = requests.post('http://www.ft.com/xxx', data = {'key':'v... | 1 | 2016-08-30T11:59:04Z | [
"python",
"python-2.7"
] |
String Index Out Of Range When Reading Text File | 39,226,586 | <p>I keep on getting this error on the second last line of my program , and I am not sure why , all I am doing is reading a line from a text file.</p>
<pre><code>if (items[0]) == 86947367 :
with open("read_it.txt") as text_file:
try:
price = int(text_file.readlines()[2])
... | 2 | 2016-08-30T11:42:39Z | 39,226,683 | <p><strong>problem:</strong></p>
<pre><code>price = int(text_file.readlines()[2])
</code></pre>
<p>the readlines() cause the readline() to return none or something like that.
try to store readlines() in a
<strong>tmp var and then</strong> </p>
<pre><code>price = tmp[2]
product =tmp[1]
</code></pre>
| 0 | 2016-08-30T11:47:39Z | [
"python",
"python-3.x"
] |
String Index Out Of Range When Reading Text File | 39,226,586 | <p>I keep on getting this error on the second last line of my program , and I am not sure why , all I am doing is reading a line from a text file.</p>
<pre><code>if (items[0]) == 86947367 :
with open("read_it.txt") as text_file:
try:
price = int(text_file.readlines()[2])
... | 2 | 2016-08-30T11:42:39Z | 39,227,745 | <p>When you use <code>readlines()</code>, your "cursor" in the file reaches the end. If you call it a second time, it'll have nothing left to read. </p>
<p>To avoid this behavior, you can store <code>readlines()</code> in a variable for multiple uses, or use <code>text_file.seek(0)</code> to put your cursor back at th... | 1 | 2016-08-30T12:38:07Z | [
"python",
"python-3.x"
] |
Sorting the keys of a dictionary based on different values | 39,226,604 | <p>I have a dictionary:</p>
<pre><code>d = {"A":{"a":1, "b":2, "c":3}, "B":{"a":5, "b":6, "c":7}, "C":{"a":4, "b":6, "c":7}}
</code></pre>
<p>I want to sort the keys "A", "B" and "C" in a list, first on the basis of numerical values of "a", then if some tie occurs on the basis of numerical values of "b" and so on. </... | 0 | 2016-08-30T11:43:23Z | 39,226,705 | <pre><code>>>> d = {"A":{"a":1, "b":2, "c":3}, "B":{"a":5, "b":6, "c":7}, "C":{"a":4, "b":6, "c":7}}
>>>
>>> d.items()
[('A', {'a': 1, 'c': 3, 'b': 2}), ('C', {'a': 4, 'c': 7, 'b': 6}), ('B', {'a': 5, 'c': 7, 'b': 6})]
>>> sorted(d.items(), key=lambda x: [y[1] for y in sorted(x[1].i... | 2 | 2016-08-30T11:48:42Z | [
"python",
"sorting",
"dictionary",
"ranking"
] |
Sorting the keys of a dictionary based on different values | 39,226,604 | <p>I have a dictionary:</p>
<pre><code>d = {"A":{"a":1, "b":2, "c":3}, "B":{"a":5, "b":6, "c":7}, "C":{"a":4, "b":6, "c":7}}
</code></pre>
<p>I want to sort the keys "A", "B" and "C" in a list, first on the basis of numerical values of "a", then if some tie occurs on the basis of numerical values of "b" and so on. </... | 0 | 2016-08-30T11:43:23Z | 39,226,804 | <p>Make a list of your dictionary like so:</p>
<pre><code>my_list = [(key, value) for item in d.items()]
</code></pre>
<p>Then sort the list using whatever criteria you have in mind:</p>
<pre><code>def sort_function(a, b):
# whatever complicated sort function you like
return True if a > b else False
my_lis... | 0 | 2016-08-30T11:53:47Z | [
"python",
"sorting",
"dictionary",
"ranking"
] |
Sorting the keys of a dictionary based on different values | 39,226,604 | <p>I have a dictionary:</p>
<pre><code>d = {"A":{"a":1, "b":2, "c":3}, "B":{"a":5, "b":6, "c":7}, "C":{"a":4, "b":6, "c":7}}
</code></pre>
<p>I want to sort the keys "A", "B" and "C" in a list, first on the basis of numerical values of "a", then if some tie occurs on the basis of numerical values of "b" and so on. </... | 0 | 2016-08-30T11:43:23Z | 39,226,867 | <p>You can use:</p>
<pre><code>sorted(d, key=lambda key:(d[key]['a'], d[key]['b'], d[key]['c']))
</code></pre>
<p>And here is a general solution in case you have an arbitrary number of elements in the inner dictionaries:</p>
<pre><code>sorted(d, key=lambda key:[value for value in sorted(d[key].items())])
</code></pr... | 2 | 2016-08-30T11:57:08Z | [
"python",
"sorting",
"dictionary",
"ranking"
] |
Pandas conditional creation of a new dataframe column | 39,226,656 | <p>This question is an extension of <a href="http://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column/39224761#39224761">Pandas conditional creation of a series/dataframe column</a>.
If we had this dataframe:</p>
<pre><code> Col1 Col2
1 A Z
2 B ... | 2 | 2016-08-30T11:46:17Z | 39,226,738 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> and last <a href="http://pandas.pydata.org/pandas... | 3 | 2016-08-30T11:50:30Z | [
"python",
"pandas",
"if-statement",
"dataframe",
"multiple-columns"
] |
Pandas conditional creation of a new dataframe column | 39,226,656 | <p>This question is an extension of <a href="http://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column/39224761#39224761">Pandas conditional creation of a series/dataframe column</a>.
If we had this dataframe:</p>
<pre><code> Col1 Col2
1 A Z
2 B ... | 2 | 2016-08-30T11:46:17Z | 39,228,211 | <p>Try this use np.where : <code>outcome = np.where(condition, true, false)</code></p>
<pre><code> df["Col3"] = np.where(df['Col2'].isin(['Z','X']), "J", np.where(df['Col2'].isin(['Y']), 'K', df['Col1']))
Col1 Col2 Col3
1 A Z J
2 B Z J
3 B X J
4 C Y K
5 C W C
</code></... | 0 | 2016-08-30T12:59:47Z | [
"python",
"pandas",
"if-statement",
"dataframe",
"multiple-columns"
] |
Python logging class in Docker: logs gone | 39,226,846 | <p>For several years now I've used Python's logging class in the same way:</p>
<pre><code>def get_module_logger(mod_name):
"""
To use this, do logger = get_module_logger(__name__)
"""
logger = logging.getLogger(mod_name)
handler = logging.StreamHandler()
formatter = logging.Formatter(
'... | 0 | 2016-08-30T11:56:21Z | 39,227,617 | <p>This is an issue with docker, not python. With docker, the file system seen inside an instance is unique to that instance. Any changes made are not reflected on the host machine. This is a feature of the union file system that docker uses.</p>
<p>You can use "<a href="https://docs.docker.com/engine/tutorials/docker... | -1 | 2016-08-30T12:32:22Z | [
"python",
"docker"
] |
Python logging class in Docker: logs gone | 39,226,846 | <p>For several years now I've used Python's logging class in the same way:</p>
<pre><code>def get_module_logger(mod_name):
"""
To use this, do logger = get_module_logger(__name__)
"""
logger = logging.getLogger(mod_name)
handler = logging.StreamHandler()
formatter = logging.Formatter(
'... | 0 | 2016-08-30T11:56:21Z | 39,233,389 | <p>I was able to see the log outputs and was not able to reproduce your issue with your code.</p>
<p>I created a file called <code>tommy.py</code>:</p>
<pre><code>import logging
def get_module_logger(mod_name):
"""
To use this, do logger = get_module_logger(__name__)
"""
logger = logging.getLogger(mo... | 0 | 2016-08-30T17:12:03Z | [
"python",
"docker"
] |
How can I find the function of a python module? | 39,226,927 | <p>I am using OpenCV, and I want to see what the "rectangle" function is.
I can use the dir(module) function, to get at the function definition, and name, but I don't know how to view the actual function. I am Using Linux (Ubuntu 16.04), and I'm wondering if the libraries are in "/usr/local/" or some other place. The ... | 0 | 2016-08-30T11:59:57Z | 39,227,107 | <p>There are multiple ways :</p>
<ul>
<li><p>If you want to get the source code on runtime you can use <code>inspect.getsourcelines(object)</code> (see <a href="https://docs.python.org/3/library/inspect.html#inspect.getsourcelines" rel="nofollow">https://docs.python.org/3/library/inspect.html#inspect.getsourcelines</a... | 3 | 2016-08-30T12:08:41Z | [
"python",
"function",
"opencv",
"module"
] |
How can I find the function of a python module? | 39,226,927 | <p>I am using OpenCV, and I want to see what the "rectangle" function is.
I can use the dir(module) function, to get at the function definition, and name, but I don't know how to view the actual function. I am Using Linux (Ubuntu 16.04), and I'm wondering if the libraries are in "/usr/local/" or some other place. The ... | 0 | 2016-08-30T11:59:57Z | 39,526,919 | <p>I suggest you to use the wonderful <a href="https://ipython.org/" rel="nofollow">IPython</a> interactive shell.</p>
<p>You can see the definition of any function (or in general of any object whose source code is available) by appending two question marks <code>??</code> to its name. Below is a short example run on ... | 0 | 2016-09-16T08:28:29Z | [
"python",
"function",
"opencv",
"module"
] |
Get coordinates of image after warpPerspective | 39,226,955 | <p>I apply cv2.warpPerspective to imageA</p>
<pre><code>result = cv2.warpPerspective(imageA, Ht.dot(H), (xmax-xmin, ymax-ymin))
</code></pre>
<p>and that work works correctly, but i need coordinates of new image like this
<a href="http://i.stack.imgur.com/z5sUl.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/z... | 0 | 2016-08-30T12:01:11Z | 39,230,666 | <p>old_points=[[[ 3.27589822, -24.28251266]],[[ 8.85595226, 270.21176147]], [[ 408.69842529, 258.427948 ]],[[ 398.14550781, -36.64953613]]]</p>
<p>new_points = cv2.perspectiveTransform(old_points, H)</p>
| 0 | 2016-08-30T14:46:07Z | [
"python",
"opencv"
] |
How to get the second largest number by not usings list and max()min() | 39,226,965 | <p>I want to find the second largest number such as this topic. <a href="http://stackoverflow.com/questions/16225677/get-the-second-largest-number-in-a-list-in-linear-time">Get the second largest number in a list in linear time</a></p>
<p>My problem is this restricting words <code>list</code>, <code>[]</code>, <code>r... | -7 | 2016-08-30T12:01:34Z | 39,227,069 | <pre><code>first_max=arr[0]
second_max=first_max
if(arr[0]>arr[1]):
first_max=arr[0]
second_max=arr[1]
for i in range(1,len(arr)):
if(arr[i]>first_max):
second_max=first_max
first_max=arr[i]
elif(arr[i]>second_max):
second_max=arr[i]
print(second_max)
</code></pre>
<p>I t... | 0 | 2016-08-30T12:07:03Z | [
"python"
] |
How to get the second largest number by not usings list and max()min() | 39,226,965 | <p>I want to find the second largest number such as this topic. <a href="http://stackoverflow.com/questions/16225677/get-the-second-largest-number-in-a-list-in-linear-time">Get the second largest number in a list in linear time</a></p>
<p>My problem is this restricting words <code>list</code>, <code>[]</code>, <code>r... | -7 | 2016-08-30T12:01:34Z | 39,227,083 | <p>Try this -></p>
<pre><code>a = [1,5,7,8,3,4,6,8,2,9]
x=-999999999999
n=999999999999
for i in a:
if i>x:
x=i
for i in a:
if x-i!=0 and x-i<n:
n=x-i
ans=i
print ans
</code></pre>
| 0 | 2016-08-30T12:07:35Z | [
"python"
] |
How to get the second largest number by not usings list and max()min() | 39,226,965 | <p>I want to find the second largest number such as this topic. <a href="http://stackoverflow.com/questions/16225677/get-the-second-largest-number-in-a-list-in-linear-time">Get the second largest number in a list in linear time</a></p>
<p>My problem is this restricting words <code>list</code>, <code>[]</code>, <code>r... | -7 | 2016-08-30T12:01:34Z | 39,227,180 | <p>Not sure I've understood correctly your question but the <a href="http://stackoverflow.com/questions/16225677/get-the-second-largest-number-in-a-list-in-linear-time">post</a> you've mentioned is giving you already few good solutions. For instance, if you don't want to code the algorithm by yourself, use the standard... | 2 | 2016-08-30T12:12:01Z | [
"python"
] |
Updating Python using 'PIP' | 39,227,100 | <p>just like we install packages like Matplotlib, using pip command in the cmd (pip install matplotlib) can we also update to newer version of python by some pip command?
<a href="http://i.stack.imgur.com/r108C.png" rel="nofollow">enter image description here</a></p>
| 1 | 2016-08-30T12:08:14Z | 39,227,632 | <p>Pip is designed for managing python packages and <strong>not python versions</strong> to update Python you must download the version you wish from their <a href="https://www.python.org/downloads/" rel="nofollow">site in the download selection.</a></p>
<h1>Simple Answer</h1>
<p>No you cannot</p>
| 3 | 2016-08-30T12:32:52Z | [
"python",
"pip"
] |
How to zip only the files inside the folder and not the sub folders? | 39,227,114 | <p>I have a folder structure as:</p>
<pre><code>/sample/debug/
--debug.exe
--sample.exe
--sample.pdb
--debug.pdb
--sample.dll
--debug.dll
/config
--sample.txt
--new.txt
/general
--general.txt
--code.txt
</code></pre>
<p>So, what I want is only to zip the... | 1 | 2016-08-30T12:08:55Z | 39,229,094 | <p>You can grab all files from a folder without going into the subfolders using:</p>
<pre><code>import os
def getfilesfrom(directory):
return filter(lambda x:
not os.path.isdir(os.path.join(directory, x)),
os.listdir(directory))
# or alternatively, using generators (as suggeste... | 2 | 2016-08-30T13:38:05Z | [
"python",
"windows",
"zipfile"
] |
How to zip only the files inside the folder and not the sub folders? | 39,227,114 | <p>I have a folder structure as:</p>
<pre><code>/sample/debug/
--debug.exe
--sample.exe
--sample.pdb
--debug.pdb
--sample.dll
--debug.dll
/config
--sample.txt
--new.txt
/general
--general.txt
--code.txt
</code></pre>
<p>So, what I want is only to zip the... | 1 | 2016-08-30T12:08:55Z | 39,243,226 | <p>The following makes use of the new ZipFile context manager available:</p>
<pre><code>from zipfile import ZipFile
def zip_folder(zip_name, folder):
with ZipFile(zip_name, 'w') as myzip:
for entry in os.listdir(folder):
if os.path.isfile(entry):
myzip.write(os.path.join(folder... | 0 | 2016-08-31T07:23:28Z | [
"python",
"windows",
"zipfile"
] |
Can scrapy yield different kinds of items? | 39,227,277 | <p>I have two kinds of Item:</p>
<pre><code>class MovieItem(scrapy.Item):
id = scrapy.Field()
image_urls=scrapy.Field()
image_paths =scrapy.Field()
torrents = scrapy.Field()
#...other fields
class TorrentItem(scrapy.Item):
id = scrapy.Field()
movie_id = scrapy.Field()
image_urls=scrap... | -1 | 2016-08-30T12:17:21Z | 39,239,137 | <p>The answer is yes, you can. Here's an example on how to do it. Here's an <code>example.py</code> spider:</p>
<pre><code># -*- coding: utf-8 -*-
import scrapy
class MovieItem(scrapy.Item):
id = scrapy.Field()
image_urls=scrapy.Field()
images =scrapy.Field()
torrents = scrapy.Field()
itemtype = ... | 0 | 2016-08-31T00:49:23Z | [
"python",
"scrapy"
] |
Sort list with according to uneven value | 39,227,312 | <p>I am creating a script for a library, that sorts authors in decending order of their Avg rating.</p>
<p>Below is my list: ( It have author name + < space > + Avg Rating )</p>
<pre><code>['Michael Crichton 4.71', 'J.K. Rowling 4.36', 'Sidney Sheldon 4.63', 'Narendra Kohli 4.9', 'Jeffrey Archer 4.62', 'Devdutt P... | 0 | 2016-08-30T12:18:46Z | 39,227,384 | <p>Use <code>rsplit</code></p>
<pre><code>>>> help(''.rsplit)
Help on built-in function rsplit:
rsplit(...)
S.rsplit([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string, starting at the end of the string and working
to the fr... | 2 | 2016-08-30T12:22:55Z | [
"python",
"python-2.7"
] |
Sort list with according to uneven value | 39,227,312 | <p>I am creating a script for a library, that sorts authors in decending order of their Avg rating.</p>
<p>Below is my list: ( It have author name + < space > + Avg Rating )</p>
<pre><code>['Michael Crichton 4.71', 'J.K. Rowling 4.36', 'Sidney Sheldon 4.63', 'Narendra Kohli 4.9', 'Jeffrey Archer 4.62', 'Devdutt P... | 0 | 2016-08-30T12:18:46Z | 39,227,405 | <p>You could split at spaces, and then take the floating-point value of the last component. Here is the whole thing as a one-liner:</p>
<pre><code>>>> print sorted(rate_order, key=lambda r:float(r.split(' ')[-1]))
['Katherine Applegate 3.0', 'Stephen King 3.66', 'Eoin Colfer 4.25', 'J.K. Rowling 4.36', 'Devdu... | 3 | 2016-08-30T12:23:54Z | [
"python",
"python-2.7"
] |
Sort list with according to uneven value | 39,227,312 | <p>I am creating a script for a library, that sorts authors in decending order of their Avg rating.</p>
<p>Below is my list: ( It have author name + < space > + Avg Rating )</p>
<pre><code>['Michael Crichton 4.71', 'J.K. Rowling 4.36', 'Sidney Sheldon 4.63', 'Narendra Kohli 4.9', 'Jeffrey Archer 4.62', 'Devdutt P... | 0 | 2016-08-30T12:18:46Z | 39,227,462 | <pre><code>rate_order=['Michael Crichton 4.71', 'J.K. Rowling 4.36', 'Sidney Sheldon 4.63', 'Narendra Kohli 4.9', 'Jeffrey Archer 4.62', 'Devdutt Pattanaik 4.42', 'George R.R. Martin 5.0', 'Dan Brown 5.0', 'Katherine Applegate 3.0', 'Eoin Colfer 4.25', 'Arthur Conan Doyle 5.0', 'Clive Cussler 4.66', 'Stephen King 3.66'... | 1 | 2016-08-30T12:25:59Z | [
"python",
"python-2.7"
] |
Sort list with according to uneven value | 39,227,312 | <p>I am creating a script for a library, that sorts authors in decending order of their Avg rating.</p>
<p>Below is my list: ( It have author name + < space > + Avg Rating )</p>
<pre><code>['Michael Crichton 4.71', 'J.K. Rowling 4.36', 'Sidney Sheldon 4.63', 'Narendra Kohli 4.9', 'Jeffrey Archer 4.62', 'Devdutt P... | 0 | 2016-08-30T12:18:46Z | 39,228,231 | <p>You can use regex (<a href="https://en.wikipedia.org/wiki/Regular_expression" rel="nofollow">regular expressions</a>) matching in <code>sorted</code> function. Using this method of searching you can find rating independent from it's position in the string.
</p>
<pre><code>import re
print sorted(sort_list, key=lamb... | 0 | 2016-08-30T13:00:55Z | [
"python",
"python-2.7"
] |
pandas dataframe, add one column as moving average of another column for each group | 39,227,519 | <p>I have a dataframe <code>df</code> like below. </p>
<pre><code>dates = pd.date_range('2000-01-01', '2001-01-01')
df1 = pd.DataFrame({'date':dates, 'value':np.random.normal(size = len(dates)), 'market':'GOLD'})
df2 = pd.DataFrame({'date':dates, 'value':np.random.normal(size = len(dates)), 'market':'SILVER'})
df = pd... | 1 | 2016-08-30T12:28:06Z | 39,227,650 | <p>You could use <code>groupby/rolling/mean</code>:</p>
<pre><code>result = (df.set_index('date')
.groupby('market')['value']
.rolling(10).mean()
.unstack('market'))
</code></pre>
<p>yields</p>
<pre><code>market GOLD SILVER
date
2000-01-01 ... | 3 | 2016-08-30T12:33:48Z | [
"python",
"pandas"
] |
pandas dataframe, add one column as moving average of another column for each group | 39,227,519 | <p>I have a dataframe <code>df</code> like below. </p>
<pre><code>dates = pd.date_range('2000-01-01', '2001-01-01')
df1 = pd.DataFrame({'date':dates, 'value':np.random.normal(size = len(dates)), 'market':'GOLD'})
df2 = pd.DataFrame({'date':dates, 'value':np.random.normal(size = len(dates)), 'market':'SILVER'})
df = pd... | 1 | 2016-08-30T12:28:06Z | 39,319,486 | <p>This builds on @unutbu's answer, and adds the results back to the original dataframe as a new column.</p>
<pre><code>result = df.set_index('date').groupby('market')['value'].rolling(10).mean()
</code></pre>
<p>Now if <code>df</code> is sorted by <code>market</code> <strong>first</strong> and then <code>date</code>... | 1 | 2016-09-04T17:11:57Z | [
"python",
"pandas"
] |
Django Restful Framework Authentication HTTP Post Error | 39,227,593 | <p>I was following the Django restful framework tutorial and I came across a error at the "Authenticating with the API" step. I've retraced myself however can't seem to see where I went wrong. Basically when I go to post to my API i get an error see below. Ideally I would also like to setup permissions which state "acc... | 0 | 2016-08-30T12:31:40Z | 39,647,010 | <p>The error should be <code>owner = serializers.ReadOnlyField(source='owner.username')</code></p>
<p>Your serializer need <strong>owner</strong> to create Snippet instance.</p>
<p>If you let owner to be <strong>readonly</strong>, then you will lack the owner field, therefore it failed to create snippet instance. </p... | 1 | 2016-09-22T19:03:58Z | [
"python",
"django",
"django-rest-framework"
] |
How do you mock a return value from PyMySQL for testing in Python? | 39,227,681 | <p>I'm trying to set up some tests for a script that will pull data from a MySQL database. I found an example <a href="https://github.com/chimpler/catdb/blob/master/tests/test_mysql.py" rel="nofollow">here</a> that looks like what I want to do, but it just gives me an object instead of results:</p>
<p><code><MagicM... | 1 | 2016-08-30T12:35:16Z | 39,229,832 | <p>It looks like your mock is missing a reference to cursor</p>
<p><code>mock_pymysql.connect.return_value.cursor.return_value.__enter__.return_value = mock_cursor</code></p>
<p>I've always found mocking call syntax to be awkward but the MagicMock displays what's wrong in a roundabout way. It's saying it has no retur... | 1 | 2016-08-30T14:10:24Z | [
"python",
"unit-testing"
] |
Merge two lists and create a new dictionary | 39,227,706 | <p>I could not find a good way to do this. Suppose I have two lists (the lists have objects with given attributes). I need to create a new dictionary/list with merged atttributes.</p>
<pre><code>listA = [
{
"alpha": "some value",
"time": "datetime",
},
...
]
listB = [
{
"beta": "some val",
"ga... | -4 | 2016-08-30T12:36:06Z | 39,228,238 | <p>This code might be a good start:</p>
<pre><code>listA = [
{
"time": "Jan 1",
"alpha": "one"
},
{
"time": "Jan 3",
"alpha": "three"
}
]
listB = [
{
"beta": "one-one",
"gamma": "one-two",
"time": "Jan 1"
},
{
"beta": "two-one",
"gamma": "two-two",
"time": "Jan 2"... | 0 | 2016-08-30T13:01:12Z | [
"python",
"list",
"dictionary"
] |
Merge two lists and create a new dictionary | 39,227,706 | <p>I could not find a good way to do this. Suppose I have two lists (the lists have objects with given attributes). I need to create a new dictionary/list with merged atttributes.</p>
<pre><code>listA = [
{
"alpha": "some value",
"time": "datetime",
},
...
]
listB = [
{
"beta": "some val",
"ga... | -4 | 2016-08-30T12:36:06Z | 39,228,280 | <h1>Using a list comprehension</h1>
<p>Since you are searching for an alternative not using a for loop here is an implementation using <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehensions</a>, which results in a two liner. I am not sure though that thi... | 2 | 2016-08-30T13:03:43Z | [
"python",
"list",
"dictionary"
] |
Merge two lists and create a new dictionary | 39,227,706 | <p>I could not find a good way to do this. Suppose I have two lists (the lists have objects with given attributes). I need to create a new dictionary/list with merged atttributes.</p>
<pre><code>listA = [
{
"alpha": "some value",
"time": "datetime",
},
...
]
listB = [
{
"beta": "some val",
"ga... | -4 | 2016-08-30T12:36:06Z | 39,229,105 | <p>Another answer, that's perhaps cleaner in that it avoids conditional tests in favour of dict methods and uses only one level of indentation:</p>
<pre><code>d={}
for e in listA:
t = e["time"]
d.setdefault(t, {}).update(**e)
for e in listB:
t = e["time"]
d.setdefault(t, {}).update(**e)
# get rid of... | 1 | 2016-08-30T13:38:32Z | [
"python",
"list",
"dictionary"
] |
Navigating table by using th text | 39,227,725 | <p>I have the following table:</p>
<pre><code><table class="information">
<tr> .... lots of rows with <th> and <td></tr>
<tr>
<th>Nationality</th>
<td><a href="..">Stackoverflowian</a></td>
</tr>
</table>
</code></pre>
<p>... | 0 | 2016-08-30T12:37:21Z | 39,227,978 | <p>Find the <code>th</code> tag, then get its <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling" rel="nofollow">next sibling</a>:</p>
<pre><code>soup = BeautifulSoup(html)
ths = soup.find_all('th')
for th in ths:
if th.text == "Nationality":
print th.next_sib... | 2 | 2016-08-30T12:48:43Z | [
"python",
"beautifulsoup"
] |
Navigating table by using th text | 39,227,725 | <p>I have the following table:</p>
<pre><code><table class="information">
<tr> .... lots of rows with <th> and <td></tr>
<tr>
<th>Nationality</th>
<td><a href="..">Stackoverflowian</a></td>
</tr>
</table>
</code></pre>
<p>... | 0 | 2016-08-30T12:37:21Z | 39,227,991 | <p>I've modified this answer as you gave a specific HTML page you're trying to parse.</p>
<pre><code>r = requests.get("http://https://en.wikipedia.org/wiki/Usain_Bolt")
# test that we loaded the page successfully!
soup = BeautifulSoup(r.text, "html.parser")
thTag = soup.find('th', text='Nationality'):
tdTag = thTag.n... | 1 | 2016-08-30T12:49:10Z | [
"python",
"beautifulsoup"
] |
ApiError: Incorrect username or password YouTube Account Authentication error | 39,227,756 | <p>I am new for stack overflow and also Python Django with YouTube API, I am trying to upload video from my own website using django-youtube 0.2 python-package. I am using django 7.11,
My project is configured as <a href="https://github.com/laplacesdemon/django-youtube" rel="nofollow">https://github.com/laplacesdemon/d... | 0 | 2016-08-30T12:38:33Z | 39,306,677 | <pre><code>Issue Resolved Needs- Google Account 2 Step Verification For YouTube API Access for Upload Videos ...
</code></pre>
| 0 | 2016-09-03T12:03:31Z | [
"python",
"django",
"youtube"
] |
requests process hangs | 39,227,820 | <p>I'm using <code>requests</code> to get a URL, such as:</p>
<pre><code>while True:
try:
rv = requests.get(url, timeout=1)
doSth(rv)
except socket.timeout as e:
print e
except Exception as e:
print e
</code></pre>
<p>After it runs for a while, it quits working. No exceptio... | 0 | 2016-08-30T12:41:08Z | 39,229,526 | <p>It appears that the server you're sending your <code>request</code> to is throttling you - that is, it's sending <code>bytes</code> with less than 1 second between each package (thus not triggering your <code>timeout</code> parameter), but slow enough for it to appear to be stuck. </p>
<p>The only fix for this I ca... | 0 | 2016-08-30T13:57:16Z | [
"python",
"python-requests"
] |
Train Inception from Scratch in TensorFlow | 39,227,825 | <p>I wanted to train the inception model like shown in the tensorflow github-tutorial.
Except i wanted to use a selfmade Dataset of TFRecord files.</p>
<pre><code>bazel build inception/imagenet_train
bazel-bin/inception/imagenet_train --num_gpus=1 --batch_size=32 --train_dir=/tmp/imagenet_train --data_dir=/tmp/imagene... | 1 | 2016-08-30T12:41:17Z | 39,234,383 | <p>Yes you are training from scratch: see the <a href="https://github.com/tensorflow/models/blob/master/inception/inception/inception_train.py#L180" rel="nofollow">code</a></p>
| -1 | 2016-08-30T18:12:03Z | [
"python",
"machine-learning",
"tensorflow"
] |
Class for making asynchronous API requests with Twisted | 39,227,842 | <p>I am working on development of a system that collect data from rest servers and manipulates it.</p>
<p>One of the requirements is multiple and frequent API requests. We currently implement this in a somewhat synchronous way. I can easily implement this using threads but considering the system might need to support ... | -1 | 2016-08-30T12:42:03Z | 39,234,929 | <p>Sounds like you want to use a Twisted project called <a href="http://treq.readthedocs.io/en/latest/index.html" rel="nofollow"><code>treq</code></a> which allows you to send requests to HTTP endpoints. It works alot like <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>. I... | 0 | 2016-08-30T18:45:01Z | [
"python",
"asynchronous",
"twisted"
] |
Pyqt5 acces GUI elements from subclass | 39,228,057 | <p>Need a help to read and write to GUI elements from subclass.
The code:</p>
<pre><code>UI element:
[] doABC
# main.py
import mySubclass
class myAppController(QtWidgets.QMainWindow):
def __init__(self):
super(myAppController, self).__init__()
# load view
uifile = 'myApp.ui'
ui... | 0 | 2016-08-30T12:52:56Z | 39,261,463 | <p>Your problem is that mysubclass needs a reference to doABC to check it.</p>
<p>Here is a working example:</p>
<p>main.py file</p>
<pre><code>#!python3
# main.py
import mySubclass
import sys
from PyQt5 import QtWidgets, uic
class myAppController(QtWidgets.QMainWindow):
def __init__(self):
super(myAp... | 0 | 2016-09-01T01:37:29Z | [
"python",
"subclass",
"pyqt5"
] |
Is there a neat way to integrate lithoxyl into flask.logger? | 39,228,114 | <p>I like the look of <a href="http://lithoxyl.readthedocs.io/en/latest/index.html" rel="nofollow">lithoxyl</a> and would like to progressively replace my current usage of <a href="http://flask.pocoo.org/docs/0.11/api/#flask.Flask.logger" rel="nofollow">flask.logger</a> with it.</p>
<p>Is there a good way to get the t... | 1 | 2016-08-30T12:55:30Z | 39,249,247 | <p>I've managed to make some improvements as I found <a href="https://github.com/mahmoud/lithoxyl/blob/master/lithoxyl/_syslog_emitter.py" rel="nofollow">https://github.com/mahmoud/lithoxyl/blob/master/lithoxyl/_syslog_emitter.py</a> and created a similar class:</p>
<pre><code>import logging
from lithoxyl.common impor... | 1 | 2016-08-31T12:08:18Z | [
"python",
"logging",
"flask",
"lithoxyl"
] |
How to plot dates on the x-axis using Seaborn (or matplotlib) | 39,228,121 | <p>I have a csv file with some time series data. I create a Data Frame as such:</p>
<pre><code>df = pd.read_csv('C:\\Desktop\\Scripts\\TimeSeries.log')
</code></pre>
<p>When I call <code>df.head(6)</code>, the data appears as follows:</p>
<pre><code>Company Date Value
ABC 08/21/16 00:00:... | 0 | 2016-08-30T12:55:45Z | 39,230,682 | <p>Not sure that tsplot is the best tool for that. You can just use:</p>
<pre><code>df[['Date','Value']].set_index('Date').plot()
</code></pre>
| 1 | 2016-08-30T14:47:00Z | [
"python",
"matplotlib",
"seaborn",
"timeserieschart"
] |
How to plot dates on the x-axis using Seaborn (or matplotlib) | 39,228,121 | <p>I have a csv file with some time series data. I create a Data Frame as such:</p>
<pre><code>df = pd.read_csv('C:\\Desktop\\Scripts\\TimeSeries.log')
</code></pre>
<p>When I call <code>df.head(6)</code>, the data appears as follows:</p>
<pre><code>Company Date Value
ABC 08/21/16 00:00:... | 0 | 2016-08-30T12:55:45Z | 39,534,449 | <p>use the <code>time</code> parameter for <code>tsplot</code></p>
<p>from docs:</p>
<pre><code>time : string or series-like
Either the name of the field corresponding to time in the data DataFrame or x values for a plot when data is an array. If a Series, the name will be used to label the x axis.
#Plot the Valu... | 0 | 2016-09-16T14:53:04Z | [
"python",
"matplotlib",
"seaborn",
"timeserieschart"
] |
Simpy how to access objects in a resource queue | 39,228,126 | <p>I am moving code written in Simpy 2 to version 3 and could not find an equivalent to the following operation.</p>
<p>In the code below I access job objects (derived from class job_(Process)) in a Simpy resource's activeQ.</p>
<pre><code>def select_LPT(self, mc_no):
job = 0
ptime = 0
for j in buffer[mc_... | 0 | 2016-08-30T12:55:52Z | 39,241,488 | <p>In SimPy, request objects do not know which process created them. However, since we are in Python land you can easily add this information:</p>
<pre><code>with resource.request() as req:
req.obj = self
yield req
...
# In another process/function
for user_req in resource.users:
print(user_req.ob... | 0 | 2016-08-31T05:35:30Z | [
"python",
"simulation",
"simpy"
] |
OpenERP/Odoo: fields.datetime.now() show the date of the latest restart | 39,228,319 | <p>I have a field datetime. This field should have by default the datetime of "now", the current time.</p>
<p>However, the default date is the time of <strong>the lastest restart</strong>. </p>
<p>Please find below my code:</p>
<pre><code>'date_action': fields.datetime('Date current action', required=False, readonly... | 1 | 2016-08-30T13:05:17Z | 39,232,076 | <p>You are setting the default value of <code>date_action</code> as the value returned by <code>fields.datetime.now()</code>, that is executed when odoo server is started.</p>
<p>You should set the default value as the call to the method:</p>
<pre><code>'date_action': fields.datetime.now,
</code></pre>
| 2 | 2016-08-30T15:52:21Z | [
"python",
"datetime",
"openerp"
] |
How to access directory file outside django project? | 39,228,449 | <p>I have my Django project running on RHEL 7 OS. The project is in path <code>/root/project</code>. And project is hosted on httpd server. Now iam trying to access a file out side the directory like <code>/root/data/info/test.txt</code></p>
<p>How should I access this path in views.py so that I can read and write fil... | 1 | 2016-08-30T13:11:02Z | 39,231,603 | <p>Add the following lines to your <code>settings.py</code></p>
<pre><code>import os
..
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FILES_DIR = os.path.abspath(os.path.join(BASE_DIR, '../data/info'))
</code></pre>
<p>Then you can use in your view</p>
<pre><code>from django.conf import sett... | 1 | 2016-08-30T15:29:15Z | [
"python",
"django",
"apache",
"httpd.conf"
] |
Listing more than 100 stacks using boto3 | 39,228,551 | <p>We need to list all the stacks that are in CREATE_COMPLETE state. In our AWS account we have >400 such stacks. We have the following code written for this:</p>
<pre><code>stack_session = session.client('cloudformation')
list_stacks = stack_session.list_stacks(StackStatusFilter=['CREATE_COMPLETE'])
</code></pre>
<p... | 1 | 2016-08-30T13:15:10Z | 39,228,956 | <p>I got this working using pagination. The code I wrote is below:</p>
<pre><code>stack_session = session.client('cloudformation')
paginator = stack_session.get_paginator('list_stacks')
response_iterator = paginator.paginate(StackStatusFilter=['CREATE_COMPLETE'])
for page in response_iterator:
stack = page['StackS... | 1 | 2016-08-30T13:32:20Z | [
"python",
"boto3",
"cloudformation"
] |
edit django's generated javascript files | 39,228,552 | <p>i'm not actually sure that want i want to do is doable, so i'm asking to people with more experience in Python/Django than me: what i have is a local instance of a django web app, i don't have the django files but only the css/js generated from that (specifically, is an <a href="https://www.reviewboard.org/" rel="no... | 0 | 2016-08-30T13:15:12Z | 39,229,388 | <p>I will use an example of overriding static files (html and JavaScript) involving the admin app since it is built in.</p>
<p>Let's say you have an app <code>cars_app</code>, and you would like to change the behaviour of the admin page for the model <code>car</code>.</p>
<p>In the root directory of your django proje... | 0 | 2016-08-30T13:50:58Z | [
"javascript",
"python",
"django"
] |
edit django's generated javascript files | 39,228,552 | <p>i'm not actually sure that want i want to do is doable, so i'm asking to people with more experience in Python/Django than me: what i have is a local instance of a django web app, i don't have the django files but only the css/js generated from that (specifically, is an <a href="https://www.reviewboard.org/" rel="no... | 0 | 2016-08-30T13:15:12Z | 39,685,949 | <p>Use Reviewboard extension hooks for this purpose. Extension hooks are the primary mechanism for customizing Review Boardâs appearance and behavior. Specifically for adding custom css/js please try template hook and it has the option to specific the page in which you need your custom js/css. Please refer <a href="h... | 0 | 2016-09-25T10:43:22Z | [
"javascript",
"python",
"django"
] |
get user contribution number in pybossa | 39,228,554 | <p>I'm building a project in Pybossa.
When I export users, on exported user data I want to include a field which to get the number of contributions that each user did. </p>
<p>On PyBossa project statistics page I see that there is table with all contributors which is generated from this method in python: </p>
<pre><... | 0 | 2016-08-30T13:15:17Z | 39,243,832 | <p>Unfortunately this is not implemented. However, you can build a plugin yourself that will include that information, or if you prefer send us a pull request to include that feature. Happy to merge it into our upstream code base of PYBOSSA.</p>
<p>See documentation about our plugin architecture here: <a href="http://... | 1 | 2016-08-31T07:56:07Z | [
"python",
"postgresql",
"pybossa"
] |
Unable to display content on homepage ; Flask app on Google App Engine | 39,228,648 | <p>I am trying to deploy a flask app on GAE.<br><br>
All dependencies like Flask, jinja2 etc are in the same directory<br><br></p>
<p>When GAE launcher deploys the app locally, it gets deployed but <strong>nothing gets displayed on the home url once the local server is up and running</strong> even though the main.py r... | 0 | 2016-08-30T13:18:54Z | 39,231,256 | <p>try changing main to name:</p>
<pre><code>app = Flask("__name__")
</code></pre>
<p>and </p>
<pre><code>if __name__ == "__main__":
app.run(debug=True)
</code></pre>
| 0 | 2016-08-30T15:13:59Z | [
"python",
"google-app-engine",
"web-applications",
"flask"
] |
Unable to display content on homepage ; Flask app on Google App Engine | 39,228,648 | <p>I am trying to deploy a flask app on GAE.<br><br>
All dependencies like Flask, jinja2 etc are in the same directory<br><br></p>
<p>When GAE launcher deploys the app locally, it gets deployed but <strong>nothing gets displayed on the home url once the local server is up and running</strong> even though the main.py r... | 0 | 2016-08-30T13:18:54Z | 39,233,400 | <p>Flask already handles the:</p>
<pre><code>if __name__ == "__main__":
app.run()
</code></pre>
<p>so delete that. Read the <code>run(host=None, port=None, debug=None, **options)</code> section at:</p>
<p><a href="http://flask.pocoo.org/docs/0.11/api/" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/</a></... | 0 | 2016-08-30T17:12:51Z | [
"python",
"google-app-engine",
"web-applications",
"flask"
] |
How I can send json map object from flask and use it as javascript object? | 39,228,698 | <p>flask script</p>
<pre><code>from flask import Flask, render_template, request
import os
import sys
import json
data_raw = [('0', '1', '0', '0'), ('0', '0', '1', '0'), ('1', '0', '0', '0')]
app = Flask(__name__)
@app.route('/')
def index():
return render_template('test.html', data=map(json.dumps, data_raw))
<... | 0 | 2016-08-30T13:21:19Z | 39,228,814 | <p>Flask, like Django, autoescapes values by default. You need to use the <code>|safe</code> filter to render the literal values.</p>
<pre><code>var data_flask = {{ data|safe }};
</code></pre>
| 0 | 2016-08-30T13:26:20Z | [
"javascript",
"python",
"json"
] |
How I can send json map object from flask and use it as javascript object? | 39,228,698 | <p>flask script</p>
<pre><code>from flask import Flask, render_template, request
import os
import sys
import json
data_raw = [('0', '1', '0', '0'), ('0', '0', '1', '0'), ('1', '0', '0', '0')]
app = Flask(__name__)
@app.route('/')
def index():
return render_template('test.html', data=map(json.dumps, data_raw))
<... | 0 | 2016-08-30T13:21:19Z | 39,228,876 | <p>you should do <code>map(json.dump, data_raw)</code> and it should work instead of <code>map(json.dumps, data_raw)</code></p>
| 0 | 2016-08-30T13:29:04Z | [
"javascript",
"python",
"json"
] |
Understanding the behavior of function descriptors | 39,228,722 | <p>I was reading <a href="http://www.aleax.it/Python/nylug05_om.pdf" rel="nofollow">a presentation</a> on Python's Object model when, in one slide (number <code>9</code>), the author asserts that Pythons' functions are descriptors. The example he presents to illustrate is similar to this one I wrote:</p>
<pre><code>de... | 8 | 2016-08-30T13:22:30Z | 39,228,774 | <p>That's Python doing what it does in order to support dynamically adding functions to classes. </p>
<p>When <code>__get__</code> is invoked on a function object, which is usually done via dot access on an instance of a class, Python will transform the function to a method and implicitly pass the instance (usually re... | 8 | 2016-08-30T13:24:47Z | [
"python",
"python-2.7",
"function",
"python-3.x"
] |
Launching scripts from bash and directing outputs | 39,228,764 | <p>I have a question about syntax of bash regarding launching scripts from within bash script.</p>
<p>My questions are: </p>
<ol>
<li><p>I've seen the following syntax:</p>
<pre><code>#!/bin/bash
python do_something.py > /dev/null 2>&1 &
</code></pre>
<p>Can you please explain what is directed to <c... | 1 | 2016-08-30T13:24:19Z | 39,229,057 | <p>1) stdout (Standard Output) is redirected to /dev/null and stderr (error messages) is redirected to standard output i.e console. </p>
<ul>
<li>1>filename : Redirect stdout to file "filename."</li>
<li>1>>filename: Redirect and append stdout to file "filename."</li>
<li>2>filename : Redirect stderr to file "filename... | 1 | 2016-08-30T13:36:32Z | [
"python",
"linux",
"bash"
] |
Launching scripts from bash and directing outputs | 39,228,764 | <p>I have a question about syntax of bash regarding launching scripts from within bash script.</p>
<p>My questions are: </p>
<ol>
<li><p>I've seen the following syntax:</p>
<pre><code>#!/bin/bash
python do_something.py > /dev/null 2>&1 &
</code></pre>
<p>Can you please explain what is directed to <c... | 1 | 2016-08-30T13:24:19Z | 39,229,089 | <p>Answers:</p>
<p>1, 2. <code>></code> redirects whatever that is printed in <code>stdout</code> as result of executing the command (in your case <code>python do_something.py</code>) to a file called <code>/dev/null</code>. The <code>/dev/null</code> is kind of a black hole. Whatever you write to it disappers.</p>... | 1 | 2016-08-30T13:37:52Z | [
"python",
"linux",
"bash"
] |
Launching scripts from bash and directing outputs | 39,228,764 | <p>I have a question about syntax of bash regarding launching scripts from within bash script.</p>
<p>My questions are: </p>
<ol>
<li><p>I've seen the following syntax:</p>
<pre><code>#!/bin/bash
python do_something.py > /dev/null 2>&1 &
</code></pre>
<p>Can you please explain what is directed to <c... | 1 | 2016-08-30T13:24:19Z | 39,231,591 | <p>Ok, <strong>diclaimer</strong>: I don't have access to a bash right now, so I might be wrong.</p>
<ol>
<li><p>Let's break your command: <code>python do_something.py > /dev/null 2>&1 &</code></p>
<p><code>python do_something.py</code> will run your command<br/>
<code>> /dev/null</code> will redirec... | 1 | 2016-08-30T15:28:42Z | [
"python",
"linux",
"bash"
] |
Way to get specific keys from dictionary | 39,228,893 | <p>I am looking for a way to get specific keys from a dictionary. </p>
<p>In the example below, I am trying to <code>get all keys except 'inside'</code></p>
<pre><code>>>> d
{'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
>>> d_keys = list(... | 3 | 2016-08-30T13:29:59Z | 39,229,016 | <p>you can do it with a dict comprehension for example to only get evens.</p>
<pre><code>d = {1:'a', 2:'b', 3:'c', 4:'d'}
new_d = {k : v for k,v in d.items() if k % 2 == 0}
</code></pre>
<p>for your case because of complaints.</p>
<pre><code>d = {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', ... | -1 | 2016-08-30T13:34:51Z | [
"python",
"dictionary"
] |
Way to get specific keys from dictionary | 39,228,893 | <p>I am looking for a way to get specific keys from a dictionary. </p>
<p>In the example below, I am trying to <code>get all keys except 'inside'</code></p>
<pre><code>>>> d
{'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
>>> d_keys = list(... | 3 | 2016-08-30T13:29:59Z | 39,229,020 | <p>There's not really a good way to do this if you need to keep the original dictionary the same.</p>
<p>If you don't, you could <code>pop</code> the key you don't want before getting the keys.</p>
<pre><code>d = {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged... | 0 | 2016-08-30T13:35:00Z | [
"python",
"dictionary"
] |
Way to get specific keys from dictionary | 39,228,893 | <p>I am looking for a way to get specific keys from a dictionary. </p>
<p>In the example below, I am trying to <code>get all keys except 'inside'</code></p>
<pre><code>>>> d
{'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
>>> d_keys = list(... | 3 | 2016-08-30T13:29:59Z | 39,229,028 | <pre><code>for key in d_keys:
if key not in ['inside']:
print "key: %s, value: %s" % (key, d[key])
</code></pre>
| 0 | 2016-08-30T13:35:18Z | [
"python",
"dictionary"
] |
Way to get specific keys from dictionary | 39,228,893 | <p>I am looking for a way to get specific keys from a dictionary. </p>
<p>In the example below, I am trying to <code>get all keys except 'inside'</code></p>
<pre><code>>>> d
{'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
>>> d_keys = list(... | 3 | 2016-08-30T13:29:59Z | 39,229,044 | <p>In python 3.X most of dictionary attributes like <code>keys</code>, return a view object which is a set-like object, so you don't need to convert it to set again:</p>
<pre><code>>>> d_keys = d.keys() - {"inside",}
>>> d_keys
{'fill', 'size', 'angle', 'shape'}
</code></pre>
<p>Or if you are in pyt... | 4 | 2016-08-30T13:35:56Z | [
"python",
"dictionary"
] |
Way to get specific keys from dictionary | 39,228,893 | <p>I am looking for a way to get specific keys from a dictionary. </p>
<p>In the example below, I am trying to <code>get all keys except 'inside'</code></p>
<pre><code>>>> d
{'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
>>> d_keys = list(... | 3 | 2016-08-30T13:29:59Z | 39,229,047 | <p>Not sure what you need with inside but this will give your result.</p>
<pre><code>for key in d.keys:
if key != 'inside':
print "key: %s, value: %s" % (key, d[key])
</code></pre>
| 0 | 2016-08-30T13:36:03Z | [
"python",
"dictionary"
] |
Way to get specific keys from dictionary | 39,228,893 | <p>I am looking for a way to get specific keys from a dictionary. </p>
<p>In the example below, I am trying to <code>get all keys except 'inside'</code></p>
<pre><code>>>> d
{'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
>>> d_keys = list(... | 3 | 2016-08-30T13:29:59Z | 39,229,080 | <p>a cross-version approach:</p>
<pre><code>d = {'shape': 'unchanged', 'fill': 'unchanged',
'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
d_keys = [k for k in d.keys() if k != 'inside']
print(d_keys)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>['fill', 'shape', 'angle', 'size']
... | 1 | 2016-08-30T13:37:22Z | [
"python",
"dictionary"
] |
Way to get specific keys from dictionary | 39,228,893 | <p>I am looking for a way to get specific keys from a dictionary. </p>
<p>In the example below, I am trying to <code>get all keys except 'inside'</code></p>
<pre><code>>>> d
{'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
>>> d_keys = list(... | 3 | 2016-08-30T13:29:59Z | 39,229,360 | <p>Here's a little benchmark comparing a couple of good posted solutions:</p>
<pre><code>import timeit
d = {'shape': 'unchanged', 'fill': 'unchanged',
'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
def f1(d):
return d.viewkeys() - {"inside", }
def f2(d):
return filter(lambda x: x not... | 0 | 2016-08-30T13:49:57Z | [
"python",
"dictionary"
] |
Way to get specific keys from dictionary | 39,228,893 | <p>I am looking for a way to get specific keys from a dictionary. </p>
<p>In the example below, I am trying to <code>get all keys except 'inside'</code></p>
<pre><code>>>> d
{'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
>>> d_keys = list(... | 3 | 2016-08-30T13:29:59Z | 39,229,392 | <p>You can use remove() built-in.</p>
<pre><code>d = {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
d_keys = list(d.keys())
d_keys.remove('inside')
for i in d_keys:
print("Key: {}, Value: {}".format(d_keys, d[d_keys]))
</code></pre>
| 1 | 2016-08-30T13:51:26Z | [
"python",
"dictionary"
] |
identify non pandas datetimeindex? | 39,228,916 | <p>How to identify and delete non <code>datetimeindex</code> rows in following index.</p>
<p><code>Index([nan, nan, nan, nan, u'aveValue', u'minValue', u'maxValue', u'firstValue', u'lastValue', u'nPointsTot', u'nGood', u'nBlankTimes', u'nBlankValues', u'level_nGood', u'level_nSuspect', u'level_nBad', u'status_nGood', ... | 0 | 2016-08-30T13:30:57Z | 39,229,670 | <p>Convert the index <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">to datetime</a>, coerce errors, and filter <code>NaT</code> results:</p>
<pre><code>df[pd.to_datetime(df.index, errors='coerce').to_series().notnull().values]
</code></pre>
<p>In order to use th... | 1 | 2016-08-30T14:03:47Z | [
"python",
"pandas"
] |
How to bind a Python socket to a specific domain? | 39,228,928 | <p>I have a Heroku application that has a domain <code>moarcatz.tk</code>. It listens for non-HTTP requests using Python's <code>socket</code>.<br>
The documenatation states that if I bind a socket to an empty string as an IP address, it will listen on all available interfaces. I kept getting empty requests from variou... | 1 | 2016-08-30T13:31:15Z | 39,231,015 | <p>You can't control this via your code, but you can control this via Heroku.</p>
<p>Heroku has a pretty nifty DNS CNAME tool you can use to ensure your app ONLY listens to incoming requests for specific domains -- it's part of the core Heroku platform.</p>
<p>What you do is this:</p>
<pre><code>heroku domains:add w... | 0 | 2016-08-30T15:02:04Z | [
"python",
"sockets",
"heroku"
] |
Is there an alternative result for Python unit tests, other than a Pass or Fail? | 39,228,974 | <p>I'm writing unit tests that have a database dependency (so technically they're functional tests). Often these tests not only rely on the database to be live and functional, but they can also rely on certain data to be available.</p>
<p>For example, in one test I might query the database to retrieve sample data tha... | 0 | 2016-08-30T13:33:15Z | 39,249,810 | <p>In general I think the advice by <a href="http://stackoverflow.com/questions/39228974/is-there-an-alternative-result-for-python-unit-tests-other-than-a-pass-or-fail#comment65795188_39228974">Paul Becotte</a> is best for most cases:</p>
<blockquote>
<p>This is a failure though- your tests failed to set up the syst... | 0 | 2016-08-31T12:33:45Z | [
"python",
"unit-testing",
"functional-testing"
] |
pivot_table No numeric types to aggregate | 39,229,005 | <p>I want to make a pivot table from the following dataframe with columns <code>sales</code>, <code>rep</code>. The pivot table shows <code>sales</code> but no <code>rep</code>. When I tried with only <code>rep</code>, I got the error <code>DataError: No numeric types to aggregate</code>. How to fix this such that I se... | 1 | 2016-08-30T13:34:25Z | 39,229,232 | <p>You could use <code>set_index</code> and <code>unstack</code>:</p>
<pre><code>df = pd.DataFrame(data)
df.set_index(['year','country']).unstack('year')
</code></pre>
<p>yields</p>
<pre><code> rep sales
year 2013 2014 2015 2016 2013 2014 2015 2016
country ... | 3 | 2016-08-30T13:44:19Z | [
"python",
"pandas"
] |
pivot_table No numeric types to aggregate | 39,229,005 | <p>I want to make a pivot table from the following dataframe with columns <code>sales</code>, <code>rep</code>. The pivot table shows <code>sales</code> but no <code>rep</code>. When I tried with only <code>rep</code>, I got the error <code>DataError: No numeric types to aggregate</code>. How to fix this such that I se... | 1 | 2016-08-30T13:34:25Z | 39,229,396 | <p>It seems that the problem comes from the different types for column rep and sales, if you convert the sales to <code>str</code> type and specify the aggfunc as <code>sum</code>, it works fine:</p>
<pre><code>df.sales = df.sales.astype(str)
pd.pivot_table(df, index=['country'], columns=['year'], values=['rep', 'sal... | 1 | 2016-08-30T13:51:47Z | [
"python",
"pandas"
] |
How can I self hide and show QDialog() in PyQT5? | 39,229,053 | <p>I have a GUI that was generated using Qt Designer, I used pyuic5 to generate a .py file. In a separate py (program.py) file I import my UI a do all my work there. </p>
<p><strong>program.py</strong></p>
<pre><code>import sys, os, time
from subprocess import call
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt... | 0 | 2016-08-30T13:36:20Z | 39,230,866 | <p>In your code snippet, <code>dialog</code> is of type <code>QDialog</code> and thereby having <code>hide</code> method. However instances of <code>MyGUI</code> class seem to not have such a method. So, if you write <code>dialog.hide()</code> in that <code>__init__()</code> function, you can hide it.</p>
| 1 | 2016-08-30T14:55:58Z | [
"python",
"qt",
"python-3.x",
"pyqt5"
] |
Selenium find_element_by_xpath last | 39,229,109 | <p>I have a bunch of elements and need to select last one using xpath.
The elements looks like:</p>
<pre><code>xpath=(//a[contains(text(),'Actions')])[2]
xpath=(//a[contains(text(),'Actions')])[3]
xpath=(//a[contains(text(),'Actions')])[4]
xpath=(//a[contains(text(),'Actions')])[5]
xpath=(//a[contains(text(),'Actions'... | 0 | 2016-08-30T13:38:42Z | 39,232,685 | <p>Your code is selecting first because you are using find element by xpath try </p>
<pre><code>ele= driver.find_elements_by_xpath("//a[contains(text(),'Actions')][last ()]")
ele[-1].click
</code></pre>
| 0 | 2016-08-30T16:28:57Z | [
"python",
"selenium",
"xpath"
] |
How to get text of children tag's description using beautiful soup | 39,229,110 | <p>I am using beautiful soup to scrap some data from
<a href="http://www.foodily.com/r/0y1ygzt3zf-perfect-vanilla-cupcakes-by-annie-s" rel="nofollow">foodily.com</a></p>
<p>On above page there is a div with class 'ings' and I want to get data within its p tags for that I have written below code:</p>
<pre><code>ingre... | 0 | 2016-08-30T13:38:44Z | 39,229,193 | <p>Call <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow"><code>get_text()</code></a> for every <code>p</code> element found inside the <code>div</code> element with <code>class="ings"</code>.</p>
<p>Complete working code:</p>
<pre><code>from bs4 import BeautifulSoup
import requ... | 2 | 2016-08-30T13:42:31Z | [
"python",
"beautifulsoup"
] |
How to get text of children tag's description using beautiful soup | 39,229,110 | <p>I am using beautiful soup to scrap some data from
<a href="http://www.foodily.com/r/0y1ygzt3zf-perfect-vanilla-cupcakes-by-annie-s" rel="nofollow">foodily.com</a></p>
<p>On above page there is a div with class 'ings' and I want to get data within its p tags for that I have written below code:</p>
<pre><code>ingre... | 0 | 2016-08-30T13:38:44Z | 39,231,652 | <p>Another way:</p>
<pre><code>import requests
from bs4 import BeautifulSoup as bs
url = "http://www.foodily.com/r/0y1ygzt3zf-perfect-vanilla-cupcakes-by-annie-s"
source = requests.get(url)
text_new = source.text
soup = bs(text_new, "html.parser")
ingredients = soup.findAll('div', {"class": "ings"})
for a in ingred... | 0 | 2016-08-30T15:32:23Z | [
"python",
"beautifulsoup"
] |
How to get text of children tag's description using beautiful soup | 39,229,110 | <p>I am using beautiful soup to scrap some data from
<a href="http://www.foodily.com/r/0y1ygzt3zf-perfect-vanilla-cupcakes-by-annie-s" rel="nofollow">foodily.com</a></p>
<p>On above page there is a div with class 'ings' and I want to get data within its p tags for that I have written below code:</p>
<pre><code>ingre... | 0 | 2016-08-30T13:38:44Z | 39,236,959 | <p>If you already have the list of <code>p</code> tags, use <code>get_text()</code>. This will return only the text of them:</p>
<pre><code>ingredient_list = p.get_text() for p in ingredients
</code></pre>
<p>The result array will look like:</p>
<pre><code>ingredient_list = [
'For the cupcakes:', '1 stick (113g) ... | 0 | 2016-08-30T20:56:20Z | [
"python",
"beautifulsoup"
] |
Firefox works but PhantomJS throws Unable to find element with css selector | 39,229,207 | <p>I recently changed from <code>webdriver.Firefox()</code> to <code>webdriver.PhantomJS()</code> to get a speed improvement and i started getting some errors when i try to find an element on my datepicker in order to click it after</p>
<pre><code> self.driver = webdriver.PhantomJS()
self.driver.set_window_size... | 1 | 2016-08-30T13:43:05Z | 39,235,433 | <p>I've reproduced your issue and was able to fix it by <em>maximizing the browser window</em>:</p>
<pre><code>self.driver = webdriver.PhantomJS()
self.driver.maximize_window()
</code></pre>
| 0 | 2016-08-30T19:15:33Z | [
"python",
"python-3.x",
"selenium",
"datepicker",
"phantomjs"
] |
Join list from specific index | 39,229,286 | <p>I have a list like below:</p>
<pre><code>ingredients = ['apple','cream','salt','sugar','cider']
</code></pre>
<p>I want to join this list to get a string but I want to join from 2nd index till the last one.</p>
<p>to get this : <code>"salt sugar cider"</code>
Length of list may vary.</p>
<p>Is it possible to do ... | 0 | 2016-08-30T13:46:52Z | 39,229,311 | <p>Just <a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation"><em>slice</em> the list</a>:</p>
<pre><code>>>> l = ['apple', 'cream', 'salt', 'sugar', 'cider']
>>> ' '.join(l[2:])
'salt sugar cider'
</code></pre>
<p>We don't specify the end of the slice which means that i... | 8 | 2016-08-30T13:48:02Z | [
"python",
"django",
"list",
"python-2.7"
] |
Convert 11/2/1998 to 110298 | 39,229,313 | <p>What is the simplest way to convert a date formatted <code>3/2/2004</code> to <code>030204</code> in pure bash, or if not possible, then Python?
I need to at zeros in front of an single digit sectors of the date, remove the parenthesis, and have only the last two characters of the 4 digit year.
I know I could write ... | -8 | 2016-08-30T13:48:03Z | 39,229,390 | <pre><code>date -d'11/2/1998' +%m%d%y
110298
</code></pre>
| 2 | 2016-08-30T13:51:04Z | [
"python",
"bash",
"awk",
"sed",
"grep"
] |
Convert 11/2/1998 to 110298 | 39,229,313 | <p>What is the simplest way to convert a date formatted <code>3/2/2004</code> to <code>030204</code> in pure bash, or if not possible, then Python?
I need to at zeros in front of an single digit sectors of the date, remove the parenthesis, and have only the last two characters of the 4 digit year.
I know I could write ... | -8 | 2016-08-30T13:48:03Z | 39,229,535 | <pre><code>import datetime
d = datetime.datetime.strptime("11/2/1998", "%d/%m/%Y")
print d.strftime("%d%m%y")
</code></pre>
| 2 | 2016-08-30T13:57:31Z | [
"python",
"bash",
"awk",
"sed",
"grep"
] |
Encoding error when reading url with urllib | 39,229,439 | <p>When I try to scrape a wikipedia site with a special character in its URL, using urllib.request and Python, I get the following error <code>UnicodeEncodeError: 'ascii' codec can't encode character '\xf8' in position 23: ordinal not in range(128)</code></p>
<p>The code:</p>
<pre><code># -*- coding: utf-8 -*-
import... | 0 | 2016-08-30T13:53:36Z | 39,229,490 | <p>New plan - Using requests</p>
<pre><code>from bs4 import BeautifulSoup
import requests
def scrape():
url = "http://no.wikipedia.org/wiki/Jonas_Gahr_Støre"
r = requests.get(url).content
soup = BeautifulSoup(r).encode('utf-8')
print soup
print r
if __name__ == '__main__':
scrape()
</code>... | 0 | 2016-08-30T13:55:30Z | [
"python",
"urllib"
] |
Encoding error when reading url with urllib | 39,229,439 | <p>When I try to scrape a wikipedia site with a special character in its URL, using urllib.request and Python, I get the following error <code>UnicodeEncodeError: 'ascii' codec can't encode character '\xf8' in position 23: ordinal not in range(128)</code></p>
<p>The code:</p>
<pre><code># -*- coding: utf-8 -*-
import... | 0 | 2016-08-30T13:53:36Z | 39,229,882 | <p>Apparently, urllib can only handle ASCII requests, and converting your url to ascii gives a error on your special character.
Replacing ø with %C3%B8, the proper way to encode this special character in http, seems to do the trick. However, I can't find a method to do this automatically like your browser does.</p>
<... | 0 | 2016-08-30T14:12:18Z | [
"python",
"urllib"
] |
Encoding error when reading url with urllib | 39,229,439 | <p>When I try to scrape a wikipedia site with a special character in its URL, using urllib.request and Python, I get the following error <code>UnicodeEncodeError: 'ascii' codec can't encode character '\xf8' in position 23: ordinal not in range(128)</code></p>
<p>The code:</p>
<pre><code># -*- coding: utf-8 -*-
import... | 0 | 2016-08-30T13:53:36Z | 39,229,884 | <p>If using a library is an option, I would suggest the awesome <a href="http://docs.python-requests.org/" rel="nofollow">requests</a></p>
<pre><code># -*- coding: utf-8 -*-
import requests
r = requests.get('https://no.wikipedia.org/wiki/Jonas_Gahr_Støre')
print(r.text)
</code></pre>
| 0 | 2016-08-30T14:12:26Z | [
"python",
"urllib"
] |
Encoding error when reading url with urllib | 39,229,439 | <p>When I try to scrape a wikipedia site with a special character in its URL, using urllib.request and Python, I get the following error <code>UnicodeEncodeError: 'ascii' codec can't encode character '\xf8' in position 23: ordinal not in range(128)</code></p>
<p>The code:</p>
<pre><code># -*- coding: utf-8 -*-
import... | 0 | 2016-08-30T13:53:36Z | 39,230,084 | <p>Using the <a href="http://stackoverflow.com/a/39229882/2169327">answer from @mousetail</a> I wrote a custom encoder for the characters I needed:</p>
<pre><code>def properEncode(url):
url = url.replace("ø", "%C3%B8")
url = url.replace("Ã¥", "%C3%A5")
url = url.replace("æ", "%C3%A6")
url = url.replace("Ã",... | -1 | 2016-08-30T14:20:49Z | [
"python",
"urllib"
] |
Error while accessing dictionary in python | 39,229,607 | <p>I have a dictionary named <code>json_dict</code> given below. </p>
<p>I need to access the element <code>==> json_dict['OptionSettings'][3]['Value']</code>.</p>
<p>I need to access the element using the syntax</p>
<p><code>print(json_dict[parameter])</code>. </p>
<p>When I give a parameter such as</p>
<p><co... | -5 | 2016-08-30T14:01:12Z | 39,229,696 | <p>Unfortunately you can't do that. </p>
<p>When you type <code>param="['OptionSettings'][3]['Value']"</code> and then <code>json_dict[param]</code>, you are basically asking for the value represented by the key <code>"['OptionSettings'][3]['Value']"</code> which does not exists.</p>
<p>You´ll have to navigate throu... | 2 | 2016-08-30T14:04:43Z | [
"python",
"json",
"python-2.7",
"python-3.x",
"dictionary"
] |
Error while accessing dictionary in python | 39,229,607 | <p>I have a dictionary named <code>json_dict</code> given below. </p>
<p>I need to access the element <code>==> json_dict['OptionSettings'][3]['Value']</code>.</p>
<p>I need to access the element using the syntax</p>
<p><code>print(json_dict[parameter])</code>. </p>
<p>When I give a parameter such as</p>
<p><co... | -5 | 2016-08-30T14:01:12Z | 39,249,022 | <p>This worked for me</p>
<pre><code>str1="json_dict"
params="['OptionSettings'][3]['Value']"
str2=str1+params
print(eval(str5))
</code></pre>
<p>Here the use of function <strong><em>eval()</em></strong> is the key to solve this.</p>
| 0 | 2016-08-31T11:56:57Z | [
"python",
"json",
"python-2.7",
"python-3.x",
"dictionary"
] |
How to execute set of commands after sudo using python script | 39,229,620 | <p>I am trying to automate deployment process using the python. In deployment I do "dzdo su - sysid" first and then perform the deployment process. But I am not able to handle this part in python. I have done similar thing in shell where I used following piece of code,</p>
<pre><code>/bin/bash
psh su - sysid <<... | 0 | 2016-08-30T14:01:42Z | 39,254,379 | <p>The text between <code><< EOF</code> and <code>EOF</code> in your shell script example will be written to the standard input of the <code>psh</code> process. So you have to redirect the standard input of your <code>Popen</code> instance and write the data either directly into the <code>stdin</code> file of yo... | 0 | 2016-08-31T16:10:11Z | [
"python",
"linux",
"shell",
"subprocess"
] |
Encoding/decoding troubleshooting for python CSVs and JSON files | 39,229,646 | <p>I initially dumped a file which contained a particular sentence using:</p>
<pre><code> with open(labelFile, "wb") as out:
json.dump(result, out,indent=4)
</code></pre>
<p>This sentence within the JSON looks like:</p>
<pre><code>"-LSB- 97 -RSB- However , the influx of immigrants from mainland China , appro... | 2 | 2016-08-30T14:02:48Z | 39,236,900 | <p>I figured out the solution to this. The solution was to decode the CSV file from its original format (identified as <code>UTF-8</code>) and then the sentence becomes the original one. So:</p>
<pre><code>csvfile = open(sys.argv[1], 'r')
fieldnames = ("x","y","z")
reader = csv.DictReader(csvfile, fieldnames)
next(re... | 1 | 2016-08-30T20:52:35Z | [
"python",
"csv",
"encoding",
"decode",
"utf"
] |
boto3 Create non-expiring URLS | 39,229,688 | <p>In boto3, there is a function that generate to generate pre-signed-urls, but they time out.
See: <a href="http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.generate_presigned_url" rel="nofollow">http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.generate_presigned_url... | 0 | 2016-08-30T14:04:24Z | 39,230,260 | <p>There is no way to create non-pre-signed URLs or pre-signed URLs without expiration. The basic use of presigned URLs is </p>
<blockquote>
<p>A pre-signed URL gives you access to the object identified in the URL,
provided that the creator of the pre-signed URL has permissions to
access that object. That is, if... | 1 | 2016-08-30T14:27:57Z | [
"python",
"python-2.7",
"boto3"
] |
How to install PyPdf2 in PyCharm (Windows-64 bits) | 39,229,692 | <p>I want to install PyPdf2 in PyCharm for Windows (64 bits)
I have tried to go to Settings\Project\Project Interpreter, Then pressing the "+" sign, but It did not found PyPdf2. </p>
<ul>
<li><p>I already Installed it to the normal python2.7 by going to the extracted path of PyPdf2 then I run (python.exe setup.py inst... | 0 | 2016-08-30T14:04:35Z | 39,231,297 | <p>Try the a look at the documentation to install library</p>
<p><a href="https://www.jetbrains.com/help/pycharm/2016.1/installing-uninstalling-and-upgrading-packages.html" rel="nofollow">Pycharm Documentation</a></p>
| 0 | 2016-08-30T15:15:15Z | [
"python",
"windows",
"package",
"pycharm",
"pypdf2"
] |
Novice python user need help passing data between functions | 39,229,738 | <p>I am finishing an assignment for a class where a teacher can input the student ID numbers and the students grades. The final grade will be calculated and returned next to the students number. I can calculate the final grade just fine, but I cannot append the grade to the list of student numbers. </p>
<pre><code>def... | 0 | 2016-08-30T14:06:30Z | 39,234,397 | <p>Your problem is here:</p>
<pre><code>f = assignments().finalGrade
netIDList.append(": " + f)
</code></pre>
<p>You're accessing <code>assignments</code> like it is an object rather than a function. You want to have <code>assignments</code> return a value to append.</p>
<pre><code>def assignments():
# do all yo... | 0 | 2016-08-30T18:12:45Z | [
"python",
"function"
] |
change data in Python import file | 39,229,823 | <p>In my main script, I import some user specific data (another script):<br>
main script: </p>
<pre><code>.....
import a lot of things....
import acemedat
..... here goes the main code
</code></pre>
<p>the imported file ('acemedat.py'): </p>
<pre><code># some comment
azcor = 10 # value can be user d... | 1 | 2016-08-30T14:10:03Z | 39,229,909 | <p>The file <em>is</em> only strings (well, one big string); what is in that file is used to create the variable you are interested in (amongst other things).</p>
<p>So what you need to do is modify your file to contain the string representation of what you want your variable's value to be, as if you had opened the fi... | 1 | 2016-08-30T14:13:18Z | [
"python"
] |
XML RPC add a date | 39,229,828 | <p>im trying to import salesorder from excel then insert them in sales order odoo</p>
<p>for now im trying to add the sales order then later i will add the order lines</p>
<pre><code>import psycopg2
import psycopg2.extras
import pyexcel_xls
import pyexcel as pe
from pyexcel_xls import get_data
from datetime import da... | 0 | 2016-08-30T14:10:18Z | 39,232,249 | <p>You have to use Odoo's date format for using dates. It's the ISO 8601 international date format: <code>YYYY-MM-DD</code>.</p>
| 0 | 2016-08-30T16:01:01Z | [
"python",
"web-services",
"openerp",
"xml-rpc",
"odoo-9"
] |
Python Import Text Array with Numpy | 39,229,830 | <p>I have a text file that looks like this:</p>
<pre><code>...
5 [0, 1] [512, 479] 991
10 [1, 0] [706, 280] 986
15 [1, 0] [807, 175] 982
20 [1, 0] [895, 92] 987
...
</code></pre>
<p>Each column is tab separated, but there are arrays in some of the columns. Can I import these with <code>np.genfromtxt</co... | 0 | 2016-08-30T14:10:19Z | 39,233,680 | <p>Brackets in a <code>csv</code> file are klunky no matter how you look at it. The default <code>csv</code> structure is 2d - rows and uniform columns. The brackets add a level of nesting. But the fact that the columns are tab separated, while the nested blocks are comma separated makes it a bit easier.</p>
<p>You... | 0 | 2016-08-30T17:30:28Z | [
"python",
"arrays",
"numpy",
"genfromtxt"
] |
Python Import Text Array with Numpy | 39,229,830 | <p>I have a text file that looks like this:</p>
<pre><code>...
5 [0, 1] [512, 479] 991
10 [1, 0] [706, 280] 986
15 [1, 0] [807, 175] 982
20 [1, 0] [895, 92] 987
...
</code></pre>
<p>Each column is tab separated, but there are arrays in some of the columns. Can I import these with <code>np.genfromtxt</co... | 0 | 2016-08-30T14:10:19Z | 39,233,688 | <p>Potential approach for given data, however not using numpy:</p>
<pre><code>import ast
data1, data2, data3, data4 = [],[],[],[]
for l in open('data.txt'):
data = l.split('\t')
data1.append(int(data[0]))
data2.append(ast.literal_eval(data[1]))
data3.append(ast.literal_eval(data[2]))
data4.appen... | 1 | 2016-08-30T17:30:45Z | [
"python",
"arrays",
"numpy",
"genfromtxt"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.