code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for i in range(self.width):
tot = 0
for letter in ACGT:
if self.logP:
Pij = pow(2.0, self.logP[i][letter])
else:
Pij = pow(2.0, self.ll[i][letter]) * self.background[letter]
if Pij > 0.01:
... | def denoise(self,bitthresh=0.5) | m.denoise(bitthresh=0.5) -- Set low-information positions (below bitthresh) to Ns | 4.679187 | 4.645379 | 1.007278 |
return giflogo(self,id,title,scale) | def giflogo(self,id,title=None,scale=0.8,info_str='') | m.giflogo(id,title=None,scale=0.8) -- (Requires seqlogo package) Make a gif sequence logo | 9.512166 | 9.417167 | 1.010088 |
bits = []
tots = []
str = []
for i in range(self.width):
D = {}
tot = 0
for letter in ['A', 'C', 'T', 'G']:
if self.logP:
Pij = pow(2.0, self.logP[i][letter])
else:
... | def _print_bits(self,norm=2.3, height=8.0) | m._print_bits(,norm=2.3, height=8.0) -- Print a text-rendering of the Motif Logo
norm -- maximum number of bits to show
height -- number of lines of text to use to render logo | 3.278362 | 3.232259 | 1.014263 |
for Dll in self.ll:
for L in one2two.keys():
Dll[L] = max(Dll[one2two[L][0]], Dll[one2two[L][1]] )
Dll['N'] = 0.0
Dll['B'] = 0.0 | def _compute_ambig_ll(self) | m._compute_ambig_ll() -- Extend log-likelihood matrix to include ambiguity codes
e.g. What the score of a 'S'? Here we use the max of C and G. | 5.859175 | 5.072982 | 1.154976 |
prevlett = {'B':'A', 'D':'C', 'V':'T', 'H':'G'}
countmat = []
text = re.sub('[\.\-]','N',text.upper())
for i in range(len(text)):
D = {'A': 0, 'C': 0, 'T':0, 'G':0}
letter = text[i]
if letter in ['B', 'D', 'V', 'H']: #B == no "A", etc...
... | def compute_from_text(self,text,beta=0.001) | m.compute_from_text(,text,beta=0.001) -- Compute a matrix values from a text string of ambiguity codes.
Use Motif_from_text utility instead to build motifs on the fly. | 4.648298 | 4.524796 | 1.027294 |
counts = []
for pos in self.logP:
D = {}
for L,lp in pos.items():
D[L] = math.pow(2.0,lp)
counts.append(D)
self.background = bg
self.compute_from_counts(counts,0) | def new_bg(self,bg) | m.new_bg(,bg) -- Change the ACGT background frequencies to those in the supplied dictionary.
Recompute log-likelihood, etc. with new background. | 7.181648 | 6.393615 | 1.123253 |
self.counts = countmat
self.width = len(countmat)
self.bgscale = 0
maxcount = 0
#Determine Biggest column
for col in countmat:
tot = 0
for v in col.values():
tot = tot + v
if tot > maxcount: maxcount = tot
... | def compute_from_counts(self,countmat,beta=0) | m.compute_from_counts(,countmat,beta=0) -- Utility function to build a motif object from a matrix of letter counts. | 4.873546 | 4.765066 | 1.022766 |
pow = math.pow
bgATtot = 0
nocount = 0
near0 = lambda x:(-0.01 < x and x < 0.01)
for i in range(self.width):
_D = self.ll[i]
ATtot = pow(2,_D['A']) + pow(2,_D['T'])
GCtot = pow(2,_D['C']) + pow(2,_D['G'])
if near... | def _compute_bg_from_ll(self) | m._compute_bg_from_ll()
Compute background model from log-likelihood matrix
by noting that: pA + pT + pC + pG = 1
and bgA + bgT + bgC + bgG = 1
and bgA = bgT, bgC = bgG
and so bgA = 0.5 - bgC
and pA = lA * bgA... | 3.234607 | 2.937579 | 1.101113 |
log = math.log
logP = []
for i in range(self.width):
D = {}
for L in ACGT:
''' if ll = log(p/b) then
2^ll = p/b
and ll = log(p) - log(b)
so log(p) = ll + log(b)'''
#Pi... | def _compute_logP_from_ll(self) | m._compute_logP_from_ll() -- Compute self's logP matrix from the self.ll (log-likelihood) | 6.468678 | 6.382406 | 1.013517 |
print "# ",
for i in range(self.width):
print " %4d "%i,
print
for L in ['A', 'C', 'T', 'G']:
print "#%s "%L,
for i in range(self.width):
print "%8.3f "%self.ll[i][L],
print | def _print_ll(self) | m._print_ll() -- Print log-likelihood (scoring) matrix | 4.262951 | 4.175003 | 1.021065 |
print "# ",
for i in range(self.width):
print " %4d "%i,
print
for L in ['A', 'C', 'T', 'G']:
print "#%s "%L,
for i in range(self.width):
print "%8.3f "%math.pow(2,self.logP[i][L]),
print | def _print_p(self) | m._print_p() -- Print probability (frequency) matrix | 4.886549 | 4.50252 | 1.085292 |
print "# ",
for i in range(self.width):
print " %4d "%i,
print
for L in ['A', 'C', 'T', 'G']:
print "#%s "%L,
for i in range(self.width):
print "%8.3f "%self.counts[i][L],
print | def _print_counts(self) | m._print_counts() -- Print count matrix | 4.240921 | 3.929869 | 1.079151 |
total = 0
lowtot= 0
for lli in self.ll:
total = total + max(lli.values())
lowtot= lowtot+ min(lli.values())
self.maxscore = total
self.minscore = lowtot | def _maxscore(self) | m._maxscore() -- Sets self.maxscore and self.minscore | 5.063468 | 4.416449 | 1.146502 |
scoretally = []
for seq in self.seqs:
matches,endpoints,scores = self.scan(seq,-100)
scoretally.append(scores[0])
ave,std = avestd(scoretally)
self.threshold = ave - z *std | def _compute_threshold(self,z=2.0) | m._compute_threshold(z=2.0) -- For Motif objects assembled from a set of sequence,
compute a self.threshold with a z-score based on the distribution
of scores in among the original input sequences. | 9.713646 | 8.753219 | 1.109723 |
matches,endpoints,scores = self.scan(seq,-100)
t = zip(scores,matches)
t.sort()
bestseq = t[-1][1]
bestscore = t[-1][0]
return bestscore, bestseq | def bestscanseq(self,seq) | m.bestscanseq(seq) -- Return score,sequence of the best match to the motif in the supplied sequence | 5.901181 | 5.186175 | 1.137868 |
matches,endpoints,scores = self.scan(seq,-100)
if not scores: return -100
scores.sort()
best = scores[-1]
return best | def bestscan(self,seq) | m.bestscan(seq) -- Return the score of the best match to the motif in the supplied sequence | 7.050034 | 6.334625 | 1.112936 |
ans = []
txts,endpoints,scores = self.scan(seq,factor=factor)
for txt, startstop in zip(txts,endpoints):
start, stop = startstop
rctxt = revcomplement(txt)
orient = (self.bestscore(txt,1) >= self.bestscore(rctxt,1))
ans.append((start,orie... | def matchstartorient(self,seq, factor=0.7) | m.matchstartorient(,seq, factor=0.7) -- Returns list of (start,orientation) coordinate pairs of
matches to the motif in the supplied sequence. Factor
is multiplied by m.maxscore to get a match threshold. | 6.838783 | 6.388735 | 1.070444 |
if len(seq) < self.width:
return(self._scan_smaller(seq,threshold))
else:
return(self._scan(seq,threshold,factor=factor)) | def scan(self, seq, threshold = '', factor=0.7) | m.scan(seq, threshold = '', factor=0.7) -- Scan the sequence. Returns three lists:
matching sequences, endpoints, and scores. The value of
'factor' is multiplied by m.maxscore to get a match threshold
... | 4.549453 | 4.983711 | 0.912864 |
ll = self.ll
sum = 0
width = self.width
width_r = range(width)
width_rcr = range(width-1,-1,-1)
width_ranges = zip(width_r,width_rcr)
seqcomp = seq.translate(revcompTBL)
total = 0
hits = 0
etotal= 0
fo... | def scansum(self,seq,threshold = -1000) | m.scansum(seq,threshold = -1000) -- Sum of scores over every window in the sequence. Returns
total, number of matches above threshold, average score, sum of exp(score) | 3.779214 | 3.571731 | 1.05809 |
matches, endpoints, scores = self._scan(seq,threshold=-100000,forw_only=fwd)
return scores[0] | def score(self, seq, fwd='Y') | m.score(seq, fwd='Y') -- Returns the score of the first w-bases of the sequence, where w is the motif width. | 16.614832 | 14.879189 | 1.116649 |
matches, endpoints, scores = self._scan(seq,threshold=-100000,forw_only=fwd)
if scores: return max(scores)
else: return -1000 | def bestscore(self,seq, fwd='') | m.bestscore(seq, fwd='') -- Returns the score of the best matching subsequence in seq. | 9.635489 | 9.903688 | 0.972919 |
ll = self.ll #Shortcut for Log-likelihood matrix
if not threshold: threshold = factor * self.maxscore
#print '%5.3f'%(threshold/self.maxscore)
matches = []
endpoints = []
scores = []
width = self.width
width_r ... | def _scan(self, seq,threshold='',forw_only='',factor=0.7) | m._scan(seq,threshold='',forw_only='',factor=0.7) -- Internal tility function for performing sequence scans | 3.89871 | 3.908371 | 0.997528 |
ll = self.ll #Shortcut for Log-likelihood matrix
matches = []
endpoints = []
scores = []
w = self.width
oseq = seq
seq = seq.upper()
for offset in range(self.width-len(seq)+1): #Check if +/-1 needed
maximum =... | def _scan_smaller(self, seq, threshold='') | m._scan_smaller(seq, threshold='') -- Internal utility function for performing sequence scans
The sequence is smaller than the PSSM. Are there
good matches to regions of the PSSM? | 3.960349 | 3.893549 | 1.017157 |
masked = ''
matches, endpoints, scores = self.scan(seq)
cursor = 0
for start, stop in endpoints:
masked = masked + seq[cursor:start] + 'N'*self.width
cursor = stop+1
masked = masked + seq[cursor:]
return masked | def mask_seq(self,seq) | m.mask_seq(seq) -- Return a copy of input sequence in which any regions matching m are replaced with strings of N's | 5.884105 | 5.683879 | 1.035227 |
ns = self.seq_neighborhoods(seq,flanksize)
return [self.mask_seq(n) for n in ns] | def masked_neighborhoods(self,seq,flanksize) | m.masked_neighborhoods(seq,flanksize) -- Chop up the input sequence into regions surrounding matches to m. Replace the
subsequences that match the motif with N's. | 3.980549 | 4.613976 | 0.862715 |
subseqs = []
matches, endpoints, scores = self.scan(seq)
laststart, laststop = -1, -1
for start, stop in endpoints:
curstart, curstop = max(0,start-flanksize), min(stop+flanksize,len(seq))
if curstart > laststop:
if laststop != -1:
... | def seq_neighborhoods(self,seq,flanksize) | m.seq_neighborhoods(seq,flanksize) -- Chop up the input sequence into regions surrounding matches to the motif. | 2.710064 | 2.656657 | 1.020103 |
POW = math.pow
D = 0
for i in range(self.width):
_min = 100
_max = -100
for L in ACGT:
val = POW(2,self.logP[i][L])
if val > _max:
_max = val
_maxL = L
elif va... | def maxdiff(self) | m.maxdiff() -- Compute maximum possible Euclidean distance to another motif. (For normalizing?) | 3.70001 | 3.559167 | 1.039572 |
for start in range(0,self.width-1):
if self.bits[start]>=thresh: break
for stop in range(self.width,1,-1):
if self.bits[stop-1]>=thresh: break
m = self[start,stop]
return m | def trimmed(self,thresh=0.1) | m.trimmed(,thresh=0.1) -- Return motif with low-information flanks removed. 'thresh' is in bits. | 3.790698 | 3.3689 | 1.125203 |
if not thresh:
if self._bestseqs:
return self._bestseqs
if not thresh: thresh = 0.8 * self.maxscore
self._bestseqs = bestseqs(self,thresh)
return self._bestseqs | def bestseqs(self,thresh=None) | m.bestseqs(,thresh=None) -- Return all k-mers that match motif with a score >= thresh | 3.743626 | 3.841366 | 0.974556 |
if not self.cumP:
for logcol in self.logP:
tups = []
for L in ACGT:
p = math.pow(2,logcol[L])
tups.append((p,L))
tups.sort()
cumu = []
tot = 0
for p,L in ... | def emit(self,prob_min=0.0,prob_max=1.0) | m.emit(,prob_min=0.0,prob_max=1.0) -- Consider motif as a generative model, and have it emit a sequence | 4.131269 | 4.173119 | 0.989972 |
if not self._bestseqs: self._bestseqs = self.bestseqs()
seqs = self._bestseqs
pos = int(random() * len(seqs))
print 'Random: ',self.oneletter,seqs[pos][1]
return(seqs[pos][1]) | def random_kmer(self) | m.random_kmer() -- Generate one of the many k-mers that matches the motif. See m.emit() for a more probabilistic generator | 8.097193 | 7.648842 | 1.058617 |
a = Motif()
a.__dict__ = self.__dict__.copy()
return a | def copy(self) | m.copy() -- Return a 'deep' copy of the motif | 7.568892 | 4.304903 | 1.758203 |
POW = math.pow
#Build p-value inspired matrix
#Make totals cummulative:
# A: 0.1 C: 0.4 T:0.2 G:0.3
# -> A:0.0 C:0.1 T:0.5 G:0.7 0.0
#Take bg into account:
# We want to pick P' for each letter such that:
# ... | def bogus_kmers(self,count=200) | m.bogus_kmers(count=200) -- Generate a faked multiple sequence alignment that will reproduce
the probability matrix. | 5.647485 | 5.583714 | 1.011421 |
self.clear()
self.delete(self.session_key)
self.create() | def flush(self) | Removes the current session data from the database and regenerates the
key. | 19.403479 | 6.37943 | 3.041569 |
actual_decorator = method_decorator(decorator)
if inspect.isfunction(obj):
wrapped_obj = actual_decorator(obj)
update_wrapper(wrapped_obj, obj, assigned=available_attrs(obj))
elif inspect.isclass(obj):
for method_name in obj.http_method_names:
if hasattr(obj, method... | def wrap_object(obj, decorator) | Decorates the given object with the decorator function.
If obj is a method, the method is decorated with the decorator function
and returned. If obj is a class (i.e., a class based view), the methods
in the class corresponding to HTTP methods will be decorated and the
resultant class object will be ret... | 2.298896 | 2.214323 | 1.038194 |
column = index.column()
if index.isValid():
if column in [C.COL_START, C.COL_END]:
# return Qt.ItemFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
return Qt.ItemFlags(Qt.ItemIsEnabled)
else:
return Qt.ItemFlags(Qt.ItemIsEnabl... | def flags(self, index) | Override Qt method | 2.20929 | 2.176789 | 1.01493 |
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
return to_qvariant(int(Qt.AlignRight | Qt.AlignVCenter))
elif role == Qt.DisplayRole and orientation == Qt.Horizontal:
... | def headerData(self, section, orientation, role=Qt.DisplayRole) | Override Qt method | 1.995792 | 1.95817 | 1.019213 |
package_data = self._packages.get(name)
versions = []
if package_data:
versions = sort_versions(list(package_data.get('versions', [])))
return versions | def get_package_versions(self, name) | Gives all the compatible package canonical name
name : str
Name of the package | 3.949102 | 4.402312 | 0.897052 |
main = self.main
main.add_dockwidget(self)
#if getattr(main.projectexplorer, 'sig_project_closed', False):
# pe = main.projectexplorer
# pe.condamanager = self
# pe.sig_project_closed.connect(self.project_closed)
# pe.sig_project_loaded.conne... | def register_plugin(self) | Register plugin in Spyder's main window | 4.643682 | 4.02992 | 1.152302 |
if self.busy:
answer = QMessageBox.question(
self,
'Conda Manager',
'Conda Manager is still busy.\n\nDo you want to quit?',
buttons=QMessageBox.Yes | QMessageBox.No)
if answer == QMessageBox.Yes:
re... | def closing_plugin(self, cancelable=False) | Perform actions before parent main window is closed. | 3.420193 | 3.085303 | 1.108544 |
def get_conf_path(filename=None):
conf_dir = osp.join(get_home_dir(), '.condamanager')
if not osp.isdir(conf_dir):
os.mkdir(conf_dir)
if filename is None:
return conf_dir
else:
return osp.join(conf_dir, filename) | Return absolute path for configuration file with specified filename. | null | null | null | |
def sort_versions(versions=(), reverse=False, sep=u'.'):
if versions == []:
return []
digits = u'0123456789'
def toint(x):
try:
n = int(x)
except:
n = x
return n
versions = list(versions)
new_versions, alpha, sizes = [], se... | Sort a list of version number strings.
This function ensures that the package sorting based on number name is
performed correctly when including alpha, dev rc1 etc... | null | null | null | |
fname_parts = [str(part) for part in fname_parts]
# try to create the directory
if len(fname_parts) > 1:
try:
os.makedirs(os.path.join(*fname_parts[:-1]))
except OSError:
pass
# write file
fhandle = open(os.path.join(*fname_parts), "w")
fhandle.write... | def write_file(fname_parts, content) | write a file and create all needed directories | 2.188493 | 1.968113 | 1.111975 |
self._filter_string = text.lower()
self._filter_status = status
self.invalidateFilter() | def set_filter(self, text, status) | text : string
The string to be used for pattern matching.
status : int
TODO: add description | 5.206573 | 5.996346 | 0.868291 |
self._filter_functions[name] = new_function
self.invalidateFilter() | def add_filter_function(self, name, new_function) | name : hashable object
The object to be used as the key for
this filter function. Use this object
to remove the filter function in the future.
Typically this is a self descriptive string.
new_function : function
A new function which must take two argu... | 5.746625 | 5.372616 | 1.069614 |
if name in self._filter_functions.keys():
del self._filter_functions[name]
self.invalidateFilter() | def remove_filter_function(self, name) | Removes the filter function associated with name, if it exists.
name : hashable object | 3.453993 | 4.297154 | 0.803786 |
model = self.sourceModel()
# The source model should have a method called row()
# which returns the table row as a python list.
tests = [func(model.row(row_num), self._filter_string,
self._filter_status) for func in
self._filter_functions.value... | def filterAcceptsRow(self, row_num, parent) | Qt override.
Reimplemented from base class to allow the use of custom filtering. | 8.613996 | 7.936473 | 1.085368 |
key = event.key()
if key in [Qt.Key_Escape]:
self.clear_text()
else:
super(LineEditSearch, self).keyPressEvent(event) | def keyPressEvent(self, event) | Qt override. | 3.9397 | 3.489512 | 1.129012 |
if sys.platform.startswith('linux'):
if PY3:
data_files = [('share/applications',
['scripts/condamanager3.desktop']),
('share/pixmaps',
['img_src/condamanager3.png'])]
else:
data_files = [('s... | def get_data_files() | Return data_files in a platform dependent manner | 2.748983 | 2.580233 | 1.065401 |
def get_coding(text):
for line in text.splitlines()[:2]:
result = CODING_RE.search(to_text_string(line))
if result:
return result.group(1)
return None | Function to get the coding of a text.
@param text text to inspect (string)
@return coding string | null | null | null | |
def encode(text, orig_coding):
if orig_coding == 'utf-8-bom':
return BOM_UTF8 + text.encode("utf-8"), 'utf-8-bom'
# Try declared coding spec
coding = get_coding(text)
if coding:
try:
return text.encode(coding), coding
except (UnicodeError, LookupError)... | Function to encode a text.
@param text text to encode (string)
@param orig_coding type of the original coding (string)
@return encoded text and encoding | null | null | null | |
def write(text, filename, encoding='utf-8', mode='wb'):
text, encoding = encode(text, encoding)
with open(filename, mode) as textfile:
textfile.write(text)
return encoding | Write 'text' to file ('filename') assuming 'encoding'
Return (eventually new) encoding | null | null | null | |
def is_text_file(filename):
try:
open(filename)
except Exception:
return False
with open(filename, 'rb') as fid:
try:
CHUNKSIZE = 1024
chunk = fid.read(CHUNKSIZE)
# check for a UTF BOM
for bom in [BOM_UTF8, BOM_UTF16, BO... | Test if the given path is a text-like file.
Adapted from: http://stackoverflow.com/a/3002505
Original Authors: Trent Mick <TrentM@ActiveState.com>
Jorge Orpinel <jorge@orpinel.com> | null | null | null | |
def qapplication(translate=True, test_time=3):
app = QApplication.instance()
if app is None:
app = QApplication(['Conda-Manager'])
app.setApplicationName('Conda-Manager')
if translate:
install_translator(app)
test_travis = os.environ.get('TEST_CI', None)
if te... | Return QApplication instance
Creates it if it doesn't already exist | null | null | null | |
def create_action(parent, text, shortcut=None, icon=None, tip=None,
toggled=None, triggered=None, data=None, menurole=None,
context=Qt.WindowShortcut):
action = QAction(text, parent)
if triggered is not None:
action.triggered.connect(triggered)
if togg... | Create a QAction | null | null | null | |
aes_mode_attr = "MODE_{}".format(mode.upper())
try:
aes_mode = getattr(AES, aes_mode_attr)
except AttributeError:
raise Exception(
"Pycrypto/pycryptodome does not seem to support {}. ".format(aes_mode_attr) +
"If you use pycrypto, you need a version >= 2.7a1 (or ... | def get_aes_mode(mode) | Return pycrypto's AES mode, raise exception if not supported | 4.421311 | 4.034246 | 1.095945 |
proxy_settings_dic = {}
for key in proxy_settings:
proxy = proxy_settings[key]
proxy_config = [m.groupdict() for m in PROXY_RE.finditer(proxy)]
if proxy_config:
proxy_config = proxy_config[0]
host_port = proxy_config.pop('host_port')
if ':' in ho... | def process_proxy_servers(proxy_settings) | Split the proxy conda configuration to be used by the proxy factory. | 2.108007 | 2.054713 | 1.025938 |
proxy_servers = {}
if self._load_rc_func is None:
return proxy_servers
else:
HTTP_PROXY = os.environ.get('HTTP_PROXY')
HTTPS_PROXY = os.environ.get('HTTPS_PROXY')
if HTTP_PROXY:
proxy_servers['http'] = HTTP_PROXY
... | def proxy_servers(self) | Return the proxy servers available.
First env variables will be searched and updated with values from
condarc config file. | 2.315753 | 2.313924 | 1.00079 |
proxy = QNetworkProxy()
proxy_scheme = proxy_setting['scheme']
proxy_host = proxy_setting['host']
proxy_port = proxy_setting['port']
proxy_username = proxy_setting['username']
proxy_password = proxy_setting['password']
proxy_scheme_host = '{0}://{1}'.form... | def _create_proxy(proxy_setting) | Create a Network proxy for the given proxy settings. | 1.938908 | 1.825444 | 1.062157 |
# Query is a QNetworkProxyQuery
valid_proxies = []
query_scheme = query.url().scheme()
query_host = query.url().host()
query_scheme_host = '{0}://{1}'.format(query_scheme, query_host)
proxy_servers = process_proxy_servers(self.proxy_servers)
# print(proxy... | def queryProxy(self, query) | Override Qt method. | 2.47155 | 2.414021 | 1.023831 |
if self._workers:
for url in self._workers.copy():
w = self._workers[url]
if w.is_finished():
self._workers.pop(url)
self._paths.pop(url)
if url in self._get_requests:
self._g... | def _clean(self) | Check for inactive workers and remove their references. | 4.272414 | 3.253959 | 1.31299 |
url = to_text_string(reply.url().toEncoded(), encoding='utf-8')
if url in self._paths:
path = self._paths[url]
if url in self._workers:
worker = self._workers[url]
if url in self._head_requests:
error = reply.error()
# print(url, ... | def _request_finished(self, reply) | Callback for download once the request has finished. | 3.32036 | 3.263013 | 1.017575 |
worker = self._workers[url]
path = self._paths[url]
if len(data):
try:
with open(path, 'wb') as f:
f.write(data)
except Exception:
logger.error((url, path))
# Clean up
worker.finished = True
... | def _save(self, url, path, data) | Save `data` of downloaded `url` in `path`. | 3.654471 | 3.522732 | 1.037397 |
worker.sig_download_progress.emit(
worker.url, worker.path, bytes_received, bytes_total) | def _progress(bytes_received, bytes_total, worker) | Return download progress. | 6.131858 | 5.59334 | 1.096279 |
# original_url = url
# print(url)
qurl = QUrl(url)
url = to_text_string(qurl.toEncoded(), encoding='utf-8')
logger.debug(str((url, path)))
if url in self._workers:
while not self._workers[url].finished:
return self._workers[url]
... | def download(self, url, path) | Download url and save data to path. | 3.867578 | 3.873932 | 0.99836 |
if self._workers:
for w in self._workers:
if w.is_finished():
self._workers.remove(w)
if self._threads:
for t in self._threads:
if t.isFinished():
self._threads.remove(t)
else:
s... | def _clean(self) | Check for inactive workers and remove their references. | 3.458165 | 2.609223 | 1.325362 |
if len(self._queue) == 1:
thread = self._queue.popleft()
thread.start()
self._timer.start() | def _start(self) | Start the next threaded worker in the queue. | 5.147672 | 3.924834 | 1.311564 |
thread = QThread()
worker = RequestsDownloadWorker(method, args, kwargs)
worker.moveToThread(thread)
worker.sig_finished.connect(self._start)
self._sig_download_finished.connect(worker.sig_download_finished)
self._sig_download_progress.connect(worker.sig_download... | def _create_worker(self, method, *args, **kwargs) | Create a new worker instance. | 2.703141 | 2.679915 | 1.008667 |
if path is None:
path = url.split('/')[-1]
# Make dir if non existent
folder = os.path.dirname(os.path.abspath(path))
if not os.path.isdir(folder):
os.makedirs(folder)
# Start actual download
try:
r = requests.get(url, strea... | def _download(self, url, path=None, force=False) | Callback for download. | 2.527948 | 2.496444 | 1.01262 |
try:
r = requests.head(url, proxies=self.proxy_servers)
value = r.status_code in [200]
except Exception as error:
logger.error(str(error))
value = False
return value | def _is_valid_url(self, url) | Callback for is_valid_url. | 3.594556 | 3.51792 | 1.021784 |
if channel.startswith('https://') or channel.startswith('http://'):
url = channel
else:
url = "{0}/{1}".format(conda_url, channel)
if url[-1] == '/':
url = url[:-1]
plat = self._conda_api.get_platform()
repodata_url = "{0}/{1}/{2}".f... | def _is_valid_channel(self, channel,
conda_url='https://conda.anaconda.org') | Callback for is_valid_channel. | 2.576944 | 2.585941 | 0.996521 |
# Check response is a JSON with ok: 1
data = {}
try:
r = requests.get(url, proxies=self.proxy_servers)
content = to_text_string(r.content, encoding='utf-8')
data = json.loads(content)
except Exception as error:
logger.error(str(err... | def _is_valid_api_url(self, url) | Callback for is_valid_api_url. | 4.468867 | 4.364021 | 1.024025 |
logger.debug(str((url, path, force)))
method = self._download
return self._create_worker(method, url, path=path, force=force) | def download(self, url, path=None, force=False) | Download file given by url and save it to path. | 5.763758 | 5.932105 | 0.971621 |
for t in self._threads:
t.quit()
self._thread = []
self._workers = [] | def terminate(self) | Terminate all workers and threads. | 8.489159 | 6.88777 | 1.232497 |
logger.debug(str((url)))
if non_blocking:
method = self._is_valid_url
return self._create_worker(method, url)
else:
return self._is_valid_url(url) | def is_valid_url(self, url, non_blocking=True) | Check if url is valid. | 4.74248 | 4.502966 | 1.05319 |
logger.debug(str((url)))
if non_blocking:
method = self._is_valid_api_url
return self._create_worker(method, url)
else:
return self._is_valid_api_url(url=url) | def is_valid_api_url(self, url, non_blocking=True) | Check if anaconda api url is valid. | 4.445009 | 4.183356 | 1.062546 |
logger.debug(str((channel, conda_url)))
if non_blocking:
method = self._is_valid_channel
return self._create_worker(method, channel, conda_url)
else:
return self._is_valid_channel(channel, conda_url=conda_url) | def is_valid_channel(self,
channel,
conda_url='https://conda.anaconda.org',
non_blocking=True) | Check if a conda channel is valid. | 3.541391 | 3.519329 | 1.006269 |
if n < 1024:
return '%d B' % n
k = n/1024
if k < 1024:
return '%d KB' % round(k)
m = k/1024
if m < 1024:
return '%.1f MB' % m
g = m/1024
return '%.2f GB' % g | def human_bytes(n) | Return the number of bytes n in more human readable form. | 1.621147 | 1.605903 | 1.009492 |
def ready_print(worker, output, error): # pragma : no cover
global COUNTER
COUNTER += 1
print(COUNTER, output, error) | Local test helper. | null | null | null | |
raw_stdout = self._process.readAllStandardOutput()
stdout = handle_qbytearray(raw_stdout, _CondaAPI.UTF8)
json_stdout = stdout.replace('\n\x00', '')
try:
json_stdout = json.loads(json_stdout)
except Exception:
json_stdout = stdout
if sel... | def _partial(self) | Callback for partial output. | 5.178411 | 4.958543 | 1.044341 |
self._communicate_first = True
self._process.waitForFinished()
if self._partial_stdout is None:
raw_stdout = self._process.readAllStandardOutput()
stdout = handle_qbytearray(raw_stdout, _CondaAPI.UTF8)
else:
stdout = self._partial_stdout
... | def communicate(self) | Retrieve information. | 4.058939 | 4.037864 | 1.005219 |
logger.debug(str(' '.join(self._cmd_list)))
if not self._fired:
self._partial_ouput = None
self._process.start(self._cmd_list[0], self._cmd_list[1:])
self._timer.start()
else:
raise CondaProcessWorker('A Conda ProcessWorker can only run o... | def start(self) | Start process. | 9.382993 | 8.975432 | 1.045408 |
if self._workers:
for w in self._workers:
if w.is_finished():
self._workers.remove(w)
else:
self._current_worker = None
self._timer.stop() | def _clean(self) | Remove references of inactive workers periodically. | 4.651412 | 3.364269 | 1.382592 |
if abspath:
if sys.platform == 'win32':
python = join(self.ROOT_PREFIX, 'python.exe')
conda = join(self.ROOT_PREFIX, 'Scripts',
'conda-script.py')
else:
python = join(self.ROOT_PREFIX, 'bin/python')
... | def _call_conda(self, extra_args, abspath=True, parse=False,
callback=None) | Call conda with the list of extra arguments, and return the worker.
The result can be force by calling worker.communicate(), which returns
the tuple (stdout, stderr). | 2.811129 | 2.902322 | 0.968579 |
cmd_list = []
if kwargs.get('override_channels', False) and 'channel' not in kwargs:
raise TypeError('conda search: override_channels requires channel')
if 'env' in kwargs:
cmd_list.extend(['--name', kwargs.pop('env')])
if 'prefix' in kwargs:
... | def _setup_install_commands_from_kwargs(kwargs, keys=tuple()) | Setup install commands for conda. | 2.50133 | 2.24569 | 1.113836 |
if prefix:
self.ROOT_PREFIX = prefix
else:
# Find some conda instance, and then use info to get 'root_prefix'
worker = self._call_and_parse(['info', '--json'], abspath=False)
info = worker.communicate()[0]
self.ROOT_PREFIX = info['root... | def set_root_prefix(self, prefix=None) | Set the prefix to the root environment (default is /opt/anaconda).
This function should only be called once (right after importing
conda_api). | 7.913259 | 7.509924 | 1.053707 |
# argparse outputs version to stderr in Python < 3.4.
# http://bugs.python.org/issue18920
pat = re.compile(r'conda:?\s+(\d+\.\d\S+|unknown)')
m = pat.match(stderr.decode().strip())
if m is None:
m = pat.match(stdout.decode().strip())
if m is None:
... | def _get_conda_version(stdout, stderr) | Callback for get_conda_version. | 4.383331 | 4.135399 | 1.059954 |
if log:
logger.debug('')
# return self._call_and_parse(['info', '--json'],
# callback=lambda o, e: o['envs'])
envs = os.listdir(os.sep.join([self.ROOT_PREFIX, 'envs']))
envs = [os.sep.join([self.ROOT_PREFIX, 'envs', i]) for i in envs... | def get_envs(self, log=True) | Return environment list of absolute path to their prefixes. | 4.310095 | 3.934228 | 1.095538 |
prefix = None
if name == 'root':
prefix = self.ROOT_PREFIX
# envs, error = self.get_envs().communicate()
envs = self.get_envs()
for p in envs:
if basename(p) == name:
prefix = p
return prefix | def get_prefix_envname(self, name, log=False) | Return full prefix path of environment defined by `name`. | 6.175536 | 5.445392 | 1.134085 |
logger.debug(str(prefix))
if not isdir(prefix):
return set()
meta_dir = join(prefix, 'conda-meta')
if not isdir(meta_dir):
# We might have nothing in linked (and no conda-meta directory)
return set()
return set(fn[:-5] for fn in os.... | def linked(prefix) | Return set of canonical names of linked packages in `prefix`. | 4.796996 | 4.23746 | 1.132045 |
logger.debug(str(''))
return self._call_and_parse(['info', '--json'], abspath=abspath) | def info(self, abspath=True) | Return a dictionary with configuration information.
No guarantee is made about which keys exist. Therefore this function
should only be used for testing and debugging. | 12.332479 | 13.691631 | 0.900731 |
return self._call_and_parse(['info', package, '--json'],
abspath=abspath) | def package_info(self, package, abspath=True) | Return a dictionary with package information. | 8.008914 | 6.37273 | 1.256748 |
cmd_list = ['search', '--json']
if regex and spec:
raise TypeError('conda search: only one of regex or spec allowed')
if regex:
cmd_list.append(regex)
if spec:
cmd_list.extend(['--spec', spec])
if 'platform' in kwargs:
... | def search(self, regex=None, spec=None, **kwargs) | Search for packages. | 4.026253 | 3.847547 | 1.046447 |
logger.debug(str((name, yamlfile)))
cmd_list = ['env', 'create', '-n', name, '-f', yamlfile, '--json']
return self._call_and_parse(cmd_list) | def create_from_yaml(self, name, yamlfile) | Create new environment using conda-env via a yaml specification file.
Unlike other methods, this calls conda-env, and requires a named
environment and uses channels as defined in rcfiles.
Parameters
----------
name : string
Environment name
yamlfile : string... | 5.35933 | 5.743679 | 0.933083 |
logger.debug(str((prefix, pkgs, channels)))
# TODO: Fix temporal hack
if (not pkgs or (not isinstance(pkgs, (list, tuple)) and
not is_text_string(pkgs))):
raise TypeError('must specify a list of one or more packages to '
... | def create(self, name=None, prefix=None, pkgs=None, channels=None) | Create an environment with a specified set of packages. | 3.60762 | 3.608193 | 0.999841 |
if (token and channel not in self.DEFAULT_CHANNELS and
channel != 'defaults'):
url_parts = channel.split('/')
start = url_parts[:-1]
middle = 't/{0}'.format(token)
end = url_parts[-1]
token_channel = '{0}/{1}/{2}'.format('/'.jo... | def parse_token_channel(self, channel, token) | Adapt a channel to include token of the logged user.
Ignore default channels. | 4.376433 | 4.013099 | 1.090537 |
logger.debug(str((prefix, pkgs, channels)))
# TODO: Fix temporal hack
if not pkgs or not isinstance(pkgs, (list, tuple, str)):
raise TypeError('must specify a list of one or more packages to '
'install into existing environment')
cmd_lis... | def install(self, name=None, prefix=None, pkgs=None, dep=True,
channels=None, token=None) | Install a set of packages into an environment by name or path.
If token is specified, the channels different from the defaults will
get the token appended. | 3.631269 | 3.575278 | 1.015661 |
cmd_list = ['update', '--json', '--yes']
if not pkgs and not kwargs.get('all'):
raise TypeError("Must specify at least one package to update, or "
"all=True.")
cmd_list.extend(
self._setup_install_commands_from_kwargs(
... | def update(self, *pkgs, **kwargs) | Update package(s) (in an environment) by name. | 5.518321 | 5.284918 | 1.044164 |
logger.debug(str((prefix, pkgs)))
cmd_list = ['remove', '--json', '--yes']
if not pkgs and not all_:
raise TypeError("Must specify at least one package to remove, or "
"all=True.")
if name:
cmd_list.extend(['--name', name])
... | def remove(self, name=None, prefix=None, pkgs=None, all_=False) | Remove a package (from an environment) by name.
Returns {
success: bool, (this is always true),
(other information)
} | 3.33738 | 3.327298 | 1.00303 |
return self.remove(name=name, path=path, all=True, **kwargs) | def remove_environment(self, name=None, path=None, **kwargs) | Remove an environment entirely.
See ``remove``. | 4.930683 | 5.275133 | 0.934703 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.