Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
7,400 | 14,414,345 | Specifying the full path to an entity with inheritance hierarchies in contains_eager() | <p>I have a query like</p>
<pre><code>(session.query(Root).with_polymorphic('*')
.outerjoin(Subclass.related1).options(contains_eager(Subclass.related1)))
</code></pre>
<p>So far things work.</p>
<p>I want also want to eagerly load <code>Related1.related2</code> and I tried this:</p>
<pre><code>(session.query(R... | <p>contains_eager needs a full path from the entities the query knows about:</p>
<pre><code>contains_eager(Subclass.related1, Related1.related2)
</code></pre> | python|sqlalchemy | 19 |
7,401 | 41,499,782 | Python ~ Getting first few numbers from left to right | <p>I am currently writing a programme with two variables in random and need to be calculated in an equation and want to fetch first three numbers and converting it to a percentage, the following is what I want the programme to reply</p>
<pre><code>formular = (((((3*m-2*h)*g*c*b)/3*m)*o)/lvl)/100
print formular
#g and ... | <p>There's no inbuilt function, but it's easy to string something together with a couple of operations.</p>
<p>First is to reduce your number to 2 significant digits. You can get the number of significant digits with the <code>log</code> function, then use exponentiation to get the magnitude. Finish it off with a <cod... | python|python-2.7 | 0 |
7,402 | 41,291,517 | How do you form data to make an array of n features and n samples in scikit learn decision tree? | <p>I am new to scikit learn, and I am attempting to train a classifier to predict what type of car is most likely given a specific input:</p>
<p>My data looks like this:</p>
<p>18.0 8 307.0 130.0 3504. 12.0 70 1 chevrolet </p>
<p>15.0 8 350.0 165.0 3693. 11.5 70 1 ... | <p>Your have a problem here at the X declaration. As stated in the documentation, X must be of shape [n_samples, n_features], whereas in your code, what you have is an array of shape [n_features, n_samples], i.e [[18.0,15.0,...,14.0], [8,8,...,8],...,[1,1,...,1]].</p>
<p>What you need is actually an array where each r... | python|machine-learning|scikit-learn | 2 |
7,403 | 41,529,936 | Plot Additional Quantiles on Seaborn Violin Plots | <p>Using the example on <a href="https://seaborn.pydata.org/generated/seaborn.violinplot.html" rel="nofollow noreferrer">http://seaborn.pydata.org/generated/seaborn.violinplot.html</a>:</p>
<pre><code>import seaborn as sns
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.violinplot(x="day", y="total... | <p>Here is a rather hacky solution:</p>
<p>What about drawing another boxplot on top of your Violin plot? (And hiding the box in the box plot.)</p>
<p>Here is the output using 2.5 and 97.5:</p>
<p><a href="https://i.stack.imgur.com/bEThq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bEThq.png" a... | python|seaborn|violin-plot | 4 |
7,404 | 57,279,034 | Mystic - how to properly stop an optimization | <p>I have a fairly large and complex Python application to which I recently added the ability to perform nonlinear optimization using Mystic (<a href="https://github.com/uqfoundation/mystic" rel="nofollow noreferrer">https://github.com/uqfoundation/mystic</a>). The optimization runs in a separate thread from the main (... | <p>I'm the <code>mystic</code> author. There are two ways, generally.</p>
<p>If you are using the function interface (i.e. <code>mystic.solvers.diffev2(...)</code>), then you can use the keyword <code>handler=True</code>. If you do a signal-interrupt, it will pause a running solver that has the handler enabled. Two... | python|nonlinear-optimization|mystic | 0 |
7,405 | 44,567,634 | how to display inputbox dynamically using select widget in bokeh | <p>I am trying to implement chart in bokeh depending upon the user input, the requirement is cascade the dropdown so that it will make appearance of textbox depending upon the selected item in the dropdown </p>
<ul>
<li>if I select fruits, dynamically it should ask the input for price and quantity</li>
<li>if I select... | <p>Running on a bokeh server, you can interactively edit any objects property using only python code. For a select box you can attach a function to check for changes on your select menu and then specify in the python function, how to change your the input objects based on the selected value. Something similar to this.<... | python|charts|bokeh | 1 |
7,406 | 44,599,589 | Inserting new rows in pandas data frame at specific indices | <p>I have a following data frame <strong>df</strong> with two columns "identifier", "values" and "subid":</p>
<pre><code> identifier values subid
0 1 101 1
1 1 102 1
2 1 103 2 #index in list x
3 1 104 2
4 1 ... | <p>Preserving the index order is the tricky part. I'm not sure this is the most efficient way to do this, but it should work.</p>
<pre><code>x = [2,8,12]
rows = []
cur = {}
for i in df.index:
if i in x:
cur['index'] = i
cur['identifier'] = df.iloc[i].identifier
cur['values'] = df.iloc[i]['... | python|pandas|dataframe | 4 |
7,407 | 44,787,680 | Sorting Column Data from Excel using Python | <p>Is there a way to take the columns from an excel sheet, write the columns as lists, sort them, and then rewrite them to another excel sheet? This is what I've tried so far, but it only writes the last column of data. I do not need the first 2 rows of data, as they are just headers.</p>
<pre><code>import xlrd
import... | <p>I think you need to append() or extend() column names from your excel to the list 'col'. currently it is replacing the value of 'i' every time the FOR loop iterates. </p>
<p>maybe something like this:
col.append(ws.col_values(i))</p>
<p>P.S. This is my first answer on stack-overflow. hope it helps. I have not test... | python|excel|xlrd|xlsxwriter | 0 |
7,408 | 44,747,757 | Getting internal server error 500 while displaying output in Flask | <p>I have just started learning Flask and referring a tutorial to run a small piece of test code. </p>
<p>Here is the code:</p>
<p><strong>Hello.py</strong></p>
<pre><code>from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def student():
return render_template('student.html')... | <p>You passed in the <code>request.form</code> object to your template. As the traceback tells you, that object has no <code>iteritems()</code> method:</p>
<pre><code>'werkzeug.datastructures.ImmutableMultiDict object' has no attribute 'iteritems'
</code></pre>
<p>The <code>iteritems()</code> methods on dictionaries ... | python|html|flask | 0 |
7,409 | 23,709,403 | Plotting profile hitstograms in python | <p>I am trying to make a profile plot for two columns of a pandas.DataFrame. I would not expect this to be in pandas directly but it seems there is nothing in matplotlib either. I have searched around and cannot find it in any package other than rootpy. Before I take the time to write this myself I thought I would ask ... | <p>You can easily do it using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binned_statistic.html" rel="noreferrer"><code>scipy.stats.binned_statistic</code></a>.</p>
<pre><code>import scipy.stats
import numpy
import matplotlib.pyplot as plt
x = numpy.random.rand(10000)
y = x + scipy.stats.... | python|matplotlib|pandas|histogram | 5 |
7,410 | 24,281,544 | How to add an onChange event to Django form fields with field itself as an argument | <p>I'm adding <code>onChange</code> event on a TextField dynamically. The following code explains what I'm doing:</p>
<pre><code>fields.widget.attrs['onchange'] = 'execute_function(arg)'
</code></pre>
<p>I have add field itself as an argument to javascript function similar to <code>function_name(this)</code> in djang... | <p>If I understand your question it should be as easy as changing <code>arg</code> to <code>this</code>:</p>
<pre><code>fields.widget.attrs['onchange'] = 'execute_function(this)'
</code></pre> | javascript|python-2.7|django-forms | 0 |
7,411 | 71,986,209 | array implementation using python from scratch | <p>My teacher has asked me to implement an array using python without using any inbuilt functions but I am confused and I don't know how to? this is the complete question...</p>
<pre><code>Write a program in Python to implement the “Array” data structure. Perform operations like add or insert, delete or remove and disp... | <p>You can store the array in a list L, and write a function for each list operation. For example, to search for an element x in a list L and return the index of the first occurrence of x in L, rather than using the built-in function index, you would implement the linear search algorithm. So, the following code would ... | python|arrays | 1 |
7,412 | 71,793,056 | Adding roles in discord py | <h2>Adding roles using discord py</h2>
<p>I'm coding a bot on Discord, where I can mute any user just by using a simple command. Here, I tried to get the user by using the <code>client.fetch_user(id)</code> function and then add a role to the user, but I got an error saying:</p>
<blockquote>
<p>AttributeError: 'corouti... | <p>The issue is that <a href="https://discordpy.readthedocs.io/en/latest/api.html?highlight=fetch_member#discord.Guild.fetch_member" rel="nofollow noreferrer"><code>await fetch_member()</code> takes an integer ID, not a string</a>.</p>
<p>In your code, you have a mention in the format <code>'<@12345>'</code>, whi... | python|discord|discord.py | 0 |
7,413 | 46,424,010 | NetSuite Error: CustomFieldRef is an abstract type and cannot be instantiated | <p>I am working on NetSuite WSDL. I am stuck on this error from past two days. I have searched on the internet but couldn't find a solution.</p>
<p>I try to add a <a href="http://www.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2017_1/schema/other/customfieldlist.html?mode=package" rel="nofollow noreferrer">cus... | <p>I solved the question by using <a href="http://www.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2017_1/schema/other/selectcustomfieldref.html?mode=package" rel="nofollow noreferrer">SelectCustomFieldRef</a> instead of CustomFieldRef. i.e.</p>
<pre><code>new_record['companyName']= 'test_clinic1'
new_record['f... | python|wsdl|netsuite | 2 |
7,414 | 46,196,346 | Why does my Game of Life simulation slow down to a crawl within seconds? Matplotlib to blame? | <p>I'm learning OOP in python and so for a bit of fun I bashed out a GameOfLife simulator this morning. When it starts up it runs at about 20 cycles per second (due to the <code>plt.pause(0.05)</code> I added), but within seconds it slows down to ~ 2 cycles per second.</p>
<p>I can't imagine it's the algorithm itself,... | <p>You will see that the images of previous calls are still present by printing the number of images inside the <code>plot</code> function, </p>
<pre><code>print ( len(plt.gca().images) )
</code></pre>
<p>In your case this number will increase steadily, even though you delete the image, because it is still part of th... | python|oop|matplotlib | 2 |
7,415 | 46,220,167 | Add columns to pivot table with pandas | <p>I have the table as follow:</p>
<pre><code>import pandas as pd
import numpy as np
#simple table
fazenda = [6010,6010,6010,6010]
quadra = [1,1,2,2]
talhao = [1,2,3,4]
arTotal = [32.12,33.13,34.14,35.15]
arCarr = [i/2 for i in arTotal]
arProd = [i/2 for i in arTotal]
varCan = ['RB1','RB2','RB3','RB4']
data = list(zi... | <p>Get the <code>pivot</code> right first.</p>
<pre><code>In [404]: values = ['ArTotal','ArCarr','ArProd']
In [405]: table = pd.pivot_table(df, values=values, index=['Quadra','Talhao','Variedade'],
fill_value=0).reset_index(level=-1)
</code></pre>
<p>Get Grand totals</p>
<pre><code... | python|pandas|numpy|pivot-table | 3 |
7,416 | 49,631,168 | How to iterate in Python through two lists with different length in paralell? | <p>I have two lists:</p>
<pre><code>list1=[1,2,3]
list2=[4,5,6,7]
</code></pre>
<p>And I want to iterate over them. What I want to obtain is something similar to this:</p>
<pre><code>1,4
2,5
3,6
,7
</code></pre>
<p>I have thought of using the <code>zip</code> function but it doesn't seem to work with different len... | <p>I think you need <a href="https://docs.python.org/3.4/library/itertools.html#itertools.zip_longest" rel="noreferrer"><code>zip_longest</code></a>:</p>
<pre><code>from itertools import zip_longest
list1=[1,2,3]
list2=[4,5,6,7]
for l1, l2 in zip_longest(list1, list2):
print(l1,l2)
# 1 4
# 2 5 ... | python|list|for-loop|iterator | 5 |
7,417 | 53,605,752 | How can I split the contents of a row into two columns in html to display better | <p>I have a sqlite db and the data is in the format - ('value','timestamp').
I am using a html file to render the data on a flask application eventually. </p>
<p>index.html is as follows - </p>
<pre><code> <!DOCTYPE html>
<html>
<head>
<title>{{ title }} - XYZ</title>
... | <p>You can access the variables of the row individually (I've comma separated the 2 values but you can just leave a space):</p>
<pre><code><th>Value</th>
<th>Timestamp</th>
{% for row in data %}
<tr>
<td>{{ row[0] }}</td> <td>{{ row[1] }}</td>
</... | python|html-table | 1 |
7,418 | 33,199,423 | How do I concatenate 'str' and 'int' objects? | <pre><code>age = raw_input ('How old are you? ')
print "In two year's time you will be: " , age + 2
</code></pre>
<p>How do I get the last line of this code to work? I get the error <code>TypeError: cannot concatenate 'str' and 'int' objects</code> when I run it in Python.</p> | <p>We can concatenate it by typecasting age to int and then adding it to an int. </p>
<pre><code> age = raw_input ('How old are you? ')
print "In two year's time you will be: " , int(age) + 2
</code></pre>
<p>Infact a better way to print this would be to use format:</p>
<pre><code>print "In two year's time you will... | python|string|concatenation | 1 |
7,419 | 13,002,966 | Class Variable In Python [set()] | <p>Why does set behave differently from a dictionary for class variables in python. For instance, </p>
<pre><code>class Test1:
x=set()
y={}
hamster=Test1()
chinchilla=Test1()
hamster.x.add('hi') # now both sets in both instances have 'hi'
hamster.y['key']=5 # only the hamster instance will contain 5
</code><... | <p>No you're wrong both have the <code>key:5</code>:</p>
<pre><code>In [56]: class Test1:
....: x=set()
....: y={}
....:
In [57]: hamster=Test1()
In [58]: chinchilla=Test1()
In [59]: hamster.x.add('hi') # now both sets in both instances have 'hi'
In [60]: hamster.y['key']=5
In [62]: hamster.x... | python | 5 |
7,420 | 21,810,823 | Clustered barchart in matplotlib? | <p>How do I plot a barchart similar to </p>
<p><a href="https://stackoverflow.com/questions/5130517/clustered-bar-plot-in-gnuplot#">Clustered bar plot in gnuplot</a> using python matplotlib?</p>
<pre><code>date|name|empid|app|subapp|hours
20140101|A|0001|IIC|I1|2.5
20140101|A|0001|IIC|I2|3
20140101|A|0001|IIC|I3|4
20... | <p>The examples didn't manage unequal # of bars but you can use another approach. I'll post you an example.</p>
<p>Note: I use pandas to <em>manipulate</em> your data, if you don't know about it you should give it a try <a href="http://pandas.pydata.org/" rel="nofollow">http://pandas.pydata.org/</a>:</p>
<pre><code>i... | python|matplotlib | 1 |
7,421 | 24,892,850 | How to get precipitation/rainfall through weather api? | <p>I tired <a href="http://openweathermap.org/current" rel="nofollow">Open Weather Map</a> because the docs say it has "rain", but when I call it it doesn't. So I tried <a href="https://code.google.com/p/python-weather-api/wiki/Examples" rel="nofollow">Python Weather API</a> but none of those options from weather.com, ... | <p>According to the <a href="http://openweathermap.org/weather-data" rel="nofollow">documentation</a>, <code>weather</code>, <code>rain.3h</code>, and <code>snow.3h</code> are all <code>optional</code> parameters, suggesting that they will not always be included in the result.</p>
<p>I interpret that to mean that rain... | python|python-requests|weather|weather-api | 3 |
7,422 | 24,926,198 | saving image from website and putting it into a sqlite database in python 2.7 | <p>I'm trying to save a photo given a URL and put it directly into a sqlite database without saving it in permanent memory. </p>
<p>Currently, the code I have to save the image is:</p>
<pre><code> file = urllib2.urlopen("http://www.example.com/images/image.jpg")
output = open('filename.jpg','wb')
output.write(file.... | <p>The data you want is already returned by <code>file.read()</code>.
You just have to put this data into the database:</p>
<pre><code>file = urllib2.urlopen("http://www.example.com/images/image.jpg")
db.execute("INSERT INTO MyTable(MyColumn) VALUES(?)", [buffer(file.read())]
db.commit()
</code></pre> | python-2.7|sqlite | 0 |
7,423 | 41,078,009 | pandas DataFrame reshape by multiple column values | <p>I'm trying to free myself of JMP for data analysis but cannot determine the pandas equivalent of JMP's <a href="http://www.jmp.com/support/help/Split_Columns.shtml" rel="noreferrer">Split Columns</a> function. I'm starting with the following DataFrame:</p>
<pre><code>In [1]: df = pd.DataFrame({'Level0': [0,0,0,0,0... | <p>It's a bit of workaround, but you can do:</p>
<pre><code>df.pivot_table(index=df.groupby(['Level0', 'Level1']).cumcount(),
columns=['Level0', 'Level1'], values='Vals', aggfunc='first')
Out:
Level0 0 1
Level1 0 1 0 1
0 1 3 7 5
1 2 4 3 3
2 1 6 2 8
</code></pre>
... | python|pandas | 3 |
7,424 | 41,039,058 | Create a new csv file | <p>I'm using python and am trying to create a new csv file using the csv module (i.e. one that doesn't currently exist). Does anyone know how to do this?</p>
<p>Thanks in advance,
Max</p> | <p>if you want simply create a csv file you can use built in method open, for more about open check <a href="https://docs.python.org/2/library/functions.html#open" rel="nofollow noreferrer">this</a></p>
<pre><code>with open("filename.csv","a+") as f:
f.write(...)
</code></pre>
<p>or if you want to read an exist ... | python-3.x | -1 |
7,425 | 31,029,496 | How to introduce the attributes of an object in python by calling a method in __init__ method? | <p>As a simple example, let's assume that we want to create a lot of <code>Earthquake</code> instances, having name, origin time, and hypocenter coordinate attributes coming from other sources encoded as strings (<code>"Nepal 25-4-2015T11:56:26 28.14 84.71 15.0"</code>).</p>
<pre><code>class Earthquake(object):
de... | <p>I would do that completely the other way around. Parsing that string is clearly part of what an <code>Earthquake</code> object should do, so provide it as an alternate constructor using a <em>class method</em>:</p>
<pre><code>class Earthquake(object):
def __init__(self, name, otime, lat, lon, depth):
s... | python|oop | 6 |
7,426 | 30,808,716 | Adding Hyphen in row data in python | <p>In my csv file, i have a col with value like
A12001
A22001
A32001</p>
<p>I need to make it look like </p>
<p>A1-2001
A2-2001
A3-2001</p>
<p>I am new to python. Any help will be appreciated.</p>
<p>Thanks</p> | <p>I'm not sure how you CSV file is made of, so for simplicity sake I will assume that your CSV file has only this column.</p>
<p>So,</p>
<p>1 - Open your CSV file for read & write, assuming its name myCSV.csv</p>
<p>2 - read each line and re-write it with the modified string.</p>
<p>3 - Close the CSV file</p>
... | python|csv | 1 |
7,427 | 40,320,797 | Can't render a matplotlib graph using Qt5Agg backend | <p>I'm trying to make this script work, but whenever I run it in the terminal, it doesn't render even if the script is still running.</p>
<p>I installed Qt5Agg using </p>
<pre><code>pip install Qt5Agg
</code></pre>
<p>I'm on a windows 10 computer.<br>
I use python 3.5<br>
I've got no error in the terminal.<br>
I've... | <p>First of all, I presume that you installed <code>PyQt5</code>, as there is no <code>Qt5Agg</code>. </p>
<p>You should not use <code>plt.switch_backend</code>, you can have a quick look at the documentation here (<a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.switch_backend" rel="noreferrer">ht... | python|matplotlib | 12 |
7,428 | 52,224,701 | color effect on map (python plotly) | <p>I create a basemap for US and want to fill in color with temperature value.</p>
<p>I want to fill the map with the color effect like the following picture.</p>
<p>But now I could only hand code the color value like 'red','orange' and 'purple' and could not get the effect.</p>
<p>Any suggestion to help me to... | <p>Looks at this <a href="https://plot.ly/ipython-notebooks/basemap-maps/" rel="nofollow noreferrer">example</a>. On this <a href="https://plot.ly/ipython-notebooks/basemap-maps/#make-contour-graph-object" rel="nofollow noreferrer">step</a> you can change <code>colorscale</code> parameter (and color changed on whole ba... | python|plotly | 1 |
7,429 | 18,787,722 | How to change directory according to the username? | <p>Is there are a way to change the user directory according to the username, something like</p>
<pre><code>os.chdir('/home/arn/cake/')
</code></pre>
<p>But imagine that I don't know what's the username on that system. How do I find out what's the username, I know that python doesn't have variables so it's hard for m... | <pre><code>pwd.getpwnam(username).pw_dir
</code></pre>
<p>is the home directory of <code>username</code>. The user executing the program has username <code>os.getlogin()</code>.</p>
<p>"I know that python doesn't have variables" -- that's nonsense. You obviously mean environment variables, which you can access using ... | python|linux | 2 |
7,430 | 18,937,708 | Multiple references in separate lists; Python | <p>I'm trying to basically create references to plot multiple relationships and store them in a list or possibly a dictionary. </p>
<p>Basically: </p>
<p><code>variable1 = 10</code></p>
<p>//in this case, 'ref' denotes that the variable should be a reference)<br>
<code>listA = [variable1(ref), variable2, variable3]<... | <p>What about two lists, each containing keys of the same collection, say dictionary?</p>
<p>For example:</p>
<pre><code>MASTER = [10,11,12,13,14]
LISTA = [0,1,2]
LISTB = [0,3,4]
for i in LISTA: MASTER[i] += 10
for i in LISTB: MASTER[i] += 10
print MASTER[LISTA[0]]
print MASTER[LISTB[0]]
</code></pre>
<p><a href... | python|list|reference|immutability|mutable | 1 |
7,431 | 62,291,417 | Try /Except inside for loop not behaving as expected | <p>CODE :</p>
<pre><code>def ValidateProxy(LIST_PROXIES):
'''
Checks if scraped proxies allow HTTPS connection
'''
for proxy in LIST_PROXIES:
print('using', proxy)
host, port = str(proxy).split(":")
try:
resp = requests.get('https://amazon.com',
... | <h1>Edit 2022-08-09</h1>
<p>I would separate the logic into two functions. Also, please follow <a href="https://peps.python.org/pep-0008/" rel="nofollow noreferrer">PEP-8</a> (I did not point that in the original answer)</p>
<pre class="lang-py prettyprint-override"><code>from typing import Iterable
import requests
d... | python|error-handling|try-catch | 2 |
7,432 | 36,299,077 | Pyinstaller "returned -1" | <p>I know this question has been asked many times before, but after browsing the answers, I cannot seem to figure out what is going wrong.</p>
<p>I have a python script (below) and I am trying to use Pyinstaller to make it into an executable file (I am on windows).</p>
<p>When I am in the directory of my Plot.py file... | <p>Try to replace every <code>exit()</code> or <code>quit()</code> or <code>os._exit()</code>
with <code>sys.exit()</code>
...I see that You dont have any of these in ur code,but somebody else might find this useful...Hope it helps :) </p>
<p>myinfo: python3.4, pyinstaller3.1.1</p> | python|matplotlib|pyinstaller | 0 |
7,433 | 36,528,453 | Concatenate array of dictionaries in one line | <p>How can I transform the following dictionaries-in-array structure into a dictionary with <code>'city': 'continent'</code> structure with just one line?</p>
<pre><code>info = [
({'Amsterdam':10,'Berlin':20,'London':30},'Europe'),
({'Hongkong':10,'Beijng':20,'Manila':30},'Asia'),
({'Nairobi':10,'Cape Town... | <p>try this (tested on 3.5):</p>
<pre><code>a = {i: y for x, y in info for i in x}
</code></pre> | python-3.x | 1 |
7,434 | 13,448,380 | how to sort a database | <p>I have a database that i now combined using this function</p>
<pre><code>def ReadAndMerge():
library1=input("Enter 1st filename to read and merge:")
with open(library1, 'r') as library1names:
library1contents = library1names.read()
library2=input("Enter 2nd filename to read and merge:")
with... | <p>You sort with the <code>sorted()</code> method. But you can't sort just a big string, you need to have the data in a list or something similar. Something like this (untested):</p>
<pre><code>def get_library_names(): # Better name of function
library1 = input("Enter 1st filename to read and merge:")
with ope... | database|sorting|python-3.x | 2 |
7,435 | 22,239,565 | Sympy: working with equalities manually | <p>I'm currently doing a maths course where my aim is to understand the concepts and process rather than crunch through problem sets as fast as possible. When solving equations, I'd like to be able to poke at them myself rather than have them solved for me.</p>
<p>Let's say we have the very simple equation <code>z + 1... | <p>There is a "do" method and discussion at <a href="https://github.com/sympy/sympy/issues/5031#issuecomment-36996878" rel="nofollow noreferrer">https://github.com/sympy/sympy/issues/5031#issuecomment-36996878</a> that would allow you to "do" operations to both sides of an Equality. It's not been accepted as an additio... | python|sympy | 11 |
7,436 | 16,830,745 | Comparison of float numbers to a known value python | <p>Hi all i have a list that is calculated from functions </p>
<pre><code>ab = (x, x1, x2, x3, x4, x5, x6, x7, x8)
</code></pre>
<p>where x, x1 and so on are float numbers calculated from a distance equation. Is there any way i can take each of these float values in the list and compare them to a known value. I.e </p... | <p>If you need to search the key often in your code, it would be advisable to pre sort the data, and perform a binary search. Based on the frequency of lookup and the length of your input data, this would be efficient</p>
<pre><code>>>> import bisect
>>> import random
>>> ab = [random.random... | python|list|comparison|floating | 0 |
7,437 | 17,053,103 | When to use "with" in python | <p>I saw <a href="https://stackoverflow.com/questions/903557/pythons-with-statement-versus-with-as">this question</a>, and I understand when you would want to use <code>with foo() as bar:</code>, but I don't understand when you would just want to do:</p>
<pre><code>bar = foo()
with bar:
....
</code></pre>
<p>Doesn... | <p>To expand a bit on @freakish's answer, <code>with</code> guarantees entry into and then exit from a "context". What the heck is a context? Well, it's "whatever the thing you're with-ing makes it". Some obvious ones are:</p>
<ul>
<li>locks: you take a lock, manipulate some data, and release the lock.</li>
<li>ext... | python | 12 |
7,438 | 43,554,078 | Is it possible to perform the same shuffle on multiple numpy arrays in place? | <p>I need to perform the same shuffle on multiple arrays simultaneously. These may be large arrays (multiple GBs), so it needs to be done in place. A simpler example:</p>
<p>Before shuffle:</p>
<pre><code>Arr1: [[1 2 3]
[4 5 6]]
Arr2: [0 1]
</code></pre>
<p>After shuffle:</p>
<pre><code>Arr1: [[4 5 6]
... | <p>Here is the best solution I've found:</p>
<pre><code>from numpy.random import RandomState
import sys
def shuffleDataAndLabelsInPlace ( arr1, arr2):
seed = random.randint(0, sys.maxint)
prng = RandomState(seed)
prng.shuffle(arr1)
prng = RandomState(seed)
prng.shuffle(arr2)
# Example:
arr1= np.a... | python|numpy | 1 |
7,439 | 53,552,527 | Reversing substrings in a string in python | <p>I am writing a program to reverse the substrings enclosed in parenthesis in python. The resultant string should not contain any parenthesis. I am printing b1 and b2 and ch for testing purposes. It seems that in the second iteration of the for loop inside the while loop, the b1 variable is not updated with the correc... | <p>A nice way to deal with nested delimiters is to use a stack. When you encounter an opening delimiter push a new collection to the stack. <code>pop()</code> when you find a closing. This will keep the order of nesting correct.</p>
<p>Here's one way to do this (it doesn't check for balanced parenthesis, but it's not ... | python|python-3.x|substring | 6 |
7,440 | 71,404,412 | Import data from csv file as variable for code in Python | <p>I am trying to import a set of data from a CSV file to shorten my code in python,</p>
<p>Before I try to use the CSV file as a variable, I have confirmed the code is working as below:</p>
<pre><code>csvone = pd.read_csv("csvone.csv")
data_a = csvone[csvone['IP Address'].str.contains(r'10.1\.')]
data_a[&qu... | <p>If you have a fixed number of digit-blocks - here 2 - you could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html#pandas.DataFrame.merge" rel="nofollow noreferrer"><code>.merge</code></a> in combination with <a href="https://pandas.pydata.org/pandas-docs/stable/refer... | python|python-3.x|pandas|csv | 1 |
7,441 | 9,098,976 | django Piston Post Request Change strings to lists | <p>I have a simple Django-Piston Handler that creates a new instance of a model and saves it.</p>
<p>From the client, I am posting using Javascript Objects and JQuery.post.</p>
<p>Upon inspecting the data with Firebug, the post string looks like this:</p>
<pre><code>classification=&organization=&title=Format... | <p>It is <strong>not</strong> an error, your data has always been in such a list, it is a <strong>design decision</strong> from Django. Whatever code is accessing the QueryDict instance and gets list values otherwise than with the <code>getlist()</code> method is using QueryDict wrong.</p>
<p><a href="https://docs.dja... | jquery|python|django|post|django-piston | 2 |
7,442 | 9,278,777 | calculate how many times of the functions or variables be invoked | <p>I want to get the invoked times of each function or variable from existing codes which is writing in python.</p>
<p>What i thought is override the object's <strong>getattribute</strong> function, such as below:</p>
<pre><code>acc = {}
class object(object):
def __getattribute__(self, p):
acc.update({st... | <p>Use a <a href="http://docs.python.org/glossary.html#term-decorator" rel="nofollow">decorator</a>.</p>
<pre><code>>>> def timestamp(container, get_timestamp):
... def timestamp_decorator(func):
... def decorated(*args, **kwargs):
... container[func.func_name] = get_timestamp()
...... | python | 2 |
7,443 | 39,282,429 | Is there a way to get the argument of argparse in the order in which they were defined? | <p>I'd like to print all options of the program and they are grouped for readability. However when accessing the arguments via <code>vars(args)</code>, the order is random.</p> | <p><code>argparse</code> parses the list of arguments in <code>sys.argv[1:]</code> (<code>sys.argv[0]</code> is used as the <code>prog</code> value in <code>usage</code>).</p>
<p><code>args=parser.parse_args()</code> returns a <code>argparse.Namespace</code> object. <code>vars(args)</code> returns a dictionary based ... | python|argparse | 3 |
7,444 | 39,146,957 | How Do I Build a Class with in a Class in Python | <p>I am trying to model services and I am having some issue. What I am trying to do is I would want something such as this in code:</p>
<pre><code>>>> service = Service()
>>> service.name = "Instance1"
>>> service.name.color = "red"
>>> service.name.color.enabled = True
</code></pre... | <p>It's not against convention to have other objects as values of attributes of your class. </p>
<p>The best thing you can do it declare your desired classes - in your example these would be <code>class Color</code>, which would have a boolean attribute <code>enabled</code>.</p> | python|class | 0 |
7,445 | 52,777,165 | Convert a matlab loop to python loop | <p>Im trying to convert a matlab script to python code and i have this loop:</p>
<pre><code>n = 3;
v = zeros(n,n);
for i =1:n
for j =1:i
v(i,j) = ((2)^(i-j))*((3)^(j-1));
end
end
</code></pre>
<p>I have managed to convert it to this python code:</p>
<pre><code>import numpy as np
n = 3
v = np.zeros(... | <pre><code>for i in range(n):
for j in range(i+1):
v[i,j] = ((2)**(i-j))*((3)**(j))
</code></pre>
<p>The (i-j) difference won't change if j and i are both reduced by one, you just have to update the last power.</p>
<p>You could also do it in one comprehension list, wich are usefull in python:</p>
<pre><c... | python|matlab|numpy | 2 |
7,446 | 47,882,825 | Understanding Collatz Conjecture Objective in Python | <p>I'm trying to decipher the following homework question. My code is supposed to evaluate to 190 but instead evaluates to 114. So, I don't think I'm understanding the coding requirement. </p>
<blockquote>
<p>The Collatz conjecture is an example of a simple computational process
whose behavior is so unpredictable ... | <p>You just misread the intermediary question. Your programs tries to answer the bigger question... This is what should return <code>190</code>:</p>
<pre><code>def f(n):
return n // 2 if n % 2 == 0 else 3*n + 1
print f(f(f(f(f(f(f(674)))))))
</code></pre> | python|algorithm | 2 |
7,447 | 47,816,610 | References and value affectations : when python does the first and when the secodn | <p>I would like to understand when precisely python affect a variable by value and when by reference.</p>
<p>Take the following example. In this code, I first create a list "dataToTreat", and then I say "dataToTreatBis=dataToTreat". But when I change dataToTreatBis, dataToTreat is not affected.</p>
<p>But in the seco... | <p>All python variables are bindings to some objects in memory.</p>
<p>In the first part:</p>
<pre><code>import numpy as np
dataToTreat=[]
for i in (np.arange(5)):
dataToTreat.append(i)
dataToTreatBis=dataToTreat
print(dataToTreat)
dataToTreatBis=[10,11,12,13,14]
print 'dataToTreatBis_id: ', id(dataToTreatBis)... | python | 1 |
7,448 | 72,539,248 | Calling python functions in R | <p>I have a Python file that is part of my R project currently, named functions.py. Now I have a series of functions defined in that I would like to call. How would I pass arguments into Python when calling it from R?</p>
<p>It seems that if I use <code>system('python functions.py hello world')</code> it will call the ... | <p>Here is how you can use <code>reticulate</code> with arguments:</p>
<p>your python file called <code>greeting.py</code></p>
<pre><code>def greetings(name,time):
print(f'Good {time.lower()} {name.upper()}')
</code></pre>
<p>Now source that into R:</p>
<pre><code>reticulate::source_python('greeting.py')
</code></p... | python|r|reticulate | 0 |
7,449 | 39,591,094 | Apache Lucene: How to use TokenStream to manually accept or reject a token when indexing | <p>I am looking for a way to write a custom index with Apache Lucene (PyLucene to be precise, but a Java answer is fine).</p>
<p>What I would like to do is the following : When adding a document to the index, Lucene will tokenize it, remove stop words, etc. This is usually done with the <code>Analyzer</code> if I am n... | <p>The way I was trying to solve the problem was wrong. This <a href="https://stackoverflow.com/questions/24145688/how-to-tokenize-only-certain-words-in-lucene/24152554?noredirect=1#comment66511266_24152554">post</a> and <em>femtoRgon</em>'s answer were the solution.</p>
<p>By defining a filter extending <code>PythonF... | java|python|apache|indexing|lucene | 0 |
7,450 | 39,493,182 | Two lists of JSON values -- do operation on some key | <p>I have 2 lists of dictionaries which look like this:</p>
<pre><code>x = [{'id':1,'num':5,'den':8},
{'id':2,'num':3,'den':5},
{'id':4,'num':11,'den':18},
{'id':3,'num':2,'den':81},
{'id':7,'num':10,'den':33}]
y = [{'id':1,'num':4,'den':9},
{'id':6,'num':5,'den':11},
{'id':3,'num':13,'d... | <p>You may achieve it using <code>list comprehension</code> as:</p>
<pre><code>>>> [{'id': i['id'], 'num': i['num'] + j['num'], 'den': i['den'] + j['den']} for i in x for j in y if i['id'] == j['id']]
[{'num': 9, 'id': 1, 'den': 17}, {'num': 18, 'id': 2, 'den': 33}, {'num': 15, 'id': 3, 'den': 164}, {'num': 1... | python|json|list|dictionary | 1 |
7,451 | 40,412,228 | File extension from MIME type with ;charset=UTF-8 | <p>I have a Python web crawler which is downloading files with different extensions. To get the extension from the HTTP header content type, I am using the Python library <a href="https://docs.python.org/3/library/mimetypes.html#module-mimetypes1" rel="nofollow noreferrer">mimetypes</a>.</p>
<pre><code>http_header = s... | <p>One simple way to deal with that is to split the MIME string and get only the first element.</p>
<p>The following code will return the expected result for both conditions.</p>
<pre><code>http_header = session.head(url, headers={'Accept-Encoding': 'identity'})
extension = mimetypes.guess_extension(http_header.heade... | python|http|mime-types|content-type | 1 |
7,452 | 40,546,178 | GridSearchCV: How to specify test set? | <p>I have a question regarding <code>GridSearchCV</code>:</p>
<p>by using this:</p>
<pre><code>gs_clf = GridSearchCV(pipeline, parameters, n_jobs=-1, cv=6, scoring="f1")
</code></pre>
<p>I specify that k-fold cross-validation should be used with 6 folds right?</p>
<p>So that means that my corpus is split into train... | <ol>
<li><code>GridSearchCV</code> is not designed for measuring the performance of your model but to optimize the hyper-parameter of classifier while training. And when you write <code>gs_clf.fit</code> you are actually trying different models on your entire data (but different folds) in the pursuit of the best hyper-... | python|scikit-learn|cross-validation|text-classification | 16 |
7,453 | 10,143,844 | Iterative grow a shuffled list in python | <p>I am trying to iteratively shuffle a list of 4 elements, then append the shuffled list to a growing list. The result will be a list that is some multiple of 4 elements long, with every four elements being some combination of my original list.</p>
<p>My code is </p>
<pre><code>import random
list1 = ['X','Y','Z','Q'... | <p>I think you wanted to write</p>
<pre><code>list2.extend(list1)
</code></pre>
<p>Otherwise, you would add the <strong>same</strong> instance of the object list1 to list2 over and over again.</p> | python|list|random | 5 |
7,454 | 68,073,526 | How to get rid of dictionary number when dynamically building on | <pre><code>device_total={}
user_n="Cisco"
pwd= "test"
count=1
for i in range(0,31):
ip_addr= input('Please enter the device IP address' + ' : ')
dev_type = input (" Enter device type" + ' : ')
dsum = {'device type':dev_type,'host':ip_addr,'username':user_n,'password':pwd}
d... | <pre><code>device_total=[]
user_n="Cisco"
pwd= "test"
count=1
for i in range(0,31):
ip_addr= input('Please enter the device IP address' + ' : ')
dev_type = input (" Enter device type" + ' : ')
dsum = {'device type':dev_type,'host':ip_addr,'username':user_n,'password':pwd}
d... | python|dictionary | 1 |
7,455 | 26,308,516 | Pairing data in python pandas | <p>For example, if the following is the data in pandas:</p>
<pre><code>import pandas as pd
data = {'type': ['cat2','cat1','cat2','cat1','cat2',
'cat1','cat2','cat1','cat1','cat2'],
'values': [1,2,3,1,2,3,1,2,3,5],
'experiment': [0,0,1,1,2,2,3,3,4,4]}
my_data = pd.DataFrame(data)
</c... | <p>Is this what you want?:</p>
<pre><code>>>> my_data.pivot(index='experiment', columns='type', values='values')
type cat1 cat2
experiment
0 2 1
1 1 3
2 3 2
3 2 1
4 3 5
</code></pre> | python|pandas|statistics | 2 |
7,456 | 2,290,375 | How to set pythonpath (python2.6) for tkinter on Ubuntu 9.04 (to use nltk)? | <p>I'd like to use the nltk toolkit on my machine which runs Ubuntu 9.04. I installed python 2.6.4 and several additional packages (numpy, scipy, matplotlib and of course nltk). I can import nltk, but calling a few methods gives various error masseges, all contain "please install Tkinter library".
Googling around I dis... | <p>Sounds like you forgot to install the appropriate TkInter when you installed Python 2.6.4. Install it from the same source.</p> | python|tkinter|nltk|pythonpath | 3 |
7,457 | 27,975,594 | Chained QSortFilterProxyModels | <p>Let's say I have a list variable <code>datalist</code> storing 10,000 string entities.
The <code>QTableView</code> needs to display only some of these entities. That's is why <code>QTableView</code> was assigned <code>QSortFilterProxyModel</code> that does all the filtering.
After all Proxy work is completed the <c... | <p>The code below uses two ProxyModels filtering 10,000 items. It works...
<img src="https://i.stack.imgur.com/Z6GBq.png" alt="enter image description here"></p>
<pre><code>from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class MyTableModel(QAbstractTableModel):
def __init__(self, parent=None, *ar... | python|qt|pyqt|pyside|qsortfilterproxymodel | 4 |
7,458 | 44,178,875 | Merge value of a list of tuple | <p>I have a task to read line by line in a large gzip file (> 1G) and then push raw data as messages to RabbitMQ. The value for a single field (in this case Synonyms) can be lay on different lines. So I read line by line map each line as a message and then reduce by the key (in this case the letter 'A')</p>
<p>So I ha... | <p>You can do something like</p>
<pre><code>>>> a[0][:-1] + (sum((x[-1] for x in a), []),)
('ctdbase-0.1', 'disease', 'A', 'synonyms', ['A', 'a'])
</code></pre>
<p>This assumes that all your tuples only differ in the last element. It takes the first n-1 values from the first tuple and adds all the last-eleme... | python | 1 |
7,459 | 14,097,746 | How to override the method in parent class in django Generic view | <p>I am using the class based generic views.</p>
<pre><code>class MyView(UpdateView):
model = MyModel
success_url = "/test/list"
</code></pre>
<p>Now this is working fine.</p>
<p>But i want to make the parent class so that my all views inherit from it and define <code>success_url</code> there like this</p>
... | <p>That is because you are not modifying an instance variable but a local variable by the same name.</p> | python|django | 0 |
7,460 | 13,900,865 | Duplicate Removal in a list of list | <pre><code>[
[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02],
[0.02, 0.02, 0.015],
[0.026, 0.026, 0.02, 0.02, 0.02, 0.015],
[0.021, 0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021],
[0.053, 0.052, 0.051, 0.023, 0.022],
[0.016, 0.016]
]
</code></pre>
<p>The above is a output from a list of li... | <p>Looks like the sublists are already sorted, so you can apply <a href="http://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>:</p>
<pre><code>In [1]: data = [
...: [0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02],
...: [0.02, 0.02, 0.015],
... | python|python-2.7|duplicate-removal|duplicate-data|itertools | 3 |
7,461 | 14,299,100 | Get both parent and child text with Xpath (HtmlXPathSelector) | <p>I am scraping a website, and I need to get the numerical values from this HTMLdocument:</p>
<pre><code><td>
<span style=" color: red; font-weight: bold;"> 1.950</span>
</td>
<td> 3.400</td>
</code></pre>
<p>I need to extract both 1.950 and 3.400, but I can't figure out how to do... | <p>You can try with : <code>/td//text()</code> to select every text node that are descendants of a <code>td</code></p> | python|html|xpath|scrapy | 5 |
7,462 | 34,802,791 | How to include special math symbols in QCheckBox text string? | <p>I want something like "A XOR B", where XOR is replaced by its symbol i.e. '+ enclosed in a circle'. This string has to displayed as a QLabel or QCheckBox text on the Qt window.</p>
<p>I tried many different things, include unicode, but nothing seems to work.</p> | <p>Qt4 and hence PyQt4 do support unicode characters. So all that one has to do is simply use unicode representation of the the symbol one needs. In your case it is '⊕' character. In unicode it is <a href="https://en.wikipedia.org/wiki/List_of_logic_symbols" rel="nofollow">U+2295</a>. The python code is</p>
<pre><code... | python-2.7|qt4|pyqt4 | 2 |
7,463 | 34,486,381 | Avoiding small numerical errors when using IPython | <p>I have been switching from Matlab to IPython.
In IPython, if we multiply 3.1 by 2.1, the following is the result:</p>
<pre><code>In [297]:
3.1 * 2.1
Out[297]:
6.510000000000001
</code></pre>
<p>There is a small round-off error. It is not a big problem, but it is a little bit annoying. I assume that it appeared wh... | <p>The numpy result is no more precise than the pure Python one - the floating point imprecision is just hidden from you because, by default, numpy prints fewer decimal places of the result:</p>
<pre><code>In [1]: float(np.array([3.1 * 2.1]))
Out[1]: 6.510000000000001
</code></pre>
<p>You can control how numpy displa... | python|numpy|floating-point|ipython | 3 |
7,464 | 41,798,387 | What's the best way to implement an SCPI command tree structure as Python class methods? | <p>SCPI commands are strings built of mnemonics that are sent to an instrument to modify/retrieve its settings and read measurements. I'd like to be able to build and send a string like this: <code>"SENSe:VOLTage:DC:RANGe 10 V"</code></p>
<p>With code like this:</p>
<pre><code>inst.sense.voltage.dc.range('10 V')
</co... | <p>I managed it, though I'm pretty unhappy with the results. It's been three years since I touched any of this, so I'm not sure why I did some things the way I did. I know I had a lot of trouble wrapping my head around organizing everything for portability. I'm sure that now, after a long wait, I'll be inundated with s... | python|class|interface|instrumentation | 0 |
7,465 | 47,415,989 | Python MySQLdb query parameters "IS NULL" instead of "= NULL" | <p>I'm working on a Python script to import data to a MySQL database.
I use MySQLdb to execute my queries.</p>
<p>I also use a function to set a query and its data with named parameters to be automatically replaced inside the request, such as:</p>
<pre><code>req = "SELECT * FROM sample WHERE `id` = %(id)s and `param... | <p>You can do something like the following.</p>
<pre><code>def query(params):
# Make sure it's hardcoded and malicious user can't overwrite it
param_whitelist = 'id', 'param1'
sql = '''
SELECT *
FROM sample
WHERE {placeholders}
'''
placeholders = ' AND '.join(
'`{... | python|mysql|mysql-python | 2 |
7,466 | 57,515,755 | Why does Python memory usage goes down after while? | <p>Specifically, I recently had to work with a large dataset (~3 GB) and to get a sense of the speed of the loading process (i.e. running <code>df = pd.read_csv(file)</code>), I opened a task manager.</p>
<p>As I thought, I saw my Python process' memory usage going constantly up. And around the time when it reached ap... | <p>The operating system's virtual memory subsystem may page out memory that hasn't been used in a while. Using <code>memory_usage='deep'</code> requires Pandas to scan all these objects, so they get paged back in, which causes your process's resident memory usage to increase. That's why this is slow, it has to read lot... | python|pandas|dataframe | 5 |
7,467 | 33,578,786 | How to extract substring from string in Python? | <p>So I was just wondering how I would extract <code>http://www.google.com</code> from the following string:</p>
<pre><code><div class="asdf"><a href="http://www.google.com">
</code></pre>
<p>Let's say I had a huge string with a bunch of links in there, and I wanted to extract all of the links within the ... | <p><a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags">You need an HTML Parser</a>. Example using <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow noreferrer"><code>BeautifulSoup</code></a>:</p>
<pre><code>from bs4 import BeautifulSo... | python|regex|string|parsing | 2 |
7,468 | 46,855,947 | How do you take values from dictionaries in python for calculations? | <p>I have to answer the following question:</p>
<p>8.
We have a dictionary containing several rectangular islands:</p>
<pre><code>islands = {
"Banana island" : (3,5,7,6),
"Mango island" : (10,3,19,4),
"Pineapple island" : (8,8,9,20),
"Coconut island" : (2,13,5,9)
}
</code></pre>
<p>Write co... | <p>You can use Python's <code>min</code> function with your <code>land_rectangle_area</code> function as a key to do this:</p>
<pre><code>def land_rectangle_area(x1, y1, x2, y2):
area=abs((int(x1)-int(x2))*(int(y1)-int(y2)))
return(area)
>>> min(islands.items(), key=lambda (k,t): land_rectangle_ar... | python|python-3.x|dictionary|math|area | 1 |
7,469 | 46,931,785 | Filling a dateframe in python | <p>I have so far created a data frame in python which looks like this:</p>
<pre><code> NEG_00_04 NEG_04_08 NEG_08_12 NEG_12_16 NEG_16_20 NEG_20_24 \
datum_von
2017-10-10 0 0 0 0 0 0
... | <p>I figured out</p>
<pre><code>for prod in Products:
if k == len(Products):
break
for dias in y:
df_.ix[dias, prod] = 3
k=k+1
</code></pre> | python|loops|dataframe | 0 |
7,470 | 38,043,209 | Vertices coordinates in graph-tool | <p>I'd like to specify the coordinates of the vertices of a graph in graph-tool in an efficient way.</p>
<p>Given a csv which looks like:</p>
<pre><code>Node,X,Y
1,2.5,3.8
2,3.4,2.9
</code></pre>
<p>...</p>
<p>I'd like graph-tool to plot vertex 1 at position (2.5,3.8) etc...</p>
<p>A non efficient solution is gi... | <p>I found an answer to my question, an efficient way to do this is to use the .set_2d_array() function;</p>
<pre><code>pos.set_2d_array(coordinates[['X','Y']].values.T)
</code></pre>
<p>does the trick.
Here ".T" is the transposition function, part of the numpy library.</p> | python|performance|pandas|graph|graph-tool | 1 |
7,471 | 27,480,355 | How to fix an UnboundLocalError caused due to a recursive function call in Python? | <p>I tried to convert the pseudo-code for the Maximum-Subarray problem given in Introduction to Algorithms By CLRS into a full-fledged working code in Python.</p>
<p>Code:</p>
<pre><code>def cross(A,low,mid,high):
left_sum = -float("inf")
s = 0
i = mid
while (i >= low):
s = s + A[i]
... | <p>Two really small mistakes:</p>
<ol>
<li>Your <strong>list</strong> i.e., <code>t</code> is of length 16. This means last index is 15. Thus call <code>maxSubarray(t,0,15)</code> not <code>maxSubarray(t,0,16)</code></li>
<li><code>while (j <= high)</code>. Loop until <code>j<= high</code> not until <code>j<h... | python|algorithm|divide-and-conquer|clrs | 1 |
7,472 | 36,821,930 | How to prepare my own data for tensorflow? | <p>I install Tensorflow on ubuntu 14.04. I completed <a href="https://www.tensorflow.org/versions/r0.8/tutorials/mnist/beginners/index.html#mnist-for-ml-beginners" rel="noreferrer">MNIST For ML Beginners</a> tutorial. I understood it.</p>
<p>Nor, I try to use my own data. I have train datas as T[1000][10]. Labels are ... | <p>In input_data.py, these two functions do the main job. </p>
<h1>1. Download</h1>
<pre><code>def maybe_download(filename, work_directory):
"""Download the data from Yann's website, unless it's already here."""
if not os.path.exists(work_directory):
os.mkdir(work_directory)
filepath = os.path.joi... | tensorflow|deep-learning|mnist | 1 |
7,473 | 36,875,258 | copying one file's contents to another in python | <p>I've been taught the best way to read a file in python is to do something like:</p>
<pre><code>with open('file.txt', 'r') as f1:
for line in f1:
do_something()
</code></pre>
<p>But I have been thinking. If my goal is to copy the contents of one file completely to another, are there any dangers of doin... | <p>Please note that the <code>shutil</code> module also contains <a href="https://docs.python.org/3/library/shutil.html#shutil.copyfileobj" rel="noreferrer">copyfileobj()</a>, basically implemented like Barmar's answer.</p>
<p>Or, to answer your question:</p>
<pre class="lang-py prettyprint-override"><code>from shuti... | python | 15 |
7,474 | 20,078,036 | file not found: /usr/lib/system/libdnsinfo.dylib for architecture i386 | <p>I am on MAC 10.9 with XCode 4.6.3 and have command line tools installed</p>
<p>I am trying to compile pycrypto-2.1.0 using
python setup.py build and getting following error</p>
<pre>
-----------------------------------------------------------------------------
ld: warning: ignoring file build/temp.macosx-10.6-in... | <p>Faced same issue in eclipse
Following worked for me:</p>
<p><strong>1) Find location of lib</strong></p>
<pre><code> locate libdnsinfo.dynlib
</code></pre>
<p>2) <strong>Copy and paste location to</strong> </p>
<pre><code> project > properties > C/C++ Build > Settings > MacOS X C Linker > Librarie... | python|ios|xcode|macos|pycrypto | 0 |
7,475 | 66,912,172 | Is there any difference between these 2 code? | <p>Which way is the better to use for loop?</p>
<p>Should i define the variable before using it in for loop or it's also okay to use it without defining?</p>
<pre><code>test_list = get_list()
for value in test_list:
pass
</code></pre>
<p>or</p>
<pre><code>for value in get_list():
pass
</code></pre> | <p>They're going to be equivalent. Python won't call <code>get_list()</code> during every iteration, only for the first.</p> | python|for-loop|variables|syntax | 0 |
7,476 | 48,018,784 | How to get single backslash instead of double backslash with encode("unicode-escape")? | <p>Get unicode point of character <code>Ä</code>.<br>
Python3 version. </p>
<pre><code>>>> str="Ä"
>>> str.encode("unicode-escape")
b'\\xc4'
</code></pre>
<p>How to get the single backslash format <code>b'\xc4'</code> instead of <code>b'\\xc4'</code> as my output ?</p> | <p>It's not entirely clear to me what you want, so I'll give you a few options.</p>
<p>Get the (Unicode) code point of a character as an integer:</p>
<pre><code>>>> ord('Ä')
196
</code></pre>
<p>Display the integer in hex notation:</p>
<pre><code>>>> hex(ord('Ä'))
'0xc4'
</code></pre>
<p>or with ... | python-3.x|unicode | 0 |
7,477 | 51,350,110 | Importing the views from my app in the project | <p>So im just starting with Django framework and i cannot explain myself why i can't import the views from my app, im watching one course online and im doing the exact same thing but it won't work, anyone help?<a href="https://i.stack.imgur.com/F5VhH.png" rel="nofollow noreferrer">Here is screenshot</a></p> | <p>First of mark the folder as a sources root in pycharm, so you get the correct indexing when trying to import it.</p>
<p>Next up make sure that polls is listed in <code>INSTALLED_APPS</code></p>
<p>When developing with python, it's better practice to be explicit rather than implicit, it "might" be better to correct... | django|python-3.x | 2 |
7,478 | 51,557,452 | Keys with same name with multiple Values in python | <p>I am practicing myself in python online and have come across this question.</p>
<p><a href="https://www.testdome.com/questions/python/file-owners/11846?visibility=1&skillId=9" rel="nofollow noreferrer">https://www.testdome.com/questions/python/file-owners/11846?visibility=1&skillId=9</a></p>
<p>I dont know... | <p>One way is to put the value in the list for "Randy", as in dictionary we can't have multiple keys of same name. Here is the solution for the same,</p>
<pre><code>class FileOwners:
@staticmethod
def group_by_owners(files):
d={}
for i in files:
if files[i] in d:
d[files... | python|dictionary | 1 |
7,479 | 51,460,046 | Python 3 localhost connection | <p>I'm trying to run the below program but I keep getting connection error's:</p>
<pre><code>from socket import *
from codecs import decode
HOST = 'localhost'
PORT = 5000
BUFSIZE = 1024
ADDRESS = (HOST, PORT)
server = socket(AF_INET, SOCK_STREAM)
server.connect(ADDRESS)
dayAndTime = decode(server.recv(BUFSIZE), 'asc... | <p>If your book doesn't mention the other half of sockets, you need a better book.</p>
<p>Socket basics are easy. You have one process <strong>listen</strong> on a port, waiting for connections. Commonly we'll call this a 'server'. Another process (perhaps on the same machine, perhaps remote) attempts to <strong>conne... | python|python-3.x | 2 |
7,480 | 64,309,431 | Ansible not finding custom python modules on remote server | <p>I am trying to call a python function from another script in a different directory. Have a playbook to execute this.</p>
<p>This works fine on localhost but on remote_server it is failing with "ModuleNotFoundError: No module named 'script2'"</p>
<h1>Here are my scripts:</h1>
<pre><code>[root@server Test]# ... | <p>As explained in module <code>script</code> document : <em>The local script at path will be transferred to the remote node and then executed</em>.</p>
<p>Any imported files in script will not, you must copy them before on remote with module <code>copy</code>.</p>
<p>Example (adapt access modes and path if needed) :</... | python|ansible | 2 |
7,481 | 55,768,915 | conversion between lists and arrays in python | <p>Hi I have a decoder that accepts the following 1D vector structure and it reads from a json file </p>
<pre><code>[423.99115959756097, 113.56845980228232, 429.4810943320526, 105.55707869260885, 411.09109879247507, 105.04387943256503, 444.51020250865184, 111.46554256405251, 395.02871954830175, 110.45595140768442, 455... | <p>If you simply want a Python list, then:</p>
<pre><code>list_of_list = [[102.14354944229126, 278.29406929016113, 93.47736525535583, 286.3470059633255, 92.25288438796997, 271.6073254644871, 94.68143308162689, 296.2039098739624, 94.90646886825562, 269.15104579925537, 122.17410278320312, 316.0685751438141, 124.30206298... | python|arrays|python-3.x|list|numpy | 0 |
7,482 | 55,910,769 | SciKit Gradient Boosting - How to combine predictions with initial table? | <p>I'm trying to use a gradient-boosting model to predict future scores in fantasy football - for now only looking at the 2 previous rounds. Currently, if a player is expected to score more than 6 points, the model would return '1', otherwise '0' - indicating whether the player would be a good captain choice or not. </... | <p>I'm assuming you are using pandas DataFrames, in which case it's quite straightforward.</p>
<p>The index numbers in your X_train and X_test DataFrames will correspond to the index in your original 'ds' DataFrame.</p>
<p>Try:</p>
<pre><code>pred = baseline.predict(X_test)
pred_original_data = ds.iloc[X_test.index]... | python|pandas|machine-learning|scikit-learn | 2 |
7,483 | 55,890,858 | How to pass a Dynamic String value from Python to html in a folium based Map? | <p>I am trying to create a map with dynamic information for all map markers. For example Map with markers for restaurants in an area that displays Name, Pic & other information relevant to that restaurant.</p>
<p><strong>Problem:</strong> How do I pass a dynamic string value from Python to HTML for each marker in ... | <p>Try this: </p>
<pre><code>var_name = 'restaurant_name'
var_loc = 'restaurant_location'
# var_picture = <base64 image data>
html = f'''<img ALIGN="Right" src="data:image/png;base64,{var_picture}">\
<h1>Name: </h1>{var_name}<br />\
<h2>Location: </h2>{var_loc}<br />\
... | python|html|python-3.x|folium | 2 |
7,484 | 55,753,391 | Append matplotlib histogram plots to a list, without overwriting | <p>I am trying to write a function, such that it creates multiple histograms(using matplotlib.pyplot) using a for loop on some data. I append these plots to a list, and the list is returned.
But when I try to use show() on each of the plots, they are all the same plot, and all the plots are being overwritten.</p>
<p>I... | <p>First, maybe we should question the need: why do you want to keep all plots at hand? Why not save them after plotting <code>plt.savefig('xxxxx')</code>? Are you planning to animate all of the figures?</p>
<p>Second, if we want to keep all figures, <code>subplots</code> might be a handy tool. Note that you are still... | python-3.x|matplotlib | 0 |
7,485 | 73,468,614 | Adding python script to Scheduled Task | <p>I'm trying to add a python script to Scheduled Task in Windows.
There are 2 ways and none of it doesnt work.
<strong>First solution:</strong>
added to a batch file the call of my python script</p>
<pre><code>python.exe hello_world.py
</code></pre>
<p>in the Scheduled task - Program\script - the path to this bat file... | <p>Dont forget to check access rights to folder where you're py script is located.</p> | python|task|scheduler | 0 |
7,486 | 50,004,310 | Convert python dictionary to uppercase | <p>For some reason my code refuses to convert to uppercase and I cant figure out why. Im trying to then write the dictionary to a file with the uppercase dictionary values being inputted into a sort of template file. </p>
<pre><code>#!/usr/bin/env python3
import fileinput
from collections import Counter
#take every ... | <p>In python 3 you cannot do that:</p>
<pre><code>for k,v in newDict.items():
newDict.update({k.upper(): v.upper()})
</code></pre>
<p>because it changes the dictionary while iterating over it and python doesn't allow that (It doesn't happen with python 2 because <code>items()</code> used to return a <em>copy</em>... | python|python-3.x|file|dictionary|file-io | 17 |
7,487 | 64,672,654 | How to move array values to a new column, based on duplicate values in a different column | <p>I'm using python with numpy and pandas and I have a dataframe that looks like this:</p>
<pre><code>index title Time Y
0 Part1 0.5 -117
1 Part1 1.0 -118
2 Part1 1.5 -137
3 Part1 2.0 -123
4 Part2 0.5 -97
5 Part2 1.0 -94
6 Part2 1.5 -95
7 Part2 2.0 -99
</code></pre>
<p... | <p>I think you need to use the <code>pivot</code> method:</p>
<pre><code>df.pivot(index="time", columns=["title"]).reset_index()
</code></pre>
<p>You can find more about it in the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferre... | python|pandas|numpy|dataframe | 0 |
7,488 | 64,744,219 | How to enter text in an iframe with Selenium and Python | <p>I'm trying to use Selenium with Python to automate logging in to Autodesk GBS. I've been able to access the "Sign In" frame like this:</p>
<pre><code>driver.get("https://gbs.autodesk.com/GBS/")
btn = driver.find_element_by_link_text('Sign In')
btn.click()
</code></pre>
<p>I can't seem to access ... | <p>The iframe tag specifies an inline frame; It is used to embed another document within the current HTML document.</p>
<p>Before acting on elements inside iframes, we have to switch to it using</p>
<pre><code>driver.switch_to.frame(iframe reference)
</code></pre>
<p>In this case, iframe is</p>
<pre><code><iframe fr... | python|selenium|selenium-webdriver|iframe|webdriver | 1 |
7,489 | 53,186,793 | How to plot weights of fully connected layer? | <p>I am using a a fully connected network with 4 input and 2 output nodes. I store the Weights of my network after completely training it. Suppose here is my weight matrix</p>
<pre><code>`W = np.array([[0.8,0.02],[0.5,0.4],[0.3,0.2],[0.1,0.7]])`
</code></pre>
<p>I want to visualize that what weights each class has ad... | <p>You should use TensorBoard for this. Also, you should not need to store the weights manually, as they are stored by TensorFlow. You can access them in a couple of different ways, such as with <code>tf.trainable_variables()</code>, or <code>tape.watched_variables()</code> in eager mode. Then its just a matter of loop... | tensorflow|matplotlib | 0 |
7,490 | 65,218,533 | one-dimesion numpy.sum returns 1 | <p>I have numpy one-dimension array like this:</p>
<pre><code>array([0.6441961 , 0.36957273, 1. , 0.4898495 , 0.24318133,
0.3721704 , 0.3205053 , 0.16859561, 0.26045567, 0.5081331 ,
0.66135716, 0.63181865])
</code></pre>
<p>My code is below, simply shows the variable.</p>
<pre><code>print(a)
print(np.sum(a... | <p>You want:</p>
<pre><code>int(a.sum())
</code></pre>
<p>or</p>
<pre><code>a.sum.astype('int16') # totally didn't see @DaniMesejo's answer before I edited this in
</code></pre>
<p>What's wrong:</p>
<p><code>np.sum(a, dtype='int16')</code> casts <code>a</code> to <code>int16</code> <em>before</em> summing. And castin... | python|numpy | 4 |
7,491 | 65,233,005 | How to read a delimited file using Spark RDD, if the actual data is embedded with same delimiter | <p>I am trying to read a text file into an rdd</p>
<p>My sample data is below</p>
<pre><code>"1" "Hai How are you!" "56"
"2" "0213"
</code></pre>
<p>3 columns with Tab delimiter. My data is also getting embedded with same delimiter(How\tHow... | <p>Use <code>shlex.split()</code> which ignores quoted delimiters:</p>
<pre><code>import shlex
sc.textFile('Mytext.txt').map(lambda line: shlex.split(line))
</code></pre>
<p>Another example with string:</p>
<pre><code>import shlex
rdd = sc.parallelize(['"1"\t"Hai\tHow are you!"\t"56"']).... | python|apache-spark|pyspark|rdd | 1 |
7,492 | 68,567,640 | Selenium webdriver retrieves an empty list | <p>I have this piece of code:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.firefox.options import Options as FirefoxOptions
firefox_options = FirefoxOptions()
firefox_options.add_argument("--headless")
driver = webdriver.Firefox(executable_path = "../../bin/geckodriver", opt... | <p>You are missing a delay before getting the elements list.<br />
The desired web elements should be fully loaded before accessing them.<br />
The simplest way to make your code work will be by simply adding some delay:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.firefox.options import Option... | python-3.x|selenium|webdriverwait | 1 |
7,493 | 62,569,955 | Calculate the area under the histogram with Seaborn | <p>I am trying to calculate the area under the histogram with seaborn using this function (data are normalised)</p>
<pre><code>sum (np.diff(bins_sns)*values_sns)
</code></pre>
<p>to get the width of the bins and values of the height I am using</p>
<pre><code>values_sns=[h.get_height()for h in sns.distplot(data).patches... | <p>Several things are going wrong here:</p>
<ul>
<li><code>sns.distplot(data)</code> creates a histogram (together with a kdeplot); in the code above it is called twice, so creating two histograms on the same spot</li>
<li><code>sns.distplot(data)</code> returns the <code>ax</code> on which it plotted; an <code>ax</cod... | python|histogram|seaborn|area | 1 |
7,494 | 61,678,924 | Can you explain difference between tensorflow loading and hdf5 loading in keras model | <p>I was trying to load the keras model which I saved during my training.So I went to <a href="https://keras.io/api/models/model_saving_apis/#save_model-function" rel="nofollow noreferrer">keras documentation</a> where I saw this.</p>
<blockquote>
<p>Only topological loading (by_name=False) is supported when loading... | <p>For clarity purpose let's consider two cases.<br>
Case 1: Simple model, and<br>
Case 2: Complex model where user-defined classes inherited from <code>tf.keras.Model</code> were used.</p>
<h3>Case 1: Simple model (as in keras Functional and Sequential models)</h3>
<p>When you save model weights (using <code>model.s... | python|tensorflow|keras|computer-vision|machine-learning-model | 3 |
7,495 | 60,591,786 | How to create a django model for JSONField that takes values from other fields from the same table? | <p>I am writing a model in django which looks like this:</p>
<pre><code>name = models.CharField(max_length=50)
address = models.CharField(max_length=100)
info = JSONField()
</code></pre>
<p>Question:
For POST request, I will provide name and address as json. Now how should I store name and address in their respective... | <p>This is more or less how I create my post requests:</p>
<pre><code>class MyPostView(View):
def post(self, request):
# Get request data
data = json.loads(request.body)
# Extract the values I need
name = data.get('name')
address = data.get('address')
# If the inf... | python|mysql|django | 0 |
7,496 | 71,116,054 | understanding of some Luigi issues | <p>Look at class ATask</p>
<pre><code>class ATask(luigi.Task):
config = luigi.Parameter()
def requires(self):
# Some Tasks maybe
def output(self):
return luigi.LocalTarget("A.txt")
def run(self):
with open("A.txt", "w") as f:
f.write(... | <ol>
<li><p>No, luigi won't start executing TaskB until TaskA has finished (ie, until it has finished writing the target file)</p>
</li>
<li><p>If you want to get a detailed response for <code>luigi.build</code> in case of error, you must pass an extra keyword argument: <code>detailed_summary=True</code> to build/run m... | python|error-handling|pipeline|luigi | 1 |
7,497 | 56,820,357 | How to customize "--help" with Click? | <p>Help messages in Click are <a href="https://click.palletsprojects.com/en/7.x/quickstart/#basic-concepts-creating-a-command" rel="nofollow noreferrer">accessed via the long option <code>--help</code></a> by default. How can I also make the short option <code>-h</code> available?</p> | <p>Use <code>context_settings</code> with <code>help_option_names</code>:</p>
<pre><code>CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
def cli():
pass
</code></pre>
<p>This is straight out of <a href="https://click.palletsprojects.com/en/7.x/documen... | python|python-click | 0 |
7,498 | 66,086,043 | python get Object inside Object property by text | <p>i have an object which hold object
Example :</p>
<pre><code>class db_foo_mng
db_user = "test"
def __init__(self):
pass
class rdata:
db_foo = None
def __init__(self):
self.db_foo = db_foo_mng()
pass
</code></pre>
<p>and i can access it like this with no problem :</p>... | <p>If you have a variable which belongs to an instance of the class, then you can use the <code>__dict__</code> to access it using the string.</p>
<p>If the variable in question is a <code>class variable</code> (like yours) then you can't even use the <code>__dict__</code> to get the attributes.</p>
<p>However the vars... | python-3.x|oop|object | 0 |
7,499 | 65,915,427 | Return webpage having a plot in Flask | <p>I have this route in my flask app which takes a file name and sprint number from the user through a form (burndown_form.html). It calls a function "burndown_gen" using these params which returns a python data frame. I need to display a plot based on this dataframe on a web page after the user clicks the su... | <p>One way to do it would be to store the plot as a figure in the static folder of your Flask app folder structure and then display it on using an image reference in your html template. Something like this:</p>
<pre><code>fig = df_b.plot.line(x='Date',y='Story Points Left',figsize=(10,5)).get_figure()
fig.savefig('stat... | python|html|matplotlib|flask | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.