labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2
values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4
values | answer stringlengths 2 905 | src stringclasses 3
values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What do the parent directory contain ?
| def makedirs(path, owner=None, grant_perms=None, deny_perms=None, inheritance=True):
path = os.path.expanduser(path)
dirname = os.path.normpath(os.path.dirname(path))
if os.path.isdir(dirname):
msg = "Directory '{0}' already exists".format(dirname)
log.debug(msg)
return msg
if os.path.exists(dirname):
msg = "The path '{0}' already exists and is not a directory".format(dirname)
log.debug(msg)
return msg
directories_to_create = []
while True:
if os.path.isdir(dirname):
break
directories_to_create.append(dirname)
current_dirname = dirname
dirname = os.path.dirname(dirname)
if (current_dirname == dirname):
raise SaltInvocationError("Recursive creation for path '{0}' would result in an infinite loop. Please use an absolute path.".format(dirname))
directories_to_create.reverse()
for directory_to_create in directories_to_create:
log.debug('Creating directory: %s', directory_to_create)
mkdir(path, owner, grant_perms, deny_perms, inheritance)
| null | null | null | this path
| codeqa | def makedirs path owner None grant perms None deny perms None inheritance True path os path expanduser path dirname os path normpath os path dirname path if os path isdir dirname msg " Directory'{ 0 }'alreadyexists" format dirname log debug msg return msgif os path exists dirname msg " Thepath'{ 0 }'alreadyexistsandisnotadirectory" format dirname log debug msg return msgdirectories to create []while True if os path isdir dirname breakdirectories to create append dirname current dirname dirnamedirname os path dirname dirname if current dirname dirname raise Salt Invocation Error " Recursivecreationforpath'{ 0 }'wouldresultinaninfiniteloop Pleaseuseanabsolutepath " format dirname directories to create reverse for directory to create in directories to create log debug ' Creatingdirectory %s' directory to create mkdir path owner grant perms deny perms inheritance
| null | null | null | null | Question:
What do the parent directory contain ?
Code:
def makedirs(path, owner=None, grant_perms=None, deny_perms=None, inheritance=True):
path = os.path.expanduser(path)
dirname = os.path.normpath(os.path.dirname(path))
if os.path.isdir(dirname):
msg = "Directory '{0}' already exists".format(dirname)
log.debug(msg)
return msg
if os.path.exists(dirname):
msg = "The path '{0}' already exists and is not a directory".format(dirname)
log.debug(msg)
return msg
directories_to_create = []
while True:
if os.path.isdir(dirname):
break
directories_to_create.append(dirname)
current_dirname = dirname
dirname = os.path.dirname(dirname)
if (current_dirname == dirname):
raise SaltInvocationError("Recursive creation for path '{0}' would result in an infinite loop. Please use an absolute path.".format(dirname))
directories_to_create.reverse()
for directory_to_create in directories_to_create:
log.debug('Creating directory: %s', directory_to_create)
mkdir(path, owner, grant_perms, deny_perms, inheritance)
|
null | null | null | What is containing this path ?
| def makedirs(path, owner=None, grant_perms=None, deny_perms=None, inheritance=True):
path = os.path.expanduser(path)
dirname = os.path.normpath(os.path.dirname(path))
if os.path.isdir(dirname):
msg = "Directory '{0}' already exists".format(dirname)
log.debug(msg)
return msg
if os.path.exists(dirname):
msg = "The path '{0}' already exists and is not a directory".format(dirname)
log.debug(msg)
return msg
directories_to_create = []
while True:
if os.path.isdir(dirname):
break
directories_to_create.append(dirname)
current_dirname = dirname
dirname = os.path.dirname(dirname)
if (current_dirname == dirname):
raise SaltInvocationError("Recursive creation for path '{0}' would result in an infinite loop. Please use an absolute path.".format(dirname))
directories_to_create.reverse()
for directory_to_create in directories_to_create:
log.debug('Creating directory: %s', directory_to_create)
mkdir(path, owner, grant_perms, deny_perms, inheritance)
| null | null | null | the parent directory
| codeqa | def makedirs path owner None grant perms None deny perms None inheritance True path os path expanduser path dirname os path normpath os path dirname path if os path isdir dirname msg " Directory'{ 0 }'alreadyexists" format dirname log debug msg return msgif os path exists dirname msg " Thepath'{ 0 }'alreadyexistsandisnotadirectory" format dirname log debug msg return msgdirectories to create []while True if os path isdir dirname breakdirectories to create append dirname current dirname dirnamedirname os path dirname dirname if current dirname dirname raise Salt Invocation Error " Recursivecreationforpath'{ 0 }'wouldresultinaninfiniteloop Pleaseuseanabsolutepath " format dirname directories to create reverse for directory to create in directories to create log debug ' Creatingdirectory %s' directory to create mkdir path owner grant perms deny perms inheritance
| null | null | null | null | Question:
What is containing this path ?
Code:
def makedirs(path, owner=None, grant_perms=None, deny_perms=None, inheritance=True):
path = os.path.expanduser(path)
dirname = os.path.normpath(os.path.dirname(path))
if os.path.isdir(dirname):
msg = "Directory '{0}' already exists".format(dirname)
log.debug(msg)
return msg
if os.path.exists(dirname):
msg = "The path '{0}' already exists and is not a directory".format(dirname)
log.debug(msg)
return msg
directories_to_create = []
while True:
if os.path.isdir(dirname):
break
directories_to_create.append(dirname)
current_dirname = dirname
dirname = os.path.dirname(dirname)
if (current_dirname == dirname):
raise SaltInvocationError("Recursive creation for path '{0}' would result in an infinite loop. Please use an absolute path.".format(dirname))
directories_to_create.reverse()
for directory_to_create in directories_to_create:
log.debug('Creating directory: %s', directory_to_create)
mkdir(path, owner, grant_perms, deny_perms, inheritance)
|
null | null | null | What does the code make ?
| def guess_spatial_dimensions(image):
if (image.ndim == 2):
return 2
if ((image.ndim == 3) and (image.shape[(-1)] != 3)):
return 3
if ((image.ndim == 3) and (image.shape[(-1)] == 3)):
return None
if ((image.ndim == 4) and (image.shape[(-1)] == 3)):
return 3
else:
raise ValueError(('Expected 2D, 3D, or 4D array, got %iD.' % image.ndim))
| null | null | null | an educated guess about whether an image has a channels dimension
| codeqa | def guess spatial dimensions image if image ndim 2 return 2if image ndim 3 and image shape[ -1 ] 3 return 3if image ndim 3 and image shape[ -1 ] 3 return Noneif image ndim 4 and image shape[ -1 ] 3 return 3else raise Value Error ' Expected 2 D 3D or 4 Darray got%i D ' % image ndim
| null | null | null | null | Question:
What does the code make ?
Code:
def guess_spatial_dimensions(image):
if (image.ndim == 2):
return 2
if ((image.ndim == 3) and (image.shape[(-1)] != 3)):
return 3
if ((image.ndim == 3) and (image.shape[(-1)] == 3)):
return None
if ((image.ndim == 4) and (image.shape[(-1)] == 3)):
return 3
else:
raise ValueError(('Expected 2D, 3D, or 4D array, got %iD.' % image.ndim))
|
null | null | null | What does an image have ?
| def guess_spatial_dimensions(image):
if (image.ndim == 2):
return 2
if ((image.ndim == 3) and (image.shape[(-1)] != 3)):
return 3
if ((image.ndim == 3) and (image.shape[(-1)] == 3)):
return None
if ((image.ndim == 4) and (image.shape[(-1)] == 3)):
return 3
else:
raise ValueError(('Expected 2D, 3D, or 4D array, got %iD.' % image.ndim))
| null | null | null | a channels dimension
| codeqa | def guess spatial dimensions image if image ndim 2 return 2if image ndim 3 and image shape[ -1 ] 3 return 3if image ndim 3 and image shape[ -1 ] 3 return Noneif image ndim 4 and image shape[ -1 ] 3 return 3else raise Value Error ' Expected 2 D 3D or 4 Darray got%i D ' % image ndim
| null | null | null | null | Question:
What does an image have ?
Code:
def guess_spatial_dimensions(image):
if (image.ndim == 2):
return 2
if ((image.ndim == 3) and (image.shape[(-1)] != 3)):
return 3
if ((image.ndim == 3) and (image.shape[(-1)] == 3)):
return None
if ((image.ndim == 4) and (image.shape[(-1)] == 3)):
return 3
else:
raise ValueError(('Expected 2D, 3D, or 4D array, got %iD.' % image.ndim))
|
null | null | null | What has a channels dimension ?
| def guess_spatial_dimensions(image):
if (image.ndim == 2):
return 2
if ((image.ndim == 3) and (image.shape[(-1)] != 3)):
return 3
if ((image.ndim == 3) and (image.shape[(-1)] == 3)):
return None
if ((image.ndim == 4) and (image.shape[(-1)] == 3)):
return 3
else:
raise ValueError(('Expected 2D, 3D, or 4D array, got %iD.' % image.ndim))
| null | null | null | an image
| codeqa | def guess spatial dimensions image if image ndim 2 return 2if image ndim 3 and image shape[ -1 ] 3 return 3if image ndim 3 and image shape[ -1 ] 3 return Noneif image ndim 4 and image shape[ -1 ] 3 return 3else raise Value Error ' Expected 2 D 3D or 4 Darray got%i D ' % image ndim
| null | null | null | null | Question:
What has a channels dimension ?
Code:
def guess_spatial_dimensions(image):
if (image.ndim == 2):
return 2
if ((image.ndim == 3) and (image.shape[(-1)] != 3)):
return 3
if ((image.ndim == 3) and (image.shape[(-1)] == 3)):
return None
if ((image.ndim == 4) and (image.shape[(-1)] == 3)):
return 3
else:
raise ValueError(('Expected 2D, 3D, or 4D array, got %iD.' % image.ndim))
|
null | null | null | What does map file relate to metadata ?
| def parse_mapping_file_to_dict(*args, **kwargs):
(mapping_data, header, comments) = parse_mapping_file(*args, **kwargs)
return (mapping_file_to_dict(mapping_data, header), comments)
| null | null | null | samples
| codeqa | def parse mapping file to dict *args **kwargs mapping data header comments parse mapping file *args **kwargs return mapping file to dict mapping data header comments
| null | null | null | null | Question:
What does map file relate to metadata ?
Code:
def parse_mapping_file_to_dict(*args, **kwargs):
(mapping_data, header, comments) = parse_mapping_file(*args, **kwargs)
return (mapping_file_to_dict(mapping_data, header), comments)
|
null | null | null | What relates samples to metadata ?
| def parse_mapping_file_to_dict(*args, **kwargs):
(mapping_data, header, comments) = parse_mapping_file(*args, **kwargs)
return (mapping_file_to_dict(mapping_data, header), comments)
| null | null | null | map file
| codeqa | def parse mapping file to dict *args **kwargs mapping data header comments parse mapping file *args **kwargs return mapping file to dict mapping data header comments
| null | null | null | null | Question:
What relates samples to metadata ?
Code:
def parse_mapping_file_to_dict(*args, **kwargs):
(mapping_data, header, comments) = parse_mapping_file(*args, **kwargs)
return (mapping_file_to_dict(mapping_data, header), comments)
|
null | null | null | What does the code produce ?
| def with_polymorphic(base, classes, selectable=False, flat=False, polymorphic_on=None, aliased=False, innerjoin=False, _use_mapper_path=False, _existing_alias=None):
primary_mapper = _class_to_mapper(base)
if _existing_alias:
assert (_existing_alias.mapper is primary_mapper)
classes = util.to_set(classes)
new_classes = set([mp.class_ for mp in _existing_alias.with_polymorphic_mappers])
if (classes == new_classes):
return _existing_alias
else:
classes = classes.union(new_classes)
(mappers, selectable) = primary_mapper._with_polymorphic_args(classes, selectable, innerjoin=innerjoin)
if (aliased or flat):
selectable = selectable.alias(flat=flat)
return AliasedClass(base, selectable, with_polymorphic_mappers=mappers, with_polymorphic_discriminator=polymorphic_on, use_mapper_path=_use_mapper_path)
| null | null | null | an : class
| codeqa | def with polymorphic base classes selectable False flat False polymorphic on None aliased False innerjoin False use mapper path False existing alias None primary mapper class to mapper base if existing alias assert existing alias mapper is primary mapper classes util to set classes new classes set [mp class for mp in existing alias with polymorphic mappers] if classes new classes return existing aliaselse classes classes union new classes mappers selectable primary mapper with polymorphic args classes selectable innerjoin innerjoin if aliased or flat selectable selectable alias flat flat return Aliased Class base selectable with polymorphic mappers mappers with polymorphic discriminator polymorphic on use mapper path use mapper path
| null | null | null | null | Question:
What does the code produce ?
Code:
def with_polymorphic(base, classes, selectable=False, flat=False, polymorphic_on=None, aliased=False, innerjoin=False, _use_mapper_path=False, _existing_alias=None):
primary_mapper = _class_to_mapper(base)
if _existing_alias:
assert (_existing_alias.mapper is primary_mapper)
classes = util.to_set(classes)
new_classes = set([mp.class_ for mp in _existing_alias.with_polymorphic_mappers])
if (classes == new_classes):
return _existing_alias
else:
classes = classes.union(new_classes)
(mappers, selectable) = primary_mapper._with_polymorphic_args(classes, selectable, innerjoin=innerjoin)
if (aliased or flat):
selectable = selectable.alias(flat=flat)
return AliasedClass(base, selectable, with_polymorphic_mappers=mappers, with_polymorphic_discriminator=polymorphic_on, use_mapper_path=_use_mapper_path)
|
null | null | null | How do activation function return ?
| def get_activation(name):
try:
return globals()[name]
except:
raise ValueError('Invalid activation function.')
| null | null | null | by name
| codeqa | def get activation name try return globals [name]except raise Value Error ' Invalidactivationfunction '
| null | null | null | null | Question:
How do activation function return ?
Code:
def get_activation(name):
try:
return globals()[name]
except:
raise ValueError('Invalid activation function.')
|
null | null | null | What avoids in the following situations : - more than one space around an assignment operator to align it with another ?
| def whitespace_around_comma(logical_line):
line = logical_line
for separator in ',;:':
found = line.find((separator + ' '))
if (found > (-1)):
return ((found + 1), ("E241 multiple spaces after '%s'" % separator))
found = line.find((separator + ' DCTB '))
if (found > (-1)):
return ((found + 1), ("E242 tab after '%s'" % separator))
| null | null | null | extraneous whitespace
| codeqa | def whitespace around comma logical line line logical linefor separator in ' ' found line find separator + '' if found > -1 return found + 1 "E 241 multiplespacesafter'%s'" % separator found line find separator + ' DCTB ' if found > -1 return found + 1 "E 242 tabafter'%s'" % separator
| null | null | null | null | Question:
What avoids in the following situations : - more than one space around an assignment operator to align it with another ?
Code:
def whitespace_around_comma(logical_line):
line = logical_line
for separator in ',;:':
found = line.find((separator + ' '))
if (found > (-1)):
return ((found + 1), ("E241 multiple spaces after '%s'" % separator))
found = line.find((separator + ' DCTB '))
if (found > (-1)):
return ((found + 1), ("E242 tab after '%s'" % separator))
|
null | null | null | Where do extraneous whitespace avoid ?
| def whitespace_around_comma(logical_line):
line = logical_line
for separator in ',;:':
found = line.find((separator + ' '))
if (found > (-1)):
return ((found + 1), ("E241 multiple spaces after '%s'" % separator))
found = line.find((separator + ' DCTB '))
if (found > (-1)):
return ((found + 1), ("E242 tab after '%s'" % separator))
| null | null | null | in the following situations : - more than one space around an assignment operator to align it with another
| codeqa | def whitespace around comma logical line line logical linefor separator in ' ' found line find separator + '' if found > -1 return found + 1 "E 241 multiplespacesafter'%s'" % separator found line find separator + ' DCTB ' if found > -1 return found + 1 "E 242 tabafter'%s'" % separator
| null | null | null | null | Question:
Where do extraneous whitespace avoid ?
Code:
def whitespace_around_comma(logical_line):
line = logical_line
for separator in ',;:':
found = line.find((separator + ' '))
if (found > (-1)):
return ((found + 1), ("E241 multiple spaces after '%s'" % separator))
found = line.find((separator + ' DCTB '))
if (found > (-1)):
return ((found + 1), ("E242 tab after '%s'" % separator))
|
null | null | null | When did predictions compute ?
| def _parallel_predict_regression(estimators, estimators_features, X):
return sum((estimator.predict(X[:, features]) for (estimator, features) in zip(estimators, estimators_features)))
| null | null | null | within a job
| codeqa | def parallel predict regression estimators estimators features X return sum estimator predict X[ features] for estimator features in zip estimators estimators features
| null | null | null | null | Question:
When did predictions compute ?
Code:
def _parallel_predict_regression(estimators, estimators_features, X):
return sum((estimator.predict(X[:, features]) for (estimator, features) in zip(estimators, estimators_features)))
|
null | null | null | What used to compute predictions within a job ?
| def _parallel_predict_regression(estimators, estimators_features, X):
return sum((estimator.predict(X[:, features]) for (estimator, features) in zip(estimators, estimators_features)))
| null | null | null | private function
| codeqa | def parallel predict regression estimators estimators features X return sum estimator predict X[ features] for estimator features in zip estimators estimators features
| null | null | null | null | Question:
What used to compute predictions within a job ?
Code:
def _parallel_predict_regression(estimators, estimators_features, X):
return sum((estimator.predict(X[:, features]) for (estimator, features) in zip(estimators, estimators_features)))
|
null | null | null | What did private function use ?
| def _parallel_predict_regression(estimators, estimators_features, X):
return sum((estimator.predict(X[:, features]) for (estimator, features) in zip(estimators, estimators_features)))
| null | null | null | to compute predictions within a job
| codeqa | def parallel predict regression estimators estimators features X return sum estimator predict X[ features] for estimator features in zip estimators estimators features
| null | null | null | null | Question:
What did private function use ?
Code:
def _parallel_predict_regression(estimators, estimators_features, X):
return sum((estimator.predict(X[:, features]) for (estimator, features) in zip(estimators, estimators_features)))
|
null | null | null | What does the code check ?
| @auth.before_request
def check_rate_limiting():
if (not flaskbb_config['AUTH_RATELIMIT_ENABLED']):
return None
return limiter.check()
| null | null | null | the the rate limits for each request for this blueprint
| codeqa | @auth before requestdef check rate limiting if not flaskbb config['AUTH RATELIMIT ENABLED'] return Nonereturn limiter check
| null | null | null | null | Question:
What does the code check ?
Code:
@auth.before_request
def check_rate_limiting():
if (not flaskbb_config['AUTH_RATELIMIT_ENABLED']):
return None
return limiter.check()
|
null | null | null | What converts into parameter names ?
| def key2param(key):
result = []
key = list(key)
if (not key[0].isalpha()):
result.append('x')
for c in key:
if c.isalnum():
result.append(c)
else:
result.append('_')
return ''.join(result)
| null | null | null | key names
| codeqa | def key 2 param key result []key list key if not key[ 0 ] isalpha result append 'x' for c in key if c isalnum result append c else result append ' ' return '' join result
| null | null | null | null | Question:
What converts into parameter names ?
Code:
def key2param(key):
result = []
key = list(key)
if (not key[0].isalpha()):
result.append('x')
for c in key:
if c.isalnum():
result.append(c)
else:
result.append('_')
return ''.join(result)
|
null | null | null | What does key names convert ?
| def key2param(key):
result = []
key = list(key)
if (not key[0].isalpha()):
result.append('x')
for c in key:
if c.isalnum():
result.append(c)
else:
result.append('_')
return ''.join(result)
| null | null | null | into parameter names
| codeqa | def key 2 param key result []key list key if not key[ 0 ] isalpha result append 'x' for c in key if c isalnum result append c else result append ' ' return '' join result
| null | null | null | null | Question:
What does key names convert ?
Code:
def key2param(key):
result = []
key = list(key)
if (not key[0].isalpha()):
result.append('x')
for c in key:
if c.isalnum():
result.append(c)
else:
result.append('_')
return ''.join(result)
|
null | null | null | What is denoting their length ?
| def length_prefix(length, offset):
if (length < 56):
return chr((offset + length))
else:
length_string = int_to_big_endian(length)
return (chr((((offset + 56) - 1) + len(length_string))) + length_string)
| null | null | null | lists or strings
| codeqa | def length prefix length offset if length < 56 return chr offset + length else length string int to big endian length return chr offset + 56 - 1 + len length string + length string
| null | null | null | null | Question:
What is denoting their length ?
Code:
def length_prefix(length, offset):
if (length < 56):
return chr((offset + length))
else:
length_string = int_to_big_endian(length)
return (chr((((offset + 56) - 1) + len(length_string))) + length_string)
|
null | null | null | What do lists or strings denote ?
| def length_prefix(length, offset):
if (length < 56):
return chr((offset + length))
else:
length_string = int_to_big_endian(length)
return (chr((((offset + 56) - 1) + len(length_string))) + length_string)
| null | null | null | their length
| codeqa | def length prefix length offset if length < 56 return chr offset + length else length string int to big endian length return chr offset + 56 - 1 + len length string + length string
| null | null | null | null | Question:
What do lists or strings denote ?
Code:
def length_prefix(length, offset):
if (length < 56):
return chr((offset + length))
else:
length_string = int_to_big_endian(length)
return (chr((((offset + 56) - 1) + len(length_string))) + length_string)
|
null | null | null | How did the code return the content ?
| def read_zfile(file_handle):
file_handle.seek(0)
header_length = (len(_ZFILE_PREFIX) + _MAX_LEN)
length = file_handle.read(header_length)
length = length[len(_ZFILE_PREFIX):]
length = int(length, 16)
next_byte = file_handle.read(1)
if (next_byte != ' '):
file_handle.seek(header_length)
data = zlib.decompress(file_handle.read(), 15, length)
assert (len(data) == length), ('Incorrect data length while decompressing %s.The file could be corrupted.' % file_handle)
return data
| null | null | null | as a string
| codeqa | def read zfile file handle file handle seek 0 header length len ZFILE PREFIX + MAX LEN length file handle read header length length length[len ZFILE PREFIX ]length int length 16 next byte file handle read 1 if next byte '' file handle seek header length data zlib decompress file handle read 15 length assert len data length ' Incorrectdatalengthwhiledecompressing%s Thefilecouldbecorrupted ' % file handle return data
| null | null | null | null | Question:
How did the code return the content ?
Code:
def read_zfile(file_handle):
file_handle.seek(0)
header_length = (len(_ZFILE_PREFIX) + _MAX_LEN)
length = file_handle.read(header_length)
length = length[len(_ZFILE_PREFIX):]
length = int(length, 16)
next_byte = file_handle.read(1)
if (next_byte != ' '):
file_handle.seek(header_length)
data = zlib.decompress(file_handle.read(), 15, length)
assert (len(data) == length), ('Incorrect data length while decompressing %s.The file could be corrupted.' % file_handle)
return data
|
null | null | null | What did the code return as a string ?
| def read_zfile(file_handle):
file_handle.seek(0)
header_length = (len(_ZFILE_PREFIX) + _MAX_LEN)
length = file_handle.read(header_length)
length = length[len(_ZFILE_PREFIX):]
length = int(length, 16)
next_byte = file_handle.read(1)
if (next_byte != ' '):
file_handle.seek(header_length)
data = zlib.decompress(file_handle.read(), 15, length)
assert (len(data) == length), ('Incorrect data length while decompressing %s.The file could be corrupted.' % file_handle)
return data
| null | null | null | the content
| codeqa | def read zfile file handle file handle seek 0 header length len ZFILE PREFIX + MAX LEN length file handle read header length length length[len ZFILE PREFIX ]length int length 16 next byte file handle read 1 if next byte '' file handle seek header length data zlib decompress file handle read 15 length assert len data length ' Incorrectdatalengthwhiledecompressing%s Thefilecouldbecorrupted ' % file handle return data
| null | null | null | null | Question:
What did the code return as a string ?
Code:
def read_zfile(file_handle):
file_handle.seek(0)
header_length = (len(_ZFILE_PREFIX) + _MAX_LEN)
length = file_handle.read(header_length)
length = length[len(_ZFILE_PREFIX):]
length = int(length, 16)
next_byte = file_handle.read(1)
if (next_byte != ' '):
file_handle.seek(header_length)
data = zlib.decompress(file_handle.read(), 15, length)
assert (len(data) == length), ('Incorrect data length while decompressing %s.The file could be corrupted.' % file_handle)
return data
|
null | null | null | What did the code read ?
| def read_zfile(file_handle):
file_handle.seek(0)
header_length = (len(_ZFILE_PREFIX) + _MAX_LEN)
length = file_handle.read(header_length)
length = length[len(_ZFILE_PREFIX):]
length = int(length, 16)
next_byte = file_handle.read(1)
if (next_byte != ' '):
file_handle.seek(header_length)
data = zlib.decompress(file_handle.read(), 15, length)
assert (len(data) == length), ('Incorrect data length while decompressing %s.The file could be corrupted.' % file_handle)
return data
| null | null | null | the z - file
| codeqa | def read zfile file handle file handle seek 0 header length len ZFILE PREFIX + MAX LEN length file handle read header length length length[len ZFILE PREFIX ]length int length 16 next byte file handle read 1 if next byte '' file handle seek header length data zlib decompress file handle read 15 length assert len data length ' Incorrectdatalengthwhiledecompressing%s Thefilecouldbecorrupted ' % file handle return data
| null | null | null | null | Question:
What did the code read ?
Code:
def read_zfile(file_handle):
file_handle.seek(0)
header_length = (len(_ZFILE_PREFIX) + _MAX_LEN)
length = file_handle.read(header_length)
length = length[len(_ZFILE_PREFIX):]
length = int(length, 16)
next_byte = file_handle.read(1)
if (next_byte != ' '):
file_handle.seek(header_length)
data = zlib.decompress(file_handle.read(), 15, length)
assert (len(data) == length), ('Incorrect data length while decompressing %s.The file could be corrupted.' % file_handle)
return data
|
null | null | null | What does the code turn into a list of longer strings and lists ?
| def collapseStrings(results):
copy = []
begun = None
listsList = [isinstance(s, list) for s in results]
pred = (lambda e: isinstance(e, tuple))
tran = {0: (lambda e: splitQuoted(''.join(e))), 1: (lambda e: [''.join([i[0] for i in e])])}
for (i, c, isList) in zip(list(range(len(results))), results, listsList):
if isList:
if (begun is not None):
copy.extend(splitOn(results[begun:i], pred, tran))
begun = None
copy.append(collapseStrings(c))
elif (begun is None):
begun = i
if (begun is not None):
copy.extend(splitOn(results[begun:], pred, tran))
return copy
| null | null | null | a list of length - one strings and lists
| codeqa | def collapse Strings results copy []begun Nonelists List [isinstance s list for s in results]pred lambda e isinstance e tuple tran {0 lambda e split Quoted '' join e 1 lambda e ['' join [i[ 0 ] for i in e] ] }for i c is List in zip list range len results results lists List if is List if begun is not None copy extend split On results[begun i] pred tran begun Nonecopy append collapse Strings c elif begun is None begun iif begun is not None copy extend split On results[begun ] pred tran return copy
| null | null | null | null | Question:
What does the code turn into a list of longer strings and lists ?
Code:
def collapseStrings(results):
copy = []
begun = None
listsList = [isinstance(s, list) for s in results]
pred = (lambda e: isinstance(e, tuple))
tran = {0: (lambda e: splitQuoted(''.join(e))), 1: (lambda e: [''.join([i[0] for i in e])])}
for (i, c, isList) in zip(list(range(len(results))), results, listsList):
if isList:
if (begun is not None):
copy.extend(splitOn(results[begun:i], pred, tran))
begun = None
copy.append(collapseStrings(c))
elif (begun is None):
begun = i
if (begun is not None):
copy.extend(splitOn(results[begun:], pred, tran))
return copy
|
null | null | null | What stored in its module system ?
| def apply_wrappers_to_content(content, module, request):
content = module.system.replace_urls(content)
content = module.system.replace_course_urls(content)
content = module.system.replace_jump_to_id_urls(content)
return make_static_urls_absolute(request, content)
| null | null | null | the filter functions
| codeqa | def apply wrappers to content content module request content module system replace urls content content module system replace course urls content content module system replace jump to id urls content return make static urls absolute request content
| null | null | null | null | Question:
What stored in its module system ?
Code:
def apply_wrappers_to_content(content, module, request):
content = module.system.replace_urls(content)
content = module.system.replace_course_urls(content)
content = module.system.replace_jump_to_id_urls(content)
return make_static_urls_absolute(request, content)
|
null | null | null | Where did the filter functions store ?
| def apply_wrappers_to_content(content, module, request):
content = module.system.replace_urls(content)
content = module.system.replace_course_urls(content)
content = module.system.replace_jump_to_id_urls(content)
return make_static_urls_absolute(request, content)
| null | null | null | in its module system
| codeqa | def apply wrappers to content content module request content module system replace urls content content module system replace course urls content content module system replace jump to id urls content return make static urls absolute request content
| null | null | null | null | Question:
Where did the filter functions store ?
Code:
def apply_wrappers_to_content(content, module, request):
content = module.system.replace_urls(content)
content = module.system.replace_course_urls(content)
content = module.system.replace_jump_to_id_urls(content)
return make_static_urls_absolute(request, content)
|
null | null | null | What does the code take ?
| def _pad_bytes(name, length):
return (name + ('\x00' * (length - len(name))))
| null | null | null | a char string
| codeqa | def pad bytes name length return name + '\x 00 ' * length - len name
| null | null | null | null | Question:
What does the code take ?
Code:
def _pad_bytes(name, length):
return (name + ('\x00' * (length - len(name))))
|
null | null | null | Till when does the code pad it with null bytes ?
| def _pad_bytes(name, length):
return (name + ('\x00' * (length - len(name))))
| null | null | null | until its length chars
| codeqa | def pad bytes name length return name + '\x 00 ' * length - len name
| null | null | null | null | Question:
Till when does the code pad it with null bytes ?
Code:
def _pad_bytes(name, length):
return (name + ('\x00' * (length - len(name))))
|
null | null | null | What does the code get ?
| def head_account(url, token, http_conn=None, headers=None, service_token=None):
if http_conn:
(parsed, conn) = http_conn
else:
(parsed, conn) = http_connection(url)
method = 'HEAD'
req_headers = {'X-Auth-Token': token}
if service_token:
req_headers['X-Service-Token'] = service_token
if headers:
req_headers.update(headers)
conn.request(method, parsed.path, '', req_headers)
resp = conn.getresponse()
body = resp.read()
http_log((url, method), {'headers': req_headers}, resp, body)
if ((resp.status < 200) or (resp.status >= 300)):
raise ClientException.from_response(resp, 'Account HEAD failed', body)
resp_headers = resp_header_dict(resp)
return resp_headers
| null | null | null | account stats
| codeqa | def head account url token http conn None headers None service token None if http conn parsed conn http connelse parsed conn http connection url method 'HEAD'req headers {'X- Auth- Token' token}if service token req headers['X- Service- Token'] service tokenif headers req headers update headers conn request method parsed path '' req headers resp conn getresponse body resp read http log url method {'headers' req headers} resp body if resp status < 200 or resp status > 300 raise Client Exception from response resp ' Account HEA Dfailed' body resp headers resp header dict resp return resp headers
| null | null | null | null | Question:
What does the code get ?
Code:
def head_account(url, token, http_conn=None, headers=None, service_token=None):
if http_conn:
(parsed, conn) = http_conn
else:
(parsed, conn) = http_connection(url)
method = 'HEAD'
req_headers = {'X-Auth-Token': token}
if service_token:
req_headers['X-Service-Token'] = service_token
if headers:
req_headers.update(headers)
conn.request(method, parsed.path, '', req_headers)
resp = conn.getresponse()
body = resp.read()
http_log((url, method), {'headers': req_headers}, resp, body)
if ((resp.status < 200) or (resp.status >= 300)):
raise ClientException.from_response(resp, 'Account HEAD failed', body)
resp_headers = resp_header_dict(resp)
return resp_headers
|
null | null | null | What does the code render using dot ?
| def dot_graph(dsk, filename='mydask', format=None, **kwargs):
g = to_graphviz(dsk, **kwargs)
fmts = ['.png', '.pdf', '.dot', '.svg', '.jpeg', '.jpg']
if ((format is None) and any((filename.lower().endswith(fmt) for fmt in fmts))):
(filename, format) = os.path.splitext(filename)
format = format[1:].lower()
if (format is None):
format = 'png'
data = g.pipe(format=format)
if (not data):
raise RuntimeError('Graphviz failed to properly produce an image. This probably means your installation of graphviz is missing png support. See: https://github.com/ContinuumIO/anaconda-issues/issues/485 for more information.')
display_cls = _get_display_cls(format)
if (not filename):
return display_cls(data=data)
full_filename = '.'.join([filename, format])
with open(full_filename, 'wb') as f:
f.write(data)
return display_cls(filename=full_filename)
| null | null | null | a task graph
| codeqa | def dot graph dsk filename 'mydask' format None **kwargs g to graphviz dsk **kwargs fmts [' png' ' pdf' ' dot' ' svg' ' jpeg' ' jpg']if format is None and any filename lower endswith fmt for fmt in fmts filename format os path splitext filename format format[ 1 ] lower if format is None format 'png'data g pipe format format if not data raise Runtime Error ' Graphvizfailedtoproperlyproduceanimage Thisprobablymeansyourinstallationofgraphvizismissingpngsupport See https //github com/ Continuum IO/anaconda-issues/issues/ 485 formoreinformation ' display cls get display cls format if not filename return display cls data data full filename ' ' join [filename format] with open full filename 'wb' as f f write data return display cls filename full filename
| null | null | null | null | Question:
What does the code render using dot ?
Code:
def dot_graph(dsk, filename='mydask', format=None, **kwargs):
g = to_graphviz(dsk, **kwargs)
fmts = ['.png', '.pdf', '.dot', '.svg', '.jpeg', '.jpg']
if ((format is None) and any((filename.lower().endswith(fmt) for fmt in fmts))):
(filename, format) = os.path.splitext(filename)
format = format[1:].lower()
if (format is None):
format = 'png'
data = g.pipe(format=format)
if (not data):
raise RuntimeError('Graphviz failed to properly produce an image. This probably means your installation of graphviz is missing png support. See: https://github.com/ContinuumIO/anaconda-issues/issues/485 for more information.')
display_cls = _get_display_cls(format)
if (not filename):
return display_cls(data=data)
full_filename = '.'.join([filename, format])
with open(full_filename, 'wb') as f:
f.write(data)
return display_cls(filename=full_filename)
|
null | null | null | How does the code render a task graph ?
| def dot_graph(dsk, filename='mydask', format=None, **kwargs):
g = to_graphviz(dsk, **kwargs)
fmts = ['.png', '.pdf', '.dot', '.svg', '.jpeg', '.jpg']
if ((format is None) and any((filename.lower().endswith(fmt) for fmt in fmts))):
(filename, format) = os.path.splitext(filename)
format = format[1:].lower()
if (format is None):
format = 'png'
data = g.pipe(format=format)
if (not data):
raise RuntimeError('Graphviz failed to properly produce an image. This probably means your installation of graphviz is missing png support. See: https://github.com/ContinuumIO/anaconda-issues/issues/485 for more information.')
display_cls = _get_display_cls(format)
if (not filename):
return display_cls(data=data)
full_filename = '.'.join([filename, format])
with open(full_filename, 'wb') as f:
f.write(data)
return display_cls(filename=full_filename)
| null | null | null | using dot
| codeqa | def dot graph dsk filename 'mydask' format None **kwargs g to graphviz dsk **kwargs fmts [' png' ' pdf' ' dot' ' svg' ' jpeg' ' jpg']if format is None and any filename lower endswith fmt for fmt in fmts filename format os path splitext filename format format[ 1 ] lower if format is None format 'png'data g pipe format format if not data raise Runtime Error ' Graphvizfailedtoproperlyproduceanimage Thisprobablymeansyourinstallationofgraphvizismissingpngsupport See https //github com/ Continuum IO/anaconda-issues/issues/ 485 formoreinformation ' display cls get display cls format if not filename return display cls data data full filename ' ' join [filename format] with open full filename 'wb' as f f write data return display cls filename full filename
| null | null | null | null | Question:
How does the code render a task graph ?
Code:
def dot_graph(dsk, filename='mydask', format=None, **kwargs):
g = to_graphviz(dsk, **kwargs)
fmts = ['.png', '.pdf', '.dot', '.svg', '.jpeg', '.jpg']
if ((format is None) and any((filename.lower().endswith(fmt) for fmt in fmts))):
(filename, format) = os.path.splitext(filename)
format = format[1:].lower()
if (format is None):
format = 'png'
data = g.pipe(format=format)
if (not data):
raise RuntimeError('Graphviz failed to properly produce an image. This probably means your installation of graphviz is missing png support. See: https://github.com/ContinuumIO/anaconda-issues/issues/485 for more information.')
display_cls = _get_display_cls(format)
if (not filename):
return display_cls(data=data)
full_filename = '.'.join([filename, format])
with open(full_filename, 'wb') as f:
f.write(data)
return display_cls(filename=full_filename)
|
null | null | null | How do users retrieve ?
| def user_get(alias=None, userids=None, **connection_args):
conn_args = _login(**connection_args)
try:
if conn_args:
method = 'user.get'
params = {'output': 'extend', 'filter': {}}
if ((not userids) and (not alias)):
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **connection_args)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return (ret['result'] if (len(ret['result']) > 0) else False)
else:
raise KeyError
except KeyError:
return False
| null | null | null | according to the given parameters
| codeqa | def user get alias None userids None **connection args conn args login **connection args try if conn args method 'user get'params {'output' 'extend' 'filter' {}}if not userids and not alias return {'result' False 'comment' ' Pleasesubmitaliasoruseridsparametertoretrieveusers '}if alias params['filter'] setdefault 'alias' alias if userids params setdefault 'userids' userids params params extend params **connection args ret query method params conn args['url'] conn args['auth'] return ret['result'] if len ret['result'] > 0 else False else raise Key Errorexcept Key Error return False
| null | null | null | null | Question:
How do users retrieve ?
Code:
def user_get(alias=None, userids=None, **connection_args):
conn_args = _login(**connection_args)
try:
if conn_args:
method = 'user.get'
params = {'output': 'extend', 'filter': {}}
if ((not userids) and (not alias)):
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **connection_args)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return (ret['result'] if (len(ret['result']) > 0) else False)
else:
raise KeyError
except KeyError:
return False
|
null | null | null | What does the code find ?
| def _get_tmp():
userdir = os.path.expanduser('~')
for testdir in [tempfile.gettempdir(), os.path.join(userdir, '.cache'), os.path.join(userdir, '.tmp'), userdir]:
if ((not os.path.exists(testdir)) or (not (_run_shell_command('echo success', testdir) == 'success'))):
continue
return testdir
return ''
| null | null | null | an executable tmp directory
| codeqa | def get tmp userdir os path expanduser '~' for testdir in [tempfile gettempdir os path join userdir ' cache' os path join userdir ' tmp' userdir] if not os path exists testdir or not run shell command 'echosuccess' testdir 'success' continuereturn testdirreturn ''
| null | null | null | null | Question:
What does the code find ?
Code:
def _get_tmp():
userdir = os.path.expanduser('~')
for testdir in [tempfile.gettempdir(), os.path.join(userdir, '.cache'), os.path.join(userdir, '.tmp'), userdir]:
if ((not os.path.exists(testdir)) or (not (_run_shell_command('echo success', testdir) == 'success'))):
continue
return testdir
return ''
|
null | null | null | When did the code set the monitor timeout for the given power scheme ?
| def set_monitor_timeout(timeout, power='ac', scheme=None):
return _set_powercfg_value(scheme, 'SUB_VIDEO', 'VIDEOIDLE', power, timeout)
| null | null | null | in minutes
| codeqa | def set monitor timeout timeout power 'ac' scheme None return set powercfg value scheme 'SUB VIDEO' 'VIDEOIDLE' power timeout
| null | null | null | null | Question:
When did the code set the monitor timeout for the given power scheme ?
Code:
def set_monitor_timeout(timeout, power='ac', scheme=None):
return _set_powercfg_value(scheme, 'SUB_VIDEO', 'VIDEOIDLE', power, timeout)
|
null | null | null | What did the code set for the given power scheme in minutes ?
| def set_monitor_timeout(timeout, power='ac', scheme=None):
return _set_powercfg_value(scheme, 'SUB_VIDEO', 'VIDEOIDLE', power, timeout)
| null | null | null | the monitor timeout
| codeqa | def set monitor timeout timeout power 'ac' scheme None return set powercfg value scheme 'SUB VIDEO' 'VIDEOIDLE' power timeout
| null | null | null | null | Question:
What did the code set for the given power scheme in minutes ?
Code:
def set_monitor_timeout(timeout, power='ac', scheme=None):
return _set_powercfg_value(scheme, 'SUB_VIDEO', 'VIDEOIDLE', power, timeout)
|
null | null | null | For what purpose did the code set the monitor timeout in minutes ?
| def set_monitor_timeout(timeout, power='ac', scheme=None):
return _set_powercfg_value(scheme, 'SUB_VIDEO', 'VIDEOIDLE', power, timeout)
| null | null | null | for the given power scheme
| codeqa | def set monitor timeout timeout power 'ac' scheme None return set powercfg value scheme 'SUB VIDEO' 'VIDEOIDLE' power timeout
| null | null | null | null | Question:
For what purpose did the code set the monitor timeout in minutes ?
Code:
def set_monitor_timeout(timeout, power='ac', scheme=None):
return _set_powercfg_value(scheme, 'SUB_VIDEO', 'VIDEOIDLE', power, timeout)
|
null | null | null | What does the code expand into a list of strings ?
| def expand_pattern(string):
(lead, pattern, remnant) = re.split(EXPANSION_PATTERN, string, maxsplit=1)
(x, y) = pattern.split('-')
for i in range(int(x), (int(y) + 1)):
if remnant:
for string in expand_pattern(remnant):
(yield '{0}{1}{2}'.format(lead, i, string))
else:
(yield '{0}{1}'.format(lead, i))
| null | null | null | a numeric pattern
| codeqa | def expand pattern string lead pattern remnant re split EXPANSION PATTERN string maxsplit 1 x y pattern split '-' for i in range int x int y + 1 if remnant for string in expand pattern remnant yield '{ 0 }{ 1 }{ 2 }' format lead i string else yield '{ 0 }{ 1 }' format lead i
| null | null | null | null | Question:
What does the code expand into a list of strings ?
Code:
def expand_pattern(string):
(lead, pattern, remnant) = re.split(EXPANSION_PATTERN, string, maxsplit=1)
(x, y) = pattern.split('-')
for i in range(int(x), (int(y) + 1)):
if remnant:
for string in expand_pattern(remnant):
(yield '{0}{1}{2}'.format(lead, i, string))
else:
(yield '{0}{1}'.format(lead, i))
|
null | null | null | What does the code update ?
| @utils.arg('server', metavar='<server>', help=_('Name (old name) or ID of server.'))
@utils.arg('--name', metavar='<name>', dest='name', default=None, help=_('New name for the server.'))
@utils.arg('--description', metavar='<description>', dest='description', default=None, help=_('New description for the server. If it equals to empty string (i.g. ""), the server description will be removed.'), start_version='2.19')
def do_update(cs, args):
update_kwargs = {}
if args.name:
update_kwargs['name'] = args.name
if (('description' in args) and (args.description is not None)):
update_kwargs['description'] = args.description
_find_server(cs, args.server).update(**update_kwargs)
| null | null | null | the name or the description for a server
| codeqa | @utils arg 'server' metavar '<server>' help ' Name oldname or I Dofserver ' @utils arg '--name' metavar '<name>' dest 'name' default None help ' Newnamefortheserver ' @utils arg '--description' metavar '<description>' dest 'description' default None help ' Newdescriptionfortheserver Ifitequalstoemptystring i g "" theserverdescriptionwillberemoved ' start version '2 19 ' def do update cs args update kwargs {}if args name update kwargs['name'] args nameif 'description' in args and args description is not None update kwargs['description'] args description find server cs args server update **update kwargs
| null | null | null | null | Question:
What does the code update ?
Code:
@utils.arg('server', metavar='<server>', help=_('Name (old name) or ID of server.'))
@utils.arg('--name', metavar='<name>', dest='name', default=None, help=_('New name for the server.'))
@utils.arg('--description', metavar='<description>', dest='description', default=None, help=_('New description for the server. If it equals to empty string (i.g. ""), the server description will be removed.'), start_version='2.19')
def do_update(cs, args):
update_kwargs = {}
if args.name:
update_kwargs['name'] = args.name
if (('description' in args) and (args.description is not None)):
update_kwargs['description'] = args.description
_find_server(cs, args.server).update(**update_kwargs)
|
null | null | null | What does the code create if one is available for the current user perspective ?
| def _create_widget_object(request, module_name, widget_name):
user = request.user.profile
perspective = user.get_perspective()
modules = perspective.get_modules()
obj = None
current_module = modules.filter(name=module_name)
widget = None
if current_module:
current_module = current_module[0]
widget = _get_widget(request, current_module, widget_name)
if widget:
obj = Widget(user=user, perspective=perspective)
obj.module_name = widget['module_name']
obj.widget_name = widget_name
obj.save()
return obj
| null | null | null | a widget object
| codeqa | def create widget object request module name widget name user request user profileperspective user get perspective modules perspective get modules obj Nonecurrent module modules filter name module name widget Noneif current module current module current module[ 0 ]widget get widget request current module widget name if widget obj Widget user user perspective perspective obj module name widget['module name']obj widget name widget nameobj save return obj
| null | null | null | null | Question:
What does the code create if one is available for the current user perspective ?
Code:
def _create_widget_object(request, module_name, widget_name):
user = request.user.profile
perspective = user.get_perspective()
modules = perspective.get_modules()
obj = None
current_module = modules.filter(name=module_name)
widget = None
if current_module:
current_module = current_module[0]
widget = _get_widget(request, current_module, widget_name)
if widget:
obj = Widget(user=user, perspective=perspective)
obj.module_name = widget['module_name']
obj.widget_name = widget_name
obj.save()
return obj
|
null | null | null | What does the code update after some of its fields were changed ?
| def update_array_info(aryty, array):
context = array._context
builder = array._builder
nitems = context.get_constant(types.intp, 1)
unpacked_shape = cgutils.unpack_tuple(builder, array.shape, aryty.ndim)
for axlen in unpacked_shape:
nitems = builder.mul(nitems, axlen, flags=['nsw'])
array.nitems = nitems
array.itemsize = context.get_constant(types.intp, get_itemsize(context, aryty))
| null | null | null | some auxiliary information in * array
| codeqa | def update array info aryty array context array contextbuilder array buildernitems context get constant types intp 1 unpacked shape cgutils unpack tuple builder array shape aryty ndim for axlen in unpacked shape nitems builder mul nitems axlen flags ['nsw'] array nitems nitemsarray itemsize context get constant types intp get itemsize context aryty
| null | null | null | null | Question:
What does the code update after some of its fields were changed ?
Code:
def update_array_info(aryty, array):
context = array._context
builder = array._builder
nitems = context.get_constant(types.intp, 1)
unpacked_shape = cgutils.unpack_tuple(builder, array.shape, aryty.ndim)
for axlen in unpacked_shape:
nitems = builder.mul(nitems, axlen, flags=['nsw'])
array.nitems = nitems
array.itemsize = context.get_constant(types.intp, get_itemsize(context, aryty))
|
null | null | null | When does the code update some auxiliary information in * array ?
| def update_array_info(aryty, array):
context = array._context
builder = array._builder
nitems = context.get_constant(types.intp, 1)
unpacked_shape = cgutils.unpack_tuple(builder, array.shape, aryty.ndim)
for axlen in unpacked_shape:
nitems = builder.mul(nitems, axlen, flags=['nsw'])
array.nitems = nitems
array.itemsize = context.get_constant(types.intp, get_itemsize(context, aryty))
| null | null | null | after some of its fields were changed
| codeqa | def update array info aryty array context array contextbuilder array buildernitems context get constant types intp 1 unpacked shape cgutils unpack tuple builder array shape aryty ndim for axlen in unpacked shape nitems builder mul nitems axlen flags ['nsw'] array nitems nitemsarray itemsize context get constant types intp get itemsize context aryty
| null | null | null | null | Question:
When does the code update some auxiliary information in * array ?
Code:
def update_array_info(aryty, array):
context = array._context
builder = array._builder
nitems = context.get_constant(types.intp, 1)
unpacked_shape = cgutils.unpack_tuple(builder, array.shape, aryty.ndim)
for axlen in unpacked_shape:
nitems = builder.mul(nitems, axlen, flags=['nsw'])
array.nitems = nitems
array.itemsize = context.get_constant(types.intp, get_itemsize(context, aryty))
|
null | null | null | What does the code delete ?
| def disk_delete(session, dc_ref, file_path):
LOG.debug('Deleting virtual disk %s', file_path)
delete_disk_task = session._call_method(session.vim, 'DeleteVirtualDisk_Task', session.vim.service_content.virtualDiskManager, name=str(file_path), datacenter=dc_ref)
session._wait_for_task(delete_disk_task)
LOG.info(_LI('Deleted virtual disk %s.'), file_path)
| null | null | null | a virtual disk
| codeqa | def disk delete session dc ref file path LOG debug ' Deletingvirtualdisk%s' file path delete disk task session call method session vim ' Delete Virtual Disk Task' session vim service content virtual Disk Manager name str file path datacenter dc ref session wait for task delete disk task LOG info LI ' Deletedvirtualdisk%s ' file path
| null | null | null | null | Question:
What does the code delete ?
Code:
def disk_delete(session, dc_ref, file_path):
LOG.debug('Deleting virtual disk %s', file_path)
delete_disk_task = session._call_method(session.vim, 'DeleteVirtualDisk_Task', session.vim.service_content.virtualDiskManager, name=str(file_path), datacenter=dc_ref)
session._wait_for_task(delete_disk_task)
LOG.info(_LI('Deleted virtual disk %s.'), file_path)
|
null | null | null | What does the code skip if caching is disabled ?
| def skip_if_cache_disabled(*sections):
def wrapper(f):
@functools.wraps(f)
def inner(*args, **kwargs):
if (not CONF.cache.enabled):
raise testcase.TestSkipped('Cache globally disabled.')
for s in sections:
conf_sec = getattr(CONF, s, None)
if (conf_sec is not None):
if (not getattr(conf_sec, 'caching', True)):
raise testcase.TestSkipped(('%s caching disabled.' % s))
return f(*args, **kwargs)
return inner
return wrapper
| null | null | null | a test
| codeqa | def skip if cache disabled *sections def wrapper f @functools wraps f def inner *args **kwargs if not CONF cache enabled raise testcase Test Skipped ' Cachegloballydisabled ' for s in sections conf sec getattr CONF s None if conf sec is not None if not getattr conf sec 'caching' True raise testcase Test Skipped '%scachingdisabled ' % s return f *args **kwargs return innerreturn wrapper
| null | null | null | null | Question:
What does the code skip if caching is disabled ?
Code:
def skip_if_cache_disabled(*sections):
def wrapper(f):
@functools.wraps(f)
def inner(*args, **kwargs):
if (not CONF.cache.enabled):
raise testcase.TestSkipped('Cache globally disabled.')
for s in sections:
conf_sec = getattr(CONF, s, None)
if (conf_sec is not None):
if (not getattr(conf_sec, 'caching', True)):
raise testcase.TestSkipped(('%s caching disabled.' % s))
return f(*args, **kwargs)
return inner
return wrapper
|
null | null | null | What does the code build ?
| def _build_subs_mat(obs_freq_mat, exp_freq_mat):
if (obs_freq_mat.ab_list != exp_freq_mat.ab_list):
raise ValueError('Alphabet mismatch in passed matrices')
subs_mat = SubstitutionMatrix(obs_freq_mat)
for i in obs_freq_mat:
subs_mat[i] = (obs_freq_mat[i] / exp_freq_mat[i])
return subs_mat
| null | null | null | the substitution matrix
| codeqa | def build subs mat obs freq mat exp freq mat if obs freq mat ab list exp freq mat ab list raise Value Error ' Alphabetmismatchinpassedmatrices' subs mat Substitution Matrix obs freq mat for i in obs freq mat subs mat[i] obs freq mat[i] / exp freq mat[i] return subs mat
| null | null | null | null | Question:
What does the code build ?
Code:
def _build_subs_mat(obs_freq_mat, exp_freq_mat):
if (obs_freq_mat.ab_list != exp_freq_mat.ab_list):
raise ValueError('Alphabet mismatch in passed matrices')
subs_mat = SubstitutionMatrix(obs_freq_mat)
for i in obs_freq_mat:
subs_mat[i] = (obs_freq_mat[i] / exp_freq_mat[i])
return subs_mat
|
null | null | null | What does the code raise ?
| def require_moderator_email_prereqs_are_satisfied():
if (not feconf.REQUIRE_EMAIL_ON_MODERATOR_ACTION):
raise Exception('For moderator emails to be sent, please ensure that REQUIRE_EMAIL_ON_MODERATOR_ACTION is set to True.')
if (not feconf.CAN_SEND_EMAILS):
raise Exception('For moderator emails to be sent, please ensure that CAN_SEND_EMAILS is set to True.')
| null | null | null | an exception if
| codeqa | def require moderator email prereqs are satisfied if not feconf REQUIRE EMAIL ON MODERATOR ACTION raise Exception ' Formoderatoremailstobesent pleaseensurethat REQUIRE EMAIL ON MODERATOR ACTIO Nissetto True ' if not feconf CAN SEND EMAILS raise Exception ' Formoderatoremailstobesent pleaseensurethat CAN SEND EMAIL Sissetto True '
| null | null | null | null | Question:
What does the code raise ?
Code:
def require_moderator_email_prereqs_are_satisfied():
if (not feconf.REQUIRE_EMAIL_ON_MODERATOR_ACTION):
raise Exception('For moderator emails to be sent, please ensure that REQUIRE_EMAIL_ON_MODERATOR_ACTION is set to True.')
if (not feconf.CAN_SEND_EMAILS):
raise Exception('For moderator emails to be sent, please ensure that CAN_SEND_EMAILS is set to True.')
|
null | null | null | What does the code retrieve ?
| def GetTokenSid(hToken):
dwSize = DWORD(0)
pStringSid = LPSTR()
TokenUser = 1
if (windll.advapi32.GetTokenInformation(hToken, TokenUser, byref(TOKEN_USER()), 0, byref(dwSize)) == 0):
address = windll.kernel32.LocalAlloc(64, dwSize)
if address:
windll.advapi32.GetTokenInformation(hToken, TokenUser, address, dwSize, byref(dwSize))
pToken_User = cast(address, POINTER(TOKEN_USER))
windll.advapi32.ConvertSidToStringSidA(pToken_User.contents.User.Sid, byref(pStringSid))
if pStringSid:
sid = pStringSid.value
windll.kernel32.LocalFree(address)
return sid
return False
| null | null | null | sid
| codeqa | def Get Token Sid h Token dw Size DWORD 0 p String Sid LPSTR Token User 1if windll advapi 32 Get Token Information h Token Token User byref TOKEN USER 0 byref dw Size 0 address windll kernel 32 Local Alloc 64 dw Size if address windll advapi 32 Get Token Information h Token Token User address dw Size byref dw Size p Token User cast address POINTER TOKEN USER windll advapi 32 Convert Sid To String Sid A p Token User contents User Sid byref p String Sid if p String Sid sid p String Sid valuewindll kernel 32 Local Free address return sidreturn False
| null | null | null | null | Question:
What does the code retrieve ?
Code:
def GetTokenSid(hToken):
dwSize = DWORD(0)
pStringSid = LPSTR()
TokenUser = 1
if (windll.advapi32.GetTokenInformation(hToken, TokenUser, byref(TOKEN_USER()), 0, byref(dwSize)) == 0):
address = windll.kernel32.LocalAlloc(64, dwSize)
if address:
windll.advapi32.GetTokenInformation(hToken, TokenUser, address, dwSize, byref(dwSize))
pToken_User = cast(address, POINTER(TOKEN_USER))
windll.advapi32.ConvertSidToStringSidA(pToken_User.contents.User.Sid, byref(pStringSid))
if pStringSid:
sid = pStringSid.value
windll.kernel32.LocalFree(address)
return sid
return False
|
null | null | null | What does the code dump to a buffer ?
| def dump_certificate_request(type, req):
bio = _new_mem_buf()
if (type == FILETYPE_PEM):
result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
elif (type == FILETYPE_ASN1):
result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
elif (type == FILETYPE_TEXT):
result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
else:
raise ValueError('type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT')
if (result_code == 0):
_raise_current_error()
return _bio_to_string(bio)
| null | null | null | a certificate request
| codeqa | def dump certificate request type req bio new mem buf if type FILETYPE PEM result code lib PEM write bio X509 REQ bio req req elif type FILETYPE ASN 1 result code lib i2 d X509 REQ bio bio req req elif type FILETYPE TEXT result code lib X509 REQ print ex bio req req 0 0 else raise Value Error 'typeargumentmustbe FILETYPE PEM FILETYPE ASN 1 or FILETYPE TEXT' if result code 0 raise current error return bio to string bio
| null | null | null | null | Question:
What does the code dump to a buffer ?
Code:
def dump_certificate_request(type, req):
bio = _new_mem_buf()
if (type == FILETYPE_PEM):
result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
elif (type == FILETYPE_ASN1):
result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
elif (type == FILETYPE_TEXT):
result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
else:
raise ValueError('type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT')
if (result_code == 0):
_raise_current_error()
return _bio_to_string(bio)
|
null | null | null | How does a value decode ?
| def b64decode(value, *args, **kwargs):
return decode(base64.b64decode(value), *args, **kwargs)
| null | null | null | using base64
| codeqa | def b64 decode value *args **kwargs return decode base 64 b64 decode value *args **kwargs
| null | null | null | null | Question:
How does a value decode ?
Code:
def b64decode(value, *args, **kwargs):
return decode(base64.b64decode(value), *args, **kwargs)
|
null | null | null | What does the code redirect to a desired location ?
| def redirect(location, code=302):
view_only = request.args.get('view_only', '')
if view_only:
url = furl.furl(location)
url.args['view_only'] = view_only
location = url.url
return flask_redirect(location, code=code)
| null | null | null | the client
| codeqa | def redirect location code 302 view only request args get 'view only' '' if view only url furl furl location url args['view only'] view onlylocation url urlreturn flask redirect location code code
| null | null | null | null | Question:
What does the code redirect to a desired location ?
Code:
def redirect(location, code=302):
view_only = request.args.get('view_only', '')
if view_only:
url = furl.furl(location)
url.args['view_only'] = view_only
location = url.url
return flask_redirect(location, code=code)
|
null | null | null | What is arising in regularized least squares ?
| def regularized_lsq_operator(J, diag):
J = aslinearoperator(J)
(m, n) = J.shape
def matvec(x):
return np.hstack((J.matvec(x), (diag * x)))
def rmatvec(x):
x1 = x[:m]
x2 = x[m:]
return (J.rmatvec(x1) + (diag * x2))
return LinearOperator(((m + n), n), matvec=matvec, rmatvec=rmatvec)
| null | null | null | a matrix
| codeqa | def regularized lsq operator J diag J aslinearoperator J m n J shapedef matvec x return np hstack J matvec x diag * x def rmatvec x x1 x[ m]x 2 x[m ]return J rmatvec x1 + diag * x2 return Linear Operator m + n n matvec matvec rmatvec rmatvec
| null | null | null | null | Question:
What is arising in regularized least squares ?
Code:
def regularized_lsq_operator(J, diag):
J = aslinearoperator(J)
(m, n) = J.shape
def matvec(x):
return np.hstack((J.matvec(x), (diag * x)))
def rmatvec(x):
x1 = x[:m]
x2 = x[m:]
return (J.rmatvec(x1) + (diag * x2))
return LinearOperator(((m + n), n), matvec=matvec, rmatvec=rmatvec)
|
null | null | null | What runs the watchers and auditors ?
| @manager.command
def start_scheduler():
from security_monkey import scheduler
scheduler.setup_scheduler()
scheduler.scheduler.start()
| null | null | null | the python scheduler
| codeqa | @manager commanddef start scheduler from security monkey import schedulerscheduler setup scheduler scheduler scheduler start
| null | null | null | null | Question:
What runs the watchers and auditors ?
Code:
@manager.command
def start_scheduler():
from security_monkey import scheduler
scheduler.setup_scheduler()
scheduler.scheduler.start()
|
null | null | null | What does the code start ?
| @manager.command
def start_scheduler():
from security_monkey import scheduler
scheduler.setup_scheduler()
scheduler.scheduler.start()
| null | null | null | the python scheduler to run the watchers and auditors
| codeqa | @manager commanddef start scheduler from security monkey import schedulerscheduler setup scheduler scheduler scheduler start
| null | null | null | null | Question:
What does the code start ?
Code:
@manager.command
def start_scheduler():
from security_monkey import scheduler
scheduler.setup_scheduler()
scheduler.scheduler.start()
|
null | null | null | What does the python scheduler run ?
| @manager.command
def start_scheduler():
from security_monkey import scheduler
scheduler.setup_scheduler()
scheduler.scheduler.start()
| null | null | null | the watchers and auditors
| codeqa | @manager commanddef start scheduler from security monkey import schedulerscheduler setup scheduler scheduler scheduler start
| null | null | null | null | Question:
What does the python scheduler run ?
Code:
@manager.command
def start_scheduler():
from security_monkey import scheduler
scheduler.setup_scheduler()
scheduler.scheduler.start()
|
null | null | null | For what purpose do every notification handler call ?
| @task(ignore_result=True)
def send_notification(notification_id):
notification = Notification.objects.get(id=notification_id)
for handler in notification_handlers:
handler(notification)
| null | null | null | for a notification
| codeqa | @task ignore result True def send notification notification id notification Notification objects get id notification id for handler in notification handlers handler notification
| null | null | null | null | Question:
For what purpose do every notification handler call ?
Code:
@task(ignore_result=True)
def send_notification(notification_id):
notification = Notification.objects.get(id=notification_id)
for handler in notification_handlers:
handler(notification)
|
null | null | null | What does the code remove from the dictionary ?
| def removeListArtOfIllusionFromDictionary(dictionary, scrubKeys):
euclidean.removeListFromDictionary(dictionary, ['bf:id', 'bf:type'])
euclidean.removeListFromDictionary(dictionary, scrubKeys)
| null | null | null | the list and art of illusion keys
| codeqa | def remove List Art Of Illusion From Dictionary dictionary scrub Keys euclidean remove List From Dictionary dictionary ['bf id' 'bf type'] euclidean remove List From Dictionary dictionary scrub Keys
| null | null | null | null | Question:
What does the code remove from the dictionary ?
Code:
def removeListArtOfIllusionFromDictionary(dictionary, scrubKeys):
euclidean.removeListFromDictionary(dictionary, ['bf:id', 'bf:type'])
euclidean.removeListFromDictionary(dictionary, scrubKeys)
|
null | null | null | What does the code transform into a multinomial form given generators ?
| def _dict_from_expr_if_gens(expr, opt):
((poly,), gens) = _parallel_dict_from_expr_if_gens((expr,), opt)
return (poly, gens)
| null | null | null | an expression
| codeqa | def dict from expr if gens expr opt poly gens parallel dict from expr if gens expr opt return poly gens
| null | null | null | null | Question:
What does the code transform into a multinomial form given generators ?
Code:
def _dict_from_expr_if_gens(expr, opt):
((poly,), gens) = _parallel_dict_from_expr_if_gens((expr,), opt)
return (poly, gens)
|
null | null | null | What given generators ?
| def _dict_from_expr_if_gens(expr, opt):
((poly,), gens) = _parallel_dict_from_expr_if_gens((expr,), opt)
return (poly, gens)
| null | null | null | a multinomial form
| codeqa | def dict from expr if gens expr opt poly gens parallel dict from expr if gens expr opt return poly gens
| null | null | null | null | Question:
What given generators ?
Code:
def _dict_from_expr_if_gens(expr, opt):
((poly,), gens) = _parallel_dict_from_expr_if_gens((expr,), opt)
return (poly, gens)
|
null | null | null | What did a multinomial form give ?
| def _dict_from_expr_if_gens(expr, opt):
((poly,), gens) = _parallel_dict_from_expr_if_gens((expr,), opt)
return (poly, gens)
| null | null | null | generators
| codeqa | def dict from expr if gens expr opt poly gens parallel dict from expr if gens expr opt return poly gens
| null | null | null | null | Question:
What did a multinomial form give ?
Code:
def _dict_from_expr_if_gens(expr, opt):
((poly,), gens) = _parallel_dict_from_expr_if_gens((expr,), opt)
return (poly, gens)
|
null | null | null | What represents imports as a tree ?
| def repr_tree_defs(data, indent_str=None):
lines = []
nodes = data.items()
for (i, (mod, (sub, files))) in enumerate(sorted(nodes, key=(lambda x: x[0]))):
if (not files):
files = ''
else:
files = ('(%s)' % ','.join(files))
if (indent_str is None):
lines.append(('%s %s' % (mod, files)))
sub_indent_str = ' '
else:
lines.append(('%s\\-%s %s' % (indent_str, mod, files)))
if (i == (len(nodes) - 1)):
sub_indent_str = ('%s ' % indent_str)
else:
sub_indent_str = ('%s| ' % indent_str)
if sub:
lines.append(repr_tree_defs(sub, sub_indent_str))
return '\n'.join(lines)
| null | null | null | a string
| codeqa | def repr tree defs data indent str None lines []nodes data items for i mod sub files in enumerate sorted nodes key lambda x x[ 0 ] if not files files ''else files ' %s ' % ' ' join files if indent str is None lines append '%s%s' % mod files sub indent str ''else lines append '%s\\-%s%s' % indent str mod files if i len nodes - 1 sub indent str '%s' % indent str else sub indent str '%s ' % indent str if sub lines append repr tree defs sub sub indent str return '\n' join lines
| null | null | null | null | Question:
What represents imports as a tree ?
Code:
def repr_tree_defs(data, indent_str=None):
lines = []
nodes = data.items()
for (i, (mod, (sub, files))) in enumerate(sorted(nodes, key=(lambda x: x[0]))):
if (not files):
files = ''
else:
files = ('(%s)' % ','.join(files))
if (indent_str is None):
lines.append(('%s %s' % (mod, files)))
sub_indent_str = ' '
else:
lines.append(('%s\\-%s %s' % (indent_str, mod, files)))
if (i == (len(nodes) - 1)):
sub_indent_str = ('%s ' % indent_str)
else:
sub_indent_str = ('%s| ' % indent_str)
if sub:
lines.append(repr_tree_defs(sub, sub_indent_str))
return '\n'.join(lines)
|
null | null | null | What does a string represent ?
| def repr_tree_defs(data, indent_str=None):
lines = []
nodes = data.items()
for (i, (mod, (sub, files))) in enumerate(sorted(nodes, key=(lambda x: x[0]))):
if (not files):
files = ''
else:
files = ('(%s)' % ','.join(files))
if (indent_str is None):
lines.append(('%s %s' % (mod, files)))
sub_indent_str = ' '
else:
lines.append(('%s\\-%s %s' % (indent_str, mod, files)))
if (i == (len(nodes) - 1)):
sub_indent_str = ('%s ' % indent_str)
else:
sub_indent_str = ('%s| ' % indent_str)
if sub:
lines.append(repr_tree_defs(sub, sub_indent_str))
return '\n'.join(lines)
| null | null | null | imports as a tree
| codeqa | def repr tree defs data indent str None lines []nodes data items for i mod sub files in enumerate sorted nodes key lambda x x[ 0 ] if not files files ''else files ' %s ' % ' ' join files if indent str is None lines append '%s%s' % mod files sub indent str ''else lines append '%s\\-%s%s' % indent str mod files if i len nodes - 1 sub indent str '%s' % indent str else sub indent str '%s ' % indent str if sub lines append repr tree defs sub sub indent str return '\n' join lines
| null | null | null | null | Question:
What does a string represent ?
Code:
def repr_tree_defs(data, indent_str=None):
lines = []
nodes = data.items()
for (i, (mod, (sub, files))) in enumerate(sorted(nodes, key=(lambda x: x[0]))):
if (not files):
files = ''
else:
files = ('(%s)' % ','.join(files))
if (indent_str is None):
lines.append(('%s %s' % (mod, files)))
sub_indent_str = ' '
else:
lines.append(('%s\\-%s %s' % (indent_str, mod, files)))
if (i == (len(nodes) - 1)):
sub_indent_str = ('%s ' % indent_str)
else:
sub_indent_str = ('%s| ' % indent_str)
if sub:
lines.append(repr_tree_defs(sub, sub_indent_str))
return '\n'.join(lines)
|
null | null | null | What does the code add ?
| def _set_persistent_module(mod):
if ((not mod) or (mod in mod_list(True)) or (mod not in available())):
return set()
__salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(mod))
return set([mod])
| null | null | null | a module to loader
| codeqa | def set persistent module mod if not mod or mod in mod list True or mod not in available return set salt ['file append'] LOADER CONF LOAD MODULE format mod return set [mod]
| null | null | null | null | Question:
What does the code add ?
Code:
def _set_persistent_module(mod):
if ((not mod) or (mod in mod_list(True)) or (mod not in available())):
return set()
__salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(mod))
return set([mod])
|
null | null | null | What is testing the admin ?
| def create_admin_user(username, password):
u = User()
u.username = username
u.email = '{0}@dev.mail.example.com'.format(username)
u.is_superuser = True
u.is_staff = True
u.set_password(password)
try:
u.save()
print('Created user {0} with password {1}.'.format(username, password))
except Exception as e:
pass
| null | null | null | a user
| codeqa | def create admin user username password u User u username usernameu email '{ 0 }@dev mail example com' format username u is superuser Trueu is staff Trueu set password password try u save print ' Createduser{ 0 }withpassword{ 1 } ' format username password except Exception as e pass
| null | null | null | null | Question:
What is testing the admin ?
Code:
def create_admin_user(username, password):
u = User()
u.username = username
u.email = '{0}@dev.mail.example.com'.format(username)
u.is_superuser = True
u.is_staff = True
u.set_password(password)
try:
u.save()
print('Created user {0} with password {1}.'.format(username, password))
except Exception as e:
pass
|
null | null | null | What does the code create ?
| def create_admin_user(username, password):
u = User()
u.username = username
u.email = '{0}@dev.mail.example.com'.format(username)
u.is_superuser = True
u.is_staff = True
u.set_password(password)
try:
u.save()
print('Created user {0} with password {1}.'.format(username, password))
except Exception as e:
pass
| null | null | null | a user for testing the admin
| codeqa | def create admin user username password u User u username usernameu email '{ 0 }@dev mail example com' format username u is superuser Trueu is staff Trueu set password password try u save print ' Createduser{ 0 }withpassword{ 1 } ' format username password except Exception as e pass
| null | null | null | null | Question:
What does the code create ?
Code:
def create_admin_user(username, password):
u = User()
u.username = username
u.email = '{0}@dev.mail.example.com'.format(username)
u.is_superuser = True
u.is_staff = True
u.set_password(password)
try:
u.save()
print('Created user {0} with password {1}.'.format(username, password))
except Exception as e:
pass
|
null | null | null | What does the code initiate from a draft registration ?
| @must_have_permission(ADMIN)
@must_be_branched_from_node
@http_error_if_disk_saving_mode
def register_draft_registration(auth, node, draft, *args, **kwargs):
data = request.get_json()
registration_choice = data.get('registrationChoice', 'immediate')
validate_registration_choice(registration_choice)
register = draft.register(auth)
draft.save()
if (registration_choice == 'embargo'):
embargo_end_date = parse_date(data['embargoEndDate'], ignoretz=True).replace(tzinfo=pytz.utc)
try:
register.embargo_registration(auth.user, embargo_end_date)
except ValidationValueError as err:
raise HTTPError(http.BAD_REQUEST, data=dict(message_long=err.message))
else:
try:
register.require_approval(auth.user)
except NodeStateError as err:
raise HTTPError(http.BAD_REQUEST, data=dict(message_long=err.message))
register.save()
push_status_message(language.AFTER_REGISTER_ARCHIVING, kind='info', trust=False)
return ({'status': 'initiated', 'urls': {'registrations': node.web_url_for('node_registrations')}}, http.ACCEPTED)
| null | null | null | a registration
| codeqa | @must have permission ADMIN @must be branched from node@http error if disk saving modedef register draft registration auth node draft *args **kwargs data request get json registration choice data get 'registration Choice' 'immediate' validate registration choice registration choice register draft register auth draft save if registration choice 'embargo' embargo end date parse date data['embargo End Date'] ignoretz True replace tzinfo pytz utc try register embargo registration auth user embargo end date except Validation Value Error as err raise HTTP Error http BAD REQUEST data dict message long err message else try register require approval auth user except Node State Error as err raise HTTP Error http BAD REQUEST data dict message long err message register save push status message language AFTER REGISTER ARCHIVING kind 'info' trust False return {'status' 'initiated' 'urls' {'registrations' node web url for 'node registrations' }} http ACCEPTED
| null | null | null | null | Question:
What does the code initiate from a draft registration ?
Code:
@must_have_permission(ADMIN)
@must_be_branched_from_node
@http_error_if_disk_saving_mode
def register_draft_registration(auth, node, draft, *args, **kwargs):
data = request.get_json()
registration_choice = data.get('registrationChoice', 'immediate')
validate_registration_choice(registration_choice)
register = draft.register(auth)
draft.save()
if (registration_choice == 'embargo'):
embargo_end_date = parse_date(data['embargoEndDate'], ignoretz=True).replace(tzinfo=pytz.utc)
try:
register.embargo_registration(auth.user, embargo_end_date)
except ValidationValueError as err:
raise HTTPError(http.BAD_REQUEST, data=dict(message_long=err.message))
else:
try:
register.require_approval(auth.user)
except NodeStateError as err:
raise HTTPError(http.BAD_REQUEST, data=dict(message_long=err.message))
register.save()
push_status_message(language.AFTER_REGISTER_ARCHIVING, kind='info', trust=False)
return ({'status': 'initiated', 'urls': {'registrations': node.web_url_for('node_registrations')}}, http.ACCEPTED)
|
null | null | null | How did the code calculate the best - paths ?
| def _cmp_by_aspath(path1, path2):
as_path1 = path1.get_pattr(BGP_ATTR_TYPE_AS_PATH)
as_path2 = path2.get_pattr(BGP_ATTR_TYPE_AS_PATH)
assert (as_path1 and as_path2)
l1 = as_path1.get_as_path_len()
l2 = as_path2.get_as_path_len()
assert ((l1 is not None) and (l2 is not None))
if (l1 > l2):
return path2
elif (l2 > l1):
return path1
else:
return None
| null | null | null | by comparing as - path lengths
| codeqa | def cmp by aspath path 1 path 2 as path 1 path 1 get pattr BGP ATTR TYPE AS PATH as path 2 path 2 get pattr BGP ATTR TYPE AS PATH assert as path 1 and as path 2 l1 as path 1 get as path len l2 as path 2 get as path len assert l1 is not None and l2 is not None if l1 > l2 return path 2 elif l2 > l1 return path 1 else return None
| null | null | null | null | Question:
How did the code calculate the best - paths ?
Code:
def _cmp_by_aspath(path1, path2):
as_path1 = path1.get_pattr(BGP_ATTR_TYPE_AS_PATH)
as_path2 = path2.get_pattr(BGP_ATTR_TYPE_AS_PATH)
assert (as_path1 and as_path2)
l1 = as_path1.get_as_path_len()
l2 = as_path2.get_as_path_len()
assert ((l1 is not None) and (l2 is not None))
if (l1 > l2):
return path2
elif (l2 > l1):
return path1
else:
return None
|
null | null | null | What did the code calculate by comparing as - path lengths ?
| def _cmp_by_aspath(path1, path2):
as_path1 = path1.get_pattr(BGP_ATTR_TYPE_AS_PATH)
as_path2 = path2.get_pattr(BGP_ATTR_TYPE_AS_PATH)
assert (as_path1 and as_path2)
l1 = as_path1.get_as_path_len()
l2 = as_path2.get_as_path_len()
assert ((l1 is not None) and (l2 is not None))
if (l1 > l2):
return path2
elif (l2 > l1):
return path1
else:
return None
| null | null | null | the best - paths
| codeqa | def cmp by aspath path 1 path 2 as path 1 path 1 get pattr BGP ATTR TYPE AS PATH as path 2 path 2 get pattr BGP ATTR TYPE AS PATH assert as path 1 and as path 2 l1 as path 1 get as path len l2 as path 2 get as path len assert l1 is not None and l2 is not None if l1 > l2 return path 2 elif l2 > l1 return path 1 else return None
| null | null | null | null | Question:
What did the code calculate by comparing as - path lengths ?
Code:
def _cmp_by_aspath(path1, path2):
as_path1 = path1.get_pattr(BGP_ATTR_TYPE_AS_PATH)
as_path2 = path2.get_pattr(BGP_ATTR_TYPE_AS_PATH)
assert (as_path1 and as_path2)
l1 = as_path1.get_as_path_len()
l2 = as_path2.get_as_path_len()
assert ((l1 is not None) and (l2 is not None))
if (l1 > l2):
return path2
elif (l2 > l1):
return path1
else:
return None
|
null | null | null | What does the code serialize to a text ?
| def serialize_tree(items):
for (name, mode, hexsha) in items:
(yield ((((('%04o' % mode).encode('ascii') + ' ') + name) + '\x00') + hex_to_sha(hexsha)))
| null | null | null | the items in a tree
| codeqa | def serialize tree items for name mode hexsha in items yield '% 04 o' % mode encode 'ascii' + '' + name + '\x 00 ' + hex to sha hexsha
| null | null | null | null | Question:
What does the code serialize to a text ?
Code:
def serialize_tree(items):
for (name, mode, hexsha) in items:
(yield ((((('%04o' % mode).encode('ascii') + ' ') + name) + '\x00') + hex_to_sha(hexsha)))
|
null | null | null | How did the application specify ?
| def compile_controllers(folder):
path = pjoin(folder, 'controllers')
for fname in listdir(path, '.+\\.py$'):
data = read_file(pjoin(path, fname))
exposed = find_exposed_functions(data)
for function in exposed:
command = (data + ('\nresponse._vars=response._caller(%s)\n' % function))
filename = pjoin(folder, 'compiled', ('controllers.%s.%s.py' % (fname[:(-3)], function)))
write_file(filename, command)
save_pyc(filename)
os.unlink(filename)
| null | null | null | by folder
| codeqa | def compile controllers folder path pjoin folder 'controllers' for fname in listdir path ' +\\ py$' data read file pjoin path fname exposed find exposed functions data for function in exposed command data + '\nresponse vars response caller %s \n' % function filename pjoin folder 'compiled' 'controllers %s %s py' % fname[ -3 ] function write file filename command save pyc filename os unlink filename
| null | null | null | null | Question:
How did the application specify ?
Code:
def compile_controllers(folder):
path = pjoin(folder, 'controllers')
for fname in listdir(path, '.+\\.py$'):
data = read_file(pjoin(path, fname))
exposed = find_exposed_functions(data)
for function in exposed:
command = (data + ('\nresponse._vars=response._caller(%s)\n' % function))
filename = pjoin(folder, 'compiled', ('controllers.%s.%s.py' % (fname[:(-3)], function)))
write_file(filename, command)
save_pyc(filename)
os.unlink(filename)
|
null | null | null | In which direction do info about uploaded files echo for tests ?
| def file_upload_echo(request):
r = dict([(k, f.name) for (k, f) in request.FILES.items()])
return HttpResponse(simplejson.dumps(r))
| null | null | null | back
| codeqa | def file upload echo request r dict [ k f name for k f in request FILES items ] return Http Response simplejson dumps r
| null | null | null | null | Question:
In which direction do info about uploaded files echo for tests ?
Code:
def file_upload_echo(request):
r = dict([(k, f.name) for (k, f) in request.FILES.items()])
return HttpResponse(simplejson.dumps(r))
|
null | null | null | For what purpose do info about uploaded files echo back ?
| def file_upload_echo(request):
r = dict([(k, f.name) for (k, f) in request.FILES.items()])
return HttpResponse(simplejson.dumps(r))
| null | null | null | for tests
| codeqa | def file upload echo request r dict [ k f name for k f in request FILES items ] return Http Response simplejson dumps r
| null | null | null | null | Question:
For what purpose do info about uploaded files echo back ?
Code:
def file_upload_echo(request):
r = dict([(k, f.name) for (k, f) in request.FILES.items()])
return HttpResponse(simplejson.dumps(r))
|
null | null | null | What does the code retrieve ?
| @decorators.which('ssh-keyscan')
def recv_known_host(hostname, enc=None, port=None, hash_known_hosts=True, timeout=5):
need_dash_t = ('CentOS-5',)
cmd = ['ssh-keyscan']
if port:
cmd.extend(['-p', port])
if enc:
cmd.extend(['-t', enc])
if ((not enc) and (__grains__.get('osfinger') in need_dash_t)):
cmd.extend(['-t', 'rsa'])
if hash_known_hosts:
cmd.append('-H')
cmd.extend(['-T', str(timeout)])
cmd.append(hostname)
lines = None
attempts = 5
while ((not lines) and (attempts > 0)):
attempts = (attempts - 1)
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
known_hosts = list(_parse_openssh_output(lines))
return (known_hosts[0] if known_hosts else None)
| null | null | null | information about host public key from remote server hostname
| codeqa | @decorators which 'ssh-keyscan' def recv known host hostname enc None port None hash known hosts True timeout 5 need dash t ' Cent OS- 5 ' cmd ['ssh-keyscan']if port cmd extend ['-p' port] if enc cmd extend ['-t' enc] if not enc and grains get 'osfinger' in need dash t cmd extend ['-t' 'rsa'] if hash known hosts cmd append '-H' cmd extend ['-T' str timeout ] cmd append hostname lines Noneattempts 5while not lines and attempts > 0 attempts attempts - 1 lines salt ['cmd run'] cmd python shell False splitlines known hosts list parse openssh output lines return known hosts[ 0 ] if known hosts else None
| null | null | null | null | Question:
What does the code retrieve ?
Code:
@decorators.which('ssh-keyscan')
def recv_known_host(hostname, enc=None, port=None, hash_known_hosts=True, timeout=5):
need_dash_t = ('CentOS-5',)
cmd = ['ssh-keyscan']
if port:
cmd.extend(['-p', port])
if enc:
cmd.extend(['-t', enc])
if ((not enc) and (__grains__.get('osfinger') in need_dash_t)):
cmd.extend(['-t', 'rsa'])
if hash_known_hosts:
cmd.append('-H')
cmd.extend(['-T', str(timeout)])
cmd.append(hostname)
lines = None
attempts = 5
while ((not lines) and (attempts > 0)):
attempts = (attempts - 1)
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
known_hosts = list(_parse_openssh_output(lines))
return (known_hosts[0] if known_hosts else None)
|
null | null | null | What does the code resolve into a unique name referred to by salt ?
| def resolve_name(name, arch, osarch=None):
if (osarch is None):
osarch = get_osarch()
if ((not check_32(arch, osarch)) and (arch not in (osarch, 'noarch'))):
name += '.{0}'.format(arch)
return name
| null | null | null | the package name and arch
| codeqa | def resolve name name arch osarch None if osarch is None osarch get osarch if not check 32 arch osarch and arch not in osarch 'noarch' name + ' {0 }' format arch return name
| null | null | null | null | Question:
What does the code resolve into a unique name referred to by salt ?
Code:
def resolve_name(name, arch, osarch=None):
if (osarch is None):
osarch = get_osarch()
if ((not check_32(arch, osarch)) and (arch not in (osarch, 'noarch'))):
name += '.{0}'.format(arch)
return name
|
null | null | null | What named tuple ?
| def PackPlacemark(placemark):
return ','.join([base64hex.B64HexEncode(x.encode('utf-8'), padding=False) for x in placemark])
| null | null | null | placemark
| codeqa | def Pack Placemark placemark return ' ' join [base 64 hex B64 Hex Encode x encode 'utf- 8 ' padding False for x in placemark]
| null | null | null | null | Question:
What named tuple ?
Code:
def PackPlacemark(placemark):
return ','.join([base64hex.B64HexEncode(x.encode('utf-8'), padding=False) for x in placemark])
|
null | null | null | What does the code get ?
| def getLoopsLoopsIntersections(loops, otherLoops):
loopsLoopsIntersections = []
for loop in loops:
addLoopLoopsIntersections(loop, loopsLoopsIntersections, otherLoops)
return loopsLoopsIntersections
| null | null | null | all the intersections of the loops with the other loops
| codeqa | def get Loops Loops Intersections loops other Loops loops Loops Intersections []for loop in loops add Loop Loops Intersections loop loops Loops Intersections other Loops return loops Loops Intersections
| null | null | null | null | Question:
What does the code get ?
Code:
def getLoopsLoopsIntersections(loops, otherLoops):
loopsLoopsIntersections = []
for loop in loops:
addLoopLoopsIntersections(loop, loopsLoopsIntersections, otherLoops)
return loopsLoopsIntersections
|
null | null | null | What matches file extension ?
| def _IsSourceExtension(s):
return (s in GetNonHeaderExtensions())
| null | null | null | a source file extension
| codeqa | def Is Source Extension s return s in Get Non Header Extensions
| null | null | null | null | Question:
What matches file extension ?
Code:
def _IsSourceExtension(s):
return (s in GetNonHeaderExtensions())
|
null | null | null | What does a source file extension match ?
| def _IsSourceExtension(s):
return (s in GetNonHeaderExtensions())
| null | null | null | file extension
| codeqa | def Is Source Extension s return s in Get Non Header Extensions
| null | null | null | null | Question:
What does a source file extension match ?
Code:
def _IsSourceExtension(s):
return (s in GetNonHeaderExtensions())
|
null | null | null | What should filter missing / empty value handling in the same way that include_names and exclude_names filter output columns ?
| @pytest.mark.parametrize('parallel', [True, False])
def test_fill_include_exclude_names(parallel, read_csv):
text = '\nA, B, C\n, 1, 2\n3, , 4\n5, 5,\n'
table = read_csv(text, fill_include_names=['A', 'B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is ma.masked)
assert (table['C'][2] is not ma.masked)
table = read_csv(text, fill_exclude_names=['A', 'B'], parallel=parallel)
assert (table['C'][2] is ma.masked)
assert (table['A'][0] is not ma.masked)
assert (table['B'][1] is not ma.masked)
table = read_csv(text, fill_include_names=['A', 'B'], fill_exclude_names=['B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is not ma.masked)
assert (table['C'][2] is not ma.masked)
| null | null | null | fill_include_names and fill_exclude_names
| codeqa | @pytest mark parametrize 'parallel' [ True False] def test fill include exclude names parallel read csv text '\n A B C\n 1 2\n 3 4\n 5 5 \n'table read csv text fill include names ['A' 'B'] parallel parallel assert table['A'][ 0 ] is ma masked assert table['B'][ 1 ] is ma masked assert table['C'][ 2 ] is not ma masked table read csv text fill exclude names ['A' 'B'] parallel parallel assert table['C'][ 2 ] is ma masked assert table['A'][ 0 ] is not ma masked assert table['B'][ 1 ] is not ma masked table read csv text fill include names ['A' 'B'] fill exclude names ['B'] parallel parallel assert table['A'][ 0 ] is ma masked assert table['B'][ 1 ] is not ma masked assert table['C'][ 2 ] is not ma masked
| null | null | null | null | Question:
What should filter missing / empty value handling in the same way that include_names and exclude_names filter output columns ?
Code:
@pytest.mark.parametrize('parallel', [True, False])
def test_fill_include_exclude_names(parallel, read_csv):
text = '\nA, B, C\n, 1, 2\n3, , 4\n5, 5,\n'
table = read_csv(text, fill_include_names=['A', 'B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is ma.masked)
assert (table['C'][2] is not ma.masked)
table = read_csv(text, fill_exclude_names=['A', 'B'], parallel=parallel)
assert (table['C'][2] is ma.masked)
assert (table['A'][0] is not ma.masked)
assert (table['B'][1] is not ma.masked)
table = read_csv(text, fill_include_names=['A', 'B'], fill_exclude_names=['B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is not ma.masked)
assert (table['C'][2] is not ma.masked)
|
null | null | null | How should fill_include_names and fill_exclude_names filter missing / empty value handling ?
| @pytest.mark.parametrize('parallel', [True, False])
def test_fill_include_exclude_names(parallel, read_csv):
text = '\nA, B, C\n, 1, 2\n3, , 4\n5, 5,\n'
table = read_csv(text, fill_include_names=['A', 'B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is ma.masked)
assert (table['C'][2] is not ma.masked)
table = read_csv(text, fill_exclude_names=['A', 'B'], parallel=parallel)
assert (table['C'][2] is ma.masked)
assert (table['A'][0] is not ma.masked)
assert (table['B'][1] is not ma.masked)
table = read_csv(text, fill_include_names=['A', 'B'], fill_exclude_names=['B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is not ma.masked)
assert (table['C'][2] is not ma.masked)
| null | null | null | in the same way that include_names and exclude_names filter output columns
| codeqa | @pytest mark parametrize 'parallel' [ True False] def test fill include exclude names parallel read csv text '\n A B C\n 1 2\n 3 4\n 5 5 \n'table read csv text fill include names ['A' 'B'] parallel parallel assert table['A'][ 0 ] is ma masked assert table['B'][ 1 ] is ma masked assert table['C'][ 2 ] is not ma masked table read csv text fill exclude names ['A' 'B'] parallel parallel assert table['C'][ 2 ] is ma masked assert table['A'][ 0 ] is not ma masked assert table['B'][ 1 ] is not ma masked table read csv text fill include names ['A' 'B'] fill exclude names ['B'] parallel parallel assert table['A'][ 0 ] is ma masked assert table['B'][ 1 ] is not ma masked assert table['C'][ 2 ] is not ma masked
| null | null | null | null | Question:
How should fill_include_names and fill_exclude_names filter missing / empty value handling ?
Code:
@pytest.mark.parametrize('parallel', [True, False])
def test_fill_include_exclude_names(parallel, read_csv):
text = '\nA, B, C\n, 1, 2\n3, , 4\n5, 5,\n'
table = read_csv(text, fill_include_names=['A', 'B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is ma.masked)
assert (table['C'][2] is not ma.masked)
table = read_csv(text, fill_exclude_names=['A', 'B'], parallel=parallel)
assert (table['C'][2] is ma.masked)
assert (table['A'][0] is not ma.masked)
assert (table['B'][1] is not ma.masked)
table = read_csv(text, fill_include_names=['A', 'B'], fill_exclude_names=['B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is not ma.masked)
assert (table['C'][2] is not ma.masked)
|
null | null | null | What should fill_include_names and fill_exclude_names filter in the same way that include_names and exclude_names filter output columns ?
| @pytest.mark.parametrize('parallel', [True, False])
def test_fill_include_exclude_names(parallel, read_csv):
text = '\nA, B, C\n, 1, 2\n3, , 4\n5, 5,\n'
table = read_csv(text, fill_include_names=['A', 'B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is ma.masked)
assert (table['C'][2] is not ma.masked)
table = read_csv(text, fill_exclude_names=['A', 'B'], parallel=parallel)
assert (table['C'][2] is ma.masked)
assert (table['A'][0] is not ma.masked)
assert (table['B'][1] is not ma.masked)
table = read_csv(text, fill_include_names=['A', 'B'], fill_exclude_names=['B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is not ma.masked)
assert (table['C'][2] is not ma.masked)
| null | null | null | missing / empty value handling
| codeqa | @pytest mark parametrize 'parallel' [ True False] def test fill include exclude names parallel read csv text '\n A B C\n 1 2\n 3 4\n 5 5 \n'table read csv text fill include names ['A' 'B'] parallel parallel assert table['A'][ 0 ] is ma masked assert table['B'][ 1 ] is ma masked assert table['C'][ 2 ] is not ma masked table read csv text fill exclude names ['A' 'B'] parallel parallel assert table['C'][ 2 ] is ma masked assert table['A'][ 0 ] is not ma masked assert table['B'][ 1 ] is not ma masked table read csv text fill include names ['A' 'B'] fill exclude names ['B'] parallel parallel assert table['A'][ 0 ] is ma masked assert table['B'][ 1 ] is not ma masked assert table['C'][ 2 ] is not ma masked
| null | null | null | null | Question:
What should fill_include_names and fill_exclude_names filter in the same way that include_names and exclude_names filter output columns ?
Code:
@pytest.mark.parametrize('parallel', [True, False])
def test_fill_include_exclude_names(parallel, read_csv):
text = '\nA, B, C\n, 1, 2\n3, , 4\n5, 5,\n'
table = read_csv(text, fill_include_names=['A', 'B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is ma.masked)
assert (table['C'][2] is not ma.masked)
table = read_csv(text, fill_exclude_names=['A', 'B'], parallel=parallel)
assert (table['C'][2] is ma.masked)
assert (table['A'][0] is not ma.masked)
assert (table['B'][1] is not ma.masked)
table = read_csv(text, fill_include_names=['A', 'B'], fill_exclude_names=['B'], parallel=parallel)
assert (table['A'][0] is ma.masked)
assert (table['B'][1] is not ma.masked)
assert (table['C'][2] is not ma.masked)
|
null | null | null | What does the code close ?
| def end_file(fid):
data_size = 0
fid.write(np.array(FIFF.FIFF_NOP, dtype='>i4').tostring())
fid.write(np.array(FIFF.FIFFT_VOID, dtype='>i4').tostring())
fid.write(np.array(data_size, dtype='>i4').tostring())
fid.write(np.array(FIFF.FIFFV_NEXT_NONE, dtype='>i4').tostring())
check_fiff_length(fid)
fid.close()
| null | null | null | the file
| codeqa | def end file fid data size 0fid write np array FIFF FIFF NOP dtype '>i 4 ' tostring fid write np array FIFF FIFFT VOID dtype '>i 4 ' tostring fid write np array data size dtype '>i 4 ' tostring fid write np array FIFF FIFFV NEXT NONE dtype '>i 4 ' tostring check fiff length fid fid close
| null | null | null | null | Question:
What does the code close ?
Code:
def end_file(fid):
data_size = 0
fid.write(np.array(FIFF.FIFF_NOP, dtype='>i4').tostring())
fid.write(np.array(FIFF.FIFFT_VOID, dtype='>i4').tostring())
fid.write(np.array(data_size, dtype='>i4').tostring())
fid.write(np.array(FIFF.FIFFV_NEXT_NONE, dtype='>i4').tostring())
check_fiff_length(fid)
fid.close()
|
null | null | null | For what purpose do graph g write in single - line adjacency - list format ?
| @open_file(1, mode='wb')
def write_adjlist(G, path, comments='#', delimiter=' ', encoding='utf-8'):
import sys
import time
pargs = ((comments + ' '.join(sys.argv)) + '\n')
header = ((((pargs + comments) + ' GMT {}\n'.format(time.asctime(time.gmtime()))) + comments) + ' {}\n'.format(G.name))
path.write(header.encode(encoding))
for line in generate_adjlist(G, delimiter):
line += '\n'
path.write(line.encode(encoding))
| null | null | null | to path
| codeqa | @open file 1 mode 'wb' def write adjlist G path comments '#' delimiter '' encoding 'utf- 8 ' import sysimport timepargs comments + '' join sys argv + '\n' header pargs + comments + 'GMT{}\n' format time asctime time gmtime + comments + '{}\n' format G name path write header encode encoding for line in generate adjlist G delimiter line + '\n'path write line encode encoding
| null | null | null | null | Question:
For what purpose do graph g write in single - line adjacency - list format ?
Code:
@open_file(1, mode='wb')
def write_adjlist(G, path, comments='#', delimiter=' ', encoding='utf-8'):
import sys
import time
pargs = ((comments + ' '.join(sys.argv)) + '\n')
header = ((((pargs + comments) + ' GMT {}\n'.format(time.asctime(time.gmtime()))) + comments) + ' {}\n'.format(G.name))
path.write(header.encode(encoding))
for line in generate_adjlist(G, delimiter):
line += '\n'
path.write(line.encode(encoding))
|
null | null | null | How do graph g write to path ?
| @open_file(1, mode='wb')
def write_adjlist(G, path, comments='#', delimiter=' ', encoding='utf-8'):
import sys
import time
pargs = ((comments + ' '.join(sys.argv)) + '\n')
header = ((((pargs + comments) + ' GMT {}\n'.format(time.asctime(time.gmtime()))) + comments) + ' {}\n'.format(G.name))
path.write(header.encode(encoding))
for line in generate_adjlist(G, delimiter):
line += '\n'
path.write(line.encode(encoding))
| null | null | null | in single - line adjacency - list format
| codeqa | @open file 1 mode 'wb' def write adjlist G path comments '#' delimiter '' encoding 'utf- 8 ' import sysimport timepargs comments + '' join sys argv + '\n' header pargs + comments + 'GMT{}\n' format time asctime time gmtime + comments + '{}\n' format G name path write header encode encoding for line in generate adjlist G delimiter line + '\n'path write line encode encoding
| null | null | null | null | Question:
How do graph g write to path ?
Code:
@open_file(1, mode='wb')
def write_adjlist(G, path, comments='#', delimiter=' ', encoding='utf-8'):
import sys
import time
pargs = ((comments + ' '.join(sys.argv)) + '\n')
header = ((((pargs + comments) + ' GMT {}\n'.format(time.asctime(time.gmtime()))) + comments) + ' {}\n'.format(G.name))
path.write(header.encode(encoding))
for line in generate_adjlist(G, delimiter):
line += '\n'
path.write(line.encode(encoding))
|
null | null | null | What does the code get ?
| def get_installed_version(dist_name, lookup_dirs=None):
req = pkg_resources.Requirement.parse(dist_name)
if (lookup_dirs is None):
working_set = pkg_resources.WorkingSet()
else:
working_set = pkg_resources.WorkingSet(lookup_dirs)
dist = working_set.find(req)
return (dist.version if dist else None)
| null | null | null | the installed version of dist_name avoiding pkg_resources cache
| codeqa | def get installed version dist name lookup dirs None req pkg resources Requirement parse dist name if lookup dirs is None working set pkg resources Working Set else working set pkg resources Working Set lookup dirs dist working set find req return dist version if dist else None
| null | null | null | null | Question:
What does the code get ?
Code:
def get_installed_version(dist_name, lookup_dirs=None):
req = pkg_resources.Requirement.parse(dist_name)
if (lookup_dirs is None):
working_set = pkg_resources.WorkingSet()
else:
working_set = pkg_resources.WorkingSet(lookup_dirs)
dist = working_set.find(req)
return (dist.version if dist else None)
|
null | null | null | What does the code grab ?
| @gen.engine
def _Start(callback):
client = db_client.DBClient.Instance()
job = Job(client, 'table_sizes')
if options.options.require_lock:
got_lock = (yield gen.Task(job.AcquireLock))
if (got_lock == False):
logging.warning('Failed to acquire job lock: exiting.')
callback()
return
try:
(yield gen.Task(RunOnce, client))
finally:
(yield gen.Task(job.ReleaseLock))
callback()
| null | null | null | a lock on job
| codeqa | @gen enginedef Start callback client db client DB Client Instance job Job client 'table sizes' if options options require lock got lock yield gen Task job Acquire Lock if got lock False logging warning ' Failedtoacquirejoblock exiting ' callback returntry yield gen Task Run Once client finally yield gen Task job Release Lock callback
| null | null | null | null | Question:
What does the code grab ?
Code:
@gen.engine
def _Start(callback):
client = db_client.DBClient.Instance()
job = Job(client, 'table_sizes')
if options.options.require_lock:
got_lock = (yield gen.Task(job.AcquireLock))
if (got_lock == False):
logging.warning('Failed to acquire job lock: exiting.')
callback()
return
try:
(yield gen.Task(RunOnce, client))
finally:
(yield gen.Task(job.ReleaseLock))
callback()
|
null | null | null | What does the code extend ?
| def _extend_blocks(extend_node, blocks):
if is_variable_extend_node(extend_node):
return
parent = extend_node.get_parent(get_context())
for node in _get_nodelist(parent).get_nodes_by_type(BlockNode):
if (not (node.name in blocks)):
blocks[node.name] = node
else:
block = blocks[node.name]
seen_supers = []
while (hasattr(block.super, 'nodelist') and (block.super not in seen_supers)):
seen_supers.append(block.super)
block = block.super
block.super = node
for node in _get_nodelist(parent).get_nodes_by_type(ExtendsNode):
_extend_blocks(node, blocks)
break
| null | null | null | the dictionary blocks with * new * blocks in the parent node
| codeqa | def extend blocks extend node blocks if is variable extend node extend node returnparent extend node get parent get context for node in get nodelist parent get nodes by type Block Node if not node name in blocks blocks[node name] nodeelse block blocks[node name]seen supers []while hasattr block super 'nodelist' and block super not in seen supers seen supers append block super block block superblock super nodefor node in get nodelist parent get nodes by type Extends Node extend blocks node blocks break
| null | null | null | null | Question:
What does the code extend ?
Code:
def _extend_blocks(extend_node, blocks):
if is_variable_extend_node(extend_node):
return
parent = extend_node.get_parent(get_context())
for node in _get_nodelist(parent).get_nodes_by_type(BlockNode):
if (not (node.name in blocks)):
blocks[node.name] = node
else:
block = blocks[node.name]
seen_supers = []
while (hasattr(block.super, 'nodelist') and (block.super not in seen_supers)):
seen_supers.append(block.super)
block = block.super
block.super = node
for node in _get_nodelist(parent).get_nodes_by_type(ExtendsNode):
_extend_blocks(node, blocks)
break
|
null | null | null | What transforms to a lower triangle matrix by performing row operations on it ?
| def lower_triangle(matlist, K):
copy_matlist = copy.deepcopy(matlist)
(lower_triangle, upper_triangle) = LU(copy_matlist, K, reverse=1)
return lower_triangle
| null | null | null | a given matrix
| codeqa | def lower triangle matlist K copy matlist copy deepcopy matlist lower triangle upper triangle LU copy matlist K reverse 1 return lower triangle
| null | null | null | null | Question:
What transforms to a lower triangle matrix by performing row operations on it ?
Code:
def lower_triangle(matlist, K):
copy_matlist = copy.deepcopy(matlist)
(lower_triangle, upper_triangle) = LU(copy_matlist, K, reverse=1)
return lower_triangle
|
null | null | null | How does a given matrix transform to a lower triangle matrix ?
| def lower_triangle(matlist, K):
copy_matlist = copy.deepcopy(matlist)
(lower_triangle, upper_triangle) = LU(copy_matlist, K, reverse=1)
return lower_triangle
| null | null | null | by performing row operations on it
| codeqa | def lower triangle matlist K copy matlist copy deepcopy matlist lower triangle upper triangle LU copy matlist K reverse 1 return lower triangle
| null | null | null | null | Question:
How does a given matrix transform to a lower triangle matrix ?
Code:
def lower_triangle(matlist, K):
copy_matlist = copy.deepcopy(matlist)
(lower_triangle, upper_triangle) = LU(copy_matlist, K, reverse=1)
return lower_triangle
|
null | null | null | What is raised in case of negative priors ?
| def test_gnb_neg_priors():
clf = GaussianNB(priors=np.array([(-1.0), 2.0]))
assert_raises(ValueError, clf.fit, X, y)
| null | null | null | an error
| codeqa | def test gnb neg priors clf Gaussian NB priors np array [ -1 0 2 0] assert raises Value Error clf fit X y
| null | null | null | null | Question:
What is raised in case of negative priors ?
Code:
def test_gnb_neg_priors():
clf = GaussianNB(priors=np.array([(-1.0), 2.0]))
assert_raises(ValueError, clf.fit, X, y)
|
null | null | null | Where is an error raised ?
| def test_gnb_neg_priors():
clf = GaussianNB(priors=np.array([(-1.0), 2.0]))
assert_raises(ValueError, clf.fit, X, y)
| null | null | null | in case of negative priors
| codeqa | def test gnb neg priors clf Gaussian NB priors np array [ -1 0 2 0] assert raises Value Error clf fit X y
| null | null | null | null | Question:
Where is an error raised ?
Code:
def test_gnb_neg_priors():
clf = GaussianNB(priors=np.array([(-1.0), 2.0]))
assert_raises(ValueError, clf.fit, X, y)
|
null | null | null | How does the code resize an image ?
| @cli.command('resize')
@click.option('-w', '--width', type=int, help='The new width of the image.')
@click.option('-h', '--height', type=int, help='The new height of the image.')
@processor
def resize_cmd(images, width, height):
for image in images:
(w, h) = ((width or image.size[0]), (height or image.size[1]))
click.echo(('Resizing "%s" to %dx%d' % (image.filename, w, h)))
image.thumbnail((w, h))
(yield image)
| null | null | null | by fitting it into the box without changing the aspect ratio
| codeqa | @cli command 'resize' @click option '-w' '--width' type int help ' Thenewwidthoftheimage ' @click option '-h' '--height' type int help ' Thenewheightoftheimage ' @processordef resize cmd images width height for image in images w h width or image size[ 0 ] height or image size[ 1 ] click echo ' Resizing"%s"to%dx%d' % image filename w h image thumbnail w h yield image
| null | null | null | null | Question:
How does the code resize an image ?
Code:
@cli.command('resize')
@click.option('-w', '--width', type=int, help='The new width of the image.')
@click.option('-h', '--height', type=int, help='The new height of the image.')
@processor
def resize_cmd(images, width, height):
for image in images:
(w, h) = ((width or image.size[0]), (height or image.size[1]))
click.echo(('Resizing "%s" to %dx%d' % (image.filename, w, h)))
image.thumbnail((w, h))
(yield image)
|
null | null | null | What does the code resize by fitting it into the box without changing the aspect ratio ?
| @cli.command('resize')
@click.option('-w', '--width', type=int, help='The new width of the image.')
@click.option('-h', '--height', type=int, help='The new height of the image.')
@processor
def resize_cmd(images, width, height):
for image in images:
(w, h) = ((width or image.size[0]), (height or image.size[1]))
click.echo(('Resizing "%s" to %dx%d' % (image.filename, w, h)))
image.thumbnail((w, h))
(yield image)
| null | null | null | an image
| codeqa | @cli command 'resize' @click option '-w' '--width' type int help ' Thenewwidthoftheimage ' @click option '-h' '--height' type int help ' Thenewheightoftheimage ' @processordef resize cmd images width height for image in images w h width or image size[ 0 ] height or image size[ 1 ] click echo ' Resizing"%s"to%dx%d' % image filename w h image thumbnail w h yield image
| null | null | null | null | Question:
What does the code resize by fitting it into the box without changing the aspect ratio ?
Code:
@cli.command('resize')
@click.option('-w', '--width', type=int, help='The new width of the image.')
@click.option('-h', '--height', type=int, help='The new height of the image.')
@processor
def resize_cmd(images, width, height):
for image in images:
(w, h) = ((width or image.size[0]), (height or image.size[1]))
click.echo(('Resizing "%s" to %dx%d' % (image.filename, w, h)))
image.thumbnail((w, h))
(yield image)
|
null | null | null | What does the code get ?
| def getNewRepository():
return FilletRepository()
| null | null | null | the repository constructor
| codeqa | def get New Repository return Fillet Repository
| null | null | null | null | Question:
What does the code get ?
Code:
def getNewRepository():
return FilletRepository()
|
null | null | null | When does development be on ?
| def DEBUG(msg, *args, **kwargs):
logger = getLogger('DEBUG')
if (len(logger.handlers) == 0):
logger.addHandler(StreamHandler())
logger.propagate = False
logger.setLevel(logging.DEBUG)
logger.DEV(msg, *args, **kwargs)
| null | null | null | always
| codeqa | def DEBUG msg *args **kwargs logger get Logger 'DEBUG' if len logger handlers 0 logger add Handler Stream Handler logger propagate Falselogger set Level logging DEBUG logger DEV msg *args **kwargs
| null | null | null | null | Question:
When does development be on ?
Code:
def DEBUG(msg, *args, **kwargs):
logger = getLogger('DEBUG')
if (len(logger.handlers) == 0):
logger.addHandler(StreamHandler())
logger.propagate = False
logger.setLevel(logging.DEBUG)
logger.DEV(msg, *args, **kwargs)
|
null | null | null | When does a dictionary of credentials of potentially sensitive info clean ?
| def _clean_credentials(credentials):
SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I)
CLEANSED_SUBSTITUTE = '********************'
for key in credentials:
if SENSITIVE_CREDENTIALS.search(key):
credentials[key] = CLEANSED_SUBSTITUTE
return credentials
| null | null | null | before sending to less secure functions
| codeqa | def clean credentials credentials SENSITIVE CREDENTIALS re compile 'api token key secret password signature' re I CLEANSED SUBSTITUTE '********************'for key in credentials if SENSITIVE CREDENTIALS search key credentials[key] CLEANSED SUBSTITUT Ereturn credentials
| null | null | null | null | Question:
When does a dictionary of credentials of potentially sensitive info clean ?
Code:
def _clean_credentials(credentials):
SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I)
CLEANSED_SUBSTITUTE = '********************'
for key in credentials:
if SENSITIVE_CREDENTIALS.search(key):
credentials[key] = CLEANSED_SUBSTITUTE
return credentials
|
null | null | null | What does the code assert ?
| def template_used(response, template_name):
templates = []
templates += [t.name for t in getattr(response, 'templates', [])]
templates += getattr(response, 'jinja_templates', [])
return (template_name in templates)
| null | null | null | a given template was used first off
| codeqa | def template used response template name templates []templates + [t name for t in getattr response 'templates' [] ]templates + getattr response 'jinja templates' [] return template name in templates
| null | null | null | null | Question:
What does the code assert ?
Code:
def template_used(response, template_name):
templates = []
templates += [t.name for t in getattr(response, 'templates', [])]
templates += getattr(response, 'jinja_templates', [])
return (template_name in templates)
|
null | null | null | When was a given template used ?
| def template_used(response, template_name):
templates = []
templates += [t.name for t in getattr(response, 'templates', [])]
templates += getattr(response, 'jinja_templates', [])
return (template_name in templates)
| null | null | null | first off
| codeqa | def template used response template name templates []templates + [t name for t in getattr response 'templates' [] ]templates + getattr response 'jinja templates' [] return template name in templates
| null | null | null | null | Question:
When was a given template used ?
Code:
def template_used(response, template_name):
templates = []
templates += [t.name for t in getattr(response, 'templates', [])]
templates += getattr(response, 'jinja_templates', [])
return (template_name in templates)
|
null | null | null | What does the code create ?
| @context.quietfunc
@with_device
def mkdir(path):
if (not path.startswith('/')):
log.error(('Must provide an absolute path: %r' % path))
with AdbClient() as c:
st = c.stat(path)
if (st and stat.S_ISDIR(st['mode'])):
return
result = process(['mkdir', path]).recvall()
if result:
log.error(result)
| null | null | null | a directory on the target device
| codeqa | @context quietfunc@with devicedef mkdir path if not path startswith '/' log error ' Mustprovideanabsolutepath %r' % path with Adb Client as c st c stat path if st and stat S ISDIR st['mode'] returnresult process ['mkdir' path] recvall if result log error result
| null | null | null | null | Question:
What does the code create ?
Code:
@context.quietfunc
@with_device
def mkdir(path):
if (not path.startswith('/')):
log.error(('Must provide an absolute path: %r' % path))
with AdbClient() as c:
st = c.stat(path)
if (st and stat.S_ISDIR(st['mode'])):
return
result = process(['mkdir', path]).recvall()
if result:
log.error(result)
|
null | null | null | What will mark a string for translation ?
| def do_translate(parser, token):
class TranslateParser(TokenParser, ):
def top(self):
value = self.value()
if (value[0] == "'"):
pos = None
m = re.match("^'([^']+)'(\\|.*$)", value)
if m:
value = ('"%s"%s' % (m.group(1).replace('"', '\\"'), m.group(2)))
elif (value[(-1)] == "'"):
value = ('"%s"' % value[1:(-1)].replace('"', '\\"'))
if self.more():
if (self.tag() == 'noop'):
noop = True
else:
raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else:
noop = False
return (value, noop)
(value, noop) = TranslateParser(token.contents).top()
return TranslateNode(parser.compile_filter(value), noop)
| null | null | null | this
| codeqa | def do translate parser token class Translate Parser Token Parser def top self value self value if value[ 0 ] "'" pos Nonem re match "^' [^']+ ' \\ *$ " value if m value '"%s"%s' % m group 1 replace '"' '\\"' m group 2 elif value[ -1 ] "'" value '"%s"' % value[ 1 -1 ] replace '"' '\\"' if self more if self tag 'noop' noop Trueelse raise Template Syntax Error "onlyoptionfor'trans'is'noop'" else noop Falsereturn value noop value noop Translate Parser token contents top return Translate Node parser compile filter value noop
| null | null | null | null | Question:
What will mark a string for translation ?
Code:
def do_translate(parser, token):
class TranslateParser(TokenParser, ):
def top(self):
value = self.value()
if (value[0] == "'"):
pos = None
m = re.match("^'([^']+)'(\\|.*$)", value)
if m:
value = ('"%s"%s' % (m.group(1).replace('"', '\\"'), m.group(2)))
elif (value[(-1)] == "'"):
value = ('"%s"' % value[1:(-1)].replace('"', '\\"'))
if self.more():
if (self.tag() == 'noop'):
noop = True
else:
raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else:
noop = False
return (value, noop)
(value, noop) = TranslateParser(token.contents).top()
return TranslateNode(parser.compile_filter(value), noop)
|
null | null | null | What will this mark ?
| def do_translate(parser, token):
class TranslateParser(TokenParser, ):
def top(self):
value = self.value()
if (value[0] == "'"):
pos = None
m = re.match("^'([^']+)'(\\|.*$)", value)
if m:
value = ('"%s"%s' % (m.group(1).replace('"', '\\"'), m.group(2)))
elif (value[(-1)] == "'"):
value = ('"%s"' % value[1:(-1)].replace('"', '\\"'))
if self.more():
if (self.tag() == 'noop'):
noop = True
else:
raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else:
noop = False
return (value, noop)
(value, noop) = TranslateParser(token.contents).top()
return TranslateNode(parser.compile_filter(value), noop)
| null | null | null | a string for translation
| codeqa | def do translate parser token class Translate Parser Token Parser def top self value self value if value[ 0 ] "'" pos Nonem re match "^' [^']+ ' \\ *$ " value if m value '"%s"%s' % m group 1 replace '"' '\\"' m group 2 elif value[ -1 ] "'" value '"%s"' % value[ 1 -1 ] replace '"' '\\"' if self more if self tag 'noop' noop Trueelse raise Template Syntax Error "onlyoptionfor'trans'is'noop'" else noop Falsereturn value noop value noop Translate Parser token contents top return Translate Node parser compile filter value noop
| null | null | null | null | Question:
What will this mark ?
Code:
def do_translate(parser, token):
class TranslateParser(TokenParser, ):
def top(self):
value = self.value()
if (value[0] == "'"):
pos = None
m = re.match("^'([^']+)'(\\|.*$)", value)
if m:
value = ('"%s"%s' % (m.group(1).replace('"', '\\"'), m.group(2)))
elif (value[(-1)] == "'"):
value = ('"%s"' % value[1:(-1)].replace('"', '\\"'))
if self.more():
if (self.tag() == 'noop'):
noop = True
else:
raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else:
noop = False
return (value, noop)
(value, noop) = TranslateParser(token.contents).top()
return TranslateNode(parser.compile_filter(value), noop)
|
null | null | null | What will translate the string for the current language ?
| def do_translate(parser, token):
class TranslateParser(TokenParser, ):
def top(self):
value = self.value()
if (value[0] == "'"):
pos = None
m = re.match("^'([^']+)'(\\|.*$)", value)
if m:
value = ('"%s"%s' % (m.group(1).replace('"', '\\"'), m.group(2)))
elif (value[(-1)] == "'"):
value = ('"%s"' % value[1:(-1)].replace('"', '\\"'))
if self.more():
if (self.tag() == 'noop'):
noop = True
else:
raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else:
noop = False
return (value, noop)
(value, noop) = TranslateParser(token.contents).top()
return TranslateNode(parser.compile_filter(value), noop)
| null | null | null | this
| codeqa | def do translate parser token class Translate Parser Token Parser def top self value self value if value[ 0 ] "'" pos Nonem re match "^' [^']+ ' \\ *$ " value if m value '"%s"%s' % m group 1 replace '"' '\\"' m group 2 elif value[ -1 ] "'" value '"%s"' % value[ 1 -1 ] replace '"' '\\"' if self more if self tag 'noop' noop Trueelse raise Template Syntax Error "onlyoptionfor'trans'is'noop'" else noop Falsereturn value noop value noop Translate Parser token contents top return Translate Node parser compile filter value noop
| null | null | null | null | Question:
What will translate the string for the current language ?
Code:
def do_translate(parser, token):
class TranslateParser(TokenParser, ):
def top(self):
value = self.value()
if (value[0] == "'"):
pos = None
m = re.match("^'([^']+)'(\\|.*$)", value)
if m:
value = ('"%s"%s' % (m.group(1).replace('"', '\\"'), m.group(2)))
elif (value[(-1)] == "'"):
value = ('"%s"' % value[1:(-1)].replace('"', '\\"'))
if self.more():
if (self.tag() == 'noop'):
noop = True
else:
raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else:
noop = False
return (value, noop)
(value, noop) = TranslateParser(token.contents).top()
return TranslateNode(parser.compile_filter(value), noop)
|
null | null | null | What will this translate for the current language ?
| def do_translate(parser, token):
class TranslateParser(TokenParser, ):
def top(self):
value = self.value()
if (value[0] == "'"):
pos = None
m = re.match("^'([^']+)'(\\|.*$)", value)
if m:
value = ('"%s"%s' % (m.group(1).replace('"', '\\"'), m.group(2)))
elif (value[(-1)] == "'"):
value = ('"%s"' % value[1:(-1)].replace('"', '\\"'))
if self.more():
if (self.tag() == 'noop'):
noop = True
else:
raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else:
noop = False
return (value, noop)
(value, noop) = TranslateParser(token.contents).top()
return TranslateNode(parser.compile_filter(value), noop)
| null | null | null | the string
| codeqa | def do translate parser token class Translate Parser Token Parser def top self value self value if value[ 0 ] "'" pos Nonem re match "^' [^']+ ' \\ *$ " value if m value '"%s"%s' % m group 1 replace '"' '\\"' m group 2 elif value[ -1 ] "'" value '"%s"' % value[ 1 -1 ] replace '"' '\\"' if self more if self tag 'noop' noop Trueelse raise Template Syntax Error "onlyoptionfor'trans'is'noop'" else noop Falsereturn value noop value noop Translate Parser token contents top return Translate Node parser compile filter value noop
| null | null | null | null | Question:
What will this translate for the current language ?
Code:
def do_translate(parser, token):
class TranslateParser(TokenParser, ):
def top(self):
value = self.value()
if (value[0] == "'"):
pos = None
m = re.match("^'([^']+)'(\\|.*$)", value)
if m:
value = ('"%s"%s' % (m.group(1).replace('"', '\\"'), m.group(2)))
elif (value[(-1)] == "'"):
value = ('"%s"' % value[1:(-1)].replace('"', '\\"'))
if self.more():
if (self.tag() == 'noop'):
noop = True
else:
raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else:
noop = False
return (value, noop)
(value, noop) = TranslateParser(token.contents).top()
return TranslateNode(parser.compile_filter(value), noop)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.