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 has been set to allow inheritance across forks and execs to child processes ?
def get_socket_inherit(socket): try: if iswindows: import win32api, win32con flags = win32api.GetHandleInformation(socket.fileno()) return bool((flags & win32con.HANDLE_FLAG_INHERIT)) else: import fcntl flags = fcntl.fcntl(socket.fileno(), fcntl.F_GETFD) return (not bool((flags & fcntl.FD_CLOEXEC))) except: import traceback traceback.print_exc()
null
null
null
the socket
codeqa
def get socket inherit socket try if iswindows import win 32 api win 32 conflags win 32 api Get Handle Information socket fileno return bool flags & win 32 con HANDLE FLAG INHERIT else import fcntlflags fcntl fcntl socket fileno fcntl F GETFD return not bool flags & fcntl FD CLOEXEC except import tracebacktraceback print exc
null
null
null
null
Question: What has been set to allow inheritance across forks and execs to child processes ? Code: def get_socket_inherit(socket): try: if iswindows: import win32api, win32con flags = win32api.GetHandleInformation(socket.fileno()) return bool((flags & win32con.HANDLE_FLAG_INHERIT)) else: import fcntl flags = fcntl.fcntl(socket.fileno(), fcntl.F_GETFD) return (not bool((flags & fcntl.FD_CLOEXEC))) except: import traceback traceback.print_exc()
null
null
null
What does the code get ?
def insert(collection_name, docs, check_keys, safe, last_error_args, continue_on_error, opts): options = 0 if continue_on_error: options += 1 data = struct.pack('<i', options) data += bson._make_c_string(collection_name) encoded = [bson.BSON.encode(doc, check_keys, opts) for doc in docs] if (not encoded): raise InvalidOperation('cannot do an empty bulk insert') max_bson_size = max(map(len, encoded)) data += _EMPTY.join(encoded) if safe: (_, insert_message) = __pack_message(2002, data) (request_id, error_message, _) = __last_error(collection_name, last_error_args) return (request_id, (insert_message + error_message), max_bson_size) else: (request_id, insert_message) = __pack_message(2002, data) return (request_id, insert_message, max_bson_size)
null
null
null
an * * insert * * message
codeqa
def insert collection name docs check keys safe last error args continue on error opts options 0if continue on error options + 1data struct pack '<i' options data + bson make c string collection name encoded [bson BSON encode doc check keys opts for doc in docs]if not encoded raise Invalid Operation 'cannotdoanemptybulkinsert' max bson size max map len encoded data + EMPTY join encoded if safe insert message pack message 2002 data request id error message last error collection name last error args return request id insert message + error message max bson size else request id insert message pack message 2002 data return request id insert message max bson size
null
null
null
null
Question: What does the code get ? Code: def insert(collection_name, docs, check_keys, safe, last_error_args, continue_on_error, opts): options = 0 if continue_on_error: options += 1 data = struct.pack('<i', options) data += bson._make_c_string(collection_name) encoded = [bson.BSON.encode(doc, check_keys, opts) for doc in docs] if (not encoded): raise InvalidOperation('cannot do an empty bulk insert') max_bson_size = max(map(len, encoded)) data += _EMPTY.join(encoded) if safe: (_, insert_message) = __pack_message(2002, data) (request_id, error_message, _) = __last_error(collection_name, last_error_args) return (request_id, (insert_message + error_message), max_bson_size) else: (request_id, insert_message) = __pack_message(2002, data) return (request_id, insert_message, max_bson_size)
null
null
null
What does the code open in it ?
@cli.command() def edit(): MARKER = '# Everything below is ignored\n' message = click.edit(('\n\n' + MARKER)) if (message is not None): msg = message.split(MARKER, 1)[0].rstrip('\n') if (not msg): click.echo('Empty message!') else: click.echo(('Message:\n' + msg)) else: click.echo('You did not enter anything!')
null
null
null
an editor with some text
codeqa
@cli command def edit MARKER '# Everythingbelowisignored\n'message click edit '\n\n' + MARKER if message is not None msg message split MARKER 1 [0 ] rstrip '\n' if not msg click echo ' Emptymessage ' else click echo ' Message \n' + msg else click echo ' Youdidnotenteranything '
null
null
null
null
Question: What does the code open in it ? Code: @cli.command() def edit(): MARKER = '# Everything below is ignored\n' message = click.edit(('\n\n' + MARKER)) if (message is not None): msg = message.split(MARKER, 1)[0].rstrip('\n') if (not msg): click.echo('Empty message!') else: click.echo(('Message:\n' + msg)) else: click.echo('You did not enter anything!')
null
null
null
Where does the code open an editor with some text ?
@cli.command() def edit(): MARKER = '# Everything below is ignored\n' message = click.edit(('\n\n' + MARKER)) if (message is not None): msg = message.split(MARKER, 1)[0].rstrip('\n') if (not msg): click.echo('Empty message!') else: click.echo(('Message:\n' + msg)) else: click.echo('You did not enter anything!')
null
null
null
in it
codeqa
@cli command def edit MARKER '# Everythingbelowisignored\n'message click edit '\n\n' + MARKER if message is not None msg message split MARKER 1 [0 ] rstrip '\n' if not msg click echo ' Emptymessage ' else click echo ' Message \n' + msg else click echo ' Youdidnotenteranything '
null
null
null
null
Question: Where does the code open an editor with some text ? Code: @cli.command() def edit(): MARKER = '# Everything below is ignored\n' message = click.edit(('\n\n' + MARKER)) if (message is not None): msg = message.split(MARKER, 1)[0].rstrip('\n') if (not msg): click.echo('Empty message!') else: click.echo(('Message:\n' + msg)) else: click.echo('You did not enter anything!')
null
null
null
For what purpose does the code check a string ?
def safe_py_code(code): bads = ('import', ';', 'subprocess', 'eval', 'open', 'file', 'exec', 'input') for bad in bads: if code.count(bad): return False return True
null
null
null
to see if it has any potentially unsafe routines which could be executed via python
codeqa
def safe py code code bads 'import' ' ' 'subprocess' 'eval' 'open' 'file' 'exec' 'input' for bad in bads if code count bad return Falsereturn True
null
null
null
null
Question: For what purpose does the code check a string ? Code: def safe_py_code(code): bads = ('import', ';', 'subprocess', 'eval', 'open', 'file', 'exec', 'input') for bad in bads: if code.count(bad): return False return True
null
null
null
How could any potentially unsafe routines be executed ?
def safe_py_code(code): bads = ('import', ';', 'subprocess', 'eval', 'open', 'file', 'exec', 'input') for bad in bads: if code.count(bad): return False return True
null
null
null
via python
codeqa
def safe py code code bads 'import' ' ' 'subprocess' 'eval' 'open' 'file' 'exec' 'input' for bad in bads if code count bad return Falsereturn True
null
null
null
null
Question: How could any potentially unsafe routines be executed ? Code: def safe_py_code(code): bads = ('import', ';', 'subprocess', 'eval', 'open', 'file', 'exec', 'input') for bad in bads: if code.count(bad): return False return True
null
null
null
What does the code check to see if it has any potentially unsafe routines which could be executed via python ?
def safe_py_code(code): bads = ('import', ';', 'subprocess', 'eval', 'open', 'file', 'exec', 'input') for bad in bads: if code.count(bad): return False return True
null
null
null
a string
codeqa
def safe py code code bads 'import' ' ' 'subprocess' 'eval' 'open' 'file' 'exec' 'input' for bad in bads if code count bad return Falsereturn True
null
null
null
null
Question: What does the code check to see if it has any potentially unsafe routines which could be executed via python ? Code: def safe_py_code(code): bads = ('import', ';', 'subprocess', 'eval', 'open', 'file', 'exec', 'input') for bad in bads: if code.count(bad): return False return True
null
null
null
How do the home directory of the user change ?
def chhome(name, home, **kwargs): kwargs = salt.utils.clean_kwargs(**kwargs) persist = kwargs.pop('persist', False) if kwargs: salt.utils.invalid_kwargs(kwargs) if persist: log.info("Ignoring unsupported 'persist' argument to user.chhome") pre_info = info(name) if (not pre_info): raise CommandExecutionError("User '{0}' does not exist".format(name)) if (home == pre_info['home']): return True _dscl(['/Users/{0}'.format(name), 'NFSHomeDirectory', pre_info['home'], home], ctype='change') time.sleep(1) return (info(name).get('home') == home)
null
null
null
cli
codeqa
def chhome name home **kwargs kwargs salt utils clean kwargs **kwargs persist kwargs pop 'persist' False if kwargs salt utils invalid kwargs kwargs if persist log info " Ignoringunsupported'persist'argumenttouser chhome" pre info info name if not pre info raise Command Execution Error " User'{ 0 }'doesnotexist" format name if home pre info['home'] return True dscl ['/ Users/{ 0 }' format name 'NFS Home Directory' pre info['home'] home] ctype 'change' time sleep 1 return info name get 'home' home
null
null
null
null
Question: How do the home directory of the user change ? Code: def chhome(name, home, **kwargs): kwargs = salt.utils.clean_kwargs(**kwargs) persist = kwargs.pop('persist', False) if kwargs: salt.utils.invalid_kwargs(kwargs) if persist: log.info("Ignoring unsupported 'persist' argument to user.chhome") pre_info = info(name) if (not pre_info): raise CommandExecutionError("User '{0}' does not exist".format(name)) if (home == pre_info['home']): return True _dscl(['/Users/{0}'.format(name), 'NFSHomeDirectory', pre_info['home'], home], ctype='change') time.sleep(1) return (info(name).get('home') == home)
null
null
null
For what purpose does the code render a page to the user ?
def showDecidePage(request, openid_request): trust_root = openid_request.trust_root return_to = openid_request.return_to try: trust_root_valid = ((verifyReturnTo(trust_root, return_to) and 'Valid') or 'Invalid') except DiscoveryFailure as err: trust_root_valid = 'DISCOVERY_FAILED' except HTTPFetchingError as err: trust_root_valid = 'Unreachable' pape_request = pape.Request.fromOpenIDRequest(openid_request) return direct_to_template(request, 'server/trust.html', {'trust_root': trust_root, 'trust_handler_url': getViewURL(request, processTrustResult), 'trust_root_valid': trust_root_valid, 'pape_request': pape_request})
null
null
null
so a trust decision can be made
codeqa
def show Decide Page request openid request trust root openid request trust rootreturn to openid request return totry trust root valid verify Return To trust root return to and ' Valid' or ' Invalid' except Discovery Failure as err trust root valid 'DISCOVERY FAILED'except HTTP Fetching Error as err trust root valid ' Unreachable'pape request pape Request from Open ID Request openid request return direct to template request 'server/trust html' {'trust root' trust root 'trust handler url' get View URL request process Trust Result 'trust root valid' trust root valid 'pape request' pape request}
null
null
null
null
Question: For what purpose does the code render a page to the user ? Code: def showDecidePage(request, openid_request): trust_root = openid_request.trust_root return_to = openid_request.return_to try: trust_root_valid = ((verifyReturnTo(trust_root, return_to) and 'Valid') or 'Invalid') except DiscoveryFailure as err: trust_root_valid = 'DISCOVERY_FAILED' except HTTPFetchingError as err: trust_root_valid = 'Unreachable' pape_request = pape.Request.fromOpenIDRequest(openid_request) return direct_to_template(request, 'server/trust.html', {'trust_root': trust_root, 'trust_handler_url': getViewURL(request, processTrustResult), 'trust_root_valid': trust_root_valid, 'pape_request': pape_request})
null
null
null
Who have desire to have ?
def has_database_privileges(cursor, user, db, privs): cur_privs = get_database_privileges(cursor, user, db) have_currently = cur_privs.intersection(privs) other_current = cur_privs.difference(privs) desired = privs.difference(cur_privs) return (have_currently, other_current, desired)
null
null
null
they
codeqa
def has database privileges cursor user db privs cur privs get database privileges cursor user db have currently cur privs intersection privs other current cur privs difference privs desired privs difference cur privs return have currently other current desired
null
null
null
null
Question: Who have desire to have ? Code: def has_database_privileges(cursor, user, db, privs): cur_privs = get_database_privileges(cursor, user, db) have_currently = cur_privs.intersection(privs) other_current = cur_privs.difference(privs) desired = privs.difference(cur_privs) return (have_currently, other_current, desired)
null
null
null
When does a user have the privileges ?
def has_database_privileges(cursor, user, db, privs): cur_privs = get_database_privileges(cursor, user, db) have_currently = cur_privs.intersection(privs) other_current = cur_privs.difference(privs) desired = privs.difference(cur_privs) return (have_currently, other_current, desired)
null
null
null
already
codeqa
def has database privileges cursor user db privs cur privs get database privileges cursor user db have currently cur privs intersection privs other current cur privs difference privs desired privs difference cur privs return have currently other current desired
null
null
null
null
Question: When does a user have the privileges ? Code: def has_database_privileges(cursor, user, db, privs): cur_privs = get_database_privileges(cursor, user, db) have_currently = cur_privs.intersection(privs) other_current = cur_privs.difference(privs) desired = privs.difference(cur_privs) return (have_currently, other_current, desired)
null
null
null
What does the code create ?
def header_property(name, doc, transform=None): normalized_name = name.lower() def fget(self): try: return self._headers[normalized_name] except KeyError: return None if (transform is None): if six.PY2: def fset(self, value): self._headers[normalized_name] = str(value) else: def fset(self, value): self._headers[normalized_name] = value else: def fset(self, value): self._headers[normalized_name] = transform(value) def fdel(self): del self._headers[normalized_name] return property(fget, fset, fdel, doc)
null
null
null
a header getter / setter
codeqa
def header property name doc transform None normalized name name lower def fget self try return self headers[normalized name]except Key Error return Noneif transform is None if six PY 2 def fset self value self headers[normalized name] str value else def fset self value self headers[normalized name] valueelse def fset self value self headers[normalized name] transform value def fdel self del self headers[normalized name]return property fget fset fdel doc
null
null
null
null
Question: What does the code create ? Code: def header_property(name, doc, transform=None): normalized_name = name.lower() def fget(self): try: return self._headers[normalized_name] except KeyError: return None if (transform is None): if six.PY2: def fset(self, value): self._headers[normalized_name] = str(value) else: def fset(self, value): self._headers[normalized_name] = value else: def fset(self, value): self._headers[normalized_name] = transform(value) def fdel(self): del self._headers[normalized_name] return property(fget, fset, fdel, doc)
null
null
null
What does the code extract from a raw byte string ?
def extract_num(buf, start, length): val = 0 for i in range(start, (start + length)): val <<= 8 val += ord(buf[i]) return val
null
null
null
a number
codeqa
def extract num buf start length val 0for i in range start start + length val << 8val + ord buf[i] return val
null
null
null
null
Question: What does the code extract from a raw byte string ? Code: def extract_num(buf, start, length): val = 0 for i in range(start, (start + length)): val <<= 8 val += ord(buf[i]) return val
null
null
null
What did the code set ?
def set_system_time(newtime): fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if (dt_obj is None): return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second)
null
null
null
the system time
codeqa
def set system time newtime fmts ['%I %M %S%p' '%I %M%p' '%H %M %S' '%H %M']dt obj try parse datetime newtime fmts if dt obj is None return Falsereturn set system date time hours dt obj hour minutes dt obj minute seconds dt obj second
null
null
null
null
Question: What did the code set ? Code: def set_system_time(newtime): fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if (dt_obj is None): return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second)
null
null
null
What does the code get ?
def getPluginFileNamesFromDirectoryPath(directoryPath): fileInDirectory = os.path.join(directoryPath, '__init__.py') fullPluginFileNames = getPythonFileNamesExceptInit(fileInDirectory) pluginFileNames = [] for fullPluginFileName in fullPluginFileNames: pluginBasename = os.path.basename(fullPluginFileName) pluginBasename = getUntilDot(pluginBasename) pluginFileNames.append(pluginBasename) return pluginFileNames
null
null
null
the file names of the python plugins in the directory path
codeqa
def get Plugin File Names From Directory Path directory Path file In Directory os path join directory Path ' init py' full Plugin File Names get Python File Names Except Init file In Directory plugin File Names []for full Plugin File Name in full Plugin File Names plugin Basename os path basename full Plugin File Name plugin Basename get Until Dot plugin Basename plugin File Names append plugin Basename return plugin File Names
null
null
null
null
Question: What does the code get ? Code: def getPluginFileNamesFromDirectoryPath(directoryPath): fileInDirectory = os.path.join(directoryPath, '__init__.py') fullPluginFileNames = getPythonFileNamesExceptInit(fileInDirectory) pluginFileNames = [] for fullPluginFileName in fullPluginFileNames: pluginBasename = os.path.basename(fullPluginFileName) pluginBasename = getUntilDot(pluginBasename) pluginFileNames.append(pluginBasename) return pluginFileNames
null
null
null
What did the code set ?
def setup(hass, config): if ('dev' in CURRENT_VERSION): _LOGGER.warning("Updater component enabled in 'dev'. No notifications but analytics will be submitted") config = config.get(DOMAIN, {}) huuid = (_load_uuid(hass) if config.get(CONF_REPORTING) else None) _dt = (datetime.now() + timedelta(hours=1)) event.track_time_change(hass, (lambda _: check_newest_version(hass, huuid)), hour=_dt.hour, minute=_dt.minute, second=_dt.second) return True
null
null
null
the updater component
codeqa
def setup hass config if 'dev' in CURRENT VERSION LOGGER warning " Updatercomponentenabledin'dev' Nonotificationsbutanalyticswillbesubmitted" config config get DOMAIN {} huuid load uuid hass if config get CONF REPORTING else None dt datetime now + timedelta hours 1 event track time change hass lambda check newest version hass huuid hour dt hour minute dt minute second dt second return True
null
null
null
null
Question: What did the code set ? Code: def setup(hass, config): if ('dev' in CURRENT_VERSION): _LOGGER.warning("Updater component enabled in 'dev'. No notifications but analytics will be submitted") config = config.get(DOMAIN, {}) huuid = (_load_uuid(hass) if config.get(CONF_REPORTING) else None) _dt = (datetime.now() + timedelta(hours=1)) event.track_time_change(hass, (lambda _: check_newest_version(hass, huuid)), hour=_dt.hour, minute=_dt.minute, second=_dt.second) return True
null
null
null
What does the code get ?
def getNewDerivation(elementNode, prefix, sideLength): return BottomDerivation(elementNode, '')
null
null
null
new derivation
codeqa
def get New Derivation element Node prefix side Length return Bottom Derivation element Node ''
null
null
null
null
Question: What does the code get ? Code: def getNewDerivation(elementNode, prefix, sideLength): return BottomDerivation(elementNode, '')
null
null
null
What does the code run ?
def run_example(example, reporter=None): if reporter: reporter.write(example) else: print(('=' * 79)) print('Running: ', example) try: mod = load_example_module(example) if reporter: suppress_output(mod.main) reporter.write('[PASS]', 'Green', align='right') else: mod.main() return True except KeyboardInterrupt as e: raise e except: if reporter: reporter.write('[FAIL]', 'Red', align='right') traceback.print_exc() return False
null
null
null
a specific example
codeqa
def run example example reporter None if reporter reporter write example else print ' ' * 79 print ' Running ' example try mod load example module example if reporter suppress output mod main reporter write '[PASS]' ' Green' align 'right' else mod main return Trueexcept Keyboard Interrupt as e raise eexcept if reporter reporter write '[FAIL]' ' Red' align 'right' traceback print exc return False
null
null
null
null
Question: What does the code run ? Code: def run_example(example, reporter=None): if reporter: reporter.write(example) else: print(('=' * 79)) print('Running: ', example) try: mod = load_example_module(example) if reporter: suppress_output(mod.main) reporter.write('[PASS]', 'Green', align='right') else: mod.main() return True except KeyboardInterrupt as e: raise e except: if reporter: reporter.write('[FAIL]', 'Red', align='right') traceback.print_exc() return False
null
null
null
What does the code add ?
def add_catalog_discover_hack(service_type, old, new): _discover._VERSION_HACKS.add_discover_hack(service_type, old, new)
null
null
null
a version removal rule for a particular service
codeqa
def add catalog discover hack service type old new discover VERSION HACKS add discover hack service type old new
null
null
null
null
Question: What does the code add ? Code: def add_catalog_discover_hack(service_type, old, new): _discover._VERSION_HACKS.add_discover_hack(service_type, old, new)
null
null
null
What is what we are testing ?
def test_import(): from ... import numpy as anp assert (anp.matmul is matmul)
null
null
null
what is imported from code
codeqa
def test import from import numpy as anpassert anp matmul is matmul
null
null
null
null
Question: What is what we are testing ? Code: def test_import(): from ... import numpy as anp assert (anp.matmul is matmul)
null
null
null
What do what is imported from code be ?
def test_import(): from ... import numpy as anp assert (anp.matmul is matmul)
null
null
null
what we are testing
codeqa
def test import from import numpy as anpassert anp matmul is matmul
null
null
null
null
Question: What do what is imported from code be ? Code: def test_import(): from ... import numpy as anp assert (anp.matmul is matmul)
null
null
null
How is what imported ?
def test_import(): from ... import numpy as anp assert (anp.matmul is matmul)
null
null
null
from code
codeqa
def test import from import numpy as anpassert anp matmul is matmul
null
null
null
null
Question: How is what imported ? Code: def test_import(): from ... import numpy as anp assert (anp.matmul is matmul)
null
null
null
What are we testing ?
def test_import(): from ... import numpy as anp assert (anp.matmul is matmul)
null
null
null
what
codeqa
def test import from import numpy as anpassert anp matmul is matmul
null
null
null
null
Question: What are we testing ? Code: def test_import(): from ... import numpy as anp assert (anp.matmul is matmul)
null
null
null
How does a view apply the task ?
def task_view(task): def _applier(request, **options): kwargs = kwdict((((request.method == 'POST') and request.POST.copy()) or request.GET.copy())) kwargs.update(options) result = task.apply_async(kwargs=kwargs) return JsonResponse({'ok': 'true', 'task_id': result.task_id}) return _applier
null
null
null
asynchronously
codeqa
def task view task def applier request **options kwargs kwdict request method 'POST' and request POST copy or request GET copy kwargs update options result task apply async kwargs kwargs return Json Response {'ok' 'true' 'task id' result task id} return applier
null
null
null
null
Question: How does a view apply the task ? Code: def task_view(task): def _applier(request, **options): kwargs = kwdict((((request.method == 'POST') and request.POST.copy()) or request.GET.copy())) kwargs.update(options) result = task.apply_async(kwargs=kwargs) return JsonResponse({'ok': 'true', 'task_id': result.task_id}) return _applier
null
null
null
What do decorator turn into a view that applies the task asynchronously ?
def task_view(task): def _applier(request, **options): kwargs = kwdict((((request.method == 'POST') and request.POST.copy()) or request.GET.copy())) kwargs.update(options) result = task.apply_async(kwargs=kwargs) return JsonResponse({'ok': 'true', 'task_id': result.task_id}) return _applier
null
null
null
any task
codeqa
def task view task def applier request **options kwargs kwdict request method 'POST' and request POST copy or request GET copy kwargs update options result task apply async kwargs kwargs return Json Response {'ok' 'true' 'task id' result task id} return applier
null
null
null
null
Question: What do decorator turn into a view that applies the task asynchronously ? Code: def task_view(task): def _applier(request, **options): kwargs = kwdict((((request.method == 'POST') and request.POST.copy()) or request.GET.copy())) kwargs.update(options) result = task.apply_async(kwargs=kwargs) return JsonResponse({'ok': 'true', 'task_id': result.task_id}) return _applier
null
null
null
What applies the task asynchronously ?
def task_view(task): def _applier(request, **options): kwargs = kwdict((((request.method == 'POST') and request.POST.copy()) or request.GET.copy())) kwargs.update(options) result = task.apply_async(kwargs=kwargs) return JsonResponse({'ok': 'true', 'task_id': result.task_id}) return _applier
null
null
null
a view
codeqa
def task view task def applier request **options kwargs kwdict request method 'POST' and request POST copy or request GET copy kwargs update options result task apply async kwargs kwargs return Json Response {'ok' 'true' 'task id' result task id} return applier
null
null
null
null
Question: What applies the task asynchronously ? Code: def task_view(task): def _applier(request, **options): kwargs = kwdict((((request.method == 'POST') and request.POST.copy()) or request.GET.copy())) kwargs.update(options) result = task.apply_async(kwargs=kwargs) return JsonResponse({'ok': 'true', 'task_id': result.task_id}) return _applier
null
null
null
What is turning any task into a view that applies the task asynchronously ?
def task_view(task): def _applier(request, **options): kwargs = kwdict((((request.method == 'POST') and request.POST.copy()) or request.GET.copy())) kwargs.update(options) result = task.apply_async(kwargs=kwargs) return JsonResponse({'ok': 'true', 'task_id': result.task_id}) return _applier
null
null
null
decorator
codeqa
def task view task def applier request **options kwargs kwdict request method 'POST' and request POST copy or request GET copy kwargs update options result task apply async kwargs kwargs return Json Response {'ok' 'true' 'task id' result task id} return applier
null
null
null
null
Question: What is turning any task into a view that applies the task asynchronously ? Code: def task_view(task): def _applier(request, **options): kwargs = kwdict((((request.method == 'POST') and request.POST.copy()) or request.GET.copy())) kwargs.update(options) result = task.apply_async(kwargs=kwargs) return JsonResponse({'ok': 'true', 'task_id': result.task_id}) return _applier
null
null
null
What does a view apply asynchronously ?
def task_view(task): def _applier(request, **options): kwargs = kwdict((((request.method == 'POST') and request.POST.copy()) or request.GET.copy())) kwargs.update(options) result = task.apply_async(kwargs=kwargs) return JsonResponse({'ok': 'true', 'task_id': result.task_id}) return _applier
null
null
null
the task
codeqa
def task view task def applier request **options kwargs kwdict request method 'POST' and request POST copy or request GET copy kwargs update options result task apply async kwargs kwargs return Json Response {'ok' 'true' 'task id' result task id} return applier
null
null
null
null
Question: What does a view apply asynchronously ? Code: def task_view(task): def _applier(request, **options): kwargs = kwdict((((request.method == 'POST') and request.POST.copy()) or request.GET.copy())) kwargs.update(options) result = task.apply_async(kwargs=kwargs) return JsonResponse({'ok': 'true', 'task_id': result.task_id}) return _applier
null
null
null
What can we pickle ?
@ignore_warnings def check_estimators_pickle(name, Estimator): check_methods = ['predict', 'transform', 'decision_function', 'predict_proba'] (X, y) = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], random_state=0, n_features=2, cluster_std=0.1) X -= X.min() y = multioutput_estimator_convert_y_2d(name, y) estimator = Estimator() set_random_state(estimator) set_testing_parameters(estimator) estimator.fit(X, y) result = dict() for method in check_methods: if hasattr(estimator, method): result[method] = getattr(estimator, method)(X) pickled_estimator = pickle.dumps(estimator) if Estimator.__module__.startswith('sklearn.'): assert_true(('version' in pickled_estimator)) unpickled_estimator = pickle.loads(pickled_estimator) for method in result: unpickled_result = getattr(unpickled_estimator, method)(X) assert_array_almost_equal(result[method], unpickled_result)
null
null
null
all estimators
codeqa
@ignore warningsdef check estimators pickle name Estimator check methods ['predict' 'transform' 'decision function' 'predict proba'] X y make blobs n samples 30 centers [[ 0 0 0] [1 1 1]] random state 0 n features 2 cluster std 0 1 X - X min y multioutput estimator convert y 2d name y estimator Estimator set random state estimator set testing parameters estimator estimator fit X y result dict for method in check methods if hasattr estimator method result[method] getattr estimator method X pickled estimator pickle dumps estimator if Estimator module startswith 'sklearn ' assert true 'version' in pickled estimator unpickled estimator pickle loads pickled estimator for method in result unpickled result getattr unpickled estimator method X assert array almost equal result[method] unpickled result
null
null
null
null
Question: What can we pickle ? Code: @ignore_warnings def check_estimators_pickle(name, Estimator): check_methods = ['predict', 'transform', 'decision_function', 'predict_proba'] (X, y) = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], random_state=0, n_features=2, cluster_std=0.1) X -= X.min() y = multioutput_estimator_convert_y_2d(name, y) estimator = Estimator() set_random_state(estimator) set_testing_parameters(estimator) estimator.fit(X, y) result = dict() for method in check_methods: if hasattr(estimator, method): result[method] = getattr(estimator, method)(X) pickled_estimator = pickle.dumps(estimator) if Estimator.__module__.startswith('sklearn.'): assert_true(('version' in pickled_estimator)) unpickled_estimator = pickle.loads(pickled_estimator) for method in result: unpickled_result = getattr(unpickled_estimator, method)(X) assert_array_almost_equal(result[method], unpickled_result)
null
null
null
What does the code decorate ?
def goodDecorator(fn): def nameCollision(*args, **kwargs): return fn(*args, **kwargs) return mergeFunctionMetadata(fn, nameCollision)
null
null
null
a function
codeqa
def good Decorator fn def name Collision *args **kwargs return fn *args **kwargs return merge Function Metadata fn name Collision
null
null
null
null
Question: What does the code decorate ? Code: def goodDecorator(fn): def nameCollision(*args, **kwargs): return fn(*args, **kwargs) return mergeFunctionMetadata(fn, nameCollision)
null
null
null
What does the code preserve ?
def goodDecorator(fn): def nameCollision(*args, **kwargs): return fn(*args, **kwargs) return mergeFunctionMetadata(fn, nameCollision)
null
null
null
the original name
codeqa
def good Decorator fn def name Collision *args **kwargs return fn *args **kwargs return merge Function Metadata fn name Collision
null
null
null
null
Question: What does the code preserve ? Code: def goodDecorator(fn): def nameCollision(*args, **kwargs): return fn(*args, **kwargs) return mergeFunctionMetadata(fn, nameCollision)
null
null
null
What does the code get ?
def _get_configured_repos(): repos_cfg = configparser.ConfigParser() repos_cfg.read([((REPOS + '/') + fname) for fname in os.listdir(REPOS)]) return repos_cfg
null
null
null
all the info about repositories from the configurations
codeqa
def get configured repos repos cfg configparser Config Parser repos cfg read [ REPOS + '/' + fname for fname in os listdir REPOS ] return repos cfg
null
null
null
null
Question: What does the code get ? Code: def _get_configured_repos(): repos_cfg = configparser.ConfigParser() repos_cfg.read([((REPOS + '/') + fname) for fname in os.listdir(REPOS)]) return repos_cfg
null
null
null
How does the code run a synchronous query ?
@snippet def client_run_sync_query_w_param(client, _): QUERY_W_PARAM = 'SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = @state' LIMIT = 100 LIMITED = ('%s LIMIT %d' % (QUERY_W_PARAM, LIMIT)) TIMEOUT_MS = 1000 from google.cloud.bigquery import ScalarQueryParameter param = ScalarQueryParameter('state', 'STRING', 'TX') query = client.run_sync_query(LIMITED, query_parameters=[param]) query.use_legacy_sql = False query.timeout_ms = TIMEOUT_MS query.run() assert query.complete assert (len(query.rows) == LIMIT) assert ([field.name for field in query.schema] == ['name'])
null
null
null
using a query parameter
codeqa
@snippetdef client run sync query w param client QUERY W PARAM 'SELEC Tname FROM`bigquery-public-data usa names usa 1910 2013 `WHER Estate @state'LIMIT 100 LIMITED '%s LIMIT%d' % QUERY W PARAM LIMIT TIMEOUT MS 1000 from google cloud bigquery import Scalar Query Parameterparam Scalar Query Parameter 'state' 'STRING' 'TX' query client run sync query LIMITED query parameters [param] query use legacy sql Falsequery timeout ms TIMEOUT M Squery run assert query completeassert len query rows LIMIT assert [field name for field in query schema] ['name']
null
null
null
null
Question: How does the code run a synchronous query ? Code: @snippet def client_run_sync_query_w_param(client, _): QUERY_W_PARAM = 'SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = @state' LIMIT = 100 LIMITED = ('%s LIMIT %d' % (QUERY_W_PARAM, LIMIT)) TIMEOUT_MS = 1000 from google.cloud.bigquery import ScalarQueryParameter param = ScalarQueryParameter('state', 'STRING', 'TX') query = client.run_sync_query(LIMITED, query_parameters=[param]) query.use_legacy_sql = False query.timeout_ms = TIMEOUT_MS query.run() assert query.complete assert (len(query.rows) == LIMIT) assert ([field.name for field in query.schema] == ['name'])
null
null
null
What does the code run using a query parameter ?
@snippet def client_run_sync_query_w_param(client, _): QUERY_W_PARAM = 'SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = @state' LIMIT = 100 LIMITED = ('%s LIMIT %d' % (QUERY_W_PARAM, LIMIT)) TIMEOUT_MS = 1000 from google.cloud.bigquery import ScalarQueryParameter param = ScalarQueryParameter('state', 'STRING', 'TX') query = client.run_sync_query(LIMITED, query_parameters=[param]) query.use_legacy_sql = False query.timeout_ms = TIMEOUT_MS query.run() assert query.complete assert (len(query.rows) == LIMIT) assert ([field.name for field in query.schema] == ['name'])
null
null
null
a synchronous query
codeqa
@snippetdef client run sync query w param client QUERY W PARAM 'SELEC Tname FROM`bigquery-public-data usa names usa 1910 2013 `WHER Estate @state'LIMIT 100 LIMITED '%s LIMIT%d' % QUERY W PARAM LIMIT TIMEOUT MS 1000 from google cloud bigquery import Scalar Query Parameterparam Scalar Query Parameter 'state' 'STRING' 'TX' query client run sync query LIMITED query parameters [param] query use legacy sql Falsequery timeout ms TIMEOUT M Squery run assert query completeassert len query rows LIMIT assert [field name for field in query schema] ['name']
null
null
null
null
Question: What does the code run using a query parameter ? Code: @snippet def client_run_sync_query_w_param(client, _): QUERY_W_PARAM = 'SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = @state' LIMIT = 100 LIMITED = ('%s LIMIT %d' % (QUERY_W_PARAM, LIMIT)) TIMEOUT_MS = 1000 from google.cloud.bigquery import ScalarQueryParameter param = ScalarQueryParameter('state', 'STRING', 'TX') query = client.run_sync_query(LIMITED, query_parameters=[param]) query.use_legacy_sql = False query.timeout_ms = TIMEOUT_MS query.run() assert query.complete assert (len(query.rows) == LIMIT) assert ([field.name for field in query.schema] == ['name'])
null
null
null
What needs to be refreshed ?
def _cached_path_needs_update(ca_path, cache_length): exists = os.path.exists(ca_path) if (not exists): return True stats = os.stat(ca_path) if (stats.st_mtime < (time.time() - ((cache_length * 60) * 60))): return True if (stats.st_size == 0): return True return False
null
null
null
a cache file
codeqa
def cached path needs update ca path cache length exists os path exists ca path if not exists return Truestats os stat ca path if stats st mtime < time time - cache length * 60 * 60 return Trueif stats st size 0 return Truereturn False
null
null
null
null
Question: What needs to be refreshed ? Code: def _cached_path_needs_update(ca_path, cache_length): exists = os.path.exists(ca_path) if (not exists): return True stats = os.stat(ca_path) if (stats.st_mtime < (time.time() - ((cache_length * 60) * 60))): return True if (stats.st_size == 0): return True return False
null
null
null
What identifies a module uniquely ?
def get_module_hash(src_code, key): to_hash = [l.strip() for l in src_code.split('\n')] if key[0]: to_hash += list(map(str, key[0])) c_link_key = key[1] error_msg = 'This should not happen unless someone modified the code that defines the CLinker key, in which case you should ensure this piece of code is still valid (and this AssertionError may be removed or modified to accomodate this change)' assert (c_link_key[0] == 'CLinker.cmodule_key'), error_msg for key_element in c_link_key[1:]: if isinstance(key_element, tuple): to_hash += list(key_element) elif isinstance(key_element, string_types): if key_element.startswith('md5:'): break elif (key_element.startswith('NPY_ABI_VERSION=0x') or key_element.startswith('c_compiler_str=')): to_hash.append(key_element) else: raise AssertionError(error_msg) else: raise AssertionError(error_msg) return hash_from_code('\n'.join(to_hash))
null
null
null
an md5 hash
codeqa
def get module hash src code key to hash [l strip for l in src code split '\n' ]if key[ 0 ] to hash + list map str key[ 0 ] c link key key[ 1 ]error msg ' Thisshouldnothappenunlesssomeonemodifiedthecodethatdefinesthe C Linkerkey inwhichcaseyoushouldensurethispieceofcodeisstillvalid andthis Assertion Errormayberemovedormodifiedtoaccomodatethischange 'assert c link key[ 0 ] 'C Linker cmodule key' error msgfor key element in c link key[ 1 ] if isinstance key element tuple to hash + list key element elif isinstance key element string types if key element startswith 'md 5 ' breakelif key element startswith 'NPY ABI VERSION 0x' or key element startswith 'c compiler str ' to hash append key element else raise Assertion Error error msg else raise Assertion Error error msg return hash from code '\n' join to hash
null
null
null
null
Question: What identifies a module uniquely ? Code: def get_module_hash(src_code, key): to_hash = [l.strip() for l in src_code.split('\n')] if key[0]: to_hash += list(map(str, key[0])) c_link_key = key[1] error_msg = 'This should not happen unless someone modified the code that defines the CLinker key, in which case you should ensure this piece of code is still valid (and this AssertionError may be removed or modified to accomodate this change)' assert (c_link_key[0] == 'CLinker.cmodule_key'), error_msg for key_element in c_link_key[1:]: if isinstance(key_element, tuple): to_hash += list(key_element) elif isinstance(key_element, string_types): if key_element.startswith('md5:'): break elif (key_element.startswith('NPY_ABI_VERSION=0x') or key_element.startswith('c_compiler_str=')): to_hash.append(key_element) else: raise AssertionError(error_msg) else: raise AssertionError(error_msg) return hash_from_code('\n'.join(to_hash))
null
null
null
What does the code generate ?
def _GenerateRequestLogId(): sec = int(_request_time) usec = int((1000000 * (_request_time - sec))) h = hashlib.sha1(str(_request_id)).digest()[:4] packed = struct.Struct('> L L').pack(sec, usec) return binascii.b2a_hex((packed + h))
null
null
null
the request log i d for the current request
codeqa
def Generate Request Log Id sec int request time usec int 1000000 * request time - sec h hashlib sha 1 str request id digest [ 4]packed struct Struct '>LL' pack sec usec return binascii b2 a hex packed + h
null
null
null
null
Question: What does the code generate ? Code: def _GenerateRequestLogId(): sec = int(_request_time) usec = int((1000000 * (_request_time - sec))) h = hashlib.sha1(str(_request_id)).digest()[:4] packed = struct.Struct('> L L').pack(sec, usec) return binascii.b2a_hex((packed + h))
null
null
null
What does the code get by name or instance i d ?
def libvlc_vlm_get_media_instance_rate(p_instance, psz_name, i_instance): f = (_Cfunctions.get('libvlc_vlm_get_media_instance_rate', None) or _Cfunction('libvlc_vlm_get_media_instance_rate', ((1,), (1,), (1,)), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)) return f(p_instance, psz_name, i_instance)
null
null
null
vlm_media instance playback rate
codeqa
def libvlc vlm get media instance rate p instance psz name i instance f Cfunctions get 'libvlc vlm get media instance rate' None or Cfunction 'libvlc vlm get media instance rate' 1 1 1 None ctypes c int Instance ctypes c char p ctypes c int return f p instance psz name i instance
null
null
null
null
Question: What does the code get by name or instance i d ? Code: def libvlc_vlm_get_media_instance_rate(p_instance, psz_name, i_instance): f = (_Cfunctions.get('libvlc_vlm_get_media_instance_rate', None) or _Cfunction('libvlc_vlm_get_media_instance_rate', ((1,), (1,), (1,)), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)) return f(p_instance, psz_name, i_instance)
null
null
null
What does the code get from the table ?
@require_context def virtual_interface_get_by_address(context, address): vif_ref = _virtual_interface_query(context).filter_by(address=address).first() return vif_ref
null
null
null
a virtual interface
codeqa
@require contextdef virtual interface get by address context address vif ref virtual interface query context filter by address address first return vif ref
null
null
null
null
Question: What does the code get from the table ? Code: @require_context def virtual_interface_get_by_address(context, address): vif_ref = _virtual_interface_query(context).filter_by(address=address).first() return vif_ref
null
null
null
How do a timezone set ?
@contextmanager def set_timezone(tz): if is_platform_windows(): import nose raise nose.SkipTest('timezone setting not supported on windows') import os import time def setTZ(tz): if (tz is None): try: del os.environ['TZ'] except: pass else: os.environ['TZ'] = tz time.tzset() orig_tz = os.environ.get('TZ') setTZ(tz) try: (yield) finally: setTZ(orig_tz)
null
null
null
temporarily
codeqa
@contextmanagerdef set timezone tz if is platform windows import noseraise nose Skip Test 'timezonesettingnotsupportedonwindows' import osimport timedef set TZ tz if tz is None try del os environ['TZ']except passelse os environ['TZ'] tztime tzset orig tz os environ get 'TZ' set TZ tz try yield finally set TZ orig tz
null
null
null
null
Question: How do a timezone set ? Code: @contextmanager def set_timezone(tz): if is_platform_windows(): import nose raise nose.SkipTest('timezone setting not supported on windows') import os import time def setTZ(tz): if (tz is None): try: del os.environ['TZ'] except: pass else: os.environ['TZ'] = tz time.tzset() orig_tz = os.environ.get('TZ') setTZ(tz) try: (yield) finally: setTZ(orig_tz)
null
null
null
What converts to a universal tag ?
def parole2universal(token, tag): if (tag == 'CS'): return (token, CONJ) if (tag == 'DP'): return (token, DET) if (tag in ('P0', 'PD', 'PI', 'PP', 'PR', 'PT', 'PX')): return (token, PRON) return penntreebank2universal(*parole2penntreebank(token, tag))
null
null
null
a parole tag
codeqa
def parole 2 universal token tag if tag 'CS' return token CONJ if tag 'DP' return token DET if tag in 'P 0 ' 'PD' 'PI' 'PP' 'PR' 'PT' 'PX' return token PRON return penntreebank 2 universal *parole 2 penntreebank token tag
null
null
null
null
Question: What converts to a universal tag ? Code: def parole2universal(token, tag): if (tag == 'CS'): return (token, CONJ) if (tag == 'DP'): return (token, DET) if (tag in ('P0', 'PD', 'PI', 'PP', 'PR', 'PT', 'PX')): return (token, PRON) return penntreebank2universal(*parole2penntreebank(token, tag))
null
null
null
What does a parole tag convert ?
def parole2universal(token, tag): if (tag == 'CS'): return (token, CONJ) if (tag == 'DP'): return (token, DET) if (tag in ('P0', 'PD', 'PI', 'PP', 'PR', 'PT', 'PX')): return (token, PRON) return penntreebank2universal(*parole2penntreebank(token, tag))
null
null
null
to a universal tag
codeqa
def parole 2 universal token tag if tag 'CS' return token CONJ if tag 'DP' return token DET if tag in 'P 0 ' 'PD' 'PI' 'PP' 'PR' 'PT' 'PX' return token PRON return penntreebank 2 universal *parole 2 penntreebank token tag
null
null
null
null
Question: What does a parole tag convert ? Code: def parole2universal(token, tag): if (tag == 'CS'): return (token, CONJ) if (tag == 'DP'): return (token, DET) if (tag in ('P0', 'PD', 'PI', 'PP', 'PR', 'PT', 'PX')): return (token, PRON) return penntreebank2universal(*parole2penntreebank(token, tag))
null
null
null
What do caught exception represent ?
def _is_resumable(exc): checker = _SELECT_ERROR_CHECKERS.get(exc.__class__, None) if (checker is not None): return checker(exc) else: return False
null
null
null
eintr error
codeqa
def is resumable exc checker SELECT ERROR CHECKERS get exc class None if checker is not None return checker exc else return False
null
null
null
null
Question: What do caught exception represent ? Code: def _is_resumable(exc): checker = _SELECT_ERROR_CHECKERS.get(exc.__class__, None) if (checker is not None): return checker(exc) else: return False
null
null
null
What has the given permissions for the particular group ?
def _has_user_permission_for_groups(user_id, permission, group_ids, capacity=None): if (not group_ids): return False q = model.Session.query(model.Member).filter(model.Member.group_id.in_(group_ids)).filter((model.Member.table_name == 'user')).filter((model.Member.state == 'active')).filter((model.Member.table_id == user_id)) if capacity: q = q.filter((model.Member.capacity == capacity)) for row in q.all(): perms = ROLE_PERMISSIONS.get(row.capacity, []) if (('admin' in perms) or (permission in perms)): return True return False
null
null
null
the user
codeqa
def has user permission for groups user id permission group ids capacity None if not group ids return Falseq model Session query model Member filter model Member group id in group ids filter model Member table name 'user' filter model Member state 'active' filter model Member table id user id if capacity q q filter model Member capacity capacity for row in q all perms ROLE PERMISSIONS get row capacity [] if 'admin' in perms or permission in perms return Truereturn False
null
null
null
null
Question: What has the given permissions for the particular group ? Code: def _has_user_permission_for_groups(user_id, permission, group_ids, capacity=None): if (not group_ids): return False q = model.Session.query(model.Member).filter(model.Member.group_id.in_(group_ids)).filter((model.Member.table_name == 'user')).filter((model.Member.state == 'active')).filter((model.Member.table_id == user_id)) if capacity: q = q.filter((model.Member.capacity == capacity)) for row in q.all(): perms = ROLE_PERMISSIONS.get(row.capacity, []) if (('admin' in perms) or (permission in perms)): return True return False
null
null
null
What do windows allow ?
def _getRegisteredExecutable(exeName): registered = None if sys.platform.startswith('win'): if (os.path.splitext(exeName)[1].lower() != '.exe'): exeName += '.exe' import _winreg try: key = ('SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' + exeName) value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key) registered = (value, ('from HKLM\\' + key)) except _winreg.error: pass if (registered and (not os.path.exists(registered[0]))): registered = None return registered
null
null
null
application paths to be registered in the registry
codeqa
def get Registered Executable exe Name registered Noneif sys platform startswith 'win' if os path splitext exe Name [1 ] lower ' exe' exe Name + ' exe'import winregtry key 'SOFTWARE\\ Microsoft\\ Windows\\ Current Version\\ App Paths\\' + exe Name value winreg Query Value winreg HKEY LOCAL MACHINE key registered value 'from HKLM\\' + key except winreg error passif registered and not os path exists registered[ 0 ] registered Nonereturn registered
null
null
null
null
Question: What do windows allow ? Code: def _getRegisteredExecutable(exeName): registered = None if sys.platform.startswith('win'): if (os.path.splitext(exeName)[1].lower() != '.exe'): exeName += '.exe' import _winreg try: key = ('SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' + exeName) value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key) registered = (value, ('from HKLM\\' + key)) except _winreg.error: pass if (registered and (not os.path.exists(registered[0]))): registered = None return registered
null
null
null
What allow application paths to be registered in the registry ?
def _getRegisteredExecutable(exeName): registered = None if sys.platform.startswith('win'): if (os.path.splitext(exeName)[1].lower() != '.exe'): exeName += '.exe' import _winreg try: key = ('SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' + exeName) value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key) registered = (value, ('from HKLM\\' + key)) except _winreg.error: pass if (registered and (not os.path.exists(registered[0]))): registered = None return registered
null
null
null
windows
codeqa
def get Registered Executable exe Name registered Noneif sys platform startswith 'win' if os path splitext exe Name [1 ] lower ' exe' exe Name + ' exe'import winregtry key 'SOFTWARE\\ Microsoft\\ Windows\\ Current Version\\ App Paths\\' + exe Name value winreg Query Value winreg HKEY LOCAL MACHINE key registered value 'from HKLM\\' + key except winreg error passif registered and not os path exists registered[ 0 ] registered Nonereturn registered
null
null
null
null
Question: What allow application paths to be registered in the registry ? Code: def _getRegisteredExecutable(exeName): registered = None if sys.platform.startswith('win'): if (os.path.splitext(exeName)[1].lower() != '.exe'): exeName += '.exe' import _winreg try: key = ('SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' + exeName) value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key) registered = (value, ('from HKLM\\' + key)) except _winreg.error: pass if (registered and (not os.path.exists(registered[0]))): registered = None return registered
null
null
null
How does the code get vector3 vertexes from attribute dictionary ?
def getGeometryOutputByArguments(arguments, elementNode): derivation = SVGDerivation() derivation.svgReader.parseSVG('', arguments[0]) return getGeometryOutput(derivation, elementNode)
null
null
null
by arguments
codeqa
def get Geometry Output By Arguments arguments element Node derivation SVG Derivation derivation svg Reader parse SVG '' arguments[ 0 ] return get Geometry Output derivation element Node
null
null
null
null
Question: How does the code get vector3 vertexes from attribute dictionary ? Code: def getGeometryOutputByArguments(arguments, elementNode): derivation = SVGDerivation() derivation.svgReader.parseSVG('', arguments[0]) return getGeometryOutput(derivation, elementNode)
null
null
null
What does the code get from attribute dictionary by arguments ?
def getGeometryOutputByArguments(arguments, elementNode): derivation = SVGDerivation() derivation.svgReader.parseSVG('', arguments[0]) return getGeometryOutput(derivation, elementNode)
null
null
null
vector3 vertexes
codeqa
def get Geometry Output By Arguments arguments element Node derivation SVG Derivation derivation svg Reader parse SVG '' arguments[ 0 ] return get Geometry Output derivation element Node
null
null
null
null
Question: What does the code get from attribute dictionary by arguments ? Code: def getGeometryOutputByArguments(arguments, elementNode): derivation = SVGDerivation() derivation.svgReader.parseSVG('', arguments[0]) return getGeometryOutput(derivation, elementNode)
null
null
null
When do most recent valid timestamp find ?
def get_future_timestamp(idx, timestamps): if (idx == (len(timestamps) - 1)): return get_past_timestamp(idx, timestamps) elif timestamps[idx]: return timestamps[idx][0] else: idx = min(len(timestamps), (idx + 1)) return get_future_timestamp(idx, timestamps)
null
null
null
in the future
codeqa
def get future timestamp idx timestamps if idx len timestamps - 1 return get past timestamp idx timestamps elif timestamps[idx] return timestamps[idx][ 0 ]else idx min len timestamps idx + 1 return get future timestamp idx timestamps
null
null
null
null
Question: When do most recent valid timestamp find ? Code: def get_future_timestamp(idx, timestamps): if (idx == (len(timestamps) - 1)): return get_past_timestamp(idx, timestamps) elif timestamps[idx]: return timestamps[idx][0] else: idx = min(len(timestamps), (idx + 1)) return get_future_timestamp(idx, timestamps)
null
null
null
What does it swallow ?
def safecall(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception: pass return wrapper
null
null
null
exceptions
codeqa
def safecall func def wrapper *args **kwargs try return func *args **kwargs except Exception passreturn wrapper
null
null
null
null
Question: What does it swallow ? Code: def safecall(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception: pass return wrapper
null
null
null
For what purpose does a function wrap ?
def safecall(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception: pass return wrapper
null
null
null
so that it swallows exceptions
codeqa
def safecall func def wrapper *args **kwargs try return func *args **kwargs except Exception passreturn wrapper
null
null
null
null
Question: For what purpose does a function wrap ? Code: def safecall(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception: pass return wrapper
null
null
null
What does the code create ?
def redact_loc(image_meta, copy_dict=True): if copy_dict: new_image_meta = copy.copy(image_meta) else: new_image_meta = image_meta new_image_meta.pop('location', None) new_image_meta.pop('location_data', None) return new_image_meta
null
null
null
a shallow copy of image meta with location removed for security
codeqa
def redact loc image meta copy dict True if copy dict new image meta copy copy image meta else new image meta image metanew image meta pop 'location' None new image meta pop 'location data' None return new image meta
null
null
null
null
Question: What does the code create ? Code: def redact_loc(image_meta, copy_dict=True): if copy_dict: new_image_meta = copy.copy(image_meta) else: new_image_meta = image_meta new_image_meta.pop('location', None) new_image_meta.pop('location_data', None) return new_image_meta
null
null
null
For what purpose did location remove ?
def redact_loc(image_meta, copy_dict=True): if copy_dict: new_image_meta = copy.copy(image_meta) else: new_image_meta = image_meta new_image_meta.pop('location', None) new_image_meta.pop('location_data', None) return new_image_meta
null
null
null
for security
codeqa
def redact loc image meta copy dict True if copy dict new image meta copy copy image meta else new image meta image metanew image meta pop 'location' None new image meta pop 'location data' None return new image meta
null
null
null
null
Question: For what purpose did location remove ? Code: def redact_loc(image_meta, copy_dict=True): if copy_dict: new_image_meta = copy.copy(image_meta) else: new_image_meta = image_meta new_image_meta.pop('location', None) new_image_meta.pop('location_data', None) return new_image_meta
null
null
null
What does the code generate ?
def pylong_join(count, digits_ptr='digits', join_type='unsigned long'): return (('(' * (count * 2)) + ' | '.join((('(%s)%s[%d])%s)' % (join_type, digits_ptr, _i, (' << PyLong_SHIFT' if _i else ''))) for _i in range((count - 1), (-1), (-1)))))
null
null
null
an unrolled shift
codeqa
def pylong join count digits ptr 'digits' join type 'unsignedlong' return ' ' * count * 2 + ' ' join ' %s %s[%d] %s ' % join type digits ptr i '<< Py Long SHIFT' if i else '' for i in range count - 1 -1 -1
null
null
null
null
Question: What does the code generate ? Code: def pylong_join(count, digits_ptr='digits', join_type='unsigned long'): return (('(' * (count * 2)) + ' | '.join((('(%s)%s[%d])%s)' % (join_type, digits_ptr, _i, (' << PyLong_SHIFT' if _i else ''))) for _i in range((count - 1), (-1), (-1)))))
null
null
null
What does the code create ?
def create_logger(app): Logger = getLoggerClass() class DebugLogger(Logger, ): def getEffectiveLevel(x): if ((x.level == 0) and app.debug): return DEBUG return Logger.getEffectiveLevel(x) class DebugHandler(StreamHandler, ): def emit(x, record): (StreamHandler.emit(x, record) if app.debug else None) handler = DebugHandler() handler.setLevel(DEBUG) handler.setFormatter(Formatter(app.debug_log_format)) logger = getLogger(app.logger_name) del logger.handlers[:] logger.__class__ = DebugLogger logger.addHandler(handler) return logger
null
null
null
a logger for the given application
codeqa
def create logger app Logger get Logger Class class Debug Logger Logger def get Effective Level x if x level 0 and app debug return DEBU Greturn Logger get Effective Level x class Debug Handler Stream Handler def emit x record Stream Handler emit x record if app debug else None handler Debug Handler handler set Level DEBUG handler set Formatter Formatter app debug log format logger get Logger app logger name del logger handlers[ ]logger class Debug Loggerlogger add Handler handler return logger
null
null
null
null
Question: What does the code create ? Code: def create_logger(app): Logger = getLoggerClass() class DebugLogger(Logger, ): def getEffectiveLevel(x): if ((x.level == 0) and app.debug): return DEBUG return Logger.getEffectiveLevel(x) class DebugHandler(StreamHandler, ): def emit(x, record): (StreamHandler.emit(x, record) if app.debug else None) handler = DebugHandler() handler.setLevel(DEBUG) handler.setFormatter(Formatter(app.debug_log_format)) logger = getLogger(app.logger_name) del logger.handlers[:] logger.__class__ = DebugLogger logger.addHandler(handler) return logger
null
null
null
What places where ?
def _handleDescriptionFromFileOption(filename, outDir, usageStr, hsVersion, claDescriptionTemplateFile): try: fileHandle = open(filename, 'r') JSONStringFromFile = fileHandle.read().splitlines() JSONStringFromFile = ''.join(JSONStringFromFile) except Exception as e: raise _InvalidCommandArgException(_makeUsageErrorStr((('File open failed for --descriptionFromFile: %s\n' + 'ARG=<%s>') % (str(e), filename)), usageStr)) _handleDescriptionOption(JSONStringFromFile, outDir, usageStr, hsVersion=hsVersion, claDescriptionTemplateFile=claDescriptionTemplateFile) return
null
null
null
generated experiment files
codeqa
def handle Description From File Option filename out Dir usage Str hs Version cla Description Template File try file Handle open filename 'r' JSON String From File file Handle read splitlines JSON String From File '' join JSON String From File except Exception as e raise Invalid Command Arg Exception make Usage Error Str ' Fileopenfailedfor--description From File %s\n' + 'ARG <%s>' % str e filename usage Str handle Description Option JSON String From File out Dir usage Str hs Version hs Version cla Description Template File cla Description Template File return
null
null
null
null
Question: What places where ? Code: def _handleDescriptionFromFileOption(filename, outDir, usageStr, hsVersion, claDescriptionTemplateFile): try: fileHandle = open(filename, 'r') JSONStringFromFile = fileHandle.read().splitlines() JSONStringFromFile = ''.join(JSONStringFromFile) except Exception as e: raise _InvalidCommandArgException(_makeUsageErrorStr((('File open failed for --descriptionFromFile: %s\n' + 'ARG=<%s>') % (str(e), filename)), usageStr)) _handleDescriptionOption(JSONStringFromFile, outDir, usageStr, hsVersion=hsVersion, claDescriptionTemplateFile=claDescriptionTemplateFile) return
null
null
null
How do description extract ?
def _handleDescriptionFromFileOption(filename, outDir, usageStr, hsVersion, claDescriptionTemplateFile): try: fileHandle = open(filename, 'r') JSONStringFromFile = fileHandle.read().splitlines() JSONStringFromFile = ''.join(JSONStringFromFile) except Exception as e: raise _InvalidCommandArgException(_makeUsageErrorStr((('File open failed for --descriptionFromFile: %s\n' + 'ARG=<%s>') % (str(e), filename)), usageStr)) _handleDescriptionOption(JSONStringFromFile, outDir, usageStr, hsVersion=hsVersion, claDescriptionTemplateFile=claDescriptionTemplateFile) return
null
null
null
well
codeqa
def handle Description From File Option filename out Dir usage Str hs Version cla Description Template File try file Handle open filename 'r' JSON String From File file Handle read splitlines JSON String From File '' join JSON String From File except Exception as e raise Invalid Command Arg Exception make Usage Error Str ' Fileopenfailedfor--description From File %s\n' + 'ARG <%s>' % str e filename usage Str handle Description Option JSON String From File out Dir usage Str hs Version hs Version cla Description Template File cla Description Template File return
null
null
null
null
Question: How do description extract ? Code: def _handleDescriptionFromFileOption(filename, outDir, usageStr, hsVersion, claDescriptionTemplateFile): try: fileHandle = open(filename, 'r') JSONStringFromFile = fileHandle.read().splitlines() JSONStringFromFile = ''.join(JSONStringFromFile) except Exception as e: raise _InvalidCommandArgException(_makeUsageErrorStr((('File open failed for --descriptionFromFile: %s\n' + 'ARG=<%s>') % (str(e), filename)), usageStr)) _handleDescriptionOption(JSONStringFromFile, outDir, usageStr, hsVersion=hsVersion, claDescriptionTemplateFile=claDescriptionTemplateFile) return
null
null
null
What does the code remove ?
def remove_lock(packages, **kwargs): locks = list_locks() try: packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys()) except MinionError as exc: raise CommandExecutionError(exc) removed = [] missing = [] for pkg in packages: if locks.get(pkg): removed.append(pkg) else: missing.append(pkg) if removed: __zypper__.call('rl', *removed) return {'removed': len(removed), 'not_found': missing}
null
null
null
specified package lock
codeqa
def remove lock packages **kwargs locks list locks try packages list salt ['pkg resource parse targets'] packages [0 ] keys except Minion Error as exc raise Command Execution Error exc removed []missing []for pkg in packages if locks get pkg removed append pkg else missing append pkg if removed zypper call 'rl' *removed return {'removed' len removed 'not found' missing}
null
null
null
null
Question: What does the code remove ? Code: def remove_lock(packages, **kwargs): locks = list_locks() try: packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys()) except MinionError as exc: raise CommandExecutionError(exc) removed = [] missing = [] for pkg in packages: if locks.get(pkg): removed.append(pkg) else: missing.append(pkg) if removed: __zypper__.call('rl', *removed) return {'removed': len(removed), 'not_found': missing}
null
null
null
How do the interactive python interpreter emulate ?
def interact(banner=None, readfunc=None, local=None, exitmsg=None): console = InteractiveConsole(local) if (readfunc is not None): console.raw_input = readfunc else: try: import readline except ImportError: pass console.interact(banner, exitmsg)
null
null
null
closely
codeqa
def interact banner None readfunc None local None exitmsg None console Interactive Console local if readfunc is not None console raw input readfuncelse try import readlineexcept Import Error passconsole interact banner exitmsg
null
null
null
null
Question: How do the interactive python interpreter emulate ? Code: def interact(banner=None, readfunc=None, local=None, exitmsg=None): console = InteractiveConsole(local) if (readfunc is not None): console.raw_input = readfunc else: try: import readline except ImportError: pass console.interact(banner, exitmsg)
null
null
null
What does the code create ?
def composite_transform_factory(a, b): if isinstance(a, IdentityTransform): return b elif isinstance(b, IdentityTransform): return a elif (isinstance(a, AffineBase) and isinstance(b, AffineBase)): return CompositeAffine2D(a, b) return CompositeGenericTransform(a, b)
null
null
null
a new composite transform that is the result of applying transform a then transform b
codeqa
def composite transform factory a b if isinstance a Identity Transform return belif isinstance b Identity Transform return aelif isinstance a Affine Base and isinstance b Affine Base return Composite Affine 2 D a b return Composite Generic Transform a b
null
null
null
null
Question: What does the code create ? Code: def composite_transform_factory(a, b): if isinstance(a, IdentityTransform): return b elif isinstance(b, IdentityTransform): return a elif (isinstance(a, AffineBase) and isinstance(b, AffineBase)): return CompositeAffine2D(a, b) return CompositeGenericTransform(a, b)
null
null
null
What does the code get from the galaxy database defined by the i d ?
def get_installed_tool_shed_repository(app, id): rval = [] if isinstance(id, list): return_list = True else: id = [id] return_list = False for i in id: rval.append(app.install_model.context.query(app.install_model.ToolShedRepository).get(app.security.decode_id(i))) if return_list: return rval return rval[0]
null
null
null
a tool shed repository record
codeqa
def get installed tool shed repository app id rval []if isinstance id list return list Trueelse id [id]return list Falsefor i in id rval append app install model context query app install model Tool Shed Repository get app security decode id i if return list return rvalreturn rval[ 0 ]
null
null
null
null
Question: What does the code get from the galaxy database defined by the i d ? Code: def get_installed_tool_shed_repository(app, id): rval = [] if isinstance(id, list): return_list = True else: id = [id] return_list = False for i in id: rval.append(app.install_model.context.query(app.install_model.ToolShedRepository).get(app.security.decode_id(i))) if return_list: return rval return rval[0]
null
null
null
What does the code make ?
def arbitrary_state_transformation(deployment_state): uuid = uuid4() return deployment_state.transform(['nodes', uuid], NodeState(uuid=uuid, hostname=u'catcatdog'))
null
null
null
some change to a deployment state
codeqa
def arbitrary state transformation deployment state uuid uuid 4 return deployment state transform ['nodes' uuid] Node State uuid uuid hostname u'catcatdog'
null
null
null
null
Question: What does the code make ? Code: def arbitrary_state_transformation(deployment_state): uuid = uuid4() return deployment_state.transform(['nodes', uuid], NodeState(uuid=uuid, hostname=u'catcatdog'))
null
null
null
How does the provider return ?
def id_to_name(config, short_name): for (k, v) in list(config.items()): if (v.get('id') == short_name): return k break else: raise Exception('No provider with id={0} found in the config!'.format(short_name))
null
null
null
based on its i d value
codeqa
def id to name config short name for k v in list config items if v get 'id' short name return kbreakelse raise Exception ' Noproviderwithid {0 }foundintheconfig ' format short name
null
null
null
null
Question: How does the provider return ? Code: def id_to_name(config, short_name): for (k, v) in list(config.items()): if (v.get('id') == short_name): return k break else: raise Exception('No provider with id={0} found in the config!'.format(short_name))
null
null
null
What must the tables have all ?
def vstack(tables, join_type=u'outer', metadata_conflicts=u'warn'): tables = _get_list_of_tables(tables) if (len(tables) == 1): return tables[0] col_name_map = OrderedDict() out = _vstack(tables, join_type, col_name_map) _merge_col_meta(out, tables, col_name_map, metadata_conflicts=metadata_conflicts) _merge_table_meta(out, tables, metadata_conflicts=metadata_conflicts) return out
null
null
null
exactly the same column names
codeqa
def vstack tables join type u'outer' metadata conflicts u'warn' tables get list of tables tables if len tables 1 return tables[ 0 ]col name map Ordered Dict out vstack tables join type col name map merge col meta out tables col name map metadata conflicts metadata conflicts merge table meta out tables metadata conflicts metadata conflicts return out
null
null
null
null
Question: What must the tables have all ? Code: def vstack(tables, join_type=u'outer', metadata_conflicts=u'warn'): tables = _get_list_of_tables(tables) if (len(tables) == 1): return tables[0] col_name_map = OrderedDict() out = _vstack(tables, join_type, col_name_map) _merge_col_meta(out, tables, col_name_map, metadata_conflicts=metadata_conflicts) _merge_table_meta(out, tables, metadata_conflicts=metadata_conflicts) return out
null
null
null
What does the code add to the lists ?
def addElementToListDictionaryIfNotThere(element, key, listDictionary): if (key in listDictionary): elements = listDictionary[key] if (element not in elements): elements.append(element) else: listDictionary[key] = [element]
null
null
null
the value
codeqa
def add Element To List Dictionary If Not There element key list Dictionary if key in list Dictionary elements list Dictionary[key]if element not in elements elements append element else list Dictionary[key] [element]
null
null
null
null
Question: What does the code add to the lists ? Code: def addElementToListDictionaryIfNotThere(element, key, listDictionary): if (key in listDictionary): elements = listDictionary[key] if (element not in elements): elements.append(element) else: listDictionary[key] = [element]
null
null
null
What does the code make from some data ?
def make_hybi00_frame(buf): return ('\x00%s\xff' % buf)
null
null
null
a hybi-00 frame
codeqa
def make hybi 00 frame buf return '\x 00 %s\xff' % buf
null
null
null
null
Question: What does the code make from some data ? Code: def make_hybi00_frame(buf): return ('\x00%s\xff' % buf)
null
null
null
What does the code ensure ?
def ensure_correct_host(session): if session.host_checked: return this_vm_uuid = get_this_vm_uuid(session) try: session.call_xenapi('VM.get_by_uuid', this_vm_uuid) session.host_checked = True except session.XenAPI.Failure as exc: if (exc.details[0] != 'UUID_INVALID'): raise raise Exception(_('This domU must be running on the host specified by connection_url'))
null
null
null
were connected to the host
codeqa
def ensure correct host session if session host checked returnthis vm uuid get this vm uuid session try session call xenapi 'VM get by uuid' this vm uuid session host checked Trueexcept session Xen API Failure as exc if exc details[ 0 ] 'UUID INVALID' raiseraise Exception ' Thisdom Umustberunningonthehostspecifiedbyconnection url'
null
null
null
null
Question: What does the code ensure ? Code: def ensure_correct_host(session): if session.host_checked: return this_vm_uuid = get_this_vm_uuid(session) try: session.call_xenapi('VM.get_by_uuid', this_vm_uuid) session.host_checked = True except session.XenAPI.Failure as exc: if (exc.details[0] != 'UUID_INVALID'): raise raise Exception(_('This domU must be running on the host specified by connection_url'))
null
null
null
When did user authenticate ?
@route(bp, '/') def whoami(): return current_user._get_current_object()
null
null
null
currently
codeqa
@route bp '/' def whoami return current user get current object
null
null
null
null
Question: When did user authenticate ? Code: @route(bp, '/') def whoami(): return current_user._get_current_object()
null
null
null
What executes command on remote host ?
def ssh_builder(registry, xml_parent, data): builder = XML.SubElement(xml_parent, 'org.jvnet.hudson.plugins.SSHBuilder') try: XML.SubElement(builder, 'siteName').text = str(data['ssh-user-ip']) XML.SubElement(builder, 'command').text = str(data['command']) except KeyError as e: raise MissingAttributeError(("'%s'" % e.args[0]))
null
null
null
ssh - builder
codeqa
def ssh builder registry xml parent data builder XML Sub Element xml parent 'org jvnet hudson plugins SSH Builder' try XML Sub Element builder 'site Name' text str data['ssh-user-ip'] XML Sub Element builder 'command' text str data['command'] except Key Error as e raise Missing Attribute Error "'%s'" % e args[ 0 ]
null
null
null
null
Question: What executes command on remote host ? Code: def ssh_builder(registry, xml_parent, data): builder = XML.SubElement(xml_parent, 'org.jvnet.hudson.plugins.SSHBuilder') try: XML.SubElement(builder, 'siteName').text = str(data['ssh-user-ip']) XML.SubElement(builder, 'command').text = str(data['command']) except KeyError as e: raise MissingAttributeError(("'%s'" % e.args[0]))
null
null
null
Where does ssh - builder execute command ?
def ssh_builder(registry, xml_parent, data): builder = XML.SubElement(xml_parent, 'org.jvnet.hudson.plugins.SSHBuilder') try: XML.SubElement(builder, 'siteName').text = str(data['ssh-user-ip']) XML.SubElement(builder, 'command').text = str(data['command']) except KeyError as e: raise MissingAttributeError(("'%s'" % e.args[0]))
null
null
null
on remote host
codeqa
def ssh builder registry xml parent data builder XML Sub Element xml parent 'org jvnet hudson plugins SSH Builder' try XML Sub Element builder 'site Name' text str data['ssh-user-ip'] XML Sub Element builder 'command' text str data['command'] except Key Error as e raise Missing Attribute Error "'%s'" % e args[ 0 ]
null
null
null
null
Question: Where does ssh - builder execute command ? Code: def ssh_builder(registry, xml_parent, data): builder = XML.SubElement(xml_parent, 'org.jvnet.hudson.plugins.SSHBuilder') try: XML.SubElement(builder, 'siteName').text = str(data['ssh-user-ip']) XML.SubElement(builder, 'command').text = str(data['command']) except KeyError as e: raise MissingAttributeError(("'%s'" % e.args[0]))
null
null
null
What does ssh - builder execute on remote host ?
def ssh_builder(registry, xml_parent, data): builder = XML.SubElement(xml_parent, 'org.jvnet.hudson.plugins.SSHBuilder') try: XML.SubElement(builder, 'siteName').text = str(data['ssh-user-ip']) XML.SubElement(builder, 'command').text = str(data['command']) except KeyError as e: raise MissingAttributeError(("'%s'" % e.args[0]))
null
null
null
command
codeqa
def ssh builder registry xml parent data builder XML Sub Element xml parent 'org jvnet hudson plugins SSH Builder' try XML Sub Element builder 'site Name' text str data['ssh-user-ip'] XML Sub Element builder 'command' text str data['command'] except Key Error as e raise Missing Attribute Error "'%s'" % e args[ 0 ]
null
null
null
null
Question: What does ssh - builder execute on remote host ? Code: def ssh_builder(registry, xml_parent, data): builder = XML.SubElement(xml_parent, 'org.jvnet.hudson.plugins.SSHBuilder') try: XML.SubElement(builder, 'siteName').text = str(data['ssh-user-ip']) XML.SubElement(builder, 'command').text = str(data['command']) except KeyError as e: raise MissingAttributeError(("'%s'" % e.args[0]))
null
null
null
What shows in the process list ?
@retry(exception=psutil.NoSuchProcess, logfun=None, timeout=GLOBAL_TIMEOUT, interval=0.001) def wait_for_pid(pid): psutil.Process(pid) if WINDOWS: time.sleep(0.01)
null
null
null
pid
codeqa
@retry exception psutil No Such Process logfun None timeout GLOBAL TIMEOUT interval 0 001 def wait for pid pid psutil Process pid if WINDOWS time sleep 0 01
null
null
null
null
Question: What shows in the process list ? Code: @retry(exception=psutil.NoSuchProcess, logfun=None, timeout=GLOBAL_TIMEOUT, interval=0.001) def wait_for_pid(pid): psutil.Process(pid) if WINDOWS: time.sleep(0.01)
null
null
null
What did the code set in the main ?
def set_main(key, value, path=MAIN_CF): (pairs, conf_list) = _parse_main(path) new_conf = [] if (key in pairs): for line in conf_list: if line.startswith(key): new_conf.append('{0} = {1}'.format(key, value)) else: new_conf.append(line) else: conf_list.append('{0} = {1}'.format(key, value)) new_conf = conf_list _write_conf(new_conf, path) return new_conf
null
null
null
a single config value
codeqa
def set main key value path MAIN CF pairs conf list parse main path new conf []if key in pairs for line in conf list if line startswith key new conf append '{ 0 } {1 }' format key value else new conf append line else conf list append '{ 0 } {1 }' format key value new conf conf list write conf new conf path return new conf
null
null
null
null
Question: What did the code set in the main ? Code: def set_main(key, value, path=MAIN_CF): (pairs, conf_list) = _parse_main(path) new_conf = [] if (key in pairs): for line in conf_list: if line.startswith(key): new_conf.append('{0} = {1}'.format(key, value)) else: new_conf.append(line) else: conf_list.append('{0} = {1}'.format(key, value)) new_conf = conf_list _write_conf(new_conf, path) return new_conf
null
null
null
Where did the code set a single config value ?
def set_main(key, value, path=MAIN_CF): (pairs, conf_list) = _parse_main(path) new_conf = [] if (key in pairs): for line in conf_list: if line.startswith(key): new_conf.append('{0} = {1}'.format(key, value)) else: new_conf.append(line) else: conf_list.append('{0} = {1}'.format(key, value)) new_conf = conf_list _write_conf(new_conf, path) return new_conf
null
null
null
in the main
codeqa
def set main key value path MAIN CF pairs conf list parse main path new conf []if key in pairs for line in conf list if line startswith key new conf append '{ 0 } {1 }' format key value else new conf append line else conf list append '{ 0 } {1 }' format key value new conf conf list write conf new conf path return new conf
null
null
null
null
Question: Where did the code set a single config value ? Code: def set_main(key, value, path=MAIN_CF): (pairs, conf_list) = _parse_main(path) new_conf = [] if (key in pairs): for line in conf_list: if line.startswith(key): new_conf.append('{0} = {1}'.format(key, value)) else: new_conf.append(line) else: conf_list.append('{0} = {1}'.format(key, value)) new_conf = conf_list _write_conf(new_conf, path) return new_conf
null
null
null
What list directly below the given path ?
def scan_directory(project_tree, directory): try: return DirectoryListing(directory, tuple(project_tree.scandir(directory.path)), exists=True) except (IOError, OSError) as e: if (e.errno == errno.ENOENT): return DirectoryListing(directory, tuple(), exists=False) else: raise e
null
null
null
stat objects
codeqa
def scan directory project tree directory try return Directory Listing directory tuple project tree scandir directory path exists True except IO Error OS Error as e if e errno errno ENOENT return Directory Listing directory tuple exists False else raise e
null
null
null
null
Question: What list directly below the given path ? Code: def scan_directory(project_tree, directory): try: return DirectoryListing(directory, tuple(project_tree.scandir(directory.path)), exists=True) except (IOError, OSError) as e: if (e.errno == errno.ENOENT): return DirectoryListing(directory, tuple(), exists=False) else: raise e
null
null
null
What does the code get ?
def getKeyM(row, column, prefix=''): return ('%sm%s%s' % (prefix, (row + 1), (column + 1)))
null
null
null
the m format key string
codeqa
def get Key M row column prefix '' return '%sm%s%s' % prefix row + 1 column + 1
null
null
null
null
Question: What does the code get ? Code: def getKeyM(row, column, prefix=''): return ('%sm%s%s' % (prefix, (row + 1), (column + 1)))
null
null
null
How do disjoint positive root isolation intervals compute ?
def dup_inner_isolate_positive_roots(f, K, eps=None, inf=None, sup=None, fast=False, mobius=False): if ((sup is not None) and (sup < 0)): return [] roots = dup_inner_isolate_real_roots(f, K, eps=eps, fast=fast) (F, results) = (K.get_field(), []) if ((inf is not None) or (sup is not None)): for (f, M) in roots: result = _discard_if_outside_interval(f, M, inf, sup, K, False, fast, mobius) if (result is not None): results.append(result) elif (not mobius): for (f, M) in roots: (u, v) = _mobius_to_interval(M, F) results.append((u, v)) else: results = roots return results
null
null
null
iteratively
codeqa
def dup inner isolate positive roots f K eps None inf None sup None fast False mobius False if sup is not None and sup < 0 return []roots dup inner isolate real roots f K eps eps fast fast F results K get field [] if inf is not None or sup is not None for f M in roots result discard if outside interval f M inf sup K False fast mobius if result is not None results append result elif not mobius for f M in roots u v mobius to interval M F results append u v else results rootsreturn results
null
null
null
null
Question: How do disjoint positive root isolation intervals compute ? Code: def dup_inner_isolate_positive_roots(f, K, eps=None, inf=None, sup=None, fast=False, mobius=False): if ((sup is not None) and (sup < 0)): return [] roots = dup_inner_isolate_real_roots(f, K, eps=eps, fast=fast) (F, results) = (K.get_field(), []) if ((inf is not None) or (sup is not None)): for (f, M) in roots: result = _discard_if_outside_interval(f, M, inf, sup, K, False, fast, mobius) if (result is not None): results.append(result) elif (not mobius): for (f, M) in roots: (u, v) = _mobius_to_interval(M, F) results.append((u, v)) else: results = roots return results
null
null
null
When does heartbeat expire ?
def heartbeat_expires(timestamp, freq=60, expire_window=HEARTBEAT_EXPIRE_WINDOW, Decimal=Decimal, float=float, isinstance=isinstance): freq = (float(freq) if isinstance(freq, Decimal) else freq) if isinstance(timestamp, Decimal): timestamp = float(timestamp) return (timestamp + (freq * (expire_window / 100.0)))
null
null
null
return time
codeqa
def heartbeat expires timestamp freq 60 expire window HEARTBEAT EXPIRE WINDOW Decimal Decimal float float isinstance isinstance freq float freq if isinstance freq Decimal else freq if isinstance timestamp Decimal timestamp float timestamp return timestamp + freq * expire window / 100 0
null
null
null
null
Question: When does heartbeat expire ? Code: def heartbeat_expires(timestamp, freq=60, expire_window=HEARTBEAT_EXPIRE_WINDOW, Decimal=Decimal, float=float, isinstance=isinstance): freq = (float(freq) if isinstance(freq, Decimal) else freq) if isinstance(timestamp, Decimal): timestamp = float(timestamp) return (timestamp + (freq * (expire_window / 100.0)))
null
null
null
When do time return ?
def heartbeat_expires(timestamp, freq=60, expire_window=HEARTBEAT_EXPIRE_WINDOW, Decimal=Decimal, float=float, isinstance=isinstance): freq = (float(freq) if isinstance(freq, Decimal) else freq) if isinstance(timestamp, Decimal): timestamp = float(timestamp) return (timestamp + (freq * (expire_window / 100.0)))
null
null
null
when heartbeat expires
codeqa
def heartbeat expires timestamp freq 60 expire window HEARTBEAT EXPIRE WINDOW Decimal Decimal float float isinstance isinstance freq float freq if isinstance freq Decimal else freq if isinstance timestamp Decimal timestamp float timestamp return timestamp + freq * expire window / 100 0
null
null
null
null
Question: When do time return ? Code: def heartbeat_expires(timestamp, freq=60, expire_window=HEARTBEAT_EXPIRE_WINDOW, Decimal=Decimal, float=float, isinstance=isinstance): freq = (float(freq) if isinstance(freq, Decimal) else freq) if isinstance(timestamp, Decimal): timestamp = float(timestamp) return (timestamp + (freq * (expire_window / 100.0)))
null
null
null
What turns into < cell_name>@<item > ?
def cell_with_item(cell_name, item): if (cell_name is None): return item return ((cell_name + _CELL_ITEM_SEP) + str(item))
null
null
null
cell_name and item
codeqa
def cell with item cell name item if cell name is None return itemreturn cell name + CELL ITEM SEP + str item
null
null
null
null
Question: What turns into < cell_name>@<item > ? Code: def cell_with_item(cell_name, item): if (cell_name is None): return item return ((cell_name + _CELL_ITEM_SEP) + str(item))
null
null
null
What do cell_name and item turn ?
def cell_with_item(cell_name, item): if (cell_name is None): return item return ((cell_name + _CELL_ITEM_SEP) + str(item))
null
null
null
into < cell_name>@<item >
codeqa
def cell with item cell name item if cell name is None return itemreturn cell name + CELL ITEM SEP + str item
null
null
null
null
Question: What do cell_name and item turn ? Code: def cell_with_item(cell_name, item): if (cell_name is None): return item return ((cell_name + _CELL_ITEM_SEP) + str(item))
null
null
null
How does each of the templates return ?
def get_templates(): injected = {} for (name, data) in templates.items(): injected[name] = dict([(k, (v % env)) for (k, v) in data.items()]) return injected
null
null
null
with env vars injected
codeqa
def get templates injected {}for name data in templates items injected[name] dict [ k v % env for k v in data items ] return injected
null
null
null
null
Question: How does each of the templates return ? Code: def get_templates(): injected = {} for (name, data) in templates.items(): injected[name] = dict([(k, (v % env)) for (k, v) in data.items()]) return injected
null
null
null
What rewrites a function so that it returns another function from it ?
def processor(f): def new_func(*args, **kwargs): def processor(stream): return f(stream, *args, **kwargs) return processor return update_wrapper(new_func, f)
null
null
null
helper decorator
codeqa
def processor f def new func *args **kwargs def processor stream return f stream *args **kwargs return processorreturn update wrapper new func f
null
null
null
null
Question: What rewrites a function so that it returns another function from it ? Code: def processor(f): def new_func(*args, **kwargs): def processor(stream): return f(stream, *args, **kwargs) return processor return update_wrapper(new_func, f)
null
null
null
What do helper decorator rewrite so that it returns another function from it ?
def processor(f): def new_func(*args, **kwargs): def processor(stream): return f(stream, *args, **kwargs) return processor return update_wrapper(new_func, f)
null
null
null
a function
codeqa
def processor f def new func *args **kwargs def processor stream return f stream *args **kwargs return processorreturn update wrapper new func f
null
null
null
null
Question: What do helper decorator rewrite so that it returns another function from it ? Code: def processor(f): def new_func(*args, **kwargs): def processor(stream): return f(stream, *args, **kwargs) return processor return update_wrapper(new_func, f)
null
null
null
For what purpose do helper decorator rewrite a function ?
def processor(f): def new_func(*args, **kwargs): def processor(stream): return f(stream, *args, **kwargs) return processor return update_wrapper(new_func, f)
null
null
null
so that it returns another function from it
codeqa
def processor f def new func *args **kwargs def processor stream return f stream *args **kwargs return processorreturn update wrapper new func f
null
null
null
null
Question: For what purpose do helper decorator rewrite a function ? Code: def processor(f): def new_func(*args, **kwargs): def processor(stream): return f(stream, *args, **kwargs) return processor return update_wrapper(new_func, f)
null
null
null
In which direction do image scale to shape ?
def make_letterboxed_thumbnail(image, shape): assert (len(image.shape) == 3) assert (len(shape) == 2) shrunk = fit_inside(image, shape) letterboxed = letterbox(shrunk, shape) return letterboxed
null
null
null
down
codeqa
def make letterboxed thumbnail image shape assert len image shape 3 assert len shape 2 shrunk fit inside image shape letterboxed letterbox shrunk shape return letterboxed
null
null
null
null
Question: In which direction do image scale to shape ? Code: def make_letterboxed_thumbnail(image, shape): assert (len(image.shape) == 3) assert (len(shape) == 2) shrunk = fit_inside(image, shape) letterboxed = letterbox(shrunk, shape) return letterboxed
null
null
null
For what purpose do scales image ?
def make_letterboxed_thumbnail(image, shape): assert (len(image.shape) == 3) assert (len(shape) == 2) shrunk = fit_inside(image, shape) letterboxed = letterbox(shrunk, shape) return letterboxed
null
null
null
to shape
codeqa
def make letterboxed thumbnail image shape assert len image shape 3 assert len shape 2 shrunk fit inside image shape letterboxed letterbox shrunk shape return letterboxed
null
null
null
null
Question: For what purpose do scales image ? Code: def make_letterboxed_thumbnail(image, shape): assert (len(image.shape) == 3) assert (len(shape) == 2) shrunk = fit_inside(image, shape) letterboxed = letterbox(shrunk, shape) return letterboxed
null
null
null
What does the code add ?
def _add_new_repo(alias, uri, compressed, enabled=True): repostr = ('# ' if (not enabled) else '') repostr += ('src/gz ' if compressed else 'src ') repostr += (((alias + ' ') + uri) + '\n') conffile = os.path.join(OPKG_CONFDIR, (alias + '.conf')) with open(conffile, 'a') as fhandle: fhandle.write(repostr)
null
null
null
a new repo entry
codeqa
def add new repo alias uri compressed enabled True repostr '#' if not enabled else '' repostr + 'src/gz' if compressed else 'src' repostr + alias + '' + uri + '\n' conffile os path join OPKG CONFDIR alias + ' conf' with open conffile 'a' as fhandle fhandle write repostr
null
null
null
null
Question: What does the code add ? Code: def _add_new_repo(alias, uri, compressed, enabled=True): repostr = ('# ' if (not enabled) else '') repostr += ('src/gz ' if compressed else 'src ') repostr += (((alias + ' ') + uri) + '\n') conffile = os.path.join(OPKG_CONFDIR, (alias + '.conf')) with open(conffile, 'a') as fhandle: fhandle.write(repostr)
null
null
null
What does the code find ?
def _get_metadata(field, expr, metadata_expr, no_metadata_rule): if (isinstance(metadata_expr, bz.Expr) or (metadata_expr is None)): return metadata_expr try: return expr._child['_'.join(((expr._name or ''), field))] except (ValueError, AttributeError): if (no_metadata_rule == 'raise'): raise ValueError(('no %s table could be reflected for %s' % (field, expr))) elif (no_metadata_rule == 'warn'): warnings.warn(NoMetaDataWarning(expr, field), stacklevel=4) return None
null
null
null
the correct metadata expression for the expression
codeqa
def get metadata field expr metadata expr no metadata rule if isinstance metadata expr bz Expr or metadata expr is None return metadata exprtry return expr child[' ' join expr name or '' field ]except Value Error Attribute Error if no metadata rule 'raise' raise Value Error 'no%stablecouldbereflectedfor%s' % field expr elif no metadata rule 'warn' warnings warn No Meta Data Warning expr field stacklevel 4 return None
null
null
null
null
Question: What does the code find ? Code: def _get_metadata(field, expr, metadata_expr, no_metadata_rule): if (isinstance(metadata_expr, bz.Expr) or (metadata_expr is None)): return metadata_expr try: return expr._child['_'.join(((expr._name or ''), field))] except (ValueError, AttributeError): if (no_metadata_rule == 'raise'): raise ValueError(('no %s table could be reflected for %s' % (field, expr))) elif (no_metadata_rule == 'warn'): warnings.warn(NoMetaDataWarning(expr, field), stacklevel=4) return None
null
null
null
What does this give the ability to quiet a user ?
@require_chanmsg @require_privilege(OP, u'You are not a channel operator.') @commands(u'quiet') def quiet(bot, trigger): if (bot.privileges[trigger.sender][bot.nick] < OP): return bot.reply(u"I'm not a channel operator!") text = trigger.group().split() argc = len(text) if (argc < 2): return opt = Identifier(text[1]) quietmask = opt channel = trigger.sender if (not opt.is_nick()): if (argc < 3): return quietmask = text[2] channel = opt quietmask = configureHostMask(quietmask) if (quietmask == u''): return bot.write([u'MODE', channel, u'+q', quietmask])
null
null
null
admins
codeqa
@require chanmsg@require privilege OP u' Youarenotachanneloperator ' @commands u'quiet' def quiet bot trigger if bot privileges[trigger sender][bot nick] < OP return bot reply u"I'mnotachanneloperator " text trigger group split argc len text if argc < 2 returnopt Identifier text[ 1 ] quietmask optchannel trigger senderif not opt is nick if argc < 3 returnquietmask text[ 2 ]channel optquietmask configure Host Mask quietmask if quietmask u'' returnbot write [u'MODE' channel u'+q' quietmask]
null
null
null
null
Question: What does this give the ability to quiet a user ? Code: @require_chanmsg @require_privilege(OP, u'You are not a channel operator.') @commands(u'quiet') def quiet(bot, trigger): if (bot.privileges[trigger.sender][bot.nick] < OP): return bot.reply(u"I'm not a channel operator!") text = trigger.group().split() argc = len(text) if (argc < 2): return opt = Identifier(text[1]) quietmask = opt channel = trigger.sender if (not opt.is_nick()): if (argc < 3): return quietmask = text[2] channel = opt quietmask = configureHostMask(quietmask) if (quietmask == u''): return bot.write([u'MODE', channel, u'+q', quietmask])
null
null
null
What gives the ability to quiet a user admins ?
@require_chanmsg @require_privilege(OP, u'You are not a channel operator.') @commands(u'quiet') def quiet(bot, trigger): if (bot.privileges[trigger.sender][bot.nick] < OP): return bot.reply(u"I'm not a channel operator!") text = trigger.group().split() argc = len(text) if (argc < 2): return opt = Identifier(text[1]) quietmask = opt channel = trigger.sender if (not opt.is_nick()): if (argc < 3): return quietmask = text[2] channel = opt quietmask = configureHostMask(quietmask) if (quietmask == u''): return bot.write([u'MODE', channel, u'+q', quietmask])
null
null
null
this
codeqa
@require chanmsg@require privilege OP u' Youarenotachanneloperator ' @commands u'quiet' def quiet bot trigger if bot privileges[trigger sender][bot nick] < OP return bot reply u"I'mnotachanneloperator " text trigger group split argc len text if argc < 2 returnopt Identifier text[ 1 ] quietmask optchannel trigger senderif not opt is nick if argc < 3 returnquietmask text[ 2 ]channel optquietmask configure Host Mask quietmask if quietmask u'' returnbot write [u'MODE' channel u'+q' quietmask]
null
null
null
null
Question: What gives the ability to quiet a user admins ? Code: @require_chanmsg @require_privilege(OP, u'You are not a channel operator.') @commands(u'quiet') def quiet(bot, trigger): if (bot.privileges[trigger.sender][bot.nick] < OP): return bot.reply(u"I'm not a channel operator!") text = trigger.group().split() argc = len(text) if (argc < 2): return opt = Identifier(text[1]) quietmask = opt channel = trigger.sender if (not opt.is_nick()): if (argc < 3): return quietmask = text[2] channel = opt quietmask = configureHostMask(quietmask) if (quietmask == u''): return bot.write([u'MODE', channel, u'+q', quietmask])
null
null
null
What does this give admins ?
@require_chanmsg @require_privilege(OP, u'You are not a channel operator.') @commands(u'quiet') def quiet(bot, trigger): if (bot.privileges[trigger.sender][bot.nick] < OP): return bot.reply(u"I'm not a channel operator!") text = trigger.group().split() argc = len(text) if (argc < 2): return opt = Identifier(text[1]) quietmask = opt channel = trigger.sender if (not opt.is_nick()): if (argc < 3): return quietmask = text[2] channel = opt quietmask = configureHostMask(quietmask) if (quietmask == u''): return bot.write([u'MODE', channel, u'+q', quietmask])
null
null
null
the ability to quiet a user
codeqa
@require chanmsg@require privilege OP u' Youarenotachanneloperator ' @commands u'quiet' def quiet bot trigger if bot privileges[trigger sender][bot nick] < OP return bot reply u"I'mnotachanneloperator " text trigger group split argc len text if argc < 2 returnopt Identifier text[ 1 ] quietmask optchannel trigger senderif not opt is nick if argc < 3 returnquietmask text[ 2 ]channel optquietmask configure Host Mask quietmask if quietmask u'' returnbot write [u'MODE' channel u'+q' quietmask]
null
null
null
null
Question: What does this give admins ? Code: @require_chanmsg @require_privilege(OP, u'You are not a channel operator.') @commands(u'quiet') def quiet(bot, trigger): if (bot.privileges[trigger.sender][bot.nick] < OP): return bot.reply(u"I'm not a channel operator!") text = trigger.group().split() argc = len(text) if (argc < 2): return opt = Identifier(text[1]) quietmask = opt channel = trigger.sender if (not opt.is_nick()): if (argc < 3): return quietmask = text[2] channel = opt quietmask = configureHostMask(quietmask) if (quietmask == u''): return bot.write([u'MODE', channel, u'+q', quietmask])
null
null
null
What is using col ?
def show_message(message, col=c.r, update=False): g.content = content.generate_songlist_display() g.message = ((col + message) + c.w) if update: screen.update()
null
null
null
message
codeqa
def show message message col c r update False g content content generate songlist display g message col + message + c w if update screen update
null
null
null
null
Question: What is using col ? Code: def show_message(message, col=c.r, update=False): g.content = content.generate_songlist_display() g.message = ((col + message) + c.w) if update: screen.update()
null
null
null
What do message use ?
def show_message(message, col=c.r, update=False): g.content = content.generate_songlist_display() g.message = ((col + message) + c.w) if update: screen.update()
null
null
null
col
codeqa
def show message message col c r update False g content content generate songlist display g message col + message + c w if update screen update
null
null
null
null
Question: What do message use ? Code: def show_message(message, col=c.r, update=False): g.content = content.generate_songlist_display() g.message = ((col + message) + c.w) if update: screen.update()
null
null
null
How do message show ?
def show_message(message, col=c.r, update=False): g.content = content.generate_songlist_display() g.message = ((col + message) + c.w) if update: screen.update()
null
null
null
using col
codeqa
def show message message col c r update False g content content generate songlist display g message col + message + c w if update screen update
null
null
null
null
Question: How do message show ? Code: def show_message(message, col=c.r, update=False): g.content = content.generate_songlist_display() g.message = ((col + message) + c.w) if update: screen.update()
null
null
null
What did the code set ?
def setup_default_session(**kwargs): global DEFAULT_SESSION DEFAULT_SESSION = Session(**kwargs)
null
null
null
a default session
codeqa
def setup default session **kwargs global DEFAULT SESSIONDEFAULT SESSION Session **kwargs
null
null
null
null
Question: What did the code set ? Code: def setup_default_session(**kwargs): global DEFAULT_SESSION DEFAULT_SESSION = Session(**kwargs)
null
null
null
When does it yield ?
def notify_info_yielded(event): def decorator(generator): def decorated(*args, **kwargs): for v in generator(*args, **kwargs): send(event, info=v) (yield v) return decorated return decorator
null
null
null
every time
codeqa
def notify info yielded event def decorator generator def decorated *args **kwargs for v in generator *args **kwargs send event info v yield v return decoratedreturn decorator
null
null
null
null
Question: When does it yield ? Code: def notify_info_yielded(event): def decorator(generator): def decorated(*args, **kwargs): for v in generator(*args, **kwargs): send(event, info=v) (yield v) return decorated return decorator
null
null
null
How did the code get suffix hashes from the object server ?
def direct_get_suffix_hashes(node, part, suffixes, conn_timeout=5, response_timeout=15, headers=None): if (headers is None): headers = {} path = ('/%s' % '-'.join(suffixes)) with Timeout(conn_timeout): conn = http_connect(node['replication_ip'], node['replication_port'], node['device'], part, 'REPLICATE', path, headers=gen_headers(headers)) with Timeout(response_timeout): resp = conn.getresponse() if (not is_success(resp.status)): raise DirectClientException('Object', 'REPLICATE', node, part, path, resp, host={'ip': node['replication_ip'], 'port': node['replication_port']}) return pickle.loads(resp.read())
null
null
null
directly
codeqa
def direct get suffix hashes node part suffixes conn timeout 5 response timeout 15 headers None if headers is None headers {}path '/%s' % '-' join suffixes with Timeout conn timeout conn http connect node['replication ip'] node['replication port'] node['device'] part 'REPLICATE' path headers gen headers headers with Timeout response timeout resp conn getresponse if not is success resp status raise Direct Client Exception ' Object' 'REPLICATE' node part path resp host {'ip' node['replication ip'] 'port' node['replication port']} return pickle loads resp read
null
null
null
null
Question: How did the code get suffix hashes from the object server ? Code: def direct_get_suffix_hashes(node, part, suffixes, conn_timeout=5, response_timeout=15, headers=None): if (headers is None): headers = {} path = ('/%s' % '-'.join(suffixes)) with Timeout(conn_timeout): conn = http_connect(node['replication_ip'], node['replication_port'], node['device'], part, 'REPLICATE', path, headers=gen_headers(headers)) with Timeout(response_timeout): resp = conn.getresponse() if (not is_success(resp.status)): raise DirectClientException('Object', 'REPLICATE', node, part, path, resp, host={'ip': node['replication_ip'], 'port': node['replication_port']}) return pickle.loads(resp.read())
null
null
null
How does the code get the complex polar ?
def getPolarByRadians(angleRadians, radius=1.0): return (radius * euclidean.getWiddershinsUnitPolar(angleRadians))
null
null
null
by radians
codeqa
def get Polar By Radians angle Radians radius 1 0 return radius * euclidean get Widdershins Unit Polar angle Radians
null
null
null
null
Question: How does the code get the complex polar ? Code: def getPolarByRadians(angleRadians, radius=1.0): return (radius * euclidean.getWiddershinsUnitPolar(angleRadians))
null
null
null
What does the code get by radians ?
def getPolarByRadians(angleRadians, radius=1.0): return (radius * euclidean.getWiddershinsUnitPolar(angleRadians))
null
null
null
the complex polar
codeqa
def get Polar By Radians angle Radians radius 1 0 return radius * euclidean get Widdershins Unit Polar angle Radians
null
null
null
null
Question: What does the code get by radians ? Code: def getPolarByRadians(angleRadians, radius=1.0): return (radius * euclidean.getWiddershinsUnitPolar(angleRadians))