content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to fix concurrency issue with multiprocessing?
Serial function working differently than similarly designed parallel function
def update(sharedDict,node,...):
for neighbor in weightNode:
sharedDict[neighbor] += *positive float(0->1)
sharedDict[node] += *positive float(0->1)
This is the slave function of ea... | How to fix concurrency issue with multiprocessing? | Serial function working differently than similarly designed parallel function
def update(sharedDict,node,...):
for neighbor in weightNode:
sharedDict[neighbor] += *positive float(0->1)
sharedDict[node] += *positive float(0->1)
This is the slave function of each process. Each addition is a positive float unaffected... | [
"It is not safe to update the same dict in parallel from multiple processes/threads. This cause a race condition. The threads needs to write in different places so to avoid this (they can read the same part safely though). Adding new key or removing existing ones to the same shared dict also cause a race condition ... | [
1
] | [] | [] | [
"concurrency",
"dictionary",
"parallel_processing",
"python",
"python_multiprocessing"
] | stackoverflow_0074636784_concurrency_dictionary_parallel_processing_python_python_multiprocessing.txt |
Q:
reporting R2 score in tensorflow "regression" model
I would like my model to report r2 square in the validation, however I cannot find the right metric to fill in ???,
model.compile(loss = 'mse',
optimizer = 'adam',
metrics = '???')
Thanks for any hint in advance
A:
my answer to the ... | reporting R2 score in tensorflow "regression" model | I would like my model to report r2 square in the validation, however I cannot find the right metric to fill in ???,
model.compile(loss = 'mse',
optimizer = 'adam',
metrics = '???')
Thanks for any hint in advance
| [
"my answer to the question comment is y calculation R2 scores is R square scores but tfa.metrics.RSquare needs to use the same sizes same order of y_true and y_predict R2 but you can do it for multi-classes when you need input to output as channels or discrete.\nSample: Custom multi classes, it required tf.float32 ... | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074638809_keras_python_tensorflow.txt |
Q:
GitLab CI Python black formatter says: would reformat, whereas running black does not reformat
When I run GitLab CI on this commit
with this gitlab-ci.yml:
stages:
- format
- test
black_formatting:
image: python:3.6
stage: format
before_script:
# Perform an update to make sure the system is u... | GitLab CI Python black formatter says: would reformat, whereas running black does not reformat | When I run GitLab CI on this commit
with this gitlab-ci.yml:
stages:
- format
- test
black_formatting:
image: python:3.6
stage: format
before_script:
# Perform an update to make sure the system is up to date.
- sudo apt-get update --fix-missing
# Download miniconda.
- wget -q https://r... | [
"The miniconda environment in the GitLab CI used python black version:\nblack, 22.3.0 (compiled: yes)\n\nWhereas the local environment used python black version:\nblack, version 19.10b0\n\nUpdating the local black version, pushing the formatted code according to the latest python black version, and running the GitL... | [
3,
1
] | [] | [] | [
"continuous_integration",
"formatting",
"gitlab",
"python",
"python_black"
] | stackoverflow_0071724842_continuous_integration_formatting_gitlab_python_python_black.txt |
Q:
Cant run flask on ngrok
from flask import Flask, escape, request
app = Flask(__name__)
run_with_ngrok()
@app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
When I run the this from terminal with "flask run" it doesn't print an ngrok link.
Im i an virtual e... | Cant run flask on ngrok | from flask import Flask, escape, request
app = Flask(__name__)
run_with_ngrok()
@app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
When I run the this from terminal with "flask run" it doesn't print an ngrok link.
Im i an virtual env and i have tried running i... | [
"if you are trying to expose your ip through ngrok, you can try tunneling with ngrok on terminal for the flask app's port\nyour app code should look like :\nfrom flask import Flask, escape, request\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello():\n name = request.args.get(\"name\", \"World\")\n return ... | [
1,
0,
0
] | [] | [] | [
"ngrok",
"python"
] | stackoverflow_0072240708_ngrok_python.txt |
Q:
Issues with too many interactive plotly figures
I am using Jupyter notebook on my laptop (the version coming with Anaconda) to perform some sensitivity analysis.
I use plotly to display the results and I like the interactive features that it has.
However, when I am trying to display more than 7/8 interactive plots... | Issues with too many interactive plotly figures | I am using Jupyter notebook on my laptop (the version coming with Anaconda) to perform some sensitivity analysis.
I use plotly to display the results and I like the interactive features that it has.
However, when I am trying to display more than 7/8 interactive plots on the same notebook, some plots disappears and the ... | [
"I believe that in the second link the config file should be generated if not existing.\nYou can also try changing to gl rendering:\nhttps://plotly.com/python/webgl-vs-svg/\n"
] | [
0
] | [] | [] | [
"jupyter",
"jupyter_notebook",
"memory",
"plotly",
"python"
] | stackoverflow_0074639389_jupyter_jupyter_notebook_memory_plotly_python.txt |
Q:
I need the approach to solve this problem in python
You get an integer which indicates the number of strings you get next. You have N strings where (N-1) strings follow the same pattern but one string doesnot follow the pattern. You have to find that odd string which doesnot follow the pattern and print it. Patter... | I need the approach to solve this problem in python | You get an integer which indicates the number of strings you get next. You have N strings where (N-1) strings follow the same pattern but one string doesnot follow the pattern. You have to find that odd string which doesnot follow the pattern and print it. Pattern varies in each case. Each string length may vary. Only ... | [
"You need a list to store tuples of the form (query, pattern).\nOnce you have this list you just need to find which pattern occurs only once. In that way you can easily detect the \"odd one out\"\nn = int(input())\n\nqp = []\n\nfor _ in range(n):\n query = input()\n pattern = [ord(x)-ord(y) for x, y in zip(qu... | [
0
] | [] | [] | [
"conditional_statements",
"dictionary",
"loops",
"python",
"string"
] | stackoverflow_0074639074_conditional_statements_dictionary_loops_python_string.txt |
Q:
Spark + Kafka app, getting "CassandraCatalogException: Attempting to write to C* Table but missing primary key columns: [col1,col2,col3]"
Run env
kafka ----ReadStream----> local ----WriteStream----> cassandra
source code place on local and kafka, local, writeStream is different IP \
table culumn is
col1 | col2 |... | Spark + Kafka app, getting "CassandraCatalogException: Attempting to write to C* Table but missing primary key columns: [col1,col2,col3]" | Run env
kafka ----ReadStream----> local ----WriteStream----> cassandra
source code place on local and kafka, local, writeStream is different IP \
table culumn is
col1 | col2 | col3 | col4 | col5 | col6 | col7
df.printSchema is
root
|-- key: binary (nullable = true)
|-- value: binary (nullable = true)
|-- topic: strin... | [
"Error says primary key columns: [col1,col2,col3] are missing. So df doesn't have these columns. You already have df.printSchema(). You can see it yourself that thats the case. df read from Kafka has a fixed schema and you can extract your data by parsing key and value columns. In my case data sent was in value col... | [
0
] | [] | [] | [
"apache_kafka",
"apache_spark",
"cassandra",
"python",
"spark_cassandra_connector"
] | stackoverflow_0074638402_apache_kafka_apache_spark_cassandra_python_spark_cassandra_connector.txt |
Q:
temporary logging format in a same file
i want all modules logs that import to the main.py save in main.log that i mention in logging.basicConfig() but with their formats
here is the code:
file main.py
import module1
import logging
logging.basicConfig(
filename="main.log",
format="%(asctime)s , <%(name)s... | temporary logging format in a same file | i want all modules logs that import to the main.py save in main.log that i mention in logging.basicConfig() but with their formats
here is the code:
file main.py
import module1
import logging
logging.basicConfig(
filename="main.log",
format="%(asctime)s , <%(name)s> , %(levelname)s : %(message)s",
datefm... | [
"Not the best solution but this should get the job done\nimport module1\nimport logging\n\nlogging.basicConfig(\n filename=\"main.log\",\n format=\"%(asctime)s , <%(name)s> , %(levelname)s : %(message)s\",\n datefmt=\"%Y-%m-%d %I:%M:%S\",\n level=logging.DEBUG\n)\n\n\ndef setBasicConfigFormat(format):\n... | [
0,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0072839320_logging_python.txt |
Q:
ImportError: No module named 'tensorflow.python'
here i wanna run this code for try neural network with python :
from __future__ import print_function
from keras.datasets import mnist from
keras.models import Sequential from
keras.layers import Activation, Dense
from keras.utils import np_utils
import tensorf... | ImportError: No module named 'tensorflow.python' | here i wanna run this code for try neural network with python :
from __future__ import print_function
from keras.datasets import mnist from
keras.models import Sequential from
keras.layers import Activation, Dense
from keras.utils import np_utils
import tensorflow as tf
batch_size = 128 nb_classes = 10 nb_epoch ... | [
"Uninstall tensorflow:\npip uninstall tensorflow\n\nThen reinstall it:\npip install tensorflow\n\n",
"for me upgrading pip helped,\npip install --upgrade pip\npip uninstall tensorflow\npip install tensorflow\n\n",
"I have the same problem in Windows 10. Until now I don't know why.\nBut if I create an virtual en... | [
42,
2,
1,
1,
1,
1,
0,
0,
0,
0
] | [
"pip install --upgrade pip \n\nThis worked for me\n",
"try to change the actual running python directory.\nand make sure that running python directory is not where you downloaded tensorflow. else go to any other directory and you're fine.\ni hope that solves your probleme.\n",
"try these steps\npip install --up... | [
-1,
-2,
-2
] | [
"keras",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0041415629_keras_neural_network_python_tensorflow.txt |
Q:
Add value to new column depending on values in another in pandas
I have a dataframe such as
Names Values
A 0.20
A 1.30
A 1.2
B 0.30
B 0.40
C 1.2
D 0.70
E 0.12
E 1.3
F 0.90
F 0.78
F 0.88
And I would like to add to a New_col the number :
1 where for each Names with ... | Add value to new column depending on values in another in pandas | I have a dataframe such as
Names Values
A 0.20
A 1.30
A 1.2
B 0.30
B 0.40
C 1.2
D 0.70
E 0.12
E 1.3
F 0.90
F 0.78
F 0.88
And I would like to add to a New_col the number :
1 where for each Names with at least one Values > 0.75 and one Values < 0.75
0 for each Names wi... | [
"First test by condition for compare threshold 0.75, get names if match at least one value, compare again membership of Names and last pass to numpy.select:\nm = df.Values > 0.75\n\ns1 = df.loc[m, 'Names'].unique()\ns2 = df.loc[~m, 'Names'].unique()\n\nm1 = df['Names'].isin(s1)\nm2 = df['Names'].isin(s2)\n\ndf['New... | [
2,
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074638806_pandas_python.txt |
Q:
replace last occurrence if equal the first
I have df like:
value
0 yes
1 nan
2 no
3 nan
4 yes
5 no
6 yes
7 nan
8 nan
9 nan
I do not have a guarantee that the first not nan value,yes, will be at the first row. It could as well start at later index.
I need to check if the first occurrence of string that is not Na... | replace last occurrence if equal the first | I have df like:
value
0 yes
1 nan
2 no
3 nan
4 yes
5 no
6 yes
7 nan
8 nan
9 nan
I do not have a guarantee that the first not nan value,yes, will be at the first row. It could as well start at later index.
I need to check if the first occurrence of string that is not Nan, equals the last string that is not nan, and i... | [
"Use Series.first_valid_index and\nSeries.last_valid_index for indices first and last non missing values, get values by DataFrame.loc, last use if-else statement for set values by scalars:\nfirst_idx = df['value'].first_valid_index()\nlast_idx = df['value'].last_valid_index()\nfirst = df.loc[first_idx, 'value']\nla... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074639669_pandas_python.txt |
Q:
Is there a way to send multiple image to tf serving model?
I'm trying this below code but I got unexpected error
This is my code for getting input and pass it to model.
def get_instances(dir = '/test_data'):
instances = list()
file_names = [file.split('/')[-1] for file in os.listdir(dir)]
... | Is there a way to send multiple image to tf serving model? | I'm trying this below code but I got unexpected error
This is my code for getting input and pass it to model.
def get_instances(dir = '/test_data'):
instances = list()
file_names = [file.split('/')[-1] for file in os.listdir(dir)]
for file in file_names :
image = nv.imread(os.path.joi... | [
"You can use tf.make_tensor_proto and tf.make_ndarray for image numpy array to/from tensor conversions. Then, you can use 'serving_default' signature to make predictions and pass multiple images to serving_default request to achieve faster results. 'serving_default' signature supports multiple images to be processe... | [
0
] | [] | [] | [
"json",
"python",
"tensorflow",
"tensorflow_serving"
] | stackoverflow_0072728351_json_python_tensorflow_tensorflow_serving.txt |
Q:
How to apply filtering over order by and distict in django orm?
Name email date
_________________________________________________
Dane dane_1@yahoo.com 2017-06-20
Dane dane_2@yahoo.com 2017-06-20
Dane dane_3@yahoo.com 2017-06-20
Dane... | How to apply filtering over order by and distict in django orm? | Name email date
_________________________________________________
Dane dane_1@yahoo.com 2017-06-20
Dane dane_2@yahoo.com 2017-06-20
Dane dane_3@yahoo.com 2017-06-20
Dane dane_4@yahoo.com 2017-06-20
Kim kim@gm... | [
"You can use F() expressions with __istartswith lookup to exclude those emails which starts with their name so:\nEmailModel.objects.exclude(email__istartswith=F('Name')).order_by(\"date\").distinct(\"Name\")\n\nOr you'd like to avoid the Name in entire email so you can use __icontains lookup so:\nEmailModel.objects... | [
0,
0
] | [
"Supposed your model name is User\nSo for order by with filter you can used\n\n\nUser.object.filter(parameters).order_by(parameters)\n\n\n\n"
] | [
-2
] | [
"django",
"django_models",
"django_orm",
"django_queryset",
"python"
] | stackoverflow_0074623133_django_django_models_django_orm_django_queryset_python.txt |
Q:
Use Python code to show a list of users that have Owner permissions to my Azure subscription
I am trying to find all the users in my subscription that have the role of Owner. I have to use python to do this and Microsoft doesn't seem to have any working options for this.
I've ran several options with the Azure SDK... | Use Python code to show a list of users that have Owner permissions to my Azure subscription | I am trying to find all the users in my subscription that have the role of Owner. I have to use python to do this and Microsoft doesn't seem to have any working options for this.
I've ran several options with the Azure SDK for Python class at azure.mgmt.authorization to try to return an appropriate result but nothing i... | [
"To list all the users in a subscription that have owner role:\nThis Azure PowerShell command get-azroleassignment provides all the owner roles. It worked as below:\nget-azroleassignment -RoleDefinitionId \"xxxxxxxx\" -Scope \"/subscriptions/<subscriptionID>\"\n\n\nTo display name & signin name(mail) use select ope... | [
0
] | [] | [] | [
"azure",
"python",
"sdk"
] | stackoverflow_0074482794_azure_python_sdk.txt |
Q:
Pytorch LSTM and cross entropy
I am working on sentiment analysis, I want to classify the output into 4 classes. For loss I am using cross-entropy.
The problem is PyTorch cross-entropy needs the input of (batch_size, output) which is am having trouble with.
I am taking a batch size of 12 and sequence size is 32
im... | Pytorch LSTM and cross entropy | I am working on sentiment analysis, I want to classify the output into 4 classes. For loss I am using cross-entropy.
The problem is PyTorch cross-entropy needs the input of (batch_size, output) which is am having trouble with.
I am taking a batch size of 12 and sequence size is 32
import torch.nn as nn
class RNN(nn.M... | [
"According to the CrossEntropyLoss docs:\n\ninput has to be a Tensor of size (C) for unbatched input, (minibatch,C) [for batched input] [...]\n\nThe code you provided is only the RNN class and not the data processing and the actual call to CrossEntropyLoss, but the error you stated in the comments makes me think th... | [
0
] | [] | [] | [
"cross_entropy",
"nlp",
"numpy",
"python",
"pytorch"
] | stackoverflow_0067529350_cross_entropy_nlp_numpy_python_pytorch.txt |
Q:
How to color second level columns based on condition
Below is the script I am currently working with. I'd like to color the C column only based on the condition below. So in column C, anything positive should be colored green, anything negative with red, and lastly when 0, it would be yellow. I've attached the exp... | How to color second level columns based on condition | Below is the script I am currently working with. I'd like to color the C column only based on the condition below. So in column C, anything positive should be colored green, anything negative with red, and lastly when 0, it would be yellow. I've attached the expected outcome. Any help would be greatly appreciated.
impo... | [
"Just added a few more lines, you can try something like below\n#your code\ndf = pd.DataFrame(data=[[100,200,400,500,222,222], [77,28,110,211,222,222], [11,22,33,11,22,33],[213,124,136,147,54,56]])\ndf.columns = pd.MultiIndex.from_product([['x', 'y', 'z'], list('ab')])\n\nfor c in df.columns.levels[0]:\n df[(c, ... | [
1
] | [] | [] | [
"dataframe",
"multi_index",
"pandas",
"python"
] | stackoverflow_0074621869_dataframe_multi_index_pandas_python.txt |
Q:
Pascal Triangle Tkinter Python
i'm new to python so i would be very grateful if you could help me.
i need to make a program that gives me pascal triangle lines by writing a number and clicking a button
i have a problem with pulling out a number from entry.get. here is my code:
from tkinter import *
from tkinter im... | Pascal Triangle Tkinter Python | i'm new to python so i would be very grateful if you could help me.
i need to make a program that gives me pascal triangle lines by writing a number and clicking a button
i have a problem with pulling out a number from entry.get. here is my code:
from tkinter import *
from tkinter import messagebox, ttk
root=Tk()
w = ... | [
"Edit: Redo: To get input working. I commented out line 34 and 34. I also removed show_message function. It is up to you.\nI added from math import factorial Then I changed formula for pascal triangle in PrintPasTriangle function.\nTry this:\nfrom tkinter import *\nfrom tkinter import messagebox, ttk\nfrom math imp... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074636867_python_tkinter.txt |
Q:
python google_auth_oauthlib Out Of Band (OOB) error
I am trying to run an internal app (this is a simple script) and authenticating using OAuth with python. But I run into the following error when I click on the link to authenticate my user after running my script :
The out-of-band (OOB) flow has been blocked in ... | python google_auth_oauthlib Out Of Band (OOB) error | I am trying to run an internal app (this is a simple script) and authenticating using OAuth with python. But I run into the following error when I click on the link to authenticate my user after running my script :
The out-of-band (OOB) flow has been blocked in order to keep users secure. Follow the Out-of-Band (OOB) ... | [
"First off make sure that you have updated the client library. Im not sure which version you are running but the library was fixed about a year ago.\nSecond remove the port.\n\"redirect_uris\":[\"http://localhost\"]\n\nThird\nIf that doesn't work here is my sample for videos.insert it should work out of the box.\n... | [
1
] | [] | [] | [
"google_api_python_client",
"google_oauth",
"python",
"youtube_api",
"youtube_data_api"
] | stackoverflow_0074635264_google_api_python_client_google_oauth_python_youtube_api_youtube_data_api.txt |
Q:
Passing python objects from main flask app to blueprints
I am trying to define a mongodb object inside main flask app. And I want to send that object to one of the blueprints that I created. I may have to create more database objects in main app and import them in different blueprints. I tried to do it this way.
f... | Passing python objects from main flask app to blueprints | I am trying to define a mongodb object inside main flask app. And I want to send that object to one of the blueprints that I created. I may have to create more database objects in main app and import them in different blueprints. I tried to do it this way.
from flask import Flask, render_template
import pymongo
from ad... | [
"The idea you are attempting is correct; however it just needs to be done a little differently.\nFirst, start by declaring your mongo object in your application factory:\nIn your app/__init__.py:\nimport pymongo\nfrom flask import Flask\n \nmongo = pymongo.MongoClient(\n host='mongodb+srv:... | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0073727018_flask_python.txt |
Q:
Mocking an I/O event in Python
My code is listening for file changes in a folder, in class A. When a change occurs, then I trigger a function of class B, which is a field in class A.
class A:
def __init__(self, b):
...
self.handler = b
def run(self):
# listen for changes in a folder using watchdog... | Mocking an I/O event in Python | My code is listening for file changes in a folder, in class A. When a change occurs, then I trigger a function of class B, which is a field in class A.
class A:
def __init__(self, b):
...
self.handler = b
def run(self):
# listen for changes in a folder using watchdog.observers.Observer
self.observe... | [
"Workaround for your test in a multiprocessing context\nI agree with you that multiprocessing causes the failure of the test. I have found a workaround that can help you to do the test in a strange way, but that you can adapt for your needs.\nThe workaround is based on the use of Sharing Global Variables in Multip... | [
0
] | [] | [] | [
"mocking",
"python",
"unit_testing"
] | stackoverflow_0074634906_mocking_python_unit_testing.txt |
Q:
How can i call a file program in another file in python?
How can i call a file program in another file in python?What i mean is i have a file called fun.py which has a small program that program prints Hello World, and i have a 2nd file called main.py so i want that if i run my main.py that fun.py file program run... | How can i call a file program in another file in python? | How can i call a file program in another file in python?What i mean is i have a file called fun.py which has a small program that program prints Hello World, and i have a 2nd file called main.py so i want that if i run my main.py that fun.py file program runs and that fun.py file also loop 2 times, So that fun.py file ... | [
"I'm going to answer with an example:\n\nfun.py\n\nprint(\"from fun\")\ndef show_im_having_fun():\n return \"I'm having fun!\"\n\n\nmain.py\n\n# You have the following options to make an import:\nfrom fun import *\nimport fun # the recommended for this case\nfrom fun import show_im_having_fun\nprint(\"from main\... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074639587_python_python_3.x.txt |
Q:
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Order->order, expression 'Status' failed to locate a name ('Status')
Cannot save record to my db.
I created endpoint which makes user and saves him to db:
@router.post("/user/register/", tags=['user'], status_code=201)
async def user_registe... | sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Order->order, expression 'Status' failed to locate a name ('Status') | Cannot save record to my db.
I created endpoint which makes user and saves him to db:
@router.post("/user/register/", tags=['user'], status_code=201)
async def user_register_web(user: RegisterWebSchema, db: Session = Depends(get_db)):
if user.password != user.password_repeat:
raise HTTPException(status_code... | [] | [] | [
"In order to make it work I had to import all of my modules into api file with endpoint. I don't know why but it works right now.\n"
] | [
-1
] | [
"backend",
"fastapi",
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0074636010_backend_fastapi_postgresql_python_sqlalchemy.txt |
Q:
Flask app wont launch 'ImportError: cannot import name 'cached_property' from 'werkzeug' '
I've been working on a Flask app for a few weeks. I finished it today and went to deploy it... and now it won't launch.
I haven't added or removed any code so assume something has changed in the deployment process?
Anyway, h... | Flask app wont launch 'ImportError: cannot import name 'cached_property' from 'werkzeug' ' | I've been working on a Flask app for a few weeks. I finished it today and went to deploy it... and now it won't launch.
I haven't added or removed any code so assume something has changed in the deployment process?
Anyway, here is the full error displayed in the terminal:
Traceback (most recent call last):
File "C:\U... | [
"The proper answer for May 2020: flask-restplus is dead, move to flask-restx.\nFrom noirbizarre/flask-restplus#778 (comment):\n\nflask-restplus work has been discontinued due to maintainers not having pypi keys. See the drop in replacement, flask-restx. It's an official fork by the maintainer team. We have already ... | [
36,
21,
14,
10,
1,
0,
0
] | [] | [] | [
"flask",
"flask_restplus",
"python"
] | stackoverflow_0060156202_flask_flask_restplus_python.txt |
Q:
How to match the string after the character and space in Python3?
I have the following string:
'- Submission GMV / return finance027110/06 Abdul Rahman -26,00- Submission GMV / return finance02432548/08 Michael Scott -56,47- GMV success. 452630/10/21 Lehazq998890/92 +60,00'
How can I return the values as:
[['- Sub... | How to match the string after the character and space in Python3? | I have the following string:
'- Submission GMV / return finance027110/06 Abdul Rahman -26,00- Submission GMV / return finance02432548/08 Michael Scott -56,47- GMV success. 452630/10/21 Lehazq998890/92 +60,00'
How can I return the values as:
[['- Submission PVT / return finance027110/06 Abdul Rahman','-26,00'],
['- Sub... | [
"Your requirement is easy to come by using re.findall with two capture groups:\ninp = \"- Submission GMV / return finance027110/06 Abdul Rahman -26,00- Submission GMV / return finance02432548/08 Michael Scott -56,47- GMV success. 452630/10/21 Lehazq998890/92 +60,00\"\nmatches = re.findall(r'(-.*?) ([+-]\\d+(?:,\\d+... | [
0,
0
] | [] | [] | [
"extract",
"python",
"string"
] | stackoverflow_0074639725_extract_python_string.txt |
Q:
How to connect to a MSSQL database on a remote (windows) server from python?
I have the following information about the remote server.
IP address
Database user name
Database password
Database name
I can even connect to the remote server using azure data studio, running on my Laptop, which is running on Ubuntu 20... | How to connect to a MSSQL database on a remote (windows) server from python? | I have the following information about the remote server.
IP address
Database user name
Database password
Database name
I can even connect to the remote server using azure data studio, running on my Laptop, which is running on Ubuntu 20.04.
However, this is my requirement
Connect to the MSSQL database programmatical... | [
"Usually you need to do something like:\nPorbably you are missing the \"Driver={SQL Server} or you need to change it to something else\ncnxn = pyodbc.connect(\"Driver={SQL Server};\" \n \"Server=\" your server + \";\"\n \"Database=\" your db+ \";\"\n... | [
1
] | [] | [] | [
"pyodbc",
"python",
"sql_server"
] | stackoverflow_0074639811_pyodbc_python_sql_server.txt |
Q:
Dataframe line length
I have a dataframe that contains x-y coordinates for a series of objects over time. I am trying to work out the total path length of each of these objects. I know the equation to work out the length of a line it
(√((x2-x1))^2+(y2-y1))) + (√((x3 - x2))^2+(y3-y2)))...
How would I work out the ... | Dataframe line length | I have a dataframe that contains x-y coordinates for a series of objects over time. I am trying to work out the total path length of each of these objects. I know the equation to work out the length of a line it
(√((x2-x1))^2+(y2-y1))) + (√((x3 - x2))^2+(y3-y2)))...
How would I work out the length of each individuals ... | [
"I am unsure what exactly you mean by 'length of each individual object path'. If you want to add the distance between each 2 successive points in the dataframe, with the last point connecting to the first, use something like this:\nimport math\n\ndata = {\"x\": [0,2,6,4,0,3,6]\n \"y\": [0,4,2,3,4,1,7]\n ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"trackpy"
] | stackoverflow_0074628856_dataframe_pandas_python_trackpy.txt |
Q:
Change subprocess.run architecture from x86 to arm
I am running python on a m1 Mac with Rosetta, on a x86_64 architecture.
During the execution I need to use subprocess.run to launch some external program. However that program need to run under arm64 architecture.
Is there a possible solution for doing that? Simpl... | Change subprocess.run architecture from x86 to arm | I am running python on a m1 Mac with Rosetta, on a x86_64 architecture.
During the execution I need to use subprocess.run to launch some external program. However that program need to run under arm64 architecture.
Is there a possible solution for doing that? Simply running from an arm64 terminal does not do the trick, ... | [
"The root of the problem was actually not in the subprocess.run, the process I was trying to spawn was compiled such that the binary is multi-arch support, supporting both arm64 and x86_64 (the support for the latter was mainly launching the program and crashing after not supported error).\nAs the call for subproce... | [
0
] | [] | [] | [
"apple_m1",
"macos",
"python",
"rosetta_2",
"subprocess"
] | stackoverflow_0074615048_apple_m1_macos_python_rosetta_2_subprocess.txt |
Q:
Tweets scraping using Python selinum
I am trying to scrape tweets under a hashtag using Python selinum and I use the following code to scroll down
driver.execute_script('window.scrollTo(0,document.body.scrollHeight);')
The problem is that selinum only scrapes shown tweets (only 3 tweets) and then scroll down to th... | Tweets scraping using Python selinum | I am trying to scrape tweets under a hashtag using Python selinum and I use the following code to scroll down
driver.execute_script('window.scrollTo(0,document.body.scrollHeight);')
The problem is that selinum only scrapes shown tweets (only 3 tweets) and then scroll down to the end of the page and load more tweets and... | [
"Scroll down the page by pixels, so the page will get the time to load the data, try the below code:\nlast_height = driver.execute_script(\"return document.body.scrollHeight\")\nwhile True:\n driver.execute_script(\"window.scrollBy(0, 800);\") # you can increase or decrease the scrolling height, i.e - '800'\n ... | [
0,
0
] | [] | [] | [
"python",
"selenium",
"twitter",
"web_scraping"
] | stackoverflow_0074635176_python_selenium_twitter_web_scraping.txt |
Q:
Calling different DataFrames in a For Loop
I am trying to use a for loop where a different DataFrame should be used in each iteration. It is thef'forecast_{s} below which is the problem.
What I want is that first, the DataFrame forecast_24 should be used, then forecast_168 etc. I can't understand why this is not w... | Calling different DataFrames in a For Loop | I am trying to use a for loop where a different DataFrame should be used in each iteration. It is thef'forecast_{s} below which is the problem.
What I want is that first, the DataFrame forecast_24 should be used, then forecast_168 etc. I can't understand why this is not working. Does it have to do with that a string ca... | [
"If I understand this correctly, you are trying to access the value forecast_24[column] at the first iteration of the loop and so on. Could you maybe do this instead:\nnaive_list = list([forecast_24, forecast_168, forecast_standard, forecast_custom])\n"
] | [
0
] | [] | [] | [
"for_loop",
"python",
"string"
] | stackoverflow_0074639643_for_loop_python_string.txt |
Q:
'' disappears after encoding xml to string python
In my xml file I have <?xml version="1.0" encoding="utf-8"?> at the beginning. But it disappears if I encode it to a string. By that I mean my string does not have it anymore at the beginning. I thought I can simply insert it in my string like in the code below (wh... | '' disappears after encoding xml to string python | In my xml file I have <?xml version="1.0" encoding="utf-8"?> at the beginning. But it disappears if I encode it to a string. By that I mean my string does not have it anymore at the beginning. I thought I can simply insert it in my string like in the code below (which worked when printing it), but when I wanted to save... | [
"To make it more visible:\nBefore I saved the file so:\ntree = ET.ElementTree(ET.fromstring(xml_str)) \ntree.write(open('test2.xml', 'a'), encoding='unicode')\n\nBut now, I save it like this so I don't miss the declaration at the beginning of the xml file:\ntree = ET.ElementTree(ET.fromstring(xml_str)) \ntree.write... | [
0
] | [] | [] | [
"lxml",
"python",
"utf_8",
"xml",
"xml_encoding"
] | stackoverflow_0074625433_lxml_python_utf_8_xml_xml_encoding.txt |
Q:
find a function of the form 1/x like to fit data python
I am trying to fit a function of the form f(x)=1/x or somthing like f(x)=1/poly(x) to this data:
data of points
I try to use scipy.optimize.curve_fit which do works but not return the regression itself, I want to know the function itself that succeeded in fit... | find a function of the form 1/x like to fit data python | I am trying to fit a function of the form f(x)=1/x or somthing like f(x)=1/poly(x) to this data:
data of points
I try to use scipy.optimize.curve_fit which do works but not return the regression itself, I want to know the function itself that succeeded in fitting the data. Also, I thought about an option of rotating an... | [
"If you have no model coming from physics try various mathemetical models up to find a satisfising one. For example with the exponential function :\n\nDon't be surprised if the values of the parameters that you get with your software are slightly different from the above values (a, b, c). The criteria of fitting im... | [
0
] | [] | [] | [
"curve_fitting",
"python",
"regression"
] | stackoverflow_0074616037_curve_fitting_python_regression.txt |
Q:
Query influxdb with special character
I am trying to perform. simple get on influxdb using python. The connection works great and I am able to query several values. However, I have one of them which is reported as homeassistant.autogen.°C. When I try to query it, I always get
influxdb.exceptions.InfluxDBClientErro... | Query influxdb with special character | I am trying to perform. simple get on influxdb using python. The connection works great and I am able to query several values. However, I have one of them which is reported as homeassistant.autogen.°C. When I try to query it, I always get
influxdb.exceptions.InfluxDBClientError: 400: {"error":"error parsing query: foun... | [
"Have you tried escaping with a backslash?\nclient = InfluxDBClient(host='192.168.1.x', port=8086, username='user', password='password')\nresults = client.query(r'SELECT \"value\" FROM homeassistant.autogen.\\°C WHERE entity_id = sensor.x_temperature')\n\nor containing the entire field name in double quotes, e.g.:\... | [
0,
0,
0
] | [] | [] | [
"influxdb",
"python"
] | stackoverflow_0074517426_influxdb_python.txt |
Q:
Sum every N col and row in python
I have a data list more than 100 row in csv file sth like this:
A
B
C
D
E
F
H
0
9
0
9
0
9
0
0
9
0
0
0
9
0
0
0
0
0
0
9
0
0
0
0
0
0
9
0
0
0
0
0
0
9
0
0
9
0
9
0
9
0
0
9
0
0
0
9
0
0
0
0
0
0
9
0
0
0
0
0
0
9
0
0
0
0
0
0
9
0
I need to sum each 5 cell of a column
And write the... | Sum every N col and row in python | I have a data list more than 100 row in csv file sth like this:
A
B
C
D
E
F
H
0
9
0
9
0
9
0
0
9
0
0
0
9
0
0
0
0
0
0
9
0
0
0
0
0
0
9
0
0
0
0
0
0
9
0
0
9
0
9
0
9
0
0
9
0
0
0
9
0
0
0
0
0
0
9
0
0
0
0
0
0
9
0
0
0
0
0
0
9
0
I need to sum each 5 cell of a column
And write the answer in a new row ... | [
"You could use .groupby to do that:\nN = 5\ndf_sum = df.groupby([n // N for n in range(df.shape[0])]).sum()\n\nThe list used to group over uses floor division to build blocks of 5 consecutive rows. If you're using the standard index you could do\ndf_sum = df.groupby(df.index // N).sum()\n\ninstead.\nResult for your... | [
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074638739_arrays_python.txt |
Q:
How to periodically spawn objects in Pygame
elif x1 == foodx2 and y1 == foody2:
foodx2 = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody2 = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 2
this is the code for food gen after it... | How to periodically spawn objects in Pygame | elif x1 == foodx2 and y1 == foody2:
foodx2 = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody2 = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 2
this is the code for food gen after it has been eaten once how do I delay its spawning ... | [
"you can use pygame timer function to set the spawn time for particular objects like food, enemies etc. It has a particular time frame to be triggered. In below example, food is triggered every 250ms.\n# Create a custom event for adding a new food\nADDFOOD = pygame.USEREVENT + 1\npygame.time.set_timer(ADDFOOD, 250)... | [
0
] | [] | [] | [
"pygame",
"pygame_clock",
"pygame_tick",
"python"
] | stackoverflow_0074639964_pygame_pygame_clock_pygame_tick_python.txt |
Q:
the method form.is_valid always returns always
I do my own project and I'm stuck on this problem. My form always returns False when calling form.is_valid.
This is my code:
forms.py:
I need to let user to choose the size he need from the list of available sizes, so I retrieve sizes from the database and then make a... | the method form.is_valid always returns always | I do my own project and I'm stuck on this problem. My form always returns False when calling form.is_valid.
This is my code:
forms.py:
I need to let user to choose the size he need from the list of available sizes, so I retrieve sizes from the database and then make a ChoiceField with variants of these sizes.
class Car... | [
"You need to pass the data, so:\nform = CartAddProductForm(\n instance=product,\n pk=product_id,\n data=request.POST,\n)\n"
] | [
0
] | [] | [] | [
"django",
"django_4.0",
"python",
"python_3.x"
] | stackoverflow_0074630614_django_django_4.0_python_python_3.x.txt |
Q:
Image cannot be displayed after saving the data in Django. The code for it is given below
Problem Statement:
In shown image, default profile pic is visible but i need uploaded photo to be displayed here when i upload and saved in the database.I am using django framework.
What have I Tried here?
In setting.html fi... | Image cannot be displayed after saving the data in Django. The code for it is given below | Problem Statement:
In shown image, default profile pic is visible but i need uploaded photo to be displayed here when i upload and saved in the database.I am using django framework.
What have I Tried here?
In setting.html file,The below is the HTML code for what is have tried to display image, bio, location. The probl... | [
"You're trying to fetch the image in the wrong way.\nInstead you can use this\nsrc=\"/media/{{user_profile.profileimg}}\"\n\nIf it doesn't work try removing \"/\" before media.\nPlease reply to this message if the issue still persist.\n",
"Oh, Holy Shit.\nHow could I miss it.\nMy friend problem is with view.\nAdd... | [
1,
1,
0,
0
] | [] | [] | [
"django",
"django_views",
"html",
"image",
"python"
] | stackoverflow_0074637830_django_django_views_html_image_python.txt |
Q:
How to load only the most recent file from a directory where the filenames startswith the date?
I have files in one directory/folder named:
2022-07-31_DATA_GVAX_ARPA_COMBINED.csv
2022-08-31_DATA_GVAX_ARPA_COMBINED.csv
2022-09-30_DATA_GVAX_ARPA_COMBINED.csv
The folder will be updated with each month's file in the... | How to load only the most recent file from a directory where the filenames startswith the date? | I have files in one directory/folder named:
2022-07-31_DATA_GVAX_ARPA_COMBINED.csv
2022-08-31_DATA_GVAX_ARPA_COMBINED.csv
2022-09-30_DATA_GVAX_ARPA_COMBINED.csv
The folder will be updated with each month's file in the same format as above eg.:
2022-10-31_DATA_GVAX_ARPA_COMBINED.csv
2022-11-30_DATA_GVAX_ARPA_COMBINED... | [
"Glob the directory with the pattern for known files of interest. Sort (natural) on the basename.\nfrom glob import glob as GLOB\nfrom os.path import join as JOIN, basename as BASENAME\n\ndef get_latest(directory):\n if all_files := list(GLOB(JOIN(directory, '*_DATA_GVAX_ARPA_COMBINED.csv'))):\n return so... | [
0,
0
] | [] | [] | [
"csv",
"dataframe",
"glob",
"pandas",
"python"
] | stackoverflow_0074639989_csv_dataframe_glob_pandas_python.txt |
Q:
What is the difference of int and 'int' in python?
I'm doing my homework in python and I happen to meet a very tricky problem: the difference between int and 'int' in python? Here is the code:
type(1) == 'int'
type(1) == int
and here is the result:
False
True
I firstly thought that maybe 'int' here is purely a s... | What is the difference of int and 'int' in python? | I'm doing my homework in python and I happen to meet a very tricky problem: the difference between int and 'int' in python? Here is the code:
type(1) == 'int'
type(1) == int
and here is the result:
False
True
I firstly thought that maybe 'int' here is purely a string, but later I used pd.DataFrame for another test:
t... | [
"anything in quotes is a string.\ntype() in python returns the type of an object. So type(1) is the type int (integer) and the type int is equal to int. But the type int is not equal to 'int' the string.\nOnto the example with pandas:\npandas dtype does not return a python class. It returns an object, which can be ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074639882_python.txt |
Q:
Almost correct output, but not quite right. Math help in Python
I am trying to match an expected output of "13031.157014219536" exactly, and I have attempted 3 times to get the value with different methods, detailed below, and come extremely close to the value, but not close enough. What is happening in these code... | Almost correct output, but not quite right. Math help in Python | I am trying to match an expected output of "13031.157014219536" exactly, and I have attempted 3 times to get the value with different methods, detailed below, and come extremely close to the value, but not close enough. What is happening in these code snippets that it causing the deviation? Is it rounding error in the ... | [
"On most machine, floats are represented by fp64, or double floats.\nYou can check the precision of those for your number that way (not a method to be used for real computation. Just out of curiosity):\nimport struct\nstruct.pack('d', 13031.157014219536)\n# bytes representing that number in fp64 b'\\xf5\\xbc\\n\\x1... | [
0
] | [] | [] | [
"math",
"python",
"rounding_error"
] | stackoverflow_0074636533_math_python_rounding_error.txt |
Q:
Cannot create secondary x-axis with xlsxwriter
I am trying to generate a chart with a secondary x-axis, but I can't get the secondary x-axis to be added to the chart.
Below is the code I'm using. If I change "x2_axis" to "y2_axis" and "set_x2_axis" to "set_y2_axis", then I am able to create a secondary y axis succ... | Cannot create secondary x-axis with xlsxwriter | I am trying to generate a chart with a secondary x-axis, but I can't get the secondary x-axis to be added to the chart.
Below is the code I'm using. If I change "x2_axis" to "y2_axis" and "set_x2_axis" to "set_y2_axis", then I am able to create a secondary y axis successfully -- but it does not work for a secondary x a... | [
"Setting a secondary X axis in Excel (or XlsxWriter) isn't obvious, in comparison to setting a secondary Y axis. Generally, you need to add a secondary Y and X axis pair before you can set a secondary X axis. Something like this:\nimport xlsxwriter\n\nworkbook = xlsxwriter.Workbook('test.xlsx')\nworksheet = workboo... | [
0
] | [] | [] | [
"pandas",
"python",
"xlsx",
"xlsxwriter"
] | stackoverflow_0074635534_pandas_python_xlsx_xlsxwriter.txt |
Q:
ImportError: Missing optional dependency 'openpyxl' still doesn't work after instllation
ubuntu 18.04, python3.8 and using pycharm.
Interpreter path in pychamr is correctly set.
while trying to read specific sheet in excel, using openpyxl it keeps on giving me ImportError.
ImportError: Missing optional dependency ... | ImportError: Missing optional dependency 'openpyxl' still doesn't work after instllation | ubuntu 18.04, python3.8 and using pycharm.
Interpreter path in pychamr is correctly set.
while trying to read specific sheet in excel, using openpyxl it keeps on giving me ImportError.
ImportError: Missing optional dependency 'openpyxl'. Use pip or conda to install openpyxl.
I've installed using pip3 install openpyxl ... | [
"for me worked typing the following inside an interactive session:\nimport pip\npip.main([\"install\", \"openpyxl\"])\n\n",
"I ran into something similar because pandas is using this behind the scenes.\nClean your local python environment or create a fresh virtual environment to use from your IDE. Then if possibl... | [
9,
3,
1,
0,
0,
0,
0
] | [] | [] | [
"openpyxl",
"python",
"ubuntu"
] | stackoverflow_0067513336_openpyxl_python_ubuntu.txt |
Q:
How to find name of file type in python
I'm attempting to create a clone of the windows 10 file explorer in python using tkinter and I cant work out how to get the name of the file type from its file extension like file explorer does
I have already got a function to get the programs file extension and another to o... | How to find name of file type in python | I'm attempting to create a clone of the windows 10 file explorer in python using tkinter and I cant work out how to get the name of the file type from its file extension like file explorer does
I have already got a function to get the programs file extension and another to open it in the default application however now... | [
"This value is stored in the registery at the location _HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes. For example, the value of the key Python.File at this location is Python File.\nThe first step is to get the key name linked with the human readable name of the file. That key is the value of the key name as the extension... | [
3,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0074639783_python_windows.txt |
Q:
Getting int value from a series in a dataframe cell
Suppose I have a df like this-
A B
1 {'meta': 3}
2 {'meta': 3}
3 {'tera': 3}
I want to retrieve the int value from column-B.
Desired Dataframe-
A B
1 3
2 3
3 3
Thanks in advance.
A:
Column B is a dict, so let's get the value corresponding to the key... | Getting int value from a series in a dataframe cell | Suppose I have a df like this-
A B
1 {'meta': 3}
2 {'meta': 3}
3 {'tera': 3}
I want to retrieve the int value from column-B.
Desired Dataframe-
A B
1 3
2 3
3 3
Thanks in advance.
| [
"Column B is a dict, so let's get the value corresponding to the key.\nAs we don't know the key name, take the first value.\nIt's already an integer. No conversion needed.\ndf[\"B\"] = df[\"B\"].map(lambda x: list(d.values())[0])\n\n"
] | [
2
] | [] | [] | [
"dataframe",
"group_by",
"numpy",
"pandas",
"python"
] | stackoverflow_0074640120_dataframe_group_by_numpy_pandas_python.txt |
Q:
Backup and restore a sqlalchemy db using sqlite as an engine
Hi!
I'm working on a flask-sqlalchemy application, and as you can imagine I'm changing database models and other thing through the process, every time that I made changes to the models I have to populate de DB again, and at the same time, as a safety mea... | Backup and restore a sqlalchemy db using sqlite as an engine | Hi!
I'm working on a flask-sqlalchemy application, and as you can imagine I'm changing database models and other thing through the process, every time that I made changes to the models I have to populate de DB again, and at the same time, as a safety measure I need to have some sort of backup restore process prepared i... | [] | [] | [
"I found a solution that works for me, if you have a better alternative don't hesitate to share it:\nfrom the terminal:\n\nback up your current db\n\nsqlite3 instance/pre_backup.db .dump > back.sql\n\n\ndelete your db\n\nrm instance/pre_backup.db\n\n\ninit your project in order to create the instances of your db\n\... | [
-1
] | [
"backup",
"python",
"restore",
"sqlalchemy",
"sqlite"
] | stackoverflow_0074639572_backup_python_restore_sqlalchemy_sqlite.txt |
Q:
How can I hide source code from Python file?
I am developing a paid application in Python. I do not want the users to see the source code or decompile it. How can I accomplish this task of hiding the source code from the user, but running the code perfectly with the same performance?
A:
You may distribute the co... | How can I hide source code from Python file? | I am developing a paid application in Python. I do not want the users to see the source code or decompile it. How can I accomplish this task of hiding the source code from the user, but running the code perfectly with the same performance?
| [
"You may distribute the compiled .pyc files which is a byte code that the Python interpreter compiles your .py files to.\nMore info on this found here on stackoverflow.\nHow to compile all your project files.\nThis will somewhat hide your actual code into bytecode, but it can be disassembled. To prevent from disass... | [
1,
0,
0
] | [] | [] | [
"pyscript",
"python",
"python_3.x"
] | stackoverflow_0074640301_pyscript_python_python_3.x.txt |
Q:
Storing scipy sparse matrix as HDF5
I want to compress and store a humongous Scipy matrix in HDF5 format. How do I do this? I've tried the below code:
a = csr_matrix((dat, (row, col)), shape=(947969, 36039))
f = h5py.File('foo.h5','w')
dset = f.create_dataset("init", data=a, dtype = int, compression='gzip')
I... | Storing scipy sparse matrix as HDF5 | I want to compress and store a humongous Scipy matrix in HDF5 format. How do I do this? I've tried the below code:
a = csr_matrix((dat, (row, col)), shape=(947969, 36039))
f = h5py.File('foo.h5','w')
dset = f.create_dataset("init", data=a, dtype = int, compression='gzip')
I get errors like these,
TypeError: Scalar... | [
"A csr matrix stores it's values in 3 arrays. It is not an array or array subclass, so h5py cannot save it directly. The best you can do is save the attributes, and recreate the matrix on loading:\nIn [248]: M = sparse.random(5,10,.1, 'csr')\nIn [249]: M\nOut[249]: \n<5x10 sparse matrix of type '<class 'numpy.flo... | [
15,
4,
0
] | [] | [] | [
"h5py",
"hdf5",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0043390038_h5py_hdf5_python_scipy_sparse_matrix.txt |
Q:
Do I need to clean/remove the images created on deployments of my Cloud Run instance?
I have a Cloud Run instance up and running on my Google Cloud Platform project.
Whenever I do any changes to my main.py file, I perform the following steps:
gcloud builds submit --tag ${CONTAINER}
gcloud run deploy ${SERVICE} --i... | Do I need to clean/remove the images created on deployments of my Cloud Run instance? | I have a Cloud Run instance up and running on my Google Cloud Platform project.
Whenever I do any changes to my main.py file, I perform the following steps:
gcloud builds submit --tag ${CONTAINER}
gcloud run deploy ${SERVICE} --image $CONTAINER --platform managed
which builds a new image and deploys the container to a... | [
"Container images are not automatically removed by Google. You have to delete them manually if you want.\nThere is no good practice, as it depends. If you are sure that you will not use old images anymore, you can delete them; otherwise, you may want to keep them to rollback easily to an older version. If you are u... | [
6,
0
] | [] | [] | [
"google_cloud_platform",
"google_cloud_run",
"python"
] | stackoverflow_0067636234_google_cloud_platform_google_cloud_run_python.txt |
Q:
Making Window Topmost with Python and/or Windows API
I'm trying to write a piece of code which finds a target window (returns its handler), brings it to top, and makes it topmost. The problem is that I cannot make the window topmost.
HWND_TOPMOST = -1
SWP_NOSIZE = 1
SWP_NOMOVE = 2
hwnd = ctypes.windll.user32.FindW... | Making Window Topmost with Python and/or Windows API | I'm trying to write a piece of code which finds a target window (returns its handler), brings it to top, and makes it topmost. The problem is that I cannot make the window topmost.
HWND_TOPMOST = -1
SWP_NOSIZE = 1
SWP_NOMOVE = 2
hwnd = ctypes.windll.user32.FindWindowW(None, title) # works OK
ctypes.windll.user32.BringW... | [
"I've found a solution. It looks like ctypes cannot convert a negative int (HWND_TOPMOST) to HWND type. Thus, HWND function from ctypes.windtypes module should be used.\nimport ctypes.wintypes\n\nctypes.windll.user32.SetWindowPos(hwnd, ctypes.wintypes.HWND(HWND_TOPMOST), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE)\n\n"
] | [
0
] | [] | [] | [
"python",
"winapi"
] | stackoverflow_0074589479_python_winapi.txt |
Q:
How can I use virtual environment in Visual Studio?
I activate the virtual environment in VSCode terminal:
and I check the pip list:
I can see the sklearn pip.
So I enter
import sklearn
in script but script can't find sklearn.
what is the problem?
Isn't the virtual environment activated just by typing in the te... | How can I use virtual environment in Visual Studio? | I activate the virtual environment in VSCode terminal:
and I check the pip list:
I can see the sklearn pip.
So I enter
import sklearn
in script but script can't find sklearn.
what is the problem?
Isn't the virtual environment activated just by typing in the terminal?
| [
"It's fine. Try to run this code and you won't get exceptions. To avoid this underscore pip install autopep8 might help\n"
] | [
0
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0074640274_python_virtualenv.txt |
Q:
Selecting a Iframe with Selenium
I am trying to build a program to login to my email account based on Selenium.
However I am running into the problem that a iframe Pop up will show with a button to continue and I am unable to select the button using Selenium.
The Website to login is: https://www.gmx.net/ which wil... | Selecting a Iframe with Selenium | I am trying to build a program to login to my email account based on Selenium.
However I am running into the problem that a iframe Pop up will show with a button to continue and I am unable to select the button using Selenium.
The Website to login is: https://www.gmx.net/ which will switch you to this site/popup
https:... | [
"The element Akzeptieren und weiter is within nested <frame> / <iframe> elements so you have to:\n\nInduce WebDriverWait for the parent frame to be available and switch to it.\n\nInduce WebDriverWait for the child frame to be available and switch to it.\n\nInduce WebDriverWait for the desired element to be clickabl... | [
1
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074640064_python_selenium.txt |
Q:
Understand how xreplace works
I'm trying to figure out how xreplace works. When I write
from sympy import *
my_list = [1234.5678, 22.333333]
my_list.xreplace({n : round(n, 4) for n in my_list.atoms(Number)})
I get an error: 'list' object has no attribute 'xreplace'. What did I write wrong?
A:
xrepla... | Understand how xreplace works | I'm trying to figure out how xreplace works. When I write
from sympy import *
my_list = [1234.5678, 22.333333]
my_list.xreplace({n : round(n, 4) for n in my_list.atoms(Number)})
I get an error: 'list' object has no attribute 'xreplace'. What did I write wrong?
| [
"xreplace is a method of SymPy's objects. Your my_list is just an ordinary Python list, so it doesn't expose that method. What you can do it this:\nfrom sympy import *\n# Tuple is the SymPy version of a python tuple\nmy_list = Tuple(1234.5678, 22.333333)\nmy_list.xreplace({n : round(n, 4) for n in my_list.atoms(Num... | [
4
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074639816_python_sympy.txt |
Q:
Helper tool to refactor large python file into smaller files
I have a 3000+ line python file (call it orig) containing 30ish utility functions. I'd like to split it into 5 files (say A.py, B.py, etc).
After the split, is there a helper tool to change all the orig.func1 and orig.func2 in the entire repo to A.func1,... | Helper tool to refactor large python file into smaller files | I have a 3000+ line python file (call it orig) containing 30ish utility functions. I'd like to split it into 5 files (say A.py, B.py, etc).
After the split, is there a helper tool to change all the orig.func1 and orig.func2 in the entire repo to A.func1, B.func2?
| [
"As @BrokenBenchmark suggested, I ended up writing my own helper in python\nlines = open('calc.py').readlines()\n\nout = []\nfor line in lines:\n if 'orig.' in line:\n m = re.search('orig.(.*?)\\(', line)\n f = m.group(1) \n if f in dir(A):\n line = line.replace('orig.', 'A.')\... | [
0,
0
] | [] | [] | [
"python",
"refactoring"
] | stackoverflow_0071230919_python_refactoring.txt |
Q:
File is showing in use even after using file.close()
I am trying to send an email with the file attachment and post that it should rename and move that file to Archive Folder.
No issues with email.
if (exception_count != 0):
filename= "abc.log"
with open(filename) as file:
try:
sender =... | File is showing in use even after using file.close() | I am trying to send an email with the file attachment and post that it should rename and move that file to Archive Folder.
No issues with email.
if (exception_count != 0):
filename= "abc.log"
with open(filename) as file:
try:
sender = 'from@email.com'
receivers='someone@email.com... | [
"The problem you are seeing is likely due to the fact that you are opening the file twice in your code.\nIf you have code that looks like this:\nfile = open(\"abc.log\", mode='r')\n\nthen you need some code to close the file\nfile.close()\n\n\n\nHowever, if you have code that looks like this:\nwith open(filename) a... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074630955_python.txt |
Q:
How to break a line of chained methods in Python?
I have a line of the following code (don't blame for naming conventions, they are not mine):
subkeyword = Session.query(
Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
subkeyword_company_id=self.e_company_id
).filter_by(
subkeyword_wo... | How to break a line of chained methods in Python? | I have a line of the following code (don't blame for naming conventions, they are not mine):
subkeyword = Session.query(
Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
subkeyword_company_id=self.e_company_id
).filter_by(
subkeyword_word=subkeyword_word
).filter_by(
subkeyword_active=T... | [
"You could use additional parentheses:\nsubkeyword = (\n Session.query(Subkeyword.subkeyword_id, Subkeyword.subkeyword_word)\n .filter_by(subkeyword_company_id=self.e_company_id)\n .filter_by(subkeyword_word=subkeyword_word)\n .filter_by(subkeyword_active=True)\n .one()\n )\n\n... | [
312,
70,
21,
12,
9,
4,
1,
1,
0
] | [] | [] | [
"coding_style",
"pep8",
"python"
] | stackoverflow_0004768941_coding_style_pep8_python.txt |
Q:
Python mariadb module does not connect to database on network
I am trying to connect to a mariadb-database on my local network. using Python.
import mariadb
cursor = mariadb.connect(host='192.168.178.77', user='someuser', password='somepass', db='temps')
Output is:
Traceback (most recent call last):
File "/Use... | Python mariadb module does not connect to database on network | I am trying to connect to a mariadb-database on my local network. using Python.
import mariadb
cursor = mariadb.connect(host='192.168.178.77', user='someuser', password='somepass', db='temps')
Output is:
Traceback (most recent call last):
File "/Users/localuser/PycharmProjects/SQL/main.py", line 20, in <module>
... | [
"This happens due to a bug in MariaDB Connector/C. (Issue CONC-612).\nThe issue was fixed in C/C Version 3.3.3 - which is available via brew:\nAfter\nbrew update\nbrew upgrade mariadb-connector-c\n\nconnection should work as expected.\n"
] | [
0
] | [
"I've got the same problem recently. Add port variable and check other. If doesn't help, try mysql-connector-python it works similar. Or install mariadb connector manually\n"
] | [
-2
] | [
"connection",
"mariadb",
"network_programming",
"pycharm",
"python"
] | stackoverflow_0074639957_connection_mariadb_network_programming_pycharm_python.txt |
Q:
pip is not using extra index url defined in pip.conf
I am using MacOS, and I created a pip.conf in ~/.pip. There is only one extral-index-url in this file, which looks like:
[global]
extra-index-url=https://[username]:[password]@artifactory
After that I tried to run pip config list, and I can see global.extra-ind... | pip is not using extra index url defined in pip.conf | I am using MacOS, and I created a pip.conf in ~/.pip. There is only one extral-index-url in this file, which looks like:
[global]
extra-index-url=https://[username]:[password]@artifactory
After that I tried to run pip config list, and I can see global.extra-index-url=https://[username]:[password]@artifactory in the te... | [
"@hoefling's comment on the question is the answer I needed. According to the docs, if a directory\n$HOME/Library/Application Support/pip/\n\nexists, that will shadow any\n$HOME/.config/pip/pip.conf\n\nfile. If that exists, it will shadow any\n$HOME/.pip/pip.conf\n\nfile. So investigate those locations in order,... | [
5,
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0061419865_pip_python.txt |
Q:
Battleship game crashes if I click outside of grid. How do I stop this?
I'm relatively new to pygame (and writing code in general), so I decided to make a battleship game for my project. The game is relatively simple, ships will be randomly placed and the player has a set amount of shots to find and sink all ships... | Battleship game crashes if I click outside of grid. How do I stop this? | I'm relatively new to pygame (and writing code in general), so I decided to make a battleship game for my project. The game is relatively simple, ships will be randomly placed and the player has a set amount of shots to find and sink all ships else they lose. However, I have made a grid which responds to player input b... | [
"you must check that COLUMN and ROW are within the range of the grid::\nwhile PLAYING == True:\n for event in pygame.event.get():\n # [...]\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n POS = pygame.mouse.get_pos()\n COLUMN = POS[0] // (GRIDWIDTH + MARGIN)\n ROW = ... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074640245_pygame_python.txt |
Q:
Numba.jit() built in function to make our performance faster in python
can anyone give one example to clarify it.Thanks!
I would like to know before I imply it.
A:
You can read this article.
Instead of doing operation with numpy array or pandas you can do the following
from numba import njit
@njit
def add_arrays... | Numba.jit() built in function to make our performance faster in python | can anyone give one example to clarify it.Thanks!
I would like to know before I imply it.
| [
"You can read this article.\nInstead of doing operation with numpy array or pandas you can do the following\nfrom numba import njit\n@njit\ndef add_arrays(x, y):\n return x + y\n\n\nInstead of\ndef add_arrays(x, y):\n return x + y\n\nOf course there are more applications and uses of njit and numba in general ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074640533_python.txt |
Q:
Azure Function (Consumption Linux Plan) is not working with System Identity to access the storage account for zip deployment
Since "managed identity for AzureWebJobsStorage" has been published for enabling the Function App to access the storage account I wanted to give it a shot and implement across our APIs. Howe... | Azure Function (Consumption Linux Plan) is not working with System Identity to access the storage account for zip deployment | Since "managed identity for AzureWebJobsStorage" has been published for enabling the Function App to access the storage account I wanted to give it a shot and implement across our APIs. However, this didn't work for Azure Function Linux Consumption Plan. The setup looks like that:
Function runtime: ~4
Python version: ... | [
"The below works on my side(Linux consumption plan):\ntrigger:\n- none\n\nvariables:\n # Azure Resource Manager connection created during pipeline creation\n azureSubscription: 'xxx'\n resourceGroupName: 'xxx'\n # Function app name\n functionAppName: 'xxx'\n # Agent VM image name\n vmImageName: 'ubuntu-lates... | [
0,
0
] | [] | [] | [
"azure",
"azure_functions",
"azure_functions_core_tools",
"azure_pipelines",
"python"
] | stackoverflow_0073898612_azure_azure_functions_azure_functions_core_tools_azure_pipelines_python.txt |
Q:
Drawing a selection area with mouse in Tkinter
I am developing an application which takes input from user in .csv form and plots the graph for the corresponding values using matplotlib.
def plotgraph():
x = []
y = []
data = text.get("1.0", END)
sepFile = data.split('\n')
for plotPair in sepFil... | Drawing a selection area with mouse in Tkinter | I am developing an application which takes input from user in .csv form and plots the graph for the corresponding values using matplotlib.
def plotgraph():
x = []
y = []
data = text.get("1.0", END)
sepFile = data.split('\n')
for plotPair in sepFile:
xAndY = plotPair.split(',')
if le... | [
"To use class you need at list something like this\nclass Annotate(object):\n def __init__(self):\n print \"Annotate is runing\"\n # rest of your code\n\nroot = Tk()\nmy_object = Annotate()\n\nroot.mainloop()\n\nAnd probably you will need more work with this.\n",
"I think now the simplest wat to ... | [
1,
0
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0024743407_matplotlib_python_tkinter.txt |
Q:
"python setup.py egg_info" failed with error code 1 for netCDF4
on my Home Office I use Ubuntu 12.04. Now I try to configure python with netcdf4. I installed a lot of packages like numpy, pandas, matplotlib, hdf5, cython, h5py,... When I try to install netcdf4 I got the error message:
Collecting netcdf
/usr/local... | "python setup.py egg_info" failed with error code 1 for netCDF4 | on my Home Office I use Ubuntu 12.04. Now I try to configure python with netcdf4. I installed a lot of packages like numpy, pandas, matplotlib, hdf5, cython, h5py,... When I try to install netcdf4 I got the error message:
Collecting netcdf
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages /urllib... | [
"I was trying to do the same and I finally found the full list :\npython3 -m pip install -U pip\npip3 install -upgrade setuptools\npip3 install netCDF4\n\nit should work now :) it worked for me (centos8, python3)\n"
] | [
0
] | [] | [] | [
"python",
"setup.py"
] | stackoverflow_0035924115_python_setup.py.txt |
Q:
Calculate average temperature/humidity between 2 dates pandas data frames
I have the following data frames:
df3
Harvest_date
Starting_date
2022-10-06
2022-08-06
2022-02-22
2021-12-22
df (I have all temp and humid starting from 2021-01-01 till the present)
date
temp
humid
2022-10-06 00:30:00
2
30
2022-10-06 ... | Calculate average temperature/humidity between 2 dates pandas data frames | I have the following data frames:
df3
Harvest_date
Starting_date
2022-10-06
2022-08-06
2022-02-22
2021-12-22
df (I have all temp and humid starting from 2021-01-01 till the present)
date
temp
humid
2022-10-06 00:30:00
2
30
2022-10-06 00:01:00
1
30
2022-10-06 00:01:30
0
30
2022-10-06 00:02:00... | [
"Use DataFrame.loc with match indices by means of another DataFrame:\n#changed data for match with df3\nprint (df)\n date temp humid\n0 2022-10-06 00:30:00 2 30\n1 2022-09-06 00:01:00 1 33\n2 2022-09-06 00:01:30 0 23\n3 2022-10-06 00:02:00 0 30\n4 2022-01-06 0... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074640609_pandas_python.txt |
Q:
Doit in Python not simplifying derivatives when re/im operator included
This is a continuation on my previous question Switch order of differential and real operator in expression in Python.
I would like to simplify the following derivatives in Python
where u and v are independent (Sympy) complex variables. The d... | Doit in Python not simplifying derivatives when re/im operator included | This is a continuation on my previous question Switch order of differential and real operator in expression in Python.
I would like to simplify the following derivatives in Python
where u and v are independent (Sympy) complex variables. The derivatives and the re operator are commutative here, and hence by switching t... | [
"You have two complex variables:\nIn [1]: u, v = symbols('u, v')\n\nIn [2]: diff(re(u*v), u, v)\nOut[2]: \n 2 \n ∂ \n─────(re(u⋅v))\n∂v ∂u \n\nHere you just get an unevaluated Derivative back. That is SymPy's way of saying that it can't compute an expression for this derivative.\nNow what shou... | [
2
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074639164_python_sympy.txt |
Q:
Instantiate empty type-hinted list
I have the following code:
from typing import List, NewType
MultiList = NewType("MultiList", List[List[int]])
def myfunc():
multi: MultiList = []
# More stuff here
The code works fine, it's just my IDE (PyCharm) doesn't like the instantiation of multi to an empty list, I g... | Instantiate empty type-hinted list | I have the following code:
from typing import List, NewType
MultiList = NewType("MultiList", List[List[int]])
def myfunc():
multi: MultiList = []
# More stuff here
The code works fine, it's just my IDE (PyCharm) doesn't like the instantiation of multi to an empty list, I get this error:
"Expected type 'MultiLis... | [
"The entire purpose of the typing.NewType is to distinguish a type from another and treat it as a subtype. You annotate it as MultiList, which is treated as a subtype of list, so assigning a list instance is wrong.\nYou need to instantiate MultiList properly. Example:\ndef myfunc():\n multi: MultiList = MultiLis... | [
2,
1
] | [] | [] | [
"python",
"python_typing",
"type_hinting"
] | stackoverflow_0074640651_python_python_typing_type_hinting.txt |
Q:
How to use strip to substring in dataframe?
I have a dataset with 100,000 rows and 300 columns
Here is the sample dataset:
EVENT_DTL
0 8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family
1 8. Background : Engineer / living with his mom marriage... | How to use strip to substring in dataframe? | I have a dataset with 100,000 rows and 300 columns
Here is the sample dataset:
EVENT_DTL
0 8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family
1 8. Background : Engineer / living with his mom marriage_married
How can I remove the white blank betwee... | [
"You can use pandas.Series.str to replace \"\\s+\" (1 or more whitespace) by a single whitespace.\nTry this :\ndf[\"EVENT_DTL\"]= df[\"EVENT_DTL\"].str.replace(\"\\s+\", \" \", regex=True)\n\nOutput :\nprint(df)\n EVEN... | [
4,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074640495_pandas_python.txt |
Q:
Getting unique values from csv file, output to new file
I am trying to get the unique values from a csv file. Here's an example of the file:
12,life,car,good,exellent
10,gift,truck,great,great
11,time,car,great,perfect
The desired output in the new file is this:
12,10,11
life,gift,time
car,truck
good.great
excell... | Getting unique values from csv file, output to new file | I am trying to get the unique values from a csv file. Here's an example of the file:
12,life,car,good,exellent
10,gift,truck,great,great
11,time,car,great,perfect
The desired output in the new file is this:
12,10,11
life,gift,time
car,truck
good.great
excellent,great,perfect
Here is my code:
def attribute_values(in_f... | [
"You could try to use zip to iterate over the columns of the input file, and then eliminate the duplicates:\nimport csv\n\ndef attribute_values(in_file, out_file):\n with open(in_file, \"r\") as fin, open(out_file, \"w\") as fout:\n for column in zip(*csv.reader(fin)):\n items, row = set(), []\... | [
1
] | [] | [] | [
"csv",
"python",
"unique"
] | stackoverflow_0074637028_csv_python_unique.txt |
Q:
How to bypass the validation popup on dell support page when submiting the search string using Python and SeleniumWebdriver
I'm trying to automate a task where I need to input service tags in the dell support page and extract the laptop information. But sometimes when I try to submit, the webpage shows a validatio... | How to bypass the validation popup on dell support page when submiting the search string using Python and SeleniumWebdriver | I'm trying to automate a task where I need to input service tags in the dell support page and extract the laptop information. But sometimes when I try to submit, the webpage shows a validation pop-up and it has a waiting time of 30 seconds
Does anyone have any suggestions on how to bypass this validation? Here is what... | [
"You are seeing the validation pop-up with a waiting time of 30 seconds\n\npossibly as the ChromeDriver initiated Chrome Browser browsing context is geting detected as a bot.\n\nSolution\nA potential solution would be to keep the ChromeDriver synchronized with the google-chrome browsing context inducing WebDriverWa... | [
0,
0
] | [] | [] | [
"google_chrome",
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0073393336_google_chrome_python_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
Can't connect to Azure SQL DB - pyodbc Operational Error
Attempting to connect to an Azure SQL database, most other configurations I've tried result in an instant error:
Client unable to establish connection (0) (SQLDriverConnect)')
But this one I'm currently trying times out and is the closest I've got:
cnxn = ... | Can't connect to Azure SQL DB - pyodbc Operational Error | Attempting to connect to an Azure SQL database, most other configurations I've tried result in an instant error:
Client unable to establish connection (0) (SQLDriverConnect)')
But this one I'm currently trying times out and is the closest I've got:
cnxn = pyodbc.connect(driver='{ODBC Driver 17 for SQL Server}', serve... | [
"There is no requirement for the connection string to include the default SQL Server port, which is 1433.\nAdd server name without tcp, use tcp: before quotes of servername, Server name format is servername.database.windows.net\nExample String\npyodbc.connect('DRIVER='+driver+';SERVER=tcp:'+server+';DATABASE='+data... | [
0,
0
] | [] | [] | [
"azure_sql_database",
"azure_sql_server",
"pyodbc",
"python",
"sql_server"
] | stackoverflow_0072961737_azure_sql_database_azure_sql_server_pyodbc_python_sql_server.txt |
Q:
Rolling count specific number
Suppose I have dataframe "df" like this
Time
Group
Data
2022-10-01 00:05:00
A
0
2022-10-01 00:10:00
A
0
2022-10-01 00:15:00
A
1
2022-10-01 00:20:00
A
1
2022-10-01 00:25:00
A
1
2022-10-01 00:30:00
A
0
2022-10-01 00:35:00
A
1
2022-10-01 00:40:00
A
0
2022-10-01 00:05:00
B
11
2... | Rolling count specific number | Suppose I have dataframe "df" like this
Time
Group
Data
2022-10-01 00:05:00
A
0
2022-10-01 00:10:00
A
0
2022-10-01 00:15:00
A
1
2022-10-01 00:20:00
A
1
2022-10-01 00:25:00
A
1
2022-10-01 00:30:00
A
0
2022-10-01 00:35:00
A
1
2022-10-01 00:40:00
A
0
2022-10-01 00:05:00
B
11
2022-10-01 00:10:00
B... | [
"You can use:\n(df.assign(Count_0_last_15_min=df['Data'].eq(0))\n .groupby('Group', as_index=False)\n .rolling(3, min_periods=1)['Count_0_last_15_min'].sum()\n .droplevel(0)\n)\n\nOutput:\n0 1.0\n1 2.0\n2 2.0\n3 1.0\n4 0.0\n5 1.0\n6 1.0\n7 2.0\n8 0.0\n9 1.0\n10 1.0\n... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074640705_pandas_python.txt |
Q:
Python - using TSV files to find averages
I am working on a lab project for school and am completely lost on how to do it. The following code is as far i have gotten after watching a few hours of python videos and googling for info on how to do this. The instructions are as follows:
Write a program that reads the... | Python - using TSV files to find averages | I am working on a lab project for school and am completely lost on how to do it. The following code is as far i have gotten after watching a few hours of python videos and googling for info on how to do this. The instructions are as follows:
Write a program that reads the student information from a tab seperated value... | [
"You define students as a dict and then try to use method \"append\", no can do.\nDict has no such method. Define it as a list\nstudents = []\n\nYou forgot the \"f\" for f-string\nwith open(f\"{user_file}\") as file:\n\nYou have to indent the line with \"append\" (so that it's executed IN the for loop)\nWhen calcul... | [
0
] | [] | [] | [
"csv",
"dictionary",
"key_value",
"python"
] | stackoverflow_0074634109_csv_dictionary_key_value_python.txt |
Q:
Trouble installing keras
I have a problem with keras; I've installed it once but somehow I cannot import it anymore since I recently installed some other packages. If I want to import keras, I get the following error (among many other warnings etc.):
ModuleNotFoundError: No module named 'tensorflow.tsl'
I tried t... | Trouble installing keras | I have a problem with keras; I've installed it once but somehow I cannot import it anymore since I recently installed some other packages. If I want to import keras, I get the following error (among many other warnings etc.):
ModuleNotFoundError: No module named 'tensorflow.tsl'
I tried to force reinstall both keras a... | [
"You need to upgrade Tensorflow or downgrade keras\npip install keras==2.8\n\nand do the same for the other two libraries\n"
] | [
0
] | [] | [] | [
"keras",
"pip",
"python"
] | stackoverflow_0074640526_keras_pip_python.txt |
Q:
Anaconda python: PackagesNotFoundError error when trying to roll back revision
For some reason I decided to upgrade setuptools. The so-called package plan that popped up when I ran conda install -c anaconda setuptools was as follows:
The following packages will be downloaded:
package | ... | Anaconda python: PackagesNotFoundError error when trying to roll back revision | For some reason I decided to upgrade setuptools. The so-called package plan that popped up when I ran conda install -c anaconda setuptools was as follows:
The following packages will be downloaded:
package | build
---------------------------|-----------------
certifi-2019.3.9 ... | [
"It appears you are maintaining your environment by\nissuing a series of conda install commands.\nYou could continue to do this,\nwith an additional version specification on the command line.\nBut I encourage you to switch to this approach:\nCreate an environment.yml file that looks like this.\nname: myproject\n\nc... | [
4,
3,
3,
0
] | [] | [] | [
"anaconda",
"python",
"python_3.x"
] | stackoverflow_0056190556_anaconda_python_python_3.x.txt |
Q:
How can I change the textScrollList depending upon the options I have selected in optionMenu in Maya?
`
This is the function that i wrote the operation, where om = optionMenu
def selection(*args):
selected = cmds.optionMenu(om,sl=True, q=True)
cmds.textScrollList(tsl, e=True, removeAll=True)
... | How can I change the textScrollList depending upon the options I have selected in optionMenu in Maya? | `
This is the function that i wrote the operation, where om = optionMenu
def selection(*args):
selected = cmds.optionMenu(om,sl=True, q=True)
cmds.textScrollList(tsl, e=True, removeAll=True)
for item in temp[selected]:
cmds.textScrollList(label=item, parent=om)
`
enter image... | [
"to get a qualified answer, you should provide a minimal executable script. And you did not write what exactly does not work. Please describe exactly what errors you get. What I can see is that you create a list of textScrollList ui elements instead of filling the existing text scroll list. A complete solution can ... | [
1
] | [] | [] | [
"maya",
"maya_api",
"pymel",
"python"
] | stackoverflow_0074640068_maya_maya_api_pymel_python.txt |
Q:
How to make two different list of strings same?
I have two random lists of strings. The length of two lists won't be necessarily equal all the time. There is no repetition of the elements within a list.
list1=['A', 'A-B', 'B', 'C']
list2=['A', 'A-B', 'B', 'D']
I want to compare the two lists, and the final output... | How to make two different list of strings same? | I have two random lists of strings. The length of two lists won't be necessarily equal all the time. There is no repetition of the elements within a list.
list1=['A', 'A-B', 'B', 'C']
list2=['A', 'A-B', 'B', 'D']
I want to compare the two lists, and the final output should be two lists with all common elements.
Expect... | [
"Use the set python module. Just using set1.intersection(set2) you can have the common elements between set1 and set2. Or using set1.union(set2) for the union set.\n"
] | [
1
] | [
"Youve requested 2 lists with all common elements:\nlist1=['A', 'A-B', 'B', 'C']\nlist2=['A', 'A-B', 'B', 'D']\n\nlist1_final=[]\nlist2_final=[]\n\nfor item in list1:\n if item in list2:\n list1_final.append(item)\n list2_final.append(item)\n\nreturns\nlist 1 = ['A', 'A-B', 'B']\nlist 2 = ['A', 'A-... | [
-2
] | [
"list",
"python",
"set",
"string"
] | stackoverflow_0074640726_list_python_set_string.txt |
Q:
'bytes' object has no attribute 'encode' in decryption AES CTR
so i have function for encryption and decryption using AES CTR. i was using python 3.x and the idea for this aes ctr from tweaksp
when i try to decrypt to get the plaintext, i got error message:
'bytes' object has no attribute 'encode'
after i check ... | 'bytes' object has no attribute 'encode' in decryption AES CTR | so i have function for encryption and decryption using AES CTR. i was using python 3.x and the idea for this aes ctr from tweaksp
when i try to decrypt to get the plaintext, i got error message:
'bytes' object has no attribute 'encode'
after i check another stackoverflow, i found if .encode('hex') not works on python... | [
"OK, I found the problem. I commented the offending code and replaced it with iv_int = int(binascii.hexlify(iv), 16) This is the updated code that works:\nfrom Crypto import Random\nfrom Crypto.Cipher import AES\nfrom Crypto.Util import Counter\n\nimport binascii\n\nkey_bytes = 16\ndef encrypt(key, plaintext):\n ... | [
0
] | [] | [] | [
"aes",
"encryption",
"python"
] | stackoverflow_0074639218_aes_encryption_python.txt |
Q:
PYTHON | Extracting specific text from variable [regex]
I have this text:
Intel Core i5-1235U 3.3GHz (10C 12T • 12MB Cache • up to 4.4GHz)
and i want to extract everything after the word "Core" till the next backspace
"i5-1235U"
the pattern of the text can be changed, like
Intel Core i7-1255U 3.3GHz (10C 12T • 12M... | PYTHON | Extracting specific text from variable [regex] | I have this text:
Intel Core i5-1235U 3.3GHz (10C 12T • 12MB Cache • up to 4.4GHz)
and i want to extract everything after the word "Core" till the next backspace
"i5-1235U"
the pattern of the text can be changed, like
Intel Core i7-1255U 3.3GHz (10C 12T • 12MB Cache • up to 4.4GHz)
where I want the
"i7-1255U"
or
Intel ... | [
"You can try code below:\ntext = 'Intel Core i7-920P 3.3GHz (10C 12T • 12MB Cache • up to 4.4GHz)'\n\ncpu_type = (text.split('Core')[1]).split()[0]\n\n"
] | [
0
] | [] | [] | [
"extract",
"python",
"string"
] | stackoverflow_0074640816_extract_python_string.txt |
Q:
Python HVPLOT In a future version of pandas a length 1 tuple will be returned when iterating over a groupby with a grouper equal to a list of length 1
I am working on a data visualization using Python's Pandas, hvplot, and Panel libraries.
I am able to shape the dataframe as I want, but when it comes to plotting t... | Python HVPLOT In a future version of pandas a length 1 tuple will be returned when iterating over a groupby with a grouper equal to a list of length 1 | I am working on a data visualization using Python's Pandas, hvplot, and Panel libraries.
I am able to shape the dataframe as I want, but when it comes to plotting this in hvplot. I start getting the following errors:
/home/****/_git/data-science-books/venv/lib/python3.8/site-packages/holoviews/core/data/pandas.py:231: ... | [
"\nI experienced the exact same warning in my own data analytics code using the same modules (all modules up to date).\nHowever my charts where never broken and always come out as expected (except see legend image below) when supplying a list of length 1 or more based on a param to hvplot using \"by\".\n\nThis code... | [
0
] | [] | [] | [
"hvplot",
"pandas",
"python"
] | stackoverflow_0074283744_hvplot_pandas_python.txt |
Q:
CNN is not getting good accuracy using unseen data
My cnn model is not performing well on my test set. I have trained the images on dark and white background, the image is cropped to eliminate other objects in the picture. My goal is to determine the position a person is facing on the bed.
ImageDataGenerator was u... | CNN is not getting good accuracy using unseen data | My cnn model is not performing well on my test set. I have trained the images on dark and white background, the image is cropped to eliminate other objects in the picture. My goal is to determine the position a person is facing on the bed.
ImageDataGenerator was used for splitting and augmenting the data.The dataset fo... | [
"You have overfitting problem, try to balance the images between the test and train data and have more layers in the model because it's and reduce dropout value.\none more thing is you could try pretrained model on the same split you have now to check out the data integrity.\n"
] | [
0
] | [] | [] | [
"conv_neural_network",
"python"
] | stackoverflow_0074640413_conv_neural_network_python.txt |
Q:
python requests invalid parameter
I'm trying to post a request to this API. Here is my code:
import requests
accesstoken = "74e41f9c-8ae6-4ebd-9568-f0c92e83bb54"
authnn = "4ef2db2b-70ea-11ed-9f86-063d0d6fdfb5"
def sender(number):
smstext = "hello test now#"
headers = {'User-Agent': 'Mozilla/5.0 (Windows ... | python requests invalid parameter | I'm trying to post a request to this API. Here is my code:
import requests
accesstoken = "74e41f9c-8ae6-4ebd-9568-f0c92e83bb54"
authnn = "4ef2db2b-70ea-11ed-9f86-063d0d6fdfb5"
def sender(number):
smstext = "hello test now#"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20... | [
"I suspect your problem lies with this block of code:\nif __name__ == \"__main__\":\n nums = input(\"NUMBERS LIST : \")\n op = open(nums, \"r\")\n for i in op:\n for i in i.split():\n sender(i)\n\nIn that you are probably not calling the sender function with the correct entry from your text fi... | [
0
] | [
"The code may have other issues, but remove the comma after 'to':number see below\n json_data = {\n 'content': smstext,\n 'contentType': 'TEXT',\n 'from': '+447860002234',\n 'to': number \n }\n\n"
] | [
-2
] | [
"json",
"python",
"python_requests"
] | stackoverflow_0074636276_json_python_python_requests.txt |
Q:
Serialize _wmi_object into JSON in Python3
I am having hard time with serializing _wmi_objects. I have tried with just json.dumps() and JsonPickle library without success getting Not JSON serializable errors or with JsonPickle some unneeded fields which can't be removed and null values for every entity.Tried hardc... | Serialize _wmi_object into JSON in Python3 | I am having hard time with serializing _wmi_objects. I have tried with just json.dumps() and JsonPickle library without success getting Not JSON serializable errors or with JsonPickle some unneeded fields which can't be removed and null values for every entity.Tried hardcoding every entity in a dict literal and after t... | [
"Since i just ran into this myself:\nproduct is a _wmi_object containing all kind of methods, classes and properties.\nThe actual data is in the property properties (which already is a dict())\nSo something like:\njson.dumps(product.properties)\n\nCheers\n"
] | [
0
] | [] | [] | [
"json",
"object",
"python",
"serialization",
"wmi"
] | stackoverflow_0058248984_json_object_python_serialization_wmi.txt |
Q:
Python Script to get text from excel file and write on an image
I have an excel file that contain data.I want to write that on an image that have same name as an excel file.Little bit of help will be highly appreciated.
from PIL import Image,ImageDraw,ImageFont
import glob
import os
images=glob.glob("E:\Images/*.... | Python Script to get text from excel file and write on an image | I have an excel file that contain data.I want to write that on an image that have same name as an excel file.Little bit of help will be highly appreciated.
from PIL import Image,ImageDraw,ImageFont
import glob
import os
images=glob.glob("E:\Images/*.jpg")
for img in images:
images=Image.open(img)
draw=ImageDr... | [
"Care to provide WHAT unique text exactly?\nRight now it's the same text, because your text is just a hardcoded string.\nYou can use f-string to customize it:\nname = \"Bob\"\ntext = f\"Hi {name}\"\n\nWill give you\ntext = \"Hi Bob\"\n"
] | [
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0074640947_python_python_imaging_library.txt |
Q:
mock flask-sqlalchemy query
I'm getting an error of Module not found when trying to create a test function to mock the get method of sqlalchemy query (with pytest)
example:
from mock import patch
@patch('flask_sqlalchemy._QueryProperty.__get__')
def test_get_all(queryMock):
assert True
When running pytes... | mock flask-sqlalchemy query | I'm getting an error of Module not found when trying to create a test function to mock the get method of sqlalchemy query (with pytest)
example:
from mock import patch
@patch('flask_sqlalchemy._QueryProperty.__get__')
def test_get_all(queryMock):
assert True
When running pytest i get an error:
ModuleNotFoundE... | [
"Use flask_sqlalchemy.model._QueryProperty.__get__ instead of flask_sqlalchemy._QueryProperty.__get__. This will resolve your issue as _QueryProperty class has been moved into model.\nfrom mock import patch \n@patch('flask_sqlalchemy.model._QueryProperty.__get__')\ndef test_get_all(queryMock):\n assert True\... | [
1
] | [] | [] | [
"mocking",
"pytest",
"python",
"sqlalchemy"
] | stackoverflow_0074546855_mocking_pytest_python_sqlalchemy.txt |
Q:
Why is this saying error? elif-else how to order this?
enter image description here
I'm making a registration code, and it keeps saying error. What should I change?
I tried substituting it with every combination possible. I even took the space out, and yes there's a if code above.
enter image description here
A:
... | Why is this saying error? elif-else how to order this? | enter image description here
I'm making a registration code, and it keeps saying error. What should I change?
I tried substituting it with every combination possible. I even took the space out, and yes there's a if code above.
enter image description here
| [
"The indents in the str(input.. lines are wrong. If you put indents at the beginning of these lines, the problem is solved.\n",
"I think the issue is that you haven't indented the inputs. When the code is running, it would assume the if loop has ended and then causes a syntax error due to the next elif statement.... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074640941_python_python_3.x.txt |
Q:
Using conditional statement in ipywidgets
I am still very new to coding and I am playing around with ipywidgets. How do I implement a conditional statement based on the answer of my first widget. For example, if the user selects Yes, it moves on. But if the user selects No, it goes into the second part of the widg... | Using conditional statement in ipywidgets | I am still very new to coding and I am playing around with ipywidgets. How do I implement a conditional statement based on the answer of my first widget. For example, if the user selects Yes, it moves on. But if the user selects No, it goes into the second part of the widget.
friends = widgets.ToggleButtons(
o... | [
"This solution works for ipywidgets 3.8 or higher. The second widget appears only when the value of the first widget == 'Yes.':\nimport ipywidgets as widgets\nfrom ipywidgets import Output\n\n# create widgets\nfriends = widgets.ToggleButtons(\n options= [\"Just me!\", \"Yes.\"])\n \nwho = widgets.BoundedI... | [
0
] | [] | [] | [
"conditional_statements",
"python",
"widget"
] | stackoverflow_0074637156_conditional_statements_python_widget.txt |
Q:
How to do function overloading in Python?
I want to implement function overloading in Python. I know by default Python does not support overloading. That is what I am asking this question.
I have the following code:
def parse():
results = doSomething()
return results
x = namedtuple('x',"a b c")
def pa... | How to do function overloading in Python? | I want to implement function overloading in Python. I know by default Python does not support overloading. That is what I am asking this question.
I have the following code:
def parse():
results = doSomething()
return results
x = namedtuple('x',"a b c")
def parse(query: str, data: list[x]):
results = d... | [
"There is the typing.overload decorator used for properly annotating a callable with two or more distinct call signatures. But it still requires exactly one actual implementation. The usage would be as follows:\nfrom typing import overload\n\n\n@overload\ndef parse(query: None = None, data: None = None) -> None:\n ... | [
2
] | [] | [] | [
"decorator",
"overloading",
"python",
"python_3.x",
"python_decorators"
] | stackoverflow_0074637458_decorator_overloading_python_python_3.x_python_decorators.txt |
Q:
How to change float('inf') representation?
I want to change float('inf') representation -> ∞, can u help me with it? I try to use this, but it didn't work
class Inf(float('inf')):
def __repr__(self) -> str:
return '∞'
inf=Inf()
those, when I use print() I want to see '∞' instead 'inf'
I want result l... | How to change float('inf') representation? | I want to change float('inf') representation -> ∞, can u help me with it? I try to use this, but it didn't work
class Inf(float('inf')):
def __repr__(self) -> str:
return '∞'
inf=Inf()
those, when I use print() I want to see '∞' instead 'inf'
I want result like in
from sympy import oo
but get it with oop... | [
"drop the ('inf') in class inheritance. You inherit from classes, not their instances. Then in __repr__ check if your float is infinity.\nclass FloatWithGlyphInf(float):\n def __repr__(self) -> str:\n if self == float('inf'):\n return '∞'\n else:\n return super().__repr__()\n\... | [
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0074641037_oop_python.txt |
Q:
idxs = cv2.dnn.NMSBoxes(boxes, confidence, MIN_CORP, NMS_THRESH) TypeError: Can't parse 'scores'. Input argument doesn't provide sequence protocol
help meee TT i received error in my coding of social distancing detection system using webcam. i done search the error but there is nothing difference with my code TT ... | idxs = cv2.dnn.NMSBoxes(boxes, confidence, MIN_CORP, NMS_THRESH) TypeError: Can't parse 'scores'. Input argument doesn't provide sequence protocol | help meee TT i received error in my coding of social distancing detection system using webcam. i done search the error but there is nothing difference with my code TT i wite my coding using notepad++ and run using command prompt. below is my error :
C:\Users\User\Downloads\Social_Distancing_Detection_Real_Time>python ... | [
"The answer to your problem (as usually) likes in response from the interpreter:\nTypeError: Can't parse 'scores'. Input argument doesn't provide sequence protocol\n\nscores is the second argument to cv2.dnn.NMSBoxes which in your case is confidence. confidence is a single number, you can't iterate over it. You've ... | [
0
] | [] | [] | [
"deep_learning",
"detection",
"opencv",
"python",
"yolo"
] | stackoverflow_0070235839_deep_learning_detection_opencv_python_yolo.txt |
Q:
Raise TimeoutException(message, screen, stacktrace)
I new to python and selenium in general and i was trying to do a project based on it.
code example:
options = Options()
options.headless = True
service_ = Service(executable_path = 'C:/Users/Downloads/chromedriver_win32/chromedriver.exe')
driver = webdriver.Chrom... | Raise TimeoutException(message, screen, stacktrace) | I new to python and selenium in general and i was trying to do a project based on it.
code example:
options = Options()
options.headless = True
service_ = Service(executable_path = 'C:/Users/Downloads/chromedriver_win32/chromedriver.exe')
driver = webdriver.Chrome(service = service_, options = options)
wait = WebDriver... | [
"In the webpage there are numerous item summaries.\nTo extract the texts from the item summaries you have to induce WebDriverWait for visibility_of_all_elements_located() and using List Comprehension you can use either of the following locator strategies:\n\nUsing CSS_SELECTOR:\ndriver.get(\"https://1stkissmanga.io... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074637137_python_selenium_selenium_webdriver.txt |
Q:
What is right order for defining decorators in django views
I want to set more than one decorator for my django function view. The problem is that I can't figure out how should be the order of decorators.
For example this is the view I have:
@permission_classes([IsAuthenticated])
@api_view(["POST"])
def logout(req... | What is right order for defining decorators in django views | I want to set more than one decorator for my django function view. The problem is that I can't figure out how should be the order of decorators.
For example this is the view I have:
@permission_classes([IsAuthenticated])
@api_view(["POST"])
def logout(request):
pass
In this case, first decorator never applies! nei... | [
"This is the correct way of ordering 'api_view' consider the view as API view that the decorator is defined by restframework.\nfrom rest_framework.decorators import api_view, permission_classes\n\n@api_view([\"POST\"])\n@permission_classes([IsAuthenticated])\ndef logout(request):\n pass\n\n"
] | [
1
] | [] | [] | [
"decorator",
"django",
"django_views",
"python",
"python_decorators"
] | stackoverflow_0074640885_decorator_django_django_views_python_python_decorators.txt |
Q:
Can't run Python programs from the terminal window, how do I fix this? (Windows 10, Python version 3.8.5)
I've been studying Python for a month now and normally I run all my programs in Sublime Text 3.
Today I learn to run Python programs in the terminal window as introduced in this section of the Automate the Bor... | Can't run Python programs from the terminal window, how do I fix this? (Windows 10, Python version 3.8.5) | I've been studying Python for a month now and normally I run all my programs in Sublime Text 3.
Today I learn to run Python programs in the terminal window as introduced in this section of the Automate the Boring Stuff with Python book following this video. Basically, I followed the instruction in the video and created... | [
"I solved the problem.\nWhen I looked into my user directory at C:\\Users\\<Username>, it appears that there is a py.exe file that has 0 bytes.\nI was told in this thread that the py.exe file shouldn't be in my user directory so I removed that file and it fixed the problem.\nI still don't know how the py.exe file g... | [
1,
0,
0
] | [] | [] | [
"python",
"terminal",
"windows"
] | stackoverflow_0063525600_python_terminal_windows.txt |
Q:
Sorting only specific subset of rows in pandas dataframe
I spent some time trying to figure out a solution to but haven't been able to figure a simple and clean solution to my problem. Basically I have the following dataframe:
Plane Parts
Quantity
is_plane
G6_32 FAB
1
True
G6_32 KIT
2
True
Item D
2
False
Item... | Sorting only specific subset of rows in pandas dataframe | I spent some time trying to figure out a solution to but haven't been able to figure a simple and clean solution to my problem. Basically I have the following dataframe:
Plane Parts
Quantity
is_plane
G6_32 FAB
1
True
G6_32 KIT
2
True
Item D
2
False
Item C
4
False
Item A
5
False
G6_32 SITE
5
True
G6_... | [
"make grouper for grouping\ngrouper = df['is_plane'].ne(df['is_plane'].shift(1)).cumsum()\n\ngrouper:\n0 1\n1 1\n2 2\n3 2\n4 2\n5 3\n6 3\n7 4\n8 4\n9 4\nName: is_plane, dtype: int32\n\nuse groupby by grouper\ngroup that its 'Plane Parts' is all False, sort_values by Plane Parts.\ndf.gr... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074640757_dataframe_pandas_python_python_3.x.txt |
Q:
python-socketio asyncio client: Is it possible to know when emit is completelly send data over the wire to server?
Do python-socketio or underlying python-engineio have any kind of confirmation that specific message was completely delivered to other side, similar to what TCP does to ensure all data was successfull... | python-socketio asyncio client: Is it possible to know when emit is completelly send data over the wire to server? | Do python-socketio or underlying python-engineio have any kind of confirmation that specific message was completely delivered to other side, similar to what TCP does to ensure all data was successfully transferred to other side?
I have kind of pubsub service built on python-socketio server, which sends back ok/error st... | [
"Socket.IO has ACK packets that can be used for the receiving side to acknowledge receipt of an event.\nWhen using the Python client and server, you can replace the emit() with call() to wait for the ack to be received. The return value of call() is whatever data the other side returned in the acknowledgement.\nBut... | [
1
] | [] | [] | [
"python",
"python_asyncio",
"python_socketio"
] | stackoverflow_0074639951_python_python_asyncio_python_socketio.txt |
Q:
Can't run python on windows anymore
Since the most recent update to Windows 10, I have been seeing this message every time I try to do anything with Python
I have reinstalled it, tried running it as administrator. Nothing works.
A:
First make sure that python.exe exists in the given directory and that its not ... | Can't run python on windows anymore | Since the most recent update to Windows 10, I have been seeing this message every time I try to do anything with Python
I have reinstalled it, tried running it as administrator. Nothing works.
| [
"First make sure that python.exe exists in the given directory and that its not a zero-length file. More likely though is that you installed the wrong version of python. Make sure you download and install the x86 version as it will work on both 64-bit and x86 systems. Do a full uninstall and install python via t... | [
8,
5,
1,
0
] | [] | [] | [
"python",
"python_2.7",
"updates",
"windows_10"
] | stackoverflow_0044394965_python_python_2.7_updates_windows_10.txt |
Q:
How to mock psycopg2 cursor object?
I have this code segment in Python2:
def super_cool_method():
con = psycopg2.connect(**connection_stuff)
cur = con.cursor(cursor_factory=DictCursor)
cur.execute("Super duper SQL query")
rows = cur.fetchall()
for row in rows:
# do some data manipulati... | How to mock psycopg2 cursor object? | I have this code segment in Python2:
def super_cool_method():
con = psycopg2.connect(**connection_stuff)
cur = con.cursor(cursor_factory=DictCursor)
cur.execute("Super duper SQL query")
rows = cur.fetchall()
for row in rows:
# do some data manipulation on row
return rows
that I'd like ... | [
"You have a series of chained calls, each returning a new object. If you mock just the psycopg2.connect() call, you can follow that chain of calls (each producing mock objects) via .return_value attributes, which reference the returned mock for such calls:\n@mock.patch(\"psycopg2.connect\")\ndef test_super_awesome_... | [
58,
16,
2,
0
] | [] | [] | [
"mocking",
"psycopg2",
"python",
"python_2.7",
"unit_testing"
] | stackoverflow_0035143055_mocking_psycopg2_python_python_2.7_unit_testing.txt |
Q:
Beautiful Soup find_All doesn't find all blocks
I'm trying to parse headhunter.kz website.
In use: python 3.9, beautifulsoup4.
When i parse pages with vacancies, i parse only 20 div-block with "serp-item" classes, hen in fact there are 40 div blocks. (I open the html file in the browser and see the presence of 40 ... | Beautiful Soup find_All doesn't find all blocks | I'm trying to parse headhunter.kz website.
In use: python 3.9, beautifulsoup4.
When i parse pages with vacancies, i parse only 20 div-block with "serp-item" classes, hen in fact there are 40 div blocks. (I open the html file in the browser and see the presence of 40 blocks).
import requests
import os
import time
import... | [
"I think you should you use selenium and try to scroll to end of page before you parse any data\n\n# Get scroll height\nlast_height = driver.execute_script(\"return document.body.scrollHeight\")\n\nwhile True:\n # Scroll down to bottom\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\... | [
0
] | [] | [] | [
"beautifulsoup",
"findall",
"javascript",
"parsing",
"python"
] | stackoverflow_0074640907_beautifulsoup_findall_javascript_parsing_python.txt |
Q:
Cannot create a virtual environment with a specific version of Python in ubuntu with virtualenv
I am trying to create a virtual enviroment in my ubuntu OS using virtualenv
The command I am using is
virtualenv -p /usr/bin/python3.8.13 py3.8.13_env
The error shown is
FileNotFoundError:[Errno 2]No such file or direc... | Cannot create a virtual environment with a specific version of Python in ubuntu with virtualenv | I am trying to create a virtual enviroment in my ubuntu OS using virtualenv
The command I am using is
virtualenv -p /usr/bin/python3.8.13 py3.8.13_env
The error shown is
FileNotFoundError:[Errno 2]No such file or directory:'/usr/bin/python3.8.13'
I have tried several other python versions but I get the same error
| [
"You can see what versions of Python you have by:\nls -l /usr/bin/python*\n\nIf you don't provide one then virtualenv will use a default of /usr/bin/python3. On Ubuntu this will be a symlink to a specific version. e.g.\n/usr/bin/python3 -> python3.10\n\nSo just calling virtualenv like:\nvirtualenv py3.10_venv\n\nWo... | [
1
] | [] | [] | [
"filenotfounderror",
"python",
"ubuntu",
"virtual_environment",
"virtualenv"
] | stackoverflow_0074641147_filenotfounderror_python_ubuntu_virtual_environment_virtualenv.txt |
Q:
dcc.store value not updating when i access the database in Python Dash
i have been trying to create a dashboard using Python Dash. The dashboard tries to access the database after every 5 seconds and tries to update the graph. After getting the values from the db for the first time, I try to update the store with ... | dcc.store value not updating when i access the database in Python Dash | i have been trying to create a dashboard using Python Dash. The dashboard tries to access the database after every 5 seconds and tries to update the graph. After getting the values from the db for the first time, I try to update the store with the values of the dataframe that are in the format.
| Date | Count... | [
"So I found the answer.\nThe reason why it wasn't working properly with the database call was, The database call was taking longer than my interval.\nSo Dash would update the n_interval count when the 5 seconds interval passes. Resulting in kicking another call, that would lead to another database call, while the p... | [
0
] | [] | [] | [
"dashboard",
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074640551_dashboard_plotly_plotly_dash_python.txt |
Q:
Unable to use Python's Paramiko library in AWS Lambda Function
I have uploaded Paramiko library as a layer in the Lambda function. However, still when I am attempting to import the same, it is giving me the following error:
Response { "errorMessage": "Unable to import module
'lambda_function': No module named '... | Unable to use Python's Paramiko library in AWS Lambda Function | I have uploaded Paramiko library as a layer in the Lambda function. However, still when I am attempting to import the same, it is giving me the following error:
Response { "errorMessage": "Unable to import module
'lambda_function': No module named 'paramiko'", "errorType":
"Runtime.ImportModuleError", "requestId... | [
"I finally resolved it myself.\nTurns out I was following all the steps correctly. But being new to AWS, and due to the unavailability of a Linux System, I was using the Windows system, and since Amazon works with Linux in the background, there was a discrepancy. I made use of the EC2 instance for Linux based libra... | [
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"aws_lambda_layers",
"paramiko",
"python"
] | stackoverflow_0074607660_amazon_web_services_aws_lambda_aws_lambda_layers_paramiko_python.txt |
Q:
Python Select Specific Row and Column from CSV file
I want to print specific row and column from a csv file.
csv file look like,
R,IMSI,DATE FIRST EVENT,TIME FIRST EVENT,DATE LAST EVENT,TIME LAST EVENT,DC(HHMMSS),NC,VOLUME,SDR
R
C,634012007277489,20221122,150025,20221122,150025,711,1,0,294
C,634012031576061,202211... | Python Select Specific Row and Column from CSV file | I want to print specific row and column from a csv file.
csv file look like,
R,IMSI,DATE FIRST EVENT,TIME FIRST EVENT,DATE LAST EVENT,TIME LAST EVENT,DC(HHMMSS),NC,VOLUME,SDR
R
C,634012007277489,20221122,150025,20221122,150025,711,1,0,294
C,634012031576061,20221122,150859,20221122,151738,905,3,0,1597
C,634012045006518,... | [
"Use pandas (you need to install it first by pip install pandas in the terminal).\nimport pandas as pd\n\ndf = pd.read_csv(fullpath.csv)\nx = df[column_name].iloc[row_number]\n\n",
"Try reading it with pandas.read_csv()\nimport pandas as pd\ndf = pd.read_csv('filename.csv', skipfooter=1, header=1)\ndf.iloc[row_nu... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074641237_python.txt |
Q:
How do I split a custom dataset into training and test datasets?
import pandas as pd
import numpy as np
import cv2
from torch.utils.data.dataset import Dataset
class CustomDatasetFromCSV(Dataset):
def __init__(self, csv_path, transform=None):
self.data = pd.read_csv(csv_path)
self.labels = pd.... | How do I split a custom dataset into training and test datasets? | import pandas as pd
import numpy as np
import cv2
from torch.utils.data.dataset import Dataset
class CustomDatasetFromCSV(Dataset):
def __init__(self, csv_path, transform=None):
self.data = pd.read_csv(csv_path)
self.labels = pd.get_dummies(self.data['emotion']).as_matrix()
self.height = 48... | [
"Starting in PyTorch 0.4.1 you can use random_split:\ntrain_size = int(0.8 * len(full_dataset))\ntest_size = len(full_dataset) - train_size\ntrain_dataset, test_dataset = torch.utils.data.random_split(full_dataset, [train_size, test_size])\n\n",
"Using Pytorch's SubsetRandomSampler:\nimport torch\nimport numpy as... | [
183,
143,
25,
19,
6,
0,
0,
0
] | [] | [] | [
"deep_learning",
"python",
"pytorch"
] | stackoverflow_0050544730_deep_learning_python_pytorch.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.