labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2
values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4
values | answer stringlengths 2 905 | src stringclasses 3
values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | Where is the stability calculated ?
| def populationStability(vectors, numSamples=None):
numVectors = len(vectors)
if (numSamples is None):
numSamples = (numVectors - 1)
countOn = range((numVectors - 1))
else:
countOn = numpy.random.randint(0, (numVectors - 1), numSamples)
sigmap = 0.0
for i in countOn:
match = checkMatch(vectors[i], vectors[(i + 1)], sparse=False)
if (match[1] != 0):
sigmap += (float(match[0]) / match[1])
return (sigmap / numSamples)
| null | null | null | the vectors
| codeqa | def population Stability vectors num Samples None num Vectors len vectors if num Samples is None num Samples num Vectors - 1 count On range num Vectors - 1 else count On numpy random randint 0 num Vectors - 1 num Samples sigmap 0 0for i in count On match check Match vectors[i] vectors[ i + 1 ] sparse False if match[ 1 ] 0 sigmap + float match[ 0 ] / match[ 1 ] return sigmap / num Samples
| null | null | null | null | Question:
Where is the stability calculated ?
Code:
def populationStability(vectors, numSamples=None):
numVectors = len(vectors)
if (numSamples is None):
numSamples = (numVectors - 1)
countOn = range((numVectors - 1))
else:
countOn = numpy.random.randint(0, (numVectors - 1), numSamples)
sigmap = 0.0
for i in countOn:
match = checkMatch(vectors[i], vectors[(i + 1)], sparse=False)
if (match[1] != 0):
sigmap += (float(match[0]) / match[1])
return (sigmap / numSamples)
|
null | null | null | When do a chart render the same ?
| def test_multi_render(Chart, datas):
chart = Chart()
chart = make_data(chart, datas)
svg = chart.render()
for i in range(2):
assert (svg == chart.render())
| null | null | null | always
| codeqa | def test multi render Chart datas chart Chart chart make data chart datas svg chart render for i in range 2 assert svg chart render
| null | null | null | null | Question:
When do a chart render the same ?
Code:
def test_multi_render(Chart, datas):
chart = Chart()
chart = make_data(chart, datas)
svg = chart.render()
for i in range(2):
assert (svg == chart.render())
|
null | null | null | What render the same always ?
| def test_multi_render(Chart, datas):
chart = Chart()
chart = make_data(chart, datas)
svg = chart.render()
for i in range(2):
assert (svg == chart.render())
| null | null | null | a chart
| codeqa | def test multi render Chart datas chart Chart chart make data chart datas svg chart render for i in range 2 assert svg chart render
| null | null | null | null | Question:
What render the same always ?
Code:
def test_multi_render(Chart, datas):
chart = Chart()
chart = make_data(chart, datas)
svg = chart.render()
for i in range(2):
assert (svg == chart.render())
|
null | null | null | What does the code remove ?
| @require_POST
@login_required
def remove_coupon(request, course_id):
coupon_id = request.POST.get('id', None)
if (not coupon_id):
return JsonResponse({'message': _('coupon id is None')}, status=400)
try:
coupon = Coupon.objects.get(id=coupon_id)
except ObjectDoesNotExist:
return JsonResponse({'message': _('coupon with the coupon id ({coupon_id}) DoesNotExist').format(coupon_id=coupon_id)}, status=400)
if (not coupon.is_active):
return JsonResponse({'message': _('coupon with the coupon id ({coupon_id}) is already inactive').format(coupon_id=coupon_id)}, status=400)
coupon.is_active = False
coupon.save()
return JsonResponse({'message': _('coupon with the coupon id ({coupon_id}) updated successfully').format(coupon_id=coupon_id)})
| null | null | null | the coupon against the coupon i d
| codeqa | @require POST@login requireddef remove coupon request course id coupon id request POST get 'id' None if not coupon id return Json Response {'message' 'couponidis None' } status 400 try coupon Coupon objects get id coupon id except Object Does Not Exist return Json Response {'message' 'couponwiththecouponid {coupon id} Does Not Exist' format coupon id coupon id } status 400 if not coupon is active return Json Response {'message' 'couponwiththecouponid {coupon id} isalreadyinactive' format coupon id coupon id } status 400 coupon is active Falsecoupon save return Json Response {'message' 'couponwiththecouponid {coupon id} updatedsuccessfully' format coupon id coupon id }
| null | null | null | null | Question:
What does the code remove ?
Code:
@require_POST
@login_required
def remove_coupon(request, course_id):
coupon_id = request.POST.get('id', None)
if (not coupon_id):
return JsonResponse({'message': _('coupon id is None')}, status=400)
try:
coupon = Coupon.objects.get(id=coupon_id)
except ObjectDoesNotExist:
return JsonResponse({'message': _('coupon with the coupon id ({coupon_id}) DoesNotExist').format(coupon_id=coupon_id)}, status=400)
if (not coupon.is_active):
return JsonResponse({'message': _('coupon with the coupon id ({coupon_id}) is already inactive').format(coupon_id=coupon_id)}, status=400)
coupon.is_active = False
coupon.save()
return JsonResponse({'message': _('coupon with the coupon id ({coupon_id}) updated successfully').format(coupon_id=coupon_id)})
|
null | null | null | What does the code create ?
| def create_factory_from_config(table, config):
args = config.copy()
del args['name']
key = args.pop('type')
try:
factory = table[key]
except KeyError:
return None
return partial(factory, **args)
| null | null | null | a benchmark parameter factory
| codeqa | def create factory from config table config args config copy del args['name']key args pop 'type' try factory table[key]except Key Error return Nonereturn partial factory **args
| null | null | null | null | Question:
What does the code create ?
Code:
def create_factory_from_config(table, config):
args = config.copy()
del args['name']
key = args.pop('type')
try:
factory = table[key]
except KeyError:
return None
return partial(factory, **args)
|
null | null | null | For what purpose do conditional retrieval support ?
| def condition(etag_func=None, last_modified_func=None):
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
def get_last_modified():
if last_modified_func:
dt = last_modified_func(request, *args, **kwargs)
if dt:
return timegm(dt.utctimetuple())
res_etag = (etag_func(request, *args, **kwargs) if etag_func else None)
res_etag = (quote_etag(res_etag) if (res_etag is not None) else None)
res_last_modified = get_last_modified()
response = get_conditional_response(request, etag=res_etag, last_modified=res_last_modified)
if (response is None):
response = func(request, *args, **kwargs)
if (res_last_modified and (not response.has_header('Last-Modified'))):
response['Last-Modified'] = http_date(res_last_modified)
if (res_etag and (not response.has_header('ETag'))):
response['ETag'] = res_etag
return response
return inner
return decorator
| null | null | null | for a view function
| codeqa | def condition etag func None last modified func None def decorator func @wraps func def inner request *args **kwargs def get last modified if last modified func dt last modified func request *args **kwargs if dt return timegm dt utctimetuple res etag etag func request *args **kwargs if etag func else None res etag quote etag res etag if res etag is not None else None res last modified get last modified response get conditional response request etag res etag last modified res last modified if response is None response func request *args **kwargs if res last modified and not response has header ' Last- Modified' response[' Last- Modified'] http date res last modified if res etag and not response has header 'E Tag' response['E Tag'] res etagreturn responsereturn innerreturn decorator
| null | null | null | null | Question:
For what purpose do conditional retrieval support ?
Code:
def condition(etag_func=None, last_modified_func=None):
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
def get_last_modified():
if last_modified_func:
dt = last_modified_func(request, *args, **kwargs)
if dt:
return timegm(dt.utctimetuple())
res_etag = (etag_func(request, *args, **kwargs) if etag_func else None)
res_etag = (quote_etag(res_etag) if (res_etag is not None) else None)
res_last_modified = get_last_modified()
response = get_conditional_response(request, etag=res_etag, last_modified=res_last_modified)
if (response is None):
response = func(request, *args, **kwargs)
if (res_last_modified and (not response.has_header('Last-Modified'))):
response['Last-Modified'] = http_date(res_last_modified)
if (res_etag and (not response.has_header('ETag'))):
response['ETag'] = res_etag
return response
return inner
return decorator
|
null | null | null | What does the code merge ?
| def get_load(jid):
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_load'.format(returner_)](jid))
return ret
| null | null | null | the load data from all returners
| codeqa | def get load jid ret {}for returner in opts [CONFIG KEY] ret update mminion returners['{ 0 } get load' format returner ] jid return ret
| null | null | null | null | Question:
What does the code merge ?
Code:
def get_load(jid):
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_load'.format(returner_)](jid))
return ret
|
null | null | null | What converts into a list of string words ?
| def process_sentence(sentence, start_word='<S>', end_word='</S>'):
try:
import nltk
except:
raise Exception('Hint : NLTK is required.')
if (start_word is not None):
process_sentence = [start_word]
else:
process_sentence = []
process_sentence.extend(nltk.tokenize.word_tokenize(sentence.lower()))
if (end_word is not None):
process_sentence.append(end_word)
return process_sentence
| null | null | null | a sentence string
| codeqa | def process sentence sentence start word '<S>' end word '</S>' try import nltkexcept raise Exception ' Hint NLT Kisrequired ' if start word is not None process sentence [start word]else process sentence []process sentence extend nltk tokenize word tokenize sentence lower if end word is not None process sentence append end word return process sentence
| null | null | null | null | Question:
What converts into a list of string words ?
Code:
def process_sentence(sentence, start_word='<S>', end_word='</S>'):
try:
import nltk
except:
raise Exception('Hint : NLTK is required.')
if (start_word is not None):
process_sentence = [start_word]
else:
process_sentence = []
process_sentence.extend(nltk.tokenize.word_tokenize(sentence.lower()))
if (end_word is not None):
process_sentence.append(end_word)
return process_sentence
|
null | null | null | What does a sentence string convert ?
| def process_sentence(sentence, start_word='<S>', end_word='</S>'):
try:
import nltk
except:
raise Exception('Hint : NLTK is required.')
if (start_word is not None):
process_sentence = [start_word]
else:
process_sentence = []
process_sentence.extend(nltk.tokenize.word_tokenize(sentence.lower()))
if (end_word is not None):
process_sentence.append(end_word)
return process_sentence
| null | null | null | into a list of string words
| codeqa | def process sentence sentence start word '<S>' end word '</S>' try import nltkexcept raise Exception ' Hint NLT Kisrequired ' if start word is not None process sentence [start word]else process sentence []process sentence extend nltk tokenize word tokenize sentence lower if end word is not None process sentence append end word return process sentence
| null | null | null | null | Question:
What does a sentence string convert ?
Code:
def process_sentence(sentence, start_word='<S>', end_word='</S>'):
try:
import nltk
except:
raise Exception('Hint : NLTK is required.')
if (start_word is not None):
process_sentence = [start_word]
else:
process_sentence = []
process_sentence.extend(nltk.tokenize.word_tokenize(sentence.lower()))
if (end_word is not None):
process_sentence.append(end_word)
return process_sentence
|
null | null | null | What did the code set ?
| def libvlc_video_set_subtitle_file(p_mi, psz_subtitle):
f = (_Cfunctions.get('libvlc_video_set_subtitle_file', None) or _Cfunction('libvlc_video_set_subtitle_file', ((1,), (1,)), None, ctypes.c_int, MediaPlayer, ctypes.c_char_p))
return f(p_mi, psz_subtitle)
| null | null | null | new video subtitle file
| codeqa | def libvlc video set subtitle file p mi psz subtitle f Cfunctions get 'libvlc video set subtitle file' None or Cfunction 'libvlc video set subtitle file' 1 1 None ctypes c int Media Player ctypes c char p return f p mi psz subtitle
| null | null | null | null | Question:
What did the code set ?
Code:
def libvlc_video_set_subtitle_file(p_mi, psz_subtitle):
f = (_Cfunctions.get('libvlc_video_set_subtitle_file', None) or _Cfunction('libvlc_video_set_subtitle_file', ((1,), (1,)), None, ctypes.c_int, MediaPlayer, ctypes.c_char_p))
return f(p_mi, psz_subtitle)
|
null | null | null | What does the code get for a given user ?
| def _get_drafts(user):
drafts = {'image': None, 'video': None}
if user.is_authenticated():
drafts['image'] = Image.objects.filter(creator=user, is_draft=True)
drafts['video'] = Video.objects.filter(creator=user, is_draft=True)
return drafts
| null | null | null | video and image drafts
| codeqa | def get drafts user drafts {'image' None 'video' None}if user is authenticated drafts['image'] Image objects filter creator user is draft True drafts['video'] Video objects filter creator user is draft True return drafts
| null | null | null | null | Question:
What does the code get for a given user ?
Code:
def _get_drafts(user):
drafts = {'image': None, 'video': None}
if user.is_authenticated():
drafts['image'] = Image.objects.filter(creator=user, is_draft=True)
drafts['video'] = Video.objects.filter(creator=user, is_draft=True)
return drafts
|
null | null | null | What does the code remove from each line of a chunk of text ?
| def _reindent(s, indent, reformat=True):
s = textwrap.dedent(s)
s = s.split('\n')
s = [x.rstrip() for x in s]
while (s and (not s[0])):
s = s[1:]
while (s and (not s[(-1)])):
s = s[:(-1)]
if reformat:
s = '\n'.join(s)
s = textwrap.wrap(s, initial_indent=indent, subsequent_indent=indent)
else:
s = [(indent + x) for x in s]
return ('\n'.join(s) + '\n')
| null | null | null | the existing indentation
| codeqa | def reindent s indent reformat True s textwrap dedent s s s split '\n' s [x rstrip for x in s]while s and not s[ 0 ] s s[ 1 ]while s and not s[ -1 ] s s[ -1 ]if reformat s '\n' join s s textwrap wrap s initial indent indent subsequent indent indent else s [ indent + x for x in s]return '\n' join s + '\n'
| null | null | null | null | Question:
What does the code remove from each line of a chunk of text ?
Code:
def _reindent(s, indent, reformat=True):
s = textwrap.dedent(s)
s = s.split('\n')
s = [x.rstrip() for x in s]
while (s and (not s[0])):
s = s[1:]
while (s and (not s[(-1)])):
s = s[:(-1)]
if reformat:
s = '\n'.join(s)
s = textwrap.wrap(s, initial_indent=indent, subsequent_indent=indent)
else:
s = [(indent + x) for x in s]
return ('\n'.join(s) + '\n')
|
null | null | null | What does the code return if successful ?
| def _run_horcmshutdown(inst):
result = utils.execute('horcmshutdown.sh', inst)
return result[0]
| null | null | null | 0
| codeqa | def run horcmshutdown inst result utils execute 'horcmshutdown sh' inst return result[ 0 ]
| null | null | null | null | Question:
What does the code return if successful ?
Code:
def _run_horcmshutdown(inst):
result = utils.execute('horcmshutdown.sh', inst)
return result[0]
|
null | null | null | What does the code locate ?
| def locateMark(mark, payload):
index = payload.find(mark, 0, (const.MAX_PADDING_LENGTH + const.MARK_LENGTH))
if (index < 0):
log.debug('Could not find the mark just yet.')
return None
if (((len(payload) - index) - const.MARK_LENGTH) < const.HMAC_SHA256_128_LENGTH):
log.debug('Found the mark but the HMAC is still incomplete.')
return None
log.debug('Successfully located the mark.')
return index
| null | null | null | the given mark in payload
| codeqa | def locate Mark mark payload index payload find mark 0 const MAX PADDING LENGTH + const MARK LENGTH if index < 0 log debug ' Couldnotfindthemarkjustyet ' return Noneif len payload - index - const MARK LENGTH < const HMAC SHA 256 128 LENGTH log debug ' Foundthemarkbutthe HMA Cisstillincomplete ' return Nonelog debug ' Successfullylocatedthemark ' return index
| null | null | null | null | Question:
What does the code locate ?
Code:
def locateMark(mark, payload):
index = payload.find(mark, 0, (const.MAX_PADDING_LENGTH + const.MARK_LENGTH))
if (index < 0):
log.debug('Could not find the mark just yet.')
return None
if (((len(payload) - index) - const.MARK_LENGTH) < const.HMAC_SHA256_128_LENGTH):
log.debug('Found the mark but the HMAC is still incomplete.')
return None
log.debug('Successfully located the mark.')
return index
|
null | null | null | What does the code return ?
| def locateMark(mark, payload):
index = payload.find(mark, 0, (const.MAX_PADDING_LENGTH + const.MARK_LENGTH))
if (index < 0):
log.debug('Could not find the mark just yet.')
return None
if (((len(payload) - index) - const.MARK_LENGTH) < const.HMAC_SHA256_128_LENGTH):
log.debug('Found the mark but the HMAC is still incomplete.')
return None
log.debug('Successfully located the mark.')
return index
| null | null | null | its index
| codeqa | def locate Mark mark payload index payload find mark 0 const MAX PADDING LENGTH + const MARK LENGTH if index < 0 log debug ' Couldnotfindthemarkjustyet ' return Noneif len payload - index - const MARK LENGTH < const HMAC SHA 256 128 LENGTH log debug ' Foundthemarkbutthe HMA Cisstillincomplete ' return Nonelog debug ' Successfullylocatedthemark ' return index
| null | null | null | null | Question:
What does the code return ?
Code:
def locateMark(mark, payload):
index = payload.find(mark, 0, (const.MAX_PADDING_LENGTH + const.MARK_LENGTH))
if (index < 0):
log.debug('Could not find the mark just yet.')
return None
if (((len(payload) - index) - const.MARK_LENGTH) < const.HMAC_SHA256_128_LENGTH):
log.debug('Found the mark but the HMAC is still incomplete.')
return None
log.debug('Successfully located the mark.')
return index
|
null | null | null | What do an object use to set attributes ?
| def mock_object(**params):
return type('Mock', (), params)()
| null | null | null | params
| codeqa | def mock object **params return type ' Mock' params
| null | null | null | null | Question:
What do an object use to set attributes ?
Code:
def mock_object(**params):
return type('Mock', (), params)()
|
null | null | null | What does the code get with given task i d ?
| def _task_info_get(task_id):
global DATA
try:
task_info = DATA['task_info'][task_id]
except KeyError:
msg = (_LW('Could not find task info %s') % task_id)
LOG.warn(msg)
raise exception.TaskNotFound(task_id=task_id)
return task_info
| null | null | null | task info for task
| codeqa | def task info get task id global DAT Atry task info DATA['task info'][task id]except Key Error msg LW ' Couldnotfindtaskinfo%s' % task id LOG warn msg raise exception Task Not Found task id task id return task info
| null | null | null | null | Question:
What does the code get with given task i d ?
Code:
def _task_info_get(task_id):
global DATA
try:
task_info = DATA['task_info'][task_id]
except KeyError:
msg = (_LW('Could not find task info %s') % task_id)
LOG.warn(msg)
raise exception.TaskNotFound(task_id=task_id)
return task_info
|
null | null | null | How does the code get task info for task ?
| def _task_info_get(task_id):
global DATA
try:
task_info = DATA['task_info'][task_id]
except KeyError:
msg = (_LW('Could not find task info %s') % task_id)
LOG.warn(msg)
raise exception.TaskNotFound(task_id=task_id)
return task_info
| null | null | null | with given task i d
| codeqa | def task info get task id global DAT Atry task info DATA['task info'][task id]except Key Error msg LW ' Couldnotfindtaskinfo%s' % task id LOG warn msg raise exception Task Not Found task id task id return task info
| null | null | null | null | Question:
How does the code get task info for task ?
Code:
def _task_info_get(task_id):
global DATA
try:
task_info = DATA['task_info'][task_id]
except KeyError:
msg = (_LW('Could not find task info %s') % task_id)
LOG.warn(msg)
raise exception.TaskNotFound(task_id=task_id)
return task_info
|
null | null | null | What does the code find ?
| @celery_app.task(name='website.notifications.tasks.send_users_email', max_retries=0)
def send_users_email(send_type):
grouped_emails = get_users_emails(send_type)
if (not grouped_emails):
return
for group in grouped_emails:
user = User.load(group['user_id'])
if (not user):
log_exception()
continue
info = group['info']
notification_ids = [message['_id'] for message in info]
sorted_messages = group_by_node(info)
if sorted_messages:
mails.send_mail(to_addr=user.username, mimetype='html', mail=mails.DIGEST, name=user.fullname, message=sorted_messages, callback=remove_notifications(email_notification_ids=notification_ids))
| null | null | null | pending emails
| codeqa | @celery app task name 'website notifications tasks send users email' max retries 0 def send users email send type grouped emails get users emails send type if not grouped emails returnfor group in grouped emails user User load group['user id'] if not user log exception continueinfo group['info']notification ids [message[' id'] for message in info]sorted messages group by node info if sorted messages mails send mail to addr user username mimetype 'html' mail mails DIGEST name user fullname message sorted messages callback remove notifications email notification ids notification ids
| null | null | null | null | Question:
What does the code find ?
Code:
@celery_app.task(name='website.notifications.tasks.send_users_email', max_retries=0)
def send_users_email(send_type):
grouped_emails = get_users_emails(send_type)
if (not grouped_emails):
return
for group in grouped_emails:
user = User.load(group['user_id'])
if (not user):
log_exception()
continue
info = group['info']
notification_ids = [message['_id'] for message in info]
sorted_messages = group_by_node(info)
if sorted_messages:
mails.send_mail(to_addr=user.username, mimetype='html', mail=mails.DIGEST, name=user.fullname, message=sorted_messages, callback=remove_notifications(email_notification_ids=notification_ids))
|
null | null | null | What does the code compute ?
| def strict_dependencies(target, dep_context):
for declared in _resolve_aliases(target):
if isinstance(declared, dep_context.compiler_plugin_types):
for r in declared.closure(bfs=True, **dep_context.target_closure_kwargs):
(yield r)
else:
(yield declared)
| null | null | null | the strict compile target dependencies for this target
| codeqa | def strict dependencies target dep context for declared in resolve aliases target if isinstance declared dep context compiler plugin types for r in declared closure bfs True **dep context target closure kwargs yield r else yield declared
| null | null | null | null | Question:
What does the code compute ?
Code:
def strict_dependencies(target, dep_context):
for declared in _resolve_aliases(target):
if isinstance(declared, dep_context.compiler_plugin_types):
for r in declared.closure(bfs=True, **dep_context.target_closure_kwargs):
(yield r)
else:
(yield declared)
|
null | null | null | How does the code perform all checks on a host ?
| def CheckHost(host_data, os_name=None, cpe=None, labels=None, exclude_checks=None, restrict_checks=None):
kb = host_data.get('KnowledgeBase')
if (os_name is None):
os_name = kb.os
if (cpe is None):
pass
if (labels is None):
pass
return CheckRegistry.Process(host_data, os_name=os_name, cpe=cpe, labels=labels, restrict_checks=restrict_checks, exclude_checks=exclude_checks)
| null | null | null | using acquired artifacts
| codeqa | def Check Host host data os name None cpe None labels None exclude checks None restrict checks None kb host data get ' Knowledge Base' if os name is None os name kb osif cpe is None passif labels is None passreturn Check Registry Process host data os name os name cpe cpe labels labels restrict checks restrict checks exclude checks exclude checks
| null | null | null | null | Question:
How does the code perform all checks on a host ?
Code:
def CheckHost(host_data, os_name=None, cpe=None, labels=None, exclude_checks=None, restrict_checks=None):
kb = host_data.get('KnowledgeBase')
if (os_name is None):
os_name = kb.os
if (cpe is None):
pass
if (labels is None):
pass
return CheckRegistry.Process(host_data, os_name=os_name, cpe=cpe, labels=labels, restrict_checks=restrict_checks, exclude_checks=exclude_checks)
|
null | null | null | What does the code use ?
| def CheckHost(host_data, os_name=None, cpe=None, labels=None, exclude_checks=None, restrict_checks=None):
kb = host_data.get('KnowledgeBase')
if (os_name is None):
os_name = kb.os
if (cpe is None):
pass
if (labels is None):
pass
return CheckRegistry.Process(host_data, os_name=os_name, cpe=cpe, labels=labels, restrict_checks=restrict_checks, exclude_checks=exclude_checks)
| null | null | null | acquired artifacts
| codeqa | def Check Host host data os name None cpe None labels None exclude checks None restrict checks None kb host data get ' Knowledge Base' if os name is None os name kb osif cpe is None passif labels is None passreturn Check Registry Process host data os name os name cpe cpe labels labels restrict checks restrict checks exclude checks exclude checks
| null | null | null | null | Question:
What does the code use ?
Code:
def CheckHost(host_data, os_name=None, cpe=None, labels=None, exclude_checks=None, restrict_checks=None):
kb = host_data.get('KnowledgeBase')
if (os_name is None):
os_name = kb.os
if (cpe is None):
pass
if (labels is None):
pass
return CheckRegistry.Process(host_data, os_name=os_name, cpe=cpe, labels=labels, restrict_checks=restrict_checks, exclude_checks=exclude_checks)
|
null | null | null | What does the code perform using acquired artifacts ?
| def CheckHost(host_data, os_name=None, cpe=None, labels=None, exclude_checks=None, restrict_checks=None):
kb = host_data.get('KnowledgeBase')
if (os_name is None):
os_name = kb.os
if (cpe is None):
pass
if (labels is None):
pass
return CheckRegistry.Process(host_data, os_name=os_name, cpe=cpe, labels=labels, restrict_checks=restrict_checks, exclude_checks=exclude_checks)
| null | null | null | all checks on a host
| codeqa | def Check Host host data os name None cpe None labels None exclude checks None restrict checks None kb host data get ' Knowledge Base' if os name is None os name kb osif cpe is None passif labels is None passreturn Check Registry Process host data os name os name cpe cpe labels labels restrict checks restrict checks exclude checks exclude checks
| null | null | null | null | Question:
What does the code perform using acquired artifacts ?
Code:
def CheckHost(host_data, os_name=None, cpe=None, labels=None, exclude_checks=None, restrict_checks=None):
kb = host_data.get('KnowledgeBase')
if (os_name is None):
os_name = kb.os
if (cpe is None):
pass
if (labels is None):
pass
return CheckRegistry.Process(host_data, os_name=os_name, cpe=cpe, labels=labels, restrict_checks=restrict_checks, exclude_checks=exclude_checks)
|
null | null | null | What does the code get ?
| def getOverlapRatio(loop, pointTable):
numberOfOverlaps = 0
for point in loop:
if (point in pointTable):
numberOfOverlaps += 1
return (float(numberOfOverlaps) / float(len(loop)))
| null | null | null | the overlap ratio between the loop and the point table
| codeqa | def get Overlap Ratio loop point Table number Of Overlaps 0for point in loop if point in point Table number Of Overlaps + 1return float number Of Overlaps / float len loop
| null | null | null | null | Question:
What does the code get ?
Code:
def getOverlapRatio(loop, pointTable):
numberOfOverlaps = 0
for point in loop:
if (point in pointTable):
numberOfOverlaps += 1
return (float(numberOfOverlaps) / float(len(loop)))
|
null | null | null | What does the code create ?
| def SubTemplateElement(parent, tag, attrib=None, selector=None, subselector=None, **extra):
attrib = (attrib or {})
attrib.update(extra)
elem = TemplateElement(tag, attrib=attrib, selector=selector, subselector=subselector)
if (parent is not None):
parent.append(elem)
return elem
| null | null | null | a template element
| codeqa | def Sub Template Element parent tag attrib None selector None subselector None **extra attrib attrib or {} attrib update extra elem Template Element tag attrib attrib selector selector subselector subselector if parent is not None parent append elem return elem
| null | null | null | null | Question:
What does the code create ?
Code:
def SubTemplateElement(parent, tag, attrib=None, selector=None, subselector=None, **extra):
attrib = (attrib or {})
attrib.update(extra)
elem = TemplateElement(tag, attrib=attrib, selector=selector, subselector=subselector)
if (parent is not None):
parent.append(elem)
return elem
|
null | null | null | What does the code remove ?
| def ValidHeadersRewriter(response):
for (key, value) in response.headers.items():
try:
key.decode('ascii')
value.decode('ascii')
except UnicodeDecodeError:
del response.headers[key]
| null | null | null | invalid response headers
| codeqa | def Valid Headers Rewriter response for key value in response headers items try key decode 'ascii' value decode 'ascii' except Unicode Decode Error del response headers[key]
| null | null | null | null | Question:
What does the code remove ?
Code:
def ValidHeadersRewriter(response):
for (key, value) in response.headers.items():
try:
key.decode('ascii')
value.decode('ascii')
except UnicodeDecodeError:
del response.headers[key]
|
null | null | null | What is the given user following ?
| def is_following(user, actor):
return Follow.objects.is_following(user, actor)
| null | null | null | the actor
| codeqa | def is following user actor return Follow objects is following user actor
| null | null | null | null | Question:
What is the given user following ?
Code:
def is_following(user, actor):
return Follow.objects.is_following(user, actor)
|
null | null | null | What is following the actor ?
| def is_following(user, actor):
return Follow.objects.is_following(user, actor)
| null | null | null | the given user
| codeqa | def is following user actor return Follow objects is following user actor
| null | null | null | null | Question:
What is following the actor ?
Code:
def is_following(user, actor):
return Follow.objects.is_following(user, actor)
|
null | null | null | How does 401 response return ?
| def response_authenticate():
response = HttpResponse(status=401)
response['WWW-Authenticate'] = 'Basic realm="Git"'
return response
| null | null | null | with authenticate header
| codeqa | def response authenticate response Http Response status 401 response['WWW- Authenticate'] ' Basicrealm " Git"'return response
| null | null | null | null | Question:
How does 401 response return ?
Code:
def response_authenticate():
response = HttpResponse(status=401)
response['WWW-Authenticate'] = 'Basic realm="Git"'
return response
|
null | null | null | What does the function create actually ?
| def _track_from_response(result, timeout):
response = result['response']
status = response['track']['status'].lower()
if (status == 'pending'):
result = _wait_for_pending_track(response['track']['id'], timeout)
response = result['response']
status = response['track']['status'].lower()
if (not (status == 'complete')):
track_id = response['track']['id']
if (status == 'pending'):
raise Exception(("%s: the operation didn't complete before the timeout (%d secs)" % (track_id, timeout)))
else:
raise Exception(('%s: there was an error analyzing the track, status: %s' % (track_id, status)))
else:
track_properties = response['track']
identifier = track_properties.pop('id')
md5 = track_properties.pop('md5', None)
track_properties.update(track_properties.pop('audio_summary'))
return Track(identifier, md5, track_properties)
| null | null | null | the track object
| codeqa | def track from response result timeout response result['response']status response['track']['status'] lower if status 'pending' result wait for pending track response['track']['id'] timeout response result['response']status response['track']['status'] lower if not status 'complete' track id response['track']['id']if status 'pending' raise Exception "%s theoperationdidn'tcompletebeforethetimeout %dsecs " % track id timeout else raise Exception '%s therewasanerroranalyzingthetrack status %s' % track id status else track properties response['track']identifier track properties pop 'id' md 5 track properties pop 'md 5 ' None track properties update track properties pop 'audio summary' return Track identifier md 5 track properties
| null | null | null | null | Question:
What does the function create actually ?
Code:
def _track_from_response(result, timeout):
response = result['response']
status = response['track']['status'].lower()
if (status == 'pending'):
result = _wait_for_pending_track(response['track']['id'], timeout)
response = result['response']
status = response['track']['status'].lower()
if (not (status == 'complete')):
track_id = response['track']['id']
if (status == 'pending'):
raise Exception(("%s: the operation didn't complete before the timeout (%d secs)" % (track_id, timeout)))
else:
raise Exception(('%s: there was an error analyzing the track, status: %s' % (track_id, status)))
else:
track_properties = response['track']
identifier = track_properties.pop('id')
md5 = track_properties.pop('md5', None)
track_properties.update(track_properties.pop('audio_summary'))
return Track(identifier, md5, track_properties)
|
null | null | null | What does the code add next to a node ?
| def decorate(svg, node, metadata):
if (not metadata):
return node
xlink = metadata.get('xlink')
if xlink:
if (not isinstance(xlink, dict)):
xlink = {'href': xlink, 'target': '_blank'}
node = svg.node(node, 'a', **xlink)
svg.node(node, 'desc', class_='xlink').text = to_unicode(xlink.get('href'))
if ('tooltip' in metadata):
svg.node(node, 'title').text = to_unicode(metadata['tooltip'])
if ('color' in metadata):
color = metadata.pop('color')
node.attrib['style'] = ('fill: %s; stroke: %s' % (color, color))
if ('style' in metadata):
node.attrib['style'] = metadata.pop('style')
if ('label' in metadata):
svg.node(node, 'desc', class_='label').text = to_unicode(metadata['label'])
return node
| null | null | null | metedata
| codeqa | def decorate svg node metadata if not metadata return nodexlink metadata get 'xlink' if xlink if not isinstance xlink dict xlink {'href' xlink 'target' ' blank'}node svg node node 'a' **xlink svg node node 'desc' class 'xlink' text to unicode xlink get 'href' if 'tooltip' in metadata svg node node 'title' text to unicode metadata['tooltip'] if 'color' in metadata color metadata pop 'color' node attrib['style'] 'fill %s stroke %s' % color color if 'style' in metadata node attrib['style'] metadata pop 'style' if 'label' in metadata svg node node 'desc' class 'label' text to unicode metadata['label'] return node
| null | null | null | null | Question:
What does the code add next to a node ?
Code:
def decorate(svg, node, metadata):
if (not metadata):
return node
xlink = metadata.get('xlink')
if xlink:
if (not isinstance(xlink, dict)):
xlink = {'href': xlink, 'target': '_blank'}
node = svg.node(node, 'a', **xlink)
svg.node(node, 'desc', class_='xlink').text = to_unicode(xlink.get('href'))
if ('tooltip' in metadata):
svg.node(node, 'title').text = to_unicode(metadata['tooltip'])
if ('color' in metadata):
color = metadata.pop('color')
node.attrib['style'] = ('fill: %s; stroke: %s' % (color, color))
if ('style' in metadata):
node.attrib['style'] = metadata.pop('style')
if ('label' in metadata):
svg.node(node, 'desc', class_='label').text = to_unicode(metadata['label'])
return node
|
null | null | null | When does the code truncate a string ?
| def truncatewords(value, arg):
from django.utils.text import truncate_words
try:
length = int(arg)
except ValueError:
return value
if (not isinstance(value, basestring)):
value = str(value)
return truncate_words(value, length)
| null | null | null | after a certain number of words argument
| codeqa | def truncatewords value arg from django utils text import truncate wordstry length int arg except Value Error return valueif not isinstance value basestring value str value return truncate words value length
| null | null | null | null | Question:
When does the code truncate a string ?
Code:
def truncatewords(value, arg):
from django.utils.text import truncate_words
try:
length = int(arg)
except ValueError:
return value
if (not isinstance(value, basestring)):
value = str(value)
return truncate_words(value, length)
|
null | null | null | When do number truncate ?
| def truncatewords(value, arg):
from django.utils.text import truncate_words
try:
length = int(arg)
except ValueError:
return value
if (not isinstance(value, basestring)):
value = str(value)
return truncate_words(value, length)
| null | null | null | after
| codeqa | def truncatewords value arg from django utils text import truncate wordstry length int arg except Value Error return valueif not isinstance value basestring value str value return truncate words value length
| null | null | null | null | Question:
When do number truncate ?
Code:
def truncatewords(value, arg):
from django.utils.text import truncate_words
try:
length = int(arg)
except ValueError:
return value
if (not isinstance(value, basestring)):
value = str(value)
return truncate_words(value, length)
|
null | null | null | What does the code truncate after a certain number of words argument ?
| def truncatewords(value, arg):
from django.utils.text import truncate_words
try:
length = int(arg)
except ValueError:
return value
if (not isinstance(value, basestring)):
value = str(value)
return truncate_words(value, length)
| null | null | null | a string
| codeqa | def truncatewords value arg from django utils text import truncate wordstry length int arg except Value Error return valueif not isinstance value basestring value str value return truncate words value length
| null | null | null | null | Question:
What does the code truncate after a certain number of words argument ?
Code:
def truncatewords(value, arg):
from django.utils.text import truncate_words
try:
length = int(arg)
except ValueError:
return value
if (not isinstance(value, basestring)):
value = str(value)
return truncate_words(value, length)
|
null | null | null | What do we extract ?
| def parse_arxiv_url(url):
ix = url.rfind('/')
idversion = j['id'][(ix + 1):]
parts = idversion.split('v')
assert (len(parts) == 2), ('error parsing url ' + url)
return (parts[0], int(parts[1]))
| null | null | null | the raw i d and the version
| codeqa | def parse arxiv url url ix url rfind '/' idversion j['id'][ ix + 1 ]parts idversion split 'v' assert len parts 2 'errorparsingurl' + url return parts[ 0 ] int parts[ 1 ]
| null | null | null | null | Question:
What do we extract ?
Code:
def parse_arxiv_url(url):
ix = url.rfind('/')
idversion = j['id'][(ix + 1):]
parts = idversion.split('v')
assert (len(parts) == 2), ('error parsing url ' + url)
return (parts[0], int(parts[1]))
|
null | null | null | What do we want ?
| def parse_arxiv_url(url):
ix = url.rfind('/')
idversion = j['id'][(ix + 1):]
parts = idversion.split('v')
assert (len(parts) == 2), ('error parsing url ' + url)
return (parts[0], int(parts[1]))
| null | null | null | to extract the raw i d and the version
| codeqa | def parse arxiv url url ix url rfind '/' idversion j['id'][ ix + 1 ]parts idversion split 'v' assert len parts 2 'errorparsingurl' + url return parts[ 0 ] int parts[ 1 ]
| null | null | null | null | Question:
What do we want ?
Code:
def parse_arxiv_url(url):
ix = url.rfind('/')
idversion = j['id'][(ix + 1):]
parts = idversion.split('v')
assert (len(parts) == 2), ('error parsing url ' + url)
return (parts[0], int(parts[1]))
|
null | null | null | What does a model subclass set on the class ?
| def ensure_default_manager(sender, **kwargs):
cls = sender
if cls._meta.abstract:
return
if (not getattr(cls, '_default_manager', None)):
try:
cls._meta.get_field('objects')
raise ValueError(("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__))
except FieldDoesNotExist:
pass
cls.add_to_class('objects', Manager())
cls._base_manager = cls.objects
elif (not getattr(cls, '_base_manager', None)):
default_mgr = cls._default_manager.__class__
if ((default_mgr is Manager) or getattr(default_mgr, 'use_for_related_fields', False)):
cls._base_manager = cls._default_manager
else:
for base_class in default_mgr.mro()[1:]:
if ((base_class is Manager) or getattr(base_class, 'use_for_related_fields', False)):
cls.add_to_class('_base_manager', base_class())
return
raise AssertionError('Should never get here. Please report a bug, including your model and model manager setup.')
| null | null | null | the _ default_manager attribute
| codeqa | def ensure default manager sender **kwargs cls senderif cls meta abstract returnif not getattr cls ' default manager' None try cls meta get field 'objects' raise Value Error " Model%smustspecifyacustom Manager becauseithasafieldnamed'objects'" % cls name except Field Does Not Exist passcls add to class 'objects' Manager cls base manager cls objectselif not getattr cls ' base manager' None default mgr cls default manager class if default mgr is Manager or getattr default mgr 'use for related fields' False cls base manager cls default managerelse for base class in default mgr mro [1 ] if base class is Manager or getattr base class 'use for related fields' False cls add to class ' base manager' base class returnraise Assertion Error ' Shouldnevergethere Pleasereportabug includingyourmodelandmodelmanagersetup '
| null | null | null | null | Question:
What does a model subclass set on the class ?
Code:
def ensure_default_manager(sender, **kwargs):
cls = sender
if cls._meta.abstract:
return
if (not getattr(cls, '_default_manager', None)):
try:
cls._meta.get_field('objects')
raise ValueError(("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__))
except FieldDoesNotExist:
pass
cls.add_to_class('objects', Manager())
cls._base_manager = cls.objects
elif (not getattr(cls, '_base_manager', None)):
default_mgr = cls._default_manager.__class__
if ((default_mgr is Manager) or getattr(default_mgr, 'use_for_related_fields', False)):
cls._base_manager = cls._default_manager
else:
for base_class in default_mgr.mro()[1:]:
if ((base_class is Manager) or getattr(base_class, 'use_for_related_fields', False)):
cls.add_to_class('_base_manager', base_class())
return
raise AssertionError('Should never get here. Please report a bug, including your model and model manager setup.')
|
null | null | null | What does a model subclass contain ?
| def ensure_default_manager(sender, **kwargs):
cls = sender
if cls._meta.abstract:
return
if (not getattr(cls, '_default_manager', None)):
try:
cls._meta.get_field('objects')
raise ValueError(("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__))
except FieldDoesNotExist:
pass
cls.add_to_class('objects', Manager())
cls._base_manager = cls.objects
elif (not getattr(cls, '_base_manager', None)):
default_mgr = cls._default_manager.__class__
if ((default_mgr is Manager) or getattr(default_mgr, 'use_for_related_fields', False)):
cls._base_manager = cls._default_manager
else:
for base_class in default_mgr.mro()[1:]:
if ((base_class is Manager) or getattr(base_class, 'use_for_related_fields', False)):
cls.add_to_class('_base_manager', base_class())
return
raise AssertionError('Should never get here. Please report a bug, including your model and model manager setup.')
| null | null | null | a default manager
| codeqa | def ensure default manager sender **kwargs cls senderif cls meta abstract returnif not getattr cls ' default manager' None try cls meta get field 'objects' raise Value Error " Model%smustspecifyacustom Manager becauseithasafieldnamed'objects'" % cls name except Field Does Not Exist passcls add to class 'objects' Manager cls base manager cls objectselif not getattr cls ' base manager' None default mgr cls default manager class if default mgr is Manager or getattr default mgr 'use for related fields' False cls base manager cls default managerelse for base class in default mgr mro [1 ] if base class is Manager or getattr base class 'use for related fields' False cls add to class ' base manager' base class returnraise Assertion Error ' Shouldnevergethere Pleasereportabug includingyourmodelandmodelmanagersetup '
| null | null | null | null | Question:
What does a model subclass contain ?
Code:
def ensure_default_manager(sender, **kwargs):
cls = sender
if cls._meta.abstract:
return
if (not getattr(cls, '_default_manager', None)):
try:
cls._meta.get_field('objects')
raise ValueError(("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__))
except FieldDoesNotExist:
pass
cls.add_to_class('objects', Manager())
cls._base_manager = cls.objects
elif (not getattr(cls, '_base_manager', None)):
default_mgr = cls._default_manager.__class__
if ((default_mgr is Manager) or getattr(default_mgr, 'use_for_related_fields', False)):
cls._base_manager = cls._default_manager
else:
for base_class in default_mgr.mro()[1:]:
if ((base_class is Manager) or getattr(base_class, 'use_for_related_fields', False)):
cls.add_to_class('_base_manager', base_class())
return
raise AssertionError('Should never get here. Please report a bug, including your model and model manager setup.')
|
null | null | null | What contains a default manager ?
| def ensure_default_manager(sender, **kwargs):
cls = sender
if cls._meta.abstract:
return
if (not getattr(cls, '_default_manager', None)):
try:
cls._meta.get_field('objects')
raise ValueError(("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__))
except FieldDoesNotExist:
pass
cls.add_to_class('objects', Manager())
cls._base_manager = cls.objects
elif (not getattr(cls, '_base_manager', None)):
default_mgr = cls._default_manager.__class__
if ((default_mgr is Manager) or getattr(default_mgr, 'use_for_related_fields', False)):
cls._base_manager = cls._default_manager
else:
for base_class in default_mgr.mro()[1:]:
if ((base_class is Manager) or getattr(base_class, 'use_for_related_fields', False)):
cls.add_to_class('_base_manager', base_class())
return
raise AssertionError('Should never get here. Please report a bug, including your model and model manager setup.')
| null | null | null | a model subclass
| codeqa | def ensure default manager sender **kwargs cls senderif cls meta abstract returnif not getattr cls ' default manager' None try cls meta get field 'objects' raise Value Error " Model%smustspecifyacustom Manager becauseithasafieldnamed'objects'" % cls name except Field Does Not Exist passcls add to class 'objects' Manager cls base manager cls objectselif not getattr cls ' base manager' None default mgr cls default manager class if default mgr is Manager or getattr default mgr 'use for related fields' False cls base manager cls default managerelse for base class in default mgr mro [1 ] if base class is Manager or getattr base class 'use for related fields' False cls add to class ' base manager' base class returnraise Assertion Error ' Shouldnevergethere Pleasereportabug includingyourmodelandmodelmanagersetup '
| null | null | null | null | Question:
What contains a default manager ?
Code:
def ensure_default_manager(sender, **kwargs):
cls = sender
if cls._meta.abstract:
return
if (not getattr(cls, '_default_manager', None)):
try:
cls._meta.get_field('objects')
raise ValueError(("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__))
except FieldDoesNotExist:
pass
cls.add_to_class('objects', Manager())
cls._base_manager = cls.objects
elif (not getattr(cls, '_base_manager', None)):
default_mgr = cls._default_manager.__class__
if ((default_mgr is Manager) or getattr(default_mgr, 'use_for_related_fields', False)):
cls._base_manager = cls._default_manager
else:
for base_class in default_mgr.mro()[1:]:
if ((base_class is Manager) or getattr(base_class, 'use_for_related_fields', False)):
cls.add_to_class('_base_manager', base_class())
return
raise AssertionError('Should never get here. Please report a bug, including your model and model manager setup.')
|
null | null | null | What sets the _ default_manager attribute on the class ?
| def ensure_default_manager(sender, **kwargs):
cls = sender
if cls._meta.abstract:
return
if (not getattr(cls, '_default_manager', None)):
try:
cls._meta.get_field('objects')
raise ValueError(("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__))
except FieldDoesNotExist:
pass
cls.add_to_class('objects', Manager())
cls._base_manager = cls.objects
elif (not getattr(cls, '_base_manager', None)):
default_mgr = cls._default_manager.__class__
if ((default_mgr is Manager) or getattr(default_mgr, 'use_for_related_fields', False)):
cls._base_manager = cls._default_manager
else:
for base_class in default_mgr.mro()[1:]:
if ((base_class is Manager) or getattr(base_class, 'use_for_related_fields', False)):
cls.add_to_class('_base_manager', base_class())
return
raise AssertionError('Should never get here. Please report a bug, including your model and model manager setup.')
| null | null | null | a model subclass
| codeqa | def ensure default manager sender **kwargs cls senderif cls meta abstract returnif not getattr cls ' default manager' None try cls meta get field 'objects' raise Value Error " Model%smustspecifyacustom Manager becauseithasafieldnamed'objects'" % cls name except Field Does Not Exist passcls add to class 'objects' Manager cls base manager cls objectselif not getattr cls ' base manager' None default mgr cls default manager class if default mgr is Manager or getattr default mgr 'use for related fields' False cls base manager cls default managerelse for base class in default mgr mro [1 ] if base class is Manager or getattr base class 'use for related fields' False cls add to class ' base manager' base class returnraise Assertion Error ' Shouldnevergethere Pleasereportabug includingyourmodelandmodelmanagersetup '
| null | null | null | null | Question:
What sets the _ default_manager attribute on the class ?
Code:
def ensure_default_manager(sender, **kwargs):
cls = sender
if cls._meta.abstract:
return
if (not getattr(cls, '_default_manager', None)):
try:
cls._meta.get_field('objects')
raise ValueError(("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__))
except FieldDoesNotExist:
pass
cls.add_to_class('objects', Manager())
cls._base_manager = cls.objects
elif (not getattr(cls, '_base_manager', None)):
default_mgr = cls._default_manager.__class__
if ((default_mgr is Manager) or getattr(default_mgr, 'use_for_related_fields', False)):
cls._base_manager = cls._default_manager
else:
for base_class in default_mgr.mro()[1:]:
if ((base_class is Manager) or getattr(base_class, 'use_for_related_fields', False)):
cls.add_to_class('_base_manager', base_class())
return
raise AssertionError('Should never get here. Please report a bug, including your model and model manager setup.')
|
null | null | null | What match source ?
| def rewriterule(source, target, variables=(), condition=None, assume=None):
def rewrite_rl(expr, assumptions=True):
for match in unify(source, expr, {}, variables=variables):
if (condition and (not condition(*[match.get(var, var) for var in variables]))):
continue
if (assume and (not ask(assume.xreplace(match), assumptions))):
continue
expr2 = subs(match)(target)
if isinstance(expr2, Expr):
expr2 = rebuild(expr2)
(yield expr2)
return rewrite_rl
| null | null | null | expressions
| codeqa | def rewriterule source target variables condition None assume None def rewrite rl expr assumptions True for match in unify source expr {} variables variables if condition and not condition *[match get var var for var in variables] continueif assume and not ask assume xreplace match assumptions continueexpr 2 subs match target if isinstance expr 2 Expr expr 2 rebuild expr 2 yield expr 2 return rewrite rl
| null | null | null | null | Question:
What match source ?
Code:
def rewriterule(source, target, variables=(), condition=None, assume=None):
def rewrite_rl(expr, assumptions=True):
for match in unify(source, expr, {}, variables=variables):
if (condition and (not condition(*[match.get(var, var) for var in variables]))):
continue
if (assume and (not ask(assume.xreplace(match), assumptions))):
continue
expr2 = subs(match)(target)
if isinstance(expr2, Expr):
expr2 = rebuild(expr2)
(yield expr2)
return rewrite_rl
|
null | null | null | What do expressions match ?
| def rewriterule(source, target, variables=(), condition=None, assume=None):
def rewrite_rl(expr, assumptions=True):
for match in unify(source, expr, {}, variables=variables):
if (condition and (not condition(*[match.get(var, var) for var in variables]))):
continue
if (assume and (not ask(assume.xreplace(match), assumptions))):
continue
expr2 = subs(match)(target)
if isinstance(expr2, Expr):
expr2 = rebuild(expr2)
(yield expr2)
return rewrite_rl
| null | null | null | source
| codeqa | def rewriterule source target variables condition None assume None def rewrite rl expr assumptions True for match in unify source expr {} variables variables if condition and not condition *[match get var var for var in variables] continueif assume and not ask assume xreplace match assumptions continueexpr 2 subs match target if isinstance expr 2 Expr expr 2 rebuild expr 2 yield expr 2 return rewrite rl
| null | null | null | null | Question:
What do expressions match ?
Code:
def rewriterule(source, target, variables=(), condition=None, assume=None):
def rewrite_rl(expr, assumptions=True):
for match in unify(source, expr, {}, variables=variables):
if (condition and (not condition(*[match.get(var, var) for var in variables]))):
continue
if (assume and (not ask(assume.xreplace(match), assumptions))):
continue
expr2 = subs(match)(target)
if isinstance(expr2, Expr):
expr2 = rebuild(expr2)
(yield expr2)
return rewrite_rl
|
null | null | null | What does the code get ?
| def getlines(filename, module_globals=None):
if (filename in cache):
entry = cache[filename]
if (len(entry) != 1):
return cache[filename][2]
try:
return updatecache(filename, module_globals)
except MemoryError:
clearcache()
return []
| null | null | null | the lines for a python source file from the cache
| codeqa | def getlines filename module globals None if filename in cache entry cache[filename]if len entry 1 return cache[filename][ 2 ]try return updatecache filename module globals except Memory Error clearcache return []
| null | null | null | null | Question:
What does the code get ?
Code:
def getlines(filename, module_globals=None):
if (filename in cache):
entry = cache[filename]
if (len(entry) != 1):
return cache[filename][2]
try:
return updatecache(filename, module_globals)
except MemoryError:
clearcache()
return []
|
null | null | null | When is this function called ?
| def set_prefs(prefs):
prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg', '.svn', '_svn', '.git', '.tox', '.env', 'env', 'venv', 'node_modules', 'bower_components']
prefs['save_objectdb'] = True
prefs['compress_objectdb'] = False
prefs['automatic_soa'] = True
prefs['soa_followed_calls'] = 0
prefs['perform_doa'] = True
prefs['validate_objectdb'] = True
prefs['max_history_items'] = 32
prefs['save_history'] = True
prefs['compress_history'] = False
prefs['indent_size'] = 4
prefs['extension_modules'] = []
prefs['import_dynload_stdmods'] = True
prefs['ignore_syntax_errors'] = False
prefs['ignore_bad_imports'] = False
prefs['prefer_module_from_imports'] = False
prefs['split_imports'] = False
prefs['sort_imports_alphabetically'] = False
| null | null | null | before opening the project
| codeqa | def set prefs prefs prefs['ignored resources'] ['* pyc' '*~' ' ropeproject' ' hg' ' svn' ' svn' ' git' ' tox' ' env' 'env' 'venv' 'node modules' 'bower components']prefs['save objectdb'] Trueprefs['compress objectdb'] Falseprefs['automatic soa'] Trueprefs['soa followed calls'] 0prefs['perform doa'] Trueprefs['validate objectdb'] Trueprefs['max history items'] 32 prefs['save history'] Trueprefs['compress history'] Falseprefs['indent size'] 4prefs['extension modules'] []prefs['import dynload stdmods'] Trueprefs['ignore syntax errors'] Falseprefs['ignore bad imports'] Falseprefs['prefer module from imports'] Falseprefs['split imports'] Falseprefs['sort imports alphabetically'] False
| null | null | null | null | Question:
When is this function called ?
Code:
def set_prefs(prefs):
prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg', '.svn', '_svn', '.git', '.tox', '.env', 'env', 'venv', 'node_modules', 'bower_components']
prefs['save_objectdb'] = True
prefs['compress_objectdb'] = False
prefs['automatic_soa'] = True
prefs['soa_followed_calls'] = 0
prefs['perform_doa'] = True
prefs['validate_objectdb'] = True
prefs['max_history_items'] = 32
prefs['save_history'] = True
prefs['compress_history'] = False
prefs['indent_size'] = 4
prefs['extension_modules'] = []
prefs['import_dynload_stdmods'] = True
prefs['ignore_syntax_errors'] = False
prefs['ignore_bad_imports'] = False
prefs['prefer_module_from_imports'] = False
prefs['split_imports'] = False
prefs['sort_imports_alphabetically'] = False
|
null | null | null | What does the code provide in the given content ?
| def _get_quote_indices(line, escaped):
(indices, quote_index) = ([], (-1))
for _ in range(2):
quote_index = line.find('"', (quote_index + 1))
if escaped:
while ((quote_index >= 1) and (line[(quote_index - 1)] == '\\')):
quote_index = line.find('"', (quote_index + 1))
indices.append(quote_index)
return tuple(indices)
| null | null | null | the indices of the next two quotes
| codeqa | def get quote indices line escaped indices quote index [] -1 for in range 2 quote index line find '"' quote index + 1 if escaped while quote index > 1 and line[ quote index - 1 ] '\\' quote index line find '"' quote index + 1 indices append quote index return tuple indices
| null | null | null | null | Question:
What does the code provide in the given content ?
Code:
def _get_quote_indices(line, escaped):
(indices, quote_index) = ([], (-1))
for _ in range(2):
quote_index = line.find('"', (quote_index + 1))
if escaped:
while ((quote_index >= 1) and (line[(quote_index - 1)] == '\\')):
quote_index = line.find('"', (quote_index + 1))
indices.append(quote_index)
return tuple(indices)
|
null | null | null | Where does the code provide the indices of the next two quotes ?
| def _get_quote_indices(line, escaped):
(indices, quote_index) = ([], (-1))
for _ in range(2):
quote_index = line.find('"', (quote_index + 1))
if escaped:
while ((quote_index >= 1) and (line[(quote_index - 1)] == '\\')):
quote_index = line.find('"', (quote_index + 1))
indices.append(quote_index)
return tuple(indices)
| null | null | null | in the given content
| codeqa | def get quote indices line escaped indices quote index [] -1 for in range 2 quote index line find '"' quote index + 1 if escaped while quote index > 1 and line[ quote index - 1 ] '\\' quote index line find '"' quote index + 1 indices append quote index return tuple indices
| null | null | null | null | Question:
Where does the code provide the indices of the next two quotes ?
Code:
def _get_quote_indices(line, escaped):
(indices, quote_index) = ([], (-1))
for _ in range(2):
quote_index = line.find('"', (quote_index + 1))
if escaped:
while ((quote_index >= 1) and (line[(quote_index - 1)] == '\\')):
quote_index = line.find('"', (quote_index + 1))
indices.append(quote_index)
return tuple(indices)
|
null | null | null | What does this function allow ?
| @allow_jsonp
def register_public_key_server_auto(request):
public_key = urllib.unquote(request.GET.get('device_key', ''))
if RegisteredDevicePublicKey.objects.filter(public_key=public_key):
return HttpResponseForbidden('Device is already registered.')
zone = Zone(name=('Zone for public key %s' % public_key[:50]))
zone.save()
RegisteredDevicePublicKey(zone=zone, public_key=public_key).save()
return JsonResponse({})
| null | null | null | an anonymous client to request a device key to be associated with a new zone
| codeqa | @allow jsonpdef register public key server auto request public key urllib unquote request GET get 'device key' '' if Registered Device Public Key objects filter public key public key return Http Response Forbidden ' Deviceisalreadyregistered ' zone Zone name ' Zoneforpublickey%s' % public key[ 50 ] zone save Registered Device Public Key zone zone public key public key save return Json Response {}
| null | null | null | null | Question:
What does this function allow ?
Code:
@allow_jsonp
def register_public_key_server_auto(request):
public_key = urllib.unquote(request.GET.get('device_key', ''))
if RegisteredDevicePublicKey.objects.filter(public_key=public_key):
return HttpResponseForbidden('Device is already registered.')
zone = Zone(name=('Zone for public key %s' % public_key[:50]))
zone.save()
RegisteredDevicePublicKey(zone=zone, public_key=public_key).save()
return JsonResponse({})
|
null | null | null | What does an anonymous client request ?
| @allow_jsonp
def register_public_key_server_auto(request):
public_key = urllib.unquote(request.GET.get('device_key', ''))
if RegisteredDevicePublicKey.objects.filter(public_key=public_key):
return HttpResponseForbidden('Device is already registered.')
zone = Zone(name=('Zone for public key %s' % public_key[:50]))
zone.save()
RegisteredDevicePublicKey(zone=zone, public_key=public_key).save()
return JsonResponse({})
| null | null | null | a device key to be associated with a new zone
| codeqa | @allow jsonpdef register public key server auto request public key urllib unquote request GET get 'device key' '' if Registered Device Public Key objects filter public key public key return Http Response Forbidden ' Deviceisalreadyregistered ' zone Zone name ' Zoneforpublickey%s' % public key[ 50 ] zone save Registered Device Public Key zone zone public key public key save return Json Response {}
| null | null | null | null | Question:
What does an anonymous client request ?
Code:
@allow_jsonp
def register_public_key_server_auto(request):
public_key = urllib.unquote(request.GET.get('device_key', ''))
if RegisteredDevicePublicKey.objects.filter(public_key=public_key):
return HttpResponseForbidden('Device is already registered.')
zone = Zone(name=('Zone for public key %s' % public_key[:50]))
zone.save()
RegisteredDevicePublicKey(zone=zone, public_key=public_key).save()
return JsonResponse({})
|
null | null | null | What requests a device key to be associated with a new zone ?
| @allow_jsonp
def register_public_key_server_auto(request):
public_key = urllib.unquote(request.GET.get('device_key', ''))
if RegisteredDevicePublicKey.objects.filter(public_key=public_key):
return HttpResponseForbidden('Device is already registered.')
zone = Zone(name=('Zone for public key %s' % public_key[:50]))
zone.save()
RegisteredDevicePublicKey(zone=zone, public_key=public_key).save()
return JsonResponse({})
| null | null | null | an anonymous client
| codeqa | @allow jsonpdef register public key server auto request public key urllib unquote request GET get 'device key' '' if Registered Device Public Key objects filter public key public key return Http Response Forbidden ' Deviceisalreadyregistered ' zone Zone name ' Zoneforpublickey%s' % public key[ 50 ] zone save Registered Device Public Key zone zone public key public key save return Json Response {}
| null | null | null | null | Question:
What requests a device key to be associated with a new zone ?
Code:
@allow_jsonp
def register_public_key_server_auto(request):
public_key = urllib.unquote(request.GET.get('device_key', ''))
if RegisteredDevicePublicKey.objects.filter(public_key=public_key):
return HttpResponseForbidden('Device is already registered.')
zone = Zone(name=('Zone for public key %s' % public_key[:50]))
zone.save()
RegisteredDevicePublicKey(zone=zone, public_key=public_key).save()
return JsonResponse({})
|
null | null | null | What does the code build ?
| def buildAppropriateDataset(module):
if module.sequential:
d = SequentialDataSet(module.indim, module.outdim)
for dummy in range(2):
d.newSequence()
for dummy in range(3):
d.addSample(randn(module.indim), randn(module.outdim))
else:
d = SupervisedDataSet(module.indim, module.outdim)
for dummy in range(3):
d.addSample(randn(module.indim), randn(module.outdim))
return d
| null | null | null | a sequential dataset with 2 sequences of 3 samples
| codeqa | def build Appropriate Dataset module if module sequential d Sequential Data Set module indim module outdim for dummy in range 2 d new Sequence for dummy in range 3 d add Sample randn module indim randn module outdim else d Supervised Data Set module indim module outdim for dummy in range 3 d add Sample randn module indim randn module outdim return d
| null | null | null | null | Question:
What does the code build ?
Code:
def buildAppropriateDataset(module):
if module.sequential:
d = SequentialDataSet(module.indim, module.outdim)
for dummy in range(2):
d.newSequence()
for dummy in range(3):
d.addSample(randn(module.indim), randn(module.outdim))
else:
d = SupervisedDataSet(module.indim, module.outdim)
for dummy in range(3):
d.addSample(randn(module.indim), randn(module.outdim))
return d
|
null | null | null | When did dummy function call ?
| def on_loop(notifier, counter):
if (counter.count > 4):
sys.stdout.write('Exit\n')
notifier.stop()
sys.exit(0)
else:
sys.stdout.write(('Loop %d\n' % counter.count))
counter.plusone()
| null | null | null | after each event loop
| codeqa | def on loop notifier counter if counter count > 4 sys stdout write ' Exit\n' notifier stop sys exit 0 else sys stdout write ' Loop%d\n' % counter count counter plusone
| null | null | null | null | Question:
When did dummy function call ?
Code:
def on_loop(notifier, counter):
if (counter.count > 4):
sys.stdout.write('Exit\n')
notifier.stop()
sys.exit(0)
else:
sys.stdout.write(('Loop %d\n' % counter.count))
counter.plusone()
|
null | null | null | What does the code create in the help database ?
| def create_help_entry(key, entrytext, category='General', locks=None, aliases=None):
global _HelpEntry
if (not _HelpEntry):
from evennia.help.models import HelpEntry as _HelpEntry
try:
new_help = _HelpEntry()
new_help.key = key
new_help.entrytext = entrytext
new_help.help_category = category
if locks:
new_help.locks.add(locks)
if aliases:
new_help.aliases.add(aliases)
new_help.save()
return new_help
except IntegrityError:
string = ("Could not add help entry: key '%s' already exists." % key)
logger.log_err(string)
return None
except Exception:
logger.log_trace()
return None
| null | null | null | a static help entry
| codeqa | def create help entry key entrytext category ' General' locks None aliases None global Help Entryif not Help Entry from evennia help models import Help Entry as Help Entrytry new help Help Entry new help key keynew help entrytext entrytextnew help help category categoryif locks new help locks add locks if aliases new help aliases add aliases new help save return new helpexcept Integrity Error string " Couldnotaddhelpentry key'%s'alreadyexists " % key logger log err string return Noneexcept Exception logger log trace return None
| null | null | null | null | Question:
What does the code create in the help database ?
Code:
def create_help_entry(key, entrytext, category='General', locks=None, aliases=None):
global _HelpEntry
if (not _HelpEntry):
from evennia.help.models import HelpEntry as _HelpEntry
try:
new_help = _HelpEntry()
new_help.key = key
new_help.entrytext = entrytext
new_help.help_category = category
if locks:
new_help.locks.add(locks)
if aliases:
new_help.aliases.add(aliases)
new_help.save()
return new_help
except IntegrityError:
string = ("Could not add help entry: key '%s' already exists." % key)
logger.log_err(string)
return None
except Exception:
logger.log_trace()
return None
|
null | null | null | Where does the code create a static help entry ?
| def create_help_entry(key, entrytext, category='General', locks=None, aliases=None):
global _HelpEntry
if (not _HelpEntry):
from evennia.help.models import HelpEntry as _HelpEntry
try:
new_help = _HelpEntry()
new_help.key = key
new_help.entrytext = entrytext
new_help.help_category = category
if locks:
new_help.locks.add(locks)
if aliases:
new_help.aliases.add(aliases)
new_help.save()
return new_help
except IntegrityError:
string = ("Could not add help entry: key '%s' already exists." % key)
logger.log_err(string)
return None
except Exception:
logger.log_trace()
return None
| null | null | null | in the help database
| codeqa | def create help entry key entrytext category ' General' locks None aliases None global Help Entryif not Help Entry from evennia help models import Help Entry as Help Entrytry new help Help Entry new help key keynew help entrytext entrytextnew help help category categoryif locks new help locks add locks if aliases new help aliases add aliases new help save return new helpexcept Integrity Error string " Couldnotaddhelpentry key'%s'alreadyexists " % key logger log err string return Noneexcept Exception logger log trace return None
| null | null | null | null | Question:
Where does the code create a static help entry ?
Code:
def create_help_entry(key, entrytext, category='General', locks=None, aliases=None):
global _HelpEntry
if (not _HelpEntry):
from evennia.help.models import HelpEntry as _HelpEntry
try:
new_help = _HelpEntry()
new_help.key = key
new_help.entrytext = entrytext
new_help.help_category = category
if locks:
new_help.locks.add(locks)
if aliases:
new_help.aliases.add(aliases)
new_help.save()
return new_help
except IntegrityError:
string = ("Could not add help entry: key '%s' already exists." % key)
logger.log_err(string)
return None
except Exception:
logger.log_trace()
return None
|
null | null | null | What does the code create ?
| def _mk_tree():
basedir = tempfile.mkdtemp()
paths = ['BUILD', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS']
for path in paths:
full = os.path.join(basedir, path)
os.makedirs(full)
return basedir
| null | null | null | the rpm build tree
| codeqa | def mk tree basedir tempfile mkdtemp paths ['BUILD' 'RPMS' 'SOURCES' 'SPECS' 'SRPMS']for path in paths full os path join basedir path os makedirs full return basedir
| null | null | null | null | Question:
What does the code create ?
Code:
def _mk_tree():
basedir = tempfile.mkdtemp()
paths = ['BUILD', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS']
for path in paths:
full = os.path.join(basedir, path)
os.makedirs(full)
return basedir
|
null | null | null | What does the code register ?
| def create_application():
return webapp.WSGIApplication([('.*/worker_callback', handlers.MapperWorkerCallbackHandler), ('.*/controller_callback', handlers.ControllerCallbackHandler), ('.*/kickoffjob_callback', handlers.KickOffJobHandler), ('.*/command/start_job', handlers.StartJobHandler), ('.*/command/cleanup_job', handlers.CleanUpJobHandler), ('.*/command/abort_job', handlers.AbortJobHandler), ('.*/command/list_configs', status.ListConfigsHandler), ('.*/command/list_jobs', status.ListJobsHandler), ('.*/command/get_job_detail', status.GetJobDetailHandler), ('/[^/]+(?:/)?', RedirectHandler), ('.+/([a-zA-Z0-9]+(?:\\.(?:css|js))?)', status.ResourceHandler)], debug=True)
| null | null | null | all handlers
| codeqa | def create application return webapp WSGI Application [ ' */worker callback' handlers Mapper Worker Callback Handler ' */controller callback' handlers Controller Callback Handler ' */kickoffjob callback' handlers Kick Off Job Handler ' */command/start job' handlers Start Job Handler ' */command/cleanup job' handlers Clean Up Job Handler ' */command/abort job' handlers Abort Job Handler ' */command/list configs' status List Configs Handler ' */command/list jobs' status List Jobs Handler ' */command/get job detail' status Get Job Detail Handler '/[^/]+ ? / ?' Redirect Handler ' +/ [a-z A-Z 0 - 9 ]+ ? \\ ? css js ? ' status Resource Handler ] debug True
| null | null | null | null | Question:
What does the code register ?
Code:
def create_application():
return webapp.WSGIApplication([('.*/worker_callback', handlers.MapperWorkerCallbackHandler), ('.*/controller_callback', handlers.ControllerCallbackHandler), ('.*/kickoffjob_callback', handlers.KickOffJobHandler), ('.*/command/start_job', handlers.StartJobHandler), ('.*/command/cleanup_job', handlers.CleanUpJobHandler), ('.*/command/abort_job', handlers.AbortJobHandler), ('.*/command/list_configs', status.ListConfigsHandler), ('.*/command/list_jobs', status.ListJobsHandler), ('.*/command/get_job_detail', status.GetJobDetailHandler), ('/[^/]+(?:/)?', RedirectHandler), ('.+/([a-zA-Z0-9]+(?:\\.(?:css|js))?)', status.ResourceHandler)], debug=True)
|
null | null | null | What does the code make ?
| @task
def code_activate(requirements_revision=None):
assert (not is_old_code()), 'Active code is old-style (directory, not symlink). Manual intervention required!'
req_rev = (requirements_revision or hg_revision())
assert code_verify(req_rev), ('Desired code revision %s invalid, cannot be made active' % req_rev)
run(('ln -T -s -f ~/viewfinder.%s ~/viewfinder' % req_rev))
fprint(('Code at revision %s marked active.' % req_rev))
| null | null | null | the code at revision active
| codeqa | @taskdef code activate requirements revision None assert not is old code ' Activecodeisold-style directory notsymlink Manualinterventionrequired 'req rev requirements revision or hg revision assert code verify req rev ' Desiredcoderevision%sinvalid cannotbemadeactive' % req rev run 'ln-T-s-f~/viewfinder %s~/viewfinder' % req rev fprint ' Codeatrevision%smarkedactive ' % req rev
| null | null | null | null | Question:
What does the code make ?
Code:
@task
def code_activate(requirements_revision=None):
assert (not is_old_code()), 'Active code is old-style (directory, not symlink). Manual intervention required!'
req_rev = (requirements_revision or hg_revision())
assert code_verify(req_rev), ('Desired code revision %s invalid, cannot be made active' % req_rev)
run(('ln -T -s -f ~/viewfinder.%s ~/viewfinder' % req_rev))
fprint(('Code at revision %s marked active.' % req_rev))
|
null | null | null | What has a permission ?
| @jinja2.contextfunction
@library.global_function
def has_perm_or_owns(context, perm, obj, perm_obj, field_name='creator'):
user = context['request'].user
if user.is_anonymous():
return False
return access.has_perm_or_owns(user, perm, obj, perm_obj, field_name)
| null | null | null | the user
| codeqa | @jinja 2 contextfunction@library global functiondef has perm or owns context perm obj perm obj field name 'creator' user context['request'] userif user is anonymous return Falsereturn access has perm or owns user perm obj perm obj field name
| null | null | null | null | Question:
What has a permission ?
Code:
@jinja2.contextfunction
@library.global_function
def has_perm_or_owns(context, perm, obj, perm_obj, field_name='creator'):
user = context['request'].user
if user.is_anonymous():
return False
return access.has_perm_or_owns(user, perm, obj, perm_obj, field_name)
|
null | null | null | What does the user own ?
| @jinja2.contextfunction
@library.global_function
def has_perm_or_owns(context, perm, obj, perm_obj, field_name='creator'):
user = context['request'].user
if user.is_anonymous():
return False
return access.has_perm_or_owns(user, perm, obj, perm_obj, field_name)
| null | null | null | the object
| codeqa | @jinja 2 contextfunction@library global functiondef has perm or owns context perm obj perm obj field name 'creator' user context['request'] userif user is anonymous return Falsereturn access has perm or owns user perm obj perm obj field name
| null | null | null | null | Question:
What does the user own ?
Code:
@jinja2.contextfunction
@library.global_function
def has_perm_or_owns(context, perm, obj, perm_obj, field_name='creator'):
user = context['request'].user
if user.is_anonymous():
return False
return access.has_perm_or_owns(user, perm, obj, perm_obj, field_name)
|
null | null | null | What owns the object ?
| @jinja2.contextfunction
@library.global_function
def has_perm_or_owns(context, perm, obj, perm_obj, field_name='creator'):
user = context['request'].user
if user.is_anonymous():
return False
return access.has_perm_or_owns(user, perm, obj, perm_obj, field_name)
| null | null | null | the user
| codeqa | @jinja 2 contextfunction@library global functiondef has perm or owns context perm obj perm obj field name 'creator' user context['request'] userif user is anonymous return Falsereturn access has perm or owns user perm obj perm obj field name
| null | null | null | null | Question:
What owns the object ?
Code:
@jinja2.contextfunction
@library.global_function
def has_perm_or_owns(context, perm, obj, perm_obj, field_name='creator'):
user = context['request'].user
if user.is_anonymous():
return False
return access.has_perm_or_owns(user, perm, obj, perm_obj, field_name)
|
null | null | null | What is calling code ?
| def _is_leading_zero_possible(country_code):
region_code = region_code_for_country_code(country_code)
metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code)
if (metadata is None):
return False
return metadata.leading_zero_possible
| null | null | null | the country
| codeqa | def is leading zero possible country code region code region code for country code country code metadata Phone Metadata metadata for region or calling code country code region code if metadata is None return Falsereturn metadata leading zero possible
| null | null | null | null | Question:
What is calling code ?
Code:
def _is_leading_zero_possible(country_code):
region_code = region_code_for_country_code(country_code)
metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code)
if (metadata is None):
return False
return metadata.leading_zero_possible
|
null | null | null | What could whose national significant number contain ?
| def _is_leading_zero_possible(country_code):
region_code = region_code_for_country_code(country_code)
metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code)
if (metadata is None):
return False
return metadata.leading_zero_possible
| null | null | null | a leading zero
| codeqa | def is leading zero possible country code region code region code for country code country code metadata Phone Metadata metadata for region or calling code country code region code if metadata is None return Falsereturn metadata leading zero possible
| null | null | null | null | Question:
What could whose national significant number contain ?
Code:
def _is_leading_zero_possible(country_code):
region_code = region_code_for_country_code(country_code)
metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code)
if (metadata is None):
return False
return metadata.leading_zero_possible
|
null | null | null | What do the country call ?
| def _is_leading_zero_possible(country_code):
region_code = region_code_for_country_code(country_code)
metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code)
if (metadata is None):
return False
return metadata.leading_zero_possible
| null | null | null | code
| codeqa | def is leading zero possible country code region code region code for country code country code metadata Phone Metadata metadata for region or calling code country code region code if metadata is None return Falsereturn metadata leading zero possible
| null | null | null | null | Question:
What do the country call ?
Code:
def _is_leading_zero_possible(country_code):
region_code = region_code_for_country_code(country_code)
metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code)
if (metadata is None):
return False
return metadata.leading_zero_possible
|
null | null | null | What could contain a leading zero ?
| def _is_leading_zero_possible(country_code):
region_code = region_code_for_country_code(country_code)
metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code)
if (metadata is None):
return False
return metadata.leading_zero_possible
| null | null | null | whose national significant number
| codeqa | def is leading zero possible country code region code region code for country code country code metadata Phone Metadata metadata for region or calling code country code region code if metadata is None return Falsereturn metadata leading zero possible
| null | null | null | null | Question:
What could contain a leading zero ?
Code:
def _is_leading_zero_possible(country_code):
region_code = region_code_for_country_code(country_code)
metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code)
if (metadata is None):
return False
return metadata.leading_zero_possible
|
null | null | null | What does the code get ?
| def getEdgeWidth(elementNode):
if (elementNode == None):
return 0.72
preferences = skeinforge_craft.getCraftPreferences('carve')
layerHeight = skeinforge_craft.getCraftValue('Layer Height', preferences)
layerHeight = getCascadeFloatWithoutSelf(layerHeight, elementNode, 'layerHeight')
edgeWidthOverHeight = skeinforge_craft.getCraftValue('Edge Width over Height', preferences)
edgeWidthOverHeight = getCascadeFloatWithoutSelf(edgeWidthOverHeight, elementNode, 'edgeWidthOverHeight')
return getCascadeFloatWithoutSelf((edgeWidthOverHeight * layerHeight), elementNode, 'edgeWidth')
| null | null | null | the edge width
| codeqa | def get Edge Width element Node if element Node None return 0 72 preferences skeinforge craft get Craft Preferences 'carve' layer Height skeinforge craft get Craft Value ' Layer Height' preferences layer Height get Cascade Float Without Self layer Height element Node 'layer Height' edge Width Over Height skeinforge craft get Craft Value ' Edge Widthover Height' preferences edge Width Over Height get Cascade Float Without Self edge Width Over Height element Node 'edge Width Over Height' return get Cascade Float Without Self edge Width Over Height * layer Height element Node 'edge Width'
| null | null | null | null | Question:
What does the code get ?
Code:
def getEdgeWidth(elementNode):
if (elementNode == None):
return 0.72
preferences = skeinforge_craft.getCraftPreferences('carve')
layerHeight = skeinforge_craft.getCraftValue('Layer Height', preferences)
layerHeight = getCascadeFloatWithoutSelf(layerHeight, elementNode, 'layerHeight')
edgeWidthOverHeight = skeinforge_craft.getCraftValue('Edge Width over Height', preferences)
edgeWidthOverHeight = getCascadeFloatWithoutSelf(edgeWidthOverHeight, elementNode, 'edgeWidthOverHeight')
return getCascadeFloatWithoutSelf((edgeWidthOverHeight * layerHeight), elementNode, 'edgeWidth')
|
null | null | null | What does the code call ?
| def data_spider(path, ignore=(ValueError, NotImplementedError), followlinks=True, hidden=False, extra_kwargs=None):
return {os.path.basename(path): _spider(path, ignore=ignore, followlinks=followlinks, hidden=hidden, extra_kwargs=extra_kwargs)}
| null | null | null | blaze
| codeqa | def data spider path ignore Value Error Not Implemented Error followlinks True hidden False extra kwargs None return {os path basename path spider path ignore ignore followlinks followlinks hidden hidden extra kwargs extra kwargs }
| null | null | null | null | Question:
What does the code call ?
Code:
def data_spider(path, ignore=(ValueError, NotImplementedError), followlinks=True, hidden=False, extra_kwargs=None):
return {os.path.basename(path): _spider(path, ignore=ignore, followlinks=followlinks, hidden=hidden, extra_kwargs=extra_kwargs)}
|
null | null | null | What does the code traverse ?
| def data_spider(path, ignore=(ValueError, NotImplementedError), followlinks=True, hidden=False, extra_kwargs=None):
return {os.path.basename(path): _spider(path, ignore=ignore, followlinks=followlinks, hidden=hidden, extra_kwargs=extra_kwargs)}
| null | null | null | a directory
| codeqa | def data spider path ignore Value Error Not Implemented Error followlinks True hidden False extra kwargs None return {os path basename path spider path ignore ignore followlinks followlinks hidden hidden extra kwargs extra kwargs }
| null | null | null | null | Question:
What does the code traverse ?
Code:
def data_spider(path, ignore=(ValueError, NotImplementedError), followlinks=True, hidden=False, extra_kwargs=None):
return {os.path.basename(path): _spider(path, ignore=ignore, followlinks=followlinks, hidden=hidden, extra_kwargs=extra_kwargs)}
|
null | null | null | What has instance_profile_name argument ?
| def boto_supports_profile_name_arg(ec2):
run_instances_method = getattr(ec2, 'run_instances')
return ('instance_profile_name' in get_function_code(run_instances_method).co_varnames)
| null | null | null | boto library
| codeqa | def boto supports profile name arg ec 2 run instances method getattr ec 2 'run instances' return 'instance profile name' in get function code run instances method co varnames
| null | null | null | null | Question:
What has instance_profile_name argument ?
Code:
def boto_supports_profile_name_arg(ec2):
run_instances_method = getattr(ec2, 'run_instances')
return ('instance_profile_name' in get_function_code(run_instances_method).co_varnames)
|
null | null | null | What does the code do ?
| def post(url, data, api_key=None):
try:
(opener, request) = build_request_with_data(url, data, api_key, 'POST')
post_request = opener.open(request)
return json.loads(post_request.read())
except urllib2.HTTPError as e:
return dict(status='error', message=str(e.read(1024)))
| null | null | null | the post
| codeqa | def post url data api key None try opener request build request with data url data api key 'POST' post request opener open request return json loads post request read except urllib 2 HTTP Error as e return dict status 'error' message str e read 1024
| null | null | null | null | Question:
What does the code do ?
Code:
def post(url, data, api_key=None):
try:
(opener, request) = build_request_with_data(url, data, api_key, 'POST')
post_request = opener.open(request)
return json.loads(post_request.read())
except urllib2.HTTPError as e:
return dict(status='error', message=str(e.read(1024)))
|
null | null | null | What should a feature object have ?
| def test_feature_has_scenarios():
feature = Feature.from_string(FEATURE1)
expect(feature.scenarios).to.be.a(list)
expect(feature.scenarios).to.have.length_of(3)
expected_scenario_names = ['Renting a featured movie', 'Renting a non-featured movie', 'Renting two movies allows client to take one more without charge']
for (scenario, expected_name) in zip(feature.scenarios, expected_scenario_names):
expect(scenario).to.be.a(Scenario)
expect(scenario.name).to.equal(expected_name)
expect(feature.scenarios[1].steps[0].keys).to.equal(('Name', 'Rating', 'New', 'Available'))
expect(list(feature.scenarios[1].steps[0].hashes)).to.equal([{'Name': 'A night at the museum 2', 'Rating': '3 stars', 'New': 'yes', 'Available': '9'}, {'Name': 'Matrix Revolutions', 'Rating': '4 stars', 'New': 'no', 'Available': '6'}])
| null | null | null | a list of scenarios
| codeqa | def test feature has scenarios feature Feature from string FEATURE 1 expect feature scenarios to be a list expect feature scenarios to have length of 3 expected scenario names [' Rentingafeaturedmovie' ' Rentinganon-featuredmovie' ' Rentingtwomoviesallowsclienttotakeonemorewithoutcharge']for scenario expected name in zip feature scenarios expected scenario names expect scenario to be a Scenario expect scenario name to equal expected name expect feature scenarios[ 1 ] steps[ 0 ] keys to equal ' Name' ' Rating' ' New' ' Available' expect list feature scenarios[ 1 ] steps[ 0 ] hashes to equal [{' Name' ' Anightatthemuseum 2 ' ' Rating' '3 stars' ' New' 'yes' ' Available' '9 '} {' Name' ' Matrix Revolutions' ' Rating' '4 stars' ' New' 'no' ' Available' '6 '}]
| null | null | null | null | Question:
What should a feature object have ?
Code:
def test_feature_has_scenarios():
feature = Feature.from_string(FEATURE1)
expect(feature.scenarios).to.be.a(list)
expect(feature.scenarios).to.have.length_of(3)
expected_scenario_names = ['Renting a featured movie', 'Renting a non-featured movie', 'Renting two movies allows client to take one more without charge']
for (scenario, expected_name) in zip(feature.scenarios, expected_scenario_names):
expect(scenario).to.be.a(Scenario)
expect(scenario.name).to.equal(expected_name)
expect(feature.scenarios[1].steps[0].keys).to.equal(('Name', 'Rating', 'New', 'Available'))
expect(list(feature.scenarios[1].steps[0].hashes)).to.equal([{'Name': 'A night at the museum 2', 'Rating': '3 stars', 'New': 'yes', 'Available': '9'}, {'Name': 'Matrix Revolutions', 'Rating': '4 stars', 'New': 'no', 'Available': '6'}])
|
null | null | null | What should have a list of scenarios ?
| def test_feature_has_scenarios():
feature = Feature.from_string(FEATURE1)
expect(feature.scenarios).to.be.a(list)
expect(feature.scenarios).to.have.length_of(3)
expected_scenario_names = ['Renting a featured movie', 'Renting a non-featured movie', 'Renting two movies allows client to take one more without charge']
for (scenario, expected_name) in zip(feature.scenarios, expected_scenario_names):
expect(scenario).to.be.a(Scenario)
expect(scenario.name).to.equal(expected_name)
expect(feature.scenarios[1].steps[0].keys).to.equal(('Name', 'Rating', 'New', 'Available'))
expect(list(feature.scenarios[1].steps[0].hashes)).to.equal([{'Name': 'A night at the museum 2', 'Rating': '3 stars', 'New': 'yes', 'Available': '9'}, {'Name': 'Matrix Revolutions', 'Rating': '4 stars', 'New': 'no', 'Available': '6'}])
| null | null | null | a feature object
| codeqa | def test feature has scenarios feature Feature from string FEATURE 1 expect feature scenarios to be a list expect feature scenarios to have length of 3 expected scenario names [' Rentingafeaturedmovie' ' Rentinganon-featuredmovie' ' Rentingtwomoviesallowsclienttotakeonemorewithoutcharge']for scenario expected name in zip feature scenarios expected scenario names expect scenario to be a Scenario expect scenario name to equal expected name expect feature scenarios[ 1 ] steps[ 0 ] keys to equal ' Name' ' Rating' ' New' ' Available' expect list feature scenarios[ 1 ] steps[ 0 ] hashes to equal [{' Name' ' Anightatthemuseum 2 ' ' Rating' '3 stars' ' New' 'yes' ' Available' '9 '} {' Name' ' Matrix Revolutions' ' Rating' '4 stars' ' New' 'no' ' Available' '6 '}]
| null | null | null | null | Question:
What should have a list of scenarios ?
Code:
def test_feature_has_scenarios():
feature = Feature.from_string(FEATURE1)
expect(feature.scenarios).to.be.a(list)
expect(feature.scenarios).to.have.length_of(3)
expected_scenario_names = ['Renting a featured movie', 'Renting a non-featured movie', 'Renting two movies allows client to take one more without charge']
for (scenario, expected_name) in zip(feature.scenarios, expected_scenario_names):
expect(scenario).to.be.a(Scenario)
expect(scenario.name).to.equal(expected_name)
expect(feature.scenarios[1].steps[0].keys).to.equal(('Name', 'Rating', 'New', 'Available'))
expect(list(feature.scenarios[1].steps[0].hashes)).to.equal([{'Name': 'A night at the museum 2', 'Rating': '3 stars', 'New': 'yes', 'Available': '9'}, {'Name': 'Matrix Revolutions', 'Rating': '4 stars', 'New': 'no', 'Available': '6'}])
|
null | null | null | Where was the python name deprecated ?
| def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
if (format is None):
format = DEPRECATION_WARNING_FORMAT
warningString = (format % {'fqpn': fqpn, 'version': getVersionString(version)})
if replacement:
warningString = ('%s; %s' % (warningString, _getReplacementString(replacement)))
return warningString
| null | null | null | in the given version
| codeqa | def get Deprecation Warning String fqpn version format None replacement None if format is None format DEPRECATION WARNING FORMA Twarning String format % {'fqpn' fqpn 'version' get Version String version } if replacement warning String '%s %s' % warning String get Replacement String replacement return warning String
| null | null | null | null | Question:
Where was the python name deprecated ?
Code:
def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
if (format is None):
format = DEPRECATION_WARNING_FORMAT
warningString = (format % {'fqpn': fqpn, 'version': getVersionString(version)})
if replacement:
warningString = ('%s; %s' % (warningString, _getReplacementString(replacement)))
return warningString
|
null | null | null | What do a string indicate ?
| def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
if (format is None):
format = DEPRECATION_WARNING_FORMAT
warningString = (format % {'fqpn': fqpn, 'version': getVersionString(version)})
if replacement:
warningString = ('%s; %s' % (warningString, _getReplacementString(replacement)))
return warningString
| null | null | null | that the python name was deprecated in the given version
| codeqa | def get Deprecation Warning String fqpn version format None replacement None if format is None format DEPRECATION WARNING FORMA Twarning String format % {'fqpn' fqpn 'version' get Version String version } if replacement warning String '%s %s' % warning String get Replacement String replacement return warning String
| null | null | null | null | Question:
What do a string indicate ?
Code:
def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
if (format is None):
format = DEPRECATION_WARNING_FORMAT
warningString = (format % {'fqpn': fqpn, 'version': getVersionString(version)})
if replacement:
warningString = ('%s; %s' % (warningString, _getReplacementString(replacement)))
return warningString
|
null | null | null | What is indicating that the python name was deprecated in the given version ?
| def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
if (format is None):
format = DEPRECATION_WARNING_FORMAT
warningString = (format % {'fqpn': fqpn, 'version': getVersionString(version)})
if replacement:
warningString = ('%s; %s' % (warningString, _getReplacementString(replacement)))
return warningString
| null | null | null | a string
| codeqa | def get Deprecation Warning String fqpn version format None replacement None if format is None format DEPRECATION WARNING FORMA Twarning String format % {'fqpn' fqpn 'version' get Version String version } if replacement warning String '%s %s' % warning String get Replacement String replacement return warning String
| null | null | null | null | Question:
What is indicating that the python name was deprecated in the given version ?
Code:
def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
if (format is None):
format = DEPRECATION_WARNING_FORMAT
warningString = (format % {'fqpn': fqpn, 'version': getVersionString(version)})
if replacement:
warningString = ('%s; %s' % (warningString, _getReplacementString(replacement)))
return warningString
|
null | null | null | What was deprecated in the given version ?
| def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
if (format is None):
format = DEPRECATION_WARNING_FORMAT
warningString = (format % {'fqpn': fqpn, 'version': getVersionString(version)})
if replacement:
warningString = ('%s; %s' % (warningString, _getReplacementString(replacement)))
return warningString
| null | null | null | the python name
| codeqa | def get Deprecation Warning String fqpn version format None replacement None if format is None format DEPRECATION WARNING FORMA Twarning String format % {'fqpn' fqpn 'version' get Version String version } if replacement warning String '%s %s' % warning String get Replacement String replacement return warning String
| null | null | null | null | Question:
What was deprecated in the given version ?
Code:
def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
if (format is None):
format = DEPRECATION_WARNING_FORMAT
warningString = (format % {'fqpn': fqpn, 'version': getVersionString(version)})
if replacement:
warningString = ('%s; %s' % (warningString, _getReplacementString(replacement)))
return warningString
|
null | null | null | When do check policy correspond to the wrapped methods ?
| def wrap_check_policy(func):
@functools.wraps(func)
def wrapped(self, context, *args, **kwargs):
action = func.__name__
check_policy(context, action)
return func(self, context, *args, **kwargs)
return wrapped
| null | null | null | prior to execution
| codeqa | def wrap check policy func @functools wraps func def wrapped self context *args **kwargs action func name check policy context action return func self context *args **kwargs return wrapped
| null | null | null | null | Question:
When do check policy correspond to the wrapped methods ?
Code:
def wrap_check_policy(func):
@functools.wraps(func)
def wrapped(self, context, *args, **kwargs):
action = func.__name__
check_policy(context, action)
return func(self, context, *args, **kwargs)
return wrapped
|
null | null | null | What does the code decorate ?
| def step(step_func_or_sentence):
if _is_step_sentence(step_func_or_sentence):
return (lambda func: STEP_REGISTRY.load(step_func_or_sentence, func))
else:
return STEP_REGISTRY.load_func(step_func_or_sentence)
| null | null | null | a function
| codeqa | def step step func or sentence if is step sentence step func or sentence return lambda func STEP REGISTRY load step func or sentence func else return STEP REGISTRY load func step func or sentence
| null | null | null | null | Question:
What does the code decorate ?
Code:
def step(step_func_or_sentence):
if _is_step_sentence(step_func_or_sentence):
return (lambda func: STEP_REGISTRY.load(step_func_or_sentence, func))
else:
return STEP_REGISTRY.load_func(step_func_or_sentence)
|
null | null | null | What did the code read ?
| def read_data_list(ofile):
data = [next(ofile)]
if (data[0].strip()[0] == '{'):
raise ValueError('This looks like a sparse ARFF: not supported yet')
data.extend([i for i in ofile])
return data
| null | null | null | each line of the iterable
| codeqa | def read data list ofile data [next ofile ]if data[ 0 ] strip [0 ] '{' raise Value Error ' Thislookslikeasparse ARFF notsupportedyet' data extend [i for i in ofile] return data
| null | null | null | null | Question:
What did the code read ?
Code:
def read_data_list(ofile):
data = [next(ofile)]
if (data[0].strip()[0] == '{'):
raise ValueError('This looks like a sparse ARFF: not supported yet')
data.extend([i for i in ofile])
return data
|
null | null | null | What has views checks ?
| def permission_required(perm, login_url=None):
return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
| null | null | null | whether a user has a particular permission enabled
| codeqa | def permission required perm login url None return user passes test lambda u u has perm perm login url login url
| null | null | null | null | Question:
What has views checks ?
Code:
def permission_required(perm, login_url=None):
return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
|
null | null | null | What does a user have ?
| def permission_required(perm, login_url=None):
return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
| null | null | null | a particular permission enabled
| codeqa | def permission required perm login url None return user passes test lambda u u has perm perm login url login url
| null | null | null | null | Question:
What does a user have ?
Code:
def permission_required(perm, login_url=None):
return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
|
null | null | null | What has checks whether a user has a particular permission enabled ?
| def permission_required(perm, login_url=None):
return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
| null | null | null | views
| codeqa | def permission required perm login url None return user passes test lambda u u has perm perm login url login url
| null | null | null | null | Question:
What has checks whether a user has a particular permission enabled ?
Code:
def permission_required(perm, login_url=None):
return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
|
null | null | null | What has a particular permission enabled ?
| def permission_required(perm, login_url=None):
return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
| null | null | null | a user
| codeqa | def permission required perm login url None return user passes test lambda u u has perm perm login url login url
| null | null | null | null | Question:
What has a particular permission enabled ?
Code:
def permission_required(perm, login_url=None):
return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
|
null | null | null | What did the code build ?
| def build_desired_iface_config(module):
module.custom_desired_config = {'addr_family': None, 'auto': True, 'config': {}, 'name': module.params.get('name')}
for _attr in ['vlan_aware', 'pvid', 'ports', 'stp']:
build_bridge_attr(module, _attr)
build_addr_method(module)
build_address(module)
build_vids(module)
build_alias_name(module)
build_vrr(module)
for _attr in ['mtu', 'mstpctl_treeprio']:
build_generic_attr(module, _attr)
| null | null | null | ifupdown2 compatible hash
| codeqa | def build desired iface config module module custom desired config {'addr family' None 'auto' True 'config' {} 'name' module params get 'name' }for attr in ['vlan aware' 'pvid' 'ports' 'stp'] build bridge attr module attr build addr method module build address module build vids module build alias name module build vrr module for attr in ['mtu' 'mstpctl treeprio'] build generic attr module attr
| null | null | null | null | Question:
What did the code build ?
Code:
def build_desired_iface_config(module):
module.custom_desired_config = {'addr_family': None, 'auto': True, 'config': {}, 'name': module.params.get('name')}
for _attr in ['vlan_aware', 'pvid', 'ports', 'stp']:
build_bridge_attr(module, _attr)
build_addr_method(module)
build_address(module)
build_vids(module)
build_alias_name(module)
build_vrr(module)
for _attr in ['mtu', 'mstpctl_treeprio']:
build_generic_attr(module, _attr)
|
null | null | null | What does the code take ?
| def build_desired_iface_config(module):
module.custom_desired_config = {'addr_family': None, 'auto': True, 'config': {}, 'name': module.params.get('name')}
for _attr in ['vlan_aware', 'pvid', 'ports', 'stp']:
build_bridge_attr(module, _attr)
build_addr_method(module)
build_address(module)
build_vids(module)
build_alias_name(module)
build_vrr(module)
for _attr in ['mtu', 'mstpctl_treeprio']:
build_generic_attr(module, _attr)
| null | null | null | parameters defined
| codeqa | def build desired iface config module module custom desired config {'addr family' None 'auto' True 'config' {} 'name' module params get 'name' }for attr in ['vlan aware' 'pvid' 'ports' 'stp'] build bridge attr module attr build addr method module build address module build vids module build alias name module build vrr module for attr in ['mtu' 'mstpctl treeprio'] build generic attr module attr
| null | null | null | null | Question:
What does the code take ?
Code:
def build_desired_iface_config(module):
module.custom_desired_config = {'addr_family': None, 'auto': True, 'config': {}, 'name': module.params.get('name')}
for _attr in ['vlan_aware', 'pvid', 'ports', 'stp']:
build_bridge_attr(module, _attr)
build_addr_method(module)
build_address(module)
build_vids(module)
build_alias_name(module)
build_vrr(module)
for _attr in ['mtu', 'mstpctl_treeprio']:
build_generic_attr(module, _attr)
|
null | null | null | What does a content type match ?
| def _full_ct_query(action, actor_only=None):
actstream.registry.check(action.actor)
query = _ct_query(action.actor)
if (action.target is not None):
actstream.registry.check(action.target)
query |= _ct_query(action.target, actor_only)
if (action.action_object is not None):
actstream.registry.check(action.action_object)
query |= _ct_query(action.action_object, actor_only)
return query
| null | null | null | an action
| codeqa | def full ct query action actor only None actstream registry check action actor query ct query action actor if action target is not None actstream registry check action target query ct query action target actor only if action action object is not None actstream registry check action action object query ct query action action object actor only return query
| null | null | null | null | Question:
What does a content type match ?
Code:
def _full_ct_query(action, actor_only=None):
actstream.registry.check(action.actor)
query = _ct_query(action.actor)
if (action.target is not None):
actstream.registry.check(action.target)
query |= _ct_query(action.target, actor_only)
if (action.action_object is not None):
actstream.registry.check(action.action_object)
query |= _ct_query(action.action_object, actor_only)
return query
|
null | null | null | What matches an action ?
| def _full_ct_query(action, actor_only=None):
actstream.registry.check(action.actor)
query = _ct_query(action.actor)
if (action.target is not None):
actstream.registry.check(action.target)
query |= _ct_query(action.target, actor_only)
if (action.action_object is not None):
actstream.registry.check(action.action_object)
query |= _ct_query(action.action_object, actor_only)
return query
| null | null | null | a content type
| codeqa | def full ct query action actor only None actstream registry check action actor query ct query action actor if action target is not None actstream registry check action target query ct query action target actor only if action action object is not None actstream registry check action action object query ct query action action object actor only return query
| null | null | null | null | Question:
What matches an action ?
Code:
def _full_ct_query(action, actor_only=None):
actstream.registry.check(action.actor)
query = _ct_query(action.actor)
if (action.target is not None):
actstream.registry.check(action.target)
query |= _ct_query(action.target, actor_only)
if (action.action_object is not None):
actstream.registry.check(action.action_object)
query |= _ct_query(action.action_object, actor_only)
return query
|
null | null | null | What does the code build ?
| def _full_ct_query(action, actor_only=None):
actstream.registry.check(action.actor)
query = _ct_query(action.actor)
if (action.target is not None):
actstream.registry.check(action.target)
query |= _ct_query(action.target, actor_only)
if (action.action_object is not None):
actstream.registry.check(action.action_object)
query |= _ct_query(action.action_object, actor_only)
return query
| null | null | null | a query that matches objects with a content type that matches an action
| codeqa | def full ct query action actor only None actstream registry check action actor query ct query action actor if action target is not None actstream registry check action target query ct query action target actor only if action action object is not None actstream registry check action action object query ct query action action object actor only return query
| null | null | null | null | Question:
What does the code build ?
Code:
def _full_ct_query(action, actor_only=None):
actstream.registry.check(action.actor)
query = _ct_query(action.actor)
if (action.target is not None):
actstream.registry.check(action.target)
query |= _ct_query(action.target, actor_only)
if (action.action_object is not None):
actstream.registry.check(action.action_object)
query |= _ct_query(action.action_object, actor_only)
return query
|
null | null | null | What does the code delete ?
| def delete_draft(db_session, account, draft):
thread = draft.thread
assert draft.is_draft
schedule_action('delete_draft', draft, draft.namespace.id, db_session, nylas_uid=draft.nylas_uid, message_id_header=draft.message_id_header)
db_session.delete(draft)
if (not thread.messages):
db_session.delete(thread)
db_session.commit()
| null | null | null | the given draft
| codeqa | def delete draft db session account draft thread draft threadassert draft is draftschedule action 'delete draft' draft draft namespace id db session nylas uid draft nylas uid message id header draft message id header db session delete draft if not thread messages db session delete thread db session commit
| null | null | null | null | Question:
What does the code delete ?
Code:
def delete_draft(db_session, account, draft):
thread = draft.thread
assert draft.is_draft
schedule_action('delete_draft', draft, draft.namespace.id, db_session, nylas_uid=draft.nylas_uid, message_id_header=draft.message_id_header)
db_session.delete(draft)
if (not thread.messages):
db_session.delete(thread)
db_session.commit()
|
null | null | null | What does the code produce ?
| def literal_column(text, type_=None):
return ColumnClause(text, type_=type_, is_literal=True)
| null | null | null | a : class
| codeqa | def literal column text type None return Column Clause text type type is literal True
| null | null | null | null | Question:
What does the code produce ?
Code:
def literal_column(text, type_=None):
return ColumnClause(text, type_=type_, is_literal=True)
|
null | null | null | What does the code take ?
| def merge(left, right):
result = []
(n, m) = (0, 0)
while ((n < len(left)) and (m < len(right))):
if (left[n] <= right[m]):
result.append(left[n])
n += 1
else:
result.append(right[m])
m += 1
result += left[n:]
result += right[m:]
return result
| null | null | null | two sorted sub lists
| codeqa | def merge left right result [] n m 0 0 while n < len left and m < len right if left[n] < right[m] result append left[n] n + 1else result append right[m] m + 1result + left[n ]result + right[m ]return result
| null | null | null | null | Question:
What does the code take ?
Code:
def merge(left, right):
result = []
(n, m) = (0, 0)
while ((n < len(left)) and (m < len(right))):
if (left[n] <= right[m]):
result.append(left[n])
n += 1
else:
result.append(right[m])
m += 1
result += left[n:]
result += right[m:]
return result
|
null | null | null | What does the code get ?
| def snapshot_get_all_active_by_window(context, begin, end=None, project_id=None):
return IMPL.snapshot_get_all_active_by_window(context, begin, end, project_id)
| null | null | null | all the snapshots inside the window
| codeqa | def snapshot get all active by window context begin end None project id None return IMPL snapshot get all active by window context begin end project id
| null | null | null | null | Question:
What does the code get ?
Code:
def snapshot_get_all_active_by_window(context, begin, end=None, project_id=None):
return IMPL.snapshot_get_all_active_by_window(context, begin, end, project_id)
|
null | null | null | What did the code split from the key ?
| def _parse_key(key):
splt = key.split('\\')
hive = splt.pop(0)
key = '\\'.join(splt)
return (hive, key)
| null | null | null | the hive
| codeqa | def parse key key splt key split '\\' hive splt pop 0 key '\\' join splt return hive key
| null | null | null | null | Question:
What did the code split from the key ?
Code:
def _parse_key(key):
splt = key.split('\\')
hive = splt.pop(0)
key = '\\'.join(splt)
return (hive, key)
|
null | null | null | What does the code remove ?
| def rm(device, minor):
_validate_device(device)
try:
int(minor)
except Exception:
raise CommandExecutionError('Invalid minor number passed to partition.rm')
cmd = 'parted -m -s {0} rm {1}'.format(device, minor)
out = __salt__['cmd.run'](cmd).splitlines()
return out
| null | null | null | the partition with number < minor >
| codeqa | def rm device minor validate device device try int minor except Exception raise Command Execution Error ' Invalidminornumberpassedtopartition rm' cmd 'parted-m-s{ 0 }rm{ 1 }' format device minor out salt ['cmd run'] cmd splitlines return out
| null | null | null | null | Question:
What does the code remove ?
Code:
def rm(device, minor):
_validate_device(device)
try:
int(minor)
except Exception:
raise CommandExecutionError('Invalid minor number passed to partition.rm')
cmd = 'parted -m -s {0} rm {1}'.format(device, minor)
out = __salt__['cmd.run'](cmd).splitlines()
return out
|
null | null | null | For what purpose does a user watch ?
| def _set_up_ready_watcher():
ready_watcher = UserFactory(email='ready@example.com')
ReadyRevisionEvent.notify(ready_watcher)
return ready_watcher
| null | null | null | for revision readiness
| codeqa | def set up ready watcher ready watcher User Factory email 'ready@example com' Ready Revision Event notify ready watcher return ready watcher
| null | null | null | null | Question:
For what purpose does a user watch ?
Code:
def _set_up_ready_watcher():
ready_watcher = UserFactory(email='ready@example.com')
ReadyRevisionEvent.notify(ready_watcher)
return ready_watcher
|
null | null | null | What does the code make ?
| def _set_up_ready_watcher():
ready_watcher = UserFactory(email='ready@example.com')
ReadyRevisionEvent.notify(ready_watcher)
return ready_watcher
| null | null | null | a user who watches for revision readiness
| codeqa | def set up ready watcher ready watcher User Factory email 'ready@example com' Ready Revision Event notify ready watcher return ready watcher
| null | null | null | null | Question:
What does the code make ?
Code:
def _set_up_ready_watcher():
ready_watcher = UserFactory(email='ready@example.com')
ReadyRevisionEvent.notify(ready_watcher)
return ready_watcher
|
null | null | null | How can the configuration of the specified zone be installed on the machine ?
| def verify(zone):
ret = {'status': True}
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(zone=zone))
ret['status'] = (res['retcode'] == 0)
ret['message'] = (res['stdout'] if ret['status'] else res['stderr'])
ret['message'] = ret['message'].replace('zoneadm: ', '')
if (ret['message'] == ''):
del ret['message']
return ret
| null | null | null | safely
| codeqa | def verify zone ret {'status' True}res salt ['cmd run all'] 'zoneadm-z{zone}verify' format zone zone ret['status'] res['retcode'] 0 ret['message'] res['stdout'] if ret['status'] else res['stderr'] ret['message'] ret['message'] replace 'zoneadm ' '' if ret['message'] '' del ret['message']return ret
| null | null | null | null | Question:
How can the configuration of the specified zone be installed on the machine ?
Code:
def verify(zone):
ret = {'status': True}
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(zone=zone))
ret['status'] = (res['retcode'] == 0)
ret['message'] = (res['stdout'] if ret['status'] else res['stderr'])
ret['message'] = ret['message'].replace('zoneadm: ', '')
if (ret['message'] == ''):
del ret['message']
return ret
|
null | null | null | For what purpose do last cache update time update ?
| def setLastRefresh(exList):
cache_db_con = db.DBConnection('cache.db')
cache_db_con.upsert('scene_exceptions_refresh', {'last_refreshed': int(time.mktime(datetime.datetime.today().timetuple()))}, {'list': exList})
| null | null | null | for shows in list
| codeqa | def set Last Refresh ex List cache db con db DB Connection 'cache db' cache db con upsert 'scene exceptions refresh' {'last refreshed' int time mktime datetime datetime today timetuple } {'list' ex List}
| null | null | null | null | Question:
For what purpose do last cache update time update ?
Code:
def setLastRefresh(exList):
cache_db_con = db.DBConnection('cache.db')
cache_db_con.upsert('scene_exceptions_refresh', {'last_refreshed': int(time.mktime(datetime.datetime.today().timetuple()))}, {'list': exList})
|
null | null | null | What does the code make ?
| def _make_c_string(string):
if isinstance(string, bytes):
try:
_utf_8_decode(string, None, True)
return (string + '\x00')
except UnicodeError:
raise InvalidStringData(('strings in documents must be valid UTF-8: %r' % string))
else:
return (_utf_8_encode(string)[0] + '\x00')
| null | null | null | a c string
| codeqa | def make c string string if isinstance string bytes try utf 8 decode string None True return string + '\x 00 ' except Unicode Error raise Invalid String Data 'stringsindocumentsmustbevalid UTF- 8 %r' % string else return utf 8 encode string [0 ] + '\x 00 '
| null | null | null | null | Question:
What does the code make ?
Code:
def _make_c_string(string):
if isinstance(string, bytes):
try:
_utf_8_decode(string, None, True)
return (string + '\x00')
except UnicodeError:
raise InvalidStringData(('strings in documents must be valid UTF-8: %r' % string))
else:
return (_utf_8_encode(string)[0] + '\x00')
|
null | null | null | What does the code add for the model ?
| def loss(logits, labels, batch_size=None):
if (not batch_size):
batch_size = FLAGS.batch_size
sparse_labels = tf.reshape(labels, [batch_size, 1])
indices = tf.reshape(tf.range(batch_size), [batch_size, 1])
concated = tf.concat(1, [indices, sparse_labels])
num_classes = logits[0].get_shape()[(-1)].value
dense_labels = tf.sparse_to_dense(concated, [batch_size, num_classes], 1.0, 0.0)
slim.losses.cross_entropy_loss(logits[0], dense_labels, label_smoothing=0.1, weight=1.0)
slim.losses.cross_entropy_loss(logits[1], dense_labels, label_smoothing=0.1, weight=0.4, scope='aux_loss')
| null | null | null | all losses
| codeqa | def loss logits labels batch size None if not batch size batch size FLAGS batch sizesparse labels tf reshape labels [batch size 1] indices tf reshape tf range batch size [batch size 1] concated tf concat 1 [indices sparse labels] num classes logits[ 0 ] get shape [ -1 ] valuedense labels tf sparse to dense concated [batch size num classes] 1 0 0 0 slim losses cross entropy loss logits[ 0 ] dense labels label smoothing 0 1 weight 1 0 slim losses cross entropy loss logits[ 1 ] dense labels label smoothing 0 1 weight 0 4 scope 'aux loss'
| null | null | null | null | Question:
What does the code add for the model ?
Code:
def loss(logits, labels, batch_size=None):
if (not batch_size):
batch_size = FLAGS.batch_size
sparse_labels = tf.reshape(labels, [batch_size, 1])
indices = tf.reshape(tf.range(batch_size), [batch_size, 1])
concated = tf.concat(1, [indices, sparse_labels])
num_classes = logits[0].get_shape()[(-1)].value
dense_labels = tf.sparse_to_dense(concated, [batch_size, num_classes], 1.0, 0.0)
slim.losses.cross_entropy_loss(logits[0], dense_labels, label_smoothing=0.1, weight=1.0)
slim.losses.cross_entropy_loss(logits[1], dense_labels, label_smoothing=0.1, weight=0.4, scope='aux_loss')
|
null | null | null | What does the code flash depending on if the flash_messages configuration value is set ?
| def do_flash(message, category=None):
if config_value('FLASH_MESSAGES'):
flash(message, category)
| null | null | null | a message
| codeqa | def do flash message category None if config value 'FLASH MESSAGES' flash message category
| null | null | null | null | Question:
What does the code flash depending on if the flash_messages configuration value is set ?
Code:
def do_flash(message, category=None):
if config_value('FLASH_MESSAGES'):
flash(message, category)
|
null | null | null | What does the code get ?
| def service_get_all_bmc_by_host(context, host):
return IMPL.service_get_all_bmc_by_host(context, host)
| null | null | null | all compute services for a given host
| codeqa | def service get all bmc by host context host return IMPL service get all bmc by host context host
| null | null | null | null | Question:
What does the code get ?
Code:
def service_get_all_bmc_by_host(context, host):
return IMPL.service_get_all_bmc_by_host(context, host)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.