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
8,900
66,766,386
In Airflow, how do I execute a task only if my Variable.get("ENVIRONMENT") = "PROD"?
<p>Example:</p> <p>There are 2 different environments: development and production.</p> <pre><code>**IMPORT &lt;everything&gt; env = Variable.get(&quot;ENVIRONMENT&quot;) ... ... ... default_args... WITH DAG( dag_id = '...', catchup= False, schedule_interval= '00 4 * * *', ) a = BigQueryOperator( task_id = '...', sql = ...
<p>There are two ways to accomplish what you want:</p> <ol> <li><p>Read the variable while parsing the DAG file and only create the task b if the variable is set to the correct string value. This could be done with a simple conditional in the DAG.</p> </li> <li><p>Use a ShortCircuitOperator to skip task b based on the ...
python|google-cloud-platform|airflow|airflow-scheduler
0
8,901
67,041,108
How can I add "http" to the "src" attributes?
<p>I am trying to scrape content from some websites, this is the websites HTML:</p> <pre><code>&lt;div class=&quot;answer-given-body ugc-base&quot;&gt; &lt;p&gt;&lt;img alt=&quot;&quot; src=&quot;//d2vlcm61l7u1fs.cloudfront.net/media%2F61d%2F61d6042d-e4dd-41d9-9a5c-0ceb481ddbc9%2FphpKFGb9B.png&quot;/&gt;&lt;img alt=&...
<p>To add &quot;https&quot; to the tags <code>src</code>, you can access the <code>src</code> attribute using <code>[]</code> and and &quot;https&quot; as follows:</p> <pre><code>from bs4 import BeautifulSoup html = &quot;&quot;&quot; &lt;div class=&quot;answer-given-body ugc-base&quot;&gt; &lt;p&gt;&lt;img alt=&qu...
python|beautifulsoup|python-requests
0
8,902
72,334,113
Django Generate Excel and save as Object with Celery and RabbitMQ
<p>I am using Django 2.2.5, Celery 5.2.6 and RabbitMQ and I am new to the last 2.</p> <p>I want to generate an Excel sheet and store it in a FileField inside a newly created object (not download it), and this is what I did:</p> <p>project/settings.py:</p> <pre><code>CELERY_RESULT_BACKEND = &quot;django-db&quot; CELERY_...
<p>Here's the solution:</p> <pre><code>from io import BytesIO from django.core.files.base import ContentFile vworkbook = BytesIO() workbook.save(vworkbook) content = vworkbook.getvalue() try: Export.objects.create( status=&quot;Dossiers archivés&quot;, file=ContentFile( content, name=...
python|django|excel|rabbitmq|celery
0
8,903
50,996,321
SQLAlchemy: What is the best way to validate a model before inserting or updating
<p>I'm trying to validate a SQLAlchemy model before it is inserted or updated, e.g</p> <pre><code>class MyModel(db.Model): foo = db.Column(db.String(255)) bar = db.Column(db.String(255)) </code></pre> <p>I've tried a few approaches, but none seem to work. One possibility was to listen to <code>before_insert</...
<p>Use the provided validation decorator. See: <a href="https://docs.sqlalchemy.org/en/14/orm/mapped_attributes.html#simple-validators" rel="nofollow noreferrer"><code>sqlalchemy.orm.validates</code></a></p> <p>Example:</p> <pre><code>from sqlalchemy.orm import validates class MyModel(...): # ... status ...
python|database|orm|sqlalchemy
0
8,904
51,104,648
Pytorch gradients exist but weights not updating
<p>So, I have a deep convolutional network with an lstm layer, and after the ltsm layer it splits off to compute two different functions (using two different linear layers) whose results are then added together to form the final network output. </p> <p>When I compute the loss of the network so that I can have it compu...
<p><a href="https://discuss.pytorch.org/t/gradients-exist-but-weights-not-updating/20484/2?u=wr01" rel="nofollow noreferrer">https://discuss.pytorch.org/t/gradients-exist-but-weights-not-updating/20484/2?u=wr01</a> has the answer I sought. The problem was that <code>neuralnet.parameters()</code> does not clone the list...
python|neural-network|conv-neural-network|lstm|pytorch
3
8,905
50,865,222
Trying to learn tensorflow.js but need a simpler example like brain.js
<p>The examples for brain.js allowed me to understand the software really well - and various aspects of machine learning.</p> <p>It's hard to replicate the same kind of code now that I'm trying to learn tensorflow.js.</p> <p>For example, what is the TensorFlow equivalent to the following brain code?</p> <pre><code>v...
<p>This would be a kind of simplified version of your provided example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const net = tf.sequential(); net.add(tf.layers.dense({ ...
javascript|node.js|tensorflow.js|brain.js
9
8,906
3,497,270
Defining path to module's configuration files
<p>A Python module I'm developing has a master configuration file in <code>/path/to/module/conf.conf</code>. The <code>/path/to/module</code>/ depends on the platform (for instance, <code>/Users/me/module</code> in OS X, <code>/home/me/module</code> in Linux, etc).</p> <p>Currently I define the <code>/path/to/module</...
<p>Inside of your <code>__init__.py</code>, you could get the directory where the <code>__init_.py</code> script lives using the <code>__file__</code> magic variable like so:</p> <pre><code>from os.path import dirname ROOT = dirname(__file__) </code></pre> <p>Then you know that <code>conf.conf</code> will be located ...
python|configuration|cross-platform
2
8,907
50,252,213
udemy course ai cannot continue installation matplotlib.pyplot
<p>great thanks but nnow when i do pip3 install pyplot</p> <p>it says: could not find a version that satisfies the requirement pyplot</p> <p>Sorry quite noob still in this area but willing to do great things :)</p>
<p><code>pip install numpy</code> usually does the trick. Note, that you have to be in <code>venv</code> already when doing it, otherwise it tries to load it to outside of the virtual environment.</p> <p>What comes to "matplotlib.pyplot" <code>pyplot</code> and <code>matplotlib</code> are separate modules.</p> <p>-><...
python|linux|ubuntu
-1
8,908
50,546,027
Filter column value from multiple csv files using python(pandas)
<p>CITY_DATA = { 'chicago': 'chicago.csv','new york city': 'new_york_city.csv','washington': 'washington.csv' }</p> <p>Asks user to specify a city, month, and day to analyze.</p> <pre><code>Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no mon...
<p>This is the data analysis project for Udacity. This is how I did it. </p> <pre><code>import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks use...
python|pandas|filter
0
8,909
35,041,522
create list with negative value permutation
<p>Can anyone help with creating lists with negative values out of a given list?</p> <p>For example:</p> <pre><code>values = [1, 2, 3] </code></pre> <p>Desired output would be </p> <pre><code>[[-1, 2, 3], [1, -2, 3], [1, 2, -3],[-1, -2, 3], [1, -2, -3], [-1, 2, -3], [-1, -2, -3]] </code></pre>
<p>Produce the product of 3 times <code>[1, -1]</code> and multiply the result with your input list:</p> <pre><code>from itertools import product values = [1, 2, 3] [[num * mul for num, mul in zip(values, combo)] for combo in product([1, -1], repeat=len(values))] </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; ...
python|list|permutation
2
8,910
26,635,786
I need to reverse the output format of a printed triangle using O's
<p>I need to reverse the output format of a printed triangle using O's</p> <p>my code is</p> <pre><code>userRows=int(input("Enter a positive number less than or equal to 20!")); while((userRows&gt;21) or (userRows&lt;0)): userRows=int(input("Try again! Please enter a positive number less than or equal to 20.")...
<p>print n(user input - number of iteration )white space before print 'o' </p> <pre><code>def displayTriganle(userInput): [print(' '*(userInput-i)+ 'o'*i) for i in range(1,userInput+1)] o oo ooo oooo ooooo ooo...
python|formatting|output
0
8,911
26,896,662
Errno 2: No such file or directory: Python
<p>I am writing a loop to plot data using matplotlib. to start, I have </p> <pre><code>path = os.listdir('/users/me/path_to_folder_with_data') for file in path: code that I know works for plotting data </code></pre> <p>But when I run this, I get an error that says <code>[Errno 2] No such file or directory: 'data1...
<p>You need to join the path to the directory</p> <pre><code>location = '/users/me/path_to_folder_with_data' for file in os.listdir(location): fullPath = os.path.join(location, file) # now try to open fullPath </code></pre>
python|matplotlib|data-analysis
2
8,912
61,464,371
Back Button in Python, I want to go back to the main window
<p>I have some problems with my code. I wanted to make a back button and I have an error when I display my window. My goal is to make a catalog in which the user can push some buttons and interact with the product. But when you push the button this error comes out. </p> <pre><code>Exception in Tkinter callback Traceba...
<p><em>The error <code>_tkinter.TclError: bad window path name</code> triggers when you destroy any window with tkmacosx <code>Button</code>.</em> This issue has been fixed with the latest update to <a href="https://pypi.org/project/tkmacosx/" rel="nofollow noreferrer">tkmacosx (0.1.3)</a>. </p> <p>By updating the pac...
python|button|tkinter|back
0
8,913
60,411,773
How to remove the quotes around the value in the string representation of a dict?
<p>How can I not print the quotes around a string? I understand that this is a string, as a result Python is adding the quotes.</p> <p>To give more context:</p> <pre class="lang-py prettyprint-override"><code>def a(content): return {'row_contents': content} print(a("Hello")) </code></pre> <p>This gives output a...
<p>you can ues <code>f string</code></p> <pre><code>def a(content): return f"{{'row_contents': {content}}}" print(a("Hello")) </code></pre> <p>or just this:</p> <pre><code>def a(content): return "{'row_contents':"+content+"}" </code></pre> <p>Output:</p> <pre><code>{'row_contents': Hello} </code></pre>
python|dictionary|repr
1
8,914
18,388,538
How to auto-close xml tags in truncated file?
<p>I receive an email when a system in my company generates an error. This email contains XML all crammed onto a single line. </p> <p>I wrote a notepad++ Python script that parses out everything except XML and pretty prints it. Unfortunately some of the emails contain too much XML data and it gets truncated. In genera...
<p>Use <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">Beautiful Soup</a></p> <pre><code>&gt;&gt;&gt; import bs4 &gt;&gt;&gt; s= bs4.BeautifulSoup("&lt;asd&gt;&lt;xyz&gt;asd&lt;/xyz&gt;") &gt;&gt;&gt; s &lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;asd&gt;&lt;xyz&gt;asd&lt;/xyz&gt...
python|xml|notepad++
5
8,915
18,457,678
Python, write in memory zip to file
<p>How do I write an in memory zipfile to a file? </p> <pre><code># Create in memory zip and add files zf = zipfile.ZipFile(StringIO.StringIO(), mode='w',compression=zipfile.ZIP_DEFLATED) zf.writestr('file1.txt', "hi") zf.writestr('file2.txt', "hi") # Need to write it out f = file("C:/path/my_zip.zip", "w") f.write(z...
<p><a href="http://docs.python.org/2/library/stringio.html#StringIO.StringIO.getvalue"><code>StringIO.getvalue</code></a> return content of <code>StringIO</code>:</p> <pre><code>&gt;&gt;&gt; import StringIO &gt;&gt;&gt; f = StringIO.StringIO() &gt;&gt;&gt; f.write('asdf') &gt;&gt;&gt; f.getvalue() 'asdf' </code></pre>...
python|zip|stringio
37
8,916
71,555,412
Replacing acronyms with their full forms in Python
<p>I have an acronym dictionary that has <code>keys</code> as an acronym and <code>values</code> as full forms.</p> <p>I want to replace the acronyms found in the <code>text_list</code> with the full forms to arrive at the <code>ouput_list</code></p> <pre><code>acronym_dict = { 'QUO': 'Quotation', 'IN': 'India'...
<p>You might use <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow noreferrer"><code>re.sub</code></a> for this task by delivering function as 2nd argument following way</p> <pre><code>import re acronym_dict = { 'QUO': 'Quotation', 'IN': 'India', 'SW': 'Software', 'RE': 'Regular E...
python|regex
2
8,917
71,563,220
How do I iterate through nested pandas dataframe by column?
<p><strong>Problem:</strong> I have a 1 row dataframe <code>dfA</code> whose column length can vary, within each cell contains a json object. All fields in each json object are the same.</p> <p>I'm trying to write code that loops through each cell, parses the JSON object, and loads ALL data into 1 single dataframe <cod...
<p><code>dfA[0]</code> only gets the first column. You should convert you dataframe first row to list then feed the result to <code>pd.json_normalize()</code></p> <pre class="lang-py prettyprint-override"><code>pd.json_normalize((dfA.iloc[0, :].values)) </code></pre>
python|pandas|dataframe|for-loop|iteration
0
8,918
71,682,367
Convert list with one item to item itself in dict value
<p>For example, there is a dictionary with key-value pairs, where the values are lists with different &quot;content&quot;. Some lists have only one element. These elements can be different types of data.</p> <p><strong>Question:</strong> What is the most efficient way to convert list type key values with one element in...
<p>In order to tackle this problem, I concentrate on how to convert the value: I create a function called <code>delist</code> to delete the list with 1 element:</p> <pre class="lang-py prettyprint-override"><code>def delist(value): while isinstance(value, list) and len(value) == 1: value = value[0] if v...
python|python-3.x|list|dictionary|one-liner
4
8,919
69,384,050
Python ModuleNotFoundError for my main package
<p>This is a follow up question for a <a href="https://stackoverflow.com/a/68936664/9977758">question I asked not long ago</a>. The answer is correct and works great, but when I tried to apply it to the main package it didn't work.</p> <p>Lets say I have the following files structure:</p> <pre><code>a/ -&gt;b/ -&gt;c...
<p>You can backwardly add folder <code>b</code> to your path and then import only from <code>c</code> folder, like this:</p> <pre class="lang-py prettyprint-override"><code>from os.path import realpath, dirname import sys sys.path.append(dirname(dirname(realpath(__file__)))) from c import script1 </code></pre>
python|python-3.x|import
1
8,920
57,460,506
Python pandas pivot vs pivot_table
<p>If I have a multiindex DataFrame in Pandas, if I read through the documentation of <code>pivot</code> and <code>pivot_table</code> I cannot seem to find the reason why <code>pivot</code> doesn't work in this example. Clearly I am missing something, but it takes the same parameters and seems to suggest that it would ...
<p>Here function <code>pivot</code> not working with <code>MultiIndex</code>, solution is <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>DataFrame.reset_index</code></a> for convert levels to columns:</p> <pre><code>print(df.reset_i...
python|pandas|dataframe|pivot|pivot-table
0
8,921
42,322,828
Alternatives to decorators for saving metadata about classes
<p>I'm writing a GUI library, and I'd like to let the programmer provide meta-information about their program which I can use to fine-tune the GUI. I was planning to use function decorators for this purpose, for example like this:</p> <pre><code>class App: @Useraction(description='close the program', hotkey='ctrl+...
<p>You are using decorators to add meta data to methods. That is fine. It can be done e.g. this way:</p> <pre><code>def user_action(description): def decorate(func): func.user_action = {'description': description} return func return decorate </code></pre> <p>Now, you want to collect that data ...
python|python-3.x|decorator
3
8,922
54,017,404
from nltk.util import Trie ImportError: cannot import name Trie
<p>I am new in <code>NLP (Natural Language Processing)</code>, I have installed <code>NLTK</code> on my computer and I have downloaded all the packages using <code>nltk.download()</code></p> <blockquote> <p>My Script</p> </blockquote> <pre><code>from nltk.tokenize import sent_tokenize example_text = "Hello Mr. Sha...
<p>I can see that your script is named test.py, but I'm wondering if at any point you created a tokenize.py file? Try removing any tokenize.pyc and renaming any tokenize.py file. I had this same issue just now. Upon renaming the file it worked.</p> <p>Also note that you will have to import nltk before being able to ca...
python|nlp|nltk
1
8,923
58,555,258
Tensorflow object detection API and images size
<p>I'm practicing with computer vision in general and specifically with the TensorFlow object detection API, and there are a few things I don't really understand yet.</p> <p>I'm trying to re-train an SSD model to detect <strong>one class</strong> of custom objects (guitars).<br> I've been using <em>ssd_mobilenet_v1_co...
<p>I am not sure for the answer I am giving below but it worked for me, as you correctly said that images are resized to 300x 300 in the config file of ssd_mobilenet-v2, what this resizing does is compress image to 300 x 300 thus loosing the important features. This adversely effect the object that are small in size as...
python|tensorflow|object-detection|object-detection-api
1
8,924
58,455,750
cv.GetSubRect migration to OpenCV 4
<p>OpenCV used to have function GetSubRect see e.g. <a href="https://docs.opencv.org/2.4/modules/core/doc/old_basic_structures.html" rel="nofollow noreferrer">https://docs.opencv.org/2.4/modules/core/doc/old_basic_structures.html</a></p> <p>So the following lines where valid:</p> <pre><code>top = cv.GetSubRect(tmp, (...
<p>The first part I could answer my self now:</p> <p><strong>Code:</strong></p> <pre><code>def getSubRect(self,image,rect): x,y,w,h = rect return image[y:y+h,x:x+w] </code></pre> <p><strong>test:</strong></p> <pre><code>def test_getSubRect(): image=cv2.imread(&quot;testMedia/chessBoard001.jpg&quot;,1) s...
python|opencv
3
8,925
45,379,338
BeautifulSoup+HTML+Regex = ...Nothing?
<p>I'm trying to make a webscraper that gets some information (in this case a phone number). In order to get the phone number, I'm using a self-created and tested regex (using RegExr) to search for the phone number, which is here (accounting for country code (+1 in the USA), parentheses, etc.)</p> <pre><code>regexPhon...
<p>Added raw string to regex and extracted only text from <code>soup</code> using <code>soup.get_text()</code>.</p> <pre><code>regexPhone = re.compile(r"(\+?1[-.\s]?)?(([0-9]{3}|(\([0-9]{3}\)))[-.\s]?[0-9]{3}[-.\s]?[0-9]{4})|[0-9]{11}|[0-9]{10}|[0-9]{7}") soup = BeautifulSoup(request.content, "html.parser") text = so...
python|html|regex|beautifulsoup
0
8,926
28,750,070
Displaying binomials and matrices using asciimath with mathjax
<p>I'm trying to display different math problems using asciimath and mathjax. However some things does not seem to be supported in asciimath. For instance I'm trying to display a binomial/matrix and I can't really figure out how to do it. Would I have to use latex or mathml to do this, or is there a way to use asciimat...
<p>You can use</p> <pre><code>([1],[3]) </code></pre> <p>to get a matrix with two rows of one element each surrounded by parentheses. That may be what you want, though it may be too tall for use with in-line expressions.</p>
python-3.x|mathjax|asciimath
2
8,927
14,723,861
mySQLdb select formatting?
<pre><code>c.execute("select a, c, d from table") for row in c: print(row) </code></pre> <p>Whenever I go this, the output is always:</p> <pre><code>('text field 1', 'text field 2', 'text field 3', 'text field 4') </code></pre> <p>I've been googling and cannot find the answer, is there a way I can make it like</...
<p>You printed the whole row, which is a tuple. To print it with a little formatting, you could use <a href="http://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow"><code>''.join()</code></a>:</p> <pre><code>', '.join(row) </code></pre>
python|string-formatting|mysql-python
3
8,928
14,703,547
How to quickly access all values corresponding to a specific second level key regardless of first level key in a Python dictionary?
<p>I have a Python Dictionary like:</p> <blockquote> <p>Mydict = {'a': {'y': 1, 'x': 5}, 'b': {'y': 10, 'x': 8}}</p> </blockquote> <p>Is there any quick way to access the values corresponding to the key: 'x', which in this case is a second level key, regardless of the first level key?</p> <p>I know it can be don...
<p>Using <a href="http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list-comprehension</a>:</p> <pre><code>mylist = [v['x'] for v in Mydict.values()] </code></pre> <p>Since you do not need the outer keys, you just iterate over the inner dicts, and get the desired <co...
python|dictionary
6
8,929
14,454,744
Does it make sense to install my Python unit tests in site-packages?
<p>I'm developing my first Python distribution package. My learning curve on Python packaging seems to be leveling off a bit, but I'm still wrestling with a few open questions. One is whether I should cause my unit tests to be installed alongside my code.</p> <p>I understand <a href="https://stackoverflow.com/question...
<p>In my opinion the right answer is NO but you will find quite a few distributions that install the tests. Tests shouldn't be installed but they should be included in the source distribution. In my opinion in an ideal world testing installed packages should be a task performed by the package manager (pip) and the <cod...
python|unit-testing|installation|setuptools|software-distribution
14
8,930
6,320,058
What is the best way to use os.makedirs() when mode is ignored
<p>On a linux server I'm working on I need to create directories with the following structure:</p> <p>/dir1/dir2/dir3/YYYY/MM/DD/file.ext</p> <p>There are certain cases (since the directories depend on the date) that I need to create more than a single directory at a time, such as .../2011/01/01/, all of them needing...
<p>From the <code>mkdir(2)</code> man page:</p> <blockquote> <pre><code>NOTES Under Linux apart from the permission bits, only the S_ISVTX mode bit is honored. That is, under Linux the created directory actually gets mode (mode &amp; ~umask &amp; 01777). </code></pre> </blockquote> <p>So ...
python|linux|permissions
0
8,931
53,816,211
plot 3D connected prism matplotlib based on vertices
<p>I have a set of coordinates <strong>x, y, z</strong> from <strong>4-6</strong> vectors. I want to plot the corresponding prism. But my lines are crossed and do not look like a prism at all.</p> <p>I assume I have to sort my dataset, but I am not sure how or if this is the correct answer.</p> <h2>My plot</h2> <p>Th...
<p>A very well-asked first question!</p> <p>I think what you are looking for is the convex hull of your data points, which can be computed using <code>scipy.spatial.ConvexHull</code>. The problem with this approach is, however, that this function returns a set of triangles, which will not correspond to the set of face...
python|matplotlib
4
8,932
25,473,159
Python object1 = object2
<p>I am writing a vector class in python (just to see if i can). i ran into a problem with the subtract method and i have no idea what could be causing this. this is the class (i omitted "class Vector:").</p> <pre><code>def __init__(self, p): print self self.p = p def __str__(self): return str(list(self.p...
<p>First question:</p> <pre><code>(1, 1) - (1, 1) == (0, 0) </code></pre> <p>The output of your program is correct. You change the values of <code>a</code> in your function with <code>a[i] -= b[i]</code> where <code>a</code> is the list of coordinates (<strong>not</strong> a copy of the list) in <code>self</code> and...
python|class|variables|object
0
8,933
36,230,333
Python GUI stays frozen waiting for thread code to finish running
<p>I have a python GUI program that needs to do a same task but with several threads. The problem is that I call the threads but they don't execute parallel but sequentially. First one executes, it ends and then second one, etc. I want them to start independently.</p> <p>The main components are:<br> 1. Menu (view)<br...
<p>you call <code>procesor.start_process()</code> immediately when specifying it as the target of the Thread:</p> <pre><code>#use this procesor_thread = Thread(target=procesor.start_process) #not this procesor_thread = Thread(target=procesor.start_process()) # this is called right away ^ </c...
python|multithreading
3
8,934
36,041,966
Counting substrings in Python - more efficient approach?
<p>So I've been learning Python for a couple months now. I came across an exercise that wants you to count how many times a sub-string appears in a string. I searched, but couldn't find quite the exact answer I was looking for. Here is the code I wrote, that is functional. However, it does take a second due to the ...
<p>You could just do:</p> <p><code>'banana'.count('ba')</code></p> <p>The docs for the count method of strings say:</p> <blockquote> <p>Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.</p> </block...
python|substring|counting
4
8,935
29,382,285
Python - making a function that would add "-" between letters
<p>I'm trying to make a function, <code>f(x)</code>, that would add a <code>"-"</code> between each letter:</p> <p>For example:</p> <pre><code>f("James") </code></pre> <p>should output as:</p> <pre><code>J-a-m-e-s- </code></pre> <p>I would love it if you could use simple python functions as I am new to programming...
<p>Can I try like this:</p> <pre><code>&gt;&gt;&gt; def f(n): ... return '-'.join(n) ... &gt;&gt;&gt; f('james') 'j-a-m-e-s' &gt;&gt;&gt; </code></pre> <p>Not really sure if you require the last 'hyphen'.</p> <p>Edit:</p> <p>Even if you want suffixed <code>'-'</code>, then can do like </p> <pre><code>def f(n):...
python
8
8,936
21,317,924
KeyError: Backslash in Python Dictionary Key
<p>I am trying in Python to retrieve values from a dictionary created with json.loads() from the .text of a requests object which uses:</p> <pre><code>'\/' </code></pre> <p>as a separator in some of the dictionary keys. The dictionary is the standard output from another program not under my control.</p> <p>If I try...
<p>I tried it in Idle (2.7.6) and it looks valid:</p> <pre><code>&gt;&gt;&gt; d={'text\/text':'test'} &gt;&gt;&gt; d {'text\\/text': 'test'} &gt;&gt;&gt; d['text\/text'] 'test' &gt;&gt;&gt; </code></pre>
python|dictionary|backslash|keyerror
0
8,937
62,834,168
Is it possible to deconstruct `self` when using class methods in Python?
<p>I want to clean up my code so it uses less <code>self.attribute</code> instances and is easier to read.</p> <h2>Example of regular functionality:</h2> <pre class="lang-py prettyprint-override"><code>class Car: brand = None color = None model = None def __init__(self, color, brand, model): se...
<p>You can use <a href="https://docs.python.org/3/library/functions.html#vars" rel="nofollow noreferrer">the builtin function <code>vars</code></a> to get the attributes of most instances as a dictionary. This allows to invoke callables with the attributes, e.g. by using <code>**</code>-unpacking to use them as keyword...
python|oop
3
8,938
70,047,266
Check if elements in a list equal to the sum value of the list
<p>I am trying to figure out a more pythonic way of accepting a list and enumerating through the list, checking whether the sum of a sequence of elements == to the sum of the whole list, if so, it will create a return a sub list.</p> <p>Note: A solution for checking any combination of elements would be interesting too....
<p>You could iterate over all combinations of <code>list</code>:</p> <pre><code>import itertools def calc_sum(lst): res = [] lst_sum = sum(lst) for L in range(1, len(lst)): for subset in itertools.combinations(lst, L): if sum(subset) == lst_sum: res.append(subset) p...
python|list
1
8,939
46,019,567
Sharing variables between .py and .kv files, also loading and saving
<p>I'm making a text based game, which is pretty much fully completed on python. I have a saving and loading system, and it is a fluently running game, however, i wanted to make a GUI to make it more user friendly. I decided to use kivy. I have worked out how to use screens, and switch between screens (basically I have...
<p>Please refer to the example below.</p> <p><strong>main.py</strong></p> <pre><code>class RootWidget(BoxLayout): ego_stat = NumericProperty(0) def update_ego_stat(self): self.ego_stat += 1 def save_ego_stat(self): with open("ego_stat.txt", "w") as fobj: fobj.write(str(self.e...
python|python-3.x|kivy|python-3.6
0
8,940
46,140,297
pandas.read_csv can't import file with accent mark in path
<p>I am developing an application with Python and a QT GUI. I need to import a file to a <code>DataFrame</code>. I use a <code>QFileDialog.getOpenFileName</code> to get the path and filename to open it with <code>pandas.read_csv</code> method. Everything works well until I get a path with special characters like "ó". ...
<p>Looking in deep, this behavior comes in a combination of Python 3.6 and pandas.read_csv only in Windows systems. </p> <p>Python 3.6 change Windows filesystem encoding from "mbcs" to "UTF-8". See <a href="https://docs.python.org/3/whatsnew/3.6.html#pep-529-change-windows-filesystem-encoding-to-utf-8" rel="nofollow n...
python|pandas|dataframe|non-ascii-characters
3
8,941
55,078,509
how to extract span info from div with soup
<p>I have a piece of HTML code below:</p> <pre><code> &lt;div class="user-tagline "&gt; &lt;span class="username " data-avatar="aaaaaaa"&gt;player1&lt;/span&gt; &lt;span class="user-rating"&gt;(1357)&lt;/span&gt; &lt;span class="country-flag-small flag-113" tip="Portugal"&gt;&lt;/span&gt; &lt;...
<p>If you are interested <strong>only</strong> in the first div, you can go with this:</p> <pre><code>res = bsobj.find('div', {'class':'user-tagline'}).findAll('span') print(res[0].text, res[1].text, res[2]['tip']) </code></pre>
python|html|beautifulsoup
0
8,942
54,931,567
Partitioning a string with multiple delimiters
<p>I know partition() exists, but it only takes in one value, I'm trying to partition around various values:</p> <p>for example say I wanted to partition around symbols in a string:</p> <p>input: "function():"</p> <p>output: ["function", "(", ")", ":"] </p> <p>I can't seem to find an efficient way to handle variabl...
<p>You can use <code>re.findall</code> with an alternation pattern that matches either a word or a non-space character:</p> <pre><code>re.findall(r'\w+|\S', s) </code></pre> <p>so that given <code>s = 'function():'</code>, this returns:</p> <pre><code>['function', '(', ')', ':'] </code></pre>
python
2
8,943
21,796,981
Google Adwords API query the number of conversions per click
<p>I would like to query the number of conversions per click in a google adwords report using the SOAP API. Unfortuately the following query (Python),</p> <pre><code># Create report definition. report = { 'reportName': 'Last 30 days ADGROUP_PERFORMANCE_REPORT', 'dateRangeType': 'LAST_30_DAYS', 'reportType': 'ADG...
<p>Not sure if I am understanding you correctly, but the field is called <code>Conversions</code>, not <code>Conv1PerClick</code>. If you download the report in XML format, then the corresponding field attribute name <em>used</em> to be <code>conv1PerClick</code>, but this changed in v201402 in line with some changes t...
python|sql|google-analytics|google-analytics-api|google-ads-api
0
8,944
38,228,880
NLP nltk using the custom grammar
<p>Hi let's imagine i have a grammar like this S-> NNP VBZ NNP . However the number of NNPs are huge and its in a file. How can I load that directly into grammar or how can I make sure that the grammar fetches the words from the corpus instead of specifying all the words ?</p>
<p>Assuming each POS has its own text file consisting of every possible word with that tag on a separate line, you just want to make a dictionary by reading in the lines:</p> <pre><code>lexicon = {} with open('path/to/the/files/NNP.txt', 'r') as NNP_File: # 'with' automatically closes the file once you're done ...
python|nlp|nltk|grammar
1
8,945
29,130,884
Python - Highest with alphabetical order from text file
<p>I have made a quiz using python, the end score is out of 10. From this quiz each users name, class and score is saved in a text file. Now what I am trying to do is create a new program which can organize the users name in alphabetical order with the users highest score only and print this out. So far I have been suc...
<p>First, I would probably use a <code>defaultdict</code> using student names as keys and the value being a list of their scores. <code>defaultdict</code> simply initializes on first access, in this case with an empty list.</p> <pre><code>from collections import defaultdict scores = defaultdict(list) </code></pre> <...
python
0
8,946
28,950,331
Can't connect to remote postgreSQL using psycopg2
<p>I am trying to connect to a remote postgreSQL database, using the following code:</p> <pre><code>import psycopg2 try: # this: conn = psycopg2.connect(database="A B C", user="user", password="pass", host="yyyy.xxxxx.com", port= 5432) # or this: conn = psycopg2.connect("dbname=A B C user=user passw...
<p>You should see more info in <code>e</code> exception and also use very useful <code>traceback</code> module:</p> <pre><code>import traceback ... except psycopg2.Error as e: print "I am unable to connect to the database" print e print e.pgcode print e.pgerror print traceback.format_exc() </code...
python|postgresql|psycopg2
4
8,947
51,971,493
How to print a Kinect frame in OpenCV using OpenNI bindings
<p>I'm trying to use OpenCV to Process depth images from a kinect. Im using Python and primesense's bindings (<a href="https://pypi.org/project/primesense/" rel="nofollow noreferrer">https://pypi.org/project/primesense/</a>), but im having a lot of trouble just showing the images i get from openNI. Im usin</p> <pre>...
<p>I found the solution:</p> <p>Instead of using <code>image = np.array(frame_data, dtype=np.uint8)</code> for getting the image, you have to use <code>frame_data = frame.get_buffer_as_uint16()</code>. also, i was failing to set the image shape correctly.</p> <p><strong>FOR FUTURE REFERENCE</strong></p> <p>To take a...
python|opencv|openni
1
8,948
59,585,050
copy and paste the contents of many txt files to create one big file
<p>I have multiple txt files and I want to copy and paste the contents of each file to create one big file using python. Any help is greatly appreciated.</p>
<p>First, we should break down the problem.</p> <ol> <li><p>You have a bunch of text files</p></li> <li><p>Create a big file from those files</p></li> </ol> <p>Lets now work with that. Doing a little quick googling, we should look into how to take the contents of files with python, and put them into a big one.</p> <...
python|text|copy|paste
1
8,949
36,319,261
How to sum fields in a view Qweb?
<p>I am creating a report (qweb view) in the account.invoice model and wish to sum some fields for each invoice line as shown in the following image:</p> <p><a href="https://i.stack.imgur.com/g4F0U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g4F0U.png" alt="enter image description here"></a></p>...
<p>You need to define one class which is inherited from <strong>report_sxw.rml_parse</strong> class, in that class you need to define <strong>init</strong> method where you need to add your <strong>method name</strong> as <strong>KEY</strong> of <strong>localcontext</strong> dictionary.</p> <pre><code>class sale_quota...
python|openerp|odoo-9
1
8,950
13,286,324
Mac OS X: _tkinter.TclError: no display name and no $DISPLAY environment variable
<p>As I said, I have installed Python 3.3 from Macports. </p> <p>Now when I do a spotlight search for Idle </p> <pre><code>Idle -- Python 3.3 </code></pre> <p>shows up. However when I try to click it, nothing happens. No error is shown or anything- it plain does not start.</p> <p>What do you think might be wrong? <...
<p>Using macports, install <code>py33-tkinter</code></p> <p><code>sudo port install py33-tkinter</code></p> <p>Edit: Make sure you have X11 or Xquartz installed too.</p>
python|macos|macports
3
8,951
17,055,318
Create transaction in GnuCash in response to an email?
<p>I would like to create a script which is triggered by an email filter which, when run, creates two transactions in GnuCash. I see that <a href="http://wiki.gnucash.org/wiki/Python_Bindings" rel="nofollow">GnuCash has Python bindings</a> but the documentation is sparse at best... a better term would be "nonexistent"....
<p>Here is an alternative solution using piecash (<a href="https://github.com/sdementen/piecash" rel="noreferrer">https://github.com/sdementen/piecash</a>, version 0.10.1), a modern python library to work with gnucash books (<strong>disclaimer</strong>: I am the author)</p> <pre><code>from piecash import open_book, Tr...
python|gnucash
6
8,952
16,683,018
Function returns tuple instead of string
<p>I have a function in python similar to the following:</p> <pre><code>def checkargs(*args): if len(args) == 1: x = args y = something elif len(args) == 2: x, y = args return x, y </code></pre> <p>When I put in only one argument (a string), x comes out as a tuple. When I put in t...
<p>This happens because <code>args</code> is <em>always</em> a tuple, even if you only put in one argument. So, when you do:</p> <pre><code>x = args </code></pre> <p>This is like doing:</p> <pre><code>x = ('abc',) </code></pre> <p>There are two (equivalent) ways to fix this: either explicitly assign <code>x</code> ...
python|string|function|python-2.7|tuples
6
8,953
16,698,621
google app engine: Error: HTTPError
<p>I am trying "Hello world" with python </p> <pre><code> import webapp2 class MainHandler(webapp2.RequestHandler): def get(self): self.response.write('Hello world!') app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True) </code></pre> <p>app.yaml</p> <pre><code>application: engineapp v...
<p>I had this very same issue with my MacOSX when using a proxy server using Google App Engine Launcher 1.8.6 behind a proxy server. Apparently there's an issue with "proxy_bypass" on "urllib2.py".</p> <p>There are two possible solutions:</p> <ol> <li>Downgrade to 1.7.5, but, who wants to downgrade?</li> <li><p>Edit...
python|google-app-engine|python-2.7
22
8,954
54,292,805
Can I get lists as keys in a dictionary?
<p>I have an iteration process that after every iteration gives me a list, eg. a = [1,2,3,4]. Can I use this list as a key to a dictionary? The next iteration the same list changes elements, say after the 2nd iteration I have [2,1,3,4]. Can I construct a dictionary d = {[1,2,3,4]:"value1", [2,1,3,4]:"value2"]} </p> <p...
<p>not sure if this works for you but you could just convert the list to a string, so that you can use it as a key in the dictionary:</p> <pre><code>trylist = [1,2,3,4] d = {} d[str(trylist)] = 'value' print(d) </code></pre> <p>but using a tuple should work too:</p> <pre><code>trylist = (1,2,3,4) d = {} d[trylist] =...
python|list|dictionary|tuples|key
0
8,955
39,242,333
Tensorflow : Implementing gradient for user op in C++?
<p>I'd ideally like the operation to be wholly self-contained (gradient and operation defined in same file). The official tutorial only highlights a python implementation. Does anyone know if it's possible to implement the gradient in C++, and how to go about it?</p>
<p>Automatic gradient computation is currently only fully supported in the Python API. So the association of an operation to its gradient operation should still be specified manually in Python. Suppose you have an op <code>Foo</code> and its gradient op <code>FooGrad</code> defined in C++, you should get the correspond...
tensorflow
0
8,956
39,119,500
How to I list down the results of a function (python)
<p>I want to list down the sums taken from numberA. </p> <p>The function "add" prompts the user if he wants to add. If he selects yes, then it will go to the function "numberA". This part will loop. </p> <p>I want to list down the list of the sums when the user selects "N" in the function "add". And finally sum up a...
<p>This help</p> <pre><code>def add(): ask = True res = [] while ask : num1=int(input("Enter First Number : ")) num2=int(input("Enter Second Number : ")) total = num1+num2 userSelect = input("Do You Want to Add?" "\n(Y) Yes ; (N) No" "\n") if userSele...
python
0
8,957
52,868,835
I'm getting a TypeError for a += b, but not b += a (numpy)
<p>why I'm getting <code>TypeError</code> for <code>a += b</code> but it works fine for <code>b += a</code> for below code</p> <pre><code>import numpy as np a = np.ones((2,3), dtype=int) b = np.random.random((2,3)) a += b </code></pre>
<p>Report the whole TypeError!</p> <pre><code>----&gt; 3 a += b TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind' </code></pre> <p><code>a</code> is integer dtype, right? <code>b</code> is float. Add a float and integer and the result is a float. But...
python|numpy|typeerror
12
8,958
52,664,293
Why (or why not) Add Anaconda to path?
<p>I have found a partial answer in this question: <a href="https://stackoverflow.com/questions/45185057/adding-anaconda-to-path-or-not">Adding Anaconda to Path or not</a> </p> <p>But I still don't fully understand. I have had a lot of installation issues when switching from a normal installation Python to Anaconda, r...
<p><code>PATH</code> is an environment variable that is a list of locations where executable programs lie (see also the <a href="https://en.wikipedia.org/wiki/PATH_(variable)" rel="noreferrer">wikipedia page</a>.</p> <p>Whenever you are in your command line and try to execute some program, for example <code>regedit</co...
python|path|pycharm|anaconda|conda
47
8,959
37,533,577
Arabic stemmer doesn't work for sentences
<p>I have python 2.7 and i installed <a href="http://www.arabicstemmer.com/" rel="nofollow">this</a> , I have this code : </p> <pre><code>from snowballstemmer import stemmer ar_stemmer = stemmer("arabic") stem = ar_stemmer.stemWord(u"مكتبة لمعالجةالكلمات العربية وتجذيعها ") print stem </code></pre> <p>When i run i...
<p>Split the sentence on words like this:</p> <pre><code>from snowballstemmer import stemmer ar_stemmer = stemmer("arabic") sentence = u"مكتبة لمعالجة الكلمات العربية وتجذيعها" for word in sentence.split(" "): stem = ar_stemmer.stemWord(word) print stem </code></pre>
python|arabic|stemming
2
8,960
37,589,975
How to split dictionary keys into multiple separate keys in python?
<p>In Python I am using the RRDTool Python wrapper to store and read values into / from a RRD-Database.</p> <p>The RRDTool for Python is a wrapper for the C-based source / command-line utility of rrdtool. </p> <p>After creating a database I want to read out it's header using the python command: </p> <pre><code>heade...
<p>We need to parse the keys to see if they look like <code>ds[some_identifier].type</code> etc.</p> <pre><code>def process_dict(dictionary): import re rgx = re.compile(r"^(ds)\[(.+?)\]\.(index|type)$") processed = {} for k, v in dictionary.items(): # does k have the format ds[some_key].i...
python|string|dictionary|rrdtool
1
8,961
37,586,218
Object is not defined
<p>I have a problem with my code. The program is designed to parse the file, select it with the information and save them in the list of objects of the class.</p> <p>But first - it does not save them correctly. In fact, nothing does save, it returns empty records.</p> <p>I tried to create a minimum of code entirely ...
<p>I really like <code>xml.etree</code> for this kind of task. Supposing your xml example has multiple <code>Entry</code> records inside an other element, I used this xml file to test my code:</p> <pre><code>&lt;Records&gt; &lt;Entry id="AA0003"&gt; &lt;Header&gt; &lt;Code&gt;AA0003&lt;/Code&gt; &lt;/Header&gt; &lt;Na...
python|python-3.x|xml-parsing|minidom
0
8,962
34,253,656
Reportlab align text in cells
<p>I try to generate a pdf table with reportlab but I have problems with TableStyle.</p> <p>Valign and background work but not align and textcolor and I don't understand why.</p> <p>Here is my code :</p> <pre><code>response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment;...
<p>It is because you have wrapped each Cell into a Paragraph. The Cell is right aligned, but the Paragraph in the cell is left aligned.</p> <p>If you want a right aligned field, use <strong>cell</strong> rather than <strong>Paragraph(cell, s)</strong></p> <p>The text will then not wrap though.</p>
python|reportlab
0
8,963
34,094,377
Updating text in real time in python
<p>Currently i'm in a beginners python class, making christmas cards to learn how to use tkinter to draw stuff. What I want to figure out is how to make it so that my signature is written directly into the card itself, not in a input window, and allow me to hit backspace and delete stuf if i make a typo. Then when I p...
<p>You could try this, I've created an entry field and confirm button that the user enters their signature into. When they press the confirm button, it destroys the button and entry field, and puts their entered signature into the canvas:</p> <pre><code>from tkinter import * window=Tk() window.title('At the \'Sell You...
python|tkinter
0
8,964
7,561,073
How do I run twisted trial on all tests in a directory?
<p>How do I run trial so that it executes all tests within a directory? All my unit tests pass if I run trial on each file individually, but if I try something like...</p> <pre><code>trial test/ </code></pre> <p>on the test directory, it gives me one "<code>PASSED</code>", and the following message...</p> <pre><cod...
<p>First of all: you can't call your top-level unit test package <code>test</code>. That's the name of Python's unit tests, so you will never be able to run your tests in an installed configuration, and depending on how your python is set up, you may end up importing python's own tests instead of your own.</p> <p>Sec...
python|twisted|trial
5
8,965
39,818,241
How to save multiple output in multiple file where each file has a different title coming from an object in python?
<p>I'm scraping rss feed from a web site (<a href="http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&amp;type=rss" rel="nofollow">http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&amp;type=rss</a>). I have wrote down a script to extract and purifie the text from every of the feed....
<p>First off, you misplaced the comma, it should be after the <code>%tit</code> not before.</p> <p>Secondly, you don't need to close the file because the <code>with</code> statement that you use, does it automatically for you. And where did the codecs came from? I don't see it anywhere else.... anyway, the correct <co...
python|rss|feed
0
8,966
31,959,570
python + from <module> + how from - import know the PATH
<p>How the from in python know the PATH of the directory that all module are exists?</p> <p>For example</p> <p>Under</p> <pre><code> /data_py/Python/modulespy </code></pre> <p>I have all the modules as:</p> <pre><code>Df.py Tr.py Sw.py </code></pre> <p>So how the following <strong>from</strong> syntax in pytho...
<pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.path ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] </code></pre> ...
python|python-2.7
1
8,967
32,065,027
Python Delay on Loop
<p>I need an alternative to "delay" actions on a LOOP. When using <code>time.sleep(1)</code> the whole process pauses for a second. The <code>print 'something'</code> should be executed after every 1 second, 50 times and not interrupting the rest of the process.</p> <p>Actual code:</p> <pre><code>for num in range(50,...
<p>If I understand what you want, you need to use threads. One thread will do exactly what you did: just count and sleep. The other thread will be "the rest of process", doing whatever it wants, without being interrupted by sleeping.</p> <pre><code>import time import threading def count(): for num in range(50, -1...
python|loops|time|process|delay
1
8,968
38,686,918
Pandas - Unpack column of lists of varying lengths of tuples
<p>I would like to take a Pandas Dataframe named <code>df</code> which has an ID column and a lists column of lists that have variable number of tuples, all the tuples have the same length. Looks like this:</p> <pre><code>ID list 1 [(0,1,2,3),(1,2,3,4),(2,3,4,NaN)] 2 [(Nan,1,2,3),(9,2,3,4)] 3 [(Nan,1,2,3),(9,2,...
<pre><code>In [38]: (df.groupby('ID')['list'] .apply(lambda x: pd.DataFrame(x.iloc[0], columns=['A', 'B', 'C', 'D'])) .reset_index()) Out[38]: ID level_1 A B C D 0 1 0 0 1 2 3 1 1 1 1 2 3 4 2 1 2 2 3 4 NaN 3 2 0 NaN 1 2 ...
python|pandas|group-by|iterable-unpacking
6
8,969
40,357,288
Why does my class cost so much memory?
<pre><code>from guppy import hpy hp = hpy() class Demo(object): __slots__ = ('v0', 'v1') def __init__(self, v0, v1): self.v0 = v0 self.v1 = v1 from array import array value = 1.01 ar = array('f') ar2 = array('f') for i in range(5000000): ar.append(value + i) ar2.append(value + i *...
<p><code>sys.getsizeof()</code> doesn't recurse into sub-objects, and you only took the size of the <em>class</em>, not of an instance. Each instance takes up 64 bytes, plus 24 bytes per <code>float</code> object (on OS X, using Python 2.7.12):</p> <pre><code>&gt;&gt;&gt; d = Demo(1.0, 2.0) &gt;&gt;&gt; sys.getsizeof(...
python|python-2.7|memory
3
8,970
26,375,763
Why is z3.And() slow?
<p>I am using Z3 Python bindings to create an And expression via <code>z3.And(exprs)</code> where <code>exprs</code> is a python list of 48000 equality constraints over boolean variables. This operation takes 2 seconds on a MBP with 2.6GHz processor.</p> <p>What could I be doing wrong? Is this an issue with z3 Pytho...
<p>Using Z3 over Python is generally pretty slow. It includes parameter checks and marshaling (_coerce_expr among others). For scalability you will be better of using one of the other bindings or bypass the Python runtime where possible. </p>
python|z3|z3py
2
8,971
63,277,201
don't get value on button press in html
<p>I have a button which when clicked just need to execute a javascript function. The javascript function returns a string which I intend to capture in the flask backend. Currently the javascript function runs on onclick.</p> <p>The code:</p> <pre><code>&lt;form id='details'method=&quot;post&quot;&gt; &lt;input cl...
<hr /> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <p><strong>#EDIT 2</strong> check this answer <a href="https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request">Here</a>.</p> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> <p>I report here the m...
javascript|html|python-3.x|flask
0
8,972
63,090,990
Python Check if element exists in SQLite result
<p>I want to see if the username inputted by the user already exists on my database. Currently I am able to create usernames that have already been taken. This is my current code (newUser is a string):</p> <pre><code>with sqlite3.connect('database.db') as conn: cursor = conn.cursor() taken = cur...
<p>Turns out using fetchall returns a list of tuples, so I was able to find the string like this:</p> <pre><code>for item in takenUsers: if item[0] == newUser: session['error'] = 'Username already taken' return redirect('/error') </code></pre>
python|sqlite
0
8,973
44,123,613
Can't use sample_weights both for fit or evaluate model on Keras
<p>I need to set sample_weights parameter for training a unbalanced classes on Keras.</p> <p>If I try to use a list of weights it gives a error: AttributeError: 'list' object has no attribute 'shape'</p> <p>If I try to use a 1D array, it gives the error: ValueError: Found a sample_weight array with shape (17,) for an...
<p>You need weights shaped as <code>(180,)</code>. One weight per sample in the training data. </p>
python-3.x|keras
0
8,974
44,314,578
Testing database read/write plus analytics script in Python
<p>I often have the need to write a command line script that will read from a database, perform some analytics, and write the results back to the database. My effort to decouple and create a separate data layer generally is to write scripts <code>load.py</code>, <code>write.py</code>, and <code>do_analytics.py</code> w...
<p>In your case I would have 4 files.</p> <p><strong>database_provider.py</strong></p> <pre><code>class DatabaseProvider(object): def get_data(self): return db.get() # Get your data def set_data(self, data): db.set(data) # update your data </code></pre> <p><strong>analytic_manager.py</strong...
python|unit-testing|testing|mocking|integration-testing
1
8,975
12,130,497
GMM clustering algorithm with equal weight and shared diagonal covariance
<p>I'm looking for a Gaussian mixture model clustering algorithm that would allow me to set equal component weights and shared diagonal covariances. I need to analyze a set of data and I don't have the time to try to write the code myself.</p>
<p>In python you can use scikit's GMM. It's easy to do, see the doc:</p> <p><a href="http://scikit-learn.sourceforge.net/dev/modules/generated/sklearn.mixture.GMM.html" rel="nofollow">http://scikit-learn.sourceforge.net/dev/modules/generated/sklearn.mixture.GMM.html</a></p> <p>Re your specific needs:</p> <pre><code>...
python|matlab|machine-learning|computer-vision|mixture-model
2
8,976
23,320,668
How to render markdown content with jinja2, in a django project?
<p>I am working on a django project with a model like:</p> <pre class="lang-py prettyprint-override"><code>class Article(models.Model): ... # which is submitted by users through a markdown editor. content = models.TextField(_('content'), blank=True) ... </code></pre> <p>As a result, I render the conte...
<p>Not sure about Django, but I use Markdown with Jinja2 in flask. I initialize Markdown when the app runs like this.</p> <h3>app</h3> <pre><code>from flask.ext.markdown import Markdown md = Markdown(app, extensions=['fenced_code']) </code></pre> <p>Then I add the filter to the template.</p> <h3>template</h3> <pre><co...
python|markdown|jinja2
21
8,977
1,263,451
Python decorators in classes
<p>Can one write something like:</p> <pre><code>class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass </code></pre> <p>This fails: self in @self is unknown</p> <p>I also tried:</p> <pre><code>@Test._decorator(self) </code></pre> <p>which also fails: ...
<p>Would something like this do what you need?</p> <pre><code>class Test(object): def _decorator(foo): def magic( self ) : print "start magic" foo( self ) print "end magic" return magic @_decorator def bar( self ) : print "normal call" test = Te...
python|class|decorator|self
332
8,978
42,086,872
Python - XML not well-formed (invalid token) Debug Values
<p>I'm getting this error when I try to import some of the saleorders, I need to debug the values of the return statement but i'm not getting anything but errors. The code is working for the majority of the saleorders but i get in the error on a couple of orders and i can't identify the error.</p> <p>I try with print_...
<p>Try with the method serialize of the xmlrpcval to see the values Link: <a href="https://gggeek.github.io/jsxmlrpc/javadoc/xmlrpcval.html#serialize" rel="nofollow noreferrer">https://gggeek.github.io/jsxmlrpc/javadoc/xmlrpcval.html#serialize</a></p>
php|python|odoo-8|xml-rpc
0
8,979
47,356,180
How to disable Hybrid Shutdown in Windows with a Command Line
<p>How to disable Hybrid Shutdown in Windows with a Command Line.</p> <p>I am using a ramdisk (with imdisk software), after the upgrade from Windows 8.1 pro into Windows 10 pro - The Computer does Save automatic My Ramdisk to My Hard Disk everytime if i Shutdown my Windows, <strong>i do not want that</strong>. (The ra...
<p>You can use these msdos bat files:</p> <p>1 - HybridOn_ShutDown.bat </p> <p>This will save the Whole Ram memory to your HardDisk (MemoryFile), and then it will ShutDown Windows. The next time that you will start up your Computer, it Will Load your (MemoryFile) into the Ram Memory - The Pros are:The Computer will ...
python|windows|batch-file|registry|autohotkey
1
8,980
70,816,445
Replacing every other position in a list
<p>I'm trying to make something that allows me to replace every other position in a list with a single item:</p> <pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] l[::2] = &quot;A&quot; print(l) </code></pre> <p>I'm expecting something like:</p> <pre><code>[&quot;A&quot;, 1, &quot;A,&quot; 3, &quot;A&quot;, 5, &quot;A&...
<p>The slice is correct, but you need to provide a sequence with enough elements to fill all the elements.</p> <pre><code>l[::2] = [&quot;A&quot;] * math.ceil(len(l)/2) </code></pre>
python|list|indexing
4
8,981
47,080,696
Distributed tensorflow where to keep data
<p>I am using 3 machines for distributed tensorflow (2 workers and 1 ps). All lie on the same cluster. I have placed my data on worker 1. My model works well but it uses only ps and 1 worker. My question is how is data placed so that all my workers can access it? Should I place it in shared memory like hdfs? </p> <p><...
<p>Found some relevant info here: [1]<a href="https://stackoverflow.com/questions/46322337/grpc-causes-training-to-pause-in-individual-worker-distributed-tensorflow-sync">GRPC causes training to pause in individual worker (distributed tensorflow, synchronised)</a> Appears that we need to create TFRecords.</p>
tensorflow|distributed
0
8,982
46,695,808
Telegram bot delete new message (python)
<p>How to make a bot delete a new or last message in a group</p> <pre><code>import telebot import constants bot = telebot.TeleBot(constants.token) LAST_UPDATE_ID = bot.get_updates () [- 1] .update_id, LAST_UPDATE_ID = False bot.getUpdates () [- 1] .update_id </code></pre>
<p>You can use <a href="https://core.telegram.org/bots/api#deletemessage" rel="nofollow noreferrer">deleteMessage</a> method:</p> <p><a href="https://i.stack.imgur.com/KioPQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KioPQ.jpg" alt="Awesome Telegram Bot"></a></p> <p>Note that <code>message_id<...
python|telegram|telegram-bot
-1
8,983
30,251,658
Python to combine lines in a txt file
<p>a question regarding combine lines in a txt file.</p> <p>file contents as below (movie subtitles). I want to combine the subtitles, those English words and sentences in each paragraph into 1 line, instead of now showing either 1, 2 or 3 lines separably.</p> <p>could you please advise which method is feasible in Py...
<h1>Intuitive solution</h1> <p>A simple solution based on the 4 types of lines you can have:</p> <ul> <li>an empty line</li> <li>a number indicating the position (no letters)</li> <li>a timing for the subtitle (with a specific pattern; no letters)</li> <li>text</li> </ul> <p>You can just loop over each line, classif...
python
3
8,984
56,926,406
Conversion of Daily pandas dataframe to minute frequency incorrectly fills dates
<p>I am trying to convert a daily frequency dataframe to minute data, that is for each row, I want to have that combination of ticker and date repeated on minute basis, and in a previous post (<a href="https://stackoverflow.com/questions/56371996/conversion-of-daily-pandas-dataframe-to-minute-frequency">Conversion of D...
<p>So the solution below works for me, I simply create new column with the daily dates and after the conversion, I creaete a another daily column and only keep the rows where both match:</p> <pre><code> df['date_column']=pd.to_datetime(df.index.get_level_values(0)) df['date_column']=pd.to_datetime(df['date_column']...
python|pandas|dataframe
1
8,985
57,034,460
How to extract number from HTML Xpath
<p>Please consider this statement :</p> <pre><code>hxs.select('//span[@class="product-count"]') </code></pre> <p>It selects span which is recognized by product-count. It returns correct html path which is :</p> <pre><code>HtmlXPathSelector xpath='//span[@class="product-count"]' data='&lt;span class="product-count"&g...
<p>Try this:</p> <pre><code>number = response.xpath('//span[@class="product-count"]/text()').get() </code></pre>
python|scrapy|pycharm
1
8,986
27,809,261
subprocess.popen making the cgi script stuck
<p>When opening the page with following code the page keeps loading forever..</p> <pre><code>import cgitb import subprocess,shlex cgitb.enable() print "Content-type:text/html\r\n\r\n" print 'Hello' CMD = '/usr/bin/python -u /path/to/file/filename.py -c %s -r' cmd = CMD % 'somearg' proc = subprocess.Popen(shlex.split(c...
<p>CMD is missing '\n'.</p> <pre><code>CMD = '/usr/bin/python -u /path/to/file/filename.py -c %s -r\n' </code></pre>
python|apache|subprocess|cgi-bin
-1
8,987
27,713,282
What does int() function with 2 args do in Python
<p>In the following code what does int() do with these 2 arguments:</p> <pre><code>if (i=='0X0F'): stat = int(log[i+1],16) </code></pre>
<pre class="lang-none prettyprint-override"><code>class int(object) | int(x=0) -&gt; int or long | int(x, base=10) -&gt; int or long | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is floating point, the conversion truncates towards zero. | If x is outside the i...
python|int
11
8,988
72,193,738
Is it possible to search for something specific in the output of an outside executable file using python?
<p>I am writing a code that is using an outside executable file and i am trying to see if there is a way I can search through the output for information that only corresponds with a specific date I provide. The executable file is tsk_gettimes and I am needing to scan through all of the information of the provided file ...
<p>Use <code>subprocess.popen()</code> to run a command and read its output.</p> <pre><code>import subprocess with subprocess.Popen(['C:\\Program Files\\sleuthkit-4.11.1-win32\\bin\\tsk_gettimes.exe', filename], stdout=PIPE) as proc: output = proc.stdout.read() if re.search(regexp, output): ... </code></pre>
python|executable
2
8,989
48,889,081
Python Data Analysis
<p>I am new to python. I have various versions of python installed in my Mac.</p> <p>The pandas is installed in python 3.5. I want to use python 2.7. However when I do </p> <p>import pandas </p> <p>It says:</p> <p>ImportError: No module named pandas</p> <p>I tried pip install pandas but it is installing in python3...
<p>I would suggest you to create a <code>virtual environment</code> and get started with the <code>Python</code> version you want to work on. Link to <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/#lower-level-virtualenv" rel="nofollow noreferrer">Documentation</a></p> <p>You may also follow easy inst...
python|pandas|importerror
1
8,990
20,289,730
How to implement a for loop
<p>I have my for loop set up, but im missing one condition and just don't know where to put it! Let's say the user already picked <code>"a1"</code> and picks it again. I don't want that value to be used but instead tell him it's already been picked and let him pick again. I tried making it but the way I had it, it told...
<p>So you want to force the user to repeatedly enter a move until they enter a valid one. That means that you need to wrap the <code>input</code> statement in a loop, something like this:</p> <pre><code>while some_condition_is_not_met: user = input("Enter your move: ") if not valid_move(user): print "b...
python|function|for-loop|python-3.x
2
8,991
69,474,976
How to open Python 3.10 from cmd when I have 3.7 installed?
<p>I have python 3.7 and Python 3.10 both installed on my computer. However, when I launch it from cmd by typing 'python' it launches python 3.7 instead of 3.10. Howe to launch 3.10 specifically? Also, I have Pycharm which currently runs on 3.7, so, how to run it on 3.10?</p>
<p>You must edit your <code>PATH</code> variable to link to Python 3.10, currently you have it linked to Python 3.7</p> <p>Search for Edit Environment Variables, click the Environment Variables, Go to Path, and edit python to link to the Python 3.10 directory.</p>
python|python-3.x
0
8,992
55,919,597
Cython compilation error with simple inheritance - object has no attribute
<p>I am trying to wrap a simple C++ class that uses shared pointers and a very simple inheritance. I have a class Point that is a base class and SphericalPoint is it's child class. I have a vector of shared pointers of Points. I want the vector to hold the child class objects in it i.e. Spherical Points. There can be m...
<p>Cython can work this out for regular pointer types and generate c++ code with <code>-&gt;</code>, however it isn't able to work this out for types that implement a pointer interface with operator overloading.</p> <p>Instead you should use <a href="https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlus...
python|pointers|compiler-errors|cython
1
8,993
73,383,132
How to check if all grouped by month data is equal to nan?
<p>I have this df:</p> <pre><code> DATE CODE PP YEAR_MONTH 9862 1991-01-01 100007 NaN 1991-01 9863 1991-01-02 100007 NaN 1991-01 9864 1991-01-03 100007 NaN 1991-01 9865 1991-01-04 100007 NaN 1991-01 9866 1991-01-05 100007 NaN 1991-01 ... ... ... ...
<p>Create helper column <code>NAN_MONTH</code> and then call <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.all.html" rel="nofollow noreferrer"><code>GroupBy.all</code></a>:</p> <pre><code>out = (df.assign(NAN_MONTH = df['PP'].isna()) .groupby(['CODE','YEAR_MONTH...
python|pandas
1
8,994
49,806,171
Why can't I subclass a subclass of Enum?
<p>Consider the following code:</p> <pre><code>from enum import Enum class SubclassOfEnum(Enum): x = 5 print(SubclassOfEnum.x) class SubSubclassOfEnum(SubclassOfEnum): y = 6 print(SubSubclassOfEnum.y) </code></pre> <p>We get an error, <code>TypeError: Cannot extend enumerations</code>,</p> <p>from: <code>...
<p>Because subclassing <code>Enum</code>s with members is <a href="https://docs.python.org/3/library/enum.html#restricted-subclassing-of-enumerations" rel="nofollow noreferrer">specifically disallowed</a>.</p> <p>For general use-cases for <code>Enum</code> check out <a href="https://stackoverflow.com/q/22586895/208880...
python|python-3.x|enums
5
8,995
67,249,315
Django can’t establish a connection to the server
<p>I'm using docker to start a project using django after I did build I get no error and I did up I get no error but still can't connect to server</p> <p>my docker ps return</p> <pre><code>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 385...
<h2>Explain</h2> <pre class="lang-sh prettyprint-override"><code>python manage.py runserver 127.0.0.1:7777 </code></pre> <p>Using command above in a container will make the Django server listening on loopback. For more detail you can read this <a href="https://www.howtogeek.com/225487/what-is-the-difference-between-127...
python-3.x|django|docker|docker-compose
2
8,996
60,505,059
Which all folders will be included in serverless functions when packaging individually?
<p>I am very new to the serverless framework and am very curious to know that when we execute "serverless package" and serverless.yml contains package individual as true then which folders will be added default to each functions. Will it by default add all folders in every function or is their any specific condition fo...
<p>By default the Serverless Framework will replicate the entire folder structure for each function that gets deployed. You can alter this by using some additional plugins that will optimise the packaging process per function. These plugins include:</p> <ul> <li><a href="https://serverless.com/plugins/serverless-webpa...
python-3.6|serverless
0
8,997
69,054,387
Saving the Learned Weights of a Network to Train on another Dataset
<p>I would like to train a MLP(Multi Layer Perceptron) with MNIST dataset. I use a validation set so I can save the weights of the best model. Then I want to load these weights back into the same architecture and use them to initialize and train with another dataset. I would like to know if this is possible with Tensor...
<p>I suggest you take a look at tensorflow's documentation, here a link of a tutorial to save your weights and load them afterwards:</p> <p><a href="https://www.tensorflow.org/tutorials/keras/save_and_load" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/keras/save_and_load</a></p>
tensorflow|keras|neural-network
1
8,998
68,269,602
How do I click on a navigation bar item using Selenium?
<p>I am fairly new in Selenium and I've been trying to work on automating the login for this [website], but for some reason <code>element.click()</code> on selenium does not seem to work when I try to click onto the Login button. I keep getting this <code>TypeError: 'str' object is not callable</code> error.</p> <p>Her...
<p>You are trying to use wrong locator.<br /> Selenium fails to find such element.<br /> Also, it's better to use expected conditions of element visibility instead of element presence since when element becomes existing on the page it is still not clickable / visible.<br /> So, please try this:</p> <pre><code>element =...
python|python-3.x|selenium|xpath
0
8,999
59,097,923
Output number of iterations for Newton Method using Scipy
<p>I would like to know how I can output the number of iterations when finding the root using Newtons method. I am calculating the root automatically using Scipy, so I wanted to know if there is a way of knowing how many iterations it took:</p> <pre><code>from spicy.optimize import newton from math import * f = lambd...
<p>Spicy is a cool name for scipy. :)</p> <p>Jokes aside, you simply need to include <code>full_output=True</code> in your call to <code>newton</code> (see the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html" rel="nofollow noreferrer">doc</a> for more detail). Executing your co...
python|scipy|newtons-method|numerical-analysis
1