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 |
|---|---|---|---|---|---|---|
200 | 71,740,466 | Sympy: How to calculate the t value for a point on a 3D Line | <p>Using sympy how would one go about to solve for the t value for a specific point on a line or line segment?</p>
<pre><code>p1 = sympy.Point3D(0,0,0)
p2 = sympy.Point3D(1,1,1)
p3 = sympy.Point3D(0.5,0.5,0.5)
lineSegment = sympy.Segment(p1,p2)
eqnV = lineSegment.arbitrary_point()
if lineSegment.contains(p3):
t = ... | <p>You can get a list of coordinate equations and pass them to sympy's solve function:</p>
<pre><code>In [112]: solve((lineSegment.arbitrary_point() - p3).coordinates)
Out[112]: {t: 1/2}
</code></pre> | python-3.x|sympy | 1 |
201 | 62,547,186 | Python Dataframe add new row based on column name | <p>How do I add a new row to my dataframe, with values that are based on the column names?</p>
<p>For example</p>
<pre><code>Dog = 'happy'
Cat = 'sad'
df = pd.DataFrame(columns=['Dog', 'Cat'])
</code></pre>
<p>I want to add a new line to the dataframe where is pulls in the variable of the column heading</p>
<pre><code>... | <p>You can try <code>append</code>:</p>
<pre><code>df.append({'Dog':Dog,'Cat':Cat}, ignore_index=True)
</code></pre>
<p>Output:</p>
<pre><code> Dog Cat
0 happy sad
</code></pre> | python|pandas | 1 |
202 | 62,541,592 | Write Data to BigQuery table using load_table_from_dataframe method ERROR - 'str' object has no attribute 'to_api_repr' | <p>I am trying to read the data from Cloud storage and write the data into BigQuery table. Used Pandas library for reading the data from GCS and to write the data used client.load_table_from_dataframe method. I am executing this code as python operator in Google cloud composer. Got below error when i execute the code.<... | <p>Basically Panda consider string as object, but BigQuery doesn't know it. We need to explicitly convert the object to string using Panda in order to make it load the data to BQ table.</p>
<p>df[columnname] = df[columnname].astype(str)</p> | python|google-bigquery|google-cloud-composer | 0 |
203 | 61,657,432 | Python tracemalloc's "compare_to" function delivers always "StatisticDiff" objects with len(traceback)=1 | <p>Using Python's 3.5 tracemalloc module as follows</p>
<pre><code>tracemalloc.start(25) # (I also tried PYTHONTRACEMALLOC=25)
snapshot_start = tracemalloc.take_snapshot()
... # my code is running
snapshot_stop = tracemalloc.take_snapshot()
diff = snapshot_stop.compare_to(snapshot_start, 'lineno')
tracemalloc.stop()... | <p>You need to use <code>'traceback'</code> instead of <code>'lineno'</code> when calling <code>compare_to()</code> to get more than one line.</p>
<p>BTW, I also answered a similar question <a href="https://stackoverflow.com/questions/56935252/how-to-get-more-frames-from-backtrace-in-tracemalloc-snapshot-comparisons-py... | python|compare|diff|snapshot|tracemalloc | 1 |
204 | 67,491,254 | Filter objects manyTomany with users manyTomany | <p>I want to filter the model <code>Foo</code> by its manyTomany field <code>bar</code> with users <code>bar</code>.</p>
<p>Models</p>
<pre><code>class User(models.Model):
bar = models.ManyToManyField("Bar", verbose_name=_("Bar"), blank=True)
class Foo(models.Model):
bar = models.ManyToManyFiel... | <pre><code>foos = Foo.objects.filter(bar__in=user.bar.all())
</code></pre> | python|django|django-models | 1 |
205 | 60,981,187 | Not able to align specific patterns side by side in this grid | <p><a href="https://i.stack.imgur.com/CZzNP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CZzNP.png" alt=""></a></p>
<p>So I tried different methods to do this like:</p>
<pre><code>a = ("+ " + "- "*4)
b = ("|\n"*4)
print(a + a + "\n" + b + a + a + "\n" + b + a + a)
</code></pre>
<p>But the basi... | <p>I got it actually and thought of posting the solution I might help others:
we ought to make use of the do_twice and do_four function:</p>
<pre><code>def draw_grid_art():
a = "+ - - - - + - - - - +"
def do_twice(f):
f()
f()
def do_four(f):
do_twice(f)
do_twice(f)
def vertical():
b ... | python|function | 0 |
206 | 60,948,399 | How to remove rows that contains a repeating number pandas python | <p>I have a dataframe like:</p>
<pre><code>'a' 'b' 'c' 'd'
0 1 2 3
3 3 4 5
9 8 8 8
</code></pre>
<p>and I want to remove rows that have a number that repeats more than once. So the answer is :</p>
<pre><code>'a' 'b' 'c' 'd'
0 1 2 3
</code></pre>
<p>Thanks.</p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nunique.html" rel="noreferrer"><code>DataFrame.nunique</code></a> with compare length of columns ad filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="noreferrer"><code>... | python|pandas|dataframe | 5 |
207 | 69,002,851 | Slowly updating global window side inputs In Python | <p>I try to get the updating sideinputs working in python as stated in the Documentation (there is only a java example provided) [https://beam.apache.org/documentation/patterns/side-inputs/]</p>
<p>I already found this thread here on Stackoverflow: [https://stackoverflow.com/questions/63812879/how-to-implement-the-slow... | <p>The reason why all of the elements from <code>PeriodicImpulse</code> are emitted at the same time is because of the parameters you use when creating the transform. The documentation of the transform states that the arguments <code>start_timestamp</code> and <code>stop_timestamp</code> are timestamps, and (despite th... | python|apache-beam | 1 |
208 | 69,042,451 | StaleElementReferenceException while looping over list | <p>I'm trying to make a webscraper for <a href="https://opendata-dashboard.cijfersoverwonen.nl/dashboard/opendata-dashboard/beleidswaarde" rel="nofollow noreferrer">this</a> website. The idea is that code iterates over all institutions by selecting the institution's name (3B-Wonen at first instance), closes the pop-up ... | <p>This code worked for me. But I am not doing <code>driver.find_element_by_id("utils-export-spreadsheet").click()</code></p>
<pre><code>from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome(executable_path="path")
driv... | python|selenium|staleelementreferenceexception | 1 |
209 | 72,741,276 | SQLite|Pandas|Python: Select rows that contain values in any column? | <p>I have an SQLite table with 13500 rows with the following SQL schema:</p>
<pre><code>PRAGMA foreign_keys = false;
-- ----------------------------
-- Table structure for numbers
-- ----------------------------
DROP TABLE IF EXISTS "numbers";
CREATE TABLE "numbers" (
"RowId" INTEGER NO... | <p>Here's an SQLite query that will give you the results you want. It creates a CTE of all the values of interest, then joins your <code>numbers</code> table to the CTE if any of the columns contain the value from the CTE, selecting only <code>RowId</code> values from <code>numbers</code> where the number of rows in th... | python|python-3.x|pandas|dataframe|sqlite | 2 |
210 | 59,263,662 | How to configure logging with colour, format etc in separate setting file in python? | <p>I am trying to call python script from bash script.
(Note: I am using python version 3.7)
Following is the Directory structure (so_test is a directory)</p>
<pre><code>so_test
shell_script_to_call_py.sh
main_file.py
log_settings.py
</code></pre>
<p>files are as below,</p>
<p><strong>shell_script_to_call_py.s... | <p>I got the code working with the following changes:</p>
<ol>
<li><p>Declare 'log' variable outside the function in log_settings.py, so that it can be imported by other programs.</p></li>
<li><p>Rename the function named log_config to log_conf, which is referred in the main program.</p></li>
<li><p>In the main progra... | python-3.x|logging|python-logging | 1 |
211 | 63,222,141 | How to slice Data frame with Pandas, and operate on each slice | <p>I'm new into pandas and python in general and I want to <strong>know your opinion about the best way</strong> to create a new data frame using slices of an "original" data frame.</p>
<p>input (original df):</p>
<pre><code> date author_id time_spent
0 2020-01-02 1 2.5
1 2020-... | <p>What we will do</p>
<pre><code>df = df.groupby(['date','author_id'])['time_spent'].sum().reset_index()
date author_id time_spent
0 2020-01-01 1 3.0
1 2020-01-01 2 3.0
2 2020-01-01 3 3.5
3 2020-01-02 1 4.0
4 2020-01-02 2 ... | python|pandas|dataframe | 2 |
212 | 63,196,745 | Convert one-hot encoded data-frame columns into one column | <p>In the pandas data frame, the one-hot encoded vectors are present as columns, i.e:</p>
<pre><code>Rows A B C D E
0 0 0 0 1 0
1 0 0 1 0 0
2 0 1 0 0 0
3 0 0 0 1 0
4 1 0 0 0 0
4 0 0 0 0 1
</code></pre>
<p>How to convert these columns into one data frame colum... | <p>Try with <code>argmax</code></p>
<pre><code>#df=df.set_index('Rows')
df['New']=df.values.argmax(1)+1
df
Out[231]:
A B C D E New
Rows
0 0 0 0 1 0 4
1 0 0 1 0 0 3
2 0 1 0 0 0 2
3 0 0 0 1 0 4
4 1 0 0 0 0 1
4 0 0 0 0 1 5
<... | python|pandas|numpy|dataframe | 6 |
213 | 59,608,406 | Odoo 11 - Action Server | <p>Here is my code for a custom action declaration:</p>
<pre><code> <record id="scheduler_synchronization_update_school_and_grade" model="ir.cron">
<field name="name">Action automatisee ...</field>
<field name="user_id" ref="base.user_root"/>
<field... | <p>You missed the <code>state</code> field in the cron definition. This is the "Action To Do" field. Try following:</p>
<pre><code> <record id="scheduler_synchronization_update_school_and_grade" model="ir.cron">
<field name="name">Action automatisee ...</field>
<field name="user... | python|xml|odoo | 1 |
214 | 48,993,334 | Execute python script in Qlik Sense load script | <p>I am trying to run python script inside my load script in Qlik Sense app.</p>
<p>I know that I need to put <code>OverrideScriptSecurity=1</code> in <code>Settings.ini</code></p>
<p>I put</p>
<pre><code>Execute py lib://python/getSolution.py 100 'bla'; // 100 and 'bla' are parameters
</code></pre>
<p>and I get no... | <p>I figure out what was wrong.
For all others that would have similar problems:</p>
<p>Problem is in space in path.
If I move my script in c:\Windows\getSolution.py it work. I also need to change the python path to c:\Windows\py.exe</p>
<p>so end script looks like:</p>
<pre><code>Execute c:\Windows\py.exe c:\Wind... | python|qliksense | 1 |
215 | 49,203,023 | openAI Gym NameError in Google Colaboratory | <p>I've just installed openAI gym on Google Colab, but when I try to run 'CartPole-v0' environment as <a href="https://gym.openai.com/docs/" rel="noreferrer">explained here</a>.</p>
<p>Code:</p>
<pre><code>import gym
env = gym.make('CartPole-v0')
for i_episode in range(20):
observation = env.reset()
for t in ... | <p>One way to render gym environment in google colab is to use pyvirtualdisplay and store rgb frame array while running environment. Environment frames can be animated using animation feature of matplotlib and HTML function used for Ipython display module.
You can find the implementation <a href="https://colab.research... | python|google-colaboratory|openai-gym | 12 |
216 | 70,940,598 | I need example on how to mention using PTB | <p>I need further elaboration on this thread <a href="https://stackoverflow.com/questions/40905948/how-can-i-mention-telegram-users-without-a-username">How can I mention Telegram users without a username?</a></p>
<p>Can someone give me an example of how to use the markdown style? I am also using PTB library</p>
<p>The ... | <p>Alright, so I finally found the answer. The example below should work.</p>
<pre><code>context.bot.send_message(chat_id=update.effective_chat.id,
parse_mode = ParseMode.MARKDOWN_V2,
text = "[inline mention of a user](tg://user?id=123456789)")
</code></pre> | python|python-telegram-bot | 0 |
217 | 60,208,374 | Increasing distances among nodes in NetworkX | <p>I'm trying to create a network of approximately 6500 nodes for retweets. The shape of network looks so bad with a very low distance among node. I've tried spring_layout to increase the distances but it didn't change anything.</p>
<pre><code>nx.draw(G, with_labels=False, node_color=color_map_n, node_size=5,layout=nx... | <p>I swapped "layout=..." with "pos=..." and it worked</p> | python|matplotlib|networkx|pos | 0 |
218 | 67,953,320 | Selenium not sending keys to input field | <p>I'm trying to scrape this url <a href="https://www.veikkaus.fi/fi/tulokset#!/tarkennettu-haku" rel="nofollow noreferrer">https://www.veikkaus.fi/fi/tulokset#!/tarkennettu-haku</a></p>
<p>There's three main parts to the scrape:</p>
<ol>
<li>Select the correct game type from "Valitse peli" <br />
For this I ... | <p>For me, simply doing the following works:</p>
<pre><code>driver.find_element_by_css_selector('.date-input.from-date').send_keys(from_date)
ActionChains(driver).send_keys(Keys.RETURN).perform()
driver.find_element_by_css_selector('.date-input.to-date').send_keys(to_date)
ActionChains(driver).send_keys(Keys.RETURN).pe... | python|css|selenium|web-scraping | 1 |
219 | 67,015,296 | Python Multiple Datetimes To One | <p>I have two types of datetime format in a Dataframe.</p>
<pre><code>Date
2019-01-06 00:00:00 (%Y-%d-%m %H:%M:%S')
07/17/2018 ('%m/%d/%Y')
</code></pre>
<p>I want to convert into one specific datetime format. Below is the script that I am using</p>
<pre><code>d1 = pd.to_datetime(df1['DATE'], format='%m/%d/%Y',errors=... | <p>If there are mixed format also in format <code>2019-01-06 00:00:00</code> - it means it should be January or June, only ways is prioritize one format - e.g. here first months and add first format <code>d2</code> and then <code>d3</code> in chained <code>fillna</code>:</p>
<pre><code>d1 = pd.to_datetime(df1['DATE'],... | python|pandas|dataframe|datetime|datetime-format | 2 |
220 | 72,257,321 | pandas change all rows with Type X if 1 Type X Result = 1 | <p>Here is a simple pandas df:</p>
<pre><code>>>> df
Type Var1 Result
0 A 1 NaN
1 A 2 NaN
2 A 3 NaN
3 B 4 NaN
4 B 5 NaN
5 B 6 NaN
6 C 1 NaN
7 C 2 NaN
8 C 3 NaN
9 D 4 NaN
10 D 5 ... | <p>Create boolean mask and for <code>True/False</code> to <code>1/0</code> mapp convert values to integers:</p>
<pre><code>df['Result'] = df['Type'].isin(df.loc[df['Var1'].eq(3), 'Type']).astype(int)
#alternative
df['Result'] = np.where(df['Type'].isin(df.loc[df['Var1'].eq(3), 'Type']), 1, 0)
print (df)
Type Var1 ... | pandas | 1 |
221 | 50,909,754 | Referencing folder without absolute path | <p>I am writing a code that will be implemented alongside my company's software. My code is written in Python and requires access to a data file (<code>.ini</code> format) that will be stored on the user's desktop, inside the software's shortcuts folder.</p>
<p>This being said, I want to be able to read/write from tha... | <p>In windows, desktop absolute path looks like this:</p>
<pre><code>%systemdrive%\users\%username%\Desktop
</code></pre>
<p>So this path will fit your requirements:</p>
<pre><code>%systemdrive%\users\%username%\Desktop\Parameters\ParameterUpdate.ini
</code></pre>
<p>Please make sure u don't actually mean public de... | python|path | 1 |
222 | 35,267,743 | Subscription modelling in Flask SQLAlchemy | <p>I am trying to model the following scenario in Flask SQLAlchemy:</p>
<p>There are a list of <code>SubscriptionPacks</code> available for purchase. When a particular <code>User</code> buys a <code>SubscriptionPack</code> they start an instance of that <code>Subscription</code>.</p>
<p>The model is as follows:</p>
... | <p>For those who stumble upon this, what I was looking for was the <a href="http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html" rel="nofollow">bidirectional SQLAlchemy Association Object pattern</a>.</p>
<p>This allows the intermediate table of a Many-to-Many to have it's own stored details. In my insta... | python|orm|flask|sqlalchemy|flask-sqlalchemy | 1 |
223 | 26,545,188 | Append information to failed tests | <p>I have some details I have to print out for a failed test. Right now I'm just outputting this information to STDOUT and I use the -s to see this information. But I would like to append this information to the test case details when it failed, and not need to use the -s option.</p> | <p>You can just keep printing to stdout and simply not use <code>-s</code>. If you do this py.test will put the details you printed next to the assertion failure message when the test fails, in a "captured stdout" section.</p>
<p>When using <code>-s</code> things get worse since they are also printed to stdout even i... | python|pytest | 0 |
224 | 57,763,773 | Install Numpy Requirement in a Dockerfile. Results in error | <p>I am attempting to install a numpy dependancy inside a docker container. (My code heavily uses it). On building the container the numpy library simply does not install and the build fails. This is on OS raspbian-buster/stretch. This does however work when building the container on MAC OS. </p>
<p>I suspect some kin... | <p>To use Numpy on python3 here, we first head over to the <a href="https://docs.scipy.org/doc/numpy/user/building.html" rel="noreferrer">official documentation</a> to find what dependencies are required to build Numpy.</p>
<p>Mainly these 5 packages + their dependencies must be installed:</p>
<ol>
<li>Python3 - 70 m... | numpy|docker|docker-compose | 7 |
225 | 28,535,121 | Python program can not import dot parser | <p>I am trying to run a huge evolution simulating python software from the command line. The software is dependent on the following python packages:</p>
<p>1-networkX </p>
<p>2-pyparsing</p>
<p>3-numpy</p>
<p>4-pydot </p>
<p>5-matplotlib</p>
<p>6-graphviz</p>
<p>The error I get is this:</p>
<pre><code>Couldn't ... | <p>Any particular reason you're not using the newest version of pydot?</p>
<p>This revision of 1.0.2 looks like it fixes exactly that problem:</p>
<p><a href="https://code.google.com/p/pydot/source/diff?spec=svn10&r=10&format=side&path=/trunk/pydot.py" rel="nofollow">https://code.google.com/p/pydot/source... | python|numpy|graphviz|pydot | 3 |
226 | 53,681,564 | How to extract specific time period from Alpha Vantage in Python? | <p>outputsize='compact' is giving last 100 days, and outputsize='full' is giving whole history which is too much data. Any idea how to write a code that extract some specific period? </p>
<pre><code>ts=TimeSeries(key='KEY', output_format='pandas')
data, meta_data = ts.get_daily(symbol='MSFT', outputsize='compact')
pri... | <p>This is how I was able to get the dates to work</p>
<pre><code>ts = TimeSeries (key=api_key, output_format = "pandas")
data_daily, meta_data = ts.get_daily_adjusted(symbol=stock_ticker, outputsize ='full')
start_date = datetime.datetime(2000, 1, 1)
end_date = datetime.datetime(2019, 12, 31)
# Create... | python|alpha-vantage | 0 |
227 | 41,189,951 | How do I get hundreds of DLL files? | <p>I am using python and I am trying to install the GDAL library. I kept having an error telling me that many DLL files were missing so I used the software Dependency Walker and it showed me that 330 DLL files were missing...</p>
<p>My question is: How do I get that much files without downloading them one by one on a ... | <p>First of all, never download <code>.dll</code> files from shady websites.</p>
<p>The best way of repairing missing dependencies is to reinstall the software that shipped the <code>.dll</code> files completely.</p> | python|dll|gdal | 2 |
228 | 54,477,877 | How to change the performance metric from accuracy to precision, recall and other metrics in the code below? | <p>As a beginner in scikit-learn, and trying to classify the iris dataset, I'm having <em>problems with adjusting the scoring metric</em> from <code>scoring='accuracy'</code> to <em>others like precision, recall, f1</em> etc., in the cross-validation step. Below is the <strong>full</strong> code sample (<strong>enough ... | <blockquote>
<p>1) I guess the above is happening because 'precision' and 'recall' are defined in scikit-learn only for binary classification-is that correct?</p>
</blockquote>
<p>No. Precision & recall are certainly valid for multi-class problems, too - see the docs for <a href="https://scikit-learn.org/stable/... | python|machine-learning|scikit-learn|multiclass-classification | 2 |
229 | 39,711,473 | Cannot find django.views.generic . Where is generic. Looked in all folders for the file | <p>I know this is a strange question but I am lost on what to do. i cloned pinry... It is working and up . I am trying to find django.views.generic. I have searched the directory in my text editor, I have looked in django.views. But I cannot see generic (only a folder with the name "generic"). I cant understand where t... | <p>Try running this from a Python interpreter: </p>
<pre><code>>>> import django.views.generic
>>> django.views.generic.__file__
</code></pre>
<p>This will show you the location of the <code>gerneric</code> as a string path. In my case the output is:</p>
<pre><code>'/.../python3.5/site-packages/dja... | python|django|generics | 3 |
230 | 38,022,480 | Django- limit_choices_to using 2 different tables | <p>I fear that what I am trying to do might be impossible but here we go:</p>
<p>Among my models, I have the following</p>
<pre><code>Class ParentCategory(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
Class Category(models.Model):
parentCategory ... | <p>Maybe this will work:</p>
<pre><code>limit_choices_to={'parentCategory__name': 'comp method'}
</code></pre> | python|django|django-models | 1 |
231 | 58,057,031 | How to reduce the retry count for kubernetes cluster in kubernetes-client-python | <p>I need to reduce the retry count for unavailable/deleted kubernetes cluster using kubernetes-client-python, currently by default it is 3.</p>
<pre><code>WARNING Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.Verif... | <p>Sadly it seems that it's not possible because:</p>
<p>Python client use urlib3 PoolManager to make requests as you can see there </p>
<p><a href="https://github.com/kubernetes-client/python/blob/master/kubernetes/client/rest.py#L162" rel="nofollow noreferrer">https://github.com/kubernetes-client/python/blob/master... | python|kubernetes|kubernetes-pod|kubernetes-python-client|kubeconfig | 2 |
232 | 55,481,872 | Sum value by group by and cumulatively add to separate list or numpy array cumulatively and use the last value in conditional statement | <p>I want to sum the values for multi-level index pandas dataframe. I would then like to add this value to another value in a cumulative fashion. I would then like to use a conditional statement which is dependant on the last value of this cumulative list for the next index value of the same level.</p>
<p>I have been ... | <p>Let's change balance to a pd.Series:</p>
<pre><code>balance = pd.Series([20000])
Your code
#change this line
df['BET'] = np.where(df.groupby(level = 0)['LIABILITY'].transform('sum') < 0.75*balance.values.tolist()[-1], df['POT_BET'], 0)
Your code
balance = pd.concat([balance, results]).cumsum().tolist()
</code>... | python|pandas|numpy | 3 |
233 | 55,216,093 | Questions Tags Users Unanswered shifting specific column to before/after specific column in dataframe | <p>In dataframe example :</p>
<pre><code> medcine_preg_oth medcine_preg_oth1 medcine_preg_oth2 medcine_preg_oth3
0 Berplex Berplex None None
1 NaN NaN NaN NaN
2 NaN NaN NaN ... | <p>You can re-arrange your columns like this:</p>
<pre><code>re_ordered_columns = ['medicine_pred_oth','medcine_preg_oth1','medcine_preg_oth2','medcine_preg_oth3']
df = df[re_ordered_columns+df.columns.difference(re_ordered_columns).tolist()]
</code></pre>
<p>add the remaining columns in place of <code>...</code></p> | python|pandas|dataframe|data-cleaning | 0 |
234 | 45,646,569 | padding a batch with 0 vectors in dynamic rnn | <p>I have a prediction task working with variable sequences of input data. Directly using a dynamic rnn will run into the trouble of splitting the outputs according to this post:</p>
<p><a href="https://stackoverflow.com/questions/34970582/using-a-variable-for-num-splits-for-tf-split">Using a variable for num_splits f... | <p>These days (2022) two methods you can use to pad sequences in tensorflow are using a tf.data.Dataset pipeline, or preprocessing with tf.keras.utils.pad_sequences.</p>
<h2>Method 1: Use Tensorflow Pipelines (tf.data.Dataset)</h2>
<p>The padded_batch() method can be used in place of a normal batch() method to pad the ... | tensorflow|rnn | 1 |
235 | 57,127,821 | Login to a website then open it in browser | <p>I am trying to write a Python 3 code that logins in to a website and then opens it in a web browser to be able to take a screenshot of it.
Looking online I found that I could do webbrowser.open('example.com')
This opens the website, but cannot login.
Then I found that it is possible to login to a website using the r... | <p>Have you considered <a href="https://www.seleniumhq.org/" rel="nofollow noreferrer">Selenium</a>? It drives a browser natively as a user would, and its Python client is pretty easy to use. </p>
<p>Here is one of my latest works with Selenium. It is a script to scrape multiple pages from a certain website and save t... | python-3.x|request|urllib | 0 |
236 | 44,734,655 | scrapy callback doesnt work in function | <p>When executing the first <strong>yield</strong> it will not go into the function <strong>parse_url</strong> and when executing the second <strong>yield</strong> it will not go back the function <strong>parse</strong> and it just end. During the whole process, there are no exceptions. I don't know how to deal with th... | <p>If you carefully looked at the logs then you might have noticed that <code>scrapy</code> filtered offsite domain requests. This means when <code>scrapy</code> tried to ping <code>short.58.com</code> and <code>jxjump.58.com</code>, it did not follow through. You can add those domains to the <code>allowed_domains</cod... | python-3.x|scrapy | 3 |
237 | 36,155,760 | Splitting HTML text by <br> while using beautifulsoup | <p>HTML code:</p>
<pre><code><td> <label class="identifier">Speed (avg./max):</label> </td> <td class="value"> <span class="block">4.5 kn<br>7.1 kn</span> </td>
</code></pre>
<p>I need to get values 4.5 kn and 7.1 as separate list items so I could append them sepa... | <p>Locate the "Speed (avg./max)" label first and then go to the value via <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all-next-and-find-next" rel="nofollow"><code>.find_next()</code></a>:</p>
<pre><code>from bs4 import BeautifulSoup
data = '<td> <label class="identifier">Speed (... | python|regex|beautifulsoup | 0 |
238 | 46,356,238 | Repeating if statement | <p>I am having a problem with my code mapping a random walk in 3D space. The purpose of this code is to simulate N steps of a random walk in 3 dimensions. At each step, a random direction is chosen (north, south, east, west, up, down) and a step of size 1 is taken in that direction. Here is my code:</p>
<pre><code>imp... | <p>If you remove the multiple <code>n = random.random()</code> from within the if statements and replace by a single <code>n = random.random()</code> at start of the while loop then there will be only one step per loop.</p> | python | 2 |
239 | 21,538,254 | Trying to create and use a class; name 'is_empty' is not defined | <p>I'm trying to create a class called <code>Stack</code> (it's probably not very useful for writing actual programmes, I'm just doing it to learn about creating classes in general) and this is my code, identical to the example in the guide I'm following save for one function name:</p>
<pre><code>class Stack:
def ... | <p>The method <code>is_empty()</code> is part of the class. To call it you need to <code>my_stack.is_empty()</code></p> | python|python-3.x | 3 |
240 | 24,869,306 | How to control if a component exists in a Tk object/window? | <p>I would like to know what is the most effecient way to control if a certain component (label, button or entry) exists already on the Tk object/window.</p>
<p>I have searched on the web for a while and the only thing I found is:</p>
<p><code>if component.winfo_exists(): # But this doesn't work for me (I am using Py... | <p>I think your second approach is good enough.</p>
<pre><code>self.label = None # Initialize `self.label` as None somewhere.
...
if not self.label:
self.label = Label(self, text="Label")
</code></pre>
<p>This will work, because before the label creation, <code>self.label</code> is evaluated as false when use... | python|python-3.x|tkinter|python-3.4 | 1 |
241 | 40,186,467 | How to determine the version of PyJWT? | <p>I have two different software environments (<strong>Environment A</strong> and <strong>Environment B</strong>) and I'm trying to run PyJWT on both environments. It is working perfectly fine on one environment <strong>Environment A</strong> but fail on <strong>Environment B</strong>. </p>
<p>The error I'm getting on... | <p>The PyJWT <code>.__version__</code> attribute appeared in <code>0.2.2</code> in <a href="https://github.com/jpadilla/pyjwt/commit/d626f7e034c5a19627ba7a65dacc25d1e21d6573" rel="nofollow">this</a> commit.</p>
<p>Generally, to find the version of the package, that was installed via setuptools, you need to run followi... | python|pyjwt | 5 |
242 | 40,113,514 | Setting up proxy with selenium / python | <p>I am using selenium with python.
I need to configure a proxy.</p>
<p>It is working for HTTP but not for HTTPS.</p>
<p>The code I am using is:</p>
<pre><code># configure firefox
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", '11.111... | <p>Check out <a href="https://github.com/AutomatedTester/browsermob-proxy-py" rel="nofollow">browsermob proxy</a> for setting up a proxies for use with <code>selenium</code></p>
<pre><code>from browsermobproxy import Server
server = Server("path/to/browsermob-proxy")
server.start()
proxy = server.create_proxy()
from ... | python|selenium|proxy | 1 |
243 | 51,588,981 | link in html do not function | <p>python 2.7 DJANGO 1.11.14 win7</p>
<p>when I click the link in FWinstance_list_applied_user.html it was supposed to jump to FW_detail.html but nothing happened</p>
<p>url.py</p>
<pre><code>urlpatterns += [
url(r'^myFWs/', views.LoanedFWsByUserListView.as_view(), name='my-applied'),
url(r'^myFWs/(?P&l... | <p>You haven't terminated your "my-applied" URL pattern, so it matches everything <em>beginning</em> with "myFWs/" - including things that that would match the detail URL. Make sure you always use a terminating <code>$</code> with regex URLs.</p>
<pre><code>url(r'^myFWs/$', views.LoanedFWsByUserListView.as_view(), nam... | python|django | 2 |
244 | 38,676,937 | Allow_Other with fusepy? | <p>I have a 16.04 ubuntu server with <a href="https://github.com/sondree/b2_fuse/issues" rel="nofollow">b2_fuse</a> mounting my b2 cloud storage bucket which uses pyfuse. The problem is, I have no idea how I can pass the allow_other argument like with FUSE! This is an issue because other services running under differ... | <p>Inside of file <code>b2fuse.py</code> if you change the line:</p>
<pre><code>FUSE(filesystem, mountpoint, nothreads=True, foreground=True)
</code></pre>
<p><em>to</em></p>
<pre><code>FUSE(filesystem, mountpoint, nothreads=True, foreground=True,**{'allow_other': True})
</code></pre>
<p>the volume will be mounted ... | python|fuse | 5 |
245 | 40,703,458 | Python3 + vagrant ubuntu 16.04 + ssl request = [Errno 104] Connection reset by peer | <p>I'm using on my Mac Vagrant with "bento/ubuntu-16.04" box. I'm trying to use Google Adwords Api via python library but got error <code>[Errno 104] Connection reset by peer</code></p>
<p>I make sample script to check possibility to send requests:</p>
<pre><code>import urllib.request
url ="https://adwords.google.co... | <p>I found solution. It looks like bug in Virtualbox 5.1.8 version. You can read about it <a href="https://github.com/mitchellh/vagrant/issues/7946" rel="nofollow noreferrer">here</a></p>
<p>So, you can fix it by downgrade Virtualbox to < 5.1.6</p> | python|google-api|vagrant|python-3.5|ubuntu-16.04 | 0 |
246 | 44,287,861 | While loop causing issues with CSV read | <p>Everything was going fine until I tried to combine a while loop with a CSV read and I am just unsure where to go with this.</p>
<p>The code that I am struggling with:</p>
<pre><code>airport = input('Please input the airport ICAO code: ')
with open('airport-codes.csv', encoding='Latin-1') as f:
reader = csv.read... | <p>I had a different suggestion using functions:</p>
<pre><code>import csv
def findAirportCode(airport):
with open('airport-codes.csv', encoding='Latin-1') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if airport.lower() == row[0].lower():
airp... | python|csv|while-loop | 0 |
247 | 47,409,456 | Getting next Timestamp Value | <p>What is the proper solution in pandas to get the next timestamp value?</p>
<p>I have the following timestamp:</p>
<pre><code>Timestamp('2017-11-01 00:00:00', freq='MS')
</code></pre>
<p>I want to get this as the result for the next timestamp value:</p>
<pre><code>Timestamp('2017-12-01 00:00:00', freq='MS')
</cod... | <p>General solution is convert strings to <code>offset</code> and add to timestamp:</p>
<pre><code>L = ['1min', '5min', '15min', '60min', 'D', 'W-SUN', 'MS']
t = pd.Timestamp('2017-11-01 00:00:00', freq='MS')
t1 = [t + pd.tseries.frequencies.to_offset(x) for x in L]
print (t1)
[Timestamp('2017-11-01 00:01:00', freq=... | python|pandas | 3 |
248 | 43,403,894 | Django 1.10 Count on Models ForeignKey | <p>I guess this must be simple, but I've been trying for hours and can't find anything to help.</p>
<p>I have 2 models. One for a <strong>Template Categories</strong> and another for a <strong>Template</strong></p>
<p>I'm listing the Template Categories on the Homepage and for each Category I want to show how many te... | <p><strong>Views.py</strong></p>
<pre><code>from django.shortcuts import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.db.models import Count
from .models import TemplateType
from .models import TemplateFile
def home(request):
queryset = TemplateType.objects.order_by('type_title... | python|django | 0 |
249 | 43,291,347 | Internal Error 500 when using Flask and Apache | <p>I am working on a small college project using Raspberry Pi. Basically, the project is to provide an html interface to control a sensor attached to the Pi. I wrote a very simple Python code attached with a very basic html code also. Everything is done in this path /var/www/NewTest. However everytime I try to access i... | <p>The problem was in led.conf. The user needs to be pi.</p>
<pre><code><virtualhost *:80>
ServerName 10.0.0.146
WSGIDaemonProcess led user=pi group=www-data threads=5 home=/var/www/NewTest/
WSGIScriptAlias / /var/www/NewTest/led.wsgi
<directory /var/www/NewTest>
WSGIProcessGroup ... | python|apache|flask|raspberry-pi|raspbian | 0 |
250 | 37,083,434 | lmdb no locks available error | <p>I have a data.mdb and lock.mdb file in test/ directory. I was trying to use the python lmdb package to read/write data from the lmdb database. I tried</p>
<pre><code>import lmdb
env = lmdb.open('test', map_size=(1024**3), readonly=True)
</code></pre>
<p>but got the following error:</p>
<pre><code>lmdb.Error: te... | <p>Use the -r option in mdb_stat to check the number of readers in the reader lock table. You may be hitting the max limit for number of readers. You can try setting this limit to a higher number.</p> | python|lmdb | 0 |
251 | 51,234,035 | Neural networks pytorch | <p>I am very new in pytorch and implementing my own network of image classifier. However I see for each epoch training accuracy is very good but validation accuracy is 0.i noted till 5th epoch. I am using Adam optimizer and have learning rate .001. also resampling the whole data set after each epoch into training n val... | <p>I think you did not take into account that <code>acc += torch.sum(predClass == labels.data)</code> returns a tensor instead of a float value. Depending on the version of pytorch you are using I think you should change it to:</p>
<pre><code>acc += torch.sum(predClass == labels.data).cpu().data[0] #pytorch 0.3
acc +=... | python|machine-learning|conv-neural-network|pytorch | 2 |
252 | 24,787,962 | How to feed weights into igraph community detection [Python/C/R] | <p>When using <code>commuinity_leading_eigenvector</code> of <a href="http://igraph.org/python/doc/igraph.Graph-class.html#community_leading_eigenvector" rel="nofollow">igraph</a>, assuming a graph g has already been created, how do I pass the list of weights of graph g to <code>community_leading_eigenvector</code>?</p... | <p>You can either pass the name of the attribute containing the weights to the <code>weights</code> parameter, or retrieve all the weights into a list using <code>g.es["weight"]</code> and then pass that to the <code>weights</code> parameter. So, either of these would suffice, assuming that your weights are in the <cod... | python|c|r|graph|igraph | 3 |
253 | 40,845,169 | Aggregation fails when using lambdas | <p>I'm trying to port parts of my application from pandas to dask and I hit a roadblock when using a lamdba function in a groupby on a dask DataFrame.</p>
<pre><code>import dask.dataframe as dd
dask_df = dd.from_pandas(pandasDataFrame, npartitions=2)
dask_df = dask_df.groupby(
['one', 'two', '... | <p>From <a href="https://docs.dask.org/en/latest/dataframe-groupby.html#aggregate" rel="nofollow noreferrer">the Dask docs</a>:</p>
<p>"Dask supports Pandas’ aggregate syntax to run multiple reductions on the same groups. Common reductions such as max, sum, list and mean are directly supported.</p>
<p>Dask also su... | python|dask | 0 |
254 | 38,468,549 | how to convert pandas series to tuple of index and value | <p>I'm looking for an efficient way to convert a series to a tuple of its index with its values.</p>
<pre><code>s = pd.Series([1, 2, 3], ['a', 'b', 'c'])
</code></pre>
<p>I want an array, list, series, some iterable:</p>
<pre><code>[(1, 'a'), (2, 'b'), (3, 'c')]
</code></pre> | <p>Well it seems simply <code>zip(s,s.index)</code> works too!</p>
<p>For Python-3.x, we need to wrap it with <code>list</code> -</p>
<pre><code>list(zip(s,s.index))
</code></pre>
<p>To get a tuple of tuples, use <code>tuple()</code> : <code>tuple(zip(s,s.index))</code>.</p>
<p>Sample run -</p>
<pre><code>In [8]: ... | python|pandas|series|iterable | 59 |
255 | 31,029,641 | Python Kivy: Add Background loop | <p>I want to paste a background loop into my Python-Kivy script. The problem is, that I've got only a <code>App().run()</code> under my script. So, if I put a loop, somewhere in the the App-Class, the whole App stopps updating and checking for events. Is there a function name like <code>build(self)</code>, that's recog... | <p>In case you need to schedule a repeated activity in a loop, you can use <code>Clock.schedule_interval()</code> to call a function on a regular schedule:</p>
<pre><code>def my_repeated_function(data):
print ("My function called.")
Clock.schedule_interval(my_repeated_function, 1.0 / 30) # no brackets on function... | android|python|infinite-loop|kivy | 2 |
256 | 40,305,692 | How to learn multi-class multi-output CNN with TensorFlow | <p>I want to train a convolutional neural network with TensorFlow to do multi-output multi-class classification.</p>
<p>For example: If we take the MNIST sample set and always combine two random images two a single one and then want to classify the resulting image. The result of the classification should be the two di... | <p>For nomenclature of classification problems, you can have a look at this link:
<a href="http://scikit-learn.org/stable/modules/multiclass.html" rel="nofollow noreferrer">http://scikit-learn.org/stable/modules/multiclass.html</a></p>
<p>So your problem is called "Multilabel Classification". In normal TensorFlow mult... | tensorflow|conv-neural-network | 3 |
257 | 29,043,138 | Using Tweepy to determine the age on an account | <p>I'm looking to use Tweepy for a small project. I'd like to be able to write a bit of code that returns the age of a given Twitter account. The best way I can think of to do this is to return all Tweets from the very first page, find the earliest Tweet and check the date/timestamp on it. </p>
<p>It's a bit hacky but... | <p>The get_user method returns a user object that includes a created_at field.</p>
<p>Check <a href="https://dev.twitter.com/overview/api/users" rel="nofollow">https://dev.twitter.com/overview/api/users</a></p> | python|date|twitter|tweepy | 1 |
258 | 58,619,136 | how to remove /n and comma while extracting using response.css | <p>I am trying to crawl amazon to get product name, price and [savings information]. i am using response.css to extract [saving information] as below</p>
<p>python code to extract [savings information]:</p>
<pre><code>savingsinfo = amzscrape.css(".a-color-secondary .a-row , .a-row.a-size-small.a-color-secondary span"... | <pre class="lang-py prettyprint-override"><code>output = ''.join(savingsinfo['savingsinfo_item'])
</code></pre> | python|css|web-scraping | 2 |
259 | 52,358,022 | BeautifulSoup not defined when called in function | <p>My web scraper is throwing <code>NameError: name 'BeautifulSoup' is not defined</code> when I call BeautifulSoup() inside my function, but it works normally when I call it outside the function and pass the Soup as an argument. </p>
<p>Here is the working code:</p>
<pre><code>from teams.models import *
from bs4 imp... | <p>I guess you are doing some spelling mistake of BeautifulSoup, its case sensitive. if not, use requests in your code as:</p>
<pre><code>from teams.models import *
from bs4 import BeautifulSoup
from django.conf import settings
import requests, os, string
def scrapeTeamPage(url):
res = requests.get(url)
soup ... | python|beautifulsoup | 2 |
260 | 19,037,703 | Missing parameters when creating new table in Google BigQuery through Python API V2 | <p>I'm trying to create new table using BigQuery's Python API:</p>
<pre><code>bigquery.tables().insert(
projectId="xxxxxxxxxxxxxx",
datasetId="xxxxxxxxxxxxxx",
body='{
"tableReference": {
"projectId":"xxxxxxxxxxxxxx",
"tableId":"xxxxxxxxxxxxxx",
"datasetId":"a... | <p>The only required parameter for a <code>tables.insert</code> is the <code>tableReference</code>, which must have <code>tableId</code>, <code>datasetId</code>, and <code>projectId</code> fields. I think the actual issue may be that you're passing the JSON string when you could just pass a <code>dict</code> with the v... | python|google-bigquery | 2 |
261 | 69,072,902 | Loop does not iterate over all data | <p>I have code that produces the following df as output:</p>
<pre><code> year month day category keywords
0 '2021' '09' '06' 'us' ['afghan, refugees, volunteers']
1 '2021' '09' '05' 'u... | <p>I think the problem is that with:</p>
<pre class="lang-py prettyprint-override"><code>for p in df.loc[i, 'keywords']:
</code></pre>
<p>you are iterating over the letters in the first entry. So you will stop at that count.</p>
<p>This should work for you:</p>
<pre class="lang-py prettyprint-override"><code>for testst... | python|loops | 1 |
262 | 68,898,700 | How use asyncio with pyqt6? | <p>qasync doesn't support pyqt6 yet and I'm trying to run discord.py in the same loop as pyqt but so far I'm not doing the best. I've tried multiprocess, multithread, and even running synchronous code from non-synchronous code but I either end up with blocking code that makes the pyqt program non responsive or it just ... | <p><del>qasync does not currently support PyQt6 but I have created a <a href="https://github.com/CabbageDevelopment/qasync/pull/53" rel="nofollow noreferrer">PR</a> that implements it.</del></p>
<p><del>At the moment you can install my version of qasync using the following command:</del></p>
<pre><code>pip install git+... | python|pyqt|python-asyncio|pyqt6 | 2 |
263 | 68,921,822 | Used IDs are not available anymore in Selenium Python | <p>I am using Python and Selenium to <strong>scrape</strong> some data out of an website. This website has the following structure:</p>
<p>First group item has the following base ID: <em><strong>frmGroupList_Label_GroupName</strong></em> and then you add <em><strong>_2</strong></em> or <em><strong>_3</strong></em> at ... | <p>As the saying goes... it ain't stupid, if it works.</p>
<pre><code>def refresh():
# accessing the groups page
url = "https://google.com"
browser.get(url)
time.sleep(5)
url = "https://my_url.com"
browser.get(url)
time.sleep(5)
</code></pre>
<p>While trying to debug this... | python|selenium|caching|memory|browser | 0 |
264 | 62,368,281 | Finding an unfilled circle in an image of finite size using Python | <p>Trying to find a circle in an <a href="https://1drv.ms/u/s!AtEnXvOorHZ4sp4moxmUXtErAc2lVw?e=7tfsYe" rel="nofollow noreferrer">image</a> that has finite radius. Started off using 'HoughCircles' method from OpenCV as the parameters for it seemed very much related to my situation. But it is failing to find it. Looks li... | <p>simple, draw your circles: <code>cv2.HoughCircles</code> returns a list of circles..</p>
<p>take care of <code>maxRadius = 100</code></p>
<pre><code>for i in circles[0,:]:
# draw the outer circle
cv2.circle(image,(i[0],i[1]),i[2],(255,255,0),2)
# draw the center of the circle
cv2.circle(image,(i[... | python|opencv | 2 |
265 | 56,418,087 | How to Plot Time Stamps HH:MM on Python Matplotlib "Clock" Polar Plot | <p>I am trying to plot mammalian feeding data on time points on a polar plot. In the example below, there is only one day, but each day will eventually be plotted on the same graph (via different axes). I currently have all of the aesthetics worked out, but my data is not graphing correctly. How do I get the hours to p... | <pre><code>import numpy as np
from matplotlib import pyplot as plt
import datetime
df = pd.DataFrame({'Day': {0: '5/22', 1: '5/22', 2: '5/22', 3: '5/22', 4: '5/22'},
'Time': {0: '16:15', 1: '19:50', 2: '20:15', 3: '21:00', 4: '23:30'},
'Feeding_Quality': {0: 'G', 1: 'G', 2: 'G', 3:... | python|matplotlib | 2 |
266 | 56,246,052 | How to fix 'else' outputting more than 1 outcome | <p>Very basic problem, trying to output if a number is divisible by 3/5/both/none but else will return 2 statements when they are not true. How do I fix this?</p>
<p>I've tried to move where the else is indented, first time it wouldn't output for the numbers that are not multiples of 3 or 5 and second time it would ou... | <p>If you incorporate all the comment suggestions so far you get something like this:</p>
<pre><code>while True:
z = input("Please enter a number- to end the program enter z as -1 ")
# cast to int
z = int(z)
# break early
if z == -1:
break
elif z % 3 == 0 and z % 5 == 0:
print("... | python | 2 |
267 | 63,572,310 | pytest will not run the test files in subdirectories | <p>I am new to pytest and trying to run a simple test to check if pytest works. I'm using windows 10, python 3.8.5 and pytest 6.0.1.</p>
<p>Here is my project directory:</p>
<pre><code>projects/
tests/
__init__.py
test_sample.py
</code></pre>
<p>Here is what I put in test_sample.py:</p>
<pre><code>def fun... | <p>The "best practices" approach to configuring a project with pytest is using <a href="https://docs.pytest.org/en/latest/customize.html#initialization-determining-rootdir-and-configfile" rel="nofollow noreferrer">a config file</a>. The simplest solution is a <code>pytest.ini</code> that looks like this:</p>
... | python|pytest | 1 |
268 | 36,341,820 | Updating R that is used within IPython/ Jupyter | <p>I wanted to use R within Jupyter Notebook so I installed via R Essentials (see: <a href="https://www.continuum.io/blog/developer/jupyter-and-conda-r" rel="nofollow">https://www.continuum.io/blog/developer/jupyter-and-conda-r</a>). The version that got installed is the following:</p>
<pre><code>R.Version()
Out[2]:
... | <p>If you want to stay with conda packages, try <code>conda update --all</code>, but I think there are still no R 3.2.x packages for windows.</p>
<p>You can also install R via the binary installer available at r-project.org, install the R kernel manually; e.g. via </p>
<pre><code>install_github("irkernel/repr")
insta... | r|ipython|jupyter | 5 |
269 | 19,361,740 | How to find orphan process's pid | <p>How can I find child process pid after the parent process died.
I have program that creates child process that continues running after it (the parent) terminates.</p>
<p>i.e.,</p>
<p>I run a program from python script <code>(PID = 2)</code>.</p>
<p>The script calls <code>program P (PID = 3, PPID = 2)</code></p>
... | <p>The information is lost when a process-in-the-middle terminates. So in your situation there is no way to find this out.</p>
<p>You can, of course, invent your own infrastructure to store this information at forking time. The middle process (PID 3 in your example) can of course save the information which child PID... | python|linux|process | 2 |
270 | 13,506,498 | "Threading" in Python, plotting received data and sending simultaneously | <p>I am asking for some high level advice here. I am using Python to plot data that is received constantly through serial. At the same time, I want the user to be able to input data through a prompt (such as the Python shell). That data will then be sent through the same serial port to talk to the device that is al... | <p>Disclaimer: I don't think that the following is good practice.</p>
<p>You can put the execution of the wx stuff inside a separate thread.</p>
<pre><code>app = wx.App()
window = DataLoggerWindow()
import threading
class WindowThread(threading.Thread):
def run(self):
window.Show()
app.MainLoop()
... | python|multithreading|wxpython|blocking|pyserial | 1 |
271 | 22,163,797 | building dictionary to be JSON encoded - python | <p>I have a list of class objects. Each object needs to be added to a dictionary so that it can be json encoded. I've already determined that I will need to use the json library and <code>dump</code> method. The objects look like this:</p>
<pre><code>class Metro:
def __init__(self, code, name, country, continent,... | <p>dict comprehension will not be very complicated.</p>
<pre><code>import json
list_of_metros = [Metro(...), Metro(...)]
fields = ('code', 'name', 'country', 'continent', 'timezone',
'coordinates', 'population', 'region',)
d = {
'metros': [
{f:getattr(metro, f) for f in fields}
for met... | python|json|dictionary | 3 |
272 | 43,684,048 | Tensorflow: building graph with batch sizes varying in dimension 1? | <p>I'm trying to build a CNN model in Tensorflow where all the inputs within a batch are equal shape, but between batches the inputs vary in dimension 1 (i.e. minibatch sizes are the same but minibatch shapes are not). </p>
<p>To make this clearer, I have data (Nx23x1) of various values N that I sort in ascending orde... | <p>There is no way to do this, as you want to use a differently shaped matrix (for fully-connected layer) for every distinct batch. </p>
<p>One possible solution is to use global average pooling (along all spatial dimensions) to get a tensor of shape <code>(batch_size, 1, 1, NUM_CHANNELS)</code> regardless of the seco... | tensorflow|conv-neural-network | 2 |
273 | 54,677,982 | How can I find out if a file-like object performs newline translation? | <p>I have a <a href="https://github.com/aptiko/textbisect" rel="nofollow noreferrer">library</a> that does some kind of binary search in a seekable open file that it receives as an argument.</p>
<p>The file must have been opened with <code>open(..., newline="\n")</code>, otherwise <code>.seek()</code> and <code>.tell(... | <p>I see two ways around this. One is Python 3.7's <a href="https://docs.python.org/3/library/io.html#io.TextIOWrapper.reconfigure" rel="nofollow noreferrer">io.TextIOWrapper.reconfigure()</a> (thanks @martineau!).</p>
<p>The second one is to make some tests to see whether <code>seek</code>/<code>tell</code> work as e... | python|python-3.x | 0 |
274 | 54,687,461 | Opencv - Ellipse Contour Not fitting correctly | <p>I want to draw contours around the concentric ellipses shown in the image appended below. I am not getting the expected result. </p>
<p><strong><em>I have tried the following steps:</em></strong></p>
<ol>
<li>Read the Image </li>
<li>Convert Image to Grayscale.</li>
<li>Apply GaussianBlur</li>
<li>Get the Canny ed... | <p>Algorithm can be simple:</p>
<ol>
<li><p>Convert RGB to HSV, split and working with a V channel.</p></li>
<li><p>Threshold for delete all color lines.</p></li>
<li><p>HoughLinesP for delete non color lines.</p></li>
<li><p>dilate + erosion for close holes in ellipses.</p></li>
<li><p>findContours + fitEllipse.</p><... | python-3.x|opencv|computer-vision | 4 |
275 | 71,166,697 | How can I delete stopwords from a column in a df? | <p>I've been trying to delete the stopwords from a column in a df, but I'm having trouble doing it.</p>
<pre><code>discografia["SSW"] = [word for word in discografia.CANCIONES if not word in stopwords.words('spanish')]
</code></pre>
<p>But in the new column I just get the same words as in the column "CAN... | <p>We can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>explode</code></a> in conjunction with grouping by the original index to assign back to the original DataFrame.</p>
<pre><code>stopwords = ["buzz"]
df = pd.DataFrame({"CANCIO... | python|dataframe | 0 |
276 | 9,324,802 | Running interactive python script from emacs | <p>I am a fairly proficient vim user, but friends of mine told me so much good stuff about emacs that I decided to give it a try -- especially after finding about the aptly-named evil mode...</p>
<p>Anyways, I am currently working on a python script that requires user input (a subclass of cmd.Cmd). In vim, if I wante... | <p>I don't know about <em>canonical</em>, but if I needed to interact with a script I'd do <kbd>M</kbd>-<kbd>x</kbd><code>shell</code><kbd>RET</kbd> and run the script from there.</p>
<p>There's also <kbd>M</kbd>-<kbd>x</kbd><code>terminal-emulator</code> for more serious terminal emulation, not just shell stuff.</p> | python|emacs | 4 |
277 | 39,372,778 | How can I print the entire converted sentence on a single line? | <p>I am trying to expand on Codeacademy's Pig Latin converter to practice basic programming concepts. </p>
<p>I believe I have the logic nearly right (I'm sure it's not as concise as it could be!) and now I am trying to output the converted Pig Latin sentence entered by the user on a single line.</p>
<p>If I print fr... | <p>Try:</p>
<pre><code>pyg = 'ay'
print ("Welcome to Matt's Pig Latin Converter!")
def convert(original):
while True:
if len(original) > 0 and (original.isalpha() or " " in original):
final_sentence = ""
print "You entered \"%s\"." % original
split_list = original.s... | python|join|printing | 0 |
278 | 52,854,560 | How to use if statments on Tags in Beautiful Soup? | <p>I'm a beginner using Beautiful Soup and I have a question to do with 'if' statements.</p>
<p>I am trying to scrap data from tables from a webpage but there are pro-ceding and post-ceding tables too.</p>
<p>All the required tables have divisions with the form , while the useless tables have various divisions.</p>
... | <p>This would get you what you are looking for I believe.</p>
<pre><code>for result in results:
if 'align="center"' in str(result.contents[0]):
#append to some list
</code></pre> | python|html|web-scraping|html-table|beautifulsoup | 1 |
279 | 52,848,894 | How to click HTML button in Python + Selenium | <p>I am trying to simulate button click in Python using Selenium. </p>
<pre><code><li class="next" role="button" aria-disabled="false"><a href="www.abc.com">Next →</a></li>
</code></pre>
<p>The Python script is
<code>driver.find_element_by_class_name('next').click()</code>.</p>
<p>This give... | <p>You can try the following code:</p>
<pre><code>from selenium.webdriver.support import ui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
ui.WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".next[role='button']"))).click()
</... | python|python-3.x|selenium | 1 |
280 | 47,974,874 | Algorithm for grouping points in given distance | <p>I'm currently searching for an <strong>efficient</strong> algorithm that takes in a set of points from three dimensional spaces and groups them into classes (maybe represented by a list). A point should belong to a class if it is close to one or more other points from the class. Two classes are then the same if they... | <h2>What I ended up doing</h2>
<p>After following all the suggestions of your comments, help from cs.stackexchange and doing some research I was able to write down two different methods for solving this problem. In case someone might be interested, I decided to share them here. Again, the problem is to write a program... | python|algorithm|performance | 2 |
281 | 34,401,791 | Please help. I get this error: "SyntaxError: Unexpected EOF while parsing" | <pre><code>try:
f1=int(input("enter first digit"))
f2=int(input("enter second digit"))
answ=(f1/f2)
print (answ)
except ZeroDivisionError:
</code></pre> | <p>You can't have an <code>except</code> line with nothing after it. You have to have <em>some</em> code there, even if it doesn't do anything.</p>
<pre><code>try:
f1=int(input("enter first digit"))
f2=int(input("enter second digit"))
answ=(f1/f2)
print (answ)
except ZeroDivisionError:
pass
</code></pre> | python | 1 |
282 | 34,034,812 | what is the role of magic method in python? | <p>Base on my understanding, magic methods such as <code>__str__</code> , <code>__next__</code>, <code>__setattr__</code> are built-in features in Python. They will automatically called when a instance object is created. It also plays a role of overridden. What else some important features of magic method do I omit or ... | <p>"magic" methods in python do specific things in specific contexts.</p>
<p>For example, to "override" the addition operator (+), you'd define a <code>__add__</code> method. subtraction is <code>__sub__</code>, etc.</p>
<p>Other methods are called during object creation (<code>__new__</code>, <code>__init__</code>)... | python | 4 |
283 | 7,187,493 | Persisting test data across apps | <p>My Django site has two apps — <code>Authors</code> and <code>Books</code>. My <code>Books</code> app has a model which has a foreign key to a model in <code>Authors</code>. I have some tests for the <code>Authors</code> app which tests all my models and managers and this works fine. However, my app <code>Books</code... | <p>Create a <a href="https://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-data-with-fixtures" rel="nofollow">fixture</a> containing the test data you need. You can then load the same data for both your <code>Authors</code> and <code>Books</code> tests.</p>
<p>For details, see <a href="https://do... | python|django|unit-testing|testing|integration-testing | 0 |
284 | 39,694,357 | loop through numpy arrays, plot all arrays to single figure (matplotlib) | <p>the functions below each plot a single numpy array<br />
plot1D, plot2D, and plot3D take arrays with 1, 2, and 3 columns, respectively</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def plot1D(data):
x=np.arange(len(data))
plot2D(np.hstack((np.... | <p>To plot multiple data sets on the same axes, you can do something like this:</p>
<pre><code>def plot2D_list(data,*args,**kwargs):
# type: (object) -> object
#if 2d, make a scatter
n = len(data)
fig,ax = plt.subplots() #create figure and axes
for i in range(n):
#now plot data set i
... | python|arrays|numpy|matplotlib | 1 |
285 | 16,529,524 | remove arguments passed to chrome by selenium / chromedriver | <p>I'm using selenium with python and chromium / chromedriver. I want to REMOVE switches passed to chrome (e.g. --full-memory-crash-report), but so far I could only find out how to add further switches.</p>
<p>My current setup:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Chrome(executable_path="/... | <p>It helped me:</p>
<pre><code>options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["test-type"])
options.add_argument("--incognito")
driver = webdriver.Chrome(options=options)
</code></pre>
<p>Found solution here <a href="https://help.applitools.com/hc/en-us/articles/360007189411-... | python|selenium|webdriver|selenium-webdriver|selenium-chromedriver | 4 |
286 | 40,690,674 | importing from a text file to a dictionary | <p>filename:<code>dictionary.txt</code></p>
<pre><code>YAHOO:YHOO
GOOGLE INC:GOOG
Harley-Davidson:HOG
Yamana Gold:AUY
Sotheby’s:BID
inBev:BUD
</code></pre>
<p>code:</p>
<pre><code>infile = open('dictionary.txt', 'r')
content= infile.readlines()
infile.close()
counters ={}
for line in content:
counters.appen... | <p>First off, instead of opening and closing the files explicitly you can use <code>with</code> statement for opening the files which, closes the file automatically at the end of the block.</p>
<p>Secondly, as the file objects are iterator-like objects (one shot iterable) you can loop over the lines and split them wit... | python|python-3.x|dictionary | 0 |
287 | 26,123,137 | Python Daemon: checking to have one daemon run at all times | <p>myalert.py</p>
<pre><code>from daemon import Daemon
import os, time, sys
class alertDaemon(Daemon):
def run(self):
while True:
time.sleep(1)
if __name__ == "__main__":
alert_pid = '/tmp/ex.pid'
# if pid doesnt exists run
if os.path.isfile(alert_pid): # is this check... | <p>The <a href="https://pypi.python.org/pypi/python-daemon/" rel="nofollow"><code>python-daemon</code></a> library, which is the reference implementation for <a href="http://legacy.python.org/dev/peps/pep-3143/" rel="nofollow">PEP 3143</a>: "Standard daemon process library", handles this by using a file lock (via the <... | python|daemon|python-daemon | 2 |
288 | 2,084,292 | Where (at which point in the code) does pyAMF client accept SSL certificate? | <p>I've set up a server listening on an SSL port. I am able to connect to it and with proper credentials I am able to access the services (echo service in the example below)</p>
<p>The code below works fine, but I don't understand <b>at which point the client accepts the certificate</b></p>
<p>Server:</p>
<pre><code... | <p>PyAMF uses <code>httplib</code> under the hood to power the remoting requests. When connecting via <code>https://</code>, <a href="http://docs.python.org/library/httplib.html#httplib.HTTPSConnection" rel="nofollow noreferrer">httplib.HTTPSConnection</a> is used as the <code>connection</code> attribute to the <code>R... | python|ssl|certificate|cherrypy|pyamf | 2 |
289 | 1,802,971 | NameError: name 'self' is not defined | <p>Why such structure</p>
<pre><code>class A:
def __init__(self, a):
self.a = a
def p(self, b=self.a):
print b
</code></pre>
<p>gives an error <code>NameError: name 'self' is not defined</code>?</p> | <p>Default argument values are evaluated at function define-time, but <code>self</code> is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.</p>
<p>It's a common pattern to default an argument to <code>None</code> and add a test for that in code:</p>
<pre><co... | python|nameerror | 199 |
290 | 63,087,983 | How to send post requests using multi threading in python? | <p>I'm trying to use multi threading to send post requests with tokens from a txt file.</p>
<p>I only managed to send GET requests,if i try to send post requests it results in a error.
I tried modifying the GET to POST but it gets an error.</p>
<p>I want to send post requests with tokens in them and verify for each tok... | <p>I finally managed to do post requests using multi threading.</p>
<p>If anyone sees an error or if you can do an improvement for my code feel free to do it :)</p>
<pre><code>import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from time import time
url_list = [
"https://www.google... | python|multithreading|post|python-requests | 1 |
291 | 32,232,462 | Scrolled Panel not working in wxPython | <pre><code> class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None,-1, "SCSM Observatory Log", size=(700, 700))
panel = wxScrolledPanel.ScrolledPanel(self,-1, size=(800,10000))
panel.SetupScrolling()
</code></pre>
<p>Could someone please explain why this code is not workin... | <p>Not sure why it is not working for you, following a sample which works for me. I like using sized_controls as they handle sizers nicely (in my view).</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
print(wx.VERSION_STRING)
import wx.lib.sized_controls as SC
class MyCtrl(SC.SizedPanel):
... | python|wxpython | 1 |
292 | 27,988,429 | Not able to add a column from a pandas data frame to mysql in python | <p>I have connected to mysql from python and I can add a whole data frame to sql by using df.to_sql command. When I am adding/updating a single column from pd.DataFrame, not able udate/add.</p>
<p>Here is the information about dataset, result,</p>
<pre><code>In [221]: result.shape
Out[221]: (226, 5)
In [223]: result... | <p>You cannot add a column to your table with data in it all in one step. You must use at least two separate statements to perform the DDL first (<code>ALTER TABLE</code>) and the DML second (<code>UPDATE</code> or <code>INSERT ... ON DUPLICATE KEY UPDATE</code>).</p>
<p>This means that to add a column with a <code>NO... | mysql|python-2.7|pandas | 2 |
293 | 32,845,601 | count how often each field point is inside a contour | <p>I'm working with 2D geographical data. I have a long list of contour paths. Now I want to determine for every point in my domain inside how many contours it resides (i.e. I want to compute the spatial frequency distribution of the features represented by the contours).</p>
<p>To illustrate what I want to do, here's... | <p>If your input polygons are actually contours, then you're better off working directly with your input grids than calculating contours and testing if a point is inside them.</p>
<p>Contours follow a constant value of gridded data. Each contour is a polygon enclosing areas of the input grid greater than that value.<... | python|numpy|scipy|shapely | 4 |
294 | 12,622,038 | Sending raw bytes over ZeroMQ in Python | <p>I'm porting some Python code that uses raw TCP sockets to ZeroMQ for better stability and a cleaner interface.</p>
<p>Right off the bat I can see that a single packet of raw bytes is not sent as I'm expecting.</p>
<p>In raw sockets:</p>
<pre><code>import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STR... | <p>Oh. Wow. I overlooked a major flaw in my test, the remote server I was testing on was expecting a raw TCP connection, not a ZMQ connection.</p>
<p>Of course ZMQ wasn't able to transfer the message, it didn't even negotiate the connection successfully. When I tested locally I was testing with a dummy ZMQ server, so ... | python|sockets|tcp|zeromq | 4 |
295 | 23,248,996 | How to filter for specific objects in a HDF5 file | <p>Learning the <a href="http://ilnumerics.net/hdf5-interface.html" rel="nofollow">ILNumerics HDF5 API</a>. I really like the option to setup a complex HDF5 file in one expression using C# object initializers. I created the following file: </p>
<pre><code>using (var f = new H5File("myFile.h5")) {
f.Add(new H5Grou... | <p><code>H5Group</code> provides the <code>Find<T></code> method which does just what you are looking for. It iterates over the whole subtree, taking arbitrary predicates into account: </p>
<pre><code>var matches = f.Find<H5Dataset>(
predicate: ds => ds.Attributes.Any(a => a.Name.Con... | c#|python|hdf5|ilnumerics|hdf | 1 |
296 | 23,245,915 | Total/Average/Changing Salary 1,2,3,4 Menu | <p>Change your program so there is a main menu for the manager to select from with four options: </p>
<ol>
<li>Print the total weekly salaries bill.</li>
<li>Print the average salary.</li>
<li>Change a player’s salary.</li>
<li>Quit</li>
</ol>
<p>When I run the program, I enter the number 1 and the program stops. How... | <p>Put the raw input in a while.</p>
<pre><code> while True:
user_input = raw_input("Welcome!...")
if user_input == 1:
...
elif user_unput == 2:
...
else:
print "this salary is ridic..."
</code></pre>
<p>After completing a 1,2,3... input ask the user if they would like to do something else y/n, if n: break,... | python|python-3.3 | 0 |
297 | 57,579,911 | How to get python's json module to cope with right quotation marks? | <p>I am trying to load a utf-8 encoded json file using python's json module. The file contains several <a href="https://www.utf8-chartable.de/unicode-utf8-table.pl?start=8192&number=128" rel="nofollow noreferrer">right quotation marks, encoded as <code>E2 80 9D</code></a>. When I call</p>
<pre><code>json.load(f, e... | <p>There is no <code>encoding</code> in the signature of <code>json.load</code>. The solution should be simply:</p>
<pre><code>with open(filename, encoding='utf-8') as f:
x = json.load(f)
</code></pre> | python|json | 1 |
298 | 70,792,656 | How do I get pending windows updates in python? | <p>I am trying to get pending windows updates on python but no module returns me the pending windows updates, only windows update history, I don't need especifiation about the update I just need to know if there are pending updates or not, I'm trying to use this code:</p>
<pre><code>from windows_tools.updates import ge... | <p>There was no solution in python, so I did a vbs script and called from inside my function.
the vbs script is</p>
<pre><code>Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()
Set searchResult = updateSearcher.Search("IsInstall... | python|python-3.x|windows | 0 |
299 | 70,928,435 | Python: get values from list of dictionaries | <p>I am using <a href="https://github.com/broadinstitute/python-sudoers" rel="nofollow noreferrer">python-sudoers</a> to parse a massive load of sudoers files, alas this library returns some weird data.</p>
<p>looks like a list of dictionaries, i dont really know.</p>
<pre><code>[{'run_as': ['ALL'], 'tags': ['NOPASSWD'... | <p>So because in each dict we have repeated variable names the only possible solution is to name them <code>extracted_run_as_0 = 'ALL'</code>, <code>extracted_run_as_1 = 'ALL'</code> etc.</p>
<pre class="lang-py prettyprint-override"><code>for i, dictionary in enumerate(lst):
for k, v in dictionary.items():
... | python-3.x | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.