repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
matllubos/django-is-core
is_core/filters/default_filters.py
UIForeignKeyFilter.get_widget
def get_widget(self, request): """ Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for filtering. """ return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget)
python
def get_widget(self, request): """ Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for filtering. """ return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget)
[ "def", "get_widget", "(", "self", ",", "request", ")", ":", "return", "self", ".", "_update_widget_choices", "(", "self", ".", "field", ".", "formfield", "(", "widget", "=", "RestrictedSelectWidget", ")", ".", "widget", ")" ]
Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for filtering.
[ "Field", "widget", "is", "replaced", "with", "RestrictedSelectWidget", "because", "we", "not", "want", "to", "use", "modified", "widgets", "for", "filtering", "." ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/filters/default_filters.py#L56-L61
train
51,900
vcs-python/libvcs
libvcs/svn.py
get_rev_options
def get_rev_options(url, rev): """Return revision options. from pip pip.vcs.subversion. """ if rev: rev_options = ['-r', rev] else: rev_options = [] r = urlparse.urlsplit(url) if hasattr(r, 'username'): # >= Python-2.5 username, password = r.username, r.password else: netloc = r[1] if '@' in netloc: auth = netloc.split('@')[0] if ':' in auth: username, password = auth.split(':', 1) else: username, password = auth, None else: username, password = None, None if username: rev_options += ['--username', username] if password: rev_options += ['--password', password] return rev_options
python
def get_rev_options(url, rev): """Return revision options. from pip pip.vcs.subversion. """ if rev: rev_options = ['-r', rev] else: rev_options = [] r = urlparse.urlsplit(url) if hasattr(r, 'username'): # >= Python-2.5 username, password = r.username, r.password else: netloc = r[1] if '@' in netloc: auth = netloc.split('@')[0] if ':' in auth: username, password = auth.split(':', 1) else: username, password = auth, None else: username, password = None, None if username: rev_options += ['--username', username] if password: rev_options += ['--password', password] return rev_options
[ "def", "get_rev_options", "(", "url", ",", "rev", ")", ":", "if", "rev", ":", "rev_options", "=", "[", "'-r'", ",", "rev", "]", "else", ":", "rev_options", "=", "[", "]", "r", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "if", "hasattr", "(",...
Return revision options. from pip pip.vcs.subversion.
[ "Return", "revision", "options", "." ]
f7dc055250199bac6be7439b1d2240583f0bb354
https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/svn.py#L146-L176
train
51,901
vcs-python/libvcs
libvcs/svn.py
SubversionRepo.get_revision_file
def get_revision_file(self, location): """Return revision for a file.""" current_rev = self.run(['info', location]) _INI_RE = re.compile(r"^([^:]+):\s+(\S.*)$", re.M) info_list = _INI_RE.findall(current_rev) return int(dict(info_list)['Revision'])
python
def get_revision_file(self, location): """Return revision for a file.""" current_rev = self.run(['info', location]) _INI_RE = re.compile(r"^([^:]+):\s+(\S.*)$", re.M) info_list = _INI_RE.findall(current_rev) return int(dict(info_list)['Revision'])
[ "def", "get_revision_file", "(", "self", ",", "location", ")", ":", "current_rev", "=", "self", ".", "run", "(", "[", "'info'", ",", "location", "]", ")", "_INI_RE", "=", "re", ".", "compile", "(", "r\"^([^:]+):\\s+(\\S.*)$\"", ",", "re", ".", "M", ")", ...
Return revision for a file.
[ "Return", "revision", "for", "a", "file", "." ]
f7dc055250199bac6be7439b1d2240583f0bb354
https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/svn.py#L77-L85
train
51,902
The-Politico/django-slackchat-serializer
slackchat/serializers/channel.py
ChannelSerializer.get_publish_path
def get_publish_path(self, obj): """ publish_path joins the publish_paths for the chat type and the channel. """ return os.path.join( obj.chat_type.publish_path, obj.publish_path.lstrip("/") )
python
def get_publish_path(self, obj): """ publish_path joins the publish_paths for the chat type and the channel. """ return os.path.join( obj.chat_type.publish_path, obj.publish_path.lstrip("/") )
[ "def", "get_publish_path", "(", "self", ",", "obj", ")", ":", "return", "os", ".", "path", ".", "join", "(", "obj", ".", "chat_type", ".", "publish_path", ",", "obj", ".", "publish_path", ".", "lstrip", "(", "\"/\"", ")", ")" ]
publish_path joins the publish_paths for the chat type and the channel.
[ "publish_path", "joins", "the", "publish_paths", "for", "the", "chat", "type", "and", "the", "channel", "." ]
9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40
https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/serializers/channel.py#L37-L43
train
51,903
intelligenia/modeltranslation
modeltranslation/models.py
FieldTranslation._init_module_cache
def _init_module_cache(): """ Module caching, it helps with not having to import again and again same modules. @return: boolean, True if module caching has been done, False if module caching was already done. """ # While there are not loaded modules, load these ones if len(FieldTranslation._modules) < len(FieldTranslation._model_module_paths): for module_path in FieldTranslation._model_module_paths: FieldTranslation._modules[module_path] = importlib.import_module(module_path) return True return False
python
def _init_module_cache(): """ Module caching, it helps with not having to import again and again same modules. @return: boolean, True if module caching has been done, False if module caching was already done. """ # While there are not loaded modules, load these ones if len(FieldTranslation._modules) < len(FieldTranslation._model_module_paths): for module_path in FieldTranslation._model_module_paths: FieldTranslation._modules[module_path] = importlib.import_module(module_path) return True return False
[ "def", "_init_module_cache", "(", ")", ":", "# While there are not loaded modules, load these ones", "if", "len", "(", "FieldTranslation", ".", "_modules", ")", "<", "len", "(", "FieldTranslation", ".", "_model_module_paths", ")", ":", "for", "module_path", "in", "Fie...
Module caching, it helps with not having to import again and again same modules. @return: boolean, True if module caching has been done, False if module caching was already done.
[ "Module", "caching", "it", "helps", "with", "not", "having", "to", "import", "again", "and", "again", "same", "modules", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L155-L166
train
51,904
intelligenia/modeltranslation
modeltranslation/models.py
FieldTranslation._load_source_object
def _load_source_object(self): """ Loads related object in a dynamic attribute and returns it. """ if hasattr(self, "source_obj"): self.source_text = getattr(self.source_obj, self.field) return self.source_obj self._load_source_model() self.source_obj = self.source_model.objects.get(id=self.object_id) return self.source_obj
python
def _load_source_object(self): """ Loads related object in a dynamic attribute and returns it. """ if hasattr(self, "source_obj"): self.source_text = getattr(self.source_obj, self.field) return self.source_obj self._load_source_model() self.source_obj = self.source_model.objects.get(id=self.object_id) return self.source_obj
[ "def", "_load_source_object", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"source_obj\"", ")", ":", "self", ".", "source_text", "=", "getattr", "(", "self", ".", "source_obj", ",", "self", ".", "field", ")", "return", "self", ".", "source...
Loads related object in a dynamic attribute and returns it.
[ "Loads", "related", "object", "in", "a", "dynamic", "attribute", "and", "returns", "it", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L206-L216
train
51,905
intelligenia/modeltranslation
modeltranslation/models.py
FieldTranslation.delete_orphan_translations
def delete_orphan_translations(condition=None): """ Delete orphan translations. This method needs refactoring to be improve its performance. """ if condition is None: condition = {} # TODO: optimize using one SQL sentence translations = FieldTranslation.objects.all() for translation in translations: translation._load_source_model() condition["id"] = translation.object_id if not translation.source_model.objects.filter(**condition).exists(): translation.delete()
python
def delete_orphan_translations(condition=None): """ Delete orphan translations. This method needs refactoring to be improve its performance. """ if condition is None: condition = {} # TODO: optimize using one SQL sentence translations = FieldTranslation.objects.all() for translation in translations: translation._load_source_model() condition["id"] = translation.object_id if not translation.source_model.objects.filter(**condition).exists(): translation.delete()
[ "def", "delete_orphan_translations", "(", "condition", "=", "None", ")", ":", "if", "condition", "is", "None", ":", "condition", "=", "{", "}", "# TODO: optimize using one SQL sentence", "translations", "=", "FieldTranslation", ".", "objects", ".", "all", "(", ")"...
Delete orphan translations. This method needs refactoring to be improve its performance.
[ "Delete", "orphan", "translations", ".", "This", "method", "needs", "refactoring", "to", "be", "improve", "its", "performance", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L222-L235
train
51,906
intelligenia/modeltranslation
modeltranslation/models.py
FieldTranslation.update_translations
def update_translations(condition=None): """ Updates FieldTranslations table """ if condition is None: condition = {} # Number of updated translations num_translations = 0 # Module caching FieldTranslation._init_module_cache() # Current languages dict LANGUAGES = dict(lang for lang in MODELTRANSLATION_LANG_CHOICES) if settings.LANGUAGE_CODE in LANGUAGES: del LANGUAGES[settings.LANGUAGE_CODE] # For each module, we are going to update the translations for key in FieldTranslation._modules.keys(): module = FieldTranslation._modules[key] # Class of the module clsmembers = inspect.getmembers(sys.modules[key], inspect.isclass) for cls in clsmembers: cls = cls[1] # If the model has in Meta "translatable_fields", we insert this fields if hasattr(cls,"_meta") and not cls._meta.abstract and hasattr(cls._meta,"translatable_fields") and len(cls._meta.translatable_fields)>0: objects = cls.objects.filter(**condition) # For each object, language and field are updated for obj in objects: for lang in LANGUAGES.keys(): for field in cls._meta.translatable_fields: if FieldTranslation.update(obj=obj, field=field, lang=lang, context=""): num_translations += 1 return num_translations
python
def update_translations(condition=None): """ Updates FieldTranslations table """ if condition is None: condition = {} # Number of updated translations num_translations = 0 # Module caching FieldTranslation._init_module_cache() # Current languages dict LANGUAGES = dict(lang for lang in MODELTRANSLATION_LANG_CHOICES) if settings.LANGUAGE_CODE in LANGUAGES: del LANGUAGES[settings.LANGUAGE_CODE] # For each module, we are going to update the translations for key in FieldTranslation._modules.keys(): module = FieldTranslation._modules[key] # Class of the module clsmembers = inspect.getmembers(sys.modules[key], inspect.isclass) for cls in clsmembers: cls = cls[1] # If the model has in Meta "translatable_fields", we insert this fields if hasattr(cls,"_meta") and not cls._meta.abstract and hasattr(cls._meta,"translatable_fields") and len(cls._meta.translatable_fields)>0: objects = cls.objects.filter(**condition) # For each object, language and field are updated for obj in objects: for lang in LANGUAGES.keys(): for field in cls._meta.translatable_fields: if FieldTranslation.update(obj=obj, field=field, lang=lang, context=""): num_translations += 1 return num_translations
[ "def", "update_translations", "(", "condition", "=", "None", ")", ":", "if", "condition", "is", "None", ":", "condition", "=", "{", "}", "# Number of updated translations", "num_translations", "=", "0", "# Module caching", "FieldTranslation", ".", "_init_module_cache"...
Updates FieldTranslations table
[ "Updates", "FieldTranslations", "table" ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L241-L278
train
51,907
intelligenia/modeltranslation
modeltranslation/models.py
FieldTranslation.factory
def factory(obj, field, source_text, lang, context=""): """ Static method that constructs a translation based on its contents. """ # Model name obj_classname = obj.__class__.__name__ # Module name obj_module = obj.__module__ # Computation of MD5 of the source text source_md5 = checksum(source_text) # Translated text translation = "" # Translation text attribute name field_lang = trans_attr(field,lang) # If in source object there is a translation and is not empty, we asume it was assigned and it's correct if hasattr(obj,field_lang) and getattr(obj,field_lang)!="": translation = getattr(obj,field_lang) # Is the translation fuzzy? is_fuzzy = True is_fuzzy_lang = trans_is_fuzzy_attr(field,lang) if hasattr(obj,is_fuzzy_lang): is_fuzzy = getattr(obj,is_fuzzy_lang) # Construction of the translation trans = FieldTranslation(module=obj_module, model=obj_classname, object_id=obj.id, field=field, lang=lang, source_text=source_text, source_md5=source_md5, translation=translation, is_fuzzy=is_fuzzy, context=context) return trans
python
def factory(obj, field, source_text, lang, context=""): """ Static method that constructs a translation based on its contents. """ # Model name obj_classname = obj.__class__.__name__ # Module name obj_module = obj.__module__ # Computation of MD5 of the source text source_md5 = checksum(source_text) # Translated text translation = "" # Translation text attribute name field_lang = trans_attr(field,lang) # If in source object there is a translation and is not empty, we asume it was assigned and it's correct if hasattr(obj,field_lang) and getattr(obj,field_lang)!="": translation = getattr(obj,field_lang) # Is the translation fuzzy? is_fuzzy = True is_fuzzy_lang = trans_is_fuzzy_attr(field,lang) if hasattr(obj,is_fuzzy_lang): is_fuzzy = getattr(obj,is_fuzzy_lang) # Construction of the translation trans = FieldTranslation(module=obj_module, model=obj_classname, object_id=obj.id, field=field, lang=lang, source_text=source_text, source_md5=source_md5, translation=translation, is_fuzzy=is_fuzzy, context=context) return trans
[ "def", "factory", "(", "obj", ",", "field", ",", "source_text", ",", "lang", ",", "context", "=", "\"\"", ")", ":", "# Model name", "obj_classname", "=", "obj", ".", "__class__", ".", "__name__", "# Module name", "obj_module", "=", "obj", ".", "__module__", ...
Static method that constructs a translation based on its contents.
[ "Static", "method", "that", "constructs", "a", "translation", "based", "on", "its", "contents", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L313-L347
train
51,908
intelligenia/modeltranslation
modeltranslation/models.py
FieldTranslation.save
def save(self, *args, **kwargs): """ Save object in database, updating the datetimes accordingly. """ # Now in UTC now_datetime = timezone.now() # If we are in a creation, assigns creation_datetime if not self.id: self.creation_datetime = now_datetime # Las update datetime is always updated self.last_update_datetime = now_datetime # Current user is creator # (get current user with django-cuser middleware) self.creator_user = None current_user = CuserMiddleware.get_user() if not current_user is None and not current_user.is_anonymous(): self.creator_user_id = current_user.id # Parent constructor call super(FieldTranslation, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): """ Save object in database, updating the datetimes accordingly. """ # Now in UTC now_datetime = timezone.now() # If we are in a creation, assigns creation_datetime if not self.id: self.creation_datetime = now_datetime # Las update datetime is always updated self.last_update_datetime = now_datetime # Current user is creator # (get current user with django-cuser middleware) self.creator_user = None current_user = CuserMiddleware.get_user() if not current_user is None and not current_user.is_anonymous(): self.creator_user_id = current_user.id # Parent constructor call super(FieldTranslation, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Now in UTC", "now_datetime", "=", "timezone", ".", "now", "(", ")", "# If we are in a creation, assigns creation_datetime", "if", "not", "self", ".", "id", ":", "self", ".", ...
Save object in database, updating the datetimes accordingly.
[ "Save", "object", "in", "database", "updating", "the", "datetimes", "accordingly", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L413-L436
train
51,909
softwarefactory-project/distroinfo
distroinfo/parse.py
parse_info
def parse_info(raw_info, apply_tag=None): """ Parse raw rdoinfo metadata inplace. :param raw_info: raw info to parse :param apply_tag: tag to apply :returns: dictionary containing all packages in rdoinfo """ parse_releases(raw_info) parse_packages(raw_info, apply_tag=apply_tag) return raw_info
python
def parse_info(raw_info, apply_tag=None): """ Parse raw rdoinfo metadata inplace. :param raw_info: raw info to parse :param apply_tag: tag to apply :returns: dictionary containing all packages in rdoinfo """ parse_releases(raw_info) parse_packages(raw_info, apply_tag=apply_tag) return raw_info
[ "def", "parse_info", "(", "raw_info", ",", "apply_tag", "=", "None", ")", ":", "parse_releases", "(", "raw_info", ")", "parse_packages", "(", "raw_info", ",", "apply_tag", "=", "apply_tag", ")", "return", "raw_info" ]
Parse raw rdoinfo metadata inplace. :param raw_info: raw info to parse :param apply_tag: tag to apply :returns: dictionary containing all packages in rdoinfo
[ "Parse", "raw", "rdoinfo", "metadata", "inplace", "." ]
86a7419232a3376157c06e70528ec627e03ff82a
https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/parse.py#L8-L18
train
51,910
xapple/plumbing
plumbing/common.py
alphanumeric
def alphanumeric(text): """Make an ultra-safe, ASCII version a string. For instance for use as a filename. \w matches any alphanumeric character and the underscore.""" return "".join([c for c in text if re.match(r'\w', c)])
python
def alphanumeric(text): """Make an ultra-safe, ASCII version a string. For instance for use as a filename. \w matches any alphanumeric character and the underscore.""" return "".join([c for c in text if re.match(r'\w', c)])
[ "def", "alphanumeric", "(", "text", ")", ":", "return", "\"\"", ".", "join", "(", "[", "c", "for", "c", "in", "text", "if", "re", ".", "match", "(", "r'\\w'", ",", "c", ")", "]", ")" ]
Make an ultra-safe, ASCII version a string. For instance for use as a filename. \w matches any alphanumeric character and the underscore.
[ "Make", "an", "ultra", "-", "safe", "ASCII", "version", "a", "string", ".", "For", "instance", "for", "use", "as", "a", "filename", ".", "\\", "w", "matches", "any", "alphanumeric", "character", "and", "the", "underscore", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L23-L27
train
51,911
xapple/plumbing
plumbing/common.py
all_combinations
def all_combinations(items): """Generate all combinations of a given list of items.""" return (set(compress(items,mask)) for mask in product(*[[0,1]]*len(items)))
python
def all_combinations(items): """Generate all combinations of a given list of items.""" return (set(compress(items,mask)) for mask in product(*[[0,1]]*len(items)))
[ "def", "all_combinations", "(", "items", ")", ":", "return", "(", "set", "(", "compress", "(", "items", ",", "mask", ")", ")", "for", "mask", "in", "product", "(", "*", "[", "[", "0", ",", "1", "]", "]", "*", "len", "(", "items", ")", ")", ")" ...
Generate all combinations of a given list of items.
[ "Generate", "all", "combinations", "of", "a", "given", "list", "of", "items", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L92-L94
train
51,912
xapple/plumbing
plumbing/common.py
pad_equal_whitespace
def pad_equal_whitespace(string, pad=None): """Given a multiline string, add whitespaces to every line so that every line has the same length.""" if pad is None: pad = max(map(len, string.split('\n'))) + 1 return '\n'.join(('{0: <%i}' % pad).format(line) for line in string.split('\n'))
python
def pad_equal_whitespace(string, pad=None): """Given a multiline string, add whitespaces to every line so that every line has the same length.""" if pad is None: pad = max(map(len, string.split('\n'))) + 1 return '\n'.join(('{0: <%i}' % pad).format(line) for line in string.split('\n'))
[ "def", "pad_equal_whitespace", "(", "string", ",", "pad", "=", "None", ")", ":", "if", "pad", "is", "None", ":", "pad", "=", "max", "(", "map", "(", "len", ",", "string", ".", "split", "(", "'\\n'", ")", ")", ")", "+", "1", "return", "'\\n'", "."...
Given a multiline string, add whitespaces to every line so that every line has the same length.
[ "Given", "a", "multiline", "string", "add", "whitespaces", "to", "every", "line", "so", "that", "every", "line", "has", "the", "same", "length", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L97-L101
train
51,913
xapple/plumbing
plumbing/common.py
concatenate_by_line
def concatenate_by_line(first, second): """Zip two strings together, line wise""" return '\n'.join(x+y for x,y in zip(first.split('\n'), second.split('\n')))
python
def concatenate_by_line(first, second): """Zip two strings together, line wise""" return '\n'.join(x+y for x,y in zip(first.split('\n'), second.split('\n')))
[ "def", "concatenate_by_line", "(", "first", ",", "second", ")", ":", "return", "'\\n'", ".", "join", "(", "x", "+", "y", "for", "x", ",", "y", "in", "zip", "(", "first", ".", "split", "(", "'\\n'", ")", ",", "second", ".", "split", "(", "'\\n'", ...
Zip two strings together, line wise
[ "Zip", "two", "strings", "together", "line", "wise" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L115-L117
train
51,914
xapple/plumbing
plumbing/common.py
sort_string_by_pairs
def sort_string_by_pairs(strings): """Group a list of strings by pairs, by matching those with only one character difference between each other together.""" assert len(strings) % 2 == 0 pairs = [] strings = list(strings) # This shallow copies the list while strings: template = strings.pop() for i, candidate in enumerate(strings): if count_string_diff(template, candidate) == 1: pair = [template, strings.pop(i)] pair.sort() pairs.append(pair) break return pairs
python
def sort_string_by_pairs(strings): """Group a list of strings by pairs, by matching those with only one character difference between each other together.""" assert len(strings) % 2 == 0 pairs = [] strings = list(strings) # This shallow copies the list while strings: template = strings.pop() for i, candidate in enumerate(strings): if count_string_diff(template, candidate) == 1: pair = [template, strings.pop(i)] pair.sort() pairs.append(pair) break return pairs
[ "def", "sort_string_by_pairs", "(", "strings", ")", ":", "assert", "len", "(", "strings", ")", "%", "2", "==", "0", "pairs", "=", "[", "]", "strings", "=", "list", "(", "strings", ")", "# This shallow copies the list", "while", "strings", ":", "template", ...
Group a list of strings by pairs, by matching those with only one character difference between each other together.
[ "Group", "a", "list", "of", "strings", "by", "pairs", "by", "matching", "those", "with", "only", "one", "character", "difference", "between", "each", "other", "together", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L120-L134
train
51,915
xapple/plumbing
plumbing/common.py
count_string_diff
def count_string_diff(a,b): """Return the number of characters in two strings that don't exactly match""" shortest = min(len(a), len(b)) return sum(a[i] != b[i] for i in range(shortest))
python
def count_string_diff(a,b): """Return the number of characters in two strings that don't exactly match""" shortest = min(len(a), len(b)) return sum(a[i] != b[i] for i in range(shortest))
[ "def", "count_string_diff", "(", "a", ",", "b", ")", ":", "shortest", "=", "min", "(", "len", "(", "a", ")", ",", "len", "(", "b", ")", ")", "return", "sum", "(", "a", "[", "i", "]", "!=", "b", "[", "i", "]", "for", "i", "in", "range", "(",...
Return the number of characters in two strings that don't exactly match
[ "Return", "the", "number", "of", "characters", "in", "two", "strings", "that", "don", "t", "exactly", "match" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L137-L140
train
51,916
xapple/plumbing
plumbing/common.py
iflatten
def iflatten(L): """Iterative flatten.""" for sublist in L: if hasattr(sublist, '__iter__'): for item in iflatten(sublist): yield item else: yield sublist
python
def iflatten(L): """Iterative flatten.""" for sublist in L: if hasattr(sublist, '__iter__'): for item in iflatten(sublist): yield item else: yield sublist
[ "def", "iflatten", "(", "L", ")", ":", "for", "sublist", "in", "L", ":", "if", "hasattr", "(", "sublist", ",", "'__iter__'", ")", ":", "for", "item", "in", "iflatten", "(", "sublist", ")", ":", "yield", "item", "else", ":", "yield", "sublist" ]
Iterative flatten.
[ "Iterative", "flatten", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L143-L148
train
51,917
xapple/plumbing
plumbing/common.py
uniquify_list
def uniquify_list(L): """Same order unique list using only a list compression.""" return [e for i, e in enumerate(L) if L.index(e) == i]
python
def uniquify_list(L): """Same order unique list using only a list compression.""" return [e for i, e in enumerate(L) if L.index(e) == i]
[ "def", "uniquify_list", "(", "L", ")", ":", "return", "[", "e", "for", "i", ",", "e", "in", "enumerate", "(", "L", ")", "if", "L", ".", "index", "(", "e", ")", "==", "i", "]" ]
Same order unique list using only a list compression.
[ "Same", "order", "unique", "list", "using", "only", "a", "list", "compression", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L151-L153
train
51,918
xapple/plumbing
plumbing/common.py
average
def average(iterator): """Iterative mean.""" count = 0 total = 0 for num in iterator: count += 1 total += num return float(total)/count
python
def average(iterator): """Iterative mean.""" count = 0 total = 0 for num in iterator: count += 1 total += num return float(total)/count
[ "def", "average", "(", "iterator", ")", ":", "count", "=", "0", "total", "=", "0", "for", "num", "in", "iterator", ":", "count", "+=", "1", "total", "+=", "num", "return", "float", "(", "total", ")", "/", "count" ]
Iterative mean.
[ "Iterative", "mean", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L156-L163
train
51,919
xapple/plumbing
plumbing/common.py
get_next_item
def get_next_item(iterable): """Gets the next item of an iterable. If the iterable is exhausted, returns None.""" try: x = iterable.next() except StopIteration: x = None except AttributeError: x = None return x
python
def get_next_item(iterable): """Gets the next item of an iterable. If the iterable is exhausted, returns None.""" try: x = iterable.next() except StopIteration: x = None except AttributeError: x = None return x
[ "def", "get_next_item", "(", "iterable", ")", ":", "try", ":", "x", "=", "iterable", ".", "next", "(", ")", "except", "StopIteration", ":", "x", "=", "None", "except", "AttributeError", ":", "x", "=", "None", "return", "x" ]
Gets the next item of an iterable. If the iterable is exhausted, returns None.
[ "Gets", "the", "next", "item", "of", "an", "iterable", ".", "If", "the", "iterable", "is", "exhausted", "returns", "None", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L166-L172
train
51,920
xapple/plumbing
plumbing/common.py
andify
def andify(list_of_strings): """ Given a list of strings will join them with commas and a final "and" word. >>> andify(['Apples', 'Oranges', 'Mangos']) 'Apples, Oranges and Mangos' """ result = ', '.join(list_of_strings) comma_index = result.rfind(',') if comma_index > -1: result = result[:comma_index] + ' and' + result[comma_index+1:] return result
python
def andify(list_of_strings): """ Given a list of strings will join them with commas and a final "and" word. >>> andify(['Apples', 'Oranges', 'Mangos']) 'Apples, Oranges and Mangos' """ result = ', '.join(list_of_strings) comma_index = result.rfind(',') if comma_index > -1: result = result[:comma_index] + ' and' + result[comma_index+1:] return result
[ "def", "andify", "(", "list_of_strings", ")", ":", "result", "=", "', '", ".", "join", "(", "list_of_strings", ")", "comma_index", "=", "result", ".", "rfind", "(", "','", ")", "if", "comma_index", ">", "-", "1", ":", "result", "=", "result", "[", ":",...
Given a list of strings will join them with commas and a final "and" word. >>> andify(['Apples', 'Oranges', 'Mangos']) 'Apples, Oranges and Mangos'
[ "Given", "a", "list", "of", "strings", "will", "join", "them", "with", "commas", "and", "a", "final", "and", "word", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L183-L194
train
51,921
xapple/plumbing
plumbing/common.py
num_to_ith
def num_to_ith(num): """1 becomes 1st, 2 becomes 2nd, etc.""" value = str(num) before_last_digit = value[-2] last_digit = value[-1] if len(value) > 1 and before_last_digit == '1': return value +'th' if last_digit == '1': return value + 'st' if last_digit == '2': return value + 'nd' if last_digit == '3': return value + 'rd' return value + 'th'
python
def num_to_ith(num): """1 becomes 1st, 2 becomes 2nd, etc.""" value = str(num) before_last_digit = value[-2] last_digit = value[-1] if len(value) > 1 and before_last_digit == '1': return value +'th' if last_digit == '1': return value + 'st' if last_digit == '2': return value + 'nd' if last_digit == '3': return value + 'rd' return value + 'th'
[ "def", "num_to_ith", "(", "num", ")", ":", "value", "=", "str", "(", "num", ")", "before_last_digit", "=", "value", "[", "-", "2", "]", "last_digit", "=", "value", "[", "-", "1", "]", "if", "len", "(", "value", ")", ">", "1", "and", "before_last_di...
1 becomes 1st, 2 becomes 2nd, etc.
[ "1", "becomes", "1st", "2", "becomes", "2nd", "etc", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L197-L206
train
51,922
xapple/plumbing
plumbing/common.py
isubsample
def isubsample(full_sample, k, full_sample_len=None): """Down-sample an enumerable list of things""" # Determine length # if not full_sample_len: full_sample_len = len(full_sample) # Check size coherence # if not 0 <= k <= full_sample_len: raise ValueError('Required that 0 <= k <= full_sample_length') # Do it # picked = 0 for i, element in enumerate(full_sample): prob = (k-picked) / (full_sample_len-i) if random.random() < prob: yield element picked += 1 # Did we pick the right amount # assert picked == k
python
def isubsample(full_sample, k, full_sample_len=None): """Down-sample an enumerable list of things""" # Determine length # if not full_sample_len: full_sample_len = len(full_sample) # Check size coherence # if not 0 <= k <= full_sample_len: raise ValueError('Required that 0 <= k <= full_sample_length') # Do it # picked = 0 for i, element in enumerate(full_sample): prob = (k-picked) / (full_sample_len-i) if random.random() < prob: yield element picked += 1 # Did we pick the right amount # assert picked == k
[ "def", "isubsample", "(", "full_sample", ",", "k", ",", "full_sample_len", "=", "None", ")", ":", "# Determine length #", "if", "not", "full_sample_len", ":", "full_sample_len", "=", "len", "(", "full_sample", ")", "# Check size coherence #", "if", "not", "0", "...
Down-sample an enumerable list of things
[ "Down", "-", "sample", "an", "enumerable", "list", "of", "things" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L209-L224
train
51,923
xapple/plumbing
plumbing/common.py
moving_average
def moving_average(interval, windowsize, borders=None): """This is essentially a convolving operation. Several option exist for dealing with the border cases. * None: Here the returned signal will be smaller than the inputted interval. * zero_padding: Here the returned signal will be larger than the inputted interval and we will add zeros to the original interval before operating the convolution. * zero_padding_and_cut: Same as above only the result is truncated to be the same size as the original input. * copy_padding: Here the returned signal will be larger than the inputted interval and we will use the right and leftmost values for padding before operating the convolution. * copy_padding_and_cut: Same as above only the result is truncated to be the same size as the original input. * zero_stretching: Here we will compute the convolution only in the valid domain, then add zeros to the result so that the output is the same size as the input. * copy_stretching: Here we will compute the convolution only in the valid domain, then copy the right and leftmost values so that the output is the same size as the input. """ # The window size in half # half = int(math.floor(windowsize/2.0)) # The normalized rectangular signal # window = numpy.ones(int(windowsize))/float(windowsize) # How do we deal with borders # if borders == None: return numpy.convolve(interval, window, 'valid') if borders == 'zero_padding': return numpy.convolve(interval, window, 'full') if borders == 'zero_padding_and_cut': return numpy.convolve(interval, window, 'same') if borders == 'copy_padding': new_interval = [interval[0]]*(windowsize-1) + interval + [interval[-1]]*(windowsize-1) return numpy.convolve(new_interval, window, 'valid') if borders == 'copy_padding_and_cut': new_interval = [interval[0]]*(windowsize-1) + interval + [interval[-1]]*(windowsize-1) return numpy.convolve(new_interval, window, 'valid')[half:-half] if borders == 'zero_stretching': result = numpy.convolve(interval, window, 'valid') pad = numpy.zeros(half) return numpy.concatenate((pad, result, pad)) if borders == 'copy_stretching': result = numpy.convolve(interval, window, 'valid') left = numpy.ones(half)*result[0] right = numpy.ones(half)*result[-1] return numpy.concatenate((left, result, right))
python
def moving_average(interval, windowsize, borders=None): """This is essentially a convolving operation. Several option exist for dealing with the border cases. * None: Here the returned signal will be smaller than the inputted interval. * zero_padding: Here the returned signal will be larger than the inputted interval and we will add zeros to the original interval before operating the convolution. * zero_padding_and_cut: Same as above only the result is truncated to be the same size as the original input. * copy_padding: Here the returned signal will be larger than the inputted interval and we will use the right and leftmost values for padding before operating the convolution. * copy_padding_and_cut: Same as above only the result is truncated to be the same size as the original input. * zero_stretching: Here we will compute the convolution only in the valid domain, then add zeros to the result so that the output is the same size as the input. * copy_stretching: Here we will compute the convolution only in the valid domain, then copy the right and leftmost values so that the output is the same size as the input. """ # The window size in half # half = int(math.floor(windowsize/2.0)) # The normalized rectangular signal # window = numpy.ones(int(windowsize))/float(windowsize) # How do we deal with borders # if borders == None: return numpy.convolve(interval, window, 'valid') if borders == 'zero_padding': return numpy.convolve(interval, window, 'full') if borders == 'zero_padding_and_cut': return numpy.convolve(interval, window, 'same') if borders == 'copy_padding': new_interval = [interval[0]]*(windowsize-1) + interval + [interval[-1]]*(windowsize-1) return numpy.convolve(new_interval, window, 'valid') if borders == 'copy_padding_and_cut': new_interval = [interval[0]]*(windowsize-1) + interval + [interval[-1]]*(windowsize-1) return numpy.convolve(new_interval, window, 'valid')[half:-half] if borders == 'zero_stretching': result = numpy.convolve(interval, window, 'valid') pad = numpy.zeros(half) return numpy.concatenate((pad, result, pad)) if borders == 'copy_stretching': result = numpy.convolve(interval, window, 'valid') left = numpy.ones(half)*result[0] right = numpy.ones(half)*result[-1] return numpy.concatenate((left, result, right))
[ "def", "moving_average", "(", "interval", ",", "windowsize", ",", "borders", "=", "None", ")", ":", "# The window size in half #", "half", "=", "int", "(", "math", ".", "floor", "(", "windowsize", "/", "2.0", ")", ")", "# The normalized rectangular signal #", "w...
This is essentially a convolving operation. Several option exist for dealing with the border cases. * None: Here the returned signal will be smaller than the inputted interval. * zero_padding: Here the returned signal will be larger than the inputted interval and we will add zeros to the original interval before operating the convolution. * zero_padding_and_cut: Same as above only the result is truncated to be the same size as the original input. * copy_padding: Here the returned signal will be larger than the inputted interval and we will use the right and leftmost values for padding before operating the convolution. * copy_padding_and_cut: Same as above only the result is truncated to be the same size as the original input. * zero_stretching: Here we will compute the convolution only in the valid domain, then add zeros to the result so that the output is the same size as the input. * copy_stretching: Here we will compute the convolution only in the valid domain, then copy the right and leftmost values so that the output is the same size as the input.
[ "This", "is", "essentially", "a", "convolving", "operation", ".", "Several", "option", "exist", "for", "dealing", "with", "the", "border", "cases", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L227-L269
train
51,924
xapple/plumbing
plumbing/common.py
wait
def wait(predicate, interval=1, message=lambda: "Waiting..."): """Wait until the predicate turns true and display a turning ball.""" ball, next_ball = u"|/-\\", "|" sys.stdout.write(" \033[K") sys.stdout.flush() while not predicate(): time.sleep(1) next_ball = ball[(ball.index(next_ball) + 1) % len(ball)] sys.stdout.write("\r " + str(message()) + " " + next_ball + " \033[K") sys.stdout.flush() print("\r Done. \033[K") sys.stdout.flush()
python
def wait(predicate, interval=1, message=lambda: "Waiting..."): """Wait until the predicate turns true and display a turning ball.""" ball, next_ball = u"|/-\\", "|" sys.stdout.write(" \033[K") sys.stdout.flush() while not predicate(): time.sleep(1) next_ball = ball[(ball.index(next_ball) + 1) % len(ball)] sys.stdout.write("\r " + str(message()) + " " + next_ball + " \033[K") sys.stdout.flush() print("\r Done. \033[K") sys.stdout.flush()
[ "def", "wait", "(", "predicate", ",", "interval", "=", "1", ",", "message", "=", "lambda", ":", "\"Waiting...\"", ")", ":", "ball", ",", "next_ball", "=", "u\"|/-\\\\\"", ",", "\"|\"", "sys", ".", "stdout", ".", "write", "(", "\" \\033[K\"", ")", "sys...
Wait until the predicate turns true and display a turning ball.
[ "Wait", "until", "the", "predicate", "turns", "true", "and", "display", "a", "turning", "ball", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L272-L283
train
51,925
xapple/plumbing
plumbing/common.py
natural_sort
def natural_sort(item): """ Sort strings that contain numbers correctly. Works in Python 2 and 3. >>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1'] >>> l.sort(key=natural_sort) >>> l.__repr__() "['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" """ dre = re.compile(r'(\d+)') return [int(s) if s.isdigit() else s.lower() for s in re.split(dre, item)]
python
def natural_sort(item): """ Sort strings that contain numbers correctly. Works in Python 2 and 3. >>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1'] >>> l.sort(key=natural_sort) >>> l.__repr__() "['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" """ dre = re.compile(r'(\d+)') return [int(s) if s.isdigit() else s.lower() for s in re.split(dre, item)]
[ "def", "natural_sort", "(", "item", ")", ":", "dre", "=", "re", ".", "compile", "(", "r'(\\d+)'", ")", "return", "[", "int", "(", "s", ")", "if", "s", ".", "isdigit", "(", ")", "else", "s", ".", "lower", "(", ")", "for", "s", "in", "re", ".", ...
Sort strings that contain numbers correctly. Works in Python 2 and 3. >>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1'] >>> l.sort(key=natural_sort) >>> l.__repr__() "['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
[ "Sort", "strings", "that", "contain", "numbers", "correctly", ".", "Works", "in", "Python", "2", "and", "3", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L286-L296
train
51,926
xapple/plumbing
plumbing/common.py
split_thousands
def split_thousands(s): """ Splits a number on thousands. >>> split_thousands(1000012) "1'000'012" """ # Check input # if s is None: return "0" # If it's a string # if isinstance(s, basestring): s = float(s) # If it's a float that should be an int # if isinstance(s, float) and s.is_integer(): s = int(s) # Use python built-in # result = "{:,}".format(s) # But we want single quotes # result = result.replace(',', "'") # Return # return result
python
def split_thousands(s): """ Splits a number on thousands. >>> split_thousands(1000012) "1'000'012" """ # Check input # if s is None: return "0" # If it's a string # if isinstance(s, basestring): s = float(s) # If it's a float that should be an int # if isinstance(s, float) and s.is_integer(): s = int(s) # Use python built-in # result = "{:,}".format(s) # But we want single quotes # result = result.replace(',', "'") # Return # return result
[ "def", "split_thousands", "(", "s", ")", ":", "# Check input #", "if", "s", "is", "None", ":", "return", "\"0\"", "# If it's a string #", "if", "isinstance", "(", "s", ",", "basestring", ")", ":", "s", "=", "float", "(", "s", ")", "# If it's a float that sho...
Splits a number on thousands. >>> split_thousands(1000012) "1'000'012"
[ "Splits", "a", "number", "on", "thousands", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L299-L317
train
51,927
xapple/plumbing
plumbing/common.py
reverse_compl_with_name
def reverse_compl_with_name(old_seq): """Reverse a SeqIO sequence, but keep its name intact.""" new_seq = old_seq.reverse_complement() new_seq.id = old_seq.id new_seq.description = old_seq.description return new_seq
python
def reverse_compl_with_name(old_seq): """Reverse a SeqIO sequence, but keep its name intact.""" new_seq = old_seq.reverse_complement() new_seq.id = old_seq.id new_seq.description = old_seq.description return new_seq
[ "def", "reverse_compl_with_name", "(", "old_seq", ")", ":", "new_seq", "=", "old_seq", ".", "reverse_complement", "(", ")", "new_seq", ".", "id", "=", "old_seq", ".", "id", "new_seq", ".", "description", "=", "old_seq", ".", "description", "return", "new_seq" ...
Reverse a SeqIO sequence, but keep its name intact.
[ "Reverse", "a", "SeqIO", "sequence", "but", "keep", "its", "name", "intact", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L333-L338
train
51,928
xapple/plumbing
plumbing/common.py
load_json_path
def load_json_path(path): """Load a file with the json module, but report errors better if it fails. And have it ordered too !""" with open(path) as handle: try: return json.load(handle, object_pairs_hook=collections.OrderedDict) except ValueError as error: message = "Could not decode JSON file '%s'." % path message = "-"*20 + "\n" + message + "\n" + str(error) + "\n" + "-"*20 + "\n" sys.stderr.write(message) raise error
python
def load_json_path(path): """Load a file with the json module, but report errors better if it fails. And have it ordered too !""" with open(path) as handle: try: return json.load(handle, object_pairs_hook=collections.OrderedDict) except ValueError as error: message = "Could not decode JSON file '%s'." % path message = "-"*20 + "\n" + message + "\n" + str(error) + "\n" + "-"*20 + "\n" sys.stderr.write(message) raise error
[ "def", "load_json_path", "(", "path", ")", ":", "with", "open", "(", "path", ")", "as", "handle", ":", "try", ":", "return", "json", ".", "load", "(", "handle", ",", "object_pairs_hook", "=", "collections", ".", "OrderedDict", ")", "except", "ValueError", ...
Load a file with the json module, but report errors better if it fails. And have it ordered too !
[ "Load", "a", "file", "with", "the", "json", "module", "but", "report", "errors", "better", "if", "it", "fails", ".", "And", "have", "it", "ordered", "too", "!" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L390-L399
train
51,929
xapple/plumbing
plumbing/common.py
md5sum
def md5sum(file_path, blocksize=65536): """Compute the md5 of a file. Pretty fast.""" md5 = hashlib.md5() with open(file_path, "rb") as f: for block in iter(lambda: f.read(blocksize), ""): md5.update(block) return md5.hexdigest()
python
def md5sum(file_path, blocksize=65536): """Compute the md5 of a file. Pretty fast.""" md5 = hashlib.md5() with open(file_path, "rb") as f: for block in iter(lambda: f.read(blocksize), ""): md5.update(block) return md5.hexdigest()
[ "def", "md5sum", "(", "file_path", ",", "blocksize", "=", "65536", ")", ":", "md5", "=", "hashlib", ".", "md5", "(", ")", "with", "open", "(", "file_path", ",", "\"rb\"", ")", "as", "f", ":", "for", "block", "in", "iter", "(", "lambda", ":", "f", ...
Compute the md5 of a file. Pretty fast.
[ "Compute", "the", "md5", "of", "a", "file", ".", "Pretty", "fast", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L408-L414
train
51,930
xapple/plumbing
plumbing/common.py
reversed_lines
def reversed_lines(path): """Generate the lines of file in reverse order.""" with open(path, 'r') as handle: part = '' for block in reversed_blocks(handle): for c in reversed(block): if c == '\n' and part: yield part[::-1] part = '' part += c if part: yield part[::-1]
python
def reversed_lines(path): """Generate the lines of file in reverse order.""" with open(path, 'r') as handle: part = '' for block in reversed_blocks(handle): for c in reversed(block): if c == '\n' and part: yield part[::-1] part = '' part += c if part: yield part[::-1]
[ "def", "reversed_lines", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "handle", ":", "part", "=", "''", "for", "block", "in", "reversed_blocks", "(", "handle", ")", ":", "for", "c", "in", "reversed", "(", "block", ")", ...
Generate the lines of file in reverse order.
[ "Generate", "the", "lines", "of", "file", "in", "reverse", "order", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L448-L458
train
51,931
xapple/plumbing
plumbing/common.py
reversed_blocks
def reversed_blocks(handle, blocksize=4096): """Generate blocks of file's contents in reverse order.""" handle.seek(0, os.SEEK_END) here = handle.tell() while 0 < here: delta = min(blocksize, here) here -= delta handle.seek(here, os.SEEK_SET) yield handle.read(delta)
python
def reversed_blocks(handle, blocksize=4096): """Generate blocks of file's contents in reverse order.""" handle.seek(0, os.SEEK_END) here = handle.tell() while 0 < here: delta = min(blocksize, here) here -= delta handle.seek(here, os.SEEK_SET) yield handle.read(delta)
[ "def", "reversed_blocks", "(", "handle", ",", "blocksize", "=", "4096", ")", ":", "handle", ".", "seek", "(", "0", ",", "os", ".", "SEEK_END", ")", "here", "=", "handle", ".", "tell", "(", ")", "while", "0", "<", "here", ":", "delta", "=", "min", ...
Generate blocks of file's contents in reverse order.
[ "Generate", "blocks", "of", "file", "s", "contents", "in", "reverse", "order", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L461-L469
train
51,932
sunlightlabs/django-mediasync
mediasync/templatetags/media.py
BaseTagNode.supports_gzip
def supports_gzip(self, context): """ Looks at the RequestContext object and determines if the client supports gzip encoded content. If the client does, we will send them to the gzipped version of files that are allowed to be compressed. Clients without gzip support will be served the original media. """ if 'request' in context and client.supports_gzip(): enc = context['request'].META.get('HTTP_ACCEPT_ENCODING', '') return 'gzip' in enc and msettings['SERVE_REMOTE'] return False
python
def supports_gzip(self, context): """ Looks at the RequestContext object and determines if the client supports gzip encoded content. If the client does, we will send them to the gzipped version of files that are allowed to be compressed. Clients without gzip support will be served the original media. """ if 'request' in context and client.supports_gzip(): enc = context['request'].META.get('HTTP_ACCEPT_ENCODING', '') return 'gzip' in enc and msettings['SERVE_REMOTE'] return False
[ "def", "supports_gzip", "(", "self", ",", "context", ")", ":", "if", "'request'", "in", "context", "and", "client", ".", "supports_gzip", "(", ")", ":", "enc", "=", "context", "[", "'request'", "]", ".", "META", ".", "get", "(", "'HTTP_ACCEPT_ENCODING'", ...
Looks at the RequestContext object and determines if the client supports gzip encoded content. If the client does, we will send them to the gzipped version of files that are allowed to be compressed. Clients without gzip support will be served the original media.
[ "Looks", "at", "the", "RequestContext", "object", "and", "determines", "if", "the", "client", "supports", "gzip", "encoded", "content", ".", "If", "the", "client", "does", "we", "will", "send", "them", "to", "the", "gzipped", "version", "of", "files", "that"...
aa8ce4cfff757bbdb488463c64c0863cca6a1932
https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L32-L42
train
51,933
sprockets/sprockets.http
sprockets/http/app.py
wrap_application
def wrap_application(application, before_run, on_start, shutdown): """ Wrap a tornado application in a callback-aware wrapper. :param tornado.web.Application application: application to wrap. :param list|NoneType before_run: optional list of callbacks to invoke before the IOLoop is started. :param list|NoneType on_start: optional list of callbacks to register with :meth:`~tornado.IOLoop.spawn_callback`. :param list|NoneType shutdown: optional list of callbacks to invoke before stopping the IOLoop :return: a wrapped application object :rtype: sprockets.http.app.Application """ before_run = [] if before_run is None else before_run on_start = [] if on_start is None else on_start shutdown = [] if shutdown is None else shutdown if not isinstance(application, Application): application = _ApplicationAdapter(application) application.before_run_callbacks.extend(before_run) application.on_start_callbacks.extend(on_start) application.on_shutdown_callbacks.extend(shutdown) return application
python
def wrap_application(application, before_run, on_start, shutdown): """ Wrap a tornado application in a callback-aware wrapper. :param tornado.web.Application application: application to wrap. :param list|NoneType before_run: optional list of callbacks to invoke before the IOLoop is started. :param list|NoneType on_start: optional list of callbacks to register with :meth:`~tornado.IOLoop.spawn_callback`. :param list|NoneType shutdown: optional list of callbacks to invoke before stopping the IOLoop :return: a wrapped application object :rtype: sprockets.http.app.Application """ before_run = [] if before_run is None else before_run on_start = [] if on_start is None else on_start shutdown = [] if shutdown is None else shutdown if not isinstance(application, Application): application = _ApplicationAdapter(application) application.before_run_callbacks.extend(before_run) application.on_start_callbacks.extend(on_start) application.on_shutdown_callbacks.extend(shutdown) return application
[ "def", "wrap_application", "(", "application", ",", "before_run", ",", "on_start", ",", "shutdown", ")", ":", "before_run", "=", "[", "]", "if", "before_run", "is", "None", "else", "before_run", "on_start", "=", "[", "]", "if", "on_start", "is", "None", "e...
Wrap a tornado application in a callback-aware wrapper. :param tornado.web.Application application: application to wrap. :param list|NoneType before_run: optional list of callbacks to invoke before the IOLoop is started. :param list|NoneType on_start: optional list of callbacks to register with :meth:`~tornado.IOLoop.spawn_callback`. :param list|NoneType shutdown: optional list of callbacks to invoke before stopping the IOLoop :return: a wrapped application object :rtype: sprockets.http.app.Application
[ "Wrap", "a", "tornado", "application", "in", "a", "callback", "-", "aware", "wrapper", "." ]
8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3
https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/app.py#L229-L257
train
51,934
sprockets/sprockets.http
sprockets/http/app.py
CallbackManager.start
def start(self, io_loop): """ Run the ``before_run`` callbacks and queue to ``on_start`` callbacks. :param tornado.ioloop.IOLoop io_loop: loop to start the app on. """ for callback in self.before_run_callbacks: try: callback(self.tornado_application, io_loop) except Exception: self.logger.error('before_run callback %r cancelled start', callback, exc_info=1) self.stop(io_loop) raise for callback in self.on_start_callbacks: io_loop.spawn_callback(callback, self.tornado_application, io_loop)
python
def start(self, io_loop): """ Run the ``before_run`` callbacks and queue to ``on_start`` callbacks. :param tornado.ioloop.IOLoop io_loop: loop to start the app on. """ for callback in self.before_run_callbacks: try: callback(self.tornado_application, io_loop) except Exception: self.logger.error('before_run callback %r cancelled start', callback, exc_info=1) self.stop(io_loop) raise for callback in self.on_start_callbacks: io_loop.spawn_callback(callback, self.tornado_application, io_loop)
[ "def", "start", "(", "self", ",", "io_loop", ")", ":", "for", "callback", "in", "self", ".", "before_run_callbacks", ":", "try", ":", "callback", "(", "self", ".", "tornado_application", ",", "io_loop", ")", "except", "Exception", ":", "self", ".", "logger...
Run the ``before_run`` callbacks and queue to ``on_start`` callbacks. :param tornado.ioloop.IOLoop io_loop: loop to start the app on.
[ "Run", "the", "before_run", "callbacks", "and", "queue", "to", "on_start", "callbacks", "." ]
8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3
https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/app.py#L87-L104
train
51,935
sprockets/sprockets.http
sprockets/http/app.py
CallbackManager.stop
def stop(self, io_loop): """ Asynchronously stop the application. :param tornado.ioloop.IOLoop io_loop: loop to run until all callbacks, timeouts, and queued calls are complete Call this method to start the application shutdown process. The IOLoop will be stopped once the application is completely shut down. """ running_async = False shutdown = _ShutdownHandler(io_loop) for callback in self.on_shutdown_callbacks: try: maybe_future = callback(self.tornado_application) if asyncio.iscoroutine(maybe_future): maybe_future = asyncio.create_task(maybe_future) if concurrent.is_future(maybe_future): shutdown.add_future(maybe_future) running_async = True except Exception as error: self.logger.warning('exception raised from shutdown ' 'callback %r, ignored: %s', callback, error, exc_info=1) if not running_async: shutdown.on_shutdown_ready()
python
def stop(self, io_loop): """ Asynchronously stop the application. :param tornado.ioloop.IOLoop io_loop: loop to run until all callbacks, timeouts, and queued calls are complete Call this method to start the application shutdown process. The IOLoop will be stopped once the application is completely shut down. """ running_async = False shutdown = _ShutdownHandler(io_loop) for callback in self.on_shutdown_callbacks: try: maybe_future = callback(self.tornado_application) if asyncio.iscoroutine(maybe_future): maybe_future = asyncio.create_task(maybe_future) if concurrent.is_future(maybe_future): shutdown.add_future(maybe_future) running_async = True except Exception as error: self.logger.warning('exception raised from shutdown ' 'callback %r, ignored: %s', callback, error, exc_info=1) if not running_async: shutdown.on_shutdown_ready()
[ "def", "stop", "(", "self", ",", "io_loop", ")", ":", "running_async", "=", "False", "shutdown", "=", "_ShutdownHandler", "(", "io_loop", ")", "for", "callback", "in", "self", ".", "on_shutdown_callbacks", ":", "try", ":", "maybe_future", "=", "callback", "(...
Asynchronously stop the application. :param tornado.ioloop.IOLoop io_loop: loop to run until all callbacks, timeouts, and queued calls are complete Call this method to start the application shutdown process. The IOLoop will be stopped once the application is completely shut down.
[ "Asynchronously", "stop", "the", "application", "." ]
8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3
https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/app.py#L106-L136
train
51,936
sunlightlabs/django-mediasync
mediasync/__init__.py
sync
def sync(client=None, force=False, verbose=True): """ Let's face it... pushing this stuff to S3 is messy. A lot of different things need to be calculated for each file and they have to be in a certain order as some variables rely on others. """ from mediasync import backends from mediasync.conf import msettings from mediasync.signals import pre_sync, post_sync # create client connection if client is None: client = backends.client() client.open() client.serve_remote = True # send pre-sync signal pre_sync.send(sender=client) # # sync joined media # for joinfile, sourcefiles in msettings['JOINED'].iteritems(): filedata = combine_files(joinfile, sourcefiles, client) if filedata is None: # combine_files() is only interested in CSS/JS files. continue filedata, dirname = filedata content_type = mimetypes.guess_type(joinfile)[0] or msettings['DEFAULT_MIMETYPE'] remote_path = joinfile if dirname: remote_path = "%s/%s" % (dirname, remote_path) if client.process_and_put(filedata, content_type, remote_path, force=force): if verbose: print "[%s] %s" % (content_type, remote_path) # # sync static media # for dirname in os.listdir(client.media_root): dirpath = os.path.abspath(os.path.join(client.media_root, dirname)) if os.path.isdir(dirpath): for filename in listdir_recursive(dirpath): # calculate local and remote paths filepath = os.path.join(dirpath, filename) remote_path = "%s/%s" % (dirname, filename) content_type = mimetypes.guess_type(filepath)[0] or msettings['DEFAULT_MIMETYPE'] if not is_syncable_file(os.path.basename(filename)) or not os.path.isfile(filepath): continue # hidden file or directory, do not upload filedata = open(filepath, 'rb').read() if client.process_and_put(filedata, content_type, remote_path, force=force): if verbose: print "[%s] %s" % (content_type, remote_path) # send post-sync signal while client is still open post_sync.send(sender=client) client.close()
python
def sync(client=None, force=False, verbose=True): """ Let's face it... pushing this stuff to S3 is messy. A lot of different things need to be calculated for each file and they have to be in a certain order as some variables rely on others. """ from mediasync import backends from mediasync.conf import msettings from mediasync.signals import pre_sync, post_sync # create client connection if client is None: client = backends.client() client.open() client.serve_remote = True # send pre-sync signal pre_sync.send(sender=client) # # sync joined media # for joinfile, sourcefiles in msettings['JOINED'].iteritems(): filedata = combine_files(joinfile, sourcefiles, client) if filedata is None: # combine_files() is only interested in CSS/JS files. continue filedata, dirname = filedata content_type = mimetypes.guess_type(joinfile)[0] or msettings['DEFAULT_MIMETYPE'] remote_path = joinfile if dirname: remote_path = "%s/%s" % (dirname, remote_path) if client.process_and_put(filedata, content_type, remote_path, force=force): if verbose: print "[%s] %s" % (content_type, remote_path) # # sync static media # for dirname in os.listdir(client.media_root): dirpath = os.path.abspath(os.path.join(client.media_root, dirname)) if os.path.isdir(dirpath): for filename in listdir_recursive(dirpath): # calculate local and remote paths filepath = os.path.join(dirpath, filename) remote_path = "%s/%s" % (dirname, filename) content_type = mimetypes.guess_type(filepath)[0] or msettings['DEFAULT_MIMETYPE'] if not is_syncable_file(os.path.basename(filename)) or not os.path.isfile(filepath): continue # hidden file or directory, do not upload filedata = open(filepath, 'rb').read() if client.process_and_put(filedata, content_type, remote_path, force=force): if verbose: print "[%s] %s" % (content_type, remote_path) # send post-sync signal while client is still open post_sync.send(sender=client) client.close()
[ "def", "sync", "(", "client", "=", "None", ",", "force", "=", "False", ",", "verbose", "=", "True", ")", ":", "from", "mediasync", "import", "backends", "from", "mediasync", ".", "conf", "import", "msettings", "from", "mediasync", ".", "signals", "import",...
Let's face it... pushing this stuff to S3 is messy. A lot of different things need to be calculated for each file and they have to be in a certain order as some variables rely on others.
[ "Let", "s", "face", "it", "...", "pushing", "this", "stuff", "to", "S3", "is", "messy", ".", "A", "lot", "of", "different", "things", "need", "to", "be", "calculated", "for", "each", "file", "and", "they", "have", "to", "be", "in", "a", "certain", "o...
aa8ce4cfff757bbdb488463c64c0863cca6a1932
https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/__init__.py#L101-L173
train
51,937
VitorRamos/cpufreq
cpufreq/cpufreq.py
cpuFreq.enable_all_cpu
def enable_all_cpu(self): ''' Enable all offline cpus ''' for cpu in self.__get_ranges("offline"): fpath = path.join("cpu%i"%cpu,"online") self.__write_cpu_file(fpath, b"1")
python
def enable_all_cpu(self): ''' Enable all offline cpus ''' for cpu in self.__get_ranges("offline"): fpath = path.join("cpu%i"%cpu,"online") self.__write_cpu_file(fpath, b"1")
[ "def", "enable_all_cpu", "(", "self", ")", ":", "for", "cpu", "in", "self", ".", "__get_ranges", "(", "\"offline\"", ")", ":", "fpath", "=", "path", ".", "join", "(", "\"cpu%i\"", "%", "cpu", ",", "\"online\"", ")", "self", ".", "__write_cpu_file", "(", ...
Enable all offline cpus
[ "Enable", "all", "offline", "cpus" ]
1246e35a8ceeb823df804af34730f7b15dc89204
https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L93-L99
train
51,938
VitorRamos/cpufreq
cpufreq/cpufreq.py
cpuFreq.reset
def reset(self, rg=None): ''' Enable all offline cpus, and reset max and min frequencies files rg: range or list of threads to reset ''' if type(rg) == int: rg= [rg] to_reset= rg if rg else self.__get_ranges("present") self.enable_cpu(to_reset) for cpu in to_reset: fpath = path.join("cpu%i"%cpu,"cpufreq","cpuinfo_max_freq") max_freq = self.__read_cpu_file(fpath) fpath = path.join("cpu%i"%cpu,"cpufreq","cpuinfo_min_freq") min_freq = self.__read_cpu_file(fpath) fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_max_freq") self.__write_cpu_file(fpath, max_freq.encode()) fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_min_freq") self.__write_cpu_file(fpath, min_freq.encode())
python
def reset(self, rg=None): ''' Enable all offline cpus, and reset max and min frequencies files rg: range or list of threads to reset ''' if type(rg) == int: rg= [rg] to_reset= rg if rg else self.__get_ranges("present") self.enable_cpu(to_reset) for cpu in to_reset: fpath = path.join("cpu%i"%cpu,"cpufreq","cpuinfo_max_freq") max_freq = self.__read_cpu_file(fpath) fpath = path.join("cpu%i"%cpu,"cpufreq","cpuinfo_min_freq") min_freq = self.__read_cpu_file(fpath) fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_max_freq") self.__write_cpu_file(fpath, max_freq.encode()) fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_min_freq") self.__write_cpu_file(fpath, min_freq.encode())
[ "def", "reset", "(", "self", ",", "rg", "=", "None", ")", ":", "if", "type", "(", "rg", ")", "==", "int", ":", "rg", "=", "[", "rg", "]", "to_reset", "=", "rg", "if", "rg", "else", "self", ".", "__get_ranges", "(", "\"present\"", ")", "self", "...
Enable all offline cpus, and reset max and min frequencies files rg: range or list of threads to reset
[ "Enable", "all", "offline", "cpus", "and", "reset", "max", "and", "min", "frequencies", "files" ]
1246e35a8ceeb823df804af34730f7b15dc89204
https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L101-L120
train
51,939
VitorRamos/cpufreq
cpufreq/cpufreq.py
cpuFreq.disable_hyperthread
def disable_hyperthread(self): ''' Disable all threads attached to the same core ''' to_disable = [] online_cpus = self.__get_ranges("online") for cpu in online_cpus: fpath = path.join("cpu%i"%cpu,"topology","thread_siblings_list") to_disable += self.__get_ranges(fpath)[1:] to_disable = set(to_disable) & set(online_cpus) for cpu in to_disable: fpath = path.join("cpu%i"%cpu,"online") self.__write_cpu_file(fpath, b"0")
python
def disable_hyperthread(self): ''' Disable all threads attached to the same core ''' to_disable = [] online_cpus = self.__get_ranges("online") for cpu in online_cpus: fpath = path.join("cpu%i"%cpu,"topology","thread_siblings_list") to_disable += self.__get_ranges(fpath)[1:] to_disable = set(to_disable) & set(online_cpus) for cpu in to_disable: fpath = path.join("cpu%i"%cpu,"online") self.__write_cpu_file(fpath, b"0")
[ "def", "disable_hyperthread", "(", "self", ")", ":", "to_disable", "=", "[", "]", "online_cpus", "=", "self", ".", "__get_ranges", "(", "\"online\"", ")", "for", "cpu", "in", "online_cpus", ":", "fpath", "=", "path", ".", "join", "(", "\"cpu%i\"", "%", "...
Disable all threads attached to the same core
[ "Disable", "all", "threads", "attached", "to", "the", "same", "core" ]
1246e35a8ceeb823df804af34730f7b15dc89204
https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L122-L135
train
51,940
VitorRamos/cpufreq
cpufreq/cpufreq.py
cpuFreq.set_frequencies
def set_frequencies(self, freq, rg=None, setMaxfeq=True, setMinfreq=True, setSpeed=True): ''' Set cores frequencies freq: int frequency in KHz rg: list of range of cores setMaxfeq: set the maximum frequency, default to true setMinfreq: set the minimum frequency, default to true setSpeed: only set the frequency, default to true ''' to_change = self.__get_ranges("online") if type(rg) == int: rg= [rg] if rg: to_change= set(rg) & set(self.__get_ranges("online")) for cpu in to_change: if setSpeed: fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_setspeed") self.__write_cpu_file(fpath, str(freq).encode()) if setMinfreq: fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_min_freq") self.__write_cpu_file(fpath, str(freq).encode()) if setMaxfeq: fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_max_freq") self.__write_cpu_file(fpath, str(freq).encode())
python
def set_frequencies(self, freq, rg=None, setMaxfeq=True, setMinfreq=True, setSpeed=True): ''' Set cores frequencies freq: int frequency in KHz rg: list of range of cores setMaxfeq: set the maximum frequency, default to true setMinfreq: set the minimum frequency, default to true setSpeed: only set the frequency, default to true ''' to_change = self.__get_ranges("online") if type(rg) == int: rg= [rg] if rg: to_change= set(rg) & set(self.__get_ranges("online")) for cpu in to_change: if setSpeed: fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_setspeed") self.__write_cpu_file(fpath, str(freq).encode()) if setMinfreq: fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_min_freq") self.__write_cpu_file(fpath, str(freq).encode()) if setMaxfeq: fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_max_freq") self.__write_cpu_file(fpath, str(freq).encode())
[ "def", "set_frequencies", "(", "self", ",", "freq", ",", "rg", "=", "None", ",", "setMaxfeq", "=", "True", ",", "setMinfreq", "=", "True", ",", "setSpeed", "=", "True", ")", ":", "to_change", "=", "self", ".", "__get_ranges", "(", "\"online\"", ")", "i...
Set cores frequencies freq: int frequency in KHz rg: list of range of cores setMaxfeq: set the maximum frequency, default to true setMinfreq: set the minimum frequency, default to true setSpeed: only set the frequency, default to true
[ "Set", "cores", "frequencies" ]
1246e35a8ceeb823df804af34730f7b15dc89204
https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L163-L186
train
51,941
VitorRamos/cpufreq
cpufreq/cpufreq.py
cpuFreq.get_available_frequencies
def get_available_frequencies(self): ''' Get all possible frequencies ''' fpath = path.join("cpu0","cpufreq","scaling_available_frequencies") data = self.__read_cpu_file(fpath).rstrip("\n").split() return data
python
def get_available_frequencies(self): ''' Get all possible frequencies ''' fpath = path.join("cpu0","cpufreq","scaling_available_frequencies") data = self.__read_cpu_file(fpath).rstrip("\n").split() return data
[ "def", "get_available_frequencies", "(", "self", ")", ":", "fpath", "=", "path", ".", "join", "(", "\"cpu0\"", ",", "\"cpufreq\"", ",", "\"scaling_available_frequencies\"", ")", "data", "=", "self", ".", "__read_cpu_file", "(", "fpath", ")", ".", "rstrip", "("...
Get all possible frequencies
[ "Get", "all", "possible", "frequencies" ]
1246e35a8ceeb823df804af34730f7b15dc89204
https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L203-L209
train
51,942
codeforamerica/three
three/core.py
Three.configure
def configure(self, endpoint=None, **kwargs): """Configure a previously initialized instance of the class.""" if endpoint: kwargs['endpoint'] = endpoint keywords = self._keywords.copy() keywords.update(kwargs) if 'endpoint' in kwargs: # Then we need to correctly format the endpoint. endpoint = kwargs['endpoint'] keywords['endpoint'] = self._configure_endpoint(endpoint) self.api_key = keywords['api_key'] or self._global_api_key() self.endpoint = keywords['endpoint'] self.format = keywords['format'] or 'json' self.jurisdiction = keywords['jurisdiction'] self.proxy = keywords['proxy'] self.discovery_url = keywords['discovery'] or None # Use a custom requests session and set the correct SSL version if # specified. self.session = requests.Session() if 'ssl_version' in keywords: self.session.mount('https://', SSLAdapter(keywords['ssl_version']))
python
def configure(self, endpoint=None, **kwargs): """Configure a previously initialized instance of the class.""" if endpoint: kwargs['endpoint'] = endpoint keywords = self._keywords.copy() keywords.update(kwargs) if 'endpoint' in kwargs: # Then we need to correctly format the endpoint. endpoint = kwargs['endpoint'] keywords['endpoint'] = self._configure_endpoint(endpoint) self.api_key = keywords['api_key'] or self._global_api_key() self.endpoint = keywords['endpoint'] self.format = keywords['format'] or 'json' self.jurisdiction = keywords['jurisdiction'] self.proxy = keywords['proxy'] self.discovery_url = keywords['discovery'] or None # Use a custom requests session and set the correct SSL version if # specified. self.session = requests.Session() if 'ssl_version' in keywords: self.session.mount('https://', SSLAdapter(keywords['ssl_version']))
[ "def", "configure", "(", "self", ",", "endpoint", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "endpoint", ":", "kwargs", "[", "'endpoint'", "]", "=", "endpoint", "keywords", "=", "self", ".", "_keywords", ".", "copy", "(", ")", "keywords", ...
Configure a previously initialized instance of the class.
[ "Configure", "a", "previously", "initialized", "instance", "of", "the", "class", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L66-L87
train
51,943
codeforamerica/three
three/core.py
Three._configure_endpoint
def _configure_endpoint(self, endpoint): """Configure the endpoint with a schema and end slash.""" if not endpoint.startswith('http'): endpoint = 'https://' + endpoint if not endpoint.endswith('/'): endpoint += '/' return endpoint
python
def _configure_endpoint(self, endpoint): """Configure the endpoint with a schema and end slash.""" if not endpoint.startswith('http'): endpoint = 'https://' + endpoint if not endpoint.endswith('/'): endpoint += '/' return endpoint
[ "def", "_configure_endpoint", "(", "self", ",", "endpoint", ")", ":", "if", "not", "endpoint", ".", "startswith", "(", "'http'", ")", ":", "endpoint", "=", "'https://'", "+", "endpoint", "if", "not", "endpoint", ".", "endswith", "(", "'/'", ")", ":", "en...
Configure the endpoint with a schema and end slash.
[ "Configure", "the", "endpoint", "with", "a", "schema", "and", "end", "slash", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L89-L95
train
51,944
codeforamerica/three
three/core.py
Three.get
def get(self, *args, **kwargs): """Perform a get request.""" if 'convert' in kwargs: conversion = kwargs.pop('convert') else: conversion = True kwargs = self._get_keywords(**kwargs) url = self._create_path(*args) request = self.session.get(url, params=kwargs) content = request.content self._request = request return self.convert(content, conversion)
python
def get(self, *args, **kwargs): """Perform a get request.""" if 'convert' in kwargs: conversion = kwargs.pop('convert') else: conversion = True kwargs = self._get_keywords(**kwargs) url = self._create_path(*args) request = self.session.get(url, params=kwargs) content = request.content self._request = request return self.convert(content, conversion)
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'convert'", "in", "kwargs", ":", "conversion", "=", "kwargs", ".", "pop", "(", "'convert'", ")", "else", ":", "conversion", "=", "True", "kwargs", "=", "self", "...
Perform a get request.
[ "Perform", "a", "get", "request", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L107-L118
train
51,945
codeforamerica/three
three/core.py
Three._get_keywords
def _get_keywords(self, **kwargs): """Format GET request parameters and keywords.""" if self.jurisdiction and 'jurisdiction_id' not in kwargs: kwargs['jurisdiction_id'] = self.jurisdiction if 'count' in kwargs: kwargs['page_size'] = kwargs.pop('count') if 'start' in kwargs: start = kwargs.pop('start') if 'end' in kwargs: end = kwargs.pop('end') else: end = date.today().strftime('%m-%d-%Y') start, end = self._format_dates(start, end) kwargs['start_date'] = start kwargs['end_date'] = end elif 'between' in kwargs: start, end = kwargs.pop('between') start, end = self._format_dates(start, end) kwargs['start_date'] = start kwargs['end_date'] = end return kwargs
python
def _get_keywords(self, **kwargs): """Format GET request parameters and keywords.""" if self.jurisdiction and 'jurisdiction_id' not in kwargs: kwargs['jurisdiction_id'] = self.jurisdiction if 'count' in kwargs: kwargs['page_size'] = kwargs.pop('count') if 'start' in kwargs: start = kwargs.pop('start') if 'end' in kwargs: end = kwargs.pop('end') else: end = date.today().strftime('%m-%d-%Y') start, end = self._format_dates(start, end) kwargs['start_date'] = start kwargs['end_date'] = end elif 'between' in kwargs: start, end = kwargs.pop('between') start, end = self._format_dates(start, end) kwargs['start_date'] = start kwargs['end_date'] = end return kwargs
[ "def", "_get_keywords", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "jurisdiction", "and", "'jurisdiction_id'", "not", "in", "kwargs", ":", "kwargs", "[", "'jurisdiction_id'", "]", "=", "self", ".", "jurisdiction", "if", "'count'", "...
Format GET request parameters and keywords.
[ "Format", "GET", "request", "parameters", "and", "keywords", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L120-L140
train
51,946
codeforamerica/three
three/core.py
Three._format_dates
def _format_dates(self, start, end): """Format start and end dates.""" start = self._split_date(start) end = self._split_date(end) return start, end
python
def _format_dates(self, start, end): """Format start and end dates.""" start = self._split_date(start) end = self._split_date(end) return start, end
[ "def", "_format_dates", "(", "self", ",", "start", ",", "end", ")", ":", "start", "=", "self", ".", "_split_date", "(", "start", ")", "end", "=", "self", ".", "_split_date", "(", "end", ")", "return", "start", ",", "end" ]
Format start and end dates.
[ "Format", "start", "and", "end", "dates", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L142-L146
train
51,947
codeforamerica/three
three/core.py
Three._split_date
def _split_date(self, time): """Split apart a date string.""" if isinstance(time, str): month, day, year = [int(t) for t in re.split(r'-|/', time)] if year < 100: # Quick hack for dates < 2000. year += 2000 time = date(year, month, day) return time.strftime('%Y-%m-%dT%H:%M:%SZ')
python
def _split_date(self, time): """Split apart a date string.""" if isinstance(time, str): month, day, year = [int(t) for t in re.split(r'-|/', time)] if year < 100: # Quick hack for dates < 2000. year += 2000 time = date(year, month, day) return time.strftime('%Y-%m-%dT%H:%M:%SZ')
[ "def", "_split_date", "(", "self", ",", "time", ")", ":", "if", "isinstance", "(", "time", ",", "str", ")", ":", "month", ",", "day", ",", "year", "=", "[", "int", "(", "t", ")", "for", "t", "in", "re", ".", "split", "(", "r'-|/'", ",", "time",...
Split apart a date string.
[ "Split", "apart", "a", "date", "string", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L148-L156
train
51,948
codeforamerica/three
three/core.py
Three.convert
def convert(self, content, conversion): """Convert content to Python data structures.""" if not conversion: data = content elif self.format == 'json': data = json.loads(content) elif self.format == 'xml': content = xml(content) first = list(content.keys())[0] data = content[first] else: data = content return data
python
def convert(self, content, conversion): """Convert content to Python data structures.""" if not conversion: data = content elif self.format == 'json': data = json.loads(content) elif self.format == 'xml': content = xml(content) first = list(content.keys())[0] data = content[first] else: data = content return data
[ "def", "convert", "(", "self", ",", "content", ",", "conversion", ")", ":", "if", "not", "conversion", ":", "data", "=", "content", "elif", "self", ".", "format", "==", "'json'", ":", "data", "=", "json", ".", "loads", "(", "content", ")", "elif", "s...
Convert content to Python data structures.
[ "Convert", "content", "to", "Python", "data", "structures", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L158-L170
train
51,949
codeforamerica/three
three/core.py
Three.discovery
def discovery(self, url=None): """ Retrieve the standard discovery file that provides routing information. >>> Three().discovery() {'discovery': 'data'} """ if url: data = self.session.get(url).content elif self.discovery_url: response = self.session.get(self.discovery_url) if self.format == 'xml': # Because, SF doesn't follow the spec. data = xml(response.text) else: # Spec calls for discovery always allowing JSON. data = response.json() else: data = self.get('discovery') return data
python
def discovery(self, url=None): """ Retrieve the standard discovery file that provides routing information. >>> Three().discovery() {'discovery': 'data'} """ if url: data = self.session.get(url).content elif self.discovery_url: response = self.session.get(self.discovery_url) if self.format == 'xml': # Because, SF doesn't follow the spec. data = xml(response.text) else: # Spec calls for discovery always allowing JSON. data = response.json() else: data = self.get('discovery') return data
[ "def", "discovery", "(", "self", ",", "url", "=", "None", ")", ":", "if", "url", ":", "data", "=", "self", ".", "session", ".", "get", "(", "url", ")", ".", "content", "elif", "self", ".", "discovery_url", ":", "response", "=", "self", ".", "sessio...
Retrieve the standard discovery file that provides routing information. >>> Three().discovery() {'discovery': 'data'}
[ "Retrieve", "the", "standard", "discovery", "file", "that", "provides", "routing", "information", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L172-L192
train
51,950
codeforamerica/three
three/core.py
Three.services
def services(self, code=None, **kwargs): """ Retrieve information about available services. You can also enter a specific service code argument. >>> Three().services() {'all': {'service_code': 'data'}} >>> Three().services('033') {'033': {'service_code': 'data'}} """ data = self.get('services', code, **kwargs) return data
python
def services(self, code=None, **kwargs): """ Retrieve information about available services. You can also enter a specific service code argument. >>> Three().services() {'all': {'service_code': 'data'}} >>> Three().services('033') {'033': {'service_code': 'data'}} """ data = self.get('services', code, **kwargs) return data
[ "def", "services", "(", "self", ",", "code", "=", "None", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "get", "(", "'services'", ",", "code", ",", "*", "*", "kwargs", ")", "return", "data" ]
Retrieve information about available services. You can also enter a specific service code argument. >>> Three().services() {'all': {'service_code': 'data'}} >>> Three().services('033') {'033': {'service_code': 'data'}}
[ "Retrieve", "information", "about", "available", "services", ".", "You", "can", "also", "enter", "a", "specific", "service", "code", "argument", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L194-L205
train
51,951
codeforamerica/three
three/core.py
Three.requests
def requests(self, code=None, **kwargs): """ Retrieve open requests. You can also enter a specific service code argument. >>> Three('api.city.gov').requests() {'all': {'requests': 'data'}} >>> Three('api.city.gov').requests('123') {'123': {'requests': 'data'}} """ if code: kwargs['service_code'] = code data = self.get('requests', **kwargs) return data
python
def requests(self, code=None, **kwargs): """ Retrieve open requests. You can also enter a specific service code argument. >>> Three('api.city.gov').requests() {'all': {'requests': 'data'}} >>> Three('api.city.gov').requests('123') {'123': {'requests': 'data'}} """ if code: kwargs['service_code'] = code data = self.get('requests', **kwargs) return data
[ "def", "requests", "(", "self", ",", "code", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "code", ":", "kwargs", "[", "'service_code'", "]", "=", "code", "data", "=", "self", ".", "get", "(", "'requests'", ",", "*", "*", "kwargs", ")", "...
Retrieve open requests. You can also enter a specific service code argument. >>> Three('api.city.gov').requests() {'all': {'requests': 'data'}} >>> Three('api.city.gov').requests('123') {'123': {'requests': 'data'}}
[ "Retrieve", "open", "requests", ".", "You", "can", "also", "enter", "a", "specific", "service", "code", "argument", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L207-L220
train
51,952
codeforamerica/three
three/core.py
Three.request
def request(self, id, **kwargs): """ Retrieve a specific request using its service code ID. >>> Three('api.city.gov').request('12345') {'request': {'service_code': {'12345': 'data'}}} """ data = self.get('requests', id, **kwargs) return data
python
def request(self, id, **kwargs): """ Retrieve a specific request using its service code ID. >>> Three('api.city.gov').request('12345') {'request': {'service_code': {'12345': 'data'}}} """ data = self.get('requests', id, **kwargs) return data
[ "def", "request", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "get", "(", "'requests'", ",", "id", ",", "*", "*", "kwargs", ")", "return", "data" ]
Retrieve a specific request using its service code ID. >>> Three('api.city.gov').request('12345') {'request': {'service_code': {'12345': 'data'}}}
[ "Retrieve", "a", "specific", "request", "using", "its", "service", "code", "ID", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L222-L230
train
51,953
codeforamerica/three
three/core.py
Three.post
def post(self, service_code='0', **kwargs): """ Post a new Open311 request. >>> t = Three('api.city.gov') >>> t.post('123', address='123 Any St', name='Zach Williams', ... phone='555-5555', description='My issue description.', ... media=open('photo.png', 'rb')) {'successful': {'request': 'post'}} """ kwargs['service_code'] = service_code kwargs = self._post_keywords(**kwargs) media = kwargs.pop('media', None) if media: files = {'media': media} else: files = None url = self._create_path('requests') self.post_response = self.session.post(url, data=kwargs, files=files) content = self.post_response.content if self.post_response.status_code >= 500: conversion = False else: conversion = True return self.convert(content, conversion)
python
def post(self, service_code='0', **kwargs): """ Post a new Open311 request. >>> t = Three('api.city.gov') >>> t.post('123', address='123 Any St', name='Zach Williams', ... phone='555-5555', description='My issue description.', ... media=open('photo.png', 'rb')) {'successful': {'request': 'post'}} """ kwargs['service_code'] = service_code kwargs = self._post_keywords(**kwargs) media = kwargs.pop('media', None) if media: files = {'media': media} else: files = None url = self._create_path('requests') self.post_response = self.session.post(url, data=kwargs, files=files) content = self.post_response.content if self.post_response.status_code >= 500: conversion = False else: conversion = True return self.convert(content, conversion)
[ "def", "post", "(", "self", ",", "service_code", "=", "'0'", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'service_code'", "]", "=", "service_code", "kwargs", "=", "self", ".", "_post_keywords", "(", "*", "*", "kwargs", ")", "media", "=", "kwargs...
Post a new Open311 request. >>> t = Three('api.city.gov') >>> t.post('123', address='123 Any St', name='Zach Williams', ... phone='555-5555', description='My issue description.', ... media=open('photo.png', 'rb')) {'successful': {'request': 'post'}}
[ "Post", "a", "new", "Open311", "request", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L232-L257
train
51,954
codeforamerica/three
three/core.py
Three._post_keywords
def _post_keywords(self, **kwargs): """Configure keyword arguments for Open311 POST requests.""" if self.jurisdiction and 'jurisdiction_id' not in kwargs: kwargs['jurisdiction_id'] = self.jurisdiction if 'address' in kwargs: address = kwargs.pop('address') kwargs['address_string'] = address if 'name' in kwargs: first, last = kwargs.pop('name').split(' ') kwargs['first_name'] = first kwargs['last_name'] = last if 'api_key' not in kwargs: kwargs['api_key'] = self.api_key return kwargs
python
def _post_keywords(self, **kwargs): """Configure keyword arguments for Open311 POST requests.""" if self.jurisdiction and 'jurisdiction_id' not in kwargs: kwargs['jurisdiction_id'] = self.jurisdiction if 'address' in kwargs: address = kwargs.pop('address') kwargs['address_string'] = address if 'name' in kwargs: first, last = kwargs.pop('name').split(' ') kwargs['first_name'] = first kwargs['last_name'] = last if 'api_key' not in kwargs: kwargs['api_key'] = self.api_key return kwargs
[ "def", "_post_keywords", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "jurisdiction", "and", "'jurisdiction_id'", "not", "in", "kwargs", ":", "kwargs", "[", "'jurisdiction_id'", "]", "=", "self", ".", "jurisdiction", "if", "'address'", ...
Configure keyword arguments for Open311 POST requests.
[ "Configure", "keyword", "arguments", "for", "Open311", "POST", "requests", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L259-L272
train
51,955
codeforamerica/three
three/core.py
Three.token
def token(self, id, **kwargs): """ Retrieve a service request ID from a token. >>> Three('api.city.gov').token('12345') {'service_request_id': {'for': {'token': '12345'}}} """ data = self.get('tokens', id, **kwargs) return data
python
def token(self, id, **kwargs): """ Retrieve a service request ID from a token. >>> Three('api.city.gov').token('12345') {'service_request_id': {'for': {'token': '12345'}}} """ data = self.get('tokens', id, **kwargs) return data
[ "def", "token", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "get", "(", "'tokens'", ",", "id", ",", "*", "*", "kwargs", ")", "return", "data" ]
Retrieve a service request ID from a token. >>> Three('api.city.gov').token('12345') {'service_request_id': {'for': {'token': '12345'}}}
[ "Retrieve", "a", "service", "request", "ID", "from", "a", "token", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L274-L282
train
51,956
matllubos/django-is-core
is_core/utils/compatibility.py
CompatibilityWidgetMixin.build_attrs
def build_attrs(self, base_attrs, extra_attrs=None, **kwargs): """ Helper function for building an attribute dictionary. This is combination of the same method from Django<=1.10 and Django1.11+ """ attrs = dict(base_attrs, **kwargs) if extra_attrs: attrs.update(extra_attrs) return attrs
python
def build_attrs(self, base_attrs, extra_attrs=None, **kwargs): """ Helper function for building an attribute dictionary. This is combination of the same method from Django<=1.10 and Django1.11+ """ attrs = dict(base_attrs, **kwargs) if extra_attrs: attrs.update(extra_attrs) return attrs
[ "def", "build_attrs", "(", "self", ",", "base_attrs", ",", "extra_attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "attrs", "=", "dict", "(", "base_attrs", ",", "*", "*", "kwargs", ")", "if", "extra_attrs", ":", "attrs", ".", "update", "(", "e...
Helper function for building an attribute dictionary. This is combination of the same method from Django<=1.10 and Django1.11+
[ "Helper", "function", "for", "building", "an", "attribute", "dictionary", ".", "This", "is", "combination", "of", "the", "same", "method", "from", "Django<", "=", "1", ".", "10", "and", "Django1", ".", "11", "+" ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/compatibility.py#L74-L83
train
51,957
xapple/plumbing
plumbing/csv_tables.py
CSVTable.to_dataframe
def to_dataframe(self, **kwargs): """Load up the CSV file as a pandas dataframe""" return pandas.io.parsers.read_csv(self.path, sep=self.d, **kwargs)
python
def to_dataframe(self, **kwargs): """Load up the CSV file as a pandas dataframe""" return pandas.io.parsers.read_csv(self.path, sep=self.d, **kwargs)
[ "def", "to_dataframe", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "pandas", ".", "io", ".", "parsers", ".", "read_csv", "(", "self", ".", "path", ",", "sep", "=", "self", ".", "d", ",", "*", "*", "kwargs", ")" ]
Load up the CSV file as a pandas dataframe
[ "Load", "up", "the", "CSV", "file", "as", "a", "pandas", "dataframe" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/csv_tables.py#L61-L63
train
51,958
moonso/interval_tree
interval_tree/interval_tree.py
IntervalTree.get_elementary_intervals
def get_elementary_intervals(self, features): """Generates a sorted list of elementary intervals""" coords = [] try: for interval in features: if len(interval) != 3: raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval)) coords.extend([interval[0],interval[1]]) except IndexError: raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval)) coords = list(set(coords)) coords.sort() return coords
python
def get_elementary_intervals(self, features): """Generates a sorted list of elementary intervals""" coords = [] try: for interval in features: if len(interval) != 3: raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval)) coords.extend([interval[0],interval[1]]) except IndexError: raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval)) coords = list(set(coords)) coords.sort() return coords
[ "def", "get_elementary_intervals", "(", "self", ",", "features", ")", ":", "coords", "=", "[", "]", "try", ":", "for", "interval", "in", "features", ":", "if", "len", "(", "interval", ")", "!=", "3", ":", "raise", "SyntaxError", "(", "'Interval malformed %...
Generates a sorted list of elementary intervals
[ "Generates", "a", "sorted", "list", "of", "elementary", "intervals" ]
c588177f5bd90bd9e2f1447216c78b024353f7a1
https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L50-L62
train
51,959
moonso/interval_tree
interval_tree/interval_tree.py
IntervalTree.pt_within
def pt_within(self, pt, subject): """Accessory function to check if a point is within a range""" try: if pt >= int(subject[0]) and pt <= int(subject[1]): return True except ValueError: raise ValueError('Interval start and stop has to be integers. %s' % str(subject)) return False
python
def pt_within(self, pt, subject): """Accessory function to check if a point is within a range""" try: if pt >= int(subject[0]) and pt <= int(subject[1]): return True except ValueError: raise ValueError('Interval start and stop has to be integers. %s' % str(subject)) return False
[ "def", "pt_within", "(", "self", ",", "pt", ",", "subject", ")", ":", "try", ":", "if", "pt", ">=", "int", "(", "subject", "[", "0", "]", ")", "and", "pt", "<=", "int", "(", "subject", "[", "1", "]", ")", ":", "return", "True", "except", "Value...
Accessory function to check if a point is within a range
[ "Accessory", "function", "to", "check", "if", "a", "point", "is", "within", "a", "range" ]
c588177f5bd90bd9e2f1447216c78b024353f7a1
https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L99-L107
train
51,960
moonso/interval_tree
interval_tree/interval_tree.py
IntervalTree.is_within
def is_within(self, query, subject): """Accessory function to check if a range is fully within another range""" if self.pt_within(query[0], subject) and self.pt_within(query[1], subject): return True return False
python
def is_within(self, query, subject): """Accessory function to check if a range is fully within another range""" if self.pt_within(query[0], subject) and self.pt_within(query[1], subject): return True return False
[ "def", "is_within", "(", "self", ",", "query", ",", "subject", ")", ":", "if", "self", ".", "pt_within", "(", "query", "[", "0", "]", ",", "subject", ")", "and", "self", ".", "pt_within", "(", "query", "[", "1", "]", ",", "subject", ")", ":", "re...
Accessory function to check if a range is fully within another range
[ "Accessory", "function", "to", "check", "if", "a", "range", "is", "fully", "within", "another", "range" ]
c588177f5bd90bd9e2f1447216c78b024353f7a1
https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L109-L114
train
51,961
moonso/interval_tree
interval_tree/interval_tree.py
IntervalTree.overlap
def overlap(self, query, subject): """Accessory function to check if two ranges overlap""" if (self.pt_within(query[0], subject) or self.pt_within(query[1], subject) or self.pt_within(subject[0], query) or self.pt_within(subject[1], query)): return True return False
python
def overlap(self, query, subject): """Accessory function to check if two ranges overlap""" if (self.pt_within(query[0], subject) or self.pt_within(query[1], subject) or self.pt_within(subject[0], query) or self.pt_within(subject[1], query)): return True return False
[ "def", "overlap", "(", "self", ",", "query", ",", "subject", ")", ":", "if", "(", "self", ".", "pt_within", "(", "query", "[", "0", "]", ",", "subject", ")", "or", "self", ".", "pt_within", "(", "query", "[", "1", "]", ",", "subject", ")", "or", ...
Accessory function to check if two ranges overlap
[ "Accessory", "function", "to", "check", "if", "two", "ranges", "overlap" ]
c588177f5bd90bd9e2f1447216c78b024353f7a1
https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L116-L122
train
51,962
moonso/interval_tree
interval_tree/interval_tree.py
IntervalTree.recursive_insert
def recursive_insert(self, node, coord, data, start, end): """Recursively inserts id data into nodes""" if node[0] != -1: left = (start, node[0]) right = (node[0], end) #if left is totally within coord if self.is_within(left, coord): node[1][-1].append(data) elif self.overlap(left, coord): self.recursive_insert(node[1], coord, data, left[0], left[1]) if self.is_within(right, coord): node[2][-1].append(data) elif self.overlap(right, coord): self.recursive_insert(node[2], coord, data, right[0], right[1])
python
def recursive_insert(self, node, coord, data, start, end): """Recursively inserts id data into nodes""" if node[0] != -1: left = (start, node[0]) right = (node[0], end) #if left is totally within coord if self.is_within(left, coord): node[1][-1].append(data) elif self.overlap(left, coord): self.recursive_insert(node[1], coord, data, left[0], left[1]) if self.is_within(right, coord): node[2][-1].append(data) elif self.overlap(right, coord): self.recursive_insert(node[2], coord, data, right[0], right[1])
[ "def", "recursive_insert", "(", "self", ",", "node", ",", "coord", ",", "data", ",", "start", ",", "end", ")", ":", "if", "node", "[", "0", "]", "!=", "-", "1", ":", "left", "=", "(", "start", ",", "node", "[", "0", "]", ")", "right", "=", "(...
Recursively inserts id data into nodes
[ "Recursively", "inserts", "id", "data", "into", "nodes" ]
c588177f5bd90bd9e2f1447216c78b024353f7a1
https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L124-L139
train
51,963
moonso/interval_tree
interval_tree/interval_tree.py
IntervalTree.insert_data
def insert_data(self, node, data, start, end): """loops through all the data and inserts them into the empty tree""" for item in data: self.recursive_insert(node, [item[0], item[1]], item[-1], start, end)
python
def insert_data(self, node, data, start, end): """loops through all the data and inserts them into the empty tree""" for item in data: self.recursive_insert(node, [item[0], item[1]], item[-1], start, end)
[ "def", "insert_data", "(", "self", ",", "node", ",", "data", ",", "start", ",", "end", ")", ":", "for", "item", "in", "data", ":", "self", ".", "recursive_insert", "(", "node", ",", "[", "item", "[", "0", "]", ",", "item", "[", "1", "]", "]", "...
loops through all the data and inserts them into the empty tree
[ "loops", "through", "all", "the", "data", "and", "inserts", "them", "into", "the", "empty", "tree" ]
c588177f5bd90bd9e2f1447216c78b024353f7a1
https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L141-L144
train
51,964
moonso/interval_tree
interval_tree/interval_tree.py
IntervalTree.trim_tree
def trim_tree(self, node): """trims the tree for any empty data nodes""" data_len = len(node[-1]) if node[1] == -1 and node[2] == -1: if data_len == 0: return 1 else: return 0 else: if self.trim_tree(node[1]) == 1: node[1] = -1 if self.trim_tree(node[2]) == 1: node[2] = -1 if node[1] == -1 and node[2] == -1: if data_len == 0: return 1 else: return 0
python
def trim_tree(self, node): """trims the tree for any empty data nodes""" data_len = len(node[-1]) if node[1] == -1 and node[2] == -1: if data_len == 0: return 1 else: return 0 else: if self.trim_tree(node[1]) == 1: node[1] = -1 if self.trim_tree(node[2]) == 1: node[2] = -1 if node[1] == -1 and node[2] == -1: if data_len == 0: return 1 else: return 0
[ "def", "trim_tree", "(", "self", ",", "node", ")", ":", "data_len", "=", "len", "(", "node", "[", "-", "1", "]", ")", "if", "node", "[", "1", "]", "==", "-", "1", "and", "node", "[", "2", "]", "==", "-", "1", ":", "if", "data_len", "==", "0...
trims the tree for any empty data nodes
[ "trims", "the", "tree", "for", "any", "empty", "data", "nodes" ]
c588177f5bd90bd9e2f1447216c78b024353f7a1
https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L146-L166
train
51,965
moonso/interval_tree
interval_tree/interval_tree.py
IntervalTree.find
def find(self, node, interval, start, end): """recursively finds ids within a range""" data = [] if len(interval) != 2: raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval)) left = (start, node[0]) right = (node[0], end) if self.overlap(left, interval): data.extend(node[-1]) if node[1] != -1: data.extend(self.find(node[1], interval, left[0], left[1])) if self.overlap(right, interval): data.extend(node[-1]) if node[2] != -1: data.extend(self.find(node[2], interval, right[0], right[1])) return list(set(data))
python
def find(self, node, interval, start, end): """recursively finds ids within a range""" data = [] if len(interval) != 2: raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval)) left = (start, node[0]) right = (node[0], end) if self.overlap(left, interval): data.extend(node[-1]) if node[1] != -1: data.extend(self.find(node[1], interval, left[0], left[1])) if self.overlap(right, interval): data.extend(node[-1]) if node[2] != -1: data.extend(self.find(node[2], interval, right[0], right[1])) return list(set(data))
[ "def", "find", "(", "self", ",", "node", ",", "interval", ",", "start", ",", "end", ")", ":", "data", "=", "[", "]", "if", "len", "(", "interval", ")", "!=", "2", ":", "raise", "SyntaxError", "(", "'Interval malformed %s. Allways specify start and end positi...
recursively finds ids within a range
[ "recursively", "finds", "ids", "within", "a", "range" ]
c588177f5bd90bd9e2f1447216c78b024353f7a1
https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L168-L188
train
51,966
moonso/interval_tree
interval_tree/interval_tree.py
IntervalTree.find_range
def find_range(self, interval): """wrapper for find""" return self.find(self.tree, interval, self.start, self.end)
python
def find_range(self, interval): """wrapper for find""" return self.find(self.tree, interval, self.start, self.end)
[ "def", "find_range", "(", "self", ",", "interval", ")", ":", "return", "self", ".", "find", "(", "self", ".", "tree", ",", "interval", ",", "self", ".", "start", ",", "self", ".", "end", ")" ]
wrapper for find
[ "wrapper", "for", "find" ]
c588177f5bd90bd9e2f1447216c78b024353f7a1
https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L190-L192
train
51,967
moonso/interval_tree
interval_tree/interval_tree.py
IntervalTree.pprint
def pprint(self, ind): """pretty prints the tree with indentation""" pp = pprint.PrettyPrinter(indent=ind) pp.pprint(self.tree)
python
def pprint(self, ind): """pretty prints the tree with indentation""" pp = pprint.PrettyPrinter(indent=ind) pp.pprint(self.tree)
[ "def", "pprint", "(", "self", ",", "ind", ")", ":", "pp", "=", "pprint", ".", "PrettyPrinter", "(", "indent", "=", "ind", ")", "pp", ".", "pprint", "(", "self", ".", "tree", ")" ]
pretty prints the tree with indentation
[ "pretty", "prints", "the", "tree", "with", "indentation" ]
c588177f5bd90bd9e2f1447216c78b024353f7a1
https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L194-L197
train
51,968
matllubos/django-is-core
is_core/site.py
get_model_core
def get_model_core(model): """ Return core view of given model or None """ model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name)) return registered_model_cores.get(model_label)
python
def get_model_core(model): """ Return core view of given model or None """ model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name)) return registered_model_cores.get(model_label)
[ "def", "get_model_core", "(", "model", ")", ":", "model_label", "=", "lower", "(", "'%s.%s'", "%", "(", "model", ".", "_meta", ".", "app_label", ",", "model", ".", "_meta", ".", "object_name", ")", ")", "return", "registered_model_cores", ".", "get", "(", ...
Return core view of given model or None
[ "Return", "core", "view", "of", "given", "model", "or", "None" ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/site.py#L28-L33
train
51,969
vcs-python/libvcs
libvcs/shortcuts.py
create_repo
def create_repo(url, vcs, **kwargs): r"""Return a object representation of a VCS repository. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: >>> from libvcs.shortcuts import create_repo >>> r = create_repo( ... url='https://www.github.com/you/myrepo', ... vcs='git', ... repo_dir='/tmp/myrepo') >>> r.update_repo() |myrepo| (git) Repo directory for myrepo (git) does not exist @ \ /tmp/myrepo |myrepo| (git) Cloning. |myrepo| (git) git clone https://www.github.com/tony/myrepo \ /tmp/myrepo Cloning into '/tmp/myrepo'... Checking connectivity... done. |myrepo| (git) git fetch |myrepo| (git) git pull Already up-to-date. """ if vcs == 'git': return GitRepo(url, **kwargs) elif vcs == 'hg': return MercurialRepo(url, **kwargs) elif vcs == 'svn': return SubversionRepo(url, **kwargs) else: raise InvalidVCS('VCS %s is not a valid VCS' % vcs)
python
def create_repo(url, vcs, **kwargs): r"""Return a object representation of a VCS repository. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: >>> from libvcs.shortcuts import create_repo >>> r = create_repo( ... url='https://www.github.com/you/myrepo', ... vcs='git', ... repo_dir='/tmp/myrepo') >>> r.update_repo() |myrepo| (git) Repo directory for myrepo (git) does not exist @ \ /tmp/myrepo |myrepo| (git) Cloning. |myrepo| (git) git clone https://www.github.com/tony/myrepo \ /tmp/myrepo Cloning into '/tmp/myrepo'... Checking connectivity... done. |myrepo| (git) git fetch |myrepo| (git) git pull Already up-to-date. """ if vcs == 'git': return GitRepo(url, **kwargs) elif vcs == 'hg': return MercurialRepo(url, **kwargs) elif vcs == 'svn': return SubversionRepo(url, **kwargs) else: raise InvalidVCS('VCS %s is not a valid VCS' % vcs)
[ "def", "create_repo", "(", "url", ",", "vcs", ",", "*", "*", "kwargs", ")", ":", "if", "vcs", "==", "'git'", ":", "return", "GitRepo", "(", "url", ",", "*", "*", "kwargs", ")", "elif", "vcs", "==", "'hg'", ":", "return", "MercurialRepo", "(", "url"...
r"""Return a object representation of a VCS repository. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: >>> from libvcs.shortcuts import create_repo >>> r = create_repo( ... url='https://www.github.com/you/myrepo', ... vcs='git', ... repo_dir='/tmp/myrepo') >>> r.update_repo() |myrepo| (git) Repo directory for myrepo (git) does not exist @ \ /tmp/myrepo |myrepo| (git) Cloning. |myrepo| (git) git clone https://www.github.com/tony/myrepo \ /tmp/myrepo Cloning into '/tmp/myrepo'... Checking connectivity... done. |myrepo| (git) git fetch |myrepo| (git) git pull Already up-to-date.
[ "r", "Return", "a", "object", "representation", "of", "a", "VCS", "repository", "." ]
f7dc055250199bac6be7439b1d2240583f0bb354
https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/shortcuts.py#L8-L43
train
51,970
vcs-python/libvcs
libvcs/shortcuts.py
create_repo_from_pip_url
def create_repo_from_pip_url(pip_url, **kwargs): r"""Return a object representation of a VCS repository via pip-style url. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: >>> from libvcs.shortcuts import create_repo_from_pip_url >>> r = create_repo_from_pip_url( ... pip_url='git+https://www.github.com/you/myrepo', ... repo_dir='/tmp/myrepo') >>> r.update_repo() |myrepo| (git) Repo directory for myrepo (git) does not exist @ \ /tmp/myrepo |myrepo| (git) Cloning. |myrepo| (git) git clone https://www.github.com/tony/myrepo \ /tmp/myrepo Cloning into '/tmp/myrepo'... Checking connectivity... done. |myrepo| (git) git fetch |myrepo| (git) git pull Already up-to-date. """ if pip_url.startswith('git+'): return GitRepo.from_pip_url(pip_url, **kwargs) elif pip_url.startswith('hg+'): return MercurialRepo.from_pip_url(pip_url, **kwargs) elif pip_url.startswith('svn+'): return SubversionRepo.from_pip_url(pip_url, **kwargs) else: raise InvalidPipURL(pip_url)
python
def create_repo_from_pip_url(pip_url, **kwargs): r"""Return a object representation of a VCS repository via pip-style url. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: >>> from libvcs.shortcuts import create_repo_from_pip_url >>> r = create_repo_from_pip_url( ... pip_url='git+https://www.github.com/you/myrepo', ... repo_dir='/tmp/myrepo') >>> r.update_repo() |myrepo| (git) Repo directory for myrepo (git) does not exist @ \ /tmp/myrepo |myrepo| (git) Cloning. |myrepo| (git) git clone https://www.github.com/tony/myrepo \ /tmp/myrepo Cloning into '/tmp/myrepo'... Checking connectivity... done. |myrepo| (git) git fetch |myrepo| (git) git pull Already up-to-date. """ if pip_url.startswith('git+'): return GitRepo.from_pip_url(pip_url, **kwargs) elif pip_url.startswith('hg+'): return MercurialRepo.from_pip_url(pip_url, **kwargs) elif pip_url.startswith('svn+'): return SubversionRepo.from_pip_url(pip_url, **kwargs) else: raise InvalidPipURL(pip_url)
[ "def", "create_repo_from_pip_url", "(", "pip_url", ",", "*", "*", "kwargs", ")", ":", "if", "pip_url", ".", "startswith", "(", "'git+'", ")", ":", "return", "GitRepo", ".", "from_pip_url", "(", "pip_url", ",", "*", "*", "kwargs", ")", "elif", "pip_url", ...
r"""Return a object representation of a VCS repository via pip-style url. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: >>> from libvcs.shortcuts import create_repo_from_pip_url >>> r = create_repo_from_pip_url( ... pip_url='git+https://www.github.com/you/myrepo', ... repo_dir='/tmp/myrepo') >>> r.update_repo() |myrepo| (git) Repo directory for myrepo (git) does not exist @ \ /tmp/myrepo |myrepo| (git) Cloning. |myrepo| (git) git clone https://www.github.com/tony/myrepo \ /tmp/myrepo Cloning into '/tmp/myrepo'... Checking connectivity... done. |myrepo| (git) git fetch |myrepo| (git) git pull Already up-to-date.
[ "r", "Return", "a", "object", "representation", "of", "a", "VCS", "repository", "via", "pip", "-", "style", "url", "." ]
f7dc055250199bac6be7439b1d2240583f0bb354
https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/shortcuts.py#L46-L80
train
51,971
xapple/plumbing
plumbing/slurm/job.py
JobSLURM.set_paths
def set_paths(self, base_dir, script_path): """Set the directory, the script path and the outfile path""" # Make absolute paths # if 'change_dir' in self.kwargs: self.kwargs['change_dir'] = DirectoryPath(os.path.abspath(self.kwargs['change_dir'])) if 'out_file' in self.kwargs: self.kwargs['out_file'] = FilePath(os.path.abspath(self.kwargs['out_file'])) # In case there is a base directory # if base_dir is not None: self.base_dir = DirectoryPath(os.path.abspath(base_dir)) self.script_path = FilePath(base_dir + "run." + self.extensions[self.language]) self.kwargs['change_dir'] = base_dir self.kwargs['out_file'] = FilePath(base_dir + "run.out") # Other cases # if base_dir is None and script_path is None: self.script_path = FilePath(new_temp_path()) if script_path is not None: self.script_path = FilePath(os.path.abspath(script_path))
python
def set_paths(self, base_dir, script_path): """Set the directory, the script path and the outfile path""" # Make absolute paths # if 'change_dir' in self.kwargs: self.kwargs['change_dir'] = DirectoryPath(os.path.abspath(self.kwargs['change_dir'])) if 'out_file' in self.kwargs: self.kwargs['out_file'] = FilePath(os.path.abspath(self.kwargs['out_file'])) # In case there is a base directory # if base_dir is not None: self.base_dir = DirectoryPath(os.path.abspath(base_dir)) self.script_path = FilePath(base_dir + "run." + self.extensions[self.language]) self.kwargs['change_dir'] = base_dir self.kwargs['out_file'] = FilePath(base_dir + "run.out") # Other cases # if base_dir is None and script_path is None: self.script_path = FilePath(new_temp_path()) if script_path is not None: self.script_path = FilePath(os.path.abspath(script_path))
[ "def", "set_paths", "(", "self", ",", "base_dir", ",", "script_path", ")", ":", "# Make absolute paths #", "if", "'change_dir'", "in", "self", ".", "kwargs", ":", "self", ".", "kwargs", "[", "'change_dir'", "]", "=", "DirectoryPath", "(", "os", ".", "path", ...
Set the directory, the script path and the outfile path
[ "Set", "the", "directory", "the", "script", "path", "and", "the", "outfile", "path" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L121-L136
train
51,972
xapple/plumbing
plumbing/slurm/job.py
JobSLURM.slurm_params
def slurm_params(self): """The list of parameters to give to the `sbatch` command.""" # Main loop # result = OrderedDict() for param, info in self.slurm_headers.items(): if not info['needed'] and not param in self.kwargs: continue if param in self.kwargs: result[param] = self.kwargs.get(param) else: result[param] = info['default'] # Special cases # if result.get('cluster') == 'halvan': result['partition'] = 'halvan' # Return # return result
python
def slurm_params(self): """The list of parameters to give to the `sbatch` command.""" # Main loop # result = OrderedDict() for param, info in self.slurm_headers.items(): if not info['needed'] and not param in self.kwargs: continue if param in self.kwargs: result[param] = self.kwargs.get(param) else: result[param] = info['default'] # Special cases # if result.get('cluster') == 'halvan': result['partition'] = 'halvan' # Return # return result
[ "def", "slurm_params", "(", "self", ")", ":", "# Main loop #", "result", "=", "OrderedDict", "(", ")", "for", "param", ",", "info", "in", "self", ".", "slurm_headers", ".", "items", "(", ")", ":", "if", "not", "info", "[", "'needed'", "]", "and", "not"...
The list of parameters to give to the `sbatch` command.
[ "The", "list", "of", "parameters", "to", "give", "to", "the", "sbatch", "command", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L139-L150
train
51,973
xapple/plumbing
plumbing/slurm/job.py
JobSLURM.script
def script(self): """The script to be submitted to the SLURM queue.""" self.shebang_header = self.shebang_headers[self.language] self.slurm_header = [self.slurm_headers[k]['tag'] % v for k,v in self.slurm_params.items()] self.script_header = self.script_headers[self.language] self.script_footer = self.script_footers[self.language] return '\n'.join(flatter([self.shebang_header, self.slurm_header, self.script_header, self.command, self.script_footer]))
python
def script(self): """The script to be submitted to the SLURM queue.""" self.shebang_header = self.shebang_headers[self.language] self.slurm_header = [self.slurm_headers[k]['tag'] % v for k,v in self.slurm_params.items()] self.script_header = self.script_headers[self.language] self.script_footer = self.script_footers[self.language] return '\n'.join(flatter([self.shebang_header, self.slurm_header, self.script_header, self.command, self.script_footer]))
[ "def", "script", "(", "self", ")", ":", "self", ".", "shebang_header", "=", "self", ".", "shebang_headers", "[", "self", ".", "language", "]", "self", ".", "slurm_header", "=", "[", "self", ".", "slurm_headers", "[", "k", "]", "[", "'tag'", "]", "%", ...
The script to be submitted to the SLURM queue.
[ "The", "script", "to", "be", "submitted", "to", "the", "SLURM", "queue", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L153-L163
train
51,974
xapple/plumbing
plumbing/slurm/job.py
JobSLURM.make_script
def make_script(self): """Make the script and return a FilePath object pointing to the script above.""" self.script_path.write(self.script) self.script_path.permissions.make_executable() return self.script_path
python
def make_script(self): """Make the script and return a FilePath object pointing to the script above.""" self.script_path.write(self.script) self.script_path.permissions.make_executable() return self.script_path
[ "def", "make_script", "(", "self", ")", ":", "self", ".", "script_path", ".", "write", "(", "self", ".", "script", ")", "self", ".", "script_path", ".", "permissions", ".", "make_executable", "(", ")", "return", "self", ".", "script_path" ]
Make the script and return a FilePath object pointing to the script above.
[ "Make", "the", "script", "and", "return", "a", "FilePath", "object", "pointing", "to", "the", "script", "above", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L165-L169
train
51,975
xapple/plumbing
plumbing/slurm/job.py
JobSLURM.status
def status(self): """What is the status of the job ?""" # If there is no script it is either ready or a lost duplicate # if not self.script_path.exists: if self.name in jobs.names: return "DUPLICATE" if self.name not in jobs.names: return "READY" # It is submitted already # if self.name in jobs.names: if jobs[self.name]['type'] == 'queued': return "QUEUED" if jobs[self.name]['type'] == 'running': return "RUNNING" # So the script exists for sure but it is not in the queue # if not self.kwargs['out_file'].exists: return "ABORTED" # Let's look in log file # if 'CANCELED' in self.log_tail: return "CANCELLED" if 'slurmstepd: error' in self.log_tail: return "CANCELLED" # It all looks good # if 'SLURM: end at' in self.log_tail: return "FINISHED" # At this point we have no idea # return "INTERUPTED"
python
def status(self): """What is the status of the job ?""" # If there is no script it is either ready or a lost duplicate # if not self.script_path.exists: if self.name in jobs.names: return "DUPLICATE" if self.name not in jobs.names: return "READY" # It is submitted already # if self.name in jobs.names: if jobs[self.name]['type'] == 'queued': return "QUEUED" if jobs[self.name]['type'] == 'running': return "RUNNING" # So the script exists for sure but it is not in the queue # if not self.kwargs['out_file'].exists: return "ABORTED" # Let's look in log file # if 'CANCELED' in self.log_tail: return "CANCELLED" if 'slurmstepd: error' in self.log_tail: return "CANCELLED" # It all looks good # if 'SLURM: end at' in self.log_tail: return "FINISHED" # At this point we have no idea # return "INTERUPTED"
[ "def", "status", "(", "self", ")", ":", "# If there is no script it is either ready or a lost duplicate #", "if", "not", "self", ".", "script_path", ".", "exists", ":", "if", "self", ".", "name", "in", "jobs", ".", "names", ":", "return", "\"DUPLICATE\"", "if", ...
What is the status of the job ?
[ "What", "is", "the", "status", "of", "the", "job", "?" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L183-L201
train
51,976
xapple/plumbing
plumbing/slurm/job.py
JobSLURM.info
def info(self): """Get the existing job information dictionary""" if self.name not in jobs: return {'status': self.status} else: return jobs[self.name]
python
def info(self): """Get the existing job information dictionary""" if self.name not in jobs: return {'status': self.status} else: return jobs[self.name]
[ "def", "info", "(", "self", ")", ":", "if", "self", ".", "name", "not", "in", "jobs", ":", "return", "{", "'status'", ":", "self", ".", "status", "}", "else", ":", "return", "jobs", "[", "self", ".", "name", "]" ]
Get the existing job information dictionary
[ "Get", "the", "existing", "job", "information", "dictionary" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L204-L207
train
51,977
xapple/plumbing
plumbing/slurm/job.py
JobSLURM.launch
def launch(self): """Make the script file and return the newly created job id""" # Make script file # self.make_script() # Do it # sbatch_out = sh.sbatch(self.script_path) jobs.expire() # Message # print Color.i_blu + "SLURM:" + Color.end + " " + str(sbatch_out), # Return id # self.id = int(re.findall("Submitted batch job ([0-9]+)", str(sbatch_out))[0]) return self.id
python
def launch(self): """Make the script file and return the newly created job id""" # Make script file # self.make_script() # Do it # sbatch_out = sh.sbatch(self.script_path) jobs.expire() # Message # print Color.i_blu + "SLURM:" + Color.end + " " + str(sbatch_out), # Return id # self.id = int(re.findall("Submitted batch job ([0-9]+)", str(sbatch_out))[0]) return self.id
[ "def", "launch", "(", "self", ")", ":", "# Make script file #", "self", ".", "make_script", "(", ")", "# Do it #", "sbatch_out", "=", "sh", ".", "sbatch", "(", "self", ".", "script_path", ")", "jobs", ".", "expire", "(", ")", "# Message #", "print", "Color...
Make the script file and return the newly created job id
[ "Make", "the", "script", "file", "and", "return", "the", "newly", "created", "job", "id" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L225-L236
train
51,978
xapple/plumbing
plumbing/slurm/job.py
JobSLURM.run_locally
def run_locally(self): """A convenience method to run the same result as a SLURM job but locally in a non-blocking way. Useful for testing.""" self.thread = threading.Thread(target=self.execute_locally) self.thread.daemon = True # So that they die when we die self.thread.start()
python
def run_locally(self): """A convenience method to run the same result as a SLURM job but locally in a non-blocking way. Useful for testing.""" self.thread = threading.Thread(target=self.execute_locally) self.thread.daemon = True # So that they die when we die self.thread.start()
[ "def", "run_locally", "(", "self", ")", ":", "self", ".", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "execute_locally", ")", "self", ".", "thread", ".", "daemon", "=", "True", "# So that they die when we die", "self", ".", ...
A convenience method to run the same result as a SLURM job but locally in a non-blocking way. Useful for testing.
[ "A", "convenience", "method", "to", "run", "the", "same", "result", "as", "a", "SLURM", "job", "but", "locally", "in", "a", "non", "-", "blocking", "way", ".", "Useful", "for", "testing", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L248-L253
train
51,979
xapple/plumbing
plumbing/slurm/job.py
JobSLURM.execute_locally
def execute_locally(self): """Runs the equivalent command locally in a blocking way.""" # Make script file # self.make_script() # Do it # with open(self.kwargs['out_file'], 'w') as handle: sh.python(self.script_path, _out=handle, _err=handle)
python
def execute_locally(self): """Runs the equivalent command locally in a blocking way.""" # Make script file # self.make_script() # Do it # with open(self.kwargs['out_file'], 'w') as handle: sh.python(self.script_path, _out=handle, _err=handle)
[ "def", "execute_locally", "(", "self", ")", ":", "# Make script file #", "self", ".", "make_script", "(", ")", "# Do it #", "with", "open", "(", "self", ".", "kwargs", "[", "'out_file'", "]", ",", "'w'", ")", "as", "handle", ":", "sh", ".", "python", "("...
Runs the equivalent command locally in a blocking way.
[ "Runs", "the", "equivalent", "command", "locally", "in", "a", "blocking", "way", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L255-L261
train
51,980
xapple/plumbing
plumbing/slurm/job.py
JobSLURM.wait_locally
def wait_locally(self): """If you have run the query in a non-blocking way, call this method to pause until the query is finished.""" try: self.thread.join(sys.maxint) # maxint timeout so that we can Ctrl-C them except KeyboardInterrupt: print "Stopped waiting on job '%s'" % self.kwargs['job_name']
python
def wait_locally(self): """If you have run the query in a non-blocking way, call this method to pause until the query is finished.""" try: self.thread.join(sys.maxint) # maxint timeout so that we can Ctrl-C them except KeyboardInterrupt: print "Stopped waiting on job '%s'" % self.kwargs['job_name']
[ "def", "wait_locally", "(", "self", ")", ":", "try", ":", "self", ".", "thread", ".", "join", "(", "sys", ".", "maxint", ")", "# maxint timeout so that we can Ctrl-C them", "except", "KeyboardInterrupt", ":", "print", "\"Stopped waiting on job '%s'\"", "%", "self", ...
If you have run the query in a non-blocking way, call this method to pause until the query is finished.
[ "If", "you", "have", "run", "the", "query", "in", "a", "non", "-", "blocking", "way", "call", "this", "method", "to", "pause", "until", "the", "query", "is", "finished", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L263-L267
train
51,981
matllubos/django-is-core
is_core/filters/__init__.py
UIFilterMixin.get_widget
def get_widget(self, request): """ Returns concrete widget that will be used for rendering table filter. """ widget = self.widget if isinstance(widget, type): widget = widget() return widget
python
def get_widget(self, request): """ Returns concrete widget that will be used for rendering table filter. """ widget = self.widget if isinstance(widget, type): widget = widget() return widget
[ "def", "get_widget", "(", "self", ",", "request", ")", ":", "widget", "=", "self", ".", "widget", "if", "isinstance", "(", "widget", ",", "type", ")", ":", "widget", "=", "widget", "(", ")", "return", "widget" ]
Returns concrete widget that will be used for rendering table filter.
[ "Returns", "concrete", "widget", "that", "will", "be", "used", "for", "rendering", "table", "filter", "." ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/filters/__init__.py#L38-L45
train
51,982
softwarefactory-project/distroinfo
scripts/di.py
distroinfo
def distroinfo(cargs, version=__version__): """ distroinfo Command-Line Interface """ code = 1 args = docopt(__doc__, argv=cargs) try: if args['--version']: if not version: version = 'N/A' print(version) code = 0 elif args['fetch']: code = fetch( info_url=args['<info-url>'], info_files=args['<info-file>'], cache_dir=args['--cache-dir'], fetcher=args['--fetcher'], ) elif args['dump']: code = dump( info_url=args['<info-url>'], info_files=args['<info-file>'], yaml_out=args['--yaml-out'], json_out=args['--json-out'], cache_dir=args['--cache-dir'], fetcher=args['--fetcher'], ) except ( exception.InvalidInfoFormat, KeyboardInterrupt, ) as ex: code = getattr(ex, 'exit_code', code) print("") print(str(ex) or type(ex).__name__) return code
python
def distroinfo(cargs, version=__version__): """ distroinfo Command-Line Interface """ code = 1 args = docopt(__doc__, argv=cargs) try: if args['--version']: if not version: version = 'N/A' print(version) code = 0 elif args['fetch']: code = fetch( info_url=args['<info-url>'], info_files=args['<info-file>'], cache_dir=args['--cache-dir'], fetcher=args['--fetcher'], ) elif args['dump']: code = dump( info_url=args['<info-url>'], info_files=args['<info-file>'], yaml_out=args['--yaml-out'], json_out=args['--json-out'], cache_dir=args['--cache-dir'], fetcher=args['--fetcher'], ) except ( exception.InvalidInfoFormat, KeyboardInterrupt, ) as ex: code = getattr(ex, 'exit_code', code) print("") print(str(ex) or type(ex).__name__) return code
[ "def", "distroinfo", "(", "cargs", ",", "version", "=", "__version__", ")", ":", "code", "=", "1", "args", "=", "docopt", "(", "__doc__", ",", "argv", "=", "cargs", ")", "try", ":", "if", "args", "[", "'--version'", "]", ":", "if", "not", "version", ...
distroinfo Command-Line Interface
[ "distroinfo", "Command", "-", "Line", "Interface" ]
86a7419232a3376157c06e70528ec627e03ff82a
https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/scripts/di.py#L95-L132
train
51,983
matllubos/django-is-core
is_core/rest/resource.py
RESTResourceMixin._get_error_response
def _get_error_response(self, exception): """ Trasform pyston exceptions to Is-core exceptions and raise it """ response_exceptions = { MimerDataException: HTTPBadRequestResponseException, NotAllowedException: HTTPForbiddenResponseException, UnsupportedMediaTypeException: HTTPUnsupportedMediaTypeResponseException, Http404: Http404, ResourceNotFoundException: Http404, NotAllowedMethodException: HTTPMethodNotAllowedResponseException, DuplicateEntryException: HTTPDuplicateResponseException, ConflictException: HTTPDuplicateResponseException, } response_exception = response_exceptions.get(type(exception)) if response_exception: raise response_exception return super(RESTResourceMixin, self)._get_error_response(exception)
python
def _get_error_response(self, exception): """ Trasform pyston exceptions to Is-core exceptions and raise it """ response_exceptions = { MimerDataException: HTTPBadRequestResponseException, NotAllowedException: HTTPForbiddenResponseException, UnsupportedMediaTypeException: HTTPUnsupportedMediaTypeResponseException, Http404: Http404, ResourceNotFoundException: Http404, NotAllowedMethodException: HTTPMethodNotAllowedResponseException, DuplicateEntryException: HTTPDuplicateResponseException, ConflictException: HTTPDuplicateResponseException, } response_exception = response_exceptions.get(type(exception)) if response_exception: raise response_exception return super(RESTResourceMixin, self)._get_error_response(exception)
[ "def", "_get_error_response", "(", "self", ",", "exception", ")", ":", "response_exceptions", "=", "{", "MimerDataException", ":", "HTTPBadRequestResponseException", ",", "NotAllowedException", ":", "HTTPForbiddenResponseException", ",", "UnsupportedMediaTypeException", ":", ...
Trasform pyston exceptions to Is-core exceptions and raise it
[ "Trasform", "pyston", "exceptions", "to", "Is", "-", "core", "exceptions", "and", "raise", "it" ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/rest/resource.py#L138-L155
train
51,984
dgtony/afg
afg/scenarios.py
Supervisor.reprompt_error
def reprompt_error(self, message=None): """ Intended to be used in case of erroneous input data """ try: session_id = session.sessionId self.session_machines.rollback_fsm(session_id) current_state = self.session_machines.current_state(session_id) if message is None: err_msg = choice(self._scenario_steps[current_state]['reprompt']) else: err_msg = message return question(err_msg) except UninitializedStateMachine as e: logger.error(e) return statement(INTERNAL_ERROR_MSG)
python
def reprompt_error(self, message=None): """ Intended to be used in case of erroneous input data """ try: session_id = session.sessionId self.session_machines.rollback_fsm(session_id) current_state = self.session_machines.current_state(session_id) if message is None: err_msg = choice(self._scenario_steps[current_state]['reprompt']) else: err_msg = message return question(err_msg) except UninitializedStateMachine as e: logger.error(e) return statement(INTERNAL_ERROR_MSG)
[ "def", "reprompt_error", "(", "self", ",", "message", "=", "None", ")", ":", "try", ":", "session_id", "=", "session", ".", "sessionId", "self", ".", "session_machines", ".", "rollback_fsm", "(", "session_id", ")", "current_state", "=", "self", ".", "session...
Intended to be used in case of erroneous input data
[ "Intended", "to", "be", "used", "in", "case", "of", "erroneous", "input", "data" ]
831ad4c6d158610393dc21e74277d4ed6a004afd
https://github.com/dgtony/afg/blob/831ad4c6d158610393dc21e74277d4ed6a004afd/afg/scenarios.py#L116-L131
train
51,985
dgtony/afg
afg/scenarios.py
Supervisor.move_to_step
def move_to_step(self, step): """ Use in cases when you need to move in given step depending on input """ if step not in self._scenario_steps.keys(): raise UndefinedState("step {} not defined in scenario".format(step)) try: session_id = session.sessionId self.session_machines.set_state(session_id, step) except UninitializedStateMachine as e: logger.error(e) return statement(INTERNAL_ERROR_MSG)
python
def move_to_step(self, step): """ Use in cases when you need to move in given step depending on input """ if step not in self._scenario_steps.keys(): raise UndefinedState("step {} not defined in scenario".format(step)) try: session_id = session.sessionId self.session_machines.set_state(session_id, step) except UninitializedStateMachine as e: logger.error(e) return statement(INTERNAL_ERROR_MSG)
[ "def", "move_to_step", "(", "self", ",", "step", ")", ":", "if", "step", "not", "in", "self", ".", "_scenario_steps", ".", "keys", "(", ")", ":", "raise", "UndefinedState", "(", "\"step {} not defined in scenario\"", ".", "format", "(", "step", ")", ")", "...
Use in cases when you need to move in given step depending on input
[ "Use", "in", "cases", "when", "you", "need", "to", "move", "in", "given", "step", "depending", "on", "input" ]
831ad4c6d158610393dc21e74277d4ed6a004afd
https://github.com/dgtony/afg/blob/831ad4c6d158610393dc21e74277d4ed6a004afd/afg/scenarios.py#L133-L144
train
51,986
dgtony/afg
afg/scenarios.py
Supervisor.get_current_state
def get_current_state(self): """ Get current state for user session or None if session doesn't exist """ try: session_id = session.sessionId return self.session_machines.current_state(session_id) except UninitializedStateMachine as e: logger.error(e)
python
def get_current_state(self): """ Get current state for user session or None if session doesn't exist """ try: session_id = session.sessionId return self.session_machines.current_state(session_id) except UninitializedStateMachine as e: logger.error(e)
[ "def", "get_current_state", "(", "self", ")", ":", "try", ":", "session_id", "=", "session", ".", "sessionId", "return", "self", ".", "session_machines", ".", "current_state", "(", "session_id", ")", "except", "UninitializedStateMachine", "as", "e", ":", "logger...
Get current state for user session or None if session doesn't exist
[ "Get", "current", "state", "for", "user", "session", "or", "None", "if", "session", "doesn", "t", "exist" ]
831ad4c6d158610393dc21e74277d4ed6a004afd
https://github.com/dgtony/afg/blob/831ad4c6d158610393dc21e74277d4ed6a004afd/afg/scenarios.py#L146-L154
train
51,987
dgtony/afg
afg/scenarios.py
Supervisor.get_help
def get_help(self): """ Get context help, depending on the current step. If no help for current step was specified in scenario description file, default one will be returned. """ current_state = self.get_current_state() if current_state is None: return statement(INTERNAL_ERROR_MSG) else: try: return choice(self._scenario_steps[current_state]['help']) except KeyError: return choice(self._default_help)
python
def get_help(self): """ Get context help, depending on the current step. If no help for current step was specified in scenario description file, default one will be returned. """ current_state = self.get_current_state() if current_state is None: return statement(INTERNAL_ERROR_MSG) else: try: return choice(self._scenario_steps[current_state]['help']) except KeyError: return choice(self._default_help)
[ "def", "get_help", "(", "self", ")", ":", "current_state", "=", "self", ".", "get_current_state", "(", ")", "if", "current_state", "is", "None", ":", "return", "statement", "(", "INTERNAL_ERROR_MSG", ")", "else", ":", "try", ":", "return", "choice", "(", "...
Get context help, depending on the current step. If no help for current step was specified in scenario description file, default one will be returned.
[ "Get", "context", "help", "depending", "on", "the", "current", "step", ".", "If", "no", "help", "for", "current", "step", "was", "specified", "in", "scenario", "description", "file", "default", "one", "will", "be", "returned", "." ]
831ad4c6d158610393dc21e74277d4ed6a004afd
https://github.com/dgtony/afg/blob/831ad4c6d158610393dc21e74277d4ed6a004afd/afg/scenarios.py#L156-L168
train
51,988
confirm/ansibleci
ansibleci/runner.py
Runner.run
def run(self): ''' Runs all enabled tests. ''' # Run all tests. for cls in self.get_test_classes(): # Print informational message. self.logger.info('Running {cls.__name__} test...'.format(cls=cls)) # Create new test instance. test = cls(runner=self) # Run test and evaluate result. if test._run(): self.logger.passed('Test {cls.__name__} succeeded!'.format(cls=cls)) else: self.logger.failed('Test {cls.__name__} failed!'.format(cls=cls)) self.has_passed = False # Print summary. if self.has_passed: self.logger.passed('Summary: All tests passed!') else: self.logger.failed('Summary: One or more tests failed!') return self.has_passed
python
def run(self): ''' Runs all enabled tests. ''' # Run all tests. for cls in self.get_test_classes(): # Print informational message. self.logger.info('Running {cls.__name__} test...'.format(cls=cls)) # Create new test instance. test = cls(runner=self) # Run test and evaluate result. if test._run(): self.logger.passed('Test {cls.__name__} succeeded!'.format(cls=cls)) else: self.logger.failed('Test {cls.__name__} failed!'.format(cls=cls)) self.has_passed = False # Print summary. if self.has_passed: self.logger.passed('Summary: All tests passed!') else: self.logger.failed('Summary: One or more tests failed!') return self.has_passed
[ "def", "run", "(", "self", ")", ":", "# Run all tests.", "for", "cls", "in", "self", ".", "get_test_classes", "(", ")", ":", "# Print informational message.", "self", ".", "logger", ".", "info", "(", "'Running {cls.__name__} test...'", ".", "format", "(", "cls",...
Runs all enabled tests.
[ "Runs", "all", "enabled", "tests", "." ]
6a53ae8c4a4653624977e146092422857f661b8f
https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/runner.py#L71-L97
train
51,989
inveniosoftware/invenio-iiif
invenio_iiif/utils.py
iiif_image_key
def iiif_image_key(obj): """Generate the IIIF image key.""" if isinstance(obj, ObjectVersion): bucket_id = obj.bucket_id version_id = obj.version_id key = obj.key else: bucket_id = obj.get('bucket') version_id = obj.get('version_id') key = obj.get('key') return u'{}:{}:{}'.format( bucket_id, version_id, key, )
python
def iiif_image_key(obj): """Generate the IIIF image key.""" if isinstance(obj, ObjectVersion): bucket_id = obj.bucket_id version_id = obj.version_id key = obj.key else: bucket_id = obj.get('bucket') version_id = obj.get('version_id') key = obj.get('key') return u'{}:{}:{}'.format( bucket_id, version_id, key, )
[ "def", "iiif_image_key", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "ObjectVersion", ")", ":", "bucket_id", "=", "obj", ".", "bucket_id", "version_id", "=", "obj", ".", "version_id", "key", "=", "obj", ".", "key", "else", ":", "bucket_id"...
Generate the IIIF image key.
[ "Generate", "the", "IIIF", "image", "key", "." ]
e4f2f93eaabdc8e2efea81c239ab76d481191959
https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/utils.py#L18-L32
train
51,990
inveniosoftware/invenio-iiif
invenio_iiif/utils.py
ui_iiif_image_url
def ui_iiif_image_url(obj, version='v2', region='full', size='full', rotation=0, quality='default', image_format='png'): """Generate IIIF image URL from the UI application.""" return u'{prefix}{version}/{identifier}/{region}/{size}/{rotation}/' \ u'{quality}.{image_format}'.format( prefix=current_app.config['IIIF_UI_URL'], version=version, identifier=quote( iiif_image_key(obj).encode('utf8'), safe=':'), region=region, size=size, rotation=rotation, quality=quality, image_format=image_format, )
python
def ui_iiif_image_url(obj, version='v2', region='full', size='full', rotation=0, quality='default', image_format='png'): """Generate IIIF image URL from the UI application.""" return u'{prefix}{version}/{identifier}/{region}/{size}/{rotation}/' \ u'{quality}.{image_format}'.format( prefix=current_app.config['IIIF_UI_URL'], version=version, identifier=quote( iiif_image_key(obj).encode('utf8'), safe=':'), region=region, size=size, rotation=rotation, quality=quality, image_format=image_format, )
[ "def", "ui_iiif_image_url", "(", "obj", ",", "version", "=", "'v2'", ",", "region", "=", "'full'", ",", "size", "=", "'full'", ",", "rotation", "=", "0", ",", "quality", "=", "'default'", ",", "image_format", "=", "'png'", ")", ":", "return", "u'{prefix}...
Generate IIIF image URL from the UI application.
[ "Generate", "IIIF", "image", "URL", "from", "the", "UI", "application", "." ]
e4f2f93eaabdc8e2efea81c239ab76d481191959
https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/utils.py#L35-L49
train
51,991
inveniosoftware/invenio-iiif
invenio_iiif/previewer.py
preview
def preview(file): """Render appropriate template with embed flag.""" params = deepcopy(current_app.config['IIIF_PREVIEWER_PARAMS']) if 'image_format' not in params: params['image_format'] = \ 'png' if file.has_extensions('.png') else 'jpg' return render_template( current_app.config['IIIF_PREVIEW_TEMPLATE'], file=file, file_url=ui_iiif_image_url( file.file, **params ) )
python
def preview(file): """Render appropriate template with embed flag.""" params = deepcopy(current_app.config['IIIF_PREVIEWER_PARAMS']) if 'image_format' not in params: params['image_format'] = \ 'png' if file.has_extensions('.png') else 'jpg' return render_template( current_app.config['IIIF_PREVIEW_TEMPLATE'], file=file, file_url=ui_iiif_image_url( file.file, **params ) )
[ "def", "preview", "(", "file", ")", ":", "params", "=", "deepcopy", "(", "current_app", ".", "config", "[", "'IIIF_PREVIEWER_PARAMS'", "]", ")", "if", "'image_format'", "not", "in", "params", ":", "params", "[", "'image_format'", "]", "=", "'png'", "if", "...
Render appropriate template with embed flag.
[ "Render", "appropriate", "template", "with", "embed", "flag", "." ]
e4f2f93eaabdc8e2efea81c239ab76d481191959
https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/previewer.py#L35-L48
train
51,992
The-Politico/django-slackchat-serializer
slackchat/authentication.py
secure
def secure(view): """Set an auth decorator applied for views. If DEBUG is on, we serve the view without authenticating. Default is 'django.contrib.auth.decorators.login_required'. Can also be 'django.contrib.admin.views.decorators.staff_member_required' or a custom decorator. """ AUTH = getattr( settings, 'SLACKCHAT_AUTH_DECORATOR', 'django.contrib.admin.views.decorators.staff_member_required' ) auth_decorator = import_class(AUTH) return method_decorator(auth_decorator, name='dispatch')(view)
python
def secure(view): """Set an auth decorator applied for views. If DEBUG is on, we serve the view without authenticating. Default is 'django.contrib.auth.decorators.login_required'. Can also be 'django.contrib.admin.views.decorators.staff_member_required' or a custom decorator. """ AUTH = getattr( settings, 'SLACKCHAT_AUTH_DECORATOR', 'django.contrib.admin.views.decorators.staff_member_required' ) auth_decorator = import_class(AUTH) return method_decorator(auth_decorator, name='dispatch')(view)
[ "def", "secure", "(", "view", ")", ":", "AUTH", "=", "getattr", "(", "settings", ",", "'SLACKCHAT_AUTH_DECORATOR'", ",", "'django.contrib.admin.views.decorators.staff_member_required'", ")", "auth_decorator", "=", "import_class", "(", "AUTH", ")", "return", "method_deco...
Set an auth decorator applied for views. If DEBUG is on, we serve the view without authenticating. Default is 'django.contrib.auth.decorators.login_required'. Can also be 'django.contrib.admin.views.decorators.staff_member_required' or a custom decorator.
[ "Set", "an", "auth", "decorator", "applied", "for", "views", ".", "If", "DEBUG", "is", "on", "we", "serve", "the", "view", "without", "authenticating", ".", "Default", "is", "django", ".", "contrib", ".", "auth", ".", "decorators", ".", "login_required", "...
9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40
https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/authentication.py#L46-L59
train
51,993
cloud-compose/cloud-compose-cluster
cloudcompose/cluster/commands/cli.py
up
def up(cloud_init, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time): """ creates a new cluster """ try: cloud_config = CloudConfig() ci = None if cloud_init: ci = CloudInit() cloud_controller = CloudController(cloud_config) cloud_controller.up(ci, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time) except CloudComposeException as ex: print(ex)
python
def up(cloud_init, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time): """ creates a new cluster """ try: cloud_config = CloudConfig() ci = None if cloud_init: ci = CloudInit() cloud_controller = CloudController(cloud_config) cloud_controller.up(ci, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time) except CloudComposeException as ex: print(ex)
[ "def", "up", "(", "cloud_init", ",", "use_snapshots", ",", "upgrade_image", ",", "snapshot_cluster", ",", "snapshot_time", ")", ":", "try", ":", "cloud_config", "=", "CloudConfig", "(", ")", "ci", "=", "None", "if", "cloud_init", ":", "ci", "=", "CloudInit",...
creates a new cluster
[ "creates", "a", "new", "cluster" ]
b6042419e778f3bf2257915def067972e5ce72cc
https://github.com/cloud-compose/cloud-compose-cluster/blob/b6042419e778f3bf2257915def067972e5ce72cc/cloudcompose/cluster/commands/cli.py#L18-L32
train
51,994
cloud-compose/cloud-compose-cluster
cloudcompose/cluster/commands/cli.py
down
def down(force): """ destroys an existing cluster """ try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.down(force) except CloudComposeException as ex: print(ex)
python
def down(force): """ destroys an existing cluster """ try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.down(force) except CloudComposeException as ex: print(ex)
[ "def", "down", "(", "force", ")", ":", "try", ":", "cloud_config", "=", "CloudConfig", "(", ")", "cloud_controller", "=", "CloudController", "(", "cloud_config", ")", "cloud_controller", ".", "down", "(", "force", ")", "except", "CloudComposeException", "as", ...
destroys an existing cluster
[ "destroys", "an", "existing", "cluster" ]
b6042419e778f3bf2257915def067972e5ce72cc
https://github.com/cloud-compose/cloud-compose-cluster/blob/b6042419e778f3bf2257915def067972e5ce72cc/cloudcompose/cluster/commands/cli.py#L36-L45
train
51,995
cloud-compose/cloud-compose-cluster
cloudcompose/cluster/commands/cli.py
cleanup
def cleanup(): """ deletes launch configs and auto scaling group """ try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.cleanup() except CloudComposeException as ex: print(ex)
python
def cleanup(): """ deletes launch configs and auto scaling group """ try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.cleanup() except CloudComposeException as ex: print(ex)
[ "def", "cleanup", "(", ")", ":", "try", ":", "cloud_config", "=", "CloudConfig", "(", ")", "cloud_controller", "=", "CloudController", "(", "cloud_config", ")", "cloud_controller", ".", "cleanup", "(", ")", "except", "CloudComposeException", "as", "ex", ":", "...
deletes launch configs and auto scaling group
[ "deletes", "launch", "configs", "and", "auto", "scaling", "group" ]
b6042419e778f3bf2257915def067972e5ce72cc
https://github.com/cloud-compose/cloud-compose-cluster/blob/b6042419e778f3bf2257915def067972e5ce72cc/cloudcompose/cluster/commands/cli.py#L48-L57
train
51,996
cloud-compose/cloud-compose-cluster
cloudcompose/cluster/commands/cli.py
build
def build(): """ builds the cloud_init script """ try: cloud_config = CloudConfig() config_data = cloud_config.config_data('cluster') cloud_init = CloudInit() print(cloud_init.build(config_data)) except CloudComposeException as ex: print(ex)
python
def build(): """ builds the cloud_init script """ try: cloud_config = CloudConfig() config_data = cloud_config.config_data('cluster') cloud_init = CloudInit() print(cloud_init.build(config_data)) except CloudComposeException as ex: print(ex)
[ "def", "build", "(", ")", ":", "try", ":", "cloud_config", "=", "CloudConfig", "(", ")", "config_data", "=", "cloud_config", ".", "config_data", "(", "'cluster'", ")", "cloud_init", "=", "CloudInit", "(", ")", "print", "(", "cloud_init", ".", "build", "(",...
builds the cloud_init script
[ "builds", "the", "cloud_init", "script" ]
b6042419e778f3bf2257915def067972e5ce72cc
https://github.com/cloud-compose/cloud-compose-cluster/blob/b6042419e778f3bf2257915def067972e5ce72cc/cloudcompose/cluster/commands/cli.py#L60-L70
train
51,997
epandurski/flask_signalbus
flask_signalbus/signalbus_cli.py
flush
def flush(signal_names, exclude, wait): """Send pending signals over the message bus. If a list of SIGNAL_NAMES is specified, flushes only those signals. If no SIGNAL_NAMES are specified, flushes all signals. """ signalbus = current_app.extensions['signalbus'] signal_names = set(signal_names) exclude = set(exclude) models_to_flush = signalbus.get_signal_models() if signal_names and exclude: click.echo('Warning: Specified both SIGNAL_NAMES and exclude option.') if signal_names: wrong_signal_names = signal_names - {m.__name__ for m in models_to_flush} models_to_flush = [m for m in models_to_flush if m.__name__ in signal_names] else: wrong_signal_names = exclude - {m.__name__ for m in models_to_flush} for name in wrong_signal_names: click.echo('Warning: A signal with name "{}" does not exist.'.format(name)) models_to_flush = [m for m in models_to_flush if m.__name__ not in exclude] logger = logging.getLogger(__name__) try: if wait is not None: signal_count = signalbus.flush(models_to_flush, wait=max(0.0, wait)) else: signal_count = signalbus.flush(models_to_flush) except Exception: logger.exception('Caught error while sending pending signals.') sys.exit(1) if signal_count == 1: logger.warning('%i signal has been successfully processed.', signal_count) elif signal_count > 1: logger.warning('%i signals have been successfully processed.', signal_count)
python
def flush(signal_names, exclude, wait): """Send pending signals over the message bus. If a list of SIGNAL_NAMES is specified, flushes only those signals. If no SIGNAL_NAMES are specified, flushes all signals. """ signalbus = current_app.extensions['signalbus'] signal_names = set(signal_names) exclude = set(exclude) models_to_flush = signalbus.get_signal_models() if signal_names and exclude: click.echo('Warning: Specified both SIGNAL_NAMES and exclude option.') if signal_names: wrong_signal_names = signal_names - {m.__name__ for m in models_to_flush} models_to_flush = [m for m in models_to_flush if m.__name__ in signal_names] else: wrong_signal_names = exclude - {m.__name__ for m in models_to_flush} for name in wrong_signal_names: click.echo('Warning: A signal with name "{}" does not exist.'.format(name)) models_to_flush = [m for m in models_to_flush if m.__name__ not in exclude] logger = logging.getLogger(__name__) try: if wait is not None: signal_count = signalbus.flush(models_to_flush, wait=max(0.0, wait)) else: signal_count = signalbus.flush(models_to_flush) except Exception: logger.exception('Caught error while sending pending signals.') sys.exit(1) if signal_count == 1: logger.warning('%i signal has been successfully processed.', signal_count) elif signal_count > 1: logger.warning('%i signals have been successfully processed.', signal_count)
[ "def", "flush", "(", "signal_names", ",", "exclude", ",", "wait", ")", ":", "signalbus", "=", "current_app", ".", "extensions", "[", "'signalbus'", "]", "signal_names", "=", "set", "(", "signal_names", ")", "exclude", "=", "set", "(", "exclude", ")", "mode...
Send pending signals over the message bus. If a list of SIGNAL_NAMES is specified, flushes only those signals. If no SIGNAL_NAMES are specified, flushes all signals.
[ "Send", "pending", "signals", "over", "the", "message", "bus", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus_cli.py#L21-L55
train
51,998
epandurski/flask_signalbus
flask_signalbus/signalbus_cli.py
signals
def signals(): """Show all signal types.""" signalbus = current_app.extensions['signalbus'] for signal_model in signalbus.get_signal_models(): click.echo(signal_model.__name__)
python
def signals(): """Show all signal types.""" signalbus = current_app.extensions['signalbus'] for signal_model in signalbus.get_signal_models(): click.echo(signal_model.__name__)
[ "def", "signals", "(", ")", ":", "signalbus", "=", "current_app", ".", "extensions", "[", "'signalbus'", "]", "for", "signal_model", "in", "signalbus", ".", "get_signal_models", "(", ")", ":", "click", ".", "echo", "(", "signal_model", ".", "__name__", ")" ]
Show all signal types.
[ "Show", "all", "signal", "types", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus_cli.py#L82-L87
train
51,999