id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
242,100 | johnwheeler/flask-ask | flask_ask/core.py | Ask._map_player_request_to_func | def _map_player_request_to_func(self, player_request_type):
"""Provides appropriate parameters to the on_playback functions."""
# calbacks for on_playback requests are optional
view_func = self._intent_view_funcs.get(player_request_type, lambda: None)
argspec = inspect.getargspec(view_func)
arg_names = argspec.args
arg_values = self._map_params_to_view_args(player_request_type, arg_names)
return partial(view_func, *arg_values) | python | def _map_player_request_to_func(self, player_request_type):
# calbacks for on_playback requests are optional
view_func = self._intent_view_funcs.get(player_request_type, lambda: None)
argspec = inspect.getargspec(view_func)
arg_names = argspec.args
arg_values = self._map_params_to_view_args(player_request_type, arg_names)
return partial(view_func, *arg_values) | [
"def",
"_map_player_request_to_func",
"(",
"self",
",",
"player_request_type",
")",
":",
"# calbacks for on_playback requests are optional",
"view_func",
"=",
"self",
".",
"_intent_view_funcs",
".",
"get",
"(",
"player_request_type",
",",
"lambda",
":",
"None",
")",
"ar... | Provides appropriate parameters to the on_playback functions. | [
"Provides",
"appropriate",
"parameters",
"to",
"the",
"on_playback",
"functions",
"."
] | fe407646ae404a8c90b363c86d5c4c201b6a5580 | https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L842-L851 |
242,101 | johnwheeler/flask-ask | flask_ask/core.py | Ask._map_purchase_request_to_func | def _map_purchase_request_to_func(self, purchase_request_type):
"""Provides appropriate parameters to the on_purchase functions."""
if purchase_request_type in self._intent_view_funcs:
view_func = self._intent_view_funcs[purchase_request_type]
else:
raise NotImplementedError('Request type "{}" not found and no default view specified.'.format(purchase_request_type))
argspec = inspect.getargspec(view_func)
arg_names = argspec.args
arg_values = self._map_params_to_view_args(purchase_request_type, arg_names)
print('_map_purchase_request_to_func', arg_names, arg_values, view_func, purchase_request_type)
return partial(view_func, *arg_values) | python | def _map_purchase_request_to_func(self, purchase_request_type):
if purchase_request_type in self._intent_view_funcs:
view_func = self._intent_view_funcs[purchase_request_type]
else:
raise NotImplementedError('Request type "{}" not found and no default view specified.'.format(purchase_request_type))
argspec = inspect.getargspec(view_func)
arg_names = argspec.args
arg_values = self._map_params_to_view_args(purchase_request_type, arg_names)
print('_map_purchase_request_to_func', arg_names, arg_values, view_func, purchase_request_type)
return partial(view_func, *arg_values) | [
"def",
"_map_purchase_request_to_func",
"(",
"self",
",",
"purchase_request_type",
")",
":",
"if",
"purchase_request_type",
"in",
"self",
".",
"_intent_view_funcs",
":",
"view_func",
"=",
"self",
".",
"_intent_view_funcs",
"[",
"purchase_request_type",
"]",
"else",
":... | Provides appropriate parameters to the on_purchase functions. | [
"Provides",
"appropriate",
"parameters",
"to",
"the",
"on_purchase",
"functions",
"."
] | fe407646ae404a8c90b363c86d5c4c201b6a5580 | https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L853-L866 |
242,102 | johnwheeler/flask-ask | flask_ask/cache.py | push_stream | def push_stream(cache, user_id, stream):
"""
Push a stream onto the stream stack in cache.
:param cache: werkzeug BasicCache-like object
:param user_id: id of user, used as key in cache
:param stream: stream object to push onto stack
:return: True on successful update,
False if failed to update,
None if invalid input was given
"""
stack = cache.get(user_id)
if stack is None:
stack = []
if stream:
stack.append(stream)
return cache.set(user_id, stack)
return None | python | def push_stream(cache, user_id, stream):
stack = cache.get(user_id)
if stack is None:
stack = []
if stream:
stack.append(stream)
return cache.set(user_id, stack)
return None | [
"def",
"push_stream",
"(",
"cache",
",",
"user_id",
",",
"stream",
")",
":",
"stack",
"=",
"cache",
".",
"get",
"(",
"user_id",
")",
"if",
"stack",
"is",
"None",
":",
"stack",
"=",
"[",
"]",
"if",
"stream",
":",
"stack",
".",
"append",
"(",
"stream... | Push a stream onto the stream stack in cache.
:param cache: werkzeug BasicCache-like object
:param user_id: id of user, used as key in cache
:param stream: stream object to push onto stack
:return: True on successful update,
False if failed to update,
None if invalid input was given | [
"Push",
"a",
"stream",
"onto",
"the",
"stream",
"stack",
"in",
"cache",
"."
] | fe407646ae404a8c90b363c86d5c4c201b6a5580 | https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/cache.py#L6-L24 |
242,103 | johnwheeler/flask-ask | flask_ask/cache.py | pop_stream | def pop_stream(cache, user_id):
"""
Pop an item off the stack in the cache. If stack
is empty after pop, it deletes the stack.
:param cache: werkzeug BasicCache-like object
:param user_id: id of user, used as key in cache
:return: top item from stack, otherwise None
"""
stack = cache.get(user_id)
if stack is None:
return None
result = stack.pop()
if len(stack) == 0:
cache.delete(user_id)
else:
cache.set(user_id, stack)
return result | python | def pop_stream(cache, user_id):
stack = cache.get(user_id)
if stack is None:
return None
result = stack.pop()
if len(stack) == 0:
cache.delete(user_id)
else:
cache.set(user_id, stack)
return result | [
"def",
"pop_stream",
"(",
"cache",
",",
"user_id",
")",
":",
"stack",
"=",
"cache",
".",
"get",
"(",
"user_id",
")",
"if",
"stack",
"is",
"None",
":",
"return",
"None",
"result",
"=",
"stack",
".",
"pop",
"(",
")",
"if",
"len",
"(",
"stack",
")",
... | Pop an item off the stack in the cache. If stack
is empty after pop, it deletes the stack.
:param cache: werkzeug BasicCache-like object
:param user_id: id of user, used as key in cache
:return: top item from stack, otherwise None | [
"Pop",
"an",
"item",
"off",
"the",
"stack",
"in",
"the",
"cache",
".",
"If",
"stack",
"is",
"empty",
"after",
"pop",
"it",
"deletes",
"the",
"stack",
"."
] | fe407646ae404a8c90b363c86d5c4c201b6a5580 | https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/cache.py#L27-L48 |
242,104 | johnwheeler/flask-ask | flask_ask/cache.py | top_stream | def top_stream(cache, user_id):
"""
Peek at the top of the stack in the cache.
:param cache: werkzeug BasicCache-like object
:param user_id: id of user, used as key in cache
:return: top item in user's cached stack, otherwise None
"""
if not user_id:
return None
stack = cache.get(user_id)
if stack is None:
return None
return stack.pop() | python | def top_stream(cache, user_id):
if not user_id:
return None
stack = cache.get(user_id)
if stack is None:
return None
return stack.pop() | [
"def",
"top_stream",
"(",
"cache",
",",
"user_id",
")",
":",
"if",
"not",
"user_id",
":",
"return",
"None",
"stack",
"=",
"cache",
".",
"get",
"(",
"user_id",
")",
"if",
"stack",
"is",
"None",
":",
"return",
"None",
"return",
"stack",
".",
"pop",
"("... | Peek at the top of the stack in the cache.
:param cache: werkzeug BasicCache-like object
:param user_id: id of user, used as key in cache
:return: top item in user's cached stack, otherwise None | [
"Peek",
"at",
"the",
"top",
"of",
"the",
"stack",
"in",
"the",
"cache",
"."
] | fe407646ae404a8c90b363c86d5c4c201b6a5580 | https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/cache.py#L65-L80 |
242,105 | ecederstrand/exchangelib | exchangelib/transport.py | wrap | def wrap(content, version, account=None):
"""
Generate the necessary boilerplate XML for a raw SOAP request. The XML is specific to the server version.
ExchangeImpersonation allows to act as the user we want to impersonate.
"""
envelope = create_element('s:Envelope', nsmap=ns_translation)
header = create_element('s:Header')
requestserverversion = create_element('t:RequestServerVersion', Version=version)
header.append(requestserverversion)
if account:
if account.access_type == IMPERSONATION:
exchangeimpersonation = create_element('t:ExchangeImpersonation')
connectingsid = create_element('t:ConnectingSID')
add_xml_child(connectingsid, 't:PrimarySmtpAddress', account.primary_smtp_address)
exchangeimpersonation.append(connectingsid)
header.append(exchangeimpersonation)
timezonecontext = create_element('t:TimeZoneContext')
timezonedefinition = create_element('t:TimeZoneDefinition', Id=account.default_timezone.ms_id)
timezonecontext.append(timezonedefinition)
header.append(timezonecontext)
envelope.append(header)
body = create_element('s:Body')
body.append(content)
envelope.append(body)
return xml_to_str(envelope, encoding=DEFAULT_ENCODING, xml_declaration=True) | python | def wrap(content, version, account=None):
envelope = create_element('s:Envelope', nsmap=ns_translation)
header = create_element('s:Header')
requestserverversion = create_element('t:RequestServerVersion', Version=version)
header.append(requestserverversion)
if account:
if account.access_type == IMPERSONATION:
exchangeimpersonation = create_element('t:ExchangeImpersonation')
connectingsid = create_element('t:ConnectingSID')
add_xml_child(connectingsid, 't:PrimarySmtpAddress', account.primary_smtp_address)
exchangeimpersonation.append(connectingsid)
header.append(exchangeimpersonation)
timezonecontext = create_element('t:TimeZoneContext')
timezonedefinition = create_element('t:TimeZoneDefinition', Id=account.default_timezone.ms_id)
timezonecontext.append(timezonedefinition)
header.append(timezonecontext)
envelope.append(header)
body = create_element('s:Body')
body.append(content)
envelope.append(body)
return xml_to_str(envelope, encoding=DEFAULT_ENCODING, xml_declaration=True) | [
"def",
"wrap",
"(",
"content",
",",
"version",
",",
"account",
"=",
"None",
")",
":",
"envelope",
"=",
"create_element",
"(",
"'s:Envelope'",
",",
"nsmap",
"=",
"ns_translation",
")",
"header",
"=",
"create_element",
"(",
"'s:Header'",
")",
"requestserverversi... | Generate the necessary boilerplate XML for a raw SOAP request. The XML is specific to the server version.
ExchangeImpersonation allows to act as the user we want to impersonate. | [
"Generate",
"the",
"necessary",
"boilerplate",
"XML",
"for",
"a",
"raw",
"SOAP",
"request",
".",
"The",
"XML",
"is",
"specific",
"to",
"the",
"server",
"version",
".",
"ExchangeImpersonation",
"allows",
"to",
"act",
"as",
"the",
"user",
"we",
"want",
"to",
... | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/transport.py#L49-L73 |
242,106 | ecederstrand/exchangelib | exchangelib/autodiscover.py | discover | def discover(email, credentials):
"""
Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The
autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request,
and return a hopefully-cached Protocol to the callee.
"""
log.debug('Attempting autodiscover on email %s', email)
if not isinstance(credentials, Credentials):
raise ValueError("'credentials' %r must be a Credentials instance" % credentials)
domain = get_domain(email)
# We may be using multiple different credentials and changing our minds on TLS verification. This key combination
# should be safe.
autodiscover_key = (domain, credentials)
# Use lock to guard against multiple threads competing to cache information
log.debug('Waiting for _autodiscover_cache_lock')
with _autodiscover_cache_lock:
# Don't recurse while holding the lock!
log.debug('_autodiscover_cache_lock acquired')
if autodiscover_key in _autodiscover_cache:
protocol = _autodiscover_cache[autodiscover_key]
if not isinstance(protocol, AutodiscoverProtocol):
raise ValueError('Unexpected autodiscover cache contents: %s' % protocol)
log.debug('Cache hit for domain %s credentials %s: %s', domain, credentials, protocol.server)
try:
# This is the main path when the cache is primed
return _autodiscover_quick(credentials=credentials, email=email, protocol=protocol)
except AutoDiscoverFailed:
# Autodiscover no longer works with this domain. Clear cache and try again after releasing the lock
del _autodiscover_cache[autodiscover_key]
except AutoDiscoverRedirect as e:
log.debug('%s redirects to %s', email, e.redirect_email)
if email.lower() == e.redirect_email.lower():
raise_from(AutoDiscoverCircularRedirect('Redirect to same email address: %s' % email), None)
# Start over with the new email address after releasing the lock
email = e.redirect_email
else:
log.debug('Cache miss for domain %s credentials %s', domain, credentials)
log.debug('Cache contents: %s', _autodiscover_cache)
try:
# This eventually fills the cache in _autodiscover_hostname
return _try_autodiscover(hostname=domain, credentials=credentials, email=email)
except AutoDiscoverRedirect as e:
if email.lower() == e.redirect_email.lower():
raise_from(AutoDiscoverCircularRedirect('Redirect to same email address: %s' % email), None)
log.debug('%s redirects to %s', email, e.redirect_email)
# Start over with the new email address after releasing the lock
email = e.redirect_email
log.debug('Released autodiscover_cache_lock')
# We fell out of the with statement, so either cache was filled by someone else, or autodiscover redirected us to
# another email address. Start over after releasing the lock.
return discover(email=email, credentials=credentials) | python | def discover(email, credentials):
log.debug('Attempting autodiscover on email %s', email)
if not isinstance(credentials, Credentials):
raise ValueError("'credentials' %r must be a Credentials instance" % credentials)
domain = get_domain(email)
# We may be using multiple different credentials and changing our minds on TLS verification. This key combination
# should be safe.
autodiscover_key = (domain, credentials)
# Use lock to guard against multiple threads competing to cache information
log.debug('Waiting for _autodiscover_cache_lock')
with _autodiscover_cache_lock:
# Don't recurse while holding the lock!
log.debug('_autodiscover_cache_lock acquired')
if autodiscover_key in _autodiscover_cache:
protocol = _autodiscover_cache[autodiscover_key]
if not isinstance(protocol, AutodiscoverProtocol):
raise ValueError('Unexpected autodiscover cache contents: %s' % protocol)
log.debug('Cache hit for domain %s credentials %s: %s', domain, credentials, protocol.server)
try:
# This is the main path when the cache is primed
return _autodiscover_quick(credentials=credentials, email=email, protocol=protocol)
except AutoDiscoverFailed:
# Autodiscover no longer works with this domain. Clear cache and try again after releasing the lock
del _autodiscover_cache[autodiscover_key]
except AutoDiscoverRedirect as e:
log.debug('%s redirects to %s', email, e.redirect_email)
if email.lower() == e.redirect_email.lower():
raise_from(AutoDiscoverCircularRedirect('Redirect to same email address: %s' % email), None)
# Start over with the new email address after releasing the lock
email = e.redirect_email
else:
log.debug('Cache miss for domain %s credentials %s', domain, credentials)
log.debug('Cache contents: %s', _autodiscover_cache)
try:
# This eventually fills the cache in _autodiscover_hostname
return _try_autodiscover(hostname=domain, credentials=credentials, email=email)
except AutoDiscoverRedirect as e:
if email.lower() == e.redirect_email.lower():
raise_from(AutoDiscoverCircularRedirect('Redirect to same email address: %s' % email), None)
log.debug('%s redirects to %s', email, e.redirect_email)
# Start over with the new email address after releasing the lock
email = e.redirect_email
log.debug('Released autodiscover_cache_lock')
# We fell out of the with statement, so either cache was filled by someone else, or autodiscover redirected us to
# another email address. Start over after releasing the lock.
return discover(email=email, credentials=credentials) | [
"def",
"discover",
"(",
"email",
",",
"credentials",
")",
":",
"log",
".",
"debug",
"(",
"'Attempting autodiscover on email %s'",
",",
"email",
")",
"if",
"not",
"isinstance",
"(",
"credentials",
",",
"Credentials",
")",
":",
"raise",
"ValueError",
"(",
"\"'cr... | Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The
autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request,
and return a hopefully-cached Protocol to the callee. | [
"Performs",
"the",
"autodiscover",
"dance",
"and",
"returns",
"the",
"primary",
"SMTP",
"address",
"of",
"the",
"account",
"and",
"a",
"Protocol",
"on",
"success",
".",
"The",
"autodiscover",
"and",
"EWS",
"server",
"might",
"not",
"be",
"the",
"same",
"so",... | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/autodiscover.py#L173-L223 |
242,107 | ecederstrand/exchangelib | exchangelib/properties.py | TimeZone.to_server_timezone | def to_server_timezone(self, timezones, for_year):
"""Returns the Microsoft timezone ID corresponding to this timezone. There may not be a match at all, and there
may be multiple matches. If so, we return a random timezone ID.
:param timezones: A list of server timezones, as returned by
list(account.protocol.get_timezones(return_full_timezone_data=True))
:param for_year:
:return: A Microsoft timezone ID, as a string
"""
candidates = set()
for tz_id, tz_name, tz_periods, tz_transitions, tz_transitions_groups in timezones:
candidate = self.from_server_timezone(tz_periods, tz_transitions, tz_transitions_groups, for_year)
if candidate == self:
log.debug('Found exact candidate: %s (%s)', tz_id, tz_name)
# We prefer this timezone over anything else. Return immediately.
return tz_id
# Reduce list based on base bias and standard / daylight bias values
if candidate.bias != self.bias:
continue
if candidate.standard_time is None:
if self.standard_time is not None:
continue
else:
if self.standard_time is None:
continue
if candidate.standard_time.bias != self.standard_time.bias:
continue
if candidate.daylight_time is None:
if self.daylight_time is not None:
continue
else:
if self.daylight_time is None:
continue
if candidate.daylight_time.bias != self.daylight_time.bias:
continue
log.debug('Found candidate with matching biases: %s (%s)', tz_id, tz_name)
candidates.add(tz_id)
if not candidates:
raise ValueError('No server timezones match this timezone definition')
if len(candidates) == 1:
log.info('Could not find an exact timezone match for %s. Selecting the best candidate', self)
else:
log.warning('Could not find an exact timezone match for %s. Selecting a random candidate', self)
return candidates.pop() | python | def to_server_timezone(self, timezones, for_year):
candidates = set()
for tz_id, tz_name, tz_periods, tz_transitions, tz_transitions_groups in timezones:
candidate = self.from_server_timezone(tz_periods, tz_transitions, tz_transitions_groups, for_year)
if candidate == self:
log.debug('Found exact candidate: %s (%s)', tz_id, tz_name)
# We prefer this timezone over anything else. Return immediately.
return tz_id
# Reduce list based on base bias and standard / daylight bias values
if candidate.bias != self.bias:
continue
if candidate.standard_time is None:
if self.standard_time is not None:
continue
else:
if self.standard_time is None:
continue
if candidate.standard_time.bias != self.standard_time.bias:
continue
if candidate.daylight_time is None:
if self.daylight_time is not None:
continue
else:
if self.daylight_time is None:
continue
if candidate.daylight_time.bias != self.daylight_time.bias:
continue
log.debug('Found candidate with matching biases: %s (%s)', tz_id, tz_name)
candidates.add(tz_id)
if not candidates:
raise ValueError('No server timezones match this timezone definition')
if len(candidates) == 1:
log.info('Could not find an exact timezone match for %s. Selecting the best candidate', self)
else:
log.warning('Could not find an exact timezone match for %s. Selecting a random candidate', self)
return candidates.pop() | [
"def",
"to_server_timezone",
"(",
"self",
",",
"timezones",
",",
"for_year",
")",
":",
"candidates",
"=",
"set",
"(",
")",
"for",
"tz_id",
",",
"tz_name",
",",
"tz_periods",
",",
"tz_transitions",
",",
"tz_transitions_groups",
"in",
"timezones",
":",
"candidat... | Returns the Microsoft timezone ID corresponding to this timezone. There may not be a match at all, and there
may be multiple matches. If so, we return a random timezone ID.
:param timezones: A list of server timezones, as returned by
list(account.protocol.get_timezones(return_full_timezone_data=True))
:param for_year:
:return: A Microsoft timezone ID, as a string | [
"Returns",
"the",
"Microsoft",
"timezone",
"ID",
"corresponding",
"to",
"this",
"timezone",
".",
"There",
"may",
"not",
"be",
"a",
"match",
"at",
"all",
"and",
"there",
"may",
"be",
"multiple",
"matches",
".",
"If",
"so",
"we",
"return",
"a",
"random",
"... | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/properties.py#L560-L603 |
242,108 | ecederstrand/exchangelib | exchangelib/protocol.py | BaseProtocol.decrease_poolsize | def decrease_poolsize(self):
"""Decreases the session pool size in response to error messages from the server requesting to rate-limit
requests. We decrease by one session per call.
"""
# Take a single session from the pool and discard it. We need to protect this with a lock while we are changing
# the pool size variable, to avoid race conditions. We must keep at least one session in the pool.
if self._session_pool_size <= 1:
raise SessionPoolMinSizeReached('Session pool size cannot be decreased further')
with self._session_pool_lock:
if self._session_pool_size <= 1:
log.debug('Session pool size was decreased in another thread')
return
log.warning('Lowering session pool size from %s to %s', self._session_pool_size,
self._session_pool_size - 1)
self.get_session().close()
self._session_pool_size -= 1 | python | def decrease_poolsize(self):
# Take a single session from the pool and discard it. We need to protect this with a lock while we are changing
# the pool size variable, to avoid race conditions. We must keep at least one session in the pool.
if self._session_pool_size <= 1:
raise SessionPoolMinSizeReached('Session pool size cannot be decreased further')
with self._session_pool_lock:
if self._session_pool_size <= 1:
log.debug('Session pool size was decreased in another thread')
return
log.warning('Lowering session pool size from %s to %s', self._session_pool_size,
self._session_pool_size - 1)
self.get_session().close()
self._session_pool_size -= 1 | [
"def",
"decrease_poolsize",
"(",
"self",
")",
":",
"# Take a single session from the pool and discard it. We need to protect this with a lock while we are changing",
"# the pool size variable, to avoid race conditions. We must keep at least one session in the pool.",
"if",
"self",
".",
"_sessi... | Decreases the session pool size in response to error messages from the server requesting to rate-limit
requests. We decrease by one session per call. | [
"Decreases",
"the",
"session",
"pool",
"size",
"in",
"response",
"to",
"error",
"messages",
"from",
"the",
"server",
"requesting",
"to",
"rate",
"-",
"limit",
"requests",
".",
"We",
"decrease",
"by",
"one",
"session",
"per",
"call",
"."
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/protocol.py#L100-L115 |
242,109 | ecederstrand/exchangelib | exchangelib/util.py | is_iterable | def is_iterable(value, generators_allowed=False):
"""
Checks if value is a list-like object. Don't match generators and generator-like objects here by default, because
callers don't necessarily guarantee that they only iterate the value once. Take care to not match string types and
bytes.
:param value: any type of object
:param generators_allowed: if True, generators will be treated as iterable
:return: True or False
"""
if generators_allowed:
if not isinstance(value, string_types + (bytes,)) and hasattr(value, '__iter__'):
return True
else:
if isinstance(value, (tuple, list, set)):
return True
return False | python | def is_iterable(value, generators_allowed=False):
if generators_allowed:
if not isinstance(value, string_types + (bytes,)) and hasattr(value, '__iter__'):
return True
else:
if isinstance(value, (tuple, list, set)):
return True
return False | [
"def",
"is_iterable",
"(",
"value",
",",
"generators_allowed",
"=",
"False",
")",
":",
"if",
"generators_allowed",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"string_types",
"+",
"(",
"bytes",
",",
")",
")",
"and",
"hasattr",
"(",
"value",
",",
"... | Checks if value is a list-like object. Don't match generators and generator-like objects here by default, because
callers don't necessarily guarantee that they only iterate the value once. Take care to not match string types and
bytes.
:param value: any type of object
:param generators_allowed: if True, generators will be treated as iterable
:return: True or False | [
"Checks",
"if",
"value",
"is",
"a",
"list",
"-",
"like",
"object",
".",
"Don",
"t",
"match",
"generators",
"and",
"generator",
"-",
"like",
"objects",
"here",
"by",
"default",
"because",
"callers",
"don",
"t",
"necessarily",
"guarantee",
"that",
"they",
"o... | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/util.py#L64-L80 |
242,110 | ecederstrand/exchangelib | exchangelib/util.py | chunkify | def chunkify(iterable, chunksize):
"""
Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``.
"""
from .queryset import QuerySet
if hasattr(iterable, '__getitem__') and not isinstance(iterable, QuerySet):
# tuple, list. QuerySet has __getitem__ but that evaluates the entire query greedily. We don't want that here.
for i in range(0, len(iterable), chunksize):
yield iterable[i:i + chunksize]
else:
# generator, set, map, QuerySet
chunk = []
for i in iterable:
chunk.append(i)
if len(chunk) == chunksize:
yield chunk
chunk = []
if chunk:
yield chunk | python | def chunkify(iterable, chunksize):
from .queryset import QuerySet
if hasattr(iterable, '__getitem__') and not isinstance(iterable, QuerySet):
# tuple, list. QuerySet has __getitem__ but that evaluates the entire query greedily. We don't want that here.
for i in range(0, len(iterable), chunksize):
yield iterable[i:i + chunksize]
else:
# generator, set, map, QuerySet
chunk = []
for i in iterable:
chunk.append(i)
if len(chunk) == chunksize:
yield chunk
chunk = []
if chunk:
yield chunk | [
"def",
"chunkify",
"(",
"iterable",
",",
"chunksize",
")",
":",
"from",
".",
"queryset",
"import",
"QuerySet",
"if",
"hasattr",
"(",
"iterable",
",",
"'__getitem__'",
")",
"and",
"not",
"isinstance",
"(",
"iterable",
",",
"QuerySet",
")",
":",
"# tuple, list... | Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``. | [
"Splits",
"an",
"iterable",
"into",
"chunks",
"of",
"size",
"chunksize",
".",
"The",
"last",
"chunk",
"may",
"be",
"smaller",
"than",
"chunksize",
"."
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/util.py#L83-L101 |
242,111 | ecederstrand/exchangelib | exchangelib/util.py | peek | def peek(iterable):
"""
Checks if an iterable is empty and returns status and the rewinded iterable
"""
from .queryset import QuerySet
if isinstance(iterable, QuerySet):
# QuerySet has __len__ but that evaluates the entire query greedily. We don't want that here. Instead, peek()
# should be called on QuerySet.iterator()
raise ValueError('Cannot peek on a QuerySet')
if hasattr(iterable, '__len__'):
# tuple, list, set
return not iterable, iterable
# generator
try:
first = next(iterable)
except StopIteration:
return True, iterable
# We can't rewind a generator. Instead, chain the first element and the rest of the generator
return False, itertools.chain([first], iterable) | python | def peek(iterable):
from .queryset import QuerySet
if isinstance(iterable, QuerySet):
# QuerySet has __len__ but that evaluates the entire query greedily. We don't want that here. Instead, peek()
# should be called on QuerySet.iterator()
raise ValueError('Cannot peek on a QuerySet')
if hasattr(iterable, '__len__'):
# tuple, list, set
return not iterable, iterable
# generator
try:
first = next(iterable)
except StopIteration:
return True, iterable
# We can't rewind a generator. Instead, chain the first element and the rest of the generator
return False, itertools.chain([first], iterable) | [
"def",
"peek",
"(",
"iterable",
")",
":",
"from",
".",
"queryset",
"import",
"QuerySet",
"if",
"isinstance",
"(",
"iterable",
",",
"QuerySet",
")",
":",
"# QuerySet has __len__ but that evaluates the entire query greedily. We don't want that here. Instead, peek()",
"# should ... | Checks if an iterable is empty and returns status and the rewinded iterable | [
"Checks",
"if",
"an",
"iterable",
"is",
"empty",
"and",
"returns",
"status",
"and",
"the",
"rewinded",
"iterable"
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/util.py#L104-L122 |
242,112 | ecederstrand/exchangelib | exchangelib/util.py | xml_to_str | def xml_to_str(tree, encoding=None, xml_declaration=False):
"""Serialize an XML tree. Returns unicode if 'encoding' is None. Otherwise, we return encoded 'bytes'."""
if xml_declaration and not encoding:
raise ValueError("'xml_declaration' is not supported when 'encoding' is None")
if encoding:
return tostring(tree, encoding=encoding, xml_declaration=True)
return tostring(tree, encoding=text_type, xml_declaration=False) | python | def xml_to_str(tree, encoding=None, xml_declaration=False):
if xml_declaration and not encoding:
raise ValueError("'xml_declaration' is not supported when 'encoding' is None")
if encoding:
return tostring(tree, encoding=encoding, xml_declaration=True)
return tostring(tree, encoding=text_type, xml_declaration=False) | [
"def",
"xml_to_str",
"(",
"tree",
",",
"encoding",
"=",
"None",
",",
"xml_declaration",
"=",
"False",
")",
":",
"if",
"xml_declaration",
"and",
"not",
"encoding",
":",
"raise",
"ValueError",
"(",
"\"'xml_declaration' is not supported when 'encoding' is None\"",
")",
... | Serialize an XML tree. Returns unicode if 'encoding' is None. Otherwise, we return encoded 'bytes'. | [
"Serialize",
"an",
"XML",
"tree",
".",
"Returns",
"unicode",
"if",
"encoding",
"is",
"None",
".",
"Otherwise",
"we",
"return",
"encoded",
"bytes",
"."
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/util.py#L125-L131 |
242,113 | ecederstrand/exchangelib | exchangelib/util.py | is_xml | def is_xml(text):
"""
Helper function. Lightweight test if response is an XML doc
"""
# BOM_UTF8 is an UTF-8 byte order mark which may precede the XML from an Exchange server
bom_len = len(BOM_UTF8)
if text[:bom_len] == BOM_UTF8:
return text[bom_len:bom_len + 5] == b'<?xml'
return text[:5] == b'<?xml' | python | def is_xml(text):
# BOM_UTF8 is an UTF-8 byte order mark which may precede the XML from an Exchange server
bom_len = len(BOM_UTF8)
if text[:bom_len] == BOM_UTF8:
return text[bom_len:bom_len + 5] == b'<?xml'
return text[:5] == b'<?xml' | [
"def",
"is_xml",
"(",
"text",
")",
":",
"# BOM_UTF8 is an UTF-8 byte order mark which may precede the XML from an Exchange server",
"bom_len",
"=",
"len",
"(",
"BOM_UTF8",
")",
"if",
"text",
"[",
":",
"bom_len",
"]",
"==",
"BOM_UTF8",
":",
"return",
"text",
"[",
"bo... | Helper function. Lightweight test if response is an XML doc | [
"Helper",
"function",
".",
"Lightweight",
"test",
"if",
"response",
"is",
"an",
"XML",
"doc"
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/util.py#L391-L399 |
242,114 | ecederstrand/exchangelib | exchangelib/services.py | GetItem.call | def call(self, items, additional_fields, shape):
"""
Returns all items in an account that correspond to a list of ID's, in stable order.
:param items: a list of (id, changekey) tuples or Item objects
:param additional_fields: the extra fields that should be returned with the item, as FieldPath objects
:param shape: The shape of returned objects
:return: XML elements for the items, in stable order
"""
return self._pool_requests(payload_func=self.get_payload, **dict(
items=items,
additional_fields=additional_fields,
shape=shape,
)) | python | def call(self, items, additional_fields, shape):
return self._pool_requests(payload_func=self.get_payload, **dict(
items=items,
additional_fields=additional_fields,
shape=shape,
)) | [
"def",
"call",
"(",
"self",
",",
"items",
",",
"additional_fields",
",",
"shape",
")",
":",
"return",
"self",
".",
"_pool_requests",
"(",
"payload_func",
"=",
"self",
".",
"get_payload",
",",
"*",
"*",
"dict",
"(",
"items",
"=",
"items",
",",
"additional... | Returns all items in an account that correspond to a list of ID's, in stable order.
:param items: a list of (id, changekey) tuples or Item objects
:param additional_fields: the extra fields that should be returned with the item, as FieldPath objects
:param shape: The shape of returned objects
:return: XML elements for the items, in stable order | [
"Returns",
"all",
"items",
"in",
"an",
"account",
"that",
"correspond",
"to",
"a",
"list",
"of",
"ID",
"s",
"in",
"stable",
"order",
"."
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/services.py#L689-L702 |
242,115 | ecederstrand/exchangelib | exchangelib/services.py | FindFolder.call | def call(self, additional_fields, restriction, shape, depth, max_items, offset):
"""
Find subfolders of a folder.
:param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects
:param shape: The set of attributes to return
:param depth: How deep in the folder structure to search for folders
:param max_items: The maximum number of items to return
:param offset: the offset relative to the first item in the item collection. Usually 0.
:return: XML elements for the matching folders
"""
from .folders import Folder
roots = {f.root for f in self.folders}
if len(roots) != 1:
raise ValueError('FindFolder must be called with folders in the same root hierarchy (%r)' % roots)
root = roots.pop()
for elem in self._paged_call(payload_func=self.get_payload, max_items=max_items, **dict(
additional_fields=additional_fields,
restriction=restriction,
shape=shape,
depth=depth,
page_size=self.chunk_size,
offset=offset,
)):
if isinstance(elem, Exception):
yield elem
continue
yield Folder.from_xml(elem=elem, root=root) | python | def call(self, additional_fields, restriction, shape, depth, max_items, offset):
from .folders import Folder
roots = {f.root for f in self.folders}
if len(roots) != 1:
raise ValueError('FindFolder must be called with folders in the same root hierarchy (%r)' % roots)
root = roots.pop()
for elem in self._paged_call(payload_func=self.get_payload, max_items=max_items, **dict(
additional_fields=additional_fields,
restriction=restriction,
shape=shape,
depth=depth,
page_size=self.chunk_size,
offset=offset,
)):
if isinstance(elem, Exception):
yield elem
continue
yield Folder.from_xml(elem=elem, root=root) | [
"def",
"call",
"(",
"self",
",",
"additional_fields",
",",
"restriction",
",",
"shape",
",",
"depth",
",",
"max_items",
",",
"offset",
")",
":",
"from",
".",
"folders",
"import",
"Folder",
"roots",
"=",
"{",
"f",
".",
"root",
"for",
"f",
"in",
"self",
... | Find subfolders of a folder.
:param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects
:param shape: The set of attributes to return
:param depth: How deep in the folder structure to search for folders
:param max_items: The maximum number of items to return
:param offset: the offset relative to the first item in the item collection. Usually 0.
:return: XML elements for the matching folders | [
"Find",
"subfolders",
"of",
"a",
"folder",
"."
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/services.py#L1067-L1094 |
242,116 | ecederstrand/exchangelib | exchangelib/services.py | GetFolder.call | def call(self, folders, additional_fields, shape):
"""
Takes a folder ID and returns the full information for that folder.
:param folders: a list of Folder objects
:param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects
:param shape: The set of attributes to return
:return: XML elements for the folders, in stable order
"""
# We can't easily find the correct folder class from the returned XML. Instead, return objects with the same
# class as the folder instance it was requested with.
from .folders import Folder, DistinguishedFolderId, RootOfHierarchy
folders_list = list(folders) # Convert to a list, in case 'folders' is a generator
for folder, elem in zip(folders_list, self._get_elements(payload=self.get_payload(
folders=folders,
additional_fields=additional_fields,
shape=shape,
))):
if isinstance(elem, Exception):
yield elem
continue
if isinstance(folder, RootOfHierarchy):
f = folder.from_xml(elem=elem, account=self.account)
elif isinstance(folder, Folder):
f = folder.from_xml(elem=elem, root=folder.root)
elif isinstance(folder, DistinguishedFolderId):
# We don't know the root, so assume account.root.
for folder_cls in self.account.root.WELLKNOWN_FOLDERS:
if folder_cls.DISTINGUISHED_FOLDER_ID == folder.id:
break
else:
raise ValueError('Unknown distinguished folder ID: %s', folder.id)
f = folder_cls.from_xml(elem=elem, root=self.account.root)
else:
# 'folder' is a generic FolderId instance. We don't know the root so assume account.root.
f = Folder.from_xml(elem=elem, root=self.account.root)
if isinstance(folder, DistinguishedFolderId):
f.is_distinguished = True
elif isinstance(folder, Folder) and folder.is_distinguished:
f.is_distinguished = True
yield f | python | def call(self, folders, additional_fields, shape):
# We can't easily find the correct folder class from the returned XML. Instead, return objects with the same
# class as the folder instance it was requested with.
from .folders import Folder, DistinguishedFolderId, RootOfHierarchy
folders_list = list(folders) # Convert to a list, in case 'folders' is a generator
for folder, elem in zip(folders_list, self._get_elements(payload=self.get_payload(
folders=folders,
additional_fields=additional_fields,
shape=shape,
))):
if isinstance(elem, Exception):
yield elem
continue
if isinstance(folder, RootOfHierarchy):
f = folder.from_xml(elem=elem, account=self.account)
elif isinstance(folder, Folder):
f = folder.from_xml(elem=elem, root=folder.root)
elif isinstance(folder, DistinguishedFolderId):
# We don't know the root, so assume account.root.
for folder_cls in self.account.root.WELLKNOWN_FOLDERS:
if folder_cls.DISTINGUISHED_FOLDER_ID == folder.id:
break
else:
raise ValueError('Unknown distinguished folder ID: %s', folder.id)
f = folder_cls.from_xml(elem=elem, root=self.account.root)
else:
# 'folder' is a generic FolderId instance. We don't know the root so assume account.root.
f = Folder.from_xml(elem=elem, root=self.account.root)
if isinstance(folder, DistinguishedFolderId):
f.is_distinguished = True
elif isinstance(folder, Folder) and folder.is_distinguished:
f.is_distinguished = True
yield f | [
"def",
"call",
"(",
"self",
",",
"folders",
",",
"additional_fields",
",",
"shape",
")",
":",
"# We can't easily find the correct folder class from the returned XML. Instead, return objects with the same",
"# class as the folder instance it was requested with.",
"from",
".",
"folders... | Takes a folder ID and returns the full information for that folder.
:param folders: a list of Folder objects
:param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects
:param shape: The set of attributes to return
:return: XML elements for the folders, in stable order | [
"Takes",
"a",
"folder",
"ID",
"and",
"returns",
"the",
"full",
"information",
"for",
"that",
"folder",
"."
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/services.py#L1132-L1172 |
242,117 | ecederstrand/exchangelib | exchangelib/services.py | UploadItems.get_payload | def get_payload(self, items):
"""Upload given items to given account
data is an iterable of tuples where the first element is a Folder
instance representing the ParentFolder that the item will be placed in
and the second element is a Data string returned from an ExportItems
call.
"""
from .properties import ParentFolderId
uploaditems = create_element('m:%s' % self.SERVICE_NAME)
itemselement = create_element('m:Items')
uploaditems.append(itemselement)
for parent_folder, data_str in items:
item = create_element('t:Item', CreateAction='CreateNew')
parentfolderid = ParentFolderId(parent_folder.id, parent_folder.changekey)
set_xml_value(item, parentfolderid, version=self.account.version)
add_xml_child(item, 't:Data', data_str)
itemselement.append(item)
return uploaditems | python | def get_payload(self, items):
from .properties import ParentFolderId
uploaditems = create_element('m:%s' % self.SERVICE_NAME)
itemselement = create_element('m:Items')
uploaditems.append(itemselement)
for parent_folder, data_str in items:
item = create_element('t:Item', CreateAction='CreateNew')
parentfolderid = ParentFolderId(parent_folder.id, parent_folder.changekey)
set_xml_value(item, parentfolderid, version=self.account.version)
add_xml_child(item, 't:Data', data_str)
itemselement.append(item)
return uploaditems | [
"def",
"get_payload",
"(",
"self",
",",
"items",
")",
":",
"from",
".",
"properties",
"import",
"ParentFolderId",
"uploaditems",
"=",
"create_element",
"(",
"'m:%s'",
"%",
"self",
".",
"SERVICE_NAME",
")",
"itemselement",
"=",
"create_element",
"(",
"'m:Items'",... | Upload given items to given account
data is an iterable of tuples where the first element is a Folder
instance representing the ParentFolder that the item will be placed in
and the second element is a Data string returned from an ExportItems
call. | [
"Upload",
"given",
"items",
"to",
"given",
"account"
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/services.py#L1880-L1898 |
242,118 | ecederstrand/exchangelib | exchangelib/folders.py | FolderCollection.find_items | def find_items(self, q, shape=ID_ONLY, depth=SHALLOW, additional_fields=None, order_fields=None,
calendar_view=None, page_size=None, max_items=None, offset=0):
"""
Private method to call the FindItem service
:param q: a Q instance containing any restrictions
:param shape: controls whether to return (id, chanegkey) tuples or Item objects. If additional_fields is
non-null, we always return Item objects.
:param depth: controls the whether to return soft-deleted items or not.
:param additional_fields: the extra properties we want on the return objects. Default is no properties. Be
aware that complex fields can only be fetched with fetch() (i.e. the GetItem service).
:param order_fields: the SortOrder fields, if any
:param calendar_view: a CalendarView instance, if any
:param page_size: the requested number of items per page
:param max_items: the max number of items to return
:param offset: the offset relative to the first item in the item collection
:return: a generator for the returned item IDs or items
"""
if shape not in SHAPE_CHOICES:
raise ValueError("'shape' %s must be one of %s" % (shape, SHAPE_CHOICES))
if depth not in ITEM_TRAVERSAL_CHOICES:
raise ValueError("'depth' %s must be one of %s" % (depth, ITEM_TRAVERSAL_CHOICES))
if not self.folders:
log.debug('Folder list is empty')
return
if additional_fields:
for f in additional_fields:
self.validate_item_field(field=f)
for f in additional_fields:
if f.field.is_complex:
raise ValueError("find_items() does not support field '%s'. Use fetch() instead" % f.field.name)
if calendar_view is not None and not isinstance(calendar_view, CalendarView):
raise ValueError("'calendar_view' %s must be a CalendarView instance" % calendar_view)
# Build up any restrictions
if q.is_empty():
restriction = None
query_string = None
elif q.query_string:
restriction = None
query_string = Restriction(q, folders=self.folders, applies_to=Restriction.ITEMS)
else:
restriction = Restriction(q, folders=self.folders, applies_to=Restriction.ITEMS)
query_string = None
log.debug(
'Finding %s items in folders %s (shape: %s, depth: %s, additional_fields: %s, restriction: %s)',
self.folders,
self.account,
shape,
depth,
additional_fields,
restriction.q if restriction else None,
)
items = FindItem(account=self.account, folders=self.folders, chunk_size=page_size).call(
additional_fields=additional_fields,
restriction=restriction,
order_fields=order_fields,
shape=shape,
query_string=query_string,
depth=depth,
calendar_view=calendar_view,
max_items=calendar_view.max_items if calendar_view else max_items,
offset=offset,
)
if shape == ID_ONLY and additional_fields is None:
for i in items:
yield i if isinstance(i, Exception) else Item.id_from_xml(i)
else:
for i in items:
if isinstance(i, Exception):
yield i
else:
yield Folder.item_model_from_tag(i.tag).from_xml(elem=i, account=self.account) | python | def find_items(self, q, shape=ID_ONLY, depth=SHALLOW, additional_fields=None, order_fields=None,
calendar_view=None, page_size=None, max_items=None, offset=0):
if shape not in SHAPE_CHOICES:
raise ValueError("'shape' %s must be one of %s" % (shape, SHAPE_CHOICES))
if depth not in ITEM_TRAVERSAL_CHOICES:
raise ValueError("'depth' %s must be one of %s" % (depth, ITEM_TRAVERSAL_CHOICES))
if not self.folders:
log.debug('Folder list is empty')
return
if additional_fields:
for f in additional_fields:
self.validate_item_field(field=f)
for f in additional_fields:
if f.field.is_complex:
raise ValueError("find_items() does not support field '%s'. Use fetch() instead" % f.field.name)
if calendar_view is not None and not isinstance(calendar_view, CalendarView):
raise ValueError("'calendar_view' %s must be a CalendarView instance" % calendar_view)
# Build up any restrictions
if q.is_empty():
restriction = None
query_string = None
elif q.query_string:
restriction = None
query_string = Restriction(q, folders=self.folders, applies_to=Restriction.ITEMS)
else:
restriction = Restriction(q, folders=self.folders, applies_to=Restriction.ITEMS)
query_string = None
log.debug(
'Finding %s items in folders %s (shape: %s, depth: %s, additional_fields: %s, restriction: %s)',
self.folders,
self.account,
shape,
depth,
additional_fields,
restriction.q if restriction else None,
)
items = FindItem(account=self.account, folders=self.folders, chunk_size=page_size).call(
additional_fields=additional_fields,
restriction=restriction,
order_fields=order_fields,
shape=shape,
query_string=query_string,
depth=depth,
calendar_view=calendar_view,
max_items=calendar_view.max_items if calendar_view else max_items,
offset=offset,
)
if shape == ID_ONLY and additional_fields is None:
for i in items:
yield i if isinstance(i, Exception) else Item.id_from_xml(i)
else:
for i in items:
if isinstance(i, Exception):
yield i
else:
yield Folder.item_model_from_tag(i.tag).from_xml(elem=i, account=self.account) | [
"def",
"find_items",
"(",
"self",
",",
"q",
",",
"shape",
"=",
"ID_ONLY",
",",
"depth",
"=",
"SHALLOW",
",",
"additional_fields",
"=",
"None",
",",
"order_fields",
"=",
"None",
",",
"calendar_view",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"max_i... | Private method to call the FindItem service
:param q: a Q instance containing any restrictions
:param shape: controls whether to return (id, chanegkey) tuples or Item objects. If additional_fields is
non-null, we always return Item objects.
:param depth: controls the whether to return soft-deleted items or not.
:param additional_fields: the extra properties we want on the return objects. Default is no properties. Be
aware that complex fields can only be fetched with fetch() (i.e. the GetItem service).
:param order_fields: the SortOrder fields, if any
:param calendar_view: a CalendarView instance, if any
:param page_size: the requested number of items per page
:param max_items: the max number of items to return
:param offset: the offset relative to the first item in the item collection
:return: a generator for the returned item IDs or items | [
"Private",
"method",
"to",
"call",
"the",
"FindItem",
"service"
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/folders.py#L185-L257 |
242,119 | ecederstrand/exchangelib | exchangelib/folders.py | RootOfHierarchy.get_distinguished | def get_distinguished(cls, account):
"""Gets the distinguished folder for this folder class"""
if not cls.DISTINGUISHED_FOLDER_ID:
raise ValueError('Class %s must have a DISTINGUISHED_FOLDER_ID value' % cls)
folders = list(FolderCollection(
account=account,
folders=[cls(account=account, name=cls.DISTINGUISHED_FOLDER_ID, is_distinguished=True)]
).get_folders()
)
if not folders:
raise ErrorFolderNotFound('Could not find distinguished folder %s' % cls.DISTINGUISHED_FOLDER_ID)
if len(folders) != 1:
raise ValueError('Expected result length 1, but got %s' % folders)
folder = folders[0]
if isinstance(folder, Exception):
raise folder
if folder.__class__ != cls:
raise ValueError("Expected 'folder' %r to be a %s instance" % (folder, cls))
return folder | python | def get_distinguished(cls, account):
if not cls.DISTINGUISHED_FOLDER_ID:
raise ValueError('Class %s must have a DISTINGUISHED_FOLDER_ID value' % cls)
folders = list(FolderCollection(
account=account,
folders=[cls(account=account, name=cls.DISTINGUISHED_FOLDER_ID, is_distinguished=True)]
).get_folders()
)
if not folders:
raise ErrorFolderNotFound('Could not find distinguished folder %s' % cls.DISTINGUISHED_FOLDER_ID)
if len(folders) != 1:
raise ValueError('Expected result length 1, but got %s' % folders)
folder = folders[0]
if isinstance(folder, Exception):
raise folder
if folder.__class__ != cls:
raise ValueError("Expected 'folder' %r to be a %s instance" % (folder, cls))
return folder | [
"def",
"get_distinguished",
"(",
"cls",
",",
"account",
")",
":",
"if",
"not",
"cls",
".",
"DISTINGUISHED_FOLDER_ID",
":",
"raise",
"ValueError",
"(",
"'Class %s must have a DISTINGUISHED_FOLDER_ID value'",
"%",
"cls",
")",
"folders",
"=",
"list",
"(",
"FolderCollec... | Gets the distinguished folder for this folder class | [
"Gets",
"the",
"distinguished",
"folder",
"for",
"this",
"folder",
"class"
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/folders.py#L1489-L1507 |
242,120 | ecederstrand/exchangelib | exchangelib/folders.py | RootOfHierarchy.folder_cls_from_folder_name | def folder_cls_from_folder_name(cls, folder_name, locale):
"""Returns the folder class that matches a localized folder name.
locale is a string, e.g. 'da_DK'
"""
for folder_cls in cls.WELLKNOWN_FOLDERS + NON_DELETEABLE_FOLDERS:
if folder_name.lower() in folder_cls.localized_names(locale):
return folder_cls
raise KeyError() | python | def folder_cls_from_folder_name(cls, folder_name, locale):
for folder_cls in cls.WELLKNOWN_FOLDERS + NON_DELETEABLE_FOLDERS:
if folder_name.lower() in folder_cls.localized_names(locale):
return folder_cls
raise KeyError() | [
"def",
"folder_cls_from_folder_name",
"(",
"cls",
",",
"folder_name",
",",
"locale",
")",
":",
"for",
"folder_cls",
"in",
"cls",
".",
"WELLKNOWN_FOLDERS",
"+",
"NON_DELETEABLE_FOLDERS",
":",
"if",
"folder_name",
".",
"lower",
"(",
")",
"in",
"folder_cls",
".",
... | Returns the folder class that matches a localized folder name.
locale is a string, e.g. 'da_DK' | [
"Returns",
"the",
"folder",
"class",
"that",
"matches",
"a",
"localized",
"folder",
"name",
"."
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/folders.py#L1594-L1602 |
242,121 | ecederstrand/exchangelib | exchangelib/items.py | RegisterMixIn.register | def register(cls, attr_name, attr_cls):
"""
Register a custom extended property in this item class so they can be accessed just like any other attribute
"""
if not cls.INSERT_AFTER_FIELD:
raise ValueError('Class %s is missing INSERT_AFTER_FIELD value' % cls)
try:
cls.get_field_by_fieldname(attr_name)
except InvalidField:
pass
else:
raise ValueError("'%s' is already registered" % attr_name)
if not issubclass(attr_cls, ExtendedProperty):
raise ValueError("%r must be a subclass of ExtendedProperty" % attr_cls)
# Check if class attributes are properly defined
attr_cls.validate_cls()
# ExtendedProperty is not a real field, but a placeholder in the fields list. See
# https://msdn.microsoft.com/en-us/library/office/aa580790(v=exchg.150).aspx
#
# Find the correct index for the new extended property, and insert.
field = ExtendedPropertyField(attr_name, value_cls=attr_cls)
cls.add_field(field, insert_after=cls.INSERT_AFTER_FIELD) | python | def register(cls, attr_name, attr_cls):
if not cls.INSERT_AFTER_FIELD:
raise ValueError('Class %s is missing INSERT_AFTER_FIELD value' % cls)
try:
cls.get_field_by_fieldname(attr_name)
except InvalidField:
pass
else:
raise ValueError("'%s' is already registered" % attr_name)
if not issubclass(attr_cls, ExtendedProperty):
raise ValueError("%r must be a subclass of ExtendedProperty" % attr_cls)
# Check if class attributes are properly defined
attr_cls.validate_cls()
# ExtendedProperty is not a real field, but a placeholder in the fields list. See
# https://msdn.microsoft.com/en-us/library/office/aa580790(v=exchg.150).aspx
#
# Find the correct index for the new extended property, and insert.
field = ExtendedPropertyField(attr_name, value_cls=attr_cls)
cls.add_field(field, insert_after=cls.INSERT_AFTER_FIELD) | [
"def",
"register",
"(",
"cls",
",",
"attr_name",
",",
"attr_cls",
")",
":",
"if",
"not",
"cls",
".",
"INSERT_AFTER_FIELD",
":",
"raise",
"ValueError",
"(",
"'Class %s is missing INSERT_AFTER_FIELD value'",
"%",
"cls",
")",
"try",
":",
"cls",
".",
"get_field_by_f... | Register a custom extended property in this item class so they can be accessed just like any other attribute | [
"Register",
"a",
"custom",
"extended",
"property",
"in",
"this",
"item",
"class",
"so",
"they",
"can",
"be",
"accessed",
"just",
"like",
"any",
"other",
"attribute"
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/items.py#L92-L113 |
242,122 | ecederstrand/exchangelib | exchangelib/items.py | Item.attach | def attach(self, attachments):
"""Add an attachment, or a list of attachments, to this item. If the item has already been saved, the
attachments will be created on the server immediately. If the item has not yet been saved, the attachments will
be created on the server the item is saved.
Adding attachments to an existing item will update the changekey of the item.
"""
if not is_iterable(attachments, generators_allowed=True):
attachments = [attachments]
for a in attachments:
if not a.parent_item:
a.parent_item = self
if self.id and not a.attachment_id:
# Already saved object. Attach the attachment server-side now
a.attach()
if a not in self.attachments:
self.attachments.append(a) | python | def attach(self, attachments):
if not is_iterable(attachments, generators_allowed=True):
attachments = [attachments]
for a in attachments:
if not a.parent_item:
a.parent_item = self
if self.id and not a.attachment_id:
# Already saved object. Attach the attachment server-side now
a.attach()
if a not in self.attachments:
self.attachments.append(a) | [
"def",
"attach",
"(",
"self",
",",
"attachments",
")",
":",
"if",
"not",
"is_iterable",
"(",
"attachments",
",",
"generators_allowed",
"=",
"True",
")",
":",
"attachments",
"=",
"[",
"attachments",
"]",
"for",
"a",
"in",
"attachments",
":",
"if",
"not",
... | Add an attachment, or a list of attachments, to this item. If the item has already been saved, the
attachments will be created on the server immediately. If the item has not yet been saved, the attachments will
be created on the server the item is saved.
Adding attachments to an existing item will update the changekey of the item. | [
"Add",
"an",
"attachment",
"or",
"a",
"list",
"of",
"attachments",
"to",
"this",
"item",
".",
"If",
"the",
"item",
"has",
"already",
"been",
"saved",
"the",
"attachments",
"will",
"be",
"created",
"on",
"the",
"server",
"immediately",
".",
"If",
"the",
"... | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/items.py#L426-L442 |
242,123 | ecederstrand/exchangelib | exchangelib/items.py | Item.detach | def detach(self, attachments):
"""Remove an attachment, or a list of attachments, from this item. If the item has already been saved, the
attachments will be deleted on the server immediately. If the item has not yet been saved, the attachments will
simply not be created on the server the item is saved.
Removing attachments from an existing item will update the changekey of the item.
"""
if not is_iterable(attachments, generators_allowed=True):
attachments = [attachments]
for a in attachments:
if a.parent_item is not self:
raise ValueError('Attachment does not belong to this item')
if self.id:
# Item is already created. Detach the attachment server-side now
a.detach()
if a in self.attachments:
self.attachments.remove(a) | python | def detach(self, attachments):
if not is_iterable(attachments, generators_allowed=True):
attachments = [attachments]
for a in attachments:
if a.parent_item is not self:
raise ValueError('Attachment does not belong to this item')
if self.id:
# Item is already created. Detach the attachment server-side now
a.detach()
if a in self.attachments:
self.attachments.remove(a) | [
"def",
"detach",
"(",
"self",
",",
"attachments",
")",
":",
"if",
"not",
"is_iterable",
"(",
"attachments",
",",
"generators_allowed",
"=",
"True",
")",
":",
"attachments",
"=",
"[",
"attachments",
"]",
"for",
"a",
"in",
"attachments",
":",
"if",
"a",
".... | Remove an attachment, or a list of attachments, from this item. If the item has already been saved, the
attachments will be deleted on the server immediately. If the item has not yet been saved, the attachments will
simply not be created on the server the item is saved.
Removing attachments from an existing item will update the changekey of the item. | [
"Remove",
"an",
"attachment",
"or",
"a",
"list",
"of",
"attachments",
"from",
"this",
"item",
".",
"If",
"the",
"item",
"has",
"already",
"been",
"saved",
"the",
"attachments",
"will",
"be",
"deleted",
"on",
"the",
"server",
"immediately",
".",
"If",
"the"... | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/items.py#L444-L460 |
242,124 | ecederstrand/exchangelib | exchangelib/credentials.py | ServiceAccount.back_off_until | def back_off_until(self):
"""Returns the back off value as a datetime. Resets the current back off value if it has expired."""
if self._back_off_until is None:
return None
with self._back_off_lock:
if self._back_off_until is None:
return None
if self._back_off_until < datetime.datetime.now():
self._back_off_until = None # The backoff value has expired. Reset
return None
return self._back_off_until | python | def back_off_until(self):
if self._back_off_until is None:
return None
with self._back_off_lock:
if self._back_off_until is None:
return None
if self._back_off_until < datetime.datetime.now():
self._back_off_until = None # The backoff value has expired. Reset
return None
return self._back_off_until | [
"def",
"back_off_until",
"(",
"self",
")",
":",
"if",
"self",
".",
"_back_off_until",
"is",
"None",
":",
"return",
"None",
"with",
"self",
".",
"_back_off_lock",
":",
"if",
"self",
".",
"_back_off_until",
"is",
"None",
":",
"return",
"None",
"if",
"self",
... | Returns the back off value as a datetime. Resets the current back off value if it has expired. | [
"Returns",
"the",
"back",
"off",
"value",
"as",
"a",
"datetime",
".",
"Resets",
"the",
"current",
"back",
"off",
"value",
"if",
"it",
"has",
"expired",
"."
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/credentials.py#L103-L113 |
242,125 | ecederstrand/exchangelib | exchangelib/winzone.py | generate_map | def generate_map(timeout=10):
""" Helper method to update the map if the CLDR database is updated """
r = requests.get(CLDR_WINZONE_URL, timeout=timeout)
if r.status_code != 200:
raise ValueError('Unexpected response: %s' % r)
tz_map = {}
for e in to_xml(r.content).find('windowsZones').find('mapTimezones').findall('mapZone'):
for location in e.get('type').split(' '):
if e.get('territory') == DEFAULT_TERRITORY or location not in tz_map:
# Prefer default territory. This is so MS_TIMEZONE_TO_PYTZ_MAP maps from MS timezone ID back to the
# "preferred" region/location timezone name.
tz_map[location] = e.get('other'), e.get('territory')
return tz_map | python | def generate_map(timeout=10):
r = requests.get(CLDR_WINZONE_URL, timeout=timeout)
if r.status_code != 200:
raise ValueError('Unexpected response: %s' % r)
tz_map = {}
for e in to_xml(r.content).find('windowsZones').find('mapTimezones').findall('mapZone'):
for location in e.get('type').split(' '):
if e.get('territory') == DEFAULT_TERRITORY or location not in tz_map:
# Prefer default territory. This is so MS_TIMEZONE_TO_PYTZ_MAP maps from MS timezone ID back to the
# "preferred" region/location timezone name.
tz_map[location] = e.get('other'), e.get('territory')
return tz_map | [
"def",
"generate_map",
"(",
"timeout",
"=",
"10",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"CLDR_WINZONE_URL",
",",
"timeout",
"=",
"timeout",
")",
"if",
"r",
".",
"status_code",
"!=",
"200",
":",
"raise",
"ValueError",
"(",
"'Unexpected response: ... | Helper method to update the map if the CLDR database is updated | [
"Helper",
"method",
"to",
"update",
"the",
"map",
"if",
"the",
"CLDR",
"database",
"is",
"updated"
] | 736347b337c239fcd6d592db5b29e819f753c1ba | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/winzone.py#L11-L23 |
242,126 | tanghaibao/goatools | scripts/compare_gos.py | run | def run():
"""Compare two or more sets of GO IDs. Best done using sections."""
obj = CompareGOsCli()
obj.write(obj.kws.get('xlsx'), obj.kws.get('ofile'), obj.kws.get('verbose', False)) | python | def run():
obj = CompareGOsCli()
obj.write(obj.kws.get('xlsx'), obj.kws.get('ofile'), obj.kws.get('verbose', False)) | [
"def",
"run",
"(",
")",
":",
"obj",
"=",
"CompareGOsCli",
"(",
")",
"obj",
".",
"write",
"(",
"obj",
".",
"kws",
".",
"get",
"(",
"'xlsx'",
")",
",",
"obj",
".",
"kws",
".",
"get",
"(",
"'ofile'",
")",
",",
"obj",
".",
"kws",
".",
"get",
"(",... | Compare two or more sets of GO IDs. Best done using sections. | [
"Compare",
"two",
"or",
"more",
"sets",
"of",
"GO",
"IDs",
".",
"Best",
"done",
"using",
"sections",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/scripts/compare_gos.py#L10-L13 |
242,127 | tanghaibao/goatools | goatools/grouper/sorter_gos.py | SorterGoIds.sortby | def sortby(self, ntd):
"""Return function for sorting."""
if 'reldepth' in self.grprobj.gosubdag.prt_attr['flds']:
return [ntd.NS, -1*ntd.dcnt, ntd.reldepth]
else:
return [ntd.NS, -1*ntd.dcnt, ntd.depth] | python | def sortby(self, ntd):
if 'reldepth' in self.grprobj.gosubdag.prt_attr['flds']:
return [ntd.NS, -1*ntd.dcnt, ntd.reldepth]
else:
return [ntd.NS, -1*ntd.dcnt, ntd.depth] | [
"def",
"sortby",
"(",
"self",
",",
"ntd",
")",
":",
"if",
"'reldepth'",
"in",
"self",
".",
"grprobj",
".",
"gosubdag",
".",
"prt_attr",
"[",
"'flds'",
"]",
":",
"return",
"[",
"ntd",
".",
"NS",
",",
"-",
"1",
"*",
"ntd",
".",
"dcnt",
",",
"ntd",
... | Return function for sorting. | [
"Return",
"function",
"for",
"sorting",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_gos.py#L33-L38 |
242,128 | tanghaibao/goatools | goatools/grouper/sorter_gos.py | SorterGoIds.get_nts_sorted | def get_nts_sorted(self, hdrgo_prt, hdrgos, hdrgo_sort):
"""Return a flat list of grouped and sorted GO terms."""
nts_flat = []
self.get_sorted_hdrgo2usrgos(hdrgos, nts_flat, hdrgo_prt, hdrgo_sort)
return nts_flat | python | def get_nts_sorted(self, hdrgo_prt, hdrgos, hdrgo_sort):
nts_flat = []
self.get_sorted_hdrgo2usrgos(hdrgos, nts_flat, hdrgo_prt, hdrgo_sort)
return nts_flat | [
"def",
"get_nts_sorted",
"(",
"self",
",",
"hdrgo_prt",
",",
"hdrgos",
",",
"hdrgo_sort",
")",
":",
"nts_flat",
"=",
"[",
"]",
"self",
".",
"get_sorted_hdrgo2usrgos",
"(",
"hdrgos",
",",
"nts_flat",
",",
"hdrgo_prt",
",",
"hdrgo_sort",
")",
"return",
"nts_fl... | Return a flat list of grouped and sorted GO terms. | [
"Return",
"a",
"flat",
"list",
"of",
"grouped",
"and",
"sorted",
"GO",
"terms",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_gos.py#L64-L68 |
242,129 | tanghaibao/goatools | goatools/grouper/sorter_gos.py | SorterGoIds.get_sorted_hdrgo2usrgos | def get_sorted_hdrgo2usrgos(self, hdrgos, flat_list=None, hdrgo_prt=True, hdrgo_sort=True):
"""Return GO IDs sorting using go2nt's namedtuple."""
# Return user-specfied sort or default sort of header and user GO IDs
sorted_hdrgos_usrgos = []
h2u_get = self.grprobj.hdrgo2usrgos.get
# Sort GO group headers using GO info in go2nt
hdr_go2nt = self._get_go2nt(hdrgos)
if hdrgo_sort is True:
hdr_go2nt = sorted(hdr_go2nt.items(), key=lambda t: self.hdrgo_sortby(t[1]))
for hdrgo_id, hdrgo_nt in hdr_go2nt:
if flat_list is not None:
if hdrgo_prt or hdrgo_id in self.grprobj.usrgos:
flat_list.append(hdrgo_nt)
# Sort user GOs which are under the current GO header
usrgos_unsorted = h2u_get(hdrgo_id)
if usrgos_unsorted:
usrgo2nt = self._get_go2nt(usrgos_unsorted)
usrgont_sorted = sorted(usrgo2nt.items(), key=lambda t: self.usrgo_sortby(t[1]))
usrgos_sorted, usrnts_sorted = zip(*usrgont_sorted)
if flat_list is not None:
flat_list.extend(usrnts_sorted)
sorted_hdrgos_usrgos.append((hdrgo_id, usrgos_sorted))
else:
sorted_hdrgos_usrgos.append((hdrgo_id, []))
return cx.OrderedDict(sorted_hdrgos_usrgos) | python | def get_sorted_hdrgo2usrgos(self, hdrgos, flat_list=None, hdrgo_prt=True, hdrgo_sort=True):
# Return user-specfied sort or default sort of header and user GO IDs
sorted_hdrgos_usrgos = []
h2u_get = self.grprobj.hdrgo2usrgos.get
# Sort GO group headers using GO info in go2nt
hdr_go2nt = self._get_go2nt(hdrgos)
if hdrgo_sort is True:
hdr_go2nt = sorted(hdr_go2nt.items(), key=lambda t: self.hdrgo_sortby(t[1]))
for hdrgo_id, hdrgo_nt in hdr_go2nt:
if flat_list is not None:
if hdrgo_prt or hdrgo_id in self.grprobj.usrgos:
flat_list.append(hdrgo_nt)
# Sort user GOs which are under the current GO header
usrgos_unsorted = h2u_get(hdrgo_id)
if usrgos_unsorted:
usrgo2nt = self._get_go2nt(usrgos_unsorted)
usrgont_sorted = sorted(usrgo2nt.items(), key=lambda t: self.usrgo_sortby(t[1]))
usrgos_sorted, usrnts_sorted = zip(*usrgont_sorted)
if flat_list is not None:
flat_list.extend(usrnts_sorted)
sorted_hdrgos_usrgos.append((hdrgo_id, usrgos_sorted))
else:
sorted_hdrgos_usrgos.append((hdrgo_id, []))
return cx.OrderedDict(sorted_hdrgos_usrgos) | [
"def",
"get_sorted_hdrgo2usrgos",
"(",
"self",
",",
"hdrgos",
",",
"flat_list",
"=",
"None",
",",
"hdrgo_prt",
"=",
"True",
",",
"hdrgo_sort",
"=",
"True",
")",
":",
"# Return user-specfied sort or default sort of header and user GO IDs",
"sorted_hdrgos_usrgos",
"=",
"[... | Return GO IDs sorting using go2nt's namedtuple. | [
"Return",
"GO",
"IDs",
"sorting",
"using",
"go2nt",
"s",
"namedtuple",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_gos.py#L70-L94 |
242,130 | tanghaibao/goatools | goatools/grouper/sorter_gos.py | SorterGoIds._get_go2nt | def _get_go2nt(self, goids):
"""Get go2nt for given goids."""
go2nt_all = self.grprobj.go2nt
return {go:go2nt_all[go] for go in goids} | python | def _get_go2nt(self, goids):
go2nt_all = self.grprobj.go2nt
return {go:go2nt_all[go] for go in goids} | [
"def",
"_get_go2nt",
"(",
"self",
",",
"goids",
")",
":",
"go2nt_all",
"=",
"self",
".",
"grprobj",
".",
"go2nt",
"return",
"{",
"go",
":",
"go2nt_all",
"[",
"go",
"]",
"for",
"go",
"in",
"goids",
"}"
] | Get go2nt for given goids. | [
"Get",
"go2nt",
"for",
"given",
"goids",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_gos.py#L96-L99 |
242,131 | tanghaibao/goatools | goatools/grouper/sorter_gos.py | SorterGoIds._init_hdrgo_sortby | def _init_hdrgo_sortby(self, hdrgo_sortby, sortby):
"""Initialize header sort function."""
if hdrgo_sortby is not None:
return hdrgo_sortby
if sortby is not None:
return sortby
return self.sortby | python | def _init_hdrgo_sortby(self, hdrgo_sortby, sortby):
if hdrgo_sortby is not None:
return hdrgo_sortby
if sortby is not None:
return sortby
return self.sortby | [
"def",
"_init_hdrgo_sortby",
"(",
"self",
",",
"hdrgo_sortby",
",",
"sortby",
")",
":",
"if",
"hdrgo_sortby",
"is",
"not",
"None",
":",
"return",
"hdrgo_sortby",
"if",
"sortby",
"is",
"not",
"None",
":",
"return",
"sortby",
"return",
"self",
".",
"sortby"
] | Initialize header sort function. | [
"Initialize",
"header",
"sort",
"function",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_gos.py#L101-L107 |
242,132 | tanghaibao/goatools | goatools/godag_plot.py | plot_goid2goobj | def plot_goid2goobj(fout_png, goid2goobj, *args, **kws):
"""Given a dict containing GO id and its goobj, create a plot of paths from GO ids."""
engine = kws['engine'] if 'engine' in kws else 'pydot'
godagsmall = OboToGoDagSmall(goid2goobj=goid2goobj).godag
godagplot = GODagSmallPlot(godagsmall, *args, **kws)
godagplot.plt(fout_png, engine) | python | def plot_goid2goobj(fout_png, goid2goobj, *args, **kws):
engine = kws['engine'] if 'engine' in kws else 'pydot'
godagsmall = OboToGoDagSmall(goid2goobj=goid2goobj).godag
godagplot = GODagSmallPlot(godagsmall, *args, **kws)
godagplot.plt(fout_png, engine) | [
"def",
"plot_goid2goobj",
"(",
"fout_png",
",",
"goid2goobj",
",",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"engine",
"=",
"kws",
"[",
"'engine'",
"]",
"if",
"'engine'",
"in",
"kws",
"else",
"'pydot'",
"godagsmall",
"=",
"OboToGoDagSmall",
"(",
"goid... | Given a dict containing GO id and its goobj, create a plot of paths from GO ids. | [
"Given",
"a",
"dict",
"containing",
"GO",
"id",
"and",
"its",
"goobj",
"create",
"a",
"plot",
"of",
"paths",
"from",
"GO",
"ids",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_plot.py#L19-L24 |
242,133 | tanghaibao/goatools | goatools/godag_plot.py | GODagSmallPlot._init_study_items_max | def _init_study_items_max(self):
"""User can limit the number of genes printed in a GO term."""
if self.study_items is None:
return None
if self.study_items is True:
return None
if isinstance(self.study_items, int):
return self.study_items
return None | python | def _init_study_items_max(self):
if self.study_items is None:
return None
if self.study_items is True:
return None
if isinstance(self.study_items, int):
return self.study_items
return None | [
"def",
"_init_study_items_max",
"(",
"self",
")",
":",
"if",
"self",
".",
"study_items",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"study_items",
"is",
"True",
":",
"return",
"None",
"if",
"isinstance",
"(",
"self",
".",
"study_items",
",",
... | User can limit the number of genes printed in a GO term. | [
"User",
"can",
"limit",
"the",
"number",
"of",
"genes",
"printed",
"in",
"a",
"GO",
"term",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_plot.py#L105-L113 |
242,134 | tanghaibao/goatools | goatools/godag_plot.py | GODagSmallPlot._init_go2res | def _init_go2res(**kws):
"""Initialize GOEA results."""
if 'goea_results' in kws:
return {res.GO:res for res in kws['goea_results']}
if 'go2nt' in kws:
return kws['go2nt'] | python | def _init_go2res(**kws):
if 'goea_results' in kws:
return {res.GO:res for res in kws['goea_results']}
if 'go2nt' in kws:
return kws['go2nt'] | [
"def",
"_init_go2res",
"(",
"*",
"*",
"kws",
")",
":",
"if",
"'goea_results'",
"in",
"kws",
":",
"return",
"{",
"res",
".",
"GO",
":",
"res",
"for",
"res",
"in",
"kws",
"[",
"'goea_results'",
"]",
"}",
"if",
"'go2nt'",
"in",
"kws",
":",
"return",
"... | Initialize GOEA results. | [
"Initialize",
"GOEA",
"results",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_plot.py#L116-L121 |
242,135 | tanghaibao/goatools | goatools/godag_plot.py | GODagSmallPlot._get_pydot | def _get_pydot(self):
"""Return pydot package. Load pydot, if necessary."""
if self.pydot:
return self.pydot
self.pydot = __import__("pydot")
return self.pydot | python | def _get_pydot(self):
if self.pydot:
return self.pydot
self.pydot = __import__("pydot")
return self.pydot | [
"def",
"_get_pydot",
"(",
"self",
")",
":",
"if",
"self",
".",
"pydot",
":",
"return",
"self",
".",
"pydot",
"self",
".",
"pydot",
"=",
"__import__",
"(",
"\"pydot\"",
")",
"return",
"self",
".",
"pydot"
] | Return pydot package. Load pydot, if necessary. | [
"Return",
"pydot",
"package",
".",
"Load",
"pydot",
"if",
"necessary",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_plot.py#L217-L222 |
242,136 | tanghaibao/goatools | goatools/wr_tbl.py | wr_xlsx | def wr_xlsx(fout_xlsx, data_xlsx, **kws):
"""Write a spreadsheet into a xlsx file."""
from goatools.wr_tbl_class import WrXlsx
# optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds
items_str = kws.get("items", "items") if "items" not in kws else kws["items"]
if data_xlsx:
# Open xlsx file
xlsxobj = WrXlsx(fout_xlsx, data_xlsx[0]._fields, **kws)
worksheet = xlsxobj.add_worksheet()
# Write title (optional) and headers.
row_idx = xlsxobj.wr_title(worksheet)
row_idx = xlsxobj.wr_hdrs(worksheet, row_idx)
row_idx_data0 = row_idx
# Write data
row_idx = xlsxobj.wr_data(data_xlsx, row_idx, worksheet)
# Close xlsx file
xlsxobj.workbook.close()
sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT}\n".format(
N=row_idx-row_idx_data0, ITEMS=items_str, FOUT=fout_xlsx))
else:
sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format(
ITEMS=items_str, FOUT=fout_xlsx)) | python | def wr_xlsx(fout_xlsx, data_xlsx, **kws):
from goatools.wr_tbl_class import WrXlsx
# optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds
items_str = kws.get("items", "items") if "items" not in kws else kws["items"]
if data_xlsx:
# Open xlsx file
xlsxobj = WrXlsx(fout_xlsx, data_xlsx[0]._fields, **kws)
worksheet = xlsxobj.add_worksheet()
# Write title (optional) and headers.
row_idx = xlsxobj.wr_title(worksheet)
row_idx = xlsxobj.wr_hdrs(worksheet, row_idx)
row_idx_data0 = row_idx
# Write data
row_idx = xlsxobj.wr_data(data_xlsx, row_idx, worksheet)
# Close xlsx file
xlsxobj.workbook.close()
sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT}\n".format(
N=row_idx-row_idx_data0, ITEMS=items_str, FOUT=fout_xlsx))
else:
sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format(
ITEMS=items_str, FOUT=fout_xlsx)) | [
"def",
"wr_xlsx",
"(",
"fout_xlsx",
",",
"data_xlsx",
",",
"*",
"*",
"kws",
")",
":",
"from",
"goatools",
".",
"wr_tbl_class",
"import",
"WrXlsx",
"# optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds",
"items_str",
"=",
"kws",
".",
"get",
"(",... | Write a spreadsheet into a xlsx file. | [
"Write",
"a",
"spreadsheet",
"into",
"a",
"xlsx",
"file",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L63-L84 |
242,137 | tanghaibao/goatools | goatools/wr_tbl.py | wr_xlsx_sections | def wr_xlsx_sections(fout_xlsx, xlsx_data, **kws):
"""Write xlsx file containing section names followed by lines of namedtuple data."""
from goatools.wr_tbl_class import WrXlsx
items_str = "items" if "items" not in kws else kws["items"]
prt_hdr_min = 10
num_items = 0
if xlsx_data:
# Basic data checks
assert len(xlsx_data[0]) == 2, "wr_xlsx_sections EXPECTED: [(section, nts), ..."
assert xlsx_data[0][1], \
"wr_xlsx_sections EXPECTED SECTION({S}) LIST TO HAVE DATA".format(S=xlsx_data[0][0])
# Open xlsx file and write title (optional) and headers.
xlsxobj = WrXlsx(fout_xlsx, xlsx_data[0][1][0]._fields, **kws)
worksheet = xlsxobj.add_worksheet()
row_idx = xlsxobj.wr_title(worksheet)
hdrs_wrote = False
# Write data
for section_text, data_nts in xlsx_data:
num_items += len(data_nts)
fmt = xlsxobj.wbfmtobj.get_fmt_section()
row_idx = xlsxobj.wr_row_mergeall(worksheet, section_text, fmt, row_idx)
if hdrs_wrote is False or len(data_nts) > prt_hdr_min:
row_idx = xlsxobj.wr_hdrs(worksheet, row_idx)
hdrs_wrote = True
row_idx = xlsxobj.wr_data(data_nts, row_idx, worksheet)
# Close xlsx file
xlsxobj.workbook.close()
sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT} ({S} sections)\n".format(
N=num_items, ITEMS=items_str, FOUT=fout_xlsx, S=len(xlsx_data)))
else:
sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format(
ITEMS=items_str, FOUT=fout_xlsx)) | python | def wr_xlsx_sections(fout_xlsx, xlsx_data, **kws):
from goatools.wr_tbl_class import WrXlsx
items_str = "items" if "items" not in kws else kws["items"]
prt_hdr_min = 10
num_items = 0
if xlsx_data:
# Basic data checks
assert len(xlsx_data[0]) == 2, "wr_xlsx_sections EXPECTED: [(section, nts), ..."
assert xlsx_data[0][1], \
"wr_xlsx_sections EXPECTED SECTION({S}) LIST TO HAVE DATA".format(S=xlsx_data[0][0])
# Open xlsx file and write title (optional) and headers.
xlsxobj = WrXlsx(fout_xlsx, xlsx_data[0][1][0]._fields, **kws)
worksheet = xlsxobj.add_worksheet()
row_idx = xlsxobj.wr_title(worksheet)
hdrs_wrote = False
# Write data
for section_text, data_nts in xlsx_data:
num_items += len(data_nts)
fmt = xlsxobj.wbfmtobj.get_fmt_section()
row_idx = xlsxobj.wr_row_mergeall(worksheet, section_text, fmt, row_idx)
if hdrs_wrote is False or len(data_nts) > prt_hdr_min:
row_idx = xlsxobj.wr_hdrs(worksheet, row_idx)
hdrs_wrote = True
row_idx = xlsxobj.wr_data(data_nts, row_idx, worksheet)
# Close xlsx file
xlsxobj.workbook.close()
sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT} ({S} sections)\n".format(
N=num_items, ITEMS=items_str, FOUT=fout_xlsx, S=len(xlsx_data)))
else:
sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format(
ITEMS=items_str, FOUT=fout_xlsx)) | [
"def",
"wr_xlsx_sections",
"(",
"fout_xlsx",
",",
"xlsx_data",
",",
"*",
"*",
"kws",
")",
":",
"from",
"goatools",
".",
"wr_tbl_class",
"import",
"WrXlsx",
"items_str",
"=",
"\"items\"",
"if",
"\"items\"",
"not",
"in",
"kws",
"else",
"kws",
"[",
"\"items\"",... | Write xlsx file containing section names followed by lines of namedtuple data. | [
"Write",
"xlsx",
"file",
"containing",
"section",
"names",
"followed",
"by",
"lines",
"of",
"namedtuple",
"data",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L86-L117 |
242,138 | tanghaibao/goatools | goatools/wr_tbl.py | wr_tsv | def wr_tsv(fout_tsv, tsv_data, **kws):
"""Write a file of tab-separated table data"""
items_str = "items" if "items" not in kws else kws["items"]
if tsv_data:
ifstrm = sys.stdout if fout_tsv is None else open(fout_tsv, 'w')
num_items = prt_tsv(ifstrm, tsv_data, **kws)
if fout_tsv is not None:
sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT}\n".format(
N=num_items, ITEMS=items_str, FOUT=fout_tsv))
ifstrm.close()
else:
sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format(
ITEMS=items_str, FOUT=fout_tsv)) | python | def wr_tsv(fout_tsv, tsv_data, **kws):
items_str = "items" if "items" not in kws else kws["items"]
if tsv_data:
ifstrm = sys.stdout if fout_tsv is None else open(fout_tsv, 'w')
num_items = prt_tsv(ifstrm, tsv_data, **kws)
if fout_tsv is not None:
sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT}\n".format(
N=num_items, ITEMS=items_str, FOUT=fout_tsv))
ifstrm.close()
else:
sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format(
ITEMS=items_str, FOUT=fout_tsv)) | [
"def",
"wr_tsv",
"(",
"fout_tsv",
",",
"tsv_data",
",",
"*",
"*",
"kws",
")",
":",
"items_str",
"=",
"\"items\"",
"if",
"\"items\"",
"not",
"in",
"kws",
"else",
"kws",
"[",
"\"items\"",
"]",
"if",
"tsv_data",
":",
"ifstrm",
"=",
"sys",
".",
"stdout",
... | Write a file of tab-separated table data | [
"Write",
"a",
"file",
"of",
"tab",
"-",
"separated",
"table",
"data"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L119-L131 |
242,139 | tanghaibao/goatools | goatools/wr_tbl.py | prt_tsv_sections | def prt_tsv_sections(prt, tsv_data, **kws):
"""Write tsv file containing section names followed by lines of namedtuple data."""
prt_hdr_min = 10 # Print hdr on the 1st section and for any following 'large' sections
num_items = 0
if tsv_data:
# Basic data checks
assert len(tsv_data[0]) == 2, "wr_tsv_sections EXPECTED: [(section, nts), ..."
assert tsv_data[0][1], \
"wr_tsv_sections EXPECTED SECTION({S}) LIST TO HAVE DATA".format(S=tsv_data[0][0])
hdrs_wrote = False
sep = "\t" if 'sep' not in kws else kws['sep']
prt_flds = kws['prt_flds'] if 'prt_flds' in kws else tsv_data[0]._fields
fill = sep*(len(prt_flds) - 1)
# Write data
for section_text, data_nts in tsv_data:
prt.write("{SEC}{FILL}\n".format(SEC=section_text, FILL=fill))
if hdrs_wrote is False or len(data_nts) > prt_hdr_min:
prt_tsv_hdr(prt, data_nts, **kws)
hdrs_wrote = True
num_items += prt_tsv_dat(prt, data_nts, **kws)
return num_items
else:
return 0 | python | def prt_tsv_sections(prt, tsv_data, **kws):
prt_hdr_min = 10 # Print hdr on the 1st section and for any following 'large' sections
num_items = 0
if tsv_data:
# Basic data checks
assert len(tsv_data[0]) == 2, "wr_tsv_sections EXPECTED: [(section, nts), ..."
assert tsv_data[0][1], \
"wr_tsv_sections EXPECTED SECTION({S}) LIST TO HAVE DATA".format(S=tsv_data[0][0])
hdrs_wrote = False
sep = "\t" if 'sep' not in kws else kws['sep']
prt_flds = kws['prt_flds'] if 'prt_flds' in kws else tsv_data[0]._fields
fill = sep*(len(prt_flds) - 1)
# Write data
for section_text, data_nts in tsv_data:
prt.write("{SEC}{FILL}\n".format(SEC=section_text, FILL=fill))
if hdrs_wrote is False or len(data_nts) > prt_hdr_min:
prt_tsv_hdr(prt, data_nts, **kws)
hdrs_wrote = True
num_items += prt_tsv_dat(prt, data_nts, **kws)
return num_items
else:
return 0 | [
"def",
"prt_tsv_sections",
"(",
"prt",
",",
"tsv_data",
",",
"*",
"*",
"kws",
")",
":",
"prt_hdr_min",
"=",
"10",
"# Print hdr on the 1st section and for any following 'large' sections",
"num_items",
"=",
"0",
"if",
"tsv_data",
":",
"# Basic data checks",
"assert",
"l... | Write tsv file containing section names followed by lines of namedtuple data. | [
"Write",
"tsv",
"file",
"containing",
"section",
"names",
"followed",
"by",
"lines",
"of",
"namedtuple",
"data",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L133-L155 |
242,140 | tanghaibao/goatools | goatools/wr_tbl.py | prt_tsv | def prt_tsv(prt, data_nts, **kws):
"""Print tab-separated table headers and data"""
# User-controlled printing options
prt_tsv_hdr(prt, data_nts, **kws)
return prt_tsv_dat(prt, data_nts, **kws) | python | def prt_tsv(prt, data_nts, **kws):
# User-controlled printing options
prt_tsv_hdr(prt, data_nts, **kws)
return prt_tsv_dat(prt, data_nts, **kws) | [
"def",
"prt_tsv",
"(",
"prt",
",",
"data_nts",
",",
"*",
"*",
"kws",
")",
":",
"# User-controlled printing options",
"prt_tsv_hdr",
"(",
"prt",
",",
"data_nts",
",",
"*",
"*",
"kws",
")",
"return",
"prt_tsv_dat",
"(",
"prt",
",",
"data_nts",
",",
"*",
"*... | Print tab-separated table headers and data | [
"Print",
"tab",
"-",
"separated",
"table",
"headers",
"and",
"data"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L157-L161 |
242,141 | tanghaibao/goatools | goatools/wr_tbl.py | prt_tsv_hdr | def prt_tsv_hdr(prt, data_nts, **kws):
"""Print tab-separated table headers"""
sep = "\t" if 'sep' not in kws else kws['sep']
flds_all = data_nts[0]._fields
hdrs = get_hdrs(flds_all, **kws)
prt.write("# {}\n".format(sep.join(hdrs))) | python | def prt_tsv_hdr(prt, data_nts, **kws):
sep = "\t" if 'sep' not in kws else kws['sep']
flds_all = data_nts[0]._fields
hdrs = get_hdrs(flds_all, **kws)
prt.write("# {}\n".format(sep.join(hdrs))) | [
"def",
"prt_tsv_hdr",
"(",
"prt",
",",
"data_nts",
",",
"*",
"*",
"kws",
")",
":",
"sep",
"=",
"\"\\t\"",
"if",
"'sep'",
"not",
"in",
"kws",
"else",
"kws",
"[",
"'sep'",
"]",
"flds_all",
"=",
"data_nts",
"[",
"0",
"]",
".",
"_fields",
"hdrs",
"=",
... | Print tab-separated table headers | [
"Print",
"tab",
"-",
"separated",
"table",
"headers"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L163-L168 |
242,142 | tanghaibao/goatools | goatools/wr_tbl.py | prt_tsv_dat | def prt_tsv_dat(prt, data_nts, **kws):
"""Print tab-separated table data"""
sep = "\t" if 'sep' not in kws else kws['sep']
fld2fmt = None if 'fld2fmt' not in kws else kws['fld2fmt']
if 'sort_by' in kws:
data_nts = sorted(data_nts, key=kws['sort_by'])
prt_if = kws['prt_if'] if 'prt_if' in kws else None
prt_flds = kws['prt_flds'] if 'prt_flds' in kws else data_nts[0]._fields
items = 0
for nt_data_row in data_nts:
if prt_if is None or prt_if(nt_data_row):
if fld2fmt is not None:
row_fld_vals = [(fld, getattr(nt_data_row, fld)) for fld in prt_flds]
row_vals = _fmt_fields(row_fld_vals, fld2fmt)
else:
row_vals = [getattr(nt_data_row, fld) for fld in prt_flds]
prt.write("{}\n".format(sep.join(str(d) for d in row_vals)))
items += 1
return items | python | def prt_tsv_dat(prt, data_nts, **kws):
sep = "\t" if 'sep' not in kws else kws['sep']
fld2fmt = None if 'fld2fmt' not in kws else kws['fld2fmt']
if 'sort_by' in kws:
data_nts = sorted(data_nts, key=kws['sort_by'])
prt_if = kws['prt_if'] if 'prt_if' in kws else None
prt_flds = kws['prt_flds'] if 'prt_flds' in kws else data_nts[0]._fields
items = 0
for nt_data_row in data_nts:
if prt_if is None or prt_if(nt_data_row):
if fld2fmt is not None:
row_fld_vals = [(fld, getattr(nt_data_row, fld)) for fld in prt_flds]
row_vals = _fmt_fields(row_fld_vals, fld2fmt)
else:
row_vals = [getattr(nt_data_row, fld) for fld in prt_flds]
prt.write("{}\n".format(sep.join(str(d) for d in row_vals)))
items += 1
return items | [
"def",
"prt_tsv_dat",
"(",
"prt",
",",
"data_nts",
",",
"*",
"*",
"kws",
")",
":",
"sep",
"=",
"\"\\t\"",
"if",
"'sep'",
"not",
"in",
"kws",
"else",
"kws",
"[",
"'sep'",
"]",
"fld2fmt",
"=",
"None",
"if",
"'fld2fmt'",
"not",
"in",
"kws",
"else",
"k... | Print tab-separated table data | [
"Print",
"tab",
"-",
"separated",
"table",
"data"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L170-L188 |
242,143 | tanghaibao/goatools | goatools/wr_tbl.py | _chk_flds_fmt | def _chk_flds_fmt(nt_fields, prtfmt):
"""Check that all fields in the prtfmt have corresponding data in the namedtuple."""
fmtflds = get_fmtflds(prtfmt)
missing_data = set(fmtflds).difference(set(nt_fields))
# All data needed for print is present, return.
if not missing_data:
return
#raise Exception('MISSING DATA({M}).'.format(M=" ".join(missing_data)))
msg = ['CANNOT PRINT USING: "{PF}"'.format(PF=prtfmt.rstrip())]
for fld in fmtflds:
errmrk = "" if fld in nt_fields else "ERROR-->"
msg.append(" {ERR:8} {FLD}".format(ERR=errmrk, FLD=fld))
raise Exception('\n'.join(msg)) | python | def _chk_flds_fmt(nt_fields, prtfmt):
fmtflds = get_fmtflds(prtfmt)
missing_data = set(fmtflds).difference(set(nt_fields))
# All data needed for print is present, return.
if not missing_data:
return
#raise Exception('MISSING DATA({M}).'.format(M=" ".join(missing_data)))
msg = ['CANNOT PRINT USING: "{PF}"'.format(PF=prtfmt.rstrip())]
for fld in fmtflds:
errmrk = "" if fld in nt_fields else "ERROR-->"
msg.append(" {ERR:8} {FLD}".format(ERR=errmrk, FLD=fld))
raise Exception('\n'.join(msg)) | [
"def",
"_chk_flds_fmt",
"(",
"nt_fields",
",",
"prtfmt",
")",
":",
"fmtflds",
"=",
"get_fmtflds",
"(",
"prtfmt",
")",
"missing_data",
"=",
"set",
"(",
"fmtflds",
")",
".",
"difference",
"(",
"set",
"(",
"nt_fields",
")",
")",
"# All data needed for print is pr... | Check that all fields in the prtfmt have corresponding data in the namedtuple. | [
"Check",
"that",
"all",
"fields",
"in",
"the",
"prtfmt",
"have",
"corresponding",
"data",
"in",
"the",
"namedtuple",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L199-L211 |
242,144 | tanghaibao/goatools | goatools/wr_tbl.py | _prt_txt_hdr | def _prt_txt_hdr(prt, prtfmt):
"""Print header for text report."""
tblhdrs = get_fmtfldsdict(prtfmt)
# If needed, reformat for format_string for header, which has strings, not floats.
hdrfmt = re.sub(r':(\d+)\.\S+}', r':\1}', prtfmt)
hdrfmt = re.sub(r':(0+)(\d+)}', r':\2}', hdrfmt)
prt.write("#{}".format(hdrfmt.format(**tblhdrs))) | python | def _prt_txt_hdr(prt, prtfmt):
tblhdrs = get_fmtfldsdict(prtfmt)
# If needed, reformat for format_string for header, which has strings, not floats.
hdrfmt = re.sub(r':(\d+)\.\S+}', r':\1}', prtfmt)
hdrfmt = re.sub(r':(0+)(\d+)}', r':\2}', hdrfmt)
prt.write("#{}".format(hdrfmt.format(**tblhdrs))) | [
"def",
"_prt_txt_hdr",
"(",
"prt",
",",
"prtfmt",
")",
":",
"tblhdrs",
"=",
"get_fmtfldsdict",
"(",
"prtfmt",
")",
"# If needed, reformat for format_string for header, which has strings, not floats.",
"hdrfmt",
"=",
"re",
".",
"sub",
"(",
"r':(\\d+)\\.\\S+}'",
",",
"r':... | Print header for text report. | [
"Print",
"header",
"for",
"text",
"report",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L223-L229 |
242,145 | tanghaibao/goatools | goatools/wr_tbl.py | mk_fmtfld | def mk_fmtfld(nt_item, joinchr=" ", eol="\n"):
"""Given a namedtuple, return a format_field string."""
fldstrs = []
# Default formats based on fieldname
fld2fmt = {
'hdrgo' : lambda f: "{{{FLD}:1,}}".format(FLD=f),
'dcnt' : lambda f: "{{{FLD}:6,}}".format(FLD=f),
'level' : lambda f: "L{{{FLD}:02,}}".format(FLD=f),
'depth' : lambda f: "D{{{FLD}:02,}}".format(FLD=f),
}
for fld in nt_item._fields:
if fld in fld2fmt:
val = fld2fmt[fld](fld)
else:
val = "{{{FLD}}}".format(FLD=fld)
fldstrs.append(val)
return "{LINE}{EOL}".format(LINE=joinchr.join(fldstrs), EOL=eol) | python | def mk_fmtfld(nt_item, joinchr=" ", eol="\n"):
fldstrs = []
# Default formats based on fieldname
fld2fmt = {
'hdrgo' : lambda f: "{{{FLD}:1,}}".format(FLD=f),
'dcnt' : lambda f: "{{{FLD}:6,}}".format(FLD=f),
'level' : lambda f: "L{{{FLD}:02,}}".format(FLD=f),
'depth' : lambda f: "D{{{FLD}:02,}}".format(FLD=f),
}
for fld in nt_item._fields:
if fld in fld2fmt:
val = fld2fmt[fld](fld)
else:
val = "{{{FLD}}}".format(FLD=fld)
fldstrs.append(val)
return "{LINE}{EOL}".format(LINE=joinchr.join(fldstrs), EOL=eol) | [
"def",
"mk_fmtfld",
"(",
"nt_item",
",",
"joinchr",
"=",
"\" \"",
",",
"eol",
"=",
"\"\\n\"",
")",
":",
"fldstrs",
"=",
"[",
"]",
"# Default formats based on fieldname",
"fld2fmt",
"=",
"{",
"'hdrgo'",
":",
"lambda",
"f",
":",
"\"{{{FLD}:1,}}\"",
".",
"forma... | Given a namedtuple, return a format_field string. | [
"Given",
"a",
"namedtuple",
"return",
"a",
"format_field",
"string",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L231-L247 |
242,146 | tanghaibao/goatools | goatools/cli/compare_gos.py | CompareGOsCli._get_prtfmt | def _get_prtfmt(self, objgowr, verbose):
"""Get print format containing markers."""
prtfmt = objgowr.get_prtfmt('fmt')
prtfmt = prtfmt.replace('# ', '')
# print('PPPPPPPPPPP', prtfmt)
if not verbose:
prtfmt = prtfmt.replace('{hdr1usr01:2}', '')
prtfmt = prtfmt.replace('{childcnt:3} L{level:02} ', '')
prtfmt = prtfmt.replace('{num_usrgos:>4} uGOs ', '')
prtfmt = prtfmt.replace('{D1:5} {REL} {rel}', '')
prtfmt = prtfmt.replace('R{reldepth:02} ', '')
# print('PPPPPPPPPPP', prtfmt)
marks = ''.join(['{{{}}}'.format(nt.hdr) for nt in self.go_ntsets])
return '{MARKS} {PRTFMT}'.format(MARKS=marks, PRTFMT=prtfmt) | python | def _get_prtfmt(self, objgowr, verbose):
prtfmt = objgowr.get_prtfmt('fmt')
prtfmt = prtfmt.replace('# ', '')
# print('PPPPPPPPPPP', prtfmt)
if not verbose:
prtfmt = prtfmt.replace('{hdr1usr01:2}', '')
prtfmt = prtfmt.replace('{childcnt:3} L{level:02} ', '')
prtfmt = prtfmt.replace('{num_usrgos:>4} uGOs ', '')
prtfmt = prtfmt.replace('{D1:5} {REL} {rel}', '')
prtfmt = prtfmt.replace('R{reldepth:02} ', '')
# print('PPPPPPPPPPP', prtfmt)
marks = ''.join(['{{{}}}'.format(nt.hdr) for nt in self.go_ntsets])
return '{MARKS} {PRTFMT}'.format(MARKS=marks, PRTFMT=prtfmt) | [
"def",
"_get_prtfmt",
"(",
"self",
",",
"objgowr",
",",
"verbose",
")",
":",
"prtfmt",
"=",
"objgowr",
".",
"get_prtfmt",
"(",
"'fmt'",
")",
"prtfmt",
"=",
"prtfmt",
".",
"replace",
"(",
"'# '",
",",
"''",
")",
"# print('PPPPPPPPPPP', prtfmt)",
"if",
"not"... | Get print format containing markers. | [
"Get",
"print",
"format",
"containing",
"markers",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L113-L126 |
242,147 | tanghaibao/goatools | goatools/cli/compare_gos.py | CompareGOsCli._wr_ver_n_key | def _wr_ver_n_key(self, fout_txt, verbose):
"""Write GO DAG version and key indicating presence of GO ID in a list."""
with open(fout_txt, 'w') as prt:
self._prt_ver_n_key(prt, verbose)
print(' WROTE: {TXT}'.format(TXT=fout_txt)) | python | def _wr_ver_n_key(self, fout_txt, verbose):
with open(fout_txt, 'w') as prt:
self._prt_ver_n_key(prt, verbose)
print(' WROTE: {TXT}'.format(TXT=fout_txt)) | [
"def",
"_wr_ver_n_key",
"(",
"self",
",",
"fout_txt",
",",
"verbose",
")",
":",
"with",
"open",
"(",
"fout_txt",
",",
"'w'",
")",
"as",
"prt",
":",
"self",
".",
"_prt_ver_n_key",
"(",
"prt",
",",
"verbose",
")",
"print",
"(",
"' WROTE: {TXT}'... | Write GO DAG version and key indicating presence of GO ID in a list. | [
"Write",
"GO",
"DAG",
"version",
"and",
"key",
"indicating",
"presence",
"of",
"GO",
"ID",
"in",
"a",
"list",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L153-L157 |
242,148 | tanghaibao/goatools | goatools/cli/compare_gos.py | CompareGOsCli._prt_ver_n_key | def _prt_ver_n_key(self, prt, verbose):
"""Print GO DAG version and key indicating presence of GO ID in a list."""
pre = '# '
prt.write('# ----------------------------------------------------------------\n')
prt.write('# - Description of GO ID fields\n')
prt.write('# ----------------------------------------------------------------\n')
prt.write("# Versions:\n# {VER}\n".format(VER="\n# ".join(self.objgrpd.ver_list)))
prt.write('\n# Marker keys:\n')
for ntgos in self.go_ntsets:
prt.write('# X -> GO is present in {HDR}\n'.format(HDR=ntgos.hdr))
if verbose:
prt.write('\n# Markers for header GO IDs and user GO IDs:\n')
prt.write("# '**' -> GO term is both a header and a user GO ID\n")
prt.write("# '* ' -> GO term is a header, but not a user GO ID\n")
prt.write("# ' ' -> GO term is a user GO ID\n")
prt.write('\n# GO Namspaces:\n')
prt.write('# BP -> Biological Process\n')
prt.write('# MF -> Molecular Function\n')
prt.write('# CC -> Cellualr Component\n')
if verbose:
prt.write('\n# Example fields: 5 uGOs 362 47 L04 D04 R04\n')
prt.write('# N uGOs -> number of user GO IDs under this GO header\n')
prt.write('# First integer -> number of GO descendants\n')
prt.write('# Second integer -> number of GO children for the current GO ID\n')
prt.write('\n# Depth information:\n')
if not verbose:
prt.write('# int -> number of GO descendants\n')
if verbose:
prt.write('# Lnn -> level (minimum distance from root to node)\n')
prt.write('# Dnn -> depth (maximum distance from root to node)\n')
if verbose:
prt.write('# Rnn -> depth accounting for relationships\n\n')
RelationshipStr().prt_keys(prt, pre)
if verbose:
prt.write('\n')
objd1 = GoDepth1LettersWr(self.gosubdag.rcntobj)
objd1.prt_header(prt, 'DEPTH-01 GO terms and their aliases', pre)
objd1.prt_txt(prt, pre) | python | def _prt_ver_n_key(self, prt, verbose):
pre = '# '
prt.write('# ----------------------------------------------------------------\n')
prt.write('# - Description of GO ID fields\n')
prt.write('# ----------------------------------------------------------------\n')
prt.write("# Versions:\n# {VER}\n".format(VER="\n# ".join(self.objgrpd.ver_list)))
prt.write('\n# Marker keys:\n')
for ntgos in self.go_ntsets:
prt.write('# X -> GO is present in {HDR}\n'.format(HDR=ntgos.hdr))
if verbose:
prt.write('\n# Markers for header GO IDs and user GO IDs:\n')
prt.write("# '**' -> GO term is both a header and a user GO ID\n")
prt.write("# '* ' -> GO term is a header, but not a user GO ID\n")
prt.write("# ' ' -> GO term is a user GO ID\n")
prt.write('\n# GO Namspaces:\n')
prt.write('# BP -> Biological Process\n')
prt.write('# MF -> Molecular Function\n')
prt.write('# CC -> Cellualr Component\n')
if verbose:
prt.write('\n# Example fields: 5 uGOs 362 47 L04 D04 R04\n')
prt.write('# N uGOs -> number of user GO IDs under this GO header\n')
prt.write('# First integer -> number of GO descendants\n')
prt.write('# Second integer -> number of GO children for the current GO ID\n')
prt.write('\n# Depth information:\n')
if not verbose:
prt.write('# int -> number of GO descendants\n')
if verbose:
prt.write('# Lnn -> level (minimum distance from root to node)\n')
prt.write('# Dnn -> depth (maximum distance from root to node)\n')
if verbose:
prt.write('# Rnn -> depth accounting for relationships\n\n')
RelationshipStr().prt_keys(prt, pre)
if verbose:
prt.write('\n')
objd1 = GoDepth1LettersWr(self.gosubdag.rcntobj)
objd1.prt_header(prt, 'DEPTH-01 GO terms and their aliases', pre)
objd1.prt_txt(prt, pre) | [
"def",
"_prt_ver_n_key",
"(",
"self",
",",
"prt",
",",
"verbose",
")",
":",
"pre",
"=",
"'# '",
"prt",
".",
"write",
"(",
"'# ----------------------------------------------------------------\\n'",
")",
"prt",
".",
"write",
"(",
"'# - Description of GO ID fields\\n'",
... | Print GO DAG version and key indicating presence of GO ID in a list. | [
"Print",
"GO",
"DAG",
"version",
"and",
"key",
"indicating",
"presence",
"of",
"GO",
"ID",
"in",
"a",
"list",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L160-L197 |
242,149 | tanghaibao/goatools | goatools/cli/compare_gos.py | _Init.get_grouped | def get_grouped(self, go_ntsets, go_all, gosubdag, **kws):
"""Get Grouped object."""
kws_grpd = {k:v for k, v in kws.items() if k in Grouped.kws_dict}
kws_grpd['go2nt'] = self._init_go2ntpresent(go_ntsets, go_all, gosubdag)
return Grouped(gosubdag, self.godag.version, **kws_grpd) | python | def get_grouped(self, go_ntsets, go_all, gosubdag, **kws):
kws_grpd = {k:v for k, v in kws.items() if k in Grouped.kws_dict}
kws_grpd['go2nt'] = self._init_go2ntpresent(go_ntsets, go_all, gosubdag)
return Grouped(gosubdag, self.godag.version, **kws_grpd) | [
"def",
"get_grouped",
"(",
"self",
",",
"go_ntsets",
",",
"go_all",
",",
"gosubdag",
",",
"*",
"*",
"kws",
")",
":",
"kws_grpd",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kws",
".",
"items",
"(",
")",
"if",
"k",
"in",
"Grouped",
"."... | Get Grouped object. | [
"Get",
"Grouped",
"object",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L214-L218 |
242,150 | tanghaibao/goatools | goatools/cli/compare_gos.py | _Init._init_go2ntpresent | def _init_go2ntpresent(go_ntsets, go_all, gosubdag):
"""Mark all GO IDs with an X if present in the user GO list."""
go2ntpresent = {}
ntobj = namedtuple('NtPresent', " ".join(nt.hdr for nt in go_ntsets))
# Get present marks for GO sources
for goid_all in go_all:
present_true = [goid_all in nt.go_set for nt in go_ntsets]
present_str = ['X' if tf else '.' for tf in present_true]
go2ntpresent[goid_all] = ntobj._make(present_str)
# Get present marks for all other GO ancestors
goids_ancestors = set(gosubdag.go2obj).difference(go2ntpresent)
assert not goids_ancestors.intersection(go_all)
strmark = ['.' for _ in range(len(go_ntsets))]
for goid in goids_ancestors:
go2ntpresent[goid] = ntobj._make(strmark)
return go2ntpresent | python | def _init_go2ntpresent(go_ntsets, go_all, gosubdag):
go2ntpresent = {}
ntobj = namedtuple('NtPresent', " ".join(nt.hdr for nt in go_ntsets))
# Get present marks for GO sources
for goid_all in go_all:
present_true = [goid_all in nt.go_set for nt in go_ntsets]
present_str = ['X' if tf else '.' for tf in present_true]
go2ntpresent[goid_all] = ntobj._make(present_str)
# Get present marks for all other GO ancestors
goids_ancestors = set(gosubdag.go2obj).difference(go2ntpresent)
assert not goids_ancestors.intersection(go_all)
strmark = ['.' for _ in range(len(go_ntsets))]
for goid in goids_ancestors:
go2ntpresent[goid] = ntobj._make(strmark)
return go2ntpresent | [
"def",
"_init_go2ntpresent",
"(",
"go_ntsets",
",",
"go_all",
",",
"gosubdag",
")",
":",
"go2ntpresent",
"=",
"{",
"}",
"ntobj",
"=",
"namedtuple",
"(",
"'NtPresent'",
",",
"\" \"",
".",
"join",
"(",
"nt",
".",
"hdr",
"for",
"nt",
"in",
"go_ntsets",
")",... | Mark all GO IDs with an X if present in the user GO list. | [
"Mark",
"all",
"GO",
"IDs",
"with",
"an",
"X",
"if",
"present",
"in",
"the",
"user",
"GO",
"list",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L221-L236 |
242,151 | tanghaibao/goatools | goatools/cli/compare_gos.py | _Init.get_go_ntsets | def get_go_ntsets(self, go_fins):
"""For each file containing GOs, extract GO IDs, store filename and header."""
nts = []
ntobj = namedtuple('NtGOFiles', 'hdr go_set, go_fin')
go_sets = self._init_go_sets(go_fins)
hdrs = [os.path.splitext(os.path.basename(f))[0] for f in go_fins]
assert len(go_fins) == len(go_sets)
assert len(go_fins) == len(hdrs)
for hdr, go_set, go_fin in zip(hdrs, go_sets, go_fins):
nts.append(ntobj(hdr=hdr, go_set=go_set, go_fin=go_fin))
return nts | python | def get_go_ntsets(self, go_fins):
nts = []
ntobj = namedtuple('NtGOFiles', 'hdr go_set, go_fin')
go_sets = self._init_go_sets(go_fins)
hdrs = [os.path.splitext(os.path.basename(f))[0] for f in go_fins]
assert len(go_fins) == len(go_sets)
assert len(go_fins) == len(hdrs)
for hdr, go_set, go_fin in zip(hdrs, go_sets, go_fins):
nts.append(ntobj(hdr=hdr, go_set=go_set, go_fin=go_fin))
return nts | [
"def",
"get_go_ntsets",
"(",
"self",
",",
"go_fins",
")",
":",
"nts",
"=",
"[",
"]",
"ntobj",
"=",
"namedtuple",
"(",
"'NtGOFiles'",
",",
"'hdr go_set, go_fin'",
")",
"go_sets",
"=",
"self",
".",
"_init_go_sets",
"(",
"go_fins",
")",
"hdrs",
"=",
"[",
"o... | For each file containing GOs, extract GO IDs, store filename and header. | [
"For",
"each",
"file",
"containing",
"GOs",
"extract",
"GO",
"IDs",
"store",
"filename",
"and",
"header",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L238-L248 |
242,152 | tanghaibao/goatools | goatools/cli/compare_gos.py | _Init._init_go_sets | def _init_go_sets(self, go_fins):
"""Get lists of GO IDs."""
go_sets = []
assert go_fins, "EXPECTED FILES CONTAINING GO IDs"
assert len(go_fins) >= 2, "EXPECTED 2+ GO LISTS. FOUND: {L}".format(
L=' '.join(go_fins))
obj = GetGOs(self.godag)
for fin in go_fins:
assert os.path.exists(fin), "GO FILE({F}) DOES NOT EXIST".format(F=fin)
go_sets.append(obj.get_usrgos(fin, sys.stdout))
return go_sets | python | def _init_go_sets(self, go_fins):
go_sets = []
assert go_fins, "EXPECTED FILES CONTAINING GO IDs"
assert len(go_fins) >= 2, "EXPECTED 2+ GO LISTS. FOUND: {L}".format(
L=' '.join(go_fins))
obj = GetGOs(self.godag)
for fin in go_fins:
assert os.path.exists(fin), "GO FILE({F}) DOES NOT EXIST".format(F=fin)
go_sets.append(obj.get_usrgos(fin, sys.stdout))
return go_sets | [
"def",
"_init_go_sets",
"(",
"self",
",",
"go_fins",
")",
":",
"go_sets",
"=",
"[",
"]",
"assert",
"go_fins",
",",
"\"EXPECTED FILES CONTAINING GO IDs\"",
"assert",
"len",
"(",
"go_fins",
")",
">=",
"2",
",",
"\"EXPECTED 2+ GO LISTS. FOUND: {L}\"",
".",
"format",
... | Get lists of GO IDs. | [
"Get",
"lists",
"of",
"GO",
"IDs",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L250-L260 |
242,153 | tanghaibao/goatools | goatools/gosubdag/godag_rcnt.py | CountRelatives.get_parents_letters | def get_parents_letters(self, goobj):
"""Get the letters representing all parent terms which are depth-01 GO terms."""
parents_all = set.union(self.go2parents[goobj.id])
parents_all.add(goobj.id)
# print "{}({}) D{:02}".format(goobj.id, goobj.name, goobj.depth), parents_all
parents_d1 = parents_all.intersection(self.gos_depth1)
return [self.goone2ntletter[g].D1 for g in parents_d1] | python | def get_parents_letters(self, goobj):
parents_all = set.union(self.go2parents[goobj.id])
parents_all.add(goobj.id)
# print "{}({}) D{:02}".format(goobj.id, goobj.name, goobj.depth), parents_all
parents_d1 = parents_all.intersection(self.gos_depth1)
return [self.goone2ntletter[g].D1 for g in parents_d1] | [
"def",
"get_parents_letters",
"(",
"self",
",",
"goobj",
")",
":",
"parents_all",
"=",
"set",
".",
"union",
"(",
"self",
".",
"go2parents",
"[",
"goobj",
".",
"id",
"]",
")",
"parents_all",
".",
"add",
"(",
"goobj",
".",
"id",
")",
"# print \"{}({}) D{:0... | Get the letters representing all parent terms which are depth-01 GO terms. | [
"Get",
"the",
"letters",
"representing",
"all",
"parent",
"terms",
"which",
"are",
"depth",
"-",
"01",
"GO",
"terms",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/godag_rcnt.py#L28-L34 |
242,154 | tanghaibao/goatools | goatools/gosubdag/godag_rcnt.py | CountRelatives.get_d1str | def get_d1str(self, goobj, reverse=False):
"""Get D1-string representing all parent terms which are depth-01 GO terms."""
return "".join(sorted(self.get_parents_letters(goobj), reverse=reverse)) | python | def get_d1str(self, goobj, reverse=False):
return "".join(sorted(self.get_parents_letters(goobj), reverse=reverse)) | [
"def",
"get_d1str",
"(",
"self",
",",
"goobj",
",",
"reverse",
"=",
"False",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"sorted",
"(",
"self",
".",
"get_parents_letters",
"(",
"goobj",
")",
",",
"reverse",
"=",
"reverse",
")",
")"
] | Get D1-string representing all parent terms which are depth-01 GO terms. | [
"Get",
"D1",
"-",
"string",
"representing",
"all",
"parent",
"terms",
"which",
"are",
"depth",
"-",
"01",
"GO",
"terms",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/godag_rcnt.py#L36-L38 |
242,155 | tanghaibao/goatools | goatools/gosubdag/go_most_specific.py | get_most_specific_dcnt | def get_most_specific_dcnt(goids, go2nt):
"""Get the GO ID with the lowest descendants count."""
# go2nt_usr = {go:go2nt[go] for go in goids}
# return min(go2nt_usr.items(), key=lambda t: t[1].dcnt)[0]
return min(_get_go2nt(goids, go2nt), key=lambda t: t[1].dcnt)[0] | python | def get_most_specific_dcnt(goids, go2nt):
# go2nt_usr = {go:go2nt[go] for go in goids}
# return min(go2nt_usr.items(), key=lambda t: t[1].dcnt)[0]
return min(_get_go2nt(goids, go2nt), key=lambda t: t[1].dcnt)[0] | [
"def",
"get_most_specific_dcnt",
"(",
"goids",
",",
"go2nt",
")",
":",
"# go2nt_usr = {go:go2nt[go] for go in goids}",
"# return min(go2nt_usr.items(), key=lambda t: t[1].dcnt)[0]",
"return",
"min",
"(",
"_get_go2nt",
"(",
"goids",
",",
"go2nt",
")",
",",
"key",
"=",
"lam... | Get the GO ID with the lowest descendants count. | [
"Get",
"the",
"GO",
"ID",
"with",
"the",
"lowest",
"descendants",
"count",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/go_most_specific.py#L7-L11 |
242,156 | tanghaibao/goatools | goatools/gosubdag/go_most_specific.py | _get_go2nt | def _get_go2nt(goids, go2nt_all):
"""Get user go2nt using main GO IDs, not alt IDs."""
go_nt_list = []
goids_seen = set()
for goid_usr in goids:
ntgo = go2nt_all[goid_usr]
goid_main = ntgo.id
if goid_main not in goids_seen:
goids_seen.add(goid_main)
go_nt_list.append((goid_main, ntgo))
return go_nt_list | python | def _get_go2nt(goids, go2nt_all):
go_nt_list = []
goids_seen = set()
for goid_usr in goids:
ntgo = go2nt_all[goid_usr]
goid_main = ntgo.id
if goid_main not in goids_seen:
goids_seen.add(goid_main)
go_nt_list.append((goid_main, ntgo))
return go_nt_list | [
"def",
"_get_go2nt",
"(",
"goids",
",",
"go2nt_all",
")",
":",
"go_nt_list",
"=",
"[",
"]",
"goids_seen",
"=",
"set",
"(",
")",
"for",
"goid_usr",
"in",
"goids",
":",
"ntgo",
"=",
"go2nt_all",
"[",
"goid_usr",
"]",
"goid_main",
"=",
"ntgo",
".",
"id",
... | Get user go2nt using main GO IDs, not alt IDs. | [
"Get",
"user",
"go2nt",
"using",
"main",
"GO",
"IDs",
"not",
"alt",
"IDs",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/go_most_specific.py#L25-L35 |
242,157 | tanghaibao/goatools | goatools/grouper/aart_geneproducts_one.py | AArtGeneProductSetsOne.prt_gos_grouped | def prt_gos_grouped(self, prt, **kws_grp):
"""Print grouped GO list."""
prtfmt = self.datobj.kws['fmtgo']
wrobj = WrXlsxSortedGos(self.name, self.sortobj)
# Keyword arguments: control content: hdrgo_prt section_prt top_n use_sections
desc2nts = self.sortobj.get_desc2nts(**kws_grp)
wrobj.prt_txt_desc2nts(prt, desc2nts, prtfmt) | python | def prt_gos_grouped(self, prt, **kws_grp):
prtfmt = self.datobj.kws['fmtgo']
wrobj = WrXlsxSortedGos(self.name, self.sortobj)
# Keyword arguments: control content: hdrgo_prt section_prt top_n use_sections
desc2nts = self.sortobj.get_desc2nts(**kws_grp)
wrobj.prt_txt_desc2nts(prt, desc2nts, prtfmt) | [
"def",
"prt_gos_grouped",
"(",
"self",
",",
"prt",
",",
"*",
"*",
"kws_grp",
")",
":",
"prtfmt",
"=",
"self",
".",
"datobj",
".",
"kws",
"[",
"'fmtgo'",
"]",
"wrobj",
"=",
"WrXlsxSortedGos",
"(",
"self",
".",
"name",
",",
"self",
".",
"sortobj",
")",... | Print grouped GO list. | [
"Print",
"grouped",
"GO",
"list",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L74-L80 |
242,158 | tanghaibao/goatools | goatools/grouper/aart_geneproducts_one.py | AArtGeneProductSetsOne.prt_gos_flat | def prt_gos_flat(self, prt):
"""Print flat GO list."""
prtfmt = self.datobj.kws['fmtgo']
_go2nt = self.sortobj.grprobj.go2nt
go2nt = {go:_go2nt[go] for go in self.go2nt}
prt.write("\n{N} GO IDs:\n".format(N=len(go2nt)))
_sortby = self._get_sortgo()
for ntgo in sorted(go2nt.values(), key=_sortby):
prt.write(prtfmt.format(**ntgo._asdict())) | python | def prt_gos_flat(self, prt):
prtfmt = self.datobj.kws['fmtgo']
_go2nt = self.sortobj.grprobj.go2nt
go2nt = {go:_go2nt[go] for go in self.go2nt}
prt.write("\n{N} GO IDs:\n".format(N=len(go2nt)))
_sortby = self._get_sortgo()
for ntgo in sorted(go2nt.values(), key=_sortby):
prt.write(prtfmt.format(**ntgo._asdict())) | [
"def",
"prt_gos_flat",
"(",
"self",
",",
"prt",
")",
":",
"prtfmt",
"=",
"self",
".",
"datobj",
".",
"kws",
"[",
"'fmtgo'",
"]",
"_go2nt",
"=",
"self",
".",
"sortobj",
".",
"grprobj",
".",
"go2nt",
"go2nt",
"=",
"{",
"go",
":",
"_go2nt",
"[",
"go",... | Print flat GO list. | [
"Print",
"flat",
"GO",
"list",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L82-L90 |
242,159 | tanghaibao/goatools | goatools/grouper/aart_geneproducts_one.py | AArtGeneProductSetsOne._get_sortgo | def _get_sortgo(self):
"""Get function for sorting GO terms in a list of namedtuples."""
if 'sortgo' in self.datobj.kws:
return self.datobj.kws['sortgo']
return self.datobj.grprdflt.gosubdag.prt_attr['sort'] + "\n" | python | def _get_sortgo(self):
if 'sortgo' in self.datobj.kws:
return self.datobj.kws['sortgo']
return self.datobj.grprdflt.gosubdag.prt_attr['sort'] + "\n" | [
"def",
"_get_sortgo",
"(",
"self",
")",
":",
"if",
"'sortgo'",
"in",
"self",
".",
"datobj",
".",
"kws",
":",
"return",
"self",
".",
"datobj",
".",
"kws",
"[",
"'sortgo'",
"]",
"return",
"self",
".",
"datobj",
".",
"grprdflt",
".",
"gosubdag",
".",
"p... | Get function for sorting GO terms in a list of namedtuples. | [
"Get",
"function",
"for",
"sorting",
"GO",
"terms",
"in",
"a",
"list",
"of",
"namedtuples",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L93-L97 |
242,160 | tanghaibao/goatools | goatools/grouper/aart_geneproducts_one.py | AArtGeneProductSetsOne.get_gene2binvec | def get_gene2binvec(self):
"""Return a boolean vector for each gene representing GO section membership."""
_sec2chr = self.sec2chr
return {g:[s in s2gos for s in _sec2chr] for g, s2gos in self.gene2section2gos.items()} | python | def get_gene2binvec(self):
_sec2chr = self.sec2chr
return {g:[s in s2gos for s in _sec2chr] for g, s2gos in self.gene2section2gos.items()} | [
"def",
"get_gene2binvec",
"(",
"self",
")",
":",
"_sec2chr",
"=",
"self",
".",
"sec2chr",
"return",
"{",
"g",
":",
"[",
"s",
"in",
"s2gos",
"for",
"s",
"in",
"_sec2chr",
"]",
"for",
"g",
",",
"s2gos",
"in",
"self",
".",
"gene2section2gos",
".",
"item... | Return a boolean vector for each gene representing GO section membership. | [
"Return",
"a",
"boolean",
"vector",
"for",
"each",
"gene",
"representing",
"GO",
"section",
"membership",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L140-L143 |
242,161 | tanghaibao/goatools | goatools/grouper/aart_geneproducts_one.py | _Init.get_go2nt | def get_go2nt(self, goea_results):
"""Return go2nt with added formatted string versions of the P-values."""
go2obj = self.objaartall.grprdflt.gosubdag.go2obj
# Add string version of P-values
goea_nts = MgrNtGOEAs(goea_results).get_nts_strpval()
return {go2obj[nt.GO].id:nt for nt in goea_nts if nt.GO in go2obj} | python | def get_go2nt(self, goea_results):
go2obj = self.objaartall.grprdflt.gosubdag.go2obj
# Add string version of P-values
goea_nts = MgrNtGOEAs(goea_results).get_nts_strpval()
return {go2obj[nt.GO].id:nt for nt in goea_nts if nt.GO in go2obj} | [
"def",
"get_go2nt",
"(",
"self",
",",
"goea_results",
")",
":",
"go2obj",
"=",
"self",
".",
"objaartall",
".",
"grprdflt",
".",
"gosubdag",
".",
"go2obj",
"# Add string version of P-values",
"goea_nts",
"=",
"MgrNtGOEAs",
"(",
"goea_results",
")",
".",
"get_nts_... | Return go2nt with added formatted string versions of the P-values. | [
"Return",
"go2nt",
"with",
"added",
"formatted",
"string",
"versions",
"of",
"the",
"P",
"-",
"values",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L151-L156 |
242,162 | tanghaibao/goatools | goatools/grouper/aart_geneproducts_one.py | _Init.get_sec2gos | def get_sec2gos(sortobj):
"""Initialize section_name2goids."""
sec_gos = []
for section_name, nts in sortobj.get_desc2nts_fnc(hdrgo_prt=True)['sections']:
sec_gos.append((section_name, set(nt.GO for nt in nts)))
return cx.OrderedDict(sec_gos) | python | def get_sec2gos(sortobj):
sec_gos = []
for section_name, nts in sortobj.get_desc2nts_fnc(hdrgo_prt=True)['sections']:
sec_gos.append((section_name, set(nt.GO for nt in nts)))
return cx.OrderedDict(sec_gos) | [
"def",
"get_sec2gos",
"(",
"sortobj",
")",
":",
"sec_gos",
"=",
"[",
"]",
"for",
"section_name",
",",
"nts",
"in",
"sortobj",
".",
"get_desc2nts_fnc",
"(",
"hdrgo_prt",
"=",
"True",
")",
"[",
"'sections'",
"]",
":",
"sec_gos",
".",
"append",
"(",
"(",
... | Initialize section_name2goids. | [
"Initialize",
"section_name2goids",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L159-L164 |
242,163 | tanghaibao/goatools | goatools/grouper/aart_geneproducts_one.py | _Init.get_gene2gos | def get_gene2gos(go2nt):
"""Create a gene product to GO set dict."""
gene2gos = cx.defaultdict(set)
nt0 = next(iter(go2nt.values()))
b_str = isinstance(nt0.study_items, str)
# print("NNNNTTTT", nt0)
for goid, ntgo in go2nt.items():
study_items = ntgo.study_items.split(', ') if b_str else ntgo.study_items
for geneid in study_items:
gene2gos[geneid].add(goid)
if b_str:
b_set = set(isinstance(g.isdigit(), int) for g in nt0.study_items.split(', '))
if b_set == set([True]):
return {int(g):gos for g, gos in gene2gos.items()}
return {g:gos for g, gos in gene2gos.items()} | python | def get_gene2gos(go2nt):
gene2gos = cx.defaultdict(set)
nt0 = next(iter(go2nt.values()))
b_str = isinstance(nt0.study_items, str)
# print("NNNNTTTT", nt0)
for goid, ntgo in go2nt.items():
study_items = ntgo.study_items.split(', ') if b_str else ntgo.study_items
for geneid in study_items:
gene2gos[geneid].add(goid)
if b_str:
b_set = set(isinstance(g.isdigit(), int) for g in nt0.study_items.split(', '))
if b_set == set([True]):
return {int(g):gos for g, gos in gene2gos.items()}
return {g:gos for g, gos in gene2gos.items()} | [
"def",
"get_gene2gos",
"(",
"go2nt",
")",
":",
"gene2gos",
"=",
"cx",
".",
"defaultdict",
"(",
"set",
")",
"nt0",
"=",
"next",
"(",
"iter",
"(",
"go2nt",
".",
"values",
"(",
")",
")",
")",
"b_str",
"=",
"isinstance",
"(",
"nt0",
".",
"study_items",
... | Create a gene product to GO set dict. | [
"Create",
"a",
"gene",
"product",
"to",
"GO",
"set",
"dict",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L167-L181 |
242,164 | tanghaibao/goatools | goatools/grouper/aart_geneproducts_one.py | _Init.get_gene2aart | def get_gene2aart(gene2section2gos, sec2chr):
"""Return a string for each gene representing GO section membership."""
geneid2str = {}
for geneid, section2gos_gene in gene2section2gos.items():
letters = [abc if s in section2gos_gene else "." for s, abc in sec2chr.items()]
geneid2str[geneid] = "".join(letters)
return geneid2str | python | def get_gene2aart(gene2section2gos, sec2chr):
geneid2str = {}
for geneid, section2gos_gene in gene2section2gos.items():
letters = [abc if s in section2gos_gene else "." for s, abc in sec2chr.items()]
geneid2str[geneid] = "".join(letters)
return geneid2str | [
"def",
"get_gene2aart",
"(",
"gene2section2gos",
",",
"sec2chr",
")",
":",
"geneid2str",
"=",
"{",
"}",
"for",
"geneid",
",",
"section2gos_gene",
"in",
"gene2section2gos",
".",
"items",
"(",
")",
":",
"letters",
"=",
"[",
"abc",
"if",
"s",
"in",
"section2g... | Return a string for each gene representing GO section membership. | [
"Return",
"a",
"string",
"for",
"each",
"gene",
"representing",
"GO",
"section",
"membership",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L192-L198 |
242,165 | tanghaibao/goatools | goatools/grouper/aart_geneproducts_one.py | _Init.get_gene2section2gos | def get_gene2section2gos(gene2gos, sec2gos):
"""Get a list of section aliases for each gene product ID."""
gene2section2gos = {}
for geneid, gos_gene in gene2gos.items():
section2gos = {}
for section_name, gos_sec in sec2gos.items():
gos_secgene = gos_gene.intersection(gos_sec)
if gos_secgene:
section2gos[section_name] = gos_secgene
gene2section2gos[geneid] = section2gos
return gene2section2gos | python | def get_gene2section2gos(gene2gos, sec2gos):
gene2section2gos = {}
for geneid, gos_gene in gene2gos.items():
section2gos = {}
for section_name, gos_sec in sec2gos.items():
gos_secgene = gos_gene.intersection(gos_sec)
if gos_secgene:
section2gos[section_name] = gos_secgene
gene2section2gos[geneid] = section2gos
return gene2section2gos | [
"def",
"get_gene2section2gos",
"(",
"gene2gos",
",",
"sec2gos",
")",
":",
"gene2section2gos",
"=",
"{",
"}",
"for",
"geneid",
",",
"gos_gene",
"in",
"gene2gos",
".",
"items",
"(",
")",
":",
"section2gos",
"=",
"{",
"}",
"for",
"section_name",
",",
"gos_sec... | Get a list of section aliases for each gene product ID. | [
"Get",
"a",
"list",
"of",
"section",
"aliases",
"for",
"each",
"gene",
"product",
"ID",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L201-L211 |
242,166 | tanghaibao/goatools | goatools/gosubdag/plot/gosubdag_plot.py | GoSubDagPlot._init_objcolor | def _init_objcolor(self, node_opts, **kwu):
"""Return user-created Go2Color object or create one."""
objgoea = node_opts.kws['dict'].get('objgoea', None)
# kwu: go2color go2bordercolor dflt_bordercolor key2col
return Go2Color(self.gosubdag, objgoea, **kwu) | python | def _init_objcolor(self, node_opts, **kwu):
objgoea = node_opts.kws['dict'].get('objgoea', None)
# kwu: go2color go2bordercolor dflt_bordercolor key2col
return Go2Color(self.gosubdag, objgoea, **kwu) | [
"def",
"_init_objcolor",
"(",
"self",
",",
"node_opts",
",",
"*",
"*",
"kwu",
")",
":",
"objgoea",
"=",
"node_opts",
".",
"kws",
"[",
"'dict'",
"]",
".",
"get",
"(",
"'objgoea'",
",",
"None",
")",
"# kwu: go2color go2bordercolor dflt_bordercolor key2col",
"ret... | Return user-created Go2Color object or create one. | [
"Return",
"user",
"-",
"created",
"Go2Color",
"object",
"or",
"create",
"one",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/gosubdag_plot.py#L104-L108 |
242,167 | tanghaibao/goatools | goatools/gosubdag/plot/gosubdag_plot.py | GoSubDagPlot._init_gonodeopts | def _init_gonodeopts(self, **kws_usr):
"""Initialize a GO Node plot options object, GoNodeOpts."""
options = GoNodeOpts(self.gosubdag, **self.kws['node_go'])
# Add parent edge count if either is in kws: parentcnt, prt_pcnt
if not options.kws['set'].isdisjoint(['parentcnt', 'prt_pcnt']):
options.kws['dict']['c2ps'] = self.edgesobj.get_c2ps()
# GoeaResults(kws['goea_results'], **self.kws['goea']) if 'goea_results' in kws else None
if 'goea_results' in kws_usr:
objgoea = GoeaResults(kws_usr['goea_results'], **self.kws['goea'])
options.kws['dict']['objgoea'] = objgoea
return options | python | def _init_gonodeopts(self, **kws_usr):
options = GoNodeOpts(self.gosubdag, **self.kws['node_go'])
# Add parent edge count if either is in kws: parentcnt, prt_pcnt
if not options.kws['set'].isdisjoint(['parentcnt', 'prt_pcnt']):
options.kws['dict']['c2ps'] = self.edgesobj.get_c2ps()
# GoeaResults(kws['goea_results'], **self.kws['goea']) if 'goea_results' in kws else None
if 'goea_results' in kws_usr:
objgoea = GoeaResults(kws_usr['goea_results'], **self.kws['goea'])
options.kws['dict']['objgoea'] = objgoea
return options | [
"def",
"_init_gonodeopts",
"(",
"self",
",",
"*",
"*",
"kws_usr",
")",
":",
"options",
"=",
"GoNodeOpts",
"(",
"self",
".",
"gosubdag",
",",
"*",
"*",
"self",
".",
"kws",
"[",
"'node_go'",
"]",
")",
"# Add parent edge count if either is in kws: parentcnt, prt_pc... | Initialize a GO Node plot options object, GoNodeOpts. | [
"Initialize",
"a",
"GO",
"Node",
"plot",
"options",
"object",
"GoNodeOpts",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/gosubdag_plot.py#L110-L120 |
242,168 | tanghaibao/goatools | goatools/gosubdag/plot/gosubdag_plot.py | GoSubDagPlot.prt_goids | def prt_goids(self, prt):
"""Print all GO IDs in the plot, plus their color."""
fmt = self.gosubdag.prt_attr['fmta']
nts = sorted(self.gosubdag.go2nt.values(), key=lambda nt: [nt.NS, nt.depth, nt.alt])
_get_color = self.pydotnodego.go2color.get
for ntgo in nts:
gostr = fmt.format(**ntgo._asdict())
col = _get_color(ntgo.GO, "")
prt.write("{COLOR:7} {GO}\n".format(COLOR=col, GO=gostr)) | python | def prt_goids(self, prt):
fmt = self.gosubdag.prt_attr['fmta']
nts = sorted(self.gosubdag.go2nt.values(), key=lambda nt: [nt.NS, nt.depth, nt.alt])
_get_color = self.pydotnodego.go2color.get
for ntgo in nts:
gostr = fmt.format(**ntgo._asdict())
col = _get_color(ntgo.GO, "")
prt.write("{COLOR:7} {GO}\n".format(COLOR=col, GO=gostr)) | [
"def",
"prt_goids",
"(",
"self",
",",
"prt",
")",
":",
"fmt",
"=",
"self",
".",
"gosubdag",
".",
"prt_attr",
"[",
"'fmta'",
"]",
"nts",
"=",
"sorted",
"(",
"self",
".",
"gosubdag",
".",
"go2nt",
".",
"values",
"(",
")",
",",
"key",
"=",
"lambda",
... | Print all GO IDs in the plot, plus their color. | [
"Print",
"all",
"GO",
"IDs",
"in",
"the",
"plot",
"plus",
"their",
"color",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/gosubdag_plot.py#L122-L130 |
242,169 | tanghaibao/goatools | goatools/gosubdag/plot/gosubdag_plot.py | GoSubDagPlot._init_kws | def _init_kws(self, **kws_usr):
"""Return a dict containing user-specified plotting options."""
kws_self = {}
user_keys = set(kws_usr)
for objname, expset in self.exp_keys.items():
usrkeys_curr = user_keys.intersection(expset)
kws_self[objname] = get_kwargs(kws_usr, usrkeys_curr, usrkeys_curr)
dpi = str(kws_self['dag'].get('dpi', self.dflts['dpi']))
kws_self['dag']['dpi'] = dpi
return kws_self | python | def _init_kws(self, **kws_usr):
kws_self = {}
user_keys = set(kws_usr)
for objname, expset in self.exp_keys.items():
usrkeys_curr = user_keys.intersection(expset)
kws_self[objname] = get_kwargs(kws_usr, usrkeys_curr, usrkeys_curr)
dpi = str(kws_self['dag'].get('dpi', self.dflts['dpi']))
kws_self['dag']['dpi'] = dpi
return kws_self | [
"def",
"_init_kws",
"(",
"self",
",",
"*",
"*",
"kws_usr",
")",
":",
"kws_self",
"=",
"{",
"}",
"user_keys",
"=",
"set",
"(",
"kws_usr",
")",
"for",
"objname",
",",
"expset",
"in",
"self",
".",
"exp_keys",
".",
"items",
"(",
")",
":",
"usrkeys_curr",... | Return a dict containing user-specified plotting options. | [
"Return",
"a",
"dict",
"containing",
"user",
"-",
"specified",
"plotting",
"options",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/gosubdag_plot.py#L132-L141 |
242,170 | tanghaibao/goatools | goatools/gosubdag/plot/gosubdag_plot.py | GoSubDagPlot._prt_edge | def _prt_edge(dag_edge, attr):
"""Print edge attribute"""
# sequence parent_graph points attributes type parent_edge_list
print("Edge {ATTR}: {VAL}".format(ATTR=attr, VAL=dag_edge.obj_dict[attr])) | python | def _prt_edge(dag_edge, attr):
# sequence parent_graph points attributes type parent_edge_list
print("Edge {ATTR}: {VAL}".format(ATTR=attr, VAL=dag_edge.obj_dict[attr])) | [
"def",
"_prt_edge",
"(",
"dag_edge",
",",
"attr",
")",
":",
"# sequence parent_graph points attributes type parent_edge_list",
"print",
"(",
"\"Edge {ATTR}: {VAL}\"",
".",
"format",
"(",
"ATTR",
"=",
"attr",
",",
"VAL",
"=",
"dag_edge",
".",
"obj_dict",
"[",
"attr",... | Print edge attribute | [
"Print",
"edge",
"attribute"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/gosubdag_plot.py#L205-L208 |
242,171 | tanghaibao/goatools | goatools/gosubdag/gosubdag.py | GoSubDag.prt_goids | def prt_goids(self, goids=None, prtfmt=None, sortby=True, prt=sys.stdout):
"""Given GO IDs, print decriptive info about each GO Term."""
if goids is None:
goids = self.go_sources
nts = self.get_nts(goids, sortby)
if prtfmt is None:
prtfmt = self.prt_attr['fmta']
for ntgo in nts:
key2val = ntgo._asdict()
prt.write("{GO}\n".format(GO=prtfmt.format(**key2val)))
return nts | python | def prt_goids(self, goids=None, prtfmt=None, sortby=True, prt=sys.stdout):
if goids is None:
goids = self.go_sources
nts = self.get_nts(goids, sortby)
if prtfmt is None:
prtfmt = self.prt_attr['fmta']
for ntgo in nts:
key2val = ntgo._asdict()
prt.write("{GO}\n".format(GO=prtfmt.format(**key2val)))
return nts | [
"def",
"prt_goids",
"(",
"self",
",",
"goids",
"=",
"None",
",",
"prtfmt",
"=",
"None",
",",
"sortby",
"=",
"True",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"goids",
"is",
"None",
":",
"goids",
"=",
"self",
".",
"go_sources",
"nts",
... | Given GO IDs, print decriptive info about each GO Term. | [
"Given",
"GO",
"IDs",
"print",
"decriptive",
"info",
"about",
"each",
"GO",
"Term",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/gosubdag.py#L42-L52 |
242,172 | tanghaibao/goatools | goatools/gosubdag/gosubdag.py | GoSubDag.get_nts | def get_nts(self, goids=None, sortby=None):
"""Given GO IDs, get a list of namedtuples."""
nts = []
# User GO IDs
if goids is None:
goids = self.go_sources
else:
chk_goids(goids, "GoSubDag::get_nts")
if goids:
ntobj = cx.namedtuple("NtGo", " ".join(self.prt_attr['flds']))
go2nt = self.get_go2nt(goids)
for goid, ntgo in self._get_sorted_go2nt(go2nt, sortby):
assert ntgo is not None, "{GO} NOT IN go2nt".format(GO=goid)
if goid == ntgo.GO:
nts.append(ntgo)
else:
fld2vals = ntgo._asdict()
fld2vals['GO'] = goid
nts.append(ntobj(**fld2vals))
return nts | python | def get_nts(self, goids=None, sortby=None):
nts = []
# User GO IDs
if goids is None:
goids = self.go_sources
else:
chk_goids(goids, "GoSubDag::get_nts")
if goids:
ntobj = cx.namedtuple("NtGo", " ".join(self.prt_attr['flds']))
go2nt = self.get_go2nt(goids)
for goid, ntgo in self._get_sorted_go2nt(go2nt, sortby):
assert ntgo is not None, "{GO} NOT IN go2nt".format(GO=goid)
if goid == ntgo.GO:
nts.append(ntgo)
else:
fld2vals = ntgo._asdict()
fld2vals['GO'] = goid
nts.append(ntobj(**fld2vals))
return nts | [
"def",
"get_nts",
"(",
"self",
",",
"goids",
"=",
"None",
",",
"sortby",
"=",
"None",
")",
":",
"nts",
"=",
"[",
"]",
"# User GO IDs",
"if",
"goids",
"is",
"None",
":",
"goids",
"=",
"self",
".",
"go_sources",
"else",
":",
"chk_goids",
"(",
"goids",
... | Given GO IDs, get a list of namedtuples. | [
"Given",
"GO",
"IDs",
"get",
"a",
"list",
"of",
"namedtuples",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/gosubdag.py#L54-L73 |
242,173 | tanghaibao/goatools | goatools/gosubdag/gosubdag.py | GoSubDag.get_go2nt | def get_go2nt(self, goids):
"""Return dict of GO ID as key and GO object information in namedtuple."""
get_nt = self.go2nt
goids_present = set(goids).intersection(self.go2obj)
if len(goids_present) != len(goids):
print("GO IDs NOT FOUND IN DAG: {GOs}".format(
GOs=" ".join(set(goids).difference(goids_present))))
return {g:get_nt[g] for g in goids_present} | python | def get_go2nt(self, goids):
get_nt = self.go2nt
goids_present = set(goids).intersection(self.go2obj)
if len(goids_present) != len(goids):
print("GO IDs NOT FOUND IN DAG: {GOs}".format(
GOs=" ".join(set(goids).difference(goids_present))))
return {g:get_nt[g] for g in goids_present} | [
"def",
"get_go2nt",
"(",
"self",
",",
"goids",
")",
":",
"get_nt",
"=",
"self",
".",
"go2nt",
"goids_present",
"=",
"set",
"(",
"goids",
")",
".",
"intersection",
"(",
"self",
".",
"go2obj",
")",
"if",
"len",
"(",
"goids_present",
")",
"!=",
"len",
"... | Return dict of GO ID as key and GO object information in namedtuple. | [
"Return",
"dict",
"of",
"GO",
"ID",
"as",
"key",
"and",
"GO",
"object",
"information",
"in",
"namedtuple",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/gosubdag.py#L94-L101 |
242,174 | tanghaibao/goatools | goatools/gosubdag/gosubdag.py | GoSubDag.get_key_goids | def get_key_goids(self, goids):
"""Given GO IDs, return key GO IDs."""
go2obj = self.go2obj
return set(go2obj[go].id for go in goids) | python | def get_key_goids(self, goids):
go2obj = self.go2obj
return set(go2obj[go].id for go in goids) | [
"def",
"get_key_goids",
"(",
"self",
",",
"goids",
")",
":",
"go2obj",
"=",
"self",
".",
"go2obj",
"return",
"set",
"(",
"go2obj",
"[",
"go",
"]",
".",
"id",
"for",
"go",
"in",
"goids",
")"
] | Given GO IDs, return key GO IDs. | [
"Given",
"GO",
"IDs",
"return",
"key",
"GO",
"IDs",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/gosubdag.py#L115-L118 |
242,175 | tanghaibao/goatools | goatools/gosubdag/gosubdag.py | GoSubDag.prt_objdesc | def prt_objdesc(self, prt):
"""Return description of this GoSubDag object."""
txt = "INITIALIZING GoSubDag: {N:3} sources in {M:3} GOs rcnt({R}). {A} alt GO IDs\n"
alt2obj = {go:o for go, o in self.go2obj.items() if go != o.id}
prt.write(txt.format(
N=len(self.go_sources),
M=len(self.go2obj),
R=self.rcntobj is not None,
A=len(alt2obj)))
prt.write(" GoSubDag: namedtuple fields: {FLDS}\n".format(
FLDS=" ".join(self.prt_attr['flds'])))
prt.write(" GoSubDag: relationships: {RELS}\n".format(RELS=self.relationships)) | python | def prt_objdesc(self, prt):
txt = "INITIALIZING GoSubDag: {N:3} sources in {M:3} GOs rcnt({R}). {A} alt GO IDs\n"
alt2obj = {go:o for go, o in self.go2obj.items() if go != o.id}
prt.write(txt.format(
N=len(self.go_sources),
M=len(self.go2obj),
R=self.rcntobj is not None,
A=len(alt2obj)))
prt.write(" GoSubDag: namedtuple fields: {FLDS}\n".format(
FLDS=" ".join(self.prt_attr['flds'])))
prt.write(" GoSubDag: relationships: {RELS}\n".format(RELS=self.relationships)) | [
"def",
"prt_objdesc",
"(",
"self",
",",
"prt",
")",
":",
"txt",
"=",
"\"INITIALIZING GoSubDag: {N:3} sources in {M:3} GOs rcnt({R}). {A} alt GO IDs\\n\"",
"alt2obj",
"=",
"{",
"go",
":",
"o",
"for",
"go",
",",
"o",
"in",
"self",
".",
"go2obj",
".",
"items",
"(",... | Return description of this GoSubDag object. | [
"Return",
"description",
"of",
"this",
"GoSubDag",
"object",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/gosubdag.py#L128-L139 |
242,176 | tanghaibao/goatools | goatools/anno/init/reader_genetogo.py | InitAssc._init_taxids | def _init_taxids(taxid, taxids):
"""Return taxid set"""
ret = set()
if taxids is not None:
if taxids is True:
return True
if isinstance(taxids, int):
ret.add(taxids)
else:
ret.update(taxids)
if taxid is not None:
ret.add(taxid)
if not ret:
ret.add(9606)
# pylint: disable=superfluous-parens
print('**NOTE: DEFAULT TAXID STORED FROM gene2go IS 9606 (human)\n')
return ret | python | def _init_taxids(taxid, taxids):
ret = set()
if taxids is not None:
if taxids is True:
return True
if isinstance(taxids, int):
ret.add(taxids)
else:
ret.update(taxids)
if taxid is not None:
ret.add(taxid)
if not ret:
ret.add(9606)
# pylint: disable=superfluous-parens
print('**NOTE: DEFAULT TAXID STORED FROM gene2go IS 9606 (human)\n')
return ret | [
"def",
"_init_taxids",
"(",
"taxid",
",",
"taxids",
")",
":",
"ret",
"=",
"set",
"(",
")",
"if",
"taxids",
"is",
"not",
"None",
":",
"if",
"taxids",
"is",
"True",
":",
"return",
"True",
"if",
"isinstance",
"(",
"taxids",
",",
"int",
")",
":",
"ret"... | Return taxid set | [
"Return",
"taxid",
"set"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/init/reader_genetogo.py#L34-L50 |
242,177 | tanghaibao/goatools | goatools/anno/init/reader_genetogo.py | InitAssc.init_associations | def init_associations(self, fin_anno, taxids=None):
"""Read annotation file. Store annotation data in a list of namedtuples."""
nts = []
if fin_anno is None:
return nts
tic = timeit.default_timer()
lnum = -1
line = "\t"*len(self.flds)
try:
with open(fin_anno) as ifstrm:
category2ns = {'Process':'BP', 'Function':'MF', 'Component':'CC'}
ntobj = cx.namedtuple('ntanno', self.flds)
# Get: 1) Specified taxids, default taxid(human), or all taxids
get_all = taxids is True
taxids = self.taxids
for lnum, line in enumerate(ifstrm, 1):
# Read data
if line[0] != '#':
vals = line.split('\t')
taxid = int(vals[0])
if get_all or taxid in taxids:
# assert len(vals) == 8
ntd = ntobj(
tax_id=taxid,
DB_ID=int(vals[1]),
GO_ID=vals[2],
Evidence_Code=vals[3],
Qualifier=self._get_qualifiers(vals[4]),
GO_term=vals[5],
DB_Reference=self._get_pmids(vals[6]),
NS=category2ns[vals[7].rstrip()])
#self._chk_qualifiers(qualifiers, lnum, ntd)
nts.append(ntd)
# Read header
elif line[0] == '#':
assert line[1:-1].split('\t') == self.hdrs
# pylint: disable=broad-except
except Exception as inst:
import traceback
traceback.print_exc()
sys.stderr.write("\n **FATAL: {MSG}\n\n".format(MSG=str(inst)))
sys.stderr.write("**FATAL: {FIN}[{LNUM}]:\n{L}".format(FIN=fin_anno, L=line, LNUM=lnum))
self._prt_line_detail(sys.stdout, line, lnum)
sys.exit(1)
print('HMS:{HMS} {N:7,} annotations READ: {ANNO}'.format(
N=len(nts), ANNO=fin_anno,
HMS=str(datetime.timedelta(seconds=(timeit.default_timer()-tic)))))
return nts | python | def init_associations(self, fin_anno, taxids=None):
nts = []
if fin_anno is None:
return nts
tic = timeit.default_timer()
lnum = -1
line = "\t"*len(self.flds)
try:
with open(fin_anno) as ifstrm:
category2ns = {'Process':'BP', 'Function':'MF', 'Component':'CC'}
ntobj = cx.namedtuple('ntanno', self.flds)
# Get: 1) Specified taxids, default taxid(human), or all taxids
get_all = taxids is True
taxids = self.taxids
for lnum, line in enumerate(ifstrm, 1):
# Read data
if line[0] != '#':
vals = line.split('\t')
taxid = int(vals[0])
if get_all or taxid in taxids:
# assert len(vals) == 8
ntd = ntobj(
tax_id=taxid,
DB_ID=int(vals[1]),
GO_ID=vals[2],
Evidence_Code=vals[3],
Qualifier=self._get_qualifiers(vals[4]),
GO_term=vals[5],
DB_Reference=self._get_pmids(vals[6]),
NS=category2ns[vals[7].rstrip()])
#self._chk_qualifiers(qualifiers, lnum, ntd)
nts.append(ntd)
# Read header
elif line[0] == '#':
assert line[1:-1].split('\t') == self.hdrs
# pylint: disable=broad-except
except Exception as inst:
import traceback
traceback.print_exc()
sys.stderr.write("\n **FATAL: {MSG}\n\n".format(MSG=str(inst)))
sys.stderr.write("**FATAL: {FIN}[{LNUM}]:\n{L}".format(FIN=fin_anno, L=line, LNUM=lnum))
self._prt_line_detail(sys.stdout, line, lnum)
sys.exit(1)
print('HMS:{HMS} {N:7,} annotations READ: {ANNO}'.format(
N=len(nts), ANNO=fin_anno,
HMS=str(datetime.timedelta(seconds=(timeit.default_timer()-tic)))))
return nts | [
"def",
"init_associations",
"(",
"self",
",",
"fin_anno",
",",
"taxids",
"=",
"None",
")",
":",
"nts",
"=",
"[",
"]",
"if",
"fin_anno",
"is",
"None",
":",
"return",
"nts",
"tic",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"lnum",
"=",
"-",
"1",
... | Read annotation file. Store annotation data in a list of namedtuples. | [
"Read",
"annotation",
"file",
".",
"Store",
"annotation",
"data",
"in",
"a",
"list",
"of",
"namedtuples",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/init/reader_genetogo.py#L53-L100 |
242,178 | tanghaibao/goatools | goatools/anno/init/reader_genetogo.py | InitAssc._prt_line_detail | def _prt_line_detail(self, prt, line, lnum=""):
"""Print each field and its value."""
data = zip(self.flds, line.split('\t'))
txt = ["{:2}) {:13} {}".format(i, hdr, val) for i, (hdr, val) in enumerate(data)]
prt.write("{LNUM}\n{TXT}\n".format(LNUM=lnum, TXT='\n'.join(txt))) | python | def _prt_line_detail(self, prt, line, lnum=""):
data = zip(self.flds, line.split('\t'))
txt = ["{:2}) {:13} {}".format(i, hdr, val) for i, (hdr, val) in enumerate(data)]
prt.write("{LNUM}\n{TXT}\n".format(LNUM=lnum, TXT='\n'.join(txt))) | [
"def",
"_prt_line_detail",
"(",
"self",
",",
"prt",
",",
"line",
",",
"lnum",
"=",
"\"\"",
")",
":",
"data",
"=",
"zip",
"(",
"self",
".",
"flds",
",",
"line",
".",
"split",
"(",
"'\\t'",
")",
")",
"txt",
"=",
"[",
"\"{:2}) {:13} {}\"",
".",
"forma... | Print each field and its value. | [
"Print",
"each",
"field",
"and",
"its",
"value",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/init/reader_genetogo.py#L114-L118 |
242,179 | tanghaibao/goatools | goatools/anno/gaf_reader.py | GafReader.chk_associations | def chk_associations(self, fout_err="gaf.err"):
"""Check that fields are legal in GAF"""
obj = GafData("2.1")
return obj.chk(self.associations, fout_err) | python | def chk_associations(self, fout_err="gaf.err"):
obj = GafData("2.1")
return obj.chk(self.associations, fout_err) | [
"def",
"chk_associations",
"(",
"self",
",",
"fout_err",
"=",
"\"gaf.err\"",
")",
":",
"obj",
"=",
"GafData",
"(",
"\"2.1\"",
")",
"return",
"obj",
".",
"chk",
"(",
"self",
".",
"associations",
",",
"fout_err",
")"
] | Check that fields are legal in GAF | [
"Check",
"that",
"fields",
"are",
"legal",
"in",
"GAF"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/gaf_reader.py#L33-L36 |
242,180 | tanghaibao/goatools | goatools/cli/gosubdag_plot.py | GetGOs._update_ret | def _update_ret(ret, goids, go2color):
"""Update 'GOs' and 'go2color' in dict with goids and go2color."""
if goids:
ret['GOs'].update(goids)
if go2color:
for goid, color in go2color.items():
ret['go2color'][goid] = color | python | def _update_ret(ret, goids, go2color):
if goids:
ret['GOs'].update(goids)
if go2color:
for goid, color in go2color.items():
ret['go2color'][goid] = color | [
"def",
"_update_ret",
"(",
"ret",
",",
"goids",
",",
"go2color",
")",
":",
"if",
"goids",
":",
"ret",
"[",
"'GOs'",
"]",
".",
"update",
"(",
"goids",
")",
"if",
"go2color",
":",
"for",
"goid",
",",
"color",
"in",
"go2color",
".",
"items",
"(",
")",... | Update 'GOs' and 'go2color' in dict with goids and go2color. | [
"Update",
"GOs",
"and",
"go2color",
"in",
"dict",
"with",
"goids",
"and",
"go2color",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L160-L166 |
242,181 | tanghaibao/goatools | goatools/cli/gosubdag_plot.py | PlotCli._plt_gogrouped | def _plt_gogrouped(self, goids, go2color_usr, **kws):
"""Plot grouped GO IDs."""
fout_img = self.get_outfile(kws['outfile'], goids)
sections = read_sections(kws['sections'], exclude_ungrouped=True)
# print ("KWWSSSSSSSS", kws)
# kws_plt = {k:v for k, v in kws.items if k in self.kws_plt}
grprobj_cur = self._get_grprobj(goids, sections)
# GO: purple=hdr-only, green=hdr&usr, yellow=usr-only
# BORDER: Black=hdr Blu=hdr&usr
grpcolor = GrouperColors(grprobj_cur) # get_bordercolor get_go2color_users
grp_go2color = grpcolor.get_go2color_users()
grp_go2bordercolor = grpcolor.get_bordercolor()
for goid, color in go2color_usr.items():
grp_go2color[goid] = color
objcolor = Go2Color(self.gosubdag, objgoea=None,
go2color=grp_go2color, go2bordercolor=grp_go2bordercolor)
go2txt = GrouperPlot.get_go2txt(grprobj_cur, grp_go2color, grp_go2bordercolor)
objplt = GoSubDagPlot(self.gosubdag, Go2Color=objcolor, go2txt=go2txt, **kws)
objplt.prt_goids(sys.stdout)
objplt.plt_dag(fout_img)
sys.stdout.write("{N:>6} sections read\n".format(
N="NO" if sections is None else len(sections)))
return fout_img | python | def _plt_gogrouped(self, goids, go2color_usr, **kws):
fout_img = self.get_outfile(kws['outfile'], goids)
sections = read_sections(kws['sections'], exclude_ungrouped=True)
# print ("KWWSSSSSSSS", kws)
# kws_plt = {k:v for k, v in kws.items if k in self.kws_plt}
grprobj_cur = self._get_grprobj(goids, sections)
# GO: purple=hdr-only, green=hdr&usr, yellow=usr-only
# BORDER: Black=hdr Blu=hdr&usr
grpcolor = GrouperColors(grprobj_cur) # get_bordercolor get_go2color_users
grp_go2color = grpcolor.get_go2color_users()
grp_go2bordercolor = grpcolor.get_bordercolor()
for goid, color in go2color_usr.items():
grp_go2color[goid] = color
objcolor = Go2Color(self.gosubdag, objgoea=None,
go2color=grp_go2color, go2bordercolor=grp_go2bordercolor)
go2txt = GrouperPlot.get_go2txt(grprobj_cur, grp_go2color, grp_go2bordercolor)
objplt = GoSubDagPlot(self.gosubdag, Go2Color=objcolor, go2txt=go2txt, **kws)
objplt.prt_goids(sys.stdout)
objplt.plt_dag(fout_img)
sys.stdout.write("{N:>6} sections read\n".format(
N="NO" if sections is None else len(sections)))
return fout_img | [
"def",
"_plt_gogrouped",
"(",
"self",
",",
"goids",
",",
"go2color_usr",
",",
"*",
"*",
"kws",
")",
":",
"fout_img",
"=",
"self",
".",
"get_outfile",
"(",
"kws",
"[",
"'outfile'",
"]",
",",
"goids",
")",
"sections",
"=",
"read_sections",
"(",
"kws",
"[... | Plot grouped GO IDs. | [
"Plot",
"grouped",
"GO",
"IDs",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L205-L227 |
242,182 | tanghaibao/goatools | goatools/cli/gosubdag_plot.py | PlotCli._get_grprobj | def _get_grprobj(self, goids, sections):
"""Get Grouper, given GO IDs and sections."""
grprdflt = GrouperDflts(self.gosubdag, "goslim_generic.obo")
hdrobj = HdrgosSections(self.gosubdag, grprdflt.hdrgos_dflt, sections)
return Grouper("sections", goids, hdrobj, self.gosubdag) | python | def _get_grprobj(self, goids, sections):
grprdflt = GrouperDflts(self.gosubdag, "goslim_generic.obo")
hdrobj = HdrgosSections(self.gosubdag, grprdflt.hdrgos_dflt, sections)
return Grouper("sections", goids, hdrobj, self.gosubdag) | [
"def",
"_get_grprobj",
"(",
"self",
",",
"goids",
",",
"sections",
")",
":",
"grprdflt",
"=",
"GrouperDflts",
"(",
"self",
".",
"gosubdag",
",",
"\"goslim_generic.obo\"",
")",
"hdrobj",
"=",
"HdrgosSections",
"(",
"self",
".",
"gosubdag",
",",
"grprdflt",
".... | Get Grouper, given GO IDs and sections. | [
"Get",
"Grouper",
"given",
"GO",
"IDs",
"and",
"sections",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L229-L233 |
242,183 | tanghaibao/goatools | goatools/cli/gosubdag_plot.py | PlotCli._get_kwsdag | def _get_kwsdag(self, goids, go2obj, **kws_all):
"""Get keyword args for a GoSubDag."""
kws_dag = {}
# Term Counts for GO Term information score
tcntobj = self._get_tcntobj(goids, go2obj, **kws_all) # TermCounts or None
if tcntobj is not None:
kws_dag['tcntobj'] = tcntobj
# GO letters specified by the user
if 'go_aliases' in kws_all:
fin_go_aliases = kws_all['go_aliases']
if os.path.exists(fin_go_aliases):
go2letter = read_d1_letter(fin_go_aliases)
if go2letter:
kws_dag['go2letter'] = go2letter
return kws_dag | python | def _get_kwsdag(self, goids, go2obj, **kws_all):
kws_dag = {}
# Term Counts for GO Term information score
tcntobj = self._get_tcntobj(goids, go2obj, **kws_all) # TermCounts or None
if tcntobj is not None:
kws_dag['tcntobj'] = tcntobj
# GO letters specified by the user
if 'go_aliases' in kws_all:
fin_go_aliases = kws_all['go_aliases']
if os.path.exists(fin_go_aliases):
go2letter = read_d1_letter(fin_go_aliases)
if go2letter:
kws_dag['go2letter'] = go2letter
return kws_dag | [
"def",
"_get_kwsdag",
"(",
"self",
",",
"goids",
",",
"go2obj",
",",
"*",
"*",
"kws_all",
")",
":",
"kws_dag",
"=",
"{",
"}",
"# Term Counts for GO Term information score",
"tcntobj",
"=",
"self",
".",
"_get_tcntobj",
"(",
"goids",
",",
"go2obj",
",",
"*",
... | Get keyword args for a GoSubDag. | [
"Get",
"keyword",
"args",
"for",
"a",
"GoSubDag",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L244-L258 |
242,184 | tanghaibao/goatools | goatools/cli/gosubdag_plot.py | PlotCli._chk_docopts | def _chk_docopts(self, kws):
"""Check for common user command-line errors."""
# outfile should contain .png, .png, etc.
outfile = kws['outfile']
if len(kws) == 2 and os.path.basename(kws['obo']) == "go-basic.obo" and \
kws['outfile'] == self.dflt_outfile:
self._err("NO GO IDS SPECFIED", err=False)
if 'obo' in outfile:
self._err("BAD outfile({O})".format(O=outfile))
if 'gaf' in kws and 'gene2go' in kws:
self._err("SPECIFY ANNOTAIONS FROM ONE FILE")
if 'gene2go' in kws:
if 'taxid' not in kws:
self._err("SPECIFIY taxid WHEN READ NCBI'S gene2go FILE") | python | def _chk_docopts(self, kws):
# outfile should contain .png, .png, etc.
outfile = kws['outfile']
if len(kws) == 2 and os.path.basename(kws['obo']) == "go-basic.obo" and \
kws['outfile'] == self.dflt_outfile:
self._err("NO GO IDS SPECFIED", err=False)
if 'obo' in outfile:
self._err("BAD outfile({O})".format(O=outfile))
if 'gaf' in kws and 'gene2go' in kws:
self._err("SPECIFY ANNOTAIONS FROM ONE FILE")
if 'gene2go' in kws:
if 'taxid' not in kws:
self._err("SPECIFIY taxid WHEN READ NCBI'S gene2go FILE") | [
"def",
"_chk_docopts",
"(",
"self",
",",
"kws",
")",
":",
"# outfile should contain .png, .png, etc.",
"outfile",
"=",
"kws",
"[",
"'outfile'",
"]",
"if",
"len",
"(",
"kws",
")",
"==",
"2",
"and",
"os",
".",
"path",
".",
"basename",
"(",
"kws",
"[",
"'ob... | Check for common user command-line errors. | [
"Check",
"for",
"common",
"user",
"command",
"-",
"line",
"errors",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L277-L290 |
242,185 | tanghaibao/goatools | goatools/cli/gosubdag_plot.py | PlotCli._err | def _err(self, msg, err=True):
"""Print useage and error before exiting."""
severity = "FATAL" if err else "NOTE"
txt = "".join([self.objdoc.doc,
"User's command-line:\n\n",
" % go_plot.py {ARGS}\n\n".format(ARGS=" ".join(sys.argv[1:])),
"**{SEV}: {MSG}\n".format(SEV=severity, MSG=msg)])
if err:
raise RuntimeError(txt)
sys.stdout.write(txt)
sys.exit(0) | python | def _err(self, msg, err=True):
severity = "FATAL" if err else "NOTE"
txt = "".join([self.objdoc.doc,
"User's command-line:\n\n",
" % go_plot.py {ARGS}\n\n".format(ARGS=" ".join(sys.argv[1:])),
"**{SEV}: {MSG}\n".format(SEV=severity, MSG=msg)])
if err:
raise RuntimeError(txt)
sys.stdout.write(txt)
sys.exit(0) | [
"def",
"_err",
"(",
"self",
",",
"msg",
",",
"err",
"=",
"True",
")",
":",
"severity",
"=",
"\"FATAL\"",
"if",
"err",
"else",
"\"NOTE\"",
"txt",
"=",
"\"\"",
".",
"join",
"(",
"[",
"self",
".",
"objdoc",
".",
"doc",
",",
"\"User's command-line:\\n\\n\"... | Print useage and error before exiting. | [
"Print",
"useage",
"and",
"error",
"before",
"exiting",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L292-L302 |
242,186 | tanghaibao/goatools | goatools/cli/gosubdag_plot.py | PlotCli.get_outfile | def get_outfile(self, outfile, goids=None):
"""Return output file for GO Term plot."""
# 1. Use the user-specfied output filename for the GO Term plot
if outfile != self.dflt_outfile:
return outfile
# 2. If only plotting 1 GO term, use GO is in plot name
if goids is not None and len(goids) == 1:
goid = next(iter(goids))
goobj = self.gosubdag.go2obj[goid]
fout = "GO_{NN}_{NM}".format(NN=goid.replace("GO:", ""), NM=goobj.name)
return ".".join([re.sub(r"[\s#'()+,-./:<=>\[\]_}]", '_', fout), 'png'])
# 3. Return default name
return self.dflt_outfile | python | def get_outfile(self, outfile, goids=None):
# 1. Use the user-specfied output filename for the GO Term plot
if outfile != self.dflt_outfile:
return outfile
# 2. If only plotting 1 GO term, use GO is in plot name
if goids is not None and len(goids) == 1:
goid = next(iter(goids))
goobj = self.gosubdag.go2obj[goid]
fout = "GO_{NN}_{NM}".format(NN=goid.replace("GO:", ""), NM=goobj.name)
return ".".join([re.sub(r"[\s#'()+,-./:<=>\[\]_}]", '_', fout), 'png'])
# 3. Return default name
return self.dflt_outfile | [
"def",
"get_outfile",
"(",
"self",
",",
"outfile",
",",
"goids",
"=",
"None",
")",
":",
"# 1. Use the user-specfied output filename for the GO Term plot",
"if",
"outfile",
"!=",
"self",
".",
"dflt_outfile",
":",
"return",
"outfile",
"# 2. If only plotting 1 GO term, use G... | Return output file for GO Term plot. | [
"Return",
"output",
"file",
"for",
"GO",
"Term",
"plot",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L304-L316 |
242,187 | tanghaibao/goatools | goatools/cli/gosubdag_plot.py | PlotCli._get_optional_attrs | def _get_optional_attrs(kws):
"""Given keyword args, return optional_attributes to be loaded into the GODag."""
vals = OboOptionalAttrs.attributes.intersection(kws.keys())
if 'sections' in kws:
vals.add('relationship')
if 'norel' in kws:
vals.discard('relationship')
return vals | python | def _get_optional_attrs(kws):
vals = OboOptionalAttrs.attributes.intersection(kws.keys())
if 'sections' in kws:
vals.add('relationship')
if 'norel' in kws:
vals.discard('relationship')
return vals | [
"def",
"_get_optional_attrs",
"(",
"kws",
")",
":",
"vals",
"=",
"OboOptionalAttrs",
".",
"attributes",
".",
"intersection",
"(",
"kws",
".",
"keys",
"(",
")",
")",
"if",
"'sections'",
"in",
"kws",
":",
"vals",
".",
"add",
"(",
"'relationship'",
")",
"if... | Given keyword args, return optional_attributes to be loaded into the GODag. | [
"Given",
"keyword",
"args",
"return",
"optional_attributes",
"to",
"be",
"loaded",
"into",
"the",
"GODag",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L319-L326 |
242,188 | tanghaibao/goatools | goatools/cli/wr_sections.py | WrSectionsCli._read_sections | def _read_sections(ifile):
"""Read sections_in.txt file, if it exists."""
if os.path.exists(ifile):
return read_sections(ifile, exclude_ungrouped=True, prt=None) | python | def _read_sections(ifile):
if os.path.exists(ifile):
return read_sections(ifile, exclude_ungrouped=True, prt=None) | [
"def",
"_read_sections",
"(",
"ifile",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"ifile",
")",
":",
"return",
"read_sections",
"(",
"ifile",
",",
"exclude_ungrouped",
"=",
"True",
",",
"prt",
"=",
"None",
")"
] | Read sections_in.txt file, if it exists. | [
"Read",
"sections_in",
".",
"txt",
"file",
"if",
"it",
"exists",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/wr_sections.py#L96-L99 |
242,189 | tanghaibao/goatools | goatools/gosubdag/go_paths.py | GoPaths.get_paths_from_to | def get_paths_from_to(self, goobj_start, goid_end=None, dn0_up1=True):
"""Get a list of paths from goobj_start to either top or goid_end."""
paths = []
# Queue of terms to be examined (and storage for their paths)
working_q = cx.deque([[goobj_start]])
# Loop thru GO terms until we have examined all needed GO terms
adjfnc = self.adjdir[dn0_up1]
while working_q:
#print "WORKING QUEUE LEN({})".format(len(working_q))
path_curr = working_q.popleft()
goobj_curr = path_curr[-1]
go_adjlst = adjfnc(goobj_curr)
#print 'END', goid_end, goobj_curr
# If this GO term is the endpoint, Stop. Store path.
if (goid_end is not None and goobj_curr.id == goid_end) or \
(goid_end is None and not go_adjlst):
paths.append(path_curr)
# Else if this GO term is the not the end, add neighbors to path
else:
for go_neighbor in go_adjlst:
if go_neighbor not in path_curr:
#print "{}'s NEIGHBOR IS {}".format(goobj_curr.id, go_neighbor.id)
new_path = path_curr + [go_neighbor]
#sys.stdout.write(" {}'s {} {}\n".format(goobj_curr, up_dn, go_neighbor))
working_q.append(new_path)
#self.prt_paths(paths)
return paths | python | def get_paths_from_to(self, goobj_start, goid_end=None, dn0_up1=True):
paths = []
# Queue of terms to be examined (and storage for their paths)
working_q = cx.deque([[goobj_start]])
# Loop thru GO terms until we have examined all needed GO terms
adjfnc = self.adjdir[dn0_up1]
while working_q:
#print "WORKING QUEUE LEN({})".format(len(working_q))
path_curr = working_q.popleft()
goobj_curr = path_curr[-1]
go_adjlst = adjfnc(goobj_curr)
#print 'END', goid_end, goobj_curr
# If this GO term is the endpoint, Stop. Store path.
if (goid_end is not None and goobj_curr.id == goid_end) or \
(goid_end is None and not go_adjlst):
paths.append(path_curr)
# Else if this GO term is the not the end, add neighbors to path
else:
for go_neighbor in go_adjlst:
if go_neighbor not in path_curr:
#print "{}'s NEIGHBOR IS {}".format(goobj_curr.id, go_neighbor.id)
new_path = path_curr + [go_neighbor]
#sys.stdout.write(" {}'s {} {}\n".format(goobj_curr, up_dn, go_neighbor))
working_q.append(new_path)
#self.prt_paths(paths)
return paths | [
"def",
"get_paths_from_to",
"(",
"self",
",",
"goobj_start",
",",
"goid_end",
"=",
"None",
",",
"dn0_up1",
"=",
"True",
")",
":",
"paths",
"=",
"[",
"]",
"# Queue of terms to be examined (and storage for their paths)",
"working_q",
"=",
"cx",
".",
"deque",
"(",
... | Get a list of paths from goobj_start to either top or goid_end. | [
"Get",
"a",
"list",
"of",
"paths",
"from",
"goobj_start",
"to",
"either",
"top",
"or",
"goid_end",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/go_paths.py#L19-L45 |
242,190 | tanghaibao/goatools | goatools/gosubdag/go_paths.py | GoPaths.prt_paths | def prt_paths(paths, prt=sys.stdout):
"""Print list of paths."""
pat = "PATHES: {GO} L{L:02} D{D:02}\n"
for path in paths:
for go_obj in path:
prt.write(pat.format(GO=go_obj.id, L=go_obj.level, D=go_obj.depth))
prt.write("\n") | python | def prt_paths(paths, prt=sys.stdout):
pat = "PATHES: {GO} L{L:02} D{D:02}\n"
for path in paths:
for go_obj in path:
prt.write(pat.format(GO=go_obj.id, L=go_obj.level, D=go_obj.depth))
prt.write("\n") | [
"def",
"prt_paths",
"(",
"paths",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"pat",
"=",
"\"PATHES: {GO} L{L:02} D{D:02}\\n\"",
"for",
"path",
"in",
"paths",
":",
"for",
"go_obj",
"in",
"path",
":",
"prt",
".",
"write",
"(",
"pat",
".",
"format",
... | Print list of paths. | [
"Print",
"list",
"of",
"paths",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/go_paths.py#L48-L54 |
242,191 | tanghaibao/goatools | goatools/godag/relationship_str.py | RelationshipStr.prt_keys | def prt_keys(self, prt, pre):
"""Print the alias for a relationship and its alias."""
prt.write('{PRE}Relationship to parent: {ABC}\n'.format(
PRE=pre, ABC=''.join(self.rel2chr.values())))
for rel, alias in self.rel2chr.items():
prt.write('{PRE} {A} {DESC}\n'.format(PRE=pre, A=alias, DESC=rel))
prt.write('\n{PRE}Relationship to child: {ABC}\n'.format(
PRE=pre, ABC=''.join(self.rev2chr.values())))
for rel, alias in self.rev2chr.items():
prt.write('{PRE} {A} {DESC}\n'.format(PRE=pre, A=alias, DESC=rel)) | python | def prt_keys(self, prt, pre):
prt.write('{PRE}Relationship to parent: {ABC}\n'.format(
PRE=pre, ABC=''.join(self.rel2chr.values())))
for rel, alias in self.rel2chr.items():
prt.write('{PRE} {A} {DESC}\n'.format(PRE=pre, A=alias, DESC=rel))
prt.write('\n{PRE}Relationship to child: {ABC}\n'.format(
PRE=pre, ABC=''.join(self.rev2chr.values())))
for rel, alias in self.rev2chr.items():
prt.write('{PRE} {A} {DESC}\n'.format(PRE=pre, A=alias, DESC=rel)) | [
"def",
"prt_keys",
"(",
"self",
",",
"prt",
",",
"pre",
")",
":",
"prt",
".",
"write",
"(",
"'{PRE}Relationship to parent: {ABC}\\n'",
".",
"format",
"(",
"PRE",
"=",
"pre",
",",
"ABC",
"=",
"''",
".",
"join",
"(",
"self",
".",
"rel2chr",
".",
"values"... | Print the alias for a relationship and its alias. | [
"Print",
"the",
"alias",
"for",
"a",
"relationship",
"and",
"its",
"alias",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag/relationship_str.py#L79-L88 |
242,192 | tanghaibao/goatools | goatools/anno/annoreader_base.py | AnnoReaderBase._get_id2gos | def _get_id2gos(self, associations, **kws):
"""Return given associations in a dict, id2gos"""
options = AnnoOptions(self.evobj, **kws)
# Default reduction is to remove. For all options, see goatools/anno/opts.py:
# * Evidence_Code == ND -> No biological data No biological Data available
# * Qualifiers contain NOT
assc = self.reduce_annotations(associations, options)
return self._get_dbid2goids(assc) if options.b_geneid2gos else self._get_goid2dbids(assc) | python | def _get_id2gos(self, associations, **kws):
options = AnnoOptions(self.evobj, **kws)
# Default reduction is to remove. For all options, see goatools/anno/opts.py:
# * Evidence_Code == ND -> No biological data No biological Data available
# * Qualifiers contain NOT
assc = self.reduce_annotations(associations, options)
return self._get_dbid2goids(assc) if options.b_geneid2gos else self._get_goid2dbids(assc) | [
"def",
"_get_id2gos",
"(",
"self",
",",
"associations",
",",
"*",
"*",
"kws",
")",
":",
"options",
"=",
"AnnoOptions",
"(",
"self",
".",
"evobj",
",",
"*",
"*",
"kws",
")",
"# Default reduction is to remove. For all options, see goatools/anno/opts.py:",
"# * Evide... | Return given associations in a dict, id2gos | [
"Return",
"given",
"associations",
"in",
"a",
"dict",
"id2gos"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/annoreader_base.py#L83-L90 |
242,193 | tanghaibao/goatools | goatools/anno/annoreader_base.py | AnnoReaderBase.get_date_yyyymmdd | def get_date_yyyymmdd(yyyymmdd):
"""Return datetime.date given string."""
return date(int(yyyymmdd[:4]), int(yyyymmdd[4:6], base=10), int(yyyymmdd[6:], base=10)) | python | def get_date_yyyymmdd(yyyymmdd):
return date(int(yyyymmdd[:4]), int(yyyymmdd[4:6], base=10), int(yyyymmdd[6:], base=10)) | [
"def",
"get_date_yyyymmdd",
"(",
"yyyymmdd",
")",
":",
"return",
"date",
"(",
"int",
"(",
"yyyymmdd",
"[",
":",
"4",
"]",
")",
",",
"int",
"(",
"yyyymmdd",
"[",
"4",
":",
"6",
"]",
",",
"base",
"=",
"10",
")",
",",
"int",
"(",
"yyyymmdd",
"[",
... | Return datetime.date given string. | [
"Return",
"datetime",
".",
"date",
"given",
"string",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/annoreader_base.py#L139-L141 |
242,194 | tanghaibao/goatools | goatools/anno/annoreader_base.py | AnnoReaderBase.hms | def hms(self, msg, tic=None, prt=sys.stdout):
"""Print elapsed time and message."""
if tic is None:
tic = self.tic
now = timeit.default_timer()
hms = str(datetime.timedelta(seconds=(now-tic)))
prt.write('{HMS}: {MSG}\n'.format(HMS=hms, MSG=msg))
return now | python | def hms(self, msg, tic=None, prt=sys.stdout):
if tic is None:
tic = self.tic
now = timeit.default_timer()
hms = str(datetime.timedelta(seconds=(now-tic)))
prt.write('{HMS}: {MSG}\n'.format(HMS=hms, MSG=msg))
return now | [
"def",
"hms",
"(",
"self",
",",
"msg",
",",
"tic",
"=",
"None",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"tic",
"is",
"None",
":",
"tic",
"=",
"self",
".",
"tic",
"now",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"hms",
"=",
... | Print elapsed time and message. | [
"Print",
"elapsed",
"time",
"and",
"message",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/annoreader_base.py#L143-L150 |
242,195 | tanghaibao/goatools | goatools/anno/annoreader_base.py | AnnoReaderBase.chk_qualifiers | def chk_qualifiers(self):
"""Check format of qualifier"""
if self.name == 'id2gos':
return
for ntd in self.associations:
# print(ntd)
qual = ntd.Qualifier
assert isinstance(qual, set), '{NAME}: QUALIFIER MUST BE A LIST: {NT}'.format(
NAME=self.name, NT=ntd)
assert qual != set(['']), ntd
assert qual != set(['-']), ntd
assert 'always' not in qual, 'SPEC SAID IT WOULD BE THERE' | python | def chk_qualifiers(self):
if self.name == 'id2gos':
return
for ntd in self.associations:
# print(ntd)
qual = ntd.Qualifier
assert isinstance(qual, set), '{NAME}: QUALIFIER MUST BE A LIST: {NT}'.format(
NAME=self.name, NT=ntd)
assert qual != set(['']), ntd
assert qual != set(['-']), ntd
assert 'always' not in qual, 'SPEC SAID IT WOULD BE THERE' | [
"def",
"chk_qualifiers",
"(",
"self",
")",
":",
"if",
"self",
".",
"name",
"==",
"'id2gos'",
":",
"return",
"for",
"ntd",
"in",
"self",
".",
"associations",
":",
"# print(ntd)",
"qual",
"=",
"ntd",
".",
"Qualifier",
"assert",
"isinstance",
"(",
"qual",
"... | Check format of qualifier | [
"Check",
"format",
"of",
"qualifier"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/annoreader_base.py#L164-L175 |
242,196 | tanghaibao/goatools | goatools/anno/annoreader_base.py | AnnoReaderBase._has_not_qual | def _has_not_qual(ntd):
"""Return True if the qualifiers contain a 'NOT'"""
for qual in ntd.Qualifier:
if 'not' in qual:
return True
if 'NOT' in qual:
return True
return False | python | def _has_not_qual(ntd):
"""Return True if the qualifiers contain a 'NOT'"""
for qual in ntd.Qualifier:
if 'not' in qual:
return True
if 'NOT' in qual:
return True
return False | [
"def",
"_has_not_qual",
"(",
"ntd",
")",
":",
"for",
"qual",
"in",
"ntd",
".",
"Qualifier",
":",
"if",
"'not'",
"in",
"qual",
":",
"return",
"True",
"if",
"'NOT'",
"in",
"qual",
":",
"return",
"True",
"return",
"False"
] | Return True if the qualifiers contain a 'NOT | [
"Return",
"True",
"if",
"the",
"qualifiers",
"contain",
"a",
"NOT"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/annoreader_base.py#L178-L185 |
242,197 | tanghaibao/goatools | goatools/grouper/sorter_nts.py | SorterNts._get_sorted_section | def _get_sorted_section(self, nts_section):
"""Sort GO IDs in each section, if requested by user."""
#pylint: disable=unnecessary-lambda
if self.section_sortby is True:
return sorted(nts_section, key=lambda nt: self.sortgos.usrgo_sortby(nt))
if self.section_sortby is False or self.section_sortby is None:
return nts_section
# print('SORT GO IDS IN A SECTION')
return sorted(nts_section, key=lambda nt: self.section_sortby(nt)) | python | def _get_sorted_section(self, nts_section):
#pylint: disable=unnecessary-lambda
if self.section_sortby is True:
return sorted(nts_section, key=lambda nt: self.sortgos.usrgo_sortby(nt))
if self.section_sortby is False or self.section_sortby is None:
return nts_section
# print('SORT GO IDS IN A SECTION')
return sorted(nts_section, key=lambda nt: self.section_sortby(nt)) | [
"def",
"_get_sorted_section",
"(",
"self",
",",
"nts_section",
")",
":",
"#pylint: disable=unnecessary-lambda",
"if",
"self",
".",
"section_sortby",
"is",
"True",
":",
"return",
"sorted",
"(",
"nts_section",
",",
"key",
"=",
"lambda",
"nt",
":",
"self",
".",
"... | Sort GO IDs in each section, if requested by user. | [
"Sort",
"GO",
"IDs",
"in",
"each",
"section",
"if",
"requested",
"by",
"user",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_nts.py#L88-L96 |
242,198 | tanghaibao/goatools | goatools/godag/go_tasks.py | get_relationship_targets | def get_relationship_targets(item_ids, relationships, id2rec):
"""Get item ID set of item IDs in a relationship target set."""
# Requirements to use this function:
# 1) item Terms must have been loaded with 'relationships'
# 2) item IDs in 'item_ids' arguement must be present in id2rec
# 3) Arg, 'relationships' must be True or an iterable
reltgt_objs_all = set()
for goid in item_ids:
obj = id2rec[goid]
for reltype, reltgt_objs_cur in obj.relationship.items():
if relationships is True or reltype in relationships:
reltgt_objs_all.update(reltgt_objs_cur)
return reltgt_objs_all | python | def get_relationship_targets(item_ids, relationships, id2rec):
# Requirements to use this function:
# 1) item Terms must have been loaded with 'relationships'
# 2) item IDs in 'item_ids' arguement must be present in id2rec
# 3) Arg, 'relationships' must be True or an iterable
reltgt_objs_all = set()
for goid in item_ids:
obj = id2rec[goid]
for reltype, reltgt_objs_cur in obj.relationship.items():
if relationships is True or reltype in relationships:
reltgt_objs_all.update(reltgt_objs_cur)
return reltgt_objs_all | [
"def",
"get_relationship_targets",
"(",
"item_ids",
",",
"relationships",
",",
"id2rec",
")",
":",
"# Requirements to use this function:",
"# 1) item Terms must have been loaded with 'relationships'",
"# 2) item IDs in 'item_ids' arguement must be present in id2rec",
"# 3) Arg,... | Get item ID set of item IDs in a relationship target set. | [
"Get",
"item",
"ID",
"set",
"of",
"item",
"IDs",
"in",
"a",
"relationship",
"target",
"set",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag/go_tasks.py#L35-L47 |
242,199 | tanghaibao/goatools | goatools/godag/go_tasks.py | _get_id2parents | def _get_id2parents(id2parents, item_id, item_obj):
"""Add the parent item IDs for one item object and their parents."""
if item_id in id2parents:
return id2parents[item_id]
parent_ids = set()
for parent_obj in item_obj.parents:
parent_id = parent_obj.item_id
parent_ids.add(parent_id)
parent_ids |= _get_id2parents(id2parents, parent_id, parent_obj)
id2parents[item_id] = parent_ids
return parent_ids | python | def _get_id2parents(id2parents, item_id, item_obj):
if item_id in id2parents:
return id2parents[item_id]
parent_ids = set()
for parent_obj in item_obj.parents:
parent_id = parent_obj.item_id
parent_ids.add(parent_id)
parent_ids |= _get_id2parents(id2parents, parent_id, parent_obj)
id2parents[item_id] = parent_ids
return parent_ids | [
"def",
"_get_id2parents",
"(",
"id2parents",
",",
"item_id",
",",
"item_obj",
")",
":",
"if",
"item_id",
"in",
"id2parents",
":",
"return",
"id2parents",
"[",
"item_id",
"]",
"parent_ids",
"=",
"set",
"(",
")",
"for",
"parent_obj",
"in",
"item_obj",
".",
"... | Add the parent item IDs for one item object and their parents. | [
"Add",
"the",
"parent",
"item",
"IDs",
"for",
"one",
"item",
"object",
"and",
"their",
"parents",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag/go_tasks.py#L50-L60 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.