_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q39800 | Elastic._get_connection_from_url | train | def _get_connection_from_url(self, url, timeout, **kwargs):
"""Returns a connection object given a string url"""
url = self._decode_url(url, "")
if url.scheme == 'http' or url.scheme == 'https':
return HttpConnection(url.geturl(), timeout=timeout, **kwargs)
else:
... | python | {
"resource": ""
} |
q39801 | userToJson | train | def userToJson(user):
"""Returns a serializable User dict
:param user: User to get info for
:type user: User
:returns: dict
"""
obj = {
'id': user.id,
'username': user.username,
'name': user.get_full_name(),
'email': user.email,
}
return obj | python | {
"resource": ""
} |
q39802 | commentToJson | train | def commentToJson(comment):
"""Returns a serializable Comment dict
:param comment: Comment to get info for
:type comment: Comment
:returns: dict
"""
obj = {
'id': comment.id,
'comment': comment.comment,
'user': userToJson(comment.user),
'date': comment.submit_dat... | python | {
"resource": ""
} |
q39803 | getPutData | train | def getPutData(request):
"""Adds raw post to the PUT and DELETE querydicts on the request so they behave like post
:param request: Request object to add PUT/DELETE to
:type request: Request
"""
dataDict = {}
data = request.body
for n in urlparse.parse_qsl(data):
dataDict[n[0]] = n[... | python | {
"resource": ""
} |
q39804 | getHashForFile | train | def getHashForFile(f):
"""Returns a hash value for a file
:param f: File to hash
:type f: str
:returns: str
"""
hashVal = hashlib.sha1()
while True:
r = f.read(1024)
if not r:
break
hashVal.update(r)
f.seek(0)
return hashVal.hexdigest() | python | {
"resource": ""
} |
q39805 | uniqueID | train | def uniqueID(size=6, chars=string.ascii_uppercase + string.digits):
"""A quick and dirty way to get a unique string"""
return ''.join(random.choice(chars) for x in xrange(size)) | python | {
"resource": ""
} |
q39806 | getObjectsFromGuids | train | def getObjectsFromGuids(guids):
"""Gets the model objects based on a guid list
:param guids: Guids to get objects for
:type guids: list
:returns: list
"""
guids = guids[:]
img = list(Image.objects.filter(guid__in=guids))
vid = list(Video.objects.filter(guid__in=guids))
objects = img... | python | {
"resource": ""
} |
q39807 | getClientIP | train | def getClientIP(request):
"""Returns the best IP address found from the request"""
forwardedfor = request.META.get('HTTP_X_FORWARDED_FOR')
if forwardedfor:
ip = forwardedfor.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip | python | {
"resource": ""
} |
q39808 | __discoverPlugins | train | def __discoverPlugins():
""" Discover the plugin classes contained in Python files, given a
list of directory names to scan. Return a list of plugin classes.
"""
for app in settings.INSTALLED_APPS:
if not app.startswith('django'):
module = __import__(app)
moduledir = ... | python | {
"resource": ""
} |
q39809 | Result.append | train | def append(self, val):
"""Appends the object to the end of the values list. Will also set the value to the first
item in the values list
:param val: Object to append
:type val: primitive
"""
self.values.append(val)
self.value = self.values[0] | python | {
"resource": ""
} |
q39810 | Result.asDict | train | def asDict(self):
"""Returns a serializable object"""
return {
'isError': self.isError,
'message': self.message,
'values': self.values,
'value': self.value,
} | python | {
"resource": ""
} |
q39811 | ServerMixin.auth | train | def auth(self, password):
"""Request for authentication in a password-protected Redis server.
Redis can be instructed to require a password before allowing clients
to execute commands. This is done using the ``requirepass`` directive
in the configuration file.
If the password do... | python | {
"resource": ""
} |
q39812 | ServerMixin.info | train | def info(self, section=None):
"""The INFO command returns information and statistics about the server
in a format that is simple to parse by computers and easy to read by
humans.
The optional parameter can be used to select a specific section of
information:
- serve... | python | {
"resource": ""
} |
q39813 | ServerMixin.select | train | def select(self, index=0):
"""Select the DB with having the specified zero-based numeric index.
New connections always use DB ``0``.
:param int index: The database to select
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError`
:raises: :exc:`~tredis.exceptions.Inva... | python | {
"resource": ""
} |
q39814 | ServerMixin.time | train | def time(self):
"""Retrieve the current time from the redis server.
:rtype: float
:raises: :exc:`~tredis.exceptions.RedisError`
"""
def format_response(value):
"""Format a TIME response into a datetime.datetime
:param list value: TIME response is a lis... | python | {
"resource": ""
} |
q39815 | VodTVP.get_show_name | train | def get_show_name(self):
"""
Get video show name from the website. It's located in the div with 'data-hover'
attribute under the 'title' key.
Returns:
str: Video show name.
"""
div = self.soup.find('div', attrs={'data-hover': True})
data = json.loads... | python | {
"resource": ""
} |
q39816 | BaseClient.ping | train | def ping(self, callback=None, **kwargs):
"""
Ping request to check status of elasticsearch host
"""
self.client.fetch(
self.mk_req('', method='HEAD', **kwargs),
callback = callback
) | python | {
"resource": ""
} |
q39817 | BaseClient.info | train | def info(self, callback=None, **kwargs):
"""
Get the basic info from the current cluster.
"""
self.client.fetch(
self.mk_req('', method='GET', **kwargs),
callback = callback
) | python | {
"resource": ""
} |
q39818 | ExceptionReporter.get_traceback_data | train | def get_traceback_data(self):
"""Return a dictionary containing traceback information."""
default_template_engine = None
if default_template_engine is None:
template_loaders = []
frames = self.get_traceback_frames()
for i, frame in enumerate(frames):
if ... | python | {
"resource": ""
} |
q39819 | ExceptionReporter.get_traceback_html | train | def get_traceback_html(self, **kwargs):
"Return HTML version of debug 500 HTTP error page."
t = Template(TECHNICAL_500_TEMPLATE)
c = self.get_traceback_data()
c['kwargs'] = kwargs
return t.render(Context(c)) | python | {
"resource": ""
} |
q39820 | ExceptionReporter.get_traceback_frames | train | def get_traceback_frames(self):
"""Returns the traceback frames as a list"""
frames = []
tb = self.tb
while tb is not None:
# Support for __traceback_hide__ which is used by a few libraries
# to hide internal frames.
if tb.tb_frame.f_locals.get('__trac... | python | {
"resource": ""
} |
q39821 | ExceptionReporter.format_exception | train | def format_exception(self):
"""
Return the same data as from traceback.format_exception.
"""
import traceback
frames = self.get_traceback_frames()
tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames]
list = ['Traceback (most recent... | python | {
"resource": ""
} |
q39822 | KeysMixin.expire | train | def expire(self, key, timeout):
"""Set a timeout on key. After the timeout has expired, the key will
automatically be deleted. A key with an associated timeout is often
said to be volatile in Redis terminology.
The timeout is cleared only when the key is removed using the
:meth:... | python | {
"resource": ""
} |
q39823 | KeysMixin.migrate | train | def migrate(self,
host,
port,
key,
destination_db,
timeout,
copy=False,
replace=False):
"""Atomically transfer a key from a source Redis instance to a
destination Redis instance. On success th... | python | {
"resource": ""
} |
q39824 | KeysMixin.sort | train | def sort(self,
key,
by=None,
external=None,
offset=0,
limit=None,
order=None,
alpha=False,
store_as=None):
"""Returns or stores the elements contained in the list, set or sorted
set at key. By default... | python | {
"resource": ""
} |
q39825 | KeysMixin.wait | train | def wait(self, num_slaves, timeout=0):
"""his command blocks the current client until all the previous write
commands are successfully transferred and acknowledged by at least the
specified number of slaves. If the timeout, specified in milliseconds,
is reached, the command returns even ... | python | {
"resource": ""
} |
q39826 | enable_thread_profiling | train | def enable_thread_profiling(profile_dir, exception_callback=None):
"""
Monkey-patch the threading.Thread class with our own ProfiledThread. Any subsequent imports of threading.Thread
will reference ProfiledThread instead.
"""
global profiled_thread_enabled, Thread, Process
if os.path.isdir(profi... | python | {
"resource": ""
} |
q39827 | enable_thread_logging | train | def enable_thread_logging(exception_callback=None):
"""
Monkey-patch the threading.Thread class with our own LoggedThread. Any subsequent imports of threading.Thread
will reference LoggedThread instead.
"""
global logged_thread_enabled, Thread
LoggedThread.exception_callback = exception_callback... | python | {
"resource": ""
} |
q39828 | AseParser.parse_from_calc | train | def parse_from_calc(self):
"""
Parses the datafolder, stores results.
This parser for this simple code does simply store in the DB a node
representing the file of forces in real space
"""
from aiida.common.exceptions import InvalidOperation
from aiida.common impor... | python | {
"resource": ""
} |
q39829 | HashesMixin.hset | train | def hset(self, key, field, value):
"""Sets `field` in the hash stored at `key` to `value`.
If `key` does not exist, a new key holding a hash is created. If
`field` already exists in the hash, it is overwritten.
.. note::
**Time complexity**: always ``O(1)``
:param ... | python | {
"resource": ""
} |
q39830 | HashesMixin.hgetall | train | def hgetall(self, key):
"""
Returns all fields and values of the has stored at `key`.
The underlying redis `HGETALL`_ command returns an array of
pairs. This method converts that to a Python :class:`dict`.
It will return an empty :class:`dict` when the key is not
found.... | python | {
"resource": ""
} |
q39831 | HashesMixin.hmset | train | def hmset(self, key, value_dict):
"""
Sets fields to values as in `value_dict` in the hash stored at `key`.
Sets the specified fields to their respective values in the hash
stored at `key`. This command overwrites any specified fields
already existing in the hash. If `key` doe... | python | {
"resource": ""
} |
q39832 | HashesMixin.hmget | train | def hmget(self, key, *fields):
"""
Returns the values associated with the specified `fields` in a hash.
For every ``field`` that does not exist in the hash, :data:`None`
is returned. Because a non-existing keys are treated as empty
hashes, calling :meth:`hmget` against a non-ex... | python | {
"resource": ""
} |
q39833 | HashesMixin.hdel | train | def hdel(self, key, *fields):
"""
Remove the specified fields from the hash stored at `key`.
Specified fields that do not exist within this hash are ignored.
If `key` does not exist, it is treated as an empty hash and this
command returns zero.
:param key: The key of th... | python | {
"resource": ""
} |
q39834 | HashesMixin.hsetnx | train | def hsetnx(self, key, field, value):
"""
Sets `field` in the hash stored at `key` only if it does not exist.
Sets `field` in the hash stored at `key` only if `field` does not
yet exist. If `key` does not exist, a new key holding a hash is
created. If `field` already exists, th... | python | {
"resource": ""
} |
q39835 | AuthProgs.raise_and_log_error | train | def raise_and_log_error(self, error, message):
"""Raise error, including message and original traceback.
error: the error to raise
message: the user-facing error message
"""
self.log('raising %s, traceback %s\n' %
(error, traceback.format_exc()))
raise e... | python | {
"resource": ""
} |
q39836 | AuthProgs.get_client_ip | train | def get_client_ip(self):
"""Return the client IP from the environment."""
if self.client_ip:
return self.client_ip
try:
client = os.environ.get('SSH_CONNECTION',
os.environ.get('SSH_CLIENT'))
self.client_ip = client.split(... | python | {
"resource": ""
} |
q39837 | AuthProgs.check_keyname | train | def check_keyname(self, rule):
"""If a key name is specified, verify it is permitted."""
keynames = rule.get('keynames')
if not keynames:
self.logdebug('no keynames requirement.\n')
return True
if not isinstance(keynames, list):
keynames = [keynames]
... | python | {
"resource": ""
} |
q39838 | AuthProgs.check_client_ip | train | def check_client_ip(self, rule):
"""If a client IP is specified, verify it is permitted."""
if not rule.get('from'):
self.logdebug('no "from" requirement.\n')
return True
allow_from = rule.get('from')
if not isinstance(allow_from, list):
allow_from =... | python | {
"resource": ""
} |
q39839 | AuthProgs.get_merged_config | train | def get_merged_config(self):
"""Get merged config file.
Returns an open StringIO containing the
merged config file.
"""
if self.yamldocs:
return
loadfiles = []
if self.configfile:
loadfiles.append(self.configfile)
if self... | python | {
"resource": ""
} |
q39840 | AuthProgs.load | train | def load(self):
"""Load our config, log and raise on error."""
try:
merged_configfile = self.get_merged_config()
self.yamldocs = yaml.load(merged_configfile, Loader=Loader)
# Strip out the top level 'None's we get from concatenation.
# Functionally not re... | python | {
"resource": ""
} |
q39841 | AuthProgs.dump_config | train | def dump_config(self):
"""Pretty print the configuration dict to stdout."""
yaml_content = self.get_merged_config()
print('YAML Configuration\n%s\n' % yaml_content.read())
try:
self.load()
print('Python Configuration\n%s\n' % pretty(self.yamldocs))
except ... | python | {
"resource": ""
} |
q39842 | AuthProgs.install_key_data | train | def install_key_data(self, keydata, target):
"""Install the key data into the open file."""
target.seek(0)
contents = target.read()
ssh_opts = 'no-port-forwarding'
if keydata in contents:
raise InstallError('key data already in file - refusing '
... | python | {
"resource": ""
} |
q39843 | AuthProgs.install_key | train | def install_key(self, keyfile, authorized_keys):
"""Install a key into the authorized_keys file."""
# Make the directory containing the authorized_keys
# file, if it doesn't exist. (Typically ~/.ssh).
# Ignore errors; we'll fail shortly if we can't
# create the authkeys file.
... | python | {
"resource": ""
} |
q39844 | AuthProgs.find_match_scp | train | def find_match_scp(self, rule): # pylint: disable-msg=R0911,R0912
"""Handle scp commands."""
orig_list = []
orig_list.extend(self.original_command_list)
binary = orig_list.pop(0)
allowed_binaries = ['scp', '/usr/bin/scp']
if binary not in allowed_binaries:
s... | python | {
"resource": ""
} |
q39845 | AuthProgs.find_match | train | def find_match(self):
"""Load the config and find a matching rule.
returns the results of find_match_command, a dict of
the command and (in the future) other metadata.
"""
self.load()
for yamldoc in self.yamldocs:
self.logdebug('\nchecking rule """%s"""\n' %... | python | {
"resource": ""
} |
q39846 | AuthProgs.exec_command | train | def exec_command(self):
"""Glean the command to run and exec.
On problems, sys.exit.
This method should *never* return.
"""
if not self.original_command_string:
raise SSHEnvironmentError('no SSH command found; '
'interactive shel... | python | {
"resource": ""
} |
q39847 | _py2_crc16 | train | def _py2_crc16(value):
"""Calculate the CRC for the value in Python 2
:param str value: The value to return for the CRC Checksum
:rtype: int
"""
crc = 0
for byte in value:
crc = ((crc << 8) & 0xffff) ^ \
_CRC16_LOOKUP[((crc >> 8) ^ ord(byte)) & 0xff]
return crc | python | {
"resource": ""
} |
q39848 | _py3_crc16 | train | def _py3_crc16(value):
"""Calculate the CRC for the value in Python 3
:param bytes value: The value to return for the CRC Checksum
:rtype: int
"""
crc = 0
for byte in value:
crc = ((crc << 8) & 0xffff) ^ _CRC16_LOOKUP[((crc >> 8) ^ byte) & 0xff]
return crc | python | {
"resource": ""
} |
q39849 | Extractor.validate_url | train | def validate_url(cls, url: str) -> Optional[Match[str]]:
"""Check if the Extractor can handle the given url."""
match = re.match(cls._VALID_URL, url)
return match | python | {
"resource": ""
} |
q39850 | Extractor.get_info | train | def get_info(self) -> dict:
"""Get information about the videos from YoutubeDL package."""
with suppress_stdout():
with youtube_dl.YoutubeDL() as ydl:
info_dict = ydl.extract_info(self.url, download=False)
return info_dict | python | {
"resource": ""
} |
q39851 | Extractor.update_entries | train | def update_entries(entries: Entries, data: dict) -> None:
"""Update each entry in the list with some data."""
# TODO: Is mutating the list okay, making copies is such a pain in the ass
for entry in entries:
entry.update(data) | python | {
"resource": ""
} |
q39852 | get_extra_context | train | def get_extra_context(site, ctx):
'Returns extra data useful to the templates.'
# XXX: clean this up from obsolete stuff
ctx['site'] = site
ctx['feeds'] = feeds = site.active_feeds.order_by('name')
def get_mod_chk(k):
mod, chk = (
(max(vals) if vals else None) for vals in (
filter(None, it.imap(op.attrge... | python | {
"resource": ""
} |
q39853 | get_posts_tags | train | def get_posts_tags(subscribers, object_list, feed, tag_name):
'''Adds a qtags property in every post object in a page.
Use "qtags" instead of "tags" in templates to avoid unnecesary DB hits.'''
tagd = dict()
user_obj = None
tag_obj = None
tags = models.Tag.objects.extra(
select=dict(post_id='{0}.{1}'.format(
... | python | {
"resource": ""
} |
q39854 | get_page | train | def get_page(site, page=1, **criterias):
'Returns a paginator object and a requested page from it.'
global _since_formats_vary
if 'since' in criterias:
since = criterias['since']
if since in _since_offsets:
since = datetime.today() - timedelta(_since_offsets[since])
else:
if _since_formats_vary:
for... | python | {
"resource": ""
} |
q39855 | StringsMixin.bitpos | train | def bitpos(self, key, bit, start=None, end=None):
"""Return the position of the first bit set to ``1`` or ``0`` in a
string.
The position is returned, thinking of the string as an array of bits
from left to right, where the first byte's most significant bit is at
position 0, the... | python | {
"resource": ""
} |
q39856 | StringsMixin.decrby | train | def decrby(self, key, decrement):
"""Decrements the number stored at key by decrement. If the key does
not exist, it is set to 0 before performing the operation. An error
is returned if the key contains a value of the wrong type or contains
a string that can not be represented as integer... | python | {
"resource": ""
} |
q39857 | StringsMixin.incrby | train | def incrby(self, key, increment):
"""Increments the number stored at key by increment. If the key does
not exist, it is set to 0 before performing the operation. An error is
returned if the key contains a value of the wrong type or contains a
string that can not be represented as integer... | python | {
"resource": ""
} |
q39858 | StringsMixin.setex | train | def setex(self, key, seconds, value):
"""Set key to hold the string value and set key to timeout after a
given number of seconds.
:meth:`~tredis.RedisClient.setex` is atomic, and can be reproduced by
using :meth:`~tredis.RedisClient.set` and
:meth:`~tredis.RedisClient.expire` in... | python | {
"resource": ""
} |
q39859 | StringsMixin.setrange | train | def setrange(self, key, offset, value):
"""Overwrites part of the string stored at key, starting at the
specified offset, for the entire length of value. If the offset is
larger than the current length of the string at key, the string is
padded with zero-bytes to make offset fit. Non-exi... | python | {
"resource": ""
} |
q39860 | Extension.negotiate_safe | train | def negotiate_safe(self, name, params):
"""
`name` and `params` are sent in the HTTP request by the client. Check
if the extension name is supported by this extension, and validate the
parameters. Returns a dict with accepted parameters, or None if not
accepted.
"""
... | python | {
"resource": ""
} |
q39861 | get | train | def get(request):
"""Gets the currently logged in users preferences
:returns: json
"""
res = Result()
obj, created = UserPref.objects.get_or_create(user=request.user, defaults={'data': json.dumps(DefaultPrefs.copy())})
data = obj.json()
data['subscriptions'] = [_.json() for _ in GallerySub... | python | {
"resource": ""
} |
q39862 | post | train | def post(request):
"""Sets a key to a value on the currently logged in users preferences
:param key: Key to set
:type key: str
:param val: Value to set
:type val: primitive
:returns: json
"""
data = request.POST or json.loads(request.body)['body']
key = data.get('key', None)
val... | python | {
"resource": ""
} |
q39863 | get_modified_date | train | def get_modified_date(parsed, raw):
'Return best possible guess to post modification timestamp.'
if parsed: return feedparser_ts(parsed)
if not raw: return None
# Parse weird timestamps that feedparser can't handle, e.g.: July 30, 2013
ts, val = None, raw.replace('_', ' ')
if not ts:
# coreutils' "date" parses... | python | {
"resource": ""
} |
q39864 | query_realtime_routine | train | def query_realtime_routine(bus_name, cur_station=None):
'''Get real time routine.
TODO support fuzzy matching.
:param bus_name: the routine name of the bus.
:param cur_station: current station, deaults to starting station
of the routine.
'''
routines = query_routines(bu... | python | {
"resource": ""
} |
q39865 | getRoot | train | def getRoot():
"""Convenience to return the media root with forward slashes"""
root = settings.MEDIA_ROOT.replace('\\', '/')
if not root.endswith('/'):
root += '/'
return path.Path(root) | python | {
"resource": ""
} |
q39866 | emailUser | train | def emailUser(video, error=None):
"""Emails the author of the video that it has finished processing"""
html = render_to_string('frog/video_email.html', {
'user': video.author,
'error': error,
'video': video,
'SITE_URL': FROG_SITE_URL,
})
subject, from_email, to = 'Video P... | python | {
"resource": ""
} |
q39867 | SortedSetsMixin.zrange | train | def zrange(self, key, start=0, stop=-1, with_scores=False):
"""Returns the specified range of elements in the sorted set stored at
key. The elements are considered to be ordered from the lowest to the
highest score. Lexicographical order is used for elements with equal
score.
Se... | python | {
"resource": ""
} |
q39868 | SortedSetsMixin.zrem | train | def zrem(self, key, *members):
"""Removes the specified members from the sorted set stored at key.
Non existing members are ignored.
An error is returned when key exists and does not hold a sorted set.
.. note::
**Time complexity**: ``O(M*log(N))`` with ``N`` being the num... | python | {
"resource": ""
} |
q39869 | SortedSetsMixin.zremrangebyscore | train | def zremrangebyscore(self, key, min_score, max_score):
"""Removes all elements in the sorted set stored at key with a score
between min and max.
Intervals are described in :meth:`~tredis.RedisClient.zrangebyscore`.
Returns the number of elements removed.
.. note::
... | python | {
"resource": ""
} |
q39870 | SortedSetsMixin.zrevrange | train | def zrevrange(self, key, start=0, stop=-1, with_scores=False):
"""Returns the specified range of elements in the sorted set stored at
key. The elements are considered to be ordered from the highest to the
lowest score. Descending lexicographical order is used for elements
with equal scor... | python | {
"resource": ""
} |
q39871 | getkey | train | def getkey(stype, site_id=None, key=None):
'Returns the cache key depending on its type.'
base = '{0}.feedjack'.format(settings.CACHE_MIDDLEWARE_KEY_PREFIX)
if stype == T_HOST: return '{0}.hostcache'.format(base)
elif stype == T_ITEM: return '{0}.{1}.item.{2}'.format(base, site_id, str2md5(key))
elif stype == T_ME... | python | {
"resource": ""
} |
q39872 | feed_interval_get | train | def feed_interval_get(feed_id, parameters):
'Get adaptive interval between checks for a feed.'
val = cache.get(getkey( T_INTERVAL,
key=feed_interval_key(feed_id, parameters) ))
return val if isinstance(val, tuple) else (val, None) | python | {
"resource": ""
} |
q39873 | feed_interval_set | train | def feed_interval_set(feed_id, parameters, interval, interval_ts):
'Set adaptive interval between checks for a feed.'
cache.set(getkey( T_INTERVAL,
key=feed_interval_key(feed_id, parameters) ), (interval, interval_ts)) | python | {
"resource": ""
} |
q39874 | feed_interval_delete | train | def feed_interval_delete(feed_id, parameters):
'Invalidate cached adaptive interval value.'
cache.delete(getkey( T_INTERVAL,
key=feed_interval_key(feed_id, parameters) )) | python | {
"resource": ""
} |
q39875 | cache_set | train | def cache_set(site, key, data):
'''Sets cache data for a site.
All keys related to a site are stored in a meta key. This key is per-site.'''
tkey = getkey(T_ITEM, site.id, key)
mkey = getkey(T_META, site.id)
tmp = cache.get(mkey)
longdur = 365*24*60*60
if not tmp:
tmp = [tkey]
cache.set(mkey, [tkey], longdu... | python | {
"resource": ""
} |
q39876 | cache_delsite | train | def cache_delsite(site_id):
'Removes all cache data from a site.'
mkey = getkey(T_META, site_id)
tmp = cache.get(mkey)
if not tmp:
return
for tkey in tmp:
cache.delete(tkey)
cache.delete(mkey) | python | {
"resource": ""
} |
q39877 | _canvas_route | train | def _canvas_route(self, *args, **kwargs):
""" Decorator for canvas route
"""
def outer(view_fn):
@self.route(*args, **kwargs)
def inner(*args, **kwargs):
fn_args = getargspec(view_fn)
try:
idx = fn_args.args.index(_ARG_KEY)
except ValueErr... | python | {
"resource": ""
} |
q39878 | _decode_signed_user | train | def _decode_signed_user(encoded_sig, encoded_data):
""" Decodes the ``POST``ed signed data
"""
decoded_sig = _decode(encoded_sig)
decoded_data = loads(_decode(encoded_data))
if decoded_sig != hmac.new(app.config['CANVAS_CLIENT_SECRET'],
encoded_data, sha256).digest():
raise ValueEr... | python | {
"resource": ""
} |
q39879 | User.request | train | def request(self, path, data=None, method='GET'):
""" Convenience Facebook request function.
Utility function to request resources via the graph API, with the
format expected by Facebook.
"""
url = '%s%s?access_token=%s' % (
'https://graph.facebook.com',
... | python | {
"resource": ""
} |
q39880 | User.has_permissions | train | def has_permissions(self):
""" Check current user permission set
Checks the current user permission set against the one being requested
by the application.
"""
perms = self.request('/me/permissions')['data'][0].keys()
return all(k in perms for k in app.config[
... | python | {
"resource": ""
} |
q39881 | get_calculator_impstr | train | def get_calculator_impstr(calculator_name):
"""
Returns the import string for the calculator
"""
if calculator_name.lower() == "gpaw" or calculator_name is None:
return "from gpaw import GPAW as custom_calculator"
elif calculator_name.lower() == "espresso":
return "from espresso impo... | python | {
"resource": ""
} |
q39882 | get_optimizer_impstr | train | def get_optimizer_impstr(optimizer_name):
"""
Returns the import string for the optimizer
"""
possibilities = {"bfgs":"BFGS",
"bfgslinesearch":"BFGSLineSearch",
"fire":"FIRE",
"goodoldquasinewton":"GoodOldQuasiNewton",
"... | python | {
"resource": ""
} |
q39883 | convert_the_getters | train | def convert_the_getters(getters):
"""
A function used to prepare the arguments of calculator and atoms getter methods
"""
return_list = []
for getter in getters:
if isinstance(getter,basestring):
out_args = ""
method_name = getter
else:
... | python | {
"resource": ""
} |
q39884 | convert_the_args | train | def convert_the_args(raw_args):
"""
Function used to convert the arguments of methods
"""
if not raw_args:
return ""
if isinstance(raw_args,dict):
out_args = ", ".join([ "{}={}".format(k,v) for k,v in raw_args.iteritems() ])
elif isinstance(raw_args,(list,tuple)):
... | python | {
"resource": ""
} |
q39885 | Converter.dd_docs | train | def dd_docs(self):
"""Copy and convert various documentation files."""
top = os.path.join(os.path.dirname(__file__))
doc = os.path.join(top, 'doc')
# Markdown to ronn to man page
man_md = os.path.join(doc, 'authprogs.md')
man_ronn = os.path.join(doc, 'authprogs.1.ronn')
... | python | {
"resource": ""
} |
q39886 | Converter.rm_docs | train | def rm_docs(self):
"""Remove converted docs."""
for filename in self.created:
if os.path.exists(filename):
os.unlink(filename) | python | {
"resource": ""
} |
q39887 | post | train | def post(request):
"""Returns a serialized object"""
data = request.POST or json.loads(request.body)['body']
guid = data.get('guid', None)
res = Result()
if guid:
obj = getObjectsFromGuids([guid,])[0]
comment = Comment()
comment.comment = data.get('comment', 'No comment')
... | python | {
"resource": ""
} |
q39888 | emailComment | train | def emailComment(comment, obj, request):
"""Send an email to the author about a new comment"""
if not obj.author.frog_prefs.get().json()['emailComments']:
return
if obj.author == request.user:
return
html = render_to_string('frog/comment_email.html', {
'user': comment.user,
... | python | {
"resource": ""
} |
q39889 | ClusterMixin.cluster_nodes | train | def cluster_nodes(self):
"""Each node in a Redis Cluster has its view of the current cluster
configuration, given by the set of known nodes, the state of the
connection we have with such nodes, their flags, properties and
assigned slots, and so forth.
``CLUSTER NODES`` provides ... | python | {
"resource": ""
} |
q39890 | SetsMixin.sadd | train | def sadd(self, key, *members):
"""Add the specified members to the set stored at key. Specified
members that are already a member of this set are ignored. If key does
not exist, a new set is created before adding the specified members.
An error is returned when the value stored at key i... | python | {
"resource": ""
} |
q39891 | SetsMixin.smove | train | def smove(self, source, destination, member):
"""Move member from the set at source to the set at destination. This
operation is atomic. In every given moment the element will appear to
be a member of source or destination for other clients.
If the source set does not exist or does not ... | python | {
"resource": ""
} |
q39892 | SetsMixin.spop | train | def spop(self, key, count=None):
"""Removes and returns one or more random elements from the set value
store at key.
This operation is similar to :meth:`~tredis.RedisClient.srandmember`,
that returns one or more random elements from a set but does not remove
it.
The cou... | python | {
"resource": ""
} |
q39893 | SetsMixin.srandmember | train | def srandmember(self, key, count=None):
"""When called with just the key argument, return a random element from
the set value stored at key.
Starting from Redis version 2.6, when called with the additional count
argument, return an array of count distinct elements if count is
po... | python | {
"resource": ""
} |
q39894 | SetsMixin.srem | train | def srem(self, key, *members):
"""Remove the specified members from the set stored at key. Specified
members that are not a member of this set are ignored. If key does not
exist, it is treated as an empty set and this command returns ``0``.
An error is returned when the value stored at ... | python | {
"resource": ""
} |
q39895 | TokFm._extract_id | train | def _extract_id(self) -> str:
"""
Get video_id needed to obtain the real_url of the video.
Raises:
VideoIdNotMatchedError: If video_id is not matched with regular expression.
"""
match = re.match(self._VALID_URL, self.url)
if match:
return match... | python | {
"resource": ""
} |
q39896 | convert_time_units | train | def convert_time_units(t):
""" Convert time in seconds into reasonable time units. """
if t == 0:
return '0 s'
order = log10(t)
if -9 < order < -6:
time_units = 'ns'
factor = 1000000000
elif -6 <= order < -3:
time_units = 'us'
factor = 1000000
elif -3 <= o... | python | {
"resource": ""
} |
q39897 | globalize_indentation | train | def globalize_indentation(src):
""" Strip the indentation level so the code runs in the global scope. """
lines = src.splitlines()
indent = len(lines[0]) - len(lines[0].strip(' '))
func_src = ''
for ii, l in enumerate(src.splitlines()):
line = l[indent:]
func_src += line + '\n'
r... | python | {
"resource": ""
} |
q39898 | remove_decorators | train | def remove_decorators(src):
""" Remove decorators from the source code """
src = src.strip()
src_lines = src.splitlines()
multi_line = False
n_deleted = 0
for n in range(len(src_lines)):
line = src_lines[n - n_deleted].strip()
if (line.startswith('@') and 'Benchmark' in line) or ... | python | {
"resource": ""
} |
q39899 | walk_tree | train | def walk_tree(start, attr):
"""
Recursively walk through a tree relationship. This iterates a tree in a top-down approach,
fully reaching the end of a lineage before moving onto the next sibling of that generation.
"""
path = [start]
for child in path:
yield child
idx = path.inde... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.