_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q13900 | postprocess_html | train | def postprocess_html(html, metadata):
"""Returns processed HTML to fit into the slide template format."""
if metadata.get('build_lists') and metadata['build_lists'] == 'true':
html | python | {
"resource": ""
} |
q13901 | suppress_message | train | def suppress_message(linter, checker_method, message_id_or_symbol, test_func):
"""
This wrapper allows the suppression of a message if the supplied test function
returns True. It is useful to prevent one particular message from being raised
in one particular case, while leaving the rest of the messages intact.
"""
# At some point, pylint started preferring message symbols to message IDs. However this is not done
# consistently or uniformly - occasionally there are some message IDs with no matching symbols.
# We try to work around this here by suppressing both the ID and the symbol, if we can find it.
# This also gives us compatability with a broader range of pylint versions.
# Similarly, a commit between version 1.2 and 1.3 changed where the messages are stored - see:
# https://bitbucket.org/logilab/pylint/commits/0b67f42799bed08aebb47babdc9fb0e761efc4ff#chg-reporters/__init__.py
# Therefore here, we try the new attribute name, and fall back to the old version for
# compatability with <=1.2 and >=1.3
msgs_store = getattr(linter, 'msgs_store', linter)
def | python | {
"resource": ""
} |
q13902 | SqliteStorage.lookup_full_hashes | train | def lookup_full_hashes(self, hash_values):
"""Query DB to see if hash is blacklisted"""
q = '''SELECT threat_type,platform_type,threat_entry_type, expires_at < current_timestamp AS has_expired
FROM full_hash WHERE value IN ({})
'''
output = []
with self.get_cursor() as dbc:
| python | {
"resource": ""
} |
q13903 | SqliteStorage.store_full_hash | train | def store_full_hash(self, threat_list, hash_value, cache_duration, malware_threat_type):
"""Store full hash found for the given hash prefix"""
log.info('Storing full hash %s to list %s with cache duration %s',
to_hex(hash_value), str(threat_list), cache_duration)
qi = '''INSERT OR IGNORE INTO full_hash
(value, threat_type, platform_type, threat_entry_type, malware_threat_type, downloaded_at)
VALUES
(?, ?, ?, ?, ?, current_timestamp)
'''
qu = "UPDATE full_hash SET expires_at=datetime(current_timestamp, '+{} SECONDS') \
WHERE value=? AND threat_type=? AND platform_type=? AND threat_entry_type=?"
| python | {
"resource": ""
} |
q13904 | SqliteStorage.cleanup_full_hashes | train | def cleanup_full_hashes(self, keep_expired_for=(60 * 60 * 12)):
"""Remove long expired full_hash entries."""
q = '''DELETE FROM full_hash WHERE expires_at < datetime(current_timestamp, '-{} SECONDS')
'''
| python | {
"resource": ""
} |
q13905 | SqliteStorage.get_threat_lists | train | def get_threat_lists(self):
"""Get a list of known threat lists."""
q = '''SELECT threat_type,platform_type,threat_entry_type FROM threat_list'''
output = []
with self.get_cursor() as dbc:
dbc.execute(q)
for h in dbc.fetchall():
| python | {
"resource": ""
} |
q13906 | SqliteStorage.get_client_state | train | def get_client_state(self):
"""Get a dict of known threat lists including clientState values."""
q = '''SELECT threat_type,platform_type,threat_entry_type,client_state FROM threat_list'''
output = {}
with self.get_cursor() as dbc:
dbc.execute(q)
for h in | python | {
"resource": ""
} |
q13907 | SqliteStorage.add_threat_list | train | def add_threat_list(self, threat_list):
"""Add threat list entry if it does not exist."""
q = '''INSERT OR IGNORE INTO threat_list
(threat_type, platform_type, threat_entry_type, timestamp)
VALUES
| python | {
"resource": ""
} |
q13908 | SqliteStorage.delete_threat_list | train | def delete_threat_list(self, threat_list):
"""Delete threat list entry."""
log.info('Deleting cached threat list "{}"'.format(repr(threat_list)))
q = '''DELETE FROM threat_list
WHERE threat_type=? AND platform_type=? AND threat_entry_type=?
''' | python | {
"resource": ""
} |
q13909 | SqliteStorage.hash_prefix_list_checksum | train | def hash_prefix_list_checksum(self, threat_list):
"""Returns SHA256 checksum for alphabetically-sorted concatenated list of hash prefixes"""
q = '''SELECT value FROM hash_prefix
WHERE threat_type=? AND platform_type=? AND threat_entry_type=?
ORDER BY value
'''
| python | {
"resource": ""
} |
q13910 | SqliteStorage.remove_hash_prefix_indices | train | def remove_hash_prefix_indices(self, threat_list, indices):
"""Remove records matching idices from a lexicographically-sorted local threat list."""
batch_size = 40
q = '''DELETE FROM hash_prefix
WHERE threat_type=? AND platform_type=? AND threat_entry_type=? AND value IN ({})
'''
prefixes_to_remove = self.get_hash_prefix_values_to_remove(threat_list, indices)
with self.get_cursor() as dbc:
for i in range(0, len(prefixes_to_remove), batch_size):
remove_batch = prefixes_to_remove[i:(i + batch_size)]
params = [
| python | {
"resource": ""
} |
q13911 | SqliteStorage.dump_hash_prefix_values | train | def dump_hash_prefix_values(self):
"""Export all hash prefix values.
Returns a list of known hash prefix values
"""
| python | {
"resource": ""
} |
q13912 | _check_events | train | def _check_events(tk):
"""Checks events in the queue on a given Tk instance"""
used = False
try:
# Process all enqueued events, then exit.
while True:
try:
# Get an event request from the queue.
method, args, kwargs, response_queue = tk.tk._event_queue.get_nowait()
except queue.Empty:
# No more events to process.
break
else:
# Call the event with the given arguments, and then return
# the result back to the caller via the response queue.
used = True
if tk.tk._debug >= 2:
print('Calling event from main thread:', method.__name__, args, kwargs)
try:
response_queue.put((False, method(*args, **kwargs)))
except SystemExit:
raise # Raises original SystemExit
except Exception:
| python | {
"resource": ""
} |
q13913 | SafeBrowsingList.update_hash_prefix_cache | train | def update_hash_prefix_cache(self):
"""Update locally cached threat lists."""
try:
self.storage.cleanup_full_hashes()
self.storage.commit()
self._sync_threat_lists()
self.storage.commit()
| python | {
"resource": ""
} |
q13914 | SafeBrowsingList._sync_full_hashes | train | def _sync_full_hashes(self, hash_prefixes):
"""Download full hashes matching hash_prefixes.
Also update cache expiration timestamps.
"""
client_state = self.storage.get_client_state()
self.api_client.fair_use_delay()
fh_response = self.api_client.get_full_hashes(hash_prefixes, client_state)
# update negative cache for each hash prefix
# store full hash (insert or update) with positive cache bumped up
for m in fh_response.get('matches', []):
threat_list = ThreatList(m['threatType'], m['platformType'], m['threatEntryType'])
hash_value = b64decode(m['threat']['hash'])
cache_duration = int(m['cacheDuration'].rstrip('s'))
malware_threat_type = None
for metadata in m['threatEntryMetadata'].get('entries', []):
| python | {
"resource": ""
} |
q13915 | SafeBrowsingList.lookup_url | train | def lookup_url(self, url):
"""Look up specified URL in Safe Browsing threat lists."""
if type(url) is not str:
url = url.encode('utf8')
if not url.strip():
raise ValueError("Empty input string.")
url_hashes = URL(url).hashes
try:
list_names = | python | {
"resource": ""
} |
q13916 | SafeBrowsingList._lookup_hashes | train | def _lookup_hashes(self, full_hashes):
"""Lookup URL hash in blacklists
Returns names of lists it was found in.
"""
full_hashes = list(full_hashes)
cues = [fh[0:4] for fh in full_hashes]
result = []
matching_prefixes = {}
matching_full_hashes = set()
is_potential_threat = False
# First lookup hash prefixes which match full URL hash
for (hash_prefix, negative_cache_expired) in self.storage.lookup_hash_prefix(cues):
for full_hash in full_hashes:
if full_hash.startswith(hash_prefix):
is_potential_threat = True
# consider hash prefix negative cache as expired if it is expired in at least one threat list
matching_prefixes[hash_prefix] = matching_prefixes.get(hash_prefix, False) or negative_cache_expired
matching_full_hashes.add(full_hash)
# if none matches, URL hash is clear
if not is_potential_threat:
return []
# if there is non-expired full hash, URL is blacklisted
matching_expired_threat_lists = set()
for threat_list, has_expired in self.storage.lookup_full_hashes(matching_full_hashes):
if has_expired:
matching_expired_threat_lists.add(threat_list)
else:
| python | {
"resource": ""
} |
q13917 | SafeBrowsingApiClient.get_threats_lists | train | def get_threats_lists(self):
"""Retrieve all available threat lists"""
response = self.service.threatLists().list().execute() | python | {
"resource": ""
} |
q13918 | SafeBrowsingApiClient.get_threats_update | train | def get_threats_update(self, client_state):
"""Fetch hash prefixes update for given threat list.
client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState}
"""
request_body = {
"client": {
"clientId": self.client_id,
"clientVersion": self.client_version,
},
"listUpdateRequests": [],
}
for (threat_type, platform_type, threat_entry_type), current_state in client_state.items():
request_body['listUpdateRequests'].append(
{
"threatType": threat_type,
| python | {
"resource": ""
} |
q13919 | SafeBrowsingApiClient.get_full_hashes | train | def get_full_hashes(self, prefixes, client_state):
"""Find full hashes matching hash prefixes.
client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState}
"""
request_body = {
"client": {
"clientId": self.client_id,
"clientVersion": self.client_version,
},
"clientStates": [],
"threatInfo": {
"threatTypes": [],
"platformTypes": [],
"threatEntryTypes": [],
"threatEntries": [],
}
}
for prefix in prefixes:
request_body['threatInfo']['threatEntries'].append({"hash": b64encode(prefix).decode()})
for ((threatType, platformType, threatEntryType), clientState) in client_state.items():
request_body['clientStates'].append(clientState)
if threatType not in request_body['threatInfo']['threatTypes']:
| python | {
"resource": ""
} |
q13920 | URL.hashes | train | def hashes(self):
"""Hashes of all possible permutations of the URL in canonical form"""
| python | {
"resource": ""
} |
q13921 | URL.canonical | train | def canonical(self):
"""Convert URL to its canonical form."""
def full_unescape(u):
uu = urllib.unquote(u)
if uu == u:
return uu
else:
return full_unescape(uu)
def full_unescape_to_bytes(u):
uu = urlparse.unquote_to_bytes(u)
if uu == u:
return uu
else:
return full_unescape_to_bytes(uu)
def quote(s):
safe_chars = '!"$&\'()*+,-./:;<=>?@[\\]^_`{|}~'
return urllib.quote(s, safe=safe_chars)
url = self.url.strip()
url = url.replace(b'\n', b'').replace(b'\r', b'').replace(b'\t', b'')
url = url.split(b'#', 1)[0]
if url.startswith(b'//'):
url = b'http:' + url
if len(url.split(b'://')) <= 1:
url = b'http://' + url
# at python3 work with bytes instead of string
# as URL may contain invalid unicode characters
if self.__py3 and type(url) is bytes:
url = quote(full_unescape_to_bytes(url))
else:
url = quote(full_unescape(url))
url_parts = urlparse.urlsplit(url)
| python | {
"resource": ""
} |
q13922 | URL.url_permutations | train | def url_permutations(url):
"""Try all permutations of hostname and path which can be applied
to blacklisted URLs
"""
def url_host_permutations(host):
if re.match(r'\d+\.\d+\.\d+\.\d+', host):
yield host
return
parts = host.split('.')
l = min(len(parts), 5)
if l > 4:
yield host
for i in range(l - 1):
yield '.'.join(parts[i - l:])
def url_path_permutations(path):
yield path
query = None
if '?' in path:
path, query = path.split('?', 1)
if query is not None:
yield path
path_parts = path.split('/')[0:-1]
curr_path = ''
for i in range(min(4, len(path_parts))):
curr_path = curr_path + path_parts[i] + '/'
| python | {
"resource": ""
} |
q13923 | _compare_versions | train | def _compare_versions(v1, v2):
"""
Compare two version strings and return -1, 0 or 1 depending on the equality
of the subset of matching version numbers.
The implementation is inspired by the top answer at
http://stackoverflow.com/a/1714190/997768.
"""
def normalize(v):
# strip trailing .0 or .00 or .0.0 or ...
v = re.sub(r'(\.0+)*$', '', v)
result = []
for part in v.split('.'):
# just digits
m = re.match(r'^(\d+)$', part)
if m:
result.append(int(m.group(1)))
continue
# digits letters
m = re.match(r'^(\d+)([a-zA-Z]+)$', part)
if m:
result.append(int(m.group(1)))
result.append(m.group(2))
| python | {
"resource": ""
} |
q13924 | exists | train | def exists(package):
"""
Return True if package information is available.
If ``pkg-config`` not on path, raises ``EnvironmentError``.
"""
| python | {
"resource": ""
} |
q13925 | libs | train | def libs(package, static=False):
"""
Return the LDFLAGS string returned by pkg-config.
The static specifier will also include libraries for static linking (i.e.,
includes any private libraries).
| python | {
"resource": ""
} |
q13926 | variables | train | def variables(package):
"""
Return a dictionary of all the variables defined in the .pc pkg-config file
of 'package'.
"""
_raise_if_not_exists(package)
result = _query(package, '--print-variables')
names = (x.strip() for x in | python | {
"resource": ""
} |
q13927 | installed | train | def installed(package, version):
"""
Check if the package meets the required version.
The version specifier consists of an optional comparator (one of =, ==, >,
<, >=, <=) and an arbitrarily long version number separated by dots. The
should be as you would expect, e.g. for an installed version '0.1.2' of
package 'foo':
>>> installed('foo', '==0.1.2')
True
>>> installed('foo', '<0.1')
False
>>> installed('foo', '>= 0.0.4')
True
If ``pkg-config`` not on path, raises ``EnvironmentError``.
"""
if not exists(package):
return False
number, comparator = _split_version_specifier(version)
modversion = _query(package, '--modversion')
try:
result = _compare_versions(modversion, number) | python | {
"resource": ""
} |
q13928 | parse | train | def parse(packages, static=False):
"""
Parse the output from pkg-config about the passed package or packages.
Builds a dictionary containing the 'libraries', the 'library_dirs', the
'include_dirs', and the 'define_macros' that are presented by pkg-config.
*package* is a string with space-delimited package names.
The static specifier will also include libraries for static linking (i.e.,
includes any private libraries).
If ``pkg-config`` is not on path, raises ``EnvironmentError``.
"""
for package in packages.split():
_raise_if_not_exists(package)
out = _query(packages, *_build_options('--cflags --libs', static=static))
out = out.replace('\\"', '')
result = collections.defaultdict(list)
for token in re.split(r'(?<!\\) ', out):
key = _PARSE_MAP.get(token[:2])
| python | {
"resource": ""
} |
q13929 | Connection.send | train | def send(self, data, sample_rate=None):
'''Send the data over UDP while taking the sample_rate in account
The sample rate should be a number between `0` and `1` which indicates
the probability that a message will be sent. The sample_rate is also
communicated to `statsd` so it knows what multiplier to use.
:keyword data: The data to send
:type data: dict
:keyword sample_rate: The sample rate, defaults to `1` (meaning always)
:type sample_rate: int
'''
if self._disabled:
self.logger.debug('Connection disabled, not sending data')
return False
if sample_rate is None:
sample_rate = self._sample_rate
sampled_data = {}
if sample_rate < 1:
if random.random() <= sample_rate:
# Modify the data so statsd knows our sample_rate
for stat, value in compat.iter_dict(data):
| python | {
"resource": ""
} |
q13930 | Timer.start | train | def start(self):
'''Start the timer and store the start time, this can only be executed
once per instance
It returns the timer instance so it can be chained when instantiating
| python | {
"resource": ""
} |
q13931 | Timer.intermediate | train | def intermediate(self, subname):
'''Send the time that has passed since our last measurement
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
| python | {
"resource": ""
} |
q13932 | Timer.decorate | train | def decorate(self, function_or_name):
'''Decorate a function to time the execution
The method can be called with or without a name. If no name is given
the function defaults to the name of the function.
:keyword function_or_name: The name to post to or the function to wrap
>>> from statsd import Timer
>>> timer = Timer('application_name')
>>>
>>> @timer.decorate
... def some_function():
... # resulting timer name: application_name.some_function
... pass
>>>
| python | {
"resource": ""
} |
q13933 | Timer.time | train | def time(self, subname=None, class_=None):
'''Returns a context manager to time execution of a block of code.
:keyword subname: The subname to report data to
:type subname: str
:keyword class_: The :class:`~statsd.client.Client` subclass to use
(e.g. :class:`~statsd.timer.Timer` or
:class:`~statsd.counter.Counter`)
:type class_: :class:`~statsd.client.Client`
>>> from statsd import Timer
>>> timer = Timer('application_name')
>>>
>>> with timer.time():
... # resulting timer name: application_name
| python | {
"resource": ""
} |
q13934 | Gauge.increment | train | def increment(self, subname=None, delta=1):
'''Increment the gauge with `delta`
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword delta: The delta to add to the gauge
| python | {
"resource": ""
} |
q13935 | Gauge.decrement | train | def decrement(self, subname=None, delta=1):
'''Decrement the gauge with `delta`
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword delta: The delta to remove from the gauge
| python | {
"resource": ""
} |
q13936 | Repo.aggregate | train | def aggregate(self):
""" Aggregate all merges into the target branch
If the target_dir doesn't exist, create an empty git repo otherwise
clean it, add all remotes , and merge all merges.
"""
logger.info('Start aggregation of %s', self.cwd)
target_dir = self.cwd
is_new = not os.path.exists(target_dir)
if is_new:
self.init_repository(target_dir)
self._switch_to_branch(self.target['branch'])
for r in self.remotes:
self._set_remote(**r)
self.fetch()
merges = self.merges
| python | {
"resource": ""
} |
q13937 | Repo._check_status | train | def _check_status(self):
"""Check repo status and except if dirty."""
logger.info('Checking repo status')
status = self.log_call(
['git', 'status', '--porcelain'],
| python | {
"resource": ""
} |
q13938 | Repo._fetch_options | train | def _fetch_options(self, merge):
"""Get the fetch options from the given merge dict."""
cmd = tuple()
for option in FETCH_DEFAULTS:
value = | python | {
"resource": ""
} |
q13939 | Repo.collect_prs_info | train | def collect_prs_info(self):
"""Collect all pending merge PRs info.
:returns: mapping of PRs by state
"""
REPO_RE = re.compile(
'^(https://github.com/|git@github.com:)'
'(?P<owner>.*?)/(?P<repo>.*?)(.git)?$')
PULL_RE = re.compile(
'^(refs/)?pull/(?P<pr>[0-9]+)/head$')
remotes = {r['name']: r['url'] for r in self.remotes}
all_prs = {}
for merge in self.merges:
remote = merge['remote']
ref = merge['ref']
repo_url = remotes[remote]
repo_mo = REPO_RE.match(repo_url)
if not repo_mo:
logger.debug('%s is not a github repo', repo_url)
continue
pull_mo = PULL_RE.match(ref)
if not pull_mo:
logger.debug('%s is not a github pull reqeust', ref)
continue
pr_info = {
'owner': repo_mo.group('owner'),
'repo': repo_mo.group('repo'),
'pr': pull_mo.group('pr'),
}
| python | {
"resource": ""
} |
q13940 | Repo.show_closed_prs | train | def show_closed_prs(self):
"""Log only closed PRs."""
all_prs = self.collect_prs_info()
for pr_info in all_prs.get('closed', []):
| python | {
"resource": ""
} |
q13941 | Repo.show_all_prs | train | def show_all_prs(self):
"""Log all PRs grouped by state."""
for __, prs in self.collect_prs_info().items():
for pr_info in prs:
logger.info(
| python | {
"resource": ""
} |
q13942 | load_config | train | def load_config(config, expand_env=False, force=False):
"""Return repos from a directory and fnmatch. Not recursive.
:param config: paths to config file
:type config: str
:param expand_env: True to expand environment varialbes in the config.
:type expand_env: bool
:param bool force: True to aggregate even if repo is dirty.
:returns: expanded config dict item
:rtype: iter(dict)
"""
if not os.path.exists(config):
raise ConfigException('Unable to find configuration file: %s' | python | {
"resource": ""
} |
q13943 | main | train | def main():
"""Main CLI application."""
parser = get_parser()
argcomplete.autocomplete(parser, always_complete_options=False)
args = parser.parse_args()
setup_logger(
| python | {
"resource": ""
} |
q13944 | aggregate_repo | train | def aggregate_repo(repo, args, sem, err_queue):
"""Aggregate one repo according to the args.
Args:
repo (Repo): The repository to aggregate.
args (argparse.Namespace): CLI arguments.
"""
try:
logger.debug('%s' % repo)
dirmatch = args.dirmatch
if not match_dir(repo.cwd, dirmatch):
logger.info("Skip %s", repo.cwd)
return
if args.command == 'aggregate':
repo.aggregate()
if args.do_push:
| python | {
"resource": ""
} |
q13945 | has_no_error | train | def has_no_error(
state, incorrect_msg="Your code generated an error. Fix it and try again!"
):
"""Check whether the submission did not generate a runtime error.
Simply use ``Ex().has_no_error()`` in your SCT whenever you want to check for errors.
By default, after the entire SCT finished executing, ``sqlwhat`` will check
for errors before marking the exercise as correct. You can disable this behavior
by using ``Ex().allow_error()``.
Args:
| python | {
"resource": ""
} |
q13946 | has_ncols | train | def has_ncols(
state,
incorrect_msg="Your query returned a table with {{n_stu}} column{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} column{{'s' if n_sol > 1 else ''}}.",
):
"""Test whether the student and solution query results have equal numbers of columns.
Args:
incorrect_msg: If specified, this overrides the automatically generated feedback message
in case the number of columns in the student and solution query don't match.
:Example:
Consider the following solution and SCT: ::
# solution
SELECT artist_id as id, name FROM artists
# sct
Ex().has_ncols()
# passing submission
SELECT artist_id as id, name FROM artists
# failing submission (too little columns)
SELECT artist_id as id FROM artists
| python | {
"resource": ""
} |
q13947 | check_row | train | def check_row(state, index, missing_msg=None, expand_msg=None):
"""Zoom in on a particular row in the query result, by index.
After zooming in on a row, which is represented as a single-row query result,
you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution
query result have a match in the student query result.
Args:
index: index of the row to zoom in on (zero-based indexed).
missing_msg: if specified, this overrides the automatically generated feedback
message in case the row is missing in the student query result.
expand_msg: if specified, this overrides the automatically generated feedback
message that is prepended to feedback messages that are thrown
further in the SCT chain.
:Example:
Suppose we are testing the following SELECT statements
* solution: ``SELECT artist_id as id, name FROM artists LIMIT 5``
* student : ``SELECT artist_id, name FROM artists LIMIT 2``
We can write the following SCTs: ::
# fails, since row 3 at index 2 is not in the student result
Ex().check_row(2)
# passes, since row 2 at index 1 is in the student result
Ex().check_row(0)
"""
if missing_msg is None:
missing_msg = "The | python | {
"resource": ""
} |
q13948 | check_column | train | def check_column(state, name, missing_msg=None, expand_msg=None):
"""Zoom in on a particular column in the query result, by name.
After zooming in on a column, which is represented as a single-column query result,
you can use ``has_equal_value()`` to verify whether the column in the solution query result
matches the column in student query result.
Args:
name: name of the column to zoom in on.
missing_msg: if specified, this overrides the automatically generated feedback
message in case the column is missing in the student query result.
expand_msg: if specified, this overrides the automatically generated feedback
message that is prepended to feedback messages that are thrown
further in the SCT chain.
:Example:
Suppose we are testing the following SELECT statements
* solution: ``SELECT artist_id as id, name FROM artists``
* student : ``SELECT artist_id, name FROM artists``
We can write the following SCTs: ::
# fails, since no column named id in student result
Ex().check_column('id')
# passes, since a column named name is in student_result
Ex().check_column('name')
"""
| python | {
"resource": ""
} |
q13949 | has_equal_value | train | def has_equal_value(state, ordered=False, ndigits=None, incorrect_msg=None):
"""Verify if a student and solution query result match up.
This function must always be used after 'zooming' in on certain columns or records (check_column, check_row or check_result).
``has_equal_value`` then goes over all columns that are still left in the solution query result, and compares each column with the
corresponding column in the student query result.
Args:
ordered: if set to False, the default, all rows are sorted (according
to the first column and the following columns as tie breakers).
if set to True, the order of rows in student and solution query have to match.
digits: if specified, number of decimals to use when comparing column values.
incorrect_msg: if specified, this overrides the automatically generated feedback
message in case a column in the student query result does not match
a column in the solution query result.
:Example:
Suppose we are testing the following SELECT statements
* solution: ``SELECT artist_id as id, name FROM artists ORDER BY name``
* student : ``SELECT | python | {
"resource": ""
} |
q13950 | check_query | train | def check_query(state, query, error_msg=None, expand_msg=None):
"""Run arbitrary queries against to the DB connection to verify the database state.
For queries that do not return any output (INSERTs, UPDATEs, ...),
you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result.
``check_query()`` will rerun the solution query in the transaction prepared by sqlbackend,
and immediately afterwards run the query specified in ``query``.
Next, it will also run this query after rerunning the student query in a transaction.
Finally, it produces a child state with these results, that you can then chain off of
with functions like ``check_column()`` and ``has_equal_value()``.
Args:
query: A SQL query as a string that is executed after the student query is re-executed.
error_msg: if specified, this overrides the automatically generated feedback
message in case the query generated an error.
expand_msg: if specified, this overrides the automatically generated feedback
message that is prepended to feedback messages that are thrown
further in the SCT chain.
:Example:
Suppose we are checking whether an INSERT happened correctly: ::
INSERT INTO company VALUES (2, 'filip', 28, 'sql-lane', 42)
We can write the following SCT: ::
Ex().check_query('SELECT COUNT(*) AS c FROM company').has_equal_value()
"""
if error_msg is None:
error_msg = "Running `{{query}}` after your submission generated an error." | python | {
"resource": ""
} |
q13951 | lower_case | train | def lower_case(f):
"""Decorator specifically for turning mssql AST into lowercase"""
# if it has already been wrapped, we return original
if hasattr(f, "lower_cased"):
return f | python | {
"resource": ""
} |
q13952 | try_unbuffered_file | train | def try_unbuffered_file(file, _alreadyopen={}):
""" Try re-opening a file in an unbuffered mode and return it.
If that fails, just return the original file.
This function remembers the file descriptors it opens, so it
never opens the same one twice.
This is meant for files like sys.stdout or sys.stderr.
"""
try:
fileno = file.fileno()
except (AttributeError, UnsupportedOperation):
# Unable to use fileno to re-open unbuffered. Oh well.
# The output may be line buffered, which isn't that great for
# repeatedly drawing and erasing text, or hiding/showing the cursor.
return file
filedesc | python | {
"resource": ""
} |
q13953 | WriterProcessBase._loop | train | def _loop(self):
""" This is the loop that runs in the subproces. It is called from
`run` and is responsible for all printing, text updates, and time
management.
"""
self.stop_flag.value = False
self.time_started.value = time()
self.time_elapsed.value = 0
while True:
if self.stop_flag.value:
break
| python | {
"resource": ""
} |
q13954 | WriterProcessBase.run | train | def run(self):
""" Runs the printer loop in a subprocess. This is called by
multiprocessing.
"""
try:
self._loop()
except Exception:
# Send the exception through the exc_queue, so the parent
# process | python | {
"resource": ""
} |
q13955 | WriterProcessBase.stop | train | def stop(self):
""" Stop this WriterProcessBase, and reset the cursor. """
self.stop_flag.value = True
with self.lock:
(
Control().text(C(' ', style='reset_all'))
| python | {
"resource": ""
} |
q13956 | WriterProcessBase.update_text | train | def update_text(self):
""" Write the current text, and check for any new text changes.
This also updates the elapsed time.
"""
self.write()
try:
| python | {
"resource": ""
} |
q13957 | WriterProcessBase.write | train | def write(self):
""" Write the current text to self.file, and flush it.
This can be overridden to handle custom writes.
"""
if self._text is not None:
with self.lock: | python | {
"resource": ""
} |
q13958 | WriterProcess.exception | train | def exception(self):
""" Try retrieving the last subprocess exception.
If set, the exception is returned. Otherwise None is returned.
"""
if self._exception is not None:
return self._exception
try:
exc, tblines = self.exc_queue.get_nowait()
except Empty:
| python | {
"resource": ""
} |
q13959 | StaticProgress.fmt | train | def fmt(self, value):
""" Sets self.fmt, with some extra help for plain format strings. """
if isinstance(value, str):
value = value.split(self.join_str)
if not (value and isinstance(value, (list, tuple))):
raise TypeError(
' '.join((
'Expecting str or list/tuple of formats {!r}.',
| python | {
"resource": ""
} |
q13960 | StaticProgress.run | train | def run(self):
""" Overrides WriterProcess.run, to handle KeyboardInterrupts better.
This should not be called by any user. `multiprocessing` calls
this in a subprocess.
Use `self.start` to start this instance.
"""
try: | python | {
"resource": ""
} |
q13961 | StaticProgress.stop | train | def stop(self):
""" Stop this animated progress, and block until it is finished. """
super().stop()
while not self.stopped:
# stop() should block, so printing afterwards isn't interrupted.
sleep(0.001)
| python | {
"resource": ""
} |
q13962 | StaticProgress.write | train | def write(self):
""" Writes a single frame of the progress spinner to the terminal.
This function updates the current frame before returning.
"""
if self.text is None:
# Text has not been sent through the pipe yet.
# Do not write anything until it is set to non-None value.
return None
if self._last_text == self.text:
char_delay = 0
else:
char_delay = self.char_delay
| python | {
"resource": ""
} |
q13963 | AnimatedProgress._advance_frame | train | def _advance_frame(self):
""" Sets `self.current_frame` to the next frame, looping to the
| python | {
"resource": ""
} |
q13964 | AnimatedProgress.write_char_delay | train | def write_char_delay(self, ctl, delay):
""" Write the formatted format pieces in order, applying a delay
between characters for the text only.
"""
for i, fmt in enumerate(self.fmt):
if '{text' in fmt:
# The text will use a write delay.
ctl.text(fmt.format(text=self.text))
if i != (self.fmt_len - 1):
ctl.text(self.join_str)
ctl.write(
file=self.file,
delay=delay
)
else:
# Anything else is written with no delay.
ctl.text(fmt.format(
| python | {
"resource": ""
} |
q13965 | ProgressBar.update | train | def update(self, percent=None, text=None):
""" Update the progress bar percentage and message. """
if percent is not None:
self.percent = percent
| python | {
"resource": ""
} |
q13966 | cls_get_by_name | train | def cls_get_by_name(cls, name):
""" Return a class attribute by searching the attributes `name` attribute.
"""
try:
val = getattr(cls, name)
except AttributeError:
for attr in (a for a in dir(cls) if not a.startswith('_')):
try:
val = getattr(cls, attr)
except AttributeError:
# Is known to happen.
continue
| python | {
"resource": ""
} |
q13967 | cls_names | train | def cls_names(cls, wanted_cls, registered=True):
""" Return a list of attributes for all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type.
| python | {
"resource": ""
} |
q13968 | cls_sets | train | def cls_sets(cls, wanted_cls, registered=True):
""" Return a list of all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type.
"""
sets = []
for attr in dir(cls):
if attr.startswith('_'):
continue
val = | python | {
"resource": ""
} |
q13969 | _build_color_variants | train | def _build_color_variants(cls):
""" Build colorized variants of all frames and return a list of
all frame object names.
"""
# Get the basic frame types first.
frametypes = cls.sets(registered=False)
_colornames = [
# 'black', disabled for now, it won't show on my terminal.
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white',
]
_colornames.extend('light{}'.format(s) | python | {
"resource": ""
} |
q13970 | FrameSet.from_barset | train | def from_barset(
cls, barset, name=None, delay=None,
use_wrapper=True, wrapper=None):
""" Copy a BarSet's frames to create a new FrameSet.
Arguments:
barset : An existing BarSet object to copy frames from.
name : A name for the new FrameSet.
delay : Delay for the animation.
use_wrapper : Whether to use the old barset's wrapper in the
frames.
wrapper : A new wrapper pair to use for each frame.
This overrides the `use_wrapper` option.
"""
if wrapper:
| python | {
"resource": ""
} |
q13971 | BarSet.as_rainbow | train | def as_rainbow(self, offset=35, style=None, rgb_mode=False):
""" Wrap each frame in a Colr object, using `Colr.rainbow`. """
| python | {
"resource": ""
} |
q13972 | BarSet._generate_move | train | def _generate_move(
cls, char, width=None, fill_char=None,
bounce=False, reverse=True, back_char=None):
""" Yields strings that simulate movement of a character from left
to right. For use with `BarSet.from_char`.
Arguments:
char : Character to move across the progress bar.
width : Width for the progress bar.
Default: cls.default_width
fill_char : String for empty space.
Default: cls.default_fill_char
bounce : Whether to move the character in both
directions.
reverse : Whether to start on the right side.
back_char : Character to use for the bounce's backward
movement.
Default: `char`
"""
width = width or cls.default_width
char = str(char)
filler = str(fill_char or cls.default_fill_char) * | python | {
"resource": ""
} |
q13973 | BaseTransport.set_write_buffer_limits | train | def set_write_buffer_limits(self, high=None, low=None):
"""Set the low and high watermark for the write buffer."""
if high is None:
high = self.write_buffer_size
if low is None:
| python | {
"resource": ""
} |
q13974 | BaseTransport.close | train | def close(self):
"""Close the transport after all oustanding data has been written."""
if self._closing or self._handle.closed:
return
elif self._protocol is None:
raise TransportError('transport not started')
# If the write buffer is empty, close now. Otherwise defer to
# _on_write_complete that will close when | python | {
"resource": ""
} |
q13975 | BaseTransport.abort | train | def abort(self):
"""Close the transport immediately."""
if self._handle.closed:
return
elif self._protocol is None:
| python | {
"resource": ""
} |
q13976 | Transport.write_eof | train | def write_eof(self):
"""Shut down the write direction of the transport."""
self._check_status()
if not self._writable:
raise TransportError('transport is not writable')
if self._closing:
raise TransportError('transport is closing')
try:
| python | {
"resource": ""
} |
q13977 | Transport.get_extra_info | train | def get_extra_info(self, name, default=None):
"""Get transport specific data.
In addition to the fields from :meth:`BaseTransport.get_extra_info`,
the following information is also available:
===================== ===================================================
Name Description
===================== ===================================================
``'sockname'`` The socket name i.e. the result of the
``getsockname()`` system call.
``'peername'`` The peer name i.e. the result of the
``getpeername()`` system call.
``'winsize'`` The terminal window size as a ``(cols, rows)``
tuple. Only available for :class:`pyuv.TTY`
handles.
``'unix_creds'`` The Unix credentials of the peer as a
``(pid, uid, gid)`` tuple. Only available for
:class:`pyuv.Pipe` handles on Unix.
``'server_hostname'`` The host name of the remote peer prior to
address resolution, if applicable.
===================== ===================================================
"""
if name == 'sockname':
if not hasattr(self._handle, 'getsockname'):
return default
try:
return self._handle.getsockname()
except pyuv.error.UVError:
return default
elif name == 'peername':
if not hasattr(self._handle, 'getpeername'):
return default
try:
return self._handle.getpeername()
except pyuv.error.UVError:
return default
elif name == 'winsize':
if not hasattr(self._handle, 'get_winsize'): | python | {
"resource": ""
} |
q13978 | parse_dbus_address | train | def parse_dbus_address(address):
"""Parse a D-BUS address string into a list of addresses."""
if address == 'session':
address = os.environ.get('DBUS_SESSION_BUS_ADDRESS')
if not address:
raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set')
elif address == 'system':
address = os.environ.get('DBUS_SYSTEM_BUS_ADDRESS',
'unix:path=/var/run/dbus/system_bus_socket')
addresses = []
for addr in address.split(';'):
p1 = addr.find(':')
if p1 == -1:
raise ValueError('illegal address string: {}'.format(addr))
kind = addr[:p1]
args = dict((kv.split('=') for kv in addr[p1+1:].split(',')))
if kind == 'unix':
if 'path' in args:
addr = args['path']
elif 'abstract' in args:
addr = '\0' + args['abstract']
| python | {
"resource": ""
} |
q13979 | parse_dbus_header | train | def parse_dbus_header(header):
"""Parse a D-BUS header. Return the message size."""
if six.indexbytes(header, 0) == ord('l'):
endian = '<'
elif six.indexbytes(header, 0) == ord('B'):
endian = '>'
else:
raise ValueError('illegal endianness')
if not 1 <= six.indexbytes(header, 1) <= 4:
raise ValueError('illegel message type')
if struct.unpack(endian + 'I', header[8:12])[0] == 0:
| python | {
"resource": ""
} |
q13980 | TxdbusAuthenticator.getMechanismName | train | def getMechanismName(self):
"""Return the authentication mechanism name."""
if self._server_side:
mech = self._authenticator.current_mech
| python | {
"resource": ""
} |
q13981 | DbusProtocol.get_unique_name | train | def get_unique_name(self):
"""Return the unique name of the D-BUS connection."""
self._name_acquired.wait()
| python | {
"resource": ""
} |
q13982 | DbusProtocol.send_message | train | def send_message(self, message):
"""Send a D-BUS message.
The *message* argument must be ``gruvi.txdbus.DbusMessage`` instance.
"""
if not isinstance(message, txdbus.DbusMessage):
raise TypeError('message: expecting DbusMessage instance (got {!r})',
| python | {
"resource": ""
} |
q13983 | DbusProtocol.call_method | train | def call_method(self, service, path, interface, method, signature=None,
args=None, no_reply=False, auto_start=False, timeout=-1):
"""Call a D-BUS method and wait for its reply.
This method calls the D-BUS method with name *method* that resides on
the object at bus address *service*, at path *path*, on interface
*interface*.
The *signature* and *args* are optional arguments that can be used to
add parameters to the method call. The signature is a D-BUS signature
string, while *args* must be a sequence of python types that can be
converted into the types specified by the signature. See the `D-BUS
specification
<http://dbus.freedesktop.org/doc/dbus-specification.html>`_ for a
reference on signature strings.
The flags *no_reply* and *auto_start* control the NO_REPLY_EXPECTED and
NO_AUTO_START flags on the D-BUS message.
The return value is the result of the D-BUS method call. This will be a
possibly empty sequence of values.
"""
message = txdbus.MethodCallMessage(path, method, interface=interface,
destination=service, signature=signature, body=args,
| python | {
"resource": ""
} |
q13984 | docfrom | train | def docfrom(base):
"""Decorator to set a function's docstring from another function."""
| python | {
"resource": ""
} |
q13985 | objref | train | def objref(obj):
"""Return a string that uniquely and compactly identifies an object."""
ref = _objrefs.get(obj)
if ref is None:
clsname = obj.__class__.__name__.split('.')[-1]
seqno = _lastids.setdefault(clsname, 1) | python | {
"resource": ""
} |
q13986 | delegate_method | train | def delegate_method(other, method, name=None):
"""Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argument specifies a method to delegate
to. It can be any callable as long as it takes the instances as its first
argument.
It is a common paradigm in Gruvi to expose protocol methods onto clients.
This keeps most of the logic into the protocol, but prevents the user from
having to type ``'client.protocol.*methodname*'`` all the time.
For example::
class MyClient(Client):
protocol = Client.protocol
delegate_method(protocol, MyProtocol.method)
"""
frame = sys._getframe(1)
classdict = frame.f_locals
@functools.wraps(method)
def delegate(self, *args, **kwargs):
other_self = other.__get__(self)
return method(other_self, *args, **kwargs)
if getattr(method, '__switchpoint__', False):
delegate.__switchpoint__ = True
if name is None:
name = method.__name__
propname = None
for key in classdict:
if classdict[key] is other:
| python | {
"resource": ""
} |
q13987 | accept_ws | train | def accept_ws(buf, pos):
"""Skip whitespace at the current buffer position."""
match = re_ws.match(buf, pos)
if not match:
| python | {
"resource": ""
} |
q13988 | accept_lit | train | def accept_lit(char, buf, pos):
"""Accept a literal character at the current buffer position."""
if pos >= | python | {
"resource": ""
} |
q13989 | expect_lit | train | def expect_lit(char, buf, pos):
"""Expect a literal character at the current buffer position."""
if pos >= | python | {
"resource": ""
} |
q13990 | accept_re | train | def accept_re(regexp, buf, pos):
"""Accept a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
| python | {
"resource": ""
} |
q13991 | expect_re | train | def expect_re(regexp, buf, pos):
"""Require a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
| python | {
"resource": ""
} |
q13992 | parse_content_type | train | def parse_content_type(header):
"""Parse the "Content-Type" header."""
typ = subtyp = None; options = {}
typ, pos = expect_re(re_token, header, 0)
_, pos = expect_lit('/', header, pos)
subtyp, pos = expect_re(re_token, header, pos)
ctype = header[:pos] if subtyp else ''
while pos < len(header):
_, pos = accept_ws(header, pos)
_, pos = expect_lit(';', header, pos)
_, pos = accept_ws(header, pos)
name, pos = expect_re(re_token, header, pos)
_, pos = expect_lit('=', header, pos)
char = lookahead(header, pos)
| python | {
"resource": ""
} |
q13993 | parse_te | train | def parse_te(header):
"""Parse the "TE" header."""
pos = 0
names = []
while pos < len(header):
name, pos = expect_re(re_token, header, pos)
_, pos = accept_ws(header, pos)
_, pos = accept_lit(';', header, pos)
_, pos = accept_ws(header, pos)
qvalue, pos = accept_re(re_qvalue, header, pos)
| python | {
"resource": ""
} |
q13994 | parse_trailer | train | def parse_trailer(header):
"""Parse the "Trailer" header."""
pos = 0
names = []
while pos < len(header):
name, pos = expect_re(re_token, header, pos)
if name:
names.append(name)
_, pos = | python | {
"resource": ""
} |
q13995 | parse_url | train | def parse_url(url, default_scheme='http', is_connect=False):
"""Parse an URL and return its components.
The *default_scheme* argument specifies the scheme in case URL is
an otherwise valid absolute URL but with a missing scheme.
The *is_connect* argument must be set to ``True`` if the URL was requested
with the HTTP CONNECT method. These URLs have a different form and need to
be parsed differently.
The result is a :class:`ParsedUrl` containing the URL components.
"""
# If this is not in origin-form, authority-form or asterisk-form and no
# scheme is present, assume it's in absolute-form with a missing scheme.
# See RFC7230 section 5.3.
if url[:1] not in '*/' and not is_connect and '://' not in url:
| python | {
"resource": ""
} |
q13996 | create_chunk | train | def create_chunk(buf):
"""Create a chunk for the HTTP "chunked" transfer encoding."""
chunk = []
chunk.append(s2b('{:X}\r\n'.format(len(buf)))) | python | {
"resource": ""
} |
q13997 | create_chunked_body_end | train | def create_chunked_body_end(trailers=None):
"""Create the ending that terminates a chunked body."""
chunk = []
chunk.append('0\r\n')
if trailers:
for name, value in trailers:
chunk.append(name)
| python | {
"resource": ""
} |
q13998 | create_request | train | def create_request(version, method, url, headers):
"""Create a HTTP request header."""
# According to my measurements using b''.join is faster that constructing a
# bytearray.
message = [] | python | {
"resource": ""
} |
q13999 | create_response | train | def create_response(version, status, headers):
"""Create a HTTP response header."""
message = []
message.append('HTTP/{} {}\r\n'.format(version, status))
for name, value in headers:
message.append(name)
message.append(': ')
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.