_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q237000 | Vexrc.read | train | def read(self, path, environ):
"""Read data from file into this vexrc instance.
"""
try:
inp = open(path, 'rb')
except FileNotFoundError as error:
if error.errno != 2:
raise
return None
parsing = parse_vexrc(inp, environ)
... | python | {
"resource": ""
} |
q237001 | Vexrc.get_ve_base | train | def get_ve_base(self, environ):
"""Find a directory to look for virtualenvs in.
"""
# set ve_base to a path we can look for virtualenvs:
# 1. .vexrc
# 2. WORKON_HOME (as defined for virtualenvwrapper's benefit)
# 3. $HOME/.virtualenvs
# (unless we got --path, then... | python | {
"resource": ""
} |
q237002 | Vexrc.get_shell | train | def get_shell(self, environ):
"""Find a command to run.
"""
command = self.headings[self.default_heading].get('shell')
if not command and os.name != 'nt':
command = environ.get('SHELL', '')
command = shlex.split(command) if command else None
return command | python | {
"resource": ""
} |
q237003 | Torrent.name | train | def name(self):
"""
Name of the torrent
Default to last item in :attr:`path` or ``None`` if :attr:`path` is
``None``.
Setting this property sets or removes ``name`` in :attr:`metainfo`\
``['info']``.
"""
if 'name' not in self.metainfo['info'] and self.pa... | python | {
"resource": ""
} |
q237004 | Torrent.trackers | train | def trackers(self):
"""
List of tiers of announce URLs or ``None`` for no trackers
A tier is either a single announce URL (:class:`str`) or an
:class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce
URLs.
Setting this property sets or removes ``announce`` an... | python | {
"resource": ""
} |
q237005 | Torrent.infohash | train | def infohash(self):
"""SHA1 info hash"""
self.validate()
info = self.convert()[b'info']
return sha1(bencode(info)).hexdigest() | python | {
"resource": ""
} |
q237006 | Torrent.infohash_base32 | train | def infohash_base32(self):
"""Base32 encoded SHA1 info hash"""
self.validate()
info = self.convert()[b'info']
return b32encode(sha1(bencode(info)).digest()) | python | {
"resource": ""
} |
q237007 | Torrent.generate | train | def generate(self, callback=None, interval=0):
"""
Hash pieces and report progress to `callback`
This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all
pieces are hashed successfully.
:param callable callback: Callable with signature ``(torrent, filepath,
... | python | {
"resource": ""
} |
q237008 | Torrent.magnet | train | def magnet(self, name=True, size=True, trackers=True, tracker=False, validate=True):
"""
BTIH Magnet URI
:param bool name: Whether to include the name
:param bool size: Whether to include the size
:param bool trackers: Whether to include all trackers
:param bool tracker:... | python | {
"resource": ""
} |
q237009 | Torrent.read_stream | train | def read_stream(cls, stream, validate=True):
"""
Read torrent metainfo from file-like object
:param stream: Readable file-like object (e.g. :class:`io.BytesIO`)
:param bool validate: Whether to run :meth:`validate` on the new Torrent
object
:raises ReadError: if rea... | python | {
"resource": ""
} |
q237010 | Torrent.read | train | def read(cls, filepath, validate=True):
"""
Read torrent metainfo from file
:param filepath: Path of the torrent file
:param bool validate: Whether to run :meth:`validate` on the new Torrent
object
:raises ReadError: if reading from `filepath` fails
:raises ... | python | {
"resource": ""
} |
q237011 | Torrent.copy | train | def copy(self):
"""
Return a new object with the same metainfo
Internally, this simply copies the internal metainfo dictionary with
:func:`copy.deepcopy` and gives it to the new instance.
"""
from copy import deepcopy
cp = type(self)()
cp._metainfo = deep... | python | {
"resource": ""
} |
q237012 | validated_url | train | def validated_url(url):
"""Return url if valid, raise URLError otherwise"""
try:
u = urlparse(url)
u.port # Trigger 'invalid port' exception
except Exception:
raise error.URLError(url)
else:
if not u.scheme or not u.netloc:
raise error.URLError(url)
r... | python | {
"resource": ""
} |
q237013 | read_chunks | train | def read_chunks(filepath, chunk_size):
"""Generator that yields chunks from file"""
try:
with open(filepath, 'rb') as f:
while True:
chunk = f.read(chunk_size)
if chunk:
yield chunk
else:
break # EOF
... | python | {
"resource": ""
} |
q237014 | calc_piece_size | train | def calc_piece_size(total_size, max_pieces, min_piece_size, max_piece_size):
"""Calculate piece size"""
ps = 1 << max(0, math.ceil(math.log(total_size / max_pieces, 2)))
if ps < min_piece_size:
ps = min_piece_size
if ps > max_piece_size:
ps = max_piece_size
return ps | python | {
"resource": ""
} |
q237015 | is_power_of_2 | train | def is_power_of_2(num):
"""Return whether `num` is a power of two"""
log = math.log2(num)
return int(log) == float(log) | python | {
"resource": ""
} |
q237016 | is_hidden | train | def is_hidden(path):
"""Whether file or directory is hidden"""
for name in path.split(os.sep):
if name != '.' and name != '..' and name and name[0] == '.':
return True
return False | python | {
"resource": ""
} |
q237017 | filepaths | train | def filepaths(path, exclude=(), hidden=True, empty=True):
"""
Return list of absolute, sorted file paths
path: Path to file or directory
exclude: List of file name patterns to exclude
hidden: Whether to include hidden files
empty: Whether to include empty files
Raise PathNotFoundError if p... | python | {
"resource": ""
} |
q237018 | assert_type | train | def assert_type(lst_or_dct, keys, exp_types, must_exist=True, check=None):
"""
Raise MetainfoError is not of a particular type
lst_or_dct: list or dict instance
keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a
value
exp_types: Sequence of types that the value s... | python | {
"resource": ""
} |
q237019 | error_message_and_exit | train | def error_message_and_exit(message, error_result):
"""Prints error messages in blue, the failed task result and quits."""
if message:
error_message(message)
puts(json.dumps(error_result, indent=2))
sys.exit(1) | python | {
"resource": ""
} |
q237020 | print_prompt_values | train | def print_prompt_values(values, message=None, sub_attr=None):
"""Prints prompt title and choices with a bit of formatting."""
if message:
prompt_message(message)
for index, entry in enumerate(values):
if sub_attr:
line = '{:2d}: {}'.format(index, getattr(utf8(entry), sub_attr))
... | python | {
"resource": ""
} |
q237021 | prompt_for_input | train | def prompt_for_input(message, input_type=None):
"""Prints prompt instruction and does basic input parsing."""
while True:
output = prompt.query(message)
if input_type:
try:
output = input_type(output)
except ValueError:
error_message('Inva... | python | {
"resource": ""
} |
q237022 | prompt_for_choice | train | def prompt_for_choice(values, message, input_type=int, output_type=None):
"""Prints prompt with a list of choices to choose from."""
output = None
while not output:
index = prompt_for_input(message, input_type=input_type)
try:
output = utf8(values[index])
except IndexErr... | python | {
"resource": ""
} |
q237023 | ObjectStore._retrieve_result | train | def _retrieve_result(endpoints, token_header):
"""Prepare the request list and execute them concurrently."""
request_list = [
(url, token_header)
for (task_id, url) in endpoints
]
responses = concurrent_get(request_list)
# Quick sanity check
asse... | python | {
"resource": ""
} |
q237024 | AsmasterApi._build_endpoint | train | def _build_endpoint(self, endpoint_name):
"""Generate an enpoint url from a setting name.
Args:
endpoint_name(str): setting name for the enpoint to build
Returns:
(str) url enpoint
"""
endpoint_relative = settings.get('asmaster_endpoints', endpoint_name)... | python | {
"resource": ""
} |
q237025 | AsmasterApi._set_allowed_services_and_actions | train | def _set_allowed_services_and_actions(self, services):
"""Expect services to be a list of service dictionaries, each with `name` and `actions` keys."""
for service in services:
self.services[service['name']] = {}
for action in service['actions']:
name = action.po... | python | {
"resource": ""
} |
q237026 | AsmasterApi.list_subscriptions | train | def list_subscriptions(self, service):
"""Asks for a list of all subscribed accounts and devices, along with their statuses."""
data = {
'service': service,
}
return self._perform_post_request(self.list_subscriptions_endpoint, data, self.token_header) | python | {
"resource": ""
} |
q237027 | AsmasterApi.subscribe_account | train | def subscribe_account(self, username, password, service):
"""Subscribe an account for a service.
"""
data = {
'service': service,
'username': username,
'password': password,
}
return self._perform_post_request(self.subscribe_account_endpoint, ... | python | {
"resource": ""
} |
q237028 | AsmasterDownloadFileHandler.file_id_to_file_name | train | def file_id_to_file_name(file_id):
"""Sometimes file ids are not the file names on the device, but are instead generated
by the API. These are not guaranteed to be valid file names so need hashing.
"""
if len(file_id) == 40 and re.match("^[a-f0-9]+$", file_id):
return file_id... | python | {
"resource": ""
} |
q237029 | sync | train | def sync(func):
"""Decorator to make a task synchronous."""
sync_timeout = 3600 # Match standard synchronous timeout.
def wraps(*args, **kwargs):
task = func(*args, **kwargs)
task.wait_for_result(timeout=sync_timeout)
result = json.loads(task.result)
return result
retu... | python | {
"resource": ""
} |
q237030 | SampleLiveICloudApplication.fetch_data | train | def fetch_data(self):
"""Prompt for a data type choice and execute the `fetch_data` task.
The results are saved to a file in json format.
"""
choices = self.available_data
choices.insert(0, 'All')
selected_data_type = utils.select_item(
choices,
'... | python | {
"resource": ""
} |
q237031 | SampleICloudApplication.log_in | train | def log_in(self):
"""Perform the `log_in` task to setup the API session for future data requests."""
if not self.password:
# Password wasn't give, ask for it now
self.password = getpass.getpass('Password: ')
utils.pending_message('Performing login...')
login_res... | python | {
"resource": ""
} |
q237032 | SampleICloudApplication.get_devices | train | def get_devices(self):
"""Execute the `get_devices` task and store the results in `self.devices`."""
utils.pending_message('Fetching device list...')
get_devices_task = self.client.devices(
account=self.account
)
# We wait for device list info as this sample relies ... | python | {
"resource": ""
} |
q237033 | SampleICloudApplication.download_files | train | def download_files(self, files):
"""This method uses the `download_file` task to retrieve binary files
such as attachments, images and videos.
Notice that this method does not wait for the tasks it creates to return
a result synchronously.
"""
utils.pending_message(
... | python | {
"resource": ""
} |
q237034 | Api.register_account | train | def register_account(self, username, service):
"""Register an account against a service.
The account that we're querying must be referenced during any
future task requests - so we know which account to link the task
too.
"""
data = {
'service': service,
... | python | {
"resource": ""
} |
q237035 | Api.perform_task | train | def perform_task(self, service, task_name, account, payload, callback=None):
"""Submit a task to the API.
The task is executed asyncronously, and a Task object is returned.
"""
data = {
'service': service,
'action': task_name,
'account': account,
... | python | {
"resource": ""
} |
q237036 | Api.task_status | train | def task_status(self, task_id):
"""Find the status of a task."""
data = {
'task_ids': task_id,
}
return self._perform_post_request(self.task_status_endpoint, data, self.token_header) | python | {
"resource": ""
} |
q237037 | Api.result_consumed | train | def result_consumed(self, task_id):
"""Report the result as successfully consumed."""
logger.debug('Sending result consumed message.')
data = {
'task_ids': task_id,
}
return self._perform_post_request(self.results_consumed_endpoint, data, self.token_header) | python | {
"resource": ""
} |
q237038 | NewVersionWarning.send_mails | train | def send_mails(cls):
"""
For each new django-cas-server version, if the current instance is not up to date
send one mail to ``settings.ADMINS``.
"""
if settings.CAS_NEW_VERSION_EMAIL_WARNING and settings.ADMINS:
try:
obj = cls.objects.get()
... | python | {
"resource": ""
} |
q237039 | CASClientBase.get_proxy_url | train | def get_proxy_url(self, pgt):
"""Returns proxy url, given the proxy granting ticket"""
params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url})
return "%s/proxy?%s" % (self.server_url, params) | python | {
"resource": ""
} |
q237040 | LdapAuthUser.get_conn | train | def get_conn(cls):
"""Return a connection object to the ldap database"""
conn = cls._conn
if conn is None or conn.closed:
conn = ldap3.Connection(
settings.CAS_LDAP_SERVER,
settings.CAS_LDAP_USER,
settings.CAS_LDAP_PASSWORD,
... | python | {
"resource": ""
} |
q237041 | json_encode | train | def json_encode(obj):
"""Encode a python object to json"""
try:
return json_encode.encoder.encode(obj)
except AttributeError:
json_encode.encoder = DjangoJSONEncoder(default=six.text_type)
return json_encode(obj) | python | {
"resource": ""
} |
q237042 | context | train | def context(params):
"""
Function that add somes variable to the context before template rendering
:param dict params: The context dictionary used to render templates.
:return: The ``params`` dictionary with the key ``settings`` set to
:obj:`django.conf.settings`.
:rtype... | python | {
"resource": ""
} |
q237043 | json_response | train | def json_response(request, data):
"""
Wrapper dumping `data` to a json and sending it to the user with an HttpResponse
:param django.http.HttpRequest request: The request object used to generate this response.
:param dict data: The python dictionnary to return as a json
:return: The... | python | {
"resource": ""
} |
q237044 | import_attr | train | def import_attr(path):
"""
transform a python dotted path to the attr
:param path: A dotted path to a python object or a python object
:type path: :obj:`unicode` or :obj:`str` or anything
:return: The python object pointed by the dotted path or the python object unchanged
"""
... | python | {
"resource": ""
} |
q237045 | redirect_params | train | def redirect_params(url_name, params=None):
"""
Redirect to ``url_name`` with ``params`` as querystring
:param unicode url_name: a URL pattern name
:param params: Some parameter to append to the reversed URL
:type params: :obj:`dict` or :obj:`NoneType<types.NoneType>`
:retur... | python | {
"resource": ""
} |
q237046 | reverse_params | train | def reverse_params(url_name, params=None, **kwargs):
"""
compute the reverse url of ``url_name`` and add to it parameters from ``params``
as querystring
:param unicode url_name: a URL pattern name
:param params: Some parameter to append to the reversed URL
:type params: :obj... | python | {
"resource": ""
} |
q237047 | set_cookie | train | def set_cookie(response, key, value, max_age):
"""
Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes
:param django.http.HttpResponse response: a django response where to set the cookie
:param unicode key: the cookie key
:param unicode value: ... | python | {
"resource": ""
} |
q237048 | get_current_url | train | def get_current_url(request, ignore_params=None):
"""
Giving a django request, return the current http url, possibly ignoring some GET parameters
:param django.http.HttpRequest request: The current request object.
:param set ignore_params: An optional set of GET parameters to ignore
... | python | {
"resource": ""
} |
q237049 | update_url | train | def update_url(url, params):
"""
update parameters using ``params`` in the ``url`` query string
:param url: An URL possibily with a querystring
:type url: :obj:`unicode` or :obj:`str`
:param dict params: A dictionary of parameters for updating the url querystring
:return: Th... | python | {
"resource": ""
} |
q237050 | unpack_nested_exception | train | def unpack_nested_exception(error):
"""
If exception are stacked, return the first one
:param error: A python exception with possible exception embeded within
:return: A python exception with no exception embeded within
"""
i = 0
while True:
if error.args[i:]:
... | python | {
"resource": ""
} |
q237051 | _gen_ticket | train | def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN):
"""
Generate a ticket with prefix ``prefix`` and length ``lg``
:param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU)
:param int lg: The length of the generated ticket (with the prefix)
:return: A randomll... | python | {
"resource": ""
} |
q237052 | crypt_salt_is_valid | train | def crypt_salt_is_valid(salt):
"""
Validate a salt as crypt salt
:param str salt: a password salt
:return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise
:rtype: bool
"""
if len(salt) < 2:
return False
else:
if salt[0] == '... | python | {
"resource": ""
} |
q237053 | check_password | train | def check_password(method, password, hashed_password, charset):
"""
Check that ``password`` match `hashed_password` using ``method``,
assuming the encoding is ``charset``.
:param str method: on of ``"crypt"``, ``"ldap"``, ``"hex_md5"``, ``"hex_sha1"``,
``"hex_sha224"``, ``"hex_s... | python | {
"resource": ""
} |
q237054 | last_version | train | def last_version():
"""
Fetch the last version from pypi and return it. On successful fetch from pypi, the response
is cached 24h, on error, it is cached 10 min.
:return: the last django-cas-server version
:rtype: unicode
"""
try:
last_update, version, success = last... | python | {
"resource": ""
} |
q237055 | regexpr_validator | train | def regexpr_validator(value):
"""
Test that ``value`` is a valid regular expression
:param unicode value: A regular expression to test
:raises ValidationError: if ``value`` is not a valid regular expression
"""
try:
re.compile(value)
except re.error:
raise Valida... | python | {
"resource": ""
} |
q237056 | LdapHashUserPassword.hash | train | def hash(cls, scheme, password, salt=None, charset="utf8"):
"""
Hash ``password`` with ``scheme`` using ``salt``.
This three variable beeing encoded in ``charset``.
:param bytes scheme: A valid scheme
:param bytes password: A byte string to hash using ``scheme``
... | python | {
"resource": ""
} |
q237057 | LdapHashUserPassword.get_salt | train | def get_salt(cls, hashed_passord):
"""
Return the salt of ``hashed_passord`` possibly empty
:param bytes hashed_passord: A hashed password
:return: The salt used by the hashed password (empty if no salt is used)
:rtype: bytes
:raises BadHash: if no va... | python | {
"resource": ""
} |
q237058 | visit_snippet_latex | train | def visit_snippet_latex(self, node):
"""
Latex document generator visit handler
"""
code = node.rawsource.rstrip('\n')
lang = self.hlsettingstack[-1][0]
linenos = code.count('\n') >= self.hlsettingstack[-1][1] - 1
fname = node['filename']
highlight_args = node.get('highlight_args', {})
... | python | {
"resource": ""
} |
q237059 | LogoutMixin.logout | train | def logout(self, all_session=False):
"""
effectively destroy a CAS session
:param boolean all_session: If ``True`` destroy all the user sessions, otherwise
destroy the current user session.
:return: The number of destroyed sessions
:rtype: int
... | python | {
"resource": ""
} |
q237060 | FederateAuth.get_cas_client | train | def get_cas_client(self, request, provider, renew=False):
"""
return a CAS client object matching provider
:param django.http.HttpRequest request: The current request object
:param cas_server.models.FederatedIendityProvider provider: the user identity provider
:r... | python | {
"resource": ""
} |
q237061 | FederateAuth.post | train | def post(self, request, provider=None):
"""
method called on POST request
:param django.http.HttpRequest request: The current request object
:param unicode provider: Optional parameter. The user provider suffix.
"""
# if settings.CAS_FEDERATE is not True redi... | python | {
"resource": ""
} |
q237062 | FederateAuth.get | train | def get(self, request, provider=None):
"""
method called on GET request
:param django.http.HttpRequestself. request: The current request object
:param unicode provider: Optional parameter. The user provider suffix.
"""
# if settings.CAS_FEDERATE is not True r... | python | {
"resource": ""
} |
q237063 | LoginView.init_post | train | def init_post(self, request):
"""
Initialize POST received parameters
:param django.http.HttpRequest request: The current request object
"""
self.request = request
self.service = request.POST.get('service')
self.renew = bool(request.POST.get('renew') and ... | python | {
"resource": ""
} |
q237064 | LoginView.gen_lt | train | def gen_lt(self):
"""Generate a new LoginTicket and add it to the list of valid LT for the user"""
self.request.session['lt'] = self.request.session.get('lt', []) + [utils.gen_lt()]
if len(self.request.session['lt']) > 100:
self.request.session['lt'] = self.request.session['lt'][-100... | python | {
"resource": ""
} |
q237065 | LoginView.check_lt | train | def check_lt(self):
"""
Check is the POSTed LoginTicket is valid, if yes invalide it
:return: ``True`` if the LoginTicket is valid, ``False`` otherwise
:rtype: bool
"""
# save LT for later check
lt_valid = self.request.session.get('lt', [])
lt... | python | {
"resource": ""
} |
q237066 | LoginView.init_get | train | def init_get(self, request):
"""
Initialize GET received parameters
:param django.http.HttpRequest request: The current request object
"""
self.request = request
self.service = request.GET.get('service')
self.renew = bool(request.GET.get('renew') and requ... | python | {
"resource": ""
} |
q237067 | LoginView.process_get | train | def process_get(self):
"""
Analyse the GET request
:return:
* :attr:`USER_NOT_AUTHENTICATED` if the user is not authenticated or is requesting
for authentication renewal
* :attr:`USER_AUTHENTICATED` if the user is authenticated and is no... | python | {
"resource": ""
} |
q237068 | LoginView.init_form | train | def init_form(self, values=None):
"""
Initialization of the good form depending of POST and GET parameters
:param django.http.QueryDict values: A POST or GET QueryDict
"""
if values:
values = values.copy()
values['lt'] = self.request.session['lt']... | python | {
"resource": ""
} |
q237069 | LoginView.service_login | train | def service_login(self):
"""
Perform login against a service
:return:
* The rendering of the ``settings.CAS_WARN_TEMPLATE`` if the user asked to be
warned before ticket emission and has not yep been warned.
* The redirection to the servi... | python | {
"resource": ""
} |
q237070 | LoginView.authenticated | train | def authenticated(self):
"""
Processing authenticated users
:return:
* The returned value of :meth:`service_login` if :attr:`service` is defined
* The rendering of ``settings.CAS_LOGGED_TEMPLATE`` otherwise
:rtype: django.http.HttpResponse
... | python | {
"resource": ""
} |
q237071 | LoginView.not_authenticated | train | def not_authenticated(self):
"""
Processing non authenticated users
:return:
* The rendering of ``settings.CAS_LOGIN_TEMPLATE`` with various messages
depending of GET/POST parameters
* The redirection to :class:`FederateAuth` if ``settin... | python | {
"resource": ""
} |
q237072 | LoginView.common | train | def common(self):
"""
Common part execute uppon GET and POST request
:return:
* The returned value of :meth:`authenticated` if the user is authenticated and
not requesting for authentication or if the authentication has just been renewed
... | python | {
"resource": ""
} |
q237073 | ValidateService.process_ticket | train | def process_ticket(self):
"""
fetch the ticket against the database and check its validity
:raises ValidateError: if the ticket is not found or not valid, potentially for that
service
:returns: A couple (ticket, proxies list)
:rtype: :obj:`tuple`
... | python | {
"resource": ""
} |
q237074 | ValidateService.process_pgturl | train | def process_pgturl(self, params):
"""
Handle PGT request
:param dict params: A template context dict
:raises ValidateError: if pgtUrl is invalid or if TLS validation of the pgtUrl fails
:return: The rendering of ``cas_server/serviceValidate.xml``, using ``params`... | python | {
"resource": ""
} |
q237075 | Proxy.process_proxy | train | def process_proxy(self):
"""
handle PT request
:raises ValidateError: if the PGT is not found, or the target service not allowed or
the user not allowed on the tardet service.
:return: The rendering of ``cas_server/proxy.xml``
:rtype: django.http.... | python | {
"resource": ""
} |
q237076 | SamlValidate.process_ticket | train | def process_ticket(self):
"""
validate ticket from SAML XML body
:raises: SamlValidateError: if the ticket is not found or not valid, or if we fail
to parse the posted XML.
:return: a ticket object
:rtype: :class:`models.Ticket<cas_server.models.T... | python | {
"resource": ""
} |
q237077 | main | train | def main(source):
"""
For a given command line supplied argument, negotiate the content, parse
the schema and then return any issues to stdout or if no schema issues,
return success exit code.
"""
if source is None:
click.echo(
"You need to supply a file or url to a schema to... | python | {
"resource": ""
} |
q237078 | load_source | train | def load_source(source):
"""
Common entry point for loading some form of raw swagger schema.
Supports:
- python object (dictionary-like)
- path to yaml file
- path to json file
- file object (json or yaml).
- json string.
- yaml string.
"""
if isinsta... | python | {
"resource": ""
} |
q237079 | validate | train | def validate(raw_schema, target=None, **kwargs):
"""
Given the python representation of a JSONschema as defined in the swagger
spec, validate that the schema complies to spec. If `target` is provided,
that target will be validated against the provided schema.
"""
schema = schema_validator(raw_s... | python | {
"resource": ""
} |
q237080 | validate_api_response | train | def validate_api_response(schema, raw_response, request_method='get', raw_request=None):
"""
Validate the response of an api call against a swagger schema.
"""
request = None
if raw_request is not None:
request = normalize_request(raw_request)
response = None
if raw_response is not ... | python | {
"resource": ""
} |
q237081 | find_parameter | train | def find_parameter(parameters, **kwargs):
"""
Given a list of parameters, find the one with the given name.
"""
matching_parameters = filter_parameters(parameters, **kwargs)
if len(matching_parameters) == 1:
return matching_parameters[0]
elif len(matching_parameters) > 1:
raise M... | python | {
"resource": ""
} |
q237082 | merge_parameter_lists | train | def merge_parameter_lists(*parameter_definitions):
"""
Merge multiple lists of parameters into a single list. If there are any
duplicate definitions, the last write wins.
"""
merged_parameters = {}
for parameter_list in parameter_definitions:
for parameter in parameter_list:
... | python | {
"resource": ""
} |
q237083 | validate_status_code_to_response_definition | train | def validate_status_code_to_response_definition(response, operation_definition):
"""
Given a response, validate that the response status code is in the accepted
status codes defined by this endpoint.
If so, return the response definition that corresponds to the status code.
"""
status_code = re... | python | {
"resource": ""
} |
q237084 | generate_path_validator | train | def generate_path_validator(api_path, path_definition, parameters,
context, **kwargs):
"""
Generates a callable for validating the parameters in a response object.
"""
path_level_parameters = dereference_parameter_list(
path_definition.get('parameters', []),
c... | python | {
"resource": ""
} |
q237085 | validate_response | train | def validate_response(response, request_method, schema):
"""
Response validation involves the following steps.
4. validate that the response status_code is in the allowed responses for
the request method.
5. validate that the response content validates against any provided
sche... | python | {
"resource": ""
} |
q237086 | construct_schema_validators | train | def construct_schema_validators(schema, context):
"""
Given a schema object, construct a dictionary of validators needed to
validate a response matching the given schema.
Special Cases:
- $ref:
These validators need to be Lazily evaluating so that circular
validation dep... | python | {
"resource": ""
} |
q237087 | validate_type | train | def validate_type(value, types, **kwargs):
"""
Validate that the value is one of the provided primative types.
"""
if not is_value_of_any_type(value, types):
raise ValidationError(MESSAGES['type']['invalid'].format(
repr(value), get_type_for_value(value), types,
)) | python | {
"resource": ""
} |
q237088 | generate_type_validator | train | def generate_type_validator(type_, **kwargs):
"""
Generates a callable validator for the given type or iterable of types.
"""
if is_non_string_iterable(type_):
types = tuple(type_)
else:
types = (type_,)
# support x-nullable since Swagger 2.0 doesn't support null type
# (see ... | python | {
"resource": ""
} |
q237089 | validate_multiple_of | train | def validate_multiple_of(value, divisor, **kwargs):
"""
Given a value and a divisor, validate that the value is divisible by the
divisor.
"""
if not decimal.Decimal(str(value)) % decimal.Decimal(str(divisor)) == 0:
raise ValidationError(
MESSAGES['multiple_of']['invalid'].format(... | python | {
"resource": ""
} |
q237090 | validate_minimum | train | def validate_minimum(value, minimum, is_exclusive, **kwargs):
"""
Validator function for validating that a value does not violate it's
minimum allowed value. This validation can be inclusive, or exclusive of
the minimum depending on the value of `is_exclusive`.
"""
if is_exclusive:
comp... | python | {
"resource": ""
} |
q237091 | generate_minimum_validator | train | def generate_minimum_validator(minimum, exclusiveMinimum=False, **kwargs):
"""
Generator function returning a callable for minimum value validation.
"""
return functools.partial(validate_minimum, minimum=minimum, is_exclusive=exclusiveMinimum) | python | {
"resource": ""
} |
q237092 | validate_maximum | train | def validate_maximum(value, maximum, is_exclusive, **kwargs):
"""
Validator function for validating that a value does not violate it's
maximum allowed value. This validation can be inclusive, or exclusive of
the maximum depending on the value of `is_exclusive`.
"""
if is_exclusive:
comp... | python | {
"resource": ""
} |
q237093 | generate_maximum_validator | train | def generate_maximum_validator(maximum, exclusiveMaximum=False, **kwargs):
"""
Generator function returning a callable for maximum value validation.
"""
return functools.partial(validate_maximum, maximum=maximum, is_exclusive=exclusiveMaximum) | python | {
"resource": ""
} |
q237094 | validate_min_items | train | def validate_min_items(value, minimum, **kwargs):
"""
Validator for ARRAY types to enforce a minimum number of items allowed for
the ARRAY to be valid.
"""
if len(value) < minimum:
raise ValidationError(
MESSAGES['min_items']['invalid'].format(
minimum, len(value)... | python | {
"resource": ""
} |
q237095 | validate_max_items | train | def validate_max_items(value, maximum, **kwargs):
"""
Validator for ARRAY types to enforce a maximum number of items allowed for
the ARRAY to be valid.
"""
if len(value) > maximum:
raise ValidationError(
MESSAGES['max_items']['invalid'].format(
maximum, len(value)... | python | {
"resource": ""
} |
q237096 | validate_unique_items | train | def validate_unique_items(value, **kwargs):
"""
Validator for ARRAY types to enforce that all array items must be unique.
"""
# we can't just look at the items themselves since 0 and False are treated
# the same as dictionary keys, and objects aren't hashable.
counter = collections.Counter((
... | python | {
"resource": ""
} |
q237097 | validate_object | train | def validate_object(obj, field_validators=None, non_field_validators=None,
schema=None, context=None):
"""
Takes a mapping and applies a mapping of validator functions to it
collecting and reraising any validation errors that occur.
"""
if schema is None:
schema = {}
... | python | {
"resource": ""
} |
q237098 | validate_request_method_to_operation | train | def validate_request_method_to_operation(request_method, path_definition):
"""
Given a request method, validate that the request method is valid for the
api path.
If so, return the operation definition related to this request method.
"""
try:
operation_definition = path_definition[reque... | python | {
"resource": ""
} |
q237099 | validate_path_to_api_path | train | def validate_path_to_api_path(path, paths, basePath='', context=None, **kwargs):
"""
Given a path, find the api_path it matches.
"""
if context is None:
context = {}
try:
api_path = match_path_to_api_path(
path_definitions=paths,
target_path=path,
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.