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 does the code replace ?
def _scal_elemwise_with_nfunc(nfunc, nin, nout): def construct(symbol): symbolname = symbol.__name__ inplace = symbolname.endswith('_inplace') if inplace: msg = 'inplace' else: msg = 'no_inplace' n = ('Elemwise{%s,%s}' % (symbolname, msg)) if inplace: scalar_op = getattr(scal, symbolname[:(- len('_inplace'))]) inplace_scalar_op = scalar_op.__class__(scal.transfer_type(0)) rval = elemwise.Elemwise(inplace_scalar_op, {0: 0}, name=n, nfunc_spec=(nfunc and (nfunc, nin, nout))) else: scalar_op = getattr(scal, symbolname) rval = elemwise.Elemwise(scalar_op, name=n, nfunc_spec=(nfunc and (nfunc, nin, nout))) if getattr(symbol, '__doc__', False): rval.__doc__ = ((symbol.__doc__ + '\n') + rval.__doc__) rval.__epydoc_asRoutine = symbol rval.__module__ = 'tensor' pprint.assign(rval, printing.FunctionPrinter(symbolname)) return rval return construct
null
null
null
a symbol definition with an elementwise version of the corresponding scalar op
codeqa
def scal elemwise with nfunc nfunc nin nout def construct symbol symbolname symbol name inplace symbolname endswith ' inplace' if inplace msg 'inplace'else msg 'no inplace'n ' Elemwise{%s %s}' % symbolname msg if inplace scalar op getattr scal symbolname[ - len ' inplace' ] inplace scalar op scalar op class scal transfer type 0 rval elemwise Elemwise inplace scalar op {0 0} name n nfunc spec nfunc and nfunc nin nout else scalar op getattr scal symbolname rval elemwise Elemwise scalar op name n nfunc spec nfunc and nfunc nin nout if getattr symbol ' doc ' False rval doc symbol doc + '\n' + rval doc rval epydoc as Routine symbolrval module 'tensor'pprint assign rval printing Function Printer symbolname return rvalreturn construct
null
null
null
null
Question: What does the code replace ? Code: def _scal_elemwise_with_nfunc(nfunc, nin, nout): def construct(symbol): symbolname = symbol.__name__ inplace = symbolname.endswith('_inplace') if inplace: msg = 'inplace' else: msg = 'no_inplace' n = ('Elemwise{%s,%s}' % (symbolname, msg)) if inplace: scalar_op = getattr(scal, symbolname[:(- len('_inplace'))]) inplace_scalar_op = scalar_op.__class__(scal.transfer_type(0)) rval = elemwise.Elemwise(inplace_scalar_op, {0: 0}, name=n, nfunc_spec=(nfunc and (nfunc, nin, nout))) else: scalar_op = getattr(scal, symbolname) rval = elemwise.Elemwise(scalar_op, name=n, nfunc_spec=(nfunc and (nfunc, nin, nout))) if getattr(symbol, '__doc__', False): rval.__doc__ = ((symbol.__doc__ + '\n') + rval.__doc__) rval.__epydoc_asRoutine = symbol rval.__module__ = 'tensor' pprint.assign(rval, printing.FunctionPrinter(symbolname)) return rval return construct
null
null
null
By how much do the absolute name of the module to be imported return ?
def _resolve_name(name, package, level): if (not hasattr(package, 'rindex')): raise ValueError("'package' not set to a string") dot = len(package) for x in xrange(level, 1, (-1)): try: dot = package.rindex('.', 0, dot) except ValueError: raise ValueError('attempted relative import beyond top-level package') return ('%s.%s' % (package[:dot], name))
null
null
null
code
codeqa
def resolve name name package level if not hasattr package 'rindex' raise Value Error "'package'notsettoastring" dot len package for x in xrange level 1 -1 try dot package rindex ' ' 0 dot except Value Error raise Value Error 'attemptedrelativeimportbeyondtop-levelpackage' return '%s %s' % package[ dot] name
null
null
null
null
Question: By how much do the absolute name of the module to be imported return ? Code: def _resolve_name(name, package, level): if (not hasattr(package, 'rindex')): raise ValueError("'package' not set to a string") dot = len(package) for x in xrange(level, 1, (-1)): try: dot = package.rindex('.', 0, dot) except ValueError: raise ValueError('attempted relative import beyond top-level package') return ('%s.%s' % (package[:dot], name))
null
null
null
What does the code delete ?
def resource_view_clear(context, data_dict): model = context['model'] _check_access('resource_view_clear', context, data_dict) view_types = data_dict.get('view_types') model.ResourceView.delete_all(view_types) model.repo.commit()
null
null
null
all resource views
codeqa
def resource view clear context data dict model context['model'] check access 'resource view clear' context data dict view types data dict get 'view types' model Resource View delete all view types model repo commit
null
null
null
null
Question: What does the code delete ? Code: def resource_view_clear(context, data_dict): model = context['model'] _check_access('resource_view_clear', context, data_dict) view_types = data_dict.get('view_types') model.ResourceView.delete_all(view_types) model.repo.commit()
null
null
null
Where is filename located ?
def belongs_to_folder(path, fileName): if (not path.endswith(os.path.sep)): path += os.path.sep return fileName.startswith(path)
null
null
null
under path structure
codeqa
def belongs to folder path file Name if not path endswith os path sep path + os path sepreturn file Name startswith path
null
null
null
null
Question: Where is filename located ? Code: def belongs_to_folder(path, fileName): if (not path.endswith(os.path.sep)): path += os.path.sep return fileName.startswith(path)
null
null
null
What is located under path structure ?
def belongs_to_folder(path, fileName): if (not path.endswith(os.path.sep)): path += os.path.sep return fileName.startswith(path)
null
null
null
filename
codeqa
def belongs to folder path file Name if not path endswith os path sep path + os path sepreturn file Name startswith path
null
null
null
null
Question: What is located under path structure ? Code: def belongs_to_folder(path, fileName): if (not path.endswith(os.path.sep)): path += os.path.sep return fileName.startswith(path)
null
null
null
What does the code get ?
def getNewRepository(): return LiftRepository()
null
null
null
new repository
codeqa
def get New Repository return Lift Repository
null
null
null
null
Question: What does the code get ? Code: def getNewRepository(): return LiftRepository()
null
null
null
How will utility conversion function create join tuple ?
def to_join(obj): if isinstance(obj, (tuple, list)): alias = None method = None if (len(obj) == 3): alias = obj[2] elif (len(obj) == 4): (alias, method) = (obj[2], obj[3]) elif ((len(obj) < 2) or (len(obj) > 4)): raise ArgumentError('Join object can have 1 to 4 items has {}: {}'.format(len(obj), obj)) master = to_join_key(obj[0]) detail = to_join_key(obj[1]) return Join(master, detail, alias, method) elif hasattr(obj, 'get'): return Join(to_join_key(obj.get('master')), to_join_key(obj.get('detail')), obj.get('alias'), obj.get('method')) else: return Join(to_join_key(obj.master), to_join_key(obj.detail), obj.alias, obj.method)
null
null
null
from an anonymous tuple
codeqa
def to join obj if isinstance obj tuple list alias Nonemethod Noneif len obj 3 alias obj[ 2 ]elif len obj 4 alias method obj[ 2 ] obj[ 3 ] elif len obj < 2 or len obj > 4 raise Argument Error ' Joinobjectcanhave 1 to 4 itemshas{} {}' format len obj obj master to join key obj[ 0 ] detail to join key obj[ 1 ] return Join master detail alias method elif hasattr obj 'get' return Join to join key obj get 'master' to join key obj get 'detail' obj get 'alias' obj get 'method' else return Join to join key obj master to join key obj detail obj alias obj method
null
null
null
null
Question: How will utility conversion function create join tuple ? Code: def to_join(obj): if isinstance(obj, (tuple, list)): alias = None method = None if (len(obj) == 3): alias = obj[2] elif (len(obj) == 4): (alias, method) = (obj[2], obj[3]) elif ((len(obj) < 2) or (len(obj) > 4)): raise ArgumentError('Join object can have 1 to 4 items has {}: {}'.format(len(obj), obj)) master = to_join_key(obj[0]) detail = to_join_key(obj[1]) return Join(master, detail, alias, method) elif hasattr(obj, 'get'): return Join(to_join_key(obj.get('master')), to_join_key(obj.get('detail')), obj.get('alias'), obj.get('method')) else: return Join(to_join_key(obj.master), to_join_key(obj.detail), obj.alias, obj.method)
null
null
null
How do tuple join ?
def to_join(obj): if isinstance(obj, (tuple, list)): alias = None method = None if (len(obj) == 3): alias = obj[2] elif (len(obj) == 4): (alias, method) = (obj[2], obj[3]) elif ((len(obj) < 2) or (len(obj) > 4)): raise ArgumentError('Join object can have 1 to 4 items has {}: {}'.format(len(obj), obj)) master = to_join_key(obj[0]) detail = to_join_key(obj[1]) return Join(master, detail, alias, method) elif hasattr(obj, 'get'): return Join(to_join_key(obj.get('master')), to_join_key(obj.get('detail')), obj.get('alias'), obj.get('method')) else: return Join(to_join_key(obj.master), to_join_key(obj.detail), obj.alias, obj.method)
null
null
null
from an anonymous tuple
codeqa
def to join obj if isinstance obj tuple list alias Nonemethod Noneif len obj 3 alias obj[ 2 ]elif len obj 4 alias method obj[ 2 ] obj[ 3 ] elif len obj < 2 or len obj > 4 raise Argument Error ' Joinobjectcanhave 1 to 4 itemshas{} {}' format len obj obj master to join key obj[ 0 ] detail to join key obj[ 1 ] return Join master detail alias method elif hasattr obj 'get' return Join to join key obj get 'master' to join key obj get 'detail' obj get 'alias' obj get 'method' else return Join to join key obj master to join key obj detail obj alias obj method
null
null
null
null
Question: How do tuple join ? Code: def to_join(obj): if isinstance(obj, (tuple, list)): alias = None method = None if (len(obj) == 3): alias = obj[2] elif (len(obj) == 4): (alias, method) = (obj[2], obj[3]) elif ((len(obj) < 2) or (len(obj) > 4)): raise ArgumentError('Join object can have 1 to 4 items has {}: {}'.format(len(obj), obj)) master = to_join_key(obj[0]) detail = to_join_key(obj[1]) return Join(master, detail, alias, method) elif hasattr(obj, 'get'): return Join(to_join_key(obj.get('master')), to_join_key(obj.get('detail')), obj.get('alias'), obj.get('method')) else: return Join(to_join_key(obj.master), to_join_key(obj.detail), obj.alias, obj.method)
null
null
null
What does the code convert into a space - separated list of flag text values ?
def to_text(flags): return _to_text(flags, _by_value, _flags_order)
null
null
null
a flags value
codeqa
def to text flags return to text flags by value flags order
null
null
null
null
Question: What does the code convert into a space - separated list of flag text values ? Code: def to_text(flags): return _to_text(flags, _by_value, _flags_order)
null
null
null
How do python types freeze ?
def freeze(obj): if isinstance(obj, dict): return ImmutableDict(obj) if isinstance(obj, list): return ImmutableList(obj) if isinstance(obj, set): return ImmutableSet(obj) return obj
null
null
null
by turning them into immutable structures
codeqa
def freeze obj if isinstance obj dict return Immutable Dict obj if isinstance obj list return Immutable List obj if isinstance obj set return Immutable Set obj return obj
null
null
null
null
Question: How do python types freeze ? Code: def freeze(obj): if isinstance(obj, dict): return ImmutableDict(obj) if isinstance(obj, list): return ImmutableList(obj) if isinstance(obj, set): return ImmutableSet(obj) return obj
null
null
null
What is executing in a shell ?
def getoutputerror(cmd): return get_output_error_code(cmd)[:2]
null
null
null
cmd
codeqa
def getoutputerror cmd return get output error code cmd [ 2]
null
null
null
null
Question: What is executing in a shell ? Code: def getoutputerror(cmd): return get_output_error_code(cmd)[:2]
null
null
null
Where do cmd execute ?
def getoutputerror(cmd): return get_output_error_code(cmd)[:2]
null
null
null
in a shell
codeqa
def getoutputerror cmd return get output error code cmd [ 2]
null
null
null
null
Question: Where do cmd execute ? Code: def getoutputerror(cmd): return get_output_error_code(cmd)[:2]
null
null
null
What do users play ?
@command('history') def view_history(duplicates=True): history = g.userhist.get('history') try: hist_list = list(reversed(history.songs)) message = 'Viewing play history' if (not duplicates): seen = set() seen_add = seen.add hist_list = [x for x in hist_list if (not ((x in seen) or seen_add(x)))] message = 'Viewing recent played songs' paginatesongs(hist_list) g.message = message except AttributeError: g.content = logo(c.r) g.message = 'History empty'
null
null
null
history
codeqa
@command 'history' def view history duplicates True history g userhist get 'history' try hist list list reversed history songs message ' Viewingplayhistory'if not duplicates seen set seen add seen addhist list [x for x in hist list if not x in seen or seen add x ]message ' Viewingrecentplayedsongs'paginatesongs hist list g message messageexcept Attribute Error g content logo c r g message ' Historyempty'
null
null
null
null
Question: What do users play ? Code: @command('history') def view_history(duplicates=True): history = g.userhist.get('history') try: hist_list = list(reversed(history.songs)) message = 'Viewing play history' if (not duplicates): seen = set() seen_add = seen.add hist_list = [x for x in hist_list if (not ((x in seen) or seen_add(x)))] message = 'Viewing recent played songs' paginatesongs(hist_list) g.message = message except AttributeError: g.content = logo(c.r) g.message = 'History empty'
null
null
null
What play history ?
@command('history') def view_history(duplicates=True): history = g.userhist.get('history') try: hist_list = list(reversed(history.songs)) message = 'Viewing play history' if (not duplicates): seen = set() seen_add = seen.add hist_list = [x for x in hist_list if (not ((x in seen) or seen_add(x)))] message = 'Viewing recent played songs' paginatesongs(hist_list) g.message = message except AttributeError: g.content = logo(c.r) g.message = 'History empty'
null
null
null
users
codeqa
@command 'history' def view history duplicates True history g userhist get 'history' try hist list list reversed history songs message ' Viewingplayhistory'if not duplicates seen set seen add seen addhist list [x for x in hist list if not x in seen or seen add x ]message ' Viewingrecentplayedsongs'paginatesongs hist list g message messageexcept Attribute Error g content logo c r g message ' Historyempty'
null
null
null
null
Question: What play history ? Code: @command('history') def view_history(duplicates=True): history = g.userhist.get('history') try: hist_list = list(reversed(history.songs)) message = 'Viewing play history' if (not duplicates): seen = set() seen_add = seen.add hist_list = [x for x in hist_list if (not ((x in seen) or seen_add(x)))] message = 'Viewing recent played songs' paginatesongs(hist_list) g.message = message except AttributeError: g.content = logo(c.r) g.message = 'History empty'
null
null
null
What does the code create ?
def layout(*args, **kwargs): responsive = kwargs.pop('responsive', None) sizing_mode = kwargs.pop('sizing_mode', 'fixed') children = kwargs.pop('children', None) if responsive: sizing_mode = _convert_responsive(responsive) _verify_sizing_mode(sizing_mode) children = _handle_children(children=children, *args) rows = [] for r in children: row_children = [] for item in r: if isinstance(item, LayoutDOM): item.sizing_mode = sizing_mode row_children.append(item) else: raise ValueError(('Only LayoutDOM items can be inserted into a layout.\n Tried to insert: %s of type %s' % (item, type(item)))) rows.append(row(children=row_children, sizing_mode=sizing_mode)) grid = column(children=rows, sizing_mode=sizing_mode) return grid
null
null
null
a grid - based arrangement of bokeh layout objects
codeqa
def layout *args **kwargs responsive kwargs pop 'responsive' None sizing mode kwargs pop 'sizing mode' 'fixed' children kwargs pop 'children' None if responsive sizing mode convert responsive responsive verify sizing mode sizing mode children handle children children children *args rows []for r in children row children []for item in r if isinstance item Layout DOM item sizing mode sizing moderow children append item else raise Value Error ' Only Layout DO Mitemscanbeinsertedintoalayout \n Triedtoinsert %softype%s' % item type item rows append row children row children sizing mode sizing mode grid column children rows sizing mode sizing mode return grid
null
null
null
null
Question: What does the code create ? Code: def layout(*args, **kwargs): responsive = kwargs.pop('responsive', None) sizing_mode = kwargs.pop('sizing_mode', 'fixed') children = kwargs.pop('children', None) if responsive: sizing_mode = _convert_responsive(responsive) _verify_sizing_mode(sizing_mode) children = _handle_children(children=children, *args) rows = [] for r in children: row_children = [] for item in r: if isinstance(item, LayoutDOM): item.sizing_mode = sizing_mode row_children.append(item) else: raise ValueError(('Only LayoutDOM items can be inserted into a layout.\n Tried to insert: %s of type %s' % (item, type(item)))) rows.append(row(children=row_children, sizing_mode=sizing_mode)) grid = column(children=rows, sizing_mode=sizing_mode) return grid
null
null
null
Where do a set of files download ?
def maybe_download(file_urls, directory): assert create_dir_if_needed(directory) result = [] for file_url in file_urls: filename = file_url.split('/')[(-1)] if filename.endswith('?raw=true'): filename = filename[:(-9)] filepath = ((directory + '/') + filename) result.append(filepath) if (not gfile.Exists(filepath)): def _progress(count, block_size, total_size): sys.stdout.write(('\r>> Downloading %s %.1f%%' % (filename, ((float((count * block_size)) / float(total_size)) * 100.0)))) sys.stdout.flush() (filepath, _) = urllib.request.urlretrieve(file_url, filepath, _progress) print() statinfo = os.stat(filepath) print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') return result
null
null
null
in temporary local folder
codeqa
def maybe download file urls directory assert create dir if needed directory result []for file url in file urls filename file url split '/' [ -1 ]if filename endswith '?raw true' filename filename[ -9 ]filepath directory + '/' + filename result append filepath if not gfile Exists filepath def progress count block size total size sys stdout write '\r>> Downloading%s% 1f%%' % filename float count * block size / float total size * 100 0 sys stdout flush filepath urllib request urlretrieve file url filepath progress print statinfo os stat filepath print ' Successfullydownloaded' filename statinfo st size 'bytes ' return result
null
null
null
null
Question: Where do a set of files download ? Code: def maybe_download(file_urls, directory): assert create_dir_if_needed(directory) result = [] for file_url in file_urls: filename = file_url.split('/')[(-1)] if filename.endswith('?raw=true'): filename = filename[:(-9)] filepath = ((directory + '/') + filename) result.append(filepath) if (not gfile.Exists(filepath)): def _progress(count, block_size, total_size): sys.stdout.write(('\r>> Downloading %s %.1f%%' % (filename, ((float((count * block_size)) / float(total_size)) * 100.0)))) sys.stdout.flush() (filepath, _) = urllib.request.urlretrieve(file_url, filepath, _progress) print() statinfo = os.stat(filepath) print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') return result
null
null
null
What downloads in temporary local folder ?
def maybe_download(file_urls, directory): assert create_dir_if_needed(directory) result = [] for file_url in file_urls: filename = file_url.split('/')[(-1)] if filename.endswith('?raw=true'): filename = filename[:(-9)] filepath = ((directory + '/') + filename) result.append(filepath) if (not gfile.Exists(filepath)): def _progress(count, block_size, total_size): sys.stdout.write(('\r>> Downloading %s %.1f%%' % (filename, ((float((count * block_size)) / float(total_size)) * 100.0)))) sys.stdout.flush() (filepath, _) = urllib.request.urlretrieve(file_url, filepath, _progress) print() statinfo = os.stat(filepath) print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') return result
null
null
null
a set of files
codeqa
def maybe download file urls directory assert create dir if needed directory result []for file url in file urls filename file url split '/' [ -1 ]if filename endswith '?raw true' filename filename[ -9 ]filepath directory + '/' + filename result append filepath if not gfile Exists filepath def progress count block size total size sys stdout write '\r>> Downloading%s% 1f%%' % filename float count * block size / float total size * 100 0 sys stdout flush filepath urllib request urlretrieve file url filepath progress print statinfo os stat filepath print ' Successfullydownloaded' filename statinfo st size 'bytes ' return result
null
null
null
null
Question: What downloads in temporary local folder ? Code: def maybe_download(file_urls, directory): assert create_dir_if_needed(directory) result = [] for file_url in file_urls: filename = file_url.split('/')[(-1)] if filename.endswith('?raw=true'): filename = filename[:(-9)] filepath = ((directory + '/') + filename) result.append(filepath) if (not gfile.Exists(filepath)): def _progress(count, block_size, total_size): sys.stdout.write(('\r>> Downloading %s %.1f%%' % (filename, ((float((count * block_size)) / float(total_size)) * 100.0)))) sys.stdout.flush() (filepath, _) = urllib.request.urlretrieve(file_url, filepath, _progress) print() statinfo = os.stat(filepath) print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') return result
null
null
null
What does the code calculate ?
def argrelmin(data, axis=0, order=1, mode='clip'): return argrelextrema(data, np.less, axis, order, mode)
null
null
null
the relative minima of data
codeqa
def argrelmin data axis 0 order 1 mode 'clip' return argrelextrema data np less axis order mode
null
null
null
null
Question: What does the code calculate ? Code: def argrelmin(data, axis=0, order=1, mode='clip'): return argrelextrema(data, np.less, axis, order, mode)
null
null
null
What can we take like /s / URL ?
def force_html(): c.render_style = 'html' c.extension = None c.content_type = 'text/html; charset=UTF-8'
null
null
null
uris
codeqa
def force html c render style 'html'c extension Nonec content type 'text/html charset UTF- 8 '
null
null
null
null
Question: What can we take like /s / URL ? Code: def force_html(): c.render_style = 'html' c.extension = None c.content_type = 'text/html; charset=UTF-8'
null
null
null
What are logs notification test when there are no paths to uninstall ?
def test_uninstallpathset_no_paths(caplog): from pip.req.req_uninstall import UninstallPathSet from pkg_resources import get_distribution test_dist = get_distribution('pip') uninstall_set = UninstallPathSet(test_dist) uninstall_set.remove() assert ("Can't uninstall 'pip'. No files were found to uninstall." in caplog.text())
null
null
null
uninstallpathset
codeqa
def test uninstallpathset no paths caplog from pip req req uninstall import Uninstall Path Setfrom pkg resources import get distributiontest dist get distribution 'pip' uninstall set Uninstall Path Set test dist uninstall set remove assert " Can'tuninstall'pip' Nofileswerefoundtouninstall " in caplog text
null
null
null
null
Question: What are logs notification test when there are no paths to uninstall ? Code: def test_uninstallpathset_no_paths(caplog): from pip.req.req_uninstall import UninstallPathSet from pkg_resources import get_distribution test_dist = get_distribution('pip') uninstall_set = UninstallPathSet(test_dist) uninstall_set.remove() assert ("Can't uninstall 'pip'. No files were found to uninstall." in caplog.text())
null
null
null
When do handlers all handlers remove from a logger ?
@contextmanager def no_handlers_for_logger(name=None): log = logging.getLogger(name) old_handlers = log.handlers old_propagate = log.propagate log.handlers = [NullHandler()] try: (yield) finally: if old_handlers: log.handlers = old_handlers else: log.propagate = old_propagate
null
null
null
temporarily
codeqa
@contextmanagerdef no handlers for logger name None log logging get Logger name old handlers log handlersold propagate log propagatelog handlers [ Null Handler ]try yield finally if old handlers log handlers old handlerselse log propagate old propagate
null
null
null
null
Question: When do handlers all handlers remove from a logger ? Code: @contextmanager def no_handlers_for_logger(name=None): log = logging.getLogger(name) old_handlers = log.handlers old_propagate = log.propagate log.handlers = [NullHandler()] try: (yield) finally: if old_handlers: log.handlers = old_handlers else: log.propagate = old_propagate
null
null
null
What does the code convert to the full template name based on the current_template_name ?
def construct_relative_path(current_template_name, relative_name): if (not any((relative_name.startswith(x) for x in ["'./", "'../", '"./', '"../']))): return relative_name new_name = posixpath.normpath(posixpath.join(posixpath.dirname(current_template_name.lstrip('/')), relative_name.strip('\'"'))) if new_name.startswith('../'): raise TemplateSyntaxError(("The relative path '%s' points outside the file hierarchy that template '%s' is in." % (relative_name, current_template_name))) if (current_template_name.lstrip('/') == new_name): raise TemplateSyntaxError(("The relative path '%s' was translated to template name '%s', the same template in which the tag appears." % (relative_name, current_template_name))) return ('"%s"' % new_name)
null
null
null
a relative path
codeqa
def construct relative path current template name relative name if not any relative name startswith x for x in ["' /" "' /" '" /' '" /'] return relative namenew name posixpath normpath posixpath join posixpath dirname current template name lstrip '/' relative name strip '\'"' if new name startswith ' /' raise Template Syntax Error " Therelativepath'%s'pointsoutsidethefilehierarchythattemplate'%s'isin " % relative name current template name if current template name lstrip '/' new name raise Template Syntax Error " Therelativepath'%s'wastranslatedtotemplatename'%s' thesametemplateinwhichthetagappears " % relative name current template name return '"%s"' % new name
null
null
null
null
Question: What does the code convert to the full template name based on the current_template_name ? Code: def construct_relative_path(current_template_name, relative_name): if (not any((relative_name.startswith(x) for x in ["'./", "'../", '"./', '"../']))): return relative_name new_name = posixpath.normpath(posixpath.join(posixpath.dirname(current_template_name.lstrip('/')), relative_name.strip('\'"'))) if new_name.startswith('../'): raise TemplateSyntaxError(("The relative path '%s' points outside the file hierarchy that template '%s' is in." % (relative_name, current_template_name))) if (current_template_name.lstrip('/') == new_name): raise TemplateSyntaxError(("The relative path '%s' was translated to template name '%s', the same template in which the tag appears." % (relative_name, current_template_name))) return ('"%s"' % new_name)
null
null
null
Why do tasks be pending still ?
def _depth_first_search(set_tasks, current_task, visited): visited.add(current_task) if (current_task in set_tasks['still_pending_not_ext']): upstream_failure = False upstream_missing_dependency = False upstream_run_by_other_worker = False upstream_scheduling_error = False for task in current_task._requires(): if (task not in visited): _depth_first_search(set_tasks, task, visited) if ((task in set_tasks['ever_failed']) or (task in set_tasks['upstream_failure'])): set_tasks['upstream_failure'].add(current_task) upstream_failure = True if ((task in set_tasks['still_pending_ext']) or (task in set_tasks['upstream_missing_dependency'])): set_tasks['upstream_missing_dependency'].add(current_task) upstream_missing_dependency = True if ((task in set_tasks['run_by_other_worker']) or (task in set_tasks['upstream_run_by_other_worker'])): set_tasks['upstream_run_by_other_worker'].add(current_task) upstream_run_by_other_worker = True if (task in set_tasks['scheduling_error']): set_tasks['upstream_scheduling_error'].add(current_task) upstream_scheduling_error = True if ((not upstream_failure) and (not upstream_missing_dependency) and (not upstream_run_by_other_worker) and (not upstream_scheduling_error) and (current_task not in set_tasks['run_by_other_worker'])): set_tasks['not_run'].add(current_task)
null
null
null
why
codeqa
def depth first search set tasks current task visited visited add current task if current task in set tasks['still pending not ext'] upstream failure Falseupstream missing dependency Falseupstream run by other worker Falseupstream scheduling error Falsefor task in current task requires if task not in visited depth first search set tasks task visited if task in set tasks['ever failed'] or task in set tasks['upstream failure'] set tasks['upstream failure'] add current task upstream failure Trueif task in set tasks['still pending ext'] or task in set tasks['upstream missing dependency'] set tasks['upstream missing dependency'] add current task upstream missing dependency Trueif task in set tasks['run by other worker'] or task in set tasks['upstream run by other worker'] set tasks['upstream run by other worker'] add current task upstream run by other worker Trueif task in set tasks['scheduling error'] set tasks['upstream scheduling error'] add current task upstream scheduling error Trueif not upstream failure and not upstream missing dependency and not upstream run by other worker and not upstream scheduling error and current task not in set tasks['run by other worker'] set tasks['not run'] add current task
null
null
null
null
Question: Why do tasks be pending still ? Code: def _depth_first_search(set_tasks, current_task, visited): visited.add(current_task) if (current_task in set_tasks['still_pending_not_ext']): upstream_failure = False upstream_missing_dependency = False upstream_run_by_other_worker = False upstream_scheduling_error = False for task in current_task._requires(): if (task not in visited): _depth_first_search(set_tasks, task, visited) if ((task in set_tasks['ever_failed']) or (task in set_tasks['upstream_failure'])): set_tasks['upstream_failure'].add(current_task) upstream_failure = True if ((task in set_tasks['still_pending_ext']) or (task in set_tasks['upstream_missing_dependency'])): set_tasks['upstream_missing_dependency'].add(current_task) upstream_missing_dependency = True if ((task in set_tasks['run_by_other_worker']) or (task in set_tasks['upstream_run_by_other_worker'])): set_tasks['upstream_run_by_other_worker'].add(current_task) upstream_run_by_other_worker = True if (task in set_tasks['scheduling_error']): set_tasks['upstream_scheduling_error'].add(current_task) upstream_scheduling_error = True if ((not upstream_failure) and (not upstream_missing_dependency) and (not upstream_run_by_other_worker) and (not upstream_scheduling_error) and (current_task not in set_tasks['run_by_other_worker'])): set_tasks['not_run'].add(current_task)
null
null
null
What does the code setup ?
def setup_platform(hass, config, add_devices, discovery_info=None): data = SpeedtestData(hass, config) sensor = SpeedtestSensor(data) add_devices([sensor]) def update(call=None): 'Update service for manual updates.' data.update(dt_util.now()) sensor.update() hass.services.register(DOMAIN, 'update_fastdotcom', update)
null
null
null
the fast
codeqa
def setup platform hass config add devices discovery info None data Speedtest Data hass config sensor Speedtest Sensor data add devices [sensor] def update call None ' Updateserviceformanualupdates 'data update dt util now sensor update hass services register DOMAIN 'update fastdotcom' update
null
null
null
null
Question: What does the code setup ? Code: def setup_platform(hass, config, add_devices, discovery_info=None): data = SpeedtestData(hass, config) sensor = SpeedtestSensor(data) add_devices([sensor]) def update(call=None): 'Update service for manual updates.' data.update(dt_util.now()) sensor.update() hass.services.register(DOMAIN, 'update_fastdotcom', update)
null
null
null
What does the code return ?
def get_rotation(rotation): if (rotation in ('horizontal', None)): angle = 0.0 elif (rotation == 'vertical'): angle = 90.0 else: angle = float(rotation) return (angle % 360)
null
null
null
the text angle
codeqa
def get rotation rotation if rotation in 'horizontal' None angle 0 0elif rotation 'vertical' angle 90 0else angle float rotation return angle % 360
null
null
null
null
Question: What does the code return ? Code: def get_rotation(rotation): if (rotation in ('horizontal', None)): angle = 0.0 elif (rotation == 'vertical'): angle = 90.0 else: angle = float(rotation) return (angle % 360)
null
null
null
What is describing specific volume_type ?
@require_context def volume_type_get(context, id, session=None): result = model_query(context, models.VolumeTypes, session=session).options(joinedload('extra_specs')).filter_by(id=id).first() if (not result): raise exception.VolumeTypeNotFound(volume_type_id=id) return _dict_with_extra_specs(result)
null
null
null
a dict
codeqa
@require contextdef volume type get context id session None result model query context models Volume Types session session options joinedload 'extra specs' filter by id id first if not result raise exception Volume Type Not Found volume type id id return dict with extra specs result
null
null
null
null
Question: What is describing specific volume_type ? Code: @require_context def volume_type_get(context, id, session=None): result = model_query(context, models.VolumeTypes, session=session).options(joinedload('extra_specs')).filter_by(id=id).first() if (not result): raise exception.VolumeTypeNotFound(volume_type_id=id) return _dict_with_extra_specs(result)
null
null
null
What did the code set ?
def set_bootdev(bootdev='default', persist=False, uefiboot=False, **kwargs): with _IpmiCommand(**kwargs) as s: return s.set_bootdev(bootdev)
null
null
null
boot device to use on next reboot
codeqa
def set bootdev bootdev 'default' persist False uefiboot False **kwargs with Ipmi Command **kwargs as s return s set bootdev bootdev
null
null
null
null
Question: What did the code set ? Code: def set_bootdev(bootdev='default', persist=False, uefiboot=False, **kwargs): with _IpmiCommand(**kwargs) as s: return s.set_bootdev(bootdev)
null
null
null
What have unclaimed records ?
def get_targets(): return User.find(QUERY)
null
null
null
confirmed users
codeqa
def get targets return User find QUERY
null
null
null
null
Question: What have unclaimed records ? Code: def get_targets(): return User.find(QUERY)
null
null
null
What do confirmed users have ?
def get_targets(): return User.find(QUERY)
null
null
null
unclaimed records
codeqa
def get targets return User find QUERY
null
null
null
null
Question: What do confirmed users have ? Code: def get_targets(): return User.find(QUERY)
null
null
null
What starts a vm ?
def vb_start_vm(name=None, timeout=10000, **kwargs): start_time = time.time() timeout_in_seconds = (timeout / 1000) max_time = (start_time + timeout_in_seconds) vbox = vb_get_box() machine = vbox.findMachine(name) session = _virtualboxManager.getSessionObject(vbox) log.info('Starting machine %s in state %s', name, vb_machinestate_to_str(machine.state)) try: args = (machine, session) progress = wait_for(_start_machine, timeout=timeout_in_seconds, func_args=args) if (not progress): progress = machine.launchVMProcess(session, '', '') time_left = (max_time - time.time()) progress.waitForCompletion((time_left * 1000)) finally: _virtualboxManager.closeMachineSession(session) time_left = (max_time - time.time()) vb_wait_for_session_state(session, timeout=time_left) log.info('Started machine %s', name) return vb_xpcom_to_attribute_dict(machine, 'IMachine')
null
null
null
virtualbox
codeqa
def vb start vm name None timeout 10000 **kwargs start time time time timeout in seconds timeout / 1000 max time start time + timeout in seconds vbox vb get box machine vbox find Machine name session virtualbox Manager get Session Object vbox log info ' Startingmachine%sinstate%s' name vb machinestate to str machine state try args machine session progress wait for start machine timeout timeout in seconds func args args if not progress progress machine launch VM Process session '' '' time left max time - time time progress wait For Completion time left * 1000 finally virtualbox Manager close Machine Session session time left max time - time time vb wait for session state session timeout time left log info ' Startedmachine%s' name return vb xpcom to attribute dict machine 'I Machine'
null
null
null
null
Question: What starts a vm ? Code: def vb_start_vm(name=None, timeout=10000, **kwargs): start_time = time.time() timeout_in_seconds = (timeout / 1000) max_time = (start_time + timeout_in_seconds) vbox = vb_get_box() machine = vbox.findMachine(name) session = _virtualboxManager.getSessionObject(vbox) log.info('Starting machine %s in state %s', name, vb_machinestate_to_str(machine.state)) try: args = (machine, session) progress = wait_for(_start_machine, timeout=timeout_in_seconds, func_args=args) if (not progress): progress = machine.launchVMProcess(session, '', '') time_left = (max_time - time.time()) progress.waitForCompletion((time_left * 1000)) finally: _virtualboxManager.closeMachineSession(session) time_left = (max_time - time.time()) vb_wait_for_session_state(session, timeout=time_left) log.info('Started machine %s', name) return vb_xpcom_to_attribute_dict(machine, 'IMachine')
null
null
null
How do the types of the address return ?
def address_type(address): if (type(address) == tuple): return 'AF_INET' elif ((type(address) is str) and address.startswith('\\\\')): return 'AF_PIPE' elif (type(address) is str): return 'AF_UNIX' else: raise ValueError(('address type of %r unrecognized' % address))
null
null
null
code
codeqa
def address type address if type address tuple return 'AF INET'elif type address is str and address startswith '\\\\' return 'AF PIPE'elif type address is str return 'AF UNIX'else raise Value Error 'addresstypeof%runrecognized' % address
null
null
null
null
Question: How do the types of the address return ? Code: def address_type(address): if (type(address) == tuple): return 'AF_INET' elif ((type(address) is str) and address.startswith('\\\\')): return 'AF_PIPE' elif (type(address) is str): return 'AF_UNIX' else: raise ValueError(('address type of %r unrecognized' % address))
null
null
null
What does the code locate ?
def _get_pip_bin(bin_env): if (not bin_env): which_result = __salt__['cmd.which_bin'](['pip', 'pip2', 'pip3', 'pip-python']) if (which_result is None): raise CommandNotFoundError('Could not find a `pip` binary') if salt.utils.is_windows(): return which_result.encode('string-escape') return which_result if os.path.isdir(bin_env): if salt.utils.is_windows(): pip_bin = os.path.join(bin_env, 'Scripts', 'pip.exe').encode('string-escape') else: pip_bin = os.path.join(bin_env, 'bin', 'pip') if os.path.isfile(pip_bin): return pip_bin msg = 'Could not find a `pip` binary in virtualenv {0}'.format(bin_env) raise CommandNotFoundError(msg) elif os.access(bin_env, os.X_OK): if (os.path.isfile(bin_env) or os.path.islink(bin_env)): return bin_env else: raise CommandNotFoundError('Could not find a `pip` binary')
null
null
null
the pip binary
codeqa
def get pip bin bin env if not bin env which result salt ['cmd which bin'] ['pip' 'pip 2 ' 'pip 3 ' 'pip-python'] if which result is None raise Command Not Found Error ' Couldnotfinda`pip`binary' if salt utils is windows return which result encode 'string-escape' return which resultif os path isdir bin env if salt utils is windows pip bin os path join bin env ' Scripts' 'pip exe' encode 'string-escape' else pip bin os path join bin env 'bin' 'pip' if os path isfile pip bin return pip binmsg ' Couldnotfinda`pip`binaryinvirtualenv{ 0 }' format bin env raise Command Not Found Error msg elif os access bin env os X OK if os path isfile bin env or os path islink bin env return bin envelse raise Command Not Found Error ' Couldnotfinda`pip`binary'
null
null
null
null
Question: What does the code locate ? Code: def _get_pip_bin(bin_env): if (not bin_env): which_result = __salt__['cmd.which_bin'](['pip', 'pip2', 'pip3', 'pip-python']) if (which_result is None): raise CommandNotFoundError('Could not find a `pip` binary') if salt.utils.is_windows(): return which_result.encode('string-escape') return which_result if os.path.isdir(bin_env): if salt.utils.is_windows(): pip_bin = os.path.join(bin_env, 'Scripts', 'pip.exe').encode('string-escape') else: pip_bin = os.path.join(bin_env, 'bin', 'pip') if os.path.isfile(pip_bin): return pip_bin msg = 'Could not find a `pip` binary in virtualenv {0}'.format(bin_env) raise CommandNotFoundError(msg) elif os.access(bin_env, os.X_OK): if (os.path.isfile(bin_env) or os.path.islink(bin_env)): return bin_env else: raise CommandNotFoundError('Could not find a `pip` binary')
null
null
null
When is an error raised ?
def test_sample_wrong_X(): sm = SMOTETomek(random_state=RND_SEED) sm.fit(X, Y) assert_raises(RuntimeError, sm.sample, np.random.random((100, 40)), np.array((([0] * 50) + ([1] * 50))))
null
null
null
when x is different at fitting and sampling
codeqa
def test sample wrong X sm SMOTE Tomek random state RND SEED sm fit X Y assert raises Runtime Error sm sample np random random 100 40 np array [0 ] * 50 + [1 ] * 50
null
null
null
null
Question: When is an error raised ? Code: def test_sample_wrong_X(): sm = SMOTETomek(random_state=RND_SEED) sm.fit(X, Y) assert_raises(RuntimeError, sm.sample, np.random.random((100, 40)), np.array((([0] * 50) + ([1] * 50))))
null
null
null
What does the code not wrap if several options are exclusive ?
def linmod(y, x, weights=None, sigma=None, add_const=True, filter_missing=True, **kwds): if filter_missing: (y, x) = remove_nanrows(y, x) if add_const: x = sm.add_constant(x, prepend=True) if (not (sigma is None)): return GLS(y, x, sigma=sigma, **kwds) elif (not (weights is None)): return WLS(y, x, weights=weights, **kwds) else: return OLS(y, x, **kwds)
null
null
null
the output
codeqa
def linmod y x weights None sigma None add const True filter missing True **kwds if filter missing y x remove nanrows y x if add const x sm add constant x prepend True if not sigma is None return GLS y x sigma sigma **kwds elif not weights is None return WLS y x weights weights **kwds else return OLS y x **kwds
null
null
null
null
Question: What does the code not wrap if several options are exclusive ? Code: def linmod(y, x, weights=None, sigma=None, add_const=True, filter_missing=True, **kwds): if filter_missing: (y, x) = remove_nanrows(y, x) if add_const: x = sm.add_constant(x, prepend=True) if (not (sigma is None)): return GLS(y, x, sigma=sigma, **kwds) elif (not (weights is None)): return WLS(y, x, weights=weights, **kwds) else: return OLS(y, x, **kwds)
null
null
null
What does the code get ?
def linmod(y, x, weights=None, sigma=None, add_const=True, filter_missing=True, **kwds): if filter_missing: (y, x) = remove_nanrows(y, x) if add_const: x = sm.add_constant(x, prepend=True) if (not (sigma is None)): return GLS(y, x, sigma=sigma, **kwds) elif (not (weights is None)): return WLS(y, x, weights=weights, **kwds) else: return OLS(y, x, **kwds)
null
null
null
linear model with extra options for entry dispatches to regular model class
codeqa
def linmod y x weights None sigma None add const True filter missing True **kwds if filter missing y x remove nanrows y x if add const x sm add constant x prepend True if not sigma is None return GLS y x sigma sigma **kwds elif not weights is None return WLS y x weights weights **kwds else return OLS y x **kwds
null
null
null
null
Question: What does the code get ? Code: def linmod(y, x, weights=None, sigma=None, add_const=True, filter_missing=True, **kwds): if filter_missing: (y, x) = remove_nanrows(y, x) if add_const: x = sm.add_constant(x, prepend=True) if (not (sigma is None)): return GLS(y, x, sigma=sigma, **kwds) elif (not (weights is None)): return WLS(y, x, weights=weights, **kwds) else: return OLS(y, x, **kwds)
null
null
null
Does the code wrap the output if several options are exclusive ?
def linmod(y, x, weights=None, sigma=None, add_const=True, filter_missing=True, **kwds): if filter_missing: (y, x) = remove_nanrows(y, x) if add_const: x = sm.add_constant(x, prepend=True) if (not (sigma is None)): return GLS(y, x, sigma=sigma, **kwds) elif (not (weights is None)): return WLS(y, x, weights=weights, **kwds) else: return OLS(y, x, **kwds)
null
null
null
No
codeqa
def linmod y x weights None sigma None add const True filter missing True **kwds if filter missing y x remove nanrows y x if add const x sm add constant x prepend True if not sigma is None return GLS y x sigma sigma **kwds elif not weights is None return WLS y x weights weights **kwds else return OLS y x **kwds
null
null
null
null
Question: Does the code wrap the output if several options are exclusive ? Code: def linmod(y, x, weights=None, sigma=None, add_const=True, filter_missing=True, **kwds): if filter_missing: (y, x) = remove_nanrows(y, x) if add_const: x = sm.add_constant(x, prepend=True) if (not (sigma is None)): return GLS(y, x, sigma=sigma, **kwds) elif (not (weights is None)): return WLS(y, x, weights=weights, **kwds) else: return OLS(y, x, **kwds)
null
null
null
What does the code add to allow_hosts ?
def allow(ip, port=None): if (port is None): return __apf_cmd('-a {0}'.format(ip))
null
null
null
host
codeqa
def allow ip port None if port is None return apf cmd '-a{ 0 }' format ip
null
null
null
null
Question: What does the code add to allow_hosts ? Code: def allow(ip, port=None): if (port is None): return __apf_cmd('-a {0}'.format(ip))
null
null
null
What did the code read ?
def _gpa11iterator(handle): for inline in handle: if (inline[0] == '!'): continue inrec = inline.rstrip('\n').split(' DCTB ') if (len(inrec) == 1): continue inrec[2] = inrec[2].split('|') inrec[4] = inrec[4].split('|') inrec[6] = inrec[6].split('|') inrec[10] = inrec[10].split('|') (yield dict(zip(GPA11FIELDS, inrec)))
null
null
null
gpa 1
codeqa
def gpa 11 iterator handle for inline in handle if inline[ 0 ] ' ' continueinrec inline rstrip '\n' split ' DCTB ' if len inrec 1 continueinrec[ 2 ] inrec[ 2 ] split ' ' inrec[ 4 ] inrec[ 4 ] split ' ' inrec[ 6 ] inrec[ 6 ] split ' ' inrec[ 10 ] inrec[ 10 ] split ' ' yield dict zip GPA 11 FIELDS inrec
null
null
null
null
Question: What did the code read ? Code: def _gpa11iterator(handle): for inline in handle: if (inline[0] == '!'): continue inrec = inline.rstrip('\n').split(' DCTB ') if (len(inrec) == 1): continue inrec[2] = inrec[2].split('|') inrec[4] = inrec[4].split('|') inrec[6] = inrec[6].split('|') inrec[10] = inrec[10].split('|') (yield dict(zip(GPA11FIELDS, inrec)))
null
null
null
How does the code traverse a dict or list ?
def traverse_dict_and_list(data, key, default, delimiter=DEFAULT_TARGET_DELIM): for each in key.split(delimiter): if isinstance(data, list): try: idx = int(each) except ValueError: embed_match = False for embedded in (x for x in data if isinstance(x, dict)): try: data = embedded[each] embed_match = True break except KeyError: pass if (not embed_match): return default else: try: data = data[idx] except IndexError: return default else: try: data = data[each] except (KeyError, TypeError): return default return data
null
null
null
using a colon - delimited target string
codeqa
def traverse dict and list data key default delimiter DEFAULT TARGET DELIM for each in key split delimiter if isinstance data list try idx int each except Value Error embed match Falsefor embedded in x for x in data if isinstance x dict try data embedded[each]embed match Truebreakexcept Key Error passif not embed match return defaultelse try data data[idx]except Index Error return defaultelse try data data[each]except Key Error Type Error return defaultreturn data
null
null
null
null
Question: How does the code traverse a dict or list ? Code: def traverse_dict_and_list(data, key, default, delimiter=DEFAULT_TARGET_DELIM): for each in key.split(delimiter): if isinstance(data, list): try: idx = int(each) except ValueError: embed_match = False for embedded in (x for x in data if isinstance(x, dict)): try: data = embedded[each] embed_match = True break except KeyError: pass if (not embed_match): return default else: try: data = data[idx] except IndexError: return default else: try: data = data[each] except (KeyError, TypeError): return default return data
null
null
null
What does the code traverse using a colon - delimited target string ?
def traverse_dict_and_list(data, key, default, delimiter=DEFAULT_TARGET_DELIM): for each in key.split(delimiter): if isinstance(data, list): try: idx = int(each) except ValueError: embed_match = False for embedded in (x for x in data if isinstance(x, dict)): try: data = embedded[each] embed_match = True break except KeyError: pass if (not embed_match): return default else: try: data = data[idx] except IndexError: return default else: try: data = data[each] except (KeyError, TypeError): return default return data
null
null
null
a dict or list
codeqa
def traverse dict and list data key default delimiter DEFAULT TARGET DELIM for each in key split delimiter if isinstance data list try idx int each except Value Error embed match Falsefor embedded in x for x in data if isinstance x dict try data embedded[each]embed match Truebreakexcept Key Error passif not embed match return defaultelse try data data[idx]except Index Error return defaultelse try data data[each]except Key Error Type Error return defaultreturn data
null
null
null
null
Question: What does the code traverse using a colon - delimited target string ? Code: def traverse_dict_and_list(data, key, default, delimiter=DEFAULT_TARGET_DELIM): for each in key.split(delimiter): if isinstance(data, list): try: idx = int(each) except ValueError: embed_match = False for embedded in (x for x in data if isinstance(x, dict)): try: data = embedded[each] embed_match = True break except KeyError: pass if (not embed_match): return default else: try: data = data[idx] except IndexError: return default else: try: data = data[each] except (KeyError, TypeError): return default return data
null
null
null
What should we bypass ?
def should_bypass_proxies(url): get_proxy = (lambda k: (os.environ.get(k) or os.environ.get(k.upper()))) no_proxy = get_proxy('no_proxy') netloc = urlparse(url).netloc if no_proxy: no_proxy = (host for host in no_proxy.replace(' ', '').split(',') if host) ip = netloc.split(':')[0] if is_ipv4_address(ip): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(ip, proxy_ip): return True else: for host in no_proxy: if (netloc.endswith(host) or netloc.split(':')[0].endswith(host)): return True try: bypass = proxy_bypass(netloc) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
null
null
null
proxies
codeqa
def should bypass proxies url get proxy lambda k os environ get k or os environ get k upper no proxy get proxy 'no proxy' netloc urlparse url netlocif no proxy no proxy host for host in no proxy replace '' '' split ' ' if host ip netloc split ' ' [0 ]if is ipv 4 address ip for proxy ip in no proxy if is valid cidr proxy ip if address in network ip proxy ip return Trueelse for host in no proxy if netloc endswith host or netloc split ' ' [0 ] endswith host return Truetry bypass proxy bypass netloc except Type Error socket gaierror bypass Falseif bypass return Truereturn False
null
null
null
null
Question: What should we bypass ? Code: def should_bypass_proxies(url): get_proxy = (lambda k: (os.environ.get(k) or os.environ.get(k.upper()))) no_proxy = get_proxy('no_proxy') netloc = urlparse(url).netloc if no_proxy: no_proxy = (host for host in no_proxy.replace(' ', '').split(',') if host) ip = netloc.split(':')[0] if is_ipv4_address(ip): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(ip, proxy_ip): return True else: for host in no_proxy: if (netloc.endswith(host) or netloc.split(':')[0].endswith(host)): return True try: bypass = proxy_bypass(netloc) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
null
null
null
What does the code raise ?
def rush(enable=True, realtime=False): if importWindllFailed: return False pr_rights = (PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION) pr = windll.OpenProcess(pr_rights, FALSE, os.getpid()) thr = windll.GetCurrentThread() if (enable is True): if (realtime is False): windll.SetPriorityClass(pr, HIGH_PRIORITY_CLASS) windll.SetThreadPriority(thr, THREAD_PRIORITY_HIGHEST) else: windll.SetPriorityClass(pr, REALTIME_PRIORITY_CLASS) windll.SetThreadPriority(thr, THREAD_PRIORITY_TIME_CRITICAL) else: windll.SetPriorityClass(pr, NORMAL_PRIORITY_CLASS) windll.SetThreadPriority(thr, THREAD_PRIORITY_NORMAL) return True
null
null
null
the priority of the current thread / process
codeqa
def rush enable True realtime False if import Windll Failed return Falsepr rights PROCESS QUERY INFORMATION PROCESS SET INFORMATION pr windll Open Process pr rights FALSE os getpid thr windll Get Current Thread if enable is True if realtime is False windll Set Priority Class pr HIGH PRIORITY CLASS windll Set Thread Priority thr THREAD PRIORITY HIGHEST else windll Set Priority Class pr REALTIME PRIORITY CLASS windll Set Thread Priority thr THREAD PRIORITY TIME CRITICAL else windll Set Priority Class pr NORMAL PRIORITY CLASS windll Set Thread Priority thr THREAD PRIORITY NORMAL return True
null
null
null
null
Question: What does the code raise ? Code: def rush(enable=True, realtime=False): if importWindllFailed: return False pr_rights = (PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION) pr = windll.OpenProcess(pr_rights, FALSE, os.getpid()) thr = windll.GetCurrentThread() if (enable is True): if (realtime is False): windll.SetPriorityClass(pr, HIGH_PRIORITY_CLASS) windll.SetThreadPriority(thr, THREAD_PRIORITY_HIGHEST) else: windll.SetPriorityClass(pr, REALTIME_PRIORITY_CLASS) windll.SetThreadPriority(thr, THREAD_PRIORITY_TIME_CRITICAL) else: windll.SetPriorityClass(pr, NORMAL_PRIORITY_CLASS) windll.SetThreadPriority(thr, THREAD_PRIORITY_NORMAL) return True
null
null
null
When has the action field been rendered on the page ?
def admin_actions(context): context['action_index'] = (context.get('action_index', (-1)) + 1) return context
null
null
null
the number of times
codeqa
def admin actions context context['action index'] context get 'action index' -1 + 1 return context
null
null
null
null
Question: When has the action field been rendered on the page ? Code: def admin_actions(context): context['action_index'] = (context.get('action_index', (-1)) + 1) return context
null
null
null
What has been rendered on the page ?
def admin_actions(context): context['action_index'] = (context.get('action_index', (-1)) + 1) return context
null
null
null
the action field
codeqa
def admin actions context context['action index'] context get 'action index' -1 + 1 return context
null
null
null
null
Question: What has been rendered on the page ? Code: def admin_actions(context): context['action_index'] = (context.get('action_index', (-1)) + 1) return context
null
null
null
Where has the action field been rendered the number of times ?
def admin_actions(context): context['action_index'] = (context.get('action_index', (-1)) + 1) return context
null
null
null
on the page
codeqa
def admin actions context context['action index'] context get 'action index' -1 + 1 return context
null
null
null
null
Question: Where has the action field been rendered the number of times ? Code: def admin_actions(context): context['action_index'] = (context.get('action_index', (-1)) + 1) return context
null
null
null
What does the code track ?
def admin_actions(context): context['action_index'] = (context.get('action_index', (-1)) + 1) return context
null
null
null
the number of times the action field has been rendered on the page
codeqa
def admin actions context context['action index'] context get 'action index' -1 + 1 return context
null
null
null
null
Question: What does the code track ? Code: def admin_actions(context): context['action_index'] = (context.get('action_index', (-1)) + 1) return context
null
null
null
What does this function encode ?
def encode_block_crawl(payload): return pack(crawl_response_format, *(payload.up, payload.down, payload.total_up_requester, payload.total_down_requester, payload.sequence_number_requester, payload.previous_hash_requester, payload.total_up_responder, payload.total_down_responder, payload.sequence_number_responder, payload.previous_hash_responder, payload.public_key_requester, payload.signature_requester, payload.public_key_responder, payload.signature_responder))
null
null
null
a block for the crawler
codeqa
def encode block crawl payload return pack crawl response format * payload up payload down payload total up requester payload total down requester payload sequence number requester payload previous hash requester payload total up responder payload total down responder payload sequence number responder payload previous hash responder payload public key requester payload signature requester payload public key responder payload signature responder
null
null
null
null
Question: What does this function encode ? Code: def encode_block_crawl(payload): return pack(crawl_response_format, *(payload.up, payload.down, payload.total_up_requester, payload.total_down_requester, payload.sequence_number_requester, payload.previous_hash_requester, payload.total_up_responder, payload.total_down_responder, payload.sequence_number_responder, payload.previous_hash_responder, payload.public_key_requester, payload.signature_requester, payload.public_key_responder, payload.signature_responder))
null
null
null
What does the code return ?
def test_finalizer(): global val, called val = None called = False class X(object, ): def __new__(cls): global val if (val == None): val = object.__new__(cls) return val def __del__(self): called = True a = X() b = X() AreEqual(id(a), id(b)) import gc gc.collect() AreEqual(called, False)
null
null
null
the same object
codeqa
def test finalizer global val calledval Nonecalled Falseclass X object def new cls global valif val None val object new cls return valdef del self called Truea X b X Are Equal id a id b import gcgc collect Are Equal called False
null
null
null
null
Question: What does the code return ? Code: def test_finalizer(): global val, called val = None called = False class X(object, ): def __new__(cls): global val if (val == None): val = object.__new__(cls) return val def __del__(self): called = True a = X() b = X() AreEqual(id(a), id(b)) import gc gc.collect() AreEqual(called, False)
null
null
null
Should the code cause it to be finalized ?
def test_finalizer(): global val, called val = None called = False class X(object, ): def __new__(cls): global val if (val == None): val = object.__new__(cls) return val def __del__(self): called = True a = X() b = X() AreEqual(id(a), id(b)) import gc gc.collect() AreEqual(called, False)
null
null
null
No
codeqa
def test finalizer global val calledval Nonecalled Falseclass X object def new cls global valif val None val object new cls return valdef del self called Truea X b X Are Equal id a id b import gcgc collect Are Equal called False
null
null
null
null
Question: Should the code cause it to be finalized ? Code: def test_finalizer(): global val, called val = None called = False class X(object, ): def __new__(cls): global val if (val == None): val = object.__new__(cls) return val def __del__(self): called = True a = X() b = X() AreEqual(id(a), id(b)) import gc gc.collect() AreEqual(called, False)
null
null
null
What does the code run ?
def execute(shell_cmd): cmd = Popen(shell_cmd, shell=True, stdout=PIPE, stderr=PIPE, universal_newlines=True) (out, err) = cmd.communicate() if (cmd.returncode != 0): logger.error('Hook command "%s" returned error code %d', shell_cmd, cmd.returncode) if err: base_cmd = os.path.basename(shell_cmd.split(None, 1)[0]) logger.error('Error output from %s:\n%s', base_cmd, err) return (err, out)
null
null
null
a command
codeqa
def execute shell cmd cmd Popen shell cmd shell True stdout PIPE stderr PIPE universal newlines True out err cmd communicate if cmd returncode 0 logger error ' Hookcommand"%s"returnederrorcode%d' shell cmd cmd returncode if err base cmd os path basename shell cmd split None 1 [0 ] logger error ' Erroroutputfrom%s \n%s' base cmd err return err out
null
null
null
null
Question: What does the code run ? Code: def execute(shell_cmd): cmd = Popen(shell_cmd, shell=True, stdout=PIPE, stderr=PIPE, universal_newlines=True) (out, err) = cmd.communicate() if (cmd.returncode != 0): logger.error('Hook command "%s" returned error code %d', shell_cmd, cmd.returncode) if err: base_cmd = os.path.basename(shell_cmd.split(None, 1)[0]) logger.error('Error output from %s:\n%s', base_cmd, err) return (err, out)
null
null
null
What does the code create ?
def _default_key_normalizer(key_class, request_context): context = {} for key in key_class._fields: context[key] = request_context.get(key) context['scheme'] = context['scheme'].lower() context['host'] = context['host'].lower() return key_class(**context)
null
null
null
a pool key of type key_class for a request
codeqa
def default key normalizer key class request context context {}for key in key class fields context[key] request context get key context['scheme'] context['scheme'] lower context['host'] context['host'] lower return key class **context
null
null
null
null
Question: What does the code create ? Code: def _default_key_normalizer(key_class, request_context): context = {} for key in key_class._fields: context[key] = request_context.get(key) context['scheme'] = context['scheme'].lower() context['host'] = context['host'].lower() return key_class(**context)
null
null
null
What does the code initialize ?
def init_params(options): params = OrderedDict() params['Wemb'] = norm_weight(options['n_words'], options['dim_word']) params = get_layer(options['encoder'])[0](options, params, prefix='encoder', nin=options['dim_word'], dim=options['dim']) params = get_layer('ff')[0](options, params, prefix='ff_image', nin=options['dim_image'], nout=options['dim']) return params
null
null
null
all parameters
codeqa
def init params options params Ordered Dict params[' Wemb'] norm weight options['n words'] options['dim word'] params get layer options['encoder'] [0 ] options params prefix 'encoder' nin options['dim word'] dim options['dim'] params get layer 'ff' [0 ] options params prefix 'ff image' nin options['dim image'] nout options['dim'] return params
null
null
null
null
Question: What does the code initialize ? Code: def init_params(options): params = OrderedDict() params['Wemb'] = norm_weight(options['n_words'], options['dim_word']) params = get_layer(options['encoder'])[0](options, params, prefix='encoder', nin=options['dim_word'], dim=options['dim']) params = get_layer('ff')[0](options, params, prefix='ff_image', nin=options['dim_image'], nout=options['dim']) return params
null
null
null
What does the code resolve to a valid ipv4 or ipv6 address ?
def getHostByName(name, timeout=None, effort=10): return getResolver().getHostByName(name, timeout, effort)
null
null
null
a name
codeqa
def get Host By Name name timeout None effort 10 return get Resolver get Host By Name name timeout effort
null
null
null
null
Question: What does the code resolve to a valid ipv4 or ipv6 address ? Code: def getHostByName(name, timeout=None, effort=10): return getResolver().getHostByName(name, timeout, effort)
null
null
null
Where did the code set window properties with the specified i d ?
def set_X_window_properties(win_id, **properties): import xcb, xcb.xproto conn = xcb.connect() atoms = {name: conn.core.InternAtom(False, len(name), name) for name in properties} utf8_string_atom = None for (name, val) in properties.iteritems(): atom = atoms[name].reply().atom type_atom = xcb.xproto.Atom.STRING if isinstance(val, unicode): if (utf8_string_atom is None): utf8_string_atom = conn.core.InternAtom(True, len('UTF8_STRING'), 'UTF8_STRING').reply().atom type_atom = utf8_string_atom val = val.encode(u'utf-8') conn.core.ChangePropertyChecked(xcb.xproto.PropMode.Replace, win_id, atom, type_atom, 8, len(val), val) conn.flush() conn.disconnect()
null
null
null
on the window
codeqa
def set X window properties win id **properties import xcb xcb xprotoconn xcb connect atoms {name conn core Intern Atom False len name name for name in properties}utf 8 string atom Nonefor name val in properties iteritems atom atoms[name] reply atomtype atom xcb xproto Atom STRIN Gif isinstance val unicode if utf 8 string atom is None utf 8 string atom conn core Intern Atom True len 'UTF 8 STRING' 'UTF 8 STRING' reply atomtype atom utf 8 string atomval val encode u'utf- 8 ' conn core Change Property Checked xcb xproto Prop Mode Replace win id atom type atom 8 len val val conn flush conn disconnect
null
null
null
null
Question: Where did the code set window properties with the specified i d ? Code: def set_X_window_properties(win_id, **properties): import xcb, xcb.xproto conn = xcb.connect() atoms = {name: conn.core.InternAtom(False, len(name), name) for name in properties} utf8_string_atom = None for (name, val) in properties.iteritems(): atom = atoms[name].reply().atom type_atom = xcb.xproto.Atom.STRING if isinstance(val, unicode): if (utf8_string_atom is None): utf8_string_atom = conn.core.InternAtom(True, len('UTF8_STRING'), 'UTF8_STRING').reply().atom type_atom = utf8_string_atom val = val.encode(u'utf-8') conn.core.ChangePropertyChecked(xcb.xproto.PropMode.Replace, win_id, atom, type_atom, 8, len(val), val) conn.flush() conn.disconnect()
null
null
null
What did the code set on the window with the specified i d ?
def set_X_window_properties(win_id, **properties): import xcb, xcb.xproto conn = xcb.connect() atoms = {name: conn.core.InternAtom(False, len(name), name) for name in properties} utf8_string_atom = None for (name, val) in properties.iteritems(): atom = atoms[name].reply().atom type_atom = xcb.xproto.Atom.STRING if isinstance(val, unicode): if (utf8_string_atom is None): utf8_string_atom = conn.core.InternAtom(True, len('UTF8_STRING'), 'UTF8_STRING').reply().atom type_atom = utf8_string_atom val = val.encode(u'utf-8') conn.core.ChangePropertyChecked(xcb.xproto.PropMode.Replace, win_id, atom, type_atom, 8, len(val), val) conn.flush() conn.disconnect()
null
null
null
window properties
codeqa
def set X window properties win id **properties import xcb xcb xprotoconn xcb connect atoms {name conn core Intern Atom False len name name for name in properties}utf 8 string atom Nonefor name val in properties iteritems atom atoms[name] reply atomtype atom xcb xproto Atom STRIN Gif isinstance val unicode if utf 8 string atom is None utf 8 string atom conn core Intern Atom True len 'UTF 8 STRING' 'UTF 8 STRING' reply atomtype atom utf 8 string atomval val encode u'utf- 8 ' conn core Change Property Checked xcb xproto Prop Mode Replace win id atom type atom 8 len val val conn flush conn disconnect
null
null
null
null
Question: What did the code set on the window with the specified i d ? Code: def set_X_window_properties(win_id, **properties): import xcb, xcb.xproto conn = xcb.connect() atoms = {name: conn.core.InternAtom(False, len(name), name) for name in properties} utf8_string_atom = None for (name, val) in properties.iteritems(): atom = atoms[name].reply().atom type_atom = xcb.xproto.Atom.STRING if isinstance(val, unicode): if (utf8_string_atom is None): utf8_string_atom = conn.core.InternAtom(True, len('UTF8_STRING'), 'UTF8_STRING').reply().atom type_atom = utf8_string_atom val = val.encode(u'utf-8') conn.core.ChangePropertyChecked(xcb.xproto.PropMode.Replace, win_id, atom, type_atom, 8, len(val), val) conn.flush() conn.disconnect()
null
null
null
How did the code set window properties on the window ?
def set_X_window_properties(win_id, **properties): import xcb, xcb.xproto conn = xcb.connect() atoms = {name: conn.core.InternAtom(False, len(name), name) for name in properties} utf8_string_atom = None for (name, val) in properties.iteritems(): atom = atoms[name].reply().atom type_atom = xcb.xproto.Atom.STRING if isinstance(val, unicode): if (utf8_string_atom is None): utf8_string_atom = conn.core.InternAtom(True, len('UTF8_STRING'), 'UTF8_STRING').reply().atom type_atom = utf8_string_atom val = val.encode(u'utf-8') conn.core.ChangePropertyChecked(xcb.xproto.PropMode.Replace, win_id, atom, type_atom, 8, len(val), val) conn.flush() conn.disconnect()
null
null
null
with the specified i d
codeqa
def set X window properties win id **properties import xcb xcb xprotoconn xcb connect atoms {name conn core Intern Atom False len name name for name in properties}utf 8 string atom Nonefor name val in properties iteritems atom atoms[name] reply atomtype atom xcb xproto Atom STRIN Gif isinstance val unicode if utf 8 string atom is None utf 8 string atom conn core Intern Atom True len 'UTF 8 STRING' 'UTF 8 STRING' reply atomtype atom utf 8 string atomval val encode u'utf- 8 ' conn core Change Property Checked xcb xproto Prop Mode Replace win id atom type atom 8 len val val conn flush conn disconnect
null
null
null
null
Question: How did the code set window properties on the window ? Code: def set_X_window_properties(win_id, **properties): import xcb, xcb.xproto conn = xcb.connect() atoms = {name: conn.core.InternAtom(False, len(name), name) for name in properties} utf8_string_atom = None for (name, val) in properties.iteritems(): atom = atoms[name].reply().atom type_atom = xcb.xproto.Atom.STRING if isinstance(val, unicode): if (utf8_string_atom is None): utf8_string_atom = conn.core.InternAtom(True, len('UTF8_STRING'), 'UTF8_STRING').reply().atom type_atom = utf8_string_atom val = val.encode(u'utf-8') conn.core.ChangePropertyChecked(xcb.xproto.PropMode.Replace, win_id, atom, type_atom, 8, len(val), val) conn.flush() conn.disconnect()
null
null
null
What does the code apply onto recursive containers join ?
def treeapply(tree, join, leaf=identity): for typ in join: if isinstance(tree, typ): return join[typ](*map(partial(treeapply, join=join, leaf=leaf), tree)) return leaf(tree)
null
null
null
functions
codeqa
def treeapply tree join leaf identity for typ in join if isinstance tree typ return join[typ] *map partial treeapply join join leaf leaf tree return leaf tree
null
null
null
null
Question: What does the code apply onto recursive containers join ? Code: def treeapply(tree, join, leaf=identity): for typ in join: if isinstance(tree, typ): return join[typ](*map(partial(treeapply, join=join, leaf=leaf), tree)) return leaf(tree)
null
null
null
What does the message in a raised exception match ?
def _assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj, *args, **kwds): exception = None try: callable_obj(*args, **kwds) except expected_exception as ex: exception = ex if (exception is None): self.fail(('%s not raised' % str(expected_exception.__name__))) if isinstance(expected_regexp, string_types): expected_regexp = re.compile(expected_regexp) if (not expected_regexp.search(str(exception))): self.fail(('"%s" does not match "%s"' % (expected_regexp.pattern, str(exception))))
null
null
null
a regexp
codeqa
def assert Raises Regexp self expected exception expected regexp callable obj *args **kwds exception Nonetry callable obj *args **kwds except expected exception as ex exception exif exception is None self fail '%snotraised' % str expected exception name if isinstance expected regexp string types expected regexp re compile expected regexp if not expected regexp search str exception self fail '"%s"doesnotmatch"%s"' % expected regexp pattern str exception
null
null
null
null
Question: What does the message in a raised exception match ? Code: def _assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj, *args, **kwds): exception = None try: callable_obj(*args, **kwds) except expected_exception as ex: exception = ex if (exception is None): self.fail(('%s not raised' % str(expected_exception.__name__))) if isinstance(expected_regexp, string_types): expected_regexp = re.compile(expected_regexp) if (not expected_regexp.search(str(exception))): self.fail(('"%s" does not match "%s"' % (expected_regexp.pattern, str(exception))))
null
null
null
What matches a regexp ?
def _assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj, *args, **kwds): exception = None try: callable_obj(*args, **kwds) except expected_exception as ex: exception = ex if (exception is None): self.fail(('%s not raised' % str(expected_exception.__name__))) if isinstance(expected_regexp, string_types): expected_regexp = re.compile(expected_regexp) if (not expected_regexp.search(str(exception))): self.fail(('"%s" does not match "%s"' % (expected_regexp.pattern, str(exception))))
null
null
null
the message in a raised exception
codeqa
def assert Raises Regexp self expected exception expected regexp callable obj *args **kwds exception Nonetry callable obj *args **kwds except expected exception as ex exception exif exception is None self fail '%snotraised' % str expected exception name if isinstance expected regexp string types expected regexp re compile expected regexp if not expected regexp search str exception self fail '"%s"doesnotmatch"%s"' % expected regexp pattern str exception
null
null
null
null
Question: What matches a regexp ? Code: def _assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj, *args, **kwds): exception = None try: callable_obj(*args, **kwds) except expected_exception as ex: exception = ex if (exception is None): self.fail(('%s not raised' % str(expected_exception.__name__))) if isinstance(expected_regexp, string_types): expected_regexp = re.compile(expected_regexp) if (not expected_regexp.search(str(exception))): self.fail(('"%s" does not match "%s"' % (expected_regexp.pattern, str(exception))))
null
null
null
What did the code set to the matrix ?
def setElementNodeDictionaryMatrix(elementNode, matrix4X4): if (elementNode.xmlObject == None): elementNode.attributes.update(matrix4X4.getAttributes('matrix.')) else: elementNode.xmlObject.matrix4X4 = matrix4X4
null
null
null
the element attribute dictionary or element matrix
codeqa
def set Element Node Dictionary Matrix element Node matrix 4 X 4 if element Node xml Object None element Node attributes update matrix 4 X 4 get Attributes 'matrix ' else element Node xml Object matrix 4 X 4 matrix 4 X 4
null
null
null
null
Question: What did the code set to the matrix ? Code: def setElementNodeDictionaryMatrix(elementNode, matrix4X4): if (elementNode.xmlObject == None): elementNode.attributes.update(matrix4X4.getAttributes('matrix.')) else: elementNode.xmlObject.matrix4X4 = matrix4X4
null
null
null
What does function handle ?
@anonymous_user_required def register(): if (_security.confirmable or request.json): form_class = _security.confirm_register_form else: form_class = _security.register_form if request.json: form_data = MultiDict(request.json) else: form_data = request.form form = form_class(form_data) if form.validate_on_submit(): user = register_user(**form.to_dict()) form.user = user if ((not _security.confirmable) or _security.login_without_confirmation): after_this_request(_commit) login_user(user) if (not request.json): if ('next' in form): redirect_url = get_post_register_redirect(form.next.data) else: redirect_url = get_post_register_redirect() return redirect(redirect_url) return _render_json(form, include_auth_token=True) if request.json: return _render_json(form) return _security.render_template(config_value('REGISTER_USER_TEMPLATE'), register_user_form=form, **_ctx('register'))
null
null
null
a registration request
codeqa
@anonymous user requireddef register if security confirmable or request json form class security confirm register formelse form class security register formif request json form data Multi Dict request json else form data request formform form class form data if form validate on submit user register user **form to dict form user userif not security confirmable or security login without confirmation after this request commit login user user if not request json if 'next' in form redirect url get post register redirect form next data else redirect url get post register redirect return redirect redirect url return render json form include auth token True if request json return render json form return security render template config value 'REGISTER USER TEMPLATE' register user form form ** ctx 'register'
null
null
null
null
Question: What does function handle ? Code: @anonymous_user_required def register(): if (_security.confirmable or request.json): form_class = _security.confirm_register_form else: form_class = _security.register_form if request.json: form_data = MultiDict(request.json) else: form_data = request.form form = form_class(form_data) if form.validate_on_submit(): user = register_user(**form.to_dict()) form.user = user if ((not _security.confirmable) or _security.login_without_confirmation): after_this_request(_commit) login_user(user) if (not request.json): if ('next' in form): redirect_url = get_post_register_redirect(form.next.data) else: redirect_url = get_post_register_redirect() return redirect(redirect_url) return _render_json(form, include_auth_token=True) if request.json: return _render_json(form) return _security.render_template(config_value('REGISTER_USER_TEMPLATE'), register_user_form=form, **_ctx('register'))
null
null
null
What handles a registration request ?
@anonymous_user_required def register(): if (_security.confirmable or request.json): form_class = _security.confirm_register_form else: form_class = _security.register_form if request.json: form_data = MultiDict(request.json) else: form_data = request.form form = form_class(form_data) if form.validate_on_submit(): user = register_user(**form.to_dict()) form.user = user if ((not _security.confirmable) or _security.login_without_confirmation): after_this_request(_commit) login_user(user) if (not request.json): if ('next' in form): redirect_url = get_post_register_redirect(form.next.data) else: redirect_url = get_post_register_redirect() return redirect(redirect_url) return _render_json(form, include_auth_token=True) if request.json: return _render_json(form) return _security.render_template(config_value('REGISTER_USER_TEMPLATE'), register_user_form=form, **_ctx('register'))
null
null
null
function
codeqa
@anonymous user requireddef register if security confirmable or request json form class security confirm register formelse form class security register formif request json form data Multi Dict request json else form data request formform form class form data if form validate on submit user register user **form to dict form user userif not security confirmable or security login without confirmation after this request commit login user user if not request json if 'next' in form redirect url get post register redirect form next data else redirect url get post register redirect return redirect redirect url return render json form include auth token True if request json return render json form return security render template config value 'REGISTER USER TEMPLATE' register user form form ** ctx 'register'
null
null
null
null
Question: What handles a registration request ? Code: @anonymous_user_required def register(): if (_security.confirmable or request.json): form_class = _security.confirm_register_form else: form_class = _security.register_form if request.json: form_data = MultiDict(request.json) else: form_data = request.form form = form_class(form_data) if form.validate_on_submit(): user = register_user(**form.to_dict()) form.user = user if ((not _security.confirmable) or _security.login_without_confirmation): after_this_request(_commit) login_user(user) if (not request.json): if ('next' in form): redirect_url = get_post_register_redirect(form.next.data) else: redirect_url = get_post_register_redirect() return redirect(redirect_url) return _render_json(form, include_auth_token=True) if request.json: return _render_json(form) return _security.render_template(config_value('REGISTER_USER_TEMPLATE'), register_user_form=form, **_ctx('register'))
null
null
null
What allows you to use parameters hidden from the build with parameter page ?
def hidden_param(parser, xml_parent, data): base_param(parser, xml_parent, data, True, 'com.wangyin.parameter.WHideParameterDefinition')
null
null
null
hidden
codeqa
def hidden param parser xml parent data base param parser xml parent data True 'com wangyin parameter W Hide Parameter Definition'
null
null
null
null
Question: What allows you to use parameters hidden from the build with parameter page ? Code: def hidden_param(parser, xml_parent, data): base_param(parser, xml_parent, data, True, 'com.wangyin.parameter.WHideParameterDefinition')
null
null
null
How did parameters hide from the build ?
def hidden_param(parser, xml_parent, data): base_param(parser, xml_parent, data, True, 'com.wangyin.parameter.WHideParameterDefinition')
null
null
null
with parameter page
codeqa
def hidden param parser xml parent data base param parser xml parent data True 'com wangyin parameter W Hide Parameter Definition'
null
null
null
null
Question: How did parameters hide from the build ? Code: def hidden_param(parser, xml_parent, data): base_param(parser, xml_parent, data, True, 'com.wangyin.parameter.WHideParameterDefinition')
null
null
null
What does the code setup ?
def setup_platform(hass, config, add_devices_callback, discovery_info=None): add_devices_callback([DemoLight('Bed Light', False, effect_list=LIGHT_EFFECT_LIST, effect=LIGHT_EFFECT_LIST[0]), DemoLight('Ceiling Lights', True, LIGHT_COLORS[0], LIGHT_TEMPS[1]), DemoLight('Kitchen Lights', True, LIGHT_COLORS[1], LIGHT_TEMPS[0])])
null
null
null
the demo light platform
codeqa
def setup platform hass config add devices callback discovery info None add devices callback [ Demo Light ' Bed Light' False effect list LIGHT EFFECT LIST effect LIGHT EFFECT LIST[ 0 ] Demo Light ' Ceiling Lights' True LIGHT COLORS[ 0 ] LIGHT TEMPS[ 1 ] Demo Light ' Kitchen Lights' True LIGHT COLORS[ 1 ] LIGHT TEMPS[ 0 ] ]
null
null
null
null
Question: What does the code setup ? Code: def setup_platform(hass, config, add_devices_callback, discovery_info=None): add_devices_callback([DemoLight('Bed Light', False, effect_list=LIGHT_EFFECT_LIST, effect=LIGHT_EFFECT_LIST[0]), DemoLight('Ceiling Lights', True, LIGHT_COLORS[0], LIGHT_TEMPS[1]), DemoLight('Kitchen Lights', True, LIGHT_COLORS[1], LIGHT_TEMPS[0])])
null
null
null
What does the code get ?
def get_topic_similarity(topic_1, topic_2): if ((topic_1 in RECOMMENDATION_CATEGORIES) and (topic_2 in RECOMMENDATION_CATEGORIES)): topic_similarities = get_topic_similarities_dict() return topic_similarities[topic_1][topic_2] elif (topic_1 == topic_2): return feconf.SAME_TOPIC_SIMILARITY else: return feconf.DEFAULT_TOPIC_SIMILARITY
null
null
null
the similarity between two topics
codeqa
def get topic similarity topic 1 topic 2 if topic 1 in RECOMMENDATION CATEGORIES and topic 2 in RECOMMENDATION CATEGORIES topic similarities get topic similarities dict return topic similarities[topic 1][topic 2]elif topic 1 topic 2 return feconf SAME TOPIC SIMILARIT Yelse return feconf DEFAULT TOPIC SIMILARITY
null
null
null
null
Question: What does the code get ? Code: def get_topic_similarity(topic_1, topic_2): if ((topic_1 in RECOMMENDATION_CATEGORIES) and (topic_2 in RECOMMENDATION_CATEGORIES)): topic_similarities = get_topic_similarities_dict() return topic_similarities[topic_1][topic_2] elif (topic_1 == topic_2): return feconf.SAME_TOPIC_SIMILARITY else: return feconf.DEFAULT_TOPIC_SIMILARITY
null
null
null
What does a convenience function retrieve ?
def _getOneModelInfo(nupicModelID): return _iterModels([nupicModelID]).next()
null
null
null
inforamtion about a single model
codeqa
def get One Model Info nupic Model ID return iter Models [nupic Model ID] next
null
null
null
null
Question: What does a convenience function retrieve ? Code: def _getOneModelInfo(nupicModelID): return _iterModels([nupicModelID]).next()
null
null
null
What does the code retrieve by name ?
def getProviderByName(name): if (name.lower() == 'mapnik'): from . import Mapnik return Mapnik.ImageProvider elif (name.lower() == 'proxy'): return Proxy elif (name.lower() == 'url template'): return UrlTemplate elif (name.lower() == 'vector'): from . import Vector return Vector.Provider elif (name.lower() == 'mbtiles'): from . import MBTiles return MBTiles.Provider elif (name.lower() == 'mapnik grid'): from . import Mapnik return Mapnik.GridProvider elif (name.lower() == 'sandwich'): from . import Sandwich return Sandwich.Provider raise Exception(('Unknown provider name: "%s"' % name))
null
null
null
a provider object
codeqa
def get Provider By Name name if name lower 'mapnik' from import Mapnikreturn Mapnik Image Providerelif name lower 'proxy' return Proxyelif name lower 'urltemplate' return Url Templateelif name lower 'vector' from import Vectorreturn Vector Providerelif name lower 'mbtiles' from import MB Tilesreturn MB Tiles Providerelif name lower 'mapnikgrid' from import Mapnikreturn Mapnik Grid Providerelif name lower 'sandwich' from import Sandwichreturn Sandwich Providerraise Exception ' Unknownprovidername "%s"' % name
null
null
null
null
Question: What does the code retrieve by name ? Code: def getProviderByName(name): if (name.lower() == 'mapnik'): from . import Mapnik return Mapnik.ImageProvider elif (name.lower() == 'proxy'): return Proxy elif (name.lower() == 'url template'): return UrlTemplate elif (name.lower() == 'vector'): from . import Vector return Vector.Provider elif (name.lower() == 'mbtiles'): from . import MBTiles return MBTiles.Provider elif (name.lower() == 'mapnik grid'): from . import Mapnik return Mapnik.GridProvider elif (name.lower() == 'sandwich'): from . import Sandwich return Sandwich.Provider raise Exception(('Unknown provider name: "%s"' % name))
null
null
null
How does the code retrieve a provider object ?
def getProviderByName(name): if (name.lower() == 'mapnik'): from . import Mapnik return Mapnik.ImageProvider elif (name.lower() == 'proxy'): return Proxy elif (name.lower() == 'url template'): return UrlTemplate elif (name.lower() == 'vector'): from . import Vector return Vector.Provider elif (name.lower() == 'mbtiles'): from . import MBTiles return MBTiles.Provider elif (name.lower() == 'mapnik grid'): from . import Mapnik return Mapnik.GridProvider elif (name.lower() == 'sandwich'): from . import Sandwich return Sandwich.Provider raise Exception(('Unknown provider name: "%s"' % name))
null
null
null
by name
codeqa
def get Provider By Name name if name lower 'mapnik' from import Mapnikreturn Mapnik Image Providerelif name lower 'proxy' return Proxyelif name lower 'urltemplate' return Url Templateelif name lower 'vector' from import Vectorreturn Vector Providerelif name lower 'mbtiles' from import MB Tilesreturn MB Tiles Providerelif name lower 'mapnikgrid' from import Mapnikreturn Mapnik Grid Providerelif name lower 'sandwich' from import Sandwichreturn Sandwich Providerraise Exception ' Unknownprovidername "%s"' % name
null
null
null
null
Question: How does the code retrieve a provider object ? Code: def getProviderByName(name): if (name.lower() == 'mapnik'): from . import Mapnik return Mapnik.ImageProvider elif (name.lower() == 'proxy'): return Proxy elif (name.lower() == 'url template'): return UrlTemplate elif (name.lower() == 'vector'): from . import Vector return Vector.Provider elif (name.lower() == 'mbtiles'): from . import MBTiles return MBTiles.Provider elif (name.lower() == 'mapnik grid'): from . import Mapnik return Mapnik.GridProvider elif (name.lower() == 'sandwich'): from . import Sandwich return Sandwich.Provider raise Exception(('Unknown provider name: "%s"' % name))
null
null
null
What did the code read ?
def read_float(fid): return _unpack_simple(fid, '>f4', np.float32)
null
null
null
32bit float
codeqa
def read float fid return unpack simple fid '>f 4 ' np float 32
null
null
null
null
Question: What did the code read ? Code: def read_float(fid): return _unpack_simple(fid, '>f4', np.float32)
null
null
null
What does the display name be ?
def get_service_name(*args): raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if ((raw_service['DisplayName'] in args) or (raw_service['ServiceName'] in args) or (raw_service['ServiceName'].lower() in args)): services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services
null
null
null
what is displayed in windows when services
codeqa
def get service name *args raw services get services services dict for raw service in raw services if args if raw service[' Display Name'] in args or raw service[' Service Name'] in args or raw service[' Service Name'] lower in args services[raw service[' Display Name']] raw service[' Service Name']else services[raw service[' Display Name']] raw service[' Service Name']return services
null
null
null
null
Question: What does the display name be ? Code: def get_service_name(*args): raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if ((raw_service['DisplayName'] in args) or (raw_service['ServiceName'] in args) or (raw_service['ServiceName'].lower() in args)): services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services
null
null
null
When is what displayed in windows ?
def get_service_name(*args): raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if ((raw_service['DisplayName'] in args) or (raw_service['ServiceName'] in args) or (raw_service['ServiceName'].lower() in args)): services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services
null
null
null
when services
codeqa
def get service name *args raw services get services services dict for raw service in raw services if args if raw service[' Display Name'] in args or raw service[' Service Name'] in args or raw service[' Service Name'] lower in args services[raw service[' Display Name']] raw service[' Service Name']else services[raw service[' Display Name']] raw service[' Service Name']return services
null
null
null
null
Question: When is what displayed in windows ? Code: def get_service_name(*args): raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if ((raw_service['DisplayName'] in args) or (raw_service['ServiceName'] in args) or (raw_service['ServiceName'].lower() in args)): services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services
null
null
null
What did the code expect ?
@register.assignment_tag(takes_context=False) def assignment_explicit_no_context(arg): return ('assignment_explicit_no_context - Expected result: %s' % arg)
null
null
null
assignment_explicit_no_context _ _ doc _ _
codeqa
@register assignment tag takes context False def assignment explicit no context arg return 'assignment explicit no context- Expectedresult %s' % arg
null
null
null
null
Question: What did the code expect ? Code: @register.assignment_tag(takes_context=False) def assignment_explicit_no_context(arg): return ('assignment_explicit_no_context - Expected result: %s' % arg)
null
null
null
Does asserting a string with a curly brace choke the string formatter ?
def test_doesnt_fail_on_curly(): ok = False try: assert False, '}' except AssertionError: ok = True Assert(ok)
null
null
null
No
codeqa
def test doesnt fail on curly ok Falsetry assert False '}'except Assertion Error ok True Assert ok
null
null
null
null
Question: Does asserting a string with a curly brace choke the string formatter ? Code: def test_doesnt_fail_on_curly(): ok = False try: assert False, '}' except AssertionError: ok = True Assert(ok)
null
null
null
How do a string assert ?
def test_doesnt_fail_on_curly(): ok = False try: assert False, '}' except AssertionError: ok = True Assert(ok)
null
null
null
with a curly brace
codeqa
def test doesnt fail on curly ok Falsetry assert False '}'except Assertion Error ok True Assert ok
null
null
null
null
Question: How do a string assert ? Code: def test_doesnt_fail_on_curly(): ok = False try: assert False, '}' except AssertionError: ok = True Assert(ok)
null
null
null
What aggregate downstream test results ?
def aggregate_tests(registry, xml_parent, data): agg = XML.SubElement(xml_parent, 'hudson.tasks.test.AggregatedTestResultPublisher') XML.SubElement(agg, 'includeFailedBuilds').text = str(data.get('include-failed-builds', False)).lower()
null
null
null
aggregate - tests
codeqa
def aggregate tests registry xml parent data agg XML Sub Element xml parent 'hudson tasks test Aggregated Test Result Publisher' XML Sub Element agg 'include Failed Builds' text str data get 'include-failed-builds' False lower
null
null
null
null
Question: What aggregate downstream test results ? Code: def aggregate_tests(registry, xml_parent, data): agg = XML.SubElement(xml_parent, 'hudson.tasks.test.AggregatedTestResultPublisher') XML.SubElement(agg, 'includeFailedBuilds').text = str(data.get('include-failed-builds', False)).lower()
null
null
null
What do aggregate - tests aggregate ?
def aggregate_tests(registry, xml_parent, data): agg = XML.SubElement(xml_parent, 'hudson.tasks.test.AggregatedTestResultPublisher') XML.SubElement(agg, 'includeFailedBuilds').text = str(data.get('include-failed-builds', False)).lower()
null
null
null
downstream test results
codeqa
def aggregate tests registry xml parent data agg XML Sub Element xml parent 'hudson tasks test Aggregated Test Result Publisher' XML Sub Element agg 'include Failed Builds' text str data get 'include-failed-builds' False lower
null
null
null
null
Question: What do aggregate - tests aggregate ? Code: def aggregate_tests(registry, xml_parent, data): agg = XML.SubElement(xml_parent, 'hudson.tasks.test.AggregatedTestResultPublisher') XML.SubElement(agg, 'includeFailedBuilds').text = str(data.get('include-failed-builds', False)).lower()
null
null
null
What did the code set ?
def libvlc_video_set_crop_geometry(p_mi, psz_geometry): f = (_Cfunctions.get('libvlc_video_set_crop_geometry', None) or _Cfunction('libvlc_video_set_crop_geometry', ((1,), (1,)), None, None, MediaPlayer, ctypes.c_char_p)) return f(p_mi, psz_geometry)
null
null
null
new crop filter geometry
codeqa
def libvlc video set crop geometry p mi psz geometry f Cfunctions get 'libvlc video set crop geometry' None or Cfunction 'libvlc video set crop geometry' 1 1 None None Media Player ctypes c char p return f p mi psz geometry
null
null
null
null
Question: What did the code set ? Code: def libvlc_video_set_crop_geometry(p_mi, psz_geometry): f = (_Cfunctions.get('libvlc_video_set_crop_geometry', None) or _Cfunction('libvlc_video_set_crop_geometry', ((1,), (1,)), None, None, MediaPlayer, ctypes.c_char_p)) return f(p_mi, psz_geometry)
null
null
null
What does the code normalize ?
def normalize_index(context, builder, idxty, idx): if (isinstance(idxty, types.Array) and (idxty.ndim == 0)): assert isinstance(idxty.dtype, types.Integer) idxary = make_array(idxty)(context, builder, idx) idxval = load_item(context, builder, idxty, idxary.data) return (idxty.dtype, idxval) else: return (idxty, idx)
null
null
null
the index type and value
codeqa
def normalize index context builder idxty idx if isinstance idxty types Array and idxty ndim 0 assert isinstance idxty dtype types Integer idxary make array idxty context builder idx idxval load item context builder idxty idxary data return idxty dtype idxval else return idxty idx
null
null
null
null
Question: What does the code normalize ? Code: def normalize_index(context, builder, idxty, idx): if (isinstance(idxty, types.Array) and (idxty.ndim == 0)): assert isinstance(idxty.dtype, types.Integer) idxary = make_array(idxty)(context, builder, idx) idxval = load_item(context, builder, idxty, idxary.data) return (idxty.dtype, idxval) else: return (idxty, idx)
null
null
null
What does the code ensure ?
def normalize_classname(classname): return classname.replace(u'/', u'.')
null
null
null
the dot separated class name
codeqa
def normalize classname classname return classname replace u'/' u' '
null
null
null
null
Question: What does the code ensure ? Code: def normalize_classname(classname): return classname.replace(u'/', u'.')
null
null
null
What does the code get from the table ?
@require_context def instance_info_cache_get(context, instance_uuid): return model_query(context, models.InstanceInfoCache).filter_by(instance_uuid=instance_uuid).first()
null
null
null
an instance info cache
codeqa
@require contextdef instance info cache get context instance uuid return model query context models Instance Info Cache filter by instance uuid instance uuid first
null
null
null
null
Question: What does the code get from the table ? Code: @require_context def instance_info_cache_get(context, instance_uuid): return model_query(context, models.InstanceInfoCache).filter_by(instance_uuid=instance_uuid).first()
null
null
null
What does the code create ?
def create_project(**kwargs): defaults = {} defaults.update(kwargs) ProjectTemplateFactory.create(slug=settings.DEFAULT_PROJECT_TEMPLATE) project = ProjectFactory.create(**defaults) project.default_issue_status = IssueStatusFactory.create(project=project) project.default_severity = SeverityFactory.create(project=project) project.default_priority = PriorityFactory.create(project=project) project.default_issue_type = IssueTypeFactory.create(project=project) project.default_us_status = UserStoryStatusFactory.create(project=project) project.default_task_status = TaskStatusFactory.create(project=project) project.save() return project
null
null
null
a project along with its dependencies
codeqa
def create project **kwargs defaults {}defaults update kwargs Project Template Factory create slug settings DEFAULT PROJECT TEMPLATE project Project Factory create **defaults project default issue status Issue Status Factory create project project project default severity Severity Factory create project project project default priority Priority Factory create project project project default issue type Issue Type Factory create project project project default us status User Story Status Factory create project project project default task status Task Status Factory create project project project save return project
null
null
null
null
Question: What does the code create ? Code: def create_project(**kwargs): defaults = {} defaults.update(kwargs) ProjectTemplateFactory.create(slug=settings.DEFAULT_PROJECT_TEMPLATE) project = ProjectFactory.create(**defaults) project.default_issue_status = IssueStatusFactory.create(project=project) project.default_severity = SeverityFactory.create(project=project) project.default_priority = PriorityFactory.create(project=project) project.default_issue_type = IssueTypeFactory.create(project=project) project.default_us_status = UserStoryStatusFactory.create(project=project) project.default_task_status = TaskStatusFactory.create(project=project) project.save() return project
null
null
null
What does the code display ?
def main(): if (len(sys.argv) > 1): writeOutput(' '.join(sys.argv[1:])) else: settings.startMainLoopFromConstructor(getNewRepository())
null
null
null
the cool dialog
codeqa
def main if len sys argv > 1 write Output '' join sys argv[ 1 ] else settings start Main Loop From Constructor get New Repository
null
null
null
null
Question: What does the code display ? Code: def main(): if (len(sys.argv) > 1): writeOutput(' '.join(sys.argv[1:])) else: settings.startMainLoopFromConstructor(getNewRepository())
null
null
null
What does the code get ?
def group_get_all(context, filters=None, marker=None, limit=None, offset=None, sort_keys=None, sort_dirs=None): return IMPL.group_get_all(context, filters=filters, marker=marker, limit=limit, offset=offset, sort_keys=sort_keys, sort_dirs=sort_dirs)
null
null
null
all groups
codeqa
def group get all context filters None marker None limit None offset None sort keys None sort dirs None return IMPL group get all context filters filters marker marker limit limit offset offset sort keys sort keys sort dirs sort dirs
null
null
null
null
Question: What does the code get ? Code: def group_get_all(context, filters=None, marker=None, limit=None, offset=None, sort_keys=None, sort_dirs=None): return IMPL.group_get_all(context, filters=filters, marker=marker, limit=limit, offset=offset, sort_keys=sort_keys, sort_dirs=sort_dirs)
null
null
null
How do search queries log ?
def log_query(func): def wrapper(obj, query_string, *args, **kwargs): start = time() try: return func(obj, query_string, *args, **kwargs) finally: stop = time() if settings.DEBUG: from haystack import connections connections[obj.connection_alias].queries.append({u'query_string': query_string, u'additional_args': args, u'additional_kwargs': kwargs, u'time': (u'%.3f' % (stop - start)), u'start': start, u'stop': stop}) return wrapper
null
null
null
pseudo
codeqa
def log query func def wrapper obj query string *args **kwargs start time try return func obj query string *args **kwargs finally stop time if settings DEBUG from haystack import connectionsconnections[obj connection alias] queries append {u'query string' query string u'additional args' args u'additional kwargs' kwargs u'time' u'% 3f' % stop - start u'start' start u'stop' stop} return wrapper
null
null
null
null
Question: How do search queries log ? Code: def log_query(func): def wrapper(obj, query_string, *args, **kwargs): start = time() try: return func(obj, query_string, *args, **kwargs) finally: stop = time() if settings.DEBUG: from haystack import connections connections[obj.connection_alias].queries.append({u'query_string': query_string, u'additional_args': args, u'additional_kwargs': kwargs, u'time': (u'%.3f' % (stop - start)), u'start': start, u'stop': stop}) return wrapper
null
null
null
What does the code require ?
@pytest.fixture def member2(): from django.contrib.auth import get_user_model return get_user_model().objects.get(username='member2')
null
null
null
a member2 user
codeqa
@pytest fixturedef member 2 from django contrib auth import get user modelreturn get user model objects get username 'member 2 '
null
null
null
null
Question: What does the code require ? Code: @pytest.fixture def member2(): from django.contrib.auth import get_user_model return get_user_model().objects.get(username='member2')
null
null
null
For what purpose do a tuple represent the sector ?
def sectorize(position): (x, y, z) = normalize(position) (x, y, z) = ((x // SECTOR_SIZE), (y // SECTOR_SIZE), (z // SECTOR_SIZE)) return (x, 0, z)
null
null
null
for the given position
codeqa
def sectorize position x y z normalize position x y z x // SECTOR SIZE y // SECTOR SIZE z // SECTOR SIZE return x 0 z
null
null
null
null
Question: For what purpose do a tuple represent the sector ? Code: def sectorize(position): (x, y, z) = normalize(position) (x, y, z) = ((x // SECTOR_SIZE), (y // SECTOR_SIZE), (z // SECTOR_SIZE)) return (x, 0, z)
null
null
null
What do a tuple represent for the given position ?
def sectorize(position): (x, y, z) = normalize(position) (x, y, z) = ((x // SECTOR_SIZE), (y // SECTOR_SIZE), (z // SECTOR_SIZE)) return (x, 0, z)
null
null
null
the sector
codeqa
def sectorize position x y z normalize position x y z x // SECTOR SIZE y // SECTOR SIZE z // SECTOR SIZE return x 0 z
null
null
null
null
Question: What do a tuple represent for the given position ? Code: def sectorize(position): (x, y, z) = normalize(position) (x, y, z) = ((x // SECTOR_SIZE), (y // SECTOR_SIZE), (z // SECTOR_SIZE)) return (x, 0, z)
null
null
null
What is representing the sector for the given position ?
def sectorize(position): (x, y, z) = normalize(position) (x, y, z) = ((x // SECTOR_SIZE), (y // SECTOR_SIZE), (z // SECTOR_SIZE)) return (x, 0, z)
null
null
null
a tuple
codeqa
def sectorize position x y z normalize position x y z x // SECTOR SIZE y // SECTOR SIZE z // SECTOR SIZE return x 0 z
null
null
null
null
Question: What is representing the sector for the given position ? Code: def sectorize(position): (x, y, z) = normalize(position) (x, y, z) = ((x // SECTOR_SIZE), (y // SECTOR_SIZE), (z // SECTOR_SIZE)) return (x, 0, z)
null
null
null
What does the code get in a directory ?
def get_matching_files(dirname, exclude_matchers=()): dirname = path.normpath(path.abspath(dirname)) dirlen = (len(dirname) + 1) for (root, dirs, files) in walk(dirname, followlinks=True): relativeroot = root[dirlen:] qdirs = enumerate((path_stabilize(path.join(relativeroot, dn)) for dn in dirs)) qfiles = enumerate((path_stabilize(path.join(relativeroot, fn)) for fn in files)) for matcher in exclude_matchers: qdirs = [entry for entry in qdirs if (not matcher(entry[1]))] qfiles = [entry for entry in qfiles if (not matcher(entry[1]))] dirs[:] = sorted((dirs[i] for (i, _) in qdirs)) for (i, filename) in sorted(qfiles): (yield filename)
null
null
null
all file names
codeqa
def get matching files dirname exclude matchers dirname path normpath path abspath dirname dirlen len dirname + 1 for root dirs files in walk dirname followlinks True relativeroot root[dirlen ]qdirs enumerate path stabilize path join relativeroot dn for dn in dirs qfiles enumerate path stabilize path join relativeroot fn for fn in files for matcher in exclude matchers qdirs [entry for entry in qdirs if not matcher entry[ 1 ] ]qfiles [entry for entry in qfiles if not matcher entry[ 1 ] ]dirs[ ] sorted dirs[i] for i in qdirs for i filename in sorted qfiles yield filename
null
null
null
null
Question: What does the code get in a directory ? Code: def get_matching_files(dirname, exclude_matchers=()): dirname = path.normpath(path.abspath(dirname)) dirlen = (len(dirname) + 1) for (root, dirs, files) in walk(dirname, followlinks=True): relativeroot = root[dirlen:] qdirs = enumerate((path_stabilize(path.join(relativeroot, dn)) for dn in dirs)) qfiles = enumerate((path_stabilize(path.join(relativeroot, fn)) for fn in files)) for matcher in exclude_matchers: qdirs = [entry for entry in qdirs if (not matcher(entry[1]))] qfiles = [entry for entry in qfiles if (not matcher(entry[1]))] dirs[:] = sorted((dirs[i] for (i, _) in qdirs)) for (i, filename) in sorted(qfiles): (yield filename)
null
null
null
Where does the code get all file names ?
def get_matching_files(dirname, exclude_matchers=()): dirname = path.normpath(path.abspath(dirname)) dirlen = (len(dirname) + 1) for (root, dirs, files) in walk(dirname, followlinks=True): relativeroot = root[dirlen:] qdirs = enumerate((path_stabilize(path.join(relativeroot, dn)) for dn in dirs)) qfiles = enumerate((path_stabilize(path.join(relativeroot, fn)) for fn in files)) for matcher in exclude_matchers: qdirs = [entry for entry in qdirs if (not matcher(entry[1]))] qfiles = [entry for entry in qfiles if (not matcher(entry[1]))] dirs[:] = sorted((dirs[i] for (i, _) in qdirs)) for (i, filename) in sorted(qfiles): (yield filename)
null
null
null
in a directory
codeqa
def get matching files dirname exclude matchers dirname path normpath path abspath dirname dirlen len dirname + 1 for root dirs files in walk dirname followlinks True relativeroot root[dirlen ]qdirs enumerate path stabilize path join relativeroot dn for dn in dirs qfiles enumerate path stabilize path join relativeroot fn for fn in files for matcher in exclude matchers qdirs [entry for entry in qdirs if not matcher entry[ 1 ] ]qfiles [entry for entry in qfiles if not matcher entry[ 1 ] ]dirs[ ] sorted dirs[i] for i in qdirs for i filename in sorted qfiles yield filename
null
null
null
null
Question: Where does the code get all file names ? Code: def get_matching_files(dirname, exclude_matchers=()): dirname = path.normpath(path.abspath(dirname)) dirlen = (len(dirname) + 1) for (root, dirs, files) in walk(dirname, followlinks=True): relativeroot = root[dirlen:] qdirs = enumerate((path_stabilize(path.join(relativeroot, dn)) for dn in dirs)) qfiles = enumerate((path_stabilize(path.join(relativeroot, fn)) for fn in files)) for matcher in exclude_matchers: qdirs = [entry for entry in qdirs if (not matcher(entry[1]))] qfiles = [entry for entry in qfiles if (not matcher(entry[1]))] dirs[:] = sorted((dirs[i] for (i, _) in qdirs)) for (i, filename) in sorted(qfiles): (yield filename)
null
null
null
What does position line use when ?
def test_read_twoline_wrong_marker(): table = '\n| Col1 | Col2 |\n|aaaaaa|aaaaaaaaaa|\n| 1.2 | "hello" |\n| 2.4 | \'s worlds|\n' with pytest.raises(InconsistentTableError) as excinfo: dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine, delimiter='|', guess=False) assert ('Characters in position line must be part' in str(excinfo.value))
null
null
null
characters prone to ambiguity characters in position line
codeqa
def test read twoline wrong marker table '\n Col 1 Col 2 \n aaaaaa aaaaaaaaaa \n 1 2 "hello" \n 2 4 \'sworlds \n'with pytest raises Inconsistent Table Error as excinfo dat ascii read table Reader ascii Fixed Width Two Line delimiter ' ' guess False assert ' Charactersinpositionlinemustbepart' in str excinfo value
null
null
null
null
Question: What does position line use when ? Code: def test_read_twoline_wrong_marker(): table = '\n| Col1 | Col2 |\n|aaaaaa|aaaaaaaaaa|\n| 1.2 | "hello" |\n| 2.4 | \'s worlds|\n' with pytest.raises(InconsistentTableError) as excinfo: dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine, delimiter='|', guess=False) assert ('Characters in position line must be part' in str(excinfo.value))
null
null
null
What does the code turn into an anchor ?
def _get_anchor(module_to_name, fullname): if (not _anchor_re.match(fullname)): raise ValueError(("'%s' is not a valid anchor" % fullname)) anchor = fullname for module_name in module_to_name.values(): if fullname.startswith((module_name + '.')): rest = fullname[(len(module_name) + 1):] if (len(anchor) > len(rest)): anchor = rest return anchor
null
null
null
a full member name
codeqa
def get anchor module to name fullname if not anchor re match fullname raise Value Error "'%s'isnotavalidanchor" % fullname anchor fullnamefor module name in module to name values if fullname startswith module name + ' ' rest fullname[ len module name + 1 ]if len anchor > len rest anchor restreturn anchor
null
null
null
null
Question: What does the code turn into an anchor ? Code: def _get_anchor(module_to_name, fullname): if (not _anchor_re.match(fullname)): raise ValueError(("'%s' is not a valid anchor" % fullname)) anchor = fullname for module_name in module_to_name.values(): if fullname.startswith((module_name + '.')): rest = fullname[(len(module_name) + 1):] if (len(anchor) > len(rest)): anchor = rest return anchor
null
null
null
What does the code get ?
@data def file_data(name): if (name in editors): return editors[name].get_raw_data() return current_container().raw_data(name)
null
null
null
the data for name
codeqa
@datadef file data name if name in editors return editors[name] get raw data return current container raw data name
null
null
null
null
Question: What does the code get ? Code: @data def file_data(name): if (name in editors): return editors[name].get_raw_data() return current_container().raw_data(name)
null
null
null
What does the code get ?
def snapshot_get_all_by_project(context, project_id, filters=None, marker=None, limit=None, sort_keys=None, sort_dirs=None, offset=None): return IMPL.snapshot_get_all_by_project(context, project_id, filters, marker, limit, sort_keys, sort_dirs, offset)
null
null
null
all snapshots belonging to a project
codeqa
def snapshot get all by project context project id filters None marker None limit None sort keys None sort dirs None offset None return IMPL snapshot get all by project context project id filters marker limit sort keys sort dirs offset
null
null
null
null
Question: What does the code get ? Code: def snapshot_get_all_by_project(context, project_id, filters=None, marker=None, limit=None, sort_keys=None, sort_dirs=None, offset=None): return IMPL.snapshot_get_all_by_project(context, project_id, filters, marker, limit, sort_keys, sort_dirs, offset)
null
null
null
What does helper function return ?
def _bits_to_bytes_len(length_in_bits): return ((length_in_bits + 7) // 8)
null
null
null
the numbers of bytes necessary to store the given number of bits
codeqa
def bits to bytes len length in bits return length in bits + 7 // 8
null
null
null
null
Question: What does helper function return ? Code: def _bits_to_bytes_len(length_in_bits): return ((length_in_bits + 7) // 8)
null
null
null
What returns the numbers of bytes necessary to store the given number of bits ?
def _bits_to_bytes_len(length_in_bits): return ((length_in_bits + 7) // 8)
null
null
null
helper function
codeqa
def bits to bytes len length in bits return length in bits + 7 // 8
null
null
null
null
Question: What returns the numbers of bytes necessary to store the given number of bits ? Code: def _bits_to_bytes_len(length_in_bits): return ((length_in_bits + 7) // 8)
null
null
null
What does the code serve ?
def serve_command(handler_cls, argv=sys.argv, backend=None, inf=sys.stdin, outf=sys.stdout): if (backend is None): backend = FileSystemBackend() def send_fn(data): outf.write(data) outf.flush() proto = Protocol(inf.read, send_fn) handler = handler_cls(backend, argv[1:], proto) handler.handle() return 0
null
null
null
a single command
codeqa
def serve command handler cls argv sys argv backend None inf sys stdin outf sys stdout if backend is None backend File System Backend def send fn data outf write data outf flush proto Protocol inf read send fn handler handler cls backend argv[ 1 ] proto handler handle return 0
null
null
null
null
Question: What does the code serve ? Code: def serve_command(handler_cls, argv=sys.argv, backend=None, inf=sys.stdin, outf=sys.stdout): if (backend is None): backend = FileSystemBackend() def send_fn(data): outf.write(data) outf.flush() proto = Protocol(inf.read, send_fn) handler = handler_cls(backend, argv[1:], proto) handler.handle() return 0
null
null
null
What does the code raise ?
def vo_raise(exception_class, args=(), config=None, pos=None): if (config is None): config = {} raise exception_class(args, config, pos)
null
null
null
an exception
codeqa
def vo raise exception class args config None pos None if config is None config {}raise exception class args config pos
null
null
null
null
Question: What does the code raise ? Code: def vo_raise(exception_class, args=(), config=None, pos=None): if (config is None): config = {} raise exception_class(args, config, pos)
null
null
null
How did various issues with the internet connection manifest when ?
def transient_internet(): time_out = TransientResource(IOError, errno=errno.ETIMEDOUT) socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET) ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET) return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset)
null
null
null
as exceptions
codeqa
def transient internet time out Transient Resource IO Error errno errno ETIMEDOUT socket peer reset Transient Resource socket error errno errno ECONNRESET ioerror peer reset Transient Resource IO Error errno errno ECONNRESET return contextlib nested time out socket peer reset ioerror peer reset
null
null
null
null
Question: How did various issues with the internet connection manifest when ? Code: def transient_internet(): time_out = TransientResource(IOError, errno=errno.ETIMEDOUT) socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET) ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET) return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset)