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
When did account page class register ?
def unregister_account_page_class(page_cls): warn(u'unregister_account_page_class is deprecated in Review Board 3.0 and will be removed; use AccountPage.registry.unregister instead.', DeprecationWarning) AccountPage.registry.unregister(page_cls)
null
null
null
previously
codeqa
def unregister account page class page cls warn u'unregister account page classisdeprecatedin Review Board 3 0andwillberemoved use Account Page registry unregisterinstead ' Deprecation Warning Account Page registry unregister page cls
null
null
null
null
Question: When did account page class register ? Code: def unregister_account_page_class(page_cls): warn(u'unregister_account_page_class is deprecated in Review Board 3.0 and will be removed; use AccountPage.registry.unregister instead.', DeprecationWarning) AccountPage.registry.unregister(page_cls)
null
null
null
What passes the given test ?
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): if (not login_url): from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = (login_url, redirect_field_name, path) return HttpResponseRedirect(('%s?%s=%s' % tup)) return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator
null
null
null
the user
codeqa
def user passes test test func login url None redirect field name REDIRECT FIELD NAME if not login url from django conf import settingslogin url settings LOGIN UR Ldef decorator view func def wrapped view request *args **kwargs if test func request user return view func request *args **kwargs path urlquote request get full path tup login url redirect field name path return Http Response Redirect '%s?%s %s' % tup return wraps view func assigned available attrs view func wrapped view return decorator
null
null
null
null
Question: What passes the given test ? Code: def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): if (not login_url): from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = (login_url, redirect_field_name, path) return HttpResponseRedirect(('%s?%s=%s' % tup)) return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator
null
null
null
What does decorator for views check ?
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): if (not login_url): from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = (login_url, redirect_field_name, path) return HttpResponseRedirect(('%s?%s=%s' % tup)) return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator
null
null
null
that the user passes the given test
codeqa
def user passes test test func login url None redirect field name REDIRECT FIELD NAME if not login url from django conf import settingslogin url settings LOGIN UR Ldef decorator view func def wrapped view request *args **kwargs if test func request user return view func request *args **kwargs path urlquote request get full path tup login url redirect field name path return Http Response Redirect '%s?%s %s' % tup return wraps view func assigned available attrs view func wrapped view return decorator
null
null
null
null
Question: What does decorator for views check ? Code: def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): if (not login_url): from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = (login_url, redirect_field_name, path) return HttpResponseRedirect(('%s?%s=%s' % tup)) return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator
null
null
null
What does the user pass ?
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): if (not login_url): from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = (login_url, redirect_field_name, path) return HttpResponseRedirect(('%s?%s=%s' % tup)) return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator
null
null
null
the given test
codeqa
def user passes test test func login url None redirect field name REDIRECT FIELD NAME if not login url from django conf import settingslogin url settings LOGIN UR Ldef decorator view func def wrapped view request *args **kwargs if test func request user return view func request *args **kwargs path urlquote request get full path tup login url redirect field name path return Http Response Redirect '%s?%s %s' % tup return wraps view func assigned available attrs view func wrapped view return decorator
null
null
null
null
Question: What does the user pass ? Code: def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): if (not login_url): from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = (login_url, redirect_field_name, path) return HttpResponseRedirect(('%s?%s=%s' % tup)) return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator
null
null
null
What checks that the user passes the given test ?
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): if (not login_url): from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = (login_url, redirect_field_name, path) return HttpResponseRedirect(('%s?%s=%s' % tup)) return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator
null
null
null
decorator for views
codeqa
def user passes test test func login url None redirect field name REDIRECT FIELD NAME if not login url from django conf import settingslogin url settings LOGIN UR Ldef decorator view func def wrapped view request *args **kwargs if test func request user return view func request *args **kwargs path urlquote request get full path tup login url redirect field name path return Http Response Redirect '%s?%s %s' % tup return wraps view func assigned available attrs view func wrapped view return decorator
null
null
null
null
Question: What checks that the user passes the given test ? Code: def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): if (not login_url): from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = (login_url, redirect_field_name, path) return HttpResponseRedirect(('%s?%s=%s' % tup)) return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator
null
null
null
When do many task statuses update ?
def task_status_update_many(context, data_dict): results = [] model = context['model'] deferred = context.get('defer_commit') context['defer_commit'] = True for data in data_dict['data']: results.append(_get_action('task_status_update')(context, data)) if (not deferred): context.pop('defer_commit') if (not context.get('defer_commit')): model.Session.commit() return {'results': results}
null
null
null
at once
codeqa
def task status update many context data dict results []model context['model']deferred context get 'defer commit' context['defer commit'] Truefor data in data dict['data'] results append get action 'task status update' context data if not deferred context pop 'defer commit' if not context get 'defer commit' model Session commit return {'results' results}
null
null
null
null
Question: When do many task statuses update ? Code: def task_status_update_many(context, data_dict): results = [] model = context['model'] deferred = context.get('defer_commit') context['defer_commit'] = True for data in data_dict['data']: results.append(_get_action('task_status_update')(context, data)) if (not deferred): context.pop('defer_commit') if (not context.get('defer_commit')): model.Session.commit() return {'results': results}
null
null
null
What do text write ?
def write(text, filename, encoding='utf-8', mode='wb'): (text, encoding) = encode(text, encoding) with open(filename, mode) as textfile: textfile.write(text) return encoding
null
null
null
to file
codeqa
def write text filename encoding 'utf- 8 ' mode 'wb' text encoding encode text encoding with open filename mode as textfile textfile write text return encoding
null
null
null
null
Question: What do text write ? Code: def write(text, filename, encoding='utf-8', mode='wb'): (text, encoding) = encode(text, encoding) with open(filename, mode) as textfile: textfile.write(text) return encoding
null
null
null
For what purpose do the filename of the cache return ?
def _get_buckets_cache_filename(bucket, prefix): cache_dir = _get_cache_dir() if (not os.path.exists(cache_dir)): os.makedirs(cache_dir) return os.path.join(cache_dir, '{0}-{1}-files.cache'.format(bucket, prefix))
null
null
null
for bucket contents
codeqa
def get buckets cache filename bucket prefix cache dir get cache dir if not os path exists cache dir os makedirs cache dir return os path join cache dir '{ 0 }-{ 1 }-files cache' format bucket prefix
null
null
null
null
Question: For what purpose do the filename of the cache return ? Code: def _get_buckets_cache_filename(bucket, prefix): cache_dir = _get_cache_dir() if (not os.path.exists(cache_dir)): os.makedirs(cache_dir) return os.path.join(cache_dir, '{0}-{1}-files.cache'.format(bucket, prefix))
null
null
null
What does the code raise if request ?
def allow(methods=None, debug=False): if (not isinstance(methods, (tuple, list))): methods = [methods] methods = [m.upper() for m in methods if m] if (not methods): methods = ['GET', 'HEAD'] elif (('GET' in methods) and ('HEAD' not in methods)): methods.append('HEAD') cherrypy.response.headers['Allow'] = ', '.join(methods) if (cherrypy.request.method not in methods): if debug: cherrypy.log(('request.method %r not in methods %r' % (cherrypy.request.method, methods)), 'TOOLS.ALLOW') raise cherrypy.HTTPError(405) elif debug: cherrypy.log(('request.method %r in methods %r' % (cherrypy.request.method, methods)), 'TOOLS.ALLOW')
null
null
null
405
codeqa
def allow methods None debug False if not isinstance methods tuple list methods [methods]methods [m upper for m in methods if m]if not methods methods ['GET' 'HEAD']elif 'GET' in methods and 'HEAD' not in methods methods append 'HEAD' cherrypy response headers[' Allow'] ' ' join methods if cherrypy request method not in methods if debug cherrypy log 'request method%rnotinmethods%r' % cherrypy request method methods 'TOOLS ALLOW' raise cherrypy HTTP Error 405 elif debug cherrypy log 'request method%rinmethods%r' % cherrypy request method methods 'TOOLS ALLOW'
null
null
null
null
Question: What does the code raise if request ? Code: def allow(methods=None, debug=False): if (not isinstance(methods, (tuple, list))): methods = [methods] methods = [m.upper() for m in methods if m] if (not methods): methods = ['GET', 'HEAD'] elif (('GET' in methods) and ('HEAD' not in methods)): methods.append('HEAD') cherrypy.response.headers['Allow'] = ', '.join(methods) if (cherrypy.request.method not in methods): if debug: cherrypy.log(('request.method %r not in methods %r' % (cherrypy.request.method, methods)), 'TOOLS.ALLOW') raise cherrypy.HTTPError(405) elif debug: cherrypy.log(('request.method %r in methods %r' % (cherrypy.request.method, methods)), 'TOOLS.ALLOW')
null
null
null
What does the code disassemble ?
def distb(tb=None): if (tb is None): try: tb = sys.last_traceback except AttributeError: raise RuntimeError, 'no last traceback to disassemble' while tb.tb_next: tb = tb.tb_next disassemble(tb.tb_frame.f_code, tb.tb_lasti)
null
null
null
a traceback
codeqa
def distb tb None if tb is None try tb sys last tracebackexcept Attribute Error raise Runtime Error 'nolasttracebacktodisassemble'while tb tb next tb tb tb nextdisassemble tb tb frame f code tb tb lasti
null
null
null
null
Question: What does the code disassemble ? Code: def distb(tb=None): if (tb is None): try: tb = sys.last_traceback except AttributeError: raise RuntimeError, 'no last traceback to disassemble' while tb.tb_next: tb = tb.tb_next disassemble(tb.tb_frame.f_code, tb.tb_lasti)
null
null
null
What does the code convert to a path ?
def url_to_path(url): assert url.startswith('file:'), ('You can only turn file: urls into filenames (not %r)' % url) path = url[len('file:'):].lstrip('/') path = urllib.unquote(path) if _url_drive_re.match(path): path = ((path[0] + ':') + path[2:]) else: path = ('/' + path) return path
null
null
null
a file
codeqa
def url to path url assert url startswith 'file ' ' Youcanonlyturnfile urlsintofilenames not%r ' % url path url[len 'file ' ] lstrip '/' path urllib unquote path if url drive re match path path path[ 0 ] + ' ' + path[ 2 ] else path '/' + path return path
null
null
null
null
Question: What does the code convert to a path ? Code: def url_to_path(url): assert url.startswith('file:'), ('You can only turn file: urls into filenames (not %r)' % url) path = url[len('file:'):].lstrip('/') path = urllib.unquote(path) if _url_drive_re.match(path): path = ((path[0] + ':') + path[2:]) else: path = ('/' + path) return path
null
null
null
What does the code delete ?
def security_group_rule_destroy(context, security_group_rule_id): return IMPL.security_group_rule_destroy(context, security_group_rule_id)
null
null
null
a security group rule
codeqa
def security group rule destroy context security group rule id return IMPL security group rule destroy context security group rule id
null
null
null
null
Question: What does the code delete ? Code: def security_group_rule_destroy(context, security_group_rule_id): return IMPL.security_group_rule_destroy(context, security_group_rule_id)
null
null
null
What did the code read ?
def read_py_file(filename, skip_encoding_cookie=True): with tokopen(filename) as f: if skip_encoding_cookie: return ''.join(strip_encoding_cookie(f)) else: return f.read()
null
null
null
a python file
codeqa
def read py file filename skip encoding cookie True with tokopen filename as f if skip encoding cookie return '' join strip encoding cookie f else return f read
null
null
null
null
Question: What did the code read ? Code: def read_py_file(filename, skip_encoding_cookie=True): with tokopen(filename) as f: if skip_encoding_cookie: return ''.join(strip_encoding_cookie(f)) else: return f.read()
null
null
null
How do pixels add to the pixel table ?
def addPixelToPixelTableWithSteepness(isSteep, pixelDictionary, value, x, y): if isSteep: addPixelToPixelTable(pixelDictionary, value, y, x) else: addPixelToPixelTable(pixelDictionary, value, x, y)
null
null
null
with steepness
codeqa
def add Pixel To Pixel Table With Steepness is Steep pixel Dictionary value x y if is Steep add Pixel To Pixel Table pixel Dictionary value y x else add Pixel To Pixel Table pixel Dictionary value x y
null
null
null
null
Question: How do pixels add to the pixel table ? Code: def addPixelToPixelTableWithSteepness(isSteep, pixelDictionary, value, x, y): if isSteep: addPixelToPixelTable(pixelDictionary, value, y, x) else: addPixelToPixelTable(pixelDictionary, value, x, y)
null
null
null
How can a file upload be updated into the post dictionary ?
def file_upload_view(request): form_data = request.POST.copy() form_data.update(request.FILES) if (isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], unicode)): if (os.path.dirname(form_data['file_field'].name) != ''): return HttpResponseServerError() return HttpResponse('') else: return HttpResponseServerError()
null
null
null
without going pear - shaped
codeqa
def file upload view request form data request POST copy form data update request FILES if isinstance form data get 'file field' Uploaded File and isinstance form data['name'] unicode if os path dirname form data['file field'] name '' return Http Response Server Error return Http Response '' else return Http Response Server Error
null
null
null
null
Question: How can a file upload be updated into the post dictionary ? Code: def file_upload_view(request): form_data = request.POST.copy() form_data.update(request.FILES) if (isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], unicode)): if (os.path.dirname(form_data['file_field'].name) != ''): return HttpResponseServerError() return HttpResponse('') else: return HttpResponseServerError()
null
null
null
What does the code find ?
def find_indentation(node): while (node is not None): if ((node.type == syms.suite) and (len(node.children) > 2)): indent = node.children[1] if (indent.type == token.INDENT): return indent.value node = node.parent return ''
null
null
null
the indentation of * node *
codeqa
def find indentation node while node is not None if node type syms suite and len node children > 2 indent node children[ 1 ]if indent type token INDENT return indent valuenode node parentreturn ''
null
null
null
null
Question: What does the code find ? Code: def find_indentation(node): while (node is not None): if ((node.type == syms.suite) and (len(node.children) > 2)): indent = node.children[1] if (indent.type == token.INDENT): return indent.value node = node.parent return ''
null
null
null
When do the predicate pr ?
def quantify(iterable, pred=bool): return sum(imap(pred, iterable))
null
null
null
how many times
codeqa
def quantify iterable pred bool return sum imap pred iterable
null
null
null
null
Question: When do the predicate pr ? Code: def quantify(iterable, pred=bool): return sum(imap(pred, iterable))
null
null
null
For what purpose do a window - change request pack the code ?
def packRequest_window_change((rows, cols, xpixel, ypixel)): return struct.pack('>4L', cols, rows, xpixel, ypixel)
null
null
null
so that it is suitable for sending
codeqa
def pack Request window change rows cols xpixel ypixel return struct pack '> 4 L' cols rows xpixel ypixel
null
null
null
null
Question: For what purpose do a window - change request pack the code ? Code: def packRequest_window_change((rows, cols, xpixel, ypixel)): return struct.pack('>4L', cols, rows, xpixel, ypixel)
null
null
null
What does the code add ?
def new_func_strip_path(func_name): (filename, line, name) = func_name if filename.endswith('__init__.py'): return ((os.path.basename(filename[:(-12)]) + filename[(-12):]), line, name) return (os.path.basename(filename), line, name)
null
null
null
parents
codeqa
def new func strip path func name filename line name func nameif filename endswith ' init py' return os path basename filename[ -12 ] + filename[ -12 ] line name return os path basename filename line name
null
null
null
null
Question: What does the code add ? Code: def new_func_strip_path(func_name): (filename, line, name) = func_name if filename.endswith('__init__.py'): return ((os.path.basename(filename[:(-12)]) + filename[(-12):]), line, name) return (os.path.basename(filename), line, name)
null
null
null
What does the code get ?
def getClippedAtEndLoopPath(clip, loopPath): if (clip <= 0.0): return loopPath loopPathLength = getPathLength(loopPath) clip = min(clip, (0.3 * loopPathLength)) lastLength = 0.0 pointIndex = 0 totalLength = 0.0 clippedLength = (loopPathLength - clip) while ((totalLength < clippedLength) and (pointIndex < (len(loopPath) - 1))): firstPoint = loopPath[pointIndex] secondPoint = loopPath[(pointIndex + 1)] pointIndex += 1 lastLength = totalLength totalLength += abs((firstPoint - secondPoint)) remainingLength = (clippedLength - lastLength) clippedLoopPath = loopPath[:pointIndex] ultimateClippedPoint = loopPath[pointIndex] penultimateClippedPoint = clippedLoopPath[(-1)] segment = (ultimateClippedPoint - penultimateClippedPoint) segmentLength = abs(segment) if (segmentLength <= 0.0): return clippedLoopPath newUltimatePoint = (penultimateClippedPoint + ((segment * remainingLength) / segmentLength)) return (clippedLoopPath + [newUltimatePoint])
null
null
null
a clipped loop path
codeqa
def get Clipped At End Loop Path clip loop Path if clip < 0 0 return loop Pathloop Path Length get Path Length loop Path clip min clip 0 3 * loop Path Length last Length 0 0point Index 0total Length 0 0clipped Length loop Path Length - clip while total Length < clipped Length and point Index < len loop Path - 1 first Point loop Path[point Index]second Point loop Path[ point Index + 1 ]point Index + 1last Length total Lengthtotal Length + abs first Point - second Point remaining Length clipped Length - last Length clipped Loop Path loop Path[ point Index]ultimate Clipped Point loop Path[point Index]penultimate Clipped Point clipped Loop Path[ -1 ]segment ultimate Clipped Point - penultimate Clipped Point segment Length abs segment if segment Length < 0 0 return clipped Loop Pathnew Ultimate Point penultimate Clipped Point + segment * remaining Length / segment Length return clipped Loop Path + [new Ultimate Point]
null
null
null
null
Question: What does the code get ? Code: def getClippedAtEndLoopPath(clip, loopPath): if (clip <= 0.0): return loopPath loopPathLength = getPathLength(loopPath) clip = min(clip, (0.3 * loopPathLength)) lastLength = 0.0 pointIndex = 0 totalLength = 0.0 clippedLength = (loopPathLength - clip) while ((totalLength < clippedLength) and (pointIndex < (len(loopPath) - 1))): firstPoint = loopPath[pointIndex] secondPoint = loopPath[(pointIndex + 1)] pointIndex += 1 lastLength = totalLength totalLength += abs((firstPoint - secondPoint)) remainingLength = (clippedLength - lastLength) clippedLoopPath = loopPath[:pointIndex] ultimateClippedPoint = loopPath[pointIndex] penultimateClippedPoint = clippedLoopPath[(-1)] segment = (ultimateClippedPoint - penultimateClippedPoint) segmentLength = abs(segment) if (segmentLength <= 0.0): return clippedLoopPath newUltimatePoint = (penultimateClippedPoint + ((segment * remainingLength) / segmentLength)) return (clippedLoopPath + [newUltimatePoint])
null
null
null
Where does the code install the given image ?
def install_os(name, **kwargs): ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ret['changes'] = __salt__['junos.install_os'](name, **kwargs) return ret
null
null
null
on the device
codeqa
def install os name **kwargs ret {'name' name 'changes' {} 'result' True 'comment' ''}ret['changes'] salt ['junos install os'] name **kwargs return ret
null
null
null
null
Question: Where does the code install the given image ? Code: def install_os(name, **kwargs): ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ret['changes'] = __salt__['junos.install_os'](name, **kwargs) return ret
null
null
null
What does the code install on the device ?
def install_os(name, **kwargs): ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ret['changes'] = __salt__['junos.install_os'](name, **kwargs) return ret
null
null
null
the given image
codeqa
def install os name **kwargs ret {'name' name 'changes' {} 'result' True 'comment' ''}ret['changes'] salt ['junos install os'] name **kwargs return ret
null
null
null
null
Question: What does the code install on the device ? Code: def install_os(name, **kwargs): ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ret['changes'] = __salt__['junos.install_os'](name, **kwargs) return ret
null
null
null
What does the code get ?
def net_if_stats(): duplex_map = {cext.DUPLEX_FULL: NIC_DUPLEX_FULL, cext.DUPLEX_HALF: NIC_DUPLEX_HALF, cext.DUPLEX_UNKNOWN: NIC_DUPLEX_UNKNOWN} names = net_io_counters().keys() ret = {} for name in names: mtu = cext_posix.net_if_mtu(name) isup = cext_posix.net_if_flags(name) (duplex, speed) = cext.net_if_duplex_speed(name) ret[name] = _common.snicstats(isup, duplex_map[duplex], speed, mtu) return ret
null
null
null
nic stats
codeqa
def net if stats duplex map {cext DUPLEX FULL NIC DUPLEX FULL cext DUPLEX HALF NIC DUPLEX HALF cext DUPLEX UNKNOWN NIC DUPLEX UNKNOWN}names net io counters keys ret {}for name in names mtu cext posix net if mtu name isup cext posix net if flags name duplex speed cext net if duplex speed name ret[name] common snicstats isup duplex map[duplex] speed mtu return ret
null
null
null
null
Question: What does the code get ? Code: def net_if_stats(): duplex_map = {cext.DUPLEX_FULL: NIC_DUPLEX_FULL, cext.DUPLEX_HALF: NIC_DUPLEX_HALF, cext.DUPLEX_UNKNOWN: NIC_DUPLEX_UNKNOWN} names = net_io_counters().keys() ret = {} for name in names: mtu = cext_posix.net_if_mtu(name) isup = cext_posix.net_if_flags(name) (duplex, speed) = cext.net_if_duplex_speed(name) ret[name] = _common.snicstats(isup, duplex_map[duplex], speed, mtu) return ret
null
null
null
What does the code get ?
def getNewRepository(): return OozebaneRepository()
null
null
null
new repository
codeqa
def get New Repository return Oozebane Repository
null
null
null
null
Question: What does the code get ? Code: def getNewRepository(): return OozebaneRepository()
null
null
null
What did the code set ?
def publish_cmdline(reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=1, argv=None, usage=default_usage, description=default_description): pub = Publisher(reader, parser, writer, settings=settings) pub.set_components(reader_name, parser_name, writer_name) output = pub.publish(argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return output
null
null
null
a publisher for command - line - based file i / o
codeqa
def publish cmdline reader None reader name 'standalone' parser None parser name 'restructuredtext' writer None writer name 'pseudoxml' settings None settings spec None settings overrides None config section None enable exit status 1 argv None usage default usage description default description pub Publisher reader parser writer settings settings pub set components reader name parser name writer name output pub publish argv usage description settings spec settings overrides config section config section enable exit status enable exit status return output
null
null
null
null
Question: What did the code set ? Code: def publish_cmdline(reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=1, argv=None, usage=default_usage, description=default_description): pub = Publisher(reader, parser, writer, settings=settings) pub.set_components(reader_name, parser_name, writer_name) output = pub.publish(argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return output
null
null
null
For what purpose did the code run a publisher ?
def publish_cmdline(reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=1, argv=None, usage=default_usage, description=default_description): pub = Publisher(reader, parser, writer, settings=settings) pub.set_components(reader_name, parser_name, writer_name) output = pub.publish(argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return output
null
null
null
for command - line - based file i / o
codeqa
def publish cmdline reader None reader name 'standalone' parser None parser name 'restructuredtext' writer None writer name 'pseudoxml' settings None settings spec None settings overrides None config section None enable exit status 1 argv None usage default usage description default description pub Publisher reader parser writer settings settings pub set components reader name parser name writer name output pub publish argv usage description settings spec settings overrides config section config section enable exit status enable exit status return output
null
null
null
null
Question: For what purpose did the code run a publisher ? Code: def publish_cmdline(reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=1, argv=None, usage=default_usage, description=default_description): pub = Publisher(reader, parser, writer, settings=settings) pub.set_components(reader_name, parser_name, writer_name) output = pub.publish(argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return output
null
null
null
What did the code rename ?
def move(path, dest, replace=False): if samefile(path, dest): return path = syspath(path) dest = syspath(dest) if (os.path.exists(dest) and (not replace)): raise FilesystemError('file exists', 'rename', (path, dest), traceback.format_exc()) try: os.rename(path, dest) except OSError: try: shutil.copyfile(path, dest) os.remove(path) except (OSError, IOError) as exc: raise FilesystemError(exc, 'move', (path, dest), traceback.format_exc())
null
null
null
a file
codeqa
def move path dest replace False if samefile path dest returnpath syspath path dest syspath dest if os path exists dest and not replace raise Filesystem Error 'fileexists' 'rename' path dest traceback format exc try os rename path dest except OS Error try shutil copyfile path dest os remove path except OS Error IO Error as exc raise Filesystem Error exc 'move' path dest traceback format exc
null
null
null
null
Question: What did the code rename ? Code: def move(path, dest, replace=False): if samefile(path, dest): return path = syspath(path) dest = syspath(dest) if (os.path.exists(dest) and (not replace)): raise FilesystemError('file exists', 'rename', (path, dest), traceback.format_exc()) try: os.rename(path, dest) except OSError: try: shutil.copyfile(path, dest) os.remove(path) except (OSError, IOError) as exc: raise FilesystemError(exc, 'move', (path, dest), traceback.format_exc())
null
null
null
What does it upgrade even if it already satisfies the requirements ?
def test_eager_does_upgrade_dependecies_when_currently_satisfied(script): script.pip_install_local('simple==2.0', expect_error=True) result = script.pip_install_local('--upgrade', '--upgrade-strategy=eager', 'require_simple', expect_error=True) assert (((script.site_packages / 'require_simple-1.0-py%s.egg-info') % pyversion) not in result.files_deleted), 'should have installed require_simple==1.0' assert (((script.site_packages / 'simple-2.0-py%s.egg-info') % pyversion) in result.files_deleted), 'should have uninstalled simple==2.0'
null
null
null
a dependency
codeqa
def test eager does upgrade dependecies when currently satisfied script script pip install local 'simple 2 0' expect error True result script pip install local '--upgrade' '--upgrade-strategy eager' 'require simple' expect error True assert script site packages / 'require simple- 1 0-py%s egg-info' % pyversion not in result files deleted 'shouldhaveinstalledrequire simple 1 0'assert script site packages / 'simple- 2 0-py%s egg-info' % pyversion in result files deleted 'shouldhaveuninstalledsimple 2 0'
null
null
null
null
Question: What does it upgrade even if it already satisfies the requirements ? Code: def test_eager_does_upgrade_dependecies_when_currently_satisfied(script): script.pip_install_local('simple==2.0', expect_error=True) result = script.pip_install_local('--upgrade', '--upgrade-strategy=eager', 'require_simple', expect_error=True) assert (((script.site_packages / 'require_simple-1.0-py%s.egg-info') % pyversion) not in result.files_deleted), 'should have installed require_simple==1.0' assert (((script.site_packages / 'simple-2.0-py%s.egg-info') % pyversion) in result.files_deleted), 'should have uninstalled simple==2.0'
null
null
null
How does the code get plugin ?
def get_plugin_by_name(name, issued_by=u'???'): if (name not in plugins): raise DependencyError(issued_by=issued_by, missing=name, message=(u'Unknown plugin %s' % name)) return plugins[name]
null
null
null
by name
codeqa
def get plugin by name name issued by u'???' if name not in plugins raise Dependency Error issued by issued by missing name message u' Unknownplugin%s' % name return plugins[name]
null
null
null
null
Question: How does the code get plugin ? Code: def get_plugin_by_name(name, issued_by=u'???'): if (name not in plugins): raise DependencyError(issued_by=issued_by, missing=name, message=(u'Unknown plugin %s' % name)) return plugins[name]
null
null
null
What does the code return as tuple ?
def _parse_localename(localename): code = normalize(localename) if ('@' in code): (code, modifier) = code.split('@') if ((modifier == 'euro') and ('.' not in code)): return (code, 'iso-8859-15') if ('.' in code): return tuple(code.split('.')[:2]) elif (code == 'C'): return (None, None) raise ValueError, ('unknown locale: %s' % localename)
null
null
null
the result
codeqa
def parse localename localename code normalize localename if '@' in code code modifier code split '@' if modifier 'euro' and ' ' not in code return code 'iso- 8859 - 15 ' if ' ' in code return tuple code split ' ' [ 2] elif code 'C' return None None raise Value Error 'unknownlocale %s' % localename
null
null
null
null
Question: What does the code return as tuple ? Code: def _parse_localename(localename): code = normalize(localename) if ('@' in code): (code, modifier) = code.split('@') if ((modifier == 'euro') and ('.' not in code)): return (code, 'iso-8859-15') if ('.' in code): return tuple(code.split('.')[:2]) elif (code == 'C'): return (None, None) raise ValueError, ('unknown locale: %s' % localename)
null
null
null
For what purpose do mixing matrix return ?
def degree_mixing_matrix(G, x='out', y='in', weight=None, nodes=None, normalized=True): d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight) s = set(d.keys()) for (k, v) in d.items(): s.update(v.keys()) m = max(s) mapping = dict(zip(range((m + 1)), range((m + 1)))) a = dict_to_numpy_array(d, mapping=mapping) if normalized: a = (a / a.sum()) return a
null
null
null
for attribute
codeqa
def degree mixing matrix G x 'out' y 'in' weight None nodes None normalized True d degree mixing dict G x x y y nodes nodes weight weight s set d keys for k v in d items s update v keys m max s mapping dict zip range m + 1 range m + 1 a dict to numpy array d mapping mapping if normalized a a / a sum return a
null
null
null
null
Question: For what purpose do mixing matrix return ? Code: def degree_mixing_matrix(G, x='out', y='in', weight=None, nodes=None, normalized=True): d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight) s = set(d.keys()) for (k, v) in d.items(): s.update(v.keys()) m = max(s) mapping = dict(zip(range((m + 1)), range((m + 1)))) a = dict_to_numpy_array(d, mapping=mapping) if normalized: a = (a / a.sum()) return a
null
null
null
What does the code get from the user ?
def askpassword(title, prompt, **kw): d = apply(_QueryPassword, (title, prompt), kw) return d.result
null
null
null
a password
codeqa
def askpassword title prompt **kw d apply Query Password title prompt kw return d result
null
null
null
null
Question: What does the code get from the user ? Code: def askpassword(title, prompt, **kw): d = apply(_QueryPassword, (title, prompt), kw) return d.result
null
null
null
How does the code detach the current process ?
def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0, workdir=None, **opts): if (not resource): raise RuntimeError('This platform does not support detach.') workdir = (os.getcwd() if (workdir is None) else workdir) signals.reset('SIGCLD') set_effective_user(uid=uid, gid=gid) (logfile and open(logfile, 'a').close()) (pidfile and create_pidlock(pidfile)) return DaemonContext(umask=umask, workdir=workdir)
null
null
null
in the background
codeqa
def detached logfile None pidfile None uid None gid None umask 0 workdir None **opts if not resource raise Runtime Error ' Thisplatformdoesnotsupportdetach ' workdir os getcwd if workdir is None else workdir signals reset 'SIGCLD' set effective user uid uid gid gid logfile and open logfile 'a' close pidfile and create pidlock pidfile return Daemon Context umask umask workdir workdir
null
null
null
null
Question: How does the code detach the current process ? Code: def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0, workdir=None, **opts): if (not resource): raise RuntimeError('This platform does not support detach.') workdir = (os.getcwd() if (workdir is None) else workdir) signals.reset('SIGCLD') set_effective_user(uid=uid, gid=gid) (logfile and open(logfile, 'a').close()) (pidfile and create_pidlock(pidfile)) return DaemonContext(umask=umask, workdir=workdir)
null
null
null
What does the code detach in the background ?
def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0, workdir=None, **opts): if (not resource): raise RuntimeError('This platform does not support detach.') workdir = (os.getcwd() if (workdir is None) else workdir) signals.reset('SIGCLD') set_effective_user(uid=uid, gid=gid) (logfile and open(logfile, 'a').close()) (pidfile and create_pidlock(pidfile)) return DaemonContext(umask=umask, workdir=workdir)
null
null
null
the current process
codeqa
def detached logfile None pidfile None uid None gid None umask 0 workdir None **opts if not resource raise Runtime Error ' Thisplatformdoesnotsupportdetach ' workdir os getcwd if workdir is None else workdir signals reset 'SIGCLD' set effective user uid uid gid gid logfile and open logfile 'a' close pidfile and create pidlock pidfile return Daemon Context umask umask workdir workdir
null
null
null
null
Question: What does the code detach in the background ? Code: def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0, workdir=None, **opts): if (not resource): raise RuntimeError('This platform does not support detach.') workdir = (os.getcwd() if (workdir is None) else workdir) signals.reset('SIGCLD') set_effective_user(uid=uid, gid=gid) (logfile and open(logfile, 'a').close()) (pidfile and create_pidlock(pidfile)) return DaemonContext(umask=umask, workdir=workdir)
null
null
null
What do code block ?
@docstring.copy_dedent(Figure.ginput) def ginput(*args, **kwargs): return gcf().ginput(*args, **kwargs)
null
null
null
call
codeqa
@docstring copy dedent Figure ginput def ginput *args **kwargs return gcf ginput *args **kwargs
null
null
null
null
Question: What do code block ? Code: @docstring.copy_dedent(Figure.ginput) def ginput(*args, **kwargs): return gcf().ginput(*args, **kwargs)
null
null
null
How do current epoch time return ?
def msec_time(): return int((time.time() * 1000.0))
null
null
null
in milliseconds
codeqa
def msec time return int time time * 1000 0
null
null
null
null
Question: How do current epoch time return ? Code: def msec_time(): return int((time.time() * 1000.0))
null
null
null
What does the code modify ?
def modify_profile(hostname, username, password, profile_type, name, **kwargs): ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: params = {'hostname': hostname, 'username': username, 'password': password, 'profile_type': profile_type, 'name': name} for (key, value) in six.iteritems(kwargs): params[key] = value return _test_output(ret, 'modify', params) existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name) if (existing['code'] == 200): modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs) if (modified['code'] == 200): del existing['content']['selfLink'] del modified['content']['selfLink'] ret = _check_for_changes('Profile', ret, existing, modified) else: ret = _load_result(modified, ret) elif (existing['code'] == 404): ret['comment'] = 'A Profile with this name was not found.' else: ret = _load_result(existing, ret) return ret
null
null
null
an existing profile
codeqa
def modify profile hostname username password profile type name **kwargs ret {'name' name 'changes' {} 'result' False 'comment' ''}if opts ['test'] params {'hostname' hostname 'username' username 'password' password 'profile type' profile type 'name' name}for key value in six iteritems kwargs params[key] valuereturn test output ret 'modify' params existing salt ['bigip list profile'] hostname username password profile type name if existing['code'] 200 modified salt ['bigip modify profile'] hostname username password profile type name **kwargs if modified['code'] 200 del existing['content']['self Link']del modified['content']['self Link']ret check for changes ' Profile' ret existing modified else ret load result modified ret elif existing['code'] 404 ret['comment'] 'A Profilewiththisnamewasnotfound 'else ret load result existing ret return ret
null
null
null
null
Question: What does the code modify ? Code: def modify_profile(hostname, username, password, profile_type, name, **kwargs): ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: params = {'hostname': hostname, 'username': username, 'password': password, 'profile_type': profile_type, 'name': name} for (key, value) in six.iteritems(kwargs): params[key] = value return _test_output(ret, 'modify', params) existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name) if (existing['code'] == 200): modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs) if (modified['code'] == 200): del existing['content']['selfLink'] del modified['content']['selfLink'] ret = _check_for_changes('Profile', ret, existing, modified) else: ret = _load_result(modified, ret) elif (existing['code'] == 404): ret['comment'] = 'A Profile with this name was not found.' else: ret = _load_result(existing, ret) return ret
null
null
null
What does the code get ?
def get_models(app_labels): from django.db.models import get_app, get_apps, get_model from django.db.models import get_models as get_all_models EXCLUDED_MODELS = (ContentType,) models = [] if (not app_labels): for app in get_apps(): models += [m for m in get_all_models(app) if (m not in EXCLUDED_MODELS)] return models for app_label in app_labels: if ('.' in app_label): (app_label, model_name) = app_label.split('.', 1) models.append(get_model(app_label, model_name)) else: models += [m for m in get_all_models(get_app(app_label)) if (m not in EXCLUDED_MODELS)] return models
null
null
null
a list of models for the given app labels
codeqa
def get models app labels from django db models import get app get apps get modelfrom django db models import get models as get all models EXCLUDED MODELS Content Type models []if not app labels for app in get apps models + [m for m in get all models app if m not in EXCLUDED MODELS ]return modelsfor app label in app labels if ' ' in app label app label model name app label split ' ' 1 models append get model app label model name else models + [m for m in get all models get app app label if m not in EXCLUDED MODELS ]return models
null
null
null
null
Question: What does the code get ? Code: def get_models(app_labels): from django.db.models import get_app, get_apps, get_model from django.db.models import get_models as get_all_models EXCLUDED_MODELS = (ContentType,) models = [] if (not app_labels): for app in get_apps(): models += [m for m in get_all_models(app) if (m not in EXCLUDED_MODELS)] return models for app_label in app_labels: if ('.' in app_label): (app_label, model_name) = app_label.split('.', 1) models.append(get_model(app_label, model_name)) else: models += [m for m in get_all_models(get_app(app_label)) if (m not in EXCLUDED_MODELS)] return models
null
null
null
What does the code do ?
def modNull(s, titlesRefs, namesRefs, charactersRefs): return s
null
null
null
nothing
codeqa
def mod Null s titles Refs names Refs characters Refs return s
null
null
null
null
Question: What does the code do ? Code: def modNull(s, titlesRefs, namesRefs, charactersRefs): return s
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 craft 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
How do directory and filename join ?
def safe_join(directory, filename): filename = posixpath.normpath(filename) for sep in _os_alt_seps: if (sep in filename): raise NotFound() if (os.path.isabs(filename) or (filename == '..') or filename.startswith('../')): raise NotFound() return os.path.join(directory, filename)
null
null
null
safely
codeqa
def safe join directory filename filename posixpath normpath filename for sep in os alt seps if sep in filename raise Not Found if os path isabs filename or filename ' ' or filename startswith ' /' raise Not Found return os path join directory filename
null
null
null
null
Question: How do directory and filename join ? Code: def safe_join(directory, filename): filename = posixpath.normpath(filename) for sep in _os_alt_seps: if (sep in filename): raise NotFound() if (os.path.isabs(filename) or (filename == '..') or filename.startswith('../')): raise NotFound() return os.path.join(directory, filename)
null
null
null
How does the code traverse a dict ?
def traverse_dict(data, key, default, delimiter=DEFAULT_TARGET_DELIM): try: for each in key.split(delimiter): data = data[each] except (KeyError, IndexError, TypeError): return default return data
null
null
null
using a colon - delimited target string
codeqa
def traverse dict data key default delimiter DEFAULT TARGET DELIM try for each in key split delimiter data data[each]except Key Error Index Error Type Error return defaultreturn data
null
null
null
null
Question: How does the code traverse a dict ? Code: def traverse_dict(data, key, default, delimiter=DEFAULT_TARGET_DELIM): try: for each in key.split(delimiter): data = data[each] except (KeyError, IndexError, TypeError): return default return data
null
null
null
What does the code traverse using a colon - delimited target string ?
def traverse_dict(data, key, default, delimiter=DEFAULT_TARGET_DELIM): try: for each in key.split(delimiter): data = data[each] except (KeyError, IndexError, TypeError): return default return data
null
null
null
a dict
codeqa
def traverse dict data key default delimiter DEFAULT TARGET DELIM try for each in key split delimiter data data[each]except Key Error Index 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(data, key, default, delimiter=DEFAULT_TARGET_DELIM): try: for each in key.split(delimiter): data = data[each] except (KeyError, IndexError, TypeError): return default return data
null
null
null
What did the code set ?
def volume_update_db(context, volume_id, host, cluster_name): volume = objects.Volume.get_by_id(context, volume_id) volume.host = host volume.cluster_name = cluster_name volume.scheduled_at = timeutils.utcnow() volume.save() return volume
null
null
null
the host
codeqa
def volume update db context volume id host cluster name volume objects Volume get by id context volume id volume host hostvolume cluster name cluster namevolume scheduled at timeutils utcnow volume save return volume
null
null
null
null
Question: What did the code set ? Code: def volume_update_db(context, volume_id, host, cluster_name): volume = objects.Volume.get_by_id(context, volume_id) volume.host = host volume.cluster_name = cluster_name volume.scheduled_at = timeutils.utcnow() volume.save() return volume
null
null
null
For what purpose do all id_mappings list ?
def list_id_mappings(): with sql.session_for_read() as session: refs = session.query(mapping_sql.IDMapping).all() return [x.to_dict() for x in refs]
null
null
null
for testing purposes
codeqa
def list id mappings with sql session for read as session refs session query mapping sql ID Mapping all return [x to dict for x in refs]
null
null
null
null
Question: For what purpose do all id_mappings list ? Code: def list_id_mappings(): with sql.session_for_read() as session: refs = session.query(mapping_sql.IDMapping).all() return [x.to_dict() for x in refs]
null
null
null
When did tags allow ?
def _sanitize_html(source): return TAG_PATTERN.sub(_sanitize_tag, source)
null
null
null
non
codeqa
def sanitize html source return TAG PATTERN sub sanitize tag source
null
null
null
null
Question: When did tags allow ? Code: def _sanitize_html(source): return TAG_PATTERN.sub(_sanitize_tag, source)
null
null
null
What does this string have in it ?
def isMultiline(s): return (s.find('\n') != (-1))
null
null
null
a newline
codeqa
def is Multiline s return s find '\n' -1
null
null
null
null
Question: What does this string have in it ? Code: def isMultiline(s): return (s.find('\n') != (-1))
null
null
null
What has a newline in it ?
def isMultiline(s): return (s.find('\n') != (-1))
null
null
null
this string
codeqa
def is Multiline s return s find '\n' -1
null
null
null
null
Question: What has a newline in it ? Code: def isMultiline(s): return (s.find('\n') != (-1))
null
null
null
Where does this string have a newline ?
def isMultiline(s): return (s.find('\n') != (-1))
null
null
null
in it
codeqa
def is Multiline s return s find '\n' -1
null
null
null
null
Question: Where does this string have a newline ? Code: def isMultiline(s): return (s.find('\n') != (-1))
null
null
null
For what purpose do a simple config build ?
def load_config(cfg=None): cfg = (cfg or {}) if (u'site_name' not in cfg): cfg[u'site_name'] = u'Example' if (u'config_file_path' not in cfg): cfg[u'config_file_path'] = os.path.join(os.path.abspath(u'.'), u'mkdocs.yml') if (u'extra_css' not in cfg): cfg[u'extra_css'] = [u'css/extra.css'] conf = config.Config(schema=config.DEFAULT_SCHEMA) conf.load_dict(cfg) errors_warnings = conf.validate() assert (errors_warnings == ([], [])), errors_warnings return conf
null
null
null
for testing
codeqa
def load config cfg None cfg cfg or {} if u'site name' not in cfg cfg[u'site name'] u' Example'if u'config file path' not in cfg cfg[u'config file path'] os path join os path abspath u' ' u'mkdocs yml' if u'extra css' not in cfg cfg[u'extra css'] [u'css/extra css']conf config Config schema config DEFAULT SCHEMA conf load dict cfg errors warnings conf validate assert errors warnings [] [] errors warningsreturn conf
null
null
null
null
Question: For what purpose do a simple config build ? Code: def load_config(cfg=None): cfg = (cfg or {}) if (u'site_name' not in cfg): cfg[u'site_name'] = u'Example' if (u'config_file_path' not in cfg): cfg[u'config_file_path'] = os.path.join(os.path.abspath(u'.'), u'mkdocs.yml') if (u'extra_css' not in cfg): cfg[u'extra_css'] = [u'css/extra.css'] conf = config.Config(schema=config.DEFAULT_SCHEMA) conf.load_dict(cfg) errors_warnings = conf.validate() assert (errors_warnings == ([], [])), errors_warnings return conf
null
null
null
What does the code get ?
def getCraftSequence(): return 'carve scale bottom preface widen inset fill multiply temperature raft skirt speed chamber tower jitter clip smooth stretch skin comb cool hop wipe oozebane dwindle splodge home lash fillet limit unpause dimension alteration export'.split()
null
null
null
the extrusion craft sequence
codeqa
def get Craft Sequence return 'carvescalebottomprefacewideninsetfillmultiplytemperatureraftskirtspeedchambertowerjitterclipsmoothstretchskincombcoolhopwipeoozebanedwindlesplodgehomelashfilletlimitunpausedimensionalterationexport' split
null
null
null
null
Question: What does the code get ? Code: def getCraftSequence(): return 'carve scale bottom preface widen inset fill multiply temperature raft skirt speed chamber tower jitter clip smooth stretch skin comb cool hop wipe oozebane dwindle splodge home lash fillet limit unpause dimension alteration export'.split()
null
null
null
What does the code get ?
def get_subscription(document_class, sub_id, topic=None): subscriptions = list_subscriptions(document_class, sub_id, topic=topic, max_results=1) if (len(subscriptions) and (subscriptions[0][0] == sub_id)): return subscriptions[0] raise SubscriptionDoesNotExist(topic, sub_id)
null
null
null
subscription information
codeqa
def get subscription document class sub id topic None subscriptions list subscriptions document class sub id topic topic max results 1 if len subscriptions and subscriptions[ 0 ][ 0 ] sub id return subscriptions[ 0 ]raise Subscription Does Not Exist topic sub id
null
null
null
null
Question: What does the code get ? Code: def get_subscription(document_class, sub_id, topic=None): subscriptions = list_subscriptions(document_class, sub_id, topic=topic, max_results=1) if (len(subscriptions) and (subscriptions[0][0] == sub_id)): return subscriptions[0] raise SubscriptionDoesNotExist(topic, sub_id)
null
null
null
How do email opt ?
def opt_in(msg_hash): (email, removed) = Email.handler.opt_in(msg_hash) if (email and removed): _system_email(email, '', Email.Kind.OPTIN) return (email, removed)
null
null
null
in
codeqa
def opt in msg hash email removed Email handler opt in msg hash if email and removed system email email '' Email Kind OPTIN return email removed
null
null
null
null
Question: How do email opt ? Code: def opt_in(msg_hash): (email, removed) = Email.handler.opt_in(msg_hash) if (email and removed): _system_email(email, '', Email.Kind.OPTIN) return (email, removed)
null
null
null
What does the code get ?
def equate(point, returnValue): point.setToVector3(evaluate.getVector3ByDictionaryListValue(returnValue, point))
null
null
null
equation for rectangular
codeqa
def equate point return Value point set To Vector 3 evaluate get Vector 3 By Dictionary List Value return Value point
null
null
null
null
Question: What does the code get ? Code: def equate(point, returnValue): point.setToVector3(evaluate.getVector3ByDictionaryListValue(returnValue, point))
null
null
null
What does the code make ?
def make_path_relative(path, rel_to): path_filename = os.path.basename(path) path = os.path.dirname(path) path = os.path.normpath(os.path.abspath(path)) rel_to = os.path.normpath(os.path.abspath(rel_to)) path_parts = path.strip(os.path.sep).split(os.path.sep) rel_to_parts = rel_to.strip(os.path.sep).split(os.path.sep) while (path_parts and rel_to_parts and (path_parts[0] == rel_to_parts[0])): path_parts.pop(0) rel_to_parts.pop(0) full_parts = (((['..'] * len(rel_to_parts)) + path_parts) + [path_filename]) if (full_parts == ['']): return ('.' + os.path.sep) return os.path.sep.join(full_parts)
null
null
null
a filename relative
codeqa
def make path relative path rel to path filename os path basename path path os path dirname path path os path normpath os path abspath path rel to os path normpath os path abspath rel to path parts path strip os path sep split os path sep rel to parts rel to strip os path sep split os path sep while path parts and rel to parts and path parts[ 0 ] rel to parts[ 0 ] path parts pop 0 rel to parts pop 0 full parts [' '] * len rel to parts + path parts + [path filename] if full parts [''] return ' ' + os path sep return os path sep join full parts
null
null
null
null
Question: What does the code make ? Code: def make_path_relative(path, rel_to): path_filename = os.path.basename(path) path = os.path.dirname(path) path = os.path.normpath(os.path.abspath(path)) rel_to = os.path.normpath(os.path.abspath(rel_to)) path_parts = path.strip(os.path.sep).split(os.path.sep) rel_to_parts = rel_to.strip(os.path.sep).split(os.path.sep) while (path_parts and rel_to_parts and (path_parts[0] == rel_to_parts[0])): path_parts.pop(0) rel_to_parts.pop(0) full_parts = (((['..'] * len(rel_to_parts)) + path_parts) + [path_filename]) if (full_parts == ['']): return ('.' + os.path.sep) return os.path.sep.join(full_parts)
null
null
null
When does that test ?
def test_record_bad(): output = StringIO() recorder = Record(file_object=output, replay=False) num_lines = 10 for i in xrange(num_lines): recorder.handle_line((str(i) + '\n')) output_value = output.getvalue() output = StringIO(output_value) playback_checker = Record(file_object=output, replay=True) for i in xrange((num_lines // 2)): playback_checker.handle_line((str(i) + '\n')) try: playback_checker.handle_line('0\n') except MismatchError: return raise AssertionError('Failed to detect mismatch between recorded sequence and repetition of it.')
null
null
null
when we record a sequence of events
codeqa
def test record bad output String IO recorder Record file object output replay False num lines 10 for i in xrange num lines recorder handle line str i + '\n' output value output getvalue output String IO output value playback checker Record file object output replay True for i in xrange num lines // 2 playback checker handle line str i + '\n' try playback checker handle line '0 \n' except Mismatch Error returnraise Assertion Error ' Failedtodetectmismatchbetweenrecordedsequenceandrepetitionofit '
null
null
null
null
Question: When does that test ? Code: def test_record_bad(): output = StringIO() recorder = Record(file_object=output, replay=False) num_lines = 10 for i in xrange(num_lines): recorder.handle_line((str(i) + '\n')) output_value = output.getvalue() output = StringIO(output_value) playback_checker = Record(file_object=output, replay=True) for i in xrange((num_lines // 2)): playback_checker.handle_line((str(i) + '\n')) try: playback_checker.handle_line('0\n') except MismatchError: return raise AssertionError('Failed to detect mismatch between recorded sequence and repetition of it.')
null
null
null
Where does this function live ?
def function(): return 0
null
null
null
at the module level
codeqa
def function return 0
null
null
null
null
Question: Where does this function live ? Code: def function(): return 0
null
null
null
What does a user belong ?
def chgroups(name, groups, append=False): if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if (ugrps == set(groups)): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return (__salt__['cmd.retcode'](cmd, python_shell=False) == 0)
null
null
null
name username
codeqa
def chgroups name groups append False if isinstance groups six string types groups groups split ' ' ugrps set list groups name if ugrps set groups return Trueif append groups + ugrpscmd ['pw' 'usermod' '-G' ' ' join groups '-n' name]return salt ['cmd retcode'] cmd python shell False 0
null
null
null
null
Question: What does a user belong ? Code: def chgroups(name, groups, append=False): if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if (ugrps == set(groups)): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return (__salt__['cmd.retcode'](cmd, python_shell=False) == 0)
null
null
null
What belongs name username ?
def chgroups(name, groups, append=False): if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if (ugrps == set(groups)): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return (__salt__['cmd.retcode'](cmd, python_shell=False) == 0)
null
null
null
a user
codeqa
def chgroups name groups append False if isinstance groups six string types groups groups split ' ' ugrps set list groups name if ugrps set groups return Trueif append groups + ugrpscmd ['pw' 'usermod' '-G' ' ' join groups '-n' name]return salt ['cmd retcode'] cmd python shell False 0
null
null
null
null
Question: What belongs name username ? Code: def chgroups(name, groups, append=False): if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if (ugrps == set(groups)): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return (__salt__['cmd.retcode'](cmd, python_shell=False) == 0)
null
null
null
How do localization check ?
def nova_not_in(logical_line): split_line = logical_line.split() if ((len(split_line) == 5) and (split_line[0] == 'if') and (split_line[1] == 'not') and (split_line[3] == 'in') and (not split_line[2].startswith('('))): (yield (logical_line.find('not'), "N902: Use the 'not in' operator for collection membership evaluation"))
null
null
null
in line
codeqa
def nova not in logical line split line logical line split if len split line 5 and split line[ 0 ] 'if' and split line[ 1 ] 'not' and split line[ 3 ] 'in' and not split line[ 2 ] startswith ' ' yield logical line find 'not' "N 902 Usethe'notin'operatorforcollectionmembershipevaluation"
null
null
null
null
Question: How do localization check ? Code: def nova_not_in(logical_line): split_line = logical_line.split() if ((len(split_line) == 5) and (split_line[0] == 'if') and (split_line[1] == 'not') and (split_line[3] == 'in') and (not split_line[2].startswith('('))): (yield (logical_line.find('not'), "N902: Use the 'not in' operator for collection membership evaluation"))
null
null
null
What did the code set to the string ?
def setIntegerValueToString(integerSetting, valueString): dotIndex = valueString.find('.') if (dotIndex > (-1)): valueString = valueString[:dotIndex] try: integerSetting.value = int(valueString) return except: print ((('Warning, can not read integer ' + integerSetting.name) + ' ') + valueString) print 'Will try reading as a boolean, which might be a mistake.' integerSetting.value = 0 if (valueString.lower() == 'true'): integerSetting.value = 1
null
null
null
the integer
codeqa
def set Integer Value To String integer Setting value String dot Index value String find ' ' if dot Index > -1 value String value String[ dot Index]try integer Setting value int value String returnexcept print ' Warning cannotreadinteger' + integer Setting name + '' + value String print ' Willtryreadingasaboolean whichmightbeamistake 'integer Setting value 0if value String lower 'true' integer Setting value 1
null
null
null
null
Question: What did the code set to the string ? Code: def setIntegerValueToString(integerSetting, valueString): dotIndex = valueString.find('.') if (dotIndex > (-1)): valueString = valueString[:dotIndex] try: integerSetting.value = int(valueString) return except: print ((('Warning, can not read integer ' + integerSetting.name) + ' ') + valueString) print 'Will try reading as a boolean, which might be a mistake.' integerSetting.value = 0 if (valueString.lower() == 'true'): integerSetting.value = 1
null
null
null
How do still everything work ?
def myTakeStep2(x): s = 0.5 x += np.random.uniform((- s), s, np.shape(x)) return x
null
null
null
ok
codeqa
def my Take Step 2 x s 0 5x + np random uniform - s s np shape x return x
null
null
null
null
Question: How do still everything work ? Code: def myTakeStep2(x): s = 0.5 x += np.random.uniform((- s), s, np.shape(x)) return x
null
null
null
What should the attribute name be used ?
def name_for_collection_relationship(base, local_cls, referred_cls, constraint): return (referred_cls.__name__.lower() + '_collection')
null
null
null
to refer from one class to another
codeqa
def name for collection relationship base local cls referred cls constraint return referred cls name lower + ' collection'
null
null
null
null
Question: What should the attribute name be used ? Code: def name_for_collection_relationship(base, local_cls, referred_cls, constraint): return (referred_cls.__name__.lower() + '_collection')
null
null
null
What should be used to refer from one class to another ?
def name_for_collection_relationship(base, local_cls, referred_cls, constraint): return (referred_cls.__name__.lower() + '_collection')
null
null
null
the attribute name
codeqa
def name for collection relationship base local cls referred cls constraint return referred cls name lower + ' collection'
null
null
null
null
Question: What should be used to refer from one class to another ? Code: def name_for_collection_relationship(base, local_cls, referred_cls, constraint): return (referred_cls.__name__.lower() + '_collection')
null
null
null
How is a view requested ?
def raw_post_data(request): return HttpResponse(request.raw_post_data)
null
null
null
with get and accesses request
codeqa
def raw post data request return Http Response request raw post data
null
null
null
null
Question: How is a view requested ? Code: def raw_post_data(request): return HttpResponse(request.raw_post_data)
null
null
null
What does the code exemplify ?
def demo_str_rule_format(): postag(ruleformat='str')
null
null
null
repr
codeqa
def demo str rule format postag ruleformat 'str'
null
null
null
null
Question: What does the code exemplify ? Code: def demo_str_rule_format(): postag(ruleformat='str')
null
null
null
What does the code compute ?
def average(values): return ((sum(values) / len(values)) if values else None)
null
null
null
the arithmetic mean of a list of numbers
codeqa
def average values return sum values / len values if values else None
null
null
null
null
Question: What does the code compute ? Code: def average(values): return ((sum(values) / len(values)) if values else None)
null
null
null
What does the code get ?
def getEvaluatedIntDefault(defaultInt, key, xmlElement=None): evaluatedInt = getEvaluatedInt(key, xmlElement) if (evaluatedInt == None): return defaultInt return evaluatedInt
null
null
null
the evaluated value as an int
codeqa
def get Evaluated Int Default default Int key xml Element None evaluated Int get Evaluated Int key xml Element if evaluated Int None return default Intreturn evaluated Int
null
null
null
null
Question: What does the code get ? Code: def getEvaluatedIntDefault(defaultInt, key, xmlElement=None): evaluatedInt = getEvaluatedInt(key, xmlElement) if (evaluatedInt == None): return defaultInt return evaluatedInt
null
null
null
What does the code initiate ?
def refresh(): if _TRAFFICCTL: cmd = _traffic_ctl('config', 'reload') else: cmd = _traffic_line('-x') log.debug('Running: %s', cmd) return _subprocess(cmd)
null
null
null
a traffic server configuration file reread
codeqa
def refresh if TRAFFICCTL cmd traffic ctl 'config' 'reload' else cmd traffic line '-x' log debug ' Running %s' cmd return subprocess cmd
null
null
null
null
Question: What does the code initiate ? Code: def refresh(): if _TRAFFICCTL: cmd = _traffic_ctl('config', 'reload') else: cmd = _traffic_line('-x') log.debug('Running: %s', cmd) return _subprocess(cmd)
null
null
null
What do point correspondences use ?
def F_from_ransac(x1, x2, model, maxiter=5000, match_theshold=1e-06): from PCV.tools import ransac data = vstack((x1, x2)) (F, ransac_data) = ransac.ransac(data.T, model, 8, maxiter, match_theshold, 20, return_all=True) return (F, ransac_data['inliers'])
null
null
null
ransac
codeqa
def F from ransac x1 x2 model maxiter 5000 match theshold 1e- 06 from PCV tools import ransacdata vstack x1 x2 F ransac data ransac ransac data T model 8 maxiter match theshold 20 return all True return F ransac data['inliers']
null
null
null
null
Question: What do point correspondences use ? Code: def F_from_ransac(x1, x2, model, maxiter=5000, match_theshold=1e-06): from PCV.tools import ransac data = vstack((x1, x2)) (F, ransac_data) = ransac.ransac(data.T, model, 8, maxiter, match_theshold, 20, return_all=True) return (F, ransac_data['inliers'])
null
null
null
What does the code create ?
def task_create(context, values, session=None): values = values.copy() session = (session or get_session()) with session.begin(): task_info_values = _pop_task_info_values(values) task_ref = models.Task() _task_update(context, task_ref, values, session=session) _task_info_create(context, task_ref.id, task_info_values, session=session) return task_get(context, task_ref.id, session)
null
null
null
a task object
codeqa
def task create context values session None values values copy session session or get session with session begin task info values pop task info values values task ref models Task task update context task ref values session session task info create context task ref id task info values session session return task get context task ref id session
null
null
null
null
Question: What does the code create ? Code: def task_create(context, values, session=None): values = values.copy() session = (session or get_session()) with session.begin(): task_info_values = _pop_task_info_values(values) task_ref = models.Task() _task_update(context, task_ref, values, session=session) _task_info_create(context, task_ref.id, task_info_values, session=session) return task_get(context, task_ref.id, session)
null
null
null
What does a check test ?
def is_float(value, min=None, max=None): (min_val, max_val) = _is_num_param(('min', 'max'), (min, max), to_float=True) if (not isinstance(value, (int, long, float, string_type))): raise VdtTypeError(value) if (not isinstance(value, float)): try: value = float(value) except ValueError: raise VdtTypeError(value) if ((min_val is not None) and (value < min_val)): raise VdtValueTooSmallError(value) if ((max_val is not None) and (value > max_val)): raise VdtValueTooBigError(value) return value
null
null
null
that a given value
codeqa
def is float value min None max None min val max val is num param 'min' 'max' min max to float True if not isinstance value int long float string type raise Vdt Type Error value if not isinstance value float try value float value except Value Error raise Vdt Type Error value if min val is not None and value < min val raise Vdt Value Too Small Error value if max val is not None and value > max val raise Vdt Value Too Big Error value return value
null
null
null
null
Question: What does a check test ? Code: def is_float(value, min=None, max=None): (min_val, max_val) = _is_num_param(('min', 'max'), (min, max), to_float=True) if (not isinstance(value, (int, long, float, string_type))): raise VdtTypeError(value) if (not isinstance(value, float)): try: value = float(value) except ValueError: raise VdtTypeError(value) if ((min_val is not None) and (value < min_val)): raise VdtValueTooSmallError(value) if ((max_val is not None) and (value > max_val)): raise VdtValueTooBigError(value) return value
null
null
null
What tests that a given value ?
def is_float(value, min=None, max=None): (min_val, max_val) = _is_num_param(('min', 'max'), (min, max), to_float=True) if (not isinstance(value, (int, long, float, string_type))): raise VdtTypeError(value) if (not isinstance(value, float)): try: value = float(value) except ValueError: raise VdtTypeError(value) if ((min_val is not None) and (value < min_val)): raise VdtValueTooSmallError(value) if ((max_val is not None) and (value > max_val)): raise VdtValueTooBigError(value) return value
null
null
null
a check
codeqa
def is float value min None max None min val max val is num param 'min' 'max' min max to float True if not isinstance value int long float string type raise Vdt Type Error value if not isinstance value float try value float value except Value Error raise Vdt Type Error value if min val is not None and value < min val raise Vdt Value Too Small Error value if max val is not None and value > max val raise Vdt Value Too Big Error value return value
null
null
null
null
Question: What tests that a given value ? Code: def is_float(value, min=None, max=None): (min_val, max_val) = _is_num_param(('min', 'max'), (min, max), to_float=True) if (not isinstance(value, (int, long, float, string_type))): raise VdtTypeError(value) if (not isinstance(value, float)): try: value = float(value) except ValueError: raise VdtTypeError(value) if ((min_val is not None) and (value < min_val)): raise VdtValueTooSmallError(value) if ((max_val is not None) and (value > max_val)): raise VdtValueTooBigError(value) return value
null
null
null
What does the code get ?
def getToothProfileCylinder(derivation, pitchRadius, teeth): toothProfileHalfCylinder = getToothProfileHalfCylinder(derivation, pitchRadius) toothProfileHalfCylinder = getThicknessMultipliedPath(toothProfileHalfCylinder, derivation.toothThicknessMultiplier) toothProfileHalf = [] innerRadius = (pitchRadius - derivation.dedendum) for point in toothProfileHalfCylinder: if (abs(point) >= innerRadius): toothProfileHalf.append(point) return getToothProfileCylinderByProfile(derivation, pitchRadius, teeth, toothProfileHalf)
null
null
null
profile for one tooth of a cylindrical gear
codeqa
def get Tooth Profile Cylinder derivation pitch Radius teeth tooth Profile Half Cylinder get Tooth Profile Half Cylinder derivation pitch Radius tooth Profile Half Cylinder get Thickness Multiplied Path tooth Profile Half Cylinder derivation tooth Thickness Multiplier tooth Profile Half []inner Radius pitch Radius - derivation dedendum for point in tooth Profile Half Cylinder if abs point > inner Radius tooth Profile Half append point return get Tooth Profile Cylinder By Profile derivation pitch Radius teeth tooth Profile Half
null
null
null
null
Question: What does the code get ? Code: def getToothProfileCylinder(derivation, pitchRadius, teeth): toothProfileHalfCylinder = getToothProfileHalfCylinder(derivation, pitchRadius) toothProfileHalfCylinder = getThicknessMultipliedPath(toothProfileHalfCylinder, derivation.toothThicknessMultiplier) toothProfileHalf = [] innerRadius = (pitchRadius - derivation.dedendum) for point in toothProfileHalfCylinder: if (abs(point) >= innerRadius): toothProfileHalf.append(point) return getToothProfileCylinderByProfile(derivation, pitchRadius, teeth, toothProfileHalf)
null
null
null
What does the code add to the exit survey campaign ?
def add_email_to_campaign(survey, email): token = settings.SURVEYGIZMO_API_TOKEN secret = settings.SURVEYGIZMO_API_TOKEN_SECRET if ((token is None) or (secret is None)): return survey_id = SURVEYS[survey]['exit_survey_id'] campaign_id = SURVEYS[survey]['exit_survey_campaign_id'] try: requests.put('https://restapi.surveygizmo.com/v2/survey/{survey}/surveycampaign/{campaign}/contact?semailaddress={email}&api_token={token}&api_token_secret={secret}'.format(survey=survey_id, campaign=campaign_id, email=email, token=token, secret=secret), timeout=30) except requests.exceptions.Timeout: print ('Timedout adding: %s' % email)
null
null
null
email
codeqa
def add email to campaign survey email token settings SURVEYGIZMO API TOKE Nsecret settings SURVEYGIZMO API TOKEN SECRE Tif token is None or secret is None returnsurvey id SURVEYS[survey]['exit survey id']campaign id SURVEYS[survey]['exit survey campaign id']try requests put 'https //restapi surveygizmo com/v 2 /survey/{survey}/surveycampaign/{campaign}/contact?semailaddress {email}&api token {token}&api token secret {secret}' format survey survey id campaign campaign id email email token token secret secret timeout 30 except requests exceptions Timeout print ' Timedoutadding %s' % email
null
null
null
null
Question: What does the code add to the exit survey campaign ? Code: def add_email_to_campaign(survey, email): token = settings.SURVEYGIZMO_API_TOKEN secret = settings.SURVEYGIZMO_API_TOKEN_SECRET if ((token is None) or (secret is None)): return survey_id = SURVEYS[survey]['exit_survey_id'] campaign_id = SURVEYS[survey]['exit_survey_campaign_id'] try: requests.put('https://restapi.surveygizmo.com/v2/survey/{survey}/surveycampaign/{campaign}/contact?semailaddress={email}&api_token={token}&api_token_secret={secret}'.format(survey=survey_id, campaign=campaign_id, email=email, token=token, secret=secret), timeout=30) except requests.exceptions.Timeout: print ('Timedout adding: %s' % email)
null
null
null
What does the code serialize ?
def serialize(model, callbacks=None, datasets=None, dump_weights=True, keep_states=True): pdict = model.serialize(fn=None, keep_states=keep_states) if (callbacks is not None): pdict['callbacks'] = callbacks.serialize() if (datasets is not None): pdict['datasets'] = datasets.serialize() return pdict
null
null
null
the model
codeqa
def serialize model callbacks None datasets None dump weights True keep states True pdict model serialize fn None keep states keep states if callbacks is not None pdict['callbacks'] callbacks serialize if datasets is not None pdict['datasets'] datasets serialize return pdict
null
null
null
null
Question: What does the code serialize ? Code: def serialize(model, callbacks=None, datasets=None, dump_weights=True, keep_states=True): pdict = model.serialize(fn=None, keep_states=keep_states) if (callbacks is not None): pdict['callbacks'] = callbacks.serialize() if (datasets is not None): pdict['datasets'] = datasets.serialize() return pdict
null
null
null
What is containing all entries stored in the specified bank ?
def list_(bank, cachedir): base = os.path.join(cachedir, os.path.normpath(bank)) if (not os.path.isdir(base)): return [] try: return os.listdir(base) except OSError as exc: raise SaltCacheError('There was an error accessing directory "{0}": {1}'.format(base, exc))
null
null
null
an iterable object
codeqa
def list bank cachedir base os path join cachedir os path normpath bank if not os path isdir base return []try return os listdir base except OS Error as exc raise Salt Cache Error ' Therewasanerroraccessingdirectory"{ 0 }" {1 }' format base exc
null
null
null
null
Question: What is containing all entries stored in the specified bank ? Code: def list_(bank, cachedir): base = os.path.join(cachedir, os.path.normpath(bank)) if (not os.path.isdir(base)): return [] try: return os.listdir(base) except OSError as exc: raise SaltCacheError('There was an error accessing directory "{0}": {1}'.format(base, exc))
null
null
null
What stored in the specified bank ?
def list_(bank, cachedir): base = os.path.join(cachedir, os.path.normpath(bank)) if (not os.path.isdir(base)): return [] try: return os.listdir(base) except OSError as exc: raise SaltCacheError('There was an error accessing directory "{0}": {1}'.format(base, exc))
null
null
null
all entries
codeqa
def list bank cachedir base os path join cachedir os path normpath bank if not os path isdir base return []try return os listdir base except OS Error as exc raise Salt Cache Error ' Therewasanerroraccessingdirectory"{ 0 }" {1 }' format base exc
null
null
null
null
Question: What stored in the specified bank ? Code: def list_(bank, cachedir): base = os.path.join(cachedir, os.path.normpath(bank)) if (not os.path.isdir(base)): return [] try: return os.listdir(base) except OSError as exc: raise SaltCacheError('There was an error accessing directory "{0}": {1}'.format(base, exc))
null
null
null
Where did all entries store ?
def list_(bank, cachedir): base = os.path.join(cachedir, os.path.normpath(bank)) if (not os.path.isdir(base)): return [] try: return os.listdir(base) except OSError as exc: raise SaltCacheError('There was an error accessing directory "{0}": {1}'.format(base, exc))
null
null
null
in the specified bank
codeqa
def list bank cachedir base os path join cachedir os path normpath bank if not os path isdir base return []try return os listdir base except OS Error as exc raise Salt Cache Error ' Therewasanerroraccessingdirectory"{ 0 }" {1 }' format base exc
null
null
null
null
Question: Where did all entries store ? Code: def list_(bank, cachedir): base = os.path.join(cachedir, os.path.normpath(bank)) if (not os.path.isdir(base)): return [] try: return os.listdir(base) except OSError as exc: raise SaltCacheError('There was an error accessing directory "{0}": {1}'.format(base, exc))
null
null
null
What do an iterable object contain ?
def list_(bank, cachedir): base = os.path.join(cachedir, os.path.normpath(bank)) if (not os.path.isdir(base)): return [] try: return os.listdir(base) except OSError as exc: raise SaltCacheError('There was an error accessing directory "{0}": {1}'.format(base, exc))
null
null
null
all entries stored in the specified bank
codeqa
def list bank cachedir base os path join cachedir os path normpath bank if not os path isdir base return []try return os listdir base except OS Error as exc raise Salt Cache Error ' Therewasanerroraccessingdirectory"{ 0 }" {1 }' format base exc
null
null
null
null
Question: What do an iterable object contain ? Code: def list_(bank, cachedir): base = os.path.join(cachedir, os.path.normpath(bank)) if (not os.path.isdir(base)): return [] try: return os.listdir(base) except OSError as exc: raise SaltCacheError('There was an error accessing directory "{0}": {1}'.format(base, exc))
null
null
null
How do a slice of items return ?
def limited(items, request, max_limit=FLAGS.osapi_max_limit): try: offset = int(request.GET.get('offset', 0)) except ValueError: msg = _('offset param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) try: limit = int(request.GET.get('limit', max_limit)) except ValueError: msg = _('limit param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) if (limit < 0): msg = _('limit param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) if (offset < 0): msg = _('offset param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) limit = min(max_limit, (limit or max_limit)) range_end = (offset + limit) return items[offset:range_end]
null
null
null
according to requested offset and limit
codeqa
def limited items request max limit FLAGS osapi max limit try offset int request GET get 'offset' 0 except Value Error msg 'offsetparammustbeaninteger' raise webob exc HTTP Bad Request explanation msg try limit int request GET get 'limit' max limit except Value Error msg 'limitparammustbeaninteger' raise webob exc HTTP Bad Request explanation msg if limit < 0 msg 'limitparammustbepositive' raise webob exc HTTP Bad Request explanation msg if offset < 0 msg 'offsetparammustbepositive' raise webob exc HTTP Bad Request explanation msg limit min max limit limit or max limit range end offset + limit return items[offset range end]
null
null
null
null
Question: How do a slice of items return ? Code: def limited(items, request, max_limit=FLAGS.osapi_max_limit): try: offset = int(request.GET.get('offset', 0)) except ValueError: msg = _('offset param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) try: limit = int(request.GET.get('limit', max_limit)) except ValueError: msg = _('limit param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) if (limit < 0): msg = _('limit param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) if (offset < 0): msg = _('offset param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) limit = min(max_limit, (limit or max_limit)) range_end = (offset + limit) return items[offset:range_end]
null
null
null
When do bundle path ca ?
def find_ca_bundle(): if (os.name == 'nt'): return get_win_certfile() else: for cert_path in cert_paths: if os.path.isfile(cert_path): return cert_path try: return pkg_resources.resource_filename('certifi', 'cacert.pem') except (ImportError, ResolutionError, ExtractionError): return None
null
null
null
existing
codeqa
def find ca bundle if os name 'nt' return get win certfile else for cert path in cert paths if os path isfile cert path return cert pathtry return pkg resources resource filename 'certifi' 'cacert pem' except Import Error Resolution Error Extraction Error return None
null
null
null
null
Question: When do bundle path ca ? Code: def find_ca_bundle(): if (os.name == 'nt'): return get_win_certfile() else: for cert_path in cert_paths: if os.path.isfile(cert_path): return cert_path try: return pkg_resources.resource_filename('certifi', 'cacert.pem') except (ImportError, ResolutionError, ExtractionError): return None
null
null
null
When ca path bundle ?
def find_ca_bundle(): if (os.name == 'nt'): return get_win_certfile() else: for cert_path in cert_paths: if os.path.isfile(cert_path): return cert_path try: return pkg_resources.resource_filename('certifi', 'cacert.pem') except (ImportError, ResolutionError, ExtractionError): return None
null
null
null
existing
codeqa
def find ca bundle if os name 'nt' return get win certfile else for cert path in cert paths if os path isfile cert path return cert pathtry return pkg resources resource filename 'certifi' 'cacert pem' except Import Error Resolution Error Extraction Error return None
null
null
null
null
Question: When ca path bundle ? Code: def find_ca_bundle(): if (os.name == 'nt'): return get_win_certfile() else: for cert_path in cert_paths: if os.path.isfile(cert_path): return cert_path try: return pkg_resources.resource_filename('certifi', 'cacert.pem') except (ImportError, ResolutionError, ExtractionError): return None
null
null
null
What is indicating abstract methods ?
def abstractmethod(funcobj): funcobj.__isabstractmethod__ = True return funcobj
null
null
null
a decorator
codeqa
def abstractmethod funcobj funcobj isabstractmethod Truereturn funcobj
null
null
null
null
Question: What is indicating abstract methods ? Code: def abstractmethod(funcobj): funcobj.__isabstractmethod__ = True return funcobj
null
null
null
What does the code install ?
def setup(app): app.add_config_value('cache_path', '_cache', '') try: os.makedirs(app.config.cache_path) except OSError as error: if (error.errno != errno.EEXIST): raise path = os.path.join(app.config.cache_path, 'spec.html') spec = fetch_or_load(path) app.add_role('validator', docutils_sucks(spec))
null
null
null
the plugin
codeqa
def setup app app add config value 'cache path' ' cache' '' try os makedirs app config cache path except OS Error as error if error errno errno EEXIST raisepath os path join app config cache path 'spec html' spec fetch or load path app add role 'validator' docutils sucks spec
null
null
null
null
Question: What does the code install ? Code: def setup(app): app.add_config_value('cache_path', '_cache', '') try: os.makedirs(app.config.cache_path) except OSError as error: if (error.errno != errno.EEXIST): raise path = os.path.join(app.config.cache_path, 'spec.html') spec = fetch_or_load(path) app.add_role('validator', docutils_sucks(spec))
null
null
null
What does the code find by instance name ?
def FindPerformanceAttributesByName(instanceName, object=None, counter=None, format=win32pdh.PDH_FMT_LONG, machine=None, bRefresh=0): if (object is None): object = find_pdh_counter_localized_name('Process', machine) if (counter is None): counter = find_pdh_counter_localized_name('ID Process', machine) if bRefresh: win32pdh.EnumObjects(None, machine, 0, 1) instanceName = string.lower(instanceName) (items, instances) = win32pdh.EnumObjectItems(None, None, object, (-1)) instance_dict = {} for instance in instances: try: instance_dict[instance] = (instance_dict[instance] + 1) except KeyError: instance_dict[instance] = 0 ret = [] for (instance, max_instances) in instance_dict.items(): for inum in xrange((max_instances + 1)): if (string.lower(instance) == instanceName): ret.append(GetPerformanceAttributes(object, counter, instance, inum, format, machine)) return ret
null
null
null
peformance attributes
codeqa
def Find Performance Attributes By Name instance Name object None counter None format win 32 pdh PDH FMT LONG machine None b Refresh 0 if object is None object find pdh counter localized name ' Process' machine if counter is None counter find pdh counter localized name 'ID Process' machine if b Refresh win 32 pdh Enum Objects None machine 0 1 instance Name string lower instance Name items instances win 32 pdh Enum Object Items None None object -1 instance dict {}for instance in instances try instance dict[instance] instance dict[instance] + 1 except Key Error instance dict[instance] 0ret []for instance max instances in instance dict items for inum in xrange max instances + 1 if string lower instance instance Name ret append Get Performance Attributes object counter instance inum format machine return ret
null
null
null
null
Question: What does the code find by instance name ? Code: def FindPerformanceAttributesByName(instanceName, object=None, counter=None, format=win32pdh.PDH_FMT_LONG, machine=None, bRefresh=0): if (object is None): object = find_pdh_counter_localized_name('Process', machine) if (counter is None): counter = find_pdh_counter_localized_name('ID Process', machine) if bRefresh: win32pdh.EnumObjects(None, machine, 0, 1) instanceName = string.lower(instanceName) (items, instances) = win32pdh.EnumObjectItems(None, None, object, (-1)) instance_dict = {} for instance in instances: try: instance_dict[instance] = (instance_dict[instance] + 1) except KeyError: instance_dict[instance] = 0 ret = [] for (instance, max_instances) in instance_dict.items(): for inum in xrange((max_instances + 1)): if (string.lower(instance) == instanceName): ret.append(GetPerformanceAttributes(object, counter, instance, inum, format, machine)) return ret
null
null
null
What does the code take ?
@register.filter def can_write(obj, user): return obj.can_write(user)
null
null
null
article or related to article model
codeqa
@register filterdef can write obj user return obj can write user
null
null
null
null
Question: What does the code take ? Code: @register.filter def can_write(obj, user): return obj.can_write(user)
null
null
null
How do authors create ?
def generate_authors(): jenkins_email = 'jenkins@review.(openstack|stackforge).org' old_authors = 'AUTHORS.in' new_authors = 'AUTHORS' if (not os.getenv('SKIP_GENERATE_AUTHORS')): if os.path.exists('.git'): git_log_cmd = (("git log --format='%aN <%aE>' | sort -u | egrep -v '" + jenkins_email) + "'") changelog = _run_shell_command(git_log_cmd) mailmap = parse_mailmap() with open(new_authors, 'w') as new_authors_fh: new_authors_fh.write(canonicalize_emails(changelog, mailmap)) if os.path.exists(old_authors): with open(old_authors, 'r') as old_authors_fh: new_authors_fh.write(('\n' + old_authors_fh.read())) else: open(new_authors, 'w').close()
null
null
null
using git commits
codeqa
def generate authors jenkins email 'jenkins@review openstack stackforge org'old authors 'AUTHORS in'new authors 'AUTHORS'if not os getenv 'SKIP GENERATE AUTHORS' if os path exists ' git' git log cmd "gitlog--format '%a N<%a E>' sort-u egrep-v'" + jenkins email + "'" changelog run shell command git log cmd mailmap parse mailmap with open new authors 'w' as new authors fh new authors fh write canonicalize emails changelog mailmap if os path exists old authors with open old authors 'r' as old authors fh new authors fh write '\n' + old authors fh read else open new authors 'w' close
null
null
null
null
Question: How do authors create ? Code: def generate_authors(): jenkins_email = 'jenkins@review.(openstack|stackforge).org' old_authors = 'AUTHORS.in' new_authors = 'AUTHORS' if (not os.getenv('SKIP_GENERATE_AUTHORS')): if os.path.exists('.git'): git_log_cmd = (("git log --format='%aN <%aE>' | sort -u | egrep -v '" + jenkins_email) + "'") changelog = _run_shell_command(git_log_cmd) mailmap = parse_mailmap() with open(new_authors, 'w') as new_authors_fh: new_authors_fh.write(canonicalize_emails(changelog, mailmap)) if os.path.exists(old_authors): with open(old_authors, 'r') as old_authors_fh: new_authors_fh.write(('\n' + old_authors_fh.read())) else: open(new_authors, 'w').close()
null
null
null
What does the code convert into a list of positional and keyword parameters ?
def _parse(description): (args, kw) = ([], {}) colon = _matchingString(u':', description) def add(sofar): if (len(sofar) == 1): args.append(sofar[0]) else: kw[nativeString(sofar[0])] = sofar[1] sofar = () for (type, value) in _tokenize(description): if (type is _STRING): sofar += (value,) elif (value == colon): add(sofar) sofar = () add(sofar) return (args, kw)
null
null
null
a description string
codeqa
def parse description args kw [] {} colon matching String u' ' description def add sofar if len sofar 1 args append sofar[ 0 ] else kw[native String sofar[ 0 ] ] sofar[ 1 ]sofar for type value in tokenize description if type is STRING sofar + value elif value colon add sofar sofar add sofar return args kw
null
null
null
null
Question: What does the code convert into a list of positional and keyword parameters ? Code: def _parse(description): (args, kw) = ([], {}) colon = _matchingString(u':', description) def add(sofar): if (len(sofar) == 1): args.append(sofar[0]) else: kw[nativeString(sofar[0])] = sofar[1] sofar = () for (type, value) in _tokenize(description): if (type is _STRING): sofar += (value,) elif (value == colon): add(sofar) sofar = () add(sofar) return (args, kw)
null
null
null
How do filter match ?
def condition_not_db_filter(model, field, value, auto_none=True): result = (~ condition_db_filter(model, field, value)) if (auto_none and ((isinstance(value, collections.Iterable) and (not isinstance(value, six.string_types)) and (None not in value)) or (value is not None))): orm_field = getattr(model, field) result = or_(result, orm_field.is_(None)) return result
null
null
null
non
codeqa
def condition not db filter model field value auto none True result ~ condition db filter model field value if auto none and isinstance value collections Iterable and not isinstance value six string types and None not in value or value is not None orm field getattr model field result or result orm field is None return result
null
null
null
null
Question: How do filter match ? Code: def condition_not_db_filter(model, field, value, auto_none=True): result = (~ condition_db_filter(model, field, value)) if (auto_none and ((isinstance(value, collections.Iterable) and (not isinstance(value, six.string_types)) and (None not in value)) or (value is not None))): orm_field = getattr(model, field) result = or_(result, orm_field.is_(None)) return result
null
null
null
What do functions support ?
def memoize(fun): @functools.wraps(fun) def wrapper(*args, **kwargs): key = (args, frozenset(sorted(kwargs.items()))) try: return cache[key] except KeyError: ret = cache[key] = fun(*args, **kwargs) return ret def cache_clear(): 'Clear cache.' cache.clear() cache = {} wrapper.cache_clear = cache_clear return wrapper
null
null
null
positional arguments
codeqa
def memoize fun @functools wraps fun def wrapper *args **kwargs key args frozenset sorted kwargs items try return cache[key]except Key Error ret cache[key] fun *args **kwargs return retdef cache clear ' Clearcache 'cache clear cache {}wrapper cache clear cache clearreturn wrapper
null
null
null
null
Question: What do functions support ? Code: def memoize(fun): @functools.wraps(fun) def wrapper(*args, **kwargs): key = (args, frozenset(sorted(kwargs.items()))) try: return cache[key] except KeyError: ret = cache[key] = fun(*args, **kwargs) return ret def cache_clear(): 'Clear cache.' cache.clear() cache = {} wrapper.cache_clear = cache_clear return wrapper
null
null
null
What is supporting positional arguments ?
def memoize(fun): @functools.wraps(fun) def wrapper(*args, **kwargs): key = (args, frozenset(sorted(kwargs.items()))) try: return cache[key] except KeyError: ret = cache[key] = fun(*args, **kwargs) return ret def cache_clear(): 'Clear cache.' cache.clear() cache = {} wrapper.cache_clear = cache_clear return wrapper
null
null
null
functions
codeqa
def memoize fun @functools wraps fun def wrapper *args **kwargs key args frozenset sorted kwargs items try return cache[key]except Key Error ret cache[key] fun *args **kwargs return retdef cache clear ' Clearcache 'cache clear cache {}wrapper cache clear cache clearreturn wrapper
null
null
null
null
Question: What is supporting positional arguments ? Code: def memoize(fun): @functools.wraps(fun) def wrapper(*args, **kwargs): key = (args, frozenset(sorted(kwargs.items()))) try: return cache[key] except KeyError: ret = cache[key] = fun(*args, **kwargs) return ret def cache_clear(): 'Clear cache.' cache.clear() cache = {} wrapper.cache_clear = cache_clear return wrapper
null
null
null
What do we get with no catch ?
def test_no_stdlib_collections3(): import collections matplotlib = import_module('matplotlib', __import__kwargs={'fromlist': ['cm', 'collections']}, min_module_version='1.1.0') if matplotlib: assert (collections != matplotlib.collections)
null
null
null
the right collections
codeqa
def test no stdlib collections 3 import collectionsmatplotlib import module 'matplotlib' import kwargs {'fromlist' ['cm' 'collections']} min module version '1 1 0' if matplotlib assert collections matplotlib collections
null
null
null
null
Question: What do we get with no catch ? Code: def test_no_stdlib_collections3(): import collections matplotlib = import_module('matplotlib', __import__kwargs={'fromlist': ['cm', 'collections']}, min_module_version='1.1.0') if matplotlib: assert (collections != matplotlib.collections)
null
null
null
When did thread create ?
def track_created_event(request, event_name, course, obj, data): if (len(obj.body) > TRACKING_MAX_FORUM_BODY): data['truncated'] = True else: data['truncated'] = False data['body'] = obj.body[:TRACKING_MAX_FORUM_BODY] track_forum_event(request, event_name, course, obj, data)
null
null
null
newly
codeqa
def track created event request event name course obj data if len obj body > TRACKING MAX FORUM BODY data['truncated'] Trueelse data['truncated'] Falsedata['body'] obj body[ TRACKING MAX FORUM BODY]track forum event request event name course obj data
null
null
null
null
Question: When did thread create ? Code: def track_created_event(request, event_name, course, obj, data): if (len(obj.body) > TRACKING_MAX_FORUM_BODY): data['truncated'] = True else: data['truncated'] = False data['body'] = obj.body[:TRACKING_MAX_FORUM_BODY] track_forum_event(request, event_name, course, obj, data)
null
null
null
What does the code delete ?
def DeleteOldFeedItems(client, feed_item_ids, feed): if (not feed_item_ids): return feed_item_service = client.GetService('FeedItemService', 'v201605') operations = [{'operator': 'REMOVE', 'operand': {'feedId': feed['id'], 'feedItemId': feed_item_id}} for feed_item_id in feed_item_ids] feed_item_service.mutate(operations)
null
null
null
the old feed items for which extension settings have been created
codeqa
def Delete Old Feed Items client feed item ids feed if not feed item ids returnfeed item service client Get Service ' Feed Item Service' 'v 201605 ' operations [{'operator' 'REMOVE' 'operand' {'feed Id' feed['id'] 'feed Item Id' feed item id}} for feed item id in feed item ids]feed item service mutate operations
null
null
null
null
Question: What does the code delete ? Code: def DeleteOldFeedItems(client, feed_item_ids, feed): if (not feed_item_ids): return feed_item_service = client.GetService('FeedItemService', 'v201605') operations = [{'operator': 'REMOVE', 'operand': {'feedId': feed['id'], 'feedItemId': feed_item_id}} for feed_item_id in feed_item_ids] feed_item_service.mutate(operations)
null
null
null
What is representing the configured indexes ?
def get_indexes(**ctx_options): return get_indexes_async(**ctx_options).get_result()
null
null
null
a data structure
codeqa
def get indexes **ctx options return get indexes async **ctx options get result
null
null
null
null
Question: What is representing the configured indexes ? Code: def get_indexes(**ctx_options): return get_indexes_async(**ctx_options).get_result()
null
null
null
What do a data structure represent ?
def get_indexes(**ctx_options): return get_indexes_async(**ctx_options).get_result()
null
null
null
the configured indexes
codeqa
def get indexes **ctx options return get indexes async **ctx options get result
null
null
null
null
Question: What do a data structure represent ? Code: def get_indexes(**ctx_options): return get_indexes_async(**ctx_options).get_result()
null
null
null
What does the code get ?
def get_indexes(**ctx_options): return get_indexes_async(**ctx_options).get_result()
null
null
null
a data structure representing the configured indexes
codeqa
def get indexes **ctx options return get indexes async **ctx options get result
null
null
null
null
Question: What does the code get ? Code: def get_indexes(**ctx_options): return get_indexes_async(**ctx_options).get_result()
null
null
null
How does an object import ?
def import_object(name): if (isinstance(name, unicode_type) and (str is not unicode_type)): name = name.encode('utf-8') if (name.count('.') == 0): return __import__(name, None, None) parts = name.split('.') obj = __import__('.'.join(parts[:(-1)]), None, None, [parts[(-1)]], 0) try: return getattr(obj, parts[(-1)]) except AttributeError: raise ImportError(('No module named %s' % parts[(-1)]))
null
null
null
by name
codeqa
def import object name if isinstance name unicode type and str is not unicode type name name encode 'utf- 8 ' if name count ' ' 0 return import name None None parts name split ' ' obj import ' ' join parts[ -1 ] None None [parts[ -1 ]] 0 try return getattr obj parts[ -1 ] except Attribute Error raise Import Error ' Nomodulenamed%s' % parts[ -1 ]
null
null
null
null
Question: How does an object import ? Code: def import_object(name): if (isinstance(name, unicode_type) and (str is not unicode_type)): name = name.encode('utf-8') if (name.count('.') == 0): return __import__(name, None, None) parts = name.split('.') obj = __import__('.'.join(parts[:(-1)]), None, None, [parts[(-1)]], 0) try: return getattr(obj, parts[(-1)]) except AttributeError: raise ImportError(('No module named %s' % parts[(-1)]))
null
null
null
How do configuration examine ?
@memoize def _construct_uri(profile): return 'http://{host}:{port}'.format(**profile)
null
null
null
in the following format
codeqa
@memoizedef construct uri profile return 'http //{host} {port}' format **profile
null
null
null
null
Question: How do configuration examine ? Code: @memoize def _construct_uri(profile): return 'http://{host}:{port}'.format(**profile)