question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
64,233,121
2020-10-6
https://stackoverflow.com/questions/64233121/why-doesnt-pytest-load-conftest-py-when-running-only-a-subset-of-tests
Here is my API test directory layout: api_tests ├── conftest.py └── query └── me_test.py Contents of conftest.py: print("CONFTEST LOADED") Contents of me_test.py: """Tests the "me" query""" def test_me(): assert True If I simply run pytest, everything works: ================================================= test ses...
The conftest plugin will be registered in both invocations, the only difference being the registration stage. If in doubt, add the --traceconfig argument to list the registered plugins in order of their registration: $ pytest --traceconfig PLUGIN registered: <_pytest.config.PytestPluginManager object at 0x7f23033ff100>...
10
8
64,234,214
2020-10-6
https://stackoverflow.com/questions/64234214/how-to-generate-a-blob-signed-url-in-google-cloud-run
Under Google Cloud Run, you can select which service account your container is running. Using the default compute service account fails to generate a signed url. The work around listed here works on Google Cloud Compute -- if you allow all the scopes for the service account. There does not seem to be away to do that in...
Yes you can, but I had to deep dive to find how (jump to the end if you don't care about the details) If you go in the _signing.py file, line 623, you can see this if access_token and service_account_email: signature = _sign_message(string_to_sign, access_token, service_account_email) ... If you provide the access_tok...
26
27
64,227,384
2020-10-6
https://stackoverflow.com/questions/64227384/how-can-i-know-whether-a-tensorflow-tensor-is-in-cuda-or-cpu
How can I know whether tensorflow tensor is in cuda or cpu? Take this very simple example: import tensorflow as tf tf.debugging.set_log_device_placement(True) # Place tensors on the CPU with tf.device('/device:GPU:0'): a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6....
As of Tensorflow 2.3 you can use .device property of a Tensor: import tensorflow as tf a = tf.constant([1, 2, 3]) print(a.device) # /job:localhost/replica:0/task:0/device:CPU:0 More detailed explanation can be found here
8
7
64,234,757
2020-10-6
https://stackoverflow.com/questions/64234757/plotly-express-heatmap-cell-size
How can i change the size of cells in a plotly express heatmap? I would need bigger cells import plotly.express as px fig1 = px.imshow(df[col],color_continuous_scale='Greens') fig1.layout.yaxis.type = 'category' fig1.layout.xaxis.type = 'category' fig1.layout.yaxis.tickmode = 'linear' fig1.layout.xaxis.tickmode = 'line...
'px' may not make it square due to the color bar, so why not use 'go'? import plotly.graph_objects as go fig = go.Figure(data=go.Heatmap( z=[[1, 20, 30], [20, 1, 60], [30, 60, 1]])) fig.show() Set the graph size. fig.layout.height = 500 fig.layout.width = 500 Examples at px import plotly.express as px data=[[1, 25,...
9
7
64,229,717
2020-10-6
https://stackoverflow.com/questions/64229717/what-is-the-idea-behind-using-nn-identity-for-residual-learning
So, I've read about half the original ResNet paper, and am trying to figure out how to make my version for tabular data. I've read a few blog posts on how it works in PyTorch, and I see heavy use of nn.Identity(). Now, the paper also frequently uses the term identity mapping. However, it just refers to adding the input...
What is the idea behind using nn.Identity for residual learning? There is none (almost, see the end of the post), all nn.Identity does is forwarding the input given to it (basically no-op). As shown in PyTorch repo issue you linked in comment this idea was first rejected, later merged into PyTorch, due to other use (...
12
23
64,209,855
2020-10-5
https://stackoverflow.com/questions/64209855/cannot-see-pyc-files-in-pycharm
I am using PyCharm for a project and I need to access pyc files. Unfortunately, IDE seems not to show *.pyc files nor __pycache__, even in searches with double Shift+Shift. I cannot find settings or documentation about it. Do you have any idea on how can I show these files and folders in IDE?
The setting you are looking for is Settings... | Editor | File Types | Ignore Files and Folders. Remove *.pyc and __pycache__ from the list to see the files.
13
15
64,222,815
2020-10-6
https://stackoverflow.com/questions/64222815/flask-wtforms-validation-inputrequired-for-at-least-one-field
Is there a way to implement a validation in WTFforms that enforces the fact that at least one of the fields is required? For example, I have two StringFields and I want to make sure the user writes something in at least one of the fields before clicking on "submit". field1 = StringField('Field 1', validators=[???]) fie...
Override your form's validate method. For example: class CustomForm(FlaskForm): field1 = StringField('Field 1') field2 = StringField('Field 2') def validate(self, extra_validators=None): if super().validate(extra_validators): # your logic here e.g. if not (self.field1.data or self.field2.data): self.field1.errors.appen...
8
7
64,215,540
2020-10-5
https://stackoverflow.com/questions/64215540/how-to-do-model-solve-not-show-any-message-in-python-using-pulp
I'm doing a implementation using pulp in python in a code that runtime is very important. #Initialize model model = LpProblem('eUCB_Model', sense=LpMaximize) #Define decision variables y = LpVariable.dicts('tenant', [(i) for i in range(size)], lowBound=None, upBound=None, cat='Binary') #Define model model += lpSum([y[i...
I don't think showing the log is the performance issue. Anyways, as the documentation shows: https://coin-or.github.io/pulp/technical/solvers.html#pulp.apis.PULP_CBC_CMD You can just pass msg=False as argument by doing: model.solve(PULP_CBC_CMD(msg=False))
7
8
64,220,438
2020-10-6
https://stackoverflow.com/questions/64220438/groupby-based-on-a-multiple-logical-conditions-applied-to-a-different-columns-da
I have this dataframe: df = pd.DataFrame({'value':[1,2,3,4,2,42,12,21,21,424,34,12,42], 'type':['big','small','medium','big','big','big','big','medium','small','small','small','medium','small'], 'entity':['R','R','R','P','R','P','P','P','R','R','P','R','R']}) value type entity 0 1 big R 1 2 small R 2 3 medium R 3 4 big...
Create mask by your conditions - here for greater by Series.gt with not equal by Series.ne chained by & for bitwise AND and then use GroupBy.transform for count Trues by sum: mask = df['value'].gt(3) & df['type'].ne('medium') df['count'] = mask.groupby(df['entity']).transform('sum') Solution with helper column new: ma...
11
6
64,218,839
2020-10-6
https://stackoverflow.com/questions/64218839/removing-loops-with-numpy-einsum
I have a some nested loops (three total) where I'm trying to use numpy.einsum to speed up the calculations, but I'm struggling to get the notation correct. I managed to get rid of one loop, but I can't figure out the other two. Here's what I've got so far: import numpy as np import time def myfunc(r, q, f): nr = r.shap...
Your function seems to be equivalent to the following: # this is so called broadcasting s = np.sinc(q * r[...,None]/np.pi) np.einsum('iq,jq,ijq->q',f,f,s) Which took about 20 seconds on my system, with most of the time to allocate s. Let's test it for a small sample: np.random.seed(1) r = np.random.random(size=(10,10)...
8
6
64,214,769
2020-10-5
https://stackoverflow.com/questions/64214769/finding-multiple-substrings-in-a-string-without-iterating-over-it-multiple-times
I need to find if items from a list appear in a string, and then add the items to a different list. This code works: data =[] line = 'akhgvfalfhda.dhgfa.lidhfalihflaih**Thing1**aoufgyafkugafkjhafkjhflahfklh**Thing2**dlfkhalfhafli...' _legal = ['thing1', 'thing2', 'thing3', 'thing4',...] for i in _legal: if i in line: d...
One way I could think of to improve is: Get all unique lengths of the words in _legal Build a dictionary of words from line of those particular lengths using a sliding window technique. The complexity should be O( len(line)*num_of_unique_lengths ), this should be better than brute force. Now look for each thing in the...
9
4
64,207,149
2020-10-5
https://stackoverflow.com/questions/64207149/python-setuptools-package-directory-does-not-exist
I have a project with this setup.py file: import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="", version="0.0.1", author="", author_email="", description="", long_description=long_description, long_description_content_type="text/markdown", packages=setuptools.find_p...
find_packages() automatically generates package names. That is, in your case all it does is generate ['my_pkg']. It doesn't actually tell setup() where to find my_pkg, just that it should expect to find a package called my_pkg somewhere. You have to separately tell setup() where it should look for packages. Is this con...
15
20
64,206,070
2020-10-5
https://stackoverflow.com/questions/64206070/pytorch-runtimeerror-enforce-fail-at-inline-container-cc209-file-not-fou
Problem I'm trying to load a file using PyTorch, but the error states archive/data.pkl does not exist. Code import torch cachefile = 'cacheddata.pth' torch.load(cachefile) Output --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-4-...
Turned out the file was somehow corrupted. After generating it again it loaded without issue.
18
13
64,202,437
2020-10-5
https://stackoverflow.com/questions/64202437/airflow-got-an-unexpected-keyword-argument-conf
I'm learning Apache Airflow to implement it at my workplace, I stumbled on a problem, when trying to pass parameter to function like this (I followed the documentation) from airflow import DAG import pendulum from datetime import datetime, timedelta from airflow.operators.python_operator import PythonOperator args = { ...
You have set provide_context=True so PythonOperator will send the execute context to your python_callable. So a generic catch all keyword arguments, **kwargs fixes the issue. https://github.com/apache/airflow/blob/v1-10-stable/airflow/operators/python_operator.py#L108. If you are not going to use anything from the cont...
17
30
64,199,121
2020-10-4
https://stackoverflow.com/questions/64199121/missing-scope-error-dropbox-api-authentication
I'm trying to download a large Dropbox folder with a bunch of subfolders to an external harddrive using the scripts at: http://tilburgsciencehub.com/examples/dropbox/ import dropbox from get_dropbox import get_folders, get_files from dropbox.exceptions import ApiError, AuthError # read access token access_token = "sl.s...
The 'missing_scope' error indicates that while the app is permitted to use that scope, the particular access token you're using to make the API call does not have that scope granted. Adding a scope to your app via the App Console does not retroactively grant that scope to existing access tokens. That being the case, to...
10
34
64,199,814
2020-10-4
https://stackoverflow.com/questions/64199814/reverse-key-value-pairing-in-python-dictionary
I need a way to reverse my key values pairing. Let me illustrate my requirements. dict = {1: (a, b), 2: (c, d), 3: (e, f)} I want the above to be converted to the following: dict = {1: (e, f), 2: (c, d), 3: (a, b)}
You just need: new_dict = dict(zip(old_dict, reversed(old_dict.values()))) Note, prior to Python 3.8, where dict_values objects are not reversible, you will need something like: new_dict = dict(zip(old_dict, reversed(list(old_dict.values()))))
12
12
64,194,634
2020-10-4
https://stackoverflow.com/questions/64194634/why-pip-freeze-returns-some-gibberish-instead-of-package-version
Here is what I did: ❯ pip freeze aiohttp @ file:///Users/aiven/Library/Caches/pypoetry/artifacts/50/32/0b/b64b02b6cefa4c089d84ab9edf6f0d960ca26cfbe57fe0e693a00912da/aiohttp-3.6.2-py3-none-any.whl async-timeout @ file:///Users/aiven/Library/Caches/pypoetry/artifacts/0d/5d/3e/630122e534c1b25e36c3142597c4b0b2e9d3f2e0a9cea...
This seems to come from the changes to support PEP 610. In particular refer to the Freezing an environment section. The notion of what "freezing" entails has been expanded to include preserving direct url sources for packages that were installed with direct origins. Poetry, with 1.1.0 has introduced a new installer tha...
8
14
64,197,434
2020-10-4
https://stackoverflow.com/questions/64197434/replace-column-value-based-on-value-in-other-column
so far my dataframe looks like this: ID Area Stage 1 P X 2 Q X 3 P X 4 Q Y I would like to replace the area 'Q' with 'P' for every row where the Stage is equal to 'X'. So the result should look like: ID Area Stage 1 P X 2 P X 3 P X 4 Q Y I tried: data.query('Stage in ["X"]')['Area']=data.query('Stage in ["X"]')['Area...
You can use loc to specify where you want to replace, and pass the replaced series to the assignment: df.loc[df['Stage']=='X', 'Area'] = df['Area'].replace('Q','P') Output: ID Area Stage 0 1 P X 1 2 P X 2 3 P X 3 4 Q Y
8
3
64,196,443
2020-10-4
https://stackoverflow.com/questions/64196443/get-last-message-s-from-telegram-channel-with-python
I'm using the python-telegram-bot library to write a bot in Python that sends URLs into a channel where the bot is administrator. Now, I would like to have the bot reading, let's say, the last 5 messages (I don't really care about the number as I just need to read the message on the chat) and store them into a list in ...
That's not possible in Bots unfortunately. Here you can find all available methods (that python-telegram-bot invokes behind the scenes) and there's no such method available to fetch messages on demand. The closest you can get through the api is getChat (which would return the pinned_message in that chat). What you can ...
10
9
64,196,315
2020-10-4
https://stackoverflow.com/questions/64196315/json-dump-into-specific-folder
This seems like it should be simple enough, but haven't been able to find a working example of how to approach this. Simply put I am generating a JSON file based on a list that a script generates. What I would like to do, is use some variables to run the dump() function, and produce a json file into specific folders. B...
Python's pathlib is quite convenient to use for this task: import json from pathlib import Path data = ['steve','martin'] season = '2019-2020' Paths of the new directory and json file: base = Path('Best') jsonpath = base / (season + ".json") Create the directory if it does not exist and write json file: base.mkdir(ex...
10
7
64,189,176
2020-10-3
https://stackoverflow.com/questions/64189176/os-sched-getaffinity0-vs-os-cpu-count
So, I know the difference between the two methods in the title, but not the practical implications. From what I understand: If you use more NUM_WORKERS than are cores actually available, you face big performance drops because your OS constantly switches back and forth trying to keep things in parallel. Don't know how t...
If you had a tasks that were pure 100% CPU bound, i.e. did nothing but calculations, then clearly nothing would/could be gained by having a process pool size greater than the number of CPUs available on your computer. But what if there was a mix of I/O thrown in whereby a process would relinquish the CPU waiting for an...
15
6
64,195,153
2020-10-4
https://stackoverflow.com/questions/64195153/get-index-value-from-pandas-dataframe
I have a Pandas dataframe (countries) and need to get specific index value. (Say index 2 => I need Japan) I used iloc, but i got the data (7.542) return countries.iloc[2] 7.542
call the index directly return countries.index[2] but what you post here looks like a pandas dataframe instead of a series - if that's the case do countries['Country_Name'].iloc[2]
7
11
64,180,054
2020-10-3
https://stackoverflow.com/questions/64180054/importerror-cannot-import-name-command-from-celery-bin-base
When I run the command flower -A main --port=5555 Flower doesn't work, the error is: > ImportError: cannot import name 'Command' from 'celery.bin.base' Any ideas? Main is a Django Project
Flower is always lagging behind Celery, so if you use the latest Celery (they refactored the CLI) it will probably fail. Stick to 4.4.x until Flower catches up.
21
28
64,183,806
2020-10-3
https://stackoverflow.com/questions/64183806/extracting-the-exponent-from-scientific-notation
I have a bunch of numbers in scientific notation and I would like to find their exponent. For example: >>> find_exp(3.7e-13) 13 >>> find_exp(-7.2e-11) 11 Hence I only need their exponent ignoring everything else including the sign. I have looked for such a way in python but similar questions are only for formatting pu...
Common logarithm is what you need here, you can use log10 + floor: from math import log10, floor def find_exp(number) -> int: base10 = log10(abs(number)) return abs(floor(base10)) find_exp(3.7e-13) # 13 find_exp(-7.2e-11) # 11
10
14
64,182,077
2020-10-3
https://stackoverflow.com/questions/64182077/getting-name-of-a-variable-in-python
If I have local/global variable var of any type how do I get its name, i.e. string "var"? I.e. for some imaginary function or operator nameof() next code should work: var = 123 assert nameof(var) == "var" There's .__name__ property for getting name of a function or a type object that variable holds value of, but is th...
You can do this with the package python-varname: https://github.com/pwwang/python-varname First run pip install varname. Then see the code below: from varname import nameof var = 123 name = nameof(var) #name will be 'var'
16
24
64,180,609
2020-10-3
https://stackoverflow.com/questions/64180609/delete-both-row-and-column-in-numpy-array
Say I have an array like this: x = [1, 2, 3] [4, 5, 6] [7, 8, 9] And I want to delete both the ith row and column. So if i=1, I'd create (with 0-indexing): [1, 3] [7, 9] Is there an easy way of doing this with a one-liner? I know I can call np.delete() twice, but that seems a little unclean. It'd be exactly equivalen...
In [196]: x = np.arange(1,10).reshape(3,3) If you look at np.delete code, you'll see that it's python (not compiled) and takes different approaches depending on how the delete values are specified. One is to make a res array of right size, and copy two slices to it. Another is to make a boolean mask. For example: In [...
8
5
64,176,468
2020-10-2
https://stackoverflow.com/questions/64176468/how-to-create-a-subscriptable-mock-object
Suppose, I have a code snippet as foo = SomeClass() bar = foo[1:999].execute() To test this, I have tried something as foo_mock = Mock() foo_mock[1:999].execute() Unfortunately, this raised an exception, TypeError: 'Mock' object is not subscriptable So, How can I create a subscriptable Mock object?
Just use a MagicMock instead. >>> from unittest.mock import Mock, MagicMock >>> Mock()[1:999] TypeError: 'Mock' object is not subscriptable >>> MagicMock()[1:999] <MagicMock name='mock.__getitem__()' id='140737078563504'> It's so called "magic" because it supports __magic__ methods such as __getitem__.
25
46
64,169,867
2020-10-2
https://stackoverflow.com/questions/64169867/numpy-finding-interval-which-has-a-least-k-points
I have some points in the interval [0,20] I have a window of size window_size=3 that I can move inside the above interval. Therefore the beginning of the window - let's call start is constrained to [0,17]. Let's say we have some points below: points = [1.4,1.8, 11.3,11.8,12.3,13.2, 18.2,18.3,18.4,18.5] If we wanted a ...
After a bit of struggle I came up with this solution. First a bit of explanations, and order of thoughts: Ideally we would want to set a window size and slide it from the most left acceptable point until the most right acceptable point, and start counting when min_points are in the window, and finish count when min_po...
7
2
64,173,613
2020-10-2
https://stackoverflow.com/questions/64173613/where-is-python-interpreter-located-in-virtualenv
Where is python intrepreter located in virtual environment ? I am making a GUI project and I stuck while finding the python interpreter in my virtual environment.
Execute next code and it will print location of your python interpreter. import sys print(sys.executable)
7
19
64,171,665
2020-10-2
https://stackoverflow.com/questions/64171665/why-is-gunicorn-displaying-so-many-processes
I have a simple web app built with Django & running with Gunicorn with Nginx. When I open HTOP, I see there are so many processes & threads spawn -- for a single tutorial app that just displays a login form. See screenshot of HTOP below: Why are there so many of them open for such a simple app? Here is my configuratio...
That's because of gunicorn's design: Gunicorn is based on the pre-fork worker model. This means that there is a central master process that manages a set of worker processes. The master never knows anything about individual clients. All requests and responses are handled completely by worker processes. That means tha...
7
5
64,163,528
2020-10-1
https://stackoverflow.com/questions/64163528/ubuntu-command-pip-not-found-but-there-are-18-similar-ones
I am trying to install a toolkit, I'm on WSL using ubuntu - I downloaded ubuntu yesterday. Here is what the installation process looks like for this toolkit. On windows cmd it says I have python 3.7.9 but on ubuntu its saying I have python 3.8.2 git clone https://github.com... cd program pip install -e . or: pip insta...
Short answer: Try running python3 -m pip install -e . Some explanations: The different versions of Python are not surprising. WSL is, effectively, an ultra-lightweight virtual machine. Your Windows python installation is entirely independent of the WSL python installation. Python has two widely used major versions, Py...
16
23
64,160,594
2020-10-1
https://stackoverflow.com/questions/64160594/fastapi-enum-type-models-not-populated
Below is my fastAPI code from typing import Optional, Set from fastapi import FastAPI from pydantic import BaseModel, HttpUrl, Field from enum import Enum app = FastAPI() class Status(Enum): RECEIVED = 'RECEIVED' CREATED = 'CREATED' CREATE_ERROR = 'CREATE_ERROR' class Item(BaseModel): name: str description: Optional[st...
create the Status class by inheriting from both str and Enum class Status(str, Enum): RECEIVED = 'RECEIVED' CREATED = 'CREATED' CREATE_ERROR = 'CREATE_ERROR' References Working with Python enumerations--(FastAPI doc) [BUG] docs don't show nested enum attribute for body--(Issue #329)
20
49
64,159,770
2020-10-1
https://stackoverflow.com/questions/64159770/whats-the-difference-between-numpy-random-vs-numpy-random-generate
I've been trying to simulate some Monte Carlos simulations lately and came across numpy.random. Checking the documentation of the exponential generator I've noticed that that's a warning in the page, which tells that Generator.exponential should be used for new code. Althought that, numpy.random.exponential still wor...
The Generator referred to in the documentation is a class, introduced in NumPy 1.17: it's the core class responsible for adapting values from an underlying bit generator to generate samples from various distributions. numpy.random.exponential is part of the (now) legacy Mersenne-Twister-based random framework. You prob...
9
9
64,158,898
2020-10-1
https://stackoverflow.com/questions/64158898/what-does-keras-tokenizer-num-words-specify
Given this piece of code: from tensorflow.keras.preprocessing.text import Tokenizer sentences = [ 'i love my dog', 'I, love my cat', 'You love my dog!' ] tokenizer = Tokenizer(num_words = 1) tokenizer.fit_on_texts(sentences) word_index = tokenizer.word_index print(word_index) whether num_words=1 or num_words=100, I ge...
word_index it's simply a mapping of words to ids for the entire text corpus passed whatever the num_words is the difference is evident in the usage. for example, if we call texts_to_sequences sentences = [ 'i love my dog', 'I, love my cat', 'You love my dog!' ] tokenizer = Tokenizer(num_words = 1+1) tokenizer.fit_on_te...
10
13
64,151,774
2020-10-1
https://stackoverflow.com/questions/64151774/does-javascript-use-hashtables-for-map-and-set
I'm a Python developer, making my first steps in JavaScript. I started using Map and Set. They seem to have the same API as dict and set in Python, so I assumed they're a hashtable and I can count on O(1) lookup time. But then, out of curiosity, I tried to see what would happen if I were to do this in Chrome's console:...
Consider the following JS code: > m1 = new Map([['a', 1]]) Map { 'a' => 1 } > m2 = new Map() Map {} > m2.set(m1, 3) Map { Map { 'a' => 1 } => 3 } > m2.get(m1) 3 But note, it is hashing based on identity, i.e. ===, so... > m2.get(new Map([['a',1]])) undefined So really, how useful is this map? Note, this isn't differe...
12
8
64,149,878
2020-10-1
https://stackoverflow.com/questions/64149878/importerror-cannot-import-name-types-from-google-cloud-vision-though-i-have
I have installed google-cloud-vision library following the documentation. It is for some reason unable to import types from google.cloud.vision. It worked fine on my pc, now when I shared with my client, he had a problem with imports though he has the library installed via pip. Here's the line that throws error: from g...
It's probably because there's some version mismatch (or less likely there's other library(s) with the same name). Have your client use a virtual environment. This should resolve the issue. P.S. You'll have to provide him with a requirements.txt file (obtained from pip3 freeze) so that he can do a pip3 install -r requir...
12
5
64,148,371
2020-10-1
https://stackoverflow.com/questions/64148371/discord-bot-can-only-see-itself-and-no-other-users-in-guild
I have recently been following this tutorial to get myself started with Discord's API. Unfortunately, when I got the part about printing all the users in the guild I hit a wall. When I try to print all users' names it only prints the name of the bot and nothing else. For reference, there are six total users in the guil...
As of discord.py v1.5.0, you are required to use Intents for your bot, you can read more about them by clicking here In other words, you need to do the following changes in your code - import discord from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') inten...
12
10
64,145,131
2020-9-30
https://stackoverflow.com/questions/64145131/socket-bind-vs-socket-listen
I've learned how to write a python server, and figured out that I have a hole in my knowledge. Therefore, I would glad to know more about the differences between the commands bind(), listen() of the module called socket. In addition, when I use bind() with a specific port as a parameter, Is the particular port being in...
I found a tutorial which explains in detail: ... bind() is used to associate the socket with the server address. Calling listen() puts the socket into server mode, and accept() waits for an incoming connection. listen() is what differentiates a server socket from a client. Once bind() is called, the port is now rese...
7
10
64,141,383
2020-9-30
https://stackoverflow.com/questions/64141383/how-to-import-own-module-within-aws-lambda-function
I am trying to import my own module but I am getting error: Unable to import module 'lambda_function': attempted relative import with no known parent package lambda_function.py Own modulename.py
You import it as if you were to import any other Python module. In other words don't do this: from .name import * but do this: from name import show_name For example: The contents of name.py: def my_name(): print("Your name goes here.") Don't forget to Deploy your function after making changes.
8
13
64,139,881
2020-9-30
https://stackoverflow.com/questions/64139881/pandas-error-indexerror-iloc-cannot-enlarge-its-target-object
I want to replace the value of a dataframe cell using pandas. I'm using this line: submission.iloc[i, coli] = train2.iloc[i2, coli-1] I get the following error line: IndexError: iloc cannot enlarge its target object What is the reason for this?
I think this happens because either 'i' or 'coli' is out of bounds in submission. According to the documentation, you can Enlarge the dataframe with loc, meaning it would add the required row and column (in either axis) if you assign a value to a row/column that currently does not exist, but apparently iloc will not do...
27
34
64,138,572
2020-9-30
https://stackoverflow.com/questions/64138572/pyenv-global-interpreter-not-working-on-windows10
I have just installed pyenv following the installation guide pyenv-win, things goes smoothly, but i could not make the pyenv global python as the global interpreter I have rehashed after installation using pyenv rehash PS D:\> pyenv versions 3.5.1 3.6.2 3.7.7 * 3.8.2 (set by C:\Users\xxx\.pyenv\pyenv-win\version) resu...
In windows NT, the PATH variable is a combined result of the system and user variables: The Path is constructed from the system path, which can be viewed in the System Environment Variables field in the System dialog box. The User path is appended to the system path Shims PATH are defined in the user variables, so ma...
13
4
64,137,236
2020-9-30
https://stackoverflow.com/questions/64137236/algorithm-that-generates-all-contiguous-subarrays
Using the following input, [1, 2, 3, 4] I'm trying to get the following output [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]] As far I have made such an algorithm, but time complexity is not good. def find(height): num1 = 0 out = [] for i in range(len(height)): num2 = 1 for j in rang...
Contiguous sub-sequences The OP specified in comments that they were interested in contiguous sub-sequences. All that is needed to select a contiguous sub-sequence is to select a starting index i and an ending index j. Then we can simply return the slice l[i:j]. def contiguous_subsequences(l): return [l[i:j] for i in r...
7
6
64,132,044
2020-9-30
https://stackoverflow.com/questions/64132044/how-to-replace-none-in-the-list-with-previous-value
I want to replace the None in the list with the previous variables (for all the consecutive None). I did it with if and for (multiple lines). Is there any way to do this in a single line? i.e., List comprehension, Lambda and or map And my idea was using the list comprehension but I was not able to assign variables in a...
In Python 3.8 or higher you can do this using the assignment operator: def none_replace(ls): p = None return [p:=e if e is not None else p for e in ls]
13
12
64,109,483
2020-9-28
https://stackoverflow.com/questions/64109483/how-to-recognize-if-string-is-human-name
So I have some text data that's been messily parsed, and due to that I get names mixed in with the actual data. Is there any kind of package/library that helps identify whether a word is a name or not? (In this case, I would be assuming US/western/euro-centric names) Otherwise, what would be a good way to flag this? Ma...
import nltk from nltk.tag.stanford import NERTagger st = NERTagger('stanford-ner/all.3class.distsim.crf.ser.gz', 'stanford-ner/stanford-ner.jar') text = """YOUR TEXT GOES HERE""" for sent in nltk.sent_tokenize(text): tokens = nltk.tokenize.word_tokenize(sent) tags = st.tag(tokens) for tag in tags: if tag[1]=='PERSON': ...
7
6
64,090,762
2020-9-27
https://stackoverflow.com/questions/64090762/how-can-i-make-the-short-circuiting-of-pythons-any-and-all-functions-effect
Python's any and all built-in functions are supposed to short-circuit, like the logical operators or and and do. However, suppose we have a function definition like so: def func(s): print(s) return True and use it to build a list of values passed to any or all: >>> any([func('s'), func('t')]) 's' 't' True Since the l...
We can use a generator expression, passing the functions and their arguments separately and evaluating only in the generator like so: >>> any(func(arg) for arg in ('s', 't')) 's' True For different functions with different signatures, this could look like the following: any( f(*args) for f, args in [(func1, ('s',)), (...
20
31
64,101,194
2020-9-28
https://stackoverflow.com/questions/64101194/partial-fraction-decomposition-using-sympy-python
How do I find the constants A,B,C,D,K,S such that 1/(x**6+1) = (A*x+B)/(x**2+1) + (C*x+D)/(x**2-sqrt(3)*x+1) + (K*x+S)/(x**2+sqrt(3)*x+1) is true for every real x. I need some sympy code maybe, not sure. Or any other Python lib which could help here. I tried by hand but it's not easy at all: after 1 hour of calculating...
You can do this using apart in sympy but apart will look for a rational factorisation by default so you have to tell it to work in Q(sqrt(3)): In [37]: apart(1/(x**6+1)) Out[37]: 2 x - 2 1 - ─────────────── + ────────── ⎛ 4 2 ⎞ ⎛ 2 ⎞ 3⋅⎝x - x + 1⎠ 3⋅⎝x + 1⎠ In [36]: apart(1/(x**6+1), extension=sqrt(3)) Out[36]: √3⋅x - ...
9
5
64,070,050
2020-9-25
https://stackoverflow.com/questions/64070050/how-to-get-a-list-of-installed-windows-fonts-using-python
How do I get a list of all the font names that are on my computer's system?
This is just a matter of listing the files in Windows\fonts: import os print(os.listdir(r'C:\Windows\fonts')) The output is a list that starts with something that looks like this: ['arial.ttf', 'arialbd.ttf', 'arialbi.ttf', 'cambria.ttc', 'cambriab.ttf'
9
6
64,062,225
2020-9-25
https://stackoverflow.com/questions/64062225/load-markdown-file-on-a-jupyter-notebook-cell
I know about the existance of the %load markdown_file.md magic command but this will load the content of the file on the first run of the cell. If the file changes, the cell won't be updated. Does anyone know if it is possible to avoid this problem and load the content of the file each time the cell runs?
If you want to load a markdown every time a cell is run, you can do: from IPython.display import Markdown, display display(Markdown("markdown_file.md"))
12
18
64,127,075
2020-9-29
https://stackoverflow.com/questions/64127075/how-to-retrieve-partial-matches-from-a-list-of-strings
For approaches to retrieving partial matches in a numeric list, go to: How to return a subset of a list that matches a condition? Python: Find in list But if you're looking for how to retrieve partial matches for a list of strings, you'll find the best approaches concisely explained in the answer below. SO: Python...
startswith and in, return a Boolean. The in operator is a test of membership. This can be performed with a list-comprehension or filter. Using a list-comprehension, with in, is the fastest implementation tested. If case is not an issue, consider mapping all the words to lowercase. l = list(map(str.lower, l)). Teste...
31
50
64,063,732
2020-9-25
https://stackoverflow.com/questions/64063732/type-hint-for-return-return-none-and-no-return-at-all
Is there any difference in the return type hint amongst these three functions? def my_func1(): print("Hello World") return None def my_func2(): print("Hello World") return def my_func3(): print("Hello World") Should they all have -> None return type hint, since that's what they in fact return, explicitly or implicitly...
They all should have the -> None return type, since they all clearly return None. Note that there also exists the typing.NoReturn type for functions that actually never return anything, e.g. from typing import NoReturn def raise_err() -> NoReturn: raise AssertionError("oops an error") Other types of functions (pointed...
28
37
64,043,297
2020-9-24
https://stackoverflow.com/questions/64043297/how-can-i-listen-to-windows-10-notifications-in-python
My Python test script causes our product to raise Windows notifications ("Toasts"). How can my python script verify that the notifications are indeed raised? I see it's possible to make a notification listener in C# using Windows.UI.Notifications.Management.UserNotificationListener (ref), And I see I can make my own no...
You can use pywinrt to access the bindings in python. A basic example would look something like this: from winrt.windows.ui.notifications.management import UserNotificationListener, UserNotificationListenerAccessStatus from winrt.windows.ui.notifications import NotificationKinds, KnownNotificationBindings if not ApiInf...
9
3
64,053,068
2020-9-24
https://stackoverflow.com/questions/64053068/how-to-type-hint-a-functions-optional-return-parameter
How do I type hint an optional output parameter: def myfunc( x: float, return_y: bool = False ) -> float, Optional[float] : # !!! WRONG !!! # ... code here # # y and z are floats if return_y: return z, y return z --- edit This seem to work: -> Tuple[float, Union[None, float]] : but that is so ugly and seems to overw...
Since Python 3.10 and PEP 604 you now can use | instead of Union. The return type would be float | Tuple[float, float] The right type hint would be: from typing import Tuple, Union def myfunc(x: float, return_y: bool = False) -> Union[float, Tuple[float, float]]: z = 1.5 if return_y: y = 2.0 return z, y return z Howe...
8
7
64,097,426
2020-9-28
https://stackoverflow.com/questions/64097426/is-there-unstack-in-numpy
There is np.stack in NumPy, but is there an opposite np.unstack same as tf.unstack?
Coming across this late, here is a much simpler answer: def unstack(a, axis=0): return np.moveaxis(a, axis, 0) # return list(np.moveaxis(a, axis, 0)) As a bonus, the result is still a numpy array. The unwrapping happens if you just python-unwrap it: A, B, = unstack([[1, 2], [3, 4]], axis=1) assert list(A) == [1, 3] as...
10
12
64,084,033
2020-9-27
https://stackoverflow.com/questions/64084033/modern-2020-way-to-call-c-code-from-python
I am trying to call a C++ function from a Python script. I have seen different solutions on Stackoverflow from 2010-2015 but they are all using complicated packages and was hoping for something easier/newer and more sophisticated. The C++ function I am trying to call takes in a double variable and returns a double. dou...
Python has ctypes package which allows calling functions in DLLs or shared libraries. Compile your C++ project into a shared library (.so) on Linux, or DLL on Windows. Export the functions you wish to expose outside. C++ supports function overloading, to avoid ambiguity in the binary code, additional information is add...
21
31
64,092,280
2020-9-27
https://stackoverflow.com/questions/64092280/aws-lambda-python-multiple-files-application-cant-import-one-from-another
I have the following structure of my AWS lambda project: module app.py b.py app.py is my default aws lambda function with lambda_handler, it works fine. I decided to pull all the heavy calculations out of it to function calc of b.py. Then, I imported it to app.py: from module.b import calc Now, when I run it locally ...
This is how me resolve that problem. First your root folder need to seem like this: lambda_folder lambda_function.py // Or your main.py.... this file have the method lambda_handler Now... When I use multiple files... I always use a lib folder. Like this: lambda_folder lib lib1.py lib2.py lib3.py lambda_function.py IM...
16
23
64,095,094
2020-9-28
https://stackoverflow.com/questions/64095094/command-python-setup-py-egg-info-failed-with-error-code-1-in-tmp
I got the following error installing a dependency with pip: pip9.exceptions.InstallationError Command "python setup.py egg_info" failed with error code 1 in /tmp/tmpoons7qgkbuild/opencv-python/ Below is the result of running the command pipenv install opencv-python on a recent linux (5.4.0 x64) system. Locking [packa...
How to fix the pip9.exceptions.InstallationError Make sure the version of your pip and setuptools is sufficient for manylinux2014 wheels. A) System Install sudo python3 -m pip install -U pip sudo python3 -m pip install -U setuptools B) Virtual Env / Pipenv # Within the venv pip3 install -U pip pip3 install -U setuptoo...
48
89
64,080,277
2020-9-26
https://stackoverflow.com/questions/64080277/how-to-get-the-most-recent-message-of-a-channel-in-discord-py
Is there a way to get the most recent message of a specific channel using discord.py? I looked at the official docs and didn't find a way to.
I've now figured it out by myself: For a discord.Client class you just need these lines of code for the last message: (await self.get_channel(CHANNEL_ID).history(limit=1).flatten())[0] If you use a discord.ext.commands.Bot @thegamecracks' answer is correct.
9
12
64,046,773
2020-9-24
https://stackoverflow.com/questions/64046773/return-database-name-memory-or-mode-memory-in-database-name-typeerror
I am practicing Django but when I command python manage.py makemigration and python manage.py migrate then I got an error as show in the title. the full error is mentioned below: C:\Users\Manan\python projects\djangoandmongo\new_Socrai>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, c...
It seems like the setting DATABASES - NAME expects a string, not a Path object. In your settings try changing this line 'NAME': BASE_DIR / 'db.sqlite3', to 'NAME': str(BASE_DIR / 'db.sqlite3'), so that NAME is a string instead of a Path. The error comes from this line of code django/db/backends/sqlite3/creation.py#L...
12
30
64,118,680
2020-9-29
https://stackoverflow.com/questions/64118680/reload-flag-with-uvicorn-can-we-exclude-certain-code
Is it somehow possible to exclude certain part of the code when reloading the scrip with --reload flag? uvicorn main:app --reload Use case: I have a model which takes a lot of time loading so I was wondering if there is a way to ignore that line of code when reloading. Or is it just impossible?
Update Uvicorn now supports including/excluding certain directories/files to/from watchlist. --reload-include TEXT Set glob patterns to include while watching for files. Includes '*.py' by default, which can be overridden in reload-excludes. --reload-exclude TEXT Set glob patterns to exclude while watching for files. ...
19
23
64,099,259
2020-9-28
https://stackoverflow.com/questions/64099259/ansible-ansible-python-interpreter-error
I want to instal influxdb and configuration with ansible. File copy and influxdb configuration is ok But creating database and user create section is give a "ansible_python_interpreter" error. I searched this error and tried something but I can't solve this problem with myself This is my ansible hosts file [loadbalance...
There are 3 ways to solve this problem if you encounter it on your remote host: Set ansible_python_interpreter: /usr/bin/python3 variable for all hosts that have python3 installed by default Install Python 2 using Ansible’s raw module Symlink /usr/bin/python3 to /usr/bin/python using Ansible’s raw module. All 3 optio...
6
16
64,098,376
2020-9-28
https://stackoverflow.com/questions/64098376/getting-oserror-202-where-running-urequests-get-from-micropy
hi im having error with this code but it runs in python shell could any body help me from machine import Pin import time import network import urequests p0 = Pin(0,Pin.OUT) wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect('ssid', 'pass') response = urequests.get('http://jsonplaceholder.typicode.com/al...
Your issue (my guess) is that you begin to urequest.get() without connected to WiFi. Create function that do wifi connection and call it def do_connect(): import network wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): print('connecting to network...') wlan.connect('essid', 'password') w...
7
9
64,128,255
2020-9-29
https://stackoverflow.com/questions/64128255/pyjwt-wont-import-jwt-algorithms-modulenotfounderror-no-module-named-jwt-alg
For some reason, PyJTW doesn't seem to work on my virtualenv on Ubuntu 16.04, but it worked fine on my local Windows machine (inside a venv too). I'm clueless, I've tried different versions, copied the exact same versions as I had on my Windows machine, and yet I still couldn't get this to work. Installed packages: Pac...
I had the same issue. The error seems to be a conflict between the pyjwt and jwt modules (as mentioned by @vimalloc above). What worked for me was to run the following command (NOTE: I am using Python 3.6.10). pip3 install -U pyjwt
10
7
64,063,850
2020-9-25
https://stackoverflow.com/questions/64063850/azure-python-sdk-serviceprincipalcredentials-object-has-no-attribute-get-tok
So I have the following Python3 script to list all virtual machines. import os, json from azure.mgmt.compute import ComputeManagementClient from azure.mgmt.network import NetworkManagementClient from azure.mgmt.resource import ResourceManagementClient, SubscriptionClient from azure.common.credentials import ServicePrin...
The Azure libraries for Python are currently being updated to share common cloud patterns such as authentication protocols, logging, tracing, transport protocols, buffered responses, and retries. This would change the Authentication mechanism a bit as well. In the older version, ServicePrincipalCredentials in azure.com...
26
50
64,095,396
2020-9-28
https://stackoverflow.com/questions/64095396/detecting-collisions-between-polygons-and-rectangles-in-pygame
So I am trying to make an among us type game with pygame. I just started, so I don't have much of anything and am working on the map right now. However, one thing I'm struggling with is the collision logic. The map has an elongated octagon shape for now, but I think no matter the shape I will use something like a pygam...
Write a function collideLineLine that test if to line segments are intersecting. The algorithm to this function is explained in detail in the answer to the question pygame, detecting collision of a rotating rectangle: def collideLineLine(l1_p1, l1_p2, l2_p1, l2_p2): # normalized direction of the lines and start of the ...
6
8
64,118,474
2020-9-29
https://stackoverflow.com/questions/64118474/checking-dict-keys-to-ensure-a-required-key-always-exists-and-that-the-dict-has
I have a dict in python that follows this general format: {'field': ['$.name'], 'group': 'name', 'function': 'some_function'} I want to do some pre-check of the dict to ensure that 'field' always exists, and that no more keys exist beyond 'group' and 'function' which are both optional. I know I can do this by using a ...
As far as I'm concerned you want to check, that The set {'field'} is always contained in the set of your dict keys The set of your dict keys is always contained in the set {'field', 'group', 'function'} So just code it! required_fields = {'field'} allowed_fields = required_fields | {'group', 'function'} d = {'field':...
44
44
64,126,185
2020-9-29
https://stackoverflow.com/questions/64126185/openpyxl-cant-read-xlsx-file-but-if-i-save-the-file-it-opens
So, I tried to open an excel file with openpyxl with this line wb_bs = openpyxl.load_workbook(filename=filepath) And got this error: C:\Users\T-Gamer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\styles\stylesheet.py:214: UserWarning: Workbook contains no default style, apply openpyxl's default ...
The reason may be the security prevention of MS-Windows: Whenever you download an MS-Office file from an outer source (internet), MS-Windows inserts a flag in that file which marks the file to be opened in protected view only. That protection stays still until you enable editing and save the file with the security flag...
6
1
64,118,331
2020-9-29
https://stackoverflow.com/questions/64118331/attributeerror-module-keras-backend-has-no-attribute-common
I tried to execute some project. But I've got an attribute error. I checked my Tensorflow and Keras version. Name: tensorflow Version: 2.3.1 Name: Keras Version: 2.4.3 Summary: Deep Learning for humans python 3.8.2 The code is here. self.dim_ordering = K.common.image_dim_ordering() Error message: self.dim_ordering = ...
Yes. It is okay to use k.image_data_format() In Keras v2 the method has been renamed to image_data_format
7
9
64,039,737
2020-9-24
https://stackoverflow.com/questions/64039737/object-is-not-subscriptable-using-django-and-python
I am having this error TypeError: 'StudentSubjectGrade' object is not subscriptable of course the data filtered is exist in the database, and i am sure that the filter is correct. what should i do to correct this ? note: this is recycle question, please dont mind the comment below, def SummaryPeriod(request): period = ...
TypeError: 'StudentSubjectGrade' object is not subscriptable this means that student is not a dictionary, you cannot use student['key'] to get what you want. you should use student.sth instead.
18
33
64,127,278
2020-9-29
https://stackoverflow.com/questions/64127278/what-is-the-proper-way-to-specify-a-custom-template-path-for-jupyter-nbconvert-v
What is the proper way to specify a custom template path for nbconvert? Under nbonvert version 6, templates are now a directory with several files. Those templates can live in any number of locations depending on the platform. Raspbian: ['/home/pi/.local/share/jupyter/nbconvert/templates', '/usr/local/share/jupyter/nbc...
Issue #1428 on the Git Repo contains the basis for this solution. From scratch/recent upgrade from v5 to v6 do the following: Generate a current and up-to-date configuration file for V6 in ~/.jupyter $ jupyter nbconvert --generate-config Edit the configuration file ~/.jupyter/jupyter_nbconvert_config.py to add the ...
6
8
64,116,781
2020-9-29
https://stackoverflow.com/questions/64116781/how-do-i-automerge-dependabot-updates-config-version-2
Following "Dependabot is moving natively into GitHub!", I had to update my dependabot config files to use version 2 format. My .dependabot/config.yaml did look like: version: 1 update_configs: - package_manager: "python" directory: "/" update_schedule: "live" automerged_updates: - match: dependency_type: "all" update_t...
Here is one solution that doesn't require any additional marketplace installations (originally found here). Simply create a new GitHub workflow (e.g. .github/workflows/dependabotautomerge.yml) containing: name: "Dependabot Automerge - Action" on: pull_request: jobs: worker: runs-on: ubuntu-latest if: github.actor == 'd...
26
14
64,099,248
2020-9-28
https://stackoverflow.com/questions/64099248/pytesseract-improve-ocr-accuracy
I want to extract the text from an image in python. In order to do that, I have chosen pytesseract. When I tried extracting the text from the image, the results weren't satisfactory. I also went through this and implemented all the techniques listed down. Yet, it doesn't seem to perform well. Image: Code: import pytes...
I changed resize from 1.2 to 2 and removed all preprocessing. I got good results with psm 11 and psm 12 import pytesseract import cv2 import numpy as np img = cv2.imread('wavy.png') # img = cv2.resize(img, None, fx=1.2, fy=1.2, interpolation=cv2.INTER_CUBIC) img = cv2.resize(img, None, fx=2, fy=2) img = cv2.cvtColor(im...
7
9
64,111,015
2020-9-28
https://stackoverflow.com/questions/64111015/pip-install-psutil-is-throwing-error-unsupported-architecture-any-workarou
I want to install psutil on my macOS Catalina, for which I am doing pip install psutil, but it doesn't succeed. Instead I get multiple error messages being thrown from Xcode saying that the architecture is not supported. Has anyone faced similar issues? Here's the entire output: Collecting psutil Using cached psutil-5....
At the time of the error, I was using Python 3.8.2. This was fixed after upgrading to Python 3.8.5
9
5
64,115,084
2020-9-29
https://stackoverflow.com/questions/64115084/are-predictions-on-scikit-learn-models-thread-safe
Given some classifier (SVC/Forest/NN/whatever) is it safe to call .predict on the same instance concurrently from different threads? From a distant point of view, my guess is they do not mutate any internal state. But I did not find anything in the docs about it. Here is a minimal example showing what I mean: #!/usr/bi...
Check out this Q&A, the predict and predict_proba methods should be thread safe as they only call NumPy, they do not affect model itself in any case so answer to your question is yes. You can find some info as well in replies here. For example in naive bayes the code is following: def predict(self, X): """ Perform clas...
10
1
64,104,341
2020-9-28
https://stackoverflow.com/questions/64104341/how-to-get-the-most-frequent-row-in-table
How to get the most frequent row in a DataFrame? For example, if I have the following table: col_1 col_2 col_3 0 1 1 A 1 1 0 A 2 0 1 A 3 1 1 A 4 1 0 B 5 1 0 C Expected result: col_1 col_2 col_3 0 1 1 A EDIT: I need the most frequent row (as one unit) and not the most frequent column value that can be calculated wit...
In Pandas 1.1.0. is possible to use the method value_counts() to count unique rows in DataFrame: df.value_counts() Output: col_1 col_2 col_3 1 1 A 2 0 C 1 B 1 A 1 0 1 A 1 This method can be used to find the most frequent row: df.value_counts().head(1).index.to_frame(index=False) Output: col_1 col_2 col_3 0 1 1 A
15
2
64,035,952
2020-9-23
https://stackoverflow.com/questions/64035952/how-to-key-press-detection-on-a-linux-terminal-low-level-style-in-python
I just implemented a Linux command shell in python using only the os library's low level system calls, like fork() and so on. I was wondering how I can implement a key listener that will listen for key (UP|DOWN) to scroll through the history of my shell. I want do do this without using any fancy libraries, but I am als...
By default the standard input is buffered and uses canonical mode. This allows you to edit your input. When you press the enter key, the input can be read by Python. If you want a lower level access to the input you can use tty.setraw() on the standard input file descriptor. This allows you to read one character at a t...
7
9
64,127,158
2020-9-29
https://stackoverflow.com/questions/64127158/how-to-update-a-pandas-dataframe-from-multiple-api-calls
I need to do a python script to Read a csv file with the columns (person_id, name, flag). The file has 3000 rows. Based on the person_id from the csv file, I need to call a URL passing the person_id to do a GET http://api.myendpoint.intranet/get-data/1234 The URL will return some information of the person_id, like exa...
Code Explanation Create dataframe, df, with pd.read_csv. It is expected that all of the values in 'person_id', are unique. Use .apply on 'person_id', to call prepare_data. prepare_data expects 'person_id' to be a str or int, as indicated by the type annotation, Union[int, str] Call the API, which will return a d...
6
4
64,123,551
2020-9-29
https://stackoverflow.com/questions/64123551/what-is-the-safest-way-to-queue-multiple-threads-originating-in-a-loop
My script loops through each line of an input file and performs some actions using the string in each line. Since the tasks performed on each line are independent of each other, I decided to separate the task into threads so that the script doesn't have to wait for the task to complete to continue with the loop. The co...
Queues are one way to do it. The way to use them is to put function parameters on a queue, and use threads to get them and do the processing. The queue size doesn't matter too much in this case because reading the next line is fast. In another case, a more optimized solution would be to set the queue size to at least t...
8
5
64,089,691
2020-9-27
https://stackoverflow.com/questions/64089691/feather-format-for-long-term-storage-since-the-release-of-apache-arrow-1-0-1
As I'm given to understand due to the search of issues in the Feather Github, as well as questions in stackoverflow such as What are the differences between feather and parquet?, the Feather format was not recommended as long term storage due to Apache Arrow versions being 0.x.x, and considered volatile due to the cont...
Feather files (using the v2 -- default -- format version, not the v1 "legacy" version) are stable starting with Apache Arrow 1.0.0.
26
30
64,089,854
2020-9-27
https://stackoverflow.com/questions/64089854/pytorch-detection-of-cuda
Which is the command to see the "correct" CUDA Version that pytorch in conda env is seeing? This, is a similar question, but doesn't get me far. nvidia-smi says I have cuda version 10.1 conda list tells me cudatoolkit version is 10.2.89 torch.cuda.is_available() shows FALSE, so it sees No CUDA? print(torch.cuda.cur...
In the conda env (myenv) where pytorch is installed do the following: conda activate myenv torch.version.cuda Nvidia-smi only shows compatible version. Does not seem to talk about the version pytorch's own cuda is built on.
38
53
64,124,931
2020-9-29
https://stackoverflow.com/questions/64124931/how-to-fix-versionconflict-locking-failure-in-pipenv
I'm using pipenv inside a docker container. I tried installing a package and found that the installation succeeds (gets added to the Pipfile), but the locking keeps failing. Everything was fine until yesterday. Here's the error: (app) root@7284b7892266:/usr/src/app# pipenv install scrapy-djangoitem Installing scrapy-dj...
Here are my debugging notes. Still not sure which package is causing the problem, but this does seem to fix it. The error you get when you first run pipenv install with pipenv version 2020.8.13. Traceback (most recent call last): File "/usr/local/bin/pipenv", line 8, in <module> sys.exit(cli()) File "/usr/local/lib/pyt...
34
20
64,126,653
2020-9-29
https://stackoverflow.com/questions/64126653/decrypting-aes-cbc-in-python-from-openssl-aes
I need to decrypt a file encrypted on OpenSSL with python but I am not understanding the options of pycrypto. Here what I do in OpenSSL openssl enc -aes-256-cbc -a -salt -pbkdf2 -iter 100000 -in "clear.txt" -out "crypt.txt" -pass pass:"mypassword" openssl enc -d -aes-256-cbc -a -pbkdf2 -iter 100000 -in "crypt.txt" -o...
The OpenSSL statement uses PBKDF2 to create a 32 bytes key and a 16 bytes IV. For this, a random 8 bytes salt is implicitly generated and the specified password, iteration count and digest (default: SHA-256) are applied. The key/IV pair is used to encrypt the plaintext with AES-256 in CBC mode and PKCS7 padding, s. her...
11
9
64,115,628
2020-9-29
https://stackoverflow.com/questions/64115628/get-starlette-request-body-in-the-middleware-context
I have such middleware class RequestContext(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next: RequestResponseEndpoint): request_id = request_ctx.set(str(uuid4())) # generate uuid to request body = await request.body() if body: logger.info(...) # log request with body else: logger.info(...) # lo...
I would not create a Middleware that inherits from BaseHTTPMiddleware since it has some issues, FastAPI gives you a opportunity to create your own routers, in my experience this approach is way better. from fastapi import APIRouter, FastAPI, Request, Response, Body from fastapi.routing import APIRoute from typing impor...
12
5
64,125,560
2020-9-29
https://stackoverflow.com/questions/64125560/how-do-you-broadcast-np-random-choice-across-each-row-of-a-numpy-array
Suppose I have this numpy array: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] My goal is to select two random elements from each row and create a new numpy array that might look something like: [[2, 4], [5, 8], [9, 10], [15, 16]] I can easily do this using a for loop. However, is there a way that I...
Approach #1 Based on this trick, here's a vectorized way - n = 2 # number of elements to select per row idx = np.random.rand(*a.shape).argsort(1)[:,:n] out = np.take_along_axis(a, idx, axis=1) Sample run - In [251]: a Out[251]: array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) In [252]: idx = n...
8
10
64,122,700
2020-9-29
https://stackoverflow.com/questions/64122700/efficiently-remove-partial-duplicates-in-a-list-of-tuples
I have a list of tuples, the list can vary in length between ~8 - 1000 depending on the length of the tuples. Each tuple in the list is unique. A tuple is of length N where each entry is a generic word. An example tuple can be of length N (Word 1, Word 2, Word 3, ..., Word N) For any tuple in the list, element j in sai...
Let's conceptualize each tuple as a binary array, where 1 is "contains something" and 2 is "contains an empty string". Since the item at each position will be the same, we don't need to care what is at each position, only that something is. l = [('A','B','',''),('A','B','C',''),('','','','D'),('A','','','D'),('','B',''...
9
6
64,122,311
2020-9-29
https://stackoverflow.com/questions/64122311/group-pandas-dataframe-in-unusual-way
Problem I have the following Pandas dataframe: data = { 'ID': [100, 100, 100, 100, 200, 200, 200, 200, 200, 300, 300, 300, 300, 300], 'value': [False, False, True, False, False, True, True, True, False, False, False, True, True, False], } df = pandas.DataFrame (data, columns = ['ID','value']) I want to get the follow...
Let us try shift + cumsum create the groupby key: BTW I really like the way you display your expected output s = df.groupby('ID')['value'].apply(lambda x : x.ne(x.shift()).cumsum()) d = {x : y for x ,y in df.groupby(s)} d[2] ID value 2 100 True 5 200 True 6 200 True 7 200 True 11 300 True 12 300 True d[1] ID value 0 10...
15
9
64,111,320
2020-9-29
https://stackoverflow.com/questions/64111320/sqlalchemy-hybrid-property-v-property-hybrid-method-v-classmethod
I have a Model (which I'm using as an abstract base class), that has some common methods and properties. SQLAlchemy allows creating properties and methods with @hybrid_property and @hybrid_method, but also the standard @property, @classmethod, @staticmethod decorators give me the results I'm after. Are there any advant...
The hybrid provides for an expression that works at both the Python level as well as at the SQL expression level Let's look at an example: class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) firstname = Column(String(50)) lastname = Column(String(50)) @hybrid_property def fullname(self): r...
15
12
64,113,002
2020-9-29
https://stackoverflow.com/questions/64113002/how-i-can-aggregate-employee-based-on-their-department-and-show-average-salary-i
This is my code which has data in which I want to perform the task using pandas.DataFrame.groupby import pandas as pd data = {'employees_no': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 'employees_name': ['Jugal Sompura', 'Maya Rajput', 'Chaitya Panchal', 'Sweta Rampariya', 'Prakshal Patel', 'Dhruv Panchal', 'Prachi D...
Extending what @Chris did and adding the part of remove average salary values if department_name is same. Here's the full code: import pandas as pd data = {'employees_no': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 'employees_name': ['Jugal Sompura', 'Maya Rajput', 'Chaitya Panchal', 'Sweta Rampariya', 'Prakshal Pate...
7
3
64,105,616
2020-9-28
https://stackoverflow.com/questions/64105616/greenlet-runtime-error-and-deployed-app-in-docker-keeps-booting-all-the-workers
RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility. Expected 144 from C header, got 152 from PyObject And all the workers are being booted. 2020-09-28T14:09:41.864089908Z [2020-09-28 14:09:41 +0000] [31] [INFO] Booting worker with pid: 31 2020-09-28T14:09:43.933141974Z [2020-09-28 14...
as https://discuss.redash.io/t/binary-compatibility-issue-with-greenlet/7237 indicates a workaround is greenlet==0.4.16 or upgrade your gevent to 20.9.0 following fix is suggested on the greenlet github page https://github.com/python-greenlet/greenlet/issues/178#issuecomment-697342964 also see following issues https:/...
16
23
64,082,541
2020-9-26
https://stackoverflow.com/questions/64082541/difference-between-python-type-hints-of-type-and-type
Today, I came across a function type hinted with type. I have done some research as to when one should type hint with type or Type, and I can't find a satisfactory answer. From my research it seems there's some overlap between the two. My question: What is the difference between type and Type? What is an example use c...
type is a metaclass. Just like object instances are instances of classes, classes are instances of metaclasses. Type is an annotation used to tell a type checker that a class object itself is to be handled at wherever the annotation is used, instead of an instance of that class object. There's a couple ways they are re...
6
8
64,105,927
2020-9-28
https://stackoverflow.com/questions/64105927/using-q-object-with-variable
I'd like to use the django.db.models.Q object in a way that the query term is coming from a variable. What i'd like to achieve is identical to this: q = Q(some_field__icontains='sth') Obj.objects.filter(q) , but the some_field value should come from a variable: field_name='some_field' q = Q('%s__icontains=sth' % field...
You can pass a 2-tuple to a Q object with the name of the fieldname(s) and lookups as first item, and the value as second item: Obj.objects.filter(Q(('%s__icontains' % field_name, 'sth'))) this is probably the most convenient way. That being said the dictionary unpacking, although less elegant, should also work.
7
9
64,103,507
2020-9-28
https://stackoverflow.com/questions/64103507/how-to-rename-a-single-node-of-a-networkx-graph
I wanted to know how I can change a single node name of a node of a digraph. I am new to networkx and could only find answers on how to change all node names. In my case I am iterating over a graph A to create graph B. p and c are nodes of graph A. The edge (p,c) of graph A contains data I want to add to the node p of ...
You have nx.relabel_nodes for this. Here's a simple use case: G = nx.from_edgelist([('a','b'), ('f','g')]) mapping = {'b':'c'} G = nx.relabel_nodes(G, mapping) G.edges() # EdgeView([('a', 'c'), ('f', 'g')])
11
18
64,100,160
2020-9-28
https://stackoverflow.com/questions/64100160/numpy-split-array-into-chunks-of-equal-size-with-remainder
Is there a numpy function that splits an array into equal chunks of size m (excluding any remainder which would have a size less than m). I have looked at the function np.array_split but that doesn't let you split by specifying the sizes of the chunks. An example of what I'm looking for is below: X = np.arange(10) spli...
Here's one way with np.split + np.arange/range - def split_given_size(a, size): return np.split(a, np.arange(size,len(a),size)) Sample runs - In [140]: X Out[140]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [141]: split_given_size(X,3) Out[141]: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([9])] In [143]...
11
19
64,099,107
2020-9-28
https://stackoverflow.com/questions/64099107/convert-multipolygon-geometry-into-list
How can I please convert a multipolygon geometry into a list? I tried this: mycoords=geom.exterior.coords mycoordslist = list(mycoords) But I get the error: AttributeError: 'MultiPolygon' object has no attribute 'exterior'
You will have to loop over geometries within your MultiPolygon. mycoordslist = [list(x.exterior.coords) for x in geom.geoms] Note that the result is a list of coords lists.
7
14
64,096,953
2020-9-28
https://stackoverflow.com/questions/64096953/how-to-convert-yolo-format-bounding-box-coordinates-into-opencv-format
I have Yolo format bounding box annotations of objects saved in a .txt files. Now I want to load those coordinates and draw it on the image using OpenCV, but I don’t know how to convert those float values into OpenCV format coordinates values I tried this post but it didn’t help, below is a sample example of what I am ...
There's another Q&A on this topic, and there's this1 interesting comment below the accepted answer. The bottom line is, that the YOLO coordinates have a different centering w.r.t. to the image. Unfortunately, the commentator didn't provide the Python port, so I did that here: import cv2 import matplotlib.pyplot as plt ...
19
48
64,096,624
2020-9-28
https://stackoverflow.com/questions/64096624/what-is-the-difference-between-using-softmax-as-a-sequential-layer-in-tf-keras-a
what is the difference between using softmax as a sequential layer in tf.keras and softmax as an activation function for a dense layer? tf.keras.layers.Dense(10, activation=tf.nn.softmax) and tf.keras.layers.Softmax(10)
they are the same, you can test it on your own # generate data x = np.random.uniform(0,1, (5,20)).astype('float32') # 1st option X = Dense(10, activation=tf.nn.softmax) A = X(x) # 2nd option w,b = X.get_weights() B = Softmax()(tf.matmul(x,w) + b) tf.reduce_all(A == B) # <tf.Tensor: shape=(), dtype=bool, numpy=True> Pa...
8
6
64,095,346
2020-9-28
https://stackoverflow.com/questions/64095346/pickle-how-does-it-pickle-a-function
In a post I posted yesterday, I accidentally found changing the __qualname__ of a function has an unexpected effect on pickle. By running more tests, I found that when pickling a function, pickle does not work in the way I thought, and changing the __qualname__ of the function has a real effect on how pickle behaves. T...
Pickling of function objects is defined in the save_global method in pickle.py: First, the name of the function is retrieved via __qualname__: name = getattr(obj, '__qualname__', None) Afterwards, after retrieving the module, it is reimported: __import__(module_name, level=0) module = sys.modules[module_name] This fr...
8
5
64,095,876
2020-9-28
https://stackoverflow.com/questions/64095876/multiprocessing-fork-vs-spawn
I was reading the description of the two from the python doc: spawn The parent process starts a fresh python interpreter process. The child process will only inherit those resources necessary to run the process objects run() method. In particular, unnecessary file descriptors and handles from the parent process will n...
is it that the fork is much quicker 'cuz it does not try to identify which resources to copy? Yes, it's much quicker. The kernel can clone the whole process and only copies modified memory-pages as a whole. Piping resources to a new process and booting the interpreter from scratch is not necessary. is it that, si...
71
21
64,094,162
2020-9-27
https://stackoverflow.com/questions/64094162/i-have-accidently-delete-my-sceret-key-form-settings-py-in-django
while pulling from git hub i lost my secret key which i have updated. is there any way to obtain secret key for the same project. while pulling from git hub i lost my secret key which i have updated. is there any way to obtain secret key for the same project.
run : python manage.py shell write and enter the following lines sequentially: from django.core.management.utils import get_random_secret_key print(get_random_secret_key()) exit() copy this secret_key to your settings.py SECRET_KEY. And reload this server. If it will not work, refresh the page with ctrl+shift+r, dele...
9
13
64,090,818
2020-9-27
https://stackoverflow.com/questions/64090818/unconsumed-column-names-sqlalchemy-python
I am facing the following error using SQLAlchemy: Unconsumed column names: company I want to insert data for 1 specific column, and not all columns in the table: INSERT INTO customers (company) VALUES ('sample name'); My code: engine.execute(table('customers').insert().values({'company': 'sample name'})) Create Table:...
After hours of frustration, I was able to test a way that I think works for my use case. As we know, you can insert to specific columns, or all columns in a table. In my use case, I dynamically need to insert to the customers table, depending on what columns a user has permissions to insert to. I found that I needed to...
11
10
64,083,104
2020-9-26
https://stackoverflow.com/questions/64083104/making-python-generator-via-c20-coroutines
Let's say I have this python code: def double_inputs(): while True: x = yield yield x * 2 gen = double_inputs() next(gen) print(gen.send(1)) It prints "2", just as expected. I can make a generator in c++20 like that: #include <coroutine> template <class T> struct generator { struct promise_type; using coro_handle = st...
You have essentially two problems to overcome if you want to do this. The first is that C++ is a statically typed language. This means that the types of everything involved need to be known at compile time. This is why your generator type needs to be a template, so that the user can specify what type it shepherds from ...
20
17