code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def _scan_smaller(self, seq, threshold=''):
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): ... | 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? |
def mask_seq(self,seq):
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 | m.mask_seq(seq) -- Return a copy of input sequence in which any regions matching m are replaced with strings of N's |
def masked_neighborhoods(self,seq,flanksize):
ns = self.seq_neighborhoods(seq,flanksize)
return [self.mask_seq(n) for n in ns] | 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. |
def seq_neighborhoods(self,seq,flanksize):
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:... | m.seq_neighborhoods(seq,flanksize) -- Chop up the input sequence into regions surrounding matches to the motif. |
def maxdiff(self):
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
... | m.maxdiff() -- Compute maximum possible Euclidean distance to another motif. (For normalizing?) |
def trimmed(self,thresh=0.1):
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 | m.trimmed(,thresh=0.1) -- Return motif with low-information flanks removed. 'thresh' is in bits. |
def bestseqs(self,thresh=None):
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 | m.bestseqs(,thresh=None) -- Return all k-mers that match motif with a score >= thresh |
def emit(self,prob_min=0.0,prob_max=1.0):
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 = []
... | m.emit(,prob_min=0.0,prob_max=1.0) -- Consider motif as a generative model, and have it emit a sequence |
def random_kmer(self):
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]) | m.random_kmer() -- Generate one of the many k-mers that matches the motif. See m.emit() for a more probabilistic generator |
def copy(self):
a = Motif()
a.__dict__ = self.__dict__.copy()
return a | m.copy() -- Return a 'deep' copy of the motif |
def bogus_kmers(self,count=200):
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 e... | m.bogus_kmers(count=200) -- Generate a faked multiple sequence alignment that will reproduce
the probability matrix. |
def flush(self):
self.clear()
self.delete(self.session_key)
self.create() | Removes the current session data from the database and regenerates the
key. |
def wrap_object(obj, decorator):
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:
... | 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... |
def flags(self, index):
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.... | Override Qt method |
def headerData(self, section, orientation, role=Qt.DisplayRole):
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 ro... | Override Qt method |
def get_package_versions(self, name):
package_data = self._packages.get(name)
versions = []
if package_data:
versions = sort_versions(list(package_data.get('versions', [])))
return versions | Gives all the compatible package canonical name
name : str
Name of the package |
def register_plugin(self):
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)
# ... | Register plugin in Spyder's main window |
def closing_plugin(self, cancelable=False):
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 a... | Perform actions before parent main window is closed. |
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. |
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... |
def write_file(fname_parts, content):
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... | write a file and create all needed directories |
def set_filter(self, text, status):
self._filter_string = text.lower()
self._filter_status = status
self.invalidateFilter() | text : string
The string to be used for pattern matching.
status : int
TODO: add description |
def add_filter_function(self, name, new_function):
self._filter_functions[name] = new_function
self.invalidateFilter() | 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... |
def remove_filter_function(self, name):
if name in self._filter_functions.keys():
del self._filter_functions[name]
self.invalidateFilter() | Removes the filter function associated with name, if it exists.
name : hashable object |
def filterAcceptsRow(self, row_num, parent):
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
... | Qt override.
Reimplemented from base class to allow the use of custom filtering. |
def keyPressEvent(self, event):
key = event.key()
if key in [Qt.Key_Escape]:
self.clear_text()
else:
super(LineEditSearch, self).keyPressEvent(event) | Qt override. |
def get_data_files():
if sys.platform.startswith('linux'):
if PY3:
data_files = [('share/applications',
['scripts/condamanager3.desktop']),
('share/pixmaps',
['img_src/condamanager3.png'])]
else:
... | Return data_files in a platform dependent manner |
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 |
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 |
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 |
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> |
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 |
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 |
def get_aes_mode(mode):
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... | Return pycrypto's AES mode, raise exception if not supported |
def process_proxy_servers(proxy_settings):
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_confi... | Split the proxy conda configuration to be used by the proxy factory. |
def proxy_servers(self):
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... | Return the proxy servers available.
First env variables will be searched and updated with values from
condarc config file. |
def _create_proxy(proxy_setting):
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']
pr... | Create a Network proxy for the given proxy settings. |
def queryProxy(self, query):
# 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_... | Override Qt method. |
def _clean(self):
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:
... | Check for inactive workers and remove their references. |
def _request_finished(self, reply):
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 = re... | Callback for download once the request has finished. |
def _save(self, url, path, data):
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... | Save `data` of downloaded `url` in `path`. |
def _progress(bytes_received, bytes_total, worker):
worker.sig_download_progress.emit(
worker.url, worker.path, bytes_received, bytes_total) | Return download progress. |
def download(self, url, path):
# 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:
r... | Download url and save data to path. |
def _clean(self):
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)
e... | Check for inactive workers and remove their references. |
def _start(self):
if len(self._queue) == 1:
thread = self._queue.popleft()
thread.start()
self._timer.start() | Start the next threaded worker in the queue. |
def _create_worker(self, method, *args, **kwargs):
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... | Create a new worker instance. |
def _download(self, url, path=None, force=False):
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
... | Callback for download. |
def _is_valid_url(self, url):
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 | Callback for is_valid_url. |
def _is_valid_channel(self, channel,
conda_url='https://conda.anaconda.org'):
if channel.startswith('https://') or channel.startswith('http://'):
url = channel
else:
url = "{0}/{1}".format(conda_url, channel)
if url[-1] == '/':
... | Callback for is_valid_channel. |
def _is_valid_api_url(self, url):
# 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... | Callback for is_valid_api_url. |
def download(self, url, path=None, force=False):
logger.debug(str((url, path, force)))
method = self._download
return self._create_worker(method, url, path=path, force=force) | Download file given by url and save it to path. |
def terminate(self):
for t in self._threads:
t.quit()
self._thread = []
self._workers = [] | Terminate all workers and threads. |
def is_valid_url(self, url, non_blocking=True):
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) | Check if url is valid. |
def is_valid_api_url(self, url, non_blocking=True):
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) | Check if anaconda api url is valid. |
def is_valid_channel(self,
channel,
conda_url='https://conda.anaconda.org',
non_blocking=True):
logger.debug(str((channel, conda_url)))
if non_blocking:
method = self._is_valid_channel
return self... | Check if a conda channel is valid. |
def human_bytes(n):
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 | Return the number of bytes n in more human readable form. |
def ready_print(worker, output, error): # pragma : no cover
global COUNTER
COUNTER += 1
print(COUNTER, output, error) | Local test helper. |
def _partial(self):
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 = st... | Callback for partial output. |
def communicate(self):
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 = se... | Retrieve information. |
def start(self):
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 ProcessWork... | Start process. |
def _clean(self):
if self._workers:
for w in self._workers:
if w.is_finished():
self._workers.remove(w)
else:
self._current_worker = None
self._timer.stop() | Remove references of inactive workers periodically. |
def _call_conda(self, extra_args, abspath=True, parse=False,
callback=None):
if abspath:
if sys.platform == 'win32':
python = join(self.ROOT_PREFIX, 'python.exe')
conda = join(self.ROOT_PREFIX, 'Scripts',
'cond... | 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). |
def _setup_install_commands_from_kwargs(kwargs, keys=tuple()):
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',... | Setup install commands for conda. |
def set_root_prefix(self, prefix=None):
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]
... | Set the prefix to the root environment (default is /opt/anaconda).
This function should only be called once (right after importing
conda_api). |
def _get_conda_version(stdout, stderr):
# 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.dec... | Callback for get_conda_version. |
def get_envs(self, log=True):
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_PRE... | Return environment list of absolute path to their prefixes. |
def get_prefix_envname(self, name, log=False):
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 full prefix path of environment defined by `name`. |
def linked(prefix):
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(f... | Return set of canonical names of linked packages in `prefix`. |
def info(self, abspath=True):
logger.debug(str(''))
return self._call_and_parse(['info', '--json'], abspath=abspath) | 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. |
def package_info(self, package, abspath=True):
return self._call_and_parse(['info', package, '--json'],
abspath=abspath) | Return a dictionary with package information. |
def search(self, regex=None, spec=None, **kwargs):
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', sp... | Search for packages. |
def create_from_yaml(self, name, yamlfile):
logger.debug(str((name, yamlfile)))
cmd_list = ['env', 'create', '-n', name, '-f', yamlfile, '--json']
return self._call_and_parse(cmd_list) | 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... |
def create(self, name=None, prefix=None, pkgs=None, channels=None):
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 spec... | Create an environment with a specified set of packages. |
def parse_token_channel(self, channel, token):
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]
... | Adapt a channel to include token of the logged user.
Ignore default channels. |
def install(self, name=None, prefix=None, pkgs=None, dep=True,
channels=None, token=None):
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 ... | 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. |
def update(self, *pkgs, **kwargs):
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_c... | Update package(s) (in an environment) by name. |
def remove(self, name=None, prefix=None, pkgs=None, all_=False):
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.")... | Remove a package (from an environment) by name.
Returns {
success: bool, (this is always true),
(other information)
} |
def remove_environment(self, name=None, path=None, **kwargs):
return self.remove(name=name, path=path, all=True, **kwargs) | Remove an environment entirely.
See ``remove``. |
def clone_environment(self, clone, name=None, prefix=None, **kwargs):
cmd_list = ['create', '--json']
if (name and prefix) or not (name or prefix):
raise TypeError("conda clone_environment: exactly one of `name` "
"or `path` required")
if name:
... | Clone the environment `clone` into `name` or `prefix`. |
def _setup_config_from_kwargs(kwargs):
cmd_list = ['--json', '--force']
if 'file' in kwargs:
cmd_list.extend(['--file', kwargs['file']])
if 'system' in kwargs:
cmd_list.append('--system')
return cmd_list | Setup config commands for conda. |
def config_add(self, key, value, **kwargs):
cmd_list = ['config', '--add', key, value]
cmd_list.extend(self._setup_config_from_kwargs(kwargs))
return self._call_and_parse(
cmd_list,
abspath=kwargs.get('abspath', True),
callback=lambda o, e: o.get('wa... | Add a value to a key.
Returns a list of warnings Conda may have emitted. |
def dependencies(self, name=None, prefix=None, pkgs=None, channels=None,
dep=True):
if not pkgs or not isinstance(pkgs, (list, tuple)):
raise TypeError('must specify a list of one or more packages to '
'install into existing environment')
... | Get dependenciy list for packages to be installed in an env. |
def environment_exists(self, name=None, prefix=None, abspath=True,
log=True):
if log:
logger.debug(str((name, prefix)))
if name and prefix:
raise TypeError("Exactly one of 'name' or 'prefix' is required.")
if name:
prefix ... | Check if an environment exists by 'name' or by 'prefix'.
If query is by 'name' only the default conda environments directory is
searched. |
def clear_lock(self, abspath=True):
cmd_list = ['clean', '--lock', '--json']
return self._call_and_parse(cmd_list, abspath=abspath) | Clean any conda lock in the system. |
def package_version(self, prefix=None, name=None, pkg=None, build=False):
package_versions = {}
if name and prefix:
raise TypeError("Exactly one of 'name' or 'prefix' is required.")
if name:
prefix = self.get_prefix_envname(name)
if self.environment_ex... | Get installed package version in a given env. |
def get_platform():
_sys_map = {'linux2': 'linux', 'linux': 'linux',
'darwin': 'osx', 'win32': 'win', 'openbsd5': 'openbsd'}
non_x86_linux_machines = {'armv6l', 'armv7l', 'ppc64le'}
sys_platform = _sys_map.get(sys.platform, 'unknown')
bits = 8 * tuple.__item... | Get platform of current system (system and bitness). |
def load_rc(self, path=None, system=False):
if os.path.isfile(self.user_rc_path) and not system:
path = self.user_rc_path
elif os.path.isfile(self.sys_rc_path):
path = self.sys_rc_path
if not path or not os.path.isfile(path):
return {}
with ... | Load the conda configuration file.
If both user and system configuration exists, user will be used. |
def get_condarc_channels(self,
normalize=False,
conda_url='https://conda.anaconda.org',
channels=None):
# https://docs.continuum.io/anaconda-repository/configuration
# They can only exist on a system condarc
... | Return all the channel urls defined in .condarc.
If no condarc file is found, use the default channels.
the `default_channel_alias` key is ignored and only the anaconda client
`url` key is used. |
def _call_pip(self, name=None, prefix=None, extra_args=None,
callback=None):
cmd_list = self._pip_cmd(name=name, prefix=prefix)
cmd_list.extend(extra_args)
process_worker = ProcessWorker(cmd_list, pip=True, callback=callback)
process_worker.sig_finished.connec... | Call pip in QProcess worker. |
def _pip_cmd(self, name=None, prefix=None):
if (name and prefix) or not (name or prefix):
raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
"required.")
if name and self.environment_exists(name=name):
prefix = self.get_prefix_... | Get pip location based on environment `name` or `prefix`. |
def pip_list(self, name=None, prefix=None, abspath=True):
if (name and prefix) or not (name or prefix):
raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
"required.")
if name:
prefix = self.get_prefix_envname(name)
pi... | Get list of pip installed packages. |
def _pip_list(self, stdout, stderr, prefix=None):
result = stdout # A dict
linked = self.linked(prefix)
pip_only = []
linked_names = [self.split_canonical_name(l)[0] for l in linked]
for pkg in result:
name = self.split_canonical_name(pkg)[0]
... | Callback for `pip_list`. |
def pip_remove(self, name=None, prefix=None, pkgs=None):
logger.debug(str((prefix, pkgs)))
if isinstance(pkgs, (list, tuple)):
pkg = ' '.join(pkgs)
else:
pkg = pkgs
extra_args = ['uninstall', '--yes', pkg]
return self._call_pip(name=name, prefi... | Remove a pip package in given environment by `name` or `prefix`. |
def pip_search(self, search_string=None):
extra_args = ['search', search_string]
return self._call_pip(name='root', extra_args=extra_args,
callback=self._pip_search) | Search for pip packages in PyPI matching `search_string`. |
def _pip_search(stdout, stderr):
result = {}
lines = to_text_string(stdout).split('\n')
while '' in lines:
lines.remove('')
for line in lines:
if ' - ' in line:
parts = line.split(' - ')
name = parts[0].strip()
... | Callback for pip search. |
def _timer_update(self):
self._timer_counter += 1
dot = self._timer_dots.pop(0)
self._timer_dots = self._timer_dots + [dot]
self._rows = [[_(u'Resolving dependencies') + dot, u'', u'', u'']]
index = self.createIndex(0, 0)
self.dataChanged.emit(index, index)
... | Add some moving points to the dependency resolution text. |
def flags(self, index):
if not index.isValid():
return Qt.ItemIsEnabled
column = index.column()
if column in [0, 1, 2, 3]:
return Qt.ItemFlags(Qt.ItemIsEnabled)
else:
return Qt.ItemFlags(Qt.NoItemFlags) | Override Qt method |
def data(self, index, role=Qt.DisplayRole):
if not index.isValid() or not 0 <= index.row() < len(self._rows):
return to_qvariant()
row = index.row()
column = index.column()
# Carefull here with the order, this has to be adjusted manually
if self._rows[row] =... | Override Qt method |
def start(self):
error, output = None, None
try:
time.sleep(0.1)
output = self.method(*self.args, **self.kwargs)
except Exception as err:
logger.debug(str((self.method.__module__, self.method.__name__,
err)))
... | Start the worker process. |
def _create_worker(self, method, *args, **kwargs):
# FIXME: this might be heavy...
thread = QThread()
worker = ClientWorker(method, args, kwargs)
worker.moveToThread(thread)
worker.sig_finished.connect(self._start)
worker.sig_finished.connect(thread.quit)
... | Create a worker for this client to be run in a separate thread. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.