INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
回复某条站内消息 | 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 = {
... |
Get IP geolocation. | 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... |
Get a link to google maps pointing on this IP s geolocation. | 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 ... |
Get a link to open street map pointing on this IP s geolocation. | 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):
... |
Chart for status codes. | def status_codes_chart():
"""Chart for status codes."""
stats = status_codes_stats()
chart_options = {
'chart': {
'type': 'pie'
},
'title': {
'text': ''
},
'subtitle': {
'text': ''
},
'tooltip': {
'formatt... |
Chart for most visited pages legend. | 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... |
Chart for most visited pages. | 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': '... |
Adds all settings that are part of mod to the global settings object. | 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):
... |
Get urls method. | 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'),
... |
Adds widget attributes to a bound form field. | 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 %}
{... |
Turn any template filter into a blocktag. | 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... |
Returns the thumbnail dimensions depending on the images format. | 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) |
Allows to call any method of any object with parameters. | 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... |
Concatenates the given strings. | 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".
"""
... |
Returns the content type of an object. | 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, ... |
Returns the verbose name of an object s field. | 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... |
Allows to change one of the URL get parameter while keeping all the others. | 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... |
Returns active if the given URL is in the url path otherwise. | 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... |
Returns a range of numbers around the given number. | 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... |
Adds the given value to the total value currently held in key. | 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... |
Tag to render x - tmpl templates with Django template code. | 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... |
Adds the possessive s after a string. | 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) |
This parses the arguments and returns a tuple containing: | 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... |
: 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 callback function wh... | 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... |
Return the URL patterns for the logs views. | 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... |
Get information about an IP. | 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... |
Parses a raw datagram and return the right type of message | 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) !... |
Returns a XOR of all the bytes specified inside of the given list | 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... |
Compose a SCS message | 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])) |
computes the correlation coefficient between each distinct pairing of columns preprocessing note: any rows with missing values ( in either paired column ) are dropped for that pairing categorical columns are replaced with one - hot encoded columns any columns which have only one distinct value ( after dropping missing ... | def get_canonical_correlations(dataframe, column_types):
'''
computes the correlation coefficient between each distinct pairing of columns
preprocessing note:
any rows with missing values (in either paired column) are dropped for that pairing
categorical columns are replaced with one-hot enc... |
Sends an email based on templates for subject and body. | 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... |
Check if URL is part of the current project s URLs. | 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... |
Function generator. | 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:
... |
Save a collection of 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) |
Save a collection of records to the database. Database writes are cached. | 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,
... |
Get the serialized value for a given key. | 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... |
Get the deserialized value for a given key and the serialized version. | 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... |
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. | 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:
... |
Load 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... |
Run a single trial of the simulation | 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... |
A wrapper for run_trial that catches exceptions and returns them. It is meant for async simulations | 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__
... |
Search the ORCID public API | 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 ... |
Yield one date per day from starting date to ending date. | 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... |
Convert a month name ( MMM ) to its number ( 01 - 12 ). | 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 = {
... |
Read and parse ReSpecTh XML file metadata ( file author version etc. ) | 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... |
Read reference info from root of ReSpecTh XML file. | 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')
... |
Read common properties from root of ReSpecTh XML file. | 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... |
Read common properties from root of ReSpecTh XML file. | 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... |
Gets ignition type and target. | 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... |
Parse datapoints with ignition delay from file. | 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... |
Convert ReSpecTh XML file to ChemKED - compliant dictionary. | 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... |
Command - line entry point for converting a ReSpecTh XML file to a ChemKED YAML file. | 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,
... |
Command - line entry point for converting a ChemKED YAML file to a ReSpecTh XML file. | 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,
... |
General function for converting between ReSpecTh and ChemKED files based on extension. | 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... |
Add user details. | def process_exception(self, request, exception):
"""
Add user details.
"""
if request.user and hasattr(request.user, 'email'):
request.META['USER'] = request.user.email |
Send broken link emails for relevant 404 NOT FOUND responses. | 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(... |
Returns True if referring URL is the same domain as current 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)) |
Returns True if the given request * shouldn t * notify the site managers. | 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)... |
Parses a duration string representation | 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... |
Get or create an entry using obtained information from an 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 ... |
Update the 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.
... |
Start a thread to continuously read log files and append lines in DB. | 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.
"""
... |
Construct a ChemKED instance directly from a ReSpecTh file. | 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... |
Validate the parsed YAML file for adherance to the ChemKED format. | 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... |
Get a Pandas DataFrame of the datapoints in this instance. | 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... |
Write new ChemKED YAML file based on object. | 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 ... |
Convert ChemKED record to ReSpecTh XML file. | 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:
... |
Process the uncertainty information from a given quantity and return it | 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 =... |
Get the composition in a string format suitable for input to Cantera. | 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_... |
Get the mole fractions in a string format suitable for input to Cantera. | 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 ... |
Get the mass fractions in a string format suitable for input to Cantera. | 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 ... |
Only runs the method if the lockfile is not acquired. | 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... |
Checks if a string is a email adress or not. | 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... |
Creates a payload with no none values. | 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}
... |
Get historical rates for any day since date. | 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... |
load requirements from a pip requirements file | 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("#")] |
: DEPRECATED: Periodically save the state of the environment and the agents. | 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: {}'.... |
Return a list where the duplicates have been removed. | 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(_))) |
Does the heavy lifting of finding 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')
... |
Returns a list of the format modules found | 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... |
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 | 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... |
Main entry point for a request - response process. | 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 "
... |
Get the 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... |
Get the items. | 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 word(self, word, url='https://api.shanbay.com/bdc/search/'):
"""查询单词"""
params = {
'word': word
}
return self._request(url, params=params).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=data).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['type'] = type
return self._request(url, params=params).json() |
创建例句 | 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 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 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 notes(self, word_id, url='https://api.shanbay.com/bdc/note/'):
"""获取笔记"""
params = {
'vocabulary_id': word_id
}
return self._request(url, params=params).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, 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', data=data).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='delete').json() |
Retrieves a scale representation from it s string representation | 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... |
Returns a JSON response transforming context to make the payload. | 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),
... |
Asserts a provided string is a valid duration token representation | 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)... |
Extracts durations tokens from a duration representation. | 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
"""
... |
Returns a random string based on the provided arguments. | def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789',
repetitions=False):
"""
Returns a random string, based on the provided arguments.
It returns capital letters and numbers by default.
Ambiguous characters are left out, repetitions will be avoided.
... |
Loads and returns a class for a given fully qualified name. | def load_member(fqn):
"""Loads and returns a class for a given fully qualified name."""
modulename, member_name = split_fqn(fqn)
module = __import__(modulename, globals(), locals(), member_name)
return getattr(module, member_name) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.