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
Where should all the views exist ?
def ensure_views(): options = _get_options(ret=None) _response = _request('GET', ((options['url'] + options['db']) + '/_design/salt')) if ('error' in _response): return set_salt_view() for view in get_valid_salt_views(): if (view not in _response['views']): return set_salt_view() return True
null
null
null
in the design document
codeqa
def ensure views options get options ret None response request 'GET' options['url'] + options['db'] + '/ design/salt' if 'error' in response return set salt view for view in get valid salt views if view not in response['views'] return set salt view return True
null
null
null
null
Question: Where should all the views exist ? Code: def ensure_views(): options = _get_options(ret=None) _response = _request('GET', ((options['url'] + options['db']) + '/_design/salt')) if ('error' in _response): return set_salt_view() for view in get_valid_salt_views(): if (view not in _response['views']): return set_salt_view() return True
null
null
null
How is a given cookie set ?
@bdd.then(bdd.parsers.parse('the cookie {name} should be set to {value}')) def check_cookie(quteproc, name, value): content = quteproc.get_content() data = json.loads(content) print data assert (data['cookies'][name] == value)
null
null
null
correctly
codeqa
@bdd then bdd parsers parse 'thecookie{name}shouldbesetto{value}' def check cookie quteproc name value content quteproc get content data json loads content print dataassert data['cookies'][name] value
null
null
null
null
Question: How is a given cookie set ? Code: @bdd.then(bdd.parsers.parse('the cookie {name} should be set to {value}')) def check_cookie(quteproc, name, value): content = quteproc.get_content() data = json.loads(content) print data assert (data['cookies'][name] == value)
null
null
null
What is neglecting its initial ordering ?
def unsorted_unique(lista): return list(set(lista))
null
null
null
duplicates
codeqa
def unsorted unique lista return list set lista
null
null
null
null
Question: What is neglecting its initial ordering ? Code: def unsorted_unique(lista): return list(set(lista))
null
null
null
What do duplicates neglect ?
def unsorted_unique(lista): return list(set(lista))
null
null
null
its initial ordering
codeqa
def unsorted unique lista return list set lista
null
null
null
null
Question: What do duplicates neglect ? Code: def unsorted_unique(lista): return list(set(lista))
null
null
null
What does the code clear ?
def clearScreen(): sys.stdout.write((((SEQ_PREFIX + '[H') + SEQ_PREFIX) + '[2J'))
null
null
null
the screen
codeqa
def clear Screen sys stdout write SEQ PREFIX + '[H' + SEQ PREFIX + '[ 2 J'
null
null
null
null
Question: What does the code clear ? Code: def clearScreen(): sys.stdout.write((((SEQ_PREFIX + '[H') + SEQ_PREFIX) + '[2J'))
null
null
null
How was the namespace required previously ?
def get_required_version(namespace): global _versions return _versions.get(namespace, None)
null
null
null
through require_version
codeqa
def get required version namespace global versionsreturn versions get namespace None
null
null
null
null
Question: How was the namespace required previously ? Code: def get_required_version(namespace): global _versions return _versions.get(namespace, None)
null
null
null
When was the namespace required through require_version ?
def get_required_version(namespace): global _versions return _versions.get(namespace, None)
null
null
null
previously
codeqa
def get required version namespace global versionsreturn versions get namespace None
null
null
null
null
Question: When was the namespace required through require_version ? Code: def get_required_version(namespace): global _versions return _versions.get(namespace, None)
null
null
null
For what purpose do the stop point of the next batch return ?
def _expiry_range_batched(session, upper_bound_func, batch_size): LOG.debug('Token expiration batch size: %d', batch_size) query = session.query(TokenModel.expires) query = query.filter((TokenModel.expires < upper_bound_func())) query = query.order_by(TokenModel.expires) query = query.offset((batch_size - 1)) query = query.limit(1) while True: try: next_expiration = query.one()[0] except sql.NotFound: break (yield next_expiration) (yield upper_bound_func())
null
null
null
for expiration
codeqa
def expiry range batched session upper bound func batch size LOG debug ' Tokenexpirationbatchsize %d' batch size query session query Token Model expires query query filter Token Model expires < upper bound func query query order by Token Model expires query query offset batch size - 1 query query limit 1 while True try next expiration query one [0 ]except sql Not Found break yield next expiration yield upper bound func
null
null
null
null
Question: For what purpose do the stop point of the next batch return ? Code: def _expiry_range_batched(session, upper_bound_func, batch_size): LOG.debug('Token expiration batch size: %d', batch_size) query = session.query(TokenModel.expires) query = query.filter((TokenModel.expires < upper_bound_func())) query = query.order_by(TokenModel.expires) query = query.offset((batch_size - 1)) query = query.limit(1) while True: try: next_expiration = query.one()[0] except sql.NotFound: break (yield next_expiration) (yield upper_bound_func())
null
null
null
Where be print expression evaluated ?
def print_python(leaves, expr): if (isinstance(expr, Expr) and any((expr.isidentical(lf) for lf in leaves))): return (valid_identifier(expr._name), {}) return _print_python(expr, leaves=leaves)
null
null
null
in python
codeqa
def print python leaves expr if isinstance expr Expr and any expr isidentical lf for lf in leaves return valid identifier expr name {} return print python expr leaves leaves
null
null
null
null
Question: Where be print expression evaluated ? Code: def print_python(leaves, expr): if (isinstance(expr, Expr) and any((expr.isidentical(lf) for lf in leaves))): return (valid_identifier(expr._name), {}) return _print_python(expr, leaves=leaves)
null
null
null
Where does the code return a dict of all available vm sizes ?
def avail_sizes(call=None): if (call == 'action'): raise SaltCloudSystemExit('The avail_sizes function must be called with -f or --function, or with the --list-sizes option') ret = {} conn = get_conn(service='SoftLayer_Product_Package') for category in conn.getCategories(id=50): if (category['categoryCode'] != 'server_core'): continue for group in category['groups']: for price in group['prices']: ret[price['id']] = price['item'].copy() del ret[price['id']]['id'] return ret
null
null
null
on the cloud provider
codeqa
def avail sizes call None if call 'action' raise Salt Cloud System Exit ' Theavail sizesfunctionmustbecalledwith-for--function orwiththe--list-sizesoption' ret {}conn get conn service ' Soft Layer Product Package' for category in conn get Categories id 50 if category['category Code'] 'server core' continuefor group in category['groups'] for price in group['prices'] ret[price['id']] price['item'] copy del ret[price['id']]['id']return ret
null
null
null
null
Question: Where does the code return a dict of all available vm sizes ? Code: def avail_sizes(call=None): if (call == 'action'): raise SaltCloudSystemExit('The avail_sizes function must be called with -f or --function, or with the --list-sizes option') ret = {} conn = get_conn(service='SoftLayer_Product_Package') for category in conn.getCategories(id=50): if (category['categoryCode'] != 'server_core'): continue for group in category['groups']: for price in group['prices']: ret[price['id']] = price['item'].copy() del ret[price['id']]['id'] return ret
null
null
null
For what purpose do events offer ?
def setup(hass, config): component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL, DOMAIN) component.setup(config) return True
null
null
null
for calendars
codeqa
def setup hass config component Entity Component logging get Logger name DOMAIN hass SCAN INTERVAL DOMAIN component setup config return True
null
null
null
null
Question: For what purpose do events offer ? Code: def setup(hass, config): component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL, DOMAIN) component.setup(config) return True
null
null
null
What can a driver function advance ?
def sine(w, A=1, phi=0, offset=0): from math import sin def f(i): return ((A * sin(((w * i) + phi))) + offset) return partial(_force, sequence=_advance(f))
null
null
null
a sequence of sine values
codeqa
def sine w A 1 phi 0 offset 0 from math import sindef f i return A * sin w * i + phi + offset return partial force sequence advance f
null
null
null
null
Question: What can a driver function advance ? Code: def sine(w, A=1, phi=0, offset=0): from math import sin def f(i): return ((A * sin(((w * i) + phi))) + offset) return partial(_force, sequence=_advance(f))
null
null
null
What can advance a sequence of sine values ?
def sine(w, A=1, phi=0, offset=0): from math import sin def f(i): return ((A * sin(((w * i) + phi))) + offset) return partial(_force, sequence=_advance(f))
null
null
null
a driver function
codeqa
def sine w A 1 phi 0 offset 0 from math import sindef f i return A * sin w * i + phi + offset return partial force sequence advance f
null
null
null
null
Question: What can advance a sequence of sine values ? Code: def sine(w, A=1, phi=0, offset=0): from math import sin def f(i): return ((A * sin(((w * i) + phi))) + offset) return partial(_force, sequence=_advance(f))
null
null
null
What does the code delete ?
@patch('twilio.rest.resources.base.Resource.request') def test_delete(req): resp = Mock() resp.content = '' resp.status_code = 204 req.return_value = (resp, {}) app = Call(list_resource, 'CA123') app.delete() uri = 'https://api.twilio.com/2010-04-01/Accounts/AC123/Calls/CA123' req.assert_called_with('DELETE', uri)
null
null
null
a call
codeqa
@patch 'twilio rest resources base Resource request' def test delete req resp Mock resp content ''resp status code 204 req return value resp {} app Call list resource 'CA 123 ' app delete uri 'https //api twilio com/ 2010 - 04 - 01 / Accounts/AC 123 / Calls/CA 123 'req assert called with 'DELETE' uri
null
null
null
null
Question: What does the code delete ? Code: @patch('twilio.rest.resources.base.Resource.request') def test_delete(req): resp = Mock() resp.content = '' resp.status_code = 204 req.return_value = (resp, {}) app = Call(list_resource, 'CA123') app.delete() uri = 'https://api.twilio.com/2010-04-01/Accounts/AC123/Calls/CA123' req.assert_called_with('DELETE', uri)
null
null
null
What does the code parse ?
def parse_date_from_string(datetime_str): datetime_obj = datetime.datetime.strptime(datetime_str, feconf.DASHBOARD_STATS_DATETIME_STRING_FORMAT) return {'year': datetime_obj.year, 'month': datetime_obj.month, 'day': datetime_obj.day}
null
null
null
the given string
codeqa
def parse date from string datetime str datetime obj datetime datetime strptime datetime str feconf DASHBOARD STATS DATETIME STRING FORMAT return {'year' datetime obj year 'month' datetime obj month 'day' datetime obj day}
null
null
null
null
Question: What does the code parse ? Code: def parse_date_from_string(datetime_str): datetime_obj = datetime.datetime.strptime(datetime_str, feconf.DASHBOARD_STATS_DATETIME_STRING_FORMAT) return {'year': datetime_obj.year, 'month': datetime_obj.month, 'day': datetime_obj.day}
null
null
null
When do a method such that wrap ?
def save_method_args(method): args_and_kwargs = collections.namedtuple(u'args_and_kwargs', u'args kwargs') @functools.wraps(method) def wrapper(self, *args, **kwargs): attr_name = (u'_saved_' + method.__name__) attr = args_and_kwargs(args, kwargs) setattr(self, attr_name, attr) return method(self, *args, **kwargs) return wrapper
null
null
null
when it is called
codeqa
def save method args method args and kwargs collections namedtuple u'args and kwargs' u'argskwargs' @functools wraps method def wrapper self *args **kwargs attr name u' saved ' + method name attr args and kwargs args kwargs setattr self attr name attr return method self *args **kwargs return wrapper
null
null
null
null
Question: When do a method such that wrap ? Code: def save_method_args(method): args_and_kwargs = collections.namedtuple(u'args_and_kwargs', u'args kwargs') @functools.wraps(method) def wrapper(self, *args, **kwargs): attr_name = (u'_saved_' + method.__name__) attr = args_and_kwargs(args, kwargs) setattr(self, attr_name, attr) return method(self, *args, **kwargs) return wrapper
null
null
null
What does the code return as a deferred ?
def deferToThreadPool(reactor, threadpool, f, *args, **kwargs): d = defer.Deferred() def onResult(success, result): if success: reactor.callFromThread(d.callback, result) else: reactor.callFromThread(d.errback, result) threadpool.callInThreadWithCallback(onResult, f, *args, **kwargs) return d
null
null
null
the result
codeqa
def defer To Thread Pool reactor threadpool f *args **kwargs d defer Deferred def on Result success result if success reactor call From Thread d callback result else reactor call From Thread d errback result threadpool call In Thread With Callback on Result f *args **kwargs return d
null
null
null
null
Question: What does the code return as a deferred ? Code: def deferToThreadPool(reactor, threadpool, f, *args, **kwargs): d = defer.Deferred() def onResult(success, result): if success: reactor.callFromThread(d.callback, result) else: reactor.callFromThread(d.errback, result) threadpool.callInThreadWithCallback(onResult, f, *args, **kwargs) return d
null
null
null
What did foo use ?
def test_crash_empty_prefix(lookup): results = lookup.lookup(u':Eevee') assert (results[0].object.name == u'Eevee')
null
null
null
to crash
codeqa
def test crash empty prefix lookup results lookup lookup u' Eevee' assert results[ 0 ] object name u' Eevee'
null
null
null
null
Question: What did foo use ? Code: def test_crash_empty_prefix(lookup): results = lookup.lookup(u':Eevee') assert (results[0].object.name == u'Eevee')
null
null
null
What used to crash ?
def test_crash_empty_prefix(lookup): results = lookup.lookup(u':Eevee') assert (results[0].object.name == u'Eevee')
null
null
null
foo
codeqa
def test crash empty prefix lookup results lookup lookup u' Eevee' assert results[ 0 ] object name u' Eevee'
null
null
null
null
Question: What used to crash ? Code: def test_crash_empty_prefix(lookup): results = lookup.lookup(u':Eevee') assert (results[0].object.name == u'Eevee')
null
null
null
What chooses one ?
def explore_folder(c, name): while True: c.select_folder(name, readonly=True) msgdict = c.fetch('1:*', ['BODY.PEEK[HEADER.FIELDS (FROM SUBJECT)]', 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE']) print for uid in sorted(msgdict): items = msgdict[uid] print ('%6d %20s %6d bytes %s' % (uid, items['INTERNALDATE'], items['RFC822.SIZE'], ' '.join(items['FLAGS']))) for i in items['BODY[HEADER.FIELDS (FROM SUBJECT)]'].splitlines(): print (' ' * 6), i.strip() reply = raw_input(('Folder %s - type a message UID, or "q" to quit: ' % name)).strip() if reply.lower().startswith('q'): break try: reply = int(reply) except ValueError: print 'Please type an integer or "q" to quit' else: if (reply in msgdict): explore_message(c, reply) c.close_folder()
null
null
null
the user
codeqa
def explore folder c name while True c select folder name readonly True msgdict c fetch '1 *' ['BODY PEEK[HEADER FIELDS FROMSUBJECT ]' 'FLAGS' 'INTERNALDATE' 'RFC 822 SIZE'] printfor uid in sorted msgdict items msgdict[uid]print '% 6 d% 20 s% 6 dbytes%s' % uid items['INTERNALDATE'] items['RFC 822 SIZE'] '' join items['FLAGS'] for i in items['BODY[HEADER FIELDS FROMSUBJECT ]'] splitlines print '' * 6 i strip reply raw input ' Folder%s-typeamessage UID or"q"toquit ' % name strip if reply lower startswith 'q' breaktry reply int reply except Value Error print ' Pleasetypeanintegeror"q"toquit'else if reply in msgdict explore message c reply c close folder
null
null
null
null
Question: What chooses one ? Code: def explore_folder(c, name): while True: c.select_folder(name, readonly=True) msgdict = c.fetch('1:*', ['BODY.PEEK[HEADER.FIELDS (FROM SUBJECT)]', 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE']) print for uid in sorted(msgdict): items = msgdict[uid] print ('%6d %20s %6d bytes %s' % (uid, items['INTERNALDATE'], items['RFC822.SIZE'], ' '.join(items['FLAGS']))) for i in items['BODY[HEADER.FIELDS (FROM SUBJECT)]'].splitlines(): print (' ' * 6), i.strip() reply = raw_input(('Folder %s - type a message UID, or "q" to quit: ' % name)).strip() if reply.lower().startswith('q'): break try: reply = int(reply) except ValueError: print 'Please type an integer or "q" to quit' else: if (reply in msgdict): explore_message(c, reply) c.close_folder()
null
null
null
Where do the messages list ?
def explore_folder(c, name): while True: c.select_folder(name, readonly=True) msgdict = c.fetch('1:*', ['BODY.PEEK[HEADER.FIELDS (FROM SUBJECT)]', 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE']) print for uid in sorted(msgdict): items = msgdict[uid] print ('%6d %20s %6d bytes %s' % (uid, items['INTERNALDATE'], items['RFC822.SIZE'], ' '.join(items['FLAGS']))) for i in items['BODY[HEADER.FIELDS (FROM SUBJECT)]'].splitlines(): print (' ' * 6), i.strip() reply = raw_input(('Folder %s - type a message UID, or "q" to quit: ' % name)).strip() if reply.lower().startswith('q'): break try: reply = int(reply) except ValueError: print 'Please type an integer or "q" to quit' else: if (reply in msgdict): explore_message(c, reply) c.close_folder()
null
null
null
in folder name
codeqa
def explore folder c name while True c select folder name readonly True msgdict c fetch '1 *' ['BODY PEEK[HEADER FIELDS FROMSUBJECT ]' 'FLAGS' 'INTERNALDATE' 'RFC 822 SIZE'] printfor uid in sorted msgdict items msgdict[uid]print '% 6 d% 20 s% 6 dbytes%s' % uid items['INTERNALDATE'] items['RFC 822 SIZE'] '' join items['FLAGS'] for i in items['BODY[HEADER FIELDS FROMSUBJECT ]'] splitlines print '' * 6 i strip reply raw input ' Folder%s-typeamessage UID or"q"toquit ' % name strip if reply lower startswith 'q' breaktry reply int reply except Value Error print ' Pleasetypeanintegeror"q"toquit'else if reply in msgdict explore message c reply c close folder
null
null
null
null
Question: Where do the messages list ? Code: def explore_folder(c, name): while True: c.select_folder(name, readonly=True) msgdict = c.fetch('1:*', ['BODY.PEEK[HEADER.FIELDS (FROM SUBJECT)]', 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE']) print for uid in sorted(msgdict): items = msgdict[uid] print ('%6d %20s %6d bytes %s' % (uid, items['INTERNALDATE'], items['RFC822.SIZE'], ' '.join(items['FLAGS']))) for i in items['BODY[HEADER.FIELDS (FROM SUBJECT)]'].splitlines(): print (' ' * 6), i.strip() reply = raw_input(('Folder %s - type a message UID, or "q" to quit: ' % name)).strip() if reply.lower().startswith('q'): break try: reply = int(reply) except ValueError: print 'Please type an integer or "q" to quit' else: if (reply in msgdict): explore_message(c, reply) c.close_folder()
null
null
null
What lists in folder name ?
def explore_folder(c, name): while True: c.select_folder(name, readonly=True) msgdict = c.fetch('1:*', ['BODY.PEEK[HEADER.FIELDS (FROM SUBJECT)]', 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE']) print for uid in sorted(msgdict): items = msgdict[uid] print ('%6d %20s %6d bytes %s' % (uid, items['INTERNALDATE'], items['RFC822.SIZE'], ' '.join(items['FLAGS']))) for i in items['BODY[HEADER.FIELDS (FROM SUBJECT)]'].splitlines(): print (' ' * 6), i.strip() reply = raw_input(('Folder %s - type a message UID, or "q" to quit: ' % name)).strip() if reply.lower().startswith('q'): break try: reply = int(reply) except ValueError: print 'Please type an integer or "q" to quit' else: if (reply in msgdict): explore_message(c, reply) c.close_folder()
null
null
null
the messages
codeqa
def explore folder c name while True c select folder name readonly True msgdict c fetch '1 *' ['BODY PEEK[HEADER FIELDS FROMSUBJECT ]' 'FLAGS' 'INTERNALDATE' 'RFC 822 SIZE'] printfor uid in sorted msgdict items msgdict[uid]print '% 6 d% 20 s% 6 dbytes%s' % uid items['INTERNALDATE'] items['RFC 822 SIZE'] '' join items['FLAGS'] for i in items['BODY[HEADER FIELDS FROMSUBJECT ]'] splitlines print '' * 6 i strip reply raw input ' Folder%s-typeamessage UID or"q"toquit ' % name strip if reply lower startswith 'q' breaktry reply int reply except Value Error print ' Pleasetypeanintegeror"q"toquit'else if reply in msgdict explore message c reply c close folder
null
null
null
null
Question: What lists in folder name ? Code: def explore_folder(c, name): while True: c.select_folder(name, readonly=True) msgdict = c.fetch('1:*', ['BODY.PEEK[HEADER.FIELDS (FROM SUBJECT)]', 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE']) print for uid in sorted(msgdict): items = msgdict[uid] print ('%6d %20s %6d bytes %s' % (uid, items['INTERNALDATE'], items['RFC822.SIZE'], ' '.join(items['FLAGS']))) for i in items['BODY[HEADER.FIELDS (FROM SUBJECT)]'].splitlines(): print (' ' * 6), i.strip() reply = raw_input(('Folder %s - type a message UID, or "q" to quit: ' % name)).strip() if reply.lower().startswith('q'): break try: reply = int(reply) except ValueError: print 'Please type an integer or "q" to quit' else: if (reply in msgdict): explore_message(c, reply) c.close_folder()
null
null
null
What does the code convert to a set ?
def _multiple_range_string_to_set(ranges_str): char_set = set() for range_str in ranges_str.split(', '): if range_str.startswith('and '): range_str = range_str[4:] char_set.update(_range_string_to_set(range_str)) return char_set
null
null
null
a string of multiple ranges
codeqa
def multiple range string to set ranges str char set set for range str in ranges str split ' ' if range str startswith 'and' range str range str[ 4 ]char set update range string to set range str return char set
null
null
null
null
Question: What does the code convert to a set ? Code: def _multiple_range_string_to_set(ranges_str): char_set = set() for range_str in ranges_str.split(', '): if range_str.startswith('and '): range_str = range_str[4:] char_set.update(_range_string_to_set(range_str)) return char_set
null
null
null
When is coverage running ?
def is_coverage_running(): if ('coverage' not in sys.modules): return False tracer = sys.gettrace() if (tracer is None): return False try: mod = tracer.__module__ except AttributeError: try: mod = tracer.__class__.__module__ except AttributeError: return False return mod.startswith('coverage')
null
null
null
currently
codeqa
def is coverage running if 'coverage' not in sys modules return Falsetracer sys gettrace if tracer is None return Falsetry mod tracer module except Attribute Error try mod tracer class module except Attribute Error return Falsereturn mod startswith 'coverage'
null
null
null
null
Question: When is coverage running ? Code: def is_coverage_running(): if ('coverage' not in sys.modules): return False tracer = sys.gettrace() if (tracer is None): return False try: mod = tracer.__module__ except AttributeError: try: mod = tracer.__class__.__module__ except AttributeError: return False return mod.startswith('coverage')
null
null
null
For what purpose does a coefficient matrix return ?
def upper_tri_to_full(n): entries = ((n * (n + 1)) // 2) val_arr = [] row_arr = [] col_arr = [] count = 0 for i in range(n): for j in range(i, n): col_arr.append(count) row_arr.append(((j * n) + i)) val_arr.append(1.0) if (i != j): col_arr.append(count) row_arr.append(((i * n) + j)) val_arr.append(1.0) count += 1 return sp.coo_matrix((val_arr, (row_arr, col_arr)), ((n * n), entries)).tocsc()
null
null
null
to create a symmetric matrix
codeqa
def upper tri to full n entries n * n + 1 // 2 val arr []row arr []col arr []count 0for i in range n for j in range i n col arr append count row arr append j * n + i val arr append 1 0 if i j col arr append count row arr append i * n + j val arr append 1 0 count + 1return sp coo matrix val arr row arr col arr n * n entries tocsc
null
null
null
null
Question: For what purpose does a coefficient matrix return ? Code: def upper_tri_to_full(n): entries = ((n * (n + 1)) // 2) val_arr = [] row_arr = [] col_arr = [] count = 0 for i in range(n): for j in range(i, n): col_arr.append(count) row_arr.append(((j * n) + i)) val_arr.append(1.0) if (i != j): col_arr.append(count) row_arr.append(((i * n) + j)) val_arr.append(1.0) count += 1 return sp.coo_matrix((val_arr, (row_arr, col_arr)), ((n * n), entries)).tocsc()
null
null
null
What found in the locale folder ?
def get_available_translations(): locale_path = get_module_data_path('spyder', relpath='locale', attr_name='LOCALEPATH') listdir = os.listdir(locale_path) langs = [d for d in listdir if osp.isdir(osp.join(locale_path, d))] langs = ([DEFAULT_LANGUAGE] + langs) langs = list((set(langs) - set(DISABLED_LANGUAGES))) for lang in langs: if (lang not in LANGUAGE_CODES): error = _('Update LANGUAGE_CODES (inside config/base.py) if a new translation has been added to Spyder') raise Exception(error) return langs
null
null
null
the folders
codeqa
def get available translations locale path get module data path 'spyder' relpath 'locale' attr name 'LOCALEPATH' listdir os listdir locale path langs [d for d in listdir if osp isdir osp join locale path d ]langs [DEFAULT LANGUAGE] + langs langs list set langs - set DISABLED LANGUAGES for lang in langs if lang not in LANGUAGE CODES error ' Update LANGUAGE CODES insideconfig/base py ifanewtranslationhasbeenaddedto Spyder' raise Exception error return langs
null
null
null
null
Question: What found in the locale folder ? Code: def get_available_translations(): locale_path = get_module_data_path('spyder', relpath='locale', attr_name='LOCALEPATH') listdir = os.listdir(locale_path) langs = [d for d in listdir if osp.isdir(osp.join(locale_path, d))] langs = ([DEFAULT_LANGUAGE] + langs) langs = list((set(langs) - set(DISABLED_LANGUAGES))) for lang in langs: if (lang not in LANGUAGE_CODES): error = _('Update LANGUAGE_CODES (inside config/base.py) if a new translation has been added to Spyder') raise Exception(error) return langs
null
null
null
Where did the folders find ?
def get_available_translations(): locale_path = get_module_data_path('spyder', relpath='locale', attr_name='LOCALEPATH') listdir = os.listdir(locale_path) langs = [d for d in listdir if osp.isdir(osp.join(locale_path, d))] langs = ([DEFAULT_LANGUAGE] + langs) langs = list((set(langs) - set(DISABLED_LANGUAGES))) for lang in langs: if (lang not in LANGUAGE_CODES): error = _('Update LANGUAGE_CODES (inside config/base.py) if a new translation has been added to Spyder') raise Exception(error) return langs
null
null
null
in the locale folder
codeqa
def get available translations locale path get module data path 'spyder' relpath 'locale' attr name 'LOCALEPATH' listdir os listdir locale path langs [d for d in listdir if osp isdir osp join locale path d ]langs [DEFAULT LANGUAGE] + langs langs list set langs - set DISABLED LANGUAGES for lang in langs if lang not in LANGUAGE CODES error ' Update LANGUAGE CODES insideconfig/base py ifanewtranslationhasbeenaddedto Spyder' raise Exception error return langs
null
null
null
null
Question: Where did the folders find ? Code: def get_available_translations(): locale_path = get_module_data_path('spyder', relpath='locale', attr_name='LOCALEPATH') listdir = os.listdir(locale_path) langs = [d for d in listdir if osp.isdir(osp.join(locale_path, d))] langs = ([DEFAULT_LANGUAGE] + langs) langs = list((set(langs) - set(DISABLED_LANGUAGES))) for lang in langs: if (lang not in LANGUAGE_CODES): error = _('Update LANGUAGE_CODES (inside config/base.py) if a new translation has been added to Spyder') raise Exception(error) return langs
null
null
null
What is needed in fast_compile ?
@register_canonicalize('fast_compile') @register_useless @gof.local_optimizer([T.fill]) def local_useless_fill(node): if (node.op == T.fill): (r, v) = node.inputs if (v.type == node.outputs[0].type): return [v]
null
null
null
this optimization
codeqa
@register canonicalize 'fast compile' @register useless@gof local optimizer [T fill] def local useless fill node if node op T fill r v node inputsif v type node outputs[ 0 ] type return [v]
null
null
null
null
Question: What is needed in fast_compile ? Code: @register_canonicalize('fast_compile') @register_useless @gof.local_optimizer([T.fill]) def local_useless_fill(node): if (node.op == T.fill): (r, v) = node.inputs if (v.type == node.outputs[0].type): return [v]
null
null
null
For what purpose is this optimization needed only in fast_compile ?
@register_canonicalize('fast_compile') @register_useless @gof.local_optimizer([T.fill]) def local_useless_fill(node): if (node.op == T.fill): (r, v) = node.inputs if (v.type == node.outputs[0].type): return [v]
null
null
null
to make the code more readable
codeqa
@register canonicalize 'fast compile' @register useless@gof local optimizer [T fill] def local useless fill node if node op T fill r v node inputsif v type node outputs[ 0 ] type return [v]
null
null
null
null
Question: For what purpose is this optimization needed only in fast_compile ? Code: @register_canonicalize('fast_compile') @register_useless @gof.local_optimizer([T.fill]) def local_useless_fill(node): if (node.op == T.fill): (r, v) = node.inputs if (v.type == node.outputs[0].type): return [v]
null
null
null
Where is this optimization needed only to make the code more readable ?
@register_canonicalize('fast_compile') @register_useless @gof.local_optimizer([T.fill]) def local_useless_fill(node): if (node.op == T.fill): (r, v) = node.inputs if (v.type == node.outputs[0].type): return [v]
null
null
null
in fast_compile
codeqa
@register canonicalize 'fast compile' @register useless@gof local optimizer [T fill] def local useless fill node if node op T fill r v node inputsif v type node outputs[ 0 ] type return [v]
null
null
null
null
Question: Where is this optimization needed only to make the code more readable ? Code: @register_canonicalize('fast_compile') @register_useless @gof.local_optimizer([T.fill]) def local_useless_fill(node): if (node.op == T.fill): (r, v) = node.inputs if (v.type == node.outputs[0].type): return [v]
null
null
null
What does beta function create via frames ?
def create_animations(figure, filename=None, sharing='public', auto_open=True): body = {'figure': figure, 'world_readable': True} if filename: if ('/' in filename): warnings.warn("This BETA version of 'create_animations' does not support automatic folder creation. This means a filename of the form 'name1/name2' will just create the plot with that name only.") body['filename'] = filename if (sharing == 'public'): body['world_readable'] = True elif (sharing == 'private'): body['world_readable'] = False elif (sharing == 'secret'): body['world_readable'] = False body['share_key_enabled'] = True else: raise exceptions.PlotlyError("Whoops, sharing can only be set to either 'public', 'private', or 'secret'.") response = v2.plots.create(body) parsed_content = response.json() if (sharing == 'secret'): web_url = ((parsed_content['file']['web_url'][:(-1)] + '?share_key=') + parsed_content['file']['share_key']) else: web_url = parsed_content['file']['web_url'] if auto_open: _open_url(web_url) return web_url
null
null
null
plots with animations
codeqa
def create animations figure filename None sharing 'public' auto open True body {'figure' figure 'world readable' True}if filename if '/' in filename warnings warn " This BET Aversionof'create animations'doesnotsupportautomaticfoldercreation Thismeansafilenameoftheform'name 1 /name 2 'willjustcreatetheplotwiththatnameonly " body['filename'] filenameif sharing 'public' body['world readable'] Trueelif sharing 'private' body['world readable'] Falseelif sharing 'secret' body['world readable'] Falsebody['share key enabled'] Trueelse raise exceptions Plotly Error " Whoops sharingcanonlybesettoeither'public' 'private' or'secret' " response v2 plots create body parsed content response json if sharing 'secret' web url parsed content['file']['web url'][ -1 ] + '?share key ' + parsed content['file']['share key'] else web url parsed content['file']['web url']if auto open open url web url return web url
null
null
null
null
Question: What does beta function create via frames ? Code: def create_animations(figure, filename=None, sharing='public', auto_open=True): body = {'figure': figure, 'world_readable': True} if filename: if ('/' in filename): warnings.warn("This BETA version of 'create_animations' does not support automatic folder creation. This means a filename of the form 'name1/name2' will just create the plot with that name only.") body['filename'] = filename if (sharing == 'public'): body['world_readable'] = True elif (sharing == 'private'): body['world_readable'] = False elif (sharing == 'secret'): body['world_readable'] = False body['share_key_enabled'] = True else: raise exceptions.PlotlyError("Whoops, sharing can only be set to either 'public', 'private', or 'secret'.") response = v2.plots.create(body) parsed_content = response.json() if (sharing == 'secret'): web_url = ((parsed_content['file']['web_url'][:(-1)] + '?share_key=') + parsed_content['file']['share_key']) else: web_url = parsed_content['file']['web_url'] if auto_open: _open_url(web_url) return web_url
null
null
null
What creates plots with animations via frames ?
def create_animations(figure, filename=None, sharing='public', auto_open=True): body = {'figure': figure, 'world_readable': True} if filename: if ('/' in filename): warnings.warn("This BETA version of 'create_animations' does not support automatic folder creation. This means a filename of the form 'name1/name2' will just create the plot with that name only.") body['filename'] = filename if (sharing == 'public'): body['world_readable'] = True elif (sharing == 'private'): body['world_readable'] = False elif (sharing == 'secret'): body['world_readable'] = False body['share_key_enabled'] = True else: raise exceptions.PlotlyError("Whoops, sharing can only be set to either 'public', 'private', or 'secret'.") response = v2.plots.create(body) parsed_content = response.json() if (sharing == 'secret'): web_url = ((parsed_content['file']['web_url'][:(-1)] + '?share_key=') + parsed_content['file']['share_key']) else: web_url = parsed_content['file']['web_url'] if auto_open: _open_url(web_url) return web_url
null
null
null
beta function
codeqa
def create animations figure filename None sharing 'public' auto open True body {'figure' figure 'world readable' True}if filename if '/' in filename warnings warn " This BET Aversionof'create animations'doesnotsupportautomaticfoldercreation Thismeansafilenameoftheform'name 1 /name 2 'willjustcreatetheplotwiththatnameonly " body['filename'] filenameif sharing 'public' body['world readable'] Trueelif sharing 'private' body['world readable'] Falseelif sharing 'secret' body['world readable'] Falsebody['share key enabled'] Trueelse raise exceptions Plotly Error " Whoops sharingcanonlybesettoeither'public' 'private' or'secret' " response v2 plots create body parsed content response json if sharing 'secret' web url parsed content['file']['web url'][ -1 ] + '?share key ' + parsed content['file']['share key'] else web url parsed content['file']['web url']if auto open open url web url return web url
null
null
null
null
Question: What creates plots with animations via frames ? Code: def create_animations(figure, filename=None, sharing='public', auto_open=True): body = {'figure': figure, 'world_readable': True} if filename: if ('/' in filename): warnings.warn("This BETA version of 'create_animations' does not support automatic folder creation. This means a filename of the form 'name1/name2' will just create the plot with that name only.") body['filename'] = filename if (sharing == 'public'): body['world_readable'] = True elif (sharing == 'private'): body['world_readable'] = False elif (sharing == 'secret'): body['world_readable'] = False body['share_key_enabled'] = True else: raise exceptions.PlotlyError("Whoops, sharing can only be set to either 'public', 'private', or 'secret'.") response = v2.plots.create(body) parsed_content = response.json() if (sharing == 'secret'): web_url = ((parsed_content['file']['web_url'][:(-1)] + '?share_key=') + parsed_content['file']['share_key']) else: web_url = parsed_content['file']['web_url'] if auto_open: _open_url(web_url) return web_url
null
null
null
How does beta function create plots with animations ?
def create_animations(figure, filename=None, sharing='public', auto_open=True): body = {'figure': figure, 'world_readable': True} if filename: if ('/' in filename): warnings.warn("This BETA version of 'create_animations' does not support automatic folder creation. This means a filename of the form 'name1/name2' will just create the plot with that name only.") body['filename'] = filename if (sharing == 'public'): body['world_readable'] = True elif (sharing == 'private'): body['world_readable'] = False elif (sharing == 'secret'): body['world_readable'] = False body['share_key_enabled'] = True else: raise exceptions.PlotlyError("Whoops, sharing can only be set to either 'public', 'private', or 'secret'.") response = v2.plots.create(body) parsed_content = response.json() if (sharing == 'secret'): web_url = ((parsed_content['file']['web_url'][:(-1)] + '?share_key=') + parsed_content['file']['share_key']) else: web_url = parsed_content['file']['web_url'] if auto_open: _open_url(web_url) return web_url
null
null
null
via frames
codeqa
def create animations figure filename None sharing 'public' auto open True body {'figure' figure 'world readable' True}if filename if '/' in filename warnings warn " This BET Aversionof'create animations'doesnotsupportautomaticfoldercreation Thismeansafilenameoftheform'name 1 /name 2 'willjustcreatetheplotwiththatnameonly " body['filename'] filenameif sharing 'public' body['world readable'] Trueelif sharing 'private' body['world readable'] Falseelif sharing 'secret' body['world readable'] Falsebody['share key enabled'] Trueelse raise exceptions Plotly Error " Whoops sharingcanonlybesettoeither'public' 'private' or'secret' " response v2 plots create body parsed content response json if sharing 'secret' web url parsed content['file']['web url'][ -1 ] + '?share key ' + parsed content['file']['share key'] else web url parsed content['file']['web url']if auto open open url web url return web url
null
null
null
null
Question: How does beta function create plots with animations ? Code: def create_animations(figure, filename=None, sharing='public', auto_open=True): body = {'figure': figure, 'world_readable': True} if filename: if ('/' in filename): warnings.warn("This BETA version of 'create_animations' does not support automatic folder creation. This means a filename of the form 'name1/name2' will just create the plot with that name only.") body['filename'] = filename if (sharing == 'public'): body['world_readable'] = True elif (sharing == 'private'): body['world_readable'] = False elif (sharing == 'secret'): body['world_readable'] = False body['share_key_enabled'] = True else: raise exceptions.PlotlyError("Whoops, sharing can only be set to either 'public', 'private', or 'secret'.") response = v2.plots.create(body) parsed_content = response.json() if (sharing == 'secret'): web_url = ((parsed_content['file']['web_url'][:(-1)] + '?share_key=') + parsed_content['file']['share_key']) else: web_url = parsed_content['file']['web_url'] if auto_open: _open_url(web_url) return web_url
null
null
null
What does the code suspend until another ?
def join(coro): return JoinEvent(coro)
null
null
null
the thread
codeqa
def join coro return Join Event coro
null
null
null
null
Question: What does the code suspend until another ? Code: def join(coro): return JoinEvent(coro)
null
null
null
Till when does the code suspend the thread ?
def join(coro): return JoinEvent(coro)
null
null
null
until another
codeqa
def join coro return Join Event coro
null
null
null
null
Question: Till when does the code suspend the thread ? Code: def join(coro): return JoinEvent(coro)
null
null
null
What is providing in templates ?
@register.tag def lorem(parser, token): bits = list(token.split_contents()) tagname = bits[0] common = (bits[(-1)] != 'random') if (not common): bits.pop() if (bits[(-1)] in ('w', 'p', 'b')): method = bits.pop() else: method = 'b' if (len(bits) > 1): count = bits.pop() else: count = '1' count = parser.compile_filter(count) if (len(bits) != 1): raise TemplateSyntaxError(('Incorrect format for %r tag' % tagname)) return LoremNode(count, method, common)
null
null
null
test data
codeqa
@register tagdef lorem parser token bits list token split contents tagname bits[ 0 ]common bits[ -1 ] 'random' if not common bits pop if bits[ -1 ] in 'w' 'p' 'b' method bits pop else method 'b'if len bits > 1 count bits pop else count '1 'count parser compile filter count if len bits 1 raise Template Syntax Error ' Incorrectformatfor%rtag' % tagname return Lorem Node count method common
null
null
null
null
Question: What is providing in templates ? Code: @register.tag def lorem(parser, token): bits = list(token.split_contents()) tagname = bits[0] common = (bits[(-1)] != 'random') if (not common): bits.pop() if (bits[(-1)] in ('w', 'p', 'b')): method = bits.pop() else: method = 'b' if (len(bits) > 1): count = bits.pop() else: count = '1' count = parser.compile_filter(count) if (len(bits) != 1): raise TemplateSyntaxError(('Incorrect format for %r tag' % tagname)) return LoremNode(count, method, common)
null
null
null
Where do test data provide ?
@register.tag def lorem(parser, token): bits = list(token.split_contents()) tagname = bits[0] common = (bits[(-1)] != 'random') if (not common): bits.pop() if (bits[(-1)] in ('w', 'p', 'b')): method = bits.pop() else: method = 'b' if (len(bits) > 1): count = bits.pop() else: count = '1' count = parser.compile_filter(count) if (len(bits) != 1): raise TemplateSyntaxError(('Incorrect format for %r tag' % tagname)) return LoremNode(count, method, common)
null
null
null
in templates
codeqa
@register tagdef lorem parser token bits list token split contents tagname bits[ 0 ]common bits[ -1 ] 'random' if not common bits pop if bits[ -1 ] in 'w' 'p' 'b' method bits pop else method 'b'if len bits > 1 count bits pop else count '1 'count parser compile filter count if len bits 1 raise Template Syntax Error ' Incorrectformatfor%rtag' % tagname return Lorem Node count method common
null
null
null
null
Question: Where do test data provide ? Code: @register.tag def lorem(parser, token): bits = list(token.split_contents()) tagname = bits[0] common = (bits[(-1)] != 'random') if (not common): bits.pop() if (bits[(-1)] in ('w', 'p', 'b')): method = bits.pop() else: method = 'b' if (len(bits) > 1): count = bits.pop() else: count = '1' count = parser.compile_filter(count) if (len(bits) != 1): raise TemplateSyntaxError(('Incorrect format for %r tag' % tagname)) return LoremNode(count, method, common)
null
null
null
What is obeying a power law distribution ?
def _powerlaw_sequence(gamma, low, high, condition, length, max_iters): for i in range(max_iters): seq = [] while (not length(seq)): seq.append(_zipf_rv_below(gamma, low, high)) if condition(seq): return seq raise nx.ExceededMaxIterations('Could not create power law sequence')
null
null
null
numbers
codeqa
def powerlaw sequence gamma low high condition length max iters for i in range max iters seq []while not length seq seq append zipf rv below gamma low high if condition seq return seqraise nx Exceeded Max Iterations ' Couldnotcreatepowerlawsequence'
null
null
null
null
Question: What is obeying a power law distribution ? Code: def _powerlaw_sequence(gamma, low, high, condition, length, max_iters): for i in range(max_iters): seq = [] while (not length(seq)): seq.append(_zipf_rv_below(gamma, low, high)) if condition(seq): return seq raise nx.ExceededMaxIterations('Could not create power law sequence')
null
null
null
What do numbers obey ?
def _powerlaw_sequence(gamma, low, high, condition, length, max_iters): for i in range(max_iters): seq = [] while (not length(seq)): seq.append(_zipf_rv_below(gamma, low, high)) if condition(seq): return seq raise nx.ExceededMaxIterations('Could not create power law sequence')
null
null
null
a power law distribution
codeqa
def powerlaw sequence gamma low high condition length max iters for i in range max iters seq []while not length seq seq append zipf rv below gamma low high if condition seq return seqraise nx Exceeded Max Iterations ' Couldnotcreatepowerlawsequence'
null
null
null
null
Question: What do numbers obey ? Code: def _powerlaw_sequence(gamma, low, high, condition, length, max_iters): for i in range(max_iters): seq = [] while (not length(seq)): seq.append(_zipf_rv_below(gamma, low, high)) if condition(seq): return seq raise nx.ExceededMaxIterations('Could not create power law sequence')
null
null
null
What require translation ?
@flake8ext def validate_log_translations(logical_line, physical_line, filename): if ('neutron/tests' in filename): return if pep8.noqa(physical_line): return msg = 'N320: Log messages require translation hints!' if log_translation_hint.match(logical_line): (yield (0, msg))
null
null
null
n320 - log messages
codeqa
@flake 8 extdef validate log translations logical line physical line filename if 'neutron/tests' in filename returnif pep 8 noqa physical line returnmsg 'N 320 Logmessagesrequiretranslationhints 'if log translation hint match logical line yield 0 msg
null
null
null
null
Question: What require translation ? Code: @flake8ext def validate_log_translations(logical_line, physical_line, filename): if ('neutron/tests' in filename): return if pep8.noqa(physical_line): return msg = 'N320: Log messages require translation hints!' if log_translation_hint.match(logical_line): (yield (0, msg))
null
null
null
What do n320 - log messages require ?
@flake8ext def validate_log_translations(logical_line, physical_line, filename): if ('neutron/tests' in filename): return if pep8.noqa(physical_line): return msg = 'N320: Log messages require translation hints!' if log_translation_hint.match(logical_line): (yield (0, msg))
null
null
null
translation
codeqa
@flake 8 extdef validate log translations logical line physical line filename if 'neutron/tests' in filename returnif pep 8 noqa physical line returnmsg 'N 320 Logmessagesrequiretranslationhints 'if log translation hint match logical line yield 0 msg
null
null
null
null
Question: What do n320 - log messages require ? Code: @flake8ext def validate_log_translations(logical_line, physical_line, filename): if ('neutron/tests' in filename): return if pep8.noqa(physical_line): return msg = 'N320: Log messages require translation hints!' if log_translation_hint.match(logical_line): (yield (0, msg))
null
null
null
What does the code validate ?
def demo_serialize_tagger(): postag(serialize_output='tagger.pcl')
null
null
null
the process
codeqa
def demo serialize tagger postag serialize output 'tagger pcl'
null
null
null
null
Question: What does the code validate ? Code: def demo_serialize_tagger(): postag(serialize_output='tagger.pcl')
null
null
null
What does the code serialize to a file in pickle format ?
def demo_serialize_tagger(): postag(serialize_output='tagger.pcl')
null
null
null
the learned tagger
codeqa
def demo serialize tagger postag serialize output 'tagger pcl'
null
null
null
null
Question: What does the code serialize to a file in pickle format ? Code: def demo_serialize_tagger(): postag(serialize_output='tagger.pcl')
null
null
null
What does the code run ?
def _putResultInDeferred(reactor, deferred, f, args, kwargs): try: result = f(*args, **kwargs) except Exception: f = failure.Failure() reactor.callFromThread(deferred.errback, f) else: reactor.callFromThread(deferred.callback, result)
null
null
null
a function
codeqa
def put Result In Deferred reactor deferred f args kwargs try result f *args **kwargs except Exception f failure Failure reactor call From Thread deferred errback f else reactor call From Thread deferred callback result
null
null
null
null
Question: What does the code run ? Code: def _putResultInDeferred(reactor, deferred, f, args, kwargs): try: result = f(*args, **kwargs) except Exception: f = failure.Failure() reactor.callFromThread(deferred.errback, f) else: reactor.callFromThread(deferred.callback, result)
null
null
null
What does the code give to a deferred ?
def _putResultInDeferred(reactor, deferred, f, args, kwargs): try: result = f(*args, **kwargs) except Exception: f = failure.Failure() reactor.callFromThread(deferred.errback, f) else: reactor.callFromThread(deferred.callback, result)
null
null
null
results
codeqa
def put Result In Deferred reactor deferred f args kwargs try result f *args **kwargs except Exception f failure Failure reactor call From Thread deferred errback f else reactor call From Thread deferred callback result
null
null
null
null
Question: What does the code give to a deferred ? Code: def _putResultInDeferred(reactor, deferred, f, args, kwargs): try: result = f(*args, **kwargs) except Exception: f = failure.Failure() reactor.callFromThread(deferred.errback, f) else: reactor.callFromThread(deferred.callback, result)
null
null
null
How will a class import from a string path ?
def dynamic_class_import(class_path): try: tmp = class_path.split('.') module_path = '.'.join(tmp[0:(-1)]) package = __import__(module_path) return reduce(getattr, tmp[1:], package) except Exception as e: log.error(LOGMSG_ERR_FAB_ADDON_IMPORT.format(class_path, e))
null
null
null
dynamically
codeqa
def dynamic class import class path try tmp class path split ' ' module path ' ' join tmp[ 0 -1 ] package import module path return reduce getattr tmp[ 1 ] package except Exception as e log error LOGMSG ERR FAB ADDON IMPORT format class path e
null
null
null
null
Question: How will a class import from a string path ? Code: def dynamic_class_import(class_path): try: tmp = class_path.split('.') module_path = '.'.join(tmp[0:(-1)]) package = __import__(module_path) return reduce(getattr, tmp[1:], package) except Exception as e: log.error(LOGMSG_ERR_FAB_ADDON_IMPORT.format(class_path, e))
null
null
null
What does the code get ?
def GetGlobalVSMacroEnv(vs_version): env = {} if vs_version.Path(): env['$(VSInstallDir)'] = vs_version.Path() env['$(VCInstallDir)'] = (os.path.join(vs_version.Path(), 'VC') + '\\') dxsdk_dir = _FindDirectXInstallation() env['$(DXSDK_DIR)'] = (dxsdk_dir if dxsdk_dir else '') env['$(WDK_DIR)'] = os.environ.get('WDK_DIR', '') return env
null
null
null
a dict of variables mapping internal vs macro names to their gyp equivalents
codeqa
def Get Global VS Macro Env vs version env {}if vs version Path env['$ VS Install Dir '] vs version Path env['$ VC Install Dir '] os path join vs version Path 'VC' + '\\' dxsdk dir Find Direct X Installation env['$ DXSDK DIR '] dxsdk dir if dxsdk dir else '' env['$ WDK DIR '] os environ get 'WDK DIR' '' return env
null
null
null
null
Question: What does the code get ? Code: def GetGlobalVSMacroEnv(vs_version): env = {} if vs_version.Path(): env['$(VSInstallDir)'] = vs_version.Path() env['$(VCInstallDir)'] = (os.path.join(vs_version.Path(), 'VC') + '\\') dxsdk_dir = _FindDirectXInstallation() env['$(DXSDK_DIR)'] = (dxsdk_dir if dxsdk_dir else '') env['$(WDK_DIR)'] = os.environ.get('WDK_DIR', '') return env
null
null
null
What does the code delete by name ?
def delete_image(gce, name, module): try: gce.ex_delete_image(name) return True except ResourceNotFoundError: return False except GoogleBaseError as e: module.fail_json(msg=str(e), changed=False)
null
null
null
a specific image resource
codeqa
def delete image gce name module try gce ex delete image name return Trueexcept Resource Not Found Error return Falseexcept Google Base Error as e module fail json msg str e changed False
null
null
null
null
Question: What does the code delete by name ? Code: def delete_image(gce, name, module): try: gce.ex_delete_image(name) return True except ResourceNotFoundError: return False except GoogleBaseError as e: module.fail_json(msg=str(e), changed=False)
null
null
null
How does the code delete a specific image resource ?
def delete_image(gce, name, module): try: gce.ex_delete_image(name) return True except ResourceNotFoundError: return False except GoogleBaseError as e: module.fail_json(msg=str(e), changed=False)
null
null
null
by name
codeqa
def delete image gce name module try gce ex delete image name return Trueexcept Resource Not Found Error return Falseexcept Google Base Error as e module fail json msg str e changed False
null
null
null
null
Question: How does the code delete a specific image resource ? Code: def delete_image(gce, name, module): try: gce.ex_delete_image(name) return True except ResourceNotFoundError: return False except GoogleBaseError as e: module.fail_json(msg=str(e), changed=False)
null
null
null
What does the code ask ?
def askyesno(title=None, message=None, **options): s = _show(title, message, QUESTION, YESNO, **options) return (s == YES)
null
null
null
a question
codeqa
def askyesno title None message None **options s show title message QUESTION YESNO **options return s YES
null
null
null
null
Question: What does the code ask ? Code: def askyesno(title=None, message=None, **options): s = _show(title, message, QUESTION, YESNO, **options) return (s == YES)
null
null
null
What does the code monitor ?
def OperationRetriesCriteria(operation_rate, retry_rate): alerts = [] warnings = [] def _ComputeThreshold(x): return (math.ceil(math.sqrt(x)) / 3) if (retry_rate['cluster_total'] > _ComputeThreshold(operation_rate['cluster_total'])): warnings.append(CLUSTER_TOKEN) for (m, v) in operation_rate['machine_data'].iteritems(): if (retry_rate['machine_data'][m] > _ComputeThreshold(v)): warnings.append(m) return (alerts, warnings)
null
null
null
the rate of operation retries on the server
codeqa
def Operation Retries Criteria operation rate retry rate alerts []warnings []def Compute Threshold x return math ceil math sqrt x / 3 if retry rate['cluster total'] > Compute Threshold operation rate['cluster total'] warnings append CLUSTER TOKEN for m v in operation rate['machine data'] iteritems if retry rate['machine data'][m] > Compute Threshold v warnings append m return alerts warnings
null
null
null
null
Question: What does the code monitor ? Code: def OperationRetriesCriteria(operation_rate, retry_rate): alerts = [] warnings = [] def _ComputeThreshold(x): return (math.ceil(math.sqrt(x)) / 3) if (retry_rate['cluster_total'] > _ComputeThreshold(operation_rate['cluster_total'])): warnings.append(CLUSTER_TOKEN) for (m, v) in operation_rate['machine_data'].iteritems(): if (retry_rate['machine_data'][m] > _ComputeThreshold(v)): warnings.append(m) return (alerts, warnings)
null
null
null
When do on each item call ?
def interleave(inter, f, seq): seq = iter(seq) try: f(seq.next()) except StopIteration: pass else: for x in seq: inter() f(x)
null
null
null
in seq
codeqa
def interleave inter f seq seq iter seq try f seq next except Stop Iteration passelse for x in seq inter f x
null
null
null
null
Question: When do on each item call ? Code: def interleave(inter, f, seq): seq = iter(seq) try: f(seq.next()) except StopIteration: pass else: for x in seq: inter() f(x)
null
null
null
When did the specified course use typically ?
def remove_entrance_exam_graders(course_key, user): grading_model = CourseGradingModel.fetch(course_key) graders = grading_model.graders for (i, grader) in enumerate(graders): if (grader['type'] == GRADER_TYPES['ENTRANCE_EXAM']): CourseGradingModel.delete_grader(course_key, i, user)
null
null
null
when adding / removing an entrance exam
codeqa
def remove entrance exam graders course key user grading model Course Grading Model fetch course key graders grading model gradersfor i grader in enumerate graders if grader['type'] GRADER TYPES['ENTRANCE EXAM'] Course Grading Model delete grader course key i user
null
null
null
null
Question: When did the specified course use typically ? Code: def remove_entrance_exam_graders(course_key, user): grading_model = CourseGradingModel.fetch(course_key) graders = grading_model.graders for (i, grader) in enumerate(graders): if (grader['type'] == GRADER_TYPES['ENTRANCE_EXAM']): CourseGradingModel.delete_grader(course_key, i, user)
null
null
null
What do a boto3 client access ?
def get_cloudwatchevents_client(module): try: (region, ec2_url, aws_conn_kwargs) = get_aws_connection_info(module, boto3=True) if (not region): module.fail_json(msg='Region must be specified as a parameter, in EC2_REGION or AWS_REGION environment variables or in boto configuration file') return boto3_conn(module, conn_type='client', resource='events', region=region, endpoint=ec2_url, **aws_conn_kwargs) except boto3.exception.NoAuthHandlerFound as e: module.fail_json(msg=str(e))
null
null
null
cloudwatch events
codeqa
def get cloudwatchevents client module try region ec 2 url aws conn kwargs get aws connection info module boto 3 True if not region module fail json msg ' Regionmustbespecifiedasaparameter in EC 2 REGIO Nor AWS REGIO Nenvironmentvariablesorinbotoconfigurationfile' return boto 3 conn module conn type 'client' resource 'events' region region endpoint ec 2 url **aws conn kwargs except boto 3 exception No Auth Handler Found as e module fail json msg str e
null
null
null
null
Question: What do a boto3 client access ? Code: def get_cloudwatchevents_client(module): try: (region, ec2_url, aws_conn_kwargs) = get_aws_connection_info(module, boto3=True) if (not region): module.fail_json(msg='Region must be specified as a parameter, in EC2_REGION or AWS_REGION environment variables or in boto configuration file') return boto3_conn(module, conn_type='client', resource='events', region=region, endpoint=ec2_url, **aws_conn_kwargs) except boto3.exception.NoAuthHandlerFound as e: module.fail_json(msg=str(e))
null
null
null
When does a list of courses sort ?
def sort_by_announcement(courses): key = (lambda course: course.sorting_score) courses = sorted(courses, key=key) return courses
null
null
null
by their announcement date
codeqa
def sort by announcement courses key lambda course course sorting score courses sorted courses key key return courses
null
null
null
null
Question: When does a list of courses sort ? Code: def sort_by_announcement(courses): key = (lambda course: course.sorting_score) courses = sorted(courses, key=key) return courses
null
null
null
What should it download ?
def test_download_wheel_archive(script, data): wheel_filename = 'colander-0.9.9-py2.py3-none-any.whl' wheel_path = os.path.join(data.find_links, wheel_filename) result = script.pip('install', wheel_path, '-d', '.', '--no-deps', expect_stderr=True) assert ((Path('scratch') / wheel_filename) in result.files_created)
null
null
null
a wheel archive path
codeqa
def test download wheel archive script data wheel filename 'colander- 0 9 9-py 2 py 3 -none-any whl'wheel path os path join data find links wheel filename result script pip 'install' wheel path '-d' ' ' '--no-deps' expect stderr True assert Path 'scratch' / wheel filename in result files created
null
null
null
null
Question: What should it download ? Code: def test_download_wheel_archive(script, data): wheel_filename = 'colander-0.9.9-py2.py3-none-any.whl' wheel_path = os.path.join(data.find_links, wheel_filename) result = script.pip('install', wheel_path, '-d', '.', '--no-deps', expect_stderr=True) assert ((Path('scratch') / wheel_filename) in result.files_created)
null
null
null
What does the code get ?
def getHexagonalGrid(diameter, loopsComplex, maximumComplex, minimumComplex, zigzag): diameter = complex(diameter.real, (math.sqrt(0.75) * diameter.imag)) demiradius = (0.25 * diameter) xRadius = (0.5 * diameter.real) xStart = (minimumComplex.real - demiradius.real) y = (minimumComplex.imag - demiradius.imag) gridPath = [] rowIndex = 0 while (y < maximumComplex.imag): x = xStart if ((rowIndex % 2) == 1): x -= xRadius addGridRow(diameter, gridPath, loopsComplex, maximumComplex, rowIndex, x, y, zigzag) y += diameter.imag rowIndex += 1 return gridPath
null
null
null
hexagonal grid
codeqa
def get Hexagonal Grid diameter loops Complex maximum Complex minimum Complex zigzag diameter complex diameter real math sqrt 0 75 * diameter imag demiradius 0 25 * diameter x Radius 0 5 * diameter real x Start minimum Complex real - demiradius real y minimum Complex imag - demiradius imag grid Path []row Index 0while y < maximum Complex imag x x Startif row Index % 2 1 x - x Radiusadd Grid Row diameter grid Path loops Complex maximum Complex row Index x y zigzag y + diameter imagrow Index + 1return grid Path
null
null
null
null
Question: What does the code get ? Code: def getHexagonalGrid(diameter, loopsComplex, maximumComplex, minimumComplex, zigzag): diameter = complex(diameter.real, (math.sqrt(0.75) * diameter.imag)) demiradius = (0.25 * diameter) xRadius = (0.5 * diameter.real) xStart = (minimumComplex.real - demiradius.real) y = (minimumComplex.imag - demiradius.imag) gridPath = [] rowIndex = 0 while (y < maximumComplex.imag): x = xStart if ((rowIndex % 2) == 1): x -= xRadius addGridRow(diameter, gridPath, loopsComplex, maximumComplex, rowIndex, x, y, zigzag) y += diameter.imag rowIndex += 1 return gridPath
null
null
null
How does it behave ?
def test_sun(): from ..funcs import get_sun northern_summer_solstice = Time(u'2010-6-21') northern_winter_solstice = Time(u'2010-12-21') equinox_1 = Time(u'2010-3-21') equinox_2 = Time(u'2010-9-21') gcrs1 = get_sun(equinox_1) assert (np.abs(gcrs1.dec.deg) < 1) gcrs2 = get_sun(Time([northern_summer_solstice, equinox_2, northern_winter_solstice])) assert np.all((np.abs((gcrs2.dec - ([23.5, 0, (-23.5)] * u.deg))) < (1 * u.deg)))
null
null
null
roughly as it should
codeqa
def test sun from funcs import get sunnorthern summer solstice Time u' 2010 - 6 - 21 ' northern winter solstice Time u' 2010 - 12 - 21 ' equinox 1 Time u' 2010 - 3 - 21 ' equinox 2 Time u' 2010 - 9 - 21 ' gcrs 1 get sun equinox 1 assert np abs gcrs 1 dec deg < 1 gcrs 2 get sun Time [northern summer solstice equinox 2 northern winter solstice] assert np all np abs gcrs 2 dec - [23 5 0 -23 5 ] * u deg < 1 * u deg
null
null
null
null
Question: How does it behave ? Code: def test_sun(): from ..funcs import get_sun northern_summer_solstice = Time(u'2010-6-21') northern_winter_solstice = Time(u'2010-12-21') equinox_1 = Time(u'2010-3-21') equinox_2 = Time(u'2010-9-21') gcrs1 = get_sun(equinox_1) assert (np.abs(gcrs1.dec.deg) < 1) gcrs2 = get_sun(Time([northern_summer_solstice, equinox_2, northern_winter_solstice])) assert np.all((np.abs((gcrs2.dec - ([23.5, 0, (-23.5)] * u.deg))) < (1 * u.deg)))
null
null
null
What does the code ensure ?
def set_container_agent_enabled_on_node(node, enabled): if enabled: d = node.run_script('enable_service', 'flocker-container-agent') else: d = node.run_script('disable_service', 'flocker-container-agent') if (not enabled): d.addCallback((lambda _: node.reboot())) d.addCallback((lambda _: deferLater(reactor, 20, (lambda : None)))) d = d.addCallback((lambda _: verify_socket(node.public_address, 22))) d.addCallback((lambda _: loop_until(reactor, (lambda : is_process_running(node, 'flocker-dataset-agent'))))) d.addCallback((lambda _: node.run_script('disable_service', 'flocker-dataset-agent'))) d.addCallback((lambda _: node.run_script('enable_service', 'flocker-dataset-agent'))) d.addCallback((lambda _: loop_until(reactor, (lambda : is_process_running(node, 'flocker-dataset-agent'))))) d.addCallback((lambda _: None)) return d
null
null
null
the container agent is enabled / disabled as specified
codeqa
def set container agent enabled on node node enabled if enabled d node run script 'enable service' 'flocker-container-agent' else d node run script 'disable service' 'flocker-container-agent' if not enabled d add Callback lambda node reboot d add Callback lambda defer Later reactor 20 lambda None d d add Callback lambda verify socket node public address 22 d add Callback lambda loop until reactor lambda is process running node 'flocker-dataset-agent' d add Callback lambda node run script 'disable service' 'flocker-dataset-agent' d add Callback lambda node run script 'enable service' 'flocker-dataset-agent' d add Callback lambda loop until reactor lambda is process running node 'flocker-dataset-agent' d add Callback lambda None return d
null
null
null
null
Question: What does the code ensure ? Code: def set_container_agent_enabled_on_node(node, enabled): if enabled: d = node.run_script('enable_service', 'flocker-container-agent') else: d = node.run_script('disable_service', 'flocker-container-agent') if (not enabled): d.addCallback((lambda _: node.reboot())) d.addCallback((lambda _: deferLater(reactor, 20, (lambda : None)))) d = d.addCallback((lambda _: verify_socket(node.public_address, 22))) d.addCallback((lambda _: loop_until(reactor, (lambda : is_process_running(node, 'flocker-dataset-agent'))))) d.addCallback((lambda _: node.run_script('disable_service', 'flocker-dataset-agent'))) d.addCallback((lambda _: node.run_script('enable_service', 'flocker-dataset-agent'))) d.addCallback((lambda _: loop_until(reactor, (lambda : is_process_running(node, 'flocker-dataset-agent'))))) d.addCallback((lambda _: None)) return d
null
null
null
How does the code run a series of changes ?
def in_parallel(changes, sleep_when_empty=timedelta(seconds=60)): if all((isinstance(c, NoOp) for c in changes)): sleep = (min((c.sleep for c in changes)) if changes else sleep_when_empty) return NoOp(sleep=sleep) return _InParallel(changes=changes)
null
null
null
in parallel
codeqa
def in parallel changes sleep when empty timedelta seconds 60 if all isinstance c No Op for c in changes sleep min c sleep for c in changes if changes else sleep when empty return No Op sleep sleep return In Parallel changes changes
null
null
null
null
Question: How does the code run a series of changes ? Code: def in_parallel(changes, sleep_when_empty=timedelta(seconds=60)): if all((isinstance(c, NoOp) for c in changes)): sleep = (min((c.sleep for c in changes)) if changes else sleep_when_empty) return NoOp(sleep=sleep) return _InParallel(changes=changes)
null
null
null
What does the code run in parallel ?
def in_parallel(changes, sleep_when_empty=timedelta(seconds=60)): if all((isinstance(c, NoOp) for c in changes)): sleep = (min((c.sleep for c in changes)) if changes else sleep_when_empty) return NoOp(sleep=sleep) return _InParallel(changes=changes)
null
null
null
a series of changes
codeqa
def in parallel changes sleep when empty timedelta seconds 60 if all isinstance c No Op for c in changes sleep min c sleep for c in changes if changes else sleep when empty return No Op sleep sleep return In Parallel changes changes
null
null
null
null
Question: What does the code run in parallel ? Code: def in_parallel(changes, sleep_when_empty=timedelta(seconds=60)): if all((isinstance(c, NoOp) for c in changes)): sleep = (min((c.sleep for c in changes)) if changes else sleep_when_empty) return NoOp(sleep=sleep) return _InParallel(changes=changes)
null
null
null
What does the code resolve into the name of the referenced table ?
def s3_get_foreign_key(field, m2m=True): ftype = str(field.type) multiple = False if (ftype[:9] == 'reference'): key = ftype[10:] elif (m2m and (ftype[:14] == 'list:reference')): key = ftype[15:] multiple = True else: key = current.s3db.virtual_reference(field) if (not key): return (None, None, None) if ('.' in key): (rtablename, key) = key.split('.') else: rtablename = key rtable = current.s3db.table(rtablename) if rtable: key = rtable._id.name else: key = None return (rtablename, key, multiple)
null
null
null
a field type
codeqa
def s3 get foreign key field m2 m True ftype str field type multiple Falseif ftype[ 9] 'reference' key ftype[ 10 ]elif m2 m and ftype[ 14 ] 'list reference' key ftype[ 15 ]multiple Trueelse key current s3 db virtual reference field if not key return None None None if ' ' in key rtablename key key split ' ' else rtablename keyrtable current s3 db table rtablename if rtable key rtable id nameelse key Nonereturn rtablename key multiple
null
null
null
null
Question: What does the code resolve into the name of the referenced table ? Code: def s3_get_foreign_key(field, m2m=True): ftype = str(field.type) multiple = False if (ftype[:9] == 'reference'): key = ftype[10:] elif (m2m and (ftype[:14] == 'list:reference')): key = ftype[15:] multiple = True else: key = current.s3db.virtual_reference(field) if (not key): return (None, None, None) if ('.' in key): (rtablename, key) = key.split('.') else: rtablename = key rtable = current.s3db.table(rtablename) if rtable: key = rtable._id.name else: key = None return (rtablename, key, multiple)
null
null
null
What stored at path in cache ?
def load_stored_item(cache, path, item): return cache.load_parser(path, (item.change_time - 1))
null
null
null
load item
codeqa
def load stored item cache path item return cache load parser path item change time - 1
null
null
null
null
Question: What stored at path in cache ? Code: def load_stored_item(cache, path, item): return cache.load_parser(path, (item.change_time - 1))
null
null
null
Where did load item store ?
def load_stored_item(cache, path, item): return cache.load_parser(path, (item.change_time - 1))
null
null
null
at path in cache
codeqa
def load stored item cache path item return cache load parser path item change time - 1
null
null
null
null
Question: Where did load item store ? Code: def load_stored_item(cache, path, item): return cache.load_parser(path, (item.change_time - 1))
null
null
null
What did the code set ?
def setup_platform(hass, config, add_devices, discovery_info=None): import pwaqi dev = [] station_filter = config.get(CONF_STATIONS) for location_name in config.get(CONF_LOCATIONS): station_ids = pwaqi.findStationCodesByCity(location_name) _LOGGER.info('The following stations were returned: %s', station_ids) for station in station_ids: waqi_sensor = WaqiSensor(WaqiData(station), station) if ((not station_filter) or (waqi_sensor.station_name in station_filter)): dev.append(WaqiSensor(WaqiData(station), station)) add_devices(dev)
null
null
null
the requested world air quality index locations
codeqa
def setup platform hass config add devices discovery info None import pwaqidev []station filter config get CONF STATIONS for location name in config get CONF LOCATIONS station ids pwaqi find Station Codes By City location name LOGGER info ' Thefollowingstationswerereturned %s' station ids for station in station ids waqi sensor Waqi Sensor Waqi Data station station if not station filter or waqi sensor station name in station filter dev append Waqi Sensor Waqi Data station station add devices dev
null
null
null
null
Question: What did the code set ? Code: def setup_platform(hass, config, add_devices, discovery_info=None): import pwaqi dev = [] station_filter = config.get(CONF_STATIONS) for location_name in config.get(CONF_LOCATIONS): station_ids = pwaqi.findStationCodesByCity(location_name) _LOGGER.info('The following stations were returned: %s', station_ids) for station in station_ids: waqi_sensor = WaqiSensor(WaqiData(station), station) if ((not station_filter) or (waqi_sensor.station_name in station_filter)): dev.append(WaqiSensor(WaqiData(station), station)) add_devices(dev)
null
null
null
What does the code get ?
def getPerimeterWidth(elementNode): if (elementNode == None): return 0.72 preferences = skeinforge_craft.getCraftPreferences('carve') layerThickness = skeinforge_craft.getCraftValue('Layer Thickness', preferences) layerThickness = getCascadeFloatWithoutSelf(layerThickness, elementNode, 'layerThickness') perimeterWidthOverThickness = skeinforge_craft.getCraftValue('Perimeter Width over Thickness', preferences) perimeterWidthOverThickness = getCascadeFloatWithoutSelf(perimeterWidthOverThickness, elementNode, 'perimeterWidthOverThickness') return getCascadeFloatWithoutSelf((perimeterWidthOverThickness * layerThickness), elementNode, 'perimeterWidth')
null
null
null
the perimeter width
codeqa
def get Perimeter Width element Node if element Node None return 0 72 preferences skeinforge craft get Craft Preferences 'carve' layer Thickness skeinforge craft get Craft Value ' Layer Thickness' preferences layer Thickness get Cascade Float Without Self layer Thickness element Node 'layer Thickness' perimeter Width Over Thickness skeinforge craft get Craft Value ' Perimeter Widthover Thickness' preferences perimeter Width Over Thickness get Cascade Float Without Self perimeter Width Over Thickness element Node 'perimeter Width Over Thickness' return get Cascade Float Without Self perimeter Width Over Thickness * layer Thickness element Node 'perimeter Width'
null
null
null
null
Question: What does the code get ? Code: def getPerimeterWidth(elementNode): if (elementNode == None): return 0.72 preferences = skeinforge_craft.getCraftPreferences('carve') layerThickness = skeinforge_craft.getCraftValue('Layer Thickness', preferences) layerThickness = getCascadeFloatWithoutSelf(layerThickness, elementNode, 'layerThickness') perimeterWidthOverThickness = skeinforge_craft.getCraftValue('Perimeter Width over Thickness', preferences) perimeterWidthOverThickness = getCascadeFloatWithoutSelf(perimeterWidthOverThickness, elementNode, 'perimeterWidthOverThickness') return getCascadeFloatWithoutSelf((perimeterWidthOverThickness * layerThickness), elementNode, 'perimeterWidth')
null
null
null
What do groups have ?
def _check_group_branches(config, physical_skel): logging.debug('Checking group branches match expectations') for (group, relations) in physical_skel.items(): if ('belongs_to' not in relations): continue parents = relations['belongs_to'] for parent in parents: if (parent in config.keys()): message = 'Group {parent} has a child group {child}, but also has host entries in user configuration. Hosts cannot be sibling with groups.'.format(parent=parent, child=group) raise GroupConflict(message) logging.debug('Group branches ok.') return True
null
null
null
either hosts or child groups
codeqa
def check group branches config physical skel logging debug ' Checkinggroupbranchesmatchexpectations' for group relations in physical skel items if 'belongs to' not in relations continueparents relations['belongs to']for parent in parents if parent in config keys message ' Group{parent}hasachildgroup{child} butalsohashostentriesinuserconfiguration Hostscannotbesiblingwithgroups ' format parent parent child group raise Group Conflict message logging debug ' Groupbranchesok ' return True
null
null
null
null
Question: What do groups have ? Code: def _check_group_branches(config, physical_skel): logging.debug('Checking group branches match expectations') for (group, relations) in physical_skel.items(): if ('belongs_to' not in relations): continue parents = relations['belongs_to'] for parent in parents: if (parent in config.keys()): message = 'Group {parent} has a child group {child}, but also has host entries in user configuration. Hosts cannot be sibling with groups.'.format(parent=parent, child=group) raise GroupConflict(message) logging.debug('Group branches ok.') return True
null
null
null
What have either hosts or child groups ?
def _check_group_branches(config, physical_skel): logging.debug('Checking group branches match expectations') for (group, relations) in physical_skel.items(): if ('belongs_to' not in relations): continue parents = relations['belongs_to'] for parent in parents: if (parent in config.keys()): message = 'Group {parent} has a child group {child}, but also has host entries in user configuration. Hosts cannot be sibling with groups.'.format(parent=parent, child=group) raise GroupConflict(message) logging.debug('Group branches ok.') return True
null
null
null
groups
codeqa
def check group branches config physical skel logging debug ' Checkinggroupbranchesmatchexpectations' for group relations in physical skel items if 'belongs to' not in relations continueparents relations['belongs to']for parent in parents if parent in config keys message ' Group{parent}hasachildgroup{child} butalsohashostentriesinuserconfiguration Hostscannotbesiblingwithgroups ' format parent parent child group raise Group Conflict message logging debug ' Groupbranchesok ' return True
null
null
null
null
Question: What have either hosts or child groups ? Code: def _check_group_branches(config, physical_skel): logging.debug('Checking group branches match expectations') for (group, relations) in physical_skel.items(): if ('belongs_to' not in relations): continue parents = relations['belongs_to'] for parent in parents: if (parent in config.keys()): message = 'Group {parent} has a child group {child}, but also has host entries in user configuration. Hosts cannot be sibling with groups.'.format(parent=parent, child=group) raise GroupConflict(message) logging.debug('Group branches ok.') return True
null
null
null
What does the code add ?
def sdm_add(f, g, O, K): h = dict(f) for (monom, c) in g: if (monom in h): coeff = (h[monom] + c) if (not coeff): del h[monom] else: h[monom] = coeff else: h[monom] = c return sdm_from_dict(h, O)
null
null
null
two module elements f
codeqa
def sdm add f g O K h dict f for monom c in g if monom in h coeff h[monom] + c if not coeff del h[monom]else h[monom] coeffelse h[monom] creturn sdm from dict h O
null
null
null
null
Question: What does the code add ? Code: def sdm_add(f, g, O, K): h = dict(f) for (monom, c) in g: if (monom in h): coeff = (h[monom] + c) if (not coeff): del h[monom] else: h[monom] = coeff else: h[monom] = c return sdm_from_dict(h, O)
null
null
null
What does the code provide ?
def __virtual__(): if _check_zpool(): return 'zpool' return (False, 'Module zpool: zpool not found')
null
null
null
zpool
codeqa
def virtual if check zpool return 'zpool'return False ' Modulezpool zpoolnotfound'
null
null
null
null
Question: What does the code provide ? Code: def __virtual__(): if _check_zpool(): return 'zpool' return (False, 'Module zpool: zpool not found')
null
null
null
What does this function attempt if the given module is actually a package ?
def _matching_loader_thinks_module_is_package(loader, mod_name): if hasattr(loader, 'is_package'): return loader.is_package(mod_name) elif ((loader.__class__.__module__ == '_frozen_importlib') and (loader.__class__.__name__ == 'NamespaceLoader')): return True raise AttributeError(('%s.is_package() method is missing but is required by Flask of PEP 302 import hooks. If you do not use import hooks and you encounter this error please file a bug against Flask.' % loader.__class__.__name__))
null
null
null
to figure out
codeqa
def matching loader thinks module is package loader mod name if hasattr loader 'is package' return loader is package mod name elif loader class module ' frozen importlib' and loader class name ' Namespace Loader' return Trueraise Attribute Error '%s is package methodismissingbutisrequiredby Flaskof PEP 302 importhooks Ifyoudonotuseimporthooksandyouencounterthiserrorpleasefileabugagainst Flask ' % loader class name
null
null
null
null
Question: What does this function attempt if the given module is actually a package ? Code: def _matching_loader_thinks_module_is_package(loader, mod_name): if hasattr(loader, 'is_package'): return loader.is_package(mod_name) elif ((loader.__class__.__module__ == '_frozen_importlib') and (loader.__class__.__name__ == 'NamespaceLoader')): return True raise AttributeError(('%s.is_package() method is missing but is required by Flask of PEP 302 import hooks. If you do not use import hooks and you encounter this error please file a bug against Flask.' % loader.__class__.__name__))
null
null
null
What loaded a module ?
def _matching_loader_thinks_module_is_package(loader, mod_name): if hasattr(loader, 'is_package'): return loader.is_package(mod_name) elif ((loader.__class__.__module__ == '_frozen_importlib') and (loader.__class__.__name__ == 'NamespaceLoader')): return True raise AttributeError(('%s.is_package() method is missing but is required by Flask of PEP 302 import hooks. If you do not use import hooks and you encounter this error please file a bug against Flask.' % loader.__class__.__name__))
null
null
null
the loader
codeqa
def matching loader thinks module is package loader mod name if hasattr loader 'is package' return loader is package mod name elif loader class module ' frozen importlib' and loader class name ' Namespace Loader' return Trueraise Attribute Error '%s is package methodismissingbutisrequiredby Flaskof PEP 302 importhooks Ifyoudonotuseimporthooksandyouencounterthiserrorpleasefileabugagainst Flask ' % loader class name
null
null
null
null
Question: What loaded a module ? Code: def _matching_loader_thinks_module_is_package(loader, mod_name): if hasattr(loader, 'is_package'): return loader.is_package(mod_name) elif ((loader.__class__.__module__ == '_frozen_importlib') and (loader.__class__.__name__ == 'NamespaceLoader')): return True raise AttributeError(('%s.is_package() method is missing but is required by Flask of PEP 302 import hooks. If you do not use import hooks and you encounter this error please file a bug against Flask.' % loader.__class__.__name__))
null
null
null
What did the code give ?
def _matching_loader_thinks_module_is_package(loader, mod_name): if hasattr(loader, 'is_package'): return loader.is_package(mod_name) elif ((loader.__class__.__module__ == '_frozen_importlib') and (loader.__class__.__name__ == 'NamespaceLoader')): return True raise AttributeError(('%s.is_package() method is missing but is required by Flask of PEP 302 import hooks. If you do not use import hooks and you encounter this error please file a bug against Flask.' % loader.__class__.__name__))
null
null
null
the loader that loaded a module and the module
codeqa
def matching loader thinks module is package loader mod name if hasattr loader 'is package' return loader is package mod name elif loader class module ' frozen importlib' and loader class name ' Namespace Loader' return Trueraise Attribute Error '%s is package methodismissingbutisrequiredby Flaskof PEP 302 importhooks Ifyoudonotuseimporthooksandyouencounterthiserrorpleasefileabugagainst Flask ' % loader class name
null
null
null
null
Question: What did the code give ? Code: def _matching_loader_thinks_module_is_package(loader, mod_name): if hasattr(loader, 'is_package'): return loader.is_package(mod_name) elif ((loader.__class__.__module__ == '_frozen_importlib') and (loader.__class__.__name__ == 'NamespaceLoader')): return True raise AttributeError(('%s.is_package() method is missing but is required by Flask of PEP 302 import hooks. If you do not use import hooks and you encounter this error please file a bug against Flask.' % loader.__class__.__name__))
null
null
null
What did the loader load ?
def _matching_loader_thinks_module_is_package(loader, mod_name): if hasattr(loader, 'is_package'): return loader.is_package(mod_name) elif ((loader.__class__.__module__ == '_frozen_importlib') and (loader.__class__.__name__ == 'NamespaceLoader')): return True raise AttributeError(('%s.is_package() method is missing but is required by Flask of PEP 302 import hooks. If you do not use import hooks and you encounter this error please file a bug against Flask.' % loader.__class__.__name__))
null
null
null
a module
codeqa
def matching loader thinks module is package loader mod name if hasattr loader 'is package' return loader is package mod name elif loader class module ' frozen importlib' and loader class name ' Namespace Loader' return Trueraise Attribute Error '%s is package methodismissingbutisrequiredby Flaskof PEP 302 importhooks Ifyoudonotuseimporthooksandyouencounterthiserrorpleasefileabugagainst Flask ' % loader class name
null
null
null
null
Question: What did the loader load ? Code: def _matching_loader_thinks_module_is_package(loader, mod_name): if hasattr(loader, 'is_package'): return loader.is_package(mod_name) elif ((loader.__class__.__module__ == '_frozen_importlib') and (loader.__class__.__name__ == 'NamespaceLoader')): return True raise AttributeError(('%s.is_package() method is missing but is required by Flask of PEP 302 import hooks. If you do not use import hooks and you encounter this error please file a bug against Flask.' % loader.__class__.__name__))
null
null
null
For what purpose does no more reference to it be ?
def update_chain(graph, loc, du, ud): ins = graph.get_ins_from_loc(loc) for var in ins.get_used_vars(): for def_loc in set(ud[(var, loc)]): du[(var, def_loc)].remove(loc) ud[(var, loc)].remove(def_loc) if (not ud.get((var, loc))): ud.pop((var, loc)) if ((def_loc >= 0) and (not du[(var, def_loc)])): du.pop((var, def_loc)) def_ins = graph.get_ins_from_loc(def_loc) if def_ins.is_call(): def_ins.remove_defined_var() elif def_ins.has_side_effect(): continue else: update_chain(graph, def_loc, du, ud) graph.remove_ins(def_loc)
null
null
null
so that we can remove it
codeqa
def update chain graph loc du ud ins graph get ins from loc loc for var in ins get used vars for def loc in set ud[ var loc ] du[ var def loc ] remove loc ud[ var loc ] remove def loc if not ud get var loc ud pop var loc if def loc > 0 and not du[ var def loc ] du pop var def loc def ins graph get ins from loc def loc if def ins is call def ins remove defined var elif def ins has side effect continueelse update chain graph def loc du ud graph remove ins def loc
null
null
null
null
Question: For what purpose does no more reference to it be ? Code: def update_chain(graph, loc, du, ud): ins = graph.get_ins_from_loc(loc) for var in ins.get_used_vars(): for def_loc in set(ud[(var, loc)]): du[(var, def_loc)].remove(loc) ud[(var, loc)].remove(def_loc) if (not ud.get((var, loc))): ud.pop((var, loc)) if ((def_loc >= 0) and (not du[(var, def_loc)])): du.pop((var, def_loc)) def_ins = graph.get_ins_from_loc(def_loc) if def_ins.is_call(): def_ins.remove_defined_var() elif def_ins.has_side_effect(): continue else: update_chain(graph, def_loc, du, ud) graph.remove_ins(def_loc)
null
null
null
Does the code quoting do anything ?
def no_quote(s): return s
null
null
null
No
codeqa
def no quote s return s
null
null
null
null
Question: Does the code quoting do anything ? Code: def no_quote(s): return s
null
null
null
What does the code create ?
def list_interfaces(call=None, kwargs=None): global netconn if (not netconn): netconn = get_conn(NetworkManagementClient) if (kwargs is None): kwargs = {} if (kwargs.get('resource_group') is None): kwargs['resource_group'] = config.get_cloud_config_value('resource_group', {}, __opts__, search_global=True, default=config.get_cloud_config_value('group', {}, __opts__, search_global=True)) region = get_location() bank = 'cloud/metadata/azurearm/{0}'.format(region) interfaces = cache.cache(bank, 'network_interfaces', netconn.network_interfaces.list, loop_fun=make_safe, expire=config.get_cloud_config_value('expire_interface_cache', get_configured_provider(), __opts__, search_global=False, default=86400), resource_group_name=kwargs['resource_group']) ret = {} for interface in interfaces: ret[interface['name']] = interface return ret
null
null
null
a network interface
codeqa
def list interfaces call None kwargs None global netconnif not netconn netconn get conn Network Management Client if kwargs is None kwargs {}if kwargs get 'resource group' is None kwargs['resource group'] config get cloud config value 'resource group' {} opts search global True default config get cloud config value 'group' {} opts search global True region get location bank 'cloud/metadata/azurearm/{ 0 }' format region interfaces cache cache bank 'network interfaces' netconn network interfaces list loop fun make safe expire config get cloud config value 'expire interface cache' get configured provider opts search global False default 86400 resource group name kwargs['resource group'] ret {}for interface in interfaces ret[interface['name']] interfacereturn ret
null
null
null
null
Question: What does the code create ? Code: def list_interfaces(call=None, kwargs=None): global netconn if (not netconn): netconn = get_conn(NetworkManagementClient) if (kwargs is None): kwargs = {} if (kwargs.get('resource_group') is None): kwargs['resource_group'] = config.get_cloud_config_value('resource_group', {}, __opts__, search_global=True, default=config.get_cloud_config_value('group', {}, __opts__, search_global=True)) region = get_location() bank = 'cloud/metadata/azurearm/{0}'.format(region) interfaces = cache.cache(bank, 'network_interfaces', netconn.network_interfaces.list, loop_fun=make_safe, expire=config.get_cloud_config_value('expire_interface_cache', get_configured_provider(), __opts__, search_global=False, default=86400), resource_group_name=kwargs['resource_group']) ret = {} for interface in interfaces: ret[interface['name']] = interface return ret
null
null
null
What does the code send to the viewfinder auth service ?
def _GenerateAccessToken(action, tester, device_dict, auth_info_dict, user_cookie=None, use_short_token=True): version = (message.MAX_SUPPORTED_MESSAGE_VERSION if use_short_token else message.Message.SUPPRESS_AUTH_NAME) url = tester.GetUrl(('/%s/viewfinder' % action)) request_dict = auth_test._CreateRegisterRequest(device_dict, auth_info_dict, version=version) response = auth_test._SendAuthRequest(tester, url, 'POST', user_cookie=user_cookie, request_dict=request_dict) return json.loads(response.body)
null
null
null
a request
codeqa
def Generate Access Token action tester device dict auth info dict user cookie None use short token True version message MAX SUPPORTED MESSAGE VERSION if use short token else message Message SUPPRESS AUTH NAME url tester Get Url '/%s/viewfinder' % action request dict auth test Create Register Request device dict auth info dict version version response auth test Send Auth Request tester url 'POST' user cookie user cookie request dict request dict return json loads response body
null
null
null
null
Question: What does the code send to the viewfinder auth service ? Code: def _GenerateAccessToken(action, tester, device_dict, auth_info_dict, user_cookie=None, use_short_token=True): version = (message.MAX_SUPPORTED_MESSAGE_VERSION if use_short_token else message.Message.SUPPRESS_AUTH_NAME) url = tester.GetUrl(('/%s/viewfinder' % action)) request_dict = auth_test._CreateRegisterRequest(device_dict, auth_info_dict, version=version) response = auth_test._SendAuthRequest(tester, url, 'POST', user_cookie=user_cookie, request_dict=request_dict) return json.loads(response.body)
null
null
null
What d the code finds ?
def obtain_lock_id_to_hog(): for id in board_ids(): if _obtain_lock(id): return id return (-1)
null
null
null
a free i d
codeqa
def obtain lock id to hog for id in board ids if obtain lock id return idreturn -1
null
null
null
null
Question: What d the code finds ? Code: def obtain_lock_id_to_hog(): for id in board_ids(): if _obtain_lock(id): return id return (-1)
null
null
null
What do directory contain ?
def filter_pathdir(val): return os.path.dirname((val or u''))
null
null
null
the given path
codeqa
def filter pathdir val return os path dirname val or u''
null
null
null
null
Question: What do directory contain ? Code: def filter_pathdir(val): return os.path.dirname((val or u''))
null
null
null
What is containing the given path ?
def filter_pathdir(val): return os.path.dirname((val or u''))
null
null
null
directory
codeqa
def filter pathdir val return os path dirname val or u''
null
null
null
null
Question: What is containing the given path ? Code: def filter_pathdir(val): return os.path.dirname((val or u''))
null
null
null
What is making a build for certain push ?
def ci_skip(registry, xml_parent, data): rpobj = XML.SubElement(xml_parent, 'ruby-proxy-object') robj = XML.SubElement(rpobj, 'ruby-object', attrib={'pluginid': 'ci-skip', 'ruby-class': 'Jenkins::Tasks::BuildWrapperProxy'}) pluginid = XML.SubElement(robj, 'pluginid', {'pluginid': 'ci-skip', 'ruby-class': 'String'}) pluginid.text = 'ci-skip' obj = XML.SubElement(robj, 'object', {'ruby-class': 'CiSkipWrapper', 'pluginid': 'ci-skip'}) XML.SubElement(obj, 'ci__skip', {'pluginid': 'ci-skip', 'ruby-class': 'NilClass'})
null
null
null
ci
codeqa
def ci skip registry xml parent data rpobj XML Sub Element xml parent 'ruby-proxy-object' robj XML Sub Element rpobj 'ruby-object' attrib {'pluginid' 'ci-skip' 'ruby-class' ' Jenkins Tasks Build Wrapper Proxy'} pluginid XML Sub Element robj 'pluginid' {'pluginid' 'ci-skip' 'ruby-class' ' String'} pluginid text 'ci-skip'obj XML Sub Element robj 'object' {'ruby-class' ' Ci Skip Wrapper' 'pluginid' 'ci-skip'} XML Sub Element obj 'ci skip' {'pluginid' 'ci-skip' 'ruby-class' ' Nil Class'}
null
null
null
null
Question: What is making a build for certain push ? Code: def ci_skip(registry, xml_parent, data): rpobj = XML.SubElement(xml_parent, 'ruby-proxy-object') robj = XML.SubElement(rpobj, 'ruby-object', attrib={'pluginid': 'ci-skip', 'ruby-class': 'Jenkins::Tasks::BuildWrapperProxy'}) pluginid = XML.SubElement(robj, 'pluginid', {'pluginid': 'ci-skip', 'ruby-class': 'String'}) pluginid.text = 'ci-skip' obj = XML.SubElement(robj, 'object', {'ruby-class': 'CiSkipWrapper', 'pluginid': 'ci-skip'}) XML.SubElement(obj, 'ci__skip', {'pluginid': 'ci-skip', 'ruby-class': 'NilClass'})
null
null
null
How did the intermediate distribution define ?
def neg_sampling(W_list, b_list, nsamples, beta=1.0, pa_bias=None, marginalize_odd=True, theano_rng=None): depth = len(b_list) new_nsamples = [nsamples[i] for i in xrange(depth)] _sample_even_odd(W_list, b_list, new_nsamples, beta, odd=marginalize_odd) _activation_even_odd(W_list, b_list, new_nsamples, beta, odd=(not marginalize_odd)) new_nsamples[(not marginalize_odd)] += (pa_bias * (1.0 - beta)) for i in xrange((not marginalize_odd), depth, 2): new_nsamples[i] = T.nnet.sigmoid(new_nsamples[i]) new_nsamples[i] = theano_rng.binomial(size=nsamples[i].get_value().shape, n=1, p=new_nsamples[i], dtype=floatX) return new_nsamples
null
null
null
at inverse temperature beta
codeqa
def neg sampling W list b list nsamples beta 1 0 pa bias None marginalize odd True theano rng None depth len b list new nsamples [nsamples[i] for i in xrange depth ] sample even odd W list b list new nsamples beta odd marginalize odd activation even odd W list b list new nsamples beta odd not marginalize odd new nsamples[ not marginalize odd ] + pa bias * 1 0 - beta for i in xrange not marginalize odd depth 2 new nsamples[i] T nnet sigmoid new nsamples[i] new nsamples[i] theano rng binomial size nsamples[i] get value shape n 1 p new nsamples[i] dtype float X return new nsamples
null
null
null
null
Question: How did the intermediate distribution define ? Code: def neg_sampling(W_list, b_list, nsamples, beta=1.0, pa_bias=None, marginalize_odd=True, theano_rng=None): depth = len(b_list) new_nsamples = [nsamples[i] for i in xrange(depth)] _sample_even_odd(W_list, b_list, new_nsamples, beta, odd=marginalize_odd) _activation_even_odd(W_list, b_list, new_nsamples, beta, odd=(not marginalize_odd)) new_nsamples[(not marginalize_odd)] += (pa_bias * (1.0 - beta)) for i in xrange((not marginalize_odd), depth, 2): new_nsamples[i] = T.nnet.sigmoid(new_nsamples[i]) new_nsamples[i] = theano_rng.binomial(size=nsamples[i].get_value().shape, n=1, p=new_nsamples[i], dtype=floatX) return new_nsamples
null
null
null
What does the code generate ?
def neg_sampling(W_list, b_list, nsamples, beta=1.0, pa_bias=None, marginalize_odd=True, theano_rng=None): depth = len(b_list) new_nsamples = [nsamples[i] for i in xrange(depth)] _sample_even_odd(W_list, b_list, new_nsamples, beta, odd=marginalize_odd) _activation_even_odd(W_list, b_list, new_nsamples, beta, odd=(not marginalize_odd)) new_nsamples[(not marginalize_odd)] += (pa_bias * (1.0 - beta)) for i in xrange((not marginalize_odd), depth, 2): new_nsamples[i] = T.nnet.sigmoid(new_nsamples[i]) new_nsamples[i] = theano_rng.binomial(size=nsamples[i].get_value().shape, n=1, p=new_nsamples[i], dtype=floatX) return new_nsamples
null
null
null
a sample from the intermediate distribution defined at inverse temperature beta
codeqa
def neg sampling W list b list nsamples beta 1 0 pa bias None marginalize odd True theano rng None depth len b list new nsamples [nsamples[i] for i in xrange depth ] sample even odd W list b list new nsamples beta odd marginalize odd activation even odd W list b list new nsamples beta odd not marginalize odd new nsamples[ not marginalize odd ] + pa bias * 1 0 - beta for i in xrange not marginalize odd depth 2 new nsamples[i] T nnet sigmoid new nsamples[i] new nsamples[i] theano rng binomial size nsamples[i] get value shape n 1 p new nsamples[i] dtype float X return new nsamples
null
null
null
null
Question: What does the code generate ? Code: def neg_sampling(W_list, b_list, nsamples, beta=1.0, pa_bias=None, marginalize_odd=True, theano_rng=None): depth = len(b_list) new_nsamples = [nsamples[i] for i in xrange(depth)] _sample_even_odd(W_list, b_list, new_nsamples, beta, odd=marginalize_odd) _activation_even_odd(W_list, b_list, new_nsamples, beta, odd=(not marginalize_odd)) new_nsamples[(not marginalize_odd)] += (pa_bias * (1.0 - beta)) for i in xrange((not marginalize_odd), depth, 2): new_nsamples[i] = T.nnet.sigmoid(new_nsamples[i]) new_nsamples[i] = theano_rng.binomial(size=nsamples[i].get_value().shape, n=1, p=new_nsamples[i], dtype=floatX) return new_nsamples
null
null
null
What is describing specific group_type ?
@require_context def group_types_get_by_name_or_id(context, group_type_list): req_group_types = [] for grp_t in group_type_list: if (not uuidutils.is_uuid_like(grp_t)): grp_type = _group_type_get_by_name(context, grp_t) else: grp_type = _group_type_get(context, grp_t) req_group_types.append(grp_type) return req_group_types
null
null
null
a dict
codeqa
@require contextdef group types get by name or id context group type list req group types []for grp t in group type list if not uuidutils is uuid like grp t grp type group type get by name context grp t else grp type group type get context grp t req group types append grp type return req group types
null
null
null
null
Question: What is describing specific group_type ? Code: @require_context def group_types_get_by_name_or_id(context, group_type_list): req_group_types = [] for grp_t in group_type_list: if (not uuidutils.is_uuid_like(grp_t)): grp_type = _group_type_get_by_name(context, grp_t) else: grp_type = _group_type_get(context, grp_t) req_group_types.append(grp_type) return req_group_types
null
null
null
How does review requests close ?
@require_POST def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None, hooks_uuid=None): repository = get_repository_for_hook(repository_id, hosting_service_id, local_site_name, hooks_uuid) try: payload = json.loads(request.body) except ValueError as e: logging.error(u'The payload is not in JSON format: %s', e, exc_info=1) return HttpResponseBadRequest(u'Invalid payload format') server_url = get_server_url(request=request) review_request_id_to_commits_map = close_review_requests(payload, server_url) if review_request_id_to_commits_map: close_all_review_requests(review_request_id_to_commits_map, local_site_name, repository, hosting_service_id) return HttpResponse()
null
null
null
as submitted automatically after a push
codeqa
@require POS Tdef post receive hook close submitted request local site name None repository id None hosting service id None hooks uuid None repository get repository for hook repository id hosting service id local site name hooks uuid try payload json loads request body except Value Error as e logging error u' Thepayloadisnotin JSO Nformat %s' e exc info 1 return Http Response Bad Request u' Invalidpayloadformat' server url get server url request request review request id to commits map close review requests payload server url if review request id to commits map close all review requests review request id to commits map local site name repository hosting service id return Http Response
null
null
null
null
Question: How does review requests close ? Code: @require_POST def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None, hooks_uuid=None): repository = get_repository_for_hook(repository_id, hosting_service_id, local_site_name, hooks_uuid) try: payload = json.loads(request.body) except ValueError as e: logging.error(u'The payload is not in JSON format: %s', e, exc_info=1) return HttpResponseBadRequest(u'Invalid payload format') server_url = get_server_url(request=request) review_request_id_to_commits_map = close_review_requests(payload, server_url) if review_request_id_to_commits_map: close_all_review_requests(review_request_id_to_commits_map, local_site_name, repository, hosting_service_id) return HttpResponse()
null
null
null
What should object type comparisons use always ?
def comparison_type(logical_line, noqa): match = COMPARE_TYPE_REGEX.search(logical_line) if (match and (not noqa)): inst = match.group(1) if (inst and isidentifier(inst) and (inst not in SINGLETONS)): return (yield (match.start(), "E721 do not compare types, use 'isinstance()'"))
null
null
null
isinstance
codeqa
def comparison type logical line noqa match COMPARE TYPE REGEX search logical line if match and not noqa inst match group 1 if inst and isidentifier inst and inst not in SINGLETONS return yield match start "E 721 donotcomparetypes use'isinstance '"
null
null
null
null
Question: What should object type comparisons use always ? Code: def comparison_type(logical_line, noqa): match = COMPARE_TYPE_REGEX.search(logical_line) if (match and (not noqa)): inst = match.group(1) if (inst and isidentifier(inst) and (inst not in SINGLETONS)): return (yield (match.start(), "E721 do not compare types, use 'isinstance()'"))
null
null
null
What does the code add to the flavor access list ?
@require_admin_context def instance_type_access_add(context, flavor_id, project_id): session = get_session() with session.begin(): instance_type_ref = instance_type_get_by_flavor_id(context, flavor_id, session=session) instance_type_id = instance_type_ref['id'] access_ref = _instance_type_access_query(context, session=session).filter_by(instance_type_id=instance_type_id).filter_by(project_id=project_id).first() if access_ref: raise exception.FlavorAccessExists(flavor_id=flavor_id, project_id=project_id) access_ref = models.InstanceTypeProjects() access_ref.update({'instance_type_id': instance_type_id, 'project_id': project_id}) access_ref.save(session=session) return access_ref
null
null
null
given tenant
codeqa
@require admin contextdef instance type access add context flavor id project id session get session with session begin instance type ref instance type get by flavor id context flavor id session session instance type id instance type ref['id']access ref instance type access query context session session filter by instance type id instance type id filter by project id project id first if access ref raise exception Flavor Access Exists flavor id flavor id project id project id access ref models Instance Type Projects access ref update {'instance type id' instance type id 'project id' project id} access ref save session session return access ref
null
null
null
null
Question: What does the code add to the flavor access list ? Code: @require_admin_context def instance_type_access_add(context, flavor_id, project_id): session = get_session() with session.begin(): instance_type_ref = instance_type_get_by_flavor_id(context, flavor_id, session=session) instance_type_id = instance_type_ref['id'] access_ref = _instance_type_access_query(context, session=session).filter_by(instance_type_id=instance_type_id).filter_by(project_id=project_id).first() if access_ref: raise exception.FlavorAccessExists(flavor_id=flavor_id, project_id=project_id) access_ref = models.InstanceTypeProjects() access_ref.update({'instance_type_id': instance_type_id, 'project_id': project_id}) access_ref.save(session=session) return access_ref
null
null
null
What does the code get ?
def equatePolar(point, returnValue): equateCylindrical(point, returnValue)
null
null
null
equation for polar
codeqa
def equate Polar point return Value equate Cylindrical point return Value
null
null
null
null
Question: What does the code get ? Code: def equatePolar(point, returnValue): equateCylindrical(point, returnValue)
null
null
null
How does the first item return ?
def first(iterable): return next(iter(iterable))
null
null
null
by iterating over an iterable object
codeqa
def first iterable return next iter iterable
null
null
null
null
Question: How does the first item return ? Code: def first(iterable): return next(iter(iterable))
null
null
null
What does the code save ?
def save_resized_image(image_file, width_, height_, basewidth, aspect, height_size, upload_path, ext='jpg', remove_after_upload=False): filename = '{filename}.{ext}'.format(filename=time.time(), ext=ext) img = Image.open(image_file) if (aspect == 'on'): width_percent = (basewidth / float(img.size[0])) height_size = int((float(img.size[1]) * float(width_percent))) img = img.resize((basewidth, height_size), PIL.Image.ANTIALIAS) img.save(image_file) file = UploadedFile(file_path=image_file, filename=filename) if remove_after_upload: os.remove(image_file) return upload(file, upload_path)
null
null
null
the resized version of the background image
codeqa
def save resized image image file width height basewidth aspect height size upload path ext 'jpg' remove after upload False filename '{filename} {ext}' format filename time time ext ext img Image open image file if aspect 'on' width percent basewidth / float img size[ 0 ] height size int float img size[ 1 ] * float width percent img img resize basewidth height size PIL Image ANTIALIAS img save image file file Uploaded File file path image file filename filename if remove after upload os remove image file return upload file upload path
null
null
null
null
Question: What does the code save ? Code: def save_resized_image(image_file, width_, height_, basewidth, aspect, height_size, upload_path, ext='jpg', remove_after_upload=False): filename = '{filename}.{ext}'.format(filename=time.time(), ext=ext) img = Image.open(image_file) if (aspect == 'on'): width_percent = (basewidth / float(img.size[0])) height_size = int((float(img.size[1]) * float(width_percent))) img = img.resize((basewidth, height_size), PIL.Image.ANTIALIAS) img.save(image_file) file = UploadedFile(file_path=image_file, filename=filename) if remove_after_upload: os.remove(image_file) return upload(file, upload_path)
null
null
null
What did the code rename ?
def call_rename(*args, **kwargs): dev_id = _get_devices(kwargs) if (len(dev_id) > 1): raise CommandExecutionError('Only one device can be renamed at a time') if ('title' not in kwargs): raise CommandExecutionError('Title is missing') return _set(dev_id[0], {'name': kwargs['title']}, method='')
null
null
null
a device
codeqa
def call rename *args **kwargs dev id get devices kwargs if len dev id > 1 raise Command Execution Error ' Onlyonedevicecanberenamedatatime' if 'title' not in kwargs raise Command Execution Error ' Titleismissing' return set dev id[ 0 ] {'name' kwargs['title']} method ''
null
null
null
null
Question: What did the code rename ? Code: def call_rename(*args, **kwargs): dev_id = _get_devices(kwargs) if (len(dev_id) > 1): raise CommandExecutionError('Only one device can be renamed at a time') if ('title' not in kwargs): raise CommandExecutionError('Title is missing') return _set(dev_id[0], {'name': kwargs['title']}, method='')
null
null
null
What does the code get ?
def _get_service(name): services = _available_services() name = name.lower() if (name in services): return services[name] for service in six.itervalues(services): if (service['file_path'].lower() == name): return service (basename, ext) = os.path.splitext(service['file_name']) if (basename.lower() == name): return service raise CommandExecutionError('Service not found: {0}'.format(name))
null
null
null
information about a service
codeqa
def get service name services available services name name lower if name in services return services[name]for service in six itervalues services if service['file path'] lower name return service basename ext os path splitext service['file name'] if basename lower name return serviceraise Command Execution Error ' Servicenotfound {0 }' format name
null
null
null
null
Question: What does the code get ? Code: def _get_service(name): services = _available_services() name = name.lower() if (name in services): return services[name] for service in six.itervalues(services): if (service['file_path'].lower() == name): return service (basename, ext) = os.path.splitext(service['file_name']) if (basename.lower() == name): return service raise CommandExecutionError('Service not found: {0}'.format(name))
null
null
null
What does helper handle transparently ?
def decode_json(json_string): return json.loads(unicodehelper.decode(json_string))
null
null
null
bom encoding
codeqa
def decode json json string return json loads unicodehelper decode json string
null
null
null
null
Question: What does helper handle transparently ? Code: def decode_json(json_string): return json.loads(unicodehelper.decode(json_string))
null
null
null
What does the code get by prefix ?
def getStrokeRadiusByPrefix(prefix, xmlElement): strokeRadius = getFloatByPrefixBeginEnd((prefix + 'strokeRadius'), (prefix + 'strokeWidth'), 1.0, xmlElement) return getFloatByPrefixBeginEnd((prefix + 'radius'), (prefix + 'diameter'), strokeRadius, xmlElement)
null
null
null
strokeradius
codeqa
def get Stroke Radius By Prefix prefix xml Element stroke Radius get Float By Prefix Begin End prefix + 'stroke Radius' prefix + 'stroke Width' 1 0 xml Element return get Float By Prefix Begin End prefix + 'radius' prefix + 'diameter' stroke Radius xml Element
null
null
null
null
Question: What does the code get by prefix ? Code: def getStrokeRadiusByPrefix(prefix, xmlElement): strokeRadius = getFloatByPrefixBeginEnd((prefix + 'strokeRadius'), (prefix + 'strokeWidth'), 1.0, xmlElement) return getFloatByPrefixBeginEnd((prefix + 'radius'), (prefix + 'diameter'), strokeRadius, xmlElement)
null
null
null
When did modules load ?
def lsmod(): ret = [] for line in __salt__['cmd.run']('kldstat').splitlines(): comps = line.split() if (not (len(comps) > 2)): continue if (comps[0] == 'Id'): continue if (comps[4] == 'kernel'): continue ret.append({'module': comps[4][:(-3)], 'size': comps[3], 'depcount': comps[1]}) return ret
null
null
null
currently
codeqa
def lsmod ret []for line in salt ['cmd run'] 'kldstat' splitlines comps line split if not len comps > 2 continueif comps[ 0 ] ' Id' continueif comps[ 4 ] 'kernel' continueret append {'module' comps[ 4 ][ -3 ] 'size' comps[ 3 ] 'depcount' comps[ 1 ]} return ret
null
null
null
null
Question: When did modules load ? Code: def lsmod(): ret = [] for line in __salt__['cmd.run']('kldstat').splitlines(): comps = line.split() if (not (len(comps) > 2)): continue if (comps[0] == 'Id'): continue if (comps[4] == 'kernel'): continue ret.append({'module': comps[4][:(-3)], 'size': comps[3], 'depcount': comps[1]}) return ret
null
null
null
What does the code get ?
def metadef_resource_type_delete(context, resource_type_name, session=None): session = (session or get_session()) return metadef_resource_type_api.delete(context, resource_type_name, session)
null
null
null
a resource_type
codeqa
def metadef resource type delete context resource type name session None session session or get session return metadef resource type api delete context resource type name session
null
null
null
null
Question: What does the code get ? Code: def metadef_resource_type_delete(context, resource_type_name, session=None): session = (session or get_session()) return metadef_resource_type_api.delete(context, resource_type_name, session)
null
null
null
What found inside ?
def names_from_file(filename): with io.open(filename, 'rt', encoding='utf8') as names_file: for name in filter_koan_names(names_file): (yield name) return
null
null
null
testcases
codeqa
def names from file filename with io open filename 'rt' encoding 'utf 8 ' as names file for name in filter koan names names file yield name return
null
null
null
null
Question: What found inside ? Code: def names_from_file(filename): with io.open(filename, 'rt', encoding='utf8') as names_file: for name in filter_koan_names(names_file): (yield name) return
null
null
null
When do time happen ?
def is_soon(dt, window): soon = (utcnow() + datetime.timedelta(seconds=window)) return (normalize_time(dt) <= soon)
null
null
null
in the next window seconds
codeqa
def is soon dt window soon utcnow + datetime timedelta seconds window return normalize time dt < soon
null
null
null
null
Question: When do time happen ? Code: def is_soon(dt, window): soon = (utcnow() + datetime.timedelta(seconds=window)) return (normalize_time(dt) <= soon)
null
null
null
What does the code compute ?
def compute_mul(tree): (neg, inputs) = tree if (inputs is None): raise AssertionError('Function `compute_mul` found a missing leaf, did you forget to call `simplify_mul` on the tree first?') elif isinstance(inputs, list): rval = tensor.mul(*list(map(compute_mul, inputs))) else: rval = inputs if neg: rval = (- rval) return rval
null
null
null
the variable that is the output of a multiplication tree
codeqa
def compute mul tree neg inputs treeif inputs is None raise Assertion Error ' Function`compute mul`foundamissingleaf didyouforgettocall`simplify mul`onthetreefirst?' elif isinstance inputs list rval tensor mul *list map compute mul inputs else rval inputsif neg rval - rval return rval
null
null
null
null
Question: What does the code compute ? Code: def compute_mul(tree): (neg, inputs) = tree if (inputs is None): raise AssertionError('Function `compute_mul` found a missing leaf, did you forget to call `simplify_mul` on the tree first?') elif isinstance(inputs, list): rval = tensor.mul(*list(map(compute_mul, inputs))) else: rval = inputs if neg: rval = (- rval) return rval