repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
NearHuscarl/py-currency | currency/currency.py | convert | def convert(from_currency, to_currency, from_currency_price=1):
""" convert from from_currency to to_currency using cached info """
get_cache()
from_currency, to_currency = validate_currency(from_currency, to_currency)
update_cache(from_currency, to_currency)
return ccache[from_currency][to_currency]['value'] * fr... | python | def convert(from_currency, to_currency, from_currency_price=1):
""" convert from from_currency to to_currency using cached info """
get_cache()
from_currency, to_currency = validate_currency(from_currency, to_currency)
update_cache(from_currency, to_currency)
return ccache[from_currency][to_currency]['value'] * fr... | [
"def",
"convert",
"(",
"from_currency",
",",
"to_currency",
",",
"from_currency_price",
"=",
"1",
")",
":",
"get_cache",
"(",
")",
"from_currency",
",",
"to_currency",
"=",
"validate_currency",
"(",
"from_currency",
",",
"to_currency",
")",
"update_cache",
"(",
... | convert from from_currency to to_currency using cached info | [
"convert",
"from",
"from_currency",
"to",
"to_currency",
"using",
"cached",
"info"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L160-L165 | train | convert from from_currency to to_currency using cached info |
jaraco/jaraco.windows | jaraco/windows/timers.py | WaitableTimer.wait_for_signal | def wait_for_signal(self, timeout=None):
"""
wait for the signal; return after the signal has occurred or the
timeout in seconds elapses.
"""
timeout_ms = int(timeout * 1000) if timeout else win32event.INFINITE
win32event.WaitForSingleObject(self.signal_event, timeout_ms) | python | def wait_for_signal(self, timeout=None):
"""
wait for the signal; return after the signal has occurred or the
timeout in seconds elapses.
"""
timeout_ms = int(timeout * 1000) if timeout else win32event.INFINITE
win32event.WaitForSingleObject(self.signal_event, timeout_ms) | [
"def",
"wait_for_signal",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"timeout_ms",
"=",
"int",
"(",
"timeout",
"*",
"1000",
")",
"if",
"timeout",
"else",
"win32event",
".",
"INFINITE",
"win32event",
".",
"WaitForSingleObject",
"(",
"self",
".",
"s... | wait for the signal; return after the signal has occurred or the
timeout in seconds elapses. | [
"wait",
"for",
"the",
"signal",
";",
"return",
"after",
"the",
"signal",
"has",
"occurred",
"or",
"the",
"timeout",
"in",
"seconds",
"elapses",
"."
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/timers.py#L36-L42 | train | Wait for the signal to arrive. |
mozillazg/python-shanbay | shanbay/message.py | Message.send_message | def send_message(self, recipient_list, subject, body):
"""发送站内消息
:param recipient_list: 收件人列表
:param subject: 标题
:param body: 内容(不能超过 1024 个字符)
"""
url = 'http://www.shanbay.com/api/v1/message/'
recipient = ','.join(recipient_list)
data = {
'r... | python | def send_message(self, recipient_list, subject, body):
"""发送站内消息
:param recipient_list: 收件人列表
:param subject: 标题
:param body: 内容(不能超过 1024 个字符)
"""
url = 'http://www.shanbay.com/api/v1/message/'
recipient = ','.join(recipient_list)
data = {
'r... | [
"def",
"send_message",
"(",
"self",
",",
"recipient_list",
",",
"subject",
",",
"body",
")",
":",
"url",
"=",
"'http://www.shanbay.com/api/v1/message/'",
"recipient",
"=",
"','",
".",
"join",
"(",
"recipient_list",
")",
"data",
"=",
"{",
"'recipient'",
":",
"r... | 发送站内消息
:param recipient_list: 收件人列表
:param subject: 标题
:param body: 内容(不能超过 1024 个字符) | [
"发送站内消息"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/message.py#L33-L49 | train | Send a message to a list of recipients. |
mozillazg/python-shanbay | shanbay/message.py | Message.reply_message | def reply_message(self, message_url, body):
"""回复某条站内消息
:param message_url: 该条消息的页面 URL
:param body: 内容(不能超过 1024 个字符)
"""
id = re.findall(r'(\d+)/?$', message_url)[0]
api = 'http://www.shanbay.com/api/v1/message/%s/reply/'
url = api % id
data = {
... | python | def reply_message(self, message_url, body):
"""回复某条站内消息
:param message_url: 该条消息的页面 URL
:param body: 内容(不能超过 1024 个字符)
"""
id = re.findall(r'(\d+)/?$', message_url)[0]
api = 'http://www.shanbay.com/api/v1/message/%s/reply/'
url = api % id
data = {
... | [
"def",
"reply_message",
"(",
"self",
",",
"message_url",
",",
"body",
")",
":",
"id",
"=",
"re",
".",
"findall",
"(",
"r'(\\d+)/?$'",
",",
"message_url",
")",
"[",
"0",
"]",
"api",
"=",
"'http://www.shanbay.com/api/v1/message/%s/reply/'",
"url",
"=",
"api",
... | 回复某条站内消息
:param message_url: 该条消息的页面 URL
:param body: 内容(不能超过 1024 个字符) | [
"回复某条站内消息"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/message.py#L51-L64 | train | reply message to a specific user |
Genida/django-meerkat | src/meerkat/utils/geolocation.py | ip_geoloc | def ip_geoloc(ip, hit_api=True):
"""
Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated.
"""
from ..logs.models import IPInfoCheck
try... | python | def ip_geoloc(ip, hit_api=True):
"""
Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated.
"""
from ..logs.models import IPInfoCheck
try... | [
"def",
"ip_geoloc",
"(",
"ip",
",",
"hit_api",
"=",
"True",
")",
":",
"from",
".",
".",
"logs",
".",
"models",
"import",
"IPInfoCheck",
"try",
":",
"obj",
"=",
"IPInfoCheck",
".",
"objects",
".",
"get",
"(",
"ip_address",
"=",
"ip",
")",
".",
"ip_inf... | Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated. | [
"Get",
"IP",
"geolocation",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L8-L30 | train | Get IP geolocation. |
Genida/django-meerkat | src/meerkat/utils/geolocation.py | google_maps_geoloc_link | def google_maps_geoloc_link(data):
"""
Get a link to google maps pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to google maps pointing on this IP's geolocation.
"""
if isinstance(data, str):
lat_lon ... | python | def google_maps_geoloc_link(data):
"""
Get a link to google maps pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to google maps pointing on this IP's geolocation.
"""
if isinstance(data, str):
lat_lon ... | [
"def",
"google_maps_geoloc_link",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"lat_lon",
"=",
"ip_geoloc",
"(",
"data",
")",
"if",
"lat_lon",
"is",
"None",
":",
"return",
"''",
"lat",
",",
"lon",
"=",
"lat_lon",
"else"... | Get a link to google maps pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to google maps pointing on this IP's geolocation. | [
"Get",
"a",
"link",
"to",
"google",
"maps",
"pointing",
"on",
"this",
"IP",
"s",
"geolocation",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L33-L53 | train | Returns a link to google maps pointing on this IP s geolocation. |
Genida/django-meerkat | src/meerkat/utils/geolocation.py | open_street_map_geoloc_link | def open_street_map_geoloc_link(data):
"""
Get a link to open street map pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to open street map pointing on this IP's geolocation.
"""
if isinstance(data, str):
... | python | def open_street_map_geoloc_link(data):
"""
Get a link to open street map pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to open street map pointing on this IP's geolocation.
"""
if isinstance(data, str):
... | [
"def",
"open_street_map_geoloc_link",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"lat_lon",
"=",
"ip_geoloc",
"(",
"data",
")",
"if",
"lat_lon",
"is",
"None",
":",
"return",
"''",
"lat",
",",
"lon",
"=",
"lat_lon",
"e... | Get a link to open street map pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to open street map pointing on this IP's geolocation. | [
"Get",
"a",
"link",
"to",
"open",
"street",
"map",
"pointing",
"on",
"this",
"IP",
"s",
"geolocation",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L56-L74 | train | Returns a link to open street map pointing on this IP s geolocation. |
Genida/django-meerkat | src/meerkat/logs/charts.py | status_codes_chart | def status_codes_chart():
"""Chart for status codes."""
stats = status_codes_stats()
chart_options = {
'chart': {
'type': 'pie'
},
'title': {
'text': ''
},
'subtitle': {
'text': ''
},
'tooltip': {
'formatt... | python | def status_codes_chart():
"""Chart for status codes."""
stats = status_codes_stats()
chart_options = {
'chart': {
'type': 'pie'
},
'title': {
'text': ''
},
'subtitle': {
'text': ''
},
'tooltip': {
'formatt... | [
"def",
"status_codes_chart",
"(",
")",
":",
"stats",
"=",
"status_codes_stats",
"(",
")",
"chart_options",
"=",
"{",
"'chart'",
":",
"{",
"'type'",
":",
"'pie'",
"}",
",",
"'title'",
":",
"{",
"'text'",
":",
"''",
"}",
",",
"'subtitle'",
":",
"{",
"'te... | Chart for status codes. | [
"Chart",
"for",
"status",
"codes",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/charts.py#L19-L63 | train | Return a chart for status codes. |
Genida/django-meerkat | src/meerkat/logs/charts.py | most_visited_pages_legend_chart | def most_visited_pages_legend_chart():
"""Chart for most visited pages legend."""
return {
'chart': {
'type': 'bar',
'height': 200,
},
'title': {
'text': _('Legend')
},
'xAxis': {
'categories': [
_('Project U... | python | def most_visited_pages_legend_chart():
"""Chart for most visited pages legend."""
return {
'chart': {
'type': 'bar',
'height': 200,
},
'title': {
'text': _('Legend')
},
'xAxis': {
'categories': [
_('Project U... | [
"def",
"most_visited_pages_legend_chart",
"(",
")",
":",
"return",
"{",
"'chart'",
":",
"{",
"'type'",
":",
"'bar'",
",",
"'height'",
":",
"200",
",",
"}",
",",
"'title'",
":",
"{",
"'text'",
":",
"_",
"(",
"'Legend'",
")",
"}",
",",
"'xAxis'",
":",
... | Chart for most visited pages legend. | [
"Chart",
"for",
"most",
"visited",
"pages",
"legend",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/charts.py#L100-L154 | train | Chart for most visited pages legend. |
Genida/django-meerkat | src/meerkat/logs/charts.py | most_visited_pages_charts | def most_visited_pages_charts():
"""Chart for most visited pages."""
stats = most_visited_pages_stats()
charts = []
for i, stat in enumerate(stats['more_than_10']):
bound = stat['bound']
subset = stat['subset']
chart_options = {
'chart': {
'type': '... | python | def most_visited_pages_charts():
"""Chart for most visited pages."""
stats = most_visited_pages_stats()
charts = []
for i, stat in enumerate(stats['more_than_10']):
bound = stat['bound']
subset = stat['subset']
chart_options = {
'chart': {
'type': '... | [
"def",
"most_visited_pages_charts",
"(",
")",
":",
"stats",
"=",
"most_visited_pages_stats",
"(",
")",
"charts",
"=",
"[",
"]",
"for",
"i",
",",
"stat",
"in",
"enumerate",
"(",
"stats",
"[",
"'more_than_10'",
"]",
")",
":",
"bound",
"=",
"stat",
"[",
"'b... | Chart for most visited pages. | [
"Chart",
"for",
"most",
"visited",
"pages",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/charts.py#L157-L318 | train | Returns a list of dicts that can be used to display a chart for the most visited pages. |
dcramer/logan | logan/settings.py | add_settings | def add_settings(mod, allow_extras=True, settings=django_settings):
"""
Adds all settings that are part of ``mod`` to the global settings object.
Special cases ``EXTRA_APPS`` to append the specified applications to the
list of ``INSTALLED_APPS``.
"""
extras = {}
for setting in dir(mod):
... | python | def add_settings(mod, allow_extras=True, settings=django_settings):
"""
Adds all settings that are part of ``mod`` to the global settings object.
Special cases ``EXTRA_APPS`` to append the specified applications to the
list of ``INSTALLED_APPS``.
"""
extras = {}
for setting in dir(mod):
... | [
"def",
"add_settings",
"(",
"mod",
",",
"allow_extras",
"=",
"True",
",",
"settings",
"=",
"django_settings",
")",
":",
"extras",
"=",
"{",
"}",
"for",
"setting",
"in",
"dir",
"(",
"mod",
")",
":",
"if",
"setting",
"==",
"setting",
".",
"upper",
"(",
... | Adds all settings that are part of ``mod`` to the global settings object.
Special cases ``EXTRA_APPS`` to append the specified applications to the
list of ``INSTALLED_APPS``. | [
"Adds",
"all",
"settings",
"that",
"are",
"part",
"of",
"mod",
"to",
"the",
"global",
"settings",
"object",
"."
] | 8b18456802d631a822e2823bf9a4e9810a15a20e | https://github.com/dcramer/logan/blob/8b18456802d631a822e2823bf9a4e9810a15a20e/logan/settings.py#L73-L101 | train | Adds all settings that are part of mod to the global settings object. |
Genida/django-meerkat | src/meerkat/sites.py | DashboardSite.get_urls | def get_urls(self):
"""
Get urls method.
Returns:
list: the list of url objects.
"""
urls = super(DashboardSite, self).get_urls()
custom_urls = [
url(r'^$',
self.admin_view(HomeView.as_view()),
name='index'),
... | python | def get_urls(self):
"""
Get urls method.
Returns:
list: the list of url objects.
"""
urls = super(DashboardSite, self).get_urls()
custom_urls = [
url(r'^$',
self.admin_view(HomeView.as_view()),
name='index'),
... | [
"def",
"get_urls",
"(",
"self",
")",
":",
"urls",
"=",
"super",
"(",
"DashboardSite",
",",
"self",
")",
".",
"get_urls",
"(",
")",
"custom_urls",
"=",
"[",
"url",
"(",
"r'^$'",
",",
"self",
".",
"admin_view",
"(",
"HomeView",
".",
"as_view",
"(",
")"... | Get urls method.
Returns:
list: the list of url objects. | [
"Get",
"urls",
"method",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/sites.py#L23-L41 | train | Get urls method. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | add_form_widget_attr | def add_form_widget_attr(field, attr_name, attr_value, replace=0):
"""
Adds widget attributes to a bound form field.
This is helpful if you would like to add a certain class to all your forms
(i.e. `form-control` to all form fields when you are using Bootstrap)::
{% load libs_tags %}
{... | python | def add_form_widget_attr(field, attr_name, attr_value, replace=0):
"""
Adds widget attributes to a bound form field.
This is helpful if you would like to add a certain class to all your forms
(i.e. `form-control` to all form fields when you are using Bootstrap)::
{% load libs_tags %}
{... | [
"def",
"add_form_widget_attr",
"(",
"field",
",",
"attr_name",
",",
"attr_value",
",",
"replace",
"=",
"0",
")",
":",
"if",
"not",
"replace",
":",
"attr",
"=",
"field",
".",
"field",
".",
"widget",
".",
"attrs",
".",
"get",
"(",
"attr_name",
",",
"''",... | Adds widget attributes to a bound form field.
This is helpful if you would like to add a certain class to all your forms
(i.e. `form-control` to all form fields when you are using Bootstrap)::
{% load libs_tags %}
{% for field in form.fields %}
{% add_form_widget_attr field 'class'... | [
"Adds",
"widget",
"attributes",
"to",
"a",
"bound",
"form",
"field",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L32-L60 | train | Adds widget attributes to a bound form field. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | block_anyfilter | def block_anyfilter(parser, token):
"""
Turn any template filter into a blocktag.
Usage::
{% load libs_tags %}
{% block_anyfilter django.template.defaultfilters.truncatewords_html 15 %}
// Something complex that generates html output
{% endblockanyfilter %}
"""
bits = token.co... | python | def block_anyfilter(parser, token):
"""
Turn any template filter into a blocktag.
Usage::
{% load libs_tags %}
{% block_anyfilter django.template.defaultfilters.truncatewords_html 15 %}
// Something complex that generates html output
{% endblockanyfilter %}
"""
bits = token.co... | [
"def",
"block_anyfilter",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endblockanyfilter'",
",",
")",
")",
"parser",
".",
"delete_first_token",
... | Turn any template filter into a blocktag.
Usage::
{% load libs_tags %}
{% block_anyfilter django.template.defaultfilters.truncatewords_html 15 %}
// Something complex that generates html output
{% endblockanyfilter %} | [
"Turn",
"any",
"template",
"filter",
"into",
"a",
"blocktag",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L64-L79 | train | Turn any template filter into a blocktag. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | calculate_dimensions | def calculate_dimensions(image, long_side, short_side):
"""Returns the thumbnail dimensions depending on the images format."""
if image.width >= image.height:
return '{0}x{1}'.format(long_side, short_side)
return '{0}x{1}'.format(short_side, long_side) | python | def calculate_dimensions(image, long_side, short_side):
"""Returns the thumbnail dimensions depending on the images format."""
if image.width >= image.height:
return '{0}x{1}'.format(long_side, short_side)
return '{0}x{1}'.format(short_side, long_side) | [
"def",
"calculate_dimensions",
"(",
"image",
",",
"long_side",
",",
"short_side",
")",
":",
"if",
"image",
".",
"width",
">=",
"image",
".",
"height",
":",
"return",
"'{0}x{1}'",
".",
"format",
"(",
"long_side",
",",
"short_side",
")",
"return",
"'{0}x{1}'",... | Returns the thumbnail dimensions depending on the images format. | [
"Returns",
"the",
"thumbnail",
"dimensions",
"depending",
"on",
"the",
"images",
"format",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L95-L99 | train | Returns the thumbnail dimensions depending on the images format. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | call | def call(obj, method, *args, **kwargs):
"""
Allows to call any method of any object with parameters.
Because come on! It's bloody stupid that Django's templating engine doesn't
allow that.
Usage::
{% call myobj 'mymethod' myvar foobar=myvar2 as result %}
{% call myobj 'mydict' 'my... | python | def call(obj, method, *args, **kwargs):
"""
Allows to call any method of any object with parameters.
Because come on! It's bloody stupid that Django's templating engine doesn't
allow that.
Usage::
{% call myobj 'mymethod' myvar foobar=myvar2 as result %}
{% call myobj 'mydict' 'my... | [
"def",
"call",
"(",
"obj",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"function_or_dict_or_member",
"=",
"getattr",
"(",
"obj",
",",
"method",
")",
"if",
"callable",
"(",
"function_or_dict_or_member",
")",
":",
"# If it is a function... | Allows to call any method of any object with parameters.
Because come on! It's bloody stupid that Django's templating engine doesn't
allow that.
Usage::
{% call myobj 'mymethod' myvar foobar=myvar2 as result %}
{% call myobj 'mydict' 'mykey' as result %}
{% call myobj 'myattribute... | [
"Allows",
"to",
"call",
"any",
"method",
"of",
"any",
"object",
"with",
"parameters",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L103-L129 | train | A function that can be called on the object that has the specified method. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | concatenate | def concatenate(*args, **kwargs):
"""
Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar".
"""
... | python | def concatenate(*args, **kwargs):
"""
Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar".
"""
... | [
"def",
"concatenate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"divider",
"=",
"kwargs",
".",
"get",
"(",
"'divider'",
",",
"''",
")",
"result",
"=",
"''",
"for",
"arg",
"in",
"args",
":",
"if",
"result",
"==",
"''",
":",
"result",
"+... | Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar". | [
"Concatenates",
"the",
"given",
"strings",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L133-L153 | train | Concatenates the given strings. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | get_content_type | def get_content_type(obj, field_name=False):
"""
Returns the content type of an object.
:param obj: A model instance.
:param field_name: Field of the object to return.
"""
content_type = ContentType.objects.get_for_model(obj)
if field_name:
return getattr(content_type, field_name, ... | python | def get_content_type(obj, field_name=False):
"""
Returns the content type of an object.
:param obj: A model instance.
:param field_name: Field of the object to return.
"""
content_type = ContentType.objects.get_for_model(obj)
if field_name:
return getattr(content_type, field_name, ... | [
"def",
"get_content_type",
"(",
"obj",
",",
"field_name",
"=",
"False",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
"if",
"field_name",
":",
"return",
"getattr",
"(",
"content_type",
",",
"field_name",
... | Returns the content type of an object.
:param obj: A model instance.
:param field_name: Field of the object to return. | [
"Returns",
"the",
"content",
"type",
"of",
"an",
"object",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L157-L168 | train | Returns the content type of an object. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | get_verbose | def get_verbose(obj, field_name=""):
"""
Returns the verbose name of an object's field.
:param obj: A model instance.
:param field_name: The requested field value in string format.
"""
if hasattr(obj, "_meta") and hasattr(obj._meta, "get_field_by_name"):
try:
return obj._me... | python | def get_verbose(obj, field_name=""):
"""
Returns the verbose name of an object's field.
:param obj: A model instance.
:param field_name: The requested field value in string format.
"""
if hasattr(obj, "_meta") and hasattr(obj._meta, "get_field_by_name"):
try:
return obj._me... | [
"def",
"get_verbose",
"(",
"obj",
",",
"field_name",
"=",
"\"\"",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"_meta\"",
")",
"and",
"hasattr",
"(",
"obj",
".",
"_meta",
",",
"\"get_field_by_name\"",
")",
":",
"try",
":",
"return",
"obj",
".",
"_meta... | Returns the verbose name of an object's field.
:param obj: A model instance.
:param field_name: The requested field value in string format. | [
"Returns",
"the",
"verbose",
"name",
"of",
"an",
"object",
"s",
"field",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L200-L213 | train | Returns the verbose name of an object s field. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | get_query_params | def get_query_params(request, *args):
"""
Allows to change one of the URL get parameter while keeping all the others.
Usage::
{% load libs_tags %}
{% get_query_params request "page" page_obj.next_page_number as query %}
<a href="?{{ query }}">Next</a>
You can also pass in several pa... | python | def get_query_params(request, *args):
"""
Allows to change one of the URL get parameter while keeping all the others.
Usage::
{% load libs_tags %}
{% get_query_params request "page" page_obj.next_page_number as query %}
<a href="?{{ query }}">Next</a>
You can also pass in several pa... | [
"def",
"get_query_params",
"(",
"request",
",",
"*",
"args",
")",
":",
"query",
"=",
"request",
".",
"GET",
".",
"copy",
"(",
")",
"index",
"=",
"1",
"key",
"=",
"''",
"for",
"arg",
"in",
"args",
":",
"if",
"index",
"%",
"2",
"!=",
"0",
":",
"k... | Allows to change one of the URL get parameter while keeping all the others.
Usage::
{% load libs_tags %}
{% get_query_params request "page" page_obj.next_page_number as query %}
<a href="?{{ query }}">Next</a>
You can also pass in several pairs of keys and values::
{% get_query_param... | [
"Allows",
"to",
"change",
"one",
"of",
"the",
"URL",
"get",
"parameter",
"while",
"keeping",
"all",
"the",
"others",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L217-L258 | train | This function returns a URL query string that can be used to get the values of the object. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | navactive | def navactive(request, url, exact=0, use_resolver=1):
"""
Returns ``active`` if the given URL is in the url path, otherwise ''.
Usage::
{% load libs_tags %}
...
<li class="{% navactive request "/news/" exact=1 %}">
:param request: A request instance.
:param url: A string r... | python | def navactive(request, url, exact=0, use_resolver=1):
"""
Returns ``active`` if the given URL is in the url path, otherwise ''.
Usage::
{% load libs_tags %}
...
<li class="{% navactive request "/news/" exact=1 %}">
:param request: A request instance.
:param url: A string r... | [
"def",
"navactive",
"(",
"request",
",",
"url",
",",
"exact",
"=",
"0",
",",
"use_resolver",
"=",
"1",
")",
":",
"if",
"use_resolver",
":",
"try",
":",
"if",
"url",
"==",
"resolve",
"(",
"request",
".",
"path",
")",
".",
"url_name",
":",
"# Checks th... | Returns ``active`` if the given URL is in the url path, otherwise ''.
Usage::
{% load libs_tags %}
...
<li class="{% navactive request "/news/" exact=1 %}">
:param request: A request instance.
:param url: A string representing a part of the URL that needs to exist
in order f... | [
"Returns",
"active",
"if",
"the",
"given",
"URL",
"is",
"in",
"the",
"url",
"path",
"otherwise",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L290-L331 | train | Returns the active name of the given URL. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | get_range_around | def get_range_around(range_value, current_item, padding):
"""
Returns a range of numbers around the given number.
This is useful for pagination, where you might want to show something
like this::
<< < ... 4 5 (6) 7 8 .. > >>
In this example `6` would be the current page and we show 2 item... | python | def get_range_around(range_value, current_item, padding):
"""
Returns a range of numbers around the given number.
This is useful for pagination, where you might want to show something
like this::
<< < ... 4 5 (6) 7 8 .. > >>
In this example `6` would be the current page and we show 2 item... | [
"def",
"get_range_around",
"(",
"range_value",
",",
"current_item",
",",
"padding",
")",
":",
"total_items",
"=",
"1",
"+",
"padding",
"*",
"2",
"left_bound",
"=",
"padding",
"right_bound",
"=",
"range_value",
"-",
"padding",
"if",
"range_value",
"<=",
"total_... | Returns a range of numbers around the given number.
This is useful for pagination, where you might want to show something
like this::
<< < ... 4 5 (6) 7 8 .. > >>
In this example `6` would be the current page and we show 2 items around
that page (including the page itself).
Usage::
... | [
"Returns",
"a",
"range",
"of",
"numbers",
"around",
"the",
"given",
"number",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L364-L420 | train | Returns a range of numbers around the given number. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | sum | def sum(context, key, value, multiplier=1):
"""
Adds the given value to the total value currently held in ``key``.
Use the multiplier if you want to turn a positive value into a negative
and actually substract from the current total sum.
Usage::
{% sum "MY_TOTAL" 42 -1 %}
{{ MY_TO... | python | def sum(context, key, value, multiplier=1):
"""
Adds the given value to the total value currently held in ``key``.
Use the multiplier if you want to turn a positive value into a negative
and actually substract from the current total sum.
Usage::
{% sum "MY_TOTAL" 42 -1 %}
{{ MY_TO... | [
"def",
"sum",
"(",
"context",
",",
"key",
",",
"value",
",",
"multiplier",
"=",
"1",
")",
":",
"if",
"key",
"not",
"in",
"context",
".",
"dicts",
"[",
"0",
"]",
":",
"context",
".",
"dicts",
"[",
"0",
"]",
"[",
"key",
"]",
"=",
"0",
"context",
... | Adds the given value to the total value currently held in ``key``.
Use the multiplier if you want to turn a positive value into a negative
and actually substract from the current total sum.
Usage::
{% sum "MY_TOTAL" 42 -1 %}
{{ MY_TOTAL }} | [
"Adds",
"the",
"given",
"value",
"to",
"the",
"total",
"value",
"currently",
"held",
"in",
"key",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L468-L484 | train | Adds the given value to the total value currently held in key. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | verbatim | def verbatim(parser, token):
"""Tag to render x-tmpl templates with Django template code."""
text = []
while 1:
token = parser.tokens.pop(0)
if token.contents == 'endverbatim':
break
if token.token_type == TOKEN_VAR:
text.append('{{ ')
elif token.token... | python | def verbatim(parser, token):
"""Tag to render x-tmpl templates with Django template code."""
text = []
while 1:
token = parser.tokens.pop(0)
if token.contents == 'endverbatim':
break
if token.token_type == TOKEN_VAR:
text.append('{{ ')
elif token.token... | [
"def",
"verbatim",
"(",
"parser",
",",
"token",
")",
":",
"text",
"=",
"[",
"]",
"while",
"1",
":",
"token",
"=",
"parser",
".",
"tokens",
".",
"pop",
"(",
"0",
")",
"if",
"token",
".",
"contents",
"==",
"'endverbatim'",
":",
"break",
"if",
"token"... | Tag to render x-tmpl templates with Django template code. | [
"Tag",
"to",
"render",
"x",
"-",
"tmpl",
"templates",
"with",
"Django",
"template",
"code",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L502-L520 | train | Tag to render x - tmpl templates with Django template code. |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | append_s | def append_s(value):
"""
Adds the possessive s after a string.
value = 'Hans' becomes Hans'
and value = 'Susi' becomes Susi's
"""
if value.endswith('s'):
return u"{0}'".format(value)
else:
return u"{0}'s".format(value) | python | def append_s(value):
"""
Adds the possessive s after a string.
value = 'Hans' becomes Hans'
and value = 'Susi' becomes Susi's
"""
if value.endswith('s'):
return u"{0}'".format(value)
else:
return u"{0}'s".format(value) | [
"def",
"append_s",
"(",
"value",
")",
":",
"if",
"value",
".",
"endswith",
"(",
"'s'",
")",
":",
"return",
"u\"{0}'\"",
".",
"format",
"(",
"value",
")",
"else",
":",
"return",
"u\"{0}'s\"",
".",
"format",
"(",
"value",
")"
] | Adds the possessive s after a string.
value = 'Hans' becomes Hans'
and value = 'Susi' becomes Susi's | [
"Adds",
"the",
"possessive",
"s",
"after",
"a",
"string",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L566-L577 | train | Adds the possessive s after a string. |
dcramer/logan | logan/runner.py | parse_args | def parse_args(args):
"""
This parses the arguments and returns a tuple containing:
(args, command, command_args)
For example, "--config=bar start --with=baz" would return:
(['--config=bar'], 'start', ['--with=baz'])
"""
index = None
for arg_i, arg in enumerate(args):
if not a... | python | def parse_args(args):
"""
This parses the arguments and returns a tuple containing:
(args, command, command_args)
For example, "--config=bar start --with=baz" would return:
(['--config=bar'], 'start', ['--with=baz'])
"""
index = None
for arg_i, arg in enumerate(args):
if not a... | [
"def",
"parse_args",
"(",
"args",
")",
":",
"index",
"=",
"None",
"for",
"arg_i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"not",
"arg",
".",
"startswith",
"(",
"'-'",
")",
":",
"index",
"=",
"arg_i",
"break",
"# Unable to parse any ... | This parses the arguments and returns a tuple containing:
(args, command, command_args)
For example, "--config=bar start --with=baz" would return:
(['--config=bar'], 'start', ['--with=baz']) | [
"This",
"parses",
"the",
"arguments",
"and",
"returns",
"a",
"tuple",
"containing",
":"
] | 8b18456802d631a822e2823bf9a4e9810a15a20e | https://github.com/dcramer/logan/blob/8b18456802d631a822e2823bf9a4e9810a15a20e/logan/runner.py#L35-L55 | train | Parses the arguments and returns a tuple containing the command and command_args. |
dcramer/logan | logan/runner.py | configure_app | def configure_app(config_path=None, project=None, default_config_path=None,
default_settings=None, settings_initializer=None,
settings_envvar=None, initializer=None, allow_extras=True,
config_module_name=None, runner_name=None, on_configure=None):
"""
:param... | python | def configure_app(config_path=None, project=None, default_config_path=None,
default_settings=None, settings_initializer=None,
settings_envvar=None, initializer=None, allow_extras=True,
config_module_name=None, runner_name=None, on_configure=None):
"""
:param... | [
"def",
"configure_app",
"(",
"config_path",
"=",
"None",
",",
"project",
"=",
"None",
",",
"default_config_path",
"=",
"None",
",",
"default_settings",
"=",
"None",
",",
"settings_initializer",
"=",
"None",
",",
"settings_envvar",
"=",
"None",
",",
"initializer"... | :param project: should represent the canonical name for the project, generally
the same name it assigned in distutils.
:param default_config_path: the default location for the configuration file.
:param default_settings: default settings to load (think inheritence).
:param settings_initializer: a ca... | [
":",
"param",
"project",
":",
"should",
"represent",
"the",
"canonical",
"name",
"for",
"the",
"project",
"generally",
"the",
"same",
"name",
"it",
"assigned",
"in",
"distutils",
".",
":",
"param",
"default_config_path",
":",
"the",
"default",
"location",
"for... | 8b18456802d631a822e2823bf9a4e9810a15a20e | https://github.com/dcramer/logan/blob/8b18456802d631a822e2823bf9a4e9810a15a20e/logan/runner.py#L63-L141 | train | Configure a new app. |
Genida/django-meerkat | src/meerkat/logs/urls.py | logs_urlpatterns | def logs_urlpatterns(admin_view=lambda x: x):
"""
Return the URL patterns for the logs views.
Args:
admin_view (callable): admin_view method from an AdminSite instance.
Returns:
list: the URL patterns for the logs views.
"""
return [
url(r'^$',
admin_view(Lo... | python | def logs_urlpatterns(admin_view=lambda x: x):
"""
Return the URL patterns for the logs views.
Args:
admin_view (callable): admin_view method from an AdminSite instance.
Returns:
list: the URL patterns for the logs views.
"""
return [
url(r'^$',
admin_view(Lo... | [
"def",
"logs_urlpatterns",
"(",
"admin_view",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"return",
"[",
"url",
"(",
"r'^$'",
",",
"admin_view",
"(",
"LogsMenu",
".",
"as_view",
"(",
")",
")",
",",
"name",
"=",
"'logs'",
")",
",",
"url",
"(",
"r'^status_... | Return the URL patterns for the logs views.
Args:
admin_view (callable): admin_view method from an AdminSite instance.
Returns:
list: the URL patterns for the logs views. | [
"Return",
"the",
"URL",
"patterns",
"for",
"the",
"logs",
"views",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/urls.py#L11-L34 | train | Returns the list of URL patterns for the logs views. |
Genida/django-meerkat | src/meerkat/utils/ip_info.py | IpInfoHandler._get | def _get(self, ip):
"""
Get information about an IP.
Args:
ip (str): an IP (xxx.xxx.xxx.xxx).
Returns:
dict: see http://ipinfo.io/developers/getting-started
"""
# Geoloc updated up to once a week:
# http://ipinfo.io/developers/data#geoloc... | python | def _get(self, ip):
"""
Get information about an IP.
Args:
ip (str): an IP (xxx.xxx.xxx.xxx).
Returns:
dict: see http://ipinfo.io/developers/getting-started
"""
# Geoloc updated up to once a week:
# http://ipinfo.io/developers/data#geoloc... | [
"def",
"_get",
"(",
"self",
",",
"ip",
")",
":",
"# Geoloc updated up to once a week:",
"# http://ipinfo.io/developers/data#geolocation-data",
"retries",
"=",
"10",
"for",
"retry",
"in",
"range",
"(",
"retries",
")",
":",
"try",
":",
"response",
"=",
"requests",
"... | Get information about an IP.
Args:
ip (str): an IP (xxx.xxx.xxx.xxx).
Returns:
dict: see http://ipinfo.io/developers/getting-started | [
"Get",
"information",
"about",
"an",
"IP",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/ip_info.py#L100-L122 | train | Get information about an IP. |
flavio/scsgate | scsgate/messages.py | parse | def parse(data):
""" Parses a raw datagram and return the right type of message """
# convert to string
data = data.decode("ascii")
if len(data) == 2 and data == "A5":
return AckMessage()
# split into bytes
raw = [data[i:i+2] for i in range(len(data)) if i % 2 == 0]
if len(raw) !... | python | def parse(data):
""" Parses a raw datagram and return the right type of message """
# convert to string
data = data.decode("ascii")
if len(data) == 2 and data == "A5":
return AckMessage()
# split into bytes
raw = [data[i:i+2] for i in range(len(data)) if i % 2 == 0]
if len(raw) !... | [
"def",
"parse",
"(",
"data",
")",
":",
"# convert to string",
"data",
"=",
"data",
".",
"decode",
"(",
"\"ascii\"",
")",
"if",
"len",
"(",
"data",
")",
"==",
"2",
"and",
"data",
"==",
"\"A5\"",
":",
"return",
"AckMessage",
"(",
")",
"# split into bytes",... | Parses a raw datagram and return the right type of message | [
"Parses",
"a",
"raw",
"datagram",
"and",
"return",
"the",
"right",
"type",
"of",
"message"
] | aad1d181eef4714ab475f4ff7fcfac4a6425fbb4 | https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/messages.py#L213-L237 | train | Parses a raw datagram and returns the right type of message |
flavio/scsgate | scsgate/messages.py | checksum_bytes | def checksum_bytes(data):
""" Returns a XOR of all the bytes specified inside of the given list """
int_values = [int(x, 16) for x in data]
int_xor = reduce(lambda x, y: x ^ y, int_values)
hex_xor = "{:X}".format(int_xor)
if len(hex_xor) % 2 != 0:
hex_xor = "0" + hex_xor
return str.enc... | python | def checksum_bytes(data):
""" Returns a XOR of all the bytes specified inside of the given list """
int_values = [int(x, 16) for x in data]
int_xor = reduce(lambda x, y: x ^ y, int_values)
hex_xor = "{:X}".format(int_xor)
if len(hex_xor) % 2 != 0:
hex_xor = "0" + hex_xor
return str.enc... | [
"def",
"checksum_bytes",
"(",
"data",
")",
":",
"int_values",
"=",
"[",
"int",
"(",
"x",
",",
"16",
")",
"for",
"x",
"in",
"data",
"]",
"int_xor",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"^",
"y",
",",
"int_values",
")",
"hex_xor",... | Returns a XOR of all the bytes specified inside of the given list | [
"Returns",
"a",
"XOR",
"of",
"all",
"the",
"bytes",
"specified",
"inside",
"of",
"the",
"given",
"list"
] | aad1d181eef4714ab475f4ff7fcfac4a6425fbb4 | https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/messages.py#L240-L249 | train | Returns a XOR of all the bytes specified inside of the given list |
flavio/scsgate | scsgate/messages.py | compose_telegram | def compose_telegram(body):
""" Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance)
"""
msg = [b"A8"] + body + [checksum_bytes(body)] + [b"A3"]
return str.encode("".join([x.decode() for x in msg])) | python | def compose_telegram(body):
""" Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance)
"""
msg = [b"A8"] + body + [checksum_bytes(body)] + [b"A3"]
return str.encode("".join([x.decode() for x in msg])) | [
"def",
"compose_telegram",
"(",
"body",
")",
":",
"msg",
"=",
"[",
"b\"A8\"",
"]",
"+",
"body",
"+",
"[",
"checksum_bytes",
"(",
"body",
")",
"]",
"+",
"[",
"b\"A3\"",
"]",
"return",
"str",
".",
"encode",
"(",
"\"\"",
".",
"join",
"(",
"[",
"x",
... | Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance) | [
"Compose",
"a",
"SCS",
"message"
] | aad1d181eef4714ab475f4ff7fcfac4a6425fbb4 | https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/messages.py#L252-L260 | train | Compose a SCS message containing the body of the message. |
bitlabstudio/django-libs | django_libs/utils/email.py | send_email | def send_email(request, context, subject_template, body_template,
from_email, recipients, priority="medium", reply_to=None,
headers=None, cc=None, bcc=None):
"""
Sends an email based on templates for subject and body.
:param request: The current request instance.
:param co... | python | def send_email(request, context, subject_template, body_template,
from_email, recipients, priority="medium", reply_to=None,
headers=None, cc=None, bcc=None):
"""
Sends an email based on templates for subject and body.
:param request: The current request instance.
:param co... | [
"def",
"send_email",
"(",
"request",
",",
"context",
",",
"subject_template",
",",
"body_template",
",",
"from_email",
",",
"recipients",
",",
"priority",
"=",
"\"medium\"",
",",
"reply_to",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"cc",
"=",
"None",
... | Sends an email based on templates for subject and body.
:param request: The current request instance.
:param context: A dictionary of items that should be added to the
templates' contexts.
:param subject_template: A string representing the path to the template of
of the email's subject.
... | [
"Sends",
"an",
"email",
"based",
"on",
"templates",
"for",
"subject",
"and",
"body",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/utils/email.py#L18-L92 | train | Sends an email based on templates for subject and body. |
Genida/django-meerkat | src/meerkat/utils/url.py | url_is_project | def url_is_project(url, default='not_a_func'):
"""
Check if URL is part of the current project's URLs.
Args:
url (str): URL to check.
default (callable): used to filter out some URLs attached to function.
Returns:
"""
try:
u = resolve(url)
if u and u.func != de... | python | def url_is_project(url, default='not_a_func'):
"""
Check if URL is part of the current project's URLs.
Args:
url (str): URL to check.
default (callable): used to filter out some URLs attached to function.
Returns:
"""
try:
u = resolve(url)
if u and u.func != de... | [
"def",
"url_is_project",
"(",
"url",
",",
"default",
"=",
"'not_a_func'",
")",
":",
"try",
":",
"u",
"=",
"resolve",
"(",
"url",
")",
"if",
"u",
"and",
"u",
".",
"func",
"!=",
"default",
":",
"return",
"True",
"except",
"Resolver404",
":",
"static_url"... | Check if URL is part of the current project's URLs.
Args:
url (str): URL to check.
default (callable): used to filter out some URLs attached to function.
Returns: | [
"Check",
"if",
"URL",
"is",
"part",
"of",
"the",
"current",
"project",
"s",
"URLs",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/url.py#L14-L40 | train | Check if URL is part of the current project s URLs. |
Genida/django-meerkat | src/meerkat/utils/url.py | url_is | def url_is(white_list):
"""
Function generator.
Args:
white_list (dict): dict with PREFIXES and CONSTANTS keys (list values).
Returns:
func: a function to check if a URL is...
"""
def func(url):
prefixes = white_list.get('PREFIXES', ())
for prefix in prefixes:
... | python | def url_is(white_list):
"""
Function generator.
Args:
white_list (dict): dict with PREFIXES and CONSTANTS keys (list values).
Returns:
func: a function to check if a URL is...
"""
def func(url):
prefixes = white_list.get('PREFIXES', ())
for prefix in prefixes:
... | [
"def",
"url_is",
"(",
"white_list",
")",
":",
"def",
"func",
"(",
"url",
")",
":",
"prefixes",
"=",
"white_list",
".",
"get",
"(",
"'PREFIXES'",
",",
"(",
")",
")",
"for",
"prefix",
"in",
"prefixes",
":",
"if",
"url",
".",
"startswith",
"(",
"prefix"... | Function generator.
Args:
white_list (dict): dict with PREFIXES and CONSTANTS keys (list values).
Returns:
func: a function to check if a URL is... | [
"Function",
"generator",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/url.py#L43-L63 | train | Function generator. Returns a function to check if a URL is... |
gsi-upm/soil | soil/history.py | History.save_records | def save_records(self, records):
'''
Save a collection of records
'''
for record in records:
if not isinstance(record, Record):
record = Record(*record)
self.save_record(*record) | python | def save_records(self, records):
'''
Save a collection of records
'''
for record in records:
if not isinstance(record, Record):
record = Record(*record)
self.save_record(*record) | [
"def",
"save_records",
"(",
"self",
",",
"records",
")",
":",
"for",
"record",
"in",
"records",
":",
"if",
"not",
"isinstance",
"(",
"record",
",",
"Record",
")",
":",
"record",
"=",
"Record",
"(",
"*",
"record",
")",
"self",
".",
"save_record",
"(",
... | Save a collection of records | [
"Save",
"a",
"collection",
"of",
"records"
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L70-L77 | train | Save a collection of records. |
gsi-upm/soil | soil/history.py | History.save_record | def save_record(self, agent_id, t_step, key, value):
'''
Save a collection of records to the database.
Database writes are cached.
'''
value = self.convert(key, value)
self._tups.append(Record(agent_id=agent_id,
t_step=t_step,
... | python | def save_record(self, agent_id, t_step, key, value):
'''
Save a collection of records to the database.
Database writes are cached.
'''
value = self.convert(key, value)
self._tups.append(Record(agent_id=agent_id,
t_step=t_step,
... | [
"def",
"save_record",
"(",
"self",
",",
"agent_id",
",",
"t_step",
",",
"key",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"convert",
"(",
"key",
",",
"value",
")",
"self",
".",
"_tups",
".",
"append",
"(",
"Record",
"(",
"agent_id",
"=",
"a... | Save a collection of records to the database.
Database writes are cached. | [
"Save",
"a",
"collection",
"of",
"records",
"to",
"the",
"database",
".",
"Database",
"writes",
"are",
"cached",
"."
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L79-L90 | train | Save a record to the database. |
gsi-upm/soil | soil/history.py | History.convert | def convert(self, key, value):
"""Get the serialized value for a given key."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
name = utils.name(value)
serializer = utils.serializer(name)
deserializer = uti... | python | def convert(self, key, value):
"""Get the serialized value for a given key."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
name = utils.name(value)
serializer = utils.serializer(name)
deserializer = uti... | [
"def",
"convert",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_dtypes",
":",
"self",
".",
"read_types",
"(",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_dtypes",
":",
"name",
"=",
"utils",
".",
"name... | Get the serialized value for a given key. | [
"Get",
"the",
"serialized",
"value",
"for",
"a",
"given",
"key",
"."
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L92-L103 | train | Get the serialized value for a given key. |
gsi-upm/soil | soil/history.py | History.recover | def recover(self, key, value):
"""Get the deserialized value for a given key, and the serialized version."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
raise ValueError("Unknown datatype for {} and {}".format(key, value))
return self... | python | def recover(self, key, value):
"""Get the deserialized value for a given key, and the serialized version."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
raise ValueError("Unknown datatype for {} and {}".format(key, value))
return self... | [
"def",
"recover",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_dtypes",
":",
"self",
".",
"read_types",
"(",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_dtypes",
":",
"raise",
"ValueError",
"(",
"\"Unk... | Get the deserialized value for a given key, and the serialized version. | [
"Get",
"the",
"deserialized",
"value",
"for",
"a",
"given",
"key",
"and",
"the",
"serialized",
"version",
"."
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L105-L111 | train | Get the deserialized value for a given key and the serialized version. |
gsi-upm/soil | soil/history.py | History.flush_cache | def flush_cache(self):
'''
Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed.
'''
logger.debug('Flushing cache {}'.format(self.db_path))
with self.db:
... | python | def flush_cache(self):
'''
Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed.
'''
logger.debug('Flushing cache {}'.format(self.db_path))
with self.db:
... | [
"def",
"flush_cache",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Flushing cache {}'",
".",
"format",
"(",
"self",
".",
"db_path",
")",
")",
"with",
"self",
".",
"db",
":",
"for",
"rec",
"in",
"self",
".",
"_tups",
":",
"self",
".",
"db",
... | Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed. | [
"Use",
"a",
"cache",
"to",
"save",
"state",
"changes",
"to",
"avoid",
"opening",
"a",
"session",
"for",
"every",
"change",
".",
"The",
"cache",
"will",
"be",
"flushed",
"at",
"the",
"end",
"of",
"the",
"simulation",
"and",
"when",
"history",
"is",
"acces... | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L114-L123 | train | Flushes the cache for all the entries in the database. |
inveniosoftware/invenio-search-ui | examples/app.py | records | def records():
"""Load records."""
import pkg_resources
import uuid
from dojson.contrib.marc21 import marc21
from dojson.contrib.marc21.utils import create_record, split_blob
from invenio_pidstore import current_pidstore
from invenio_records.api import Record
# pkg resources the demodat... | python | def records():
"""Load records."""
import pkg_resources
import uuid
from dojson.contrib.marc21 import marc21
from dojson.contrib.marc21.utils import create_record, split_blob
from invenio_pidstore import current_pidstore
from invenio_records.api import Record
# pkg resources the demodat... | [
"def",
"records",
"(",
")",
":",
"import",
"pkg_resources",
"import",
"uuid",
"from",
"dojson",
".",
"contrib",
".",
"marc21",
"import",
"marc21",
"from",
"dojson",
".",
"contrib",
".",
"marc21",
".",
"utils",
"import",
"create_record",
",",
"split_blob",
"f... | Load records. | [
"Load",
"records",
"."
] | 4b61737f938cbfdc1aad6602a73f3a24d53b3312 | https://github.com/inveniosoftware/invenio-search-ui/blob/4b61737f938cbfdc1aad6602a73f3a24d53b3312/examples/app.py#L206-L233 | train | Load records from a MARC - 21 XML file. |
gsi-upm/soil | soil/simulation.py | Simulation.run_trial | def run_trial(self, trial_id = 0, until = None, return_env = True, **opts):
"""Run a single trial of the simulation
Parameters
----------
trial_id : int
"""
# Set-up trial environment and graph
until=until or self.max_time
env=self.get_env(trial_id = tria... | python | def run_trial(self, trial_id = 0, until = None, return_env = True, **opts):
"""Run a single trial of the simulation
Parameters
----------
trial_id : int
"""
# Set-up trial environment and graph
until=until or self.max_time
env=self.get_env(trial_id = tria... | [
"def",
"run_trial",
"(",
"self",
",",
"trial_id",
"=",
"0",
",",
"until",
"=",
"None",
",",
"return_env",
"=",
"True",
",",
"*",
"*",
"opts",
")",
":",
"# Set-up trial environment and graph",
"until",
"=",
"until",
"or",
"self",
".",
"max_time",
"env",
"... | Run a single trial of the simulation
Parameters
----------
trial_id : int | [
"Run",
"a",
"single",
"trial",
"of",
"the",
"simulation"
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/simulation.py#L178-L195 | train | Run a single trial of the simulation. |
gsi-upm/soil | soil/simulation.py | Simulation.run_trial_exceptions | def run_trial_exceptions(self, *args, **kwargs):
'''
A wrapper for run_trial that catches exceptions and returns them.
It is meant for async simulations
'''
try:
return self.run_trial(*args, **kwargs)
except Exception as ex:
c = ex.__cause__
... | python | def run_trial_exceptions(self, *args, **kwargs):
'''
A wrapper for run_trial that catches exceptions and returns them.
It is meant for async simulations
'''
try:
return self.run_trial(*args, **kwargs)
except Exception as ex:
c = ex.__cause__
... | [
"def",
"run_trial_exceptions",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"run_trial",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"ex",
":",
"c",
"=",
"ex",... | A wrapper for run_trial that catches exceptions and returns them.
It is meant for async simulations | [
"A",
"wrapper",
"for",
"run_trial",
"that",
"catches",
"exceptions",
"and",
"returns",
"them",
".",
"It",
"is",
"meant",
"for",
"async",
"simulations"
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/simulation.py#L196-L206 | train | A wrapper for run_trial that catches exceptions and returns them. |
pr-omethe-us/PyKED | pyked/orcid.py | search_orcid | def search_orcid(orcid):
"""
Search the ORCID public API
Specfically, return a dictionary with the personal details
(name, etc.) of the person associated with the given ORCID
Args:
orcid (`str`): The ORCID to be searched
Returns:
`dict`: Dictionary with the JSON response from ... | python | def search_orcid(orcid):
"""
Search the ORCID public API
Specfically, return a dictionary with the personal details
(name, etc.) of the person associated with the given ORCID
Args:
orcid (`str`): The ORCID to be searched
Returns:
`dict`: Dictionary with the JSON response from ... | [
"def",
"search_orcid",
"(",
"orcid",
")",
":",
"url",
"=",
"'https://pub.orcid.org/v2.1/{orcid}/person'",
".",
"format",
"(",
"orcid",
"=",
"orcid",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"if",
"r",
".",
"... | Search the ORCID public API
Specfically, return a dictionary with the personal details
(name, etc.) of the person associated with the given ORCID
Args:
orcid (`str`): The ORCID to be searched
Returns:
`dict`: Dictionary with the JSON response from the API
Raises:
`~reques... | [
"Search",
"the",
"ORCID",
"public",
"API"
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/orcid.py#L8-L29 | train | Search the ORCID public API and return a dictionary with the personal details of the person associated with the given ORCID |
Genida/django-meerkat | src/meerkat/utils/time.py | daterange | def daterange(start_date, end_date):
"""
Yield one date per day from starting date to ending date.
Args:
start_date (date): starting date.
end_date (date): ending date.
Yields:
date: a date for each day within the range.
"""
for n in range(int((end_date - start_date).da... | python | def daterange(start_date, end_date):
"""
Yield one date per day from starting date to ending date.
Args:
start_date (date): starting date.
end_date (date): ending date.
Yields:
date: a date for each day within the range.
"""
for n in range(int((end_date - start_date).da... | [
"def",
"daterange",
"(",
"start_date",
",",
"end_date",
")",
":",
"for",
"n",
"in",
"range",
"(",
"int",
"(",
"(",
"end_date",
"-",
"start_date",
")",
".",
"days",
")",
")",
":",
"yield",
"start_date",
"+",
"timedelta",
"(",
"n",
")"
] | Yield one date per day from starting date to ending date.
Args:
start_date (date): starting date.
end_date (date): ending date.
Yields:
date: a date for each day within the range. | [
"Yield",
"one",
"date",
"per",
"day",
"from",
"starting",
"date",
"to",
"ending",
"date",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/time.py#L21-L33 | train | Yields one date per day from starting date to ending date. |
Genida/django-meerkat | src/meerkat/utils/time.py | month_name_to_number | def month_name_to_number(month, to_int=False):
"""
Convert a month name (MMM) to its number (01-12).
Args:
month (str): 3-letters string describing month.
to_int (bool): cast number to int or not.
Returns:
str/int: the month's number (between 01 and 12).
"""
number = {
... | python | def month_name_to_number(month, to_int=False):
"""
Convert a month name (MMM) to its number (01-12).
Args:
month (str): 3-letters string describing month.
to_int (bool): cast number to int or not.
Returns:
str/int: the month's number (between 01 and 12).
"""
number = {
... | [
"def",
"month_name_to_number",
"(",
"month",
",",
"to_int",
"=",
"False",
")",
":",
"number",
"=",
"{",
"'Jan'",
":",
"'01'",
",",
"'Feb'",
":",
"'02'",
",",
"'Mar'",
":",
"'03'",
",",
"'Apr'",
":",
"'04'",
",",
"'May'",
":",
"'05'",
",",
"'Jun'",
... | Convert a month name (MMM) to its number (01-12).
Args:
month (str): 3-letters string describing month.
to_int (bool): cast number to int or not.
Returns:
str/int: the month's number (between 01 and 12). | [
"Convert",
"a",
"month",
"name",
"(",
"MMM",
")",
"to",
"its",
"number",
"(",
"01",
"-",
"12",
")",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/time.py#L75-L91 | train | Convert a month name to its number. |
pr-omethe-us/PyKED | pyked/converters.py | get_file_metadata | def get_file_metadata(root):
"""Read and parse ReSpecTh XML file metadata (file author, version, etc.)
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with file metadata
"""
properties = {}
file_author = getattr... | python | def get_file_metadata(root):
"""Read and parse ReSpecTh XML file metadata (file author, version, etc.)
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with file metadata
"""
properties = {}
file_author = getattr... | [
"def",
"get_file_metadata",
"(",
"root",
")",
":",
"properties",
"=",
"{",
"}",
"file_author",
"=",
"getattr",
"(",
"root",
".",
"find",
"(",
"'fileAuthor'",
")",
",",
"'text'",
",",
"False",
")",
"# Test for missing attribute or empty string in the same statement",... | Read and parse ReSpecTh XML file metadata (file author, version, etc.)
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with file metadata | [
"Read",
"and",
"parse",
"ReSpecTh",
"XML",
"file",
"metadata",
"(",
"file",
"author",
"version",
"etc",
".",
")"
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L59-L83 | train | Read and parse ReSpecTh XML file metadata. |
pr-omethe-us/PyKED | pyked/converters.py | get_reference | def get_reference(root):
"""Read reference info from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with reference information
"""
reference = {}
elem = root.find('bibliographyLink')
... | python | def get_reference(root):
"""Read reference info from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with reference information
"""
reference = {}
elem = root.find('bibliographyLink')
... | [
"def",
"get_reference",
"(",
"root",
")",
":",
"reference",
"=",
"{",
"}",
"elem",
"=",
"root",
".",
"find",
"(",
"'bibliographyLink'",
")",
"if",
"elem",
"is",
"None",
":",
"raise",
"MissingElementError",
"(",
"'bibliographyLink'",
")",
"# Try to get referenc... | Read reference info from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with reference information | [
"Read",
"reference",
"info",
"from",
"root",
"of",
"ReSpecTh",
"XML",
"file",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L86-L149 | train | Read reference information from the root of ReSpecTh XML file. |
pr-omethe-us/PyKED | pyked/converters.py | get_experiment_kind | def get_experiment_kind(root):
"""Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with experiment type and apparatus information.
"""
properties = {}
if root... | python | def get_experiment_kind(root):
"""Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with experiment type and apparatus information.
"""
properties = {}
if root... | [
"def",
"get_experiment_kind",
"(",
"root",
")",
":",
"properties",
"=",
"{",
"}",
"if",
"root",
".",
"find",
"(",
"'experimentType'",
")",
".",
"text",
"==",
"'Ignition delay measurement'",
":",
"properties",
"[",
"'experiment-type'",
"]",
"=",
"'ignition delay'... | Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with experiment type and apparatus information. | [
"Read",
"common",
"properties",
"from",
"root",
"of",
"ReSpecTh",
"XML",
"file",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L152-L177 | train | Read common properties from root of ReSpecTh XML file. |
pr-omethe-us/PyKED | pyked/converters.py | get_common_properties | def get_common_properties(root):
"""Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with common properties
"""
properties = {}
for elem in root.iterfind('co... | python | def get_common_properties(root):
"""Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with common properties
"""
properties = {}
for elem in root.iterfind('co... | [
"def",
"get_common_properties",
"(",
"root",
")",
":",
"properties",
"=",
"{",
"}",
"for",
"elem",
"in",
"root",
".",
"iterfind",
"(",
"'commonProperties/property'",
")",
":",
"name",
"=",
"elem",
".",
"attrib",
"[",
"'name'",
"]",
"if",
"name",
"==",
"'... | Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with common properties | [
"Read",
"common",
"properties",
"from",
"root",
"of",
"ReSpecTh",
"XML",
"file",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L180-L260 | train | Read common properties from the root of ReSpecTh XML file. |
pr-omethe-us/PyKED | pyked/converters.py | get_ignition_type | def get_ignition_type(root):
"""Gets ignition type and target.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with ignition type/target information
"""
properties = {}
elem = root.find('ignitionType')
if el... | python | def get_ignition_type(root):
"""Gets ignition type and target.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with ignition type/target information
"""
properties = {}
elem = root.find('ignitionType')
if el... | [
"def",
"get_ignition_type",
"(",
"root",
")",
":",
"properties",
"=",
"{",
"}",
"elem",
"=",
"root",
".",
"find",
"(",
"'ignitionType'",
")",
"if",
"elem",
"is",
"None",
":",
"raise",
"MissingElementError",
"(",
"'ignitionType'",
")",
"elem",
"=",
"elem",
... | Gets ignition type and target.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with ignition type/target information | [
"Gets",
"ignition",
"type",
"and",
"target",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L263-L315 | train | Gets ignition type and target information from a ReSpecTh XML file. |
pr-omethe-us/PyKED | pyked/converters.py | get_datapoints | def get_datapoints(root):
"""Parse datapoints with ignition delay from file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with ignition delay data
"""
# Shock tube experiment will have one data group, while RCM ma... | python | def get_datapoints(root):
"""Parse datapoints with ignition delay from file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with ignition delay data
"""
# Shock tube experiment will have one data group, while RCM ma... | [
"def",
"get_datapoints",
"(",
"root",
")",
":",
"# Shock tube experiment will have one data group, while RCM may have one",
"# or two (one for ignition delay, one for volume-history)",
"dataGroups",
"=",
"root",
".",
"findall",
"(",
"'dataGroup'",
")",
"if",
"not",
"dataGroups",
... | Parse datapoints with ignition delay from file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with ignition delay data | [
"Parse",
"datapoints",
"with",
"ignition",
"delay",
"from",
"file",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L318-L471 | train | Parse datapoints with ignition delay from file. |
pr-omethe-us/PyKED | pyked/converters.py | ReSpecTh_to_ChemKED | def ReSpecTh_to_ChemKED(filename_xml, file_author='', file_author_orcid='', *, validate=False):
"""Convert ReSpecTh XML file to ChemKED-compliant dictionary.
Args:
filename_xml (`str`): Name of ReSpecTh XML file to be converted.
file_author (`str`, optional): Name to override original file auth... | python | def ReSpecTh_to_ChemKED(filename_xml, file_author='', file_author_orcid='', *, validate=False):
"""Convert ReSpecTh XML file to ChemKED-compliant dictionary.
Args:
filename_xml (`str`): Name of ReSpecTh XML file to be converted.
file_author (`str`, optional): Name to override original file auth... | [
"def",
"ReSpecTh_to_ChemKED",
"(",
"filename_xml",
",",
"file_author",
"=",
"''",
",",
"file_author_orcid",
"=",
"''",
",",
"*",
",",
"validate",
"=",
"False",
")",
":",
"# get all information from XML file",
"tree",
"=",
"etree",
".",
"parse",
"(",
"filename_xm... | Convert ReSpecTh XML file to ChemKED-compliant dictionary.
Args:
filename_xml (`str`): Name of ReSpecTh XML file to be converted.
file_author (`str`, optional): Name to override original file author
file_author_orcid (`str`, optional): ORCID of file author
validate (`bool`, optional... | [
"Convert",
"ReSpecTh",
"XML",
"file",
"to",
"ChemKED",
"-",
"compliant",
"dictionary",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L474-L544 | train | Convert a ReSpecTh XML file to ChemKED - compliant dictionary. |
pr-omethe-us/PyKED | pyked/converters.py | respth2ck | def respth2ck(argv=None):
"""Command-line entry point for converting a ReSpecTh XML file to a ChemKED YAML file.
"""
parser = ArgumentParser(
description='Convert a ReSpecTh XML file to a ChemKED YAML file.'
)
parser.add_argument('-i', '--input',
type=str,
... | python | def respth2ck(argv=None):
"""Command-line entry point for converting a ReSpecTh XML file to a ChemKED YAML file.
"""
parser = ArgumentParser(
description='Convert a ReSpecTh XML file to a ChemKED YAML file.'
)
parser.add_argument('-i', '--input',
type=str,
... | [
"def",
"respth2ck",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"'Convert a ReSpecTh XML file to a ChemKED YAML file.'",
")",
"parser",
".",
"add_argument",
"(",
"'-i'",
",",
"'--input'",
",",
"type",
"=",
"str",
... | Command-line entry point for converting a ReSpecTh XML file to a ChemKED YAML file. | [
"Command",
"-",
"line",
"entry",
"point",
"for",
"converting",
"a",
"ReSpecTh",
"XML",
"file",
"to",
"a",
"ChemKED",
"YAML",
"file",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L547-L595 | train | Command - line entry point for converting a ReSpecTh XML file to a ChemKED YAML file. |
pr-omethe-us/PyKED | pyked/converters.py | ck2respth | def ck2respth(argv=None):
"""Command-line entry point for converting a ChemKED YAML file to a ReSpecTh XML file.
"""
parser = ArgumentParser(
description='Convert a ChemKED YAML file to a ReSpecTh XML file.'
)
parser.add_argument('-i', '--input',
type=str,
... | python | def ck2respth(argv=None):
"""Command-line entry point for converting a ChemKED YAML file to a ReSpecTh XML file.
"""
parser = ArgumentParser(
description='Convert a ChemKED YAML file to a ReSpecTh XML file.'
)
parser.add_argument('-i', '--input',
type=str,
... | [
"def",
"ck2respth",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"'Convert a ChemKED YAML file to a ReSpecTh XML file.'",
")",
"parser",
".",
"add_argument",
"(",
"'-i'",
",",
"'--input'",
",",
"type",
"=",
"str",
... | Command-line entry point for converting a ChemKED YAML file to a ReSpecTh XML file. | [
"Command",
"-",
"line",
"entry",
"point",
"for",
"converting",
"a",
"ChemKED",
"YAML",
"file",
"to",
"a",
"ReSpecTh",
"XML",
"file",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L598-L619 | train | Command - line entry point for converting a ChemKED YAML file to a ReSpecTh XML file. |
pr-omethe-us/PyKED | pyked/converters.py | main | def main(argv=None):
"""General function for converting between ReSpecTh and ChemKED files based on extension.
"""
parser = ArgumentParser(
description='Convert between ReSpecTh XML file and ChemKED YAML file '
'automatically based on file extension.'
)
parser.add_arg... | python | def main(argv=None):
"""General function for converting between ReSpecTh and ChemKED files based on extension.
"""
parser = ArgumentParser(
description='Convert between ReSpecTh XML file and ChemKED YAML file '
'automatically based on file extension.'
)
parser.add_arg... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"'Convert between ReSpecTh XML file and ChemKED YAML file '",
"'automatically based on file extension.'",
")",
"parser",
".",
"add_argument",
"(",
"'-i'",
",",
"... | General function for converting between ReSpecTh and ChemKED files based on extension. | [
"General",
"function",
"for",
"converting",
"between",
"ReSpecTh",
"and",
"ChemKED",
"files",
"based",
"on",
"extension",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L622-L672 | train | This function is used to convert between ReSpecTh and ChemKED files based on file extension. |
bitlabstudio/django-libs | django_libs/middleware.py | ErrorMiddleware.process_exception | def process_exception(self, request, exception):
"""
Add user details.
"""
if request.user and hasattr(request.user, 'email'):
request.META['USER'] = request.user.email | python | def process_exception(self, request, exception):
"""
Add user details.
"""
if request.user and hasattr(request.user, 'email'):
request.META['USER'] = request.user.email | [
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"if",
"request",
".",
"user",
"and",
"hasattr",
"(",
"request",
".",
"user",
",",
"'email'",
")",
":",
"request",
".",
"META",
"[",
"'USER'",
"]",
"=",
"request",
".",... | Add user details. | [
"Add",
"user",
"details",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/middleware.py#L36-L41 | train | Add user details to the request. META. |
bitlabstudio/django-libs | django_libs/middleware.py | CustomBrokenLinkEmailsMiddleware.process_response | def process_response(self, request, response):
"""
Send broken link emails for relevant 404 NOT FOUND responses.
"""
if response.status_code == 404 and not settings.DEBUG:
domain = request.get_host()
path = request.get_full_path()
referer = force_text(... | python | def process_response(self, request, response):
"""
Send broken link emails for relevant 404 NOT FOUND responses.
"""
if response.status_code == 404 and not settings.DEBUG:
domain = request.get_host()
path = request.get_full_path()
referer = force_text(... | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"404",
"and",
"not",
"settings",
".",
"DEBUG",
":",
"domain",
"=",
"request",
".",
"get_host",
"(",
")",
"path",
"=",
"request"... | Send broken link emails for relevant 404 NOT FOUND responses. | [
"Send",
"broken",
"link",
"emails",
"for",
"relevant",
"404",
"NOT",
"FOUND",
"responses",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/middleware.py#L94-L129 | train | Send broken link emails for relevant 404 NOT FOUND responses. |
bitlabstudio/django-libs | django_libs/middleware.py | CustomBrokenLinkEmailsMiddleware.is_internal_request | def is_internal_request(self, domain, referer):
"""
Returns True if referring URL is the same domain as current request.
"""
# Different subdomains are treated as different domains.
return bool(re.match("^https?://%s/" % re.escape(domain), referer)) | python | def is_internal_request(self, domain, referer):
"""
Returns True if referring URL is the same domain as current request.
"""
# Different subdomains are treated as different domains.
return bool(re.match("^https?://%s/" % re.escape(domain), referer)) | [
"def",
"is_internal_request",
"(",
"self",
",",
"domain",
",",
"referer",
")",
":",
"# Different subdomains are treated as different domains.",
"return",
"bool",
"(",
"re",
".",
"match",
"(",
"\"^https?://%s/\"",
"%",
"re",
".",
"escape",
"(",
"domain",
")",
",",
... | Returns True if referring URL is the same domain as current request. | [
"Returns",
"True",
"if",
"referring",
"URL",
"is",
"the",
"same",
"domain",
"as",
"current",
"request",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/middleware.py#L131-L137 | train | Returns True if the referer is the same domain as the current request. |
bitlabstudio/django-libs | django_libs/middleware.py | CustomBrokenLinkEmailsMiddleware.is_ignorable_request | def is_ignorable_request(self, request, uri, domain, referer):
"""
Returns True if the given request *shouldn't* notify the site managers.
"""
# '?' in referer is identified as search engine source
if (not referer or (not self.is_internal_request(
domain, referer)... | python | def is_ignorable_request(self, request, uri, domain, referer):
"""
Returns True if the given request *shouldn't* notify the site managers.
"""
# '?' in referer is identified as search engine source
if (not referer or (not self.is_internal_request(
domain, referer)... | [
"def",
"is_ignorable_request",
"(",
"self",
",",
"request",
",",
"uri",
",",
"domain",
",",
"referer",
")",
":",
"# '?' in referer is identified as search engine source",
"if",
"(",
"not",
"referer",
"or",
"(",
"not",
"self",
".",
"is_internal_request",
"(",
"doma... | Returns True if the given request *shouldn't* notify the site managers. | [
"Returns",
"True",
"if",
"the",
"given",
"request",
"*",
"shouldn",
"t",
"*",
"notify",
"the",
"site",
"managers",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/middleware.py#L139-L148 | train | Returns True if the given request shouldn t notify the site managers. |
oleiade/durations | durations/duration.py | Duration.parse | def parse(self, representation):
"""Parses a duration string representation
:param representation: duration as a string, example: '1d' (day),
'34minutes' (minutes), '485s' (seconds)...
:type representation: string
:returns: the parsed duration repres... | python | def parse(self, representation):
"""Parses a duration string representation
:param representation: duration as a string, example: '1d' (day),
'34minutes' (minutes), '485s' (seconds)...
:type representation: string
:returns: the parsed duration repres... | [
"def",
"parse",
"(",
"self",
",",
"representation",
")",
":",
"elements",
"=",
"extract_tokens",
"(",
"representation",
")",
"try",
":",
"scales",
"=",
"[",
"DurationRepresentation",
"(",
"float",
"(",
"p",
"[",
"0",
"]",
")",
",",
"Scale",
"(",
"p",
"... | Parses a duration string representation
:param representation: duration as a string, example: '1d' (day),
'34minutes' (minutes), '485s' (seconds)...
:type representation: string
:returns: the parsed duration representation
:rtype: DurationRepresentat... | [
"Parses",
"a",
"duration",
"string",
"representation"
] | 62c176dfa7d36d5c59bf93bdebfdc80ab53757bd | https://github.com/oleiade/durations/blob/62c176dfa7d36d5c59bf93bdebfdc80ab53757bd/durations/duration.py#L53-L71 | train | Parses a duration string representation into a list of DurationRepresentation objects |
Genida/django-meerkat | src/meerkat/logs/models.py | IPInfo.get_or_create_from_ip | def get_or_create_from_ip(ip):
"""
Get or create an entry using obtained information from an IP.
Args:
ip (str): IP address xxx.xxx.xxx.xxx.
Returns:
ip_info: an instance of IPInfo.
"""
data = ip_api_handler.get(ip)
if data and any(v for ... | python | def get_or_create_from_ip(ip):
"""
Get or create an entry using obtained information from an IP.
Args:
ip (str): IP address xxx.xxx.xxx.xxx.
Returns:
ip_info: an instance of IPInfo.
"""
data = ip_api_handler.get(ip)
if data and any(v for ... | [
"def",
"get_or_create_from_ip",
"(",
"ip",
")",
":",
"data",
"=",
"ip_api_handler",
".",
"get",
"(",
"ip",
")",
"if",
"data",
"and",
"any",
"(",
"v",
"for",
"v",
"in",
"data",
".",
"values",
"(",
")",
")",
":",
"if",
"data",
".",
"get",
"(",
"'ip... | Get or create an entry using obtained information from an IP.
Args:
ip (str): IP address xxx.xxx.xxx.xxx.
Returns:
ip_info: an instance of IPInfo. | [
"Get",
"or",
"create",
"an",
"entry",
"using",
"obtained",
"information",
"from",
"an",
"IP",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/models.py#L128-L143 | train | Get or create an entry using obtained information from an IP. |
Genida/django-meerkat | src/meerkat/logs/models.py | RequestLog.update_ip_info | def update_ip_info(self, since_days=10, save=False, force=False):
"""
Update the IP info.
Args:
since_days (int): if checked less than this number of days ago,
don't check again (default to 10 days).
save (bool): whether to save anyway or not.
... | python | def update_ip_info(self, since_days=10, save=False, force=False):
"""
Update the IP info.
Args:
since_days (int): if checked less than this number of days ago,
don't check again (default to 10 days).
save (bool): whether to save anyway or not.
... | [
"def",
"update_ip_info",
"(",
"self",
",",
"since_days",
"=",
"10",
",",
"save",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"# If ip already checked",
"try",
":",
"last_check",
"=",
"IPInfoCheck",
".",
"objects",
".",
"get",
"(",
"ip_address",
"="... | Update the IP info.
Args:
since_days (int): if checked less than this number of days ago,
don't check again (default to 10 days).
save (bool): whether to save anyway or not.
force (bool): whether to update ip_info to last checked one.
Returns:
... | [
"Update",
"the",
"IP",
"info",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/models.py#L333-L387 | train | Update the IP info object for the current user. |
Genida/django-meerkat | src/meerkat/logs/models.py | RequestLog.start_daemon | def start_daemon():
"""
Start a thread to continuously read log files and append lines in DB.
Work in progress. Currently the thread doesn't append anything,
it only print the information parsed from each line read.
Returns:
thread: the started thread.
"""
... | python | def start_daemon():
"""
Start a thread to continuously read log files and append lines in DB.
Work in progress. Currently the thread doesn't append anything,
it only print the information parsed from each line read.
Returns:
thread: the started thread.
"""
... | [
"def",
"start_daemon",
"(",
")",
":",
"if",
"RequestLog",
".",
"daemon",
"is",
"None",
":",
"parser",
"=",
"get_nginx_parser",
"(",
")",
"RequestLog",
".",
"daemon",
"=",
"RequestLog",
".",
"ParseToDBThread",
"(",
"parser",
",",
"daemon",
"=",
"True",
")",... | Start a thread to continuously read log files and append lines in DB.
Work in progress. Currently the thread doesn't append anything,
it only print the information parsed from each line read.
Returns:
thread: the started thread. | [
"Start",
"a",
"thread",
"to",
"continuously",
"read",
"log",
"files",
"and",
"append",
"lines",
"in",
"DB",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/models.py#L648-L662 | train | Start a daemon thread to continuously read log files and append lines in DB. |
pr-omethe-us/PyKED | pyked/chemked.py | ChemKED.from_respecth | def from_respecth(cls, filename_xml, file_author='', file_author_orcid=''):
"""Construct a ChemKED instance directly from a ReSpecTh file.
Arguments:
filename_xml (`str`): Filename of the ReSpecTh-formatted XML file to be imported
file_author (`str`, optional): File author to be... | python | def from_respecth(cls, filename_xml, file_author='', file_author_orcid=''):
"""Construct a ChemKED instance directly from a ReSpecTh file.
Arguments:
filename_xml (`str`): Filename of the ReSpecTh-formatted XML file to be imported
file_author (`str`, optional): File author to be... | [
"def",
"from_respecth",
"(",
"cls",
",",
"filename_xml",
",",
"file_author",
"=",
"''",
",",
"file_author_orcid",
"=",
"''",
")",
":",
"properties",
"=",
"ReSpecTh_to_ChemKED",
"(",
"filename_xml",
",",
"file_author",
",",
"file_author_orcid",
",",
"validate",
"... | Construct a ChemKED instance directly from a ReSpecTh file.
Arguments:
filename_xml (`str`): Filename of the ReSpecTh-formatted XML file to be imported
file_author (`str`, optional): File author to be added to the list generated from the
XML file
file_author_... | [
"Construct",
"a",
"ChemKED",
"instance",
"directly",
"from",
"a",
"ReSpecTh",
"file",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L146-L167 | train | Construct a ChemKED instance from a ReSpecTh file. |
pr-omethe-us/PyKED | pyked/chemked.py | ChemKED.validate_yaml | def validate_yaml(self, properties):
"""Validate the parsed YAML file for adherance to the ChemKED format.
Arguments:
properties (`dict`): Dictionary created from the parsed YAML file
Raises:
`ValueError`: If the YAML file cannot be validated, a `ValueError` is raised w... | python | def validate_yaml(self, properties):
"""Validate the parsed YAML file for adherance to the ChemKED format.
Arguments:
properties (`dict`): Dictionary created from the parsed YAML file
Raises:
`ValueError`: If the YAML file cannot be validated, a `ValueError` is raised w... | [
"def",
"validate_yaml",
"(",
"self",
",",
"properties",
")",
":",
"validator",
"=",
"OurValidator",
"(",
"schema",
")",
"if",
"not",
"validator",
".",
"validate",
"(",
"properties",
")",
":",
"for",
"key",
",",
"value",
"in",
"validator",
".",
"errors",
... | Validate the parsed YAML file for adherance to the ChemKED format.
Arguments:
properties (`dict`): Dictionary created from the parsed YAML file
Raises:
`ValueError`: If the YAML file cannot be validated, a `ValueError` is raised whose
string contains the errors ... | [
"Validate",
"the",
"parsed",
"YAML",
"file",
"for",
"adherance",
"to",
"the",
"ChemKED",
"format",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L169-L186 | train | Validate the YAML file for adherance to the ChemKED format. |
pr-omethe-us/PyKED | pyked/chemked.py | ChemKED.get_dataframe | def get_dataframe(self, output_columns=None):
"""Get a Pandas DataFrame of the datapoints in this instance.
Arguments:
output_columns (`list`, optional): List of strings specifying the columns to include
in the output DataFrame. The default is `None`, which outputs all of th... | python | def get_dataframe(self, output_columns=None):
"""Get a Pandas DataFrame of the datapoints in this instance.
Arguments:
output_columns (`list`, optional): List of strings specifying the columns to include
in the output DataFrame. The default is `None`, which outputs all of th... | [
"def",
"get_dataframe",
"(",
"self",
",",
"output_columns",
"=",
"None",
")",
":",
"import",
"pandas",
"as",
"pd",
"valid_labels",
"=",
"[",
"a",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
"for",
"a",
"in",
"self",
".",
"__dict__",
"if",
"not",
"("... | Get a Pandas DataFrame of the datapoints in this instance.
Arguments:
output_columns (`list`, optional): List of strings specifying the columns to include
in the output DataFrame. The default is `None`, which outputs all of the
columns. Options include (not case sens... | [
"Get",
"a",
"Pandas",
"DataFrame",
"of",
"the",
"datapoints",
"in",
"this",
"instance",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L188-L308 | train | Returns a Pandas DataFrame of the datapoints in this instance. |
pr-omethe-us/PyKED | pyked/chemked.py | ChemKED.write_file | def write_file(self, filename, *, overwrite=False):
"""Write new ChemKED YAML file based on object.
Arguments:
filename (`str`): Filename for target YAML file
overwrite (`bool`, optional): Whether to overwrite file with given name if present.
Must be supplied as ... | python | def write_file(self, filename, *, overwrite=False):
"""Write new ChemKED YAML file based on object.
Arguments:
filename (`str`): Filename for target YAML file
overwrite (`bool`, optional): Whether to overwrite file with given name if present.
Must be supplied as ... | [
"def",
"write_file",
"(",
"self",
",",
"filename",
",",
"*",
",",
"overwrite",
"=",
"False",
")",
":",
"# Ensure file isn't already present",
"if",
"exists",
"(",
"filename",
")",
"and",
"not",
"overwrite",
":",
"raise",
"OSError",
"(",
"filename",
"+",
"' a... | Write new ChemKED YAML file based on object.
Arguments:
filename (`str`): Filename for target YAML file
overwrite (`bool`, optional): Whether to overwrite file with given name if present.
Must be supplied as a keyword-argument.
Raises:
`NameError`: I... | [
"Write",
"new",
"ChemKED",
"YAML",
"file",
"based",
"on",
"object",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L310-L332 | train | Write the object to a new ChemKED file based on the properties. |
pr-omethe-us/PyKED | pyked/chemked.py | ChemKED.convert_to_ReSpecTh | def convert_to_ReSpecTh(self, filename):
"""Convert ChemKED record to ReSpecTh XML file.
This converter uses common information in a ChemKED file to generate a
ReSpecTh XML file. Note that some information may be lost, as ChemKED stores
some additional attributes.
Arguments:
... | python | def convert_to_ReSpecTh(self, filename):
"""Convert ChemKED record to ReSpecTh XML file.
This converter uses common information in a ChemKED file to generate a
ReSpecTh XML file. Note that some information may be lost, as ChemKED stores
some additional attributes.
Arguments:
... | [
"def",
"convert_to_ReSpecTh",
"(",
"self",
",",
"filename",
")",
":",
"root",
"=",
"etree",
".",
"Element",
"(",
"'experiment'",
")",
"file_author",
"=",
"etree",
".",
"SubElement",
"(",
"root",
",",
"'fileAuthor'",
")",
"file_author",
".",
"text",
"=",
"s... | Convert ChemKED record to ReSpecTh XML file.
This converter uses common information in a ChemKED file to generate a
ReSpecTh XML file. Note that some information may be lost, as ChemKED stores
some additional attributes.
Arguments:
filename (`str`): Filename for output ReSp... | [
"Convert",
"ChemKED",
"record",
"to",
"ReSpecTh",
"XML",
"file",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L334-L585 | train | Convert a ChemKED record to ReSpecTh XML file. |
pr-omethe-us/PyKED | pyked/chemked.py | DataPoint.process_quantity | def process_quantity(self, properties):
"""Process the uncertainty information from a given quantity and return it
"""
quant = Q_(properties[0])
if len(properties) > 1:
unc = properties[1]
uncertainty = unc.get('uncertainty', False)
upper_uncertainty =... | python | def process_quantity(self, properties):
"""Process the uncertainty information from a given quantity and return it
"""
quant = Q_(properties[0])
if len(properties) > 1:
unc = properties[1]
uncertainty = unc.get('uncertainty', False)
upper_uncertainty =... | [
"def",
"process_quantity",
"(",
"self",
",",
"properties",
")",
":",
"quant",
"=",
"Q_",
"(",
"properties",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"properties",
")",
">",
"1",
":",
"unc",
"=",
"properties",
"[",
"1",
"]",
"uncertainty",
"=",
"unc",
... | Process the uncertainty information from a given quantity and return it | [
"Process",
"the",
"uncertainty",
"information",
"from",
"a",
"given",
"quantity",
"and",
"return",
"it"
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L722-L760 | train | Process the uncertainty information from a given quantity and return it. |
pr-omethe-us/PyKED | pyked/chemked.py | DataPoint.get_cantera_composition_string | def get_cantera_composition_string(self, species_conversion=None):
"""Get the composition in a string format suitable for input to Cantera.
Returns a formatted string no matter the type of composition. As such, this method
is not recommended for end users; instead, prefer the `get_cantera_mole_... | python | def get_cantera_composition_string(self, species_conversion=None):
"""Get the composition in a string format suitable for input to Cantera.
Returns a formatted string no matter the type of composition. As such, this method
is not recommended for end users; instead, prefer the `get_cantera_mole_... | [
"def",
"get_cantera_composition_string",
"(",
"self",
",",
"species_conversion",
"=",
"None",
")",
":",
"if",
"self",
".",
"composition_type",
"in",
"[",
"'mole fraction'",
",",
"'mass fraction'",
"]",
":",
"factor",
"=",
"1.0",
"elif",
"self",
".",
"composition... | Get the composition in a string format suitable for input to Cantera.
Returns a formatted string no matter the type of composition. As such, this method
is not recommended for end users; instead, prefer the `get_cantera_mole_fraction`
or `get_cantera_mass_fraction` methods.
Arguments:
... | [
"Get",
"the",
"composition",
"in",
"a",
"string",
"format",
"suitable",
"for",
"input",
"to",
"Cantera",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L762-L815 | train | Get the composition in a string suitable for input to Cantera. |
pr-omethe-us/PyKED | pyked/chemked.py | DataPoint.get_cantera_mole_fraction | def get_cantera_mole_fraction(self, species_conversion=None):
"""Get the mole fractions in a string format suitable for input to Cantera.
Arguments:
species_conversion (`dict`, optional): Mapping of species identifier to a
species name. This argument should be supplied when ... | python | def get_cantera_mole_fraction(self, species_conversion=None):
"""Get the mole fractions in a string format suitable for input to Cantera.
Arguments:
species_conversion (`dict`, optional): Mapping of species identifier to a
species name. This argument should be supplied when ... | [
"def",
"get_cantera_mole_fraction",
"(",
"self",
",",
"species_conversion",
"=",
"None",
")",
":",
"if",
"self",
".",
"composition_type",
"==",
"'mass fraction'",
":",
"raise",
"ValueError",
"(",
"'Cannot get mole fractions from the given composition.\\n'",
"'{}'",
".",
... | Get the mole fractions in a string format suitable for input to Cantera.
Arguments:
species_conversion (`dict`, optional): Mapping of species identifier to a
species name. This argument should be supplied when the name of the
species in the ChemKED YAML file does not... | [
"Get",
"the",
"mole",
"fractions",
"in",
"a",
"string",
"format",
"suitable",
"for",
"input",
"to",
"Cantera",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L817-L851 | train | Get the mole fractions in a string format suitable for input to Cantera. |
pr-omethe-us/PyKED | pyked/chemked.py | DataPoint.get_cantera_mass_fraction | def get_cantera_mass_fraction(self, species_conversion=None):
"""Get the mass fractions in a string format suitable for input to Cantera.
Arguments:
species_conversion (`dict`, optional): Mapping of species identifier to a
species name. This argument should be supplied when ... | python | def get_cantera_mass_fraction(self, species_conversion=None):
"""Get the mass fractions in a string format suitable for input to Cantera.
Arguments:
species_conversion (`dict`, optional): Mapping of species identifier to a
species name. This argument should be supplied when ... | [
"def",
"get_cantera_mass_fraction",
"(",
"self",
",",
"species_conversion",
"=",
"None",
")",
":",
"if",
"self",
".",
"composition_type",
"in",
"[",
"'mole fraction'",
",",
"'mole percent'",
"]",
":",
"raise",
"ValueError",
"(",
"'Cannot get mass fractions from the gi... | Get the mass fractions in a string format suitable for input to Cantera.
Arguments:
species_conversion (`dict`, optional): Mapping of species identifier to a
species name. This argument should be supplied when the name of the
species in the ChemKED YAML file does not... | [
"Get",
"the",
"mass",
"fractions",
"in",
"a",
"string",
"format",
"suitable",
"for",
"input",
"to",
"Cantera",
"."
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L853-L889 | train | Get the mass fractions in a string format suitable for input to Cantera. |
bitlabstudio/django-libs | django_libs/decorators.py | lockfile | def lockfile(lockfile_name, lock_wait_timeout=-1):
"""
Only runs the method if the lockfile is not acquired.
You should create a setting ``LOCKFILE_PATH`` which points to
``/home/username/tmp/``.
In your management command, use it like so::
LOCKFILE = os.path.join(
settings.LO... | python | def lockfile(lockfile_name, lock_wait_timeout=-1):
"""
Only runs the method if the lockfile is not acquired.
You should create a setting ``LOCKFILE_PATH`` which points to
``/home/username/tmp/``.
In your management command, use it like so::
LOCKFILE = os.path.join(
settings.LO... | [
"def",
"lockfile",
"(",
"lockfile_name",
",",
"lock_wait_timeout",
"=",
"-",
"1",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lock",
"=... | Only runs the method if the lockfile is not acquired.
You should create a setting ``LOCKFILE_PATH`` which points to
``/home/username/tmp/``.
In your management command, use it like so::
LOCKFILE = os.path.join(
settings.LOCKFILE_FOLDER, 'command_name')
class Command(NoArgsCom... | [
"Only",
"runs",
"the",
"method",
"if",
"the",
"lockfile",
"is",
"not",
"acquired",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/decorators.py#L11-L51 | train | A decorator that creates a command that will lock a file. |
bitlabstudio/django-libs | django_libs/decorators.py | get_username | def get_username(identifier):
"""Checks if a string is a email adress or not."""
pattern = re.compile('.+@\w+\..+')
if pattern.match(identifier):
try:
user = User.objects.get(email=identifier)
except:
raise Http404
else:
return user.username
el... | python | def get_username(identifier):
"""Checks if a string is a email adress or not."""
pattern = re.compile('.+@\w+\..+')
if pattern.match(identifier):
try:
user = User.objects.get(email=identifier)
except:
raise Http404
else:
return user.username
el... | [
"def",
"get_username",
"(",
"identifier",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'.+@\\w+\\..+'",
")",
"if",
"pattern",
".",
"match",
"(",
"identifier",
")",
":",
"try",
":",
"user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"email",... | Checks if a string is a email adress or not. | [
"Checks",
"if",
"a",
"string",
"is",
"a",
"email",
"adress",
"or",
"not",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/decorators.py#L54-L65 | train | Checks if a string is an email adress or not. |
amatellanes/fixerio | fixerio/client.py | Fixerio._create_payload | def _create_payload(self, symbols):
""" Creates a payload with no none values.
:param symbols: currency symbols to request specific exchange rates.
:type symbols: list or tuple
:return: a payload.
:rtype: dict
"""
payload = {'access_key': self.access_key}
... | python | def _create_payload(self, symbols):
""" Creates a payload with no none values.
:param symbols: currency symbols to request specific exchange rates.
:type symbols: list or tuple
:return: a payload.
:rtype: dict
"""
payload = {'access_key': self.access_key}
... | [
"def",
"_create_payload",
"(",
"self",
",",
"symbols",
")",
":",
"payload",
"=",
"{",
"'access_key'",
":",
"self",
".",
"access_key",
"}",
"if",
"symbols",
"is",
"not",
"None",
":",
"payload",
"[",
"'symbols'",
"]",
"=",
"','",
".",
"join",
"(",
"symbo... | Creates a payload with no none values.
:param symbols: currency symbols to request specific exchange rates.
:type symbols: list or tuple
:return: a payload.
:rtype: dict | [
"Creates",
"a",
"payload",
"with",
"no",
"none",
"values",
"."
] | 0890e0ee3d39a2a3a2396d934c32bc9ed5f4c974 | https://github.com/amatellanes/fixerio/blob/0890e0ee3d39a2a3a2396d934c32bc9ed5f4c974/fixerio/client.py#L32-L44 | train | Creates a payload with no none values. |
amatellanes/fixerio | fixerio/client.py | Fixerio.historical_rates | def historical_rates(self, date, symbols=None):
"""
Get historical rates for any day since `date`.
:param date: a date
:type date: date or str
:param symbols: currency symbols to request specific exchange rates.
:type symbols: list or tuple
:return: the historica... | python | def historical_rates(self, date, symbols=None):
"""
Get historical rates for any day since `date`.
:param date: a date
:type date: date or str
:param symbols: currency symbols to request specific exchange rates.
:type symbols: list or tuple
:return: the historica... | [
"def",
"historical_rates",
"(",
"self",
",",
"date",
",",
"symbols",
"=",
"None",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"date",
",",
"datetime",
".",
"date",
")",
":",
"# Convert date to ISO 8601 format.",
"date",
"=",
"date",
".",
"isoformat",
"(... | Get historical rates for any day since `date`.
:param date: a date
:type date: date or str
:param symbols: currency symbols to request specific exchange rates.
:type symbols: list or tuple
:return: the historical rates for any day since `date`.
:rtype: dict
:rais... | [
"Get",
"historical",
"rates",
"for",
"any",
"day",
"since",
"date",
"."
] | 0890e0ee3d39a2a3a2396d934c32bc9ed5f4c974 | https://github.com/amatellanes/fixerio/blob/0890e0ee3d39a2a3a2396d934c32bc9ed5f4c974/fixerio/client.py#L69-L97 | train | Get historical rates for any day since a given date. |
gsi-upm/soil | setup.py | parse_requirements | def parse_requirements(filename):
""" load requirements from a pip requirements file """
with open(filename, 'r') as f:
lineiter = list(line.strip() for line in f)
return [line for line in lineiter if line and not line.startswith("#")] | python | def parse_requirements(filename):
""" load requirements from a pip requirements file """
with open(filename, 'r') as f:
lineiter = list(line.strip() for line in f)
return [line for line in lineiter if line and not line.startswith("#")] | [
"def",
"parse_requirements",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"lineiter",
"=",
"list",
"(",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"f",
")",
"return",
"[",
"line",
"for",
"li... | load requirements from a pip requirements file | [
"load",
"requirements",
"from",
"a",
"pip",
"requirements",
"file"
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/setup.py#L10-L14 | train | load a pip requirements file |
gsi-upm/soil | soil/environment.py | Environment.save_state | def save_state(self):
'''
:DEPRECATED:
Periodically save the state of the environment and the agents.
'''
self._save_state()
while self.peek() != simpy.core.Infinity:
delay = max(self.peek() - self.now, self.interval)
utils.logger.debug('Step: {}'.... | python | def save_state(self):
'''
:DEPRECATED:
Periodically save the state of the environment and the agents.
'''
self._save_state()
while self.peek() != simpy.core.Infinity:
delay = max(self.peek() - self.now, self.interval)
utils.logger.debug('Step: {}'.... | [
"def",
"save_state",
"(",
"self",
")",
":",
"self",
".",
"_save_state",
"(",
")",
"while",
"self",
".",
"peek",
"(",
")",
"!=",
"simpy",
".",
"core",
".",
"Infinity",
":",
"delay",
"=",
"max",
"(",
"self",
".",
"peek",
"(",
")",
"-",
"self",
".",... | :DEPRECATED:
Periodically save the state of the environment and the agents. | [
":",
"DEPRECATED",
":",
"Periodically",
"save",
"the",
"state",
"of",
"the",
"environment",
"and",
"the",
"agents",
"."
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/environment.py#L175-L190 | train | Yields the state of the environment and agents. |
Genida/django-meerkat | src/meerkat/utils/list.py | distinct | def distinct(l):
"""
Return a list where the duplicates have been removed.
Args:
l (list): the list to filter.
Returns:
list: the same list without duplicates.
"""
seen = set()
seen_add = seen.add
return (_ for _ in l if not (_ in seen or seen_add(_))) | python | def distinct(l):
"""
Return a list where the duplicates have been removed.
Args:
l (list): the list to filter.
Returns:
list: the same list without duplicates.
"""
seen = set()
seen_add = seen.add
return (_ for _ in l if not (_ in seen or seen_add(_))) | [
"def",
"distinct",
"(",
"l",
")",
":",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"(",
"_",
"for",
"_",
"in",
"l",
"if",
"not",
"(",
"_",
"in",
"seen",
"or",
"seen_add",
"(",
"_",
")",
")",
")"
] | Return a list where the duplicates have been removed.
Args:
l (list): the list to filter.
Returns:
list: the same list without duplicates. | [
"Return",
"a",
"list",
"where",
"the",
"duplicates",
"have",
"been",
"removed",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/list.py#L6-L18 | train | Returns a list of the unique entries in the list l. |
bitlabstudio/django-libs | django_libs/format_utils.py | iter_format_modules | def iter_format_modules(lang):
"""
Does the heavy lifting of finding format modules.
"""
if check_for_language(lang):
format_locations = []
for path in CUSTOM_FORMAT_MODULE_PATHS:
format_locations.append(path + '.%s')
format_locations.append('django.conf.locale.%s')
... | python | def iter_format_modules(lang):
"""
Does the heavy lifting of finding format modules.
"""
if check_for_language(lang):
format_locations = []
for path in CUSTOM_FORMAT_MODULE_PATHS:
format_locations.append(path + '.%s')
format_locations.append('django.conf.locale.%s')
... | [
"def",
"iter_format_modules",
"(",
"lang",
")",
":",
"if",
"check_for_language",
"(",
"lang",
")",
":",
"format_locations",
"=",
"[",
"]",
"for",
"path",
"in",
"CUSTOM_FORMAT_MODULE_PATHS",
":",
"format_locations",
".",
"append",
"(",
"path",
"+",
"'.%s'",
")"... | Does the heavy lifting of finding format modules. | [
"Does",
"the",
"heavy",
"lifting",
"of",
"finding",
"format",
"modules",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/format_utils.py#L50-L69 | train | Iterates over all format modules in the given language. |
bitlabstudio/django-libs | django_libs/format_utils.py | get_format_modules | def get_format_modules(lang=None, reverse=False):
"""
Returns a list of the format modules found
"""
if lang is None:
lang = get_language()
modules = _format_modules_cache.setdefault(lang, list(
iter_format_modules(lang)))
if reverse:
return list(reversed(modules))
r... | python | def get_format_modules(lang=None, reverse=False):
"""
Returns a list of the format modules found
"""
if lang is None:
lang = get_language()
modules = _format_modules_cache.setdefault(lang, list(
iter_format_modules(lang)))
if reverse:
return list(reversed(modules))
r... | [
"def",
"get_format_modules",
"(",
"lang",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"lang",
"is",
"None",
":",
"lang",
"=",
"get_language",
"(",
")",
"modules",
"=",
"_format_modules_cache",
".",
"setdefault",
"(",
"lang",
",",
"list",
"... | Returns a list of the format modules found | [
"Returns",
"a",
"list",
"of",
"the",
"format",
"modules",
"found"
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/format_utils.py#L72-L83 | train | Returns a list of the format modules found in the given language. |
bitlabstudio/django-libs | django_libs/format_utils.py | get_format | def get_format(format_type, lang=None, use_l10n=None):
"""
For a specific format type, returns the format for the current
language (locale), defaults to the format in the settings.
format_type is the name of the format, e.g. 'DATE_FORMAT'
If use_l10n is provided and is not None, that will force the... | python | def get_format(format_type, lang=None, use_l10n=None):
"""
For a specific format type, returns the format for the current
language (locale), defaults to the format in the settings.
format_type is the name of the format, e.g. 'DATE_FORMAT'
If use_l10n is provided and is not None, that will force the... | [
"def",
"get_format",
"(",
"format_type",
",",
"lang",
"=",
"None",
",",
"use_l10n",
"=",
"None",
")",
":",
"format_type",
"=",
"str_encode",
"(",
"format_type",
")",
"if",
"use_l10n",
"or",
"(",
"use_l10n",
"is",
"None",
"and",
"settings",
".",
"USE_L10N",... | For a specific format type, returns the format for the current
language (locale), defaults to the format in the settings.
format_type is the name of the format, e.g. 'DATE_FORMAT'
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settin... | [
"For",
"a",
"specific",
"format",
"type",
"returns",
"the",
"format",
"for",
"the",
"current",
"language",
"(",
"locale",
")",
"defaults",
"to",
"the",
"format",
"in",
"the",
"settings",
".",
"format_type",
"is",
"the",
"name",
"of",
"the",
"format",
"e",
... | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/format_utils.py#L86-L122 | train | Returns the format for a specific format type |
bitlabstudio/django-libs | django_libs/views.py | HybridView.as_view | def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
# sanitize keyword arguments
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
... | python | def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
# sanitize keyword arguments
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
... | [
"def",
"as_view",
"(",
"cls",
",",
"*",
"*",
"initkwargs",
")",
":",
"# sanitize keyword arguments",
"for",
"key",
"in",
"initkwargs",
":",
"if",
"key",
"in",
"cls",
".",
"http_method_names",
":",
"raise",
"TypeError",
"(",
"\"You tried to pass in the %s method na... | Main entry point for a request-response process. | [
"Main",
"entry",
"point",
"for",
"a",
"request",
"-",
"response",
"process",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/views.py#L54-L88 | train | A function that returns a view that will dispatch to the specified class. |
Genida/django-meerkat | src/meerkat/logs/boxes.py | BoxLogsStatusCodesByDate.context | def context(self):
"""Get the context."""
stats = status_codes_by_date_stats()
attacks_data = [{
'type': 'line',
'zIndex': 9,
'name': _('Attacks'),
'data': [(v[0], v[1]['attacks'])
for v in stats]
}]
codes_dat... | python | def context(self):
"""Get the context."""
stats = status_codes_by_date_stats()
attacks_data = [{
'type': 'line',
'zIndex': 9,
'name': _('Attacks'),
'data': [(v[0], v[1]['attacks'])
for v in stats]
}]
codes_dat... | [
"def",
"context",
"(",
"self",
")",
":",
"stats",
"=",
"status_codes_by_date_stats",
"(",
")",
"attacks_data",
"=",
"[",
"{",
"'type'",
":",
"'line'",
",",
"'zIndex'",
":",
"9",
",",
"'name'",
":",
"_",
"(",
"'Attacks'",
")",
",",
"'data'",
":",
"[",
... | Get the context. | [
"Get",
"the",
"context",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/boxes.py#L68-L100 | train | Get the context. |
Genida/django-meerkat | src/meerkat/logs/boxes.py | BoxLogsMostVisitedPages.widgets | def widgets(self):
"""Get the items."""
widgets = []
for i, chart in enumerate(most_visited_pages_charts()):
widgets.append(Widget(html_id='most_visited_chart_%d' % i,
content=json.dumps(chart),
template='meerkat/wid... | python | def widgets(self):
"""Get the items."""
widgets = []
for i, chart in enumerate(most_visited_pages_charts()):
widgets.append(Widget(html_id='most_visited_chart_%d' % i,
content=json.dumps(chart),
template='meerkat/wid... | [
"def",
"widgets",
"(",
"self",
")",
":",
"widgets",
"=",
"[",
"]",
"for",
"i",
",",
"chart",
"in",
"enumerate",
"(",
"most_visited_pages_charts",
"(",
")",
")",
":",
"widgets",
".",
"append",
"(",
"Widget",
"(",
"html_id",
"=",
"'most_visited_chart_%d'",
... | Get the items. | [
"Get",
"the",
"items",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/boxes.py#L118-L127 | train | Get the items. |
mozillazg/python-shanbay | shanbay/api.py | API.word | def word(self, word, url='https://api.shanbay.com/bdc/search/'):
"""查询单词"""
params = {
'word': word
}
return self._request(url, params=params).json() | python | def word(self, word, url='https://api.shanbay.com/bdc/search/'):
"""查询单词"""
params = {
'word': word
}
return self._request(url, params=params).json() | [
"def",
"word",
"(",
"self",
",",
"word",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/search/'",
")",
":",
"params",
"=",
"{",
"'word'",
":",
"word",
"}",
"return",
"self",
".",
"_request",
"(",
"url",
",",
"params",
"=",
"params",
")",
".",
"json",
... | 查询单词 | [
"查询单词"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L50-L55 | train | Search for a single word in Shanbay |
mozillazg/python-shanbay | shanbay/api.py | API.add_word | def add_word(self, word_id, url='https://api.shanbay.com/bdc/learning/'):
"""添加单词"""
data = {
'id': word_id
}
return self._request(url, method='post', data=data).json() | python | def add_word(self, word_id, url='https://api.shanbay.com/bdc/learning/'):
"""添加单词"""
data = {
'id': word_id
}
return self._request(url, method='post', data=data).json() | [
"def",
"add_word",
"(",
"self",
",",
"word_id",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/learning/'",
")",
":",
"data",
"=",
"{",
"'id'",
":",
"word_id",
"}",
"return",
"self",
".",
"_request",
"(",
"url",
",",
"method",
"=",
"'post'",
",",
"data",
... | 添加单词 | [
"添加单词"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L58-L63 | train | add word to a user s list |
mozillazg/python-shanbay | shanbay/api.py | API.examples | def examples(self, word_id, type=None,
url='https://api.shanbay.com/bdc/example/'):
"""获取单词的例句"""
params = {
'vocabulary_id': word_id
}
if type is not None:
params['type'] = type
return self._request(url, params=params).json() | python | def examples(self, word_id, type=None,
url='https://api.shanbay.com/bdc/example/'):
"""获取单词的例句"""
params = {
'vocabulary_id': word_id
}
if type is not None:
params['type'] = type
return self._request(url, params=params).json() | [
"def",
"examples",
"(",
"self",
",",
"word_id",
",",
"type",
"=",
"None",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/example/'",
")",
":",
"params",
"=",
"{",
"'vocabulary_id'",
":",
"word_id",
"}",
"if",
"type",
"is",
"not",
"None",
":",
"params",
"["... | 获取单词的例句 | [
"获取单词的例句"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L66-L74 | train | Get examples for a given word |
mozillazg/python-shanbay | shanbay/api.py | API.add_example | def add_example(self, word_id, original, translation,
url='https://api.shanbay.com/bdc/example/'):
"""创建例句"""
data = {
'vocabulary': word_id,
'original': original,
'translation': translation
}
return self._request(url, method='post'... | python | def add_example(self, word_id, original, translation,
url='https://api.shanbay.com/bdc/example/'):
"""创建例句"""
data = {
'vocabulary': word_id,
'original': original,
'translation': translation
}
return self._request(url, method='post'... | [
"def",
"add_example",
"(",
"self",
",",
"word_id",
",",
"original",
",",
"translation",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/example/'",
")",
":",
"data",
"=",
"{",
"'vocabulary'",
":",
"word_id",
",",
"'original'",
":",
"original",
",",
"'translation'... | 创建例句 | [
"创建例句"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L77-L85 | train | add an example to a user s list of words |
mozillazg/python-shanbay | shanbay/api.py | API.favorite_example | def favorite_example(self, example_id,
url='https://api.shanbay.com/bdc/learning_example/'):
"""收藏例句"""
data = {
'example_id': example_id
}
return self._request(url, method='post', data=data).json() | python | def favorite_example(self, example_id,
url='https://api.shanbay.com/bdc/learning_example/'):
"""收藏例句"""
data = {
'example_id': example_id
}
return self._request(url, method='post', data=data).json() | [
"def",
"favorite_example",
"(",
"self",
",",
"example_id",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/learning_example/'",
")",
":",
"data",
"=",
"{",
"'example_id'",
":",
"example_id",
"}",
"return",
"self",
".",
"_request",
"(",
"url",
",",
"method",
"=",
... | 收藏例句 | [
"收藏例句"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L88-L94 | train | favorite an instance of a user |
mozillazg/python-shanbay | shanbay/api.py | API.delete_example | def delete_example(self, example_id,
url='https://api.shanbay.com/bdc/example/{example_id}/'):
"""删除例句"""
url = url.format(example_id=example_id)
return self._request(url, method='delete').json() | python | def delete_example(self, example_id,
url='https://api.shanbay.com/bdc/example/{example_id}/'):
"""删除例句"""
url = url.format(example_id=example_id)
return self._request(url, method='delete').json() | [
"def",
"delete_example",
"(",
"self",
",",
"example_id",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/example/{example_id}/'",
")",
":",
"url",
"=",
"url",
".",
"format",
"(",
"example_id",
"=",
"example_id",
")",
"return",
"self",
".",
"_request",
"(",
"url",... | 删除例句 | [
"删除例句"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L97-L101 | train | Delete an example from Shanbay |
mozillazg/python-shanbay | shanbay/api.py | API.notes | def notes(self, word_id, url='https://api.shanbay.com/bdc/note/'):
"""获取笔记"""
params = {
'vocabulary_id': word_id
}
return self._request(url, params=params).json() | python | def notes(self, word_id, url='https://api.shanbay.com/bdc/note/'):
"""获取笔记"""
params = {
'vocabulary_id': word_id
}
return self._request(url, params=params).json() | [
"def",
"notes",
"(",
"self",
",",
"word_id",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/note/'",
")",
":",
"params",
"=",
"{",
"'vocabulary_id'",
":",
"word_id",
"}",
"return",
"self",
".",
"_request",
"(",
"url",
",",
"params",
"=",
"params",
")",
"."... | 获取笔记 | [
"获取笔记"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L104-L109 | train | Get a list of notes for a given word |
mozillazg/python-shanbay | shanbay/api.py | API.add_note | def add_note(self, word_id, note,
url='https://api.shanbay.com/bdc/note/'):
"""创建笔记"""
data = {
'vocabulary': word_id,
'note': note
}
return self._request(url, method='post', data=data).json() | python | def add_note(self, word_id, note,
url='https://api.shanbay.com/bdc/note/'):
"""创建笔记"""
data = {
'vocabulary': word_id,
'note': note
}
return self._request(url, method='post', data=data).json() | [
"def",
"add_note",
"(",
"self",
",",
"word_id",
",",
"note",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/note/'",
")",
":",
"data",
"=",
"{",
"'vocabulary'",
":",
"word_id",
",",
"'note'",
":",
"note",
"}",
"return",
"self",
".",
"_request",
"(",
"url",... | 创建笔记 | [
"创建笔记"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L112-L119 | train | add a note to a user s list |
mozillazg/python-shanbay | shanbay/api.py | API.favorite_note | def favorite_note(self, note_id,
url='https://api.shanbay.com/bdc/learning_note/'):
"""收藏笔记"""
data = {
'note_id': note_id
}
return self._request(url, method='post', data=data).json() | python | def favorite_note(self, note_id,
url='https://api.shanbay.com/bdc/learning_note/'):
"""收藏笔记"""
data = {
'note_id': note_id
}
return self._request(url, method='post', data=data).json() | [
"def",
"favorite_note",
"(",
"self",
",",
"note_id",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/learning_note/'",
")",
":",
"data",
"=",
"{",
"'note_id'",
":",
"note_id",
"}",
"return",
"self",
".",
"_request",
"(",
"url",
",",
"method",
"=",
"'post'",
"... | 收藏笔记 | [
"收藏笔记"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L122-L128 | train | Favorite note. |
mozillazg/python-shanbay | shanbay/api.py | API.delete_note | def delete_note(self, note_id,
url='https://api.shanbay.com/bdc/note/{note_id}/'):
"""删除笔记"""
url = url.format(note_id=note_id)
return self._request(url, method='delete').json() | python | def delete_note(self, note_id,
url='https://api.shanbay.com/bdc/note/{note_id}/'):
"""删除笔记"""
url = url.format(note_id=note_id)
return self._request(url, method='delete').json() | [
"def",
"delete_note",
"(",
"self",
",",
"note_id",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/note/{note_id}/'",
")",
":",
"url",
"=",
"url",
".",
"format",
"(",
"note_id",
"=",
"note_id",
")",
"return",
"self",
".",
"_request",
"(",
"url",
",",
"method"... | 删除笔记 | [
"删除笔记"
] | d505ba614dc13a36afce46969d13fc64e10dde0d | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L131-L135 | train | Delete a note from Shanbay |
oleiade/durations | durations/scales.py | Scale.get | def get(self, str_representation):
"""Retrieves a scale representation from it's string representation
:param str_representation: scale string representation to be retrieved
:type str_representation: string
:raises: ScaleFormatError
:returns: scale representation
:rt... | python | def get(self, str_representation):
"""Retrieves a scale representation from it's string representation
:param str_representation: scale string representation to be retrieved
:type str_representation: string
:raises: ScaleFormatError
:returns: scale representation
:rt... | [
"def",
"get",
"(",
"self",
",",
"str_representation",
")",
":",
"for",
"scale",
"in",
"self",
".",
"SCALES",
":",
"if",
"str_representation",
"in",
"scale",
":",
"return",
"scale",
"raise",
"ScaleFormatError",
"(",
"\"Unsupported scale format: {0}\"",
".",
"form... | Retrieves a scale representation from it's string representation
:param str_representation: scale string representation to be retrieved
:type str_representation: string
:raises: ScaleFormatError
:returns: scale representation
:rtype: ScaleRepresentation | [
"Retrieves",
"a",
"scale",
"representation",
"from",
"it",
"s",
"string",
"representation"
] | 62c176dfa7d36d5c59bf93bdebfdc80ab53757bd | https://github.com/oleiade/durations/blob/62c176dfa7d36d5c59bf93bdebfdc80ab53757bd/durations/scales.py#L52-L65 | train | Retrieves a scale representation from it s string representation |
bitlabstudio/django-libs | django_libs/views_mixins.py | JSONResponseMixin.render_to_response | def render_to_response(self, context, **response_kwargs):
"""
Returns a JSON response, transforming 'context' to make the payload.
"""
response_kwargs['content_type'] = 'application/json'
return self.response_class(
self.convert_context_to_json(context),
... | python | def render_to_response(self, context, **response_kwargs):
"""
Returns a JSON response, transforming 'context' to make the payload.
"""
response_kwargs['content_type'] = 'application/json'
return self.response_class(
self.convert_context_to_json(context),
... | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"response_kwargs",
"[",
"'content_type'",
"]",
"=",
"'application/json'",
"return",
"self",
".",
"response_class",
"(",
"self",
".",
"convert_context_to_json",
"(... | Returns a JSON response, transforming 'context' to make the payload. | [
"Returns",
"a",
"JSON",
"response",
"transforming",
"context",
"to",
"make",
"the",
"payload",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/views_mixins.py#L90-L99 | train | Returns a JSON response for the given context |
oleiade/durations | durations/parser.py | valid_token | def valid_token(token):
"""Asserts a provided string is a valid duration token representation
:param token: duration representation token
:type token: string
"""
is_scale = False
# Check if the token represents a scale
# If it doesn't set a flag accordingly
try:
Scale(token)... | python | def valid_token(token):
"""Asserts a provided string is a valid duration token representation
:param token: duration representation token
:type token: string
"""
is_scale = False
# Check if the token represents a scale
# If it doesn't set a flag accordingly
try:
Scale(token)... | [
"def",
"valid_token",
"(",
"token",
")",
":",
"is_scale",
"=",
"False",
"# Check if the token represents a scale",
"# If it doesn't set a flag accordingly",
"try",
":",
"Scale",
"(",
"token",
")",
"is_scale",
"=",
"True",
"except",
"ScaleFormatError",
":",
"pass",
"# ... | Asserts a provided string is a valid duration token representation
:param token: duration representation token
:type token: string | [
"Asserts",
"a",
"provided",
"string",
"is",
"a",
"valid",
"duration",
"token",
"representation"
] | 62c176dfa7d36d5c59bf93bdebfdc80ab53757bd | https://github.com/oleiade/durations/blob/62c176dfa7d36d5c59bf93bdebfdc80ab53757bd/durations/parser.py#L10-L31 | train | Asserts a provided string is a valid duration token representation |
oleiade/durations | durations/parser.py | extract_tokens | def extract_tokens(representation, separators=SEPARATOR_CHARACTERS):
"""Extracts durations tokens from a duration representation.
Parses the string representation incrementaly and raises
on first error met.
:param representation: duration representation
:type representation: string
"""
... | python | def extract_tokens(representation, separators=SEPARATOR_CHARACTERS):
"""Extracts durations tokens from a duration representation.
Parses the string representation incrementaly and raises
on first error met.
:param representation: duration representation
:type representation: string
"""
... | [
"def",
"extract_tokens",
"(",
"representation",
",",
"separators",
"=",
"SEPARATOR_CHARACTERS",
")",
":",
"buff",
"=",
"\"\"",
"elements",
"=",
"[",
"]",
"last_index",
"=",
"0",
"last_token",
"=",
"None",
"for",
"index",
",",
"c",
"in",
"enumerate",
"(",
"... | Extracts durations tokens from a duration representation.
Parses the string representation incrementaly and raises
on first error met.
:param representation: duration representation
:type representation: string | [
"Extracts",
"durations",
"tokens",
"from",
"a",
"duration",
"representation",
"."
] | 62c176dfa7d36d5c59bf93bdebfdc80ab53757bd | https://github.com/oleiade/durations/blob/62c176dfa7d36d5c59bf93bdebfdc80ab53757bd/durations/parser.py#L43-L93 | train | Extracts tokens from a duration representation. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.