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: TypeError: object of type 'NoneType' has no len() when using KerasClassifier I want to build a logistic regression model using Keras and train with X epochs. I want to obtain the accuracy and loss scores from the model. My code raised TypeError: object of type 'NoneType' has no len(). However, X_train[cv_train] an...
TypeError: object of type 'NoneType' has no len() when using KerasClassifier
I want to build a logistic regression model using Keras and train with X epochs. I want to obtain the accuracy and loss scores from the model. My code raised TypeError: object of type 'NoneType' has no len(). However, X_train[cv_train] and y_train[cv_train] are not NoneType. Code: X_train, X_test, y_train, y_test = tra...
[ "Give a good look at your code and error before posting a question. Then if that does not help, thoroughly read the documentation.\nKeras fit() documentation -> What does .fit() return?\nYou have made a typo I believe. You expect the KerasClassifier object to have an attribute .history_. However this attribute is c...
[ 0 ]
[]
[]
[ "keras", "logistic_regression", "machine_learning", "python", "scikit_learn" ]
stackoverflow_0074476839_keras_logistic_regression_machine_learning_python_scikit_learn.txt
Q: I get bad request when I send a POST request to create a new user I'm trying to test registering new users, I send a POST request and I get "details": "USER WITH THIS EMAIL ALREADY EXITS!", even though when i check in the database the new user does get created.. I delete it and try again, still get the same outcom...
I get bad request when I send a POST request to create a new user
I'm trying to test registering new users, I send a POST request and I get "details": "USER WITH THIS EMAIL ALREADY EXITS!", even though when i check in the database the new user does get created.. I delete it and try again, still get the same outcome.. Having a hard time finding what's wrong with my code views.py: clas...
[ "If the user gets created, the problem is in the next lines. Remove the \"try\" and you'll probably see an exception in serializer = UserSerializerWithToken(user, many=False) or in return Response(serializer.data). You are currently catching all exceptions, and sending your message (\"USER WITH THIS EMAIL ALREADY E...
[ 0 ]
[]
[]
[ "django_rest_framework", "postman", "python", "serialization" ]
stackoverflow_0074476942_django_rest_framework_postman_python_serialization.txt
Q: How can I fit circles into a shape using python? So for a project, I gotta make a web-site that fills a shape with circles that wont intersact at any point.The user is going to upload a shape, and also choose the radius of the circles, and the code is going to place as many circles(with the chosen radius) as it ca...
How can I fit circles into a shape using python?
So for a project, I gotta make a web-site that fills a shape with circles that wont intersact at any point.The user is going to upload a shape, and also choose the radius of the circles, and the code is going to place as many circles(with the chosen radius) as it can into the shape. For example, if the user uploads an ...
[ "You could try the package circle-packing. It looks like you can get the behavior you want by setting the arguments rho_max and rho_min of the class ShapeFill to the radius provided by user. I've not used it so cannot attest to its' correctness or usability. Please let us know if it works for you.\nNote: The licens...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074475271_python.txt
Q: Search pattern to include square brackets I am trying to search for exact words in a file. I read the file by lines and loop through the lines to find the exact words. As the in keyword is not suitable for finding exact words, I am using a regex pattern. def findWord(w): return re.compile(r'\b({0})\b'.format(w...
Search pattern to include square brackets
I am trying to search for exact words in a file. I read the file by lines and loop through the lines to find the exact words. As the in keyword is not suitable for finding exact words, I am using a regex pattern. def findWord(w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search The problem wit...
[ "It's because of that regex engine assume the square brackets as character class which are regex characters for get ride of this problem you need to escape your regex characters. you can use re.escape function :\ndef findWord(w):\n return re.compile(r'\\b({0})\\b'.format(re.escape(w)), flags=re.IGNORECASE).searc...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "regex", "string_search" ]
stackoverflow_0031532290_python_regex_string_search.txt
Q: How to get a random value from a dictionary that is in a list So I have a list (shown below) and I need to randomly access one of the dictionaries in a list, and print it out: e.g. Instagram, 346, Social media platform, United States I've tried to google and search for it, but whatever I tried it didn't work. I kn...
How to get a random value from a dictionary that is in a list
So I have a list (shown below) and I need to randomly access one of the dictionaries in a list, and print it out: e.g. Instagram, 346, Social media platform, United States I've tried to google and search for it, but whatever I tried it didn't work. I know how to print out the whole list, but I don't know how to print a...
[ "You can use random.choice:\nimport random\n\nrandom.choice(data)\n\n", "import random\nprint(random.choice(data))\n\n#Output1\n{'name': 'Cristiano Ronaldo', 'follower_count': 215, 'description': 'Footballer', 'country': 'Portugal'}\n\nprint(random.choice(data))\n#Output2\n{'name': 'Ariana Grande', 'follower_coun...
[ 1, 1 ]
[]
[]
[ "dictionary", "list", "python", "random" ]
stackoverflow_0074477108_dictionary_list_python_random.txt
Q: How to fix 'NoneType' object is not subscriptable error Please tell me why when I start the program I get the error 'NoneType' object is not subscriptable def binary_search(array: list, element: int, start: int, end: int, counter: int) -> (int, int): counter += 1 mid = (start + end) // 2 if elemen...
How to fix 'NoneType' object is not subscriptable error
Please tell me why when I start the program I get the error 'NoneType' object is not subscriptable def binary_search(array: list, element: int, start: int, end: int, counter: int) -> (int, int): counter += 1 mid = (start + end) // 2 if element == array[mid]: return mid, counter if element <...
[ "Doing:\narray = array.sort()\n\nwill make array None and then you try to subscript array by doing array[i]. Instead you only need:\narray.sort()\n\nThis is because the .sort() function sorts the list in place and does not return a sorted list.\nAlso it would be good practice to call array.sort() before the for loo...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074477125_python.txt
Q: AttributeError: 'Client' object has no attribute 'author' (Discord Bot) The following is my code for an Amazon web scrapper. But I am getting the Client object has no attribute 'author' error. It specifically says File "/Users/kailash/Documents/devkai/Amazon Scrapper/bot.py", line 13, in on_message AttributeError:...
AttributeError: 'Client' object has no attribute 'author' (Discord Bot)
The following is my code for an Amazon web scrapper. But I am getting the Client object has no attribute 'author' error. It specifically says File "/Users/kailash/Documents/devkai/Amazon Scrapper/bot.py", line 13, in on_message AttributeError: 'Client' object has no attribute 'author' On line 13, there is just a blank ...
[ "I think your attribute error is being caused by your client definition. You define client as discord.Client however, this is usually done by defining client like this:\nfrom discord.ext import commands \n\nclient = commands.Bot(command_prefix='your prefix') # you can add other stuff here too but this is just the b...
[ 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python", "python_3.x" ]
stackoverflow_0074468089_bots_discord_discord.py_python_python_3.x.txt
Q: How can you create an os.environ object with a modified environment, e.g. after loading many different modules with "module load"? I have a python script that calls an application using subprocess. I am calling this application many times, currently I am doing something along the lines of out, err = subprocess.Pop...
How can you create an os.environ object with a modified environment, e.g. after loading many different modules with "module load"?
I have a python script that calls an application using subprocess. I am calling this application many times, currently I am doing something along the lines of out, err = subprocess.Popen(f"module load {' '.join(my_module_list)} && ./my_binary", stdout=sp.PIPE, stderr=sp.STDOUT, shell = True).communicate() to run my pr...
[ "I'd be tempted to call python in the subprocess and dump from os.environ in it\npython -c 'import os; print(os.environ)'\n\nOnce you know what you're after, you can pass a dict directly to subprocess's env arg to set custom environmental vars, which could be something like\ncustom_env = os.environ.copy()\ncustom_e...
[ 1 ]
[]
[]
[ "environment_variables", "module", "python" ]
stackoverflow_0074476744_environment_variables_module_python.txt
Q: ValueError : Call arguments received: • inputs=tf.Tensor(shape=(None, 1), dtype=float32) • training=None I get the described error with the Input layer and I can't seem to pinpoint the problem. I'm working on a text classification dataset and wanted to use the universal sentence encoder model for embeddings but it...
ValueError : Call arguments received: • inputs=tf.Tensor(shape=(None, 1), dtype=float32) • training=None
I get the described error with the Input layer and I can't seem to pinpoint the problem. I'm working on a text classification dataset and wanted to use the universal sentence encoder model for embeddings but it doesn't seem to work here. When I created my own embeddings using the embedding layer and the text vectorizat...
[ "I tried to build model for text classification and it worked for me. Providing the shape as blank and mentioning data type as string in the Input layer worked for me as we are dealing with text data.\nkeras.Input(shape=[], dtype = tf.string)\n\nExample Code Snippet:\nuse = hub.KerasLayer('https://tfhub.dev/google/...
[ 1 ]
[]
[]
[ "keras", "python", "tensorflow", "text_classification" ]
stackoverflow_0074006276_keras_python_tensorflow_text_classification.txt
Q: Add parameter description when converting a Dataclass to BaseModel I need to add a description to a FastAPI query parameter, which I pass to the endpoint through a dataclass, in order to display it OpenAPI (auto-documentation). How can I do it? I tried through metadata in fields but it has no effect (no descriptio...
Add parameter description when converting a Dataclass to BaseModel
I need to add a description to a FastAPI query parameter, which I pass to the endpoint through a dataclass, in order to display it OpenAPI (auto-documentation). How can I do it? I tried through metadata in fields but it has no effect (no description for x): To my understanding the dataclass object is used to create a ...
[ "Instead of the field from dataclass, use Query from pydantic:\nfrom dataclasses import dataclass\nfrom fastapi import FastAPI, Depends, Query\n\napp = FastAPI()\n\n\n@dataclass\nclass MyDataclass:\n x: str = Query(default=None, description='descr of x')\n\n\n" ]
[ 0 ]
[]
[]
[ "fastapi", "pydantic", "python", "python_3.x", "python_dataclasses" ]
stackoverflow_0074477129_fastapi_pydantic_python_python_3.x_python_dataclasses.txt
Q: Why my url appears as a post request when its get django I have some templates in a django project. I'm trying to save them in the the url with a post request even though I specify it in the html document. Here's my views.py ` from django.shortcuts import render from django.http import HttpResponse, HttpResponseRe...
Why my url appears as a post request when its get django
I have some templates in a django project. I'm trying to save them in the the url with a post request even though I specify it in the html document. Here's my views.py ` from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import WcaForm, IdForm from . import wcaScr...
[ "Your url does not appear as a POST, but as a GET. If your problem is the token, just remove the {%csrf_token%} from your template.\n" ]
[ 0 ]
[]
[]
[ "django", "get", "html", "python" ]
stackoverflow_0074451407_django_get_html_python.txt
Q: How to install dependencies of a custom python package I have built a Python package according to the documentation: https://packaging.python.org/en/latest/tutorials/packaging-projects/ Everything works, but when I call pip install my_package.whl, the dependencies are not installed. The dependencies are listed in ...
How to install dependencies of a custom python package
I have built a Python package according to the documentation: https://packaging.python.org/en/latest/tutorials/packaging-projects/ Everything works, but when I call pip install my_package.whl, the dependencies are not installed. The dependencies are listed in the pyproject.toml file as follows: requires = ["hatchling",...
[ "require is for build time dependencies.\nYou want to use dependencies for runtime ones.\ni.e.\ndependencies = [\"package1\", \"package2\"]\n\n", "I've managed to solve it in the meantime.\nQ1: These are packages required during the build, not for using the package.\nQ2: Use setuptool and the setup.py file instea...
[ 1, 0 ]
[]
[]
[ "packaging", "pip", "python" ]
stackoverflow_0074475746_packaging_pip_python.txt
Q: __init__() missing 1 required keyword-only argument: 'intents' discord I was trying to make a discord bot and I used this code: import discord from discord.ext import commands bot=commands.Bot(command_prefix='/') @bot.event async def on_ready(): print("Black_knight is up again")\` and this error pops up: line ...
__init__() missing 1 required keyword-only argument: 'intents' discord
I was trying to make a discord bot and I used this code: import discord from discord.ext import commands bot=commands.Bot(command_prefix='/') @bot.event async def on_ready(): print("Black_knight is up again")\` and this error pops up: line 6, in \<module\> bot=commands.Bot(command_prefix='/') TypeError: __init__() ...
[ "This code should work but IT IMPORTS ALL INTENTS\nintents = discord.Intents().all()\nclient = commands.Bot(command_prefix=',', intents=intents)\n\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "python", "python_3.8" ]
stackoverflow_0074477418_discord_discord.py_python_python_3.8.txt
Q: Sync Date and Time in Windows OS from python To avoid a time delay error with a (Binance) API I once in a while need to sync the Windows OS via the Data and Time settings. I want to avoid doing this manually every day and was wondering if I can do this programmatically from python. I wasn't successful in finding ...
Sync Date and Time in Windows OS from python
To avoid a time delay error with a (Binance) API I once in a while need to sync the Windows OS via the Data and Time settings. I want to avoid doing this manually every day and was wondering if I can do this programmatically from python. I wasn't successful in finding how to do this To run the exe file I am trying wi...
[]
[]
[ "os.path.realpath(\"C:\\Windows\\System32\\w32tm.exe\" )\n\nRun this code\n" ]
[ -2 ]
[ "operating_system", "python", "windows" ]
stackoverflow_0069869411_operating_system_python_windows.txt
Q: SQLAlchemy - Get most recent child from every parent Here's my situation. I have to tables Parent id other 1 ... 2 ... 3 ... 4 ... Children id parent_id time_created 1 1 2022-11-17 13:18:49 2 1 2022-11-17 13:47:05 3 2 2022-11-18 12:00:22 4 2 2022-11-18 16:06:17 What I would like to do, using SQLAlchemy...
SQLAlchemy - Get most recent child from every parent
Here's my situation. I have to tables Parent id other 1 ... 2 ... 3 ... 4 ... Children id parent_id time_created 1 1 2022-11-17 13:18:49 2 1 2022-11-17 13:47:05 3 2 2022-11-18 12:00:22 4 2 2022-11-18 16:06:17 What I would like to do, using SQLAlchemy in Python, is to retrieve the mos...
[ "As for constructing the query in SQL, the cleanest way to achieve this is to use Postgre's DISTINCT ON feature:\nSELECT DISTINCT ON (parent_id) *\nFROM Children\nORDER BY parent_id, time_created DESC;\n\nBased on this answer, this could be mapped to the following SQLAlchemy code:\nlatest_children = Children.query....
[ 0 ]
[]
[]
[ "flask_sqlalchemy", "postgresql", "python", "sql", "sqlalchemy" ]
stackoverflow_0074477152_flask_sqlalchemy_postgresql_python_sql_sqlalchemy.txt
Q: How to summarise dataframe by way of majority votes of a column This is a really tricky statistics that I want to produce. My dataframe contains information about true classes and prediction results of a machine learning model, for trips and corresponding trips' segments. The problem can best be explained with exa...
How to summarise dataframe by way of majority votes of a column
This is a really tricky statistics that I want to produce. My dataframe contains information about true classes and prediction results of a machine learning model, for trips and corresponding trips' segments. The problem can best be explained with example, so I give the following example df: df = pd.DataFrame( {'tr...
[ "You can do it this way. you can comment all but the first line and then uncomment one by one to see what is happening with the command line.\nres_seg = (\n df['class'].eq(df['prediction'])\n .groupby([df['class'],df['segment']]).mean()\n .ge(0.5)\n .groupby(level='class').agg(['size','sum'])\n ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074476074_dataframe_pandas_python.txt
Q: make a list with 2 value of 2 columns depending another column I would like to create a list based on the value of a column, the value here is "Auvergne-Rhône-Alpes". And in this list put the 2 values ​​latitude and longitude for this region. My data frame : I want to make a list like this : listeNom_Région = [[4...
make a list with 2 value of 2 columns depending another column
I would like to create a list based on the value of a column, the value here is "Auvergne-Rhône-Alpes". And in this list put the 2 values ​​latitude and longitude for this region. My data frame : I want to make a list like this : listeNom_Région = [[46.153426, 4.926114],[46.009188,5.428017]...[45.749499,5.594320]]
[ "liste_norm = list(zip(df['latitude'], df['longitude']))\n\nThis will create tuples instead of lists inside your list. However, tuples function very similar to list. If you really want lists, you can iterate over the result and change them like this:\nliste_norm = [list(elem) for elem in liste_norm]\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "list", "python" ]
stackoverflow_0074477309_dataframe_list_python.txt
Q: Converting two complex dictionary list to a dictionary suppose I have two dictionary list below: all=[] lis1={ 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'D...
Converting two complex dictionary list to a dictionary
suppose I have two dictionary list below: all=[] lis1={ 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 }...
[ "You need to refine what you are trying to accomplish. lis1 is a dict, not a list. lis1['commandes'] is a list containing a single dict, but presumably in the general case it might have more. Each of those has a key \"date\" and another key \"content\", which is again a list of dicts ....\nAn arbitrary example woul...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074476197_django_python.txt
Q: Trouble visualize GIS data with Geopandas.plot() I want to visualize the GIS data about Iran accidents in googlecolab, I have latitude, longitude, and death_count information but when I try to read it as Geopaandas data frame the plot function is not working correctly, May you please advise me on this issue, I hav...
Trouble visualize GIS data with Geopandas.plot()
I want to visualize the GIS data about Iran accidents in googlecolab, I have latitude, longitude, and death_count information but when I try to read it as Geopaandas data frame the plot function is not working correctly, May you please advise me on this issue, I have 3720 rows and 3 columns, and the result of visualiza...
[ "You have points_from_xy(df.latitude , df.longitude). points_from_xy expects (x, y) not (y, x). You need to switch the lat/lon order to lon, lat\n" ]
[ 0 ]
[]
[]
[ "geopandas", "python" ]
stackoverflow_0074477057_geopandas_python.txt
Q: open a password protected .pem and .crt file using python I created a private and pulic key key using command : ..... openssl genrsa -aes256 -passout pass:password -out key.pem 4096 && openssl rsa -in key.pem -passin pass:password -pubout -out pukey.pub and then created cert file using this command: openss...
open a password protected .pem and .crt file using python
I created a private and pulic key key using command : ..... openssl genrsa -aes256 -passout pass:password -out key.pem 4096 && openssl rsa -in key.pem -passin pass:password -pubout -out pukey.pub and then created cert file using this command: openssl req -new -key key.pem -passin pass:password -x509 -out keyc...
[ "use this line :\nwith open('key.pem', 'rb') as f:\n private_key=load_pem_private_key(f.read(), password=\"1\".encode(),\n backend=default_backend())\n pem =private_key.private_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PrivateForma...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074472138_python_python_3.x.txt
Q: What are the 4 values passed in shape for ndarray in numPy? What is the meaning of: shape=(1, 224, 224, 3) I mean what are all the values specifying given here for shape? A: Python NumPy numpy.shape() function finds the shape of an array. By shape, we mean that it helps in finding the dimensions of an array. It ...
What are the 4 values passed in shape for ndarray in numPy?
What is the meaning of: shape=(1, 224, 224, 3) I mean what are all the values specifying given here for shape?
[ "Python NumPy numpy.shape() function finds the shape of an array. By shape, we mean that it helps in finding the dimensions of an array. It returns the shape in the form of a tuple because we cannot alter a tuple just like we cannot alter the dimensions of an array.\nExample Codes: numpy.shape() to Pass a Simple Ar...
[ 0, 0, 0 ]
[]
[]
[ "numpy_ndarray", "python" ]
stackoverflow_0074477420_numpy_ndarray_python.txt
Q: Unflatten a pandas dataframe I have a pandas dataframe df_flat = pd.DataFrame({'dim1': ['a', 'a', 'b', 'b'], 'dim2': ['x', 'y', 'x', 'y'], 'val': [2, 4, 6, 8]}) I want to transform this dataframe, unflatten for want of a better words and transform it to a np ND array such that is looks like: df_unflatten = pd.Dat...
Unflatten a pandas dataframe
I have a pandas dataframe df_flat = pd.DataFrame({'dim1': ['a', 'a', 'b', 'b'], 'dim2': ['x', 'y', 'x', 'y'], 'val': [2, 4, 6, 8]}) I want to transform this dataframe, unflatten for want of a better words and transform it to a np ND array such that is looks like: df_unflatten = pd.DataFrame({'dim1': ['a', 'b'], 'x': [...
[ "I think the term you're looking for is \"unmelt\" since to \"melt\" a DataFrame is to bring it into the form you called df_flat. In order to achiece said unmelting, you can to as follows:\ndf = df_flat.set_index(['dim1', 'dim2'])['val'].unstack().reset_index()\n\n# Output:\ndim2 dim1 x y\n0 a 2 4\n1 ...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074477214_pandas_python.txt
Q: I made a Discord Bot, but It can't reply me on server I'm new on Python and Discord programming, and I made a bot there, but I can't see my Bot send me a message on my server, but only in private chats. I follow the freecodecamp tutorial to made it. How could I fix it there? ` import os import discord import reque...
I made a Discord Bot, but It can't reply me on server
I'm new on Python and Discord programming, and I made a bot there, but I can't see my Bot send me a message on my server, but only in private chats. I follow the freecodecamp tutorial to made it. How could I fix it there? ` import os import discord import requests import json import random from replit import db from ke...
[ "I followed the same tutorial when I started making bots, and honestly it is kind of a misleading tutorial. Having your commands in the on_message event can be pretty inconsistent in my experience. I would reccommend that instead, you create defined commands. This can be done like this:\nfrom discord.ext import com...
[ 0 ]
[]
[]
[ "discord", "python", "server" ]
stackoverflow_0074470705_discord_python_server.txt
Q: AttributeError: 'str' object has no attribute 'request' - googletrans I am trying to use this google translate python library googletrans 3.0.0, which I installed from pypi. I used this code to start with: from googletrans import Translator proxies = {'http': 'http://myproxy.com:8080', 'https': 'http://myproxy.co...
AttributeError: 'str' object has no attribute 'request' - googletrans
I am trying to use this google translate python library googletrans 3.0.0, which I installed from pypi. I used this code to start with: from googletrans import Translator proxies = {'http': 'http://myproxy.com:8080', 'https': 'http://myproxy.com:8080'} translator = Translator(proxies=proxies) translator.translate("col...
[ "This seems to be very confusing according to the official docs, but this github issue has a solution.\nFor some reason the docs specify both strings and HTTPTransports but this has been clarified in the issue above.\nBasically:\nfrom httpcore import SyncHTTPProxy\nfrom googletrans import Translator\n\nhttp_proxy =...
[ 2, 0 ]
[]
[]
[ "google_translate", "python" ]
stackoverflow_0071033206_google_translate_python.txt
Q: Create a CSV using pandas I have a method which is returning a list of data based on some conditions. example: source_image = cv2.imread("images/source_test.tif") target_image= cv2.imread("images/target_test.tif") total_matching_points =998 if total_matching_points > 500: generateTargetCSV(source_image, target...
Create a CSV using pandas
I have a method which is returning a list of data based on some conditions. example: source_image = cv2.imread("images/source_test.tif") target_image= cv2.imread("images/target_test.tif") total_matching_points =998 if total_matching_points > 500: generateTargetCSV(source_image, target_image, total_matching_points) ...
[ "Assuming you are passing lists into the method, to create a pandas df you should do\n df = pd.DataFrame({'source':source, 'target':target, 'total_matching_points': total_matching_points})\n\nYou can then save with\ndf.to_csv(location+filename, index=(Boolean))\n\n" ]
[ 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074475072_csv_dataframe_pandas_python.txt
Q: Can't store a pdf file in a MySql table I need to store a pdf file in MySql. Whether I use escape_string or not, I always get the same error b_blob = open(dir + fname_only, "rb") myblob = b_blob.read() ####<- b'%PDF-1.4\n%\xaa\xab\xac\xad\n4 0 obj\n<<\n/Producer (Apache FOP Version 0.94)\ try: conn = ...
Can't store a pdf file in a MySql table
I need to store a pdf file in MySql. Whether I use escape_string or not, I always get the same error b_blob = open(dir + fname_only, "rb") myblob = b_blob.read() ####<- b'%PDF-1.4\n%\xaa\xab\xac\xad\n4 0 obj\n<<\n/Producer (Apache FOP Version 0.94)\ try: conn = mysql.connector.connect( usual stuff ) ...
[ "So it looks like your problem is arriving from the quotes at the start of your string. I would consider putting double quotes around the newblob variable. Should look like this.\nquery = \"\"\"INSERT INTO `mytable` (`storing`) VALUES(\"%s\")\"\"\" %(newblob)\n\n" ]
[ 0 ]
[]
[]
[ "mysql", "mysql_connector_python", "python" ]
stackoverflow_0074476809_mysql_mysql_connector_python_python.txt
Q: How do I combine repeating columns, appending the values from merged columns I have an output of a dataframe below, into a dictionary. {0: ['RevitCategory', 'Door'], 1: ['DesignModelID', 'ModelA_Rev1'], 2: ['DesignObjectID', 'ModelA_Rev1_Object1'], 3: ['TypeName', 'ARC_DOR_INTERNAL'], 4: ['Function', 'Internal...
How do I combine repeating columns, appending the values from merged columns
I have an output of a dataframe below, into a dictionary. {0: ['RevitCategory', 'Door'], 1: ['DesignModelID', 'ModelA_Rev1'], 2: ['DesignObjectID', 'ModelA_Rev1_Object1'], 3: ['TypeName', 'ARC_DOR_INTERNAL'], 4: ['Function', 'Internal'], 5: ['Uniclass2015_Ss', 'Ss_25_30_20_25 : Doorset systems'], 6: ['IfcExportAs...
[ "Unless I misunderstood your problem and depending on if 'RevitCategory' marks the begining of the new row, it could work like this. I don't know if there is a solution more idiomatic to pandas.\ndf = pd.DataFrame()\nj = 0\nfor key in dict:\n if dict[key][0] == 'RevitCategory':\n row = {dict[key][0]: dict...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074477154_pandas_python.txt
Q: np_r function with two values I have found the following code: x=0.3*np.random.randn(100,2) x_train=np.r_[x+2,x-2] In the first case x is an array of 100 rows and two columns in a format list of list, for what I see. In this case when I use size it returns 200. However, in the x_train part it is using np.r_. For ...
np_r function with two values
I have found the following code: x=0.3*np.random.randn(100,2) x_train=np.r_[x+2,x-2] In the first case x is an array of 100 rows and two columns in a format list of list, for what I see. In this case when I use size it returns 200. However, in the x_train part it is using np.r_. For what I know this instruction serves...
[ "The linked scikit is showing how to find two separate classes in 2 dimensions. The code you are asking about generates random x&y coordinate data for those two separate classes\nThe purpose of np.random.randn is to generate 100 normally-distributed random x and y coordinate pairs (ie x is a 100x2 matrix). Side no...
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074477098_numpy_python.txt
Q: from urllib3.util.ssl_ import ( ImportError: cannot import name ssl My resources: Python 2.7, Ubunutu 18.04, Pycharm, virtual box oracle I have an automation solution built in python. The solution can be run from both cmd or pycharm of course. 2 options to run automation solution. python main.py args a,b,c...(run ...
from urllib3.util.ssl_ import ( ImportError: cannot import name ssl
My resources: Python 2.7, Ubunutu 18.04, Pycharm, virtual box oracle I have an automation solution built in python. The solution can be run from both cmd or pycharm of course. 2 options to run automation solution. python main.py args a,b,c...(run 1 suite of tests) python jenkinsRun.py arg a,b,c...(run main.py with diff...
[ "Could be some issue with installation. I did re-installed on MAC and it worked\nsudo pip install awscli --ignore-installed six\n\n", "Just to make sure: are you certain that you are invoking Python 2.x ?\nUbuntu 18.04 has Python 3.x as default, so make sure that you are not accidentally starting the script using...
[ 16, 3, 3, 0, 0, 0, 0, 0 ]
[ "I am not sure why it worked. But, I had this issue in AWS Glue, and I was able to get around this problem by using Glue 3.0 instead of Glue 2.0.\n", "Please update the latest urllib package:\nrun :\npip3 uninstall urllib3\npip3 install urllib3\n\n" ]
[ -1, -1 ]
[ "python", "python_2.7" ]
stackoverflow_0054217137_python_python_2.7.txt
Q: How to Convert list to string and keep the 'quotes' I have the following list : StringTest = ['A','B','C','D'] The output excepted is : "'A','B','C','D'" but it seems that the '' are perma deleted. Below is the code I tried : StringTest = ['A','B','C','D'] StringTest = ','.join(StringTest ) print(StringTest ) ...
How to Convert list to string and keep the 'quotes'
I have the following list : StringTest = ['A','B','C','D'] The output excepted is : "'A','B','C','D'" but it seems that the '' are perma deleted. Below is the code I tried : StringTest = ['A','B','C','D'] StringTest = ','.join(StringTest ) print(StringTest ) which returns : "A,B,C,D" How can I do ?
[ "You could do it like this:\nStringTest = ['A','B','C','D']\n\nprint('\"'+','.join(f\"'{s}'\" for s in StringTest)+'\"')\n\nOutput:\n\"'A','B','C','D'\"\n\n", "Have you tried repr?\nprint(','.join(map(repr, StringTest)))\n# 'A','B','C','D'\nprint(repr(','.join(map(repr, StringTest)))\n# \"'A','B','C','D'\"\n\n", ...
[ 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074477391_python.txt
Q: Need to plot a number of graphs in a grid from a for loop creation I have a straightforward for loop that loops through datasets in a set and plots the resultant scatterplot for each dataset using the code below; for i in dataframes: x = i['cycleNumber'] y = i['QCharge_mA_h'] plt.figure() sns.scat...
Need to plot a number of graphs in a grid from a for loop creation
I have a straightforward for loop that loops through datasets in a set and plots the resultant scatterplot for each dataset using the code below; for i in dataframes: x = i['cycleNumber'] y = i['QCharge_mA_h'] plt.figure() sns.scatterplot(x=x, y=y).set(title=i.name) This plots the graphs out as expec...
[ "Few ways you could do this.\nThe Original\nimport matplotlib # 3.6.0\nfrom matplotlib import pyplot as plt\nimport numpy as np # 1.23.3\nimport pandas as pd # 1.5.1\nimport seaborn as sns # 0.12.1\n\n\n# make fake data\ndf = pd.DataFrame({\n \"cycleNumber\": np.random.random(size=(100,)),\n \"QCharge_mA_...
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "python", "seaborn" ]
stackoverflow_0074477227_matplotlib_pandas_python_seaborn.txt
Q: Fail to import Alpha_vantage.timesseries EDIT: When I wrote this post I was a beginner on Stackoverflow and in programming generally. I don't remember how I solved this inquiry unfortunately. How can I close this post? I am having trouble working with this specific module. At first, I had a problem importing alpha...
Fail to import Alpha_vantage.timesseries
EDIT: When I wrote this post I was a beginner on Stackoverflow and in programming generally. I don't remember how I solved this inquiry unfortunately. How can I close this post? I am having trouble working with this specific module. At first, I had a problem importing alpha vantage but I could install it with the follo...
[ "In your example you import TimesSeries from alpha_vantage.timeseries.\nPlease note that you have an extra s in TimeSeries.\n\nIt should be TimeSeries and not TimesSeries\n\nHere is an example from their website\nfrom alpha_vantage.timeseries import TimeSeries\n\n" ]
[ 0 ]
[ "I just went to another direction and used other library.\nEDIT: When I wrote this post I was a beginner on Stackoverflow and in programming generally. I don't remember how I solved this inquiry unfortunately. How can I close this post?\n" ]
[ -1 ]
[ "alpha_vantage", "import_module", "python" ]
stackoverflow_0070448183_alpha_vantage_import_module_python.txt
Q: Package install issue "error: legacy-install-failure" MacOS I am getting the below error when trying to install wordcloud. I am using MacOs 13.0.1 and Python 3.8.10. Jesse-Burton@MacBook-Pro-4 ~ % pip3 install wordcloud Collecting wordcloud Using cached wordcloud-1.8.2.2.tar.gz (220 kB) Preparing metadata (setup....
Package install issue "error: legacy-install-failure" MacOS
I am getting the below error when trying to install wordcloud. I am using MacOs 13.0.1 and Python 3.8.10. Jesse-Burton@MacBook-Pro-4 ~ % pip3 install wordcloud Collecting wordcloud Using cached wordcloud-1.8.2.2.tar.gz (220 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: numpy>=1.6.1 in ./.py...
[ "So it turns out that I was getting this similar error on several packages, gensim being a core one.\nI saw further up in the error message in the gensim install failure that it failed building the wheel and further down in that error message as well in this error message was this:\n\nxcrun: error: invalid active d...
[ 0 ]
[]
[]
[ "python", "python_3.x", "word_cloud" ]
stackoverflow_0074461573_python_python_3.x_word_cloud.txt
Q: Django postgres psycopg2: ImproperlyConfigure even though module installed I am using Django for the first time but have used PostgreSQL previously. I am trying to follow the official Django tutorial to set up with a database. I have followed everything but I get an error when using the command "python manage.py m...
Django postgres psycopg2: ImproperlyConfigure even though module installed
I am using Django for the first time but have used PostgreSQL previously. I am trying to follow the official Django tutorial to set up with a database. I have followed everything but I get an error when using the command "python manage.py migrate" that psycopg2 is not found even though I have it installed.Traceback (mo...
[ "It's seems like you use system python for running your migrations. Error traceback contains following path of python binary: \"/Users/alexanderverheecke/Library/Python/3.9/...\", however in pip show command your python path is \"/opt/homebrew/lib/python3.10/\".\nActually I don't understand how it's even possible, ...
[ 0 ]
[]
[]
[ "django", "postgresql", "psycopg2", "python" ]
stackoverflow_0074477149_django_postgresql_psycopg2_python.txt
Q: Error when appending data to existing data frame to retrain a model I am adding more data to a my X_train data as well as to my y_train data in order to retrain my model with more data. I do this using pd. concat(). However, when I train my model using the concatenated dataset I get the following error: /usr/local...
Error when appending data to existing data frame to retrain a model
I am adding more data to a my X_train data as well as to my y_train data in order to retrain my model with more data. I do this using pd. concat(). However, when I train my model using the concatenated dataset I get the following error: /usr/local/lib/python3.7/dist-packages/sklearn/utils/validation.py:1692: FutureWar...
[ "Given a data frame that is entirely strings but can be turned without errors into numbers, you can just call df.astype(float) on the whole lot.\n>>> df = pd.DataFrame([str(i) for i in range(0, 1000)], columns=['x'])\n>>> df\n x\n0 0\n1 1\n2 2\n3 3\n4 4\n.. ...\n995 995\n996 996\n...
[ 2 ]
[]
[]
[ "floating_point", "pandas", "python" ]
stackoverflow_0074477605_floating_point_pandas_python.txt
Q: assignments to list elements for a list created using the * operator not working as expected in Python >>> m=[[-1]*2]*2 >>> n=[[-1,-1],[-1,-1]] >>> m==n True >>> for i in range(2): ... m[i][i]=10 ... >>> m [[10, 10], [10, 10]] >>> for i in range(2): ... n[i][i]=10 ... >>> n [[10, -1], [-1, 10]] In the code bloc...
assignments to list elements for a list created using the * operator not working as expected in Python
>>> m=[[-1]*2]*2 >>> n=[[-1,-1],[-1,-1]] >>> m==n True >>> for i in range(2): ... m[i][i]=10 ... >>> m [[10, 10], [10, 10]] >>> for i in range(2): ... n[i][i]=10 ... >>> n [[10, -1], [-1, 10]] In the code block above, the assignment to the elements of n takes place as expected, but the assignment to elements of m is...
[]
[]
[ "Lists are used to store separate values, you can't declare a integer into a list and attempt to multiply it without specifying which number to multiply, and putting a integer in brackets m=[[-1]*2]*2 is how that can work, instead, do m=[-1] m[0]*2*2\n" ]
[ -2 ]
[ "list", "python" ]
stackoverflow_0074477705_list_python.txt
Q: Having n (2048 bit number), how can I find two numbers p and q that satisfy n = p*q, where p = r||s (r and s concatenated) and q = s||r? I'm using the RSA encryption/decryption system, and I have the modulus n (which is a 2048 bit number) and I need to find p and q, which satisfy n = p*q and both are prime numbers...
Having n (2048 bit number), how can I find two numbers p and q that satisfy n = p*q, where p = r||s (r and s concatenated) and q = s||r?
I'm using the RSA encryption/decryption system, and I have the modulus n (which is a 2048 bit number) and I need to find p and q, which satisfy n = p*q and both are prime numbers. The clue that is given to me is that p is equal to q but with its bits inverted as I say in the title of this post (concretely r and s have ...
[ "OK here's how you can solve this problem.\nStart by representing p and q in terms of two k-bit numbers r and s as follows (for your example, k=512):\n\np = 2kr + s\nq = 2ks + r\n\nThe value of n is the product of these two numbers:\n\nn   =   pq   =   (2kr + s)(2ks + r)   =   22krs + 2k(r2 + s2) + rs\n\nThe first ...
[ 1 ]
[]
[]
[ "cryptography", "encryption", "factors", "python", "rsa" ]
stackoverflow_0074451247_cryptography_encryption_factors_python_rsa.txt
Q: Pandas map returns column with NaN values I have two dataframes. I am trying to map state postal codes from state_abbv_dict to the state column. county_2015.head() Year Month State County Rate min_wage 0 2015 February Mississippi Newton County 6.1 7.91 1 2015 February Mississippi ...
Pandas map returns column with NaN values
I have two dataframes. I am trying to map state postal codes from state_abbv_dict to the state column. county_2015.head() Year Month State County Rate min_wage 0 2015 February Mississippi Newton County 6.1 7.91 1 2015 February Mississippi Panola County 9.4 7.91 2 2015 February ...
[ "It looks like it's because the states are a secondary level, I think you just need to change it to this:\ncounty_2015['State'] = county_2015['State'].map(state_abbv_dict['Postal Code'])\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "merge", "python" ]
stackoverflow_0074477794_dictionary_merge_python.txt
Q: Selenium - can't get the correct XPath using Chrome inspect elements - @id="layers" vs @id="react-root" - Python Trying to get the correct XPATH for the username box for the Twitter login. My (simplified) code is: from selenium import webdriver from selenium.webdriver import Keys from selenium.webdriver.chrome.ser...
Selenium - can't get the correct XPath using Chrome inspect elements - @id="layers" vs @id="react-root" - Python
Trying to get the correct XPATH for the username box for the Twitter login. My (simplified) code is: from selenium import webdriver from selenium.webdriver import Keys from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By import time driver_service = Service(executable_path=...
[ "A manual procedure using xml2xpath can be used to show all possible XPath expressions from an HTML/XML source.\nSaving the page source from the browser or the Outer Html from dev console to a file and passing a starting XPath expression:\nxml2xpath.sh -s '//*[@id=\"react-root\"]' -l tmp.html\n\nResult using Outer...
[ 0 ]
[]
[]
[ "python", "reactjs", "selenium_chromedriver", "selenium_webdriver", "xpath" ]
stackoverflow_0074476685_python_reactjs_selenium_chromedriver_selenium_webdriver_xpath.txt
Q: How to make a non-overriding method stub in Python multi-inheritance? Imagine that you have 2 mixin classes, that each define abstract methods and implementations. Together they implement every method, but depending on the inheritance order, the empty stubs will overwrite the implementation from the other class. T...
How to make a non-overriding method stub in Python multi-inheritance?
Imagine that you have 2 mixin classes, that each define abstract methods and implementations. Together they implement every method, but depending on the inheritance order, the empty stubs will overwrite the implementation from the other class. There's at least two ways to overcome this in most situations but I don't re...
[ "OK, this is what an ABC-based implementation might look like.\nYou just have to mix and match the Mixins to achieve what you want. The Mixins only implement what they are actually providing.\nmypy will flag errors during type-checking\nabc will also throw errors about missing methods at runtime\nfrom abc import A...
[ 0, 0 ]
[]
[]
[ "multiple_inheritance", "python", "virtual" ]
stackoverflow_0074220534_multiple_inheritance_python_virtual.txt
Q: Get Binary Representation of PIL Image Without Saving I am writing an application that uses images intensively. It is composed of two parts. The client part is written in Python. It does some preprocessing on images and sends them over TCP to a Node.js server. After preprocessing, the Image object looks like this...
Get Binary Representation of PIL Image Without Saving
I am writing an application that uses images intensively. It is composed of two parts. The client part is written in Python. It does some preprocessing on images and sends them over TCP to a Node.js server. After preprocessing, the Image object looks like this: window = img.crop((x,y,width+x,height+y)) window = windo...
[ "According to the documentation, (at effbot.org):\n\"You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the seek, tell, and write methods, and be opened in binary mode.\"\nThis means you can pass a StringIO object. Write to it and get t...
[ 4, 0 ]
[ "It's about the difference between in-memory file-like object and BufferedReader object.\nHere is my experiment in Jupyter(Python 3.8.10):\nfrom PIL import Image as PILImage, ImageOps as PILImageOps\nfrom IPython.display import display, Image\nfrom io import BytesIO\nimport base64\n\nurl = \"https://learn.microsoft...
[ -1, -2 ]
[ "node.js", "python", "python_imaging_library", "sockets" ]
stackoverflow_0027652121_node.js_python_python_imaging_library_sockets.txt
Q: ElementNotVisibleException: Message: element not interactable in Robot Framework Example code: <div class="modal-footer"> <button type="button" class="btn btn-primary btn-block" data-modal="AlertSubmitApproval" id="btn_close_modal">ตกลง</button> </div> I try to click the button id="btn_close_modal" but it seem...
ElementNotVisibleException: Message: element not interactable in Robot Framework
Example code: <div class="modal-footer"> <button type="button" class="btn btn-primary btn-block" data-modal="AlertSubmitApproval" id="btn_close_modal">ตกลง</button> </div> I try to click the button id="btn_close_modal" but it seems like the button is not visible then robot response ElementNotVisibleException: Messa...
[ "The desired element is within a Modal Dialog Box so you need to induce WebDriverWait for the element to be visible/enabled and you can use either/both (clubbing up) of the following solutions:\n\nWait Until Element Is Visible:\nRequest approve\nSelenium2Library.Click Element &{Landing}[reqApprove]\nSleep 2s\nS...
[ 3, 0, 0, 0 ]
[]
[]
[ "element", "python", "robotframework", "selenium", "webdriverwait" ]
stackoverflow_0053097684_element_python_robotframework_selenium_webdriverwait.txt
Q: sklearn cross_val_score() returns NaN values i'm trying to predict next customer purchase to my job. I followed a guide, but when i tried to use cross_val_score() function, it returns NaN values.Google Colab notebook screenshot Variables: X_train is a dataframe X_test is a dataframe y_train is a list y_test is a...
sklearn cross_val_score() returns NaN values
i'm trying to predict next customer purchase to my job. I followed a guide, but when i tried to use cross_val_score() function, it returns NaN values.Google Colab notebook screenshot Variables: X_train is a dataframe X_test is a dataframe y_train is a list y_test is a list Code: X_train, X_test, y_train, y_test = tr...
[ "My case is a bit different. I was using cross_validate instead of cross_val_score with a list of performance metrics. Doing a 5 fold CV, I kept getting NaNs for all performance metrics for a RandomForestRegressor:\nscorers = ['neg_mean_absolute_error', 'neg_root_mean_squared_error', 'r2', 'accuracy']\n\nresults = ...
[ 5, 4, 1, 0, 0, 0, 0 ]
[ "For me using xtrain.values, ytrain.values worked as the cross validation needs the input to be an array and not dataframe.\n", "The cross_val_score method returns NaN when there are null values in your dataset.\nEither use a model which can deal with missing values or remove all the null values from your dataset...
[ -1, -2 ]
[ "cross_validation", "nan", "prediction", "python", "sklearn_pandas" ]
stackoverflow_0060172458_cross_validation_nan_prediction_python_sklearn_pandas.txt
Q: New dataframe in Pandas based on specific values(a lot of them) from existing df Good evening! I'm using pandas on Jupyter Notebook. I have a huge dataframe representing full history of posts of 26 channels in a messenger. It has a column "dialog_id" which represents in which dialog the message was sent(so, there ...
New dataframe in Pandas based on specific values(a lot of them) from existing df
Good evening! I'm using pandas on Jupyter Notebook. I have a huge dataframe representing full history of posts of 26 channels in a messenger. It has a column "dialog_id" which represents in which dialog the message was sent(so, there can be only 26 unique values in the column, but there are more then 700k rows, and the...
[ "The easiest way seems to be just setting up a query.\ndf = pd.DataFrame(dict(col_id=[1,2,3,4,], other=[5,6,7,8,]))\n\nchannel_groupA = [1,2]\nchannel_groupB = [3,4]\n\ndf_groupA = df.query(f'col_id == {channel_groupA}')\ndf_groupB = df.query(f'col_id == {channel_groupB}')\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074477104_dataframe_jupyter_notebook_pandas_python.txt
Q: Trick_winner Funciton I have created a class function called trick_winner(self) within the class Cards which take the value within self.trick1 for example self.trick1 = ('AH' 'JH' 'KH' '2H') and returns the pairs in order from great to least, being that 'A' is the highest value followed by '7', 'J', 'K', 'Q', '6',...
Trick_winner Funciton
I have created a class function called trick_winner(self) within the class Cards which take the value within self.trick1 for example self.trick1 = ('AH' 'JH' 'KH' '2H') and returns the pairs in order from great to least, being that 'A' is the highest value followed by '7', 'J', 'K', 'Q', '6', '5', '4', '3', '2'. But wh...
[ "You should create a class for a single card and implement the order. Look here:\nR = {\"2\": 0, \"3\": 0, \"4\": 0, \"5\": 0, \"6\": 0, \"J\": 4, \"Q\": 3, \"K\": 5, \"7\": 10, \"A\": 11}\n\nclass Card:\n def __init__(self, color, value):\n self.color = color\n self.value = value\n\n def __lt__...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074477641_python.txt
Q: I am trying to run this code that asks user to enter a sentence, the display the number of vowels and consonants in the sentence I am getting syntax errors when trying to run or sometimes it runs but does not execute the way I am intending it to. I have been playing around with the formatting but still no solution...
I am trying to run this code that asks user to enter a sentence, the display the number of vowels and consonants in the sentence
I am getting syntax errors when trying to run or sometimes it runs but does not execute the way I am intending it to. I have been playing around with the formatting but still no solution. def checkVowelsConsonants(s): vowels=0 consonants=0 for ch in s: #convert character into its ASCII equivalent as...
[ "I've cleaned up your code, checking ascii values with 65 <= ascii_value <= 90.\nAs you want to check lowercase and upper case vowels I made this one if condition by checking if ch in \"aeiouAEIOU\" making all other valid characters lowercase or uppercase consonants.\nIt is also not necessary to convert your user i...
[ 0, 0 ]
[]
[]
[ "for_loop", "python", "syntax_error", "while_loop" ]
stackoverflow_0074475753_for_loop_python_syntax_error_while_loop.txt
Q: How do I parse a List JSON File in CSV into a dataframe [{"Apertura":35,"Apertura_Homogeneo":35,"Cantidad_Operaciones":1,"Cierre":35,"Cierre_Homogeneo":35,"Denominacion":"INSUMOS AGROQUIMICOS S.A.","Fecha":"02\/02\/2018","Maximo":35,"Maximo_Homogeneo":35,"Minimo":35,"Minimo_Homogeneo":35,"Monto_Operado_Pesos":175,...
How do I parse a List JSON File in CSV into a dataframe
[{"Apertura":35,"Apertura_Homogeneo":35,"Cantidad_Operaciones":1,"Cierre":35,"Cierre_Homogeneo":35,"Denominacion":"INSUMOS AGROQUIMICOS S.A.","Fecha":"02\/02\/2018","Maximo":35,"Maximo_Homogeneo":35,"Minimo":35,"Minimo_Homogeneo":35,"Monto_Operado_Pesos":175,"Promedio":35,"Promedio_Homogeneo":35,"Simbolo":"INAG","Varia...
[ "You do not need to convert the dataframe to json and back.\nIf you want the sum of a column you can use:\ndf = pd.read_csv(r'filename')\ndf[\"Volumen_Nominal\"].sum()\n\n" ]
[ 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074477954_json_pandas_python.txt
Q: replacing in dataframe based on list/array If I have an array/list like such, (['Alabama', 'Arizona', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah']) and I have a dataframe column where those values in the array are present and repeating, how do I replace them based on the location's index in the...
replacing in dataframe based on list/array
If I have an array/list like such, (['Alabama', 'Arizona', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah']) and I have a dataframe column where those values in the array are present and repeating, how do I replace them based on the location's index in the array? eg my column has Alabama which has an in...
[ "Let us say you have a dataframe like this:\ndf = pd.DataFrame({\"States\": ['Alabama', 'Arizona', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah',\n 'Alabama', 'Arizona', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah']})\n\nprint(df)\n\n\nThen you could a...
[ 0 ]
[]
[]
[ "for_loop", "python", "replace" ]
stackoverflow_0074477848_for_loop_python_replace.txt
Q: InvocationException: GraphViz's executables not found I'm unable to visualize or write the Decision tree. How can I go about it? Python version 3.5, Anaconda 3, I have even set the environment variables from sklearn import tree model = tree.DecisionTreeClassifier(criterion='gini') model=tree.DecisionT...
InvocationException: GraphViz's executables not found
I'm unable to visualize or write the Decision tree. How can I go about it? Python version 3.5, Anaconda 3, I have even set the environment variables from sklearn import tree model = tree.DecisionTreeClassifier(criterion='gini') model=tree.DecisionTreeClassifier() model.fit(trainData,trainLabel) mod...
[ "I understand the thread is a little old but today I got the same error when trying to visualize a Bayesian Network in a Jupyter notebook with the PyAgrum library.\nI'm on Windows 10 using the Anaconda package management. In my case I needed to install the package python-graphviz using the following command:\nconda...
[ 1, 0, 0 ]
[ "You can take help of this code !!\nimport pydotplus\nfrom sklearn.datasets import load_iris\nfrom sklearn import tree\nimport collections\n\n# Data Collection\nX = [ [180, 15,0], \n [177, 42,0],\n [136, 35,1],\n [174, 65,0],\n [141, 28,1]]\n\nY = ['man', 'woman', 'woman', 'man', 'woman'] ...
[ -4 ]
[ "decision_tree", "pygraphviz", "python", "python_3.x" ]
stackoverflow_0043535863_decision_tree_pygraphviz_python_python_3.x.txt
Q: How to count characters from nested lists of strings inside a dictionary (Python)? I'm trying to count the frequency of a charater from nested lists of strings inside a dictionary. Returning, for each key, the most frequent value. I was thinking something along the lines of: res = {0: ['a', 'a', 'b'], 1: ['e'], 2:...
How to count characters from nested lists of strings inside a dictionary (Python)?
I'm trying to count the frequency of a charater from nested lists of strings inside a dictionary. Returning, for each key, the most frequent value. I was thinking something along the lines of: res = {0: ['a', 'a', 'b'], 1: ['e'], 2: ['i', 'x', 'i', 'c']} for k, v in res.items(): # count the most frequent print(res)...
[ "output = {k: most_frequenct(v) for k, v in data.items()}\n\nmost_frequenct could be any of the following\nhttps://www.geeksforgeeks.org/python-find-most-frequent-element-in-a-list/\nHope it helps\n" ]
[ 0 ]
[]
[]
[ "dictionary", "list", "python", "string" ]
stackoverflow_0074477988_dictionary_list_python_string.txt
Q: How to do this Not In operation without triggering an overflow in the marker amount of operations in pyobdc/sqlalchemy? This is a simplification of the case: I have two databases, a MySQL and a MS_Access. I am trying to delete all elements from the MsAccess that are not in the MySQL table but are still in MSAccess...
How to do this Not In operation without triggering an overflow in the marker amount of operations in pyobdc/sqlalchemy?
This is a simplification of the case: I have two databases, a MySQL and a MS_Access. I am trying to delete all elements from the MsAccess that are not in the MySQL table but are still in MSAccess. I am using sqlalchemy to connect to both DB. To connect with MSAccess (I know, this database should not be used anymore, th...
[ "\nI could do this query in blocks of 32768 rows\n\nThat won't work for a NOT IN query. Say you had a list of rows to keep:\n[1, 2, 3, 4, 5, 6]\n\nIf you tried to do that in batches of 3 then the first DELETE would be\nDELETE FROM access_table WHERE id NOT IN (1, 2, 3)\n\nwhich would delete the rows with id values ...
[ 2 ]
[]
[]
[ "ms_access", "mysql", "pyodbc", "python", "sqlalchemy" ]
stackoverflow_0074474679_ms_access_mysql_pyodbc_python_sqlalchemy.txt
Q: Create a new dataframe by removing the outliers from the column I am working on removing outlier tutorial but it quite confused me when this loop not working properly: target = df['ConvertedComp'] mean = target.mean() sd = target.std() for x in target: z_score = (x-mean)/sd if np.abs(z_score) > 3: ...
Create a new dataframe by removing the outliers from the column
I am working on removing outlier tutorial but it quite confused me when this loop not working properly: target = df['ConvertedComp'] mean = target.mean() sd = target.std() for x in target: z_score = (x-mean)/sd if np.abs(z_score) > 3: selected_df = df[df.ConvertedComp != x] Also are there any other met...
[ "You can try the following code to select rows where z_score calculated from ConvertedComp column is less than or equal to 3.\nmask = df['ConvertedComp'].sub(df['ConvertedComp'].mean()).div(df['ConvertedComp'].std()).abs().le(3)\n\ndf = df[mask]\n\n", "Here is what worked for me.\n(NOTE: A variation of this answe...
[ 0, 0 ]
[]
[]
[ "dataframe", "outliers", "pandas", "python" ]
stackoverflow_0067513640_dataframe_outliers_pandas_python.txt
Q: Python, adding a for loop to limit no. of tries - error in code In the following code, I am trying to use a flag to break out of the loop when true (password is correct) but limit the number of incorrect tries to 3. def secretagent(): flag=False while flag==False: for i in range(3): password=input("E...
Python, adding a for loop to limit no. of tries - error in code
In the following code, I am trying to use a flag to break out of the loop when true (password is correct) but limit the number of incorrect tries to 3. def secretagent(): flag=False while flag==False: for i in range(3): password=input("Enter password:") if password=="secret007": print("Acces...
[ "Use int instead of bool\nimport sys\n\nnumber_of_tries = 0\nwhile True:\n if number_of_tries == 3:\n sys.exit() # exit the program\n password=input(\"Enter password:\")\n if password==\"secret007\":\n print(\"Access Granted!\")\n break\n else:\n print(\"Impostor...access den...
[ 2, 2 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074477916_loops_python.txt
Q: Divide DataFrame Column on (,) into two new columns I have a pandas DataFrame called data_combined with the following structure: index corr_year corr_5d 0 (DAL, AAL) 0.873762 0.778594 1 (WEC, ED) 0.851578 0.850549 2 (CMS, LNT) 0.850028 0.776143 3 (SWKS, QRVO) 0.850799 0.830603 4 ...
Divide DataFrame Column on (,) into two new columns
I have a pandas DataFrame called data_combined with the following structure: index corr_year corr_5d 0 (DAL, AAL) 0.873762 0.778594 1 (WEC, ED) 0.851578 0.850549 2 (CMS, LNT) 0.850028 0.776143 3 (SWKS, QRVO) 0.850799 0.830603 4 (ALK, DAL) 0.874162 0.744590 Now I am trying to di...
[ "How about a simple apply? (Assuming 'index' column is a tuple)\ndata_results_combined['index1'] = data_results_combined['index'].apply(lambda x: x[0])\ndata_results_combined['index2'] = data_results_combined['index'].apply(lambda x: x[1])\n\n", "df[['index1','index2']] = df['index'].str.split(',',expand=True)\n\...
[ 2, 0 ]
[]
[]
[ "explode", "pandas", "python" ]
stackoverflow_0074478109_explode_pandas_python.txt
Q: How to properly mask a numpy 2D array? Say I have a two dimensional array of coordinates that looks something like x = array([[1,2],[2,3],[3,4]]) Previously in my work so far, I generated a mask that ends up looking something like mask = [False,False,True] When I try to use this mask on the 2D coordinate vector, I...
How to properly mask a numpy 2D array?
Say I have a two dimensional array of coordinates that looks something like x = array([[1,2],[2,3],[3,4]]) Previously in my work so far, I generated a mask that ends up looking something like mask = [False,False,True] When I try to use this mask on the 2D coordinate vector, I get an error newX = np.ma.compressed(np.ma....
[ "Is this what you are looking for?\nimport numpy as np\nx[~np.array(mask)]\n# array([[1, 2],\n# [2, 3]])\n\nOr from numpy masked array:\nnewX = np.ma.array(x, mask = np.column_stack((mask, mask)))\nnewX\n\n# masked_array(data =\n# [[1 2]\n# [2 3]\n# [-- --]],\n# mask =\n# [[False False]\n# ...
[ 25, 9, 8, 2, 2, 1, 0 ]
[]
[]
[ "mask", "masked_array", "matrix", "numpy", "python" ]
stackoverflow_0038193958_mask_masked_array_matrix_numpy_python.txt
Q: Snakemake MissingOutputException when writing list to file I'm having a MissingOutputException with what I think is a very basic rule. I'm trying to print a list given through the config file into a file using some Python commands but Snakemake keeps throwing MissingOutputException error: # --- Importing Configura...
Snakemake MissingOutputException when writing list to file
I'm having a MissingOutputException with what I think is a very basic rule. I'm trying to print a list given through the config file into a file using some Python commands but Snakemake keeps throwing MissingOutputException error: # --- Importing Configuration Files --- # configfile: "config.yaml" # -----------------...
[ "If you want to include Python code directly into your Snakefile you have to loose the quotation marks around your Python code in the run directive:\nscaffolds = [\"dummy\", \"entries\"]\n\nlocalrules: all, MakeScaffoldList\n\n# -------------------------------------------------\n\nrule all:\n input:\n LIS...
[ 1 ]
[]
[]
[ "python", "snakemake" ]
stackoverflow_0074475638_python_snakemake.txt
Q: filter out observation of a column which start with values of a list I have the following dataframe: import pandas as pd df = pd.DataFrame({'code': ['52511', '52512', '12525', '13333']}) and the following list: list = ['525', '13333'] I want to consider only the observations of df that start witht the element of...
filter out observation of a column which start with values of a list
I have the following dataframe: import pandas as pd df = pd.DataFrame({'code': ['52511', '52512', '12525', '13333']}) and the following list: list = ['525', '13333'] I want to consider only the observations of df that start witht the element of list. Desired output: import pandas as pd df = pd.DataFrame({'code': ['52...
[ "The startswith function supports tuple type. You can convert list to tuple.\nlistt = ['525', '13333']\ndf=df[df['code'].str.startswith(tuple(listt))]\ndf\n'''\n code\n0 52511\n1 52512\n3 13333\n\n'''\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python", "string" ]
stackoverflow_0074478159_pandas_python_string.txt
Q: How to generate a time-ordered uid in Python? Is this possible? I've heard Cassandra has something similar : https://datastax.github.io/python-driver/api/cassandra/util.html I have been using a ISO timestamp concatenated with a uuid4, but that ended up way too large (58 characters) and probably overkill. Keeping a...
How to generate a time-ordered uid in Python?
Is this possible? I've heard Cassandra has something similar : https://datastax.github.io/python-driver/api/cassandra/util.html I have been using a ISO timestamp concatenated with a uuid4, but that ended up way too large (58 characters) and probably overkill. Keeping a sequential number doesn't work in my context (Dyna...
[ "Why uuid.uuid1 is not sequential\nuuid.uuid1(node=None, clock_seq=None) is effectively:\n\n60 bits of timestamp (representing number of 100-ns intervals after 1582-10-15 00:00:00)\n14 bits of \"clock sequence\"\n48 bits of \"Node info\" (generated from network card's mac-address or from hostname or from RNG).\n\nI...
[ 11, 1, 1, 0 ]
[]
[]
[ "amazon_dynamodb", "python", "python_3.x", "uuid" ]
stackoverflow_0056119272_amazon_dynamodb_python_python_3.x_uuid.txt
Q: Timestamp overlapping matplotlib I am trying to create a graph using matplotlib with number of requests (y-axis) vs timestamp (x-axis in HH:MM format). This graph will show the pattern for the all the requests received between 6:00 AM to 6:00 PM. Below is the sample data. Actual data has more than 500 entries. tim...
Timestamp overlapping matplotlib
I am trying to create a graph using matplotlib with number of requests (y-axis) vs timestamp (x-axis in HH:MM format). This graph will show the pattern for the all the requests received between 6:00 AM to 6:00 PM. Below is the sample data. Actual data has more than 500 entries. time_stamp = ['06:02', '06:03', '06:12', ...
[ "For just fully rotating the labels like in your excel plot. Try this.\nplt.setp( ax.xaxis.get_majorticklabels(), rotation=90)\n\n", "After doing more research finally I am able to plot it.\ndates = []\nfor ts in time_stamp:\n local_d = datetime.strptime(ts, '%H:%M')\n dates.append( local_d)\n\nfig, ax = plt....
[ 0, 0, 0, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0049947615_matplotlib_python.txt
Q: Angle of reflection relative to coordinate system I have a two 2D points u = (ux, uy) and v = (vx, vy) that define a line segment. Additionally I have an angle θ that is defined relative to the coordinate system (angle to x-axis), indicating the directing of a moving particle. Is there a simple way to find the ang...
Angle of reflection relative to coordinate system
I have a two 2D points u = (ux, uy) and v = (vx, vy) that define a line segment. Additionally I have an angle θ that is defined relative to the coordinate system (angle to x-axis), indicating the directing of a moving particle. Is there a simple way to find the angle of reflection resulting (again, relative to the coor...
[ "Segment has length\nleng = hypot(vy-uy, vx-ux)\n\nand unit direction vector (perhaps in numpy there is ready function like normalized)\ndx = (vx-ux) / leng\ndy = (vy-uy) / leng\n\nUnit normal to segment\nnx = - dy\nny = dx\n\nparticle direction vector is\npx = cos(θ)\npy = sin(θ)\n\nReflected vector\ndott = dot(p...
[ 1 ]
[]
[]
[ "geometry", "python", "reflection", "simulation", "vector" ]
stackoverflow_0074477952_geometry_python_reflection_simulation_vector.txt
Q: How to send data between 2 EC2 instances I have two AWS EC2 instances, one running a.py and b.py. These two programs use data produced by the other to complete tasks, a.py waits for b.py to create some data that it uses to create some data that a.py will use to create data that b.py will .... basically, they will ...
How to send data between 2 EC2 instances
I have two AWS EC2 instances, one running a.py and b.py. These two programs use data produced by the other to complete tasks, a.py waits for b.py to create some data that it uses to create some data that a.py will use to create data that b.py will .... basically, they will keep passing data back and forth until a condi...
[ "As you are using AWS already, the native solution for things like that is SQS queue. To achieve that task, you need to create two SQS queue:\n\nSQS-Queue-App-A\nSQS-Queue-App-B\n\nThen make a.py, something along these lines:\nimport boto3\n\n# Create SQS client\nsqs = boto3.client('sqs')\n\nqueue_a_url = 'SQS_QUEU...
[ 2 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "python" ]
stackoverflow_0074477177_amazon_ec2_amazon_web_services_python.txt
Q: How to check if a specific number is present in the lines of a file? I have a file named in.txt. in.txt 0000fb435 00000326fab123bc2a 20 00003b4c6 0020346afeff655423 26 0000cb341 be3652a156fffcabd5 26 . . i need to check if number 20 is present in file and if present i need the output to look like this. Expecte...
How to check if a specific number is present in the lines of a file?
I have a file named in.txt. in.txt 0000fb435 00000326fab123bc2a 20 00003b4c6 0020346afeff655423 26 0000cb341 be3652a156fffcabd5 26 . . i need to check if number 20 is present in file and if present i need the output to look like this. Expected output: out.txt 0020fb435 00000326fab123bc2a 20 twenty_number 00003b4c6...
[ "You just need to use endswith as the if condition.\nwith open(\"in.txt\", \"r\") as fin:\n with open(\"out.txt\", \"w\") as fout:\n for line in fin:\n line = line.strip()\n if line.endswith('20'):\n fout.write(line + f\" twenty_number \\n\")\n else:\n ...
[ 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074478191_python_python_3.x.txt
Q: How do I use a custom generator function to feed Keras model.fit samples one by one? The Problem Feeding data into Keras LSTM model with my custom generator function (see code below) gives me the following error. WARNING:tensorflow:Model was constructed with shape (None, 3177, 2) for input KerasTensor(type_spec=T...
How do I use a custom generator function to feed Keras model.fit samples one by one?
The Problem Feeding data into Keras LSTM model with my custom generator function (see code below) gives me the following error. WARNING:tensorflow:Model was constructed with shape (None, 3177, 2) for input KerasTensor(type_spec=TensorSpec(shape=(None, 3177, 2), dtype=tf.float32, name='masking_9_input'), name='masking_...
[ "For any future people with the same question:\nI'm not really sure what the problem was. My guess is that my generator was feeding the whole tuple (input, label) to the network as an input, while I only desired it to feed the input and not the label. Hence, the error with input_shape. However, the Keras docs state...
[ 0 ]
[]
[]
[ "generator", "keras", "lstm", "machine_learning", "python" ]
stackoverflow_0074404355_generator_keras_lstm_machine_learning_python.txt
Q: How to split df column into df row? I have a df that looks like this id shortTextContent shortTextCode longPlainTextContent longTextCode semiTextContent semiTextCode 1 shortContent1 shortCode1 long1 longCode1 semiContent1 semiCode1 2 shortContent2 shortCode2 l...
How to split df column into df row?
I have a df that looks like this id shortTextContent shortTextCode longPlainTextContent longTextCode semiTextContent semiTextCode 1 shortContent1 shortCode1 long1 longCode1 semiContent1 semiCode1 2 shortContent2 shortCode2 long2 longCode2 semiCont...
[ "df = pd.DataFrame(dict(id=[1,2,3,4],other=['a','b','c','d']))\ndf_melted = pd.melt(df)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074476475_dataframe_pandas_python.txt
Q: writing Airflow 2 dag I have been in Airflow 1.10.14 for a long time, and now I'm trying to upgrade to Airflow 2.4.3 (latest?) I have built this dag in the new format in hopes to assimilate the language and understand how the new format works. Below is my dag: from airflow.decorators import dag, task from airflo...
writing Airflow 2 dag
I have been in Airflow 1.10.14 for a long time, and now I'm trying to upgrade to Airflow 2.4.3 (latest?) I have built this dag in the new format in hopes to assimilate the language and understand how the new format works. Below is my dag: from airflow.decorators import dag, task from airflow.models import Variable f...
[ "You forgot to remove an undefined dag variable in CLEAR_STAGING. When you are using decorator, remove dag=dag.\nCLEAR_STAGING = BashOperator(\n task_id='Clear_Folders',\n bash_command=clear_Staging_Folders,\n # dag=dag <== Remove this\n)\n\n" ]
[ 1 ]
[]
[]
[ "airflow", "airflow_2.x", "python" ]
stackoverflow_0074470445_airflow_airflow_2.x_python.txt
Q: Pygame.event.get() stopped working. It says the video system hasn't been initialized I was dealing with another section of my code not working (which can be found in the code's comments) when I noticed that my filename wasn't what I wanted it to be. I closed VS Code, changed the filename, and it started giving thi...
Pygame.event.get() stopped working. It says the video system hasn't been initialized
I was dealing with another section of my code not working (which can be found in the code's comments) when I noticed that my filename wasn't what I wanted it to be. I closed VS Code, changed the filename, and it started giving this error. I'm not sure what's up, and all I could find on the internet was 'initialize pyga...
[ "It is a matter of indentation, pygame.quit() must be called after the application loop, but not in the application loop:\nwhile not quitt: #main loop\n clock.tick(60) #60 fps\n for event in pygame.event.get(): # this is breaking\n if event.type == pygame.QUIT:\n quitt = True\n pygame.draw.rect(win, (0, ...
[ 0 ]
[]
[]
[ "pygame", "python", "window" ]
stackoverflow_0074478317_pygame_python_window.txt
Q: How to have nested generators continue their logic while parent generators needs to stop? Lets say I have the following code def top(): counter = 0 for ch in child_1(): print(ch) counter += 1 if counter > 2: break def child_1(): for ch in child_2(): yield ...
How to have nested generators continue their logic while parent generators needs to stop?
Lets say I have the following code def top(): counter = 0 for ch in child_1(): print(ch) counter += 1 if counter > 2: break def child_1(): for ch in child_2(): yield ch print("child_1 logic has finished") def child_2(): for ch in "123456789": ...
[ "If you want the children to \"finish\" what they're doing (i.e. perform the rest of the iteration), keep a reference to the iterator, and exhaust it after you break:\ndef top():\n counter = 0\n\n iter_1 = child_1()\n for ch in iter_1:\n print(ch)\n counter += 1\n\n if counter > 2:\n ...
[ 3, 1 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0074477990_generator_python.txt
Q: Extract value associated with column name on non-zero rows I have two dfs(500x100 & 1300x2) and want to create a new column in the first one with which categories that occur on each row. To achieve this I need to fetch the category associated with the column name from second df. There might be several categories o...
Extract value associated with column name on non-zero rows
I have two dfs(500x100 & 1300x2) and want to create a new column in the first one with which categories that occur on each row. To achieve this I need to fetch the category associated with the column name from second df. There might be several categories on same row. df = pd.DataFrame({'apple': [0, 0, 1, 0], 'strawber...
[ "there might be easier ways of doing this but this works i think :)\ndf = pd.DataFrame({'apple': [0, 0, 1, 0], \n'strawberries': [0, 1, 1, 0], \n'cucumber': [1, 1, 0, 0], \n'hawthorn': [0, 1, 0, 1]})\n\ndf2 = pd.DataFrame({'storage': ['apple', 'strawberries', 'cucumber', 'hawthorn'],\n'category': ['fruits', 'berrie...
[ 0, 0 ]
[]
[]
[ "categories", "dictionary", "pandas", "python" ]
stackoverflow_0074477817_categories_dictionary_pandas_python.txt
Q: Python not running shell command I am trying to download a youtube video using yt-dlp. The python file uses yt-dlp to download a youtube video by passing a URL of the video manually into python script using the subprocess.Open function. import subprocess from moviepy.editor import * import os import moviepy.editor...
Python not running shell command
I am trying to download a youtube video using yt-dlp. The python file uses yt-dlp to download a youtube video by passing a URL of the video manually into python script using the subprocess.Open function. import subprocess from moviepy.editor import * import os import moviepy.editor as mp # Download files through url a...
[ "From the docs:\n\nAn example of passing some arguments to an external program as a sequence is:\nPopen([\"/usr/bin/git\", \"commit\", \"-m\", \"Fixes a bug.\"])\nOn POSIX, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arg...
[ 1 ]
[]
[]
[ "moviepy", "python", "subprocess" ]
stackoverflow_0074473623_moviepy_python_subprocess.txt
Q: How to install Tensorflow properly on Windows using Python? I'm trying to use tensorflow with my PC's GPU (Nvidia RTX 3070Ti) in python-conda environment. I'm solving a small image-classification problem from kaggle. I've solved it in google-collab, but now I'm intrested in solving it on my local machine. However ...
How to install Tensorflow properly on Windows using Python?
I'm trying to use tensorflow with my PC's GPU (Nvidia RTX 3070Ti) in python-conda environment. I'm solving a small image-classification problem from kaggle. I've solved it in google-collab, but now I'm intrested in solving it on my local machine. However TF doesn't work properly locally and I have no idea why. I've rea...
[ "So here is what worked for me:\n\nCreate 3.9 python environment\nInstall cuda and tensorflow packages from \"Esri\":\n\n\nconda install -c esri cudatoolkit\nconda install -c esri cudnn\nconda install -c esri tensorflow-gpu\n\n\n\nThen install tensorflow-hub:\n\n\nconda install -c conda-forge tensorflow-hub\n\n\nIt...
[ 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074163000_python_tensorflow.txt
Q: How to save average values of column in a csv? a=np.array(h5py.File('/Users/D/FIELD-3D.h5', 'r')['Zone']['TOp']['data']) a=(a.flatten(order='C')) a.shape(3,1000) How could i get the average value of each column in a written in a csv file? A: you can use np.average with the axis attribute: np.average(a, axis=0) ...
How to save average values of column in a csv?
a=np.array(h5py.File('/Users/D/FIELD-3D.h5', 'r')['Zone']['TOp']['data']) a=(a.flatten(order='C')) a.shape(3,1000) How could i get the average value of each column in a written in a csv file?
[ "you can use np.average with the axis attribute:\nnp.average(a, axis=0)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074478289_python.txt
Q: Error (java.lang.NoSuchMethodError) when sending a Spark data frame to Azure Eventhubs from a Databricks notebook I need to send a pyspark Dataframe to an Eventhub from my Databricks notebook. The problem happens at this part of the code: ehWriteConf = { 'eventhubs.connectionString' : EVENT_HUB_CONNECTION_STRING...
Error (java.lang.NoSuchMethodError) when sending a Spark data frame to Azure Eventhubs from a Databricks notebook
I need to send a pyspark Dataframe to an Eventhub from my Databricks notebook. The problem happens at this part of the code: ehWriteConf = { 'eventhubs.connectionString' : EVENT_HUB_CONNECTION_STRING } def send_to_eventhub(df:DataFrame): ds = df.select(struct(*[c for c in df.columns]).alias("body"))\ .sele...
[ "The dataframe to write needs to have the following schema:\nColumn | Type\n----------------------------------------------\nbody (required) | string or binary \npartitionId (*optional) | string \npartitionKey (*optional) | string\n\nThis worked for me.\ndf.withColumn('body', F.to...
[ 0 ]
[]
[]
[ "azure", "azure_databricks", "azure_eventhub", "pyspark", "python" ]
stackoverflow_0073962665_azure_azure_databricks_azure_eventhub_pyspark_python.txt
Q: OpenVINO cannot convert MLP Mixer TensorFlow model I use this GitHub repository to train MLP Mixer TensorFlow 2.5.0 model. And I try to generate .bin and .xml files with the command mo --data_type FP16 --saved_model_dir C:\Users\john0\Desktop\mlp --input_shape (1,150,150,3) The following is the error I faced. [ ...
OpenVINO cannot convert MLP Mixer TensorFlow model
I use this GitHub repository to train MLP Mixer TensorFlow 2.5.0 model. And I try to generate .bin and .xml files with the command mo --data_type FP16 --saved_model_dir C:\Users\john0\Desktop\mlp --input_shape (1,150,150,3) The following is the error I faced. [ WARNING ] Failed to parse a tensor with Unicode charact...
[ "The error is due to the model having multiple inputs, and can be resolved using this MO command mo --data_type FP16 --saved_model_dir model\\directory\\mlp\\ --input_shape (1..,150,150,3). However, I'm getting different errors now:\n[ ERROR ] List of operations that cannot be converted to Inference Engine IR:\n[...
[ 0 ]
[]
[]
[ "mlp", "openvino", "python", "tensorflow" ]
stackoverflow_0074432043_mlp_openvino_python_tensorflow.txt
Q: How to modify django's request.user in a Middleware? What I'm trying to do is to detect the type of logged-in user and then setting a .profile parameter to request.user, so I can use it by calling request.user.profile in my views. To do this, I've wrote a Middleware as follows: class SetProfileMiddleware: def ...
How to modify django's request.user in a Middleware?
What I'm trying to do is to detect the type of logged-in user and then setting a .profile parameter to request.user, so I can use it by calling request.user.profile in my views. To do this, I've wrote a Middleware as follows: class SetProfileMiddleware: def __init__(self, get_response): self.get_response = ...
[ "The problem is that you cannot add new properties to the User class.\ninstead try to add the property directly to the request like this\nrequest.user_profile = User.get_profile(profile_type, request.user)\ndef set_profile(view_function):\n \n def decorated_function(request, *args, **kwargs):\n\n user,...
[ 0, 0 ]
[]
[]
[ "django", "django_middleware", "django_rest_framework", "django_rest_framework_simplejwt", "python" ]
stackoverflow_0074473955_django_django_middleware_django_rest_framework_django_rest_framework_simplejwt_python.txt
Q: Can't import from keras module 'tensorflow._api.v1.compat.v2.compat' has no attribute 'v1' I'm using jupyter/python (anaconda) and I was successful in loading these libraries I tried to print tf ver tf.print(tf. __ version __) <tf.Operation 'PrintV2' type=PrintV2> and when I ran tf.__version__ it said that I'm r...
Can't import from keras module 'tensorflow._api.v1.compat.v2.compat' has no attribute 'v1'
I'm using jupyter/python (anaconda) and I was successful in loading these libraries I tried to print tf ver tf.print(tf. __ version __) <tf.Operation 'PrintV2' type=PrintV2> and when I ran tf.__version__ it said that I'm running TF 1.14.0' and keras ver 2.2.4-tf' import pandas as pd import numpy as np import tensorf...
[ "Please install the latest tensorflow version using below code.\n!pip install --upgrade tensorflow\nimport tensorflow as tf\ntf.__version__\n\nthen try importing the above mentioned libraries using tensorflow.keras:\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.keras.models import Sequential\...
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0073939042_keras_python_tensorflow.txt
Q: How can I execute multiple commands in cmd in different lines of code in Python? I am trying to run multiple commands in command prompt using Python, but I want to organize them into separete lines of code, so it's easier for me to read and edit later. I started by using: import os os.system('cmd /c "command_1 & ...
How can I execute multiple commands in cmd in different lines of code in Python?
I am trying to run multiple commands in command prompt using Python, but I want to organize them into separete lines of code, so it's easier for me to read and edit later. I started by using: import os os.system('cmd /c "command_1 & command_2 & command_3 & ... & command_n"') But as I developed my program, I began to ...
[ "You can make up the single string on multiple lines:\nos.system('cmd /c \"'\n + 'command_1 & '\n + 'command_2 & '\n + 'command_3 & '\n ...\n + 'command_n\"'\n)\n\nIt's the same string, but formatted differently. Whereas the ''' multi-line string includes the line-breaks in the string, this one doesn't.\n...
[ 0 ]
[]
[]
[ "cmd", "python", "python_os", "subprocess" ]
stackoverflow_0074477733_cmd_python_python_os_subprocess.txt
Q: Why does Coverage.py ignore files with no coverage? I first run nosetests --with-coverage So I should have a .coverage file with all the default settings. Within folder_1, I have file_1.py, file_2.py, and file_3.py When I cd into folder_1 and run coverage report It outputs: It doesn't generate anything for file...
Why does Coverage.py ignore files with no coverage?
I first run nosetests --with-coverage So I should have a .coverage file with all the default settings. Within folder_1, I have file_1.py, file_2.py, and file_3.py When I cd into folder_1 and run coverage report It outputs: It doesn't generate anything for file_3.py! But then when I run: coverage report file_3.py it...
[ "You need to specify a source directory for coverage.py to find files that have never been executed at all. You can use --source=folder_1 on the command line, or [run] source=folder_1 in your .coveragerc file.\n", "I ran into this same scenario yesterday and lost some time trying make Coverage consider the corre...
[ 7, 0 ]
[]
[]
[ "coverage.py", "python" ]
stackoverflow_0043077589_coverage.py_python.txt
Q: QtWdgets how to make a line dependent on the mouse I want to achieve the follwing in QtWidjets. I have a line that moves with the mouse but I want it to move only when clicking (and holding the click) on the actual line; when there is no left click on the mouse nothing should happen. so far I only managed to make ...
QtWdgets how to make a line dependent on the mouse
I want to achieve the follwing in QtWidjets. I have a line that moves with the mouse but I want it to move only when clicking (and holding the click) on the actual line; when there is no left click on the mouse nothing should happen. so far I only managed to make it move automatically with the mouse. I am new to QtWidg...
[ "I used the button_press_event and button_release_event events documented here to get the button state into SnaptoCursor:\nimport numpy as np\nfrom PySide2 import QtWidgets\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas\nfrom matplotlib.figure import Figure\nimport matplotlib.pyplot as plt\n\nclass Sn...
[ 0 ]
[]
[]
[ "events", "python", "qtwidgets" ]
stackoverflow_0074478401_events_python_qtwidgets.txt
Q: Python packaging with setup.py does ignore manifest specifications I'm currently trying to pack a module that uses precompiled *.pyd files from a swig routine. The process for the user is supposed to be: install base library (C, C++); directories linked in the environment variables; here are also the *.pyd files....
Python packaging with setup.py does ignore manifest specifications
I'm currently trying to pack a module that uses precompiled *.pyd files from a swig routine. The process for the user is supposed to be: install base library (C, C++); directories linked in the environment variables; here are also the *.pyd files. get python package; open dir from python environment (be it conda or el...
[ "I made it too complicated. The dir management copying the *.pyd files into a separate directory inside source (src) did not work.\nPutting it directly into src/mypackage worked like a charm. The code for setup.py is:\nfrom pathlib import Path\nfrom setuptools import setup, find_packages, Extension\nimport os\nimpo...
[ 0 ]
[]
[]
[ "pip", "pyd", "python", "setup.py", "setuptools" ]
stackoverflow_0074441268_pip_pyd_python_setup.py_setuptools.txt
Q: python: can't open file '//ML_project.py': [Errno 2] No such file or directory in Docker Here is the content in my Dockerfile. I am trying to containerise a python script (ML_project.py). FROM continuumio/miniconda3:latest COPY ML_Project.py . RUN pip install fxcmpy CMD ["python", "ML_project.py"] My dockerfil...
python: can't open file '//ML_project.py': [Errno 2] No such file or directory in Docker
Here is the content in my Dockerfile. I am trying to containerise a python script (ML_project.py). FROM continuumio/miniconda3:latest COPY ML_Project.py . RUN pip install fxcmpy CMD ["python", "ML_project.py"] My dockerfile and ML_project.py lies within the same folder (fxcm_project) C:\Users\Jack\PycharmProjects\f...
[ "When you docker build, you create a container which embeds all stuffs specified in the Dockerfile.\nIf during the execution a local resource cannot be found, then it is most likely that the ressource is not wothin the container or you passed a wrong location.\nIn your case, you might be looking for the WORKDIR doc...
[ 2 ]
[]
[]
[ "docker", "python" ]
stackoverflow_0074478598_docker_python.txt
Q: How do I create a function that takes a numeric argument and prints “The argument is [argument]” This is the full question I am working on: Create a function called Q6 that takes a numeric argument and prints “The argument is [argument]” (for example: With argument 5, the function would print “The argument is 5”) ...
How do I create a function that takes a numeric argument and prints “The argument is [argument]”
This is the full question I am working on: Create a function called Q6 that takes a numeric argument and prints “The argument is [argument]” (for example: With argument 5, the function would print “The argument is 5”) I got this question right but only because the grading system expected "5" to be the numerical argumen...
[ "Instead of using literal values as you did, you can use the parameter passed to the function and return it in an f-string:\n>>>def Q6(x): \n... return f'The argument is {x}'\n>>>\n>>> Q6(200)\n'The argument is 200'\n>>> Q6(5)\n'The argument is 5'\n\n" ]
[ 0 ]
[]
[]
[ "arguments", "function", "jupyter_notebook", "python" ]
stackoverflow_0074478623_arguments_function_jupyter_notebook_python.txt
Q: Loop failure when connecting to can network For a little project I made a Gui where the user selects a folder to save a log file of the Can bus messages on the bus. When the directory is selected and it is an valid directory the logger instantaneously start to connect to the bus and log all the messages. To keep t...
Loop failure when connecting to can network
For a little project I made a Gui where the user selects a folder to save a log file of the Can bus messages on the bus. When the directory is selected and it is an valid directory the logger instantaneously start to connect to the bus and log all the messages. To keep the Gui from freezing I tried to integrate the win...
[ "It seem that you are reconnecting to the bus over and over again.\nI don't understand the while loop you are using in there because I would expect you only need to connect once.\nYou then probably want to download the information and write it to your file.\nYour example has missing code, so I'm not sure when and h...
[ 0 ]
[]
[]
[ "can_bus", "logging", "python", "tkinter" ]
stackoverflow_0074473289_can_bus_logging_python_tkinter.txt
Q: Python Flask render response body from String instead of template I know that you can render a view from a template file in Flask. rendered = render_template('pdf/template.html', toPerson=message.to_user, fromPerson=message.from_user, message=message.user_message) I'm wondering how you would render from a string ...
Python Flask render response body from String instead of template
I know that you can render a view from a template file in Flask. rendered = render_template('pdf/template.html', toPerson=message.to_user, fromPerson=message.from_user, message=message.user_message) I'm wondering how you would render from a string instead of providing the 'pdf/template.html' section. I've tried the be...
[ "If you want to use a string as a template instead of a loaded file, you can use the from_string function of the existing Jinja environment.\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n templ_str = '''<h1>Hello {{ name }}</h1>'''\n templ = app.jinja_env.from_string(temp...
[ 0 ]
[]
[]
[ "flask", "jinja2", "python" ]
stackoverflow_0074473696_flask_jinja2_python.txt
Q: How to use variables from an environment file Python? I have a project that I'm working on in which I need to store sensitive information into an environment file as variables that can later be called in my code. I'm having issues with it working and so I've dumbed it down to the simplest test I can think of. I ha...
How to use variables from an environment file Python?
I have a project that I'm working on in which I need to store sensitive information into an environment file as variables that can later be called in my code. I'm having issues with it working and so I've dumbed it down to the simplest test I can think of. I have create a test.py file and a var.env file within the same...
[ "You need to call load_dotenv first.\n#test.py\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv('var.env')\n\nprint(os.getenv('PROJECT'))\n\n" ]
[ 2 ]
[]
[]
[ "environment_variables", "python", "python_dotenv" ]
stackoverflow_0074478643_environment_variables_python_python_dotenv.txt
Q: NamedTuple is shared across variables from typing import NamedTuple, List, Set, Tuple, Dict class EmbeddingInfoStruct(NamedTuple): emb_names : list[str] =[] idx_in_data: list[int] =[] emb_dim: list[int] =[] info1 =EmbeddingInfoStruct() info1.emb_names.append("name1") info2=EmbeddingInfoStruct() pri...
NamedTuple is shared across variables
from typing import NamedTuple, List, Set, Tuple, Dict class EmbeddingInfoStruct(NamedTuple): emb_names : list[str] =[] idx_in_data: list[int] =[] emb_dim: list[int] =[] info1 =EmbeddingInfoStruct() info1.emb_names.append("name1") info2=EmbeddingInfoStruct() print("info1 address = ", id(info1), ", info2 ...
[ "I think you mistook NamedTuple from the typing module, describing the type of a named tuple for type hinting purpose, and the named tuple you can get from namedtuple() from the collection package (see the collection documentation).\nHere, you are actually changing class member of your EmbeddingInfoStruct, thus the...
[ 1, 1 ]
[]
[]
[ "namedtuple", "python" ]
stackoverflow_0074478576_namedtuple_python.txt
Q: Trying to edit a row of a csv file in python, but for some reason it also adds blank rows when run? I'm trying to make it so you can edit a single client's details in a csv file, and while the code I wrote runs it for some reason adds a gap in between each client as well as changing the client - i'd really appreci...
Trying to edit a row of a csv file in python, but for some reason it also adds blank rows when run?
I'm trying to make it so you can edit a single client's details in a csv file, and while the code I wrote runs it for some reason adds a gap in between each client as well as changing the client - i'd really appreciate if someone could tell me why this is happening. Here's an excerpt of my csv: first_name,last_name,tit...
[ "I believe it is adding an extra carriage return when writing. Try changing this line:\nwith open(\"mock_data.csv\", \"w+\") as file:\nto\nwith open(\"mock_data.csv\", newline= \"\", \"w+\") as file:\n" ]
[ 2 ]
[]
[]
[ "csv", "list", "python" ]
stackoverflow_0074478689_csv_list_python.txt
Q: Reading contents of a gzip file from a AWS S3 in Python I am trying to read some logs from a Hadoop process that I run in AWS. The logs are stored in an S3 folder and have the following path. bucketname = name key = y/z/stderr.gz Here Y is the cluster id and z is a folder name. Both of these act as folders(objects...
Reading contents of a gzip file from a AWS S3 in Python
I am trying to read some logs from a Hadoop process that I run in AWS. The logs are stored in an S3 folder and have the following path. bucketname = name key = y/z/stderr.gz Here Y is the cluster id and z is a folder name. Both of these act as folders(objects) in AWS. So the full path is like x/y/z/stderr.gz. Now I wan...
[ "This is old, but you no longer need the BytesIO object in the middle of it (at least on my boto3==1.9.223 and python3.7) \nimport boto3\nimport gzip\n\ns3 = boto3.resource(\"s3\")\nobj = s3.Object(\"YOUR_BUCKET_NAME\", \"path/to/your_key.gz\")\nwith gzip.GzipFile(fileobj=obj.get()[\"Body\"]) as gzipfile:\n cont...
[ 39, 20, 10, 1, 0, 0, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "python" ]
stackoverflow_0041161006_amazon_s3_amazon_web_services_boto3_python.txt
Q: Class object attributes to list in a one liner I have a list of class objects, e.g.: child1 = Child(Name = 'Max', height = 5.1, weight = 100) child2 = Child(Name = 'Mimi, height = 4.1, weight = 80) my_object_list = [child1, child2] Is there a way to create a new list dynamically with one similiar attribute of eac...
Class object attributes to list in a one liner
I have a list of class objects, e.g.: child1 = Child(Name = 'Max', height = 5.1, weight = 100) child2 = Child(Name = 'Mimi, height = 4.1, weight = 80) my_object_list = [child1, child2] Is there a way to create a new list dynamically with one similiar attribute of each object as a one liner? I know how to do it in a fo...
[ "this kind of things is made easy by the comprehension syntax in Python;\nmy_new_list = [item.name for item in old_list]\nNow, if one does not know at coding-time which attribute should be retrieved, the getattr built-in can be used to retrieve an attribute by name passed as a string:\nattr = 'name'\nmy_new_list = ...
[ 0 ]
[]
[]
[ "dynamic", "list", "python" ]
stackoverflow_0074478676_dynamic_list_python.txt
Q: How to split strings with multiple delimiters while keep the delimiters | python For example, I have a string section 213(d)-456(c) How can I split it to get a list of strings: ['section', '213', '(', 'd', ')', '-', '456', '(', 'c', ')']. Thank you! A: You can do so using Regex. import re text = "section 213(d)-...
How to split strings with multiple delimiters while keep the delimiters | python
For example, I have a string section 213(d)-456(c) How can I split it to get a list of strings: ['section', '213', '(', 'd', ')', '-', '456', '(', 'c', ')']. Thank you!
[ "You can do so using Regex.\nimport re\ntext = \"section 213(d)-456(c)\"\noutput = re.split(\"(\\W)\", text)\n\nOutput: ['section', ' ', '213', '(', 'd', ')', '', '-', '456', '(', 'c', ')', '']\nHere \\W is for non-word character!\n", "You can come close with\nre.split(r'([-\\s()])', 'section 213(d)-456(c)')\n\nW...
[ 2, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0074478758_python_split_string.txt
Q: I want to validaton condition for two fields Pydantic The task is to make a validator for two dependent fields. If MCC is not empty, then you need to check that OUTSIDE is passed in the type field. And vice versa. If MCC is empty, then INSIDE should be passed in the type field. I wrote this code, but it doesn't wo...
I want to validaton condition for two fields Pydantic
The task is to make a validator for two dependent fields. If MCC is not empty, then you need to check that OUTSIDE is passed in the type field. And vice versa. If MCC is empty, then INSIDE should be passed in the type field. I wrote this code, but it doesn't work. Can someone tell me the best way to do this import json...
[ "I think you are looking for this, the validator on MCC will have to deal with both your cases.\n @validator(\"MCC\")\n def check_passwords_match(cls, v, values):\n if \"type\" not in values:\n raise ValueError(\"TYPE VALIDATION FAILED\")\n if (v is not None and values[\"type\"] != \"...
[ 0 ]
[]
[]
[ "pydantic", "python", "validation" ]
stackoverflow_0074475176_pydantic_python_validation.txt
Q: Selecting columns based on characters in column names I have a pandas dataframe with columns names as ['INV01_M1_I', 'INV01_M1_V', 'INV01_M2_I', 'INV01_M2_V', 'INV02_M1_I', 'INV02_M1_V', 'INV02_M2_I', 'INV02_M2_V'....] AND SO ON. I want to sum those columns which have same 'INV_no_here' and the last character i.e....
Selecting columns based on characters in column names
I have a pandas dataframe with columns names as ['INV01_M1_I', 'INV01_M1_V', 'INV01_M2_I', 'INV01_M2_V', 'INV02_M1_I', 'INV02_M1_V', 'INV02_M2_I', 'INV02_M2_V'....] AND SO ON. I want to sum those columns which have same 'INV_no_here' and the last character i.e. I or V. That is sum INV01_M1_I+INVO1_M2_I in one column an...
[ "here is one way :\nfor cols in df.columns.str.split('_'): \n if not cols[0] +'_'+ cols[2] in df.columns:\n df[cols[0] +'_'+ cols[2]] = df[[col for col in df.columns if col.startswith(cols[0]) and col.endswith(cols[2])]].sum(axis=1)\n\noutput :\n>>\n INV01_M1_I INV01_M1_V INV01_M2_I ... INV01_V ...
[ 2 ]
[]
[]
[ "character", "data_science", "dataframe", "pandas", "python" ]
stackoverflow_0074478602_character_data_science_dataframe_pandas_python.txt
Q: How to use redirect() properly with parameters? Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. return redirect('post_detail', slug=post.slug) This is my comment view: def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slu...
How to use redirect() properly with parameters?
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. return redirect('post_detail', slug=post.slug) This is my comment view: def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__...
[ "The post_detail view requires the four url params and you are only passing one param, so kindly pass all the params as:\nreturn redirect('blog:post_detail',year=year, month=month, day=day, slug=post.slug)\n\nFor redirecting in the same page simply use:\nreturn HttpResponseRedirect(request.path_info)\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_forms", "django_urls", "django_views", "python" ]
stackoverflow_0074478825_django_django_forms_django_urls_django_views_python.txt
Q: Trying to filter in dask.read_parquet tries to compare NoneType and str I have a project where I pass the following load_args to read_parquet: filters = {'filters': [('itemId', '=', '9403cfde-7fe5-4c9c-916c-41ff0b595c5c')]} According to the documentation, a List[Tuple] like this should be accepted and I should ge...
Trying to filter in dask.read_parquet tries to compare NoneType and str
I have a project where I pass the following load_args to read_parquet: filters = {'filters': [('itemId', '=', '9403cfde-7fe5-4c9c-916c-41ff0b595c5c')]} According to the documentation, a List[Tuple] like this should be accepted and I should get all partitions which match the predicate (or equivalently, filter out those...
[ "The problem probably arises when min and max haven't been redefined before, so they still refer to the built-in functions that compute the minimum and maximum of two numbers, which obviously can't be compared with a string. Try using different name for these variables (as a rule of thumb, avoid too generic variabl...
[ 0 ]
[]
[]
[ "dask", "parquet", "python" ]
stackoverflow_0074478839_dask_parquet_python.txt
Q: Can't add standard metrics for multioutput model I have classification + detection model of cats and dogs based on MobileNet v2. It trains well, but now I want to add metrics for it and I can't do that. Here is the main part of code: def localization_loss(y_true, yhat): delta_coord = tf.reduce_sum(...
Can't add standard metrics for multioutput model
I have classification + detection model of cats and dogs based on MobileNet v2. It trains well, but now I want to add metrics for it and I can't do that. Here is the main part of code: def localization_loss(y_true, yhat): delta_coord = tf.reduce_sum(tf.square(y_true[:,:2] - yhat[:,:2])) h_...
[ "As I answered here, correct metrics are: BinaryAccuracy and custom MeanIoU (default MeanIoU is not applicable to bboxes regression as I understood). Working code snippet is in the first link.\n" ]
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0074460685_keras_python_tensorflow_tensorflow2.0.txt
Q: Print String in Python I tried running this basic python script to print something, and it doesn't seem to be executing properly. name = "Tyler"; print{name}; I am getting this error: File "C:\Users\tyler\main.py", line 2 print{name}; ^^^^^^^^^^^ SyntaxError: Missing parentheses in call to 'print'. Did yo...
Print String in Python
I tried running this basic python script to print something, and it doesn't seem to be executing properly. name = "Tyler"; print{name}; I am getting this error: File "C:\Users\tyler\main.py", line 2 print{name}; ^^^^^^^^^^^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)? I tried ...
[ "You don't need semicolons in Python\nThe issue was the use of curly braces. Call your variable name with print() like this:\nname = \"Tyler\"\nprint(name)\n\n" ]
[ 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074478880_python_string.txt
Q: Python Keras: Pass y/target to custom activation function I would like to pass my Python Keras model y (target/response/etc) to a custom activation. My custom activation function which limits the fit range to be within lower and upper is: def activation_range(x, lower=-1, upper=1) : """ Custom activation ...
Python Keras: Pass y/target to custom activation function
I would like to pass my Python Keras model y (target/response/etc) to a custom activation. My custom activation function which limits the fit range to be within lower and upper is: def activation_range(x, lower=-1, upper=1) : """ Custom activation layer to restrict layer output range """ x02 = backend...
[ "You can. Just use functional API in combination with subclassed layers instead of the basic Sequential which only supports single-input single-output models. Note that this requires you to pass (x,y) as the x argument to model.fit and also as the input during inference.\nimport tensorflow as tf\nimport numpy as np...
[ 1 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074467258_keras_python_tensorflow.txt
Q: Python NameError: name is not defined (variable names already defined but I get error) I am trying to run the following codes. I get the error NameError: name 'XXXXX' is not defined. if __name__ == '__main__': land_dir = "C:/Users/mb/Documents/Land" MOD_dir = "C:/Users/mb/Documents/MOD" def search_la...
Python NameError: name is not defined (variable names already defined but I get error)
I am trying to run the following codes. I get the error NameError: name 'XXXXX' is not defined. if __name__ == '__main__': land_dir = "C:/Users/mb/Documents/Land" MOD_dir = "C:/Users/mb/Documents/MOD" def search_land_name(path): """to get the land list file name""" output_list =[] pt=os.listd...
[ "LD_B3_name is locally defined inside your function search_landsat_name.\nThat means that the variable only exists inside your function.\nIf you want to access the variable outside of search_landsat_name you can simply return the variable:\ndef search_landsat_name(path):\n # some code\n return LD_B3_name\n\nL...
[ 0 ]
[]
[]
[ "arrays", "list", "python", "python_3.x" ]
stackoverflow_0074478937_arrays_list_python_python_3.x.txt
Q: Match key word in list of strings to variables I am reading all files from a directory and storing the file paths of those in that directory in a list using files = [os.path.abspath(x) for x in os.listdir(r"my directory")] Each file in a unique template so the resulting list is something like [C:\Users\....\Templ...
Match key word in list of strings to variables
I am reading all files from a directory and storing the file paths of those in that directory in a list using files = [os.path.abspath(x) for x in os.listdir(r"my directory")] Each file in a unique template so the resulting list is something like [C:\Users\....\Template_Coversheet.xlsx C:\Users\....\Template_Blanks.xl...
[ "First, if this depends only on the file name, you can use that instead of the whole path. You can use regular expressions if the patterns are complex. But in your case and if it's just Template_TEMPLATENAME.xlsx you can create a dictionary and map TEMPLATENAME to the full name. The code would be something like thi...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074478971_python.txt
Q: Python - Before adding text to a file check it doesn't already exist - How? I need to add device names and device IP addresses to the bottom of a text file each time a new device goes live so I can connect via name instead of IP. My problem is how to check the device I'm adding doesn't already exist, if it does ex...
Python - Before adding text to a file check it doesn't already exist - How?
I need to add device names and device IP addresses to the bottom of a text file each time a new device goes live so I can connect via name instead of IP. My problem is how to check the device I'm adding doesn't already exist, if it does exist then the logic should be to ignore, otherwise it should be added to the botto...
[ "It's really simple - You need to analize the data inside file and check it.\nI suggest you to write data in csv format e.g. row: 'device_name, device_ip\\n' - this will facilitate data analysis.\nYou can also sort your device list by name or ip and optimize searches or use pandas etc.\nexample file content:\ndevic...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074478537_python.txt
Q: Random.choice to return and fill null values equally I'm trying to fill all the null values with random choices made from a list using: new_df = new_df.fillna(new_df.loc[new_df['rest_type'] == 'Cafe' ,'dish_liked'].fillna(random.choice(top5C))) Here is the list, for example : top5C = ['Pasta', 'Waffles', 'Mocktai...
Random.choice to return and fill null values equally
I'm trying to fill all the null values with random choices made from a list using: new_df = new_df.fillna(new_df.loc[new_df['rest_type'] == 'Cafe' ,'dish_liked'].fillna(random.choice(top5C))) Here is the list, for example : top5C = ['Pasta', 'Waffles', 'Mocktails', 'Coffee', 'BrownieChocolate', 'Burgers'] The prob...
[ "Edited: I had entirely neglected the fact that the column containing NaN is of type string. Answer updated to use pd.isnull instead of np.isnan\nHow about this, where I use the pandas map method together with some numpy functions and your random.choice to infill only where we have NaN:\nimport numpy as np\nimport ...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074474573_numpy_pandas_python.txt