content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to send discord custom emoji from any server using discord.py?
How do I send custom emoji using discord.py that is from another server?
Here is what I've tried:
@client.command()
async def sendemoji(ctx):
emoji = client.get_emoji(946753004365815878)
await ctx.send(f'{emoji}')
The result was "None"
A:... | How to send discord custom emoji from any server using discord.py? | How do I send custom emoji using discord.py that is from another server?
Here is what I've tried:
@client.command()
async def sendemoji(ctx):
emoji = client.get_emoji(946753004365815878)
await ctx.send(f'{emoji}')
The result was "None"
| [
"Your bot needs to be in the server you are trying to pull the emoji from. If it's a large server that you aren't the owner of or can't add your bot too, you can probably find the emoji online and add it to one of your own servers. From there, you can add your bot to that server and then use the emoji globally. Hop... | [
0
] | [] | [] | [
"discord",
"discord.py",
"nextcord",
"pycord",
"python"
] | stackoverflow_0074240332_discord_discord.py_nextcord_pycord_python.txt |
Q:
Python group repeating characters in list together
I want to split a string of 1s and 0s into a list of repeated groups of these characters.
Example:
m = '00001100011111000'
Goes to:
m = ['0000', '11', '000', '11111', '000']
How would I do this in efficient concise code? Would regex work for this?
A:
Yes, you ca... | Python group repeating characters in list together | I want to split a string of 1s and 0s into a list of repeated groups of these characters.
Example:
m = '00001100011111000'
Goes to:
m = ['0000', '11', '000', '11111', '000']
How would I do this in efficient concise code? Would regex work for this?
| [
"Yes, you can use re. For example:\nimport re\n\nm = \"00001100011111000\"\n\nprint([\"\".join(v) for v, _ in re.findall(r\"((.)\\2*)\", m)])\n\nPrints:\n['0000', '11', '000', '11111', '000']\n\n\nOther regex:\nprint(re.findall(r\"0+|1+\", m))\n\nPrints:\n['0000', '11', '000', '11111', '000']\n\n",
"You can use i... | [
2,
2,
1,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074249192_list_python_python_3.x.txt |
Q:
How to save a keras model when both precision and recall are better?
Using python 3.7 and tensorflow 2.1.0 I would like to know how to save the best model when both precision and recall are better.
The following code gives elements to save the best model when only the precision is better.
# some dependencies
from ... | How to save a keras model when both precision and recall are better? | Using python 3.7 and tensorflow 2.1.0 I would like to know how to save the best model when both precision and recall are better.
The following code gives elements to save the best model when only the precision is better.
# some dependencies
from tensorflow.keras.metrics import Precision, Recall
# some coding instructi... | [
"I come up with a solution, hope it will help some guys.\nclass CustomCallback(tf.keras.callbacks.Callback):\n def __init__(self, model, path, metrics):\n self.model = model\n self.path = path\n self.metrics = metrics\n self.history = []\n\n def on_epoch_end(self, epoch, logs):\n ... | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074248901_keras_python_tensorflow.txt |
Q:
Break in Condition
The user is supposed to enter a number from 1 to 10 and the code is supposed to check for 3 conditions
if the input is not a number ask for entering again, if the input is out of 1-10 ask for entering again, and if the number is in range of 1-10 break the loop and store the value in the variable... | Break in Condition | The user is supposed to enter a number from 1 to 10 and the code is supposed to check for 3 conditions
if the input is not a number ask for entering again, if the input is out of 1-10 ask for entering again, and if the number is in range of 1-10 break the loop and store the value in the variable. the first two checks a... | [
"if num_guess != int should be:\ntry:\n num_guess = int(num_guess)\nexcept ValueError:\n print(\"Not a number!\")\n continue\n\nReference: How to check if string input is a number?\n",
"The input() method takes you input and converts it into a string input. So even if you enter number 12, the input will ... | [
3,
2,
0,
0
] | [
"Replace if num_guess != int with if type(num_guess) != int.\nThis is because you need to check what data type the number is, using an equality operator with int would try to check if the object is the class int.\nIn python everything is an object (or a data type), even the constructors for objects.\n",
"If you w... | [
-1,
-1
] | [
"python"
] | stackoverflow_0074249014_python.txt |
Q:
How can I ensure that my Python version is updated after installing version 3.11 using Mac?
I've just installed Python version 3.11 (I also moved versions 3.8 and 3.9 to the trash from my Applications folder).
I can see it in the following:
$ myname@name-MBP miniconda3 % ls /usr/local/bin/py*
/usr/local/bin/pydoc3... | How can I ensure that my Python version is updated after installing version 3.11 using Mac? | I've just installed Python version 3.11 (I also moved versions 3.8 and 3.9 to the trash from my Applications folder).
I can see it in the following:
$ myname@name-MBP miniconda3 % ls /usr/local/bin/py*
/usr/local/bin/pydoc3 /usr/local/bin/python3-intel64
/usr/local/bin/pydoc3.11 /usr/local/bin/python3.... | [
"So first thing to understand is setting the variable PYTHONPATH will not affect which version of python is executed by the shell. The shell (bash/zsh) only knows to scan the paths in the PATH env var to figure out all the executables.\nNow there are two ways to solve this.\n1. Using the python@3.11 from homebrew.\... | [
1
] | [] | [] | [
"macos",
"path",
"python",
"python_3.x",
"pythonpath"
] | stackoverflow_0074244945_macos_path_python_python_3.x_pythonpath.txt |
Q:
Trying to implement a rotating image on PySide6, the rotation is right but the image is jiggling
I'm trying to have an image to be dynamically rotating depending on motors positions as for monitoring purposes and user interface interactions.
I used a sample image and simulated a constant rotation to do some tests.... | Trying to implement a rotating image on PySide6, the rotation is right but the image is jiggling | I'm trying to have an image to be dynamically rotating depending on motors positions as for monitoring purposes and user interface interactions.
I used a sample image and simulated a constant rotation to do some tests.
I could get the signals and the rotation of the Pixmap with Qtransform right, but the image itself gi... | [
"The given approach is not a good one, because it completely rotates the whole pixmap and, as the documentation explains (emphasis mine):\n\nThe transformation transform is internally adjusted to compensate for unwanted translation; i.e. the pixmap produced is the smallest pixmap that contains all the transformed p... | [
0
] | [] | [] | [
"pyqt6",
"pyside6",
"python"
] | stackoverflow_0074244010_pyqt6_pyside6_python.txt |
Q:
gym RL with MultiDiscrete ActionSpace AttributeError: 'MultiDiscrete' object has no attribute 'spaces'
I'm trying to build an Reinforcement Learning Algorithm, which can play the MasterMind Game. I'm using an MultiDiscrete Anction and Observation Space. The Action Space takes 4 slots with 6 colors each and the Ob... | gym RL with MultiDiscrete ActionSpace AttributeError: 'MultiDiscrete' object has no attribute 'spaces' | I'm trying to build an Reinforcement Learning Algorithm, which can play the MasterMind Game. I'm using an MultiDiscrete Anction and Observation Space. The Action Space takes 4 slots with 6 colors each and the Observation Space is 2x4. I created an Custom Environment to connect with my programmed game. The Environment ... | [
"observation_space = MultiDiscrete(np.array([4,4]), dtype=int)\n...\nmodel = A2C(MultiInputActorCriticPolicy, env)\n...\nfor key, subspace in observation_space.spaces.items():\n\nMultiInput should not be needed for a MultiDiscrete space. It is still only one observation space while MultiInput is needed when providi... | [
0
] | [] | [] | [
"artificial_intelligence",
"openai_gym",
"python",
"reinforcement_learning",
"stable_baselines"
] | stackoverflow_0074152052_artificial_intelligence_openai_gym_python_reinforcement_learning_stable_baselines.txt |
Q:
Python: use time.sleep with opencv without stopping the video footage
Im using opencv for detecting a hand gesture (in this case, when i lift my index finger), when that happens it prints "hi", then i use time.sleep to pause the print for 1 second because it will print it until I put my index down, but time.sleep ... | Python: use time.sleep with opencv without stopping the video footage | Im using opencv for detecting a hand gesture (in this case, when i lift my index finger), when that happens it prints "hi", then i use time.sleep to pause the print for 1 second because it will print it until I put my index down, but time.sleep pauses the entire footage, so if i sleep 5 seconds, the footage wont run un... | [
"I tried to use 2 separate threads for the entire while loop and another one for the sleep, it´s not sleeping.\ndef sleep():\n time.sleep(2)\n\ndef main_loop():\n while True:\n #all the opencv initial stuff\n #mediapipe functions for the hand detection\n\n if INDEX_UP:\n print(\"hi\")\n th.Thread(targe... | [
0,
0
] | [] | [] | [
"opencv",
"python",
"sleep"
] | stackoverflow_0074248962_opencv_python_sleep.txt |
Q:
python setup.py bdist_wheel did not run successfully (python 3.10)
i'm new to data science and i need to install scikit-surprise on my M1 chip using python 3.10. But i get this error instead. Somehow i get this message often with python 3.10.
i only install with pip
%pip install scikit-surprise
and i get this erro... | python setup.py bdist_wheel did not run successfully (python 3.10) | i'm new to data science and i need to install scikit-surprise on my M1 chip using python 3.10. But i get this error instead. Somehow i get this message often with python 3.10.
i only install with pip
%pip install scikit-surprise
and i get this error. what should i do?
python setup.py bdist_wheel did not run successfull... | [
"Try running\npip install wheel\n\nbefore running pip install scikit-surprise\n",
"Try\npip install attrdict3\n\nit worked for me\n"
] | [
0,
0
] | [] | [] | [
"apple_m1",
"pip",
"python"
] | stackoverflow_0073286297_apple_m1_pip_python.txt |
Q:
Pandas hist how to set bins by slice step
For example, there is a dataset of vacancies with salary mentioned, so I want to make a histogram showing the distribution of salaries by number of vacancies. I want to organise bins by regular steps, e.g. a new bin every 50000 "money". I can write them directly, like in d... | Pandas hist how to set bins by slice step | For example, there is a dataset of vacancies with salary mentioned, so I want to make a histogram showing the distribution of salaries by number of vacancies. I want to organise bins by regular steps, e.g. a new bin every 50000 "money". I can write them directly, like in documentation:
df['salary'].hist(bins=(50000, 10... | [
"what about bins=[bin for bin in range(0, 2000000, 50000)]\nto calculate the max use\n[bin for bin in range(0, df['salary'].max()+50000, 50000)]\n\n"
] | [
2
] | [] | [] | [
"histogram",
"pandas",
"python"
] | stackoverflow_0074249327_histogram_pandas_python.txt |
Q:
pygame mixer music change playback speed
I want to playback an .mp3 file at 50% it's original speed, naturally pitched down (i.e. keeping the pitch is not my requirement).
I am using pygame.mixer and found several solutions (such as this one) that suggest changing the frequency on initialization should do the job ... | pygame mixer music change playback speed | I want to playback an .mp3 file at 50% it's original speed, naturally pitched down (i.e. keeping the pitch is not my requirement).
I am using pygame.mixer and found several solutions (such as this one) that suggest changing the frequency on initialization should do the job as shown below, however that does not work for... | [
"One way to do this would be to use this Audio Slowdown Software.]1\nThis would have the advantage of being easily reusable without having to type extra code or extra lines.\n"
] | [
0
] | [] | [] | [
"audio",
"pygame",
"python"
] | stackoverflow_0074204907_audio_pygame_python.txt |
Q:
Serverless flask python application - No module named 'numpy.core._multiarray_umath' when using Numpy
The numpy package fails to import when running in the lambda function after deploying. I am not sure what the issue is but the numpy module simply just fails to finish importing with the following error:
ModuleNot... | Serverless flask python application - No module named 'numpy.core._multiarray_umath' when using Numpy | The numpy package fails to import when running in the lambda function after deploying. I am not sure what the issue is but the numpy module simply just fails to finish importing with the following error:
ModuleNotFoundError: No module named 'numpy.core._multiarray_umath'
the outputted versions are as follows:
* The P... | [
"The issue was being triggered by the numpy module not importing correctly inside of lambda at runtime.\nThis was caused by the incorrect architecture being used to deploy the lambda function, as my local setup did not match the environment lambda operates in.\nI used a docker image to solve this and the module imp... | [
0
] | [] | [] | [
"aws_lambda",
"python",
"serverless"
] | stackoverflow_0074055014_aws_lambda_python_serverless.txt |
Q:
Most efficient way to find and replace 'None' cells with value from a similar cell pair in dataframe?
I'm trying to find the most efficient way to fill in cells with a value of 'None' in a dataframe based on a rule.
If column 'A' has a specific value, such as 'Apple', and column 'B' is empty, I want to find all ot... | Most efficient way to find and replace 'None' cells with value from a similar cell pair in dataframe? | I'm trying to find the most efficient way to fill in cells with a value of 'None' in a dataframe based on a rule.
If column 'A' has a specific value, such as 'Apple', and column 'B' is empty, I want to find all other instances of column 'A' with value 'Apple' and fill it with whatever is in column 'B's if it is not emp... | [
"Filter rows with no None values, remove duplicates and convert to Series, last mapping None values by Series.map:\nm = df['Column B'].ne('None')\ns = df[m].drop_duplicates('Column A').set_index('Column A')['Column B']\ndf.loc[~m, 'Column B'] = df.loc[~m, 'Column A'].map(s)\n\nprint (df)\n Column A Column B\n0 ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074249450_dataframe_pandas_python.txt |
Q:
`random.seed` doesn't work with generators
I have a function that generates a sequence of random integers using random.randint. I also include a seed parameter for reproducibility.
I noticed an odd behavior when I returned a generator object. Different calls with the same seed did not return the same result. Howev... | `random.seed` doesn't work with generators | I have a function that generates a sequence of random integers using random.randint. I also include a seed parameter for reproducibility.
I noticed an odd behavior when I returned a generator object. Different calls with the same seed did not return the same result. However, when I returned a tuple instead of a generat... | [
"The generator expression is evaluated later, lazily,\nand it has side effects on the PRNG.\nYou will find it much easier to reason about your\nalgorithm if you first store PRNG outputs in a container,\nsuch as a tuple or list.\nSpecifically, if your code produced\nfirst = [f0, f1, f2, ..., f9]\nsecond = [s0, s1, s... | [
1
] | [] | [] | [
"generator",
"python",
"random",
"random_seed"
] | stackoverflow_0074249443_generator_python_random_random_seed.txt |
Q:
Numberlong to datetime format conversion
I have a column in my dataframe, which I want to convert to an acceptable date format, so that I can plot it using plotly.
I tried the following methods to get it to work, but I believe the input string is supposed to be in the same format.
`
df['InsertedDate'] = pd.to_date... | Numberlong to datetime format conversion | I have a column in my dataframe, which I want to convert to an acceptable date format, so that I can plot it using plotly.
I tried the following methods to get it to work, but I believe the input string is supposed to be in the same format.
`
df['InsertedDate'] = pd.to_datetime(df['InsertedDate'], format='%Y%m%d')
df[... | [
"I believe unit='ms' might be what you are looking for:\ndf['commitDate'] = pd.to_datetime(df['commitDate'], unit='ms')\n\ndf\n\nwill produce this:\n\n"
] | [
1
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074249502_datetime_pandas_python.txt |
Q:
WxPython wxSplitterWindow.SplitVertically always shows uneven split
I'm trying to understand how to use the wxSplitterWindow class but can't seem to get a vertical split to be even (i.e. left and right panes each take up the same amount of space). According to the wxPython 3.03 documentation, wxSplitterWindow.Spli... | WxPython wxSplitterWindow.SplitVertically always shows uneven split | I'm trying to understand how to use the wxSplitterWindow class but can't seem to get a vertical split to be even (i.e. left and right panes each take up the same amount of space). According to the wxPython 3.03 documentation, wxSplitterWindow.SplitVertically has the following signature:
SplitVertically(self, window1, w... | [
"I had the same problem, by trial, and error I get that this modification solved the problem\nself.splitter.SplitHorizontally(self.leftPanel, self.rightPanel, 100)\n\nBut this is dependent on the size of the frame.\nI'm using wxpython version 3.0.0.0\n",
"I know this thread is ancient, but in case anyone else has... | [
0,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0032195823_python_wxpython.txt |
Q:
How to incorporate individual measurement uncertainties into Gaussian Process?
I have a set of observations, f_i=f(x_i), and I want to construct a probabilistic surrogate, f(x) ~ N[mu(x), sigma(x)], where N is a normal distribution. Each observed output, f_i, is associated with a measurement uncertainty, sigma_i. ... | How to incorporate individual measurement uncertainties into Gaussian Process? | I have a set of observations, f_i=f(x_i), and I want to construct a probabilistic surrogate, f(x) ~ N[mu(x), sigma(x)], where N is a normal distribution. Each observed output, f_i, is associated with a measurement uncertainty, sigma_i. I would like to incorporate these measurement uncertainties into my surrogate, f_i, ... | [
"As @amance has suggested, you need to square errs - see this scikit example. However, the resulting means and standard deviations don't seem to tie up with your Monte-Carlo results, and increasing the number of calibrations and paths does not seem to improve the situation. I do not know how to explain the discrepa... | [
2,
1
] | [] | [] | [
"gaussian_process",
"python",
"scikit_learn",
"uncertainty"
] | stackoverflow_0074151442_gaussian_process_python_scikit_learn_uncertainty.txt |
Q:
Dataframe on PyPy
PyPy does a great job in accelerating my code (for the portion of the code where Pandas is not used). However, when it comes to using Pandas on PyPy, as expected, it is not speeding up the code that much. I am looking for a way to replace that part of the code with few lines of code that does not... | Dataframe on PyPy | PyPy does a great job in accelerating my code (for the portion of the code where Pandas is not used). However, when it comes to using Pandas on PyPy, as expected, it is not speeding up the code that much. I am looking for a way to replace that part of the code with few lines of code that does not rely on Pandas such th... | [
"You complain that your code runs more slowly than desired.\n\nbenefit from the full power of PyPy.\n\nWell, PyPy can loop through a million iterations faster than\nthe cPython bytecode interpreter, and cython can go faster still.\nBut your difficulty seems to be with your algorithm,\nstarting with allocating stora... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"pypy",
"python"
] | stackoverflow_0074249344_dataframe_pandas_pypy_python.txt |
Q:
Access a discord account via token and post messages in every channel
So i can't figure out how to login into a discord account with a token and then post a message in every channel of every server the user is in. I know this might be against discord tos but I still wanna know. Is that possible with python?
I know... | Access a discord account via token and post messages in every channel | So i can't figure out how to login into a discord account with a token and then post a message in every channel of every server the user is in. I know this might be against discord tos but I still wanna know. Is that possible with python?
I know how to let a bot do it but not how u can do it with an account.
| [
"Please read the discord API docs next time\napi = \"https://canary.discord.com/api/v8\"\nmessage = \"\"\nguilds = requests.get(\n f\"{api}/users/@me/guilds\",\n headers=headers\n).json()\n\nfor guild in guilds:\n channels = requests.get(\n f\"{api}/guilds/{guild['id']}/channels\",\n headers ... | [
0
] | [] | [] | [
"discord",
"python"
] | stackoverflow_0074248711_discord_python.txt |
Q:
How to trim down a Pandas data frame rows?
I'm trying so hard to shorten this awful lot of rows from an XML sitemap but I can't find a solution to trim it down.
import advertools as adv
import pandas as pd
site = "https://www.halfords.com/sitemap_index.xml"
sitemap = adv.sitemap_to_df(site)
sitemap = sitemap.dro... | How to trim down a Pandas data frame rows? | I'm trying so hard to shorten this awful lot of rows from an XML sitemap but I can't find a solution to trim it down.
import advertools as adv
import pandas as pd
site = "https://www.halfords.com/sitemap_index.xml"
sitemap = adv.sitemap_to_df(site)
sitemap = sitemap.dropna(subset=["loc"]).reset_index(drop=True)
... | [
"Two things:\n\nYou can use adv.url_to_df to split URLs and get the slugs (there should be a column called last_dir:\n\nurldf = adv.url_to_df(sitemap['loc'].dropna())\nurldf\n\n\n\n\n\n\nurl\nscheme\nnetloc\npath\nquery\nfragment\ndir_1\ndir_2\ndir_3\ndir_4\ndir_5\ndir_6\ndir_7\ndir_8\ndir_9\nlast_dir\n\n\n\n\n0\nh... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074220705_python.txt |
Q:
About python vaex merging columns to a new column while changing int to float
I am able to write a function to merge columns to a new column, but fail to change int column into float before changing to string for merging.
I hope that in the new merged column, those integer would have pending ".00000".
At the end I... | About python vaex merging columns to a new column while changing int to float | I am able to write a function to merge columns to a new column, but fail to change int column into float before changing to string for merging.
I hope that in the new merged column, those integer would have pending ".00000".
At the end I was trying to make merged column as key for joining two vaex on multiple key/colum... | [
"It looks like the vaex expression system does not always play nicely with the try / except checks. So you need to be careful with the dtypes. One way of handing this:\nimport vaex\n\ndf = vaex.datasets.titanic() # dataframe for testing\n\ndef new_column_by_column_merging2(df, columns=None):\n if columns is Non... | [
0
] | [] | [] | [
"python",
"vaex"
] | stackoverflow_0074241870_python_vaex.txt |
Q:
Are there separate call tree depths for recursive and non-recursive calls?
As we all know, if you have a function like this:
def foo():
foo()
The function will call itself 1000 times and then you get a RecursionError exception.
But what if you had a thousand and one different functions that call each other? ... | Are there separate call tree depths for recursive and non-recursive calls? | As we all know, if you have a function like this:
def foo():
foo()
The function will call itself 1000 times and then you get a RecursionError exception.
But what if you had a thousand and one different functions that call each other? i.e. a() calls b() calls c() and so on.
Would you get any sort of error at the 1... | [
"RecursionError is thrown when the call stack is exceeded. This most commonly occurs due to recursion, but it can occur in general.\nTo test this, we can write a quick for loop to generate a couple hundred different functions that call each other.\n\nfunction = lambda: \"Success!\"\nfor _i in range(999):\n def n... | [
2
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074249497_python_recursion.txt |
Q:
import cv2 >> ModuleNotFoundError: No module named 'cv2'
import cv2
ModuleNotFoundError: No module named 'cv2'
although it already installed but run in cmd only
not working in any IDE like Vs or spyder or Jupyter
i wanna to make IDE import OpenCv
A:
try:
import opencv-python
except:
subprocess.che... | import cv2 >> ModuleNotFoundError: No module named 'cv2' | import cv2
ModuleNotFoundError: No module named 'cv2'
although it already installed but run in cmd only
not working in any IDE like Vs or spyder or Jupyter
i wanna to make IDE import OpenCv
| [
"try:\n import opencv-python\nexcept:\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", 'opencv-python'])\n\nAlternatively, open a console in your IDE and execute the following:\npip install opencv-python\nYour IDE probably uses a different python instance to the one your console uses\n"
] | [
-1
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074249283_opencv_python.txt |
Q:
Python client for Managing Kafka ACL
Do we have any python client for managing Kafka ACL?
I know we have Java Admin client and same can be performed using Kafka scripts (kafka-acl.sh) but cannot find one for python client.
confluent python library doesn't support it. Came across kafka-python but as per documentati... | Python client for Managing Kafka ACL | Do we have any python client for managing Kafka ACL?
I know we have Java Admin client and same can be performed using Kafka scripts (kafka-acl.sh) but cannot find one for python client.
confluent python library doesn't support it. Came across kafka-python but as per documentation it doesn't support creating ACL for exi... | [
"Use kafka-python lib\nconfigure acl, new add, example:\nUser user1 has read access to topic2 and group2 groups (consumer)\nUser user2 has write permission on topic2 (producer)\nfrom kafka.admin import KafkaAdminClient, ACLPermissionType, ResourcePattern, ResourceType, ACL, ACLOperation, ACLFilter\n\nbrokers = 'loc... | [
0
] | [] | [] | [
"apache_kafka",
"confluent_kafka_python",
"kafka_python",
"python"
] | stackoverflow_0072347000_apache_kafka_confluent_kafka_python_kafka_python_python.txt |
Q:
Python: access to variables defined in nested class functions
Here I defined a class with custom ___mul__ operator.
Inside the __mul__ operator I define a _backward function that use an argument to that function (other variable ).
How does python keep track of the other variable when I call the _backward function ... | Python: access to variables defined in nested class functions | Here I defined a class with custom ___mul__ operator.
Inside the __mul__ operator I define a _backward function that use an argument to that function (other variable ).
How does python keep track of the other variable when I call the _backward function on out.
Does it internally keep track of the scope in which the fun... | [
"In Python, first, it will check if there is a local variable (local to _backward function) called other. Then it will check in the outer scope which is __mul__, then it will check in the global scope, i.e., a variable declared in the zero level of indentation.\nlocal variable to _backward\nclass Value:\n ...\n ... | [
1
] | [] | [] | [
"function",
"nested",
"python",
"python_3.x",
"scope"
] | stackoverflow_0074249603_function_nested_python_python_3.x_scope.txt |
Q:
ModuleNotFoundError: No module named 'allennlp.data.iterators'
In Google colab I am to trying import BucketIterator using:
from allennlp.data.iterators import BucketIterator
But it is raising the same error again and again-
ModuleNotFoundError: No module named 'allennlp.data.iterators
After installing allennlp ... | ModuleNotFoundError: No module named 'allennlp.data.iterators' | In Google colab I am to trying import BucketIterator using:
from allennlp.data.iterators import BucketIterator
But it is raising the same error again and again-
ModuleNotFoundError: No module named 'allennlp.data.iterators
After installing allennlp with the imports:
from allennlp.data.token_indexers import TokenInde... | [
"I was facing the same issue.\nIt won't work, since Iterators are removed from allennlp.\n",
"Install a legacy version of allennlp. allennlp is depended upon the PyTorch(torchtext) library. And since torchtext removed iterators form their newer versions allennlp did it too.\nYou can directly use torchtext.data.Bu... | [
0,
0
] | [] | [] | [
"debugging",
"nlp",
"python",
"pytorch"
] | stackoverflow_0064022499_debugging_nlp_python_pytorch.txt |
Q:
Name Error when defining function inside other function
I am creating a text based game and trying to define the next function with an if/else statement so that the player can decide if they want to progress in the game or not. It is working on the previous line but stops working in the nested else statement.
def... | Name Error when defining function inside other function | I am creating a text based game and trying to define the next function with an if/else statement so that the player can decide if they want to progress in the game or not. It is working on the previous line but stops working in the nested else statement.
def Baker_Street ():
print("""
A man named Henry Knight ... | [
"The error message clearly tells you what the error is:\nNameError: name 'dartmoor_inn' is not defined\n\nSo the code is calling a function which has not yet been defined !\nThe code in the question is also missing an import:\nimport time as t\n\nAnd also, clear() is not a function, so it needs to be removed.\nFina... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074249576_python.txt |
Q:
I want to know the url pip has used to download a package (.whl file)
I need a list of URLs that pip is using to download packages from the internet preferably using a list of python packages in a requirements.txt file.
Do you know a quick and easy solution to this problem? Maybe there is a tool out there or a fea... | I want to know the url pip has used to download a package (.whl file) | I need a list of URLs that pip is using to download packages from the internet preferably using a list of python packages in a requirements.txt file.
Do you know a quick and easy solution to this problem? Maybe there is a tool out there or a feature of pip that I'm unaware of?
I need to know the download urls without i... | [
"You could use the pip show <package-name> command in the command prompt. This will display the url where the package can be found under Home-page.\nFor example:\n> pip show gym\nName: gym\nVersion: 0.26.1\nSummary: Gym: A universal API for reinforcement learning environments\nHome-page: https://www.gymlibrary.dev/... | [
0,
0,
0
] | [] | [] | [
"pip",
"pypi",
"python"
] | stackoverflow_0074241809_pip_pypi_python.txt |
Q:
Why can't the for-loop skip to the next if condition I have set if it does not meet the first one?
I'm trying to have a function use the autokey cipher to encrypt a message. The function has an if statement telling it whether to use the uppercase ASCII letters or lower case. I do not understand why that if stateme... | Why can't the for-loop skip to the next if condition I have set if it does not meet the first one? | I'm trying to have a function use the autokey cipher to encrypt a message. The function has an if statement telling it whether to use the uppercase ASCII letters or lower case. I do not understand why that if statement is not working. If the letter getting ciphered is lowercase, it should use the lowercase list, but th... | [
"Nothing wrong with the if statement, its your algorithm that needs a little tweaking. Take a look at this statement for example:\n(alphau.index(letter)+alphau.index(key[i]))%26\n\nas per your input\nplaintext = \"MyNameIsMhegazy\"\nkey = \"jMiXMyNameIsMahm\"\n\non the first iteration, the letter is \"M\", i = 0, s... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074249613_python.txt |
Q:
Following pagination next page links is not working with scrapy. My CSS selector is not selecting the href for next page
I'm trying to scrape https://www.realtor.com/ to get rental information. I want to scrape all pages
I have been continuously having this problem of not being to follow the href to the next page ... | Following pagination next page links is not working with scrapy. My CSS selector is not selecting the href for next page | I'm trying to scrape https://www.realtor.com/ to get rental information. I want to scrape all pages
I have been continuously having this problem of not being to follow the href to the next page using scrapy. I think my problem is I'm not actually selecting the href of the required a element.
Here's my code;
import scra... | [
"The reason why your selector is not working is because you need to quote attribute values that have spaces in them.\nYour next_page selector :\nnext_page = response.css('div.jsx-1709448077.pagination-wrapper div.styles__StyledPaginator-rui__sc-1vqyfdo-0 a[aria-label=Go to next page]').attrib['href']\n\nAll you nee... | [
0
] | [] | [] | [
"css_selectors",
"python",
"python_3.x",
"scrapy",
"web_scraping"
] | stackoverflow_0074248808_css_selectors_python_python_3.x_scrapy_web_scraping.txt |
Q:
How can I merge all the videos in a folder to make a single video file using FFMPEG
I have a folder with 20+ video files and I need to merge them to make one long video file. How can I achieve this using FFMPEG in Python?
I know the following command
ffmpeg -vcodec copy -isync -i \ "concat:file1.mp4|file2.mp4|...|... | How can I merge all the videos in a folder to make a single video file using FFMPEG | I have a folder with 20+ video files and I need to merge them to make one long video file. How can I achieve this using FFMPEG in Python?
I know the following command
ffmpeg -vcodec copy -isync -i \ "concat:file1.mp4|file2.mp4|...|fileN.mp4" \
outputfile.mp4
But I'd rather not type all the names of the 20+ files.
| [
"This is what I've ended up using...\nfind *.mp4 | sed 's:\\ :\\\\\\ :g'| sed 's/^/file /' > fl.txt; ffmpeg -f concat -i fl.txt -c copy output.mp4; rm fl.txt\n\nIt's ugliness pains me but it seems to work ok and it handles spaces in the file names. Also, not sure why OP was asking about python - no need to use some... | [
41,
19,
9,
7,
2,
0,
0
] | [] | [] | [
"ffmpeg",
"python",
"video"
] | stackoverflow_0028922352_ffmpeg_python_video.txt |
Q:
Turn Pandas Multi-Index into column
I have a dataframe with 2 index levels:
value
Trial measurement
1 0 13
1 3
2 4
2 0 NaN
1 12
3 0 34
... | Turn Pandas Multi-Index into column | I have a dataframe with 2 index levels:
value
Trial measurement
1 0 13
1 3
2 4
2 0 NaN
1 12
3 0 34
Which I want to turn into this:
Trial ... | [
"The reset_index() is a pandas DataFrame method that will transfer index values into the DataFrame as columns. The default setting for the parameter is drop=False (which will keep the index values as columns).\nAll you have to do call .reset_index() after the name of the DataFrame:\ndf = df.reset_index() \n\n",
... | [
297,
37,
21,
17,
5,
2,
0
] | [] | [] | [
"dataframe",
"flatten",
"multi_index",
"pandas",
"python"
] | stackoverflow_0020110170_dataframe_flatten_multi_index_pandas_python.txt |
Q:
Get countries and capitals from website Python
I need get countries and capitals from https://geographyfieldwork.com/WorldCapitalCities.htm and create DataFrame with 2 columns: country, capital
With module 'requests'
I tried using the 're' module, but it didn't work(
A:
Using pd.read_html() which returns a list.... | Get countries and capitals from website Python | I need get countries and capitals from https://geographyfieldwork.com/WorldCapitalCities.htm and create DataFrame with 2 columns: country, capital
With module 'requests'
I tried using the 're' module, but it didn't work(
| [
"Using pd.read_html() which returns a list. The table you want is in index 2.\nimport pandas as pd\n\n\nurl = \"https://geographyfieldwork.com/WorldCapitalCities.htm\"\ndf = pd.read_html(url)[2]\n\nprint(df)\n\n"
] | [
0
] | [] | [] | [
"parsing",
"python",
"python_re",
"python_requests"
] | stackoverflow_0074249595_parsing_python_python_re_python_requests.txt |
Q:
Number of occurrences of digit in numbers from 0 to n
Given a number n, count number of occurrences of digits 0, 2 and 4 including n.
Example1:
n = 10
output: 4
Example2:
n = 22
output: 11
My Code:
n = 22
def count_digit(n):
count = 0
for i in range(n+1):
if '2' in str(i):
count += 1... | Number of occurrences of digit in numbers from 0 to n | Given a number n, count number of occurrences of digits 0, 2 and 4 including n.
Example1:
n = 10
output: 4
Example2:
n = 22
output: 11
My Code:
n = 22
def count_digit(n):
count = 0
for i in range(n+1):
if '2' in str(i):
count += 1
if '0' in str(i):
count += 1
... | [
"There are numbers in which the desired number is repeated, such as 20 or 22, so instead of adding 1 you must add 2\n>>> \n>>> string = ','.join(map(str,range(23)))\n>>> \n>>> string\n'0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22'\n>>> \n>>> string.count('0') + string.count('2') + string.count('4')\n1... | [
2,
2,
2,
0,
0
] | [
"Using single branch conditional\ndef count_digit(n):\n s = '024'\n out = 0\n for integer in map(str, range(n+1)): # integer as string\n for digit in integer:\n if digit in s:\n out += 1\n return out\n\nor more compactly\ndef count_digit(n):\n s = '024'\n return su... | [
-1
] | [
"algorithm",
"data_structures",
"list",
"python",
"python_3.x"
] | stackoverflow_0073821319_algorithm_data_structures_list_python_python_3.x.txt |
Q:
Trying to generate a conditional coin flip
So I'm a trying to create a function which first flips an unbiased coin but if the result is heads it flips a biased coin with 0.75 probability of heads. If it shows tails then the next flip is unbiased. I've tried the following code but I can only run this flow once i.e.... | Trying to generate a conditional coin flip | So I'm a trying to create a function which first flips an unbiased coin but if the result is heads it flips a biased coin with 0.75 probability of heads. If it shows tails then the next flip is unbiased. I've tried the following code but I can only run this flow once i.e., if it's a head, then only the next one flip is... | [
"From what I understand, the biasing only depend on the previous choice.\nI would simplify the code with this:\nimport random\ntossList = ['H', 'T']\nchoice = 'T' # first choice will be unbiased\nheads,tails = 0,0\nfor _ in range(500):\n weights = (0.5, 0.5) if choice == 'T' else (0.75, 0.25)\n choice = random.... | [
1,
0,
0
] | [] | [] | [
"coin_flipping",
"montecarlo",
"probability",
"python",
"statistics"
] | stackoverflow_0074249617_coin_flipping_montecarlo_probability_python_statistics.txt |
Q:
sum inside list comprehension
I have a list comprehension operation like below:
a = [1,2,15]
def tt(n):
if n < 1:
return [[]]
st= tt(n-1)
return [row + [v*a[n-1]] for row in st for v in [0,1]]
tt(3)
I am trying to get sum of each sub list rather than the list.
I currently get :
[[0, 0, 0],
[0, 0, 15],
... | sum inside list comprehension | I have a list comprehension operation like below:
a = [1,2,15]
def tt(n):
if n < 1:
return [[]]
st= tt(n-1)
return [row + [v*a[n-1]] for row in st for v in [0,1]]
tt(3)
I am trying to get sum of each sub list rather than the list.
I currently get :
[[0, 0, 0],
[0, 0, 15],
[0, 2, 0],
[0, 2, 15],
[1, 0, 0... | [
"Here's a modified version of your code (but Daniel Hao's suggestion remains valid).\na = [1,2,15]\ndef tt(n):\n if n < 1:\n return [0]\n st= tt(n-1)\n return [row + v*a[n-1] for row in st for v in [0,1]]\n\n"
] | [
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074249751_list_python_python_3.x.txt |
Q:
How to perform .replace() function on list, if list contains strings, integers and/or floats?
Imagine I have a list as such:
mylist = [None, None, None, None, None, None, None, '#N/A', '#N/A', '#N/A', '#N/A', None, None, None, '#N/A', None, None, None, None, None, None, None, None, None, None, None, None, None, No... | How to perform .replace() function on list, if list contains strings, integers and/or floats? | Imagine I have a list as such:
mylist = [None, None, None, None, None, None, None, '#N/A', '#N/A', '#N/A', '#N/A', None, None, None, '#N/A', None, None, None, None, None, None, None, None, None, None, None, None, None, None]
Now I want to replace all #N/A's with None, and am able to do so with the code below:
#Here we... | [
"You could try this:\nnewlist = [None if item == '#N/A' else item for item in mylist]\n\nThat will work regardless of the data types contained in your list.\nGiven:\nmylist = [\n \"xxx\",\n None,\n \"x\",\n \"x\",\n None,\n \"Pv\",\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 1,\n ... | [
2
] | [] | [] | [
"for_loop",
"list",
"python",
"replace",
"string"
] | stackoverflow_0074249818_for_loop_list_python_replace_string.txt |
Q:
Dynamically brute-force all numerical combinations
As the title says I'm trying to get all possible numerical combinations for an unknown number of parameters. I don't mind if you use pandas or numpy. See the code section to understand my problem easily. Any help would be appreciated.
# n can be any integer. 4 is ... | Dynamically brute-force all numerical combinations | As the title says I'm trying to get all possible numerical combinations for an unknown number of parameters. I don't mind if you use pandas or numpy. See the code section to understand my problem easily. Any help would be appreciated.
# n can be any integer. 4 is just an example.
n = 4
possibleValues = range(1, n+1)
#... | [
"itertools.product() will do this for you. You need to tell it how many to repeat, which in this case is the length of the dict keys. Then just zip them up and pass to dict():\nfrom itertools import product\n\nn = 4 \npossibleValues = range(1, n+1)\nparameters = [\"foo\", \"boo\"]\n\n[dict(zip(parameters, pair)) fo... | [
1
] | [] | [] | [
"combinatorics",
"python"
] | stackoverflow_0074249804_combinatorics_python.txt |
Q:
How to do superscripts and subscripts in Jupyter Notebook?
I want to to use numbers to indicate references in footnotes, so I was wondering inside of Jupyter Notebook how can I use superscripts and subscripts?
A:
You can do this inside of a markdown cell. A markdown cell can be created by selecting a cell then p... | How to do superscripts and subscripts in Jupyter Notebook? | I want to to use numbers to indicate references in footnotes, so I was wondering inside of Jupyter Notebook how can I use superscripts and subscripts?
| [
"You can do this inside of a markdown cell. A markdown cell can be created by selecting a cell then pressing the esc key followed by the M key. You can tell when you have converted a cell to markdown when In [ ]: seen to the right of the default code cell is gone. Then you can input the following code that uses lat... | [
57,
33,
4,
0,
0
] | [] | [] | [
"data_science",
"ipython_notebook",
"jupyter",
"jupyter_notebook",
"python"
] | stackoverflow_0046011785_data_science_ipython_notebook_jupyter_jupyter_notebook_python.txt |
Q:
Django Standalone Script
I am trying to access my Django (v1.10) app DB from another python script and having some trouble doing so.
This is my file and folder structure:
store
store
__init.py__
settings.py
urls.py
wsgi.py
store_app
__init.py__
admin.py
apps.py
models.py
...
db.sqlite... | Django Standalone Script | I am trying to access my Django (v1.10) app DB from another python script and having some trouble doing so.
This is my file and folder structure:
store
store
__init.py__
settings.py
urls.py
wsgi.py
store_app
__init.py__
admin.py
apps.py
models.py
...
db.sqlite3
manage.py
other_script.py
... | [
"Try this\nimport sys, os, django\nsys.path.append(\"/path/to/store\") #here store is root folder(means parent).\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"store.settings\")\ndjango.setup()\n\nfrom store_app.models import MyModel\n\nThis script you can use anywhere in your system.\n",
"This sounds like ... | [
58,
14,
2,
2,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0039723310_django_python.txt |
Q:
Python fitting a curve spitting TypeError: only size-1 arrays can be converted to Python scalars
I am trying to fit a curve, this is my code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.optimize import curve_fit
import math
vector = np.vectorize(np.int_)
x_data = np.array([-... | Python fitting a curve spitting TypeError: only size-1 arrays can be converted to Python scalars | I am trying to fit a curve, this is my code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.optimize import curve_fit
import math
vector = np.vectorize(np.int_)
x_data = np.array([-5.0, -4, -3, -2, -1, 0, 1, 2, 3, 4])
x1 = vector(x_data)
y_data = np.array([77, 81, 171, 303, 409, 3... | [
"Don't call vectorize, and don't use the math module; use np. equivalents. Also your initial values were way off and produced a degenerate solution. Either don't provide initial values at all, or provide ones in the ballpark of what you know to be needed:\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\... | [
1
] | [] | [] | [
"arrays",
"curve_fitting",
"numpy",
"python"
] | stackoverflow_0074247837_arrays_curve_fitting_numpy_python.txt |
Q:
How to check if year is a leap year
I can't figure out how to use the tk calender ui to print if the year selected is a leap year or no.
from tkinter import*
from tkcalendar import*
root=Tk()
root.title("Code project")
selectedDate = Label(root, text="")
def selectDate():
myDate =my_Cal.get_date()
sele... | How to check if year is a leap year | I can't figure out how to use the tk calender ui to print if the year selected is a leap year or no.
from tkinter import*
from tkcalendar import*
root=Tk()
root.title("Code project")
selectedDate = Label(root, text="")
def selectDate():
myDate =my_Cal.get_date()
selectedDate.config(text=myDate)
selected... | [
"A year must fulfill the following criteria for it to be a leap year:\n\nThe year must be evenly divisible by 4;\nIf the year can also be evenly divided by 100, it is not a leap year;\nunless\nThe year is also evenly divisible by 400. Then it is a leap year.\n\nsource: https://www.timeanddate.com/date/leapyear.html... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074249749_python.txt |
Q:
Scrapy empty information on a website with protection
I am struggling on a website to get some information, I set up ROBOTSTXT_OBEY = False but still doesnt retrieve any information, how to fix it?
start_urls = ['https://tienda.mercadona.es/search-results?query=leche%20entera']
def parse(self, response):
samp... | Scrapy empty information on a website with protection | I am struggling on a website to get some information, I set up ROBOTSTXT_OBEY = False but still doesnt retrieve any information, how to fix it?
start_urls = ['https://tienda.mercadona.es/search-results?query=leche%20entera']
def parse(self, response):
sample = response.css("div").get()
yield {'name':sample}
T... | [
"The site you are trying to scrape is dynamically loaded with JavaScript. Vanilla Scrapy won't handle javascript by default but there are plugins that may help. A simple one that comes to mind is Scrapy-Playwright. Once configured properly it usually just requires adding DOWNLOAD_HANDLERS to the settings.py file li... | [
1
] | [] | [] | [
"python",
"scrapy",
"web_scraping"
] | stackoverflow_0074233679_python_scrapy_web_scraping.txt |
Q:
How do I get rid of this syntax error that keeps appearing no matter what I do?
I am attempting to recreate a machine learning example on google colab using datasets different to the one used in the example. I have a cell that is giving me an invalid syntax error.
This is the code:
# Mean and Std from ImageNet
NO... | How do I get rid of this syntax error that keeps appearing no matter what I do? | I am attempting to recreate a machine learning example on google colab using datasets different to the one used in the example. I have a cell that is giving me an invalid syntax error.
This is the code:
# Mean and Std from ImageNet
NORM_MEAN = np.array([0.485, 0.456, 0.406])
NORM_STD = np.array([0.229, 0.224, 0.225])
... | [
"That is a valid syntax added in Python 3.8:\n\nf-strings support = for self-documenting expressions and debugging.\n... An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of the evaluated expression...\n\nIf using <3.8 it is a syntax error.\nDemonstrati... | [
0
] | [] | [] | [
"python",
"syntax_error"
] | stackoverflow_0074247533_python_syntax_error.txt |
Q:
flask-login without flask-sqlalchemy or ORM
I am currently using flask-login in my application for user login session management. I am using flask-sqlalchemy, so all working ok.
Because of my previous sql experience, I am not fan of ORM. I like to use SQL directly. May be it is because of my not sound knowledge in... | flask-login without flask-sqlalchemy or ORM | I am currently using flask-login in my application for user login session management. I am using flask-sqlalchemy, so all working ok.
Because of my previous sql experience, I am not fan of ORM. I like to use SQL directly. May be it is because of my not sound knowledge in ORM. Anyways, my question is- is there any way I... | [
"I went with the following solution. It allows to redefine getting user from request Authorization header and use in stateless application.\nfrom flask_login import login_required, LoginManager\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n\n@login_manager.request_loader\ndef load_user_from_requ... | [
0
] | [] | [] | [
"flask",
"flask_login",
"flask_sqlalchemy",
"pymysql",
"python"
] | stackoverflow_0054750019_flask_flask_login_flask_sqlalchemy_pymysql_python.txt |
Q:
Python: skip comment lines marked with # in csv.DictReader
Processing CSV files with csv.DictReader is great - but I have CSV files with comment lines (indicated by a hash at the start of a line), for example:
# step size=1.61853
val0,val1,val2,hybridisation,temp,smattr
0.206895,0.797923,0.202077,0.631199,0.368801... | Python: skip comment lines marked with # in csv.DictReader | Processing CSV files with csv.DictReader is great - but I have CSV files with comment lines (indicated by a hash at the start of a line), for example:
# step size=1.61853
val0,val1,val2,hybridisation,temp,smattr
0.206895,0.797923,0.202077,0.631199,0.368801,0.311052,0.688948,0.597237,0.402763
-169.32,1,1.61853,2.04069e-... | [
"Actually this works nicely with filter:\nimport csv\nfp = open('samples.csv')\nrdr = csv.DictReader(filter(lambda row: row[0]!='#', fp))\nfor row in rdr:\n print(row)\nfp.close()\n\n",
"Good question. Python's CSV library lacks basic support for comments (not uncommon at the top of CSV files). While Dan Stowe... | [
113,
24,
12,
0
] | [
"Just posting the bugfix from @sigvaldm's solution.\ndef decomment(csvfile):\nfor row in csvfile:\n raw = row.split('#')[0].strip()\n if raw: yield row\n\nwith open('dummy.csv') as csvfile:\n reader = csv.reader(decomment(csvfile))\n for row in reader:\n print(row)\n\nA CSV line can contain \"#\"... | [
-1
] | [
"comments",
"csv",
"python"
] | stackoverflow_0014158868_comments_csv_python.txt |
Q:
Error raise KeyError(key) with configparser
I am trying to write a database application with Python3 using an INI file to store connection settings. If the file does not exist, the script ought to create it using an IF statement. The code that I have is below:
import configparser, os
if os.path.exists("main.ini")... | Error raise KeyError(key) with configparser | I am trying to write a database application with Python3 using an INI file to store connection settings. If the file does not exist, the script ought to create it using an IF statement. The code that I have is below:
import configparser, os
if os.path.exists("main.ini"):
config = configparser.ConfigParser()
wi... | [
"Create the following before adding values:\nconfig['connect'] = {} # Create the section in .INI\nconfig['connect']['host'] = host\n...\n\nThe whole section with variables can be created by passing a filled-out dictionary as well.\nconfig['connect'] = {'host': host,\n 'user': user,\n... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074249972_python.txt |
Q:
Log in user using either email address or username in Django
I am trying to create an auth backend to allow my users to log in using either their email address or their username in Django 1.6 with a custom user model. The backend works when I log in with a user name but for some reason does not with an email. Is t... | Log in user using either email address or username in Django | I am trying to create an auth backend to allow my users to log in using either their email address or their username in Django 1.6 with a custom user model. The backend works when I log in with a user name but for some reason does not with an email. Is there something I am forgetting to do?
from django.conf import sett... | [
"Yet another solution:\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.backends import ModelBackend\nfrom django.db.models import Q\n\n\nclass EmailOrUsernameModelBackend(ModelBackend):\n \"\"\"\n Authentication backend which allows users to authenticate using either their\n usern... | [
32,
21,
9,
5,
3,
3,
2,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"django",
"django_authentication",
"django_login",
"python"
] | stackoverflow_0025316765_django_django_authentication_django_login_python.txt |
Q:
python-pptx content remove bullet
Using python-pptx, I created a slide that contains a title and content. The content has a bullet point by default. How do I remove this bullet point?
prs = pptx.Presentation()
slide = _add_slide(prs, 'Title and Content')
slide.placeholders[0].text = "Title"
slide.placeholders[1].t... | python-pptx content remove bullet | Using python-pptx, I created a slide that contains a title and content. The content has a bullet point by default. How do I remove this bullet point?
prs = pptx.Presentation()
slide = _add_slide(prs, 'Title and Content')
slide.placeholders[0].text = "Title"
slide.placeholders[1].text_frame.paragraphs[0].text = "Content... | [
"Is there a particular reason you wanted to use placeholders? You could use a different slide layout or even a blank slide layout and place textboxes etc yourself. There isn't a straight forward way to remove the bullet point and instead relies on editing the xml like so...\nimport pptx\nfrom lxml import etree\n\n\... | [
0
] | [] | [] | [
"powerpoint",
"python",
"python_pptx"
] | stackoverflow_0074238809_powerpoint_python_python_pptx.txt |
Q:
Exporting dataframe to existing Excel sheet in workbook breaks pivot slicer connection in other sheets
My code works exactly like I would like it to by taking the data from the df and inserting it into the desired Excel file while skipping the appropriate rows. However, when I hit the .save() function other sheets... | Exporting dataframe to existing Excel sheet in workbook breaks pivot slicer connection in other sheets | My code works exactly like I would like it to by taking the data from the df and inserting it into the desired Excel file while skipping the appropriate rows. However, when I hit the .save() function other sheets that reference the data (mostly through pivots) seem to break even though they were not touched by the writ... | [
"I found an Excel file with a slicer so I took a look.\nSample file:\n\nSite: https://www.contextures.com/excelpivottableslicers.html#download\n\nTry:\nimport pandas as pd\nfrom openpyxl import load_workbook\n\n# sample Excel file with slicers.\n# if required download and unzip and put in the folder with this scrip... | [
0,
0
] | [] | [] | [
"excel",
"openpyxl",
"pandas",
"python",
"xlsx"
] | stackoverflow_0068853179_excel_openpyxl_pandas_python_xlsx.txt |
Q:
Flask Swagger UI not able to find swagger.json
I'm trying to run flask swagger ui but its prompting me message of No API definition found.
there is online swagger.json that i'm fetching using requests and putting it in static > swagger.json .
Can't share online swagger url as it is organisation property.
folder st... | Flask Swagger UI not able to find swagger.json | I'm trying to run flask swagger ui but its prompting me message of No API definition found.
there is online swagger.json that i'm fetching using requests and putting it in static > swagger.json .
Can't share online swagger url as it is organisation property.
folder structure:
| App
| static
| swagger.jso... | [
"The basic example of flask-swagger-ui explicitly says that local resources are accepted. So this should work:\nfrom pathlib import Path\n\nAPI_URL = Path(\"C:/Users/swagger/api/static/swagger.json\") # maybe you need a .resolve() if Path objects are not supported\n\n",
"File structure:\n| root\n | requiremen... | [
0,
0
] | [] | [] | [
"flask",
"python",
"swagger"
] | stackoverflow_0063154447_flask_python_swagger.txt |
Q:
string parsing/replace in python(Using reg expression)
I am trying to write a parser: convert string to query format. And stuck at a particular point of string replace (by matching a pattern).
I can't figure out the regular expression pattern matching.
I have a input_string like
ip_query_string = "CITY == 'Mumbai... | string parsing/replace in python(Using reg expression) | I am trying to write a parser: convert string to query format. And stuck at a particular point of string replace (by matching a pattern).
I can't figure out the regular expression pattern matching.
I have a input_string like
ip_query_string = "CITY == 'Mumbai' & LOCATION in ['Harrys Bar & Cafe: Mumbai','Hard Rock Cafe... | [
"Got it worked in some odd way (may not be pythonic), but it worked.\ndef rplc_str(s):\n sp = s.split(\"'\")\n print('After split==',sp)\n sp1 = [x.replace(' & ', ' AND ') if ((x.startswith(' &')) or (x.startswith('] &'))) else x for x in sp]\n print('After replacing & ==',sp1)\n sp2 = [x.replace(' in ', ... | [
0,
0,
0
] | [] | [] | [
"parsing",
"python",
"regex",
"string"
] | stackoverflow_0042301280_parsing_python_regex_string.txt |
Q:
How to easily change the contents of str(function) in python
Printing a python function directly always gives you an ugly and lengthy string.
def myfunc_addition(a,b):
return a + b
print(myfunc_addition(1, 2)) # 3
print(str(myfunc_addition)) # <function myfunc_addition at 0x00000215FC2BC8C8>
I want to change... | How to easily change the contents of str(function) in python | Printing a python function directly always gives you an ugly and lengthy string.
def myfunc_addition(a,b):
return a + b
print(myfunc_addition(1, 2)) # 3
print(str(myfunc_addition)) # <function myfunc_addition at 0x00000215FC2BC8C8>
I want to change this but I have no idea how to achieve it. I googled with "string... | [
"If calling it as str(function) isn't strictly required, you could add a docstring to the function and then print that:\ndef myfunc_addition(a, b):\n \"\"\"+\"\"\"\n return a+b\n\nprint(myfunc_addition.__doc__)\n+\n\nThis has the benefit that Python already supports docstrings in the function definition.\n"
] | [
2
] | [] | [] | [
"class",
"function",
"python",
"string"
] | stackoverflow_0074250045_class_function_python_string.txt |
Q:
var.get() variable in python
I am writing code by python tkinter and everything in the code is seems alright except var.get() which python can't define it at all. IntVar() function holds integer data where we can set integer data and can retrieve them.
here is my code:::
'''
Created on 29 Oct 2022
@author: musta
... | var.get() variable in python | I am writing code by python tkinter and everything in the code is seems alright except var.get() which python can't define it at all. IntVar() function holds integer data where we can set integer data and can retrieve them.
here is my code:::
'''
Created on 29 Oct 2022
@author: musta
'''
import sys
import tkinter as ... | [
"Does this example will help?\nimport tkinter as tk\n \nroot = tk.Tk()\n \nint_var = tk.IntVar(root, value = 255)\n \nnum = int_var.get()\n \nprint(num)\n\nOutput: 255\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074246195_python_tkinter.txt |
Q:
Strategy Pattern in Python Functional Redesign
I'm trying to create a program that returns "emergency messages" using the Strategy Pattern. I'm building it in a more functional way in that instead of using abstract classes to define my functions, I just defined the functions and called those.
However, I get the er... | Strategy Pattern in Python Functional Redesign | I'm trying to create a program that returns "emergency messages" using the Strategy Pattern. I'm building it in a more functional way in that instead of using abstract classes to define my functions, I just defined the functions and called those.
However, I get the error
TypeError: text_alarm() missing 1 required posit... | [
"I think that (at least)\n_alarm_behavior = text_alarm() should be _alarm_behavior = text_alarm and\n_suggested_message = evacuate_message() should be _suggested_message = evacuate_message and then the methods should be referred to as FireDrill._suggested_message and FireDrill._alarm_behavior.\nSo a problem is call... | [
0
] | [] | [] | [
"design_patterns",
"oop",
"python"
] | stackoverflow_0074250031_design_patterns_oop_python.txt |
Q:
Using Holoview, datashader plot dynamicmap but freeze
Basic needs: plot a map, and update accoding to variable. Challenges:
have to use rasterize, aggregation by datashade (big data)
holoviews .DynamicMap seems like not support rasterize.
import holoviews as hv, datashader as ds, geoviews as gv, geoviews.tile_so... | Using Holoview, datashader plot dynamicmap but freeze | Basic needs: plot a map, and update accoding to variable. Challenges:
have to use rasterize, aggregation by datashade (big data)
holoviews .DynamicMap seems like not support rasterize.
import holoviews as hv, datashader as ds, geoviews as gv, geoviews.tile_sources as gvts
from holoviews.operation.datashader import da... | [
"The original code isn't runnable (try to show a fully reproducible example!), but when I made it runnable and removed GeoViews (not in my current envt), it seems to work:\nimport holoviews as hv, datashader as ds, panel as pn, pandas as pd\nfrom holoviews.operation.datashader import datashade, rasterize, dynspread... | [
0
] | [] | [] | [
"datashader",
"holoviews",
"python"
] | stackoverflow_0074229685_datashader_holoviews_python.txt |
Q:
How do I return the output in dictionary or JSON format in FAST API?
I have been asked to upload a CSV File which contains the details of students and request the user to input the student ID (In this case the Index) and print the respective row showing the details of that particular student.
The output prints fin... | How do I return the output in dictionary or JSON format in FAST API? | I have been asked to upload a CSV File which contains the details of students and request the user to input the student ID (In this case the Index) and print the respective row showing the details of that particular student.
The output prints fine inside the compiler, both in dictionary and JSON format. But when defini... | [
"Could you do something like this?\nimport pandas as pd\nfrom fastapi import FastAPI\nimport uvicorn\n\n# Reading the CSV file\ndf_data_csv = pd.read_csv('data.csv')\ndata_dict = df_data_csv.to_dict(orient='index')\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"Test\"}\n\n\n@app.get(\"/stu... | [
1
] | [] | [] | [
"api",
"fastapi",
"python"
] | stackoverflow_0074249921_api_fastapi_python.txt |
Q:
Discord bot not responding (python)
import discord
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'... | Discord bot not responding (python) | import discord
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('He... | [
"I'm assuming you're new to discord.py which is fine, though writing code like this is a little counter-intuitive. Instead of registering it as an event, why not just register it as an actual command?\nThis is how it should be done:\nfrom discord.ext import commands\n\nclient = commands.Bot(command_prefix='$') # Th... | [
0
] | [] | [] | [
"discord",
"python"
] | stackoverflow_0074250119_discord_python.txt |
Q:
Counting the number of a specific string in another string
Given a string s, with length N, contain those letters: R G B
count the number of triples (i, j, k) (1 <= i < j< k<= N)
Si != Sj != Sk; j - i != k - j
first line contains N, next line contains s
N = int(input())
s = input()
res = s[1:]
cnt = 0
for i in ra... | Counting the number of a specific string in another string | Given a string s, with length N, contain those letters: R G B
count the number of triples (i, j, k) (1 <= i < j< k<= N)
Si != Sj != Sk; j - i != k - j
first line contains N, next line contains s
N = int(input())
s = input()
res = s[1:]
cnt = 0
for i in range(len(res)):
if res[i-1] == 'R':
for k in range(le... | [
"# You only need one loop\n\nN = int(input())\ns = input()\ncnt = 0\nfor i in range(1,len(s)-1):\n if s[i-1] == \"R\" and s[i] == \"G\" and s[i+1] == \"B\":\n cnt+=1\nprint(cnt)\n\n"
] | [
0
] | [] | [] | [
"python",
"string",
"substring"
] | stackoverflow_0074249951_python_string_substring.txt |
Q:
Issue with writing simple TCP server in python
I am writing a is simple TCP server using python. when i type in "localhost:12001/HelloWorld.html" into my web browser it is meant to display "Hello world" from the html file saved in my directory.
When i run it, this is what is displayed in my web browser:
<!DOCTYPE ... | Issue with writing simple TCP server in python | I am writing a is simple TCP server using python. when i type in "localhost:12001/HelloWorld.html" into my web browser it is meant to display "Hello world" from the html file saved in my directory.
When i run it, this is what is displayed in my web browser:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.... | [
"\nDon't send your text one character at a time in a loop\n\nChange this:\nfor i in range(0, len(outputdata)):\n connectionSocket.send(outputdata[i])\n\nTo this:\nconnectionSocket.send(outputdata)\n\n\nEncode all response strings as utf-8 bytes\n\noutputdata = f.read().encode(encoding='utf-8')\n\n\nAdd the Conte... | [
0
] | [] | [] | [
"html",
"python",
"tcp"
] | stackoverflow_0074250061_html_python_tcp.txt |
Q:
How can I automatically make my code paraphrase the outputted paragraph in such a way that there is more than one possible output?
My code obtains certain paragraphs from a textbook. I would like the code to spit out several versions of this paragraph using some sort of paraphrasing tool, automatically. The code i... | How can I automatically make my code paraphrase the outputted paragraph in such a way that there is more than one possible output? | My code obtains certain paragraphs from a textbook. I would like the code to spit out several versions of this paragraph using some sort of paraphrasing tool, automatically. The code is written mostly in Python, but also uses Js (and Ts) for certain aspects.
I tried implementing several completed models, including;
(py... | [] | [] | [
"Paraphrasing isn't an easy task. You'd need to check what can be removed from a paragraph and still make sense. You'd need an algorithm which understands English to be able to remove what is unnecessary.\nConsidering you mentioned that you're on python, you could always try parrot\n",
"You might wanna look at\nh... | [
-1,
-1
] | [
"api",
"artificial_intelligence",
"javascript",
"python",
"typescript"
] | stackoverflow_0074250107_api_artificial_intelligence_javascript_python_typescript.txt |
Q:
Split then strip txt lines then save to dictionary
I have this .txt file that I wanted to split, strip then save the content to a dictionary
Jon, ID1, 30.0, ID2, 35.4, ID3, 478.5
Paige, ID1, 15.8, ID3, 723.5, ID4, 250, ID6, 66.2
Jil, ID1, 46.2, ID2, 37.7, ID3, 68.4, ID4, 40, ID5, 22
Jig5, ID1, 90.5, ID2, 69.4, ID6... | Split then strip txt lines then save to dictionary | I have this .txt file that I wanted to split, strip then save the content to a dictionary
Jon, ID1, 30.0, ID2, 35.4, ID3, 478.5
Paige, ID1, 15.8, ID3, 723.5, ID4, 250, ID6, 66.2
Jil, ID1, 46.2, ID2, 37.7, ID3, 68.4, ID4, 40, ID5, 22
Jig5, ID1, 90.5, ID2, 69.4, ID6, 35.8
Kit4, ID3, 700.2, ID4, 260, ID5, 96
I wanted to ... | [
"As a comment pointed out, your data is essentially a CSV file. Therefore, you can use the built-in csv module. Like this:\nimport csv\n\n\ndef pairs(lst):\n for i in range(0, len(lst), 2):\n yield (lst[i], lst[i + 1])\n\n\nwith open('test.csv', 'r') as f:\n for row in csv.reader(f):\n dct = {k.... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074250028_python.txt |
Q:
starting Python IDLE from command line to edit scripts
I've tried many variations of this command: idle.py -e filepath, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.
So how can I do the equivalent of opening IDLE, file>open>filepath via the command l... | starting Python IDLE from command line to edit scripts | I've tried many variations of this command: idle.py -e filepath, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.
So how can I do the equivalent of opening IDLE, file>open>filepath via the command line (or perhaps even a Python module)?
| [
"You need to do as stated in the main.py file of the idelib folder (C:\\Python33\\Lib\\idlelib), at least on the python 3.3 version explains that:\nIDLE main entry point\n\nRun IDLE as python -m idlelib\n\nSo with python -m idlelib <script_to_edit> you will be able to open and edit the script with idle. I haven't c... | [
16,
6,
5,
3,
2,
0,
0,
0
] | [] | [] | [
"python",
"python_idle",
"windows"
] | stackoverflow_0002345607_python_python_idle_windows.txt |
Q:
How to group by and get latest record in group contain all of fields in Django?
Imagine we have a table like this:
id
name
type
created_at
1
James
male
2022-03-02
2
Jane
female
2022-04-02
3
Kirk
male
2022-03-04
4
Sarah
female
2022-04-04
5
Jason
male
2022-03-05
And i want to group by type and just get latest... | How to group by and get latest record in group contain all of fields in Django? | Imagine we have a table like this:
id
name
type
created_at
1
James
male
2022-03-02
2
Jane
female
2022-04-02
3
Kirk
male
2022-03-04
4
Sarah
female
2022-04-04
5
Jason
male
2022-03-05
And i want to group by type and just get latest records based on created_at.
So i tried this code and not bad:
result =... | [
"Use order_by with distinct\nUser.objects.order_by(\"type\", \"-created_at\").distinct(\"type\")\n\n",
"this might help you\nresult = User.objects.values('type').annotate(\n latest_date=Max('created_at'),\n ).values('id','name','type','latest_date')\n\n"
] | [
2,
0
] | [] | [] | [
"django",
"django_annotate",
"group_by",
"jquery",
"python"
] | stackoverflow_0074248480_django_django_annotate_group_by_jquery_python.txt |
Q:
Use a list of item and list of indices as a reference to index other lists
If I have two lists, one with all possible items and one with indices for those items. For instance lets say The first list is all the 26 alphabet and the other list is sequence of 26 numbers from 100 to 2600 with 100 increment.
alpha = ["A... | Use a list of item and list of indices as a reference to index other lists | If I have two lists, one with all possible items and one with indices for those items. For instance lets say The first list is all the 26 alphabet and the other list is sequence of 26 numbers from 100 to 2600 with 100 increment.
alpha = ["A", "B", "C", "D", "E", ......., "X', "Y", "Z"]
idx = [100, 200, 300, 400, 500, .... | [
"An approach using a dictionary to get the value of each letter and using list/dict compreension\nalpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nalpha = [l for l in alpha]\nd = {k:v*100 for v,k in enumerate(alpha, start=1)}\n\ninput = [\"E\", \"R\", \"I\", \"N\", \"W\", \"A\", \"L\", \"T\", \"E\", \"R\"]\n\noutput = [d[l]... | [
0
] | [] | [] | [
"indexing",
"list",
"python"
] | stackoverflow_0071544194_indexing_list_python.txt |
Q:
When i print the object it only shows <__main__.City object at 0x7fa6b8877340> instead of a real object i want. Why could this happend?
cityNames = ['Detroit', 'Ann Arbor', 'Pittsburgh']
populations = [680250, 117070, 304391]
states = ['MI', 'MI', 'PA']
city_tuples = zip(cityNames, populations, states)
print(city... | When i print the object it only shows <__main__.City object at 0x7fa6b8877340> instead of a real object i want. Why could this happend? |
cityNames = ['Detroit', 'Ann Arbor', 'Pittsburgh']
populations = [680250, 117070, 304391]
states = ['MI', 'MI', 'PA']
city_tuples = zip(cityNames, populations, states)
print(city_tuples)
class City:
def __init__(self, n, p, s):
self.name = n
self.population = p
self.state = s
def __str__(self):
... | [
"When using lists as print arguments, __str__ method is not the method called for printing each Object, it is __repr__ instead. See this post for reference.\nYou can add __repr__ method or print the Objects one by one:\n...\n\n#print(cities) replace this!!\n\nfor city in cities:\n print(city)\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074250196_python_python_3.x.txt |
Q:
please explain me how this program works?
def print_prime_1_n(n):
for i in range(1, n+1):
prime = True
for j in range(2, i):
if i % j == 0:
prime = False
break
if prime:
print(i)
print_prime_1_n(10)
I spent 2 days to figure out this code but i coudn't find a way to figou... | please explain me how this program works? | def print_prime_1_n(n):
for i in range(1, n+1):
prime = True
for j in range(2, i):
if i % j == 0:
prime = False
break
if prime:
print(i)
print_prime_1_n(10)
I spent 2 days to figure out this code but i coudn't find a way to figout it out. please explain to me?
| [
"I hope this helps:\ndef print_prime_1_n(n):\n # For all numbers from 1 to n+1\n for i in range(1, n+1):\n # Assume i is prime until proven otherwise\n prime = True\n # For all numbers from 2 to i (second number used to check if i is prime)\n for j in range(2, i):\n # If... | [
2,
1,
0
] | [] | [] | [
"for_loop",
"primes",
"python"
] | stackoverflow_0074250158_for_loop_primes_python.txt |
Q:
pySimpleGUI - Set Cursor and refresh
Using pySimpleGUI I simply want to change the mouse cursor while the code is processing a query, but the cursor does only change after the code is executed... it does work when I put a window.read() after the set_cursor() call, but then the proceeding code is not executed immed... | pySimpleGUI - Set Cursor and refresh | Using pySimpleGUI I simply want to change the mouse cursor while the code is processing a query, but the cursor does only change after the code is executed... it does work when I put a window.read() after the set_cursor() call, but then the proceeding code is not executed immediately. What am I doing wrong? Unfortunate... | [
"Not completely sure why is that, but the following works as desired. The crucial part is to add the Submit button ID at the window['Submit'].set_cursor(\"coffee_mug\"), then the new cursor is displayed before the next code is executed. And it will also show the new cursor at the entire window, not only when hoveri... | [
1,
0,
0
] | [] | [] | [
"pysimplegui",
"python"
] | stackoverflow_0074232601_pysimplegui_python.txt |
Q:
I just shifted to python and was building guess a number game but i am facing an issue
the issue is that i want to compare each element of input number and the random number guessed and then compare each element one by one and give response like print on terminal.
# import random
# number = random.randint(1, 10)
... | I just shifted to python and was building guess a number game but i am facing an issue | the issue is that i want to compare each element of input number and the random number guessed and then compare each element one by one and give response like print on terminal.
# import random
# number = random.randint(1, 10)
number = '165'
player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('... | [
"Could you do something like this?\nimport random\n\nplayer_name = input(\"Hello, What's your name?\")\nprint('okay! ' + player_name + ' I am Guessing a number between 1 and 10:')\n\nrandom_number = random.randint(1, 10)\nguess_count = 0\nguess_limit = 5\n\nwhile guess_count < guess_limit:\n guess = int(input('G... | [
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074250264_python_string.txt |
Q:
How to save data array generated by python?
I developed a python code that generates several arrays of data. I want to save these arrays in a specific location on my computer and then import them into another notebook. It's important that, given a matrix saved as "data.csv", I can import caluns or rows from it. Fo... | How to save data array generated by python? | I developed a python code that generates several arrays of data. I want to save these arrays in a specific location on my computer and then import them into another notebook. It's important that, given a matrix saved as "data.csv", I can import caluns or rows from it. For example data[0] or data[0][1] for example.
I've... | [
"If you are trying to store dictionary, you can consider using json, this can be done by import json\nYou can dump dictionary into a string, and load them from file very quickly.\nYou can learn about how to use json here:\nhttps://www.w3schools.com/python/python_json.asp\nIf you are using csv, the result of open() ... | [
0
] | [] | [] | [
"csv",
"database",
"python"
] | stackoverflow_0074250226_csv_database_python.txt |
Q:
RSA key generation, signature and verification does not give expected results
For educational purposes, I'm trying to implement the RSA key generation and then signing a message with subsequent verification. Although, I'm following the general formulas for the key generation, eventually the verification returns Fa... | RSA key generation, signature and verification does not give expected results | For educational purposes, I'm trying to implement the RSA key generation and then signing a message with subsequent verification. Although, I'm following the general formulas for the key generation, eventually the verification returns False.
import hashlib
def fast_modular_exponentiation(a, b, n):
result = 1
w... | [
"For everybody that comes up with the same problem, thanks to the above comments I could find a working solution:\nimport hashlib\nfrom Crypto.Util.number import getPrime\n\n\ndef fast_modular_exponentiation(a, b, n):\n result = 1\n while b > 0:\n if b % 2 == 1:\n result = (result * a) % n\n... | [
0
] | [] | [] | [
"cryptography",
"python",
"rsa",
"sha",
"signature"
] | stackoverflow_0074242385_cryptography_python_rsa_sha_signature.txt |
Q:
Filter Pandas dataframe by Key+Unique values of column
My pandas dataframe looks something like this:
Country
Continent
N. of cases
Norway
Europe
163
Norway
Europe
163
Norway
Europe
163
Norway
Europe
18
Norway
Europe
18
Norway
Europe
18
Norway
Europe
27
Norway
Europe
27
Italy
Europe
34
Italy
Europe
34
... | Filter Pandas dataframe by Key+Unique values of column | My pandas dataframe looks something like this:
Country
Continent
N. of cases
Norway
Europe
163
Norway
Europe
163
Norway
Europe
163
Norway
Europe
18
Norway
Europe
18
Norway
Europe
18
Norway
Europe
27
Norway
Europe
27
Italy
Europe
34
Italy
Europe
34
Italy
Europe
11
Italy
Europe
11
Italy
Eu... | [
"Remove duplictes per all 3 columns and aggregate sum:\ndf1 = (df.drop_duplicates(['Country','Continent','N. of cases'])\n .groupby(['Country','Continent'], as_index=False, sort=False)['N. of cases']\n .sum())\n\nIf only 3 columns:\ndf1 = (df.drop_duplicates()\n .groupby(['Country','Continen... | [
0,
0
] | [] | [] | [
"dataframe",
"filter",
"pandas",
"python",
"unique"
] | stackoverflow_0071645692_dataframe_filter_pandas_python_unique.txt |
Q:
Battle system in rock , paper, scissors game unable to effectively pull hp values
When entering a battle in my game, I update both the enemy and players hp as the battle progresses. The game is a basic Rock, Paper, Scissors battle type. I've deleted a lot a lot of the other command you can use to make it shorter b... | Battle system in rock , paper, scissors game unable to effectively pull hp values | When entering a battle in my game, I update both the enemy and players hp as the battle progresses. The game is a basic Rock, Paper, Scissors battle type. I've deleted a lot a lot of the other command you can use to make it shorter but the error still occurs
Here is the code:
import random
equippedweapon = ['Bare Fists... | [
"Numerous issues. I've stayed with your code structure below however as a next step you might look to creating a character/monster class where the name, hp, weapon are all properties. This will allow you to abstract your code.\nAlso, use 4 space indents. If your indent is too deep the message is that your code stru... | [
0
] | [] | [] | [
"global",
"python",
"syntax_error",
"variables"
] | stackoverflow_0074250120_global_python_syntax_error_variables.txt |
Q:
visualize a two-dimensional point set using Python
I'm new to Python and want to perform a rather simple task. I've got a two-dimensional point set, which is stored as binary data (i.e. (x, y)-coordinates) in a file, which I want to visualize. The output should look as in the picture below.
However, I'm somehow ov... | visualize a two-dimensional point set using Python | I'm new to Python and want to perform a rather simple task. I've got a two-dimensional point set, which is stored as binary data (i.e. (x, y)-coordinates) in a file, which I want to visualize. The output should look as in the picture below.
However, I'm somehow overwhelmed by the amount of google results on this topic.... | [
"Install and import matplotlib and pyplot:\nimport matplotlib.pyplot as plt\n\nAssuming this is your data:\nx = [1, 2, 5, 1, 5, 7, 8, 3, 2, 6]\ny = [6, 7, 1, 2, 6, 2, 1, 6, 3, 1]\n\nIf you need, you can use a comprehension to split the coordinates into seperate lists:\nx = [p[0] for p in points]\ny = [p[1] for p in... | [
7,
1,
0,
0
] | [] | [] | [
"python",
"visual_studio",
"visualization"
] | stackoverflow_0074127477_python_visual_studio_visualization.txt |
Q:
How to perform a pairwise swap of a list?
I want to write a small code in python that Swap Elements in a list this program will accept a list, and will return a list that exchanges the positions of each pair of adjacent elements: positions 0 and 1, positions 2 and 3, and so on. If the list has an odd number of el... | How to perform a pairwise swap of a list? | I want to write a small code in python that Swap Elements in a list this program will accept a list, and will return a list that exchanges the positions of each pair of adjacent elements: positions 0 and 1, positions 2 and 3, and so on. If the list has an odd number of elements, then the element in the last position s... | [
"Most pythonic way:\ndef swappairwise(a):\n l = len(a)&~1\n a[1:l:2],a[:l:2] = a[:l:2],a[1:l:2]\n\n",
"Here is a neat one, if you are always guaranteed to have even numbers:\n nums = [1,2,3,4,5,6]\n print([nums[i^1] for i in range(len(nums))])\n >>[2, 1, 4, 3, 6, 5] \n\nExplanation:\nprint (0^1) #1\nprint (1... | [
5,
4,
2,
0,
0,
0,
0,
0,
0
] | [
"Found this to be much simpler solution and handels the list with odd elements\nelements = list(map(int,input().split()))\nswap = []\n\ni = 0\nwhile i < len(elements):\n if i+1 < len(elements):\n swap.append(elements[i+1])\n swap.append(elements[i]) \n else:\n swap.append(elements[-1])\n ... | [
-1
] | [
"python"
] | stackoverflow_0030097512_python.txt |
Q:
How to filter a dataframe by another dataframe by row elements
df_new is the actual data and I filtered df_new to obtain paypal_data. I want to filter df_new by paypal_data. But when filtering by created_at I just want to filter by month, day, year, without taking hours
A:
You can convert the column to just date... | How to filter a dataframe by another dataframe by row elements | df_new is the actual data and I filtered df_new to obtain paypal_data. I want to filter df_new by paypal_data. But when filtering by created_at I just want to filter by month, day, year, without taking hours
| [
"You can convert the column to just date first.\ndf_new[\"created_at\"] = pd.to_datetime(df_new[\"created_at\"]).dt.date\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074250205_dataframe_pandas_python.txt |
Q:
How do I loop through a list and print each element separated by commas without the last comma?
I'm trying to loop through the elements of a list, print them out, separate them by a comma but leave the trailing comma; all in a single loop. I'm aware of the join() method but I wanted to ask if there was a way to co... | How do I loop through a list and print each element separated by commas without the last comma? | I'm trying to loop through the elements of a list, print them out, separate them by a comma but leave the trailing comma; all in a single loop. I'm aware of the join() method but I wanted to ask if there was a way to complete that within the loop?
This is the code I'm currently working with:
grades = [['A1', 12], ['A2'... | [
"You can use print with sep parameter, or join:\ngrades = [['A1', 12], ['A2', 18], ['A3', 20], ['A4', 19]]\n\nprint(*(x[0] for x in grades), sep=', ') # A1, A2, A3, A4\n\nprint(', '.join(x[0] for x in grades)) # A1, A2, A3, A4\n\n",
"I believe this should work:\ngrades = [['A1', 12], ['A2', 18], ['A3', 20], ['A4'... | [
1,
0
] | [] | [] | [
"list",
"loops",
"python",
"python_3.x"
] | stackoverflow_0074250331_list_loops_python_python_3.x.txt |
Q:
Using __call__ and @property to have a class return a value like a normal variable when called
I'm trying to create a class that can contain a variable and a unit (e.g. 5 m/s) but I want it to behave like a normal variable whenever it is called. My intention was to use the @property decorator in addition to the __... | Using __call__ and @property to have a class return a value like a normal variable when called | I'm trying to create a class that can contain a variable and a unit (e.g. 5 m/s) but I want it to behave like a normal variable whenever it is called. My intention was to use the @property decorator in addition to the __call__ magic method to achieve this.
My code looks like this:
from dataclasses import dataclass
impo... | [
"In your code you are doing some wrong things\nyou should not use property decorator with magic_methods.\nfrom dataclasses import dataclass\nimport typing as tp\nimport numpy as np\n\n\n@dataclass\nclass _Value():\n value: float\n\n @property\n def __call__(self):\n return self.value\n\n\n@dataclass... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074250260_python_python_3.x.txt |
Q:
How to make batch requests in web3.py?
This is my take for async based on this
How to use AsyncHTTPProvider in web3py?
article. However, upon running this code it executes like a
synchronous function.
For web3.js, there is a support for batch request
https://dapp-world.com/smartbook/web3-batch-request-Eku8 . Howe... | How to make batch requests in web3.py? |
This is my take for async based on this
How to use AsyncHTTPProvider in web3py?
article. However, upon running this code it executes like a
synchronous function.
For web3.js, there is a support for batch request
https://dapp-world.com/smartbook/web3-batch-request-Eku8 . However,
web3.py does not have any.
I am usin... | [
"I think my idea isn't the best but you can use it as a temporary solution.\nFor this, you have to use ThreadpoolExecutor.\nI executed a benchmark and found these results:\n\nWithout ThreadpoolExecutor, using BSC Public RPC, just running in for loop, takes more than 3 minutes to finish the process.\nClick here to s... | [
1
] | [] | [] | [
"asynchronous",
"ethereum",
"python"
] | stackoverflow_0074218115_asynchronous_ethereum_python.txt |
Q:
Spelling numbers from digits to words
Using Python, write a function that takes a whole number as an argument and returns a string containing the number spelled out in English. For example, the function call:
spell(123123)
will return the string:
"one hundred twenty three thousand one hundred twenty thre... | Spelling numbers from digits to words | Using Python, write a function that takes a whole number as an argument and returns a string containing the number spelled out in English. For example, the function call:
spell(123123)
will return the string:
"one hundred twenty three thousand one hundred twenty three"
This is my code so far but I'm stuck. m... | [
"This question comes from LeetCode. Here’s a solution. The idea is to print the highest value from the given number and then iterate on the remaining. Some edge cases need to be handled, like leading zeros.\nfrom collections.abc import Mapping\nimport itertools\n\nclass Solution:\n def __init__(self):\n s... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074250362_python.txt |
Q:
Find the nth term of a specific sequence given the rule python
Given a sequence U1, U2, U3,...
and the rule is Ui = U(i-1) - 2*U(i-2)
given the natural number n find Un
Here's my approach
n = int(input())
u1 = 1
u2 = 1
for i in range(n//2-1):
s = u2 - 2*u1
t = s - 2*u2
u1 = s
u2 = t
if n == 3:
... | Find the nth term of a specific sequence given the rule python | Given a sequence U1, U2, U3,...
and the rule is Ui = U(i-1) - 2*U(i-2)
given the natural number n find Un
Here's my approach
n = int(input())
u1 = 1
u2 = 1
for i in range(n//2-1):
s = u2 - 2*u1
t = s - 2*u2
u1 = s
u2 = t
if n == 3:
print(-1)
elif n % 2 != 0:
print(s)
else:
print(t)
exam... | [
"It looks like you are trying to do two updates per loop, which requires the special cases for printing the result. That's harder to get all the cases right. It would be much easier to just do the updates using the formula:\ns = u2 - 2*u1\nu1 = u2\nu2 = s\n\nWith that body, the loop should go to n, and you should... | [
0,
0
] | [] | [] | [
"arithmetic_expressions",
"python",
"rules",
"sequence"
] | stackoverflow_0074250346_arithmetic_expressions_python_rules_sequence.txt |
Q:
if statements, TTK
ytac=[]
import tkinter as tk
from tkinter import ttk
class App(tk.Tk):
def __init__(self, title: str):
super().__init__()
self.title(title)
self.style = ttk.Style(self)
self.style.theme_use("classic")
self.frame0 = ttk.Frame(self, padding=(5,5))
self.frame1 = ttk.F... | if statements, TTK | ytac=[]
import tkinter as tk
from tkinter import ttk
class App(tk.Tk):
def __init__(self, title: str):
super().__init__()
self.title(title)
self.style = ttk.Style(self)
self.style.theme_use("classic")
self.frame0 = ttk.Frame(self, padding=(5,5))
self.frame1 = ttk.Frame(self, padding=(5,5... | [
"Without seeing all of the code I cannot accurately diagnose your problem, but it may lie in how you're using the Tkinter buttons.\nAnother question that seems similar to yours\nTo Detect Button Press In Python Tkinter Module\nA very thorough tutorial for Tkinter buttons:\nhttps://www.tutorialspoint.com/python/tk_b... | [
1
] | [] | [] | [
"if_statement",
"python",
"tkinter"
] | stackoverflow_0074250363_if_statement_python_tkinter.txt |
Q:
How do I append to a Pandas DataFrame column?
I have a DataFrame that I am adding data to, but I do not gather the data for each row at the same time. Some of the columns are assembled in pieces.
The first time I have some data for a column, I can simply assign it:
import pandas as pd
df = pd.DataFrame()
df["name... | How do I append to a Pandas DataFrame column? | I have a DataFrame that I am adding data to, but I do not gather the data for each row at the same time. Some of the columns are assembled in pieces.
The first time I have some data for a column, I can simply assign it:
import pandas as pd
df = pd.DataFrame()
df["name"] = pd.Series(["A", "B", "C", "D", "E", "F", "G", ... | [
"Before concat to original value, you need drop the NaN first first\ndf['data'] = pd.concat([df['data'].dropna(), new_data], ignore_index=True)\n\nprint(df)\n\n name data\n0 A 1.0\n1 B 2.0\n2 C 3.0\n3 D 4.0\n4 E 5.0\n5 F 6.0\n6 G NaN\n7 H NaN\n8 I NaN\n\nIf the new con... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074250329_dataframe_pandas_python.txt |
Q:
undetected_chromedriver runs slowly, suggestions?
I'm making a price scraping program and have ran into the issue of antiscraping systems. I managed to get around these with the undetected_chromedriver but now I'm running into 2 issues
the first is that the UC is significantly slower than the standard chrome drive... | undetected_chromedriver runs slowly, suggestions? | I'm making a price scraping program and have ran into the issue of antiscraping systems. I managed to get around these with the undetected_chromedriver but now I'm running into 2 issues
the first is that the UC is significantly slower than the standard chrome driver, through I need it for some sites, so I have some sit... | [
"You can use https://github.com/seleniumbase/SeleniumBase to speed things up.\n(It has a special undetected-chromedriver mode that works with headless mode.)\npip install -U seleniumbase\nAnd then run the following with python:\nfrom seleniumbase import Driver\nfrom seleniumbase import page_actions\n\ndriver = Driv... | [
1
] | [] | [] | [
"python",
"selenium_chromedriver",
"undetected_chromedriver",
"web_scraping"
] | stackoverflow_0073999362_python_selenium_chromedriver_undetected_chromedriver_web_scraping.txt |
Q:
How to read path with arabic characters in python?
I'm trying to access to a folder with arabic characters in name and read the images with CV2 but got issue that's my code:
class_names = ['ا', 'ب', 'ت']
for dirname, _, filenames in os.walk(r'C:\Users\emady\Desktop\VS Code\HandWriten_Arabic\Train2'):
for file... | How to read path with arabic characters in python? | I'm trying to access to a folder with arabic characters in name and read the images with CV2 but got issue that's my code:
class_names = ['ا', 'ب', 'ت']
for dirname, _, filenames in os.walk(r'C:\Users\emady\Desktop\VS Code\HandWriten_Arabic\Train2'):
for filename in filenames:
print(os.path.join(dirname[:-... | [
"img = cv2.imdecode(np.fromfile(path2, dtype=np.uint8),\n cv2.IMREAD_UNCHANGED)\n\nThat's solved my issue\n"
] | [
1
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074250433_opencv_python.txt |
Q:
Python JSON get all children and grandchildren
My JSON data looks like this:
data = {
"areas": [
{
"id": "1348828088398400836",
"name": "Building A",
"children": [
{
"id": "1348828088398403213",
"name": "Floor 1... | Python JSON get all children and grandchildren | My JSON data looks like this:
data = {
"areas": [
{
"id": "1348828088398400836",
"name": "Building A",
"children": [
{
"id": "1348828088398403213",
"name": "Floor 1",
"children": [
... | [
"You can use a recursive function like so:\nfrom typing import Any\n\n\ndata = ...\n\n\ndef print_children(dictionary: dict[str, Any]) -> None:\n print(\"Name:\", dictionary.get(\"name\"))\n if \"children\" not in dictionary.keys():\n return\n for child_dict in dictionary[\"children\"]:\n pri... | [
1
] | [
"https://github.com/hansalemaos/flatten_any_dict_iterable_or_whatsoever\nfrom flatten_any_dict_iterable_or_whatsoever import fla_tu\n\ndata = {\n \"areas\": [\n {\n \"id\": \"1348828088398400836\",\n \"name\": \"Building A\",\n \"children\": [\n {\n ... | [
-2
] | [
"dictionary",
"json",
"python"
] | stackoverflow_0074234587_dictionary_json_python.txt |
Q:
How can I compare the value in dictionary to the input value from users? python
I'm asking a user to input a number from the keyboard. For example users input 190, How can I compare 190 that user input to the value of the dictionary with the same value? is it equal or not?
This is my code:
my_dict = {'apple': [900... | How can I compare the value in dictionary to the input value from users? python | I'm asking a user to input a number from the keyboard. For example users input 190, How can I compare 190 that user input to the value of the dictionary with the same value? is it equal or not?
This is my code:
my_dict = {'apple': [900, 190], 'orange': [1300, 90], 'pineapple': [550, 13], 'carrot': [600, 60], 'cucumber'... | [
"Your code is correct, but since your values are list so instead of == you should do in check\nmy_dict = {'apple': [900, 190], 'orange': [1300, 90], 'pineapple': [550, 13], 'carrot': [600, 60], 'cucumber': [900, 30], 'egg plant': [1100, 20], 'zucchini': [1300, 10], 'garlic': [300, 70]}\nusernumber = int(input('Inpu... | [
0,
0
] | [] | [] | [
"compare",
"dictionary",
"input",
"list",
"python"
] | stackoverflow_0074250502_compare_dictionary_input_list_python.txt |
Q:
How to access each element of a nested list for naming output in snakemake?
This is a similar problem: Snakemake: using a python nested list comprehension for conditional analyses
I have the following:
RUN_ID = ["run1", "run2"]
SAMPLES = [["A", "B", "C"], ["D","E","F"]]
rule all:
input:
summary = exp... | How to access each element of a nested list for naming output in snakemake? | This is a similar problem: Snakemake: using a python nested list comprehension for conditional analyses
I have the following:
RUN_ID = ["run1", "run2"]
SAMPLES = [["A", "B", "C"], ["D","E","F"]]
rule all:
input:
summary = expand("foo/{run}/{sample}/outs/{sample}_report.html", run=RUN_ID, sample=SAMPLES)
... | [
"expand is a convenience utility, for more complex cases it's typically faster to generate the desired list directly using python:\nRUN_ID = [\"run1\", \"run2\"]\nSAMPLES = [[\"A\", \"B\", \"C\"], [\"D\",\"E\",\"F\"]]\n\ndesired_files = []\nfor run, SAMPLE in zip(RUN_ID, SAMPLES):\n for sample in SAMPLE:\n f... | [
2
] | [] | [] | [
"list_comprehension",
"nested_lists",
"python",
"snakemake"
] | stackoverflow_0074250506_list_comprehension_nested_lists_python_snakemake.txt |
Q:
Python Sympy solve returns list vs. dictionary
I am using sympy and its solve function, but I noticed that it sometimes returns a dictionary in a list but in other cases just a dictionary, without a list.
from sympy import *
x, y = symbols('x y')
q = 16*x**0.5*y**0.5
solve((diff(q, x)/5 - diff(q, y)/20, 3200 - q)... | Python Sympy solve returns list vs. dictionary | I am using sympy and its solve function, but I noticed that it sometimes returns a dictionary in a list but in other cases just a dictionary, without a list.
from sympy import *
x, y = symbols('x y')
q = 16*x**0.5*y**0.5
solve((diff(q, x)/5 - diff(q, y)/20, 3200 - q))
This returns a list: [{x: 400.000000000000, y: 10... | [] | [] | [
"And explanation of output types has been added to the documentation. The gist is given in that exaplanation's opening paragraph:\n\nThe reasons for this are historical and are biased toward human\ninteraction rather than programmatic use. The type of output will\ndepend on the type of equation(s) (and how they are... | [
-1
] | [
"python",
"sympy"
] | stackoverflow_0065957880_python_sympy.txt |
Q:
Correct way to parse JSON string in Python
I have the string:
'[\'{"cx":3575,"cy":1657,"r":98}\', \'{"cx":3284,"cy":1706,"r":81}\', \'{"cx":4260,"cy":1611,"r":97}\', \'{"cx":3350,"cy":1632,"r":60}\', \'{"cx":3475,"cy":1586,"r":77}\', \'{"cx":4243,"cy":1474,"r":87}\']'
How I can get correct array of dicts from thi... | Correct way to parse JSON string in Python | I have the string:
'[\'{"cx":3575,"cy":1657,"r":98}\', \'{"cx":3284,"cy":1706,"r":81}\', \'{"cx":4260,"cy":1611,"r":97}\', \'{"cx":3350,"cy":1632,"r":60}\', \'{"cx":3475,"cy":1586,"r":77}\', \'{"cx":4243,"cy":1474,"r":87}\']'
How I can get correct array of dicts from this?
| [
"Could you do something like this?\nimport ast\n\nstring = '[\\'{\"cx\":3575,\"cy\":1657,\"r\":98}\\', \\'{\"cx\":3284,\"cy\":1706,\"r\":81}\\', \\'{\"cx\":4260,\"cy\":1611,\"r\":97}\\', \\'{\"cx\":3350,\"cy\":1632,\"r\":60}\\', \\'{\"cx\":3475,\"cy\":1586,\"r\":77}\\', \\'{\"cx\":4243,\"cy\":1474,\"r\":87}\\']'\n\... | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074250582_json_python.txt |
Q:
django.db.utils.ProgrammingError: cannot cast type uuid to integer
I tried to upload my web to Heroku server and stuck at this ploblem
my error when I try to migrate my database
The above exception was the direct cause of the following exception:
return self.cursor.execute(sql, params)
File "/app/.heroku/pyt... | django.db.utils.ProgrammingError: cannot cast type uuid to integer | I tried to upload my web to Heroku server and stuck at this ploblem
my error when I try to migrate my database
The above exception was the direct cause of the following exception:
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit_... | [
"As pointed out in this answer:\n\n\"A better approach is usually to add a uuid column, then fix up any foreign key references to point to it, and finally drop the original column.\"\n\nSo, to handle this in django, do the following:\n1) revert migrations to a working graph\n2) add temp_id = models.UUIDField(defaul... | [
17,
1,
0,
0,
0
] | [] | [] | [
"django",
"heroku",
"python",
"python_3.x"
] | stackoverflow_0061464113_django_heroku_python_python_3.x.txt |
Q:
How to get list of lists of decreasing size from n to one
I want for a number n for their to be a list starting off of n and decreasing to one as elements in the list. If n was 4, the list would be:
[[0, 0, 0, 0][0, 0, 0][0, 0,][0]]
triangle = []
for i in range(n):
for k in range(i):
triangle.append(0)... | How to get list of lists of decreasing size from n to one | I want for a number n for their to be a list starting off of n and decreasing to one as elements in the list. If n was 4, the list would be:
[[0, 0, 0, 0][0, 0, 0][0, 0,][0]]
triangle = []
for i in range(n):
for k in range(i):
triangle.append(0)
That just gave out for input n = 5,
[0, 0, 0, 0, 0, 0, 0... | [
"If you want to mantain your code form, you just use this function:\ndef get_triangle_list(n):\n triangle_list = []\n for i in range(n, 0, -1):\n tmp_list = []\n for k in range(i):\n tmp_list.append(0)\n triangle_list.append(tmp_list)\n return triangle_list\n\nprint(get_tria... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074250583_python.txt |
Q:
ValueError: no gopen handler defined
I am new to using webdataset library from pytorch. I have created .tar files of a sample dataset present locally in my system using webdataset.TarWriter(). The .tar files creation seems to be successful as I could extract them separately on windows platform and verify the same ... | ValueError: no gopen handler defined | I am new to using webdataset library from pytorch. I have created .tar files of a sample dataset present locally in my system using webdataset.TarWriter(). The .tar files creation seems to be successful as I could extract them separately on windows platform and verify the same dataset files.
Now, I create train_dataset... | [
"I have had the same error since yesterday, I finally found the culprit. WebDataset/tarIterators.py makes use of WebDataset/gopen.py. In gopen.py urllib.parse.urlparse is called to parse the url to be opened, in your case the url is D:/PhD/....\ngopen_schemes = dict(\n __default__=gopen_error,\n pipe=gopen_pi... | [
1,
0
] | [] | [] | [
"deep_learning",
"pypi",
"python",
"pytorch"
] | stackoverflow_0068299665_deep_learning_pypi_python_pytorch.txt |
Q:
Installing pip packages in python file
I do my project. I need to install pip packages in python code. But I get error.
If I try this:
pip._internal.main(['install', package]) or this pip.main(['install', package]) I get this:
NameError: name 'pip' is not defined. I use python 3.10 and pip 22. For do this code I u... | Installing pip packages in python file | I do my project. I need to install pip packages in python code. But I get error.
If I try this:
pip._internal.main(['install', package]) or this pip.main(['install', package]) I get this:
NameError: name 'pip' is not defined. I use python 3.10 and pip 22. For do this code I use exec().
| [
"Could you do something like this?\nimport subprocess\nimport sys\n\n\ndef install_package(package):\n \"\"\"\n Install a package using pip\n \"\"\"\n\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package])\n\n"
] | [
1
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0074250627_pip_python.txt |
Q:
how to unhide the letters in this game?
it's a guess-the-letter game something like hangman. it generates a random word in the length of 4 or 5 it's the user's choice and after that, it displays it like this ^^^^ for 4 letters for example. each time user can guess a letter if it's not right I display a message and... | how to unhide the letters in this game? | it's a guess-the-letter game something like hangman. it generates a random word in the length of 4 or 5 it's the user's choice and after that, it displays it like this ^^^^ for 4 letters for example. each time user can guess a letter if it's not right I display a message and says it but if it's right has to display tha... | [
"I think this base code will work for this,\nNote: You need to find index of all occurrences if character is present more than twice in word ( ex: pool ) here o is occurring twice, so you can loop over the base method to replace both occurrences\noriginal_word = 'avatar'\nmasked_word = '*' * len(original_word)\n\ni... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074250542_python.txt |
Q:
how to sort data inside text file in accending order in python?
I have a text file containing number integer and string value pairs I want to sort them in ascending order but I am not getting it correct
**TextFile.txt **
87,Toronto
45,USA
45,PAKISTAN
33,India
38,Jerry
30,Tom
23,Jim
7,Love
38,Hate
30,Stress
My cod... | how to sort data inside text file in accending order in python? | I have a text file containing number integer and string value pairs I want to sort them in ascending order but I am not getting it correct
**TextFile.txt **
87,Toronto
45,USA
45,PAKISTAN
33,India
38,Jerry
30,Tom
23,Jim
7,Love
38,Hate
30,Stress
My code
def sort_outputFiles():
print('********* Sorting now **********... | [
"You are comparing strings, not numbers.\nIn an dictionary (like, the physical book), the words are sorted by who has the \"lowest\" first letter, and if it's a tie, we pick the lowest second letter, and so on. This is called lexicographical order.\nSo the string \"aaaa\" < \"ab\". Also, \"1111\" < \"12\"\nTo fix t... | [
0,
0,
0
] | [] | [] | [
"helper",
"list",
"python",
"sorting"
] | stackoverflow_0074250612_helper_list_python_sorting.txt |
Q:
How to insert data frame result into one specific column in python?
I have a data frame result which I need to insert into existing table line by line, How will I insert result into a specific column name - imgtext
table structure
As in SQL I know I can write query as -
INSERT INTO tableName(imgtext) VALUES('Lea... | How to insert data frame result into one specific column in python? | I have a data frame result which I need to insert into existing table line by line, How will I insert result into a specific column name - imgtext
table structure
As in SQL I know I can write query as -
INSERT INTO tableName(imgtext) VALUES('Learn MySQL INSERT Statement');
Python script:
This code takes some value f... | [
"to add value from CSV to your SQL table you will need to use a Python SQL Driver (pyodbc). Please see the sample code for connecting python to SQL.\nsample code:\nimport pyodbc\nimport pandas as pd\n\nserver = 'yourservername' \ndatabase = 'yourdatabasename' \nusername = 'username' \npassword = 'yourpassword' \n\n... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074250511_dataframe_pandas_python_python_3.x.txt |
Q:
Pandas - replacing column values
I know there are a number of topics on this question, but none of the methods worked for me so I'm posting about my specific situation
I have a dataframe that looks like this:
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
data['sex'].replace(0, 'Female')
... | Pandas - replacing column values | I know there are a number of topics on this question, but none of the methods worked for me so I'm posting about my specific situation
I have a dataframe that looks like this:
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
data['sex'].replace(0, 'Female')
data['sex'].replace(1, 'Male')
data
W... | [
"Yes, you are using it incorrectly, Series.replace() is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace keyword argument as True Example -\ndata['... | [
66,
9,
2,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0031888871_pandas_python.txt |
Q:
<__main__.User object at 0x000002C1B781D310> - python
Hello so im new to python and im in progress to learning class and function. I keep getting this error code, i don't know whats wrong on my code. Here is the source code:
class Data:
def __init__(self,nama):
self.nama=nama
def __private(self):
... | <__main__.User object at 0x000002C1B781D310> - python | Hello so im new to python and im in progress to learning class and function. I keep getting this error code, i don't know whats wrong on my code. Here is the source code:
class Data:
def __init__(self,nama):
self.nama=nama
def __private(self):
self.ganti="Replace"
def ganti(self):
se... | [
"You have some Syntax error in your code.\n\nVariable name and function name shouldn't be the same.\nWhen a variable is defined in init, all functions use it and there is no need to redefine it. Even when a class inherits from another class.\n\nThis code will print the output you want.\nclass Data:\n def __init_... | [
1
] | [] | [] | [
"class",
"function",
"inheritance",
"python"
] | stackoverflow_0074250537_class_function_inheritance_python.txt |
Q:
Python Turtle Graphics : Created class error when using goto
I am attempting to recreate the breakout game using turtle graphics.
however, whenever I try and move the bricks I've created from a custom class in my main script, I get an Attribute error -
AttributeError: 'Brick' object has no attribute '_drawing'.
I'... | Python Turtle Graphics : Created class error when using goto | I am attempting to recreate the breakout game using turtle graphics.
however, whenever I try and move the bricks I've created from a custom class in my main script, I get an Attribute error -
AttributeError: 'Brick' object has no attribute '_drawing'.
I've created paddles that work fine using the same method, however c... | [
"I think i might have figured out my answer.\nI think I am attempting to access the instance of the class i have created and not the brick object which is created as part of the class.\nif i do brick.brick.goto then i think it should work.\n"
] | [
0
] | [] | [] | [
"graphics",
"python",
"turtle_graphics"
] | stackoverflow_0074249436_graphics_python_turtle_graphics.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.