content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How can I generate a financial summary using pandas dataframes?
I'd like to create a table from a data frame with subtotals per business, totals per business type, and columns summing multiple value columns. Long term is to create a selection tool based on the ingested Excel sheet for whichever month's summary I b... | How can I generate a financial summary using pandas dataframes? | I'd like to create a table from a data frame with subtotals per business, totals per business type, and columns summing multiple value columns. Long term is to create a selection tool based on the ingested Excel sheet for whichever month's summary I bring in to compare month summaries (e.g. did minerals item 26 from BA... | [
"You should try to use the group_by method for this. Group_by allows for several grouping options. I have attached a link to the documentation on the method. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html\n"
] | [
0
] | [] | [] | [
"dataframe",
"excel",
"pandas",
"python",
"summary"
] | stackoverflow_0074311293_dataframe_excel_pandas_python_summary.txt |
Q:
Undistort image containing planar object of known dimensions using openCV python
I have the following image extracted from a video:
It is a field hockey pitch with standard dimensions (91.4m x 55m). I can even map all lines intersections if necessary.
The image is distorded. I'd like to undistord it using openCV.... | Undistort image containing planar object of known dimensions using openCV python | I have the following image extracted from a video:
It is a field hockey pitch with standard dimensions (91.4m x 55m). I can even map all lines intersections if necessary.
The image is distorded. I'd like to undistord it using openCV.
I thought something similar to cv2.FindChessBoardCorners() followed by CalibrateCamer... | [
"I guess there are 2 possible directions.\n1. Do Camera Calibration\nChessboard pattern is often used for calibration, but of course other patterns may be used.\nWhat we need is constraints that we can use for optimization.\nTherefore, the geometric knowledges of the pitch you have also may be able to used.\ne.g. s... | [
0
] | [] | [] | [
"camera_calibration",
"computer_vision",
"opencv",
"python"
] | stackoverflow_0074262965_camera_calibration_computer_vision_opencv_python.txt |
Q:
What is a good way to predict pseudo random numbers with neural networks?
Today I tried to see if a neural network could predict the next random number generated from a sequence of 20 previous random numbers. However, when I actually predicted using the model it simply returned the most common number. I'm very new... | What is a good way to predict pseudo random numbers with neural networks? | Today I tried to see if a neural network could predict the next random number generated from a sequence of 20 previous random numbers. However, when I actually predicted using the model it simply returned the most common number. I'm very new to keras and tensorflow so I have no idea how I could approach this problem, o... | [
"I don't think you can predict numbers from Python's random module based on past outputs. The random module uses a Mersenne Twister that repeats only after 2^19937-1 numbers. A neural network won't be able to predict the following numbers based on previous numbers.\nThe reason your neural network is returning the m... | [
2
] | [] | [] | [
"artificial_intelligence",
"keras",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0074311106_artificial_intelligence_keras_neural_network_python_tensorflow.txt |
Q:
Stable version for Graph Gym execution
My trouble is happened when running a single experiment from:
https://pytorch-geometric.readthedocs.io/en/latest/notes/graphgym.html
(graphenv) D:\graph\pytorch_geometric\graphgym>bash run_single.sh
run_single.sh: line 2: $'\r': command not found
run_single.sh: line 4: python... | Stable version for Graph Gym execution | My trouble is happened when running a single experiment from:
https://pytorch-geometric.readthedocs.io/en/latest/notes/graphgym.html
(graphenv) D:\graph\pytorch_geometric\graphgym>bash run_single.sh
run_single.sh: line 2: $'\r': command not found
run_single.sh: line 4: python: command not found
run_single.sh: line 5: p... | [
"For those who had the same problem. WSL2 is solution.\nHereby the link:\nhttps://learn.microsoft.com/en-us/windows/wsl/install\nLinux is better solution for graphgym experimental.\n"
] | [
0
] | [] | [] | [
"deep_learning",
"geometry",
"graph",
"python",
"pytorch"
] | stackoverflow_0073591701_deep_learning_geometry_graph_python_pytorch.txt |
Q:
asyncio.run() seems to be blocking the other process i started
This code is supposed to control a servo from stdin
import asyncio
import sys
import threading
from multiprocessing import Process
async def connect_stdin_stdout():
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader()
protocol =... | asyncio.run() seems to be blocking the other process i started | This code is supposed to control a servo from stdin
import asyncio
import sys
import threading
from multiprocessing import Process
async def connect_stdin_stdout():
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader()
protocol = asyncio.StreamReaderProtocol(reader)
await loop.connect_read_pi... | [
"So, as I said in comment, you are not sharing servo0ang. You have two processes. Each of them has its own variables. They have the same name, and the same initial value, as in a fork in other languages. Because the new process starts as a copy of the main one. But they are just 2 different python running, with alm... | [
0
] | [] | [] | [
"python",
"python_asyncio",
"python_multiprocessing",
"raspberry_pi",
"servo"
] | stackoverflow_0074310756_python_python_asyncio_python_multiprocessing_raspberry_pi_servo.txt |
Q:
How to ask the user which students grade they want to look up. And print that student’s grade from the input listed
The code I wrote is directly below and my question is under it.
student= {}
for i in range(5):
name = input("Add students name: ")
grade = input("Add students grade: ")
student[name] = gr... | How to ask the user which students grade they want to look up. And print that student’s grade from the input listed | The code I wrote is directly below and my question is under it.
student= {}
for i in range(5):
name = input("Add students name: ")
grade = input("Add students grade: ")
student[name] = grade
print(student)
My question would be easier to show you and I would like the output to be what is listed below howeve... | [
"Check the code for this problem below.\nstudent= {}\nfor i in range(3):\n name = input(\"Add students name: \")\n grade = input(\"Add students grade: \")\n student[name] = grade\nlookup_name = input(\"Type a name to lookup in the dictionary: \")\ntry:\n lookup_grade = student[lookup_name]\n print(lo... | [
0
] | [] | [] | [
"dictionary",
"for_loop",
"python",
"user_input"
] | stackoverflow_0074311048_dictionary_for_loop_python_user_input.txt |
Q:
How do you filter rows in a dataframe containing values in another dataframe?
I have a column with in a dataframe that I want to filter the dataframe with based on which rows contain values that are in another dataframe.
In other words, I have a blacklist of keywords that I want to make sure are not in a dataframe... | How do you filter rows in a dataframe containing values in another dataframe? | I have a column with in a dataframe that I want to filter the dataframe with based on which rows contain values that are in another dataframe.
In other words, I have a blacklist of keywords that I want to make sure are not in a dataframe.
| [
"To select rows whose column value is in an iterable, some_values, use isin:\ndf.loc[df['column_name'].isin(some_values)]\n\nYou can convert your whitelist of keywords to a set, and use the solution above. A similar question that I refer to is here.\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074311504_pandas_python.txt |
Q:
Python package not found - Alpaca
I followed the guide from the official Alpaca-py Documentation - https://alpaca.markets/docs/python-sdk/getting_started.html#introduction
I ran: pip install alpaca-py
Then I created this file called alpaca.py:
from alpaca.data.historical import StockHistoricalDataClient
from alpac... | Python package not found - Alpaca | I followed the guide from the official Alpaca-py Documentation - https://alpaca.markets/docs/python-sdk/getting_started.html#introduction
I ran: pip install alpaca-py
Then I created this file called alpaca.py:
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest... | [
"It looks like it was a naming conflict with my file name being alpaca.py.\nThis post helped me: Python 'No module named' error; 'package' is not a package\n"
] | [
1
] | [] | [] | [
"alpaca",
"pip",
"python",
"python_3.x"
] | stackoverflow_0074311076_alpaca_pip_python_python_3.x.txt |
Q:
Check and store in dict number of repeating substrings and characters of a string python
I'm trying to find the number of substrings and characters of a given string comparing with a list and returning them in a dict, it doesn't matter the order, like the example:
string = "Lorem ipsum dolor sit amet, consectetur ... | Check and store in dict number of repeating substrings and characters of a string python | I'm trying to find the number of substrings and characters of a given string comparing with a list and returning them in a dict, it doesn't matter the order, like the example:
string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
list = ["a... | [
"Use .count() to count substring in the string and dict comprehension to make the dict\ntxt = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua\"\nlst = [\"a\", \"em\", \"i\", \"el\"]\n\nd = {k: txt.count(k) for k in lst}\nprint(d)\n\n{'a': ... | [
1
] | [] | [] | [
"algorithm",
"data_structures",
"python",
"string"
] | stackoverflow_0074311533_algorithm_data_structures_python_string.txt |
Q:
How to replace a string with the user input in its designated spot - hangman
displayed_word = ["-"*length]
#how do you write the guess in the designated spot in hangman?? and to replace the "-" ]
designated_spot = s.find(guess)
how_many = s.count(guess)
print(f"the word had {how_many} of y... | How to replace a string with the user input in its designated spot - hangman | displayed_word = ["-"*length]
#how do you write the guess in the designated spot in hangman?? and to replace the "-" ]
designated_spot = s.find(guess)
how_many = s.count(guess)
print(f"the word had {how_many} of your guess in it")
print(designated_spot)
newletter = s.replace(gue... | [
"I think what you're looking for is something like this:\nword = \"apple\" # example output from your list\ndisplayed_word = \"-\"*len(word) # make a string the same length of the word that shows guessed letters\n\ndef make_guess(s: str, guess: str, displayed_word: str) -> str:\n # convert the displayed word... | [
0
] | [] | [] | [
"python",
"replace"
] | stackoverflow_0074310646_python_replace.txt |
Q:
Python - Get max value of a column then print two different columns that relate to that max value
Sorry if the title is a bit incoherent.
This is all done in pandas and basically I have 20 columns but all I need for what I'm trying to do is the following three:
Area Month DetectedSpeed
Wendly 1 ... | Python - Get max value of a column then print two different columns that relate to that max value | Sorry if the title is a bit incoherent.
This is all done in pandas and basically I have 20 columns but all I need for what I'm trying to do is the following three:
Area Month DetectedSpeed
Wendly 1 15
Wendly 1 35
Wendly 2 18
Sarall 6 23
... | [
"https://pandas.pydata.org/docs/reference/api/pandas.Series.idxmax.html?highlight=idxmax#pandas.Series.idxmax\n\nReturn the row label of the maximum value.\nIf multiple values equal the maximum, the first row label with that\nvalue is returned.\n\nrow_with_max_DetectedSpeed = df.loc[df[\"DetectedSpeed\"].idxmax()]\... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074311581_dataframe_pandas_python_python_3.x.txt |
Q:
How does the below code produce more than 10 outputs as the slice operation must be restricting it to 10 values?
(autos["date_crawled"]
.str[:10]
.value_counts(normalize=True, dropna=False)
.sort_index()
)
here we are working with Ebay sales data(https://www.kaggle.com/datasets/viv... | How does the below code produce more than 10 outputs as the slice operation must be restricting it to 10 values? | (autos["date_crawled"]
.str[:10]
.value_counts(normalize=True, dropna=False)
.sort_index()
)
here we are working with Ebay sales data(https://www.kaggle.com/datasets/viveksinghgulia/autoscsv)
Running the above code gives the followiing output
2016-03-05 0.025327
2016-03-06 0.01404... | [
".str[:10] is not slicing the rows. It just takes the first 10 characters of the string in each row. So .str[:10] of a value like '2016-03-05' is just '2016-03-05' . If you did .str[:4] it would be '2016'.\nTo limit the number of rows, use .head(10) or .iloc[:10]\n"
] | [
1
] | [] | [] | [
"data_analysis",
"pandas",
"python"
] | stackoverflow_0074309075_data_analysis_pandas_python.txt |
Q:
Replace method in Pandas
How do I replace multiple column names with different values? Ideally I want to remove certain characters in column names and replace others.
I have to run my jupyter notebook twice in order to get this code to work. Does anyone know the reason for this? Also, how would I go about simplify... | Replace method in Pandas | How do I replace multiple column names with different values? Ideally I want to remove certain characters in column names and replace others.
I have to run my jupyter notebook twice in order to get this code to work. Does anyone know the reason for this? Also, how would I go about simplifying this code (I am aware of j... | [
"I can't comment due to 'points' but firstly - avoid inplace - https://github.com/pandas-dev/pandas/issues/16529#issuecomment-443763553\nFor the replacement of multiple values in multiple columns you can use:\ndf = df.rename(columns = { ... }).rename(columns = lambda x: x.lower())\n\nWhich will rename using the giv... | [
2,
0,
0
] | [] | [] | [
"data_science",
"pandas",
"python",
"replace"
] | stackoverflow_0074310659_data_science_pandas_python_replace.txt |
Q:
Python Visual Studio code import Syntax problems // color
For some reasons my Visual Studio code doesn´t show the color for the imported library.
In the attached file you see what I mean.
I tried already:
Deinstalled vsc and reinstalled it again
deleted the settings.json in (%APPDATA%\Code\User)
deinstalled all e... | Python Visual Studio code import Syntax problems // color | For some reasons my Visual Studio code doesn´t show the color for the imported library.
In the attached file you see what I mean.
I tried already:
Deinstalled vsc and reinstalled it again
deleted the settings.json in (%APPDATA%\Code\User)
deinstalled all extensions and reinstalled it again
If you know how I can fix i... | [
"This is an issue with the newest update of VSCode. Here is a bug report showing the same problems. Changing linters seems not to fix the issue at the moment. Here are the patch notes as well, even though they aren't helpful here. I suggest downgrading VSCode if you want to fix this issue, which may require you to ... | [
1,
0
] | [] | [] | [
"colors",
"python",
"syntax",
"visual_studio_code"
] | stackoverflow_0067927982_colors_python_syntax_visual_studio_code.txt |
Q:
Python: Trouble running any additional queries on Geopy output?
have encountered the following - Struggling to wrap my head around it.
Have some data that looks like this:
I've written the following Python that works out the distance between the 2 sets of coordinates:
from geopy import distance
# Calculate dista... | Python: Trouble running any additional queries on Geopy output? | have encountered the following - Struggling to wrap my head around it.
Have some data that looks like this:
I've written the following Python that works out the distance between the 2 sets of coordinates:
from geopy import distance
# Calculate distance between 2 sets of coordinates
# Result is float64
data['Distance... | [
"#Create sample data\ndat = [[43.11944,-75.2932, 40.12029, -74.2935],[40.83488,-75.8662, 40.83377, -73.8633],[40.81212,-73.9165, 40.80491, -73.9112],\n[43.07367,-78.9906, 43.07523, -78.9906],\n[41.30884,-74.0253, 40.30746, -74.028]]\ndata = pd.DataFrame(dat, columns=['Start_lat', 'Start_Lng', 'End_Lat', 'End_Lng'])... | [
1
] | [] | [] | [
"coordinates",
"geopy",
"python"
] | stackoverflow_0074311491_coordinates_geopy_python.txt |
Q:
Python Win32: error when using SelectObject with HBITMAP
I'm trying to select a DC with a HBITMAP, but I seem to get an error. I'm using Pywin32 for Win32 functions as well as ctypes for the VirtualAlloc function.
data = VirtualAlloc(0, (x*y+x)*512,MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)
hbm = CreateBitmap(x,y,... | Python Win32: error when using SelectObject with HBITMAP | I'm trying to select a DC with a HBITMAP, but I seem to get an error. I'm using Pywin32 for Win32 functions as well as ctypes for the VirtualAlloc function.
data = VirtualAlloc(0, (x*y+x)*512,MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)
hbm = CreateBitmap(x,y,1,32,data)
SelectObject(hdcdc, hbm)
Here's the error that occ... | [
"You should invoke CreateDCFromHandle to create a DC object then use it's SelectObject method.\ndc_hwnd = win32gui.GetWindowDC(desk_hwnd)\ndesk_dc = win32ui.CreateDCFromHandle(dc_hwnd)\npen = win32ui.CreatePen(win32con.PS_SOLID, 10, win32api.RGB(255, 0, 0))\nold_pen = desk_dc.SelectObject(pen)\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"pywin32",
"winapi",
"windows"
] | stackoverflow_0069618458_python_python_3.x_pywin32_winapi_windows.txt |
Q:
Can't transform 2D array to 1D in numpy
So I wanto to multiply a vector (1D array) by a rotation matrix (2D array) but the resulted vector turns out 2D. flatten or ravel for some reason still return a 2D array.
import numpy as np
a = np.array([5, 5, 0])
Rx = np.matrix([[1, 0, 0],
[0, 1, 0],
... | Can't transform 2D array to 1D in numpy | So I wanto to multiply a vector (1D array) by a rotation matrix (2D array) but the resulted vector turns out 2D. flatten or ravel for some reason still return a 2D array.
import numpy as np
a = np.array([5, 5, 0])
Rx = np.matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
b = a * Rx
b = b.flatt... | [
"import numpy as np\n\na = np.array([5, 5, 0])\n\nRx = np.matrix([[1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]])\nb = a * Rx\nb = np.array(b).flatten()\n\nprint(b)\n\nOtherwise you can convert matrix to array and can use flatten for it as above.\n",
"If you have to use np.matrix use b =np.arr... | [
0,
0
] | [] | [] | [
"arrays",
"flatten",
"numpy",
"python"
] | stackoverflow_0074002697_arrays_flatten_numpy_python.txt |
Q:
Building error for Kivy-ios. Failing to download openssl
Trying to build my first kivy app for ios. Following this video: https://www.youtube.com/watch?v=6gLGyrlgqCU
When I run toolchain build kivy it gets stuck downloading and openssl link. I don't know anything about ssl. Any help is greatly appreciated.
i also ... | Building error for Kivy-ios. Failing to download openssl | Trying to build my first kivy app for ios. Following this video: https://www.youtube.com/watch?v=6gLGyrlgqCU
When I run toolchain build kivy it gets stuck downloading and openssl link. I don't know anything about ssl. Any help is greatly appreciated.
i also tried toolchain build openssl but that had the same error resu... | [
"I found the issue on my own. I needed to install Certificates.command from python's application folder. \n"
] | [
0
] | [] | [] | [
"kivy",
"openssl",
"python",
"toolchain"
] | stackoverflow_0074310076_kivy_openssl_python_toolchain.txt |
Q:
how to extract specific sentence in pandas dataframe?
I'm trying to extract specific sentence in string column and copy&paste it to Nan rows in another column
here is the detail:
`
KEY WARNSIGN_DTL EVENT_DTL
55116 77981 Nan 1. Name: Johnson 2. Date: 09 June 2018 3. Place to be fo... | how to extract specific sentence in pandas dataframe? | I'm trying to extract specific sentence in string column and copy&paste it to Nan rows in another column
here is the detail:
`
KEY WARNSIGN_DTL EVENT_DTL
55116 77981 Nan 1. Name: Johnson 2. Date: 09 June 2018 3. Place to be found: Wall street 4. Found in his apartment 5. Method: overd... | [
"Use the below snippet:\nimport re\n\ndef extract_my_string(my_str):\n \"\"\"\n Func that uses regex to extract content between 3. and 5.\n \"\"\"\n result = re.search('3.(.*)5.', my_str)\n return f'3.{result.group(1)}'\n \n\n\ndf['WARNSIGN_DTL'] = df['EVENT_DTL'].apply(lambda x: extract_my_string(x)) \n\n",
... | [
0,
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074311595_dataframe_python.txt |
Q:
`alembic revision --autogenerate` produces redundant foreign key migrations
Software versions: alembic 1.0.5, SQLAlchemy 1.2.14, MySQL 5.7, Python 3.6.7
I am trying to use alembic to keep a MySQL database schema and the Python ORM representation in step.
The issue I am seeing is that the migrations always have red... | `alembic revision --autogenerate` produces redundant foreign key migrations | Software versions: alembic 1.0.5, SQLAlchemy 1.2.14, MySQL 5.7, Python 3.6.7
I am trying to use alembic to keep a MySQL database schema and the Python ORM representation in step.
The issue I am seeing is that the migrations always have redundant drop and create commands for foreign keys. It seems that autogenerate is ... | [
"So, although this SO question is old and got me the Tumbleweed badge, I think it would be nice to answer it and close it off. I got a good answer from the package maintainer, Mike Bayer, on GitHub:\n\nOK, so here is the thing. you are connecting with \"test_fktdb\" in your database URL as the default schema. whic... | [
2,
1
] | [] | [] | [
"alembic",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0053523529_alembic_mysql_python_sqlalchemy.txt |
Q:
Python GEKKO Unexpected Behavior with Constraints
I've been playing around with GEKKO for solving flow optimizations and I have come across behavior that is confusing me.
Context:
Sources --> [mixing and delivery] --> Sinks
I have multiple sources (where my flow is coming from), and multiple sinks (where my flow g... | Python GEKKO Unexpected Behavior with Constraints | I've been playing around with GEKKO for solving flow optimizations and I have come across behavior that is confusing me.
Context:
Sources --> [mixing and delivery] --> Sinks
I have multiple sources (where my flow is coming from), and multiple sinks (where my flow goes to). For a given source (e.g., SOURCE_1), the total... | [
"This same improvement occurs with complementary constraints for conditional statements when using s1*s2<=0 (easier to solve) versus s1*s2==0 (harder to solve).\n\n\nFrom the research papers I've seen, the justification is that the solver has more room to search to find the optimal solution even if it always ends u... | [
1
] | [] | [] | [
"gekko",
"mathematical_optimization",
"python"
] | stackoverflow_0074308167_gekko_mathematical_optimization_python.txt |
Q:
Python: calling __init__ of parent class - Error fix
I am programming a basic python game. I am attempting to make it dynamic and easy to add creatures to. Currently I am running into the issue of calling the init of the parent class.
My code:
from main import *
class Entity:
def __init__(self,x,y,image):
... | Python: calling __init__ of parent class - Error fix | I am programming a basic python game. I am attempting to make it dynamic and easy to add creatures to. Currently I am running into the issue of calling the init of the parent class.
My code:
from main import *
class Entity:
def __init__(self,x,y,image):
self.x = x
self.y = y
self.image = ima... | [
"The Entity class is an old style class, which does not work like that with super(). If you make Entity a new style class, your code will work.\nTo make Entity a new style class, simply make it inherit from object:\ndef Entity(object):\n def __init__(self, x, y, image):\n # ...\n\nYour code will then work... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0017005365_python.txt |
Q:
Filtering a distance matrix
so I'm working on an optimization problem and wanted to create a function that, given a client X will give me the cities under a certain distance radius.
Say you pick client A. I want to get a list of all the clients that are less than 2 miles away. If you see the image you can see tha... | Filtering a distance matrix | so I'm working on an optimization problem and wanted to create a function that, given a client X will give me the cities under a certain distance radius.
Say you pick client A. I want to get a list of all the clients that are less than 2 miles away. If you see the image you can see that I should get a list that looks ... | [
"I get that \"Cliente\" is both index and columns of the dataframe\ndf.loc[(df.loc[:, \"A\"] < 2) & (df.index != \"A\")].index.to_list()\n\n\nor by columns\n\ndf.loc[\"A\", df[\"A\"] < 2].drop(\"A\").index.to_list()\n\n\nIf you want to leave \"A\" (the initial client)\n\n# by index\ndf.loc[df.loc[:, \"A\"] < 2].ind... | [
0
] | [] | [] | [
"data_science",
"optimization",
"pandas",
"python"
] | stackoverflow_0074311707_data_science_optimization_pandas_python.txt |
Q:
Python - requests.exceptions.SSLError - dh key too small
I'm scraping some internal pages using Python and requests. I've turned off SSL verifications and warnings.
requests.packages.urllib3.disable_warnings()
page = requests.get(url, verify=False)
On certain servers I receive an SSL error I can't get past.
Trac... | Python - requests.exceptions.SSLError - dh key too small | I'm scraping some internal pages using Python and requests. I've turned off SSL verifications and warnings.
requests.packages.urllib3.disable_warnings()
page = requests.get(url, verify=False)
On certain servers I receive an SSL error I can't get past.
Traceback (most recent call last):
File "scraper.py", line 6, in... | [
"this is not an extra answer just try to combine the solution code from question with extra information \nSo others can copy it directly without extra try\nIt is not only a DH Key issues in server side, but also lots of different libraries are mismatched in python modules.\nCode segment below is used to ignore thos... | [
44,
25,
20,
13,
4,
3,
3,
2,
1,
1,
1,
0
] | [] | [] | [
"python",
"python_requests",
"ssl"
] | stackoverflow_0038015537_python_python_requests_ssl.txt |
Q:
JSON Fields with Panda DataFrame
I'm using Python (google colb) and I have a json dataframe with some fields like:
[{'ActedBy': ['team'], 'ActedAt': '2022-03-07T22:43:46Z', 'Status': 'Completed', 'LAB': 'No'}]
I need to get the "ActedAt" in order to get the "date" how can I get this?
Thanks!
A:
You have an arra... | JSON Fields with Panda DataFrame | I'm using Python (google colb) and I have a json dataframe with some fields like:
[{'ActedBy': ['team'], 'ActedAt': '2022-03-07T22:43:46Z', 'Status': 'Completed', 'LAB': 'No'}]
I need to get the "ActedAt" in order to get the "date" how can I get this?
Thanks!
| [
"You have an array of dictionaries. First, grab a dictionary from the array by index, then proceed to get the ActedAt property. Something like this:\njson = [{'ActedBy': ['team'], 'ActedAt': '2022-03-07T22:43:46Z', 'Status': 'Completed', 'LAB': 'No'}]\n# index into a variable for explicit readability\nindex = 0\n# ... | [
0
] | [] | [] | [
"google_colaboratory",
"json",
"pandas",
"python"
] | stackoverflow_0074311780_google_colaboratory_json_pandas_python.txt |
Q:
How do I combine string Pandas columns with null values and a condition?
I'm trying to combine to 2 Pandas columns with this format:
Column A
Column B
NaN
'1'
'12'
'34'
'56'
'78'
NaN
'90'
Column B will always have a value and I want to combine if Column A has a value, otherwise, I will just keep B. This is t... | How do I combine string Pandas columns with null values and a condition? | I'm trying to combine to 2 Pandas columns with this format:
Column A
Column B
NaN
'1'
'12'
'34'
'56'
'78'
NaN
'90'
Column B will always have a value and I want to combine if Column A has a value, otherwise, I will just keep B. This is the basic function that I tried to do for this
def func():
if Col... | [
"You can use the Numpy where() function for creating the conditional statement. Please sample code below\nCode:\nimport pandas as pd\nimport numpy as np\ndata = {\"Column A\": [None,'12','56',None],\n 'Column B': ['1','34','78','90']}\ndf = pd.DataFrame(data)\ndf['Column C'] = np.where(df['Column A'].notnull... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074311691_pandas_python.txt |
Q:
When I run the code, it stops when the sanity check dataloader, but no error is prompted
Through debugging, I found that the problem occurred when I ran to the line of trainer. fit (model).It seems that there are some problems when loading data.
Here's my code
WEIGHT = "bert-base-uncased"
class Classifier(pl.Ligh... | When I run the code, it stops when the sanity check dataloader, but no error is prompted | Through debugging, I found that the problem occurred when I ran to the line of trainer. fit (model).It seems that there are some problems when loading data.
Here's my code
WEIGHT = "bert-base-uncased"
class Classifier(pl.LightningModule):
def __init__(self,
num_classes: int,
... | [
"打印出异常信息后发现。forward方法中调用的classfier方法需要传入tensor,但是传入了字符串。\nprint(self.bert(input_ids = input_ids)输出一个字典,print(bert_logits, bert_pooled)得到这两个变量对应的key,通过bert_pooled = self.bert(input_ids = input_ids)['pooler_output']重新赋值,问题解决\n"
] | [
0
] | [] | [] | [
"bert_language_model",
"python",
"pytorch",
"pytorch_lightning"
] | stackoverflow_0074162510_bert_language_model_python_pytorch_pytorch_lightning.txt |
Q:
Python and GEKKO optimisation of a blackbox function
I am using GEKKO for fitting purposes trying to optimise functions which are explicitly defined - so I have a fully functional form and can create equation objects for optimisation purposes.
But now I have a different problem.
I can't create equations because of... | Python and GEKKO optimisation of a blackbox function | I am using GEKKO for fitting purposes trying to optimise functions which are explicitly defined - so I have a fully functional form and can create equation objects for optimisation purposes.
But now I have a different problem.
I can't create equations because of the complexed functional dependence.
But I have a python ... | [
"Gekko compiles equations into byte-code and requires all equations in Gekko format so that it can overload equation operators to provide exact first and second derivatives in sparse form. Black-box functions do not provide the necessary first and second derivatives, but they can provide function evaluations for fi... | [
0
] | [] | [] | [
"gekko",
"optimization",
"python"
] | stackoverflow_0074304348_gekko_optimization_python.txt |
Q:
how can i send input int to another file in tkinter?
i want to send input int to function in another file but i found error
this is home.py
a=Entry(win, width=21)
a.place(x=200, y=155)
b=Entry(win, width=22)
b.place(x=375, y=155)
this is function.py
t1=int(a.get())
t2=int(b.get())
t3=(1/3)*pi*t1*t1*t2
but after ... | how can i send input int to another file in tkinter? | i want to send input int to function in another file but i found error
this is home.py
a=Entry(win, width=21)
a.place(x=200, y=155)
b=Entry(win, width=22)
b.place(x=375, y=155)
this is function.py
t1=int(a.get())
t2=int(b.get())
t3=(1/3)*pi*t1*t1*t2
but after I run it i found erorr
t1=int(a.get())
NameError: name 'a'... | [
"NameError: name 'a' is not defined is causing because 'a' is not declared in function.py\nyou have to import another script in the working script if you want to use any variable/function that exists in another script.\nexample:\nIf, home.py contains a\nb = 2\nc = 3\na = b + c\n\nand you want to use it inside funct... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074311378_python_tkinter.txt |
Q:
Why my code palindrome works only for single input not for many inputs?
A palindrome is a word or a phrase that is the same when read both forward and backward. Examples are: "bob," "sees," or "never odd or even" (ignoring spaces). Write a program whose input is a word or phrase, and that outputs whether the input... | Why my code palindrome works only for single input not for many inputs? | A palindrome is a word or a phrase that is the same when read both forward and backward. Examples are: "bob," "sees," or "never odd or even" (ignoring spaces). Write a program whose input is a word or phrase, and that outputs whether the input is a palindrome.
I'm only getting this half right. my code is working for bo... | [
"You are comparing word with new, but to generate new you had removed all the spaces.\n",
"That is because of line new = word.replace(\" \", \"\") - the word is kept with the spaces in it. You should make a version of word with no spaces, reverse that, then compare it with the no-spaces word.\nSomething like:\n ... | [
0,
0,
0,
0
] | [] | [] | [
"palindrome",
"python"
] | stackoverflow_0071708263_palindrome_python.txt |
Q:
Python SQLAlchemy ON DUPLICATE KEY UPDATE with multiple records
I'd like to use the ON DUPLICATE KEY UPDATE optionality provided by SQLAlchemy to upsert a bunch of records.
These records have been sucessfully inserted with python using the following (where connection is engine.connect() object and table is a Table... | Python SQLAlchemy ON DUPLICATE KEY UPDATE with multiple records | I'd like to use the ON DUPLICATE KEY UPDATE optionality provided by SQLAlchemy to upsert a bunch of records.
These records have been sucessfully inserted with python using the following (where connection is engine.connect() object and table is a Table object)
record_list = [{'col1': 'name1', 'col2': '2015-01-31', 'col3... | [
"I just ran into a similar problem and creating a dictionary out of query.inserted solved it for me.\nquery = insert(table).values(record_list)\nupdate_dict = {x.name: x for x in query.inserted}\nupsert_query = query.on_duplicate_key_update(update_dict)\n\n",
"@user12730260’s answer is great! but has a little bug... | [
9,
1,
0
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0059291434_mysql_python_sqlalchemy.txt |
Q:
How to cast django.db.models F to a String?
Note: working on expensive corporate legacy code and models that are not allowed to be changed
What I'm trying to do:
Combine two fields into one as a DateTime field.
Model.py:
from django.db import models
class DateThing(models.Model):
date = models.DateField()
... | How to cast django.db.models F to a String? | Note: working on expensive corporate legacy code and models that are not allowed to be changed
What I'm trying to do:
Combine two fields into one as a DateTime field.
Model.py:
from django.db import models
class DateThing(models.Model):
date = models.DateField()
start_time = models.CharField("Start time", m... | [
"Figured it out from someone else on the team\nclass ViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):\n queryset_shifts = DateThing.objects.annotate(\n s_time=Cast(\"start_time\", output_field=TimeField()),\n start=Concat(\n F(\"date\"),\n Value(\" \"),\n F(... | [
0
] | [] | [] | [
"datetime",
"django",
"django_annotate",
"django_models",
"python"
] | stackoverflow_0074311808_datetime_django_django_annotate_django_models_python.txt |
Q:
Trying to solve a number to mnemonics problem using recursion
Given a stringified phone number of non-zero length, write a function that returns all mnemonics for this phone number in any order.
`
def phoneNumberMnemonics(phoneNumber, Mnemonics=[''], idx=0):
number_lookup={'0':['0'], '1':['1'], '2':['a','b','c... | Trying to solve a number to mnemonics problem using recursion | Given a stringified phone number of non-zero length, write a function that returns all mnemonics for this phone number in any order.
`
def phoneNumberMnemonics(phoneNumber, Mnemonics=[''], idx=0):
number_lookup={'0':['0'], '1':['1'], '2':['a','b','c'], '3':['d','e','f'], '4':['g','h','i'], '5':['j','k','l'], '6':['... | [
"The correct list (Mnemonics) was generated for the deepest call of the recursion. However, it was not passed back to previous calls.\nTo fix this, the Mnemonics not only needs to be returned in the \"else\" block, but it also needs to be set to equal the output of the recursive function phone Number Mnemonics.\nde... | [
0,
0
] | [] | [] | [
"algorithm",
"mnemonics",
"python",
"recursion",
"return"
] | stackoverflow_0074283410_algorithm_mnemonics_python_recursion_return.txt |
Q:
Adjusting the plotly colorbar for each subplot according to their min and max
I wanted to find out how to have three different colorbars for my plotly 3 subplots and be able to adjust each of the three colorbars according to their min and max. (attached snapshot).
Does anyone know how to have each colorbar on the... | Adjusting the plotly colorbar for each subplot according to their min and max | I wanted to find out how to have three different colorbars for my plotly 3 subplots and be able to adjust each of the three colorbars according to their min and max. (attached snapshot).
Does anyone know how to have each colorbar on the right side of each subplot?
Also, for some reasons, the plot sizes are not perfec... | [
"To display a color bar for each subplot, the x-axis position must be set for each subplot. Also, for the subplot titles, the top margin is set to 0, which hides the text display area, so I set the top margin to 50. Finally, there does not seem to be a way to synchronize the zoom of the subplots at this time; the p... | [
2
] | [] | [] | [
"plotly",
"plotly_python",
"python",
"visualization"
] | stackoverflow_0074311319_plotly_plotly_python_python_visualization.txt |
Q:
Pandas read_sql with multiple parameters and lists
I've the following script:
now = dt.datetime.now()
date_filter = now - timedelta(days=3)
list_ids = [1,2,3]
dq_connection = mysql.connector.connect(user='user', password='pass', host='localhost', database='db')
engine = create_engine('localhost/db')
cursor = conne... | Pandas read_sql with multiple parameters and lists | I've the following script:
now = dt.datetime.now()
date_filter = now - timedelta(days=3)
list_ids = [1,2,3]
dq_connection = mysql.connector.connect(user='user', password='pass', host='localhost', database='db')
engine = create_engine('localhost/db')
cursor = connection.cursor(buffered=True)
query = ('''
SELECT *
FROM (... | [
"Because IN clause receives multiple values, you need to adjust prepared statement with requisite number of placeholders, %s, and then unpack list for parameters with func(*list). Plus no subquery is needed for both WHERE clauses.\nquery = '''SELECT * FROM myTable1 \n WHERE id in (%s, %s, %s) AND date >= ... | [
2,
0
] | [] | [] | [
"filter",
"pandas",
"python",
"sql"
] | stackoverflow_0057825950_filter_pandas_python_sql.txt |
Q:
What is model.trainable_variables?
I have vgg19 model and I want to Fine-Tune.
# fine tuning the vgg19 model
# let's take a look to see how many layers are in the base model
print("Number of layers in the base model: ", len(vgg_model.layers))
# fine-tune from this layer onwards
fine_tune_at = 100
# freeze all t... | What is model.trainable_variables? | I have vgg19 model and I want to Fine-Tune.
# fine tuning the vgg19 model
# let's take a look to see how many layers are in the base model
print("Number of layers in the base model: ", len(vgg_model.layers))
# fine-tune from this layer onwards
fine_tune_at = 100
# freeze all the layers before the `fine_tune_at` laye... | [
"\nMost models are made of layers. Layers are functions with a known\nmathematical structure that can be reused and have trainable\nvariables. Any variable that can be modified during training of the model is known as a trainable variable.\n\nThe distinction between trainable variables and non-trainable variables\n... | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074154534_python_tensorflow.txt |
Q:
Return a string that has been repeated a specified number of times, with a given separator
I am having trouble trying to get my string to repeat the amount of times I want it to.
Here is my code, but I am not sure where I am going wrong.
def respond_echo(input_string, number_of_echoes, spacer):
echo_outpu... | Return a string that has been repeated a specified number of times, with a given separator | I am having trouble trying to get my string to repeat the amount of times I want it to.
Here is my code, but I am not sure where I am going wrong.
def respond_echo(input_string, number_of_echoes, spacer):
echo_output = ''
if len(input_string) > 0:
for i in range(number_of_echoes):
echo... | [
"I have corrected it. When I tried the code it output meow~meow~meow~meow~meow~meow~meow~meow~meow~.\nThe problem is that every time in the for loop you are multiplying the string, so I removed it. The corrected code is:\ndef respond_echo(input_string, number_of_echoes, spacer):\n\n echo_output = \"\"\n if le... | [
0,
0
] | [] | [] | [
"for_loop",
"loops",
"python",
"string"
] | stackoverflow_0074311967_for_loop_loops_python_string.txt |
Q:
How to identify the specific entity while scrapping wikipedia page by python?
My question is about how to scrape specific entity from wikipedia page.
I am using wikipedia api and got an array of all links from the page
https://en.wikipedia.org/wiki/List_of_painters_by_name_beginning_with_%22A%22
import re
painters... | How to identify the specific entity while scrapping wikipedia page by python? | My question is about how to scrape specific entity from wikipedia page.
I am using wikipedia api and got an array of all links from the page
https://en.wikipedia.org/wiki/List_of_painters_by_name_beginning_with_%22A%22
import re
paintersListArray = []
check = re.compile("List of painters by name*")
for link in dt.links... | [
"What we do is we get the HTML of the webpage and then we use BeautifulSoup to get all the 'li'(The webpage is formatted where all the information we want is in this part). After we do that we make sure all the text in the printers list is only printers and not other information.\nimport requests\nfrom bs4 import B... | [
0
] | [] | [] | [
"python",
"python_3.x",
"web_scraping",
"wikipedia"
] | stackoverflow_0074311936_python_python_3.x_web_scraping_wikipedia.txt |
Q:
Why won't my while loop repeat the calculations more than once?
I'm trying to program something that checks to see if two birthdays match, and counts how many birthdays have to be generated before we get a matching date. The actual date isn't important so I used the random.sample function to generate two numbers b... | Why won't my while loop repeat the calculations more than once? | I'm trying to program something that checks to see if two birthdays match, and counts how many birthdays have to be generated before we get a matching date. The actual date isn't important so I used the random.sample function to generate two numbers between 1 and 365. However when I try to compare these numbers in a wh... | [
"The documentation for random.sample (emphasis mine):\n\nReturn a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.\n\nYou'll never pick the same two numbers.\nTry random.choices instead:\n\nReturn a k sized list of elements chosen from the populatio... | [
2,
0
] | [] | [] | [
"python",
"while_loop"
] | stackoverflow_0074311804_python_while_loop.txt |
Q:
ModuleNotFoundError: No module named 'utils'
I'm trying to run the object_detection API in Tensorflow using my webcam as an input.
The error says: "from utils import label_map_util ModuleNotFoundError: No module named 'utils'"
Which relates to the lines:
from utils import label_map_util
from utils import visuali... | ModuleNotFoundError: No module named 'utils' | I'm trying to run the object_detection API in Tensorflow using my webcam as an input.
The error says: "from utils import label_map_util ModuleNotFoundError: No module named 'utils'"
Which relates to the lines:
from utils import label_map_util
from utils import visualization_utils as vis_util
I've tried "pip install ... | [
"add object_detection to the front of utils:\n# from utils import label_map_util\n# from utils import visualization_utils as vis_util\n\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\n\n",
"What folder are you running your python script from?... | [
8,
6,
5,
2,
0,
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0049545142_python_tensorflow.txt |
Q:
how to combine common values from 2 txt files into 1 file using python
I'm not sure how to write a script to combine values in 2 separate txt files using the specific tag of not done and ensure there are no duplicates. I currently have 2 files with lists of filenames.
Each of them have 'tags' that indicate whether... | how to combine common values from 2 txt files into 1 file using python | I'm not sure how to write a script to combine values in 2 separate txt files using the specific tag of not done and ensure there are no duplicates. I currently have 2 files with lists of filenames.
Each of them have 'tags' that indicate whether they 'exist' or not.
Here is an example:
File1.txt:
P03T10C01 ...[not don... | [
"The below script will read the textfiles, find the common elements and write it on another file\ntxt1, txt2 = '', ''\nwith open(\"path/to/txtfile1.txt\", \"r\") as f1:\n txt1 = f1.read()\nwith open(\"path/to/txtfile2.txt\", \"r\") as f2:\n txt2 = f2.read()\n\ntxtlist1 = [x for x in txt1.split(\"\\n\") if \"n... | [
1
] | [] | [] | [
"io",
"python"
] | stackoverflow_0074312057_io_python.txt |
Q:
Refactoring repeated code with specific implementations?
I've got a method that has to loop through a dataset and then performs a specific lookup:
def lookup_x(findings, count, client, value):
for finding in findings["Findings"]:
for resource in finding["Resources"]:
if finding["Status"] ==... | Refactoring repeated code with specific implementations? | I've got a method that has to loop through a dataset and then performs a specific lookup:
def lookup_x(findings, count, client, value):
for finding in findings["Findings"]:
for resource in finding["Resources"]:
if finding["Status"] == "DEPLOYED":
if count == 0:
... | [
"You can pass the specific method with a set of fixed parameters using functools.partial.\nfunctools.partial will take:\n\na callable object (a function, or a class instance that implements __call__)\nany number of positional arguments\nany number of keyword arguments\n\nand will return a new callable object that h... | [
0
] | [] | [] | [
"json",
"oop",
"python",
"refactoring"
] | stackoverflow_0074311882_json_oop_python_refactoring.txt |
Q:
Django PythonAnywhere (2003, "Can't connect to MySQL server (timed out)")
I'm trying to setup a Django project and I can't seem to connect to MySQL database made in PythonAnywhere.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'username$dbname',
'USER': 'usern... | Django PythonAnywhere (2003, "Can't connect to MySQL server (timed out)") | I'm trying to setup a Django project and I can't seem to connect to MySQL database made in PythonAnywhere.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'username$dbname',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'username.mysql.pythonany... | [
"Add PORT in default database settings.\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'username$dbname',\n 'USER': 'username',\n 'PASSWORD': 'password',\n 'HOST': 'username.mysql.pythonanywhere-services.com',\n 'PORT': '3306'\n }\n}\n... | [
0,
0,
0
] | [] | [] | [
"database",
"django",
"mysql",
"python",
"pythonanywhere"
] | stackoverflow_0069545310_database_django_mysql_python_pythonanywhere.txt |
Q:
I have a dataframe containing arrays, is there a way collect all of the elements and store it in a seperate dataframe?
I cant seem to find a way to split all of the array values from the column of a dataframe.
I have managed to get all the array values using this code:
The dataframe is as follows:
I want to use ... | I have a dataframe containing arrays, is there a way collect all of the elements and store it in a seperate dataframe? | I cant seem to find a way to split all of the array values from the column of a dataframe.
I have managed to get all the array values using this code:
The dataframe is as follows:
I want to use value.counts() on the dataframe and I get this
I want the array values that are clubbed together to be split so that I can g... | [
"You could try .explode(), which would create a new row for every value in each list.\ndf_mentioned_id_exploded = pd.DataFrame(df_mentioned_id.explode('entities.user_mentions'))\n\nWith the above code you would create a new dataframe df_mentioned_id_exploded with a single column entities.user_mentions, which you co... | [
0
] | [] | [] | [
"dataframe",
"python",
"python_3.x"
] | stackoverflow_0074312151_dataframe_python_python_3.x.txt |
Q:
Modify the number of channels in pre-trained CNN model
I have trained a CNN model with input size (None, 256, 256, 1) and saved this mthe model using model.save() method.
In this model, I have used GlobalAveragePooling2D() before connecting to a dense layer, which in turn leads to the output of three values.
I wan... | Modify the number of channels in pre-trained CNN model | I have trained a CNN model with input size (None, 256, 256, 1) and saved this mthe model using model.save() method.
In this model, I have used GlobalAveragePooling2D() before connecting to a dense layer, which in turn leads to the output of three values.
I want the whole model as it is (i.e., the same architecture and ... | [
"it is easy and that is supposed to re-training models for new values for correct results of prediction or working\n\nYou can create 4 channels input picture and modify a 3-channels picture but the results are working because some colors influent the image patterns recognitions.\nI recommended using the same input ... | [
0
] | [] | [] | [
"conv_neural_network",
"deep_learning",
"python",
"tensorflow"
] | stackoverflow_0074312011_conv_neural_network_deep_learning_python_tensorflow.txt |
Q:
I need to send encrypted post data in x-www-form-urlencoded format using python
i have to send encrypted data in
x-www-form-urlencoded
using python
I tried encrypting the data using cryptography module using fernet
the data i have to send is in dictionary form
message = {'Id':1,'Desktop':dtop[0],'Mobile':mob[0]}
... | I need to send encrypted post data in x-www-form-urlencoded format using python | i have to send encrypted data in
x-www-form-urlencoded
using python
I tried encrypting the data using cryptography module using fernet
the data i have to send is in dictionary form
message = {'Id':1,'Desktop':dtop[0],'Mobile':mob[0]}
message1=json.dumps(message)
print(message1)
key = Fernet.generate_key()
print('key'... | [
"Thats how you can send x-www-form-urlencoded data in a request\nurl = \"http://example.com/\"\nheaders = {\"Content-Type\": \"application/x-www-form-urlencoded\"}\ndata = {\"data\": encrypted}\nresponse = requests.post(url, headers=headers, data=data)\nprint(response.text)\n\n"
] | [
0
] | [] | [] | [
"api",
"cryptography",
"encryption",
"python",
"python_requests"
] | stackoverflow_0074312203_api_cryptography_encryption_python_python_requests.txt |
Q:
How to find duplicates in a string
I am working on creating a world game, and I do not want my game to accept duplicate input's by the user, ex: 'mirror'.
I tried finding the duplicates one way but it didn't work, and I do not know how to make my program realize that the inout is a duplicate.
this is my non workin... | How to find duplicates in a string | I am working on creating a world game, and I do not want my game to accept duplicate input's by the user, ex: 'mirror'.
I tried finding the duplicates one way but it didn't work, and I do not know how to make my program realize that the inout is a duplicate.
this is my non working code:
def checkForDuplicates(userWord)... | [
"The issue here is your return statement is nested inside of your for loop so it will always return after checking the first letter. You could move the return into an else statement so that it returns True after the first duplicate letter is found and then put return False after it gets all the way through the for ... | [
0,
0,
0,
0
] | [] | [] | [
"boolean_expression",
"duplicates",
"for_loop",
"python"
] | stackoverflow_0074312025_boolean_expression_duplicates_for_loop_python.txt |
Q:
calculation in list of dictionaries based on assigning the values for its keys in another dictionary
How to calculate in list of dictionaries based on assigning the values for its keys in another dictionary?
How to do this for the following input, print in descending order of bid based on summation of value of ity... | calculation in list of dictionaries based on assigning the values for its keys in another dictionary | How to calculate in list of dictionaries based on assigning the values for its keys in another dictionary?
How to do this for the following input, print in descending order of bid based on summation of value of itype in coef
class ininput(NamedTuple):
itype: str
bid: int
coefficient= {'dr e': 2.0,'ph': ... | [
"\nFix typos like:\n\nc-in in coefficient while c_in in ininput\n\"itype\":\"ph:,\" -> \"itype\": \"ph\"\nsortbid = calvalue(ininputs) -> sortbid = calvalue(ininput)\n2.\ncoefficient= {'dr e': 2.0, 'ph': 1.0, 'c_in': 0.8, 'bk': 0.25}\n\ndef calvalue(ininputs):\n # initialize a sum dict with 0\n sum_dict = {_[... | [
0
] | [] | [] | [
"dictionary",
"hashmap",
"list",
"nested",
"python"
] | stackoverflow_0074311695_dictionary_hashmap_list_nested_python.txt |
Q:
Is it possible to use another programming language for example python(backend) for flutter(frontend)?
Please, Can somebody help me. I need to do cross-platform app based on flutter as frontend, and there is problem with backend. I know python very well and I want use it for my app as backend. Is it possible to use... | Is it possible to use another programming language for example python(backend) for flutter(frontend)? | Please, Can somebody help me. I need to do cross-platform app based on flutter as frontend, and there is problem with backend. I know python very well and I want use it for my app as backend. Is it possible to use python(backend) for flutter(frontend)?
And I just started to learn flutter and don't knowing the Dart lang... | [
"Yes, you can\nyou can make the front end and UI of your app with flutter/dart, then you can make a backend with whatever language and technologies you want, such as node js, python, go, travel...\nthen you can link it and use it in your app using a REST API.\n",
"Frontend and backend technologies are independent... | [
0,
0
] | [] | [] | [
"android",
"cross_platform",
"flutter",
"ios",
"python"
] | stackoverflow_0074309212_android_cross_platform_flutter_ios_python.txt |
Q:
print the first character after the same element in every line
Im trying to print the first character after an element that occurs in each line.
w.txt:
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
osboxes tty7 :0 22:23 42:15 2.27s 0.23s
cinnamon-session --session cin... | print the first character after the same element in every line | Im trying to print the first character after an element that occurs in each line.
w.txt:
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
osboxes tty7 :0 22:23 42:15 2.27s 0.23s
cinnamon-session --session cinnamon
osboxes pts/1 192.168.1.17 22:25 1:26 0.06s 0.00s ... | [
"You could use re.findall() to scan for any digit after a /. This will give you strings, but you can convert those to integers fairly easily.\nimport re\n\nwith open(path, 'r') as file:\n found = re.findall(r'/(\\d)', file.read())\n # ['1', '3', '0']\n\n[int(i) for i in found]\n# [1, 3, 0]\n\n",
"You can us... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074312149_python_python_3.x.txt |
Q:
RenderUpdates.draw() always returns rects
I'm using a sprite group class from pygame, specifically pygame.sprite.RenderUpdates
The reason I'm using that sprite group class is because it's supposed to return a list of rects that have been modified.
Specifically, the documentation says this about pygame.sprite.Rende... | RenderUpdates.draw() always returns rects | I'm using a sprite group class from pygame, specifically pygame.sprite.RenderUpdates
The reason I'm using that sprite group class is because it's supposed to return a list of rects that have been modified.
Specifically, the documentation says this about pygame.sprite.RenderUpdates draw() method:
...This method also re... | [
"\nIsn't the draw() method only supposed to return rects that have been changed?\n\nNo it is not. pygame.sprite.RenderUpdates.draw. does not validate the content of the redraw areas or compare pixels, because that would cost too much time. The method collects only the areas that are redrawn, even if they are redraw... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074311476_pygame_python.txt |
Q:
How to take PostgreSQL table's data constantly using Python?
How to take PostgreSQL table's data constantly using Python? (For example, every 1 minute, it needs to take the next row's data)
Could you please help me with that?
import psycopg2
#establishing the connection
conn = psycopg2.connect(
database="mydb"... | How to take PostgreSQL table's data constantly using Python? | How to take PostgreSQL table's data constantly using Python? (For example, every 1 minute, it needs to take the next row's data)
Could you please help me with that?
import psycopg2
#establishing the connection
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5... | [
"You can use while loop and timer to execute your code as shown below.\nimport psycopg2\nimport time\n\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Cr... | [
1
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0074312443_postgresql_python.txt |
Q:
creating a neon-glow with python numpy
I'm trying to create a neon-effect w/ a source image. I have included three images, the source, my current attempt & a target. The program takes the image, finds the white-edges, & calculates the distance from each pixel to the nearest white-edge (these parts both work fine);... | creating a neon-glow with python numpy | I'm trying to create a neon-effect w/ a source image. I have included three images, the source, my current attempt & a target. The program takes the image, finds the white-edges, & calculates the distance from each pixel to the nearest white-edge (these parts both work fine); from there, I am struggling to find the rig... | [
"I think I would do this with convolution instead. Convolving an image with a Gaussian kernel is a common way to blur an image. You can do it in various ways, but maybe the easiest to use is scipy.ndimage.gaussian_filter. Here's one way to implement all this, see if you like the result.\nfrom PIL import Image\nfrom... | [
2,
2
] | [] | [] | [
"arrays",
"image_processing",
"numpy",
"opencv",
"python"
] | stackoverflow_0074309185_arrays_image_processing_numpy_opencv_python.txt |
Q:
Kivy widget sizing not working correctly on IOS
So I am using the metrics sd and dp from Kivy for the sizing of my widgets. I also set the GridLayout row_heights according to the height of the screen. I also set the Resolution of my Kivy app on the Mac to the Phone Resolution. Yet when I load the app to my phone, ... | Kivy widget sizing not working correctly on IOS | So I am using the metrics sd and dp from Kivy for the sizing of my widgets. I also set the GridLayout row_heights according to the height of the screen. I also set the Resolution of my Kivy app on the Mac to the Phone Resolution. Yet when I load the app to my phone, the widgets are a completely different size and don't... | [
"Good afternoon!\nTry adding the *.xcode parameter to your main.m file in your project\nputenv(\"KIVY_METRICS_DENSITY=1.75\");\nand change the value at your discretion.\nenter image description here\n"
] | [
0
] | [] | [] | [
"kivy",
"python",
"xcode"
] | stackoverflow_0074151388_kivy_python_xcode.txt |
Q:
Combine two csr matrice when they have incompatible dimensions
I have two sparse matrice where the first has the property of
<1x40 sparse matrix of type '<class 'numpy.intc'>'
with 10 stored elements in Compressed Sparse Row format>
And the second one:
<9x15426 sparse matrix of type '<class 'numpy.int64'>'
... | Combine two csr matrice when they have incompatible dimensions | I have two sparse matrice where the first has the property of
<1x40 sparse matrix of type '<class 'numpy.intc'>'
with 10 stored elements in Compressed Sparse Row format>
And the second one:
<9x15426 sparse matrix of type '<class 'numpy.int64'>'
with 25 stored elements in Compressed Sparse Row format>
I want t... | [
"Yes it is possible. You just need to go into the contents of the matrix and carefully loop over it. Here is an example (probably could skip turning into lists but I thought concatenations are more simple with lists):\nfrom scipy.sparse import csr_matrix\nimport numpy as np\n\ncsr1 = csr_matrix(\n np.random.rand... | [
1,
1
] | [] | [] | [
"python",
"python_3.x",
"scipy",
"sparse_matrix"
] | stackoverflow_0074311829_python_python_3.x_scipy_sparse_matrix.txt |
Q:
Qt and opencv app not working in virtual environment
I created a GUI app using pyqt5 and opencv. The app works fine without activating the virtual env but when I activate the virtual env and run the app it shows this error:
QObject::moveToThread: Current thread (0x125b2f0) is not the object's thread (0x189e780).
C... | Qt and opencv app not working in virtual environment | I created a GUI app using pyqt5 and opencv. The app works fine without activating the virtual env but when I activate the virtual env and run the app it shows this error:
QObject::moveToThread: Current thread (0x125b2f0) is not the object's thread (0x189e780).
Cannot move to target thread (0x125b2f0)
qt.qpa.plugin: Co... | [
"The problem is that the version of Qt with which opencv was compiled is not similar to the one used by PyQt5 causing a conflict.\nA possible solution is to indicate to use the Qt plugins used by PyQt5.\nimport os\nfrom pathlib import Path\n\nimport PyQt5\nfrom PyQt5.QtWidgets import QWidget # others imports\nimpor... | [
10,
2,
0,
0
] | [] | [] | [
"opencv",
"pyqt5",
"python",
"python_3.x"
] | stackoverflow_0068417682_opencv_pyqt5_python_python_3.x.txt |
Q:
Compare two text files and create another file which contain data along with matching prints
I have two text files eg1.txt and eg2.txt.
I need to compare eg1.txt with respect to eg2.txt and create another file named out.txt .
eg1.txt:
000b423573 bdbaskbjejbajbkjfsjba
00036713dc sjgdjgdgdjadgygdeg263
00123fd351 heq... | Compare two text files and create another file which contain data along with matching prints | I have two text files eg1.txt and eg2.txt.
I need to compare eg1.txt with respect to eg2.txt and create another file named out.txt .
eg1.txt:
000b423573 bdbaskbjejbajbkjfsjba
00036713dc sjgdjgdgdjadgygdeg263
00123fd351 heqgrg63u1quidg87gduq
0105517f52 vgfeeyguuiduiueyruuur
eg2.txt
0105517f52 vgfeeyguuiduiueyruuur
000b... | [
"I notice that in your example you name eg2.txt file_1 and vice versa which leads you to find the lines ineg1.txt which do not exist in eg2.txt. Additionally, you have not yet added logic to concatenate the endings to the line, with can simply be done with +. With those slight modifications your code works.\nHere i... | [
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074312235_python_python_3.x.txt |
Q:
Azure functions keep on running, inserting 10x values in Database
I have built a pipeline with Stream Analytics data triggering Azure Functions.
There are 5000 values merged in a single data. I wrote a simple python program in the Function to validate the data, parse the bulk data, and save it in Cosmos DB as an i... | Azure functions keep on running, inserting 10x values in Database | I have built a pipeline with Stream Analytics data triggering Azure Functions.
There are 5000 values merged in a single data. I wrote a simple python program in the Function to validate the data, parse the bulk data, and save it in Cosmos DB as an individual document. But the problem is, my functions don't stop. After ... | [
"I found the solution! (I am the OP)\nIn my resource group, an App service plan is enabled for a Web application. So, when creating an Azure Function, it doesn't let me deploy it in the Serverless option. So, I deployed with the same app service plan used for Web applications. And while testing, the function comple... | [
0
] | [] | [] | [
"azure",
"azure_cosmosdb",
"azure_functions",
"python"
] | stackoverflow_0074160318_azure_azure_cosmosdb_azure_functions_python.txt |
Q:
How to use one = with multiple and/or
while party!='R' and party!='D':
can this be shortened to
while party!='R' and 'D':
while party!=('R' and 'D'):
or the like? (that is, is there any equivalent expression with only one party!=)
A:
If you want to use multiple condition:
try this.
l=['R','D']
while party not in... | How to use one = with multiple and/or | while party!='R' and party!='D':
can this be shortened to
while party!='R' and 'D':
while party!=('R' and 'D'):
or the like? (that is, is there any equivalent expression with only one party!=)
| [
"If you want to use multiple condition:\ntry this.\nl=['R','D']\nwhile party not in l:\n\n",
"you can simply create list and use like this\nvalidList = ['R', 'S']\n# You can also use not in operator for other condition\nif party in validList:\n # Do your stuff here\n print(\"It's Present\")\n\n"
] | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074312543_python.txt |
Q:
Find all strings that differ with each other in at least three positions, generated by only four characters
I am currently learning to code in python and one of the bonus exercises to solve is the following:
chars=['A','B','C','D']
From the list of characters above, I need to generate a list of twelve four-letter... | Find all strings that differ with each other in at least three positions, generated by only four characters | I am currently learning to code in python and one of the bonus exercises to solve is the following:
chars=['A','B','C','D']
From the list of characters above, I need to generate a list of twelve four-letter strings, that differ with each other in at least three positions.The final list can possibly look like this (the... | [
"This sounds like a backtracking problem. Here is one solution:\n\nWe represent the problem state by a partial mapping from (word, position) indices to characters.\nThe algorithm starts with a blank state.\nAt each step, we check if the state has a conflict (two words have the same characters in two of the same pos... | [
0
] | [] | [] | [
"algorithm",
"numpy",
"pandas",
"python"
] | stackoverflow_0074309544_algorithm_numpy_pandas_python.txt |
Q:
How do I turn off Windows Defender in python
I have an old computer that I want to try to remove Windows Defender on with a python script. I tried to use the command:
sc stop WinDefend
This command isn’t useful since it is used by the command prompt. Can someone show me?
A:
You can run this command using python ... | How do I turn off Windows Defender in python | I have an old computer that I want to try to remove Windows Defender on with a python script. I tried to use the command:
sc stop WinDefend
This command isn’t useful since it is used by the command prompt. Can someone show me?
| [
"You can run this command using python like this;\nimport os\n\ncommand = \"sc stop WinDefend\"\n\nos.system(command)\n\n"
] | [
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0074312589_python_windows.txt |
Q:
Limiting a row set defined by a prefix in Google Cloud Bigtable
I was trying to do this in Python: I have multiple prefixes to query in Bigtable, but I only want the first result of each row set defined by a prefix. In essence, applying a limit of 1 for each row set, not for the entire scan.
Imagine you have the f... | Limiting a row set defined by a prefix in Google Cloud Bigtable | I was trying to do this in Python: I have multiple prefixes to query in Bigtable, but I only want the first result of each row set defined by a prefix. In essence, applying a limit of 1 for each row set, not for the entire scan.
Imagine you have the following records' row keys:
collection_1#item1#reversed_timestamp1
co... | [
"Is collection_1#item1#reversed_timestamp1 the rowkey or is reversed_timestamp1 actually a timestamp?\nIf it is not part of the rowkey you could use a filter like cells per column\nhttps://cloud.google.com/bigtable/docs/using-filters#cells-per-column-limit e.g.\nrows = table.read_rows(filter_=row_filters.CellsColum... | [
0
] | [] | [] | [
"bigtable",
"google_cloud_bigtable",
"python"
] | stackoverflow_0069198443_bigtable_google_cloud_bigtable_python.txt |
Q:
How to only extract only organization names from text using spacy
I want to extract only organization from a string or column.
I am using this code:
def ent(doc):
for x in (nlp(doc)).ents:
if x.label_ != "ORG": continue
else:
return (x.text)
d= ("Brock Group (American Industrial Pa... | How to only extract only organization names from text using spacy | I want to extract only organization from a string or column.
I am using this code:
def ent(doc):
for x in (nlp(doc)).ents:
if x.label_ != "ORG": continue
else:
return (x.text)
d= ("Brock Group (American Industrial Partners) acquires Aegion's Energy Services Businesses")
ent(d)
Howev... | [
"Your code only extracts the first organization name because it returns when the condition is met. You can use list comprehension\ndef ent(doc):\n return [x for x in (nlp(doc)).ents if x.label_ == \"ORG\"]\n\n"
] | [
3
] | [] | [] | [
"nlp",
"pandas",
"python",
"spacy"
] | stackoverflow_0074312267_nlp_pandas_python_spacy.txt |
Q:
how to convert a program made with python classes to a program only with functions
I was making a hangman game using a class. I was wondering how can I delete the class and run everything into a main function. I'm leaving the code here. Every feedback is appreciate it and it can really help me learn. Thank you.
cl... | how to convert a program made with python classes to a program only with functions | I was making a hangman game using a class. I was wondering how can I delete the class and run everything into a main function. I'm leaving the code here. Every feedback is appreciate it and it can really help me learn. Thank you.
class game:
def __init__(user):
user.guesses = 0
user.letters_guessed... | [
"Not sure why you'd want to do this after all of your current work, but the way that classes work is when they are instantiated using game(), their __init__ function is called. Your variable name \"user\" in these methods should follow standard practice and be called \"self\", but if you're removing classes these v... | [
0
] | [] | [] | [
"class",
"function",
"python"
] | stackoverflow_0074312165_class_function_python.txt |
Q:
How to connect to a child conhost.exe process of an external application
I'm trying to communicate with an interactive Windows Console application, to send commands to it and receive their output, but the subprocess the create_subprocess_exec() catches seems to be the wrong process, as the application creates two ... | How to connect to a child conhost.exe process of an external application | I'm trying to communicate with an interactive Windows Console application, to send commands to it and receive their output, but the subprocess the create_subprocess_exec() catches seems to be the wrong process, as the application creates two processes.
When starting the subprocess, two processes open - JoyShockMapper.e... | [
"There is no fix.\nAfter I posted this question I've did some more research and I'm pretty sure I saw somewhere Microsoft stating that it's impossible to connect to a running application's stdin and stdout outside of the code that has launched it (JSM's code in this case).\nI've decided to rather find the PID of th... | [
0
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074221894_python_python_asyncio.txt |
Q:
Incrementing frequency in data,for a specific number using a Python dataframe?
I have a dataset like:
a
c
c
d
b
a
a
d
d
c
c
b
a
b
I want to add a column that looks like the one below. When 'c' is reached, the new column will be zero and then be increased by one. Is there a way ... | Incrementing frequency in data,for a specific number using a Python dataframe? | I have a dataset like:
a
c
c
d
b
a
a
d
d
c
c
b
a
b
I want to add a column that looks like the one below. When 'c' is reached, the new column will be zero and then be increased by one. Is there a way we can do this using python?
a 1
c 0
c 0
d 2
b 2
a 2
a 2
d 2
d 2
c... | [
"Use:\ns = df['col'].eq('c')\ndf['new'] = s.ne(s.shift())[~s].cumsum().reindex(df.index, fill_value=0)\n\n\ns = df['col'].ne('c')\ndf['new'] = (s & ~s.shift(fill_value=False)).cumsum().where(s, 0)\n\n\nprint (df)\n col new\n0 a 1\n1 c 0\n2 c 0\n3 d 2\n4 b 2\n5 a 2\n6 a 2... | [
3,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074301929_dataframe_pandas_python_python_3.x.txt |
Q:
Trouble getting file name with extension using pathlib
I have this code which gives me the filename no problem. It gives it to me without the extension. Any way to get with extension?
from pathlib import Path
file = 'somepath'
path_object = Path(file)
filename = path_object.stem
A:
You can use .name attribute o... | Trouble getting file name with extension using pathlib | I have this code which gives me the filename no problem. It gives it to me without the extension. Any way to get with extension?
from pathlib import Path
file = 'somepath'
path_object = Path(file)
filename = path_object.stem
| [
"You can use .name attribute of the Path object.\n>>> from pathlib import Path\n>>>\n>>> p = Path(\"SomePath/filename.txt\")\n>>> p.name\n'filename.txt'\n\n"
] | [
1
] | [] | [] | [
"pathlib",
"python",
"windows"
] | stackoverflow_0074312682_pathlib_python_windows.txt |
Q:
How to import packages from inside another package
So, I am making an application in python where i am inside a package, and i want to a import a package from outside that older. I have tried os.chdir() but that doesn't work. I have tried to import it by simply saying
I expect the package to be imported and any f... | How to import packages from inside another package | So, I am making an application in python where i am inside a package, and i want to a import a package from outside that older. I have tried os.chdir() but that doesn't work. I have tried to import it by simply saying
I expect the package to be imported and any file that i want can be used as many times as possible so... | [
"My username is too new to comment so I'll indirectly answer, if your UserData is a module (given there is an __init__), and so too is SignLoginLogic, and they are at the same directory level, I have never seen a case where you're importing using your requested method (importing somehow from another module's __init... | [
0
] | [] | [] | [
"package",
"python"
] | stackoverflow_0074312279_package_python.txt |
Q:
Listing Available Message Attributes with win32com.client
I have a directory with hundreds of Outlook emails stored in .msg format. I have a script to access specific attributes, e.g. SenderName, Subject etc, however the script fails upon certain files. After some investigation, the failing files are responses to ... | Listing Available Message Attributes with win32com.client | I have a directory with hundreds of Outlook emails stored in .msg format. I have a script to access specific attributes, e.g. SenderName, Subject etc, however the script fails upon certain files. After some investigation, the failing files are responses to calendar invites, and the attribute that fails is the 'To' attr... | [
"Before accessing any message properties, check the Class property (exposed by all OOM objects) - it will be 43 (olMailItem) for the MailItem object.\n",
"print(message.__dir__())\nOutput:\n\n['TaskStartDate', '_username_', '_print_details_', '__lt__', '__doc__', 'ReceivedByEntryID', '_FlagAsMethod', 'MessageClas... | [
0,
0
] | [] | [] | [
"outlook",
"python",
"win32com"
] | stackoverflow_0056492400_outlook_python_win32com.txt |
Q:
Insert a rectangle shape with xlwings
How do you insert a rectangle shape in a range with xlwings? Then modify it to transparent
sheet.range((7, 4), (10, 8)).shape
A:
You can use AddShape which takes the following params; (Type, Left, Top, Width, Height).
A rectangle is shape type 1.
Then assuming (7, 4), (10, 8... | Insert a rectangle shape with xlwings | How do you insert a rectangle shape in a range with xlwings? Then modify it to transparent
sheet.range((7, 4), (10, 8)).shape
| [
"You can use AddShape which takes the following params; (Type, Left, Top, Width, Height).\nA rectangle is shape type 1.\nThen assuming (7, 4), (10, 8) is your cell positioning the example will place the rectangle and set its transparency to 1.\n\nDetermining the rectangle positioning can be done in a couple of ways... | [
0
] | [] | [] | [
"python",
"xlwings"
] | stackoverflow_0074312191_python_xlwings.txt |
Q:
BooleanField Model not showing the default False value but '-' instead
I have a model class where the variable completed_application should default to False when creating a new user (to show that the user hasn't completed an application yet). However, by default when a new user is created it doesn't show as False ... | BooleanField Model not showing the default False value but '-' instead | I have a model class where the variable completed_application should default to False when creating a new user (to show that the user hasn't completed an application yet). However, by default when a new user is created it doesn't show as False in Django admin but '-' instead.
models.py:
class Company(models.Model):
... | [
"From the docs, the can_delete should be can_delete=False not can_delete:False\n",
"I believe it is the cant_delete that is passed false, try to remove it\n"
] | [
2,
0
] | [] | [] | [
"django",
"django_admin",
"django_modeladmin",
"django_models",
"python"
] | stackoverflow_0074309903_django_django_admin_django_modeladmin_django_models_python.txt |
Q:
Register Basic Auth in Selenium 4 BiDi API with Python WebDriver
I can do basic auth in Python using the Selenium Web Driver by embedding the credentials in the URL:
driver.get(f'https://{ACCESS_USERNAME}:{ACCESS_PASSWORD}@{TEST_URL}')
Selenium 4 introduces the BiDi API with a Register Basic Auth option. This al... | Register Basic Auth in Selenium 4 BiDi API with Python WebDriver | I can do basic auth in Python using the Selenium Web Driver by embedding the credentials in the URL:
driver.get(f'https://{ACCESS_USERNAME}:{ACCESS_PASSWORD}@{TEST_URL}')
Selenium 4 introduces the BiDi API with a Register Basic Auth option. This allows registering a username and password for a site instead of using t... | [
"I faced same issue. I resolved this issue as below. Things to be noted\n\nWe need to encode as byte(encode(\"ascii\")), encode to base64(b64encode), credentials and then decode as string (decode(\"ascii\")) - Note - This encode ascii convert string to bytes, similar way the decode(\"ascii\") will decode the bytes ... | [
0
] | [] | [] | [
"authentication",
"python",
"selenium_webdriver"
] | stackoverflow_0070638123_authentication_python_selenium_webdriver.txt |
Q:
Setting environment variable when running Python unit tests inside VSCode
I'd like to execute code inside my unit tests conditioned on whether they're running from within VSCode or the command line. Is there a way to do so?
The reasoning is to add additional visual feedback through cv2.imwrite statements, but to ... | Setting environment variable when running Python unit tests inside VSCode | I'd like to execute code inside my unit tests conditioned on whether they're running from within VSCode or the command line. Is there a way to do so?
The reasoning is to add additional visual feedback through cv2.imwrite statements, but to omit these when running a full regression from the command line or when running... | [
"Try defining environment variables by using .env files\n\n.env:\nMY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS = 1\n\ntest1.py:\nimport os\nfrom pathlib import Path\nfrom dotenv import find_dotenv, load_dotenv\n\nenv_path = Path(\".\") / \".env\"\nload_dotenv(dotenv_path=env_path, verbose=True)\nprint(os.getenv(\"MY_ENV... | [
0,
0
] | [] | [] | [
"environment_variables",
"python",
"python_unittest",
"visual_studio_code"
] | stackoverflow_0073599859_environment_variables_python_python_unittest_visual_studio_code.txt |
Q:
Hello, I am needing some help to hexdump a .bin file that a python program created
I am following Ben Eaters tutorial on the 6502 computer and I'm completely lost on the python programming stuff. I have a little bit of programming knowledge, but not enough to understand which programs he is swithcing between. Her... | Hello, I am needing some help to hexdump a .bin file that a python program created | I am following Ben Eaters tutorial on the 6502 computer and I'm completely lost on the python programming stuff. I have a little bit of programming knowledge, but not enough to understand which programs he is swithcing between. Here is the link to the video I'm referring to (around the 9:40 mark): https://www.youtube.... | [
"Too many questions to ask to clarify what you are asking. I would use Python for Windows if you're on Windows and then call > python.exe YourScriptName.py from within PowerShell. If you're on Linux just use your bash terminal and call $ python YourScriptName.py.\nYour program above works. To check the file that it... | [
-2
] | [] | [] | [
"python",
"pythoninterpreter"
] | stackoverflow_0074312192_python_pythoninterpreter.txt |
Q:
How to Update a dataframe column by taking value from another dataframe?
I have two dataframes df_1 and df_2:
rdd = spark.sparkContext.parallelize([
(1, '', '5647-0394'),
(2, '', '6748-9384'),
(3, '', '9485-9484')])
df_1 = spark.createDataFrame(rdd, schema=['ID', 'UPDATED_MESSAGE', 'ZIP_CODE'])
# +---+... | How to Update a dataframe column by taking value from another dataframe? | I have two dataframes df_1 and df_2:
rdd = spark.sparkContext.parallelize([
(1, '', '5647-0394'),
(2, '', '6748-9384'),
(3, '', '9485-9484')])
df_1 = spark.createDataFrame(rdd, schema=['ID', 'UPDATED_MESSAGE', 'ZIP_CODE'])
# +---+---------------+---------+
# | ID|UPDATED_MESSAGE| ZIP_CODE|
# +---+----------... | [
"I hope I've interpreted what you need well. If yes, then your logic seems strange. It seems, that your tables are very small. Spark is the engine for big data (millions to billions of records). If your tables are small, consider doing things in Pandas.\nfrom pyspark.sql import functions as F\n\ndf_2 = df_2.groupBy... | [
1,
1,
0
] | [
"Why use dataframes when Spark SQL is so much easier?\nTurn data frames into temporary views.\n%python\ndf_1.createOrReplaceTempView(\"tmp_zipcodes\")\ndf_2.createOrReplaceTempView(\"tmp_person\")\n\nWrite simple Spark SQL to get answer.\n%sql \nselect \n a.id, \n case when b.code is null then '' else b.code end ... | [
-1
] | [
"apache_spark",
"databricks",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074301106_apache_spark_databricks_dataframe_pyspark_python.txt |
Q:
Change in return position throws variable not defined error
I came across this problem while learning how to return a sorted list in Python. When I write the code this way
def func(A):
return A
A = sorted([4,5,6,7,2,1])
print(A)
It sorts the list perfectly and returns [1,2,3,4,5,6,7].
But when I change the po... | Change in return position throws variable not defined error | I came across this problem while learning how to return a sorted list in Python. When I write the code this way
def func(A):
return A
A = sorted([4,5,6,7,2,1])
print(A)
It sorts the list perfectly and returns [1,2,3,4,5,6,7].
But when I change the position of return A to
def func(A):
A = sorted([4,5,6,7,2,1])
r... | [
"Trying to summarize what has been hinted to you in the comments using examples.\nthe function is never executed\nYour code:\ndef func(A):\n return A\nA = sorted([4,5,6,7,2,1]) \nprint(A)\n\nIs equivalent to:\nA = sorted([4,5,6,7,2,1]) \nprint(A)\n\nAlthough defined, the function is never used, so you could writ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074312319_python.txt |
Q:
Layered Altair Line Plot with Multiple Colors per Line
I am trying to map two lines on a single chart in Altair that change color midway through the plot.
Here is what the plot would look like ideally:
So far I have successfully plot two lines on a single graph. Each line takes a custom color, but the colors do n... | Layered Altair Line Plot with Multiple Colors per Line | I am trying to map two lines on a single chart in Altair that change color midway through the plot.
Here is what the plot would look like ideally:
So far I have successfully plot two lines on a single graph. Each line takes a custom color, but the colors do not change at the midway point.
Here's the code:
(1) dummy ve... | [
"You need to explicitly state that you want independent legends using the resolve_scale function. I tried running your code but the x values of your mark_rect are missing. Using only the line charts, it will go something like this\nalt.layer(line_chart_1, line_chart_2).properties(**PROPERTIES).resolve_scale(color='... | [
0
] | [] | [] | [
"altair",
"python",
"vega_lite"
] | stackoverflow_0074312395_altair_python_vega_lite.txt |
Q:
Django app dissapears from Django Admin site when I add apps.py file
I'm working with Django 3.2 and trying to configure correctly the AppsConfig subclass of apps.py in order to avoid duplicate apps names when initzialing the project.
The context is the following. I have in my INSTALLED_APPS two apps whose names a... | Django app dissapears from Django Admin site when I add apps.py file | I'm working with Django 3.2 and trying to configure correctly the AppsConfig subclass of apps.py in order to avoid duplicate apps names when initzialing the project.
The context is the following. I have in my INSTALLED_APPS two apps whose names are equal although their paths not:
INSTALLED_APPS = [
...
'first_a... | [
"instead of this:\nINSTALLED_APPS = [\n ...\n 'first_app.myapp',\n 'second_app.myapp'\n]\n\nJust try this way only:\nINSTALLED_APPS = [\n ...\n 'first_app',\n 'second_app'\n]\n\nYou got that error because here first_app.myapp and second_app.myapp myapp is duplicate. you should not use like this in... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074303262_django_python.txt |
Q:
How to remove read-only attrib directory with Python in Windows?
I have a read only directory copied from version controlled directory which is locked.
When I tried to remove this directory with shutil.rmtree(TEST_OBJECTS_DIR) command, I got the following error message.
WindowsError: [Error 5] Access is denied: '... | How to remove read-only attrib directory with Python in Windows? | I have a read only directory copied from version controlled directory which is locked.
When I tried to remove this directory with shutil.rmtree(TEST_OBJECTS_DIR) command, I got the following error message.
WindowsError: [Error 5] Access is denied: 'C:\...\environment.txt'
Q : How can I change the attribute of everyt... | [
"If you are using shutil.rmtree, you can use the onerror member of that function to provide a function that takes three params: function, path, and exception info. You can use this method to mark read only files as writable while you are deleting your tree.\nimport os, shutil, stat\n\ndef on_rm_error( func, path, ... | [
79,
16,
8,
8,
4,
0
] | [] | [] | [
"attributes",
"python",
"windows"
] | stackoverflow_0004829043_attributes_python_windows.txt |
Q:
How to write 3 conditions in ternery operator of python?
my problem is to use elif in this ternary operator like i want to use 3 conditions in ternary operator
a = 3
if a>0:
print("is odd" if a %2 !=0 else "is even")
Make a code which return 3 strings one for its odd one for its even and atlast for its zero
... | How to write 3 conditions in ternery operator of python? | my problem is to use elif in this ternary operator like i want to use 3 conditions in ternary operator
a = 3
if a>0:
print("is odd" if a %2 !=0 else "is even")
Make a code which return 3 strings one for its odd one for its even and atlast for its zero
| [
"print(\"atlast\" if x == 0 else \"even\" if x%2 == 0 else \"odd\")\n\n(Thanks Ignatius Reilly for pointing out that I don't need inner parentheses)\n",
"You can check for a condition within a condition. In this case, it will first check whether the value is zero or not. If not zero, then it will move on to check... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0074312778_python.txt |
Q:
How do I click on this button in Selenium, python. Every time i click on it, its link changes, so i cant enter a particular link to click on
i wanted to automate a task which clicks on the next button if the big green button says "completed well done!". but its link changes every time I click on it.
i tried using ... | How do I click on this button in Selenium, python. Every time i click on it, its link changes, so i cant enter a particular link to click on | i wanted to automate a task which clicks on the next button if the big green button says "completed well done!". but its link changes every time I click on it.
i tried using x,y coordinates to click on it but the coordinates I entered didn't work and it just ended up clicking on a random position
| [
"It looks like the button, you want to klick, has a html id. That is pretty handy if that id is unique in that html. If so you can just search for that element with that id like so:\ndriver.find_element_by_id('relationsNextIcon')\n\nHere is an other answer with find_element_by_id: https://stackoverflow.com/a/773200... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074312571_python_selenium_selenium_webdriver.txt |
Q:
Dst tensor is not initialized. Even with small batch size
There are many, many questions about this on SO. The answers to all of them appear to be rather straight forward, pointing out it's almost certainly a memory error and that reducing the batch size should work.
In my case something else appears to be going o... | Dst tensor is not initialized. Even with small batch size | There are many, many questions about this on SO. The answers to all of them appear to be rather straight forward, pointing out it's almost certainly a memory error and that reducing the batch size should work.
In my case something else appears to be going on (or I am having a serious misunderstanding of how this work).... | [
"Based on the following experiments, size of train samples passed to model.fit(...) also matters along with the batch_size.\n\ntrain_x: Peak GPU memory increased with batch_size but not linearly\n\nmodel.fit(train_x, train_y, epochs=1, batch_size=10, callbacks= [MemoryPrintingCallback()])\n#GPU memory details [curr... | [
1
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074311806_python_tensorflow.txt |
Q:
Conda environment's python segmentation fault
I I'm trying to use python with conda environment.
I create an environment using
conda create -n new_env3 python=3.9
Then when I start python terminal (just running 'python') I get:
Python 3.9.12 (main, Apr 5 2022, 06:56:58)
[GCC 7.5.0] :: Anaconda, Inc. on linux
T... | Conda environment's python segmentation fault | I I'm trying to use python with conda environment.
I create an environment using
conda create -n new_env3 python=3.9
Then when I start python terminal (just running 'python') I get:
Python 3.9.12 (main, Apr 5 2022, 06:56:58)
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for... | [
"i met the same problem, and conda clean -a didn't solve the problem\n\n$ python \nPython 3.10.6 (main, Oct 24 2022, 16:07:47) [GCC 11.2.0] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information. \nSegmentation fault\n\n",
"Try running conda clean -a.\nThis will remove all unused ... | [
1,
0
] | [] | [] | [
"conda",
"python",
"segmentation_fault"
] | stackoverflow_0074208395_conda_python_segmentation_fault.txt |
Q:
ModuleNotFoundError: No module named 'requests' error for docker run
I have created the docker image to run python script. Now when I run below command it throwing error.
command in powershell:
docker build -t pull_request_summary .
Error:
Traceback (most recent call last):
File "/usr/app/src/./listPullRequest.py"... | ModuleNotFoundError: No module named 'requests' error for docker run | I have created the docker image to run python script. Now when I run below command it throwing error.
command in powershell:
docker build -t pull_request_summary .
Error:
Traceback (most recent call last):
File "/usr/app/src/./listPullRequest.py", line 1, in
import requests
ModuleNotFoundError: No module named 'reques... | [
"your container also must have requests installed on it\nIn your docker file put this line\nRUN pip install requests\n\n",
"I had this same error even when including RUN pip install requests in the Dockerfile. My solution was to change from:\nCMD ./myscript.py\n\nto:\nCMD [ \"python\", \"./myscript.py\" ]\n\n"
] | [
0,
0
] | [] | [] | [
"docker",
"powershell",
"python"
] | stackoverflow_0073590510_docker_powershell_python.txt |
Q:
python regex relace for wildcard
I am trying to apply regex on python for following code.
Country_name = "usa_t1_usq_t1_[0-9]*.csv"
new_result = re.sub(r'(?:_[[0-9-]+].*[a-zA-Z])+', '', Country_name)
# Display the Content
print(new_result)
The problem here is its working for above input, but not working for inpu... | python regex relace for wildcard | I am trying to apply regex on python for following code.
Country_name = "usa_t1_usq_t1_[0-9]*.csv"
new_result = re.sub(r'(?:_[[0-9-]+].*[a-zA-Z])+', '', Country_name)
# Display the Content
print(new_result)
The problem here is its working for above input, but not working for input without [0-9] pattern (3rd input in ... | [
"IIUC,\ninputs = ['usa_t1_usq_t1_[0-9]*.csv', 'usa_t1_usq_t1_[0-9]*.gzip.csv', 'usa_t1_usq_t1.gzip.csv']\nfor Country_name in inputs:\n result = re.sub('(_\\[0\\-9\\]\\*)?(\\.[a-zA-Z]+)+', '', Country_name)\n print(result)\n# usa_t1_usq_t1\n# usa_t1_usq_t1\n# usa_t1_usq_t1\n\n(_\\[0\\-9\\]\\*) matches the pla... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074312858_python_regex.txt |
Q:
I've tried to use the command pairs = list(itertools.combinations(nn[:4], 2)) on python but keep getting errors. I've read up but still don't get it
I've tried the command pairs = list(itertools.combinations(nn[:4], 2), in various different ways and I keep getting errors. The most recent way I've tried is list(ite... | I've tried to use the command pairs = list(itertools.combinations(nn[:4], 2)) on python but keep getting errors. I've read up but still don't get it | I've tried the command pairs = list(itertools.combinations(nn[:4], 2), in various different ways and I keep getting errors. The most recent way I've tried is list(itertools.combinations(g.nodes([None:4:None]),2). How else can I pair nodes not including 4?
I've tried the command pairs = list(itertools.combinations(nn[:4... | [
"itertools.combinations is doing exactly what you're asking of it, either A) your input data needs filtering or B) your output data needs filtering.\nIf I assume your data is completely random, and the goal is to ignore and filter out any case of the number 4:\nimport itertools\nimport random\ninput = [random.randr... | [
0
] | [] | [] | [
"combinations",
"python",
"python_itertools"
] | stackoverflow_0074312755_combinations_python_python_itertools.txt |
Q:
Filter Python 2D Array based on 2nd Element
I have a python 2D array like this:
array = [('aaa', 20), ('bbb', 30), ('ccc', 40), ('ddd', 50)]
I want to filter this array based on the 2nd value in each set.
for example I want to keep only the items having the 2nd item >= 40
Expected output:
filtered_array = [('ccc... | Filter Python 2D Array based on 2nd Element | I have a python 2D array like this:
array = [('aaa', 20), ('bbb', 30), ('ccc', 40), ('ddd', 50)]
I want to filter this array based on the 2nd value in each set.
for example I want to keep only the items having the 2nd item >= 40
Expected output:
filtered_array = [('ccc', 40), ('ddd', 50)]
I can achieve this with loo... | [
"You can use filter, but under the hood, it still uses a loop, because how else?\nlist(filter(lambda x: x[1] >= 40, array))\n#[('ccc', 40), ('ddd', 50)]\n\nOr you can use itertools.filterfalse (with the same footnote):\nlist(itertools.filterfalse(lambda x: x[1] < 40, array))\n#[('ccc', 40), ('ddd', 50)]\n\n",
"Cl... | [
0,
-1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074312933_arrays_numpy_python.txt |
Q:
Label not changing in window - tkinter
I have this code that I'm following from a video. This is a function that gets activated when a button is pressed. In some parts I want to erase the previous output in a label every time the button is pressed:
# Search customers
def search_customers():
search_customers = ... | Label not changing in window - tkinter | I have this code that I'm following from a video. This is a function that gets activated when a button is pressed. In some parts I want to erase the previous output in a label every time the button is pressed:
# Search customers
def search_customers():
search_customers = Tk()
search_customers.title("Search Cust... | [
"If you want to change the texts of Label widgets regularily, it pays to use the parameter textvariable. It takes a StringVar() object that can be changed by any function. As soon as the StringVar gets a new value, the label changes.\nI do not see the whole of your program, but this is how it works in general:\ndef... | [
0
] | [] | [] | [
"label",
"python",
"tkinter"
] | stackoverflow_0074312719_label_python_tkinter.txt |
Q:
Retrieving New Record of PostgreSQL Database in Python
In database table, Second and third columns have numbers. There will be added new rows constantly.
-Each time, whenever new rows added in database table, python needs to check them constantly.
*When the new row's number received in the .sql table drops below 1... | Retrieving New Record of PostgreSQL Database in Python | In database table, Second and third columns have numbers. There will be added new rows constantly.
-Each time, whenever new rows added in database table, python needs to check them constantly.
*When the new row's number received in the .sql table drops below 105, the python should print a Notification message. "Warning... | [
"If you want to check the new row value in 3rd column then\nif result[2] < 105:\n print(\"Warning! The number has dropped below 105.\")\nelif result[2] > 115:\n print(\"The number is higher than 115\")\n\nfetchone() returns a tuple of data from the row this is the first row.\nBut you have to fetch last entry ... | [
1
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0074312984_postgresql_python.txt |
Q:
Why we need to create another variable to work with dummy node in LinkedList
I have a Linked List called list1 = [1,2,4]. I tried to copy it to a new Linked List call dummy.
dummy = ListNode()
while list1:
dummy.next = list1
list1 = list1.next
dummy = dummy.next
... | Why we need to create another variable to work with dummy node in LinkedList | I have a Linked List called list1 = [1,2,4]. I tried to copy it to a new Linked List call dummy.
dummy = ListNode()
while list1:
dummy.next = list1
list1 = list1.next
dummy = dummy.next
return dummy
and
dummy = ListNode()
head = dummy
... | [
"ListNode is probably a class that has been defined something like the following:\nclass ListNode:\n def __init__(self, value=None):\n self.value = value\n self.next = None\n\nI believe you can solve the problem very easily like this:\ndummy=list1\nreturn dummy\n\nIn your first snippet of code, you... | [
0
] | [] | [] | [
"linked_list",
"python"
] | stackoverflow_0074312103_linked_list_python.txt |
Q:
Minimax algorithm for ConnectX not working as expected
I am currently following the Introduction to Game AI course on Kaggle Learn. This is my code for the exercise N-step Lookahead, but I could not get it to work. My agent cannot even do simple moves like blocking the opponent (random agent) from winning.
Here's ... | Minimax algorithm for ConnectX not working as expected | I am currently following the Introduction to Game AI course on Kaggle Learn. This is my code for the exercise N-step Lookahead, but I could not get it to work. My agent cannot even do simple moves like blocking the opponent (random agent) from winning.
Here's the code to my agent:
def my_agent(obs, config):
##... | [
"After an hour, I figured out my mistake. It was a very silly one.\nIn the drop_piece function, the correct line should be\nnext_grid[row][col] = mark\n\nBut I wrote:\nnext_grid[row][col] == mark\n\nEverything is working fine now.\n"
] | [
0
] | [] | [] | [
"game_ai",
"kaggle",
"minimax",
"python"
] | stackoverflow_0074312651_game_ai_kaggle_minimax_python.txt |
Q:
pandas filter by a range of datetime after grouby
I'd like to calculate the change in each student's score for each subject over time, based on a period of time.
For example:
Here is the original table
Datetime
Student
Subject
Score
2021-01-01
A
Math
70
2021-03-01
A
Physics I
80
2021-02-01
A
Physics I
80
2021... | pandas filter by a range of datetime after grouby | I'd like to calculate the change in each student's score for each subject over time, based on a period of time.
For example:
Here is the original table
Datetime
Student
Subject
Score
2021-01-01
A
Math
70
2021-03-01
A
Physics I
80
2021-02-01
A
Physics I
80
2021-02-15
A
Math
90
2021-02-01
B
Physics I
95
... | [
"Use Series.between for filter before DataFrameGroupBy.diff and assign only filtered rows:\ndf['Datetime'] = pd.to_datetime(df['Datetime'])\n\ndf = df.sort_values(['Student','Subject'])\n\nperiod_time = [(pd.to_datetime('2021-01-01'), pd.to_datetime('2021-02-10')),\n (pd.to_datetime('2021-02-14'), pd.... | [
0
] | [] | [] | [
"datetime",
"filter",
"pandas",
"python"
] | stackoverflow_0074312973_datetime_filter_pandas_python.txt |
Q:
How to avoid global variables in tkinter?
I've recently been using Tkinter and I'm usually running into this problem:
Let's say I have to clear a label every time I press a button to show something different to avoid the previous output mixing with the new content of the label. I made a code example to show what I... | How to avoid global variables in tkinter? | I've recently been using Tkinter and I'm usually running into this problem:
Let's say I have to clear a label every time I press a button to show something different to avoid the previous output mixing with the new content of the label. I made a code example to show what I mean:
from tkinter import *
root = Tk()
root.... | [
"Does this help? This will prevent global. I put two widget Labels outside of function You will see no effect on Label.\nfrom tkinter import *\n\nroot = Tk()\nroot.minsize(200, 200)\n\n \ndef click():\n if entry_1.get() == '1': \n label_1.grid(row=2, column=0)\n label_2.grid_remove()\n\n ... | [
0,
0
] | [] | [] | [
"global_variables",
"label",
"python",
"tkinter"
] | stackoverflow_0074310965_global_variables_label_python_tkinter.txt |
Q:
How to get event wise frequency and the frequency of each event in a dataframe?
I have a dataset like:
Data
a
a
a
a
a
b
b
b
a
a
b
I want to add a column that looks like the one below. The data will be in the form of a1,1 in the column, where the first element represent the event frequency (a1) and th... | How to get event wise frequency and the frequency of each event in a dataframe? | I have a dataset like:
Data
a
a
a
a
a
b
b
b
a
a
b
I want to add a column that looks like the one below. The data will be in the form of a1,1 in the column, where the first element represent the event frequency (a1) and the second element (,1) is the frequency for each event. Is there a way we can do this ... | [
"You can use:\n# identify changes in Data\nm = df['Data'].ne(df['Data'].shift()).cumsum()\n# cumulated increments within groups\ng1 = df.groupby(m).cumcount().add(1).astype(str)\n\n# increments of different subgroups per Data\ng2 = (df.loc[~m.duplicated(), 'Data']\n .groupby(df['Data']).cumcount().add(1)\n ... | [
3,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074013733_dataframe_pandas_python_python_3.x.txt |
Q:
How can i convert my hex values to binary in Python? binascii.a2b_hex error
Hello when I use binascii.a2b_hex, error is occured.
There is no error message but the return value is wrong.
Here is the data and the resule.
Input : FEB10AA86764FFFF
Output : b'\xfe\xb1\n\xa8gd\xff\xff'
import binascii
ta['data'] = ta['... | How can i convert my hex values to binary in Python? binascii.a2b_hex error | Hello when I use binascii.a2b_hex, error is occured.
There is no error message but the return value is wrong.
Here is the data and the resule.
Input : FEB10AA86764FFFF
Output : b'\xfe\xb1\n\xa8gd\xff\xff'
import binascii
ta['data'] = ta['data'].apply(binascii.a2b_hex)
n\xa8gd <- what it happend? how can i fix it?
I... | [
"It's actually working fine. What's confusing you is the output as a bytestring. If a byte is a valid printable character it will output the character, otherwise it will put out an escape sequence.\nFE \\xfe\nB1 \\xb1\n0A \\n\nA8 \\xa8\n67 g\n64 d\nFF \\xff\nFF \\xff\n\n",
"What you are seeing is Python... | [
2,
1,
0
] | [] | [] | [
"bin",
"binascii",
"hex",
"python"
] | stackoverflow_0074311664_bin_binascii_hex_python.txt |
Q:
Is there anyway to read .one(OneNote files) using Python script?
I am trying to read .one file(OneNote files) and want to write its content into a text file, but didn't find a single way to do it using Python. Please help me with this.
A:
Try to get the content of your notes calling:
./me/onenote/pages/1-1c13bcb... | Is there anyway to read .one(OneNote files) using Python script? | I am trying to read .one file(OneNote files) and want to write its content into a text file, but didn't find a single way to do it using Python. Please help me with this.
| [
"Try to get the content of your notes calling:\n./me/onenote/pages/1-1c13bcbae2fdd747a95b3e5386caddf1!1-xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxx/content?includeIDs=true&includeInkML=true&preAuthenticated=true\n\n\nIt will give you text/html, which you can parse with https://pypi.org/project/lxml/\n",
"I didn't find a good... | [
0,
0
] | [] | [] | [
"onenote",
"onenote_api",
"python"
] | stackoverflow_0052813670_onenote_onenote_api_python.txt |
Q:
Cobertura coverage report not showing in MR's diff
I have recently added the cobertura coverage report to my repository, but it still does not show the coverage in an MR's diff.
Here is the job of my .gitlab-ci.yml that generates the coverage report:
coverage-report:
stage: coverage
script:
- tox -e covera... | Cobertura coverage report not showing in MR's diff | I have recently added the cobertura coverage report to my repository, but it still does not show the coverage in an MR's diff.
Here is the job of my .gitlab-ci.yml that generates the coverage report:
coverage-report:
stage: coverage
script:
- tox -e coverage-report
coverage: '/(?i)total.*? (100(?:\.0+)?\%|[1-... | [
"Give coverage_report in this form.\n artifacts:\n expire_in: 1 week\n paths:\n - public/coverage\n reports:\n coverage_report:\n coverage_format: cobertura\n path: public/coverage/coverage.xml\n\nAlso at times it can take some time for the coverage to be reflected in the diff. Git... | [
0
] | [] | [] | [
"code_coverage",
"gitlab",
"gitlab_ci",
"python",
"tox"
] | stackoverflow_0074309711_code_coverage_gitlab_gitlab_ci_python_tox.txt |
Q:
How to get molecular weight of a compound in python?
User inputs a formula, for example: C12H2COOH
We have to calculate its molecular weight given that C = 12.01, H = 1.008 and O = 16.
We were told to be careful of elements with double digits after it and elements with no numbers after it. The program also keeps a... | How to get molecular weight of a compound in python? | User inputs a formula, for example: C12H2COOH
We have to calculate its molecular weight given that C = 12.01, H = 1.008 and O = 16.
We were told to be careful of elements with double digits after it and elements with no numbers after it. The program also keeps asking for a chemical formula and exits when you press ente... | [
"First thing I'd do is replace each occurrence of a letter in the input string by the same letter preceded by a '+', so\nC12H2COOH => +C12+H2+C+O+O+H\n\nnext, I'd replace each occurrence of a letter followed by a digit by the same letter followed by a '*' and then the digit\n+C12+H2+C+O+O+H => +C*12+H*2+C+O+O+H\n\n... | [
6,
6,
4,
2,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0016699180_python_python_3.x.txt |
Q:
Dash Cytoscape data from js script
I'm trying to get node position data from Dash Cytoscape. I found this solution https://community.plotly.com/t/dash-cytoscape-returning-node-positions-from-layout/23818/4
but I can't get data from the browser console in python. How can I do this?
A:
To get data from a js script... | Dash Cytoscape data from js script | I'm trying to get node position data from Dash Cytoscape. I found this solution https://community.plotly.com/t/dash-cytoscape-returning-node-positions-from-layout/23818/4
but I can't get data from the browser console in python. How can I do this?
| [
"To get data from a js script, you could use a Clientside Callback. As documented here, a clientside callback\n\ncreate(s) a callback that updates the output by calling a clientside (JavaScript) function instead of a Python function\n\nTo use it, you can for example write your JavaScript code into Python code like ... | [
0
] | [] | [] | [
"cytoscape",
"cytoscape.js",
"plotly_dash",
"python",
"python_3.x"
] | stackoverflow_0071511702_cytoscape_cytoscape.js_plotly_dash_python_python_3.x.txt |
Q:
How to access single columns in pandas for loop?
I've a column which has ratings like "4.1/5" I want to remove the slash (/) and it is a object type. I want to convert it to float so I'm trying to create a function to do that.
Please correct me what I'm doing wrong. I'm trying something like
def remove_slash_from_... | How to access single columns in pandas for loop? | I've a column which has ratings like "4.1/5" I want to remove the slash (/) and it is a object type. I want to convert it to float so I'm trying to create a function to do that.
Please correct me what I'm doing wrong. I'm trying something like
def remove_slash_from_rating(ratings):
for i in ratings:
df[rate... | [
"There is no loop, no apply necessary, use Series.str.replace for column rate:\ndf[\"rate\"] = df[\"rate\"].str.replace(r'/','')\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074313232_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.