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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
mitodl/django-server-status
server_status/views.py
get_redis_info
def get_redis_info(): """Check Redis connection.""" from kombu.utils.url import _parse_url as parse_redis_url from redis import ( StrictRedis, ConnectionError as RedisConnectionError, ResponseError as RedisResponseError, ) for conf_name in ('REDIS_URL', 'BROKER_URL', 'CELERY_...
python
def get_redis_info(): """Check Redis connection.""" from kombu.utils.url import _parse_url as parse_redis_url from redis import ( StrictRedis, ConnectionError as RedisConnectionError, ResponseError as RedisResponseError, ) for conf_name in ('REDIS_URL', 'BROKER_URL', 'CELERY_...
[ "def", "get_redis_info", "(", ")", ":", "from", "kombu", ".", "utils", ".", "url", "import", "_parse_url", "as", "parse_redis_url", "from", "redis", "import", "(", "StrictRedis", ",", "ConnectionError", "as", "RedisConnectionError", ",", "ResponseError", "as", "...
Check Redis connection.
[ "Check", "Redis", "connection", "." ]
99bd29343138f94a08718fdbd9285e551751777b
https://github.com/mitodl/django-server-status/blob/99bd29343138f94a08718fdbd9285e551751777b/server_status/views.py#L64-L102
train
mitodl/django-server-status
server_status/views.py
get_elasticsearch_info
def get_elasticsearch_info(): """Check Elasticsearch connection.""" from elasticsearch import ( Elasticsearch, ConnectionError as ESConnectionError ) if hasattr(settings, 'ELASTICSEARCH_URL'): url = settings.ELASTICSEARCH_URL else: return {"status": NO_CONFIG} sta...
python
def get_elasticsearch_info(): """Check Elasticsearch connection.""" from elasticsearch import ( Elasticsearch, ConnectionError as ESConnectionError ) if hasattr(settings, 'ELASTICSEARCH_URL'): url = settings.ELASTICSEARCH_URL else: return {"status": NO_CONFIG} sta...
[ "def", "get_elasticsearch_info", "(", ")", ":", "from", "elasticsearch", "import", "(", "Elasticsearch", ",", "ConnectionError", "as", "ESConnectionError", ")", "if", "hasattr", "(", "settings", ",", "'ELASTICSEARCH_URL'", ")", ":", "url", "=", "settings", ".", ...
Check Elasticsearch connection.
[ "Check", "Elasticsearch", "connection", "." ]
99bd29343138f94a08718fdbd9285e551751777b
https://github.com/mitodl/django-server-status/blob/99bd29343138f94a08718fdbd9285e551751777b/server_status/views.py#L105-L125
train
mitodl/django-server-status
server_status/views.py
get_celery_info
def get_celery_info(): """ Check celery availability """ import celery if not getattr(settings, 'USE_CELERY', False): log.error("No celery config found. Set USE_CELERY in settings to enable.") return {"status": NO_CONFIG} start = datetime.now() try: # pylint: disable=...
python
def get_celery_info(): """ Check celery availability """ import celery if not getattr(settings, 'USE_CELERY', False): log.error("No celery config found. Set USE_CELERY in settings to enable.") return {"status": NO_CONFIG} start = datetime.now() try: # pylint: disable=...
[ "def", "get_celery_info", "(", ")", ":", "import", "celery", "if", "not", "getattr", "(", "settings", ",", "'USE_CELERY'", ",", "False", ")", ":", "log", ".", "error", "(", "\"No celery config found. Set USE_CELERY in settings to enable.\"", ")", "return", "{", "\...
Check celery availability
[ "Check", "celery", "availability" ]
99bd29343138f94a08718fdbd9285e551751777b
https://github.com/mitodl/django-server-status/blob/99bd29343138f94a08718fdbd9285e551751777b/server_status/views.py#L128-L153
train
mitodl/django-server-status
server_status/views.py
get_certificate_info
def get_certificate_info(): """ checks app certificate expiry status """ if hasattr(settings, 'MIT_WS_CERTIFICATE') and settings.MIT_WS_CERTIFICATE: mit_ws_certificate = settings.MIT_WS_CERTIFICATE else: return {"status": NO_CONFIG} app_cert = OpenSSL.crypto.load_certificate( ...
python
def get_certificate_info(): """ checks app certificate expiry status """ if hasattr(settings, 'MIT_WS_CERTIFICATE') and settings.MIT_WS_CERTIFICATE: mit_ws_certificate = settings.MIT_WS_CERTIFICATE else: return {"status": NO_CONFIG} app_cert = OpenSSL.crypto.load_certificate( ...
[ "def", "get_certificate_info", "(", ")", ":", "if", "hasattr", "(", "settings", ",", "'MIT_WS_CERTIFICATE'", ")", "and", "settings", ".", "MIT_WS_CERTIFICATE", ":", "mit_ws_certificate", "=", "settings", ".", "MIT_WS_CERTIFICATE", "else", ":", "return", "{", "\"st...
checks app certificate expiry status
[ "checks", "app", "certificate", "expiry", "status" ]
99bd29343138f94a08718fdbd9285e551751777b
https://github.com/mitodl/django-server-status/blob/99bd29343138f94a08718fdbd9285e551751777b/server_status/views.py#L156-L182
train
bitcaster-io/bitcaster
src/telebot/__init__.py
TeleBot._start
def _start(self): '''Requests bot information based on current api_key, and sets self.whoami to dictionary with username, first_name, and id of the configured bot. ''' if self.whoami is None: me = self.get_me() if me.get('ok', False): self...
python
def _start(self): '''Requests bot information based on current api_key, and sets self.whoami to dictionary with username, first_name, and id of the configured bot. ''' if self.whoami is None: me = self.get_me() if me.get('ok', False): self...
[ "def", "_start", "(", "self", ")", ":", "if", "self", ".", "whoami", "is", "None", ":", "me", "=", "self", ".", "get_me", "(", ")", "if", "me", ".", "get", "(", "'ok'", ",", "False", ")", ":", "self", ".", "whoami", "=", "me", "[", "'result'", ...
Requests bot information based on current api_key, and sets self.whoami to dictionary with username, first_name, and id of the configured bot.
[ "Requests", "bot", "information", "based", "on", "current", "api_key", "and", "sets", "self", ".", "whoami", "to", "dictionary", "with", "username", "first_name", "and", "id", "of", "the", "configured", "bot", "." ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/telebot/__init__.py#L74-L86
train
bitcaster-io/bitcaster
src/telebot/__init__.py
TeleBot.poll
def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False): '''These should also be in the config section, but some here for overrides ''' if self.config['api_key'] is None: raise ValueError('config api_key is undefined') if offset or self.config.get('o...
python
def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False): '''These should also be in the config section, but some here for overrides ''' if self.config['api_key'] is None: raise ValueError('config api_key is undefined') if offset or self.config.get('o...
[ "def", "poll", "(", "self", ",", "offset", "=", "None", ",", "poll_timeout", "=", "600", ",", "cooldown", "=", "60", ",", "debug", "=", "False", ")", ":", "if", "self", ".", "config", "[", "'api_key'", "]", "is", "None", ":", "raise", "ValueError", ...
These should also be in the config section, but some here for overrides
[ "These", "should", "also", "be", "in", "the", "config", "section", "but", "some", "here", "for", "overrides" ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/telebot/__init__.py#L88-L114
train
bitcaster-io/bitcaster
src/bitcaster/utils/language.py
get_attr
def get_attr(obj, attr, default=None): """Recursive get object's attribute. May use dot notation. >>> class C(object): pass >>> a = C() >>> a.b = C() >>> a.b.c = 4 >>> get_attr(a, 'b.c') 4 >>> get_attr(a, 'b.c.y', None) >>> get_attr(a, 'b.c.y', 1) 1 """ if '.' not in a...
python
def get_attr(obj, attr, default=None): """Recursive get object's attribute. May use dot notation. >>> class C(object): pass >>> a = C() >>> a.b = C() >>> a.b.c = 4 >>> get_attr(a, 'b.c') 4 >>> get_attr(a, 'b.c.y', None) >>> get_attr(a, 'b.c.y', 1) 1 """ if '.' not in a...
[ "def", "get_attr", "(", "obj", ",", "attr", ",", "default", "=", "None", ")", ":", "if", "'.'", "not", "in", "attr", ":", "return", "getattr", "(", "obj", ",", "attr", ",", "default", ")", "else", ":", "L", "=", "attr", ".", "split", "(", "'.'", ...
Recursive get object's attribute. May use dot notation. >>> class C(object): pass >>> a = C() >>> a.b = C() >>> a.b.c = 4 >>> get_attr(a, 'b.c') 4 >>> get_attr(a, 'b.c.y', None) >>> get_attr(a, 'b.c.y', 1) 1
[ "Recursive", "get", "object", "s", "attribute", ".", "May", "use", "dot", "notation", "." ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/utils/language.py#L32-L51
train
bitcaster-io/bitcaster
src/bitcaster/web/templatetags/bc_assets.py
asset
def asset(path): """ Join the given path with the STATIC_URL setting. Usage:: {% static path [as varname] %} Examples:: {% static "myapp/css/base.css" %} {% static variable_with_path %} {% static "myapp/css/base.css" as admin_base_css %} {% static variable_wit...
python
def asset(path): """ Join the given path with the STATIC_URL setting. Usage:: {% static path [as varname] %} Examples:: {% static "myapp/css/base.css" %} {% static variable_with_path %} {% static "myapp/css/base.css" as admin_base_css %} {% static variable_wit...
[ "def", "asset", "(", "path", ")", ":", "commit", "=", "bitcaster", ".", "get_full_version", "(", ")", "return", "mark_safe", "(", "'{0}?{1}'", ".", "format", "(", "_static", "(", "path", ")", ",", "commit", ")", ")" ]
Join the given path with the STATIC_URL setting. Usage:: {% static path [as varname] %} Examples:: {% static "myapp/css/base.css" %} {% static variable_with_path %} {% static "myapp/css/base.css" as admin_base_css %} {% static variable_with_path as varname %}
[ "Join", "the", "given", "path", "with", "the", "STATIC_URL", "setting", "." ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/web/templatetags/bc_assets.py#L19-L35
train
bitcaster-io/bitcaster
src/bitcaster/utils/wsgi.py
get_client_ip
def get_client_ip(request): """ Naively yank the first IP address in an X-Forwarded-For header and assume this is correct. Note: Don't use this in security sensitive situations since this value may be forged from a client. """ try: return request.META['HTTP_X_FORWARDED_FOR'].split('...
python
def get_client_ip(request): """ Naively yank the first IP address in an X-Forwarded-For header and assume this is correct. Note: Don't use this in security sensitive situations since this value may be forged from a client. """ try: return request.META['HTTP_X_FORWARDED_FOR'].split('...
[ "def", "get_client_ip", "(", "request", ")", ":", "try", ":", "return", "request", ".", "META", "[", "'HTTP_X_FORWARDED_FOR'", "]", ".", "split", "(", "','", ")", "[", "0", "]", ".", "strip", "(", ")", "except", "(", "KeyError", ",", "IndexError", ")",...
Naively yank the first IP address in an X-Forwarded-For header and assume this is correct. Note: Don't use this in security sensitive situations since this value may be forged from a client.
[ "Naively", "yank", "the", "first", "IP", "address", "in", "an", "X", "-", "Forwarded", "-", "For", "header", "and", "assume", "this", "is", "correct", "." ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/utils/wsgi.py#L6-L17
train
bitcaster-io/bitcaster
src/tweepy/api.py
API._pack_image
def _pack_image(filename, max_size, form_field='image', f=None): """Pack image from file into multipart-formdata post body""" # image must be less than 700kb in size if f is None: try: if os.path.getsize(filename) > (max_size * 1024): raise TweepEr...
python
def _pack_image(filename, max_size, form_field='image', f=None): """Pack image from file into multipart-formdata post body""" # image must be less than 700kb in size if f is None: try: if os.path.getsize(filename) > (max_size * 1024): raise TweepEr...
[ "def", "_pack_image", "(", "filename", ",", "max_size", ",", "form_field", "=", "'image'", ",", "f", "=", "None", ")", ":", "if", "f", "is", "None", ":", "try", ":", "if", "os", ".", "path", ".", "getsize", "(", "filename", ")", ">", "(", "max_size...
Pack image from file into multipart-formdata post body
[ "Pack", "image", "from", "file", "into", "multipart", "-", "formdata", "post", "body" ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/tweepy/api.py#L1344-L1394
train
bitcaster-io/bitcaster
src/bitcaster/web/templatetags/bitcaster.py
channel_submit_row
def channel_submit_row(context): """ Display the row of buttons for delete and save. """ change = context['change'] is_popup = context['is_popup'] save_as = context['save_as'] show_save = context.get('show_save', True) show_save_and_continue = context.get('show_save_and_continue', True) ...
python
def channel_submit_row(context): """ Display the row of buttons for delete and save. """ change = context['change'] is_popup = context['is_popup'] save_as = context['save_as'] show_save = context.get('show_save', True) show_save_and_continue = context.get('show_save_and_continue', True) ...
[ "def", "channel_submit_row", "(", "context", ")", ":", "change", "=", "context", "[", "'change'", "]", "is_popup", "=", "context", "[", "'is_popup'", "]", "save_as", "=", "context", "[", "'save_as'", "]", "show_save", "=", "context", ".", "get", "(", "'sho...
Display the row of buttons for delete and save.
[ "Display", "the", "row", "of", "buttons", "for", "delete", "and", "save", "." ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/web/templatetags/bitcaster.py#L77-L106
train
bitcaster-io/bitcaster
src/bitcaster/social_auth.py
BitcasterStrategy.get_setting
def get_setting(self, name): notfound = object() "get configuration from 'constance.config' first " value = getattr(config, name, notfound) if name.endswith('_WHITELISTED_DOMAINS'): if value: return value.split(',') else: return [] ...
python
def get_setting(self, name): notfound = object() "get configuration from 'constance.config' first " value = getattr(config, name, notfound) if name.endswith('_WHITELISTED_DOMAINS'): if value: return value.split(',') else: return [] ...
[ "def", "get_setting", "(", "self", ",", "name", ")", ":", "notfound", "=", "object", "(", ")", "\"get configuration from 'constance.config' first \"", "value", "=", "getattr", "(", "config", ",", "name", ",", "notfound", ")", "if", "name", ".", "endswith", "("...
get configuration from 'constance.config' first
[ "get", "configuration", "from", "constance", ".", "config", "first" ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/social_auth.py#L78-L95
train
bitcaster-io/bitcaster
src/bitcaster/messages.py
Wrapper.debug
def debug(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``DEBUG`` level.""" add(self.target_name, request, constants.DEBUG, message, extra_tags=extra_tags, fail_silently=fail_silently)
python
def debug(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``DEBUG`` level.""" add(self.target_name, request, constants.DEBUG, message, extra_tags=extra_tags, fail_silently=fail_silently)
[ "def", "debug", "(", "self", ",", "request", ",", "message", ",", "extra_tags", "=", "''", ",", "fail_silently", "=", "False", ")", ":", "add", "(", "self", ".", "target_name", ",", "request", ",", "constants", ".", "DEBUG", ",", "message", ",", "extra...
Add a message with the ``DEBUG`` level.
[ "Add", "a", "message", "with", "the", "DEBUG", "level", "." ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/messages.py#L54-L57
train
bitcaster-io/bitcaster
src/bitcaster/messages.py
Wrapper.info
def info(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``INFO`` level.""" add(self.target_name, request, constants.INFO, message, extra_tags=extra_tags, fail_silently=fail_silently)
python
def info(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``INFO`` level.""" add(self.target_name, request, constants.INFO, message, extra_tags=extra_tags, fail_silently=fail_silently)
[ "def", "info", "(", "self", ",", "request", ",", "message", ",", "extra_tags", "=", "''", ",", "fail_silently", "=", "False", ")", ":", "add", "(", "self", ".", "target_name", ",", "request", ",", "constants", ".", "INFO", ",", "message", ",", "extra_t...
Add a message with the ``INFO`` level.
[ "Add", "a", "message", "with", "the", "INFO", "level", "." ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/messages.py#L59-L63
train
bitcaster-io/bitcaster
src/bitcaster/messages.py
Wrapper.success
def success(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``SUCCESS`` level.""" add(self.target_name, request, constants.SUCCESS, message, extra_tags=extra_tags, fail_silently=fail_silently)
python
def success(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``SUCCESS`` level.""" add(self.target_name, request, constants.SUCCESS, message, extra_tags=extra_tags, fail_silently=fail_silently)
[ "def", "success", "(", "self", ",", "request", ",", "message", ",", "extra_tags", "=", "''", ",", "fail_silently", "=", "False", ")", ":", "add", "(", "self", ".", "target_name", ",", "request", ",", "constants", ".", "SUCCESS", ",", "message", ",", "e...
Add a message with the ``SUCCESS`` level.
[ "Add", "a", "message", "with", "the", "SUCCESS", "level", "." ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/messages.py#L65-L68
train
bitcaster-io/bitcaster
src/bitcaster/messages.py
Wrapper.warning
def warning(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``WARNING`` level.""" add(self.target_name, request, constants.WARNING, message, extra_tags=extra_tags, fail_silently=fail_silently)
python
def warning(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``WARNING`` level.""" add(self.target_name, request, constants.WARNING, message, extra_tags=extra_tags, fail_silently=fail_silently)
[ "def", "warning", "(", "self", ",", "request", ",", "message", ",", "extra_tags", "=", "''", ",", "fail_silently", "=", "False", ")", ":", "add", "(", "self", ".", "target_name", ",", "request", ",", "constants", ".", "WARNING", ",", "message", ",", "e...
Add a message with the ``WARNING`` level.
[ "Add", "a", "message", "with", "the", "WARNING", "level", "." ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/messages.py#L70-L73
train
bitcaster-io/bitcaster
src/bitcaster/messages.py
Wrapper.error
def error(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``ERROR`` level.""" add(self.target_name, request, constants.ERROR, message, extra_tags=extra_tags, fail_silently=fail_silently)
python
def error(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``ERROR`` level.""" add(self.target_name, request, constants.ERROR, message, extra_tags=extra_tags, fail_silently=fail_silently)
[ "def", "error", "(", "self", ",", "request", ",", "message", ",", "extra_tags", "=", "''", ",", "fail_silently", "=", "False", ")", ":", "add", "(", "self", ".", "target_name", ",", "request", ",", "constants", ".", "ERROR", ",", "message", ",", "extra...
Add a message with the ``ERROR`` level.
[ "Add", "a", "message", "with", "the", "ERROR", "level", "." ]
04625a4b67c1ad01e5d38faa3093828b360d4a98
https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/messages.py#L75-L78
train
bread-and-pepper/django-userena
userena/views.py
signup
def signup(request, signup_form=SignupForm, template_name='userena/signup_form.html', success_url=None, extra_context=None): """ Signup of an account. Signup requiring a username, email and password. After signup a user gets an email with an activation link used to activate their ...
python
def signup(request, signup_form=SignupForm, template_name='userena/signup_form.html', success_url=None, extra_context=None): """ Signup of an account. Signup requiring a username, email and password. After signup a user gets an email with an activation link used to activate their ...
[ "def", "signup", "(", "request", ",", "signup_form", "=", "SignupForm", ",", "template_name", "=", "'userena/signup_form.html'", ",", "success_url", "=", "None", ",", "extra_context", "=", "None", ")", ":", "if", "userena_settings", ".", "USERENA_DISABLE_SIGNUP", ...
Signup of an account. Signup requiring a username, email and password. After signup a user gets an email with an activation link used to activate their account. After successful signup redirects to ``success_url``. :param signup_form: Form that will be used to sign a user. Defaults to userena'...
[ "Signup", "of", "an", "account", "." ]
7dfb3d5d148127e32f217a62096d507266a3a83c
https://github.com/bread-and-pepper/django-userena/blob/7dfb3d5d148127e32f217a62096d507266a3a83c/userena/views.py#L73-L146
train
openvax/mhcflurry
mhcflurry/hyperparameters.py
HyperparameterDefaults.extend
def extend(self, other): """ Return a new HyperparameterDefaults instance containing the hyperparameters from the current instance combined with those from other. It is an error if self and other have any hyperparameters in common. """ overlap = [key for ...
python
def extend(self, other): """ Return a new HyperparameterDefaults instance containing the hyperparameters from the current instance combined with those from other. It is an error if self and other have any hyperparameters in common. """ overlap = [key for ...
[ "def", "extend", "(", "self", ",", "other", ")", ":", "overlap", "=", "[", "key", "for", "key", "in", "other", ".", "defaults", "if", "key", "in", "self", ".", "defaults", "]", "if", "overlap", ":", "raise", "ValueError", "(", "\"Duplicate hyperparameter...
Return a new HyperparameterDefaults instance containing the hyperparameters from the current instance combined with those from other. It is an error if self and other have any hyperparameters in common.
[ "Return", "a", "new", "HyperparameterDefaults", "instance", "containing", "the", "hyperparameters", "from", "the", "current", "instance", "combined", "with", "those", "from", "other", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/hyperparameters.py#L22-L37
train
openvax/mhcflurry
mhcflurry/hyperparameters.py
HyperparameterDefaults.with_defaults
def with_defaults(self, obj): """ Given a dict of hyperparameter settings, return a dict containing those settings augmented by the defaults for any keys missing from the dict. """ self.check_valid_keys(obj) obj = dict(obj) for (key, value) in self.default...
python
def with_defaults(self, obj): """ Given a dict of hyperparameter settings, return a dict containing those settings augmented by the defaults for any keys missing from the dict. """ self.check_valid_keys(obj) obj = dict(obj) for (key, value) in self.default...
[ "def", "with_defaults", "(", "self", ",", "obj", ")", ":", "self", ".", "check_valid_keys", "(", "obj", ")", "obj", "=", "dict", "(", "obj", ")", "for", "(", "key", ",", "value", ")", "in", "self", ".", "defaults", ".", "items", "(", ")", ":", "i...
Given a dict of hyperparameter settings, return a dict containing those settings augmented by the defaults for any keys missing from the dict.
[ "Given", "a", "dict", "of", "hyperparameter", "settings", "return", "a", "dict", "containing", "those", "settings", "augmented", "by", "the", "defaults", "for", "any", "keys", "missing", "from", "the", "dict", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/hyperparameters.py#L39-L50
train
openvax/mhcflurry
mhcflurry/hyperparameters.py
HyperparameterDefaults.subselect
def subselect(self, obj): """ Filter a dict of hyperparameter settings to only those keys defined in this HyperparameterDefaults . """ return dict( (key, value) for (key, value) in obj.items() if key in self.defaults)
python
def subselect(self, obj): """ Filter a dict of hyperparameter settings to only those keys defined in this HyperparameterDefaults . """ return dict( (key, value) for (key, value) in obj.items() if key in self.defaults)
[ "def", "subselect", "(", "self", ",", "obj", ")", ":", "return", "dict", "(", "(", "key", ",", "value", ")", "for", "(", "key", ",", "value", ")", "in", "obj", ".", "items", "(", ")", "if", "key", "in", "self", ".", "defaults", ")" ]
Filter a dict of hyperparameter settings to only those keys defined in this HyperparameterDefaults .
[ "Filter", "a", "dict", "of", "hyperparameter", "settings", "to", "only", "those", "keys", "defined", "in", "this", "HyperparameterDefaults", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/hyperparameters.py#L52-L60
train
openvax/mhcflurry
mhcflurry/hyperparameters.py
HyperparameterDefaults.check_valid_keys
def check_valid_keys(self, obj): """ Given a dict of hyperparameter settings, throw an exception if any keys are not defined in this HyperparameterDefaults instance. """ invalid_keys = [ x for x in obj if x not in self.defaults ] if invalid_keys: ...
python
def check_valid_keys(self, obj): """ Given a dict of hyperparameter settings, throw an exception if any keys are not defined in this HyperparameterDefaults instance. """ invalid_keys = [ x for x in obj if x not in self.defaults ] if invalid_keys: ...
[ "def", "check_valid_keys", "(", "self", ",", "obj", ")", ":", "invalid_keys", "=", "[", "x", "for", "x", "in", "obj", "if", "x", "not", "in", "self", ".", "defaults", "]", "if", "invalid_keys", ":", "raise", "ValueError", "(", "\"No such model parameters: ...
Given a dict of hyperparameter settings, throw an exception if any keys are not defined in this HyperparameterDefaults instance.
[ "Given", "a", "dict", "of", "hyperparameter", "settings", "throw", "an", "exception", "if", "any", "keys", "are", "not", "defined", "in", "this", "HyperparameterDefaults", "instance", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/hyperparameters.py#L62-L74
train
openvax/mhcflurry
mhcflurry/hyperparameters.py
HyperparameterDefaults.models_grid
def models_grid(self, **kwargs): ''' Make a grid of models by taking the cartesian product of all specified model parameter lists. Parameters ----------- The valid kwarg parameters are the entries of this HyperparameterDefaults instance. Each parameter must be a ...
python
def models_grid(self, **kwargs): ''' Make a grid of models by taking the cartesian product of all specified model parameter lists. Parameters ----------- The valid kwarg parameters are the entries of this HyperparameterDefaults instance. Each parameter must be a ...
[ "def", "models_grid", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "check_valid_keys", "(", "kwargs", ")", "for", "(", "key", ",", "value", ")", "in", "kwargs", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", "value", ",", ...
Make a grid of models by taking the cartesian product of all specified model parameter lists. Parameters ----------- The valid kwarg parameters are the entries of this HyperparameterDefaults instance. Each parameter must be a list giving the values to search across. ...
[ "Make", "a", "grid", "of", "models", "by", "taking", "the", "cartesian", "product", "of", "all", "specified", "model", "parameter", "lists", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/hyperparameters.py#L76-L112
train
openvax/mhcflurry
mhcflurry/allele_encoding.py
AlleleEncoding.fixed_length_vector_encoded_sequences
def fixed_length_vector_encoded_sequences(self, vector_encoding_name): """ Encode alleles. Parameters ---------- vector_encoding_name : string How to represent amino acids. One of "BLOSUM62", "one-hot", etc. Full list of supported vector encod...
python
def fixed_length_vector_encoded_sequences(self, vector_encoding_name): """ Encode alleles. Parameters ---------- vector_encoding_name : string How to represent amino acids. One of "BLOSUM62", "one-hot", etc. Full list of supported vector encod...
[ "def", "fixed_length_vector_encoded_sequences", "(", "self", ",", "vector_encoding_name", ")", ":", "cache_key", "=", "(", "\"fixed_length_vector_encoding\"", ",", "vector_encoding_name", ")", "if", "cache_key", "not", "in", "self", ".", "encoding_cache", ":", "index_en...
Encode alleles. Parameters ---------- vector_encoding_name : string How to represent amino acids. One of "BLOSUM62", "one-hot", etc. Full list of supported vector encodings is given by available_vector_encodings() in amino_acid. Returns -----...
[ "Encode", "alleles", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/allele_encoding.py#L40-L68
train
openvax/mhcflurry
mhcflurry/amino_acid.py
index_encoding
def index_encoding(sequences, letter_to_index_dict): """ Encode a sequence of same-length strings to a matrix of integers of the same shape. The map from characters to integers is given by `letter_to_index_dict`. Given a sequence of `n` strings all of length `k`, return a `k * n` array where th...
python
def index_encoding(sequences, letter_to_index_dict): """ Encode a sequence of same-length strings to a matrix of integers of the same shape. The map from characters to integers is given by `letter_to_index_dict`. Given a sequence of `n` strings all of length `k`, return a `k * n` array where th...
[ "def", "index_encoding", "(", "sequences", ",", "letter_to_index_dict", ")", ":", "df", "=", "pandas", ".", "DataFrame", "(", "iter", "(", "s", ")", "for", "s", "in", "sequences", ")", "result", "=", "df", ".", "replace", "(", "letter_to_index_dict", ")", ...
Encode a sequence of same-length strings to a matrix of integers of the same shape. The map from characters to integers is given by `letter_to_index_dict`. Given a sequence of `n` strings all of length `k`, return a `k * n` array where the (`i`, `j`)th element is `letter_to_index_dict[sequence[i][j]]`....
[ "Encode", "a", "sequence", "of", "same", "-", "length", "strings", "to", "a", "matrix", "of", "integers", "of", "the", "same", "shape", ".", "The", "map", "from", "characters", "to", "integers", "is", "given", "by", "letter_to_index_dict", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/amino_acid.py#L110-L130
train
openvax/mhcflurry
mhcflurry/class1_neural_network.py
Class1NeuralNetwork.apply_hyperparameter_renames
def apply_hyperparameter_renames(cls, hyperparameters): """ Handle hyperparameter renames. Parameters ---------- hyperparameters : dict Returns ------- dict : updated hyperparameters """ for (from_name, to_name) in cls.hyperparameter_ren...
python
def apply_hyperparameter_renames(cls, hyperparameters): """ Handle hyperparameter renames. Parameters ---------- hyperparameters : dict Returns ------- dict : updated hyperparameters """ for (from_name, to_name) in cls.hyperparameter_ren...
[ "def", "apply_hyperparameter_renames", "(", "cls", ",", "hyperparameters", ")", ":", "for", "(", "from_name", ",", "to_name", ")", "in", "cls", ".", "hyperparameter_renames", ".", "items", "(", ")", ":", "if", "from_name", "in", "hyperparameters", ":", "value"...
Handle hyperparameter renames. Parameters ---------- hyperparameters : dict Returns ------- dict : updated hyperparameters
[ "Handle", "hyperparameter", "renames", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_neural_network.py#L136-L154
train
openvax/mhcflurry
mhcflurry/class1_neural_network.py
Class1NeuralNetwork.borrow_cached_network
def borrow_cached_network(klass, network_json, network_weights): """ Return a keras Model with the specified architecture and weights. As an optimization, when possible this will reuse architectures from a process-wide cache. The returned object is "borrowed" in the sense that i...
python
def borrow_cached_network(klass, network_json, network_weights): """ Return a keras Model with the specified architecture and weights. As an optimization, when possible this will reuse architectures from a process-wide cache. The returned object is "borrowed" in the sense that i...
[ "def", "borrow_cached_network", "(", "klass", ",", "network_json", ",", "network_weights", ")", ":", "assert", "network_weights", "is", "not", "None", "key", "=", "klass", ".", "keras_network_cache_key", "(", "network_json", ")", "if", "key", "not", "in", "klass...
Return a keras Model with the specified architecture and weights. As an optimization, when possible this will reuse architectures from a process-wide cache. The returned object is "borrowed" in the sense that its weights can change later after subsequent calls to this method from other ...
[ "Return", "a", "keras", "Model", "with", "the", "specified", "architecture", "and", "weights", ".", "As", "an", "optimization", "when", "possible", "this", "will", "reuse", "architectures", "from", "a", "process", "-", "wide", "cache", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_neural_network.py#L183-L224
train
openvax/mhcflurry
mhcflurry/class1_neural_network.py
Class1NeuralNetwork.network
def network(self, borrow=False): """ Return the keras model associated with this predictor. Parameters ---------- borrow : bool Whether to return a cached model if possible. See borrow_cached_network for details Returns ------- ke...
python
def network(self, borrow=False): """ Return the keras model associated with this predictor. Parameters ---------- borrow : bool Whether to return a cached model if possible. See borrow_cached_network for details Returns ------- ke...
[ "def", "network", "(", "self", ",", "borrow", "=", "False", ")", ":", "if", "self", ".", "_network", "is", "None", "and", "self", ".", "network_json", "is", "not", "None", ":", "self", ".", "load_weights", "(", ")", "if", "borrow", ":", "return", "se...
Return the keras model associated with this predictor. Parameters ---------- borrow : bool Whether to return a cached model if possible. See borrow_cached_network for details Returns ------- keras.models.Model
[ "Return", "the", "keras", "model", "associated", "with", "this", "predictor", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_neural_network.py#L226-L253
train
openvax/mhcflurry
mhcflurry/class1_neural_network.py
Class1NeuralNetwork.load_weights
def load_weights(self): """ Load weights by evaluating self.network_weights_loader, if needed. After calling this, self.network_weights_loader will be None and self.network_weights will be the weights list, if available. """ if self.network_weights_loader: se...
python
def load_weights(self): """ Load weights by evaluating self.network_weights_loader, if needed. After calling this, self.network_weights_loader will be None and self.network_weights will be the weights list, if available. """ if self.network_weights_loader: se...
[ "def", "load_weights", "(", "self", ")", ":", "if", "self", ".", "network_weights_loader", ":", "self", ".", "network_weights", "=", "self", ".", "network_weights_loader", "(", ")", "self", ".", "network_weights_loader", "=", "None" ]
Load weights by evaluating self.network_weights_loader, if needed. After calling this, self.network_weights_loader will be None and self.network_weights will be the weights list, if available.
[ "Load", "weights", "by", "evaluating", "self", ".", "network_weights_loader", "if", "needed", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_neural_network.py#L315-L324
train
openvax/mhcflurry
mhcflurry/class1_neural_network.py
Class1NeuralNetwork.predict
def predict(self, peptides, allele_encoding=None, batch_size=4096): """ Predict affinities. If peptides are specified as EncodableSequences, then the predictions will be cached for this predictor as long as the EncodableSequences object remains in memory. The cache is keyed in t...
python
def predict(self, peptides, allele_encoding=None, batch_size=4096): """ Predict affinities. If peptides are specified as EncodableSequences, then the predictions will be cached for this predictor as long as the EncodableSequences object remains in memory. The cache is keyed in t...
[ "def", "predict", "(", "self", ",", "peptides", ",", "allele_encoding", "=", "None", ",", "batch_size", "=", "4096", ")", ":", "assert", "self", ".", "prediction_cache", "is", "not", "None", "use_cache", "=", "(", "allele_encoding", "is", "None", "and", "i...
Predict affinities. If peptides are specified as EncodableSequences, then the predictions will be cached for this predictor as long as the EncodableSequences object remains in memory. The cache is keyed in the object identity of the EncodableSequences, not the sequences themselves. ...
[ "Predict", "affinities", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_neural_network.py#L739-L782
train
openvax/mhcflurry
mhcflurry/scoring.py
make_scores
def make_scores( ic50_y, ic50_y_pred, sample_weight=None, threshold_nm=500, max_ic50=50000): """ Calculate AUC, F1, and Kendall Tau scores. Parameters ----------- ic50_y : float list true IC50s (i.e. affinities) ic50_y_pred : float list p...
python
def make_scores( ic50_y, ic50_y_pred, sample_weight=None, threshold_nm=500, max_ic50=50000): """ Calculate AUC, F1, and Kendall Tau scores. Parameters ----------- ic50_y : float list true IC50s (i.e. affinities) ic50_y_pred : float list p...
[ "def", "make_scores", "(", "ic50_y", ",", "ic50_y_pred", ",", "sample_weight", "=", "None", ",", "threshold_nm", "=", "500", ",", "max_ic50", "=", "50000", ")", ":", "y_pred", "=", "from_ic50", "(", "ic50_y_pred", ",", "max_ic50", ")", "try", ":", "auc", ...
Calculate AUC, F1, and Kendall Tau scores. Parameters ----------- ic50_y : float list true IC50s (i.e. affinities) ic50_y_pred : float list predicted IC50s sample_weight : float list [optional] threshold_nm : float [optional] max_ic50 : float [optional] Returns ...
[ "Calculate", "AUC", "F1", "and", "Kendall", "Tau", "scores", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/scoring.py#L14-L68
train
openvax/mhcflurry
mhcflurry/encodable_sequences.py
EncodableSequences.variable_length_to_fixed_length_vector_encoding
def variable_length_to_fixed_length_vector_encoding( self, vector_encoding_name, left_edge=4, right_edge=4, max_length=15): """ Encode variable-length sequences using a fixed-length encoding designed for preserving the anchor positions of class I peptides. The sequences must...
python
def variable_length_to_fixed_length_vector_encoding( self, vector_encoding_name, left_edge=4, right_edge=4, max_length=15): """ Encode variable-length sequences using a fixed-length encoding designed for preserving the anchor positions of class I peptides. The sequences must...
[ "def", "variable_length_to_fixed_length_vector_encoding", "(", "self", ",", "vector_encoding_name", ",", "left_edge", "=", "4", ",", "right_edge", "=", "4", ",", "max_length", "=", "15", ")", ":", "cache_key", "=", "(", "\"fixed_length_vector_encoding\"", ",", "vect...
Encode variable-length sequences using a fixed-length encoding designed for preserving the anchor positions of class I peptides. The sequences must be of length at least left_edge + right_edge, and at most max_length. Parameters ---------- vector_encoding_name : string ...
[ "Encode", "variable", "-", "length", "sequences", "using", "a", "fixed", "-", "length", "encoding", "designed", "for", "preserving", "the", "anchor", "positions", "of", "class", "I", "peptides", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/encodable_sequences.py#L89-L131
train
openvax/mhcflurry
mhcflurry/encodable_sequences.py
EncodableSequences.sequences_to_fixed_length_index_encoded_array
def sequences_to_fixed_length_index_encoded_array( klass, sequences, left_edge=4, right_edge=4, max_length=15): """ Transform a sequence of strings, where each string is of length at least left_edge + right_edge and at most max_length into strings of length max_length using a...
python
def sequences_to_fixed_length_index_encoded_array( klass, sequences, left_edge=4, right_edge=4, max_length=15): """ Transform a sequence of strings, where each string is of length at least left_edge + right_edge and at most max_length into strings of length max_length using a...
[ "def", "sequences_to_fixed_length_index_encoded_array", "(", "klass", ",", "sequences", ",", "left_edge", "=", "4", ",", "right_edge", "=", "4", ",", "max_length", "=", "15", ")", ":", "result", "=", "numpy", ".", "full", "(", "fill_value", "=", "amino_acid", ...
Transform a sequence of strings, where each string is of length at least left_edge + right_edge and at most max_length into strings of length max_length using a scheme designed to preserve the anchor positions of class I peptides. The first left_edge characters in the input always map t...
[ "Transform", "a", "sequence", "of", "strings", "where", "each", "string", "is", "of", "length", "at", "least", "left_edge", "+", "right_edge", "and", "at", "most", "max_length", "into", "strings", "of", "length", "max_length", "using", "a", "scheme", "designed...
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/encodable_sequences.py#L134-L223
train
openvax/mhcflurry
mhcflurry/ensemble_centrality.py
robust_mean
def robust_mean(log_values): """ Mean of values falling within the 25-75 percentiles. Parameters ---------- log_values : 2-d numpy.array Center is computed along the second axis (i.e. per row). Returns ------- center : numpy.array of length log_values.shape[1] """ if l...
python
def robust_mean(log_values): """ Mean of values falling within the 25-75 percentiles. Parameters ---------- log_values : 2-d numpy.array Center is computed along the second axis (i.e. per row). Returns ------- center : numpy.array of length log_values.shape[1] """ if l...
[ "def", "robust_mean", "(", "log_values", ")", ":", "if", "log_values", ".", "shape", "[", "1", "]", "<=", "3", ":", "return", "numpy", ".", "nanmean", "(", "log_values", ",", "axis", "=", "1", ")", "without_nans", "=", "numpy", ".", "nan_to_num", "(", ...
Mean of values falling within the 25-75 percentiles. Parameters ---------- log_values : 2-d numpy.array Center is computed along the second axis (i.e. per row). Returns ------- center : numpy.array of length log_values.shape[1]
[ "Mean", "of", "values", "falling", "within", "the", "25", "-", "75", "percentiles", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/ensemble_centrality.py#L11-L33
train
openvax/mhcflurry
mhcflurry/class1_affinity_predictor.py
Class1AffinityPredictor.neural_networks
def neural_networks(self): """ List of the neural networks in the ensemble. Returns ------- list of `Class1NeuralNetwork` """ result = [] for models in self.allele_to_allele_specific_models.values(): result.extend(models) result.extend...
python
def neural_networks(self): """ List of the neural networks in the ensemble. Returns ------- list of `Class1NeuralNetwork` """ result = [] for models in self.allele_to_allele_specific_models.values(): result.extend(models) result.extend...
[ "def", "neural_networks", "(", "self", ")", ":", "result", "=", "[", "]", "for", "models", "in", "self", ".", "allele_to_allele_specific_models", ".", "values", "(", ")", ":", "result", ".", "extend", "(", "models", ")", "result", ".", "extend", "(", "se...
List of the neural networks in the ensemble. Returns ------- list of `Class1NeuralNetwork`
[ "List", "of", "the", "neural", "networks", "in", "the", "ensemble", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_affinity_predictor.py#L140-L152
train
openvax/mhcflurry
mhcflurry/class1_affinity_predictor.py
Class1AffinityPredictor.merge
def merge(cls, predictors): """ Merge the ensembles of two or more `Class1AffinityPredictor` instances. Note: the resulting merged predictor will NOT have calibrated percentile ranks. Call `calibrate_percentile_ranks` on it if these are needed. Parameters ---------- ...
python
def merge(cls, predictors): """ Merge the ensembles of two or more `Class1AffinityPredictor` instances. Note: the resulting merged predictor will NOT have calibrated percentile ranks. Call `calibrate_percentile_ranks` on it if these are needed. Parameters ---------- ...
[ "def", "merge", "(", "cls", ",", "predictors", ")", ":", "assert", "len", "(", "predictors", ")", ">", "0", "if", "len", "(", "predictors", ")", "==", "1", ":", "return", "predictors", "[", "0", "]", "allele_to_allele_specific_models", "=", "collections", ...
Merge the ensembles of two or more `Class1AffinityPredictor` instances. Note: the resulting merged predictor will NOT have calibrated percentile ranks. Call `calibrate_percentile_ranks` on it if these are needed. Parameters ---------- predictors : sequence of `Class1AffinityPre...
[ "Merge", "the", "ensembles", "of", "two", "or", "more", "Class1AffinityPredictor", "instances", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_affinity_predictor.py#L155-L190
train
openvax/mhcflurry
mhcflurry/class1_affinity_predictor.py
Class1AffinityPredictor.merge_in_place
def merge_in_place(self, others): """ Add the models present other predictors into the current predictor. Parameters ---------- others : list of Class1AffinityPredictor Other predictors to merge into the current predictor. Returns ------- lis...
python
def merge_in_place(self, others): """ Add the models present other predictors into the current predictor. Parameters ---------- others : list of Class1AffinityPredictor Other predictors to merge into the current predictor. Returns ------- lis...
[ "def", "merge_in_place", "(", "self", ",", "others", ")", ":", "new_model_names", "=", "[", "]", "for", "predictor", "in", "others", ":", "for", "model", "in", "predictor", ".", "class1_pan_allele_models", ":", "model_name", "=", "self", ".", "model_name", "...
Add the models present other predictors into the current predictor. Parameters ---------- others : list of Class1AffinityPredictor Other predictors to merge into the current predictor. Returns ------- list of string : names of newly added models
[ "Add", "the", "models", "present", "other", "predictors", "into", "the", "current", "predictor", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_affinity_predictor.py#L192-L241
train
openvax/mhcflurry
mhcflurry/class1_affinity_predictor.py
Class1AffinityPredictor.percentile_ranks
def percentile_ranks(self, affinities, allele=None, alleles=None, throw=True): """ Return percentile ranks for the given ic50 affinities and alleles. The 'allele' and 'alleles' argument are as in the `predict` method. Specify one of these. Parameters ---------- ...
python
def percentile_ranks(self, affinities, allele=None, alleles=None, throw=True): """ Return percentile ranks for the given ic50 affinities and alleles. The 'allele' and 'alleles' argument are as in the `predict` method. Specify one of these. Parameters ---------- ...
[ "def", "percentile_ranks", "(", "self", ",", "affinities", ",", "allele", "=", "None", ",", "alleles", "=", "None", ",", "throw", "=", "True", ")", ":", "if", "allele", "is", "not", "None", ":", "try", ":", "transform", "=", "self", ".", "allele_to_per...
Return percentile ranks for the given ic50 affinities and alleles. The 'allele' and 'alleles' argument are as in the `predict` method. Specify one of these. Parameters ---------- affinities : sequence of float nM affinities allele : string alleles : ...
[ "Return", "percentile", "ranks", "for", "the", "given", "ic50", "affinities", "and", "alleles", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_affinity_predictor.py#L722-L766
train
openvax/mhcflurry
mhcflurry/class1_affinity_predictor.py
Class1AffinityPredictor.calibrate_percentile_ranks
def calibrate_percentile_ranks( self, peptides=None, num_peptides_per_length=int(1e5), alleles=None, bins=None): """ Compute the cumulative distribution of ic50 values for a set of alleles over a large universe of random peptides, to en...
python
def calibrate_percentile_ranks( self, peptides=None, num_peptides_per_length=int(1e5), alleles=None, bins=None): """ Compute the cumulative distribution of ic50 values for a set of alleles over a large universe of random peptides, to en...
[ "def", "calibrate_percentile_ranks", "(", "self", ",", "peptides", "=", "None", ",", "num_peptides_per_length", "=", "int", "(", "1e5", ")", ",", "alleles", "=", "None", ",", "bins", "=", "None", ")", ":", "if", "bins", "is", "None", ":", "bins", "=", ...
Compute the cumulative distribution of ic50 values for a set of alleles over a large universe of random peptides, to enable computing quantiles in this distribution later. Parameters ---------- peptides : sequence of string or EncodableSequences, optional Peptides to...
[ "Compute", "the", "cumulative", "distribution", "of", "ic50", "values", "for", "a", "set", "of", "alleles", "over", "a", "large", "universe", "of", "random", "peptides", "to", "enable", "computing", "quantiles", "in", "this", "distribution", "later", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_affinity_predictor.py#L1074-L1128
train
openvax/mhcflurry
mhcflurry/class1_affinity_predictor.py
Class1AffinityPredictor.filter_networks
def filter_networks(self, predicate): """ Return a new Class1AffinityPredictor containing a subset of this predictor's neural networks. Parameters ---------- predicate : Class1NeuralNetwork -> boolean Function specifying which neural networks to include ...
python
def filter_networks(self, predicate): """ Return a new Class1AffinityPredictor containing a subset of this predictor's neural networks. Parameters ---------- predicate : Class1NeuralNetwork -> boolean Function specifying which neural networks to include ...
[ "def", "filter_networks", "(", "self", ",", "predicate", ")", ":", "allele_to_allele_specific_models", "=", "{", "}", "for", "(", "allele", ",", "models", ")", "in", "self", ".", "allele_to_allele_specific_models", ".", "items", "(", ")", ":", "allele_to_allele_...
Return a new Class1AffinityPredictor containing a subset of this predictor's neural networks. Parameters ---------- predicate : Class1NeuralNetwork -> boolean Function specifying which neural networks to include Returns ------- Class1AffinityPredicto...
[ "Return", "a", "new", "Class1AffinityPredictor", "containing", "a", "subset", "of", "this", "predictor", "s", "neural", "networks", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_affinity_predictor.py#L1130-L1157
train
openvax/mhcflurry
mhcflurry/class1_affinity_predictor.py
Class1AffinityPredictor.model_select
def model_select( self, score_function, alleles=None, min_models=1, max_models=10000): """ Perform model selection using a user-specified scoring function. Model selection is done using a "step up" variable selection procedure, ...
python
def model_select( self, score_function, alleles=None, min_models=1, max_models=10000): """ Perform model selection using a user-specified scoring function. Model selection is done using a "step up" variable selection procedure, ...
[ "def", "model_select", "(", "self", ",", "score_function", ",", "alleles", "=", "None", ",", "min_models", "=", "1", ",", "max_models", "=", "10000", ")", ":", "if", "alleles", "is", "None", ":", "alleles", "=", "self", ".", "supported_alleles", "dfs", "...
Perform model selection using a user-specified scoring function. Model selection is done using a "step up" variable selection procedure, in which models are repeatedly added to an ensemble until the score stops improving. Parameters ---------- score_function : Class1Aff...
[ "Perform", "model", "selection", "using", "a", "user", "-", "specified", "scoring", "function", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_affinity_predictor.py#L1159-L1245
train
openvax/mhcflurry
mhcflurry/percent_rank_transform.py
PercentRankTransform.to_series
def to_series(self): """ Serialize the fit to a pandas.Series. The index on the series gives the bin edges and the valeus give the CDF. Returns ------- pandas.Series """ return pandas.Series( self.cdf, index=[numpy.nan] + list(self.bin_edges...
python
def to_series(self): """ Serialize the fit to a pandas.Series. The index on the series gives the bin edges and the valeus give the CDF. Returns ------- pandas.Series """ return pandas.Series( self.cdf, index=[numpy.nan] + list(self.bin_edges...
[ "def", "to_series", "(", "self", ")", ":", "return", "pandas", ".", "Series", "(", "self", ".", "cdf", ",", "index", "=", "[", "numpy", ".", "nan", "]", "+", "list", "(", "self", ".", "bin_edges", ")", "+", "[", "numpy", ".", "nan", "]", ")" ]
Serialize the fit to a pandas.Series. The index on the series gives the bin edges and the valeus give the CDF. Returns ------- pandas.Series
[ "Serialize", "the", "fit", "to", "a", "pandas", ".", "Series", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/percent_rank_transform.py#L46-L58
train
openvax/mhcflurry
mhcflurry/downloads.py
get_default_class1_models_dir
def get_default_class1_models_dir(test_exists=True): """ Return the absolute path to the default class1 models dir. If environment variable MHCFLURRY_DEFAULT_CLASS1_MODELS is set to an absolute path, return that path. If it's set to a relative path (i.e. does not start with /) then return that path...
python
def get_default_class1_models_dir(test_exists=True): """ Return the absolute path to the default class1 models dir. If environment variable MHCFLURRY_DEFAULT_CLASS1_MODELS is set to an absolute path, return that path. If it's set to a relative path (i.e. does not start with /) then return that path...
[ "def", "get_default_class1_models_dir", "(", "test_exists", "=", "True", ")", ":", "if", "_MHCFLURRY_DEFAULT_CLASS1_MODELS_DIR", ":", "result", "=", "join", "(", "get_downloads_dir", "(", ")", ",", "_MHCFLURRY_DEFAULT_CLASS1_MODELS_DIR", ")", "if", "test_exists", "and",...
Return the absolute path to the default class1 models dir. If environment variable MHCFLURRY_DEFAULT_CLASS1_MODELS is set to an absolute path, return that path. If it's set to a relative path (i.e. does not start with /) then return that path taken to be relative to the mhcflurry downloads dir. If...
[ "Return", "the", "absolute", "path", "to", "the", "default", "class1", "models", "dir", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/downloads.py#L57-L85
train
openvax/mhcflurry
mhcflurry/downloads.py
get_current_release_downloads
def get_current_release_downloads(): """ Return a dict of all available downloads in the current release. The dict keys are the names of the downloads. The values are a dict with two entries: downloaded : bool Whether the download is currently available locally metadata : dict ...
python
def get_current_release_downloads(): """ Return a dict of all available downloads in the current release. The dict keys are the names of the downloads. The values are a dict with two entries: downloaded : bool Whether the download is currently available locally metadata : dict ...
[ "def", "get_current_release_downloads", "(", ")", ":", "downloads", "=", "(", "get_downloads_metadata", "(", ")", "[", "'releases'", "]", "[", "get_current_release", "(", ")", "]", "[", "'downloads'", "]", ")", "return", "OrderedDict", "(", "(", "download", "[...
Return a dict of all available downloads in the current release. The dict keys are the names of the downloads. The values are a dict with two entries: downloaded : bool Whether the download is currently available locally metadata : dict Info about the download from downloads.yml such ...
[ "Return", "a", "dict", "of", "all", "available", "downloads", "in", "the", "current", "release", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/downloads.py#L88-L111
train
openvax/mhcflurry
mhcflurry/downloads.py
get_path
def get_path(download_name, filename='', test_exists=True): """ Get the local path to a file in a MHCflurry download Parameters ----------- download_name : string filename : string Relative path within the download to the file of interest test_exists : boolean If True (def...
python
def get_path(download_name, filename='', test_exists=True): """ Get the local path to a file in a MHCflurry download Parameters ----------- download_name : string filename : string Relative path within the download to the file of interest test_exists : boolean If True (def...
[ "def", "get_path", "(", "download_name", ",", "filename", "=", "''", ",", "test_exists", "=", "True", ")", ":", "assert", "'/'", "not", "in", "download_name", ",", "\"Invalid download: %s\"", "%", "download_name", "path", "=", "join", "(", "get_downloads_dir", ...
Get the local path to a file in a MHCflurry download Parameters ----------- download_name : string filename : string Relative path within the download to the file of interest test_exists : boolean If True (default) throw an error telling the user how to download the data i...
[ "Get", "the", "local", "path", "to", "a", "file", "in", "a", "MHCflurry", "download" ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/downloads.py#L114-L141
train
openvax/mhcflurry
mhcflurry/downloads.py
configure
def configure(): """ Setup various global variables based on environment variables. """ global _DOWNLOADS_DIR global _CURRENT_RELEASE _CURRENT_RELEASE = None _DOWNLOADS_DIR = environ.get("MHCFLURRY_DOWNLOADS_DIR") if not _DOWNLOADS_DIR: metadata = get_downloads_metadata() ...
python
def configure(): """ Setup various global variables based on environment variables. """ global _DOWNLOADS_DIR global _CURRENT_RELEASE _CURRENT_RELEASE = None _DOWNLOADS_DIR = environ.get("MHCFLURRY_DOWNLOADS_DIR") if not _DOWNLOADS_DIR: metadata = get_downloads_metadata() ...
[ "def", "configure", "(", ")", ":", "global", "_DOWNLOADS_DIR", "global", "_CURRENT_RELEASE", "_CURRENT_RELEASE", "=", "None", "_DOWNLOADS_DIR", "=", "environ", ".", "get", "(", "\"MHCFLURRY_DOWNLOADS_DIR\"", ")", "if", "not", "_DOWNLOADS_DIR", ":", "metadata", "=", ...
Setup various global variables based on environment variables.
[ "Setup", "various", "global", "variables", "based", "on", "environment", "variables", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/downloads.py#L144-L179
train
openvax/mhcflurry
mhcflurry/parallelism.py
make_worker_pool
def make_worker_pool( processes=None, initializer=None, initializer_kwargs_per_process=None, max_tasks_per_worker=None): """ Convenience wrapper to create a multiprocessing.Pool. This function adds support for per-worker initializer arguments, which are not natively supp...
python
def make_worker_pool( processes=None, initializer=None, initializer_kwargs_per_process=None, max_tasks_per_worker=None): """ Convenience wrapper to create a multiprocessing.Pool. This function adds support for per-worker initializer arguments, which are not natively supp...
[ "def", "make_worker_pool", "(", "processes", "=", "None", ",", "initializer", "=", "None", ",", "initializer_kwargs_per_process", "=", "None", ",", "max_tasks_per_worker", "=", "None", ")", ":", "if", "not", "processes", ":", "processes", "=", "cpu_count", "(", ...
Convenience wrapper to create a multiprocessing.Pool. This function adds support for per-worker initializer arguments, which are not natively supported by the multiprocessing module. The motivation for this feature is to support allocating each worker to a (different) GPU. IMPLEMENTATION NOTE: ...
[ "Convenience", "wrapper", "to", "create", "a", "multiprocessing", ".", "Pool", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/parallelism.py#L115-L188
train
openvax/mhcflurry
mhcflurry/calibrate_percentile_ranks_command.py
calibrate_percentile_ranks
def calibrate_percentile_ranks(allele, predictor, peptides=None): """ Private helper function. """ global GLOBAL_DATA if peptides is None: peptides = GLOBAL_DATA["calibration_peptides"] predictor.calibrate_percentile_ranks( peptides=peptides, alleles=[allele]) return ...
python
def calibrate_percentile_ranks(allele, predictor, peptides=None): """ Private helper function. """ global GLOBAL_DATA if peptides is None: peptides = GLOBAL_DATA["calibration_peptides"] predictor.calibrate_percentile_ranks( peptides=peptides, alleles=[allele]) return ...
[ "def", "calibrate_percentile_ranks", "(", "allele", ",", "predictor", ",", "peptides", "=", "None", ")", ":", "global", "GLOBAL_DATA", "if", "peptides", "is", "None", ":", "peptides", "=", "GLOBAL_DATA", "[", "\"calibration_peptides\"", "]", "predictor", ".", "c...
Private helper function.
[ "Private", "helper", "function", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/calibrate_percentile_ranks_command.py#L140-L152
train
openvax/mhcflurry
mhcflurry/common.py
set_keras_backend
def set_keras_backend(backend=None, gpu_device_nums=None, num_threads=None): """ Configure Keras backend to use GPU or CPU. Only tensorflow is supported. Parameters ---------- backend : string, optional one of 'tensorflow-default', 'tensorflow-cpu', 'tensorflow-gpu' gpu_device_nums : l...
python
def set_keras_backend(backend=None, gpu_device_nums=None, num_threads=None): """ Configure Keras backend to use GPU or CPU. Only tensorflow is supported. Parameters ---------- backend : string, optional one of 'tensorflow-default', 'tensorflow-cpu', 'tensorflow-gpu' gpu_device_nums : l...
[ "def", "set_keras_backend", "(", "backend", "=", "None", ",", "gpu_device_nums", "=", "None", ",", "num_threads", "=", "None", ")", ":", "os", ".", "environ", "[", "\"KERAS_BACKEND\"", "]", "=", "\"tensorflow\"", "original_backend", "=", "backend", "if", "not"...
Configure Keras backend to use GPU or CPU. Only tensorflow is supported. Parameters ---------- backend : string, optional one of 'tensorflow-default', 'tensorflow-cpu', 'tensorflow-gpu' gpu_device_nums : list of int, optional GPU devices to potentially use num_threads : int, optio...
[ "Configure", "Keras", "backend", "to", "use", "GPU", "or", "CPU", ".", "Only", "tensorflow", "is", "supported", "." ]
deb7c1629111254b484a2711619eb2347db36524
https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/common.py#L14-L68
train
JonathanRaiman/pytreebank
pytreebank/labeled_trees.py
LabeledTree.uproot
def uproot(tree): """ Take a subranch of a tree and deep-copy the children of this subbranch into a new LabeledTree """ uprooted = tree.copy() uprooted.parent = None for child in tree.all_children(): uprooted.add_general_child(child) return upr...
python
def uproot(tree): """ Take a subranch of a tree and deep-copy the children of this subbranch into a new LabeledTree """ uprooted = tree.copy() uprooted.parent = None for child in tree.all_children(): uprooted.add_general_child(child) return upr...
[ "def", "uproot", "(", "tree", ")", ":", "uprooted", "=", "tree", ".", "copy", "(", ")", "uprooted", ".", "parent", "=", "None", "for", "child", "in", "tree", ".", "all_children", "(", ")", ":", "uprooted", ".", "add_general_child", "(", "child", ")", ...
Take a subranch of a tree and deep-copy the children of this subbranch into a new LabeledTree
[ "Take", "a", "subranch", "of", "a", "tree", "and", "deep", "-", "copy", "the", "children", "of", "this", "subbranch", "into", "a", "new", "LabeledTree" ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L35-L44
train
JonathanRaiman/pytreebank
pytreebank/labeled_trees.py
LabeledTree.copy
def copy(self): """ Deep Copy of a LabeledTree """ return LabeledTree( udepth = self.udepth, depth = self.depth, text = self.text, label = self.label, children = self.children.copy() if self.children != None else [], ...
python
def copy(self): """ Deep Copy of a LabeledTree """ return LabeledTree( udepth = self.udepth, depth = self.depth, text = self.text, label = self.label, children = self.children.copy() if self.children != None else [], ...
[ "def", "copy", "(", "self", ")", ":", "return", "LabeledTree", "(", "udepth", "=", "self", ".", "udepth", ",", "depth", "=", "self", ".", "depth", ",", "text", "=", "self", ".", "text", ",", "label", "=", "self", ".", "label", ",", "children", "=",...
Deep Copy of a LabeledTree
[ "Deep", "Copy", "of", "a", "LabeledTree" ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L60-L70
train
JonathanRaiman/pytreebank
pytreebank/labeled_trees.py
LabeledTree.add_child
def add_child(self, child): """ Adds a branch to the current tree. """ self.children.append(child) child.parent = self self.udepth = max([child.udepth for child in self.children]) + 1
python
def add_child(self, child): """ Adds a branch to the current tree. """ self.children.append(child) child.parent = self self.udepth = max([child.udepth for child in self.children]) + 1
[ "def", "add_child", "(", "self", ",", "child", ")", ":", "self", ".", "children", ".", "append", "(", "child", ")", "child", ".", "parent", "=", "self", "self", ".", "udepth", "=", "max", "(", "[", "child", ".", "udepth", "for", "child", "in", "sel...
Adds a branch to the current tree.
[ "Adds", "a", "branch", "to", "the", "current", "tree", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L72-L78
train
JonathanRaiman/pytreebank
pytreebank/labeled_trees.py
LabeledTree.lowercase
def lowercase(self): """ Lowercase all strings in this tree. Works recursively and in-place. """ if len(self.children) > 0: for child in self.children: child.lowercase() else: self.text = self.text.lower()
python
def lowercase(self): """ Lowercase all strings in this tree. Works recursively and in-place. """ if len(self.children) > 0: for child in self.children: child.lowercase() else: self.text = self.text.lower()
[ "def", "lowercase", "(", "self", ")", ":", "if", "len", "(", "self", ".", "children", ")", ">", "0", ":", "for", "child", "in", "self", ".", "children", ":", "child", ".", "lowercase", "(", ")", "else", ":", "self", ".", "text", "=", "self", ".",...
Lowercase all strings in this tree. Works recursively and in-place.
[ "Lowercase", "all", "strings", "in", "this", "tree", ".", "Works", "recursively", "and", "in", "-", "place", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L92-L101
train
JonathanRaiman/pytreebank
pytreebank/labeled_trees.py
LabeledTree.inject_visualization_javascript
def inject_visualization_javascript(tree_width=1200, tree_height=400, tree_node_radius=10): """ In an Ipython notebook, show SST trees using the same Javascript code as used by Jason Chuang's visualisations. """ from .javascript import insert_sentiment_markup insert_senti...
python
def inject_visualization_javascript(tree_width=1200, tree_height=400, tree_node_radius=10): """ In an Ipython notebook, show SST trees using the same Javascript code as used by Jason Chuang's visualisations. """ from .javascript import insert_sentiment_markup insert_senti...
[ "def", "inject_visualization_javascript", "(", "tree_width", "=", "1200", ",", "tree_height", "=", "400", ",", "tree_node_radius", "=", "10", ")", ":", "from", ".", "javascript", "import", "insert_sentiment_markup", "insert_sentiment_markup", "(", "tree_width", "=", ...
In an Ipython notebook, show SST trees using the same Javascript code as used by Jason Chuang's visualisations.
[ "In", "an", "Ipython", "notebook", "show", "SST", "trees", "using", "the", "same", "Javascript", "code", "as", "used", "by", "Jason", "Chuang", "s", "visualisations", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L195-L201
train
JonathanRaiman/pytreebank
pytreebank/parse.py
create_tree_from_string
def create_tree_from_string(line): """ Parse and convert a string representation of an example into a LabeledTree datastructure. Arguments: ---------- line : str, string version of the tree. Returns: -------- LabeledTree : parsed tree. """ depth = 0 curr...
python
def create_tree_from_string(line): """ Parse and convert a string representation of an example into a LabeledTree datastructure. Arguments: ---------- line : str, string version of the tree. Returns: -------- LabeledTree : parsed tree. """ depth = 0 curr...
[ "def", "create_tree_from_string", "(", "line", ")", ":", "depth", "=", "0", "current_word", "=", "\"\"", "root", "=", "None", "current_node", "=", "root", "for", "char", "in", "line", ":", "if", "char", "==", "'('", ":", "if", "current_node", "is", "not"...
Parse and convert a string representation of an example into a LabeledTree datastructure. Arguments: ---------- line : str, string version of the tree. Returns: -------- LabeledTree : parsed tree.
[ "Parse", "and", "convert", "a", "string", "representation", "of", "an", "example", "into", "a", "LabeledTree", "datastructure", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L49-L101
train
JonathanRaiman/pytreebank
pytreebank/parse.py
import_tree_corpus
def import_tree_corpus(path): """ Import a text file of treebank trees. Arguments: ---------- path : str, filename for tree corpus. Returns: -------- list<LabeledTree> : loaded examples. """ tree_list = LabeledTreeCorpus() with codecs.open(path, "r", "UTF-8") as f: ...
python
def import_tree_corpus(path): """ Import a text file of treebank trees. Arguments: ---------- path : str, filename for tree corpus. Returns: -------- list<LabeledTree> : loaded examples. """ tree_list = LabeledTreeCorpus() with codecs.open(path, "r", "UTF-8") as f: ...
[ "def", "import_tree_corpus", "(", "path", ")", ":", "tree_list", "=", "LabeledTreeCorpus", "(", ")", "with", "codecs", ".", "open", "(", "path", ",", "\"r\"", ",", "\"UTF-8\"", ")", "as", "f", ":", "for", "line", "in", "f", ":", "tree_list", ".", "appe...
Import a text file of treebank trees. Arguments: ---------- path : str, filename for tree corpus. Returns: -------- list<LabeledTree> : loaded examples.
[ "Import", "a", "text", "file", "of", "treebank", "trees", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L144-L160
train
JonathanRaiman/pytreebank
pytreebank/parse.py
load_sst
def load_sst(path=None, url='http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip'): """ Download and read in the Stanford Sentiment Treebank dataset into a dictionary with a 'train', 'dev', and 'test' keys. The dictionary keys point to lists of LabeledTrees. Arguments: ----...
python
def load_sst(path=None, url='http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip'): """ Download and read in the Stanford Sentiment Treebank dataset into a dictionary with a 'train', 'dev', and 'test' keys. The dictionary keys point to lists of LabeledTrees. Arguments: ----...
[ "def", "load_sst", "(", "path", "=", "None", ",", "url", "=", "'http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip'", ")", ":", "if", "path", "is", "None", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/stanford_sentiment_treebank/\"", ...
Download and read in the Stanford Sentiment Treebank dataset into a dictionary with a 'train', 'dev', and 'test' keys. The dictionary keys point to lists of LabeledTrees. Arguments: ---------- path : str, (optional defaults to ~/stanford_sentiment_treebank), directory where the corp...
[ "Download", "and", "read", "in", "the", "Stanford", "Sentiment", "Treebank", "dataset", "into", "a", "dictionary", "with", "a", "train", "dev", "and", "test", "keys", ".", "The", "dictionary", "keys", "point", "to", "lists", "of", "LabeledTrees", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L163-L187
train
JonathanRaiman/pytreebank
pytreebank/parse.py
LabeledTreeCorpus.labels
def labels(self): """ Construct a dictionary of string -> labels Returns: -------- OrderedDict<str, int> : string label pairs. """ labelings = OrderedDict() for tree in self: for label, line in tree.to_labeled_lines(): labe...
python
def labels(self): """ Construct a dictionary of string -> labels Returns: -------- OrderedDict<str, int> : string label pairs. """ labelings = OrderedDict() for tree in self: for label, line in tree.to_labeled_lines(): labe...
[ "def", "labels", "(", "self", ")", ":", "labelings", "=", "OrderedDict", "(", ")", "for", "tree", "in", "self", ":", "for", "label", ",", "line", "in", "tree", ".", "to_labeled_lines", "(", ")", ":", "labelings", "[", "line", "]", "=", "label", "retu...
Construct a dictionary of string -> labels Returns: -------- OrderedDict<str, int> : string label pairs.
[ "Construct", "a", "dictionary", "of", "string", "-", ">", "labels" ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L112-L124
train
JonathanRaiman/pytreebank
pytreebank/parse.py
LabeledTreeCorpus.to_file
def to_file(self, path, mode="w"): """ Save the corpus to a text file in the original format. Arguments: ---------- path : str, where to save the corpus. mode : str, how to open the file. """ with open(path, mode=mode) as f: fo...
python
def to_file(self, path, mode="w"): """ Save the corpus to a text file in the original format. Arguments: ---------- path : str, where to save the corpus. mode : str, how to open the file. """ with open(path, mode=mode) as f: fo...
[ "def", "to_file", "(", "self", ",", "path", ",", "mode", "=", "\"w\"", ")", ":", "with", "open", "(", "path", ",", "mode", "=", "mode", ")", "as", "f", ":", "for", "tree", "in", "self", ":", "for", "label", ",", "line", "in", "tree", ".", "to_l...
Save the corpus to a text file in the original format. Arguments: ---------- path : str, where to save the corpus. mode : str, how to open the file.
[ "Save", "the", "corpus", "to", "a", "text", "file", "in", "the", "original", "format", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L127-L140
train
JonathanRaiman/pytreebank
pytreebank/treelstm.py
import_tree_corpus
def import_tree_corpus(labels_path, parents_path, texts_path): """ Import dataset from the TreeLSTM data generation scrips. Arguments: ---------- labels_path : str, where are labels are stored (should be in data/sst/labels.txt). parents_path : str, where the parent relations...
python
def import_tree_corpus(labels_path, parents_path, texts_path): """ Import dataset from the TreeLSTM data generation scrips. Arguments: ---------- labels_path : str, where are labels are stored (should be in data/sst/labels.txt). parents_path : str, where the parent relations...
[ "def", "import_tree_corpus", "(", "labels_path", ",", "parents_path", ",", "texts_path", ")", ":", "with", "codecs", ".", "open", "(", "labels_path", ",", "\"r\"", ",", "\"UTF-8\"", ")", "as", "f", ":", "label_lines", "=", "f", ".", "readlines", "(", ")", ...
Import dataset from the TreeLSTM data generation scrips. Arguments: ---------- labels_path : str, where are labels are stored (should be in data/sst/labels.txt). parents_path : str, where the parent relationships are stored (should be in data/sst/parents.txt). te...
[ "Import", "dataset", "from", "the", "TreeLSTM", "data", "generation", "scrips", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/treelstm.py#L8-L42
train
JonathanRaiman/pytreebank
pytreebank/treelstm.py
assign_texts
def assign_texts(node, words, next_idx=0): """ Recursively assign the words to nodes by finding and assigning strings to the leaves of a tree in left to right order. """ if len(node.children) == 0: node.text = words[next_idx] return next_idx + 1 else: for child in nod...
python
def assign_texts(node, words, next_idx=0): """ Recursively assign the words to nodes by finding and assigning strings to the leaves of a tree in left to right order. """ if len(node.children) == 0: node.text = words[next_idx] return next_idx + 1 else: for child in nod...
[ "def", "assign_texts", "(", "node", ",", "words", ",", "next_idx", "=", "0", ")", ":", "if", "len", "(", "node", ".", "children", ")", "==", "0", ":", "node", ".", "text", "=", "words", "[", "next_idx", "]", "return", "next_idx", "+", "1", "else", ...
Recursively assign the words to nodes by finding and assigning strings to the leaves of a tree in left to right order.
[ "Recursively", "assign", "the", "words", "to", "nodes", "by", "finding", "and", "assigning", "strings", "to", "the", "leaves", "of", "a", "tree", "in", "left", "to", "right", "order", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/treelstm.py#L44-L56
train
JonathanRaiman/pytreebank
pytreebank/treelstm.py
read_tree
def read_tree(parents, labels, words): """ Take as input a list of integers for parents and labels, along with a list of words, and reconstruct a LabeledTree. """ trees = {} root = None for i in range(1, len(parents) + 1): if not i in trees and parents[i - 1] != - 1: ...
python
def read_tree(parents, labels, words): """ Take as input a list of integers for parents and labels, along with a list of words, and reconstruct a LabeledTree. """ trees = {} root = None for i in range(1, len(parents) + 1): if not i in trees and parents[i - 1] != - 1: ...
[ "def", "read_tree", "(", "parents", ",", "labels", ",", "words", ")", ":", "trees", "=", "{", "}", "root", "=", "None", "for", "i", "in", "range", "(", "1", ",", "len", "(", "parents", ")", "+", "1", ")", ":", "if", "not", "i", "in", "trees", ...
Take as input a list of integers for parents and labels, along with a list of words, and reconstruct a LabeledTree.
[ "Take", "as", "input", "a", "list", "of", "integers", "for", "parents", "and", "labels", "along", "with", "a", "list", "of", "words", "and", "reconstruct", "a", "LabeledTree", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/treelstm.py#L58-L89
train
GiulioRossetti/ndlib
ndlib/models/opinions/CognitiveOpDynModel.py
CognitiveOpDynModel.set_initial_status
def set_initial_status(self, configuration=None): """ Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. Generates random node profiles. """ super(CognitiveOpDynModel, self).set_initial_status(configuration) ...
python
def set_initial_status(self, configuration=None): """ Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. Generates random node profiles. """ super(CognitiveOpDynModel, self).set_initial_status(configuration) ...
[ "def", "set_initial_status", "(", "self", ",", "configuration", "=", "None", ")", ":", "super", "(", "CognitiveOpDynModel", ",", "self", ")", ".", "set_initial_status", "(", "configuration", ")", "for", "node", "in", "self", ".", "status", ":", "self", ".", ...
Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. Generates random node profiles.
[ "Override", "behaviour", "of", "methods", "in", "class", "DiffusionModel", ".", "Overwrites", "initial", "status", "using", "random", "real", "values", ".", "Generates", "random", "node", "profiles", "." ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/CognitiveOpDynModel.py#L92-L133
train
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_node_configuration
def add_node_configuration(self, param_name, node_id, param_value): """ Set a parameter for a given node :param param_name: parameter identifier (as specified by the chosen model) :param node_id: node identifier :param param_value: parameter value """ if param_na...
python
def add_node_configuration(self, param_name, node_id, param_value): """ Set a parameter for a given node :param param_name: parameter identifier (as specified by the chosen model) :param node_id: node identifier :param param_value: parameter value """ if param_na...
[ "def", "add_node_configuration", "(", "self", ",", "param_name", ",", "node_id", ",", "param_value", ")", ":", "if", "param_name", "not", "in", "self", ".", "config", "[", "'nodes'", "]", ":", "self", ".", "config", "[", "'nodes'", "]", "[", "param_name", ...
Set a parameter for a given node :param param_name: parameter identifier (as specified by the chosen model) :param node_id: node identifier :param param_value: parameter value
[ "Set", "a", "parameter", "for", "a", "given", "node" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L72-L83
train
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_node_set_configuration
def add_node_set_configuration(self, param_name, node_to_value): """ Set Nodes parameter :param param_name: parameter identifier (as specified by the chosen model) :param node_to_value: dictionary mapping each node a parameter value """ for nid, val in future.utils.iteri...
python
def add_node_set_configuration(self, param_name, node_to_value): """ Set Nodes parameter :param param_name: parameter identifier (as specified by the chosen model) :param node_to_value: dictionary mapping each node a parameter value """ for nid, val in future.utils.iteri...
[ "def", "add_node_set_configuration", "(", "self", ",", "param_name", ",", "node_to_value", ")", ":", "for", "nid", ",", "val", "in", "future", ".", "utils", ".", "iteritems", "(", "node_to_value", ")", ":", "self", ".", "add_node_configuration", "(", "param_na...
Set Nodes parameter :param param_name: parameter identifier (as specified by the chosen model) :param node_to_value: dictionary mapping each node a parameter value
[ "Set", "Nodes", "parameter" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L85-L93
train
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_edge_configuration
def add_edge_configuration(self, param_name, edge, param_value): """ Set a parameter for a given edge :param param_name: parameter identifier (as specified by the chosen model) :param edge: edge identifier :param param_value: parameter value """ if param_name not...
python
def add_edge_configuration(self, param_name, edge, param_value): """ Set a parameter for a given edge :param param_name: parameter identifier (as specified by the chosen model) :param edge: edge identifier :param param_value: parameter value """ if param_name not...
[ "def", "add_edge_configuration", "(", "self", ",", "param_name", ",", "edge", ",", "param_value", ")", ":", "if", "param_name", "not", "in", "self", ".", "config", "[", "'edges'", "]", ":", "self", ".", "config", "[", "'edges'", "]", "[", "param_name", "...
Set a parameter for a given edge :param param_name: parameter identifier (as specified by the chosen model) :param edge: edge identifier :param param_value: parameter value
[ "Set", "a", "parameter", "for", "a", "given", "edge" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L95-L106
train
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_edge_set_configuration
def add_edge_set_configuration(self, param_name, edge_to_value): """ Set Edges parameter :param param_name: parameter identifier (as specified by the chosen model) :param edge_to_value: dictionary mapping each edge a parameter value """ for edge, val in future.utils.iter...
python
def add_edge_set_configuration(self, param_name, edge_to_value): """ Set Edges parameter :param param_name: parameter identifier (as specified by the chosen model) :param edge_to_value: dictionary mapping each edge a parameter value """ for edge, val in future.utils.iter...
[ "def", "add_edge_set_configuration", "(", "self", ",", "param_name", ",", "edge_to_value", ")", ":", "for", "edge", ",", "val", "in", "future", ".", "utils", ".", "iteritems", "(", "edge_to_value", ")", ":", "self", ".", "add_edge_configuration", "(", "param_n...
Set Edges parameter :param param_name: parameter identifier (as specified by the chosen model) :param edge_to_value: dictionary mapping each edge a parameter value
[ "Set", "Edges", "parameter" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L108-L116
train
GiulioRossetti/ndlib
ndlib/utils.py
multi_runs
def multi_runs(model, execution_number=1, iteration_number=50, infection_sets=None, nprocesses=multiprocessing.cpu_count()): """ Multiple executions of a given model varying the initial set of infected nodes :param model: a configured diffusion model :param execution_number: number of in...
python
def multi_runs(model, execution_number=1, iteration_number=50, infection_sets=None, nprocesses=multiprocessing.cpu_count()): """ Multiple executions of a given model varying the initial set of infected nodes :param model: a configured diffusion model :param execution_number: number of in...
[ "def", "multi_runs", "(", "model", ",", "execution_number", "=", "1", ",", "iteration_number", "=", "50", ",", "infection_sets", "=", "None", ",", "nprocesses", "=", "multiprocessing", ".", "cpu_count", "(", ")", ")", ":", "if", "nprocesses", ">", "multiproc...
Multiple executions of a given model varying the initial set of infected nodes :param model: a configured diffusion model :param execution_number: number of instantiations :param iteration_number: number of iterations per execution :param infection_sets: predefined set of infected nodes sets :param...
[ "Multiple", "executions", "of", "a", "given", "model", "varying", "the", "initial", "set", "of", "infected", "nodes" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/utils.py#L15-L58
train
GiulioRossetti/ndlib
ndlib/utils.py
__execute
def __execute(model, iteration_number): """ Execute a simulation model :param model: a configured diffusion model :param iteration_number: number of iterations :return: computed trends """ iterations = model.iteration_bunch(iteration_number, False) trends = model.build_trends(iterations...
python
def __execute(model, iteration_number): """ Execute a simulation model :param model: a configured diffusion model :param iteration_number: number of iterations :return: computed trends """ iterations = model.iteration_bunch(iteration_number, False) trends = model.build_trends(iterations...
[ "def", "__execute", "(", "model", ",", "iteration_number", ")", ":", "iterations", "=", "model", ".", "iteration_bunch", "(", "iteration_number", ",", "False", ")", "trends", "=", "model", ".", "build_trends", "(", "iterations", ")", "[", "0", "]", "del", ...
Execute a simulation model :param model: a configured diffusion model :param iteration_number: number of iterations :return: computed trends
[ "Execute", "a", "simulation", "model" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/utils.py#L61-L73
train
GiulioRossetti/ndlib
ndlib/models/opinions/AlgorithmicBiasModel.py
AlgorithmicBiasModel.set_initial_status
def set_initial_status(self, configuration=None): """ Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. """ super(AlgorithmicBiasModel, self).set_initial_status(configuration) # set node status for node in ...
python
def set_initial_status(self, configuration=None): """ Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. """ super(AlgorithmicBiasModel, self).set_initial_status(configuration) # set node status for node in ...
[ "def", "set_initial_status", "(", "self", ",", "configuration", "=", "None", ")", ":", "super", "(", "AlgorithmicBiasModel", ",", "self", ")", ".", "set_initial_status", "(", "configuration", ")", "for", "node", "in", "self", ".", "status", ":", "self", ".",...
Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values.
[ "Override", "behaviour", "of", "methods", "in", "class", "DiffusionModel", ".", "Overwrites", "initial", "status", "using", "random", "real", "values", "." ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/AlgorithmicBiasModel.py#L54-L64
train
HearthSim/python-hearthstone
hearthstone/entities.py
Player.names
def names(self): """ Returns the player's name and real name. Returns two empty strings if the player is unknown. AI real name is always an empty string. """ if self.name == self.UNKNOWN_HUMAN_PLAYER: return "", "" if not self.is_ai and " " in self.name: return "", self.name return self.name, ""
python
def names(self): """ Returns the player's name and real name. Returns two empty strings if the player is unknown. AI real name is always an empty string. """ if self.name == self.UNKNOWN_HUMAN_PLAYER: return "", "" if not self.is_ai and " " in self.name: return "", self.name return self.name, ""
[ "def", "names", "(", "self", ")", ":", "if", "self", ".", "name", "==", "self", ".", "UNKNOWN_HUMAN_PLAYER", ":", "return", "\"\"", ",", "\"\"", "if", "not", "self", ".", "is_ai", "and", "\" \"", "in", "self", ".", "name", ":", "return", "\"\"", ",",...
Returns the player's name and real name. Returns two empty strings if the player is unknown. AI real name is always an empty string.
[ "Returns", "the", "player", "s", "name", "and", "real", "name", ".", "Returns", "two", "empty", "strings", "if", "the", "player", "is", "unknown", ".", "AI", "real", "name", "is", "always", "an", "empty", "string", "." ]
3690b714248b578dcbba8a492bf228ff09a6aeaf
https://github.com/HearthSim/python-hearthstone/blob/3690b714248b578dcbba8a492bf228ff09a6aeaf/hearthstone/entities.py#L147-L159
train
scikit-hep/root_pandas
root_pandas/readwrite.py
_getgroup
def _getgroup(string, depth): """ Get a group from the string, where group is a list of all the comma separated substrings up to the next '}' char or the brace enclosed substring if there is no comma """ out, comma = [], False while string: items, string = _getitem(string, depth) ...
python
def _getgroup(string, depth): """ Get a group from the string, where group is a list of all the comma separated substrings up to the next '}' char or the brace enclosed substring if there is no comma """ out, comma = [], False while string: items, string = _getitem(string, depth) ...
[ "def", "_getgroup", "(", "string", ",", "depth", ")", ":", "out", ",", "comma", "=", "[", "]", ",", "False", "while", "string", ":", "items", ",", "string", "=", "_getitem", "(", "string", ",", "depth", ")", "if", "not", "string", ":", "break", "ou...
Get a group from the string, where group is a list of all the comma separated substrings up to the next '}' char or the brace enclosed substring if there is no comma
[ "Get", "a", "group", "from", "the", "string", "where", "group", "is", "a", "list", "of", "all", "the", "comma", "separated", "substrings", "up", "to", "the", "next", "}", "char", "or", "the", "brace", "enclosed", "substring", "if", "there", "is", "no", ...
57991a4feaeb9213575cfba7a369fc05cc0d846b
https://github.com/scikit-hep/root_pandas/blob/57991a4feaeb9213575cfba7a369fc05cc0d846b/root_pandas/readwrite.py#L55-L77
train
scikit-hep/root_pandas
root_pandas/readwrite.py
filter_noexpand_columns
def filter_noexpand_columns(columns): """Return columns not containing and containing the noexpand prefix. Parameters ---------- columns: sequence of str A sequence of strings to be split Returns ------- Two lists, the first containing strings without the noexpand prefix, the ...
python
def filter_noexpand_columns(columns): """Return columns not containing and containing the noexpand prefix. Parameters ---------- columns: sequence of str A sequence of strings to be split Returns ------- Two lists, the first containing strings without the noexpand prefix, the ...
[ "def", "filter_noexpand_columns", "(", "columns", ")", ":", "prefix_len", "=", "len", "(", "NOEXPAND_PREFIX", ")", "noexpand", "=", "[", "c", "[", "prefix_len", ":", "]", "for", "c", "in", "columns", "if", "c", ".", "startswith", "(", "NOEXPAND_PREFIX", ")...
Return columns not containing and containing the noexpand prefix. Parameters ---------- columns: sequence of str A sequence of strings to be split Returns ------- Two lists, the first containing strings without the noexpand prefix, the second containing those that do with the pre...
[ "Return", "columns", "not", "containing", "and", "containing", "the", "noexpand", "prefix", "." ]
57991a4feaeb9213575cfba7a369fc05cc0d846b
https://github.com/scikit-hep/root_pandas/blob/57991a4feaeb9213575cfba7a369fc05cc0d846b/root_pandas/readwrite.py#L117-L133
train
scikit-hep/root_pandas
root_pandas/readwrite.py
to_root
def to_root(df, path, key='my_ttree', mode='w', store_index=True, *args, **kwargs): """ Write DataFrame to a ROOT file. Parameters ---------- path: string File path to new ROOT file (will be overwritten) key: string Name of tree that the DataFrame will be saved as mode: stri...
python
def to_root(df, path, key='my_ttree', mode='w', store_index=True, *args, **kwargs): """ Write DataFrame to a ROOT file. Parameters ---------- path: string File path to new ROOT file (will be overwritten) key: string Name of tree that the DataFrame will be saved as mode: stri...
[ "def", "to_root", "(", "df", ",", "path", ",", "key", "=", "'my_ttree'", ",", "mode", "=", "'w'", ",", "store_index", "=", "True", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "mode", "==", "'a'", ":", "mode", "=", "'update'", "elif", "...
Write DataFrame to a ROOT file. Parameters ---------- path: string File path to new ROOT file (will be overwritten) key: string Name of tree that the DataFrame will be saved as mode: string, {'w', 'a'} Mode that the file should be opened in (default: 'w') store_index: bo...
[ "Write", "DataFrame", "to", "a", "ROOT", "file", "." ]
57991a4feaeb9213575cfba7a369fc05cc0d846b
https://github.com/scikit-hep/root_pandas/blob/57991a4feaeb9213575cfba7a369fc05cc0d846b/root_pandas/readwrite.py#L334-L417
train
MisterY/gnucash-portfolio
gnucash_portfolio/reports/security_info.py
SecurityInfoReport.run
def run(self, symbol: str) -> SecurityDetailsViewModel: """ Loads the model for security details """ from pydatum import Datum svc = self._svc sec_agg = svc.securities.get_aggregate_for_symbol(symbol) model = SecurityDetailsViewModel() model.symbol = sec_agg.security.n...
python
def run(self, symbol: str) -> SecurityDetailsViewModel: """ Loads the model for security details """ from pydatum import Datum svc = self._svc sec_agg = svc.securities.get_aggregate_for_symbol(symbol) model = SecurityDetailsViewModel() model.symbol = sec_agg.security.n...
[ "def", "run", "(", "self", ",", "symbol", ":", "str", ")", "->", "SecurityDetailsViewModel", ":", "from", "pydatum", "import", "Datum", "svc", "=", "self", ".", "_svc", "sec_agg", "=", "svc", ".", "securities", ".", "get_aggregate_for_symbol", "(", "symbol",...
Loads the model for security details
[ "Loads", "the", "model", "for", "security", "details" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/reports/security_info.py#L15-L93
train
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
handle_friday
def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum): """ Extracted the calculation for when the next_day is Friday """ assert isinstance(next_date, Datum) assert isinstance(start_date, Datum) # Starting from line 220. tmp_sat = next_date.clone() tmp_sat.add_days(1) ...
python
def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum): """ Extracted the calculation for when the next_day is Friday """ assert isinstance(next_date, Datum) assert isinstance(start_date, Datum) # Starting from line 220. tmp_sat = next_date.clone() tmp_sat.add_days(1) ...
[ "def", "handle_friday", "(", "next_date", ":", "Datum", ",", "period", ":", "str", ",", "mult", ":", "int", ",", "start_date", ":", "Datum", ")", ":", "assert", "isinstance", "(", "next_date", ",", "Datum", ")", "assert", "isinstance", "(", "start_date", ...
Extracted the calculation for when the next_day is Friday
[ "Extracted", "the", "calculation", "for", "when", "the", "next_day", "is", "Friday" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L173-L212
train
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
ScheduledTxAggregate.get_next_occurrence
def get_next_occurrence(self) -> date: """ Returns the next occurrence date for transaction """ result = get_next_occurrence(self.transaction) assert isinstance(result, date) return result
python
def get_next_occurrence(self) -> date: """ Returns the next occurrence date for transaction """ result = get_next_occurrence(self.transaction) assert isinstance(result, date) return result
[ "def", "get_next_occurrence", "(", "self", ")", "->", "date", ":", "result", "=", "get_next_occurrence", "(", "self", ".", "transaction", ")", "assert", "isinstance", "(", "result", ",", "date", ")", "return", "result" ]
Returns the next occurrence date for transaction
[ "Returns", "the", "next", "occurrence", "date", "for", "transaction" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L222-L226
train
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
ScheduledTxsAggregate.get_enabled
def get_enabled(self) -> List[ScheduledTransaction]: """ Returns only enabled scheduled transactions """ query = ( self.query .filter(ScheduledTransaction.enabled == True) ) return query.all()
python
def get_enabled(self) -> List[ScheduledTransaction]: """ Returns only enabled scheduled transactions """ query = ( self.query .filter(ScheduledTransaction.enabled == True) ) return query.all()
[ "def", "get_enabled", "(", "self", ")", "->", "List", "[", "ScheduledTransaction", "]", ":", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "ScheduledTransaction", ".", "enabled", "==", "True", ")", ")", "return", "query", ".", "all", "(", ...
Returns only enabled scheduled transactions
[ "Returns", "only", "enabled", "scheduled", "transactions" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L254-L260
train
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
ScheduledTxsAggregate.get_by_id
def get_by_id(self, tx_id: str) -> ScheduledTransaction: """ Fetches a tx by id """ return self.query.filter(ScheduledTransaction.guid == tx_id).first()
python
def get_by_id(self, tx_id: str) -> ScheduledTransaction: """ Fetches a tx by id """ return self.query.filter(ScheduledTransaction.guid == tx_id).first()
[ "def", "get_by_id", "(", "self", ",", "tx_id", ":", "str", ")", "->", "ScheduledTransaction", ":", "return", "self", ".", "query", ".", "filter", "(", "ScheduledTransaction", ".", "guid", "==", "tx_id", ")", ".", "first", "(", ")" ]
Fetches a tx by id
[ "Fetches", "a", "tx", "by", "id" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L262-L264
train
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
ScheduledTxsAggregate.get_aggregate_by_id
def get_aggregate_by_id(self, tx_id: str) -> ScheduledTxAggregate: """ Creates an aggregate for single entity """ tran = self.get_by_id(tx_id) return self.get_aggregate_for(tran)
python
def get_aggregate_by_id(self, tx_id: str) -> ScheduledTxAggregate: """ Creates an aggregate for single entity """ tran = self.get_by_id(tx_id) return self.get_aggregate_for(tran)
[ "def", "get_aggregate_by_id", "(", "self", ",", "tx_id", ":", "str", ")", "->", "ScheduledTxAggregate", ":", "tran", "=", "self", ".", "get_by_id", "(", "tx_id", ")", "return", "self", ".", "get_aggregate_for", "(", "tran", ")" ]
Creates an aggregate for single entity
[ "Creates", "an", "aggregate", "for", "single", "entity" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L270-L273
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_avg_price_stat
def get_avg_price_stat(self) -> Decimal: """ Calculates the statistical average price for the security, by averaging only the prices paid. Very simple first implementation. """ avg_price = Decimal(0) price_total = Decimal(0) price_count = 0 for account i...
python
def get_avg_price_stat(self) -> Decimal: """ Calculates the statistical average price for the security, by averaging only the prices paid. Very simple first implementation. """ avg_price = Decimal(0) price_total = Decimal(0) price_count = 0 for account i...
[ "def", "get_avg_price_stat", "(", "self", ")", "->", "Decimal", ":", "avg_price", "=", "Decimal", "(", "0", ")", "price_total", "=", "Decimal", "(", "0", ")", "price_count", "=", "0", "for", "account", "in", "self", ".", "security", ".", "accounts", ":",...
Calculates the statistical average price for the security, by averaging only the prices paid. Very simple first implementation.
[ "Calculates", "the", "statistical", "average", "price", "for", "the", "security", "by", "averaging", "only", "the", "prices", "paid", ".", "Very", "simple", "first", "implementation", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L41-L67
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_avg_price_fifo
def get_avg_price_fifo(self) -> Decimal: """ Calculates the average price paid for the security. security = Commodity Returns Decimal value. """ balance = self.get_quantity() if not balance: return Decimal(0) paid = Decimal(0) accounts...
python
def get_avg_price_fifo(self) -> Decimal: """ Calculates the average price paid for the security. security = Commodity Returns Decimal value. """ balance = self.get_quantity() if not balance: return Decimal(0) paid = Decimal(0) accounts...
[ "def", "get_avg_price_fifo", "(", "self", ")", "->", "Decimal", ":", "balance", "=", "self", ".", "get_quantity", "(", ")", "if", "not", "balance", ":", "return", "Decimal", "(", "0", ")", "paid", "=", "Decimal", "(", "0", ")", "accounts", "=", "self",...
Calculates the average price paid for the security. security = Commodity Returns Decimal value.
[ "Calculates", "the", "average", "price", "paid", "for", "the", "security", ".", "security", "=", "Commodity", "Returns", "Decimal", "value", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L69-L89
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_available_splits_for_account
def get_available_splits_for_account(self, account: Account) -> List[Split]: """ Returns all unused splits in the account. Used for the calculation of avg.price. The split that has been partially used will have its quantity reduced to available quantity only. """ available_splits = [] ...
python
def get_available_splits_for_account(self, account: Account) -> List[Split]: """ Returns all unused splits in the account. Used for the calculation of avg.price. The split that has been partially used will have its quantity reduced to available quantity only. """ available_splits = [] ...
[ "def", "get_available_splits_for_account", "(", "self", ",", "account", ":", "Account", ")", "->", "List", "[", "Split", "]", ":", "available_splits", "=", "[", "]", "query", "=", "(", "self", ".", "get_splits_query", "(", ")", ".", "filter", "(", "Split",...
Returns all unused splits in the account. Used for the calculation of avg.price. The split that has been partially used will have its quantity reduced to available quantity only.
[ "Returns", "all", "unused", "splits", "in", "the", "account", ".", "Used", "for", "the", "calculation", "of", "avg", ".", "price", ".", "The", "split", "that", "has", "been", "partially", "used", "will", "have", "its", "quantity", "reduced", "to", "availab...
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L91-L133
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_num_shares
def get_num_shares(self) -> Decimal: """ Returns the number of shares at this time """ from pydatum import Datum today = Datum().today() return self.get_num_shares_on(today)
python
def get_num_shares(self) -> Decimal: """ Returns the number of shares at this time """ from pydatum import Datum today = Datum().today() return self.get_num_shares_on(today)
[ "def", "get_num_shares", "(", "self", ")", "->", "Decimal", ":", "from", "pydatum", "import", "Datum", "today", "=", "Datum", "(", ")", ".", "today", "(", ")", "return", "self", ".", "get_num_shares_on", "(", "today", ")" ]
Returns the number of shares at this time
[ "Returns", "the", "number", "of", "shares", "at", "this", "time" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L135-L139
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_last_available_price
def get_last_available_price(self) -> PriceModel: """ Finds the last available price for security. Uses PriceDb. """ price_db = PriceDbApplication() symbol = SecuritySymbol(self.security.namespace, self.security.mnemonic) result = price_db.get_latest_price(symbol) return result
python
def get_last_available_price(self) -> PriceModel: """ Finds the last available price for security. Uses PriceDb. """ price_db = PriceDbApplication() symbol = SecuritySymbol(self.security.namespace, self.security.mnemonic) result = price_db.get_latest_price(symbol) return result
[ "def", "get_last_available_price", "(", "self", ")", "->", "PriceModel", ":", "price_db", "=", "PriceDbApplication", "(", ")", "symbol", "=", "SecuritySymbol", "(", "self", ".", "security", ".", "namespace", ",", "self", ".", "security", ".", "mnemonic", ")", ...
Finds the last available price for security. Uses PriceDb.
[ "Finds", "the", "last", "available", "price", "for", "security", ".", "Uses", "PriceDb", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L154-L159
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.__get_holding_accounts_query
def __get_holding_accounts_query(self): """ Returns all holding accounts, except Trading accounts. """ query = ( self.book.session.query(Account) .filter(Account.commodity == self.security) .filter(Account.type != AccountType.trading.value) ) # generic...
python
def __get_holding_accounts_query(self): """ Returns all holding accounts, except Trading accounts. """ query = ( self.book.session.query(Account) .filter(Account.commodity == self.security) .filter(Account.type != AccountType.trading.value) ) # generic...
[ "def", "__get_holding_accounts_query", "(", "self", ")", ":", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Account", ")", ".", "filter", "(", "Account", ".", "commodity", "==", "self", ".", "security", ")", ".", "filter", ...
Returns all holding accounts, except Trading accounts.
[ "Returns", "all", "holding", "accounts", "except", "Trading", "accounts", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L180-L188
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_income_accounts
def get_income_accounts(self) -> List[Account]: """ Returns all income accounts for this security. Income accounts are accounts not under Trading, expressed in currency, and having the same name as the mnemonic. They should be under Assets but this requires a recursive SQL query....
python
def get_income_accounts(self) -> List[Account]: """ Returns all income accounts for this security. Income accounts are accounts not under Trading, expressed in currency, and having the same name as the mnemonic. They should be under Assets but this requires a recursive SQL query....
[ "def", "get_income_accounts", "(", "self", ")", "->", "List", "[", "Account", "]", ":", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Account", ")", ".", "join", "(", "Commodity", ")", ".", "filter", "(", "Account", ".",...
Returns all income accounts for this security. Income accounts are accounts not under Trading, expressed in currency, and having the same name as the mnemonic. They should be under Assets but this requires a recursive SQL query.
[ "Returns", "all", "income", "accounts", "for", "this", "security", ".", "Income", "accounts", "are", "accounts", "not", "under", "Trading", "expressed", "in", "currency", "and", "having", "the", "same", "name", "as", "the", "mnemonic", ".", "They", "should", ...
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L190-L214
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_income_total
def get_income_total(self) -> Decimal: """ Sum of all income = sum of balances of all income accounts. """ accounts = self.get_income_accounts() # log(DEBUG, "income accounts: %s", accounts) income = Decimal(0) for acct in accounts: income += acct.get_balance() ...
python
def get_income_total(self) -> Decimal: """ Sum of all income = sum of balances of all income accounts. """ accounts = self.get_income_accounts() # log(DEBUG, "income accounts: %s", accounts) income = Decimal(0) for acct in accounts: income += acct.get_balance() ...
[ "def", "get_income_total", "(", "self", ")", "->", "Decimal", ":", "accounts", "=", "self", ".", "get_income_accounts", "(", ")", "income", "=", "Decimal", "(", "0", ")", "for", "acct", "in", "accounts", ":", "income", "+=", "acct", ".", "get_balance", "...
Sum of all income = sum of balances of all income accounts.
[ "Sum", "of", "all", "income", "=", "sum", "of", "balances", "of", "all", "income", "accounts", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L216-L223
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_income_in_period
def get_income_in_period(self, start: datetime, end: datetime) -> Decimal: """ Returns all income in the given period """ accounts = self.get_income_accounts() income = Decimal(0) for acct in accounts: acc_agg = AccountAggregate(self.book, acct) acc_bal = acc_agg....
python
def get_income_in_period(self, start: datetime, end: datetime) -> Decimal: """ Returns all income in the given period """ accounts = self.get_income_accounts() income = Decimal(0) for acct in accounts: acc_agg = AccountAggregate(self.book, acct) acc_bal = acc_agg....
[ "def", "get_income_in_period", "(", "self", ",", "start", ":", "datetime", ",", "end", ":", "datetime", ")", "->", "Decimal", ":", "accounts", "=", "self", ".", "get_income_accounts", "(", ")", "income", "=", "Decimal", "(", "0", ")", "for", "acct", "in"...
Returns all income in the given period
[ "Returns", "all", "income", "in", "the", "given", "period" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L225-L234
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_prices
def get_prices(self) -> List[PriceModel]: """ Returns all available prices for security """ # return self.security.prices.order_by(Price.date) from pricedb.dal import Price pricedb = PriceDbApplication() repo = pricedb.get_price_repository() query = (repo.query(Price) ...
python
def get_prices(self) -> List[PriceModel]: """ Returns all available prices for security """ # return self.security.prices.order_by(Price.date) from pricedb.dal import Price pricedb = PriceDbApplication() repo = pricedb.get_price_repository() query = (repo.query(Price) ...
[ "def", "get_prices", "(", "self", ")", "->", "List", "[", "PriceModel", "]", ":", "from", "pricedb", ".", "dal", "import", "Price", "pricedb", "=", "PriceDbApplication", "(", ")", "repo", "=", "pricedb", ".", "get_price_repository", "(", ")", "query", "=",...
Returns all available prices for security
[ "Returns", "all", "available", "prices", "for", "security" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L236-L248
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_quantity
def get_quantity(self) -> Decimal: """ Returns the number of shares for the given security. It gets the number from all the accounts in the book. """ from pydatum import Datum # Use today's date but reset hour and lower. today = Datum() today.today() ...
python
def get_quantity(self) -> Decimal: """ Returns the number of shares for the given security. It gets the number from all the accounts in the book. """ from pydatum import Datum # Use today's date but reset hour and lower. today = Datum() today.today() ...
[ "def", "get_quantity", "(", "self", ")", "->", "Decimal", ":", "from", "pydatum", "import", "Datum", "today", "=", "Datum", "(", ")", "today", ".", "today", "(", ")", "today", ".", "end_of_day", "(", ")", "return", "self", ".", "get_num_shares_on", "(", ...
Returns the number of shares for the given security. It gets the number from all the accounts in the book.
[ "Returns", "the", "number", "of", "shares", "for", "the", "given", "security", ".", "It", "gets", "the", "number", "from", "all", "the", "accounts", "in", "the", "book", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L250-L260
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_splits_query
def get_splits_query(self): """ Returns the query for all splits for this security """ query = ( self.book.session.query(Split) .join(Account) .filter(Account.type != AccountType.trading.value) .filter(Account.commodity_guid == self.security.guid) ...
python
def get_splits_query(self): """ Returns the query for all splits for this security """ query = ( self.book.session.query(Split) .join(Account) .filter(Account.type != AccountType.trading.value) .filter(Account.commodity_guid == self.security.guid) ...
[ "def", "get_splits_query", "(", "self", ")", ":", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Split", ")", ".", "join", "(", "Account", ")", ".", "filter", "(", "Account", ".", "type", "!=", "AccountType", ".", "tradin...
Returns the query for all splits for this security
[ "Returns", "the", "query", "for", "all", "splits", "for", "this", "security" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L262-L270
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_total_paid
def get_total_paid(self) -> Decimal: """ Returns the total amount paid, in currency, for the stocks owned """ query = ( self.get_splits_query() ) splits = query.all() total = Decimal(0) for split in splits: total += split.value return tot...
python
def get_total_paid(self) -> Decimal: """ Returns the total amount paid, in currency, for the stocks owned """ query = ( self.get_splits_query() ) splits = query.all() total = Decimal(0) for split in splits: total += split.value return tot...
[ "def", "get_total_paid", "(", "self", ")", "->", "Decimal", ":", "query", "=", "(", "self", ".", "get_splits_query", "(", ")", ")", "splits", "=", "query", ".", "all", "(", ")", "total", "=", "Decimal", "(", "0", ")", "for", "split", "in", "splits", ...
Returns the total amount paid, in currency, for the stocks owned
[ "Returns", "the", "total", "amount", "paid", "in", "currency", "for", "the", "stocks", "owned" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L272-L283
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_total_paid_for_remaining_stock
def get_total_paid_for_remaining_stock(self) -> Decimal: """ Returns the amount paid only for the remaining stock """ paid = Decimal(0) accounts = self.get_holding_accounts() for acc in accounts: splits = self.get_available_splits_for_account(acc) paid += sum(spl...
python
def get_total_paid_for_remaining_stock(self) -> Decimal: """ Returns the amount paid only for the remaining stock """ paid = Decimal(0) accounts = self.get_holding_accounts() for acc in accounts: splits = self.get_available_splits_for_account(acc) paid += sum(spl...
[ "def", "get_total_paid_for_remaining_stock", "(", "self", ")", "->", "Decimal", ":", "paid", "=", "Decimal", "(", "0", ")", "accounts", "=", "self", ".", "get_holding_accounts", "(", ")", "for", "acc", "in", "accounts", ":", "splits", "=", "self", ".", "ge...
Returns the amount paid only for the remaining stock
[ "Returns", "the", "amount", "paid", "only", "for", "the", "remaining", "stock" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L285-L293
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_value
def get_value(self) -> Decimal: """ Returns the current value of stocks """ quantity = self.get_quantity() price = self.get_last_available_price() if not price: # raise ValueError("no price found for", self.full_symbol) return Decimal(0) value = quantity ...
python
def get_value(self) -> Decimal: """ Returns the current value of stocks """ quantity = self.get_quantity() price = self.get_last_available_price() if not price: # raise ValueError("no price found for", self.full_symbol) return Decimal(0) value = quantity ...
[ "def", "get_value", "(", "self", ")", "->", "Decimal", ":", "quantity", "=", "self", ".", "get_quantity", "(", ")", "price", "=", "self", ".", "get_last_available_price", "(", ")", "if", "not", "price", ":", "return", "Decimal", "(", "0", ")", "value", ...
Returns the current value of stocks
[ "Returns", "the", "current", "value", "of", "stocks" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L295-L304
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_value_in_base_currency
def get_value_in_base_currency(self) -> Decimal: """ Calculates the value of security holdings in base currency """ # check if the currency is the base currency. amt_orig = self.get_value() # Security currency sec_cur = self.get_currency() #base_cur = self.book.default_cu...
python
def get_value_in_base_currency(self) -> Decimal: """ Calculates the value of security holdings in base currency """ # check if the currency is the base currency. amt_orig = self.get_value() # Security currency sec_cur = self.get_currency() #base_cur = self.book.default_cu...
[ "def", "get_value_in_base_currency", "(", "self", ")", "->", "Decimal", ":", "amt_orig", "=", "self", ".", "get_value", "(", ")", "sec_cur", "=", "self", ".", "get_currency", "(", ")", "cur_svc", "=", "CurrenciesAggregate", "(", "self", ".", "book", ")", "...
Calculates the value of security holdings in base currency
[ "Calculates", "the", "value", "of", "security", "holdings", "in", "base", "currency" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L306-L324
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.accounts
def accounts(self) -> List[Account]: """ Returns the asset accounts in which the security is held """ # use only Assets sub-accounts result = ( [acct for acct in self.security.accounts if acct.fullname.startswith('Assets')] ) return result
python
def accounts(self) -> List[Account]: """ Returns the asset accounts in which the security is held """ # use only Assets sub-accounts result = ( [acct for acct in self.security.accounts if acct.fullname.startswith('Assets')] ) return result
[ "def", "accounts", "(", "self", ")", "->", "List", "[", "Account", "]", ":", "result", "=", "(", "[", "acct", "for", "acct", "in", "self", ".", "security", ".", "accounts", "if", "acct", ".", "fullname", ".", "startswith", "(", "'Assets'", ")", "]", ...
Returns the asset accounts in which the security is held
[ "Returns", "the", "asset", "accounts", "in", "which", "the", "security", "is", "held" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L348-L354
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecuritiesAggregate.find
def find(self, search_term: str) -> List[Commodity]: """ Searches for security by part of the name """ query = ( self.query .filter(Commodity.mnemonic.like('%' + search_term + '%') | Commodity.fullname.like('%' + search_term + '%')) ) return qu...
python
def find(self, search_term: str) -> List[Commodity]: """ Searches for security by part of the name """ query = ( self.query .filter(Commodity.mnemonic.like('%' + search_term + '%') | Commodity.fullname.like('%' + search_term + '%')) ) return qu...
[ "def", "find", "(", "self", ",", "search_term", ":", "str", ")", "->", "List", "[", "Commodity", "]", ":", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "Commodity", ".", "mnemonic", ".", "like", "(", "'%'", "+", "search_term", "+", ...
Searches for security by part of the name
[ "Searches", "for", "security", "by", "part", "of", "the", "name" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L370-L377
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecuritiesAggregate.get_all
def get_all(self) -> List[Commodity]: """ Loads all non-currency commodities, assuming they are stocks. """ query = ( self.query .order_by(Commodity.namespace, Commodity.mnemonic) ) return query.all()
python
def get_all(self) -> List[Commodity]: """ Loads all non-currency commodities, assuming they are stocks. """ query = ( self.query .order_by(Commodity.namespace, Commodity.mnemonic) ) return query.all()
[ "def", "get_all", "(", "self", ")", "->", "List", "[", "Commodity", "]", ":", "query", "=", "(", "self", ".", "query", ".", "order_by", "(", "Commodity", ".", "namespace", ",", "Commodity", ".", "mnemonic", ")", ")", "return", "query", ".", "all", "(...
Loads all non-currency commodities, assuming they are stocks.
[ "Loads", "all", "non", "-", "currency", "commodities", "assuming", "they", "are", "stocks", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L379-L385
train
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecuritiesAggregate.get_by_symbol
def get_by_symbol(self, symbol: str) -> Commodity: """ Returns the commodity with the given symbol. If more are found, an exception will be thrown. """ # handle namespace. Accept GnuCash and Yahoo-style symbols. full_symbol = self.__parse_gc_symbol(symbol) query ...
python
def get_by_symbol(self, symbol: str) -> Commodity: """ Returns the commodity with the given symbol. If more are found, an exception will be thrown. """ # handle namespace. Accept GnuCash and Yahoo-style symbols. full_symbol = self.__parse_gc_symbol(symbol) query ...
[ "def", "get_by_symbol", "(", "self", ",", "symbol", ":", "str", ")", "->", "Commodity", ":", "full_symbol", "=", "self", ".", "__parse_gc_symbol", "(", "symbol", ")", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "Commodity", ".", "mnemoni...
Returns the commodity with the given symbol. If more are found, an exception will be thrown.
[ "Returns", "the", "commodity", "with", "the", "given", "symbol", ".", "If", "more", "are", "found", "an", "exception", "will", "be", "thrown", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L387-L402
train