labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2
values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4
values | answer stringlengths 2 905 | src stringclasses 3
values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What does the code create ?
| def libvlc_media_new_path(p_instance, path):
f = (_Cfunctions.get('libvlc_media_new_path', None) or _Cfunction('libvlc_media_new_path', ((1,), (1,)), class_result(Media), ctypes.c_void_p, Instance, ctypes.c_char_p))
return f(p_instance, path)
| null | null | null | a media
| codeqa | def libvlc media new path p instance path f Cfunctions get 'libvlc media new path' None or Cfunction 'libvlc media new path' 1 1 class result Media ctypes c void p Instance ctypes c char p return f p instance path
| null | null | null | null | Question:
What does the code create ?
Code:
def libvlc_media_new_path(p_instance, path):
f = (_Cfunctions.get('libvlc_media_new_path', None) or _Cfunction('libvlc_media_new_path', ((1,), (1,)), class_result(Media), ctypes.c_void_p, Instance, ctypes.c_char_p))
return f(p_instance, path)
|
null | null | null | For what purpose does the code add a path based resolver ?
| def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):
Loader.add_path_resolver(tag, path, kind)
Dumper.add_path_resolver(tag, path, kind)
| null | null | null | for the given tag
| codeqa | def add path resolver tag path kind None Loader Loader Dumper Dumper Loader add path resolver tag path kind Dumper add path resolver tag path kind
| null | null | null | null | Question:
For what purpose does the code add a path based resolver ?
Code:
def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):
Loader.add_path_resolver(tag, path, kind)
Dumper.add_path_resolver(tag, path, kind)
|
null | null | null | What does the code add for the given tag ?
| def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):
Loader.add_path_resolver(tag, path, kind)
Dumper.add_path_resolver(tag, path, kind)
| null | null | null | a path based resolver
| codeqa | def add path resolver tag path kind None Loader Loader Dumper Dumper Loader add path resolver tag path kind Dumper add path resolver tag path kind
| null | null | null | null | Question:
What does the code add for the given tag ?
Code:
def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):
Loader.add_path_resolver(tag, path, kind)
Dumper.add_path_resolver(tag, path, kind)
|
null | null | null | What does the code retrieve ?
| def _get_target_host(iscsi_string):
if iscsi_string:
host = iscsi_string.split(':')[0]
if (len(host) > 0):
return host
return CONF.xenserver.target_host
| null | null | null | target host
| codeqa | def get target host iscsi string if iscsi string host iscsi string split ' ' [0 ]if len host > 0 return hostreturn CONF xenserver target host
| null | null | null | null | Question:
What does the code retrieve ?
Code:
def _get_target_host(iscsi_string):
if iscsi_string:
host = iscsi_string.split(':')[0]
if (len(host) > 0):
return host
return CONF.xenserver.target_host
|
null | null | null | How do a password hash ?
| def pbkdf2(password, salt, iterations, digestMod):
hash = password
for i in range(iterations):
hash = hmac.new(salt, hash, digestMod).digest()
return hash
| null | null | null | according to the pbkdf2 specification
| codeqa | def pbkdf 2 password salt iterations digest Mod hash passwordfor i in range iterations hash hmac new salt hash digest Mod digest return hash
| null | null | null | null | Question:
How do a password hash ?
Code:
def pbkdf2(password, salt, iterations, digestMod):
hash = password
for i in range(iterations):
hash = hmac.new(salt, hash, digestMod).digest()
return hash
|
null | null | null | What is indicating whether unit_1 is larger than unit_2 ?
| def is_larger(unit_1, unit_2):
unit_1 = functions.value_for_key(INFORMATION_UNITS, unit_1)
unit_2 = functions.value_for_key(INFORMATION_UNITS, unit_2)
return (ureg.parse_expression(unit_1) > ureg.parse_expression(unit_2))
| null | null | null | a boolean
| codeqa | def is larger unit 1 unit 2 unit 1 functions value for key INFORMATION UNITS unit 1 unit 2 functions value for key INFORMATION UNITS unit 2 return ureg parse expression unit 1 > ureg parse expression unit 2
| null | null | null | null | Question:
What is indicating whether unit_1 is larger than unit_2 ?
Code:
def is_larger(unit_1, unit_2):
unit_1 = functions.value_for_key(INFORMATION_UNITS, unit_1)
unit_2 = functions.value_for_key(INFORMATION_UNITS, unit_2)
return (ureg.parse_expression(unit_1) > ureg.parse_expression(unit_2))
|
null | null | null | What do a boolean indicate ?
| def is_larger(unit_1, unit_2):
unit_1 = functions.value_for_key(INFORMATION_UNITS, unit_1)
unit_2 = functions.value_for_key(INFORMATION_UNITS, unit_2)
return (ureg.parse_expression(unit_1) > ureg.parse_expression(unit_2))
| null | null | null | whether unit_1 is larger than unit_2
| codeqa | def is larger unit 1 unit 2 unit 1 functions value for key INFORMATION UNITS unit 1 unit 2 functions value for key INFORMATION UNITS unit 2 return ureg parse expression unit 1 > ureg parse expression unit 2
| null | null | null | null | Question:
What do a boolean indicate ?
Code:
def is_larger(unit_1, unit_2):
unit_1 = functions.value_for_key(INFORMATION_UNITS, unit_1)
unit_2 = functions.value_for_key(INFORMATION_UNITS, unit_2)
return (ureg.parse_expression(unit_1) > ureg.parse_expression(unit_2))
|
null | null | null | What does the code produce ?
| def fountain(url):
zsock = zcontext.socket(zmq.PUSH)
zsock.bind(url)
words = [w for w in dir(__builtins__) if w.islower()]
while True:
zsock.send(random.choice(words))
time.sleep(0.4)
| null | null | null | a steady stream of words
| codeqa | def fountain url zsock zcontext socket zmq PUSH zsock bind url words [w for w in dir builtins if w islower ]while True zsock send random choice words time sleep 0 4
| null | null | null | null | Question:
What does the code produce ?
Code:
def fountain(url):
zsock = zcontext.socket(zmq.PUSH)
zsock.bind(url)
words = [w for w in dir(__builtins__) if w.islower()]
while True:
zsock.send(random.choice(words))
time.sleep(0.4)
|
null | null | null | How did the code deprecate ?
| def startKeepingErrors():
warnings.warn('log.startKeepingErrors is deprecated since Twisted 2.5', category=DeprecationWarning, stacklevel=2)
global _keepErrors
_keepErrors = 1
| null | null | null | in twisted 2
| codeqa | def start Keeping Errors warnings warn 'log start Keeping Errorsisdeprecatedsince Twisted 2 5' category Deprecation Warning stacklevel 2 global keep Errors keep Errors 1
| null | null | null | null | Question:
How did the code deprecate ?
Code:
def startKeepingErrors():
warnings.warn('log.startKeepingErrors is deprecated since Twisted 2.5', category=DeprecationWarning, stacklevel=2)
global _keepErrors
_keepErrors = 1
|
null | null | null | What do decorator ignore ?
| def skip_on_access_denied(only_if=None):
def decorator(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
try:
return fun(*args, **kwargs)
except psutil.AccessDenied:
if (only_if is not None):
if (not only_if):
raise
msg = ('%r was skipped because it raised AccessDenied' % fun.__name__)
raise unittest.SkipTest(msg)
return wrapper
return decorator
| null | null | null | accessdenied exceptions
| codeqa | def skip on access denied only if None def decorator fun @functools wraps fun def wrapper *args **kwargs try return fun *args **kwargs except psutil Access Denied if only if is not None if not only if raisemsg '%rwasskippedbecauseitraised Access Denied' % fun name raise unittest Skip Test msg return wrapperreturn decorator
| null | null | null | null | Question:
What do decorator ignore ?
Code:
def skip_on_access_denied(only_if=None):
def decorator(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
try:
return fun(*args, **kwargs)
except psutil.AccessDenied:
if (only_if is not None):
if (not only_if):
raise
msg = ('%r was skipped because it raised AccessDenied' % fun.__name__)
raise unittest.SkipTest(msg)
return wrapper
return decorator
|
null | null | null | How did the file name ?
| def readFile(filename, offset, length):
absoffset = abs(offset)
abslength = abs(length)
try:
with open(filename, 'rb') as f:
if (absoffset != offset):
if length:
raise ValueError('BAD_ARGUMENTS')
f.seek(0, 2)
sz = f.tell()
pos = int((sz - absoffset))
if (pos < 0):
pos = 0
f.seek(pos)
data = f.read(absoffset)
else:
if (abslength != length):
raise ValueError('BAD_ARGUMENTS')
if (length == 0):
f.seek(offset)
data = f.read()
else:
f.seek(offset)
data = f.read(length)
except (OSError, IOError):
raise ValueError('FAILED')
return data
| null | null | null | by filename
| codeqa | def read File filename offset length absoffset abs offset abslength abs length try with open filename 'rb' as f if absoffset offset if length raise Value Error 'BAD ARGUMENTS' f seek 0 2 sz f tell pos int sz - absoffset if pos < 0 pos 0f seek pos data f read absoffset else if abslength length raise Value Error 'BAD ARGUMENTS' if length 0 f seek offset data f read else f seek offset data f read length except OS Error IO Error raise Value Error 'FAILED' return data
| null | null | null | null | Question:
How did the file name ?
Code:
def readFile(filename, offset, length):
absoffset = abs(offset)
abslength = abs(length)
try:
with open(filename, 'rb') as f:
if (absoffset != offset):
if length:
raise ValueError('BAD_ARGUMENTS')
f.seek(0, 2)
sz = f.tell()
pos = int((sz - absoffset))
if (pos < 0):
pos = 0
f.seek(pos)
data = f.read(absoffset)
else:
if (abslength != length):
raise ValueError('BAD_ARGUMENTS')
if (length == 0):
f.seek(offset)
data = f.read()
else:
f.seek(offset)
data = f.read(length)
except (OSError, IOError):
raise ValueError('FAILED')
return data
|
null | null | null | What does the code get ?
| def getNewRepository():
return RaftRepository()
| null | null | null | the repository constructor
| codeqa | def get New Repository return Raft Repository
| null | null | null | null | Question:
What does the code get ?
Code:
def getNewRepository():
return RaftRepository()
|
null | null | null | What did the code set ?
| def generic_group_update_db(context, group, host, cluster_name):
group.update({'host': host, 'updated_at': timeutils.utcnow(), 'cluster_name': cluster_name})
group.save()
return group
| null | null | null | the host and the scheduled_at field of a group
| codeqa | def generic group update db context group host cluster name group update {'host' host 'updated at' timeutils utcnow 'cluster name' cluster name} group save return group
| null | null | null | null | Question:
What did the code set ?
Code:
def generic_group_update_db(context, group, host, cluster_name):
group.update({'host': host, 'updated_at': timeutils.utcnow(), 'cluster_name': cluster_name})
group.save()
return group
|
null | null | null | When do position line have ?
| def test_read_twoline_human():
table = '\n+------+----------+\n| Col1 | Col2 |\n+------|----------+\n| 1.2 | "hello" |\n| 2.4 | \'s worlds|\n+------+----------+\n'
dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine, delimiter='+', header_start=1, position_line=0, data_start=3, data_end=(-1))
assert_equal(dat.dtype.names, ('Col1', 'Col2'))
assert_almost_equal(dat[1][0], 2.4)
assert_equal(dat[0][1], '"hello"')
assert_equal(dat[1][1], "'s worlds")
| null | null | null | before the header line
| codeqa | def test read twoline human table '\n+------+----------+\n Col 1 Col 2 \n+------ ----------+\n 1 2 "hello" \n 2 4 \'sworlds \n+------+----------+\n'dat ascii read table Reader ascii Fixed Width Two Line delimiter '+' header start 1 position line 0 data start 3 data end -1 assert equal dat dtype names ' Col 1 ' ' Col 2 ' assert almost equal dat[ 1 ][ 0 ] 2 4 assert equal dat[ 0 ][ 1 ] '"hello"' assert equal dat[ 1 ][ 1 ] "'sworlds"
| null | null | null | null | Question:
When do position line have ?
Code:
def test_read_twoline_human():
table = '\n+------+----------+\n| Col1 | Col2 |\n+------|----------+\n| 1.2 | "hello" |\n| 2.4 | \'s worlds|\n+------+----------+\n'
dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine, delimiter='+', header_start=1, position_line=0, data_start=3, data_end=(-1))
assert_equal(dat.dtype.names, ('Col1', 'Col2'))
assert_almost_equal(dat[1][0], 2.4)
assert_equal(dat[0][1], '"hello"')
assert_equal(dat[1][1], "'s worlds")
|
null | null | null | What does the code make ?
| @pytest.mark.django_db
@pytest.mark.usefixtures('regular_user')
def test_picotable_correctly_sorts_translated_fields(rf, admin_user, regular_user):
populate_if_required()
columns = [Column('id', 'Id', filter_config=Filter(), display=instance_id), Column('name', 'Name', sort_field='translations__name', filter_config=TextFilter(filter_field='translations__name'))]
pico = get_pico(rf, model=Product, columns=columns)
sorted_products = pico.get_data({'perPage': 100, 'page': 1, 'sort': '+name'})
sorted_names = [p['name'] for p in sorted_products['items']]
assert (sorted_names == sorted(sorted_names))
sorted_products = pico.get_data({'perPage': 100, 'page': 1, 'sort': '-name'})
sorted_names = [p['name'] for p in sorted_products['items']]
assert (sorted_names == sorted(sorted_names, reverse=True))
| null | null | null | sure that translated fields
| codeqa | @pytest mark django db@pytest mark usefixtures 'regular user' def test picotable correctly sorts translated fields rf admin user regular user populate if required columns [ Column 'id' ' Id' filter config Filter display instance id Column 'name' ' Name' sort field 'translations name' filter config Text Filter filter field 'translations name' ]pico get pico rf model Product columns columns sorted products pico get data {'per Page' 100 'page' 1 'sort' '+name'} sorted names [p['name'] for p in sorted products['items']]assert sorted names sorted sorted names sorted products pico get data {'per Page' 100 'page' 1 'sort' '-name'} sorted names [p['name'] for p in sorted products['items']]assert sorted names sorted sorted names reverse True
| null | null | null | null | Question:
What does the code make ?
Code:
@pytest.mark.django_db
@pytest.mark.usefixtures('regular_user')
def test_picotable_correctly_sorts_translated_fields(rf, admin_user, regular_user):
populate_if_required()
columns = [Column('id', 'Id', filter_config=Filter(), display=instance_id), Column('name', 'Name', sort_field='translations__name', filter_config=TextFilter(filter_field='translations__name'))]
pico = get_pico(rf, model=Product, columns=columns)
sorted_products = pico.get_data({'perPage': 100, 'page': 1, 'sort': '+name'})
sorted_names = [p['name'] for p in sorted_products['items']]
assert (sorted_names == sorted(sorted_names))
sorted_products = pico.get_data({'perPage': 100, 'page': 1, 'sort': '-name'})
sorted_names = [p['name'] for p in sorted_products['items']]
assert (sorted_names == sorted(sorted_names, reverse=True))
|
null | null | null | What does the code get ?
| def tracks_for_id(track_id):
candidates = [track_for_mbid(track_id)]
candidates.extend(plugins.track_for_id(track_id))
return filter(None, candidates)
| null | null | null | a list of tracks for an i d
| codeqa | def tracks for id track id candidates [track for mbid track id ]candidates extend plugins track for id track id return filter None candidates
| null | null | null | null | Question:
What does the code get ?
Code:
def tracks_for_id(track_id):
candidates = [track_for_mbid(track_id)]
candidates.extend(plugins.track_for_id(track_id))
return filter(None, candidates)
|
null | null | null | What do we coerce to a rule_code ?
| def _maybe_coerce_freq(code):
assert (code is not None)
if isinstance(code, offsets.DateOffset):
code = code.rule_code
return code.upper()
| null | null | null | a code
| codeqa | def maybe coerce freq code assert code is not None if isinstance code offsets Date Offset code code rule codereturn code upper
| null | null | null | null | Question:
What do we coerce to a rule_code ?
Code:
def _maybe_coerce_freq(code):
assert (code is not None)
if isinstance(code, offsets.DateOffset):
code = code.rule_code
return code.upper()
|
null | null | null | What do we uppercase ?
| def _maybe_coerce_freq(code):
assert (code is not None)
if isinstance(code, offsets.DateOffset):
code = code.rule_code
return code.upper()
| null | null | null | it parameters
| codeqa | def maybe coerce freq code assert code is not None if isinstance code offsets Date Offset code code rule codereturn code upper
| null | null | null | null | Question:
What do we uppercase ?
Code:
def _maybe_coerce_freq(code):
assert (code is not None)
if isinstance(code, offsets.DateOffset):
code = code.rule_code
return code.upper()
|
null | null | null | What might we need ?
| def _maybe_coerce_freq(code):
assert (code is not None)
if isinstance(code, offsets.DateOffset):
code = code.rule_code
return code.upper()
| null | null | null | to coerce a code to a rule_code and uppercase it parameters source : string frequency converting from returns string code
| codeqa | def maybe coerce freq code assert code is not None if isinstance code offsets Date Offset code code rule codereturn code upper
| null | null | null | null | Question:
What might we need ?
Code:
def _maybe_coerce_freq(code):
assert (code is not None)
if isinstance(code, offsets.DateOffset):
code = code.rule_code
return code.upper()
|
null | null | null | What does the code write to a file ?
| def create_temp_profile(scan_profile):
scan_profile_file = os.path.join(tempdir, ('%s.pw3af' % uuid4()))
file(scan_profile_file, 'w').write(scan_profile)
return (scan_profile_file, tempdir)
| null | null | null | the scan_profile
| codeqa | def create temp profile scan profile scan profile file os path join tempdir '%s pw 3 af' % uuid 4 file scan profile file 'w' write scan profile return scan profile file tempdir
| null | null | null | null | Question:
What does the code write to a file ?
Code:
def create_temp_profile(scan_profile):
scan_profile_file = os.path.join(tempdir, ('%s.pw3af' % uuid4()))
file(scan_profile_file, 'w').write(scan_profile)
return (scan_profile_file, tempdir)
|
null | null | null | What is containing the item stored in world ?
| def visit_scenario_item(item_key):
url = django_url(reverse('jump_to', kwargs={'course_id': unicode(world.scenario_dict['COURSE'].id), 'location': unicode(world.scenario_dict[item_key].location)}))
world.browser.visit(url)
| null | null | null | the courseware page
| codeqa | def visit scenario item item key url django url reverse 'jump to' kwargs {'course id' unicode world scenario dict['COURSE'] id 'location' unicode world scenario dict[item key] location } world browser visit url
| null | null | null | null | Question:
What is containing the item stored in world ?
Code:
def visit_scenario_item(item_key):
url = django_url(reverse('jump_to', kwargs={'course_id': unicode(world.scenario_dict['COURSE'].id), 'location': unicode(world.scenario_dict[item_key].location)}))
world.browser.visit(url)
|
null | null | null | Where did the item store ?
| def visit_scenario_item(item_key):
url = django_url(reverse('jump_to', kwargs={'course_id': unicode(world.scenario_dict['COURSE'].id), 'location': unicode(world.scenario_dict[item_key].location)}))
world.browser.visit(url)
| null | null | null | in world
| codeqa | def visit scenario item item key url django url reverse 'jump to' kwargs {'course id' unicode world scenario dict['COURSE'] id 'location' unicode world scenario dict[item key] location } world browser visit url
| null | null | null | null | Question:
Where did the item store ?
Code:
def visit_scenario_item(item_key):
url = django_url(reverse('jump_to', kwargs={'course_id': unicode(world.scenario_dict['COURSE'].id), 'location': unicode(world.scenario_dict[item_key].location)}))
world.browser.visit(url)
|
null | null | null | What stored in world ?
| def visit_scenario_item(item_key):
url = django_url(reverse('jump_to', kwargs={'course_id': unicode(world.scenario_dict['COURSE'].id), 'location': unicode(world.scenario_dict[item_key].location)}))
world.browser.visit(url)
| null | null | null | the item
| codeqa | def visit scenario item item key url django url reverse 'jump to' kwargs {'course id' unicode world scenario dict['COURSE'] id 'location' unicode world scenario dict[item key] location } world browser visit url
| null | null | null | null | Question:
What stored in world ?
Code:
def visit_scenario_item(item_key):
url = django_url(reverse('jump_to', kwargs={'course_id': unicode(world.scenario_dict['COURSE'].id), 'location': unicode(world.scenario_dict[item_key].location)}))
world.browser.visit(url)
|
null | null | null | How is user_id formatted ?
| def jwt_get_user_id_from_payload_handler(payload):
warnings.warn('The following will be removed in the future. Use `JWT_PAYLOAD_GET_USERNAME_HANDLER` instead.', DeprecationWarning)
return payload.get('user_id')
| null | null | null | differently
| codeqa | def jwt get user id from payload handler payload warnings warn ' Thefollowingwillberemovedinthefuture Use`JWT PAYLOAD GET USERNAME HANDLER`instead ' Deprecation Warning return payload get 'user id'
| null | null | null | null | Question:
How is user_id formatted ?
Code:
def jwt_get_user_id_from_payload_handler(payload):
warnings.warn('The following will be removed in the future. Use `JWT_PAYLOAD_GET_USERNAME_HANDLER` instead.', DeprecationWarning)
return payload.get('user_id')
|
null | null | null | What does the code convert ?
| def timedelta_to_integral_seconds(delta):
return int(delta.total_seconds())
| null | null | null | a pd
| codeqa | def timedelta to integral seconds delta return int delta total seconds
| null | null | null | null | Question:
What does the code convert ?
Code:
def timedelta_to_integral_seconds(delta):
return int(delta.total_seconds())
|
null | null | null | What does the code find ?
| def FindNextMultiLineCommentStart(lines, lineix):
while (lineix < len(lines)):
if lines[lineix].strip().startswith('/*'):
if (lines[lineix].strip().find('*/', 2) < 0):
return lineix
lineix += 1
return len(lines)
| null | null | null | the beginning marker for a multiline comment
| codeqa | def Find Next Multi Line Comment Start lines lineix while lineix < len lines if lines[lineix] strip startswith '/*' if lines[lineix] strip find '*/' 2 < 0 return lineixlineix + 1return len lines
| null | null | null | null | Question:
What does the code find ?
Code:
def FindNextMultiLineCommentStart(lines, lineix):
while (lineix < len(lines)):
if lines[lineix].strip().startswith('/*'):
if (lines[lineix].strip().find('*/', 2) < 0):
return lineix
lineix += 1
return len(lines)
|
null | null | null | What does the code create ?
| def OpenDocumentPresentation():
doc = OpenDocument('application/vnd.oasis.opendocument.presentation')
doc.presentation = Presentation()
doc.body.addElement(doc.presentation)
return doc
| null | null | null | a presentation document
| codeqa | def Open Document Presentation doc Open Document 'application/vnd oasis opendocument presentation' doc presentation Presentation doc body add Element doc presentation return doc
| null | null | null | null | Question:
What does the code create ?
Code:
def OpenDocumentPresentation():
doc = OpenDocument('application/vnd.oasis.opendocument.presentation')
doc.presentation = Presentation()
doc.body.addElement(doc.presentation)
return doc
|
null | null | null | What does the code activate ?
| @anonymous_csrf
@mobile_template('users/{mobile/}activate.html')
def activate(request, template, activation_key, user_id=None):
activation_key = activation_key.lower()
if user_id:
user = get_object_or_404(User, id=user_id)
else:
user = RegistrationProfile.objects.get_user(activation_key)
if (user and user.is_active):
messages.add_message(request, messages.INFO, _(u'Your account is already activated, log in below.'))
return HttpResponseRedirect(reverse('users.login'))
account = RegistrationProfile.objects.activate_user(activation_key, request)
my_questions = None
form = AuthenticationForm()
if account:
statsd.incr('user.activate')
claim_watches.delay(account)
my_questions = Question.objects.filter(creator=account)
for q in my_questions:
q.created = datetime.now()
q.save(update=True)
return render(request, template, {'account': account, 'questions': my_questions, 'form': form})
| null | null | null | a user account
| codeqa | @anonymous csrf@mobile template 'users/{mobile/}activate html' def activate request template activation key user id None activation key activation key lower if user id user get object or 404 User id user id else user Registration Profile objects get user activation key if user and user is active messages add message request messages INFO u' Youraccountisalreadyactivated loginbelow ' return Http Response Redirect reverse 'users login' account Registration Profile objects activate user activation key request my questions Noneform Authentication Form if account statsd incr 'user activate' claim watches delay account my questions Question objects filter creator account for q in my questions q created datetime now q save update True return render request template {'account' account 'questions' my questions 'form' form}
| null | null | null | null | Question:
What does the code activate ?
Code:
@anonymous_csrf
@mobile_template('users/{mobile/}activate.html')
def activate(request, template, activation_key, user_id=None):
activation_key = activation_key.lower()
if user_id:
user = get_object_or_404(User, id=user_id)
else:
user = RegistrationProfile.objects.get_user(activation_key)
if (user and user.is_active):
messages.add_message(request, messages.INFO, _(u'Your account is already activated, log in below.'))
return HttpResponseRedirect(reverse('users.login'))
account = RegistrationProfile.objects.activate_user(activation_key, request)
my_questions = None
form = AuthenticationForm()
if account:
statsd.incr('user.activate')
claim_watches.delay(account)
my_questions = Question.objects.filter(creator=account)
for q in my_questions:
q.created = datetime.now()
q.save(update=True)
return render(request, template, {'account': account, 'questions': my_questions, 'form': form})
|
null | null | null | For what purpose does an image type handler create dynamically ?
| def image(image_format, doc=None):
@on_valid('image/{0}'.format(image_format))
def image_handler(data, **kwargs):
if hasattr(data, 'read'):
return data
elif hasattr(data, 'save'):
output = stream()
if (introspect.takes_all_arguments(data.save, 'format') or introspect.takes_kwargs(data.save)):
data.save(output, format=image_format.upper())
else:
data.save(output)
output.seek(0)
return output
elif hasattr(data, 'render'):
return data.render()
elif os.path.isfile(data):
return open(data, 'rb')
image_handler.__doc__ = (doc or '{0} formatted image'.format(image_format))
return image_handler
| null | null | null | for the specified image type
| codeqa | def image image format doc None @on valid 'image/{ 0 }' format image format def image handler data **kwargs if hasattr data 'read' return dataelif hasattr data 'save' output stream if introspect takes all arguments data save 'format' or introspect takes kwargs data save data save output format image format upper else data save output output seek 0 return outputelif hasattr data 'render' return data render elif os path isfile data return open data 'rb' image handler doc doc or '{ 0 }formattedimage' format image format return image handler
| null | null | null | null | Question:
For what purpose does an image type handler create dynamically ?
Code:
def image(image_format, doc=None):
@on_valid('image/{0}'.format(image_format))
def image_handler(data, **kwargs):
if hasattr(data, 'read'):
return data
elif hasattr(data, 'save'):
output = stream()
if (introspect.takes_all_arguments(data.save, 'format') or introspect.takes_kwargs(data.save)):
data.save(output, format=image_format.upper())
else:
data.save(output)
output.seek(0)
return output
elif hasattr(data, 'render'):
return data.render()
elif os.path.isfile(data):
return open(data, 'rb')
image_handler.__doc__ = (doc or '{0} formatted image'.format(image_format))
return image_handler
|
null | null | null | How does an image type handler create for the specified image type ?
| def image(image_format, doc=None):
@on_valid('image/{0}'.format(image_format))
def image_handler(data, **kwargs):
if hasattr(data, 'read'):
return data
elif hasattr(data, 'save'):
output = stream()
if (introspect.takes_all_arguments(data.save, 'format') or introspect.takes_kwargs(data.save)):
data.save(output, format=image_format.upper())
else:
data.save(output)
output.seek(0)
return output
elif hasattr(data, 'render'):
return data.render()
elif os.path.isfile(data):
return open(data, 'rb')
image_handler.__doc__ = (doc or '{0} formatted image'.format(image_format))
return image_handler
| null | null | null | dynamically
| codeqa | def image image format doc None @on valid 'image/{ 0 }' format image format def image handler data **kwargs if hasattr data 'read' return dataelif hasattr data 'save' output stream if introspect takes all arguments data save 'format' or introspect takes kwargs data save data save output format image format upper else data save output output seek 0 return outputelif hasattr data 'render' return data render elif os path isfile data return open data 'rb' image handler doc doc or '{ 0 }formattedimage' format image format return image handler
| null | null | null | null | Question:
How does an image type handler create for the specified image type ?
Code:
def image(image_format, doc=None):
@on_valid('image/{0}'.format(image_format))
def image_handler(data, **kwargs):
if hasattr(data, 'read'):
return data
elif hasattr(data, 'save'):
output = stream()
if (introspect.takes_all_arguments(data.save, 'format') or introspect.takes_kwargs(data.save)):
data.save(output, format=image_format.upper())
else:
data.save(output)
output.seek(0)
return output
elif hasattr(data, 'render'):
return data.render()
elif os.path.isfile(data):
return open(data, 'rb')
image_handler.__doc__ = (doc or '{0} formatted image'.format(image_format))
return image_handler
|
null | null | null | What does the code return ?
| def get_pack_group():
return cfg.CONF.content.pack_group
| null | null | null | a name of the group with write permissions to pack directory
| codeqa | def get pack group return cfg CONF content pack group
| null | null | null | null | Question:
What does the code return ?
Code:
def get_pack_group():
return cfg.CONF.content.pack_group
|
null | null | null | When is an error raised ?
| def test_tl_sample_wt_fit():
tl = TomekLinks(random_state=RND_SEED)
assert_raises(RuntimeError, tl.sample, X, Y)
| null | null | null | when sample is called before fitting
| codeqa | def test tl sample wt fit tl Tomek Links random state RND SEED assert raises Runtime Error tl sample X Y
| null | null | null | null | Question:
When is an error raised ?
Code:
def test_tl_sample_wt_fit():
tl = TomekLinks(random_state=RND_SEED)
assert_raises(RuntimeError, tl.sample, X, Y)
|
null | null | null | What loads a template ?
| def load_template(name):
full_fname = os.path.join(os.path.dirname(__file__), u'script_templates', name)
template_file = open(full_fname)
template = Template(template_file.read())
template_file.close()
return template
| null | null | null | from the script_templates directory parameters
| codeqa | def load template name full fname os path join os path dirname file u'script templates' name template file open full fname template Template template file read template file close return template
| null | null | null | null | Question:
What loads a template ?
Code:
def load_template(name):
full_fname = os.path.join(os.path.dirname(__file__), u'script_templates', name)
template_file = open(full_fname)
template = Template(template_file.read())
template_file.close()
return template
|
null | null | null | Where is the raw pillar data available ?
| def raw(key=None):
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
| null | null | null | in the module
| codeqa | def raw key None if key ret pillar get key {} else ret pillar return ret
| null | null | null | null | Question:
Where is the raw pillar data available ?
Code:
def raw(key=None):
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
|
null | null | null | What is available in the module ?
| def raw(key=None):
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
| null | null | null | the raw pillar data
| codeqa | def raw key None if key ret pillar get key {} else ret pillar return ret
| null | null | null | null | Question:
What is available in the module ?
Code:
def raw(key=None):
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
|
null | null | null | How do logarithmic test ?
| def test_logarithmic_small_scale():
line = Line(logarithmic=True)
line.add('_', [(1 + (10 ** 10)), (3 + (10 ** 10)), (2 + (10 ** 10))])
q = line.render_pyquery()
assert (len(q('.y.axis .guides')) == 11)
| null | null | null | with a small range of values
| codeqa | def test logarithmic small scale line Line logarithmic True line add ' ' [ 1 + 10 ** 10 3 + 10 ** 10 2 + 10 ** 10 ] q line render pyquery assert len q ' y axis guides' 11
| null | null | null | null | Question:
How do logarithmic test ?
Code:
def test_logarithmic_small_scale():
line = Line(logarithmic=True)
line.add('_', [(1 + (10 ** 10)), (3 + (10 ** 10)), (2 + (10 ** 10))])
q = line.render_pyquery()
assert (len(q('.y.axis .guides')) == 11)
|
null | null | null | How does text extract from element ?
| def _wrap(element, output, wrapper=u''):
output.append(wrapper)
if element.text:
output.append(_collapse_whitespace(element.text))
for child in element:
_element_to_text(child, output)
output.append(wrapper)
| null | null | null | recursively
| codeqa | def wrap element output wrapper u'' output append wrapper if element text output append collapse whitespace element text for child in element element to text child output output append wrapper
| null | null | null | null | Question:
How does text extract from element ?
Code:
def _wrap(element, output, wrapper=u''):
output.append(wrapper)
if element.text:
output.append(_collapse_whitespace(element.text))
for child in element:
_element_to_text(child, output)
output.append(wrapper)
|
null | null | null | What fails to delete attached ?
| @mock_ec2
def test_igw_delete_attached():
conn = boto.connect_vpc(u'the_key', u'the_secret')
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as cm:
conn.delete_internet_gateway(igw.id)
cm.exception.code.should.equal(u'DependencyViolation')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
| null | null | null | internet gateway
| codeqa | @mock ec 2 def test igw delete attached conn boto connect vpc u'the key' u'the secret' igw conn create internet gateway vpc conn create vpc VPC CIDR conn attach internet gateway igw id vpc id with assert raises EC 2 Response Error as cm conn delete internet gateway igw id cm exception code should equal u' Dependency Violation' cm exception status should equal 400 cm exception request id should not be none
| null | null | null | null | Question:
What fails to delete attached ?
Code:
@mock_ec2
def test_igw_delete_attached():
conn = boto.connect_vpc(u'the_key', u'the_secret')
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as cm:
conn.delete_internet_gateway(igw.id)
cm.exception.code.should.equal(u'DependencyViolation')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
|
null | null | null | What do internet gateway fail ?
| @mock_ec2
def test_igw_delete_attached():
conn = boto.connect_vpc(u'the_key', u'the_secret')
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as cm:
conn.delete_internet_gateway(igw.id)
cm.exception.code.should.equal(u'DependencyViolation')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
| null | null | null | to delete attached
| codeqa | @mock ec 2 def test igw delete attached conn boto connect vpc u'the key' u'the secret' igw conn create internet gateway vpc conn create vpc VPC CIDR conn attach internet gateway igw id vpc id with assert raises EC 2 Response Error as cm conn delete internet gateway igw id cm exception code should equal u' Dependency Violation' cm exception status should equal 400 cm exception request id should not be none
| null | null | null | null | Question:
What do internet gateway fail ?
Code:
@mock_ec2
def test_igw_delete_attached():
conn = boto.connect_vpc(u'the_key', u'the_secret')
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as cm:
conn.delete_internet_gateway(igw.id)
cm.exception.code.should.equal(u'DependencyViolation')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
|
null | null | null | What build fingerprint ?
| @with_device
def fingerprint():
return str(properties.ro.build.fingerprint)
| null | null | null | the device
| codeqa | @with devicedef fingerprint return str properties ro build fingerprint
| null | null | null | null | Question:
What build fingerprint ?
Code:
@with_device
def fingerprint():
return str(properties.ro.build.fingerprint)
|
null | null | null | What does the device build ?
| @with_device
def fingerprint():
return str(properties.ro.build.fingerprint)
| null | null | null | fingerprint
| codeqa | @with devicedef fingerprint return str properties ro build fingerprint
| null | null | null | null | Question:
What does the device build ?
Code:
@with_device
def fingerprint():
return str(properties.ro.build.fingerprint)
|
null | null | null | What does the matrix have ?
| def test_posdef_symmetric3():
data = np.array([[1.0, 1], [1, 1]], dtype=theano.config.floatX)
assert (mv.posdef(data) == 0)
| null | null | null | 0 eigenvalue
| codeqa | def test posdef symmetric 3 data np array [[ 1 0 1] [1 1]] dtype theano config float X assert mv posdef data 0
| null | null | null | null | Question:
What does the matrix have ?
Code:
def test_posdef_symmetric3():
data = np.array([[1.0, 1], [1, 1]], dtype=theano.config.floatX)
assert (mv.posdef(data) == 0)
|
null | null | null | What has 0 eigenvalue ?
| def test_posdef_symmetric3():
data = np.array([[1.0, 1], [1, 1]], dtype=theano.config.floatX)
assert (mv.posdef(data) == 0)
| null | null | null | the matrix
| codeqa | def test posdef symmetric 3 data np array [[ 1 0 1] [1 1]] dtype theano config float X assert mv posdef data 0
| null | null | null | null | Question:
What has 0 eigenvalue ?
Code:
def test_posdef_symmetric3():
data = np.array([[1.0, 1], [1, 1]], dtype=theano.config.floatX)
assert (mv.posdef(data) == 0)
|
null | null | null | What does the code get ?
| def random_port():
sock = socket.socket()
sock.bind(('', 0))
port = sock.getsockname()[1]
sock.close()
return port
| null | null | null | a single random port
| codeqa | def random port sock socket socket sock bind '' 0 port sock getsockname [1 ]sock close return port
| null | null | null | null | Question:
What does the code get ?
Code:
def random_port():
sock = socket.socket()
sock.bind(('', 0))
port = sock.getsockname()[1]
sock.close()
return port
|
null | null | null | How does a : class : handler and : class : formatter instantiate ?
| def install_default_handler():
logger = logging.getLogger('pwnlib')
if (console not in logger.handlers):
logger.addHandler(console)
logger.addHandler(log_file)
logger.setLevel(1)
| null | null | null | install_default_handler
| codeqa | def install default handler logger logging get Logger 'pwnlib' if console not in logger handlers logger add Handler console logger add Handler log file logger set Level 1
| null | null | null | null | Question:
How does a : class : handler and : class : formatter instantiate ?
Code:
def install_default_handler():
logger = logging.getLogger('pwnlib')
if (console not in logger.handlers):
logger.addHandler(console)
logger.addHandler(log_file)
logger.setLevel(1)
|
null | null | null | What does the code create ?
| def _GetChartFactory(chart_class, display_class):
def Inner(*args, **kwargs):
chart = chart_class(*args, **kwargs)
chart.display = display_class(chart)
return chart
return Inner
| null | null | null | a factory method for instantiating charts with displays
| codeqa | def Get Chart Factory chart class display class def Inner *args **kwargs chart chart class *args **kwargs chart display display class chart return chartreturn Inner
| null | null | null | null | Question:
What does the code create ?
Code:
def _GetChartFactory(chart_class, display_class):
def Inner(*args, **kwargs):
chart = chart_class(*args, **kwargs)
chart.display = display_class(chart)
return chart
return Inner
|
null | null | null | How do charts instantiate ?
| def _GetChartFactory(chart_class, display_class):
def Inner(*args, **kwargs):
chart = chart_class(*args, **kwargs)
chart.display = display_class(chart)
return chart
return Inner
| null | null | null | with displays
| codeqa | def Get Chart Factory chart class display class def Inner *args **kwargs chart chart class *args **kwargs chart display display class chart return chartreturn Inner
| null | null | null | null | Question:
How do charts instantiate ?
Code:
def _GetChartFactory(chart_class, display_class):
def Inner(*args, **kwargs):
chart = chart_class(*args, **kwargs)
chart.display = display_class(chart)
return chart
return Inner
|
null | null | null | What is creating it if necessary ?
| def get_hook(name):
return _HOOKS.setdefault(name, Hook())
| null | null | null | the named hook name
| codeqa | def get hook name return HOOKS setdefault name Hook
| null | null | null | null | Question:
What is creating it if necessary ?
Code:
def get_hook(name):
return _HOOKS.setdefault(name, Hook())
|
null | null | null | What does the code return if necessary ?
| def get_hook(name):
return _HOOKS.setdefault(name, Hook())
| null | null | null | the named hook name creating it
| codeqa | def get hook name return HOOKS setdefault name Hook
| null | null | null | null | Question:
What does the code return if necessary ?
Code:
def get_hook(name):
return _HOOKS.setdefault(name, Hook())
|
null | null | null | When is an error raised ?
| def test_smote_sample_wt_fit():
smote = SMOTETomek(random_state=RND_SEED)
assert_raises(RuntimeError, smote.sample, X, Y)
| null | null | null | when sample is called before fitting
| codeqa | def test smote sample wt fit smote SMOTE Tomek random state RND SEED assert raises Runtime Error smote sample X Y
| null | null | null | null | Question:
When is an error raised ?
Code:
def test_smote_sample_wt_fit():
smote = SMOTETomek(random_state=RND_SEED)
assert_raises(RuntimeError, smote.sample, X, Y)
|
null | null | null | What does the code remove from a variable in the make ?
| def trim_var(var, value):
makeconf = _get_makeconf()
old_value = get_var(var)
if (old_value is not None):
__salt__['file.sed'](makeconf, value, '', limit=var)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
| null | null | null | a value
| codeqa | def trim var var value makeconf get makeconf old value get var var if old value is not None salt ['file sed'] makeconf value '' limit var new value get var var return {var {'old' old value 'new' new value}}
| null | null | null | null | Question:
What does the code remove from a variable in the make ?
Code:
def trim_var(var, value):
makeconf = _get_makeconf()
old_value = get_var(var)
if (old_value is not None):
__salt__['file.sed'](makeconf, value, '', limit=var)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
|
null | null | null | What does the code update if it does not exist or not visible ?
| @utils.no_4byte_params
def metadef_namespace_update(context, namespace_id, namespace_dict, session=None):
session = (session or get_session())
return metadef_namespace_api.update(context, namespace_id, namespace_dict, session)
| null | null | null | a namespace
| codeqa | @utils no 4byte paramsdef metadef namespace update context namespace id namespace dict session None session session or get session return metadef namespace api update context namespace id namespace dict session
| null | null | null | null | Question:
What does the code update if it does not exist or not visible ?
Code:
@utils.no_4byte_params
def metadef_namespace_update(context, namespace_id, namespace_dict, session=None):
session = (session or get_session())
return metadef_namespace_api.update(context, namespace_id, namespace_dict, session)
|
null | null | null | What do a string contain ?
| def _parse_periods(pattern):
parts = pattern.split('..', 1)
if (len(parts) == 1):
instant = Period.parse(parts[0])
return (instant, instant)
else:
start = Period.parse(parts[0])
end = Period.parse(parts[1])
return (start, end)
| null | null | null | two dates separated by two dots
| codeqa | def parse periods pattern parts pattern split ' ' 1 if len parts 1 instant Period parse parts[ 0 ] return instant instant else start Period parse parts[ 0 ] end Period parse parts[ 1 ] return start end
| null | null | null | null | Question:
What do a string contain ?
Code:
def _parse_periods(pattern):
parts = pattern.split('..', 1)
if (len(parts) == 1):
instant = Period.parse(parts[0])
return (instant, instant)
else:
start = Period.parse(parts[0])
end = Period.parse(parts[1])
return (start, end)
|
null | null | null | When did object save ?
| def load_pickle(fname):
with get_file_obj(fname, 'rb') as fin:
return cPickle.load(fin)
| null | null | null | previously
| codeqa | def load pickle fname with get file obj fname 'rb' as fin return c Pickle load fin
| null | null | null | null | Question:
When did object save ?
Code:
def load_pickle(fname):
with get_file_obj(fname, 'rb') as fin:
return cPickle.load(fin)
|
null | null | null | What can this method be used ?
| def load_pickle(fname):
with get_file_obj(fname, 'rb') as fin:
return cPickle.load(fin)
| null | null | null | to load * both * models and results
| codeqa | def load pickle fname with get file obj fname 'rb' as fin return c Pickle load fin
| null | null | null | null | Question:
What can this method be used ?
Code:
def load_pickle(fname):
with get_file_obj(fname, 'rb') as fin:
return cPickle.load(fin)
|
null | null | null | What does the code look by email ?
| def user(email):
return User.objects.get(email=email)
| null | null | null | a user
| codeqa | def user email return User objects get email email
| null | null | null | null | Question:
What does the code look by email ?
Code:
def user(email):
return User.objects.get(email=email)
|
null | null | null | What does the code remove ?
| def remove(path):
path = os.path.expanduser(path)
if (not os.path.isabs(path)):
raise SaltInvocationError('File path must be absolute: {0}'.format(path))
try:
if (os.path.isfile(path) or os.path.islink(path)):
os.remove(path)
return True
elif os.path.isdir(path):
shutil.rmtree(path)
return True
except (OSError, IOError) as exc:
raise CommandExecutionError("Could not remove '{0}': {1}".format(path, exc))
return False
| null | null | null | the named file
| codeqa | def remove path path os path expanduser path if not os path isabs path raise Salt Invocation Error ' Filepathmustbeabsolute {0 }' format path try if os path isfile path or os path islink path os remove path return Trueelif os path isdir path shutil rmtree path return Trueexcept OS Error IO Error as exc raise Command Execution Error " Couldnotremove'{ 0 }' {1 }" format path exc return False
| null | null | null | null | Question:
What does the code remove ?
Code:
def remove(path):
path = os.path.expanduser(path)
if (not os.path.isabs(path)):
raise SaltInvocationError('File path must be absolute: {0}'.format(path))
try:
if (os.path.isfile(path) or os.path.islink(path)):
os.remove(path)
return True
elif os.path.isdir(path):
shutil.rmtree(path)
return True
except (OSError, IOError) as exc:
raise CommandExecutionError("Could not remove '{0}': {1}".format(path, exc))
return False
|
null | null | null | What does the code stop by power off ?
| def powered_off(name):
return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off')
| null | null | null | a vm
| codeqa | def powered off name return virt call name 'stop' 'unpowered' ' Machinehasbeenpoweredoff'
| null | null | null | null | Question:
What does the code stop by power off ?
Code:
def powered_off(name):
return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off')
|
null | null | null | How does the code stop a vm ?
| def powered_off(name):
return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off')
| null | null | null | by power off
| codeqa | def powered off name return virt call name 'stop' 'unpowered' ' Machinehasbeenpoweredoff'
| null | null | null | null | Question:
How does the code stop a vm ?
Code:
def powered_off(name):
return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off')
|
null | null | null | What does the code get ?
| def _get_skiprows(skiprows):
if isinstance(skiprows, slice):
return lrange((skiprows.start or 0), skiprows.stop, (skiprows.step or 1))
elif (isinstance(skiprows, numbers.Integral) or is_list_like(skiprows)):
return skiprows
elif (skiprows is None):
return 0
raise TypeError(('%r is not a valid type for skipping rows' % type(skiprows).__name__))
| null | null | null | an iterator given an integer
| codeqa | def get skiprows skiprows if isinstance skiprows slice return lrange skiprows start or 0 skiprows stop skiprows step or 1 elif isinstance skiprows numbers Integral or is list like skiprows return skiprowselif skiprows is None return 0raise Type Error '%risnotavalidtypeforskippingrows' % type skiprows name
| null | null | null | null | Question:
What does the code get ?
Code:
def _get_skiprows(skiprows):
if isinstance(skiprows, slice):
return lrange((skiprows.start or 0), skiprows.stop, (skiprows.step or 1))
elif (isinstance(skiprows, numbers.Integral) or is_list_like(skiprows)):
return skiprows
elif (skiprows is None):
return 0
raise TypeError(('%r is not a valid type for skipping rows' % type(skiprows).__name__))
|
null | null | null | For what purpose do buffer cache drop ?
| def drop_buffer_cache(fd, offset, length):
global _posix_fadvise
if (_posix_fadvise is None):
_posix_fadvise = load_libc_function('posix_fadvise64')
ret = _posix_fadvise(fd, ctypes.c_uint64(offset), ctypes.c_uint64(length), 4)
if (ret != 0):
logging.warn(('posix_fadvise64(%s, %s, %s, 4) -> %s' % (fd, offset, length, ret)))
| null | null | null | for the given range of the given file
| codeqa | def drop buffer cache fd offset length global posix fadviseif posix fadvise is None posix fadvise load libc function 'posix fadvise 64 ' ret posix fadvise fd ctypes c uint 64 offset ctypes c uint 64 length 4 if ret 0 logging warn 'posix fadvise 64 %s %s %s 4 ->%s' % fd offset length ret
| null | null | null | null | Question:
For what purpose do buffer cache drop ?
Code:
def drop_buffer_cache(fd, offset, length):
global _posix_fadvise
if (_posix_fadvise is None):
_posix_fadvise = load_libc_function('posix_fadvise64')
ret = _posix_fadvise(fd, ctypes.c_uint64(offset), ctypes.c_uint64(length), 4)
if (ret != 0):
logging.warn(('posix_fadvise64(%s, %s, %s, 4) -> %s' % (fd, offset, length, ret)))
|
null | null | null | What does the code get ?
| def get_tag_mode(view, tag_mode_config):
default_mode = None
syntax = view.settings().get('syntax')
language = (splitext(basename(syntax))[0].lower() if (syntax is not None) else 'plain text')
if isinstance(tag_mode_config, list):
for item in tag_mode_config:
if (isinstance(item, dict) and compare_languge(language, item.get('syntax', []))):
first_line = item.get('first_line', '')
if first_line:
size = (view.size() - 1)
if (size > 256):
size = 256
if (isinstance(first_line, str) and bre.compile_search(first_line, bre.I).match(view.substr(sublime.Region(0, size)))):
return item.get('mode', default_mode)
else:
return item.get('mode', default_mode)
return default_mode
| null | null | null | the tag mode
| codeqa | def get tag mode view tag mode config default mode Nonesyntax view settings get 'syntax' language splitext basename syntax [0 ] lower if syntax is not None else 'plaintext' if isinstance tag mode config list for item in tag mode config if isinstance item dict and compare languge language item get 'syntax' [] first line item get 'first line' '' if first line size view size - 1 if size > 256 size 256 if isinstance first line str and bre compile search first line bre I match view substr sublime Region 0 size return item get 'mode' default mode else return item get 'mode' default mode return default mode
| null | null | null | null | Question:
What does the code get ?
Code:
def get_tag_mode(view, tag_mode_config):
default_mode = None
syntax = view.settings().get('syntax')
language = (splitext(basename(syntax))[0].lower() if (syntax is not None) else 'plain text')
if isinstance(tag_mode_config, list):
for item in tag_mode_config:
if (isinstance(item, dict) and compare_languge(language, item.get('syntax', []))):
first_line = item.get('first_line', '')
if first_line:
size = (view.size() - 1)
if (size > 256):
size = 256
if (isinstance(first_line, str) and bre.compile_search(first_line, bre.I).match(view.substr(sublime.Region(0, size)))):
return item.get('mode', default_mode)
else:
return item.get('mode', default_mode)
return default_mode
|
null | null | null | For what purpose does all the child entries delete ?
| def _image_child_entry_delete_all(child_model_cls, image_id, delete_time=None, session=None):
session = (session or get_session())
query = session.query(child_model_cls).filter_by(image_id=image_id).filter_by(deleted=False)
delete_time = (delete_time or timeutils.utcnow())
count = query.update({'deleted': True, 'deleted_at': delete_time})
return count
| null | null | null | for the given image i d
| codeqa | def image child entry delete all child model cls image id delete time None session None session session or get session query session query child model cls filter by image id image id filter by deleted False delete time delete time or timeutils utcnow count query update {'deleted' True 'deleted at' delete time} return count
| null | null | null | null | Question:
For what purpose does all the child entries delete ?
Code:
def _image_child_entry_delete_all(child_model_cls, image_id, delete_time=None, session=None):
session = (session or get_session())
query = session.query(child_model_cls).filter_by(image_id=image_id).filter_by(deleted=False)
delete_time = (delete_time or timeutils.utcnow())
count = query.update({'deleted': True, 'deleted_at': delete_time})
return count
|
null | null | null | What did the code set ?
| @frappe.whitelist()
def set_indicator(board_name, column_name, indicator):
board = frappe.get_doc(u'Kanban Board', board_name)
for column in board.columns:
if (column.column_name == column_name):
column.indicator = indicator
board.save()
return board
| null | null | null | the indicator color of column
| codeqa | @frappe whitelist def set indicator board name column name indicator board frappe get doc u' Kanban Board' board name for column in board columns if column column name column name column indicator indicatorboard save return board
| null | null | null | null | Question:
What did the code set ?
Code:
@frappe.whitelist()
def set_indicator(board_name, column_name, indicator):
board = frappe.get_doc(u'Kanban Board', board_name)
for column in board.columns:
if (column.column_name == column_name):
column.indicator = indicator
board.save()
return board
|
null | null | null | When has the action field been rendered on the page ?
| def filer_actions(context):
context[u'action_index'] = (context.get(u'action_index', (-1)) + 1)
return context
| null | null | null | the number of times
| codeqa | def filer actions context context[u'action index'] context get u'action index' -1 + 1 return context
| null | null | null | null | Question:
When has the action field been rendered on the page ?
Code:
def filer_actions(context):
context[u'action_index'] = (context.get(u'action_index', (-1)) + 1)
return context
|
null | null | null | What has been rendered on the page ?
| def filer_actions(context):
context[u'action_index'] = (context.get(u'action_index', (-1)) + 1)
return context
| null | null | null | the action field
| codeqa | def filer actions context context[u'action index'] context get u'action index' -1 + 1 return context
| null | null | null | null | Question:
What has been rendered on the page ?
Code:
def filer_actions(context):
context[u'action_index'] = (context.get(u'action_index', (-1)) + 1)
return context
|
null | null | null | Where has the action field been rendered the number of times ?
| def filer_actions(context):
context[u'action_index'] = (context.get(u'action_index', (-1)) + 1)
return context
| null | null | null | on the page
| codeqa | def filer actions context context[u'action index'] context get u'action index' -1 + 1 return context
| null | null | null | null | Question:
Where has the action field been rendered the number of times ?
Code:
def filer_actions(context):
context[u'action_index'] = (context.get(u'action_index', (-1)) + 1)
return context
|
null | null | null | What does the code track ?
| def filer_actions(context):
context[u'action_index'] = (context.get(u'action_index', (-1)) + 1)
return context
| null | null | null | the number of times the action field has been rendered on the page
| codeqa | def filer actions context context[u'action index'] context get u'action index' -1 + 1 return context
| null | null | null | null | Question:
What does the code track ?
Code:
def filer_actions(context):
context[u'action_index'] = (context.get(u'action_index', (-1)) + 1)
return context
|
null | null | null | What does the code get ?
| def snapshot_get_all(context):
return IMPL.snapshot_get_all(context)
| null | null | null | all snapshots
| codeqa | def snapshot get all context return IMPL snapshot get all context
| null | null | null | null | Question:
What does the code get ?
Code:
def snapshot_get_all(context):
return IMPL.snapshot_get_all(context)
|
null | null | null | What does the code create ?
| def interface_decorator(decorator_name, interface, method_decorator, *args, **kwargs):
for method_name in interface.names():
if (not isinstance(interface[method_name], Method)):
raise TypeError('{} does not support interfaces with non-methods attributes'.format(decorator_name))
def class_decorator(cls):
for name in interface.names():
setattr(cls, name, method_decorator(name, *args, **kwargs))
return cls
return class_decorator
| null | null | null | a class decorator which applies a method decorator to each method of an interface
| codeqa | def interface decorator decorator name interface method decorator *args **kwargs for method name in interface names if not isinstance interface[method name] Method raise Type Error '{}doesnotsupportinterfaceswithnon-methodsattributes' format decorator name def class decorator cls for name in interface names setattr cls name method decorator name *args **kwargs return clsreturn class decorator
| null | null | null | null | Question:
What does the code create ?
Code:
def interface_decorator(decorator_name, interface, method_decorator, *args, **kwargs):
for method_name in interface.names():
if (not isinstance(interface[method_name], Method)):
raise TypeError('{} does not support interfaces with non-methods attributes'.format(decorator_name))
def class_decorator(cls):
for name in interface.names():
setattr(cls, name, method_decorator(name, *args, **kwargs))
return cls
return class_decorator
|
null | null | null | What applies a method decorator to each method of an interface ?
| def interface_decorator(decorator_name, interface, method_decorator, *args, **kwargs):
for method_name in interface.names():
if (not isinstance(interface[method_name], Method)):
raise TypeError('{} does not support interfaces with non-methods attributes'.format(decorator_name))
def class_decorator(cls):
for name in interface.names():
setattr(cls, name, method_decorator(name, *args, **kwargs))
return cls
return class_decorator
| null | null | null | a class decorator
| codeqa | def interface decorator decorator name interface method decorator *args **kwargs for method name in interface names if not isinstance interface[method name] Method raise Type Error '{}doesnotsupportinterfaceswithnon-methodsattributes' format decorator name def class decorator cls for name in interface names setattr cls name method decorator name *args **kwargs return clsreturn class decorator
| null | null | null | null | Question:
What applies a method decorator to each method of an interface ?
Code:
def interface_decorator(decorator_name, interface, method_decorator, *args, **kwargs):
for method_name in interface.names():
if (not isinstance(interface[method_name], Method)):
raise TypeError('{} does not support interfaces with non-methods attributes'.format(decorator_name))
def class_decorator(cls):
for name in interface.names():
setattr(cls, name, method_decorator(name, *args, **kwargs))
return cls
return class_decorator
|
null | null | null | What does a class decorator apply to each method of an interface ?
| def interface_decorator(decorator_name, interface, method_decorator, *args, **kwargs):
for method_name in interface.names():
if (not isinstance(interface[method_name], Method)):
raise TypeError('{} does not support interfaces with non-methods attributes'.format(decorator_name))
def class_decorator(cls):
for name in interface.names():
setattr(cls, name, method_decorator(name, *args, **kwargs))
return cls
return class_decorator
| null | null | null | a method decorator
| codeqa | def interface decorator decorator name interface method decorator *args **kwargs for method name in interface names if not isinstance interface[method name] Method raise Type Error '{}doesnotsupportinterfaceswithnon-methodsattributes' format decorator name def class decorator cls for name in interface names setattr cls name method decorator name *args **kwargs return clsreturn class decorator
| null | null | null | null | Question:
What does a class decorator apply to each method of an interface ?
Code:
def interface_decorator(decorator_name, interface, method_decorator, *args, **kwargs):
for method_name in interface.names():
if (not isinstance(interface[method_name], Method)):
raise TypeError('{} does not support interfaces with non-methods attributes'.format(decorator_name))
def class_decorator(cls):
for name in interface.names():
setattr(cls, name, method_decorator(name, *args, **kwargs))
return cls
return class_decorator
|
null | null | null | What does the code find ?
| def find_root(node):
while (node.type != syms.file_input):
assert node.parent, 'Tree is insane! root found before file_input node was found.'
node = node.parent
return node
| null | null | null | the top level namespace
| codeqa | def find root node while node type syms file input assert node parent ' Treeisinsane rootfoundbeforefile inputnodewasfound 'node node parentreturn node
| null | null | null | null | Question:
What does the code find ?
Code:
def find_root(node):
while (node.type != syms.file_input):
assert node.parent, 'Tree is insane! root found before file_input node was found.'
node = node.parent
return node
|
null | null | null | What does the code provide ?
| def _section_cohort_management(course, access):
course_key = course.id
ccx_enabled = hasattr(course_key, 'ccx')
section_data = {'section_key': 'cohort_management', 'section_display_name': _('Cohorts'), 'access': access, 'ccx_is_enabled': ccx_enabled, 'course_cohort_settings_url': reverse('course_cohort_settings', kwargs={'course_key_string': unicode(course_key)}), 'cohorts_url': reverse('cohorts', kwargs={'course_key_string': unicode(course_key)}), 'upload_cohorts_csv_url': reverse('add_users_to_cohorts', kwargs={'course_id': unicode(course_key)}), 'discussion_topics_url': reverse('cohort_discussion_topics', kwargs={'course_key_string': unicode(course_key)}), 'verified_track_cohorting_url': reverse('verified_track_cohorting', kwargs={'course_key_string': unicode(course_key)})}
return section_data
| null | null | null | data for the corresponding cohort management section
| codeqa | def section cohort management course access course key course idccx enabled hasattr course key 'ccx' section data {'section key' 'cohort management' 'section display name' ' Cohorts' 'access' access 'ccx is enabled' ccx enabled 'course cohort settings url' reverse 'course cohort settings' kwargs {'course key string' unicode course key } 'cohorts url' reverse 'cohorts' kwargs {'course key string' unicode course key } 'upload cohorts csv url' reverse 'add users to cohorts' kwargs {'course id' unicode course key } 'discussion topics url' reverse 'cohort discussion topics' kwargs {'course key string' unicode course key } 'verified track cohorting url' reverse 'verified track cohorting' kwargs {'course key string' unicode course key } }return section data
| null | null | null | null | Question:
What does the code provide ?
Code:
def _section_cohort_management(course, access):
course_key = course.id
ccx_enabled = hasattr(course_key, 'ccx')
section_data = {'section_key': 'cohort_management', 'section_display_name': _('Cohorts'), 'access': access, 'ccx_is_enabled': ccx_enabled, 'course_cohort_settings_url': reverse('course_cohort_settings', kwargs={'course_key_string': unicode(course_key)}), 'cohorts_url': reverse('cohorts', kwargs={'course_key_string': unicode(course_key)}), 'upload_cohorts_csv_url': reverse('add_users_to_cohorts', kwargs={'course_id': unicode(course_key)}), 'discussion_topics_url': reverse('cohort_discussion_topics', kwargs={'course_key_string': unicode(course_key)}), 'verified_track_cohorting_url': reverse('verified_track_cohorting', kwargs={'course_key_string': unicode(course_key)})}
return section_data
|
null | null | null | In which direction do files copy to another ?
| def copy(source, destination, recursive):
if ('s3://' in [source[:5], destination[:5]]):
cp_args = ['aws', 's3', 'cp', source, destination, '--quiet']
if recursive:
cp_args.append('--recursive')
subprocess.check_call(cp_args)
return
if recursive:
shutil.copytree(source, destination)
else:
shutil.copy(source, destination)
| null | null | null | from one location
| codeqa | def copy source destination recursive if 's 3 //' in [source[ 5] destination[ 5]] cp args ['aws' 's 3 ' 'cp' source destination '--quiet']if recursive cp args append '--recursive' subprocess check call cp args returnif recursive shutil copytree source destination else shutil copy source destination
| null | null | null | null | Question:
In which direction do files copy to another ?
Code:
def copy(source, destination, recursive):
if ('s3://' in [source[:5], destination[:5]]):
cp_args = ['aws', 's3', 'cp', source, destination, '--quiet']
if recursive:
cp_args.append('--recursive')
subprocess.check_call(cp_args)
return
if recursive:
shutil.copytree(source, destination)
else:
shutil.copy(source, destination)
|
null | null | null | What should filters receive only ?
| def stringfilter(func):
def _dec(*args, **kwargs):
if args:
args = list(args)
args[0] = force_unicode(args[0])
if (isinstance(args[0], SafeData) and getattr(func, 'is_safe', False)):
return mark_safe(func(*args, **kwargs))
return func(*args, **kwargs)
_dec._decorated_function = getattr(func, '_decorated_function', func)
for attr in ('is_safe', 'needs_autoescape'):
if hasattr(func, attr):
setattr(_dec, attr, getattr(func, attr))
return wraps(func)(_dec)
| null | null | null | unicode objects
| codeqa | def stringfilter func def dec *args **kwargs if args args list args args[ 0 ] force unicode args[ 0 ] if isinstance args[ 0 ] Safe Data and getattr func 'is safe' False return mark safe func *args **kwargs return func *args **kwargs dec decorated function getattr func ' decorated function' func for attr in 'is safe' 'needs autoescape' if hasattr func attr setattr dec attr getattr func attr return wraps func dec
| null | null | null | null | Question:
What should filters receive only ?
Code:
def stringfilter(func):
def _dec(*args, **kwargs):
if args:
args = list(args)
args[0] = force_unicode(args[0])
if (isinstance(args[0], SafeData) and getattr(func, 'is_safe', False)):
return mark_safe(func(*args, **kwargs))
return func(*args, **kwargs)
_dec._decorated_function = getattr(func, '_decorated_function', func)
for attr in ('is_safe', 'needs_autoescape'):
if hasattr(func, attr):
setattr(_dec, attr, getattr(func, attr))
return wraps(func)(_dec)
|
null | null | null | What do factory create ?
| def make_step_decorator(context, instance, update_instance_progress, total_offset=0):
step_info = dict(total=total_offset, current=0)
def bump_progress():
step_info['current'] += 1
update_instance_progress(context, instance, step_info['current'], step_info['total'])
def step_decorator(f):
step_info['total'] += 1
@functools.wraps(f)
def inner(*args, **kwargs):
rv = f(*args, **kwargs)
bump_progress()
return rv
return inner
return step_decorator
| null | null | null | a decorator that records instance progress as a series of discrete steps
| codeqa | def make step decorator context instance update instance progress total offset 0 step info dict total total offset current 0 def bump progress step info['current'] + 1update instance progress context instance step info['current'] step info['total'] def step decorator f step info['total'] + 1@functools wraps f def inner *args **kwargs rv f *args **kwargs bump progress return rvreturn innerreturn step decorator
| null | null | null | null | Question:
What do factory create ?
Code:
def make_step_decorator(context, instance, update_instance_progress, total_offset=0):
step_info = dict(total=total_offset, current=0)
def bump_progress():
step_info['current'] += 1
update_instance_progress(context, instance, step_info['current'], step_info['total'])
def step_decorator(f):
step_info['total'] += 1
@functools.wraps(f)
def inner(*args, **kwargs):
rv = f(*args, **kwargs)
bump_progress()
return rv
return inner
return step_decorator
|
null | null | null | What creates a decorator that records instance progress as a series of discrete steps ?
| def make_step_decorator(context, instance, update_instance_progress, total_offset=0):
step_info = dict(total=total_offset, current=0)
def bump_progress():
step_info['current'] += 1
update_instance_progress(context, instance, step_info['current'], step_info['total'])
def step_decorator(f):
step_info['total'] += 1
@functools.wraps(f)
def inner(*args, **kwargs):
rv = f(*args, **kwargs)
bump_progress()
return rv
return inner
return step_decorator
| null | null | null | factory
| codeqa | def make step decorator context instance update instance progress total offset 0 step info dict total total offset current 0 def bump progress step info['current'] + 1update instance progress context instance step info['current'] step info['total'] def step decorator f step info['total'] + 1@functools wraps f def inner *args **kwargs rv f *args **kwargs bump progress return rvreturn innerreturn step decorator
| null | null | null | null | Question:
What creates a decorator that records instance progress as a series of discrete steps ?
Code:
def make_step_decorator(context, instance, update_instance_progress, total_offset=0):
step_info = dict(total=total_offset, current=0)
def bump_progress():
step_info['current'] += 1
update_instance_progress(context, instance, step_info['current'], step_info['total'])
def step_decorator(f):
step_info['total'] += 1
@functools.wraps(f)
def inner(*args, **kwargs):
rv = f(*args, **kwargs)
bump_progress()
return rv
return inner
return step_decorator
|
null | null | null | For what purpose does the code convert a parameter ?
| def _tofloat(value):
if isiterable(value):
try:
value = np.array(value, dtype=np.float)
except (TypeError, ValueError):
raise InputParameterError(u'Parameter of {0} could not be converted to float'.format(type(value)))
elif isinstance(value, np.ndarray):
value = float(value.item())
elif isinstance(value, (numbers.Number, np.number)):
value = float(value)
elif isinstance(value, bool):
raise InputParameterError(u'Expected parameter to be of numerical type, not boolean')
else:
raise InputParameterError(u"Don't know how to convert parameter of {0} to float".format(type(value)))
return value
| null | null | null | to float or float array
| codeqa | def tofloat value if isiterable value try value np array value dtype np float except Type Error Value Error raise Input Parameter Error u' Parameterof{ 0 }couldnotbeconvertedtofloat' format type value elif isinstance value np ndarray value float value item elif isinstance value numbers Number np number value float value elif isinstance value bool raise Input Parameter Error u' Expectedparametertobeofnumericaltype notboolean' else raise Input Parameter Error u" Don'tknowhowtoconvertparameterof{ 0 }tofloat" format type value return value
| null | null | null | null | Question:
For what purpose does the code convert a parameter ?
Code:
def _tofloat(value):
if isiterable(value):
try:
value = np.array(value, dtype=np.float)
except (TypeError, ValueError):
raise InputParameterError(u'Parameter of {0} could not be converted to float'.format(type(value)))
elif isinstance(value, np.ndarray):
value = float(value.item())
elif isinstance(value, (numbers.Number, np.number)):
value = float(value)
elif isinstance(value, bool):
raise InputParameterError(u'Expected parameter to be of numerical type, not boolean')
else:
raise InputParameterError(u"Don't know how to convert parameter of {0} to float".format(type(value)))
return value
|
null | null | null | What does the code convert to float or float array ?
| def _tofloat(value):
if isiterable(value):
try:
value = np.array(value, dtype=np.float)
except (TypeError, ValueError):
raise InputParameterError(u'Parameter of {0} could not be converted to float'.format(type(value)))
elif isinstance(value, np.ndarray):
value = float(value.item())
elif isinstance(value, (numbers.Number, np.number)):
value = float(value)
elif isinstance(value, bool):
raise InputParameterError(u'Expected parameter to be of numerical type, not boolean')
else:
raise InputParameterError(u"Don't know how to convert parameter of {0} to float".format(type(value)))
return value
| null | null | null | a parameter
| codeqa | def tofloat value if isiterable value try value np array value dtype np float except Type Error Value Error raise Input Parameter Error u' Parameterof{ 0 }couldnotbeconvertedtofloat' format type value elif isinstance value np ndarray value float value item elif isinstance value numbers Number np number value float value elif isinstance value bool raise Input Parameter Error u' Expectedparametertobeofnumericaltype notboolean' else raise Input Parameter Error u" Don'tknowhowtoconvertparameterof{ 0 }tofloat" format type value return value
| null | null | null | null | Question:
What does the code convert to float or float array ?
Code:
def _tofloat(value):
if isiterable(value):
try:
value = np.array(value, dtype=np.float)
except (TypeError, ValueError):
raise InputParameterError(u'Parameter of {0} could not be converted to float'.format(type(value)))
elif isinstance(value, np.ndarray):
value = float(value.item())
elif isinstance(value, (numbers.Number, np.number)):
value = float(value)
elif isinstance(value, bool):
raise InputParameterError(u'Expected parameter to be of numerical type, not boolean')
else:
raise InputParameterError(u"Don't know how to convert parameter of {0} to float".format(type(value)))
return value
|
null | null | null | How do import record create ?
| def create_import_job(task):
ij = ImportJob(task=task, user=g.user)
save_to_db(ij, 'Import job saved')
| null | null | null | in db
| codeqa | def create import job task ij Import Job task task user g user save to db ij ' Importjobsaved'
| null | null | null | null | Question:
How do import record create ?
Code:
def create_import_job(task):
ij = ImportJob(task=task, user=g.user)
save_to_db(ij, 'Import job saved')
|
null | null | null | Where is k the total number of neurons in the layer ?
| def softmax(x):
return theano.tensor.nnet.softmax(x)
| null | null | null | where
| codeqa | def softmax x return theano tensor nnet softmax x
| null | null | null | null | Question:
Where is k the total number of neurons in the layer ?
Code:
def softmax(x):
return theano.tensor.nnet.softmax(x)
|
null | null | null | What is the total number of neurons in the layer where ?
| def softmax(x):
return theano.tensor.nnet.softmax(x)
| null | null | null | k
| codeqa | def softmax x return theano tensor nnet softmax x
| null | null | null | null | Question:
What is the total number of neurons in the layer where ?
Code:
def softmax(x):
return theano.tensor.nnet.softmax(x)
|
null | null | null | When did exception occur ?
| def get_error_details(exclude_robot_traces=EXCLUDE_ROBOT_TRACES):
details = ErrorDetails(exclude_robot_traces=exclude_robot_traces)
return (details.message, details.traceback)
| null | null | null | last
| codeqa | def get error details exclude robot traces EXCLUDE ROBOT TRACES details Error Details exclude robot traces exclude robot traces return details message details traceback
| null | null | null | null | Question:
When did exception occur ?
Code:
def get_error_details(exclude_robot_traces=EXCLUDE_ROBOT_TRACES):
details = ErrorDetails(exclude_robot_traces=exclude_robot_traces)
return (details.message, details.traceback)
|
null | null | null | Where does the code truncate a string ?
| def truncate(string, index):
if ((len(string) > index) and (index > 0)):
string = (string[:(index - 1)] + u('\xe2\x80\xa6'))
return string
| null | null | null | at index
| codeqa | def truncate string index if len string > index and index > 0 string string[ index - 1 ] + u '\xe 2 \x 80 \xa 6 ' return string
| null | null | null | null | Question:
Where does the code truncate a string ?
Code:
def truncate(string, index):
if ((len(string) > index) and (index > 0)):
string = (string[:(index - 1)] + u('\xe2\x80\xa6'))
return string
|
null | null | null | What does the code truncate at index ?
| def truncate(string, index):
if ((len(string) > index) and (index > 0)):
string = (string[:(index - 1)] + u('\xe2\x80\xa6'))
return string
| null | null | null | a string
| codeqa | def truncate string index if len string > index and index > 0 string string[ index - 1 ] + u '\xe 2 \x 80 \xa 6 ' return string
| null | null | null | null | Question:
What does the code truncate at index ?
Code:
def truncate(string, index):
if ((len(string) > index) and (index > 0)):
string = (string[:(index - 1)] + u('\xe2\x80\xa6'))
return string
|
null | null | null | What does the code restart ?
| def reboot(zone, single=False, altinit=None, smf_options=None):
ret = {'status': True}
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit:
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if (boot_options != ''):
boot_options = ' -- {0}'.format(boot_options.strip())
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(zone=('-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone)), boot_opts=boot_options))
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 | the zone
| codeqa | def reboot zone single False altinit None smf options None ret {'status' True}boot options ''if single boot options '-s{ 0 }' format boot options if altinit boot options '-i{ 0 }{ 1 }' format altinit boot options if smf options boot options '-m{ 0 }{ 1 }' format smf options boot options if boot options '' boot options '--{ 0 }' format boot options strip res salt ['cmd run all'] 'zoneadm{zone}reboot{boot opts}' format zone '-u{ 0 }' format zone if is uuid zone else '-z{ 0 }' format zone boot opts boot options 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:
What does the code restart ?
Code:
def reboot(zone, single=False, altinit=None, smf_options=None):
ret = {'status': True}
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit:
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if (boot_options != ''):
boot_options = ' -- {0}'.format(boot_options.strip())
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(zone=('-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone)), boot_opts=boot_options))
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 | How is the response body encoded ?
| def structured(inputSchema, outputSchema, schema_store=None, ignore_body=False):
if (schema_store is None):
schema_store = {}
inputValidator = getValidator(inputSchema, schema_store)
outputValidator = getValidator(outputSchema, schema_store)
def deco(original):
@wraps(original)
@_remote_logging
@_logging
@_serialize(outputValidator)
def loadAndDispatch(self, request, **routeArguments):
if ((request.method in ('GET', 'DELETE')) or ignore_body):
objects = {}
else:
body = request.content.read()
try:
objects = loads(body)
except ValueError:
raise DECODING_ERROR
errors = []
for error in inputValidator.iter_errors(objects):
errors.append(error.message)
if errors:
raise InvalidRequestJSON(errors=errors, schema=inputSchema)
objects.update(routeArguments)
return maybeDeferred(original, self, **objects)
loadAndDispatch.inputSchema = inputSchema
loadAndDispatch.outputSchema = outputSchema
return loadAndDispatch
return deco
| null | null | null | automatically
| codeqa | def structured input Schema output Schema schema store None ignore body False if schema store is None schema store {}input Validator get Validator input Schema schema store output Validator get Validator output Schema schema store def deco original @wraps original @ remote logging@ logging@ serialize output Validator def load And Dispatch self request **route Arguments if request method in 'GET' 'DELETE' or ignore body objects {}else body request content read try objects loads body except Value Error raise DECODING ERRO Rerrors []for error in input Validator iter errors objects errors append error message if errors raise Invalid Request JSON errors errors schema input Schema objects update route Arguments return maybe Deferred original self **objects load And Dispatch input Schema input Schemaload And Dispatch output Schema output Schemareturn load And Dispatchreturn deco
| null | null | null | null | Question:
How is the response body encoded ?
Code:
def structured(inputSchema, outputSchema, schema_store=None, ignore_body=False):
if (schema_store is None):
schema_store = {}
inputValidator = getValidator(inputSchema, schema_store)
outputValidator = getValidator(outputSchema, schema_store)
def deco(original):
@wraps(original)
@_remote_logging
@_logging
@_serialize(outputValidator)
def loadAndDispatch(self, request, **routeArguments):
if ((request.method in ('GET', 'DELETE')) or ignore_body):
objects = {}
else:
body = request.content.read()
try:
objects = loads(body)
except ValueError:
raise DECODING_ERROR
errors = []
for error in inputValidator.iter_errors(objects):
errors.append(error.message)
if errors:
raise InvalidRequestJSON(errors=errors, schema=inputSchema)
objects.update(routeArguments)
return maybeDeferred(original, self, **objects)
loadAndDispatch.inputSchema = inputSchema
loadAndDispatch.outputSchema = outputSchema
return loadAndDispatch
return deco
|
null | null | null | How is the request body decoded ?
| def structured(inputSchema, outputSchema, schema_store=None, ignore_body=False):
if (schema_store is None):
schema_store = {}
inputValidator = getValidator(inputSchema, schema_store)
outputValidator = getValidator(outputSchema, schema_store)
def deco(original):
@wraps(original)
@_remote_logging
@_logging
@_serialize(outputValidator)
def loadAndDispatch(self, request, **routeArguments):
if ((request.method in ('GET', 'DELETE')) or ignore_body):
objects = {}
else:
body = request.content.read()
try:
objects = loads(body)
except ValueError:
raise DECODING_ERROR
errors = []
for error in inputValidator.iter_errors(objects):
errors.append(error.message)
if errors:
raise InvalidRequestJSON(errors=errors, schema=inputSchema)
objects.update(routeArguments)
return maybeDeferred(original, self, **objects)
loadAndDispatch.inputSchema = inputSchema
loadAndDispatch.outputSchema = outputSchema
return loadAndDispatch
return deco
| null | null | null | automatically
| codeqa | def structured input Schema output Schema schema store None ignore body False if schema store is None schema store {}input Validator get Validator input Schema schema store output Validator get Validator output Schema schema store def deco original @wraps original @ remote logging@ logging@ serialize output Validator def load And Dispatch self request **route Arguments if request method in 'GET' 'DELETE' or ignore body objects {}else body request content read try objects loads body except Value Error raise DECODING ERRO Rerrors []for error in input Validator iter errors objects errors append error message if errors raise Invalid Request JSON errors errors schema input Schema objects update route Arguments return maybe Deferred original self **objects load And Dispatch input Schema input Schemaload And Dispatch output Schema output Schemareturn load And Dispatchreturn deco
| null | null | null | null | Question:
How is the request body decoded ?
Code:
def structured(inputSchema, outputSchema, schema_store=None, ignore_body=False):
if (schema_store is None):
schema_store = {}
inputValidator = getValidator(inputSchema, schema_store)
outputValidator = getValidator(outputSchema, schema_store)
def deco(original):
@wraps(original)
@_remote_logging
@_logging
@_serialize(outputValidator)
def loadAndDispatch(self, request, **routeArguments):
if ((request.method in ('GET', 'DELETE')) or ignore_body):
objects = {}
else:
body = request.content.read()
try:
objects = loads(body)
except ValueError:
raise DECODING_ERROR
errors = []
for error in inputValidator.iter_errors(objects):
errors.append(error.message)
if errors:
raise InvalidRequestJSON(errors=errors, schema=inputSchema)
objects.update(routeArguments)
return maybeDeferred(original, self, **objects)
loadAndDispatch.inputSchema = inputSchema
loadAndDispatch.outputSchema = outputSchema
return loadAndDispatch
return deco
|
null | null | null | What does the code get in order of preference ?
| def getSupportedKeyExchanges():
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from twisted.conch.ssh.keys import _curveTable
backend = default_backend()
kexAlgorithms = _kexAlgorithms.copy()
for keyAlgorithm in list(kexAlgorithms):
if keyAlgorithm.startswith('ecdh'):
keyAlgorithmDsa = keyAlgorithm.replace('ecdh', 'ecdsa')
supported = backend.elliptic_curve_exchange_algorithm_supported(ec.ECDH(), _curveTable[keyAlgorithmDsa])
if (not supported):
kexAlgorithms.pop(keyAlgorithm)
return sorted(kexAlgorithms, key=(lambda kexAlgorithm: kexAlgorithms[kexAlgorithm].preference))
| null | null | null | a list of supported key exchange algorithm names
| codeqa | def get Supported Key Exchanges from cryptography hazmat backends import default backendfrom cryptography hazmat primitives asymmetric import ecfrom twisted conch ssh keys import curve Tablebackend default backend kex Algorithms kex Algorithms copy for key Algorithm in list kex Algorithms if key Algorithm startswith 'ecdh' key Algorithm Dsa key Algorithm replace 'ecdh' 'ecdsa' supported backend elliptic curve exchange algorithm supported ec ECDH curve Table[key Algorithm Dsa] if not supported kex Algorithms pop key Algorithm return sorted kex Algorithms key lambda kex Algorithm kex Algorithms[kex Algorithm] preference
| null | null | null | null | Question:
What does the code get in order of preference ?
Code:
def getSupportedKeyExchanges():
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from twisted.conch.ssh.keys import _curveTable
backend = default_backend()
kexAlgorithms = _kexAlgorithms.copy()
for keyAlgorithm in list(kexAlgorithms):
if keyAlgorithm.startswith('ecdh'):
keyAlgorithmDsa = keyAlgorithm.replace('ecdh', 'ecdsa')
supported = backend.elliptic_curve_exchange_algorithm_supported(ec.ECDH(), _curveTable[keyAlgorithmDsa])
if (not supported):
kexAlgorithms.pop(keyAlgorithm)
return sorted(kexAlgorithms, key=(lambda kexAlgorithm: kexAlgorithms[kexAlgorithm].preference))
|
null | null | null | For what purpose does the code get a list of supported key exchange algorithm names ?
| def getSupportedKeyExchanges():
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from twisted.conch.ssh.keys import _curveTable
backend = default_backend()
kexAlgorithms = _kexAlgorithms.copy()
for keyAlgorithm in list(kexAlgorithms):
if keyAlgorithm.startswith('ecdh'):
keyAlgorithmDsa = keyAlgorithm.replace('ecdh', 'ecdsa')
supported = backend.elliptic_curve_exchange_algorithm_supported(ec.ECDH(), _curveTable[keyAlgorithmDsa])
if (not supported):
kexAlgorithms.pop(keyAlgorithm)
return sorted(kexAlgorithms, key=(lambda kexAlgorithm: kexAlgorithms[kexAlgorithm].preference))
| null | null | null | in order of preference
| codeqa | def get Supported Key Exchanges from cryptography hazmat backends import default backendfrom cryptography hazmat primitives asymmetric import ecfrom twisted conch ssh keys import curve Tablebackend default backend kex Algorithms kex Algorithms copy for key Algorithm in list kex Algorithms if key Algorithm startswith 'ecdh' key Algorithm Dsa key Algorithm replace 'ecdh' 'ecdsa' supported backend elliptic curve exchange algorithm supported ec ECDH curve Table[key Algorithm Dsa] if not supported kex Algorithms pop key Algorithm return sorted kex Algorithms key lambda kex Algorithm kex Algorithms[kex Algorithm] preference
| null | null | null | null | Question:
For what purpose does the code get a list of supported key exchange algorithm names ?
Code:
def getSupportedKeyExchanges():
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from twisted.conch.ssh.keys import _curveTable
backend = default_backend()
kexAlgorithms = _kexAlgorithms.copy()
for keyAlgorithm in list(kexAlgorithms):
if keyAlgorithm.startswith('ecdh'):
keyAlgorithmDsa = keyAlgorithm.replace('ecdh', 'ecdsa')
supported = backend.elliptic_curve_exchange_algorithm_supported(ec.ECDH(), _curveTable[keyAlgorithmDsa])
if (not supported):
kexAlgorithms.pop(keyAlgorithm)
return sorted(kexAlgorithms, key=(lambda kexAlgorithm: kexAlgorithms[kexAlgorithm].preference))
|
null | null | null | What does the code provide ?
| def get_process_name():
global _PROCESS_NAME, _MAX_NAME_LENGTH
if (_PROCESS_NAME is None):
ps_output = call(('ps -p %i -o args' % os.getpid()), [])
if ((len(ps_output) == 2) and (ps_output[0] in ('COMMAND', 'ARGS'))):
_PROCESS_NAME = ps_output[1]
else:
(args, argc) = ([], argc_t())
for i in range(100):
try:
if (argc[i] is None):
break
except ValueError:
break
args.append(str(argc[i]))
_PROCESS_NAME = ' '.join(args)
_MAX_NAME_LENGTH = len(_PROCESS_NAME)
return _PROCESS_NAME
| null | null | null | the present name of our process
| codeqa | def get process name global PROCESS NAME MAX NAME LENGT Hif PROCESS NAME is None ps output call 'ps-p%i-oargs' % os getpid [] if len ps output 2 and ps output[ 0 ] in 'COMMAND' 'ARGS' PROCESS NAME ps output[ 1 ]else args argc [] argc t for i in range 100 try if argc[i] is None breakexcept Value Error breakargs append str argc[i] PROCESS NAME '' join args MAX NAME LENGTH len PROCESS NAME return PROCESS NAME
| null | null | null | null | Question:
What does the code provide ?
Code:
def get_process_name():
global _PROCESS_NAME, _MAX_NAME_LENGTH
if (_PROCESS_NAME is None):
ps_output = call(('ps -p %i -o args' % os.getpid()), [])
if ((len(ps_output) == 2) and (ps_output[0] in ('COMMAND', 'ARGS'))):
_PROCESS_NAME = ps_output[1]
else:
(args, argc) = ([], argc_t())
for i in range(100):
try:
if (argc[i] is None):
break
except ValueError:
break
args.append(str(argc[i]))
_PROCESS_NAME = ' '.join(args)
_MAX_NAME_LENGTH = len(_PROCESS_NAME)
return _PROCESS_NAME
|
null | null | null | What does the code compute ?
| @not_implemented_for('undirected')
def out_degree_centrality(G):
centrality = {}
s = (1.0 / (len(G) - 1.0))
centrality = {n: (d * s) for (n, d) in G.out_degree()}
return centrality
| null | null | null | the out - degree centrality for nodes
| codeqa | @not implemented for 'undirected' def out degree centrality G centrality {}s 1 0 / len G - 1 0 centrality {n d * s for n d in G out degree }return centrality
| null | null | null | null | Question:
What does the code compute ?
Code:
@not_implemented_for('undirected')
def out_degree_centrality(G):
centrality = {}
s = (1.0 / (len(G) - 1.0))
centrality = {n: (d * s) for (n, d) in G.out_degree()}
return centrality
|
null | null | null | What does the code load ?
| def load_backend(full_backend_path):
path_bits = full_backend_path.split(u'.')
if (len(path_bits) < 2):
raise ImproperlyConfigured((u"The provided backend '%s' is not a complete Python path to a BaseEngine subclass." % full_backend_path))
return import_class(full_backend_path)
| null | null | null | a backend for interacting with the search engine
| codeqa | def load backend full backend path path bits full backend path split u' ' if len path bits < 2 raise Improperly Configured u" Theprovidedbackend'%s'isnotacomplete Pythonpathtoa Base Enginesubclass " % full backend path return import class full backend path
| null | null | null | null | Question:
What does the code load ?
Code:
def load_backend(full_backend_path):
path_bits = full_backend_path.split(u'.')
if (len(path_bits) < 2):
raise ImproperlyConfigured((u"The provided backend '%s' is not a complete Python path to a BaseEngine subclass." % full_backend_path))
return import_class(full_backend_path)
|
null | null | null | When do on each item call ?
| def interleave(inter, f, seq):
seq = iter(seq)
try:
f(next(seq))
except StopIteration:
pass
else:
for x in seq:
inter()
f(x)
| null | null | null | in seq
| codeqa | def interleave inter f seq seq iter seq try f next seq except Stop Iteration passelse for x in seq inter f x
| null | null | null | null | Question:
When do on each item call ?
Code:
def interleave(inter, f, seq):
seq = iter(seq)
try:
f(next(seq))
except StopIteration:
pass
else:
for x in seq:
inter()
f(x)
|
null | null | null | What does the code return ?
| def readpipe(argv, preexec_fn=None, shell=False):
p = subprocess.Popen(argv, stdout=subprocess.PIPE, preexec_fn=preexec_fn, shell=shell)
(out, err) = p.communicate()
if (p.returncode != 0):
raise Exception(('subprocess %r failed with status %d' % (' '.join(argv), p.returncode)))
return out
| null | null | null | its output
| codeqa | def readpipe argv preexec fn None shell False p subprocess Popen argv stdout subprocess PIPE preexec fn preexec fn shell shell out err p communicate if p returncode 0 raise Exception 'subprocess%rfailedwithstatus%d' % '' join argv p returncode return out
| null | null | null | null | Question:
What does the code return ?
Code:
def readpipe(argv, preexec_fn=None, shell=False):
p = subprocess.Popen(argv, stdout=subprocess.PIPE, preexec_fn=preexec_fn, shell=shell)
(out, err) = p.communicate()
if (p.returncode != 0):
raise Exception(('subprocess %r failed with status %d' % (' '.join(argv), p.returncode)))
return out
|
null | null | null | For what purpose can generator be iterated ?
| def all_index_generator(k=10):
all_make_index_funcs = [makeIntIndex, makeFloatIndex, makeStringIndex, makeUnicodeIndex, makeDateIndex, makePeriodIndex, makeTimedeltaIndex, makeBoolIndex, makeCategoricalIndex]
for make_index_func in all_make_index_funcs:
(yield make_index_func(k=k))
| null | null | null | to get instances of all the various index classes
| codeqa | def all index generator k 10 all make index funcs [make Int Index make Float Index make String Index make Unicode Index make Date Index make Period Index make Timedelta Index make Bool Index make Categorical Index]for make index func in all make index funcs yield make index func k k
| null | null | null | null | Question:
For what purpose can generator be iterated ?
Code:
def all_index_generator(k=10):
all_make_index_funcs = [makeIntIndex, makeFloatIndex, makeStringIndex, makeUnicodeIndex, makeDateIndex, makePeriodIndex, makeTimedeltaIndex, makeBoolIndex, makeCategoricalIndex]
for make_index_func in all_make_index_funcs:
(yield make_index_func(k=k))
|
null | null | null | What does the code return to a glance server ?
| def get_client(options):
return glance.image_cache.client.get_client(host=options.host, port=options.port, username=options.os_username, password=options.os_password, tenant=options.os_tenant_name, auth_url=options.os_auth_url, auth_strategy=options.os_auth_strategy, auth_token=options.os_auth_token, region=options.os_region_name, insecure=options.insecure)
| null | null | null | a new client object
| codeqa | def get client options return glance image cache client get client host options host port options port username options os username password options os password tenant options os tenant name auth url options os auth url auth strategy options os auth strategy auth token options os auth token region options os region name insecure options insecure
| null | null | null | null | Question:
What does the code return to a glance server ?
Code:
def get_client(options):
return glance.image_cache.client.get_client(host=options.host, port=options.port, username=options.os_username, password=options.os_password, tenant=options.os_tenant_name, auth_url=options.os_auth_url, auth_strategy=options.os_auth_strategy, auth_token=options.os_auth_token, region=options.os_region_name, insecure=options.insecure)
|
null | null | null | In which direction can the name be parsed to its original form for both single and multi episodes ?
| def check_valid_naming(pattern=None, multi=None, anime_type=None):
if (pattern is None):
pattern = sickrage.srCore.srConfig.NAMING_PATTERN
if (anime_type is None):
anime_type = sickrage.srCore.srConfig.NAMING_ANIME
sickrage.srCore.srLogger.debug(((u'Checking whether the pattern ' + pattern) + u' is valid'))
return validate_name(pattern, multi, anime_type)
| null | null | null | back
| codeqa | def check valid naming pattern None multi None anime type None if pattern is None pattern sickrage sr Core sr Config NAMING PATTER Nif anime type is None anime type sickrage sr Core sr Config NAMING ANIM Esickrage sr Core sr Logger debug u' Checkingwhetherthepattern' + pattern + u'isvalid' return validate name pattern multi anime type
| null | null | null | null | Question:
In which direction can the name be parsed to its original form for both single and multi episodes ?
Code:
def check_valid_naming(pattern=None, multi=None, anime_type=None):
if (pattern is None):
pattern = sickrage.srCore.srConfig.NAMING_PATTERN
if (anime_type is None):
anime_type = sickrage.srCore.srConfig.NAMING_ANIME
sickrage.srCore.srLogger.debug(((u'Checking whether the pattern ' + pattern) + u' is valid'))
return validate_name(pattern, multi, anime_type)
|
null | null | null | What does the code attach ?
| def volume_attach(context, values):
return IMPL.volume_attach(context, values)
| null | null | null | a volume
| codeqa | def volume attach context values return IMPL volume attach context values
| null | null | null | null | Question:
What does the code attach ?
Code:
def volume_attach(context, values):
return IMPL.volume_attach(context, values)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.