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 take ?
def convert_time_to_utc(timestr): combined = datetime.combine(dt_util.start_of_local_day(), dt_util.parse_time(timestr)) if (combined < datetime.now()): combined = (combined + timedelta(days=1)) return dt_util.as_timestamp(combined)
null
null
null
a string
codeqa
def convert time to utc timestr combined datetime combine dt util start of local day dt util parse time timestr if combined < datetime now combined combined + timedelta days 1 return dt util as timestamp combined
null
null
null
null
Question: What does the code take ? Code: def convert_time_to_utc(timestr): combined = datetime.combine(dt_util.start_of_local_day(), dt_util.parse_time(timestr)) if (combined < datetime.now()): combined = (combined + timedelta(days=1)) return dt_util.as_timestamp(combined)
null
null
null
What does the code return ?
def vpn_ping(address, port, timeout=0.05, session_id=None): if (session_id is None): session_id = random.randint(0, 18446744073709551615L) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = struct.pack('!BQxxxxx', 56, session_id) sock.sendto(data, (address, port)) sock.settimeout(timeout) try: received = sock.recv(2048) except socket.timeout: return False finally: sock.close() fmt = '!BQxxxxxQxxxx' if (len(received) != struct.calcsize(fmt)): print struct.calcsize(fmt) return False (identifier, server_sess, client_sess) = struct.unpack(fmt, received) if ((identifier == 64) and (client_sess == session_id)): return server_sess
null
null
null
the server session
codeqa
def vpn ping address port timeout 0 05 session id None if session id is None session id random randint 0 18446744073709551615 L sock socket socket socket AF INET socket SOCK DGRAM data struct pack ' B Qxxxxx' 56 session id sock sendto data address port sock settimeout timeout try received sock recv 2048 except socket timeout return Falsefinally sock close fmt ' B Qxxxxx Qxxxx'if len received struct calcsize fmt print struct calcsize fmt return False identifier server sess client sess struct unpack fmt received if identifier 64 and client sess session id return server sess
null
null
null
null
Question: What does the code return ? Code: def vpn_ping(address, port, timeout=0.05, session_id=None): if (session_id is None): session_id = random.randint(0, 18446744073709551615L) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = struct.pack('!BQxxxxx', 56, session_id) sock.sendto(data, (address, port)) sock.settimeout(timeout) try: received = sock.recv(2048) except socket.timeout: return False finally: sock.close() fmt = '!BQxxxxxQxxxx' if (len(received) != struct.calcsize(fmt)): print struct.calcsize(fmt) return False (identifier, server_sess, client_sess) = struct.unpack(fmt, received) if ((identifier == 64) and (client_sess == session_id)): return server_sess
null
null
null
How do the ring status return code ?
def get_ring(): ring_output = check_output([NODE_TOOL, 'ring', KEYSPACE]) ring = [] index = 0 for line in ring_output.splitlines(): fields = line.split() if (len(fields) != 8): continue ring.append({'index': index, 'ip': fields[0], 'status': fields[2], 'state': fields[3], 'load': load_bytes(float(fields[4]), fields[5]), 'token': fields[7]}) index += 1 assert (len(ring) > 0) ideal_load = (sum((node['load'] for node in ring)) / len(ring)) for (index, node) in enumerate(ring): try: node['skew'] = (abs((node['load'] - ideal_load)) / ideal_load) except ZeroDivisionError: node['skew'] = 0 node['diff'] = abs((node['load'] - ring[(index - 1)]['load'])) return ring
null
null
null
in a structured way
codeqa
def get ring ring output check output [NODE TOOL 'ring' KEYSPACE] ring []index 0for line in ring output splitlines fields line split if len fields 8 continuering append {'index' index 'ip' fields[ 0 ] 'status' fields[ 2 ] 'state' fields[ 3 ] 'load' load bytes float fields[ 4 ] fields[ 5 ] 'token' fields[ 7 ]} index + 1assert len ring > 0 ideal load sum node['load'] for node in ring / len ring for index node in enumerate ring try node['skew'] abs node['load'] - ideal load / ideal load except Zero Division Error node['skew'] 0node['diff'] abs node['load'] - ring[ index - 1 ]['load'] return ring
null
null
null
null
Question: How do the ring status return code ? Code: def get_ring(): ring_output = check_output([NODE_TOOL, 'ring', KEYSPACE]) ring = [] index = 0 for line in ring_output.splitlines(): fields = line.split() if (len(fields) != 8): continue ring.append({'index': index, 'ip': fields[0], 'status': fields[2], 'state': fields[3], 'load': load_bytes(float(fields[4]), fields[5]), 'token': fields[7]}) index += 1 assert (len(ring) > 0) ideal_load = (sum((node['load'] for node in ring)) / len(ring)) for (index, node) in enumerate(ring): try: node['skew'] = (abs((node['load'] - ideal_load)) / ideal_load) except ZeroDivisionError: node['skew'] = 0 node['diff'] = abs((node['load'] - ring[(index - 1)]['load'])) return ring
null
null
null
What does the code convert into a valid slice object which can be used as indices for a list or array ?
def sliceFromString(sliceString): sliceArgs = [] for val in sliceString.split(':'): if (len(val) == 0): sliceArgs.append(None) else: sliceArgs.append(int(round(float(val)))) return apply(slice, sliceArgs)
null
null
null
a text string
codeqa
def slice From String slice String slice Args []for val in slice String split ' ' if len val 0 slice Args append None else slice Args append int round float val return apply slice slice Args
null
null
null
null
Question: What does the code convert into a valid slice object which can be used as indices for a list or array ? Code: def sliceFromString(sliceString): sliceArgs = [] for val in sliceString.split(':'): if (len(val) == 0): sliceArgs.append(None) else: sliceArgs.append(int(round(float(val)))) return apply(slice, sliceArgs)
null
null
null
Where are all the terms in the needles list found ?
def assertContainsAll(haystack, needles, test_case): for needle in reversed(needles): if (needle in haystack): needles.remove(needle) if needles: test_case.fail('{haystack} did not contain {needles}'.format(haystack=haystack, needles=needles))
null
null
null
in the haystack
codeqa
def assert Contains All haystack needles test case for needle in reversed needles if needle in haystack needles remove needle if needles test case fail '{haystack}didnotcontain{needles}' format haystack haystack needles needles
null
null
null
null
Question: Where are all the terms in the needles list found ? Code: def assertContainsAll(haystack, needles, test_case): for needle in reversed(needles): if (needle in haystack): needles.remove(needle) if needles: test_case.fail('{haystack} did not contain {needles}'.format(haystack=haystack, needles=needles))
null
null
null
What are found in the haystack ?
def assertContainsAll(haystack, needles, test_case): for needle in reversed(needles): if (needle in haystack): needles.remove(needle) if needles: test_case.fail('{haystack} did not contain {needles}'.format(haystack=haystack, needles=needles))
null
null
null
all the terms in the needles list
codeqa
def assert Contains All haystack needles test case for needle in reversed needles if needle in haystack needles remove needle if needles test case fail '{haystack}didnotcontain{needles}' format haystack haystack needles needles
null
null
null
null
Question: What are found in the haystack ? Code: def assertContainsAll(haystack, needles, test_case): for needle in reversed(needles): if (needle in haystack): needles.remove(needle) if needles: test_case.fail('{haystack} did not contain {needles}'.format(haystack=haystack, needles=needles))
null
null
null
Where does the item return from inside each tuple in the list ?
def unzip(i, iterable): return [x[i] for x in iterable]
null
null
null
at the given index
codeqa
def unzip i iterable return [x[i] for x in iterable]
null
null
null
null
Question: Where does the item return from inside each tuple in the list ? Code: def unzip(i, iterable): return [x[i] for x in iterable]
null
null
null
What returns from inside each tuple in the list at the given index ?
def unzip(i, iterable): return [x[i] for x in iterable]
null
null
null
the item
codeqa
def unzip i iterable return [x[i] for x in iterable]
null
null
null
null
Question: What returns from inside each tuple in the list at the given index ? Code: def unzip(i, iterable): return [x[i] for x in iterable]
null
null
null
What affects the real pipe ?
def make_or_pipe(pipe): p1 = OrPipe(pipe) p2 = OrPipe(pipe) p1._partner = p2 p2._partner = p1 return (p1, p2)
null
null
null
which
codeqa
def make or pipe pipe p1 Or Pipe pipe p2 Or Pipe pipe p1 partner p2 p 2 partner p1 return p1 p2
null
null
null
null
Question: What affects the real pipe ? Code: def make_or_pipe(pipe): p1 = OrPipe(pipe) p2 = OrPipe(pipe) p1._partner = p2 p2._partner = p1 return (p1, p2)
null
null
null
What do which affect ?
def make_or_pipe(pipe): p1 = OrPipe(pipe) p2 = OrPipe(pipe) p1._partner = p2 p2._partner = p1 return (p1, p2)
null
null
null
the real pipe
codeqa
def make or pipe pipe p1 Or Pipe pipe p2 Or Pipe pipe p1 partner p2 p 2 partner p1 return p1 p2
null
null
null
null
Question: What do which affect ? Code: def make_or_pipe(pipe): p1 = OrPipe(pipe) p2 = OrPipe(pipe) p1._partner = p2 p2._partner = p1 return (p1, p2)
null
null
null
What does the code create ?
def create_condition(condition_class, **kwargs): return Condition.objects.create(proxy_class=_class_path(condition_class), **kwargs)
null
null
null
a custom condition instance
codeqa
def create condition condition class **kwargs return Condition objects create proxy class class path condition class **kwargs
null
null
null
null
Question: What does the code create ? Code: def create_condition(condition_class, **kwargs): return Condition.objects.create(proxy_class=_class_path(condition_class), **kwargs)
null
null
null
What does the code get ?
def get_namespace_keys(app, limit): ns_query = datastore.Query('__namespace__', keys_only=True, _app=app) return ns_query.Get(limit=limit)
null
null
null
namespace keys
codeqa
def get namespace keys app limit ns query datastore Query ' namespace ' keys only True app app return ns query Get limit limit
null
null
null
null
Question: What does the code get ? Code: def get_namespace_keys(app, limit): ns_query = datastore.Query('__namespace__', keys_only=True, _app=app) return ns_query.Get(limit=limit)
null
null
null
What does the code add to the lists ?
def addListsToRepositoryByFunction(fileNameHelp, getProfileDirectory, repository): repository.displayEntities = [] repository.executeTitle = None repository.fileNameHelp = fileNameHelp repository.fileNameInput = None repository.lowerName = fileNameHelp.split('.')[(-2)] repository.baseName = (repository.lowerName + '.csv') repository.baseNameSynonym = None repository.baseNameSynonymDictionary = None repository.capitalizedName = getEachWordCapitalized(repository.lowerName) repository.getProfileDirectory = getProfileDirectory repository.openLocalHelpPage = HelpPage().getOpenFromDocumentationSubName(repository.fileNameHelp) repository.openWikiManualHelpPage = None repository.preferences = [] repository.repositoryDialog = None repository.saveListenerTable = {} repository.title = (repository.capitalizedName + ' Settings') repository.menuEntities = [] repository.saveCloseTitle = 'Save and Close' repository.windowPosition = WindowPosition().getFromValue(repository, '0+0') for setting in repository.preferences: setting.repository = repository
null
null
null
the value
codeqa
def add Lists To Repository By Function file Name Help get Profile Directory repository repository display Entities []repository execute Title Nonerepository file Name Help file Name Helprepository file Name Input Nonerepository lower Name file Name Help split ' ' [ -2 ]repository base Name repository lower Name + ' csv' repository base Name Synonym Nonerepository base Name Synonym Dictionary Nonerepository capitalized Name get Each Word Capitalized repository lower Name repository get Profile Directory get Profile Directoryrepository open Local Help Page Help Page get Open From Documentation Sub Name repository file Name Help repository open Wiki Manual Help Page Nonerepository preferences []repository repository Dialog Nonerepository save Listener Table {}repository title repository capitalized Name + ' Settings' repository menu Entities []repository save Close Title ' Saveand Close'repository window Position Window Position get From Value repository '0 + 0 ' for setting in repository preferences setting repository repository
null
null
null
null
Question: What does the code add to the lists ? Code: def addListsToRepositoryByFunction(fileNameHelp, getProfileDirectory, repository): repository.displayEntities = [] repository.executeTitle = None repository.fileNameHelp = fileNameHelp repository.fileNameInput = None repository.lowerName = fileNameHelp.split('.')[(-2)] repository.baseName = (repository.lowerName + '.csv') repository.baseNameSynonym = None repository.baseNameSynonymDictionary = None repository.capitalizedName = getEachWordCapitalized(repository.lowerName) repository.getProfileDirectory = getProfileDirectory repository.openLocalHelpPage = HelpPage().getOpenFromDocumentationSubName(repository.fileNameHelp) repository.openWikiManualHelpPage = None repository.preferences = [] repository.repositoryDialog = None repository.saveListenerTable = {} repository.title = (repository.capitalizedName + ' Settings') repository.menuEntities = [] repository.saveCloseTitle = 'Save and Close' repository.windowPosition = WindowPosition().getFromValue(repository, '0+0') for setting in repository.preferences: setting.repository = repository
null
null
null
What does the code add to an integer n ?
def commify(n): if (n is None): return None n = str(n) if ('.' in n): (dollars, cents) = n.split('.') else: (dollars, cents) = (n, None) r = [] for (i, c) in enumerate(str(dollars)[::(-1)]): if (i and (not (i % 3))): r.insert(0, ',') r.insert(0, c) out = ''.join(r) if cents: out += ('.' + cents) return out
null
null
null
commas
codeqa
def commify n if n is None return Nonen str n if ' ' in n dollars cents n split ' ' else dollars cents n None r []for i c in enumerate str dollars [ -1 ] if i and not i % 3 r insert 0 ' ' r insert 0 c out '' join r if cents out + ' ' + cents return out
null
null
null
null
Question: What does the code add to an integer n ? Code: def commify(n): if (n is None): return None n = str(n) if ('.' in n): (dollars, cents) = n.split('.') else: (dollars, cents) = (n, None) r = [] for (i, c) in enumerate(str(dollars)[::(-1)]): if (i and (not (i % 3))): r.insert(0, ',') r.insert(0, c) out = ''.join(r) if cents: out += ('.' + cents) return out
null
null
null
What does the code find ?
def best_match(supported, header): parsed_header = [parse_media_range(r) for r in header.split(',')] weighted_matches = [(quality_parsed(mime_type, parsed_header), mime_type) for mime_type in supported] weighted_matches.sort() return ((weighted_matches[(-1)][0] and weighted_matches[(-1)][1]) or '')
null
null
null
the best match for all the media - ranges listed in header
codeqa
def best match supported header parsed header [parse media range r for r in header split ' ' ]weighted matches [ quality parsed mime type parsed header mime type for mime type in supported]weighted matches sort return weighted matches[ -1 ][ 0 ] and weighted matches[ -1 ][ 1 ] or ''
null
null
null
null
Question: What does the code find ? Code: def best_match(supported, header): parsed_header = [parse_media_range(r) for r in header.split(',')] weighted_matches = [(quality_parsed(mime_type, parsed_header), mime_type) for mime_type in supported] weighted_matches.sort() return ((weighted_matches[(-1)][0] and weighted_matches[(-1)][1]) or '')
null
null
null
What does the code take ?
def best_match(supported, header): parsed_header = [parse_media_range(r) for r in header.split(',')] weighted_matches = [(quality_parsed(mime_type, parsed_header), mime_type) for mime_type in supported] weighted_matches.sort() return ((weighted_matches[(-1)][0] and weighted_matches[(-1)][1]) or '')
null
null
null
a list of supported mime - types
codeqa
def best match supported header parsed header [parse media range r for r in header split ' ' ]weighted matches [ quality parsed mime type parsed header mime type for mime type in supported]weighted matches sort return weighted matches[ -1 ][ 0 ] and weighted matches[ -1 ][ 1 ] or ''
null
null
null
null
Question: What does the code take ? Code: def best_match(supported, header): parsed_header = [parse_media_range(r) for r in header.split(',')] weighted_matches = [(quality_parsed(mime_type, parsed_header), mime_type) for mime_type in supported] weighted_matches.sort() return ((weighted_matches[(-1)][0] and weighted_matches[(-1)][1]) or '')
null
null
null
How was any state setup previously ?
def teardown_function(function): slogging.configure(**function.snapshot)
null
null
null
with a setup_function call
codeqa
def teardown function function slogging configure **function snapshot
null
null
null
null
Question: How was any state setup previously ? Code: def teardown_function(function): slogging.configure(**function.snapshot)
null
null
null
When was any state setup with a setup_function call ?
def teardown_function(function): slogging.configure(**function.snapshot)
null
null
null
previously
codeqa
def teardown function function slogging configure **function snapshot
null
null
null
null
Question: When was any state setup with a setup_function call ? Code: def teardown_function(function): slogging.configure(**function.snapshot)
null
null
null
What does the code modify for a test ?
@contextmanager def __environ(values, remove=[]): new_keys = (set(environ.keys()) - set(values.keys())) old_environ = environ.copy() try: environ.update(values) for to_remove in remove: try: del environ[remove] except KeyError: pass (yield) finally: environ.update(old_environ) for key in new_keys: del environ[key]
null
null
null
the environment
codeqa
@contextmanagerdef environ values remove [] new keys set environ keys - set values keys old environ environ copy try environ update values for to remove in remove try del environ[remove]except Key Error pass yield finally environ update old environ for key in new keys del environ[key]
null
null
null
null
Question: What does the code modify for a test ? Code: @contextmanager def __environ(values, remove=[]): new_keys = (set(environ.keys()) - set(values.keys())) old_environ = environ.copy() try: environ.update(values) for to_remove in remove: try: del environ[remove] except KeyError: pass (yield) finally: environ.update(old_environ) for key in new_keys: del environ[key]
null
null
null
For what purpose does the code modify the environment ?
@contextmanager def __environ(values, remove=[]): new_keys = (set(environ.keys()) - set(values.keys())) old_environ = environ.copy() try: environ.update(values) for to_remove in remove: try: del environ[remove] except KeyError: pass (yield) finally: environ.update(old_environ) for key in new_keys: del environ[key]
null
null
null
for a test
codeqa
@contextmanagerdef environ values remove [] new keys set environ keys - set values keys old environ environ copy try environ update values for to remove in remove try del environ[remove]except Key Error pass yield finally environ update old environ for key in new keys del environ[key]
null
null
null
null
Question: For what purpose does the code modify the environment ? Code: @contextmanager def __environ(values, remove=[]): new_keys = (set(environ.keys()) - set(values.keys())) old_environ = environ.copy() try: environ.update(values) for to_remove in remove: try: del environ[remove] except KeyError: pass (yield) finally: environ.update(old_environ) for key in new_keys: del environ[key]
null
null
null
What unpacks to the directory specified by to_path at the specified path ?
def extract(path, to_path=''): with Archive(path) as archive: archive.extract(to_path)
null
null
null
the tar or zip file
codeqa
def extract path to path '' with Archive path as archive archive extract to path
null
null
null
null
Question: What unpacks to the directory specified by to_path at the specified path ? Code: def extract(path, to_path=''): with Archive(path) as archive: archive.extract(to_path)
null
null
null
What does the code take ?
def generic_passthrough_kodi_set(results): try: setting_value = results[0] except IndexError: setting_value = None return setting_value
null
null
null
a results list
codeqa
def generic passthrough kodi set results try setting value results[ 0 ]except Index Error setting value Nonereturn setting value
null
null
null
null
Question: What does the code take ? Code: def generic_passthrough_kodi_set(results): try: setting_value = results[0] except IndexError: setting_value = None return setting_value
null
null
null
What did this return in python 2 always ?
def get_type_hints(obj, globalns=None, localns=None): return None
null
null
null
none
codeqa
def get type hints obj globalns None localns None return None
null
null
null
null
Question: What did this return in python 2 always ? Code: def get_type_hints(obj, globalns=None, localns=None): return None
null
null
null
When did this return none in python 2 ?
def get_type_hints(obj, globalns=None, localns=None): return None
null
null
null
always
codeqa
def get type hints obj globalns None localns None return None
null
null
null
null
Question: When did this return none in python 2 ? Code: def get_type_hints(obj, globalns=None, localns=None): return None
null
null
null
What does the code receive ?
def ms_payload(payload): return {'1': 'windows/shell_reverse_tcp', '2': 'windows/meterpreter/reverse_tcp', '3': 'windows/vncinject/reverse_tcp', '4': 'windows/x64/shell_reverse_tcp', '5': 'windows/x64/meterpreter/reverse_tcp', '6': 'windows/meterpreter/reverse_tcp_allports', '7': 'windows/meterpreter/reverse_https', '8': 'windows/meterpreter/reverse_tcp_dns', '9': 'windows/download_exec'}.get(payload, 'ERROR')
null
null
null
the input given by the user from create_payload
codeqa
def ms payload payload return {' 1 ' 'windows/shell reverse tcp' '2 ' 'windows/meterpreter/reverse tcp' '3 ' 'windows/vncinject/reverse tcp' '4 ' 'windows/x 64 /shell reverse tcp' '5 ' 'windows/x 64 /meterpreter/reverse tcp' '6 ' 'windows/meterpreter/reverse tcp allports' '7 ' 'windows/meterpreter/reverse https' '8 ' 'windows/meterpreter/reverse tcp dns' '9 ' 'windows/download exec'} get payload 'ERROR'
null
null
null
null
Question: What does the code receive ? Code: def ms_payload(payload): return {'1': 'windows/shell_reverse_tcp', '2': 'windows/meterpreter/reverse_tcp', '3': 'windows/vncinject/reverse_tcp', '4': 'windows/x64/shell_reverse_tcp', '5': 'windows/x64/meterpreter/reverse_tcp', '6': 'windows/meterpreter/reverse_tcp_allports', '7': 'windows/meterpreter/reverse_https', '8': 'windows/meterpreter/reverse_tcp_dns', '9': 'windows/download_exec'}.get(payload, 'ERROR')
null
null
null
What does the code add if no service type is specified ?
def servicegroup_add(sg_name, sg_type='HTTP', **connection_args): ret = True if servicegroup_exists(sg_name): return False nitro = _connect(**connection_args) if (nitro is None): return False sg = NSServiceGroup() sg.set_servicegroupname(sg_name) sg.set_servicetype(sg_type.upper()) try: NSServiceGroup.add(nitro, sg) except NSNitroError as error: log.debug('netscaler module error - NSServiceGroup.add() failed: {0}'.format(error)) ret = False _disconnect(nitro) return ret
null
null
null
a new service group
codeqa
def servicegroup add sg name sg type 'HTTP' **connection args ret Trueif servicegroup exists sg name return Falsenitro connect **connection args if nitro is None return Falsesg NS Service Group sg set servicegroupname sg name sg set servicetype sg type upper try NS Service Group add nitro sg except NS Nitro Error as error log debug 'netscalermoduleerror-NS Service Group add failed {0 }' format error ret False disconnect nitro return ret
null
null
null
null
Question: What does the code add if no service type is specified ? Code: def servicegroup_add(sg_name, sg_type='HTTP', **connection_args): ret = True if servicegroup_exists(sg_name): return False nitro = _connect(**connection_args) if (nitro is None): return False sg = NSServiceGroup() sg.set_servicegroupname(sg_name) sg.set_servicetype(sg_type.upper()) try: NSServiceGroup.add(nitro, sg) except NSNitroError as error: log.debug('netscaler module error - NSServiceGroup.add() failed: {0}'.format(error)) ret = False _disconnect(nitro) return ret
null
null
null
What does the code perform ?
def _interact(cookiejar, url, set_cookie_hdrs, hdr_name): req = urllib.request.Request(url) cookiejar.add_cookie_header(req) cookie_hdr = req.get_header('Cookie', '') headers = [] for hdr in set_cookie_hdrs: headers.append(('%s: %s' % (hdr_name, hdr))) res = FakeResponse(headers, url) cookiejar.extract_cookies(res, req) return cookie_hdr
null
null
null
a single request / response cycle
codeqa
def interact cookiejar url set cookie hdrs hdr name req urllib request Request url cookiejar add cookie header req cookie hdr req get header ' Cookie' '' headers []for hdr in set cookie hdrs headers append '%s %s' % hdr name hdr res Fake Response headers url cookiejar extract cookies res req return cookie hdr
null
null
null
null
Question: What does the code perform ? Code: def _interact(cookiejar, url, set_cookie_hdrs, hdr_name): req = urllib.request.Request(url) cookiejar.add_cookie_header(req) cookie_hdr = req.get_header('Cookie', '') headers = [] for hdr in set_cookie_hdrs: headers.append(('%s: %s' % (hdr_name, hdr))) res = FakeResponse(headers, url) cookiejar.extract_cookies(res, req) return cookie_hdr
null
null
null
What do multiplication with strings produce ?
def test_unit_multiplication_with_string(): u1 = u.cm us = u'kg' assert ((us * u1) == (u.Unit(us) * u1)) assert ((u1 * us) == (u1 * u.Unit(us)))
null
null
null
the correct unit
codeqa
def test unit multiplication with string u1 u cmus u'kg'assert us * u1 u Unit us * u1 assert u1 * us u1 * u Unit us
null
null
null
null
Question: What do multiplication with strings produce ? Code: def test_unit_multiplication_with_string(): u1 = u.cm us = u'kg' assert ((us * u1) == (u.Unit(us) * u1)) assert ((u1 * us) == (u1 * u.Unit(us)))
null
null
null
What produces the correct unit ?
def test_unit_multiplication_with_string(): u1 = u.cm us = u'kg' assert ((us * u1) == (u.Unit(us) * u1)) assert ((u1 * us) == (u1 * u.Unit(us)))
null
null
null
multiplication with strings
codeqa
def test unit multiplication with string u1 u cmus u'kg'assert us * u1 u Unit us * u1 assert u1 * us u1 * u Unit us
null
null
null
null
Question: What produces the correct unit ? Code: def test_unit_multiplication_with_string(): u1 = u.cm us = u'kg' assert ((us * u1) == (u.Unit(us) * u1)) assert ((u1 * us) == (u1 * u.Unit(us)))
null
null
null
What does the code convert to k ?
def dup_from_sympy(f, K): return dup_strip([K.from_sympy(c) for c in f])
null
null
null
the ground domain of f
codeqa
def dup from sympy f K return dup strip [K from sympy c for c in f]
null
null
null
null
Question: What does the code convert to k ? Code: def dup_from_sympy(f, K): return dup_strip([K.from_sympy(c) for c in f])
null
null
null
What does the code reduce by padding ?
def extra_padding_y_keep_ratio(original_size, padding): return _resize(original_size, 1, padding=padding, keep_aspect_ratio=True)
null
null
null
the height of original_size
codeqa
def extra padding y keep ratio original size padding return resize original size 1 padding padding keep aspect ratio True
null
null
null
null
Question: What does the code reduce by padding ? Code: def extra_padding_y_keep_ratio(original_size, padding): return _resize(original_size, 1, padding=padding, keep_aspect_ratio=True)
null
null
null
How does the code reduce the height of original_size ?
def extra_padding_y_keep_ratio(original_size, padding): return _resize(original_size, 1, padding=padding, keep_aspect_ratio=True)
null
null
null
by padding
codeqa
def extra padding y keep ratio original size padding return resize original size 1 padding padding keep aspect ratio True
null
null
null
null
Question: How does the code reduce the height of original_size ? Code: def extra_padding_y_keep_ratio(original_size, padding): return _resize(original_size, 1, padding=padding, keep_aspect_ratio=True)
null
null
null
When is an error raised ?
def test_renn_sample_wrong_X(): renn = RepeatedEditedNearestNeighbours(random_state=RND_SEED) renn.fit(X, Y) assert_raises(RuntimeError, renn.sample, np.random.random((100, 40)), np.array((([0] * 50) + ([1] * 50))))
null
null
null
when x is different at fitting and sampling
codeqa
def test renn sample wrong X renn Repeated Edited Nearest Neighbours random state RND SEED renn fit X Y assert raises Runtime Error renn sample np random random 100 40 np array [0 ] * 50 + [1 ] * 50
null
null
null
null
Question: When is an error raised ? Code: def test_renn_sample_wrong_X(): renn = RepeatedEditedNearestNeighbours(random_state=RND_SEED) renn.fit(X, Y) assert_raises(RuntimeError, renn.sample, np.random.random((100, 40)), np.array((([0] * 50) + ([1] * 50))))
null
null
null
What did the code set ?
@frappe.whitelist() def update_column_order(board_name, order): board = frappe.get_doc(u'Kanban Board', board_name) order = json.loads(order) old_columns = board.columns new_columns = [] for col in order: for column in old_columns: if (col == column.column_name): new_columns.append(column) old_columns.remove(column) new_columns.extend(old_columns) board.columns = [] for col in new_columns: board.append(u'columns', dict(column_name=col.column_name, status=col.status, order=col.order, indicator=col.indicator)) board.save() return board
null
null
null
the order of columns in kanban board
codeqa
@frappe whitelist def update column order board name order board frappe get doc u' Kanban Board' board name order json loads order old columns board columnsnew columns []for col in order for column in old columns if col column column name new columns append column old columns remove column new columns extend old columns board columns []for col in new columns board append u'columns' dict column name col column name status col status order col order indicator col indicator board save return board
null
null
null
null
Question: What did the code set ? Code: @frappe.whitelist() def update_column_order(board_name, order): board = frappe.get_doc(u'Kanban Board', board_name) order = json.loads(order) old_columns = board.columns new_columns = [] for col in order: for column in old_columns: if (col == column.column_name): new_columns.append(column) old_columns.remove(column) new_columns.extend(old_columns) board.columns = [] for col in new_columns: board.append(u'columns', dict(column_name=col.column_name, status=col.status, order=col.order, indicator=col.indicator)) board.save() return board
null
null
null
What does the code decorate ?
def validates(*names, **kw): include_removes = kw.pop('include_removes', False) include_backrefs = kw.pop('include_backrefs', True) def wrap(fn): fn.__sa_validators__ = names fn.__sa_validation_opts__ = {'include_removes': include_removes, 'include_backrefs': include_backrefs} return fn return wrap
null
null
null
a method as a validator for one or more named properties
codeqa
def validates *names **kw include removes kw pop 'include removes' False include backrefs kw pop 'include backrefs' True def wrap fn fn sa validators namesfn sa validation opts {'include removes' include removes 'include backrefs' include backrefs}return fnreturn wrap
null
null
null
null
Question: What does the code decorate ? Code: def validates(*names, **kw): include_removes = kw.pop('include_removes', False) include_backrefs = kw.pop('include_backrefs', True) def wrap(fn): fn.__sa_validators__ = names fn.__sa_validation_opts__ = {'include_removes': include_removes, 'include_backrefs': include_backrefs} return fn return wrap
null
null
null
What does the code compute ?
@constructor def prod(input, axis=None, dtype=None, keepdims=False, acc_dtype=None, no_zeros_in_input=False): out = elemwise.Prod(axis, dtype=dtype, acc_dtype=acc_dtype, no_zeros_in_input=no_zeros_in_input)(input) if keepdims: out = makeKeepDims(input, out, axis) return out
null
null
null
the product along the given axis of a tensor input
codeqa
@constructordef prod input axis None dtype None keepdims False acc dtype None no zeros in input False out elemwise Prod axis dtype dtype acc dtype acc dtype no zeros in input no zeros in input input if keepdims out make Keep Dims input out axis return out
null
null
null
null
Question: What does the code compute ? Code: @constructor def prod(input, axis=None, dtype=None, keepdims=False, acc_dtype=None, no_zeros_in_input=False): out = elemwise.Prod(axis, dtype=dtype, acc_dtype=acc_dtype, no_zeros_in_input=no_zeros_in_input)(input) if keepdims: out = makeKeepDims(input, out, axis) return out
null
null
null
How did a multivariate series compute ?
def rs_fun(p, f, *args): _R = p.ring (R1, _x) = ring('_x', _R.domain) h = int(args[(-1)]) args1 = (args[:(-2)] + (_x, h)) zm = _R.zero_monom if (zm in p): x1 = (_x + p[zm]) p1 = (p - p[zm]) else: x1 = _x p1 = p if isinstance(f, str): q = getattr(x1, f)(*args1) else: q = f(x1, *args1) a = sorted(q.items()) c = ([0] * h) for x in a: c[x[0][0]] = x[1] p1 = rs_series_from_list(p1, c, args[(-2)], args[(-1)]) return p1
null
null
null
by substitution
codeqa
def rs fun p f *args R p ring R1 x ring ' x' R domain h int args[ -1 ] args 1 args[ -2 ] + x h zm R zero monomif zm in p x1 x + p[zm] p1 p - p[zm] else x1 xp 1 pif isinstance f str q getattr x1 f *args 1 else q f x1 *args 1 a sorted q items c [0 ] * h for x in a c[x[ 0 ][ 0 ]] x[ 1 ]p 1 rs series from list p1 c args[ -2 ] args[ -1 ] return p1
null
null
null
null
Question: How did a multivariate series compute ? Code: def rs_fun(p, f, *args): _R = p.ring (R1, _x) = ring('_x', _R.domain) h = int(args[(-1)]) args1 = (args[:(-2)] + (_x, h)) zm = _R.zero_monom if (zm in p): x1 = (_x + p[zm]) p1 = (p - p[zm]) else: x1 = _x p1 = p if isinstance(f, str): q = getattr(x1, f)(*args1) else: q = f(x1, *args1) a = sorted(q.items()) c = ([0] * h) for x in a: c[x[0][0]] = x[1] p1 = rs_series_from_list(p1, c, args[(-2)], args[(-1)]) return p1
null
null
null
By how much did file know ?
def save_to_well_known_file(credentials, well_known_file=None): if (well_known_file is None): well_known_file = _get_well_known_file() config_dir = os.path.dirname(well_known_file) if (not os.path.isdir(config_dir)): raise OSError('Config directory does not exist: {0}'.format(config_dir)) credentials_data = credentials.serialization_data _save_private_file(well_known_file, credentials_data)
null
null
null
well
codeqa
def save to well known file credentials well known file None if well known file is None well known file get well known file config dir os path dirname well known file if not os path isdir config dir raise OS Error ' Configdirectorydoesnotexist {0 }' format config dir credentials data credentials serialization data save private file well known file credentials data
null
null
null
null
Question: By how much did file know ? Code: def save_to_well_known_file(credentials, well_known_file=None): if (well_known_file is None): well_known_file = _get_well_known_file() config_dir = os.path.dirname(well_known_file) if (not os.path.isdir(config_dir)): raise OSError('Config directory does not exist: {0}'.format(config_dir)) credentials_data = credentials.serialization_data _save_private_file(well_known_file, credentials_data)
null
null
null
What does the code transform to a number ?
def aton(sr): try: return int(sr) except ValueError: try: return float(sr) except ValueError: return False
null
null
null
a string
codeqa
def aton sr try return int sr except Value Error try return float sr except Value Error return False
null
null
null
null
Question: What does the code transform to a number ? Code: def aton(sr): try: return int(sr) except ValueError: try: return float(sr) except ValueError: return False
null
null
null
What does the code ensure ?
@py.test.mark.parametrize('item_name', [item.name for item in six._urllib_request_moved_attributes]) def test_move_items_urllib_request(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.request)) getattr(six.moves.urllib.request, item_name)
null
null
null
that everything loads correctly
codeqa
@py test mark parametrize 'item name' [item name for item in six urllib request moved attributes] def test move items urllib request item name if sys version info[ 2] > 2 6 assert item name in dir six moves urllib request getattr six moves urllib request item name
null
null
null
null
Question: What does the code ensure ? Code: @py.test.mark.parametrize('item_name', [item.name for item in six._urllib_request_moved_attributes]) def test_move_items_urllib_request(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.request)) getattr(six.moves.urllib.request, item_name)
null
null
null
How do everything load ?
@py.test.mark.parametrize('item_name', [item.name for item in six._urllib_request_moved_attributes]) def test_move_items_urllib_request(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.request)) getattr(six.moves.urllib.request, item_name)
null
null
null
correctly
codeqa
@py test mark parametrize 'item name' [item name for item in six urllib request moved attributes] def test move items urllib request item name if sys version info[ 2] > 2 6 assert item name in dir six moves urllib request getattr six moves urllib request item name
null
null
null
null
Question: How do everything load ? Code: @py.test.mark.parametrize('item_name', [item.name for item in six._urllib_request_moved_attributes]) def test_move_items_urllib_request(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.request)) getattr(six.moves.urllib.request, item_name)
null
null
null
What does the code convert into a cookie containing the one k / v pair ?
def morsel_to_cookie(morsel): expires = None if morsel['max-age']: try: expires = int((time.time() + int(morsel['max-age']))) except ValueError: raise TypeError(('max-age: %s must be integer' % morsel['max-age'])) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = calendar.timegm(time.strptime(morsel['expires'], time_template)) return create_cookie(comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=(morsel['version'] or 0))
null
null
null
a morsel object
codeqa
def morsel to cookie morsel expires Noneif morsel['max-age'] try expires int time time + int morsel['max-age'] except Value Error raise Type Error 'max-age %smustbeinteger' % morsel['max-age'] elif morsel['expires'] time template '%a %d-%b-%Y%H %M %SGMT'expires calendar timegm time strptime morsel['expires'] time template return create cookie comment morsel['comment'] comment url bool morsel['comment'] discard False domain morsel['domain'] expires expires name morsel key path morsel['path'] port None rest {' Http Only' morsel['httponly']} rfc 2109 False secure bool morsel['secure'] value morsel value version morsel['version'] or 0
null
null
null
null
Question: What does the code convert into a cookie containing the one k / v pair ? Code: def morsel_to_cookie(morsel): expires = None if morsel['max-age']: try: expires = int((time.time() + int(morsel['max-age']))) except ValueError: raise TypeError(('max-age: %s must be integer' % morsel['max-age'])) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = calendar.timegm(time.strptime(morsel['expires'], time_template)) return create_cookie(comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=(morsel['version'] or 0))
null
null
null
What is containing the one k / v pair ?
def morsel_to_cookie(morsel): expires = None if morsel['max-age']: try: expires = int((time.time() + int(morsel['max-age']))) except ValueError: raise TypeError(('max-age: %s must be integer' % morsel['max-age'])) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = calendar.timegm(time.strptime(morsel['expires'], time_template)) return create_cookie(comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=(morsel['version'] or 0))
null
null
null
a cookie
codeqa
def morsel to cookie morsel expires Noneif morsel['max-age'] try expires int time time + int morsel['max-age'] except Value Error raise Type Error 'max-age %smustbeinteger' % morsel['max-age'] elif morsel['expires'] time template '%a %d-%b-%Y%H %M %SGMT'expires calendar timegm time strptime morsel['expires'] time template return create cookie comment morsel['comment'] comment url bool morsel['comment'] discard False domain morsel['domain'] expires expires name morsel key path morsel['path'] port None rest {' Http Only' morsel['httponly']} rfc 2109 False secure bool morsel['secure'] value morsel value version morsel['version'] or 0
null
null
null
null
Question: What is containing the one k / v pair ? Code: def morsel_to_cookie(morsel): expires = None if morsel['max-age']: try: expires = int((time.time() + int(morsel['max-age']))) except ValueError: raise TypeError(('max-age: %s must be integer' % morsel['max-age'])) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = calendar.timegm(time.strptime(morsel['expires'], time_template)) return create_cookie(comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=(morsel['version'] or 0))
null
null
null
What does this method take ?
def create_request_object(request_dict): r = request_dict request_object = AWSRequest(method=r['method'], url=r['url'], data=r['body'], headers=r['headers']) request_object.context.update(r['context']) return request_object
null
null
null
a request dict
codeqa
def create request object request dict r request dictrequest object AWS Request method r['method'] url r['url'] data r['body'] headers r['headers'] request object context update r['context'] return request object
null
null
null
null
Question: What does this method take ? Code: def create_request_object(request_dict): r = request_dict request_object = AWSRequest(method=r['method'], url=r['url'], data=r['body'], headers=r['headers']) request_object.context.update(r['context']) return request_object
null
null
null
What does the code display ?
@preloaderStop def successMessage(message): printLine(message, '\n')
null
null
null
a message
codeqa
@preloader Stopdef success Message message print Line message '\n'
null
null
null
null
Question: What does the code display ? Code: @preloaderStop def successMessage(message): printLine(message, '\n')
null
null
null
How does the code calculate a robust standard deviation ?
def mad_std(data, axis=None): return (median_absolute_deviation(data, axis=axis) * 1.482602218505602)
null
null
null
using the median absolute deviation < URL
codeqa
def mad std data axis None return median absolute deviation data axis axis * 1 482602218505602
null
null
null
null
Question: How does the code calculate a robust standard deviation ? Code: def mad_std(data, axis=None): return (median_absolute_deviation(data, axis=axis) * 1.482602218505602)
null
null
null
What does the code calculate using the median absolute deviation < URL ?
def mad_std(data, axis=None): return (median_absolute_deviation(data, axis=axis) * 1.482602218505602)
null
null
null
a robust standard deviation
codeqa
def mad std data axis None return median absolute deviation data axis axis * 1 482602218505602
null
null
null
null
Question: What does the code calculate using the median absolute deviation < URL ? Code: def mad_std(data, axis=None): return (median_absolute_deviation(data, axis=axis) * 1.482602218505602)
null
null
null
What is started on the server ?
def stream_with_context(generator_or_function): try: gen = iter(generator_or_function) except TypeError: def decorator(*args, **kwargs): gen = generator_or_function(*args, **kwargs) return stream_with_context(gen) return update_wrapper(decorator, generator_or_function) def generator(): ctx = _request_ctx_stack.top if (ctx is None): raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.') with ctx: (yield None) try: for item in gen: (yield item) finally: if hasattr(gen, 'close'): gen.close() wrapped_g = generator() next(wrapped_g) return wrapped_g
null
null
null
the response
codeqa
def stream with context generator or function try gen iter generator or function except Type Error def decorator *args **kwargs gen generator or function *args **kwargs return stream with context gen return update wrapper decorator generator or function def generator ctx request ctx stack topif ctx is None raise Runtime Error ' Attemptedtostreamwithcontextbuttherewasnocontextinthefirstplacetokeeparound ' with ctx yield None try for item in gen yield item finally if hasattr gen 'close' gen close wrapped g generator next wrapped g return wrapped g
null
null
null
null
Question: What is started on the server ? Code: def stream_with_context(generator_or_function): try: gen = iter(generator_or_function) except TypeError: def decorator(*args, **kwargs): gen = generator_or_function(*args, **kwargs) return stream_with_context(gen) return update_wrapper(decorator, generator_or_function) def generator(): ctx = _request_ctx_stack.top if (ctx is None): raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.') with ctx: (yield None) try: for item in gen: (yield item) finally: if hasattr(gen, 'close'): gen.close() wrapped_g = generator() next(wrapped_g) return wrapped_g
null
null
null
When do request contexts disappear ?
def stream_with_context(generator_or_function): try: gen = iter(generator_or_function) except TypeError: def decorator(*args, **kwargs): gen = generator_or_function(*args, **kwargs) return stream_with_context(gen) return update_wrapper(decorator, generator_or_function) def generator(): ctx = _request_ctx_stack.top if (ctx is None): raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.') with ctx: (yield None) try: for item in gen: (yield item) finally: if hasattr(gen, 'close'): gen.close() wrapped_g = generator() next(wrapped_g) return wrapped_g
null
null
null
when the response is started on the server
codeqa
def stream with context generator or function try gen iter generator or function except Type Error def decorator *args **kwargs gen generator or function *args **kwargs return stream with context gen return update wrapper decorator generator or function def generator ctx request ctx stack topif ctx is None raise Runtime Error ' Attemptedtostreamwithcontextbuttherewasnocontextinthefirstplacetokeeparound ' with ctx yield None try for item in gen yield item finally if hasattr gen 'close' gen close wrapped g generator next wrapped g return wrapped g
null
null
null
null
Question: When do request contexts disappear ? Code: def stream_with_context(generator_or_function): try: gen = iter(generator_or_function) except TypeError: def decorator(*args, **kwargs): gen = generator_or_function(*args, **kwargs) return stream_with_context(gen) return update_wrapper(decorator, generator_or_function) def generator(): ctx = _request_ctx_stack.top if (ctx is None): raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.') with ctx: (yield None) try: for item in gen: (yield item) finally: if hasattr(gen, 'close'): gen.close() wrapped_g = generator() next(wrapped_g) return wrapped_g
null
null
null
Where is the response started when ?
def stream_with_context(generator_or_function): try: gen = iter(generator_or_function) except TypeError: def decorator(*args, **kwargs): gen = generator_or_function(*args, **kwargs) return stream_with_context(gen) return update_wrapper(decorator, generator_or_function) def generator(): ctx = _request_ctx_stack.top if (ctx is None): raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.') with ctx: (yield None) try: for item in gen: (yield item) finally: if hasattr(gen, 'close'): gen.close() wrapped_g = generator() next(wrapped_g) return wrapped_g
null
null
null
on the server
codeqa
def stream with context generator or function try gen iter generator or function except Type Error def decorator *args **kwargs gen generator or function *args **kwargs return stream with context gen return update wrapper decorator generator or function def generator ctx request ctx stack topif ctx is None raise Runtime Error ' Attemptedtostreamwithcontextbuttherewasnocontextinthefirstplacetokeeparound ' with ctx yield None try for item in gen yield item finally if hasattr gen 'close' gen close wrapped g generator next wrapped g return wrapped g
null
null
null
null
Question: Where is the response started when ? Code: def stream_with_context(generator_or_function): try: gen = iter(generator_or_function) except TypeError: def decorator(*args, **kwargs): gen = generator_or_function(*args, **kwargs) return stream_with_context(gen) return update_wrapper(decorator, generator_or_function) def generator(): ctx = _request_ctx_stack.top if (ctx is None): raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.') with ctx: (yield None) try: for item in gen: (yield item) finally: if hasattr(gen, 'close'): gen.close() wrapped_g = generator() next(wrapped_g) return wrapped_g
null
null
null
What matches an extraction method mapping ?
def check_and_call_extract_file(filepath, method_map, options_map, callback, keywords, comment_tags, strip_comment_tags, dirpath=None): filename = relpath(filepath, dirpath) for (pattern, method) in method_map: if (not pathmatch(pattern, filename)): continue options = {} for (opattern, odict) in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for message_tuple in extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags=strip_comment_tags): (yield ((filename,) + message_tuple)) break
null
null
null
the given file
codeqa
def check and call extract file filepath method map options map callback keywords comment tags strip comment tags dirpath None filename relpath filepath dirpath for pattern method in method map if not pathmatch pattern filename continueoptions {}for opattern odict in options map items if pathmatch opattern filename options odictif callback callback filename method options for message tuple in extract from file method filepath keywords keywords comment tags comment tags options options strip comment tags strip comment tags yield filename + message tuple break
null
null
null
null
Question: What matches an extraction method mapping ? Code: def check_and_call_extract_file(filepath, method_map, options_map, callback, keywords, comment_tags, strip_comment_tags, dirpath=None): filename = relpath(filepath, dirpath) for (pattern, method) in method_map: if (not pathmatch(pattern, filename)): continue options = {} for (opattern, odict) in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for message_tuple in extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags=strip_comment_tags): (yield ((filename,) + message_tuple)) break
null
null
null
What does the given file match ?
def check_and_call_extract_file(filepath, method_map, options_map, callback, keywords, comment_tags, strip_comment_tags, dirpath=None): filename = relpath(filepath, dirpath) for (pattern, method) in method_map: if (not pathmatch(pattern, filename)): continue options = {} for (opattern, odict) in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for message_tuple in extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags=strip_comment_tags): (yield ((filename,) + message_tuple)) break
null
null
null
an extraction method mapping
codeqa
def check and call extract file filepath method map options map callback keywords comment tags strip comment tags dirpath None filename relpath filepath dirpath for pattern method in method map if not pathmatch pattern filename continueoptions {}for opattern odict in options map items if pathmatch opattern filename options odictif callback callback filename method options for message tuple in extract from file method filepath keywords keywords comment tags comment tags options options strip comment tags strip comment tags yield filename + message tuple break
null
null
null
null
Question: What does the given file match ? Code: def check_and_call_extract_file(filepath, method_map, options_map, callback, keywords, comment_tags, strip_comment_tags, dirpath=None): filename = relpath(filepath, dirpath) for (pattern, method) in method_map: if (not pathmatch(pattern, filename)): continue options = {} for (opattern, odict) in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for message_tuple in extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags=strip_comment_tags): (yield ((filename,) + message_tuple)) break
null
null
null
What does the code resize into thumbnails ?
def resize_thumbnails(pelican): global enabled if (not enabled): return in_path = _image_path(pelican) sizes = pelican.settings.get('THUMBNAIL_SIZES', DEFAULT_THUMBNAIL_SIZES) resizers = dict(((k, _resizer(k, v, in_path)) for (k, v) in sizes.items())) logger.debug('Thumbnailer Started') for (dirpath, _, filenames) in os.walk(in_path): for filename in filenames: if (not filename.startswith('.')): for (name, resizer) in resizers.items(): in_filename = path.join(dirpath, filename) out_path = get_out_path(pelican, in_path, in_filename, name) resizer.resize_file_to(in_filename, out_path, pelican.settings.get('THUMBNAIL_KEEP_NAME'))
null
null
null
a directory tree full of images
codeqa
def resize thumbnails pelican global enabledif not enabled returnin path image path pelican sizes pelican settings get 'THUMBNAIL SIZES' DEFAULT THUMBNAIL SIZES resizers dict k resizer k v in path for k v in sizes items logger debug ' Thumbnailer Started' for dirpath filenames in os walk in path for filename in filenames if not filename startswith ' ' for name resizer in resizers items in filename path join dirpath filename out path get out path pelican in path in filename name resizer resize file to in filename out path pelican settings get 'THUMBNAIL KEEP NAME'
null
null
null
null
Question: What does the code resize into thumbnails ? Code: def resize_thumbnails(pelican): global enabled if (not enabled): return in_path = _image_path(pelican) sizes = pelican.settings.get('THUMBNAIL_SIZES', DEFAULT_THUMBNAIL_SIZES) resizers = dict(((k, _resizer(k, v, in_path)) for (k, v) in sizes.items())) logger.debug('Thumbnailer Started') for (dirpath, _, filenames) in os.walk(in_path): for filename in filenames: if (not filename.startswith('.')): for (name, resizer) in resizers.items(): in_filename = path.join(dirpath, filename) out_path = get_out_path(pelican, in_path, in_filename, name) resizer.resize_file_to(in_filename, out_path, pelican.settings.get('THUMBNAIL_KEEP_NAME'))
null
null
null
How does the currently - active dashboard and/or panel set ?
def _current_component(view_func, dashboard=None, panel=None): @functools.wraps(view_func, assigned=available_attrs(view_func)) def dec(request, *args, **kwargs): if dashboard: request.horizon['dashboard'] = dashboard if panel: request.horizon['panel'] = panel return view_func(request, *args, **kwargs) return dec
null
null
null
on the request
codeqa
def current component view func dashboard None panel None @functools wraps view func assigned available attrs view func def dec request *args **kwargs if dashboard request horizon['dashboard'] dashboardif panel request horizon['panel'] panelreturn view func request *args **kwargs return dec
null
null
null
null
Question: How does the currently - active dashboard and/or panel set ? Code: def _current_component(view_func, dashboard=None, panel=None): @functools.wraps(view_func, assigned=available_attrs(view_func)) def dec(request, *args, **kwargs): if dashboard: request.horizon['dashboard'] = dashboard if panel: request.horizon['panel'] = panel return view_func(request, *args, **kwargs) return dec
null
null
null
What does membership controller use ?
def group_membership(): s3db.hrm_configure_pr_group_membership() table = db.pr_group_membership gtable = db.pr_group htable = s3db.hrm_human_resource s3.filter = ((((gtable.system == False) & (gtable.group_type == 3)) & (htable.type == 1)) & (htable.person_id == table.person_id)) def prep(r): if (r.method in ('create', 'create.popup', 'update', 'update.popup')): person_id = get_vars.get('~.person_id', None) if person_id: field = table.person_id field.default = person_id field.readable = field.writable = False return True s3.prep = prep output = s3_rest_controller('pr', 'group_membership', csv_stylesheet=('hrm', 'group_membership.xsl'), csv_template='group_membership') return output
null
null
null
the group_membership table
codeqa
def group membership s3 db hrm configure pr group membership table db pr group membershipgtable db pr grouphtable s3 db hrm human resources 3 filter gtable system False & gtable group type 3 & htable type 1 & htable person id table person id def prep r if r method in 'create' 'create popup' 'update' 'update popup' person id get vars get '~ person id' None if person id field table person idfield default person idfield readable field writable Falsereturn Trues 3 prep prepoutput s3 rest controller 'pr' 'group membership' csv stylesheet 'hrm' 'group membership xsl' csv template 'group membership' return output
null
null
null
null
Question: What does membership controller use ? Code: def group_membership(): s3db.hrm_configure_pr_group_membership() table = db.pr_group_membership gtable = db.pr_group htable = s3db.hrm_human_resource s3.filter = ((((gtable.system == False) & (gtable.group_type == 3)) & (htable.type == 1)) & (htable.person_id == table.person_id)) def prep(r): if (r.method in ('create', 'create.popup', 'update', 'update.popup')): person_id = get_vars.get('~.person_id', None) if person_id: field = table.person_id field.default = person_id field.readable = field.writable = False return True s3.prep = prep output = s3_rest_controller('pr', 'group_membership', csv_stylesheet=('hrm', 'group_membership.xsl'), csv_template='group_membership') return output
null
null
null
What uses the group_membership table ?
def group_membership(): s3db.hrm_configure_pr_group_membership() table = db.pr_group_membership gtable = db.pr_group htable = s3db.hrm_human_resource s3.filter = ((((gtable.system == False) & (gtable.group_type == 3)) & (htable.type == 1)) & (htable.person_id == table.person_id)) def prep(r): if (r.method in ('create', 'create.popup', 'update', 'update.popup')): person_id = get_vars.get('~.person_id', None) if person_id: field = table.person_id field.default = person_id field.readable = field.writable = False return True s3.prep = prep output = s3_rest_controller('pr', 'group_membership', csv_stylesheet=('hrm', 'group_membership.xsl'), csv_template='group_membership') return output
null
null
null
membership controller
codeqa
def group membership s3 db hrm configure pr group membership table db pr group membershipgtable db pr grouphtable s3 db hrm human resources 3 filter gtable system False & gtable group type 3 & htable type 1 & htable person id table person id def prep r if r method in 'create' 'create popup' 'update' 'update popup' person id get vars get '~ person id' None if person id field table person idfield default person idfield readable field writable Falsereturn Trues 3 prep prepoutput s3 rest controller 'pr' 'group membership' csv stylesheet 'hrm' 'group membership xsl' csv template 'group membership' return output
null
null
null
null
Question: What uses the group_membership table ? Code: def group_membership(): s3db.hrm_configure_pr_group_membership() table = db.pr_group_membership gtable = db.pr_group htable = s3db.hrm_human_resource s3.filter = ((((gtable.system == False) & (gtable.group_type == 3)) & (htable.type == 1)) & (htable.person_id == table.person_id)) def prep(r): if (r.method in ('create', 'create.popup', 'update', 'update.popup')): person_id = get_vars.get('~.person_id', None) if person_id: field = table.person_id field.default = person_id field.readable = field.writable = False return True s3.prep = prep output = s3_rest_controller('pr', 'group_membership', csv_stylesheet=('hrm', 'group_membership.xsl'), csv_template='group_membership') return output
null
null
null
What does not contain any possible characters that are indicative of a security breach ?
def is_string_secure(string): if re.match(VALID_CHARS_REGEX, string): return True else: return False
null
null
null
this string
codeqa
def is string secure string if re match VALID CHARS REGEX string return Trueelse return False
null
null
null
null
Question: What does not contain any possible characters that are indicative of a security breach ? Code: def is_string_secure(string): if re.match(VALID_CHARS_REGEX, string): return True else: return False
null
null
null
Does this string contain any possible characters that are indicative of a security breach ?
def is_string_secure(string): if re.match(VALID_CHARS_REGEX, string): return True else: return False
null
null
null
No
codeqa
def is string secure string if re match VALID CHARS REGEX string return Trueelse return False
null
null
null
null
Question: Does this string contain any possible characters that are indicative of a security breach ? Code: def is_string_secure(string): if re.match(VALID_CHARS_REGEX, string): return True else: return False
null
null
null
What does this string not contain ?
def is_string_secure(string): if re.match(VALID_CHARS_REGEX, string): return True else: return False
null
null
null
any possible characters that are indicative of a security breach
codeqa
def is string secure string if re match VALID CHARS REGEX string return Trueelse return False
null
null
null
null
Question: What does this string not contain ? Code: def is_string_secure(string): if re.match(VALID_CHARS_REGEX, string): return True else: return False
null
null
null
What do the line of text contain within a string ?
def line(loc, strg): lastCR = strg.rfind('\n', 0, loc) nextCR = strg.find('\n', loc) if (nextCR > 0): return strg[(lastCR + 1):nextCR] else: return strg[(lastCR + 1):]
null
null
null
loc
codeqa
def line loc strg last CR strg rfind '\n' 0 loc next CR strg find '\n' loc if next CR > 0 return strg[ last CR + 1 next CR]else return strg[ last CR + 1 ]
null
null
null
null
Question: What do the line of text contain within a string ? Code: def line(loc, strg): lastCR = strg.rfind('\n', 0, loc) nextCR = strg.find('\n', loc) if (nextCR > 0): return strg[(lastCR + 1):nextCR] else: return strg[(lastCR + 1):]
null
null
null
Do we have one already ?
def plus_or_dot(pieces): if ('+' in pieces.get('closest-tag', '')): return '.' return '+'
null
null
null
No
codeqa
def plus or dot pieces if '+' in pieces get 'closest-tag' '' return ' 'return '+'
null
null
null
null
Question: Do we have one already ? Code: def plus_or_dot(pieces): if ('+' in pieces.get('closest-tag', '')): return '.' return '+'
null
null
null
What did the code make ?
def siva(x, y): print x, y (x, y) = (y, x) print x, y
null
null
null
me fall in love with python
codeqa
def siva x y print x y x y y x print x y
null
null
null
null
Question: What did the code make ? Code: def siva(x, y): print x, y (x, y) = (y, x) print x, y
null
null
null
Where do all items of arrays differ in at most n units ?
def assert_array_max_ulp(a, b, maxulp=1, dtype=None): numpy.testing.assert_array_max_ulp(cupy.asnumpy(a), cupy.asnumpy(b), maxulp=maxulp, dtype=dtype)
null
null
null
in the last place
codeqa
def assert array max ulp a b maxulp 1 dtype None numpy testing assert array max ulp cupy asnumpy a cupy asnumpy b maxulp maxulp dtype dtype
null
null
null
null
Question: Where do all items of arrays differ in at most n units ? Code: def assert_array_max_ulp(a, b, maxulp=1, dtype=None): numpy.testing.assert_array_max_ulp(cupy.asnumpy(a), cupy.asnumpy(b), maxulp=maxulp, dtype=dtype)
null
null
null
For what purpose does the code check ?
def test_output_displayed(): with AssertPrints('2'): ip.run_cell('1+1', store_history=True) with AssertPrints('2'): ip.run_cell('1+1 # comment with a semicolon;', store_history=True) with AssertPrints('2'): ip.run_cell('1+1\n#commented_out_function();', store_history=True)
null
null
null
to make sure that output is displayed
codeqa
def test output displayed with Assert Prints '2 ' ip run cell '1 + 1 ' store history True with Assert Prints '2 ' ip run cell '1 + 1 #commentwithasemicolon ' store history True with Assert Prints '2 ' ip run cell '1 + 1 \n#commented out function ' store history True
null
null
null
null
Question: For what purpose does the code check ? Code: def test_output_displayed(): with AssertPrints('2'): ip.run_cell('1+1', store_history=True) with AssertPrints('2'): ip.run_cell('1+1 # comment with a semicolon;', store_history=True) with AssertPrints('2'): ip.run_cell('1+1\n#commented_out_function();', store_history=True)
null
null
null
When has a release failed ?
def hasFailed(release, size, provider='%'): release = prepareFailedName(release) failed_db_con = db.DBConnection('failed.db') sql_results = failed_db_con.select('SELECT release FROM failed WHERE release=? AND size=? AND provider LIKE ? LIMIT 1', [release, size, provider]) return (len(sql_results) > 0)
null
null
null
previously
codeqa
def has Failed release size provider '%' release prepare Failed Name release failed db con db DB Connection 'failed db' sql results failed db con select 'SELEC Trelease FRO Mfailed WHER Erelease ?AN Dsize ?AN Dprovider LIKE?LIMIT 1 ' [release size provider] return len sql results > 0
null
null
null
null
Question: When has a release failed ? Code: def hasFailed(release, size, provider='%'): release = prepareFailedName(release) failed_db_con = db.DBConnection('failed.db') sql_results = failed_db_con.select('SELECT release FROM failed WHERE release=? AND size=? AND provider LIKE ? LIMIT 1', [release, size, provider]) return (len(sql_results) > 0)
null
null
null
What does the code create ?
def create_menu(title, parent): qmenu = QtWidgets.QMenu(title, parent) return qmenu
null
null
null
a menu
codeqa
def create menu title parent qmenu Qt Widgets Q Menu title parent return qmenu
null
null
null
null
Question: What does the code create ? Code: def create_menu(title, parent): qmenu = QtWidgets.QMenu(title, parent) return qmenu
null
null
null
What does the code set ?
def create_menu(title, parent): qmenu = QtWidgets.QMenu(title, parent) return qmenu
null
null
null
its title
codeqa
def create menu title parent qmenu Qt Widgets Q Menu title parent return qmenu
null
null
null
null
Question: What does the code set ? Code: def create_menu(title, parent): qmenu = QtWidgets.QMenu(title, parent) return qmenu
null
null
null
What does the code apply ?
def ReplaceChunks(chunks): chunks_by_file = _SortChunksByFile(chunks) sorted_file_list = sorted(iterkeys(chunks_by_file)) num_files_to_open = _GetNumNonVisibleFiles(sorted_file_list) if (num_files_to_open > 0): if (not Confirm(FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format(num_files_to_open))): return locations = [] for filepath in sorted_file_list: (buffer_num, close_window) = _OpenFileInSplitIfNeeded(filepath) ReplaceChunksInBuffer(chunks_by_file[filepath], vim.buffers[buffer_num], locations) if close_window: vim.command(u'lclose') vim.command(u'hide') if locations: SetQuickFixList(locations) PostVimMessage(u'Applied {0} changes'.format(len(chunks)), warning=False)
null
null
null
the source file deltas supplied in |chunks| to arbitrary files
codeqa
def Replace Chunks chunks chunks by file Sort Chunks By File chunks sorted file list sorted iterkeys chunks by file num files to open Get Num Non Visible Files sorted file list if num files to open > 0 if not Confirm FIXIT OPENING BUFFERS MESSAGE FORMAT format num files to open returnlocations []for filepath in sorted file list buffer num close window Open File In Split If Needed filepath Replace Chunks In Buffer chunks by file[filepath] vim buffers[buffer num] locations if close window vim command u'lclose' vim command u'hide' if locations Set Quick Fix List locations Post Vim Message u' Applied{ 0 }changes' format len chunks warning False
null
null
null
null
Question: What does the code apply ? Code: def ReplaceChunks(chunks): chunks_by_file = _SortChunksByFile(chunks) sorted_file_list = sorted(iterkeys(chunks_by_file)) num_files_to_open = _GetNumNonVisibleFiles(sorted_file_list) if (num_files_to_open > 0): if (not Confirm(FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format(num_files_to_open))): return locations = [] for filepath in sorted_file_list: (buffer_num, close_window) = _OpenFileInSplitIfNeeded(filepath) ReplaceChunksInBuffer(chunks_by_file[filepath], vim.buffers[buffer_num], locations) if close_window: vim.command(u'lclose') vim.command(u'hide') if locations: SetQuickFixList(locations) PostVimMessage(u'Applied {0} changes'.format(len(chunks)), warning=False)
null
null
null
How did the source file deltas supply to arbitrary files ?
def ReplaceChunks(chunks): chunks_by_file = _SortChunksByFile(chunks) sorted_file_list = sorted(iterkeys(chunks_by_file)) num_files_to_open = _GetNumNonVisibleFiles(sorted_file_list) if (num_files_to_open > 0): if (not Confirm(FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format(num_files_to_open))): return locations = [] for filepath in sorted_file_list: (buffer_num, close_window) = _OpenFileInSplitIfNeeded(filepath) ReplaceChunksInBuffer(chunks_by_file[filepath], vim.buffers[buffer_num], locations) if close_window: vim.command(u'lclose') vim.command(u'hide') if locations: SetQuickFixList(locations) PostVimMessage(u'Applied {0} changes'.format(len(chunks)), warning=False)
null
null
null
in
codeqa
def Replace Chunks chunks chunks by file Sort Chunks By File chunks sorted file list sorted iterkeys chunks by file num files to open Get Num Non Visible Files sorted file list if num files to open > 0 if not Confirm FIXIT OPENING BUFFERS MESSAGE FORMAT format num files to open returnlocations []for filepath in sorted file list buffer num close window Open File In Split If Needed filepath Replace Chunks In Buffer chunks by file[filepath] vim buffers[buffer num] locations if close window vim command u'lclose' vim command u'hide' if locations Set Quick Fix List locations Post Vim Message u' Applied{ 0 }changes' format len chunks warning False
null
null
null
null
Question: How did the source file deltas supply to arbitrary files ? Code: def ReplaceChunks(chunks): chunks_by_file = _SortChunksByFile(chunks) sorted_file_list = sorted(iterkeys(chunks_by_file)) num_files_to_open = _GetNumNonVisibleFiles(sorted_file_list) if (num_files_to_open > 0): if (not Confirm(FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format(num_files_to_open))): return locations = [] for filepath in sorted_file_list: (buffer_num, close_window) = _OpenFileInSplitIfNeeded(filepath) ReplaceChunksInBuffer(chunks_by_file[filepath], vim.buffers[buffer_num], locations) if close_window: vim.command(u'lclose') vim.command(u'hide') if locations: SetQuickFixList(locations) PostVimMessage(u'Applied {0} changes'.format(len(chunks)), warning=False)
null
null
null
What is describing specific flavor ?
@require_context @pick_context_manager_reader def flavor_get_by_name(context, name): result = _flavor_get_query(context).filter_by(name=name).first() if (not result): raise exception.FlavorNotFoundByName(flavor_name=name) return _dict_with_extra_specs(result)
null
null
null
a dict
codeqa
@require context@pick context manager readerdef flavor get by name context name result flavor get query context filter by name name first if not result raise exception Flavor Not Found By Name flavor name name return dict with extra specs result
null
null
null
null
Question: What is describing specific flavor ? Code: @require_context @pick_context_manager_reader def flavor_get_by_name(context, name): result = _flavor_get_query(context).filter_by(name=name).first() if (not result): raise exception.FlavorNotFoundByName(flavor_name=name) return _dict_with_extra_specs(result)
null
null
null
What has permission to do a certain action ?
def action_allowed(request, app, action): return action_allowed_user(request.user, app, action)
null
null
null
the request user
codeqa
def action allowed request app action return action allowed user request user app action
null
null
null
null
Question: What has permission to do a certain action ? Code: def action_allowed(request, app, action): return action_allowed_user(request.user, app, action)
null
null
null
What does the request user have ?
def action_allowed(request, app, action): return action_allowed_user(request.user, app, action)
null
null
null
permission to do a certain action
codeqa
def action allowed request app action return action allowed user request user app action
null
null
null
null
Question: What does the request user have ? Code: def action_allowed(request, app, action): return action_allowed_user(request.user, app, action)
null
null
null
What dos a certain action ?
def action_allowed(request, app, action): return action_allowed_user(request.user, app, action)
null
null
null
the request user
codeqa
def action allowed request app action return action allowed user request user app action
null
null
null
null
Question: What dos a certain action ? Code: def action_allowed(request, app, action): return action_allowed_user(request.user, app, action)
null
null
null
What do the request user do ?
def action_allowed(request, app, action): return action_allowed_user(request.user, app, action)
null
null
null
a certain action
codeqa
def action allowed request app action return action allowed user request user app action
null
null
null
null
Question: What do the request user do ? Code: def action_allowed(request, app, action): return action_allowed_user(request.user, app, action)
null
null
null
For what purpose do a tail process launch ?
def launch_tails(follow_paths, lastlines_dirpath=None): if (lastlines_dirpath and (not os.path.exists(lastlines_dirpath))): os.makedirs(lastlines_dirpath) tail_cmd = ('/usr/bin/tail', '--retry', '--follow=name') procs = {} pipes = {} for path in follow_paths: cmd = list(tail_cmd) if lastlines_dirpath: reverse_lineno = lookup_lastlines(lastlines_dirpath, path) if (reverse_lineno is None): reverse_lineno = 1 cmd.append(('--lines=%d' % reverse_lineno)) cmd.append(path) tail_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) procs[path] = tail_proc pipes[nonblocking(tail_proc.stdout)] = path return (procs, pipes)
null
null
null
for each follow_path
codeqa
def launch tails follow paths lastlines dirpath None if lastlines dirpath and not os path exists lastlines dirpath os makedirs lastlines dirpath tail cmd '/usr/bin/tail' '--retry' '--follow name' procs {}pipes {}for path in follow paths cmd list tail cmd if lastlines dirpath reverse lineno lookup lastlines lastlines dirpath path if reverse lineno is None reverse lineno 1cmd append '--lines %d' % reverse lineno cmd append path tail proc subprocess Popen cmd stdout subprocess PIPE procs[path] tail procpipes[nonblocking tail proc stdout ] pathreturn procs pipes
null
null
null
null
Question: For what purpose do a tail process launch ? Code: def launch_tails(follow_paths, lastlines_dirpath=None): if (lastlines_dirpath and (not os.path.exists(lastlines_dirpath))): os.makedirs(lastlines_dirpath) tail_cmd = ('/usr/bin/tail', '--retry', '--follow=name') procs = {} pipes = {} for path in follow_paths: cmd = list(tail_cmd) if lastlines_dirpath: reverse_lineno = lookup_lastlines(lastlines_dirpath, path) if (reverse_lineno is None): reverse_lineno = 1 cmd.append(('--lines=%d' % reverse_lineno)) cmd.append(path) tail_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) procs[path] = tail_proc pipes[nonblocking(tail_proc.stdout)] = path return (procs, pipes)
null
null
null
What does the code get ?
def getAbs(value): return abs(value)
null
null
null
the abs
codeqa
def get Abs value return abs value
null
null
null
null
Question: What does the code get ? Code: def getAbs(value): return abs(value)
null
null
null
What does the code convert into an integer ?
def string_to_int(s): result = 0 for c in s: if (not isinstance(c, int)): c = ord(c) result = ((256 * result) + c) return result
null
null
null
a string of bytes
codeqa
def string to int s result 0for c in s if not isinstance c int c ord c result 256 * result + c return result
null
null
null
null
Question: What does the code convert into an integer ? Code: def string_to_int(s): result = 0 for c in s: if (not isinstance(c, int)): c = ord(c) result = ((256 * result) + c) return result
null
null
null
How did group present ?
def reidemeister_presentation(fp_grp, H, elm_rounds=2, simp_rounds=2): C = coset_enumeration_r(fp_grp, H) C.compress() C.standardize() define_schreier_generators(C) reidemeister_relators(C) for i in range(20): elimination_technique_1(C) simplify_presentation(C) C.schreier_generators = tuple(C._schreier_generators) C.reidemeister_relators = tuple(C._reidemeister_relators) return (C.schreier_generators, C.reidemeister_relators)
null
null
null
finitely
codeqa
def reidemeister presentation fp grp H elm rounds 2 simp rounds 2 C coset enumeration r fp grp H C compress C standardize define schreier generators C reidemeister relators C for i in range 20 elimination technique 1 C simplify presentation C C schreier generators tuple C schreier generators C reidemeister relators tuple C reidemeister relators return C schreier generators C reidemeister relators
null
null
null
null
Question: How did group present ? Code: def reidemeister_presentation(fp_grp, H, elm_rounds=2, simp_rounds=2): C = coset_enumeration_r(fp_grp, H) C.compress() C.standardize() define_schreier_generators(C) reidemeister_relators(C) for i in range(20): elimination_technique_1(C) simplify_presentation(C) C.schreier_generators = tuple(C._schreier_generators) C.reidemeister_relators = tuple(C._reidemeister_relators) return (C.schreier_generators, C.reidemeister_relators)
null
null
null
How does the code trim a string ?
def trim(string): lines = string.expandtabs().splitlines() lines = (list(map(str.lstrip, lines[:1])) + left_trim_lines(lines[1:])) return '\n'.join(trim_leading_lines(trim_trailing_lines(lines)))
null
null
null
in pep-256 compatible way
codeqa
def trim string lines string expandtabs splitlines lines list map str lstrip lines[ 1] + left trim lines lines[ 1 ] return '\n' join trim leading lines trim trailing lines lines
null
null
null
null
Question: How does the code trim a string ? Code: def trim(string): lines = string.expandtabs().splitlines() lines = (list(map(str.lstrip, lines[:1])) + left_trim_lines(lines[1:])) return '\n'.join(trim_leading_lines(trim_trailing_lines(lines)))
null
null
null
What does the code trim in pep-256 compatible way ?
def trim(string): lines = string.expandtabs().splitlines() lines = (list(map(str.lstrip, lines[:1])) + left_trim_lines(lines[1:])) return '\n'.join(trim_leading_lines(trim_trailing_lines(lines)))
null
null
null
a string
codeqa
def trim string lines string expandtabs splitlines lines list map str lstrip lines[ 1] + left trim lines lines[ 1 ] return '\n' join trim leading lines trim trailing lines lines
null
null
null
null
Question: What does the code trim in pep-256 compatible way ? Code: def trim(string): lines = string.expandtabs().splitlines() lines = (list(map(str.lstrip, lines[:1])) + left_trim_lines(lines[1:])) return '\n'.join(trim_leading_lines(trim_trailing_lines(lines)))
null
null
null
For what purpose do the first sentence extract from a block of test ?
def title_from_content(content): for end in (u'. ', u'?', u'!', u'<br />', u'\n', u'</p>'): if (end in content): content = (content.split(end)[0] + end) break return strip_tags(content)
null
null
null
to use as a title
codeqa
def title from content content for end in u' ' u'?' u' ' u'<br/>' u'\n' u'</p>' if end in content content content split end [0 ] + end breakreturn strip tags content
null
null
null
null
Question: For what purpose do the first sentence extract from a block of test ? Code: def title_from_content(content): for end in (u'. ', u'?', u'!', u'<br />', u'\n', u'</p>'): if (end in content): content = (content.split(end)[0] + end) break return strip_tags(content)
null
null
null
What return a geometry ?
def geom_output(func, argtypes): if argtypes: func.argtypes = argtypes func.restype = GEOM_PTR func.errcheck = check_geom return func
null
null
null
routines
codeqa
def geom output func argtypes if argtypes func argtypes argtypesfunc restype GEOM PT Rfunc errcheck check geomreturn func
null
null
null
null
Question: What return a geometry ? Code: def geom_output(func, argtypes): if argtypes: func.argtypes = argtypes func.restype = GEOM_PTR func.errcheck = check_geom return func
null
null
null
What do routines return ?
def geom_output(func, argtypes): if argtypes: func.argtypes = argtypes func.restype = GEOM_PTR func.errcheck = check_geom return func
null
null
null
a geometry
codeqa
def geom output func argtypes if argtypes func argtypes argtypesfunc restype GEOM PT Rfunc errcheck check geomreturn func
null
null
null
null
Question: What do routines return ? Code: def geom_output(func, argtypes): if argtypes: func.argtypes = argtypes func.restype = GEOM_PTR func.errcheck = check_geom return func
null
null
null
What does the code generate ?
def restore(delta, which): try: tag = {1: '- ', 2: '+ '}[int(which)] except KeyError: raise ValueError, ('unknown delta choice (must be 1 or 2): %r' % which) prefixes = (' ', tag) for line in delta: if (line[:2] in prefixes): (yield line[2:])
null
null
null
one of the two sequences that generated a delta
codeqa
def restore delta which try tag {1 '-' 2 '+'}[int which ]except Key Error raise Value Error 'unknowndeltachoice mustbe 1 or 2 %r' % which prefixes '' tag for line in delta if line[ 2] in prefixes yield line[ 2 ]
null
null
null
null
Question: What does the code generate ? Code: def restore(delta, which): try: tag = {1: '- ', 2: '+ '}[int(which)] except KeyError: raise ValueError, ('unknown delta choice (must be 1 or 2): %r' % which) prefixes = (' ', tag) for line in delta: if (line[:2] in prefixes): (yield line[2:])
null
null
null
What did the two sequences generate ?
def restore(delta, which): try: tag = {1: '- ', 2: '+ '}[int(which)] except KeyError: raise ValueError, ('unknown delta choice (must be 1 or 2): %r' % which) prefixes = (' ', tag) for line in delta: if (line[:2] in prefixes): (yield line[2:])
null
null
null
a delta
codeqa
def restore delta which try tag {1 '-' 2 '+'}[int which ]except Key Error raise Value Error 'unknowndeltachoice mustbe 1 or 2 %r' % which prefixes '' tag for line in delta if line[ 2] in prefixes yield line[ 2 ]
null
null
null
null
Question: What did the two sequences generate ? Code: def restore(delta, which): try: tag = {1: '- ', 2: '+ '}[int(which)] except KeyError: raise ValueError, ('unknown delta choice (must be 1 or 2): %r' % which) prefixes = (' ', tag) for line in delta: if (line[:2] in prefixes): (yield line[2:])
null
null
null
What generated a delta ?
def restore(delta, which): try: tag = {1: '- ', 2: '+ '}[int(which)] except KeyError: raise ValueError, ('unknown delta choice (must be 1 or 2): %r' % which) prefixes = (' ', tag) for line in delta: if (line[:2] in prefixes): (yield line[2:])
null
null
null
the two sequences
codeqa
def restore delta which try tag {1 '-' 2 '+'}[int which ]except Key Error raise Value Error 'unknowndeltachoice mustbe 1 or 2 %r' % which prefixes '' tag for line in delta if line[ 2] in prefixes yield line[ 2 ]
null
null
null
null
Question: What generated a delta ? Code: def restore(delta, which): try: tag = {1: '- ', 2: '+ '}[int(which)] except KeyError: raise ValueError, ('unknown delta choice (must be 1 or 2): %r' % which) prefixes = (' ', tag) for line in delta: if (line[:2] in prefixes): (yield line[2:])
null
null
null
For what purpose do two records compare ?
def do_comparison(good_record, test_record): good_handle = StringIO(good_record) test_handle = StringIO(test_record) while True: good_line = good_handle.readline() test_line = test_handle.readline() if ((not good_line) and (not test_line)): break if (not good_line): if good_line.strip(): raise AssertionError(('Extra info in Test: `%s`' % test_line)) if (not test_line): if test_line.strip(): raise AssertionError(('Extra info in Expected: `%s`' % good_line)) assert (test_line == good_line), ('Expected does not match Test.\nExpect:`%s`\nTest :`%s`\n' % (good_line, test_line))
null
null
null
to see if they are the same
codeqa
def do comparison good record test record good handle String IO good record test handle String IO test record while True good line good handle readline test line test handle readline if not good line and not test line breakif not good line if good line strip raise Assertion Error ' Extrainfoin Test `%s`' % test line if not test line if test line strip raise Assertion Error ' Extrainfoin Expected `%s`' % good line assert test line good line ' Expecteddoesnotmatch Test \n Expect `%s`\n Test `%s`\n' % good line test line
null
null
null
null
Question: For what purpose do two records compare ? Code: def do_comparison(good_record, test_record): good_handle = StringIO(good_record) test_handle = StringIO(test_record) while True: good_line = good_handle.readline() test_line = test_handle.readline() if ((not good_line) and (not test_line)): break if (not good_line): if good_line.strip(): raise AssertionError(('Extra info in Test: `%s`' % test_line)) if (not test_line): if test_line.strip(): raise AssertionError(('Extra info in Expected: `%s`' % good_line)) assert (test_line == good_line), ('Expected does not match Test.\nExpect:`%s`\nTest :`%s`\n' % (good_line, test_line))
null
null
null
What does the code transform by the projection matrix ?
def proj_transform(xs, ys, zs, M): vec = vec_pad_ones(xs, ys, zs) return proj_transform_vec(vec, M)
null
null
null
the points
codeqa
def proj transform xs ys zs M vec vec pad ones xs ys zs return proj transform vec vec M
null
null
null
null
Question: What does the code transform by the projection matrix ? Code: def proj_transform(xs, ys, zs, M): vec = vec_pad_ones(xs, ys, zs) return proj_transform_vec(vec, M)
null
null
null
How does the code transform the points ?
def proj_transform(xs, ys, zs, M): vec = vec_pad_ones(xs, ys, zs) return proj_transform_vec(vec, M)
null
null
null
by the projection matrix
codeqa
def proj transform xs ys zs M vec vec pad ones xs ys zs return proj transform vec vec M
null
null
null
null
Question: How does the code transform the points ? Code: def proj_transform(xs, ys, zs, M): vec = vec_pad_ones(xs, ys, zs) return proj_transform_vec(vec, M)
null
null
null
What will it return ?
def secure_filename(filename): if isinstance(filename, text_type): from unicodedata import normalize filename = normalize('NFKD', filename).encode('ascii', 'ignore') if (not PY2): filename = filename.decode('ascii') for sep in (os.path.sep, os.path.altsep): if sep: filename = filename.replace(sep, ' ') filename = str(_filename_ascii_strip_re.sub('', '_'.join(filename.split()))).strip('._') if ((os.name == 'nt') and filename and (filename.split('.')[0].upper() in _windows_device_files)): filename = ('_' + filename) return filename
null
null
null
a secure version of it
codeqa
def secure filename filename if isinstance filename text type from unicodedata import normalizefilename normalize 'NFKD' filename encode 'ascii' 'ignore' if not PY 2 filename filename decode 'ascii' for sep in os path sep os path altsep if sep filename filename replace sep '' filename str filename ascii strip re sub '' ' ' join filename split strip ' ' if os name 'nt' and filename and filename split ' ' [0 ] upper in windows device files filename ' ' + filename return filename
null
null
null
null
Question: What will it return ? Code: def secure_filename(filename): if isinstance(filename, text_type): from unicodedata import normalize filename = normalize('NFKD', filename).encode('ascii', 'ignore') if (not PY2): filename = filename.decode('ascii') for sep in (os.path.sep, os.path.altsep): if sep: filename = filename.replace(sep, ' ') filename = str(_filename_ascii_strip_re.sub('', '_'.join(filename.split()))).strip('._') if ((os.name == 'nt') and filename and (filename.split('.')[0].upper() in _windows_device_files)): filename = ('_' + filename) return filename
null
null
null
For what purpose does the code update the glance metadata ?
def volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id): return IMPL.volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id)
null
null
null
for a snapshot
codeqa
def volume glance metadata copy to snapshot context snapshot id volume id return IMPL volume glance metadata copy to snapshot context snapshot id volume id
null
null
null
null
Question: For what purpose does the code update the glance metadata ? Code: def volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id): return IMPL.volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id)
null
null
null
What does the code update for a snapshot ?
def volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id): return IMPL.volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id)
null
null
null
the glance metadata
codeqa
def volume glance metadata copy to snapshot context snapshot id volume id return IMPL volume glance metadata copy to snapshot context snapshot id volume id
null
null
null
null
Question: What does the code update for a snapshot ? Code: def volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id): return IMPL.volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id)
null
null
null
How does the code convert a text string to a byte string ?
def t2b(t): clean = b(rws(t)) if ((len(clean) % 2) == 1): raise ValueError('Even number of characters expected') return a2b_hex(clean)
null
null
null
with bytes in hex form
codeqa
def t2 b t clean b rws t if len clean % 2 1 raise Value Error ' Evennumberofcharactersexpected' return a2 b hex clean
null
null
null
null
Question: How does the code convert a text string to a byte string ? Code: def t2b(t): clean = b(rws(t)) if ((len(clean) % 2) == 1): raise ValueError('Even number of characters expected') return a2b_hex(clean)
null
null
null
What does the code add into the task queue ?
def _enqueue_suggestion_email_task(exploration_id, thread_id): payload = {'exploration_id': exploration_id, 'thread_id': thread_id} taskqueue_services.enqueue_task(feconf.TASK_URL_SUGGESTION_EMAILS, payload, 0)
null
null
null
a send suggestion email task
codeqa
def enqueue suggestion email task exploration id thread id payload {'exploration id' exploration id 'thread id' thread id}taskqueue services enqueue task feconf TASK URL SUGGESTION EMAILS payload 0
null
null
null
null
Question: What does the code add into the task queue ? Code: def _enqueue_suggestion_email_task(exploration_id, thread_id): payload = {'exploration_id': exploration_id, 'thread_id': thread_id} taskqueue_services.enqueue_task(feconf.TASK_URL_SUGGESTION_EMAILS, payload, 0)
null
null
null
What does the code get ?
def do_get_relationship(parser, token): bits = token.contents.split() if (len(bits) == 3): return GetRelationship(bits[1], bits[2]) if (len(bits) == 5): return GetRelationship(bits[1], bits[2], bits[4]) if (len(bits) == 4): raise template.TemplateSyntaxError, ("The tag '%s' needs an 'as' as its third argument." % bits[0]) if (len(bits) < 3): raise template.TemplateSyntaxError, ("The tag '%s' takes two arguments" % bits[0])
null
null
null
relationship between two users
codeqa
def do get relationship parser token bits token contents split if len bits 3 return Get Relationship bits[ 1 ] bits[ 2 ] if len bits 5 return Get Relationship bits[ 1 ] bits[ 2 ] bits[ 4 ] if len bits 4 raise template Template Syntax Error " Thetag'%s'needsan'as'asitsthirdargument " % bits[ 0 ] if len bits < 3 raise template Template Syntax Error " Thetag'%s'takestwoarguments" % bits[ 0 ]
null
null
null
null
Question: What does the code get ? Code: def do_get_relationship(parser, token): bits = token.contents.split() if (len(bits) == 3): return GetRelationship(bits[1], bits[2]) if (len(bits) == 5): return GetRelationship(bits[1], bits[2], bits[4]) if (len(bits) == 4): raise template.TemplateSyntaxError, ("The tag '%s' needs an 'as' as its third argument." % bits[0]) if (len(bits) < 3): raise template.TemplateSyntaxError, ("The tag '%s' takes two arguments" % bits[0])
null
null
null
What do we have still ?
def keep_awake(): if (KERNEL32 or sleepless): if sabnzbd.cfg.keep_awake(): awake = False if (not sabnzbd.downloader.Downloader.do.paused): if ((not PostProcessor.do.empty()) or (not NzbQueue.do.is_empty())): awake = True if KERNEL32: KERNEL32.SetThreadExecutionState(ctypes.c_int(1)) else: sleepless.keep_awake(u'SABnzbd is busy downloading and/or post-processing') if ((not awake) and sleepless): sleepless.allow_sleep()
null
null
null
work to do
codeqa
def keep awake if KERNEL 32 or sleepless if sabnzbd cfg keep awake awake Falseif not sabnzbd downloader Downloader do paused if not Post Processor do empty or not Nzb Queue do is empty awake Trueif KERNEL 32 KERNEL 32 Set Thread Execution State ctypes c int 1 else sleepless keep awake u'SA Bnzbdisbusydownloadingand/orpost-processing' if not awake and sleepless sleepless allow sleep
null
null
null
null
Question: What do we have still ? Code: def keep_awake(): if (KERNEL32 or sleepless): if sabnzbd.cfg.keep_awake(): awake = False if (not sabnzbd.downloader.Downloader.do.paused): if ((not PostProcessor.do.empty()) or (not NzbQueue.do.is_empty())): awake = True if KERNEL32: KERNEL32.SetThreadExecutionState(ctypes.c_int(1)) else: sleepless.keep_awake(u'SABnzbd is busy downloading and/or post-processing') if ((not awake) and sleepless): sleepless.allow_sleep()
null
null
null
Till when do we have work to do ?
def keep_awake(): if (KERNEL32 or sleepless): if sabnzbd.cfg.keep_awake(): awake = False if (not sabnzbd.downloader.Downloader.do.paused): if ((not PostProcessor.do.empty()) or (not NzbQueue.do.is_empty())): awake = True if KERNEL32: KERNEL32.SetThreadExecutionState(ctypes.c_int(1)) else: sleepless.keep_awake(u'SABnzbd is busy downloading and/or post-processing') if ((not awake) and sleepless): sleepless.allow_sleep()
null
null
null
still
codeqa
def keep awake if KERNEL 32 or sleepless if sabnzbd cfg keep awake awake Falseif not sabnzbd downloader Downloader do paused if not Post Processor do empty or not Nzb Queue do is empty awake Trueif KERNEL 32 KERNEL 32 Set Thread Execution State ctypes c int 1 else sleepless keep awake u'SA Bnzbdisbusydownloadingand/orpost-processing' if not awake and sleepless sleepless allow sleep
null
null
null
null
Question: Till when do we have work to do ? Code: def keep_awake(): if (KERNEL32 or sleepless): if sabnzbd.cfg.keep_awake(): awake = False if (not sabnzbd.downloader.Downloader.do.paused): if ((not PostProcessor.do.empty()) or (not NzbQueue.do.is_empty())): awake = True if KERNEL32: KERNEL32.SetThreadExecutionState(ctypes.c_int(1)) else: sleepless.keep_awake(u'SABnzbd is busy downloading and/or post-processing') if ((not awake) and sleepless): sleepless.allow_sleep()
null
null
null
What does the code get ?
def read_index(group): return (u'%s_%s' % (settings.ES_INDEX_PREFIX, settings.ES_INDEXES[group]))
null
null
null
the name of the read index for a group
codeqa
def read index group return u'%s %s' % settings ES INDEX PREFIX settings ES INDEXES[group]
null
null
null
null
Question: What does the code get ? Code: def read_index(group): return (u'%s_%s' % (settings.ES_INDEX_PREFIX, settings.ES_INDEXES[group]))
null
null
null
Why could groups be split ?
def find_first_level_groups(string, enclosing, blank_sep=None): groups = find_first_level_groups_span(string, enclosing) if blank_sep: for (start, end) in groups: string = str_replace(string, start, blank_sep) string = str_replace(string, (end - 1), blank_sep) return split_on_groups(string, groups)
null
null
null
because of explicit grouping
codeqa
def find first level groups string enclosing blank sep None groups find first level groups span string enclosing if blank sep for start end in groups string str replace string start blank sep string str replace string end - 1 blank sep return split on groups string groups
null
null
null
null
Question: Why could groups be split ? Code: def find_first_level_groups(string, enclosing, blank_sep=None): groups = find_first_level_groups_span(string, enclosing) if blank_sep: for (start, end) in groups: string = str_replace(string, start, blank_sep) string = str_replace(string, (end - 1), blank_sep) return split_on_groups(string, groups)
null
null
null
How did validator couple validator to the implementation of the classes here ?
def _validator(validator): name = validator.__name__ doc = validator.__doc__ def fget(self): return self._tls[name] def fset(self, val): self._tls[name] = validator(self, val) def fdel(self): self._tls._current.pop(name, None) return property(fget, fset, fdel, doc)
null
null
null
tightly
codeqa
def validator validator name validator name doc validator doc def fget self return self tls[name]def fset self val self tls[name] validator self val def fdel self self tls current pop name None return property fget fset fdel doc
null
null
null
null
Question: How did validator couple validator to the implementation of the classes here ? Code: def _validator(validator): name = validator.__name__ doc = validator.__doc__ def fget(self): return self._tls[name] def fset(self, val): self._tls[name] = validator(self, val) def fdel(self): self._tls._current.pop(name, None) return property(fget, fset, fdel, doc)