repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
beregond/jsonmodels
jsonmodels/fields.py
BoolField.parse_value
def parse_value(self, value): """Cast value to `bool`.""" parsed = super(BoolField, self).parse_value(value) return bool(parsed) if parsed is not None else None
python
def parse_value(self, value): """Cast value to `bool`.""" parsed = super(BoolField, self).parse_value(value) return bool(parsed) if parsed is not None else None
[ "def", "parse_value", "(", "self", ",", "value", ")", ":", "parsed", "=", "super", "(", "BoolField", ",", "self", ")", ".", "parse_value", "(", "value", ")", "return", "bool", "(", "parsed", ")", "if", "parsed", "is", "not", "None", "else", "None" ]
Cast value to `bool`.
[ "Cast", "value", "to", "bool", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/fields.py#L178-L181
beregond/jsonmodels
jsonmodels/fields.py
ListField.parse_value
def parse_value(self, values): """Cast value to proper collection.""" result = self.get_default_value() if not values: return result if not isinstance(values, list): return values return [self._cast_value(value) for value in values]
python
def parse_value(self, values): """Cast value to proper collection.""" result = self.get_default_value() if not values: return result if not isinstance(values, list): return values return [self._cast_value(value) for value in values]
[ "def", "parse_value", "(", "self", ",", "values", ")", ":", "result", "=", "self", ".", "get_default_value", "(", ")", "if", "not", "values", ":", "return", "result", "if", "not", "isinstance", "(", "values", ",", "list", ")", ":", "return", "values", ...
Cast value to proper collection.
[ "Cast", "value", "to", "proper", "collection", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/fields.py#L245-L255
beregond/jsonmodels
jsonmodels/fields.py
EmbeddedField.parse_value
def parse_value(self, value): """Parse value to proper model type.""" if not isinstance(value, dict): return value embed_type = self._get_embed_type() return embed_type(**value)
python
def parse_value(self, value): """Parse value to proper model type.""" if not isinstance(value, dict): return value embed_type = self._get_embed_type() return embed_type(**value)
[ "def", "parse_value", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "value", "embed_type", "=", "self", ".", "_get_embed_type", "(", ")", "return", "embed_type", "(", "*", "*", "value", "...
Parse value to proper model type.
[ "Parse", "value", "to", "proper", "model", "type", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/fields.py#L329-L335
beregond/jsonmodels
jsonmodels/fields.py
TimeField.to_struct
def to_struct(self, value): """Cast `time` object to string.""" if self.str_format: return value.strftime(self.str_format) return value.isoformat()
python
def to_struct(self, value): """Cast `time` object to string.""" if self.str_format: return value.strftime(self.str_format) return value.isoformat()
[ "def", "to_struct", "(", "self", ",", "value", ")", ":", "if", "self", ".", "str_format", ":", "return", "value", ".", "strftime", "(", "self", ".", "str_format", ")", "return", "value", ".", "isoformat", "(", ")" ]
Cast `time` object to string.
[ "Cast", "time", "object", "to", "string", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/fields.py#L412-L416
beregond/jsonmodels
jsonmodels/fields.py
TimeField.parse_value
def parse_value(self, value): """Parse string into instance of `time`.""" if value is None: return value if isinstance(value, datetime.time): return value return parse(value).timetz()
python
def parse_value(self, value): """Parse string into instance of `time`.""" if value is None: return value if isinstance(value, datetime.time): return value return parse(value).timetz()
[ "def", "parse_value", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "value", "if", "isinstance", "(", "value", ",", "datetime", ".", "time", ")", ":", "return", "value", "return", "parse", "(", "value", ")", ".", "t...
Parse string into instance of `time`.
[ "Parse", "string", "into", "instance", "of", "time", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/fields.py#L418-L424
beregond/jsonmodels
jsonmodels/fields.py
DateField.to_struct
def to_struct(self, value): """Cast `date` object to string.""" if self.str_format: return value.strftime(self.str_format) return value.strftime(self.default_format)
python
def to_struct(self, value): """Cast `date` object to string.""" if self.str_format: return value.strftime(self.str_format) return value.strftime(self.default_format)
[ "def", "to_struct", "(", "self", ",", "value", ")", ":", "if", "self", ".", "str_format", ":", "return", "value", ".", "strftime", "(", "self", ".", "str_format", ")", "return", "value", ".", "strftime", "(", "self", ".", "default_format", ")" ]
Cast `date` object to string.
[ "Cast", "date", "object", "to", "string", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/fields.py#L444-L448
beregond/jsonmodels
jsonmodels/fields.py
DateTimeField.parse_value
def parse_value(self, value): """Parse string into instance of `datetime`.""" if isinstance(value, datetime.datetime): return value if value: return parse(value) else: return None
python
def parse_value(self, value): """Parse string into instance of `datetime`.""" if isinstance(value, datetime.datetime): return value if value: return parse(value) else: return None
[ "def", "parse_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", "if", "value", ":", "return", "parse", "(", "value", ")", "else", ":", "return", "None" ]
Parse string into instance of `datetime`.
[ "Parse", "string", "into", "instance", "of", "datetime", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/fields.py#L481-L488
beregond/jsonmodels
jsonmodels/validators.py
Min.validate
def validate(self, value): """Validate value.""" if self.exclusive: if value <= self.minimum_value: tpl = "'{value}' is lower or equal than minimum ('{min}')." raise ValidationError( tpl.format(value=value, min=self.minimum_value)) ...
python
def validate(self, value): """Validate value.""" if self.exclusive: if value <= self.minimum_value: tpl = "'{value}' is lower or equal than minimum ('{min}')." raise ValidationError( tpl.format(value=value, min=self.minimum_value)) ...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "self", ".", "exclusive", ":", "if", "value", "<=", "self", ".", "minimum_value", ":", "tpl", "=", "\"'{value}' is lower or equal than minimum ('{min}').\"", "raise", "ValidationError", "(", "tpl", "....
Validate value.
[ "Validate", "value", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/validators.py#L25-L36
beregond/jsonmodels
jsonmodels/validators.py
Min.modify_schema
def modify_schema(self, field_schema): """Modify field schema.""" field_schema['minimum'] = self.minimum_value if self.exclusive: field_schema['exclusiveMinimum'] = True
python
def modify_schema(self, field_schema): """Modify field schema.""" field_schema['minimum'] = self.minimum_value if self.exclusive: field_schema['exclusiveMinimum'] = True
[ "def", "modify_schema", "(", "self", ",", "field_schema", ")", ":", "field_schema", "[", "'minimum'", "]", "=", "self", ".", "minimum_value", "if", "self", ".", "exclusive", ":", "field_schema", "[", "'exclusiveMinimum'", "]", "=", "True" ]
Modify field schema.
[ "Modify", "field", "schema", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/validators.py#L38-L42
beregond/jsonmodels
jsonmodels/validators.py
Max.validate
def validate(self, value): """Validate value.""" if self.exclusive: if value >= self.maximum_value: tpl = "'{val}' is bigger or equal than maximum ('{max}')." raise ValidationError( tpl.format(val=value, max=self.maximum_value)) els...
python
def validate(self, value): """Validate value.""" if self.exclusive: if value >= self.maximum_value: tpl = "'{val}' is bigger or equal than maximum ('{max}')." raise ValidationError( tpl.format(val=value, max=self.maximum_value)) els...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "self", ".", "exclusive", ":", "if", "value", ">=", "self", ".", "maximum_value", ":", "tpl", "=", "\"'{val}' is bigger or equal than maximum ('{max}').\"", "raise", "ValidationError", "(", "tpl", "."...
Validate value.
[ "Validate", "value", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/validators.py#L60-L71
beregond/jsonmodels
jsonmodels/validators.py
Max.modify_schema
def modify_schema(self, field_schema): """Modify field schema.""" field_schema['maximum'] = self.maximum_value if self.exclusive: field_schema['exclusiveMaximum'] = True
python
def modify_schema(self, field_schema): """Modify field schema.""" field_schema['maximum'] = self.maximum_value if self.exclusive: field_schema['exclusiveMaximum'] = True
[ "def", "modify_schema", "(", "self", ",", "field_schema", ")", ":", "field_schema", "[", "'maximum'", "]", "=", "self", ".", "maximum_value", "if", "self", ".", "exclusive", ":", "field_schema", "[", "'exclusiveMaximum'", "]", "=", "True" ]
Modify field schema.
[ "Modify", "field", "schema", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/validators.py#L73-L77
beregond/jsonmodels
jsonmodels/validators.py
Regex.validate
def validate(self, value): """Validate value.""" flags = self._calculate_flags() try: result = re.search(self.pattern, value, flags) except TypeError as te: raise ValidationError(*te.args) if not result: raise ValidationError( ...
python
def validate(self, value): """Validate value.""" flags = self._calculate_flags() try: result = re.search(self.pattern, value, flags) except TypeError as te: raise ValidationError(*te.args) if not result: raise ValidationError( ...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "flags", "=", "self", ".", "_calculate_flags", "(", ")", "try", ":", "result", "=", "re", ".", "search", "(", "self", ".", "pattern", ",", "value", ",", "flags", ")", "except", "TypeError", "as"...
Validate value.
[ "Validate", "value", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/validators.py#L112-L125
beregond/jsonmodels
jsonmodels/validators.py
Regex.modify_schema
def modify_schema(self, field_schema): """Modify field schema.""" field_schema['pattern'] = utilities.convert_python_regex_to_ecma( self.pattern, self.flags)
python
def modify_schema(self, field_schema): """Modify field schema.""" field_schema['pattern'] = utilities.convert_python_regex_to_ecma( self.pattern, self.flags)
[ "def", "modify_schema", "(", "self", ",", "field_schema", ")", ":", "field_schema", "[", "'pattern'", "]", "=", "utilities", ".", "convert_python_regex_to_ecma", "(", "self", ".", "pattern", ",", "self", ".", "flags", ")" ]
Modify field schema.
[ "Modify", "field", "schema", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/validators.py#L130-L133
beregond/jsonmodels
jsonmodels/validators.py
Length.validate
def validate(self, value): """Validate value.""" len_ = len(value) if self.minimum_value is not None and len_ < self.minimum_value: tpl = "Value '{val}' length is lower than allowed minimum '{min}'." raise ValidationError(tpl.format( val=value, min=self.m...
python
def validate(self, value): """Validate value.""" len_ = len(value) if self.minimum_value is not None and len_ < self.minimum_value: tpl = "Value '{val}' length is lower than allowed minimum '{min}'." raise ValidationError(tpl.format( val=value, min=self.m...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "len_", "=", "len", "(", "value", ")", "if", "self", ".", "minimum_value", "is", "not", "None", "and", "len_", "<", "self", ".", "minimum_value", ":", "tpl", "=", "\"Value '{val}' length is lower than...
Validate value.
[ "Validate", "value", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/validators.py#L157-L173
beregond/jsonmodels
jsonmodels/validators.py
Length.modify_schema
def modify_schema(self, field_schema): """Modify field schema.""" if self.minimum_value: field_schema['minLength'] = self.minimum_value if self.maximum_value: field_schema['maxLength'] = self.maximum_value
python
def modify_schema(self, field_schema): """Modify field schema.""" if self.minimum_value: field_schema['minLength'] = self.minimum_value if self.maximum_value: field_schema['maxLength'] = self.maximum_value
[ "def", "modify_schema", "(", "self", ",", "field_schema", ")", ":", "if", "self", ".", "minimum_value", ":", "field_schema", "[", "'minLength'", "]", "=", "self", ".", "minimum_value", "if", "self", ".", "maximum_value", ":", "field_schema", "[", "'maxLength'"...
Modify field schema.
[ "Modify", "field", "schema", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/validators.py#L175-L181
beregond/jsonmodels
jsonmodels/parsers.py
to_struct
def to_struct(model): """Cast instance of model to python structure. :param model: Model to be casted. :rtype: ``dict`` """ model.validate() resp = {} for _, name, field in model.iterate_with_name(): value = field.__get__(model) if value is None: continue ...
python
def to_struct(model): """Cast instance of model to python structure. :param model: Model to be casted. :rtype: ``dict`` """ model.validate() resp = {} for _, name, field in model.iterate_with_name(): value = field.__get__(model) if value is None: continue ...
[ "def", "to_struct", "(", "model", ")", ":", "model", ".", "validate", "(", ")", "resp", "=", "{", "}", "for", "_", ",", "name", ",", "field", "in", "model", ".", "iterate_with_name", "(", ")", ":", "value", "=", "field", ".", "__get__", "(", "model...
Cast instance of model to python structure. :param model: Model to be casted. :rtype: ``dict``
[ "Cast", "instance", "of", "model", "to", "python", "structure", "." ]
train
https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/parsers.py#L7-L24
noirbizarre/django.js
djangojs/management/commands/js.py
Command.run_from_argv
def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. """ parser = self.create_parser(argv...
python
def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. """ parser = self.create_parser(argv...
[ "def", "run_from_argv", "(", "self", ",", "argv", ")", ":", "parser", "=", "self", ".", "create_parser", "(", "argv", "[", "0", "]", ",", "argv", "[", "1", "]", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", "[", "2", ":", "]", ")", ...
Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr.
[ "Set", "up", "any", "environment", "changes", "requested", "(", "e", ".", "g", ".", "Python", "path", "and", "Django", "settings", ")", "then", "run", "this", "command", ".", "If", "the", "command", "raises", "a", "CommandError", "intercept", "it", "and", ...
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/management/commands/js.py#L36-L59
noirbizarre/django.js
djangojs/management/commands/js.py
Command.create_parser
def create_parser(self, prog_name, subcommand): """ Create and return the ``OptionParser`` which will be used to parse the arguments to this command. """ parser = argparse.ArgumentParser(prog='%s %s' % (prog_name, subcommand), description=self.help) parser.add_argument(...
python
def create_parser(self, prog_name, subcommand): """ Create and return the ``OptionParser`` which will be used to parse the arguments to this command. """ parser = argparse.ArgumentParser(prog='%s %s' % (prog_name, subcommand), description=self.help) parser.add_argument(...
[ "def", "create_parser", "(", "self", ",", "prog_name", ",", "subcommand", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'%s %s'", "%", "(", "prog_name", ",", "subcommand", ")", ",", "description", "=", "self", ".", "help", ...
Create and return the ``OptionParser`` which will be used to parse the arguments to this command.
[ "Create", "and", "return", "the", "OptionParser", "which", "will", "be", "used", "to", "parse", "the", "arguments", "to", "this", "command", "." ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/management/commands/js.py#L61-L83
noirbizarre/django.js
setup.py
rst
def rst(filename): ''' Load rst file and sanitize it for PyPI. Remove unsupported github tags: - code-block directive - travis ci build badge ''' content = codecs.open(filename, encoding='utf-8').read() for regex, replacement in PYPI_RST_FILTERS: content = re.sub(regex, replace...
python
def rst(filename): ''' Load rst file and sanitize it for PyPI. Remove unsupported github tags: - code-block directive - travis ci build badge ''' content = codecs.open(filename, encoding='utf-8').read() for regex, replacement in PYPI_RST_FILTERS: content = re.sub(regex, replace...
[ "def", "rst", "(", "filename", ")", ":", "content", "=", "codecs", ".", "open", "(", "filename", ",", "encoding", "=", "'utf-8'", ")", ".", "read", "(", ")", "for", "regex", ",", "replacement", "in", "PYPI_RST_FILTERS", ":", "content", "=", "re", ".", ...
Load rst file and sanitize it for PyPI. Remove unsupported github tags: - code-block directive - travis ci build badge
[ "Load", "rst", "file", "and", "sanitize", "it", "for", "PyPI", ".", "Remove", "unsupported", "github", "tags", ":", "-", "code", "-", "block", "directive", "-", "travis", "ci", "build", "badge" ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/setup.py#L22-L32
noirbizarre/django.js
djangojs/templatetags/js.py
javascript
def javascript(filename, type='text/javascript'): '''A simple shortcut to render a ``script`` tag to a static javascript file''' if '?' in filename and len(filename.split('?')) is 2: filename, params = filename.split('?') return '<script type="%s" src="%s?%s"></script>' % (type, staticfiles_stor...
python
def javascript(filename, type='text/javascript'): '''A simple shortcut to render a ``script`` tag to a static javascript file''' if '?' in filename and len(filename.split('?')) is 2: filename, params = filename.split('?') return '<script type="%s" src="%s?%s"></script>' % (type, staticfiles_stor...
[ "def", "javascript", "(", "filename", ",", "type", "=", "'text/javascript'", ")", ":", "if", "'?'", "in", "filename", "and", "len", "(", "filename", ".", "split", "(", "'?'", ")", ")", "is", "2", ":", "filename", ",", "params", "=", "filename", ".", ...
A simple shortcut to render a ``script`` tag to a static javascript file
[ "A", "simple", "shortcut", "to", "render", "a", "script", "tag", "to", "a", "static", "javascript", "file" ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/templatetags/js.py#L111-L117
noirbizarre/django.js
djangojs/templatetags/js.py
jquery_js
def jquery_js(version=None, migrate=False): '''A shortcut to render a ``script`` tag for the packaged jQuery''' version = version or settings.JQUERY_VERSION suffix = '.min' if not settings.DEBUG else '' libs = [js_lib('jquery-%s%s.js' % (version, suffix))] if _boolean(migrate): libs.append(j...
python
def jquery_js(version=None, migrate=False): '''A shortcut to render a ``script`` tag for the packaged jQuery''' version = version or settings.JQUERY_VERSION suffix = '.min' if not settings.DEBUG else '' libs = [js_lib('jquery-%s%s.js' % (version, suffix))] if _boolean(migrate): libs.append(j...
[ "def", "jquery_js", "(", "version", "=", "None", ",", "migrate", "=", "False", ")", ":", "version", "=", "version", "or", "settings", ".", "JQUERY_VERSION", "suffix", "=", "'.min'", "if", "not", "settings", ".", "DEBUG", "else", "''", "libs", "=", "[", ...
A shortcut to render a ``script`` tag for the packaged jQuery
[ "A", "shortcut", "to", "render", "a", "script", "tag", "for", "the", "packaged", "jQuery" ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/templatetags/js.py#L156-L163
noirbizarre/django.js
djangojs/templatetags/js.py
django_js
def django_js(context, jquery=True, i18n=True, csrf=True, init=True): '''Include Django.js javascript library in the page''' return { 'js': { 'minified': not settings.DEBUG, 'jquery': _boolean(jquery), 'i18n': _boolean(i18n), 'csrf': _boolean(csrf), ...
python
def django_js(context, jquery=True, i18n=True, csrf=True, init=True): '''Include Django.js javascript library in the page''' return { 'js': { 'minified': not settings.DEBUG, 'jquery': _boolean(jquery), 'i18n': _boolean(i18n), 'csrf': _boolean(csrf), ...
[ "def", "django_js", "(", "context", ",", "jquery", "=", "True", ",", "i18n", "=", "True", ",", "csrf", "=", "True", ",", "init", "=", "True", ")", ":", "return", "{", "'js'", ":", "{", "'minified'", ":", "not", "settings", ".", "DEBUG", ",", "'jque...
Include Django.js javascript library in the page
[ "Include", "Django", ".", "js", "javascript", "library", "in", "the", "page" ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/templatetags/js.py#L167-L177
noirbizarre/django.js
djangojs/templatetags/js.py
django_js_init
def django_js_init(context, jquery=False, i18n=True, csrf=True, init=True): '''Include Django.js javascript library initialization in the page''' return { 'js': { 'jquery': _boolean(jquery), 'i18n': _boolean(i18n), 'csrf': _boolean(csrf), 'init': _boolean(...
python
def django_js_init(context, jquery=False, i18n=True, csrf=True, init=True): '''Include Django.js javascript library initialization in the page''' return { 'js': { 'jquery': _boolean(jquery), 'i18n': _boolean(i18n), 'csrf': _boolean(csrf), 'init': _boolean(...
[ "def", "django_js_init", "(", "context", ",", "jquery", "=", "False", ",", "i18n", "=", "True", ",", "csrf", "=", "True", ",", "init", "=", "True", ")", ":", "return", "{", "'js'", ":", "{", "'jquery'", ":", "_boolean", "(", "jquery", ")", ",", "'i...
Include Django.js javascript library initialization in the page
[ "Include", "Django", ".", "js", "javascript", "library", "initialization", "in", "the", "page" ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/templatetags/js.py#L181-L190
noirbizarre/django.js
djangojs/context_serializer.py
ContextSerializer.as_dict
def as_dict(self): ''' Serialize the context as a dictionnary from a given request. ''' data = {} if settings.JS_CONTEXT_ENABLED: for context in RequestContext(self.request): for key, value in six.iteritems(context): if settings.JS_...
python
def as_dict(self): ''' Serialize the context as a dictionnary from a given request. ''' data = {} if settings.JS_CONTEXT_ENABLED: for context in RequestContext(self.request): for key, value in six.iteritems(context): if settings.JS_...
[ "def", "as_dict", "(", "self", ")", ":", "data", "=", "{", "}", "if", "settings", ".", "JS_CONTEXT_ENABLED", ":", "for", "context", "in", "RequestContext", "(", "self", ".", "request", ")", ":", "for", "key", ",", "value", "in", "six", ".", "iteritems"...
Serialize the context as a dictionnary from a given request.
[ "Serialize", "the", "context", "as", "a", "dictionnary", "from", "a", "given", "request", "." ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/context_serializer.py#L37-L57
noirbizarre/django.js
djangojs/context_serializer.py
ContextSerializer.process_LANGUAGE_CODE
def process_LANGUAGE_CODE(self, language_code, data): ''' Fix language code when set to non included default `en` and add the extra variables ``LANGUAGE_NAME`` and ``LANGUAGE_NAME_LOCAL``. ''' # Dirty hack to fix non included default language_code = 'en-us' if language_co...
python
def process_LANGUAGE_CODE(self, language_code, data): ''' Fix language code when set to non included default `en` and add the extra variables ``LANGUAGE_NAME`` and ``LANGUAGE_NAME_LOCAL``. ''' # Dirty hack to fix non included default language_code = 'en-us' if language_co...
[ "def", "process_LANGUAGE_CODE", "(", "self", ",", "language_code", ",", "data", ")", ":", "# Dirty hack to fix non included default", "language_code", "=", "'en-us'", "if", "language_code", "==", "'en'", "else", "language_code", "language", "=", "translation", ".", "g...
Fix language code when set to non included default `en` and add the extra variables ``LANGUAGE_NAME`` and ``LANGUAGE_NAME_LOCAL``.
[ "Fix", "language", "code", "when", "set", "to", "non", "included", "default", "en", "and", "add", "the", "extra", "variables", "LANGUAGE_NAME", "and", "LANGUAGE_NAME_LOCAL", "." ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/context_serializer.py#L69-L83
noirbizarre/django.js
djangojs/context_serializer.py
ContextSerializer.handle_user
def handle_user(self, data): ''' Insert user informations in data Override it to add extra user attributes. ''' # Default to unauthenticated anonymous user data['user'] = { 'username': '', 'is_authenticated': False, 'is_staff': False, ...
python
def handle_user(self, data): ''' Insert user informations in data Override it to add extra user attributes. ''' # Default to unauthenticated anonymous user data['user'] = { 'username': '', 'is_authenticated': False, 'is_staff': False, ...
[ "def", "handle_user", "(", "self", ",", "data", ")", ":", "# Default to unauthenticated anonymous user", "data", "[", "'user'", "]", "=", "{", "'username'", ":", "''", ",", "'is_authenticated'", ":", "False", ",", "'is_staff'", ":", "False", ",", "'is_superuser'...
Insert user informations in data Override it to add extra user attributes.
[ "Insert", "user", "informations", "in", "data" ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/context_serializer.py#L85-L111
noirbizarre/django.js
djangojs/utils.py
class_from_string
def class_from_string(name): ''' Get a python class object from its name ''' module_name, class_name = name.rsplit('.', 1) __import__(module_name) module = sys.modules[module_name] return getattr(module, class_name)
python
def class_from_string(name): ''' Get a python class object from its name ''' module_name, class_name = name.rsplit('.', 1) __import__(module_name) module = sys.modules[module_name] return getattr(module, class_name)
[ "def", "class_from_string", "(", "name", ")", ":", "module_name", ",", "class_name", "=", "name", ".", "rsplit", "(", "'.'", ",", "1", ")", "__import__", "(", "module_name", ")", "module", "=", "sys", ".", "modules", "[", "module_name", "]", "return", "g...
Get a python class object from its name
[ "Get", "a", "python", "class", "object", "from", "its", "name" ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/utils.py#L27-L34
noirbizarre/django.js
djangojs/utils.py
StorageGlobber.glob
def glob(cls, files=None): ''' Glob a pattern or a list of pattern static storage relative(s). ''' files = files or [] if isinstance(files, str): files = os.path.normpath(files) matches = lambda path: matches_patterns(path, [files]) return [pat...
python
def glob(cls, files=None): ''' Glob a pattern or a list of pattern static storage relative(s). ''' files = files or [] if isinstance(files, str): files = os.path.normpath(files) matches = lambda path: matches_patterns(path, [files]) return [pat...
[ "def", "glob", "(", "cls", ",", "files", "=", "None", ")", ":", "files", "=", "files", "or", "[", "]", "if", "isinstance", "(", "files", ",", "str", ")", ":", "files", "=", "os", ".", "path", ".", "normpath", "(", "files", ")", "matches", "=", ...
Glob a pattern or a list of pattern static storage relative(s).
[ "Glob", "a", "pattern", "or", "a", "list", "of", "pattern", "static", "storage", "relative", "(", "s", ")", "." ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/utils.py#L54-L69
noirbizarre/django.js
djangojs/runners.py
PhantomJsRunner.execute
def execute(self, command): ''' Execute a subprocess yielding output lines ''' process = Popen(command, stdout=PIPE, stderr=STDOUT, universal_newlines=True) while True: if process.poll() is not None: self.returncode = process.returncode # pylint: disa...
python
def execute(self, command): ''' Execute a subprocess yielding output lines ''' process = Popen(command, stdout=PIPE, stderr=STDOUT, universal_newlines=True) while True: if process.poll() is not None: self.returncode = process.returncode # pylint: disa...
[ "def", "execute", "(", "self", ",", "command", ")", ":", "process", "=", "Popen", "(", "command", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "STDOUT", ",", "universal_newlines", "=", "True", ")", "while", "True", ":", "if", "process", ".", "poll",...
Execute a subprocess yielding output lines
[ "Execute", "a", "subprocess", "yielding", "output", "lines" ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/runners.py#L99-L108
noirbizarre/django.js
djangojs/runners.py
PhantomJsRunner.phantomjs
def phantomjs(self, *args, **kwargs): ''' Execute PhantomJS by giving ``args`` as command line arguments. If test are run in verbose mode (``-v/--verbosity`` = 2), it output: - the title as header (with separators before and after) - modules and test names - assert...
python
def phantomjs(self, *args, **kwargs): ''' Execute PhantomJS by giving ``args`` as command line arguments. If test are run in verbose mode (``-v/--verbosity`` = 2), it output: - the title as header (with separators before and after) - modules and test names - assert...
[ "def", "phantomjs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "separator", "=", "'='", "*", "LINE_SIZE", "title", "=", "kwargs", "[", "'title'", "]", "if", "'title'", "in", "kwargs", "else", "'phantomjs output'", "nb_spaces", "=",...
Execute PhantomJS by giving ``args`` as command line arguments. If test are run in verbose mode (``-v/--verbosity`` = 2), it output: - the title as header (with separators before and after) - modules and test names - assertions results (with ``django.utils.termcolors`` support) ...
[ "Execute", "PhantomJS", "by", "giving", "args", "as", "command", "line", "arguments", "." ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/runners.py#L110-L152
noirbizarre/django.js
djangojs/runners.py
PhantomJsRunner.run_suite
def run_suite(self): ''' Run a phantomjs test suite. - ``phantomjs_runner`` is mandatory. - Either ``url`` or ``url_name`` needs to be defined. ''' if not self.phantomjs_runner: raise JsTestException('phantomjs_runner need to be defined') url = sel...
python
def run_suite(self): ''' Run a phantomjs test suite. - ``phantomjs_runner`` is mandatory. - Either ``url`` or ``url_name`` needs to be defined. ''' if not self.phantomjs_runner: raise JsTestException('phantomjs_runner need to be defined') url = sel...
[ "def", "run_suite", "(", "self", ")", ":", "if", "not", "self", ".", "phantomjs_runner", ":", "raise", "JsTestException", "(", "'phantomjs_runner need to be defined'", ")", "url", "=", "self", ".", "get_url", "(", ")", "self", ".", "phantomjs", "(", "self", ...
Run a phantomjs test suite. - ``phantomjs_runner`` is mandatory. - Either ``url`` or ``url_name`` needs to be defined.
[ "Run", "a", "phantomjs", "test", "suite", "." ]
train
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/runners.py#L154-L167
frictionlessdata/tableschema-sql-py
tableschema_sql/writer.py
Writer.write
def write(self, rows, keyed=False): """Write rows/keyed_rows to table """ for row in rows: keyed_row = row if not keyed: keyed_row = dict(zip(self.__schema.field_names, row)) keyed_row = self.__convert_row(keyed_row) if self.__check...
python
def write(self, rows, keyed=False): """Write rows/keyed_rows to table """ for row in rows: keyed_row = row if not keyed: keyed_row = dict(zip(self.__schema.field_names, row)) keyed_row = self.__convert_row(keyed_row) if self.__check...
[ "def", "write", "(", "self", ",", "rows", ",", "keyed", "=", "False", ")", ":", "for", "row", "in", "rows", ":", "keyed_row", "=", "row", "if", "not", "keyed", ":", "keyed_row", "=", "dict", "(", "zip", "(", "self", ".", "__schema", ".", "field_nam...
Write rows/keyed_rows to table
[ "Write", "rows", "/", "keyed_rows", "to", "table" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/writer.py#L32-L52
frictionlessdata/tableschema-sql-py
tableschema_sql/writer.py
Writer.__prepare_bloom
def __prepare_bloom(self): """Prepare bloom for existing checks """ self.__bloom = pybloom_live.ScalableBloomFilter() columns = [getattr(self.__table.c, key) for key in self.__update_keys] keys = select(columns).execution_options(stream_results=True).execute() for key in ...
python
def __prepare_bloom(self): """Prepare bloom for existing checks """ self.__bloom = pybloom_live.ScalableBloomFilter() columns = [getattr(self.__table.c, key) for key in self.__update_keys] keys = select(columns).execution_options(stream_results=True).execute() for key in ...
[ "def", "__prepare_bloom", "(", "self", ")", ":", "self", ".", "__bloom", "=", "pybloom_live", ".", "ScalableBloomFilter", "(", ")", "columns", "=", "[", "getattr", "(", "self", ".", "__table", ".", "c", ",", "key", ")", "for", "key", "in", "self", ".",...
Prepare bloom for existing checks
[ "Prepare", "bloom", "for", "existing", "checks" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/writer.py#L56-L63
frictionlessdata/tableschema-sql-py
tableschema_sql/writer.py
Writer.__insert
def __insert(self): """Insert rows to table """ if len(self.__buffer) > 0: # Insert data statement = self.__table.insert() if self.__autoincrement: statement = statement.returning( getattr(self.__table.c, self.__autoincremen...
python
def __insert(self): """Insert rows to table """ if len(self.__buffer) > 0: # Insert data statement = self.__table.insert() if self.__autoincrement: statement = statement.returning( getattr(self.__table.c, self.__autoincremen...
[ "def", "__insert", "(", "self", ")", ":", "if", "len", "(", "self", ".", "__buffer", ")", ">", "0", ":", "# Insert data", "statement", "=", "self", ".", "__table", ".", "insert", "(", ")", "if", "self", ".", "__autoincrement", ":", "statement", "=", ...
Insert rows to table
[ "Insert", "rows", "to", "table" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/writer.py#L65-L84
frictionlessdata/tableschema-sql-py
tableschema_sql/writer.py
Writer.__update
def __update(self, row): """Update rows in table """ expr = self.__table.update().values(row) for key in self.__update_keys: expr = expr.where(getattr(self.__table.c, key) == row[key]) if self.__autoincrement: expr = expr.returning(getattr(self.__table.c, ...
python
def __update(self, row): """Update rows in table """ expr = self.__table.update().values(row) for key in self.__update_keys: expr = expr.where(getattr(self.__table.c, key) == row[key]) if self.__autoincrement: expr = expr.returning(getattr(self.__table.c, ...
[ "def", "__update", "(", "self", ",", "row", ")", ":", "expr", "=", "self", ".", "__table", ".", "update", "(", ")", ".", "values", "(", "row", ")", "for", "key", "in", "self", ".", "__update_keys", ":", "expr", "=", "expr", ".", "where", "(", "ge...
Update rows in table
[ "Update", "rows", "in", "table" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/writer.py#L86-L101
frictionlessdata/tableschema-sql-py
tableschema_sql/writer.py
Writer.__check_existing
def __check_existing(self, row): """Check if row exists in table """ if self.__update_keys is not None: key = tuple(row[key] for key in self.__update_keys) if key in self.__bloom: return True self.__bloom.add(key) return False ...
python
def __check_existing(self, row): """Check if row exists in table """ if self.__update_keys is not None: key = tuple(row[key] for key in self.__update_keys) if key in self.__bloom: return True self.__bloom.add(key) return False ...
[ "def", "__check_existing", "(", "self", ",", "row", ")", ":", "if", "self", ".", "__update_keys", "is", "not", "None", ":", "key", "=", "tuple", "(", "row", "[", "key", "]", "for", "key", "in", "self", ".", "__update_keys", ")", "if", "key", "in", ...
Check if row exists in table
[ "Check", "if", "row", "exists", "in", "table" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/writer.py#L103-L112
frictionlessdata/tableschema-sql-py
tableschema_sql/storage.py
Storage.buckets
def buckets(self): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ buckets = [] for table in self.__metadata.sorted_tables: bucket = self.__mapper.restore_bucket(table.name) if bucket is not None: buckets.append(bucket) ...
python
def buckets(self): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ buckets = [] for table in self.__metadata.sorted_tables: bucket = self.__mapper.restore_bucket(table.name) if bucket is not None: buckets.append(bucket) ...
[ "def", "buckets", "(", "self", ")", ":", "buckets", "=", "[", "]", "for", "table", "in", "self", ".", "__metadata", ".", "sorted_tables", ":", "bucket", "=", "self", ".", "__mapper", ".", "restore_bucket", "(", "table", ".", "name", ")", "if", "bucket"...
https://github.com/frictionlessdata/tableschema-sql-py#storage
[ "https", ":", "//", "github", ".", "com", "/", "frictionlessdata", "/", "tableschema", "-", "sql", "-", "py#storage" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/storage.py#L57-L65
frictionlessdata/tableschema-sql-py
tableschema_sql/storage.py
Storage.create
def create(self, bucket, descriptor, force=False, indexes_fields=None): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Make lists buckets = bucket if isinstance(bucket, six.string_types): buckets = [bucket] descriptors = descriptor ...
python
def create(self, bucket, descriptor, force=False, indexes_fields=None): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Make lists buckets = bucket if isinstance(bucket, six.string_types): buckets = [bucket] descriptors = descriptor ...
[ "def", "create", "(", "self", ",", "bucket", ",", "descriptor", ",", "force", "=", "False", ",", "indexes_fields", "=", "None", ")", ":", "# Make lists", "buckets", "=", "bucket", "if", "isinstance", "(", "bucket", ",", "six", ".", "string_types", ")", "...
https://github.com/frictionlessdata/tableschema-sql-py#storage
[ "https", ":", "//", "github", ".", "com", "/", "frictionlessdata", "/", "tableschema", "-", "sql", "-", "py#storage" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/storage.py#L67-L107
frictionlessdata/tableschema-sql-py
tableschema_sql/storage.py
Storage.delete
def delete(self, bucket=None, ignore=False): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Make lists buckets = bucket if isinstance(bucket, six.string_types): buckets = [bucket] elif bucket is None: buckets = reversed(se...
python
def delete(self, bucket=None, ignore=False): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Make lists buckets = bucket if isinstance(bucket, six.string_types): buckets = [bucket] elif bucket is None: buckets = reversed(se...
[ "def", "delete", "(", "self", ",", "bucket", "=", "None", ",", "ignore", "=", "False", ")", ":", "# Make lists", "buckets", "=", "bucket", "if", "isinstance", "(", "bucket", ",", "six", ".", "string_types", ")", ":", "buckets", "=", "[", "bucket", "]",...
https://github.com/frictionlessdata/tableschema-sql-py#storage
[ "https", ":", "//", "github", ".", "com", "/", "frictionlessdata", "/", "tableschema", "-", "sql", "-", "py#storage" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/storage.py#L109-L142
frictionlessdata/tableschema-sql-py
tableschema_sql/storage.py
Storage.describe
def describe(self, bucket, descriptor=None): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Set descriptor if descriptor is not None: self.__descriptors[bucket] = descriptor # Get descriptor else: descriptor = self.__desc...
python
def describe(self, bucket, descriptor=None): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Set descriptor if descriptor is not None: self.__descriptors[bucket] = descriptor # Get descriptor else: descriptor = self.__desc...
[ "def", "describe", "(", "self", ",", "bucket", ",", "descriptor", "=", "None", ")", ":", "# Set descriptor", "if", "descriptor", "is", "not", "None", ":", "self", ".", "__descriptors", "[", "bucket", "]", "=", "descriptor", "# Get descriptor", "else", ":", ...
https://github.com/frictionlessdata/tableschema-sql-py#storage
[ "https", ":", "//", "github", ".", "com", "/", "frictionlessdata", "/", "tableschema", "-", "sql", "-", "py#storage" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/storage.py#L144-L160
frictionlessdata/tableschema-sql-py
tableschema_sql/storage.py
Storage.iter
def iter(self, bucket): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Get table and fallbacks table = self.__get_table(bucket) schema = tableschema.Schema(self.describe(bucket)) # Open and close transaction with self.__connection.begin(...
python
def iter(self, bucket): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Get table and fallbacks table = self.__get_table(bucket) schema = tableschema.Schema(self.describe(bucket)) # Open and close transaction with self.__connection.begin(...
[ "def", "iter", "(", "self", ",", "bucket", ")", ":", "# Get table and fallbacks", "table", "=", "self", ".", "__get_table", "(", "bucket", ")", "schema", "=", "tableschema", ".", "Schema", "(", "self", ".", "describe", "(", "bucket", ")", ")", "# Open and ...
https://github.com/frictionlessdata/tableschema-sql-py#storage
[ "https", ":", "//", "github", ".", "com", "/", "frictionlessdata", "/", "tableschema", "-", "sql", "-", "py#storage" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/storage.py#L162-L178
frictionlessdata/tableschema-sql-py
tableschema_sql/storage.py
Storage.write
def write(self, bucket, rows, keyed=False, as_generator=False, update_keys=None): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Check update keys if update_keys is not None and len(update_keys) == 0: message = 'Argument "update_keys" cannot be an em...
python
def write(self, bucket, rows, keyed=False, as_generator=False, update_keys=None): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Check update keys if update_keys is not None and len(update_keys) == 0: message = 'Argument "update_keys" cannot be an em...
[ "def", "write", "(", "self", ",", "bucket", ",", "rows", ",", "keyed", "=", "False", ",", "as_generator", "=", "False", ",", "update_keys", "=", "None", ")", ":", "# Check update keys", "if", "update_keys", "is", "not", "None", "and", "len", "(", "update...
https://github.com/frictionlessdata/tableschema-sql-py#storage
[ "https", ":", "//", "github", ".", "com", "/", "frictionlessdata", "/", "tableschema", "-", "sql", "-", "py#storage" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/storage.py#L186-L207
frictionlessdata/tableschema-sql-py
tableschema_sql/storage.py
Storage.__get_table
def __get_table(self, bucket): """Get table by bucket """ table_name = self.__mapper.convert_bucket(bucket) if self.__dbschema: table_name = '.'.join((self.__dbschema, table_name)) return self.__metadata.tables[table_name]
python
def __get_table(self, bucket): """Get table by bucket """ table_name = self.__mapper.convert_bucket(bucket) if self.__dbschema: table_name = '.'.join((self.__dbschema, table_name)) return self.__metadata.tables[table_name]
[ "def", "__get_table", "(", "self", ",", "bucket", ")", ":", "table_name", "=", "self", ".", "__mapper", ".", "convert_bucket", "(", "bucket", ")", "if", "self", ".", "__dbschema", ":", "table_name", "=", "'.'", ".", "join", "(", "(", "self", ".", "__db...
Get table by bucket
[ "Get", "table", "by", "bucket" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/storage.py#L211-L217
frictionlessdata/tableschema-sql-py
tableschema_sql/storage.py
Storage.__reflect
def __reflect(self): """Reflect metadata """ def only(name, _): return self.__only(name) and self.__mapper.restore_bucket(name) is not None self.__metadata.reflect(only=only)
python
def __reflect(self): """Reflect metadata """ def only(name, _): return self.__only(name) and self.__mapper.restore_bucket(name) is not None self.__metadata.reflect(only=only)
[ "def", "__reflect", "(", "self", ")", ":", "def", "only", "(", "name", ",", "_", ")", ":", "return", "self", ".", "__only", "(", "name", ")", "and", "self", ".", "__mapper", ".", "restore_bucket", "(", "name", ")", "is", "not", "None", "self", ".",...
Reflect metadata
[ "Reflect", "metadata" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/storage.py#L219-L226
frictionlessdata/tableschema-sql-py
tableschema_sql/mapper.py
_get_field_comment
def _get_field_comment(field, separator=' - '): """ Create SQL comment from field's title and description :param field: tableschema-py Field, with optional 'title' and 'description' values :param separator: :return: >>> _get_field_comment(tableschema.Field({'title': 'my_title', 'description': ...
python
def _get_field_comment(field, separator=' - '): """ Create SQL comment from field's title and description :param field: tableschema-py Field, with optional 'title' and 'description' values :param separator: :return: >>> _get_field_comment(tableschema.Field({'title': 'my_title', 'description': ...
[ "def", "_get_field_comment", "(", "field", ",", "separator", "=", "' - '", ")", ":", "title", "=", "field", ".", "descriptor", ".", "get", "(", "'title'", ")", "or", "''", "description", "=", "field", ".", "descriptor", ".", "get", "(", "'description'", ...
Create SQL comment from field's title and description :param field: tableschema-py Field, with optional 'title' and 'description' values :param separator: :return: >>> _get_field_comment(tableschema.Field({'title': 'my_title', 'description': 'my_desc'})) 'my_title - my_desc' >>> _get_field_com...
[ "Create", "SQL", "comment", "from", "field", "s", "title", "and", "description" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/mapper.py#L281-L300
frictionlessdata/tableschema-sql-py
tableschema_sql/mapper.py
Mapper.convert_descriptor
def convert_descriptor(self, bucket, descriptor, index_fields=[], autoincrement=None): """Convert descriptor to SQL """ # Prepare columns = [] indexes = [] fallbacks = [] constraints = [] column_mapping = {} table_name = self.convert_bucket(bucket...
python
def convert_descriptor(self, bucket, descriptor, index_fields=[], autoincrement=None): """Convert descriptor to SQL """ # Prepare columns = [] indexes = [] fallbacks = [] constraints = [] column_mapping = {} table_name = self.convert_bucket(bucket...
[ "def", "convert_descriptor", "(", "self", ",", "bucket", ",", "descriptor", ",", "index_fields", "=", "[", "]", ",", "autoincrement", "=", "None", ")", ":", "# Prepare", "columns", "=", "[", "]", "indexes", "=", "[", "]", "fallbacks", "=", "[", "]", "c...
Convert descriptor to SQL
[ "Convert", "descriptor", "to", "SQL" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/mapper.py#L32-L104
frictionlessdata/tableschema-sql-py
tableschema_sql/mapper.py
Mapper.convert_row
def convert_row(self, keyed_row, schema, fallbacks): """Convert row to SQL """ for key, value in list(keyed_row.items()): field = schema.get_field(key) if not field: del keyed_row[key] if key in fallbacks: value = _uncast_value(...
python
def convert_row(self, keyed_row, schema, fallbacks): """Convert row to SQL """ for key, value in list(keyed_row.items()): field = schema.get_field(key) if not field: del keyed_row[key] if key in fallbacks: value = _uncast_value(...
[ "def", "convert_row", "(", "self", ",", "keyed_row", ",", "schema", ",", "fallbacks", ")", ":", "for", "key", ",", "value", "in", "list", "(", "keyed_row", ".", "items", "(", ")", ")", ":", "field", "=", "schema", ".", "get_field", "(", "key", ")", ...
Convert row to SQL
[ "Convert", "row", "to", "SQL" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/mapper.py#L106-L118
frictionlessdata/tableschema-sql-py
tableschema_sql/mapper.py
Mapper.convert_type
def convert_type(self, type): """Convert type to SQL """ # Default dialect mapping = { 'any': sa.Text, 'array': None, 'boolean': sa.Boolean, 'date': sa.Date, 'datetime': sa.DateTime, 'duration': None, 'g...
python
def convert_type(self, type): """Convert type to SQL """ # Default dialect mapping = { 'any': sa.Text, 'array': None, 'boolean': sa.Boolean, 'date': sa.Date, 'datetime': sa.DateTime, 'duration': None, 'g...
[ "def", "convert_type", "(", "self", ",", "type", ")", ":", "# Default dialect", "mapping", "=", "{", "'any'", ":", "sa", ".", "Text", ",", "'array'", ":", "None", ",", "'boolean'", ":", "sa", ".", "Boolean", ",", "'date'", ":", "sa", ".", "Date", ","...
Convert type to SQL
[ "Convert", "type", "to", "SQL" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/mapper.py#L120-L157
frictionlessdata/tableschema-sql-py
tableschema_sql/mapper.py
Mapper.restore_bucket
def restore_bucket(self, table_name): """Restore bucket from SQL """ if table_name.startswith(self.__prefix): return table_name.replace(self.__prefix, '', 1) return None
python
def restore_bucket(self, table_name): """Restore bucket from SQL """ if table_name.startswith(self.__prefix): return table_name.replace(self.__prefix, '', 1) return None
[ "def", "restore_bucket", "(", "self", ",", "table_name", ")", ":", "if", "table_name", ".", "startswith", "(", "self", ".", "__prefix", ")", ":", "return", "table_name", ".", "replace", "(", "self", ".", "__prefix", ",", "''", ",", "1", ")", "return", ...
Restore bucket from SQL
[ "Restore", "bucket", "from", "SQL" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/mapper.py#L159-L164
frictionlessdata/tableschema-sql-py
tableschema_sql/mapper.py
Mapper.restore_descriptor
def restore_descriptor(self, table_name, columns, constraints, autoincrement_column=None): """Restore descriptor from SQL """ # Fields fields = [] for column in columns: if column.name == autoincrement_column: continue field_type = self.re...
python
def restore_descriptor(self, table_name, columns, constraints, autoincrement_column=None): """Restore descriptor from SQL """ # Fields fields = [] for column in columns: if column.name == autoincrement_column: continue field_type = self.re...
[ "def", "restore_descriptor", "(", "self", ",", "table_name", ",", "columns", ",", "constraints", ",", "autoincrement_column", "=", "None", ")", ":", "# Fields", "fields", "=", "[", "]", "for", "column", "in", "columns", ":", "if", "column", ".", "name", "=...
Restore descriptor from SQL
[ "Restore", "descriptor", "from", "SQL" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/mapper.py#L166-L221
frictionlessdata/tableschema-sql-py
tableschema_sql/mapper.py
Mapper.restore_row
def restore_row(self, row, schema): """Restore row from SQL """ row = list(row) for index, field in enumerate(schema.fields): if self.__dialect == 'postgresql': if field.type in ['array', 'object']: continue row[index] = field.c...
python
def restore_row(self, row, schema): """Restore row from SQL """ row = list(row) for index, field in enumerate(schema.fields): if self.__dialect == 'postgresql': if field.type in ['array', 'object']: continue row[index] = field.c...
[ "def", "restore_row", "(", "self", ",", "row", ",", "schema", ")", ":", "row", "=", "list", "(", "row", ")", "for", "index", ",", "field", "in", "enumerate", "(", "schema", ".", "fields", ")", ":", "if", "self", ".", "__dialect", "==", "'postgresql'"...
Restore row from SQL
[ "Restore", "row", "from", "SQL" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/mapper.py#L223-L232
frictionlessdata/tableschema-sql-py
tableschema_sql/mapper.py
Mapper.restore_type
def restore_type(self, type): """Restore type from SQL """ # All dialects mapping = { ARRAY: 'array', sa.Boolean: 'boolean', sa.Date: 'date', sa.DateTime: 'datetime', sa.Float: 'number', sa.Integer: 'integer', ...
python
def restore_type(self, type): """Restore type from SQL """ # All dialects mapping = { ARRAY: 'array', sa.Boolean: 'boolean', sa.Date: 'date', sa.DateTime: 'datetime', sa.Float: 'number', sa.Integer: 'integer', ...
[ "def", "restore_type", "(", "self", ",", "type", ")", ":", "# All dialects", "mapping", "=", "{", "ARRAY", ":", "'array'", ",", "sa", ".", "Boolean", ":", "'boolean'", ",", "sa", ".", "Date", ":", "'date'", ",", "sa", ".", "DateTime", ":", "'datetime'"...
Restore type from SQL
[ "Restore", "type", "from", "SQL" ]
train
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/mapper.py#L234-L266
varunsrin/one-py
onepy/onmanager.py
ONProcess.open_hierarchy
def open_hierarchy(self, path, relative_to_object_id, object_id, create_file_type=0): """ CreateFileType 0 - Creates no new object. 1 - Creates a notebook with the specified name at the specified location. 2 - Creates a section group with the specified name at the specifi...
python
def open_hierarchy(self, path, relative_to_object_id, object_id, create_file_type=0): """ CreateFileType 0 - Creates no new object. 1 - Creates a notebook with the specified name at the specified location. 2 - Creates a section group with the specified name at the specifi...
[ "def", "open_hierarchy", "(", "self", ",", "path", ",", "relative_to_object_id", ",", "object_id", ",", "create_file_type", "=", "0", ")", ":", "try", ":", "return", "(", "self", ".", "process", ".", "OpenHierarchy", "(", "path", ",", "relative_to_object_id", ...
CreateFileType 0 - Creates no new object. 1 - Creates a notebook with the specified name at the specified location. 2 - Creates a section group with the specified name at the specified location. 3 - Creates a section with the specified name at the specified location.
[ "CreateFileType", "0", "-", "Creates", "no", "new", "object", ".", "1", "-", "Creates", "a", "notebook", "with", "the", "specified", "name", "at", "the", "specified", "location", ".", "2", "-", "Creates", "a", "section", "group", "with", "the", "specified"...
train
https://github.com/varunsrin/one-py/blob/8fcf021bcf776a1802a69f50dfd180daf83536ff/onepy/onmanager.py#L53-L65
varunsrin/one-py
onepy/onmanager.py
ONProcess.create_new_page
def create_new_page (self, section_id, new_page_style=0): """ NewPageStyle 0 - Create a Page that has Default Page Style 1 - Create a blank page with no title 2 - Createa blank page that has no title """ try: self.process.CreateNewPage(section_...
python
def create_new_page (self, section_id, new_page_style=0): """ NewPageStyle 0 - Create a Page that has Default Page Style 1 - Create a blank page with no title 2 - Createa blank page that has no title """ try: self.process.CreateNewPage(section_...
[ "def", "create_new_page", "(", "self", ",", "section_id", ",", "new_page_style", "=", "0", ")", ":", "try", ":", "self", ".", "process", ".", "CreateNewPage", "(", "section_id", ",", "\"\"", ",", "new_page_style", ")", "except", "Exception", "as", "e", ":"...
NewPageStyle 0 - Create a Page that has Default Page Style 1 - Create a blank page with no title 2 - Createa blank page that has no title
[ "NewPageStyle", "0", "-", "Create", "a", "Page", "that", "has", "Default", "Page", "Style", "1", "-", "Create", "a", "blank", "page", "with", "no", "title", "2", "-", "Createa", "blank", "page", "that", "has", "no", "title" ]
train
https://github.com/varunsrin/one-py/blob/8fcf021bcf776a1802a69f50dfd180daf83536ff/onepy/onmanager.py#L75-L86
varunsrin/one-py
onepy/onmanager.py
ONProcess.get_page_content
def get_page_content(self, page_id, page_info=0): """ PageInfo 0 - Returns only basic page content, without selection markup and binary data objects. This is the standard value to pass. 1 - Returns page content with no selection markup, but with all binary data. 2 - Retur...
python
def get_page_content(self, page_id, page_info=0): """ PageInfo 0 - Returns only basic page content, without selection markup and binary data objects. This is the standard value to pass. 1 - Returns page content with no selection markup, but with all binary data. 2 - Retur...
[ "def", "get_page_content", "(", "self", ",", "page_id", ",", "page_info", "=", "0", ")", ":", "try", ":", "return", "(", "self", ".", "process", ".", "GetPageContent", "(", "page_id", ",", "\"\"", ",", "page_info", ")", ")", "except", "Exception", "as", ...
PageInfo 0 - Returns only basic page content, without selection markup and binary data objects. This is the standard value to pass. 1 - Returns page content with no selection markup, but with all binary data. 2 - Returns page content with selection markup, but no binary data. 3 -...
[ "PageInfo", "0", "-", "Returns", "only", "basic", "page", "content", "without", "selection", "markup", "and", "binary", "data", "objects", ".", "This", "is", "the", "standard", "value", "to", "pass", ".", "1", "-", "Returns", "page", "content", "with", "no...
train
https://github.com/varunsrin/one-py/blob/8fcf021bcf776a1802a69f50dfd180daf83536ff/onepy/onmanager.py#L95-L107
varunsrin/one-py
onepy/onmanager.py
ONProcess.publish
def publish(self, hierarchy_id, target_file_path, publish_format, clsid_of_exporter=""): """ PublishFormat 0 - Published page is in .one format. 1 - Published page is in .onea format. 2 - Published page is in .mht format. 3 - Published page is in .pdf format. ...
python
def publish(self, hierarchy_id, target_file_path, publish_format, clsid_of_exporter=""): """ PublishFormat 0 - Published page is in .one format. 1 - Published page is in .onea format. 2 - Published page is in .mht format. 3 - Published page is in .pdf format. ...
[ "def", "publish", "(", "self", ",", "hierarchy_id", ",", "target_file_path", ",", "publish_format", ",", "clsid_of_exporter", "=", "\"\"", ")", ":", "try", ":", "self", ".", "process", ".", "Publish", "(", "hierarchy_id", ",", "target_file_path", ",", "publish...
PublishFormat 0 - Published page is in .one format. 1 - Published page is in .onea format. 2 - Published page is in .mht format. 3 - Published page is in .pdf format. 4 - Published page is in .xps format. 5 - Published page is in .doc or .docx format. ...
[ "PublishFormat", "0", "-", "Published", "page", "is", "in", ".", "one", "format", ".", "1", "-", "Published", "page", "is", "in", ".", "onea", "format", ".", "2", "-", "Published", "page", "is", "in", ".", "mht", "format", ".", "3", "-", "Published",...
train
https://github.com/varunsrin/one-py/blob/8fcf021bcf776a1802a69f50dfd180daf83536ff/onepy/onmanager.py#L141-L156
varunsrin/one-py
onepy/onmanager.py
ONProcess.get_special_location
def get_special_location(self, special_location=0): """ SpecialLocation 0 - Gets the path to the Backup Folders folder location. 1 - Gets the path to the Unfiled Notes folder location. 2 - Gets the path to the Default Notebook folder location. """ try: ...
python
def get_special_location(self, special_location=0): """ SpecialLocation 0 - Gets the path to the Backup Folders folder location. 1 - Gets the path to the Unfiled Notes folder location. 2 - Gets the path to the Default Notebook folder location. """ try: ...
[ "def", "get_special_location", "(", "self", ",", "special_location", "=", "0", ")", ":", "try", ":", "return", "(", "self", ".", "process", ".", "GetSpecialLocation", "(", "special_location", ")", ")", "except", "Exception", "as", "e", ":", "print", "(", "...
SpecialLocation 0 - Gets the path to the Backup Folders folder location. 1 - Gets the path to the Unfiled Notes folder location. 2 - Gets the path to the Default Notebook folder location.
[ "SpecialLocation", "0", "-", "Gets", "the", "path", "to", "the", "Backup", "Folders", "folder", "location", ".", "1", "-", "Gets", "the", "path", "to", "the", "Unfiled", "Notes", "folder", "location", ".", "2", "-", "Gets", "the", "path", "to", "the", ...
train
https://github.com/varunsrin/one-py/blob/8fcf021bcf776a1802a69f50dfd180daf83536ff/onepy/onmanager.py#L179-L190
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
memory
def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory()._asdict().items(): mem_info[k] = i...
python
def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory()._asdict().items(): mem_info[k] = i...
[ "def", "memory", "(", ")", ":", "mem_info", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "psutil", ".", "virtual_memory", "(", ")", ".", "_asdict", "(", ")", ".", "items", "(", ")", ":", "mem_info", "[", "k", "]", "=", "int", "(", "v", ...
Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system.
[ "Determine", "memory", "specifications", "of", "the", "machine", "." ]
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L69-L83
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
get_chunk_size
def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of ar...
python
def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of ar...
[ "def", "get_chunk_size", "(", "N", ",", "n", ")", ":", "mem_free", "=", "memory", "(", ")", "[", "'free'", "]", "if", "mem_free", ">", "60000000", ":", "chunk_size", "=", "int", "(", "(", "(", "mem_free", "-", "10000000", ")", "*", "1000", ")", "/"...
Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_siz...
[ "Given", "a", "two", "-", "dimensional", "array", "with", "a", "dimension", "of", "size", "N", "determine", "the", "number", "of", "rows", "or", "columns", "that", "can", "fit", "into", "memory", "." ]
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L86-L127
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
get_compression_filter
def get_compression_filter(byte_counts): """Determine whether or not to use a compression on the array stored in a hierarchical data format, and which compression library to use to that purpose. Compression reduces the HDF5 file size and also helps improving I/O efficiency for large datasets...
python
def get_compression_filter(byte_counts): """Determine whether or not to use a compression on the array stored in a hierarchical data format, and which compression library to use to that purpose. Compression reduces the HDF5 file size and also helps improving I/O efficiency for large datasets...
[ "def", "get_compression_filter", "(", "byte_counts", ")", ":", "assert", "isinstance", "(", "byte_counts", ",", "numbers", ".", "Integral", ")", "and", "byte_counts", ">", "0", "if", "2", "*", "byte_counts", ">", "1000", "*", "memory", "(", ")", "[", "'fre...
Determine whether or not to use a compression on the array stored in a hierarchical data format, and which compression library to use to that purpose. Compression reduces the HDF5 file size and also helps improving I/O efficiency for large datasets. Parameters ---------- byte_co...
[ "Determine", "whether", "or", "not", "to", "use", "a", "compression", "on", "the", "array", "stored", "in", "a", "hierarchical", "data", "format", "and", "which", "compression", "library", "to", "use", "to", "that", "purpose", ".", "Compression", "reduces", ...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L130-L157
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
build_hypergraph_adjacency
def build_hypergraph_adjacency(cluster_runs): """Return the adjacency matrix to a hypergraph, in sparse matrix representation. Parameters ---------- cluster_runs : array of shape (n_partitions, n_samples) Returns ------- hypergraph_adjacency : compressed sparse row matrix R...
python
def build_hypergraph_adjacency(cluster_runs): """Return the adjacency matrix to a hypergraph, in sparse matrix representation. Parameters ---------- cluster_runs : array of shape (n_partitions, n_samples) Returns ------- hypergraph_adjacency : compressed sparse row matrix R...
[ "def", "build_hypergraph_adjacency", "(", "cluster_runs", ")", ":", "N_runs", "=", "cluster_runs", ".", "shape", "[", "0", "]", "hypergraph_adjacency", "=", "create_membership_matrix", "(", "cluster_runs", "[", "0", "]", ")", "for", "i", "in", "range", "(", "1...
Return the adjacency matrix to a hypergraph, in sparse matrix representation. Parameters ---------- cluster_runs : array of shape (n_partitions, n_samples) Returns ------- hypergraph_adjacency : compressed sparse row matrix Represents the hypergraph associated with an ensemble ...
[ "Return", "the", "adjacency", "matrix", "to", "a", "hypergraph", "in", "sparse", "matrix", "representation", ".", "Parameters", "----------", "cluster_runs", ":", "array", "of", "shape", "(", "n_partitions", "n_samples", ")", "Returns", "-------", "hypergraph_adjace...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L160-L183
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
store_hypergraph_adjacency
def store_hypergraph_adjacency(hypergraph_adjacency, hdf5_file_name): """Write an hypergraph adjacency to disk to disk in an HDF5 data structure. Parameters ---------- hypergraph_adjacency : compressed sparse row matrix hdf5_file_name : file handle or string """ assert(hypergra...
python
def store_hypergraph_adjacency(hypergraph_adjacency, hdf5_file_name): """Write an hypergraph adjacency to disk to disk in an HDF5 data structure. Parameters ---------- hypergraph_adjacency : compressed sparse row matrix hdf5_file_name : file handle or string """ assert(hypergra...
[ "def", "store_hypergraph_adjacency", "(", "hypergraph_adjacency", ",", "hdf5_file_name", ")", ":", "assert", "(", "hypergraph_adjacency", ".", "__class__", "==", "scipy", ".", "sparse", ".", "csr", ".", "csr_matrix", ")", "byte_counts", "=", "hypergraph_adjacency", ...
Write an hypergraph adjacency to disk to disk in an HDF5 data structure. Parameters ---------- hypergraph_adjacency : compressed sparse row matrix hdf5_file_name : file handle or string
[ "Write", "an", "hypergraph", "adjacency", "to", "disk", "to", "disk", "in", "an", "HDF5", "data", "structure", ".", "Parameters", "----------", "hypergraph_adjacency", ":", "compressed", "sparse", "row", "matrix", "hdf5_file_name", ":", "file", "handle", "or", "...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L186-L215
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
load_hypergraph_adjacency
def load_hypergraph_adjacency(hdf5_file_name): """ Parameters ---------- hdf5_file_name : file handle or string Returns ------- hypergraph_adjacency : compressed sparse row matrix """ with tables.open_file(hdf5_file_name, 'r+') as fileh: pars = [] for par i...
python
def load_hypergraph_adjacency(hdf5_file_name): """ Parameters ---------- hdf5_file_name : file handle or string Returns ------- hypergraph_adjacency : compressed sparse row matrix """ with tables.open_file(hdf5_file_name, 'r+') as fileh: pars = [] for par i...
[ "def", "load_hypergraph_adjacency", "(", "hdf5_file_name", ")", ":", "with", "tables", ".", "open_file", "(", "hdf5_file_name", ",", "'r+'", ")", "as", "fileh", ":", "pars", "=", "[", "]", "for", "par", "in", "(", "'data'", ",", "'indices'", ",", "'indptr'...
Parameters ---------- hdf5_file_name : file handle or string Returns ------- hypergraph_adjacency : compressed sparse row matrix
[ "Parameters", "----------", "hdf5_file_name", ":", "file", "handle", "or", "string", "Returns", "-------", "hypergraph_adjacency", ":", "compressed", "sparse", "row", "matrix" ]
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L218-L237
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
cluster_ensembles
def cluster_ensembles(cluster_runs, hdf5_file_name = None, verbose = False, N_clusters_max = None): """Call up to three different functions for heuristic ensemble clustering (namely CSPA, HGPA and MCLA) then select as the definitive consensus clustering the one with the highest average mutual informat...
python
def cluster_ensembles(cluster_runs, hdf5_file_name = None, verbose = False, N_clusters_max = None): """Call up to three different functions for heuristic ensemble clustering (namely CSPA, HGPA and MCLA) then select as the definitive consensus clustering the one with the highest average mutual informat...
[ "def", "cluster_ensembles", "(", "cluster_runs", ",", "hdf5_file_name", "=", "None", ",", "verbose", "=", "False", ",", "N_clusters_max", "=", "None", ")", ":", "if", "hdf5_file_name", "is", "None", ":", "hdf5_file_name", "=", "'./Cluster_Ensembles.h5'", "fileh", ...
Call up to three different functions for heuristic ensemble clustering (namely CSPA, HGPA and MCLA) then select as the definitive consensus clustering the one with the highest average mutual information score between its vector of consensus labels and the vectors of labels associated to each ...
[ "Call", "up", "to", "three", "different", "functions", "for", "heuristic", "ensemble", "clustering", "(", "namely", "CSPA", "HGPA", "and", "MCLA", ")", "then", "select", "as", "the", "definitive", "consensus", "clustering", "the", "one", "with", "the", "highes...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L240-L315
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
ceEvalMutual
def ceEvalMutual(cluster_runs, cluster_ensemble = None, verbose = False): """Compute a weighted average of the mutual information with the known labels, the weights being proportional to the fraction of known labels. Parameters ---------- cluster_runs : array of shape (n_partitions, n_samples)...
python
def ceEvalMutual(cluster_runs, cluster_ensemble = None, verbose = False): """Compute a weighted average of the mutual information with the known labels, the weights being proportional to the fraction of known labels. Parameters ---------- cluster_runs : array of shape (n_partitions, n_samples)...
[ "def", "ceEvalMutual", "(", "cluster_runs", ",", "cluster_ensemble", "=", "None", ",", "verbose", "=", "False", ")", ":", "if", "cluster_ensemble", "is", "None", ":", "return", "0.0", "if", "reduce", "(", "operator", ".", "mul", ",", "cluster_runs", ".", "...
Compute a weighted average of the mutual information with the known labels, the weights being proportional to the fraction of known labels. Parameters ---------- cluster_runs : array of shape (n_partitions, n_samples) Each row of this matrix is such that the i-th entry corresponds to the ...
[ "Compute", "a", "weighted", "average", "of", "the", "mutual", "information", "with", "the", "known", "labels", "the", "weights", "being", "proportional", "to", "the", "fraction", "of", "known", "labels", "." ]
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L318-L368
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
checkcl
def checkcl(cluster_run, verbose = False): """Ensure that a cluster labelling is in a valid format. Parameters ---------- cluster_run : array of shape (n_samples,) A vector of cluster IDs for each of the samples selected for a given round of clustering. The samples not selected are lab...
python
def checkcl(cluster_run, verbose = False): """Ensure that a cluster labelling is in a valid format. Parameters ---------- cluster_run : array of shape (n_samples,) A vector of cluster IDs for each of the samples selected for a given round of clustering. The samples not selected are lab...
[ "def", "checkcl", "(", "cluster_run", ",", "verbose", "=", "False", ")", ":", "cluster_run", "=", "np", ".", "asanyarray", "(", "cluster_run", ")", "if", "cluster_run", ".", "size", "==", "0", ":", "raise", "ValueError", "(", "\"\\nERROR: Cluster_Ensembles: ch...
Ensure that a cluster labelling is in a valid format. Parameters ---------- cluster_run : array of shape (n_samples,) A vector of cluster IDs for each of the samples selected for a given round of clustering. The samples not selected are labelled with NaN. verbose : Boolean, optional (...
[ "Ensure", "that", "a", "cluster", "labelling", "is", "in", "a", "valid", "format", "." ]
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L371-L430
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
one_to_max
def one_to_max(array_in): """Alter a vector of cluster labels to a dense mapping. Given that this function is herein always called after passing a vector to the function checkcl, one_to_max relies on the assumption that cluster_run does not contain any NaN entries. Parameters ---...
python
def one_to_max(array_in): """Alter a vector of cluster labels to a dense mapping. Given that this function is herein always called after passing a vector to the function checkcl, one_to_max relies on the assumption that cluster_run does not contain any NaN entries. Parameters ---...
[ "def", "one_to_max", "(", "array_in", ")", ":", "x", "=", "np", ".", "asanyarray", "(", "array_in", ")", "N_in", "=", "x", ".", "size", "array_in", "=", "x", ".", "reshape", "(", "N_in", ")", "sorted_array", "=", "np", ".", "sort", "(", "array_in", ...
Alter a vector of cluster labels to a dense mapping. Given that this function is herein always called after passing a vector to the function checkcl, one_to_max relies on the assumption that cluster_run does not contain any NaN entries. Parameters ---------- array_in : a list or ...
[ "Alter", "a", "vector", "of", "cluster", "labels", "to", "a", "dense", "mapping", ".", "Given", "that", "this", "function", "is", "herein", "always", "called", "after", "passing", "a", "vector", "to", "the", "function", "checkcl", "one_to_max", "relies", "on...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L433-L469
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
checks
def checks(similarities, verbose = False): """Check that a matrix is a proper similarity matrix and bring appropriate changes if applicable. Parameters ---------- similarities : array of shape (n_samples, n_samples) A matrix of pairwise similarities between (sub)-samples of the data-se...
python
def checks(similarities, verbose = False): """Check that a matrix is a proper similarity matrix and bring appropriate changes if applicable. Parameters ---------- similarities : array of shape (n_samples, n_samples) A matrix of pairwise similarities between (sub)-samples of the data-se...
[ "def", "checks", "(", "similarities", ",", "verbose", "=", "False", ")", ":", "if", "similarities", ".", "size", "==", "0", ":", "raise", "ValueError", "(", "\"\\nERROR: Cluster_Ensembles: checks: the similarities \"", "\"matrix provided as input happens to be empty.\\n\"",...
Check that a matrix is a proper similarity matrix and bring appropriate changes if applicable. Parameters ---------- similarities : array of shape (n_samples, n_samples) A matrix of pairwise similarities between (sub)-samples of the data-set. verbose : Boolean, optional (default = Fa...
[ "Check", "that", "a", "matrix", "is", "a", "proper", "similarity", "matrix", "and", "bring", "appropriate", "changes", "if", "applicable", "." ]
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L472-L551
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
CSPA
def CSPA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None): """Cluster-based Similarity Partitioning Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose...
python
def CSPA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None): """Cluster-based Similarity Partitioning Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose...
[ "def", "CSPA", "(", "hdf5_file_name", ",", "cluster_runs", ",", "verbose", "=", "False", ",", "N_clusters_max", "=", "None", ")", ":", "print", "(", "'*****'", ")", "print", "(", "\"INFO: Cluster_Ensembles: CSPA: consensus clustering using CSPA.\"", ")", "if", "N_cl...
Cluster-based Similarity Partitioning Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose : bool, optional (default = False) N_clusters_max : int, optional (default = ...
[ "Cluster", "-", "based", "Similarity", "Partitioning", "Algorithm", "for", "a", "consensus", "function", ".", "Parameters", "----------", "hdf5_file_name", ":", "file", "handle", "or", "string", "cluster_runs", ":", "array", "of", "shape", "(", "n_partitions", "n_...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L554-L623
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
HGPA
def HGPA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None): """HyperGraph-Partitioning Algorithm for a consensus function. Parameters ---------- hdf5_file_name : string or file handle cluster_runs: array of shape (n_partitions, n_samples) verbose : bool, option...
python
def HGPA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None): """HyperGraph-Partitioning Algorithm for a consensus function. Parameters ---------- hdf5_file_name : string or file handle cluster_runs: array of shape (n_partitions, n_samples) verbose : bool, option...
[ "def", "HGPA", "(", "hdf5_file_name", ",", "cluster_runs", ",", "verbose", "=", "False", ",", "N_clusters_max", "=", "None", ")", ":", "print", "(", "'\\n*****'", ")", "print", "(", "\"INFO: Cluster_Ensembles: HGPA: consensus clustering using HGPA.\"", ")", "if", "N...
HyperGraph-Partitioning Algorithm for a consensus function. Parameters ---------- hdf5_file_name : string or file handle cluster_runs: array of shape (n_partitions, n_samples) verbose : bool, optional (default = False) N_clusters_max : int, optional (default = None) ...
[ "HyperGraph", "-", "Partitioning", "Algorithm", "for", "a", "consensus", "function", ".", "Parameters", "----------", "hdf5_file_name", ":", "string", "or", "file", "handle", "cluster_runs", ":", "array", "of", "shape", "(", "n_partitions", "n_samples", ")", "verb...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L626-L657
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
MCLA
def MCLA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None): """Meta-CLustering Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose : bool, optional (def...
python
def MCLA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None): """Meta-CLustering Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose : bool, optional (def...
[ "def", "MCLA", "(", "hdf5_file_name", ",", "cluster_runs", ",", "verbose", "=", "False", ",", "N_clusters_max", "=", "None", ")", ":", "print", "(", "'\\n*****'", ")", "print", "(", "'INFO: Cluster_Ensembles: MCLA: consensus clustering using MCLA.'", ")", "if", "N_c...
Meta-CLustering Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose : bool, optional (default = False) N_clusters_max : int, optional (default = None) Returns...
[ "Meta", "-", "CLustering", "Algorithm", "for", "a", "consensus", "function", ".", "Parameters", "----------", "hdf5_file_name", ":", "file", "handle", "or", "string", "cluster_runs", ":", "array", "of", "shape", "(", "n_partitions", "n_samples", ")", "verbose", ...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L660-L881
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
create_membership_matrix
def create_membership_matrix(cluster_run): """For a label vector represented by cluster_run, constructs the binary membership indicator matrix. Such matrices, when concatenated, contribute to the adjacency matrix for a hypergraph representation of an ensemble of clusterings. Para...
python
def create_membership_matrix(cluster_run): """For a label vector represented by cluster_run, constructs the binary membership indicator matrix. Such matrices, when concatenated, contribute to the adjacency matrix for a hypergraph representation of an ensemble of clusterings. Para...
[ "def", "create_membership_matrix", "(", "cluster_run", ")", ":", "cluster_run", "=", "np", ".", "asanyarray", "(", "cluster_run", ")", "if", "reduce", "(", "operator", ".", "mul", ",", "cluster_run", ".", "shape", ",", "1", ")", "!=", "max", "(", "cluster_...
For a label vector represented by cluster_run, constructs the binary membership indicator matrix. Such matrices, when concatenated, contribute to the adjacency matrix for a hypergraph representation of an ensemble of clusterings. Parameters ---------- cluster_run : array of s...
[ "For", "a", "label", "vector", "represented", "by", "cluster_run", "constructs", "the", "binary", "membership", "indicator", "matrix", ".", "Such", "matrices", "when", "concatenated", "contribute", "to", "the", "adjacency", "matrix", "for", "a", "hypergraph", "rep...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L884-L919
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
metis
def metis(hdf5_file_name, N_clusters_max): """METIS algorithm by Karypis and Kumar. Partitions the induced similarity graph passed by CSPA. Parameters ---------- hdf5_file_name : string or file handle N_clusters_max : int Returns ------- labels : array of shape (n_sam...
python
def metis(hdf5_file_name, N_clusters_max): """METIS algorithm by Karypis and Kumar. Partitions the induced similarity graph passed by CSPA. Parameters ---------- hdf5_file_name : string or file handle N_clusters_max : int Returns ------- labels : array of shape (n_sam...
[ "def", "metis", "(", "hdf5_file_name", ",", "N_clusters_max", ")", ":", "file_name", "=", "wgraph", "(", "hdf5_file_name", ")", "labels", "=", "sgraph", "(", "N_clusters_max", ",", "file_name", ")", "subprocess", ".", "call", "(", "[", "'rm'", ",", "file_nam...
METIS algorithm by Karypis and Kumar. Partitions the induced similarity graph passed by CSPA. Parameters ---------- hdf5_file_name : string or file handle N_clusters_max : int Returns ------- labels : array of shape (n_samples,) A vector of labels denoting the clu...
[ "METIS", "algorithm", "by", "Karypis", "and", "Kumar", ".", "Partitions", "the", "induced", "similarity", "graph", "passed", "by", "CSPA", "." ]
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L922-L949
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
hmetis
def hmetis(hdf5_file_name, N_clusters_max, w = None): """Gives cluster labels ranging from 1 to N_clusters_max for hypergraph partitioning required for HGPA. Parameters ---------- hdf5_file_name : file handle or string N_clusters_max : int w : array, optional (default = None)...
python
def hmetis(hdf5_file_name, N_clusters_max, w = None): """Gives cluster labels ranging from 1 to N_clusters_max for hypergraph partitioning required for HGPA. Parameters ---------- hdf5_file_name : file handle or string N_clusters_max : int w : array, optional (default = None)...
[ "def", "hmetis", "(", "hdf5_file_name", ",", "N_clusters_max", ",", "w", "=", "None", ")", ":", "if", "w", "is", "None", ":", "file_name", "=", "wgraph", "(", "hdf5_file_name", ",", "None", ",", "2", ")", "else", ":", "file_name", "=", "wgraph", "(", ...
Gives cluster labels ranging from 1 to N_clusters_max for hypergraph partitioning required for HGPA. Parameters ---------- hdf5_file_name : file handle or string N_clusters_max : int w : array, optional (default = None) Returns ------- labels : array of shape (n_...
[ "Gives", "cluster", "labels", "ranging", "from", "1", "to", "N_clusters_max", "for", "hypergraph", "partitioning", "required", "for", "HGPA", "." ]
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L952-L987
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
wgraph
def wgraph(hdf5_file_name, w = None, method = 0): """Write a graph file in a format apposite to later use by METIS or HMETIS. Parameters ---------- hdf5_file_name : file handle or string w : list or array, optional (default = None) method : int, optional (default = 0) Ret...
python
def wgraph(hdf5_file_name, w = None, method = 0): """Write a graph file in a format apposite to later use by METIS or HMETIS. Parameters ---------- hdf5_file_name : file handle or string w : list or array, optional (default = None) method : int, optional (default = 0) Ret...
[ "def", "wgraph", "(", "hdf5_file_name", ",", "w", "=", "None", ",", "method", "=", "0", ")", ":", "print", "(", "'\\n#'", ")", "if", "method", "==", "0", ":", "fileh", "=", "tables", ".", "open_file", "(", "hdf5_file_name", ",", "'r+'", ")", "e_mat",...
Write a graph file in a format apposite to later use by METIS or HMETIS. Parameters ---------- hdf5_file_name : file handle or string w : list or array, optional (default = None) method : int, optional (default = 0) Returns ------- file_name : string
[ "Write", "a", "graph", "file", "in", "a", "format", "apposite", "to", "later", "use", "by", "METIS", "or", "HMETIS", ".", "Parameters", "----------", "hdf5_file_name", ":", "file", "handle", "or", "string", "w", ":", "list", "or", "array", "optional", "(",...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L1024-L1154
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
sgraph
def sgraph(N_clusters_max, file_name): """Runs METIS or hMETIS and returns the labels found by those (hyper-)graph partitioning algorithms. Parameters ---------- N_clusters_max : int file_name : string Returns ------- labels : array of shape (n_samples,) ...
python
def sgraph(N_clusters_max, file_name): """Runs METIS or hMETIS and returns the labels found by those (hyper-)graph partitioning algorithms. Parameters ---------- N_clusters_max : int file_name : string Returns ------- labels : array of shape (n_samples,) ...
[ "def", "sgraph", "(", "N_clusters_max", ",", "file_name", ")", ":", "if", "file_name", "==", "'DO_NOT_PROCESS'", ":", "return", "[", "]", "print", "(", "'\\n#'", ")", "k", "=", "str", "(", "N_clusters_max", ")", "out_name", "=", "file_name", "+", "'.part.'...
Runs METIS or hMETIS and returns the labels found by those (hyper-)graph partitioning algorithms. Parameters ---------- N_clusters_max : int file_name : string Returns ------- labels : array of shape (n_samples,) A vector of labels denoting the cluster to ...
[ "Runs", "METIS", "or", "hMETIS", "and", "returns", "the", "labels", "found", "by", "those", "(", "hyper", "-", ")", "graph", "partitioning", "algorithms", ".", "Parameters", "----------", "N_clusters_max", ":", "int", "file_name", ":", "string", "Returns", "--...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L1157-L1221
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
overlap_matrix
def overlap_matrix(hdf5_file_name, consensus_labels, cluster_runs): """Writes on disk (in an HDF5 file whose handle is provided as the first argument to this function) a stack of matrices, each describing for a particular run the overlap of cluster ID's that are matching each of the cluster ID...
python
def overlap_matrix(hdf5_file_name, consensus_labels, cluster_runs): """Writes on disk (in an HDF5 file whose handle is provided as the first argument to this function) a stack of matrices, each describing for a particular run the overlap of cluster ID's that are matching each of the cluster ID...
[ "def", "overlap_matrix", "(", "hdf5_file_name", ",", "consensus_labels", ",", "cluster_runs", ")", ":", "if", "reduce", "(", "operator", ".", "mul", ",", "cluster_runs", ".", "shape", ",", "1", ")", "==", "max", "(", "cluster_runs", ".", "shape", ")", ":",...
Writes on disk (in an HDF5 file whose handle is provided as the first argument to this function) a stack of matrices, each describing for a particular run the overlap of cluster ID's that are matching each of the cluster ID's stored in 'consensus_labels' (the vector of labels obtained by e...
[ "Writes", "on", "disk", "(", "in", "an", "HDF5", "file", "whose", "handle", "is", "provided", "as", "the", "first", "argument", "to", "this", "function", ")", "a", "stack", "of", "matrices", "each", "describing", "for", "a", "particular", "run", "the", "...
train
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L1224-L1322
9b/google-alerts
google_alerts/__init__.py
obfuscate
def obfuscate(p, action): """Obfuscate the auth details to avoid easy snatching. It's best to use a throw away account for these alerts to avoid having your authentication put at risk by storing it locally. """ key = "ru7sll3uQrGtDPcIW3okutpFLo6YYtd5bWSpbZJIopYQ0Du0a1WlhvJOaZEH" s = list() ...
python
def obfuscate(p, action): """Obfuscate the auth details to avoid easy snatching. It's best to use a throw away account for these alerts to avoid having your authentication put at risk by storing it locally. """ key = "ru7sll3uQrGtDPcIW3okutpFLo6YYtd5bWSpbZJIopYQ0Du0a1WlhvJOaZEH" s = list() ...
[ "def", "obfuscate", "(", "p", ",", "action", ")", ":", "key", "=", "\"ru7sll3uQrGtDPcIW3okutpFLo6YYtd5bWSpbZJIopYQ0Du0a1WlhvJOaZEH\"", "s", "=", "list", "(", ")", "if", "action", "==", "'store'", ":", "if", "PY2", ":", "for", "i", "in", "range", "(", "len", ...
Obfuscate the auth details to avoid easy snatching. It's best to use a throw away account for these alerts to avoid having your authentication put at risk by storing it locally.
[ "Obfuscate", "the", "auth", "details", "to", "avoid", "easy", "snatching", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L58-L85
9b/google-alerts
google_alerts/__init__.py
GoogleAlerts._config_bootstrap
def _config_bootstrap(self): """Go through and establish the defaults on the file system. The approach here was stolen from the CLI tool provided with the module. Idea being that the user should not always need to provide a username and password in order to run the script. If the config...
python
def _config_bootstrap(self): """Go through and establish the defaults on the file system. The approach here was stolen from the CLI tool provided with the module. Idea being that the user should not always need to provide a username and password in order to run the script. If the config...
[ "def", "_config_bootstrap", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "CONFIG_PATH", ")", ":", "os", ".", "makedirs", "(", "CONFIG_PATH", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "CONFIG_FILE", ")", ":...
Go through and establish the defaults on the file system. The approach here was stolen from the CLI tool provided with the module. Idea being that the user should not always need to provide a username and password in order to run the script. If the configuration file is already present ...
[ "Go", "through", "and", "establish", "the", "defaults", "on", "the", "file", "system", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L133-L162
9b/google-alerts
google_alerts/__init__.py
GoogleAlerts._session_check
def _session_check(self): """Attempt to authenticate the user through a session file. This process is done to avoid having to authenticate the user every single time. It uses a session file that is saved when a valid session is captured and then reused. Because sessions can expire, we n...
python
def _session_check(self): """Attempt to authenticate the user through a session file. This process is done to avoid having to authenticate the user every single time. It uses a session file that is saved when a valid session is captured and then reused. Because sessions can expire, we n...
[ "def", "_session_check", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "SESSION_FILE", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"Session file does not exist\"", ")", "return", "False", "with", "open", "(", "SESSION_F...
Attempt to authenticate the user through a session file. This process is done to avoid having to authenticate the user every single time. It uses a session file that is saved when a valid session is captured and then reused. Because sessions can expire, we need to test the session prior...
[ "Attempt", "to", "authenticate", "the", "user", "through", "a", "session", "file", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L164-L187
9b/google-alerts
google_alerts/__init__.py
GoogleAlerts._logger
def _logger(self): """Create a logger to be used between processes. :returns: Logging instance. """ logger = logging.getLogger(self.NAME) logger.setLevel(self.LOG_LEVEL) shandler = logging.StreamHandler(sys.stdout) fmt = '\033[1;32m%(levelname)-5s %(module)s:%(fu...
python
def _logger(self): """Create a logger to be used between processes. :returns: Logging instance. """ logger = logging.getLogger(self.NAME) logger.setLevel(self.LOG_LEVEL) shandler = logging.StreamHandler(sys.stdout) fmt = '\033[1;32m%(levelname)-5s %(module)s:%(fu...
[ "def", "_logger", "(", "self", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "self", ".", "NAME", ")", "logger", ".", "setLevel", "(", "self", ".", "LOG_LEVEL", ")", "shandler", "=", "logging", ".", "StreamHandler", "(", "sys", ".", "stdou...
Create a logger to be used between processes. :returns: Logging instance.
[ "Create", "a", "logger", "to", "be", "used", "between", "processes", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L189-L201
9b/google-alerts
google_alerts/__init__.py
GoogleAlerts.set_log_level
def set_log_level(self, level): """Override the default log level of the class""" if level == 'info': level = logging.INFO if level == 'debug': level = logging.DEBUG if level == 'error': level = logging.ERROR self._log.setLevel(level)
python
def set_log_level(self, level): """Override the default log level of the class""" if level == 'info': level = logging.INFO if level == 'debug': level = logging.DEBUG if level == 'error': level = logging.ERROR self._log.setLevel(level)
[ "def", "set_log_level", "(", "self", ",", "level", ")", ":", "if", "level", "==", "'info'", ":", "level", "=", "logging", ".", "INFO", "if", "level", "==", "'debug'", ":", "level", "=", "logging", ".", "DEBUG", "if", "level", "==", "'error'", ":", "l...
Override the default log level of the class
[ "Override", "the", "default", "log", "level", "of", "the", "class" ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L203-L211
9b/google-alerts
google_alerts/__init__.py
GoogleAlerts._process_state
def _process_state(self): """Process the application state configuration. Google Alerts manages the account information and alert data through some custom state configuration. Not all values have been completely enumerated. """ self._log.debug("Capturing state from the r...
python
def _process_state(self): """Process the application state configuration. Google Alerts manages the account information and alert data through some custom state configuration. Not all values have been completely enumerated. """ self._log.debug("Capturing state from the r...
[ "def", "_process_state", "(", "self", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"Capturing state from the request\"", ")", "response", "=", "self", ".", "_session", ".", "get", "(", "url", "=", "self", ".", "ALERTS_URL", ",", "headers", "=", "sel...
Process the application state configuration. Google Alerts manages the account information and alert data through some custom state configuration. Not all values have been completely enumerated.
[ "Process", "the", "application", "state", "configuration", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L213-L230
9b/google-alerts
google_alerts/__init__.py
GoogleAlerts.authenticate
def authenticate(self): """Authenticate the user and setup our state.""" valid = self._session_check() if self._is_authenticated and valid: self._log.debug("[!] User has already authenticated") return init = self._session.get(url=self.LOGIN_URL, headers=self.HEADE...
python
def authenticate(self): """Authenticate the user and setup our state.""" valid = self._session_check() if self._is_authenticated and valid: self._log.debug("[!] User has already authenticated") return init = self._session.get(url=self.LOGIN_URL, headers=self.HEADE...
[ "def", "authenticate", "(", "self", ")", ":", "valid", "=", "self", ".", "_session_check", "(", ")", "if", "self", ".", "_is_authenticated", "and", "valid", ":", "self", ".", "_log", ".", "debug", "(", "\"[!] User has already authenticated\"", ")", "return", ...
Authenticate the user and setup our state.
[ "Authenticate", "the", "user", "and", "setup", "our", "state", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L277-L306
9b/google-alerts
google_alerts/__init__.py
GoogleAlerts.list
def list(self, term=None): """List alerts configured for the account.""" if not self._state: raise InvalidState("State was not properly obtained from the app") self._process_state() if not self._state[1]: self._log.info("No monitors have been created yet.") ...
python
def list(self, term=None): """List alerts configured for the account.""" if not self._state: raise InvalidState("State was not properly obtained from the app") self._process_state() if not self._state[1]: self._log.info("No monitors have been created yet.") ...
[ "def", "list", "(", "self", ",", "term", "=", "None", ")", ":", "if", "not", "self", ".", "_state", ":", "raise", "InvalidState", "(", "\"State was not properly obtained from the app\"", ")", "self", ".", "_process_state", "(", ")", "if", "not", "self", ".",...
List alerts configured for the account.
[ "List", "alerts", "configured", "for", "the", "account", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L308-L337
9b/google-alerts
google_alerts/__init__.py
GoogleAlerts.create
def create(self, term, options): """Create a monitor using passed configuration.""" if not self._state: raise InvalidState("State was not properly obtained from the app") options['action'] = 'CREATE' payload = self._build_payload(term, options) url = self.ALERTS_CREAT...
python
def create(self, term, options): """Create a monitor using passed configuration.""" if not self._state: raise InvalidState("State was not properly obtained from the app") options['action'] = 'CREATE' payload = self._build_payload(term, options) url = self.ALERTS_CREAT...
[ "def", "create", "(", "self", ",", "term", ",", "options", ")", ":", "if", "not", "self", ".", "_state", ":", "raise", "InvalidState", "(", "\"State was not properly obtained from the app\"", ")", "options", "[", "'action'", "]", "=", "'CREATE'", "payload", "=...
Create a monitor using passed configuration.
[ "Create", "a", "monitor", "using", "passed", "configuration", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L339-L355
9b/google-alerts
google_alerts/__init__.py
GoogleAlerts.modify
def modify(self, monitor_id, options): """Create a monitor using passed configuration.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors obj = None for monitor in monitors...
python
def modify(self, monitor_id, options): """Create a monitor using passed configuration.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors obj = None for monitor in monitors...
[ "def", "modify", "(", "self", ",", "monitor_id", ",", "options", ")", ":", "if", "not", "self", ".", "_state", ":", "raise", "InvalidState", "(", "\"State was not properly obtained from the app\"", ")", "monitors", "=", "self", ".", "list", "(", ")", "# Get th...
Create a monitor using passed configuration.
[ "Create", "a", "monitor", "using", "passed", "configuration", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L357-L380
9b/google-alerts
google_alerts/__init__.py
GoogleAlerts.delete
def delete(self, monitor_id): """Delete a monitor by ID.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors bit = None for monitor in monitors: if monitor_id !=...
python
def delete(self, monitor_id): """Delete a monitor by ID.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors bit = None for monitor in monitors: if monitor_id !=...
[ "def", "delete", "(", "self", ",", "monitor_id", ")", ":", "if", "not", "self", ".", "_state", ":", "raise", "InvalidState", "(", "\"State was not properly obtained from the app\"", ")", "monitors", "=", "self", ".", "list", "(", ")", "# Get the latest set of moni...
Delete a monitor by ID.
[ "Delete", "a", "monitor", "by", "ID", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L382-L403
9b/google-alerts
google_alerts/cli/manage.py
main
def main(): """Run the core.""" parser = ArgumentParser() subs = parser.add_subparsers(dest='cmd') setup_parser = subs.add_parser('setup') setup_parser.add_argument('-e', '--email', dest='email', required=True, help='Email of the Google user.', type=str) setup_parse...
python
def main(): """Run the core.""" parser = ArgumentParser() subs = parser.add_subparsers(dest='cmd') setup_parser = subs.add_parser('setup') setup_parser.add_argument('-e', '--email', dest='email', required=True, help='Email of the Google user.', type=str) setup_parse...
[ "def", "main", "(", ")", ":", "parser", "=", "ArgumentParser", "(", ")", "subs", "=", "parser", ".", "add_subparsers", "(", "dest", "=", "'cmd'", ")", "setup_parser", "=", "subs", ".", "add_parser", "(", "'setup'", ")", "setup_parser", ".", "add_argument",...
Run the core.
[ "Run", "the", "core", "." ]
train
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/cli/manage.py#L65-L166
r1chardj0n3s/pip-check-reqs
pip_check_reqs/common.py
search_packages_info
def search_packages_info(query): """ Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. """ installed = {} for p in pkg_re...
python
def search_packages_info(query): """ Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. """ installed = {} for p in pkg_re...
[ "def", "search_packages_info", "(", "query", ")", ":", "installed", "=", "{", "}", "for", "p", "in", "pkg_resources", ".", "working_set", ":", "installed", "[", "canonicalize_name", "(", "p", ".", "project_name", ")", "]", "=", "p", "query_names", "=", "["...
Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory.
[ "Gather", "details", "from", "installed", "distributions", ".", "Print", "distribution", "name", "version", "location", "and", "installed", "files", ".", "Installed", "files", "requires", "a", "pip", "generated", "installed", "-", "files", ".", "txt", "in", "the...
train
https://github.com/r1chardj0n3s/pip-check-reqs/blob/2f9bfe821d122dca1877c51f288b8a8b31877f79/pip_check_reqs/common.py#L161-L198
loftylabs/django-developer-panel
djdev_panel/middleware.py
DebugMiddleware.process_view
def process_view(self, request, view_func, view_args, view_kwargs): """ Collect data on Class-Based Views """ # Purge data in view method cache # Python 3's keys() method returns an iterator, so force evaluation before iterating. view_keys = list(VIEW_METHOD_DATA.keys())...
python
def process_view(self, request, view_func, view_args, view_kwargs): """ Collect data on Class-Based Views """ # Purge data in view method cache # Python 3's keys() method returns an iterator, so force evaluation before iterating. view_keys = list(VIEW_METHOD_DATA.keys())...
[ "def", "process_view", "(", "self", ",", "request", ",", "view_func", ",", "view_args", ",", "view_kwargs", ")", ":", "# Purge data in view method cache", "# Python 3's keys() method returns an iterator, so force evaluation before iterating.", "view_keys", "=", "list", "(", "...
Collect data on Class-Based Views
[ "Collect", "data", "on", "Class", "-", "Based", "Views" ]
train
https://github.com/loftylabs/django-developer-panel/blob/52fd2666a158b197fdd643d3c2c4d9bbc5ba230a/djdev_panel/middleware.py#L141-L171
loftylabs/django-developer-panel
djdev_panel/middleware.py
DebugMiddleware.process_response
def process_response(self, request, response): """Let's handle old-style response processing here, as usual.""" # For debug only. if not settings.DEBUG: return response # Check for responses where the data can't be inserted. content_encoding = response.get('Content-...
python
def process_response(self, request, response): """Let's handle old-style response processing here, as usual.""" # For debug only. if not settings.DEBUG: return response # Check for responses where the data can't be inserted. content_encoding = response.get('Content-...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "# For debug only.", "if", "not", "settings", ".", "DEBUG", ":", "return", "response", "# Check for responses where the data can't be inserted.", "content_encoding", "=", "response", ".",...
Let's handle old-style response processing here, as usual.
[ "Let", "s", "handle", "old", "-", "style", "response", "processing", "here", "as", "usual", "." ]
train
https://github.com/loftylabs/django-developer-panel/blob/52fd2666a158b197fdd643d3c2c4d9bbc5ba230a/djdev_panel/middleware.py#L191-L217
codeinthehole/django-cacheback
cacheback/utils.py
get_job_class
def get_job_class(klass_str): """ Return the job class """ mod_name, klass_name = klass_str.rsplit('.', 1) try: mod = importlib.import_module(mod_name) except ImportError as e: logger.error("Error importing job module %s: '%s'", mod_name, e) return try: klass ...
python
def get_job_class(klass_str): """ Return the job class """ mod_name, klass_name = klass_str.rsplit('.', 1) try: mod = importlib.import_module(mod_name) except ImportError as e: logger.error("Error importing job module %s: '%s'", mod_name, e) return try: klass ...
[ "def", "get_job_class", "(", "klass_str", ")", ":", "mod_name", ",", "klass_name", "=", "klass_str", ".", "rsplit", "(", "'.'", ",", "1", ")", "try", ":", "mod", "=", "importlib", ".", "import_module", "(", "mod_name", ")", "except", "ImportError", "as", ...
Return the job class
[ "Return", "the", "job", "class" ]
train
https://github.com/codeinthehole/django-cacheback/blob/0c79a524a28ca2fada98ed58c26c544f07a58e14/cacheback/utils.py#L32-L47
codeinthehole/django-cacheback
cacheback/base.py
Job.get
def get(self, *raw_args, **raw_kwargs): """ Return the data for this function (using the cache if possible). This method is not intended to be overidden """ # We pass args and kwargs through a filter to allow them to be # converted into values that can be pickled. ...
python
def get(self, *raw_args, **raw_kwargs): """ Return the data for this function (using the cache if possible). This method is not intended to be overidden """ # We pass args and kwargs through a filter to allow them to be # converted into values that can be pickled. ...
[ "def", "get", "(", "self", ",", "*", "raw_args", ",", "*", "*", "raw_kwargs", ")", ":", "# We pass args and kwargs through a filter to allow them to be", "# converted into values that can be pickled.", "args", "=", "self", ".", "prepare_args", "(", "*", "raw_args", ")",...
Return the data for this function (using the cache if possible). This method is not intended to be overidden
[ "Return", "the", "data", "for", "this", "function", "(", "using", "the", "cache", "if", "possible", ")", "." ]
train
https://github.com/codeinthehole/django-cacheback/blob/0c79a524a28ca2fada98ed58c26c544f07a58e14/cacheback/base.py#L133-L212
codeinthehole/django-cacheback
cacheback/base.py
Job.invalidate
def invalidate(self, *raw_args, **raw_kwargs): """ Mark a cached item invalid and trigger an asynchronous job to refresh the cache """ args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwargs) item = sel...
python
def invalidate(self, *raw_args, **raw_kwargs): """ Mark a cached item invalid and trigger an asynchronous job to refresh the cache """ args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwargs) item = sel...
[ "def", "invalidate", "(", "self", ",", "*", "raw_args", ",", "*", "*", "raw_kwargs", ")", ":", "args", "=", "self", ".", "prepare_args", "(", "*", "raw_args", ")", "kwargs", "=", "self", ".", "prepare_kwargs", "(", "*", "*", "raw_kwargs", ")", "key", ...
Mark a cached item invalid and trigger an asynchronous job to refresh the cache
[ "Mark", "a", "cached", "item", "invalid", "and", "trigger", "an", "asynchronous", "job", "to", "refresh", "the", "cache" ]
train
https://github.com/codeinthehole/django-cacheback/blob/0c79a524a28ca2fada98ed58c26c544f07a58e14/cacheback/base.py#L214-L226
codeinthehole/django-cacheback
cacheback/base.py
Job.delete
def delete(self, *raw_args, **raw_kwargs): """ Remove an item from the cache """ args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwargs) item = self.cache.get(key) if item is not None: self...
python
def delete(self, *raw_args, **raw_kwargs): """ Remove an item from the cache """ args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwargs) item = self.cache.get(key) if item is not None: self...
[ "def", "delete", "(", "self", ",", "*", "raw_args", ",", "*", "*", "raw_kwargs", ")", ":", "args", "=", "self", ".", "prepare_args", "(", "*", "raw_args", ")", "kwargs", "=", "self", ".", "prepare_kwargs", "(", "*", "*", "raw_kwargs", ")", "key", "="...
Remove an item from the cache
[ "Remove", "an", "item", "from", "the", "cache" ]
train
https://github.com/codeinthehole/django-cacheback/blob/0c79a524a28ca2fada98ed58c26c544f07a58e14/cacheback/base.py#L228-L237
codeinthehole/django-cacheback
cacheback/base.py
Job.raw_get
def raw_get(self, *raw_args, **raw_kwargs): """ Retrieve the item (tuple of value and expiry) that is actually in the cache, without causing a refresh. """ args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwa...
python
def raw_get(self, *raw_args, **raw_kwargs): """ Retrieve the item (tuple of value and expiry) that is actually in the cache, without causing a refresh. """ args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwa...
[ "def", "raw_get", "(", "self", ",", "*", "raw_args", ",", "*", "*", "raw_kwargs", ")", ":", "args", "=", "self", ".", "prepare_args", "(", "*", "raw_args", ")", "kwargs", "=", "self", ".", "prepare_kwargs", "(", "*", "*", "raw_kwargs", ")", "key", "=...
Retrieve the item (tuple of value and expiry) that is actually in the cache, without causing a refresh.
[ "Retrieve", "the", "item", "(", "tuple", "of", "value", "and", "expiry", ")", "that", "is", "actually", "in", "the", "cache", "without", "causing", "a", "refresh", "." ]
train
https://github.com/codeinthehole/django-cacheback/blob/0c79a524a28ca2fada98ed58c26c544f07a58e14/cacheback/base.py#L239-L250
codeinthehole/django-cacheback
cacheback/base.py
Job.set
def set(self, *raw_args, **raw_kwargs): """ Manually set the cache value with its appropriate expiry. """ if self.set_data_kwarg in raw_kwargs: data = raw_kwargs.pop(self.set_data_kwarg) else: raw_args = list(raw_args) data = raw_args.pop() ...
python
def set(self, *raw_args, **raw_kwargs): """ Manually set the cache value with its appropriate expiry. """ if self.set_data_kwarg in raw_kwargs: data = raw_kwargs.pop(self.set_data_kwarg) else: raw_args = list(raw_args) data = raw_args.pop() ...
[ "def", "set", "(", "self", ",", "*", "raw_args", ",", "*", "*", "raw_kwargs", ")", ":", "if", "self", ".", "set_data_kwarg", "in", "raw_kwargs", ":", "data", "=", "raw_kwargs", ".", "pop", "(", "self", ".", "set_data_kwarg", ")", "else", ":", "raw_args...
Manually set the cache value with its appropriate expiry.
[ "Manually", "set", "the", "cache", "value", "with", "its", "appropriate", "expiry", "." ]
train
https://github.com/codeinthehole/django-cacheback/blob/0c79a524a28ca2fada98ed58c26c544f07a58e14/cacheback/base.py#L252-L272
codeinthehole/django-cacheback
cacheback/base.py
Job.store
def store(self, key, expiry, data): """ Add a result to the cache :key: Cache key to use :expiry: The expiry timestamp after which the result is stale :data: The data to cache """ self.cache.set(key, (expiry, data), self.cache_ttl) if getattr(settings, '...
python
def store(self, key, expiry, data): """ Add a result to the cache :key: Cache key to use :expiry: The expiry timestamp after which the result is stale :data: The data to cache """ self.cache.set(key, (expiry, data), self.cache_ttl) if getattr(settings, '...
[ "def", "store", "(", "self", ",", "key", ",", "expiry", ",", "data", ")", ":", "self", ".", "cache", ".", "set", "(", "key", ",", "(", "expiry", ",", "data", ")", ",", "self", ".", "cache_ttl", ")", "if", "getattr", "(", "settings", ",", "'CACHEB...
Add a result to the cache :key: Cache key to use :expiry: The expiry timestamp after which the result is stale :data: The data to cache
[ "Add", "a", "result", "to", "the", "cache" ]
train
https://github.com/codeinthehole/django-cacheback/blob/0c79a524a28ca2fada98ed58c26c544f07a58e14/cacheback/base.py#L284-L302
codeinthehole/django-cacheback
cacheback/base.py
Job.refresh
def refresh(self, *args, **kwargs): """ Fetch the result SYNCHRONOUSLY and populate the cache """ result = self.fetch(*args, **kwargs) self.store(self.key(*args, **kwargs), self.expiry(*args, **kwargs), result) return result
python
def refresh(self, *args, **kwargs): """ Fetch the result SYNCHRONOUSLY and populate the cache """ result = self.fetch(*args, **kwargs) self.store(self.key(*args, **kwargs), self.expiry(*args, **kwargs), result) return result
[ "def", "refresh", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "fetch", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "store", "(", "self", ".", "key", "(", "*", "args", ",", "*"...
Fetch the result SYNCHRONOUSLY and populate the cache
[ "Fetch", "the", "result", "SYNCHRONOUSLY", "and", "populate", "the", "cache" ]
train
https://github.com/codeinthehole/django-cacheback/blob/0c79a524a28ca2fada98ed58c26c544f07a58e14/cacheback/base.py#L304-L310