_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q279000 | RPCSystem.create_function_stub | test | def create_function_stub(self, url):
"""
Create a callable that will invoke the given remote function.
The stub will return a deferred even if the remote function does not.
"""
assert self._opened, "RPC System is not opened"
logging.debug("create_function_stub(%s... | python | {
"resource": ""
} |
q279001 | RPCSystem._ping | test | def _ping(self, peerid, callid):
"""
Called from remote to ask if a call made to here is still in progress.
"""
if not (peerid, callid) in self._remote_to_local:
logger.warn("No remote call %s from %s. Might just be unfoutunate timing." % (callid, peerid)) | python | {
"resource": ""
} |
q279002 | _CommandCompleterMixin._cmdRegex | test | def _cmdRegex(self, cmd_grp=None):
"""Get command regex string and completer dict."""
cmd_grp = cmd_grp or "cmd"
help_opts = ("-h", "--help")
cmd = self.name()
names = "|".join([re.escape(cmd)] +
[re.escape(a) for a in self.aliases()])
opts = []... | python | {
"resource": ""
} |
q279003 | NestedAMPBox.fromStringProto | test | def fromStringProto(self, inString, proto):
"""
Defers to `amp.AmpList`, then gets the element from the list.
"""
value, = amp.AmpList.fromStringProto(self, inString, proto)
return value | python | {
"resource": ""
} |
q279004 | NestedAMPBox.toStringProto | test | def toStringProto(self, inObject, proto):
"""
Wraps the object in a list, and then defers to ``amp.AmpList``.
"""
return amp.AmpList.toStringProto(self, [inObject], proto) | python | {
"resource": ""
} |
q279005 | MetadataStatement.verify | test | def verify(self, **kwargs):
"""
Verifies that an instance of this class adheres to the given
restrictions.
:param kwargs: A set of keyword arguments
:return: True if it verifies OK otherwise False.
"""
super(MetadataStatement, self).verify(**kwargs)
if "s... | python | {
"resource": ""
} |
q279006 | KeyBundle._parse_remote_response | test | def _parse_remote_response(self, response):
"""
Parse simple JWKS or signed JWKS from the HTTP response.
:param response: HTTP response from the 'jwks_uri' or 'signed_jwks_uri'
endpoint
:return: response parsed as JSON or None
"""
# Check if the content type ... | python | {
"resource": ""
} |
q279007 | dump | test | def dump(filename, dbname, username=None, password=None, host=None,
port=None, tempdir='/tmp', pg_dump_path='pg_dump', format='p'):
"""Performs a pg_dump backup.
It runs with the current systemuser's privileges, unless you specify
username and password.
By default pg_dump connects to the value giv... | python | {
"resource": ""
} |
q279008 | db_list | test | def db_list(username=None, password=None, host=None, port=None,
maintain_db='postgres'):
"returns a list of all databases on this server"
conn = _connection(username=username, password=password, host=host,
port=port, db=maintain_db)
cur = conn.cursor()
cur.execute('SELECT DATNAME from... | python | {
"resource": ""
} |
q279009 | Tigre._get_local_files | test | def _get_local_files(self, path):
"""Returns a dictionary of all the files under a path."""
if not path:
raise ValueError("No path specified")
files = defaultdict(lambda: None)
path_len = len(path) + 1
for root, dirs, filenames in os.walk(path):
for name i... | python | {
"resource": ""
} |
q279010 | Tigre.sync_folder | test | def sync_folder(self, path, bucket):
"""Syncs a local directory with an S3 bucket.
Currently does not delete files from S3 that are not in the local directory.
path: The path to the directory to sync to S3
bucket: The name of the bucket on S3
"""
bucket = self.conn... | python | {
"resource": ""
} |
q279011 | tokens_required | test | def tokens_required(service_list):
"""
Ensure the user has the necessary tokens for the specified services
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
for service in service_list:
if service not in request.session["user_tokens"]:... | python | {
"resource": ""
} |
q279012 | login | test | def login(request, template_name='ci/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm):
"""
Displays the login form and handles the login action.
"""
redirect_to = request.POST.get(redirect_field_name,
req... | python | {
"resource": ""
} |
q279013 | build | test | def build(cli, path, package):
"""Build CLI dynamically based on the package structure.
"""
for _, name, ispkg in iter_modules(path):
module = import_module(f'.{name}', package)
if ispkg:
build(cli.group(name)(module.group),
module.__path__,
mo... | python | {
"resource": ""
} |
q279014 | Fridge.readonly | test | def readonly(cls, *args, **kwargs):
"""
Return an already closed read-only instance of Fridge.
Arguments are the same as for the constructor.
"""
fridge = cls(*args, **kwargs)
fridge.close()
return fridge | python | {
"resource": ""
} |
q279015 | Fridge.load | test | def load(self):
"""
Force reloading the data from the file.
All data in the in-memory dictionary is discarded.
This method is called automatically by the constructor, normally you
don't need to call it.
"""
self._check_open()
try:
data = json.l... | python | {
"resource": ""
} |
q279016 | self_sign_jwks | test | def self_sign_jwks(keyjar, iss, kid='', lifetime=3600):
"""
Create a signed JWT containing a JWKS. The JWT is signed by one of the
keys in the JWKS.
:param keyjar: A KeyJar instance with at least one private signing key
:param iss: issuer of the JWT, should be the owner of the keys
:param kid: ... | python | {
"resource": ""
} |
q279017 | request_signed_by_signing_keys | test | def request_signed_by_signing_keys(keyjar, msreq, iss, lifetime, kid=''):
"""
A metadata statement signing request with 'signing_keys' signed by one
of the keys in 'signing_keys'.
:param keyjar: A KeyJar instance with the private signing key
:param msreq: Metadata statement signing request. A Metad... | python | {
"resource": ""
} |
q279018 | library | test | def library(func):
"""
A decorator for providing a unittest with a library and have it called only
once.
"""
@wraps(func)
def wrapped(*args, **kwargs):
"""Transparent wrapper."""
return func(*args, **kwargs)
SINGLES.append(wrapped)
return wrapped | python | {
"resource": ""
} |
q279019 | descovery | test | def descovery(testdir):
"""Descover and load greencard tests."""
from os.path import join, exists, isdir, splitext, basename, sep
if not testdir or not exists(testdir) or not isdir(testdir):
return None
from os import walk
import fnmatch
import imp
for root, _, filenames in walk(te... | python | {
"resource": ""
} |
q279020 | main | test | def main(clargs=None):
"""Command line entry point."""
from argparse import ArgumentParser
from librarian.library import Library
import sys
parser = ArgumentParser(
description="A test runner for each card in a librarian library.")
parser.add_argument("library", help="Library database")... | python | {
"resource": ""
} |
q279021 | letter_score | test | def letter_score(letter):
"""Returns the Scrabble score of a letter.
Args:
letter: a single character string
Raises:
TypeError if a non-Scrabble character is supplied
"""
score_map = {
1: ["a", "e", "i", "o", "u", "l", "n", "r", "s", "t"],
2: ["d", "g"],
3:... | python | {
"resource": ""
} |
q279022 | word_score | test | def word_score(word, input_letters, questions=0):
"""Checks the Scrabble score of a single word.
Args:
word: a string to check the Scrabble score of
input_letters: the letters in our rack
questions: integer of the tiles already on the board to build on
Returns:
an integer S... | python | {
"resource": ""
} |
q279023 | word_list | test | def word_list(sowpods=False, start="", end=""):
"""Opens the word list file.
Args:
sowpods: a boolean to declare using the sowpods list or TWL (default)
start: a string of starting characters to find anagrams based on
end: a string of ending characters to find anagrams based on
Yei... | python | {
"resource": ""
} |
q279024 | valid_scrabble_word | test | def valid_scrabble_word(word):
"""Checks if the input word could be played with a full bag of tiles.
Returns:
True or false
"""
letters_in_bag = {
"a": 9,
"b": 2,
"c": 2,
"d": 4,
"e": 12,
"f": 2,
"g": 3,
"h": 2,
"i": 9,
... | python | {
"resource": ""
} |
q279025 | main | test | def main(args):
"""docstring for main"""
try:
args.query = ' '.join(args.query).replace('?', '')
so = SOSearch(args.query, args.tags)
result = so.first_q().best_answer.code
if result != None:
print result
else:
print("Sorry I can't find your answe... | python | {
"resource": ""
} |
q279026 | cli_run | test | def cli_run():
"""docstring for argparse"""
parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')
parser.add_argument('query', help="What's the problem ?", type=str, nargs='+')
parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')
... | python | {
"resource": ""
} |
q279027 | JSONAMPDialectReceiver.stringReceived | test | def stringReceived(self, string):
"""Handle a JSON AMP dialect request.
First, the JSON is parsed. Then, all JSON dialect specific
values in the request are turned into the correct objects.
Then, finds the correct responder function, calls it, and
serializes the result (or error... | python | {
"resource": ""
} |
q279028 | JSONAMPDialectReceiver._getCommandAndResponder | test | def _getCommandAndResponder(self, commandName):
"""Gets the command class and matching responder function for the
given command name.
"""
# DISGUSTING IMPLEMENTATION DETAIL EXPLOITING HACK
locator = self._remote.boxReceiver.locator
responder = locator.locateResponder(com... | python | {
"resource": ""
} |
q279029 | JSONAMPDialectReceiver._parseRequestValues | test | def _parseRequestValues(self, request, command):
"""Parses all the values in the request that are in a form specific
to the JSON AMP dialect.
"""
for key, ampType in command.arguments:
ampClass = ampType.__class__
if ampClass is exposed.ExposedResponderLocator:
... | python | {
"resource": ""
} |
q279030 | JSONAMPDialectReceiver._runResponder | test | def _runResponder(self, responder, request, command, identifier):
"""Run the responser function. If it succeeds, add the _answer key.
If it fails with an error known to the command, serialize the
error.
"""
d = defer.maybeDeferred(responder, **request)
def _addIdentifie... | python | {
"resource": ""
} |
q279031 | JSONAMPDialectReceiver._writeResponse | test | def _writeResponse(self, response):
"""
Serializes the response to JSON, and writes it to the transport.
"""
encoded = dumps(response, default=_default)
self.transport.write(encoded) | python | {
"resource": ""
} |
q279032 | JSONAMPDialectReceiver.connectionLost | test | def connectionLost(self, reason):
"""
Tells the box receiver to stop receiving boxes.
"""
self._remote.boxReceiver.stopReceivingBoxes(reason)
return basic.NetstringReceiver.connectionLost(self, reason) | python | {
"resource": ""
} |
q279033 | JSONAMPDialectFactory.buildProtocol | test | def buildProtocol(self, addr):
"""
Builds a bridge and associates it with an AMP protocol instance.
"""
proto = self._factory.buildProtocol(addr)
return JSONAMPDialectReceiver(proto) | python | {
"resource": ""
} |
q279034 | jwks_to_keyjar | test | def jwks_to_keyjar(jwks, iss=''):
"""
Convert a JWKS to a KeyJar instance.
:param jwks: String representation of a JWKS
:return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
"""
if not isinstance(jwks, dict):
try:
jwks = json.loads(jwks)
except json.JSONDecodeError:... | python | {
"resource": ""
} |
q279035 | JWKSBundle.loads | test | def loads(self, jstr):
"""
Upload a bundle from an unsigned JSON document
:param jstr: A bundle as a dictionary or a JSON document
"""
if isinstance(jstr, dict):
_info = jstr
else:
_info = json.loads(jstr)
for iss, jwks in _info.items():
... | python | {
"resource": ""
} |
q279036 | nova_process | test | def nova_process(body, message):
"""
This function deal with the nova notification.
First, find process from customer_process that not include wildcard.
if not find from customer_process, then find process from customer_process_wildcard.
if not find from customer_process_wildcard, then use ternya d... | python | {
"resource": ""
} |
q279037 | cinder_process | test | def cinder_process(body, message):
"""
This function deal with the cinder notification.
First, find process from customer_process that not include wildcard.
if not find from customer_process, then find process from customer_process_wildcard.
if not find from customer_process_wildcard, then use tern... | python | {
"resource": ""
} |
q279038 | neutron_process | test | def neutron_process(body, message):
"""
This function deal with the neutron notification.
First, find process from customer_process that not include wildcard.
if not find from customer_process, then find process from customer_process_wildcard.
if not find from customer_process_wildcard, then use te... | python | {
"resource": ""
} |
q279039 | glance_process | test | def glance_process(body, message):
"""
This function deal with the glance notification.
First, find process from customer_process that not include wildcard.
if not find from customer_process, then find process from customer_process_wildcard.
if not find from customer_process_wildcard, then use tern... | python | {
"resource": ""
} |
q279040 | swift_process | test | def swift_process(body, message):
"""
This function deal with the swift notification.
First, find process from customer_process that not include wildcard.
if not find from customer_process, then find process from customer_process_wildcard.
if not find from customer_process_wildcard, then use ternya... | python | {
"resource": ""
} |
q279041 | keystone_process | test | def keystone_process(body, message):
"""
This function deal with the keystone notification.
First, find process from customer_process that not include wildcard.
if not find from customer_process, then find process from customer_process_wildcard.
if not find from customer_process_wildcard, then use ... | python | {
"resource": ""
} |
q279042 | heat_process | test | def heat_process(body, message):
"""
This function deal with the heat notification.
First, find process from customer_process that not include wildcard.
if not find from customer_process, then find process from customer_process_wildcard.
if not find from customer_process_wildcard, then use ternya d... | python | {
"resource": ""
} |
q279043 | App.serve | test | def serve(self, server=None):
"""Serve app using wsgiref or provided server.
Args:
- server (callable): An callable
"""
if server is None:
from wsgiref.simple_server import make_server
server = lambda app: make_server('', 8000, app).serve_forever()
... | python | {
"resource": ""
} |
q279044 | pout | test | def pout(msg, log=None):
"""Print 'msg' to stdout, and option 'log' at info level."""
_print(msg, sys.stdout, log_func=log.info if log else None) | python | {
"resource": ""
} |
q279045 | perr | test | def perr(msg, log=None):
"""Print 'msg' to stderr, and option 'log' at info level."""
_print(msg, sys.stderr, log_func=log.error if log else None) | python | {
"resource": ""
} |
q279046 | register | test | def register(CommandSubClass):
"""A class decorator for Command classes to register in the default set."""
name = CommandSubClass.name()
if name in Command._all_commands:
raise ValueError("Command already exists: " + name)
Command._all_commands[name] = CommandSubClass
return CommandSubClass | python | {
"resource": ""
} |
q279047 | Command.register | test | def register(Class, CommandSubClass):
"""A class decorator for Command classes to register."""
for name in [CommandSubClass.name()] + CommandSubClass.aliases():
if name in Class._registered_commands[Class]:
raise ValueError("Command already exists: " + name)
Class... | python | {
"resource": ""
} |
q279048 | ConstrainedArgument.toString | test | def toString(self, value):
"""
If all of the constraints are satisfied with the given value, defers
to the composed AMP argument's ``toString`` method.
"""
self._checkConstraints(value)
return self.baseArgument.toString(value) | python | {
"resource": ""
} |
q279049 | ConstrainedArgument.fromString | test | def fromString(self, string):
"""
Converts the string to a value using the composed AMP argument, then
checks all the constraints against that value.
"""
value = self.baseArgument.fromString(string)
self._checkConstraints(value)
return value | python | {
"resource": ""
} |
q279050 | _updateCompleterDict | test | def _updateCompleterDict(completers, cdict, regex=None):
"""Merges ``cdict`` into ``completers``. In the event that a key
in cdict already exists in the completers dict a ValueError is raised
iff ``regex`` false'y. If a regex str is provided it and the duplicate
key are updated to be uni... | python | {
"resource": ""
} |
q279051 | Ternya.work | test | def work(self):
"""
Start ternya work.
First, import customer's service modules.
Second, init openstack mq.
Third, keep a ternya connection that can auto-reconnect.
"""
self.init_modules()
connection = self.init_mq()
TernyaConnection(self, connect... | python | {
"resource": ""
} |
q279052 | Ternya.init_mq | test | def init_mq(self):
"""Init connection and consumer with openstack mq."""
mq = self.init_connection()
self.init_consumer(mq)
return mq.connection | python | {
"resource": ""
} |
q279053 | Ternya.init_modules | test | def init_modules(self):
"""Import customer's service modules."""
if not self.config:
raise ValueError("please read your config file.")
log.debug("begin to import customer's service modules.")
modules = ServiceModules(self.config)
modules.import_modules()
log.... | python | {
"resource": ""
} |
q279054 | Ternya.init_nova_consumer | test | def init_nova_consumer(self, mq):
"""
Init openstack nova mq
1. Check if enable listening nova notification
2. Create consumer
:param mq: class ternya.mq.MQ
"""
if not self.enable_component_notification(Openstack.Nova):
log.debug("disable listening n... | python | {
"resource": ""
} |
q279055 | Ternya.init_cinder_consumer | test | def init_cinder_consumer(self, mq):
"""
Init openstack cinder mq
1. Check if enable listening cinder notification
2. Create consumer
:param mq: class ternya.mq.MQ
"""
if not self.enable_component_notification(Openstack.Cinder):
log.debug("disable lis... | python | {
"resource": ""
} |
q279056 | Ternya.init_neutron_consumer | test | def init_neutron_consumer(self, mq):
"""
Init openstack neutron mq
1. Check if enable listening neutron notification
2. Create consumer
:param mq: class ternya.mq.MQ
"""
if not self.enable_component_notification(Openstack.Neutron):
log.debug("disable... | python | {
"resource": ""
} |
q279057 | Ternya.init_glance_consumer | test | def init_glance_consumer(self, mq):
"""
Init openstack glance mq
1. Check if enable listening glance notification
2. Create consumer
:param mq: class ternya.mq.MQ
"""
if not self.enable_component_notification(Openstack.Glance):
log.debug("disable lis... | python | {
"resource": ""
} |
q279058 | Ternya.init_heat_consumer | test | def init_heat_consumer(self, mq):
"""
Init openstack heat mq
1. Check if enable listening heat notification
2. Create consumer
:param mq: class ternya.mq.MQ
"""
if not self.enable_component_notification(Openstack.Heat):
log.debug("disable listening h... | python | {
"resource": ""
} |
q279059 | Ternya.enable_component_notification | test | def enable_component_notification(self, openstack_component):
"""
Check if customer enable openstack component notification.
:param openstack_component: Openstack component type.
"""
openstack_component_mapping = {
Openstack.Nova: self.config.listen_nova_notification... | python | {
"resource": ""
} |
q279060 | music_info | test | def music_info(songid):
"""
Get music info from baidu music api
"""
if isinstance(songid, list):
songid = ','.join(songid)
data = {
"hq": 1,
"songIds": songid
}
res = requests.post(MUSIC_INFO_URL, data=data)
info = res.json()
music_data = info["data"]
son... | python | {
"resource": ""
} |
q279061 | download_music | test | def download_music(song, thread_num=4):
"""
process for downing music with multiple threads
"""
filename = "{}.mp3".format(song["name"])
if os.path.exists(filename):
os.remove(filename)
part = int(song["size"] / thread_num)
if part <= 1024:
thread_num = 1
_id = uuid.uu... | python | {
"resource": ""
} |
q279062 | Machine.execute | test | def execute(self, globals_=None, _locals=None):
"""
Execute a code object
The inputs and behavior of this function should match those of
eval_ and exec_.
.. _eval: https://docs.python.org/3/library/functions.html?highlight=eval#eval
.. _exec: https://docs.python... | python | {
"resource": ""
} |
q279063 | Machine.load_name | test | def load_name(self, name):
"""
Implementation of the LOAD_NAME operation
"""
if name in self.globals_:
return self.globals_[name]
b = self.globals_['__builtins__']
if isinstance(b, dict):
return b[name]
else:
return get... | python | {
"resource": ""
} |
q279064 | Machine.call_function | test | def call_function(self, c, i):
"""
Implement the CALL_FUNCTION_ operation.
.. _CALL_FUNCTION: https://docs.python.org/3/library/dis.html#opcode-CALL_FUNCTION
"""
callable_ = self.__stack[-1-i.arg]
args = tuple(self.__stack[len(self.__stack) - i.arg:])
... | python | {
"resource": ""
} |
q279065 | dump | test | def dump(filename, dbname, username=None, password=None, host=None,
port=None, tempdir='/tmp', mysqldump_path='mysqldump'):
"""Perfoms a mysqldump backup.
Create a database dump for the given database.
returns statuscode and shelloutput
"""
filepath = os.path.join(tempdir, filename)
cmd = ... | python | {
"resource": ""
} |
q279066 | render_ditaa | test | def render_ditaa(self, code, options, prefix='ditaa'):
"""Render ditaa code into a PNG output file."""
hashkey = code.encode('utf-8') + str(options) + \
str(self.builder.config.ditaa) + \
str(self.builder.config.ditaa_args)
infname = '%s-%s.%s' % (prefix, sha(hashkey).hexdigest()... | python | {
"resource": ""
} |
q279067 | Application._atexit | test | def _atexit(self):
"""Invoked in the 'finally' block of Application.run."""
self.log.debug("Application._atexit")
if self._atexit_func:
self._atexit_func(self) | python | {
"resource": ""
} |
q279068 | Application.run | test | def run(self, args_list=None):
"""Run Application.main and exits with the return value."""
self.log.debug("Application.run: {args_list}".format(**locals()))
retval = None
try:
retval = self._run(args_list=args_list)
except KeyboardInterrupt:
self.log.verbo... | python | {
"resource": ""
} |
q279069 | cd | test | def cd(path):
"""Context manager that changes to directory `path` and return to CWD
when exited.
"""
old_path = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(old_path) | python | {
"resource": ""
} |
q279070 | copytree | test | def copytree(src, dst, symlinks=True):
"""
Modified from shutil.copytree docs code sample, merges files rather than
requiring dst to not exist.
"""
from shutil import copy2, Error, copystat
names = os.listdir(src)
if not Path(dst).exists():
os.makedirs(dst)
errors = []
for... | python | {
"resource": ""
} |
q279071 | debugger | test | def debugger():
"""If called in the context of an exception, calls post_mortem; otherwise
set_trace.
``ipdb`` is preferred over ``pdb`` if installed.
"""
e, m, tb = sys.exc_info()
if tb is not None:
_debugger.post_mortem(tb)
else:
_debugger.set_trace() | python | {
"resource": ""
} |
q279072 | FileSystem.get_mtime | test | def get_mtime(fname):
"""
Find the time this file was last modified.
:param fname: File name
:return: The last time the file was modified.
"""
try:
mtime = os.stat(fname).st_mtime_ns
except OSError:
# The file might be right in the middle ... | python | {
"resource": ""
} |
q279073 | FileSystem.is_changed | test | def is_changed(self, item):
"""
Find out if this item has been modified since last
:param item: A key
:return: True/False
"""
fname = os.path.join(self.fdir, item)
if os.path.isfile(fname):
mtime = self.get_mtime(fname)
try:
... | python | {
"resource": ""
} |
q279074 | FileSystem.sync | test | def sync(self):
"""
Goes through the directory and builds a local cache based on
the content of the directory.
"""
if not os.path.isdir(self.fdir):
os.makedirs(self.fdir)
for f in os.listdir(self.fdir):
fname = os.path.join(self.fdir, f)
... | python | {
"resource": ""
} |
q279075 | FileSystem.clear | test | def clear(self):
"""
Completely resets the database. This means that all information in
the local cache and on disc will be erased.
"""
if not os.path.isdir(self.fdir):
os.makedirs(self.fdir, exist_ok=True)
return
for f in os.listdir(self.fdir):
... | python | {
"resource": ""
} |
q279076 | scrape | test | def scrape(ctx, url):
"""
Rip the events from a given rss feed, normalize the data and store.
"""
data = load_feed(url)
feed = data['feed']
entries = data['entries']
# THIS IS SPECIFIC TO # http://konfery.cz/rss/
_type = 'community'
country = 'Czech Republic'
# title, title_de... | python | {
"resource": ""
} |
q279077 | Camera.download_image | test | def download_image(self):
"""
Download the image and return the
local path to the image file.
"""
split = urlsplit(self.url)
filename = split.path.split("/")[-1]
# Ensure the directory to store the image cache exists
if not os.path.exists(self.cache_direc... | python | {
"resource": ""
} |
q279078 | Camera.has_changed | test | def has_changed(self):
"""
Method to check if an image has changed
since it was last downloaded. By making
a head request, this check can be done
quicker that downloading and processing
the whole file.
"""
request = urllib_request.Request(self.url)
... | python | {
"resource": ""
} |
q279079 | fancy_tag_compiler | test | def fancy_tag_compiler(params, defaults, takes_var_args, takes_var_kwargs, takes_context, name, node_class, parser, token):
"Returns a template.Node subclass."
bits = token.split_contents()[1:]
if takes_context:
if 'context' in params[:1]:
params = params[1:]
else:
r... | python | {
"resource": ""
} |
q279080 | SeabornLogger.findCaller | test | def findCaller(self, stack_info=False):
"""
Find the stack frame of the caller so that we can note the source
file name, line number and function name.
"""
f = logging.currentframe()
# On some versions of IronPython, currentframe() returns None if
# IronPython isn... | python | {
"resource": ""
} |
q279081 | get_defining_component | test | def get_defining_component(pe_pe):
'''
get the C_C in which pe_pe is defined
'''
if pe_pe is None:
return None
if pe_pe.__class__.__name__ != 'PE_PE':
pe_pe = xtuml.navigate_one(pe_pe).PE_PE[8001]()
ep_pkg = xtuml.navigate_one(pe_pe).EP_PKG[8000]()
if ep_pkg:
... | python | {
"resource": ""
} |
q279082 | main | test | def main():
'''
Parse command line options and launch the prebuilder.
'''
parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path..]",
version=xtuml.version.complete_string,
formatter=optparse.TitledHelp... | python | {
"resource": ""
} |
q279083 | SymbolTable.find_symbol | test | def find_symbol(self, name=None, kind=None):
'''
Find a symbol in the symbol table by name, kind, or both.
'''
for s in reversed(self.stack):
for symbol_name, handle in s.symbols.items():
symbol_kind = handle.__class__.__name__
... | python | {
"resource": ""
} |
q279084 | is_contained_in | test | def is_contained_in(pe_pe, root):
'''
Determine if a PE_PE is contained within a EP_PKG or a C_C.
'''
if not pe_pe:
return False
if type(pe_pe).__name__ != 'PE_PE':
pe_pe = one(pe_pe).PE_PE[8001]()
ep_pkg = one(pe_pe).EP_PKG[8000]()
c_c = one(pe_pe).C_C[8003]()
... | python | {
"resource": ""
} |
q279085 | is_global | test | def is_global(pe_pe):
'''
Check if a PE_PE is globally defined, i.e. not inside a C_C
'''
if type(pe_pe).__name__ != 'PE_PE':
pe_pe = one(pe_pe).PE_PE[8001]()
if one(pe_pe).C_C[8003]():
return False
pe_pe = one(pe_pe).EP_PKG[8000].PE_PE[8001]()
if not pe_pe:
... | python | {
"resource": ""
} |
q279086 | _get_data_type_name | test | def _get_data_type_name(s_dt):
'''
Convert a BridgePoint data type to a pyxtuml meta model type.
'''
s_cdt = one(s_dt).S_CDT[17]()
if s_cdt and s_cdt.Core_Typ in range(1, 6):
return s_dt.Name.upper()
if one(s_dt).S_EDT[17]():
return 'INTEGER'
s_dt = one(s_dt).S_UDT[... | python | {
"resource": ""
} |
q279087 | _get_related_attributes | test | def _get_related_attributes(r_rgo, r_rto):
'''
The two lists of attributes which relates two classes in an association.
'''
l1 = list()
l2 = list()
ref_filter = lambda ref: ref.OIR_ID == r_rgo.OIR_ID
for o_ref in many(r_rto).O_RTIDA[110].O_REF[111](ref_filter):
o_attr = one(o_re... | python | {
"resource": ""
} |
q279088 | mk_enum | test | def mk_enum(s_edt):
'''
Create a named tuple from a BridgePoint enumeration.
'''
s_dt = one(s_edt).S_DT[17]()
enums = list()
kwlist =['False', 'None', 'True'] + keyword.kwlist
for enum in many(s_edt).S_ENUM[27]():
if enum.Name in kwlist:
enums.append(enum.Name + '_')
... | python | {
"resource": ""
} |
q279089 | mk_bridge | test | def mk_bridge(metamodel, s_brg):
'''
Create a python function from a BridgePoint bridge.
'''
action = s_brg.Action_Semantics_internal
label = s_brg.Name
return lambda **kwargs: interpret.run_function(metamodel, label,
action, kwargs) | python | {
"resource": ""
} |
q279090 | mk_external_entity | test | def mk_external_entity(metamodel, s_ee):
'''
Create a python object from a BridgePoint external entity with bridges
realized as python member functions.
'''
bridges = many(s_ee).S_BRG[19]()
names = [brg.Name for brg in bridges]
EE = collections.namedtuple(s_ee.Key_Lett, names)
funcs = l... | python | {
"resource": ""
} |
q279091 | mk_function | test | def mk_function(metamodel, s_sync):
'''
Create a python function from a BridgePoint function.
'''
action = s_sync.Action_Semantics_internal
label = s_sync.Name
return lambda **kwargs: interpret.run_function(metamodel, label,
action, kwargs) | python | {
"resource": ""
} |
q279092 | mk_constant | test | def mk_constant(cnst_syc):
'''
Create a python value from a BridgePoint constant.
'''
s_dt = one(cnst_syc).S_DT[1500]()
cnst_lsc = one(cnst_syc).CNST_LFSC[1502].CNST_LSC[1503]()
if s_dt.Name == 'boolean':
return cnst_lsc.Value.lower() == 'true'
if s_dt.Name == 'integer':
... | python | {
"resource": ""
} |
q279093 | mk_operation | test | def mk_operation(metaclass, o_tfr):
'''
Create a python function that interprets that action of a BridgePoint class
operation.
'''
o_obj = one(o_tfr).O_OBJ[115]()
action = o_tfr.Action_Semantics_internal
label = '%s::%s' % (o_obj.Name, o_tfr.Name)
run = interpret.run_operation
i... | python | {
"resource": ""
} |
q279094 | mk_derived_attribute | test | def mk_derived_attribute(metaclass, o_dbattr):
'''
Create a python property that interprets that action of a BridgePoint derived
attribute.
'''
o_attr = one(o_dbattr).O_BATTR[107].O_ATTR[106]()
o_obj = one(o_attr).O_OBJ[102]()
action = o_dbattr.Action_Semantics_internal
label = '%s::%s' ... | python | {
"resource": ""
} |
q279095 | mk_class | test | def mk_class(m, o_obj, derived_attributes=False):
'''
Create a pyxtuml class from a BridgePoint class.
'''
first_filter = lambda selected: not one(selected).O_ATTR[103, 'succeeds']()
o_attr = one(o_obj).O_ATTR[102](first_filter)
attributes = list()
while o_attr:
s_dt = get_a... | python | {
"resource": ""
} |
q279096 | mk_simple_association | test | def mk_simple_association(m, r_simp):
'''
Create a pyxtuml association from a simple association in BridgePoint.
'''
r_rel = one(r_simp).R_REL[206]()
r_form = one(r_simp).R_FORM[208]()
r_part = one(r_simp).R_PART[207]()
r_rgo = one(r_form).R_RGO[205]()
r_rto = one(r_part).R_RTO[204... | python | {
"resource": ""
} |
q279097 | mk_linked_association | test | def mk_linked_association(m, r_assoc):
'''
Create pyxtuml associations from a linked association in BridgePoint.
'''
r_rel = one(r_assoc).R_REL[206]()
r_rgo = one(r_assoc).R_ASSR[211].R_RGO[205]()
source_o_obj = one(r_rgo).R_OIR[203].O_OBJ[201]()
def _mk_assoc(side1, side2):
r_r... | python | {
"resource": ""
} |
q279098 | mk_association | test | def mk_association(m, r_rel):
'''
Create a pyxtuml association from a R_REL in ooaofooa.
'''
handler = {
'R_SIMP': mk_simple_association,
'R_ASSOC': mk_linked_association,
'R_SUBSUP': mk_subsuper_association,
'R_COMP': mk_derived_association,
}
inst = subtype(r_re... | python | {
"resource": ""
} |
q279099 | mk_component | test | def mk_component(bp_model, c_c=None, derived_attributes=False):
'''
Create a pyxtuml meta model from a BridgePoint model.
Optionally, restrict to classes and associations contained in the
component c_c.
'''
target = Domain()
c_c_filt = lambda sel: c_c is None or is_contained_in(sel, c_c)
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.