spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » PYTHON » Page 5
How can I find where a vector value passes a threshold and the n+1 value meets a condition?
Well, I solved it myself! (see Finding local maxima/minima with Numpy in a 1D numpy array ) locs = (np.diff(np.sign(np.diff(v_1))) < 0).nonzero()[0] +1

Categories : Python

How to make an object of a class extending Enum
Per the docstring in the source code (note that this method is defined on the metaclass, EnumMeta): [__call__] is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum('Color', names='red green blue')). The required positional argument value is either one of the values of an existing enumerator, or th

Categories : Python

Exception in classes when using Django
You shouldn't be trying to return an HttpResponse in your requests class. Instead of catching the exception and replacing it with an unwanted HttpResponse, let it propagate and catch it in the view: try: user_details = auth_client['auth/users/%s/details' % (request.POST.get('username'))].get().json()['result'] except requests.Timeout: return HttpResponse('whatever') Edit OK, so here's a

Categories : Python

Find and replace empty rows in list width Python
It is easy to keep record of the previous value in a loop than of the coming values. So my idea is to reverse the list. Replace each empty value by its previous one. Finally reverse the list back and you will get the result. >>> lst=('2047', '1971', '', '1919', '', '1878', '', '', '1760', '1731', '', '1667', '', '') >>> lst=list(lst[::-1]) >>> pr=0 >>> for j in

Categories : Python

