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 extract name and number and make new columns in pandas?
I have a column with a name and number, and I would like to extract the information and create 3 separate columns with the info in pandas using python. I'd like to also drop the original column. What is the most efficient code to do it? Is it feasible ... | How to extract name and number and make new columns in pandas? | I have a column with a name and number, and I would like to extract the information and create 3 separate columns with the info in pandas using python. I'd like to also drop the original column. What is the most efficient code to do it? Is it feasible with a single line?
The number has brackets [] around it, which I al... | [
"We can use str.extract here with 3 capture groups for each component:\ndf[[\"last\", \"first\", \"number\"]] = df[\"last_first_number\"].str.extract(r'(\\w+), (\\w+) \\[(\\d+)\\]')\n\n"
] | [
2
] | [] | [] | [
"lambda",
"pandas",
"python",
"strip"
] | stackoverflow_0074260115_lambda_pandas_python_strip.txt |
Q:
Django rest framework create or update in POST resquest
can anyone help please, with DRF
according to POST request, I want to create(if not exists) or update() table
belows are my codes
model.py
class User1(models.Model):
user = models.CharField(max_length=10)
full_name = models.CharField(max_length=20)
... | Django rest framework create or update in POST resquest | can anyone help please, with DRF
according to POST request, I want to create(if not exists) or update() table
belows are my codes
model.py
class User1(models.Model):
user = models.CharField(max_length=10)
full_name = models.CharField(max_length=20)
logon_data = models.DateTimeField(blank=True, null=True)
s... | [
"@api_view(['GET', 'POST'])\ndef UserView(request):\n if request.method == 'GET':\n users = User1.objects.all()\n serializer = UserSerializer(users, many=True)\n return Response(serializer.data)\n elif request.method == 'POST':\n serializer = UserSerializer(data=request.data, many=... | [
2,
0
] | [] | [] | [
"django",
"django_rest_framework",
"post",
"python"
] | stackoverflow_0074259926_django_django_rest_framework_post_python.txt |
Q:
what's the easiest way to explode/flatten deeply nested struct using pyspark?
i have an example dataset:
+---+------------------------------+
|id |example_field |
+---+------------------------------+
|1 |{[{[{111, AAA}, {222, BBB}]}]}|
+---+------------------------------+
The data type of the tw... | what's the easiest way to explode/flatten deeply nested struct using pyspark? | i have an example dataset:
+---+------------------------------+
|id |example_field |
+---+------------------------------+
|1 |{[{[{111, AAA}, {222, BBB}]}]}|
+---+------------------------------+
The data type of the two fields are:
[('id', 'int'),
('example_field',
'struct<xxx:array<struct<nested_... | [
"The following code should do the trick:\nfrom pyspark.sql import functions as F\n\n(\n df\n .withColumn('_temp_ef', F.explode('example_field.xxx'))\n .withColumn('_temp_nf', F.explode('_temp_ef.nested_field'))\n .select(\n 'id',\n F.col('_temp_nf.*')\n )\n)\n\nThe function explode crea... | [
1
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"pyspark",
"python"
] | stackoverflow_0074238177_apache_spark_apache_spark_sql_pyspark_python.txt |
Q:
MemoryError: Unable to allocate MiB for an array with shape and data type, when using anymodel.fit() in sklearn
Getting this memory error. But the book/link I am following doesn't get this error.
A part of Code:
from sklearn.linear_model import SGDClassifier
sgd_clf = SGDClassifier()
sgd_clf.fit(x_train, y_train)
... | MemoryError: Unable to allocate MiB for an array with shape and data type, when using anymodel.fit() in sklearn | Getting this memory error. But the book/link I am following doesn't get this error.
A part of Code:
from sklearn.linear_model import SGDClassifier
sgd_clf = SGDClassifier()
sgd_clf.fit(x_train, y_train)
Error:
MemoryError: Unable to allocate 359. MiB for an array with shape (60000, 784) and data type float64
I also ge... | [
"Upgrading python-64 bit seems to have solved all the \"Memory Error\" problem.\n",
"The message is straight forward, yes, it has to do with the available memory.\n359 MiB = 359 * 2^20 bytes = 60000 * 784 * 8 bytes\nwhere MiB = Mebibyte = 2^20 bytes, 60000 x 784 are the dimensions of your array and 8 bytes is the... | [
8,
7,
0
] | [
"Just Restart Your PC After Closing All Tabs And Softwares.\n"
] | [
-1
] | [
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0062839068_machine_learning_python_scikit_learn.txt |
Q:
Inline button in Telegram (using aiogram)
How to make an inline button handler, so that pressing button 10000 will output 1, and pressing button 20000 will output 2 etc. I searched all over the Internet, everything they write does not work(
kb_1 = InlineKeyboardButton(text='10000', callback_data='ib_1')
kb_2 = Inl... | Inline button in Telegram (using aiogram) | How to make an inline button handler, so that pressing button 10000 will output 1, and pressing button 20000 will output 2 etc. I searched all over the Internet, everything they write does not work(
kb_1 = InlineKeyboardButton(text='10000', callback_data='ib_1')
kb_2 = InlineKeyboardButton(text='20000', callback_data='... | [
"Try this:\nfrom aiogram.utils.callback_data import CallbackData\n\ncb_inline = CallbackData(\"post\", 'action', \"data\")\nkeyboard = InlineKeyboardMarkup(\n inline_keyboard= [\n InlineKeyboardButton(text='MyText', callback_data=cb_inline.new(action='myact', data='MyText')\n ]\n\n@dp.callback_quer... | [
0
] | [] | [] | [
"aiogram",
"python",
"telegram"
] | stackoverflow_0074256052_aiogram_python_telegram.txt |
Q:
(PYTHON) How to ALTOGETHER Add every Nth term of elements inside list to produce new list?
Let's say we have following list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
Now I want to add every 3 numbers together to provide length of 6 list thus,
[6, 15, 24, 33, 42, 51]
I want to do this in pyt... | (PYTHON) How to ALTOGETHER Add every Nth term of elements inside list to produce new list? | Let's say we have following list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
Now I want to add every 3 numbers together to provide length of 6 list thus,
[6, 15, 24, 33, 42, 51]
I want to do this in python.... please help! (was my question worded weirdly,,?)
Until now I tried
z = np.zeros(6)
p = 0... | [
"Consider using a list comprehension:\n>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]\n>>> [sum(nums[i:i+3]) for i in range(0, len(nums), 3)] \n[6, 15, 24, 33, 42, 51]\n\nOr numpy:\n>>> import numpy as np\n>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]\n>>> np... | [
8,
1
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074259924_list_python_python_3.x.txt |
Q:
How to change column name for multiple CSV into the same column name?
df1.rename(columns={'movie_title':'title'}, inplace=True)
For this it only change the specific of "movie_title". How do I code it in such a way that if it detects for example 'name' or 'titles' or 'movie_name' and change it in to 'title'?
A:
... | How to change column name for multiple CSV into the same column name? | df1.rename(columns={'movie_title':'title'}, inplace=True)
For this it only change the specific of "movie_title". How do I code it in such a way that if it detects for example 'name' or 'titles' or 'movie_name' and change it in to 'title'?
| [
"Add every option to the rename function:\ndf1.rename(columns={'name':'title','movie_name':'title', 'titles':'title'}, inplace=True)\n\nIf you want this fully automated you'll need to check for semantic similarity with title, eg using this module:\nfrom semantic_text_similarity.models import WebBertSimilarity\n\nwe... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074260164_python.txt |
Q:
How to change the default link time of pymysql
In my project, I used pandas and pymysql to read the database. The default setting is that pymysql will automatically disconnect after 8 hours if you do not perform any operation after creating a link.
I used close () to close the link, but the database shows that the... | How to change the default link time of pymysql | In my project, I used pandas and pymysql to read the database. The default setting is that pymysql will automatically disconnect after 8 hours if you do not perform any operation after creating a link.
I used close () to close the link, but the database shows that the link exists and has not been operated for more than... | [
"I gauss you can try to change \"wait_timeout\" in mysql system setting which default is 28800s\n",
"To set the timeout for pymysql read and write operations, use the following parameters that can be passed to pymysql.connections.Connection(..) when you establish the connection:\nread_timeout – The timeout for re... | [
0,
0
] | [] | [] | [
"pandas",
"pymysql",
"python"
] | stackoverflow_0074258368_pandas_pymysql_python.txt |
Q:
Adding Key and Value inside a list of lists python
I have data that looks like this [[{'title': 'Line'}], [{'title': 'asd'}]]. I want to add a new key and value for every list inside of lists.
I have tried this but I'm having an error 'list' object is not a mapping. Any suggestion?
data = [[{'title': 'Line'}], [{'... | Adding Key and Value inside a list of lists python | I have data that looks like this [[{'title': 'Line'}], [{'title': 'asd'}]]. I want to add a new key and value for every list inside of lists.
I have tried this but I'm having an error 'list' object is not a mapping. Any suggestion?
data = [[{'title': 'Line'}], [{'title': 'asd'}]]
titleID = [{'id': 373}, {'id': 374}]
co... | [
"Try this list comphrehension and unpacking\ndata = [[{'title': 'Line'}], [{'title': 'asd'}]]\ntitleID = [{'id': 373}, {'id': 374}]\n[[{**i[0], **j}] for i,j in zip(data, titleID)]\n\nOutput\n[[{'title': 'Line', 'id': 373}], [{'title': 'asd', 'id': 374}]]\n\n",
"You can use list comprehension for a one-liner:\n[[... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074260188_python.txt |
Q:
Providing fields for every id through network in pandas
I am sorry for re-posting this old question of mine but it has not been quite solved and the older post was getting long and confusing.
So, the issue is the one described below basically. A very good reply to the problem was given to me by applying network t... | Providing fields for every id through network in pandas | I am sorry for re-posting this old question of mine but it has not been quite solved and the older post was getting long and confusing.
So, the issue is the one described below basically. A very good reply to the problem was given to me by applying network theory and namely performing this:
# generate exploded version... | [
"Here is a different approach of your interesting question, less sophisticated and probably less efficient on your real data than your current solution, but I would be interested to know anyway.\ndef select_patents(dist, patents):\n \"\"\"Helper function.\n\n Args:\n dist: distances of cited patents.\n... | [
1
] | [] | [] | [
"networkx",
"pandas",
"python"
] | stackoverflow_0074179059_networkx_pandas_python.txt |
Q:
apply BorderIndex with xlwings
How do you use BorderIndex in xlwings?
sheet.range((4, 2), (Dimy+3, Dimx+1)
).api.BordersIndex.xlEdgeLeft = -4138
A:
Import the BordersIndex and LineStyle constants if you are wanting to use a border with other than solid line.
from xlwings.constants import BordersInd... | apply BorderIndex with xlwings | How do you use BorderIndex in xlwings?
sheet.range((4, 2), (Dimy+3, Dimx+1)
).api.BordersIndex.xlEdgeLeft = -4138
| [
"Import the BordersIndex and LineStyle constants if you are wanting to use a border with other than solid line.\nfrom xlwings.constants import BordersIndex, LineStyle\n\nThen specifiy for 'Border' and either set 'Weight' or 'LineStyle' at the same time as setting the border.\nCheck the xlwings constants file for th... | [
0
] | [] | [] | [
"python",
"xlwings"
] | stackoverflow_0074250512_python_xlwings.txt |
Q:
Can someone explain what exactly this error means,TypeError: issubclass() arg 1 must be a class
I have zero idea as to why I'm getting this error.
A:
as people said, the 2 arguments of issubclass() should be classes, not instances of an object.
consider this sample:
>>> issubclass( 1, int )
Traceback (most recen... | Can someone explain what exactly this error means,TypeError: issubclass() arg 1 must be a class | I have zero idea as to why I'm getting this error.
| [
"as people said, the 2 arguments of issubclass() should be classes, not instances of an object.\nconsider this sample:\n>>> issubclass( 1, int )\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: issubclass() arg 1 must be a class\n>>> issubclass( type(1), int )\nTrue \n>>> ... | [
24,
4,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002464568_python.txt |
Q:
While Loop displaying even numbers in Python
I am unable to solve this.
Problem Statement:-
Make use of while loop and print all positive even numbers smaller than or equal to the number given by the user
e.g.:-
User Input: 6
Output: 2, 4, 6
I have tried this but the code is running into an infinite loop.
num = i... | While Loop displaying even numbers in Python | I am unable to solve this.
Problem Statement:-
Make use of while loop and print all positive even numbers smaller than or equal to the number given by the user
e.g.:-
User Input: 6
Output: 2, 4, 6
I have tried this but the code is running into an infinite loop.
num = int(input("Please enter an even number: "))
i = 0
... | [
"Don't use a while loop here, just use a for loop:\nnum = int(input(\"Please enter an even number: \"))\n\nfor nr in range(0, num, 2):\n print(nr)\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074260237_python.txt |
Q:
How to return a substring using python if a particular substring occurs in the string?
I'm trying to return or print a specific substring that occurs before a search keyword in a very lengthy string using python.
For example if my string is as below
string = "id:0, an apple a day keeps the doctor away, id=1, orang... | How to return a substring using python if a particular substring occurs in the string? | I'm trying to return or print a specific substring that occurs before a search keyword in a very lengthy string using python.
For example if my string is as below
string = "id:0, an apple a day keeps the doctor away, id=1, oranges are orange not red, id=3, fox jumps over the dog, id=4, fox ate grapes"
If the search ke... | [
"You can use the following regex to return the indices and key word matches.\nimport re\n\ndef find_id(string, word):\n pattern = r'id[:=](\\d+),[\\w\\s]+' + word\n return list(map(int, re.findall(pattern, string)))\n\nstring = \"id:0, an apple a day keeps the doctor away, id=1, oranges are orange not red, id... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0074260133_python.txt |
Q:
Remove first occurrence of word in string
test = 'User Key Account Department Account Start Date'
I want to remove duplicate words from strings. The solution from this question functions well...
def unique_list(l):
ulist = []
[ulist.append(x) for x in l if x not in ulist]
return ulist
test = ' '.jo... | Remove first occurrence of word in string | test = 'User Key Account Department Account Start Date'
I want to remove duplicate words from strings. The solution from this question functions well...
def unique_list(l):
ulist = []
[ulist.append(x) for x in l if x not in ulist]
return ulist
test = ' '.join(unique_list(test.split()))
But it only keep... | [
"This should do the job:\ntest = 'User Key Account Department Account Start Date'\n\nwords = test.split()\n\n# if word doesn't exist in the rest of the word list, add it\ntest = ' '.join([word for i, word in enumerate(words) if word not in words[i+1:]])\n\nprint(test) # User Key Department Account Start Date\n\n",... | [
3,
1,
1,
1,
0,
0
] | [
"put all element in to a set.\ntokenize your sentence into strings and insert into a set.\nset<std::string> s;\n\ns.insert(\"aa\");\ns.insert(\"bb\");\ns.insert(\"cc\");\ns.insert(\"cc\");\ns.insert(\"dd\");\n\n"
] | [
-1
] | [
"duplicates",
"python"
] | stackoverflow_0068475659_duplicates_python.txt |
Q:
Use base64 encoded image in Google Chat card image widget
I am using the Google Chat card api to send a card back to a user to answer their questions. I wish to include an image within the results, however a direct URL cannot be provided since it is only exposed to the company network.
Instead I have attempted to ... | Use base64 encoded image in Google Chat card image widget | I am using the Google Chat card api to send a card back to a user to answer their questions. I wish to include an image within the results, however a direct URL cannot be provided since it is only exposed to the company network.
Instead I have attempted to do the following:
"image": {
"imageUrl": "data:image/png;ba... | [
"It is currently not possible to include base64-encoded images instead of providing an imageURL within a Google Chat Card\nA feature request to change this has already been filed on Google's Issue Tracker.\nCurrently this feature request is still under review and the best thing you can do is to \"star\" it to show ... | [
0
] | [] | [] | [
"google_apps_script",
"google_apps_script_api",
"google_chat",
"python"
] | stackoverflow_0074205826_google_apps_script_google_apps_script_api_google_chat_python.txt |
Q:
trying to delete inactive users in django
I am writing a site that sends confirmation emails on signup. Until the user clicks the link, the is_active field is set to false. How can I automatically delete any users who do not click the activation link within a certain period of time? Is this even a viable option or... | trying to delete inactive users in django | I am writing a site that sends confirmation emails on signup. Until the user clicks the link, the is_active field is set to false. How can I automatically delete any users who do not click the activation link within a certain period of time? Is this even a viable option or is there a better way to work around users who... | [
"I had the same problem, what i did was set a celery task that checks for user that hasn't activated their account after a specified period...\nyour task.py should be like this\n@shared_task(name=\"delete_unactivated_users\")\ndef delete_unactivated_users(self, *args, **kwargs):\n User = get_user_model() ... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_users",
"python"
] | stackoverflow_0048859515_django_django_forms_django_users_python.txt |
Q:
Django cannot find data that I'm sure exists in the database
basically my app receives a serial number through an AJAX POST request from the front end, and it has to find the product who's serial number matches the given serial number and return it's details.
here is my view , I have confirmed that the data is bei... | Django cannot find data that I'm sure exists in the database | basically my app receives a serial number through an AJAX POST request from the front end, and it has to find the product who's serial number matches the given serial number and return it's details.
here is my view , I have confirmed that the data is being received correctly and that a product with the exact serial num... | [
"I would try to filter it first manually like this:\nquery = request.body.decode('utf-8')\nobj = Products.objects.all()\nfirst_obj = obj.filter(serial_number=query)\nprint(first_obj)\n\nMake sure you really get query from the Ajax, I would get it like this:\nquery = request.POST.get('serial_numeber')\n\n",
"so if... | [
0,
0
] | [] | [] | [
"django",
"mariadb",
"python"
] | stackoverflow_0074260000_django_mariadb_python.txt |
Q:
Removing substring from string in Python
I want to write a function that takes 2 inputs: a string and a substring, then the function will remove that part of the substring from the string.
def remove_substring(s, substr):
"""(str, str) -> NoneType
Returns string without string substr
remove_substring_from_stri... | Removing substring from string in Python | I want to write a function that takes 2 inputs: a string and a substring, then the function will remove that part of the substring from the string.
def remove_substring(s, substr):
"""(str, str) -> NoneType
Returns string without string substr
remove_substring_from_string("Im in cs", "cs")
Im in
"""
other_s... | [
"Avoiding the use of Python functions.\nMethod 1\ndef remove_substring_from_string(s, substr):\n '''\n find start index in s of substring\n remove it by skipping over it\n '''\n i = 0\n while i < len(s) - len(substr) + 1:\n # Check if substring starts at i\n if s[i:i+len(substr)] == ... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0069519122_python.txt |
Q:
Labels(tkinter) in python, how can I update the value of a Label and then display it, without showing the previous values of that label?
So, I have this code, and it calculates an OTP(value) each time I click on Button(OTP), and that value is showed on myLabel. However, when it is displayed the values are getting ... | Labels(tkinter) in python, how can I update the value of a Label and then display it, without showing the previous values of that label? | So, I have this code, and it calculates an OTP(value) each time I click on Button(OTP), and that value is showed on myLabel. However, when it is displayed the values are getting accumulated, E.g. if I click on Button 10 times I will see 10 values on the WINDOW, but I dont want that, I want myLabel shows only one value ... | [
"Your function is creating a new label widget every time you click the button.\nInstead create the label outside of the function and update the text only when the function runs. For example:\nfrom tkinter import *\nimport hmac\nimport hashlib\n\nroot=Tk()\nroot.title(\"Client\")\nroot.geometry(\"200x500\")\n\nkey... | [
1
] | [] | [] | [
"object_oriented_analysis",
"python",
"tkinter"
] | stackoverflow_0074260194_object_oriented_analysis_python_tkinter.txt |
Q:
Merge 200 + Excel Files into 1
I have a folder with 200+ excel files. I have the respective path and sheet names for each file in the folder. Is it possible to merge all of these files into one or a couple large excel file via python? If so, what libraries would be good for me to start reading up on for this type ... | Merge 200 + Excel Files into 1 | I have a folder with 200+ excel files. I have the respective path and sheet names for each file in the folder. Is it possible to merge all of these files into one or a couple large excel file via python? If so, what libraries would be good for me to start reading up on for this type of script?
I am trying to condense t... | [
"For example, suppose there are a.xlsx, b.xlsx, c.xlsx.\nWith using os(by import os) and endswith method, you can take all xlsx files.(You would easily find how to do it)\nThen, read xlsx files in the loop(for or while statement) and with pandas and add it into a new excelwriter like below\ne.g.\nimport pandas as p... | [
0,
0
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074257433_excel_pandas_python.txt |
Q:
Cant get pyperclip to use copy and paste modules on python3
Specs:
Python3.5
Latest Pyperclip
Both xclip and python3-pyqt4 installed
using ssh(Putty) to connect to headleass raspberry pi 2 model B using Latest Raspian Stretch Light
Error: pyperclip.copy('Hello world!')
File "/usr/local/lib/python3.5/dist-packa... | Cant get pyperclip to use copy and paste modules on python3 | Specs:
Python3.5
Latest Pyperclip
Both xclip and python3-pyqt4 installed
using ssh(Putty) to connect to headleass raspberry pi 2 model B using Latest Raspian Stretch Light
Error: pyperclip.copy('Hello world!')
File "/usr/local/lib/python3.5/dist-packages/pyperclip/__init__.py", line 612, in lazy_load_stub_copy
... | [
"The clipboard is part of your GUI. But you don't have a GUI. So there is no clipboard to copy and paste with. There is no clipboard for pyperclip to access, so it doesn't matter how you try to access it, you're going to fail.\nYou can test very easily by running this at the shell:\nxclip\n\nIf it says something li... | [
11,
3,
0,
0,
0
] | [] | [] | [
"linux",
"python",
"raspberry_pi"
] | stackoverflow_0051662213_linux_python_raspberry_pi.txt |
Q:
Iterate an iterator by chunks (of n) in Python?
Can you think of a nice way (maybe with itertools) to split an iterator into chunks of given size?
Therefore l=[1,2,3,4,5,6,7] with chunks(l,3) becomes an iterator [1,2,3], [4,5,6], [7]
I can think of a small program to do that but not a nice way with maybe itertools... | Iterate an iterator by chunks (of n) in Python? | Can you think of a nice way (maybe with itertools) to split an iterator into chunks of given size?
Therefore l=[1,2,3,4,5,6,7] with chunks(l,3) becomes an iterator [1,2,3], [4,5,6], [7]
I can think of a small program to do that but not a nice way with maybe itertools.
| [
"The grouper() recipe from the itertools documentation's recipes comes close to what you want:\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n\nIt will fill up the last chunk with ... | [
170,
87,
16,
8,
7,
3,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0008991506_iterator_python.txt |
Q:
New columns with list of columns of databse tables
I have a DataFrame with a column with all the table names in my database of Databricks:
%sql
SHOW TABLES FROM default
tableName
table1
table2
table3
I wanted to add a column with a list of columns of each table:
tableName
tableColumns
table1
col1,col2,col3
... | New columns with list of columns of databse tables | I have a DataFrame with a column with all the table names in my database of Databricks:
%sql
SHOW TABLES FROM default
tableName
table1
table2
table3
I wanted to add a column with a list of columns of each table:
tableName
tableColumns
table1
col1,col2,col3
table2
col1
table3
col1,col2
I ... | [
"You won't be able to get that using a single Spark call, but you can just loop over tables in Python and collect column information one by one.\ntables = [row[\"tableName\"] for row in spark.sql(\"show tables from default\").collect()]\ntablesWithColumns = [[t, \",\".join(spark.table(\"default.\" + t).columns)] fo... | [
0
] | [] | [] | [
"database",
"databricks",
"pyspark",
"python"
] | stackoverflow_0074253960_database_databricks_pyspark_python.txt |
Q:
InvalidArgumentError on custom tensorflow model
As a part of TPS July challenge, I was trying to implement a custom tensorflow model based on Recurrent neural networks
Idea: I wanted to include an RNN, which predicts values at current iteration, based the model's prediction at previous iteration. So, I implemented... | InvalidArgumentError on custom tensorflow model | As a part of TPS July challenge, I was trying to implement a custom tensorflow model based on Recurrent neural networks
Idea: I wanted to include an RNN, which predicts values at current iteration, based the model's prediction at previous iteration. So, I implemented a custom Model, which saves output of current iterat... | [
"As Priya highlighted, the error says dim[0] which refers to the batch dimension so this answer might not solve your error but it will definitely help you implement your model.\nWithin your make_model() function, try changing dense_out to\ndense_out = tfa.layers.WeightNormalization(layers.Dense(8,activation='selu'... | [
0,
0
] | [] | [] | [
"lstm",
"python",
"tensorflow"
] | stackoverflow_0068281041_lstm_python_tensorflow.txt |
Q:
Why doesn't module openpyxl exist?
I am on Windows and have done pip3 install openpyxl.
I have also gotten "Requirement already satisfied: openpyxl in..."
However when I try to run a script that imports openpyxl, it gives:
ModuleNotFoundError: No module named 'openpyxl.
I have tried python -m pip install openpyxl... | Why doesn't module openpyxl exist? | I am on Windows and have done pip3 install openpyxl.
I have also gotten "Requirement already satisfied: openpyxl in..."
However when I try to run a script that imports openpyxl, it gives:
ModuleNotFoundError: No module named 'openpyxl.
I have tried python -m pip install openpyxl and python3 -m pip install openpyxl. Op... | [
"Realised I had many versions of Python installed in different directories, which messed with the pip installation of openpyxl.\nUninstalled them all and reinstalled Python 3.10, with pip in the same directory.\nReinstalled openpyxl, worked.\n\n"
] | [
1
] | [] | [] | [
"openpyxl",
"powershell",
"python"
] | stackoverflow_0074259568_openpyxl_powershell_python.txt |
Q:
Accuracy does not increase Pytorch
I'm currently working on a project using Pytorch. I want to evaluate the accuracy of a neural network but it seems it does not increase when the test is running. The output I get is:
As you can see, I print the accuracy of every epoch always getting the same number.
Here you are... | Accuracy does not increase Pytorch | I'm currently working on a project using Pytorch. I want to evaluate the accuracy of a neural network but it seems it does not increase when the test is running. The output I get is:
As you can see, I print the accuracy of every epoch always getting the same number.
Here you are the code of my classifier:
class Classi... | [] | [] | [
"The last layer of your model produces a tensor of shape (batch size, 1), since you have set out_features = 1. I assume your dataset has more than 1 class?\nWhen you are calculating your accuracy, torch.argmax(out, axis=1) will always give the same class index, being 0 in this case. This explains why your accuracy ... | [
-1
] | [
"deep_learning",
"machine_learning",
"neural_network",
"python",
"pytorch"
] | stackoverflow_0074260312_deep_learning_machine_learning_neural_network_python_pytorch.txt |
Q:
How to select a value from a JSON dictionary and assign the new selected value as a Key value?
This is the JSON data I have. I want to assign 'organization' as the new key and when I call 'organization' rest of the field data should appear based on the organization number.
{
"objects": {
"record": [
... | How to select a value from a JSON dictionary and assign the new selected value as a Key value? | This is the JSON data I have. I want to assign 'organization' as the new key and when I call 'organization' rest of the field data should appear based on the organization number.
{
"objects": {
"record": [
{
"organization": 3,
"code": 34,
"name": "Luku' Dean",
"... | [
"IIC you want a new dictionary with organization values as keys:\ndata = {\n \"objects\": {\n \"record\": [\n {\n \"organization\": 3,\n \"code\": 34,\n \"name\": \"Luku' Dean\",\n \"address_1\": \"\",\n \"address_2\": \"\",\n \"city\": \"\",\n ... | [
3
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074260530_json_python.txt |
Q:
How do I change the line thickness in a table using python docx
Line thickness 1 within a table
Line thickness 2 within a table
I am currently trying to change the line thicknesss of a table within a Microsoft word document. The table comes with a default line thickness of 1 pt, I am trying to find a way to change... | How do I change the line thickness in a table using python docx | Line thickness 1 within a table
Line thickness 2 within a table
I am currently trying to change the line thicknesss of a table within a Microsoft word document. The table comes with a default line thickness of 1 pt, I am trying to find a way to change the line thickness to 2pt using python docx.
| [
"documentation for setting table/cell border is available here: http://officeopenxml.com/WPtableBorders.php\ni've reused the existing code available to set table cell border answered here https://stackoverflow.com/a/49615968/5736491 and modified it to set single table property. this will set the uniform property fo... | [
0
] | [] | [] | [
"ms_word",
"python",
"python_docx"
] | stackoverflow_0072466704_ms_word_python_python_docx.txt |
Q:
How to debug Jupyter Notebook profile_default/startup File?
I am placing a .py file in Jupyter Notebook profile_default/startup folder. It has some problems, I want to debug and see the logs. Is there any way I see the output or logs generated by that file. I am on windows 10. There are a few methods .py file. I a... | How to debug Jupyter Notebook profile_default/startup File? | I am placing a .py file in Jupyter Notebook profile_default/startup folder. It has some problems, I want to debug and see the logs. Is there any way I see the output or logs generated by that file. I am on windows 10. There are a few methods .py file. I am using keyboard module to generate a hotkey whenever the noteboo... | [
"The easiest way I've found so far is to fire up ipython from your console.\nAssuming the error is not specific to how Jupyter starts the kernel, you will see the error with the stacktrace before the ipython shell starts.\nIf the error is specific to jupyter kernel, use jupyter kernel. It will start the kernel you ... | [
0
] | [] | [] | [
"ipython",
"jupyter_notebook",
"kernel",
"python"
] | stackoverflow_0068536121_ipython_jupyter_notebook_kernel_python.txt |
Q:
Cannot (always) fetch an attribute in an object even though it exists
I'm currently developing locally an Azure function that communicates with Microsoft Sentinel, in order to fetch the alert rules from it, and more specifically their respective querys :
credentials = AzureCliCredential()
alert_rules_operations = ... | Cannot (always) fetch an attribute in an object even though it exists | I'm currently developing locally an Azure function that communicates with Microsoft Sentinel, in order to fetch the alert rules from it, and more specifically their respective querys :
credentials = AzureCliCredential()
alert_rules_operations = SecurityInsights(credentials, SUBSCRIPTION_ID).alert_rules
list_alert_rules... | [
"I have tried with same as you used After I changed like below; I get the valid response.\n# Management Plane - Alert Rules\n\nalertRules = mgmt_client.alert_rules.list_by_resource_group('<ResourceGroup>')\nfor rule in alertRules:\n # Try this\n test.query = rule.query //Get the result\n #print(rule)\n\... | [
0,
0
] | [] | [] | [
"azure",
"azure_functions",
"azure_sentinel",
"python",
"python_3.x"
] | stackoverflow_0074113094_azure_azure_functions_azure_sentinel_python_python_3.x.txt |
Q:
pandas: create another data frame using existing data frame from the given index position
I have a following dataframe where I have one another list of index position based on some condition so just want to create the new dataframe based on the index position and check some condition on that.
df = pd.DataFrame()
d... | pandas: create another data frame using existing data frame from the given index position | I have a following dataframe where I have one another list of index position based on some condition so just want to create the new dataframe based on the index position and check some condition on that.
df = pd.DataFrame()
df['index'] = [ 0, 28, 35, 49, 85, 105, 208, 386, 419, 512, 816, 888, 914, 989]
df['diff_in_min'... | [
"From sample data for groups created by df['diff_in_min'] >= 300) add cumulative sum, then aggregate sum, compare for another condition and count Trues by sum:\ns = (df['diff_in_min'] >= 300).cumsum()\n\nout = (df['diff_in_min'].groupby(s).sum() > 500).sum()\nprint (out)\n2\n\n",
"jezrael's answer is much better ... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074260484_dataframe_pandas_python.txt |
Q:
Scraping table with Beautifulsoup and output to compare with value
I try to scrape a webpage with hourly energy prices. I want to use the data for home-automation. if the hourly price =< baseload price, certain times should turn on via Mqtt.
I managed to get the data from the baseload price and the hourly prices f... | Scraping table with Beautifulsoup and output to compare with value | I try to scrape a webpage with hourly energy prices. I want to use the data for home-automation. if the hourly price =< baseload price, certain times should turn on via Mqtt.
I managed to get the data from the baseload price and the hourly prices from its column. The output from the column seems not to be in one list b... | [
"You simply need to use join:\ncolumn3_text = \"\".join([td.text.strip() for td in column3])\n\n",
"In the for loop for columns in table, you are creating a new list column3_text. If you intend for column3 text to be a list of the next 24 hours, you can replace this for loop with this:\ncolumn3_text = [column.fin... | [
0,
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074260323_beautifulsoup_python_web_scraping.txt |
Q:
Making merged lists out of several lists of lists
I have four lists of lists each containing millions of data. The length of each individual list is always 2. e.g.,
L_1 = [[1,2], [3,4], [10,12]]
L_2 = [[5,9], [0,1]]
L_3 = [[3,5]]
L_4 = [[4,9]]
They always contain only integer values. I want to find all possible c... | Making merged lists out of several lists of lists | I have four lists of lists each containing millions of data. The length of each individual list is always 2. e.g.,
L_1 = [[1,2], [3,4], [10,12]]
L_2 = [[5,9], [0,1]]
L_3 = [[3,5]]
L_4 = [[4,9]]
They always contain only integer values. I want to find all possible combinations of L_1 and L_2 considering two conditions: ... | [
"You could use product from itertools and check your conditions with some if statements\n"
] | [
0
] | [] | [] | [
"dataframe",
"iteration",
"list",
"nested_lists",
"python"
] | stackoverflow_0074260681_dataframe_iteration_list_nested_lists_python.txt |
Q:
How to run a python script relative to its location?
I have a python script on another drive:
E:/myscripts/run.py
I am running this from cmd like this:
python
Once I am in the python interpreter, I just do this:
file = "E:/myscripts/run.py"
exec(open(file).read())
It throws an error "No such file or directory: ... | How to run a python script relative to its location? | I have a python script on another drive:
E:/myscripts/run.py
I am running this from cmd like this:
python
Once I am in the python interpreter, I just do this:
file = "E:/myscripts/run.py"
exec(open(file).read())
It throws an error "No such file or directory: config.txt". This is a file the script opens inside:
open(... | [
"In your run.py script, you could first use the OS package to determine the current path of your run.py script and thus load config.txt.\nTo determine the full path of your currently running script you can use the following command:\nimport os\npath2runpy = os.path.dirname(__file__)\n\nIf you print the variable pat... | [
1
] | [] | [] | [
"cmd",
"exec",
"python",
"python_3.x"
] | stackoverflow_0074260602_cmd_exec_python_python_3.x.txt |
Q:
How do I plot collections of patches of polygons with each collection of patches has a different color with matplotlib?
I have been trying to plot a bunch of polygons, which has been easy. But now I am trying to color code each polygon based on a certain parameter. First I grouped them in a dictionary under the pa... | How do I plot collections of patches of polygons with each collection of patches has a different color with matplotlib? | I have been trying to plot a bunch of polygons, which has been easy. But now I am trying to color code each polygon based on a certain parameter. First I grouped them in a dictionary under the parameter and then from the coordinates of each polygon made a polygon and appended it to a patch which then I put into a colle... | [
"You create your dictionary with duplicate keys, which probably isn't what you intend to do.\nIt's a little unclear what you're exactly trying to do. You keep appending to a single list (patches), causing every PatchCollection to contain incrementally more polygons, until the last one that contains all, and then ge... | [
1
] | [] | [] | [
"matplotlib",
"polygon",
"python"
] | stackoverflow_0074258801_matplotlib_polygon_python.txt |
Q:
Split AttributeError, "'str' object has no attribute 'spilt'"
text is shown below, I've searched high and low for the solution, but can't find anything. any help is appreciated
import random
from aiohttp import request
from aiohttp import web
from random import randint
response = request.__get__('https://svnweb.f... | Split AttributeError, "'str' object has no attribute 'spilt'" | text is shown below, I've searched high and low for the solution, but can't find anything. any help is appreciated
import random
from aiohttp import request
from aiohttp import web
from random import randint
response = request.__get__('https://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text%2Fplain'... | [
"You misspelled split.\nindivial_words = str(dootdoot).split() # instead of .spilt()\n\n"
] | [
1
] | [] | [] | [
"casting",
"module",
"python",
"python_module"
] | stackoverflow_0074260761_casting_module_python_python_module.txt |
Q:
String slugification in Python
I am in search of the best way to "slugify" string what "slug" is, and my current solution is based on this recipe
I have changed it a little bit to:
s = 'String to slugify'
slug = unicodedata.normalize('NFKD', s)
slug = slug.encode('ascii', 'ignore').lower()
slug = re.sub(r'[^a-z0-... | String slugification in Python | I am in search of the best way to "slugify" string what "slug" is, and my current solution is based on this recipe
I have changed it a little bit to:
s = 'String to slugify'
slug = unicodedata.normalize('NFKD', s)
slug = slug.encode('ascii', 'ignore').lower()
slug = re.sub(r'[^a-z0-9]+', '-', slug).strip('-')
slug = r... | [
"There is a python package named python-slugify, which does a pretty good job of slugifying:\npip install python-slugify\n\nWorks like this:\nfrom slugify import slugify\n\ntxt = \"This is a test ---\"\nr = slugify(txt)\nself.assertEquals(r, \"this-is-a-test\")\n\ntxt = \"This -- is a ## test ---\"\nr = slugify(txt... | [
194,
38,
12,
8,
8,
7,
4,
3,
1,
1,
0,
0
] | [] | [] | [
"python",
"slug"
] | stackoverflow_0005574042_python_slug.txt |
Q:
datetime strptime converts 10 to 01?
I am working with a date column in this form:
Date
1871.01
1871.02
...
1871.10
1871.11
So to convert the column to a datetimeindex, I use:
df["Date"].apply(lambda x: datetime.strptime(str(x), "%Y.%m"))
however the column is converted to:
Date
1871-01-01
1871-02-01
..... | datetime strptime converts 10 to 01? | I am working with a date column in this form:
Date
1871.01
1871.02
...
1871.10
1871.11
So to convert the column to a datetimeindex, I use:
df["Date"].apply(lambda x: datetime.strptime(str(x), "%Y.%m"))
however the column is converted to:
Date
1871-01-01
1871-02-01
...
1871-01-01
1871... | [
"If the first format is a float, the 1871.10 and 1871.1 are exactly the same numbers. So the string of it will have the second value (the shortest one). But then it would seems it is January (month 1).\nSo you should stringify forcing two digits:\ndf[\"Date\"].apply(lambda x: datetime.strptime(\"{:.2f}\" % x, \"%Y.... | [
0
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074257429_datetime_pandas_python.txt |
Q:
How to change value of variable inside sum() function?
i=1
if int(n)==sum(int(x)**i for x in str(n); i=i+1)
print("Disarum Number")
else:
print("Non-Disarum Number")
I expected the value of i to increase after each iteration. I wanted a short version of the following code :-
i=1
s=0
for x in str(n):
s=s+(... | How to change value of variable inside sum() function? | i=1
if int(n)==sum(int(x)**i for x in str(n); i=i+1)
print("Disarum Number")
else:
print("Non-Disarum Number")
I expected the value of i to increase after each iteration. I wanted a short version of the following code :-
i=1
s=0
for x in str(n):
s=s+(int(x)**i)
i=i+1
| [
"This should work (enumerate(iterable)) attaches indexes to the iterable).\nif int(n)==sum(int(x)**i for i,x in enumerate(str(n),1)):\n print(\"Disarum Number\")\nelse:\n print(\"Non-Disarum Number\")\n\nAnother way to do this would be to loop on the INDEX i, and retrieve the digit with str(n)[i] :\nif int(n) =... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074260294_python.txt |
Q:
Problem converting matlab code to python (numpy)
I have a code from this paper and trying to convert it to python (numpy especially). But in this code, it has a declare that confuse me.
XF=[X fit'];
The X is getting from
function[Best_score,Best_pos,DTBO_curve]=DTBO(SearchAgents,Max_iterations,lowerbound,upperbou... | Problem converting matlab code to python (numpy) | I have a code from this paper and trying to convert it to python (numpy especially). But in this code, it has a declare that confuse me.
XF=[X fit'];
The X is getting from
function[Best_score,Best_pos,DTBO_curve]=DTBO(SearchAgents,Max_iterations,lowerbound,upperbound,dimension,fitness)
lowerbound=ones(1,dimension).*(... | [
"It would have been better if you would have given the shapes of X and fit, but I guess it is something like:\nimport numpy as np\n\nN, M = 10, 20\nX = np.random.rand(N, M)\nfit = np.random.rand(M)\n\nXF = np.concatenate([X, fit[None, :]], axis=0)\nprint(XF.shape) # (11, 20)\n\nYou might also want to take a look a... | [
0
] | [] | [] | [
"matlab",
"numpy",
"python"
] | stackoverflow_0074259083_matlab_numpy_python.txt |
Q:
Web scraping for company logos from domain urls
I am working on web scraping from domain urls for scraping company logos using python.
import requests
url = "https://logo.clearbit.com/shopify.com"
payload={}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text... | Web scraping for company logos from domain urls | I am working on web scraping from domain urls for scraping company logos using python.
import requests
url = "https://logo.clearbit.com/shopify.com"
payload={}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
However, it just renders the image but I need the ... | [
"You can try using the requests_html library....\npip install requests-html\nfrom requests_html import HTMLSession\nsession = HTMLSession()\nresponse = session.get('https://en.wikipedia.org/wiki/Pepsi')\nselector = response.html.xpath(\"//img[contains(@alt,'logo')]/@src\")[0]\nprint(selector)\n\noutput:\n//upload.w... | [
0
] | [] | [] | [
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0074260609_python_python_requests_web_scraping.txt |
Q:
Python ,Duration Calcution between Timestamps
I'm working on backend ,Short Explanation :
I have 2 timestamps which are in this format "2022-10-29T16:30:00+05:30","2022-10-29T17:30:00+05:30" .I need to calculate this duration between these but I tried to figure out the format of this timestamp,so I could calculate... | Python ,Duration Calcution between Timestamps | I'm working on backend ,Short Explanation :
I have 2 timestamps which are in this format "2022-10-29T16:30:00+05:30","2022-10-29T17:30:00+05:30" .I need to calculate this duration between these but I tried to figure out the format of this timestamp,so I could calculate using datetime method in python.
| [
"This uses the method datetime.fromisoformat(date_string) to convert the ISO 8601-formatted string into a datetime object. From there, you can subtract to find the time difference. Additionally, you may want to add some code to check for negative results, or you can simply use the function abs(x).\nimport datetime\... | [
2
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0074260065_datetime_python.txt |
Q:
Django Auto Increment Field Non Pk
How to make the model so that each order that a costumer submit is gonna be auto incremented (ie. order_number) without messing with the order obj primary_key?
Models.py
class Customer(models.Model):
customer_name = models.CharField(max_length=100)
customerID = models.Cha... | Django Auto Increment Field Non Pk | How to make the model so that each order that a costumer submit is gonna be auto incremented (ie. order_number) without messing with the order obj primary_key?
Models.py
class Customer(models.Model):
customer_name = models.CharField(max_length=100)
customerID = models.CharField(max_length=100)
class Order(mode... | [
"What I think could work is using an IntegerField (pretty much what an AutoField uses under the hood), and increment that on the model's first save (before it's ever put into the database).\nexample:\nfrom django.db import models\n\nclass MyModel(models.Model):\n\n # This is what you would increment on save\n ... | [
2,
0,
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"django_views",
"python"
] | stackoverflow_0074260809_django_django_models_django_rest_framework_django_views_python.txt |
Q:
Python multiprocessing memory usage
I have writen a program that can be summarized as follows:
def loadHugeData():
#load it
return data
def processHugeData(data, res_queue):
for item in data:
#process it
res_queue.put(result)
res_queue.put("END")
def writeOutput(outFile, res_queue... | Python multiprocessing memory usage | I have writen a program that can be summarized as follows:
def loadHugeData():
#load it
return data
def processHugeData(data, res_queue):
for item in data:
#process it
res_queue.put(result)
res_queue.put("END")
def writeOutput(outFile, res_queue):
with open(outFile, 'w') as f
... | [
"The multiprocessing module is effectively based on the fork system call which creates a copy of the current process. Since you are loading the huge data before you fork (or create the multiprocessing.Process), the child process inherits a copy of the data.\nHowever, if the operating system you are running on imple... | [
30,
0
] | [] | [] | [
"linux",
"memory_management",
"multiprocessing",
"python"
] | stackoverflow_0014749897_linux_memory_management_multiprocessing_python.txt |
Q:
python image unified transform
I looking for a way to transform a Image into a another one.
The tool from GIMP work perfectly for my task: "Unified Transform Tool"
But is there a way to do it with a python lib? Like openCV or PIL?
My Goal is it to add images to mockup photos and I have to do it automaticly.
A:
I... | python image unified transform | I looking for a way to transform a Image into a another one.
The tool from GIMP work perfectly for my task: "Unified Transform Tool"
But is there a way to do it with a python lib? Like openCV or PIL?
My Goal is it to add images to mockup photos and I have to do it automaticly.
| [
"I don't know the GIMP technique, but it looks like a \"Scale Rotate Translate\" kind of thing which you can do in Python with wand.\nYou can do the same thing in the Terminal with ImageMagick. Tutorial and examples here.\n"
] | [
1
] | [] | [] | [
"gimp",
"image",
"opencv",
"python",
"python_imaging_library"
] | stackoverflow_0074260759_gimp_image_opencv_python_python_imaging_library.txt |
Q:
Pandas .loc with sort_values assignment does not work
I am trying to assign a value and/or a series of values to a slice of a pandas dataframe selected using .loc after sorting values.
For reference, this is the code I am trying to run, with a set string value ('filler')
df.sort_values(['col_1','col_2']).loc[
... | Pandas .loc with sort_values assignment does not work | I am trying to assign a value and/or a series of values to a slice of a pandas dataframe selected using .loc after sorting values.
For reference, this is the code I am trying to run, with a set string value ('filler')
df.sort_values(['col_1','col_2']).loc[
df.col_1.isin(rows_selector),col_2] = 'filler'
and with a ... | [
"You would need an intermediary step in this for it to work. While the sorted df called before the loc will be sorted, the df used in the loc (df.col_1.isin()) will still be calling from the unsorted df. For example:\ndf = pd.DataFrame({'col_1':[1,1,7,5,9,7],\n 'col_2':[4,1,5,6,6,3]})\n\n col_1... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"pandas_loc",
"python",
"sorting"
] | stackoverflow_0074260827_dataframe_pandas_pandas_loc_python_sorting.txt |
Q:
second occurence of substring
Please write a program which finds the second occurrence of a substring. If there is no second (or first) occurrence, the program should print out a message accordingly.
n=input("please type the word: ")
c=input("Please type in a substring: ")
index=n.find(c)
index2=n.find(c,index+1)
... | second occurence of substring | Please write a program which finds the second occurrence of a substring. If there is no second (or first) occurrence, the program should print out a message accordingly.
n=input("please type the word: ")
c=input("Please type in a substring: ")
index=n.find(c)
index2=n.find(c,index+1)
if index2==-1:
print("The subst... | [
"It's easy to see if you write it on paper and underline the sub-strings:\nabababa\n---\n ---\n ---\n\nThe substring is found three times, at index 0, index 2 and index 4.\nIf you want to skip overlapping sub-strings, you need to start the next search at index len(c):\nindex2 = n.find(c, index + len(c))\n\n"
] | [
0
] | [] | [] | [
"indexing",
"python",
"string"
] | stackoverflow_0074260864_indexing_python_string.txt |
Q:
How to get filenames list from S3 bucket using Boto3
How to get a list of all the filenames present in the s3 bucket.
import boto3
import pandas as pd
s3 = boto3.client('s3')
s3 = boto3.resource( service_name='s3', region_name='us',
aws_access_key_id='pjh', aws_secret_access_key='mm')
ob = []
for i in s3.Bucket('... | How to get filenames list from S3 bucket using Boto3 | How to get a list of all the filenames present in the s3 bucket.
import boto3
import pandas as pd
s3 = boto3.client('s3')
s3 = boto3.resource( service_name='s3', region_name='us',
aws_access_key_id='pjh', aws_secret_access_key='mm')
ob = []
for i in s3.Bucket('xyzbucket').objects.all():
ob.append(i)
test= []
for ... | [
"It should be:\ntest.append(i.key)\n\nnot\ntest.append(i['Contents']['key'])\n\n"
] | [
2
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"boto3",
"python"
] | stackoverflow_0074260866_amazon_s3_amazon_web_services_boto3_python.txt |
Q:
Different aggregate function based on value of column pandas
I have the following dataframe
import pandas as pd
test = pd.DataFrame({'y':[1,2,3,4,5,6], 'label': ['bottom', 'top','bottom', 'top','bottom', 'top']})
y label
0 1 bottom
1 2 top
2 3 bottom
3 4 top
4 5 bottom
5 6 top
I would l... | Different aggregate function based on value of column pandas | I have the following dataframe
import pandas as pd
test = pd.DataFrame({'y':[1,2,3,4,5,6], 'label': ['bottom', 'top','bottom', 'top','bottom', 'top']})
y label
0 1 bottom
1 2 top
2 3 bottom
3 4 top
4 5 bottom
5 6 top
I would like to add a new column, agg_y, which would be the the max(y) if l... | [
"Your solution in one line solution is:\ntest['agg_y'] = np.where(test.label == \"bottom\",\n test.groupby('label').y.transform('max'), \n test.groupby('label').y.transform('min'))\n\nSolution without groupby, thank you @ouroboros1:\ntest['agg_y'] = np.where(test.labe... | [
4
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074260802_pandas_python.txt |
Q:
How to lock /check if locked linux file in python
I need to implement the following functionality
locked = False
while not locked:
file_path = get_file_path_from_poll()
locked = try_lock_file(file_path)
if locked:
# do some staff
locked = True
release_lock(file_path)
How can this ... | How to lock /check if locked linux file in python | I need to implement the following functionality
locked = False
while not locked:
file_path = get_file_path_from_poll()
locked = try_lock_file(file_path)
if locked:
# do some staff
locked = True
release_lock(file_path)
How can this be implemented in python?
I need to work with Linux fil... | [
"Here are very simplistic examples of using fcntl\nhttps://docs.python.org/3/library/fcntl.html#module-fcntl\nThe first uses LOCK_NB to avoid blocking, the second doesn't, which means it will block, waiting for file access.\nimport fcntl\nimport time\nprint('Attempting to lock file')\nf = open('./locked.txt', 'w')\... | [
1
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0074260131_linux_python.txt |
Q:
cURL an API in python and return the response as JSON
I'm learning Python and try to use it in my class project. I'm looking for a way to curl an API and return the response json. For example, the response after curling an API is JSON and how can I return it also as JSON
response = requests.get("https://gi... | cURL an API in python and return the response as JSON | I'm learning Python and try to use it in my class project. I'm looking for a way to curl an API and return the response json. For example, the response after curling an API is JSON and how can I return it also as JSON
response = requests.get("https://github.com/timeline.json")
response = response.conten... | [
"response = requests.get(\"https://github.com/timeline.json\")\nresponse_json = response.json()\nprint(response_json[\"message\"])\nprint(response_json[\"documentation_url\"])\n\nThe method json() returns the json-encoded content of a response as a dict. Additionally, you may want to use the new API at https://api.... | [
1
] | [] | [] | [
"python",
"python_requests"
] | stackoverflow_0074260909_python_python_requests.txt |
Q:
How to know which extension is chaning the code in VSCode
I have this code in VSCode:
import django
from models import Product
The problem is that when I save the file, VSCode change the code (somehow trying to beautify it):
from models import Product
import django
I had this Prettier extension, and I disabled i... | How to know which extension is chaning the code in VSCode | I have this code in VSCode:
import django
from models import Product
The problem is that when I save the file, VSCode change the code (somehow trying to beautify it):
from models import Product
import django
I had this Prettier extension, and I disabled it, but I still got the problem.
| [
"I turned off all the related extensions, but it didn't work.\nSOLUTION:\nIn the end, what worked for me was to turn the Format On Save off.\nIn VSCode: File -> Preferences -> Settings -> Text Editor -> Formatting.\nHere turn the Format On Save off.\n"
] | [
0
] | [] | [] | [
"django",
"python",
"visual_studio_code"
] | stackoverflow_0074252219_django_python_visual_studio_code.txt |
Q:
website search bar doesn't work for python selenium
I would like auto-click the website and search for the information, but somehow the website cannot search, and keep loading. Or just close quickly after it print the key in search bar.
I would like auto-click the website and search for the information, and I trie... | website search bar doesn't work for python selenium | I would like auto-click the website and search for the information, but somehow the website cannot search, and keep loading. Or just close quickly after it print the key in search bar.
I would like auto-click the website and search for the information, and I tried:
import selenium
import pandas as pd
import numpy as np... | [
"There are several issues here:\n\nto prevent site from very long loading you can use eager pageLoadStrategy.\nI see redundant ) at the end of this line driver.find_element('xpath', '//*[@id=\"inputSuggest\"]').send_keys('sz111973'))\nThe following code works perfect:\n\nfrom selenium import webdriver\nfrom seleniu... | [
0
] | [] | [] | [
"pageloadstrategy",
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074260729_pageloadstrategy_python_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
Python regular expression to match everything until the last occurrence of before string with :
How can I create regular expression to return data in a correct way? I think I should somehow use lookahead, but I can't figure out the correct way.
My code:
import re
txt = "Person:Tester Test<br>Count:1<br>Testing:... | Python regular expression to match everything until the last occurrence of before string with : | How can I create regular expression to return data in a correct way? I think I should somehow use lookahead, but I can't figure out the correct way.
My code:
import re
txt = "Person:Tester Test<br>Count:1<br>Testing:test<br>Additional Information:test1<br>test2<br>test3<br>Temp:123<br>"
x = re.findall("(.*?<br>)", tx... | [
"You can use\n.*?<br>(?=\\w+:|$)\n\nSee the regex demo.\nDetails:\n\n.*? - zero or more chars other than line break chars as few as possible\n<br> - a fixed string\n(?=\\w+:|$) - a positive lookahead that requires one or more letters/digits/underscores and then a colon immediately to the right of the current locati... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074260963_python_regex.txt |
Q:
How to cluster names
I have a dataset of words in a non-semantic context, basically names. I want to perform an act of grouping all the similar ones (say samantha, samanta, sammanta, samaynta.. ) in the same groups.
Since it is a non-semantic context, I cannot vectorize the data using TF-IDF or something else, so ... | How to cluster names | I have a dataset of words in a non-semantic context, basically names. I want to perform an act of grouping all the similar ones (say samantha, samanta, sammanta, samaynta.. ) in the same groups.
Since it is a non-semantic context, I cannot vectorize the data using TF-IDF or something else, so I am using the data as it ... | [
"For clustering you need a distance metric, such as the Levenshtein distance. If that does not give you the desired result, you need to use another one.\nI would start by defining what you mean by similar: obviously it is not similarity in spelling, as otherwise the Levenshtein distance should work. What else is th... | [
0
] | [] | [] | [
"artificial_intelligence",
"cluster_analysis",
"levenshtein_distance",
"python",
"text"
] | stackoverflow_0074253414_artificial_intelligence_cluster_analysis_levenshtein_distance_python_text.txt |
Q:
Why do I have more row after the left merge and drop_duplciates()?
iso_selected.shape gives the result: (257, 2)
gravity.shapegives the result: (4428288, 79)
and I merge them in the following way:
gravity1 = gravity.merge(iso_selected, how="left", left_on = "iso3_o", right_on="iso3").drop_duplicates()
gravity1.sha... | Why do I have more row after the left merge and drop_duplciates()? | iso_selected.shape gives the result: (257, 2)
gravity.shapegives the result: (4428288, 79)
and I merge them in the following way:
gravity1 = gravity.merge(iso_selected, how="left", left_on = "iso3_o", right_on="iso3").drop_duplicates()
gravity1.shape gives the result: (4571136, 81)
Why would I have more rows than 44282... | [
"You need remove duplicates before DataFrame.merge by column iso3_o:\ngravity1 = gravity.merge(iso_selected.drop_duplicates(subset=[\"iso3_o\"]), \n how=\"left\", \n on = \"iso3_o\")\n\n"
] | [
0
] | [] | [] | [
"merge",
"pandas",
"python"
] | stackoverflow_0074260941_merge_pandas_python.txt |
Q:
How to read data in tf.Tensor
I have dataset for video captioning project. The dataset pipeline for training is Built as:
dataset = tf.data.Dataset.from_tensor_slices((videos , tf.ragged.constant(captions)))
I want to read all batch_data that goes to training step which is look like:
class VideoCaptioningModel(ke... | How to read data in tf.Tensor | I have dataset for video captioning project. The dataset pipeline for training is Built as:
dataset = tf.data.Dataset.from_tensor_slices((videos , tf.ragged.constant(captions)))
I want to read all batch_data that goes to training step which is look like:
class VideoCaptioningModel(keras.Model):
.
.
.
def train_ste... | [
"Your dataset consists of videos and captions and each entry in your dataset is a tuple. See:\nfor x in dataset:\n tf.print(x[0]) # videos\n tf.print(x[1]) # captions\n\nNow, note that you can call .numpy() on a tf.Tensor in Eager Execution mode, but tuples do not have this property. So try:\ntf.print('batch_data... | [
1
] | [] | [] | [
"dataset",
"python",
"tensorflow"
] | stackoverflow_0074258977_dataset_python_tensorflow.txt |
Q:
Is there any faster ways to make DataFrame with .describe() values?
I have DataFrame with 20000 rows and 1600 columns. Each row represent an observed object and each column is a date. Example:
df2 = pd.DataFrame(np.array([[1, 2, 3, 4, 5], [6, np.NaN, np.NaN, np.NaN, 10], [np.NaN, np.NaN, 14, 13, 15], [16, 17, 18, ... | Is there any faster ways to make DataFrame with .describe() values? | I have DataFrame with 20000 rows and 1600 columns. Each row represent an observed object and each column is a date. Example:
df2 = pd.DataFrame(np.array([[1, 2, 3, 4, 5], [6, np.NaN, np.NaN, np.NaN, 10], [np.NaN, np.NaN, 14, 13, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]),
columns=['2016-01-01'... | [
"Instead of your loop just use:\ndf = df2.T.describe()\n\n"
] | [
0
] | [] | [] | [
"optimization",
"pandas",
"python"
] | stackoverflow_0074260943_optimization_pandas_python.txt |
Q:
Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:
I am new to programming, this is actually my first work assignment with coding. my code below is throwing an error:
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect.
I'm ... | Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: | I am new to programming, this is actually my first work assignment with coding. my code below is throwing an error:
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect.
I'm not able to find where the issue is.
import os
folders = ["pdcom1", "pdcom1reg", "pdcomopen"]
for fold... | [
"As it solved the problem, I put it as an answer.\nDon't use single and double quotes, especially when you define a raw string with r in front of it. \nThe correct call is then\npath = r\"C:\\Apps\\CorVu\\DATA\\Reports\\AlliD\\Monthly Commission Reports\\Output\\pdcom1\"\n\nor \npath = r'C:\\Apps\\CorVu\\DATA\\Repo... | [
36,
4,
3,
2,
2,
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0033618656_python.txt |
Q:
How to compare column in different dataframes for fragment of characters in python
I have two dataframes of different size but common columns, with ID numbers as key column.
I want to compare the column "names" in both dataframes.
But sometimes the "names" does not match because there are upper cases or there are ... | How to compare column in different dataframes for fragment of characters in python | I have two dataframes of different size but common columns, with ID numbers as key column.
I want to compare the column "names" in both dataframes.
But sometimes the "names" does not match because there are upper cases or there are additional uncommon words.
Is there a way to "match" the column with something like a "t... | [
"You can use TheFuzz; Is a package that implements Levenshtein distance in python.\nfrom thefuzz import fuzz\n\ndf3 = df1.merge(df2, how='inner', on='key_column', suffixes=['_df1', '_df2'])\n\nthreshold = 50 # Value range: 0-100\nrow_selection = df3.apply(lambda row: fuzz.ratio(row['names_df1'], row['names_df2']) >... | [
1
] | [] | [] | [
"comparison",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074260981_comparison_dataframe_pandas_python.txt |
Q:
Yahoo Finance API yf.Ticker(ticker).info to CSV problem
When I'm using
ticker = "MSFT"
stock = yf.Ticker('MSFT').history('5y')
stock
I get a dataframe in response
When I use
ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info
I'm receiving a list from Yahoo finance API. How can I transform this lis... | Yahoo Finance API yf.Ticker(ticker).info to CSV problem | When I'm using
ticker = "MSFT"
stock = yf.Ticker('MSFT').history('5y')
stock
I get a dataframe in response
When I use
ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info
I'm receiving a list from Yahoo finance API. How can I transform this list to a Dataframe in Pandas?
So I could use
stock.to_csv(folde... | [
"The response is a dict so wrap it in square brackets and pass it to pandas.\npd.DataFrame([stock_info]).to_csv(\"/path/to/write/MSFT.csv\", index=False)\n\n",
"I fixed it using\n stock_info\n df = pd.DataFrame.from_dict(stock_info,orient='index').T\n\n\nThanks anyway :-)\n"
] | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"yahoo",
"yahoo_finance"
] | stackoverflow_0074255549_dataframe_pandas_python_yahoo_yahoo_finance.txt |
Q:
Python binance api order bid and ask
I connected to Binance api and download the recent orders and put them in a dataframe using Python.
I need to get di "bid orders" and "ask orders" to calculate the delta for each candlestick.
Basically, to calculate the delta it's very simple, is Volume of trading at the Ask pr... | Python binance api order bid and ask | I connected to Binance api and download the recent orders and put them in a dataframe using Python.
I need to get di "bid orders" and "ask orders" to calculate the delta for each candlestick.
Basically, to calculate the delta it's very simple, is Volume of trading at the Ask price – Volume of trading at the Bid price.
... | [] | [] | [
"priceslist = client.get_order_book(symbol='BTCBUSD')\n\nthis could help you\n"
] | [
-1
] | [
"binance",
"cryptocurrency",
"python"
] | stackoverflow_0074192214_binance_cryptocurrency_python.txt |
Q:
Copy the values from another column if the column A has null values
How to copy the values from column A to column B, if the column B has null values.
DATA:
A B
12525 1FWE23
14654
24798
38945
46456 46485
AD545 45346
A5D66
EXPECTED :
A ... | Copy the values from another column if the column A has null values | How to copy the values from column A to column B, if the column B has null values.
DATA:
A B
12525 1FWE23
14654
24798
38945
46456 46485
AD545 45346
A5D66
EXPECTED :
A B
12525 1FWE23
14654 14654
24798 24798
389... | [
"If your blank values are nan, you can just use fillna():\ndf['B'] = df['B'].fillna(df['A'])\n\n A B \n12525 1FWE23 \n14654 14654 \n24798 24798 \n38945 38945 \n46456 46485 \nAD545 45346 \nA5D66 A5D66 \n\nIf they are empty strings, you can replace() them with na... | [
1,
0
] | [
"df['B'] = df['B'].fillna(df['A'])\n\nThe above code fixed the issue for me by replacing the blank values in the column B with the column A values\n"
] | [
-1
] | [
"dataframe",
"python"
] | stackoverflow_0074261257_dataframe_python.txt |
Q:
how to download excel file in python and streamlit?
I have a Python script that read files and convert it to dataframe using Python and streamlit. Then I want to create a function to allows the user to download this dataframe as an Excel file with extension .xls.
So I tried to read the dataframe and convert it to ... | how to download excel file in python and streamlit? | I have a Python script that read files and convert it to dataframe using Python and streamlit. Then I want to create a function to allows the user to download this dataframe as an Excel file with extension .xls.
So I tried to read the dataframe and convert it to an Excel file using these two functions:
pd.ExcelWriter
d... | [
"With the streamlit latest release(above 1.0.0):\nUse\nst.download_button\n\nDisplays a download button widget.\nThis is useful when you would like to provide a way for your users to download a file directly from your app.\nNote that the data to be downloaded is stored in memory while the user is connected, so it's... | [
6,
1
] | [
"line 5 can't be executed since you havent assigned any excel to the DataFrame df.\ntry something like this in your code:\ndf = pd.read_csv('update2.xlsx')\n\nI hope, this helped.\nTake care\n",
"def get_binary_file_downloader_html(bin_file, file_label='File'):\n with open(bin_file, 'rb') as f:\n data... | [
-2,
-3
] | [
"excel",
"pandas",
"pandas.excelwriter",
"python",
"streamlit"
] | stackoverflow_0067564627_excel_pandas_pandas.excelwriter_python_streamlit.txt |
Q:
How to denote null values and empty lists and dictionaries in Firebase's Realtime Database?
I want to be able to denote the following as an actual value in Firebase's Realtime Database:
Empty lists
Empty dictionaries
Null / none / nil
These values, when posted to the database along with the key, will not show up... | How to denote null values and empty lists and dictionaries in Firebase's Realtime Database? | I want to be able to denote the following as an actual value in Firebase's Realtime Database:
Empty lists
Empty dictionaries
Null / none / nil
These values, when posted to the database along with the key, will not show up in the database. For example, this is what an example database would look like before the update... | [
"The answer is that you shouldn't do this. Storing null values in a NoSQL database is not advised.\nYour code should instead have logic to validate if a key is present and then respond accordingly to your needs. You're already adding logic to turn null values into fake-null values, so you're basically already doing... | [
0
] | [] | [] | [
"firebase_realtime_database",
"python"
] | stackoverflow_0074261059_firebase_realtime_database_python.txt |
Q:
How do I select pseudo-elements in python with Selenium?
These two elements have the exact same attributes except for the text in the pseudo-element. Is there anyway I can click on the "Practical" element. I've tried the following to no avail:
driver.find_element(By.XPATH, "//div[contains(text(),'Practical')]").cl... | How do I select pseudo-elements in python with Selenium? |
These two elements have the exact same attributes except for the text in the pseudo-element. Is there anyway I can click on the "Practical" element. I've tried the following to no avail:
driver.find_element(By.XPATH, "//div[contains(text(),'Practical')]").click()
driver.find_element(By.XPATH, "//div[@class='v-tab']")[... | [
"Pseudo elements are not elements. So, that ::before seems to be just a kind of text content of div element.\nI can't give you tested answer since you didn't share a link to the page you are working on, but I can suggest.\nI'd try this:\ndriver.find_element(By.XPATH, \"//div[@class='v-tab'][contains(.,'Practical')]... | [
0
] | [] | [] | [
"html",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074261218_html_python_selenium_selenium_webdriver.txt |
Q:
How to put a multiline newline - delimit json which I am trying to put in a pandas Dataframe?
I have this ndjson file from a yelp API. I am trying to put it into a pandas dataframe. Eachline has a nested json.
How do I put it into a pandas dataframe? this is what I have so far
`
bn=pd.DataFrame(df.result.values.to... | How to put a multiline newline - delimit json which I am trying to put in a pandas Dataframe? | I have this ndjson file from a yelp API. I am trying to put it into a pandas dataframe. Eachline has a nested json.
How do I put it into a pandas dataframe? this is what I have so far
`
bn=pd.DataFrame(df.result.values.tolist())['extractorData']
sj = pd.json_normalize(bn)
`
I tried to itrate through explode but unfor... | [
"you can use:\ndf=pd.read_json('https://gist.githubusercontent.com/rfmcnally/0a5a16e09374da7dd478ffbe6ba52503/raw/095e75121f31a8b7dc88aa89dbd637a944ce264a/ndjson-sample.json',lines=True)\n\n#convert result column\ndf1=df.join(df['result'].apply(pd.Series)).drop(['result'],axis=1)\n\n#convert pageData and rename. Be... | [
0
] | [] | [] | [
"dataframe",
"json",
"nested",
"pandas",
"python"
] | stackoverflow_0074259860_dataframe_json_nested_pandas_python.txt |
Q:
convert python to dart
I want to know how I can write the following python code in dart.
encrypt = str.maketrans({'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5',
'f': '6', 'g': '7', 'h': '8', 'i': '9', 'j': 'A',
'k': 'B', 'l': 'C', 'm': 'D', 'n': 'E', 'o': 'F',
'p': 'F', 'q': 'H... | convert python to dart | I want to know how I can write the following python code in dart.
encrypt = str.maketrans({'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5',
'f': '6', 'g': '7', 'h': '8', 'i': '9', 'j': 'A',
'k': 'B', 'l': 'C', 'm': 'D', 'n': 'E', 'o': 'F',
'p': 'F', 'q': 'H', 'r': 'I', 's': 'J', 't': ... | [
"From my understating, you are trying to encrypt a text and convert each letter into a new one. In dart there is no such method like maketrans, but you can use a normal key-value map for this purpose:\nimport 'dart:convert';\nimport 'dart:io';\n\nmain() {\n Map<String, String> letterMap = {\n 'a': '1',\n 'b'... | [
0
] | [] | [] | [
"dart",
"python"
] | stackoverflow_0074261182_dart_python.txt |
Q:
(Python) How to pull random elements from a list according to user input?
I'm writing a program which will create 4 lists with words in them. A user is prompted to answer how many words they'd like to print from list A, how many from list B, how many from list C, D etc. and the program randomly chooses those words... | (Python) How to pull random elements from a list according to user input? | I'm writing a program which will create 4 lists with words in them. A user is prompted to answer how many words they'd like to print from list A, how many from list B, how many from list C, D etc. and the program randomly chooses those words and prints them out.
I've got the shell out ready, the lists are made up, and ... | [
"Python has the built-in module random that contains a function known as choice which randomly selects an element from a list. Import it using the following.\nfrom random import choice\n\nx is that list containing the words.\nn is how much you want the new list elements be.\nacc is an accumulator.\nHow this functio... | [
1,
0,
0
] | [] | [] | [
"python",
"user_input"
] | stackoverflow_0074253077_python_user_input.txt |
Q:
I have one N-queen problem As I want to know the approach I am using is correct or not
My concern is that I have problem of N*N chess board in which I have to place my queen in such a way that no other queen should be attack over each other either in row, column or diagonal, So my first approach is I have taken a ... | I have one N-queen problem As I want to know the approach I am using is correct or not | My concern is that I have problem of N*N chess board in which I have to place my queen in such a way that no other queen should be attack over each other either in row, column or diagonal, So my first approach is I have taken a variable in which I have value of 0 and I am letting that (1) will be the position of queen ... | [
"There's a much better approach than your first:\nIf you take into consideration that each queen will have to occupy one column and one row, You realize that the queen positions form a bijection from {A, B, C, D, E, F, G, H} to {1, 2, 3, 4, 5, 6, 7, 8}. Once you've figured how to enumerate only these bijections, yo... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074261361_python.txt |
Q:
How to get key filtered by its value in multidimensional array Python
I got this data
employee_detail_list = {
'John Doe': {
'name': 'EMP-0001',
'first_name': 'John',
'last_name': 'Doe',
'full_name': 'John Doe',
'company': 'Company 1'
},
'Tom Smit... | How to get key filtered by its value in multidimensional array Python | I got this data
employee_detail_list = {
'John Doe': {
'name': 'EMP-0001',
'first_name': 'John',
'last_name': 'Doe',
'full_name': 'John Doe',
'company': 'Company 1'
},
'Tom Smith': {
'name': 'EMP-0002',
'first_name': 'Tom',
... | [
"It does what you need. .items() returns data as iterable objects that can be traversed.\nfor key, value in employee_detail_list.items():\n if value[\"company\"] == \"Company 2\":\n print(key)\n\n# Output\nTom Smith\nAndrew Sebastian\n\nThe problem with your solution is that val_list = list(employee_detai... | [
1,
1
] | [] | [] | [
"arrays",
"multidimensional_array",
"python"
] | stackoverflow_0074261281_arrays_multidimensional_array_python.txt |
Q:
python read outlook emails with oauth2
I've been using basic auth to log in to my outlook email with imap.
imap = imaplib.IMAP4_SSL("imap-mail.outlook.com")
# authenticate
imap.login(username, password)
status, messages = imap.select("INBOX")
Now that Microsoft moved to oauth2 I'm getting "Login failed" messages ... | python read outlook emails with oauth2 | I've been using basic auth to log in to my outlook email with imap.
imap = imaplib.IMAP4_SSL("imap-mail.outlook.com")
# authenticate
imap.login(username, password)
status, messages = imap.select("INBOX")
Now that Microsoft moved to oauth2 I'm getting "Login failed" messages even although the credentials are correct.
C... | [
"This is my solution,\n\nfollow this guide to create an app with necessary permissions.\n\nhttps://docs.emailengine.app/setting-up-oauth2-with-outlook/#:%7E:text=Navigate%20to%20Configuration-%3EOAuth2%20and,of%20accounts%20your%20application%20supports\n\nuse the following code in your app.\nimap = imaplib.IMAP4_S... | [
2
] | [] | [] | [
"imap",
"oauth_2.0",
"office365",
"python",
"python_3.x"
] | stackoverflow_0074251788_imap_oauth_2.0_office365_python_python_3.x.txt |
Q:
Scikit-learn: NameError: name 'load_iris' is not defined
I got the error message of scikit-learn: iris database = load_iris () and after I get the error :NameError: name 'load_iris' is not defined
What could be the problem? Help me please!
I use :
Phyton 3.9.5
Anaconda 4.10.1
Scikit-learn 2.2.0
A:
from sklearn.d... | Scikit-learn: NameError: name 'load_iris' is not defined | I got the error message of scikit-learn: iris database = load_iris () and after I get the error :NameError: name 'load_iris' is not defined
What could be the problem? Help me please!
I use :
Phyton 3.9.5
Anaconda 4.10.1
Scikit-learn 2.2.0
| [
"from sklearn.datasets import load_iris\n\niris = load_iris()\n\nprint(iris.data)\nprint(iris.target)\n\nhttps://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html\nhttps://scikit-learn.org/stable/tutorial/basic/tutorial.html\n",
"You have to import load_iris first. Try this:\nfrom sklearn.... | [
0,
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0069675761_python_scikit_learn.txt |
Q:
httpx.ReadTimeout on Range filter on Supabase-py
I have 375000 items in my table.
I am doing a loop to obtain all id of all items, with API limit set to 20000 items per api call.
After 200000 I always start to get httpx.ReadTimeout: The read operation timed out sometime it may reach 240000 but never go ahead.
I ha... | httpx.ReadTimeout on Range filter on Supabase-py | I have 375000 items in my table.
I am doing a loop to obtain all id of all items, with API limit set to 20000 items per api call.
After 200000 I always start to get httpx.ReadTimeout: The read operation timed out sometime it may reach 240000 but never go ahead.
I have tried to have different wait time after each loop.
... | [
"I had the same problem, so I create a function to get 1000 item and merge it!\nthis is my code:\ndef count_data(tb_name: str, field_name: str):\nreturn supabase.table(tb_name).select(field_name, count='exact').execute().count\n\n\ndef get_field_data(tb_name: str, src_field: str, len_record: int, id_field: str = 'i... | [
1
] | [] | [] | [
"python",
"supabase_py"
] | stackoverflow_0074186356_python_supabase_py.txt |
Q:
Python variables in Spark dataframes
Being a bit new to Pyspark I've hit an issue where passing Python variables into Spark commands is concerned. I need to vary the year in a spark condition so I have a variable CurrentYear = '2022'.
In spark I want to compare a column with that value, so something like
.withColu... | Python variables in Spark dataframes | Being a bit new to Pyspark I've hit an issue where passing Python variables into Spark commands is concerned. I need to vary the year in a spark condition so I have a variable CurrentYear = '2022'.
In spark I want to compare a column with that value, so something like
.withColumn('IsCurrentYear',when(col('ColumnName') ... | [
"Just lit(CurrentYear) will work, which would be equivalent to lit('2022')\nCurrentYear = '2022'\n.withColumn('IsCurrentYear',when(col('ColumnName') == lit(CurrentYear), lit('Y')).otherwise(lit('n')))\n\n"
] | [
0
] | [] | [] | [
"apache_spark",
"pyspark",
"python",
"variables"
] | stackoverflow_0074261595_apache_spark_pyspark_python_variables.txt |
Q:
Python text to voice with pyttsx3
So i wanted to convert a text into a mp3 file using pyttsx3 i wanted to apply a voice for the file but I was getting this error:
Traceback (most recent call last):
File "c:\Users\user\Desktop\Informatik\Praktik\Projekte\Python\productivity\wikipedia_webscraper\main.py", line 32,... | Python text to voice with pyttsx3 | So i wanted to convert a text into a mp3 file using pyttsx3 i wanted to apply a voice for the file but I was getting this error:
Traceback (most recent call last):
File "c:\Users\user\Desktop\Informatik\Praktik\Projekte\Python\productivity\wikipedia_webscraper\main.py", line 32, in <module>
engine.setProperty("vo... | [
"The documentation set the voice in this way:\nvoices = engine.getProperty('voices') #getting details of current voice\n#engine.setProperty('voice', voices[0].id) #changing index, changes voices. o for male\nengine.setProperty('voice', voices[1].id) #changing index, changes voices. 1 for female\n\nReferenc... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"pyttsx",
"pyttsx3",
"wikipedia"
] | stackoverflow_0071542305_python_python_3.x_pyttsx_pyttsx3_wikipedia.txt |
Q:
Replicating rows of a Pandas dataframe based on a column condition
I have a dataframe looking like this:
Weekday Day_in_Month Starting_hour Ending_hour Power
3 1 1 3 35
3 1 3 7 15
4 2 22 2 5
.
.
.
I... | Replicating rows of a Pandas dataframe based on a column condition | I have a dataframe looking like this:
Weekday Day_in_Month Starting_hour Ending_hour Power
3 1 1 3 35
3 1 3 7 15
4 2 22 2 5
.
.
.
I want to duplicate every column until the Starting_hour matches the End... | [
"Use Index.repeat with subtracted values and repeat rows by DataFrame.loc, then add counter to Starting_hour by GroupBy.cumcount:\ndf1 = df.loc[df.index.repeat(df['Ending_hour'].sub(df['Starting_hour']).add(1))]\ndf1['Starting_hour'] += df1.groupby(level=0).cumcount()\ndf1 = df1.reset_index(drop=True)\nprint (df1)\... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074261498_dataframe_pandas_python.txt |
Q:
Aggregate Dataframe by multiple indices
I have a dataframe that looks like this:
index
period
category
1
20181231
1
2
20181231
2
3
20181231
3
4
20190131
1
5
20190131
2
6
20190131
2
I want to get the following dataframe:
index
period
category
category_count
period_count
1
20181231
1
1
3
2
20181231
2
1
3
... | Aggregate Dataframe by multiple indices | I have a dataframe that looks like this:
index
period
category
1
20181231
1
2
20181231
2
3
20181231
3
4
20190131
1
5
20190131
2
6
20190131
2
I want to get the following dataframe:
index
period
category
category_count
period_count
1
20181231
1
1
3
2
20181231
2
1
3
3
20181231
3
1
3
4
2... | [
"One can create both category_count and period_count with pandas.core.groupby.DataFrameGroupBy.transform as follows\ndf['category_count'] = df.groupby(['period', 'category'])['category'].transform('count')\ndf['period_count'] = df.groupby(['period'])['category'].transform('count')\n\n[Out]:\n\n period cate... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074261558_dataframe_pandas_python.txt |
Q:
how to update nested dictionary types in python
I am really a beginner in Python and I wanted to update a nested dictionary.
Here is my code:
players_score= {}
per_round_score = dict()
name =["ram","shyam"]
for k in range(0,len(name)):
for _ in range(0,2):
per_round_score[f'round_{k}'] = {k:name[k]}
... | how to update nested dictionary types in python | I am really a beginner in Python and I wanted to update a nested dictionary.
Here is my code:
players_score= {}
per_round_score = dict()
name =["ram","shyam"]
for k in range(0,len(name)):
for _ in range(0,2):
per_round_score[f'round_{k}'] = {k:name[k]}
players_score.update(per_round_score)
print(player... | [
"zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator is paired together etc.\nYou can try this:\nplayers_score = {}\n\nper_round_score = dict()\nname = [\"ram\", \"shyam\"]\nfor k in ran... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074261529_python.txt |
Q:
"Slicing" dictionary keys in python
In python I can use slice objects like this:
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(2)
print(a[x])
I need to do something similar with dictionary keys, for example:
output = {
'track': {
'urlparams': {
'trackartist': 'artist_name'
... | "Slicing" dictionary keys in python | In python I can use slice objects like this:
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(2)
print(a[x])
I need to do something similar with dictionary keys, for example:
output = {
'track': {
'urlparams': {
'trackartist': 'artist_name'
}
}
}
key = dict_key_slice("['track'... | [
"I am not aware of a python function, but you can create your own.\nfrom functools import reduce\ndef dict_key_slice(nested_dict, path, split_by=\":\"):\n return reduce(lambda d, n: d[n], path.split(split_by), nested_dict)\n\ngiven your dict as:\noutput = {\n 'track': {\n 'urlparams': {\n 't... | [
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074252867_dictionary_python.txt |
Q:
Pandas Groupby and remove rows with numbers that are close to each other
I have a data frame df
df =
Code Bikes Year
12 356 2020
4 378 2020
2 389 2020
35 378 2021
40 370 2021
32 350 2021
I would like to group the data frame based on Year using df.groupby('Year') and che... | Pandas Groupby and remove rows with numbers that are close to each other | I have a data frame df
df =
Code Bikes Year
12 356 2020
4 378 2020
2 389 2020
35 378 2021
40 370 2021
32 350 2021
I would like to group the data frame based on Year using df.groupby('Year') and check the close values in column df['Çode'] to find values that are close by at l... | [
"You can first sort values per both columns by DataFrame.sort_values, then create groups by compare differences with treshold 3 and cumulative sum, last use DataFrameGroupBy.idxmax for get maximal indices by Bikes per Year and helper Series:\ndf1 = df.sort_values(['Year','Code'])\ng = df1.groupby('Year')['Code'].di... | [
1,
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074261301_dataframe_group_by_pandas_python.txt |
Q:
Tag-like (/x=y/yellow=flower) Pattern-Matching Regex Python
I need to match the information associated with each tag with a regex pattern. The tags here are not HTML but follow the format of: /x=y or
tags = "/yellow=flower/blue=sky"
What would be the regex pattern to yield this information?
I have tried:
linein =... | Tag-like (/x=y/yellow=flower) Pattern-Matching Regex Python | I need to match the information associated with each tag with a regex pattern. The tags here are not HTML but follow the format of: /x=y or
tags = "/yellow=flower/blue=sky"
What would be the regex pattern to yield this information?
I have tried:
linein = "/yellow=flower/blue=sky"
pattern = "^[A-Za-z0-9]{1}^[A-Za-z0-9]... | [
"Your attempt has several issues:\n\nIt doesn't attempt to match /, nor =\n^ will (by default) match the start of the input, so having it in the middle of your regex pattern is a guarantee of having no matches. Moreover, you want to match pairs that are not at the start of your input, so there really shouldn't be a... | [
1
] | [] | [] | [
"data_structures",
"pattern_matching",
"python",
"python_3.x",
"regex"
] | stackoverflow_0074257296_data_structures_pattern_matching_python_python_3.x_regex.txt |
Q:
How to convert str time to timestamp?
I have a string "15:15:00"
I need to convert it to timestamp like 1410748201
Python
A:
A UNIX timestamp always needs a relation between a date and a time to actually form it, since it is the number of seconds that are passed since 1970-01-01 00:00. Therefore I would recommen... | How to convert str time to timestamp? | I have a string "15:15:00"
I need to convert it to timestamp like 1410748201
Python
| [
"A UNIX timestamp always needs a relation between a date and a time to actually form it, since it is the number of seconds that are passed since 1970-01-01 00:00. Therefore I would recommend you to use the datetime module.\nLet's assume you have given the following format: \"2022-10-31 15:15:00\".\nWith datetime yo... | [
1
] | [] | [] | [
"python",
"time",
"timestamp"
] | stackoverflow_0074261771_python_time_timestamp.txt |
Q:
pandas group by with different calculations (row level and column level)
I have the following dataframe:
Customer ID
Country
Is True
123
China
1
124
China
1
125
Colombia
0
126
Bangladesh
0
127
Bangladesh
1
128
China
0
129
Colombia
0
130
Bangladesh
0
131
Bangladesh
0
132
China
1
I want to create somethi... | pandas group by with different calculations (row level and column level) | I have the following dataframe:
Customer ID
Country
Is True
123
China
1
124
China
1
125
Colombia
0
126
Bangladesh
0
127
Bangladesh
1
128
China
0
129
Colombia
0
130
Bangladesh
0
131
Bangladesh
0
132
China
1
I want to create something like pivot that will give me:
Country
Count Customers... | [
"Dataframe:\nimport pandas as pd\ndf = pd.DataFrame(\n {\n 'Customer ID':range(123,133),\n 'Country':['China', 'China', 'Colombia', 'Bangladesh', 'Bangladesh', 'China', 'Colombia', 'Bangladesh', 'Bangladesh', 'China'],\n 'is True':[1,1,0,0,1,0,0,0,0,1]\n }\n)\n\nFirst you can use the grou... | [
2
] | [] | [] | [
"aggregation_framework",
"pandas",
"python"
] | stackoverflow_0074261319_aggregation_framework_pandas_python.txt |
Q:
Does ConfigParser preserve the order of sections from file?
The order of the sections in my INI file is important.
Apparently, when I use ConfigParser.sections(), the order of sections in the returned list is the same as in the file. But is this guaranteed? I couldn't find this detail in documentation.
If not, wha... | Does ConfigParser preserve the order of sections from file? | The order of the sections in my INI file is important.
Apparently, when I use ConfigParser.sections(), the order of sections in the returned list is the same as in the file. But is this guaranteed? I couldn't find this detail in documentation.
If not, what is the best approach to informing the order of sections?
Exampl... | [
"Yes, because the sections are added to an internal dictionary as the file is being read line by line. As of Python version 3.7, dictionaries are ordered, therefore the sections should be in the order you define them in the config file.\nInspecting the source code of configparser, you can see the sections are store... | [
1
] | [] | [] | [
"configparser",
"python"
] | stackoverflow_0074261755_configparser_python.txt |
Q:
Save compressed numpy array one after another (without having everything in RAM)
We can save many arrays, one after another, without having all of them in RAM at the same time with:
with open('test.npy', 'wb') as f:
A = compute_my_np_array(1)
np.save(f, A)
# we could even do: del A (but not needed her... | Save compressed numpy array one after another (without having everything in RAM) | We can save many arrays, one after another, without having all of them in RAM at the same time with:
with open('test.npy', 'wb') as f:
A = compute_my_np_array(1)
np.save(f, A)
# we could even do: del A (but not needed here, because it is freed anyway in the next line)
A = compute_my_np_array(2)
... | [
"On solution is to use packages like gzip so to open the file as a gzip stream instead of a raw binary file. Here is an example:\nimport gzip\n\nwith gzip.open('test.npy.gz', 'wb') as f:\n A = compute_my_np_array(1)\n np.save(f, A)\n\nThe result is a npy file compressed with gzip. You need also to open it wit... | [
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074260797_arrays_numpy_python.txt |
Q:
add new contact to group using google people API with python
I am trying to create a code that saves new contacts and puts them in a certain group.
Creating a contact works great-
service = build('people', 'v1', credentials=creds)
service.people().createContact(body={"names": [{"givenName": name}], "phoneNumbers":... | add new contact to group using google people API with python | I am trying to create a code that saves new contacts and puts them in a certain group.
Creating a contact works great-
service = build('people', 'v1', credentials=creds)
service.people().createContact(body={"names": [{"givenName": name}], "phoneNumbers": [{'value': phone}],}).execute()
There is no problem in creating ... | [
"I think the problem here is where the {contactGroupId} you are specifying in contactGroupResourceName, you are putting the name of the contact group you created, the id should be an int value for what can I see in the examples, something like \"contactGroupResourceName\": \"contactGroups/123123123\"\nMost likely ... | [
1
] | [] | [] | [
"api",
"google_api",
"google_api_python_client",
"google_contacts_api",
"python"
] | stackoverflow_0074261636_api_google_api_google_api_python_client_google_contacts_api_python.txt |
Q:
Pytorch: RuntimeError: The size of tensor a (2) must match the size of tensor b (4) at non-singleton dimension 1
The pytorch program needs to return the result of the "Rock, Paper, Scissors" game. Input is given as one-hot tensors: [ [1,0,0], [0,1,0] ] ([1,0,0]-rock, [0,1,0] - scissors) output must be: [1, 0] (fir... | Pytorch: RuntimeError: The size of tensor a (2) must match the size of tensor b (4) at non-singleton dimension 1 | The pytorch program needs to return the result of the "Rock, Paper, Scissors" game. Input is given as one-hot tensors: [ [1,0,0], [0,1,0] ] ([1,0,0]-rock, [0,1,0] - scissors) output must be: [1, 0] (first player win, second player lose). What's wrong with this code?
import torch
from torch import nn
import torch.utils.... | [
"you have the following problem: You want your model to get as input the rock/paper/scissors of player1 and the rock/paper/scissors of player2. Since you do one-hot encoding you want to input 6 values into your neural network. 3 for player1 and 3 for player2. But you are trying to\nHey, a dense/feed-forward neural ... | [
0
] | [] | [] | [
"deep_learning",
"python",
"pytorch"
] | stackoverflow_0074261495_deep_learning_python_pytorch.txt |
Q:
Any effective solver to solve selection problem with constraints
I am working on a package selection problem. I have to put a constraint on the final result, like ‘top3 brands among selected products should account for less than 50%’.
I try to implement that on Pulp. But it seems CBC solver do not support such con... | Any effective solver to solve selection problem with constraints | I am working on a package selection problem. I have to put a constraint on the final result, like ‘top3 brands among selected products should account for less than 50%’.
I try to implement that on Pulp. But it seems CBC solver do not support such constraint. Please help me. How can I put such constraint? Or should I sw... | [
"It depends a bit on what exactly \"top 3 brands\" is. If you mean the sum of the three largest x[i] should be less than 50% of the total, then this can be linearized as follows:\n y1 >= x[i] for all i\n y2 >= x[i]-M*delta1[i] for all i\n y3 >= x[i]-M*delta2[i] for all i\n y1+y2+y3 <= sum... | [
1
] | [] | [] | [
"linear_programming",
"optimization",
"pulp",
"python"
] | stackoverflow_0074202039_linear_programming_optimization_pulp_python.txt |
Q:
Compute list difference
In Python, what is the best way to compute the difference between two lists?
example
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
A:
If the order does not matter, you can simply calculate the set difference:
>>> set([1,2,3,4]) - set([2,5])
set([1, 4, 3])
>>> set([2,5]) - set([1,2,... | Compute list difference | In Python, what is the best way to compute the difference between two lists?
example
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
| [
"If the order does not matter, you can simply calculate the set difference:\n>>> set([1,2,3,4]) - set([2,5])\nset([1, 4, 3])\n>>> set([2,5]) - set([1,2,3,4])\nset([5])\n\n",
"Use set if you don't care about items order or repetition. Use list comprehensions if you do:\n>>> def diff(first, second):\n second... | [
450,
217,
72,
36,
18,
15,
9,
8,
6,
6,
2,
1,
1,
0,
0,
0
] | [
"When having a look at TimeComplexity of In-operator, in worst case it works with O(n). Even for Sets.\nSo when comparing two arrays we'll have a TimeComplexity of O(n) in best case and O(n^2) in worst case.\nAn alternative (but unfortunately more complex) solution, which works with O(n) in best and worst case is t... | [
-1
] | [
"list",
"python"
] | stackoverflow_0006486450_list_python.txt |
Q:
Python Polars write csv resulting string data type is rounded and zero prefix missing
I'm using Polars to handle my excel data with big size. The result dataframe will be written to csv pldf_csv.write_csv("C:\\mydir\\code testings\\result.csv"). The column 3PL TN is like a numeric ID for the table, the values of t... | Python Polars write csv resulting string data type is rounded and zero prefix missing | I'm using Polars to handle my excel data with big size. The result dataframe will be written to csv pldf_csv.write_csv("C:\\mydir\\code testings\\result.csv"). The column 3PL TN is like a numeric ID for the table, the values of that column are like this 004087782412. I have make sure that column datatype is in string
... | [
"This isn't a polars problem but an Excel one. For instance if I open notepad++ and create a csv that looks like:\n3PL TN, weight\n004092306725, 1\n004092306726, 2\n\nand then I open it in Excel then it'll do the same thing with the leading 0s.\nThis answer tells us that if there's a tab before the value then Exce... | [
2
] | [] | [] | [
"csv",
"python",
"python_polars"
] | stackoverflow_0074258333_csv_python_python_polars.txt |
Q:
Increase django fixed value
In my Django project, there is a fixed number in one of the html input fields and I want this number to increase every time the form is opened. But since it will increase every time the form is opened, it is necessary to get the value of the last data from the database in that field. Ho... | Increase django fixed value | In my Django project, there is a fixed number in one of the html input fields and I want this number to increase every time the form is opened. But since it will increase every time the form is opened, it is necessary to get the value of the last data from the database in that field. How can I apply something like this... | [
"You can create custom tag that will change the value in database everytime anyone renders a template that includes base.html:\nfrom django import template\n\nregister = template.Library()\n\n@register.simple_tag\ndef raise_visit_counter():\n # here add +1 where you need and remember to use .save()\n return \... | [
0
] | [] | [] | [
"django",
"html",
"javascript",
"python"
] | stackoverflow_0074261518_django_html_javascript_python.txt |
Q:
How to launch a list of python scripts asynchronously?
I tried making a script that reads an array of scripts directories in it, and launches them asynchronously. The problem in my script is that it launches only the last script in the array.
import json
import asyncio
import firstscript
import secondscript
def ... | How to launch a list of python scripts asynchronously? | I tried making a script that reads an array of scripts directories in it, and launches them asynchronously. The problem in my script is that it launches only the last script in the array.
import json
import asyncio
import firstscript
import secondscript
def main():
list = json.load(open('list.json'))
launch_l... | [
"I know this is not perfectly the solution you asked for, but using Python itself to run concurrent scripts poses some drawbacks (e.g. having real tasks distributed over multiple physical cores on the CPU for each script).\nIf you're using a UNIX-system with e.g. a bash-shell you can use the taskset to run scripts ... | [
1
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074261913_python_python_asyncio.txt |
Q:
How to get route's name using FastAPI/Starlette?
How can I get the name of a route/endpoint using FastAPI/Starlette? I have access to the Request object and I need this information in one of my middlewares. For example, if I hit services/1, I should then be able to get the abc name. Is this possible in FastAPI?
@a... | How to get route's name using FastAPI/Starlette? | How can I get the name of a route/endpoint using FastAPI/Starlette? I have access to the Request object and I need this information in one of my middlewares. For example, if I hit services/1, I should then be able to get the abc name. Is this possible in FastAPI?
@app.get("/services/{service}", name="abc")
async def li... | [
"You can get the name value as follows:\nfrom fastapi import FastAPI,Request\n \napp = FastAPI()\n\n@app.get('/', name='abc')\ndef get_name(request: Request):\n return request.scope['route'].name\n\nIn a middleware, make sure to get the route's name after calling call_next(request), otherwise you would be fac... | [
2
] | [] | [] | [
"fastapi",
"python",
"starlette"
] | stackoverflow_0074261401_fastapi_python_starlette.txt |
Q:
Can we use chrome extensions in selenium pythonanywhere?
I am working on a flask app which is hosted on pythonanywhere, and I want to use chrome extensions with my chrome driver.But, it looks like pythonanywhere does not have any support for chrome extensions.
(I tried adding extensions both using crx and zip)
Any... | Can we use chrome extensions in selenium pythonanywhere? | I am working on a flask app which is hosted on pythonanywhere, and I want to use chrome extensions with my chrome driver.But, it looks like pythonanywhere does not have any support for chrome extensions.
(I tried adding extensions both using crx and zip)
Any form of help will be considered HUGE!
I tried using
chrome_op... | [
"Make sure that the extension file that you're trying to use is actually there and that you are using the correct path to it: https://help.pythonanywhere.com/pages/NoSuchFileOrDirectory/\n"
] | [
0
] | [] | [] | [
"python",
"pythonanywhere",
"selenium"
] | stackoverflow_0074211517_python_pythonanywhere_selenium.txt |
Q:
Computing the outer product of two vectors in Eigen c++
I have a piece of python code written using numpy that I'm trying to port over to C++ using the eigen library. I haven't really found anything suitable in the eigen library.
This is the python equivalent:
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, ... | Computing the outer product of two vectors in Eigen c++ | I have a piece of python code written using numpy that I'm trying to port over to C++ using the eigen library. I haven't really found anything suitable in the eigen library.
This is the python equivalent:
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(n... | [
"To achieve the same behavior as np.outer(a, b), where a and b are both column vectors (i.e. VectorXf for instance) in Eigen it would simply be:\na * b.transpose()\n\n\nFor info, the thread you linked has nothing to do with the outer product. Rather, it's about the \"exterior product\" (I know the two names are con... | [
0
] | [] | [] | [
"c++",
"eigen",
"eigen3",
"python"
] | stackoverflow_0074199536_c++_eigen_eigen3_python.txt |
Q:
Add df under other df Pandas
I'm using a for to generate a excel file to graph the data from a df so I'm using value_counts but I would like to add under this df a second one with the same data but with percentages so my code is this one:
li = []
for i in range(0, len(df.columns)):
value_counts = df.iloc[:, i... | Add df under other df Pandas | I'm using a for to generate a excel file to graph the data from a df so I'm using value_counts but I would like to add under this df a second one with the same data but with percentages so my code is this one:
li = []
for i in range(0, len(df.columns)):
value_counts = df.iloc[:, i].value_counts().to_frame().reset_... | [
"As long as the column names match between the two data frames you should be able to use pd.concat() to concatenate the two data frames. To concatenate them vertically, I think you should use axis=0 instead of axis=1 see docs\n",
"Data\nLet's prepare some dummy data to work with. Based on the provided screenshot,... | [
4,
2
] | [] | [] | [
"append",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074140872_append_dataframe_pandas_python.txt |
Q:
How to convert array to Gray Scale Image output?
I have the data in a txt.How should i do to convert the data to Gray Scale Image output?Thx!
The number of rows is 2378 and the number of columns is 5362.
I'm a noob in python.I have tried this,but it did not work.
from numpy import *
from PIL import Image
def rdn... | How to convert array to Gray Scale Image output? | I have the data in a txt.How should i do to convert the data to Gray Scale Image output?Thx!
The number of rows is 2378 and the number of columns is 5362.
I'm a noob in python.I have tried this,but it did not work.
from numpy import *
from PIL import Image
def rdnumpy(txtname):
f = open(txtname)
line = f.rea... | [
"Your code with small changes (see # <<< in code):\nfrom numpy import *\nfrom PIL import Image\n\n\ndef rdnumpy(txtname):\n f = open(txtname)\n line = f.readlines()\n lines = len(line)\n for l in line:\n le = l.strip('\\n').split(' ')\n columns = len(le)\n A = zeros((lines, columns), dt... | [
0,
0,
0
] | [] | [] | [
"grayscale",
"image",
"python"
] | stackoverflow_0074261440_grayscale_image_python.txt |
Q:
Reading the excel file from python pandas given MSAT extension error
raise CompDocError(msg)
xlrd.compdoc.CompDocError: MSAT extension: accessing sector 131072 but only 22863 in file
A:
You might be trying to open a corrupt Excel file. Assuming you're opening the file using xlrd, you could try adding the ignore_... | Reading the excel file from python pandas given MSAT extension error | raise CompDocError(msg)
xlrd.compdoc.CompDocError: MSAT extension: accessing sector 131072 but only 22863 in file
| [
"You might be trying to open a corrupt Excel file. Assuming you're opening the file using xlrd, you could try adding the ignore_workbook_corruption=True parameter:\nworkbook = xlrd.open_workbook('file_name.xls', ignore_workbook_corruption=True)\n\n"
] | [
0
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074262026_excel_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.