labNo
float64
1
10
taskNo
float64
0
4
questioner
stringclasses
2 values
question
stringlengths
9
201
code
stringlengths
18
30.3k
startLine
float64
0
192
endLine
float64
0
196
questionType
stringclasses
4 values
answer
stringlengths
2
905
src
stringclasses
3 values
code_processed
stringlengths
12
28.3k
id
stringlengths
2
5
raw_code
stringlengths
20
30.3k
raw_comment
stringlengths
10
242
comment
stringlengths
9
207
q_code
stringlengths
66
30.3k
null
null
null
What does the code serve from the given filename ?
def staticfile(filename, root=None, match='', content_types=None, debug=False): request = cherrypy.serving.request if (request.method not in ('GET', 'HEAD')): if debug: cherrypy.log('request.method not GET or HEAD', 'TOOLS.STATICFILE') return False if (match and (not re.search(match, request.path_info))): if debug: cherrypy.log(('request.path_info %r does not match pattern %r' % (request.path_info, match)), 'TOOLS.STATICFILE') return False if (not os.path.isabs(filename)): if (not root): msg = ("Static tool requires an absolute filename (got '%s')." % filename) if debug: cherrypy.log(msg, 'TOOLS.STATICFILE') raise ValueError(msg) filename = os.path.join(root, filename) return _attempt(filename, content_types, debug=debug)
null
null
null
a static resource
codeqa
def staticfile filename root None match '' content types None debug False request cherrypy serving requestif request method not in 'GET' 'HEAD' if debug cherrypy log 'request methodnot GE Tor HEAD' 'TOOLS STATICFILE' return Falseif match and not re search match request path info if debug cherrypy log 'request path info%rdoesnotmatchpattern%r' % request path info match 'TOOLS STATICFILE' return Falseif not os path isabs filename if not root msg " Statictoolrequiresanabsolutefilename got'%s' " % filename if debug cherrypy log msg 'TOOLS STATICFILE' raise Value Error msg filename os path join root filename return attempt filename content types debug debug
null
null
null
null
Question: What does the code serve from the given filename ? Code: def staticfile(filename, root=None, match='', content_types=None, debug=False): request = cherrypy.serving.request if (request.method not in ('GET', 'HEAD')): if debug: cherrypy.log('request.method not GET or HEAD', 'TOOLS.STATICFILE') return False if (match and (not re.search(match, request.path_info))): if debug: cherrypy.log(('request.path_info %r does not match pattern %r' % (request.path_info, match)), 'TOOLS.STATICFILE') return False if (not os.path.isabs(filename)): if (not root): msg = ("Static tool requires an absolute filename (got '%s')." % filename) if debug: cherrypy.log(msg, 'TOOLS.STATICFILE') raise ValueError(msg) filename = os.path.join(root, filename) return _attempt(filename, content_types, debug=debug)
null
null
null
How do intersections sort ?
def comparePointIndexDescending(self, other): if (self.pointIndex > other.pointIndex): return (-1) if (self.pointIndex < other.pointIndex): return 1 return 0
null
null
null
in descending order of point index
codeqa
def compare Point Index Descending self other if self point Index > other point Index return -1 if self point Index < other point Index return 1return 0
null
null
null
null
Question: How do intersections sort ? Code: def comparePointIndexDescending(self, other): if (self.pointIndex > other.pointIndex): return (-1) if (self.pointIndex < other.pointIndex): return 1 return 0
null
null
null
What does the code get in order to sort y intersections in descending order of point index ?
def comparePointIndexDescending(self, other): if (self.pointIndex > other.pointIndex): return (-1) if (self.pointIndex < other.pointIndex): return 1 return 0
null
null
null
comparison
codeqa
def compare Point Index Descending self other if self point Index > other point Index return -1 if self point Index < other point Index return 1return 0
null
null
null
null
Question: What does the code get in order to sort y intersections in descending order of point index ? Code: def comparePointIndexDescending(self, other): if (self.pointIndex > other.pointIndex): return (-1) if (self.pointIndex < other.pointIndex): return 1 return 0
null
null
null
For what purpose does the code get comparison ?
def comparePointIndexDescending(self, other): if (self.pointIndex > other.pointIndex): return (-1) if (self.pointIndex < other.pointIndex): return 1 return 0
null
null
null
in order to sort y intersections in descending order of point index
codeqa
def compare Point Index Descending self other if self point Index > other point Index return -1 if self point Index < other point Index return 1return 0
null
null
null
null
Question: For what purpose does the code get comparison ? Code: def comparePointIndexDescending(self, other): if (self.pointIndex > other.pointIndex): return (-1) if (self.pointIndex < other.pointIndex): return 1 return 0
null
null
null
What does the code run in a worker process ?
def fork_job(mod_name, func_name, args=(), kwargs={}, timeout=300, cwd=None, priority=u'normal', env={}, no_output=False, heartbeat=None, abort=None, module_is_source_code=False): ans = {u'result': None, u'stdout_stderr': None} (listener, w) = create_worker(env, priority, cwd) try: communicate(ans, w, listener, (mod_name, func_name, args, kwargs, module_is_source_code), timeout=timeout, heartbeat=heartbeat, abort=abort) finally: t = Thread(target=w.kill) t.daemon = True t.start() if no_output: try: os.remove(w.log_path) except: pass if (not no_output): ans[u'stdout_stderr'] = w.log_path return ans
null
null
null
a job
codeqa
def fork job mod name func name args kwargs {} timeout 300 cwd None priority u'normal' env {} no output False heartbeat None abort None module is source code False ans {u'result' None u'stdout stderr' None} listener w create worker env priority cwd try communicate ans w listener mod name func name args kwargs module is source code timeout timeout heartbeat heartbeat abort abort finally t Thread target w kill t daemon Truet start if no output try os remove w log path except passif not no output ans[u'stdout stderr'] w log pathreturn ans
null
null
null
null
Question: What does the code run in a worker process ? Code: def fork_job(mod_name, func_name, args=(), kwargs={}, timeout=300, cwd=None, priority=u'normal', env={}, no_output=False, heartbeat=None, abort=None, module_is_source_code=False): ans = {u'result': None, u'stdout_stderr': None} (listener, w) = create_worker(env, priority, cwd) try: communicate(ans, w, listener, (mod_name, func_name, args, kwargs, module_is_source_code), timeout=timeout, heartbeat=heartbeat, abort=abort) finally: t = Thread(target=w.kill) t.daemon = True t.start() if no_output: try: os.remove(w.log_path) except: pass if (not no_output): ans[u'stdout_stderr'] = w.log_path return ans
null
null
null
How does the code run a job ?
def fork_job(mod_name, func_name, args=(), kwargs={}, timeout=300, cwd=None, priority=u'normal', env={}, no_output=False, heartbeat=None, abort=None, module_is_source_code=False): ans = {u'result': None, u'stdout_stderr': None} (listener, w) = create_worker(env, priority, cwd) try: communicate(ans, w, listener, (mod_name, func_name, args, kwargs, module_is_source_code), timeout=timeout, heartbeat=heartbeat, abort=abort) finally: t = Thread(target=w.kill) t.daemon = True t.start() if no_output: try: os.remove(w.log_path) except: pass if (not no_output): ans[u'stdout_stderr'] = w.log_path return ans
null
null
null
in a worker process
codeqa
def fork job mod name func name args kwargs {} timeout 300 cwd None priority u'normal' env {} no output False heartbeat None abort None module is source code False ans {u'result' None u'stdout stderr' None} listener w create worker env priority cwd try communicate ans w listener mod name func name args kwargs module is source code timeout timeout heartbeat heartbeat abort abort finally t Thread target w kill t daemon Truet start if no output try os remove w log path except passif not no output ans[u'stdout stderr'] w log pathreturn ans
null
null
null
null
Question: How does the code run a job ? Code: def fork_job(mod_name, func_name, args=(), kwargs={}, timeout=300, cwd=None, priority=u'normal', env={}, no_output=False, heartbeat=None, abort=None, module_is_source_code=False): ans = {u'result': None, u'stdout_stderr': None} (listener, w) = create_worker(env, priority, cwd) try: communicate(ans, w, listener, (mod_name, func_name, args, kwargs, module_is_source_code), timeout=timeout, heartbeat=heartbeat, abort=abort) finally: t = Thread(target=w.kill) t.daemon = True t.start() if no_output: try: os.remove(w.log_path) except: pass if (not no_output): ans[u'stdout_stderr'] = w.log_path return ans
null
null
null
What does the code create ?
def new_figure_manager(num, *args, **kwargs): if DEBUG: print(u'backend_qt4agg.new_figure_manager') FigureClass = kwargs.pop(u'FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) return new_figure_manager_given_figure(num, thisFig)
null
null
null
a new figure manager instance
codeqa
def new figure manager num *args **kwargs if DEBUG print u'backend qt 4 agg new figure manager' Figure Class kwargs pop u' Figure Class' Figure this Fig Figure Class *args **kwargs return new figure manager given figure num this Fig
null
null
null
null
Question: What does the code create ? Code: def new_figure_manager(num, *args, **kwargs): if DEBUG: print(u'backend_qt4agg.new_figure_manager') FigureClass = kwargs.pop(u'FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) return new_figure_manager_given_figure(num, thisFig)
null
null
null
How does the code find a room ?
def find_room(name, api_key=None): if (not api_key): api_key = _get_api_key() if name.startswith('#'): name = name[1:] ret = list_rooms(api_key) if ret['res']: rooms = ret['message'] if rooms: for room in range(0, len(rooms)): if (rooms[room]['name'] == name): return rooms[room] return False
null
null
null
by name
codeqa
def find room name api key None if not api key api key get api key if name startswith '#' name name[ 1 ]ret list rooms api key if ret['res'] rooms ret['message']if rooms for room in range 0 len rooms if rooms[room]['name'] name return rooms[room]return False
null
null
null
null
Question: How does the code find a room ? Code: def find_room(name, api_key=None): if (not api_key): api_key = _get_api_key() if name.startswith('#'): name = name[1:] ret = list_rooms(api_key) if ret['res']: rooms = ret['message'] if rooms: for room in range(0, len(rooms)): if (rooms[room]['name'] == name): return rooms[room] return False
null
null
null
What does the code find by name ?
def find_room(name, api_key=None): if (not api_key): api_key = _get_api_key() if name.startswith('#'): name = name[1:] ret = list_rooms(api_key) if ret['res']: rooms = ret['message'] if rooms: for room in range(0, len(rooms)): if (rooms[room]['name'] == name): return rooms[room] return False
null
null
null
a room
codeqa
def find room name api key None if not api key api key get api key if name startswith '#' name name[ 1 ]ret list rooms api key if ret['res'] rooms ret['message']if rooms for room in range 0 len rooms if rooms[room]['name'] name return rooms[room]return False
null
null
null
null
Question: What does the code find by name ? Code: def find_room(name, api_key=None): if (not api_key): api_key = _get_api_key() if name.startswith('#'): name = name[1:] ret = list_rooms(api_key) if ret['res']: rooms = ret['message'] if rooms: for room in range(0, len(rooms)): if (rooms[room]['name'] == name): return rooms[room] return False
null
null
null
What does the code make ?
def sdb(opts, functions=None, whitelist=None): return LazyLoader(_module_dirs(opts, 'sdb'), opts, tag='sdb', pack={'__sdb__': functions}, whitelist=whitelist)
null
null
null
a very small database call
codeqa
def sdb opts functions None whitelist None return Lazy Loader module dirs opts 'sdb' opts tag 'sdb' pack {' sdb ' functions} whitelist whitelist
null
null
null
null
Question: What does the code make ? Code: def sdb(opts, functions=None, whitelist=None): return LazyLoader(_module_dirs(opts, 'sdb'), opts, tag='sdb', pack={'__sdb__': functions}, whitelist=whitelist)
null
null
null
What does the code send ?
def patch(url, data=None, **kwargs): return request('patch', url, data=data, **kwargs)
null
null
null
a patch request
codeqa
def patch url data None **kwargs return request 'patch' url data data **kwargs
null
null
null
null
Question: What does the code send ? Code: def patch(url, data=None, **kwargs): return request('patch', url, data=data, **kwargs)
null
null
null
What does the code remove from the system ?
def remove_course_content_user_milestones(course_key, content_key, user, relationship): if (not settings.FEATURES.get('MILESTONES_APP')): return [] course_content_milestones = milestones_api.get_course_content_milestones(course_key, content_key, relationship) for milestone in course_content_milestones: milestones_api.remove_user_milestone({'id': user.id}, milestone)
null
null
null
the specified user - milestone link
codeqa
def remove course content user milestones course key content key user relationship if not settings FEATURES get 'MILESTONES APP' return []course content milestones milestones api get course content milestones course key content key relationship for milestone in course content milestones milestones api remove user milestone {'id' user id} milestone
null
null
null
null
Question: What does the code remove from the system ? Code: def remove_course_content_user_milestones(course_key, content_key, user, relationship): if (not settings.FEATURES.get('MILESTONES_APP')): return [] course_content_milestones = milestones_api.get_course_content_milestones(course_key, content_key, relationship) for milestone in course_content_milestones: milestones_api.remove_user_milestone({'id': user.id}, milestone)
null
null
null
What do you decorate with this ?
def fresh_login_required(func): @wraps(func) def decorated_view(*args, **kwargs): if (request.method in EXEMPT_METHODS): return func(*args, **kwargs) elif current_app.login_manager._login_disabled: return func(*args, **kwargs) elif (not current_user.is_authenticated): return current_app.login_manager.unauthorized() elif (not login_fresh()): return current_app.login_manager.needs_refresh() return func(*args, **kwargs) return decorated_view
null
null
null
a view
codeqa
def fresh login required func @wraps func def decorated view *args **kwargs if request method in EXEMPT METHODS return func *args **kwargs elif current app login manager login disabled return func *args **kwargs elif not current user is authenticated return current app login manager unauthorized elif not login fresh return current app login manager needs refresh return func *args **kwargs return decorated view
null
null
null
null
Question: What do you decorate with this ? Code: def fresh_login_required(func): @wraps(func) def decorated_view(*args, **kwargs): if (request.method in EXEMPT_METHODS): return func(*args, **kwargs) elif current_app.login_manager._login_disabled: return func(*args, **kwargs) elif (not current_user.is_authenticated): return current_app.login_manager.unauthorized() elif (not login_fresh()): return current_app.login_manager.needs_refresh() return func(*args, **kwargs) return decorated_view
null
null
null
By how much does the code read in the : ref : user guide < metrics > ?
def paired_cosine_distances(X, Y): (X, Y) = check_paired_arrays(X, Y) return (0.5 * row_norms((normalize(X) - normalize(Y)), squared=True))
null
null
null
more
codeqa
def paired cosine distances X Y X Y check paired arrays X Y return 0 5 * row norms normalize X - normalize Y squared True
null
null
null
null
Question: By how much does the code read in the : ref : user guide < metrics > ? Code: def paired_cosine_distances(X, Y): (X, Y) = check_paired_arrays(X, Y) return (0.5 * row_norms((normalize(X) - normalize(Y)), squared=True))
null
null
null
Where does the code read more ?
def paired_cosine_distances(X, Y): (X, Y) = check_paired_arrays(X, Y) return (0.5 * row_norms((normalize(X) - normalize(Y)), squared=True))
null
null
null
in the : ref : user guide < metrics >
codeqa
def paired cosine distances X Y X Y check paired arrays X Y return 0 5 * row norms normalize X - normalize Y squared True
null
null
null
null
Question: Where does the code read more ? Code: def paired_cosine_distances(X, Y): (X, Y) = check_paired_arrays(X, Y) return (0.5 * row_norms((normalize(X) - normalize(Y)), squared=True))
null
null
null
What does the code compute ?
def paired_cosine_distances(X, Y): (X, Y) = check_paired_arrays(X, Y) return (0.5 * row_norms((normalize(X) - normalize(Y)), squared=True))
null
null
null
the paired cosine distances between x
codeqa
def paired cosine distances X Y X Y check paired arrays X Y return 0 5 * row norms normalize X - normalize Y squared True
null
null
null
null
Question: What does the code compute ? Code: def paired_cosine_distances(X, Y): (X, Y) = check_paired_arrays(X, Y) return (0.5 * row_norms((normalize(X) - normalize(Y)), squared=True))
null
null
null
What did the code set ?
def libvlc_video_set_crop_geometry(p_mi, psz_geometry): f = (_Cfunctions.get('libvlc_video_set_crop_geometry', None) or _Cfunction('libvlc_video_set_crop_geometry', ((1,), (1,)), None, None, MediaPlayer, ctypes.c_char_p)) return f(p_mi, psz_geometry)
null
null
null
new crop filter geometry
codeqa
def libvlc video set crop geometry p mi psz geometry f Cfunctions get 'libvlc video set crop geometry' None or Cfunction 'libvlc video set crop geometry' 1 1 None None Media Player ctypes c char p return f p mi psz geometry
null
null
null
null
Question: What did the code set ? Code: def libvlc_video_set_crop_geometry(p_mi, psz_geometry): f = (_Cfunctions.get('libvlc_video_set_crop_geometry', None) or _Cfunction('libvlc_video_set_crop_geometry', ((1,), (1,)), None, None, MediaPlayer, ctypes.c_char_p)) return f(p_mi, psz_geometry)
null
null
null
When do we train it on a dummy dataset-- tiny model and dataset ?
def test_conv_sigmoid_basic(): yaml_file = os.path.join(pylearn2.__path__[0], 'models/tests/conv_elemwise_sigm.yaml') with open(yaml_file) as yamlh: yaml_lines = yamlh.readlines() yaml_str = ''.join(yaml_lines) train = yaml_parse.load(yaml_str) train.main_loop()
null
null
null
for a few epochs
codeqa
def test conv sigmoid basic yaml file os path join pylearn 2 path [0 ] 'models/tests/conv elemwise sigm yaml' with open yaml file as yamlh yaml lines yamlh readlines yaml str '' join yaml lines train yaml parse load yaml str train main loop
null
null
null
null
Question: When do we train it on a dummy dataset-- tiny model and dataset ? Code: def test_conv_sigmoid_basic(): yaml_file = os.path.join(pylearn2.__path__[0], 'models/tests/conv_elemwise_sigm.yaml') with open(yaml_file) as yamlh: yaml_lines = yamlh.readlines() yaml_str = ''.join(yaml_lines) train = yaml_parse.load(yaml_str) train.main_loop()
null
null
null
What can we load ?
def test_conv_sigmoid_basic(): yaml_file = os.path.join(pylearn2.__path__[0], 'models/tests/conv_elemwise_sigm.yaml') with open(yaml_file) as yamlh: yaml_lines = yamlh.readlines() yaml_str = ''.join(yaml_lines) train = yaml_parse.load(yaml_str) train.main_loop()
null
null
null
a convolutional sigmoid model
codeqa
def test conv sigmoid basic yaml file os path join pylearn 2 path [0 ] 'models/tests/conv elemwise sigm yaml' with open yaml file as yamlh yaml lines yamlh readlines yaml str '' join yaml lines train yaml parse load yaml str train main loop
null
null
null
null
Question: What can we load ? Code: def test_conv_sigmoid_basic(): yaml_file = os.path.join(pylearn2.__path__[0], 'models/tests/conv_elemwise_sigm.yaml') with open(yaml_file) as yamlh: yaml_lines = yamlh.readlines() yaml_str = ''.join(yaml_lines) train = yaml_parse.load(yaml_str) train.main_loop()
null
null
null
What installs the instrumentation ?
def appstats_wsgi_middleware(app): def appstats_wsgi_wrapper(environ, start_response): 'Outer wrapper function around the WSGI protocol.\n\n The top-level appstats_wsgi_middleware() function returns this\n function to the caller instead of the app class or function passed\n in. When the caller calls this function (which may happen\n multiple times, to handle multiple requests) this function\n instantiates the app class (or calls the app function), sandwiched\n between calls to start_recording() and end_recording() which\n manipulate the recording state.\n\n The signature is determined by the WSGI protocol.\n ' start_recording(environ) save_status = [None] datamodel_pb.AggregateRpcStatsProto.total_billed_ops_str = total_billed_ops_to_str datamodel_pb.IndividualRpcStatsProto.billed_ops_str = individual_billed_ops_to_str def appstats_start_response(status, headers, exc_info=None): "Inner wrapper function for the start_response() function argument.\n\n The purpose of this wrapper is save the HTTP status (which the\n WSGI protocol only makes available through the start_response()\n function) into the surrounding scope. This is done through a\n hack because Python 2.x doesn't support assignment to nonlocal\n variables. If this function is called more than once, the last\n status value will be used.\n\n The signature is determined by the WSGI protocol.\n " save_status.append(status) return start_response(status, headers, exc_info) try: result = app(environ, appstats_start_response) except Exception: end_recording(500) raise if (result is not None): for value in result: (yield value) status = save_status[(-1)] if (status is not None): status = status[:3] end_recording(status) return appstats_wsgi_wrapper
null
null
null
wsgi middleware
codeqa
def appstats wsgi middleware app def appstats wsgi wrapper environ start response ' Outerwrapperfunctionaroundthe WSG Iprotocol \n\n Thetop-levelappstats wsgi middleware functionreturnsthis\nfunctiontothecallerinsteadoftheappclassorfunctionpassed\nin Whenthecallercallsthisfunction whichmayhappen\nmultipletimes tohandlemultiplerequests thisfunction\ninstantiatestheappclass orcallstheappfunction sandwiched\nbetweencallstostart recording andend recording which\nmanipulatetherecordingstate \n\n Thesignatureisdeterminedbythe WSG Iprotocol \n'start recording environ save status [ None]datamodel pb Aggregate Rpc Stats Proto total billed ops str total billed ops to strdatamodel pb Individual Rpc Stats Proto billed ops str individual billed ops to strdef appstats start response status headers exc info None " Innerwrapperfunctionforthestart response functionargument \n\n Thepurposeofthiswrapperissavethe HTT Pstatus whichthe\n WSG Iprotocolonlymakesavailablethroughthestart response \nfunction intothesurroundingscope Thisisdonethrougha\nhackbecause Python 2 xdoesn'tsupportassignmenttononlocal\nvariables Ifthisfunctioniscalledmorethanonce thelast\nstatusvaluewillbeused \n\n Thesignatureisdeterminedbythe WSG Iprotocol \n"save status append status return start response status headers exc info try result app environ appstats start response except Exception end recording 500 raiseif result is not None for value in result yield value status save status[ -1 ]if status is not None status status[ 3]end recording status return appstats wsgi wrapper
null
null
null
null
Question: What installs the instrumentation ? Code: def appstats_wsgi_middleware(app): def appstats_wsgi_wrapper(environ, start_response): 'Outer wrapper function around the WSGI protocol.\n\n The top-level appstats_wsgi_middleware() function returns this\n function to the caller instead of the app class or function passed\n in. When the caller calls this function (which may happen\n multiple times, to handle multiple requests) this function\n instantiates the app class (or calls the app function), sandwiched\n between calls to start_recording() and end_recording() which\n manipulate the recording state.\n\n The signature is determined by the WSGI protocol.\n ' start_recording(environ) save_status = [None] datamodel_pb.AggregateRpcStatsProto.total_billed_ops_str = total_billed_ops_to_str datamodel_pb.IndividualRpcStatsProto.billed_ops_str = individual_billed_ops_to_str def appstats_start_response(status, headers, exc_info=None): "Inner wrapper function for the start_response() function argument.\n\n The purpose of this wrapper is save the HTTP status (which the\n WSGI protocol only makes available through the start_response()\n function) into the surrounding scope. This is done through a\n hack because Python 2.x doesn't support assignment to nonlocal\n variables. If this function is called more than once, the last\n status value will be used.\n\n The signature is determined by the WSGI protocol.\n " save_status.append(status) return start_response(status, headers, exc_info) try: result = app(environ, appstats_start_response) except Exception: end_recording(500) raise if (result is not None): for value in result: (yield value) status = save_status[(-1)] if (status is not None): status = status[:3] end_recording(status) return appstats_wsgi_wrapper
null
null
null
What does the code get ?
def recommend_for_user(user): return recommend_for_brands(brandsfor.get(user, set()))
null
null
null
a users brands
codeqa
def recommend for user user return recommend for brands brandsfor get user set
null
null
null
null
Question: What does the code get ? Code: def recommend_for_user(user): return recommend_for_brands(brandsfor.get(user, set()))
null
null
null
How is user dict return from ?
def get_user(host, port, username): url = api_url(host, port, '/Users/Public') r = requests.get(url) user = [i for i in r.json() if (i['Name'] == username)] return user
null
null
null
server or none
codeqa
def get user host port username url api url host port '/ Users/ Public' r requests get url user [i for i in r json if i[' Name'] username ]return user
null
null
null
null
Question: How is user dict return from ? Code: def get_user(host, port, username): url = api_url(host, port, '/Users/Public') r = requests.get(url) user = [i for i in r.json() if (i['Name'] == username)] return user
null
null
null
In which direction is user dict return server or none ?
def get_user(host, port, username): url = api_url(host, port, '/Users/Public') r = requests.get(url) user = [i for i in r.json() if (i['Name'] == username)] return user
null
null
null
from
codeqa
def get user host port username url api url host port '/ Users/ Public' r requests get url user [i for i in r json if i[' Name'] username ]return user
null
null
null
null
Question: In which direction is user dict return server or none ? Code: def get_user(host, port, username): url = api_url(host, port, '/Users/Public') r = requests.get(url) user = [i for i in r.json() if (i['Name'] == username)] return user
null
null
null
What do time - frequency representation use ?
@verbose def tfr_stockwell(inst, fmin=None, fmax=None, n_fft=None, width=1.0, decim=1, return_itc=False, n_jobs=1, verbose=None): data = _get_data(inst, return_itc) picks = pick_types(inst.info, meg=True, eeg=True) info = pick_info(inst.info, picks) data = data[:, picks, :] n_jobs = check_n_jobs(n_jobs) (power, itc, freqs) = _induced_power_stockwell(data, sfreq=info['sfreq'], fmin=fmin, fmax=fmax, n_fft=n_fft, width=width, decim=decim, return_itc=return_itc, n_jobs=n_jobs) times = inst.times[::decim].copy() nave = len(data) out = AverageTFR(info, power, times, freqs, nave, method='stockwell-power') if return_itc: out = (out, AverageTFR(deepcopy(info), itc, times.copy(), freqs.copy(), nave, method='stockwell-itc')) return out
null
null
null
stockwell transform
codeqa
@verbosedef tfr stockwell inst fmin None fmax None n fft None width 1 0 decim 1 return itc False n jobs 1 verbose None data get data inst return itc picks pick types inst info meg True eeg True info pick info inst info picks data data[ picks ]n jobs check n jobs n jobs power itc freqs induced power stockwell data sfreq info['sfreq'] fmin fmin fmax fmax n fft n fft width width decim decim return itc return itc n jobs n jobs times inst times[ decim] copy nave len data out Average TFR info power times freqs nave method 'stockwell-power' if return itc out out Average TFR deepcopy info itc times copy freqs copy nave method 'stockwell-itc' return out
null
null
null
null
Question: What do time - frequency representation use ? Code: @verbose def tfr_stockwell(inst, fmin=None, fmax=None, n_fft=None, width=1.0, decim=1, return_itc=False, n_jobs=1, verbose=None): data = _get_data(inst, return_itc) picks = pick_types(inst.info, meg=True, eeg=True) info = pick_info(inst.info, picks) data = data[:, picks, :] n_jobs = check_n_jobs(n_jobs) (power, itc, freqs) = _induced_power_stockwell(data, sfreq=info['sfreq'], fmin=fmin, fmax=fmax, n_fft=n_fft, width=width, decim=decim, return_itc=return_itc, n_jobs=n_jobs) times = inst.times[::decim].copy() nave = len(data) out = AverageTFR(info, power, times, freqs, nave, method='stockwell-power') if return_itc: out = (out, AverageTFR(deepcopy(info), itc, times.copy(), freqs.copy(), nave, method='stockwell-itc')) return out
null
null
null
What does the code add ?
def add_instance_type_access(flavorid, projectid, ctxt=None): if (ctxt is None): ctxt = context.get_admin_context() return db.instance_type_access_add(ctxt, flavorid, projectid)
null
null
null
instance type access for project
codeqa
def add instance type access flavorid projectid ctxt None if ctxt is None ctxt context get admin context return db instance type access add ctxt flavorid projectid
null
null
null
null
Question: What does the code add ? Code: def add_instance_type_access(flavorid, projectid, ctxt=None): if (ctxt is None): ctxt = context.get_admin_context() return db.instance_type_access_add(ctxt, flavorid, projectid)
null
null
null
What does the code return ?
def _pool_hash_and_name(bootstrap_actions): for bootstrap_action in bootstrap_actions: if (bootstrap_action.name == 'master'): args = [arg.value for arg in bootstrap_action.args] if ((len(args) == 2) and args[0].startswith('pool-')): return (args[0][5:], args[1]) return (None, None)
null
null
null
the hash and pool name for the given cluster
codeqa
def pool hash and name bootstrap actions for bootstrap action in bootstrap actions if bootstrap action name 'master' args [arg value for arg in bootstrap action args]if len args 2 and args[ 0 ] startswith 'pool-' return args[ 0 ][ 5 ] args[ 1 ] return None None
null
null
null
null
Question: What does the code return ? Code: def _pool_hash_and_name(bootstrap_actions): for bootstrap_action in bootstrap_actions: if (bootstrap_action.name == 'master'): args = [arg.value for arg in bootstrap_action.args] if ((len(args) == 2) and args[0].startswith('pool-')): return (args[0][5:], args[1]) return (None, None)
null
null
null
What does the code use ?
def parse_soup_page(soup): (titles, authors, links) = (list(), list(), list()) for div in soup.findAll('div'): if ((div.name == 'div') and (div.get('class') == 'gs_ri')): links.append(div.a['href']) div_pub = div.findAll('div') for d in div_pub: if ((d.name == 'div') and (d.get('class') == 'gs_a')): authors.append(d.text) titles.append(div.a.text) return (titles, authors, links)
null
null
null
beautifulsoup
codeqa
def parse soup page soup titles authors links list list list for div in soup find All 'div' if div name 'div' and div get 'class' 'gs ri' links append div a['href'] div pub div find All 'div' for d in div pub if d name 'div' and d get 'class' 'gs a' authors append d text titles append div a text return titles authors links
null
null
null
null
Question: What does the code use ? Code: def parse_soup_page(soup): (titles, authors, links) = (list(), list(), list()) for div in soup.findAll('div'): if ((div.name == 'div') and (div.get('class') == 'gs_ri')): links.append(div.a['href']) div_pub = div.findAll('div') for d in div_pub: if ((d.name == 'div') and (d.get('class') == 'gs_a')): authors.append(d.text) titles.append(div.a.text) return (titles, authors, links)
null
null
null
What does the code remove ?
@task def clean(): d = ['build', 'dist', 'scipy.egg-info'] for i in d: if os.path.exists(i): shutil.rmtree(i) bdir = os.path.join('doc', options.sphinx.builddir) if os.path.exists(bdir): shutil.rmtree(bdir)
null
null
null
build
codeqa
@taskdef clean d ['build' 'dist' 'scipy egg-info']for i in d if os path exists i shutil rmtree i bdir os path join 'doc' options sphinx builddir if os path exists bdir shutil rmtree bdir
null
null
null
null
Question: What does the code remove ? Code: @task def clean(): d = ['build', 'dist', 'scipy.egg-info'] for i in d: if os.path.exists(i): shutil.rmtree(i) bdir = os.path.join('doc', options.sphinx.builddir) if os.path.exists(bdir): shutil.rmtree(bdir)
null
null
null
What does the code delete at the given path ?
def _clear_search_indexes_storage(search_index_path): if os.path.lexists(search_index_path): try: os.remove(search_index_path) except OSError as e: logging.warning('Failed to remove search indexes file %r: %s', search_index_path, e)
null
null
null
the search indexes storage file
codeqa
def clear search indexes storage search index path if os path lexists search index path try os remove search index path except OS Error as e logging warning ' Failedtoremovesearchindexesfile%r %s' search index path e
null
null
null
null
Question: What does the code delete at the given path ? Code: def _clear_search_indexes_storage(search_index_path): if os.path.lexists(search_index_path): try: os.remove(search_index_path) except OSError as e: logging.warning('Failed to remove search indexes file %r: %s', search_index_path, e)
null
null
null
Where does the code delete the search indexes storage file ?
def _clear_search_indexes_storage(search_index_path): if os.path.lexists(search_index_path): try: os.remove(search_index_path) except OSError as e: logging.warning('Failed to remove search indexes file %r: %s', search_index_path, e)
null
null
null
at the given path
codeqa
def clear search indexes storage search index path if os path lexists search index path try os remove search index path except OS Error as e logging warning ' Failedtoremovesearchindexesfile%r %s' search index path e
null
null
null
null
Question: Where does the code delete the search indexes storage file ? Code: def _clear_search_indexes_storage(search_index_path): if os.path.lexists(search_index_path): try: os.remove(search_index_path) except OSError as e: logging.warning('Failed to remove search indexes file %r: %s', search_index_path, e)
null
null
null
What does the code take ?
def basic_auth_header(username, password): return (b('Basic %s') % base64.b64encode(to_bytes(('%s:%s' % (username, password)), errors='surrogate_or_strict')))
null
null
null
a username and password
codeqa
def basic auth header username password return b ' Basic%s' % base 64 b64 encode to bytes '%s %s' % username password errors 'surrogate or strict'
null
null
null
null
Question: What does the code take ? Code: def basic_auth_header(username, password): return (b('Basic %s') % base64.b64encode(to_bytes(('%s:%s' % (username, password)), errors='surrogate_or_strict')))
null
null
null
What does the code get ?
def get_member_names(group): return [r.name for r in get_members(group)]
null
null
null
a list of resource names of the resources in the specified group
codeqa
def get member names group return [r name for r in get members group ]
null
null
null
null
Question: What does the code get ? Code: def get_member_names(group): return [r.name for r in get_members(group)]
null
null
null
What does the code expand ?
def get_long_path_name(path): return _get_long_path_name(path)
null
null
null
a path
codeqa
def get long path name path return get long path name path
null
null
null
null
Question: What does the code expand ? Code: def get_long_path_name(path): return _get_long_path_name(path)
null
null
null
What does the code restart ?
def restart(): if (os.name == 'nt'): threading.Thread(target=_reexec).start() else: os.kill(server.pid, signal.SIGHUP)
null
null
null
the server
codeqa
def restart if os name 'nt' threading Thread target reexec start else os kill server pid signal SIGHUP
null
null
null
null
Question: What does the code restart ? Code: def restart(): if (os.name == 'nt'): threading.Thread(target=_reexec).start() else: os.kill(server.pid, signal.SIGHUP)
null
null
null
For what purpose do console start ?
@click.command(u'console') @pass_context def console(context): site = get_site(context) frappe.init(site=site) frappe.connect() frappe.local.lang = frappe.db.get_default(u'lang') import IPython IPython.embed()
null
null
null
for a site
codeqa
@click command u'console' @pass contextdef console context site get site context frappe init site site frappe connect frappe local lang frappe db get default u'lang' import I Python I Python embed
null
null
null
null
Question: For what purpose do console start ? Code: @click.command(u'console') @pass_context def console(context): site = get_site(context) frappe.init(site=site) frappe.connect() frappe.local.lang = frappe.db.get_default(u'lang') import IPython IPython.embed()
null
null
null
What does the code ensure ?
def absent(name, database, **client_args): ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'continuous query {0} is not present'.format(name)} if __salt__['influxdb.continuous_query_exists'](database, name, **client_args): if __opts__['test']: ret['result'] = None ret['comment'] = 'continuous query {0} is present and needs to be removed'.format(name) return ret if __salt__['influxdb.drop_continuous_query'](database, name, **client_args): ret['comment'] = 'continuous query {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret else: ret['comment'] = 'Failed to remove continuous query {0}'.format(name) ret['result'] = False return ret return ret
null
null
null
that given continuous query is absent
codeqa
def absent name database **client args ret {'name' name 'changes' {} 'result' True 'comment' 'continuousquery{ 0 }isnotpresent' format name }if salt ['influxdb continuous query exists'] database name **client args if opts ['test'] ret['result'] Noneret['comment'] 'continuousquery{ 0 }ispresentandneedstoberemoved' format name return retif salt ['influxdb drop continuous query'] database name **client args ret['comment'] 'continuousquery{ 0 }hasbeenremoved' format name ret['changes'][name] ' Absent'return retelse ret['comment'] ' Failedtoremovecontinuousquery{ 0 }' format name ret['result'] Falsereturn retreturn ret
null
null
null
null
Question: What does the code ensure ? Code: def absent(name, database, **client_args): ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'continuous query {0} is not present'.format(name)} if __salt__['influxdb.continuous_query_exists'](database, name, **client_args): if __opts__['test']: ret['result'] = None ret['comment'] = 'continuous query {0} is present and needs to be removed'.format(name) return ret if __salt__['influxdb.drop_continuous_query'](database, name, **client_args): ret['comment'] = 'continuous query {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret else: ret['comment'] = 'Failed to remove continuous query {0}'.format(name) ret['result'] = False return ret return ret
null
null
null
What does the code create on a specified network ?
def port_create(request, network_id, **kwargs): LOG.debug(('port_create(): netid=%s, kwargs=%s' % (network_id, kwargs))) body = {'port': {'network_id': network_id}} body['port'].update(kwargs) port = quantumclient(request).create_port(body=body).get('port') return Port(port)
null
null
null
a port
codeqa
def port create request network id **kwargs LOG debug 'port create netid %s kwargs %s' % network id kwargs body {'port' {'network id' network id}}body['port'] update kwargs port quantumclient request create port body body get 'port' return Port port
null
null
null
null
Question: What does the code create on a specified network ? Code: def port_create(request, network_id, **kwargs): LOG.debug(('port_create(): netid=%s, kwargs=%s' % (network_id, kwargs))) body = {'port': {'network_id': network_id}} body['port'].update(kwargs) port = quantumclient(request).create_port(body=body).get('port') return Port(port)
null
null
null
Where does the code create a port ?
def port_create(request, network_id, **kwargs): LOG.debug(('port_create(): netid=%s, kwargs=%s' % (network_id, kwargs))) body = {'port': {'network_id': network_id}} body['port'].update(kwargs) port = quantumclient(request).create_port(body=body).get('port') return Port(port)
null
null
null
on a specified network
codeqa
def port create request network id **kwargs LOG debug 'port create netid %s kwargs %s' % network id kwargs body {'port' {'network id' network id}}body['port'] update kwargs port quantumclient request create port body body get 'port' return Port port
null
null
null
null
Question: Where does the code create a port ? Code: def port_create(request, network_id, **kwargs): LOG.debug(('port_create(): netid=%s, kwargs=%s' % (network_id, kwargs))) body = {'port': {'network_id': network_id}} body['port'].update(kwargs) port = quantumclient(request).create_port(body=body).get('port') return Port(port)
null
null
null
For what purpose do a new task create ?
def group_albums(session): def group(item): return ((item.albumartist or item.artist), item.album) task = None while True: task = (yield task) if task.skip: continue tasks = [] for (_, items) in itertools.groupby(task.items, group): tasks.append(ImportTask(items=list(items))) tasks.append(SentinelImportTask(task.toppath, task.paths)) task = pipeline.multiple(tasks)
null
null
null
for each album
codeqa
def group albums session def group item return item albumartist or item artist item album task Nonewhile True task yield task if task skip continuetasks []for items in itertools groupby task items group tasks append Import Task items list items tasks append Sentinel Import Task task toppath task paths task pipeline multiple tasks
null
null
null
null
Question: For what purpose do a new task create ? Code: def group_albums(session): def group(item): return ((item.albumartist or item.artist), item.album) task = None while True: task = (yield task) if task.skip: continue tasks = [] for (_, items) in itertools.groupby(task.items, group): tasks.append(ImportTask(items=list(items))) tasks.append(SentinelImportTask(task.toppath, task.paths)) task = pipeline.multiple(tasks)
null
null
null
How do an image shift ?
def shift(x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.0): (h, w) = (x.shape[row_index], x.shape[col_index]) if is_random: tx = (np.random.uniform((- hrg), hrg) * h) ty = (np.random.uniform((- wrg), wrg) * w) else: (tx, ty) = ((hrg * h), (wrg * w)) translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]]) transform_matrix = translation_matrix x = apply_transform(x, transform_matrix, channel_index, fill_mode, cval) return x
null
null
null
randomly or non - randomly
codeqa
def shift x wrg 0 1 hrg 0 1 is random False row index 0 col index 1 channel index 2 fill mode 'nearest' cval 0 0 h w x shape[row index] x shape[col index] if is random tx np random uniform - hrg hrg * h ty np random uniform - wrg wrg * w else tx ty hrg * h wrg * w translation matrix np array [[ 1 0 tx] [0 1 ty] [0 0 1]] transform matrix translation matrixx apply transform x transform matrix channel index fill mode cval return x
null
null
null
null
Question: How do an image shift ? Code: def shift(x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.0): (h, w) = (x.shape[row_index], x.shape[col_index]) if is_random: tx = (np.random.uniform((- hrg), hrg) * h) ty = (np.random.uniform((- wrg), wrg) * w) else: (tx, ty) = ((hrg * h), (wrg * w)) translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]]) transform_matrix = translation_matrix x = apply_transform(x, transform_matrix, channel_index, fill_mode, cval) return x
null
null
null
What does the code update ?
def deep_update(source, overrides): if (sys.version_info >= (3, 0)): items = overrides.items() else: items = overrides.iteritems() for (key, value) in items: if (isinstance(value, collections.Mapping) and value): returned = deep_update(source.get(key, {}), value) source[key] = returned else: source[key] = overrides[key] return source
null
null
null
a nested dictionary or similar mapping
codeqa
def deep update source overrides if sys version info > 3 0 items overrides items else items overrides iteritems for key value in items if isinstance value collections Mapping and value returned deep update source get key {} value source[key] returnedelse source[key] overrides[key]return source
null
null
null
null
Question: What does the code update ? Code: def deep_update(source, overrides): if (sys.version_info >= (3, 0)): items = overrides.items() else: items = overrides.iteritems() for (key, value) in items: if (isinstance(value, collections.Mapping) and value): returned = deep_update(source.get(key, {}), value) source[key] = returned else: source[key] = overrides[key] return source
null
null
null
What do source field use ?
def forwards_move_org_source(apps, schema_editor): RemoteOrganization = apps.get_model(u'oauth', u'RemoteOrganization') SocialAccount = apps.get_model(u'socialaccount', u'SocialAccount') for account in SocialAccount.objects.all(): rows = RemoteOrganization.objects.filter(users=account.user, source=account.provider).update(account=account)
null
null
null
to set organization account
codeqa
def forwards move org source apps schema editor Remote Organization apps get model u'oauth' u' Remote Organization' Social Account apps get model u'socialaccount' u' Social Account' for account in Social Account objects all rows Remote Organization objects filter users account user source account provider update account account
null
null
null
null
Question: What do source field use ? Code: def forwards_move_org_source(apps, schema_editor): RemoteOrganization = apps.get_model(u'oauth', u'RemoteOrganization') SocialAccount = apps.get_model(u'socialaccount', u'SocialAccount') for account in SocialAccount.objects.all(): rows = RemoteOrganization.objects.filter(users=account.user, source=account.provider).update(account=account)
null
null
null
What uses to set organization account ?
def forwards_move_org_source(apps, schema_editor): RemoteOrganization = apps.get_model(u'oauth', u'RemoteOrganization') SocialAccount = apps.get_model(u'socialaccount', u'SocialAccount') for account in SocialAccount.objects.all(): rows = RemoteOrganization.objects.filter(users=account.user, source=account.provider).update(account=account)
null
null
null
source field
codeqa
def forwards move org source apps schema editor Remote Organization apps get model u'oauth' u' Remote Organization' Social Account apps get model u'socialaccount' u' Social Account' for account in Social Account objects all rows Remote Organization objects filter users account user source account provider update account account
null
null
null
null
Question: What uses to set organization account ? Code: def forwards_move_org_source(apps, schema_editor): RemoteOrganization = apps.get_model(u'oauth', u'RemoteOrganization') SocialAccount = apps.get_model(u'socialaccount', u'SocialAccount') for account in SocialAccount.objects.all(): rows = RemoteOrganization.objects.filter(users=account.user, source=account.provider).update(account=account)
null
null
null
What does the code convert into sets ?
def change_lists_to_sets(iterable): if isinstance(iterable, dict): for key in iterable: if isinstance(iterable[key], (list, tuple)): try: iterable[key] = set(iterable[key]) except TypeError: pass elif getattr(iterable[key], '__iter__', False): change_lists_to_sets(iterable[key]) elif isinstance(iterable, (list, tuple)): for item in iterable: if isinstance(item, (list, tuple)): iterable.pop(item) iterable.append(set(item)) elif getattr(item, '__iter__', False): change_lists_to_sets(item) else: raise NotImplementedError
null
null
null
any lists or tuples in iterable
codeqa
def change lists to sets iterable if isinstance iterable dict for key in iterable if isinstance iterable[key] list tuple try iterable[key] set iterable[key] except Type Error passelif getattr iterable[key] ' iter ' False change lists to sets iterable[key] elif isinstance iterable list tuple for item in iterable if isinstance item list tuple iterable pop item iterable append set item elif getattr item ' iter ' False change lists to sets item else raise Not Implemented Error
null
null
null
null
Question: What does the code convert into sets ? Code: def change_lists_to_sets(iterable): if isinstance(iterable, dict): for key in iterable: if isinstance(iterable[key], (list, tuple)): try: iterable[key] = set(iterable[key]) except TypeError: pass elif getattr(iterable[key], '__iter__', False): change_lists_to_sets(iterable[key]) elif isinstance(iterable, (list, tuple)): for item in iterable: if isinstance(item, (list, tuple)): iterable.pop(item) iterable.append(set(item)) elif getattr(item, '__iter__', False): change_lists_to_sets(item) else: raise NotImplementedError
null
null
null
What does the code send ?
def head(url, **kwargs): kwargs.setdefault('allow_redirects', False) return request('head', url, **kwargs)
null
null
null
a head request
codeqa
def head url **kwargs kwargs setdefault 'allow redirects' False return request 'head' url **kwargs
null
null
null
null
Question: What does the code send ? Code: def head(url, **kwargs): kwargs.setdefault('allow_redirects', False) return request('head', url, **kwargs)
null
null
null
What do functional test validate ?
def test_import_submodule_global_shadowed(pyi_builder): pyi_builder.test_source('\n # Assert that this submodule is shadowed by a string global variable.\n from pyi_testmod_submodule_global_shadowed import submodule\n assert type(submodule) == str\n\n # Assert that this submodule is still frozen into this test application.\n # To do so:\n #\n # 1. Delete this global variable from its parent package.\n # 2. Assert that this submodule is unshadowed by this global variable.\n import pyi_testmod_submodule_global_shadowed, sys\n del pyi_testmod_submodule_global_shadowed.submodule\n from pyi_testmod_submodule_global_shadowed import submodule\n assert type(submodule) == type(sys)\n ')
null
null
null
issue # 1919
codeqa
def test import submodule global shadowed pyi builder pyi builder test source '\n# Assertthatthissubmoduleisshadowedbyastringglobalvariable \nfrompyi testmod submodule global shadowedimportsubmodule\nasserttype submodule str\n\n# Assertthatthissubmoduleisstillfrozenintothistestapplication \n# Todoso \n#\n# 1 Deletethisglobalvariablefromitsparentpackage \n# 2 Assertthatthissubmoduleisunshadowedbythisglobalvariable \nimportpyi testmod submodule global shadowed sys\ndelpyi testmod submodule global shadowed submodule\nfrompyi testmod submodule global shadowedimportsubmodule\nasserttype submodule type sys \n'
null
null
null
null
Question: What do functional test validate ? Code: def test_import_submodule_global_shadowed(pyi_builder): pyi_builder.test_source('\n # Assert that this submodule is shadowed by a string global variable.\n from pyi_testmod_submodule_global_shadowed import submodule\n assert type(submodule) == str\n\n # Assert that this submodule is still frozen into this test application.\n # To do so:\n #\n # 1. Delete this global variable from its parent package.\n # 2. Assert that this submodule is unshadowed by this global variable.\n import pyi_testmod_submodule_global_shadowed, sys\n del pyi_testmod_submodule_global_shadowed.submodule\n from pyi_testmod_submodule_global_shadowed import submodule\n assert type(submodule) == type(sys)\n ')
null
null
null
What is validating issue # 1919 ?
def test_import_submodule_global_shadowed(pyi_builder): pyi_builder.test_source('\n # Assert that this submodule is shadowed by a string global variable.\n from pyi_testmod_submodule_global_shadowed import submodule\n assert type(submodule) == str\n\n # Assert that this submodule is still frozen into this test application.\n # To do so:\n #\n # 1. Delete this global variable from its parent package.\n # 2. Assert that this submodule is unshadowed by this global variable.\n import pyi_testmod_submodule_global_shadowed, sys\n del pyi_testmod_submodule_global_shadowed.submodule\n from pyi_testmod_submodule_global_shadowed import submodule\n assert type(submodule) == type(sys)\n ')
null
null
null
functional test
codeqa
def test import submodule global shadowed pyi builder pyi builder test source '\n# Assertthatthissubmoduleisshadowedbyastringglobalvariable \nfrompyi testmod submodule global shadowedimportsubmodule\nasserttype submodule str\n\n# Assertthatthissubmoduleisstillfrozenintothistestapplication \n# Todoso \n#\n# 1 Deletethisglobalvariablefromitsparentpackage \n# 2 Assertthatthissubmoduleisunshadowedbythisglobalvariable \nimportpyi testmod submodule global shadowed sys\ndelpyi testmod submodule global shadowed submodule\nfrompyi testmod submodule global shadowedimportsubmodule\nasserttype submodule type sys \n'
null
null
null
null
Question: What is validating issue # 1919 ? Code: def test_import_submodule_global_shadowed(pyi_builder): pyi_builder.test_source('\n # Assert that this submodule is shadowed by a string global variable.\n from pyi_testmod_submodule_global_shadowed import submodule\n assert type(submodule) == str\n\n # Assert that this submodule is still frozen into this test application.\n # To do so:\n #\n # 1. Delete this global variable from its parent package.\n # 2. Assert that this submodule is unshadowed by this global variable.\n import pyi_testmod_submodule_global_shadowed, sys\n del pyi_testmod_submodule_global_shadowed.submodule\n from pyi_testmod_submodule_global_shadowed import submodule\n assert type(submodule) == type(sys)\n ')
null
null
null
What does the code look ?
def lookup_object(spec): (parts, target) = (spec.split(':') if (':' in spec) else (spec, None)) module = __import__(parts) for part in (parts.split('.')[1:] + ([target] if target else [])): module = getattr(module, part) return module
null
null
null
a module or object from a some
codeqa
def lookup object spec parts target spec split ' ' if ' ' in spec else spec None module import parts for part in parts split ' ' [1 ] + [target] if target else [] module getattr module part return module
null
null
null
null
Question: What does the code look ? Code: def lookup_object(spec): (parts, target) = (spec.split(':') if (':' in spec) else (spec, None)) module = __import__(parts) for part in (parts.split('.')[1:] + ([target] if target else [])): module = getattr(module, part) return module
null
null
null
What does the code run on the input data ?
def bench_isotonic_regression(Y): gc.collect() tstart = datetime.now() isotonic_regression(Y) delta = (datetime.now() - tstart) return total_seconds(delta)
null
null
null
a single iteration of isotonic regression
codeqa
def bench isotonic regression Y gc collect tstart datetime now isotonic regression Y delta datetime now - tstart return total seconds delta
null
null
null
null
Question: What does the code run on the input data ? Code: def bench_isotonic_regression(Y): gc.collect() tstart = datetime.now() isotonic_regression(Y) delta = (datetime.now() - tstart) return total_seconds(delta)
null
null
null
Where does the code run a single iteration of isotonic regression ?
def bench_isotonic_regression(Y): gc.collect() tstart = datetime.now() isotonic_regression(Y) delta = (datetime.now() - tstart) return total_seconds(delta)
null
null
null
on the input data
codeqa
def bench isotonic regression Y gc collect tstart datetime now isotonic regression Y delta datetime now - tstart return total seconds delta
null
null
null
null
Question: Where does the code run a single iteration of isotonic regression ? Code: def bench_isotonic_regression(Y): gc.collect() tstart = datetime.now() isotonic_regression(Y) delta = (datetime.now() - tstart) return total_seconds(delta)
null
null
null
What splits into its package and resource name parts ?
def package_resource_name(name): if (PRN_SEPARATOR in name): val = tuple(name.split(PRN_SEPARATOR)) if (len(val) != 2): raise ValueError(('invalid name [%s]' % name)) else: return val else: return ('', name)
null
null
null
a name
codeqa
def package resource name name if PRN SEPARATOR in name val tuple name split PRN SEPARATOR if len val 2 raise Value Error 'invalidname[%s]' % name else return valelse return '' name
null
null
null
null
Question: What splits into its package and resource name parts ? Code: def package_resource_name(name): if (PRN_SEPARATOR in name): val = tuple(name.split(PRN_SEPARATOR)) if (len(val) != 2): raise ValueError(('invalid name [%s]' % name)) else: return val else: return ('', name)
null
null
null
What does the code display ?
def do_authentication(environ, start_response, authn_context, key, redirect_uri): logger.debug('Do authentication') auth_info = AUTHN_BROKER.pick(authn_context) if len(auth_info): (method, reference) = auth_info[0] logger.debug(('Authn chosen: %s (ref=%s)' % (method, reference))) return method(environ, start_response, reference, key, redirect_uri) else: resp = Unauthorized('No usable authentication method') return resp(environ, start_response)
null
null
null
the login form
codeqa
def do authentication environ start response authn context key redirect uri logger debug ' Doauthentication' auth info AUTHN BROKER pick authn context if len auth info method reference auth info[ 0 ]logger debug ' Authnchosen %s ref %s ' % method reference return method environ start response reference key redirect uri else resp Unauthorized ' Nousableauthenticationmethod' return resp environ start response
null
null
null
null
Question: What does the code display ? Code: def do_authentication(environ, start_response, authn_context, key, redirect_uri): logger.debug('Do authentication') auth_info = AUTHN_BROKER.pick(authn_context) if len(auth_info): (method, reference) = auth_info[0] logger.debug(('Authn chosen: %s (ref=%s)' % (method, reference))) return method(environ, start_response, reference, key, redirect_uri) else: resp = Unauthorized('No usable authentication method') return resp(environ, start_response)
null
null
null
What does the code create from the retrieved certificate data ?
def get_certificate(context, signature_certificate_uuid): keymgr_api = key_manager.API() try: cert = keymgr_api.get(context, signature_certificate_uuid) except KeyManagerError as e: msg = (_LE('Unable to retrieve certificate with ID %(id)s: %(e)s') % {'id': signature_certificate_uuid, 'e': encodeutils.exception_to_unicode(e)}) LOG.error(msg) raise exception.SignatureVerificationError(reason=(_('Unable to retrieve certificate with ID: %s') % signature_certificate_uuid)) if (cert.format not in CERTIFICATE_FORMATS): raise exception.SignatureVerificationError(reason=(_('Invalid certificate format: %s') % cert.format)) if (cert.format == X_509): cert_data = cert.get_encoded() certificate = x509.load_der_x509_certificate(cert_data, default_backend()) verify_certificate(certificate) return certificate
null
null
null
the certificate object
codeqa
def get certificate context signature certificate uuid keymgr api key manager API try cert keymgr api get context signature certificate uuid except Key Manager Error as e msg LE ' Unabletoretrievecertificatewith ID% id s % e s' % {'id' signature certificate uuid 'e' encodeutils exception to unicode e } LOG error msg raise exception Signature Verification Error reason ' Unabletoretrievecertificatewith ID %s' % signature certificate uuid if cert format not in CERTIFICATE FORMATS raise exception Signature Verification Error reason ' Invalidcertificateformat %s' % cert format if cert format X 509 cert data cert get encoded certificate x509 load der x509 certificate cert data default backend verify certificate certificate return certificate
null
null
null
null
Question: What does the code create from the retrieved certificate data ? Code: def get_certificate(context, signature_certificate_uuid): keymgr_api = key_manager.API() try: cert = keymgr_api.get(context, signature_certificate_uuid) except KeyManagerError as e: msg = (_LE('Unable to retrieve certificate with ID %(id)s: %(e)s') % {'id': signature_certificate_uuid, 'e': encodeutils.exception_to_unicode(e)}) LOG.error(msg) raise exception.SignatureVerificationError(reason=(_('Unable to retrieve certificate with ID: %s') % signature_certificate_uuid)) if (cert.format not in CERTIFICATE_FORMATS): raise exception.SignatureVerificationError(reason=(_('Invalid certificate format: %s') % cert.format)) if (cert.format == X_509): cert_data = cert.get_encoded() certificate = x509.load_der_x509_certificate(cert_data, default_backend()) verify_certificate(certificate) return certificate
null
null
null
How do integer increase ?
def getSerial(filename='/tmp/twisted-names.serial'): serial = time.strftime('%Y%m%d') o = os.umask(127) try: if (not os.path.exists(filename)): with open(filename, 'w') as f: f.write((serial + ' 0')) finally: os.umask(o) with open(filename, 'r') as serialFile: (lastSerial, zoneID) = serialFile.readline().split() zoneID = (((lastSerial == serial) and (int(zoneID) + 1)) or 0) with open(filename, 'w') as serialFile: serialFile.write(('%s %d' % (serial, zoneID))) serial = (serial + ('%02d' % (zoneID,))) return serial
null
null
null
monotonically
codeqa
def get Serial filename '/tmp/twisted-names serial' serial time strftime '%Y%m%d' o os umask 127 try if not os path exists filename with open filename 'w' as f f write serial + '0 ' finally os umask o with open filename 'r' as serial File last Serial zone ID serial File readline split zone ID last Serial serial and int zone ID + 1 or 0 with open filename 'w' as serial File serial File write '%s%d' % serial zone ID serial serial + '% 02 d' % zone ID return serial
null
null
null
null
Question: How do integer increase ? Code: def getSerial(filename='/tmp/twisted-names.serial'): serial = time.strftime('%Y%m%d') o = os.umask(127) try: if (not os.path.exists(filename)): with open(filename, 'w') as f: f.write((serial + ' 0')) finally: os.umask(o) with open(filename, 'r') as serialFile: (lastSerial, zoneID) = serialFile.readline().split() zoneID = (((lastSerial == serial) and (int(zoneID) + 1)) or 0) with open(filename, 'w') as serialFile: serialFile.write(('%s %d' % (serial, zoneID))) serial = (serial + ('%02d' % (zoneID,))) return serial
null
null
null
When does the code create an index of days ?
def days_at_time(days, t, tz, day_offset=0): if (len(days) == 0): return days days = DatetimeIndex(days).tz_localize(None) delta = pd.Timedelta(days=day_offset, hours=t.hour, minutes=t.minute, seconds=t.second) return (days + delta).tz_localize(tz).tz_convert('UTC')
null
null
null
at time t
codeqa
def days at time days t tz day offset 0 if len days 0 return daysdays Datetime Index days tz localize None delta pd Timedelta days day offset hours t hour minutes t minute seconds t second return days + delta tz localize tz tz convert 'UTC'
null
null
null
null
Question: When does the code create an index of days ? Code: def days_at_time(days, t, tz, day_offset=0): if (len(days) == 0): return days days = DatetimeIndex(days).tz_localize(None) delta = pd.Timedelta(days=day_offset, hours=t.hour, minutes=t.minute, seconds=t.second) return (days + delta).tz_localize(tz).tz_convert('UTC')
null
null
null
What does the code create at time t ?
def days_at_time(days, t, tz, day_offset=0): if (len(days) == 0): return days days = DatetimeIndex(days).tz_localize(None) delta = pd.Timedelta(days=day_offset, hours=t.hour, minutes=t.minute, seconds=t.second) return (days + delta).tz_localize(tz).tz_convert('UTC')
null
null
null
an index of days
codeqa
def days at time days t tz day offset 0 if len days 0 return daysdays Datetime Index days tz localize None delta pd Timedelta days day offset hours t hour minutes t minute seconds t second return days + delta tz localize tz tz convert 'UTC'
null
null
null
null
Question: What does the code create at time t ? Code: def days_at_time(days, t, tz, day_offset=0): if (len(days) == 0): return days days = DatetimeIndex(days).tz_localize(None) delta = pd.Timedelta(days=day_offset, hours=t.hour, minutes=t.minute, seconds=t.second) return (days + delta).tz_localize(tz).tz_convert('UTC')
null
null
null
What finds in statements ?
def _defined_names(current): names = [] if is_node(current, 'testlist_star_expr', 'testlist_comp', 'exprlist'): for child in current.children[::2]: names += _defined_names(child) elif is_node(current, 'atom', 'star_expr'): names += _defined_names(current.children[1]) elif is_node(current, 'power', 'atom_expr'): if (current.children[(-2)] != '**'): trailer = current.children[(-1)] if (trailer.children[0] == '.'): names.append(trailer.children[1]) else: names.append(current) return names
null
null
null
the defined names
codeqa
def defined names current names []if is node current 'testlist star expr' 'testlist comp' 'exprlist' for child in current children[ 2] names + defined names child elif is node current 'atom' 'star expr' names + defined names current children[ 1 ] elif is node current 'power' 'atom expr' if current children[ -2 ] '**' trailer current children[ -1 ]if trailer children[ 0 ] ' ' names append trailer children[ 1 ] else names append current return names
null
null
null
null
Question: What finds in statements ? Code: def _defined_names(current): names = [] if is_node(current, 'testlist_star_expr', 'testlist_comp', 'exprlist'): for child in current.children[::2]: names += _defined_names(child) elif is_node(current, 'atom', 'star_expr'): names += _defined_names(current.children[1]) elif is_node(current, 'power', 'atom_expr'): if (current.children[(-2)] != '**'): trailer = current.children[(-1)] if (trailer.children[0] == '.'): names.append(trailer.children[1]) else: names.append(current) return names
null
null
null
Where do the defined names find ?
def _defined_names(current): names = [] if is_node(current, 'testlist_star_expr', 'testlist_comp', 'exprlist'): for child in current.children[::2]: names += _defined_names(child) elif is_node(current, 'atom', 'star_expr'): names += _defined_names(current.children[1]) elif is_node(current, 'power', 'atom_expr'): if (current.children[(-2)] != '**'): trailer = current.children[(-1)] if (trailer.children[0] == '.'): names.append(trailer.children[1]) else: names.append(current) return names
null
null
null
in statements
codeqa
def defined names current names []if is node current 'testlist star expr' 'testlist comp' 'exprlist' for child in current children[ 2] names + defined names child elif is node current 'atom' 'star expr' names + defined names current children[ 1 ] elif is node current 'power' 'atom expr' if current children[ -2 ] '**' trailer current children[ -1 ]if trailer children[ 0 ] ' ' names append trailer children[ 1 ] else names append current return names
null
null
null
null
Question: Where do the defined names find ? Code: def _defined_names(current): names = [] if is_node(current, 'testlist_star_expr', 'testlist_comp', 'exprlist'): for child in current.children[::2]: names += _defined_names(child) elif is_node(current, 'atom', 'star_expr'): names += _defined_names(current.children[1]) elif is_node(current, 'power', 'atom_expr'): if (current.children[(-2)] != '**'): trailer = current.children[(-1)] if (trailer.children[0] == '.'): names.append(trailer.children[1]) else: names.append(current) return names
null
null
null
When did user log ?
def assert_request_user_is_system_admin(request): is_system_admin = request_user_is_system_admin(request=request) if (not is_system_admin): user_db = get_user_db_from_request(request=request) raise AccessDeniedError(message='System Administrator access required', user_db=user_db)
null
null
null
currently
codeqa
def assert request user is system admin request is system admin request user is system admin request request if not is system admin user db get user db from request request request raise Access Denied Error message ' System Administratoraccessrequired' user db user db
null
null
null
null
Question: When did user log ? Code: def assert_request_user_is_system_admin(request): is_system_admin = request_user_is_system_admin(request=request) if (not is_system_admin): user_db = get_user_db_from_request(request=request) raise AccessDeniedError(message='System Administrator access required', user_db=user_db)
null
null
null
What does the code get ?
def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement): if (len(loop) < 3): return [loop] radius = lineation.getRadiusByPrefix(prefix, sideLength, xmlElement) if (radius == 0.0): return loop bevelLoop = [] for pointIndex in xrange(len(loop)): begin = loop[(((pointIndex + len(loop)) - 1) % len(loop))] center = loop[pointIndex] end = loop[((pointIndex + 1) % len(loop))] bevelLoop += getBevelPath(begin, center, close, end, radius) return [euclidean.getLoopWithoutCloseSequentialPoints(close, bevelLoop)]
null
null
null
bevel loop
codeqa
def get Manipulated Paths close loop prefix side Length xml Element if len loop < 3 return [loop]radius lineation get Radius By Prefix prefix side Length xml Element if radius 0 0 return loopbevel Loop []for point Index in xrange len loop begin loop[ point Index + len loop - 1 % len loop ]center loop[point Index]end loop[ point Index + 1 % len loop ]bevel Loop + get Bevel Path begin center close end radius return [euclidean get Loop Without Close Sequential Points close bevel Loop ]
null
null
null
null
Question: What does the code get ? Code: def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement): if (len(loop) < 3): return [loop] radius = lineation.getRadiusByPrefix(prefix, sideLength, xmlElement) if (radius == 0.0): return loop bevelLoop = [] for pointIndex in xrange(len(loop)): begin = loop[(((pointIndex + len(loop)) - 1) % len(loop))] center = loop[pointIndex] end = loop[((pointIndex + 1) % len(loop))] bevelLoop += getBevelPath(begin, center, close, end, radius) return [euclidean.getLoopWithoutCloseSequentialPoints(close, bevelLoop)]
null
null
null
What does the code remove from the subversion repository from the subversion repository ?
def remove(cwd, targets, msg=None, user=None, username=None, password=None, *opts): if msg: opts += ('-m', msg) if targets: opts += tuple(salt.utils.shlex_split(targets)) return _run_svn('remove', cwd, user, username, password, opts)
null
null
null
files and directories
codeqa
def remove cwd targets msg None user None username None password None *opts if msg opts + '-m' msg if targets opts + tuple salt utils shlex split targets return run svn 'remove' cwd user username password opts
null
null
null
null
Question: What does the code remove from the subversion repository from the subversion repository ? Code: def remove(cwd, targets, msg=None, user=None, username=None, password=None, *opts): if msg: opts += ('-m', msg) if targets: opts += tuple(salt.utils.shlex_split(targets)) return _run_svn('remove', cwd, user, username, password, opts)
null
null
null
What ends in a newline ?
def endsInNewline(s): return (s[(- len('\n')):] == '\n')
null
null
null
this string
codeqa
def ends In Newline s return s[ - len '\n' ] '\n'
null
null
null
null
Question: What ends in a newline ? Code: def endsInNewline(s): return (s[(- len('\n')):] == '\n')
null
null
null
Where does this string end ?
def endsInNewline(s): return (s[(- len('\n')):] == '\n')
null
null
null
in a newline
codeqa
def ends In Newline s return s[ - len '\n' ] '\n'
null
null
null
null
Question: Where does this string end ? Code: def endsInNewline(s): return (s[(- len('\n')):] == '\n')
null
null
null
How do disjoint negative root isolation intervals compute ?
def dup_inner_isolate_negative_roots(f, K, inf=None, sup=None, eps=None, fast=False, mobius=False): if ((inf is not None) and (inf >= 0)): return [] roots = dup_inner_isolate_real_roots(dup_mirror(f, K), K, eps=eps, fast=fast) (F, results) = (K.get_field(), []) if ((inf is not None) or (sup is not None)): for (f, M) in roots: result = _discard_if_outside_interval(f, M, inf, sup, K, True, fast, mobius) if (result is not None): results.append(result) elif (not mobius): for (f, M) in roots: (u, v) = _mobius_to_interval(M, F) results.append(((- v), (- u))) else: results = roots return results
null
null
null
iteratively
codeqa
def dup inner isolate negative roots f K inf None sup None eps None fast False mobius False if inf is not None and inf > 0 return []roots dup inner isolate real roots dup mirror f K K eps eps fast fast F results K get field [] if inf is not None or sup is not None for f M in roots result discard if outside interval f M inf sup K True fast mobius if result is not None results append result elif not mobius for f M in roots u v mobius to interval M F results append - v - u else results rootsreturn results
null
null
null
null
Question: How do disjoint negative root isolation intervals compute ? Code: def dup_inner_isolate_negative_roots(f, K, inf=None, sup=None, eps=None, fast=False, mobius=False): if ((inf is not None) and (inf >= 0)): return [] roots = dup_inner_isolate_real_roots(dup_mirror(f, K), K, eps=eps, fast=fast) (F, results) = (K.get_field(), []) if ((inf is not None) or (sup is not None)): for (f, M) in roots: result = _discard_if_outside_interval(f, M, inf, sup, K, True, fast, mobius) if (result is not None): results.append(result) elif (not mobius): for (f, M) in roots: (u, v) = _mobius_to_interval(M, F) results.append(((- v), (- u))) else: results = roots return results
null
null
null
What do format spec convert ?
def _convert_fits2record(format): (repeat, dtype, option) = _parse_tformat(format) if (dtype in FITS2NUMPY): if (dtype == 'A'): output_format = (FITS2NUMPY[dtype] + str(repeat)) if ((format.lstrip()[0] == 'A') and (option != '')): output_format = (FITS2NUMPY[dtype] + str(int(option))) else: repeat_str = '' if (repeat != 1): repeat_str = str(repeat) output_format = (repeat_str + FITS2NUMPY[dtype]) elif (dtype == 'X'): output_format = _FormatX(repeat) elif (dtype == 'P'): output_format = _FormatP.from_tform(format) elif (dtype == 'Q'): output_format = _FormatQ.from_tform(format) elif (dtype == 'F'): output_format = 'f8' else: raise ValueError('Illegal format {}.'.format(format)) return output_format
null
null
null
to record format spec
codeqa
def convert fits 2 record format repeat dtype option parse tformat format if dtype in FITS 2 NUMPY if dtype 'A' output format FITS 2 NUMPY[dtype] + str repeat if format lstrip [0 ] 'A' and option '' output format FITS 2 NUMPY[dtype] + str int option else repeat str ''if repeat 1 repeat str str repeat output format repeat str + FITS 2 NUMPY[dtype] elif dtype 'X' output format Format X repeat elif dtype 'P' output format Format P from tform format elif dtype 'Q' output format Format Q from tform format elif dtype 'F' output format 'f 8 'else raise Value Error ' Illegalformat{} ' format format return output format
null
null
null
null
Question: What do format spec convert ? Code: def _convert_fits2record(format): (repeat, dtype, option) = _parse_tformat(format) if (dtype in FITS2NUMPY): if (dtype == 'A'): output_format = (FITS2NUMPY[dtype] + str(repeat)) if ((format.lstrip()[0] == 'A') and (option != '')): output_format = (FITS2NUMPY[dtype] + str(int(option))) else: repeat_str = '' if (repeat != 1): repeat_str = str(repeat) output_format = (repeat_str + FITS2NUMPY[dtype]) elif (dtype == 'X'): output_format = _FormatX(repeat) elif (dtype == 'P'): output_format = _FormatP.from_tform(format) elif (dtype == 'Q'): output_format = _FormatQ.from_tform(format) elif (dtype == 'F'): output_format = 'f8' else: raise ValueError('Illegal format {}.'.format(format)) return output_format
null
null
null
What converts to record format spec ?
def _convert_fits2record(format): (repeat, dtype, option) = _parse_tformat(format) if (dtype in FITS2NUMPY): if (dtype == 'A'): output_format = (FITS2NUMPY[dtype] + str(repeat)) if ((format.lstrip()[0] == 'A') and (option != '')): output_format = (FITS2NUMPY[dtype] + str(int(option))) else: repeat_str = '' if (repeat != 1): repeat_str = str(repeat) output_format = (repeat_str + FITS2NUMPY[dtype]) elif (dtype == 'X'): output_format = _FormatX(repeat) elif (dtype == 'P'): output_format = _FormatP.from_tform(format) elif (dtype == 'Q'): output_format = _FormatQ.from_tform(format) elif (dtype == 'F'): output_format = 'f8' else: raise ValueError('Illegal format {}.'.format(format)) return output_format
null
null
null
format spec
codeqa
def convert fits 2 record format repeat dtype option parse tformat format if dtype in FITS 2 NUMPY if dtype 'A' output format FITS 2 NUMPY[dtype] + str repeat if format lstrip [0 ] 'A' and option '' output format FITS 2 NUMPY[dtype] + str int option else repeat str ''if repeat 1 repeat str str repeat output format repeat str + FITS 2 NUMPY[dtype] elif dtype 'X' output format Format X repeat elif dtype 'P' output format Format P from tform format elif dtype 'Q' output format Format Q from tform format elif dtype 'F' output format 'f 8 'else raise Value Error ' Illegalformat{} ' format format return output format
null
null
null
null
Question: What converts to record format spec ? Code: def _convert_fits2record(format): (repeat, dtype, option) = _parse_tformat(format) if (dtype in FITS2NUMPY): if (dtype == 'A'): output_format = (FITS2NUMPY[dtype] + str(repeat)) if ((format.lstrip()[0] == 'A') and (option != '')): output_format = (FITS2NUMPY[dtype] + str(int(option))) else: repeat_str = '' if (repeat != 1): repeat_str = str(repeat) output_format = (repeat_str + FITS2NUMPY[dtype]) elif (dtype == 'X'): output_format = _FormatX(repeat) elif (dtype == 'P'): output_format = _FormatP.from_tform(format) elif (dtype == 'Q'): output_format = _FormatQ.from_tform(format) elif (dtype == 'F'): output_format = 'f8' else: raise ValueError('Illegal format {}.'.format(format)) return output_format
null
null
null
What does the code create ?
def _get_direct_filter_query(args): query = Q() for arg in args: if (hasattr(Document, arg) and args[arg]): append = Q(**{str((arg + '__id')): long(args[arg])}) query = (query & append) return query
null
null
null
a query to filter documents
codeqa
def get direct filter query args query Q for arg in args if hasattr Document arg and args[arg] append Q **{str arg + ' id' long args[arg] } query query & append return query
null
null
null
null
Question: What does the code create ? Code: def _get_direct_filter_query(args): query = Q() for arg in args: if (hasattr(Document, arg) and args[arg]): append = Q(**{str((arg + '__id')): long(args[arg])}) query = (query & append) return query
null
null
null
What does the code ensure ?
def compare(name, first, second, bfr): o = bfr[first.begin:first.end] c = bfr[second.begin:second.end] match = False if ((o == 'if') and (c == 'fi')): match = True elif ((o in BASH_KEYWORDS) and (c == 'done')): match = True elif ((o == 'case') and (c == 'esac')): match = True return match
null
null
null
correct open is paired with correct close
codeqa
def compare name first second bfr o bfr[first begin first end]c bfr[second begin second end]match Falseif o 'if' and c 'fi' match Trueelif o in BASH KEYWORDS and c 'done' match Trueelif o 'case' and c 'esac' match Truereturn match
null
null
null
null
Question: What does the code ensure ? Code: def compare(name, first, second, bfr): o = bfr[first.begin:first.end] c = bfr[second.begin:second.end] match = False if ((o == 'if') and (c == 'fi')): match = True elif ((o in BASH_KEYWORDS) and (c == 'done')): match = True elif ((o == 'case') and (c == 'esac')): match = True return match
null
null
null
What does the code retrieve ?
def get_enrollment_attributes(user_id, course_id): return _ENROLLMENT_ATTRIBUTES
null
null
null
enrollment attribute array
codeqa
def get enrollment attributes user id course id return ENROLLMENT ATTRIBUTES
null
null
null
null
Question: What does the code retrieve ? Code: def get_enrollment_attributes(user_id, course_id): return _ENROLLMENT_ATTRIBUTES
null
null
null
What does the code add to a server ?
@api_versions.wraps('2.26') @utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('tag', metavar='<tag>', nargs='+', help=_('Tag(s) to add.')) def do_server_tag_add(cs, args): server = _find_server(cs, args.server) utils.do_action_on_many((lambda t: server.add_tag(t)), args.tag, _('Request to add tag %s to specified server has been accepted.'), _('Unable to add tag %s to the specified server.'))
null
null
null
one or more tags
codeqa
@api versions wraps '2 26 ' @utils arg 'server' metavar '<server>' help ' Nameor I Dofserver ' @utils arg 'tag' metavar '<tag>' nargs '+' help ' Tag s toadd ' def do server tag add cs args server find server cs args server utils do action on many lambda t server add tag t args tag ' Requesttoaddtag%stospecifiedserverhasbeenaccepted ' ' Unabletoaddtag%stothespecifiedserver '
null
null
null
null
Question: What does the code add to a server ? Code: @api_versions.wraps('2.26') @utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('tag', metavar='<tag>', nargs='+', help=_('Tag(s) to add.')) def do_server_tag_add(cs, args): server = _find_server(cs, args.server) utils.do_action_on_many((lambda t: server.add_tag(t)), args.tag, _('Request to add tag %s to specified server has been accepted.'), _('Unable to add tag %s to the specified server.'))
null
null
null
What does the code extract ?
def head_splitter(headfile, remote, module=None, fail_on_error=False): res = None if os.path.exists(headfile): rawdata = None try: f = open(headfile, 'r') rawdata = f.readline() f.close() except: if (fail_on_error and module): module.fail_json(msg=('Unable to read %s' % headfile)) if rawdata: try: rawdata = rawdata.replace(('refs/remotes/%s' % remote), '', 1) refparts = rawdata.split(' ') newref = refparts[(-1)] nrefparts = newref.split('/', 2) res = nrefparts[(-1)].rstrip('\n') except: if (fail_on_error and module): module.fail_json(msg=("Unable to split head from '%s'" % rawdata)) return res
null
null
null
the head reference
codeqa
def head splitter headfile remote module None fail on error False res Noneif os path exists headfile rawdata Nonetry f open headfile 'r' rawdata f readline f close except if fail on error and module module fail json msg ' Unabletoread%s' % headfile if rawdata try rawdata rawdata replace 'refs/remotes/%s' % remote '' 1 refparts rawdata split '' newref refparts[ -1 ]nrefparts newref split '/' 2 res nrefparts[ -1 ] rstrip '\n' except if fail on error and module module fail json msg " Unabletosplitheadfrom'%s'" % rawdata return res
null
null
null
null
Question: What does the code extract ? Code: def head_splitter(headfile, remote, module=None, fail_on_error=False): res = None if os.path.exists(headfile): rawdata = None try: f = open(headfile, 'r') rawdata = f.readline() f.close() except: if (fail_on_error and module): module.fail_json(msg=('Unable to read %s' % headfile)) if rawdata: try: rawdata = rawdata.replace(('refs/remotes/%s' % remote), '', 1) refparts = rawdata.split(' ') newref = refparts[(-1)] nrefparts = newref.split('/', 2) res = nrefparts[(-1)].rstrip('\n') except: if (fail_on_error and module): module.fail_json(msg=("Unable to split head from '%s'" % rawdata)) return res
null
null
null
What does the code tell if the string looks like a revision i d or not ?
def is_id(id_string): reg_ex = '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' return bool(re.match(reg_ex, id_string))
null
null
null
the client
codeqa
def is id id string reg ex '^[ 0 - 9 a-f]{ 8 }-[ 0 - 9 a-f]{ 4 }-[ 0 - 9 a-f]{ 4 }-[ 0 - 9 a-f]{ 4 }-[ 0 - 9 a-f]{ 12 }$'return bool re match reg ex id string
null
null
null
null
Question: What does the code tell if the string looks like a revision i d or not ? Code: def is_id(id_string): reg_ex = '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' return bool(re.match(reg_ex, id_string))
null
null
null
What does the code create ?
def make_suite(path=test_dir): loader = unittest.TestLoader() python_module_names = get_python_module_names(os.listdir(path)) test_module_names = get_test_module_names(python_module_names) suite = loader.loadTestsFromNames(test_module_names) return suite
null
null
null
the test suite
codeqa
def make suite path test dir loader unittest Test Loader python module names get python module names os listdir path test module names get test module names python module names suite loader load Tests From Names test module names return suite
null
null
null
null
Question: What does the code create ? Code: def make_suite(path=test_dir): loader = unittest.TestLoader() python_module_names = get_python_module_names(os.listdir(path)) test_module_names = get_test_module_names(python_module_names) suite = loader.loadTestsFromNames(test_module_names) return suite
null
null
null
How do all kinds return ?
def get_kinds(start=None, end=None): q = Kind.all() if ((start is not None) and (start != '')): q.filter('__key__ >=', Kind.key_for_kind(start)) if (end is not None): if (end == ''): return [] q.filter('__key__ <', Kind.key_for_kind(end)) return [x.kind_name for x in q.run()]
null
null
null
in the specified range
codeqa
def get kinds start None end None q Kind all if start is not None and start '' q filter ' key > ' Kind key for kind start if end is not None if end '' return []q filter ' key <' Kind key for kind end return [x kind name for x in q run ]
null
null
null
null
Question: How do all kinds return ? Code: def get_kinds(start=None, end=None): q = Kind.all() if ((start is not None) and (start != '')): q.filter('__key__ >=', Kind.key_for_kind(start)) if (end is not None): if (end == ''): return [] q.filter('__key__ <', Kind.key_for_kind(end)) return [x.kind_name for x in q.run()]
null
null
null
What does the fast parser splitting count ?
def test_fake_parentheses(): src = dedent("\n def x():\n a = (')'\n if 1 else 2)\n def y():\n pass\n def z():\n pass\n ") check_fp(src, 3, 2, 1)
null
null
null
parentheses
codeqa
def test fake parentheses src dedent "\ndefx \na ' '\nif 1 else 2 \ndefy \npass\ndefz \npass\n" check fp src 3 2 1
null
null
null
null
Question: What does the fast parser splitting count ? Code: def test_fake_parentheses(): src = dedent("\n def x():\n a = (')'\n if 1 else 2)\n def y():\n pass\n def z():\n pass\n ") check_fp(src, 3, 2, 1)
null
null
null
What adds environment variables to the whole build process ?
def env_file(registry, xml_parent, data): eib = XML.SubElement(xml_parent, 'hudson.plugins.envfile.EnvFileBuildWrapper') jenkins_jobs.modules.base.add_nonblank_xml_subelement(eib, 'filePath', data.get('properties-file'))
null
null
null
env - file
codeqa
def env file registry xml parent data eib XML Sub Element xml parent 'hudson plugins envfile Env File Build Wrapper' jenkins jobs modules base add nonblank xml subelement eib 'file Path' data get 'properties-file'
null
null
null
null
Question: What adds environment variables to the whole build process ? Code: def env_file(registry, xml_parent, data): eib = XML.SubElement(xml_parent, 'hudson.plugins.envfile.EnvFileBuildWrapper') jenkins_jobs.modules.base.add_nonblank_xml_subelement(eib, 'filePath', data.get('properties-file'))
null
null
null
What do env - file add to the whole build process ?
def env_file(registry, xml_parent, data): eib = XML.SubElement(xml_parent, 'hudson.plugins.envfile.EnvFileBuildWrapper') jenkins_jobs.modules.base.add_nonblank_xml_subelement(eib, 'filePath', data.get('properties-file'))
null
null
null
environment variables
codeqa
def env file registry xml parent data eib XML Sub Element xml parent 'hudson plugins envfile Env File Build Wrapper' jenkins jobs modules base add nonblank xml subelement eib 'file Path' data get 'properties-file'
null
null
null
null
Question: What do env - file add to the whole build process ? Code: def env_file(registry, xml_parent, data): eib = XML.SubElement(xml_parent, 'hudson.plugins.envfile.EnvFileBuildWrapper') jenkins_jobs.modules.base.add_nonblank_xml_subelement(eib, 'filePath', data.get('properties-file'))
null
null
null
What does the code get from a device object ?
def get_device(*args): for arg in args: if (type(arg) in _integer_types): check_cuda_available() return Device(arg) if isinstance(arg, ndarray): if (arg.device is None): continue return arg.device if (available and isinstance(arg, Device)): return arg return DummyDevice
null
null
null
the device
codeqa
def get device *args for arg in args if type arg in integer types check cuda available return Device arg if isinstance arg ndarray if arg device is None continuereturn arg deviceif available and isinstance arg Device return argreturn Dummy Device
null
null
null
null
Question: What does the code get from a device object ? Code: def get_device(*args): for arg in args: if (type(arg) in _integer_types): check_cuda_available() return Device(arg) if isinstance(arg, ndarray): if (arg.device is None): continue return arg.device if (available and isinstance(arg, Device)): return arg return DummyDevice
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 chop dialog
codeqa
def main if len sys argv > 1 write Output '' join sys argv[ 1 ] else settings start Main Loop From Constructor get New Repository
null
null
null
null
Question: What does the code display ? Code: def main(): if (len(sys.argv) > 1): writeOutput(' '.join(sys.argv[1:])) else: settings.startMainLoopFromConstructor(getNewRepository())
null
null
null
What does the code add ?
def sources_add(source_uri, ruby=None, runas=None, gem_bin=None): return _gem(['sources', '--add', source_uri], ruby, gem_bin=gem_bin, runas=runas)
null
null
null
a gem source
codeqa
def sources add source uri ruby None runas None gem bin None return gem ['sources' '--add' source uri] ruby gem bin gem bin runas runas
null
null
null
null
Question: What does the code add ? Code: def sources_add(source_uri, ruby=None, runas=None, gem_bin=None): return _gem(['sources', '--add', source_uri], ruby, gem_bin=gem_bin, runas=runas)
null
null
null
In which direction did the content type pass ?
def content_type(transformers, default=None): transformers = {content_type: (auto_kwargs(transformer) if transformer else transformer) for (content_type, transformer) in transformers.items()} default = (default and auto_kwargs(default)) def transform(data, request): transformer = transformers.get(request.content_type.split(';')[0], default) if (not transformer): return data return transformer(data) return transform
null
null
null
in
codeqa
def content type transformers default None transformers {content type auto kwargs transformer if transformer else transformer for content type transformer in transformers items }default default and auto kwargs default def transform data request transformer transformers get request content type split ' ' [0 ] default if not transformer return datareturn transformer data return transform
null
null
null
null
Question: In which direction did the content type pass ? Code: def content_type(transformers, default=None): transformers = {content_type: (auto_kwargs(transformer) if transformer else transformer) for (content_type, transformer) in transformers.items()} default = (default and auto_kwargs(default)) def transform(data, request): transformer = transformers.get(request.content_type.split(';')[0], default) if (not transformer): return data return transformer(data) return transform
null
null
null
How does a file open depending on whether it is a ?
def get_cmd(some_file, notebook_options=''): if some_file.endswith('.py'): command = 'python' elif some_file.endswith('.ipynb'): command = ('ipython notebook %s' % notebook_options) return command
null
null
null
how
codeqa
def get cmd some file notebook options '' if some file endswith ' py' command 'python'elif some file endswith ' ipynb' command 'ipythonnotebook%s' % notebook options return command
null
null
null
null
Question: How does a file open depending on whether it is a ? Code: def get_cmd(some_file, notebook_options=''): if some_file.endswith('.py'): command = 'python' elif some_file.endswith('.ipynb'): command = ('ipython notebook %s' % notebook_options) return command
null
null
null
What did the code set ?
@profiler.trace def flavor_extra_set(request, flavor_id, metadata): flavor = novaclient(request).flavors.get(flavor_id) if (not metadata): return None return flavor.set_keys(metadata)
null
null
null
the flavor extra spec keys
codeqa
@profiler tracedef flavor extra set request flavor id metadata flavor novaclient request flavors get flavor id if not metadata return Nonereturn flavor set keys metadata
null
null
null
null
Question: What did the code set ? Code: @profiler.trace def flavor_extra_set(request, flavor_id, metadata): flavor = novaclient(request).flavors.get(flavor_id) if (not metadata): return None return flavor.set_keys(metadata)
null
null
null
What did the code use ?
def blueprint_is_module(bp): return isinstance(bp, Module)
null
null
null
to figure out if something is actually a module
codeqa
def blueprint is module bp return isinstance bp Module
null
null
null
null
Question: What did the code use ? Code: def blueprint_is_module(bp): return isinstance(bp, Module)
null
null
null
What does the code get ?
def get_region(): return (parse_region(getattr(_local, 'region', '')) or RESTOFWORLD)
null
null
null
the region for the current request lifecycle
codeqa
def get region return parse region getattr local 'region' '' or RESTOFWORLD
null
null
null
null
Question: What does the code get ? Code: def get_region(): return (parse_region(getattr(_local, 'region', '')) or RESTOFWORLD)
null
null
null
What did the code read ?
def swift_load_pack_index(scon, filename): f = scon.get_object(filename) try: return load_pack_index_file(filename, f) finally: f.close()
null
null
null
a pack index file
codeqa
def swift load pack index scon filename f scon get object filename try return load pack index file filename f finally f close
null
null
null
null
Question: What did the code read ? Code: def swift_load_pack_index(scon, filename): f = scon.get_object(filename) try: return load_pack_index_file(filename, f) finally: f.close()
null
null
null
What does the code update ?
def build_requirements(docs_path, package_name=u'mezzanine'): mezz_string = u'Mezzanine==' project_path = os.path.join(docs_path, u'..') requirements_file = os.path.join(project_path, package_name, u'project_template', u'requirements.txt') with open(requirements_file, u'r') as f: requirements = f.readlines() with open(requirements_file, u'w') as f: f.write((u'Mezzanine==%s\n' % __version__)) for requirement in requirements: if (requirement.strip() and (not requirement.startswith(mezz_string))): f.write(requirement)
null
null
null
the requirements file with mezzanines version number
codeqa
def build requirements docs path package name u'mezzanine' mezz string u' Mezzanine 'project path os path join docs path u' ' requirements file os path join project path package name u'project template' u'requirements txt' with open requirements file u'r' as f requirements f readlines with open requirements file u'w' as f f write u' Mezzanine %s\n' % version for requirement in requirements if requirement strip and not requirement startswith mezz string f write requirement
null
null
null
null
Question: What does the code update ? Code: def build_requirements(docs_path, package_name=u'mezzanine'): mezz_string = u'Mezzanine==' project_path = os.path.join(docs_path, u'..') requirements_file = os.path.join(project_path, package_name, u'project_template', u'requirements.txt') with open(requirements_file, u'r') as f: requirements = f.readlines() with open(requirements_file, u'w') as f: f.write((u'Mezzanine==%s\n' % __version__)) for requirement in requirements: if (requirement.strip() and (not requirement.startswith(mezz_string))): f.write(requirement)
null
null
null
What is containing coffee files ?
def coffeescript_files(): dirs = ' '.join(((Env.REPO_ROOT / coffee_dir) for coffee_dir in COFFEE_DIRS)) return cmd('find', dirs, '-type f', '-name "*.coffee"')
null
null
null
paths
codeqa
def coffeescript files dirs '' join Env REPO ROOT / coffee dir for coffee dir in COFFEE DIRS return cmd 'find' dirs '-typef' '-name"* coffee"'
null
null
null
null
Question: What is containing coffee files ? Code: def coffeescript_files(): dirs = ' '.join(((Env.REPO_ROOT / coffee_dir) for coffee_dir in COFFEE_DIRS)) return cmd('find', dirs, '-type f', '-name "*.coffee"')
null
null
null
What do paths contain ?
def coffeescript_files(): dirs = ' '.join(((Env.REPO_ROOT / coffee_dir) for coffee_dir in COFFEE_DIRS)) return cmd('find', dirs, '-type f', '-name "*.coffee"')
null
null
null
coffee files
codeqa
def coffeescript files dirs '' join Env REPO ROOT / coffee dir for coffee dir in COFFEE DIRS return cmd 'find' dirs '-typef' '-name"* coffee"'
null
null
null
null
Question: What do paths contain ? Code: def coffeescript_files(): dirs = ' '.join(((Env.REPO_ROOT / coffee_dir) for coffee_dir in COFFEE_DIRS)) return cmd('find', dirs, '-type f', '-name "*.coffee"')
null
null
null
When do you be ?
def changequery(**kw): query = input(_method='get') for (k, v) in kw.iteritems(): if (v is None): query.pop(k, None) else: query[k] = v out = ctx.path if query: out += ('?' + urllib.urlencode(query)) return out
null
null
null
at /foo?a=1&b=2
codeqa
def changequery **kw query input method 'get' for k v in kw iteritems if v is None query pop k None else query[k] vout ctx pathif query out + '?' + urllib urlencode query return out
null
null
null
null
Question: When do you be ? Code: def changequery(**kw): query = input(_method='get') for (k, v) in kw.iteritems(): if (v is None): query.pop(k, None) else: query[k] = v out = ctx.path if query: out += ('?' + urllib.urlencode(query)) return out
null
null
null
What does the code generate ?
def listCoordinates(filename): coords = (line.strip().split('/') for line in open(filename, 'r')) coords = (map(int, (row, column, zoom)) for (zoom, column, row) in coords) coords = [Coordinate(*args) for args in coords] count = len(coords) for (offset, coord) in enumerate(coords): (yield (offset, count, coord))
null
null
null
a stream of tuples for seeding
codeqa
def list Coordinates filename coords line strip split '/' for line in open filename 'r' coords map int row column zoom for zoom column row in coords coords [ Coordinate *args for args in coords]count len coords for offset coord in enumerate coords yield offset count coord
null
null
null
null
Question: What does the code generate ? Code: def listCoordinates(filename): coords = (line.strip().split('/') for line in open(filename, 'r')) coords = (map(int, (row, column, zoom)) for (zoom, column, row) in coords) coords = [Coordinate(*args) for args in coords] count = len(coords) for (offset, coord) in enumerate(coords): (yield (offset, count, coord))
null
null
null
How does the code manage the authentication keys ?
def salt_key(): import salt.cli.key try: client = salt.cli.key.SaltKey() _install_signal_handlers(client) client.run() except Exception as err: sys.stderr.write('Error: {0}\n'.format(err))
null
null
null
with salt - key
codeqa
def salt key import salt cli keytry client salt cli key Salt Key install signal handlers client client run except Exception as err sys stderr write ' Error {0 }\n' format err
null
null
null
null
Question: How does the code manage the authentication keys ? Code: def salt_key(): import salt.cli.key try: client = salt.cli.key.SaltKey() _install_signal_handlers(client) client.run() except Exception as err: sys.stderr.write('Error: {0}\n'.format(err))
null
null
null
What does the code manage with salt - key ?
def salt_key(): import salt.cli.key try: client = salt.cli.key.SaltKey() _install_signal_handlers(client) client.run() except Exception as err: sys.stderr.write('Error: {0}\n'.format(err))
null
null
null
the authentication keys
codeqa
def salt key import salt cli keytry client salt cli key Salt Key install signal handlers client client run except Exception as err sys stderr write ' Error {0 }\n' format err
null
null
null
null
Question: What does the code manage with salt - key ? Code: def salt_key(): import salt.cli.key try: client = salt.cli.key.SaltKey() _install_signal_handlers(client) client.run() except Exception as err: sys.stderr.write('Error: {0}\n'.format(err))
null
null
null
What does the code calculate ?
def _sigma(values): return math.sqrt(_variance(values))
null
null
null
the sigma for a list of integers
codeqa
def sigma values return math sqrt variance values
null
null
null
null
Question: What does the code calculate ? Code: def _sigma(values): return math.sqrt(_variance(values))
null
null
null
Where did binary number write ?
def bin2long(text, endian): assert (endian in (LITTLE_ENDIAN, BIG_ENDIAN)) bits = [(ord(character) - ord('0')) for character in text if (character in '01')] assert (len(bits) != 0) if (endian is not BIG_ENDIAN): bits = reversed(bits) value = 0 for bit in bits: value *= 2 value += bit return value
null
null
null
in a string
codeqa
def bin 2 long text endian assert endian in LITTLE ENDIAN BIG ENDIAN bits [ ord character - ord '0 ' for character in text if character in '01 ' ]assert len bits 0 if endian is not BIG ENDIAN bits reversed bits value 0for bit in bits value * 2value + bitreturn value
null
null
null
null
Question: Where did binary number write ? Code: def bin2long(text, endian): assert (endian in (LITTLE_ENDIAN, BIG_ENDIAN)) bits = [(ord(character) - ord('0')) for character in text if (character in '01')] assert (len(bits) != 0) if (endian is not BIG_ENDIAN): bits = reversed(bits) value = 0 for bit in bits: value *= 2 value += bit return value
null
null
null
What written in a string ?
def bin2long(text, endian): assert (endian in (LITTLE_ENDIAN, BIG_ENDIAN)) bits = [(ord(character) - ord('0')) for character in text if (character in '01')] assert (len(bits) != 0) if (endian is not BIG_ENDIAN): bits = reversed(bits) value = 0 for bit in bits: value *= 2 value += bit return value
null
null
null
binary number
codeqa
def bin 2 long text endian assert endian in LITTLE ENDIAN BIG ENDIAN bits [ ord character - ord '0 ' for character in text if character in '01 ' ]assert len bits 0 if endian is not BIG ENDIAN bits reversed bits value 0for bit in bits value * 2value + bitreturn value
null
null
null
null
Question: What written in a string ? Code: def bin2long(text, endian): assert (endian in (LITTLE_ENDIAN, BIG_ENDIAN)) bits = [(ord(character) - ord('0')) for character in text if (character in '01')] assert (len(bits) != 0) if (endian is not BIG_ENDIAN): bits = reversed(bits) value = 0 for bit in bits: value *= 2 value += bit return value
null
null
null
What does the code retrieve ?
@db_api.retry_if_session_inactive() def get_reservations_for_resources(context, tenant_id, resources, expired=False): if (not resources): return now = utcnow() resv_query = context.session.query(quota_models.ResourceDelta.resource, quota_models.Reservation.expiration, sql.func.sum(quota_models.ResourceDelta.amount)).join(quota_models.Reservation) if expired: exp_expr = (quota_models.Reservation.expiration < now) else: exp_expr = (quota_models.Reservation.expiration >= now) resv_query = resv_query.filter(sa.and_((quota_models.Reservation.tenant_id == tenant_id), quota_models.ResourceDelta.resource.in_(resources), exp_expr)).group_by(quota_models.ResourceDelta.resource, quota_models.Reservation.expiration) return dict(((resource, total_reserved) for (resource, exp, total_reserved) in resv_query))
null
null
null
total amount of reservations for specified resources
codeqa
@db api retry if session inactive def get reservations for resources context tenant id resources expired False if not resources returnnow utcnow resv query context session query quota models Resource Delta resource quota models Reservation expiration sql func sum quota models Resource Delta amount join quota models Reservation if expired exp expr quota models Reservation expiration < now else exp expr quota models Reservation expiration > now resv query resv query filter sa and quota models Reservation tenant id tenant id quota models Resource Delta resource in resources exp expr group by quota models Resource Delta resource quota models Reservation expiration return dict resource total reserved for resource exp total reserved in resv query
null
null
null
null
Question: What does the code retrieve ? Code: @db_api.retry_if_session_inactive() def get_reservations_for_resources(context, tenant_id, resources, expired=False): if (not resources): return now = utcnow() resv_query = context.session.query(quota_models.ResourceDelta.resource, quota_models.Reservation.expiration, sql.func.sum(quota_models.ResourceDelta.amount)).join(quota_models.Reservation) if expired: exp_expr = (quota_models.Reservation.expiration < now) else: exp_expr = (quota_models.Reservation.expiration >= now) resv_query = resv_query.filter(sa.and_((quota_models.Reservation.tenant_id == tenant_id), quota_models.ResourceDelta.resource.in_(resources), exp_expr)).group_by(quota_models.ResourceDelta.resource, quota_models.Reservation.expiration) return dict(((resource, total_reserved) for (resource, exp, total_reserved) in resv_query))
null
null
null
When does your preferred format set ?
@commands(u'settimeformat', u'settf') @example(u'.settf %Y-%m-%dT%T%z') def update_user_format(bot, trigger): tformat = trigger.group(2) if (not tformat): bot.reply(u'What format do you want me to use? Try using http://strftime.net to make one.') return tz = get_timezone(bot.db, bot.config, None, trigger.nick, trigger.sender) old_format = bot.db.get_nick_value(trigger.nick, u'time_format') bot.db.set_nick_value(trigger.nick, u'time_format', tformat) try: timef = format_time(db=bot.db, zone=tz, nick=trigger.nick) except: bot.reply(u"That format doesn't work. Try using http://strftime.net to make one.") bot.db.set_nick_value(trigger.nick, u'time_format', old_format) return bot.reply((u'Got it. Your time will now appear as %s. (If the timezone is wrong, you might try the settz command)' % timef))
null
null
null
for time
codeqa
@commands u'settimeformat' u'settf' @example u' settf%Y-%m-%d T%T%z' def update user format bot trigger tformat trigger group 2 if not tformat bot reply u' Whatformatdoyouwantmetouse? Tryusinghttp //strftime nettomakeone ' returntz get timezone bot db bot config None trigger nick trigger sender old format bot db get nick value trigger nick u'time format' bot db set nick value trigger nick u'time format' tformat try timef format time db bot db zone tz nick trigger nick except bot reply u" Thatformatdoesn'twork Tryusinghttp //strftime nettomakeone " bot db set nick value trigger nick u'time format' old format returnbot reply u' Gotit Yourtimewillnowappearas%s Ifthetimezoneiswrong youmighttrythesettzcommand ' % timef
null
null
null
null
Question: When does your preferred format set ? Code: @commands(u'settimeformat', u'settf') @example(u'.settf %Y-%m-%dT%T%z') def update_user_format(bot, trigger): tformat = trigger.group(2) if (not tformat): bot.reply(u'What format do you want me to use? Try using http://strftime.net to make one.') return tz = get_timezone(bot.db, bot.config, None, trigger.nick, trigger.sender) old_format = bot.db.get_nick_value(trigger.nick, u'time_format') bot.db.set_nick_value(trigger.nick, u'time_format', tformat) try: timef = format_time(db=bot.db, zone=tz, nick=trigger.nick) except: bot.reply(u"That format doesn't work. Try using http://strftime.net to make one.") bot.db.set_nick_value(trigger.nick, u'time_format', old_format) return bot.reply((u'Got it. Your time will now appear as %s. (If the timezone is wrong, you might try the settz command)' % timef))
null
null
null
What does the code stop ?
def _chain_stop_result(service, stop): maybeDeferred(service.stopService).chainDeferred(stop)
null
null
null
a service and chain
codeqa
def chain stop result service stop maybe Deferred service stop Service chain Deferred stop
null
null
null
null
Question: What does the code stop ? Code: def _chain_stop_result(service, stop): maybeDeferred(service.stopService).chainDeferred(stop)
null
null
null
What does the code get ?
def _get_vm_mdo(vm_ref): if (_db_content.get('VirtualMachine', None) is None): raise exception.NotFound('There is no VM registered') if (vm_ref not in _db_content.get('VirtualMachine')): raise exception.NotFound(('Virtual Machine with ref %s is not there' % vm_ref)) return _db_content.get('VirtualMachine')[vm_ref]
null
null
null
the virtual machine with the ref from the db
codeqa
def get vm mdo vm ref if db content get ' Virtual Machine' None is None raise exception Not Found ' Thereisno V Mregistered' if vm ref not in db content get ' Virtual Machine' raise exception Not Found ' Virtual Machinewithref%sisnotthere' % vm ref return db content get ' Virtual Machine' [vm ref]
null
null
null
null
Question: What does the code get ? Code: def _get_vm_mdo(vm_ref): if (_db_content.get('VirtualMachine', None) is None): raise exception.NotFound('There is no VM registered') if (vm_ref not in _db_content.get('VirtualMachine')): raise exception.NotFound(('Virtual Machine with ref %s is not there' % vm_ref)) return _db_content.get('VirtualMachine')[vm_ref]