Celery task that returns group in chain
Convert your group task to chord to achieve that. Here is a simple example. @app.task def dummy_task(): return 'I am a dummy task' @app.task def add(x, y): return x + y @app.task def task_with_group_task(): task1 = add.si(1, 2) group_task = group(add.si(i, i) for i in range(5)) task2 = chord(group_task, dummy_task.si()) task3 = add.si(9, 9) pipeline = chain(task1, t

Categories : Python

how to do 3d matrix to 3d multiplication in python without loops?
AFAIK, numpy can braodcast biscuitMask along the color dimension to fit the shape of the frame. This broadcasting is done automatically. Thus, maskedFrame = rgbFrame * biscuitMask maskedHsvFrame = hsvFrame * biscuitMask Should work without any loops or modifications. PS, If you are familiar with matlab, broadcasting is very much like applying bsxfun only numpy does it automatically for you.

Categories : Python

len(n) x len(m) array in NumPy
>>> arr = np.empty((len(m), len(n)), dtype=str) >>> arr.fill('') >>> arr[0] = list(n) >>> arr[:,0] = list(m) >>> arr array([['A', 'A', 'A', 'D', 'D', 'D', 'E', 'E', 'E'], ['A', '', '', '', '', '', '', '', ''], ['D', '', '', '', '', '', '', '', ''], ['D', '', '', '', '', '', '', '', ''], ['D', '', '', '', '', '', '', '', ''],

Categories : Python

python xpath IndexError: list index out of range
Use Try Except import requests from lxml import html def do_get(xpath): # OR URL What ever you need url='http://www.example.com' cont=requests.get(url) tree=html.fromstring(cont) out=tree.xpath(xpath)[0] try: do_get('....') except: do_get('....') Or if you wanna do it forever until you get the right one: def do_get(xpath): url='http://www.example.com' cont=req

Categories : Python

How to deal with keys not found in Python Dictionaries
collections.defaultdict import collections D = collections.defaultdict(int) D['foo'] = 42 print D['foo'], D['bar']

Categories : Python

Is there a python code to concatenate values into 1 cell in excel
This will take the input, and 'uniquify' on the 2nd column. #!/usr/bin/env python import csv dict={} with open('gene_test.csv','rB') as f: reader = csv.reader(f) for line in reader: try: dict[line[1]].append(line[0]) except: dict[line[1]]=[line[0]] with open('out_gene_test.csv','wb') as f: writer = csv.writer(f, delimiter='|') for key in

Categories : Python

Weird behavior from pythons multiprocessing
Fabric has its own facilities for parallel execution of tasks - you should use those, rather than just trying to execute Fabric tasks in multiprocessing pools. The problem is that the env object is mutated when executing the tasks, so the different workers are stepping on each other (unless you put locking in).

Categories : Python

Get all disconnected pairs of nodes in a network
Re the first question (listing pairs of disconnected nodes): yes, you have to do this manually, but it is fairly easy: from itertools import product all_nodes = set(range(g.vcount()) disconnected_pairs = [list(product(cluster, all_nodes.difference(cluster))) for cluster in g.clusters()] But beware, this could be a fairly large list if your graph is large and consists of

Categories : Python

Save File Using Common Dialog in Python3
Use could use the class FileChooserDialog from the module gtk: import gtk gtk.FileChooserDialog().run()

Categories : Python

Null/No SIFT descriptor and keypoints generated in python
The function sift.detectAndCompute will first try to detect a SIFT keypoint then compute a descriptor at the found location. This is not what you want: you want to have a descriptor for each patch. You can hand craft the keypoint locations first (by adjusting their pt property to the center of your patches and adjusting their size property to your patch size). Then, call only the descriptor extr

Categories : Python

Gaussian kernel density smoothing for pandas.DataFrame.resample?
I have now found that this is option is available in pandas.stats.moments.ewma and it works quite nicely. Here are the results: from pandas.stats.moments import ewma hourly[0][344:468].plot(style='b') ewma(hourly[0][344:468], span=35).plot(style='k')

Categories : Python

how to add packages like numpy,scipy and others to the sublime 2 python?
To install packages such as pyGame, you need to download the installer and run it. Since you have multiple versions of Python, you will need to select the required version in the installer. A link to pyGame: http://www.pygame.org/download.shtml Link to all packages: https://pypi.python.org/pypi?%3Aaction=index Make sure to download the packages for your required python version. You could also u

Categories : Python

Persisting the dictionary index after deleting item
You may simply iterate through the loop in reverse. This way you delete elements from the end as necessary, which won't displace elements that you haven't iterated through. We can do this by converting your enumeration to a list, and wrapping this list with reversed: for k1,v1 in reversed(list(enumerate(value['match']))): if k1 != '': print ' Category: ',k1,' ',v1['category']

Categories : Python

Feedparser to Parse Specific Text in Entries
Never used feed parser myself, but here is an alternative way. I suggest you take a look at the imaplib - it provides tools for accessing email accounts and retrieving emails. Also take a look at the email module - you can use it to parse an email and get subject, sender, etc. Take a look at this example: import imaplib import email import time GREETINGS = "Merry Christmas" while True: # Co

Categories : Python

Django form re-validation for null/blank fields
You can override the clean method in modelform like this: def clean(self): if self.cleaned_data['image'] is not None or self.cleaned_data['content'] != '' : return super().clean() #For python 3 #return super(YourForm, self).clean() // for python 2 raise ValidationError('Some Error')

Categories : Python

Where is mimetools.choose_boundary function in Python3?
Well, I answer my question since no other available answer here. Yes, I got the result finally, for more info about my work around the question, the below information may help. 1. What does boundary do in an multipart/form-data request? In fact, to separate the different parts of data is such a request, we use a separator, here we call boundary, to divide the form data. These parts may be fi

Categories : Python

get alphabatic list from numeric one
>>> import operator >>> import string >>> operator.itemgetter(*[1, 2, 3, 4, 5])(' ' + string.ascii_uppercase) ('A', 'B', 'C', 'D', 'E') (But don't really do it this way...)

Categories : Python

Why is the following attribute not found in Enum?
You're confusing enum with enum. They have many similarities, but are not the same thing. In particular, the attribute you're looking for does not exist.

Categories : Python

python AttributeError: 'list' object has no attribute 'Race'
DriverList is a list of objects. You need to select objects from that list to call function race. #Code-------- num = 0 while num<(len(DriverList)-1): DriverList[num].Race() num+=1 if RaceWinner in DriverList: print("The winner is", DriverList.Winner()) break

Categories : Python

Using MacPorts to install modules via a certain path
While you could adjust your PYTHONPATH environment variable or modify the path using sys.path.insert, you should not try to mix a Python module built for MacPorts' Python with Anaconda. This may work just fine if the module is python-only, but as soon as the module contains compiled code it is not certain that the two installations are binary-compatible. In the best case, loading the module will f

Categories : Python

How do I get lines between same pattern using python regex
Use a positive lookahead and lookbehind assertion like below. >>> import re >>> s="abc123abcfndfabc1234drfabc" >>> re.findall(r'(?<=abc).*?(?=abc)', s) ['123', 'fndf', '1234drf'] DEMO Explanation: (?<=abc) Positive Lookbehind which asserts that the string preceds the match must be abc .*? Non-greedy match of zero or more chracaters. (?=abc) Positive lookahead

Categories : Python

Numpy float64 vs Python float
>>> numpy.float64(5.9975).hex() '0x1.7fd70a3d70a3dp+2' >>> (5.9975).hex() '0x1.7fd70a3d70a3dp+2' They are the same number. What differs is their representation; the Python native type uses a "sane" representation, and the NumPy type uses an accurate representation.

Categories : Python

Finding the average of columns from nested lists in a dictionary's value
Assuming value in dictionary contains list of only two elements (which are again lists): d = {'dog': [['4.1', '7.0', 'dog'], ['1.2', '3.4', 'dog']], 'cat': [['1', '8.2', '5.501', 'cat'], ['6.5', '8', '9.1', 'cat']]} avg_dict = {} for key in d: avg_list = [] i = 0 while (i < len(d[key][0]) - 1): avg_list.append((float(d[key][0][i]) + float(d[key][1][i])) /2.0) i +

Categories : Python

Read and Write on Python
Open() def Open(): try: infile = open("grades.txt", "r") except: print("Error: can't find file or read data") When you open file for reading the mode needs to r.Or else it will create a new file cleeaning the old data.Also assign input in try block to grade.

Categories : Python

Separate data with a comma CSV Python
Just use the csv.writer from the csv module. import csv data = [['A','B','C'] ['a1,a2','b1','c1'] ['a2,a4','b3','ct']] fname = "myfile.csv" with open(fname,'wb') as f: writer = csv.writer(f) for row in data: writer.writerow(row) https://docs.python.org/2/library/csv.html#csv.writer

Categories : Python

Rudimentary program TypeError. What am I doing wrong?
x,y are strings. You need to do int(x). You might want to catch the exception if either of those is not an integer (empty (user only pressed return), whitespace, symbols, letters). print (int(y) * int(x)) [This must be a duplicate of other questions here...]

Categories : Python

SQLAlchemy exectutemany with generator
There are execution_options for the Connection, which take a stream_results parameter, but unforutunately at the bottom it says that "the flag is currently understood only by the psycopg2 dialect", even though there are other drivers with streaming support (e.g. oursql). Until it is fully supported in sqlalchemy, you can easily write a helper function to break any iterable into chunks to avoid th

Categories : Python

My use of Scipy curve_fit does not seem to work well
You have to pass an initial guess for popt, otherwise the fit starts with [1,1,1] as initial guess which is pretty poor for your dataset! The following gives reasonable results for me: popt, pcov = curve_fit(func, xk, Kp4, p0=[20,630,5]) The initial guess could be [np.mean(Kp4), np.mean(xk),5*(max(xk)-min(xk))/len(xk)], to have a general starting point. Don't forget to put plt.show() or somet

Categories : Python

TypeError: read_hdf() takes exactly 2 arguments (1 given)
Having never worked with hdf files before I was able to use the online docs to cook an example: In [59]: # create a temp df and store it df_tl = pd.DataFrame(dict(A=list(range(5)), B=list(range(5)))) df_tl.to_hdf('store_tl.h5','table',append=True) In [60]: # we can simply read it again and the keys are displayed store = pd.HDFStore('store_tl.h5') # keys will be displayed in the output store Out[6

Categories : Python

How to run python file in cmd?
To get it working properly, you must add ;C:Python34 on the end of the Path (or PATH) enviroment variable. I don't think C:Python3.4 would work. The environment variables can be changed by going to: Control Panel > System > Advanced (tab) > Environment Variables.

Categories : Python

Django static files urls setting
If you will write the below code in urls.py it will work for both the DEBUG status url( r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT } ), and one thing to be noted my static root is like for django 1.4+ PROJECT_DIR = os.path.dirname(os.path.dirname( __file__ )) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') along with this you need to

Categories : Python

Translate OID value pairs from MIB textual convention using pysnmp
That is possible with pysnmp: from pysnmp.smi import builder mibBuilder = builder.MibBuilder() TruthValue, = mibBuilder.importSymbols('SNMPv2-TC', 'TruthValue') print(TruthValue(1).prettyPrint()) # prints 'true' However in general you would have to somehow map OIDs to value types (some of which may resolve into TEXTUAL-CONVENTIONS). This can be done in an ad-hoc manner by hardcoding OID->type

Categories : Python

Naming LDA topics in Python
Labeling topics is completely distinct from topic modeling. Here's an article that describes using a keyword extraction technique (KERA) to apply meaningful labels to topics: http://arxiv.org/abs/1308.2359

Categories : Python

NLTK FCFG's : Maximum Recursion Depth Exceeded
The problem appears resolved! The issue seems to have been with functools.py, not nltk, per this StackOverflow question: Django RuntimeError: maximum recursion depth exceeded

Categories : Python

Getting the indices of the top k numbers by value in a numpy array?
You need to flat your array first , then sort it and use unique to refuse from duplicated entry . >>> a.flatten() array([1, 2, 3, 4, 3, 1]) >>> b=a.flatten() >>> np.unique(np.sort(b))[-3:] array([2, 3, 4]) and for get the indices you can use argsort : >>> b.argsort()[-3:] array([2, 4, 3])

Categories : Python


Recently Add
Overriding save method vs Model Method?
function encrypt file - input & output to same file in python
urllib.error.URLError:
python if statement fails to compute compound logic
referencing sphinx generated Python docs from YAML file
Subclassing datetime64
filter view from url parameter with an intermediate model?
How to stream twitter mentions with tweepy?
How to space out rows and columns in Python Tkinter
Python: Using BeautifulSoup to save content to CSV
Python - Take parts of a txt file and put them in another txt
Python socket send doesn't send the whole string
Python: prime test
How to import one day old logs
Appending filters to django models
Python: parsing .xls file failed with both xlrd and pandas
writing pandas dataframe columns to csv rows staggered
parse_args doesn't seem to understand json arguments
Django ORM, get data
Pygame, keep jumping and glitching through the "ground"
Is it possible to import a class defined inside a function?
How to handle a variable number of nested for loops?
Boolean expression with strings
Object duplicated when using processing.Manager?
What is the syntax of PBS job limit directive
python 3.x overwrite previous terminal line
Deploying django app. on heroku (gunicorn, wsgi issue)
How can I create an "ID" column in one dataframe based on the index of another dataframe?
PIL Module Error
pandas.read_html returns only one table
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.