labNo
float64
1
10
taskNo
float64
0
4
questioner
stringclasses
2 values
question
stringlengths
9
201
code
stringlengths
18
30.3k
startLine
float64
0
192
endLine
float64
0
196
questionType
stringclasses
4 values
answer
stringlengths
2
905
src
stringclasses
3 values
code_processed
stringlengths
12
28.3k
id
stringlengths
2
5
raw_code
stringlengths
20
30.3k
raw_comment
stringlengths
10
242
comment
stringlengths
9
207
q_code
stringlengths
66
30.3k
null
null
null
What does the figure preserve ?
def test_mpl_preserve_standard(): f = create_figure() exp = mplhooks.figure_to_rgb_array(f) (width, height) = f.canvas.get_width_height() s = mplhooks.figure_to_tight_array(f, (0.5 * width), (0.5 * height), False) obs = mplhooks.figure_to_rgb_array(f) plt.close(f) assert np.all((exp == obs))
null
null
null
height settings
codeqa
def test mpl preserve standard f create figure exp mplhooks figure to rgb array f width height f canvas get width height s mplhooks figure to tight array f 0 5 * width 0 5 * height False obs mplhooks figure to rgb array f plt close f assert np all exp obs
null
null
null
null
Question: What does the figure preserve ? Code: def test_mpl_preserve_standard(): f = create_figure() exp = mplhooks.figure_to_rgb_array(f) (width, height) = f.canvas.get_width_height() s = mplhooks.figure_to_tight_array(f, (0.5 * width), (0.5 * height), False) obs = mplhooks.figure_to_rgb_array(f) plt.close(f) assert np.all((exp == obs))
null
null
null
What can we extend ?
def is_image_extendable(image): LOG.debug('Checking if we can extend filesystem inside %(image)s.', {'image': image}) if ((not isinstance(image, imgmodel.LocalImage)) or (image.format != imgmodel.FORMAT_RAW)): fs = None try: fs = vfs.VFS.instance_for_image(image, None) fs.setup(mount=False) if (fs.get_image_fs() in SUPPORTED_FS_TO_EXTEND): return True except exception.NovaException as e: LOG.warning(_LW('Unable to mount image %(image)s with error %(error)s. Cannot resize.'), {'image': image, 'error': e}) finally: if (fs is not None): fs.teardown() return False else: try: utils.execute('e2label', image.path) except processutils.ProcessExecutionError as e: LOG.debug('Unable to determine label for image %(image)s with error %(error)s. Cannot resize.', {'image': image, 'error': e}) return False return True
null
null
null
the image
codeqa
def is image extendable image LOG debug ' Checkingifwecanextendfilesysteminside% image s ' {'image' image} if not isinstance image imgmodel Local Image or image format imgmodel FORMAT RAW fs Nonetry fs vfs VFS instance for image image None fs setup mount False if fs get image fs in SUPPORTED FS TO EXTEND return Trueexcept exception Nova Exception as e LOG warning LW ' Unabletomountimage% image switherror% error s Cannotresize ' {'image' image 'error' e} finally if fs is not None fs teardown return Falseelse try utils execute 'e 2 label' image path except processutils Process Execution Error as e LOG debug ' Unabletodeterminelabelforimage% image switherror% error s Cannotresize ' {'image' image 'error' e} return Falsereturn True
null
null
null
null
Question: What can we extend ? Code: def is_image_extendable(image): LOG.debug('Checking if we can extend filesystem inside %(image)s.', {'image': image}) if ((not isinstance(image, imgmodel.LocalImage)) or (image.format != imgmodel.FORMAT_RAW)): fs = None try: fs = vfs.VFS.instance_for_image(image, None) fs.setup(mount=False) if (fs.get_image_fs() in SUPPORTED_FS_TO_EXTEND): return True except exception.NovaException as e: LOG.warning(_LW('Unable to mount image %(image)s with error %(error)s. Cannot resize.'), {'image': image, 'error': e}) finally: if (fs is not None): fs.teardown() return False else: try: utils.execute('e2label', image.path) except processutils.ProcessExecutionError as e: LOG.debug('Unable to determine label for image %(image)s with error %(error)s. Cannot resize.', {'image': image, 'error': e}) return False return True
null
null
null
How should some of the curator methods not operate at once ?
def check_csv(value): if (type(value) is type(list())): return True string = False if (sys.version_info < (3, 0)): if (type(value) is type(unicode())): value = str(value) if (type(value) is type(str())): if (len(value.split(',')) > 1): return True else: return False else: raise TypeError('Passed value: {0} is not a list or a string but is of type {1}'.format(value, type(value)))
null
null
null
against multiple indices
codeqa
def check csv value if type value is type list return Truestring Falseif sys version info < 3 0 if type value is type unicode value str value if type value is type str if len value split ' ' > 1 return Trueelse return Falseelse raise Type Error ' Passedvalue {0 }isnotalistorastringbutisoftype{ 1 }' format value type value
null
null
null
null
Question: How should some of the curator methods not operate at once ? Code: def check_csv(value): if (type(value) is type(list())): return True string = False if (sys.version_info < (3, 0)): if (type(value) is type(unicode())): value = str(value) if (type(value) is type(str())): if (len(value.split(',')) > 1): return True else: return False else: raise TypeError('Passed value: {0} is not a list or a string but is of type {1}'.format(value, type(value)))
null
null
null
When should some of the curator methods not operate against multiple indices ?
def check_csv(value): if (type(value) is type(list())): return True string = False if (sys.version_info < (3, 0)): if (type(value) is type(unicode())): value = str(value) if (type(value) is type(str())): if (len(value.split(',')) > 1): return True else: return False else: raise TypeError('Passed value: {0} is not a list or a string but is of type {1}'.format(value, type(value)))
null
null
null
at once
codeqa
def check csv value if type value is type list return Truestring Falseif sys version info < 3 0 if type value is type unicode value str value if type value is type str if len value split ' ' > 1 return Trueelse return Falseelse raise Type Error ' Passedvalue {0 }isnotalistorastringbutisoftype{ 1 }' format value type value
null
null
null
null
Question: When should some of the curator methods not operate against multiple indices ? Code: def check_csv(value): if (type(value) is type(list())): return True string = False if (sys.version_info < (3, 0)): if (type(value) is type(unicode())): value = str(value) if (type(value) is type(str())): if (len(value.split(',')) > 1): return True else: return False else: raise TypeError('Passed value: {0} is not a list or a string but is of type {1}'.format(value, type(value)))
null
null
null
What do whose names contain ?
def tag_search(context, data_dict): (tags, count) = _tag_search(context, data_dict) return {'count': count, 'results': [_table_dictize(tag, context) for tag in tags]}
null
null
null
a given string
codeqa
def tag search context data dict tags count tag search context data dict return {'count' count 'results' [ table dictize tag context for tag in tags]}
null
null
null
null
Question: What do whose names contain ? Code: def tag_search(context, data_dict): (tags, count) = _tag_search(context, data_dict) return {'count': count, 'results': [_table_dictize(tag, context) for tag in tags]}
null
null
null
What contain a given string ?
def tag_search(context, data_dict): (tags, count) = _tag_search(context, data_dict) return {'count': count, 'results': [_table_dictize(tag, context) for tag in tags]}
null
null
null
whose names
codeqa
def tag search context data dict tags count tag search context data dict return {'count' count 'results' [ table dictize tag context for tag in tags]}
null
null
null
null
Question: What contain a given string ? Code: def tag_search(context, data_dict): (tags, count) = _tag_search(context, data_dict) return {'count': count, 'results': [_table_dictize(tag, context) for tag in tags]}
null
null
null
What does the code draw ?
def rectangle(win, uly, ulx, lry, lrx): win.vline((uly + 1), ulx, curses.ACS_VLINE, ((lry - uly) - 1)) win.hline(uly, (ulx + 1), curses.ACS_HLINE, ((lrx - ulx) - 1)) win.hline(lry, (ulx + 1), curses.ACS_HLINE, ((lrx - ulx) - 1)) win.vline((uly + 1), lrx, curses.ACS_VLINE, ((lry - uly) - 1)) win.addch(uly, ulx, curses.ACS_ULCORNER) win.addch(uly, lrx, curses.ACS_URCORNER) win.addch(lry, lrx, curses.ACS_LRCORNER) win.addch(lry, ulx, curses.ACS_LLCORNER)
null
null
null
a rectangle with corners at the provided upper - left and lower - right coordinates
codeqa
def rectangle win uly ulx lry lrx win vline uly + 1 ulx curses ACS VLINE lry - uly - 1 win hline uly ulx + 1 curses ACS HLINE lrx - ulx - 1 win hline lry ulx + 1 curses ACS HLINE lrx - ulx - 1 win vline uly + 1 lrx curses ACS VLINE lry - uly - 1 win addch uly ulx curses ACS ULCORNER win addch uly lrx curses ACS URCORNER win addch lry lrx curses ACS LRCORNER win addch lry ulx curses ACS LLCORNER
null
null
null
null
Question: What does the code draw ? Code: def rectangle(win, uly, ulx, lry, lrx): win.vline((uly + 1), ulx, curses.ACS_VLINE, ((lry - uly) - 1)) win.hline(uly, (ulx + 1), curses.ACS_HLINE, ((lrx - ulx) - 1)) win.hline(lry, (ulx + 1), curses.ACS_HLINE, ((lrx - ulx) - 1)) win.vline((uly + 1), lrx, curses.ACS_VLINE, ((lry - uly) - 1)) win.addch(uly, ulx, curses.ACS_ULCORNER) win.addch(uly, lrx, curses.ACS_URCORNER) win.addch(lry, lrx, curses.ACS_LRCORNER) win.addch(lry, ulx, curses.ACS_LLCORNER)
null
null
null
What does the code return ?
def ip_network(address, version=None, strict=True): if version: if (version == 4): return IPv4Network(address, strict) elif (version == 6): return IPv6Network(address, strict) try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError(('%r does not appear to be an IPv4 or IPv6 network' % address))
null
null
null
an object of the correct type
codeqa
def ip network address version None strict True if version if version 4 return I Pv 4 Network address strict elif version 6 return I Pv 6 Network address strict try return I Pv 4 Network address strict except Address Value Error Netmask Value Error passtry return I Pv 6 Network address strict except Address Value Error Netmask Value Error passraise Value Error '%rdoesnotappeartobean I Pv 4 or I Pv 6 network' % address
null
null
null
null
Question: What does the code return ? Code: def ip_network(address, version=None, strict=True): if version: if (version == 4): return IPv4Network(address, strict) elif (version == 6): return IPv6Network(address, strict) try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError(('%r does not appear to be an IPv4 or IPv6 network' % address))
null
null
null
What finds magnetometer coil types ?
def _get_T1T2_mag_inds(info): picks = pick_types(info, meg='mag') old_mag_inds = [] for ii in picks: ch = info['chs'][ii] if (ch['coil_type'] in (FIFF.FIFFV_COIL_VV_MAG_T1, FIFF.FIFFV_COIL_VV_MAG_T2)): old_mag_inds.append(ii) return old_mag_inds
null
null
null
helper
codeqa
def get T1 T 2 mag inds info picks pick types info meg 'mag' old mag inds []for ii in picks ch info['chs'][ii]if ch['coil type'] in FIFF FIFFV COIL VV MAG T1 FIFF FIFFV COIL VV MAG T2 old mag inds append ii return old mag inds
null
null
null
null
Question: What finds magnetometer coil types ? Code: def _get_T1T2_mag_inds(info): picks = pick_types(info, meg='mag') old_mag_inds = [] for ii in picks: ch = info['chs'][ii] if (ch['coil_type'] in (FIFF.FIFFV_COIL_VV_MAG_T1, FIFF.FIFFV_COIL_VV_MAG_T2)): old_mag_inds.append(ii) return old_mag_inds
null
null
null
What do helper find ?
def _get_T1T2_mag_inds(info): picks = pick_types(info, meg='mag') old_mag_inds = [] for ii in picks: ch = info['chs'][ii] if (ch['coil_type'] in (FIFF.FIFFV_COIL_VV_MAG_T1, FIFF.FIFFV_COIL_VV_MAG_T2)): old_mag_inds.append(ii) return old_mag_inds
null
null
null
magnetometer coil types
codeqa
def get T1 T 2 mag inds info picks pick types info meg 'mag' old mag inds []for ii in picks ch info['chs'][ii]if ch['coil type'] in FIFF FIFFV COIL VV MAG T1 FIFF FIFFV COIL VV MAG T2 old mag inds append ii return old mag inds
null
null
null
null
Question: What do helper find ? Code: def _get_T1T2_mag_inds(info): picks = pick_types(info, meg='mag') old_mag_inds = [] for ii in picks: ch = info['chs'][ii] if (ch['coil_type'] in (FIFF.FIFFV_COIL_VV_MAG_T1, FIFF.FIFFV_COIL_VV_MAG_T2)): old_mag_inds.append(ii) return old_mag_inds
null
null
null
When do a single listener disconnect from a blinker signal ?
@contextmanager def disconnected_from(signal, listener): signal.disconnect(listener) (yield) signal.connect(listener)
null
null
null
temporarily
codeqa
@contextmanagerdef disconnected from signal listener signal disconnect listener yield signal connect listener
null
null
null
null
Question: When do a single listener disconnect from a blinker signal ? Code: @contextmanager def disconnected_from(signal, listener): signal.disconnect(listener) (yield) signal.connect(listener)
null
null
null
How did the file name ?
def tailFile(filename, offset, length): try: with open(filename, 'rb') as f: overflow = False f.seek(0, 2) sz = f.tell() if (sz > (offset + length)): overflow = True offset = (sz - 1) if ((offset + length) > sz): if (offset > (sz - 1)): length = 0 offset = (sz - length) if (offset < 0): offset = 0 if (length < 0): length = 0 if (length == 0): data = '' else: f.seek(offset) data = f.read(length) offset = sz return [as_string(data), offset, overflow] except (OSError, IOError): return ['', offset, False]
null
null
null
by filename
codeqa
def tail File filename offset length try with open filename 'rb' as f overflow Falsef seek 0 2 sz f tell if sz > offset + length overflow Trueoffset sz - 1 if offset + length > sz if offset > sz - 1 length 0offset sz - length if offset < 0 offset 0if length < 0 length 0if length 0 data ''else f seek offset data f read length offset szreturn [as string data offset overflow]except OS Error IO Error return ['' offset False]
null
null
null
null
Question: How did the file name ? Code: def tailFile(filename, offset, length): try: with open(filename, 'rb') as f: overflow = False f.seek(0, 2) sz = f.tell() if (sz > (offset + length)): overflow = True offset = (sz - 1) if ((offset + length) > sz): if (offset > (sz - 1)): length = 0 offset = (sz - length) if (offset < 0): offset = 0 if (length < 0): length = 0 if (length == 0): data = '' else: f.seek(offset) data = f.read(length) offset = sz return [as_string(data), offset, overflow] except (OSError, IOError): return ['', offset, False]
null
null
null
What does the code evaluate ?
def getEvaluatedExpressionValue(elementNode, value): try: return getEvaluatedExpressionValueBySplitLine(elementNode, getEvaluatorSplitWords(value)) except: print 'Warning, in getEvaluatedExpressionValue in evaluate could not get a value for:' print value traceback.print_exc(file=sys.stdout) return None
null
null
null
the expression value
codeqa
def get Evaluated Expression Value element Node value try return get Evaluated Expression Value By Split Line element Node get Evaluator Split Words value except print ' Warning inget Evaluated Expression Valueinevaluatecouldnotgetavaluefor 'print valuetraceback print exc file sys stdout return None
null
null
null
null
Question: What does the code evaluate ? Code: def getEvaluatedExpressionValue(elementNode, value): try: return getEvaluatedExpressionValueBySplitLine(elementNode, getEvaluatorSplitWords(value)) except: print 'Warning, in getEvaluatedExpressionValue in evaluate could not get a value for:' print value traceback.print_exc(file=sys.stdout) return None
null
null
null
What does the code get from pillar if not passed ?
def _conn_info_check(infoblox_server=None, infoblox_user=None, infoblox_password=None): if (infoblox_server is None): infoblox_server = __salt__['pillar.get']('infoblox:server', None) if (infoblox_user is None): infoblox_user = __salt__['pillar.get']('infoblox:user', None) log.debug('Infoblox username is "{0}"'.format(infoblox_user)) if (infoblox_password is None): infoblox_password = __salt__['pillar.get']('infoblox:password', None) return (infoblox_server, infoblox_user, infoblox_password)
null
null
null
infoblox stuff
codeqa
def conn info check infoblox server None infoblox user None infoblox password None if infoblox server is None infoblox server salt ['pillar get'] 'infoblox server' None if infoblox user is None infoblox user salt ['pillar get'] 'infoblox user' None log debug ' Infobloxusernameis"{ 0 }"' format infoblox user if infoblox password is None infoblox password salt ['pillar get'] 'infoblox password' None return infoblox server infoblox user infoblox password
null
null
null
null
Question: What does the code get from pillar if not passed ? Code: def _conn_info_check(infoblox_server=None, infoblox_user=None, infoblox_password=None): if (infoblox_server is None): infoblox_server = __salt__['pillar.get']('infoblox:server', None) if (infoblox_user is None): infoblox_user = __salt__['pillar.get']('infoblox:user', None) log.debug('Infoblox username is "{0}"'.format(infoblox_user)) if (infoblox_password is None): infoblox_password = __salt__['pillar.get']('infoblox:password', None) return (infoblox_server, infoblox_user, infoblox_password)
null
null
null
What does the code install ?
def install(packages=None, cyg_arch='x86_64', mirrors=None): args = [] if (packages is not None): args.append('--packages {pkgs}'.format(pkgs=packages)) if (not _check_cygwin_installed(cyg_arch)): _run_silent_cygwin(cyg_arch=cyg_arch) return _run_silent_cygwin(cyg_arch=cyg_arch, args=args, mirrors=mirrors)
null
null
null
one or several packages
codeqa
def install packages None cyg arch 'x 86 64 ' mirrors None args []if packages is not None args append '--packages{pkgs}' format pkgs packages if not check cygwin installed cyg arch run silent cygwin cyg arch cyg arch return run silent cygwin cyg arch cyg arch args args mirrors mirrors
null
null
null
null
Question: What does the code install ? Code: def install(packages=None, cyg_arch='x86_64', mirrors=None): args = [] if (packages is not None): args.append('--packages {pkgs}'.format(pkgs=packages)) if (not _check_cygwin_installed(cyg_arch)): _run_silent_cygwin(cyg_arch=cyg_arch) return _run_silent_cygwin(cyg_arch=cyg_arch, args=args, mirrors=mirrors)
null
null
null
What does the code create ?
def _create_rand_fdist(numsamples, numoutcomes): import random fdist = FreqDist() for x in range(numoutcomes): y = (random.randint(1, ((1 + numsamples) // 2)) + random.randint(0, (numsamples // 2))) fdist[y] += 1 return fdist
null
null
null
a new frequency distribution
codeqa
def create rand fdist numsamples numoutcomes import randomfdist Freq Dist for x in range numoutcomes y random randint 1 1 + numsamples // 2 + random randint 0 numsamples // 2 fdist[y] + 1return fdist
null
null
null
null
Question: What does the code create ? Code: def _create_rand_fdist(numsamples, numoutcomes): import random fdist = FreqDist() for x in range(numoutcomes): y = (random.randint(1, ((1 + numsamples) // 2)) + random.randint(0, (numsamples // 2))) fdist[y] += 1 return fdist
null
null
null
What generator over all subclasses of a given class ?
def itersubclasses(cls, _seen=None): if (not isinstance(cls, type)): raise TypeError('itersubclasses must be called with new-style classes, not {:.100r}'.format(cls)) if (_seen is None): _seen = set() try: subs = cls.__subclasses__() except TypeError: subs = cls.__subclasses__(cls) for sub in sorted(subs, key=operator.attrgetter('__name__')): if (sub not in _seen): _seen.add(sub) (yield sub) for sub in itersubclasses(sub, _seen): (yield sub)
null
null
null
itersubclasses
codeqa
def itersubclasses cls seen None if not isinstance cls type raise Type Error 'itersubclassesmustbecalledwithnew-styleclasses not{ 100 r}' format cls if seen is None seen set try subs cls subclasses except Type Error subs cls subclasses cls for sub in sorted subs key operator attrgetter ' name ' if sub not in seen seen add sub yield sub for sub in itersubclasses sub seen yield sub
null
null
null
null
Question: What generator over all subclasses of a given class ? Code: def itersubclasses(cls, _seen=None): if (not isinstance(cls, type)): raise TypeError('itersubclasses must be called with new-style classes, not {:.100r}'.format(cls)) if (_seen is None): _seen = set() try: subs = cls.__subclasses__() except TypeError: subs = cls.__subclasses__(cls) for sub in sorted(subs, key=operator.attrgetter('__name__')): if (sub not in _seen): _seen.add(sub) (yield sub) for sub in itersubclasses(sub, _seen): (yield sub)
null
null
null
How do a string test ?
def test_pl(): o = nikola.utils.slugify(u'za\u017c\xf3\u0142\u0107g\u0119\u015bl\u0105ja\u017a\u0144', lang=u'pl') assert (o == u'zazolcgeslajazn') assert isinstance(o, nikola.utils.unicode_str)
null
null
null
with polish diacritical characters
codeqa
def test pl o nikola utils slugify u'za\u 017 c\xf 3 \u 0142 \u 0107 g\u 0119 \u 015 bl\u 0105 ja\u 017 a\u 0144 ' lang u'pl' assert o u'zazolcgeslajazn' assert isinstance o nikola utils unicode str
null
null
null
null
Question: How do a string test ? Code: def test_pl(): o = nikola.utils.slugify(u'za\u017c\xf3\u0142\u0107g\u0119\u015bl\u0105ja\u017a\u0144', lang=u'pl') assert (o == u'zazolcgeslajazn') assert isinstance(o, nikola.utils.unicode_str)
null
null
null
What does the code return ?
def get_profile_user_fieldname(profile_model=None, user_model=None): Profile = (profile_model or get_profile_model()) User = (user_model or get_user_model()) for field in Profile._meta.fields: if (field.rel and (field.rel.to == User)): return field.name raise ImproperlyConfigured((u'Value for ACCOUNTS_PROFILE_MODEL does not contain a ForeignKey field for auth.User: %s' % Profile.__name__))
null
null
null
the name of the first field on the profile model that points to the auth
codeqa
def get profile user fieldname profile model None user model None Profile profile model or get profile model User user model or get user model for field in Profile meta fields if field rel and field rel to User return field nameraise Improperly Configured u' Valuefor ACCOUNTS PROFILE MODE Ldoesnotcontaina Foreign Keyfieldforauth User %s' % Profile name
null
null
null
null
Question: What does the code return ? Code: def get_profile_user_fieldname(profile_model=None, user_model=None): Profile = (profile_model or get_profile_model()) User = (user_model or get_user_model()) for field in Profile._meta.fields: if (field.rel and (field.rel.to == User)): return field.name raise ImproperlyConfigured((u'Value for ACCOUNTS_PROFILE_MODEL does not contain a ForeignKey field for auth.User: %s' % Profile.__name__))
null
null
null
How do data sign ?
def sign(pkey, data, digest): data = _text_to_bytes_and_warn('data', data) digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest)) if (digest_obj == _ffi.NULL): raise ValueError('No such digest method') md_ctx = _ffi.new('EVP_MD_CTX*') md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup) _lib.EVP_SignInit(md_ctx, digest_obj) _lib.EVP_SignUpdate(md_ctx, data, len(data)) signature_buffer = _ffi.new('unsigned char[]', 512) signature_length = _ffi.new('unsigned int*') signature_length[0] = len(signature_buffer) final_result = _lib.EVP_SignFinal(md_ctx, signature_buffer, signature_length, pkey._pkey) if (final_result != 1): _raise_current_error() return _ffi.buffer(signature_buffer, signature_length[0])[:]
null
null
null
with a digest
codeqa
def sign pkey data digest data text to bytes and warn 'data' data digest obj lib EVP get digestbyname byte string digest if digest obj ffi NULL raise Value Error ' Nosuchdigestmethod' md ctx ffi new 'EVP MD CTX*' md ctx ffi gc md ctx lib EVP MD CTX cleanup lib EVP Sign Init md ctx digest obj lib EVP Sign Update md ctx data len data signature buffer ffi new 'unsignedchar[]' 512 signature length ffi new 'unsignedint*' signature length[ 0 ] len signature buffer final result lib EVP Sign Final md ctx signature buffer signature length pkey pkey if final result 1 raise current error return ffi buffer signature buffer signature length[ 0 ] [ ]
null
null
null
null
Question: How do data sign ? Code: def sign(pkey, data, digest): data = _text_to_bytes_and_warn('data', data) digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest)) if (digest_obj == _ffi.NULL): raise ValueError('No such digest method') md_ctx = _ffi.new('EVP_MD_CTX*') md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup) _lib.EVP_SignInit(md_ctx, digest_obj) _lib.EVP_SignUpdate(md_ctx, data, len(data)) signature_buffer = _ffi.new('unsigned char[]', 512) signature_length = _ffi.new('unsigned int*') signature_length[0] = len(signature_buffer) final_result = _lib.EVP_SignFinal(md_ctx, signature_buffer, signature_length, pkey._pkey) if (final_result != 1): _raise_current_error() return _ffi.buffer(signature_buffer, signature_length[0])[:]
null
null
null
What does the code update ?
def update_package(package, local=False, npm='npm'): if local: run(('%(npm)s update -l %(package)s' % locals())) else: run_as_root(('HOME=/root %(npm)s update -g %(package)s' % locals()))
null
null
null
a node
codeqa
def update package package local False npm 'npm' if local run '% npm supdate-l% package s' % locals else run as root 'HOME /root% npm supdate-g% package s' % locals
null
null
null
null
Question: What does the code update ? Code: def update_package(package, local=False, npm='npm'): if local: run(('%(npm)s update -l %(package)s' % locals())) else: run_as_root(('HOME=/root %(npm)s update -g %(package)s' % locals()))
null
null
null
How does an iterable over nodes in g return ?
def strategy_connected_sequential(G, colors, traversal='bfs'): if (traversal == 'bfs'): traverse = nx.bfs_edges elif (traversal == 'dfs'): traverse = nx.dfs_edges else: raise nx.NetworkXError("Please specify one of the strings 'bfs' or 'dfs' for connected sequential ordering") for component in nx.connected_component_subgraphs(G): source = arbitrary_element(component) (yield source) for (_, end) in traverse(component, source): (yield end)
null
null
null
in the order given by a breadth - first or depth - first traversal
codeqa
def strategy connected sequential G colors traversal 'bfs' if traversal 'bfs' traverse nx bfs edgeselif traversal 'dfs' traverse nx dfs edgeselse raise nx Network X Error " Pleasespecifyoneofthestrings'bfs'or'dfs'forconnectedsequentialordering" for component in nx connected component subgraphs G source arbitrary element component yield source for end in traverse component source yield end
null
null
null
null
Question: How does an iterable over nodes in g return ? Code: def strategy_connected_sequential(G, colors, traversal='bfs'): if (traversal == 'bfs'): traverse = nx.bfs_edges elif (traversal == 'dfs'): traverse = nx.dfs_edges else: raise nx.NetworkXError("Please specify one of the strings 'bfs' or 'dfs' for connected sequential ordering") for component in nx.connected_component_subgraphs(G): source = arbitrary_element(component) (yield source) for (_, end) in traverse(component, source): (yield end)
null
null
null
What does the code find ?
@_get_client def image_member_find(client, image_id=None, member=None, status=None, include_deleted=False): return client.image_member_find(image_id=image_id, member=member, status=status, include_deleted=include_deleted)
null
null
null
all members that meet the given criteria
codeqa
@ get clientdef image member find client image id None member None status None include deleted False return client image member find image id image id member member status status include deleted include deleted
null
null
null
null
Question: What does the code find ? Code: @_get_client def image_member_find(client, image_id=None, member=None, status=None, include_deleted=False): return client.image_member_find(image_id=image_id, member=member, status=status, include_deleted=include_deleted)
null
null
null
What do all members meet ?
@_get_client def image_member_find(client, image_id=None, member=None, status=None, include_deleted=False): return client.image_member_find(image_id=image_id, member=member, status=status, include_deleted=include_deleted)
null
null
null
the given criteria
codeqa
@ get clientdef image member find client image id None member None status None include deleted False return client image member find image id image id member member status status include deleted include deleted
null
null
null
null
Question: What do all members meet ? Code: @_get_client def image_member_find(client, image_id=None, member=None, status=None, include_deleted=False): return client.image_member_find(image_id=image_id, member=member, status=status, include_deleted=include_deleted)
null
null
null
What meet the given criteria ?
@_get_client def image_member_find(client, image_id=None, member=None, status=None, include_deleted=False): return client.image_member_find(image_id=image_id, member=member, status=status, include_deleted=include_deleted)
null
null
null
all members
codeqa
@ get clientdef image member find client image id None member None status None include deleted False return client image member find image id image id member member status status include deleted include deleted
null
null
null
null
Question: What meet the given criteria ? Code: @_get_client def image_member_find(client, image_id=None, member=None, status=None, include_deleted=False): return client.image_member_find(image_id=image_id, member=member, status=status, include_deleted=include_deleted)
null
null
null
Where does inference run ?
def run_inference_on_image(image): if (not tf.gfile.Exists(image)): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() create_graph() with tf.Session() as sess: softmax_tensor = sess.graph.get_tensor_by_name('softmax:0') predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) predictions = np.squeeze(predictions) node_lookup = NodeLookup() top_k = predictions.argsort()[(- FLAGS.num_top_predictions):][::(-1)] for node_id in top_k: human_string = node_lookup.id_to_string(node_id) score = predictions[node_id] print(('%s (score = %.5f)' % (human_string, score)))
null
null
null
on an image
codeqa
def run inference on image image if not tf gfile Exists image tf logging fatal ' Filedoesnotexist%s' image image data tf gfile Fast G File image 'rb' read create graph with tf Session as sess softmax tensor sess graph get tensor by name 'softmax 0' predictions sess run softmax tensor {' Decode Jpeg/contents 0' image data} predictions np squeeze predictions node lookup Node Lookup top k predictions argsort [ - FLAGS num top predictions ][ -1 ]for node id in top k human string node lookup id to string node id score predictions[node id]print '%s score % 5f ' % human string score
null
null
null
null
Question: Where does inference run ? Code: def run_inference_on_image(image): if (not tf.gfile.Exists(image)): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() create_graph() with tf.Session() as sess: softmax_tensor = sess.graph.get_tensor_by_name('softmax:0') predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) predictions = np.squeeze(predictions) node_lookup = NodeLookup() top_k = predictions.argsort()[(- FLAGS.num_top_predictions):][::(-1)] for node_id in top_k: human_string = node_lookup.id_to_string(node_id) score = predictions[node_id] print(('%s (score = %.5f)' % (human_string, score)))
null
null
null
What runs on an image ?
def run_inference_on_image(image): if (not tf.gfile.Exists(image)): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() create_graph() with tf.Session() as sess: softmax_tensor = sess.graph.get_tensor_by_name('softmax:0') predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) predictions = np.squeeze(predictions) node_lookup = NodeLookup() top_k = predictions.argsort()[(- FLAGS.num_top_predictions):][::(-1)] for node_id in top_k: human_string = node_lookup.id_to_string(node_id) score = predictions[node_id] print(('%s (score = %.5f)' % (human_string, score)))
null
null
null
inference
codeqa
def run inference on image image if not tf gfile Exists image tf logging fatal ' Filedoesnotexist%s' image image data tf gfile Fast G File image 'rb' read create graph with tf Session as sess softmax tensor sess graph get tensor by name 'softmax 0' predictions sess run softmax tensor {' Decode Jpeg/contents 0' image data} predictions np squeeze predictions node lookup Node Lookup top k predictions argsort [ - FLAGS num top predictions ][ -1 ]for node id in top k human string node lookup id to string node id score predictions[node id]print '%s score % 5f ' % human string score
null
null
null
null
Question: What runs on an image ? Code: def run_inference_on_image(image): if (not tf.gfile.Exists(image)): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() create_graph() with tf.Session() as sess: softmax_tensor = sess.graph.get_tensor_by_name('softmax:0') predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) predictions = np.squeeze(predictions) node_lookup = NodeLookup() top_k = predictions.argsort()[(- FLAGS.num_top_predictions):][::(-1)] for node_id in top_k: human_string = node_lookup.id_to_string(node_id) score = predictions[node_id] print(('%s (score = %.5f)' % (human_string, score)))
null
null
null
What does the code give you on your public streams ?
def add_new_user_history(user_profile, streams): one_week_ago = (now() - datetime.timedelta(weeks=1)) recipients = Recipient.objects.filter(type=Recipient.STREAM, type_id__in=[stream.id for stream in streams if (not stream.invite_only)]) recent_messages = Message.objects.filter(recipient_id__in=recipients, pub_date__gt=one_week_ago).order_by('-id') message_ids_to_use = list(reversed(recent_messages.values_list('id', flat=True)[0:100])) if (len(message_ids_to_use) == 0): return already_ids = set(UserMessage.objects.filter(message_id__in=message_ids_to_use, user_profile=user_profile).values_list('message_id', flat=True)) ums_to_create = [UserMessage(user_profile=user_profile, message_id=message_id, flags=UserMessage.flags.read) for message_id in message_ids_to_use if (message_id not in already_ids)] UserMessage.objects.bulk_create(ums_to_create)
null
null
null
the last 100 messages
codeqa
def add new user history user profile streams one week ago now - datetime timedelta weeks 1 recipients Recipient objects filter type Recipient STREAM type id in [stream id for stream in streams if not stream invite only ] recent messages Message objects filter recipient id in recipients pub date gt one week ago order by '-id' message ids to use list reversed recent messages values list 'id' flat True [0 100 ] if len message ids to use 0 returnalready ids set User Message objects filter message id in message ids to use user profile user profile values list 'message id' flat True ums to create [ User Message user profile user profile message id message id flags User Message flags read for message id in message ids to use if message id not in already ids ] User Message objects bulk create ums to create
null
null
null
null
Question: What does the code give you on your public streams ? Code: def add_new_user_history(user_profile, streams): one_week_ago = (now() - datetime.timedelta(weeks=1)) recipients = Recipient.objects.filter(type=Recipient.STREAM, type_id__in=[stream.id for stream in streams if (not stream.invite_only)]) recent_messages = Message.objects.filter(recipient_id__in=recipients, pub_date__gt=one_week_ago).order_by('-id') message_ids_to_use = list(reversed(recent_messages.values_list('id', flat=True)[0:100])) if (len(message_ids_to_use) == 0): return already_ids = set(UserMessage.objects.filter(message_id__in=message_ids_to_use, user_profile=user_profile).values_list('message_id', flat=True)) ums_to_create = [UserMessage(user_profile=user_profile, message_id=message_id, flags=UserMessage.flags.read) for message_id in message_ids_to_use if (message_id not in already_ids)] UserMessage.objects.bulk_create(ums_to_create)
null
null
null
How do for source node search ?
def get_source_node(node): source = (node.registered_from or node.forked_from) if (source is None): return None if check_node(source): return source return get_source_node(source)
null
null
null
recursively
codeqa
def get source node node source node registered from or node forked from if source is None return Noneif check node source return sourcereturn get source node source
null
null
null
null
Question: How do for source node search ? Code: def get_source_node(node): source = (node.registered_from or node.forked_from) if (source is None): return None if check_node(source): return source return get_source_node(source)
null
null
null
What does the code use the command - line flags ?
def process_flags(flags=None): if (flags is None): flags = [] try: FLAGS(flags) except gflags.FlagsError as e: print(('%s\nUsage: %s ARGS\n%s' % (e, str(flags), FLAGS))) sys.exit(1) logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
null
null
null
to set the logging level
codeqa
def process flags flags None if flags is None flags []try FLAGS flags except gflags Flags Error as e print '%s\n Usage %s ARGS\n%s' % e str flags FLAGS sys exit 1 logging get Logger set Level getattr logging FLAGS logging level
null
null
null
null
Question: What does the code use the command - line flags ? Code: def process_flags(flags=None): if (flags is None): flags = [] try: FLAGS(flags) except gflags.FlagsError as e: print(('%s\nUsage: %s ARGS\n%s' % (e, str(flags), FLAGS))) sys.exit(1) logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
null
null
null
What does the code set ?
def process_flags(flags=None): if (flags is None): flags = [] try: FLAGS(flags) except gflags.FlagsError as e: print(('%s\nUsage: %s ARGS\n%s' % (e, str(flags), FLAGS))) sys.exit(1) logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
null
null
null
the logging level
codeqa
def process flags flags None if flags is None flags []try FLAGS flags except gflags Flags Error as e print '%s\n Usage %s ARGS\n%s' % e str flags FLAGS sys exit 1 logging get Logger set Level getattr logging FLAGS logging level
null
null
null
null
Question: What does the code set ? Code: def process_flags(flags=None): if (flags is None): flags = [] try: FLAGS(flags) except gflags.FlagsError as e: print(('%s\nUsage: %s ARGS\n%s' % (e, str(flags), FLAGS))) sys.exit(1) logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
null
null
null
What does the code use to set the logging level ?
def process_flags(flags=None): if (flags is None): flags = [] try: FLAGS(flags) except gflags.FlagsError as e: print(('%s\nUsage: %s ARGS\n%s' % (e, str(flags), FLAGS))) sys.exit(1) logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
null
null
null
the command - line flags
codeqa
def process flags flags None if flags is None flags []try FLAGS flags except gflags Flags Error as e print '%s\n Usage %s ARGS\n%s' % e str flags FLAGS sys exit 1 logging get Logger set Level getattr logging FLAGS logging level
null
null
null
null
Question: What does the code use to set the logging level ? Code: def process_flags(flags=None): if (flags is None): flags = [] try: FLAGS(flags) except gflags.FlagsError as e: print(('%s\nUsage: %s ARGS\n%s' % (e, str(flags), FLAGS))) sys.exit(1) logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
null
null
null
What does the code cause ?
def clear(path): cmd = 'xattr -c "{0}"'.format(path) try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if ('No such file' in exc.strerror): raise CommandExecutionError('File not found: {0}'.format(path)) raise CommandExecutionError('Unknown Error: {0}'.format(exc.strerror)) return (list_(path) == {})
null
null
null
the all attributes on the file / directory to be removed
codeqa
def clear path cmd 'xattr-c"{ 0 }"' format path try salt utils mac utils execute return success cmd except Command Execution Error as exc if ' Nosuchfile' in exc strerror raise Command Execution Error ' Filenotfound {0 }' format path raise Command Execution Error ' Unknown Error {0 }' format exc strerror return list path {}
null
null
null
null
Question: What does the code cause ? Code: def clear(path): cmd = 'xattr -c "{0}"'.format(path) try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if ('No such file' in exc.strerror): raise CommandExecutionError('File not found: {0}'.format(path)) raise CommandExecutionError('Unknown Error: {0}'.format(exc.strerror)) return (list_(path) == {})
null
null
null
What does the code perform ?
def main(args=None): startLogging(stdout) options = BufferingBenchmark() options.parseOptions(args) d = benchmark(options['scale']) def cbBenchmark(result): pprint(result) def ebBenchmark(err): print(err.getTraceback()) d.addCallbacks(cbBenchmark, ebBenchmark) def stopReactor(ign): reactor.stop() d.addBoth(stopReactor) reactor.run()
null
null
null
a single benchmark run
codeqa
def main args None start Logging stdout options Buffering Benchmark options parse Options args d benchmark options['scale'] def cb Benchmark result pprint result def eb Benchmark err print err get Traceback d add Callbacks cb Benchmark eb Benchmark def stop Reactor ign reactor stop d add Both stop Reactor reactor run
null
null
null
null
Question: What does the code perform ? Code: def main(args=None): startLogging(stdout) options = BufferingBenchmark() options.parseOptions(args) d = benchmark(options['scale']) def cbBenchmark(result): pprint(result) def ebBenchmark(err): print(err.getTraceback()) d.addCallbacks(cbBenchmark, ebBenchmark) def stopReactor(ign): reactor.stop() d.addBoth(stopReactor) reactor.run()
null
null
null
What does the code delete from the specified table & chain ?
def delete(table, chain=None, position=None, rule=None, family='ipv4'): if (position and rule): return 'Error: Only specify a position or a rule, not both' if (not check_table(table, family=family)): return 'Error: table {0} in family {1} does not exist'.format(table, family) if (not check_chain(table, chain, family=family)): return 'Error: chain {0} in table {1} in family {2} does not exist'.format(chain, table, family) if (not check(table, chain, rule, family=family)): return 'Error: rule {0} chain {1} in table {2} in family {3} does not exist'.format(rule, chain, table, family) if (not position): position = get_rule_handle(table, chain, rule, family) nft_family = _NFTABLES_FAMILIES[family] cmd = '{0} delete rule {1} {2} {3} handle {4}'.format(_nftables_cmd(), nft_family, table, chain, position) out = __salt__['cmd.run'](cmd, python_shell=False) if (len(out) == 0): return True else: return False
null
null
null
a rule
codeqa
def delete table chain None position None rule None family 'ipv 4 ' if position and rule return ' Error Onlyspecifyapositionorarule notboth'if not check table table family family return ' Error table{ 0 }infamily{ 1 }doesnotexist' format table family if not check chain table chain family family return ' Error chain{ 0 }intable{ 1 }infamily{ 2 }doesnotexist' format chain table family if not check table chain rule family family return ' Error rule{ 0 }chain{ 1 }intable{ 2 }infamily{ 3 }doesnotexist' format rule chain table family if not position position get rule handle table chain rule family nft family NFTABLES FAMILIES[family]cmd '{ 0 }deleterule{ 1 }{ 2 }{ 3 }handle{ 4 }' format nftables cmd nft family table chain position out salt ['cmd run'] cmd python shell False if len out 0 return Trueelse return False
null
null
null
null
Question: What does the code delete from the specified table & chain ? Code: def delete(table, chain=None, position=None, rule=None, family='ipv4'): if (position and rule): return 'Error: Only specify a position or a rule, not both' if (not check_table(table, family=family)): return 'Error: table {0} in family {1} does not exist'.format(table, family) if (not check_chain(table, chain, family=family)): return 'Error: chain {0} in table {1} in family {2} does not exist'.format(chain, table, family) if (not check(table, chain, rule, family=family)): return 'Error: rule {0} chain {1} in table {2} in family {3} does not exist'.format(rule, chain, table, family) if (not position): position = get_rule_handle(table, chain, rule, family) nft_family = _NFTABLES_FAMILIES[family] cmd = '{0} delete rule {1} {2} {3} handle {4}'.format(_nftables_cmd(), nft_family, table, chain, position) out = __salt__['cmd.run'](cmd, python_shell=False) if (len(out) == 0): return True else: return False
null
null
null
What does the code compute ?
def _trace_symbanded(a, b, lower=0): if lower: t = _zero_triband((a * b), lower=1) return (t[0].sum() + (2 * t[1:].sum())) else: t = _zero_triband((a * b), lower=0) return (t[(-1)].sum() + (2 * t[:(-1)].sum()))
null
null
null
the trace for two upper or banded real symmetric matrices stored either in either upper or lower form
codeqa
def trace symbanded a b lower 0 if lower t zero triband a * b lower 1 return t[ 0 ] sum + 2 * t[ 1 ] sum else t zero triband a * b lower 0 return t[ -1 ] sum + 2 * t[ -1 ] sum
null
null
null
null
Question: What does the code compute ? Code: def _trace_symbanded(a, b, lower=0): if lower: t = _zero_triband((a * b), lower=1) return (t[0].sum() + (2 * t[1:].sum())) else: t = _zero_triband((a * b), lower=0) return (t[(-1)].sum() + (2 * t[:(-1)].sum()))
null
null
null
How did two upper or banded real symmetric matrices store ?
def _trace_symbanded(a, b, lower=0): if lower: t = _zero_triband((a * b), lower=1) return (t[0].sum() + (2 * t[1:].sum())) else: t = _zero_triband((a * b), lower=0) return (t[(-1)].sum() + (2 * t[:(-1)].sum()))
null
null
null
either in either upper or lower form
codeqa
def trace symbanded a b lower 0 if lower t zero triband a * b lower 1 return t[ 0 ] sum + 2 * t[ 1 ] sum else t zero triband a * b lower 0 return t[ -1 ] sum + 2 * t[ -1 ] sum
null
null
null
null
Question: How did two upper or banded real symmetric matrices store ? Code: def _trace_symbanded(a, b, lower=0): if lower: t = _zero_triband((a * b), lower=1) return (t[0].sum() + (2 * t[1:].sum())) else: t = _zero_triband((a * b), lower=0) return (t[(-1)].sum() + (2 * t[:(-1)].sum()))
null
null
null
What does the code return ?
def get_python_module_names(file_list, file_suffix='.py'): module_names = [m[:m.rfind(file_suffix)] for m in file_list if m.endswith(file_suffix)] return module_names
null
null
null
a list of module names from a filename list
codeqa
def get python module names file list file suffix ' py' module names [m[ m rfind file suffix ] for m in file list if m endswith file suffix ]return module names
null
null
null
null
Question: What does the code return ? Code: def get_python_module_names(file_list, file_suffix='.py'): module_names = [m[:m.rfind(file_suffix)] for m in file_list if m.endswith(file_suffix)] return module_names
null
null
null
What does the code get ?
def getUnpackedLoops(loops): if (len(loops) == 1): firstLoop = loops[0] if (firstLoop.__class__ == list): return firstLoop return loops
null
null
null
unpacked loops
codeqa
def get Unpacked Loops loops if len loops 1 first Loop loops[ 0 ]if first Loop class list return first Loopreturn loops
null
null
null
null
Question: What does the code get ? Code: def getUnpackedLoops(loops): if (len(loops) == 1): firstLoop = loops[0] if (firstLoop.__class__ == list): return firstLoop return loops
null
null
null
What does the code make ?
def _set_version_locations(config): split_branches = False version_paths = [_get_version_branch_path(config)] for release in RELEASES: for branch in MIGRATION_BRANCHES: version_path = _get_version_branch_path(config, release, branch) if (split_branches or os.path.exists(version_path)): split_branches = True version_paths.append(version_path) config.set_main_option('version_locations', ' '.join(version_paths))
null
null
null
alembic see all revisions in all migration branches
codeqa
def set version locations config split branches Falseversion paths [ get version branch path config ]for release in RELEASES for branch in MIGRATION BRANCHES version path get version branch path config release branch if split branches or os path exists version path split branches Trueversion paths append version path config set main option 'version locations' '' join version paths
null
null
null
null
Question: What does the code make ? Code: def _set_version_locations(config): split_branches = False version_paths = [_get_version_branch_path(config)] for release in RELEASES: for branch in MIGRATION_BRANCHES: version_path = _get_version_branch_path(config, release, branch) if (split_branches or os.path.exists(version_path)): split_branches = True version_paths.append(version_path) config.set_main_option('version_locations', ' '.join(version_paths))
null
null
null
What does s3 server - side encryption require ?
def sse_md5(params, **kwargs): _sse_md5(params, 'SSECustomer')
null
null
null
the encryption key to be sent to the server base64 encoded
codeqa
def sse md 5 params **kwargs sse md 5 params 'SSE Customer'
null
null
null
null
Question: What does s3 server - side encryption require ? Code: def sse_md5(params, **kwargs): _sse_md5(params, 'SSECustomer')
null
null
null
When did package activities change ?
def recently_changed_packages_activity_list(limit, offset): q = _changed_packages_activity_query() return _activities_at_offset(q, limit, offset)
null
null
null
recently
codeqa
def recently changed packages activity list limit offset q changed packages activity query return activities at offset q limit offset
null
null
null
null
Question: When did package activities change ? Code: def recently_changed_packages_activity_list(limit, offset): q = _changed_packages_activity_query() return _activities_at_offset(q, limit, offset)
null
null
null
What does a schema validate ?
def one_or_more(schema, unique_items=False): schema.setdefault(u'title', u'single value') return {u'oneOf': [{u'title': u'multiple values', u'type': u'array', u'items': schema, u'minItems': 1, u'uniqueItems': unique_items}, schema]}
null
null
null
items matching schema or an array containing items matching schema
codeqa
def one or more schema unique items False schema setdefault u'title' u'singlevalue' return {u'one Of' [{u'title' u'multiplevalues' u'type' u'array' u'items' schema u'min Items' 1 u'unique Items' unique items} schema]}
null
null
null
null
Question: What does a schema validate ? Code: def one_or_more(schema, unique_items=False): schema.setdefault(u'title', u'single value') return {u'oneOf': [{u'title': u'multiple values', u'type': u'array', u'items': schema, u'minItems': 1, u'uniqueItems': unique_items}, schema]}
null
null
null
What is matching schema ?
def one_or_more(schema, unique_items=False): schema.setdefault(u'title', u'single value') return {u'oneOf': [{u'title': u'multiple values', u'type': u'array', u'items': schema, u'minItems': 1, u'uniqueItems': unique_items}, schema]}
null
null
null
items
codeqa
def one or more schema unique items False schema setdefault u'title' u'singlevalue' return {u'one Of' [{u'title' u'multiplevalues' u'type' u'array' u'items' schema u'min Items' 1 u'unique Items' unique items} schema]}
null
null
null
null
Question: What is matching schema ? Code: def one_or_more(schema, unique_items=False): schema.setdefault(u'title', u'single value') return {u'oneOf': [{u'title': u'multiple values', u'type': u'array', u'items': schema, u'minItems': 1, u'uniqueItems': unique_items}, schema]}
null
null
null
What is containing items matching schema ?
def one_or_more(schema, unique_items=False): schema.setdefault(u'title', u'single value') return {u'oneOf': [{u'title': u'multiple values', u'type': u'array', u'items': schema, u'minItems': 1, u'uniqueItems': unique_items}, schema]}
null
null
null
an array
codeqa
def one or more schema unique items False schema setdefault u'title' u'singlevalue' return {u'one Of' [{u'title' u'multiplevalues' u'type' u'array' u'items' schema u'min Items' 1 u'unique Items' unique items} schema]}
null
null
null
null
Question: What is containing items matching schema ? Code: def one_or_more(schema, unique_items=False): schema.setdefault(u'title', u'single value') return {u'oneOf': [{u'title': u'multiple values', u'type': u'array', u'items': schema, u'minItems': 1, u'uniqueItems': unique_items}, schema]}
null
null
null
What validates items matching schema or an array containing items matching schema ?
def one_or_more(schema, unique_items=False): schema.setdefault(u'title', u'single value') return {u'oneOf': [{u'title': u'multiple values', u'type': u'array', u'items': schema, u'minItems': 1, u'uniqueItems': unique_items}, schema]}
null
null
null
a schema
codeqa
def one or more schema unique items False schema setdefault u'title' u'singlevalue' return {u'one Of' [{u'title' u'multiplevalues' u'type' u'array' u'items' schema u'min Items' 1 u'unique Items' unique items} schema]}
null
null
null
null
Question: What validates items matching schema or an array containing items matching schema ? Code: def one_or_more(schema, unique_items=False): schema.setdefault(u'title', u'single value') return {u'oneOf': [{u'title': u'multiple values', u'type': u'array', u'items': schema, u'minItems': 1, u'uniqueItems': unique_items}, schema]}
null
null
null
What do items match ?
def one_or_more(schema, unique_items=False): schema.setdefault(u'title', u'single value') return {u'oneOf': [{u'title': u'multiple values', u'type': u'array', u'items': schema, u'minItems': 1, u'uniqueItems': unique_items}, schema]}
null
null
null
schema
codeqa
def one or more schema unique items False schema setdefault u'title' u'singlevalue' return {u'one Of' [{u'title' u'multiplevalues' u'type' u'array' u'items' schema u'min Items' 1 u'unique Items' unique items} schema]}
null
null
null
null
Question: What do items match ? Code: def one_or_more(schema, unique_items=False): schema.setdefault(u'title', u'single value') return {u'oneOf': [{u'title': u'multiple values', u'type': u'array', u'items': schema, u'minItems': 1, u'uniqueItems': unique_items}, schema]}
null
null
null
What does the code get from text ?
def getargsfromtext(text, objname): signature = getsignaturefromtext(text, objname) if signature: argtxt = signature[(signature.find('(') + 1):(-1)] return argtxt.split(',')
null
null
null
arguments
codeqa
def getargsfromtext text objname signature getsignaturefromtext text objname if signature argtxt signature[ signature find ' ' + 1 -1 ]return argtxt split ' '
null
null
null
null
Question: What does the code get from text ? Code: def getargsfromtext(text, objname): signature = getsignaturefromtext(text, objname) if signature: argtxt = signature[(signature.find('(') + 1):(-1)] return argtxt.split(',')
null
null
null
What does the code insert into a loop ?
def addWithLeastLength(importRadius, loops, point): close = (1.65 * importRadius) shortestAdditionalLength = close shortestLoop = None shortestPointIndex = None for loop in loops: if (len(loop) > 3): for pointIndex in xrange(len(loop)): additionalLoopLength = getAdditionalLoopLength(loop, point, pointIndex) if (additionalLoopLength < shortestAdditionalLength): if getIsPointCloseInline(close, loop, point, pointIndex): shortestAdditionalLength = additionalLoopLength shortestLoop = loop shortestPointIndex = pointIndex if (shortestPointIndex != None): shortestLoop.insert(shortestPointIndex, point)
null
null
null
a point
codeqa
def add With Least Length import Radius loops point close 1 65 * import Radius shortest Additional Length closeshortest Loop Noneshortest Point Index Nonefor loop in loops if len loop > 3 for point Index in xrange len loop additional Loop Length get Additional Loop Length loop point point Index if additional Loop Length < shortest Additional Length if get Is Point Close Inline close loop point point Index shortest Additional Length additional Loop Lengthshortest Loop loopshortest Point Index point Indexif shortest Point Index None shortest Loop insert shortest Point Index point
null
null
null
null
Question: What does the code insert into a loop ? Code: def addWithLeastLength(importRadius, loops, point): close = (1.65 * importRadius) shortestAdditionalLength = close shortestLoop = None shortestPointIndex = None for loop in loops: if (len(loop) > 3): for pointIndex in xrange(len(loop)): additionalLoopLength = getAdditionalLoopLength(loop, point, pointIndex) if (additionalLoopLength < shortestAdditionalLength): if getIsPointCloseInline(close, loop, point, pointIndex): shortestAdditionalLength = additionalLoopLength shortestLoop = loop shortestPointIndex = pointIndex if (shortestPointIndex != None): shortestLoop.insert(shortestPointIndex, point)
null
null
null
What do we have ?
def test_merge_once_only(merge_log_err): packages = {'pack_1': {'homeassistant': {}}, 'pack_2': {'mqtt': {}, 'api': {}}} config = {config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, 'mqtt': {}, 'api': {}} config_util.merge_packages_config(config, packages) assert (merge_log_err.call_count == 3) assert (len(config) == 3)
null
null
null
a merge for a comp that may occur only once
codeqa
def test merge once only merge log err packages {'pack 1' {'homeassistant' {}} 'pack 2' {'mqtt' {} 'api' {}}}config {config util CONF CORE {config util CONF PACKAGES packages} 'mqtt' {} 'api' {}}config util merge packages config config packages assert merge log err call count 3 assert len config 3
null
null
null
null
Question: What do we have ? Code: def test_merge_once_only(merge_log_err): packages = {'pack_1': {'homeassistant': {}}, 'pack_2': {'mqtt': {}, 'api': {}}} config = {config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, 'mqtt': {}, 'api': {}} config_util.merge_packages_config(config, packages) assert (merge_log_err.call_count == 3) assert (len(config) == 3)
null
null
null
When may a comp occur ?
def test_merge_once_only(merge_log_err): packages = {'pack_1': {'homeassistant': {}}, 'pack_2': {'mqtt': {}, 'api': {}}} config = {config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, 'mqtt': {}, 'api': {}} config_util.merge_packages_config(config, packages) assert (merge_log_err.call_count == 3) assert (len(config) == 3)
null
null
null
only once
codeqa
def test merge once only merge log err packages {'pack 1' {'homeassistant' {}} 'pack 2' {'mqtt' {} 'api' {}}}config {config util CONF CORE {config util CONF PACKAGES packages} 'mqtt' {} 'api' {}}config util merge packages config config packages assert merge log err call count 3 assert len config 3
null
null
null
null
Question: When may a comp occur ? Code: def test_merge_once_only(merge_log_err): packages = {'pack_1': {'homeassistant': {}}, 'pack_2': {'mqtt': {}, 'api': {}}} config = {config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}, 'mqtt': {}, 'api': {}} config_util.merge_packages_config(config, packages) assert (merge_log_err.call_count == 3) assert (len(config) == 3)
null
null
null
What does the code get ?
def get_exchange(conn): ex = copy(event_exchange) if (conn.transport.driver_type == u'redis'): ex.type = u'fanout' return ex
null
null
null
exchange used for sending events
codeqa
def get exchange conn ex copy event exchange if conn transport driver type u'redis' ex type u'fanout'return ex
null
null
null
null
Question: What does the code get ? Code: def get_exchange(conn): ex = copy(event_exchange) if (conn.transport.driver_type == u'redis'): ex.type = u'fanout' return ex
null
null
null
What does the code convert to a string of space - separated numbers ?
def stripList(listObj): return ' '.join((str(i) for i in listObj))
null
null
null
a list of numbers
codeqa
def strip List list Obj return '' join str i for i in list Obj
null
null
null
null
Question: What does the code convert to a string of space - separated numbers ? Code: def stripList(listObj): return ' '.join((str(i) for i in listObj))
null
null
null
For what purpose do full path return to the user - specific data ?
def user_data_dir(appname, roaming=False): if WINDOWS: const = ((roaming and 'CSIDL_APPDATA') or 'CSIDL_LOCAL_APPDATA') path = os.path.join(os.path.normpath(_get_win_folder(const)), appname) elif (sys.platform == 'darwin'): path = os.path.join(expanduser('~/Library/Application Support/'), appname) else: path = os.path.join(os.getenv('XDG_DATA_HOME', expanduser('~/.local/share')), appname) return path
null
null
null
for this application
codeqa
def user data dir appname roaming False if WINDOWS const roaming and 'CSIDL APPDATA' or 'CSIDL LOCAL APPDATA' path os path join os path normpath get win folder const appname elif sys platform 'darwin' path os path join expanduser '~/ Library/ Application Support/' appname else path os path join os getenv 'XDG DATA HOME' expanduser '~/ local/share' appname return path
null
null
null
null
Question: For what purpose do full path return to the user - specific data ? Code: def user_data_dir(appname, roaming=False): if WINDOWS: const = ((roaming and 'CSIDL_APPDATA') or 'CSIDL_LOCAL_APPDATA') path = os.path.join(os.path.normpath(_get_win_folder(const)), appname) elif (sys.platform == 'darwin'): path = os.path.join(expanduser('~/Library/Application Support/'), appname) else: path = os.path.join(os.getenv('XDG_DATA_HOME', expanduser('~/.local/share')), appname) return path
null
null
null
What does not install a dependency because of the fork - worker model that is both necessary for throughput and makes more obscure the cause of failures when ?
def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
one
codeqa
def external program check to check frozenset [PSQL BIN LZOP BIN PV BIN] could not run []error msgs []def psql err handler popen assert popen returncode 0 error msgs append textwrap fill ' Couldnotgetaconnectiontothedatabase notethatsuperuseraccessisrequired' raise Environment Error 'INTERNAL Hadproblemsrunningpsqlfromexternal program check' with open os devnull 'wb' as nullf for program in to check try if program is PSQL BIN psql csv run 'SELECT 1 ' error handler psql err handler else if program is PV BIN extra args ['--quiet']else extra args []proc popen sp [program] + extra args stdout nullf stderr nullf stdin subprocess PIPE proc stdin close proc wait except Environment Error could not run append program if could not run error msgs append ' Couldnotrunthefollowingprograms aretheyinstalled?' + ' ' join could not run if error msgs raise User Exception 'couldnotrunoneormoreexternalprograms WAL- Edependsupon' '\n' join error msgs return None
null
null
null
null
Question: What does not install a dependency because of the fork - worker model that is both necessary for throughput and makes more obscure the cause of failures when ? Code: def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
What does the fork - worker model make ?
def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
more obscure the cause of failures
codeqa
def external program check to check frozenset [PSQL BIN LZOP BIN PV BIN] could not run []error msgs []def psql err handler popen assert popen returncode 0 error msgs append textwrap fill ' Couldnotgetaconnectiontothedatabase notethatsuperuseraccessisrequired' raise Environment Error 'INTERNAL Hadproblemsrunningpsqlfromexternal program check' with open os devnull 'wb' as nullf for program in to check try if program is PSQL BIN psql csv run 'SELECT 1 ' error handler psql err handler else if program is PV BIN extra args ['--quiet']else extra args []proc popen sp [program] + extra args stdout nullf stderr nullf stdin subprocess PIPE proc stdin close proc wait except Environment Error could not run append program if could not run error msgs append ' Couldnotrunthefollowingprograms aretheyinstalled?' + ' ' join could not run if error msgs raise User Exception 'couldnotrunoneormoreexternalprograms WAL- Edependsupon' '\n' join error msgs return None
null
null
null
null
Question: What does the fork - worker model make ? Code: def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
Does one install a dependency because of the fork - worker model that is both necessary for throughput and makes more obscure the cause of failures when ?
def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
No
codeqa
def external program check to check frozenset [PSQL BIN LZOP BIN PV BIN] could not run []error msgs []def psql err handler popen assert popen returncode 0 error msgs append textwrap fill ' Couldnotgetaconnectiontothedatabase notethatsuperuseraccessisrequired' raise Environment Error 'INTERNAL Hadproblemsrunningpsqlfromexternal program check' with open os devnull 'wb' as nullf for program in to check try if program is PSQL BIN psql csv run 'SELECT 1 ' error handler psql err handler else if program is PV BIN extra args ['--quiet']else extra args []proc popen sp [program] + extra args stdout nullf stderr nullf stdin subprocess PIPE proc stdin close proc wait except Environment Error could not run append program if could not run error msgs append ' Couldnotrunthefollowingprograms aretheyinstalled?' + ' ' join could not run if error msgs raise User Exception 'couldnotrunoneormoreexternalprograms WAL- Edependsupon' '\n' join error msgs return None
null
null
null
null
Question: Does one install a dependency because of the fork - worker model that is both necessary for throughput and makes more obscure the cause of failures when ? Code: def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
When do confusing error output get ?
def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
when one does not install a dependency because of the fork - worker model that is both necessary for throughput and makes more obscure the cause of failures
codeqa
def external program check to check frozenset [PSQL BIN LZOP BIN PV BIN] could not run []error msgs []def psql err handler popen assert popen returncode 0 error msgs append textwrap fill ' Couldnotgetaconnectiontothedatabase notethatsuperuseraccessisrequired' raise Environment Error 'INTERNAL Hadproblemsrunningpsqlfromexternal program check' with open os devnull 'wb' as nullf for program in to check try if program is PSQL BIN psql csv run 'SELECT 1 ' error handler psql err handler else if program is PV BIN extra args ['--quiet']else extra args []proc popen sp [program] + extra args stdout nullf stderr nullf stdin subprocess PIPE proc stdin close proc wait except Environment Error could not run append program if could not run error msgs append ' Couldnotrunthefollowingprograms aretheyinstalled?' + ' ' join could not run if error msgs raise User Exception 'couldnotrunoneormoreexternalprograms WAL- Edependsupon' '\n' join error msgs return None
null
null
null
null
Question: When do confusing error output get ? Code: def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
Why does one not install a dependency when ?
def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
because of the fork - worker model that is both necessary for throughput and makes more obscure the cause of failures
codeqa
def external program check to check frozenset [PSQL BIN LZOP BIN PV BIN] could not run []error msgs []def psql err handler popen assert popen returncode 0 error msgs append textwrap fill ' Couldnotgetaconnectiontothedatabase notethatsuperuseraccessisrequired' raise Environment Error 'INTERNAL Hadproblemsrunningpsqlfromexternal program check' with open os devnull 'wb' as nullf for program in to check try if program is PSQL BIN psql csv run 'SELECT 1 ' error handler psql err handler else if program is PV BIN extra args ['--quiet']else extra args []proc popen sp [program] + extra args stdout nullf stderr nullf stdin subprocess PIPE proc stdin close proc wait except Environment Error could not run append program if could not run error msgs append ' Couldnotrunthefollowingprograms aretheyinstalled?' + ' ' join could not run if error msgs raise User Exception 'couldnotrunoneormoreexternalprograms WAL- Edependsupon' '\n' join error msgs return None
null
null
null
null
Question: Why does one not install a dependency when ? Code: def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
What makes more obscure the cause of failures ?
def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
the fork - worker model
codeqa
def external program check to check frozenset [PSQL BIN LZOP BIN PV BIN] could not run []error msgs []def psql err handler popen assert popen returncode 0 error msgs append textwrap fill ' Couldnotgetaconnectiontothedatabase notethatsuperuseraccessisrequired' raise Environment Error 'INTERNAL Hadproblemsrunningpsqlfromexternal program check' with open os devnull 'wb' as nullf for program in to check try if program is PSQL BIN psql csv run 'SELECT 1 ' error handler psql err handler else if program is PV BIN extra args ['--quiet']else extra args []proc popen sp [program] + extra args stdout nullf stderr nullf stdin subprocess PIPE proc stdin close proc wait except Environment Error could not run append program if could not run error msgs append ' Couldnotrunthefollowingprograms aretheyinstalled?' + ' ' join could not run if error msgs raise User Exception 'couldnotrunoneormoreexternalprograms WAL- Edependsupon' '\n' join error msgs return None
null
null
null
null
Question: What makes more obscure the cause of failures ? Code: def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
What does one not install because of the fork - worker model that is both necessary for throughput and makes more obscure the cause of failures when ?
def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
a dependency
codeqa
def external program check to check frozenset [PSQL BIN LZOP BIN PV BIN] could not run []error msgs []def psql err handler popen assert popen returncode 0 error msgs append textwrap fill ' Couldnotgetaconnectiontothedatabase notethatsuperuseraccessisrequired' raise Environment Error 'INTERNAL Hadproblemsrunningpsqlfromexternal program check' with open os devnull 'wb' as nullf for program in to check try if program is PSQL BIN psql csv run 'SELECT 1 ' error handler psql err handler else if program is PV BIN extra args ['--quiet']else extra args []proc popen sp [program] + extra args stdout nullf stderr nullf stdin subprocess PIPE proc stdin close proc wait except Environment Error could not run append program if could not run error msgs append ' Couldnotrunthefollowingprograms aretheyinstalled?' + ' ' join could not run if error msgs raise User Exception 'couldnotrunoneormoreexternalprograms WAL- Edependsupon' '\n' join error msgs return None
null
null
null
null
Question: What does one not install because of the fork - worker model that is both necessary for throughput and makes more obscure the cause of failures when ? Code: def external_program_check(to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert (popen.returncode != 0) error_msgs.append(textwrap.fill('Could not get a connection to the database: note that superuser access is required')) raise EnvironmentError('INTERNAL: Had problems running psql from external_program_check') with open(os.devnull, 'wb') as nullf: for program in to_check: try: if (program is PSQL_BIN): psql_csv_run('SELECT 1', error_handler=psql_err_handler) else: if (program is PV_BIN): extra_args = ['--quiet'] else: extra_args = [] proc = popen_sp(([program] + extra_args), stdout=nullf, stderr=nullf, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() except EnvironmentError: could_not_run.append(program) if could_not_run: error_msgs.append(('Could not run the following programs, are they installed? ' + ', '.join(could_not_run))) if error_msgs: raise UserException('could not run one or more external programs WAL-E depends upon', '\n'.join(error_msgs)) return None
null
null
null
What does the code run in the supplied target_history ?
def __invoke(trans, workflow, workflow_run_config, workflow_invocation=None, populate_state=False): if populate_state: modules.populate_module_and_state(trans, workflow, workflow_run_config.param_map, allow_tool_state_corrections=workflow_run_config.allow_tool_state_corrections) invoker = WorkflowInvoker(trans, workflow, workflow_run_config, workflow_invocation=workflow_invocation) try: outputs = invoker.invoke() except modules.CancelWorkflowEvaluation: if workflow_invocation: if workflow_invocation.cancel(): trans.sa_session.add(workflow_invocation) outputs = [] except Exception: log.exception('Failed to execute scheduled workflow.') if workflow_invocation: workflow_invocation.fail() trans.sa_session.add(workflow_invocation) else: raise outputs = [] if workflow_invocation: trans.sa_session.flush() return (outputs, invoker.workflow_invocation)
null
null
null
the supplied workflow
codeqa
def invoke trans workflow workflow run config workflow invocation None populate state False if populate state modules populate module and state trans workflow workflow run config param map allow tool state corrections workflow run config allow tool state corrections invoker Workflow Invoker trans workflow workflow run config workflow invocation workflow invocation try outputs invoker invoke except modules Cancel Workflow Evaluation if workflow invocation if workflow invocation cancel trans sa session add workflow invocation outputs []except Exception log exception ' Failedtoexecutescheduledworkflow ' if workflow invocation workflow invocation fail trans sa session add workflow invocation else raiseoutputs []if workflow invocation trans sa session flush return outputs invoker workflow invocation
null
null
null
null
Question: What does the code run in the supplied target_history ? Code: def __invoke(trans, workflow, workflow_run_config, workflow_invocation=None, populate_state=False): if populate_state: modules.populate_module_and_state(trans, workflow, workflow_run_config.param_map, allow_tool_state_corrections=workflow_run_config.allow_tool_state_corrections) invoker = WorkflowInvoker(trans, workflow, workflow_run_config, workflow_invocation=workflow_invocation) try: outputs = invoker.invoke() except modules.CancelWorkflowEvaluation: if workflow_invocation: if workflow_invocation.cancel(): trans.sa_session.add(workflow_invocation) outputs = [] except Exception: log.exception('Failed to execute scheduled workflow.') if workflow_invocation: workflow_invocation.fail() trans.sa_session.add(workflow_invocation) else: raise outputs = [] if workflow_invocation: trans.sa_session.flush() return (outputs, invoker.workflow_invocation)
null
null
null
How does the code run the supplied workflow ?
def __invoke(trans, workflow, workflow_run_config, workflow_invocation=None, populate_state=False): if populate_state: modules.populate_module_and_state(trans, workflow, workflow_run_config.param_map, allow_tool_state_corrections=workflow_run_config.allow_tool_state_corrections) invoker = WorkflowInvoker(trans, workflow, workflow_run_config, workflow_invocation=workflow_invocation) try: outputs = invoker.invoke() except modules.CancelWorkflowEvaluation: if workflow_invocation: if workflow_invocation.cancel(): trans.sa_session.add(workflow_invocation) outputs = [] except Exception: log.exception('Failed to execute scheduled workflow.') if workflow_invocation: workflow_invocation.fail() trans.sa_session.add(workflow_invocation) else: raise outputs = [] if workflow_invocation: trans.sa_session.flush() return (outputs, invoker.workflow_invocation)
null
null
null
in the supplied target_history
codeqa
def invoke trans workflow workflow run config workflow invocation None populate state False if populate state modules populate module and state trans workflow workflow run config param map allow tool state corrections workflow run config allow tool state corrections invoker Workflow Invoker trans workflow workflow run config workflow invocation workflow invocation try outputs invoker invoke except modules Cancel Workflow Evaluation if workflow invocation if workflow invocation cancel trans sa session add workflow invocation outputs []except Exception log exception ' Failedtoexecutescheduledworkflow ' if workflow invocation workflow invocation fail trans sa session add workflow invocation else raiseoutputs []if workflow invocation trans sa session flush return outputs invoker workflow invocation
null
null
null
null
Question: How does the code run the supplied workflow ? Code: def __invoke(trans, workflow, workflow_run_config, workflow_invocation=None, populate_state=False): if populate_state: modules.populate_module_and_state(trans, workflow, workflow_run_config.param_map, allow_tool_state_corrections=workflow_run_config.allow_tool_state_corrections) invoker = WorkflowInvoker(trans, workflow, workflow_run_config, workflow_invocation=workflow_invocation) try: outputs = invoker.invoke() except modules.CancelWorkflowEvaluation: if workflow_invocation: if workflow_invocation.cancel(): trans.sa_session.add(workflow_invocation) outputs = [] except Exception: log.exception('Failed to execute scheduled workflow.') if workflow_invocation: workflow_invocation.fail() trans.sa_session.add(workflow_invocation) else: raise outputs = [] if workflow_invocation: trans.sa_session.flush() return (outputs, invoker.workflow_invocation)
null
null
null
What does the code remove from a file ?
def delete(filename): OggFLAC(filename).delete()
null
null
null
tags
codeqa
def delete filename Ogg FLAC filename delete
null
null
null
null
Question: What does the code remove from a file ? Code: def delete(filename): OggFLAC(filename).delete()
null
null
null
What does the code require ?
def command(): from fabtools.require.deb import package as require_deb_package from fabtools.require.pkg import package as require_pkg_package from fabtools.require.rpm import package as require_rpm_package from fabtools.require.portage import package as require_portage_package res = run('git --version', quiet=True) if res.failed: family = distrib_family() if (family == 'debian'): require_deb_package('git-core') elif (family == 'redhat'): require_rpm_package('git') elif (family == 'sun'): require_pkg_package('scmgit-base') elif (family == 'gentoo'): require_portage_package('dev-vcs/git') else: raise UnsupportedFamily(supported=['debian', 'redhat', 'sun', 'gentoo'])
null
null
null
the git command - line tool
codeqa
def command from fabtools require deb import package as require deb packagefrom fabtools require pkg import package as require pkg packagefrom fabtools require rpm import package as require rpm packagefrom fabtools require portage import package as require portage packageres run 'git--version' quiet True if res failed family distrib family if family 'debian' require deb package 'git-core' elif family 'redhat' require rpm package 'git' elif family 'sun' require pkg package 'scmgit-base' elif family 'gentoo' require portage package 'dev-vcs/git' else raise Unsupported Family supported ['debian' 'redhat' 'sun' 'gentoo']
null
null
null
null
Question: What does the code require ? Code: def command(): from fabtools.require.deb import package as require_deb_package from fabtools.require.pkg import package as require_pkg_package from fabtools.require.rpm import package as require_rpm_package from fabtools.require.portage import package as require_portage_package res = run('git --version', quiet=True) if res.failed: family = distrib_family() if (family == 'debian'): require_deb_package('git-core') elif (family == 'redhat'): require_rpm_package('git') elif (family == 'sun'): require_pkg_package('scmgit-base') elif (family == 'gentoo'): require_portage_package('dev-vcs/git') else: raise UnsupportedFamily(supported=['debian', 'redhat', 'sun', 'gentoo'])
null
null
null
What does key function factory put ?
def regex_last_key(regex): def k(obj): if regex.search(obj): return (1, obj) return (0, obj) return k
null
null
null
items that match a regular expression last
codeqa
def regex last key regex def k obj if regex search obj return 1 obj return 0 obj return k
null
null
null
null
Question: What does key function factory put ? Code: def regex_last_key(regex): def k(obj): if regex.search(obj): return (1, obj) return (0, obj) return k
null
null
null
When do a regular expression match items ?
def regex_last_key(regex): def k(obj): if regex.search(obj): return (1, obj) return (0, obj) return k
null
null
null
last
codeqa
def regex last key regex def k obj if regex search obj return 1 obj return 0 obj return k
null
null
null
null
Question: When do a regular expression match items ? Code: def regex_last_key(regex): def k(obj): if regex.search(obj): return (1, obj) return (0, obj) return k
null
null
null
What puts items that match a regular expression last ?
def regex_last_key(regex): def k(obj): if regex.search(obj): return (1, obj) return (0, obj) return k
null
null
null
key function factory
codeqa
def regex last key regex def k obj if regex search obj return 1 obj return 0 obj return k
null
null
null
null
Question: What puts items that match a regular expression last ? Code: def regex_last_key(regex): def k(obj): if regex.search(obj): return (1, obj) return (0, obj) return k
null
null
null
What does fixture set as current ?
@pytest.fixture() def depends_on_current_app(celery_app): celery_app.set_current()
null
null
null
app
codeqa
@pytest fixture def depends on current app celery app celery app set current
null
null
null
null
Question: What does fixture set as current ? Code: @pytest.fixture() def depends_on_current_app(celery_app): celery_app.set_current()
null
null
null
What sets app as current ?
@pytest.fixture() def depends_on_current_app(celery_app): celery_app.set_current()
null
null
null
fixture
codeqa
@pytest fixture def depends on current app celery app celery app set current
null
null
null
null
Question: What sets app as current ? Code: @pytest.fixture() def depends_on_current_app(celery_app): celery_app.set_current()
null
null
null
What does the code remove from a sparse matrix ?
def clean(x): return ensure_sorted_indices(remove0(x))
null
null
null
explicit zeros
codeqa
def clean x return ensure sorted indices remove 0 x
null
null
null
null
Question: What does the code remove from a sparse matrix ? Code: def clean(x): return ensure_sorted_indices(remove0(x))
null
null
null
What does the code create ?
def new_figure_manager(num, *args, **kwargs): thisFig = Figure(*args, **kwargs) return new_figure_manager_given_figure(num, thisFig)
null
null
null
a new figure manager instance
codeqa
def new figure manager num *args **kwargs this Fig Figure *args **kwargs return new figure manager given figure num this Fig
null
null
null
null
Question: What does the code create ? Code: def new_figure_manager(num, *args, **kwargs): thisFig = Figure(*args, **kwargs) return new_figure_manager_given_figure(num, thisFig)
null
null
null
What does the code show ?
@utils.arg('network_id', metavar='<network_id>', help='ID of network') @shell.deprecated_network def do_tenant_network_show(cs, args): network = cs.tenant_networks.get(args.network_id) utils.print_dict(network._info)
null
null
null
a tenant network
codeqa
@utils arg 'network id' metavar '<network id>' help 'I Dofnetwork' @shell deprecated networkdef do tenant network show cs args network cs tenant networks get args network id utils print dict network info
null
null
null
null
Question: What does the code show ? Code: @utils.arg('network_id', metavar='<network_id>', help='ID of network') @shell.deprecated_network def do_tenant_network_show(cs, args): network = cs.tenant_networks.get(args.network_id) utils.print_dict(network._info)
null
null
null
What compares the auth_map with the password ?
def checkResponse(auth_map, password, method='GET', encrypt=None, **kwargs): checker = AUTH_RESPONSES[auth_map['auth_scheme']] return checker(auth_map, password, method=method, encrypt=encrypt, **kwargs)
null
null
null
checkresponse
codeqa
def check Response auth map password method 'GET' encrypt None **kwargs checker AUTH RESPONSES[auth map['auth scheme']]return checker auth map password method method encrypt encrypt **kwargs
null
null
null
null
Question: What compares the auth_map with the password ? Code: def checkResponse(auth_map, password, method='GET', encrypt=None, **kwargs): checker = AUTH_RESPONSES[auth_map['auth_scheme']] return checker(auth_map, password, method=method, encrypt=encrypt, **kwargs)
null
null
null
What does the code get ?
def get_module_from_file(category, field, fallback_module_name=None): module_name = get_module_name(category, field, fallback_module_name) rc = MODULE_CACHE.get(module_name, None) if (rc is None): raise CX((_('Failed to load module for %s/%s') % (category, field))) return rc
null
null
null
python module
codeqa
def get module from file category field fallback module name None module name get module name category field fallback module name rc MODULE CACHE get module name None if rc is None raise CX ' Failedtoloadmodulefor%s/%s' % category field return rc
null
null
null
null
Question: What does the code get ? Code: def get_module_from_file(category, field, fallback_module_name=None): module_name = get_module_name(category, field, fallback_module_name) rc = MODULE_CACHE.get(module_name, None) if (rc is None): raise CX((_('Failed to load module for %s/%s') % (category, field))) return rc
null
null
null
How did respective review actions take ?
@task def send_mail(cleaned_data, theme_lock): with override('en-US'): theme = cleaned_data['theme'] action = cleaned_data['action'] comment = cleaned_data['comment'] reject_reason = cleaned_data['reject_reason'] reason = None if reject_reason: reason = rvw.THEME_REJECT_REASONS[reject_reason] elif (action == rvw.ACTION_DUPLICATE): reason = _('Duplicate Submission') emails = set(theme.addon.authors.values_list('email', flat=True)) context = {'theme': theme, 'base_url': settings.SITE_URL, 'reason': reason, 'comment': comment} subject = None if (action == rvw.ACTION_APPROVE): subject = _('Thanks for submitting your Theme') template = 'editors/themes/emails/approve.html' elif (action in (rvw.ACTION_REJECT, rvw.ACTION_DUPLICATE)): subject = _('A problem with your Theme submission') template = 'editors/themes/emails/reject.html' elif (action == rvw.ACTION_FLAG): subject = _('Theme submission flagged for review') template = 'editors/themes/emails/flag_reviewer.html' emails = [settings.THEMES_EMAIL] elif (action == rvw.ACTION_MOREINFO): subject = _('A question about your Theme submission') template = 'editors/themes/emails/moreinfo.html' context['reviewer_email'] = theme_lock.reviewer.email send_mail_jinja(subject, template, context, recipient_list=emails, from_email=settings.ADDONS_EMAIL, headers={'Reply-To': settings.THEMES_EMAIL})
null
null
null
on themes
codeqa
@taskdef send mail cleaned data theme lock with override 'en-US' theme cleaned data['theme']action cleaned data['action']comment cleaned data['comment']reject reason cleaned data['reject reason']reason Noneif reject reason reason rvw THEME REJECT REASONS[reject reason]elif action rvw ACTION DUPLICATE reason ' Duplicate Submission' emails set theme addon authors values list 'email' flat True context {'theme' theme 'base url' settings SITE URL 'reason' reason 'comment' comment}subject Noneif action rvw ACTION APPROVE subject ' Thanksforsubmittingyour Theme' template 'editors/themes/emails/approve html'elif action in rvw ACTION REJECT rvw ACTION DUPLICATE subject ' Aproblemwithyour Themesubmission' template 'editors/themes/emails/reject html'elif action rvw ACTION FLAG subject ' Themesubmissionflaggedforreview' template 'editors/themes/emails/flag reviewer html'emails [settings THEMES EMAIL]elif action rvw ACTION MOREINFO subject ' Aquestionaboutyour Themesubmission' template 'editors/themes/emails/moreinfo html'context['reviewer email'] theme lock reviewer emailsend mail jinja subject template context recipient list emails from email settings ADDONS EMAIL headers {' Reply- To' settings THEMES EMAIL}
null
null
null
null
Question: How did respective review actions take ? Code: @task def send_mail(cleaned_data, theme_lock): with override('en-US'): theme = cleaned_data['theme'] action = cleaned_data['action'] comment = cleaned_data['comment'] reject_reason = cleaned_data['reject_reason'] reason = None if reject_reason: reason = rvw.THEME_REJECT_REASONS[reject_reason] elif (action == rvw.ACTION_DUPLICATE): reason = _('Duplicate Submission') emails = set(theme.addon.authors.values_list('email', flat=True)) context = {'theme': theme, 'base_url': settings.SITE_URL, 'reason': reason, 'comment': comment} subject = None if (action == rvw.ACTION_APPROVE): subject = _('Thanks for submitting your Theme') template = 'editors/themes/emails/approve.html' elif (action in (rvw.ACTION_REJECT, rvw.ACTION_DUPLICATE)): subject = _('A problem with your Theme submission') template = 'editors/themes/emails/reject.html' elif (action == rvw.ACTION_FLAG): subject = _('Theme submission flagged for review') template = 'editors/themes/emails/flag_reviewer.html' emails = [settings.THEMES_EMAIL] elif (action == rvw.ACTION_MOREINFO): subject = _('A question about your Theme submission') template = 'editors/themes/emails/moreinfo.html' context['reviewer_email'] = theme_lock.reviewer.email send_mail_jinja(subject, template, context, recipient_list=emails, from_email=settings.ADDONS_EMAIL, headers={'Reply-To': settings.THEMES_EMAIL})
null
null
null
In which direction does the code send emails for respective review actions taken on themes ?
@task def send_mail(cleaned_data, theme_lock): with override('en-US'): theme = cleaned_data['theme'] action = cleaned_data['action'] comment = cleaned_data['comment'] reject_reason = cleaned_data['reject_reason'] reason = None if reject_reason: reason = rvw.THEME_REJECT_REASONS[reject_reason] elif (action == rvw.ACTION_DUPLICATE): reason = _('Duplicate Submission') emails = set(theme.addon.authors.values_list('email', flat=True)) context = {'theme': theme, 'base_url': settings.SITE_URL, 'reason': reason, 'comment': comment} subject = None if (action == rvw.ACTION_APPROVE): subject = _('Thanks for submitting your Theme') template = 'editors/themes/emails/approve.html' elif (action in (rvw.ACTION_REJECT, rvw.ACTION_DUPLICATE)): subject = _('A problem with your Theme submission') template = 'editors/themes/emails/reject.html' elif (action == rvw.ACTION_FLAG): subject = _('Theme submission flagged for review') template = 'editors/themes/emails/flag_reviewer.html' emails = [settings.THEMES_EMAIL] elif (action == rvw.ACTION_MOREINFO): subject = _('A question about your Theme submission') template = 'editors/themes/emails/moreinfo.html' context['reviewer_email'] = theme_lock.reviewer.email send_mail_jinja(subject, template, context, recipient_list=emails, from_email=settings.ADDONS_EMAIL, headers={'Reply-To': settings.THEMES_EMAIL})
null
null
null
out
codeqa
@taskdef send mail cleaned data theme lock with override 'en-US' theme cleaned data['theme']action cleaned data['action']comment cleaned data['comment']reject reason cleaned data['reject reason']reason Noneif reject reason reason rvw THEME REJECT REASONS[reject reason]elif action rvw ACTION DUPLICATE reason ' Duplicate Submission' emails set theme addon authors values list 'email' flat True context {'theme' theme 'base url' settings SITE URL 'reason' reason 'comment' comment}subject Noneif action rvw ACTION APPROVE subject ' Thanksforsubmittingyour Theme' template 'editors/themes/emails/approve html'elif action in rvw ACTION REJECT rvw ACTION DUPLICATE subject ' Aproblemwithyour Themesubmission' template 'editors/themes/emails/reject html'elif action rvw ACTION FLAG subject ' Themesubmissionflaggedforreview' template 'editors/themes/emails/flag reviewer html'emails [settings THEMES EMAIL]elif action rvw ACTION MOREINFO subject ' Aquestionaboutyour Themesubmission' template 'editors/themes/emails/moreinfo html'context['reviewer email'] theme lock reviewer emailsend mail jinja subject template context recipient list emails from email settings ADDONS EMAIL headers {' Reply- To' settings THEMES EMAIL}
null
null
null
null
Question: In which direction does the code send emails for respective review actions taken on themes ? Code: @task def send_mail(cleaned_data, theme_lock): with override('en-US'): theme = cleaned_data['theme'] action = cleaned_data['action'] comment = cleaned_data['comment'] reject_reason = cleaned_data['reject_reason'] reason = None if reject_reason: reason = rvw.THEME_REJECT_REASONS[reject_reason] elif (action == rvw.ACTION_DUPLICATE): reason = _('Duplicate Submission') emails = set(theme.addon.authors.values_list('email', flat=True)) context = {'theme': theme, 'base_url': settings.SITE_URL, 'reason': reason, 'comment': comment} subject = None if (action == rvw.ACTION_APPROVE): subject = _('Thanks for submitting your Theme') template = 'editors/themes/emails/approve.html' elif (action in (rvw.ACTION_REJECT, rvw.ACTION_DUPLICATE)): subject = _('A problem with your Theme submission') template = 'editors/themes/emails/reject.html' elif (action == rvw.ACTION_FLAG): subject = _('Theme submission flagged for review') template = 'editors/themes/emails/flag_reviewer.html' emails = [settings.THEMES_EMAIL] elif (action == rvw.ACTION_MOREINFO): subject = _('A question about your Theme submission') template = 'editors/themes/emails/moreinfo.html' context['reviewer_email'] = theme_lock.reviewer.email send_mail_jinja(subject, template, context, recipient_list=emails, from_email=settings.ADDONS_EMAIL, headers={'Reply-To': settings.THEMES_EMAIL})
null
null
null
What does the code send out for respective review actions taken on themes ?
@task def send_mail(cleaned_data, theme_lock): with override('en-US'): theme = cleaned_data['theme'] action = cleaned_data['action'] comment = cleaned_data['comment'] reject_reason = cleaned_data['reject_reason'] reason = None if reject_reason: reason = rvw.THEME_REJECT_REASONS[reject_reason] elif (action == rvw.ACTION_DUPLICATE): reason = _('Duplicate Submission') emails = set(theme.addon.authors.values_list('email', flat=True)) context = {'theme': theme, 'base_url': settings.SITE_URL, 'reason': reason, 'comment': comment} subject = None if (action == rvw.ACTION_APPROVE): subject = _('Thanks for submitting your Theme') template = 'editors/themes/emails/approve.html' elif (action in (rvw.ACTION_REJECT, rvw.ACTION_DUPLICATE)): subject = _('A problem with your Theme submission') template = 'editors/themes/emails/reject.html' elif (action == rvw.ACTION_FLAG): subject = _('Theme submission flagged for review') template = 'editors/themes/emails/flag_reviewer.html' emails = [settings.THEMES_EMAIL] elif (action == rvw.ACTION_MOREINFO): subject = _('A question about your Theme submission') template = 'editors/themes/emails/moreinfo.html' context['reviewer_email'] = theme_lock.reviewer.email send_mail_jinja(subject, template, context, recipient_list=emails, from_email=settings.ADDONS_EMAIL, headers={'Reply-To': settings.THEMES_EMAIL})
null
null
null
emails
codeqa
@taskdef send mail cleaned data theme lock with override 'en-US' theme cleaned data['theme']action cleaned data['action']comment cleaned data['comment']reject reason cleaned data['reject reason']reason Noneif reject reason reason rvw THEME REJECT REASONS[reject reason]elif action rvw ACTION DUPLICATE reason ' Duplicate Submission' emails set theme addon authors values list 'email' flat True context {'theme' theme 'base url' settings SITE URL 'reason' reason 'comment' comment}subject Noneif action rvw ACTION APPROVE subject ' Thanksforsubmittingyour Theme' template 'editors/themes/emails/approve html'elif action in rvw ACTION REJECT rvw ACTION DUPLICATE subject ' Aproblemwithyour Themesubmission' template 'editors/themes/emails/reject html'elif action rvw ACTION FLAG subject ' Themesubmissionflaggedforreview' template 'editors/themes/emails/flag reviewer html'emails [settings THEMES EMAIL]elif action rvw ACTION MOREINFO subject ' Aquestionaboutyour Themesubmission' template 'editors/themes/emails/moreinfo html'context['reviewer email'] theme lock reviewer emailsend mail jinja subject template context recipient list emails from email settings ADDONS EMAIL headers {' Reply- To' settings THEMES EMAIL}
null
null
null
null
Question: What does the code send out for respective review actions taken on themes ? Code: @task def send_mail(cleaned_data, theme_lock): with override('en-US'): theme = cleaned_data['theme'] action = cleaned_data['action'] comment = cleaned_data['comment'] reject_reason = cleaned_data['reject_reason'] reason = None if reject_reason: reason = rvw.THEME_REJECT_REASONS[reject_reason] elif (action == rvw.ACTION_DUPLICATE): reason = _('Duplicate Submission') emails = set(theme.addon.authors.values_list('email', flat=True)) context = {'theme': theme, 'base_url': settings.SITE_URL, 'reason': reason, 'comment': comment} subject = None if (action == rvw.ACTION_APPROVE): subject = _('Thanks for submitting your Theme') template = 'editors/themes/emails/approve.html' elif (action in (rvw.ACTION_REJECT, rvw.ACTION_DUPLICATE)): subject = _('A problem with your Theme submission') template = 'editors/themes/emails/reject.html' elif (action == rvw.ACTION_FLAG): subject = _('Theme submission flagged for review') template = 'editors/themes/emails/flag_reviewer.html' emails = [settings.THEMES_EMAIL] elif (action == rvw.ACTION_MOREINFO): subject = _('A question about your Theme submission') template = 'editors/themes/emails/moreinfo.html' context['reviewer_email'] = theme_lock.reviewer.email send_mail_jinja(subject, template, context, recipient_list=emails, from_email=settings.ADDONS_EMAIL, headers={'Reply-To': settings.THEMES_EMAIL})
null
null
null
For what purpose does the code send emails out ?
@task def send_mail(cleaned_data, theme_lock): with override('en-US'): theme = cleaned_data['theme'] action = cleaned_data['action'] comment = cleaned_data['comment'] reject_reason = cleaned_data['reject_reason'] reason = None if reject_reason: reason = rvw.THEME_REJECT_REASONS[reject_reason] elif (action == rvw.ACTION_DUPLICATE): reason = _('Duplicate Submission') emails = set(theme.addon.authors.values_list('email', flat=True)) context = {'theme': theme, 'base_url': settings.SITE_URL, 'reason': reason, 'comment': comment} subject = None if (action == rvw.ACTION_APPROVE): subject = _('Thanks for submitting your Theme') template = 'editors/themes/emails/approve.html' elif (action in (rvw.ACTION_REJECT, rvw.ACTION_DUPLICATE)): subject = _('A problem with your Theme submission') template = 'editors/themes/emails/reject.html' elif (action == rvw.ACTION_FLAG): subject = _('Theme submission flagged for review') template = 'editors/themes/emails/flag_reviewer.html' emails = [settings.THEMES_EMAIL] elif (action == rvw.ACTION_MOREINFO): subject = _('A question about your Theme submission') template = 'editors/themes/emails/moreinfo.html' context['reviewer_email'] = theme_lock.reviewer.email send_mail_jinja(subject, template, context, recipient_list=emails, from_email=settings.ADDONS_EMAIL, headers={'Reply-To': settings.THEMES_EMAIL})
null
null
null
for respective review actions taken on themes
codeqa
@taskdef send mail cleaned data theme lock with override 'en-US' theme cleaned data['theme']action cleaned data['action']comment cleaned data['comment']reject reason cleaned data['reject reason']reason Noneif reject reason reason rvw THEME REJECT REASONS[reject reason]elif action rvw ACTION DUPLICATE reason ' Duplicate Submission' emails set theme addon authors values list 'email' flat True context {'theme' theme 'base url' settings SITE URL 'reason' reason 'comment' comment}subject Noneif action rvw ACTION APPROVE subject ' Thanksforsubmittingyour Theme' template 'editors/themes/emails/approve html'elif action in rvw ACTION REJECT rvw ACTION DUPLICATE subject ' Aproblemwithyour Themesubmission' template 'editors/themes/emails/reject html'elif action rvw ACTION FLAG subject ' Themesubmissionflaggedforreview' template 'editors/themes/emails/flag reviewer html'emails [settings THEMES EMAIL]elif action rvw ACTION MOREINFO subject ' Aquestionaboutyour Themesubmission' template 'editors/themes/emails/moreinfo html'context['reviewer email'] theme lock reviewer emailsend mail jinja subject template context recipient list emails from email settings ADDONS EMAIL headers {' Reply- To' settings THEMES EMAIL}
null
null
null
null
Question: For what purpose does the code send emails out ? Code: @task def send_mail(cleaned_data, theme_lock): with override('en-US'): theme = cleaned_data['theme'] action = cleaned_data['action'] comment = cleaned_data['comment'] reject_reason = cleaned_data['reject_reason'] reason = None if reject_reason: reason = rvw.THEME_REJECT_REASONS[reject_reason] elif (action == rvw.ACTION_DUPLICATE): reason = _('Duplicate Submission') emails = set(theme.addon.authors.values_list('email', flat=True)) context = {'theme': theme, 'base_url': settings.SITE_URL, 'reason': reason, 'comment': comment} subject = None if (action == rvw.ACTION_APPROVE): subject = _('Thanks for submitting your Theme') template = 'editors/themes/emails/approve.html' elif (action in (rvw.ACTION_REJECT, rvw.ACTION_DUPLICATE)): subject = _('A problem with your Theme submission') template = 'editors/themes/emails/reject.html' elif (action == rvw.ACTION_FLAG): subject = _('Theme submission flagged for review') template = 'editors/themes/emails/flag_reviewer.html' emails = [settings.THEMES_EMAIL] elif (action == rvw.ACTION_MOREINFO): subject = _('A question about your Theme submission') template = 'editors/themes/emails/moreinfo.html' context['reviewer_email'] = theme_lock.reviewer.email send_mail_jinja(subject, template, context, recipient_list=emails, from_email=settings.ADDONS_EMAIL, headers={'Reply-To': settings.THEMES_EMAIL})
null
null
null
How did ports create ?
def collect_neutron_ports(bridges): ports = [] for bridge in bridges: ovs = ovs_lib.OVSBridge(bridge) ports += [port.port_name for port in ovs.get_vif_ports()] return ports
null
null
null
by neutron
codeqa
def collect neutron ports bridges ports []for bridge in bridges ovs ovs lib OVS Bridge bridge ports + [port port name for port in ovs get vif ports ]return ports
null
null
null
null
Question: How did ports create ? Code: def collect_neutron_ports(bridges): ports = [] for bridge in bridges: ovs = ovs_lib.OVSBridge(bridge) ports += [port.port_name for port in ovs.get_vif_ports()] return ports
null
null
null
What did the user start ?
def build_user_vars(registry, xml_parent, data): XML.SubElement(xml_parent, 'org.jenkinsci.plugins.builduser.BuildUser')
null
null
null
the build
codeqa
def build user vars registry xml parent data XML Sub Element xml parent 'org jenkinsci plugins builduser Build User'
null
null
null
null
Question: What did the user start ? Code: def build_user_vars(registry, xml_parent, data): XML.SubElement(xml_parent, 'org.jenkinsci.plugins.builduser.BuildUser')
null
null
null
What started the build ?
def build_user_vars(registry, xml_parent, data): XML.SubElement(xml_parent, 'org.jenkinsci.plugins.builduser.BuildUser')
null
null
null
the user
codeqa
def build user vars registry xml parent data XML Sub Element xml parent 'org jenkinsci plugins builduser Build User'
null
null
null
null
Question: What started the build ? Code: def build_user_vars(registry, xml_parent, data): XML.SubElement(xml_parent, 'org.jenkinsci.plugins.builduser.BuildUser')
null
null
null
What does the code add ?
def sum_expr(operators): return lo.LinOp(lo.SUM, operators[0].size, operators, None)
null
null
null
linear operators
codeqa
def sum expr operators return lo Lin Op lo SUM operators[ 0 ] size operators None
null
null
null
null
Question: What does the code add ? Code: def sum_expr(operators): return lo.LinOp(lo.SUM, operators[0].size, operators, None)
null
null
null
For what purpose did parameters need ?
def goGoodSamaritan(prevValue, originalCharset): if (kb.commonOutputs is None): initCommonOutputs() predictionSet = set() commonValue = None commonPattern = None countCommonValue = 0 if (kb.partRun in kb.commonOutputs): commonPartOutputs = kb.commonOutputs[kb.partRun] commonPattern = commonFinderOnly(prevValue, commonPartOutputs) if (commonPattern and (commonPattern == prevValue)): commonPattern = None for item in commonPartOutputs: if item.startswith(prevValue): commonValue = item countCommonValue += 1 if (len(item) > len(prevValue)): char = item[len(prevValue)] predictionSet.add(char) if (countCommonValue > 1): commonValue = None commonCharset = [] otherCharset = [] for ordChar in originalCharset: if (chr(ordChar) not in predictionSet): otherCharset.append(ordChar) else: commonCharset.append(ordChar) commonCharset.sort() return (commonValue, commonPattern, commonCharset, originalCharset) else: return (None, None, None, originalCharset)
null
null
null
for common prediction feature
codeqa
def go Good Samaritan prev Value original Charset if kb common Outputs is None init Common Outputs prediction Set set common Value Nonecommon Pattern Nonecount Common Value 0if kb part Run in kb common Outputs common Part Outputs kb common Outputs[kb part Run]common Pattern common Finder Only prev Value common Part Outputs if common Pattern and common Pattern prev Value common Pattern Nonefor item in common Part Outputs if item startswith prev Value common Value itemcount Common Value + 1if len item > len prev Value char item[len prev Value ]prediction Set add char if count Common Value > 1 common Value Nonecommon Charset []other Charset []for ord Char in original Charset if chr ord Char not in prediction Set other Charset append ord Char else common Charset append ord Char common Charset sort return common Value common Pattern common Charset original Charset else return None None None original Charset
null
null
null
null
Question: For what purpose did parameters need ? Code: def goGoodSamaritan(prevValue, originalCharset): if (kb.commonOutputs is None): initCommonOutputs() predictionSet = set() commonValue = None commonPattern = None countCommonValue = 0 if (kb.partRun in kb.commonOutputs): commonPartOutputs = kb.commonOutputs[kb.partRun] commonPattern = commonFinderOnly(prevValue, commonPartOutputs) if (commonPattern and (commonPattern == prevValue)): commonPattern = None for item in commonPartOutputs: if item.startswith(prevValue): commonValue = item countCommonValue += 1 if (len(item) > len(prevValue)): char = item[len(prevValue)] predictionSet.add(char) if (countCommonValue > 1): commonValue = None commonCharset = [] otherCharset = [] for ordChar in originalCharset: if (chr(ordChar) not in predictionSet): otherCharset.append(ordChar) else: commonCharset.append(ordChar) commonCharset.sort() return (commonValue, commonPattern, commonCharset, originalCharset) else: return (None, None, None, originalCharset)
null
null
null
What do decorator skip if condition is true ?
def skip_if(condition, msg=None): def deco(test): @tools.make_decorator(test) def skipper(*args, **kwds): if condition: raise SkipTest((msg or 'conditional skip')) return test(*args, **kwds) return skipper return deco
null
null
null
test
codeqa
def skip if condition msg None def deco test @tools make decorator test def skipper *args **kwds if condition raise Skip Test msg or 'conditionalskip' return test *args **kwds return skipperreturn deco
null
null
null
null
Question: What do decorator skip if condition is true ? Code: def skip_if(condition, msg=None): def deco(test): @tools.make_decorator(test) def skipper(*args, **kwds): if condition: raise SkipTest((msg or 'conditional skip')) return test(*args, **kwds) return skipper return deco
null
null
null
What skips test if condition is true ?
def skip_if(condition, msg=None): def deco(test): @tools.make_decorator(test) def skipper(*args, **kwds): if condition: raise SkipTest((msg or 'conditional skip')) return test(*args, **kwds) return skipper return deco
null
null
null
decorator
codeqa
def skip if condition msg None def deco test @tools make decorator test def skipper *args **kwds if condition raise Skip Test msg or 'conditionalskip' return test *args **kwds return skipperreturn deco
null
null
null
null
Question: What skips test if condition is true ? Code: def skip_if(condition, msg=None): def deco(test): @tools.make_decorator(test) def skipper(*args, **kwds): if condition: raise SkipTest((msg or 'conditional skip')) return test(*args, **kwds) return skipper return deco
null
null
null
What does the code get ?
def _get_service_endpoint(context, svc, region=None, public=True): region = _safe_region(region) context = (context or identity) url_type = {True: 'public', False: 'private'}[public] svc_obj = context.services.get(svc) if (not svc_obj): return None ep = svc_obj.endpoints.get(region, {}).get(url_type) if (not ep): ep = svc_obj.endpoints.get('ALL', {}).get(url_type) return ep
null
null
null
the proper endpoint for the given service
codeqa
def get service endpoint context svc region None public True region safe region region context context or identity url type { True 'public' False 'private'}[public]svc obj context services get svc if not svc obj return Noneep svc obj endpoints get region {} get url type if not ep ep svc obj endpoints get 'ALL' {} get url type return ep
null
null
null
null
Question: What does the code get ? Code: def _get_service_endpoint(context, svc, region=None, public=True): region = _safe_region(region) context = (context or identity) url_type = {True: 'public', False: 'private'}[public] svc_obj = context.services.get(svc) if (not svc_obj): return None ep = svc_obj.endpoints.get(region, {}).get(url_type) if (not ep): ep = svc_obj.endpoints.get('ALL', {}).get(url_type) return ep
null
null
null
What does the code get ?
def get_num_profiles(): error_encountered = True profiles = get_install_server_profiles() if (profiles is not None): if (len(profiles) < 1): return 1 else: return (len(profiles) + 1) if error_encountered: return 1
null
null
null
the number of profiles
codeqa
def get num profiles error encountered Trueprofiles get install server profiles if profiles is not None if len profiles < 1 return 1else return len profiles + 1 if error encountered return 1
null
null
null
null
Question: What does the code get ? Code: def get_num_profiles(): error_encountered = True profiles = get_install_server_profiles() if (profiles is not None): if (len(profiles) < 1): return 1 else: return (len(profiles) + 1) if error_encountered: return 1
null
null
null
What do decorator define ?
def roles(*role_list): return _list_annotating_decorator('roles', *role_list)
null
null
null
a list of role names
codeqa
def roles *role list return list annotating decorator 'roles' *role list
null
null
null
null
Question: What do decorator define ? Code: def roles(*role_list): return _list_annotating_decorator('roles', *role_list)
null
null
null
What is defining a list of role names ?
def roles(*role_list): return _list_annotating_decorator('roles', *role_list)
null
null
null
decorator
codeqa
def roles *role list return list annotating decorator 'roles' *role list
null
null
null
null
Question: What is defining a list of role names ? Code: def roles(*role_list): return _list_annotating_decorator('roles', *role_list)
null
null
null
What does the code get ?
@register.tag def get_people(parser, token): try: (tag_name, arg) = token.contents.split(None, 1) except ValueError: raise template.TemplateSyntaxError, ('%s tag requires arguments' % token.contents.split()[0]) m1 = re.search('as (\\w+)', arg) m2 = re.search('(.*?) as (\\w+)', arg) if (not m1): raise template.TemplateSyntaxError, ('%s tag had invalid arguments' % tag_name) else: var_name = m1.groups()[0] return GetPeople(var_name) if (not m2): raise template.TemplateSyntaxError, ('%s tag had invalid arguments' % tag_name) else: (format_string, var_name) = m2.groups() return GetPeople(var_name, format_string[0])
null
null
null
any number of latest posts
codeqa
@register tagdef get people parser token try tag name arg token contents split None 1 except Value Error raise template Template Syntax Error '%stagrequiresarguments' % token contents split [0 ] m1 re search 'as \\w+ ' arg m2 re search ' *? as \\w+ ' arg if not m1 raise template Template Syntax Error '%staghadinvalidarguments' % tag name else var name m1 groups [0 ]return Get People var name if not m2 raise template Template Syntax Error '%staghadinvalidarguments' % tag name else format string var name m2 groups return Get People var name format string[ 0 ]
null
null
null
null
Question: What does the code get ? Code: @register.tag def get_people(parser, token): try: (tag_name, arg) = token.contents.split(None, 1) except ValueError: raise template.TemplateSyntaxError, ('%s tag requires arguments' % token.contents.split()[0]) m1 = re.search('as (\\w+)', arg) m2 = re.search('(.*?) as (\\w+)', arg) if (not m1): raise template.TemplateSyntaxError, ('%s tag had invalid arguments' % tag_name) else: var_name = m1.groups()[0] return GetPeople(var_name) if (not m2): raise template.TemplateSyntaxError, ('%s tag had invalid arguments' % tag_name) else: (format_string, var_name) = m2.groups() return GetPeople(var_name, format_string[0])
null
null
null
What did the code set ?
def set_exception_context(e, s): e._context = s
null
null
null
the context of a given exception
codeqa
def set exception context e s e context s
null
null
null
null
Question: What did the code set ? Code: def set_exception_context(e, s): e._context = s
null
null
null
What did the code read ?
def get_config_from_root(root): setup_cfg = os.path.join(root, 'setup.cfg') parser = configparser.SafeConfigParser() with open(setup_cfg, 'r') as f: parser.readfp(f) VCS = parser.get('versioneer', 'VCS') def get(parser, name): if parser.has_option('versioneer', name): return parser.get('versioneer', name) return None cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = (get(parser, 'style') or '') cfg.versionfile_source = get(parser, 'versionfile_source') cfg.versionfile_build = get(parser, 'versionfile_build') cfg.tag_prefix = get(parser, 'tag_prefix') if (cfg.tag_prefix in ("''", '""')): cfg.tag_prefix = '' cfg.parentdir_prefix = get(parser, 'parentdir_prefix') cfg.verbose = get(parser, 'verbose') return cfg
null
null
null
the project setup
codeqa
def get config from root root setup cfg os path join root 'setup cfg' parser configparser Safe Config Parser with open setup cfg 'r' as f parser readfp f VCS parser get 'versioneer' 'VCS' def get parser name if parser has option 'versioneer' name return parser get 'versioneer' name return Nonecfg Versioneer Config cfg VCS VC Scfg style get parser 'style' or '' cfg versionfile source get parser 'versionfile source' cfg versionfile build get parser 'versionfile build' cfg tag prefix get parser 'tag prefix' if cfg tag prefix in "''" '""' cfg tag prefix ''cfg parentdir prefix get parser 'parentdir prefix' cfg verbose get parser 'verbose' return cfg
null
null
null
null
Question: What did the code read ? Code: def get_config_from_root(root): setup_cfg = os.path.join(root, 'setup.cfg') parser = configparser.SafeConfigParser() with open(setup_cfg, 'r') as f: parser.readfp(f) VCS = parser.get('versioneer', 'VCS') def get(parser, name): if parser.has_option('versioneer', name): return parser.get('versioneer', name) return None cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = (get(parser, 'style') or '') cfg.versionfile_source = get(parser, 'versionfile_source') cfg.versionfile_build = get(parser, 'versionfile_build') cfg.tag_prefix = get(parser, 'tag_prefix') if (cfg.tag_prefix in ("''", '""')): cfg.tag_prefix = '' cfg.parentdir_prefix = get(parser, 'parentdir_prefix') cfg.verbose = get(parser, 'verbose') return cfg
null
null
null
How does the code convert a tuple string into a tuple ?
def strtotuple(s): if (not match('^[,.0-9 ()\\[\\]]*$', s)): raise Exception('Invalid characters in string for tuple conversion') if (s.count('(') != s.count(')')): raise Exception('Invalid count of ( and )') if (s.count('[') != s.count(']')): raise Exception('Invalid count of [ and ]') r = eval(s) if (type(r) not in (list, tuple)): raise Exception('Conversion failed') return r
null
null
null
with some security checks
codeqa
def strtotuple s if not match '^[ 0- 9 \\[\\]]*$' s raise Exception ' Invalidcharactersinstringfortupleconversion' if s count ' ' s count ' ' raise Exception ' Invalidcountof and ' if s count '[' s count ']' raise Exception ' Invalidcountof[and]' r eval s if type r not in list tuple raise Exception ' Conversionfailed' return r
null
null
null
null
Question: How does the code convert a tuple string into a tuple ? Code: def strtotuple(s): if (not match('^[,.0-9 ()\\[\\]]*$', s)): raise Exception('Invalid characters in string for tuple conversion') if (s.count('(') != s.count(')')): raise Exception('Invalid count of ( and )') if (s.count('[') != s.count(']')): raise Exception('Invalid count of [ and ]') r = eval(s) if (type(r) not in (list, tuple)): raise Exception('Conversion failed') return r
null
null
null
What does the code convert into a tuple with some security checks ?
def strtotuple(s): if (not match('^[,.0-9 ()\\[\\]]*$', s)): raise Exception('Invalid characters in string for tuple conversion') if (s.count('(') != s.count(')')): raise Exception('Invalid count of ( and )') if (s.count('[') != s.count(']')): raise Exception('Invalid count of [ and ]') r = eval(s) if (type(r) not in (list, tuple)): raise Exception('Conversion failed') return r
null
null
null
a tuple string
codeqa
def strtotuple s if not match '^[ 0- 9 \\[\\]]*$' s raise Exception ' Invalidcharactersinstringfortupleconversion' if s count ' ' s count ' ' raise Exception ' Invalidcountof and ' if s count '[' s count ']' raise Exception ' Invalidcountof[and]' r eval s if type r not in list tuple raise Exception ' Conversionfailed' return r
null
null
null
null
Question: What does the code convert into a tuple with some security checks ? Code: def strtotuple(s): if (not match('^[,.0-9 ()\\[\\]]*$', s)): raise Exception('Invalid characters in string for tuple conversion') if (s.count('(') != s.count(')')): raise Exception('Invalid count of ( and )') if (s.count('[') != s.count(']')): raise Exception('Invalid count of [ and ]') r = eval(s) if (type(r) not in (list, tuple)): raise Exception('Conversion failed') return r
null
null
null
What does the code generate ?
def parse_commits(head, name): for commit in head.traverse(): (yield {'_id': commit.hexsha, '_parent': name, 'committed_date': datetime.fromtimestamp(commit.committed_date), 'committer': {'name': commit.committer.name, 'email': commit.committer.email}, 'authored_date': datetime.fromtimestamp(commit.authored_date), 'author': {'name': commit.author.name, 'email': commit.author.email}, 'description': commit.message, 'parent_shas': [p.hexsha for p in commit.parents], 'files': list(commit.stats.files), 'stats': commit.stats.total})
null
null
null
a document per commit containing all the metadata
codeqa
def parse commits head name for commit in head traverse yield {' id' commit hexsha ' parent' name 'committed date' datetime fromtimestamp commit committed date 'committer' {'name' commit committer name 'email' commit committer email} 'authored date' datetime fromtimestamp commit authored date 'author' {'name' commit author name 'email' commit author email} 'description' commit message 'parent shas' [p hexsha for p in commit parents] 'files' list commit stats files 'stats' commit stats total}
null
null
null
null
Question: What does the code generate ? Code: def parse_commits(head, name): for commit in head.traverse(): (yield {'_id': commit.hexsha, '_parent': name, 'committed_date': datetime.fromtimestamp(commit.committed_date), 'committer': {'name': commit.committer.name, 'email': commit.committer.email}, 'authored_date': datetime.fromtimestamp(commit.authored_date), 'author': {'name': commit.author.name, 'email': commit.author.email}, 'description': commit.message, 'parent_shas': [p.hexsha for p in commit.parents], 'files': list(commit.stats.files), 'stats': commit.stats.total})
null
null
null
What is containing all the metadata ?
def parse_commits(head, name): for commit in head.traverse(): (yield {'_id': commit.hexsha, '_parent': name, 'committed_date': datetime.fromtimestamp(commit.committed_date), 'committer': {'name': commit.committer.name, 'email': commit.committer.email}, 'authored_date': datetime.fromtimestamp(commit.authored_date), 'author': {'name': commit.author.name, 'email': commit.author.email}, 'description': commit.message, 'parent_shas': [p.hexsha for p in commit.parents], 'files': list(commit.stats.files), 'stats': commit.stats.total})
null
null
null
a document
codeqa
def parse commits head name for commit in head traverse yield {' id' commit hexsha ' parent' name 'committed date' datetime fromtimestamp commit committed date 'committer' {'name' commit committer name 'email' commit committer email} 'authored date' datetime fromtimestamp commit authored date 'author' {'name' commit author name 'email' commit author email} 'description' commit message 'parent shas' [p hexsha for p in commit parents] 'files' list commit stats files 'stats' commit stats total}
null
null
null
null
Question: What is containing all the metadata ? Code: def parse_commits(head, name): for commit in head.traverse(): (yield {'_id': commit.hexsha, '_parent': name, 'committed_date': datetime.fromtimestamp(commit.committed_date), 'committer': {'name': commit.committer.name, 'email': commit.committer.email}, 'authored_date': datetime.fromtimestamp(commit.authored_date), 'author': {'name': commit.author.name, 'email': commit.author.email}, 'description': commit.message, 'parent_shas': [p.hexsha for p in commit.parents], 'files': list(commit.stats.files), 'stats': commit.stats.total})
null
null
null
What does the code send ?
def notify(conf, context, topic, msg, connection_pool, envelope): LOG.debug(_('Sending %(event_type)s on %(topic)s'), dict(event_type=msg.get('event_type'), topic=topic)) _add_unique_id(msg) pack_context(msg, context) with ConnectionContext(conf, connection_pool) as conn: if envelope: msg = rpc_common.serialize_msg(msg) conn.notify_send(topic, msg)
null
null
null
a notification event on a topic
codeqa
def notify conf context topic msg connection pool envelope LOG debug ' Sending% event type son% topic s' dict event type msg get 'event type' topic topic add unique id msg pack context msg context with Connection Context conf connection pool as conn if envelope msg rpc common serialize msg msg conn notify send topic msg
null
null
null
null
Question: What does the code send ? Code: def notify(conf, context, topic, msg, connection_pool, envelope): LOG.debug(_('Sending %(event_type)s on %(topic)s'), dict(event_type=msg.get('event_type'), topic=topic)) _add_unique_id(msg) pack_context(msg, context) with ConnectionContext(conf, connection_pool) as conn: if envelope: msg = rpc_common.serialize_msg(msg) conn.notify_send(topic, msg)
null
null
null
What does the code ignore ?
def ignore(name): to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return (to_ignore in list_ignored())
null
null
null
a specific program update
codeqa
def ignore name to ignore name rsplit '-' 1 [0 ]cmd ['softwareupdate' '--ignore' to ignore]salt utils mac utils execute return success cmd return to ignore in list ignored
null
null
null
null
Question: What does the code ignore ? Code: def ignore(name): to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return (to_ignore in list_ignored())
null
null
null
Where do the previous tasks be task ?
@shared_task(bind=True) def collect_ids(self, res, i): return (res, (self.request.root_id, self.request.parent_id, i))
null
null
null
a chain or group
codeqa
@shared task bind True def collect ids self res i return res self request root id self request parent id i
null
null
null
null
Question: Where do the previous tasks be task ? Code: @shared_task(bind=True) def collect_ids(self, res, i): return (res, (self.request.root_id, self.request.parent_id, i))