id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
44,000 | asweigart/pytweening | pytweening/__init__.py | easeInBack | def easeInBack(n, s=1.70158):
"""A tween function that backs up first at the start and then goes to the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnL... | python | def easeInBack(n, s=1.70158):
"""A tween function that backs up first at the start and then goes to the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnL... | [
"def",
"easeInBack",
"(",
"n",
",",
"s",
"=",
"1.70158",
")",
":",
"_checkRange",
"(",
"n",
")",
"return",
"n",
"*",
"n",
"*",
"(",
"(",
"s",
"+",
"1",
")",
"*",
"n",
"-",
"s",
")"
] | A tween function that backs up first at the start and then goes to the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). | [
"A",
"tween",
"function",
"that",
"backs",
"up",
"first",
"at",
"the",
"start",
"and",
"then",
"goes",
"to",
"the",
"destination",
"."
] | 20d74368e53dc7d0f77c810b624b2c90994f099d | https://github.com/asweigart/pytweening/blob/20d74368e53dc7d0f77c810b624b2c90994f099d/pytweening/__init__.py#L498-L508 |
44,001 | asweigart/pytweening | pytweening/__init__.py | easeOutBack | def easeOutBack(n, s=1.70158):
"""A tween function that overshoots the destination a little and then backs into the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to... | python | def easeOutBack(n, s=1.70158):
"""A tween function that overshoots the destination a little and then backs into the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to... | [
"def",
"easeOutBack",
"(",
"n",
",",
"s",
"=",
"1.70158",
")",
":",
"_checkRange",
"(",
"n",
")",
"n",
"=",
"n",
"-",
"1",
"return",
"n",
"*",
"n",
"*",
"(",
"(",
"s",
"+",
"1",
")",
"*",
"n",
"+",
"s",
")",
"+",
"1"
] | A tween function that overshoots the destination a little and then backs into the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). | [
"A",
"tween",
"function",
"that",
"overshoots",
"the",
"destination",
"a",
"little",
"and",
"then",
"backs",
"into",
"the",
"destination",
"."
] | 20d74368e53dc7d0f77c810b624b2c90994f099d | https://github.com/asweigart/pytweening/blob/20d74368e53dc7d0f77c810b624b2c90994f099d/pytweening/__init__.py#L511-L522 |
44,002 | asweigart/pytweening | pytweening/__init__.py | easeInOutBack | def easeInOutBack(n, s=1.70158):
"""A "back-in" tween function that overshoots both the start and destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().... | python | def easeInOutBack(n, s=1.70158):
"""A "back-in" tween function that overshoots both the start and destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().... | [
"def",
"easeInOutBack",
"(",
"n",
",",
"s",
"=",
"1.70158",
")",
":",
"_checkRange",
"(",
"n",
")",
"n",
"=",
"n",
"*",
"2",
"if",
"n",
"<",
"1",
":",
"s",
"*=",
"1.525",
"return",
"0.5",
"*",
"(",
"n",
"*",
"n",
"*",
"(",
"(",
"s",
"+",
... | A "back-in" tween function that overshoots both the start and destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). | [
"A",
"back",
"-",
"in",
"tween",
"function",
"that",
"overshoots",
"both",
"the",
"start",
"and",
"destination",
"."
] | 20d74368e53dc7d0f77c810b624b2c90994f099d | https://github.com/asweigart/pytweening/blob/20d74368e53dc7d0f77c810b624b2c90994f099d/pytweening/__init__.py#L525-L542 |
44,003 | asweigart/pytweening | pytweening/__init__.py | easeOutBounce | def easeOutBounce(n):
"""A bouncing tween function that hits the destination and then bounces to rest.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
"""... | python | def easeOutBounce(n):
"""A bouncing tween function that hits the destination and then bounces to rest.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
"""... | [
"def",
"easeOutBounce",
"(",
"n",
")",
":",
"_checkRange",
"(",
"n",
")",
"if",
"n",
"<",
"(",
"1",
"/",
"2.75",
")",
":",
"return",
"7.5625",
"*",
"n",
"*",
"n",
"elif",
"n",
"<",
"(",
"2",
"/",
"2.75",
")",
":",
"n",
"-=",
"(",
"1.5",
"/"... | A bouncing tween function that hits the destination and then bounces to rest.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). | [
"A",
"bouncing",
"tween",
"function",
"that",
"hits",
"the",
"destination",
"and",
"then",
"bounces",
"to",
"rest",
"."
] | 20d74368e53dc7d0f77c810b624b2c90994f099d | https://github.com/asweigart/pytweening/blob/20d74368e53dc7d0f77c810b624b2c90994f099d/pytweening/__init__.py#L558-L578 |
44,004 | nnseva/django-access | access/admin.py | AccessControlMixin.formfield_for_manytomany | def formfield_for_manytomany(self, db_field, request, **kwargs):
'''
Not all Admin subclasses use get_field_queryset here, so we will use it explicitly
'''
db = kwargs.get('using')
kwargs['queryset'] = kwargs.get('queryset', self.get_field_queryset(db, db_field, request))
... | python | def formfield_for_manytomany(self, db_field, request, **kwargs):
'''
Not all Admin subclasses use get_field_queryset here, so we will use it explicitly
'''
db = kwargs.get('using')
kwargs['queryset'] = kwargs.get('queryset', self.get_field_queryset(db, db_field, request))
... | [
"def",
"formfield_for_manytomany",
"(",
"self",
",",
"db_field",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"db",
"=",
"kwargs",
".",
"get",
"(",
"'using'",
")",
"kwargs",
"[",
"'queryset'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'queryset'",
",... | Not all Admin subclasses use get_field_queryset here, so we will use it explicitly | [
"Not",
"all",
"Admin",
"subclasses",
"use",
"get_field_queryset",
"here",
"so",
"we",
"will",
"use",
"it",
"explicitly"
] | 2e8b72830b1092652ca63125a8309189d70ad584 | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/admin.py#L151-L157 |
44,005 | nnseva/django-access | access/admin.py | AccessControlMixin.delete_selected | def delete_selected(self, request, queryset):
'''
The real delete function always evaluated either from the action, or from the instance delete link
'''
opts = self.model._meta
app_label = opts.app_label
# Populate deletable_objects, a data structure of all related objec... | python | def delete_selected(self, request, queryset):
'''
The real delete function always evaluated either from the action, or from the instance delete link
'''
opts = self.model._meta
app_label = opts.app_label
# Populate deletable_objects, a data structure of all related objec... | [
"def",
"delete_selected",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"app_label",
"=",
"opts",
".",
"app_label",
"# Populate deletable_objects, a data structure of all related objects that",
"# will also be d... | The real delete function always evaluated either from the action, or from the instance delete link | [
"The",
"real",
"delete",
"function",
"always",
"evaluated",
"either",
"from",
"the",
"action",
"or",
"from",
"the",
"instance",
"delete",
"link"
] | 2e8b72830b1092652ca63125a8309189d70ad584 | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/admin.py#L288-L354 |
44,006 | nnseva/django-access | access/admin.py | AccessControlMixin.get_deleted_objects | def get_deleted_objects(self, request, queryset):
"""
Find all objects related to instances of ``queryset`` that should also be deleted.
Returns
- to_delete - a nested list of strings suitable for display in the template with the ``unordered_list`` filter.
- model_count ... | python | def get_deleted_objects(self, request, queryset):
"""
Find all objects related to instances of ``queryset`` that should also be deleted.
Returns
- to_delete - a nested list of strings suitable for display in the template with the ``unordered_list`` filter.
- model_count ... | [
"def",
"get_deleted_objects",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"collector",
"=",
"NestedObjects",
"(",
"using",
"=",
"queryset",
".",
"db",
")",
"collector",
".",
"collect",
"(",
"queryset",
")",
"model_perms_needed",
"=",
"set",
"(",
... | Find all objects related to instances of ``queryset`` that should also be deleted.
Returns
- to_delete - a nested list of strings suitable for display in the template with the ``unordered_list`` filter.
- model_count - statistics for models of all deleted instances
- perms_n... | [
"Find",
"all",
"objects",
"related",
"to",
"instances",
"of",
"queryset",
"that",
"should",
"also",
"be",
"deleted",
"."
] | 2e8b72830b1092652ca63125a8309189d70ad584 | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/admin.py#L358-L421 |
44,007 | nnseva/django-access | access/managers.py | AccessManager.register_plugins | def register_plugins(cls, plugins):
'''
Reguster plugins. The plugins parameter should be dict mapping model to plugin.
Just calls a register_plugin for every such a pair.
'''
for model in plugins:
cls.register_plugin(model, plugins[model]) | python | def register_plugins(cls, plugins):
'''
Reguster plugins. The plugins parameter should be dict mapping model to plugin.
Just calls a register_plugin for every such a pair.
'''
for model in plugins:
cls.register_plugin(model, plugins[model]) | [
"def",
"register_plugins",
"(",
"cls",
",",
"plugins",
")",
":",
"for",
"model",
"in",
"plugins",
":",
"cls",
".",
"register_plugin",
"(",
"model",
",",
"plugins",
"[",
"model",
"]",
")"
] | Reguster plugins. The plugins parameter should be dict mapping model to plugin.
Just calls a register_plugin for every such a pair. | [
"Reguster",
"plugins",
".",
"The",
"plugins",
"parameter",
"should",
"be",
"dict",
"mapping",
"model",
"to",
"plugin",
"."
] | 2e8b72830b1092652ca63125a8309189d70ad584 | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/managers.py#L28-L35 |
44,008 | nnseva/django-access | access/managers.py | AccessManager.register_plugin | def register_plugin(cls, model, plugin):
'''
Reguster a plugin for the model.
The only one plugin can be registered. If you want to combine plugins, use CompoundPlugin.
'''
logger.info("Plugin registered for %s: %s", model, plugin)
cls.plugins[model] = plugin | python | def register_plugin(cls, model, plugin):
'''
Reguster a plugin for the model.
The only one plugin can be registered. If you want to combine plugins, use CompoundPlugin.
'''
logger.info("Plugin registered for %s: %s", model, plugin)
cls.plugins[model] = plugin | [
"def",
"register_plugin",
"(",
"cls",
",",
"model",
",",
"plugin",
")",
":",
"logger",
".",
"info",
"(",
"\"Plugin registered for %s: %s\"",
",",
"model",
",",
"plugin",
")",
"cls",
".",
"plugins",
"[",
"model",
"]",
"=",
"plugin"
] | Reguster a plugin for the model.
The only one plugin can be registered. If you want to combine plugins, use CompoundPlugin. | [
"Reguster",
"a",
"plugin",
"for",
"the",
"model",
"."
] | 2e8b72830b1092652ca63125a8309189d70ad584 | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/managers.py#L38-L45 |
44,009 | nnseva/django-access | access/managers.py | AccessManager.get_default_plugin | def get_default_plugin(cls):
'''
Return a default plugin.
'''
from importlib import import_module
from django.conf import settings
default_plugin = getattr(settings, 'ACCESS_DEFAULT_PLUGIN', "access.plugins.DjangoAccessPlugin")
if default_plugin not in cls.default... | python | def get_default_plugin(cls):
'''
Return a default plugin.
'''
from importlib import import_module
from django.conf import settings
default_plugin = getattr(settings, 'ACCESS_DEFAULT_PLUGIN', "access.plugins.DjangoAccessPlugin")
if default_plugin not in cls.default... | [
"def",
"get_default_plugin",
"(",
"cls",
")",
":",
"from",
"importlib",
"import",
"import_module",
"from",
"django",
".",
"conf",
"import",
"settings",
"default_plugin",
"=",
"getattr",
"(",
"settings",
",",
"'ACCESS_DEFAULT_PLUGIN'",
",",
"\"access.plugins.DjangoAcce... | Return a default plugin. | [
"Return",
"a",
"default",
"plugin",
"."
] | 2e8b72830b1092652ca63125a8309189d70ad584 | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/managers.py#L66-L80 |
44,010 | nnseva/django-access | access/managers.py | AccessManager.plugin_for | def plugin_for(cls, model):
'''
Find and return a plugin for this model. Uses inheritance to find a model where the plugin is registered.
'''
logger.debug("Getting a plugin for: %s", model)
if not issubclass(model, Model):
return
if model in cls.plugins:
... | python | def plugin_for(cls, model):
'''
Find and return a plugin for this model. Uses inheritance to find a model where the plugin is registered.
'''
logger.debug("Getting a plugin for: %s", model)
if not issubclass(model, Model):
return
if model in cls.plugins:
... | [
"def",
"plugin_for",
"(",
"cls",
",",
"model",
")",
":",
"logger",
".",
"debug",
"(",
"\"Getting a plugin for: %s\"",
",",
"model",
")",
"if",
"not",
"issubclass",
"(",
"model",
",",
"Model",
")",
":",
"return",
"if",
"model",
"in",
"cls",
".",
"plugins"... | Find and return a plugin for this model. Uses inheritance to find a model where the plugin is registered. | [
"Find",
"and",
"return",
"a",
"plugin",
"for",
"this",
"model",
".",
"Uses",
"inheritance",
"to",
"find",
"a",
"model",
"where",
"the",
"plugin",
"is",
"registered",
"."
] | 2e8b72830b1092652ca63125a8309189d70ad584 | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/managers.py#L83-L95 |
44,011 | nnseva/django-access | access/managers.py | AccessManager.visible | def visible(self, request):
'''
Checks the both, check_visible and apply_visible, against the owned model and it's instance set
'''
return self.apply_visible(self.get_queryset(), request) if self.check_visible(self.model, request) is not False else self.get_queryset().none() | python | def visible(self, request):
'''
Checks the both, check_visible and apply_visible, against the owned model and it's instance set
'''
return self.apply_visible(self.get_queryset(), request) if self.check_visible(self.model, request) is not False else self.get_queryset().none() | [
"def",
"visible",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"apply_visible",
"(",
"self",
".",
"get_queryset",
"(",
")",
",",
"request",
")",
"if",
"self",
".",
"check_visible",
"(",
"self",
".",
"model",
",",
"request",
")",
"is",
... | Checks the both, check_visible and apply_visible, against the owned model and it's instance set | [
"Checks",
"the",
"both",
"check_visible",
"and",
"apply_visible",
"against",
"the",
"owned",
"model",
"and",
"it",
"s",
"instance",
"set"
] | 2e8b72830b1092652ca63125a8309189d70ad584 | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/managers.py#L172-L176 |
44,012 | nnseva/django-access | access/managers.py | AccessManager.changeable | def changeable(self, request):
'''
Checks the both, check_changeable and apply_changeable, against the owned model and it's instance set
'''
return self.apply_changeable(self.get_queryset(), request) if self.check_changeable(self.model, request) is not False else self.get_queryset().none... | python | def changeable(self, request):
'''
Checks the both, check_changeable and apply_changeable, against the owned model and it's instance set
'''
return self.apply_changeable(self.get_queryset(), request) if self.check_changeable(self.model, request) is not False else self.get_queryset().none... | [
"def",
"changeable",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"apply_changeable",
"(",
"self",
".",
"get_queryset",
"(",
")",
",",
"request",
")",
"if",
"self",
".",
"check_changeable",
"(",
"self",
".",
"model",
",",
"request",
")",... | Checks the both, check_changeable and apply_changeable, against the owned model and it's instance set | [
"Checks",
"the",
"both",
"check_changeable",
"and",
"apply_changeable",
"against",
"the",
"owned",
"model",
"and",
"it",
"s",
"instance",
"set"
] | 2e8b72830b1092652ca63125a8309189d70ad584 | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/managers.py#L178-L182 |
44,013 | nnseva/django-access | access/managers.py | AccessManager.deleteable | def deleteable(self, request):
'''
Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set
'''
return self.apply_deleteable(self.get_queryset(), request) if self.check_deleteable(self.model, request) is not False else self.get_queryset().none... | python | def deleteable(self, request):
'''
Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set
'''
return self.apply_deleteable(self.get_queryset(), request) if self.check_deleteable(self.model, request) is not False else self.get_queryset().none... | [
"def",
"deleteable",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"apply_deleteable",
"(",
"self",
".",
"get_queryset",
"(",
")",
",",
"request",
")",
"if",
"self",
".",
"check_deleteable",
"(",
"self",
".",
"model",
",",
"request",
")",... | Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set | [
"Checks",
"the",
"both",
"check_deleteable",
"and",
"apply_deleteable",
"against",
"the",
"owned",
"model",
"and",
"it",
"s",
"instance",
"set"
] | 2e8b72830b1092652ca63125a8309189d70ad584 | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/managers.py#L184-L188 |
44,014 | krischer/django-plugins | djangoplugins/utils.py | get_plugin_from_string | def get_plugin_from_string(plugin_name):
"""
Returns plugin or plugin point class from given ``plugin_name`` string.
Example of ``plugin_name``::
'my_app.MyPlugin'
"""
modulename, classname = plugin_name.rsplit('.', 1)
module = import_module(modulename)
return getattr(module, clas... | python | def get_plugin_from_string(plugin_name):
"""
Returns plugin or plugin point class from given ``plugin_name`` string.
Example of ``plugin_name``::
'my_app.MyPlugin'
"""
modulename, classname = plugin_name.rsplit('.', 1)
module = import_module(modulename)
return getattr(module, clas... | [
"def",
"get_plugin_from_string",
"(",
"plugin_name",
")",
":",
"modulename",
",",
"classname",
"=",
"plugin_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"import_module",
"(",
"modulename",
")",
"return",
"getattr",
"(",
"module",
",",
"cla... | Returns plugin or plugin point class from given ``plugin_name`` string.
Example of ``plugin_name``::
'my_app.MyPlugin' | [
"Returns",
"plugin",
"or",
"plugin",
"point",
"class",
"from",
"given",
"plugin_name",
"string",
"."
] | 0064e3306a7ed7af83f1ff51231acdf7478215fe | https://github.com/krischer/django-plugins/blob/0064e3306a7ed7af83f1ff51231acdf7478215fe/djangoplugins/utils.py#L14-L25 |
44,015 | RealTimeWeb/datasets | builder/languages/detect_distribution.py | make_pdf | def make_pdf(dist, params, size=10000):
"""Generate distributions's Propbability Distribution Function """
# Separate parts of parameters
arg = params[:-2]
loc = params[-2]
scale = params[-1]
# Get sane start and end points of distribution
start = dist.ppf(0.01, *arg, loc=loc, scale=scale)... | python | def make_pdf(dist, params, size=10000):
"""Generate distributions's Propbability Distribution Function """
# Separate parts of parameters
arg = params[:-2]
loc = params[-2]
scale = params[-1]
# Get sane start and end points of distribution
start = dist.ppf(0.01, *arg, loc=loc, scale=scale)... | [
"def",
"make_pdf",
"(",
"dist",
",",
"params",
",",
"size",
"=",
"10000",
")",
":",
"# Separate parts of parameters",
"arg",
"=",
"params",
"[",
":",
"-",
"2",
"]",
"loc",
"=",
"params",
"[",
"-",
"2",
"]",
"scale",
"=",
"params",
"[",
"-",
"1",
"]... | Generate distributions's Propbability Distribution Function | [
"Generate",
"distributions",
"s",
"Propbability",
"Distribution",
"Function"
] | 2fe5befd251c783744d000bd4763e277616a152f | https://github.com/RealTimeWeb/datasets/blob/2fe5befd251c783744d000bd4763e277616a152f/builder/languages/detect_distribution.py#L79-L96 |
44,016 | RealTimeWeb/datasets | preprocess/earthquakes/earthquakes.py | urlencode | def urlencode(query, params):
"""
Correctly convert the given query and parameters into a full query+query
string, ensuring the order of the params.
"""
return query + '?' + "&".join(key+'='+quote_plus(str(value))
for key, value in params) | python | def urlencode(query, params):
"""
Correctly convert the given query and parameters into a full query+query
string, ensuring the order of the params.
"""
return query + '?' + "&".join(key+'='+quote_plus(str(value))
for key, value in params) | [
"def",
"urlencode",
"(",
"query",
",",
"params",
")",
":",
"return",
"query",
"+",
"'?'",
"+",
"\"&\"",
".",
"join",
"(",
"key",
"+",
"'='",
"+",
"quote_plus",
"(",
"str",
"(",
"value",
")",
")",
"for",
"key",
",",
"value",
"in",
"params",
")"
] | Correctly convert the given query and parameters into a full query+query
string, ensuring the order of the params. | [
"Correctly",
"convert",
"the",
"given",
"query",
"and",
"parameters",
"into",
"a",
"full",
"query",
"+",
"query",
"string",
"ensuring",
"the",
"order",
"of",
"the",
"params",
"."
] | 2fe5befd251c783744d000bd4763e277616a152f | https://github.com/RealTimeWeb/datasets/blob/2fe5befd251c783744d000bd4763e277616a152f/preprocess/earthquakes/earthquakes.py#L32-L38 |
44,017 | RealTimeWeb/datasets | preprocess/earthquakes/earthquakes.py | _load_from_string | def _load_from_string(data):
'''Loads the cache from the string'''
global _CACHE
if PYTHON_3:
data = json.loads(data.decode("utf-8"))
else:
data = json.loads(data)
_CACHE = _recursively_convert_unicode_to_str(data)['data'] | python | def _load_from_string(data):
'''Loads the cache from the string'''
global _CACHE
if PYTHON_3:
data = json.loads(data.decode("utf-8"))
else:
data = json.loads(data)
_CACHE = _recursively_convert_unicode_to_str(data)['data'] | [
"def",
"_load_from_string",
"(",
"data",
")",
":",
"global",
"_CACHE",
"if",
"PYTHON_3",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"data",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"else",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"data",
")",... | Loads the cache from the string | [
"Loads",
"the",
"cache",
"from",
"the",
"string"
] | 2fe5befd251c783744d000bd4763e277616a152f | https://github.com/RealTimeWeb/datasets/blob/2fe5befd251c783744d000bd4763e277616a152f/preprocess/earthquakes/earthquakes.py#L139-L146 |
44,018 | krischer/django-plugins | djangoplugins/point.py | PluginPoint.get_model | def get_model(cls, name=None, status=ENABLED):
"""
Returns model instance of plugin point or plugin, depending from which
class this methos is called.
Example::
plugin_model_instance = MyPlugin.get_model()
plugin_model_instance = MyPluginPoint.get_model('plugin-... | python | def get_model(cls, name=None, status=ENABLED):
"""
Returns model instance of plugin point or plugin, depending from which
class this methos is called.
Example::
plugin_model_instance = MyPlugin.get_model()
plugin_model_instance = MyPluginPoint.get_model('plugin-... | [
"def",
"get_model",
"(",
"cls",
",",
"name",
"=",
"None",
",",
"status",
"=",
"ENABLED",
")",
":",
"ppath",
"=",
"cls",
".",
"get_pythonpath",
"(",
")",
"if",
"is_plugin_point",
"(",
"cls",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"kwargs",
... | Returns model instance of plugin point or plugin, depending from which
class this methos is called.
Example::
plugin_model_instance = MyPlugin.get_model()
plugin_model_instance = MyPluginPoint.get_model('plugin-name')
plugin_point_model_instance = MyPluginPoint.get_... | [
"Returns",
"model",
"instance",
"of",
"plugin",
"point",
"or",
"plugin",
"depending",
"from",
"which",
"class",
"this",
"methos",
"is",
"called",
"."
] | 0064e3306a7ed7af83f1ff51231acdf7478215fe | https://github.com/krischer/django-plugins/blob/0064e3306a7ed7af83f1ff51231acdf7478215fe/djangoplugins/point.py#L63-L86 |
44,019 | krischer/django-plugins | djangoplugins/point.py | PluginPoint.get_point_model | def get_point_model(cls):
"""
Returns plugin point model instance. Only used from plugin classes.
"""
if is_plugin_point(cls):
raise Exception(_('This method is only available to plugin '
'classes.'))
else:
return PluginPointM... | python | def get_point_model(cls):
"""
Returns plugin point model instance. Only used from plugin classes.
"""
if is_plugin_point(cls):
raise Exception(_('This method is only available to plugin '
'classes.'))
else:
return PluginPointM... | [
"def",
"get_point_model",
"(",
"cls",
")",
":",
"if",
"is_plugin_point",
"(",
"cls",
")",
":",
"raise",
"Exception",
"(",
"_",
"(",
"'This method is only available to plugin '",
"'classes.'",
")",
")",
"else",
":",
"return",
"PluginPointModel",
".",
"objects",
"... | Returns plugin point model instance. Only used from plugin classes. | [
"Returns",
"plugin",
"point",
"model",
"instance",
".",
"Only",
"used",
"from",
"plugin",
"classes",
"."
] | 0064e3306a7ed7af83f1ff51231acdf7478215fe | https://github.com/krischer/django-plugins/blob/0064e3306a7ed7af83f1ff51231acdf7478215fe/djangoplugins/point.py#L104-L113 |
44,020 | krischer/django-plugins | djangoplugins/point.py | PluginPoint.get_plugins | def get_plugins(cls):
"""
Returns all plugin instances of plugin point, passing all args and
kwargs to plugin constructor.
"""
# Django >= 1.9 changed something with the migration logic causing
# plugins to be executed before the corresponding database tables
# ex... | python | def get_plugins(cls):
"""
Returns all plugin instances of plugin point, passing all args and
kwargs to plugin constructor.
"""
# Django >= 1.9 changed something with the migration logic causing
# plugins to be executed before the corresponding database tables
# ex... | [
"def",
"get_plugins",
"(",
"cls",
")",
":",
"# Django >= 1.9 changed something with the migration logic causing",
"# plugins to be executed before the corresponding database tables",
"# exist. This method will only return something if the database",
"# tables have already been created.",
"# XXX:... | Returns all plugin instances of plugin point, passing all args and
kwargs to plugin constructor. | [
"Returns",
"all",
"plugin",
"instances",
"of",
"plugin",
"point",
"passing",
"all",
"args",
"and",
"kwargs",
"to",
"plugin",
"constructor",
"."
] | 0064e3306a7ed7af83f1ff51231acdf7478215fe | https://github.com/krischer/django-plugins/blob/0064e3306a7ed7af83f1ff51231acdf7478215fe/djangoplugins/point.py#L116-L136 |
44,021 | krischer/django-plugins | djangoplugins/point.py | PluginPoint.get_plugins_qs | def get_plugins_qs(cls):
"""
Returns query set of all plugins belonging to plugin point.
Example::
for plugin_instance in MyPluginPoint.get_plugins_qs():
print(plugin_instance.get_plugin().name)
"""
if is_plugin_point(cls):
point_pythonp... | python | def get_plugins_qs(cls):
"""
Returns query set of all plugins belonging to plugin point.
Example::
for plugin_instance in MyPluginPoint.get_plugins_qs():
print(plugin_instance.get_plugin().name)
"""
if is_plugin_point(cls):
point_pythonp... | [
"def",
"get_plugins_qs",
"(",
"cls",
")",
":",
"if",
"is_plugin_point",
"(",
"cls",
")",
":",
"point_pythonpath",
"=",
"cls",
".",
"get_pythonpath",
"(",
")",
"return",
"Plugin",
".",
"objects",
".",
"filter",
"(",
"point__pythonpath",
"=",
"point_pythonpath",... | Returns query set of all plugins belonging to plugin point.
Example::
for plugin_instance in MyPluginPoint.get_plugins_qs():
print(plugin_instance.get_plugin().name) | [
"Returns",
"query",
"set",
"of",
"all",
"plugins",
"belonging",
"to",
"plugin",
"point",
"."
] | 0064e3306a7ed7af83f1ff51231acdf7478215fe | https://github.com/krischer/django-plugins/blob/0064e3306a7ed7af83f1ff51231acdf7478215fe/djangoplugins/point.py#L139-L156 |
44,022 | RealTimeWeb/datasets | preprocess/classics/process_rdf.py | safeunicode | def safeunicode(arg, *args, **kwargs):
"""Coerce argument to unicode, if it's not already."""
return arg if isinstance(arg, unicode) else unicode(arg, *args, **kwargs) | python | def safeunicode(arg, *args, **kwargs):
"""Coerce argument to unicode, if it's not already."""
return arg if isinstance(arg, unicode) else unicode(arg, *args, **kwargs) | [
"def",
"safeunicode",
"(",
"arg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"arg",
"if",
"isinstance",
"(",
"arg",
",",
"unicode",
")",
"else",
"unicode",
"(",
"arg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Coerce argument to unicode, if it's not already. | [
"Coerce",
"argument",
"to",
"unicode",
"if",
"it",
"s",
"not",
"already",
"."
] | 2fe5befd251c783744d000bd4763e277616a152f | https://github.com/RealTimeWeb/datasets/blob/2fe5befd251c783744d000bd4763e277616a152f/preprocess/classics/process_rdf.py#L194-L196 |
44,023 | RealTimeWeb/datasets | datasets/python/energy/energy.py | get_reports | def get_reports():
"""
Returns energy data from 1960 to 2014 across various factors.
"""
if False:
# If there was a Test version of this method, it would go here. But alas.
pass
else:
rows = _Constants._DATABASE.execute("SELECT data FROM energy".format(
hardw... | python | def get_reports():
"""
Returns energy data from 1960 to 2014 across various factors.
"""
if False:
# If there was a Test version of this method, it would go here. But alas.
pass
else:
rows = _Constants._DATABASE.execute("SELECT data FROM energy".format(
hardw... | [
"def",
"get_reports",
"(",
")",
":",
"if",
"False",
":",
"# If there was a Test version of this method, it would go here. But alas.",
"pass",
"else",
":",
"rows",
"=",
"_Constants",
".",
"_DATABASE",
".",
"execute",
"(",
"\"SELECT data FROM energy\"",
".",
"format",
"("... | Returns energy data from 1960 to 2014 across various factors. | [
"Returns",
"energy",
"data",
"from",
"1960",
"to",
"2014",
"across",
"various",
"factors",
"."
] | 2fe5befd251c783744d000bd4763e277616a152f | https://github.com/RealTimeWeb/datasets/blob/2fe5befd251c783744d000bd4763e277616a152f/datasets/python/energy/energy.py#L237-L251 |
44,024 | krischer/django-plugins | djangoplugins/management/commands/syncplugins.py | SyncPlugins.available | def available(self, src, dst, model):
"""
Iterate over all registered plugins or plugin points and prepare to add
them to database.
"""
for name, point in six.iteritems(src):
inst = dst.pop(name, None)
if inst is None:
self.print_(1, "Regis... | python | def available(self, src, dst, model):
"""
Iterate over all registered plugins or plugin points and prepare to add
them to database.
"""
for name, point in six.iteritems(src):
inst = dst.pop(name, None)
if inst is None:
self.print_(1, "Regis... | [
"def",
"available",
"(",
"self",
",",
"src",
",",
"dst",
",",
"model",
")",
":",
"for",
"name",
",",
"point",
"in",
"six",
".",
"iteritems",
"(",
"src",
")",
":",
"inst",
"=",
"dst",
".",
"pop",
"(",
"name",
",",
"None",
")",
"if",
"inst",
"is"... | Iterate over all registered plugins or plugin points and prepare to add
them to database. | [
"Iterate",
"over",
"all",
"registered",
"plugins",
"or",
"plugin",
"points",
"and",
"prepare",
"to",
"add",
"them",
"to",
"database",
"."
] | 0064e3306a7ed7af83f1ff51231acdf7478215fe | https://github.com/krischer/django-plugins/blob/0064e3306a7ed7af83f1ff51231acdf7478215fe/djangoplugins/management/commands/syncplugins.py#L68-L83 |
44,025 | krischer/django-plugins | djangoplugins/management/commands/syncplugins.py | SyncPlugins.missing | def missing(self, dst):
"""
Mark all missing plugins, that exists in database, but are not
registered.
"""
for inst in six.itervalues(dst):
if inst.status != REMOVED:
inst.status = REMOVED
inst.save() | python | def missing(self, dst):
"""
Mark all missing plugins, that exists in database, but are not
registered.
"""
for inst in six.itervalues(dst):
if inst.status != REMOVED:
inst.status = REMOVED
inst.save() | [
"def",
"missing",
"(",
"self",
",",
"dst",
")",
":",
"for",
"inst",
"in",
"six",
".",
"itervalues",
"(",
"dst",
")",
":",
"if",
"inst",
".",
"status",
"!=",
"REMOVED",
":",
"inst",
".",
"status",
"=",
"REMOVED",
"inst",
".",
"save",
"(",
")"
] | Mark all missing plugins, that exists in database, but are not
registered. | [
"Mark",
"all",
"missing",
"plugins",
"that",
"exists",
"in",
"database",
"but",
"are",
"not",
"registered",
"."
] | 0064e3306a7ed7af83f1ff51231acdf7478215fe | https://github.com/krischer/django-plugins/blob/0064e3306a7ed7af83f1ff51231acdf7478215fe/djangoplugins/management/commands/syncplugins.py#L85-L93 |
44,026 | krischer/django-plugins | djangoplugins/management/commands/syncplugins.py | SyncPlugins.all | def all(self):
"""
Synchronize all registered plugins and plugin points to database.
"""
# Django >= 1.9 changed something with the migration logic causing
# plugins to be executed before the corresponding database tables
# exist. This method will only return something if... | python | def all(self):
"""
Synchronize all registered plugins and plugin points to database.
"""
# Django >= 1.9 changed something with the migration logic causing
# plugins to be executed before the corresponding database tables
# exist. This method will only return something if... | [
"def",
"all",
"(",
"self",
")",
":",
"# Django >= 1.9 changed something with the migration logic causing",
"# plugins to be executed before the corresponding database tables",
"# exist. This method will only return something if the database",
"# tables have already been created.",
"# XXX: I don'... | Synchronize all registered plugins and plugin points to database. | [
"Synchronize",
"all",
"registered",
"plugins",
"and",
"plugin",
"points",
"to",
"database",
"."
] | 0064e3306a7ed7af83f1ff51231acdf7478215fe | https://github.com/krischer/django-plugins/blob/0064e3306a7ed7af83f1ff51231acdf7478215fe/djangoplugins/management/commands/syncplugins.py#L131-L145 |
44,027 | RealTimeWeb/datasets | datasets/python/weather/weather.py | get_weather | def get_weather(test=False):
"""
Returns weather reports from the dataset.
"""
if _Constants._TEST or test:
rows = _Constants._DATABASE.execute("SELECT data FROM weather LIMIT {hardware}".format(
hardware=_Constants._HARDWARE))
data = [r[0] for r in rows]
data = ... | python | def get_weather(test=False):
"""
Returns weather reports from the dataset.
"""
if _Constants._TEST or test:
rows = _Constants._DATABASE.execute("SELECT data FROM weather LIMIT {hardware}".format(
hardware=_Constants._HARDWARE))
data = [r[0] for r in rows]
data = ... | [
"def",
"get_weather",
"(",
"test",
"=",
"False",
")",
":",
"if",
"_Constants",
".",
"_TEST",
"or",
"test",
":",
"rows",
"=",
"_Constants",
".",
"_DATABASE",
".",
"execute",
"(",
"\"SELECT data FROM weather LIMIT {hardware}\"",
".",
"format",
"(",
"hardware",
"... | Returns weather reports from the dataset. | [
"Returns",
"weather",
"reports",
"from",
"the",
"dataset",
"."
] | 2fe5befd251c783744d000bd4763e277616a152f | https://github.com/RealTimeWeb/datasets/blob/2fe5befd251c783744d000bd4763e277616a152f/datasets/python/weather/weather.py#L152-L171 |
44,028 | joealcorn/xbox | xbox/client.py | Client._get | def _get(self, url, **kw):
'''
Makes a GET request, setting Authorization
header by default
'''
headers = kw.pop('headers', {})
headers.setdefault('Content-Type', 'application/json')
headers.setdefault('Accept', 'application/json')
headers.setdefault('Auth... | python | def _get(self, url, **kw):
'''
Makes a GET request, setting Authorization
header by default
'''
headers = kw.pop('headers', {})
headers.setdefault('Content-Type', 'application/json')
headers.setdefault('Accept', 'application/json')
headers.setdefault('Auth... | [
"def",
"_get",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kw",
")",
":",
"headers",
"=",
"kw",
".",
"pop",
"(",
"'headers'",
",",
"{",
"}",
")",
"headers",
".",
"setdefault",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
"headers",
".",
"setde... | Makes a GET request, setting Authorization
header by default | [
"Makes",
"a",
"GET",
"request",
"setting",
"Authorization",
"header",
"by",
"default"
] | 3d2aeba10244dcb58d714d76fc88487c74bd1510 | https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/client.py#L42-L54 |
44,029 | joealcorn/xbox | xbox/client.py | Client._post | def _post(self, url, **kw):
'''
Makes a POST request, setting Authorization
header by default
'''
headers = kw.pop('headers', {})
headers.setdefault('Authorization', self.AUTHORIZATION_HEADER)
kw['headers'] = headers
resp = self.session.post(url, **kw)
... | python | def _post(self, url, **kw):
'''
Makes a POST request, setting Authorization
header by default
'''
headers = kw.pop('headers', {})
headers.setdefault('Authorization', self.AUTHORIZATION_HEADER)
kw['headers'] = headers
resp = self.session.post(url, **kw)
... | [
"def",
"_post",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kw",
")",
":",
"headers",
"=",
"kw",
".",
"pop",
"(",
"'headers'",
",",
"{",
"}",
")",
"headers",
".",
"setdefault",
"(",
"'Authorization'",
",",
"self",
".",
"AUTHORIZATION_HEADER",
")",
"kw",... | Makes a POST request, setting Authorization
header by default | [
"Makes",
"a",
"POST",
"request",
"setting",
"Authorization",
"header",
"by",
"default"
] | 3d2aeba10244dcb58d714d76fc88487c74bd1510 | https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/client.py#L56-L66 |
44,030 | joealcorn/xbox | xbox/client.py | Client._post_json | def _post_json(self, url, data, **kw):
'''
Makes a POST request, setting Authorization
and Content-Type headers by default
'''
data = json.dumps(data)
headers = kw.pop('headers', {})
headers.setdefault('Content-Type', 'application/json')
headers.setdefault... | python | def _post_json(self, url, data, **kw):
'''
Makes a POST request, setting Authorization
and Content-Type headers by default
'''
data = json.dumps(data)
headers = kw.pop('headers', {})
headers.setdefault('Content-Type', 'application/json')
headers.setdefault... | [
"def",
"_post_json",
"(",
"self",
",",
"url",
",",
"data",
",",
"*",
"*",
"kw",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"headers",
"=",
"kw",
".",
"pop",
"(",
"'headers'",
",",
"{",
"}",
")",
"headers",
".",
"setdefault",
... | Makes a POST request, setting Authorization
and Content-Type headers by default | [
"Makes",
"a",
"POST",
"request",
"setting",
"Authorization",
"and",
"Content",
"-",
"Type",
"headers",
"by",
"default"
] | 3d2aeba10244dcb58d714d76fc88487c74bd1510 | https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/client.py#L68-L80 |
44,031 | joealcorn/xbox | xbox/client.py | Client.authenticate | def authenticate(self, login=None, password=None):
'''
Authenticated this client instance.
``login`` and ``password`` default to the environment
variables ``MS_LOGIN`` and ``MS_PASSWD`` respectively.
:param login: Email address associated with a microsoft account
:para... | python | def authenticate(self, login=None, password=None):
'''
Authenticated this client instance.
``login`` and ``password`` default to the environment
variables ``MS_LOGIN`` and ``MS_PASSWD`` respectively.
:param login: Email address associated with a microsoft account
:para... | [
"def",
"authenticate",
"(",
"self",
",",
"login",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"login",
"is",
"None",
":",
"login",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'MS_LOGIN'",
")",
"if",
"password",
"is",
"None",
":",
"p... | Authenticated this client instance.
``login`` and ``password`` default to the environment
variables ``MS_LOGIN`` and ``MS_PASSWD`` respectively.
:param login: Email address associated with a microsoft account
:param password: Matching password
:raises: :class:`~xbox.exception... | [
"Authenticated",
"this",
"client",
"instance",
"."
] | 3d2aeba10244dcb58d714d76fc88487c74bd1510 | https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/client.py#L82-L198 |
44,032 | joealcorn/xbox | xbox/resource.py | GamerProfile.from_xuid | def from_xuid(cls, xuid):
'''
Instantiates an instance of ``GamerProfile`` from
an xuid
:param xuid: Xuid to look up
:raises: :class:`~xbox.exceptions.GamertagNotFound`
:returns: :class:`~xbox.GamerProfile` instance
'''
url = 'https://profile.xboxlive.... | python | def from_xuid(cls, xuid):
'''
Instantiates an instance of ``GamerProfile`` from
an xuid
:param xuid: Xuid to look up
:raises: :class:`~xbox.exceptions.GamertagNotFound`
:returns: :class:`~xbox.GamerProfile` instance
'''
url = 'https://profile.xboxlive.... | [
"def",
"from_xuid",
"(",
"cls",
",",
"xuid",
")",
":",
"url",
"=",
"'https://profile.xboxlive.com/users/xuid(%s)/profile/settings'",
"%",
"xuid",
"try",
":",
"return",
"cls",
".",
"_fetch",
"(",
"url",
")",
"except",
"(",
"GamertagNotFound",
",",
"InvalidRequest",... | Instantiates an instance of ``GamerProfile`` from
an xuid
:param xuid: Xuid to look up
:raises: :class:`~xbox.exceptions.GamertagNotFound`
:returns: :class:`~xbox.GamerProfile` instance | [
"Instantiates",
"an",
"instance",
"of",
"GamerProfile",
"from",
"an",
"xuid"
] | 3d2aeba10244dcb58d714d76fc88487c74bd1510 | https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/resource.py#L33-L51 |
44,033 | joealcorn/xbox | xbox/resource.py | GamerProfile.from_gamertag | def from_gamertag(cls, gamertag):
'''
Instantiates an instance of ``GamerProfile`` from
a gamertag
:param gamertag: Gamertag to look up
:raises: :class:`~xbox.exceptions.GamertagNotFound`
:returns: :class:`~xbox.GamerProfile` instance
'''
url = 'https:/... | python | def from_gamertag(cls, gamertag):
'''
Instantiates an instance of ``GamerProfile`` from
a gamertag
:param gamertag: Gamertag to look up
:raises: :class:`~xbox.exceptions.GamertagNotFound`
:returns: :class:`~xbox.GamerProfile` instance
'''
url = 'https:/... | [
"def",
"from_gamertag",
"(",
"cls",
",",
"gamertag",
")",
":",
"url",
"=",
"'https://profile.xboxlive.com/users/gt(%s)/profile/settings'",
"%",
"gamertag",
"try",
":",
"return",
"cls",
".",
"_fetch",
"(",
"url",
")",
"except",
"GamertagNotFound",
":",
"raise",
"Ga... | Instantiates an instance of ``GamerProfile`` from
a gamertag
:param gamertag: Gamertag to look up
:raises: :class:`~xbox.exceptions.GamertagNotFound`
:returns: :class:`~xbox.GamerProfile` instance | [
"Instantiates",
"an",
"instance",
"of",
"GamerProfile",
"from",
"a",
"gamertag"
] | 3d2aeba10244dcb58d714d76fc88487c74bd1510 | https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/resource.py#L54-L69 |
44,034 | joealcorn/xbox | xbox/resource.py | Clip.get | def get(cls, xuid, scid, clip_id):
'''
Gets a specific game clip
:param xuid: xuid of an xbox live user
:param scid: scid of a clip
:param clip_id: id of a clip
'''
url = (
'https://gameclipsmetadata.xboxlive.com/users'
'/xuid(%(xuid)s)/sc... | python | def get(cls, xuid, scid, clip_id):
'''
Gets a specific game clip
:param xuid: xuid of an xbox live user
:param scid: scid of a clip
:param clip_id: id of a clip
'''
url = (
'https://gameclipsmetadata.xboxlive.com/users'
'/xuid(%(xuid)s)/sc... | [
"def",
"get",
"(",
"cls",
",",
"xuid",
",",
"scid",
",",
"clip_id",
")",
":",
"url",
"=",
"(",
"'https://gameclipsmetadata.xboxlive.com/users'",
"'/xuid(%(xuid)s)/scids/%(scid)s/clips/%(clip_id)s'",
"%",
"{",
"'xuid'",
":",
"xuid",
",",
"'scid'",
":",
"scid",
",",... | Gets a specific game clip
:param xuid: xuid of an xbox live user
:param scid: scid of a clip
:param clip_id: id of a clip | [
"Gets",
"a",
"specific",
"game",
"clip"
] | 3d2aeba10244dcb58d714d76fc88487c74bd1510 | https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/resource.py#L201-L234 |
44,035 | joealcorn/xbox | xbox/resource.py | Clip.saved_from_user | def saved_from_user(cls, user, include_pending=False):
'''
Gets all clips 'saved' by a user.
:param user: :class:`~xbox.GamerProfile` instance
:param bool include_pending: whether to ignore clips that are not
yet uploaded. These clips will have thumbnails and media_url
... | python | def saved_from_user(cls, user, include_pending=False):
'''
Gets all clips 'saved' by a user.
:param user: :class:`~xbox.GamerProfile` instance
:param bool include_pending: whether to ignore clips that are not
yet uploaded. These clips will have thumbnails and media_url
... | [
"def",
"saved_from_user",
"(",
"cls",
",",
"user",
",",
"include_pending",
"=",
"False",
")",
":",
"url",
"=",
"'https://gameclipsmetadata.xboxlive.com/users/xuid(%s)/clips/saved'",
"resp",
"=",
"xbox",
".",
"client",
".",
"_get",
"(",
"url",
"%",
"user",
".",
"... | Gets all clips 'saved' by a user.
:param user: :class:`~xbox.GamerProfile` instance
:param bool include_pending: whether to ignore clips that are not
yet uploaded. These clips will have thumbnails and media_url
set to ``None``
:returns: Iterator of :class:`~xbox.Clip` in... | [
"Gets",
"all",
"clips",
"saved",
"by",
"a",
"user",
"."
] | 3d2aeba10244dcb58d714d76fc88487c74bd1510 | https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/resource.py#L238-L254 |
44,036 | joealcorn/xbox | xbox/vendor/requests/models.py | PreparedRequest.prepare_url | def prepare_url(self, url, params):
"""Prepares the given HTTP URL."""
url = to_native_string(url)
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and... | python | def prepare_url(self, url, params):
"""Prepares the given HTTP URL."""
url = to_native_string(url)
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and... | [
"def",
"prepare_url",
"(",
"self",
",",
"url",
",",
"params",
")",
":",
"url",
"=",
"to_native_string",
"(",
"url",
")",
"# Don't do any URL preparation for non-HTTP schemes like `mailto`,",
"# `data` etc to work around exceptions from `url_parse`, which",
"# handles RFC 3986 onl... | Prepares the given HTTP URL. | [
"Prepares",
"the",
"given",
"HTTP",
"URL",
"."
] | 3d2aeba10244dcb58d714d76fc88487c74bd1510 | https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/vendor/requests/models.py#L326-L385 |
44,037 | joealcorn/xbox | xbox/vendor/requests/packages/chardet/chardetect.py | description_of | def description_of(file, name='stdin'):
"""Return a string describing the probable encoding of a file."""
u = UniversalDetector()
for line in file:
u.feed(line)
u.close()
result = u.result
if result['encoding']:
return '%s: %s with confidence %s' % (name,
... | python | def description_of(file, name='stdin'):
"""Return a string describing the probable encoding of a file."""
u = UniversalDetector()
for line in file:
u.feed(line)
u.close()
result = u.result
if result['encoding']:
return '%s: %s with confidence %s' % (name,
... | [
"def",
"description_of",
"(",
"file",
",",
"name",
"=",
"'stdin'",
")",
":",
"u",
"=",
"UniversalDetector",
"(",
")",
"for",
"line",
"in",
"file",
":",
"u",
".",
"feed",
"(",
"line",
")",
"u",
".",
"close",
"(",
")",
"result",
"=",
"u",
".",
"res... | Return a string describing the probable encoding of a file. | [
"Return",
"a",
"string",
"describing",
"the",
"probable",
"encoding",
"of",
"a",
"file",
"."
] | 3d2aeba10244dcb58d714d76fc88487c74bd1510 | https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/vendor/requests/packages/chardet/chardetect.py#L21-L33 |
44,038 | JakeWharton/py-videodownloader | videodownloader/providers/__init__.py | Provider.run | def run(self):
'''
Download the video.
'''
#Callback
self._debug('Provider', 'run', 'Running pre-download callback.')
self._pre_download()
url = None
out = None
success = False
try:
url = Provider._download(self.get_download_u... | python | def run(self):
'''
Download the video.
'''
#Callback
self._debug('Provider', 'run', 'Running pre-download callback.')
self._pre_download()
url = None
out = None
success = False
try:
url = Provider._download(self.get_download_u... | [
"def",
"run",
"(",
"self",
")",
":",
"#Callback",
"self",
".",
"_debug",
"(",
"'Provider'",
",",
"'run'",
",",
"'Running pre-download callback.'",
")",
"self",
".",
"_pre_download",
"(",
")",
"url",
"=",
"None",
"out",
"=",
"None",
"success",
"=",
"False",... | Download the video. | [
"Download",
"the",
"video",
"."
] | 787e88ad46280288f559e728598fcb2a8487129c | https://github.com/JakeWharton/py-videodownloader/blob/787e88ad46280288f559e728598fcb2a8487129c/videodownloader/providers/__init__.py#L82-L127 |
44,039 | vaidik/commentjson | commentjson/commentjson.py | dumps | def dumps(obj, **kwargs):
''' Serialize `obj` to a JSON formatted `str`. Accepts the same arguments
as `json` module in stdlib.
:param obj: a JSON serializable Python object.
:param kwargs: all the arguments that `json.dumps <http://docs.python.org/
2/library/json.html#json.dumps>`_ ... | python | def dumps(obj, **kwargs):
''' Serialize `obj` to a JSON formatted `str`. Accepts the same arguments
as `json` module in stdlib.
:param obj: a JSON serializable Python object.
:param kwargs: all the arguments that `json.dumps <http://docs.python.org/
2/library/json.html#json.dumps>`_ ... | [
"def",
"dumps",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"json",
".",
"dumps",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"JSONLibraryException",
"(",
"e",
")"
] | Serialize `obj` to a JSON formatted `str`. Accepts the same arguments
as `json` module in stdlib.
:param obj: a JSON serializable Python object.
:param kwargs: all the arguments that `json.dumps <http://docs.python.org/
2/library/json.html#json.dumps>`_ accepts.
:raises: commentjson.... | [
"Serialize",
"obj",
"to",
"a",
"JSON",
"formatted",
"str",
".",
"Accepts",
"the",
"same",
"arguments",
"as",
"json",
"module",
"in",
"stdlib",
"."
] | 7ef01ea6939f046b48f812b30a6df6610015a4af | https://github.com/vaidik/commentjson/blob/7ef01ea6939f046b48f812b30a6df6610015a4af/commentjson/commentjson.py#L86-L100 |
44,040 | dennisv/django-storage-swift | swift/storage.py | prepend_name_prefix | def prepend_name_prefix(func):
"""
Decorator that wraps instance methods to prepend the instance's filename
prefix to the beginning of the referenced filename. Must only be used on
instance methods where the first parameter after `self` is `name` or a
comparable parameter of a different name.
""... | python | def prepend_name_prefix(func):
"""
Decorator that wraps instance methods to prepend the instance's filename
prefix to the beginning of the referenced filename. Must only be used on
instance methods where the first parameter after `self` is `name` or a
comparable parameter of a different name.
""... | [
"def",
"prepend_name_prefix",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"prepend_prefix",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"self",
".",
"name_prefix",
"+",
"name",
"return... | Decorator that wraps instance methods to prepend the instance's filename
prefix to the beginning of the referenced filename. Must only be used on
instance methods where the first parameter after `self` is `name` or a
comparable parameter of a different name. | [
"Decorator",
"that",
"wraps",
"instance",
"methods",
"to",
"prepend",
"the",
"instance",
"s",
"filename",
"prefix",
"to",
"the",
"beginning",
"of",
"the",
"referenced",
"filename",
".",
"Must",
"only",
"be",
"used",
"on",
"instance",
"methods",
"where",
"the",... | d7c0e8a256c241f429c464c487a14e21629acd7a | https://github.com/dennisv/django-storage-swift/blob/d7c0e8a256c241f429c464c487a14e21629acd7a/swift/storage.py#L103-L114 |
44,041 | anthonyalmarza/chalk | chalk/logging.py | get_chalk | def get_chalk(level):
"""Gets the appropriate piece of chalk for the logging level
"""
if level >= logging.ERROR:
_chalk = chalk.red
elif level >= logging.WARNING:
_chalk = chalk.yellow
elif level >= logging.INFO:
_chalk = chalk.blue
elif level >= logging.DEBUG:
_... | python | def get_chalk(level):
"""Gets the appropriate piece of chalk for the logging level
"""
if level >= logging.ERROR:
_chalk = chalk.red
elif level >= logging.WARNING:
_chalk = chalk.yellow
elif level >= logging.INFO:
_chalk = chalk.blue
elif level >= logging.DEBUG:
_... | [
"def",
"get_chalk",
"(",
"level",
")",
":",
"if",
"level",
">=",
"logging",
".",
"ERROR",
":",
"_chalk",
"=",
"chalk",
".",
"red",
"elif",
"level",
">=",
"logging",
".",
"WARNING",
":",
"_chalk",
"=",
"chalk",
".",
"yellow",
"elif",
"level",
">=",
"l... | Gets the appropriate piece of chalk for the logging level | [
"Gets",
"the",
"appropriate",
"piece",
"of",
"chalk",
"for",
"the",
"logging",
"level"
] | 0f562c4ae7e0412f7a47d7b44778979761b380cc | https://github.com/anthonyalmarza/chalk/blob/0f562c4ae7e0412f7a47d7b44778979761b380cc/chalk/logging.py#L7-L20 |
44,042 | anthonyalmarza/chalk | chalk/utils.py | to_str | def to_str(obj):
"""Attempts to convert given object to a string object
"""
if not isinstance(obj, str) and PY3 and isinstance(obj, bytes):
obj = obj.decode('utf-8')
return obj if isinstance(obj, string_types) else str(obj) | python | def to_str(obj):
"""Attempts to convert given object to a string object
"""
if not isinstance(obj, str) and PY3 and isinstance(obj, bytes):
obj = obj.decode('utf-8')
return obj if isinstance(obj, string_types) else str(obj) | [
"def",
"to_str",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"str",
")",
"and",
"PY3",
"and",
"isinstance",
"(",
"obj",
",",
"bytes",
")",
":",
"obj",
"=",
"obj",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"obj",
"if",
"i... | Attempts to convert given object to a string object | [
"Attempts",
"to",
"convert",
"given",
"object",
"to",
"a",
"string",
"object"
] | 0f562c4ae7e0412f7a47d7b44778979761b380cc | https://github.com/anthonyalmarza/chalk/blob/0f562c4ae7e0412f7a47d7b44778979761b380cc/chalk/utils.py#L256-L261 |
44,043 | anthonyalmarza/chalk | chalk/utils.py | Color.get_color | def get_color(self, value):
"""Helper method to validate and map values used in the instantiation of
of the Color object to the correct unicode value.
"""
if value in COLOR_SET:
value = COLOR_MAP[value]
else:
try:
value = int(value)
... | python | def get_color(self, value):
"""Helper method to validate and map values used in the instantiation of
of the Color object to the correct unicode value.
"""
if value in COLOR_SET:
value = COLOR_MAP[value]
else:
try:
value = int(value)
... | [
"def",
"get_color",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"COLOR_SET",
":",
"value",
"=",
"COLOR_MAP",
"[",
"value",
"]",
"else",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"if",
"value",
">=",
"8",
":",
"raise",
... | Helper method to validate and map values used in the instantiation of
of the Color object to the correct unicode value. | [
"Helper",
"method",
"to",
"validate",
"and",
"map",
"values",
"used",
"in",
"the",
"instantiation",
"of",
"of",
"the",
"Color",
"object",
"to",
"the",
"correct",
"unicode",
"value",
"."
] | 0f562c4ae7e0412f7a47d7b44778979761b380cc | https://github.com/anthonyalmarza/chalk/blob/0f562c4ae7e0412f7a47d7b44778979761b380cc/chalk/utils.py#L124-L140 |
44,044 | icoxfog417/mlimages | mlimages/model.py | LabelFile.shuffle | def shuffle(self, overwrite=False):
"""
This method creates new shuffled file.
"""
if overwrite:
shuffled = self.path
else:
shuffled = FileAPI.add_ext_name(self.path, "_shuffled")
lines = open(self.path).readlines()
random.shuffle(lines)
... | python | def shuffle(self, overwrite=False):
"""
This method creates new shuffled file.
"""
if overwrite:
shuffled = self.path
else:
shuffled = FileAPI.add_ext_name(self.path, "_shuffled")
lines = open(self.path).readlines()
random.shuffle(lines)
... | [
"def",
"shuffle",
"(",
"self",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"overwrite",
":",
"shuffled",
"=",
"self",
".",
"path",
"else",
":",
"shuffled",
"=",
"FileAPI",
".",
"add_ext_name",
"(",
"self",
".",
"path",
",",
"\"_shuffled\"",
")",
"l... | This method creates new shuffled file. | [
"This",
"method",
"creates",
"new",
"shuffled",
"file",
"."
] | 724ce145e95a2e2c3597db43327f6e69babb83e2 | https://github.com/icoxfog417/mlimages/blob/724ce145e95a2e2c3597db43327f6e69babb83e2/mlimages/model.py#L44-L57 |
44,045 | biocore-ntnu/epic | epic/run/run_epic.py | multiple_files_count_reads_in_windows | def multiple_files_count_reads_in_windows(bed_files, args):
# type: (Iterable[str], Namespace) -> OrderedDict[str, List[pd.DataFrame]]
"""Use count_reads on multiple files and store result in dict.
Untested since does the same thing as count reads."""
bed_windows = OrderedDict() # type: OrderedDict[st... | python | def multiple_files_count_reads_in_windows(bed_files, args):
# type: (Iterable[str], Namespace) -> OrderedDict[str, List[pd.DataFrame]]
"""Use count_reads on multiple files and store result in dict.
Untested since does the same thing as count reads."""
bed_windows = OrderedDict() # type: OrderedDict[st... | [
"def",
"multiple_files_count_reads_in_windows",
"(",
"bed_files",
",",
"args",
")",
":",
"# type: (Iterable[str], Namespace) -> OrderedDict[str, List[pd.DataFrame]]",
"bed_windows",
"=",
"OrderedDict",
"(",
")",
"# type: OrderedDict[str, List[pd.DataFrame]]",
"for",
"bed_file",
"in... | Use count_reads on multiple files and store result in dict.
Untested since does the same thing as count reads. | [
"Use",
"count_reads",
"on",
"multiple",
"files",
"and",
"store",
"result",
"in",
"dict",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/run/run_epic.py#L129-L144 |
44,046 | biocore-ntnu/epic | epic/run/run_epic.py | _merge_files | def _merge_files(windows, nb_cpu):
# type: (Iterable[pd.DataFrame], int) -> pd.DataFrame
"""Merge lists of chromosome bin df chromosome-wise.
windows is an OrderedDict where the keys are files, the values are lists of
dfs, one per chromosome.
Returns a list of dataframes, one per chromosome, with ... | python | def _merge_files(windows, nb_cpu):
# type: (Iterable[pd.DataFrame], int) -> pd.DataFrame
"""Merge lists of chromosome bin df chromosome-wise.
windows is an OrderedDict where the keys are files, the values are lists of
dfs, one per chromosome.
Returns a list of dataframes, one per chromosome, with ... | [
"def",
"_merge_files",
"(",
"windows",
",",
"nb_cpu",
")",
":",
"# type: (Iterable[pd.DataFrame], int) -> pd.DataFrame",
"# windows is a list of chromosome dfs per file",
"windows",
"=",
"iter",
"(",
"windows",
")",
"# can iterate over because it is odict_values",
"merged",
"=",
... | Merge lists of chromosome bin df chromosome-wise.
windows is an OrderedDict where the keys are files, the values are lists of
dfs, one per chromosome.
Returns a list of dataframes, one per chromosome, with the collective count
per bin for all files.
TODO: is it faster to merge all in one command? | [
"Merge",
"lists",
"of",
"chromosome",
"bin",
"df",
"chromosome",
"-",
"wise",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/run/run_epic.py#L147-L169 |
44,047 | kvesteri/intervals | intervals/interval.py | py2round | def py2round(value):
"""Round values as in Python 2, for Python 3 compatibility.
All x.5 values are rounded away from zero.
In Python 3, this has changed to avoid bias: when x is even,
rounding is towards zero, when x is odd, rounding is away
from zero. Thus, in Python 3, round(2.5) results in 2,
... | python | def py2round(value):
"""Round values as in Python 2, for Python 3 compatibility.
All x.5 values are rounded away from zero.
In Python 3, this has changed to avoid bias: when x is even,
rounding is towards zero, when x is odd, rounding is away
from zero. Thus, in Python 3, round(2.5) results in 2,
... | [
"def",
"py2round",
"(",
"value",
")",
":",
"if",
"value",
">",
"0",
":",
"return",
"float",
"(",
"floor",
"(",
"float",
"(",
"value",
")",
"+",
"0.5",
")",
")",
"else",
":",
"return",
"float",
"(",
"ceil",
"(",
"float",
"(",
"value",
")",
"-",
... | Round values as in Python 2, for Python 3 compatibility.
All x.5 values are rounded away from zero.
In Python 3, this has changed to avoid bias: when x is even,
rounding is towards zero, when x is odd, rounding is away
from zero. Thus, in Python 3, round(2.5) results in 2,
round(3.5) is 4.
Py... | [
"Round",
"values",
"as",
"in",
"Python",
"2",
"for",
"Python",
"3",
"compatibility",
"."
] | 964c9c19826aaa4a6277a584c2427f18d8102542 | https://github.com/kvesteri/intervals/blob/964c9c19826aaa4a6277a584c2427f18d8102542/intervals/interval.py#L30-L45 |
44,048 | kvesteri/intervals | intervals/interval.py | canonicalize | def canonicalize(interval, lower_inc=True, upper_inc=False):
"""
Convert equivalent discrete intervals to different representations.
"""
if not interval.discrete:
raise TypeError('Only discrete ranges can be canonicalized')
if interval.empty:
return interval
lower, lower_inc = ... | python | def canonicalize(interval, lower_inc=True, upper_inc=False):
"""
Convert equivalent discrete intervals to different representations.
"""
if not interval.discrete:
raise TypeError('Only discrete ranges can be canonicalized')
if interval.empty:
return interval
lower, lower_inc = ... | [
"def",
"canonicalize",
"(",
"interval",
",",
"lower_inc",
"=",
"True",
",",
"upper_inc",
"=",
"False",
")",
":",
"if",
"not",
"interval",
".",
"discrete",
":",
"raise",
"TypeError",
"(",
"'Only discrete ranges can be canonicalized'",
")",
"if",
"interval",
".",
... | Convert equivalent discrete intervals to different representations. | [
"Convert",
"equivalent",
"discrete",
"intervals",
"to",
"different",
"representations",
"."
] | 964c9c19826aaa4a6277a584c2427f18d8102542 | https://github.com/kvesteri/intervals/blob/964c9c19826aaa4a6277a584c2427f18d8102542/intervals/interval.py#L66-L83 |
44,049 | kvesteri/intervals | intervals/interval.py | AbstractInterval.glb | def glb(self, other):
"""
Return the greatest lower bound for given intervals.
:param other: AbstractInterval instance
"""
return self.__class__(
[
min(self.lower, other.lower),
min(self.upper, other.upper)
],
l... | python | def glb(self, other):
"""
Return the greatest lower bound for given intervals.
:param other: AbstractInterval instance
"""
return self.__class__(
[
min(self.lower, other.lower),
min(self.upper, other.upper)
],
l... | [
"def",
"glb",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"[",
"min",
"(",
"self",
".",
"lower",
",",
"other",
".",
"lower",
")",
",",
"min",
"(",
"self",
".",
"upper",
",",
"other",
".",
"upper",
")",
"]",
","... | Return the greatest lower bound for given intervals.
:param other: AbstractInterval instance | [
"Return",
"the",
"greatest",
"lower",
"bound",
"for",
"given",
"intervals",
"."
] | 964c9c19826aaa4a6277a584c2427f18d8102542 | https://github.com/kvesteri/intervals/blob/964c9c19826aaa4a6277a584c2427f18d8102542/intervals/interval.py#L542-L555 |
44,050 | kvesteri/intervals | intervals/interval.py | AbstractInterval.lub | def lub(self, other):
"""
Return the least upper bound for given intervals.
:param other: AbstractInterval instance
"""
return self.__class__(
[
max(self.lower, other.lower),
max(self.upper, other.upper),
],
low... | python | def lub(self, other):
"""
Return the least upper bound for given intervals.
:param other: AbstractInterval instance
"""
return self.__class__(
[
max(self.lower, other.lower),
max(self.upper, other.upper),
],
low... | [
"def",
"lub",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"[",
"max",
"(",
"self",
".",
"lower",
",",
"other",
".",
"lower",
")",
",",
"max",
"(",
"self",
".",
"upper",
",",
"other",
".",
"upper",
")",
",",
"]"... | Return the least upper bound for given intervals.
:param other: AbstractInterval instance | [
"Return",
"the",
"least",
"upper",
"bound",
"for",
"given",
"intervals",
"."
] | 964c9c19826aaa4a6277a584c2427f18d8102542 | https://github.com/kvesteri/intervals/blob/964c9c19826aaa4a6277a584c2427f18d8102542/intervals/interval.py#L558-L571 |
44,051 | biocore-ntnu/epic | epic/statistics/compute_values_needed_for_recurrence.py | compute_enriched_threshold | def compute_enriched_threshold(average_window_readcount):
# type: (float) -> int
"""
Computes the minimum number of tags required in window for an island to be enriched.
"""
current_threshold, survival_function = 0, 1
for current_threshold in count(start=0, step=1):
survival_function -=... | python | def compute_enriched_threshold(average_window_readcount):
# type: (float) -> int
"""
Computes the minimum number of tags required in window for an island to be enriched.
"""
current_threshold, survival_function = 0, 1
for current_threshold in count(start=0, step=1):
survival_function -=... | [
"def",
"compute_enriched_threshold",
"(",
"average_window_readcount",
")",
":",
"# type: (float) -> int",
"current_threshold",
",",
"survival_function",
"=",
"0",
",",
"1",
"for",
"current_threshold",
"in",
"count",
"(",
"start",
"=",
"0",
",",
"step",
"=",
"1",
"... | Computes the minimum number of tags required in window for an island to be enriched. | [
"Computes",
"the",
"minimum",
"number",
"of",
"tags",
"required",
"in",
"window",
"for",
"an",
"island",
"to",
"be",
"enriched",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/statistics/compute_values_needed_for_recurrence.py#L7-L22 |
44,052 | biocore-ntnu/epic | epic/statistics/compute_poisson.py | _factln | def _factln(num):
# type: (int) -> float
"""
Computes logfactorial regularly for tractable numbers, uses Ramanujans approximation otherwise.
"""
if num < 20:
log_factorial = log(factorial(num))
else:
log_factorial = num * log(num) - num + log(num * (1 + 4 * num * (
1... | python | def _factln(num):
# type: (int) -> float
"""
Computes logfactorial regularly for tractable numbers, uses Ramanujans approximation otherwise.
"""
if num < 20:
log_factorial = log(factorial(num))
else:
log_factorial = num * log(num) - num + log(num * (1 + 4 * num * (
1... | [
"def",
"_factln",
"(",
"num",
")",
":",
"# type: (int) -> float",
"if",
"num",
"<",
"20",
":",
"log_factorial",
"=",
"log",
"(",
"factorial",
"(",
"num",
")",
")",
"else",
":",
"log_factorial",
"=",
"num",
"*",
"log",
"(",
"num",
")",
"-",
"num",
"+"... | Computes logfactorial regularly for tractable numbers, uses Ramanujans approximation otherwise. | [
"Computes",
"logfactorial",
"regularly",
"for",
"tractable",
"numbers",
"uses",
"Ramanujans",
"approximation",
"otherwise",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/statistics/compute_poisson.py#L6-L18 |
44,053 | biocore-ntnu/epic | epic/merge/merge_helpers.py | add_new_enriched_bins_matrixes | def add_new_enriched_bins_matrixes(region_files, dfs, bin_size):
"""Add enriched bins based on bed files.
There is no way to find the correspondence between region file and matrix
file, but it does not matter."""
dfs = _remove_epic_enriched(dfs)
names = ["Enriched_" + os.path.basename(r) for r i... | python | def add_new_enriched_bins_matrixes(region_files, dfs, bin_size):
"""Add enriched bins based on bed files.
There is no way to find the correspondence between region file and matrix
file, but it does not matter."""
dfs = _remove_epic_enriched(dfs)
names = ["Enriched_" + os.path.basename(r) for r i... | [
"def",
"add_new_enriched_bins_matrixes",
"(",
"region_files",
",",
"dfs",
",",
"bin_size",
")",
":",
"dfs",
"=",
"_remove_epic_enriched",
"(",
"dfs",
")",
"names",
"=",
"[",
"\"Enriched_\"",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"r",
")",
"for",
"r... | Add enriched bins based on bed files.
There is no way to find the correspondence between region file and matrix
file, but it does not matter. | [
"Add",
"enriched",
"bins",
"based",
"on",
"bed",
"files",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/merge/merge_helpers.py#L51-L75 |
44,054 | biocore-ntnu/epic | epic/windows/count/merge_chromosome_dfs.py | merge_chromosome_dfs | def merge_chromosome_dfs(df_tuple):
# type: (Tuple[pd.DataFrame, pd.DataFrame]) -> pd.DataFrame
"""Merges data from the two strands into strand-agnostic counts."""
plus_df, minus_df = df_tuple
index_cols = "Chromosome Bin".split()
count_column = plus_df.columns[0]
if plus_df.empty:
ret... | python | def merge_chromosome_dfs(df_tuple):
# type: (Tuple[pd.DataFrame, pd.DataFrame]) -> pd.DataFrame
"""Merges data from the two strands into strand-agnostic counts."""
plus_df, minus_df = df_tuple
index_cols = "Chromosome Bin".split()
count_column = plus_df.columns[0]
if plus_df.empty:
ret... | [
"def",
"merge_chromosome_dfs",
"(",
"df_tuple",
")",
":",
"# type: (Tuple[pd.DataFrame, pd.DataFrame]) -> pd.DataFrame",
"plus_df",
",",
"minus_df",
"=",
"df_tuple",
"index_cols",
"=",
"\"Chromosome Bin\"",
".",
"split",
"(",
")",
"count_column",
"=",
"plus_df",
".",
"c... | Merges data from the two strands into strand-agnostic counts. | [
"Merges",
"data",
"from",
"the",
"two",
"strands",
"into",
"strand",
"-",
"agnostic",
"counts",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/windows/count/merge_chromosome_dfs.py#L5-L32 |
44,055 | biocore-ntnu/epic | epic/bigwig/create_bigwigs.py | create_log2fc_bigwigs | def create_log2fc_bigwigs(matrix, outdir, args):
# type: (pd.DataFrame, str, Namespace) -> None
"""Create bigwigs from matrix."""
call("mkdir -p {}".format(outdir), shell=True)
genome_size_dict = args.chromosome_sizes
outpaths = []
for bed_file in matrix[args.treatment]:
outpath = join... | python | def create_log2fc_bigwigs(matrix, outdir, args):
# type: (pd.DataFrame, str, Namespace) -> None
"""Create bigwigs from matrix."""
call("mkdir -p {}".format(outdir), shell=True)
genome_size_dict = args.chromosome_sizes
outpaths = []
for bed_file in matrix[args.treatment]:
outpath = join... | [
"def",
"create_log2fc_bigwigs",
"(",
"matrix",
",",
"outdir",
",",
"args",
")",
":",
"# type: (pd.DataFrame, str, Namespace) -> None",
"call",
"(",
"\"mkdir -p {}\"",
".",
"format",
"(",
"outdir",
")",
",",
"shell",
"=",
"True",
")",
"genome_size_dict",
"=",
"args... | Create bigwigs from matrix. | [
"Create",
"bigwigs",
"from",
"matrix",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/bigwig/create_bigwigs.py#L33-L47 |
44,056 | biocore-ntnu/epic | epic/statistics/add_to_island_expectations.py | add_to_island_expectations_dict | def add_to_island_expectations_dict(average_window_readcount,
current_max_scaled_score,
island_eligibility_threshold,
island_expectations, gap_contribution):
# type: ( float, int, float, Dict[int, float], flo... | python | def add_to_island_expectations_dict(average_window_readcount,
current_max_scaled_score,
island_eligibility_threshold,
island_expectations, gap_contribution):
# type: ( float, int, float, Dict[int, float], flo... | [
"def",
"add_to_island_expectations_dict",
"(",
"average_window_readcount",
",",
"current_max_scaled_score",
",",
"island_eligibility_threshold",
",",
"island_expectations",
",",
"gap_contribution",
")",
":",
"# type: ( float, int, float, Dict[int, float], float) -> Dict[int, float]",
"... | Can probably be heavily optimized.
Time required to run can be seen from logging info. | [
"Can",
"probably",
"be",
"heavily",
"optimized",
".",
"Time",
"required",
"to",
"run",
"can",
"be",
"seen",
"from",
"logging",
"info",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/statistics/add_to_island_expectations.py#L12-L41 |
44,057 | biocore-ntnu/epic | epic/scripts/effective_genome_size.py | effective_genome_size | def effective_genome_size(fasta, read_length, nb_cores, tmpdir="/tmp"):
# type: (str, int, int, str) -> None
"""Compute effective genome size for genome."""
idx = Fasta(fasta)
genome_length = sum([len(c) for c in idx])
logging.info("Temporary directory: " + tmpdir)
logging.info("File analyzed... | python | def effective_genome_size(fasta, read_length, nb_cores, tmpdir="/tmp"):
# type: (str, int, int, str) -> None
"""Compute effective genome size for genome."""
idx = Fasta(fasta)
genome_length = sum([len(c) for c in idx])
logging.info("Temporary directory: " + tmpdir)
logging.info("File analyzed... | [
"def",
"effective_genome_size",
"(",
"fasta",
",",
"read_length",
",",
"nb_cores",
",",
"tmpdir",
"=",
"\"/tmp\"",
")",
":",
"# type: (str, int, int, str) -> None",
"idx",
"=",
"Fasta",
"(",
"fasta",
")",
"genome_length",
"=",
"sum",
"(",
"[",
"len",
"(",
"c",... | Compute effective genome size for genome. | [
"Compute",
"effective",
"genome",
"size",
"for",
"genome",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/scripts/effective_genome_size.py#L15-L68 |
44,058 | biocore-ntnu/epic | epic/matrixes/matrixes.py | get_island_bins | def get_island_bins(df, window_size, genome, args):
# type: (pd.DataFrame, int, str, Namespace) -> Dict[str, Set[int]]
"""Finds the enriched bins in a df."""
# need these chromos because the df might not have islands in all chromos
chromosomes = natsorted(list(args.chromosome_sizes))
chromosome_is... | python | def get_island_bins(df, window_size, genome, args):
# type: (pd.DataFrame, int, str, Namespace) -> Dict[str, Set[int]]
"""Finds the enriched bins in a df."""
# need these chromos because the df might not have islands in all chromos
chromosomes = natsorted(list(args.chromosome_sizes))
chromosome_is... | [
"def",
"get_island_bins",
"(",
"df",
",",
"window_size",
",",
"genome",
",",
"args",
")",
":",
"# type: (pd.DataFrame, int, str, Namespace) -> Dict[str, Set[int]]",
"# need these chromos because the df might not have islands in all chromos",
"chromosomes",
"=",
"natsorted",
"(",
... | Finds the enriched bins in a df. | [
"Finds",
"the",
"enriched",
"bins",
"in",
"a",
"df",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/matrixes/matrixes.py#L184-L205 |
44,059 | biocore-ntnu/epic | epic/config/genomes.py | create_genome_size_dict | def create_genome_size_dict(genome):
# type: (str) -> Dict[str,int]
"""Creates genome size dict from string containing data."""
size_file = get_genome_size_file(genome)
size_lines = open(size_file).readlines()
size_dict = {}
for line in size_lines:
genome, length = line.split()
... | python | def create_genome_size_dict(genome):
# type: (str) -> Dict[str,int]
"""Creates genome size dict from string containing data."""
size_file = get_genome_size_file(genome)
size_lines = open(size_file).readlines()
size_dict = {}
for line in size_lines:
genome, length = line.split()
... | [
"def",
"create_genome_size_dict",
"(",
"genome",
")",
":",
"# type: (str) -> Dict[str,int]",
"size_file",
"=",
"get_genome_size_file",
"(",
"genome",
")",
"size_lines",
"=",
"open",
"(",
"size_file",
")",
".",
"readlines",
"(",
")",
"size_dict",
"=",
"{",
"}",
"... | Creates genome size dict from string containing data. | [
"Creates",
"genome",
"size",
"dict",
"from",
"string",
"containing",
"data",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/config/genomes.py#L29-L41 |
44,060 | biocore-ntnu/epic | epic/statistics/compute_score_threshold.py | compute_score_threshold | def compute_score_threshold(average_window_readcount,
island_enriched_threshold,
gap_contribution, boundary_contribution,
genome_length_in_bins):
# type: (float, int, float, float, float) -> float
"""
What does island_expect... | python | def compute_score_threshold(average_window_readcount,
island_enriched_threshold,
gap_contribution, boundary_contribution,
genome_length_in_bins):
# type: (float, int, float, float, float) -> float
"""
What does island_expect... | [
"def",
"compute_score_threshold",
"(",
"average_window_readcount",
",",
"island_enriched_threshold",
",",
"gap_contribution",
",",
"boundary_contribution",
",",
"genome_length_in_bins",
")",
":",
"# type: (float, int, float, float, float) -> float",
"required_p_value",
"=",
"poisso... | What does island_expectations do? | [
"What",
"does",
"island_expectations",
"do?"
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/statistics/compute_score_threshold.py#L10-L67 |
44,061 | biocore-ntnu/epic | epic/utils/find_readlength.py | find_readlength | def find_readlength(args):
# type: (Namespace) -> int
"""Estimate length of reads based on 10000 first."""
try:
bed_file = args.treatment[0]
except AttributeError:
bed_file = args.infiles[0]
filereader = "cat "
if bed_file.endswith(".gz") and search("linux", platform, IGNORECAS... | python | def find_readlength(args):
# type: (Namespace) -> int
"""Estimate length of reads based on 10000 first."""
try:
bed_file = args.treatment[0]
except AttributeError:
bed_file = args.infiles[0]
filereader = "cat "
if bed_file.endswith(".gz") and search("linux", platform, IGNORECAS... | [
"def",
"find_readlength",
"(",
"args",
")",
":",
"# type: (Namespace) -> int",
"try",
":",
"bed_file",
"=",
"args",
".",
"treatment",
"[",
"0",
"]",
"except",
"AttributeError",
":",
"bed_file",
"=",
"args",
".",
"infiles",
"[",
"0",
"]",
"filereader",
"=",
... | Estimate length of reads based on 10000 first. | [
"Estimate",
"length",
"of",
"reads",
"based",
"on",
"10000",
"first",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/utils/find_readlength.py#L16-L55 |
44,062 | biocore-ntnu/epic | epic/utils/find_readlength.py | get_closest_readlength | def get_closest_readlength(estimated_readlength):
# type: (int) -> int
"""Find the predefined readlength closest to the estimated readlength.
In the case of a tie, choose the shortest readlength."""
readlengths = [36, 50, 75, 100]
differences = [abs(r - estimated_readlength) for r in readlengths]
... | python | def get_closest_readlength(estimated_readlength):
# type: (int) -> int
"""Find the predefined readlength closest to the estimated readlength.
In the case of a tie, choose the shortest readlength."""
readlengths = [36, 50, 75, 100]
differences = [abs(r - estimated_readlength) for r in readlengths]
... | [
"def",
"get_closest_readlength",
"(",
"estimated_readlength",
")",
":",
"# type: (int) -> int",
"readlengths",
"=",
"[",
"36",
",",
"50",
",",
"75",
",",
"100",
"]",
"differences",
"=",
"[",
"abs",
"(",
"r",
"-",
"estimated_readlength",
")",
"for",
"r",
"in"... | Find the predefined readlength closest to the estimated readlength.
In the case of a tie, choose the shortest readlength. | [
"Find",
"the",
"predefined",
"readlength",
"closest",
"to",
"the",
"estimated",
"readlength",
"."
] | ed0024939ec6182a0a39d59d845ff14a4889a6ef | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/utils/find_readlength.py#L58-L71 |
44,063 | shendo/websnort | websnort/ids/snort.py | parse_version | def parse_version(output):
"""
Parses the supplied output and returns the version string.
:param output: A string containing the output of running snort.
:returns: Version string for the version of snort run. None if not found.
"""
for x in output.splitlines():
match = VERSION_PATTERN.m... | python | def parse_version(output):
"""
Parses the supplied output and returns the version string.
:param output: A string containing the output of running snort.
:returns: Version string for the version of snort run. None if not found.
"""
for x in output.splitlines():
match = VERSION_PATTERN.m... | [
"def",
"parse_version",
"(",
"output",
")",
":",
"for",
"x",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"match",
"=",
"VERSION_PATTERN",
".",
"match",
"(",
"x",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"'version'",
")",
"... | Parses the supplied output and returns the version string.
:param output: A string containing the output of running snort.
:returns: Version string for the version of snort run. None if not found. | [
"Parses",
"the",
"supplied",
"output",
"and",
"returns",
"the",
"version",
"string",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/ids/snort.py#L80-L91 |
44,064 | shendo/websnort | websnort/ids/snort.py | parse_alert | def parse_alert(output):
"""
Parses the supplied output and yields any alerts.
Example alert format:
01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900
... | python | def parse_alert(output):
"""
Parses the supplied output and yields any alerts.
Example alert format:
01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900
... | [
"def",
"parse_alert",
"(",
"output",
")",
":",
"for",
"x",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"match",
"=",
"ALERT_PATTERN",
".",
"match",
"(",
"x",
")",
"if",
"match",
":",
"rec",
"=",
"{",
"'timestamp'",
":",
"datetime",
".",
"strpti... | Parses the supplied output and yields any alerts.
Example alert format:
01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900
:param output: A string containing... | [
"Parses",
"the",
"supplied",
"output",
"and",
"yields",
"any",
"alerts",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/ids/snort.py#L93-L118 |
44,065 | shendo/websnort | websnort/ids/snort.py | Snort.run | def run(self, pcap):
"""
Runs snort against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
proc = Popen(self._snort_cmd(pcap), stdout=PIPE,
stderr=PIPE, universal_newlines=True)
st... | python | def run(self, pcap):
"""
Runs snort against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
proc = Popen(self._snort_cmd(pcap), stdout=PIPE,
stderr=PIPE, universal_newlines=True)
st... | [
"def",
"run",
"(",
"self",
",",
"pcap",
")",
":",
"proc",
"=",
"Popen",
"(",
"self",
".",
"_snort_cmd",
"(",
"pcap",
")",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"universal_newlines",
"=",
"True",
")",
"stdout",
",",
"stderr",
... | Runs snort against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts | [
"Runs",
"snort",
"against",
"the",
"supplied",
"pcap",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/ids/snort.py#L63-L78 |
44,066 | shendo/websnort | websnort/ids/suricata.py | Suricata.run | def run(self, pcap):
"""
Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
tmpdir = None
try:
tmpdir = tempfile.mkdtemp(prefix='tmpsuri')
proc = Popen(self._s... | python | def run(self, pcap):
"""
Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
tmpdir = None
try:
tmpdir = tempfile.mkdtemp(prefix='tmpsuri')
proc = Popen(self._s... | [
"def",
"run",
"(",
"self",
",",
"pcap",
")",
":",
"tmpdir",
"=",
"None",
"try",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'tmpsuri'",
")",
"proc",
"=",
"Popen",
"(",
"self",
".",
"_suri_cmd",
"(",
"pcap",
",",
"tmpdir",
"... | Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts | [
"Runs",
"suricata",
"against",
"the",
"supplied",
"pcap",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/ids/suricata.py#L66-L88 |
44,067 | shendo/websnort | websnort/web.py | analyse_pcap | def analyse_pcap(infile, filename):
"""
Run IDS across the supplied file.
:param infile: File like object containing pcap data.
:param filename: Filename of the submitted file.
:returns: Dictionary of analysis results.
"""
tmp = tempfile.NamedTemporaryFile(suffix=".pcap", delete=False)
... | python | def analyse_pcap(infile, filename):
"""
Run IDS across the supplied file.
:param infile: File like object containing pcap data.
:param filename: Filename of the submitted file.
:returns: Dictionary of analysis results.
"""
tmp = tempfile.NamedTemporaryFile(suffix=".pcap", delete=False)
... | [
"def",
"analyse_pcap",
"(",
"infile",
",",
"filename",
")",
":",
"tmp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"\".pcap\"",
",",
"delete",
"=",
"False",
")",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"results",
"=",
"{",
"'fil... | Run IDS across the supplied file.
:param infile: File like object containing pcap data.
:param filename: Filename of the submitted file.
:returns: Dictionary of analysis results. | [
"Run",
"IDS",
"across",
"the",
"supplied",
"file",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/web.py#L59-L89 |
44,068 | shendo/websnort | websnort/web.py | submit_and_render | def submit_and_render():
"""
Blocking POST handler for file submission.
Runs snort on supplied file and returns results as rendered html.
"""
data = request.files.file
template = env.get_template("results.html")
if not data:
pass
results = analyse_pcap(data.file, data.filename)
... | python | def submit_and_render():
"""
Blocking POST handler for file submission.
Runs snort on supplied file and returns results as rendered html.
"""
data = request.files.file
template = env.get_template("results.html")
if not data:
pass
results = analyse_pcap(data.file, data.filename)
... | [
"def",
"submit_and_render",
"(",
")",
":",
"data",
"=",
"request",
".",
"files",
".",
"file",
"template",
"=",
"env",
".",
"get_template",
"(",
"\"results.html\"",
")",
"if",
"not",
"data",
":",
"pass",
"results",
"=",
"analyse_pcap",
"(",
"data",
".",
"... | Blocking POST handler for file submission.
Runs snort on supplied file and returns results as rendered html. | [
"Blocking",
"POST",
"handler",
"for",
"file",
"submission",
".",
"Runs",
"snort",
"on",
"supplied",
"file",
"and",
"returns",
"results",
"as",
"rendered",
"html",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/web.py#L92-L103 |
44,069 | shendo/websnort | websnort/web.py | api_submit | def api_submit():
"""
Blocking POST handler for file submission.
Runs snort on supplied file and returns results as json text.
"""
data = request.files.file
response.content_type = 'application/json'
if not data or not hasattr(data, 'file'):
return json.dumps({"status": "Failed", "st... | python | def api_submit():
"""
Blocking POST handler for file submission.
Runs snort on supplied file and returns results as json text.
"""
data = request.files.file
response.content_type = 'application/json'
if not data or not hasattr(data, 'file'):
return json.dumps({"status": "Failed", "st... | [
"def",
"api_submit",
"(",
")",
":",
"data",
"=",
"request",
".",
"files",
".",
"file",
"response",
".",
"content_type",
"=",
"'application/json'",
"if",
"not",
"data",
"or",
"not",
"hasattr",
"(",
"data",
",",
"'file'",
")",
":",
"return",
"json",
".",
... | Blocking POST handler for file submission.
Runs snort on supplied file and returns results as json text. | [
"Blocking",
"POST",
"handler",
"for",
"file",
"submission",
".",
"Runs",
"snort",
"on",
"supplied",
"file",
"and",
"returns",
"results",
"as",
"json",
"text",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/web.py#L106-L115 |
44,070 | shendo/websnort | websnort/web.py | main | def main():
"""
Main entrypoint for command-line webserver.
"""
parser = argparse.ArgumentParser()
parser.add_argument("-H", "--host", help="Web server Host address to bind to",
default="0.0.0.0", action="store", required=False)
parser.add_argument("-p", "--port", help="W... | python | def main():
"""
Main entrypoint for command-line webserver.
"""
parser = argparse.ArgumentParser()
parser.add_argument("-H", "--host", help="Web server Host address to bind to",
default="0.0.0.0", action="store", required=False)
parser.add_argument("-p", "--port", help="W... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"-H\"",
",",
"\"--host\"",
",",
"help",
"=",
"\"Web server Host address to bind to\"",
",",
"default",
"=",
"\"0.0.0.0\"",
",",
"act... | Main entrypoint for command-line webserver. | [
"Main",
"entrypoint",
"for",
"command",
"-",
"line",
"webserver",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/web.py#L126-L138 |
44,071 | shendo/websnort | websnort/runner.py | is_pcap | def is_pcap(pcap):
"""
Simple test for pcap magic bytes in supplied file.
:param pcap: File path to Pcap file to check
:returns: True if content is pcap (magic bytes present), otherwise False.
"""
with open(pcap, 'rb') as tmp:
header = tmp.read(4)
# check for both big/little end... | python | def is_pcap(pcap):
"""
Simple test for pcap magic bytes in supplied file.
:param pcap: File path to Pcap file to check
:returns: True if content is pcap (magic bytes present), otherwise False.
"""
with open(pcap, 'rb') as tmp:
header = tmp.read(4)
# check for both big/little end... | [
"def",
"is_pcap",
"(",
"pcap",
")",
":",
"with",
"open",
"(",
"pcap",
",",
"'rb'",
")",
"as",
"tmp",
":",
"header",
"=",
"tmp",
".",
"read",
"(",
"4",
")",
"# check for both big/little endian",
"if",
"header",
"==",
"b\"\\xa1\\xb2\\xc3\\xd4\"",
"or",
"head... | Simple test for pcap magic bytes in supplied file.
:param pcap: File path to Pcap file to check
:returns: True if content is pcap (magic bytes present), otherwise False. | [
"Simple",
"test",
"for",
"pcap",
"magic",
"bytes",
"in",
"supplied",
"file",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/runner.py#L46-L59 |
44,072 | shendo/websnort | websnort/runner.py | _run_ids | def _run_ids(runner, pcap):
"""
Runs the specified IDS runner.
:param runner: Runner instance to use
:param pcap: File path to pcap for analysis
:returns: dict of run metadata/alerts
"""
run = {'name': runner.conf.get('name'),
'module': runner.conf.get('module'),
'rule... | python | def _run_ids(runner, pcap):
"""
Runs the specified IDS runner.
:param runner: Runner instance to use
:param pcap: File path to pcap for analysis
:returns: dict of run metadata/alerts
"""
run = {'name': runner.conf.get('name'),
'module': runner.conf.get('module'),
'rule... | [
"def",
"_run_ids",
"(",
"runner",
",",
"pcap",
")",
":",
"run",
"=",
"{",
"'name'",
":",
"runner",
".",
"conf",
".",
"get",
"(",
"'name'",
")",
",",
"'module'",
":",
"runner",
".",
"conf",
".",
"get",
"(",
"'module'",
")",
",",
"'ruleset'",
":",
... | Runs the specified IDS runner.
:param runner: Runner instance to use
:param pcap: File path to pcap for analysis
:returns: dict of run metadata/alerts | [
"Runs",
"the",
"specified",
"IDS",
"runner",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/runner.py#L61-L84 |
44,073 | shendo/websnort | websnort/runner.py | run | def run(pcap):
"""
Runs all configured IDS instances against the supplied pcap.
:param pcap: File path to pcap file to analyse
:returns: Dict with details and results of run/s
"""
start = datetime.now()
errors = []
status = STATUS_FAILED
analyses = []
pool = ThreadPool(MAX_THREA... | python | def run(pcap):
"""
Runs all configured IDS instances against the supplied pcap.
:param pcap: File path to pcap file to analyse
:returns: Dict with details and results of run/s
"""
start = datetime.now()
errors = []
status = STATUS_FAILED
analyses = []
pool = ThreadPool(MAX_THREA... | [
"def",
"run",
"(",
"pcap",
")",
":",
"start",
"=",
"datetime",
".",
"now",
"(",
")",
"errors",
"=",
"[",
"]",
"status",
"=",
"STATUS_FAILED",
"analyses",
"=",
"[",
"]",
"pool",
"=",
"ThreadPool",
"(",
"MAX_THREADS",
")",
"try",
":",
"if",
"not",
"i... | Runs all configured IDS instances against the supplied pcap.
:param pcap: File path to pcap file to analyse
:returns: Dict with details and results of run/s | [
"Runs",
"all",
"configured",
"IDS",
"instances",
"against",
"the",
"supplied",
"pcap",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/runner.py#L86-L126 |
44,074 | gmcguire/django-db-pool | dbpool/db/backends/postgresql_psycopg2/base.py | _set_up_pool_config | def _set_up_pool_config(self):
'''
Helper to configure pool options during DatabaseWrapper initialization.
'''
self._max_conns = self.settings_dict['OPTIONS'].get('MAX_CONNS', pool_config_defaults['MAX_CONNS'])
self._min_conns = self.settings_dict['OPTIONS'].get('MIN_CONNS', self._max_conns)
... | python | def _set_up_pool_config(self):
'''
Helper to configure pool options during DatabaseWrapper initialization.
'''
self._max_conns = self.settings_dict['OPTIONS'].get('MAX_CONNS', pool_config_defaults['MAX_CONNS'])
self._min_conns = self.settings_dict['OPTIONS'].get('MIN_CONNS', self._max_conns)
... | [
"def",
"_set_up_pool_config",
"(",
"self",
")",
":",
"self",
".",
"_max_conns",
"=",
"self",
".",
"settings_dict",
"[",
"'OPTIONS'",
"]",
".",
"get",
"(",
"'MAX_CONNS'",
",",
"pool_config_defaults",
"[",
"'MAX_CONNS'",
"]",
")",
"self",
".",
"_min_conns",
"=... | Helper to configure pool options during DatabaseWrapper initialization. | [
"Helper",
"to",
"configure",
"pool",
"options",
"during",
"DatabaseWrapper",
"initialization",
"."
] | d4e0aa6a150fd7bd2024e079cd3b7147ea341e63 | https://github.com/gmcguire/django-db-pool/blob/d4e0aa6a150fd7bd2024e079cd3b7147ea341e63/dbpool/db/backends/postgresql_psycopg2/base.py#L85-L98 |
44,075 | gmcguire/django-db-pool | dbpool/db/backends/postgresql_psycopg2/base.py | _create_connection_pool | def _create_connection_pool(self, conn_params):
'''
Helper to initialize the connection pool.
'''
connection_pools_lock.acquire()
try:
# One more read to prevent a read/write race condition (We do this
# here to avoid the overhead of locking each time we get a connection.)
if... | python | def _create_connection_pool(self, conn_params):
'''
Helper to initialize the connection pool.
'''
connection_pools_lock.acquire()
try:
# One more read to prevent a read/write race condition (We do this
# here to avoid the overhead of locking each time we get a connection.)
if... | [
"def",
"_create_connection_pool",
"(",
"self",
",",
"conn_params",
")",
":",
"connection_pools_lock",
".",
"acquire",
"(",
")",
"try",
":",
"# One more read to prevent a read/write race condition (We do this",
"# here to avoid the overhead of locking each time we get a connection.)",... | Helper to initialize the connection pool. | [
"Helper",
"to",
"initialize",
"the",
"connection",
"pool",
"."
] | d4e0aa6a150fd7bd2024e079cd3b7147ea341e63 | https://github.com/gmcguire/django-db-pool/blob/d4e0aa6a150fd7bd2024e079cd3b7147ea341e63/dbpool/db/backends/postgresql_psycopg2/base.py#L101-L122 |
44,076 | gmcguire/django-db-pool | dbpool/db/backends/postgresql_psycopg2/base.py | PooledConnection.close | def close(self):
'''
Override to return the connection to the pool rather than closing it.
'''
if self._wrapped_connection and self._pool:
logger.debug("Returning connection %s to pool %s" % (self._wrapped_connection, self._pool))
self._pool.putconn(self._wrapped_... | python | def close(self):
'''
Override to return the connection to the pool rather than closing it.
'''
if self._wrapped_connection and self._pool:
logger.debug("Returning connection %s to pool %s" % (self._wrapped_connection, self._pool))
self._pool.putconn(self._wrapped_... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wrapped_connection",
"and",
"self",
".",
"_pool",
":",
"logger",
".",
"debug",
"(",
"\"Returning connection %s to pool %s\"",
"%",
"(",
"self",
".",
"_wrapped_connection",
",",
"self",
".",
"_pool",
... | Override to return the connection to the pool rather than closing it. | [
"Override",
"to",
"return",
"the",
"connection",
"to",
"the",
"pool",
"rather",
"than",
"closing",
"it",
"."
] | d4e0aa6a150fd7bd2024e079cd3b7147ea341e63 | https://github.com/gmcguire/django-db-pool/blob/d4e0aa6a150fd7bd2024e079cd3b7147ea341e63/dbpool/db/backends/postgresql_psycopg2/base.py#L56-L63 |
44,077 | oskyk/cashaddress | cashaddress/base58.py | b58encode_int | def b58encode_int(i, default_one=True):
'''Encode an integer using Base58'''
if not i and default_one:
return alphabet[0]
string = ""
while i:
i, idx = divmod(i, 58)
string = alphabet[idx] + string
return string | python | def b58encode_int(i, default_one=True):
'''Encode an integer using Base58'''
if not i and default_one:
return alphabet[0]
string = ""
while i:
i, idx = divmod(i, 58)
string = alphabet[idx] + string
return string | [
"def",
"b58encode_int",
"(",
"i",
",",
"default_one",
"=",
"True",
")",
":",
"if",
"not",
"i",
"and",
"default_one",
":",
"return",
"alphabet",
"[",
"0",
"]",
"string",
"=",
"\"\"",
"while",
"i",
":",
"i",
",",
"idx",
"=",
"divmod",
"(",
"i",
",",
... | Encode an integer using Base58 | [
"Encode",
"an",
"integer",
"using",
"Base58"
] | d65615368c6ca35190ff160140e721e6156ce0be | https://github.com/oskyk/cashaddress/blob/d65615368c6ca35190ff160140e721e6156ce0be/cashaddress/base58.py#L54-L62 |
44,078 | prymitive/bootstrap-breadcrumbs | django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py | breadcrumb_safe | def breadcrumb_safe(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not escaped.
"""
append_breadcrumb(context, _(label), viewname, args, kwargs)
return '' | python | def breadcrumb_safe(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not escaped.
"""
append_breadcrumb(context, _(label), viewname, args, kwargs)
return '' | [
"def",
"breadcrumb_safe",
"(",
"context",
",",
"label",
",",
"viewname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"append_breadcrumb",
"(",
"context",
",",
"_",
"(",
"label",
")",
",",
"viewname",
",",
"args",
",",
"kwargs",
")",
"return",
... | Same as breadcrumb but label is not escaped. | [
"Same",
"as",
"breadcrumb",
"but",
"label",
"is",
"not",
"escaped",
"."
] | 14e7b911c70c96a5ce18512615cdb896efefa7e2 | https://github.com/prymitive/bootstrap-breadcrumbs/blob/14e7b911c70c96a5ce18512615cdb896efefa7e2/django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py#L86-L91 |
44,079 | prymitive/bootstrap-breadcrumbs | django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py | breadcrumb_raw | def breadcrumb_raw(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not translated.
"""
append_breadcrumb(context, escape(label), viewname, args, kwargs)
return '' | python | def breadcrumb_raw(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not translated.
"""
append_breadcrumb(context, escape(label), viewname, args, kwargs)
return '' | [
"def",
"breadcrumb_raw",
"(",
"context",
",",
"label",
",",
"viewname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"append_breadcrumb",
"(",
"context",
",",
"escape",
"(",
"label",
")",
",",
"viewname",
",",
"args",
",",
"kwargs",
")",
"retur... | Same as breadcrumb but label is not translated. | [
"Same",
"as",
"breadcrumb",
"but",
"label",
"is",
"not",
"translated",
"."
] | 14e7b911c70c96a5ce18512615cdb896efefa7e2 | https://github.com/prymitive/bootstrap-breadcrumbs/blob/14e7b911c70c96a5ce18512615cdb896efefa7e2/django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py#L95-L100 |
44,080 | prymitive/bootstrap-breadcrumbs | django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py | breadcrumb_raw_safe | def breadcrumb_raw_safe(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not escaped and translated.
"""
append_breadcrumb(context, label, viewname, args, kwargs)
return '' | python | def breadcrumb_raw_safe(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not escaped and translated.
"""
append_breadcrumb(context, label, viewname, args, kwargs)
return '' | [
"def",
"breadcrumb_raw_safe",
"(",
"context",
",",
"label",
",",
"viewname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"append_breadcrumb",
"(",
"context",
",",
"label",
",",
"viewname",
",",
"args",
",",
"kwargs",
")",
"return",
"''"
] | Same as breadcrumb but label is not escaped and translated. | [
"Same",
"as",
"breadcrumb",
"but",
"label",
"is",
"not",
"escaped",
"and",
"translated",
"."
] | 14e7b911c70c96a5ce18512615cdb896efefa7e2 | https://github.com/prymitive/bootstrap-breadcrumbs/blob/14e7b911c70c96a5ce18512615cdb896efefa7e2/django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py#L104-L109 |
44,081 | prymitive/bootstrap-breadcrumbs | django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py | render_breadcrumbs | def render_breadcrumbs(context, *args):
"""
Render breadcrumbs html using bootstrap css classes.
"""
try:
template_path = args[0]
except IndexError:
template_path = getattr(settings, 'BREADCRUMBS_TEMPLATE',
'django_bootstrap_breadcrumbs/bootstrap2.htm... | python | def render_breadcrumbs(context, *args):
"""
Render breadcrumbs html using bootstrap css classes.
"""
try:
template_path = args[0]
except IndexError:
template_path = getattr(settings, 'BREADCRUMBS_TEMPLATE',
'django_bootstrap_breadcrumbs/bootstrap2.htm... | [
"def",
"render_breadcrumbs",
"(",
"context",
",",
"*",
"args",
")",
":",
"try",
":",
"template_path",
"=",
"args",
"[",
"0",
"]",
"except",
"IndexError",
":",
"template_path",
"=",
"getattr",
"(",
"settings",
",",
"'BREADCRUMBS_TEMPLATE'",
",",
"'django_bootst... | Render breadcrumbs html using bootstrap css classes. | [
"Render",
"breadcrumbs",
"html",
"using",
"bootstrap",
"css",
"classes",
"."
] | 14e7b911c70c96a5ce18512615cdb896efefa7e2 | https://github.com/prymitive/bootstrap-breadcrumbs/blob/14e7b911c70c96a5ce18512615cdb896efefa7e2/django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py#L114-L160 |
44,082 | danijar/layered | layered/problem.py | Problem._find_symbol | def _find_symbol(self, module, name, fallback=None):
"""
Find the symbol of the specified name inside the module or raise an
exception.
"""
if not hasattr(module, name) and fallback:
return self._find_symbol(module, fallback, None)
return getattr(module, name) | python | def _find_symbol(self, module, name, fallback=None):
"""
Find the symbol of the specified name inside the module or raise an
exception.
"""
if not hasattr(module, name) and fallback:
return self._find_symbol(module, fallback, None)
return getattr(module, name) | [
"def",
"_find_symbol",
"(",
"self",
",",
"module",
",",
"name",
",",
"fallback",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"module",
",",
"name",
")",
"and",
"fallback",
":",
"return",
"self",
".",
"_find_symbol",
"(",
"module",
",",
"fallbac... | Find the symbol of the specified name inside the module or raise an
exception. | [
"Find",
"the",
"symbol",
"of",
"the",
"specified",
"name",
"inside",
"the",
"module",
"or",
"raise",
"an",
"exception",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/problem.py#L72-L79 |
44,083 | danijar/layered | layered/network.py | Layer.apply | def apply(self, incoming):
"""
Store the incoming activation, apply the activation function and store
the result as outgoing activation.
"""
assert len(incoming) == self.size
self.incoming = incoming
outgoing = self.activation(self.incoming)
assert len(out... | python | def apply(self, incoming):
"""
Store the incoming activation, apply the activation function and store
the result as outgoing activation.
"""
assert len(incoming) == self.size
self.incoming = incoming
outgoing = self.activation(self.incoming)
assert len(out... | [
"def",
"apply",
"(",
"self",
",",
"incoming",
")",
":",
"assert",
"len",
"(",
"incoming",
")",
"==",
"self",
".",
"size",
"self",
".",
"incoming",
"=",
"incoming",
"outgoing",
"=",
"self",
".",
"activation",
"(",
"self",
".",
"incoming",
")",
"assert",... | Store the incoming activation, apply the activation function and store
the result as outgoing activation. | [
"Store",
"the",
"incoming",
"activation",
"apply",
"the",
"activation",
"function",
"and",
"store",
"the",
"result",
"as",
"outgoing",
"activation",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/network.py#L27-L36 |
44,084 | danijar/layered | layered/network.py | Layer.delta | def delta(self, above):
"""
The derivative of the activation function at the current state.
"""
return self.activation.delta(self.incoming, self.outgoing, above) | python | def delta(self, above):
"""
The derivative of the activation function at the current state.
"""
return self.activation.delta(self.incoming, self.outgoing, above) | [
"def",
"delta",
"(",
"self",
",",
"above",
")",
":",
"return",
"self",
".",
"activation",
".",
"delta",
"(",
"self",
".",
"incoming",
",",
"self",
".",
"outgoing",
",",
"above",
")"
] | The derivative of the activation function at the current state. | [
"The",
"derivative",
"of",
"the",
"activation",
"function",
"at",
"the",
"current",
"state",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/network.py#L38-L42 |
44,085 | danijar/layered | layered/network.py | Network.feed | def feed(self, weights, data):
"""
Evaluate the network with alternative weights on the input data and
return the output activation.
"""
assert len(data) == self.layers[0].size
self.layers[0].apply(data)
# Propagate trough the remaining layers.
connections... | python | def feed(self, weights, data):
"""
Evaluate the network with alternative weights on the input data and
return the output activation.
"""
assert len(data) == self.layers[0].size
self.layers[0].apply(data)
# Propagate trough the remaining layers.
connections... | [
"def",
"feed",
"(",
"self",
",",
"weights",
",",
"data",
")",
":",
"assert",
"len",
"(",
"data",
")",
"==",
"self",
".",
"layers",
"[",
"0",
"]",
".",
"size",
"self",
".",
"layers",
"[",
"0",
"]",
".",
"apply",
"(",
"data",
")",
"# Propagate trou... | Evaluate the network with alternative weights on the input data and
return the output activation. | [
"Evaluate",
"the",
"network",
"with",
"alternative",
"weights",
"on",
"the",
"input",
"data",
"and",
"return",
"the",
"output",
"activation",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/network.py#L154-L167 |
44,086 | danijar/layered | layered/trainer.py | Trainer._init_network | def _init_network(self):
"""Define model and initialize weights."""
self.network = Network(self.problem.layers)
self.weights = Matrices(self.network.shapes)
if self.load:
loaded = np.load(self.load)
assert loaded.shape == self.weights.shape, (
'wei... | python | def _init_network(self):
"""Define model and initialize weights."""
self.network = Network(self.problem.layers)
self.weights = Matrices(self.network.shapes)
if self.load:
loaded = np.load(self.load)
assert loaded.shape == self.weights.shape, (
'wei... | [
"def",
"_init_network",
"(",
"self",
")",
":",
"self",
".",
"network",
"=",
"Network",
"(",
"self",
".",
"problem",
".",
"layers",
")",
"self",
".",
"weights",
"=",
"Matrices",
"(",
"self",
".",
"network",
".",
"shapes",
")",
"if",
"self",
".",
"load... | Define model and initialize weights. | [
"Define",
"model",
"and",
"initialize",
"weights",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/trainer.py#L25-L37 |
44,087 | danijar/layered | layered/trainer.py | Trainer._init_training | def _init_training(self):
# pylint: disable=redefined-variable-type
"""Classes needed during training."""
if self.check:
self.backprop = CheckedBackprop(self.network, self.problem.cost)
else:
self.backprop = BatchBackprop(self.network, self.problem.cost)
s... | python | def _init_training(self):
# pylint: disable=redefined-variable-type
"""Classes needed during training."""
if self.check:
self.backprop = CheckedBackprop(self.network, self.problem.cost)
else:
self.backprop = BatchBackprop(self.network, self.problem.cost)
s... | [
"def",
"_init_training",
"(",
"self",
")",
":",
"# pylint: disable=redefined-variable-type",
"if",
"self",
".",
"check",
":",
"self",
".",
"backprop",
"=",
"CheckedBackprop",
"(",
"self",
".",
"network",
",",
"self",
".",
"problem",
".",
"cost",
")",
"else",
... | Classes needed during training. | [
"Classes",
"needed",
"during",
"training",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/trainer.py#L39-L50 |
44,088 | danijar/layered | layered/trainer.py | Trainer._every | def _every(times, step_size, index):
"""
Given a loop over batches of an iterable and an operation that should
be performed every few elements. Determine whether the operation should
be called for the current index.
"""
current = index * step_size
step = current /... | python | def _every(times, step_size, index):
"""
Given a loop over batches of an iterable and an operation that should
be performed every few elements. Determine whether the operation should
be called for the current index.
"""
current = index * step_size
step = current /... | [
"def",
"_every",
"(",
"times",
",",
"step_size",
",",
"index",
")",
":",
"current",
"=",
"index",
"*",
"step_size",
"step",
"=",
"current",
"//",
"times",
"*",
"times",
"reached",
"=",
"current",
">=",
"step",
"overshot",
"=",
"current",
">=",
"step",
... | Given a loop over batches of an iterable and an operation that should
be performed every few elements. Determine whether the operation should
be called for the current index. | [
"Given",
"a",
"loop",
"over",
"batches",
"of",
"an",
"iterable",
"and",
"an",
"operation",
"that",
"should",
"be",
"performed",
"every",
"few",
"elements",
".",
"Determine",
"whether",
"the",
"operation",
"should",
"be",
"called",
"for",
"the",
"current",
"i... | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/trainer.py#L127-L137 |
44,089 | smdabdoub/kraken-biom | kraken_biom.py | parse_tax_lvl | def parse_tax_lvl(entry, tax_lvl_depth=[]):
"""
Parse a single kraken-report entry and return a dictionary of taxa for its
named ranks.
:type entry: dict
:param entry: attributes of a single kraken-report row.
:type tax_lvl_depth: list
:param tax_lvl_depth: running record of taxon levels en... | python | def parse_tax_lvl(entry, tax_lvl_depth=[]):
"""
Parse a single kraken-report entry and return a dictionary of taxa for its
named ranks.
:type entry: dict
:param entry: attributes of a single kraken-report row.
:type tax_lvl_depth: list
:param tax_lvl_depth: running record of taxon levels en... | [
"def",
"parse_tax_lvl",
"(",
"entry",
",",
"tax_lvl_depth",
"=",
"[",
"]",
")",
":",
"# How deep in the hierarchy are we currently? Each two spaces of",
"# indentation is one level deeper. Also parse the scientific name at this",
"# level.",
"depth_and_name",
"=",
"re",
".",
"m... | Parse a single kraken-report entry and return a dictionary of taxa for its
named ranks.
:type entry: dict
:param entry: attributes of a single kraken-report row.
:type tax_lvl_depth: list
:param tax_lvl_depth: running record of taxon levels encountered in
previous calls. | [
"Parse",
"a",
"single",
"kraken",
"-",
"report",
"entry",
"and",
"return",
"a",
"dictionary",
"of",
"taxa",
"for",
"its",
"named",
"ranks",
"."
] | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L85-L109 |
44,090 | smdabdoub/kraken-biom | kraken_biom.py | parse_kraken_report | def parse_kraken_report(kdata, max_rank, min_rank):
"""
Parse a single output file from the kraken-report tool. Return a list
of counts at each of the acceptable taxonomic levels, and a list of
NCBI IDs and a formatted string representing their taxonomic hierarchies.
:type kdata: str
:param kd... | python | def parse_kraken_report(kdata, max_rank, min_rank):
"""
Parse a single output file from the kraken-report tool. Return a list
of counts at each of the acceptable taxonomic levels, and a list of
NCBI IDs and a formatted string representing their taxonomic hierarchies.
:type kdata: str
:param kd... | [
"def",
"parse_kraken_report",
"(",
"kdata",
",",
"max_rank",
",",
"min_rank",
")",
":",
"# map between NCBI taxonomy IDs and the string rep. of the hierarchy",
"taxa",
"=",
"OrderedDict",
"(",
")",
"# the master collection of read counts (keyed on NCBI ID)",
"counts",
"=",
"Ord... | Parse a single output file from the kraken-report tool. Return a list
of counts at each of the acceptable taxonomic levels, and a list of
NCBI IDs and a formatted string representing their taxonomic hierarchies.
:type kdata: str
:param kdata: Contents of the kraken report file. | [
"Parse",
"a",
"single",
"output",
"file",
"from",
"the",
"kraken",
"-",
"report",
"tool",
".",
"Return",
"a",
"list",
"of",
"counts",
"at",
"each",
"of",
"the",
"acceptable",
"taxonomic",
"levels",
"and",
"a",
"list",
"of",
"NCBI",
"IDs",
"and",
"a",
"... | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L111-L155 |
44,091 | smdabdoub/kraken-biom | kraken_biom.py | process_samples | def process_samples(kraken_reports_fp, max_rank, min_rank):
"""
Parse all kraken-report data files into sample counts dict
and store global taxon id -> taxonomy data
"""
taxa = OrderedDict()
sample_counts = OrderedDict()
for krep_fp in kraken_reports_fp:
if not osp.isfile(krep_fp):
... | python | def process_samples(kraken_reports_fp, max_rank, min_rank):
"""
Parse all kraken-report data files into sample counts dict
and store global taxon id -> taxonomy data
"""
taxa = OrderedDict()
sample_counts = OrderedDict()
for krep_fp in kraken_reports_fp:
if not osp.isfile(krep_fp):
... | [
"def",
"process_samples",
"(",
"kraken_reports_fp",
",",
"max_rank",
",",
"min_rank",
")",
":",
"taxa",
"=",
"OrderedDict",
"(",
")",
"sample_counts",
"=",
"OrderedDict",
"(",
")",
"for",
"krep_fp",
"in",
"kraken_reports_fp",
":",
"if",
"not",
"osp",
".",
"i... | Parse all kraken-report data files into sample counts dict
and store global taxon id -> taxonomy data | [
"Parse",
"all",
"kraken",
"-",
"report",
"data",
"files",
"into",
"sample",
"counts",
"dict",
"and",
"store",
"global",
"taxon",
"id",
"-",
">",
"taxonomy",
"data"
] | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L158-L187 |
44,092 | smdabdoub/kraken-biom | kraken_biom.py | create_biom_table | def create_biom_table(sample_counts, taxa):
"""
Create a BIOM table from sample counts and taxonomy metadata.
:type sample_counts: dict
:param sample_counts: A dictionary of dictionaries with the first level
keyed on sample ID, and the second level keyed on
... | python | def create_biom_table(sample_counts, taxa):
"""
Create a BIOM table from sample counts and taxonomy metadata.
:type sample_counts: dict
:param sample_counts: A dictionary of dictionaries with the first level
keyed on sample ID, and the second level keyed on
... | [
"def",
"create_biom_table",
"(",
"sample_counts",
",",
"taxa",
")",
":",
"data",
"=",
"[",
"[",
"0",
"if",
"taxid",
"not",
"in",
"sample_counts",
"[",
"sid",
"]",
"else",
"sample_counts",
"[",
"sid",
"]",
"[",
"taxid",
"]",
"for",
"sid",
"in",
"sample_... | Create a BIOM table from sample counts and taxonomy metadata.
:type sample_counts: dict
:param sample_counts: A dictionary of dictionaries with the first level
keyed on sample ID, and the second level keyed on
taxon ID with counts as values.
:type taxa: d... | [
"Create",
"a",
"BIOM",
"table",
"from",
"sample",
"counts",
"and",
"taxonomy",
"metadata",
"."
] | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L190-L216 |
44,093 | smdabdoub/kraken-biom | kraken_biom.py | write_biom | def write_biom(biomT, output_fp, fmt="hdf5", gzip=False):
"""
Write the BIOM table to a file.
:type biomT: biom.table.Table
:param biomT: A BIOM table containing the per-sample OTU counts and metadata
to be written out to file.
:type output_fp str
:param output_fp: Path to the... | python | def write_biom(biomT, output_fp, fmt="hdf5", gzip=False):
"""
Write the BIOM table to a file.
:type biomT: biom.table.Table
:param biomT: A BIOM table containing the per-sample OTU counts and metadata
to be written out to file.
:type output_fp str
:param output_fp: Path to the... | [
"def",
"write_biom",
"(",
"biomT",
",",
"output_fp",
",",
"fmt",
"=",
"\"hdf5\"",
",",
"gzip",
"=",
"False",
")",
":",
"opener",
"=",
"open",
"mode",
"=",
"'w'",
"if",
"gzip",
"and",
"fmt",
"!=",
"\"hdf5\"",
":",
"if",
"not",
"output_fp",
".",
"endsw... | Write the BIOM table to a file.
:type biomT: biom.table.Table
:param biomT: A BIOM table containing the per-sample OTU counts and metadata
to be written out to file.
:type output_fp str
:param output_fp: Path to the BIOM-format file that will be written.
:type fmt: str
:param ... | [
"Write",
"the",
"BIOM",
"table",
"to",
"a",
"file",
"."
] | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L219-L252 |
44,094 | smdabdoub/kraken-biom | kraken_biom.py | write_otu_file | def write_otu_file(otu_ids, fp):
"""
Write out a file containing only the list of OTU IDs from the kraken data.
One line per ID.
:type otu_ids: list or iterable
:param otu_ids: The OTU identifiers that will be written to file.
:type fp: str
:param fp: The path to the output file.
"""
... | python | def write_otu_file(otu_ids, fp):
"""
Write out a file containing only the list of OTU IDs from the kraken data.
One line per ID.
:type otu_ids: list or iterable
:param otu_ids: The OTU identifiers that will be written to file.
:type fp: str
:param fp: The path to the output file.
"""
... | [
"def",
"write_otu_file",
"(",
"otu_ids",
",",
"fp",
")",
":",
"fpdir",
"=",
"osp",
".",
"split",
"(",
"fp",
")",
"[",
"0",
"]",
"if",
"not",
"fpdir",
"==",
"\"\"",
"and",
"not",
"osp",
".",
"isdir",
"(",
"fpdir",
")",
":",
"raise",
"RuntimeError",
... | Write out a file containing only the list of OTU IDs from the kraken data.
One line per ID.
:type otu_ids: list or iterable
:param otu_ids: The OTU identifiers that will be written to file.
:type fp: str
:param fp: The path to the output file. | [
"Write",
"out",
"a",
"file",
"containing",
"only",
"the",
"list",
"of",
"OTU",
"IDs",
"from",
"the",
"kraken",
"data",
".",
"One",
"line",
"per",
"ID",
"."
] | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L255-L271 |
44,095 | neptune-ml/steppy-toolkit | toolkit/postprocessing.py | BlendingOptimizer.transform | def transform(self, X):
"""Performs predictions blending using the trained weights.
Args:
X (array-like): Predictions of different models.
Returns: dict with blended predictions (key is 'y_pred').
"""
assert np.shape(X)[0] == len(self._weights), (
'Blendi... | python | def transform(self, X):
"""Performs predictions blending using the trained weights.
Args:
X (array-like): Predictions of different models.
Returns: dict with blended predictions (key is 'y_pred').
"""
assert np.shape(X)[0] == len(self._weights), (
'Blendi... | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"assert",
"np",
".",
"shape",
"(",
"X",
")",
"[",
"0",
"]",
"==",
"len",
"(",
"self",
".",
"_weights",
")",
",",
"(",
"'BlendingOptimizer: Number of models to blend its predictions and weights does not match: ... | Performs predictions blending using the trained weights.
Args:
X (array-like): Predictions of different models.
Returns: dict with blended predictions (key is 'y_pred'). | [
"Performs",
"predictions",
"blending",
"using",
"the",
"trained",
"weights",
"."
] | bf3f48cfcc65dffc46e65ddd5d6cfec6bb9f9132 | https://github.com/neptune-ml/steppy-toolkit/blob/bf3f48cfcc65dffc46e65ddd5d6cfec6bb9f9132/toolkit/postprocessing.py#L166-L180 |
44,096 | neptune-ml/steppy-toolkit | toolkit/postprocessing.py | BlendingOptimizer.fit_transform | def fit_transform(self, X, y, step_size=0.1, init_weights=None, warm_start=False):
"""Fit optimizer to X, then transforms X. See `fit` and `transform` for further explanation."""
self.fit(X=X, y=y, step_size=step_size, init_weights=init_weights, warm_start=warm_start)
return self.transform(X=X) | python | def fit_transform(self, X, y, step_size=0.1, init_weights=None, warm_start=False):
"""Fit optimizer to X, then transforms X. See `fit` and `transform` for further explanation."""
self.fit(X=X, y=y, step_size=step_size, init_weights=init_weights, warm_start=warm_start)
return self.transform(X=X) | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
",",
"step_size",
"=",
"0.1",
",",
"init_weights",
"=",
"None",
",",
"warm_start",
"=",
"False",
")",
":",
"self",
".",
"fit",
"(",
"X",
"=",
"X",
",",
"y",
"=",
"y",
",",
"step_size",
"=",... | Fit optimizer to X, then transforms X. See `fit` and `transform` for further explanation. | [
"Fit",
"optimizer",
"to",
"X",
"then",
"transforms",
"X",
".",
"See",
"fit",
"and",
"transform",
"for",
"further",
"explanation",
"."
] | bf3f48cfcc65dffc46e65ddd5d6cfec6bb9f9132 | https://github.com/neptune-ml/steppy-toolkit/blob/bf3f48cfcc65dffc46e65ddd5d6cfec6bb9f9132/toolkit/postprocessing.py#L182-L186 |
44,097 | romansalin/django-seo2 | djangoseo/utils.py | escape_tags | def escape_tags(value, valid_tags):
"""
Strips text from the given html string, leaving only tags.
This functionality requires BeautifulSoup, nothing will be
done otherwise.
This isn't perfect. Someone could put javascript in here:
<a onClick="alert('hi');">test</a>
So if you use v... | python | def escape_tags(value, valid_tags):
"""
Strips text from the given html string, leaving only tags.
This functionality requires BeautifulSoup, nothing will be
done otherwise.
This isn't perfect. Someone could put javascript in here:
<a onClick="alert('hi');">test</a>
So if you use v... | [
"def",
"escape_tags",
"(",
"value",
",",
"valid_tags",
")",
":",
"# 1. escape everything",
"value",
"=",
"conditional_escape",
"(",
"value",
")",
"# 2. Reenable certain tags",
"if",
"valid_tags",
":",
"# TODO: precompile somewhere once?",
"tag_re",
"=",
"re",
".",
"co... | Strips text from the given html string, leaving only tags.
This functionality requires BeautifulSoup, nothing will be
done otherwise.
This isn't perfect. Someone could put javascript in here:
<a onClick="alert('hi');">test</a>
So if you use valid_tags, you still need to trust your data ent... | [
"Strips",
"text",
"from",
"the",
"given",
"html",
"string",
"leaving",
"only",
"tags",
".",
"This",
"functionality",
"requires",
"BeautifulSoup",
"nothing",
"will",
"be",
"done",
"otherwise",
"."
] | f788699a88e286ab9a698759d9b42f57852865d8 | https://github.com/romansalin/django-seo2/blob/f788699a88e286ab9a698759d9b42f57852865d8/djangoseo/utils.py#L82-L113 |
44,098 | romansalin/django-seo2 | djangoseo/utils.py | _get_seo_content_types | def _get_seo_content_types(seo_models):
"""Returns a list of content types from the models defined in settings."""
try:
return [ContentType.objects.get_for_model(m).id for m in seo_models]
except Exception: # previously caught DatabaseError
# Return an empty list if this is called too early... | python | def _get_seo_content_types(seo_models):
"""Returns a list of content types from the models defined in settings."""
try:
return [ContentType.objects.get_for_model(m).id for m in seo_models]
except Exception: # previously caught DatabaseError
# Return an empty list if this is called too early... | [
"def",
"_get_seo_content_types",
"(",
"seo_models",
")",
":",
"try",
":",
"return",
"[",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"m",
")",
".",
"id",
"for",
"m",
"in",
"seo_models",
"]",
"except",
"Exception",
":",
"# previously caught Databa... | Returns a list of content types from the models defined in settings. | [
"Returns",
"a",
"list",
"of",
"content",
"types",
"from",
"the",
"models",
"defined",
"in",
"settings",
"."
] | f788699a88e286ab9a698759d9b42f57852865d8 | https://github.com/romansalin/django-seo2/blob/f788699a88e286ab9a698759d9b42f57852865d8/djangoseo/utils.py#L116-L122 |
44,099 | romansalin/django-seo2 | djangoseo/admin.py | register_seo_admin | def register_seo_admin(admin_site, metadata_class):
"""Register the backends specified in Meta.backends with the admin."""
if metadata_class._meta.use_sites:
path_admin = SitePathMetadataAdmin
model_instance_admin = SiteModelInstanceMetadataAdmin
model_admin = SiteModelMetadataAdmin
... | python | def register_seo_admin(admin_site, metadata_class):
"""Register the backends specified in Meta.backends with the admin."""
if metadata_class._meta.use_sites:
path_admin = SitePathMetadataAdmin
model_instance_admin = SiteModelInstanceMetadataAdmin
model_admin = SiteModelMetadataAdmin
... | [
"def",
"register_seo_admin",
"(",
"admin_site",
",",
"metadata_class",
")",
":",
"if",
"metadata_class",
".",
"_meta",
".",
"use_sites",
":",
"path_admin",
"=",
"SitePathMetadataAdmin",
"model_instance_admin",
"=",
"SiteModelInstanceMetadataAdmin",
"model_admin",
"=",
"... | Register the backends specified in Meta.backends with the admin. | [
"Register",
"the",
"backends",
"specified",
"in",
"Meta",
".",
"backends",
"with",
"the",
"admin",
"."
] | f788699a88e286ab9a698759d9b42f57852865d8 | https://github.com/romansalin/django-seo2/blob/f788699a88e286ab9a698759d9b42f57852865d8/djangoseo/admin.py#L67-L120 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.