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
intelligenia/modeltranslation
modeltranslation/translation.py
_set_dict_translations
def _set_dict_translations(instance, dict_translations): """ Establece los atributos de traducciones a partir de una dict que contiene todas las traducciones. """ # If class has no translatable fields get out if not hasattr(instance._meta, "translatable_fields"): return False # If we are in a site with one language there is no need of saving translations if site_is_monolingual(): return False # Translatable fields translatable_fields = instance._meta.translatable_fields # For each translatable field and for each language (excluding default language), we have to see if there is # two dynamic fields: # - <attribute>_<language_code>: translated atribute in <language_code>. # For example: name_fr, name_es, description_it, etc. # - <attribute>_is_fuzzy_<language_code>: is a provisional translation of <attribute> for language <language_code>. # For example: name_is_fuzzy_fr, name_is_fuzzy_es, description_is_fuzzy_it, etc. for field in translatable_fields: for lang in settings.LANGUAGES: lang = lang[0] if lang != settings.LANGUAGE_CODE: # Translated field name trans_field = trans_attr(field,lang) # If translated field name is in the dict, we assign it to the object if dict_translations.has_key(trans_field): setattr(instance,trans_field,dict_translations[trans_field]) # Is fuzzy attribute trans_isfuzzy = trans_is_fuzzy_attr(field,lang) # If "is fuzzy" name is in the dict, we assign it to the object if dict_translations.has_key(trans_isfuzzy): is_fuzzy_value = (dict_translations[trans_isfuzzy]=="1") or (dict_translations[trans_isfuzzy]==1) setattr(instance,trans_isfuzzy, is_fuzzy_value)
python
def _set_dict_translations(instance, dict_translations): """ Establece los atributos de traducciones a partir de una dict que contiene todas las traducciones. """ # If class has no translatable fields get out if not hasattr(instance._meta, "translatable_fields"): return False # If we are in a site with one language there is no need of saving translations if site_is_monolingual(): return False # Translatable fields translatable_fields = instance._meta.translatable_fields # For each translatable field and for each language (excluding default language), we have to see if there is # two dynamic fields: # - <attribute>_<language_code>: translated atribute in <language_code>. # For example: name_fr, name_es, description_it, etc. # - <attribute>_is_fuzzy_<language_code>: is a provisional translation of <attribute> for language <language_code>. # For example: name_is_fuzzy_fr, name_is_fuzzy_es, description_is_fuzzy_it, etc. for field in translatable_fields: for lang in settings.LANGUAGES: lang = lang[0] if lang != settings.LANGUAGE_CODE: # Translated field name trans_field = trans_attr(field,lang) # If translated field name is in the dict, we assign it to the object if dict_translations.has_key(trans_field): setattr(instance,trans_field,dict_translations[trans_field]) # Is fuzzy attribute trans_isfuzzy = trans_is_fuzzy_attr(field,lang) # If "is fuzzy" name is in the dict, we assign it to the object if dict_translations.has_key(trans_isfuzzy): is_fuzzy_value = (dict_translations[trans_isfuzzy]=="1") or (dict_translations[trans_isfuzzy]==1) setattr(instance,trans_isfuzzy, is_fuzzy_value)
[ "def", "_set_dict_translations", "(", "instance", ",", "dict_translations", ")", ":", "# If class has no translatable fields get out", "if", "not", "hasattr", "(", "instance", ".", "_meta", ",", "\"translatable_fields\"", ")", ":", "return", "False", "# If we are in a sit...
Establece los atributos de traducciones a partir de una dict que contiene todas las traducciones.
[ "Establece", "los", "atributos", "de", "traducciones", "a", "partir", "de", "una", "dict", "que", "contiene", "todas", "las", "traducciones", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L139-L178
train
51,800
intelligenia/modeltranslation
modeltranslation/translation.py
add_translation
def add_translation(sender): """ Adds the actions to a class. """ # 1. Execute _save_translations when saving an object signals.post_save.connect(_save_translations, sender=sender) # 2. Adds get_fieldtranslations to class. Remember that this method get all the translations. sender.add_to_class("get_fieldtranslations", _get_fieldtranslations) # 3. Adss load_translations. Remember that this method included all the translations as dynamic attributes. sender.add_to_class("load_translations", _load_translations) # 4. Adds _set_dict_translations. This methods allows us setting all the translated fields form a dict. # Very useful when dealing with ModelForms. sender.add_to_class("set_translation_fields", _set_dict_translations) # 5. This methods returns one translated attribute in Django. # Avoid using _ and use get_trans_attr because Django maketranslations parser is fooled believing that everything # inside _ methods is translatable. sender.add_to_class("_", _get_translated_field) sender.add_to_class("get_trans_attr", _get_translated_field) sender.add_to_class("_t", _get_translated_field)
python
def add_translation(sender): """ Adds the actions to a class. """ # 1. Execute _save_translations when saving an object signals.post_save.connect(_save_translations, sender=sender) # 2. Adds get_fieldtranslations to class. Remember that this method get all the translations. sender.add_to_class("get_fieldtranslations", _get_fieldtranslations) # 3. Adss load_translations. Remember that this method included all the translations as dynamic attributes. sender.add_to_class("load_translations", _load_translations) # 4. Adds _set_dict_translations. This methods allows us setting all the translated fields form a dict. # Very useful when dealing with ModelForms. sender.add_to_class("set_translation_fields", _set_dict_translations) # 5. This methods returns one translated attribute in Django. # Avoid using _ and use get_trans_attr because Django maketranslations parser is fooled believing that everything # inside _ methods is translatable. sender.add_to_class("_", _get_translated_field) sender.add_to_class("get_trans_attr", _get_translated_field) sender.add_to_class("_t", _get_translated_field)
[ "def", "add_translation", "(", "sender", ")", ":", "# 1. Execute _save_translations when saving an object", "signals", ".", "post_save", ".", "connect", "(", "_save_translations", ",", "sender", "=", "sender", ")", "# 2. Adds get_fieldtranslations to class. Remember that this m...
Adds the actions to a class.
[ "Adds", "the", "actions", "to", "a", "class", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L216-L234
train
51,801
StorjOld/file-encryptor
file_encryptor/convergence.py
encrypt_file_inline
def encrypt_file_inline(filename, passphrase): """Encrypt file inline, with an optional passphrase. If you set the passphrase to None, a default is used. This will make you vulnerable to confirmation attacks and learn-partial-information attacks. :param filename: The name of the file to encrypt. :type filename: str :param passphrase: The passphrase used to decrypt the file. :type passphrase: str or None :returns: The key required to decrypt the file. :rtype: str """ key = key_generators.key_from_file(filename, passphrase) inline_transform(filename, key) return key
python
def encrypt_file_inline(filename, passphrase): """Encrypt file inline, with an optional passphrase. If you set the passphrase to None, a default is used. This will make you vulnerable to confirmation attacks and learn-partial-information attacks. :param filename: The name of the file to encrypt. :type filename: str :param passphrase: The passphrase used to decrypt the file. :type passphrase: str or None :returns: The key required to decrypt the file. :rtype: str """ key = key_generators.key_from_file(filename, passphrase) inline_transform(filename, key) return key
[ "def", "encrypt_file_inline", "(", "filename", ",", "passphrase", ")", ":", "key", "=", "key_generators", ".", "key_from_file", "(", "filename", ",", "passphrase", ")", "inline_transform", "(", "filename", ",", "key", ")", "return", "key" ]
Encrypt file inline, with an optional passphrase. If you set the passphrase to None, a default is used. This will make you vulnerable to confirmation attacks and learn-partial-information attacks. :param filename: The name of the file to encrypt. :type filename: str :param passphrase: The passphrase used to decrypt the file. :type passphrase: str or None :returns: The key required to decrypt the file. :rtype: str
[ "Encrypt", "file", "inline", "with", "an", "optional", "passphrase", "." ]
245191c45dbd68e09a4a8f07c5d7331be195dc6b
https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/convergence.py#L33-L51
train
51,802
StorjOld/file-encryptor
file_encryptor/convergence.py
inline_transform
def inline_transform(filename, key): """Encrypt file inline. Encrypts a given file with the given key, and replaces it directly without any extra space requirement. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to encrypt the file. :type key: str """ pos = 0 for chunk, fp in iter_transform(filename, key): fp.seek(pos) fp.write(chunk) fp.flush() pos = fp.tell()
python
def inline_transform(filename, key): """Encrypt file inline. Encrypts a given file with the given key, and replaces it directly without any extra space requirement. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to encrypt the file. :type key: str """ pos = 0 for chunk, fp in iter_transform(filename, key): fp.seek(pos) fp.write(chunk) fp.flush() pos = fp.tell()
[ "def", "inline_transform", "(", "filename", ",", "key", ")", ":", "pos", "=", "0", "for", "chunk", ",", "fp", "in", "iter_transform", "(", "filename", ",", "key", ")", ":", "fp", ".", "seek", "(", "pos", ")", "fp", ".", "write", "(", "chunk", ")", ...
Encrypt file inline. Encrypts a given file with the given key, and replaces it directly without any extra space requirement. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to encrypt the file. :type key: str
[ "Encrypt", "file", "inline", "." ]
245191c45dbd68e09a4a8f07c5d7331be195dc6b
https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/convergence.py#L85-L102
train
51,803
StorjOld/file-encryptor
file_encryptor/convergence.py
iter_transform
def iter_transform(filename, key): """Generate encrypted file with given key. This generator function reads the file in chunks and encrypts them using AES-CTR, with the specified key. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to encrypt the file. :type key: str :returns: A generator that produces encrypted file chunks. :rtype: generator """ # We are not specifying the IV here. aes = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)) with open(filename, 'rb+') as f: for chunk in iter(lambda: f.read(CHUNK_SIZE), b''): yield aes.encrypt(chunk), f
python
def iter_transform(filename, key): """Generate encrypted file with given key. This generator function reads the file in chunks and encrypts them using AES-CTR, with the specified key. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to encrypt the file. :type key: str :returns: A generator that produces encrypted file chunks. :rtype: generator """ # We are not specifying the IV here. aes = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)) with open(filename, 'rb+') as f: for chunk in iter(lambda: f.read(CHUNK_SIZE), b''): yield aes.encrypt(chunk), f
[ "def", "iter_transform", "(", "filename", ",", "key", ")", ":", "# We are not specifying the IV here.", "aes", "=", "AES", ".", "new", "(", "key", ",", "AES", ".", "MODE_CTR", ",", "counter", "=", "Counter", ".", "new", "(", "128", ")", ")", "with", "ope...
Generate encrypted file with given key. This generator function reads the file in chunks and encrypts them using AES-CTR, with the specified key. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to encrypt the file. :type key: str :returns: A generator that produces encrypted file chunks. :rtype: generator
[ "Generate", "encrypted", "file", "with", "given", "key", "." ]
245191c45dbd68e09a4a8f07c5d7331be195dc6b
https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/convergence.py#L105-L124
train
51,804
epandurski/flask_signalbus
flask_signalbus/signalbus.py
SignalBusMixin.signalbus
def signalbus(self): """The associated `SignalBus` object.""" try: signalbus = self.__signalbus except AttributeError: signalbus = self.__signalbus = SignalBus(self, init_app=False) return signalbus
python
def signalbus(self): """The associated `SignalBus` object.""" try: signalbus = self.__signalbus except AttributeError: signalbus = self.__signalbus = SignalBus(self, init_app=False) return signalbus
[ "def", "signalbus", "(", "self", ")", ":", "try", ":", "signalbus", "=", "self", ".", "__signalbus", "except", "AttributeError", ":", "signalbus", "=", "self", ".", "__signalbus", "=", "SignalBus", "(", "self", ",", "init_app", "=", "False", ")", "return",...
The associated `SignalBus` object.
[ "The", "associated", "SignalBus", "object", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L53-L60
train
51,805
epandurski/flask_signalbus
flask_signalbus/signalbus.py
SignalBus.get_signal_models
def get_signal_models(self): """Return all signal types in a list. :rtype: list(`signal-model`) """ base = self.db.Model return [ cls for cls in base._decl_class_registry.values() if ( isinstance(cls, type) and issubclass(cls, base) and hasattr(cls, 'send_signalbus_message') ) ]
python
def get_signal_models(self): """Return all signal types in a list. :rtype: list(`signal-model`) """ base = self.db.Model return [ cls for cls in base._decl_class_registry.values() if ( isinstance(cls, type) and issubclass(cls, base) and hasattr(cls, 'send_signalbus_message') ) ]
[ "def", "get_signal_models", "(", "self", ")", ":", "base", "=", "self", ".", "db", ".", "Model", "return", "[", "cls", "for", "cls", "in", "base", ".", "_decl_class_registry", ".", "values", "(", ")", "if", "(", "isinstance", "(", "cls", ",", "type", ...
Return all signal types in a list. :rtype: list(`signal-model`)
[ "Return", "all", "signal", "types", "in", "a", "list", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L118-L132
train
51,806
epandurski/flask_signalbus
flask_signalbus/signalbus.py
SignalBus.flush
def flush(self, models=None, wait=3.0): """Send all pending signals over the message bus. :param models: If passed, flushes only signals of the specified types. :type models: list(`signal-model`) or `None` :param float wait: The number of seconds the method will wait after obtaining the list of pending signals, to allow concurrent senders to complete :return: The total number of signals that have been sent """ models_to_flush = self.get_signal_models() if models is None else models pks_to_flush = {} try: for model in models_to_flush: _raise_error_if_not_signal_model(model) m = inspect(model) pk_attrs = [m.get_property_by_column(c).class_attribute for c in m.primary_key] pks_to_flush[model] = self.signal_session.query(*pk_attrs).all() self.signal_session.rollback() time.sleep(wait) return sum( self._flush_signals_with_retry(model, pk_values_set=set(pks_to_flush[model])) for model in models_to_flush ) finally: self.signal_session.remove()
python
def flush(self, models=None, wait=3.0): """Send all pending signals over the message bus. :param models: If passed, flushes only signals of the specified types. :type models: list(`signal-model`) or `None` :param float wait: The number of seconds the method will wait after obtaining the list of pending signals, to allow concurrent senders to complete :return: The total number of signals that have been sent """ models_to_flush = self.get_signal_models() if models is None else models pks_to_flush = {} try: for model in models_to_flush: _raise_error_if_not_signal_model(model) m = inspect(model) pk_attrs = [m.get_property_by_column(c).class_attribute for c in m.primary_key] pks_to_flush[model] = self.signal_session.query(*pk_attrs).all() self.signal_session.rollback() time.sleep(wait) return sum( self._flush_signals_with_retry(model, pk_values_set=set(pks_to_flush[model])) for model in models_to_flush ) finally: self.signal_session.remove()
[ "def", "flush", "(", "self", ",", "models", "=", "None", ",", "wait", "=", "3.0", ")", ":", "models_to_flush", "=", "self", ".", "get_signal_models", "(", ")", "if", "models", "is", "None", "else", "models", "pks_to_flush", "=", "{", "}", "try", ":", ...
Send all pending signals over the message bus. :param models: If passed, flushes only signals of the specified types. :type models: list(`signal-model`) or `None` :param float wait: The number of seconds the method will wait after obtaining the list of pending signals, to allow concurrent senders to complete :return: The total number of signals that have been sent
[ "Send", "all", "pending", "signals", "over", "the", "message", "bus", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L134-L161
train
51,807
sprockets/sprockets.http
examples.py
StatusHandler.get
def get(self, status_code): """ Returns the requested status. :param int status_code: the status code to return :queryparam str reason: optional reason phrase """ status_code = int(status_code) if status_code >= 400: kwargs = {'status_code': status_code} if self.get_query_argument('reason', None): kwargs['reason'] = self.get_query_argument('reason') if self.get_query_argument('log_message', None): kwargs['log_message'] = self.get_query_argument('log_message') self.send_error(**kwargs) else: self.set_status(status_code)
python
def get(self, status_code): """ Returns the requested status. :param int status_code: the status code to return :queryparam str reason: optional reason phrase """ status_code = int(status_code) if status_code >= 400: kwargs = {'status_code': status_code} if self.get_query_argument('reason', None): kwargs['reason'] = self.get_query_argument('reason') if self.get_query_argument('log_message', None): kwargs['log_message'] = self.get_query_argument('log_message') self.send_error(**kwargs) else: self.set_status(status_code)
[ "def", "get", "(", "self", ",", "status_code", ")", ":", "status_code", "=", "int", "(", "status_code", ")", "if", "status_code", ">=", "400", ":", "kwargs", "=", "{", "'status_code'", ":", "status_code", "}", "if", "self", ".", "get_query_argument", "(", ...
Returns the requested status. :param int status_code: the status code to return :queryparam str reason: optional reason phrase
[ "Returns", "the", "requested", "status", "." ]
8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3
https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/examples.py#L10-L27
train
51,808
confirm/ansibleci
ansibleci/helper.py
Helper.get_absolute_path
def get_absolute_path(self, path): ''' Returns the absolute path of the ``path`` argument. If ``path`` is already absolute, nothing changes. If the ``path`` is relative, then the BASEDIR will be prepended. ''' if os.path.isabs(path): return path else: return os.path.abspath(os.path.join(self.config.BASEDIR, path))
python
def get_absolute_path(self, path): ''' Returns the absolute path of the ``path`` argument. If ``path`` is already absolute, nothing changes. If the ``path`` is relative, then the BASEDIR will be prepended. ''' if os.path.isabs(path): return path else: return os.path.abspath(os.path.join(self.config.BASEDIR, path))
[ "def", "get_absolute_path", "(", "self", ",", "path", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", "else", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "s...
Returns the absolute path of the ``path`` argument. If ``path`` is already absolute, nothing changes. If the ``path`` is relative, then the BASEDIR will be prepended.
[ "Returns", "the", "absolute", "path", "of", "the", "path", "argument", "." ]
6a53ae8c4a4653624977e146092422857f661b8f
https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L25-L35
train
51,809
confirm/ansibleci
ansibleci/helper.py
Helper.get_roles
def get_roles(self): ''' Returns a key-value dict with a roles, while the key is the role name and the value is the absolute role path. ''' roles = {} paths = self.get_roles_paths() for path in paths: for entry in os.listdir(path): rolepath = os.path.join(path, entry) if os.path.isdir(rolepath): roles[entry] = rolepath return roles
python
def get_roles(self): ''' Returns a key-value dict with a roles, while the key is the role name and the value is the absolute role path. ''' roles = {} paths = self.get_roles_paths() for path in paths: for entry in os.listdir(path): rolepath = os.path.join(path, entry) if os.path.isdir(rolepath): roles[entry] = rolepath return roles
[ "def", "get_roles", "(", "self", ")", ":", "roles", "=", "{", "}", "paths", "=", "self", ".", "get_roles_paths", "(", ")", "for", "path", "in", "paths", ":", "for", "entry", "in", "os", ".", "listdir", "(", "path", ")", ":", "rolepath", "=", "os", ...
Returns a key-value dict with a roles, while the key is the role name and the value is the absolute role path.
[ "Returns", "a", "key", "-", "value", "dict", "with", "a", "roles", "while", "the", "key", "is", "the", "role", "name", "and", "the", "value", "is", "the", "absolute", "role", "path", "." ]
6a53ae8c4a4653624977e146092422857f661b8f
https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L49-L63
train
51,810
confirm/ansibleci
ansibleci/helper.py
Helper.read_yaml
def read_yaml(self, filename): ''' Reads and parses a YAML file and returns the content. ''' with open(filename, 'r') as f: d = re.sub(r'\{\{ *([^ ]+) *\}\}', r'\1', f.read()) y = yaml.safe_load(d) return y if y else {}
python
def read_yaml(self, filename): ''' Reads and parses a YAML file and returns the content. ''' with open(filename, 'r') as f: d = re.sub(r'\{\{ *([^ ]+) *\}\}', r'\1', f.read()) y = yaml.safe_load(d) return y if y else {}
[ "def", "read_yaml", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "d", "=", "re", ".", "sub", "(", "r'\\{\\{ *([^ ]+) *\\}\\}'", ",", "r'\\1'", ",", "f", ".", "read", "(", ")", ")", "y", ...
Reads and parses a YAML file and returns the content.
[ "Reads", "and", "parses", "a", "YAML", "file", "and", "returns", "the", "content", "." ]
6a53ae8c4a4653624977e146092422857f661b8f
https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L65-L72
train
51,811
confirm/ansibleci
ansibleci/helper.py
Helper.get_yaml_items
def get_yaml_items(self, dir_path, param=None): ''' Loops through the dir_path and parses all YAML files inside the directory. If no param is defined, then all YAML items will be returned in a list. If a param is defined, then all items will be scanned for this param and a list of all those values will be returned. ''' result = [] if not os.path.isdir(dir_path): return [] for filename in os.listdir(dir_path): path = os.path.join(dir_path, filename) items = self.read_yaml(path) for item in items: if param: if param in item: item = item[param] if isinstance(item, list): result.extend(item) else: result.append(item) else: result.append(item) return result
python
def get_yaml_items(self, dir_path, param=None): ''' Loops through the dir_path and parses all YAML files inside the directory. If no param is defined, then all YAML items will be returned in a list. If a param is defined, then all items will be scanned for this param and a list of all those values will be returned. ''' result = [] if not os.path.isdir(dir_path): return [] for filename in os.listdir(dir_path): path = os.path.join(dir_path, filename) items = self.read_yaml(path) for item in items: if param: if param in item: item = item[param] if isinstance(item, list): result.extend(item) else: result.append(item) else: result.append(item) return result
[ "def", "get_yaml_items", "(", "self", ",", "dir_path", ",", "param", "=", "None", ")", ":", "result", "=", "[", "]", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", ":", "return", "[", "]", "for", "filename", "in", "os", ".", ...
Loops through the dir_path and parses all YAML files inside the directory. If no param is defined, then all YAML items will be returned in a list. If a param is defined, then all items will be scanned for this param and a list of all those values will be returned.
[ "Loops", "through", "the", "dir_path", "and", "parses", "all", "YAML", "files", "inside", "the", "directory", "." ]
6a53ae8c4a4653624977e146092422857f661b8f
https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L74-L105
train
51,812
The-Politico/django-slackchat-serializer
slackchat/tasks/webhook.py
clean_response
def clean_response(response): """ Cleans string quoting in response. """ response = re.sub("^['\"]", "", response) response = re.sub("['\"]$", "", response) return response
python
def clean_response(response): """ Cleans string quoting in response. """ response = re.sub("^['\"]", "", response) response = re.sub("['\"]$", "", response) return response
[ "def", "clean_response", "(", "response", ")", ":", "response", "=", "re", ".", "sub", "(", "\"^['\\\"]\"", ",", "\"\"", ",", "response", ")", "response", "=", "re", ".", "sub", "(", "\"['\\\"]$\"", ",", "\"\"", ",", "response", ")", "return", "response"...
Cleans string quoting in response.
[ "Cleans", "string", "quoting", "in", "response", "." ]
9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40
https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/tasks/webhook.py#L63-L67
train
51,813
epandurski/flask_signalbus
flask_signalbus/utils.py
retry_on_deadlock
def retry_on_deadlock(session, retries=6, min_wait=0.1, max_wait=10.0): """Return function decorator that executes the function again in case of a deadlock.""" def decorator(action): """Function decorator that retries `action` in case of a deadlock.""" @wraps(action) def f(*args, **kwargs): num_failures = 0 while True: try: return action(*args, **kwargs) except (DBAPIError, DBSerializationError) as e: num_failures += 1 is_serialization_error = ( isinstance(e, DBSerializationError) or get_db_error_code(e.orig) in DEADLOCK_ERROR_CODES ) if num_failures > retries or not is_serialization_error: raise session.rollback() wait_seconds = min(max_wait, min_wait * 2 ** (num_failures - 1)) time.sleep(wait_seconds) return f return decorator
python
def retry_on_deadlock(session, retries=6, min_wait=0.1, max_wait=10.0): """Return function decorator that executes the function again in case of a deadlock.""" def decorator(action): """Function decorator that retries `action` in case of a deadlock.""" @wraps(action) def f(*args, **kwargs): num_failures = 0 while True: try: return action(*args, **kwargs) except (DBAPIError, DBSerializationError) as e: num_failures += 1 is_serialization_error = ( isinstance(e, DBSerializationError) or get_db_error_code(e.orig) in DEADLOCK_ERROR_CODES ) if num_failures > retries or not is_serialization_error: raise session.rollback() wait_seconds = min(max_wait, min_wait * 2 ** (num_failures - 1)) time.sleep(wait_seconds) return f return decorator
[ "def", "retry_on_deadlock", "(", "session", ",", "retries", "=", "6", ",", "min_wait", "=", "0.1", ",", "max_wait", "=", "10.0", ")", ":", "def", "decorator", "(", "action", ")", ":", "\"\"\"Function decorator that retries `action` in case of a deadlock.\"\"\"", "@"...
Return function decorator that executes the function again in case of a deadlock.
[ "Return", "function", "decorator", "that", "executes", "the", "function", "again", "in", "case", "of", "a", "deadlock", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/utils.py#L28-L54
train
51,814
xapple/plumbing
plumbing/cache.py
cached
def cached(f): """Decorator for functions evaluated only once.""" def memoized(*args, **kwargs): if hasattr(memoized, '__cache__'): return memoized.__cache__ result = f(*args, **kwargs) memoized.__cache__ = result return result return memoized
python
def cached(f): """Decorator for functions evaluated only once.""" def memoized(*args, **kwargs): if hasattr(memoized, '__cache__'): return memoized.__cache__ result = f(*args, **kwargs) memoized.__cache__ = result return result return memoized
[ "def", "cached", "(", "f", ")", ":", "def", "memoized", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "memoized", ",", "'__cache__'", ")", ":", "return", "memoized", ".", "__cache__", "result", "=", "f", "(", "*", "args...
Decorator for functions evaluated only once.
[ "Decorator", "for", "functions", "evaluated", "only", "once", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/cache.py#L12-L20
train
51,815
xapple/plumbing
plumbing/cache.py
property_pickled
def property_pickled(f): """Same thing as above but the result will be stored on disk The path of the pickle file will be determined by looking for the `cache_dir` attribute of the instance containing the cached property. If no `cache_dir` attribute exists the `p` attribute will be accessed with the name of the property being cached.""" # Called when you access the property # def retrieve_from_cache(self): # Is it in the cache ? # if '__cache__' not in self.__dict__: self.__cache__ = {} if f.__name__ in self.__cache__: return self.__cache__[f.__name__] # Where should we look in the file system ? # if 'cache_dir' in self.__dict__: path = FilePath(self.__dict__['cache_dir'] + f.func_name + '.pickle') else: path = getattr(self.p, f.func_name) # Is it on disk ? # if path.exists: with open(path) as handle: result = pickle.load(handle) self.__cache__[f.__name__] = result return result # Otherwise let's compute it # result = f(self) with open(path, 'w') as handle: pickle.dump(result, handle) self.__cache__[f.__name__] = result return result # Called when you set the property # def overwrite_cache(self, value): # Where should we look in the file system ? # if 'cache_dir' in self.__dict__: path = FilePath(self.__dict__['cache_dir'] + f.func_name + '.pickle') else: path = getattr(self.p, f.func_name) if value is None: path.remove() else: raise Exception("You can't set a pickled property, you can only delete it") # Return a wrapper # retrieve_from_cache.__doc__ = f.__doc__ return property(retrieve_from_cache, overwrite_cache)
python
def property_pickled(f): """Same thing as above but the result will be stored on disk The path of the pickle file will be determined by looking for the `cache_dir` attribute of the instance containing the cached property. If no `cache_dir` attribute exists the `p` attribute will be accessed with the name of the property being cached.""" # Called when you access the property # def retrieve_from_cache(self): # Is it in the cache ? # if '__cache__' not in self.__dict__: self.__cache__ = {} if f.__name__ in self.__cache__: return self.__cache__[f.__name__] # Where should we look in the file system ? # if 'cache_dir' in self.__dict__: path = FilePath(self.__dict__['cache_dir'] + f.func_name + '.pickle') else: path = getattr(self.p, f.func_name) # Is it on disk ? # if path.exists: with open(path) as handle: result = pickle.load(handle) self.__cache__[f.__name__] = result return result # Otherwise let's compute it # result = f(self) with open(path, 'w') as handle: pickle.dump(result, handle) self.__cache__[f.__name__] = result return result # Called when you set the property # def overwrite_cache(self, value): # Where should we look in the file system ? # if 'cache_dir' in self.__dict__: path = FilePath(self.__dict__['cache_dir'] + f.func_name + '.pickle') else: path = getattr(self.p, f.func_name) if value is None: path.remove() else: raise Exception("You can't set a pickled property, you can only delete it") # Return a wrapper # retrieve_from_cache.__doc__ = f.__doc__ return property(retrieve_from_cache, overwrite_cache)
[ "def", "property_pickled", "(", "f", ")", ":", "# Called when you access the property #", "def", "retrieve_from_cache", "(", "self", ")", ":", "# Is it in the cache ? #", "if", "'__cache__'", "not", "in", "self", ".", "__dict__", ":", "self", ".", "__cache__", "=", ...
Same thing as above but the result will be stored on disk The path of the pickle file will be determined by looking for the `cache_dir` attribute of the instance containing the cached property. If no `cache_dir` attribute exists the `p` attribute will be accessed with the name of the property being cached.
[ "Same", "thing", "as", "above", "but", "the", "result", "will", "be", "stored", "on", "disk", "The", "path", "of", "the", "pickle", "file", "will", "be", "determined", "by", "looking", "for", "the", "cache_dir", "attribute", "of", "the", "instance", "conta...
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/cache.py#L85-L122
train
51,816
matllubos/django-is-core
is_core/forms/formsets.py
smartformset_factory
def smartformset_factory(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, min_num=None, max_num=None, validate_min=False, validate_max=False): """Return a FormSet for the given form class.""" if max_num is None: max_num = DEFAULT_MAX_NUM # hard limit on forms instantiated, to prevent memory-exhaustion attacks # limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM # if max_num is None in the first place) absolute_max = max_num + DEFAULT_MAX_NUM if min_num is None: min_num = 0 attrs = {'form': form, 'extra': extra, 'can_order': can_order, 'can_delete': can_delete, 'min_num': min_num, 'max_num': max_num, 'absolute_max': absolute_max, 'validate_min': validate_min, 'validate_max': validate_max} return type(form.__name__ + str('FormSet'), (formset,), attrs)
python
def smartformset_factory(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, min_num=None, max_num=None, validate_min=False, validate_max=False): """Return a FormSet for the given form class.""" if max_num is None: max_num = DEFAULT_MAX_NUM # hard limit on forms instantiated, to prevent memory-exhaustion attacks # limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM # if max_num is None in the first place) absolute_max = max_num + DEFAULT_MAX_NUM if min_num is None: min_num = 0 attrs = {'form': form, 'extra': extra, 'can_order': can_order, 'can_delete': can_delete, 'min_num': min_num, 'max_num': max_num, 'absolute_max': absolute_max, 'validate_min': validate_min, 'validate_max': validate_max} return type(form.__name__ + str('FormSet'), (formset,), attrs)
[ "def", "smartformset_factory", "(", "form", ",", "formset", "=", "BaseFormSet", ",", "extra", "=", "1", ",", "can_order", "=", "False", ",", "can_delete", "=", "False", ",", "min_num", "=", "None", ",", "max_num", "=", "None", ",", "validate_min", "=", "...
Return a FormSet for the given form class.
[ "Return", "a", "FormSet", "for", "the", "given", "form", "class", "." ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/formsets.py#L34-L50
train
51,817
matllubos/django-is-core
is_core/generic_views/form_views.py
DefaultFormView.save_form
def save_form(self, form, **kwargs): """Contains formset save, prepare obj for saving""" obj = form.save(commit=False) change = obj.pk is not None self.save_obj(obj, form, change) if hasattr(form, 'save_m2m'): form.save_m2m() return obj
python
def save_form(self, form, **kwargs): """Contains formset save, prepare obj for saving""" obj = form.save(commit=False) change = obj.pk is not None self.save_obj(obj, form, change) if hasattr(form, 'save_m2m'): form.save_m2m() return obj
[ "def", "save_form", "(", "self", ",", "form", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "change", "=", "obj", ".", "pk", "is", "not", "None", "self", ".", "save_obj", "(", "obj", ",", ...
Contains formset save, prepare obj for saving
[ "Contains", "formset", "save", "prepare", "obj", "for", "saving" ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/form_views.py#L109-L117
train
51,818
matllubos/django-is-core
is_core/generic_views/form_views.py
DefaultFormView.get_method_returning_field_value
def get_method_returning_field_value(self, field_name): """ Field values can be obtained from view or core. """ return ( super().get_method_returning_field_value(field_name) or self.core.get_method_returning_field_value(field_name) )
python
def get_method_returning_field_value(self, field_name): """ Field values can be obtained from view or core. """ return ( super().get_method_returning_field_value(field_name) or self.core.get_method_returning_field_value(field_name) )
[ "def", "get_method_returning_field_value", "(", "self", ",", "field_name", ")", ":", "return", "(", "super", "(", ")", ".", "get_method_returning_field_value", "(", "field_name", ")", "or", "self", ".", "core", ".", "get_method_returning_field_value", "(", "field_na...
Field values can be obtained from view or core.
[ "Field", "values", "can", "be", "obtained", "from", "view", "or", "core", "." ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/form_views.py#L267-L274
train
51,819
matllubos/django-is-core
is_core/generic_views/form_views.py
DetailModelFormView._get_perm_obj_or_404
def _get_perm_obj_or_404(self, pk=None): """ If is send parameter pk is returned object according this pk, else is returned object from get_obj method, but it search only inside filtered values for current user, finally if object is still None is returned according the input key from all objects. If object does not exist is raised Http404 """ if pk: obj = get_object_or_none(self.core.model, pk=pk) else: try: obj = self.get_obj(False) except Http404: obj = get_object_or_none(self.core.model, **self.get_obj_filters()) if not obj: raise Http404 return obj
python
def _get_perm_obj_or_404(self, pk=None): """ If is send parameter pk is returned object according this pk, else is returned object from get_obj method, but it search only inside filtered values for current user, finally if object is still None is returned according the input key from all objects. If object does not exist is raised Http404 """ if pk: obj = get_object_or_none(self.core.model, pk=pk) else: try: obj = self.get_obj(False) except Http404: obj = get_object_or_none(self.core.model, **self.get_obj_filters()) if not obj: raise Http404 return obj
[ "def", "_get_perm_obj_or_404", "(", "self", ",", "pk", "=", "None", ")", ":", "if", "pk", ":", "obj", "=", "get_object_or_none", "(", "self", ".", "core", ".", "model", ",", "pk", "=", "pk", ")", "else", ":", "try", ":", "obj", "=", "self", ".", ...
If is send parameter pk is returned object according this pk, else is returned object from get_obj method, but it search only inside filtered values for current user, finally if object is still None is returned according the input key from all objects. If object does not exist is raised Http404
[ "If", "is", "send", "parameter", "pk", "is", "returned", "object", "according", "this", "pk", "else", "is", "returned", "object", "from", "get_obj", "method", "but", "it", "search", "only", "inside", "filtered", "values", "for", "current", "user", "finally", ...
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/form_views.py#L652-L669
train
51,820
intelligenia/modeltranslation
modeltranslation/admin/views.py
view_all
def view_all(request, language, filter=None): """ View all translations that are in site. """ # Is there any filter? if request.method == "POST": data = request.POST.dict() if not data["search"] or data["search"]=="": return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language"],data["filter"]))) return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language"],data["filter"]))+"?search="+data["search"]) LANGUAGES = dict(lang for lang in settings.LANGUAGES) if language not in LANGUAGES.keys(): raise Http404(u"Language {0} does not exist".format(language)) if language == settings.LANGUAGE_CODE: raise Http404(u"El idioma {0} es el idioma por defecto".format(language)) # Translation filter trans_filter = {"lang":language} if filter == "all" or filter is None: pass elif filter == "fuzzy": trans_filter["is_fuzzy"] = True elif filter == "completed": trans_filter["is_fuzzy"] = False search_query = "" if request.GET and "search" in request.GET and request.GET.get("search")!="": search_query = request.GET.get("search") trans_filter["source_text__icontains"] = search_query translations = FieldTranslation.objects.filter(**trans_filter) # Update translations active_translations = [] for translation in translations: source_model = translation.get_source_model() if not translation.field in source_model._meta.translatable_fields: translation.delete() else: active_translations.append(translation) replacements = {"translations":active_translations, "filter":filter, "lang":language, "language":LANGUAGES[language], "search_query":search_query} return render_to_response('modeltranslation/admin/list.html',replacements, RequestContext(request))
python
def view_all(request, language, filter=None): """ View all translations that are in site. """ # Is there any filter? if request.method == "POST": data = request.POST.dict() if not data["search"] or data["search"]=="": return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language"],data["filter"]))) return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language"],data["filter"]))+"?search="+data["search"]) LANGUAGES = dict(lang for lang in settings.LANGUAGES) if language not in LANGUAGES.keys(): raise Http404(u"Language {0} does not exist".format(language)) if language == settings.LANGUAGE_CODE: raise Http404(u"El idioma {0} es el idioma por defecto".format(language)) # Translation filter trans_filter = {"lang":language} if filter == "all" or filter is None: pass elif filter == "fuzzy": trans_filter["is_fuzzy"] = True elif filter == "completed": trans_filter["is_fuzzy"] = False search_query = "" if request.GET and "search" in request.GET and request.GET.get("search")!="": search_query = request.GET.get("search") trans_filter["source_text__icontains"] = search_query translations = FieldTranslation.objects.filter(**trans_filter) # Update translations active_translations = [] for translation in translations: source_model = translation.get_source_model() if not translation.field in source_model._meta.translatable_fields: translation.delete() else: active_translations.append(translation) replacements = {"translations":active_translations, "filter":filter, "lang":language, "language":LANGUAGES[language], "search_query":search_query} return render_to_response('modeltranslation/admin/list.html',replacements, RequestContext(request))
[ "def", "view_all", "(", "request", ",", "language", ",", "filter", "=", "None", ")", ":", "# Is there any filter?", "if", "request", ".", "method", "==", "\"POST\"", ":", "data", "=", "request", ".", "POST", ".", "dict", "(", ")", "if", "not", "data", ...
View all translations that are in site.
[ "View", "all", "translations", "that", "are", "in", "site", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L27-L74
train
51,821
intelligenia/modeltranslation
modeltranslation/admin/views.py
edit
def edit(request, translation): """ Edit a translation. @param request: Django HttpRequest object. @param translation: Translation id @return Django HttpResponse object with the view or a redirection. """ translation = get_object_or_404(FieldTranslation, id=translation) if request.method == 'POST': if "cancel" in request.POST: return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all"))) elif "save" in request.POST: form = FieldTranslationForm(request.POST, instance=translation) valid_form = form.is_valid() if valid_form: translation = form.save(commit=False) translation.context = u"Admin. Traducciones" translation.save() return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all"))) else: form = FieldTranslationForm(instance=translation) else: form = FieldTranslationForm(instance=translation) LANGUAGES = dict(lang for lang in settings.LANGUAGES) language = LANGUAGES[translation.lang] return render_to_response('modeltranslation/admin/edit_translation.html',{"translation":translation, "form":form, "lang":translation.lang, "language":language}, RequestContext(request))
python
def edit(request, translation): """ Edit a translation. @param request: Django HttpRequest object. @param translation: Translation id @return Django HttpResponse object with the view or a redirection. """ translation = get_object_or_404(FieldTranslation, id=translation) if request.method == 'POST': if "cancel" in request.POST: return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all"))) elif "save" in request.POST: form = FieldTranslationForm(request.POST, instance=translation) valid_form = form.is_valid() if valid_form: translation = form.save(commit=False) translation.context = u"Admin. Traducciones" translation.save() return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all"))) else: form = FieldTranslationForm(instance=translation) else: form = FieldTranslationForm(instance=translation) LANGUAGES = dict(lang for lang in settings.LANGUAGES) language = LANGUAGES[translation.lang] return render_to_response('modeltranslation/admin/edit_translation.html',{"translation":translation, "form":form, "lang":translation.lang, "language":language}, RequestContext(request))
[ "def", "edit", "(", "request", ",", "translation", ")", ":", "translation", "=", "get_object_or_404", "(", "FieldTranslation", ",", "id", "=", "translation", ")", "if", "request", ".", "method", "==", "'POST'", ":", "if", "\"cancel\"", "in", "request", ".", ...
Edit a translation. @param request: Django HttpRequest object. @param translation: Translation id @return Django HttpResponse object with the view or a redirection.
[ "Edit", "a", "translation", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L80-L107
train
51,822
intelligenia/modeltranslation
modeltranslation/admin/views.py
export_translations
def export_translations(request, language): """ Export translations view. """ FieldTranslation.delete_orphan_translations() translations = FieldTranslation.objects.filter(lang=language) for trans in translations: trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"") trans.translation = trans.translation.replace("'","\'").replace("\"","\\\"") replacements = {"translations":translations, "lang":language} if len(settings.ADMINS)>0: replacements["last_translator"] = settings.ADMINS[0][0] replacements["last_translator_email"] = settings.ADMINS[0][1] if settings.WEBSITE_NAME: replacements["website_name"] = settings.WEBSITE_NAME response = render(request=request, template_name='modeltranslation/admin/export_translations.po', dictionary=replacements, context_instance=RequestContext(request), content_type="text/x-gettext-translation") response['Content-Disposition'] = 'attachment; filename="{0}.po"'.format(language) return response
python
def export_translations(request, language): """ Export translations view. """ FieldTranslation.delete_orphan_translations() translations = FieldTranslation.objects.filter(lang=language) for trans in translations: trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"") trans.translation = trans.translation.replace("'","\'").replace("\"","\\\"") replacements = {"translations":translations, "lang":language} if len(settings.ADMINS)>0: replacements["last_translator"] = settings.ADMINS[0][0] replacements["last_translator_email"] = settings.ADMINS[0][1] if settings.WEBSITE_NAME: replacements["website_name"] = settings.WEBSITE_NAME response = render(request=request, template_name='modeltranslation/admin/export_translations.po', dictionary=replacements, context_instance=RequestContext(request), content_type="text/x-gettext-translation") response['Content-Disposition'] = 'attachment; filename="{0}.po"'.format(language) return response
[ "def", "export_translations", "(", "request", ",", "language", ")", ":", "FieldTranslation", ".", "delete_orphan_translations", "(", ")", "translations", "=", "FieldTranslation", ".", "objects", ".", "filter", "(", "lang", "=", "language", ")", "for", "trans", "...
Export translations view.
[ "Export", "translations", "view", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L182-L199
train
51,823
qba73/circleclient
circleclient/circleclient.py
CircleClient.client_get
def client_get(self, url, **kwargs): """Send GET request with given url.""" response = requests.get(self.make_url(url), headers=self.headers) if not response.ok: raise Exception( '{status}: {reason}.\nCircleCI Status NOT OK'.format( status=response.status_code, reason=response.reason)) return response.json()
python
def client_get(self, url, **kwargs): """Send GET request with given url.""" response = requests.get(self.make_url(url), headers=self.headers) if not response.ok: raise Exception( '{status}: {reason}.\nCircleCI Status NOT OK'.format( status=response.status_code, reason=response.reason)) return response.json()
[ "def", "client_get", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "response", "=", "requests", ".", "get", "(", "self", ".", "make_url", "(", "url", ")", ",", "headers", "=", "self", ".", "headers", ")", "if", "not", "response", ".",...
Send GET request with given url.
[ "Send", "GET", "request", "with", "given", "url", "." ]
8bf5b093e416c899cc39e43a770c17a5466487b0
https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L37-L44
train
51,824
qba73/circleclient
circleclient/circleclient.py
CircleClient.client_post
def client_post(self, url, **kwargs): """Send POST request with given url and keyword args.""" response = requests.post(self.make_url(url), data=json.dumps(kwargs), headers=self.headers) if not response.ok: raise Exception( '{status}: {reason}.\nCircleCI Status NOT OK'.format( status=response.status_code, reason=response.reason)) return response.json()
python
def client_post(self, url, **kwargs): """Send POST request with given url and keyword args.""" response = requests.post(self.make_url(url), data=json.dumps(kwargs), headers=self.headers) if not response.ok: raise Exception( '{status}: {reason}.\nCircleCI Status NOT OK'.format( status=response.status_code, reason=response.reason)) return response.json()
[ "def", "client_post", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "response", "=", "requests", ".", "post", "(", "self", ".", "make_url", "(", "url", ")", ",", "data", "=", "json", ".", "dumps", "(", "kwargs", ")", ",", "headers", ...
Send POST request with given url and keyword args.
[ "Send", "POST", "request", "with", "given", "url", "and", "keyword", "args", "." ]
8bf5b093e416c899cc39e43a770c17a5466487b0
https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L46-L55
train
51,825
qba73/circleclient
circleclient/circleclient.py
CircleClient.client_delete
def client_delete(self, url, **kwargs): """Send POST request with given url.""" response = requests.delete(self.make_url(url), headers=self.headers) if not response.ok: raise Exception( '{status}: {reason}.\nCircleCI Status NOT OK'.format( status=response.status_code, reason=response.reason)) return response.json()
python
def client_delete(self, url, **kwargs): """Send POST request with given url.""" response = requests.delete(self.make_url(url), headers=self.headers) if not response.ok: raise Exception( '{status}: {reason}.\nCircleCI Status NOT OK'.format( status=response.status_code, reason=response.reason)) return response.json()
[ "def", "client_delete", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "response", "=", "requests", ".", "delete", "(", "self", ".", "make_url", "(", "url", ")", ",", "headers", "=", "self", ".", "headers", ")", "if", "not", "response", ...
Send POST request with given url.
[ "Send", "POST", "request", "with", "given", "url", "." ]
8bf5b093e416c899cc39e43a770c17a5466487b0
https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L57-L64
train
51,826
qba73/circleclient
circleclient/circleclient.py
Projects.list_projects
def list_projects(self): """Return a list of all followed projects.""" method = 'GET' url = '/projects?circle-token={token}'.format( token=self.client.api_token) json_data = self.client.request(method, url) return json_data
python
def list_projects(self): """Return a list of all followed projects.""" method = 'GET' url = '/projects?circle-token={token}'.format( token=self.client.api_token) json_data = self.client.request(method, url) return json_data
[ "def", "list_projects", "(", "self", ")", ":", "method", "=", "'GET'", "url", "=", "'/projects?circle-token={token}'", ".", "format", "(", "token", "=", "self", ".", "client", ".", "api_token", ")", "json_data", "=", "self", ".", "client", ".", "request", ...
Return a list of all followed projects.
[ "Return", "a", "list", "of", "all", "followed", "projects", "." ]
8bf5b093e416c899cc39e43a770c17a5466487b0
https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L97-L103
train
51,827
qba73/circleclient
circleclient/circleclient.py
Build.trigger
def trigger(self, username, project, branch, **build_params): """Trigger new build and return a summary of the build.""" method = 'POST' url = ('/project/{username}/{project}/tree/{branch}?' 'circle-token={token}'.format( username=username, project=project, branch=branch, token=self.client.api_token)) if build_params is not None: json_data = self.client.request(method, url, build_parameters=build_params) else: json_data = self.client.request(method, url) return json_data
python
def trigger(self, username, project, branch, **build_params): """Trigger new build and return a summary of the build.""" method = 'POST' url = ('/project/{username}/{project}/tree/{branch}?' 'circle-token={token}'.format( username=username, project=project, branch=branch, token=self.client.api_token)) if build_params is not None: json_data = self.client.request(method, url, build_parameters=build_params) else: json_data = self.client.request(method, url) return json_data
[ "def", "trigger", "(", "self", ",", "username", ",", "project", ",", "branch", ",", "*", "*", "build_params", ")", ":", "method", "=", "'POST'", "url", "=", "(", "'/project/{username}/{project}/tree/{branch}?'", "'circle-token={token}'", ".", "format", "(", "use...
Trigger new build and return a summary of the build.
[ "Trigger", "new", "build", "and", "return", "a", "summary", "of", "the", "build", "." ]
8bf5b093e416c899cc39e43a770c17a5466487b0
https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L111-L124
train
51,828
qba73/circleclient
circleclient/circleclient.py
Build.cancel
def cancel(self, username, project, build_num): """Cancel the build and return its summary.""" method = 'POST' url = ('/project/{username}/{project}/{build_num}/cancel?' 'circle-token={token}'.format(username=username, project=project, build_num=build_num, token=self.client.api_token)) json_data = self.client.request(method, url) return json_data
python
def cancel(self, username, project, build_num): """Cancel the build and return its summary.""" method = 'POST' url = ('/project/{username}/{project}/{build_num}/cancel?' 'circle-token={token}'.format(username=username, project=project, build_num=build_num, token=self.client.api_token)) json_data = self.client.request(method, url) return json_data
[ "def", "cancel", "(", "self", ",", "username", ",", "project", ",", "build_num", ")", ":", "method", "=", "'POST'", "url", "=", "(", "'/project/{username}/{project}/{build_num}/cancel?'", "'circle-token={token}'", ".", "format", "(", "username", "=", "username", "...
Cancel the build and return its summary.
[ "Cancel", "the", "build", "and", "return", "its", "summary", "." ]
8bf5b093e416c899cc39e43a770c17a5466487b0
https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L126-L135
train
51,829
qba73/circleclient
circleclient/circleclient.py
Build.recent_all_projects
def recent_all_projects(self, limit=30, offset=0): """Return information about recent builds across all projects. Args: limit (int), Number of builds to return, max=100, defaults=30. offset (int): Builds returned from this point, default=0. Returns: A list of dictionaries. """ method = 'GET' url = ('/recent-builds?circle-token={token}&limit={limit}&' 'offset={offset}'.format(token=self.client.api_token, limit=limit, offset=offset)) json_data = self.client.request(method, url) return json_data
python
def recent_all_projects(self, limit=30, offset=0): """Return information about recent builds across all projects. Args: limit (int), Number of builds to return, max=100, defaults=30. offset (int): Builds returned from this point, default=0. Returns: A list of dictionaries. """ method = 'GET' url = ('/recent-builds?circle-token={token}&limit={limit}&' 'offset={offset}'.format(token=self.client.api_token, limit=limit, offset=offset)) json_data = self.client.request(method, url) return json_data
[ "def", "recent_all_projects", "(", "self", ",", "limit", "=", "30", ",", "offset", "=", "0", ")", ":", "method", "=", "'GET'", "url", "=", "(", "'/recent-builds?circle-token={token}&limit={limit}&'", "'offset={offset}'", ".", "format", "(", "token", "=", "self",...
Return information about recent builds across all projects. Args: limit (int), Number of builds to return, max=100, defaults=30. offset (int): Builds returned from this point, default=0. Returns: A list of dictionaries.
[ "Return", "information", "about", "recent", "builds", "across", "all", "projects", "." ]
8bf5b093e416c899cc39e43a770c17a5466487b0
https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L173-L189
train
51,830
qba73/circleclient
circleclient/circleclient.py
Build.recent
def recent(self, username, project, limit=1, offset=0, branch=None, status_filter=""): """Return status of recent builds for given project. Retrieves build statuses for given project and branch. If branch is None it retrieves most recent build. Args: username (str): Name of the user. project (str): Name of the project. limit (int): Number of builds to return, default=1, max=100. offset (int): Returns builds starting from given offset. branch (str): Optional branch name as string. If specified only builds from given branch are returned. status_filter (str): Restricts which builds are returned. Set to "completed", "successful", "failed", "running", or defaults to no filter. Returns: A list of dictionaries with information about each build. """ method = 'GET' if branch is not None: url = ('/project/{username}/{project}/tree/{branch}?' 'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'.format( username=username, project=project, branch=branch, token=self.client.api_token, limit=limit, offset=offset, status_filter=status_filter)) else: url = ('/project/{username}/{project}?' 'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'.format( username=username, project=project, token=self.client.api_token, limit=limit, offset=offset, status_filter=status_filter)) json_data = self.client.request(method, url) return json_data
python
def recent(self, username, project, limit=1, offset=0, branch=None, status_filter=""): """Return status of recent builds for given project. Retrieves build statuses for given project and branch. If branch is None it retrieves most recent build. Args: username (str): Name of the user. project (str): Name of the project. limit (int): Number of builds to return, default=1, max=100. offset (int): Returns builds starting from given offset. branch (str): Optional branch name as string. If specified only builds from given branch are returned. status_filter (str): Restricts which builds are returned. Set to "completed", "successful", "failed", "running", or defaults to no filter. Returns: A list of dictionaries with information about each build. """ method = 'GET' if branch is not None: url = ('/project/{username}/{project}/tree/{branch}?' 'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'.format( username=username, project=project, branch=branch, token=self.client.api_token, limit=limit, offset=offset, status_filter=status_filter)) else: url = ('/project/{username}/{project}?' 'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'.format( username=username, project=project, token=self.client.api_token, limit=limit, offset=offset, status_filter=status_filter)) json_data = self.client.request(method, url) return json_data
[ "def", "recent", "(", "self", ",", "username", ",", "project", ",", "limit", "=", "1", ",", "offset", "=", "0", ",", "branch", "=", "None", ",", "status_filter", "=", "\"\"", ")", ":", "method", "=", "'GET'", "if", "branch", "is", "not", "None", ":...
Return status of recent builds for given project. Retrieves build statuses for given project and branch. If branch is None it retrieves most recent build. Args: username (str): Name of the user. project (str): Name of the project. limit (int): Number of builds to return, default=1, max=100. offset (int): Returns builds starting from given offset. branch (str): Optional branch name as string. If specified only builds from given branch are returned. status_filter (str): Restricts which builds are returned. Set to "completed", "successful", "failed", "running", or defaults to no filter. Returns: A list of dictionaries with information about each build.
[ "Return", "status", "of", "recent", "builds", "for", "given", "project", "." ]
8bf5b093e416c899cc39e43a770c17a5466487b0
https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L191-L225
train
51,831
qba73/circleclient
circleclient/circleclient.py
Cache.clear
def clear(self, username, project): """Clear the cache for given project.""" method = 'DELETE' url = ('/project/{username}/{project}/build-cache?' 'circle-token={token}'.format(username=username, project=project, token=self.client.api_token)) json_data = self.client.request(method, url) return json_data
python
def clear(self, username, project): """Clear the cache for given project.""" method = 'DELETE' url = ('/project/{username}/{project}/build-cache?' 'circle-token={token}'.format(username=username, project=project, token=self.client.api_token)) json_data = self.client.request(method, url) return json_data
[ "def", "clear", "(", "self", ",", "username", ",", "project", ")", ":", "method", "=", "'DELETE'", "url", "=", "(", "'/project/{username}/{project}/build-cache?'", "'circle-token={token}'", ".", "format", "(", "username", "=", "username", ",", "project", "=", "p...
Clear the cache for given project.
[ "Clear", "the", "cache", "for", "given", "project", "." ]
8bf5b093e416c899cc39e43a770c17a5466487b0
https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L233-L241
train
51,832
The-Politico/django-slackchat-serializer
slackchat/views/api/channel.py
ChannelDeserializer.post
def post(self, request, format=None): """ Add a new Channel. """ data = request.data.copy() # Get chat type record try: ct = ChatType.objects.get(pk=data.pop("chat_type")) data["chat_type"] = ct except ChatType.DoesNotExist: return typeNotFound404 if not self.is_path_unique( None, data["publish_path"], ct.publish_path ): return notUnique400 # Get user record try: u = User.objects.get(pk=data.pop("owner")) data["owner"] = u except User.DoesNotExist: return userNotFound404 c = Channel(**data) c.save() self.handle_webhook(c) return Response( { "text": "Channel saved.", "method": "POST", "saved": ChannelCMSSerializer(c).data, }, 200, )
python
def post(self, request, format=None): """ Add a new Channel. """ data = request.data.copy() # Get chat type record try: ct = ChatType.objects.get(pk=data.pop("chat_type")) data["chat_type"] = ct except ChatType.DoesNotExist: return typeNotFound404 if not self.is_path_unique( None, data["publish_path"], ct.publish_path ): return notUnique400 # Get user record try: u = User.objects.get(pk=data.pop("owner")) data["owner"] = u except User.DoesNotExist: return userNotFound404 c = Channel(**data) c.save() self.handle_webhook(c) return Response( { "text": "Channel saved.", "method": "POST", "saved": ChannelCMSSerializer(c).data, }, 200, )
[ "def", "post", "(", "self", ",", "request", ",", "format", "=", "None", ")", ":", "data", "=", "request", ".", "data", ".", "copy", "(", ")", "# Get chat type record", "try", ":", "ct", "=", "ChatType", ".", "objects", ".", "get", "(", "pk", "=", "...
Add a new Channel.
[ "Add", "a", "new", "Channel", "." ]
9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40
https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/views/api/channel.py#L66-L103
train
51,833
The-Politico/django-slackchat-serializer
slackchat/views/api/channel.py
ChannelDeserializer.patch
def patch(self, request, format=None): """ Update an existing Channel """ data = request.data.copy() # Get chat type record try: ct = ChatType.objects.get(id=data.pop("chat_type")) data["chat_type"] = ct except ChatType.DoesNotExist: return typeNotFound404 if not self.is_path_unique( data["id"], data["publish_path"], ct.publish_path ): return notUnique400 # Get channel record try: c = Channel.objects.get(id=data.pop("id")) except Channel.DoesNotExist: return channelNotFound404 # Save new data for key, value in data.items(): setattr(c, key, value) c.save() self.handle_webhook(c) return Response( { "text": "Channel saved.", "method": "PATCH", "saved": ChannelCMSSerializer(c).data, }, 200, )
python
def patch(self, request, format=None): """ Update an existing Channel """ data = request.data.copy() # Get chat type record try: ct = ChatType.objects.get(id=data.pop("chat_type")) data["chat_type"] = ct except ChatType.DoesNotExist: return typeNotFound404 if not self.is_path_unique( data["id"], data["publish_path"], ct.publish_path ): return notUnique400 # Get channel record try: c = Channel.objects.get(id=data.pop("id")) except Channel.DoesNotExist: return channelNotFound404 # Save new data for key, value in data.items(): setattr(c, key, value) c.save() self.handle_webhook(c) return Response( { "text": "Channel saved.", "method": "PATCH", "saved": ChannelCMSSerializer(c).data, }, 200, )
[ "def", "patch", "(", "self", ",", "request", ",", "format", "=", "None", ")", ":", "data", "=", "request", ".", "data", ".", "copy", "(", ")", "# Get chat type record", "try", ":", "ct", "=", "ChatType", ".", "objects", ".", "get", "(", "id", "=", ...
Update an existing Channel
[ "Update", "an", "existing", "Channel" ]
9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40
https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/views/api/channel.py#L105-L143
train
51,834
StorjOld/file-encryptor
file_encryptor/key_generators.py
sha256_file
def sha256_file(path): """Calculate sha256 hex digest of a file. :param path: The path of the file you are calculating the digest of. :type path: str :returns: The sha256 hex digest of the specified file. :rtype: builtin_function_or_method """ h = hashlib.sha256() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(CHUNK_SIZE), b''): h.update(chunk) return h.hexdigest()
python
def sha256_file(path): """Calculate sha256 hex digest of a file. :param path: The path of the file you are calculating the digest of. :type path: str :returns: The sha256 hex digest of the specified file. :rtype: builtin_function_or_method """ h = hashlib.sha256() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(CHUNK_SIZE), b''): h.update(chunk) return h.hexdigest()
[ "def", "sha256_file", "(", "path", ")", ":", "h", "=", "hashlib", ".", "sha256", "(", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "for", "chunk", "in", "iter", "(", "lambda", ":", "f", ".", "read", "(", "CHUNK_SIZE", ")", ...
Calculate sha256 hex digest of a file. :param path: The path of the file you are calculating the digest of. :type path: str :returns: The sha256 hex digest of the specified file. :rtype: builtin_function_or_method
[ "Calculate", "sha256", "hex", "digest", "of", "a", "file", "." ]
245191c45dbd68e09a4a8f07c5d7331be195dc6b
https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/key_generators.py#L32-L46
train
51,835
StorjOld/file-encryptor
file_encryptor/key_generators.py
key_from_file
def key_from_file(filename, passphrase): """Calculate convergent encryption key. This takes a filename and an optional passphrase. If no passphrase is given, a default is used. Using the default passphrase means you will be vulnerable to confirmation attacks and learn-partial-information attacks. :param filename: The filename you want to create a key for. :type filename: str :param passphrase: The passphrase you want to use to encrypt the file. :type passphrase: str or None :returns: A convergent encryption key. :rtype: str """ hexdigest = sha256_file(filename) if passphrase is None: passphrase = DEFAULT_HMAC_PASSPHRASE return keyed_hash(hexdigest, passphrase)
python
def key_from_file(filename, passphrase): """Calculate convergent encryption key. This takes a filename and an optional passphrase. If no passphrase is given, a default is used. Using the default passphrase means you will be vulnerable to confirmation attacks and learn-partial-information attacks. :param filename: The filename you want to create a key for. :type filename: str :param passphrase: The passphrase you want to use to encrypt the file. :type passphrase: str or None :returns: A convergent encryption key. :rtype: str """ hexdigest = sha256_file(filename) if passphrase is None: passphrase = DEFAULT_HMAC_PASSPHRASE return keyed_hash(hexdigest, passphrase)
[ "def", "key_from_file", "(", "filename", ",", "passphrase", ")", ":", "hexdigest", "=", "sha256_file", "(", "filename", ")", "if", "passphrase", "is", "None", ":", "passphrase", "=", "DEFAULT_HMAC_PASSPHRASE", "return", "keyed_hash", "(", "hexdigest", ",", "pass...
Calculate convergent encryption key. This takes a filename and an optional passphrase. If no passphrase is given, a default is used. Using the default passphrase means you will be vulnerable to confirmation attacks and learn-partial-information attacks. :param filename: The filename you want to create a key for. :type filename: str :param passphrase: The passphrase you want to use to encrypt the file. :type passphrase: str or None :returns: A convergent encryption key. :rtype: str
[ "Calculate", "convergent", "encryption", "key", "." ]
245191c45dbd68e09a4a8f07c5d7331be195dc6b
https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/key_generators.py#L49-L70
train
51,836
IwoHerka/sexpr
sexpr/utils.py
find_child
def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr]: """Search for a tag among direct children of the s-expression.""" _assert_valid_sexpr(sexpr) for child in sexpr[1:]: if _is_sexpr(child) and child[0] in tags: return child return None
python
def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr]: """Search for a tag among direct children of the s-expression.""" _assert_valid_sexpr(sexpr) for child in sexpr[1:]: if _is_sexpr(child) and child[0] in tags: return child return None
[ "def", "find_child", "(", "sexpr", ":", "Sexpr", ",", "*", "tags", ":", "str", ")", "->", "Optional", "[", "Sexpr", "]", ":", "_assert_valid_sexpr", "(", "sexpr", ")", "for", "child", "in", "sexpr", "[", "1", ":", "]", ":", "if", "_is_sexpr", "(", ...
Search for a tag among direct children of the s-expression.
[ "Search", "for", "a", "tag", "among", "direct", "children", "of", "the", "s", "-", "expression", "." ]
28e32f543a127bbbf832b2dba7cb93f9e57db3b6
https://github.com/IwoHerka/sexpr/blob/28e32f543a127bbbf832b2dba7cb93f9e57db3b6/sexpr/utils.py#L51-L59
train
51,837
matllubos/django-is-core
is_core/forms/widgets.py
WrapperWidget.build_attrs
def build_attrs(self, *args, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(*args, **kwargs) return self.attrs
python
def build_attrs(self, *args, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(*args, **kwargs) return self.attrs
[ "def", "build_attrs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "attrs", "=", "self", ".", "widget", ".", "build_attrs", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "attrs" ]
Helper function for building an attribute dictionary.
[ "Helper", "function", "for", "building", "an", "attribute", "dictionary", "." ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/widgets.py#L52-L55
train
51,838
matllubos/django-is-core
is_core/forms/widgets.py
ClearableFileInput.get_template_substitution_values
def get_template_substitution_values(self, value): """ Return value-related substitutions. """ return { 'initial': os.path.basename(conditional_escape(value)), 'initial_url': conditional_escape(value.url), }
python
def get_template_substitution_values(self, value): """ Return value-related substitutions. """ return { 'initial': os.path.basename(conditional_escape(value)), 'initial_url': conditional_escape(value.url), }
[ "def", "get_template_substitution_values", "(", "self", ",", "value", ")", ":", "return", "{", "'initial'", ":", "os", ".", "path", ".", "basename", "(", "conditional_escape", "(", "value", ")", ")", ",", "'initial_url'", ":", "conditional_escape", "(", "value...
Return value-related substitutions.
[ "Return", "value", "-", "related", "substitutions", "." ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/widgets.py#L109-L116
train
51,839
matllubos/django-is-core
is_core/forms/widgets.py
RestrictedSelectWidgetMixin.is_restricted
def is_restricted(self): """ Returns True or False according to number of objects in queryset. If queryset contains too much objects the widget will be restricted and won't be used select box with choices. """ return ( not hasattr(self.choices, 'queryset') or self.choices.queryset.count() > settings.FOREIGN_KEY_MAX_SELECBOX_ENTRIES )
python
def is_restricted(self): """ Returns True or False according to number of objects in queryset. If queryset contains too much objects the widget will be restricted and won't be used select box with choices. """ return ( not hasattr(self.choices, 'queryset') or self.choices.queryset.count() > settings.FOREIGN_KEY_MAX_SELECBOX_ENTRIES )
[ "def", "is_restricted", "(", "self", ")", ":", "return", "(", "not", "hasattr", "(", "self", ".", "choices", ",", "'queryset'", ")", "or", "self", ".", "choices", ".", "queryset", ".", "count", "(", ")", ">", "settings", ".", "FOREIGN_KEY_MAX_SELECBOX_ENTR...
Returns True or False according to number of objects in queryset. If queryset contains too much objects the widget will be restricted and won't be used select box with choices.
[ "Returns", "True", "or", "False", "according", "to", "number", "of", "objects", "in", "queryset", ".", "If", "queryset", "contains", "too", "much", "objects", "the", "widget", "will", "be", "restricted", "and", "won", "t", "be", "used", "select", "box", "w...
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/widgets.py#L412-L420
train
51,840
codeforamerica/three
three/api.py
city
def city(name=None): """ Store the city that will be queried against. >>> three.city('sf') """ info = find_info(name) os.environ['OPEN311_CITY_INFO'] = dumps(info) return Three(**info)
python
def city(name=None): """ Store the city that will be queried against. >>> three.city('sf') """ info = find_info(name) os.environ['OPEN311_CITY_INFO'] = dumps(info) return Three(**info)
[ "def", "city", "(", "name", "=", "None", ")", ":", "info", "=", "find_info", "(", "name", ")", "os", ".", "environ", "[", "'OPEN311_CITY_INFO'", "]", "=", "dumps", "(", "info", ")", "return", "Three", "(", "*", "*", "info", ")" ]
Store the city that will be queried against. >>> three.city('sf')
[ "Store", "the", "city", "that", "will", "be", "queried", "against", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/api.py#L23-L31
train
51,841
codeforamerica/three
three/api.py
dev
def dev(endpoint, **kwargs): """ Use an endpoint and any additional keyword arguments rather than one of the pre-defined cities. Similar to the `city` function, but useful for development. """ kwargs['endpoint'] = endpoint os.environ['OPEN311_CITY_INFO'] = dumps(kwargs) return Three(**kwargs)
python
def dev(endpoint, **kwargs): """ Use an endpoint and any additional keyword arguments rather than one of the pre-defined cities. Similar to the `city` function, but useful for development. """ kwargs['endpoint'] = endpoint os.environ['OPEN311_CITY_INFO'] = dumps(kwargs) return Three(**kwargs)
[ "def", "dev", "(", "endpoint", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'endpoint'", "]", "=", "endpoint", "os", ".", "environ", "[", "'OPEN311_CITY_INFO'", "]", "=", "dumps", "(", "kwargs", ")", "return", "Three", "(", "*", "*", "kwargs", ...
Use an endpoint and any additional keyword arguments rather than one of the pre-defined cities. Similar to the `city` function, but useful for development.
[ "Use", "an", "endpoint", "and", "any", "additional", "keyword", "arguments", "rather", "than", "one", "of", "the", "pre", "-", "defined", "cities", ".", "Similar", "to", "the", "city", "function", "but", "useful", "for", "development", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/api.py#L40-L48
train
51,842
matllubos/django-is-core
is_core/utils/__init__.py
display_object_data
def display_object_data(obj, field_name, request=None): """ Returns humanized value of model object that can be rendered to HTML or returned as part of REST examples: boolean True/Talse ==> Yes/No objects ==> object display name with link if current user has permissions to see the object field with choices ==> string value of choice field with humanize function ==> result of humanize function """ from is_core.forms.utils import ReadonlyValue value, _, _ = get_readonly_field_data(field_name, obj) return display_for_value(value.humanized_value if isinstance(value, ReadonlyValue) else value, request=request)
python
def display_object_data(obj, field_name, request=None): """ Returns humanized value of model object that can be rendered to HTML or returned as part of REST examples: boolean True/Talse ==> Yes/No objects ==> object display name with link if current user has permissions to see the object field with choices ==> string value of choice field with humanize function ==> result of humanize function """ from is_core.forms.utils import ReadonlyValue value, _, _ = get_readonly_field_data(field_name, obj) return display_for_value(value.humanized_value if isinstance(value, ReadonlyValue) else value, request=request)
[ "def", "display_object_data", "(", "obj", ",", "field_name", ",", "request", "=", "None", ")", ":", "from", "is_core", ".", "forms", ".", "utils", "import", "ReadonlyValue", "value", ",", "_", ",", "_", "=", "get_readonly_field_data", "(", "field_name", ",",...
Returns humanized value of model object that can be rendered to HTML or returned as part of REST examples: boolean True/Talse ==> Yes/No objects ==> object display name with link if current user has permissions to see the object field with choices ==> string value of choice field with humanize function ==> result of humanize function
[ "Returns", "humanized", "value", "of", "model", "object", "that", "can", "be", "rendered", "to", "HTML", "or", "returned", "as", "part", "of", "REST" ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L249-L262
train
51,843
matllubos/django-is-core
is_core/utils/__init__.py
display_for_value
def display_for_value(value, request=None): """ Converts humanized value examples: boolean True/Talse ==> Yes/No objects ==> object display name with link if current user has permissions to see the object datetime ==> in localized format """ from is_core.utils.compatibility import admin_display_for_value if request and isinstance(value, Model): return render_model_object_with_link(request, value) else: return ( (value and ugettext('Yes') or ugettext('No')) if isinstance(value, bool) else admin_display_for_value(value) )
python
def display_for_value(value, request=None): """ Converts humanized value examples: boolean True/Talse ==> Yes/No objects ==> object display name with link if current user has permissions to see the object datetime ==> in localized format """ from is_core.utils.compatibility import admin_display_for_value if request and isinstance(value, Model): return render_model_object_with_link(request, value) else: return ( (value and ugettext('Yes') or ugettext('No')) if isinstance(value, bool) else admin_display_for_value(value) )
[ "def", "display_for_value", "(", "value", ",", "request", "=", "None", ")", ":", "from", "is_core", ".", "utils", ".", "compatibility", "import", "admin_display_for_value", "if", "request", "and", "isinstance", "(", "value", ",", "Model", ")", ":", "return", ...
Converts humanized value examples: boolean True/Talse ==> Yes/No objects ==> object display name with link if current user has permissions to see the object datetime ==> in localized format
[ "Converts", "humanized", "value" ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L265-L281
train
51,844
matllubos/django-is-core
is_core/utils/__init__.py
get_url_from_model_core
def get_url_from_model_core(request, obj): """ Returns object URL from model core. """ from is_core.site import get_model_core model_core = get_model_core(obj.__class__) if model_core and hasattr(model_core, 'ui_patterns'): edit_pattern = model_core.ui_patterns.get('detail') return ( edit_pattern.get_url_string(request, obj=obj) if edit_pattern and edit_pattern.has_permission('get', request, obj=obj) else None ) else: return None
python
def get_url_from_model_core(request, obj): """ Returns object URL from model core. """ from is_core.site import get_model_core model_core = get_model_core(obj.__class__) if model_core and hasattr(model_core, 'ui_patterns'): edit_pattern = model_core.ui_patterns.get('detail') return ( edit_pattern.get_url_string(request, obj=obj) if edit_pattern and edit_pattern.has_permission('get', request, obj=obj) else None ) else: return None
[ "def", "get_url_from_model_core", "(", "request", ",", "obj", ")", ":", "from", "is_core", ".", "site", "import", "get_model_core", "model_core", "=", "get_model_core", "(", "obj", ".", "__class__", ")", "if", "model_core", "and", "hasattr", "(", "model_core", ...
Returns object URL from model core.
[ "Returns", "object", "URL", "from", "model", "core", "." ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L284-L298
train
51,845
matllubos/django-is-core
is_core/utils/__init__.py
get_obj_url
def get_obj_url(request, obj): """ Returns object URL if current logged user has permissions to see the object """ if (is_callable(getattr(obj, 'get_absolute_url', None)) and (not hasattr(obj, 'can_see_edit_link') or (is_callable(getattr(obj, 'can_see_edit_link', None)) and obj.can_see_edit_link(request)))): return call_method_with_unknown_input(obj.get_absolute_url, request=request) else: return get_url_from_model_core(request, obj)
python
def get_obj_url(request, obj): """ Returns object URL if current logged user has permissions to see the object """ if (is_callable(getattr(obj, 'get_absolute_url', None)) and (not hasattr(obj, 'can_see_edit_link') or (is_callable(getattr(obj, 'can_see_edit_link', None)) and obj.can_see_edit_link(request)))): return call_method_with_unknown_input(obj.get_absolute_url, request=request) else: return get_url_from_model_core(request, obj)
[ "def", "get_obj_url", "(", "request", ",", "obj", ")", ":", "if", "(", "is_callable", "(", "getattr", "(", "obj", ",", "'get_absolute_url'", ",", "None", ")", ")", "and", "(", "not", "hasattr", "(", "obj", ",", "'can_see_edit_link'", ")", "or", "(", "i...
Returns object URL if current logged user has permissions to see the object
[ "Returns", "object", "URL", "if", "current", "logged", "user", "has", "permissions", "to", "see", "the", "object" ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L301-L310
train
51,846
matllubos/django-is-core
is_core/utils/__init__.py
get_link_or_none
def get_link_or_none(pattern_name, request, view_kwargs=None): """ Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL. If not None is returned. Args: pattern_name (str): slug which is used for view registratin to pattern request (django.http.request.HttpRequest): Django request object view_kwargs (dict): list of kwargs necessary for URL generator Returns: """ from is_core.patterns import reverse_pattern pattern = reverse_pattern(pattern_name) assert pattern is not None, 'Invalid pattern name {}'.format(pattern_name) if pattern.has_permission('get', request, view_kwargs=view_kwargs): return pattern.get_url_string(request, view_kwargs=view_kwargs) else: return None
python
def get_link_or_none(pattern_name, request, view_kwargs=None): """ Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL. If not None is returned. Args: pattern_name (str): slug which is used for view registratin to pattern request (django.http.request.HttpRequest): Django request object view_kwargs (dict): list of kwargs necessary for URL generator Returns: """ from is_core.patterns import reverse_pattern pattern = reverse_pattern(pattern_name) assert pattern is not None, 'Invalid pattern name {}'.format(pattern_name) if pattern.has_permission('get', request, view_kwargs=view_kwargs): return pattern.get_url_string(request, view_kwargs=view_kwargs) else: return None
[ "def", "get_link_or_none", "(", "pattern_name", ",", "request", ",", "view_kwargs", "=", "None", ")", ":", "from", "is_core", ".", "patterns", "import", "reverse_pattern", "pattern", "=", "reverse_pattern", "(", "pattern_name", ")", "assert", "pattern", "is", "n...
Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL. If not None is returned. Args: pattern_name (str): slug which is used for view registratin to pattern request (django.http.request.HttpRequest): Django request object view_kwargs (dict): list of kwargs necessary for URL generator Returns:
[ "Helper", "that", "generate", "URL", "prom", "pattern", "name", "and", "kwargs", "and", "check", "if", "current", "request", "has", "permission", "to", "open", "the", "URL", ".", "If", "not", "None", "is", "returned", "." ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L339-L360
train
51,847
inveniosoftware/invenio-iiif
invenio_iiif/handlers.py
protect_api
def protect_api(uuid=None, **kwargs): """Retrieve object and check permissions. Retrieve ObjectVersion of image being requested and check permission using the Invenio-Files-REST permission factory. """ bucket, version_id, key = uuid.split(':', 2) g.obj = ObjectResource.get_object(bucket, key, version_id) return g.obj
python
def protect_api(uuid=None, **kwargs): """Retrieve object and check permissions. Retrieve ObjectVersion of image being requested and check permission using the Invenio-Files-REST permission factory. """ bucket, version_id, key = uuid.split(':', 2) g.obj = ObjectResource.get_object(bucket, key, version_id) return g.obj
[ "def", "protect_api", "(", "uuid", "=", "None", ",", "*", "*", "kwargs", ")", ":", "bucket", ",", "version_id", ",", "key", "=", "uuid", ".", "split", "(", "':'", ",", "2", ")", "g", ".", "obj", "=", "ObjectResource", ".", "get_object", "(", "bucke...
Retrieve object and check permissions. Retrieve ObjectVersion of image being requested and check permission using the Invenio-Files-REST permission factory.
[ "Retrieve", "object", "and", "check", "permissions", "." ]
e4f2f93eaabdc8e2efea81c239ab76d481191959
https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/handlers.py#L29-L37
train
51,848
inveniosoftware/invenio-iiif
invenio_iiif/handlers.py
image_opener
def image_opener(key): """Handler to locate file based on key. :param key: A key encoded in the format "<bucket>:<version>:<object_key>". :returns: A file-like object. """ if hasattr(g, 'obj'): obj = g.obj else: obj = protect_api(key) fp = obj.file.storage().open('rb') # If ImageMagick with Wand is installed, extract first page # for PDF/text. if HAS_IMAGEMAGICK and obj.mimetype in ['application/pdf', 'text/plain']: first_page = Image(Image(fp).sequence[0]) tempfile_ = tempfile.TemporaryFile() with first_page.convert(format='png') as converted: converted.save(file=tempfile_) return tempfile_ return fp
python
def image_opener(key): """Handler to locate file based on key. :param key: A key encoded in the format "<bucket>:<version>:<object_key>". :returns: A file-like object. """ if hasattr(g, 'obj'): obj = g.obj else: obj = protect_api(key) fp = obj.file.storage().open('rb') # If ImageMagick with Wand is installed, extract first page # for PDF/text. if HAS_IMAGEMAGICK and obj.mimetype in ['application/pdf', 'text/plain']: first_page = Image(Image(fp).sequence[0]) tempfile_ = tempfile.TemporaryFile() with first_page.convert(format='png') as converted: converted.save(file=tempfile_) return tempfile_ return fp
[ "def", "image_opener", "(", "key", ")", ":", "if", "hasattr", "(", "g", ",", "'obj'", ")", ":", "obj", "=", "g", ".", "obj", "else", ":", "obj", "=", "protect_api", "(", "key", ")", "fp", "=", "obj", ".", "file", ".", "storage", "(", ")", ".", ...
Handler to locate file based on key. :param key: A key encoded in the format "<bucket>:<version>:<object_key>". :returns: A file-like object.
[ "Handler", "to", "locate", "file", "based", "on", "key", "." ]
e4f2f93eaabdc8e2efea81c239ab76d481191959
https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/handlers.py#L40-L61
train
51,849
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.tables
def tables(self): """The complete list of tables.""" # If we are on unix use mdbtools instead # if os.name == "posix": mdb_tables = sh.Command("mdb-tables") tables_list = mdb_tables('-1', self.path).split('\n') condition = lambda t: t and not t.startswith('MSys') return [t.lower() for t in tables_list if condition(t)] # Default case # return [table[2].lower() for table in self.own_cursor.tables() if not table[2].startswith('MSys')]
python
def tables(self): """The complete list of tables.""" # If we are on unix use mdbtools instead # if os.name == "posix": mdb_tables = sh.Command("mdb-tables") tables_list = mdb_tables('-1', self.path).split('\n') condition = lambda t: t and not t.startswith('MSys') return [t.lower() for t in tables_list if condition(t)] # Default case # return [table[2].lower() for table in self.own_cursor.tables() if not table[2].startswith('MSys')]
[ "def", "tables", "(", "self", ")", ":", "# If we are on unix use mdbtools instead #", "if", "os", ".", "name", "==", "\"posix\"", ":", "mdb_tables", "=", "sh", ".", "Command", "(", "\"mdb-tables\"", ")", "tables_list", "=", "mdb_tables", "(", "'-1'", ",", "sel...
The complete list of tables.
[ "The", "complete", "list", "of", "tables", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L84-L93
train
51,850
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.table_as_df
def table_as_df(self, table_name): """Return a table as a dataframe.""" self.table_must_exist(table_name) query = "SELECT * FROM `%s`" % table_name.lower() return pandas.read_sql(query, self.own_conn)
python
def table_as_df(self, table_name): """Return a table as a dataframe.""" self.table_must_exist(table_name) query = "SELECT * FROM `%s`" % table_name.lower() return pandas.read_sql(query, self.own_conn)
[ "def", "table_as_df", "(", "self", ",", "table_name", ")", ":", "self", ".", "table_must_exist", "(", "table_name", ")", "query", "=", "\"SELECT * FROM `%s`\"", "%", "table_name", ".", "lower", "(", ")", "return", "pandas", ".", "read_sql", "(", "query", ","...
Return a table as a dataframe.
[ "Return", "a", "table", "as", "a", "dataframe", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L134-L138
train
51,851
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.count_rows
def count_rows(self, table_name): """Return the number of entries in a table by counting them.""" self.table_must_exist(table_name) query = "SELECT COUNT (*) FROM `%s`" % table_name.lower() self.own_cursor.execute(query) return int(self.own_cursor.fetchone()[0])
python
def count_rows(self, table_name): """Return the number of entries in a table by counting them.""" self.table_must_exist(table_name) query = "SELECT COUNT (*) FROM `%s`" % table_name.lower() self.own_cursor.execute(query) return int(self.own_cursor.fetchone()[0])
[ "def", "count_rows", "(", "self", ",", "table_name", ")", ":", "self", ".", "table_must_exist", "(", "table_name", ")", "query", "=", "\"SELECT COUNT (*) FROM `%s`\"", "%", "table_name", ".", "lower", "(", ")", "self", ".", "own_cursor", ".", "execute", "(", ...
Return the number of entries in a table by counting them.
[ "Return", "the", "number", "of", "entries", "in", "a", "table", "by", "counting", "them", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L144-L149
train
51,852
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.tables_with_counts
def tables_with_counts(self): """Return the number of entries in all table.""" table_to_count = lambda t: self.count_rows(t) return zip(self.tables, map(table_to_count, self.tables))
python
def tables_with_counts(self): """Return the number of entries in all table.""" table_to_count = lambda t: self.count_rows(t) return zip(self.tables, map(table_to_count, self.tables))
[ "def", "tables_with_counts", "(", "self", ")", ":", "table_to_count", "=", "lambda", "t", ":", "self", ".", "count_rows", "(", "t", ")", "return", "zip", "(", "self", ".", "tables", ",", "map", "(", "table_to_count", ",", "self", ".", "tables", ")", ")...
Return the number of entries in all table.
[ "Return", "the", "number", "of", "entries", "in", "all", "table", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L155-L158
train
51,853
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.convert_to_sqlite
def convert_to_sqlite(self, destination=None, method="shell", progress=False): """Who wants to use Access when you can deal with SQLite databases instead?""" # Display progress bar # if progress: progress = tqdm.tqdm else: progress = lambda x:x # Default path # if destination is None: destination = self.replace_extension('sqlite') # Delete if it exists # destination.remove() # Method with shell and a temp file # if method == 'shell': return self.sqlite_by_shell(destination) # Method without a temp file # if method == 'object': return self.sqlite_by_object(destination, progress) # Method with dataframe # if method == 'dataframe': return self.sqlite_by_df(destination, progress)
python
def convert_to_sqlite(self, destination=None, method="shell", progress=False): """Who wants to use Access when you can deal with SQLite databases instead?""" # Display progress bar # if progress: progress = tqdm.tqdm else: progress = lambda x:x # Default path # if destination is None: destination = self.replace_extension('sqlite') # Delete if it exists # destination.remove() # Method with shell and a temp file # if method == 'shell': return self.sqlite_by_shell(destination) # Method without a temp file # if method == 'object': return self.sqlite_by_object(destination, progress) # Method with dataframe # if method == 'dataframe': return self.sqlite_by_df(destination, progress)
[ "def", "convert_to_sqlite", "(", "self", ",", "destination", "=", "None", ",", "method", "=", "\"shell\"", ",", "progress", "=", "False", ")", ":", "# Display progress bar #", "if", "progress", ":", "progress", "=", "tqdm", ".", "tqdm", "else", ":", "progres...
Who wants to use Access when you can deal with SQLite databases instead?
[ "Who", "wants", "to", "use", "Access", "when", "you", "can", "deal", "with", "SQLite", "databases", "instead?" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L167-L181
train
51,854
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.sqlite_by_shell
def sqlite_by_shell(self, destination): """Method with shell and a temp file. This is hopefully fast.""" script_path = new_temp_path() self.sqlite_dump_shell(script_path) shell_output('sqlite3 -bail -init "%s" "%s" .quit' % (script, destination)) script.remove()
python
def sqlite_by_shell(self, destination): """Method with shell and a temp file. This is hopefully fast.""" script_path = new_temp_path() self.sqlite_dump_shell(script_path) shell_output('sqlite3 -bail -init "%s" "%s" .quit' % (script, destination)) script.remove()
[ "def", "sqlite_by_shell", "(", "self", ",", "destination", ")", ":", "script_path", "=", "new_temp_path", "(", ")", "self", ".", "sqlite_dump_shell", "(", "script_path", ")", "shell_output", "(", "'sqlite3 -bail -init \"%s\" \"%s\" .quit'", "%", "(", "script", ",", ...
Method with shell and a temp file. This is hopefully fast.
[ "Method", "with", "shell", "and", "a", "temp", "file", ".", "This", "is", "hopefully", "fast", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L183-L188
train
51,855
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.sqlite_by_object
def sqlite_by_object(self, destination, progress): """This is probably not very fast.""" db = SQLiteDatabase(destination) db.create() for script in self.sqlite_dump_string(progress): db.cursor.executescript(script) db.close()
python
def sqlite_by_object(self, destination, progress): """This is probably not very fast.""" db = SQLiteDatabase(destination) db.create() for script in self.sqlite_dump_string(progress): db.cursor.executescript(script) db.close()
[ "def", "sqlite_by_object", "(", "self", ",", "destination", ",", "progress", ")", ":", "db", "=", "SQLiteDatabase", "(", "destination", ")", "db", ".", "create", "(", ")", "for", "script", "in", "self", ".", "sqlite_dump_string", "(", "progress", ")", ":",...
This is probably not very fast.
[ "This", "is", "probably", "not", "very", "fast", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L190-L195
train
51,856
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.sqlite_by_df
def sqlite_by_df(self, destination, progress): """Is this fast?""" db = SQLiteDatabase(destination) db.create() for table in progress(self.real_tables): self[table].to_sql(table, con=db.connection) db.close()
python
def sqlite_by_df(self, destination, progress): """Is this fast?""" db = SQLiteDatabase(destination) db.create() for table in progress(self.real_tables): self[table].to_sql(table, con=db.connection) db.close()
[ "def", "sqlite_by_df", "(", "self", ",", "destination", ",", "progress", ")", ":", "db", "=", "SQLiteDatabase", "(", "destination", ")", "db", ".", "create", "(", ")", "for", "table", "in", "progress", "(", "self", ".", "real_tables", ")", ":", "self", ...
Is this fast?
[ "Is", "this", "fast?" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L197-L202
train
51,857
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.sqlite_dump_string
def sqlite_dump_string(self, progress): """Generate a text dump compatible with SQLite. By yielding every table one by one as a byte string.""" # First the schema # mdb_schema = sh.Command("mdb-schema") yield mdb_schema(self.path, "sqlite").encode('utf8') # Start a transaction, speeds things up when importing # yield "BEGIN TRANSACTION;\n" # Then export every table # mdb_export = sh.Command("mdb-export") for table in progress(self.tables): yield mdb_export('-I', 'sqlite', self.path, table).encode('utf8') # End the transaction yield "END TRANSACTION;\n"
python
def sqlite_dump_string(self, progress): """Generate a text dump compatible with SQLite. By yielding every table one by one as a byte string.""" # First the schema # mdb_schema = sh.Command("mdb-schema") yield mdb_schema(self.path, "sqlite").encode('utf8') # Start a transaction, speeds things up when importing # yield "BEGIN TRANSACTION;\n" # Then export every table # mdb_export = sh.Command("mdb-export") for table in progress(self.tables): yield mdb_export('-I', 'sqlite', self.path, table).encode('utf8') # End the transaction yield "END TRANSACTION;\n"
[ "def", "sqlite_dump_string", "(", "self", ",", "progress", ")", ":", "# First the schema #", "mdb_schema", "=", "sh", ".", "Command", "(", "\"mdb-schema\"", ")", "yield", "mdb_schema", "(", "self", ".", "path", ",", "\"sqlite\"", ")", ".", "encode", "(", "'u...
Generate a text dump compatible with SQLite. By yielding every table one by one as a byte string.
[ "Generate", "a", "text", "dump", "compatible", "with", "SQLite", ".", "By", "yielding", "every", "table", "one", "by", "one", "as", "a", "byte", "string", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L218-L231
train
51,858
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.import_table
def import_table(self, source, table_name): """Copy a table from another Access database to this one. Requires that you have mdbtools command line executables installed in a Windows Subsystem for Linux environment.""" # Run commands # wsl = sh.Command("wsl.exe") table_schema = wsl("-e", "mdb-schema", "-T", table_name, source.wsl_style, "access") table_contents = wsl("-e", "mdb-export", "-I", "access", source.wsl_style, table_name) # Filter # table_schema = ' '.join(l for l in table_schema.split('\n') if not l.startswith("--")) # Execute statements # self.cursor.execute(str(table_schema)) self.cursor.execute(str(table_contents))
python
def import_table(self, source, table_name): """Copy a table from another Access database to this one. Requires that you have mdbtools command line executables installed in a Windows Subsystem for Linux environment.""" # Run commands # wsl = sh.Command("wsl.exe") table_schema = wsl("-e", "mdb-schema", "-T", table_name, source.wsl_style, "access") table_contents = wsl("-e", "mdb-export", "-I", "access", source.wsl_style, table_name) # Filter # table_schema = ' '.join(l for l in table_schema.split('\n') if not l.startswith("--")) # Execute statements # self.cursor.execute(str(table_schema)) self.cursor.execute(str(table_contents))
[ "def", "import_table", "(", "self", ",", "source", ",", "table_name", ")", ":", "# Run commands #", "wsl", "=", "sh", ".", "Command", "(", "\"wsl.exe\"", ")", "table_schema", "=", "wsl", "(", "\"-e\"", ",", "\"mdb-schema\"", ",", "\"-T\"", ",", "table_name",...
Copy a table from another Access database to this one. Requires that you have mdbtools command line executables installed in a Windows Subsystem for Linux environment.
[ "Copy", "a", "table", "from", "another", "Access", "database", "to", "this", "one", ".", "Requires", "that", "you", "have", "mdbtools", "command", "line", "executables", "installed", "in", "a", "Windows", "Subsystem", "for", "Linux", "environment", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L234-L246
train
51,859
xapple/plumbing
plumbing/databases/access_database.py
AccessDatabase.create
def create(cls, destination): """Create a new empty MDB at destination.""" mdb_gz_b64 = """\ H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+ qKgIIHL8Znb39u72znWJiWP3+9l473fzm/nNY3cdf2fmbBJEPdO9E+nebLq+fWC6vrWZOImen9D7 9sR+vPPNE0PZxo/TE5879mj+yNc3/OzAD2bXv3DmV9/o/8PZnxxr+/fDL2w79ulzN7e+/sS/zvzz w3+N1z28p3PTfQ3nfn/m2YmeFS2no89uWnvqwO5HUvd/5Phr938tes3j/zm5+qT41J8/P/iZx87/ +qHrjgyduubG1t/+7eWB2XztTNuT+1clZt9c2/e7HRGizevWEwAAAAAAAACAhUEIwvE+PoRIO8K7 FzT6obPPwTMBAAAAAAAAAABcfpzPXwya+Ispo1xlEO2KEEX9eaGyWnrqyKQ60tQ0AcNZRcR1RYuy +XZCxoqRzmaMI6cKGRJuJVrIEZUOQ9UrHStUYpyzKkdNmSPFDkM6aguhXMdVHCMuHXE2Suu4IFQJ l6CErNWUDouDlbdKOZIcrKLD4S5WdNhqIEodqlVaofKgVTHpiBQ6uLG0uaKsuYbf3IS8BmV1qFAm j1Z5Hbp06GWDKC+DTS00SRN8DFA/TXNfW6mXX3upj7+mOHWllzLAObN8du0gdSdlKO3ZcWqjMbaH uOQqtidViRF+P0HbOH2c3xm0lfMb1EH7uHZ5vp32c+ks+5PqfSeXS9NejjTAvZQpd7J3kuuJFqLE qYvuVa3Ocqk7OVXWNMFxZPRVtJ1zSXuCBrlkh+rjEF1Zlt5Dw6qN0xx5Bx3gGgbowVo56EIjkc9T xX9Jdd+5PKDOD6q3VQvwv7qiZ8st419cdYHlo6iuriF8X4HA590AsodXhvrsj0yMDPnAuI+ZvOrq 1o7K51Hdy7a8cdXNm5AedbfG5W3j3lOybxFZKb6zAgAAAAAAsNzQxAlbvnYJV3VcUU3/S2luBIKF ha+IlWp+wxW4IiRXRSXxKeNU1eOxUuUbSOIINbEM7WT506ZE3LASgCOeYJWCMcnCsI/u8eSsFEYR lnlbWa6+u0jTYqSkvuQL9G5CLFwTRBMAAAAAAAAAgMtW/79lyVdLKxW7oqDF3bXOniib0UD/m/xq loWqvFwt3DX/mrLNALIu3V35NkpK1JDmL+2XOmr9pf1gKiFY4I672wc0mveaf6zaenyKmljPT6t5 hT7a6y13y0XqjFpwneJjRC0oRwvL3eUL2fHCcuyGIntjhTkDuZCd5Vc5j+HNUMyx+myYcpHW5YG5 ZijUdbg2VFu4ZzzcHFM3seQLAAAAAAAAAMtc//9S6cm1emX97ytK1v81rHelhtfVfAFnseZXRdV9 Ad7+dhGS5kbl3eqe/K8pU/nnYwX5X2VeoLbCZwHi7txD6aTELabnoLJ5AfPFC8JmFd3Pun+MlfM4 q/846/4s62i5+8Dmc7EvSVN0UG2tL00p1uPXqZTt/G5QqX+5lbufz+mSctVzFce6upBrTG3Fd+cn pmiYrUyw8+GNfL4hn8/k83qZrVlyGzgPeqbhjcOqx7KMEZRpU/MPQ+rsldEtuYm8vExkznoMS+6b KC5TZRt8wVf4xEkFX4V5D/X2vYz1/EcR8yMAAAAAAACAJY0Qf/d3vLPUlb//b4Nzzv6W3Wevtl+1 vmxts2LWTxOHErcm3jGfMUfNG0yMGQAAAAAAeJ/8rLwAMXIYRgCARFv8IIaYtKpGqCdqlN/2kupD /ob67qXhsi0lDh2Vp6728faO9tHuUflfWJ1wE0e6724f35XuG71r16Dr0FwH573by6rKi0N7RveN tnd6aTVBWrpjd3fnuJtsBMnDk90ju7zckSA5XGGtdGrK2dWhUnRcMgAAAAAAAAD4v2CIV6vqf82I Jusbcwsy7wkWSf/n1JQNq/Oc+uQGq/ecmsphYZ6Tn6XwRLjwxb7mTxDoakLgURUFshwAAAAAAAAA ljpCrHZ8W/f2/2NUAAAAAAAAAAAAhXH5RLm4IIbotqot7hbW/0MGWCp46/+pgpHwjZS3IyAlfMPy tgakNN+wfcPxNgukdN9I+kadt30gZfhGjW+s8I2V3s6CVNTbWZCK+Eatb3zAN1Z5mw5SMd+I+wZ+ +QQAAAAAAAAA/K8IcdT27Zqi3/+HkQEAAAAAAAAAsGgkMQQLjSHqbQPDAAAAAAAAAAAALGuw/g8A AAAAAAAA4DJUqwsQI7cQDWlcLiMq1/9rcGMBAAAAAAAAAADLGuh/AAAAAAAAAAAA+h8AAAAAAAAA AABLHyHusDTPjtLzTtoxnRftUftqe8YatDA+AAAAAAAAAPDeqJN/KVt+et0R9PYnzz7W8PrZRv+V HblO6qEDNEXbaYDGqJemaYQmaYJThtnK8Gvzb1opfDRTPZmUlxUY86qgm/ZyFVkOOqCC3kLhoyEI qs8raBO10O0q3EYKH+uDcNq8wnVRH93D7evnYZhHG5kkB3a0OYO2ctCWV9ZR+FhT0l2HCzl6xVBz XZyPUvi4taTjcwRuVUF7uYW9HMy9MJspfGwMAoo5A+5Qwca8UHN2WogeU/fu0ito1vmjM+M85zzp fNG5zxl2djrNzk3O9+0m+yWrx2q0fpH4buJ4Yk3ig4lvmkfxx9gBAAAAAAC4OAylQfJ5h5pfSVCc f853gqSmWPSZux6xjUznltH2HT/flNu7++0NZ7/07cg/vnPbVu30y6d/NLvlabPh+j81v/Xc5g9l 1h2f+epn9+VPdN90OHHvU50fm94y/ZXvWQ/tP/yJG/NH3llz8A79tlNPG72DHSePHdzz2s3XPzVj vzSUvSHjVys1Rv5CSUv8pEvcEqkbV/KX35JaQ+npikmRS9o4rtYIt8RYnJa4Ou6SV6stTm+l7rcX q9qSy+23pCVIcgV/SZKuJj5CSRc4Y/PpkiesLJcI53J37NvFuQzv4peGL0/SypP+C+45xVAAMAEA """ pristine = StringIO() pristine.write(base64.b64decode(mdb_gz_b64)) pristine.seek(0) pristine = gzip.GzipFile(fileobj=pristine, mode='rb') with open(destination, 'wb') as handle: shutil.copyfileobj(pristine, handle) return cls(destination)
python
def create(cls, destination): """Create a new empty MDB at destination.""" mdb_gz_b64 = """\ H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+ qKgIIHL8Znb39u72znWJiWP3+9l473fzm/nNY3cdf2fmbBJEPdO9E+nebLq+fWC6vrWZOImen9D7 9sR+vPPNE0PZxo/TE5879mj+yNc3/OzAD2bXv3DmV9/o/8PZnxxr+/fDL2w79ulzN7e+/sS/zvzz w3+N1z28p3PTfQ3nfn/m2YmeFS2no89uWnvqwO5HUvd/5Phr938tes3j/zm5+qT41J8/P/iZx87/ +qHrjgyduubG1t/+7eWB2XztTNuT+1clZt9c2/e7HRGizevWEwAAAAAAAACAhUEIwvE+PoRIO8K7 FzT6obPPwTMBAAAAAAAAAABcfpzPXwya+Ispo1xlEO2KEEX9eaGyWnrqyKQ60tQ0AcNZRcR1RYuy +XZCxoqRzmaMI6cKGRJuJVrIEZUOQ9UrHStUYpyzKkdNmSPFDkM6aguhXMdVHCMuHXE2Suu4IFQJ l6CErNWUDouDlbdKOZIcrKLD4S5WdNhqIEodqlVaofKgVTHpiBQ6uLG0uaKsuYbf3IS8BmV1qFAm j1Z5Hbp06GWDKC+DTS00SRN8DFA/TXNfW6mXX3upj7+mOHWllzLAObN8du0gdSdlKO3ZcWqjMbaH uOQqtidViRF+P0HbOH2c3xm0lfMb1EH7uHZ5vp32c+ks+5PqfSeXS9NejjTAvZQpd7J3kuuJFqLE qYvuVa3Ocqk7OVXWNMFxZPRVtJ1zSXuCBrlkh+rjEF1Zlt5Dw6qN0xx5Bx3gGgbowVo56EIjkc9T xX9Jdd+5PKDOD6q3VQvwv7qiZ8st419cdYHlo6iuriF8X4HA590AsodXhvrsj0yMDPnAuI+ZvOrq 1o7K51Hdy7a8cdXNm5AedbfG5W3j3lOybxFZKb6zAgAAAAAAsNzQxAlbvnYJV3VcUU3/S2luBIKF ha+IlWp+wxW4IiRXRSXxKeNU1eOxUuUbSOIINbEM7WT506ZE3LASgCOeYJWCMcnCsI/u8eSsFEYR lnlbWa6+u0jTYqSkvuQL9G5CLFwTRBMAAAAAAAAAgMtW/79lyVdLKxW7oqDF3bXOniib0UD/m/xq loWqvFwt3DX/mrLNALIu3V35NkpK1JDmL+2XOmr9pf1gKiFY4I672wc0mveaf6zaenyKmljPT6t5 hT7a6y13y0XqjFpwneJjRC0oRwvL3eUL2fHCcuyGIntjhTkDuZCd5Vc5j+HNUMyx+myYcpHW5YG5 ZijUdbg2VFu4ZzzcHFM3seQLAAAAAAAAAMtc//9S6cm1emX97ytK1v81rHelhtfVfAFnseZXRdV9 Ad7+dhGS5kbl3eqe/K8pU/nnYwX5X2VeoLbCZwHi7txD6aTELabnoLJ5AfPFC8JmFd3Pun+MlfM4 q/846/4s62i5+8Dmc7EvSVN0UG2tL00p1uPXqZTt/G5QqX+5lbufz+mSctVzFce6upBrTG3Fd+cn pmiYrUyw8+GNfL4hn8/k83qZrVlyGzgPeqbhjcOqx7KMEZRpU/MPQ+rsldEtuYm8vExkznoMS+6b KC5TZRt8wVf4xEkFX4V5D/X2vYz1/EcR8yMAAAAAAACAJY0Qf/d3vLPUlb//b4Nzzv6W3Wevtl+1 vmxts2LWTxOHErcm3jGfMUfNG0yMGQAAAAAAeJ/8rLwAMXIYRgCARFv8IIaYtKpGqCdqlN/2kupD /ob67qXhsi0lDh2Vp6728faO9tHuUflfWJ1wE0e6724f35XuG71r16Dr0FwH573by6rKi0N7RveN tnd6aTVBWrpjd3fnuJtsBMnDk90ju7zckSA5XGGtdGrK2dWhUnRcMgAAAAAAAAD4v2CIV6vqf82I Jusbcwsy7wkWSf/n1JQNq/Oc+uQGq/ecmsphYZ6Tn6XwRLjwxb7mTxDoakLgURUFshwAAAAAAAAA ljpCrHZ8W/f2/2NUAAAAAAAAAAAAhXH5RLm4IIbotqot7hbW/0MGWCp46/+pgpHwjZS3IyAlfMPy tgakNN+wfcPxNgukdN9I+kadt30gZfhGjW+s8I2V3s6CVNTbWZCK+Eatb3zAN1Z5mw5SMd+I+wZ+ +QQAAAAAAAAA/K8IcdT27Zqi3/+HkQEAAAAAAAAAsGgkMQQLjSHqbQPDAAAAAAAAAAAALGuw/g8A AAAAAAAA4DJUqwsQI7cQDWlcLiMq1/9rcGMBAAAAAAAAAADLGuh/AAAAAAAAAAAA+h8AAAAAAAAA AABLHyHusDTPjtLzTtoxnRftUftqe8YatDA+AAAAAAAAAPDeqJN/KVt+et0R9PYnzz7W8PrZRv+V HblO6qEDNEXbaYDGqJemaYQmaYJThtnK8Gvzb1opfDRTPZmUlxUY86qgm/ZyFVkOOqCC3kLhoyEI qs8raBO10O0q3EYKH+uDcNq8wnVRH93D7evnYZhHG5kkB3a0OYO2ctCWV9ZR+FhT0l2HCzl6xVBz XZyPUvi4taTjcwRuVUF7uYW9HMy9MJspfGwMAoo5A+5Qwca8UHN2WogeU/fu0ito1vmjM+M85zzp fNG5zxl2djrNzk3O9+0m+yWrx2q0fpH4buJ4Yk3ig4lvmkfxx9gBAAAAAAC4OAylQfJ5h5pfSVCc f853gqSmWPSZux6xjUznltH2HT/flNu7++0NZ7/07cg/vnPbVu30y6d/NLvlabPh+j81v/Xc5g9l 1h2f+epn9+VPdN90OHHvU50fm94y/ZXvWQ/tP/yJG/NH3llz8A79tlNPG72DHSePHdzz2s3XPzVj vzSUvSHjVys1Rv5CSUv8pEvcEqkbV/KX35JaQ+npikmRS9o4rtYIt8RYnJa4Ou6SV6stTm+l7rcX q9qSy+23pCVIcgV/SZKuJj5CSRc4Y/PpkiesLJcI53J37NvFuQzv4peGL0/SypP+C+45xVAAMAEA """ pristine = StringIO() pristine.write(base64.b64decode(mdb_gz_b64)) pristine.seek(0) pristine = gzip.GzipFile(fileobj=pristine, mode='rb') with open(destination, 'wb') as handle: shutil.copyfileobj(pristine, handle) return cls(destination)
[ "def", "create", "(", "cls", ",", "destination", ")", ":", "mdb_gz_b64", "=", "\"\"\"\\\n H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a\n jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+\n qKgIIHL8Znb39u72znWJiWP3+9l...
Create a new empty MDB at destination.
[ "Create", "a", "new", "empty", "MDB", "at", "destination", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L250-L299
train
51,860
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.tables
def tables(self): """The complete list of SQL tables.""" self.own_connection.row_factory = sqlite3.Row self.own_cursor.execute('SELECT name from sqlite_master where type="table";') result = [x[0].encode('ascii') for x in self.own_cursor.fetchall()] self.own_connection.row_factory = self.factory return result
python
def tables(self): """The complete list of SQL tables.""" self.own_connection.row_factory = sqlite3.Row self.own_cursor.execute('SELECT name from sqlite_master where type="table";') result = [x[0].encode('ascii') for x in self.own_cursor.fetchall()] self.own_connection.row_factory = self.factory return result
[ "def", "tables", "(", "self", ")", ":", "self", ".", "own_connection", ".", "row_factory", "=", "sqlite3", ".", "Row", "self", ".", "own_cursor", ".", "execute", "(", "'SELECT name from sqlite_master where type=\"table\";'", ")", "result", "=", "[", "x", "[", ...
The complete list of SQL tables.
[ "The", "complete", "list", "of", "SQL", "tables", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L100-L106
train
51,861
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.new_connection
def new_connection(self): """Make a new connection.""" if not self.prepared: self.prepare() con = sqlite3.connect(self.path, isolation_level=self.isolation) con.row_factory = self.factory if self.text_fact: con.text_factory = self.text_fact return con
python
def new_connection(self): """Make a new connection.""" if not self.prepared: self.prepare() con = sqlite3.connect(self.path, isolation_level=self.isolation) con.row_factory = self.factory if self.text_fact: con.text_factory = self.text_fact return con
[ "def", "new_connection", "(", "self", ")", ":", "if", "not", "self", ".", "prepared", ":", "self", ".", "prepare", "(", ")", "con", "=", "sqlite3", ".", "connect", "(", "self", ".", "path", ",", "isolation_level", "=", "self", ".", "isolation", ")", ...
Make a new connection.
[ "Make", "a", "new", "connection", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L134-L140
train
51,862
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.prepare
def prepare(self): """Check that the file exists, optionally downloads it. Checks that the file is indeed an SQLite3 database. Optionally check the MD5.""" if not os.path.exists(self.path): if self.retrieve: print("Downloading SQLite3 database...") download_from_url(self.retrieve, self.path, progress=True) else: raise Exception("The file '" + self.path + "' does not exist.") self.check_format() if self.known_md5: assert self.known_md5 == self.md5 self.prepared = True
python
def prepare(self): """Check that the file exists, optionally downloads it. Checks that the file is indeed an SQLite3 database. Optionally check the MD5.""" if not os.path.exists(self.path): if self.retrieve: print("Downloading SQLite3 database...") download_from_url(self.retrieve, self.path, progress=True) else: raise Exception("The file '" + self.path + "' does not exist.") self.check_format() if self.known_md5: assert self.known_md5 == self.md5 self.prepared = True
[ "def", "prepare", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "path", ")", ":", "if", "self", ".", "retrieve", ":", "print", "(", "\"Downloading SQLite3 database...\"", ")", "download_from_url", "(", "self", "....
Check that the file exists, optionally downloads it. Checks that the file is indeed an SQLite3 database. Optionally check the MD5.
[ "Check", "that", "the", "file", "exists", "optionally", "downloads", "it", ".", "Checks", "that", "the", "file", "is", "indeed", "an", "SQLite3", "database", ".", "Optionally", "check", "the", "MD5", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L142-L153
train
51,863
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.create
def create(self, columns=None, type_map=None, overwrite=False): """Create a new database with a certain schema.""" # Check already exists # if self.count_bytes > 0: if overwrite: self.remove() else: raise Exception("File exists already at '%s'" % self) # If we want it empty # if columns is None: self.touch() # Make the table # else: self.add_table(self.main_table, columns=columns, type_map=type_map)
python
def create(self, columns=None, type_map=None, overwrite=False): """Create a new database with a certain schema.""" # Check already exists # if self.count_bytes > 0: if overwrite: self.remove() else: raise Exception("File exists already at '%s'" % self) # If we want it empty # if columns is None: self.touch() # Make the table # else: self.add_table(self.main_table, columns=columns, type_map=type_map)
[ "def", "create", "(", "self", ",", "columns", "=", "None", ",", "type_map", "=", "None", ",", "overwrite", "=", "False", ")", ":", "# Check already exists #", "if", "self", ".", "count_bytes", ">", "0", ":", "if", "overwrite", ":", "self", ".", "remove",...
Create a new database with a certain schema.
[ "Create", "a", "new", "database", "with", "a", "certain", "schema", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L161-L172
train
51,864
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.get_columns_of_table
def get_columns_of_table(self, table=None): """Return the list of columns for a particular table by querying the SQL for the complete list of column names.""" # Check the table exists # if table is None: table = self.main_table if not table in self.tables: return [] # A PRAGMA statement will implicitly issue a commit, don't use # self.own_cursor.execute('SELECT * from "%s" LIMIT 1;' % table) columns = [x[0] for x in self.own_cursor.description] self.cursor.fetchall() return columns
python
def get_columns_of_table(self, table=None): """Return the list of columns for a particular table by querying the SQL for the complete list of column names.""" # Check the table exists # if table is None: table = self.main_table if not table in self.tables: return [] # A PRAGMA statement will implicitly issue a commit, don't use # self.own_cursor.execute('SELECT * from "%s" LIMIT 1;' % table) columns = [x[0] for x in self.own_cursor.description] self.cursor.fetchall() return columns
[ "def", "get_columns_of_table", "(", "self", ",", "table", "=", "None", ")", ":", "# Check the table exists #", "if", "table", "is", "None", ":", "table", "=", "self", ".", "main_table", "if", "not", "table", "in", "self", ".", "tables", ":", "return", "[",...
Return the list of columns for a particular table by querying the SQL for the complete list of column names.
[ "Return", "the", "list", "of", "columns", "for", "a", "particular", "table", "by", "querying", "the", "SQL", "for", "the", "complete", "list", "of", "column", "names", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L191-L201
train
51,865
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.count_entries
def count_entries(self, table=None): """How many rows in a table.""" if table is None: table = self.main_table self.own_cursor.execute('SELECT COUNT(1) FROM "%s";' % table) return int(self.own_cursor.fetchone()[0])
python
def count_entries(self, table=None): """How many rows in a table.""" if table is None: table = self.main_table self.own_cursor.execute('SELECT COUNT(1) FROM "%s";' % table) return int(self.own_cursor.fetchone()[0])
[ "def", "count_entries", "(", "self", ",", "table", "=", "None", ")", ":", "if", "table", "is", "None", ":", "table", "=", "self", ".", "main_table", "self", ".", "own_cursor", ".", "execute", "(", "'SELECT COUNT(1) FROM \"%s\";'", "%", "table", ")", "retur...
How many rows in a table.
[ "How", "many", "rows", "in", "a", "table", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L260-L264
train
51,866
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.get_first
def get_first(self, table=None): """Just the first entry.""" if table is None: table = self.main_table query = 'SELECT * FROM "%s" LIMIT 1;' % table return self.own_cursor.execute(query).fetchone()
python
def get_first(self, table=None): """Just the first entry.""" if table is None: table = self.main_table query = 'SELECT * FROM "%s" LIMIT 1;' % table return self.own_cursor.execute(query).fetchone()
[ "def", "get_first", "(", "self", ",", "table", "=", "None", ")", ":", "if", "table", "is", "None", ":", "table", "=", "self", ".", "main_table", "query", "=", "'SELECT * FROM \"%s\" LIMIT 1;'", "%", "table", "return", "self", ".", "own_cursor", ".", "execu...
Just the first entry.
[ "Just", "the", "first", "entry", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L277-L281
train
51,867
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.get_last
def get_last(self, table=None): """Just the last entry.""" if table is None: table = self.main_table query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table return self.own_cursor.execute(query).fetchone()
python
def get_last(self, table=None): """Just the last entry.""" if table is None: table = self.main_table query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table return self.own_cursor.execute(query).fetchone()
[ "def", "get_last", "(", "self", ",", "table", "=", "None", ")", ":", "if", "table", "is", "None", ":", "table", "=", "self", ".", "main_table", "query", "=", "'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;'", "%", "table", "return", "self", ".", "own_curso...
Just the last entry.
[ "Just", "the", "last", "entry", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L283-L287
train
51,868
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.get_number
def get_number(self, num, table=None): """Get a specific entry by its number.""" if table is None: table = self.main_table self.own_cursor.execute('SELECT * from "%s" LIMIT 1 OFFSET %i;' % (self.main_table, num)) return self.own_cursor.fetchone()
python
def get_number(self, num, table=None): """Get a specific entry by its number.""" if table is None: table = self.main_table self.own_cursor.execute('SELECT * from "%s" LIMIT 1 OFFSET %i;' % (self.main_table, num)) return self.own_cursor.fetchone()
[ "def", "get_number", "(", "self", ",", "num", ",", "table", "=", "None", ")", ":", "if", "table", "is", "None", ":", "table", "=", "self", ".", "main_table", "self", ".", "own_cursor", ".", "execute", "(", "'SELECT * from \"%s\" LIMIT 1 OFFSET %i;'", "%", ...
Get a specific entry by its number.
[ "Get", "a", "specific", "entry", "by", "its", "number", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L289-L293
train
51,869
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.get_entry
def get_entry(self, key, column=None, table=None): """Get a specific entry.""" if table is None: table = self.main_table if column is None: column = "id" if isinstance(key, basestring): key = key.replace("'","''") query = 'SELECT * from "%s" where "%s"=="%s" LIMIT 1;' query = query % (table, column, key) self.own_cursor.execute(query) return self.own_cursor.fetchone()
python
def get_entry(self, key, column=None, table=None): """Get a specific entry.""" if table is None: table = self.main_table if column is None: column = "id" if isinstance(key, basestring): key = key.replace("'","''") query = 'SELECT * from "%s" where "%s"=="%s" LIMIT 1;' query = query % (table, column, key) self.own_cursor.execute(query) return self.own_cursor.fetchone()
[ "def", "get_entry", "(", "self", ",", "key", ",", "column", "=", "None", ",", "table", "=", "None", ")", ":", "if", "table", "is", "None", ":", "table", "=", "self", ".", "main_table", "if", "column", "is", "None", ":", "column", "=", "\"id\"", "if...
Get a specific entry.
[ "Get", "a", "specific", "entry", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L296-L304
train
51,870
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.get_and_order
def get_and_order(self, ids, column=None, table=None): """Get specific entries and order them in the same way.""" command = """ SELECT rowid, * from "data" WHERE rowid in (%s) ORDER BY CASE rowid %s END; """ ordered = ','.join(map(str,ids)) rowids = '\n'.join("WHEN '%s' THEN %s" % (row,i) for i,row in enumerate(ids)) command = command % (ordered, rowids)
python
def get_and_order(self, ids, column=None, table=None): """Get specific entries and order them in the same way.""" command = """ SELECT rowid, * from "data" WHERE rowid in (%s) ORDER BY CASE rowid %s END; """ ordered = ','.join(map(str,ids)) rowids = '\n'.join("WHEN '%s' THEN %s" % (row,i) for i,row in enumerate(ids)) command = command % (ordered, rowids)
[ "def", "get_and_order", "(", "self", ",", "ids", ",", "column", "=", "None", ",", "table", "=", "None", ")", ":", "command", "=", "\"\"\"\n SELECT rowid, * from \"data\"\n WHERE rowid in (%s)\n ORDER BY CASE rowid\n %s\n END;\n \"\"\"", ...
Get specific entries and order them in the same way.
[ "Get", "specific", "entries", "and", "order", "them", "in", "the", "same", "way", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L334-L345
train
51,871
xapple/plumbing
plumbing/databases/sqlite_database.py
SQLiteDatabase.import_table
def import_table(self, source, table_name): """Copy a table from another SQLite database to this one.""" query = "SELECT * FROM `%s`" % table_name.lower() df = pandas.read_sql(query, source.connection) df.to_sql(table_name, con=self.own_connection)
python
def import_table(self, source, table_name): """Copy a table from another SQLite database to this one.""" query = "SELECT * FROM `%s`" % table_name.lower() df = pandas.read_sql(query, source.connection) df.to_sql(table_name, con=self.own_connection)
[ "def", "import_table", "(", "self", ",", "source", ",", "table_name", ")", ":", "query", "=", "\"SELECT * FROM `%s`\"", "%", "table_name", ".", "lower", "(", ")", "df", "=", "pandas", ".", "read_sql", "(", "query", ",", "source", ".", "connection", ")", ...
Copy a table from another SQLite database to this one.
[ "Copy", "a", "table", "from", "another", "SQLite", "database", "to", "this", "one", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L350-L354
train
51,872
dusktreader/flask-buzz
flask_buzz/__init__.py
FlaskBuzz.jsonify
def jsonify(self, status_code=None, message=None, headers=None): """ Returns a representation of the error in a jsonic form that is compatible with flask's error handling. Keyword arguments allow custom error handlers to override parts of the exception when it is jsonified """ if status_code is None: status_code = self.status_code if message is None: message = self.message if headers is None: headers = self.headers response = flask.jsonify({ 'status_code': status_code, 'error': repr(self), 'message': message, }) if status_code is not None: response.status_code = status_code if headers is not None: response.headers = headers return response
python
def jsonify(self, status_code=None, message=None, headers=None): """ Returns a representation of the error in a jsonic form that is compatible with flask's error handling. Keyword arguments allow custom error handlers to override parts of the exception when it is jsonified """ if status_code is None: status_code = self.status_code if message is None: message = self.message if headers is None: headers = self.headers response = flask.jsonify({ 'status_code': status_code, 'error': repr(self), 'message': message, }) if status_code is not None: response.status_code = status_code if headers is not None: response.headers = headers return response
[ "def", "jsonify", "(", "self", ",", "status_code", "=", "None", ",", "message", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "status_code", "is", "None", ":", "status_code", "=", "self", ".", "status_code", "if", "message", "is", "None", "...
Returns a representation of the error in a jsonic form that is compatible with flask's error handling. Keyword arguments allow custom error handlers to override parts of the exception when it is jsonified
[ "Returns", "a", "representation", "of", "the", "error", "in", "a", "jsonic", "form", "that", "is", "compatible", "with", "flask", "s", "error", "handling", "." ]
0f6754e196b4da4bc3f3675b63389338d660f6f7
https://github.com/dusktreader/flask-buzz/blob/0f6754e196b4da4bc3f3675b63389338d660f6f7/flask_buzz/__init__.py#L21-L44
train
51,873
matllubos/django-is-core
is_core/forms/models.py
humanized_model_to_dict
def humanized_model_to_dict(instance, readonly_fields, fields=None, exclude=None): """ Returns a dict containing the humanized data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, only the named fields will be included in the returned dict. ``exclude`` is an optional list of field names. If provided, the named fields will be excluded from the returned dict, even if they are listed in the ``fields`` argument. """ opts = instance._meta data = {} for f in itertools.chain(opts.concrete_fields, opts.private_fields, opts.many_to_many): if not getattr(f, 'editable', False): continue if fields and f.name not in fields: continue if f.name not in readonly_fields: continue if exclude and f.name in exclude: continue if f.humanized: data[f.name] = f.humanized(getattr(instance, f.name), instance) return data
python
def humanized_model_to_dict(instance, readonly_fields, fields=None, exclude=None): """ Returns a dict containing the humanized data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, only the named fields will be included in the returned dict. ``exclude`` is an optional list of field names. If provided, the named fields will be excluded from the returned dict, even if they are listed in the ``fields`` argument. """ opts = instance._meta data = {} for f in itertools.chain(opts.concrete_fields, opts.private_fields, opts.many_to_many): if not getattr(f, 'editable', False): continue if fields and f.name not in fields: continue if f.name not in readonly_fields: continue if exclude and f.name in exclude: continue if f.humanized: data[f.name] = f.humanized(getattr(instance, f.name), instance) return data
[ "def", "humanized_model_to_dict", "(", "instance", ",", "readonly_fields", ",", "fields", "=", "None", ",", "exclude", "=", "None", ")", ":", "opts", "=", "instance", ".", "_meta", "data", "=", "{", "}", "for", "f", "in", "itertools", ".", "chain", "(", ...
Returns a dict containing the humanized data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, only the named fields will be included in the returned dict. ``exclude`` is an optional list of field names. If provided, the named fields will be excluded from the returned dict, even if they are listed in the ``fields`` argument.
[ "Returns", "a", "dict", "containing", "the", "humanized", "data", "in", "instance", "suitable", "for", "passing", "as", "a", "Form", "s", "initial", "keyword", "argument", "." ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/models.py#L170-L196
train
51,874
codeforamerica/three
three/cities.py
find_info
def find_info(name=None): """Find the needed city server information.""" if not name: return list(servers.keys()) name = name.lower() if name in servers: info = servers[name] else: raise CityNotFound("Could not find the specified city: %s" % name) return info
python
def find_info(name=None): """Find the needed city server information.""" if not name: return list(servers.keys()) name = name.lower() if name in servers: info = servers[name] else: raise CityNotFound("Could not find the specified city: %s" % name) return info
[ "def", "find_info", "(", "name", "=", "None", ")", ":", "if", "not", "name", ":", "return", "list", "(", "servers", ".", "keys", "(", ")", ")", "name", "=", "name", ".", "lower", "(", ")", "if", "name", "in", "servers", ":", "info", "=", "servers...
Find the needed city server information.
[ "Find", "the", "needed", "city", "server", "information", "." ]
67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/cities.py#L10-L19
train
51,875
vcs-python/libvcs
libvcs/util.py
RepoLoggingAdapter.process
def process(self, msg, kwargs): """Add additional context information for loggers.""" prefixed_dict = {} prefixed_dict['repo_vcs'] = self.bin_name prefixed_dict['repo_name'] = self.name kwargs["extra"] = prefixed_dict return msg, kwargs
python
def process(self, msg, kwargs): """Add additional context information for loggers.""" prefixed_dict = {} prefixed_dict['repo_vcs'] = self.bin_name prefixed_dict['repo_name'] = self.name kwargs["extra"] = prefixed_dict return msg, kwargs
[ "def", "process", "(", "self", ",", "msg", ",", "kwargs", ")", ":", "prefixed_dict", "=", "{", "}", "prefixed_dict", "[", "'repo_vcs'", "]", "=", "self", ".", "bin_name", "prefixed_dict", "[", "'repo_name'", "]", "=", "self", ".", "name", "kwargs", "[", ...
Add additional context information for loggers.
[ "Add", "additional", "context", "information", "for", "loggers", "." ]
f7dc055250199bac6be7439b1d2240583f0bb354
https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/util.py#L105-L113
train
51,876
xapple/plumbing
plumbing/git.py
GitRepo.branches
def branches(self): """All branches in a list""" result = self.git(self.default + ['branch', '-a', '--no-color']) return [l.strip(' *\n') for l in result.split('\n') if l.strip(' *\n')]
python
def branches(self): """All branches in a list""" result = self.git(self.default + ['branch', '-a', '--no-color']) return [l.strip(' *\n') for l in result.split('\n') if l.strip(' *\n')]
[ "def", "branches", "(", "self", ")", ":", "result", "=", "self", ".", "git", "(", "self", ".", "default", "+", "[", "'branch'", ",", "'-a'", ",", "'--no-color'", "]", ")", "return", "[", "l", ".", "strip", "(", "' *\\n'", ")", "for", "l", "in", "...
All branches in a list
[ "All", "branches", "in", "a", "list" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/git.py#L64-L67
train
51,877
xapple/plumbing
plumbing/git.py
GitRepo.re_clone
def re_clone(self, repo_dir): """Clone again, somewhere else""" self.git('clone', self.remote_url, repo_dir) return GitRepo(repo_dir)
python
def re_clone(self, repo_dir): """Clone again, somewhere else""" self.git('clone', self.remote_url, repo_dir) return GitRepo(repo_dir)
[ "def", "re_clone", "(", "self", ",", "repo_dir", ")", ":", "self", ".", "git", "(", "'clone'", ",", "self", ".", "remote_url", ",", "repo_dir", ")", "return", "GitRepo", "(", "repo_dir", ")" ]
Clone again, somewhere else
[ "Clone", "again", "somewhere", "else" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/git.py#L87-L90
train
51,878
xapple/plumbing
plumbing/trees/__init__.py
Node.path
def path(self): """Iterate over all parent nodes and one-self.""" yield self if not self.parent: return for node in self.parent.path: yield node
python
def path(self): """Iterate over all parent nodes and one-self.""" yield self if not self.parent: return for node in self.parent.path: yield node
[ "def", "path", "(", "self", ")", ":", "yield", "self", "if", "not", "self", ".", "parent", ":", "return", "for", "node", "in", "self", ".", "parent", ".", "path", ":", "yield", "node" ]
Iterate over all parent nodes and one-self.
[ "Iterate", "over", "all", "parent", "nodes", "and", "one", "-", "self", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L40-L44
train
51,879
xapple/plumbing
plumbing/trees/__init__.py
Node.others
def others(self): """Iterate over all nodes of the tree excluding one self and one's children.""" if not self.parent: return yield self.parent for sibling in self.parent.children.values(): if sibling.name == self.name: continue for node in sibling: yield node for node in self.parent.others: yield node
python
def others(self): """Iterate over all nodes of the tree excluding one self and one's children.""" if not self.parent: return yield self.parent for sibling in self.parent.children.values(): if sibling.name == self.name: continue for node in sibling: yield node for node in self.parent.others: yield node
[ "def", "others", "(", "self", ")", ":", "if", "not", "self", ".", "parent", ":", "return", "yield", "self", ".", "parent", "for", "sibling", "in", "self", ".", "parent", ".", "children", ".", "values", "(", ")", ":", "if", "sibling", ".", "name", "...
Iterate over all nodes of the tree excluding one self and one's children.
[ "Iterate", "over", "all", "nodes", "of", "the", "tree", "excluding", "one", "self", "and", "one", "s", "children", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L47-L54
train
51,880
xapple/plumbing
plumbing/trees/__init__.py
Node.get_level
def get_level(self, level=2): """Get all nodes that are exactly this far away.""" if level == 1: for child in self.children.values(): yield child else: for child in self.children.values(): for node in child.get_level(level-1): yield node
python
def get_level(self, level=2): """Get all nodes that are exactly this far away.""" if level == 1: for child in self.children.values(): yield child else: for child in self.children.values(): for node in child.get_level(level-1): yield node
[ "def", "get_level", "(", "self", ",", "level", "=", "2", ")", ":", "if", "level", "==", "1", ":", "for", "child", "in", "self", ".", "children", ".", "values", "(", ")", ":", "yield", "child", "else", ":", "for", "child", "in", "self", ".", "chil...
Get all nodes that are exactly this far away.
[ "Get", "all", "nodes", "that", "are", "exactly", "this", "far", "away", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L63-L69
train
51,881
xapple/plumbing
plumbing/trees/__init__.py
Node.mend
def mend(self, length): """Cut all branches from this node to its children and adopt all nodes at certain level.""" if length == 0: raise Exception("Can't mend the root !") if length == 1: return self.children = OrderedDict((node.name, node) for node in self.get_level(length)) for child in self.children.values(): child.parent = self
python
def mend(self, length): """Cut all branches from this node to its children and adopt all nodes at certain level.""" if length == 0: raise Exception("Can't mend the root !") if length == 1: return self.children = OrderedDict((node.name, node) for node in self.get_level(length)) for child in self.children.values(): child.parent = self
[ "def", "mend", "(", "self", ",", "length", ")", ":", "if", "length", "==", "0", ":", "raise", "Exception", "(", "\"Can't mend the root !\"", ")", "if", "length", "==", "1", ":", "return", "self", ".", "children", "=", "OrderedDict", "(", "(", "node", "...
Cut all branches from this node to its children and adopt all nodes at certain level.
[ "Cut", "all", "branches", "from", "this", "node", "to", "its", "children", "and", "adopt", "all", "nodes", "at", "certain", "level", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L96-L102
train
51,882
softwarefactory-project/distroinfo
distroinfo/info.py
DistroInfo.get_info
def get_info(self, apply_tag=None, info_dicts=False): """ Get data from distroinfo instance. :param apply_tag: apply supplied tag to info :param info_dicts: return packages and releases as dicts :return: parsed info metadata """ raw_infos = self.fetcher.fetch(*self.info_files) raw_info = parse.merge_infos(*raw_infos, info_dicts=info_dicts) info = parse.parse_info(raw_info, apply_tag=apply_tag) return info
python
def get_info(self, apply_tag=None, info_dicts=False): """ Get data from distroinfo instance. :param apply_tag: apply supplied tag to info :param info_dicts: return packages and releases as dicts :return: parsed info metadata """ raw_infos = self.fetcher.fetch(*self.info_files) raw_info = parse.merge_infos(*raw_infos, info_dicts=info_dicts) info = parse.parse_info(raw_info, apply_tag=apply_tag) return info
[ "def", "get_info", "(", "self", ",", "apply_tag", "=", "None", ",", "info_dicts", "=", "False", ")", ":", "raw_infos", "=", "self", ".", "fetcher", ".", "fetch", "(", "*", "self", ".", "info_files", ")", "raw_info", "=", "parse", ".", "merge_infos", "(...
Get data from distroinfo instance. :param apply_tag: apply supplied tag to info :param info_dicts: return packages and releases as dicts :return: parsed info metadata
[ "Get", "data", "from", "distroinfo", "instance", "." ]
86a7419232a3376157c06e70528ec627e03ff82a
https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/info.py#L53-L64
train
51,883
sprockets/sprockets.http
sprockets/http/__init__.py
run
def run(create_application, settings=None, log_config=None): """ Run a Tornado create_application. :param create_application: function to call to create a new application instance :param dict|None settings: optional configuration dictionary that will be passed through to ``create_application`` as kwargs. :param dict|None log_config: optional logging configuration dictionary to use. By default, a reasonable logging configuration is generated based on settings. If you need to override the configuration, then use this parameter. It is passed as-is to :func:`logging.config.dictConfig`. .. rubric:: settings['debug'] If the `settings` parameter includes a value for the ``debug`` key, then the application will be run in Tornado debug mode. If the `settings` parameter does not include a ``debug`` key, then debug mode will be enabled based on the :envvar:`DEBUG` environment variable. .. rubric:: settings['port'] If the `settings` parameter includes a value for the ``port`` key, then the application will be configured to listen on the specified port. If this key is not present, then the :envvar:`PORT` environment variable determines which port to bind to. The default port is 8000 if nothing overrides it. .. rubric:: settings['number_of_procs'] If the `settings` parameter includes a value for the ``number_of_procs`` key, then the application will be configured to run this many processes unless in *debug* mode. This is passed to ``HTTPServer.start``. .. rubric:: settings['xheaders'] If the `settings` parameter includes a value for the ``xheaders`` key, then the application will be configured to use headers, like X-Real-IP, to get the user's IP address instead of attributing all traffic to the load balancer's IP address. When running behind a load balancer like nginx, it is recommended to pass xheaders=True. The default value is False if nothing overrides it. """ from . import runner app_settings = {} if settings is None else settings.copy() debug_mode = bool(app_settings.get('debug', int(os.environ.get('DEBUG', 0)) != 0)) app_settings['debug'] = debug_mode logging.config.dictConfig(_get_logging_config(debug_mode) if log_config is None else log_config) port_number = int(app_settings.pop('port', os.environ.get('PORT', 8000))) num_procs = int(app_settings.pop('number_of_procs', '0')) server = runner.Runner(create_application(**app_settings)) server.run(port_number, num_procs)
python
def run(create_application, settings=None, log_config=None): """ Run a Tornado create_application. :param create_application: function to call to create a new application instance :param dict|None settings: optional configuration dictionary that will be passed through to ``create_application`` as kwargs. :param dict|None log_config: optional logging configuration dictionary to use. By default, a reasonable logging configuration is generated based on settings. If you need to override the configuration, then use this parameter. It is passed as-is to :func:`logging.config.dictConfig`. .. rubric:: settings['debug'] If the `settings` parameter includes a value for the ``debug`` key, then the application will be run in Tornado debug mode. If the `settings` parameter does not include a ``debug`` key, then debug mode will be enabled based on the :envvar:`DEBUG` environment variable. .. rubric:: settings['port'] If the `settings` parameter includes a value for the ``port`` key, then the application will be configured to listen on the specified port. If this key is not present, then the :envvar:`PORT` environment variable determines which port to bind to. The default port is 8000 if nothing overrides it. .. rubric:: settings['number_of_procs'] If the `settings` parameter includes a value for the ``number_of_procs`` key, then the application will be configured to run this many processes unless in *debug* mode. This is passed to ``HTTPServer.start``. .. rubric:: settings['xheaders'] If the `settings` parameter includes a value for the ``xheaders`` key, then the application will be configured to use headers, like X-Real-IP, to get the user's IP address instead of attributing all traffic to the load balancer's IP address. When running behind a load balancer like nginx, it is recommended to pass xheaders=True. The default value is False if nothing overrides it. """ from . import runner app_settings = {} if settings is None else settings.copy() debug_mode = bool(app_settings.get('debug', int(os.environ.get('DEBUG', 0)) != 0)) app_settings['debug'] = debug_mode logging.config.dictConfig(_get_logging_config(debug_mode) if log_config is None else log_config) port_number = int(app_settings.pop('port', os.environ.get('PORT', 8000))) num_procs = int(app_settings.pop('number_of_procs', '0')) server = runner.Runner(create_application(**app_settings)) server.run(port_number, num_procs)
[ "def", "run", "(", "create_application", ",", "settings", "=", "None", ",", "log_config", "=", "None", ")", ":", "from", ".", "import", "runner", "app_settings", "=", "{", "}", "if", "settings", "is", "None", "else", "settings", ".", "copy", "(", ")", ...
Run a Tornado create_application. :param create_application: function to call to create a new application instance :param dict|None settings: optional configuration dictionary that will be passed through to ``create_application`` as kwargs. :param dict|None log_config: optional logging configuration dictionary to use. By default, a reasonable logging configuration is generated based on settings. If you need to override the configuration, then use this parameter. It is passed as-is to :func:`logging.config.dictConfig`. .. rubric:: settings['debug'] If the `settings` parameter includes a value for the ``debug`` key, then the application will be run in Tornado debug mode. If the `settings` parameter does not include a ``debug`` key, then debug mode will be enabled based on the :envvar:`DEBUG` environment variable. .. rubric:: settings['port'] If the `settings` parameter includes a value for the ``port`` key, then the application will be configured to listen on the specified port. If this key is not present, then the :envvar:`PORT` environment variable determines which port to bind to. The default port is 8000 if nothing overrides it. .. rubric:: settings['number_of_procs'] If the `settings` parameter includes a value for the ``number_of_procs`` key, then the application will be configured to run this many processes unless in *debug* mode. This is passed to ``HTTPServer.start``. .. rubric:: settings['xheaders'] If the `settings` parameter includes a value for the ``xheaders`` key, then the application will be configured to use headers, like X-Real-IP, to get the user's IP address instead of attributing all traffic to the load balancer's IP address. When running behind a load balancer like nginx, it is recommended to pass xheaders=True. The default value is False if nothing overrides it.
[ "Run", "a", "Tornado", "create_application", "." ]
8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3
https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/__init__.py#L10-L71
train
51,884
vcs-python/libvcs
libvcs/git.py
GitRepo.obtain
def obtain(self): """Retrieve the repository, clone if doesn't exist.""" self.check_destination() url = self.url cmd = ['clone', '--progress'] if self.git_shallow: cmd.extend(['--depth', '1']) if self.tls_verify: cmd.extend(['-c', 'http.sslVerify=false']) cmd.extend([url, self.path]) self.info('Cloning.') self.run(cmd, log_in_real_time=True) if self.remotes: for r in self.remotes: self.error('Adding remote %s <%s>' % (r['remote_name'], r['url'])) self.remote_set(name=r['remote_name'], url=r['url']) self.info('Initializing submodules.') self.run(['submodule', 'init'], log_in_real_time=True) cmd = ['submodule', 'update', '--recursive', '--init'] cmd.extend(self.git_submodules) self.run(cmd, log_in_real_time=True)
python
def obtain(self): """Retrieve the repository, clone if doesn't exist.""" self.check_destination() url = self.url cmd = ['clone', '--progress'] if self.git_shallow: cmd.extend(['--depth', '1']) if self.tls_verify: cmd.extend(['-c', 'http.sslVerify=false']) cmd.extend([url, self.path]) self.info('Cloning.') self.run(cmd, log_in_real_time=True) if self.remotes: for r in self.remotes: self.error('Adding remote %s <%s>' % (r['remote_name'], r['url'])) self.remote_set(name=r['remote_name'], url=r['url']) self.info('Initializing submodules.') self.run(['submodule', 'init'], log_in_real_time=True) cmd = ['submodule', 'update', '--recursive', '--init'] cmd.extend(self.git_submodules) self.run(cmd, log_in_real_time=True)
[ "def", "obtain", "(", "self", ")", ":", "self", ".", "check_destination", "(", ")", "url", "=", "self", ".", "url", "cmd", "=", "[", "'clone'", ",", "'--progress'", "]", "if", "self", ".", "git_shallow", ":", "cmd", ".", "extend", "(", "[", "'--depth...
Retrieve the repository, clone if doesn't exist.
[ "Retrieve", "the", "repository", "clone", "if", "doesn", "t", "exist", "." ]
f7dc055250199bac6be7439b1d2240583f0bb354
https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L109-L134
train
51,885
vcs-python/libvcs
libvcs/git.py
GitRepo.remotes_get
def remotes_get(self): """Return remotes like git remote -v. :rtype: dict of tuples """ remotes = {} cmd = self.run(['remote']) ret = filter(None, cmd.split('\n')) for remote_name in ret: remotes[remote_name] = self.remote_get(remote_name) return remotes
python
def remotes_get(self): """Return remotes like git remote -v. :rtype: dict of tuples """ remotes = {} cmd = self.run(['remote']) ret = filter(None, cmd.split('\n')) for remote_name in ret: remotes[remote_name] = self.remote_get(remote_name) return remotes
[ "def", "remotes_get", "(", "self", ")", ":", "remotes", "=", "{", "}", "cmd", "=", "self", ".", "run", "(", "[", "'remote'", "]", ")", "ret", "=", "filter", "(", "None", ",", "cmd", ".", "split", "(", "'\\n'", ")", ")", "for", "remote_name", "in"...
Return remotes like git remote -v. :rtype: dict of tuples
[ "Return", "remotes", "like", "git", "remote", "-", "v", "." ]
f7dc055250199bac6be7439b1d2240583f0bb354
https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L273-L285
train
51,886
vcs-python/libvcs
libvcs/git.py
GitRepo.remote_get
def remote_get(self, remote='origin'): """Get the fetch and push URL for a specified remote name. :param remote: the remote name used to define the fetch and push URL :type remote: str :returns: remote name and url in tuple form :rtype: tuple """ try: ret = self.run(['remote', 'show', '-n', remote]) lines = ret.split('\n') remote_fetch_url = lines[1].replace('Fetch URL: ', '').strip() remote_push_url = lines[2].replace('Push URL: ', '').strip() if remote_fetch_url != remote and remote_push_url != remote: res = (remote_fetch_url, remote_push_url) return res else: return None except exc.LibVCSException: return None
python
def remote_get(self, remote='origin'): """Get the fetch and push URL for a specified remote name. :param remote: the remote name used to define the fetch and push URL :type remote: str :returns: remote name and url in tuple form :rtype: tuple """ try: ret = self.run(['remote', 'show', '-n', remote]) lines = ret.split('\n') remote_fetch_url = lines[1].replace('Fetch URL: ', '').strip() remote_push_url = lines[2].replace('Push URL: ', '').strip() if remote_fetch_url != remote and remote_push_url != remote: res = (remote_fetch_url, remote_push_url) return res else: return None except exc.LibVCSException: return None
[ "def", "remote_get", "(", "self", ",", "remote", "=", "'origin'", ")", ":", "try", ":", "ret", "=", "self", ".", "run", "(", "[", "'remote'", ",", "'show'", ",", "'-n'", ",", "remote", "]", ")", "lines", "=", "ret", ".", "split", "(", "'\\n'", ")...
Get the fetch and push URL for a specified remote name. :param remote: the remote name used to define the fetch and push URL :type remote: str :returns: remote name and url in tuple form :rtype: tuple
[ "Get", "the", "fetch", "and", "push", "URL", "for", "a", "specified", "remote", "name", "." ]
f7dc055250199bac6be7439b1d2240583f0bb354
https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L287-L306
train
51,887
vcs-python/libvcs
libvcs/git.py
GitRepo.remote_set
def remote_set(self, url, name='origin'): """Set remote with name and URL like git remote add. :param url: defines the remote URL :type url: str :param name: defines the remote name. :type name: str """ url = self.chomp_protocol(url) if self.remote_get(name): self.run(['remote', 'rm', 'name']) self.run(['remote', 'add', name, url]) return self.remote_get(remote=name)
python
def remote_set(self, url, name='origin'): """Set remote with name and URL like git remote add. :param url: defines the remote URL :type url: str :param name: defines the remote name. :type name: str """ url = self.chomp_protocol(url) if self.remote_get(name): self.run(['remote', 'rm', 'name']) self.run(['remote', 'add', name, url]) return self.remote_get(remote=name)
[ "def", "remote_set", "(", "self", ",", "url", ",", "name", "=", "'origin'", ")", ":", "url", "=", "self", ".", "chomp_protocol", "(", "url", ")", "if", "self", ".", "remote_get", "(", "name", ")", ":", "self", ".", "run", "(", "[", "'remote'", ",",...
Set remote with name and URL like git remote add. :param url: defines the remote URL :type url: str :param name: defines the remote name. :type name: str
[ "Set", "remote", "with", "name", "and", "URL", "like", "git", "remote", "add", "." ]
f7dc055250199bac6be7439b1d2240583f0bb354
https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L308-L323
train
51,888
vcs-python/libvcs
libvcs/git.py
GitRepo.chomp_protocol
def chomp_protocol(url): """Return clean VCS url from RFC-style url :param url: url :type url: str :rtype: str :returns: url as VCS software would accept it :seealso: #14 """ if '+' in url: url = url.split('+', 1)[1] scheme, netloc, path, query, frag = urlparse.urlsplit(url) rev = None if '@' in path: path, rev = path.rsplit('@', 1) url = urlparse.urlunsplit((scheme, netloc, path, query, '')) if url.startswith('ssh://git@github.com/'): url = url.replace('ssh://', 'git+ssh://') elif '://' not in url: assert 'file:' not in url url = url.replace('git+', 'git+ssh://') url = url.replace('ssh://', '') return url
python
def chomp_protocol(url): """Return clean VCS url from RFC-style url :param url: url :type url: str :rtype: str :returns: url as VCS software would accept it :seealso: #14 """ if '+' in url: url = url.split('+', 1)[1] scheme, netloc, path, query, frag = urlparse.urlsplit(url) rev = None if '@' in path: path, rev = path.rsplit('@', 1) url = urlparse.urlunsplit((scheme, netloc, path, query, '')) if url.startswith('ssh://git@github.com/'): url = url.replace('ssh://', 'git+ssh://') elif '://' not in url: assert 'file:' not in url url = url.replace('git+', 'git+ssh://') url = url.replace('ssh://', '') return url
[ "def", "chomp_protocol", "(", "url", ")", ":", "if", "'+'", "in", "url", ":", "url", "=", "url", ".", "split", "(", "'+'", ",", "1", ")", "[", "1", "]", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "frag", "=", "urlparse", ".", "url...
Return clean VCS url from RFC-style url :param url: url :type url: str :rtype: str :returns: url as VCS software would accept it :seealso: #14
[ "Return", "clean", "VCS", "url", "from", "RFC", "-", "style", "url" ]
f7dc055250199bac6be7439b1d2240583f0bb354
https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L326-L348
train
51,889
confirm/ansibleci
ansibleci/logger.py
Logger._log
def _log(self, message, stream, color=None, newline=False): ''' Logs the message to the sys.stdout or sys.stderr stream. When color is defined and the TERM environemnt variable contains the string "color", then the output will be colored. ''' if color and self.color_term: colorend = Logger.COLOR_END else: color = colorend = '' stream.write('{color}{message}{colorend}\n'.format( color=color, message=message, colorend=colorend )) if newline: sys.stdout.write('\n') stream.flush()
python
def _log(self, message, stream, color=None, newline=False): ''' Logs the message to the sys.stdout or sys.stderr stream. When color is defined and the TERM environemnt variable contains the string "color", then the output will be colored. ''' if color and self.color_term: colorend = Logger.COLOR_END else: color = colorend = '' stream.write('{color}{message}{colorend}\n'.format( color=color, message=message, colorend=colorend )) if newline: sys.stdout.write('\n') stream.flush()
[ "def", "_log", "(", "self", ",", "message", ",", "stream", ",", "color", "=", "None", ",", "newline", "=", "False", ")", ":", "if", "color", "and", "self", ".", "color_term", ":", "colorend", "=", "Logger", ".", "COLOR_END", "else", ":", "color", "="...
Logs the message to the sys.stdout or sys.stderr stream. When color is defined and the TERM environemnt variable contains the string "color", then the output will be colored.
[ "Logs", "the", "message", "to", "the", "sys", ".", "stdout", "or", "sys", ".", "stderr", "stream", "." ]
6a53ae8c4a4653624977e146092422857f661b8f
https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L43-L65
train
51,890
confirm/ansibleci
ansibleci/logger.py
Logger.info
def info(self, message): ''' Logs an informational message to stdout. This method should only be used by the Runner. ''' return self._log( message=message.upper(), stream=sys.stdout )
python
def info(self, message): ''' Logs an informational message to stdout. This method should only be used by the Runner. ''' return self._log( message=message.upper(), stream=sys.stdout )
[ "def", "info", "(", "self", ",", "message", ")", ":", "return", "self", ".", "_log", "(", "message", "=", "message", ".", "upper", "(", ")", ",", "stream", "=", "sys", ".", "stdout", ")" ]
Logs an informational message to stdout. This method should only be used by the Runner.
[ "Logs", "an", "informational", "message", "to", "stdout", "." ]
6a53ae8c4a4653624977e146092422857f661b8f
https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L78-L87
train
51,891
confirm/ansibleci
ansibleci/logger.py
Logger.passed
def passed(self, message): ''' Logs as whole test result as PASSED. This method should only be used by the Runner. ''' return self._log( message=message.upper(), stream=sys.stdout, color=Logger.COLOR_GREEN_BOLD, newline=True )
python
def passed(self, message): ''' Logs as whole test result as PASSED. This method should only be used by the Runner. ''' return self._log( message=message.upper(), stream=sys.stdout, color=Logger.COLOR_GREEN_BOLD, newline=True )
[ "def", "passed", "(", "self", ",", "message", ")", ":", "return", "self", ".", "_log", "(", "message", "=", "message", ".", "upper", "(", ")", ",", "stream", "=", "sys", ".", "stdout", ",", "color", "=", "Logger", ".", "COLOR_GREEN_BOLD", ",", "newli...
Logs as whole test result as PASSED. This method should only be used by the Runner.
[ "Logs", "as", "whole", "test", "result", "as", "PASSED", "." ]
6a53ae8c4a4653624977e146092422857f661b8f
https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L89-L100
train
51,892
confirm/ansibleci
ansibleci/logger.py
Logger.failed
def failed(self, message): ''' Logs as whole test result as FAILED. This method should only be used by the Runner. ''' return self._log( message=message.upper(), stream=sys.stderr, color=Logger.COLOR_RED_BOLD, newline=True )
python
def failed(self, message): ''' Logs as whole test result as FAILED. This method should only be used by the Runner. ''' return self._log( message=message.upper(), stream=sys.stderr, color=Logger.COLOR_RED_BOLD, newline=True )
[ "def", "failed", "(", "self", ",", "message", ")", ":", "return", "self", ".", "_log", "(", "message", "=", "message", ".", "upper", "(", ")", ",", "stream", "=", "sys", ".", "stderr", ",", "color", "=", "Logger", ".", "COLOR_RED_BOLD", ",", "newline...
Logs as whole test result as FAILED. This method should only be used by the Runner.
[ "Logs", "as", "whole", "test", "result", "as", "FAILED", "." ]
6a53ae8c4a4653624977e146092422857f661b8f
https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L102-L113
train
51,893
xapple/plumbing
plumbing/runner.py
Runner.logs
def logs(self): """Find the log directory and return all the logs sorted.""" if not self.parent.loaded: self.parent.load() logs = self.parent.p.logs_dir.flat_directories logs.sort(key=lambda x: x.mod_time) return logs
python
def logs(self): """Find the log directory and return all the logs sorted.""" if not self.parent.loaded: self.parent.load() logs = self.parent.p.logs_dir.flat_directories logs.sort(key=lambda x: x.mod_time) return logs
[ "def", "logs", "(", "self", ")", ":", "if", "not", "self", ".", "parent", ".", "loaded", ":", "self", ".", "parent", ".", "load", "(", ")", "logs", "=", "self", ".", "parent", ".", "p", ".", "logs_dir", ".", "flat_directories", "logs", ".", "sort",...
Find the log directory and return all the logs sorted.
[ "Find", "the", "log", "directory", "and", "return", "all", "the", "logs", "sorted", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/runner.py#L108-L113
train
51,894
xapple/plumbing
plumbing/runner.py
Runner.run_locally
def run_locally(self, steps=None, **kwargs): """A convenience method to run the same result as a SLURM job but locally in a non-blocking way.""" self.slurm_job = LoggedJobSLURM(self.command(steps), base_dir = self.parent.p.logs_dir, modules = self.modules, **kwargs) self.slurm_job.run_locally()
python
def run_locally(self, steps=None, **kwargs): """A convenience method to run the same result as a SLURM job but locally in a non-blocking way.""" self.slurm_job = LoggedJobSLURM(self.command(steps), base_dir = self.parent.p.logs_dir, modules = self.modules, **kwargs) self.slurm_job.run_locally()
[ "def", "run_locally", "(", "self", ",", "steps", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "slurm_job", "=", "LoggedJobSLURM", "(", "self", ".", "command", "(", "steps", ")", ",", "base_dir", "=", "self", ".", "parent", ".", "p", ...
A convenience method to run the same result as a SLURM job but locally in a non-blocking way.
[ "A", "convenience", "method", "to", "run", "the", "same", "result", "as", "a", "SLURM", "job", "but", "locally", "in", "a", "non", "-", "blocking", "way", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/runner.py#L121-L128
train
51,895
xapple/plumbing
plumbing/runner.py
Runner.run_slurm
def run_slurm(self, steps=None, **kwargs): """Run the steps via the SLURM queue.""" # Optional extra SLURM parameters # params = self.extra_slurm_params params.update(kwargs) # Mandatory extra SLURM parameters # if 'time' not in params: params['time'] = self.default_time if 'job_name' not in params: params['job_name'] = self.job_name if 'email' not in params: params['email'] = None if 'dependency' not in params: params['dependency'] = 'singleton' # Send it # self.slurm_job = LoggedJobSLURM(self.command(steps), base_dir = self.parent.p.logs_dir, modules = self.modules, **params) # Return the Job ID # return self.slurm_job.run()
python
def run_slurm(self, steps=None, **kwargs): """Run the steps via the SLURM queue.""" # Optional extra SLURM parameters # params = self.extra_slurm_params params.update(kwargs) # Mandatory extra SLURM parameters # if 'time' not in params: params['time'] = self.default_time if 'job_name' not in params: params['job_name'] = self.job_name if 'email' not in params: params['email'] = None if 'dependency' not in params: params['dependency'] = 'singleton' # Send it # self.slurm_job = LoggedJobSLURM(self.command(steps), base_dir = self.parent.p.logs_dir, modules = self.modules, **params) # Return the Job ID # return self.slurm_job.run()
[ "def", "run_slurm", "(", "self", ",", "steps", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Optional extra SLURM parameters #", "params", "=", "self", ".", "extra_slurm_params", "params", ".", "update", "(", "kwargs", ")", "# Mandatory extra SLURM parameters...
Run the steps via the SLURM queue.
[ "Run", "the", "steps", "via", "the", "SLURM", "queue", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/runner.py#L131-L147
train
51,896
matllubos/django-is-core
is_core/forms/generic.py
smart_generic_inlineformset_factory
def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field='content_type', fk_field='object_id', fields=None, exclude=None, extra=3, can_order=False, can_delete=True, min_num=None, max_num=None, formfield_callback=None, widgets=None, validate_min=False, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, formreadonlyfield_callback=None, readonly_fields=None, for_concrete_model=True, readonly=False): """ Returns a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively. """ opts = model._meta # if there is no field called `ct_field` let the exception propagate ct_field = opts.get_field(ct_field) if not isinstance(ct_field, models.ForeignKey) or ct_field.related_model != ContentType: raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field) fk_field = opts.get_field(fk_field) # let the exception propagate if exclude is not None: exclude = list(exclude) exclude.extend([ct_field.name, fk_field.name]) else: exclude = [ct_field.name, fk_field.name] kwargs = { 'form': form, 'formfield_callback': formfield_callback, 'formset': formset, 'extra': extra, 'can_delete': can_delete, 'can_order': can_order, 'fields': fields, 'exclude': exclude, 'max_num': max_num, 'min_num': min_num, 'widgets': widgets, 'validate_min': validate_min, 'validate_max': validate_max, 'localized_fields': localized_fields, 'formreadonlyfield_callback': formreadonlyfield_callback, 'readonly_fields': readonly_fields, 'readonly': readonly, 'labels': labels, 'help_texts': help_texts, 'error_messages': error_messages, } FormSet = smartmodelformset_factory(model, request, **kwargs) FormSet.ct_field = ct_field FormSet.ct_fk_field = fk_field FormSet.for_concrete_model = for_concrete_model return FormSet
python
def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field='content_type', fk_field='object_id', fields=None, exclude=None, extra=3, can_order=False, can_delete=True, min_num=None, max_num=None, formfield_callback=None, widgets=None, validate_min=False, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, formreadonlyfield_callback=None, readonly_fields=None, for_concrete_model=True, readonly=False): """ Returns a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively. """ opts = model._meta # if there is no field called `ct_field` let the exception propagate ct_field = opts.get_field(ct_field) if not isinstance(ct_field, models.ForeignKey) or ct_field.related_model != ContentType: raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field) fk_field = opts.get_field(fk_field) # let the exception propagate if exclude is not None: exclude = list(exclude) exclude.extend([ct_field.name, fk_field.name]) else: exclude = [ct_field.name, fk_field.name] kwargs = { 'form': form, 'formfield_callback': formfield_callback, 'formset': formset, 'extra': extra, 'can_delete': can_delete, 'can_order': can_order, 'fields': fields, 'exclude': exclude, 'max_num': max_num, 'min_num': min_num, 'widgets': widgets, 'validate_min': validate_min, 'validate_max': validate_max, 'localized_fields': localized_fields, 'formreadonlyfield_callback': formreadonlyfield_callback, 'readonly_fields': readonly_fields, 'readonly': readonly, 'labels': labels, 'help_texts': help_texts, 'error_messages': error_messages, } FormSet = smartmodelformset_factory(model, request, **kwargs) FormSet.ct_field = ct_field FormSet.ct_fk_field = fk_field FormSet.for_concrete_model = for_concrete_model return FormSet
[ "def", "smart_generic_inlineformset_factory", "(", "model", ",", "request", ",", "form", "=", "ModelForm", ",", "formset", "=", "BaseGenericInlineFormSet", ",", "ct_field", "=", "'content_type'", ",", "fk_field", "=", "'object_id'", ",", "fields", "=", "None", ","...
Returns a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively.
[ "Returns", "a", "GenericInlineFormSet", "for", "the", "given", "kwargs", "." ]
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/generic.py#L14-L66
train
51,897
xapple/plumbing
plumbing/ec2.py
InstanceEC2.rename
def rename(self, name): """Set the name of the machine.""" self.ec2.create_tags(Resources = [self.instance_id], Tags = [{'Key': 'Name', 'Value': name}]) self.refresh_info()
python
def rename(self, name): """Set the name of the machine.""" self.ec2.create_tags(Resources = [self.instance_id], Tags = [{'Key': 'Name', 'Value': name}]) self.refresh_info()
[ "def", "rename", "(", "self", ",", "name", ")", ":", "self", ".", "ec2", ".", "create_tags", "(", "Resources", "=", "[", "self", ".", "instance_id", "]", ",", "Tags", "=", "[", "{", "'Key'", ":", "'Name'", ",", "'Value'", ":", "name", "}", "]", "...
Set the name of the machine.
[ "Set", "the", "name", "of", "the", "machine", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/ec2.py#L70-L75
train
51,898
xapple/plumbing
plumbing/ec2.py
InstanceEC2.update_ssh_config
def update_ssh_config(self, path="~/.ssh/config"): """Put the DNS into the ssh config file.""" # Read the config file # import sshconf config = sshconf.read_ssh_config(os.path.expanduser(path)) # In case it doesn't exist # if not config.host(self.instance_name): config.add(self.instance_name) # Add the new DNS # config.set(self.instance_name, Hostname=self.dns) # Write result # config.write(os.path.expanduser(path))
python
def update_ssh_config(self, path="~/.ssh/config"): """Put the DNS into the ssh config file.""" # Read the config file # import sshconf config = sshconf.read_ssh_config(os.path.expanduser(path)) # In case it doesn't exist # if not config.host(self.instance_name): config.add(self.instance_name) # Add the new DNS # config.set(self.instance_name, Hostname=self.dns) # Write result # config.write(os.path.expanduser(path))
[ "def", "update_ssh_config", "(", "self", ",", "path", "=", "\"~/.ssh/config\"", ")", ":", "# Read the config file #", "import", "sshconf", "config", "=", "sshconf", ".", "read_ssh_config", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "# In...
Put the DNS into the ssh config file.
[ "Put", "the", "DNS", "into", "the", "ssh", "config", "file", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/ec2.py#L77-L87
train
51,899