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: Graphviz (on python) not showing latin and chinese characters on github (encoding issue) I have a python notebook and using graphviz for making a graph I get all characters showing correctly on VS Code, but on github all latin and chinese characters show incorrectly like this: I know the problem is on the encodin...
Graphviz (on python) not showing latin and chinese characters on github (encoding issue)
I have a python notebook and using graphviz for making a graph I get all characters showing correctly on VS Code, but on github all latin and chinese characters show incorrectly like this: I know the problem is on the encoding, but it's related to the graphviz library. I don't have problems showing special characters ...
[ "by default this library uses as fontname: Times-roman, this is caused because probably the fontname is not compatible with chinese characters, I can relate this to another similar question and I think that the most recommended thing is to change the fontname to a compatible font for your task:\ncommand line progra...
[ 1 ]
[]
[]
[ "github", "graphviz", "jupyter_notebook", "python" ]
stackoverflow_0074513293_github_graphviz_jupyter_notebook_python.txt
Q: Bootstrap carousel elements how to decrease the built-in width of the section The 1st image is here And the 2nd image is here This is the carousel code of website. <div class="row testing"> <div id="carouselExampleMen" class="carousel carousel-dark slide" data-bs-ride="carousel"> <div class="carousel-inner m...
Bootstrap carousel elements how to decrease the built-in width of the section
The 1st image is here And the 2nd image is here This is the carousel code of website. <div class="row testing"> <div id="carouselExampleMen" class="carousel carousel-dark slide" data-bs-ride="carousel"> <div class="carousel-inner mens-section"> <div class="carousel-item active" data-bs-interval="10000"> ...
[ "You can do that by overwriting its class:\n\n\n.testing {\n width: 100%;\n}\n.carousel-inner{\n width:50%;\n max-height: 200px !important;\n}\n\n\n\nchange the width percentage as you like\nand of course, you can use media queries for different screen sizes\n@media only screen and (max-width: 488px) {}\n\n" ]
[ 0 ]
[]
[]
[ "bootstrap_5", "css", "html", "python", "web" ]
stackoverflow_0074517324_bootstrap_5_css_html_python_web.txt
Q: Problem with importing deepface in python I want to analyse pictures I've saved local in python using PyCharm. I found the module called deepface to do so. I've installed it via the windows prompt and use this code in my script: from deepface import DeepFace result = DeepFace.analyze(img_path='C:\\Users\\...\\UC0...
Problem with importing deepface in python
I want to analyse pictures I've saved local in python using PyCharm. I found the module called deepface to do so. I've installed it via the windows prompt and use this code in my script: from deepface import DeepFace result = DeepFace.analyze(img_path='C:\\Users\\...\\UC0f4MuOdnBnWbk_YuCmjwKA.jpg', actions=['gender','...
[ "So I've foudn out that deepface doesn't work with Python 3.11 because of different dependencies (Status from 2022/11/20). For me Python 3.8 worked.\n" ]
[ 0 ]
[]
[]
[ "deepface", "python", "python_module" ]
stackoverflow_0074400500_deepface_python_python_module.txt
Q: pandas multiindex columns rename hi I would like to rename the columns of my df. it has a multiindex columns and I would like to change the second level of it ie I have : ('GDP US Chained 2012 Dollars SAAR', 'GDP CHWG Index') ('GDP US Personal Consumption Chained 2012 Dollars SAAR', 'GDPCTOT Index') ('US Gross P...
pandas multiindex columns rename
hi I would like to rename the columns of my df. it has a multiindex columns and I would like to change the second level of it ie I have : ('GDP US Chained 2012 Dollars SAAR', 'GDP CHWG Index') ('GDP US Personal Consumption Chained 2012 Dollars SAAR', 'GDPCTOT Index') ('US Gross Private Domestic Investment Total C...
[ "Use rename with lambda function and parameter level=1:\nL = [('GDP US Chained 2012 Dollars SAAR', 'GDP CHWG Index'),\n ('GDP US Personal Consumption Chained 2012 Dollars SAAR', 'GDPCTOT Index'),\n ('US Gross Private Domestic Investment Total Chained 2012 SAAR', 'GPDITOTC Index')]\n\nc = pd.MultiIndex.from_tu...
[ 0, 0 ]
[]
[]
[ "multi_index", "pandas", "python", "rename" ]
stackoverflow_0074517802_multi_index_pandas_python_rename.txt
Q: Check python function determine isogram from codewars An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case. is_isogram("Dermatogly...
Check python function determine isogram from codewars
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case. is_isogram("Dermatoglyphics" ) == true is_isogram("aba" ) == false is_isogram("mo...
[ "How about using sets? Casting the string into a set will drop the duplicate characters, causing isograms to return as True, as the length of the set won't differ from the length of the original string:\ndef is_isogram(s):\n s = s.lower()\n return len(set(s)) == len(s)\n\nprint is_isogram(\"Dermatoglyphics\")...
[ 4, 3, 1, 1, 0, 0 ]
[]
[]
[ "algorithm", "python", "python_2.7", "string" ]
stackoverflow_0037924869_algorithm_python_python_2.7_string.txt
Q: Jupyter Notebook no output even though compilation successfull I am fairly new to Python and working with a Jupyter Notebook in which I am supposed to classify the MNIST dataset using a DecisionTreeClassifier. Now the dataset has previously already been divided into the features and the target variables in seperat...
Jupyter Notebook no output even though compilation successfull
I am fairly new to Python and working with a Jupyter Notebook in which I am supposed to classify the MNIST dataset using a DecisionTreeClassifier. Now the dataset has previously already been divided into the features and the target variables in seperate files. When reading those in and working with them, I can't seem t...
[ "You defined the function mnistDC, but did not call it, which is why there is no output.\nIn order to call the function, put the following line just after the definition, or in a new cell :\nmnistDC()\n\n" ]
[ 0 ]
[]
[]
[ "classification", "decision_tree", "jupyter", "output", "python" ]
stackoverflow_0074517761_classification_decision_tree_jupyter_output_python.txt
Q: Encryption of an input with Caesar Cipher in Python I have to write this code where The function must receive a path to a text file which must contain text composed of only English letters and punctuation symbols and a destination file for encrypted data. Punctuation symbols must be left as they are without any mo...
Encryption of an input with Caesar Cipher in Python
I have to write this code where The function must receive a path to a text file which must contain text composed of only English letters and punctuation symbols and a destination file for encrypted data. Punctuation symbols must be left as they are without any modification and the encrypted text must be written to a di...
[ "You can validate input string by checking if it doesn't contain any Alphabet characters then it's invalid input:\nimport string\n\ndef check_valid_input(str):\n for c in str:\n if not c.isalpha() and (c not in string.punctuation):\n return False\n return True and any(c.isalpha() for c in st...
[ 1, 0 ]
[]
[]
[ "caesar_cipher", "python" ]
stackoverflow_0074517671_caesar_cipher_python.txt
Q: Convert list of tuple string to list of tuple object in python I have string like below: [(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)] i need to convert above string to object in python like below: [('.1', 'apple'), ('.2', 'orange'), ('.3', 'banana'), ('.4', 'jack'), ('.5', 'grap...
Convert list of tuple string to list of tuple object in python
I have string like below: [(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)] i need to convert above string to object in python like below: [('.1', 'apple'), ('.2', 'orange'), ('.3', 'banana'), ('.4', 'jack'), ('.5', 'grape'), ('.6', 'mango')] is there any efficient way of converting this ...
[ "you can do the following\nimport re\n\nstring = \"\"\"[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]\"\"\"\nvalues = [tuple(ele.split(',')) for ele in re.findall(\".\\d, \\w+\", string)]\n\nthis outputs\nprint(values)\n>>> [('.1', ' apple'), ('.2', ' orange'), ('.3', ' banana'), ('...
[ 2, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0074517565_list_python_string.txt
Q: What is the requirements.txt, what should be in it? I am switching from replit to pebblehost to host my python bot. What do I put in my requirements.txt? These are the imports that I have at the start of my bot. import asyncio import datetime import functools import io import json import os import random import re...
What is the requirements.txt, what should be in it?
I am switching from replit to pebblehost to host my python bot. What do I put in my requirements.txt? These are the imports that I have at the start of my bot. import asyncio import datetime import functools import io import json import os import random import re import string import urllib.parse import urllib.request ...
[ "You just write the Packages you‘ve installed in it.\nIf you write >= 1.17 the version has to be higher than 1.17\nLike:\nDiscord.py\nPillow\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "python", "replit" ]
stackoverflow_0074506852_discord_discord.py_python_replit.txt
Q: how to move files with the exact same name of the xml file to another directory in pyhon hi I have the following code that works just fine but I do not know how to move the matching name files to the same directory. for example I have 3 files with the same name (xml, jpeg, txt) when I move the xml file I want all ...
how to move files with the exact same name of the xml file to another directory in pyhon
hi I have the following code that works just fine but I do not know how to move the matching name files to the same directory. for example I have 3 files with the same name (xml, jpeg, txt) when I move the xml file I want all the files with the same name to move with it. I was looking in the forum and did not find anyt...
[ "You should do something like this:\nimport shutil\nfrom pathlib import Path\nfrom xml.etree import ElementTree as ET\n\n\n def contains_drone(path):\n tree = ET.parse(path.as_posix())\n root = tree.getroot()\n for obj in root.findall('object'):\n rank = obj.find('name').text\n if rank == 'dr...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074517895_python.txt
Q: How to compare two JSON objects with the same elements in a different order equal? How can I test whether two JSON objects are equal in python, disregarding the order of lists? For example ... JSON document a: { "errors": [ {"error": "invalid", "field": "email"}, {"error": "required", "field": ...
How to compare two JSON objects with the same elements in a different order equal?
How can I test whether two JSON objects are equal in python, disregarding the order of lists? For example ... JSON document a: { "errors": [ {"error": "invalid", "field": "email"}, {"error": "required", "field": "name"} ], "success": false } JSON document b: { "success": false, "err...
[ "If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a and b:\nimport json\n\na = json.loads(\"\"\"\n{\n \"errors\": [\n {\"error\": \"i...
[ 198, 72, 20, 8, 2, 2, 1, 0 ]
[ "With KnoDL, it can match data without mapping fields.\n" ]
[ -1 ]
[ "comparison", "django", "json", "python" ]
stackoverflow_0025851183_comparison_django_json_python.txt
Q: Is it possible to Implement a node of data structures in artificial Intelligence? I am working on a project which have to do image predictions using artifical intelligence, this is the image, you can see that the nodes are attached with each other, and first encoding the image and then hidden layer and then decod...
Is it possible to Implement a node of data structures in artificial Intelligence?
I am working on a project which have to do image predictions using artifical intelligence, this is the image, you can see that the nodes are attached with each other, and first encoding the image and then hidden layer and then decoding layer. My question is, the real implementation of autoencoder is very difficult to ...
[ "Yes, it's definitely possible to implement neural networks using common data structures. For modern Neural Networks, the data structure of choice at top level is not the linked list but the Graph - linked lists are the simplest Graph type (just linear). More complex networks (e.g. ResNet) have more than one path.\...
[ 1, 0 ]
[]
[]
[ "autoencoder", "c++", "neural_network", "python" ]
stackoverflow_0074517187_autoencoder_c++_neural_network_python.txt
Q: Chromedriver error when exiting an EC2 instance I'm trying to run a really simple script on an Ubuntu EC2 machine with Selenium. I put the next piece of code inside a loop since the script should run in the background forever: from selenium import webdriver def play(): chrome_options = webdriver.ChromeOptions() c...
Chromedriver error when exiting an EC2 instance
I'm trying to run a really simple script on an Ubuntu EC2 machine with Selenium. I put the next piece of code inside a loop since the script should run in the background forever: from selenium import webdriver def play(): chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--headless") chrome_optio...
[ "When you run a process from ssh, it is bound to your terminal session so as soon as you close the session, all subordinate processes are terminated.\nThere are number of options how to deal. Nearly all of them implies that you have some additional tools installed and might be specific for your particular OS.\nHere...
[ 1, 0 ]
[]
[]
[ "amazon_ec2", "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0074517809_amazon_ec2_python_selenium_selenium_chromedriver.txt
Q: Is there a way to get the url of popup js onclick dialogue using selenium? This is the website link which I am trying to scrape for data https://tis.nhai.gov.in/tollplazasataglance.aspx?language=en# There are links in 4th column in above site if clicked a popup window comes which has certain info along with href f...
Is there a way to get the url of popup js onclick dialogue using selenium?
This is the website link which I am trying to scrape for data https://tis.nhai.gov.in/tollplazasataglance.aspx?language=en# There are links in 4th column in above site if clicked a popup window comes which has certain info along with href for the next link when we click More Information tab.We get to such links https:/...
[ "Those pop-ups are the result of POST requests, where the payload is each location ID. Here is a way to get the locations IDs:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nf...
[ 0 ]
[]
[]
[ "python", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074517480_python_selenium_webdriver_web_scraping.txt
Q: Finding whether 2 indices are adjacent in circular list Say I have a circular list which would look like this to a human: How can I determine whether two indices are adjacent please? So far I have: def is_next_to(a, b): if a == b: return False return abs(a - b) == 1 assert is_next_to(1, ...
Finding whether 2 indices are adjacent in circular list
Say I have a circular list which would look like this to a human: How can I determine whether two indices are adjacent please? So far I have: def is_next_to(a, b): if a == b: return False return abs(a - b) == 1 assert is_next_to(1, 1) is False assert is_next_to(1, 2) is True assert is_next_to...
[ "In a circle of 6, the number 5 is a neighbor of 0, but in a circle of 8, the number 5 would not be a neighbor of 0. So you can only reliable determine this when you know the size of the circle: this should be an extra parameter to your function.\nOnce you have that, you can use this:\ndef is_next_to(n, a, b):\n ...
[ 1 ]
[]
[]
[ "circular_list", "modular_arithmetic", "python" ]
stackoverflow_0074517997_circular_list_modular_arithmetic_python.txt
Q: How to stop FastAPI app after raising an Exception? When handling exceptions in FastAPI, is there a way to stop the application after raising an HTTPException? An example of what I am trying to achieve: @api.route("/") def index(): try: do_something() except Exception as e: raise HTTPExcept...
How to stop FastAPI app after raising an Exception?
When handling exceptions in FastAPI, is there a way to stop the application after raising an HTTPException? An example of what I am trying to achieve: @api.route("/") def index(): try: do_something() except Exception as e: raise HTTPException(status_code=500, detail="Doing something failed!") ...
[ "As described in the comments earlier, you can follow a similar approach described here, as well as here and here. Once an exception is raised, you can use a custom handler, in which you can stop the currently running event loop, using a Background Task (see Starlette's documentation as well). It is not necessary t...
[ 1, 0 ]
[]
[]
[ "exception", "fastapi", "httpexception", "python" ]
stackoverflow_0074517267_exception_fastapi_httpexception_python.txt
Q: How to resolve django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS error? I am getting this error when I try to run python3 poppulate_first_app.py file (using Kali Linux and venv with django 3.1.7). Error... Traceback (most recent call last): File "/home/hadi/Documents/first_django_proj...
How to resolve django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS error?
I am getting this error when I try to run python3 poppulate_first_app.py file (using Kali Linux and venv with django 3.1.7). Error... Traceback (most recent call last): File "/home/hadi/Documents/first_django_project/poppulate_first_app.py", line 4, in <module> from first_app.models import * File "/home/hadi/Do...
[ "I just move the\nimport os\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_django_project.settings')\n\ndjango.setup()\n\nbefore the from first_app.models import *\n", "The error message is telling what to do. Run the following line in your terminal.\nexport DJANGO_SETTINGS_MODULE=poppulate_first_app.s...
[ 7, 0, 0 ]
[]
[]
[ "django", "python", "python_3.x" ]
stackoverflow_0066716375_django_python_python_3.x.txt
Q: selenium - wait when editbox is interactable (after button click) So I'm trying to learn about interacting with elements, after they are loaded (or enabled/interactable). In this case pressing button enables Edit box (after like 3-4secs), so you can write something. Here's link: http://the-internet.herokuapp.com/d...
selenium - wait when editbox is interactable (after button click)
So I'm trying to learn about interacting with elements, after they are loaded (or enabled/interactable). In this case pressing button enables Edit box (after like 3-4secs), so you can write something. Here's link: http://the-internet.herokuapp.com/dynamic_controls Here is how it looks now - works, but what if this edit...
[ "Use WebDriverWait() and wait for element_to_be_clickable(). Also use the following xpath option.\ndriver.get('http://the-internet.herokuapp.com/dynamic_controls')\nWebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH, \"//button[text()='Enable']\"))).click()\nWebDriverWait(driver,10).until(EC.eleme...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "webdriverwait", "xpath" ]
stackoverflow_0074518012_python_selenium_selenium_webdriver_webdriverwait_xpath.txt
Q: How can i validate django field with either of two validators? Here is the code, I want ip_address to satisfy either of validate_fqdn or validate_ipv4_address. import re def validate_fqdn(value): pattern = re.compile(r'^[a-zA-Z0-9-_]+\.?[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$') if not pattern.match(value): ...
How can i validate django field with either of two validators?
Here is the code, I want ip_address to satisfy either of validate_fqdn or validate_ipv4_address. import re def validate_fqdn(value): pattern = re.compile(r'^[a-zA-Z0-9-_]+\.?[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$') if not pattern.match(value): raise ValidationError('Provided fqdn is not valid') return...
[ "A new validator will do:\ndef validate_fqdn_or_ipv4_address(value):\n try:\n return validate_fqdn(value)\n except:\n return validate_ipv4_address(value)\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "orm", "python" ]
stackoverflow_0074518214_django_django_models_django_rest_framework_orm_python.txt
Q: Extracting a dictionary into a set of tuples Giving this dictionary: d = {'x': '999999999', 'y': ['888888888', '333333333'], 'z': '666666666', 'p': ['0000000', '11111111', '22222222'] } is it possible to make a set of tuples ? The output should be {( x, 999999999),(y,888888888, 333333333),...} I tried this : x_s...
Extracting a dictionary into a set of tuples
Giving this dictionary: d = {'x': '999999999', 'y': ['888888888', '333333333'], 'z': '666666666', 'p': ['0000000', '11111111', '22222222'] } is it possible to make a set of tuples ? The output should be {( x, 999999999),(y,888888888, 333333333),...} I tried this : x_set = {(k, v) for k, values in d.items() for v in v...
[ "x_set = set()\nfor k, v in d.items():\n items = [k]\n if(type(v) == list):\n items.extend(v)\n else:\n items.append(v)\n x_set.add(tuple(items))\n\nCheck if the dictionary element is a list or not so you know whether to iterate through the element or simply append it.\n", "You could con...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074518013_python.txt
Q: this code always go to else I tried to put if in if to force code to go to it but still go to else def add(x, y): return x + y def multiple(x, y): return x * y def subtrack(x, y): return x - y def divide(x, y): return x / y print('select your operation please') print('1-Add') print('2-Multiple') pr...
this code always go to else I tried to put if in if to force code to go to it but still go to else
def add(x, y): return x + y def multiple(x, y): return x * y def subtrack(x, y): return x - y def divide(x, y): return x / y print('select your operation please') print('1-Add') print('2-Multiple') print('3-subtrack') print('4-Divide') chose=int(input('enter your selection please: ')) num1=int(input('en...
[ "When doing:\nif chose == '1' \nYou're comparing to a char in python.\nIf you do\nif chose == 1\nyou're actually comparing to a int. Which is also what you enter in the inputs.\nremoving the ' around the right hand side of your if comparison operators, you will not keep getting pushed to the 'else' statement!\n", ...
[ 1, 1, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074518179_if_statement_python.txt
Q: pytest: ignore third party library warnings with -Werror I am running my unit tests as: pytest -Werror ... to ensure my code does not raise any warnings. However I am using third party libraries I cannot fix. These third party libraries are causing warnings which then will cause pytest -Werror to abort. In my cas...
pytest: ignore third party library warnings with -Werror
I am running my unit tests as: pytest -Werror ... to ensure my code does not raise any warnings. However I am using third party libraries I cannot fix. These third party libraries are causing warnings which then will cause pytest -Werror to abort. In my case the warning is DeprecationWarning so I cannot disable this w...
[ "You can add filterwarnings in pytest.ini\n[pytest]\nfilterwarnings = ignore::DeprecationWarning:THIRD_PARTY_NAME.*:\n\nor ignore everything from this library if you prefer\nfilterwarnings = ignore:::.*.THIRD_PARTY_NAME\n\nEdit\nInstead of using -Werror flag you can use pytest.ini to get the same results and ignore...
[ 3 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0074518081_pytest_python.txt
Q: Write into workbook with extension other than xlsx I use openpyxl to write into Excel with pandas and as long as I'm working on a file I'd like to use a different extension for it. The usual convetion is to appand .lock, but openpyxl denies to cooperate with it and complains that the extension is invalid. Is there...
Write into workbook with extension other than xlsx
I use openpyxl to write into Excel with pandas and as long as I'm working on a file I'd like to use a different extension for it. The usual convetion is to appand .lock, but openpyxl denies to cooperate with it and complains that the extension is invalid. Is there a way to disable this check or altenatively to make it ...
[ "I got it! This is how it goes:\nfrom pandas.io.excel import _OpenpyxlWriter\n\nclass ExcelWriterWithLock(_OpenpyxlWriter):\n supported_extensions = (\".xlsx\", \".xlsm\", \".lock\")\n\n" ]
[ 1 ]
[]
[]
[ "openpyxl", "pandas", "python", "python_3.x" ]
stackoverflow_0074517986_openpyxl_pandas_python_python_3.x.txt
Q: Brownie: CompilerError: File outside of allowed directories I'm trying to import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol" to my contract but i encountered this error. CompilerError: solc returned the following errors: contracts/Lottery.sol:4:1: ParserError: Source "C:/Users/Алексей/.bro...
Brownie: CompilerError: File outside of allowed directories
I'm trying to import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol" to my contract but i encountered this error. CompilerError: solc returned the following errors: contracts/Lottery.sol:4:1: ParserError: Source "C:/Users/Алексей/.brownie/packages/smartcontractkit/chainlink-brownie contracts@1.1.1/...
[ "it doesn't find aggregatorV3interface.sol\nHave you installed it?\ntry pip3 install @chainlink/contracts or npm install @chainlink/contracts\nif you already done it, check if it is in the right path\n", "A \"-\" is missing in the \"remappings:\"\nit should be:\n remappings:\n - '@chainlink=smartcontractkit/c...
[ 0, 0 ]
[]
[]
[ "brownie", "python", "smartcontracts", "solidity" ]
stackoverflow_0071018981_brownie_python_smartcontracts_solidity.txt
Q: Strange error when trying to get data from database in another file I was trying to get count of items in databases. Getting count with second database is working as planned, but the first one is giving me this error KeyError: <weakref at 0x000001E85C863330; to "Flask" at 0x000001E8397750D0> This program is a very...
Strange error when trying to get data from database in another file
I was trying to get count of items in databases. Getting count with second database is working as planned, but the first one is giving me this error KeyError: <weakref at 0x000001E85C863330; to "Flask" at 0x000001E8397750D0> This program is a very simplified, but removed elements are working fine(Get, Post, Delete meth...
[ "Flask uses app contexts to determine the current app, so queries for different apps should be run in their respective contexts.\nSomething like this ought to work:\nwhile True:\n with app.app_context():\n c = Value.query.count()\n with app2.app_context:\n c2 = Value2.query.count()\n print(c,...
[ 1 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python" ]
stackoverflow_0074512773_flask_flask_sqlalchemy_python.txt
Q: Error setting spatial dimensions in netCDF file I'm trying to convert a NetCDF file to raster using rioxarray in python. However, when I try to set lat and lon as spatial dimensions (they are variables in my original .nc file), I get an error message. How can I set lon and lat from variables to dimensions? Is ther...
Error setting spatial dimensions in netCDF file
I'm trying to convert a NetCDF file to raster using rioxarray in python. However, when I try to set lat and lon as spatial dimensions (they are variables in my original .nc file), I get an error message. How can I set lon and lat from variables to dimensions? Is there an alternative way to convert a NetCDF file to rast...
[ "This error is caused because when you read the file a type Dataset object is returned, so which does not contain any method called set_spatial_dimentions, what you could do is, convert it to an array type object using function to_array and then use the set_spatial_dimen method:\nnc_file = xr.open_dataset('......')...
[ 0 ]
[]
[]
[ "geospatial", "gis", "netcdf", "python", "raster" ]
stackoverflow_0074517289_geospatial_gis_netcdf_python_raster.txt
Q: Can I run multiple windows at the same time when using selenium I want to open several more windows when starting selenium, and each window can run independently: from lxml import etree import re from selenium import webdriver from selenium.webdriver.common.by import By # 选择器 from selenium.webdriver.common.keys i...
Can I run multiple windows at the same time when using selenium
I want to open several more windows when starting selenium, and each window can run independently: from lxml import etree import re from selenium import webdriver from selenium.webdriver.common.by import By # 选择器 from selenium.webdriver.common.keys import Keys # 按键 from selenium.webdriver.support.wait import WebDrive...
[ "Yes, you can use multiple windows in Selenium:\n\ndriver.get(2nd website) (opens a new window)\npresses key to switch tabs like ctrl + 1 for firefox\ndriver.quit() (closes only that tab but doesn't close the whole browser)\n\n" ]
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074518223_python_selenium.txt
Q: Extract part of XML files in a folder I have a folder with a number of Pascal Voc XML annotations of images. The annotations looks like the one in below <annotation> <folder>images</folder> <filename>Norway_000000.jpg</filename> <size> <width>3650</width> <height>2044</height> <...
Extract part of XML files in a folder
I have a folder with a number of Pascal Voc XML annotations of images. The annotations looks like the one in below <annotation> <folder>images</folder> <filename>Norway_000000.jpg</filename> <size> <width>3650</width> <height>2044</height> <depth/> </size> <segmented>0</segme...
[ "This is a way how you can extract each objects.\nYou can later on simply iterate inside them and search for certain name.\nThis is a part where I try to find all object elements:\nimport xml.etree.ElementTree as ET\n\nxml_file = ET.parse('YourXml.xml')\nxml_root = xml_file.getroot()\nxml_objects = list()\n\nfor i ...
[ 0 ]
[]
[]
[ "annotations", "object_detection", "python", "xml" ]
stackoverflow_0074518273_annotations_object_detection_python_xml.txt
Q: Number changes in all row of array I created a 4x5 2D array using python, and when I wanted to change a number inside it, it automatically changes the number in every row rows,cols = (4,5) arr = [[0]*cols]*rows print (arr) And this is how the output shows [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0,...
Number changes in all row of array
I created a 4x5 2D array using python, and when I wanted to change a number inside it, it automatically changes the number in every row rows,cols = (4,5) arr = [[0]*cols]*rows print (arr) And this is how the output shows [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] After I created the array, I...
[ "'Multiplying' the list copies the value references repeatedly - which is fine for primitives but not so much for lists, like you've seen. If you want different instances of the list, you could use list comprehension:\nrows, cols = (4, 5)\narr = [[0] * cols for _ in range(rows)]\narr[0][2] = 3\nprint(arr) # [[0, 0,...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074518428_python.txt
Q: Playwright on google colab : Attempt to free invalid pointer 0x29000020c5a0 I was trying to run playwright on google colab but getting an error Installed playwright and chromium !pip install playwright !playwright install To run run async stuff in a notebook import nest_asyncio nest_asyncio.apply() My Code impo...
Playwright on google colab : Attempt to free invalid pointer 0x29000020c5a0
I was trying to run playwright on google colab but getting an error Installed playwright and chromium !pip install playwright !playwright install To run run async stuff in a notebook import nest_asyncio nest_asyncio.apply() My Code import time import asyncio from playwright.async_api import async_playwright async d...
[ "When I try to run the chromium browser that downloaded by playwright using this command\n!/root/.cache/ms-playwright/chromium-1033/chrome-linux/chrome\n\nIt gives this error\nsrc/tcmalloc.cc:283] Attempt to free invalid pointer 0x18400020c5a0\n\nIt means the problem is somehow related to the browser downloaded by ...
[ 1 ]
[]
[]
[ "async_await", "exception", "playwright", "python", "python_asyncio" ]
stackoverflow_0073084960_async_await_exception_playwright_python_python_asyncio.txt
Q: Exclamation mark in python Hi I am curious about how you can describe a exclamation mark in python in a for loop. Input : 145 Output : It's a Strong Number. Explanation : Number = 145 145 = 1! + 4! + 5! 145 = 1 + 24 + 120 def exponent(n): res = 0 for i in str(n): a = int(i) res = res + (#exclamation mark) ...
Exclamation mark in python
Hi I am curious about how you can describe a exclamation mark in python in a for loop. Input : 145 Output : It's a Strong Number. Explanation : Number = 145 145 = 1! + 4! + 5! 145 = 1 + 24 + 120 def exponent(n): res = 0 for i in str(n): a = int(i) res = res + (#exclamation mark) return res I have tried the cod...
[ "You should definitely use the np.math.factorial(n) for this.\nAlso notice that your \"Output\" does not really follow correct syntax and the ' sign is causing it to be evaluated as a comment.\nYou could do it like this:\nOutput = \"It's a strong number.\"\n\nFor the main problem your trying to solve:\nimport numpy...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074518291_python.txt
Q: Pandas: calculate the morning averaged values or afternoon averaged values I got a dataframe like this: gpi_data[['sig','hourtime']] Out[28]: sig hourtime datetime_doy 2007-01-02 -8.963545 2007-01-02 09:20:11.249998 2007-01-03 -8.671357...
Pandas: calculate the morning averaged values or afternoon averaged values
I got a dataframe like this: gpi_data[['sig','hourtime']] Out[28]: sig hourtime datetime_doy 2007-01-02 -8.963545 2007-01-02 09:20:11.249998 2007-01-03 -8.671357 2007-01-03 10:39:31.874991 2007-01-03 -8.996480 2007-01-03 20:22:59.999006 20...
[ "Use cut for defined 10 and 22 column by some thresholds, here is used 12 and 23 hours.\nThen create MultiIndex by minimal and maximal years in MultiIndex.from_product, aggregate mean and add missing combinations by Series.reindex, last create hourtime column:\ndf['hourtime'] = pd.cut(df['hourtime'].dt.hour, bins=[...
[ 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "pandas_resample", "python" ]
stackoverflow_0074518311_dataframe_group_by_pandas_pandas_resample_python.txt
Q: How to convert a pandas DatetimeIndex to Array of Timestamps? I've been digging at this, but think I've confused myself on the various ways pandas can represent dates and times. I've imported a csv of data which includes columnds for year, month, day, etc, and then converted that to a datetime column and then set ...
How to convert a pandas DatetimeIndex to Array of Timestamps?
I've been digging at this, but think I've confused myself on the various ways pandas can represent dates and times. I've imported a csv of data which includes columnds for year, month, day, etc, and then converted that to a datetime column and then set it as an index - all good. # import and name columns epwNames = ['y...
[ "Two ways might work:\nget_julianDate(timestamp.to_list())\n# or use pd.Index.map directly:\ntimestamp.map(pd.Timestamp.to_julian_date)\n\n" ]
[ 0 ]
[]
[]
[ "datetimeindex", "pandas", "python", "timestamp" ]
stackoverflow_0074512162_datetimeindex_pandas_python_timestamp.txt
Q: fastest way to bruteforce a 6 character password i am trying to find a faster way to brute force a password with 6 characters in this format[abc123] always 3 lower case letters and 3 numbers after. so far i have tried a few different things but im pretty sure there are more effective methods to solving this. it al...
fastest way to bruteforce a 6 character password
i am trying to find a faster way to brute force a password with 6 characters in this format[abc123] always 3 lower case letters and 3 numbers after. so far i have tried a few different things but im pretty sure there are more effective methods to solving this. it also must include the hashing the password and comparing...
[ "try em all in order, not many faster ways\n" ]
[ 0 ]
[]
[]
[ "brute_force", "multithreading", "python" ]
stackoverflow_0074240833_brute_force_multithreading_python.txt
Q: matplotlib: change title and colorbar text and tick colors I wanted to know how to change the color of the ticks in the colorbar and how to change the font color of the title and colorbar in a figure. For example, things obviously are visible in temp.png but not in temp2.png: import matplotlib.pyplot as plt import...
matplotlib: change title and colorbar text and tick colors
I wanted to know how to change the color of the ticks in the colorbar and how to change the font color of the title and colorbar in a figure. For example, things obviously are visible in temp.png but not in temp2.png: import matplotlib.pyplot as plt import numpy as np from numpy.random import randn fig = plt.figure() ...
[ "Previous answer didnt give what I wanted. \nThis is how I did it:\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.random import randn\ndata = np.clip(randn(250,250),-1,1)\ndata = np.ma.masked_where(data > 0.5, data)\n\n\nfig, ax1 = plt.subplots(1,1)\n\nim = ax1.imshow(data, interpolation='nearest'...
[ 42, 40, 18, 6, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0009662995_matplotlib_python.txt
Q: How to build a SystemTray app for Windows? I usually work on a Linux system, but I have a situation where I need to write a client app that would run on windows as a service. Can someone help me or direct, on how to build a system tray app (for example like dropbox) for the windows environment, which gets started ...
How to build a SystemTray app for Windows?
I usually work on a Linux system, but I have a situation where I need to write a client app that would run on windows as a service. Can someone help me or direct, on how to build a system tray app (for example like dropbox) for the windows environment, which gets started on OS startup and the icon sits in the TaskBar a...
[ "You do this using the pywin32 (Python for Windows Extensions) module.\nExample Code for Python 2\nSimilar Question\nTo make it run at startup you could mess around with services but it's actually much easier to install a link to the exe in the users \"Startup Folder\".\nWindows 7 and Vista\nc:\\Users\\[username]\...
[ 41, 28, 28, 6, 0 ]
[]
[]
[ "appcelerator", "desktop_application", "macos", "python", "windows" ]
stackoverflow_0009494739_appcelerator_desktop_application_macos_python_windows.txt
Q: How to find center pixel value of bounding box in opencv python? I'm trying to find the pixel intensity at the center of bounding box TO achieve this I'm finding the center coordinates of bounding box and get the pixel intensity of that coordinate as shown below img_read= cv2.imread(r'image.png') cv2.rectangle(img...
How to find center pixel value of bounding box in opencv python?
I'm trying to find the pixel intensity at the center of bounding box TO achieve this I'm finding the center coordinates of bounding box and get the pixel intensity of that coordinate as shown below img_read= cv2.imread(r'image.png') cv2.rectangle(img_read,(xmin,ymin),(xmax,ymax),(0,0,255),3) center_x = int((xmin+xmax)/...
[ "#Read the image & get the dimensions \n img_read= cv2.imread(r\"C:\\Users\\Desktop\\test_center_px.tiff\")\n dimensions = img_read.shape\n h, w=dimensions[0], dimensions[1] \n\n#create the bounding box if necessary (not in mine) \n domain = cv2.rectangle(img_read,(0,0),(w,h),(255,0,0)...
[ 0 ]
[ "Try:\nimg_read[center_y,center_x] \n\n" ]
[ -3 ]
[ "cv2", "index_error", "numpy", "python" ]
stackoverflow_0074516088_cv2_index_error_numpy_python.txt
Q: How to redirect stdout and stderr to logger in Python I have a logger that has a RotatingFileHandler. I want to redirect all Stdout and Stderr to the logger. How to do so? A: Not enough rep to comment, but I wanted to add the version of this that worked for me in case others are in a similar situation. class Log...
How to redirect stdout and stderr to logger in Python
I have a logger that has a RotatingFileHandler. I want to redirect all Stdout and Stderr to the logger. How to do so?
[ "Not enough rep to comment, but I wanted to add the version of this that worked for me in case others are in a similar situation.\nclass LoggerWriter:\n def __init__(self, level):\n # self.level is really like using log.debug(message)\n # at least in my case\n self.level = level\n\n def w...
[ 54, 37, 18, 16, 14, 11, 5, 5, 1, 0 ]
[]
[]
[ "logging", "python", "python_3.x", "stdout" ]
stackoverflow_0019425736_logging_python_python_3.x_stdout.txt
Q: How to remove empty space in second alinea? I'm tring to remove the extra space and "rebtel.bootstrappedData" in the second alinea but for some reason it won't work. This is my output "welcome_offer_cuba.block_1_title":"SaveonrechargetoCuba","welcome_offer_cuba.block_1_cta":"Sendrecharge!","welcome_offer_cuba.bloc...
How to remove empty space in second alinea?
I'm tring to remove the extra space and "rebtel.bootstrappedData" in the second alinea but for some reason it won't work. This is my output "welcome_offer_cuba.block_1_title":"SaveonrechargetoCuba","welcome_offer_cuba.block_1_cta":"Sendrecharge!","welcome_offer_cuba.block_1_cta_prebook":"Pre-bookRecarga","welcome_offer...
[ "Original answer\nYou can change the definition of your script variable by :\nscript = soup.find_all(\"script\")[4].text.replace(\"\\t\", \"\")[38:]\n\nIt will remove all tabulations on your text and so the alineas.\nEdit after conversation in the comments\nYou can use the following code to extract the data in json...
[ 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0074518444_html_python.txt
Q: Pandas aggregation function: Merge text rows, but insert spaces between them? I managed to group rows in a dataframe, given one column (id). The problem is that one column consists of parts of sentences, and when I add them together, the spaces are missing. An example probably makes it easier to understand... My d...
Pandas aggregation function: Merge text rows, but insert spaces between them?
I managed to group rows in a dataframe, given one column (id). The problem is that one column consists of parts of sentences, and when I add them together, the spaces are missing. An example probably makes it easier to understand... My dataframe looks something like this: import pandas as pd #create dataFrame df = pd....
[ "If you need to put a space between the two phrases/rows, use str.join :\nujoin = lambda s: \" \".join(dict.fromkeys(s.astype(str)))\n​\nout= df.groupby([\"id\", \"date\"], as_index=False).agg(**{\"text\": (\"text\", ujoin)})[df.columns]\n\n# Output :\nprint(out.to_string())\n\n id ...
[ 0 ]
[]
[]
[ "aggregate", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074518570_aggregate_dataframe_group_by_pandas_python.txt
Q: Error when I try to extract info in a json I have this code: api_key = "_________" ciudad = input("put the city: ") url = "https://api.openweathermap.org/data/2.5/forecast?q=" +ciudad+ "&appid=" + api_key print(url) data = urllib.request.urlopen(url).read().decode() js = json.loads(data) And it is all ok...
Error when I try to extract info in a json
I have this code: api_key = "_________" ciudad = input("put the city: ") url = "https://api.openweathermap.org/data/2.5/forecast?q=" +ciudad+ "&appid=" + api_key print(url) data = urllib.request.urlopen(url).read().decode() js = json.loads(data) And it is all okey but I need the temp max and min and I try thi...
[ "js[\"list\"][0][\"main\"] is a dictionary:\n{'temp': 288.99, 'feels_like': 288.35, 'temp_min': 286.43, 'temp_max': 288.99, 'pressure': 1012, 'sea_level': 1012, 'grnd_level': 1007, 'humidity': 66, 'temp_kf': 2.56}\n\nfor res in js[\"list\"][0][\"main\"] iterates over its keys. So res is one of the keys in this dict...
[ 2 ]
[]
[]
[ "api", "python" ]
stackoverflow_0074518504_api_python.txt
Q: How can I get specific columns form txt file and save them to new file using python I have this txt file sentences.txt that contains texts below a01-000u-s00-00 0 ok 154 19 408 746 1661 89 A|MOVE|to|stop|Mr.|Gaitskell|from a01-000u-s00-01 0 ok 156 19 395 932 1850 105 nominating|any|more|Labour|life|Peers which co...
How can I get specific columns form txt file and save them to new file using python
I have this txt file sentences.txt that contains texts below a01-000u-s00-00 0 ok 154 19 408 746 1661 89 A|MOVE|to|stop|Mr.|Gaitskell|from a01-000u-s00-01 0 ok 156 19 395 932 1850 105 nominating|any|more|Labour|life|Peers which contains 10 columns I want to use the panda's data frame to extract only the file name (at ...
[ "IIUC, you just need pandas.read_csv to read your .txt and then select the two columns :\nTry this :\nimport pandas as pd\n\ndf= ( \n pd.read_csv(\"test.txt\", header=None, sep=r\"(\\d+)\\s(?=\\D)\", engine=\"python\",\n usecols=[0,4], names=[\"filename\", \"text\"])\n .assign(f...
[ 2 ]
[]
[]
[ "deep_learning", "nlp", "pandas", "python", "pytorch_lightning" ]
stackoverflow_0074518666_deep_learning_nlp_pandas_python_pytorch_lightning.txt
Q: Pandas cummax datetime when NaT values exist I have a column of "Purchase Dates". The column either contains NaT or an actual date. Date Last_Purchase Cummax_Purchase 2010-05-28 NaT NaT 2010-06-01 2010-06-01 2010-06-01 2010-06-02 2010-06-02 2010-06-02 2010-06-03 ...
Pandas cummax datetime when NaT values exist
I have a column of "Purchase Dates". The column either contains NaT or an actual date. Date Last_Purchase Cummax_Purchase 2010-05-28 NaT NaT 2010-06-01 2010-06-01 2010-06-01 2010-06-02 2010-06-02 2010-06-02 2010-06-03 NaT NaT 2010-06-04 NaT ...
[ "Unfortunately, you do not provide a fully runnable example (see https://stackoverflow.com/help/minimal-reproducible-example), which makes it a bit hard to answer. Here is an attempt nevertheless assuming that data is a pd.DataFrame:\nmask = ~data['Purchase Dates'].isna()\ndata.loc[mask, 'Cummax_Purchase'] = data.l...
[ 0 ]
[]
[]
[ "max", "python" ]
stackoverflow_0074517822_max_python.txt
Q: Python: calling a method inside a method I am trying to implement collisions with python, the collisions isn't the problem. I want to call a method inside another method using OOP, but it isn't recognised. Can you do this? How? def collision_test(self,rect,tiles,x,y): #CREATING A RECT FOR THE GAME MAP(TILES) ...
Python: calling a method inside a method
I am trying to implement collisions with python, the collisions isn't the problem. I want to call a method inside another method using OOP, but it isn't recognised. Can you do this? How? def collision_test(self,rect,tiles,x,y): #CREATING A RECT FOR THE GAME MAP(TILES) hit_list = [] for tile in tiles...
[ "You have to call self.collision_test(rect,tiles) instead of collision_test(self,rect,tiles).\nHowever, the signature aren't matching. Your collision_test expects x and y arguments too. That might causes troubles too.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074518695_python.txt
Q: recover initial allocation form final allocation and percentage changes let's say I have a sequence of n percentage changes for 2 assets and I know that at time n the allocation is A R = np.array([ [0.0, 0.0], [0.1, 0.02], [0.05, 0.01], [0.03, 0.03] ]) A = np.array([0.72345109 0.27654891]) What should I ...
recover initial allocation form final allocation and percentage changes
let's say I have a sequence of n percentage changes for 2 assets and I know that at time n the allocation is A R = np.array([ [0.0, 0.0], [0.1, 0.02], [0.05, 0.01], [0.03, 0.03] ]) A = np.array([0.72345109 0.27654891]) What should I do if I want to recover the initial allocation? ! Edited after @mozway respon...
[ "What you want to do is not highly clear.\nAssuming you have a initial vector I, and that you successively increase (for the first value) by [0, 0.1, 0.05, 0.03] (+0%, +10%, +5%, +3%), then I can be computed from A using:\nI = A/np.prod(R+1, axis=0)\n\nOutput: array([0.60812095, 0.26062326])\nAnd indeed:\nI * np.cu...
[ 0 ]
[]
[]
[ "numpy", "portfolio", "python" ]
stackoverflow_0074518703_numpy_portfolio_python.txt
Q: Reducing code for iterating over the same list with nested for loops but with different variables Is there any in build python iterating tool that reduces 3 row of for loops into one row? Here are the nested for loops that I want to reduce. some_list = ["AB", "CD", "EF", "GH"] for word_1 in some_list: for wor...
Reducing code for iterating over the same list with nested for loops but with different variables
Is there any in build python iterating tool that reduces 3 row of for loops into one row? Here are the nested for loops that I want to reduce. some_list = ["AB", "CD", "EF", "GH"] for word_1 in some_list: for word_2 in some_list: for word_3 in some_list: print(word_1, word_2, word_3) #Outputs a...
[ "Yes there is, it's product from itertools.\nfrom itertools import product\n\nsome_list = [\"AB\", \"CD\", \"EF\", \"GH\"]\n\nfor word_1 ,word_2, word_3 in product(some_list, repeat=3):\n print(word_1 , word_2, word_3)\n\nYou can also use tuple unpacking to make it even more concise, like this\nsome_list = [\"AB...
[ 1 ]
[]
[]
[ "for_loop", "iteration", "list", "python", "reducing" ]
stackoverflow_0074518808_for_loop_iteration_list_python_reducing.txt
Q: How to draw axis with arrows the same in Python I plot the function, and write code for plotting graph of this function: import seaborn as sns import matplotlib.pyplot as plt import numpy as np from matplotlib import ticker from matplotlib import rc rc('text', usetex=True) def fct(x): if -2 <= x < -1: ...
How to draw axis with arrows the same in Python
I plot the function, and write code for plotting graph of this function: import seaborn as sns import matplotlib.pyplot as plt import numpy as np from matplotlib import ticker from matplotlib import rc rc('text', usetex=True) def fct(x): if -2 <= x < -1: y = 1.0 elif -1 <= x < 0: y = -1.0 ...
[ "To plot the axis with arrows, you can use the function matplotlib.pyplot.arrow.\nI have shown you one possible implementation in the following function plot_arrows.\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import ticker\nfrom matplotlib import rc\n\nrc('text', us...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0071572533_matplotlib_python.txt
Q: Fast Pathfinder associative network algorithm (PFNET) in Python I've been trying to implement a "Fast Pathfinder" network pruning algorithm from https://doi.org/10.1016/j.ipm.2007.09.005 in Python/networkX, and have finally stumbled on something that is returning something that looks more or less right. I'm not qu...
Fast Pathfinder associative network algorithm (PFNET) in Python
I've been trying to implement a "Fast Pathfinder" network pruning algorithm from https://doi.org/10.1016/j.ipm.2007.09.005 in Python/networkX, and have finally stumbled on something that is returning something that looks more or less right. I'm not quite competent enough to test if the results are consistently (or ever...
[ "Disclaimer : I am one of the author of the optimisation papers (Fast PFNET, but there is also a faster version, MST-PFNET). Note that the MST-PFNET version can only be applied to a subset of the original PFNET algorithm, ie, can only work with q=n-1 and r=oo. Sorry for the delay of my answer, but I just have seen ...
[ 1, 1 ]
[]
[]
[ "algorithm", "networkx", "path_finding", "python" ]
stackoverflow_0070262806_algorithm_networkx_path_finding_python.txt
Q: How to make if else condition in python 2d array I have a 2d array with shape(3,6), then i want to create a condition to check a value of each array. my data arry is as follows : array([[ 1, 2, 3, 4, 5, 6], 7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]) if in an array there are numbers < 10 then the val...
How to make if else condition in python 2d array
I have a 2d array with shape(3,6), then i want to create a condition to check a value of each array. my data arry is as follows : array([[ 1, 2, 3, 4, 5, 6], 7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]) if in an array there are numbers < 10 then the value will be 0 the result I expected array([[ 0, 0, 0...
[ "If you want to modify the array in place, use boolean indexing:\nFCDataNew = np.array([[1,2,3,4,5,6],\n [7,8,9,10,11,12],\n [13,14,15,16,17,18],\n ])\n\nFCDataNew[FCDataNew<10] = 0\n\nFor a copy:\nout = np.where(FCDataNew<10, 0, FCDataNew)\n\nOutput:\na...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074518909_python.txt
Q: How can I use python conditionals to map columns in a dataframe with duplicates in them? I am trying to create a mapping where there are duplicates in certain columns in a dataframe. Here are two examples of dataframes I am working with: issue_status trading_state reason 100 'A0...
How can I use python conditionals to map columns in a dataframe with duplicates in them?
I am trying to create a mapping where there are duplicates in certain columns in a dataframe. Here are two examples of dataframes I am working with: issue_status trading_state reason 100 'A0' 100 None 'F' 400 Non...
[ "You can filter by 400 and None values for df1, create helper Series with range and mapping last and second last values, for first 100 and None values use Series.duplicated, last join both Series by Series.combine_first:\n#if None is string\n#m1 = df['trading_state'].eq('None')\nm1 = df['trading_state'].isna()\n\nm...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074518334_dataframe_pandas_python.txt
Q: Python: How to read and compare text files in 80 separate folders and merge them into one single pandas dataframe based on a condition? I have a folder(user) which contains 80 subfolders (1,2, 3,…, 80) and in each subfolder there are 2 text files (file1 and file2). file1 has 7 columns and file2 has 3 columns both ...
Python: How to read and compare text files in 80 separate folders and merge them into one single pandas dataframe based on a condition?
I have a folder(user) which contains 80 subfolders (1,2, 3,…, 80) and in each subfolder there are 2 text files (file1 and file2). file1 has 7 columns and file2 has 3 columns both without labels and are not in the same size. First column of file1 is time and the first and second columns of file2 are start_time and end_t...
[ "Duplicate of this post. Short answer : give the same name, say ts, to the timestamp column in both dataframes, then use merge method :\npd.merge(df1, df2, on='ts', how='outer')\n\nSee also the documentation of merge method.\n" ]
[ 1 ]
[]
[]
[ "binary_search", "file_io", "python", "subdirectory", "text_files" ]
stackoverflow_0074517776_binary_search_file_io_python_subdirectory_text_files.txt
Q: __pycache__ showing up in .git/refs/remotes/origin I had an issue where an Azure DevOps pipeline stopped working, and it turned out to be because there was a ref .git/refs/remotes/origin/feature/__pycache__/app.cpython-310.pyc which was "broken" (and clearly shouldn't have existed in the first place). So I logged ...
__pycache__ showing up in .git/refs/remotes/origin
I had an issue where an Azure DevOps pipeline stopped working, and it turned out to be because there was a ref .git/refs/remotes/origin/feature/__pycache__/app.cpython-310.pyc which was "broken" (and clearly shouldn't have existed in the first place). So I logged into the server, deleted that __pycache__ directory, an...
[ "\nI'm quite puzzled at how this came to be.\n\nGit stores names—branch names, tag names, remote-tracking names, and the like—in a key-value database where the full name, e.g., refs/heads/main, is the key, and the value is a hash ID. OK, but what does this have to do with anything? Well, the actual implementation ...
[ 1, 0 ]
[]
[]
[ "git", "python" ]
stackoverflow_0073556680_git_python.txt
Q: Why does mypy raise truthy-function error for assertion? I inherited a project from a dev who is no longer at the company. He wrote this test: from contextlib import nullcontext as does_not_raise def test_validation_raised_no_error_when_validation_succeeds(): # given given_df = DataFrame(data={"foo": [1, ...
Why does mypy raise truthy-function error for assertion?
I inherited a project from a dev who is no longer at the company. He wrote this test: from contextlib import nullcontext as does_not_raise def test_validation_raised_no_error_when_validation_succeeds(): # given given_df = DataFrame(data={"foo": [1, 2], "bar": ["a", "b"]}) given_schema = Schema( [ ...
[ "The test intends to check that the # given and # when parts of the test case run without raising any exception. The # then part is probably only there to satisfy the given-when-then pattern. As mypy says, the line doesn't do anything, it is functionally equivalent to assert bool(some_existing_function_name) which ...
[ 1 ]
[]
[]
[ "mypy", "python" ]
stackoverflow_0074518978_mypy_python.txt
Q: Getting output 4 instead of 1 Write a Python code to take one integer as input and store it in a variable namely, myNum. The output is a summation of digits in the tens and the hundreds places. Assume that you will never enter 1-digit or 2-digit integer as an input. (Hint, you have to use modulo and floor division...
Getting output 4 instead of 1
Write a Python code to take one integer as input and store it in a variable namely, myNum. The output is a summation of digits in the tens and the hundreds places. Assume that you will never enter 1-digit or 2-digit integer as an input. (Hint, you have to use modulo and floor division operators, and few variables.) Sam...
[ "One option if you only want to handle hundreds + tens:\ndef getSum(n):\n n = n//10 # first get rid of units\n n, total = divmod(n, 10) # get tens\n total += n%10 # get hundreds\n return total\n\ngetSum(1234)\n# 5\n\ngetSum(234)\n# 5\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074519042_python.txt
Q: Best way to find the months between two dates I have the need to be able to accurately find the months between two dates in python. I have a solution that works but its not very good (as in elegant) or fast. dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"), datetime.strptime(dateRanges[1], "%Y-%m-%d")] m...
Best way to find the months between two dates
I have the need to be able to accurately find the months between two dates in python. I have a solution that works but its not very good (as in elegant) or fast. dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"), datetime.strptime(dateRanges[1], "%Y-%m-%d")] months = [] tmpTime = dateRange[0] oneWeek = timed...
[ "Start by defining some test cases, then you will see that the function is very simple and needs no loops\nfrom datetime import datetime\n\ndef diff_month(d1, d2):\n return (d1.year - d2.year) * 12 + d1.month - d2.month\n\nassert diff_month(datetime(2010,10,1), datetime(2010,9,1)) == 1\nassert diff_month(datetim...
[ 256, 59, 48, 15, 15, 10, 9, 8, 6, 6, 5, 5, 4, 4, 4, 4, 3, 3, 2, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "You could use something like:\nimport datetime\ndays_in_month = 365.25 / 12 # represent the average of days in a month by year\nmonth_diff = lambda end_date, start_date, precision=0: round((end_date - start_date).days / days_in_month, precision)\nstart_date = datetime.date(1978, 12, 15)\nend_date = datetime.date(...
[ -1, -1 ]
[ "date_math", "datetime", "monthcalendar", "python" ]
stackoverflow_0004039879_date_math_datetime_monthcalendar_python.txt
Q: Leaving punctuations untouched during Caesar Cipher in python I read multiple related threads about how to solve the same problem, but I couldn't apply the solutions to my code. Also, the code is supposed receive a path to a text file which must contain text composed of only English letters and punctuation symbols...
Leaving punctuations untouched during Caesar Cipher in python
I read multiple related threads about how to solve the same problem, but I couldn't apply the solutions to my code. Also, the code is supposed receive a path to a text file which must contain text composed of only English letters and punctuation symbols and a destination file for encrypted data. Any suggestions? de...
[ "As mentioned by Alex P you can simple handle all punctuation separately with a if condition:\ndef caesarcipher(string, key): # Caesar Cipher\n encrypted_string = []\n new_key = key % 26\n for letter in string:\n if letter in ['!', '?', '.', ',', ' ']:\n encrypted_s...
[ 1, 1, 1 ]
[]
[]
[ "caesar_cipher", "python" ]
stackoverflow_0074518944_caesar_cipher_python.txt
Q: How to extract a word from a line? I've started python course not so long time ago. I have a file "input.txt" with lines (id, animal, gender, name, date of birth, date arrived to the zoo): 7910 leopard male Leo 04.06.2001 05.15.2010. 9315 cat male Hiha 01.04.2004 03.24.2012. 2226 leopard female Lia 07.28.2007 08...
How to extract a word from a line?
I've started python course not so long time ago. I have a file "input.txt" with lines (id, animal, gender, name, date of birth, date arrived to the zoo): 7910 leopard male Leo 04.06.2001 05.15.2010. 9315 cat male Hiha 01.04.2004 03.24.2012. 2226 leopard female Lia 07.28.2007 08.24.2019. I need to extract from each ...
[ "I think this can work:\n>>> file = open('input.txt', 'r')\n>>> {line.split()[1] for line in file.readlines()}\n{'leopard', 'cat'}\n\nWhile the second word of each line is the kind of that animal, accessing the 1 index of it can give you the kind.\n" ]
[ 1 ]
[]
[]
[ "python", "set" ]
stackoverflow_0074519147_python_set.txt
Q: I want 3 conditions to be met with pandas If I have this dataset: IDUSER SOURCE numofvisit Transaction 1 direct 2 yes 1 google 1 no 2 google 1 no 3 yahoo 1 no 3 direct 2 yes so I want to be able to say "50% of users that did a transaction are from google and 50% are from yahoo" but If I filter based on the ...
I want 3 conditions to be met with pandas
If I have this dataset: IDUSER SOURCE numofvisit Transaction 1 direct 2 yes 1 google 1 no 2 google 1 no 3 yahoo 1 no 3 direct 2 yes so I want to be able to say "50% of users that did a transaction are from google and 50% are from yahoo" but If I filter based on the row that actually got a transactio...
[ "IIUC, you can use:\n# identify users for which there is at least one transaction\nkeep = df['Transaction'].eq('yes').groupby(df['IDUSER']).any()\n\n# keep those users\nm1 = df['IDUSER'].isin(keep[keep].index)\n# remove the direct rows\nm2 = df['SOURCE'].ne('direct')\n\n# get the proportion of each source\ndf.loc[m...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074519184_pandas_python.txt
Q: How to create classes from existing tables using Flask-SQLaclhemy I know I need to use the MetaData object, in SQLAlchemy, but I am not sure how to use it with a class, db = SQLAlchemy(app) meta =db.Metadata() class orders(db.model): pass How do I pass the meta object to the class so that it will auto generate ...
How to create classes from existing tables using Flask-SQLaclhemy
I know I need to use the MetaData object, in SQLAlchemy, but I am not sure how to use it with a class, db = SQLAlchemy(app) meta =db.Metadata() class orders(db.model): pass How do I pass the meta object to the class so that it will auto generate table schema?
[ "Well you can use SQLAlchemy's autoload feature but I still haven't figured out how to use that from flask-sqlalchemy. Here's a tutorial if you want to read about it anyway: SQLAlchemy Connecting to pre-existing databases.\nThe best solution I found for the time being is to use sqlautocode to generate the SQLAlchem...
[ 7, 3, 0 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0029455436_flask_flask_sqlalchemy_python_sqlalchemy.txt
Q: Python Multiprocessing Locks This multiprocessing code works as expected. It creates 4 Python processes, and uses them to print the numbers 0 through 39, with a delay after each print. import multiprocessing import time def job(num): print num time.sleep(1) pool = multiprocessing.Pool(4) lst = range(40) for...
Python Multiprocessing Locks
This multiprocessing code works as expected. It creates 4 Python processes, and uses them to print the numbers 0 through 39, with a delay after each print. import multiprocessing import time def job(num): print num time.sleep(1) pool = multiprocessing.Pool(4) lst = range(40) for i in lst: pool.apply_async(job,...
[ "If you change pool.apply_async to pool.apply, you get this exception:\nTraceback (most recent call last):\n File \"p.py\", line 15, in <module>\n pool.apply(job, [l, i])\n File \"/usr/lib/python2.7/multiprocessing/pool.py\", line 244, in apply\n return self.apply_async(func, args, kwds).get()\n File \"/us...
[ 32, 16, 9, 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0028267972_multiprocessing_python.txt
Q: Completely delete + purge/expunge IMAP folders using Python imaplib I'm using this script to bulk delete empty IMAP folders: https://gitlab.com/puzzlement/delete-empty-imap-dirs #!/usr/bin/env python import getpass, imaplib, sys, argparse import parseNested IGNORE = set(["INBOX", "Postponed", "Sent", "Sent Ite...
Completely delete + purge/expunge IMAP folders using Python imaplib
I'm using this script to bulk delete empty IMAP folders: https://gitlab.com/puzzlement/delete-empty-imap-dirs #!/usr/bin/env python import getpass, imaplib, sys, argparse import parseNested IGNORE = set(["INBOX", "Postponed", "Sent", "Sent Items", "Trash", "Drafts", "MQEmail.INBOX", "MQEmail.Outbox", "MQEmail.Postp...
[ "In IMAP4Rev1, there are a couple reasons why a folder may continue to exist in some form after you DELETE it:\n\nIt has child folders (it will then appear as a \\NoSelect folder).\nIt is a required system folder\nOr it is still subscribed\n\nIn the latter case, the folder does not exist, but the server may continu...
[ 1 ]
[]
[]
[ "imap", "imaplib", "python" ]
stackoverflow_0074499286_imap_imaplib_python.txt
Q: Python - Add a line break after every single line I need to add a line break to every single line of text I have changed a CSV file to a text file, in that text file I need to add a line break at the end of every line/sentance I can only manage currently to add a single line break on the first line of text, I can ...
Python - Add a line break after every single line
I need to add a line break to every single line of text I have changed a CSV file to a text file, in that text file I need to add a line break at the end of every line/sentance I can only manage currently to add a single line break on the first line of text, I can not work out how to do it for subsequent lines An examp...
[ "Sounds like a job for regex:\ntext = \"\"\"Device_1 A 10.0.0.1\nDevice_2 A 10.0.0.2\nDevice_3 A 10.0.0.3\"\"\"\n\nimport re\nprint(re.sub(\"\\n\", \"\\n\\n\", text))\n\nBe warned: as a famous rapper once almost sang, I got 99 problems and then I tried to use regex on one of them and now I have 100.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074518821_python.txt
Q: Dynamic name to function What i want to do is to make a procedural variable name for a pygame draw function inside a for loop. But i just cant figure out how to do it. I tried to follow some guides that i saw about dynamic names but they only showcased making a variable name for ints and strings. I want to give al...
Dynamic name to function
What i want to do is to make a procedural variable name for a pygame draw function inside a for loop. But i just cant figure out how to do it. I tried to follow some guides that i saw about dynamic names but they only showcased making a variable name for ints and strings. I want to give all of rectangles their own name...
[ "You can make a dict which stores pointer to a function (if you do not add parentheses the variable acts as a function). If you add parentheses it only stores the result of the function -> return value.\nfuncs = dict({})\n\nfuncs[variable_name] = pygame.draw.rect\n\nafterwards you can call it as\nfuncs[variable_nam...
[ 0 ]
[]
[]
[ "procedural", "python" ]
stackoverflow_0074519246_procedural_python.txt
Q: How to group rows in a dataframe which are in a sequence? consider i have a data frame ID Column B 10 item 1 10 item 1 10 item 1 9 item 2 8 item 3 8 item 3 8 item 3 8 item 3 7 item 4 6 item 5 4 item 6 4 item 6 5 item 7 5 item 7 and i want to update a new column as result if the id column is in decr...
How to group rows in a dataframe which are in a sequence?
consider i have a data frame ID Column B 10 item 1 10 item 1 10 item 1 9 item 2 8 item 3 8 item 3 8 item 3 8 item 3 7 item 4 6 item 5 4 item 6 4 item 6 5 item 7 5 item 7 and i want to update a new column as result if the id column is in decreasing order i want something like this ...
[ "You can use diff to compare the successive values, if >-1, this means we start a new group, with help of cumsum:\ndf['result'] = df['ID'].diff().lt(-1).cumsum().add(1)\n\nOutput:\n ID Column B result\n0 10 item 1 1\n1 10 item 1 1\n2 10 item 1 1\n3 9 item 2 1\n4 8 i...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074519425_dataframe_pandas_python.txt
Q: Python list with type strings I have got a python list Year= [‘1997JAN’, ‘1997FEB’, ‘1997MAR’‘1997APR’………………………’2021SEP’’2021OCT’] I would like to extract only years from the above list but not the months How can I extract only years? Year = [1997,1997,1997,…………………2021,2021] A: If you have these dates: dates = ...
Python list with type strings
I have got a python list Year= [‘1997JAN’, ‘1997FEB’, ‘1997MAR’‘1997APR’………………………’2021SEP’’2021OCT’] I would like to extract only years from the above list but not the months How can I extract only years? Year = [1997,1997,1997,…………………2021,2021]
[ "If you have these dates:\ndates = ['1997JAN', '1997FEB', '1997MAR','1997APR', '2022NOV']\n\nJust use this to extract years from dates:\nyears = [int(x[:4]) for x in dates]\n\n", "You import and use the module re:\nimport re\n\nYear= ['1997JAN', '1997FEB', '1997MAR','1997APR','2021SEP','2021OCT']\n\nYears_only=[r...
[ 1, 0, 0 ]
[]
[]
[ "extract", "list", "numbers", "python", "string" ]
stackoverflow_0074519289_extract_list_numbers_python_string.txt
Q: How to convert a tuple in a list to a normal list? language: Python 3.7.0 mysql-connector-python==8.0.31 I'm working on a website and have just implemented a database. The response I'm getting from the database looks like this: [('indigo', 'admin')] How do I extract the two values from the tuple in a list and con...
How to convert a tuple in a list to a normal list?
language: Python 3.7.0 mysql-connector-python==8.0.31 I'm working on a website and have just implemented a database. The response I'm getting from the database looks like this: [('indigo', 'admin')] How do I extract the two values from the tuple in a list and convert it to a list only? Expected output: ["indigo", "adm...
[ "Use tuple unpacking\nresponse = [('indigo', 'admin')]\ndata = [*response[0]]\nprint(data)\n\nOutput: ['indigo', 'admin']\n", "For this very specific example you can just access the first element of the list a = [('indigo', 'admin')] via your_tuple = a[0] which returns your_tuple = ('indigo', 'admin'). Then this ...
[ 1, 1, 1, 1 ]
[]
[]
[ "database", "list", "mysql", "python", "tuples" ]
stackoverflow_0074519459_database_list_mysql_python_tuples.txt
Q: How can I return a list from a python function https://stackoverflow.com/a/8978435/1335492 ...shows how to call a python script from LibreOffice BASIC: (How can I call a Python macro in a cell formula in OpenOffice.Org Calc? ) Function invokeScriptFunc(..., args As Array, outIdxs As Array, outArgs As Array) ......
How can I return a list from a python function
https://stackoverflow.com/a/8978435/1335492 ...shows how to call a python script from LibreOffice BASIC: (How can I call a Python macro in a cell formula in OpenOffice.Org Calc? ) Function invokeScriptFunc(..., args As Array, outIdxs As Array, outArgs As Array) ... invokeScriptFunc = oScript.invoke(args, outIdxs,...
[ "The first parameter to .invoke is (all arguments).\nThe second parameter to .invoke is a list indicating which arguments are output arguments.\nThe third parameter to .invoke is (output arguments). Because in Java, method arguments are immutable. The Java interface returns values in (output arguments). The pyth...
[ 0, 0 ]
[]
[]
[ "libreoffice", "libreoffice_basic", "python" ]
stackoverflow_0074507680_libreoffice_libreoffice_basic_python.txt
Q: How can I run code that my Python program stored in a string? So, im trying to make a script that takes code from a pastebin post and runs it. But, for some reason it doesnt run the code. I dont know why. Could someone explain why this wont work so i can fix the issue? I tried: (dont mind the imports im gonna use ...
How can I run code that my Python program stored in a string?
So, im trying to make a script that takes code from a pastebin post and runs it. But, for some reason it doesnt run the code. I dont know why. Could someone explain why this wont work so i can fix the issue? I tried: (dont mind the imports im gonna use those for later) import os from json import loads, dumps from base...
[ "In your main function instead of just printing test\nuse exec(test)\ndef main():\n exec(test)\n\n" ]
[ 0 ]
[ "you are printing nothing and 'return test' wont be ran because it is outside of the try block\n" ]
[ -2 ]
[ "pastebin", "python", "urlopen" ]
stackoverflow_0074519531_pastebin_python_urlopen.txt
Q: Auto list fields from many-to-many model I've created a model of analysis types and then I created a table that groups several analyses into one group: class AnalysisType(models.Model): a_name = models.CharField(max_length=16,primary_key=True) a_measur = models.CharField(max_length=16) a_ref_min = mode...
Auto list fields from many-to-many model
I've created a model of analysis types and then I created a table that groups several analyses into one group: class AnalysisType(models.Model): a_name = models.CharField(max_length=16,primary_key=True) a_measur = models.CharField(max_length=16) a_ref_min = models.DecimalField(max_digits=5, decimal_places=2...
[ "Try this:\nAdmin panel with StackedInline\nfrom django.contrib import admin\nfrom .models import AnalysisType, PatientGroupAnalysis\n\n# Register your models here.\n\nclass PatientGroupAnalysisInline(admin.StackedInline):\n model = PatientGroupAnalysis\n\n\n@admin.register(AnalysisType)\nclass AnalysisTypeAdmin...
[ 1 ]
[]
[]
[ "django", "django_class_based_views", "python" ]
stackoverflow_0074519224_django_django_class_based_views_python.txt
Q: How to detect when an image needs perspective transform? I have a set of images in which I need to detect which of them needs a perspective transform. The images might be plain documents or photos taken with phone cameras with perspective and I need to perform perspective transform on those. How can I detect which...
How to detect when an image needs perspective transform?
I have a set of images in which I need to detect which of them needs a perspective transform. The images might be plain documents or photos taken with phone cameras with perspective and I need to perform perspective transform on those. How can I detect which need perspective transform in opencv? I can do perspective tr...
[ "This could be a possible approach:\n\nTake a reference picture (which does not require a perspective transform).\nDefine four points of interest- (x1,y1) (x2,y2) (x3,y3) (x4,y4) in your reference image. Consider these points as your destination points.\nNow in every other image that you want to check if a perspect...
[ 0 ]
[]
[]
[ "computer_vision", "opencv", "python" ]
stackoverflow_0074473938_computer_vision_opencv_python.txt
Q: FileNotFoundError: scipy.libs I'm trying to build an exe file using cx_Freeze. but when I run the resulting file I get an error: FileNotFoundError: ..\build\exe.win-amd64-3.8\lib\scipy.libs please tell me how to fix this problem? I run the following code: from cx_Freeze import setup, Executable build_exe_option...
FileNotFoundError: scipy.libs
I'm trying to build an exe file using cx_Freeze. but when I run the resulting file I get an error: FileNotFoundError: ..\build\exe.win-amd64-3.8\lib\scipy.libs please tell me how to fix this problem? I run the following code: from cx_Freeze import setup, Executable build_exe_options = {"packages": ["torch", 'tensorf...
[ "I had this exact problem, this is only a short term fix but if you search for 'scipy.libs' in your python install location 'site-packages' folder (or virtual environment if you're using one) and copy/paste it into the libs folder in your build it should solve the issue.\nI'll edit my answer if I come across the ro...
[ 1 ]
[]
[]
[ "cx_freeze", "exe", "python", "pytorch", "tensorflow" ]
stackoverflow_0074454338_cx_freeze_exe_python_pytorch_tensorflow.txt
Q: How can I change localhost IP of azure function code when running it locally? I am new to azure function. I want to run my azure function code locally (in an azure virtual machine). I'm running my code using this line in a linux VM terminal: . env/bin/activate && func host start It was successful with this output...
How can I change localhost IP of azure function code when running it locally?
I am new to azure function. I want to run my azure function code locally (in an azure virtual machine). I'm running my code using this line in a linux VM terminal: . env/bin/activate && func host start It was successful with this output. Azure Functions Core Tools Core Tools Version: 4.0.4785 Commit hash: N/A (...
[ "\nCreated the Azure Linux VM > Hosted Azure Functions Python Project (Http Trigger Function) on it.\nEnabled the Ports HTTP, HTTPS & RDP for checking using the browser by enabling the XRDP & installed the Firefox browser\n\nGlad that enabling the HTTPS flag is resolved by yourself.\nI'm able to get the Function Ap...
[ 0 ]
[]
[]
[ "azure", "azure_functions", "json", "linux", "python" ]
stackoverflow_0074360611_azure_azure_functions_json_linux_python.txt
Q: Python function repeating itself after if statement satisfied I am a beginner python user and I am stuck with a time-calculator program I am trying to create as part of an online certification. The program will calculate in an AM/PM format the time it is added from the initial time and the correct weekday. I have ...
Python function repeating itself after if statement satisfied
I am a beginner python user and I am stuck with a time-calculator program I am trying to create as part of an online certification. The program will calculate in an AM/PM format the time it is added from the initial time and the correct weekday. I have been having problems with this part as for reasons unknown to me th...
[ "When I ran your code removing result_printer and adjust_weekday calls as i don't have it in the code you sent, my output is\nstarting weekday:tuesday\nThis is the starting day of the week's index: 1\nThis is the day count 1\nThis is the new weekday wednesday\n\nI believe the problem comes from the other functions ...
[ 1, 1, 0 ]
[]
[]
[ "function", "if_statement", "python", "repeat" ]
stackoverflow_0074519394_function_if_statement_python_repeat.txt
Q: How to make an IF statement with conditions articulated with OR that stops as soon as the first True condition is reached? Let's take an example : I would like to check if the variable s is a string with length equal or less than 3. I tried the following : if (not isinstance(s,str)) | (len(s)>3) : print("The v...
How to make an IF statement with conditions articulated with OR that stops as soon as the first True condition is reached?
Let's take an example : I would like to check if the variable s is a string with length equal or less than 3. I tried the following : if (not isinstance(s,str)) | (len(s)>3) : print("The value of s is not correct : must be a string, with length equal or less than 3") But it is not correct as the code considers the...
[ "| is a bitwise or. use the keyword or instead.\nThe or will shortcircuit as you correctly mention in your question, so if s is not a string the second part will not evaluate, preventing the error of trying to apply len to a non-string object.\nif not isinstance(s, str) or len(s) > 3:\n print(\"The value of s is...
[ 2 ]
[]
[]
[ "conditional_statements", "if_statement", "python" ]
stackoverflow_0074519773_conditional_statements_if_statement_python.txt
Q: setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 When I try to install odoo-server, I got the following error: error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Could anyone help me to solve this issue? A: I encountered the s...
setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
When I try to install odoo-server, I got the following error: error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Could anyone help me to solve this issue?
[ "I encountered the same problem in college having installed Linux Mint for the main project of my final year, the third solution below worked for me.\nWhen encountering this error please note before the error it may say you are missing a package or header file — you should find those and install them and verify if ...
[ 558, 289, 197, 136, 86, 74, 39, 38, 27, 17, 17, 11, 9, 6, 5, 5, 4, 4, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ "After installing a lot of libraries, the one that worked for me! was swig:\nsudo apt-get install swig\n\nThe error arose when installing python's M2Crypto library.\n:)\n" ]
[ -1 ]
[ "gcc", "odoo", "pip", "python" ]
stackoverflow_0026053982_gcc_odoo_pip_python.txt
Q: Need to know if the same ID it's repeated but with a different DATE I'm trying to see if the same "ID" its repeated but with a different "DATE" value. I was thinking using a numpy.where, so I created the column "Count" to use something like this: df['FULFILL?'] = np.where((df['Count']>1) & (df['DATE']), 'YES', 'NO...
Need to know if the same ID it's repeated but with a different DATE
I'm trying to see if the same "ID" its repeated but with a different "DATE" value. I was thinking using a numpy.where, so I created the column "Count" to use something like this: df['FULFILL?'] = np.where((df['Count']>1) & (df['DATE']), 'YES', 'NO') But then I got stuck because I was not sure how to end the second con...
[ "Use GroupBy.transform with DataFrameGroupBy.nunique for test number of unique values per groups, first condition (df['Count']>1) is removed, because for single value per groups number of unique values is not greater like 1:\ndf['FULFILL?'] = np.where(df.groupby('ID')['DATE'].transform('nunique').gt(1), 'YES', 'NO'...
[ 0, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074519837_numpy_pandas_python.txt
Q: How to activate a specifically named virtualenv using pipenv? I created a specifically named virtualenv by setting PIPENV_CUSTOM_VENV_NAME before doing pipenv shell as outlined in this Github issue thread on "How to set the full name of the virtualenv created". I can confirm a virtualenv with the name given exists...
How to activate a specifically named virtualenv using pipenv?
I created a specifically named virtualenv by setting PIPENV_CUSTOM_VENV_NAME before doing pipenv shell as outlined in this Github issue thread on "How to set the full name of the virtualenv created". I can confirm a virtualenv with the name given exists in /Users/username/.local/share/virtualenvs/. Now, how do I activa...
[ "You will have to always export that PIPENV_CUSTOM_VENV_NAME environment variable.\nIt's the same as what that contributor did in that Github issue thread:\n\nexport PIPENV_CUSTOM_VENV_NAME=mycustomname \npipenv install \npipenv shell \netc. etc. \n\n\nThe export link sets that environment variable for all subse...
[ 1 ]
[]
[]
[ "pipenv", "python" ]
stackoverflow_0074390453_pipenv_python.txt
Q: Communication between a python server and a C# client (Unity) Below you can see both of the python server and the C# client scripts, the process is to send and receive packets. I connect to the server via cloud, using Putty to connect to it, the client is an application created using Unity and C# script. server.py...
Communication between a python server and a C# client (Unity)
Below you can see both of the python server and the C# client scripts, the process is to send and receive packets. I connect to the server via cloud, using Putty to connect to it, the client is an application created using Unity and C# script. server.py: import socket port = 80 s = socket.socket(socket.AF_INET, socket...
[ "I think the issue is your using block. It will Dispose the ws as soon as the Start method has finished (or actually as soon as the using block has reached the end).\nI think you'd rather do something like\nprivate WebSocket ws;\n\nprivate void Start ()\n{\n ws = new WebSocket(\"ws://arb-server.tunis-plm.com/\")...
[ 0, 0 ]
[]
[]
[ "c#", "python", "unity3d", "websocket" ]
stackoverflow_0067731405_c#_python_unity3d_websocket.txt
Q: Count matches of two elements on corresponding index positions in two arrays I have two arrays where one contains integers and the other words. It can look like this with arrays with 4 elements; arr1 = ['cat', 'cat', 'dog', 'cow'] arr2 = [0, 0, 1, 2] Further I have created indexing for all possible pairs: pairs =...
Count matches of two elements on corresponding index positions in two arrays
I have two arrays where one contains integers and the other words. It can look like this with arrays with 4 elements; arr1 = ['cat', 'cat', 'dog', 'cow'] arr2 = [0, 0, 1, 2] Further I have created indexing for all possible pairs: pairs = [] for i in range(4) : for j in range(i+1, 4) : pairs.append((i, j)) ...
[ "Compare the columns of each array's pairs, and then simply get where there are both a match (True) with a logical_and operation. You can get the count afterwards with count_nonzero() or sum().\nnp.count_nonzero(\n np.logical_and(\n arr1[pairs][:, 0] == arr1[pairs][:, 1],\n arr2[pairs][:, 0] == arr...
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074519680_arrays_numpy_python.txt
Q: Why does saving an text containing html inside of variable causing beautifulsoup4 causing unexpected behavior? I am using beautifulsoup to automate posting products on one of the shopping platforms, unfortunately their API is disabled currently, so the only option right now is to use beautifulsoup. How is program ...
Why does saving an text containing html inside of variable causing beautifulsoup4 causing unexpected behavior?
I am using beautifulsoup to automate posting products on one of the shopping platforms, unfortunately their API is disabled currently, so the only option right now is to use beautifulsoup. How is program expected to work? Program is expected to read .csv file (I provide the name of the file) and store the product data ...
[ "Seems like problem was that I have had whitespaces inside of the product description, so I have solved it like this:\nfinal_description = html_and_css\nfinal_description = final_description + csvproductDescription\nfinal_description = final_description + html_and_css2\nfinal_description = \" \".join(re.split(\"\\s...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x", "string" ]
stackoverflow_0074403416_beautifulsoup_python_python_3.x_string.txt
Q: Python can't open file in autostart When I start my program in autostart I get the Error [Errno13] Permission denied when it should open the file. When I then start the program manually it all works and my program opens the file. I autostart my program as registry key in Windows I use with open('save.macros', mode...
Python can't open file in autostart
When I start my program in autostart I get the Error [Errno13] Permission denied when it should open the file. When I then start the program manually it all works and my program opens the file. I autostart my program as registry key in Windows I use with open('save.macros', mode='rb') as f to open the file. The file is...
[ "The reason of occurs error on running your file in python,\n\nFile path is not exact\nwrong File's extension\ndifference for windows and linux path slash (windows => \\ , linux => /)\nor save.macros file is using in another process\n\nand make your you placed that save.macros file in same place with your python co...
[ 0 ]
[]
[]
[ "python", "registry" ]
stackoverflow_0074519856_python_registry.txt
Q: How can I update an existing dataframe to add values, without overwriting other existing values in the same column? I have an existing dataframe with two columns as follows: reason market_state 0 NaN UNSCHEDULED_AUCTION 1 NaN None 2 NaN CLOSE...
How can I update an existing dataframe to add values, without overwriting other existing values in the same column?
I have an existing dataframe with two columns as follows: reason market_state 0 NaN UNSCHEDULED_AUCTION 1 NaN None 2 NaN CLOSED 3 NaN CONTINUOUS_TRADING 4 NaN None 5 NaN UNSCHEDULED_AUCTION 6 Na...
[ "Join values to one dictionary and add Series.fillna by same column market_state:\nd = {'F': 'OPENING_AUCTION','SL': 'CLOSING_AUCTION', 'L': 'CLOSED'}\nmarket_info_df['market_state'] = (market_info_df['reason'].map(d)\n .fillna(market_info_df['market_state']))\nprint (mar...
[ 2, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074519937_dataframe_pandas_python.txt
Q: check if a txt file exist in a specific directory or not? I am trying to find out if a txt file with 'newfile' name exists in a specified directory or not, if not create a new txt file import os.path if (os.path.exists("newfile.txt") == False): open("count.txt", "w") but it does not work since I cannot access...
check if a txt file exist in a specific directory or not?
I am trying to find out if a txt file with 'newfile' name exists in a specified directory or not, if not create a new txt file import os.path if (os.path.exists("newfile.txt") == False): open("count.txt", "w") but it does not work since I cannot access the current or specified director with this code.
[ "import inspect\nimport os\n\nmodule_path = inspect.getfile(inspect.currentframe())\nmodule_dir = os.path.realpath(os.path.dirname(module_path))\nos.chdir(module_dir) # set working directory to where file is\n\nif not os.path.exists(\"C:\\\\absolute\\\\directory\\\\newfile.txt\"):\n open(\"count.txt\", \"w\")\n\...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074519810_python.txt
Q: Write a filter Factory populated at import time in Python using metaclasses I want a simple way to implement new filters in a module. They would eventually be automatically recognized by the library at import. For example, if I want the list of all filters I do: >>> FilterFactory.available_filters { 'upper': ...
Write a filter Factory populated at import time in Python using metaclasses
I want a simple way to implement new filters in a module. They would eventually be automatically recognized by the library at import. For example, if I want the list of all filters I do: >>> FilterFactory.available_filters { 'upper': __main__.FilterUpper, 'lower': __main__.FilterLower, 'trim': __main__.Fil...
[ "TL;DR:\nThe idea is good - I don't see the problem of \"can't forward reference classes\" as a real one,a s a filter class will have to import BaseFilter anyway, even if it is in a different file, and therefore, it has to be made available early, or the program won't even run. (that is: you won't get a class decla...
[ 1 ]
[]
[]
[ "design_patterns", "factory", "metaclass", "oop", "python" ]
stackoverflow_0074467584_design_patterns_factory_metaclass_oop_python.txt
Q: Pyautogui not importing "No module named 'pyautogui' " import pyautogui print("hello") After running this I am presented with the following: C:\Users\Darkm\Anaconda3\envs\PythonChallenges\python.exe C:/Users/Darkm/PycharmProjects/PythonChallenges/Automation1.py Traceback (most recent call last): File "C:/Users...
Pyautogui not importing "No module named 'pyautogui' "
import pyautogui print("hello") After running this I am presented with the following: C:\Users\Darkm\Anaconda3\envs\PythonChallenges\python.exe C:/Users/Darkm/PycharmProjects/PythonChallenges/Automation1.py Traceback (most recent call last): File "C:/Users/Darkm/PycharmProjects/PythonChallenges/Automation1.py", lin...
[ "Why are you getting this error?\nBecause you are using PyCharm. \nIn PyCharm you don't need to install python packages from command prompt, in PyCharm you need to install python packages from PyCharm Project Interpreter.\nHere are some tips that can help you!\nStep 1: Go to PyCharm settings and go to this director...
[ 3, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "anaconda", "pyautogui", "python", "python_import" ]
stackoverflow_0058887481_anaconda_pyautogui_python_python_import.txt
Q: No module named 'cuda._lib'; 'cuda' is not a package After following the steps on cuda-python to install cuda-python with conda instruction, I try to from cuda import cuda, nvrtc as in the example in the pycharm python console, but it raises an error: Traceback (most recent call last): File "D:\Anaconda\envs\hi...
No module named 'cuda._lib'; 'cuda' is not a package
After following the steps on cuda-python to install cuda-python with conda instruction, I try to from cuda import cuda, nvrtc as in the example in the pycharm python console, but it raises an error: Traceback (most recent call last): File "D:\Anaconda\envs\hierot\lib\code.py", line 90, in runcode exec(code, self...
[ "Oh I finally solved this problem, by configuring interpreter path, which in the beginning I added site-packages/cuda because I was trying to debug another problem at that time, and thus the shadow of the name cuda. (The image below is after deleting the redundant path)\n\n" ]
[ 1 ]
[]
[]
[ "cuda", "pycharm", "python" ]
stackoverflow_0074515262_cuda_pycharm_python.txt
Q: Flask Pagination without SQLAlchemy Looking to paginate the data set without using SQLAlchemy. Am getting the data from the database using query. def data(): cursor.execute("""select * from table_data""") records = cursor.fetchall() return reneder_template('data.html') And am rendering this result in...
Flask Pagination without SQLAlchemy
Looking to paginate the data set without using SQLAlchemy. Am getting the data from the database using query. def data(): cursor.execute("""select * from table_data""") records = cursor.fetchall() return reneder_template('data.html') And am rendering this result in the @app.route method. Pagination can be...
[ "Below approach can be used to paginate in Flaks without using SQLAlchemy,\ndef data():\n\n page = request.args.get(get_page_parameter(), type=int, default=1)\n limit=20\n offset = page*limit - limit\n cursor = connection.cursor()\n cursor.execute(\"\"\"select * from user_listing\n ...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074520043_flask_python.txt
Q: Python: recursively move all files from folders and sub folders into a root folder Given a file tree with much dept like this: ├── movepy.py # the file I want use to move all other files └── testfodlerComp ├── asdas │   └── erwer.txt ├── asdasdas │   └── sdffg.txt └── asdasdasdasd ├── hoihoi.txt ...
Python: recursively move all files from folders and sub folders into a root folder
Given a file tree with much dept like this: ├── movepy.py # the file I want use to move all other files └── testfodlerComp ├── asdas │   └── erwer.txt ├── asdasdas │   └── sdffg.txt └── asdasdasdasd ├── hoihoi.txt ├── hoihej.txt └── asd ├── dfsdf.txt └── dsfsdfsd.txt How can I ...
[ "import os\nimport shutil\nfrom pathlib import Path\n\ncwd = Path(os.getcwd())\n\nto_remove = set()\nfor root, dirnames, files in os.walk(cwd):\n for d in dirnames:\n to_remove.add(root / Path(d))\n\n for f in files:\n p = root / Path(f)\n if p != cwd and p.parent != cwd:\n pri...
[ 1, 1 ]
[]
[]
[ "move", "python", "python_3.x" ]
stackoverflow_0074519777_move_python_python_3.x.txt
Q: Efficient way to calculate difference from pandas datetime columns based on days I have a dataframe with a few million rows where I want to calculate the difference on a daily basis between two columns which are in datetime format. There are stack overflow questions which answer this question computing the differe...
Efficient way to calculate difference from pandas datetime columns based on days
I have a dataframe with a few million rows where I want to calculate the difference on a daily basis between two columns which are in datetime format. There are stack overflow questions which answer this question computing the difference on a timestamp basis (see here Doing it on the timestamp basis felt quite fast: df...
[ "Use Series.dt.to_period, faster is Series.dt.normalize or Series.dt.floor :\n#300k rows\ndf = pd.concat([df] * 100000, ignore_index=True)\n\nIn [286]: %timeit (df[\"end_date\"].dt.date - df[\"start_date\"].dt.date).dt.days\n1.14 s ± 135 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nIn [287]: %timeit ...
[ 1 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074520051_datetime_pandas_python.txt
Q: ITK: Cannot find ITKConfig.cmake file in ITK-5.2.1? I've installed itk-5.2.1 with pip in an anaconda environment with Python 3.9. On the other hand, I'm trying to run CMake to build Greedy. In the Cmake console (i'm using linux) I'm asked about the directory where ITKConfig.cmake or itk-config.cmake is located. I ...
ITK: Cannot find ITKConfig.cmake file in ITK-5.2.1?
I've installed itk-5.2.1 with pip in an anaconda environment with Python 3.9. On the other hand, I'm trying to run CMake to build Greedy. In the Cmake console (i'm using linux) I'm asked about the directory where ITKConfig.cmake or itk-config.cmake is located. I have been searching in ITK binaries directory in the anac...
[ "It is usually in ...\\lib\\cmake\\ITK-5.2\\ITKConfig.cmake. One full path on my computer is M:\\a\\Seg3D-deb\\Externals\\Install\\ITK_external\\lib\\cmake\\ITK-5.3\\ITKConfig.cmake.\n" ]
[ 0 ]
[]
[]
[ "cmake", "itk", "python", "python_3.x" ]
stackoverflow_0074518440_cmake_itk_python_python_3.x.txt
Q: Time interval calculation between commits I have a dataframe that looks like this: commitdates api_spec_id/ 0 2021-04-07 84 1 2021-05-31 84 2 2021-06-21 84 3 2021-06-18 84 4 2020-12-06 124 commits commitDate 0 32 2021-04...
Time interval calculation between commits
I have a dataframe that looks like this: commitdates api_spec_id/ 0 2021-04-07 84 1 2021-05-31 84 2 2021-06-21 84 3 2021-06-18 84 4 2020-12-06 124 commits commitDate 0 32 2021-04-07 12:52:56 1 32 2...
[ "Use groupby.transform with min/max (or first/last if you really want the order, not values to matter)):\n# pre-requisite\ndf[['commitdates', 'commitDate']] = df[['commitdates', 'commitDate']].apply(pd.to_datetime)\n\ng = df.groupby('api_spec_id')['commitdates']\ndf['Age (in days)'] = g.transform('max').sub(g.trans...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074520045_pandas_python.txt
Q: basic question about python code on NLTK(sent(), list(s), for ~in~) I'm a python beginner. I know that it is very easy code but actually it is difficult to me. I'm sorry. I find somebody's python code on the internet about word2vec for embedding the word. The following code is that I'm confused. There are 2 thi...
basic question about python code on NLTK(sent(), list(s), for ~in~)
I'm a python beginner. I know that it is very easy code but actually it is difficult to me. I'm sorry. I find somebody's python code on the internet about word2vec for embedding the word. The following code is that I'm confused. There are 2 things I can't understand 1. why we have to use [ ] in line 2? 2. what is th...
[ "Answer of question no. 1\nI think, it return code in list. [Maybe]\nAnswer of question no. 2\nThe send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value\n" ]
[ 0 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0055646710_nltk_python.txt
Q: Best way to rotate (and translate) a set of points in python I have two sets of points (x,y) that I have plotted with matplotlib Just visually I can see that it seems there is some kind of rotation between those. I would like to rotate one set of points around a certain point (would like to try several points of r...
Best way to rotate (and translate) a set of points in python
I have two sets of points (x,y) that I have plotted with matplotlib Just visually I can see that it seems there is some kind of rotation between those. I would like to rotate one set of points around a certain point (would like to try several points of rotation) and plot them again. What would be the best way to rotate...
[ "Use numpy to store your points\nFor example, if you have a nx2 array, each line being a point, like this\nxy=np.array([[50, 60],\n [10, 30],\n [30, 10]])\n\nYou can plot them like this\nplt.scatter(xy[:,0], xy[:,1])\n\nAnd to rotate them, you need a rotation matrix\ndef rotateMatrix(a):\n ...
[ 1 ]
[]
[]
[ "graph", "math", "python", "rotation" ]
stackoverflow_0074519927_graph_math_python_rotation.txt
Q: SQLAlchemy raises an exception for unknown version while connecting to GaussDB (for openGauss) As the following code shows, we may choose an ORM (Object-Relational Mapping) module to connect to GaussDB (for openGauss). The most popular third-party library in Python I know is SQLAlchemy. But while I connect to the ...
SQLAlchemy raises an exception for unknown version while connecting to GaussDB (for openGauss)
As the following code shows, we may choose an ORM (Object-Relational Mapping) module to connect to GaussDB (for openGauss). The most popular third-party library in Python I know is SQLAlchemy. But while I connect to the openGauss through the following code, an exception for known version raises. from sqlalchemy.engine ...
[ "I solved the problem.\nSQLAlchemy has a version check. Hence, we can modify the function action before using SQLAlchemy.\n from sqlalchemy.dialects.postgresql.base import PGDialect\n PGDialect._get_server_version_info = lambda *args: (9, 2)\n\n" ]
[ 2 ]
[ "You may try the project opengauss-sqlalchemy at now.\nThe openGauss recently provides this project to support SQLAlchemy.\nOverride the inner method _get_server_version_info of PGDialect could solve the problem of connecting to openGauss, but some SQLs of openGauss are different from PostgreSQL. Besides, openGauss...
[ -1 ]
[ "postgresql", "python", "sqlalchemy" ]
stackoverflow_0070588587_postgresql_python_sqlalchemy.txt
Q: creating a partial-like object with dynamic arguments I'm trying to create a partial function but with dynamic arguments that are stored as class attributes and changed accordingly. Something like the following code: from functools import partial def foo(*args, msg): print(msg) class Bar: def __init__(se...
creating a partial-like object with dynamic arguments
I'm trying to create a partial function but with dynamic arguments that are stored as class attributes and changed accordingly. Something like the following code: from functools import partial def foo(*args, msg): print(msg) class Bar: def __init__(self, msg): self.msg = msg self.functions = d...
[ "You can use lambda instead of partial for deferred (or often referred to as \"lazy\") evaluation of the arguments, so that self.msg is not evaluated until the function is called:\nclass Bar:\n def __init__(self, msg):\n self.msg = msg\n self.functions = dict()\n self.functions['foo'] = lamb...
[ 3, 1, 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0052406813_python_python_3.x.txt
Q: How to search for flights using the Amadeus API and Python, by considering the originRadius and destinationRadius parameters? I am trying to get Amadeus API flight data by considering the originRadius and destinationRadius parameters. Can someone help me with that? How can I search for flights by considering these...
How to search for flights using the Amadeus API and Python, by considering the originRadius and destinationRadius parameters?
I am trying to get Amadeus API flight data by considering the originRadius and destinationRadius parameters. Can someone help me with that? How can I search for flights by considering these two parameters? Currently, I have implemented following code: def check_flights( self, originLocationCode, destinati...
[ "For that you will have to use the POST method of the Flight Offers Search API. I leave an example below that takes into consideration the originRadius. This parameter includes other possible locations around the point, located less than this distance in kilometers away with a max of 300km and it can not be combine...
[ 0 ]
[]
[]
[ "amadeus", "python" ]
stackoverflow_0074500894_amadeus_python.txt
Q: 3D geometry intersections in Python I have a genetic programming algorithm that evolves solutions for a drone trajectory (3D lines) through obstacles, which are no-fly zones in a city. In order to evaluate the fitness of the solutions I need to check if they intersect the no-fly areas (~200 evaluations per iterati...
3D geometry intersections in Python
I have a genetic programming algorithm that evolves solutions for a drone trajectory (3D lines) through obstacles, which are no-fly zones in a city. In order to evaluate the fitness of the solutions I need to check if they intersect the no-fly areas (~200 evaluations per iteration for thousands of iterations) example r...
[ "In one of your comments, you said:\n\nEven something that just checks line-segment vs triangle intersection should work\n\nSo what I could suggest is to use the Möller–Trumbore algorithm for fast, minimum storage ray-triangle intersection.\nI have developed a Python implementation that you can find here. As you ca...
[ 1 ]
[]
[]
[ "3d", "geometry", "mesh", "python" ]
stackoverflow_0074510900_3d_geometry_mesh_python.txt
Q: pandas case sensitive column names I have data which having duplicate column names some are different case and few are in same case. Pandas only renaming columns which are of same case while loading data to dataframe automatically. Is there is anyway to rename columns case insensitive. Input data: ----------------...
pandas case sensitive column names
I have data which having duplicate column names some are different case and few are in same case. Pandas only renaming columns which are of same case while loading data to dataframe automatically. Is there is anyway to rename columns case insensitive. Input data: ------------------------------------------- | id | Nam...
[]
[]
[ "You can use:\n# get lowercase name\ns = df.columns.str.lower()\n\n# group by identical names and count\nsuffix = df.groupby(s, axis=1).cumcount().add(1).astype(str)\n\n# de-duplicate \ndf.columns = np.where(s.duplicated(keep=False),\n df.columns+'.'+suffix,\n df.columns)\n...
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0074520195_pandas_python.txt
Q: Eucledian distance matrix between two matrices I have the following function that calculates the eucledian distance between all combinations of the vectors in Matrix A and Matrix B def distance_matrix(A,B): n=A.shape[1] m=B.shape[1] C=np.zeros((n,m)) for ai, a in enumerate(A.T): for bi, b...
Eucledian distance matrix between two matrices
I have the following function that calculates the eucledian distance between all combinations of the vectors in Matrix A and Matrix B def distance_matrix(A,B): n=A.shape[1] m=B.shape[1] C=np.zeros((n,m)) for ai, a in enumerate(A.T): for bi, b in enumerate(B.T): C[ai][bi]=np.linalg...
[ "You can use:\nnp.linalg.norm(A[:,:,None]-B[:,None,:],axis=0)\n\nor (totaly equivalent but without in-built function)\n((A[:,:,None]-B[:,None,:])**2).sum(axis=0)**0.5\n\nWe need a 5x4 final array so we extend our array this way:\nA[:,:,None] -> 2,5,1\n ↑ ↓ \nB[:,None,:] ...
[ 2, 1 ]
[]
[]
[ "euclidean_distance", "matrix", "numpy", "python", "scipy" ]
stackoverflow_0074520084_euclidean_distance_matrix_numpy_python_scipy.txt
Q: Tensorflow output image is black I am using below code to crop the image, saved image is all black. How to get the correct image. # Crop Image image_open = open(fullpath, 'rb') read_image = image_open.read() decode = tf.image.decode_jpeg(read_image) expand = tf.expand_dims(decode, 0) ...
Tensorflow output image is black
I am using below code to crop the image, saved image is all black. How to get the correct image. # Crop Image image_open = open(fullpath, 'rb') read_image = image_open.read() decode = tf.image.decode_jpeg(read_image) expand = tf.expand_dims(decode, 0) cropped_image = tf.image.crop_and_resi...
[ "it is because PLT is a convenient tool you need to make it correct format and dimensions when the shape of the matrix needs to compose a picture or you do need to specify the axis.\n\nSample: The screen needs to match of target dimension or separate work on channels.\n\nimport os\nfrom os.path import exists\n\nimp...
[ 0 ]
[]
[]
[ "deep_learning", "image_processing", "python", "tensorflow" ]
stackoverflow_0074519821_deep_learning_image_processing_python_tensorflow.txt