questions stringlengths 50 48.9k | answers stringlengths 0 58.3k |
|---|---|
Exception: 'module' object is not iterable When I am running the code from Github project, I am getting this error:Exception in thread django-main-thread:Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/urls/resolvers.py", line 600, in url_patterns ... | I had a look at your urls.py file from your github linkThere is a small typo where you have capitalised the urlpatterns object.from django.urls import pathfrom .views import blogListViewUrlpatterns = [ path(' ', blogListView.as_view(), name='home'), ]The spelling of urlpatterns must be exact in order for routing to wor... |
iteratively intersecting line segments in Sympy... is there a better way? OK. I have the points that comprise the borders of a polygon. I want to (a) use Sympy's geometry module to determine, from all of the possible line-segments between any pair of points, which segments do not cross the perimeter. This result will b... | I found a solution that sped the process up by about 13x (for a polygon with 35 points (like the data listed above), the old method from the code in the question took about 4hours to find all line segments inside the polygon. This new method took 18 minutes instead.) Above I was iteratated through the points, and at ea... |
How to fix freeze_support() error for computing compute Perplexity and Coherence for LDA? I am going to compute Perplexity and Coherence for my textual data for LDA. I run the following codes# Compute Perplexityprint('\nPerplexity: ', lda_model.log_perplexity(corpus)) # a measure of how good the model is. lower the be... | # Compute Perplexityprint('\nPerplexity: ', lda_model.log_perplexity(corpus)) # a measure of how good the model is. lower the better.# Compute Coherence Scoreif __name__ == '__main__': coherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v') coherence_lda... |
How to filter Django objects based on value returned by a method? I have an Django object with a method get_volume_sum(self) that return a float, and I would like to query the top n objects with the highest value, how can I do that?For example I could do a loop like this but I would like a more elegant solution.vol = [... | You should not filter with the method, this will result in an N+1 problem: for 3'000 Market objects, it will generate an additional 3'0000 queries to obtain the volumes.You can do this in bulk with a .annotate(…) [Django-doc]:from django.db.models import Sumhours = 12 # some value for hoursMarket.objects.filter( **... |
CMD color problems I want to make my python cmd output colorful!I have color-codes like this:\033[91mNow the output in cmd isn't colorful. I get a "←". How can I change this?Did anybody have the same problem? :DEditIs there an alternative to cmd? Is it hard to programm a cmd window in e.g. C#? | You need to add just two more lines at the beginning of your script.import osos.system("") |
How to check differences between column values in pandas? I'm manually comparing two or three rows very similar using pandas. Is there a more automated way to do this? I would like a better method than using '=='. | https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.diff.htmlSee if this will satisfy your needs.df['sales_diff'] = df['sales'].diff()The above code snippet creates a new column in your data frame, which contains the difference between the previous row by default. You can screw around with the parameters (axi... |
fish: Unknown command: pip today I am trying Garuda KDE Dr460nized and I am running python on it. But when I use pip for installing packages I open my Konsole and, an error comes like thisfish: Unknown command: pipI thought I should write pip3 instead of pip but still, the same error comesfish: Unknown command: pip3Can... | I think I have answered my questionI have to add:python -m pip install packageNameIt solved my error. If anyone can't solve their error you can see this answer. |
django detect user login in another tab Is there anyway in django that if user has two open tabs, both logged out, then logs in in one tab, tell that he has logged in in another tab? I mean something like github that tells you you have signed in, please refresh the page.The problem is now If I login in one tab and then... | You get csrf token missing incorrect. because when user relogins, the server generates a new csrf token to the cookie. The cookie persists across the same domain. And when you're trying to do smth on the current page, the request fails because csrf in your <form> differs from the cookie which has been changed. Th... |
Regex to find five consecutive consonants I need a regex for python that finds words with five consecutive consonants. These words would work - tnortvcvni (rtvcvn)kahjdflka (hjdflk)But these words wouldn't (no five letters in row without vowels) - peanut butterjelly | It seems you don't mean a fixed length of 5 characters but a minimum:(?:(?![aeiou])[a-z]){5,}Live demoNote: set i flag if it exists. |
Python Regex Match failed This passed on https://regex101.com/ without any issues. Did I miss anything? The entire string is in one line.def get_title_and_content(html): html = """<!DOCTYPE html> <html> <head> <title>Change delivery date with Deliv</title> </head&... | In a summary of the comments:title_pattern.search(html) Should be used instead of title_pattern.match(html)As the search function will search anywhere in the provided string instead of just from the beginning. match = title_pattern.findall(html) could be used similarly but would return a list of items instead of just o... |
Checking ISBN numbers This is my code:def isISBN(n): if len(n)!= 10: return False else: d1=int(n[0])*1 d2=int(n[1])*2 d3=int(n[2])*3 d4=int(n[3])*4 d5=int(n[4])*5 d6=int(n[5])*6 d7=int(n[6])*7 d8=int(n[7])*8 d9=int(n[8])*9 d10=(d1+d2+d3+d4+d... | Don't forget the 10th value and check for modulo equivalence to 0:def isISBN(n): if len(n)!= 10: return False else: d1=int(n[0])*1 d2=int(n[1])*2 d3=int(n[2])*3 d4=int(n[3])*4 d5=int(n[4])*5 d6=int(n[5])*6 d7=int(n[6])*7 d8=int(n[7])*8 d9=int(n... |
How do you set a variable number of regex expressions? Currently I have out = re.sub(r'[0-9][0-9][0-9]', '', input). I would like to have a variable number of [0-9]'s.So far I have;string = ''for i in xrange(numlen): string = string + '[0-9]'string = 'r' + stringout = re.sub(string, '', input)This doesn't work, and ... | You can specify repetition using {}, for example 3 digits would be[0-9]{3}So you can do something likereps = 5 # or whatever value you'd likeout = re.sub('[0-9]{{{}}}'.format(reps), '', input)Or if you don't know how many digits there will beout = re.sub('[0-9]+', '', input) |
why is this code removing the file instead of renaming it? I want to rename report.json but it is removing the file instead import osfrom pathlib import Pathimport jsonpath =Path( r'C:\Users\Sajid\Desktop\cuckoo (3)\cuckoo\storage\analyses\3\reports')filename = os.path.join(path,"report.json")with open(filename) as jso... | It's probably not deleting it, but moving it to your working directory (so if you launched your script from C:\Users\Sajid, the file would be there, not in C:\Users\Sajid\Desktop\cuckoo (3)\cuckoo\storage\analyses\3\reports). Edit: Based on your comment, this is definitely what's happening; the first time you ran your ... |
How to download GeoTiff files from GeoServer using Python I am trying to download GeoTiff files from GeoServer using Python. I have a found a few resources online about this type of thing, but I have been unable to accomplish this task.For example, here: https://gis.stackexchange.com/questions/181560/download-geotiff-f... | As the answer to your linked question says you need to make a WCS request to GeoServer to fetch a GeoTiff. The GeoServer manual provides a WCS reference that should help you get an understanding of how to proceed. You can also go to the demos page of your GeoServer installation and use the WCS Request builder to create... |
Cumulative sum in pyspark I am trying to compute the cumulative sum per class. Code is working fine by using sum(df.value).over(Window.partitionBy('class').orderBy('time'))df = sqlContext.createDataFrame( [(1,10,"a"),(3,2,"a"),(1,2,"b"),(2,5,"a"),(2,1,"b"),(9,0,"b"),(4,1,"b"),(7,8,"a"),(3,8,"b"),(2,5,"a"),(0,0,"a"),(4,... | Adding to @pault's comment, I would suggest a row_number() calculation based on orderBy('time', 'value') and then use that column in the orderBy of another window(w2) to get your cum_sum. This will handle both cases where time is the same and value is the same, and where time is the same but value isnt.from pyspark.sql... |
Weird linear regression learning curve I'm trying to build a prediction model for apartments price. I use python scikit-learn toolset. I'm using a dataset having total floor area and location of the apartment, which I have converted to dummy features. So the dataset looks like this:Then I build a learning curve to see ... | My explanation have 3 steps: The data preparation, feature extraction, and model selection.Data preparation:In this dataset there are lots of Categorical and Ordinal values. Ifthe column has several non related categories it's ok to one-hot it.but if the column has categories with order like"bad","normal","good" you ca... |
Find most common words from list of strings We have a given list:list_of_versions = ['apple II' ,'apple', 'apple 1' , 'HD APPLE','apple 3.5', 'adventures of apple' , 'apple III','orange 2' ,'300mhz apple', '300-orange II' , 'orange II HD' , 'orange II tvx', 'orange 2' , 'HD berry-vol 2', 'berry II', 'berry 2', 'berry ... | All the other answers omit the entry containing the word "adventures" because it throws off the search. You need a heuristic that can combine "longest" with "most frequent".One thing that helps is that finding the longest word in each row greatly increases SNR. In other words, it filters o... |
Python: Google-Maps-API sends unknown format to parse I use the Python Client for Google Maps Services to get following data from google-maps:{ 'address_components':[ { 'long_name':'20', 'short_name':'20', 'types':[ 'street_number' ] }, { 'lo... | The answer is: List comprehensionstry: # make a list of all address components that have type "street number" comp = [c for c in place_result_2["address_components"] if "street_number" in c["types"]] # the first one of them (assuming there will never be more than one) is the desired one self.hausnr = comp[0... |
Why using "--requirements_file" uploads dependencies onto GCS? I'm currently generating a template with those parameters: --runner DataflowRunner \ --requirements_file requirements.txt \ --project ${GOOGLE_PROJECT_ID} \ --output ${GENERATED_FILES_PATH}/staging \ --staging_location=${G... | I believe this is done to make the Dataflow worker startup process more efficient and consistent (both initially and when auto-scaling). Without this, each time a Dataflow worker starts up, that worker has to directly connect to PyPI to find the latest matching versions of dependencies. Instead of this, set of dependen... |
Got only first row in table when using Selenium scraping (Python) I'm trying to scrape the whole table from: https://free-proxy-list.net/ And I managed to scrape it but it resulted in only the first row of the table instead of 20 rows. I saw previous similar questions that were answered and I have tried the solutions g... | I think your problem is in this line :col = bod.find_elements_by_xpath("//*[@id='proxylisttable']/tbody/tr")The correct syntax is :col = bod.find_elements_by_xpath("//*[@id='proxylisttable']/tbody/tr[insert count here]")Like this :table = driver.find_element_by_xpath("//*[@id='proxylisttable']/tbody")rows = table.find_... |
How to concatenate part of three layers in Keras? I can use keras.layers.concatenate to concatenate two layers then send them to next layer, but if I want to take part of two layers then concatenate them and then send them to next layer, what should I do?For example, I want to take part of first conv layer and part of ... | Well, you can slice them as you want, like the way you would slice a numpy array or a Python list, and use K.concatenate, all in a Lambda layer. For example:from keras import backend as K# ...out = Lambda(lambda x: K.concatenate([x[0][:,:10], x[1][:,:10], ... |
Can we run tensorflow lite on linux ? Or it is for android and ios only Hi is there any possibility to run tensorflow lite on linux platform? If yes, then how we can write code in java/C++/python to load and run models on linux platform? I am familiar with bazel and successfully made Android and ios application using t... | I think the other answers are quite wrong.Look, I'll tell you my experience... I've been working with Django for many years, and I've been using normal tensorflow, but there was a problem with having 4 or 5 or more models in the same project.I don't know if you know Gunicorn + Nginx. This generates workers, so if you ... |
Don't understand these ModuleNotFound errors I am a beginner and learning Python. I have setup the environment with SublimeText and Python3.xI am fine in creating code on Sublime and building it locally through Ctrl+B and for input() function I installed SublimeREPL and it works find up till now.The issue I am facing i... | The initial Python download includes a number of libraries, but there are many, many more that must be downloaded and installed separately. Tweepy is among those libraries.You can find, and download, tweepy from here:https://pypi.org/project/tweepy/ |
How to group rows, count in one column and do the sum in the other? I want to group rows of a csv file, count in one column and add in the other.For example with the following I would like to group the lines on the Commune to make columns of the winner with the count and a column Swing with the sumCommune Winner Swing ... | Use crosstab and add new column with DataFrame.join and aggregate sum:df = pd.crosstab(df['Commune'], df['Winner']).join(df.groupby('Commune')['Swing'].sum())print (df) PAM PJD UDF SwingCommune Madrid 2 1 0 1Paris 2 1 1 3But if need counts of rows:df1 = pd.... |
Best way to fill NULL values with conditions using Pandas? So for example I have a data looks like this:df = pd.DataFrame([[np.NaN, '1-5'], [np.NaN, '26-100'], ['Yes', 'More than 1000'], ['No', '26-100'], ['Yes', '1-5']], columns=['self_employed', 'no_employees'])df self_employed no_employees0 nan ... | Use fillna is the right way to go, but instead you could do:values = df['no_employees'].eq('1-5').map({False: 'No', True: 'Yes'})df['self_employed'] = df['self_employed'].fillna(values)print(df)Output self_employed no_employees0 Yes 1-51 No 26-1002 Yes More than ... |
Cannot upload large file to Google Cloud Storage It is okay when dealing with small files. It doesn't work only when I try to upload large files. I'm using Python client. The snippet is:filename='my_csv.csv'storage_client = storage.Client()bucket_name = os.environ["GOOGLE_STORAGE_BUCKET"]bucket = storage_client.get_buc... | upload_by_filename attempts to upload the entire file in a single request.You can use Blob.chunk_size to spread the upload across many requests, each responsible for uploading one "chunk" of your file.For example:my_blob.chunk_size = 1024 * 1024 * 10 |
Python Requests Proxy Error So when i try to use proxy on python requests , the actual requests send is using my own ip http_proxy = "https://103.235.21.128:80"proxyDict = { "http" : http_proxy, }r = requests.get('http://whatismyip.org',proxies=proxyDict)print r.contentAlso Tried http_proxy =... | Have you tried setting http on the proxy like this?http_proxy = "http://103.235.21.128:80"orhttp_proxy = "http://{}:{}".format('103.235.21.128', 80)If that doesn't work you might have to find an http proxyIf you're requesting data from multiple websites (both http and https) then you'll have to add both to the diction... |
how to prioritize default mac python environment over miniconda I installed miniconda for some software I need to run. It worked great, but it made all of the other web related stuff I have set up through mac's default python environment stop working. What I would like to have is the mac python environment as the defau... | Have you considered using Python's Virtual env? This allows you to have a completely separate Python installations without causing conflicts with your main python in your path. This sounds ideal for your development needs. You would need to "activate" the virtualenv prior to starting up miniconda, which will adjust you... |
Unreadable encoding of a SMB/Browser packet in Scapy I'm trying to parse a pcap file with scapy (in python), and getting raw data at the layer above TCP.on wireshark, all the layers are shown correctly:but on scapy all i'm seeing is just a Raw layer...i'm thinking maybe it didn't parsed the packet well?maybe the NetBIO... | If someone has a similar problem…You need something likepacket[TCP].decode_payload_as(NBTSession)And then you Will get the decoded layers by scapy: packet[TCP].show()[ TCP ] sport = microsoft_ds… options = [][ NBT Session Packet ]### TYPE = Session Message RESERVED = 0 LENGTH = 4873[ SMBNegocia... |
Regex - Using * with a set of characters I'm fairly new at regex, and I've run into a problem that I cannot figure out:I am trying to match a set of characters that start with an arbitrary number of A-Z, 0-9, and _ characters that can optionally be followed by a number enclosed in a single set of parentheses and can be... | Your regex says that each paren (open & closed) may or may not be there, INDEPENDENTLY. Instead, you should say that the number-enclosed-in-parens may or may not be there:(\([\d]*\)){0,1}Note that this allows for there to be nothing in the parens; that's what your regex said, but I'm not clear that's what you actu... |
Crawling a page using LazyLoader with Python BeautifulSoup I am toying around with BeautifulSoup and I like it so far. The problem is the site I am trying to scrap has a lazyloader... And it only scraps one part of the site. Can I have a hint as to how to proceed? Must I look at how the lazyloader is implemented and pa... | It turns out that the problem itself wasn't BeautifulSoup, but the dynamics of the page itself. For this specific scenario that is. The page returns part of the page, so headers need to be analysed and sent to the server accordingly. This isn't a BeautifulSoup problem itself. Therefore, it is important to take a look a... |
How can I optimize a plotly graph with updatemenues? So, I have been using plotly a lot and recently came to use the updatemenus method for adding buttons. I've created several graphs with it, but I find it difficult to find an efficient method to update the args section in updatemenus sections. I have a data frame tha... | data frame creation can be simplified. Using pandas constructor capability with list comprehensionsfigure / traces creation is far simpler with plotly expresscore question - dynamically create visible liststhe trace is visible if it's in same name group. This where button name corresponds with name level of traceimpo... |
How to perform arithmetic with large floating numbers in python I have two numbers a and b:a = 1562239482.739072b = 1562239482.739071If I perform a-b in python, I get 1.1920928955078125e-06. However, I want 0.000001, which is the right answer after subtraction. Any help would be appreciated. Thank you in advance. t = f... | This is common problem with floating point arithmetic. Use the decimal module |
How to use __setitem__ properly? I want to make a data object:class GameData: def __init__(self, data={}): self.data = data def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value def __getattr__(self, item): return self.data[item] def __setattr__(s... | In the assignment self.data = data, __setattr__ is called because self has no attribute called data at the moment. __setattr__ then calls __getattr__ to obtain the non-existing attribute data. __getattr__ itself calls __getattr__ again. This is a recursion.Use object.__setattr__(self, 'data', data) to do the assignment... |
Python mysql.connector timeout Here's a simple connection to a MySQL database using the mysql.connector module.db = mysql.connector.connect( host=DB_SERVER, port=DB_PORT, user=DB_UNAME, passwd=DB_PASSWORD, db=DB_NAME)db.connect()mysqlCursor.execute(query)I want to control two different timeouts. First, I... | As of MySQL 5.7.8 a maximum execution time for just SELECT statements can be set per session. Set this immediately after connecting:db = mysql.connector.connect(...)cursor = db.cursor()# Limit SELECTs to 1 secondcursor.execute("SET SESSION MAX_EXECUTION_TIME=1000") |
Relative Strength Index in python pandas I am new to pandas. What is the best way to calculate the relative strength part in the RSI indicator in pandas? So far I got the following:from pylab import *import pandas as pdimport numpy as npdef Datapull(Stock): try: df = (pd.io.data.DataReader(Stock,'yahoo',start... | It is important to note that there are various ways of defining the RSI. It is commonly defined in at least two ways: using a simple moving average (SMA) as above, or using an exponential moving average (EMA). Here's a code snippet that calculates various definitions of RSI and plots them for comparison. I'm discarding... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.