_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q56700 | grant_symlink_privilege | train | def grant_symlink_privilege(who, machine=''):
"""
Grant the 'create symlink' privilege to who.
Based on http://support.microsoft.com/kb/132958
"""
flags = security.POLICY_CREATE_ACCOUNT | security.POLICY_LOOKUP_NAMES
policy = OpenPolicy(machine, flags)
return policy | python | {
"resource": ""
} |
q56701 | add_tasks_r | train | def add_tasks_r(addon_module, package_module, package_name):
'''Recursively iterate through 'package_module' and add every fabric task
to the 'addon_module' keeping the task hierarchy.
Args:
addon_module(types.ModuleType)
package_module(types.ModuleType)
package_name(str): Required,... | python | {
"resource": ""
} |
q56702 | load_addon | train | def load_addon(username, package_name, _globals):
'''Load an fabsetup addon given by 'package_name' and hook it in the
base task namespace 'username'.
Args:
username(str)
package_name(str)
_globals(dict): the globals() namespace of the fabric script.
Return: None
'''
ad... | python | {
"resource": ""
} |
q56703 | load_pip_addons | train | def load_pip_addons(_globals):
'''Load all known fabsetup addons which are installed as pypi pip-packages.
Args:
_globals(dict): the globals() namespace of the fabric script.
Return: None
'''
for package_name in known_pip_addons:
_, username = package_username(package_name)
... | python | {
"resource": ""
} |
q56704 | find_lib | train | def find_lib(lib):
r"""
Find the DLL for a given library.
Accepts a string or loaded module
>>> print(find_lib('kernel32').lower())
c:\windows\system32\kernel32.dll
"""
if isinstance(lib, str):
lib = getattr(ctypes.windll, lib)
size = 1024
result = ctypes.create_unicode_buffer(size)
library.GetModuleFile... | python | {
"resource": ""
} |
q56705 | HydroShare.getScienceMetadataRDF | train | def getScienceMetadataRDF(self, pid):
""" Get science metadata for a resource in XML+RDF format
:param pid: The HydroShare ID of the resource
:raises: HydroShareNotAuthorized if the user is not authorized to view the metadata.
:raises: HydroShareNotFound if the resource was not found.
... | python | {
"resource": ""
} |
q56706 | HydroShare.getResource | train | def getResource(self, pid, destination=None, unzip=False, wait_for_bag_creation=True):
""" Get a resource in BagIt format
:param pid: The HydroShare ID of the resource
:param destination: String representing the directory to save bag to. Bag will be saved to file named
$(PID).zip in... | python | {
"resource": ""
} |
q56707 | HydroShare.getResourceTypes | train | def getResourceTypes(self):
""" Get the list of resource types supported by the HydroShare server
:return: A set of strings representing the HydroShare resource types
:raises: HydroShareHTTPException to signal an HTTP error
"""
url = "{url_base}/resource/types".format(url_base=... | python | {
"resource": ""
} |
q56708 | HydroShare.createResource | train | def createResource(self, resource_type, title, resource_file=None, resource_filename=None,
abstract=None, keywords=None,
edit_users=None, view_users=None, edit_groups=None, view_groups=None,
metadata=None, extra_metadata=None, progress_callback=None):... | python | {
"resource": ""
} |
q56709 | HydroShare.setAccessRules | train | def setAccessRules(self, pid, public=False):
"""
Set access rules for a resource. Current only allows for setting the public or private setting.
:param pid: The HydroShare ID of the resource
:param public: True if the resource should be made public.
"""
url = "{url_base... | python | {
"resource": ""
} |
q56710 | HydroShare.addResourceFile | train | def addResourceFile(self, pid, resource_file, resource_filename=None, progress_callback=None):
""" Add a new file to an existing resource
:param pid: The HydroShare ID of the resource
:param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string
... | python | {
"resource": ""
} |
q56711 | HydroShare.getResourceFile | train | def getResourceFile(self, pid, filename, destination=None):
""" Get a file within a resource.
:param pid: The HydroShare ID of the resource
:param filename: String representing the name of the resource file to get.
:param destination: String representing the directory to save the resour... | python | {
"resource": ""
} |
q56712 | HydroShare.deleteResourceFile | train | def deleteResourceFile(self, pid, filename):
"""
Delete a resource file
:param pid: The HydroShare ID of the resource
:param filename: String representing the name of the resource file to delete
:return: Dictionary containing 'resource_id' the ID of the resource from which the ... | python | {
"resource": ""
} |
q56713 | HydroShare.getResourceFileList | train | def getResourceFileList(self, pid):
""" Get a listing of files within a resource.
:param pid: The HydroShare ID of the resource whose resource files are to be listed.
:raises: HydroShareArgumentException if any parameters are invalid.
:raises: HydroShareNotAuthorized if user is not aut... | python | {
"resource": ""
} |
q56714 | get_ssm_parameter | train | def get_ssm_parameter(parameter_name):
'''
Get the decrypted value of an SSM parameter
Args:
parameter_name - the name of the stored parameter of interest
Return:
Value if allowed and present else None
'''
try:
response = boto3.client('ssm').get_parameters(
... | python | {
"resource": ""
} |
q56715 | powerline | train | def powerline():
'''Install and set up powerline for vim, bash, tmux, and i3.
It uses pip (python2) and the most up to date powerline version (trunk) from
the github repository.
More infos:
https://github.com/powerline/powerline
https://powerline.readthedocs.io/en/latest/installation.html
... | python | {
"resource": ""
} |
q56716 | ifancestor | train | def ifancestor(parser, token):
"""
Returns the contents of the tag if the provided path consitutes the
base of the current pages path.
There are two ways to provide arguments to this tag. Firstly one may
provide a single argument that starts with a forward slash. e.g.
{% ifancestor '/path/... | python | {
"resource": ""
} |
q56717 | exit_statistics | train | def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation):
"""
Print ping exit statistics
"""
end_time = datetime.datetime.now()
duration = end_time - start_time
duration_sec = float(duration.seconds * 1000)
duration_ms = float(duration.mi... | python | {
"resource": ""
} |
q56718 | Notifier._filtered_walk | train | def _filtered_walk(path, file_filter):
"""
static method that calls os.walk, but filters out
anything that doesn't match the filter
"""
for root, dirs, files in os.walk(path):
log.debug('looking in %s', root)
log.debug('files is %s', files)
file_filter.set_root(root)
files = filter(file_filter, fi... | python | {
"resource": ""
} |
q56719 | cache_control_expires | train | def cache_control_expires(num_hours):
"""
Set the appropriate Cache-Control and Expires headers for the given
number of hours.
"""
num_seconds = int(num_hours * 60 * 60)
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
response = func(request, *... | python | {
"resource": ""
} |
q56720 | CloudStackUtility.upsert | train | def upsert(self):
"""
The main event of the utility. Create or update a Cloud Formation
stack. Injecting properties where needed
Args:
None
Returns:
True if the stack create/update is started successfully else
False if the start goes off in t... | python | {
"resource": ""
} |
q56721 | CloudStackUtility.list | train | def list(self):
"""
List the existing stacks in the indicated region
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems.
"""
self._initialize_list()
int... | python | {
"resource": ""
} |
q56722 | CloudStackUtility.smash | train | def smash(self):
"""
Smash the given stack
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems.
"""
self._initialize_smash()
try:
stack_name ... | python | {
"resource": ""
} |
q56723 | CloudStackUtility._init_boto3_clients | train | def _init_boto3_clients(self):
"""
The utililty requires boto3 clients to Cloud Formation and S3. Here is
where we make them.
Args:
None
Returns:
Good or Bad; True or False
"""
try:
profile = self._config.get('environment', {}... | python | {
"resource": ""
} |
q56724 | CloudStackUtility._get_ssm_parameter | train | def _get_ssm_parameter(self, p):
"""
Get parameters from Simple Systems Manager
Args:
p - a parameter name
Returns:
a value, decrypted if needed, if successful or None if things go
sideways.
"""
try:
response = self._ssm.g... | python | {
"resource": ""
} |
q56725 | CloudStackUtility._fill_parameters | train | def _fill_parameters(self):
"""
Fill in the _parameters dict from the properties file.
Args:
None
Returns:
True
Todo:
Figure out what could go wrong and at least acknowledge the the
fact that Murphy was an optimist.
"""
... | python | {
"resource": ""
} |
q56726 | CloudStackUtility._read_tags | train | def _read_tags(self):
"""
Fill in the _tags dict from the tags file.
Args:
None
Returns:
True
Todo:
Figure what could go wrong and at least acknowledge the
the fact that Murphy was an optimist.
"""
tags = self._co... | python | {
"resource": ""
} |
q56727 | CloudStackUtility._set_update | train | def _set_update(self):
"""
Determine if we are creating a new stack or updating and existing one.
The update member is set as you would expect at the end of this query.
Args:
None
Returns:
True
"""
try:
self._updateStack = Fal... | python | {
"resource": ""
} |
q56728 | CloudStackUtility._craft_s3_keys | train | def _craft_s3_keys(self):
"""
We are putting stuff into S3, were supplied the bucket. Here we
craft the key of the elements we are putting up there in the
internet clouds.
Args:
None
Returns:
a tuple of teplate file key and property file key
... | python | {
"resource": ""
} |
q56729 | CloudStackUtility.poll_stack | train | def poll_stack(self):
"""
Spin in a loop while the Cloud Formation process either fails or succeeds
Args:
None
Returns:
Good or bad; True or False
"""
logging.info('polling stack status, POLL_INTERVAL={}'.format(POLL_INTERVAL))
time.sleep... | python | {
"resource": ""
} |
q56730 | setup_desktop | train | def setup_desktop():
'''Run setup tasks to set up a nicely configured desktop pc.
This is highly biased on my personal preference.
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your own needs. More info: README.md
'''
run('sudo apt-get u... | python | {
"resource": ""
} |
q56731 | setup_webserver | train | def setup_webserver():
'''Run setup tasks to set up a nicely configured webserver.
Features:
* owncloud service
* fdroid repository
* certificates via letsencrypt
* and more
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your o... | python | {
"resource": ""
} |
q56732 | start_recv | train | def start_recv(sockfile=None):
'''Open a server on Unix Domain Socket'''
if sockfile is not None:
SOCKFILE = sockfile
else:
# default sockfile
SOCKFILE = "/tmp/snort_alert"
if os.path.exists(SOCKFILE):
os.unlink(SOCKFILE)
unsock = socket.socket(socket.AF_UNIX, socke... | python | {
"resource": ""
} |
q56733 | dump | train | def dump(obj, fp=None, indent=None, sort_keys=False, **kw):
"""
Dump object to a file like object or string.
:param obj:
:param fp: Open file like object
:param int indent: Indent size, default 2
:param bool sort_keys: Optionally sort dictionary keys.
:return: Yaml serialized data.
"""
... | python | {
"resource": ""
} |
q56734 | dumps | train | def dumps(obj, indent=None, default=None, sort_keys=False, **kw):
"""Dump string."""
return YAMLEncoder(indent=indent, default=default, sort_keys=sort_keys, **kw).encode(obj) | python | {
"resource": ""
} |
q56735 | load | train | def load(s, **kwargs):
"""Load yaml file"""
try:
return loads(s, **kwargs)
except TypeError:
return loads(s.read(), **kwargs) | python | {
"resource": ""
} |
q56736 | MIB_IPADDRROW.address | train | def address(self):
"The address in big-endian"
_ = struct.pack('L', self.address_num)
return struct.unpack('!L', _)[0] | python | {
"resource": ""
} |
q56737 | validate_currency | train | def validate_currency(*currencies):
""" some validation checks before doing anything """
validated_currency = []
if not currencies:
raise CurrencyException('My function need something to run, duh')
for currency in currencies:
currency = currency.upper()
if not isinstance(currency, str):
raise TypeError('Cu... | python | {
"resource": ""
} |
q56738 | validate_price | train | def validate_price(price):
""" validation checks for price argument """
if isinstance(price, str):
try:
price = int(price)
except ValueError: # fallback if convert to int failed
price = float(price)
if not isinstance(price, (int, float)):
raise TypeError('Price should be a number: ' + repr(price))
retur... | python | {
"resource": ""
} |
q56739 | name | train | def name(currency, *, plural=False):
""" return name of currency """
currency = validate_currency(currency)
if plural:
return _currencies[currency]['name_plural']
return _currencies[currency]['name'] | python | {
"resource": ""
} |
q56740 | symbol | train | def symbol(currency, *, native=True):
""" return symbol of currency """
currency = validate_currency(currency)
if native:
return _currencies[currency]['symbol_native']
return _currencies[currency]['symbol'] | python | {
"resource": ""
} |
q56741 | rounding | train | def rounding(price, currency):
""" rounding currency value based on its max decimal digits """
currency = validate_currency(currency)
price = validate_price(price)
if decimals(currency) == 0:
return round(int(price), decimals(currency))
return round(price, decimals(currency)) | python | {
"resource": ""
} |
q56742 | check_update | train | def check_update(from_currency, to_currency):
""" check if last update is over 30 mins ago. if so return True to update, else False """
if from_currency not in ccache: # if currency never get converted before
ccache[from_currency] = {}
if ccache[from_currency].get(to_currency) is None:
ccache[from_currency][to_c... | python | {
"resource": ""
} |
q56743 | update_cache | train | def update_cache(from_currency, to_currency):
""" update from_currency to_currency pair in cache if
last update for that pair is over 30 minutes ago by request API info """
if check_update(from_currency, to_currency) is True:
ccache[from_currency][to_currency]['value'] = convert_using_api(from_currency, to_currenc... | python | {
"resource": ""
} |
q56744 | convert_using_api | train | def convert_using_api(from_currency, to_currency):
""" convert from from_currency to to_currency by requesting API """
convert_str = from_currency + '_' + to_currency
options = {'compact': 'ultra', 'q': convert_str}
api_url = 'https://free.currencyconverterapi.com/api/v5/convert'
result = requests.get(api_url, par... | python | {
"resource": ""
} |
q56745 | convert | train | 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 | {
"resource": ""
} |
q56746 | WaitableTimer.wait_for_signal | train | 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 | {
"resource": ""
} |
q56747 | ip_geoloc | train | 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 | {
"resource": ""
} |
q56748 | google_maps_geoloc_link | train | 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 | {
"resource": ""
} |
q56749 | open_street_map_geoloc_link | train | 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 | {
"resource": ""
} |
q56750 | status_codes_chart | train | def status_codes_chart():
"""Chart for status codes."""
stats = status_codes_stats()
chart_options = {
'chart': {
'type': 'pie'
},
'title': {
'text': ''
},
'subtitle': {
'text': ''
},
'tooltip': {
'formatt... | python | {
"resource": ""
} |
q56751 | most_visited_pages_legend_chart | train | 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 | {
"resource": ""
} |
q56752 | add_settings | train | 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 | {
"resource": ""
} |
q56753 | DashboardSite.get_urls | train | 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 | {
"resource": ""
} |
q56754 | add_form_widget_attr | train | 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 | {
"resource": ""
} |
q56755 | block_anyfilter | train | 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 | {
"resource": ""
} |
q56756 | calculate_dimensions | train | 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 | {
"resource": ""
} |
q56757 | call | train | 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 | {
"resource": ""
} |
q56758 | concatenate | train | 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 | {
"resource": ""
} |
q56759 | get_content_type | train | 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 | {
"resource": ""
} |
q56760 | get_verbose | train | 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 | {
"resource": ""
} |
q56761 | get_query_params | train | 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 | {
"resource": ""
} |
q56762 | navactive | train | 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 | {
"resource": ""
} |
q56763 | get_range_around | train | 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 | {
"resource": ""
} |
q56764 | sum | train | 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 | {
"resource": ""
} |
q56765 | verbatim | train | 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 | {
"resource": ""
} |
q56766 | append_s | train | 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 | {
"resource": ""
} |
q56767 | logs_urlpatterns | train | 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 | {
"resource": ""
} |
q56768 | IpInfoHandler._get | train | 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 | {
"resource": ""
} |
q56769 | parse | train | 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 | {
"resource": ""
} |
q56770 | checksum_bytes | train | 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 | {
"resource": ""
} |
q56771 | compose_telegram | train | 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 | {
"resource": ""
} |
q56772 | send_email | train | 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 | {
"resource": ""
} |
q56773 | url_is_project | train | 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 | {
"resource": ""
} |
q56774 | url_is | train | 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 | {
"resource": ""
} |
q56775 | History.save_records | train | 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 | {
"resource": ""
} |
q56776 | History.save_record | train | 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 | {
"resource": ""
} |
q56777 | History.convert | train | 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 | {
"resource": ""
} |
q56778 | History.recover | train | 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 | {
"resource": ""
} |
q56779 | History.flush_cache | train | 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 | {
"resource": ""
} |
q56780 | records | train | 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 | {
"resource": ""
} |
q56781 | Simulation.run_trial_exceptions | train | 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 | {
"resource": ""
} |
q56782 | search_orcid | train | 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 | {
"resource": ""
} |
q56783 | daterange | train | 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 | {
"resource": ""
} |
q56784 | get_reference | train | 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 | {
"resource": ""
} |
q56785 | get_ignition_type | train | 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 | {
"resource": ""
} |
q56786 | ReSpecTh_to_ChemKED | train | 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 | {
"resource": ""
} |
q56787 | respth2ck | train | 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 | {
"resource": ""
} |
q56788 | ck2respth | train | 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 | {
"resource": ""
} |
q56789 | main | train | 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 | {
"resource": ""
} |
q56790 | ErrorMiddleware.process_exception | train | def process_exception(self, request, exception):
"""
Add user details.
"""
if request.user and hasattr(request.user, 'email'):
request.META['USER'] = request.user.email | python | {
"resource": ""
} |
q56791 | CustomBrokenLinkEmailsMiddleware.process_response | train | 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 | {
"resource": ""
} |
q56792 | CustomBrokenLinkEmailsMiddleware.is_internal_request | train | 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 | {
"resource": ""
} |
q56793 | Duration.parse | train | 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 | {
"resource": ""
} |
q56794 | IPInfo.get_or_create_from_ip | train | 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 | {
"resource": ""
} |
q56795 | RequestLog.update_ip_info | train | 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 | {
"resource": ""
} |
q56796 | RequestLog.start_daemon | train | 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 | {
"resource": ""
} |
q56797 | ChemKED.from_respecth | train | 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 | {
"resource": ""
} |
q56798 | ChemKED.validate_yaml | train | 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 | {
"resource": ""
} |
q56799 | ChemKED.write_file | train | 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 | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.