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
The code apply the date and locale filters to the which organization query ?
def _apply_filters(query, start, end, locale=None, product=None): if (start is None): start = (date.today() - timedelta(days=90)) query = query.filter(created__gte=start) if end: query = query.filter(created__lt=end) if locale: query = query.filter(locale=locale) if product: if isinstance(product, Product): product = product.slug query = query.filter(product=product) return query
null
null
null
eu
codeqa
def apply filters query start end locale None product None if start is None start date today - timedelta days 90 query query filter created gte start if end query query filter created lt end if locale query query filter locale locale if product if isinstance product Product product product slugquery query filter product product return query
null
null
null
null
Question: The code apply the date and locale filters to the which organization query ? Code: def _apply_filters(query, start, end, locale=None, product=None): if (start is None): start = (date.today() - timedelta(days=90)) query = query.filter(created__gte=start) if end: query = query.filter(created__lt=end) if locale: query = query.filter(locale=locale) if product: if isinstance(product, Product): product = product.slug query = query.filter(product=product) return query
null
null
null
For what purpose do the unsigned archive download ?
def download_unsigned(request, uuid, **kwargs): extension = get_object_or_404(Extension.objects.without_deleted(), uuid=uuid) version = get_object_or_404(extension.versions.without_deleted(), pk=kwargs['version_id']) def is_author(): return extension.authors.filter(pk=request.user.pk).exists() def is_reviewer(): return action_allowed(request, 'ContentTools', 'AddonReview') if (request.user.is_authenticated() and (is_author() or is_reviewer())): log.info(('Downloading unsigned add-on: %s version %s from %s' % (extension.pk, version.pk, version.file_path))) return _download(request, extension, version, version.file_path, public=False) else: raise PermissionDenied
null
null
null
for a given extension / version
codeqa
def download unsigned request uuid **kwargs extension get object or 404 Extension objects without deleted uuid uuid version get object or 404 extension versions without deleted pk kwargs['version id'] def is author return extension authors filter pk request user pk exists def is reviewer return action allowed request ' Content Tools' ' Addon Review' if request user is authenticated and is author or is reviewer log info ' Downloadingunsignedadd-on %sversion%sfrom%s' % extension pk version pk version file path return download request extension version version file path public False else raise Permission Denied
null
null
null
null
Question: For what purpose do the unsigned archive download ? Code: def download_unsigned(request, uuid, **kwargs): extension = get_object_or_404(Extension.objects.without_deleted(), uuid=uuid) version = get_object_or_404(extension.versions.without_deleted(), pk=kwargs['version_id']) def is_author(): return extension.authors.filter(pk=request.user.pk).exists() def is_reviewer(): return action_allowed(request, 'ContentTools', 'AddonReview') if (request.user.is_authenticated() and (is_author() or is_reviewer())): log.info(('Downloading unsigned add-on: %s version %s from %s' % (extension.pk, version.pk, version.file_path))) return _download(request, extension, version, version.file_path, public=False) else: raise PermissionDenied
null
null
null
How do the rows of features cluster ?
def hcluster(features, distfcn=L2dist): distances = {} node = [ClusterLeafNode(array(f), id=i) for (i, f) in enumerate(features)] while (len(node) > 1): closest = float('Inf') for (ni, nj) in combinations(node, 2): if ((ni, nj) not in distances): distances[(ni, nj)] = distfcn(ni.vec, nj.vec) d = distances[(ni, nj)] if (d < closest): closest = d lowestpair = (ni, nj) (ni, nj) = lowestpair new_vec = ((ni.vec + nj.vec) / 2.0) new_node = ClusterNode(new_vec, left=ni, right=nj, distance=closest) node.remove(ni) node.remove(nj) node.append(new_node) return node[0]
null
null
null
using hierarchical clustering
codeqa
def hcluster features distfcn L2 dist distances {}node [ Cluster Leaf Node array f id i for i f in enumerate features ]while len node > 1 closest float ' Inf' for ni nj in combinations node 2 if ni nj not in distances distances[ ni nj ] distfcn ni vec nj vec d distances[ ni nj ]if d < closest closest dlowestpair ni nj ni nj lowestpairnew vec ni vec + nj vec / 2 0 new node Cluster Node new vec left ni right nj distance closest node remove ni node remove nj node append new node return node[ 0 ]
null
null
null
null
Question: How do the rows of features cluster ? Code: def hcluster(features, distfcn=L2dist): distances = {} node = [ClusterLeafNode(array(f), id=i) for (i, f) in enumerate(features)] while (len(node) > 1): closest = float('Inf') for (ni, nj) in combinations(node, 2): if ((ni, nj) not in distances): distances[(ni, nj)] = distfcn(ni.vec, nj.vec) d = distances[(ni, nj)] if (d < closest): closest = d lowestpair = (ni, nj) (ni, nj) = lowestpair new_vec = ((ni.vec + nj.vec) / 2.0) new_node = ClusterNode(new_vec, left=ni, right=nj, distance=closest) node.remove(ni) node.remove(nj) node.append(new_node) return node[0]
null
null
null
When does the code call an assertion_expression ?
def wait_for_assertion(assertion_expression, timeout=5): start_time = time.time() while ((time.time() - start_time) < timeout): try: return assertion_expression() except AssertionError: time.sleep(0.1) return assertion_expression()
null
null
null
repeatedly
codeqa
def wait for assertion assertion expression timeout 5 start time time time while time time - start time < timeout try return assertion expression except Assertion Error time sleep 0 1 return assertion expression
null
null
null
null
Question: When does the code call an assertion_expression ? Code: def wait_for_assertion(assertion_expression, timeout=5): start_time = time.time() while ((time.time() - start_time) < timeout): try: return assertion_expression() except AssertionError: time.sleep(0.1) return assertion_expression()
null
null
null
What do one update ?
def create_or_update_trigger_db(trigger): assert isinstance(trigger, dict) existing_trigger_db = _get_trigger_db(trigger) if existing_trigger_db: is_update = True else: is_update = False trigger_api = TriggerAPI(**trigger) trigger_api.validate() trigger_db = TriggerAPI.to_model(trigger_api) if is_update: trigger_db.id = existing_trigger_db.id trigger_db = Trigger.add_or_update(trigger_db) extra = {'trigger_db': trigger_db} if is_update: LOG.audit(('Trigger updated. Trigger.id=%s' % trigger_db.id), extra=extra) else: LOG.audit(('Trigger created. Trigger.id=%s' % trigger_db.id), extra=extra) return trigger_db
null
null
null
existing one
codeqa
def create or update trigger db trigger assert isinstance trigger dict existing trigger db get trigger db trigger if existing trigger db is update Trueelse is update Falsetrigger api Trigger API **trigger trigger api validate trigger db Trigger API to model trigger api if is update trigger db id existing trigger db idtrigger db Trigger add or update trigger db extra {'trigger db' trigger db}if is update LOG audit ' Triggerupdated Trigger id %s' % trigger db id extra extra else LOG audit ' Triggercreated Trigger id %s' % trigger db id extra extra return trigger db
null
null
null
null
Question: What do one update ? Code: def create_or_update_trigger_db(trigger): assert isinstance(trigger, dict) existing_trigger_db = _get_trigger_db(trigger) if existing_trigger_db: is_update = True else: is_update = False trigger_api = TriggerAPI(**trigger) trigger_api.validate() trigger_db = TriggerAPI.to_model(trigger_api) if is_update: trigger_db.id = existing_trigger_db.id trigger_db = Trigger.add_or_update(trigger_db) extra = {'trigger_db': trigger_db} if is_update: LOG.audit(('Trigger updated. Trigger.id=%s' % trigger_db.id), extra=extra) else: LOG.audit(('Trigger created. Trigger.id=%s' % trigger_db.id), extra=extra) return trigger_db
null
null
null
What updates existing one ?
def create_or_update_trigger_db(trigger): assert isinstance(trigger, dict) existing_trigger_db = _get_trigger_db(trigger) if existing_trigger_db: is_update = True else: is_update = False trigger_api = TriggerAPI(**trigger) trigger_api.validate() trigger_db = TriggerAPI.to_model(trigger_api) if is_update: trigger_db.id = existing_trigger_db.id trigger_db = Trigger.add_or_update(trigger_db) extra = {'trigger_db': trigger_db} if is_update: LOG.audit(('Trigger updated. Trigger.id=%s' % trigger_db.id), extra=extra) else: LOG.audit(('Trigger created. Trigger.id=%s' % trigger_db.id), extra=extra) return trigger_db
null
null
null
one
codeqa
def create or update trigger db trigger assert isinstance trigger dict existing trigger db get trigger db trigger if existing trigger db is update Trueelse is update Falsetrigger api Trigger API **trigger trigger api validate trigger db Trigger API to model trigger api if is update trigger db id existing trigger db idtrigger db Trigger add or update trigger db extra {'trigger db' trigger db}if is update LOG audit ' Triggerupdated Trigger id %s' % trigger db id extra extra else LOG audit ' Triggercreated Trigger id %s' % trigger db id extra extra return trigger db
null
null
null
null
Question: What updates existing one ? Code: def create_or_update_trigger_db(trigger): assert isinstance(trigger, dict) existing_trigger_db = _get_trigger_db(trigger) if existing_trigger_db: is_update = True else: is_update = False trigger_api = TriggerAPI(**trigger) trigger_api.validate() trigger_db = TriggerAPI.to_model(trigger_api) if is_update: trigger_db.id = existing_trigger_db.id trigger_db = Trigger.add_or_update(trigger_db) extra = {'trigger_db': trigger_db} if is_update: LOG.audit(('Trigger updated. Trigger.id=%s' % trigger_db.id), extra=extra) else: LOG.audit(('Trigger created. Trigger.id=%s' % trigger_db.id), extra=extra) return trigger_db
null
null
null
What does the code release ?
def libvlc_chapter_descriptions_release(p_chapters, i_count): f = (_Cfunctions.get('libvlc_chapter_descriptions_release', None) or _Cfunction('libvlc_chapter_descriptions_release', ((1,), (1,)), None, None, ctypes.POINTER(ChapterDescription), ctypes.c_uint)) return f(p_chapters, i_count)
null
null
null
a chapter description
codeqa
def libvlc chapter descriptions release p chapters i count f Cfunctions get 'libvlc chapter descriptions release' None or Cfunction 'libvlc chapter descriptions release' 1 1 None None ctypes POINTER Chapter Description ctypes c uint return f p chapters i count
null
null
null
null
Question: What does the code release ? Code: def libvlc_chapter_descriptions_release(p_chapters, i_count): f = (_Cfunctions.get('libvlc_chapter_descriptions_release', None) or _Cfunction('libvlc_chapter_descriptions_release', ((1,), (1,)), None, None, ctypes.POINTER(ChapterDescription), ctypes.c_uint)) return f(p_chapters, i_count)
null
null
null
What does this technique eliminate ?
def elimination_technique_2(C): rels = C._reidemeister_relators rels.sort(reverse=True) gens = C._schreier_generators for i in range((len(gens) - 1), (-1), (-1)): rel = rels[i] for j in range((len(gens) - 1), (-1), (-1)): gen = gens[j] if (rel.generator_count(gen) == 1): k = rel.exponent_sum(gen) gen_index = rel.index((gen ** k)) bk = rel.subword((gen_index + 1), len(rel)) fw = rel.subword(0, gen_index) rep_by = ((bk * fw) ** ((-1) * k)) del rels[i] del gens[j] for l in range(len(rels)): rels[l] = rels[l].eliminate_word(gen, rep_by) break C._reidemeister_relators = rels C._schreier_generators = gens return (C._schreier_generators, C._reidemeister_relators)
null
null
null
one generator at a time
codeqa
def elimination technique 2 C rels C reidemeister relatorsrels sort reverse True gens C schreier generatorsfor i in range len gens - 1 -1 -1 rel rels[i]for j in range len gens - 1 -1 -1 gen gens[j]if rel generator count gen 1 k rel exponent sum gen gen index rel index gen ** k bk rel subword gen index + 1 len rel fw rel subword 0 gen index rep by bk * fw ** -1 * k del rels[i]del gens[j]for l in range len rels rels[l] rels[l] eliminate word gen rep by break C reidemeister relators rels C schreier generators gensreturn C schreier generators C reidemeister relators
null
null
null
null
Question: What does this technique eliminate ? Code: def elimination_technique_2(C): rels = C._reidemeister_relators rels.sort(reverse=True) gens = C._schreier_generators for i in range((len(gens) - 1), (-1), (-1)): rel = rels[i] for j in range((len(gens) - 1), (-1), (-1)): gen = gens[j] if (rel.generator_count(gen) == 1): k = rel.exponent_sum(gen) gen_index = rel.index((gen ** k)) bk = rel.subword((gen_index + 1), len(rel)) fw = rel.subword(0, gen_index) rep_by = ((bk * fw) ** ((-1) * k)) del rels[i] del gens[j] for l in range(len(rels)): rels[l] = rels[l].eliminate_word(gen, rep_by) break C._reidemeister_relators = rels C._schreier_generators = gens return (C._schreier_generators, C._reidemeister_relators)
null
null
null
What eliminates one generator at a time ?
def elimination_technique_2(C): rels = C._reidemeister_relators rels.sort(reverse=True) gens = C._schreier_generators for i in range((len(gens) - 1), (-1), (-1)): rel = rels[i] for j in range((len(gens) - 1), (-1), (-1)): gen = gens[j] if (rel.generator_count(gen) == 1): k = rel.exponent_sum(gen) gen_index = rel.index((gen ** k)) bk = rel.subword((gen_index + 1), len(rel)) fw = rel.subword(0, gen_index) rep_by = ((bk * fw) ** ((-1) * k)) del rels[i] del gens[j] for l in range(len(rels)): rels[l] = rels[l].eliminate_word(gen, rep_by) break C._reidemeister_relators = rels C._schreier_generators = gens return (C._schreier_generators, C._reidemeister_relators)
null
null
null
this technique
codeqa
def elimination technique 2 C rels C reidemeister relatorsrels sort reverse True gens C schreier generatorsfor i in range len gens - 1 -1 -1 rel rels[i]for j in range len gens - 1 -1 -1 gen gens[j]if rel generator count gen 1 k rel exponent sum gen gen index rel index gen ** k bk rel subword gen index + 1 len rel fw rel subword 0 gen index rep by bk * fw ** -1 * k del rels[i]del gens[j]for l in range len rels rels[l] rels[l] eliminate word gen rep by break C reidemeister relators rels C schreier generators gensreturn C schreier generators C reidemeister relators
null
null
null
null
Question: What eliminates one generator at a time ? Code: def elimination_technique_2(C): rels = C._reidemeister_relators rels.sort(reverse=True) gens = C._schreier_generators for i in range((len(gens) - 1), (-1), (-1)): rel = rels[i] for j in range((len(gens) - 1), (-1), (-1)): gen = gens[j] if (rel.generator_count(gen) == 1): k = rel.exponent_sum(gen) gen_index = rel.index((gen ** k)) bk = rel.subword((gen_index + 1), len(rel)) fw = rel.subword(0, gen_index) rep_by = ((bk * fw) ** ((-1) * k)) del rels[i] del gens[j] for l in range(len(rels)): rels[l] = rels[l].eliminate_word(gen, rep_by) break C._reidemeister_relators = rels C._schreier_generators = gens return (C._schreier_generators, C._reidemeister_relators)
null
null
null
What does the code get ?
def run_all_pillar(pillar_name): data = _execute_pillar(pillar_name, run_all) return data
null
null
null
the result of cmd
codeqa
def run all pillar pillar name data execute pillar pillar name run all return data
null
null
null
null
Question: What does the code get ? Code: def run_all_pillar(pillar_name): data = _execute_pillar(pillar_name, run_all) return data
null
null
null
What is matching the given criteria ?
def games(year, week=None, home=None, away=None, kind='REG', started=False): return list(games_gen(year, week, home, away, kind, started))
null
null
null
all games
codeqa
def games year week None home None away None kind 'REG' started False return list games gen year week home away kind started
null
null
null
null
Question: What is matching the given criteria ? Code: def games(year, week=None, home=None, away=None, kind='REG', started=False): return list(games_gen(year, week, home, away, kind, started))
null
null
null
What evaluates a given python arithmetic operator between two models ?
def _model_oper(oper, **kwargs): return (lambda left, right: _CompoundModelMeta._from_operator(oper, left, right, **kwargs))
null
null
null
a function
codeqa
def model oper oper **kwargs return lambda left right Compound Model Meta from operator oper left right **kwargs
null
null
null
null
Question: What evaluates a given python arithmetic operator between two models ? Code: def _model_oper(oper, **kwargs): return (lambda left, right: _CompoundModelMeta._from_operator(oper, left, right, **kwargs))
null
null
null
What does a function evaluate between two models ?
def _model_oper(oper, **kwargs): return (lambda left, right: _CompoundModelMeta._from_operator(oper, left, right, **kwargs))
null
null
null
a given python arithmetic operator
codeqa
def model oper oper **kwargs return lambda left right Compound Model Meta from operator oper left right **kwargs
null
null
null
null
Question: What does a function evaluate between two models ? Code: def _model_oper(oper, **kwargs): return (lambda left, right: _CompoundModelMeta._from_operator(oper, left, right, **kwargs))
null
null
null
When do all hours and days report ?
def report_entire_month(month_date, start_hour=0, start_day=1): (year, month) = month_date.split('-') (year, month) = (int(year), int(month)) hours = xrange(start_hour, 24) for day in xrange(start_day, (calendar.monthrange(year, month)[1] + 1)): for hour in hours: hour_date = ('%04d-%02d-%02d-%02d' % (year, month, day, hour)) try: report_interval(hour_date, background=False) except ValueError: print ('Failed for %s' % hour_date) continue hours = xrange(24) day_date = ('%04d-%02d-%02d' % (year, month, day)) try: report_interval(day_date, background=False) except ValueError: print ('Failed for %s' % day_date) continue report_interval(month_date, background=False)
null
null
null
from month
codeqa
def report entire month month date start hour 0 start day 1 year month month date split '-' year month int year int month hours xrange start hour 24 for day in xrange start day calendar monthrange year month [1 ] + 1 for hour in hours hour date '% 04 d-% 02 d-% 02 d-% 02 d' % year month day hour try report interval hour date background False except Value Error print ' Failedfor%s' % hour date continuehours xrange 24 day date '% 04 d-% 02 d-% 02 d' % year month day try report interval day date background False except Value Error print ' Failedfor%s' % day date continuereport interval month date background False
null
null
null
null
Question: When do all hours and days report ? Code: def report_entire_month(month_date, start_hour=0, start_day=1): (year, month) = month_date.split('-') (year, month) = (int(year), int(month)) hours = xrange(start_hour, 24) for day in xrange(start_day, (calendar.monthrange(year, month)[1] + 1)): for hour in hours: hour_date = ('%04d-%02d-%02d-%02d' % (year, month, day, hour)) try: report_interval(hour_date, background=False) except ValueError: print ('Failed for %s' % hour_date) continue hours = xrange(24) day_date = ('%04d-%02d-%02d' % (year, month, day)) try: report_interval(day_date, background=False) except ValueError: print ('Failed for %s' % day_date) continue report_interval(month_date, background=False)
null
null
null
What updates a file atomically ?
@contextmanager def atomic_write(filepath, binary=False, fsync=False): tmppath = (filepath + '~') while os.path.isfile(tmppath): tmppath += '~' try: with open(tmppath, ('wb' if binary else 'w')) as file: (yield file) if fsync: file.flush() os.fsync(file.fileno()) replace(tmppath, filepath) finally: try: os.remove(tmppath) except (IOError, OSError): pass
null
null
null
writeable file object
codeqa
@contextmanagerdef atomic write filepath binary False fsync False tmppath filepath + '~' while os path isfile tmppath tmppath + '~'try with open tmppath 'wb' if binary else 'w' as file yield file if fsync file flush os fsync file fileno replace tmppath filepath finally try os remove tmppath except IO Error OS Error pass
null
null
null
null
Question: What updates a file atomically ? Code: @contextmanager def atomic_write(filepath, binary=False, fsync=False): tmppath = (filepath + '~') while os.path.isfile(tmppath): tmppath += '~' try: with open(tmppath, ('wb' if binary else 'w')) as file: (yield file) if fsync: file.flush() os.fsync(file.fileno()) replace(tmppath, filepath) finally: try: os.remove(tmppath) except (IOError, OSError): pass
null
null
null
How do command give ?
def _shell_wrap_inner(command, shell=True, sudo_prefix=None): if (shell and (not env.use_shell)): shell = False if (sudo_prefix is None): sudo_prefix = '' else: sudo_prefix += ' ' if shell: shell = (env.shell + ' ') command = ('"%s"' % command) else: shell = '' return ((sudo_prefix + shell) + command)
null
null
null
conditionally
codeqa
def shell wrap inner command shell True sudo prefix None if shell and not env use shell shell Falseif sudo prefix is None sudo prefix ''else sudo prefix + ''if shell shell env shell + '' command '"%s"' % command else shell ''return sudo prefix + shell + command
null
null
null
null
Question: How do command give ? Code: def _shell_wrap_inner(command, shell=True, sudo_prefix=None): if (shell and (not env.use_shell)): shell = False if (sudo_prefix is None): sudo_prefix = '' else: sudo_prefix += ' ' if shell: shell = (env.shell + ' ') command = ('"%s"' % command) else: shell = '' return ((sudo_prefix + shell) + command)
null
null
null
How do command wrap ?
def _shell_wrap_inner(command, shell=True, sudo_prefix=None): if (shell and (not env.use_shell)): shell = False if (sudo_prefix is None): sudo_prefix = '' else: sudo_prefix += ' ' if shell: shell = (env.shell + ' ') command = ('"%s"' % command) else: shell = '' return ((sudo_prefix + shell) + command)
null
null
null
conditionally
codeqa
def shell wrap inner command shell True sudo prefix None if shell and not env use shell shell Falseif sudo prefix is None sudo prefix ''else sudo prefix + ''if shell shell env shell + '' command '"%s"' % command else shell ''return sudo prefix + shell + command
null
null
null
null
Question: How do command wrap ? Code: def _shell_wrap_inner(command, shell=True, sudo_prefix=None): if (shell and (not env.use_shell)): shell = False if (sudo_prefix is None): sudo_prefix = '' else: sudo_prefix += ' ' if shell: shell = (env.shell + ' ') command = ('"%s"' % command) else: shell = '' return ((sudo_prefix + shell) + command)
null
null
null
For what purpose does the code add the list of posts to every page context ?
def preBuildPage(site, page, context, data): context['posts'] = POSTS for post in POSTS: if (post['path'] == page.final_url): context.update(post) return (context, data)
null
null
null
so we can access them from wherever on the site
codeqa
def pre Build Page site page context data context['posts'] POST Sfor post in POSTS if post['path'] page final url context update post return context data
null
null
null
null
Question: For what purpose does the code add the list of posts to every page context ? Code: def preBuildPage(site, page, context, data): context['posts'] = POSTS for post in POSTS: if (post['path'] == page.final_url): context.update(post) return (context, data)
null
null
null
In which direction can we access them ?
def preBuildPage(site, page, context, data): context['posts'] = POSTS for post in POSTS: if (post['path'] == page.final_url): context.update(post) return (context, data)
null
null
null
from wherever on the site
codeqa
def pre Build Page site page context data context['posts'] POST Sfor post in POSTS if post['path'] page final url context update post return context data
null
null
null
null
Question: In which direction can we access them ? Code: def preBuildPage(site, page, context, data): context['posts'] = POSTS for post in POSTS: if (post['path'] == page.final_url): context.update(post) return (context, data)
null
null
null
What denotes an active entry ?
def is_hash_used(context, builder, h): deleted = ir.Constant(h.type, DELETED) return builder.icmp_unsigned('<', h, deleted)
null
null
null
the hash value
codeqa
def is hash used context builder h deleted ir Constant h type DELETED return builder icmp unsigned '<' h deleted
null
null
null
null
Question: What denotes an active entry ? Code: def is_hash_used(context, builder, h): deleted = ir.Constant(h.type, DELETED) return builder.icmp_unsigned('<', h, deleted)
null
null
null
What does the hash value denote ?
def is_hash_used(context, builder, h): deleted = ir.Constant(h.type, DELETED) return builder.icmp_unsigned('<', h, deleted)
null
null
null
an active entry
codeqa
def is hash used context builder h deleted ir Constant h type DELETED return builder icmp unsigned '<' h deleted
null
null
null
null
Question: What does the hash value denote ? Code: def is_hash_used(context, builder, h): deleted = ir.Constant(h.type, DELETED) return builder.icmp_unsigned('<', h, deleted)
null
null
null
How did storage share ?
def migrate_non_shared(vm_, target, ssh=False): cmd = (((_get_migrate_command() + ' --copy-storage-all ') + vm_) + _get_target(target, ssh)) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.to_str(stdout)
null
null
null
non
codeqa
def migrate non shared vm target ssh False cmd get migrate command + '--copy-storage-all' + vm + get target target ssh stdout subprocess Popen cmd shell True stdout subprocess PIPE communicate [0 ]return salt utils to str stdout
null
null
null
null
Question: How did storage share ? Code: def migrate_non_shared(vm_, target, ssh=False): cmd = (((_get_migrate_command() + ' --copy-storage-all ') + vm_) + _get_target(target, ssh)) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.to_str(stdout)
null
null
null
What does the code invert ?
def invert_transform(trans): return Transform(trans['to'], trans['from'], linalg.inv(trans['trans']))
null
null
null
a transformation between coordinate systems
codeqa
def invert transform trans return Transform trans['to'] trans['from'] linalg inv trans['trans']
null
null
null
null
Question: What does the code invert ? Code: def invert_transform(trans): return Transform(trans['to'], trans['from'], linalg.inv(trans['trans']))
null
null
null
Where do traffic server shut ?
def shutdown(): if _TRAFFICLINE: cmd = _traffic_line('-S') else: cmd = _traffic_ctl('server', 'stop') log.debug('Running: %s', cmd) _subprocess(cmd) return _statuscmd()
null
null
null
on the local node
codeqa
def shutdown if TRAFFICLINE cmd traffic line '-S' else cmd traffic ctl 'server' 'stop' log debug ' Running %s' cmd subprocess cmd return statuscmd
null
null
null
null
Question: Where do traffic server shut ? Code: def shutdown(): if _TRAFFICLINE: cmd = _traffic_line('-S') else: cmd = _traffic_ctl('server', 'stop') log.debug('Running: %s', cmd) _subprocess(cmd) return _statuscmd()
null
null
null
What shuts on the local node ?
def shutdown(): if _TRAFFICLINE: cmd = _traffic_line('-S') else: cmd = _traffic_ctl('server', 'stop') log.debug('Running: %s', cmd) _subprocess(cmd) return _statuscmd()
null
null
null
traffic server
codeqa
def shutdown if TRAFFICLINE cmd traffic line '-S' else cmd traffic ctl 'server' 'stop' log debug ' Running %s' cmd subprocess cmd return statuscmd
null
null
null
null
Question: What shuts on the local node ? Code: def shutdown(): if _TRAFFICLINE: cmd = _traffic_line('-S') else: cmd = _traffic_ctl('server', 'stop') log.debug('Running: %s', cmd) _subprocess(cmd) return _statuscmd()
null
null
null
What can our fancy importer let ?
def register_importer(): def test(importer): return (importer.__class__.__name__ == ModuleImporterFromVariables.__name__) already_registered = any([True for i in sys.meta_path if test(i)]) if (not already_registered): importer = ModuleImporterFromVariables(restrict_to=['SelfWrapper']) sys.meta_path.insert(0, importer) return (not already_registered)
null
null
null
us import from a module name
codeqa
def register importer def test importer return importer class name Module Importer From Variables name already registered any [ True for i in sys meta path if test i ] if not already registered importer Module Importer From Variables restrict to [' Self Wrapper'] sys meta path insert 0 importer return not already registered
null
null
null
null
Question: What can our fancy importer let ? Code: def register_importer(): def test(importer): return (importer.__class__.__name__ == ModuleImporterFromVariables.__name__) already_registered = any([True for i in sys.meta_path if test(i)]) if (not already_registered): importer = ModuleImporterFromVariables(restrict_to=['SelfWrapper']) sys.meta_path.insert(0, importer) return (not already_registered)
null
null
null
What can let us import from a module name ?
def register_importer(): def test(importer): return (importer.__class__.__name__ == ModuleImporterFromVariables.__name__) already_registered = any([True for i in sys.meta_path if test(i)]) if (not already_registered): importer = ModuleImporterFromVariables(restrict_to=['SelfWrapper']) sys.meta_path.insert(0, importer) return (not already_registered)
null
null
null
our fancy importer
codeqa
def register importer def test importer return importer class name Module Importer From Variables name already registered any [ True for i in sys meta path if test i ] if not already registered importer Module Importer From Variables restrict to [' Self Wrapper'] sys meta path insert 0 importer return not already registered
null
null
null
null
Question: What can let us import from a module name ? Code: def register_importer(): def test(importer): return (importer.__class__.__name__ == ModuleImporterFromVariables.__name__) already_registered = any([True for i in sys.meta_path if test(i)]) if (not already_registered): importer = ModuleImporterFromVariables(restrict_to=['SelfWrapper']) sys.meta_path.insert(0, importer) return (not already_registered)
null
null
null
When does the code take care in handling the repo_info_tuple as it evolves over time ?
def get_repo_info_tuple_contents(repo_info_tuple): if (len(repo_info_tuple) == 6): (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, tool_dependencies) = repo_info_tuple repository_dependencies = None elif (len(repo_info_tuple) == 7): (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, repository_dependencies, tool_dependencies) = repo_info_tuple return (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, repository_dependencies, tool_dependencies)
null
null
null
as new tool shed features are introduced
codeqa
def get repo info tuple contents repo info tuple if len repo info tuple 6 description repository clone url changeset revision ctx rev repository owner tool dependencies repo info tuplerepository dependencies Noneelif len repo info tuple 7 description repository clone url changeset revision ctx rev repository owner repository dependencies tool dependencies repo info tuplereturn description repository clone url changeset revision ctx rev repository owner repository dependencies tool dependencies
null
null
null
null
Question: When does the code take care in handling the repo_info_tuple as it evolves over time ? Code: def get_repo_info_tuple_contents(repo_info_tuple): if (len(repo_info_tuple) == 6): (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, tool_dependencies) = repo_info_tuple repository_dependencies = None elif (len(repo_info_tuple) == 7): (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, repository_dependencies, tool_dependencies) = repo_info_tuple return (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, repository_dependencies, tool_dependencies)
null
null
null
What does the code take in handling the repo_info_tuple as it evolves over time as new tool shed features are introduced ?
def get_repo_info_tuple_contents(repo_info_tuple): if (len(repo_info_tuple) == 6): (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, tool_dependencies) = repo_info_tuple repository_dependencies = None elif (len(repo_info_tuple) == 7): (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, repository_dependencies, tool_dependencies) = repo_info_tuple return (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, repository_dependencies, tool_dependencies)
null
null
null
care
codeqa
def get repo info tuple contents repo info tuple if len repo info tuple 6 description repository clone url changeset revision ctx rev repository owner tool dependencies repo info tuplerepository dependencies Noneelif len repo info tuple 7 description repository clone url changeset revision ctx rev repository owner repository dependencies tool dependencies repo info tuplereturn description repository clone url changeset revision ctx rev repository owner repository dependencies tool dependencies
null
null
null
null
Question: What does the code take in handling the repo_info_tuple as it evolves over time as new tool shed features are introduced ? Code: def get_repo_info_tuple_contents(repo_info_tuple): if (len(repo_info_tuple) == 6): (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, tool_dependencies) = repo_info_tuple repository_dependencies = None elif (len(repo_info_tuple) == 7): (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, repository_dependencies, tool_dependencies) = repo_info_tuple return (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, repository_dependencies, tool_dependencies)
null
null
null
What does the code check to see if the value matches it ?
def get_values_of_matching_keys(pattern_dict, user_name): ret = [] for expr in pattern_dict: if expr_match(user_name, expr): ret.extend(pattern_dict[expr]) return ret
null
null
null
a whitelist and/or blacklist
codeqa
def get values of matching keys pattern dict user name ret []for expr in pattern dict if expr match user name expr ret extend pattern dict[expr] return ret
null
null
null
null
Question: What does the code check to see if the value matches it ? Code: def get_values_of_matching_keys(pattern_dict, user_name): ret = [] for expr in pattern_dict: if expr_match(user_name, expr): ret.extend(pattern_dict[expr]) return ret
null
null
null
For what purpose does the code check a whitelist and/or blacklist ?
def get_values_of_matching_keys(pattern_dict, user_name): ret = [] for expr in pattern_dict: if expr_match(user_name, expr): ret.extend(pattern_dict[expr]) return ret
null
null
null
to see if the value matches it
codeqa
def get values of matching keys pattern dict user name ret []for expr in pattern dict if expr match user name expr ret extend pattern dict[expr] return ret
null
null
null
null
Question: For what purpose does the code check a whitelist and/or blacklist ? Code: def get_values_of_matching_keys(pattern_dict, user_name): ret = [] for expr in pattern_dict: if expr_match(user_name, expr): ret.extend(pattern_dict[expr]) return ret
null
null
null
What does the code identify ?
def find_disk_dev_for_disk_bus(mapping, bus, assigned_devices=None): dev_prefix = get_dev_prefix_for_disk_bus(bus) if (dev_prefix is None): return None if (assigned_devices is None): assigned_devices = [] max_dev = get_dev_count_for_disk_bus(bus) devs = range(max_dev) for idx in devs: disk_dev = (dev_prefix + chr((ord('a') + idx))) if (not has_disk_dev(mapping, disk_dev)): if (disk_dev not in assigned_devices): return disk_dev msg = (_("No free disk device names for prefix '%s'") % dev_prefix) raise exception.InternalError(msg)
null
null
null
a free disk dev name for a bus
codeqa
def find disk dev for disk bus mapping bus assigned devices None dev prefix get dev prefix for disk bus bus if dev prefix is None return Noneif assigned devices is None assigned devices []max dev get dev count for disk bus bus devs range max dev for idx in devs disk dev dev prefix + chr ord 'a' + idx if not has disk dev mapping disk dev if disk dev not in assigned devices return disk devmsg " Nofreediskdevicenamesforprefix'%s'" % dev prefix raise exception Internal Error msg
null
null
null
null
Question: What does the code identify ? Code: def find_disk_dev_for_disk_bus(mapping, bus, assigned_devices=None): dev_prefix = get_dev_prefix_for_disk_bus(bus) if (dev_prefix is None): return None if (assigned_devices is None): assigned_devices = [] max_dev = get_dev_count_for_disk_bus(bus) devs = range(max_dev) for idx in devs: disk_dev = (dev_prefix + chr((ord('a') + idx))) if (not has_disk_dev(mapping, disk_dev)): if (disk_dev not in assigned_devices): return disk_dev msg = (_("No free disk device names for prefix '%s'") % dev_prefix) raise exception.InternalError(msg)
null
null
null
What does the code get ?
def package_tree(pkgroot): path = os.path.dirname(__file__) subdirs = [os.path.relpath(i[0], path).replace(os.path.sep, '.') for i in os.walk(os.path.join(path, pkgroot)) if ('__init__.py' in i[2])] return sorted(subdirs)
null
null
null
the submodule list
codeqa
def package tree pkgroot path os path dirname file subdirs [os path relpath i[ 0 ] path replace os path sep ' ' for i in os walk os path join path pkgroot if ' init py' in i[ 2 ] ]return sorted subdirs
null
null
null
null
Question: What does the code get ? Code: def package_tree(pkgroot): path = os.path.dirname(__file__) subdirs = [os.path.relpath(i[0], path).replace(os.path.sep, '.') for i in os.walk(os.path.join(path, pkgroot)) if ('__init__.py' in i[2])] return sorted(subdirs)
null
null
null
What does a string convert ?
def force_str(s, encoding='utf-8'): if isinstance(s, str): return s elif isinstance(s, Text): return s.encode(encoding) elif isinstance(s, binary_type): return s.decode(encoding) else: raise TypeError('force_str expects a string type')
null
null
null
to a native string
codeqa
def force str s encoding 'utf- 8 ' if isinstance s str return selif isinstance s Text return s encode encoding elif isinstance s binary type return s decode encoding else raise Type Error 'force strexpectsastringtype'
null
null
null
null
Question: What does a string convert ? Code: def force_str(s, encoding='utf-8'): if isinstance(s, str): return s elif isinstance(s, Text): return s.encode(encoding) elif isinstance(s, binary_type): return s.decode(encoding) else: raise TypeError('force_str expects a string type')
null
null
null
What converts to a native string ?
def force_str(s, encoding='utf-8'): if isinstance(s, str): return s elif isinstance(s, Text): return s.encode(encoding) elif isinstance(s, binary_type): return s.decode(encoding) else: raise TypeError('force_str expects a string type')
null
null
null
a string
codeqa
def force str s encoding 'utf- 8 ' if isinstance s str return selif isinstance s Text return s encode encoding elif isinstance s binary type return s decode encoding else raise Type Error 'force strexpectsastringtype'
null
null
null
null
Question: What converts to a native string ? Code: def force_str(s, encoding='utf-8'): if isinstance(s, str): return s elif isinstance(s, Text): return s.encode(encoding) elif isinstance(s, binary_type): return s.decode(encoding) else: raise TypeError('force_str expects a string type')
null
null
null
How do groups capture ?
def _re_flatten(p): if ('(' not in p): return p return re.sub('(\\\\*)(\\(\\?P<[^>]+>|\\((?!\\?))', (lambda m: (m.group(0) if (len(m.group(1)) % 2) else (m.group(1) + '(?:'))), p)
null
null
null
non
codeqa
def re flatten p if ' ' not in p return preturn re sub ' \\\\* \\ \\?P<[^>]+> \\ ? \\? ' lambda m m group 0 if len m group 1 % 2 else m group 1 + ' ? ' p
null
null
null
null
Question: How do groups capture ? Code: def _re_flatten(p): if ('(' not in p): return p return re.sub('(\\\\*)(\\(\\?P<[^>]+>|\\((?!\\?))', (lambda m: (m.group(0) if (len(m.group(1)) % 2) else (m.group(1) + '(?:'))), p)
null
null
null
What does the code get ?
def get_time_info(layer): layer = gs_catalog.get_layer(layer.name) if (layer is None): raise ValueError(('no such layer: %s' % layer.name)) resource = layer.resource info = (resource.metadata.get('time', None) if resource.metadata else None) vals = None if info: value = step = None resolution = info.resolution_str() if resolution: (value, step) = resolution.split() vals = dict(enabled=info.enabled, attribute=info.attribute, end_attribute=info.end_attribute, presentation=info.presentation, precision_value=value, precision_step=step) return vals
null
null
null
the configured time dimension metadata for the layer
codeqa
def get time info layer layer gs catalog get layer layer name if layer is None raise Value Error 'nosuchlayer %s' % layer name resource layer resourceinfo resource metadata get 'time' None if resource metadata else None vals Noneif info value step Noneresolution info resolution str if resolution value step resolution split vals dict enabled info enabled attribute info attribute end attribute info end attribute presentation info presentation precision value value precision step step return vals
null
null
null
null
Question: What does the code get ? Code: def get_time_info(layer): layer = gs_catalog.get_layer(layer.name) if (layer is None): raise ValueError(('no such layer: %s' % layer.name)) resource = layer.resource info = (resource.metadata.get('time', None) if resource.metadata else None) vals = None if info: value = step = None resolution = info.resolution_str() if resolution: (value, step) = resolution.split() vals = dict(enabled=info.enabled, attribute=info.attribute, end_attribute=info.end_attribute, presentation=info.presentation, precision_value=value, precision_step=step) return vals
null
null
null
What does the code get ?
def getNextEdgeIndexAroundZ(edge, faces, remainingEdgeTable): for faceIndex in edge.faceIndexes: face = faces[faceIndex] for edgeIndex in face.edgeIndexes: if (edgeIndex in remainingEdgeTable): return edgeIndex return (-1)
null
null
null
the next edge index in the mesh carve
codeqa
def get Next Edge Index Around Z edge faces remaining Edge Table for face Index in edge face Indexes face faces[face Index]for edge Index in face edge Indexes if edge Index in remaining Edge Table return edge Indexreturn -1
null
null
null
null
Question: What does the code get ? Code: def getNextEdgeIndexAroundZ(edge, faces, remainingEdgeTable): for faceIndex in edge.faceIndexes: face = faces[faceIndex] for edgeIndex in face.edgeIndexes: if (edgeIndex in remainingEdgeTable): return edgeIndex return (-1)
null
null
null
What packs object ?
def pack(o, stream, **kwargs): packer = Packer(**kwargs) stream.write(packer.pack(o))
null
null
null
o
codeqa
def pack o stream **kwargs packer Packer **kwargs stream write packer pack o
null
null
null
null
Question: What packs object ? Code: def pack(o, stream, **kwargs): packer = Packer(**kwargs) stream.write(packer.pack(o))
null
null
null
What does the code provide ?
def get_logger(): return LOGGER
null
null
null
the stem logger
codeqa
def get logger return LOGGER
null
null
null
null
Question: What does the code provide ? Code: def get_logger(): return LOGGER
null
null
null
Where is this function run ?
def in_idle(): import sys return (sys.stdin.__class__.__name__ in ('PyShell', 'RPCProxy'))
null
null
null
within idle
codeqa
def in idle import sysreturn sys stdin class name in ' Py Shell' 'RPC Proxy'
null
null
null
null
Question: Where is this function run ? Code: def in_idle(): import sys return (sys.stdin.__class__.__name__ in ('PyShell', 'RPCProxy'))
null
null
null
What does the code run to download target ?
def _clean_check(cmd, target): try: subprocess.check_call(cmd) except subprocess.CalledProcessError: if os.access(target, os.F_OK): os.unlink(target) raise
null
null
null
the command
codeqa
def clean check cmd target try subprocess check call cmd except subprocess Called Process Error if os access target os F OK os unlink target raise
null
null
null
null
Question: What does the code run to download target ? Code: def _clean_check(cmd, target): try: subprocess.check_call(cmd) except subprocess.CalledProcessError: if os.access(target, os.F_OK): os.unlink(target) raise
null
null
null
For what purpose does the code run the command ?
def _clean_check(cmd, target): try: subprocess.check_call(cmd) except subprocess.CalledProcessError: if os.access(target, os.F_OK): os.unlink(target) raise
null
null
null
to download target
codeqa
def clean check cmd target try subprocess check call cmd except subprocess Called Process Error if os access target os F OK os unlink target raise
null
null
null
null
Question: For what purpose does the code run the command ? Code: def _clean_check(cmd, target): try: subprocess.check_call(cmd) except subprocess.CalledProcessError: if os.access(target, os.F_OK): os.unlink(target) raise
null
null
null
What does the code shuffle ?
def shuffle_data(X, L, seed=1234): prng = RandomState(seed) inds = np.arange(len(X)) prng.shuffle(inds) X = [X[i] for i in inds] L = L[inds] return (X, L)
null
null
null
the data
codeqa
def shuffle data X L seed 1234 prng Random State seed inds np arange len X prng shuffle inds X [X[i] for i in inds]L L[inds]return X L
null
null
null
null
Question: What does the code shuffle ? Code: def shuffle_data(X, L, seed=1234): prng = RandomState(seed) inds = np.arange(len(X)) prng.shuffle(inds) X = [X[i] for i in inds] L = L[inds] return (X, L)
null
null
null
What returns celery stats ?
@dog_stats_api.timed('status.service.celery.status') def celery_status(_): stats = (celery.control.inspect().stats() or {}) return HttpResponse(json.dumps(stats, indent=4), content_type='application/json')
null
null
null
a view
codeqa
@dog stats api timed 'status service celery status' def celery status stats celery control inspect stats or {} return Http Response json dumps stats indent 4 content type 'application/json'
null
null
null
null
Question: What returns celery stats ? Code: @dog_stats_api.timed('status.service.celery.status') def celery_status(_): stats = (celery.control.inspect().stats() or {}) return HttpResponse(json.dumps(stats, indent=4), content_type='application/json')
null
null
null
What does a view return ?
@dog_stats_api.timed('status.service.celery.status') def celery_status(_): stats = (celery.control.inspect().stats() or {}) return HttpResponse(json.dumps(stats, indent=4), content_type='application/json')
null
null
null
celery stats
codeqa
@dog stats api timed 'status service celery status' def celery status stats celery control inspect stats or {} return Http Response json dumps stats indent 4 content type 'application/json'
null
null
null
null
Question: What does a view return ? Code: @dog_stats_api.timed('status.service.celery.status') def celery_status(_): stats = (celery.control.inspect().stats() or {}) return HttpResponse(json.dumps(stats, indent=4), content_type='application/json')
null
null
null
What confirmed section 9 ?
def ccEstablishmentConfirmed(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Cause_presence=0): a = TpPd(pd=3) b = MessageType(mesType=6) packet = (a / b) if (RepeatIndicator_presence is 1): c = RepeatIndicatorHdr(ieiRI=13, eightBitRI=0) packet = (packet / c) if (BearerCapability_presence is 1): d = BearerCapabilityHdr(ieiBC=4, eightBitBC=0) packet = (packet / d) if (BearerCapability_presence1 is 1): e = BearerCapabilityHdr(ieiBC=4, eightBitBC=0) packet = (packet / e) if (Cause_presence is 1): f = CauseHdr(ieiC=8, eightBitC=0) packet = (packet / f) return packet
null
null
null
cc - establishment
codeqa
def cc Establishment Confirmed Repeat Indicator presence 0 Bearer Capability presence 0 Bearer Capability presence 1 0 Cause presence 0 a Tp Pd pd 3 b Message Type mes Type 6 packet a / b if Repeat Indicator presence is 1 c Repeat Indicator Hdr iei RI 13 eight Bit RI 0 packet packet / c if Bearer Capability presence is 1 d Bearer Capability Hdr iei BC 4 eight Bit BC 0 packet packet / d if Bearer Capability presence 1 is 1 e Bearer Capability Hdr iei BC 4 eight Bit BC 0 packet packet / e if Cause presence is 1 f Cause Hdr iei C 8 eight Bit C 0 packet packet / f return packet
null
null
null
null
Question: What confirmed section 9 ? Code: def ccEstablishmentConfirmed(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Cause_presence=0): a = TpPd(pd=3) b = MessageType(mesType=6) packet = (a / b) if (RepeatIndicator_presence is 1): c = RepeatIndicatorHdr(ieiRI=13, eightBitRI=0) packet = (packet / c) if (BearerCapability_presence is 1): d = BearerCapabilityHdr(ieiBC=4, eightBitBC=0) packet = (packet / d) if (BearerCapability_presence1 is 1): e = BearerCapabilityHdr(ieiBC=4, eightBitBC=0) packet = (packet / e) if (Cause_presence is 1): f = CauseHdr(ieiC=8, eightBitC=0) packet = (packet / f) return packet
null
null
null
What did cc - establishment confirm ?
def ccEstablishmentConfirmed(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Cause_presence=0): a = TpPd(pd=3) b = MessageType(mesType=6) packet = (a / b) if (RepeatIndicator_presence is 1): c = RepeatIndicatorHdr(ieiRI=13, eightBitRI=0) packet = (packet / c) if (BearerCapability_presence is 1): d = BearerCapabilityHdr(ieiBC=4, eightBitBC=0) packet = (packet / d) if (BearerCapability_presence1 is 1): e = BearerCapabilityHdr(ieiBC=4, eightBitBC=0) packet = (packet / e) if (Cause_presence is 1): f = CauseHdr(ieiC=8, eightBitC=0) packet = (packet / f) return packet
null
null
null
section 9
codeqa
def cc Establishment Confirmed Repeat Indicator presence 0 Bearer Capability presence 0 Bearer Capability presence 1 0 Cause presence 0 a Tp Pd pd 3 b Message Type mes Type 6 packet a / b if Repeat Indicator presence is 1 c Repeat Indicator Hdr iei RI 13 eight Bit RI 0 packet packet / c if Bearer Capability presence is 1 d Bearer Capability Hdr iei BC 4 eight Bit BC 0 packet packet / d if Bearer Capability presence 1 is 1 e Bearer Capability Hdr iei BC 4 eight Bit BC 0 packet packet / e if Cause presence is 1 f Cause Hdr iei C 8 eight Bit C 0 packet packet / f return packet
null
null
null
null
Question: What did cc - establishment confirm ? Code: def ccEstablishmentConfirmed(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Cause_presence=0): a = TpPd(pd=3) b = MessageType(mesType=6) packet = (a / b) if (RepeatIndicator_presence is 1): c = RepeatIndicatorHdr(ieiRI=13, eightBitRI=0) packet = (packet / c) if (BearerCapability_presence is 1): d = BearerCapabilityHdr(ieiBC=4, eightBitBC=0) packet = (packet / d) if (BearerCapability_presence1 is 1): e = BearerCapabilityHdr(ieiBC=4, eightBitBC=0) packet = (packet / e) if (Cause_presence is 1): f = CauseHdr(ieiC=8, eightBitC=0) packet = (packet / f) return packet
null
null
null
What does the code update ?
def update_collection(committer_id, collection_id, change_list, commit_message): is_public = rights_manager.is_collection_public(collection_id) if (is_public and (not commit_message)): raise ValueError('Collection is public so expected a commit message but received none.') collection = apply_change_list(collection_id, change_list) _save_collection(committer_id, collection, commit_message, change_list) update_collection_summary(collection.id, committer_id) if (not rights_manager.is_collection_private(collection.id)): user_services.update_first_contribution_msec_if_not_set(committer_id, utils.get_current_time_in_millisecs())
null
null
null
a collection
codeqa
def update collection committer id collection id change list commit message is public rights manager is collection public collection id if is public and not commit message raise Value Error ' Collectionispublicsoexpectedacommitmessagebutreceivednone ' collection apply change list collection id change list save collection committer id collection commit message change list update collection summary collection id committer id if not rights manager is collection private collection id user services update first contribution msec if not set committer id utils get current time in millisecs
null
null
null
null
Question: What does the code update ? Code: def update_collection(committer_id, collection_id, change_list, commit_message): is_public = rights_manager.is_collection_public(collection_id) if (is_public and (not commit_message)): raise ValueError('Collection is public so expected a commit message but received none.') collection = apply_change_list(collection_id, change_list) _save_collection(committer_id, collection, commit_message, change_list) update_collection_summary(collection.id, committer_id) if (not rights_manager.is_collection_private(collection.id)): user_services.update_first_contribution_msec_if_not_set(committer_id, utils.get_current_time_in_millisecs())
null
null
null
Where do whitespace combine with the element following it ?
def _combine_ws(parts, whitespace): out = [] ws = '' for part in parts: if (not part): continue elif (part in whitespace): ws += part else: out.append((ws + part)) ws = '' if ws: out.append(ws) return out
null
null
null
in a list
codeqa
def combine ws parts whitespace out []ws ''for part in parts if not part continueelif part in whitespace ws + partelse out append ws + part ws ''if ws out append ws return out
null
null
null
null
Question: Where do whitespace combine with the element following it ? Code: def _combine_ws(parts, whitespace): out = [] ws = '' for part in parts: if (not part): continue elif (part in whitespace): ws += part else: out.append((ws + part)) ws = '' if ws: out.append(ws) return out
null
null
null
What combines with the element following it in a list ?
def _combine_ws(parts, whitespace): out = [] ws = '' for part in parts: if (not part): continue elif (part in whitespace): ws += part else: out.append((ws + part)) ws = '' if ws: out.append(ws) return out
null
null
null
whitespace
codeqa
def combine ws parts whitespace out []ws ''for part in parts if not part continueelif part in whitespace ws + partelse out append ws + part ws ''if ws out append ws return out
null
null
null
null
Question: What combines with the element following it in a list ? Code: def _combine_ws(parts, whitespace): out = [] ws = '' for part in parts: if (not part): continue elif (part in whitespace): ws += part else: out.append((ws + part)) ws = '' if ws: out.append(ws) return out
null
null
null
What does the code get ?
def get_host(session): host_recs = session.xenapi.host.get_all() return session.xenapi.host.get_record(host_recs[0])
null
null
null
the host
codeqa
def get host session host recs session xenapi host get all return session xenapi host get record host recs[ 0 ]
null
null
null
null
Question: What does the code get ? Code: def get_host(session): host_recs = session.xenapi.host.get_all() return session.xenapi.host.get_record(host_recs[0])
null
null
null
What does the code convert to a dictionary ?
def valuestodict(key): dict = {} size = winreg.QueryInfoKey(key)[1] for i in range(size): data = winreg.EnumValue(key, i) dict[data[0]] = data[1] return dict
null
null
null
a registry keys values
codeqa
def valuestodict key dict {}size winreg Query Info Key key [1 ]for i in range size data winreg Enum Value key i dict[data[ 0 ]] data[ 1 ]return dict
null
null
null
null
Question: What does the code convert to a dictionary ? Code: def valuestodict(key): dict = {} size = winreg.QueryInfoKey(key)[1] for i in range(size): data = winreg.EnumValue(key, i) dict[data[0]] = data[1] return dict
null
null
null
What does the code setup ?
def setup(hass, config): if (DATA_INDEX not in hass.data): hass.data[DATA_INDEX] = {} conf = config.get(DOMAIN, {}) token_file = hass.config.path(TOKEN_FILE) if (not os.path.isfile(token_file)): do_authentication(hass, conf) else: do_setup(hass, conf) return True
null
null
null
the platform
codeqa
def setup hass config if DATA INDEX not in hass data hass data[DATA INDEX] {}conf config get DOMAIN {} token file hass config path TOKEN FILE if not os path isfile token file do authentication hass conf else do setup hass conf return True
null
null
null
null
Question: What does the code setup ? Code: def setup(hass, config): if (DATA_INDEX not in hass.data): hass.data[DATA_INDEX] = {} conf = config.get(DOMAIN, {}) token_file = hass.config.path(TOKEN_FILE) if (not os.path.isfile(token_file)): do_authentication(hass, conf) else: do_setup(hass, conf) return True
null
null
null
What expects to be able to look at the request ?
def _get_mock_request(student): request = RequestFactory().get('/') request.user = student return request
null
null
null
grading code
codeqa
def get mock request student request Request Factory get '/' request user studentreturn request
null
null
null
null
Question: What expects to be able to look at the request ? Code: def _get_mock_request(student): request = RequestFactory().get('/') request.user = student return request
null
null
null
Why does the code make a fake request ?
def _get_mock_request(student): request = RequestFactory().get('/') request.user = student return request
null
null
null
because grading code expects to be able to look at the request
codeqa
def get mock request student request Request Factory get '/' request user studentreturn request
null
null
null
null
Question: Why does the code make a fake request ? Code: def _get_mock_request(student): request = RequestFactory().get('/') request.user = student return request
null
null
null
What does the code make because grading code expects to be able to look at the request ?
def _get_mock_request(student): request = RequestFactory().get('/') request.user = student return request
null
null
null
a fake request
codeqa
def get mock request student request Request Factory get '/' request user studentreturn request
null
null
null
null
Question: What does the code make because grading code expects to be able to look at the request ? Code: def _get_mock_request(student): request = RequestFactory().get('/') request.user = student return request
null
null
null
What do grading code expect ?
def _get_mock_request(student): request = RequestFactory().get('/') request.user = student return request
null
null
null
to be able to look at the request
codeqa
def get mock request student request Request Factory get '/' request user studentreturn request
null
null
null
null
Question: What do grading code expect ? Code: def _get_mock_request(student): request = RequestFactory().get('/') request.user = student return request
null
null
null
What did the code read ?
def read_file(filename): path = os.path.abspath(os.path.dirname(__file__)) filepath = os.path.join(path, filename) try: return open(filepath).read() except IOError: return ''
null
null
null
a file
codeqa
def read file filename path os path abspath os path dirname file filepath os path join path filename try return open filepath read except IO Error return ''
null
null
null
null
Question: What did the code read ? Code: def read_file(filename): path = os.path.abspath(os.path.dirname(__file__)) filepath = os.path.join(path, filename) try: return open(filepath).read() except IOError: return ''
null
null
null
What does the code return ?
def GetIncludedBuildFiles(build_file_path, aux_data, included=None): if (included == None): included = [] if (build_file_path in included): return included included.append(build_file_path) for included_build_file in aux_data[build_file_path].get('included', []): GetIncludedBuildFiles(included_build_file, aux_data, included) return included
null
null
null
a list of all build files included into build_file_path
codeqa
def Get Included Build Files build file path aux data included None if included None included []if build file path in included return includedincluded append build file path for included build file in aux data[build file path] get 'included' [] Get Included Build Files included build file aux data included return included
null
null
null
null
Question: What does the code return ? Code: def GetIncludedBuildFiles(build_file_path, aux_data, included=None): if (included == None): included = [] if (build_file_path in included): return included included.append(build_file_path) for included_build_file in aux_data[build_file_path].get('included', []): GetIncludedBuildFiles(included_build_file, aux_data, included) return included
null
null
null
What does the code delete from a security group ?
@utils.arg('secgroup', metavar='<secgroup>', help=_('ID or name of security group.')) @utils.arg('ip_proto', metavar='<ip-proto>', help=_('IP protocol (icmp, tcp, udp).')) @utils.arg('from_port', metavar='<from-port>', help=_('Port at start of range.')) @utils.arg('to_port', metavar='<to-port>', help=_('Port at end of range.')) @utils.arg('cidr', metavar='<cidr>', help=_('CIDR for address range.')) @deprecated_network def do_secgroup_delete_rule(cs, args): secgroup = _get_secgroup(cs, args.secgroup) for rule in secgroup.rules: if (rule['ip_protocol'] and (rule['ip_protocol'].upper() == args.ip_proto.upper()) and (rule['from_port'] == int(args.from_port)) and (rule['to_port'] == int(args.to_port)) and (rule['ip_range']['cidr'] == args.cidr)): _print_secgroup_rules([rule]) return cs.security_group_rules.delete(rule['id']) raise exceptions.CommandError(_('Rule not found'))
null
null
null
a rule
codeqa
@utils arg 'secgroup' metavar '<secgroup>' help 'I Dornameofsecuritygroup ' @utils arg 'ip proto' metavar '<ip-proto>' help 'I Pprotocol icmp tcp udp ' @utils arg 'from port' metavar '<from-port>' help ' Portatstartofrange ' @utils arg 'to port' metavar '<to-port>' help ' Portatendofrange ' @utils arg 'cidr' metavar '<cidr>' help 'CID Rforaddressrange ' @deprecated networkdef do secgroup delete rule cs args secgroup get secgroup cs args secgroup for rule in secgroup rules if rule['ip protocol'] and rule['ip protocol'] upper args ip proto upper and rule['from port'] int args from port and rule['to port'] int args to port and rule['ip range']['cidr'] args cidr print secgroup rules [rule] return cs security group rules delete rule['id'] raise exceptions Command Error ' Rulenotfound'
null
null
null
null
Question: What does the code delete from a security group ? Code: @utils.arg('secgroup', metavar='<secgroup>', help=_('ID or name of security group.')) @utils.arg('ip_proto', metavar='<ip-proto>', help=_('IP protocol (icmp, tcp, udp).')) @utils.arg('from_port', metavar='<from-port>', help=_('Port at start of range.')) @utils.arg('to_port', metavar='<to-port>', help=_('Port at end of range.')) @utils.arg('cidr', metavar='<cidr>', help=_('CIDR for address range.')) @deprecated_network def do_secgroup_delete_rule(cs, args): secgroup = _get_secgroup(cs, args.secgroup) for rule in secgroup.rules: if (rule['ip_protocol'] and (rule['ip_protocol'].upper() == args.ip_proto.upper()) and (rule['from_port'] == int(args.from_port)) and (rule['to_port'] == int(args.to_port)) and (rule['ip_range']['cidr'] == args.cidr)): _print_secgroup_rules([rule]) return cs.security_group_rules.delete(rule['id']) raise exceptions.CommandError(_('Rule not found'))
null
null
null
What calls it ?
def wait_script(name, source=None, template=None, onlyif=None, unless=None, cwd=None, runas=None, shell=None, env=None, stateful=False, umask=None, use_vt=False, output_loglevel='debug', **kwargs): if (('user' in kwargs) or ('group' in kwargs)): salt.utils.warn_until('Oxygen', 'The legacy user/group arguments are deprecated. Replace them with runas. These arguments will be removed in Salt Oxygen.') if (('user' in kwargs) and (kwargs['user'] is not None) and (runas is None)): runas = kwargs.pop('user') return {'name': name, 'changes': {}, 'result': True, 'comment': ''}
null
null
null
a watch statement
codeqa
def wait script name source None template None onlyif None unless None cwd None runas None shell None env None stateful False umask None use vt False output loglevel 'debug' **kwargs if 'user' in kwargs or 'group' in kwargs salt utils warn until ' Oxygen' ' Thelegacyuser/groupargumentsaredeprecated Replacethemwithrunas Theseargumentswillberemovedin Salt Oxygen ' if 'user' in kwargs and kwargs['user'] is not None and runas is None runas kwargs pop 'user' return {'name' name 'changes' {} 'result' True 'comment' ''}
null
null
null
null
Question: What calls it ? Code: def wait_script(name, source=None, template=None, onlyif=None, unless=None, cwd=None, runas=None, shell=None, env=None, stateful=False, umask=None, use_vt=False, output_loglevel='debug', **kwargs): if (('user' in kwargs) or ('group' in kwargs)): salt.utils.warn_until('Oxygen', 'The legacy user/group arguments are deprecated. Replace them with runas. These arguments will be removed in Salt Oxygen.') if (('user' in kwargs) and (kwargs['user'] is not None) and (runas is None)): runas = kwargs.pop('user') return {'name': name, 'changes': {}, 'result': True, 'comment': ''}
null
null
null
What does the code convert to a chronologically - sortable key ?
def parse_version(s): parts = [] for part in _parse_version_parts(s.lower()): if part.startswith('*'): if (part < '*final'): while (parts and (parts[(-1)] == '*final-')): parts.pop() while (parts and (parts[(-1)] == '00000000')): parts.pop() parts.append(part) return tuple(parts)
null
null
null
a version string
codeqa
def parse version s parts []for part in parse version parts s lower if part startswith '*' if part < '*final' while parts and parts[ -1 ] '*final-' parts pop while parts and parts[ -1 ] '00000000 ' parts pop parts append part return tuple parts
null
null
null
null
Question: What does the code convert to a chronologically - sortable key ? Code: def parse_version(s): parts = [] for part in _parse_version_parts(s.lower()): if part.startswith('*'): if (part < '*final'): while (parts and (parts[(-1)] == '*final-')): parts.pop() while (parts and (parts[(-1)] == '00000000')): parts.pop() parts.append(part) return tuple(parts)
null
null
null
When did request buffer ?
def httpconnection_patched_send_output(self, message_body=None): self._buffer.extend(('', '')) msg = '\r\n'.join(self._buffer) del self._buffer[:] if isinstance(message_body, str): msg += message_body message_body = None self.send(msg) if (message_body is not None): self.send(message_body)
null
null
null
currently
codeqa
def httpconnection patched send output self message body None self buffer extend '' '' msg '\r\n' join self buffer del self buffer[ ]if isinstance message body str msg + message bodymessage body Noneself send msg if message body is not None self send message body
null
null
null
null
Question: When did request buffer ? Code: def httpconnection_patched_send_output(self, message_body=None): self._buffer.extend(('', '')) msg = '\r\n'.join(self._buffer) del self._buffer[:] if isinstance(message_body, str): msg += message_body message_body = None self.send(msg) if (message_body is not None): self.send(message_body)
null
null
null
What does the code clear ?
def httpconnection_patched_send_output(self, message_body=None): self._buffer.extend(('', '')) msg = '\r\n'.join(self._buffer) del self._buffer[:] if isinstance(message_body, str): msg += message_body message_body = None self.send(msg) if (message_body is not None): self.send(message_body)
null
null
null
the buffer
codeqa
def httpconnection patched send output self message body None self buffer extend '' '' msg '\r\n' join self buffer del self buffer[ ]if isinstance message body str msg + message bodymessage body Noneself send msg if message body is not None self send message body
null
null
null
null
Question: What does the code clear ? Code: def httpconnection_patched_send_output(self, message_body=None): self._buffer.extend(('', '')) msg = '\r\n'.join(self._buffer) del self._buffer[:] if isinstance(message_body, str): msg += message_body message_body = None self.send(msg) if (message_body is not None): self.send(message_body)
null
null
null
What does the code send ?
def httpconnection_patched_send_output(self, message_body=None): self._buffer.extend(('', '')) msg = '\r\n'.join(self._buffer) del self._buffer[:] if isinstance(message_body, str): msg += message_body message_body = None self.send(msg) if (message_body is not None): self.send(message_body)
null
null
null
the currently buffered request
codeqa
def httpconnection patched send output self message body None self buffer extend '' '' msg '\r\n' join self buffer del self buffer[ ]if isinstance message body str msg + message bodymessage body Noneself send msg if message body is not None self send message body
null
null
null
null
Question: What does the code send ? Code: def httpconnection_patched_send_output(self, message_body=None): self._buffer.extend(('', '')) msg = '\r\n'.join(self._buffer) del self._buffer[:] if isinstance(message_body, str): msg += message_body message_body = None self.send(msg) if (message_body is not None): self.send(message_body)
null
null
null
How do print exit ?
def usage(): parser.print_help() sys.exit(2)
null
null
null
with an error code
codeqa
def usage parser print help sys exit 2
null
null
null
null
Question: How do print exit ? Code: def usage(): parser.print_help() sys.exit(2)
null
null
null
What extracts from sugar / version ?
def extract_version(): with open(pjoin('zmq', 'sugar', 'version.py')) as f: while True: line = f.readline() if line.startswith('VERSION'): lines = [] while (line and (not line.startswith('def'))): lines.append(line) line = f.readline() break ns = {} exec ''.join(lines) in ns return ns['__version__']
null
null
null
pyzmq version
codeqa
def extract version with open pjoin 'zmq' 'sugar' 'version py' as f while True line f readline if line startswith 'VERSION' lines []while line and not line startswith 'def' lines append line line f readline breakns {}exec '' join lines in nsreturn ns[' version ']
null
null
null
null
Question: What extracts from sugar / version ? Code: def extract_version(): with open(pjoin('zmq', 'sugar', 'version.py')) as f: while True: line = f.readline() if line.startswith('VERSION'): lines = [] while (line and (not line.startswith('def'))): lines.append(line) line = f.readline() break ns = {} exec ''.join(lines) in ns return ns['__version__']
null
null
null
What encapsulates a boundary ?
def parse_boundary_stream(stream, max_header_size): chunk = stream.read(max_header_size) header_end = chunk.find('\r\n\r\n') def _parse_header(line): (main_value_pair, params) = parse_header(line) try: (name, value) = main_value_pair.split(u':', 1) except: raise ValueError((u'Invalid header: %r' % line)) return (name, (value, params)) if (header_end == (-1)): stream.unget(chunk) return (RAW, {}, stream) header = chunk[:header_end] stream.unget(chunk[(header_end + 4):]) TYPE = RAW outdict = {} for line in header.split('\r\n'): try: (name, (value, params)) = _parse_header(line) except: continue if (name == u'content-disposition'): TYPE = FIELD if params.get(u'filename'): TYPE = FILE outdict[name] = (value, params) if (TYPE == RAW): stream.unget(chunk) return (TYPE, outdict, stream)
null
null
null
exactly one stream
codeqa
def parse boundary stream stream max header size chunk stream read max header size header end chunk find '\r\n\r\n' def parse header line main value pair params parse header line try name value main value pair split u' ' 1 except raise Value Error u' Invalidheader %r' % line return name value params if header end -1 stream unget chunk return RAW {} stream header chunk[ header end]stream unget chunk[ header end + 4 ] TYPE RA Woutdict {}for line in header split '\r\n' try name value params parse header line except continueif name u'content-disposition' TYPE FIEL Dif params get u'filename' TYPE FIL Eoutdict[name] value params if TYPE RAW stream unget chunk return TYPE outdict stream
null
null
null
null
Question: What encapsulates a boundary ? Code: def parse_boundary_stream(stream, max_header_size): chunk = stream.read(max_header_size) header_end = chunk.find('\r\n\r\n') def _parse_header(line): (main_value_pair, params) = parse_header(line) try: (name, value) = main_value_pair.split(u':', 1) except: raise ValueError((u'Invalid header: %r' % line)) return (name, (value, params)) if (header_end == (-1)): stream.unget(chunk) return (RAW, {}, stream) header = chunk[:header_end] stream.unget(chunk[(header_end + 4):]) TYPE = RAW outdict = {} for line in header.split('\r\n'): try: (name, (value, params)) = _parse_header(line) except: continue if (name == u'content-disposition'): TYPE = FIELD if params.get(u'filename'): TYPE = FILE outdict[name] = (value, params) if (TYPE == RAW): stream.unget(chunk) return (TYPE, outdict, stream)
null
null
null
What does exactly one stream encapsulate ?
def parse_boundary_stream(stream, max_header_size): chunk = stream.read(max_header_size) header_end = chunk.find('\r\n\r\n') def _parse_header(line): (main_value_pair, params) = parse_header(line) try: (name, value) = main_value_pair.split(u':', 1) except: raise ValueError((u'Invalid header: %r' % line)) return (name, (value, params)) if (header_end == (-1)): stream.unget(chunk) return (RAW, {}, stream) header = chunk[:header_end] stream.unget(chunk[(header_end + 4):]) TYPE = RAW outdict = {} for line in header.split('\r\n'): try: (name, (value, params)) = _parse_header(line) except: continue if (name == u'content-disposition'): TYPE = FIELD if params.get(u'filename'): TYPE = FILE outdict[name] = (value, params) if (TYPE == RAW): stream.unget(chunk) return (TYPE, outdict, stream)
null
null
null
a boundary
codeqa
def parse boundary stream stream max header size chunk stream read max header size header end chunk find '\r\n\r\n' def parse header line main value pair params parse header line try name value main value pair split u' ' 1 except raise Value Error u' Invalidheader %r' % line return name value params if header end -1 stream unget chunk return RAW {} stream header chunk[ header end]stream unget chunk[ header end + 4 ] TYPE RA Woutdict {}for line in header split '\r\n' try name value params parse header line except continueif name u'content-disposition' TYPE FIEL Dif params get u'filename' TYPE FIL Eoutdict[name] value params if TYPE RAW stream unget chunk return TYPE outdict stream
null
null
null
null
Question: What does exactly one stream encapsulate ? Code: def parse_boundary_stream(stream, max_header_size): chunk = stream.read(max_header_size) header_end = chunk.find('\r\n\r\n') def _parse_header(line): (main_value_pair, params) = parse_header(line) try: (name, value) = main_value_pair.split(u':', 1) except: raise ValueError((u'Invalid header: %r' % line)) return (name, (value, params)) if (header_end == (-1)): stream.unget(chunk) return (RAW, {}, stream) header = chunk[:header_end] stream.unget(chunk[(header_end + 4):]) TYPE = RAW outdict = {} for line in header.split('\r\n'): try: (name, (value, params)) = _parse_header(line) except: continue if (name == u'content-disposition'): TYPE = FIELD if params.get(u'filename'): TYPE = FILE outdict[name] = (value, params) if (TYPE == RAW): stream.unget(chunk) return (TYPE, outdict, stream)
null
null
null
How does a file or a directory upload ?
def upload(conn, localpath, remotepath, *a, **k): if os.path.isdir(localpath): upload_dir(conn, localpath, remotepath, *a, **k) elif os.path.isfile(localpath): upload_file(conn, localpath, remotepath, *a, **k) else: raise UploadError('can only upload files or directories')
null
null
null
recursively
codeqa
def upload conn localpath remotepath *a **k if os path isdir localpath upload dir conn localpath remotepath *a **k elif os path isfile localpath upload file conn localpath remotepath *a **k else raise Upload Error 'canonlyuploadfilesordirectories'
null
null
null
null
Question: How does a file or a directory upload ? Code: def upload(conn, localpath, remotepath, *a, **k): if os.path.isdir(localpath): upload_dir(conn, localpath, remotepath, *a, **k) elif os.path.isfile(localpath): upload_file(conn, localpath, remotepath, *a, **k) else: raise UploadError('can only upload files or directories')
null
null
null
What does the code return ?
def bold(text): return u''.join([CONTROL_BOLD, text, CONTROL_BOLD])
null
null
null
the text
codeqa
def bold text return u'' join [CONTROL BOLD text CONTROL BOLD]
null
null
null
null
Question: What does the code return ? Code: def bold(text): return u''.join([CONTROL_BOLD, text, CONTROL_BOLD])
null
null
null
How do all python source files yield below the given paths ?
def walk_python_files(paths, is_python=looks_like_python, exclude_dirs=None): if (exclude_dirs is None): exclude_dirs = [] for path in paths: print_debug(('testing: %s' % path)) if os.path.isfile(path): if is_python(path): (yield path) elif os.path.isdir(path): print_debug(' it is a directory') for (dirpath, dirnames, filenames) in os.walk(path): for exclude in exclude_dirs: if (exclude in dirnames): dirnames.remove(exclude) for filename in filenames: fullpath = os.path.join(dirpath, filename) print_debug(('testing: %s' % fullpath)) if is_python(fullpath): (yield fullpath) else: print_debug(' unknown type')
null
null
null
recursively
codeqa
def walk python files paths is python looks like python exclude dirs None if exclude dirs is None exclude dirs []for path in paths print debug 'testing %s' % path if os path isfile path if is python path yield path elif os path isdir path print debug 'itisadirectory' for dirpath dirnames filenames in os walk path for exclude in exclude dirs if exclude in dirnames dirnames remove exclude for filename in filenames fullpath os path join dirpath filename print debug 'testing %s' % fullpath if is python fullpath yield fullpath else print debug 'unknowntype'
null
null
null
null
Question: How do all python source files yield below the given paths ? Code: def walk_python_files(paths, is_python=looks_like_python, exclude_dirs=None): if (exclude_dirs is None): exclude_dirs = [] for path in paths: print_debug(('testing: %s' % path)) if os.path.isfile(path): if is_python(path): (yield path) elif os.path.isdir(path): print_debug(' it is a directory') for (dirpath, dirnames, filenames) in os.walk(path): for exclude in exclude_dirs: if (exclude in dirnames): dirnames.remove(exclude) for filename in filenames: fullpath = os.path.join(dirpath, filename) print_debug(('testing: %s' % fullpath)) if is_python(fullpath): (yield fullpath) else: print_debug(' unknown type')
null
null
null
When are the values of the array are positive ?
def expln(x): def f(val): if (val < 0): return exp(val) else: return (log((val + 1.0)) + 1) try: result = array(list(map(f, x))) except TypeError: result = array(f(x)) return result
null
null
null
always
codeqa
def expln x def f val if val < 0 return exp val else return log val + 1 0 + 1 try result array list map f x except Type Error result array f x return result
null
null
null
null
Question: When are the values of the array are positive ? Code: def expln(x): def f(val): if (val < 0): return exp(val) else: return (log((val + 1.0)) + 1) try: result = array(list(map(f, x))) except TypeError: result = array(f(x)) return result
null
null
null
What ensures that the values of the array are always positive ?
def expln(x): def f(val): if (val < 0): return exp(val) else: return (log((val + 1.0)) + 1) try: result = array(list(map(f, x))) except TypeError: result = array(f(x)) return result
null
null
null
this continuous function
codeqa
def expln x def f val if val < 0 return exp val else return log val + 1 0 + 1 try result array list map f x except Type Error result array f x return result
null
null
null
null
Question: What ensures that the values of the array are always positive ? Code: def expln(x): def f(val): if (val < 0): return exp(val) else: return (log((val + 1.0)) + 1) try: result = array(list(map(f, x))) except TypeError: result = array(f(x)) return result
null
null
null
What does this continuous function ensure ?
def expln(x): def f(val): if (val < 0): return exp(val) else: return (log((val + 1.0)) + 1) try: result = array(list(map(f, x))) except TypeError: result = array(f(x)) return result
null
null
null
that the values of the array are always positive
codeqa
def expln x def f val if val < 0 return exp val else return log val + 1 0 + 1 try result array list map f x except Type Error result array f x return result
null
null
null
null
Question: What does this continuous function ensure ? Code: def expln(x): def f(val): if (val < 0): return exp(val) else: return (log((val + 1.0)) + 1) try: result = array(list(map(f, x))) except TypeError: result = array(f(x)) return result
null
null
null
What does the code require ?
def _resolve_fork_relationships(workflow): def helper(workflow, node, last_fork): if isinstance(node, Fork): join = None children = node.get_children() for child in children: join = (helper(workflow, child.get_full_node(), node) or join) link = Link(name='related', parent=node, child=join) link.save() node = join elif isinstance(node, Join): return node join = None children = node.get_children() for child in children: join = (helper(workflow, child.get_full_node(), last_fork) or join) return join helper(workflow, workflow.start.get_full_node(), None)
null
null
null
proper workflow structure
codeqa
def resolve fork relationships workflow def helper workflow node last fork if isinstance node Fork join Nonechildren node get children for child in children join helper workflow child get full node node or join link Link name 'related' parent node child join link save node joinelif isinstance node Join return nodejoin Nonechildren node get children for child in children join helper workflow child get full node last fork or join return joinhelper workflow workflow start get full node None
null
null
null
null
Question: What does the code require ? Code: def _resolve_fork_relationships(workflow): def helper(workflow, node, last_fork): if isinstance(node, Fork): join = None children = node.get_children() for child in children: join = (helper(workflow, child.get_full_node(), node) or join) link = Link(name='related', parent=node, child=join) link.save() node = join elif isinstance(node, Join): return node join = None children = node.get_children() for child in children: join = (helper(workflow, child.get_full_node(), last_fork) or join) return join helper(workflow, workflow.start.get_full_node(), None)
null
null
null
How do a directory tree copy ?
def copytree(src, dst, use_hardlink=False): names = os.listdir(src) try: os.makedirs(dst) except OSError as why: if (u'File exists' in why): pass else: raise why errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if os.path.isdir(srcname): copytree(srcname, dstname, use_hardlink) else: copyfile(srcname, dstname, True, hashmethod=u'content', use_hardlink=use_hardlink) except (IOError, os.error) as why: errors.append((srcname, dstname, str(why))) except Exception as err: errors.extend(err.args[0]) if errors: raise Exception(errors)
null
null
null
recursively
codeqa
def copytree src dst use hardlink False names os listdir src try os makedirs dst except OS Error as why if u' Fileexists' in why passelse raise whyerrors []for name in names srcname os path join src name dstname os path join dst name try if os path isdir srcname copytree srcname dstname use hardlink else copyfile srcname dstname True hashmethod u'content' use hardlink use hardlink except IO Error os error as why errors append srcname dstname str why except Exception as err errors extend err args[ 0 ] if errors raise Exception errors
null
null
null
null
Question: How do a directory tree copy ? Code: def copytree(src, dst, use_hardlink=False): names = os.listdir(src) try: os.makedirs(dst) except OSError as why: if (u'File exists' in why): pass else: raise why errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if os.path.isdir(srcname): copytree(srcname, dstname, use_hardlink) else: copyfile(srcname, dstname, True, hashmethod=u'content', use_hardlink=use_hardlink) except (IOError, os.error) as why: errors.append((srcname, dstname, str(why))) except Exception as err: errors.extend(err.args[0]) if errors: raise Exception(errors)
null
null
null
What describe its properties ?
def describe_function(FunctionName, region=None, key=None, keyid=None, profile=None): try: func = _find_function(FunctionName, region=region, key=key, keyid=keyid, profile=profile) if func: keys = ('FunctionName', 'Runtime', 'Role', 'Handler', 'CodeSha256', 'CodeSize', 'Description', 'Timeout', 'MemorySize', 'FunctionArn', 'LastModified', 'VpcConfig') return {'function': dict([(k, func.get(k)) for k in keys])} else: return {'function': None} except ClientError as e: return {'error': salt.utils.boto3.get_error(e)}
null
null
null
a function name
codeqa
def describe function Function Name region None key None keyid None profile None try func find function Function Name region region key key keyid keyid profile profile if func keys ' Function Name' ' Runtime' ' Role' ' Handler' ' Code Sha 256 ' ' Code Size' ' Description' ' Timeout' ' Memory Size' ' Function Arn' ' Last Modified' ' Vpc Config' return {'function' dict [ k func get k for k in keys] }else return {'function' None}except Client Error as e return {'error' salt utils boto 3 get error e }
null
null
null
null
Question: What describe its properties ? Code: def describe_function(FunctionName, region=None, key=None, keyid=None, profile=None): try: func = _find_function(FunctionName, region=region, key=key, keyid=keyid, profile=profile) if func: keys = ('FunctionName', 'Runtime', 'Role', 'Handler', 'CodeSha256', 'CodeSize', 'Description', 'Timeout', 'MemorySize', 'FunctionArn', 'LastModified', 'VpcConfig') return {'function': dict([(k, func.get(k)) for k in keys])} else: return {'function': None} except ClientError as e: return {'error': salt.utils.boto3.get_error(e)}
null
null
null
What found in text ?
def email_split(text): if (not text): return [] return [addr[1] for addr in getaddresses([text]) if addr[1] if ('@' in addr[1])]
null
null
null
the email addresses
codeqa
def email split text if not text return []return [addr[ 1 ] for addr in getaddresses [text] if addr[ 1 ] if '@' in addr[ 1 ] ]
null
null
null
null
Question: What found in text ? Code: def email_split(text): if (not text): return [] return [addr[1] for addr in getaddresses([text]) if addr[1] if ('@' in addr[1])]
null
null
null
Where did the email addresses find ?
def email_split(text): if (not text): return [] return [addr[1] for addr in getaddresses([text]) if addr[1] if ('@' in addr[1])]
null
null
null
in text
codeqa
def email split text if not text return []return [addr[ 1 ] for addr in getaddresses [text] if addr[ 1 ] if '@' in addr[ 1 ] ]
null
null
null
null
Question: Where did the email addresses find ? Code: def email_split(text): if (not text): return [] return [addr[1] for addr in getaddresses([text]) if addr[1] if ('@' in addr[1])]
null
null
null
What does the code combine ?
def revision_links(obj): return combine_funcs(obj, (current_revision_link, related_revisions_link))
null
null
null
the revision nav links
codeqa
def revision links obj return combine funcs obj current revision link related revisions link
null
null
null
null
Question: What does the code combine ? Code: def revision_links(obj): return combine_funcs(obj, (current_revision_link, related_revisions_link))
null
null
null
What does the code ensure ?
def _assert_required_roles(cls, roles, methods): if (('appender' not in roles) or (not hasattr(cls, roles['appender']))): raise sa_exc.ArgumentError(('Type %s must elect an appender method to be a collection class' % cls.__name__)) elif ((roles['appender'] not in methods) and (not hasattr(getattr(cls, roles['appender']), '_sa_instrumented'))): methods[roles['appender']] = ('fire_append_event', 1, None) if (('remover' not in roles) or (not hasattr(cls, roles['remover']))): raise sa_exc.ArgumentError(('Type %s must elect a remover method to be a collection class' % cls.__name__)) elif ((roles['remover'] not in methods) and (not hasattr(getattr(cls, roles['remover']), '_sa_instrumented'))): methods[roles['remover']] = ('fire_remove_event', 1, None) if (('iterator' not in roles) or (not hasattr(cls, roles['iterator']))): raise sa_exc.ArgumentError(('Type %s must elect an iterator method to be a collection class' % cls.__name__))
null
null
null
all roles are present
codeqa
def assert required roles cls roles methods if 'appender' not in roles or not hasattr cls roles['appender'] raise sa exc Argument Error ' Type%smustelectanappendermethodtobeacollectionclass' % cls name elif roles['appender'] not in methods and not hasattr getattr cls roles['appender'] ' sa instrumented' methods[roles['appender']] 'fire append event' 1 None if 'remover' not in roles or not hasattr cls roles['remover'] raise sa exc Argument Error ' Type%smustelectaremovermethodtobeacollectionclass' % cls name elif roles['remover'] not in methods and not hasattr getattr cls roles['remover'] ' sa instrumented' methods[roles['remover']] 'fire remove event' 1 None if 'iterator' not in roles or not hasattr cls roles['iterator'] raise sa exc Argument Error ' Type%smustelectaniteratormethodtobeacollectionclass' % cls name
null
null
null
null
Question: What does the code ensure ? Code: def _assert_required_roles(cls, roles, methods): if (('appender' not in roles) or (not hasattr(cls, roles['appender']))): raise sa_exc.ArgumentError(('Type %s must elect an appender method to be a collection class' % cls.__name__)) elif ((roles['appender'] not in methods) and (not hasattr(getattr(cls, roles['appender']), '_sa_instrumented'))): methods[roles['appender']] = ('fire_append_event', 1, None) if (('remover' not in roles) or (not hasattr(cls, roles['remover']))): raise sa_exc.ArgumentError(('Type %s must elect a remover method to be a collection class' % cls.__name__)) elif ((roles['remover'] not in methods) and (not hasattr(getattr(cls, roles['remover']), '_sa_instrumented'))): methods[roles['remover']] = ('fire_remove_event', 1, None) if (('iterator' not in roles) or (not hasattr(cls, roles['iterator']))): raise sa_exc.ArgumentError(('Type %s must elect an iterator method to be a collection class' % cls.__name__))
null
null
null
What does the code handle ?
def handle_socks4_negotiation(sock, username=None): received_version = sock.recv(1) command = sock.recv(1) port = _read_exactly(sock, 2) port = ((ord(port[0:1]) << 8) + ord(port[1:2])) addr = _read_exactly(sock, 4) provided_username = _read_until(sock, '\x00')[:(-1)] if (addr == '\x00\x00\x00\x01'): addr = _read_until(sock, '\x00')[:(-1)] else: addr = socket.inet_ntoa(addr) assert (received_version == SOCKS_VERSION_SOCKS4) assert (command == '\x01') if ((username is not None) and (username != provided_username)): sock.sendall('\x00]\x00\x00\x00\x00\x00\x00') sock.close() (yield False) return succeed = (yield (addr, port)) if succeed: response = '\x00Z\xea`\x7f\x00\x00\x01' else: response = '\x00[\x00\x00\x00\x00\x00\x00' sock.sendall(response) (yield True)
null
null
null
the socks4 handshake
codeqa
def handle socks 4 negotiation sock username None received version sock recv 1 command sock recv 1 port read exactly sock 2 port ord port[ 0 1] << 8 + ord port[ 1 2] addr read exactly sock 4 provided username read until sock '\x 00 ' [ -1 ]if addr '\x 00 \x 00 \x 00 \x 01 ' addr read until sock '\x 00 ' [ -1 ]else addr socket inet ntoa addr assert received version SOCKS VERSION SOCKS 4 assert command '\x 01 ' if username is not None and username provided username sock sendall '\x 00 ]\x 00 \x 00 \x 00 \x 00 \x 00 \x 00 ' sock close yield False returnsucceed yield addr port if succeed response '\x 00 Z\xea`\x 7 f\x 00 \x 00 \x 01 'else response '\x 00 [\x 00 \x 00 \x 00 \x 00 \x 00 \x 00 'sock sendall response yield True
null
null
null
null
Question: What does the code handle ? Code: def handle_socks4_negotiation(sock, username=None): received_version = sock.recv(1) command = sock.recv(1) port = _read_exactly(sock, 2) port = ((ord(port[0:1]) << 8) + ord(port[1:2])) addr = _read_exactly(sock, 4) provided_username = _read_until(sock, '\x00')[:(-1)] if (addr == '\x00\x00\x00\x01'): addr = _read_until(sock, '\x00')[:(-1)] else: addr = socket.inet_ntoa(addr) assert (received_version == SOCKS_VERSION_SOCKS4) assert (command == '\x01') if ((username is not None) and (username != provided_username)): sock.sendall('\x00]\x00\x00\x00\x00\x00\x00') sock.close() (yield False) return succeed = (yield (addr, port)) if succeed: response = '\x00Z\xea`\x7f\x00\x00\x01' else: response = '\x00[\x00\x00\x00\x00\x00\x00' sock.sendall(response) (yield True)
null
null
null
What does the code manage ?
def _queue_manangement_worker(executor_reference, processes, pending_work_items, work_ids_queue, call_queue, result_queue, shutdown_process_event): while True: _add_call_item_to_queue(pending_work_items, work_ids_queue, call_queue) try: result_item = result_queue.get(block=True, timeout=0.1) except queue.Empty: executor = executor_reference() if (_shutdown or (executor is None) or executor._shutdown_thread): if (not pending_work_items): shutdown_process_event.set() for p in processes: p.join() return del executor else: work_item = pending_work_items[result_item.work_id] del pending_work_items[result_item.work_id] if result_item.exception: work_item.future.set_exception(result_item.exception) else: work_item.future.set_result(result_item.result)
null
null
null
the communication between this process and the worker processes
codeqa
def queue manangement worker executor reference processes pending work items work ids queue call queue result queue shutdown process event while True add call item to queue pending work items work ids queue call queue try result item result queue get block True timeout 0 1 except queue Empty executor executor reference if shutdown or executor is None or executor shutdown thread if not pending work items shutdown process event set for p in processes p join returndel executorelse work item pending work items[result item work id]del pending work items[result item work id]if result item exception work item future set exception result item exception else work item future set result result item result
null
null
null
null
Question: What does the code manage ? Code: def _queue_manangement_worker(executor_reference, processes, pending_work_items, work_ids_queue, call_queue, result_queue, shutdown_process_event): while True: _add_call_item_to_queue(pending_work_items, work_ids_queue, call_queue) try: result_item = result_queue.get(block=True, timeout=0.1) except queue.Empty: executor = executor_reference() if (_shutdown or (executor is None) or executor._shutdown_thread): if (not pending_work_items): shutdown_process_event.set() for p in processes: p.join() return del executor else: work_item = pending_work_items[result_item.work_id] del pending_work_items[result_item.work_id] if result_item.exception: work_item.future.set_exception(result_item.exception) else: work_item.future.set_result(result_item.result)
null
null
null
What does the code create ?
@skip('silverlight') def test_iteration_no_mutation_bad_hash(): import random class c(object, ): def __hash__(self): return int((random.random() * 200)) l = [c() for i in xrange(1000)] b = set(l) for x in b: pass
null
null
null
a set w/ objects with a bad hash
codeqa
@skip 'silverlight' def test iteration no mutation bad hash import randomclass c object def hash self return int random random * 200 l [c for i in xrange 1000 ]b set l for x in b pass
null
null
null
null
Question: What does the code create ? Code: @skip('silverlight') def test_iteration_no_mutation_bad_hash(): import random class c(object, ): def __hash__(self): return int((random.random() * 200)) l = [c() for i in xrange(1000)] b = set(l) for x in b: pass
null
null
null
What does the code ensure ?
def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs): return __salt__['pagerduty_util.resource_absent']('users', ['email', 'name', 'id'], profile, subdomain, api_key, **kwargs)
null
null
null
pagerduty user does not exist
codeqa
def absent profile 'pagerduty' subdomain None api key None **kwargs return salt ['pagerduty util resource absent'] 'users' ['email' 'name' 'id'] profile subdomain api key **kwargs
null
null
null
null
Question: What does the code ensure ? Code: def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs): return __salt__['pagerduty_util.resource_absent']('users', ['email', 'name', 'id'], profile, subdomain, api_key, **kwargs)
null
null
null
What does the code add to negatives ?
def addNegativesByDerivation(end, extrudeDerivation, negatives, radius, start, xmlElement): extrudeDerivation.offsetAlongDefault = [start, end] extrudeDerivation.tiltFollow = True extrudeDerivation.tiltTop = Vector3(0.0, 0.0, 1.0) extrudeDerivation.setToXMLElement(xmlElement.getCopyShallow()) extrude.addNegatives(extrudeDerivation, negatives, [getTeardropPathByEndStart(end, radius, start, xmlElement)])
null
null
null
teardrop drill hole
codeqa
def add Negatives By Derivation end extrude Derivation negatives radius start xml Element extrude Derivation offset Along Default [start end]extrude Derivation tilt Follow Trueextrude Derivation tilt Top Vector 3 0 0 0 0 1 0 extrude Derivation set To XML Element xml Element get Copy Shallow extrude add Negatives extrude Derivation negatives [get Teardrop Path By End Start end radius start xml Element ]
null
null
null
null
Question: What does the code add to negatives ? Code: def addNegativesByDerivation(end, extrudeDerivation, negatives, radius, start, xmlElement): extrudeDerivation.offsetAlongDefault = [start, end] extrudeDerivation.tiltFollow = True extrudeDerivation.tiltTop = Vector3(0.0, 0.0, 1.0) extrudeDerivation.setToXMLElement(xmlElement.getCopyShallow()) extrude.addNegatives(extrudeDerivation, negatives, [getTeardropPathByEndStart(end, radius, start, xmlElement)])
null
null
null
What does the code destroy ?
def destroy(name, call=None): if (call == 'function'): raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.') __utils__['cloud.fire_event']('event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport']) name = name.split('.')[0] node = show_instance(name, call='action') conn = get_conn(service='SoftLayer_Ticket') response = conn.createCancelServerTicket({'id': node['id'], 'reason': 'Salt Cloud Hardware Server Cancellation', 'content': 'Please cancel this server', 'cancelAssociatedItems': True, 'attachmentType': 'HARDWARE'}) __utils__['cloud.fire_event']('event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport']) if (__opts__.get('update_cachedir', False) is True): __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__) return response
null
null
null
a node
codeqa
def destroy name call None if call 'function' raise Salt Cloud System Exit ' Thedestroyactionmustbecalledwith-d --destroy -aor--action ' utils ['cloud fire event'] 'event' 'destroyinginstance' 'salt/cloud/{ 0 }/destroying' format name args {'name' name} sock dir opts ['sock dir'] transport opts ['transport'] name name split ' ' [0 ]node show instance name call 'action' conn get conn service ' Soft Layer Ticket' response conn create Cancel Server Ticket {'id' node['id'] 'reason' ' Salt Cloud Hardware Server Cancellation' 'content' ' Pleasecancelthisserver' 'cancel Associated Items' True 'attachment Type' 'HARDWARE'} utils ['cloud fire event'] 'event' 'destroyedinstance' 'salt/cloud/{ 0 }/destroyed' format name args {'name' name} sock dir opts ['sock dir'] transport opts ['transport'] if opts get 'update cachedir' False is True utils ['cloud delete minion cachedir'] name active provider name split ' ' [0 ] opts return response
null
null
null
null
Question: What does the code destroy ? Code: def destroy(name, call=None): if (call == 'function'): raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.') __utils__['cloud.fire_event']('event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport']) name = name.split('.')[0] node = show_instance(name, call='action') conn = get_conn(service='SoftLayer_Ticket') response = conn.createCancelServerTicket({'id': node['id'], 'reason': 'Salt Cloud Hardware Server Cancellation', 'content': 'Please cancel this server', 'cancelAssociatedItems': True, 'attachmentType': 'HARDWARE'}) __utils__['cloud.fire_event']('event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport']) if (__opts__.get('update_cachedir', False) is True): __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__) return response
null
null
null
What does the code get ?
def equatePolarDotAzimuth(point, returnValue): equateCylindricalDotAzimuth(point, returnValue)
null
null
null
equation for polar azimuth
codeqa
def equate Polar Dot Azimuth point return Value equate Cylindrical Dot Azimuth point return Value
null
null
null
null
Question: What does the code get ? Code: def equatePolarDotAzimuth(point, returnValue): equateCylindricalDotAzimuth(point, returnValue)
null
null
null
What does the code install ?
@task @log_call def install(): sudo(u'apt-get update -y -q') apt(u'nginx libjpeg-dev python-dev python-setuptools git-core postgresql libpq-dev memcached supervisor python-pip') run((u'mkdir -p /home/%s/logs' % env.user)) sudo(u'pip install -U pip virtualenv virtualenvwrapper mercurial') run((u'mkdir -p %s' % env.venv_home)) run((u"echo 'export WORKON_HOME=%s' >> /home/%s/.bashrc" % (env.venv_home, env.user))) run((u"echo 'source /usr/local/bin/virtualenvwrapper.sh' >> /home/%s/.bashrc" % env.user)) print(green(u'Successfully set up git, mercurial, pip, virtualenv, supervisor, memcached.', bold=True))
null
null
null
the base system and python requirements for the entire server
codeqa
@task@log calldef install sudo u'apt-getupdate-y-q' apt u'nginxlibjpeg-devpython-devpython-setuptoolsgit-corepostgresqllibpq-devmemcachedsupervisorpython-pip' run u'mkdir-p/home/%s/logs' % env user sudo u'pipinstall- Upipvirtualenvvirtualenvwrappermercurial' run u'mkdir-p%s' % env venv home run u"echo'export WORKON HOME %s'>>/home/%s/ bashrc" % env venv home env user run u"echo'source/usr/local/bin/virtualenvwrapper sh'>>/home/%s/ bashrc" % env user print green u' Successfullysetupgit mercurial pip virtualenv supervisor memcached ' bold True
null
null
null
null
Question: What does the code install ? Code: @task @log_call def install(): sudo(u'apt-get update -y -q') apt(u'nginx libjpeg-dev python-dev python-setuptools git-core postgresql libpq-dev memcached supervisor python-pip') run((u'mkdir -p /home/%s/logs' % env.user)) sudo(u'pip install -U pip virtualenv virtualenvwrapper mercurial') run((u'mkdir -p %s' % env.venv_home)) run((u"echo 'export WORKON_HOME=%s' >> /home/%s/.bashrc" % (env.venv_home, env.user))) run((u"echo 'source /usr/local/bin/virtualenvwrapper.sh' >> /home/%s/.bashrc" % env.user)) print(green(u'Successfully set up git, mercurial, pip, virtualenv, supervisor, memcached.', bold=True))
null
null
null
What does the code resolve ?
def resolve_order(reg, deps): x = [] for dep in deps[reg]: x.extend(resolve_order(dep, deps)) x.append(reg) return x
null
null
null
the order of all dependencies starting at a given register
codeqa
def resolve order reg deps x []for dep in deps[reg] x extend resolve order dep deps x append reg return x
null
null
null
null
Question: What does the code resolve ? Code: def resolve_order(reg, deps): x = [] for dep in deps[reg]: x.extend(resolve_order(dep, deps)) x.append(reg) return x
null
null
null
What does the code update ?
def update(filename, data, *args, **kwargs): if (args and isinstance(args[0], Header)): header = args[0] args = args[1:] else: header = None header = kwargs.pop('header', header) new_hdu = _makehdu(data, header) closed = fileobj_closed(filename) (hdulist, _ext) = _getext(filename, 'update', *args, **kwargs) try: hdulist[_ext] = new_hdu finally: hdulist._close(closed=closed)
null
null
null
the specified extension with the input data / header
codeqa
def update filename data *args **kwargs if args and isinstance args[ 0 ] Header header args[ 0 ]args args[ 1 ]else header Noneheader kwargs pop 'header' header new hdu makehdu data header closed fileobj closed filename hdulist ext getext filename 'update' *args **kwargs try hdulist[ ext] new hdufinally hdulist close closed closed
null
null
null
null
Question: What does the code update ? Code: def update(filename, data, *args, **kwargs): if (args and isinstance(args[0], Header)): header = args[0] args = args[1:] else: header = None header = kwargs.pop('header', header) new_hdu = _makehdu(data, header) closed = fileobj_closed(filename) (hdulist, _ext) = _getext(filename, 'update', *args, **kwargs) try: hdulist[_ext] = new_hdu finally: hdulist._close(closed=closed)
null
null
null
What does the code generate ?
def ext(external, pillar=None): if isinstance(external, six.string_types): external = yaml.safe_load(external) pillar_obj = salt.pillar.get_pillar(__opts__, __grains__, __opts__['id'], __opts__['environment'], ext=external, pillar=pillar) ret = pillar_obj.compile_pillar() return ret
null
null
null
the pillar
codeqa
def ext external pillar None if isinstance external six string types external yaml safe load external pillar obj salt pillar get pillar opts grains opts ['id'] opts ['environment'] ext external pillar pillar ret pillar obj compile pillar return ret
null
null
null
null
Question: What does the code generate ? Code: def ext(external, pillar=None): if isinstance(external, six.string_types): external = yaml.safe_load(external) pillar_obj = salt.pillar.get_pillar(__opts__, __grains__, __opts__['id'], __opts__['environment'], ext=external, pillar=pillar) ret = pillar_obj.compile_pillar() return ret
null
null
null
What do decorator print ?
def profile(func, stream=None): def wrapper(*args, **kwargs): prof = LineProfiler() val = prof(func)(*args, **kwargs) show_results(prof, stream=stream) return val return wrapper
null
null
null
a line - by - line profile
codeqa
def profile func stream None def wrapper *args **kwargs prof Line Profiler val prof func *args **kwargs show results prof stream stream return valreturn wrapper
null
null
null
null
Question: What do decorator print ? Code: def profile(func, stream=None): def wrapper(*args, **kwargs): prof = LineProfiler() val = prof(func)(*args, **kwargs) show_results(prof, stream=stream) return val return wrapper
null
null
null
What will run the function ?
def profile(func, stream=None): def wrapper(*args, **kwargs): prof = LineProfiler() val = prof(func)(*args, **kwargs) show_results(prof, stream=stream) return val return wrapper
null
null
null
decorator
codeqa
def profile func stream None def wrapper *args **kwargs prof Line Profiler val prof func *args **kwargs show results prof stream stream return valreturn wrapper
null
null
null
null
Question: What will run the function ? Code: def profile(func, stream=None): def wrapper(*args, **kwargs): prof = LineProfiler() val = prof(func)(*args, **kwargs) show_results(prof, stream=stream) return val return wrapper
null
null
null
How do last 5 items show ?
def blog(): def prep(r): s3db.configure(r.tablename, listadd=False) return True s3.prep = prep def postp(r, output): if r.record: response.view = s3base.S3CRUD._view(r, 'cms/blog.html') return output s3.postp = postp output = s3_rest_controller('cms', 'series') return output
null
null
null
only
codeqa
def blog def prep r s3 db configure r tablename listadd False return Trues 3 prep prepdef postp r output if r record response view s3 base S3 CRUD view r 'cms/blog html' return outputs 3 postp postpoutput s3 rest controller 'cms' 'series' return output
null
null
null
null
Question: How do last 5 items show ? Code: def blog(): def prep(r): s3db.configure(r.tablename, listadd=False) return True s3.prep = prep def postp(r, output): if r.record: response.view = s3base.S3CRUD._view(r, 'cms/blog.html') return output s3.postp = postp output = s3_rest_controller('cms', 'series') return output
null
null
null
What does this function construct ?
def DateFromTicks(ticks): return Date(*time.gmtime(ticks)[:3])
null
null
null
an object holding a date value from the given ticks value
codeqa
def Date From Ticks ticks return Date *time gmtime ticks [ 3]
null
null
null
null
Question: What does this function construct ? Code: def DateFromTicks(ticks): return Date(*time.gmtime(ticks)[:3])
null
null
null
What is holding a date value from the given ticks value ?
def DateFromTicks(ticks): return Date(*time.gmtime(ticks)[:3])
null
null
null
an object
codeqa
def Date From Ticks ticks return Date *time gmtime ticks [ 3]
null
null
null
null
Question: What is holding a date value from the given ticks value ? Code: def DateFromTicks(ticks): return Date(*time.gmtime(ticks)[:3])
null
null
null
When is stability counted ?
def populationStability(vectors, numSamples=None): numVectors = len(vectors) if (numSamples is None): numSamples = (numVectors - 1) countOn = range((numVectors - 1)) else: countOn = numpy.random.randint(0, (numVectors - 1), numSamples) sigmap = 0.0 for i in countOn: match = checkMatch(vectors[i], vectors[(i + 1)], sparse=False) if (match[1] != 0): sigmap += (float(match[0]) / match[1]) return (sigmap / numSamples)
null
null
null
time
codeqa
def population Stability vectors num Samples None num Vectors len vectors if num Samples is None num Samples num Vectors - 1 count On range num Vectors - 1 else count On numpy random randint 0 num Vectors - 1 num Samples sigmap 0 0for i in count On match check Match vectors[i] vectors[ i + 1 ] sparse False if match[ 1 ] 0 sigmap + float match[ 0 ] / match[ 1 ] return sigmap / num Samples
null
null
null
null
Question: When is stability counted ? Code: def populationStability(vectors, numSamples=None): numVectors = len(vectors) if (numSamples is None): numSamples = (numVectors - 1) countOn = range((numVectors - 1)) else: countOn = numpy.random.randint(0, (numVectors - 1), numSamples) sigmap = 0.0 for i in countOn: match = checkMatch(vectors[i], vectors[(i + 1)], sparse=False) if (match[1] != 0): sigmap += (float(match[0]) / match[1]) return (sigmap / numSamples)