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
Why is relative path not working in python tests?
38,231,478
<p>My directory layout is as follows</p> <pre><code>project\ project\setup.py project\scripts\foo.py project\scripts\bar.py project\scripts\__init__.py project\tests\test_foo.py project\tests\__init__.py </code></pre> <p>My test file looks as follows</p> <pre><code>project\tests\test_fo.py from ..scripts import foo...
1
2016-07-06T18:42:02Z
38,231,766
<p>Relative imports only work <em>within</em> a package. <code>scripts</code> may be a package, and so is <code>tests</code>, but the <code>project</code> directory <em>is not</em> (and neither should it be). This makes <code>scripts</code> and <code>tests</code> <em>top-level packages</em>. You can't refer to other to...
3
2016-07-06T18:57:34Z
[ "python", "relative-path", "setuptools", "py.test", "setup.py" ]
What should be the size of input and hidden state in GRUCell of tensorflow (python)?
38,231,521
<p>I am new to tensorflow (1 day of experience).</p> <p>I am trying following small code to create a simple GRU based RNN with single layer and hidden size of 100 as follows:</p> <pre><code>import pickle import numpy as np import pandas as pd import tensorflow as tf # parameters batch_size = 50 hidden_size = 100 # ...
0
2016-07-06T18:44:19Z
38,232,639
<p>Input to the <code>GRUCell</code>'s call operator are expected to be 2-D tensors with <code>tf.float32</code> type. The following ought to work :</p> <pre><code>input_data = tf.placeholder(tf.float32, [batch_size, input_size]) cell = tf.nn.rnn_cell.GRUCell(hidden_size) initial_state = cell.zero_state(batch_size, ...
0
2016-07-06T19:53:16Z
[ "python", "tensorflow", "recurrent-neural-network", "gated-recurrent-unit" ]
Display rows where any value in a particular column occurs more than once
38,231,568
<p>I want to display all the rows where any value in the column - "Website" occurs more than once. For example - if a certain website "xyz.com" occurs more than once, then I want to display all those rows. I am using the below code - </p> <pre><code>df[df.website.isin(df.groupby('website').website.count() &gt; 1)] </...
4
2016-07-06T18:46:51Z
38,231,748
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html"><code>duplicated</code></a> with <code>subset='website'</code> and <code>keep=False</code>:</p> <pre><code>df[df.duplicated(subset='website', keep=False)] </code></pre> <p>Sample Input:</p> <pre><code> col1 webs...
6
2016-07-06T18:56:36Z
[ "python", "pandas" ]
Splitting dictionary/list inside a Pandas Column into Separate Columns
38,231,591
<p>I have data saved in a postgreSQL database. I am querying this data using Python2.7 and turning it into a Pandas DataFrame. However, the last column of this dataframe has a dictionary (or list?) of values within it. The DataFrame looks like this:</p> <pre><code>[1] df Station ID Pollutants 8809 {"a": ...
3
2016-07-06T18:47:56Z
38,231,651
<p>To convert the string to an actual dict, you can do <code>df['Pollutant Levels'].map(eval)</code>. Afterwards, the solution below can be used to convert the dict to different columns.</p> <hr> <p>Using a small example, you can use <code>.apply(pd.Series)</code>:</p> <pre><code>In [2]: df = pd.DataFrame({'a':[1,2,...
5
2016-07-06T18:51:37Z
[ "python", "pandas", "dictionary", "dataframe" ]
Splitting dictionary/list inside a Pandas Column into Separate Columns
38,231,591
<p>I have data saved in a postgreSQL database. I am querying this data using Python2.7 and turning it into a Pandas DataFrame. However, the last column of this dataframe has a dictionary (or list?) of values within it. The DataFrame looks like this:</p> <pre><code>[1] df Station ID Pollutants 8809 {"a": ...
3
2016-07-06T18:47:56Z
38,233,518
<p>Try this: <strong>The data returned from SQL has to converted into a Dict.</strong> or could it be <code>"Pollutant Levels"</code> is now <code>Pollutants'</code></p> <pre><code> StationID Pollutants 0 8809 {"a":"46","b":"3","c":"12"} 1 8810 {"a":"36","b":"5","c":"8"} 2 ...
0
2016-07-06T20:47:18Z
[ "python", "pandas", "dictionary", "dataframe" ]
Splitting dictionary/list inside a Pandas Column into Separate Columns
38,231,591
<p>I have data saved in a postgreSQL database. I am querying this data using Python2.7 and turning it into a Pandas DataFrame. However, the last column of this dataframe has a dictionary (or list?) of values within it. The DataFrame looks like this:</p> <pre><code>[1] df Station ID Pollutants 8809 {"a": ...
3
2016-07-06T18:47:56Z
38,256,863
<p>in one line:</p> <pre><code>df = pd.concat([df['a'], df.b.apply(pd.Series)], axis=1)` </code></pre>
0
2016-07-07T23:33:56Z
[ "python", "pandas", "dictionary", "dataframe" ]
Python 'function' object has no attribute 'uniform'
38,231,699
<p>I'm extremely new to Python (as in this is the first script I've written), and I'm just messing around trying to make something that will work.</p> <p>I've written the following:</p> <pre><code># Roll the Dice from random import randint x = randint.uniform(1, 6) y = randint.uniform(1, 6) print str(x + y) </code...
1
2016-07-06T18:54:19Z
38,231,777
<p><code>uniform</code> and <code>randint</code> are both functions* defined in the <code>random</code> module.</p> <pre><code>from random import uniform x = uniform(1, 6) </code></pre> <hr> <p>* Not quite; there is a module-level global RNG whose methods are accessible as module-level names.</p>
1
2016-07-06T18:58:26Z
[ "python" ]
Python 'function' object has no attribute 'uniform'
38,231,699
<p>I'm extremely new to Python (as in this is the first script I've written), and I'm just messing around trying to make something that will work.</p> <p>I've written the following:</p> <pre><code># Roll the Dice from random import randint x = randint.uniform(1, 6) y = randint.uniform(1, 6) print str(x + y) </code...
1
2016-07-06T18:54:19Z
38,231,834
<p>You are mixing up modules and functions. randint is a fuction in the random module, as is uniform. Instead of loading just the randint function, load the whole module. See <a href="https://docs.python.org/2/library/random.html" rel="nofollow">https://docs.python.org/2/library/random.html</a> for more information<...
2
2016-07-06T19:01:34Z
[ "python" ]
TypeError: write() argument must be str, not bytes, UTF-16
38,231,747
<p>So I'm running test cases with Selenium and python, and I want to generate HTML Test reports for these tests. I found this resource that should do it for me, <a href="http://tungwaiyip.info/software/HTMLTestRunner.html" rel="nofollow">http://tungwaiyip.info/software/HTMLTestRunner.html</a> in case anybody is interes...
1
2016-07-06T18:56:33Z
38,232,972
<p><code>HTMLTestRunner</code> is a python2 module. Python3 distinguishes between <code>str</code> and <code>bytes</code> object, whereas python2 had <code>unicode</code> and <code>str</code>.</p> <p>As the error message says, line 688 requires a <code>str</code>, not <code>bytes</code> object. As <a href="https://doc...
3
2016-07-06T20:15:08Z
[ "python", "selenium", "selenium-webdriver", "typeerror" ]
IronPython submodule import
38,231,751
<p>I have a generic issue with IronPython module import processing.</p> <p>Given a Python package, submodules can refer to each other with relative references. Assume the package is called Poultry and submodules within it are Chicken.py and Duck.py. Chicken can then import Duck simply as "import Duck" and vica versa. ...
1
2016-07-06T18:56:48Z
38,232,798
<p>You have to always import <code>Duck</code> as part of its package. Inside an application, always do either of:</p> <pre><code>import Poultry.Duck from Poultry import Duck </code></pre> <p>If you run it directly with an interpreter, you must use the <a href="https://docs.python.org/3/using/cmdline.html#cmdoption-m...
0
2016-07-06T20:03:55Z
[ "c#", "python", "ironpython" ]
IronPython submodule import
38,231,751
<p>I have a generic issue with IronPython module import processing.</p> <p>Given a Python package, submodules can refer to each other with relative references. Assume the package is called Poultry and submodules within it are Chicken.py and Duck.py. Chicken can then import Duck simply as "import Duck" and vica versa. ...
1
2016-07-06T18:56:48Z
38,273,832
<p>You still need to import Chicken by typing <code>from Poultry import Chicken</code>. You can't just do <code>import Chicken</code>. It would be the same from any file in your project. </p>
0
2016-07-08T19:11:22Z
[ "c#", "python", "ironpython" ]
How to add a column to a multi-indexed DataFrame?
38,231,809
<p>I have a DataFrame like this:</p> <pre><code>upper level1 level2 lower name name 1 Mary Tom 2 ... ... </code></pre> <p>What should I do if I want to add another column under <code>level1</code>? For example</p> <pre><code>upper level1 level2 lower name age ...
4
2016-07-06T18:59:59Z
38,231,956
<p>Try this:</p> <pre><code>df.insert(1, ('level1', 'age'), pd.Series([13])) </code></pre>
6
2016-07-06T19:09:25Z
[ "python", "pandas" ]
How to add a column to a multi-indexed DataFrame?
38,231,809
<p>I have a DataFrame like this:</p> <pre><code>upper level1 level2 lower name name 1 Mary Tom 2 ... ... </code></pre> <p>What should I do if I want to add another column under <code>level1</code>? For example</p> <pre><code>upper level1 level2 lower name age ...
4
2016-07-06T18:59:59Z
38,231,991
<p>You can use tuple in the assignment:</p> <pre><code>In [11]: df[('level1', 'age')] = 13 # or a Series here, rather than a number In [12]: df Out[12]: upper level1 level2 level1 lower name name age 0 1 Mary Tom 13 1 2 ... ... 13 </code></pre>
4
2016-07-06T19:11:22Z
[ "python", "pandas" ]
Display data from json with discord.py
38,231,937
<p>I'm currently making a discord bot that will display osu! stats. This is my code: </p> <pre><code>@bot.command() async def osu(osu_name : str): """Adds two numbers together.""" await bot.say("Fetching data") url = 'https://osu.ppy.sh/api/get_user?k={ my api key }&amp;u=' + osu_name # Do the HTTP get...
0
2016-07-06T19:08:24Z
38,232,034
<p>You can use python's builtin <code>json</code> module to convert the json response into a python dictionary - just <code>import json</code> and then do something like this to access individual elements of the response: <code>data = json.loads(response.json())[0]</code>. Then you can access individual elements like <...
0
2016-07-06T19:14:22Z
[ "python", "json", "python-3.x", "bots" ]
Display data from json with discord.py
38,231,937
<p>I'm currently making a discord bot that will display osu! stats. This is my code: </p> <pre><code>@bot.command() async def osu(osu_name : str): """Adds two numbers together.""" await bot.say("Fetching data") url = 'https://osu.ppy.sh/api/get_user?k={ my api key }&amp;u=' + osu_name # Do the HTTP get...
0
2016-07-06T19:08:24Z
38,232,954
<p>The <code>data = response.json()</code> returns a <strong>list</strong> of dictionary objects. So you have to specify the index first before accessing the value. Suppose you want to access the <code>pp_raw</code> in the first object, it will look like:</p> <pre><code>print data[0]['pp_raw'] </code></pre>
0
2016-07-06T20:14:29Z
[ "python", "json", "python-3.x", "bots" ]
Xpath - obtaining 2 nodes with 1 node having default value if missing
38,231,990
<p>I am using xpath in Python 2.7 with lxml:</p> <pre><code>from lxml import html ... tree = html.fromstring(source) results = tree.xpath(...xpath string...) </code></pre> <p>Now the problem is the xpath string and am getting quite lost in this. I am trying to get all the nodes from one path like this:</p> <pre><cod...
1
2016-07-06T19:11:21Z
38,232,503
<p>Don't make this more complicated than it is:</p> <pre><code>path1 = '//a[@class="hyperlinkClass"]/span' path2 = './following-sibling::div[@class="divClassName"]/span[@class="spanClassName"]' for link in tree.xpath(path1): other_node = link.xpath(path2) if len(other_node): print(link.text, other_nod...
2
2016-07-06T19:44:23Z
[ "python", "python-2.7", "xpath" ]
Receiving socket data in one thread, writing the data in another -- python
38,232,031
<p>I'm currently writing a Python program to receive data from either a TCP/UDP socket, and then write the data to a file. Right now, my program is I/O bound by writing each datagram to the file as it comes in (I'm doing this for very large files, so the slowdown is considerable). With that in mind, I've decided that I...
0
2016-07-06T19:14:16Z
38,232,446
<p>You need to have a buffer that the reading thread writes to, and the writing thread reads from. A <a href="https://docs.python.org/3/library/collections.html#collections.deque" rel="nofollow"><code>deque</code> from the <code>collections</code> module</a> is perfect, as it allows append/pop from either side without ...
0
2016-07-06T19:41:15Z
[ "python", "multithreading", "sockets", "io" ]
Data extraction from hierachial text using Python
38,232,046
<p>Below is the example of my hierarchical data. Using python, what is the best way to extract all the entry information and save them in a table with rows and columns organized based on the hierarchical structure. Is it possible to perform iteration over each Cluster ?</p> <pre><code>Root_file { Version = "1.1" ...
1
2016-07-06T19:14:52Z
38,232,213
<p>use json format. if you want to store this in a relational database i have no idea how to do it. but you could store the data as json using MongoDB.</p> <pre><code>Root_file = { "Version" : "1.1", "Clusters" : [ { "ClusterName" : "cluster 1", "Groups" : [ { ...
0
2016-07-06T19:26:09Z
[ "python", "hierarchical-data" ]
Data extraction from hierachial text using Python
38,232,046
<p>Below is the example of my hierarchical data. Using python, what is the best way to extract all the entry information and save them in a table with rows and columns organized based on the hierarchical structure. Is it possible to perform iteration over each Cluster ?</p> <pre><code>Root_file { Version = "1.1" ...
1
2016-07-06T19:14:52Z
38,233,775
<p>What you need is a <strong>parser</strong> for this data format. I don't know if it's a standard, therefore I don't know if there's a parser, but I came up with a parser that works <em>only</em> if the input if formatted as you have posted:</p> <pre><code>import re group_start_pattern = re.compile(r"(\w+)\s*\{") va...
0
2016-07-06T21:07:05Z
[ "python", "hierarchical-data" ]
Can I replace part of a string in a JSON key in Python?
38,232,051
<p>This is my first question here, I'm new to python and trying to figure some things out to set up an automatic 3D model processing chain that relies on data being stored in JSON files moving from one server to another.</p> <p>The problem is that I need to store absolute paths to files that are being processed, but t...
3
2016-07-06T19:15:16Z
38,232,119
<p>Your replace logic failed as you need to reassign content to the new string,<code>str.replace</code> is not an inplace operation, it creates a new string:</p> <pre><code> content = content.replace("D:\\Outgoing\\", "X:\\Incoming\\") </code></pre> <p>Using the json approach just do a replace too, using the current...
4
2016-07-06T19:20:11Z
[ "python", "json" ]
Can I replace part of a string in a JSON key in Python?
38,232,051
<p>This is my first question here, I'm new to python and trying to figure some things out to set up an automatic 3D model processing chain that relies on data being stored in JSON files moving from one server to another.</p> <p>The problem is that I need to store absolute paths to files that are being processed, but t...
3
2016-07-06T19:15:16Z
38,232,481
<p>Python come with a <a href="https://docs.python.org/2.7/library/json.html" rel="nofollow">json</a> library. With this library, you can read and write JSON files (or JSON strings). Parsed data is converted to Python objects and vice versa.</p> <p>To use the <code>json</code> library, simply import it:</p> <pre><cod...
1
2016-07-06T19:43:29Z
[ "python", "json" ]
Can I replace part of a string in a JSON key in Python?
38,232,051
<p>This is my first question here, I'm new to python and trying to figure some things out to set up an automatic 3D model processing chain that relies on data being stored in JSON files moving from one server to another.</p> <p>The problem is that I need to store absolute paths to files that are being processed, but t...
3
2016-07-06T19:15:16Z
38,232,550
<p><code>.replace</code> returns a new string, and don't change it. But you should not treat json-files as normal text files, so you can combine parsing json with replace:</p> <pre><code>def processscan(scanfile): configfile= MonitorDirectory + scanfile with open(configfile, 'rb') as settingsData: sett...
1
2016-07-06T19:47:13Z
[ "python", "json" ]
How do I put a QComboBox inside QColumnView
38,232,231
<p><strong>Scenario:</strong> I need to put a combo box inside the 4th column in qcolumnview, so the user can choose ON or OFF. </p> <p><strong>Description:</strong> In the future this will be saved as an XML file, so the user can select the parameter and generate a custom XML file. Can someone tell me how do I do tha...
2
2016-07-06T19:27:20Z
38,897,002
<p>I could not find a solution for that but I found a workaround, so I'm posting hoping to help who has the same problem as me.</p> <p>Once I couldnt put the combobox in the QColumnView as I was trying, my workaround was to create a table filled with the comboboxes I wanted, and then setting this QTable as the preview...
1
2016-08-11T12:54:19Z
[ "python", "qt", "user-interface", "pyqt" ]
Why does my game crash in PYGAME every time I try to shoot
38,232,232
<p>I am making a 2 player fighting game and whenever I try and press "v" the, the key to shoot my game seems to crash and not work. I am new to pygame and I am learning as I go. Any help is appreciated. Thanks!</p> <pre><code>import pygame pygame.init() #Sets up 8 bit colours white = (255,255,255) black = (0,0,0) re...
-2
2016-07-06T19:27:21Z
38,232,318
<p>It looks like once isShooting is set to True, the program gets stuck in the while loop (while isShooting:). It seems like you need a condition in the while loop to set isShooting back to False if a certain conditions is met, for example, if the v key is released.</p>
0
2016-07-06T19:33:18Z
[ "python", "crash", "pygame" ]
Why does my game crash in PYGAME every time I try to shoot
38,232,232
<p>I am making a 2 player fighting game and whenever I try and press "v" the, the key to shoot my game seems to crash and not work. I am new to pygame and I am learning as I go. Any help is appreciated. Thanks!</p> <pre><code>import pygame pygame.init() #Sets up 8 bit colours white = (255,255,255) black = (0,0,0) re...
-2
2016-07-06T19:27:21Z
38,232,349
<p>Just get rid of the <code>while</code> loop. <code>while isShooting</code> should be removed. The player should shoot at most one time per game loop - any more than that and they won't be able to see the effects of them firing. Plus, you create an infinite loop. </p> <p>On another note, welcome to Stack Overflow! I...
0
2016-07-06T19:35:42Z
[ "python", "crash", "pygame" ]
Move to Gmail Archive - Python Imaplib
38,232,243
<p>I'm trying to write a script which moves a particular email to Archive after getting its text, however I've looked all over the place and tried plenty of solutions. My understanding is that when a message is archived, all of its labels are removed and it only appears in the All Mail folder. </p> <p>This is my curre...
0
2016-07-06T19:27:56Z
38,292,145
<p>The Delete flag is not the same as the Trash flag, so if you set Delete, it will move it to the archive by removing any excess labels </p> <pre><code>self.connection.store(msg_id, '+FLAGS', '\\Deleted') </code></pre>
0
2016-07-10T13:01:09Z
[ "python", "gmail", "imap", "imaplib" ]
Spark pivot one column but keep others intact
38,232,249
<p>Given the following dataframe, how do I pivot the max scores but aggregate the sum of plays?</p> <pre><code>from pyspark import SparkContext from pyspark.sql import HiveContext from pyspark.sql import functions as F from pyspark.sql import Window df = sqlContext.createDataFrame([ ("u1", "g1", 10, 0, 1), ("...
1
2016-07-06T19:28:24Z
38,232,467
<p>Here's a solution using <strong>join</strong>, which I'm hoping to avoid:</p> <p><strong>Sum dataframe</strong></p> <pre><code>df_sum = df.groupBy("UserID").agg(F.sum("Plays").alias("Plays")).alias("df_sum") df_sum.show() +------+-----+ |UserID|Plays| +------+-----+ | u1| 4| | u2| 1| +------+-----+ r...
0
2016-07-06T19:42:35Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql", "pyspark-sql" ]
Spark pivot one column but keep others intact
38,232,249
<p>Given the following dataframe, how do I pivot the max scores but aggregate the sum of plays?</p> <pre><code>from pyspark import SparkContext from pyspark.sql import HiveContext from pyspark.sql import functions as F from pyspark.sql import Window df = sqlContext.createDataFrame([ ("u1", "g1", 10, 0, 1), ("...
1
2016-07-06T19:28:24Z
38,232,893
<p>I don't think it is a real improvement but you can add total number of plays </p> <pre><code>... .select( F.col("*"), F.row_number().over(rowNumberWindow).alias("GameNumber"), F.sum("Plays").over(rowNumberWindow.orderBy()).alias("total_plays") ) ... </code></pre> <p>and use it later as a secondary grouping c...
1
2016-07-06T20:10:30Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql", "pyspark-sql" ]
Django model tries to auto-create a primary key field even though it is already specified
38,232,364
<p>It is stated in the Django documentation that each model requires a Primary Key. In my MySQL schema it is specified that for my table the primary key is made up of multiple columns. Using inspectdb to auto-generate the model creates the unique_together Meta information. </p> <pre><code>class Connections(models.Mode...
2
2016-07-06T19:36:36Z
38,263,392
<p><strong><em>tl;dr: Recreate the table or add the "id" field to the database manually.</em></strong></p> <p>I don't believe it's possible to create a primary key in all databases. For example when using SQLite, if I create a simplified version of your table, altering it to add a PK returns an error:</p> <pre><code>...
2
2016-07-08T09:35:18Z
[ "python", "mysql", "django", "rdms" ]
Selenium in Python: Selecting an Option
38,232,406
<p>I am having no luck selecting an option from a <code>&lt;select&gt;</code> using selenium. I have referenced <a href="http://sqa.stackexchange.com/questions/1355/what-is-the-correct-way-to-select-an-option-using-seleniums-python-webdriver">http://sqa.stackexchange.com/questions/1355/what-is-the-correct-way-to-selec...
1
2016-07-06T19:39:23Z
38,239,051
<p>If non of the work in your case you should try <code>.execute_script()</code> as below :-</p> <pre><code>select = driver.find_element_by_id("Dropdownlistrequests") driver.execute_script("var select = arguments[0]; for(var i = 0; i &lt; select.options.length; i++){ if(select.options[i].text == arguments[1]){ select...
0
2016-07-07T06:46:23Z
[ "python", "selenium", "firefox", "selenium-webdriver", "firefox-marionette" ]
pandas selection by callables
38,232,452
<p><strong>EDIT:</strong> Turns out my initial question was simply a versionitis issue. However, in the course of answering my initial question a few other questions were addressed, so I've reworded the questions and listed them below:</p> <ol> <li><p>I'm familiarizing myself with some pandas capabilities, namely <a h...
1
2016-07-06T19:41:40Z
38,232,599
<p>You can do what you want to do without the lambda function, as follows:</p> <pre><code>df1.loc[df1.A&gt;0,:] </code></pre> <p>Perhaps the docs are outdated.</p>
1
2016-07-06T19:50:40Z
[ "python", "python-3.x", "pandas" ]
pandas selection by callables
38,232,452
<p><strong>EDIT:</strong> Turns out my initial question was simply a versionitis issue. However, in the course of answering my initial question a few other questions were addressed, so I've reworded the questions and listed them below:</p> <ol> <li><p>I'm familiarizing myself with some pandas capabilities, namely <a h...
1
2016-07-06T19:41:40Z
38,232,812
<p>You have to restart <code>IDE</code>.</p> <p>Your another <a href="http://stackoverflow.com/questions/38232452/pandas-selection-keyerror/38232812#comment63886898_38232599">question</a>:</p> <p>Use <code>apply</code> with <code>len</code>:</p> <pre><code>import pandas as pd data = {'A': [(1,2), (1,2), (1,2), (1,2...
1
2016-07-06T20:04:42Z
[ "python", "python-3.x", "pandas" ]
Numpy: Replace every value in the array with the mean of its adjacent elements
38,232,497
<p>I have an ndarray, and I want to replace every value in the array with the mean of its adjacent elements. The code below can do the job, but it is super slow when I have 700 arrays all with shape (7000, 7000) , so I wonder if there are better ways to do it. Thanks!</p> <pre><code>a = np.array(([1,2,3,4,5,6,7,8,9],[...
4
2016-07-06T19:44:03Z
38,232,755
<p>Well, that's a <a href="https://en.wikipedia.org/wiki/Smoothing" rel="nofollow"><code>smoothing operation in image processing</code></a>, which can be achieved with <code>2D</code> convolution. You are working a bit differently on the near-boundary elements. So, if the boundary elements are let off for precision, yo...
8
2016-07-06T20:00:42Z
[ "python", "arrays", "numpy", "numpy-broadcasting" ]
Numpy: Replace every value in the array with the mean of its adjacent elements
38,232,497
<p>I have an ndarray, and I want to replace every value in the array with the mean of its adjacent elements. The code below can do the job, but it is super slow when I have 700 arrays all with shape (7000, 7000) , so I wonder if there are better ways to do it. Thanks!</p> <pre><code>a = np.array(([1,2,3,4,5,6,7,8,9],[...
4
2016-07-06T19:44:03Z
38,233,229
<p>Following the discussion with @Divakar, find bellow a comparison of different convolution methods present in scipy:</p> <pre><code>import numpy as np from scipy import signal, ndimage def conv2(A, size): return signal.convolve2d(A, np.ones((size, size)), mode='same') / float(size**2) def fftconv(A, size): ...
4
2016-07-06T20:30:29Z
[ "python", "arrays", "numpy", "numpy-broadcasting" ]
Not getting the Python Run option in PyDev perspective
38,232,517
<p>I just installed PyDev to run python scripts from eclipse. I have a Java project which has a python script that I want to run. I am in PyDev perspective (did the following: Windows -> Perspective -> Open PErspective -> Other -> Pydev -> Ok). But when I right click on the python script it doesn't show me the "Python ...
0
2016-07-06T19:45:13Z
38,249,938
<p>Maybe the issue is that you're not configuring the project as a PyDev project... See: <a href="http://www.pydev.org/manual_101_root.html" rel="nofollow">http://www.pydev.org/manual_101_root.html</a> for more details on how to configure a project.</p> <p>As a note, you should be using the "PyDev package explorer vie...
0
2016-07-07T15:49:00Z
[ "python", "eclipse", "pydev" ]
Xpath following siblings until another sibling
38,232,560
<p>I'm new to using Xpath. I'm trying to parse some data in Python using Xpath.</p> <p>Parsing the following HTML:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td class="DT"&gt;29-04-14&lt;/td&gt; &lt;td class="Regio"&gt;Text&lt;/td&gt; &lt;td class="Md"&gt;Text&lt;/td&gt; &lt;/tr&gt; ...
1
2016-07-06T19:47:42Z
38,241,458
<p>I may be misinterpreting the question, but if, for each <code>&lt;tr&gt;&lt;td class="DT"&gt;xx-xx-xx&lt;/td&gt;</code>, you want all <code>&lt;tr&gt;</code> after it, and before the next <code>&lt;tr&gt;&lt;td class="DT"&gt;xx-xx-xx&lt;/td&gt;</code>, one pattern is to loop on these "boundary" <code>&lt;tr&gt;&lt;t...
0
2016-07-07T09:05:05Z
[ "python", "xpath" ]
How to grab raw all raw html within a certain XPath from a local file in Python
38,232,584
<p>I am trying to grab the raw html from a bunch of local html files. I had some help from this post in getting the raw file to read in:</p> <p><a href="http://stackoverflow.com/questions/4624062/get-all-text-inside-a-tag-in-lxml">Get all text inside a tag lxml</a></p> <p>But the code I have currently produces the en...
1
2016-07-06T19:49:24Z
38,234,219
<p>You could try using BeautifulSoup. I'm not real versed in it, but you can do something like this (or cleaner, if you read up on BeautifulSoup :)</p> <pre><code>from bs4 import BeautifulSoup soup = BeautifulSoup(open("input.html"), 'html') x = soup.find_all(class_="main-content") for line in x[0].contents: print...
-1
2016-07-06T21:38:46Z
[ "python", "lxml", "lxml.html" ]
How to grab raw all raw html within a certain XPath from a local file in Python
38,232,584
<p>I am trying to grab the raw html from a bunch of local html files. I had some help from this post in getting the raw file to read in:</p> <p><a href="http://stackoverflow.com/questions/4624062/get-all-text-inside-a-tag-in-lxml">Get all text inside a tag lxml</a></p> <p>But the code I have currently produces the en...
1
2016-07-06T19:49:24Z
38,234,693
<p>Using lxml:</p> <pre><code>from lxml import html xm = html.fromstring(h) div = xm.xpath("//div[@class='main-content']")[0] print(div.text + "".join(map(html.tostring, div.xpath("./*")))) </code></pre> <p>Or:</p> <pre><code>from lxml import html xm = html.fromstring(h) eles = xm.xpath("//div[@class='main-conte...
0
2016-07-06T22:15:36Z
[ "python", "lxml", "lxml.html" ]
Location of Objects - Python
38,232,743
<p>When I executed the following code, i got value A. When I executed it again, I got value B. Why is that. Shouldn't it have produced the same result?</p> <p><strong>Code</strong></p> <pre><code>list_a = ['one_A', 'two_A', 'three_A'] #initialize the list new_li = map(lambda i: '{0}\n'.format(i), list_a) print(ne...
-2
2016-07-06T19:59:51Z
38,232,796
<p>In python, when you assign a variable to a value, it stores the value in a memory location, and then creates a reference to that object. As a result, your variable is just a reference. So, if you assign a new value to the variable, it does not overwrite that memory location with the new value, but rather creates a ...
2
2016-07-06T20:03:35Z
[ "python", "python-2.7", "python-3.x", "oop", "memory-management" ]
WARNING:tensorflow:create_partitioned_variables is deprecated
38,232,834
<p>I'm getting this <code>WARNING</code></p> <blockquote> <p>WARNING:tensorflow:create_partitioned_variables is deprecated. Use tf.get_variable with a partitioner set, or tf.get_partitioned_variable_list, instead.</p> </blockquote> <p>I'm not using the function <code>create_partitioned_variables</code></p> <p>I'm...
4
2016-07-06T20:06:12Z
38,702,578
<p>Basically <code>sparse_column_with_keys</code> is using <code>create_partitioned_variables()</code> for its initialization, however, within the <code>create_partitioned_variables()</code> class, they throw a warning that is basically saying that <code>create_partitioned_variables()</code> is not the accepted way of ...
1
2016-08-01T15:24:10Z
[ "python", "tensorflow" ]
Convert a Python list of lists to a string
38,232,838
<p>How can I best convert a list of lists in Python to a (for example) comma-delimited-value, newline-delimited-row, string? Ideally, I'd be able to do something like this:</p> <pre><code>&gt;import csv &gt;matrix = [["Frodo","Baggins","Hole-in-the-Ground, Shire"],["Sauron", "I forget", "Mordor"]] &gt; csv_string = c...
-1
2016-07-06T20:06:31Z
38,233,075
<p>The approach in the <a href="http://stackoverflow.com/questions/44778/how-would-you-make-a-comma-separated-string-from-a-list">question</a> you link to as a reference for <code>join</code>, together with a nested <code>join</code>s (what's wrong with that?) works as long as you can convert all of the objects contain...
1
2016-07-06T20:21:31Z
[ "python", "python-2.7", "csv", "stringio" ]
Convert a Python list of lists to a string
38,232,838
<p>How can I best convert a list of lists in Python to a (for example) comma-delimited-value, newline-delimited-row, string? Ideally, I'd be able to do something like this:</p> <pre><code>&gt;import csv &gt;matrix = [["Frodo","Baggins","Hole-in-the-Ground, Shire"],["Sauron", "I forget", "Mordor"]] &gt; csv_string = c...
-1
2016-07-06T20:06:31Z
38,233,192
<p>Combine the csv-module with <code>StringIO</code>:</p> <pre><code>import io, csv result = io.StringIO() writer = csv.writer(result) writer.writerow([5,6,7]) print(result.getvalue()) </code></pre>
3
2016-07-06T20:28:10Z
[ "python", "python-2.7", "csv", "stringio" ]
2D Shadow Effect - Points on circle
38,232,929
<p>I am currently trying to implement flat shadow effects to a 2D game that i have written in Python. I have found a great deal of tutorials and methods of doing this online (<a href="http://ncase.me/sight-and-light/" rel="nofollow">http://ncase.me/sight-and-light/</a>) however, these all use polygons as the obstructio...
0
2016-07-06T20:13:03Z
38,233,883
<p>The trick is to notice what is happening at point P. At point P, the line AP is tangent to the circle so in other words the angle APO is 90 degrees. Likewise AQO is 90 degrees.</p> <p>Now we know that we have a triangle, we know 2 of the lengths and one of the angles (We know AO, OP / OQ (Same thing), and APO / A...
1
2016-07-06T21:15:03Z
[ "python", "geometry", "2d", "trigonometry", "shadows" ]
2D Shadow Effect - Points on circle
38,232,929
<p>I am currently trying to implement flat shadow effects to a 2D game that i have written in Python. I have found a great deal of tutorials and methods of doing this online (<a href="http://ncase.me/sight-and-light/" rel="nofollow">http://ncase.me/sight-and-light/</a>) however, these all use polygons as the obstructio...
0
2016-07-06T20:13:03Z
38,238,977
<p>Let's vector V = OP (unknown), vector Q = AP, vector U = AO (known)<br> Note that Q = U + V</p> <p>Vector V length is radius R, so</p> <pre><code>VX^2 + VY^2 = R^2 //1 </code></pre> <p>Vectors V and A are perpendicular, so their scalar product is zero</p> <pre><code>VX * QX + VY * QY = 0 VX * (VX + UX) + VY * ...
0
2016-07-07T06:41:50Z
[ "python", "geometry", "2d", "trigonometry", "shadows" ]
ANN_MLP() not working with Opencv 3.1.0 Dev (python)
38,232,934
<p>I have been working on Neural Networks Using OpenCV </p> <p>From the documentation I have learned that instead of <em>cv2.ANN_MLP</em> </p> <p>We have to use <em>cv2.ml.ANN_MLP_create()</em></p> <p>But what I don't get is how do I give the layer size? </p> <p>Here is the code </p> <pre><code>import cv2 import n...
0
2016-07-06T20:13:14Z
39,051,454
<p>The first thing you can do is edit your post and specify the error you get. Here are two hints nonetheless:</p> <ol> <li>There is a typo in the last line: <em>nerual</em> instead of <em>neural</em>.</li> <li><a href="http://stackoverflow.com/a/39051837/777285">This answer</a> might help with setting the number of ...
0
2016-08-20T07:02:50Z
[ "python", "opencv", "machine-learning", "neural-network" ]
Python array manipulation from psycopg2 PostgreSQL query
38,232,983
<p>I am using psycopg2 to do a psql query. </p> <pre><code>cur.execute("SELECT DISTINCT name FROM product") result = cur.fetchall() print(result) [('product1',), ('product2',), ('product3',), ('product4',)] </code></pre> <p>I need to reformat this array to make an API endpoint. Right now it is a list of tuples where...
1
2016-07-06T20:15:57Z
38,233,107
<p>Aggregate in the query:</p> <pre><code>query = ''' select array_agg(distinct name) from product ''' cursor.execute(query) rs = cursor.fetchall()[0][0] print rs </code></pre> <p>Output:</p> <pre><code>['product1', 'product2', 'product3', 'product4'] </code></pre>
1
2016-07-06T20:23:28Z
[ "python", "postgresql", "list", "psycopg2" ]
Python array manipulation from psycopg2 PostgreSQL query
38,232,983
<p>I am using psycopg2 to do a psql query. </p> <pre><code>cur.execute("SELECT DISTINCT name FROM product") result = cur.fetchall() print(result) [('product1',), ('product2',), ('product3',), ('product4',)] </code></pre> <p>I need to reformat this array to make an API endpoint. Right now it is a list of tuples where...
1
2016-07-06T20:15:57Z
38,233,109
<p>The time needed to convert the list is negligible compared to the database query. But you don't need to create a list first-hand:</p> <pre><code>cur.execute("SELECT DISTINCT name FROM product") result = [item for item, in cur] print(result) </code></pre>
1
2016-07-06T20:23:36Z
[ "python", "postgresql", "list", "psycopg2" ]
Pycharm Cant locate cPickle on six
38,233,014
<p>I'm doing the udacity course on deep neural networks and I'm trying to do the assignment related to notMNIST. I installed tensorflow and six in a virtualenv and then made Pycharm recognise this virtualenv as my project interpreter.</p> <p>Tensorflow commands can now be run but in this import section:</p> <pre><cod...
0
2016-07-06T20:17:36Z
38,295,288
<p>Pycharm has trouble with resolving names when dynamic dispatch is in play, and their tooltips on such errors say as much. While six manages to map functions to their correct py2 and py3 versions, it does so using dynamic dispatch. </p> <p>I'm not sure if the problem is a theoretical one or just an issue with the py...
0
2016-07-10T18:41:06Z
[ "python", "python-2.7", "pycharm", "tensorflow" ]
Pandas: read file with special characters in a column
38,233,046
<p>In the data that I have, some feature values are <code>?</code>. How do I replace them with <code>NA</code>? </p> <p><strong>EDIT</strong></p> <p>The code and output is as below:</p> <pre><code>df = pd.read_csv("cca-census-income.csv", header = None) df.replace('?', np.nan, inplace=True) df.ix[0,] 23 ...
3
2016-07-06T20:19:50Z
38,233,073
<p>Add parameter <code>na_values='?'</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>.</p> <p>Sample:</p> <pre><code>import pandas as pd import io temp=u"""Date Time,a 2010-01-27 16:00:00,? 2010-01-27 16:10:00,2.2 2010-01-27 16:3...
3
2016-07-06T20:21:28Z
[ "python", "python-2.7", "numpy", "pandas" ]
Pandas: read file with special characters in a column
38,233,046
<p>In the data that I have, some feature values are <code>?</code>. How do I replace them with <code>NA</code>? </p> <p><strong>EDIT</strong></p> <p>The code and output is as below:</p> <pre><code>df = pd.read_csv("cca-census-income.csv", header = None) df.replace('?', np.nan, inplace=True) df.ix[0,] 23 ...
3
2016-07-06T20:19:50Z
38,233,461
<p>after reading the file use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow">replace</a> :</p> <pre><code>df.repalce('.?',np.nan,inplace=True,regex=True) </code></pre>
1
2016-07-06T20:43:59Z
[ "python", "python-2.7", "numpy", "pandas" ]
How can I complete following GRU based RNN written in tensorflow?
38,233,056
<p>So far I have written following code:</p> <pre><code>import pickle import numpy as np import pandas as pd import tensorflow as tf # load pickled objects (x and y) x_input, y_actual = pickle.load(open('sample_input.pickle', 'rb')) x_input = np.reshape(x_input, (50, 1)) y_actual = np.reshape(y_actual, (50, 1)) # pa...
-1
2016-07-06T20:20:24Z
38,233,213
<p><code>tf.initialize_all_variables()</code> gets the "current" set of variables from the graph. Since you are creating <code>softmax_w</code> and <code>softmax_b</code> after your call to <code>tf.initialize_all_variables()</code>, they are not in the list that <code>tf.initialize_all_variables()</code> consults, and...
1
2016-07-06T20:29:33Z
[ "python", "tensorflow", "recurrent-neural-network", "gated-recurrent-unit" ]
NLTK Most common synonym (Wordnet) for each word
38,233,145
<p>Is there a way to find the most common synonym of a word with NLTK? I would like to simplify a sentence using the most common synonyms of each word on it. </p> <p>If a word used in the sentence is already the most common word from its group of synonyms, it shouldn't be changed. </p> <p>Let's say "Hi" is more commo...
3
2016-07-06T20:26:01Z
38,233,647
<p>Synonyms are a huge and open area of work in natural language processing. </p> <p>In your example, how is the program supposed to know what the allowed synonyms are? One method might be to keep a dictionary of sets of synonyms for each word. However, this can run into problems due to overlaps in <strong>parts of...
3
2016-07-06T20:56:54Z
[ "python", "python-2.7", "python-3.x", "nltk" ]
NLTK Most common synonym (Wordnet) for each word
38,233,145
<p>Is there a way to find the most common synonym of a word with NLTK? I would like to simplify a sentence using the most common synonyms of each word on it. </p> <p>If a word used in the sentence is already the most common word from its group of synonyms, it shouldn't be changed. </p> <p>Let's say "Hi" is more commo...
3
2016-07-06T20:26:01Z
38,234,243
<p>The other answer shows you how to use synonyms:</p> <blockquote> <pre><code>wn.synsets('small') [Synset('small.n.01'), Synset('small.n.02'), Synset('small.a.01'), Synset('minor.s.10'), Synset('little.s.03'), Synset('small.s.04'), Synset('humble.s.01'), Synset('little.s.07'), Synset('little.s.05'), Synset('...
1
2016-07-06T21:40:34Z
[ "python", "python-2.7", "python-3.x", "nltk" ]
NLTK Most common synonym (Wordnet) for each word
38,233,145
<p>Is there a way to find the most common synonym of a word with NLTK? I would like to simplify a sentence using the most common synonyms of each word on it. </p> <p>If a word used in the sentence is already the most common word from its group of synonyms, it shouldn't be changed. </p> <p>Let's say "Hi" is more commo...
3
2016-07-06T20:26:01Z
38,234,480
<p>Synonyms are tricky, but if you are starting out with a synset from Wordnet and you simply want to choose the most common member in the set, it's pretty straightforward: Just build your own frequency list from a corpus, and look up each member of the synset to pick the maximum.</p> <p>The nltk will let you build a ...
1
2016-07-06T21:59:00Z
[ "python", "python-2.7", "python-3.x", "nltk" ]
Python - Multithreads for calling the same function to run in parallel and independently
38,233,184
<p>I'm new in Python and I'm struggling a lot trying to solve a problem. I have three programs running. One of them has the objective to send data, the other to receive and the third one works in the middle (transparently). The difficulty is happening with this third one, which I'm calling delay_loss.py.</p> <p>It has...
0
2016-07-06T20:27:55Z
38,236,147
<p>I have found a solution to my problem. I was using the pool without necessity. It is much simpler to just use the threading.Timer() function, as shown below:</p> <pre><code>t = threading.Timer(time_delay, send_up, [pkt_recv_raw, id_pkt]) t.start() </code></pre>
0
2016-07-07T01:02:54Z
[ "python", "multithreading" ]
Efficient data structure for storing timestamp data & calculating in a rolling window
38,233,189
<p>I have a large Twitter data stream, and I am interested in analyzing the relationships of hashtags in each tweet. For example, if hashtag A and hashtag B appear in the same tweet, I would record this tweet as "A-B" together with the timestamp of the tweet. </p> <p>As such, sample inputs are:</p> <pre class="lang-b...
1
2016-07-06T20:28:07Z
38,233,799
<p>The tweets can be expected to be mostly sorted, so a sequence type with <a href="http://stackoverflow.com/q/220044/699305">insertion sort</a> should be a good way to get them ordered. Add a rolling window to replace the oldest ones after you reach 24 hours.</p> <p>For efficient insertions, you'll want a sequence ty...
1
2016-07-06T21:08:38Z
[ "python", "data-structures", "moving-average" ]
Efficient data structure for storing timestamp data & calculating in a rolling window
38,233,189
<p>I have a large Twitter data stream, and I am interested in analyzing the relationships of hashtags in each tweet. For example, if hashtag A and hashtag B appear in the same tweet, I would record this tweet as "A-B" together with the timestamp of the tweet. </p> <p>As such, sample inputs are:</p> <pre class="lang-b...
1
2016-07-06T20:28:07Z
38,233,950
<p>I would use pandas. Here is an example implementation which sorts out timestamps based on a window. You would need to copy your data into a dataframe first.</p> <pre><code>import pandas as pd import datetime import dateutil.relativedelta days_back = 1 datetimeFormat = '%Y-%m-%d %H:%M:%S' dt_now = datetime.datetime...
1
2016-07-06T21:19:52Z
[ "python", "data-structures", "moving-average" ]
Two foreign key in the same model from two different model
38,233,230
<p>I need to put two Foreign Keys in a model class from two different models. I would like to relate the third model class to the first and the second. </p> <p>I've tried something like this:</p> <pre><code>class A (models.Model) id_A = models.IntergerField (primary_key=True) #... class B (models.Model) ...
0
2016-07-06T20:30:33Z
38,233,872
<p>Django didn't pop up error because you were doing it right. It's totally reasonable that there are multiple foreign keys in one model, just like class C.</p> <p>In class C, as long as id_A and id_B is the single column primary keys of their own model, it will perfectly work out.</p> <p>"MultipleColumnPrimaryKeys" ...
0
2016-07-06T21:13:53Z
[ "python", "django", "django-models" ]
Two foreign key in the same model from two different model
38,233,230
<p>I need to put two Foreign Keys in a model class from two different models. I would like to relate the third model class to the first and the second. </p> <p>I've tried something like this:</p> <pre><code>class A (models.Model) id_A = models.IntergerField (primary_key=True) #... class B (models.Model) ...
0
2016-07-06T20:30:33Z
38,234,088
<p>You are doing it well, if you were relating id_A and id_B to a same model, django would give you an error, in this case just put <code>related_name</code> attribute in the second field.</p>
1
2016-07-06T21:29:55Z
[ "python", "django", "django-models" ]
Two foreign key in the same model from two different model
38,233,230
<p>I need to put two Foreign Keys in a model class from two different models. I would like to relate the third model class to the first and the second. </p> <p>I've tried something like this:</p> <pre><code>class A (models.Model) id_A = models.IntergerField (primary_key=True) #... class B (models.Model) ...
0
2016-07-06T20:30:33Z
38,234,126
<p>You can use a many-to-many relationship that automatically creates that intermediate model for you:</p> <pre><code>from django.db import models class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publicatio...
0
2016-07-06T21:32:16Z
[ "python", "django", "django-models" ]
Giving a model knowledge of a many-to-many related model in django
38,233,245
<p>EDIT: Given responses in comments and answer I tried suggestion and I get some errors when trying to query , also doing the related name query does not get the right results (as seen in comments)</p> <p>BusinessLocations.objects.all() </p> <p><code>Error: QuerySet object has no attribute 'objects' is the error.</...
1
2016-07-06T20:31:12Z
38,234,987
<p>What you're missing is Django's concept of <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#related-objects" rel="nofollow">related objects</a>. </p> <blockquote> <p>When you define a relationship in a model (i.e., a <code>ForeignKey</code>, <code>OneToOneField</code>, or <code>ManyToManyField</c...
1
2016-07-06T22:44:04Z
[ "python", "django", "django-models" ]
TypeError: string indices must be integers, not str, which part it refers to?
38,233,320
<p>I am a total beginner of python, may bring some basic questions here. Could someone please help?</p> <p>I want to get the average for each student and then calculate the average of those averages. Get "TypeError: string indices must be integers, not str". Cannot figure out what it referring to and how to modify. He...
1
2016-07-06T20:35:49Z
38,233,365
<p>When you enclose a name in quotes, it is a string literal, not a variable.</p> <pre><code>&gt;&gt;&gt; x = 3 &gt;&gt;&gt; x 3 &gt;&gt;&gt; 'x' 'x' </code></pre> <p>Use <code>students = [lloyd, alice, tyler]</code> to refer to the variables you defined above.</p>
6
2016-07-06T20:38:16Z
[ "python", "list", "dictionary" ]
Tkinter widget layout is wrong?
38,233,348
<p>I've been putting a menu together using Tkinter with Python 2.7. It works functionally, but the layout is very messy. I'm usng the .grid() method to organise the widgets, but they are interfering with each other, so my listbox widget is taller than the buttons so they get spaced apart etc. What can I do to resolve t...
1
2016-07-06T20:37:35Z
38,233,634
<p>You can tell the grid to let (force) a widget to take up multiple rows/columns with the <code>columnspan</code> argument to <code>grid()</code>, i.e.:</p> <pre><code>... list_box.grid(row=1, column=3, rowspan=3) ... </code></pre> <p>That will tell your <code>list_box</code> to cover (up to) three rows (if there's ...
2
2016-07-06T20:56:11Z
[ "python", "tkinter" ]
ipython on readonly filesystem: "No usable temporary directory found"
38,233,364
<p>if I start IPython on a readonly filesystem it always crashes with:</p> <pre><code> File "/usr/lib/python2.7/tempfile.py", line 217, in _get_default_tempdir ("No usable temporary directory found in %s" % dirlist)) IOError: [Errno 2] No usable temporary directory found in ['/tmp', '/var/tmp', </code></pre> <p>...
0
2016-07-06T20:38:15Z
38,237,798
<p>I am looking at the <code>ipython</code> config file to see if there's anything about automatic writing and how to turn it off.</p> <p>One that thing it does, by default, is write a <code>history.sqlite</code> file. </p> <p>Setting:</p> <pre><code>c.HistoryManager.enabled = False </code></pre> <p>might turn tha...
0
2016-07-07T04:57:35Z
[ "python", "directory", "ipython", "readonly", "temporary" ]
Possible to run Stored Procedure using documentDB SDK for Python?
38,233,391
<p>I'm using Tornado and pydocumentDB to run a storage application on Azure. I also have a stored procedure: </p> <pre><code>function userIDSproc() { var collection = getContext().getCollection(); // Query documents and take 1st item. var isAccepted = collection.queryDocuments( collection.getSelfL...
0
2016-07-06T20:39:31Z
38,234,035
<p>For the DocumentDB Python SDK, you can call <code>ExecuteStoredProcedure(self, sproc_link, params, options=None)</code>.</p> <p>You can find a short example in the SDK's unit tests here:</p> <p><a href="https://github.com/Azure/azure-documentdb-python/blob/e605e7ca7b1ddd2454f1014f536a0fded9e6f234/test/crud_tests.p...
0
2016-07-06T21:25:22Z
[ "python", "azure", "stored-procedures", "azure-documentdb" ]
How do I promote PostgreSQL warnings to exceptions in psycopg2?
38,233,400
<p>From the PostgreSQL <a href="https://www.postgresql.org/docs/9.5/static/sql-begin.html">docs</a> on <code>BEGIN</code>:</p> <blockquote> <p>Issuing BEGIN when already inside a transaction block will provoke a warning message. The state of the transaction is not affected.</p> </blockquote> <p>How can I make <co...
5
2016-07-06T20:40:03Z
38,233,977
<p>I am very far from being <code>psycopg2</code> or <code>Postgres</code> expert, and, I am sure there is a better solution to increase the warning level, but here is something that worked for me - <a href="http://initd.org/psycopg/docs/advanced.html#subclassing-connection" rel="nofollow">a custom cursor</a> which loo...
2
2016-07-06T21:21:26Z
[ "python", "postgresql", "warnings", "psycopg2" ]
Can PyDev Predefined definitions be case-insensitive?
38,233,473
<p>I'm using PyDev predefined completions, and I'd like the defined methods to be case-insensitive. Even though python method names are case-sensitive, the predefs I'm implementing represent wrapper methods which delegate to a library which is not case-sensitive. So I'd like for developers to be able to enter lowercase...
0
2016-07-06T20:44:24Z
38,249,828
<p>Adding one entry for the upper case and another for the lower case <strong>should</strong> work, so, if that's not working for you, please report this as a bug in <a href="https://sw-brainwy.rhcloud.com/tracker/PyDev" rel="nofollow">https://sw-brainwy.rhcloud.com/tracker/PyDev</a></p>
0
2016-07-07T15:44:05Z
[ "python", "eclipse-rcp", "pydev" ]
dynamodb FilterExpression returns unexpected data
38,233,502
<p>I am doing FilterExpression with boto3 library and looking for a username in a table that has 4 entries in that table. FilterExpression is returning only 1 record and LastEvaluationKey with unique_id in it. When I pass that unique_id to get more values for that user, I get different data set. </p> <pre><code>def la...
1
2016-07-06T20:46:21Z
38,234,247
<p>So, if I recursively pass the username and "LastEvaluatedKey" to the function, it returns all the data and then by chaining, I can get the complete list.</p>
0
2016-07-06T21:41:04Z
[ "python", "amazon-dynamodb", "boto3" ]
Selecting rows from sparse dataframe by index position
38,233,504
<p>In a typical python dataframe, it's easy to select desired rows based on index:</p> <pre><code>df.ix[list_of_inds] or df.loc[list_of_inds] </code></pre> <p>However, using this method to take a substantial subset of a large, sparse dataframe (73,000 rows, 8,000 columns specifically) seems to be extremely intensive ...
2
2016-07-06T20:46:30Z
38,241,810
<p>The issue you are facing could be related to view vs copy semantics. </p> <pre><code>df.ix[1:N] # uses slicing =&gt; operates on a view df.ix[np.arange(1,N)] # uses fancy indexing =&gt; "probably" creates a copy first </code></pre> <p>I created a DataFrame on my machine of shape 73000x8000 and my m...
0
2016-07-07T09:22:21Z
[ "python", "numpy", "pandas", "scipy", "sparse-matrix" ]
Pickle File Import Error
38,233,515
<p>I have been trying to load a Python pickle file using the following Python function: </p> <pre><code>import os import cPickle as pickle def load_var(var_name): fid = open(var_name + '.pkl', 'rb') data = pickle.load(fid) fid.close() return data </code></pre> <p>but I keep on running into the follo...
0
2016-07-06T20:47:13Z
38,233,851
<p>Pickle files don't actually store class or module definitions. They only store attribute values. The benefit to this is that you can pickle out an object, update the class definition in your source code, then read in the pickled data and it will use the new class definition instead of having two different versions...
1
2016-07-06T21:12:29Z
[ "python", "pickle", "importerror" ]
Download a full page with scrapy
38,233,614
<p>I want to download the content a whole page using scrapy. </p> <p>With selenium this is quite easy:</p> <pre><code>import os,sys reload(sys) sys.setdefaultencoding('utf8') from selenium import webdriver url = 'https://es.wikipedia.org/wiki/Python' driver = webdriver.Firefox() driver.get(url) content = driver....
0
2016-07-06T20:54:35Z
38,234,394
<p>Code will download this page and save it in file <code>download-a-full-page-with-scrapy.html</code></p> <p>test_scr.py</p> <pre><code>import scrapy class TestSpider(scrapy.Spider): name = "test" start_urls = [ "http://stackoverflow.com/questions/38233614/download-a-full-page-with-scrapy", ] ...
1
2016-07-06T21:52:10Z
[ "python", "web-scraping", "scrapy" ]
set null to None in Python, is it a good practice?
38,233,661
<p>Very often when I deal with input/output that are generated from different languages, I often have to deal with the null values when I get those input/output into Python. As we all know <code>None</code> is the keyword for Python instead of <code>null</code>, so it often creates error when, say, the <code>null</code...
-1
2016-07-06T20:57:46Z
38,233,764
<p>This is not a good idea. It indicates some fuzziness in your program, a blurring of the line between code and input.</p> <p>Any code you write should use <code>None</code>, not a variable set to <code>None</code>. Having a <code>null</code> constant wouldn't help because you could simply write <code>None</code>.</p...
10
2016-07-06T21:05:32Z
[ "python", null ]
set null to None in Python, is it a good practice?
38,233,661
<p>Very often when I deal with input/output that are generated from different languages, I often have to deal with the null values when I get those input/output into Python. As we all know <code>None</code> is the keyword for Python instead of <code>null</code>, so it often creates error when, say, the <code>null</code...
-1
2016-07-06T20:57:46Z
38,233,778
<p>You're losing the advantages of <code>None</code>. Try this:</p> <pre><code>None = "Hello" </code></pre> <p>It doesn't work (<code>SyntaxError</code>) because assignment to <code>None</code> is prohibited. Creating an extra variable, <code>null</code>, introduces the <em>possibility</em> that <code>null is not N...
5
2016-07-06T21:07:22Z
[ "python", null ]
set null to None in Python, is it a good practice?
38,233,661
<p>Very often when I deal with input/output that are generated from different languages, I often have to deal with the null values when I get those input/output into Python. As we all know <code>None</code> is the keyword for Python instead of <code>null</code>, so it often creates error when, say, the <code>null</code...
-1
2016-07-06T20:57:46Z
38,233,816
<p>I'm imagining you could receive input as a string <code>'null'</code>. However, this would be a string and not a key word. You'd be free to parse and deal with it as you saw fit. The only way I can imagine using <code>null = None</code> would do anything is if you were trying to evaluate strings as python code li...
1
2016-07-06T21:10:24Z
[ "python", null ]
django password_change noreversematch
38,233,663
<p>I'm new to Django, and I'm trying add user authentication to a simple app. I'm working with Django 1.9, and I'm trying to do this a simply as possible. Login and Logout work, but with "Change Password", I get a NoReverseMatch error for password_change_done.</p> <p>From my urls.py</p> <pre><code>app_name = 'leagu...
0
2016-07-06T20:57:48Z
38,234,318
<p>The <code>password_change</code> view <a href="https://github.com/django/django/blob/master/django/contrib/auth/views.py#L346" rel="nofollow">does not use</a> the <code>current_app</code> parameter to determine the redirect url. You need to explicitly pass the view name including the namespace:</p> <pre><code>url(r...
0
2016-07-06T21:46:15Z
[ "python", "django", "authentication", "passwords" ]
Reading random rows of a large csv file, python, pandas
38,233,719
<p>could you help me, I faced a problem of reading random rows from the large csv file using 0.18.1 pandas and 2.7.10 Python on Windows (8 Gb RAM).</p> <p>In <a href="http://stackoverflow.com/questions/22258491/read-a-small-random-sample-from-a-big-csv-file-into-a-python-data-frame">Read a small random sample from a b...
1
2016-07-06T21:02:21Z
38,234,137
<p>If memory is the biggest issue, a possible solution might be to use chunks, and randomly select from the chunks</p> <pre><code>n = 100 s = 10 factor = 1 # should be integer chunksize = int(s/factor) reader = pd.read_csv(path, usecols = ['Col1', 'Col2'],dtype = {'Col1': 'int32', 'Col2':'int32'}, chunksize=chunk...
0
2016-07-06T21:33:07Z
[ "python", "csv", "pandas", "large-files", "large-data" ]
Reading random rows of a large csv file, python, pandas
38,233,719
<p>could you help me, I faced a problem of reading random rows from the large csv file using 0.18.1 pandas and 2.7.10 Python on Windows (8 Gb RAM).</p> <p>In <a href="http://stackoverflow.com/questions/22258491/read-a-small-random-sample-from-a-big-csv-file-into-a-python-data-frame">Read a small random sample from a b...
1
2016-07-06T21:02:21Z
38,235,952
<p>I think this is faster than other methods showed here and may be worth trying.</p> <p>Say, we have already chosen rows to be skipped in a list <code>skipped</code>. First, I convert it to a lookup bool table.</p> <pre><code># Some preparation: skipped = np.asarray(skipped) # MAX &gt;= number of rows in the file bo...
0
2016-07-07T00:33:24Z
[ "python", "csv", "pandas", "large-files", "large-data" ]
sqlalchemy error: object() takes no parameters error after dropping column from db model.py
38,233,748
<p>I get the following error <code>typeerror: object() takes no parameters</code> on a mysql command which doesn't make sense to me. The error is due to dropping the username column from my models.py which I no longer require</p> <p><a href="http://i.stack.imgur.com/PpPms.png" rel="nofollow"><img src="http://i.stack....
0
2016-07-06T21:04:45Z
38,233,951
<p>The error is not due to removing a column, it originates from the line</p> <pre><code>Column('id', INTEGER(display_width=11), primary_key=True, nullable=False), </code></pre> <p>which the traceback clearly indicates.</p> <p><a href="http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.INTEG...
0
2016-07-06T21:19:53Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy", "sqlalchemy-migrate" ]
sqlalchemy error: object() takes no parameters error after dropping column from db model.py
38,233,748
<p>I get the following error <code>typeerror: object() takes no parameters</code> on a mysql command which doesn't make sense to me. The error is due to dropping the username column from my models.py which I no longer require</p> <p><a href="http://i.stack.imgur.com/PpPms.png" rel="nofollow"><img src="http://i.stack....
0
2016-07-06T21:04:45Z
38,233,959
<p>I think you are using the wrong data types for Column definition, here are the right ones:</p> <pre><code>from sqlalchemy import (MetaData, Table, Column, Integer, String) user = Table('user', pre_meta, Column('id', Integer, primary_key=True, nullable=False), Column('username', String(32)), Column('ema...
1
2016-07-06T21:20:12Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy", "sqlalchemy-migrate" ]
Random access over all pair-wise combinations of large list in Python
38,233,761
<p><strong>Background:</strong></p> <p>I have a list of 44906 items: <code>large = [1, 60, 17, ...]</code>. I also have a personal computer with limited memory (8GB), running Ubuntu 14.04.4 LTS.</p> <p><strong>The Goal:</strong></p> <p>I need to find all the pair-wise combinations of <code>large</code> in a memory-e...
4
2016-07-06T21:05:22Z
38,233,850
<p>Except <code>itertools.combinations</code> does not return a list - it returns an iterator. Here:</p> <pre><code>&gt;&gt;&gt; from itertools import combinations &gt;&gt;&gt; it = combinations([1, 2, 3, 4, 5], 2) &gt;&gt;&gt; next(it) (1, 2) &gt;&gt;&gt; next(it) (1, 3) &gt;&gt;&gt; next(it) (1, 4) &gt;&gt;&gt; nex...
6
2016-07-06T21:12:29Z
[ "python", "list", "combinations", "combinatorics", "large-data" ]
Random access over all pair-wise combinations of large list in Python
38,233,761
<p><strong>Background:</strong></p> <p>I have a list of 44906 items: <code>large = [1, 60, 17, ...]</code>. I also have a personal computer with limited memory (8GB), running Ubuntu 14.04.4 LTS.</p> <p><strong>The Goal:</strong></p> <p>I need to find all the pair-wise combinations of <code>large</code> in a memory-e...
4
2016-07-06T21:05:22Z
38,233,931
<p>So you've got 44906 items. Notice, however, that if you build your combinations the same way you build them in the example then there are 44905 combinations with <code>large[0]</code> as the first number. Furthermore, combination <code>i</code> for <code>i &lt;= 44905</code> looks like <code>(large[0], large[i])</co...
1
2016-07-06T21:18:18Z
[ "python", "list", "combinations", "combinatorics", "large-data" ]
Random access over all pair-wise combinations of large list in Python
38,233,761
<p><strong>Background:</strong></p> <p>I have a list of 44906 items: <code>large = [1, 60, 17, ...]</code>. I also have a personal computer with limited memory (8GB), running Ubuntu 14.04.4 LTS.</p> <p><strong>The Goal:</strong></p> <p>I need to find all the pair-wise combinations of <code>large</code> in a memory-e...
4
2016-07-06T21:05:22Z
38,233,984
<p>For well defined order of created pairs, indices of first and second elements should be related to n and length of a sequence. If you'll find them, you'll be able to achieve const-time performance, since indexing lists is <code>O(1)</code> operation.</p> <p>Pseudocode would look like this:</p> <pre><code>def find_...
1
2016-07-06T21:21:47Z
[ "python", "list", "combinations", "combinatorics", "large-data" ]
Random access over all pair-wise combinations of large list in Python
38,233,761
<p><strong>Background:</strong></p> <p>I have a list of 44906 items: <code>large = [1, 60, 17, ...]</code>. I also have a personal computer with limited memory (8GB), running Ubuntu 14.04.4 LTS.</p> <p><strong>The Goal:</strong></p> <p>I need to find all the pair-wise combinations of <code>large</code> in a memory-e...
4
2016-07-06T21:05:22Z
38,234,233
<p>If you want random access to any combination you can use this function to return the index of a corresponding lower triangular representation of the cross-product</p> <pre><code>def comb(k): row=int((math.sqrt(1+8*k)+1)/2) column=int(k-(row-1)*(row)/2) return [row,column] </c...
4
2016-07-06T21:39:57Z
[ "python", "list", "combinations", "combinatorics", "large-data" ]
Random access over all pair-wise combinations of large list in Python
38,233,761
<p><strong>Background:</strong></p> <p>I have a list of 44906 items: <code>large = [1, 60, 17, ...]</code>. I also have a personal computer with limited memory (8GB), running Ubuntu 14.04.4 LTS.</p> <p><strong>The Goal:</strong></p> <p>I need to find all the pair-wise combinations of <code>large</code> in a memory-e...
4
2016-07-06T21:05:22Z
38,234,780
<p>I started with that triangular arrangement, finding the subscript <strong>k</strong> for list members indexed <strong>row</strong> and <strong>col</strong>. Then I reversed the process, deriving <strong>row</strong> and <strong>col</strong> from <strong>k</strong>.</p> <p>For a list <strong>large</strong> of <stro...
3
2016-07-06T22:24:11Z
[ "python", "list", "combinations", "combinatorics", "large-data" ]
Tree plot from multiple strings, Python
38,233,823
<p>I have a set of structured strings. Is there a clean way to visualize this data with a tree plot? I am currently reading into <a href="http://www.graphviz.org/" rel="nofollow">http://www.graphviz.org/</a> and <a href="https://pypi.python.org/pypi/pydot" rel="nofollow">https://pypi.python.org/pypi/pydot</a> but it ...
0
2016-07-06T21:10:40Z
38,234,374
<p>By transforming the ":" into "->" and wrapping with .DOT formating, plotting is easy.</p> <pre><code>digraph graphname { A -&gt; B -&gt; C -&gt; D; A -&gt; B -&gt; C -&gt; D -&gt; F; A -&gt; B -&gt; C -&gt; E -&gt; H; A -&gt; B -&gt; C -&gt; D -&gt; G; A -&gt; B -&gt; C -&gt; E -&gt; I; } </code></pre> <p>I t...
0
2016-07-06T21:50:08Z
[ "python" ]
Tree plot from multiple strings, Python
38,233,823
<p>I have a set of structured strings. Is there a clean way to visualize this data with a tree plot? I am currently reading into <a href="http://www.graphviz.org/" rel="nofollow">http://www.graphviz.org/</a> and <a href="https://pypi.python.org/pypi/pydot" rel="nofollow">https://pypi.python.org/pypi/pydot</a> but it ...
0
2016-07-06T21:10:40Z
38,234,626
<p>Not a "simple" approach, but this script will parse your file into a tree, with each "size" value stored in the None index:</p> <p><strong>tree.txt</strong></p> <pre><code>A:B:C:D 355 A:B:C:D:F 330 A:B:C:E:H 78 A:B:C:D:G ...
1
2016-07-06T22:10:39Z
[ "python" ]
Dictionary comprehension within a list comprehension, per dictionary in other list
38,233,835
<p>I am attempting to create a list of dictionaries, where the dictionaries inside of the list are created from a preexisting list of dictionaries, for which a new dictionary should be created from the aggregate of the key-value pairs of each dictionary in the preexisting list of dictionaries, if the key is a member of...
0
2016-07-06T21:11:43Z
38,233,836
<p>A dict comprehension must be used, the compounded for does not capture the per-key-per-dictionary scope.</p> <pre><code>[{k:v for k,v in d.iteritems() if k in lst_multiple_tagnames} for d in child_container if isinstance(d, dict)] </code></pre>
1
2016-07-06T21:11:43Z
[ "python", "list-comprehension", "dictionary-comprehension" ]
Dictionary comprehension within a list comprehension, per dictionary in other list
38,233,835
<p>I am attempting to create a list of dictionaries, where the dictionaries inside of the list are created from a preexisting list of dictionaries, for which a new dictionary should be created from the aggregate of the key-value pairs of each dictionary in the preexisting list of dictionaries, if the key is a member of...
0
2016-07-06T21:11:43Z
38,234,065
<pre><code>assume child_container = [{ 1:1,3:324,2:2334}, {1:123},{2:2}] for d in child_container: ... if isinstance(d,dict): ... for k in d: ... res[k] = res.get(k,[]) + [d[k]] print res {1: [1, 123], 2: [2334, 2], 3: [324]} </code></pre>
0
2016-07-06T21:27:51Z
[ "python", "list-comprehension", "dictionary-comprehension" ]
selecting second child in beautiful soup
38,233,838
<p>Let say a have:</p> <pre><code>&lt;div&gt; &lt;p&gt;this is some text&lt;/p&gt; &lt;p&gt;...and this is some other text&lt;/p&gt; &lt;/div&gt; </code></pre> <p>How can I retrieve the text from the second paragraph in beautifulsoup?</p>
1
2016-07-06T21:11:54Z
38,233,962
<pre><code>secondp = [div.find('p') for div in soup.find('div')] In : secondp[1].text Out : Your text </code></pre> <p>Or you can use the <code>findChildren</code> directly - </p> <pre><code>div_ = soup.find('div').findChildren() for i, child in enumerate(div_): if i == 1: print child.text </code></pre...
1
2016-07-06T21:20:14Z
[ "python", "web-scraping", "beautifulsoup" ]
selecting second child in beautiful soup
38,233,838
<p>Let say a have:</p> <pre><code>&lt;div&gt; &lt;p&gt;this is some text&lt;/p&gt; &lt;p&gt;...and this is some other text&lt;/p&gt; &lt;/div&gt; </code></pre> <p>How can I retrieve the text from the second paragraph in beautifulsoup?</p>
1
2016-07-06T21:11:54Z
38,234,025
<p>You can use a CSS selector to do this:</p> <pre><code>In [57]: from bs4 import BeautifulSoup In [58]: soup = BeautifulSoup("""&lt;div&gt; ....: &lt;p&gt;this is some text&lt;/p&gt; ....: &lt;p&gt;...and this is some other text&lt;/p&gt; ....: &lt;/div&gt;""", "html.parser") In [59]: soup.select('...
3
2016-07-06T21:24:32Z
[ "python", "web-scraping", "beautifulsoup" ]
selecting second child in beautiful soup
38,233,838
<p>Let say a have:</p> <pre><code>&lt;div&gt; &lt;p&gt;this is some text&lt;/p&gt; &lt;p&gt;...and this is some other text&lt;/p&gt; &lt;/div&gt; </code></pre> <p>How can I retrieve the text from the second paragraph in beautifulsoup?</p>
1
2016-07-06T21:11:54Z
38,234,066
<p>You can use <em>nth-of-type</em>:</p> <pre><code>h = """&lt;div&gt; &lt;p&gt;this is some text&lt;/p&gt; &lt;p&gt;...and this is some other text&lt;/p&gt; &lt;/div&gt;""" soup = BeautifulSoup(h) print(soup.select_one("div p:nth-of-type(2)").text) </code></pre>
2
2016-07-06T21:28:06Z
[ "python", "web-scraping", "beautifulsoup" ]
Theano: Shape of a tensor variable inside a function
38,233,858
<p>Say I have this theano function, which defines a layer of a neural network:</p> <pre><code>def layer(W, x): b = np.array(np.ones(N)) # append 1 for intercept newx = T.concatenate([x, T.stack(b)], 0) return T.dot(W, newx) </code></pre> <p>I am concatenating ones (which is the b vector) to the end of th...
1
2016-07-06T21:12:52Z
38,240,539
<p>You can try using <a href="http://deeplearning.net/software/theano/library/tensor/basic.html#theano.tensor.shape" rel="nofollow">theano.tensor.shape</a> to get the shape of the object in question, or, more directly, you can use <a href="http://deeplearning.net/software/theano/library/tensor/basic.html#theano.tensor....
1
2016-07-07T08:11:46Z
[ "python", "neural-network", "theano" ]
Python3 test import error
38,233,870
<p>I am using python3 to try and get a test file for sample application working yet it keeps throwing <code>ImportError: No module named 'calculate'</code></p> <p>my file structure is:</p> <pre><code>/calculate __init__.py calculate.py test/ __init__.py calculate_test.py </code></pre> <p>I cannot figur...
0
2016-07-06T21:13:44Z
38,234,124
<p>Your project's structure is the reason. The test script doesn't have the outer directory in the search path when you start it. Here are some ways to fix that</p> <ol> <li>Move the test file into the same directory that contains the module it imports. That will require no changes in the test file.</li> <li><p>Use th...
0
2016-07-06T21:32:03Z
[ "python", "unit-testing", "testing" ]
Python/django - compare list with database rows
38,233,889
<p>I have a database with rows of image locations, I also have a list of image locations which is generated when I run the script. I want to keep the database in sync with the generated list. I would just drop the table, but this table has vote information which I need to keep. If I delete the image, I don't want there...
0
2016-07-06T21:15:21Z
38,234,674
<p>Assuming you have django model <code>VotableImage</code>, you can get list of one of it's fields by calling <code>db_path_list = VotableImage.objects.values_list('Path', flat=True)</code> and then check each value for presence in <code>files</code> list (that you created by script)</p>
1
2016-07-06T22:14:08Z
[ "python", "django", "sqlite" ]
Creating folders based on names in a text file in python
38,233,966
<p>I am trying to get a python script to read a text file that has a list of names in it and create folders based on those names. For example, if the text file has "john_doe" and "jane_doe" in it, the script should create two folders. One called "john_doe" and one called "jane_doe". </p> <p>When I run my script, I get...
0
2016-07-06T21:20:30Z
38,234,364
<p>Instead of:</p> <pre><code> os.mkdir(str(x)) </code></pre> <p>You meant:</p> <pre><code> os.mkdir(str(line)) </code></pre> <p>You don't even need <code>str()</code>, since <code>line</code> is already a <code>str</code>. (I suspect you only added it because <code>os.mkdir(x)</code> was giving you a...
2
2016-07-06T21:49:35Z
[ "python" ]
Creating folders based on names in a text file in python
38,233,966
<p>I am trying to get a python script to read a text file that has a list of names in it and create folders based on those names. For example, if the text file has "john_doe" and "jane_doe" in it, the script should create two folders. One called "john_doe" and one called "jane_doe". </p> <p>When I run my script, I get...
0
2016-07-06T21:20:30Z
38,234,572
<p>Check the current working directory by:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() </code></pre> <p>You may find that your program maynot have appropriate permission to make changes on the directory.</p> <p>Try changing to something else like:</p> <pre><code>&gt;&gt;&gt; os.chdir("&lt;someAbs...
0
2016-07-06T22:06:05Z
[ "python" ]
Creating folders based on names in a text file in python
38,233,966
<p>I am trying to get a python script to read a text file that has a list of names in it and create folders based on those names. For example, if the text file has "john_doe" and "jane_doe" in it, the script should create two folders. One called "john_doe" and one called "jane_doe". </p> <p>When I run my script, I get...
0
2016-07-06T21:20:30Z
38,234,837
<p>You may be catching a problem with special characters and whitespace between the names. Windows doesn't like it when you fail to escape the whitespace between multi-word directory names. </p> <p>Try (i) reading the lines as Unicode (to avoid special character problems) and then (ii) joining the names with an unde...
0
2016-07-06T22:28:52Z
[ "python" ]
Pandas Dataframe find and replace
38,234,003
<p>I have two lists:</p> <pre><code>single = ['A','B'] double = ['AA','BB'] </code></pre> <p>Data stored in dataframe <code>df</code>:</p> <pre><code> 0 1 2 3 0 All 1 AA Yes 1 A 2 All No </code></pre> <p>where All means <code>['A','B']</code> in column 0 and means <code>['AA','BB']</code> in ...
0
2016-07-06T21:23:09Z
38,234,255
<pre><code>import pandas as pd single = ['A','B'] double = ['AA','BB'] df = pd.DataFrame([['All',1,'AA','Yes'],['A',2,'All','No']]) first = pd.DataFrame([x for item in single for x in [('All', item), (item, item)]], columns=[0, 'first']) third = pd.DataFrame([x for item in double ...
2
2016-07-06T21:41:33Z
[ "python", "pandas" ]
Is there a way to access the top left corner push button of QTableView?
38,234,039
<p>PyQt 4.11.4 Qt 4.8.7</p> <p>Is there a way to get a pointer to the top left corner cell/pushbutton on a QTableView? I would like to remove it or hide it. In the image below its the cell left of the first column (Lag1_Lvl_Cng_BBB_Spread) and above the first row (qadj_disp_inc_nom)</p> <p>Any help appreciated<a hre...
1
2016-07-06T21:25:45Z
38,354,494
<p>Per the comments above, you can only disable it via <a href="http://doc.qt.io/qt-4.8/qtableview.html#cornerButtonEnabled-prop" rel="nofollow"><code>::setCornerButtonEnabled()</code></a>. </p> <p>That said, if this is important enough you can try <a href="http://www.qtcentre.org/threads/28693-QTableWidget-Using-top...
1
2016-07-13T14:27:34Z
[ "python", "qt", "pyqt4" ]
Project different embedded structures to same name
38,234,053
<p>I am writing a python script that performs these tasks:</p> <ul> <li>Query a MongoDB Collection with embeded documents</li> <li>Aggregate and Project to change the field names that are returned in the query to match a "u_" convention</li> <li>Import the values to ServiceNow via REST API</li> </ul> <p><strong>ISSUE...
4
2016-07-06T21:26:53Z
38,234,402
<p>You can use the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/ifNull/" rel="nofollow"><code>$ifNull</code></a> operator to <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/project" rel="nofollow"><code>$project</code></a> the "hostname" field.</p> <pre><code>cmp = db...
1
2016-07-06T21:52:42Z
[ "python", "mongodb", "pymongo", "aggregation-framework" ]