labNo
float64
1
10
taskNo
float64
0
4
questioner
stringclasses
2 values
question
stringlengths
9
201
code
stringlengths
18
30.3k
startLine
float64
0
192
endLine
float64
0
196
questionType
stringclasses
4 values
answer
stringlengths
2
905
src
stringclasses
3 values
code_processed
stringlengths
12
28.3k
id
stringlengths
2
5
raw_code
stringlengths
20
30.3k
raw_comment
stringlengths
10
242
comment
stringlengths
9
207
q_code
stringlengths
66
30.3k
null
null
null
What does the code delete ?
def instance_type_extra_specs_delete(context, flavor_id, key): IMPL.instance_type_extra_specs_delete(context, flavor_id, key)
null
null
null
the given extra specs item
codeqa
def instance type extra specs delete context flavor id key IMPL instance type extra specs delete context flavor id key
null
null
null
null
Question: What does the code delete ? Code: def instance_type_extra_specs_delete(context, flavor_id, key): IMPL.instance_type_extra_specs_delete(context, flavor_id, key)
null
null
null
What does the code save to its final destination ?
def save_promo_imgs(obj, img_content): tmp_dst = os.path.join(settings.TMP_PATH, 'promo_imgs', uuid.uuid4().hex) with private_storage.open(tmp_dst, 'wb') as fd: fd.write(img_content) dirname = obj.get_promo_img_dir() destination = os.path.join(dirname, ('%s' % obj.pk)) remove_promo_imgs(destination) resize_promo_imgs(tmp_dst, destination, mkt.PROMO_IMG_SIZES, set_modified_on=[obj])
null
null
null
the promo image for obj
codeqa
def save promo imgs obj img content tmp dst os path join settings TMP PATH 'promo imgs' uuid uuid 4 hex with private storage open tmp dst 'wb' as fd fd write img content dirname obj get promo img dir destination os path join dirname '%s' % obj pk remove promo imgs destination resize promo imgs tmp dst destination mkt PROMO IMG SIZES set modified on [obj]
null
null
null
null
Question: What does the code save to its final destination ? Code: def save_promo_imgs(obj, img_content): tmp_dst = os.path.join(settings.TMP_PATH, 'promo_imgs', uuid.uuid4().hex) with private_storage.open(tmp_dst, 'wb') as fd: fd.write(img_content) dirname = obj.get_promo_img_dir() destination = os.path.join(dirname, ('%s' % obj.pk)) remove_promo_imgs(destination) resize_promo_imgs(tmp_dst, destination, mkt.PROMO_IMG_SIZES, set_modified_on=[obj])
null
null
null
What does this parameter generate random - string ?
def random_string_param(registry, xml_parent, data): pdef = XML.SubElement(xml_parent, 'hudson.plugins.random__string__parameter.RandomStringParameterDefinition') if ('name' not in data): raise JenkinsJobsException('random-string must have a name parameter.') XML.SubElement(pdef, 'name').text = data['name'] XML.SubElement(pdef, 'description').text = data.get('description', '') XML.SubElement(pdef, 'failedValidationMessage').text = data.get('failed-validation-message', '')
null
null
null
a random string
codeqa
def random string param registry xml parent data pdef XML Sub Element xml parent 'hudson plugins random string parameter Random String Parameter Definition' if 'name' not in data raise Jenkins Jobs Exception 'random-stringmusthaveanameparameter ' XML Sub Element pdef 'name' text data['name']XML Sub Element pdef 'description' text data get 'description' '' XML Sub Element pdef 'failed Validation Message' text data get 'failed-validation-message' ''
null
null
null
null
Question: What does this parameter generate random - string ? Code: def random_string_param(registry, xml_parent, data): pdef = XML.SubElement(xml_parent, 'hudson.plugins.random__string__parameter.RandomStringParameterDefinition') if ('name' not in data): raise JenkinsJobsException('random-string must have a name parameter.') XML.SubElement(pdef, 'name').text = data['name'] XML.SubElement(pdef, 'description').text = data.get('description', '') XML.SubElement(pdef, 'failedValidationMessage').text = data.get('failed-validation-message', '')
null
null
null
What passes it to the build random - string ?
def random_string_param(registry, xml_parent, data): pdef = XML.SubElement(xml_parent, 'hudson.plugins.random__string__parameter.RandomStringParameterDefinition') if ('name' not in data): raise JenkinsJobsException('random-string must have a name parameter.') XML.SubElement(pdef, 'name').text = data['name'] XML.SubElement(pdef, 'description').text = data.get('description', '') XML.SubElement(pdef, 'failedValidationMessage').text = data.get('failed-validation-message', '')
null
null
null
this parameter
codeqa
def random string param registry xml parent data pdef XML Sub Element xml parent 'hudson plugins random string parameter Random String Parameter Definition' if 'name' not in data raise Jenkins Jobs Exception 'random-stringmusthaveanameparameter ' XML Sub Element pdef 'name' text data['name']XML Sub Element pdef 'description' text data get 'description' '' XML Sub Element pdef 'failed Validation Message' text data get 'failed-validation-message' ''
null
null
null
null
Question: What passes it to the build random - string ? Code: def random_string_param(registry, xml_parent, data): pdef = XML.SubElement(xml_parent, 'hudson.plugins.random__string__parameter.RandomStringParameterDefinition') if ('name' not in data): raise JenkinsJobsException('random-string must have a name parameter.') XML.SubElement(pdef, 'name').text = data['name'] XML.SubElement(pdef, 'description').text = data.get('description', '') XML.SubElement(pdef, 'failedValidationMessage').text = data.get('failed-validation-message', '')
null
null
null
How does this parameter generate a random string ?
def random_string_param(registry, xml_parent, data): pdef = XML.SubElement(xml_parent, 'hudson.plugins.random__string__parameter.RandomStringParameterDefinition') if ('name' not in data): raise JenkinsJobsException('random-string must have a name parameter.') XML.SubElement(pdef, 'name').text = data['name'] XML.SubElement(pdef, 'description').text = data.get('description', '') XML.SubElement(pdef, 'failedValidationMessage').text = data.get('failed-validation-message', '')
null
null
null
random - string
codeqa
def random string param registry xml parent data pdef XML Sub Element xml parent 'hudson plugins random string parameter Random String Parameter Definition' if 'name' not in data raise Jenkins Jobs Exception 'random-stringmusthaveanameparameter ' XML Sub Element pdef 'name' text data['name']XML Sub Element pdef 'description' text data get 'description' '' XML Sub Element pdef 'failed Validation Message' text data get 'failed-validation-message' ''
null
null
null
null
Question: How does this parameter generate a random string ? Code: def random_string_param(registry, xml_parent, data): pdef = XML.SubElement(xml_parent, 'hudson.plugins.random__string__parameter.RandomStringParameterDefinition') if ('name' not in data): raise JenkinsJobsException('random-string must have a name parameter.') XML.SubElement(pdef, 'name').text = data['name'] XML.SubElement(pdef, 'description').text = data.get('description', '') XML.SubElement(pdef, 'failedValidationMessage').text = data.get('failed-validation-message', '')
null
null
null
How does this parameter pass it to the build ?
def random_string_param(registry, xml_parent, data): pdef = XML.SubElement(xml_parent, 'hudson.plugins.random__string__parameter.RandomStringParameterDefinition') if ('name' not in data): raise JenkinsJobsException('random-string must have a name parameter.') XML.SubElement(pdef, 'name').text = data['name'] XML.SubElement(pdef, 'description').text = data.get('description', '') XML.SubElement(pdef, 'failedValidationMessage').text = data.get('failed-validation-message', '')
null
null
null
random - string
codeqa
def random string param registry xml parent data pdef XML Sub Element xml parent 'hudson plugins random string parameter Random String Parameter Definition' if 'name' not in data raise Jenkins Jobs Exception 'random-stringmusthaveanameparameter ' XML Sub Element pdef 'name' text data['name']XML Sub Element pdef 'description' text data get 'description' '' XML Sub Element pdef 'failed Validation Message' text data get 'failed-validation-message' ''
null
null
null
null
Question: How does this parameter pass it to the build ? Code: def random_string_param(registry, xml_parent, data): pdef = XML.SubElement(xml_parent, 'hudson.plugins.random__string__parameter.RandomStringParameterDefinition') if ('name' not in data): raise JenkinsJobsException('random-string must have a name parameter.') XML.SubElement(pdef, 'name').text = data['name'] XML.SubElement(pdef, 'description').text = data.get('description', '') XML.SubElement(pdef, 'failedValidationMessage').text = data.get('failed-validation-message', '')
null
null
null
How does the code get a point - of - reference timestamp in epoch + milliseconds ?
def get_point_of_reference(unit, count, epoch=None): if (unit == 'seconds'): multiplier = 1 elif (unit == 'minutes'): multiplier = 60 elif (unit == 'hours'): multiplier = 3600 elif (unit == 'days'): multiplier = (3600 * 24) elif (unit == 'weeks'): multiplier = ((3600 * 24) * 7) elif (unit == 'months'): multiplier = ((3600 * 24) * 30) elif (unit == 'years'): multiplier = ((3600 * 24) * 365) else: raise ValueError('Invalid unit: {0}.'.format(unit)) if (not epoch): epoch = time.time() epoch = fix_epoch(epoch) return (epoch - (multiplier * count))
null
null
null
by deriving from a unit and a count
codeqa
def get point of reference unit count epoch None if unit 'seconds' multiplier 1elif unit 'minutes' multiplier 60 elif unit 'hours' multiplier 3600 elif unit 'days' multiplier 3600 * 24 elif unit 'weeks' multiplier 3600 * 24 * 7 elif unit 'months' multiplier 3600 * 24 * 30 elif unit 'years' multiplier 3600 * 24 * 365 else raise Value Error ' Invalidunit {0 } ' format unit if not epoch epoch time time epoch fix epoch epoch return epoch - multiplier * count
null
null
null
null
Question: How does the code get a point - of - reference timestamp in epoch + milliseconds ? Code: def get_point_of_reference(unit, count, epoch=None): if (unit == 'seconds'): multiplier = 1 elif (unit == 'minutes'): multiplier = 60 elif (unit == 'hours'): multiplier = 3600 elif (unit == 'days'): multiplier = (3600 * 24) elif (unit == 'weeks'): multiplier = ((3600 * 24) * 7) elif (unit == 'months'): multiplier = ((3600 * 24) * 30) elif (unit == 'years'): multiplier = ((3600 * 24) * 365) else: raise ValueError('Invalid unit: {0}.'.format(unit)) if (not epoch): epoch = time.time() epoch = fix_epoch(epoch) return (epoch - (multiplier * count))
null
null
null
What does the code get by deriving from a unit and a count in epoch + milliseconds ?
def get_point_of_reference(unit, count, epoch=None): if (unit == 'seconds'): multiplier = 1 elif (unit == 'minutes'): multiplier = 60 elif (unit == 'hours'): multiplier = 3600 elif (unit == 'days'): multiplier = (3600 * 24) elif (unit == 'weeks'): multiplier = ((3600 * 24) * 7) elif (unit == 'months'): multiplier = ((3600 * 24) * 30) elif (unit == 'years'): multiplier = ((3600 * 24) * 365) else: raise ValueError('Invalid unit: {0}.'.format(unit)) if (not epoch): epoch = time.time() epoch = fix_epoch(epoch) return (epoch - (multiplier * count))
null
null
null
a point - of - reference timestamp
codeqa
def get point of reference unit count epoch None if unit 'seconds' multiplier 1elif unit 'minutes' multiplier 60 elif unit 'hours' multiplier 3600 elif unit 'days' multiplier 3600 * 24 elif unit 'weeks' multiplier 3600 * 24 * 7 elif unit 'months' multiplier 3600 * 24 * 30 elif unit 'years' multiplier 3600 * 24 * 365 else raise Value Error ' Invalidunit {0 } ' format unit if not epoch epoch time time epoch fix epoch epoch return epoch - multiplier * count
null
null
null
null
Question: What does the code get by deriving from a unit and a count in epoch + milliseconds ? Code: def get_point_of_reference(unit, count, epoch=None): if (unit == 'seconds'): multiplier = 1 elif (unit == 'minutes'): multiplier = 60 elif (unit == 'hours'): multiplier = 3600 elif (unit == 'days'): multiplier = (3600 * 24) elif (unit == 'weeks'): multiplier = ((3600 * 24) * 7) elif (unit == 'months'): multiplier = ((3600 * 24) * 30) elif (unit == 'years'): multiplier = ((3600 * 24) * 365) else: raise ValueError('Invalid unit: {0}.'.format(unit)) if (not epoch): epoch = time.time() epoch = fix_epoch(epoch) return (epoch - (multiplier * count))
null
null
null
When does the code get a point - of - reference timestamp by deriving from a unit and a count ?
def get_point_of_reference(unit, count, epoch=None): if (unit == 'seconds'): multiplier = 1 elif (unit == 'minutes'): multiplier = 60 elif (unit == 'hours'): multiplier = 3600 elif (unit == 'days'): multiplier = (3600 * 24) elif (unit == 'weeks'): multiplier = ((3600 * 24) * 7) elif (unit == 'months'): multiplier = ((3600 * 24) * 30) elif (unit == 'years'): multiplier = ((3600 * 24) * 365) else: raise ValueError('Invalid unit: {0}.'.format(unit)) if (not epoch): epoch = time.time() epoch = fix_epoch(epoch) return (epoch - (multiplier * count))
null
null
null
in epoch + milliseconds
codeqa
def get point of reference unit count epoch None if unit 'seconds' multiplier 1elif unit 'minutes' multiplier 60 elif unit 'hours' multiplier 3600 elif unit 'days' multiplier 3600 * 24 elif unit 'weeks' multiplier 3600 * 24 * 7 elif unit 'months' multiplier 3600 * 24 * 30 elif unit 'years' multiplier 3600 * 24 * 365 else raise Value Error ' Invalidunit {0 } ' format unit if not epoch epoch time time epoch fix epoch epoch return epoch - multiplier * count
null
null
null
null
Question: When does the code get a point - of - reference timestamp by deriving from a unit and a count ? Code: def get_point_of_reference(unit, count, epoch=None): if (unit == 'seconds'): multiplier = 1 elif (unit == 'minutes'): multiplier = 60 elif (unit == 'hours'): multiplier = 3600 elif (unit == 'days'): multiplier = (3600 * 24) elif (unit == 'weeks'): multiplier = ((3600 * 24) * 7) elif (unit == 'months'): multiplier = ((3600 * 24) * 30) elif (unit == 'years'): multiplier = ((3600 * 24) * 365) else: raise ValueError('Invalid unit: {0}.'.format(unit)) if (not epoch): epoch = time.time() epoch = fix_epoch(epoch) return (epoch - (multiplier * count))
null
null
null
What will be using it ?
@utils_routes.route('/serve_static/<path:filename>') def serve_static(filename): return send_from_directory((current_app.config['BASE_DIR'] + '/static/'), filename)
null
null
null
only development system
codeqa
@utils routes route '/serve static/<path filename>' def serve static filename return send from directory current app config['BASE DIR'] + '/static/' filename
null
null
null
null
Question: What will be using it ? Code: @utils_routes.route('/serve_static/<path:filename>') def serve_static(filename): return send_from_directory((current_app.config['BASE_DIR'] + '/static/'), filename)
null
null
null
What does the code shorten with the given length ?
def truncate_name(name, length=None): if ((length is None) or (len(name) <= length)): return name hash = md5_constructor(name).hexdigest()[:4] return ('%s%s' % (name[:(length - 4)], hash))
null
null
null
a string
codeqa
def truncate name name length None if length is None or len name < length return namehash md 5 constructor name hexdigest [ 4]return '%s%s' % name[ length - 4 ] hash
null
null
null
null
Question: What does the code shorten with the given length ? Code: def truncate_name(name, length=None): if ((length is None) or (len(name) <= length)): return name hash = md5_constructor(name).hexdigest()[:4] return ('%s%s' % (name[:(length - 4)], hash))
null
null
null
What does the code retrieve ?
@block_user_agents @require_GET @allow_CORS_GET @process_document_path def children(request, document_slug, document_locale): expand = ('expand' in request.GET) max_depth = 5 depth = int(request.GET.get('depth', max_depth)) if (depth > max_depth): depth = max_depth result = [] try: doc = Document.objects.get(locale=document_locale, slug=document_slug) result = _make_doc_structure(doc, 0, expand, depth) if (result is None): result = {'error': 'Document has moved.'} except Document.DoesNotExist: result = {'error': 'Document does not exist.'} return JsonResponse(result)
null
null
null
a document
codeqa
@block user agents@require GET@allow CORS GET@process document pathdef children request document slug document locale expand 'expand' in request GET max depth 5depth int request GET get 'depth' max depth if depth > max depth depth max depthresult []try doc Document objects get locale document locale slug document slug result make doc structure doc 0 expand depth if result is None result {'error' ' Documenthasmoved '}except Document Does Not Exist result {'error' ' Documentdoesnotexist '}return Json Response result
null
null
null
null
Question: What does the code retrieve ? Code: @block_user_agents @require_GET @allow_CORS_GET @process_document_path def children(request, document_slug, document_locale): expand = ('expand' in request.GET) max_depth = 5 depth = int(request.GET.get('depth', max_depth)) if (depth > max_depth): depth = max_depth result = [] try: doc = Document.objects.get(locale=document_locale, slug=document_slug) result = _make_doc_structure(doc, 0, expand, depth) if (result is None): result = {'error': 'Document has moved.'} except Document.DoesNotExist: result = {'error': 'Document does not exist.'} return JsonResponse(result)
null
null
null
What has fulfilled all milestones for the given course ?
def _has_fulfilled_all_milestones(user, course_id): return (MilestoneError() if any_unfulfilled_milestones(course_id, user.id) else ACCESS_GRANTED)
null
null
null
the given user
codeqa
def has fulfilled all milestones user course id return Milestone Error if any unfulfilled milestones course id user id else ACCESS GRANTED
null
null
null
null
Question: What has fulfilled all milestones for the given course ? Code: def _has_fulfilled_all_milestones(user, course_id): return (MilestoneError() if any_unfulfilled_milestones(course_id, user.id) else ACCESS_GRANTED)
null
null
null
What has the given user fulfilled ?
def _has_fulfilled_all_milestones(user, course_id): return (MilestoneError() if any_unfulfilled_milestones(course_id, user.id) else ACCESS_GRANTED)
null
null
null
all milestones for the given course
codeqa
def has fulfilled all milestones user course id return Milestone Error if any unfulfilled milestones course id user id else ACCESS GRANTED
null
null
null
null
Question: What has the given user fulfilled ? Code: def _has_fulfilled_all_milestones(user, course_id): return (MilestoneError() if any_unfulfilled_milestones(course_id, user.id) else ACCESS_GRANTED)
null
null
null
How is y correlated with x ?
def check_increasing(x, y): (rho, _) = spearmanr(x, y) increasing_bool = (rho >= 0) if (rho not in [(-1.0), 1.0]): F = (0.5 * math.log(((1.0 + rho) / (1.0 - rho)))) F_se = (1 / math.sqrt((len(x) - 3))) rho_0 = math.tanh((F - (1.96 * F_se))) rho_1 = math.tanh((F + (1.96 * F_se))) if (np.sign(rho_0) != np.sign(rho_1)): warnings.warn('Confidence interval of the Spearman correlation coefficient spans zero. Determination of ``increasing`` may be suspect.') return increasing_bool
null
null
null
monotonically
codeqa
def check increasing x y rho spearmanr x y increasing bool rho > 0 if rho not in [ -1 0 1 0] F 0 5 * math log 1 0 + rho / 1 0 - rho F se 1 / math sqrt len x - 3 rho 0 math tanh F - 1 96 * F se rho 1 math tanh F + 1 96 * F se if np sign rho 0 np sign rho 1 warnings warn ' Confidenceintervalofthe Spearmancorrelationcoefficientspanszero Determinationof``increasing``maybesuspect ' return increasing bool
null
null
null
null
Question: How is y correlated with x ? Code: def check_increasing(x, y): (rho, _) = spearmanr(x, y) increasing_bool = (rho >= 0) if (rho not in [(-1.0), 1.0]): F = (0.5 * math.log(((1.0 + rho) / (1.0 - rho)))) F_se = (1 / math.sqrt((len(x) - 3))) rho_0 = math.tanh((F - (1.96 * F_se))) rho_1 = math.tanh((F + (1.96 * F_se))) if (np.sign(rho_0) != np.sign(rho_1)): warnings.warn('Confidence interval of the Spearman correlation coefficient spans zero. Determination of ``increasing`` may be suspect.') return increasing_bool
null
null
null
What has an attribute with the given name ?
def hasattr(attr): def has_attr(value): return _hasattr(value, attr) return has_attr
null
null
null
the object
codeqa
def hasattr attr def has attr value return hasattr value attr return has attr
null
null
null
null
Question: What has an attribute with the given name ? Code: def hasattr(attr): def has_attr(value): return _hasattr(value, attr) return has_attr
null
null
null
What does the object have ?
def hasattr(attr): def has_attr(value): return _hasattr(value, attr) return has_attr
null
null
null
an attribute with the given name
codeqa
def hasattr attr def has attr value return hasattr value attr return has attr
null
null
null
null
Question: What does the object have ? Code: def hasattr(attr): def has_attr(value): return _hasattr(value, attr) return has_attr
null
null
null
How did the code read from a binary file ?
def read_str(fid, count=1): dtype = np.dtype(('>S%i' % count)) string = fid.read(dtype.itemsize) data = np.fromstring(string, dtype=dtype)[0] bytestr = b('').join([data[0:(data.index(b('\x00')) if (b('\x00') in data) else count)]]) return str(bytestr.decode('ascii'))
null
null
null
in a python version compatible way
codeqa
def read str fid count 1 dtype np dtype '>S%i' % count string fid read dtype itemsize data np fromstring string dtype dtype [0 ]bytestr b '' join [data[ 0 data index b '\x 00 ' if b '\x 00 ' in data else count ]] return str bytestr decode 'ascii'
null
null
null
null
Question: How did the code read from a binary file ? Code: def read_str(fid, count=1): dtype = np.dtype(('>S%i' % count)) string = fid.read(dtype.itemsize) data = np.fromstring(string, dtype=dtype)[0] bytestr = b('').join([data[0:(data.index(b('\x00')) if (b('\x00') in data) else count)]]) return str(bytestr.decode('ascii'))
null
null
null
What does the code assign to aliases ?
def test_dict_aliasing(): ad = _AliasDict({'bar': False, 'biz': True, 'baz': False}, aliases={'foo': ['bar', 'biz', 'baz']}) eq_(ad['bar'], False) eq_(ad['biz'], True) eq_(ad['baz'], False) ad['foo'] = True eq_(ad['bar'], True) eq_(ad['biz'], True) eq_(ad['baz'], True)
null
null
null
values
codeqa
def test dict aliasing ad Alias Dict {'bar' False 'biz' True 'baz' False} aliases {'foo' ['bar' 'biz' 'baz']} eq ad['bar'] False eq ad['biz'] True eq ad['baz'] False ad['foo'] Trueeq ad['bar'] True eq ad['biz'] True eq ad['baz'] True
null
null
null
null
Question: What does the code assign to aliases ? Code: def test_dict_aliasing(): ad = _AliasDict({'bar': False, 'biz': True, 'baz': False}, aliases={'foo': ['bar', 'biz', 'baz']}) eq_(ad['bar'], False) eq_(ad['biz'], True) eq_(ad['baz'], False) ad['foo'] = True eq_(ad['bar'], True) eq_(ad['biz'], True) eq_(ad['baz'], True)
null
null
null
What passes ftp_list_line to the objects ?
def parse_ftp_list_line(ftp_list_line): return FTPListDataParser().parse_line(ftp_list_line)
null
null
null
convenience function
codeqa
def parse ftp list line ftp list line return FTP List Data Parser parse line ftp list line
null
null
null
null
Question: What passes ftp_list_line to the objects ? Code: def parse_ftp_list_line(ftp_list_line): return FTPListDataParser().parse_line(ftp_list_line)
null
null
null
What does convenience function pass to the objects ?
def parse_ftp_list_line(ftp_list_line): return FTPListDataParser().parse_line(ftp_list_line)
null
null
null
ftp_list_line
codeqa
def parse ftp list line ftp list line return FTP List Data Parser parse line ftp list line
null
null
null
null
Question: What does convenience function pass to the objects ? Code: def parse_ftp_list_line(ftp_list_line): return FTPListDataParser().parse_line(ftp_list_line)
null
null
null
How do a passive mode message construct ?
def passivemode_msg(protocol, host='127.0.0.1', port=12345): msg = ('227 Entering Passive Mode (%s).' % (ftp.encodeHostPort(host, port),)) return msg.encode(protocol._encoding)
null
null
null
with the correct encoding
codeqa
def passivemode msg protocol host '127 0 0 1' port 12345 msg '227 Entering Passive Mode %s ' % ftp encode Host Port host port return msg encode protocol encoding
null
null
null
null
Question: How do a passive mode message construct ? Code: def passivemode_msg(protocol, host='127.0.0.1', port=12345): msg = ('227 Entering Passive Mode (%s).' % (ftp.encodeHostPort(host, port),)) return msg.encode(protocol._encoding)
null
null
null
What facilitates preprocessing per method ?
def preprocess(func, c, expose_request=False): if (not python.callable(func)): raise TypeError('func must be callable') if (not python.callable(c)): raise TypeError('Preprocessor must be callable') attr = func if isinstance(func, types.UnboundMethodType): attr = func.im_func if (expose_request is True): c = globals()['expose_request'](c) setattr(attr, '_pyamf_preprocessor', c) return func
null
null
null
a decorator
codeqa
def preprocess func c expose request False if not python callable func raise Type Error 'funcmustbecallable' if not python callable c raise Type Error ' Preprocessormustbecallable' attr funcif isinstance func types Unbound Method Type attr func im funcif expose request is True c globals ['expose request'] c setattr attr ' pyamf preprocessor' c return func
null
null
null
null
Question: What facilitates preprocessing per method ? Code: def preprocess(func, c, expose_request=False): if (not python.callable(func)): raise TypeError('func must be callable') if (not python.callable(c)): raise TypeError('Preprocessor must be callable') attr = func if isinstance(func, types.UnboundMethodType): attr = func.im_func if (expose_request is True): c = globals()['expose_request'](c) setattr(attr, '_pyamf_preprocessor', c) return func
null
null
null
What does a decorator facilitate ?
def preprocess(func, c, expose_request=False): if (not python.callable(func)): raise TypeError('func must be callable') if (not python.callable(c)): raise TypeError('Preprocessor must be callable') attr = func if isinstance(func, types.UnboundMethodType): attr = func.im_func if (expose_request is True): c = globals()['expose_request'](c) setattr(attr, '_pyamf_preprocessor', c) return func
null
null
null
preprocessing per method
codeqa
def preprocess func c expose request False if not python callable func raise Type Error 'funcmustbecallable' if not python callable c raise Type Error ' Preprocessormustbecallable' attr funcif isinstance func types Unbound Method Type attr func im funcif expose request is True c globals ['expose request'] c setattr attr ' pyamf preprocessor' c return func
null
null
null
null
Question: What does a decorator facilitate ? Code: def preprocess(func, c, expose_request=False): if (not python.callable(func)): raise TypeError('func must be callable') if (not python.callable(c)): raise TypeError('Preprocessor must be callable') attr = func if isinstance(func, types.UnboundMethodType): attr = func.im_func if (expose_request is True): c = globals()['expose_request'](c) setattr(attr, '_pyamf_preprocessor', c) return func
null
null
null
What does the code decorate ?
def memoized_instancemethod(fn): def oneshot(self, *args, **kw): result = fn(self, *args, **kw) memo = (lambda *a, **kw: result) memo.__name__ = fn.__name__ memo.__doc__ = fn.__doc__ self.__dict__[fn.__name__] = memo return result return update_wrapper(oneshot, fn)
null
null
null
a method
codeqa
def memoized instancemethod fn def oneshot self *args **kw result fn self *args **kw memo lambda *a **kw result memo name fn name memo doc fn doc self dict [fn name ] memoreturn resultreturn update wrapper oneshot fn
null
null
null
null
Question: What does the code decorate ? Code: def memoized_instancemethod(fn): def oneshot(self, *args, **kw): result = fn(self, *args, **kw) memo = (lambda *a, **kw: result) memo.__name__ = fn.__name__ memo.__doc__ = fn.__doc__ self.__dict__[fn.__name__] = memo return result return update_wrapper(oneshot, fn)
null
null
null
What has all rights ?
def get_change_advanced_settings_id_list(user, site, check_global=True, use_cache=True): page_ids = _get_page_ids_for_action(user=user, site=site, action='change_page_advanced_settings', check_global=check_global, use_cache=use_cache) return page_ids
null
null
null
the user
codeqa
def get change advanced settings id list user site check global True use cache True page ids get page ids for action user user site site action 'change page advanced settings' check global check global use cache use cache return page ids
null
null
null
null
Question: What has all rights ? Code: def get_change_advanced_settings_id_list(user, site, check_global=True, use_cache=True): page_ids = _get_page_ids_for_action(user=user, site=site, action='change_page_advanced_settings', check_global=check_global, use_cache=use_cache) return page_ids
null
null
null
What does the code return ?
def get_image_dimensions(file_or_path, close=False): try: from PIL import ImageFile as PILImageFile except ImportError: import ImageFile as PILImageFile p = PILImageFile.Parser() if hasattr(file_or_path, 'read'): file = file_or_path file_pos = file.tell() file.seek(0) else: file = open(file_or_path, 'rb') close = True try: while 1: data = file.read(1024) if (not data): break p.feed(data) if p.image: return p.image.size return None finally: if close: file.close() else: file.seek(file_pos)
null
null
null
the of an image
codeqa
def get image dimensions file or path close False try from PIL import Image File as PIL Image Fileexcept Import Error import Image File as PIL Image Filep PIL Image File Parser if hasattr file or path 'read' file file or pathfile pos file tell file seek 0 else file open file or path 'rb' close Truetry while 1 data file read 1024 if not data breakp feed data if p image return p image sizereturn Nonefinally if close file close else file seek file pos
null
null
null
null
Question: What does the code return ? Code: def get_image_dimensions(file_or_path, close=False): try: from PIL import ImageFile as PILImageFile except ImportError: import ImageFile as PILImageFile p = PILImageFile.Parser() if hasattr(file_or_path, 'read'): file = file_or_path file_pos = file.tell() file.seek(0) else: file = open(file_or_path, 'rb') close = True try: while 1: data = file.read(1024) if (not data): break p.feed(data) if p.image: return p.image.size return None finally: if close: file.close() else: file.seek(file_pos)
null
null
null
What do an argument parser use ?
def construct_parser(magic_func): kwds = getattr(magic_func, 'argcmd_kwds', {}) if ('description' not in kwds): kwds['description'] = getattr(magic_func, '__doc__', None) arg_name = real_name(magic_func) parser = MagicArgumentParser(arg_name, **kwds) group = None for deco in magic_func.decorators[::(-1)]: result = deco.add_to_parser(parser, group) if (result is not None): group = result magic_func.__doc__ = parser.format_help() return parser
null
null
null
the function decorations
codeqa
def construct parser magic func kwds getattr magic func 'argcmd kwds' {} if 'description' not in kwds kwds['description'] getattr magic func ' doc ' None arg name real name magic func parser Magic Argument Parser arg name **kwds group Nonefor deco in magic func decorators[ -1 ] result deco add to parser parser group if result is not None group resultmagic func doc parser format help return parser
null
null
null
null
Question: What do an argument parser use ? Code: def construct_parser(magic_func): kwds = getattr(magic_func, 'argcmd_kwds', {}) if ('description' not in kwds): kwds['description'] = getattr(magic_func, '__doc__', None) arg_name = real_name(magic_func) parser = MagicArgumentParser(arg_name, **kwds) group = None for deco in magic_func.decorators[::(-1)]: result = deco.add_to_parser(parser, group) if (result is not None): group = result magic_func.__doc__ = parser.format_help() return parser
null
null
null
What is using the function decorations ?
def construct_parser(magic_func): kwds = getattr(magic_func, 'argcmd_kwds', {}) if ('description' not in kwds): kwds['description'] = getattr(magic_func, '__doc__', None) arg_name = real_name(magic_func) parser = MagicArgumentParser(arg_name, **kwds) group = None for deco in magic_func.decorators[::(-1)]: result = deco.add_to_parser(parser, group) if (result is not None): group = result magic_func.__doc__ = parser.format_help() return parser
null
null
null
an argument parser
codeqa
def construct parser magic func kwds getattr magic func 'argcmd kwds' {} if 'description' not in kwds kwds['description'] getattr magic func ' doc ' None arg name real name magic func parser Magic Argument Parser arg name **kwds group Nonefor deco in magic func decorators[ -1 ] result deco add to parser parser group if result is not None group resultmagic func doc parser format help return parser
null
null
null
null
Question: What is using the function decorations ? Code: def construct_parser(magic_func): kwds = getattr(magic_func, 'argcmd_kwds', {}) if ('description' not in kwds): kwds['description'] = getattr(magic_func, '__doc__', None) arg_name = real_name(magic_func) parser = MagicArgumentParser(arg_name, **kwds) group = None for deco in magic_func.decorators[::(-1)]: result = deco.add_to_parser(parser, group) if (result is not None): group = result magic_func.__doc__ = parser.format_help() return parser
null
null
null
What does this primitive represent ?
def s_group(name, values): group = primitives.group(name, values) blocks.CURRENT.push(group)
null
null
null
a list of static values
codeqa
def s group name values group primitives group name values blocks CURRENT push group
null
null
null
null
Question: What does this primitive represent ? Code: def s_group(name, values): group = primitives.group(name, values) blocks.CURRENT.push(group)
null
null
null
What represents a list of static values ?
def s_group(name, values): group = primitives.group(name, values) blocks.CURRENT.push(group)
null
null
null
this primitive
codeqa
def s group name values group primitives group name values blocks CURRENT push group
null
null
null
null
Question: What represents a list of static values ? Code: def s_group(name, values): group = primitives.group(name, values) blocks.CURRENT.push(group)
null
null
null
How do image color convert ?
def convert_color(in_image, mode): return in_image.convert(mode)
null
null
null
with provided mode
codeqa
def convert color in image mode return in image convert mode
null
null
null
null
Question: How do image color convert ? Code: def convert_color(in_image, mode): return in_image.convert(mode)
null
null
null
What does the code create on file f ?
def mmap_readwrite(f, sz=0, close=True): return _mmap_do(f, sz, mmap.MAP_SHARED, (mmap.PROT_READ | mmap.PROT_WRITE), close)
null
null
null
a read - write memory mapped region
codeqa
def mmap readwrite f sz 0 close True return mmap do f sz mmap MAP SHARED mmap PROT READ mmap PROT WRITE close
null
null
null
null
Question: What does the code create on file f ? Code: def mmap_readwrite(f, sz=0, close=True): return _mmap_do(f, sz, mmap.MAP_SHARED, (mmap.PROT_READ | mmap.PROT_WRITE), close)
null
null
null
Where does the code create a read - write memory mapped region ?
def mmap_readwrite(f, sz=0, close=True): return _mmap_do(f, sz, mmap.MAP_SHARED, (mmap.PROT_READ | mmap.PROT_WRITE), close)
null
null
null
on file f
codeqa
def mmap readwrite f sz 0 close True return mmap do f sz mmap MAP SHARED mmap PROT READ mmap PROT WRITE close
null
null
null
null
Question: Where does the code create a read - write memory mapped region ? Code: def mmap_readwrite(f, sz=0, close=True): return _mmap_do(f, sz, mmap.MAP_SHARED, (mmap.PROT_READ | mmap.PROT_WRITE), close)
null
null
null
In which direction did the context dictionary pass ?
def send_mail_template(subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=None, addr_bcc=None, headers=None): if (context is None): context = {} if (attachments is None): attachments = [] if (fail_silently is None): fail_silently = settings.EMAIL_FAIL_SILENTLY context.update(context_settings()) if (isinstance(addr_to, str) or isinstance(addr_to, bytes)): addr_to = [addr_to] if ((addr_bcc is not None) and (isinstance(addr_bcc, str) or isinstance(addr_bcc, bytes))): addr_bcc = [addr_bcc] render = (lambda type: loader.get_template((u'%s.%s' % (template, type))).render(Context(context))) msg = EmailMultiAlternatives(subject, render(u'txt'), addr_from, addr_to, addr_bcc, headers=headers) msg.attach_alternative(render(u'html'), u'text/html') for attachment in attachments: msg.attach(*attachment) msg.send(fail_silently=fail_silently)
null
null
null
in
codeqa
def send mail template subject template addr from addr to context None attachments None fail silently None addr bcc None headers None if context is None context {}if attachments is None attachments []if fail silently is None fail silently settings EMAIL FAIL SILENTL Ycontext update context settings if isinstance addr to str or isinstance addr to bytes addr to [addr to]if addr bcc is not None and isinstance addr bcc str or isinstance addr bcc bytes addr bcc [addr bcc]render lambda type loader get template u'%s %s' % template type render Context context msg Email Multi Alternatives subject render u'txt' addr from addr to addr bcc headers headers msg attach alternative render u'html' u'text/html' for attachment in attachments msg attach *attachment msg send fail silently fail silently
null
null
null
null
Question: In which direction did the context dictionary pass ? Code: def send_mail_template(subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=None, addr_bcc=None, headers=None): if (context is None): context = {} if (attachments is None): attachments = [] if (fail_silently is None): fail_silently = settings.EMAIL_FAIL_SILENTLY context.update(context_settings()) if (isinstance(addr_to, str) or isinstance(addr_to, bytes)): addr_to = [addr_to] if ((addr_bcc is not None) and (isinstance(addr_bcc, str) or isinstance(addr_bcc, bytes))): addr_bcc = [addr_bcc] render = (lambda type: loader.get_template((u'%s.%s' % (template, type))).render(Context(context))) msg = EmailMultiAlternatives(subject, render(u'txt'), addr_from, addr_to, addr_bcc, headers=headers) msg.attach_alternative(render(u'html'), u'text/html') for attachment in attachments: msg.attach(*attachment) msg.send(fail_silently=fail_silently)
null
null
null
When is a particular task running ?
def _task_is_running(course_id, task_type, task_key): running_tasks = InstructorTask.objects.filter(course_id=course_id, task_type=task_type, task_key=task_key) for state in READY_STATES: running_tasks = running_tasks.exclude(task_state=state) return (len(running_tasks) > 0)
null
null
null
already
codeqa
def task is running course id task type task key running tasks Instructor Task objects filter course id course id task type task type task key task key for state in READY STATES running tasks running tasks exclude task state state return len running tasks > 0
null
null
null
null
Question: When is a particular task running ? Code: def _task_is_running(course_id, task_type, task_key): running_tasks = InstructorTask.objects.filter(course_id=course_id, task_type=task_type, task_key=task_key) for state in READY_STATES: running_tasks = running_tasks.exclude(task_state=state) return (len(running_tasks) > 0)
null
null
null
How should output prefix ?
@mock_streams('stdout') def test_puts_with_prefix(): s = 'my output' h = 'localhost' with settings(host_string=h): puts(s) eq_(sys.stdout.getvalue(), ('[%s] %s' % (h, (s + '\n'))))
null
null
null
with env
codeqa
@mock streams 'stdout' def test puts with prefix s 'myoutput'h 'localhost'with settings host string h puts s eq sys stdout getvalue '[%s]%s' % h s + '\n'
null
null
null
null
Question: How should output prefix ? Code: @mock_streams('stdout') def test_puts_with_prefix(): s = 'my output' h = 'localhost' with settings(host_string=h): puts(s) eq_(sys.stdout.getvalue(), ('[%s] %s' % (h, (s + '\n'))))
null
null
null
What did the code set ?
def windowsize(folder, size=None): fsr = Carbon.File.FSRef(folder) folder_alias = fsr.FSNewAliasMinimal() openwindow(fsr) if (not size): return _getwindowsize(folder_alias) return _setwindowsize(folder_alias, size)
null
null
null
the size of a finder window for folder to size=
codeqa
def windowsize folder size None fsr Carbon File FS Ref folder folder alias fsr FS New Alias Minimal openwindow fsr if not size return getwindowsize folder alias return setwindowsize folder alias size
null
null
null
null
Question: What did the code set ? Code: def windowsize(folder, size=None): fsr = Carbon.File.FSRef(folder) folder_alias = fsr.FSNewAliasMinimal() openwindow(fsr) if (not size): return _getwindowsize(folder_alias) return _setwindowsize(folder_alias, size)
null
null
null
How does the code select the vertex indices of a source space ?
def _stc_src_sel(src, stc): if isinstance(stc, VolSourceEstimate): vertices = [stc.vertices] else: vertices = stc.vertices if (not (len(src) == len(vertices))): raise RuntimeError(('Mismatch between number of source spaces (%s) and STC vertices (%s)' % (len(src), len(vertices)))) src_sels = [] offset = 0 for (s, v) in zip(src, vertices): src_sel = np.intersect1d(s['vertno'], v) src_sel = np.searchsorted(s['vertno'], src_sel) src_sels.append((src_sel + offset)) offset += len(s['vertno']) src_sel = np.concatenate(src_sels) return src_sel
null
null
null
using a source estimate
codeqa
def stc src sel src stc if isinstance stc Vol Source Estimate vertices [stc vertices]else vertices stc verticesif not len src len vertices raise Runtime Error ' Mismatchbetweennumberofsourcespaces %s and ST Cvertices %s ' % len src len vertices src sels []offset 0for s v in zip src vertices src sel np intersect 1 d s['vertno'] v src sel np searchsorted s['vertno'] src sel src sels append src sel + offset offset + len s['vertno'] src sel np concatenate src sels return src sel
null
null
null
null
Question: How does the code select the vertex indices of a source space ? Code: def _stc_src_sel(src, stc): if isinstance(stc, VolSourceEstimate): vertices = [stc.vertices] else: vertices = stc.vertices if (not (len(src) == len(vertices))): raise RuntimeError(('Mismatch between number of source spaces (%s) and STC vertices (%s)' % (len(src), len(vertices)))) src_sels = [] offset = 0 for (s, v) in zip(src, vertices): src_sel = np.intersect1d(s['vertno'], v) src_sel = np.searchsorted(s['vertno'], src_sel) src_sels.append((src_sel + offset)) offset += len(s['vertno']) src_sel = np.concatenate(src_sels) return src_sel
null
null
null
What does the code select using a source estimate ?
def _stc_src_sel(src, stc): if isinstance(stc, VolSourceEstimate): vertices = [stc.vertices] else: vertices = stc.vertices if (not (len(src) == len(vertices))): raise RuntimeError(('Mismatch between number of source spaces (%s) and STC vertices (%s)' % (len(src), len(vertices)))) src_sels = [] offset = 0 for (s, v) in zip(src, vertices): src_sel = np.intersect1d(s['vertno'], v) src_sel = np.searchsorted(s['vertno'], src_sel) src_sels.append((src_sel + offset)) offset += len(s['vertno']) src_sel = np.concatenate(src_sels) return src_sel
null
null
null
the vertex indices of a source space
codeqa
def stc src sel src stc if isinstance stc Vol Source Estimate vertices [stc vertices]else vertices stc verticesif not len src len vertices raise Runtime Error ' Mismatchbetweennumberofsourcespaces %s and ST Cvertices %s ' % len src len vertices src sels []offset 0for s v in zip src vertices src sel np intersect 1 d s['vertno'] v src sel np searchsorted s['vertno'] src sel src sels append src sel + offset offset + len s['vertno'] src sel np concatenate src sels return src sel
null
null
null
null
Question: What does the code select using a source estimate ? Code: def _stc_src_sel(src, stc): if isinstance(stc, VolSourceEstimate): vertices = [stc.vertices] else: vertices = stc.vertices if (not (len(src) == len(vertices))): raise RuntimeError(('Mismatch between number of source spaces (%s) and STC vertices (%s)' % (len(src), len(vertices)))) src_sels = [] offset = 0 for (s, v) in zip(src, vertices): src_sel = np.intersect1d(s['vertno'], v) src_sel = np.searchsorted(s['vertno'], src_sel) src_sels.append((src_sel + offset)) offset += len(s['vertno']) src_sel = np.concatenate(src_sels) return src_sel
null
null
null
How do a path remove ?
def _removeSafely(path): if (not path.child('_trial_marker').exists()): raise _NoTrialMarker(('%r is not a trial temporary path, refusing to remove it' % (path,))) try: path.remove() except OSError as e: print(('could not remove %r, caught OSError [Errno %s]: %s' % (path, e.errno, e.strerror))) try: newPath = FilePath(('_trial_temp_old' + str(randrange(10000000)).encode('utf-8'))) path.moveTo(newPath) except OSError as e: print(('could not rename path, caught OSError [Errno %s]: %s' % (e.errno, e.strerror))) raise
null
null
null
safely
codeqa
def remove Safely path if not path child ' trial marker' exists raise No Trial Marker '%risnotatrialtemporarypath refusingtoremoveit' % path try path remove except OS Error as e print 'couldnotremove%r caught OS Error[ Errno%s] %s' % path e errno e strerror try new Path File Path ' trial temp old' + str randrange 10000000 encode 'utf- 8 ' path move To new Path except OS Error as e print 'couldnotrenamepath caught OS Error[ Errno%s] %s' % e errno e strerror raise
null
null
null
null
Question: How do a path remove ? Code: def _removeSafely(path): if (not path.child('_trial_marker').exists()): raise _NoTrialMarker(('%r is not a trial temporary path, refusing to remove it' % (path,))) try: path.remove() except OSError as e: print(('could not remove %r, caught OSError [Errno %s]: %s' % (path, e.errno, e.strerror))) try: newPath = FilePath(('_trial_temp_old' + str(randrange(10000000)).encode('utf-8'))) path.moveTo(newPath) except OSError as e: print(('could not rename path, caught OSError [Errno %s]: %s' % (e.errno, e.strerror))) raise
null
null
null
How did the template send ?
@ensure_csrf_cookie @cache_if_anonymous() def render(request, template): (content_type, __) = mimetypes.guess_type(template) try: return render_to_response(('static_templates/' + template), {}, content_type=content_type) except TopLevelLookupException: raise Http404
null
null
null
without checking that it exists
codeqa
@ensure csrf cookie@cache if anonymous def render request template content type mimetypes guess type template try return render to response 'static templates/' + template {} content type content type except Top Level Lookup Exception raise Http 404
null
null
null
null
Question: How did the template send ? Code: @ensure_csrf_cookie @cache_if_anonymous() def render(request, template): (content_type, __) = mimetypes.guess_type(template) try: return render_to_response(('static_templates/' + template), {}, content_type=content_type) except TopLevelLookupException: raise Http404
null
null
null
What does this view function render ?
@ensure_csrf_cookie @cache_if_anonymous() def render(request, template): (content_type, __) = mimetypes.guess_type(template) try: return render_to_response(('static_templates/' + template), {}, content_type=content_type) except TopLevelLookupException: raise Http404
null
null
null
the template sent without checking that it exists
codeqa
@ensure csrf cookie@cache if anonymous def render request template content type mimetypes guess type template try return render to response 'static templates/' + template {} content type content type except Top Level Lookup Exception raise Http 404
null
null
null
null
Question: What does this view function render ? Code: @ensure_csrf_cookie @cache_if_anonymous() def render(request, template): (content_type, __) = mimetypes.guess_type(template) try: return render_to_response(('static_templates/' + template), {}, content_type=content_type) except TopLevelLookupException: raise Http404
null
null
null
What renders the template sent without checking that it exists ?
@ensure_csrf_cookie @cache_if_anonymous() def render(request, template): (content_type, __) = mimetypes.guess_type(template) try: return render_to_response(('static_templates/' + template), {}, content_type=content_type) except TopLevelLookupException: raise Http404
null
null
null
this view function
codeqa
@ensure csrf cookie@cache if anonymous def render request template content type mimetypes guess type template try return render to response 'static templates/' + template {} content type content type except Top Level Lookup Exception raise Http 404
null
null
null
null
Question: What renders the template sent without checking that it exists ? Code: @ensure_csrf_cookie @cache_if_anonymous() def render(request, template): (content_type, __) = mimetypes.guess_type(template) try: return render_to_response(('static_templates/' + template), {}, content_type=content_type) except TopLevelLookupException: raise Http404
null
null
null
How should names be stripped of whitespace ?
@pytest.mark.parametrize('fast_writer', [True, False]) def test_strip_names(fast_writer): data = table.Table([[1], [2], [3]], names=(' A', 'B ', ' C ')) out = StringIO() ascii.write(data, out, format='csv', fast_writer=fast_writer) assert (out.getvalue().splitlines()[0] == 'A,B,C')
null
null
null
by default
codeqa
@pytest mark parametrize 'fast writer' [ True False] def test strip names fast writer data table Table [[ 1 ] [2 ] [3 ]] names 'A' 'B' 'C' out String IO ascii write data out format 'csv' fast writer fast writer assert out getvalue splitlines [0 ] 'A B C'
null
null
null
null
Question: How should names be stripped of whitespace ? Code: @pytest.mark.parametrize('fast_writer', [True, False]) def test_strip_names(fast_writer): data = table.Table([[1], [2], [3]], names=(' A', 'B ', ' C ')) out = StringIO() ascii.write(data, out, format='csv', fast_writer=fast_writer) assert (out.getvalue().splitlines()[0] == 'A,B,C')
null
null
null
What does the code try with shell ssh command ?
def _try_passwordless_openssh(server, keyfile): if (pexpect is None): raise ImportError('pexpect unavailable, use paramiko') cmd = ('ssh -f ' + server) if keyfile: cmd += (' -i ' + keyfile) cmd += ' exit' env = os.environ.copy() env.pop('SSH_ASKPASS', None) ssh_newkey = 'Are you sure you want to continue connecting' p = pexpect.spawn(cmd, env=env) while True: try: i = p.expect([ssh_newkey, _password_pat], timeout=0.1) if (i == 0): raise SSHException("The authenticity of the host can't be established.") except pexpect.TIMEOUT: continue except pexpect.EOF: return True else: return False
null
null
null
passwordless login
codeqa
def try passwordless openssh server keyfile if pexpect is None raise Import Error 'pexpectunavailable useparamiko' cmd 'ssh-f' + server if keyfile cmd + '-i' + keyfile cmd + 'exit'env os environ copy env pop 'SSH ASKPASS' None ssh newkey ' Areyousureyouwanttocontinueconnecting'p pexpect spawn cmd env env while True try i p expect [ssh newkey password pat] timeout 0 1 if i 0 raise SSH Exception " Theauthenticityofthehostcan'tbeestablished " except pexpect TIMEOUT continueexcept pexpect EOF return Trueelse return False
null
null
null
null
Question: What does the code try with shell ssh command ? Code: def _try_passwordless_openssh(server, keyfile): if (pexpect is None): raise ImportError('pexpect unavailable, use paramiko') cmd = ('ssh -f ' + server) if keyfile: cmd += (' -i ' + keyfile) cmd += ' exit' env = os.environ.copy() env.pop('SSH_ASKPASS', None) ssh_newkey = 'Are you sure you want to continue connecting' p = pexpect.spawn(cmd, env=env) while True: try: i = p.expect([ssh_newkey, _password_pat], timeout=0.1) if (i == 0): raise SSHException("The authenticity of the host can't be established.") except pexpect.TIMEOUT: continue except pexpect.EOF: return True else: return False
null
null
null
How does the code try passwordless login ?
def _try_passwordless_openssh(server, keyfile): if (pexpect is None): raise ImportError('pexpect unavailable, use paramiko') cmd = ('ssh -f ' + server) if keyfile: cmd += (' -i ' + keyfile) cmd += ' exit' env = os.environ.copy() env.pop('SSH_ASKPASS', None) ssh_newkey = 'Are you sure you want to continue connecting' p = pexpect.spawn(cmd, env=env) while True: try: i = p.expect([ssh_newkey, _password_pat], timeout=0.1) if (i == 0): raise SSHException("The authenticity of the host can't be established.") except pexpect.TIMEOUT: continue except pexpect.EOF: return True else: return False
null
null
null
with shell ssh command
codeqa
def try passwordless openssh server keyfile if pexpect is None raise Import Error 'pexpectunavailable useparamiko' cmd 'ssh-f' + server if keyfile cmd + '-i' + keyfile cmd + 'exit'env os environ copy env pop 'SSH ASKPASS' None ssh newkey ' Areyousureyouwanttocontinueconnecting'p pexpect spawn cmd env env while True try i p expect [ssh newkey password pat] timeout 0 1 if i 0 raise SSH Exception " Theauthenticityofthehostcan'tbeestablished " except pexpect TIMEOUT continueexcept pexpect EOF return Trueelse return False
null
null
null
null
Question: How does the code try passwordless login ? Code: def _try_passwordless_openssh(server, keyfile): if (pexpect is None): raise ImportError('pexpect unavailable, use paramiko') cmd = ('ssh -f ' + server) if keyfile: cmd += (' -i ' + keyfile) cmd += ' exit' env = os.environ.copy() env.pop('SSH_ASKPASS', None) ssh_newkey = 'Are you sure you want to continue connecting' p = pexpect.spawn(cmd, env=env) while True: try: i = p.expect([ssh_newkey, _password_pat], timeout=0.1) if (i == 0): raise SSHException("The authenticity of the host can't be established.") except pexpect.TIMEOUT: continue except pexpect.EOF: return True else: return False
null
null
null
What does the code create over at the remote repository ?
def create_directory(repo): remote_path = repo if repo.startswith('ssh://'): (_, remote_path) = parse_ssh_path(repo) repo_run_command(repo, ('mkdir -p %s' % remote_path), cd=False)
null
null
null
a directory
codeqa
def create directory repo remote path repoif repo startswith 'ssh //' remote path parse ssh path repo repo run command repo 'mkdir-p%s' % remote path cd False
null
null
null
null
Question: What does the code create over at the remote repository ? Code: def create_directory(repo): remote_path = repo if repo.startswith('ssh://'): (_, remote_path) = parse_ssh_path(repo) repo_run_command(repo, ('mkdir -p %s' % remote_path), cd=False)
null
null
null
Where does the code create a directory ?
def create_directory(repo): remote_path = repo if repo.startswith('ssh://'): (_, remote_path) = parse_ssh_path(repo) repo_run_command(repo, ('mkdir -p %s' % remote_path), cd=False)
null
null
null
over at the remote repository
codeqa
def create directory repo remote path repoif repo startswith 'ssh //' remote path parse ssh path repo repo run command repo 'mkdir-p%s' % remote path cd False
null
null
null
null
Question: Where does the code create a directory ? Code: def create_directory(repo): remote_path = repo if repo.startswith('ssh://'): (_, remote_path) = parse_ssh_path(repo) repo_run_command(repo, ('mkdir -p %s' % remote_path), cd=False)
null
null
null
How do the reporter classes register ?
def register(linter): linter.register_reporter(JSONReporter)
null
null
null
with the linter
codeqa
def register linter linter register reporter JSON Reporter
null
null
null
null
Question: How do the reporter classes register ? Code: def register(linter): linter.register_reporter(JSONReporter)
null
null
null
What join confirmation page ?
@login_required def group_join(request, slug, template_name='groups/group_join_confirm.html'): group = get_object_or_404(Group, slug=slug, is_active=True) if (request.method == 'POST'): membership = GroupMember(group=group, user=request.user) membership.save() return redirect(request, group) return render(request, template_name, {'group': group})
null
null
null
a group
codeqa
@login requireddef group join request slug template name 'groups/group join confirm html' group get object or 404 Group slug slug is active True if request method 'POST' membership Group Member group group user request user membership save return redirect request group return render request template name {'group' group}
null
null
null
null
Question: What join confirmation page ? Code: @login_required def group_join(request, slug, template_name='groups/group_join_confirm.html'): group = get_object_or_404(Group, slug=slug, is_active=True) if (request.method == 'POST'): membership = GroupMember(group=group, user=request.user) membership.save() return redirect(request, group) return render(request, template_name, {'group': group})
null
null
null
What does a group join ?
@login_required def group_join(request, slug, template_name='groups/group_join_confirm.html'): group = get_object_or_404(Group, slug=slug, is_active=True) if (request.method == 'POST'): membership = GroupMember(group=group, user=request.user) membership.save() return redirect(request, group) return render(request, template_name, {'group': group})
null
null
null
confirmation page
codeqa
@login requireddef group join request slug template name 'groups/group join confirm html' group get object or 404 Group slug slug is active True if request method 'POST' membership Group Member group group user request user membership save return redirect request group return render request template name {'group' group}
null
null
null
null
Question: What does a group join ? Code: @login_required def group_join(request, slug, template_name='groups/group_join_confirm.html'): group = get_object_or_404(Group, slug=slug, is_active=True) if (request.method == 'POST'): membership = GroupMember(group=group, user=request.user) membership.save() return redirect(request, group) return render(request, template_name, {'group': group})
null
null
null
What does the code generate ?
def generate_config(hass, passwd): from homeassistant.components.mqtt import PROTOCOL_311 config = {'listeners': {'default': {'max-connections': 50000, 'bind': '0.0.0.0:1883', 'type': 'tcp'}, 'ws-1': {'bind': '0.0.0.0:8080', 'type': 'ws'}}, 'auth': {'allow-anonymous': (hass.config.api.api_password is None)}, 'plugins': ['auth_anonymous']} if hass.config.api.api_password: username = 'homeassistant' password = hass.config.api.api_password from passlib.apps import custom_app_context passwd.write('homeassistant:{}\n'.format(custom_app_context.encrypt(hass.config.api.api_password)).encode('utf-8')) passwd.flush() config['auth']['password-file'] = passwd.name config['plugins'].append('auth_file') else: username = None password = None client_config = ('localhost', 1883, username, password, None, PROTOCOL_311) return (config, client_config)
null
null
null
a configuration based on current home assistant instance
codeqa
def generate config hass passwd from homeassistant components mqtt import PROTOCOL 311 config {'listeners' {'default' {'max-connections' 50000 'bind' '0 0 0 0 1883 ' 'type' 'tcp'} 'ws- 1 ' {'bind' '0 0 0 0 8080 ' 'type' 'ws'}} 'auth' {'allow-anonymous' hass config api api password is None } 'plugins' ['auth anonymous']}if hass config api api password username 'homeassistant'password hass config api api passwordfrom passlib apps import custom app contextpasswd write 'homeassistant {}\n' format custom app context encrypt hass config api api password encode 'utf- 8 ' passwd flush config['auth']['password-file'] passwd nameconfig['plugins'] append 'auth file' else username Nonepassword Noneclient config 'localhost' 1883 username password None PROTOCOL 311 return config client config
null
null
null
null
Question: What does the code generate ? Code: def generate_config(hass, passwd): from homeassistant.components.mqtt import PROTOCOL_311 config = {'listeners': {'default': {'max-connections': 50000, 'bind': '0.0.0.0:1883', 'type': 'tcp'}, 'ws-1': {'bind': '0.0.0.0:8080', 'type': 'ws'}}, 'auth': {'allow-anonymous': (hass.config.api.api_password is None)}, 'plugins': ['auth_anonymous']} if hass.config.api.api_password: username = 'homeassistant' password = hass.config.api.api_password from passlib.apps import custom_app_context passwd.write('homeassistant:{}\n'.format(custom_app_context.encrypt(hass.config.api.api_password)).encode('utf-8')) passwd.flush() config['auth']['password-file'] = passwd.name config['plugins'].append('auth_file') else: username = None password = None client_config = ('localhost', 1883, username, password, None, PROTOCOL_311) return (config, client_config)
null
null
null
What copies the source file to a temporary destination ?
@contextmanager def copy_file_to_temp(source): temp_filename = get_temp_filename() with copy_file(source, temp_filename): (yield temp_filename)
null
null
null
context manager
codeqa
@contextmanagerdef copy file to temp source temp filename get temp filename with copy file source temp filename yield temp filename
null
null
null
null
Question: What copies the source file to a temporary destination ? Code: @contextmanager def copy_file_to_temp(source): temp_filename = get_temp_filename() with copy_file(source, temp_filename): (yield temp_filename)
null
null
null
What does context manager copy to a temporary destination ?
@contextmanager def copy_file_to_temp(source): temp_filename = get_temp_filename() with copy_file(source, temp_filename): (yield temp_filename)
null
null
null
the source file
codeqa
@contextmanagerdef copy file to temp source temp filename get temp filename with copy file source temp filename yield temp filename
null
null
null
null
Question: What does context manager copy to a temporary destination ? Code: @contextmanager def copy_file_to_temp(source): temp_filename = get_temp_filename() with copy_file(source, temp_filename): (yield temp_filename)
null
null
null
What does the code add ?
def getRemainingLoopAddFace(faces, remainingLoop): for (indexedVertexIndex, indexedVertex) in enumerate(remainingLoop): nextIndex = ((indexedVertexIndex + 1) % len(remainingLoop)) previousIndex = (((indexedVertexIndex + len(remainingLoop)) - 1) % len(remainingLoop)) nextVertex = remainingLoop[nextIndex] previousVertex = remainingLoop[previousIndex] remainingPath = euclidean.getAroundLoop(((indexedVertexIndex + 2) % len(remainingLoop)), previousIndex, remainingLoop) if ((len(remainingLoop) < 4) or getIsPathEntirelyOutsideTriangle(previousVertex, indexedVertex, nextVertex, remainingPath)): faceConvex = face.Face() faceConvex.index = len(faces) faceConvex.vertexIndexes.append(indexedVertex.index) faceConvex.vertexIndexes.append(nextVertex.index) faceConvex.vertexIndexes.append(previousVertex.index) faces.append(faceConvex) return euclidean.getAroundLoop(nextIndex, indexedVertexIndex, remainingLoop) print 'Warning, could not decompose polygon in getRemainingLoopAddFace in trianglemesh for:' print remainingLoop return []
null
null
null
face
codeqa
def get Remaining Loop Add Face faces remaining Loop for indexed Vertex Index indexed Vertex in enumerate remaining Loop next Index indexed Vertex Index + 1 % len remaining Loop previous Index indexed Vertex Index + len remaining Loop - 1 % len remaining Loop next Vertex remaining Loop[next Index]previous Vertex remaining Loop[previous Index]remaining Path euclidean get Around Loop indexed Vertex Index + 2 % len remaining Loop previous Index remaining Loop if len remaining Loop < 4 or get Is Path Entirely Outside Triangle previous Vertex indexed Vertex next Vertex remaining Path face Convex face Face face Convex index len faces face Convex vertex Indexes append indexed Vertex index face Convex vertex Indexes append next Vertex index face Convex vertex Indexes append previous Vertex index faces append face Convex return euclidean get Around Loop next Index indexed Vertex Index remaining Loop print ' Warning couldnotdecomposepolygoninget Remaining Loop Add Faceintrianglemeshfor 'print remaining Loopreturn []
null
null
null
null
Question: What does the code add ? Code: def getRemainingLoopAddFace(faces, remainingLoop): for (indexedVertexIndex, indexedVertex) in enumerate(remainingLoop): nextIndex = ((indexedVertexIndex + 1) % len(remainingLoop)) previousIndex = (((indexedVertexIndex + len(remainingLoop)) - 1) % len(remainingLoop)) nextVertex = remainingLoop[nextIndex] previousVertex = remainingLoop[previousIndex] remainingPath = euclidean.getAroundLoop(((indexedVertexIndex + 2) % len(remainingLoop)), previousIndex, remainingLoop) if ((len(remainingLoop) < 4) or getIsPathEntirelyOutsideTriangle(previousVertex, indexedVertex, nextVertex, remainingPath)): faceConvex = face.Face() faceConvex.index = len(faces) faceConvex.vertexIndexes.append(indexedVertex.index) faceConvex.vertexIndexes.append(nextVertex.index) faceConvex.vertexIndexes.append(previousVertex.index) faces.append(faceConvex) return euclidean.getAroundLoop(nextIndex, indexedVertexIndex, remainingLoop) print 'Warning, could not decompose polygon in getRemainingLoopAddFace in trianglemesh for:' print remainingLoop return []
null
null
null
What does the code get ?
def getRemainingLoopAddFace(faces, remainingLoop): for (indexedVertexIndex, indexedVertex) in enumerate(remainingLoop): nextIndex = ((indexedVertexIndex + 1) % len(remainingLoop)) previousIndex = (((indexedVertexIndex + len(remainingLoop)) - 1) % len(remainingLoop)) nextVertex = remainingLoop[nextIndex] previousVertex = remainingLoop[previousIndex] remainingPath = euclidean.getAroundLoop(((indexedVertexIndex + 2) % len(remainingLoop)), previousIndex, remainingLoop) if ((len(remainingLoop) < 4) or getIsPathEntirelyOutsideTriangle(previousVertex, indexedVertex, nextVertex, remainingPath)): faceConvex = face.Face() faceConvex.index = len(faces) faceConvex.vertexIndexes.append(indexedVertex.index) faceConvex.vertexIndexes.append(nextVertex.index) faceConvex.vertexIndexes.append(previousVertex.index) faces.append(faceConvex) return euclidean.getAroundLoop(nextIndex, indexedVertexIndex, remainingLoop) print 'Warning, could not decompose polygon in getRemainingLoopAddFace in trianglemesh for:' print remainingLoop return []
null
null
null
the remaining loop
codeqa
def get Remaining Loop Add Face faces remaining Loop for indexed Vertex Index indexed Vertex in enumerate remaining Loop next Index indexed Vertex Index + 1 % len remaining Loop previous Index indexed Vertex Index + len remaining Loop - 1 % len remaining Loop next Vertex remaining Loop[next Index]previous Vertex remaining Loop[previous Index]remaining Path euclidean get Around Loop indexed Vertex Index + 2 % len remaining Loop previous Index remaining Loop if len remaining Loop < 4 or get Is Path Entirely Outside Triangle previous Vertex indexed Vertex next Vertex remaining Path face Convex face Face face Convex index len faces face Convex vertex Indexes append indexed Vertex index face Convex vertex Indexes append next Vertex index face Convex vertex Indexes append previous Vertex index faces append face Convex return euclidean get Around Loop next Index indexed Vertex Index remaining Loop print ' Warning couldnotdecomposepolygoninget Remaining Loop Add Faceintrianglemeshfor 'print remaining Loopreturn []
null
null
null
null
Question: What does the code get ? Code: def getRemainingLoopAddFace(faces, remainingLoop): for (indexedVertexIndex, indexedVertex) in enumerate(remainingLoop): nextIndex = ((indexedVertexIndex + 1) % len(remainingLoop)) previousIndex = (((indexedVertexIndex + len(remainingLoop)) - 1) % len(remainingLoop)) nextVertex = remainingLoop[nextIndex] previousVertex = remainingLoop[previousIndex] remainingPath = euclidean.getAroundLoop(((indexedVertexIndex + 2) % len(remainingLoop)), previousIndex, remainingLoop) if ((len(remainingLoop) < 4) or getIsPathEntirelyOutsideTriangle(previousVertex, indexedVertex, nextVertex, remainingPath)): faceConvex = face.Face() faceConvex.index = len(faces) faceConvex.vertexIndexes.append(indexedVertex.index) faceConvex.vertexIndexes.append(nextVertex.index) faceConvex.vertexIndexes.append(previousVertex.index) faces.append(faceConvex) return euclidean.getAroundLoop(nextIndex, indexedVertexIndex, remainingLoop) print 'Warning, could not decompose polygon in getRemainingLoopAddFace in trianglemesh for:' print remainingLoop return []
null
null
null
When did the information return ?
def get_jid(jid): query = 'SELECT minion_id, full_ret FROM salt.salt_returns WHERE jid = ?;' ret = {} try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid]) if data: for row in data: minion = row.get('minion_id') full_ret = row.get('full_ret') if (minion and full_ret): ret[minion] = json.loads(full_ret) except CommandExecutionError: log.critical('Could not select job specific information.') raise except Exception as e: log.critical('Unexpected error while getting job specific information: {0}'.format(str(e))) raise return ret
null
null
null
when the specified job i d was executed
codeqa
def get jid jid query 'SELEC Tminion id full ret FRO Msalt salt returns WHER Ejid ? 'ret {}try data salt ['cassandra cql cql query with prepare'] query 'get jid' [jid] if data for row in data minion row get 'minion id' full ret row get 'full ret' if minion and full ret ret[minion] json loads full ret except Command Execution Error log critical ' Couldnotselectjobspecificinformation ' raiseexcept Exception as e log critical ' Unexpectederrorwhilegettingjobspecificinformation {0 }' format str e raisereturn ret
null
null
null
null
Question: When did the information return ? Code: def get_jid(jid): query = 'SELECT minion_id, full_ret FROM salt.salt_returns WHERE jid = ?;' ret = {} try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid]) if data: for row in data: minion = row.get('minion_id') full_ret = row.get('full_ret') if (minion and full_ret): ret[minion] = json.loads(full_ret) except CommandExecutionError: log.critical('Could not select job specific information.') raise except Exception as e: log.critical('Unexpected error while getting job specific information: {0}'.format(str(e))) raise return ret
null
null
null
What does the code ensure ?
def test_pickle_indexed_table(protocol): t = simple_table() t.add_index('a') t.add_index(['a', 'b']) ts = pickle.dumps(t) tp = pickle.loads(ts) assert (len(t.indices) == len(tp.indices)) for (index, indexp) in zip(t.indices, tp.indices): assert np.all((index.data.data == indexp.data.data)) assert (index.data.data.colnames == indexp.data.data.colnames)
null
null
null
that any indices that have been added will survive pickling
codeqa
def test pickle indexed table protocol t simple table t add index 'a' t add index ['a' 'b'] ts pickle dumps t tp pickle loads ts assert len t indices len tp indices for index indexp in zip t indices tp indices assert np all index data data indexp data data assert index data data colnames indexp data data colnames
null
null
null
null
Question: What does the code ensure ? Code: def test_pickle_indexed_table(protocol): t = simple_table() t.add_index('a') t.add_index(['a', 'b']) ts = pickle.dumps(t) tp = pickle.loads(ts) assert (len(t.indices) == len(tp.indices)) for (index, indexp) in zip(t.indices, tp.indices): assert np.all((index.data.data == indexp.data.data)) assert (index.data.data.colnames == indexp.data.data.colnames)
null
null
null
What will survive pickling ?
def test_pickle_indexed_table(protocol): t = simple_table() t.add_index('a') t.add_index(['a', 'b']) ts = pickle.dumps(t) tp = pickle.loads(ts) assert (len(t.indices) == len(tp.indices)) for (index, indexp) in zip(t.indices, tp.indices): assert np.all((index.data.data == indexp.data.data)) assert (index.data.data.colnames == indexp.data.data.colnames)
null
null
null
any indices that have been added
codeqa
def test pickle indexed table protocol t simple table t add index 'a' t add index ['a' 'b'] ts pickle dumps t tp pickle loads ts assert len t indices len tp indices for index indexp in zip t indices tp indices assert np all index data data indexp data data assert index data data colnames indexp data data colnames
null
null
null
null
Question: What will survive pickling ? Code: def test_pickle_indexed_table(protocol): t = simple_table() t.add_index('a') t.add_index(['a', 'b']) ts = pickle.dumps(t) tp = pickle.loads(ts) assert (len(t.indices) == len(tp.indices)) for (index, indexp) in zip(t.indices, tp.indices): assert np.all((index.data.data == indexp.data.data)) assert (index.data.data.colnames == indexp.data.data.colnames)
null
null
null
What will any indices that have been added survive ?
def test_pickle_indexed_table(protocol): t = simple_table() t.add_index('a') t.add_index(['a', 'b']) ts = pickle.dumps(t) tp = pickle.loads(ts) assert (len(t.indices) == len(tp.indices)) for (index, indexp) in zip(t.indices, tp.indices): assert np.all((index.data.data == indexp.data.data)) assert (index.data.data.colnames == indexp.data.data.colnames)
null
null
null
pickling
codeqa
def test pickle indexed table protocol t simple table t add index 'a' t add index ['a' 'b'] ts pickle dumps t tp pickle loads ts assert len t indices len tp indices for index indexp in zip t indices tp indices assert np all index data data indexp data data assert index data data colnames indexp data data colnames
null
null
null
null
Question: What will any indices that have been added survive ? Code: def test_pickle_indexed_table(protocol): t = simple_table() t.add_index('a') t.add_index(['a', 'b']) ts = pickle.dumps(t) tp = pickle.loads(ts) assert (len(t.indices) == len(tp.indices)) for (index, indexp) in zip(t.indices, tp.indices): assert np.all((index.data.data == indexp.data.data)) assert (index.data.data.colnames == indexp.data.data.colnames)
null
null
null
What focused activity stream ?
def actor(request, content_type_id, object_id): ctype = get_object_or_404(ContentType, pk=content_type_id) instance = get_object_or_404(ctype.model_class(), pk=object_id) return render_to_response('actstream/actor.html', {'action_list': models.actor_stream(instance), 'actor': instance, 'ctype': ctype}, context_instance=RequestContext(request))
null
null
null
actor
codeqa
def actor request content type id object id ctype get object or 404 Content Type pk content type id instance get object or 404 ctype model class pk object id return render to response 'actstream/actor html' {'action list' models actor stream instance 'actor' instance 'ctype' ctype} context instance Request Context request
null
null
null
null
Question: What focused activity stream ? Code: def actor(request, content_type_id, object_id): ctype = get_object_or_404(ContentType, pk=content_type_id) instance = get_object_or_404(ctype.model_class(), pk=object_id) return render_to_response('actstream/actor.html', {'action_list': models.actor_stream(instance), 'actor': instance, 'ctype': ctype}, context_instance=RequestContext(request))
null
null
null
What did actor focus ?
def actor(request, content_type_id, object_id): ctype = get_object_or_404(ContentType, pk=content_type_id) instance = get_object_or_404(ctype.model_class(), pk=object_id) return render_to_response('actstream/actor.html', {'action_list': models.actor_stream(instance), 'actor': instance, 'ctype': ctype}, context_instance=RequestContext(request))
null
null
null
activity stream
codeqa
def actor request content type id object id ctype get object or 404 Content Type pk content type id instance get object or 404 ctype model class pk object id return render to response 'actstream/actor html' {'action list' models actor stream instance 'actor' instance 'ctype' ctype} context instance Request Context request
null
null
null
null
Question: What did actor focus ? Code: def actor(request, content_type_id, object_id): ctype = get_object_or_404(ContentType, pk=content_type_id) instance = get_object_or_404(ctype.model_class(), pk=object_id) return render_to_response('actstream/actor.html', {'action_list': models.actor_stream(instance), 'actor': instance, 'ctype': ctype}, context_instance=RequestContext(request))
null
null
null
How does a template string expand ?
def expand(template_str, dictionary, **kwargs): t = Template(template_str, **kwargs) return t.expand(dictionary)
null
null
null
with a data dictionary
codeqa
def expand template str dictionary **kwargs t Template template str **kwargs return t expand dictionary
null
null
null
null
Question: How does a template string expand ? Code: def expand(template_str, dictionary, **kwargs): t = Template(template_str, **kwargs) return t.expand(dictionary)
null
null
null
What warns in that case ?
def _check_deprecated_scrapy_ctl(argv, inproject): if (not any((('scrapy-ctl' in x) for x in argv))): return import warnings warnings.warn('`scrapy-ctl.py` command-line tool is deprecated and will be removed in Scrapy 0.11, use `scrapy` instead', ScrapyDeprecationWarning, stacklevel=3) if inproject: projpath = os.path.abspath(os.path.dirname(os.path.dirname(settings.settings_module.__file__))) cfg_path = os.path.join(projpath, 'scrapy.cfg') if (not os.path.exists(cfg_path)): with open(cfg_path, 'w') as f: f.write(('# generated automatically - feel free to edit' + os.linesep)) f.write(('[settings]' + os.linesep)) f.write((('default = %s' % settings.settings_module.__name__) + os.linesep))
null
null
null
scrapy
codeqa
def check deprecated scrapy ctl argv inproject if not any 'scrapy-ctl' in x for x in argv returnimport warningswarnings warn '`scrapy-ctl py`command-linetoolisdeprecatedandwillberemovedin Scrapy 0 11 use`scrapy`instead' Scrapy Deprecation Warning stacklevel 3 if inproject projpath os path abspath os path dirname os path dirname settings settings module file cfg path os path join projpath 'scrapy cfg' if not os path exists cfg path with open cfg path 'w' as f f write '#generatedautomatically-feelfreetoedit' + os linesep f write '[settings]' + os linesep f write 'default %s' % settings settings module name + os linesep
null
null
null
null
Question: What warns in that case ? Code: def _check_deprecated_scrapy_ctl(argv, inproject): if (not any((('scrapy-ctl' in x) for x in argv))): return import warnings warnings.warn('`scrapy-ctl.py` command-line tool is deprecated and will be removed in Scrapy 0.11, use `scrapy` instead', ScrapyDeprecationWarning, stacklevel=3) if inproject: projpath = os.path.abspath(os.path.dirname(os.path.dirname(settings.settings_module.__file__))) cfg_path = os.path.join(projpath, 'scrapy.cfg') if (not os.path.exists(cfg_path)): with open(cfg_path, 'w') as f: f.write(('# generated automatically - feel free to edit' + os.linesep)) f.write(('[settings]' + os.linesep)) f.write((('default = %s' % settings.settings_module.__name__) + os.linesep))
null
null
null
How does a console instance coerce into proper dictionary format ?
def _translate_detail_keys(cons): pool = cons['pool'] info = {'id': cons['id'], 'console_type': pool['console_type'], 'password': cons['password'], 'instance_name': cons['instance_name'], 'port': cons['port'], 'host': pool['public_hostname']} return dict(console=info)
null
null
null
with detail
codeqa
def translate detail keys cons pool cons['pool']info {'id' cons['id'] 'console type' pool['console type'] 'password' cons['password'] 'instance name' cons['instance name'] 'port' cons['port'] 'host' pool['public hostname']}return dict console info
null
null
null
null
Question: How does a console instance coerce into proper dictionary format ? Code: def _translate_detail_keys(cons): pool = cons['pool'] info = {'id': cons['id'], 'console_type': pool['console_type'], 'password': cons['password'], 'instance_name': cons['instance_name'], 'port': cons['port'], 'host': pool['public_hostname']} return dict(console=info)
null
null
null
In which direction do them send to keen ?
def main(): args = parse_args() client = get_keen_client() dry = args.dry reverse = args.reverse if args.remove_event: remove_event_from_keen(client, args.source_collection, args.remove_event) if args.smooth_events: smooth_events_in_keen(client, args.source_collection, parse(args.start_date), parse(args.end_date), dry, reverse) elif args.transfer_collection: transfer_events_to_another_collection(client, args.source_collection, args.destination_collection, dry, reverse) elif args.old_analytics: parse_and_send_old_events_to_keen(client, dry, reverse)
null
null
null
back
codeqa
def main args parse args client get keen client dry args dryreverse args reverseif args remove event remove event from keen client args source collection args remove event if args smooth events smooth events in keen client args source collection parse args start date parse args end date dry reverse elif args transfer collection transfer events to another collection client args source collection args destination collection dry reverse elif args old analytics parse and send old events to keen client dry reverse
null
null
null
null
Question: In which direction do them send to keen ? Code: def main(): args = parse_args() client = get_keen_client() dry = args.dry reverse = args.reverse if args.remove_event: remove_event_from_keen(client, args.source_collection, args.remove_event) if args.smooth_events: smooth_events_in_keen(client, args.source_collection, parse(args.start_date), parse(args.end_date), dry, reverse) elif args.transfer_collection: transfer_events_to_another_collection(client, args.source_collection, args.destination_collection, dry, reverse) elif args.old_analytics: parse_and_send_old_events_to_keen(client, dry, reverse)
null
null
null
What does the code create ?
@pick_context_manager_writer def instance_group_create(context, values, policies=None, members=None): uuid = values.get('uuid', None) if (uuid is None): uuid = uuidutils.generate_uuid() values['uuid'] = uuid try: group = models.InstanceGroup() group.update(values) group.save(context.session) except db_exc.DBDuplicateEntry: raise exception.InstanceGroupIdExists(group_uuid=uuid) if policies: _instance_group_policies_add(context, group.id, policies) else: group._policies = [] if members: _instance_group_members_add(context, group.id, members) else: group._members = [] return instance_group_get(context, uuid)
null
null
null
a new group
codeqa
@pick context manager writerdef instance group create context values policies None members None uuid values get 'uuid' None if uuid is None uuid uuidutils generate uuid values['uuid'] uuidtry group models Instance Group group update values group save context session except db exc DB Duplicate Entry raise exception Instance Group Id Exists group uuid uuid if policies instance group policies add context group id policies else group policies []if members instance group members add context group id members else group members []return instance group get context uuid
null
null
null
null
Question: What does the code create ? Code: @pick_context_manager_writer def instance_group_create(context, values, policies=None, members=None): uuid = values.get('uuid', None) if (uuid is None): uuid = uuidutils.generate_uuid() values['uuid'] = uuid try: group = models.InstanceGroup() group.update(values) group.save(context.session) except db_exc.DBDuplicateEntry: raise exception.InstanceGroupIdExists(group_uuid=uuid) if policies: _instance_group_policies_add(context, group.id, policies) else: group._policies = [] if members: _instance_group_members_add(context, group.id, members) else: group._members = [] return instance_group_get(context, uuid)
null
null
null
What does the code create ?
@utils.arg('name', metavar='<name>', help=_('Name of security group.')) @utils.arg('description', metavar='<description>', help=_('Description of security group.')) @deprecated_network def do_secgroup_create(cs, args): secgroup = cs.security_groups.create(args.name, args.description) _print_secgroups([secgroup])
null
null
null
a security group
codeqa
@utils arg 'name' metavar '<name>' help ' Nameofsecuritygroup ' @utils arg 'description' metavar '<description>' help ' Descriptionofsecuritygroup ' @deprecated networkdef do secgroup create cs args secgroup cs security groups create args name args description print secgroups [secgroup]
null
null
null
null
Question: What does the code create ? Code: @utils.arg('name', metavar='<name>', help=_('Name of security group.')) @utils.arg('description', metavar='<description>', help=_('Description of security group.')) @deprecated_network def do_secgroup_create(cs, args): secgroup = cs.security_groups.create(args.name, args.description) _print_secgroups([secgroup])
null
null
null
What does the code find ?
def nsmallest(n, iterable, key=None): (in1, in2) = tee(iterable) it = izip(imap(key, in1), count(), in2) result = _nsmallest(n, it) return map(itemgetter(2), result)
null
null
null
the n smallest elements in a dataset
codeqa
def nsmallest n iterable key None in 1 in 2 tee iterable it izip imap key in 1 count in 2 result nsmallest n it return map itemgetter 2 result
null
null
null
null
Question: What does the code find ? Code: def nsmallest(n, iterable, key=None): (in1, in2) = tee(iterable) it = izip(imap(key, in1), count(), in2) result = _nsmallest(n, it) return map(itemgetter(2), result)
null
null
null
What does the code add ?
def addLighteningHoles(derivation, gearHolePaths, negatives, pitchRadius, positives): extrudeDerivation = extrude.ExtrudeDerivation() positiveVertexes = matrix.getVertexes(positives) bottomPath = euclidean.getTopPath(positiveVertexes) topPath = euclidean.getBottomPath(positiveVertexes) extrudeDerivation.offsetPathDefault = [Vector3(0.0, 0.0, bottomPath), Vector3(0.0, 0.0, topPath)] extrudeDerivation.setToXMLElement(derivation.copyShallow) vector3LighteningHoles = getLighteningHoles(derivation, gearHolePaths, pitchRadius) extrude.addNegativesPositives(extrudeDerivation, negatives, vector3LighteningHoles, positives)
null
null
null
lightening holes
codeqa
def add Lightening Holes derivation gear Hole Paths negatives pitch Radius positives extrude Derivation extrude Extrude Derivation positive Vertexes matrix get Vertexes positives bottom Path euclidean get Top Path positive Vertexes top Path euclidean get Bottom Path positive Vertexes extrude Derivation offset Path Default [ Vector 3 0 0 0 0 bottom Path Vector 3 0 0 0 0 top Path ]extrude Derivation set To XML Element derivation copy Shallow vector 3 Lightening Holes get Lightening Holes derivation gear Hole Paths pitch Radius extrude add Negatives Positives extrude Derivation negatives vector 3 Lightening Holes positives
null
null
null
null
Question: What does the code add ? Code: def addLighteningHoles(derivation, gearHolePaths, negatives, pitchRadius, positives): extrudeDerivation = extrude.ExtrudeDerivation() positiveVertexes = matrix.getVertexes(positives) bottomPath = euclidean.getTopPath(positiveVertexes) topPath = euclidean.getBottomPath(positiveVertexes) extrudeDerivation.offsetPathDefault = [Vector3(0.0, 0.0, bottomPath), Vector3(0.0, 0.0, topPath)] extrudeDerivation.setToXMLElement(derivation.copyShallow) vector3LighteningHoles = getLighteningHoles(derivation, gearHolePaths, pitchRadius) extrude.addNegativesPositives(extrudeDerivation, negatives, vector3LighteningHoles, positives)
null
null
null
How do fiends appear ?
def _check_for_misordered_fields(entries, expected): actual = [field for field in entries.keys() if (field in expected)] expected = [field for field in expected if (field in actual)] if (actual != expected): actual_label = ', '.join(actual) expected_label = ', '.join(expected) raise ValueError(("The fields in a section of the document are misordered. It should be '%s' but was '%s'" % (actual_label, expected_label)))
null
null
null
in a specific order
codeqa
def check for misordered fields entries expected actual [field for field in entries keys if field in expected ]expected [field for field in expected if field in actual ]if actual expected actual label ' ' join actual expected label ' ' join expected raise Value Error " Thefieldsinasectionofthedocumentaremisordered Itshouldbe'%s'butwas'%s'" % actual label expected label
null
null
null
null
Question: How do fiends appear ? Code: def _check_for_misordered_fields(entries, expected): actual = [field for field in entries.keys() if (field in expected)] expected = [field for field in expected if (field in actual)] if (actual != expected): actual_label = ', '.join(actual) expected_label = ', '.join(expected) raise ValueError(("The fields in a section of the document are misordered. It should be '%s' but was '%s'" % (actual_label, expected_label)))
null
null
null
How do transforms combine ?
@testing.requires_testing_data def test_combine(): trans = read_trans(fname) inv = invert_transform(trans) combine_transforms(trans, inv, trans['from'], trans['from']) assert_raises(RuntimeError, combine_transforms, trans, inv, trans['to'], trans['from']) assert_raises(RuntimeError, combine_transforms, trans, inv, trans['from'], trans['to']) assert_raises(RuntimeError, combine_transforms, trans, trans, trans['from'], trans['to'])
null
null
null
test
codeqa
@testing requires testing datadef test combine trans read trans fname inv invert transform trans combine transforms trans inv trans['from'] trans['from'] assert raises Runtime Error combine transforms trans inv trans['to'] trans['from'] assert raises Runtime Error combine transforms trans inv trans['from'] trans['to'] assert raises Runtime Error combine transforms trans trans trans['from'] trans['to']
null
null
null
null
Question: How do transforms combine ? Code: @testing.requires_testing_data def test_combine(): trans = read_trans(fname) inv = invert_transform(trans) combine_transforms(trans, inv, trans['from'], trans['from']) assert_raises(RuntimeError, combine_transforms, trans, inv, trans['to'], trans['from']) assert_raises(RuntimeError, combine_transforms, trans, inv, trans['from'], trans['to']) assert_raises(RuntimeError, combine_transforms, trans, trans, trans['from'], trans['to'])
null
null
null
For what purpose does the indefinite article return ?
def indefinite_article(word, gender=MALE, role=SUBJECT): return article_indefinite.get((gender[:1].lower(), role[:3].lower()))
null
null
null
for a given word
codeqa
def indefinite article word gender MALE role SUBJECT return article indefinite get gender[ 1] lower role[ 3] lower
null
null
null
null
Question: For what purpose does the indefinite article return ? Code: def indefinite_article(word, gender=MALE, role=SUBJECT): return article_indefinite.get((gender[:1].lower(), role[:3].lower()))
null
null
null
How do various extensions that python - markdown supports use ?
def markdown(value, extensions=MARKDOWN_EXTENSIONS): try: import markdown except ImportError: warnings.warn("The Python markdown library isn't installed.", RuntimeWarning) return value return markdown.markdown(force_text(value), extensions=extensions)
null
null
null
optionally
codeqa
def markdown value extensions MARKDOWN EXTENSIONS try import markdownexcept Import Error warnings warn " The Pythonmarkdownlibraryisn'tinstalled " Runtime Warning return valuereturn markdown markdown force text value extensions extensions
null
null
null
null
Question: How do various extensions that python - markdown supports use ? Code: def markdown(value, extensions=MARKDOWN_EXTENSIONS): try: import markdown except ImportError: warnings.warn("The Python markdown library isn't installed.", RuntimeWarning) return value return markdown.markdown(force_text(value), extensions=extensions)
null
null
null
What does the code get ?
def libvlc_media_player_get_length(p_mi): f = (_Cfunctions.get('libvlc_media_player_get_length', None) or _Cfunction('libvlc_media_player_get_length', ((1,),), None, ctypes.c_longlong, MediaPlayer)) return f(p_mi)
null
null
null
the current movie length
codeqa
def libvlc media player get length p mi f Cfunctions get 'libvlc media player get length' None or Cfunction 'libvlc media player get length' 1 None ctypes c longlong Media Player return f p mi
null
null
null
null
Question: What does the code get ? Code: def libvlc_media_player_get_length(p_mi): f = (_Cfunctions.get('libvlc_media_player_get_length', None) or _Cfunction('libvlc_media_player_get_length', ((1,),), None, ctypes.c_longlong, MediaPlayer)) return f(p_mi)
null
null
null
What did the code read ?
def _read_sites(handle): alphabet = dna instances = [] for line in handle: if (not line.startswith('>')): break line = next(handle) instance = '' for c in line.strip(): if (c == c.upper()): instance += c instance = Seq(instance, alphabet) instances.append(instance) instances = motifs.Instances(instances, alphabet) motif = Motif(matrix_id=None, name=None, alphabet=alphabet, instances=instances) motif.mask = ('*' * motif.length) record = Record() record.append(motif) return record
null
null
null
the motif
codeqa
def read sites handle alphabet dnainstances []for line in handle if not line startswith '>' breakline next handle instance ''for c in line strip if c c upper instance + cinstance Seq instance alphabet instances append instance instances motifs Instances instances alphabet motif Motif matrix id None name None alphabet alphabet instances instances motif mask '*' * motif length record Record record append motif return record
null
null
null
null
Question: What did the code read ? Code: def _read_sites(handle): alphabet = dna instances = [] for line in handle: if (not line.startswith('>')): break line = next(handle) instance = '' for c in line.strip(): if (c == c.upper()): instance += c instance = Seq(instance, alphabet) instances.append(instance) instances = motifs.Instances(instances, alphabet) motif = Motif(matrix_id=None, name=None, alphabet=alphabet, instances=instances) motif.mask = ('*' * motif.length) record = Record() record.append(motif) return record
null
null
null
What does the code compute ?
def rs_newton(p, x, prec): deg = p.degree() p1 = _invert_monoms(p) p2 = rs_series_inversion(p1, x, prec) p3 = rs_mul(p1.diff(x), p2, x, prec) res = (deg - (p3 * x)) return res
null
null
null
the truncated newton sum of the polynomial p examples
codeqa
def rs newton p x prec deg p degree p1 invert monoms p p2 rs series inversion p1 x prec p3 rs mul p1 diff x p2 x prec res deg - p3 * x return res
null
null
null
null
Question: What does the code compute ? Code: def rs_newton(p, x, prec): deg = p.degree() p1 = _invert_monoms(p) p2 = rs_series_inversion(p1, x, prec) p3 = rs_mul(p1.diff(x), p2, x, prec) res = (deg - (p3 * x)) return res
null
null
null
What does the code get ?
def get_all_tensor_parents(tensor): parents_list = [] parents_list.append(tensor) if tensor.op: for t in tensor.op.inputs: parents_list += get_tensor_parents(t) return list(set(parents_list))
null
null
null
all parents tensors
codeqa
def get all tensor parents tensor parents list []parents list append tensor if tensor op for t in tensor op inputs parents list + get tensor parents t return list set parents list
null
null
null
null
Question: What does the code get ? Code: def get_all_tensor_parents(tensor): parents_list = [] parents_list.append(tensor) if tensor.op: for t in tensor.op.inputs: parents_list += get_tensor_parents(t) return list(set(parents_list))
null
null
null
How did paths weight ?
def multi_source_dijkstra(G, sources, target=None, cutoff=None, weight='weight'): if (not sources): raise ValueError('sources must not be empty') if (target in sources): return ({target: 0}, {target: [target]}) weight = _weight_function(G, weight) paths = {source: [source] for source in sources} dist = _dijkstra_multisource(G, sources, weight, paths=paths, cutoff=cutoff, target=target) return (dist, paths)
null
null
null
shortest
codeqa
def multi source dijkstra G sources target None cutoff None weight 'weight' if not sources raise Value Error 'sourcesmustnotbeempty' if target in sources return {target 0} {target [target]} weight weight function G weight paths {source [source] for source in sources}dist dijkstra multisource G sources weight paths paths cutoff cutoff target target return dist paths
null
null
null
null
Question: How did paths weight ? Code: def multi_source_dijkstra(G, sources, target=None, cutoff=None, weight='weight'): if (not sources): raise ValueError('sources must not be empty') if (target in sources): return ({target: 0}, {target: [target]}) weight = _weight_function(G, weight) paths = {source: [source] for source in sources} dist = _dijkstra_multisource(G, sources, weight, paths=paths, cutoff=cutoff, target=target) return (dist, paths)
null
null
null
What does the code find from a given set of source nodes ?
def multi_source_dijkstra(G, sources, target=None, cutoff=None, weight='weight'): if (not sources): raise ValueError('sources must not be empty') if (target in sources): return ({target: 0}, {target: [target]}) weight = _weight_function(G, weight) paths = {source: [source] for source in sources} dist = _dijkstra_multisource(G, sources, weight, paths=paths, cutoff=cutoff, target=target) return (dist, paths)
null
null
null
shortest weighted paths and lengths
codeqa
def multi source dijkstra G sources target None cutoff None weight 'weight' if not sources raise Value Error 'sourcesmustnotbeempty' if target in sources return {target 0} {target [target]} weight weight function G weight paths {source [source] for source in sources}dist dijkstra multisource G sources weight paths paths cutoff cutoff target target return dist paths
null
null
null
null
Question: What does the code find from a given set of source nodes ? Code: def multi_source_dijkstra(G, sources, target=None, cutoff=None, weight='weight'): if (not sources): raise ValueError('sources must not be empty') if (target in sources): return ({target: 0}, {target: [target]}) weight = _weight_function(G, weight) paths = {source: [source] for source in sources} dist = _dijkstra_multisource(G, sources, weight, paths=paths, cutoff=cutoff, target=target) return (dist, paths)
null
null
null
What does the code convert ?
def _media_size_to_long(maxSize): if (len(maxSize) < 2): return 0 units = maxSize[(-2):].upper() bit_shift = _MEDIA_SIZE_BIT_SHIFTS.get(units) if (bit_shift is not None): return (int(maxSize[:(-2)]) << bit_shift) else: return int(maxSize)
null
null
null
a string media size
codeqa
def media size to long max Size if len max Size < 2 return 0units max Size[ -2 ] upper bit shift MEDIA SIZE BIT SHIFTS get units if bit shift is not None return int max Size[ -2 ] << bit shift else return int max Size
null
null
null
null
Question: What does the code convert ? Code: def _media_size_to_long(maxSize): if (len(maxSize) < 2): return 0 units = maxSize[(-2):].upper() bit_shift = _MEDIA_SIZE_BIT_SHIFTS.get(units) if (bit_shift is not None): return (int(maxSize[:(-2)]) << bit_shift) else: return int(maxSize)
null
null
null
By how much do the current organization switch ?
def switch_org(orgname, profile='grafana'): if isinstance(profile, string_types): profile = __salt__['config.option'](profile) org = get_org(orgname, profile) response = requests.post('{0}/api/user/using/{1}'.format(profile['grafana_url'], org['id']), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get('grafana_timeout', 3)) if (response.status_code >= 400): response.raise_for_status() return org
null
null
null
code
codeqa
def switch org orgname profile 'grafana' if isinstance profile string types profile salt ['config option'] profile org get org orgname profile response requests post '{ 0 }/api/user/using/{ 1 }' format profile['grafana url'] org['id'] auth get auth profile headers get headers profile timeout profile get 'grafana timeout' 3 if response status code > 400 response raise for status return org
null
null
null
null
Question: By how much do the current organization switch ? Code: def switch_org(orgname, profile='grafana'): if isinstance(profile, string_types): profile = __salt__['config.option'](profile) org = get_org(orgname, profile) response = requests.post('{0}/api/user/using/{1}'.format(profile['grafana_url'], org['id']), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get('grafana_timeout', 3)) if (response.status_code >= 400): response.raise_for_status() return org
null
null
null
What does the code get ?
def neighborhood(centerIndex, radius, dimensions): centerPosition = coordinatesFromIndex(centerIndex, dimensions) intervals = [] for (i, dimension) in enumerate(dimensions): left = max(0, (centerPosition[i] - radius)) right = min((dimension - 1), (centerPosition[i] + radius)) intervals.append(xrange(left, (right + 1))) coords = numpy.array(list(itertools.product(*intervals))) return numpy.ravel_multi_index(coords.T, dimensions)
null
null
null
the points in the neighborhood of a point
codeqa
def neighborhood center Index radius dimensions center Position coordinates From Index center Index dimensions intervals []for i dimension in enumerate dimensions left max 0 center Position[i] - radius right min dimension - 1 center Position[i] + radius intervals append xrange left right + 1 coords numpy array list itertools product *intervals return numpy ravel multi index coords T dimensions
null
null
null
null
Question: What does the code get ? Code: def neighborhood(centerIndex, radius, dimensions): centerPosition = coordinatesFromIndex(centerIndex, dimensions) intervals = [] for (i, dimension) in enumerate(dimensions): left = max(0, (centerPosition[i] - radius)) right = min((dimension - 1), (centerPosition[i] + radius)) intervals.append(xrange(left, (right + 1))) coords = numpy.array(list(itertools.product(*intervals))) return numpy.ravel_multi_index(coords.T, dimensions)
null
null
null
What does the code build ?
def pytest_generate_tests(metafunc): N_C_K = [(64, 64, 64), (32, 1, 128)] D_H_W = [(3, 7, 58), (3, 1, 68)] T_R_S = [(3, 3, 3), (1, 3, 3), (1, 1, 11)] pad_d_h_w = [(0, 1, 1), (0, 0, 1)] str_d_h_w = [(1, 1, 1), (1, 1, 2)] if ('fargs_tests' in metafunc.fixturenames): fargs = itt.product(N_C_K, D_H_W, T_R_S, pad_d_h_w, str_d_h_w) metafunc.parametrize('fargs_tests', fargs)
null
null
null
a list of test arguments
codeqa
def pytest generate tests metafunc N C K [ 64 64 64 32 1 128 ]D H W [ 3 7 58 3 1 68 ]T R S [ 3 3 3 1 3 3 1 1 11 ]pad d h w [ 0 1 1 0 0 1 ]str d h w [ 1 1 1 1 1 2 ]if 'fargs tests' in metafunc fixturenames fargs itt product N C K D H W T R S pad d h w str d h w metafunc parametrize 'fargs tests' fargs
null
null
null
null
Question: What does the code build ? Code: def pytest_generate_tests(metafunc): N_C_K = [(64, 64, 64), (32, 1, 128)] D_H_W = [(3, 7, 58), (3, 1, 68)] T_R_S = [(3, 3, 3), (1, 3, 3), (1, 1, 11)] pad_d_h_w = [(0, 1, 1), (0, 0, 1)] str_d_h_w = [(1, 1, 1), (1, 1, 2)] if ('fargs_tests' in metafunc.fixturenames): fargs = itt.product(N_C_K, D_H_W, T_R_S, pad_d_h_w, str_d_h_w) metafunc.parametrize('fargs_tests', fargs)
null
null
null
How do tokenization / string clean tokenization / string ?
def clean_str(string): string = re.sub("[^A-Za-z0-9(),!?\\'\\`]", ' ', string) string = re.sub("\\'s", " 's", string) string = re.sub("\\'ve", " 've", string) string = re.sub("n\\'t", " n't", string) string = re.sub("\\'re", " 're", string) string = re.sub("\\'d", " 'd", string) string = re.sub("\\'ll", " 'll", string) string = re.sub(',', ' , ', string) string = re.sub('!', ' ! ', string) string = re.sub('\\(', ' \\( ', string) string = re.sub('\\)', ' \\) ', string) string = re.sub('\\?', ' \\? ', string) string = re.sub('\\s{2,}', ' ', string) return string.strip().lower()
null
null
null
code
codeqa
def clean str string string re sub "[^A- Za-z 0 - 9 ?\\'\\`]" '' string string re sub "\\'s" "'s" string string re sub "\\'ve" "'ve" string string re sub "n\\'t" "n't" string string re sub "\\'re" "'re" string string re sub "\\'d" "'d" string string re sub "\\'ll" "'ll" string string re sub ' ' ' ' string string re sub ' ' ' ' string string re sub '\\ ' '\\ ' string string re sub '\\ ' '\\ ' string string re sub '\\?' '\\?' string string re sub '\\s{ 2 }' '' string return string strip lower
null
null
null
null
Question: How do tokenization / string clean tokenization / string ? Code: def clean_str(string): string = re.sub("[^A-Za-z0-9(),!?\\'\\`]", ' ', string) string = re.sub("\\'s", " 's", string) string = re.sub("\\'ve", " 've", string) string = re.sub("n\\'t", " n't", string) string = re.sub("\\'re", " 're", string) string = re.sub("\\'d", " 'd", string) string = re.sub("\\'ll", " 'll", string) string = re.sub(',', ' , ', string) string = re.sub('!', ' ! ', string) string = re.sub('\\(', ' \\( ', string) string = re.sub('\\)', ' \\) ', string) string = re.sub('\\?', ' \\? ', string) string = re.sub('\\s{2,}', ' ', string) return string.strip().lower()
null
null
null
For what purpose does a label set on a function ?
def SetLabel(*labels): def Decorator(f): function_labels = getattr(f, 'labels', set()) f.labels = function_labels.union(set(labels)) return f return Decorator
null
null
null
so we can run tests with different types
codeqa
def Set Label *labels def Decorator f function labels getattr f 'labels' set f labels function labels union set labels return freturn Decorator
null
null
null
null
Question: For what purpose does a label set on a function ? Code: def SetLabel(*labels): def Decorator(f): function_labels = getattr(f, 'labels', set()) f.labels = function_labels.union(set(labels)) return f return Decorator
null
null
null
What can we run with different types ?
def SetLabel(*labels): def Decorator(f): function_labels = getattr(f, 'labels', set()) f.labels = function_labels.union(set(labels)) return f return Decorator
null
null
null
tests
codeqa
def Set Label *labels def Decorator f function labels getattr f 'labels' set f labels function labels union set labels return freturn Decorator
null
null
null
null
Question: What can we run with different types ? Code: def SetLabel(*labels): def Decorator(f): function_labels = getattr(f, 'labels', set()) f.labels = function_labels.union(set(labels)) return f return Decorator
null
null
null
How can we run tests ?
def SetLabel(*labels): def Decorator(f): function_labels = getattr(f, 'labels', set()) f.labels = function_labels.union(set(labels)) return f return Decorator
null
null
null
with different types
codeqa
def Set Label *labels def Decorator f function labels getattr f 'labels' set f labels function labels union set labels return freturn Decorator
null
null
null
null
Question: How can we run tests ? Code: def SetLabel(*labels): def Decorator(f): function_labels = getattr(f, 'labels', set()) f.labels = function_labels.union(set(labels)) return f return Decorator
null
null
null
What does the code show ?
def list_employees(order_by='id'): ret = {} (status, result) = _query(action='employees', command='directory') root = ET.fromstring(result) directory = root.getchildren() for cat in directory: if (cat.tag != 'employees'): continue for item in cat: emp_id = item.items()[0][1] emp_ret = {'id': emp_id} for details in item.getchildren(): emp_ret[details.items()[0][1]] = details.text ret[emp_ret[order_by]] = emp_ret return ret
null
null
null
all employees for this company
codeqa
def list employees order by 'id' ret {} status result query action 'employees' command 'directory' root ET fromstring result directory root getchildren for cat in directory if cat tag 'employees' continuefor item in cat emp id item items [0 ][ 1 ]emp ret {'id' emp id}for details in item getchildren emp ret[details items [0 ][ 1 ]] details textret[emp ret[order by]] emp retreturn ret
null
null
null
null
Question: What does the code show ? Code: def list_employees(order_by='id'): ret = {} (status, result) = _query(action='employees', command='directory') root = ET.fromstring(result) directory = root.getchildren() for cat in directory: if (cat.tag != 'employees'): continue for item in cat: emp_id = item.items()[0][1] emp_ret = {'id': emp_id} for details in item.getchildren(): emp_ret[details.items()[0][1]] = details.text ret[emp_ret[order_by]] = emp_ret return ret
null
null
null
Where do views expose ?
def expose(url='/', methods=('GET',)): def wrap(f): if (not hasattr(f, '_urls')): f._urls = [] f._urls.append((url, methods)) return f return wrap
null
null
null
in your view classes
codeqa
def expose url '/' methods 'GET' def wrap f if not hasattr f ' urls' f urls []f urls append url methods return freturn wrap
null
null
null
null
Question: Where do views expose ? Code: def expose(url='/', methods=('GET',)): def wrap(f): if (not hasattr(f, '_urls')): f._urls = [] f._urls.append((url, methods)) return f return wrap
null
null
null
What uses to expose views in your view classes ?
def expose(url='/', methods=('GET',)): def wrap(f): if (not hasattr(f, '_urls')): f._urls = [] f._urls.append((url, methods)) return f return wrap
null
null
null
this decorator
codeqa
def expose url '/' methods 'GET' def wrap f if not hasattr f ' urls' f urls []f urls append url methods return freturn wrap
null
null
null
null
Question: What uses to expose views in your view classes ? Code: def expose(url='/', methods=('GET',)): def wrap(f): if (not hasattr(f, '_urls')): f._urls = [] f._urls.append((url, methods)) return f return wrap
null
null
null
What exposes in your view classes ?
def expose(url='/', methods=('GET',)): def wrap(f): if (not hasattr(f, '_urls')): f._urls = [] f._urls.append((url, methods)) return f return wrap
null
null
null
views
codeqa
def expose url '/' methods 'GET' def wrap f if not hasattr f ' urls' f urls []f urls append url methods return freturn wrap
null
null
null
null
Question: What exposes in your view classes ? Code: def expose(url='/', methods=('GET',)): def wrap(f): if (not hasattr(f, '_urls')): f._urls = [] f._urls.append((url, methods)) return f return wrap
null
null
null
What does the code make ?
def test_unique(): with pytest.raises(TypeError): usertypes.enum('Enum', ['item', 'item'])
null
null
null
sure elements need to be unique
codeqa
def test unique with pytest raises Type Error usertypes enum ' Enum' ['item' 'item']
null
null
null
null
Question: What does the code make ? Code: def test_unique(): with pytest.raises(TypeError): usertypes.enum('Enum', ['item', 'item'])
null
null
null
What do elements need ?
def test_unique(): with pytest.raises(TypeError): usertypes.enum('Enum', ['item', 'item'])
null
null
null
to be unique
codeqa
def test unique with pytest raises Type Error usertypes enum ' Enum' ['item' 'item']
null
null
null
null
Question: What do elements need ? Code: def test_unique(): with pytest.raises(TypeError): usertypes.enum('Enum', ['item', 'item'])
null
null
null
How are those modules related to encodings ?
def ClearAllButEncodingsModules(module_dict): for module_name in module_dict.keys(): if ((not IsEncodingsModule(module_name)) and (module_name != 'sys')): del module_dict[module_name]
null
null
null
in any way
codeqa
def Clear All But Encodings Modules module dict for module name in module dict keys if not Is Encodings Module module name and module name 'sys' del module dict[module name]
null
null
null
null
Question: How are those modules related to encodings ? Code: def ClearAllButEncodingsModules(module_dict): for module_name in module_dict.keys(): if ((not IsEncodingsModule(module_name)) and (module_name != 'sys')): del module_dict[module_name]
null
null
null
What does the code send ?
def patch(url, data=None, **kwargs): return request('patch', url, data=data, **kwargs)
null
null
null
a patch request
codeqa
def patch url data None **kwargs return request 'patch' url data data **kwargs
null
null
null
null
Question: What does the code send ? Code: def patch(url, data=None, **kwargs): return request('patch', url, data=data, **kwargs)
null
null
null
What do we have ?
@access_log_level(logging.WARN) def log_view(request): if (not request.user.is_superuser): return HttpResponse(_('You must be a superuser.')) hostname = socket.gethostname() l = logging.getLogger() for h in l.handlers: if isinstance(h, desktop.log.log_buffer.FixedBufferHandler): return render('logs.mako', request, dict(log=[l for l in h.buf], query=request.GET.get('q', ''), hostname=hostname)) return render('logs.mako', request, dict(log=[_('No logs found!')], query='', hostname=hostname))
null
null
null
a log handler that retains the last x characters of log messages
codeqa
@access log level logging WARN def log view request if not request user is superuser return Http Response ' Youmustbeasuperuser ' hostname socket gethostname l logging get Logger for h in l handlers if isinstance h desktop log log buffer Fixed Buffer Handler return render 'logs mako' request dict log [l for l in h buf] query request GET get 'q' '' hostname hostname return render 'logs mako' request dict log [ ' Nologsfound ' ] query '' hostname hostname
null
null
null
null
Question: What do we have ? Code: @access_log_level(logging.WARN) def log_view(request): if (not request.user.is_superuser): return HttpResponse(_('You must be a superuser.')) hostname = socket.gethostname() l = logging.getLogger() for h in l.handlers: if isinstance(h, desktop.log.log_buffer.FixedBufferHandler): return render('logs.mako', request, dict(log=[l for l in h.buf], query=request.GET.get('q', ''), hostname=hostname)) return render('logs.mako', request, dict(log=[_('No logs found!')], query='', hostname=hostname))
null
null
null
What does a log handler retain ?
@access_log_level(logging.WARN) def log_view(request): if (not request.user.is_superuser): return HttpResponse(_('You must be a superuser.')) hostname = socket.gethostname() l = logging.getLogger() for h in l.handlers: if isinstance(h, desktop.log.log_buffer.FixedBufferHandler): return render('logs.mako', request, dict(log=[l for l in h.buf], query=request.GET.get('q', ''), hostname=hostname)) return render('logs.mako', request, dict(log=[_('No logs found!')], query='', hostname=hostname))
null
null
null
the last x characters of log messages
codeqa
@access log level logging WARN def log view request if not request user is superuser return Http Response ' Youmustbeasuperuser ' hostname socket gethostname l logging get Logger for h in l handlers if isinstance h desktop log log buffer Fixed Buffer Handler return render 'logs mako' request dict log [l for l in h buf] query request GET get 'q' '' hostname hostname return render 'logs mako' request dict log [ ' Nologsfound ' ] query '' hostname hostname
null
null
null
null
Question: What does a log handler retain ? Code: @access_log_level(logging.WARN) def log_view(request): if (not request.user.is_superuser): return HttpResponse(_('You must be a superuser.')) hostname = socket.gethostname() l = logging.getLogger() for h in l.handlers: if isinstance(h, desktop.log.log_buffer.FixedBufferHandler): return render('logs.mako', request, dict(log=[l for l in h.buf], query=request.GET.get('q', ''), hostname=hostname)) return render('logs.mako', request, dict(log=[_('No logs found!')], query='', hostname=hostname))
null
null
null
What retains the last x characters of log messages ?
@access_log_level(logging.WARN) def log_view(request): if (not request.user.is_superuser): return HttpResponse(_('You must be a superuser.')) hostname = socket.gethostname() l = logging.getLogger() for h in l.handlers: if isinstance(h, desktop.log.log_buffer.FixedBufferHandler): return render('logs.mako', request, dict(log=[l for l in h.buf], query=request.GET.get('q', ''), hostname=hostname)) return render('logs.mako', request, dict(log=[_('No logs found!')], query='', hostname=hostname))
null
null
null
a log handler
codeqa
@access log level logging WARN def log view request if not request user is superuser return Http Response ' Youmustbeasuperuser ' hostname socket gethostname l logging get Logger for h in l handlers if isinstance h desktop log log buffer Fixed Buffer Handler return render 'logs mako' request dict log [l for l in h buf] query request GET get 'q' '' hostname hostname return render 'logs mako' request dict log [ ' Nologsfound ' ] query '' hostname hostname
null
null
null
null
Question: What retains the last x characters of log messages ? Code: @access_log_level(logging.WARN) def log_view(request): if (not request.user.is_superuser): return HttpResponse(_('You must be a superuser.')) hostname = socket.gethostname() l = logging.getLogger() for h in l.handlers: if isinstance(h, desktop.log.log_buffer.FixedBufferHandler): return render('logs.mako', request, dict(log=[l for l in h.buf], query=request.GET.get('q', ''), hostname=hostname)) return render('logs.mako', request, dict(log=[_('No logs found!')], query='', hostname=hostname))