repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.get_subscription_by_channel_id_and_endpoint_id
def get_subscription_by_channel_id_and_endpoint_id( self, channel_id, endpoint_id): """ Search for subscription by a given channel and endpoint """ subscriptions = self.search_subscriptions( channel_id=channel_id, endpoint_id=endpoint_id) try: ...
python
def get_subscription_by_channel_id_and_endpoint_id( self, channel_id, endpoint_id): """ Search for subscription by a given channel and endpoint """ subscriptions = self.search_subscriptions( channel_id=channel_id, endpoint_id=endpoint_id) try: ...
[ "def", "get_subscription_by_channel_id_and_endpoint_id", "(", "self", ",", "channel_id", ",", "endpoint_id", ")", ":", "subscriptions", "=", "self", ".", "search_subscriptions", "(", "channel_id", "=", "channel_id", ",", "endpoint_id", "=", "endpoint_id", ")", "try", ...
Search for subscription by a given channel and endpoint
[ "Search", "for", "subscription", "by", "a", "given", "channel", "and", "endpoint" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L261-L272
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.search_subscriptions
def search_subscriptions(self, **kwargs): """ Search for all subscriptions by parameters """ params = [(key, kwargs[key]) for key in sorted(kwargs.keys())] url = "/notification/v1/subscription?{}".format( urlencode(params, doseq=True)) response = NWS_DAO().ge...
python
def search_subscriptions(self, **kwargs): """ Search for all subscriptions by parameters """ params = [(key, kwargs[key]) for key in sorted(kwargs.keys())] url = "/notification/v1/subscription?{}".format( urlencode(params, doseq=True)) response = NWS_DAO().ge...
[ "def", "search_subscriptions", "(", "self", ",", "*", "*", "kwargs", ")", ":", "params", "=", "[", "(", "key", ",", "kwargs", "[", "key", "]", ")", "for", "key", "in", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", "]", "url", "=", "\"/noti...
Search for all subscriptions by parameters
[ "Search", "for", "all", "subscriptions", "by", "parameters" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L274-L291
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.get_channel_by_channel_id
def get_channel_by_channel_id(self, channel_id): """ Get a channel by channel id """ self._validate_uuid(channel_id) url = "/notification/v1/channel/{}".format(channel_id) response = NWS_DAO().getURL(url, self._read_headers) if response.status != 200: ...
python
def get_channel_by_channel_id(self, channel_id): """ Get a channel by channel id """ self._validate_uuid(channel_id) url = "/notification/v1/channel/{}".format(channel_id) response = NWS_DAO().getURL(url, self._read_headers) if response.status != 200: ...
[ "def", "get_channel_by_channel_id", "(", "self", ",", "channel_id", ")", ":", "self", ".", "_validate_uuid", "(", "channel_id", ")", "url", "=", "\"/notification/v1/channel/{}\"", ".", "format", "(", "channel_id", ")", "response", "=", "NWS_DAO", "(", ")", ".", ...
Get a channel by channel id
[ "Get", "a", "channel", "by", "channel", "id" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L293-L307
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.get_channels_by_sln
def get_channels_by_sln(self, channel_type, sln): """ Search for all channels by sln """ return self.search_channels(type=channel_type, tag_sln=sln)
python
def get_channels_by_sln(self, channel_type, sln): """ Search for all channels by sln """ return self.search_channels(type=channel_type, tag_sln=sln)
[ "def", "get_channels_by_sln", "(", "self", ",", "channel_type", ",", "sln", ")", ":", "return", "self", ".", "search_channels", "(", "type", "=", "channel_type", ",", "tag_sln", "=", "sln", ")" ]
Search for all channels by sln
[ "Search", "for", "all", "channels", "by", "sln" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L309-L313
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.get_channels_by_sln_year_quarter
def get_channels_by_sln_year_quarter( self, channel_type, sln, year, quarter): """ Search for all channels by sln, year and quarter """ return self.search_channels( type=channel_type, tag_sln=sln, tag_year=year, tag_quarter=quarter)
python
def get_channels_by_sln_year_quarter( self, channel_type, sln, year, quarter): """ Search for all channels by sln, year and quarter """ return self.search_channels( type=channel_type, tag_sln=sln, tag_year=year, tag_quarter=quarter)
[ "def", "get_channels_by_sln_year_quarter", "(", "self", ",", "channel_type", ",", "sln", ",", "year", ",", "quarter", ")", ":", "return", "self", ".", "search_channels", "(", "type", "=", "channel_type", ",", "tag_sln", "=", "sln", ",", "tag_year", "=", "yea...
Search for all channels by sln, year and quarter
[ "Search", "for", "all", "channels", "by", "sln", "year", "and", "quarter" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L315-L321
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.get_active_channels_by_year_quarter
def get_active_channels_by_year_quarter( self, channel_type, year, quarter, expires=None): """ Search for all active channels by year and quarter """ if expires is None: # Set expires_after to midnight of current day expires = datetime.combine(datetime...
python
def get_active_channels_by_year_quarter( self, channel_type, year, quarter, expires=None): """ Search for all active channels by year and quarter """ if expires is None: # Set expires_after to midnight of current day expires = datetime.combine(datetime...
[ "def", "get_active_channels_by_year_quarter", "(", "self", ",", "channel_type", ",", "year", ",", "quarter", ",", "expires", "=", "None", ")", ":", "if", "expires", "is", "None", ":", "# Set expires_after to midnight of current day", "expires", "=", "datetime", ".",...
Search for all active channels by year and quarter
[ "Search", "for", "all", "active", "channels", "by", "year", "and", "quarter" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L323-L334
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.search_channels
def search_channels(self, **kwargs): """ Search for all channels by parameters """ params = [(key, kwargs[key]) for key in sorted(kwargs.keys())] url = "/notification/v1/channel?{}".format( urlencode(params, doseq=True)) response = NWS_DAO().getURL(url, self....
python
def search_channels(self, **kwargs): """ Search for all channels by parameters """ params = [(key, kwargs[key]) for key in sorted(kwargs.keys())] url = "/notification/v1/channel?{}".format( urlencode(params, doseq=True)) response = NWS_DAO().getURL(url, self....
[ "def", "search_channels", "(", "self", ",", "*", "*", "kwargs", ")", ":", "params", "=", "[", "(", "key", ",", "kwargs", "[", "key", "]", ")", "for", "key", "in", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", "]", "url", "=", "\"/notificat...
Search for all channels by parameters
[ "Search", "for", "all", "channels", "by", "parameters" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L336-L353
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.create_person
def create_person(self, person): """ Create a new person :param person: is the new person that the client wants to crete """ self._validate_subscriber_id(person.surrogate_id) url = "/notification/v1/person" response = NWS_DAO().postURL( url, self._wri...
python
def create_person(self, person): """ Create a new person :param person: is the new person that the client wants to crete """ self._validate_subscriber_id(person.surrogate_id) url = "/notification/v1/person" response = NWS_DAO().postURL( url, self._wri...
[ "def", "create_person", "(", "self", ",", "person", ")", ":", "self", ".", "_validate_subscriber_id", "(", "person", ".", "surrogate_id", ")", "url", "=", "\"/notification/v1/person\"", "response", "=", "NWS_DAO", "(", ")", ".", "postURL", "(", "url", ",", "...
Create a new person :param person: is the new person that the client wants to crete
[ "Create", "a", "new", "person", ":", "param", "person", ":", "is", "the", "new", "person", "that", "the", "client", "wants", "to", "crete" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L374-L388
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.update_person
def update_person(self, person): """ Update an existing person :param person: is the updated person that the client wants to update """ self._validate_regid(person.person_id) self._validate_subscriber_id(person.surrogate_id) for attr in MANAGED_ATTRIBUTES: ...
python
def update_person(self, person): """ Update an existing person :param person: is the updated person that the client wants to update """ self._validate_regid(person.person_id) self._validate_subscriber_id(person.surrogate_id) for attr in MANAGED_ATTRIBUTES: ...
[ "def", "update_person", "(", "self", ",", "person", ")", ":", "self", ".", "_validate_regid", "(", "person", ".", "person_id", ")", "self", ".", "_validate_subscriber_id", "(", "person", ".", "surrogate_id", ")", "for", "attr", "in", "MANAGED_ATTRIBUTES", ":",...
Update an existing person :param person: is the updated person that the client wants to update
[ "Update", "an", "existing", "person", ":", "param", "person", ":", "is", "the", "updated", "person", "that", "the", "client", "wants", "to", "update" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L393-L411
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.create_new_dispatch
def create_new_dispatch(self, dispatch): """ Create a new dispatch :param dispatch: is the new dispatch that the client wants to create """ self._validate_uuid(dispatch.dispatch_id) # Create new dispatch url = "/notification/v1/dispatch" post_resp...
python
def create_new_dispatch(self, dispatch): """ Create a new dispatch :param dispatch: is the new dispatch that the client wants to create """ self._validate_uuid(dispatch.dispatch_id) # Create new dispatch url = "/notification/v1/dispatch" post_resp...
[ "def", "create_new_dispatch", "(", "self", ",", "dispatch", ")", ":", "self", ".", "_validate_uuid", "(", "dispatch", ".", "dispatch_id", ")", "# Create new dispatch", "url", "=", "\"/notification/v1/dispatch\"", "post_response", "=", "NWS_DAO", "(", ")", ".", "po...
Create a new dispatch :param dispatch: is the new dispatch that the client wants to create
[ "Create", "a", "new", "dispatch", ":", "param", "dispatch", ":", "is", "the", "new", "dispatch", "that", "the", "client", "wants", "to", "create" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L413-L429
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.delete_dispatch
def delete_dispatch(self, dispatch_id): """ Deleting an existing dispatch :param dispatch_id: is the dispatch that the client wants to delete """ self._validate_uuid(dispatch_id) url = "/notification/v1/dispatch/{}".format(dispatch_id) response = NWS_DAO().delete...
python
def delete_dispatch(self, dispatch_id): """ Deleting an existing dispatch :param dispatch_id: is the dispatch that the client wants to delete """ self._validate_uuid(dispatch_id) url = "/notification/v1/dispatch/{}".format(dispatch_id) response = NWS_DAO().delete...
[ "def", "delete_dispatch", "(", "self", ",", "dispatch_id", ")", ":", "self", ".", "_validate_uuid", "(", "dispatch_id", ")", "url", "=", "\"/notification/v1/dispatch/{}\"", ".", "format", "(", "dispatch_id", ")", "response", "=", "NWS_DAO", "(", ")", ".", "del...
Deleting an existing dispatch :param dispatch_id: is the dispatch that the client wants to delete
[ "Deleting", "an", "existing", "dispatch", ":", "param", "dispatch_id", ":", "is", "the", "dispatch", "that", "the", "client", "wants", "to", "delete" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L431-L443
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.get_message_type_by_id
def get_message_type_by_id(self, message_type_id): """ Get a message type by message type ID :param message_type_id: is the message type that the client wants to retrieve """ self._validate_uuid(message_type_id) url = "/notification/v1/mes...
python
def get_message_type_by_id(self, message_type_id): """ Get a message type by message type ID :param message_type_id: is the message type that the client wants to retrieve """ self._validate_uuid(message_type_id) url = "/notification/v1/mes...
[ "def", "get_message_type_by_id", "(", "self", ",", "message_type_id", ")", ":", "self", ".", "_validate_uuid", "(", "message_type_id", ")", "url", "=", "\"/notification/v1/message-type/{}\"", ".", "format", "(", "message_type_id", ")", "response", "=", "NWS_DAO", "(...
Get a message type by message type ID :param message_type_id: is the message type that the client wants to retrieve
[ "Get", "a", "message", "type", "by", "message", "type", "ID", ":", "param", "message_type_id", ":", "is", "the", "message", "type", "that", "the", "client", "wants", "to", "retrieve" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L445-L459
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.update_message_type
def update_message_type(self, message_type): """ Update an existing message type :param message_type: is the updated message type that the client wants to update """ self._validate_uuid(message_type.message_type_id) url = "/notification/v1/me...
python
def update_message_type(self, message_type): """ Update an existing message type :param message_type: is the updated message type that the client wants to update """ self._validate_uuid(message_type.message_type_id) url = "/notification/v1/me...
[ "def", "update_message_type", "(", "self", ",", "message_type", ")", ":", "self", ".", "_validate_uuid", "(", "message_type", ".", "message_type_id", ")", "url", "=", "\"/notification/v1/message-type/{}\"", ".", "format", "(", "message_type", ".", "message_type_id", ...
Update an existing message type :param message_type: is the updated message type that the client wants to update
[ "Update", "an", "existing", "message", "type", ":", "param", "message_type", ":", "is", "the", "updated", "message", "type", "that", "the", "client", "wants", "to", "update" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L461-L477
uw-it-aca/uw-restclients-nws
uw_nws/__init__.py
NWS.delete_message_type
def delete_message_type(self, message_type_id): """ Delete an existing message type :param message_type_id: is the id of the message type the client wants to delete """ self._validate_uuid(message_type_id) url = "/notification/v1/message-t...
python
def delete_message_type(self, message_type_id): """ Delete an existing message type :param message_type_id: is the id of the message type the client wants to delete """ self._validate_uuid(message_type_id) url = "/notification/v1/message-t...
[ "def", "delete_message_type", "(", "self", ",", "message_type_id", ")", ":", "self", ".", "_validate_uuid", "(", "message_type_id", ")", "url", "=", "\"/notification/v1/message-type/{}\"", ".", "format", "(", "message_type_id", ")", "response", "=", "NWS_DAO", "(", ...
Delete an existing message type :param message_type_id: is the id of the message type the client wants to delete
[ "Delete", "an", "existing", "message", "type", ":", "param", "message_type_id", ":", "is", "the", "id", "of", "the", "message", "type", "the", "client", "wants", "to", "delete" ]
train
https://github.com/uw-it-aca/uw-restclients-nws/blob/ec6fd14342ffc883d14bcb53b2fe9bc288696027/uw_nws/__init__.py#L479-L492
knagra/farnsworth
base/pipeline.py
_get_first_last
def _get_first_last(details): """ Gets a user's first and last name from details. """ if "first_name" in details and "last_name" in details: return details["first_name"], details["last_name"] elif "first_name" in details: lst = details["first_name"].rsplit(" ", 1) if len(lst)...
python
def _get_first_last(details): """ Gets a user's first and last name from details. """ if "first_name" in details and "last_name" in details: return details["first_name"], details["last_name"] elif "first_name" in details: lst = details["first_name"].rsplit(" ", 1) if len(lst)...
[ "def", "_get_first_last", "(", "details", ")", ":", "if", "\"first_name\"", "in", "details", "and", "\"last_name\"", "in", "details", ":", "return", "details", "[", "\"first_name\"", "]", ",", "details", "[", "\"last_name\"", "]", "elif", "\"first_name\"", "in",...
Gets a user's first and last name from details.
[ "Gets", "a", "user", "s", "first", "and", "last", "name", "from", "details", "." ]
train
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/pipeline.py#L17-L32
minhhoit/yacms
yacms/boot/__init__.py
parse_field_path
def parse_field_path(field_path): """ Take a path to a field like "yacms.pages.models.Page.feature_image" and return a model key, which is a tuple of the form ('pages', 'page'), and a field name, e.g. "feature_image". """ model_path, field_name = field_path.rsplit(".", 1) app_name, model_nam...
python
def parse_field_path(field_path): """ Take a path to a field like "yacms.pages.models.Page.feature_image" and return a model key, which is a tuple of the form ('pages', 'page'), and a field name, e.g. "feature_image". """ model_path, field_name = field_path.rsplit(".", 1) app_name, model_nam...
[ "def", "parse_field_path", "(", "field_path", ")", ":", "model_path", ",", "field_name", "=", "field_path", ".", "rsplit", "(", "\".\"", ",", "1", ")", "app_name", ",", "model_name", "=", "model_path", ".", "split", "(", "'.models.'", ")", "_", ",", "app_l...
Take a path to a field like "yacms.pages.models.Page.feature_image" and return a model key, which is a tuple of the form ('pages', 'page'), and a field name, e.g. "feature_image".
[ "Take", "a", "path", "to", "a", "field", "like", "yacms", ".", "pages", ".", "models", ".", "Page", ".", "feature_image", "and", "return", "a", "model", "key", "which", "is", "a", "tuple", "of", "the", "form", "(", "pages", "page", ")", "and", "a", ...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/boot/__init__.py#L26-L35
minhhoit/yacms
yacms/boot/__init__.py
import_field
def import_field(field_classpath): """ Imports a field by its dotted class path, prepending "django.db.models" to raw class names and raising an exception if the import fails. """ if '.' in field_classpath: fully_qualified = field_classpath else: fully_qualified = "django.db.mode...
python
def import_field(field_classpath): """ Imports a field by its dotted class path, prepending "django.db.models" to raw class names and raising an exception if the import fails. """ if '.' in field_classpath: fully_qualified = field_classpath else: fully_qualified = "django.db.mode...
[ "def", "import_field", "(", "field_classpath", ")", ":", "if", "'.'", "in", "field_classpath", ":", "fully_qualified", "=", "field_classpath", "else", ":", "fully_qualified", "=", "\"django.db.models.%s\"", "%", "field_classpath", "try", ":", "return", "import_dotted_...
Imports a field by its dotted class path, prepending "django.db.models" to raw class names and raising an exception if the import fails.
[ "Imports", "a", "field", "by", "its", "dotted", "class", "path", "prepending", "django", ".", "db", ".", "models", "to", "raw", "class", "names", "and", "raising", "an", "exception", "if", "the", "import", "fails", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/boot/__init__.py#L38-L52
minhhoit/yacms
yacms/boot/__init__.py
parse_extra_model_fields
def parse_extra_model_fields(extra_model_fields): """ Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model and instantiating the extra fields. Returns a sequence of tuples of the form (model_key, fields) where model_key is a pair of app_label, model_name and fields is a list of (fie...
python
def parse_extra_model_fields(extra_model_fields): """ Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model and instantiating the extra fields. Returns a sequence of tuples of the form (model_key, fields) where model_key is a pair of app_label, model_name and fields is a list of (fie...
[ "def", "parse_extra_model_fields", "(", "extra_model_fields", ")", ":", "fields", "=", "defaultdict", "(", "list", ")", "for", "entry", "in", "extra_model_fields", ":", "model_key", ",", "field_name", "=", "parse_field_path", "(", "entry", "[", "0", "]", ")", ...
Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model and instantiating the extra fields. Returns a sequence of tuples of the form (model_key, fields) where model_key is a pair of app_label, model_name and fields is a list of (field_name, field_instance) pairs.
[ "Parses", "the", "value", "of", "EXTRA_MODEL_FIELDS", "grouping", "the", "entries", "by", "model", "and", "instantiating", "the", "extra", "fields", ".", "Returns", "a", "sequence", "of", "tuples", "of", "the", "form", "(", "model_key", "fields", ")", "where",...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/boot/__init__.py#L55-L74
minhhoit/yacms
yacms/boot/__init__.py
add_extra_model_fields
def add_extra_model_fields(sender, **kwargs): """ Injects custom fields onto the given sender model as defined by the ``EXTRA_MODEL_FIELDS`` setting. This is a closure over the "fields" variable. """ model_key = sender._meta.app_label, sender._meta.model_name for field_name, field in fields....
python
def add_extra_model_fields(sender, **kwargs): """ Injects custom fields onto the given sender model as defined by the ``EXTRA_MODEL_FIELDS`` setting. This is a closure over the "fields" variable. """ model_key = sender._meta.app_label, sender._meta.model_name for field_name, field in fields....
[ "def", "add_extra_model_fields", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "model_key", "=", "sender", ".", "_meta", ".", "app_label", ",", "sender", ".", "_meta", ".", "model_name", "for", "field_name", ",", "field", "in", "fields", ".", "get", ...
Injects custom fields onto the given sender model as defined by the ``EXTRA_MODEL_FIELDS`` setting. This is a closure over the "fields" variable.
[ "Injects", "custom", "fields", "onto", "the", "given", "sender", "model", "as", "defined", "by", "the", "EXTRA_MODEL_FIELDS", "setting", ".", "This", "is", "a", "closure", "over", "the", "fields", "variable", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/boot/__init__.py#L80-L88
jmvrbanac/PackMap
packmap/finder.py
main
def main(*args, **kwargs): """ Simple entry-point that takes the package name and json output""" parser = argparse.ArgumentParser() parser.add_argument('package_name', type=str) parser.add_argument('output_filename', type=str) parsed_args = parser.parse_args() # Find all package requirements ...
python
def main(*args, **kwargs): """ Simple entry-point that takes the package name and json output""" parser = argparse.ArgumentParser() parser.add_argument('package_name', type=str) parser.add_argument('output_filename', type=str) parsed_args = parser.parse_args() # Find all package requirements ...
[ "def", "main", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'package_name'", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "'ou...
Simple entry-point that takes the package name and json output
[ "Simple", "entry", "-", "point", "that", "takes", "the", "package", "name", "and", "json", "output" ]
train
https://github.com/jmvrbanac/PackMap/blob/e35d12d21ab109cae1175e0dc94d7f4855256b23/packmap/finder.py#L57-L71
wdbm/shijian
shijian.py
tail
def tail( filepath = "log.txt", lines = 50 ): """ Return a specified number of last lines of a specified file. If there is an error or the file does not exist, return False. """ try: filepath = os.path.expanduser(os.path.expandvars(filepath)) if os.path.isfile(filepath...
python
def tail( filepath = "log.txt", lines = 50 ): """ Return a specified number of last lines of a specified file. If there is an error or the file does not exist, return False. """ try: filepath = os.path.expanduser(os.path.expandvars(filepath)) if os.path.isfile(filepath...
[ "def", "tail", "(", "filepath", "=", "\"log.txt\"", ",", "lines", "=", "50", ")", ":", "try", ":", "filepath", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "expandvars", "(", "filepath", ")", ")", "if", "os", ".", "path",...
Return a specified number of last lines of a specified file. If there is an error or the file does not exist, return False.
[ "Return", "a", "specified", "number", "of", "last", "lines", "of", "a", "specified", "file", ".", "If", "there", "is", "an", "error", "or", "the", "file", "does", "not", "exist", "return", "False", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L657-L676
wdbm/shijian
shijian.py
convert_type_list_elements
def convert_type_list_elements( list_object = None, element_type = str ): """ Recursively convert all elements and all elements of all sublists of a list to a specified type and return the new list. """ if element_type is str: return [str(element) if not isinstance(element, list...
python
def convert_type_list_elements( list_object = None, element_type = str ): """ Recursively convert all elements and all elements of all sublists of a list to a specified type and return the new list. """ if element_type is str: return [str(element) if not isinstance(element, list...
[ "def", "convert_type_list_elements", "(", "list_object", "=", "None", ",", "element_type", "=", "str", ")", ":", "if", "element_type", "is", "str", ":", "return", "[", "str", "(", "element", ")", "if", "not", "isinstance", "(", "element", ",", "list", ")",...
Recursively convert all elements and all elements of all sublists of a list to a specified type and return the new list.
[ "Recursively", "convert", "all", "elements", "and", "all", "elements", "of", "all", "sublists", "of", "a", "list", "to", "a", "specified", "type", "and", "return", "the", "new", "list", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L878-L890
wdbm/shijian
shijian.py
select_spread
def select_spread( list_of_elements = None, number_of_elements = None ): """ This function returns the specified number of elements of a list spread approximately evenly. """ if len(list_of_elements) <= number_of_elements: return list_of_elements if number_of_elements == 0:...
python
def select_spread( list_of_elements = None, number_of_elements = None ): """ This function returns the specified number of elements of a list spread approximately evenly. """ if len(list_of_elements) <= number_of_elements: return list_of_elements if number_of_elements == 0:...
[ "def", "select_spread", "(", "list_of_elements", "=", "None", ",", "number_of_elements", "=", "None", ")", ":", "if", "len", "(", "list_of_elements", ")", "<=", "number_of_elements", ":", "return", "list_of_elements", "if", "number_of_elements", "==", "0", ":", ...
This function returns the specified number of elements of a list spread approximately evenly.
[ "This", "function", "returns", "the", "specified", "number", "of", "elements", "of", "a", "list", "spread", "approximately", "evenly", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L997-L1015
wdbm/shijian
shijian.py
split_list
def split_list( list_object = None, granularity = None ): """ This function splits a list into a specified number of lists. It returns a list of lists that correspond to these parts. Negative numbers of parts are not accepted and numbers of parts greater than the number of elements in the ...
python
def split_list( list_object = None, granularity = None ): """ This function splits a list into a specified number of lists. It returns a list of lists that correspond to these parts. Negative numbers of parts are not accepted and numbers of parts greater than the number of elements in the ...
[ "def", "split_list", "(", "list_object", "=", "None", ",", "granularity", "=", "None", ")", ":", "if", "granularity", "<", "0", ":", "raise", "Exception", "(", "\"negative granularity\"", ")", "mean_length", "=", "len", "(", "list_object", ")", "/", "float",...
This function splits a list into a specified number of lists. It returns a list of lists that correspond to these parts. Negative numbers of parts are not accepted and numbers of parts greater than the number of elements in the list result in the maximum possible number of lists being returned.
[ "This", "function", "splits", "a", "list", "into", "a", "specified", "number", "of", "lists", ".", "It", "returns", "a", "list", "of", "lists", "that", "correspond", "to", "these", "parts", ".", "Negative", "numbers", "of", "parts", "are", "not", "accepted...
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1017-L1040
wdbm/shijian
shijian.py
ranges_edge_pairs
def ranges_edge_pairs( extent = None, range_length = None ): """ Return the edges of ranges within an extent of some length. For example, to separate 76 variables into groups of at most 20 variables, the ranges of the variables could be 0 to 20, 21 to 41, 42 to 62 and 63 to 76. These r...
python
def ranges_edge_pairs( extent = None, range_length = None ): """ Return the edges of ranges within an extent of some length. For example, to separate 76 variables into groups of at most 20 variables, the ranges of the variables could be 0 to 20, 21 to 41, 42 to 62 and 63 to 76. These r...
[ "def", "ranges_edge_pairs", "(", "extent", "=", "None", ",", "range_length", "=", "None", ")", ":", "number_of_ranges", "=", "int", "(", "math", ".", "ceil", "(", "extent", "/", "range_length", ")", ")", "return", "[", "(", "index", "*", "range_length", ...
Return the edges of ranges within an extent of some length. For example, to separate 76 variables into groups of at most 20 variables, the ranges of the variables could be 0 to 20, 21 to 41, 42 to 62 and 63 to 76. These range edges could be returned by this function as a list of tuples: >>> ranges_edge...
[ "Return", "the", "edges", "of", "ranges", "within", "an", "extent", "of", "some", "length", ".", "For", "example", "to", "separate", "76", "variables", "into", "groups", "of", "at", "most", "20", "variables", "the", "ranges", "of", "the", "variables", "cou...
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1042-L1065
wdbm/shijian
shijian.py
ustr
def ustr(text): """ Convert a string to Python 2 unicode or Python 3 string as appropriate to the version of Python in use. """ if text is not None: if sys.version_info >= (3, 0): return str(text) else: return unicode(text) else: return text
python
def ustr(text): """ Convert a string to Python 2 unicode or Python 3 string as appropriate to the version of Python in use. """ if text is not None: if sys.version_info >= (3, 0): return str(text) else: return unicode(text) else: return text
[ "def", "ustr", "(", "text", ")", ":", "if", "text", "is", "not", "None", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "return", "str", "(", "text", ")", "else", ":", "return", "unicode", "(", "text", ")", "else", "...
Convert a string to Python 2 unicode or Python 3 string as appropriate to the version of Python in use.
[ "Convert", "a", "string", "to", "Python", "2", "unicode", "or", "Python", "3", "string", "as", "appropriate", "to", "the", "version", "of", "Python", "in", "use", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1231-L1242
wdbm/shijian
shijian.py
replace_contractions_with_full_words_and_replace_numbers_with_digits
def replace_contractions_with_full_words_and_replace_numbers_with_digits( text = None, remove_articles = True ): """ This function replaces contractions with full words and replaces numbers with digits in specified text. There is the option to remove articles. """ words = text...
python
def replace_contractions_with_full_words_and_replace_numbers_with_digits( text = None, remove_articles = True ): """ This function replaces contractions with full words and replaces numbers with digits in specified text. There is the option to remove articles. """ words = text...
[ "def", "replace_contractions_with_full_words_and_replace_numbers_with_digits", "(", "text", "=", "None", ",", "remove_articles", "=", "True", ")", ":", "words", "=", "text", ".", "split", "(", ")", "text_translated", "=", "\"\"", "for", "word", "in", "words", ":",...
This function replaces contractions with full words and replaces numbers with digits in specified text. There is the option to remove articles.
[ "This", "function", "replaces", "contractions", "with", "full", "words", "and", "replaces", "numbers", "with", "digits", "in", "specified", "text", ".", "There", "is", "the", "option", "to", "remove", "articles", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1362-L1499
wdbm/shijian
shijian.py
add_time_variables
def add_time_variables(df, reindex = True): """ Return a DataFrame with variables for weekday index, weekday name, timedelta through day, fraction through day, hours through day and days through week added, optionally with the index set to datetime and the variable `datetime` removed. It is assumed ...
python
def add_time_variables(df, reindex = True): """ Return a DataFrame with variables for weekday index, weekday name, timedelta through day, fraction through day, hours through day and days through week added, optionally with the index set to datetime and the variable `datetime` removed. It is assumed ...
[ "def", "add_time_variables", "(", "df", ",", "reindex", "=", "True", ")", ":", "if", "not", "\"datetime\"", "in", "df", ".", "columns", ":", "log", ".", "error", "(", "\"field datetime not found in DataFrame\"", ")", "return", "False", "df", "[", "\"datetime\"...
Return a DataFrame with variables for weekday index, weekday name, timedelta through day, fraction through day, hours through day and days through week added, optionally with the index set to datetime and the variable `datetime` removed. It is assumed that the variable `datetime` exists.
[ "Return", "a", "DataFrame", "with", "variables", "for", "weekday", "index", "weekday", "name", "timedelta", "through", "day", "fraction", "through", "day", "hours", "through", "day", "and", "days", "through", "week", "added", "optionally", "with", "the", "index"...
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1578-L1611
wdbm/shijian
shijian.py
daily_plots
def daily_plots( df, variable, renormalize = True, plot = True, scatter = False, linestyle = "-", linewidth = 1, s = 1 ): """ Create daily plots of a variable in a DataFrame, optionally renormalized. It is assumed that the DataFrame index is datet...
python
def daily_plots( df, variable, renormalize = True, plot = True, scatter = False, linestyle = "-", linewidth = 1, s = 1 ): """ Create daily plots of a variable in a DataFrame, optionally renormalized. It is assumed that the DataFrame index is datet...
[ "def", "daily_plots", "(", "df", ",", "variable", ",", "renormalize", "=", "True", ",", "plot", "=", "True", ",", "scatter", "=", "False", ",", "linestyle", "=", "\"-\"", ",", "linewidth", "=", "1", ",", "s", "=", "1", ")", ":", "if", "not", "df", ...
Create daily plots of a variable in a DataFrame, optionally renormalized. It is assumed that the DataFrame index is datetime.
[ "Create", "daily", "plots", "of", "a", "variable", "in", "a", "DataFrame", "optionally", "renormalized", ".", "It", "is", "assumed", "that", "the", "DataFrame", "index", "is", "datetime", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1613-L1644
wdbm/shijian
shijian.py
weekly_plots
def weekly_plots( df, variable, renormalize = True, plot = True, scatter = False, linestyle = "-", linewidth = 1, s = 1 ): """ Create weekly plots of a variable in a DataFrame, optionally renormalized. It is assumed that the variable `days_through...
python
def weekly_plots( df, variable, renormalize = True, plot = True, scatter = False, linestyle = "-", linewidth = 1, s = 1 ): """ Create weekly plots of a variable in a DataFrame, optionally renormalized. It is assumed that the variable `days_through...
[ "def", "weekly_plots", "(", "df", ",", "variable", ",", "renormalize", "=", "True", ",", "plot", "=", "True", ",", "scatter", "=", "False", ",", "linestyle", "=", "\"-\"", ",", "linewidth", "=", "1", ",", "s", "=", "1", ")", ":", "if", "not", "\"da...
Create weekly plots of a variable in a DataFrame, optionally renormalized. It is assumed that the variable `days_through_week` exists.
[ "Create", "weekly", "plots", "of", "a", "variable", "in", "a", "DataFrame", "optionally", "renormalized", ".", "It", "is", "assumed", "that", "the", "variable", "days_through_week", "exists", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1646-L1680
wdbm/shijian
shijian.py
yearly_plots
def yearly_plots( df, variable, renormalize = True, horizontal_axis_labels_days = False, horizontal_axis_labels_months = True, plot = True, scatter = False, linestyle = "-", linewidth ...
python
def yearly_plots( df, variable, renormalize = True, horizontal_axis_labels_days = False, horizontal_axis_labels_months = True, plot = True, scatter = False, linestyle = "-", linewidth ...
[ "def", "yearly_plots", "(", "df", ",", "variable", ",", "renormalize", "=", "True", ",", "horizontal_axis_labels_days", "=", "False", ",", "horizontal_axis_labels_months", "=", "True", ",", "plot", "=", "True", ",", "scatter", "=", "False", ",", "linestyle", "...
Create yearly plots of a variable in a DataFrame, optionally renormalized. It is assumed that the DataFrame index is datetime.
[ "Create", "yearly", "plots", "of", "a", "variable", "in", "a", "DataFrame", "optionally", "renormalized", ".", "It", "is", "assumed", "that", "the", "DataFrame", "index", "is", "datetime", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1682-L1721
wdbm/shijian
shijian.py
add_rolling_statistics_variables
def add_rolling_statistics_variables( df = None, variable = None, window = 20, upper_factor = 2, lower_factor = 2 ): """ Add rolling statistics variables derived from a specified variable in a DataFrame. """ df[variable + "_rolling_mean"] = p...
python
def add_rolling_statistics_variables( df = None, variable = None, window = 20, upper_factor = 2, lower_factor = 2 ): """ Add rolling statistics variables derived from a specified variable in a DataFrame. """ df[variable + "_rolling_mean"] = p...
[ "def", "add_rolling_statistics_variables", "(", "df", "=", "None", ",", "variable", "=", "None", ",", "window", "=", "20", ",", "upper_factor", "=", "2", ",", "lower_factor", "=", "2", ")", ":", "df", "[", "variable", "+", "\"_rolling_mean\"", "]", "=", ...
Add rolling statistics variables derived from a specified variable in a DataFrame.
[ "Add", "rolling", "statistics", "variables", "derived", "from", "a", "specified", "variable", "in", "a", "DataFrame", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1723-L1738
wdbm/shijian
shijian.py
rescale_variables
def rescale_variables( df, variables_include = [], variables_exclude = [] ): """ Rescale variables in a DataFrame, excluding variables with NaNs and strings, excluding specified variables, and including specified variables. """ variables_not_rescale = variables_exclude variables_...
python
def rescale_variables( df, variables_include = [], variables_exclude = [] ): """ Rescale variables in a DataFrame, excluding variables with NaNs and strings, excluding specified variables, and including specified variables. """ variables_not_rescale = variables_exclude variables_...
[ "def", "rescale_variables", "(", "df", ",", "variables_include", "=", "[", "]", ",", "variables_exclude", "=", "[", "]", ")", ":", "variables_not_rescale", "=", "variables_exclude", "variables_not_rescale", ".", "extend", "(", "df", ".", "columns", "[", "df", ...
Rescale variables in a DataFrame, excluding variables with NaNs and strings, excluding specified variables, and including specified variables.
[ "Rescale", "variables", "in", "a", "DataFrame", "excluding", "variables", "with", "NaNs", "and", "strings", "excluding", "specified", "variables", "and", "including", "specified", "variables", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1740-L1756
wdbm/shijian
shijian.py
histogram_hour_counts
def histogram_hour_counts( df, variable ): """ Create a day-long histogram of counts of the variable for each hour. It is assumed that the DataFrame index is datetime and that the variable `hour` exists. """ if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]: l...
python
def histogram_hour_counts( df, variable ): """ Create a day-long histogram of counts of the variable for each hour. It is assumed that the DataFrame index is datetime and that the variable `hour` exists. """ if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]: l...
[ "def", "histogram_hour_counts", "(", "df", ",", "variable", ")", ":", "if", "not", "df", ".", "index", ".", "dtype", "in", "[", "\"datetime64[ns]\"", ",", "\"<M8[ns]\"", ",", "\">M8[ns]\"", "]", ":", "log", ".", "error", "(", "\"index is not datetime\"", ")"...
Create a day-long histogram of counts of the variable for each hour. It is assumed that the DataFrame index is datetime and that the variable `hour` exists.
[ "Create", "a", "day", "-", "long", "histogram", "of", "counts", "of", "the", "variable", "for", "each", "hour", ".", "It", "is", "assumed", "that", "the", "DataFrame", "index", "is", "datetime", "and", "that", "the", "variable", "hour", "exists", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1758-L1771
wdbm/shijian
shijian.py
histogram_day_counts
def histogram_day_counts( df, variable ): """ Create a week-long histogram of counts of the variable for each day. It is assumed that the DataFrame index is datetime and that the variable `weekday_name` exists. """ if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]: ...
python
def histogram_day_counts( df, variable ): """ Create a week-long histogram of counts of the variable for each day. It is assumed that the DataFrame index is datetime and that the variable `weekday_name` exists. """ if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]: ...
[ "def", "histogram_day_counts", "(", "df", ",", "variable", ")", ":", "if", "not", "df", ".", "index", ".", "dtype", "in", "[", "\"datetime64[ns]\"", ",", "\"<M8[ns]\"", ",", "\">M8[ns]\"", "]", ":", "log", ".", "error", "(", "\"index is not datetime\"", ")",...
Create a week-long histogram of counts of the variable for each day. It is assumed that the DataFrame index is datetime and that the variable `weekday_name` exists.
[ "Create", "a", "week", "-", "long", "histogram", "of", "counts", "of", "the", "variable", "for", "each", "day", ".", "It", "is", "assumed", "that", "the", "DataFrame", "index", "is", "datetime", "and", "that", "the", "variable", "weekday_name", "exists", "...
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1773-L1786
wdbm/shijian
shijian.py
histogram_month_counts
def histogram_month_counts( df, variable ): """ Create a year-long histogram of counts of the variable for each month. It is assumed that the DataFrame index is datetime and that the variable `month_name` exists. """ if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]: ...
python
def histogram_month_counts( df, variable ): """ Create a year-long histogram of counts of the variable for each month. It is assumed that the DataFrame index is datetime and that the variable `month_name` exists. """ if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]: ...
[ "def", "histogram_month_counts", "(", "df", ",", "variable", ")", ":", "if", "not", "df", ".", "index", ".", "dtype", "in", "[", "\"datetime64[ns]\"", ",", "\"<M8[ns]\"", ",", "\">M8[ns]\"", "]", ":", "log", ".", "error", "(", "\"index is not datetime\"", ")...
Create a year-long histogram of counts of the variable for each month. It is assumed that the DataFrame index is datetime and that the variable `month_name` exists.
[ "Create", "a", "year", "-", "long", "histogram", "of", "counts", "of", "the", "variable", "for", "each", "month", ".", "It", "is", "assumed", "that", "the", "DataFrame", "index", "is", "datetime", "and", "that", "the", "variable", "month_name", "exists", "...
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1788-L1801
wdbm/shijian
shijian.py
setup_Jupyter
def setup_Jupyter(): """ Set up a Jupyter notebook with a few defaults. """ sns.set(context = "paper", font = "monospace") warnings.filterwarnings("ignore") pd.set_option("display.max_rows", 500) pd.set_option("display.max_columns", 500) plt.rcParams["figure.figsize"] = (17, 10)
python
def setup_Jupyter(): """ Set up a Jupyter notebook with a few defaults. """ sns.set(context = "paper", font = "monospace") warnings.filterwarnings("ignore") pd.set_option("display.max_rows", 500) pd.set_option("display.max_columns", 500) plt.rcParams["figure.figsize"] = (17, 10)
[ "def", "setup_Jupyter", "(", ")", ":", "sns", ".", "set", "(", "context", "=", "\"paper\"", ",", "font", "=", "\"monospace\"", ")", "warnings", ".", "filterwarnings", "(", "\"ignore\"", ")", "pd", ".", "set_option", "(", "\"display.max_rows\"", ",", "500", ...
Set up a Jupyter notebook with a few defaults.
[ "Set", "up", "a", "Jupyter", "notebook", "with", "a", "few", "defaults", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1803-L1811
wdbm/shijian
shijian.py
List_Consensus.ensure_size
def ensure_size( self, size = None ): """ This function removes the least frequent elements until the size constraint is met. """ if size is None: size = self.size_constraint while sys.getsizeof(self) > size: element_frequen...
python
def ensure_size( self, size = None ): """ This function removes the least frequent elements until the size constraint is met. """ if size is None: size = self.size_constraint while sys.getsizeof(self) > size: element_frequen...
[ "def", "ensure_size", "(", "self", ",", "size", "=", "None", ")", ":", "if", "size", "is", "None", ":", "size", "=", "self", ".", "size_constraint", "while", "sys", ".", "getsizeof", "(", "self", ")", ">", "size", ":", "element_frequencies", "=", "coll...
This function removes the least frequent elements until the size constraint is met.
[ "This", "function", "removes", "the", "least", "frequent", "elements", "until", "the", "size", "constraint", "is", "met", "." ]
train
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L919-L932
flo-compbio/gopca-server
gpserver/update_handlers.py
GeneAnnotationUpdateHandler.post
def post(self): server = 'ftp.ensembl.org' #go_dir = 'pub/current_gtf' go_dir = 'pub' user = 'anonymous' # get directory listnig ftp = ftplib.FTP(server) ftp.login(user) data = [] #ftp.cwd(go_dir) ftp.dir(go_dir, data.append) #ftp...
python
def post(self): server = 'ftp.ensembl.org' #go_dir = 'pub/current_gtf' go_dir = 'pub' user = 'anonymous' # get directory listnig ftp = ftplib.FTP(server) ftp.login(user) data = [] #ftp.cwd(go_dir) ftp.dir(go_dir, data.append) #ftp...
[ "def", "post", "(", "self", ")", ":", "server", "=", "'ftp.ensembl.org'", "#go_dir = 'pub/current_gtf'", "go_dir", "=", "'pub'", "user", "=", "'anonymous'", "# get directory listnig", "ftp", "=", "ftplib", ".", "FTP", "(", "server", ")", "ftp", ".", "login", "...
for sp in self.species: sc = self.scientific_names[sp].lower() spdir = 'pub/release-%d/gtf/%s' %(latest,sc) data = [] #ftp.dir(spdir,data.append) cs_url = 'ftp://' + '/'.join([server,spdir,'CHECKSUMS']) print cs_url checksum = None ...
[ "for", "sp", "in", "self", ".", "species", ":", "sc", "=", "self", ".", "scientific_names", "[", "sp", "]", ".", "lower", "()", "spdir", "=", "pub", "/", "release", "-", "%d", "/", "gtf", "/", "%s", "%", "(", "latest", "sc", ")", "data", "=", "...
train
https://github.com/flo-compbio/gopca-server/blob/4fe396b12c39c0f156ce3bc4538cade54c9d7ffe/gpserver/update_handlers.py#L52-L137
ONSdigital/sdx-common
sdx/common/logger_config.py
logger_initial_config
def logger_initial_config(service_name=None, log_level=None, logger_format=None, logger_date_format=None): '''Set initial logging configurations. :param service_name: Name of the service :type logger: String :param log_level...
python
def logger_initial_config(service_name=None, log_level=None, logger_format=None, logger_date_format=None): '''Set initial logging configurations. :param service_name: Name of the service :type logger: String :param log_level...
[ "def", "logger_initial_config", "(", "service_name", "=", "None", ",", "log_level", "=", "None", ",", "logger_format", "=", "None", ",", "logger_date_format", "=", "None", ")", ":", "if", "not", "log_level", ":", "log_level", "=", "os", ".", "getenv", "(", ...
Set initial logging configurations. :param service_name: Name of the service :type logger: String :param log_level: A string or integer corresponding to a Python logging level :type log_level: String :param logger_format: A string defining the format of the logs :type log_level: String :...
[ "Set", "initial", "logging", "configurations", "." ]
train
https://github.com/ONSdigital/sdx-common/blob/815f6a116d41fddae182943d821dc5f582a9af69/sdx/common/logger_config.py#L5-L38
TiagoDanin/PythonColorize
PythonColorize.py
colorize
def colorize(text=None, color=None, style=None, light=None, background=None): ''' Colors | Styles | --------|--------------------| black | bold | red | dark | green | underline | yellow | negative | blue | hide | magenta | ...
python
def colorize(text=None, color=None, style=None, light=None, background=None): ''' Colors | Styles | --------|--------------------| black | bold | red | dark | green | underline | yellow | negative | blue | hide | magenta | ...
[ "def", "colorize", "(", "text", "=", "None", ",", "color", "=", "None", ",", "style", "=", "None", ",", "light", "=", "None", ",", "background", "=", "None", ")", ":", "param", "=", "colors", ".", "color", "param_color", "=", "7", "param_style", "=",...
Colors | Styles | --------|--------------------| black | bold | red | dark | green | underline | yellow | negative | blue | hide | magenta | | cyan | | white | | ...
[ "Colors", "|", "Styles", "|", "--------", "|", "--------------------", "|", "black", "|", "bold", "|", "red", "|", "dark", "|", "green", "|", "underline", "|", "yellow", "|", "negative", "|", "blue", "|", "hide", "|", "magenta", "|", "|", "cyan", "|", ...
train
https://github.com/TiagoDanin/PythonColorize/blob/26ca934b627b5bfba0b013305339fe0e030a96cc/PythonColorize.py#L290-L358
alexhayes/django-toolkit
django_toolkit/network.py
cidr_notation
def cidr_notation(ip_address, netmask): """ Retrieve the cidr notation given an ip address and netmask. For example: cidr_notation('12.34.56.78', '255.255.255.248') Would return: 12.34.56.72/29 @see http://terminalmage.net/2012/06/10/how-to-find-out-the-cidr-notation-for...
python
def cidr_notation(ip_address, netmask): """ Retrieve the cidr notation given an ip address and netmask. For example: cidr_notation('12.34.56.78', '255.255.255.248') Would return: 12.34.56.72/29 @see http://terminalmage.net/2012/06/10/how-to-find-out-the-cidr-notation-for...
[ "def", "cidr_notation", "(", "ip_address", ",", "netmask", ")", ":", "try", ":", "inet_aton", "(", "ip_address", ")", "except", ":", "raise", "Exception", "(", "\"Invalid ip address '%s'\"", "%", "ip_address", ")", "try", ":", "inet_aton", "(", "netmask", ")",...
Retrieve the cidr notation given an ip address and netmask. For example: cidr_notation('12.34.56.78', '255.255.255.248') Would return: 12.34.56.72/29 @see http://terminalmage.net/2012/06/10/how-to-find-out-the-cidr-notation-for-a-subne-given-an-ip-and-netmask/ @see http://ww...
[ "Retrieve", "the", "cidr", "notation", "given", "an", "ip", "address", "and", "netmask", ".", "For", "example", ":", "cidr_notation", "(", "12", ".", "34", ".", "56", ".", "78", "255", ".", "255", ".", "255", ".", "248", ")", "Would", "return", ":", ...
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/network.py#L10-L39
smartmob-project/smartmob-agent
smartmob_agent/__init__.py
inject_request_id
async def inject_request_id(app, handler): """aiohttp middleware: ensures each request has a unique request ID. See: ``inject_request_id``. """ async def trace_request(request): request['x-request-id'] = \ request.headers.get('x-request-id') or str(uuid.uuid4()) return awai...
python
async def inject_request_id(app, handler): """aiohttp middleware: ensures each request has a unique request ID. See: ``inject_request_id``. """ async def trace_request(request): request['x-request-id'] = \ request.headers.get('x-request-id') or str(uuid.uuid4()) return awai...
[ "async", "def", "inject_request_id", "(", "app", ",", "handler", ")", ":", "async", "def", "trace_request", "(", "request", ")", ":", "request", "[", "'x-request-id'", "]", "=", "request", ".", "headers", ".", "get", "(", "'x-request-id'", ")", "or", "str"...
aiohttp middleware: ensures each request has a unique request ID. See: ``inject_request_id``.
[ "aiohttp", "middleware", ":", "ensures", "each", "request", "has", "a", "unique", "request", "ID", "." ]
train
https://github.com/smartmob-project/smartmob-agent/blob/4039f577ab7230d135f00df68c611a51e45ddbc7/smartmob_agent/__init__.py#L73-L84
smartmob-project/smartmob-agent
smartmob_agent/__init__.py
access_log_middleware
async def access_log_middleware(app, handler): """Log each request in structured event log.""" event_log = app.get('smartmob.event_log') or structlog.get_logger() clock = app.get('smartmob.clock') or timeit.default_timer # Keep the request arrival time to ensure we get intuitive logging of # event...
python
async def access_log_middleware(app, handler): """Log each request in structured event log.""" event_log = app.get('smartmob.event_log') or structlog.get_logger() clock = app.get('smartmob.clock') or timeit.default_timer # Keep the request arrival time to ensure we get intuitive logging of # event...
[ "async", "def", "access_log_middleware", "(", "app", ",", "handler", ")", ":", "event_log", "=", "app", ".", "get", "(", "'smartmob.event_log'", ")", "or", "structlog", ".", "get_logger", "(", ")", "clock", "=", "app", ".", "get", "(", "'smartmob.clock'", ...
Log each request in structured event log.
[ "Log", "each", "request", "in", "structured", "event", "log", "." ]
train
https://github.com/smartmob-project/smartmob-agent/blob/4039f577ab7230d135f00df68c611a51e45ddbc7/smartmob_agent/__init__.py#L95-L139
smartmob-project/smartmob-agent
smartmob_agent/__init__.py
unpack_archive
def unpack_archive(archive_format, archive_path, source_path): """Extract a .zip/.tar.gz archive to a folder.""" if archive_format not in ('zip', 'tar'): raise ValueError('Unknown archive format "%s".' % archive_format) if archive_format == 'zip': with zipfile.ZipFile(archive_path) as archiv...
python
def unpack_archive(archive_format, archive_path, source_path): """Extract a .zip/.tar.gz archive to a folder.""" if archive_format not in ('zip', 'tar'): raise ValueError('Unknown archive format "%s".' % archive_format) if archive_format == 'zip': with zipfile.ZipFile(archive_path) as archiv...
[ "def", "unpack_archive", "(", "archive_format", ",", "archive_path", ",", "source_path", ")", ":", "if", "archive_format", "not", "in", "(", "'zip'", ",", "'tar'", ")", ":", "raise", "ValueError", "(", "'Unknown archive format \"%s\".'", "%", "archive_format", ")"...
Extract a .zip/.tar.gz archive to a folder.
[ "Extract", "a", ".", "zip", "/", ".", "tar", ".", "gz", "archive", "to", "a", "folder", "." ]
train
https://github.com/smartmob-project/smartmob-agent/blob/4039f577ab7230d135f00df68c611a51e45ddbc7/smartmob_agent/__init__.py#L309-L318
smartmob-project/smartmob-agent
smartmob_agent/__init__.py
start_responder
def start_responder(host='127.0.0.1', port=8080, event_log=None, loop=None): """.""" loop = loop or asyncio.get_event_loop() event_log = event_log or structlog.get_logger() # Prepare a web application. app = web.Application(loop=loop, middlewares=[ inject_request_id, access_log_mid...
python
def start_responder(host='127.0.0.1', port=8080, event_log=None, loop=None): """.""" loop = loop or asyncio.get_event_loop() event_log = event_log or structlog.get_logger() # Prepare a web application. app = web.Application(loop=loop, middlewares=[ inject_request_id, access_log_mid...
[ "def", "start_responder", "(", "host", "=", "'127.0.0.1'", ",", "port", "=", "8080", ",", "event_log", "=", "None", ",", "loop", "=", "None", ")", ":", "loop", "=", "loop", "or", "asyncio", ".", "get_event_loop", "(", ")", "event_log", "=", "event_log", ...
.
[ "." ]
train
https://github.com/smartmob-project/smartmob-agent/blob/4039f577ab7230d135f00df68c611a51e45ddbc7/smartmob_agent/__init__.py#L627-L673
smartmob-project/smartmob-agent
smartmob_agent/__init__.py
main
def main(arguments=None): """Command-line entry point. :param arguments: List of strings that contain the command-line arguments. When ``None``, the command-line arguments are looked up in ``sys.argv`` (``sys.argv[0]`` is ignored). :return: This function has no return value. :raise System...
python
def main(arguments=None): """Command-line entry point. :param arguments: List of strings that contain the command-line arguments. When ``None``, the command-line arguments are looked up in ``sys.argv`` (``sys.argv[0]`` is ignored). :return: This function has no return value. :raise System...
[ "def", "main", "(", "arguments", "=", "None", ")", ":", "# Parse command-line arguments.", "if", "arguments", "is", "None", ":", "arguments", "=", "sys", ".", "argv", "[", "1", ":", "]", "arguments", "=", "cli", ".", "parse_args", "(", "arguments", ")", ...
Command-line entry point. :param arguments: List of strings that contain the command-line arguments. When ``None``, the command-line arguments are looked up in ``sys.argv`` (``sys.argv[0]`` is ignored). :return: This function has no return value. :raise SystemExit: The command-line arguments ...
[ "Command", "-", "line", "entry", "point", "." ]
train
https://github.com/smartmob-project/smartmob-agent/blob/4039f577ab7230d135f00df68c611a51e45ddbc7/smartmob_agent/__init__.py#L697-L737
jtpaasch/simplygithub
simplygithub/internals/merges.py
merge
def merge(profile, head, base, commit_message=None): """Merge the head of a branch into the base branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``tok...
python
def merge(profile, head, base, commit_message=None): """Merge the head of a branch into the base branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``tok...
[ "def", "merge", "(", "profile", ",", "head", ",", "base", ",", "commit_message", "=", "None", ")", ":", "if", "not", "commit_message", ":", "commit_message", "=", "\"Merged \"", "+", "head", "+", "\" into \"", "+", "base", "+", "\".\"", "payload", "=", "...
Merge the head of a branch into the base branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. head The head to ...
[ "Merge", "the", "head", "of", "a", "branch", "into", "the", "base", "branch", "." ]
train
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/merges.py#L18-L53
soasme/rio-client
rio_client/parser.py
parse_netloc
def parse_netloc(scheme, netloc): """Parse netloc string.""" auth, _netloc = netloc.split('@') sender, token = auth.split(':') if ':' in _netloc: domain, port = _netloc.split(':') port = int(port) else: domain = _netloc if scheme == 'https': port = 443 ...
python
def parse_netloc(scheme, netloc): """Parse netloc string.""" auth, _netloc = netloc.split('@') sender, token = auth.split(':') if ':' in _netloc: domain, port = _netloc.split(':') port = int(port) else: domain = _netloc if scheme == 'https': port = 443 ...
[ "def", "parse_netloc", "(", "scheme", ",", "netloc", ")", ":", "auth", ",", "_netloc", "=", "netloc", ".", "split", "(", "'@'", ")", "sender", ",", "token", "=", "auth", ".", "split", "(", "':'", ")", "if", "':'", "in", "_netloc", ":", "domain", ",...
Parse netloc string.
[ "Parse", "netloc", "string", "." ]
train
https://github.com/soasme/rio-client/blob/c6d684c6f9deea5b43f2b05bcaf40714c48b5619/rio_client/parser.py#L9-L22
soasme/rio-client
rio_client/parser.py
parse_path
def parse_path(path): """Parse path string.""" version, project = path[1:].split('/') return dict(version=int(version), project=project)
python
def parse_path(path): """Parse path string.""" version, project = path[1:].split('/') return dict(version=int(version), project=project)
[ "def", "parse_path", "(", "path", ")", ":", "version", ",", "project", "=", "path", "[", "1", ":", "]", ".", "split", "(", "'/'", ")", "return", "dict", "(", "version", "=", "int", "(", "version", ")", ",", "project", "=", "project", ")" ]
Parse path string.
[ "Parse", "path", "string", "." ]
train
https://github.com/soasme/rio-client/blob/c6d684c6f9deea5b43f2b05bcaf40714c48b5619/rio_client/parser.py#L24-L27
soasme/rio-client
rio_client/parser.py
parse_dsn
def parse_dsn(dsn): """Parse dsn string.""" parsed_dsn = urlparse(dsn) parsed_path = parse_path(parsed_dsn.path) return { 'scheme': parsed_dsn.scheme, 'sender': parsed_dsn.username, 'token': parsed_dsn.password, 'domain': parsed_dsn.hostname, 'port': parsed_dsn.po...
python
def parse_dsn(dsn): """Parse dsn string.""" parsed_dsn = urlparse(dsn) parsed_path = parse_path(parsed_dsn.path) return { 'scheme': parsed_dsn.scheme, 'sender': parsed_dsn.username, 'token': parsed_dsn.password, 'domain': parsed_dsn.hostname, 'port': parsed_dsn.po...
[ "def", "parse_dsn", "(", "dsn", ")", ":", "parsed_dsn", "=", "urlparse", "(", "dsn", ")", "parsed_path", "=", "parse_path", "(", "parsed_dsn", ".", "path", ")", "return", "{", "'scheme'", ":", "parsed_dsn", ".", "scheme", ",", "'sender'", ":", "parsed_dsn"...
Parse dsn string.
[ "Parse", "dsn", "string", "." ]
train
https://github.com/soasme/rio-client/blob/c6d684c6f9deea5b43f2b05bcaf40714c48b5619/rio_client/parser.py#L29-L41
jldantas/libmft
libmft/api.py
MFTHeader.create_from_binary
def create_from_binary(cls, ignore_signature_check, binary_view): '''Creates a new object MFTHeader from a binary stream. The binary stream can be represented by a byte string, bytearray or a memoryview of the bytearray. Args: binary_view (memoryview of bytearray) - A binary...
python
def create_from_binary(cls, ignore_signature_check, binary_view): '''Creates a new object MFTHeader from a binary stream. The binary stream can be represented by a byte string, bytearray or a memoryview of the bytearray. Args: binary_view (memoryview of bytearray) - A binary...
[ "def", "create_from_binary", "(", "cls", ",", "ignore_signature_check", ",", "binary_view", ")", ":", "sig", ",", "fx_offset", ",", "fx_count", ",", "lsn", ",", "seq_number", ",", "hard_link_count", ",", "first_attr_offset", ",", "usage_flags", ",", "entry_len", ...
Creates a new object MFTHeader from a binary stream. The binary stream can be represented by a byte string, bytearray or a memoryview of the bytearray. Args: binary_view (memoryview of bytearray) - A binary stream with the information of the attribute Return...
[ "Creates", "a", "new", "object", "MFTHeader", "from", "a", "binary", "stream", ".", "The", "binary", "stream", "can", "be", "represented", "by", "a", "byte", "string", "bytearray", "or", "a", "memoryview", "of", "the", "bytearray", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L279-L316
jldantas/libmft
libmft/api.py
Datastream._get_dataruns
def _get_dataruns(self): '''Returns a list of dataruns, in order. ''' if self._data_runs is None: raise DataStreamError("Resident datastream don't have dataruns") if not self._data_runs_sorted: self._data_runs.sort(key=_itemgetter(0)) self._data_runs_...
python
def _get_dataruns(self): '''Returns a list of dataruns, in order. ''' if self._data_runs is None: raise DataStreamError("Resident datastream don't have dataruns") if not self._data_runs_sorted: self._data_runs.sort(key=_itemgetter(0)) self._data_runs_...
[ "def", "_get_dataruns", "(", "self", ")", ":", "if", "self", ".", "_data_runs", "is", "None", ":", "raise", "DataStreamError", "(", "\"Resident datastream don't have dataruns\"", ")", "if", "not", "self", ".", "_data_runs_sorted", ":", "self", ".", "_data_runs", ...
Returns a list of dataruns, in order.
[ "Returns", "a", "list", "of", "dataruns", "in", "order", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L389-L399
jldantas/libmft
libmft/api.py
Datastream.add_data_attribute
def add_data_attribute(self, data_attr): '''Interprets a DATA attribute and add it to the datastream.''' if data_attr.header.attr_type_id is not AttrTypes.DATA: raise DataStreamError("Invalid attribute. A Datastream deals only with DATA attributes") if data_attr.header.attr_name != s...
python
def add_data_attribute(self, data_attr): '''Interprets a DATA attribute and add it to the datastream.''' if data_attr.header.attr_type_id is not AttrTypes.DATA: raise DataStreamError("Invalid attribute. A Datastream deals only with DATA attributes") if data_attr.header.attr_name != s...
[ "def", "add_data_attribute", "(", "self", ",", "data_attr", ")", ":", "if", "data_attr", ".", "header", ".", "attr_type_id", "is", "not", "AttrTypes", ".", "DATA", ":", "raise", "DataStreamError", "(", "\"Invalid attribute. A Datastream deals only with DATA attributes\"...
Interprets a DATA attribute and add it to the datastream.
[ "Interprets", "a", "DATA", "attribute", "and", "add", "it", "to", "the", "datastream", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L405-L427
jldantas/libmft
libmft/api.py
Datastream.add_from_datastream
def add_from_datastream(self, source_ds): '''Add information from another datastream. Verifies if the datastream added is correct and copy the relevant fields if necessary.''' if source_ds.name != self.name: raise DataStreamError("Data from a different stream 'f{source_ds.name}' cann...
python
def add_from_datastream(self, source_ds): '''Add information from another datastream. Verifies if the datastream added is correct and copy the relevant fields if necessary.''' if source_ds.name != self.name: raise DataStreamError("Data from a different stream 'f{source_ds.name}' cann...
[ "def", "add_from_datastream", "(", "self", ",", "source_ds", ")", ":", "if", "source_ds", ".", "name", "!=", "self", ".", "name", ":", "raise", "DataStreamError", "(", "\"Data from a different stream 'f{source_ds.name}' cannot be add to this stream\"", ")", "if", "self"...
Add information from another datastream. Verifies if the datastream added is correct and copy the relevant fields if necessary.
[ "Add", "information", "from", "another", "datastream", ".", "Verifies", "if", "the", "datastream", "added", "is", "correct", "and", "copy", "the", "relevant", "fields", "if", "necessary", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L429-L444
jldantas/libmft
libmft/api.py
MFTEntry.create_from_binary
def create_from_binary(cls, mft_config, binary_data, entry_number): #TODO test carefully how to find the correct index entry, specially with NTFS versions < 3 '''Creates a MFTEntry from a binary stream. It correctly process the binary data extracting the MFTHeader, all the attributes and the ...
python
def create_from_binary(cls, mft_config, binary_data, entry_number): #TODO test carefully how to find the correct index entry, specially with NTFS versions < 3 '''Creates a MFTEntry from a binary stream. It correctly process the binary data extracting the MFTHeader, all the attributes and the ...
[ "def", "create_from_binary", "(", "cls", ",", "mft_config", ",", "binary_data", ",", "entry_number", ")", ":", "#TODO test carefully how to find the correct index entry, specially with NTFS versions < 3", "bin_view", "=", "memoryview", "(", "binary_data", ")", "entry", "=", ...
Creates a MFTEntry from a binary stream. It correctly process the binary data extracting the MFTHeader, all the attributes and the slack information from the binary stream. The binary data WILL be changed to apply the fixup array. Args: mft_config (:obj:`MFTConfig`) - An in...
[ "Creates", "a", "MFTEntry", "from", "a", "binary", "stream", ".", "It", "correctly", "process", "the", "binary", "data", "extracting", "the", "MFTHeader", "all", "the", "attributes", "and", "the", "slack", "information", "from", "the", "binary", "stream", "." ...
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L588-L632
jldantas/libmft
libmft/api.py
MFTEntry._find_datastream
def _find_datastream(self, name): """Find and return if a datastream exists, by name.""" for stream in self.data_streams: #search to see if this is a new datastream or a known one if stream.name == name: return stream return None
python
def _find_datastream(self, name): """Find and return if a datastream exists, by name.""" for stream in self.data_streams: #search to see if this is a new datastream or a known one if stream.name == name: return stream return None
[ "def", "_find_datastream", "(", "self", ",", "name", ")", ":", "for", "stream", "in", "self", ".", "data_streams", ":", "#search to see if this is a new datastream or a known one", "if", "stream", ".", "name", "==", "name", ":", "return", "stream", "return", "None...
Find and return if a datastream exists, by name.
[ "Find", "and", "return", "if", "a", "datastream", "exists", "by", "name", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L634-L639
jldantas/libmft
libmft/api.py
MFTEntry._add_data_attribute
def _add_data_attribute(self, data_attr): """Add a data attribute to the datastream structure. Data attributes require processing before they can be interpreted as datastream. This function grants that it is adding the attribute to the correct datastream or creating a new datastream if ...
python
def _add_data_attribute(self, data_attr): """Add a data attribute to the datastream structure. Data attributes require processing before they can be interpreted as datastream. This function grants that it is adding the attribute to the correct datastream or creating a new datastream if ...
[ "def", "_add_data_attribute", "(", "self", ",", "data_attr", ")", ":", "attr_name", "=", "data_attr", ".", "header", ".", "attr_name", "stream", "=", "self", ".", "_find_datastream", "(", "attr_name", ")", "if", "stream", "is", "None", ":", "stream", "=", ...
Add a data attribute to the datastream structure. Data attributes require processing before they can be interpreted as datastream. This function grants that it is adding the attribute to the correct datastream or creating a new datastream if necessary.
[ "Add", "a", "data", "attribute", "to", "the", "datastream", "structure", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L641-L654
jldantas/libmft
libmft/api.py
MFTEntry._load_attributes
def _load_attributes(self, mft_config, attrs_view): '''Loads all the attributes of an entry. Once executed, all the attributes should have been loaded in the attribute *attrs* instance attribute. Args: mft_config (:obj:`MFTConfig`) - An instance of MFTConfig, as this tells ...
python
def _load_attributes(self, mft_config, attrs_view): '''Loads all the attributes of an entry. Once executed, all the attributes should have been loaded in the attribute *attrs* instance attribute. Args: mft_config (:obj:`MFTConfig`) - An instance of MFTConfig, as this tells ...
[ "def", "_load_attributes", "(", "self", ",", "mft_config", ",", "attrs_view", ")", ":", "offset", "=", "0", "load_attrs", "=", "mft_config", ".", "attribute_load_list", "while", "(", "attrs_view", "[", "offset", ":", "offset", "+", "4", "]", "!=", "b'\\xff\\...
Loads all the attributes of an entry. Once executed, all the attributes should have been loaded in the attribute *attrs* instance attribute. Args: mft_config (:obj:`MFTConfig`) - An instance of MFTConfig, as this tells how the library will interpret data. ...
[ "Loads", "all", "the", "attributes", "of", "an", "entry", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L656-L681
jldantas/libmft
libmft/api.py
MFTEntry.merge_entries
def merge_entries(self, source_entry): '''Merge two entries. Allow the merging of two MFTEntries copying the attributes to the correct place and the datastreams. Args: source_entry (:obj:`MFTEntry`) - Source entry where the data will be copied from '...
python
def merge_entries(self, source_entry): '''Merge two entries. Allow the merging of two MFTEntries copying the attributes to the correct place and the datastreams. Args: source_entry (:obj:`MFTEntry`) - Source entry where the data will be copied from '...
[ "def", "merge_entries", "(", "self", ",", "source_entry", ")", ":", "#TODO should we change this to an overloaded iadd?", "#TODO I really don't like this. We are spending cycles to load things that are going to be discarted. Check another way.", "#copy the attributes", "for", "list_attr", ...
Merge two entries. Allow the merging of two MFTEntries copying the attributes to the correct place and the datastreams. Args: source_entry (:obj:`MFTEntry`) - Source entry where the data will be copied from
[ "Merge", "two", "entries", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L683-L705
jldantas/libmft
libmft/api.py
MFTEntry.get_datastream_names
def get_datastream_names(self): '''Returns a set with the datastream names. If there is no datastream, returns None ''' ads_names = set() for stream in self.data_streams: ads_names.add(stream.name) if len(ads_names): return ads_names else...
python
def get_datastream_names(self): '''Returns a set with the datastream names. If there is no datastream, returns None ''' ads_names = set() for stream in self.data_streams: ads_names.add(stream.name) if len(ads_names): return ads_names else...
[ "def", "get_datastream_names", "(", "self", ")", ":", "ads_names", "=", "set", "(", ")", "for", "stream", "in", "self", ".", "data_streams", ":", "ads_names", ".", "add", "(", "stream", ".", "name", ")", "if", "len", "(", "ads_names", ")", ":", "return...
Returns a set with the datastream names. If there is no datastream, returns None
[ "Returns", "a", "set", "with", "the", "datastream", "names", ".", "If", "there", "is", "no", "datastream", "returns", "None" ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L743-L755
jldantas/libmft
libmft/api.py
MFTEntry.get_main_filename_attr
def get_main_filename_attr(self): '''Returns the main filename attribute of the entry. As an entry can have multiple FILENAME attributes, this function allows to return the main one, i.e., the one with the lowest attribute id and the "biggest" namespace. ''' fn_attrs = s...
python
def get_main_filename_attr(self): '''Returns the main filename attribute of the entry. As an entry can have multiple FILENAME attributes, this function allows to return the main one, i.e., the one with the lowest attribute id and the "biggest" namespace. ''' fn_attrs = s...
[ "def", "get_main_filename_attr", "(", "self", ")", ":", "fn_attrs", "=", "self", ".", "get_attributes", "(", "AttrTypes", ".", "FILE_NAME", ")", "high_attr_id", "=", "0xFFFFFFFF", "main_fn", "=", "None", "if", "fn_attrs", "is", "not", "None", ":", "#search for...
Returns the main filename attribute of the entry. As an entry can have multiple FILENAME attributes, this function allows to return the main one, i.e., the one with the lowest attribute id and the "biggest" namespace.
[ "Returns", "the", "main", "filename", "attribute", "of", "the", "entry", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L757-L783
jldantas/libmft
libmft/api.py
MFT._load_relationship_info
def _load_relationship_info(self): """Maps parent and child entries in the MFT. Because the library expects the MFT file to be provided, it doesn't have access to anything non-resident. Because of that, if we want all the information related to the entry, it is necessary to visit all th...
python
def _load_relationship_info(self): """Maps parent and child entries in the MFT. Because the library expects the MFT file to be provided, it doesn't have access to anything non-resident. Because of that, if we want all the information related to the entry, it is necessary to visit all th...
[ "def", "_load_relationship_info", "(", "self", ")", ":", "mft_entry_size", "=", "self", ".", "mft_entry_size", "fp", "=", "self", ".", "file_pointer", "record_n", "=", "0", "#define the minimum amount that needs to be read", "base_struct", "=", "struct", ".", "Struct"...
Maps parent and child entries in the MFT. Because the library expects the MFT file to be provided, it doesn't have access to anything non-resident. Because of that, if we want all the information related to the entry, it is necessary to visit all the entries and map the relationship bet...
[ "Maps", "parent", "and", "child", "entries", "in", "the", "MFT", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L841-L881
jldantas/libmft
libmft/api.py
MFT._compute_full_path
def _compute_full_path(self, fn_parent_ref, fn_parent_seq): '''Based on the parent reference and sequence, computes the full path. The majority of the files in a filesystem has a very small amount of parent directories. By definition, a filesystem is expected to have much smaller amount...
python
def _compute_full_path(self, fn_parent_ref, fn_parent_seq): '''Based on the parent reference and sequence, computes the full path. The majority of the files in a filesystem has a very small amount of parent directories. By definition, a filesystem is expected to have much smaller amount...
[ "def", "_compute_full_path", "(", "self", ",", "fn_parent_ref", ",", "fn_parent_seq", ")", ":", "names", "=", "[", "]", "root_id", "=", "5", "index", ",", "seq", "=", "fn_parent_ref", ",", "fn_parent_seq", "is_orphan", "=", "False", "#search until hit the root e...
Based on the parent reference and sequence, computes the full path. The majority of the files in a filesystem has a very small amount of parent directories. By definition, a filesystem is expected to have much smaller amount of directories than files. As such we use a function with the ...
[ "Based", "on", "the", "parent", "reference", "and", "sequence", "computes", "the", "full", "path", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L903-L943
jldantas/libmft
libmft/api.py
MFT.get_full_path
def get_full_path(self, fn_attr): '''Returns the full path of a FILENAME. The NTFS filesystem allows for things called hardlinks. Hard links are saved, internally, as different filename attributes. Because of this, an entry can, when dealing with full paths, have multiple full paths. ...
python
def get_full_path(self, fn_attr): '''Returns the full path of a FILENAME. The NTFS filesystem allows for things called hardlinks. Hard links are saved, internally, as different filename attributes. Because of this, an entry can, when dealing with full paths, have multiple full paths. ...
[ "def", "get_full_path", "(", "self", ",", "fn_attr", ")", ":", "if", "fn_attr", ".", "header", ".", "attr_type_id", "is", "not", "AttrTypes", ".", "FILE_NAME", ":", "raise", "MFTError", "(", "\"Need a filename attribute to compute full path.\"", ")", "orphan", ","...
Returns the full path of a FILENAME. The NTFS filesystem allows for things called hardlinks. Hard links are saved, internally, as different filename attributes. Because of this, an entry can, when dealing with full paths, have multiple full paths. As such, this function receives a fn_a...
[ "Returns", "the", "full", "path", "of", "a", "FILENAME", "." ]
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L946-L972
radjkarl/appBase
appbase/mainWindowRessources/menubar.py
MenuBar.setFullscreen
def setFullscreen(self, fullscreen): """toggle between fullscreen and normal window""" if not fullscreen: self.ckBox_fullscreen.setChecked(False) self.parent().showNormal() else: self.ckBox_fullscreen.setChecked(True) self.parent().showFullS...
python
def setFullscreen(self, fullscreen): """toggle between fullscreen and normal window""" if not fullscreen: self.ckBox_fullscreen.setChecked(False) self.parent().showNormal() else: self.ckBox_fullscreen.setChecked(True) self.parent().showFullS...
[ "def", "setFullscreen", "(", "self", ",", "fullscreen", ")", ":", "if", "not", "fullscreen", ":", "self", ".", "ckBox_fullscreen", ".", "setChecked", "(", "False", ")", "self", ".", "parent", "(", ")", ".", "showNormal", "(", ")", "else", ":", "self", ...
toggle between fullscreen and normal window
[ "toggle", "between", "fullscreen", "and", "normal", "window" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/mainWindowRessources/menubar.py#L165-L172
dhain/potpy
potpy/template.py
Template.match
def match(self, string): """Match a string against the template. If the string matches the template, return a dict mapping template parameter names to converted values, otherwise return ``None``. >>> t = Template('Hello my name is {name}!') >>> t.match('Hello my name is David!'...
python
def match(self, string): """Match a string against the template. If the string matches the template, return a dict mapping template parameter names to converted values, otherwise return ``None``. >>> t = Template('Hello my name is {name}!') >>> t.match('Hello my name is David!'...
[ "def", "match", "(", "self", ",", "string", ")", ":", "m", "=", "self", ".", "regex", ".", "match", "(", "string", ")", "if", "m", ":", "c", "=", "self", ".", "type_converters", "return", "dict", "(", "(", "k", ",", "c", "[", "k", "]", "(", "...
Match a string against the template. If the string matches the template, return a dict mapping template parameter names to converted values, otherwise return ``None``. >>> t = Template('Hello my name is {name}!') >>> t.match('Hello my name is David!') {'name': 'David'} ...
[ "Match", "a", "string", "against", "the", "template", "." ]
train
https://github.com/dhain/potpy/blob/e39a5a84f763fbf144b07a620afb02a5ff3741c9/potpy/template.py#L103-L119
svetlyak40wt/twiggy-goodies
twiggy_goodies/django_rq.py
job
def job(func_or_queue, connection=None, *args, **kwargs): """This decorator does all what django_rq's one, plus it group all logged messages using uuid and sets job_name field as well.""" decorated_func = _job(func_or_queue, connection=connection, *args, **kwargs) if callable(func_or_queue): ...
python
def job(func_or_queue, connection=None, *args, **kwargs): """This decorator does all what django_rq's one, plus it group all logged messages using uuid and sets job_name field as well.""" decorated_func = _job(func_or_queue, connection=connection, *args, **kwargs) if callable(func_or_queue): ...
[ "def", "job", "(", "func_or_queue", ",", "connection", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "decorated_func", "=", "_job", "(", "func_or_queue", ",", "connection", "=", "connection", ",", "*", "args", ",", "*", "*", "kwargs...
This decorator does all what django_rq's one, plus it group all logged messages using uuid and sets job_name field as well.
[ "This", "decorator", "does", "all", "what", "django_rq", "s", "one", "plus", "it", "group", "all", "logged", "messages", "using", "uuid", "and", "sets", "job_name", "field", "as", "well", "." ]
train
https://github.com/svetlyak40wt/twiggy-goodies/blob/71528d5959fab81eb8d0e4373f20d37a013ac00e/twiggy_goodies/django_rq.py#L10-L32
chrisdrackett/django-support
support/templatetags/support_tags.py
active
def active(parser, token): """ tag to determine if a link is to the current page, and if it is, sets 'link_active' to True in the context. Use: {% active path view strict[True,False] arg1 arg2 arg3 %} path: the path to check. Generally this is just 'request.path' ...
python
def active(parser, token): """ tag to determine if a link is to the current page, and if it is, sets 'link_active' to True in the context. Use: {% active path view strict[True,False] arg1 arg2 arg3 %} path: the path to check. Generally this is just 'request.path' ...
[ "def", "active", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "path", "=", "args", "[", "1", "]", "view", "=", "args", "[", "2", "]", ".", "replace", "(", "'\"'", ",", "''", ")", ".", "replace", ...
tag to determine if a link is to the current page, and if it is, sets 'link_active' to True in the context. Use: {% active path view strict[True,False] arg1 arg2 arg3 %} path: the path to check. Generally this is just 'request.path' view: the view that you want ...
[ "tag", "to", "determine", "if", "a", "link", "is", "to", "the", "current", "page", "and", "if", "it", "is", "sets", "link_active", "to", "True", "in", "the", "context", "." ]
train
https://github.com/chrisdrackett/django-support/blob/a4f29421a31797e0b069637a0afec85328b4f0ca/support/templatetags/support_tags.py#L22-L55
chrisdrackett/django-support
support/templatetags/support_tags.py
do_truncate
def do_truncate(parser, token): """ Truncates given text (html-aware) Sample usage:: {% truncate 60 %} {{ some_text }} {% more %} <a href="asdasd">Read more..</a> {% endtruncate %} """ _, count = token.split_contents() nodelist = parser.parse((...
python
def do_truncate(parser, token): """ Truncates given text (html-aware) Sample usage:: {% truncate 60 %} {{ some_text }} {% more %} <a href="asdasd">Read more..</a> {% endtruncate %} """ _, count = token.split_contents() nodelist = parser.parse((...
[ "def", "do_truncate", "(", "parser", ",", "token", ")", ":", "_", ",", "count", "=", "token", ".", "split_contents", "(", ")", "nodelist", "=", "parser", ".", "parse", "(", "(", "'more'", ",", "'endtruncate'", ",", ")", ")", "token", "=", "parser", "...
Truncates given text (html-aware) Sample usage:: {% truncate 60 %} {{ some_text }} {% more %} <a href="asdasd">Read more..</a> {% endtruncate %}
[ "Truncates", "given", "text", "(", "html", "-", "aware", ")", "Sample", "usage", "::" ]
train
https://github.com/chrisdrackett/django-support/blob/a4f29421a31797e0b069637a0afec85328b4f0ca/support/templatetags/support_tags.py#L133-L153
chrisdrackett/django-support
support/templatetags/support_tags.py
full_width_svg
def full_width_svg(url, width, height, alt_text=None): ''' Helper to render an SVG that will size to fill its element while keeping its dimentions. ''' return { 'ratio': str((float(height)/float(width))*100)[:2], 'url': url, 'alt_text': alt_text }
python
def full_width_svg(url, width, height, alt_text=None): ''' Helper to render an SVG that will size to fill its element while keeping its dimentions. ''' return { 'ratio': str((float(height)/float(width))*100)[:2], 'url': url, 'alt_text': alt_text }
[ "def", "full_width_svg", "(", "url", ",", "width", ",", "height", ",", "alt_text", "=", "None", ")", ":", "return", "{", "'ratio'", ":", "str", "(", "(", "float", "(", "height", ")", "/", "float", "(", "width", ")", ")", "*", "100", ")", "[", ":"...
Helper to render an SVG that will size to fill its element while keeping its dimentions.
[ "Helper", "to", "render", "an", "SVG", "that", "will", "size", "to", "fill", "its", "element", "while", "keeping", "its", "dimentions", "." ]
train
https://github.com/chrisdrackett/django-support/blob/a4f29421a31797e0b069637a0afec85328b4f0ca/support/templatetags/support_tags.py#L160-L170
minhhoit/yacms
yacms/template/loader_tags.py
overextends
def overextends(parser, token): """ Extended version of Django's ``extends`` tag that allows circular inheritance to occur, eg a template can both be overridden and extended at once. """ if DJANGO_VERSION >= (1, 9): warnings.warn( "The `overextends` template tag is deprecated...
python
def overextends(parser, token): """ Extended version of Django's ``extends`` tag that allows circular inheritance to occur, eg a template can both be overridden and extended at once. """ if DJANGO_VERSION >= (1, 9): warnings.warn( "The `overextends` template tag is deprecated...
[ "def", "overextends", "(", "parser", ",", "token", ")", ":", "if", "DJANGO_VERSION", ">=", "(", "1", ",", "9", ")", ":", "warnings", ".", "warn", "(", "\"The `overextends` template tag is deprecated in favour of \"", "\"Django's built-in `extends` tag, which supports recu...
Extended version of Django's ``extends`` tag that allows circular inheritance to occur, eg a template can both be overridden and extended at once.
[ "Extended", "version", "of", "Django", "s", "extends", "tag", "that", "allows", "circular", "inheritance", "to", "occur", "eg", "a", "template", "can", "both", "be", "overridden", "and", "extended", "at", "once", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/template/loader_tags.py#L122-L144
minhhoit/yacms
yacms/template/loader_tags.py
OverExtendsNode.find_template
def find_template(self, name, context, peeking=False): """ Replacement for Django's ``find_template`` that uses the current template context to keep track of which template directories it has used when finding a template. This allows multiple templates with the same relative name...
python
def find_template(self, name, context, peeking=False): """ Replacement for Django's ``find_template`` that uses the current template context to keep track of which template directories it has used when finding a template. This allows multiple templates with the same relative name...
[ "def", "find_template", "(", "self", ",", "name", ",", "context", ",", "peeking", "=", "False", ")", ":", "# These imports want settings, which aren't available when this", "# module is imported to ``add_to_builtins``, so do them here.", "import", "django", ".", "template", "...
Replacement for Django's ``find_template`` that uses the current template context to keep track of which template directories it has used when finding a template. This allows multiple templates with the same relative name/path to be discovered, so that circular template inheritance can o...
[ "Replacement", "for", "Django", "s", "find_template", "that", "uses", "the", "current", "template", "context", "to", "keep", "track", "of", "which", "template", "directories", "it", "has", "used", "when", "finding", "a", "template", ".", "This", "allows", "mul...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/template/loader_tags.py#L41-L98
mirceaulinic/pypluribus
pyPluribus/device.py
PluribusDevice.open
def open(self): """Opens a SSH connection with a Pluribus machine.""" self._connection = paramiko.SSHClient() self._connection.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self._connection.connect(hostname=self._hostname, use...
python
def open(self): """Opens a SSH connection with a Pluribus machine.""" self._connection = paramiko.SSHClient() self._connection.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self._connection.connect(hostname=self._hostname, use...
[ "def", "open", "(", "self", ")", ":", "self", ".", "_connection", "=", "paramiko", ".", "SSHClient", "(", ")", "self", ".", "_connection", ".", "set_missing_host_key_policy", "(", "paramiko", ".", "AutoAddPolicy", "(", ")", ")", "try", ":", "self", ".", ...
Opens a SSH connection with a Pluribus machine.
[ "Opens", "a", "SSH", "connection", "with", "a", "Pluribus", "machine", "." ]
train
https://github.com/mirceaulinic/pypluribus/blob/99bb9b6de40a0e465e3f0e6636b26acdeabbbd90/pyPluribus/device.py#L57-L78
mirceaulinic/pypluribus
pyPluribus/device.py
PluribusDevice.close
def close(self): """Closes the SSH connection if the connection is UP.""" if not self.connected: return None if self.config is not None: if self.config.changed() and not self.config.committed(): try: self.config.discard() # if configur...
python
def close(self): """Closes the SSH connection if the connection is UP.""" if not self.connected: return None if self.config is not None: if self.config.changed() and not self.config.committed(): try: self.config.discard() # if configur...
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "connected", ":", "return", "None", "if", "self", ".", "config", "is", "not", "None", ":", "if", "self", ".", "config", ".", "changed", "(", ")", "and", "not", "self", ".", "config", ...
Closes the SSH connection if the connection is UP.
[ "Closes", "the", "SSH", "connection", "if", "the", "connection", "is", "UP", "." ]
train
https://github.com/mirceaulinic/pypluribus/blob/99bb9b6de40a0e465e3f0e6636b26acdeabbbd90/pyPluribus/device.py#L80-L94
mirceaulinic/pypluribus
pyPluribus/device.py
PluribusDevice.cli
def cli(self, command): """ Executes a command and returns raw output from the CLI. :param command: Command to be executed on the CLI. :raise pyPluribus.exceptions.TimeoutError: when execution of the command exceeds the timeout :raise pyPluribus.exceptions.CommandExecutionError:...
python
def cli(self, command): """ Executes a command and returns raw output from the CLI. :param command: Command to be executed on the CLI. :raise pyPluribus.exceptions.TimeoutError: when execution of the command exceeds the timeout :raise pyPluribus.exceptions.CommandExecutionError:...
[ "def", "cli", "(", "self", ",", "command", ")", ":", "if", "not", "self", ".", "connected", ":", "raise", "pyPluribus", ".", "exceptions", ".", "ConnectionError", "(", "\"Not connected to the deivce.\"", ")", "cli_output", "=", "''", "ssh_session", "=", "self"...
Executes a command and returns raw output from the CLI. :param command: Command to be executed on the CLI. :raise pyPluribus.exceptions.TimeoutError: when execution of the command exceeds the timeout :raise pyPluribus.exceptions.CommandExecutionError: when not able to retrieve the output ...
[ "Executes", "a", "command", "and", "returns", "raw", "output", "from", "the", "CLI", "." ]
train
https://github.com/mirceaulinic/pypluribus/blob/99bb9b6de40a0e465e3f0e6636b26acdeabbbd90/pyPluribus/device.py#L98-L145
mirceaulinic/pypluribus
pyPluribus/device.py
PluribusDevice.execute_show
def execute_show(self, show_command, delim=';'): """ Executes show-type commands on the CLI and returns parsable output usinng ';' as delimitor. :param show_command: Show command to be executed :param delim: Will use specific delimitor. Default: ';' :raise pyPluribus.exceptions....
python
def execute_show(self, show_command, delim=';'): """ Executes show-type commands on the CLI and returns parsable output usinng ';' as delimitor. :param show_command: Show command to be executed :param delim: Will use specific delimitor. Default: ';' :raise pyPluribus.exceptions....
[ "def", "execute_show", "(", "self", ",", "show_command", ",", "delim", "=", "';'", ")", ":", "if", "not", "show_command", ".", "endswith", "(", "'-show'", ")", ":", "raise", "pyPluribus", ".", "exceptions", ".", "CommandExecutionError", "(", "'All show command...
Executes show-type commands on the CLI and returns parsable output usinng ';' as delimitor. :param show_command: Show command to be executed :param delim: Will use specific delimitor. Default: ';' :raise pyPluribus.exceptions.TimeoutError: when execution of the command exceeds the timeout ...
[ "Executes", "show", "-", "type", "commands", "on", "the", "CLI", "and", "returns", "parsable", "output", "usinng", ";", "as", "delimitor", "." ]
train
https://github.com/mirceaulinic/pypluribus/blob/99bb9b6de40a0e465e3f0e6636b26acdeabbbd90/pyPluribus/device.py#L147-L176
mirceaulinic/pypluribus
pyPluribus/device.py
PluribusDevice.show
def show(self, command, delim=';'): """ Executes show-type commands on the CLI and returns parsable output usinng ';' as delimitor. :param command: Command to be executed :param delim: Custom delimiter. Default value: ';' :raise pyPluribus.exceptions.TimeoutError: when execution...
python
def show(self, command, delim=';'): """ Executes show-type commands on the CLI and returns parsable output usinng ';' as delimitor. :param command: Command to be executed :param delim: Custom delimiter. Default value: ';' :raise pyPluribus.exceptions.TimeoutError: when execution...
[ "def", "show", "(", "self", ",", "command", ",", "delim", "=", "';'", ")", ":", "if", "not", "command", ".", "endswith", "(", "'-show'", ")", ":", "command", "+=", "'-show'", "command", "=", "command", ".", "replace", "(", "' '", ",", "'-'", ")", "...
Executes show-type commands on the CLI and returns parsable output usinng ';' as delimitor. :param command: Command to be executed :param delim: Custom delimiter. Default value: ';' :raise pyPluribus.exceptions.TimeoutError: when execution of the command exceeds the timeout :raise pyPlu...
[ "Executes", "show", "-", "type", "commands", "on", "the", "CLI", "and", "returns", "parsable", "output", "usinng", ";", "as", "delimitor", "." ]
train
https://github.com/mirceaulinic/pypluribus/blob/99bb9b6de40a0e465e3f0e6636b26acdeabbbd90/pyPluribus/device.py#L178-L200
OpenGov/python_data_wrap
datawrap/tableloader.py
read
def read(file_name, file_contents=None, on_demand=False): ''' Loads an arbitrary file type (xlsx, xls, or csv like) and returns a list of 2D tables. For csv files this will be a list of one table, but excel formats can have many tables/worksheets. TODO: Add wrapper which can be closed/exite...
python
def read(file_name, file_contents=None, on_demand=False): ''' Loads an arbitrary file type (xlsx, xls, or csv like) and returns a list of 2D tables. For csv files this will be a list of one table, but excel formats can have many tables/worksheets. TODO: Add wrapper which can be closed/exite...
[ "def", "read", "(", "file_name", ",", "file_contents", "=", "None", ",", "on_demand", "=", "False", ")", ":", "try", ":", "if", "re", ".", "search", "(", "XML_EXT_REGEX", ",", "file_name", ")", ":", "return", "get_data_excel_xml", "(", "file_name", ",", ...
Loads an arbitrary file type (xlsx, xls, or csv like) and returns a list of 2D tables. For csv files this will be a list of one table, but excel formats can have many tables/worksheets. TODO: Add wrapper which can be closed/exited on each file type which cleans up the file handler. Arg...
[ "Loads", "an", "arbitrary", "file", "type", "(", "xlsx", "xls", "or", "csv", "like", ")", "and", "returns", "a", "list", "of", "2D", "tables", ".", "For", "csv", "files", "this", "will", "be", "a", "list", "of", "one", "table", "but", "excel", "forma...
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/tableloader.py#L16-L51
OpenGov/python_data_wrap
datawrap/tableloader.py
get_data_xlsx
def get_data_xlsx(file_name, file_contents=None, on_demand=False): ''' Loads the new excel format files. Old format files will automatically get loaded as well. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. ...
python
def get_data_xlsx(file_name, file_contents=None, on_demand=False): ''' Loads the new excel format files. Old format files will automatically get loaded as well. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. ...
[ "def", "get_data_xlsx", "(", "file_name", ",", "file_contents", "=", "None", ",", "on_demand", "=", "False", ")", ":", "return", "get_data_xls", "(", "file_name", ",", "file_contents", "=", "file_contents", ",", "on_demand", "=", "on_demand", ")" ]
Loads the new excel format files. Old format files will automatically get loaded as well. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents of file_name. ...
[ "Loads", "the", "new", "excel", "format", "files", ".", "Old", "format", "files", "will", "automatically", "get", "loaded", "as", "well", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/tableloader.py#L53-L65
OpenGov/python_data_wrap
datawrap/tableloader.py
get_data_xls
def get_data_xls(file_name, file_contents=None, on_demand=False): ''' Loads the old excel format files. New format files will automatically get loaded as well. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. ...
python
def get_data_xls(file_name, file_contents=None, on_demand=False): ''' Loads the old excel format files. New format files will automatically get loaded as well. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. ...
[ "def", "get_data_xls", "(", "file_name", ",", "file_contents", "=", "None", ",", "on_demand", "=", "False", ")", ":", "def", "tuple_to_iso_date", "(", "tuple_date", ")", ":", "'''\n Turns a gregorian (year, month, day, hour, minute, nearest_second) into a\n stan...
Loads the old excel format files. New format files will automatically get loaded as well. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents of file_name. ...
[ "Loads", "the", "old", "excel", "format", "files", ".", "New", "format", "files", "will", "automatically", "get", "loaded", "as", "well", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/tableloader.py#L145-L210
OpenGov/python_data_wrap
datawrap/tableloader.py
get_data_excel_xml
def get_data_excel_xml(file_name, file_contents=None, on_demand=False): ''' Loads xml excel format files. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents o...
python
def get_data_excel_xml(file_name, file_contents=None, on_demand=False): ''' Loads xml excel format files. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents o...
[ "def", "get_data_excel_xml", "(", "file_name", ",", "file_contents", "=", "None", ",", "on_demand", "=", "False", ")", ":", "# NOTE this method is inefficient and uses code that's not of the highest quality", "if", "file_contents", ":", "xml_file", "=", "BytesIO", "(", "f...
Loads xml excel format files. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents of file_name. If left as None, then file_name is directly loaded. ...
[ "Loads", "xml", "excel", "format", "files", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/tableloader.py#L239-L258
OpenGov/python_data_wrap
datawrap/tableloader.py
get_data_csv
def get_data_csv(file_name, encoding='utf-8', file_contents=None, on_demand=False): ''' Gets good old csv data from a file. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. encoding: Loads the file with the sp...
python
def get_data_csv(file_name, encoding='utf-8', file_contents=None, on_demand=False): ''' Gets good old csv data from a file. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. encoding: Loads the file with the sp...
[ "def", "get_data_csv", "(", "file_name", ",", "encoding", "=", "'utf-8'", ",", "file_contents", "=", "None", ",", "on_demand", "=", "False", ")", ":", "def", "yield_csv", "(", "csv_contents", ",", "csv_file", ")", ":", "try", ":", "for", "line", "in", "c...
Gets good old csv data from a file. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. encoding: Loads the file with the specified cell encoding. file_contents: The file-like object holding contents of file_name...
[ "Gets", "good", "old", "csv", "data", "from", "a", "file", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/tableloader.py#L260-L298
OpenGov/python_data_wrap
datawrap/tableloader.py
write
def write(data, file_name, worksheet_names=None): ''' Writes 2D tables to file. Args: data: 2D list of tables/worksheets. file_name: Name of the output file (determines type). worksheet_names: A list of worksheet names (optional). ''' if re.search(XML_EXT_REGEX, file_name): ...
python
def write(data, file_name, worksheet_names=None): ''' Writes 2D tables to file. Args: data: 2D list of tables/worksheets. file_name: Name of the output file (determines type). worksheet_names: A list of worksheet names (optional). ''' if re.search(XML_EXT_REGEX, file_name): ...
[ "def", "write", "(", "data", ",", "file_name", ",", "worksheet_names", "=", "None", ")", ":", "if", "re", ".", "search", "(", "XML_EXT_REGEX", ",", "file_name", ")", ":", "return", "write_xml", "(", "data", ",", "file_name", ",", "worksheet_names", "=", ...
Writes 2D tables to file. Args: data: 2D list of tables/worksheets. file_name: Name of the output file (determines type). worksheet_names: A list of worksheet names (optional).
[ "Writes", "2D", "tables", "to", "file", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/tableloader.py#L300-L318
OpenGov/python_data_wrap
datawrap/tableloader.py
write_xls
def write_xls(data, file_name, worksheet_names=None): ''' Writes out to old excel format. Args: data: 2D list of tables/worksheets. file_name: Name of the output file. worksheet_names: A list of worksheet names (optional). ''' workbook = xlwt.Workbook() for sheet_index, ...
python
def write_xls(data, file_name, worksheet_names=None): ''' Writes out to old excel format. Args: data: 2D list of tables/worksheets. file_name: Name of the output file. worksheet_names: A list of worksheet names (optional). ''' workbook = xlwt.Workbook() for sheet_index, ...
[ "def", "write_xls", "(", "data", ",", "file_name", ",", "worksheet_names", "=", "None", ")", ":", "workbook", "=", "xlwt", ".", "Workbook", "(", ")", "for", "sheet_index", ",", "sheet_data", "in", "enumerate", "(", "data", ")", ":", "if", "worksheet_names"...
Writes out to old excel format. Args: data: 2D list of tables/worksheets. file_name: Name of the output file. worksheet_names: A list of worksheet names (optional).
[ "Writes", "out", "to", "old", "excel", "format", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/tableloader.py#L342-L361
OpenGov/python_data_wrap
datawrap/tableloader.py
write_csv
def write_csv(data, file_name, encoding='utf-8'): ''' Writes out to csv format. Args: data: 2D list of tables/worksheets. file_name: Name of the output file. ''' name_extension = len(data) > 1 root, ext = os.path.splitext(file_name) for i, sheet in enumerate(data): ...
python
def write_csv(data, file_name, encoding='utf-8'): ''' Writes out to csv format. Args: data: 2D list of tables/worksheets. file_name: Name of the output file. ''' name_extension = len(data) > 1 root, ext = os.path.splitext(file_name) for i, sheet in enumerate(data): ...
[ "def", "write_csv", "(", "data", ",", "file_name", ",", "encoding", "=", "'utf-8'", ")", ":", "name_extension", "=", "len", "(", "data", ")", ">", "1", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "file_name", ")", "for", "i", ...
Writes out to csv format. Args: data: 2D list of tables/worksheets. file_name: Name of the output file.
[ "Writes", "out", "to", "csv", "format", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/tableloader.py#L363-L379
scdoshi/django-bits
bits/general.py
get_profile_model
def get_profile_model(): """ Return the model class for the currently-active user profile model, as defined by the ``AUTH_PROFILE_MODULE`` setting. :return: The model that is used as profile. """ if (not hasattr(settings, 'AUTH_PROFILE_MODULE') or not settings.AUTH_PROFILE_MODULE): ...
python
def get_profile_model(): """ Return the model class for the currently-active user profile model, as defined by the ``AUTH_PROFILE_MODULE`` setting. :return: The model that is used as profile. """ if (not hasattr(settings, 'AUTH_PROFILE_MODULE') or not settings.AUTH_PROFILE_MODULE): ...
[ "def", "get_profile_model", "(", ")", ":", "if", "(", "not", "hasattr", "(", "settings", ",", "'AUTH_PROFILE_MODULE'", ")", "or", "not", "settings", ".", "AUTH_PROFILE_MODULE", ")", ":", "raise", "SiteProfileNotAvailable", "profile_mod", "=", "get_model", "(", "...
Return the model class for the currently-active user profile model, as defined by the ``AUTH_PROFILE_MODULE`` setting. :return: The model that is used as profile.
[ "Return", "the", "model", "class", "for", "the", "currently", "-", "active", "user", "profile", "model", "as", "defined", "by", "the", "AUTH_PROFILE_MODULE", "setting", "." ]
train
https://github.com/scdoshi/django-bits/blob/0a2f4fd9374d2a8acb8df9a7b83eebcf2782256f/bits/general.py#L40-L54
scdoshi/django-bits
bits/general.py
get_group
def get_group(name): """ Return group with given name, if it exists. Check cache first. """ group = cache.get('bits.general.group_%s' % name) if not group: group = Group.objects.get(name=name) cache.set('bits.general.group_%s' % name, group, 365 * 24 * 60 * 60) return group
python
def get_group(name): """ Return group with given name, if it exists. Check cache first. """ group = cache.get('bits.general.group_%s' % name) if not group: group = Group.objects.get(name=name) cache.set('bits.general.group_%s' % name, group, 365 * 24 * 60 * 60) return group
[ "def", "get_group", "(", "name", ")", ":", "group", "=", "cache", ".", "get", "(", "'bits.general.group_%s'", "%", "name", ")", "if", "not", "group", ":", "group", "=", "Group", ".", "objects", ".", "get", "(", "name", "=", "name", ")", "cache", ".",...
Return group with given name, if it exists. Check cache first.
[ "Return", "group", "with", "given", "name", "if", "it", "exists", ".", "Check", "cache", "first", "." ]
train
https://github.com/scdoshi/django-bits/blob/0a2f4fd9374d2a8acb8df9a7b83eebcf2782256f/bits/general.py#L57-L65
abe-winter/pg13-py
pg13/sqex.py
evalop
def evalop(op,left,right): "this takes evaluated left and right (i.e. values not expressions)" if op in ('=','!=','>','<'): return threevl.ThreeVL.compare(op,left,right) elif op in ('+','-','*','/'): # todo: does arithmetic require threevl? if op=='/': raise NotImplementedError('todo: spec about int/float div...
python
def evalop(op,left,right): "this takes evaluated left and right (i.e. values not expressions)" if op in ('=','!=','>','<'): return threevl.ThreeVL.compare(op,left,right) elif op in ('+','-','*','/'): # todo: does arithmetic require threevl? if op=='/': raise NotImplementedError('todo: spec about int/float div...
[ "def", "evalop", "(", "op", ",", "left", ",", "right", ")", ":", "if", "op", "in", "(", "'='", ",", "'!='", ",", "'>'", ",", "'<'", ")", ":", "return", "threevl", ".", "ThreeVL", ".", "compare", "(", "op", ",", "left", ",", "right", ")", "elif"...
this takes evaluated left and right (i.e. values not expressions)
[ "this", "takes", "evaluated", "left", "and", "right", "(", "i", ".", "e", ".", "values", "not", "expressions", ")" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L16-L37
abe-winter/pg13-py
pg13/sqex.py
uniqify
def uniqify(list_): "inefficient on long lists; short lists only. preserves order." a=[] for x in list_: if x not in a: a.append(x) return a
python
def uniqify(list_): "inefficient on long lists; short lists only. preserves order." a=[] for x in list_: if x not in a: a.append(x) return a
[ "def", "uniqify", "(", "list_", ")", ":", "a", "=", "[", "]", "for", "x", "in", "list_", ":", "if", "x", "not", "in", "a", ":", "a", ".", "append", "(", "x", ")", "return", "a" ]
inefficient on long lists; short lists only. preserves order.
[ "inefficient", "on", "long", "lists", ";", "short", "lists", "only", ".", "preserves", "order", "." ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L39-L44
abe-winter/pg13-py
pg13/sqex.py
eliminate_sequential_children
def eliminate_sequential_children(paths): "helper for infer_columns. removes paths that are direct children of the n-1 or n-2 path" return [p for i,p in enumerate(paths) if not ((i>0 and paths[i-1]==p[:-1]) or (i>1 and paths[i-2]==p[:-1]))]
python
def eliminate_sequential_children(paths): "helper for infer_columns. removes paths that are direct children of the n-1 or n-2 path" return [p for i,p in enumerate(paths) if not ((i>0 and paths[i-1]==p[:-1]) or (i>1 and paths[i-2]==p[:-1]))]
[ "def", "eliminate_sequential_children", "(", "paths", ")", ":", "return", "[", "p", "for", "i", ",", "p", "in", "enumerate", "(", "paths", ")", "if", "not", "(", "(", "i", ">", "0", "and", "paths", "[", "i", "-", "1", "]", "==", "p", "[", ":", ...
helper for infer_columns. removes paths that are direct children of the n-1 or n-2 path
[ "helper", "for", "infer_columns", ".", "removes", "paths", "that", "are", "direct", "children", "of", "the", "n", "-", "1", "or", "n", "-", "2", "path" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L46-L48
abe-winter/pg13-py
pg13/sqex.py
infer_columns
def infer_columns(selectx,tables_dict): """infer the columns for a subselect that creates an implicit table. the output of this *can* contain duplicate names, fingers crossed that downstream code uses the first. (Look up SQL spec on dupe names.) todo(refactor): I think there's common logic here and inside NameI...
python
def infer_columns(selectx,tables_dict): """infer the columns for a subselect that creates an implicit table. the output of this *can* contain duplicate names, fingers crossed that downstream code uses the first. (Look up SQL spec on dupe names.) todo(refactor): I think there's common logic here and inside NameI...
[ "def", "infer_columns", "(", "selectx", ",", "tables_dict", ")", ":", "# todo: support CTEs -- with all this plumbing, might as well", "table2fields", "=", "{", "}", "table_order", "=", "[", "]", "for", "t", "in", "selectx", ".", "tables", ":", "if", "isinstance", ...
infer the columns for a subselect that creates an implicit table. the output of this *can* contain duplicate names, fingers crossed that downstream code uses the first. (Look up SQL spec on dupe names.) todo(refactor): I think there's common logic here and inside NameIndexer that can be merged. todo(ugly): this...
[ "infer", "the", "columns", "for", "a", "subselect", "that", "creates", "an", "implicit", "table", ".", "the", "output", "of", "this", "*", "can", "*", "contain", "duplicate", "names", "fingers", "crossed", "that", "downstream", "code", "uses", "the", "first"...
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L50-L96
abe-winter/pg13-py
pg13/sqex.py
decompose_select
def decompose_select(selectx): "return [(parent,setter) for scalar_subquery], wherex_including_on, NameIndexer. helper for run_select" nix = NameIndexer.ctor_fromlist(selectx.tables) where = [] for fromx in selectx.tables: if isinstance(fromx,sqparse2.JoinX) and fromx.on_stmt is not None: # todo: what...
python
def decompose_select(selectx): "return [(parent,setter) for scalar_subquery], wherex_including_on, NameIndexer. helper for run_select" nix = NameIndexer.ctor_fromlist(selectx.tables) where = [] for fromx in selectx.tables: if isinstance(fromx,sqparse2.JoinX) and fromx.on_stmt is not None: # todo: what...
[ "def", "decompose_select", "(", "selectx", ")", ":", "nix", "=", "NameIndexer", ".", "ctor_fromlist", "(", "selectx", ".", "tables", ")", "where", "=", "[", "]", "for", "fromx", "in", "selectx", ".", "tables", ":", "if", "isinstance", "(", "fromx", ",", ...
return [(parent,setter) for scalar_subquery], wherex_including_on, NameIndexer. helper for run_select
[ "return", "[", "(", "parent", "setter", ")", "for", "scalar_subquery", "]", "wherex_including_on", "NameIndexer", ".", "helper", "for", "run_select" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L170-L179
abe-winter/pg13-py
pg13/sqex.py
eval_where
def eval_where(where_list,composite_row,nix,tables_dict): "join-friendly whereclause evaluator. composite_row is a list or tuple of row lists. where_list is the thing from decompose_select." # todo: do I need to use 3vl instead of all() to merge where_list? evaluator = Evaluator(composite_row,nix,tables_dict) r...
python
def eval_where(where_list,composite_row,nix,tables_dict): "join-friendly whereclause evaluator. composite_row is a list or tuple of row lists. where_list is the thing from decompose_select." # todo: do I need to use 3vl instead of all() to merge where_list? evaluator = Evaluator(composite_row,nix,tables_dict) r...
[ "def", "eval_where", "(", "where_list", ",", "composite_row", ",", "nix", ",", "tables_dict", ")", ":", "# todo: do I need to use 3vl instead of all() to merge where_list?", "evaluator", "=", "Evaluator", "(", "composite_row", ",", "nix", ",", "tables_dict", ")", "retur...
join-friendly whereclause evaluator. composite_row is a list or tuple of row lists. where_list is the thing from decompose_select.
[ "join", "-", "friendly", "whereclause", "evaluator", ".", "composite_row", "is", "a", "list", "or", "tuple", "of", "row", "lists", ".", "where_list", "is", "the", "thing", "from", "decompose_select", "." ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L181-L185
abe-winter/pg13-py
pg13/sqex.py
replace_subqueries
def replace_subqueries(ex,tables,table_ctor): "this mutates passed in ex (any BaseX), replacing nested selects with their (flattened) output" # http://www.postgresql.org/docs/9.1/static/sql-expressions.html#SQL-SYNTAX-SCALAR-SUBQUERIES # see here for subquery conditions that *do* use multi-rows. ug. http://www.po...
python
def replace_subqueries(ex,tables,table_ctor): "this mutates passed in ex (any BaseX), replacing nested selects with their (flattened) output" # http://www.postgresql.org/docs/9.1/static/sql-expressions.html#SQL-SYNTAX-SCALAR-SUBQUERIES # see here for subquery conditions that *do* use multi-rows. ug. http://www.po...
[ "def", "replace_subqueries", "(", "ex", ",", "tables", ",", "table_ctor", ")", ":", "# http://www.postgresql.org/docs/9.1/static/sql-expressions.html#SQL-SYNTAX-SCALAR-SUBQUERIES", "# see here for subquery conditions that *do* use multi-rows. ug. http://www.postgresql.org/docs/9.1/static/funct...
this mutates passed in ex (any BaseX), replacing nested selects with their (flattened) output
[ "this", "mutates", "passed", "in", "ex", "(", "any", "BaseX", ")", "replacing", "nested", "selects", "with", "their", "(", "flattened", ")", "output" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L194-L203
abe-winter/pg13-py
pg13/sqex.py
collapse_group_expr
def collapse_group_expr(groupx,cols,ret_row): "collapses columns matching the group expression. I'm sure this is buggy; look at a real DB's imp of this." for i,col in enumerate(cols.children): if col==groupx: ret_row[i]=ret_row[i][0] return ret_row
python
def collapse_group_expr(groupx,cols,ret_row): "collapses columns matching the group expression. I'm sure this is buggy; look at a real DB's imp of this." for i,col in enumerate(cols.children): if col==groupx: ret_row[i]=ret_row[i][0] return ret_row
[ "def", "collapse_group_expr", "(", "groupx", ",", "cols", ",", "ret_row", ")", ":", "for", "i", ",", "col", "in", "enumerate", "(", "cols", ".", "children", ")", ":", "if", "col", "==", "groupx", ":", "ret_row", "[", "i", "]", "=", "ret_row", "[", ...
collapses columns matching the group expression. I'm sure this is buggy; look at a real DB's imp of this.
[ "collapses", "columns", "matching", "the", "group", "expression", ".", "I", "m", "sure", "this", "is", "buggy", ";", "look", "at", "a", "real", "DB", "s", "imp", "of", "this", "." ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L209-L213
abe-winter/pg13-py
pg13/sqex.py
starlike
def starlike(x): "weird things happen to cardinality when working with * in comma-lists. this detects when to do that." # todo: is '* as name' a thing? return isinstance(x,sqparse2.AsterX) or isinstance(x,sqparse2.AttrX) and isinstance(x.attr,sqparse2.AsterX)
python
def starlike(x): "weird things happen to cardinality when working with * in comma-lists. this detects when to do that." # todo: is '* as name' a thing? return isinstance(x,sqparse2.AsterX) or isinstance(x,sqparse2.AttrX) and isinstance(x.attr,sqparse2.AsterX)
[ "def", "starlike", "(", "x", ")", ":", "# todo: is '* as name' a thing?", "return", "isinstance", "(", "x", ",", "sqparse2", ".", "AsterX", ")", "or", "isinstance", "(", "x", ",", "sqparse2", ".", "AttrX", ")", "and", "isinstance", "(", "x", ".", "attr", ...
weird things happen to cardinality when working with * in comma-lists. this detects when to do that.
[ "weird", "things", "happen", "to", "cardinality", "when", "working", "with", "*", "in", "comma", "-", "lists", ".", "this", "detects", "when", "to", "do", "that", "." ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L248-L251
abe-winter/pg13-py
pg13/sqex.py
depth_first_sub
def depth_first_sub(expr,values): "replace SubLit with literals in expr. (expr is mutated)." arr=treepath.sub_slots(expr,lambda elt:elt is sqparse2.SubLit) if len(arr)!=len(values): raise ValueError('len',len(arr),len(values)) for path,val in zip(arr,values): # todo: does ArrayLit get us anything? tree trav...
python
def depth_first_sub(expr,values): "replace SubLit with literals in expr. (expr is mutated)." arr=treepath.sub_slots(expr,lambda elt:elt is sqparse2.SubLit) if len(arr)!=len(values): raise ValueError('len',len(arr),len(values)) for path,val in zip(arr,values): # todo: does ArrayLit get us anything? tree trav...
[ "def", "depth_first_sub", "(", "expr", ",", "values", ")", ":", "arr", "=", "treepath", ".", "sub_slots", "(", "expr", ",", "lambda", "elt", ":", "elt", "is", "sqparse2", ".", "SubLit", ")", "if", "len", "(", "arr", ")", "!=", "len", "(", "values", ...
replace SubLit with literals in expr. (expr is mutated).
[ "replace", "SubLit", "with", "literals", "in", "expr", ".", "(", "expr", "is", "mutated", ")", "." ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L339-L348
abe-winter/pg13-py
pg13/sqex.py
NameIndexer.update_aliases
def update_aliases(aliases,aonly,x): "helper for ctor. takes AliasX or string as second arg" if isinstance(x,basestring): aliases[x]=x elif isinstance(x,sqparse2.AliasX): if not isinstance(x.alias,basestring): raise TypeError('alias not string',type(x.alias)) if isinstance(x.name,sqparse2.NameX)...
python
def update_aliases(aliases,aonly,x): "helper for ctor. takes AliasX or string as second arg" if isinstance(x,basestring): aliases[x]=x elif isinstance(x,sqparse2.AliasX): if not isinstance(x.alias,basestring): raise TypeError('alias not string',type(x.alias)) if isinstance(x.name,sqparse2.NameX)...
[ "def", "update_aliases", "(", "aliases", ",", "aonly", ",", "x", ")", ":", "if", "isinstance", "(", "x", ",", "basestring", ")", ":", "aliases", "[", "x", "]", "=", "x", "elif", "isinstance", "(", "x", ",", "sqparse2", ".", "AliasX", ")", ":", "if"...
helper for ctor. takes AliasX or string as second arg
[ "helper", "for", "ctor", ".", "takes", "AliasX", "or", "string", "as", "second", "arg" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L104-L114
abe-winter/pg13-py
pg13/sqex.py
NameIndexer.resolve_aonly
def resolve_aonly(self,tables_dict,table_ctor): "circular depends on pgmock.Table. refactor." for alias,selectx in self.aonly.items(): table = table_ctor(alias,infer_columns(selectx,tables_dict),None) table.rows = run_select(selectx,tables_dict,table_ctor) self.aonly[alias] = table self.ao...
python
def resolve_aonly(self,tables_dict,table_ctor): "circular depends on pgmock.Table. refactor." for alias,selectx in self.aonly.items(): table = table_ctor(alias,infer_columns(selectx,tables_dict),None) table.rows = run_select(selectx,tables_dict,table_ctor) self.aonly[alias] = table self.ao...
[ "def", "resolve_aonly", "(", "self", ",", "tables_dict", ",", "table_ctor", ")", ":", "for", "alias", ",", "selectx", "in", "self", ".", "aonly", ".", "items", "(", ")", ":", "table", "=", "table_ctor", "(", "alias", ",", "infer_columns", "(", "selectx",...
circular depends on pgmock.Table. refactor.
[ "circular", "depends", "on", "pgmock", ".", "Table", ".", "refactor", "." ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqex.py#L134-L140