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: Sprite animation works when moving right, but not when moving left I'm making a simple game with Pygame. I have a character sprite which when moving right has all of the animations, but when moving left, the animations are not shown, instead it shows the default standing still animations as the character moves lef...
Sprite animation works when moving right, but not when moving left
I'm making a simple game with Pygame. I have a character sprite which when moving right has all of the animations, but when moving left, the animations are not shown, instead it shows the default standing still animations as the character moves left across the screen. I have been looking at this code for an hour trying...
[ "Answer: Possibly multiple issues.\nFirstly, the K_LEFT code is using self.standing_right for the sprite image. (It's not clear if this is correct, but it looks wrong).\nSecondly, imagine no keys are pressed, and follow the update() function in your imagination. It logically reduces down to something like:\ndef u...
[ 0 ]
[]
[]
[ "animation", "pygame", "python", "sprite" ]
stackoverflow_0074594570_animation_pygame_python_sprite.txt
Q: Compare two dates not considering Year and giving incorrect answer I have two dates I'm trying to compare in this format: a = '10.2022' (october 2022) and b = '02.2023' (February 2023) When I enter a > b I expect to have False Here is my code: import datetime a = '10-2022' # String date b = '02-2023' # String dat...
Compare two dates not considering Year and giving incorrect answer
I have two dates I'm trying to compare in this format: a = '10.2022' (october 2022) and b = '02.2023' (February 2023) When I enter a > b I expect to have False Here is my code: import datetime a = '10-2022' # String date b = '02-2023' # String date date_format = '%m.%Y' a = datetime.datetime.strptime(master_list[0][...
[ "import datetime\n\ndate_format = '%m.%Y'\n\na = datetime.datetime.strptime('10-2022', '%m-%Y') \nb = datetime.datetime.strptime('02-2023', '%m-%Y') \n\nprint(type(a))\nprint(a)\nprint(f'a is greater than b when both are datetime: {a>b}')\nprint()\n\n# now convert back to format you want...\na_as_str = a.strftime(d...
[ 0 ]
[ "You are comparing 2 numbers. 10,2022 (float) and 02,2023 (float) literally.\nTry using unix to compare time ^^\n" ]
[ -3 ]
[ "python" ]
stackoverflow_0074592476_python.txt
Q: In Pytube, is there any way to get the highest audio quality stream? I was trying to make a really simple python code to get me the stream with the highest quality audio, so I first tried something like this def get_highest_audio(url): yt = YouTube(url) best_audio_stream = yt.streams.filter(only_audio=True...
In Pytube, is there any way to get the highest audio quality stream?
I was trying to make a really simple python code to get me the stream with the highest quality audio, so I first tried something like this def get_highest_audio(url): yt = YouTube(url) best_audio_stream = yt.streams.filter(only_audio=True).all()[1] return best_audio_stream Which did return a stream, but it...
[ "You can just use:\nyt.streams.get_audio_only()\n\nthis gets the highest bitrate audio stream. It defaults to mp4.\n", "Why not remove the [1] and it will display all audio formats. From there you can select the highest one? \n", "Try This: My Github URL\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# ====...
[ 6, 0, 0 ]
[]
[]
[ "python", "pytube", "youtube" ]
stackoverflow_0061419900_python_pytube_youtube.txt
Q: if the string is "yash" then how can we can the output in the form of yyaasshh Given a string, return a string where for every char in the original, there are two chars. double_char('The') → 'TThhee' double_char('AAbb') → 'AAAAbbbb' double_char('Hi-There') → 'HHii--TThheerree' what is the code for this A: You c...
if the string is "yash" then how can we can the output in the form of yyaasshh
Given a string, return a string where for every char in the original, there are two chars. double_char('The') → 'TThhee' double_char('AAbb') → 'AAAAbbbb' double_char('Hi-There') → 'HHii--TThheerree' what is the code for this
[ "You can loop through each character and then duplicate each letter and append it to a new variable\ndef double_char(str):\n result = \"\"\n for i in range(len(str)):\n result = result + str[i] + str[i]\n return result\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074595294_python_python_3.x.txt
Q: "Int object is not callable" num = int(input("enter num ")) if num <=0: output= abs(num) print(output) else: output =abs(num) print(output) TypeError Traceback (most recent call last) <ipython-input-54-aba2c4ff0eb3> in <module> 3 INPUT: -1 OUTPUT:...
"Int object is not callable"
num = int(input("enter num ")) if num <=0: output= abs(num) print(output) else: output =abs(num) print(output) TypeError Traceback (most recent call last) <ipython-input-54-aba2c4ff0eb3> in <module> 3 INPUT: -1 OUTPUT: 1""" 4 ----> 5 num = int(...
[ "num = int(input(\"enter num \")) \n\noutput = abs(num) \nprint(output) \n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074595361_python.txt
Q: How to subtract 1 column from 4 columns and produce 4 new, resulting columns? I have a dataframe as shown. I need 4 new columns [['PriceSpread_ATL', 'PriceSpread_CHI', 'PriceSpread_LA', 'PriceSpread_NY']] that are the price spreads for each market. For 'PriceSpreadATL', each cell in the column 'FarmPrice' must be ...
How to subtract 1 column from 4 columns and produce 4 new, resulting columns?
I have a dataframe as shown. I need 4 new columns [['PriceSpread_ATL', 'PriceSpread_CHI', 'PriceSpread_LA', 'PriceSpread_NY']] that are the price spreads for each market. For 'PriceSpreadATL', each cell in the column 'FarmPrice' must be subtracted from the corresponding cell in the column 'AtlantaRetail' and divided b...
[ "You can try approaching it by iterating through a list of the title you want.\nd = {'farm_p' : [2.05, 1.49, 1.35], 'A_retail': [3.39, 2.39, 5.0], 'L_retail': [4.12, 4.12, 4.0]}\ndf = pd.DataFrame(data = d)\n\n# Generate list for titles\nheader = ['A_retail', 'L_retail']\n\nfor head in header:\n # Create column ...
[ 0, 0 ]
[]
[]
[ "group_by", "python" ]
stackoverflow_0074595375_group_by_python.txt
Q: Does iterating through a file in S3 using boto3's StreamingBody.iter_lines() count as a GET request for each line? I'm working on something where I am trying to access some data stored in a large CSV file in S3 via boto3. I'm considering iterating through the data line by line for memory sake, using: s3_client = ...
Does iterating through a file in S3 using boto3's StreamingBody.iter_lines() count as a GET request for each line?
I'm working on something where I am trying to access some data stored in a large CSV file in S3 via boto3. I'm considering iterating through the data line by line for memory sake, using: s3_client = boto3.client("s3") iterator = s3_client.get_object(Bucket='my-bucket', Key='my-key')['Body'].iter_lines() for line in i...
[ "No, it loads a fixed chunk size(in bytes) for each request, if there is another line in the loaded content cache, the __next__ call to the generator returns it, otherwise, it will make another request until there is no remaining content. See https://github.com/boto/botocore/blob/dfda41c08e3ed5354dce9f958b6db06e6c...
[ 1 ]
[]
[]
[ "amazon_s3", "boto3", "python" ]
stackoverflow_0060422708_amazon_s3_boto3_python.txt
Q: what is this color map? cmap=mglearn.cm3 I try to run the following code but it gives the following error in recognistion of mglearn color map. grr = pd.scatter_matrix( ...., cmap=mglearn.cm3) ErrorName: name 'mglearn' is not defined I should add pd is Anaconda Pandas package imported as pd but does not recognize...
what is this color map? cmap=mglearn.cm3
I try to run the following code but it gives the following error in recognistion of mglearn color map. grr = pd.scatter_matrix( ...., cmap=mglearn.cm3) ErrorName: name 'mglearn' is not defined I should add pd is Anaconda Pandas package imported as pd but does not recognize the color map mglearn.cm3 Any suggestions?
[ "Open Anaconda prompt and execute pip install mglearn\nAfter that just import mglearn\nimport pandas as pd\nimport mglearn\niris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names)\ngrr = pd.scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o',s=60, alpha=0.8, hist_kwds={'bins': ...
[ 4, 2, 0, 0, 0 ]
[]
[]
[ "anaconda", "pandas", "python" ]
stackoverflow_0040878325_anaconda_pandas_python.txt
Q: How To Open and Display .JSON Files Inside Jupyter Notebook I have an issue within Jupyter that I cannot find online anywhere and was hoping I could get some help. Essentially, I want to open .JSON files from multiple folders with different names. For example. data/weather/date=2022-11-20/data.JSON data/weather/da...
How To Open and Display .JSON Files Inside Jupyter Notebook
I have an issue within Jupyter that I cannot find online anywhere and was hoping I could get some help. Essentially, I want to open .JSON files from multiple folders with different names. For example. data/weather/date=2022-11-20/data.JSON data/weather/date=2022-11-21/data.JSON data/weather/date=2022-11-22/data.JSON da...
[ "This solution uses the os library to go thru different directories\nimport os\nimport json\n\nfor root, dirs, files in os.walk('data/weather'):\n for file in files:\n if file.endswith('.JSON'):\n with open(os.path.join(root, file), 'r') as f:\n data = json.load(f)\n ...
[ 1 ]
[]
[]
[ "jupyter_notebook", "numpy", "pandas", "python" ]
stackoverflow_0074595487_jupyter_notebook_numpy_pandas_python.txt
Q: Create a generic function to join multiple datasets in pyspark Hi I am creating a generic function or class to add n numbers of datasets but I am unable to find the proper logic to do that, I put all codes below and highlight the section in which I want some help. if you find any problem in understanding my code t...
Create a generic function to join multiple datasets in pyspark
Hi I am creating a generic function or class to add n numbers of datasets but I am unable to find the proper logic to do that, I put all codes below and highlight the section in which I want some help. if you find any problem in understanding my code then please ping me. import pyspark # importing sparksession from ...
[ "Since you're using inner join in all dataframe, if you want to prevent the bulky code, you can use the .reduce() in functools to do the joining and select the column that you want:\ndf = reduce(lambda x, y: x.join(y, on='id', how='inner'), [df_fact, df_Department, df_Leave, df_Phone])\ndf.show(10, False)\n+---+---...
[ 3 ]
[]
[]
[ "apache_spark", "dataframe", "pyspark", "python" ]
stackoverflow_0074595610_apache_spark_dataframe_pyspark_python.txt
Q: Can not read csv with pandas in azure functions with python I have created an Azure Blob Storage Trigger in Azure function in python. A CSV file adds in blob storage and I try to read it with pandas. import logging import pandas as pd import azure.functions as func def main(myblob: func.InputStream): logging...
Can not read csv with pandas in azure functions with python
I have created an Azure Blob Storage Trigger in Azure function in python. A CSV file adds in blob storage and I try to read it with pandas. import logging import pandas as pd import azure.functions as func def main(myblob: func.InputStream): logging.info(f"Python blob trigger function processed blob \n" ...
[ "If you refer to this article, it says that this piece of code will work. But this is recommended for smaller files as the entire files goes into memory. Not recommended to be used for larger files.\nimport logging\nimport pandas as pd\n\nimport azure.functions as func\nfrom io import BytesIO\n\ndef main(myblob: fu...
[ 1 ]
[]
[]
[ "azure", "pandas", "python" ]
stackoverflow_0074591834_azure_pandas_python.txt
Q: TypeError: cannot perform reduce with flexible type I have been using the scikit-learn library. I'm trying to use the Gaussian Naive Bayes Module under the scikit-learn library but I'm running into the following error. TypeError: cannot perform reduce with flexible type Below is the code snippet. training = Gauss...
TypeError: cannot perform reduce with flexible type
I have been using the scikit-learn library. I'm trying to use the Gaussian Naive Bayes Module under the scikit-learn library but I'm running into the following error. TypeError: cannot perform reduce with flexible type Below is the code snippet. training = GaussianNB() training = training.fit(trainData, target) predic...
[ "It looks like your 'trainData' is a list of strings:\n['-214' '-153' '-58' ..., '36' '191' '-37']\n\nChange your 'trainData' to a numeric type.\n import numpy as np\n np.array(['1','2','3']).astype(np.float)\n\n", "When your are trying to apply prod on string type of value like:\n['-214' '-153' '-58' ..., '36' '...
[ 169, 4, 0 ]
[]
[]
[ "python", "python_2.7", "scikit_learn" ]
stackoverflow_0028393103_python_python_2.7_scikit_learn.txt
Q: Pygame animation list index continuously goes out of range I followed a clear code tutorial to make a platformer and ended up finishing it, however one thing always continously messed up. That being the animation, at times the game just would not run and would only run in debug mode due to the animation list being...
Pygame animation list index continuously goes out of range
I followed a clear code tutorial to make a platformer and ended up finishing it, however one thing always continously messed up. That being the animation, at times the game just would not run and would only run in debug mode due to the animation list being out of index which makes no sense to me since every item in the...
[ "So it's likely that the code is not loading any of the animation frames for the 'idle' character animation.\nThe initialisation code first loads all the assets:\nclass Player(pygame.sprite.Sprite):\n def __init__(self,pos,surface,create_jump_particles):\n super().__init__()\n self.import_character...
[ 0 ]
[]
[]
[ "animation", "pygame", "python", "python_3.x" ]
stackoverflow_0074595379_animation_pygame_python_python_3.x.txt
Q: Add another level of headers to multiindex dataframe I have the following dataframe: dic = {'US':{'Quality':{'points':"-2 n", 'difference':'equal', 'stat': 'same'}, 'Prices':{'points':"-7 n", 'difference':'negative', 'stat': 'below'}, 'Satisfaction':{'points':"3 n", 'difference':'positive', 'stat': 'below'}}, ...
Add another level of headers to multiindex dataframe
I have the following dataframe: dic = {'US':{'Quality':{'points':"-2 n", 'difference':'equal', 'stat': 'same'}, 'Prices':{'points':"-7 n", 'difference':'negative', 'stat': 'below'}, 'Satisfaction':{'points':"3 n", 'difference':'positive', 'stat': 'below'}}, 'UK': {'Quality':{'points':"3 n", 'difference':'equal', ...
[ "Example\ndata = {('A', 'a'): {0: 8, 1: 3, 2: 4},\n ('A', 'b'): {0: 5, 1: 7, 2: 8},\n ('A', 'c'): {0: 1, 1: 7, 2: 6},\n ('B', 'a'): {0: 7, 1: 1, 2: 0},\n ('B', 'b'): {0: 1, 1: 1, 2: 7},\n ('B', 'c'): {0: 7, 1: 7, 2: 4}}\ndf = pd.DataFrame(data)\n\ndf\n A B\n a b ...
[ 1 ]
[]
[]
[ "dataframe", "multi_index", "pandas", "python" ]
stackoverflow_0074595521_dataframe_multi_index_pandas_python.txt
Q: Sum of all the values in a list of dictionaries I have a warehouses dictionary (shown below) and I need to get the sum of 'tons'. The values can be at various depths in the dictionary. warehouses = { "Warehouse Lisboa": [ { "name": "apples", "tons": 4}, { "name": "oranges", "tons": 10}, ...
Sum of all the values in a list of dictionaries
I have a warehouses dictionary (shown below) and I need to get the sum of 'tons'. The values can be at various depths in the dictionary. warehouses = { "Warehouse Lisboa": [ { "name": "apples", "tons": 4}, { "name": "oranges", "tons": 10}, { "name": "lemons", "tons": 50} ], "Wareho...
[ "Consider using a depth-first search approach:\nfrom typing import Union\n\ndef stock_fruits(curr: Union[dict, list]) -> int:\n if isinstance(curr, dict):\n return sum(stock_fruits(value) for value in curr.values())\n return sum(entry[\"tons\"] for entry in curr)\n\nwarehouses = {\n \"Warehouse Lisb...
[ 1, 0 ]
[]
[]
[ "dictionary", "python", "sum" ]
stackoverflow_0074595259_dictionary_python_sum.txt
Q: ufunc 'add' did not contain loop with signature matching type dtype ('S32') ('S32') ('S32') I'm trying to run someone's script for some simulations I've made to try plotting some histograms, but when I do I always get the error message mentioned above. I have no idea what's gone wrong. Here's the complete tracebac...
ufunc 'add' did not contain loop with signature matching type dtype ('S32') ('S32') ('S32')
I'm trying to run someone's script for some simulations I've made to try plotting some histograms, but when I do I always get the error message mentioned above. I have no idea what's gone wrong. Here's the complete traceback error I get: File "AVAnalyse.py", line 205, in <module> f.write(line[0] + ' ' + line[1] + '...
[ "It seems like line[0], line[1], line[2], line[3] are elements of dist_hist. dict_hist is a numpy.ndarray. The elements of dict_hist has a numeric type (like np.float64) (based on calculations from your attached file). You're trying to add elements of different types: np.float64 and str. If you want to avoid this T...
[ 32, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0041859824_numpy_python.txt
Q: 'ChebConv_Coma' object has no attribute 'weight' my code import torch from torch_scatter import scatter_add from torch_geometric.nn.conv import MessagePassing from torch_geometric.nn.conv.cheb_conv import ChebConv from torch_geometric.utils import remove_self_loops from utils import normal class ChebConv_Com...
'ChebConv_Coma' object has no attribute 'weight'
my code import torch from torch_scatter import scatter_add from torch_geometric.nn.conv import MessagePassing from torch_geometric.nn.conv.cheb_conv import ChebConv from torch_geometric.utils import remove_self_loops from utils import normal class ChebConv_Coma(ChebConv): def __init__(self, in_channels, out...
[ "Have you solved the problem?\nI've checked the Cheb_conv.py and have a guess: the Parent Class message_passing has no attribute called weight, and instead since it's an implementation of a Graph Network(the discrete model), the corresponding self.weight should be self.lins[k].weight (the linear transform matrix), ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0071015710_python.txt
Q: How can i use data which has bigger size than RAM memory? I want to search string S is in category. And category file is saved in folder. I want to load category file and search S, but size of category file exceed size of RAM memory. So i cant load category file. In this case, how can i know string S is in categor...
How can i use data which has bigger size than RAM memory?
I want to search string S is in category. And category file is saved in folder. I want to load category file and search S, but size of category file exceed size of RAM memory. So i cant load category file. In this case, how can i know string S is in category or not?
[ "The easiest way would be to process your big file one line at a time:\n#!/usr/bin/env python3\n\nN = 0\nwith open('BigFile.txt', 'r') as f:\n while True:\n line = f.readline()\n if not line:\n print('No cats found')\n break\n if 'cat' in line:\n print(f'Found cat, on lin...
[ 0 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0074595230_memory_python.txt
Q: I believe I have a Function Argument Issue For the most part all of my code seems to be working fine. The code is a text-based game. When I collect all of the items it fuctions correctly without errors. But if I go to directly to Caslte Black without collecting all the items it finishes with the proper message, bu...
I believe I have a Function Argument Issue
For the most part all of my code seems to be working fine. The code is a text-based game. When I collect all of the items it fuctions correctly without errors. But if I go to directly to Caslte Black without collecting all the items it finishes with the proper message, but I get the following error: Traceback (most rec...
[ "After the first condition in the loop, add a break or wrap the rest in an else. You're trying to access cities[\"Castle Black\"], hence the KeyError.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074595719_python.txt
Q: Is there a way to iterate through certain types of objects on a canvas in python tkinter? For example, I've got a bunch of text objects of varying font families on a canvas, can I make some kind of call to iterate through these text objects and alter them? A: You can get a list of all items on a canvas with the ...
Is there a way to iterate through certain types of objects on a canvas in python tkinter?
For example, I've got a bunch of text objects of varying font families on a canvas, can I make some kind of call to iterate through these text objects and alter them?
[ "You can get a list of all items on a canvas with the find_all() method and then just list them:\ndef get_canvas_items(canvas):\n item_list = canvas.find_all()\n for item in item_list:\n item_type = canvas.type(item) # e.g. \"text\", \"line\", etc.\n item_keys = canvas.itemconfig(item).keys() ...
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074595086_python_tkinter.txt
Q: Merge Sort in reverse i want to sort the array in descending order using mergeSort this is the code for my MergeSort implementation in ascending order def MergeSort(B): if len(B) <= 1: return mid = len(B)//2 half1 = B[:mid] half2 = B[mid:] reverseSort(half1) ...
Merge Sort in reverse
i want to sort the array in descending order using mergeSort this is the code for my MergeSort implementation in ascending order def MergeSort(B): if len(B) <= 1: return mid = len(B)//2 half1 = B[:mid] half2 = B[mid:] reverseSort(half1) reverseSort(half2) ...
[]
[]
[ "def merge_sort_descending(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n left = arr[:mid]\n right = arr[mid:]\n merge_sort_descending(left)\n merge_sort_descending(right)\n i = j = k = 0\n while i < len(left) and j < len(right):\n if left[i] > right[...
[ -1 ]
[ "python" ]
stackoverflow_0074595754_python.txt
Q: How to Create Different Colors for Tiles I am relatively new to pygame, and I am trying to create a matching card game. I am currently stuck on how to replace the colors of the tiles. I currently have a list of colors for my tiles, but I do not know how I would implement each of these colors into my tiles. For exa...
How to Create Different Colors for Tiles
I am relatively new to pygame, and I am trying to create a matching card game. I am currently stuck on how to replace the colors of the tiles. I currently have a list of colors for my tiles, but I do not know how I would implement each of these colors into my tiles. For example, tile 1 would be blue, tile 2 would be gr...
[ "I would create a data structure to hold the various pieces of information about a tile. It could be something as simple as a list:\ntile1 = [ ( 255, 0, 0 ), 10, 10, 100, 100 ]\ntile2 = [ ( 0, 255, 0 ), 120, 10, 100, 100 ]\n\nWhere each tile is a python list of [ colour, x, y, width, height ].\nAlternativ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074595313_python.txt
Q: How to get sorted list inside a dictionary with json.dumps() I have the following problem: having a python dictionary like the following: {"qqq": [{"bbb": "111"}, {"aaa": "333"}], "zzz": {"bbb": [5, 2, 1, 9]}} I would like to obtain an ordered json object such as: '{"qqq": [{"aaa": "333"}, {"bbb": "111"}], "zzz":...
How to get sorted list inside a dictionary with json.dumps()
I have the following problem: having a python dictionary like the following: {"qqq": [{"bbb": "111"}, {"aaa": "333"}], "zzz": {"bbb": [5, 2, 1, 9]}} I would like to obtain an ordered json object such as: '{"qqq": [{"aaa": "333"}, {"bbb": "111"}], "zzz": {"bbb": [1, 2, 5, 9]}}' At the moment I use the following: class...
[ "default isn't called for lists; that method is only for types the encoder doesn't know how to handle. Override the encode method instead:\nclass SortedListEncoder(json.JSONEncoder):\n def encode(self, obj):\n def sort_lists(item):\n if isinstance(item, list):\n return sorted(sor...
[ 8, 0 ]
[ "I leave this here because i ran into the same issue.\nYou can use this function to sort your nested data structures:\ndef sort_data(data):\n if isinstance(data, dict):\n output = OrderedDict()\n for key, value in data.items():\n output[key] = sort_data(value)\n return output\n ...
[ -1 ]
[ "dictionary", "json", "list", "python" ]
stackoverflow_0024076832_dictionary_json_list_python.txt
Q: How do I protect Python code from being read by users? I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time-restricted license file. If we distribute the .py files or even .pyc files it will be easy to (d...
How do I protect Python code from being read by users?
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time-restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. ...
[ "\"Is there a good way to handle this problem?\" No. Nothing can be protected against reverse engineering. Even the firmware on DVD machines has been reverse engineered and the AACS Encryption key exposed. And that's in spite of the DMCA making that a criminal offense.\nSince no technical method can stop your c...
[ 500, 413, 321, 169, 61, 46, 35, 30, 24, 20, 18, 17, 14, 13, 12, 10, 8, 6, 6, 6, 5, 4, 3, 2, 2, 2, 1, 1, 0 ]
[]
[]
[ "copy_protection", "licensing", "obfuscation", "python" ]
stackoverflow_0000261638_copy_protection_licensing_obfuscation_python.txt
Q: Multiply all elements in each row of an array by numbers in a 1D array I have a torch tensor (x) of shape [16,3,32,32], 16 images, 3 colour channels 32x32. I'm doing diffusion and need to apply the following formula to the images return sqrt_alpha_hat * x + sqrt_one_minus_alpha_hat * error Error has the same dimen...
Multiply all elements in each row of an array by numbers in a 1D array
I have a torch tensor (x) of shape [16,3,32,32], 16 images, 3 colour channels 32x32. I'm doing diffusion and need to apply the following formula to the images return sqrt_alpha_hat * x + sqrt_one_minus_alpha_hat * error Error has the same dimensions as x. This works fine when sqrt_alpha_hat and sqrt_one_minus_alpha_hat...
[ "Used\nsqrt_alpha_hat_table = torch.stack([torch.full(x.shape[1:], sqrt_alpha_hat[i]) for i in range(x.shape[0])]).to(device)\n\n", "The \"correct\" way to do this (vectorized rather than loop-based, and without allocating lots of memory for repeating row vectors) is with expand(). I'll assume that you meant eith...
[ 0, 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074593838_python_pytorch.txt
Q: How to efficiently list all files in an Azure blob using python? I need to list all files in an Azure blob using python. Currently I use the code below. this worked well when there were few files. But now I have a large number of files and the script runs more than an hour. The time-consuming part is the for loop....
How to efficiently list all files in an Azure blob using python?
I need to list all files in an Azure blob using python. Currently I use the code below. this worked well when there were few files. But now I have a large number of files and the script runs more than an hour. The time-consuming part is the for loop. How can this be done faster? import os, uuid from azure.storage.blob ...
[ "I could able to achieve this using list_blobs method of BlockBlobService. After reproducing from my end, I have observed that the list_blobs method of BlobServiceClient returns all the properties of blob which is taking more time to proocess whereas BlockBlobService returns objects. Below is the code that was work...
[ 0 ]
[]
[]
[ "azure", "python" ]
stackoverflow_0074565291_azure_python.txt
Q: webscraping on websocket streaming using Python 3.x I've been webscraping for a long time and recently decided to scrape a video stream via websocket streaming. I fully understand websockets and how they work, but I don't fully understand the streaming part. I'm trying to scrape a stream where I get base64 data us...
webscraping on websocket streaming using Python 3.x
I've been webscraping for a long time and recently decided to scrape a video stream via websocket streaming. I fully understand websockets and how they work, but I don't fully understand the streaming part. I'm trying to scrape a stream where I get base64 data using Python 3.10, and when I try to decode it I find that ...
[ "I can recommend this package: https://github.com/websocket-client/websocket-client\nIt is pretty simple and stable and it works flawlessly. Also it supports asyncio.\ndef on_message(ws, message):\n ...\n\ndef on_open(ws):\n ...\n\ndef on_close(ws, close_status_code, close_msg):\n ...\n\ndef on_error(ws, e...
[ 4 ]
[]
[]
[ "python", "web_scraping", "websocket" ]
stackoverflow_0074595506_python_web_scraping_websocket.txt
Q: how to exit a function when an event is set? I have an infinite loop thread that sets an event when a sensor is high/true event = threading.Event() def eventSetter(): while True: if sensor: event.set() else: event.clear() th1 = threading.thread(target=eventSetter) th1...
how to exit a function when an event is set?
I have an infinite loop thread that sets an event when a sensor is high/true event = threading.Event() def eventSetter(): while True: if sensor: event.set() else: event.clear() th1 = threading.thread(target=eventSetter) th1.start and I have a function capture that takes 5...
[ "Do you want breaking loop ?\nif you want break any time or condition you need to break `key.\nfor example\nevent = threading.Event()\ndef eventSetter():\n while True:\n if sensor:\n event.set()\n break\n #loop stoped.\n else:\n event.clear()\n\n ret...
[ 0, 0 ]
[]
[]
[ "events", "python" ]
stackoverflow_0074595714_events_python.txt
Q: how to upload image correctly. Django I am building a Django application (run in local) and I am having headaches about uploading files/pictures. I have read tons of questions/answers everywhere as well as followed the official doc, but somehow I still have problems. In my models.py: FuncionarioPathFoto = models.F...
how to upload image correctly. Django
I am building a Django application (run in local) and I am having headaches about uploading files/pictures. I have read tons of questions/answers everywhere as well as followed the official doc, but somehow I still have problems. In my models.py: FuncionarioPathFoto = models.FileField( "Foto", upload_to...
[ "Let me explain the process of uploading files with Django with my own method.\nIf a file is sent to the server, it is kept in request.FILES as temp. You can see it by saying print(request.FILES) .\nFirst, read the temp data and then load it into the relevant directory with the open function in python.\nFor example...
[ 1, 1 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0074595637_django_django_models_django_templates_django_views_python.txt
Q: how to insert into the list at the next odd index position I have written the python code below to create a database: list = ["a","b","c","d","e"] while(True): print("1/insert") print("2/delete") print("3/quit") print("4/display") choice=int(input("enter your choice: ")) if choice==1: name=input...
how to insert into the list at the next odd index position
I have written the python code below to create a database: list = ["a","b","c","d","e"] while(True): print("1/insert") print("2/delete") print("3/quit") print("4/display") choice=int(input("enter your choice: ")) if choice==1: name=input("enter a name:") list.insert(1,name) if choice==2: ...
[]
[]
[ "Help on method_descriptor:\n\ninsert(self, index, object, /)\n Insert object before index.\n\ninsert(1, obj) will insert the object before index 1 which will turns to be the 2th position after insert opt.\n" ]
[ -1 ]
[ "insertion", "python", "while_loop" ]
stackoverflow_0074595663_insertion_python_while_loop.txt
Q: How can I open a new browser tab with subprocess? I'm opening a new IE window with this: subprocess.Popen(r'"' + os.environ["PROGRAMFILES"] + '\Internet Explorer\IEXPLORE.EXE" ' + Call_URL) This is fine when IE is closed, but even when it's open this spawns a new window. How can I open just a new tab? If possib...
How can I open a new browser tab with subprocess?
I'm opening a new IE window with this: subprocess.Popen(r'"' + os.environ["PROGRAMFILES"] + '\Internet Explorer\IEXPLORE.EXE" ' + Call_URL) This is fine when IE is closed, but even when it's open this spawns a new window. How can I open just a new tab? If possible I'd like to use the standard browser - however I cou...
[ "Since you also wanted a standard browser am giving an example to open a new tab with chrome. If chrome is not open already it will open and then navigate to the URL.\nimport subprocess\nsubprocess.Popen(\"start chrome /new-tab www.google.com\",shell = True)\n\nThis works. Please try and let me know if this is what...
[ 4, 0 ]
[]
[]
[ "browser", "python", "subprocess" ]
stackoverflow_0035987882_browser_python_subprocess.txt
Q: How to verify installed spaCy version? I have installed spaCy with python for my NLP project. I have installed that using pip. How can I verify installed spaCy version? using pip install -U spacy What is command to verify installed spaCy version? A: You can also do python -m spacy info. If you're updating an ...
How to verify installed spaCy version?
I have installed spaCy with python for my NLP project. I have installed that using pip. How can I verify installed spaCy version? using pip install -U spacy What is command to verify installed spaCy version?
[ "You can also do python -m spacy info. If you're updating an existing installation, you might want to run python -m spacy validate, to check that the models you already have are compatible with the version you just installed.\n", "Use command - python -m spacy info to check spacy version \n", "If you ask yourse...
[ 45, 9, 8, 3, 2, 1, 0, 0 ]
[]
[]
[ "nlp", "pip", "python", "spacy", "version" ]
stackoverflow_0047350942_nlp_pip_python_spacy_version.txt
Q: Find an element's text not on screen during execution I'm learning web scraping with Selenium and to practice I'm trying to get some promotions from this site: Here is my code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By def get...
Find an element's text not on screen during execution
I'm learning web scraping with Selenium and to practice I'm trying to get some promotions from this site: Here is my code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By def get_promotion(): ''' Web scraping process to get Smile...
[ "Instead of using .text you should use .get_attribute('textContent')\nwhich would make\npromotions.append(\n { \n 'destination': promotion.find_element(By.XPATH, f'./a/div/div/h3').text,\n 'origin': promotion.find_element(By.XPATH, f'./a/div/div/h4/span[2]').text,\n 'diamont_value': promotio...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "web_scraping" ]
stackoverflow_0072842706_python_selenium_selenium_chromedriver_selenium_webdriver_web_scraping.txt
Q: Nested for loop with 2 variables. Ouput to be appended in dataframe column check_df has two column one with code and other is blank in_df has 2 column one is merged column and other is V_ORG_UNIT_NAME_LEVEL14. I want to check each code of "V_ORG_UNIT_CODE" from check_df inside "merged column from in_df. If it matc...
Nested for loop with 2 variables. Ouput to be appended in dataframe column
check_df has two column one with code and other is blank in_df has 2 column one is merged column and other is V_ORG_UNIT_NAME_LEVEL14. I want to check each code of "V_ORG_UNIT_CODE" from check_df inside "merged column from in_df. If it matches(it may contain that value may not be exact match) i want corresponding "Outp...
[ "check ,5 line \"y value\" type, that must be string type\n", "try the DataFrame class built-in function .insert\nhttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.insert.html\n", "If I've instantiated your dataframe correctly (check below), the following seems to deliver the outcome you're after:\n...
[ 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074595796_pandas_python.txt
Q: Display option value and text to select I have a select field populated from the database table 'Grade'. It displays Grade objects instead of 'Grade 1', 'Grade 2', 'Grade 3' etc. How can I populate the select to display the texts. My codes: models.py class Grade(models.Model): grade_id = models.AutoField(prim...
Display option value and text to select
I have a select field populated from the database table 'Grade'. It displays Grade objects instead of 'Grade 1', 'Grade 2', 'Grade 3' etc. How can I populate the select to display the texts. My codes: models.py class Grade(models.Model): grade_id = models.AutoField(primary_key=True) grade_name = models.CharFie...
[ "You should define the __str__() method in the model so:\nclass Grade(models.Model):\n grade_id = models.AutoField(primary_key=True)\n grade_name = models.CharField(max_length=10, default=\"\")\n\n def __str__(self):\n return f\"{self.grade_name}\"\n\n class Meta:\n db_table = 'grade'\n\n\...
[ 3, 2 ]
[]
[]
[ "django", "django_forms", "django_queryset", "django_views", "python" ]
stackoverflow_0074595889_django_django_forms_django_queryset_django_views_python.txt
Q: spaCy 3.4 Sentence segmenter permutations performing poorly on phrases without punctuation I am attempting to use two of the four alternatives from spaCy for sentence segmentation, and all of them seem to perform equally bad on phrases without punctuation. I am trying to utilize a solution such as these on spans ...
spaCy 3.4 Sentence segmenter permutations performing poorly on phrases without punctuation
I am attempting to use two of the four alternatives from spaCy for sentence segmentation, and all of them seem to perform equally bad on phrases without punctuation. I am trying to utilize a solution such as these on spans of text that are blended and not diarized (speaker diarization). My goal is to identify sentenc...
[ "\nI am trying to utilize a solution such as these on spans of text that are blended and not diarized (speaker diarization).\n\nThe issue is simply that the spaCy models are not trained for that task and won't do well. They're trained mostly on text from books or articles that reliably has punctuation.\nWhat you ca...
[ 1, 0 ]
[]
[]
[ "nlp", "python", "spacy" ]
stackoverflow_0074591575_nlp_python_spacy.txt
Q: How to make a request to get a picture from an ipcam? I have some troubles getting the picture on my ip camera on python. I have an axis camera, I almost do the work on the rtsp link and cv2 video capture but when the hours go by I got an h264 error (here I asked for that problem). So I decided to use a get reques...
How to make a request to get a picture from an ipcam?
I have some troubles getting the picture on my ip camera on python. I have an axis camera, I almost do the work on the rtsp link and cv2 video capture but when the hours go by I got an h264 error (here I asked for that problem). So I decided to use a get request to get the picture, but now I got 401, error. Here is my ...
[ "There is nothing wrong with your code. I have done the same code and works fine on my side. I would suggest you to verify the credentials that you have provided as a 401 response code is received when you provide wrong password or username.\nAdditionally, don't forget to pass the stream=True parameter inside the r...
[ 0 ]
[]
[]
[ "python", "request" ]
stackoverflow_0068714335_python_request.txt
Q: Use Python to launch and track Chrome browser (on Windows), open new tabs, then close everything when done I needed to launch Chrome programmatically, then open some more tabs, then close them all when I was done, even if an existing Chrome browser was already open. I could find partial answers, but nothing simpl...
Use Python to launch and track Chrome browser (on Windows), open new tabs, then close everything when done
I needed to launch Chrome programmatically, then open some more tabs, then close them all when I was done, even if an existing Chrome browser was already open. I could find partial answers, but nothing simple that worked with already running browsers. I needed something following the KISS principle (Keep It Simple & S...
[ "Here is a simple answer that will launch, track, and terminate a new Chrome browser instance, but with child tabs too.\nIt launches a new process for a Chrome instance, launches additional tabs into that new Chrome webbrowser instance, and finally using \"terminate()\" when finished to close the original browser l...
[ 0 ]
[]
[]
[ "google_chrome", "python", "python_webbrowser", "subprocess" ]
stackoverflow_0074596006_google_chrome_python_python_webbrowser_subprocess.txt
Q: Sorting pandas groupby output I have a dataframe that looks like name performance year bob 50 2002 bob 90 2005 bob 82 2010 joey 50 2015 joey 85 2013 joey 37 1990 sarah 90 1994 sarah 95 2020 sarah 35 ...
Sorting pandas groupby output
I have a dataframe that looks like name performance year bob 50 2002 bob 90 2005 bob 82 2010 joey 50 2015 joey 85 2013 joey 37 1990 sarah 90 1994 sarah 95 2020 sarah 35 2013 I would like groupby nam...
[ "here is my solution, basically was missing one field in the group by method.\nCode:\nimport pandas as pd\n\n# defining columns\ncols = ['name', 'performance', 'year']\n\n# defining data\ndata = [\n ['bob', 50, 2002]\n, ['bob', 90, 2005]\n, ['bob', 82, 2010]\n, ['joey', 50, 2015]\n, ['joey', 85, ...
[ 2 ]
[]
[]
[ "group_by", "pandas", "python", "sorting" ]
stackoverflow_0074595611_group_by_pandas_python_sorting.txt
Q: Python: "zsh: segmentation fault" error causes I was just playing around with a python library called 'Pyautogui.' Everything was going fun and cool until upon one run, I hit a zsh: segmentation fault. Pyautogui has stopped working on my local machine since. Any code using the Pyautogui library crashes with the sa...
Python: "zsh: segmentation fault" error causes
I was just playing around with a python library called 'Pyautogui.' Everything was going fun and cool until upon one run, I hit a zsh: segmentation fault. Pyautogui has stopped working on my local machine since. Any code using the Pyautogui library crashes with the same error. Not a big practical issue as I was just ex...
[ "This is happening because the python library you are using, 'Pyautogui', is attempting to access a memory beyond its reach.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074595898_python_python_3.x.txt
Q: PyLTSpice "LTSpice_Batch" function not working I'm using VSCode with Python 3.11.0 in a virtual enviroment. I have installed the aforementioned toolchain to configure and launch LTSpice models. However, it seems not to work and I cannot find why (I'm quite new to python programming). I attach here the actual code ...
PyLTSpice "LTSpice_Batch" function not working
I'm using VSCode with Python 3.11.0 in a virtual enviroment. I have installed the aforementioned toolchain to configure and launch LTSpice models. However, it seems not to work and I cannot find why (I'm quite new to python programming). I attach here the actual code and the traceback. Notice that the main code is take...
[ "The cause is now understood.\npyLTSpiceBatch.py is referring the XVIIx64.exe path directly.\nelse: # Windows\n LTspice_exe = [r\"C:\\Program Files\\LTC\\LTspiceXVII\\XVIIx64.exe\"]\n LTspice_arg = {'netlist': ['-netlist'], 'run': ['-b', '-Run']}\n PROCNAME = \"XVIIx64.exe\"\n\nIf you installed LTSpice to...
[ 0 ]
[ "I faced this problem too yesterday.\nBy any chance, were you trying it on windows 11?\nIf that, it is same as my situation. Probably it will work on windows 10.\nI do not know why though, it seems like that subprocess.py or command prompt is not work normally on windows 11.\nHoping that the information will be of ...
[ -1 ]
[ "python" ]
stackoverflow_0074425104_python.txt
Q: ValueError: [E1041] Expected a string, Doc, or bytes as input, but got: import pandas df['findings'] = df['findings'].astype(str) #df['findings'] = df['findings'].astype('string') df["new_column"] = GPT2_model(df['findings'], min_length=60) After running this I get the following error, even after converting my ...
ValueError: [E1041] Expected a string, Doc, or bytes as input, but got:
import pandas df['findings'] = df['findings'].astype(str) #df['findings'] = df['findings'].astype('string') df["new_column"] = GPT2_model(df['findings'], min_length=60) After running this I get the following error, even after converting my dataframe to string. ---------------------------------------------------------...
[ "Your method/model GPT2_model doesn't take a Pandas Series object. That's what the error is complaining about. You can instead apply the method to your findings column.\ndf['new_column'] = df['findings'].apply(GPT2_model, min_length=60)\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074596073_pandas_python.txt
Q: pyspark: OverflowError: mktime argument out of range I am processing parquet files in pyspark. My version info is: My data contains date and timestamp fields with values less than '1970-01-01'. I am getting the following error running locally on Mac OS Monterey v12.6.1. 22/11/27 20:22:46 ERROR Utils: Aborting tas...
pyspark: OverflowError: mktime argument out of range
I am processing parquet files in pyspark. My version info is: My data contains date and timestamp fields with values less than '1970-01-01'. I am getting the following error running locally on Mac OS Monterey v12.6.1. 22/11/27 20:22:46 ERROR Utils: Aborting task org.apache.spark.api.python.PythonException: Traceback (...
[ "I was curious and I did a little research.\nThe method mktime(), according to python's documentation, is platform dependent: more info here https://docs.python.org/3.8/library/time.html#time.mktime.\nThen I had a look at Mac OS and, as it is based on an UNIX system, it runs with epoch Unix time.\nFrom wiki: https:...
[ 0 ]
[]
[]
[ "datetime", "pyspark", "python" ]
stackoverflow_0074595439_datetime_pyspark_python.txt
Q: Entry field doesn't exist, it is made inside of a function so im trying to make a user login system, when a user clicks sign up and enters their password and username, it appends both of those to a file, however I made the entry field in the function that is called when you click sign in, Now i have an error when ...
Entry field doesn't exist, it is made inside of a function
so im trying to make a user login system, when a user clicks sign up and enters their password and username, it appends both of those to a file, however I made the entry field in the function that is called when you click sign in, Now i have an error when trying to get the data from that entry usr = (Usrfield).get()...
[ "just make your widgets global in addattr() function. use the code below:\nfrom tkinter import *\nfrom tkinter import messagebox\nHomescreen = Tk()\n\ndef addattrs():\n global Usrfield,Pswrdfield\n Signup = Tk()\n Usrfield = Entry(Signup, width=50)\n #Usrfield = signupinput.get(1.0, \"end-1c\") c\n U...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074595794_python_tkinter.txt
Q: ModuleNotFoundError: No module named ‘webdriver_manager.Edge I’m getting the error: ModuleNotFoundError: No module named ‘webdriver_manager.Edge’. My Code is: from selenium import webdriver from selenium.webdriver.edge.options import Options from selenium.webdriver.edge.service import Service from webdriver_manage...
ModuleNotFoundError: No module named ‘webdriver_manager.Edge
I’m getting the error: ModuleNotFoundError: No module named ‘webdriver_manager.Edge’. My Code is: from selenium import webdriver from selenium.webdriver.edge.options import Options from selenium.webdriver.edge.service import Service from webdriver_manager.Edge import ChromeDriverManager def Mok(): chrome_options =...
[ "import \nfrom webdriver_manager.microsoft import EdgeChromiumDriverManager\n\n[...]\n\ndriver = webdriver.Edge(EdgeChromiumDriverManager().install())\n\n\n", "You basically have a typo in your code:\nSee https://github.com/SergeyPirogov/webdriver_manager#use-with-edge\nIf you are using webdriver_manager as your ...
[ 0, 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074596027_python_selenium.txt
Q: Python Web browser click listener Is there any packages or ways to detect what is being clicking in a web browser? I mean get tag/xpath from the web browser (of what is being clicked)? To afterwards find it via selenium or similar? Or even with to determine what it is with the coordinates of the mouse click. Like ...
Python Web browser click listener
Is there any packages or ways to detect what is being clicking in a web browser? I mean get tag/xpath from the web browser (of what is being clicked)? To afterwards find it via selenium or similar? Or even with to determine what it is with the coordinates of the mouse click. Like the codegen in Playwright or similar, l...
[ "We could add window listener with JavaScript using driver.execute_script to listen to any clicks, and then call function xpath as provided in SO answer to generate Xpath of an element. As a gist, below is the window.addEventListener script which handles any click event by displaying an alert with the clicked eleme...
[ 1 ]
[]
[]
[ "python", "python_webbrowser", "selenium" ]
stackoverflow_0074592808_python_python_webbrowser_selenium.txt
Q: VSCode unable to install Jupyter / Python Extension I had to set up my Computer again and tried to install the Python Extension in VSCode. When I try to install this extension I get the following error: Unable to install extension 'ms-toolsai.jupyter' as it is not compatible with VS Code '1.54.1'. To install th...
VSCode unable to install Jupyter / Python Extension
I had to set up my Computer again and tried to install the Python Extension in VSCode. When I try to install this extension I get the following error: Unable to install extension 'ms-toolsai.jupyter' as it is not compatible with VS Code '1.54.1'. To install the Python Extension, Jupyter is needed but this Extensi...
[ "OS: Manjaro KDE\nI tried installing code and upgrading to insiders (AUR) using pacman and did not get Python to install in vscode because of the Jupyter error. I tried installing Jupyter vsix manually and this also failed.\nI ended up getting Python in to vscode by installing code using snap. https://snapcraft.io/...
[ 1, 0 ]
[]
[]
[ "jupyter", "python", "visual_studio_code" ]
stackoverflow_0066544398_jupyter_python_visual_studio_code.txt
Q: Sorting of list values in dict not working - python i am sorting a dictionary, it is sorting based on keys but not with values . if i try sorting with values am getting error "'<' not supported between instances of 'list' and 'int'" Below is code i used. cars = "ABC/{'Place': 'UK', 'Fruit': 'Apple', 'Vit': ['C...
Sorting of list values in dict not working - python
i am sorting a dictionary, it is sorting based on keys but not with values . if i try sorting with values am getting error "'<' not supported between instances of 'list' and 'int'" Below is code i used. cars = "ABC/{'Place': 'UK', 'Fruit': 'Apple', 'Vit': ['C','A'], 'Check': ['B', 'C', 'X', 'D','A']}/Place" i...
[ "You can use isinstance to check whether a value is list, and then apply sorted accordingly:\ndct = {\n 'Check': ['B', 'C', 'X', 'D', 'A'],\n 'Fruit': 'Apple',\n 'Place': 'UK',\n 'Vit': ['C', 'A']\n}\n\noutput = {k: sorted(v) if isinstance(v, list) else v for k, v in sorted(dct.items())}\n\nprint(output...
[ 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074596289_dictionary_python.txt
Q: Attaching parameters to geojson object becomes non-existant when creating a geopandas dataframe I have this dataframe d = { 'geoid': ['13085970205'], 'FIPS': ['13085'], 'Year': [2024], 'parameters': [{"Year": 2024, "hpi_prediction": 304.32205}], 'geometry':[ { "coordinates":...
Attaching parameters to geojson object becomes non-existant when creating a geopandas dataframe
I have this dataframe d = { 'geoid': ['13085970205'], 'FIPS': ['13085'], 'Year': [2024], 'parameters': [{"Year": 2024, "hpi_prediction": 304.32205}], 'geometry':[ { "coordinates": [[[[-84.126456, 34.389734], [-84.12641, 34.39026], [-84.126323, 34.39068]]]], "parameter...
[ "Geopandas relies on the shapely library to handle geometry objects. Shapely does not have a concept of parameters or additional metadata which can be included at arbitrary levels in GeoJSON but don't fit the shapely or geopandas data models.\nFor example, when parsing with shapely.geometry.shape:\nIn [10]: shape =...
[ 1, 0 ]
[]
[]
[ "geopandas", "python" ]
stackoverflow_0074596125_geopandas_python.txt
Q: Dividing the data timeline into subset of date ranges of dictioanries in a list in python I am converting date timeline into smaller date time segments based on the frequency in minutes from start time to end time. Input: start_time = '2022-11-20-09:48:00' last_time = '2022-11-20-08:48:00' frequency = 300 # second...
Dividing the data timeline into subset of date ranges of dictioanries in a list in python
I am converting date timeline into smaller date time segments based on the frequency in minutes from start time to end time. Input: start_time = '2022-11-20-09:48:00' last_time = '2022-11-20-08:48:00' frequency = 300 # seconds so it is 5 minutes what I tried so far from datetime import datetime def time_divider(s_tim...
[ "start_time should be less than end_time\nlike:\nstart_time = '2022-11-20-08:48:00'\nlast_time = '2022-11-20-09:48:00'\nand if we hadd 5 minutes in 48 it would become 53 not 52 as you have mentioned in expected output.\nHere is the solution which might solve the problem.\nfrom datetime import datetime, timedelta\n\...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074596235_python_python_3.x.txt
Q: How can I call multiple views in one url address in Django? I'm trying to show forms defined by new_measurement on index.html, but I only manage to get IndexView() to work. I tried various combinations between IndexView() and new_measurement(), but those didn't work out at all. I know that IndexView() doesn't pass...
How can I call multiple views in one url address in Django?
I'm trying to show forms defined by new_measurement on index.html, but I only manage to get IndexView() to work. I tried various combinations between IndexView() and new_measurement(), but those didn't work out at all. I know that IndexView() doesn't pass anything related to new_measurement(), and new_measurement() isn...
[ "You can't map multiple views in one url but you can do mutiple works in one view.\nupdate your views.py as you can see that I am sending (querylist and form) both in that view\nviews.py\ndef new_measurement(request):\n if request.method == \"POST\":\n form = MeasurementForm(request.POST)\n if form...
[ 5, 2, 0, 0, 0 ]
[]
[]
[ "django", "django_urls", "django_views", "python" ]
stackoverflow_0048729966_django_django_urls_django_views_python.txt
Q: How to convert a 5-level dictionary into a DataFrame? I have a dictionary with structure: Level 1: id (int) username (str) meta (contain a string of Kpi_info) This is a dictionary: dict = {'id': 206, 'username': 'hantran','meta': '{"kpi_info":\ {"2021" :{"1":{"revenue":"2000", "kpi":"2100","result":"...
How to convert a 5-level dictionary into a DataFrame?
I have a dictionary with structure: Level 1: id (int) username (str) meta (contain a string of Kpi_info) This is a dictionary: dict = {'id': 206, 'username': 'hantran','meta': '{"kpi_info":\ {"2021" :{"1":{"revenue":"2000", "kpi":"2100","result":"0"}, "2":{"revenue":"2500", "kpi":"2000", "result":"1"}},\ ...
[ "If the string in your dictionary is valid json, it can easily be converted into a dictionary:\nfrom json import loads\n\nd = {'id': 206, 'username': 'hantran', 'meta': '{\"kpi_info\": {\"2021\" :{\"1\":{\"revenue\":\"2000\", \"kpi\":\"2100\",\"result\":\"0\"}, \"2\":{\"revenue\":\"2500\", \"kpi\":\"2000\", \"resul...
[ 1 ]
[]
[]
[ "dataframe", "dictionary", "python" ]
stackoverflow_0074596127_dataframe_dictionary_python.txt
Q: how to create unique ID for pairs I have pandas dataframe that store the relationship of two customers like below. How do I create a unique ID for associated customers? Assuming there are tons of thousands of customers. The customer ID are completed random numbers which are not classified as prefix 'A' and 'B' in ...
how to create unique ID for pairs
I have pandas dataframe that store the relationship of two customers like below. How do I create a unique ID for associated customers? Assuming there are tons of thousands of customers. The customer ID are completed random numbers which are not classified as prefix 'A' and 'B' in the example presented. The prefix is ju...
[ "If you have only A and B, you can simply see the starting point to calculate the ID.\nIn [12]: df['Unique_ID'] = df['cust_1'].map(lambda x: 'ID1' if x.startswith('A')\n ...: else 'ID2') \n\nIn [13]: df ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074596426_python.txt
Q: Getting the latest python 3 version programmatically I want to get the latest python source from https://www.python.org/ftp/python/. While posting this, the latest version is 3.9.1. I do not want to hardcode 3.9.1 in my code to get the latest version and keep on updating the version when a new version comes out. I...
Getting the latest python 3 version programmatically
I want to get the latest python source from https://www.python.org/ftp/python/. While posting this, the latest version is 3.9.1. I do not want to hardcode 3.9.1 in my code to get the latest version and keep on updating the version when a new version comes out. I am using OS ubuntu 16.04 Is there a programmatic way to g...
[ "I had a similar problem and couldn't find anything better than scraping the downloads page. You mentioned curl, so I'm assuming you want a shell script. I ended up with this:\nurl='https://www.python.org/ftp/python/'\n\ncurl --silent \"$url\" |\n sed -n 's!.*href=\"\\([0-9]\\+\\.[0-9]\\+\\.[0-9]\\+\\)/\".*!\\1!...
[ 4, 0 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0065311659_pip_python_python_3.x.txt
Q: How to get mxnet function decorators in python I want to get mxnet function decorators in python. I can get the decorators for Tensorflow as follows: Given that we have the following tensorflow API: tf.math.floor(2.5) When I run the code, the function arguments are set inside tensorflow object. APIname = "tf.math...
How to get mxnet function decorators in python
I want to get mxnet function decorators in python. I can get the decorators for Tensorflow as follows: Given that we have the following tensorflow API: tf.math.floor(2.5) When I run the code, the function arguments are set inside tensorflow object. APIname = "tf.math.floor" apit_split = APIname.split('.') func_name = ...
[ "Just found the answer.\nThe problem is that I should do the above stuff inside __init__.py located in the root folder of mxnet library (installed via pip).\n" ]
[ 0 ]
[]
[]
[ "attributes", "mxnet", "python", "wrapper" ]
stackoverflow_0074595937_attributes_mxnet_python_wrapper.txt
Q: NameError: name 'allTodos' is not defined | UnboundLocalError: local variable 'allTodos' referenced before assignment Hi I am doing practice on flask, creating Todo App. If I use global after db.session.add(todo) then I get an NameError If I dont use global keyword then I get the UnboundLocalError: Here is my co...
NameError: name 'allTodos' is not defined | UnboundLocalError: local variable 'allTodos' referenced before assignment
Hi I am doing practice on flask, creating Todo App. If I use global after db.session.add(todo) then I get an NameError If I dont use global keyword then I get the UnboundLocalError: Here is my code: from flask import Flask, render_template ,request from flask_sqlalchemy import SQLAlchemy from datetime import datetime...
[ "Your variable is defined and assigned in the if statement. There is a chance that code block will not be executed, resulting in the interpreter not knowing what to do when it reaches the return statement without having \"all_todos\" defined. You can always define it and assign it a default value before the if stat...
[ 0 ]
[]
[]
[ "backend", "flask", "flask_sqlalchemy", "python", "python_3.x" ]
stackoverflow_0074596527_backend_flask_flask_sqlalchemy_python_python_3.x.txt
Q: lxml xpath exponential performance behavior I'm trying to use xpath to query a large html with multiple tables and only extract a few tables that contain a specific pattern in one of the cells. I'm running into time related challenges. I've tried to minimize by issue as much as possible. code setup: - creates 10 (...
lxml xpath exponential performance behavior
I'm trying to use xpath to query a large html with multiple tables and only extract a few tables that contain a specific pattern in one of the cells. I'm running into time related challenges. I've tried to minimize by issue as much as possible. code setup: - creates 10 (300x15) tables with random values between 0-100 i...
[ "I don't know if this is relevant (but I suspect so). You can simplify these XPaths by eliminating the //* step and the trailing /ancestor::table step.\n//table[descendant::text() = '{PAT}']\n\nNote that in your problematic XPath, for each table you will find every descendant element whose text is 80 (there might b...
[ 2 ]
[]
[]
[ "lxml", "pandas", "parsing", "python", "xpath" ]
stackoverflow_0074595362_lxml_pandas_parsing_python_xpath.txt
Q: How to plot 4 figures per page with pdfpages in matplotlib? I have the code below which produces the output I want. import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages plt.style.use('ggplot') %matplotlib inline data = di...
How to plot 4 figures per page with pdfpages in matplotlib?
I have the code below which produces the output I want. import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages plt.style.use('ggplot') %matplotlib inline data = dict({'Variable_Grouping':['Type_A', 'Type_A', 'Type_A', 'Type_C', ...
[ "The problem is, even you try to get the number of plots per page, you take the whole data inside the loop to plot with to_plot. You need to filter your to_plot with the cols you get by your grouper and your code will work.\nThe only changes I made is create the variable data_per_page and replace that with to_plot ...
[ 1 ]
[]
[]
[ "matplotlib", "pdfpages", "python" ]
stackoverflow_0074593895_matplotlib_pdfpages_python.txt
Q: opening a .txt file first, i'd like to mention that im using python via visual studio. not sure if this information will be relevant but this is my first time using file input so i'm not sure basically, i have a .txt file located in the same location as my .py file. however, when i go to access it, i get an error ...
opening a .txt file
first, i'd like to mention that im using python via visual studio. not sure if this information will be relevant but this is my first time using file input so i'm not sure basically, i have a .txt file located in the same location as my .py file. however, when i go to access it, i get an error 'FileNotFoundError: [Errn...
[ "Take into account that the script might not be running from the same path where your python script is and most probably your are not specifying the exact path of the file.\nIf your file is located in the same directory where your python sript is you can use the pathlib library this way to get your script to work:\...
[ 0 ]
[]
[]
[ "file", "input", "python" ]
stackoverflow_0074596414_file_input_python.txt
Q: How can I give a user input into terminal after running a terminal command in python? I have a python script that runs a command in terminal using the subprocess module and this command runs another script that asks for a user input. How can I give a user input to terminal from my original python script? Example: ...
How can I give a user input into terminal after running a terminal command in python?
I have a python script that runs a command in terminal using the subprocess module and this command runs another script that asks for a user input. How can I give a user input to terminal from my original python script? Example: contents of introduction.sh below #!/bin/bash **# Ask the user for their name** echo Hello,...
[ "There are a number of ways of doing this with the subprocess package. Here's a simple way to do so:\nimport subprocess\n\nprocess = subprocess.Popen('/tmp/introduction.sh', stdin=subprocess.PIPE)\nprocess.communicate(\"George\".encode())\n\nResult:\nHello, who am I talking to?\nIt's nice to meet you George\n\n" ]
[ 0 ]
[]
[]
[ "python", "terminal", "user_input" ]
stackoverflow_0074595522_python_terminal_user_input.txt
Q: How to find the closet value to input provided from list I am stuck at this point. Need to find the closet value near to my input mylist = [1,8,4,88,100] inp=5 My output: 4 I now using for loop to but need some more efficient way to handle As theinp = 5 ->The nearest value to my input is 4. So my output is 4 A...
How to find the closet value to input provided from list
I am stuck at this point. Need to find the closet value near to my input mylist = [1,8,4,88,100] inp=5 My output: 4 I now using for loop to but need some more efficient way to handle As theinp = 5 ->The nearest value to my input is 4. So my output is 4
[ "Get the absolute diff, from there you will get the nearest value. Then get the element from the index. enumerate gives you the index.\nmylist = [1,8,4,88,100]\n\ninp=5\n\nclosest_val = mylist[min([abs(i-inp), index] for index, i in enumerate(mylist))[-1]] #4\n\n", "Here is a solution using a comprehension:\nnumb...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074596525_python.txt
Q: NotFittedError: All estimators failed to fit for RandomizedSearchCV I am trying to use RandomizedSearchCV for a classification problem (2 classes). The dataset can be downloaded from this Kaggle site. Following is the code showing the error # Load packages from sklearn.model_selection import train_test_split, cros...
NotFittedError: All estimators failed to fit for RandomizedSearchCV
I am trying to use RandomizedSearchCV for a classification problem (2 classes). The dataset can be downloaded from this Kaggle site. Following is the code showing the error # Load packages from sklearn.model_selection import train_test_split, cross_val_score from sklearn.model_selection import GridSearchCV, RandomizedS...
[ "It is due to the param distributions you set. uniform(x,y) will generate float values, whereas you are using it for some params that require ints.\nparam_rand = {'max_depth':(3,10),\n 'max_features':(2,4),\n 'learning_rate':uniform(0.01,1),\n 'n_estimators':(80,150),\n ...
[ 1 ]
[]
[]
[ "machine_learning", "python", "scikit_learn" ]
stackoverflow_0074596455_machine_learning_python_scikit_learn.txt
Q: Extracting multiple strings from a Pandas row (single cell) into columns, with specific starting and ending text I have a dataframe df where one column 'Images' contains a bunch of HTML strings in each row from which I would like to extract URLs, that have a specific Start and End characters. Ideally they would th...
Extracting multiple strings from a Pandas row (single cell) into columns, with specific starting and ending text
I have a dataframe df where one column 'Images' contains a bunch of HTML strings in each row from which I would like to extract URLs, that have a specific Start and End characters. Ideally they would then be turned into columns for each URL extracted. df example: df = pd.DataFrame({ 'Description': ['USB Emergency L...
[ "Example\ns1 = pd.Series(['aaa123.jpg', 'bca234.jpg', 'aaa425.gif', 'aaa234.jpg'])\n\ns1\n0 aaa123.jpg\n1 bca234.jpg\n2 aaa425.gif\n3 aaa234.jpg\ndtype: object\n\nCode\nif you want extract from 'aa' to '.jpg'\ns1.str.extract('(aa.+.jpg)').dropna()[0]\n\nresult:\n0 aaa123.jpg\n3 aaa234.jpg\nName: ...
[ 1, 1, 1 ]
[]
[]
[ "extract", "pandas", "python", "regex" ]
stackoverflow_0074595772_extract_pandas_python_regex.txt
Q: Pytorch-Lightning ModelCheckpoint get paths of saved checkpoints I am using PytorchLightning and beside others a ModelCheckpoint which saves models with a formated filename like `filename="model_{epoch}-{val_acc:.2f}" In a process I want to load these checkpoints again, for simplicity lets say I want only the best...
Pytorch-Lightning ModelCheckpoint get paths of saved checkpoints
I am using PytorchLightning and beside others a ModelCheckpoint which saves models with a formated filename like `filename="model_{epoch}-{val_acc:.2f}" In a process I want to load these checkpoints again, for simplicity lets say I want only the best via save_top_k=N. As the filename is dynamic I wonder how can I retri...
[ "you can retrieve the best model path after training from the checkpoint\n# retrieve the best checkpoint after training\ncheckpoint_callback = ModelCheckpoint(dirpath='my/path/')\ntrainer = Trainer(callbacks=[checkpoint_callback])\nmodel = ...\ntrainer.fit(model)\ncheckpoint_callback.best_model_path\n\nTo find all ...
[ 1 ]
[]
[]
[ "python", "pytorch", "pytorch_lightning" ]
stackoverflow_0074577562_python_pytorch_pytorch_lightning.txt
Q: Working with values from 2 separate lists - Python I have 2 lists which each have 10 value and i want to multiply the values. import random n1_r = random.sample(range(1, 100), 10) n2_r = random.sample(range(1, 100), 10) n1 = n1_r n2 = n2_r for example I want to multiply the first value from n1 with the first va...
Working with values from 2 separate lists - Python
I have 2 lists which each have 10 value and i want to multiply the values. import random n1_r = random.sample(range(1, 100), 10) n2_r = random.sample(range(1, 100), 10) n1 = n1_r n2 = n2_r for example I want to multiply the first value from n1 with the first value in n2 and so on? im expecting a new list of 10 value...
[ "n3 = [a * b for a, b in zip(n1, n2)]\n\n", "You can do this in numerous ways. I would go with a basic list comprehension considering the experience level you are.\nFor example:\narray1 = [2, 2, 2, 2]\narray2 = [3, 3, 3, 3]\narray3 = [i * j for i,j in zip(array1, array2)]\n>>> array3\n[6, 6, 6, 6]\n\nThen you ca...
[ 2, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074596393_list_python.txt
Q: Set name to groupby size column in Pandas I have a data frame that I need to count the unique items of a certain row. In the example below, I want to label the name for the below function as "NUM_CIK". What's the best way to assign a name to the groupby column? Current code: cik_groupby_cusip_occur = cik_group...
Set name to groupby size column in Pandas
I have a data frame that I need to count the unique items of a certain row. In the example below, I want to label the name for the below function as "NUM_CIK". What's the best way to assign a name to the groupby column? Current code: cik_groupby_cusip_occur = cik_groupby_cusip_occur.groupby( ['CUSIP'], sort...
[ "Use Series.reset_index with name parameter:\n(cik_groupby_cusip_occur = cik_groupby_cusip_occur\n .groupby('CUSIP')['CIK COMPANY']\n .size()\n .sort_values(ascending=False)\n .reset_index(name='NUM_CIK'))\n\nOr Series.value_counts:\ncik_groupby_cusip_occur = (cik_groupby_cusip_occur...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074596543_pandas_python.txt
Q: Run Python script without Windows console appearing Is there any way to run a Python script in Windows XP without a command shell momentarily appearing? I often need to automate WordPerfect (for work) with Python, and even if my script has no output, if I execute it from without WP an empty shell still pops up for...
Run Python script without Windows console appearing
Is there any way to run a Python script in Windows XP without a command shell momentarily appearing? I often need to automate WordPerfect (for work) with Python, and even if my script has no output, if I execute it from without WP an empty shell still pops up for a second before disappearing. Is there any way to preven...
[ "pythonw.exe will run the script without a command prompt. The problem is that the Python interpreter, Python.exe, is linked against the console subsystem to produce console output (since that's 90% of cases) -- pythonw.exe is instead linked against the GUI subsystem, and Windows will not create a console output w...
[ 133, 37, 8, 4, 2, 1, 0, 0, 0, 0 ]
[ "I had the same problem. I tried many options, and all of them failed\nBut I tried this method, and it magically worked!!!!!\nSo, I had this python file (mod.py) in a folder, I used to run using command prompt\nWhen I used to close the cmd the gui is automatically closed.....(SAD),\nSo I run it as follows \nC:\\......
[ -2 ]
[ "python", "shell", "windows" ]
stackoverflow_0001689015_python_shell_windows.txt
Q: Group-by some value with time condition in pandas Suppose I have a DataFrame like this - ID-A ID-B ID-C Time 1 A X 2022/01/01 09:00:00 1 A X 2022/01/01 09:10:00 1 A Y 2022/01/02 10:15:00 2 B Y 2022/01/01 11:45:00 2 C Y 2022/01/01 01:00:00 2 C Y 202...
Group-by some value with time condition in pandas
Suppose I have a DataFrame like this - ID-A ID-B ID-C Time 1 A X 2022/01/01 09:00:00 1 A X 2022/01/01 09:10:00 1 A Y 2022/01/02 10:15:00 2 B Y 2022/01/01 11:45:00 2 C Y 2022/01/01 01:00:00 2 C Y 2022/01/01 12:00:00 I want to group by columns ID-A and I...
[ "Use:\n(df.groupby(['ID-A', 'ID-B'], as_index=False)\n .agg(Value=('ID-C', 'size'),\n start_time=('Time', 'min'),\n end_time=('Time', 'max'),\n )\n)\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "group_by", "numpy", "pandas", "python" ]
stackoverflow_0074596630_dataframe_group_by_numpy_pandas_python.txt
Q: Pandas - Applying formula on all column based on a value on the row lets say I have a dataframe like below +------+------+------+-------------+ | A | B | C | devisor_col | +------+------+------+-------------+ | 2 | 4 | 10 | 2 | | 3 | 3 | 9 | 3 | | 10 | 25 | 40 | ...
Pandas - Applying formula on all column based on a value on the row
lets say I have a dataframe like below +------+------+------+-------------+ | A | B | C | devisor_col | +------+------+------+-------------+ | 2 | 4 | 10 | 2 | | 3 | 3 | 9 | 3 | | 10 | 25 | 40 | 10 | +------+------+------+-------------+ what would be the bes...
[ "IIUC, use pandas.DataFrame.divide on axis=0 :\nmodResult= (\n pd.concat(\n [my_df, my_df.filter(like=\"Col\") # selecting columns\n .divide(my_df[\"devisor_col\"], axis=0).add_suffix(\"_div\")], axis=1)\n )\n\n# Output :\nprint(modResult)\n\n Col1 Col2 Col3 deviso...
[ 2, 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074596399_pandas_python.txt
Q: Why `vectorize` is outperformed by `frompyfunc`? Numpy offers vectorize and frompyfunc with similar functionalies. As pointed out in this SO-post, vectorize wraps frompyfunc and handles the type of the returned array correctly, while frompyfunc returns an array of np.object. However, frompyfunc outperforms vectori...
Why `vectorize` is outperformed by `frompyfunc`?
Numpy offers vectorize and frompyfunc with similar functionalies. As pointed out in this SO-post, vectorize wraps frompyfunc and handles the type of the returned array correctly, while frompyfunc returns an array of np.object. However, frompyfunc outperforms vectorize consistently by 10-20% for all sizes, which can als...
[ "Following the hints of @hpaulj we can profile the vectorize-function:\narr=np.linspace(0,1,10**7)\n%load_ext line_profiler\n\n%lprun -f np.vectorize._vectorize_call \\\n -f np.vectorize._get_ufunc_and_otypes \\\n -f np.vectorize.__call__ \\\n vectorize(arr)\n\nwhich shows that 100% of time is ...
[ 3, 0 ]
[]
[]
[ "arrays", "numpy", "performance", "perfplot", "python" ]
stackoverflow_0057253839_arrays_numpy_performance_perfplot_python.txt
Q: Getting this error called on Kaggle as ""ImportError: cannot import name 'DecisionBoundaryDisplay' from 'sklearn.inspection'"" I have searched for this error on stackoverflow, people have asked about it but I'm using and working in Kaggle which doesn't need any environment and library to install and set up. Help m...
Getting this error called on Kaggle as ""ImportError: cannot import name 'DecisionBoundaryDisplay' from 'sklearn.inspection'""
I have searched for this error on stackoverflow, people have asked about it but I'm using and working in Kaggle which doesn't need any environment and library to install and set up. Help me out with this. import warnings warnings.filterwarnings('ignore') from sklearn.datasets import load_iris from sklearn.cluster impo...
[ "DecisionBoundaryDisplay requires nightly build version of sklearn as it's a new feature. (https://scikit-learn.org/dev/modules/generated/sklearn.inspection.DecisionBoundaryDisplay.html)\nIf you run this in your Kaggle notebook:\nimport sklearn; sklearn.show_versions()\n\nyou should see that the version is insuffic...
[ 0 ]
[]
[]
[ "iris_dataset", "kaggle", "numpy", "python", "scikit_learn" ]
stackoverflow_0074588825_iris_dataset_kaggle_numpy_python_scikit_learn.txt
Q: Scrapy startproject command failed on import etree, Mac M1. The error message is: "symbol not found in flat namespace" I am trying to start a project using the Scrapy library, for a small webscraping project, but it fails on the import etree module. The exact error on the traceback is: from .. import etree ImportE...
Scrapy startproject command failed on import etree, Mac M1. The error message is: "symbol not found in flat namespace"
I am trying to start a project using the Scrapy library, for a small webscraping project, but it fails on the import etree module. The exact error on the traceback is: from .. import etree ImportError: dlopen(/Users/myname/Desktop/scrapy_project/venv/lib/python3.10/site-packages/lxml/etree.cpython-310-darwin.so, 0x0002...
[ "had the same issue, uninstall lxml:\npip3 uninstall lxml\nthen\npip3 install lxml --no-cache-dir it will force redownload and build wheel\n", "I fixed this issue with uninstalling lxml and reinstalling it with conda:\npip uninstall lxml\nconda -c install lxml\n\n" ]
[ 0, 0 ]
[]
[]
[ "apple_m1", "lxml", "python", "scrapy", "xml.etree" ]
stackoverflow_0070862598_apple_m1_lxml_python_scrapy_xml.etree.txt
Q: I have written a django query but need specific user information of particular date Models: class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=1,related_name='Employee') eid = models.IntegerField(primary_key=True) salary = models.IntegerField(null=True, bl...
I have written a django query but need specific user information of particular date
Models: class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=1,related_name='Employee') eid = models.IntegerField(primary_key=True) salary = models.IntegerField(null=True, blank=True) gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=1) ...
[ "Use this Queryset:\nfrom django.db.models import Q\nfrom datetime import date\n\n\nBreaks.objects.filter(\n Q(employee__user=request.user) & \n Q(attendance__attendance_date=date.today())\n)\n\nOr:\n\nBreaks.objects.filter(\n Q(employee__user=request.user) & \n Q(attendance__attendance_date=\"2022-11-2...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "django_queryset", "django_views", "python" ]
stackoverflow_0074596023_django_django_models_django_queryset_django_views_python.txt
Q: Django Not Reflecting Updates to Javascript Files? I have javascript files in my static folder. Django finds and loads them perfectly fine, so I don't think there is anything wrong with my configuration of the static options. However, sometimes when I make a change to a .js file and save it, the Django template th...
Django Not Reflecting Updates to Javascript Files?
I have javascript files in my static folder. Django finds and loads them perfectly fine, so I don't think there is anything wrong with my configuration of the static options. However, sometimes when I make a change to a .js file and save it, the Django template that uses it does NOT reflect those changes -- inspecting ...
[ "I believe your browser is caching your js\nyou could power refresh your browser, or clear browser cache? \non chrome control+f5 or shift + f5\ni believe on firefox it is control + shift + r\n", "Since you are editing JavaScript files and watching for the changes in the browser I assume you are actively developi...
[ 34, 15, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0015641474_django_python.txt
Q: Why does this code goes into infinite loop? - python i tried to when year and month match loop end but it not works, how i get rid of infinite loop driver.switch_to.frame(0) month = "March" year = 2023 driver.find_element(By.XPATH, "//input[@id='datepicker']").click() while True: mon = driver.find_element(B...
Why does this code goes into infinite loop? - python
i tried to when year and month match loop end but it not works, how i get rid of infinite loop driver.switch_to.frame(0) month = "March" year = 2023 driver.find_element(By.XPATH, "//input[@id='datepicker']").click() while True: mon = driver.find_element(By.XPATH, "//span[@class='ui-datepicker-month']").text ...
[ "Try using equals or is:\nmon.__eq__(month) and yr.__eq__(year)\n\nInstead of while true you can also negate the part that you use for breaking so it will be like while year and month not equal to something do this.\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "while_loop" ]
stackoverflow_0074596708_python_selenium_while_loop.txt
Q: Loop keeps returning to wrong part I'm taking a fundamentals of programming class and we're supposed to be building a menu that calculates BMI and also shows different gym membership options, what I can't figure out is why my menu keeps looping back to the BMI calculator after viewing the membership rates. this is...
Loop keeps returning to wrong part
I'm taking a fundamentals of programming class and we're supposed to be building a menu that calculates BMI and also shows different gym membership options, what I can't figure out is why my menu keeps looping back to the BMI calculator after viewing the membership rates. this is some of my code: def mainmenu(): op...
[ "It looks like the reason for this is that you're using option variable to store the value that user provide for both main menu and sub menu.\nInstead of this\nsubmenu()\noption = int(input(\"Enter your option: \"))\n\nUse\nsubmenu()\nsubmenu_option = int(input(\"Enter your option: \"))\n\nAlso replace the option...
[ 1 ]
[]
[]
[ "bmi", "menu", "python" ]
stackoverflow_0074596825_bmi_menu_python.txt
Q: Building a Python dictionary from a list (no redundant entries) while keeping a count I'm new to Python coming from a JavaScript background. I'm trying to find a solution for the following. I want to build a dictionary from list data on the fly. I only want to add the list entries that are unique, with a count of ...
Building a Python dictionary from a list (no redundant entries) while keeping a count
I'm new to Python coming from a JavaScript background. I'm trying to find a solution for the following. I want to build a dictionary from list data on the fly. I only want to add the list entries that are unique, with a count of 1. Any repeats thereafter I want to keep a count of. Hence from a list containing ["one", "...
[ "Use collections.Counter.\nIn [1]: from collections import Counter\n\nIn [2]: items = [\"one\", \"two\", \"three\", \"one\"]\n\nIn [3]: Counter(items)\nOut[3]: Counter({'one': 2, 'two': 1, 'three': 1})\n\nIn [4]: dict(Counter(items))\nOut[4]: {'one': 2, 'two': 1, 'three': 1}\n\n\n" ]
[ 0 ]
[ "#1 This might just be the answer I was looking for.\ndata = [\"one\", \"two\", \"three\", \"one\"]\nnew_dict = {}\n\n\nfor x in data:\n if x in new_dict:\n new_dict[x] = new_dict[x] + 1\n else:\n new_dict[x] = 1\n\nprint(new_dict)\n\n#2 Using list comprehension.\nnew_dict = [[x, data.count(x)] for x in set...
[ -1 ]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074596396_dictionary_python_python_3.x.txt
Q: How To Scroll Inside An Element On A Webpage (Selenium Python) How can I scroll down in a certain element of a webpage in Selenium? Basically my goal is to scroll down in this element until new profile results stop loading. Let's say that there should be 100 profile results that I'm trying to gather. By default, t...
How To Scroll Inside An Element On A Webpage (Selenium Python)
How can I scroll down in a certain element of a webpage in Selenium? Basically my goal is to scroll down in this element until new profile results stop loading. Let's say that there should be 100 profile results that I'm trying to gather. By default, the webpage will load 30 results. I need to scroll down IN THIS SECTI...
[ "OKAY! I found something that works. (If anyone knows a better solution please let me know)\nYou can use this code to scroll to the bottom of the page:\ndriver.find_element(By.TAG_NAME, 'html').send_keys(Keys.END) # works, but not inside element.\n\nWhat I had to do was more complicated though (since I am trying t...
[ 1 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_chromedriver" ]
stackoverflow_0074596105_python_python_3.x_selenium_selenium_chromedriver.txt
Q: discord py command not found I'm making a discord bot, and trying to have / menu context commands. this is my code: import discord from discord.ext import commands from dotenv import load_dotenv import requests load_dotenv() url = "https://discord.com/api/v10/applications/ID/commands" TOKEN = "TOKEN" # This is an...
discord py command not found
I'm making a discord bot, and trying to have / menu context commands. this is my code: import discord from discord.ext import commands from dotenv import load_dotenv import requests load_dotenv() url = "https://discord.com/api/v10/applications/ID/commands" TOKEN = "TOKEN" # This is an example CHAT_INPUT or Slash Comm...
[ "Seems like you try to use slash commands, but you aren’t defining any app commands (slash commands) you‘re defining a text command.\nto you slash commands, you should use the app_commands package of discord.py. it also handles registering the app commands at discord\nhttps://discordpy.readthedocs.io/en/stable/inte...
[ 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0074596095_bots_discord_discord.py_python.txt
Q: How to remove a string part of a column value? I'm working with a dataset in Python. I've loaded it into a dataframe so that I can perform a linear regression on it. But first I need to clean the dataframe so that it only has number values. One of the columns has movies' runtime in it, phrased like this: **Runtime...
How to remove a string part of a column value?
I'm working with a dataset in Python. I've loaded it into a dataframe so that I can perform a linear regression on it. But first I need to clean the dataframe so that it only has number values. One of the columns has movies' runtime in it, phrased like this: **Runtime** 142 min 175 min 152 min 202 min 96 min ... And s...
[ "If need numeric before min use Series.str.extract:\ndf['Runtime'] = df['Runtime'].str.extract('(\\d+)\\s*min', expand=False).astype(int)\n\nOr convert values to timedeltas by to_timedelta and convert to minutes from seconds by Series.dt.total_seconds and divide 60:\ndf['Runtime'] = pd.to_timedelta(df['Runtime']).d...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074597020_dataframe_pandas_python.txt
Q: i want to calculate the distance using geodesic from geopy library I have four lists of longitude and latitude ''' shop_long = [-123.223, -127.223, -123.223, -123.048] shop_lat = [49.1534, 55.1303, 49.1534, 53.2563] cus_long = [-126.07325247944962, -126.07255765553835, -126.07485428820583, -126.07335...
i want to calculate the distance using geodesic from geopy library
I have four lists of longitude and latitude ''' shop_long = [-123.223, -127.223, -123.223, -123.048] shop_lat = [49.1534, 55.1303, 49.1534, 53.2563] cus_long = [-126.07325247944962, -126.07255765553835, -126.07485428820583, -126.0733578858899, -126.07270416708549] cus_lat = [51.29548801984406, 51.2948618...
[ "Consider utilizing zip:\nfrom geopy.distance import geodesic\n\n\ndef main() -> None:\n shop_long = [-123.223, -127.223, -123.223, -123.048]\n shop_lat = [49.1534, 55.1303, 49.1534, 53.2563]\n shop_cords = [(lat, long) for lat, long in zip(shop_lat, shop_long)]\n cus_long = [-126.07325247944962, -126.0...
[ 0 ]
[]
[]
[ "data_science", "geopy", "machine_learning", "python", "r" ]
stackoverflow_0074596952_data_science_geopy_machine_learning_python_r.txt
Q: Python - AttributeError: 'NoneType' object has no attribute 'cursor' python flask I'm trying to populate the courses selectfield in my webapp using data from the database. this is my attempt. this the form ` class StudentForm(FlaskForm): idnumber = StringField('ID Number', [validators.DataRequired(), validator...
Python - AttributeError: 'NoneType' object has no attribute 'cursor' python flask
I'm trying to populate the courses selectfield in my webapp using data from the database. this is my attempt. this the form ` class StudentForm(FlaskForm): idnumber = StringField('ID Number', [validators.DataRequired(), validators.Length(min=9, max=9)]) fname = StringField('First Name', [validators.DataRequired...
[ "To create a cursor, use the cursor() method of a connection object:\ncnx = mysql.connector.connect(database='Hello_World')\ncursor = cnx.cursor()\n\n", "It seems like your mysql.connection object is None in that particular case. That's why it doesn't have a cursor attribute.\nGenerally, I recommend you to check ...
[ 0, 0 ]
[]
[]
[ "database", "flask", "laragon", "python", "web_applications" ]
stackoverflow_0074596876_database_flask_laragon_python_web_applications.txt
Q: Python mock() not mocking the return value I'm having some trouble with Python mock() and I'm not familiar enough to figure out what's going on with it. I have an abstract async task class that looks something like: class AsyncTask(object): @classmethod def enqueue(cls): .... task_ent = cls...
Python mock() not mocking the return value
I'm having some trouble with Python mock() and I'm not familiar enough to figure out what's going on with it. I have an abstract async task class that looks something like: class AsyncTask(object): @classmethod def enqueue(cls): .... task_ent = cls.createAsyncTask(body, delayed=will_delay) ...
[ "Try the following:\n@patch(\"package_name.module_name.createAsyncTask\")\ndef test_my_test(self, mock_create_task):\n ....\n mock_create_task.return_value = \"12\"\n fn() # calls CustomAsyncTaskClass.enqueue(...)\n ....\n\nwhere module_name is the name of the module which contains the class AsyncTas...
[ 2, 0 ]
[]
[]
[ "magicmock", "python", "python_mock", "python_unittest", "unit_testing" ]
stackoverflow_0031014939_magicmock_python_python_mock_python_unittest_unit_testing.txt
Q: SBERT gives same result no matter what I have a test script for SBERT: import torch from transformers import BertTokenizer, BertModel from sklearn.cluster import KMeans # 1. Use SBERT to compare two sentences for semantic similarity. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertModel...
SBERT gives same result no matter what
I have a test script for SBERT: import torch from transformers import BertTokenizer, BertModel from sklearn.cluster import KMeans # 1. Use SBERT to compare two sentences for semantic similarity. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertModel.from_pretrained('bert-base-uncased') input...
[ "There was a couple of tiny modification to sort things out. Please bear in mind in order to cluster sentences you need to catch only the first/last embedding for the sentence. In addition KMeans expects to receive a 2D array for clustering.\nimport torch\nfrom transformers import BertTokenizer, BertModel\nfrom skl...
[ 1 ]
[]
[]
[ "bert_language_model", "nlp", "python" ]
stackoverflow_0074591917_bert_language_model_nlp_python.txt
Q: Count number of substrings in String by multiple delimiters Imagine the following example Strings ‘John @ Mary John v Mary John vs Mary’ ‘John v Mary Ben v Paul John v Mary’ ‘Hello World / John v Mary John @ Mary John vs Mary’ ‘John v Mary John vs Mary John @ Mary John v Mary’ T...
Count number of substrings in String by multiple delimiters
Imagine the following example Strings ‘John @ Mary John v Mary John vs Mary’ ‘John v Mary Ben v Paul John v Mary’ ‘Hello World / John v Mary John @ Mary John vs Mary’ ‘John v Mary John vs Mary John @ Mary John v Mary’ There are 3 identified delimiters ' @ ' ' v ' ' vs ' For every f...
[ "Try with this code that assumes always exists a space before and after the delimiter\n!/usr/bin/python3\n\nimport re\nfrom copy import deepcopy\nfrom typing import List, Tuple, Union\n\ndef count_match(s: str, d: List[str]) -> Tuple[Union[None, str], int, int]:\n\n if len(s) == 0:\n return None, 0, 0\n\n...
[ 1, 0 ]
[]
[]
[ "delimiter", "python", "string", "substring" ]
stackoverflow_0074588275_delimiter_python_string_substring.txt
Q: pd.read_html(url) - awkward table design Table headings through the table are being converted into single column headings. url = "https://www.environment.nsw.gov.au/topics/animals-and-plants/threatened-species/programs-legislation-and-framework/nsw-koala-strategy/local-government-resources-for-koala-conservation/n...
pd.read_html(url) - awkward table design
Table headings through the table are being converted into single column headings. url = "https://www.environment.nsw.gov.au/topics/animals-and-plants/threatened-species/programs-legislation-and-framework/nsw-koala-strategy/local-government-resources-for-koala-conservation/north-coast-koala-management-area#:~:text=The%2...
[ "The table cannot be easily parsed with read_html because of its unorthodox use of <thead> attribute. You can try luck with BeautifulSoup:\nimport bs4\nimport urllib.request\n\nsoup = bs4.BeautifulSoup(urllib.request.urlopen(url))\ndata = [[\"\".join(cell.strings).strip() \n for cell in row.find_all(['td', ...
[ 3, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074596303_pandas_python.txt
Q: Why won't PySimpleGui.Input adjust the height correctly? I am trying to create a simple input form for data entry, but I can't get the text input box to change the height, only the width changes when setting the size parameter. Here is my code: import PySimpleGUI as sg def main(): # # create small form for Da...
Why won't PySimpleGui.Input adjust the height correctly?
I am trying to create a simple input form for data entry, but I can't get the text input box to change the height, only the width changes when setting the size parameter. Here is my code: import PySimpleGUI as sg def main(): # # create small form for Data Analysis entry last_printer = sg.Input(key = 'last_pr...
[ "last_printer = sg.Multiline(key = 'last_printer', size = (10,1))\nrejected_carts = sg.Multiline(key = 'rejected_carts', size = (20, 1))\nnotes_for_self = sg.Multiline(key = 'notes_for_self', size = (50,4))\nnotes_for_ops = sg.Multiline(key = 'notes_for_ops', size = (50, 4))\n\n" ]
[ 0 ]
[]
[]
[ "pysimplegui", "python" ]
stackoverflow_0068942822_pysimplegui_python.txt
Q: How to run a Python file in Visual Studio code from the terminal? I have tried to run a pretty simple code x = input("What's x? ") y = input("What's y? ") z= int(x) + int(y) print (z) But, when I try to run that code from the terminal writing "name_of_the_file.py", I find this error: "The term "name_of_the_file...
How to run a Python file in Visual Studio code from the terminal?
I have tried to run a pretty simple code x = input("What's x? ") y = input("What's y? ") z= int(x) + int(y) print (z) But, when I try to run that code from the terminal writing "name_of_the_file.py", I find this error: "The term "name_of_the_file.py" is not recognized as the name of a cmdlet, function, script file,...
[ "Click the play button to run the code, watch the terminal and you can see that it is using the command & c:/WorkSpace/pytest11/.venv/Scripts/python.exe c:/WorkSpace/pytest11/main.py to run the code.\n\nSo if you need to manually type commands in the terminal to run the code. You can directly copy the above command...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "terminal", "visual_studio", "visual_studio_code" ]
stackoverflow_0074595712_python_terminal_visual_studio_visual_studio_code.txt
Q: I tried to install emcee and corner for python (linux). I got missing 'python.h' during installation. How to fix the corner installation? I tried to install 'emcee' for python. It seems to work. To start I tried the example here http://dfm.io/emcee/current/user/line/ I want to get such corner plots as in the examp...
I tried to install emcee and corner for python (linux). I got missing 'python.h' during installation. How to fix the corner installation?
I tried to install 'emcee' for python. It seems to work. To start I tried the example here http://dfm.io/emcee/current/user/line/ I want to get such corner plots as in the example so I've to install 'corner' too. This fails. Uninstallation and reinstallation of wheel with pip get some small progress, but now I stuck. ...
[ "This is the duplicate question.\nPlease refer to this Answer for installation of libssl\n" ]
[ 0 ]
[]
[]
[ "apt_get", "dependencies", "installation", "module", "python" ]
stackoverflow_0056241573_apt_get_dependencies_installation_module_python.txt
Q: python subprocess does not write the output I have the following code snippet as a Python script. I get the proper job output files with no errors. However the stdout subprocess log files (i.e. COSMOSIS_output_XXX.txt etc) don't store the expected runtime logs. Instead, these files have <_io.TextIOWrapper name=9 e...
python subprocess does not write the output
I have the following code snippet as a Python script. I get the proper job output files with no errors. However the stdout subprocess log files (i.e. COSMOSIS_output_XXX.txt etc) don't store the expected runtime logs. Instead, these files have <_io.TextIOWrapper name=9 encoding='UTF-8'> as the only output written in th...
[ "First of all you are just opening the file, you are not reading anything from it, you are not storing the information of the file anywhere, so it will just create that <_io.TextIOWrapper name=9 encoding='UTF-8'> which is very easy reproducible:\nfile = open(\"testtextf.txt\",\"a\")\nprint(file)\n\nYou have to read...
[ 1, 1 ]
[ "Ok, the following snippet is sufficient solution to the question posted above.\nwith open(\"%sCOSMOSIS_output_%s.txt\" % (ERROR_PATH, ini), \"wb\") as file, open(\"%sCOSMOSIS_output_ERROR_%s.txt\" % (ERROR_PATH, ini), \"wb\") as file_e:\n job3 = subprocess.Popen(\n [\"cosmosis\" + Vector],\n shell...
[ -1 ]
[ "python", "python_3.x", "stdout", "subprocess" ]
stackoverflow_0074591331_python_python_3.x_stdout_subprocess.txt
Q: how to show both key and value in dictionary in the format they are in I have a dictionary look like this mydict = { 'type' : 'fruit', 'quantity': 20 } i wan to print only the 'type' field in the way it is ,like this {'type': 'fruit'} i found this on other website class fruits(dict): def __str__(self): ...
how to show both key and value in dictionary in the format they are in
I have a dictionary look like this mydict = { 'type' : 'fruit', 'quantity': 20 } i wan to print only the 'type' field in the way it is ,like this {'type': 'fruit'} i found this on other website class fruits(dict): def __str__(self): return json.dumps(self) collect = [['apple','grapes']] result = fruits(col...
[ "If you're trying to define a class that behaves exactly like dict with the only exception being that it always prints in a particular way, this might be the way to go:\nclass subclass_of_dict(dict):\n def __str__(self):\n return \"{'type' : \" + f\"'{self.get('type')}'\" + '}'\n\nWith your class defined ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074596593_python.txt
Q: Dealing with outliers in Pandas - Substitution of values I get a little confused dealing with outliers. I have a DataFrame that I need to go through and in every column that has a numeric value I need to find the outliers. If the value exceeds the outliers , I want to replace it with the np.nan value. I think my p...
Dealing with outliers in Pandas - Substitution of values
I get a little confused dealing with outliers. I have a DataFrame that I need to go through and in every column that has a numeric value I need to find the outliers. If the value exceeds the outliers , I want to replace it with the np.nan value. I think my problem is in replacing the outlier values with the np.nan valu...
[ "Change:\n if (new_df[col][0] < lower_limit) | (new_df[col][0] > upper_limit):\n new_df[col] = np.nan\n\nby DataFrame.loc:\nnew_df.loc[(new_df[col] < lower_limit) | (new_df[col] > upper_limit), col] = np.nan\n\nOr:\nnew_df.loc[~new_df[col].between(lower_limit,upper_limit, inclusive=\"neither\"), col] = np.na...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074597261_pandas_python.txt
Q: How to uniquely get the win32api/win32gui figure handle from the matplotlib figure object I wonder what is the best way to uniquely obtain the win32gui's window handle given the matplotlib's figure object. I know I can find it based on the window title with win32gui.FindWindow() import matplotlib.pyplot as plt imp...
How to uniquely get the win32api/win32gui figure handle from the matplotlib figure object
I wonder what is the best way to uniquely obtain the win32gui's window handle given the matplotlib's figure object. I know I can find it based on the window title with win32gui.FindWindow() import matplotlib.pyplot as plt import win32gui fig = plt.figure() my_title = 'My Figure' fig.canvas.manager.window.title(my_titl...
[ "I found the answer here after searching again by using the 'Tkinter' keyword rather than 'matplotlib'\nBasically I can get the Windows handle (in hexadecimal) with the frame() method and convert it do decimal to then use it with the win32 api:\nimport matplotlib.pyplot as plt\nimport win32gui\n\nfig1 = plt.figure(...
[ 0 ]
[]
[]
[ "matplotlib", "python", "pywin32" ]
stackoverflow_0074588416_matplotlib_python_pywin32.txt
Q: Making GET request to a tiktok url in order to get a canonical link I want to make a GET request to a tiktok url via python but it does not work. Let's say we have a tiktok link from a mobile app – https://vt.tiktok.com/ZS81uRSRR/ and I want to get its video_id which is available in a canonical link. This is the c...
Making GET request to a tiktok url in order to get a canonical link
I want to make a GET request to a tiktok url via python but it does not work. Let's say we have a tiktok link from a mobile app – https://vt.tiktok.com/ZS81uRSRR/ and I want to get its video_id which is available in a canonical link. This is the canonical link for the provided tiktok: https://www.tiktok.com/@notorious_...
[ "Method 1 - Using subprocess\nExecute curl command and catch the output and it will take ~0.5 seconds.\nimport subprocess\nimport re\nprocess_detail = subprocess.Popen([\"curl\", \"https://vt.tiktok.com/ZS81uRSRR/\"], stdout=subprocess.PIPE)\noutput = process_detail.communicate()[0].decode()\nprocess_detail.kill()\...
[ 2 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074596976_python_python_requests.txt
Q: What can I use instead of lambda in my Python code? I was wondering if there was a simple alternative to lambda in my code. def add_attack(self, attack_name): if attack_name in self.known_attacks and attack_name not in self.attacks: try: assert(len(self.attacks) < 4) ...
What can I use instead of lambda in my Python code?
I was wondering if there was a simple alternative to lambda in my code. def add_attack(self, attack_name): if attack_name in self.known_attacks and attack_name not in self.attacks: try: assert(len(self.attacks) < 4) self.attacks[attack_name] = self.known_attacks.get(a...
[ "You could define a function for it:\ndef return_attacks(self,k):\n return self.attacks[k]\n\nAnd use that function in the key:\nminval = min(self.attacks.keys(), key=(self.return_attacks))\n\nI would strongly recommend you get comfortable with lambda functions - and I think it is clear to you now that lambda x ...
[ 3, 1 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0074597006_lambda_python.txt
Q: Is there a way to create and visualize a model for this data? I am working on a small data base (~70 candidates), they are molecules. I want to find the molecule that fits the best with the actual drug. The molecules have different attribute like the type of amino acid, area, volume, affinity of binding and so on....
Is there a way to create and visualize a model for this data?
I am working on a small data base (~70 candidates), they are molecules. I want to find the molecule that fits the best with the actual drug. The molecules have different attribute like the type of amino acid, area, volume, affinity of binding and so on. I want to systematically pick the one that is the best with respec...
[]
[]
[ "Assuming you have the .xlsx file containing the raw data, you can import it in pandas, which is a good way of working with databases within python.\nYou can then use matplot to plot and visualize the data.\n(My examples are gonna seem weird because I do not know much about biochemistry, but I hope you understand h...
[ -1 ]
[ "matplotlib", "python", "seaborn" ]
stackoverflow_0074596981_matplotlib_python_seaborn.txt
Q: Invalid salt error when comparing plain text and hash with bcrypt I'm trying to compare a saved hash and a user input in python using bcrypt. My code: while passnotcorrect == True: password = input("Enter password: ") password = password.encode('utf-8') file = open('password.txt...
Invalid salt error when comparing plain text and hash with bcrypt
I'm trying to compare a saved hash and a user input in python using bcrypt. My code: while passnotcorrect == True: password = input("Enter password: ") password = password.encode('utf-8') file = open('password.txt', 'r') checkhash = file.read() file.close() ...
[ "A little late but I think your issue is that you're trying to compare 'password' which is utf8 encoded string input with 'checkhash', another string read from a file.\nBcrypt.checkpw() takes in a UTF8 encoded string for the password to check as the first argument followed by the UTF8 encoded hash to compare the pa...
[ 0 ]
[]
[]
[ "bcrypt", "compare", "hash", "python", "salt" ]
stackoverflow_0071628244_bcrypt_compare_hash_python_salt.txt
Q: Marshmallow Validation Error of Unknown field for Dict and List of Dict in POST payload This is a POST payload body received in backend for store and order generated in a test frontend application that includes 2 keys with objects List and a Object { "orderedItems": [ { "id": 1, "name": "As...
Marshmallow Validation Error of Unknown field for Dict and List of Dict in POST payload
This is a POST payload body received in backend for store and order generated in a test frontend application that includes 2 keys with objects List and a Object { "orderedItems": [ { "id": 1, "name": "Asado", "amount": 2, "price": 15.99 }, { "id": 3, "name...
[ "If you need to manage a list of objects you must use the List class.\nWhile if the json field name is different from the property name in python, you have to specify which field to load via the attribute parameter\nfrom marshmallow import Schema, fields\n\nclass OrderSchema(Schema):\n orderedItems: fields.List(fi...
[ 1 ]
[]
[]
[ "flask", "marshmallow", "python" ]
stackoverflow_0074596324_flask_marshmallow_python.txt
Q: C# class to Python class I have an class defined in C# as Servicing and i need to convert this code to Python. So how do i convert the Servicing class to a list datatype in python and then use it in Adjusted class? class Servicing { public long StatementName{ get; set; } public string City{ get; set; } } ...
C# class to Python class
I have an class defined in C# as Servicing and i need to convert this code to Python. So how do i convert the Servicing class to a list datatype in python and then use it in Adjusted class? class Servicing { public long StatementName{ get; set; } public string City{ get; set; } } Now this class is used in anot...
[ "class Adjusted:\n\n def __init__(self):\n self.Services = None\n\n\nclass Servicing:\n\n def __init__(self):\n self.StatementName = 0\n self.City = None\n\nDon't know much about Python, But it should be something like the above.\nPlease ignore compilation errors, As I am not from Pythn b...
[ 0, 0 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0074597041_c#_python.txt
Q: Using RandomizedSearchCV to find the best number of neurons and activation function I used the below code to find the best number of neurons in the two hidden layers and the best activation function. def binary_nn_builder(units,activation): model = Sequential() model.add(Input(shape=x_train_norm.shape[1]))...
Using RandomizedSearchCV to find the best number of neurons and activation function
I used the below code to find the best number of neurons in the two hidden layers and the best activation function. def binary_nn_builder(units,activation): model = Sequential() model.add(Input(shape=x_train_norm.shape[1])) model.add(Dense(units, kernel_initializer='normal', activation=activation)) mode...
[ "I believe the issue is somewhere within your data being fitted.\nI was able to get it running with some generated data:\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom tensorflow.keras.layers import Input, Dense\nfrom sklearn.datasets import mak...
[ 0 ]
[]
[]
[ "keras", "machine_learning", "neural_network", "python", "scikit_learn" ]
stackoverflow_0074593981_keras_machine_learning_neural_network_python_scikit_learn.txt