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 use ?
def new_class(name, bases=(), kwds=None, exec_body=None): (meta, ns, kwds) = prepare_class(name, bases, kwds) if (exec_body is not None): exec_body(ns) return meta(name, bases, ns, **kwds)
null
null
null
the appropriate metaclass
codeqa
def new class name bases kwds None exec body None meta ns kwds prepare class name bases kwds if exec body is not None exec body ns return meta name bases ns **kwds
null
null
null
null
Question: What does the code use ? Code: def new_class(name, bases=(), kwds=None, exec_body=None): (meta, ns, kwds) = prepare_class(name, bases, kwds) if (exec_body is not None): exec_body(ns) return meta(name, bases, ns, **kwds)
null
null
null
How does the code create a class object ?
def new_class(name, bases=(), kwds=None, exec_body=None): (meta, ns, kwds) = prepare_class(name, bases, kwds) if (exec_body is not None): exec_body(ns) return meta(name, bases, ns, **kwds)
null
null
null
dynamically
codeqa
def new class name bases kwds None exec body None meta ns kwds prepare class name bases kwds if exec body is not None exec body ns return meta name bases ns **kwds
null
null
null
null
Question: How does the code create a class object ? Code: def new_class(name, bases=(), kwds=None, exec_body=None): (meta, ns, kwds) = prepare_class(name, bases, kwds) if (exec_body is not None): exec_body(ns) return meta(name, bases, ns, **kwds)
null
null
null
What does the code read ?
def read_images(path, sz=None): c = 0 (X, y) = ([], []) for (dirname, dirnames, filenames) in os.walk(path): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) for filename in os.listdir(subject_path): try: im = Image.open(os.path.join(subject_path, filename)) im = im.convert('L') if (sz is not None): im = im.resize(sz, Image.ANTIALIAS) X.append(np.asarray(im, dtype=np.uint8)) y.append(c) except IOError as e: print 'I/O error: {0}'.format(e) raise e except: print 'Unexpected error: {0}'.format(sys.exc_info()[0]) raise c = (c + 1) return [X, y]
null
null
null
the images in a given folder
codeqa
def read images path sz None c 0 X y [] [] for dirname dirnames filenames in os walk path for subdirname in dirnames subject path os path join dirname subdirname for filename in os listdir subject path try im Image open os path join subject path filename im im convert 'L' if sz is not None im im resize sz Image ANTIALIAS X append np asarray im dtype np uint 8 y append c except IO Error as e print 'I/ Oerror {0 }' format e raise eexcept print ' Unexpectederror {0 }' format sys exc info [0 ] raisec c + 1 return [X y]
null
null
null
null
Question: What does the code read ? Code: def read_images(path, sz=None): c = 0 (X, y) = ([], []) for (dirname, dirnames, filenames) in os.walk(path): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) for filename in os.listdir(subject_path): try: im = Image.open(os.path.join(subject_path, filename)) im = im.convert('L') if (sz is not None): im = im.resize(sz, Image.ANTIALIAS) X.append(np.asarray(im, dtype=np.uint8)) y.append(c) except IOError as e: print 'I/O error: {0}'.format(e) raise e except: print 'Unexpected error: {0}'.format(sys.exc_info()[0]) raise c = (c + 1) return [X, y]
null
null
null
What did the code split ?
def split_semicolon(line, maxsplit=None): splitted_line = line.split(';') splitted_line_size = len(splitted_line) if ((maxsplit is None) or (0 > maxsplit)): maxsplit = splitted_line_size i = 0 while (i < (splitted_line_size - 1)): ends = splitted_line[i].endswith('\\') if ends: splitted_line[i] = splitted_line[i][:(-1)] if ((ends or (i >= maxsplit)) and (i < (splitted_line_size - 1))): splitted_line[i] = ';'.join([splitted_line[i], splitted_line[(i + 1)]]) del splitted_line[(i + 1)] splitted_line_size -= 1 else: i += 1 return splitted_line
null
null
null
a line on semicolons characters
codeqa
def split semicolon line maxsplit None splitted line line split ' ' splitted line size len splitted line if maxsplit is None or 0 > maxsplit maxsplit splitted line sizei 0while i < splitted line size - 1 ends splitted line[i] endswith '\\' if ends splitted line[i] splitted line[i][ -1 ]if ends or i > maxsplit and i < splitted line size - 1 splitted line[i] ' ' join [splitted line[i] splitted line[ i + 1 ]] del splitted line[ i + 1 ]splitted line size - 1else i + 1return splitted line
null
null
null
null
Question: What did the code split ? Code: def split_semicolon(line, maxsplit=None): splitted_line = line.split(';') splitted_line_size = len(splitted_line) if ((maxsplit is None) or (0 > maxsplit)): maxsplit = splitted_line_size i = 0 while (i < (splitted_line_size - 1)): ends = splitted_line[i].endswith('\\') if ends: splitted_line[i] = splitted_line[i][:(-1)] if ((ends or (i >= maxsplit)) and (i < (splitted_line_size - 1))): splitted_line[i] = ';'.join([splitted_line[i], splitted_line[(i + 1)]]) del splitted_line[(i + 1)] splitted_line_size -= 1 else: i += 1 return splitted_line
null
null
null
What does the code get ?
def console_get_by_pool_instance(context, pool_id, instance_uuid): return IMPL.console_get_by_pool_instance(context, pool_id, instance_uuid)
null
null
null
console entry for a given instance and pool
codeqa
def console get by pool instance context pool id instance uuid return IMPL console get by pool instance context pool id instance uuid
null
null
null
null
Question: What does the code get ? Code: def console_get_by_pool_instance(context, pool_id, instance_uuid): return IMPL.console_get_by_pool_instance(context, pool_id, instance_uuid)
null
null
null
What has bad checksum ?
@patch('pip.download.unpack_file') def test_unpack_http_url_bad_downloaded_checksum(mock_unpack_file): base_url = 'http://www.example.com/somepackage.tgz' contents = 'downloaded' download_hash = hashlib.new('sha1', contents) link = Link(((base_url + '#sha1=') + download_hash.hexdigest())) session = Mock() session.get = Mock() response = session.get.return_value = MockResponse(contents) response.headers = {'content-type': 'application/x-tar'} response.url = base_url download_dir = mkdtemp() try: downloaded_file = os.path.join(download_dir, 'somepackage.tgz') _write_file(downloaded_file, 'some contents') unpack_http_url(link, 'location', download_dir=download_dir, session=session, hashes=Hashes({'sha1': [download_hash.hexdigest()]})) session.get.assert_called_once_with('http://www.example.com/somepackage.tgz', headers={'Accept-Encoding': 'identity'}, stream=True) with open(downloaded_file) as fh: assert (fh.read() == 'downloaded') finally: rmtree(download_dir)
null
null
null
already - downloaded file
codeqa
@patch 'pip download unpack file' def test unpack http url bad downloaded checksum mock unpack file base url 'http //www example com/somepackage tgz'contents 'downloaded'download hash hashlib new 'sha 1 ' contents link Link base url + '#sha 1 ' + download hash hexdigest session Mock session get Mock response session get return value Mock Response contents response headers {'content-type' 'application/x-tar'}response url base urldownload dir mkdtemp try downloaded file os path join download dir 'somepackage tgz' write file downloaded file 'somecontents' unpack http url link 'location' download dir download dir session session hashes Hashes {'sha 1 ' [download hash hexdigest ]} session get assert called once with 'http //www example com/somepackage tgz' headers {' Accept- Encoding' 'identity'} stream True with open downloaded file as fh assert fh read 'downloaded' finally rmtree download dir
null
null
null
null
Question: What has bad checksum ? Code: @patch('pip.download.unpack_file') def test_unpack_http_url_bad_downloaded_checksum(mock_unpack_file): base_url = 'http://www.example.com/somepackage.tgz' contents = 'downloaded' download_hash = hashlib.new('sha1', contents) link = Link(((base_url + '#sha1=') + download_hash.hexdigest())) session = Mock() session.get = Mock() response = session.get.return_value = MockResponse(contents) response.headers = {'content-type': 'application/x-tar'} response.url = base_url download_dir = mkdtemp() try: downloaded_file = os.path.join(download_dir, 'somepackage.tgz') _write_file(downloaded_file, 'some contents') unpack_http_url(link, 'location', download_dir=download_dir, session=session, hashes=Hashes({'sha1': [download_hash.hexdigest()]})) session.get.assert_called_once_with('http://www.example.com/somepackage.tgz', headers={'Accept-Encoding': 'identity'}, stream=True) with open(downloaded_file) as fh: assert (fh.read() == 'downloaded') finally: rmtree(download_dir)
null
null
null
How do to destroy the dataset recursive try ?
def bookmark_absent(name, force=False, recursive=False): return _absent(name, 'bookmark', force, recursive)
null
null
null
harder
codeqa
def bookmark absent name force False recursive False return absent name 'bookmark' force recursive
null
null
null
null
Question: How do to destroy the dataset recursive try ? Code: def bookmark_absent(name, force=False, recursive=False): return _absent(name, 'bookmark', force, recursive)
null
null
null
What does the code ensure ?
def bookmark_absent(name, force=False, recursive=False): return _absent(name, 'bookmark', force, recursive)
null
null
null
bookmark is absent on the system name
codeqa
def bookmark absent name force False recursive False return absent name 'bookmark' force recursive
null
null
null
null
Question: What does the code ensure ? Code: def bookmark_absent(name, force=False, recursive=False): return _absent(name, 'bookmark', force, recursive)
null
null
null
How do the dataset destroy ?
def bookmark_absent(name, force=False, recursive=False): return _absent(name, 'bookmark', force, recursive)
null
null
null
recursive
codeqa
def bookmark absent name force False recursive False return absent name 'bookmark' force recursive
null
null
null
null
Question: How do the dataset destroy ? Code: def bookmark_absent(name, force=False, recursive=False): return _absent(name, 'bookmark', force, recursive)
null
null
null
What does the code get from the user arguments ?
def askinteger(title, prompt, **kw): d = _QueryInteger(title, prompt, **kw) return d.result
null
null
null
an integer
codeqa
def askinteger title prompt **kw d Query Integer title prompt **kw return d result
null
null
null
null
Question: What does the code get from the user arguments ? Code: def askinteger(title, prompt, **kw): d = _QueryInteger(title, prompt, **kw) return d.result
null
null
null
What downloads to a file - like - object from this bucket ?
def bucket_download_fileobj(self, Key, Fileobj, ExtraArgs=None, Callback=None, Config=None): return self.meta.client.download_fileobj(Bucket=self.name, Key=Key, Fileobj=Fileobj, ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
null
null
null
an object
codeqa
def bucket download fileobj self Key Fileobj Extra Args None Callback None Config None return self meta client download fileobj Bucket self name Key Key Fileobj Fileobj Extra Args Extra Args Callback Callback Config Config
null
null
null
null
Question: What downloads to a file - like - object from this bucket ? Code: def bucket_download_fileobj(self, Key, Fileobj, ExtraArgs=None, Callback=None, Config=None): return self.meta.client.download_fileobj(Bucket=self.name, Key=Key, Fileobj=Fileobj, ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
null
null
null
What do an object download from this bucket ?
def bucket_download_fileobj(self, Key, Fileobj, ExtraArgs=None, Callback=None, Config=None): return self.meta.client.download_fileobj(Bucket=self.name, Key=Key, Fileobj=Fileobj, ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
null
null
null
to a file - like - object
codeqa
def bucket download fileobj self Key Fileobj Extra Args None Callback None Config None return self meta client download fileobj Bucket self name Key Key Fileobj Fileobj Extra Args Extra Args Callback Callback Config Config
null
null
null
null
Question: What do an object download from this bucket ? Code: def bucket_download_fileobj(self, Key, Fileobj, ExtraArgs=None, Callback=None, Config=None): return self.meta.client.download_fileobj(Bucket=self.name, Key=Key, Fileobj=Fileobj, ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
null
null
null
In which direction do an object download to a file - like - object ?
def bucket_download_fileobj(self, Key, Fileobj, ExtraArgs=None, Callback=None, Config=None): return self.meta.client.download_fileobj(Bucket=self.name, Key=Key, Fileobj=Fileobj, ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
null
null
null
from this bucket
codeqa
def bucket download fileobj self Key Fileobj Extra Args None Callback None Config None return self meta client download fileobj Bucket self name Key Key Fileobj Fileobj Extra Args Extra Args Callback Callback Config Config
null
null
null
null
Question: In which direction do an object download to a file - like - object ? Code: def bucket_download_fileobj(self, Key, Fileobj, ExtraArgs=None, Callback=None, Config=None): return self.meta.client.download_fileobj(Bucket=self.name, Key=Key, Fileobj=Fileobj, ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
null
null
null
What does the code ensure ?
def subnet_group_present(name, subnet_ids=None, subnet_names=None, description=None, tags=None, region=None, key=None, keyid=None, profile=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} exists = __salt__['boto_elasticache.subnet_group_exists'](name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if (not exists): if __opts__['test']: ret['comment'] = 'Subnet group {0} is set to be created.'.format(name) ret['result'] = None return ret created = __salt__['boto_elasticache.create_subnet_group'](name=name, subnet_ids=subnet_ids, subnet_names=subnet_names, description=description, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if (not created): ret['result'] = False ret['comment'] = 'Failed to create {0} subnet group.'.format(name) return ret ret['changes']['old'] = None ret['changes']['new'] = name ret['comment'] = 'Subnet group {0} created.'.format(name) return ret ret['comment'] = 'Subnet group present.' return ret
null
null
null
elasticache subnet group exists
codeqa
def subnet group present name subnet ids None subnet names None description None tags None region None key None keyid None profile None ret {'name' name 'result' True 'comment' '' 'changes' {}}exists salt ['boto elasticache subnet group exists'] name name tags tags region region key key keyid keyid profile profile if not exists if opts ['test'] ret['comment'] ' Subnetgroup{ 0 }issettobecreated ' format name ret['result'] Nonereturn retcreated salt ['boto elasticache create subnet group'] name name subnet ids subnet ids subnet names subnet names description description tags tags region region key key keyid keyid profile profile if not created ret['result'] Falseret['comment'] ' Failedtocreate{ 0 }subnetgroup ' format name return retret['changes']['old'] Noneret['changes']['new'] nameret['comment'] ' Subnetgroup{ 0 }created ' format name return retret['comment'] ' Subnetgrouppresent 'return ret
null
null
null
null
Question: What does the code ensure ? Code: def subnet_group_present(name, subnet_ids=None, subnet_names=None, description=None, tags=None, region=None, key=None, keyid=None, profile=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} exists = __salt__['boto_elasticache.subnet_group_exists'](name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if (not exists): if __opts__['test']: ret['comment'] = 'Subnet group {0} is set to be created.'.format(name) ret['result'] = None return ret created = __salt__['boto_elasticache.create_subnet_group'](name=name, subnet_ids=subnet_ids, subnet_names=subnet_names, description=description, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if (not created): ret['result'] = False ret['comment'] = 'Failed to create {0} subnet group.'.format(name) return ret ret['changes']['old'] = None ret['changes']['new'] = name ret['comment'] = 'Subnet group {0} created.'.format(name) return ret ret['comment'] = 'Subnet group present.' return ret
null
null
null
What does the code validate ?
def ValidatePropertyLink(name, value): ValidateStringLength(name, value, max_len=_MAX_LINK_PROPERTY_LENGTH)
null
null
null
the length of an indexed link property
codeqa
def Validate Property Link name value Validate String Length name value max len MAX LINK PROPERTY LENGTH
null
null
null
null
Question: What does the code validate ? Code: def ValidatePropertyLink(name, value): ValidateStringLength(name, value, max_len=_MAX_LINK_PROPERTY_LENGTH)
null
null
null
What does the code get ?
def getNewRepository(): return CarveRepository()
null
null
null
the repository constructor
codeqa
def get New Repository return Carve Repository
null
null
null
null
Question: What does the code get ? Code: def getNewRepository(): return CarveRepository()
null
null
null
What does the code traverse in depth - first post - order ?
def _postorder_traverse(root, get_children): def dfs(elem): for v in get_children(elem): for u in dfs(v): (yield u) (yield elem) for elem in dfs(root): (yield elem)
null
null
null
a tree
codeqa
def postorder traverse root get children def dfs elem for v in get children elem for u in dfs v yield u yield elem for elem in dfs root yield elem
null
null
null
null
Question: What does the code traverse in depth - first post - order ? Code: def _postorder_traverse(root, get_children): def dfs(elem): for v in get_children(elem): for u in dfs(v): (yield u) (yield elem) for elem in dfs(root): (yield elem)
null
null
null
How does the code traverse a tree ?
def _postorder_traverse(root, get_children): def dfs(elem): for v in get_children(elem): for u in dfs(v): (yield u) (yield elem) for elem in dfs(root): (yield elem)
null
null
null
in depth - first post - order
codeqa
def postorder traverse root get children def dfs elem for v in get children elem for u in dfs v yield u yield elem for elem in dfs root yield elem
null
null
null
null
Question: How does the code traverse a tree ? Code: def _postorder_traverse(root, get_children): def dfs(elem): for v in get_children(elem): for u in dfs(v): (yield u) (yield elem) for elem in dfs(root): (yield elem)
null
null
null
What does the code generate in reverse chronological order ?
def rev_list(ref, count=None, repo_dir=None): assert (not ref.startswith('-')) opts = [] if count: opts += ['-n', str(atoi(count))] argv = ((['git', 'rev-list', '--pretty=format:%at'] + opts) + [ref, '--']) p = subprocess.Popen(argv, preexec_fn=_gitenv(repo_dir), stdout=subprocess.PIPE) commit = None for row in p.stdout: s = row.strip() if s.startswith('commit '): commit = s[7:].decode('hex') else: date = int(s) (yield (date, commit)) rv = p.wait() if rv: raise GitError, ('git rev-list returned error %d' % rv)
null
null
null
a list of reachable commits
codeqa
def rev list ref count None repo dir None assert not ref startswith '-' opts []if count opts + ['-n' str atoi count ]argv ['git' 'rev-list' '--pretty format %at'] + opts + [ref '--'] p subprocess Popen argv preexec fn gitenv repo dir stdout subprocess PIPE commit Nonefor row in p stdout s row strip if s startswith 'commit' commit s[ 7 ] decode 'hex' else date int s yield date commit rv p wait if rv raise Git Error 'gitrev-listreturnederror%d' % rv
null
null
null
null
Question: What does the code generate in reverse chronological order ? Code: def rev_list(ref, count=None, repo_dir=None): assert (not ref.startswith('-')) opts = [] if count: opts += ['-n', str(atoi(count))] argv = ((['git', 'rev-list', '--pretty=format:%at'] + opts) + [ref, '--']) p = subprocess.Popen(argv, preexec_fn=_gitenv(repo_dir), stdout=subprocess.PIPE) commit = None for row in p.stdout: s = row.strip() if s.startswith('commit '): commit = s[7:].decode('hex') else: date = int(s) (yield (date, commit)) rv = p.wait() if rv: raise GitError, ('git rev-list returned error %d' % rv)
null
null
null
How does the code generate a list of reachable commits ?
def rev_list(ref, count=None, repo_dir=None): assert (not ref.startswith('-')) opts = [] if count: opts += ['-n', str(atoi(count))] argv = ((['git', 'rev-list', '--pretty=format:%at'] + opts) + [ref, '--']) p = subprocess.Popen(argv, preexec_fn=_gitenv(repo_dir), stdout=subprocess.PIPE) commit = None for row in p.stdout: s = row.strip() if s.startswith('commit '): commit = s[7:].decode('hex') else: date = int(s) (yield (date, commit)) rv = p.wait() if rv: raise GitError, ('git rev-list returned error %d' % rv)
null
null
null
in reverse chronological order
codeqa
def rev list ref count None repo dir None assert not ref startswith '-' opts []if count opts + ['-n' str atoi count ]argv ['git' 'rev-list' '--pretty format %at'] + opts + [ref '--'] p subprocess Popen argv preexec fn gitenv repo dir stdout subprocess PIPE commit Nonefor row in p stdout s row strip if s startswith 'commit' commit s[ 7 ] decode 'hex' else date int s yield date commit rv p wait if rv raise Git Error 'gitrev-listreturnederror%d' % rv
null
null
null
null
Question: How does the code generate a list of reachable commits ? Code: def rev_list(ref, count=None, repo_dir=None): assert (not ref.startswith('-')) opts = [] if count: opts += ['-n', str(atoi(count))] argv = ((['git', 'rev-list', '--pretty=format:%at'] + opts) + [ref, '--']) p = subprocess.Popen(argv, preexec_fn=_gitenv(repo_dir), stdout=subprocess.PIPE) commit = None for row in p.stdout: s = row.strip() if s.startswith('commit '): commit = s[7:].decode('hex') else: date = int(s) (yield (date, commit)) rv = p.wait() if rv: raise GitError, ('git rev-list returned error %d' % rv)
null
null
null
What does the code create ?
def put(cont, path=None, local_file=None, profile=None): swift_conn = _auth(profile) if (path is None): return swift_conn.put_container(cont) elif (local_file is not None): return swift_conn.put_object(cont, path, local_file) else: return False
null
null
null
a new container
codeqa
def put cont path None local file None profile None swift conn auth profile if path is None return swift conn put container cont elif local file is not None return swift conn put object cont path local file else return False
null
null
null
null
Question: What does the code create ? Code: def put(cont, path=None, local_file=None, profile=None): swift_conn = _auth(profile) if (path is None): return swift_conn.put_container(cont) elif (local_file is not None): return swift_conn.put_object(cont, path, local_file) else: return False
null
null
null
What does it restart ?
def restart(old, new, node_state): return sequentially(changes=[in_parallel(changes=[sequentially(changes=[StopApplication(application=old), StartApplication(application=new, node_state=node_state)])])])
null
null
null
a particular application on a particular node
codeqa
def restart old new node state return sequentially changes [in parallel changes [sequentially changes [ Stop Application application old Start Application application new node state node state ] ] ]
null
null
null
null
Question: What does it restart ? Code: def restart(old, new, node_state): return sequentially(changes=[in_parallel(changes=[sequentially(changes=[StopApplication(application=old), StartApplication(application=new, node_state=node_state)])])])
null
null
null
What does the code create ?
def collection_backup(collection_name, location, backup_name=None, **kwargs): if (not collection_exists(collection_name, **kwargs)): raise ValueError("Collection doesn't exists") if (backup_name is not None): backup_name = '&name={0}'.format(backup_name) else: backup_name = '' _query('{collection}/replication?command=BACKUP&location={location}{backup_name}&wt=json'.format(collection=collection_name, backup_name=backup_name, location=location), **kwargs)
null
null
null
a backup for a collection
codeqa
def collection backup collection name location backup name None **kwargs if not collection exists collection name **kwargs raise Value Error " Collectiondoesn'texists" if backup name is not None backup name '&name {0 }' format backup name else backup name '' query '{collection}/replication?command BACKUP&location {location}{backup name}&wt json' format collection collection name backup name backup name location location **kwargs
null
null
null
null
Question: What does the code create ? Code: def collection_backup(collection_name, location, backup_name=None, **kwargs): if (not collection_exists(collection_name, **kwargs)): raise ValueError("Collection doesn't exists") if (backup_name is not None): backup_name = '&name={0}'.format(backup_name) else: backup_name = '' _query('{collection}/replication?command=BACKUP&location={location}{backup_name}&wt=json'.format(collection=collection_name, backup_name=backup_name, location=location), **kwargs)
null
null
null
What does the code create ?
def get_remote_image_service(context, image_href): if ('/' not in str(image_href)): image_service = get_default_image_service() return (image_service, image_href) try: (image_id, endpoint) = _endpoint_from_image_ref(image_href) glance_client = GlanceClientWrapper(context=context, endpoint=endpoint) except ValueError: raise exception.InvalidImageRef(image_href=image_href) image_service = GlanceImageServiceV2(client=glance_client) return (image_service, image_id)
null
null
null
an image_service
codeqa
def get remote image service context image href if '/' not in str image href image service get default image service return image service image href try image id endpoint endpoint from image ref image href glance client Glance Client Wrapper context context endpoint endpoint except Value Error raise exception Invalid Image Ref image href image href image service Glance Image Service V 2 client glance client return image service image id
null
null
null
null
Question: What does the code create ? Code: def get_remote_image_service(context, image_href): if ('/' not in str(image_href)): image_service = get_default_image_service() return (image_service, image_href) try: (image_id, endpoint) = _endpoint_from_image_ref(image_href) glance_client = GlanceClientWrapper(context=context, endpoint=endpoint) except ValueError: raise exception.InvalidImageRef(image_href=image_href) image_service = GlanceImageServiceV2(client=glance_client) return (image_service, image_id)
null
null
null
What does the code retain ?
def libvlc_media_retain(p_md): f = (_Cfunctions.get('libvlc_media_retain', None) or _Cfunction('libvlc_media_retain', ((1,),), None, None, Media)) return f(p_md)
null
null
null
a reference to a media descriptor object
codeqa
def libvlc media retain p md f Cfunctions get 'libvlc media retain' None or Cfunction 'libvlc media retain' 1 None None Media return f p md
null
null
null
null
Question: What does the code retain ? Code: def libvlc_media_retain(p_md): f = (_Cfunctions.get('libvlc_media_retain', None) or _Cfunction('libvlc_media_retain', ((1,),), None, None, Media)) return f(p_md)
null
null
null
What revokes its own key ?
def revoke_auth(preserve_minion_cache=False): masters = list() ret = True if ('master_uri_list' in __opts__): for master_uri in __opts__['master_uri_list']: masters.append(master_uri) else: masters.append(__opts__['master_uri']) for master in masters: channel = salt.transport.Channel.factory(__opts__, master_uri=master) tok = channel.auth.gen_token('salt') load = {'cmd': 'revoke_auth', 'id': __opts__['id'], 'tok': tok, 'preserve_minion_cache': preserve_minion_cache} try: channel.send(load) except SaltReqTimeoutError: ret = False return ret
null
null
null
the minion
codeqa
def revoke auth preserve minion cache False masters list ret Trueif 'master uri list' in opts for master uri in opts ['master uri list'] masters append master uri else masters append opts ['master uri'] for master in masters channel salt transport Channel factory opts master uri master tok channel auth gen token 'salt' load {'cmd' 'revoke auth' 'id' opts ['id'] 'tok' tok 'preserve minion cache' preserve minion cache}try channel send load except Salt Req Timeout Error ret Falsereturn ret
null
null
null
null
Question: What revokes its own key ? Code: def revoke_auth(preserve_minion_cache=False): masters = list() ret = True if ('master_uri_list' in __opts__): for master_uri in __opts__['master_uri_list']: masters.append(master_uri) else: masters.append(__opts__['master_uri']) for master in masters: channel = salt.transport.Channel.factory(__opts__, master_uri=master) tok = channel.auth.gen_token('salt') load = {'cmd': 'revoke_auth', 'id': __opts__['id'], 'tok': tok, 'preserve_minion_cache': preserve_minion_cache} try: channel.send(load) except SaltReqTimeoutError: ret = False return ret
null
null
null
What does the minion revoke ?
def revoke_auth(preserve_minion_cache=False): masters = list() ret = True if ('master_uri_list' in __opts__): for master_uri in __opts__['master_uri_list']: masters.append(master_uri) else: masters.append(__opts__['master_uri']) for master in masters: channel = salt.transport.Channel.factory(__opts__, master_uri=master) tok = channel.auth.gen_token('salt') load = {'cmd': 'revoke_auth', 'id': __opts__['id'], 'tok': tok, 'preserve_minion_cache': preserve_minion_cache} try: channel.send(load) except SaltReqTimeoutError: ret = False return ret
null
null
null
its own key
codeqa
def revoke auth preserve minion cache False masters list ret Trueif 'master uri list' in opts for master uri in opts ['master uri list'] masters append master uri else masters append opts ['master uri'] for master in masters channel salt transport Channel factory opts master uri master tok channel auth gen token 'salt' load {'cmd' 'revoke auth' 'id' opts ['id'] 'tok' tok 'preserve minion cache' preserve minion cache}try channel send load except Salt Req Timeout Error ret Falsereturn ret
null
null
null
null
Question: What does the minion revoke ? Code: def revoke_auth(preserve_minion_cache=False): masters = list() ret = True if ('master_uri_list' in __opts__): for master_uri in __opts__['master_uri_list']: masters.append(master_uri) else: masters.append(__opts__['master_uri']) for master in masters: channel = salt.transport.Channel.factory(__opts__, master_uri=master) tok = channel.auth.gen_token('salt') load = {'cmd': 'revoke_auth', 'id': __opts__['id'], 'tok': tok, 'preserve_minion_cache': preserve_minion_cache} try: channel.send(load) except SaltReqTimeoutError: ret = False return ret
null
null
null
What sends a request to the master ?
def revoke_auth(preserve_minion_cache=False): masters = list() ret = True if ('master_uri_list' in __opts__): for master_uri in __opts__['master_uri_list']: masters.append(master_uri) else: masters.append(__opts__['master_uri']) for master in masters: channel = salt.transport.Channel.factory(__opts__, master_uri=master) tok = channel.auth.gen_token('salt') load = {'cmd': 'revoke_auth', 'id': __opts__['id'], 'tok': tok, 'preserve_minion_cache': preserve_minion_cache} try: channel.send(load) except SaltReqTimeoutError: ret = False return ret
null
null
null
the minion
codeqa
def revoke auth preserve minion cache False masters list ret Trueif 'master uri list' in opts for master uri in opts ['master uri list'] masters append master uri else masters append opts ['master uri'] for master in masters channel salt transport Channel factory opts master uri master tok channel auth gen token 'salt' load {'cmd' 'revoke auth' 'id' opts ['id'] 'tok' tok 'preserve minion cache' preserve minion cache}try channel send load except Salt Req Timeout Error ret Falsereturn ret
null
null
null
null
Question: What sends a request to the master ? Code: def revoke_auth(preserve_minion_cache=False): masters = list() ret = True if ('master_uri_list' in __opts__): for master_uri in __opts__['master_uri_list']: masters.append(master_uri) else: masters.append(__opts__['master_uri']) for master in masters: channel = salt.transport.Channel.factory(__opts__, master_uri=master) tok = channel.auth.gen_token('salt') load = {'cmd': 'revoke_auth', 'id': __opts__['id'], 'tok': tok, 'preserve_minion_cache': preserve_minion_cache} try: channel.send(load) except SaltReqTimeoutError: ret = False return ret
null
null
null
What does the minion send to the master ?
def revoke_auth(preserve_minion_cache=False): masters = list() ret = True if ('master_uri_list' in __opts__): for master_uri in __opts__['master_uri_list']: masters.append(master_uri) else: masters.append(__opts__['master_uri']) for master in masters: channel = salt.transport.Channel.factory(__opts__, master_uri=master) tok = channel.auth.gen_token('salt') load = {'cmd': 'revoke_auth', 'id': __opts__['id'], 'tok': tok, 'preserve_minion_cache': preserve_minion_cache} try: channel.send(load) except SaltReqTimeoutError: ret = False return ret
null
null
null
a request
codeqa
def revoke auth preserve minion cache False masters list ret Trueif 'master uri list' in opts for master uri in opts ['master uri list'] masters append master uri else masters append opts ['master uri'] for master in masters channel salt transport Channel factory opts master uri master tok channel auth gen token 'salt' load {'cmd' 'revoke auth' 'id' opts ['id'] 'tok' tok 'preserve minion cache' preserve minion cache}try channel send load except Salt Req Timeout Error ret Falsereturn ret
null
null
null
null
Question: What does the minion send to the master ? Code: def revoke_auth(preserve_minion_cache=False): masters = list() ret = True if ('master_uri_list' in __opts__): for master_uri in __opts__['master_uri_list']: masters.append(master_uri) else: masters.append(__opts__['master_uri']) for master in masters: channel = salt.transport.Channel.factory(__opts__, master_uri=master) tok = channel.auth.gen_token('salt') load = {'cmd': 'revoke_auth', 'id': __opts__['id'], 'tok': tok, 'preserve_minion_cache': preserve_minion_cache} try: channel.send(load) except SaltReqTimeoutError: ret = False return ret
null
null
null
What returns from byte size ?
def format_size(size): for unit in ('B', 'KB', 'MB', 'GB', 'TB'): if (size < 2048): return ('%.f %s' % (size, unit)) size /= 1024.0
null
null
null
file size
codeqa
def format size size for unit in 'B' 'KB' 'MB' 'GB' 'TB' if size < 2048 return '% f%s' % size unit size / 1024 0
null
null
null
null
Question: What returns from byte size ? Code: def format_size(size): for unit in ('B', 'KB', 'MB', 'GB', 'TB'): if (size < 2048): return ('%.f %s' % (size, unit)) size /= 1024.0
null
null
null
What do file size return ?
def format_size(size): for unit in ('B', 'KB', 'MB', 'GB', 'TB'): if (size < 2048): return ('%.f %s' % (size, unit)) size /= 1024.0
null
null
null
from byte size
codeqa
def format size size for unit in 'B' 'KB' 'MB' 'GB' 'TB' if size < 2048 return '% f%s' % size unit size / 1024 0
null
null
null
null
Question: What do file size return ? Code: def format_size(size): for unit in ('B', 'KB', 'MB', 'GB', 'TB'): if (size < 2048): return ('%.f %s' % (size, unit)) size /= 1024.0
null
null
null
What does the code create next to an existing file ?
@contextmanager def alt_file(current_file): _alt_file = (current_file + '-alt') (yield _alt_file) try: shutil.move(_alt_file, current_file) except IOError: pass
null
null
null
an alternate file
codeqa
@contextmanagerdef alt file current file alt file current file + '-alt' yield alt file try shutil move alt file current file except IO Error pass
null
null
null
null
Question: What does the code create next to an existing file ? Code: @contextmanager def alt_file(current_file): _alt_file = (current_file + '-alt') (yield _alt_file) try: shutil.move(_alt_file, current_file) except IOError: pass
null
null
null
Where does the code create an alternate file ?
@contextmanager def alt_file(current_file): _alt_file = (current_file + '-alt') (yield _alt_file) try: shutil.move(_alt_file, current_file) except IOError: pass
null
null
null
next to an existing file
codeqa
@contextmanagerdef alt file current file alt file current file + '-alt' yield alt file try shutil move alt file current file except IO Error pass
null
null
null
null
Question: Where does the code create an alternate file ? Code: @contextmanager def alt_file(current_file): _alt_file = (current_file + '-alt') (yield _alt_file) try: shutil.move(_alt_file, current_file) except IOError: pass
null
null
null
What does the code create ?
def create_connect_viewer(N, N1, imgs, count, W2): pv = PatchViewer((N, count), imgs.shape[1:3], is_color=(imgs.shape[3] == 3)) for i in xrange(N): w = W2[:, i] wneg = w[(w < 0.0)] wpos = w[(w > 0.0)] w /= np.abs(w).max() wa = np.abs(w) to_sort = zip(wa, range(N1), w) s = sorted(to_sort) for j in xrange(count): idx = s[((N1 - j) - 1)][1] mag = s[((N1 - j) - 1)][2] if (mag > 0): act = (mag, 0) else: act = (0, (- mag)) pv.add_patch(imgs[idx, ...], rescale=True, activation=act) return pv
null
null
null
the patch to show connections between layers
codeqa
def create connect viewer N N1 imgs count W2 pv Patch Viewer N count imgs shape[ 1 3] is color imgs shape[ 3 ] 3 for i in xrange N w W2 [ i]wneg w[ w < 0 0 ]wpos w[ w > 0 0 ]w / np abs w max wa np abs w to sort zip wa range N1 w s sorted to sort for j in xrange count idx s[ N1 - j - 1 ][ 1 ]mag s[ N1 - j - 1 ][ 2 ]if mag > 0 act mag 0 else act 0 - mag pv add patch imgs[idx ] rescale True activation act return pv
null
null
null
null
Question: What does the code create ? Code: def create_connect_viewer(N, N1, imgs, count, W2): pv = PatchViewer((N, count), imgs.shape[1:3], is_color=(imgs.shape[3] == 3)) for i in xrange(N): w = W2[:, i] wneg = w[(w < 0.0)] wpos = w[(w > 0.0)] w /= np.abs(w).max() wa = np.abs(w) to_sort = zip(wa, range(N1), w) s = sorted(to_sort) for j in xrange(count): idx = s[((N1 - j) - 1)][1] mag = s[((N1 - j) - 1)][2] if (mag > 0): act = (mag, 0) else: act = (0, (- mag)) pv.add_patch(imgs[idx, ...], rescale=True, activation=act) return pv
null
null
null
What shows connections between layers ?
def create_connect_viewer(N, N1, imgs, count, W2): pv = PatchViewer((N, count), imgs.shape[1:3], is_color=(imgs.shape[3] == 3)) for i in xrange(N): w = W2[:, i] wneg = w[(w < 0.0)] wpos = w[(w > 0.0)] w /= np.abs(w).max() wa = np.abs(w) to_sort = zip(wa, range(N1), w) s = sorted(to_sort) for j in xrange(count): idx = s[((N1 - j) - 1)][1] mag = s[((N1 - j) - 1)][2] if (mag > 0): act = (mag, 0) else: act = (0, (- mag)) pv.add_patch(imgs[idx, ...], rescale=True, activation=act) return pv
null
null
null
the patch
codeqa
def create connect viewer N N1 imgs count W2 pv Patch Viewer N count imgs shape[ 1 3] is color imgs shape[ 3 ] 3 for i in xrange N w W2 [ i]wneg w[ w < 0 0 ]wpos w[ w > 0 0 ]w / np abs w max wa np abs w to sort zip wa range N1 w s sorted to sort for j in xrange count idx s[ N1 - j - 1 ][ 1 ]mag s[ N1 - j - 1 ][ 2 ]if mag > 0 act mag 0 else act 0 - mag pv add patch imgs[idx ] rescale True activation act return pv
null
null
null
null
Question: What shows connections between layers ? Code: def create_connect_viewer(N, N1, imgs, count, W2): pv = PatchViewer((N, count), imgs.shape[1:3], is_color=(imgs.shape[3] == 3)) for i in xrange(N): w = W2[:, i] wneg = w[(w < 0.0)] wpos = w[(w > 0.0)] w /= np.abs(w).max() wa = np.abs(w) to_sort = zip(wa, range(N1), w) s = sorted(to_sort) for j in xrange(count): idx = s[((N1 - j) - 1)][1] mag = s[((N1 - j) - 1)][2] if (mag > 0): act = (mag, 0) else: act = (0, (- mag)) pv.add_patch(imgs[idx, ...], rescale=True, activation=act) return pv
null
null
null
What can you update ?
@pytest.mark.parametrize('api_version', API_VERSIONS) def test_message_label_updates(db, api_client, default_account, api_version, custom_label): headers = dict() headers['Api-Version'] = api_version gmail_thread = add_fake_thread(db.session, default_account.namespace.id) gmail_message = add_fake_message(db.session, default_account.namespace.id, gmail_thread) resp_data = api_client.get_data('/messages/{}'.format(gmail_message.public_id), headers=headers) assert (resp_data['labels'] == []) category = custom_label.category update = dict(labels=[category.public_id]) resp = api_client.put_data('/messages/{}'.format(gmail_message.public_id), update, headers=headers) resp_data = json.loads(resp.data) if (api_version == API_VERSIONS[0]): assert (len(resp_data['labels']) == 1) assert (resp_data['labels'][0]['id'] == category.public_id) else: assert (resp_data['labels'] == [])
null
null
null
a message
codeqa
@pytest mark parametrize 'api version' API VERSIONS def test message label updates db api client default account api version custom label headers dict headers[' Api- Version'] api versiongmail thread add fake thread db session default account namespace id gmail message add fake message db session default account namespace id gmail thread resp data api client get data '/messages/{}' format gmail message public id headers headers assert resp data['labels'] [] category custom label categoryupdate dict labels [category public id] resp api client put data '/messages/{}' format gmail message public id update headers headers resp data json loads resp data if api version API VERSIONS[ 0 ] assert len resp data['labels'] 1 assert resp data['labels'][ 0 ]['id'] category public id else assert resp data['labels'] []
null
null
null
null
Question: What can you update ? Code: @pytest.mark.parametrize('api_version', API_VERSIONS) def test_message_label_updates(db, api_client, default_account, api_version, custom_label): headers = dict() headers['Api-Version'] = api_version gmail_thread = add_fake_thread(db.session, default_account.namespace.id) gmail_message = add_fake_message(db.session, default_account.namespace.id, gmail_thread) resp_data = api_client.get_data('/messages/{}'.format(gmail_message.public_id), headers=headers) assert (resp_data['labels'] == []) category = custom_label.category update = dict(labels=[category.public_id]) resp = api_client.put_data('/messages/{}'.format(gmail_message.public_id), update, headers=headers) resp_data = json.loads(resp.data) if (api_version == API_VERSIONS[0]): assert (len(resp_data['labels']) == 1) assert (resp_data['labels'][0]['id'] == category.public_id) else: assert (resp_data['labels'] == [])
null
null
null
What does the code get ?
def logical_volume_size(path): (out, _err) = execute('lvs', '-o', 'lv_size', '--noheadings', '--units', 'b', '--nosuffix', path, run_as_root=True) return int(out)
null
null
null
logical volume size in bytes
codeqa
def logical volume size path out err execute 'lvs' '-o' 'lv size' '--noheadings' '--units' 'b' '--nosuffix' path run as root True return int out
null
null
null
null
Question: What does the code get ? Code: def logical_volume_size(path): (out, _err) = execute('lvs', '-o', 'lv_size', '--noheadings', '--units', 'b', '--nosuffix', path, run_as_root=True) return int(out)
null
null
null
What does all dependencies that start with the given task and have a path to upstream_task_family return on all paths between task and upstream ?
def find_deps(task, upstream_task_family): return set([t for t in dfs_paths(task, upstream_task_family)])
null
null
null
all deps
codeqa
def find deps task upstream task family return set [t for t in dfs paths task upstream task family ]
null
null
null
null
Question: What does all dependencies that start with the given task and have a path to upstream_task_family return on all paths between task and upstream ? Code: def find_deps(task, upstream_task_family): return set([t for t in dfs_paths(task, upstream_task_family)])
null
null
null
What have a path to upstream_task_family ?
def find_deps(task, upstream_task_family): return set([t for t in dfs_paths(task, upstream_task_family)])
null
null
null
all dependencies
codeqa
def find deps task upstream task family return set [t for t in dfs paths task upstream task family ]
null
null
null
null
Question: What have a path to upstream_task_family ? Code: def find_deps(task, upstream_task_family): return set([t for t in dfs_paths(task, upstream_task_family)])
null
null
null
What do all dependencies have ?
def find_deps(task, upstream_task_family): return set([t for t in dfs_paths(task, upstream_task_family)])
null
null
null
a path to upstream_task_family
codeqa
def find deps task upstream task family return set [t for t in dfs paths task upstream task family ]
null
null
null
null
Question: What do all dependencies have ? Code: def find_deps(task, upstream_task_family): return set([t for t in dfs_paths(task, upstream_task_family)])
null
null
null
Where does all dependencies that start with the given task and have a path to upstream_task_family return all deps ?
def find_deps(task, upstream_task_family): return set([t for t in dfs_paths(task, upstream_task_family)])
null
null
null
on all paths between task and upstream
codeqa
def find deps task upstream task family return set [t for t in dfs paths task upstream task family ]
null
null
null
null
Question: Where does all dependencies that start with the given task and have a path to upstream_task_family return all deps ? Code: def find_deps(task, upstream_task_family): return set([t for t in dfs_paths(task, upstream_task_family)])
null
null
null
What returns all deps on all paths between task and upstream ?
def find_deps(task, upstream_task_family): return set([t for t in dfs_paths(task, upstream_task_family)])
null
null
null
all dependencies that start with the given task and have a path to upstream_task_family
codeqa
def find deps task upstream task family return set [t for t in dfs paths task upstream task family ]
null
null
null
null
Question: What returns all deps on all paths between task and upstream ? Code: def find_deps(task, upstream_task_family): return set([t for t in dfs_paths(task, upstream_task_family)])
null
null
null
When is an error raised ?
def test_ee_fit_invalid_ratio(): ratio = (1.0 / 10000.0) ee = EasyEnsemble(ratio=ratio, random_state=RND_SEED) assert_raises(RuntimeError, ee.fit, X, Y)
null
null
null
when the balancing ratio to fit is smaller than the one of the data
codeqa
def test ee fit invalid ratio ratio 1 0 / 10000 0 ee Easy Ensemble ratio ratio random state RND SEED assert raises Runtime Error ee fit X Y
null
null
null
null
Question: When is an error raised ? Code: def test_ee_fit_invalid_ratio(): ratio = (1.0 / 10000.0) ee = EasyEnsemble(ratio=ratio, random_state=RND_SEED) assert_raises(RuntimeError, ee.fit, X, Y)
null
null
null
When did it call ?
def get_default_metaschema(): try: return models.MetaSchema.find()[0] except IndexError: ensure_schemas() return models.MetaSchema.find()[0]
null
null
null
after the test database is set up
codeqa
def get default metaschema try return models Meta Schema find [0 ]except Index Error ensure schemas return models Meta Schema find [0 ]
null
null
null
null
Question: When did it call ? Code: def get_default_metaschema(): try: return models.MetaSchema.find()[0] except IndexError: ensure_schemas() return models.MetaSchema.find()[0]
null
null
null
What does the code get ?
def extras_require(): return {x: extras((x + '.txt')) for x in EXTENSIONS}
null
null
null
map of all extra requirements
codeqa
def extras require return {x extras x + ' txt' for x in EXTENSIONS}
null
null
null
null
Question: What does the code get ? Code: def extras_require(): return {x: extras((x + '.txt')) for x in EXTENSIONS}
null
null
null
What did the code set ?
def setup(): global unblocked_list, blocked_list top = Toplevel() top.title('MAC Blocker') top.protocol('WM_DELETE_WINDOW', core.quit) box1 = Frame(top) box2 = Frame(top) l1 = Label(box1, text='Allowed') l2 = Label(box2, text='Blocked') unblocked_list = Listbox(box1) blocked_list = Listbox(box2) l1.pack() l2.pack() unblocked_list.pack(expand=True, fill=BOTH) blocked_list.pack(expand=True, fill=BOTH) buttons = Frame(top) block_button = Button(buttons, text='Block >>', command=do_block) unblock_button = Button(buttons, text='<< Unblock', command=do_unblock) block_button.pack() unblock_button.pack() opts = {'side': LEFT, 'fill': BOTH, 'expand': True} box1.pack(**opts) buttons.pack(**{'side': LEFT}) box2.pack(**opts) core.getLogger().debug('Ready')
null
null
null
gui
codeqa
def setup global unblocked list blocked listtop Toplevel top title 'MAC Blocker' top protocol 'WM DELETE WINDOW' core quit box 1 Frame top box 2 Frame top l1 Label box 1 text ' Allowed' l2 Label box 2 text ' Blocked' unblocked list Listbox box 1 blocked list Listbox box 2 l1 pack l2 pack unblocked list pack expand True fill BOTH blocked list pack expand True fill BOTH buttons Frame top block button Button buttons text ' Block>>' command do block unblock button Button buttons text '<< Unblock' command do unblock block button pack unblock button pack opts {'side' LEFT 'fill' BOTH 'expand' True}box 1 pack **opts buttons pack **{'side' LEFT} box 2 pack **opts core get Logger debug ' Ready'
null
null
null
null
Question: What did the code set ? Code: def setup(): global unblocked_list, blocked_list top = Toplevel() top.title('MAC Blocker') top.protocol('WM_DELETE_WINDOW', core.quit) box1 = Frame(top) box2 = Frame(top) l1 = Label(box1, text='Allowed') l2 = Label(box2, text='Blocked') unblocked_list = Listbox(box1) blocked_list = Listbox(box2) l1.pack() l2.pack() unblocked_list.pack(expand=True, fill=BOTH) blocked_list.pack(expand=True, fill=BOTH) buttons = Frame(top) block_button = Button(buttons, text='Block >>', command=do_block) unblock_button = Button(buttons, text='<< Unblock', command=do_unblock) block_button.pack() unblock_button.pack() opts = {'side': LEFT, 'fill': BOTH, 'expand': True} box1.pack(**opts) buttons.pack(**{'side': LEFT}) box2.pack(**opts) core.getLogger().debug('Ready')
null
null
null
What does the code generate ?
def textListToColorsSimple(names): uNames = list(set(names)) uNames.sort() textToColor = [uNames.index(n) for n in names] textToColor = np.array(textToColor) textToColor = ((255 * (textToColor - textToColor.min())) / (textToColor.max() - textToColor.min())) textmaps = generateColorMap() colors = [textmaps[int(c)] for c in textToColor] return colors
null
null
null
a list of colors based on a list of names
codeqa
def text List To Colors Simple names u Names list set names u Names sort text To Color [u Names index n for n in names]text To Color np array text To Color text To Color 255 * text To Color - text To Color min / text To Color max - text To Color min textmaps generate Color Map colors [textmaps[int c ] for c in text To Color]return colors
null
null
null
null
Question: What does the code generate ? Code: def textListToColorsSimple(names): uNames = list(set(names)) uNames.sort() textToColor = [uNames.index(n) for n in names] textToColor = np.array(textToColor) textToColor = ((255 * (textToColor - textToColor.min())) / (textToColor.max() - textToColor.min())) textmaps = generateColorMap() colors = [textmaps[int(c)] for c in textToColor] return colors
null
null
null
What does the code remove ?
def rm_job(user, cmd, minute=None, hour=None, daymonth=None, month=None, dayweek=None, identifier=None): lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if (rm_ is not None): break if _cron_matched(lst['crons'][ind], cmd, identifier=identifier): if (not any([(x is not None) for x in (minute, hour, daymonth, month, dayweek)])): rm_ = ind elif _date_time_match(lst['crons'][ind], minute=minute, hour=hour, daymonth=daymonth, month=month, dayweek=dayweek): rm_ = ind if (rm_ is not None): lst['crons'].pop(rm_) ret = 'removed' comdat = _write_cron_lines(user, _render_tab(lst)) if comdat['retcode']: return comdat['stderr'] return ret
null
null
null
a cron job
codeqa
def rm job user cmd minute None hour None daymonth None month None dayweek None identifier None lst list tab user ret 'absent'rm Nonefor ind in range len lst['crons'] if rm is not None breakif cron matched lst['crons'][ind] cmd identifier identifier if not any [ x is not None for x in minute hour daymonth month dayweek ] rm indelif date time match lst['crons'][ind] minute minute hour hour daymonth daymonth month month dayweek dayweek rm indif rm is not None lst['crons'] pop rm ret 'removed'comdat write cron lines user render tab lst if comdat['retcode'] return comdat['stderr']return ret
null
null
null
null
Question: What does the code remove ? Code: def rm_job(user, cmd, minute=None, hour=None, daymonth=None, month=None, dayweek=None, identifier=None): lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if (rm_ is not None): break if _cron_matched(lst['crons'][ind], cmd, identifier=identifier): if (not any([(x is not None) for x in (minute, hour, daymonth, month, dayweek)])): rm_ = ind elif _date_time_match(lst['crons'][ind], minute=minute, hour=hour, daymonth=daymonth, month=month, dayweek=dayweek): rm_ = ind if (rm_ is not None): lst['crons'].pop(rm_) ret = 'removed' comdat = _write_cron_lines(user, _render_tab(lst)) if comdat['retcode']: return comdat['stderr'] return ret
null
null
null
What do user provide ?
def _step_parameters(step, param_map, legacy=False): param_dict = param_map.get(step.tool_id, {}).copy() if legacy: param_dict.update(param_map.get(str(step.id), {})) else: param_dict.update(param_map.get(str(step.order_index), {})) step_uuid = step.uuid if step_uuid: uuid_params = param_map.get(str(step_uuid), {}) param_dict.update(uuid_params) if param_dict: if (('param' in param_dict) and ('value' in param_dict)): param_dict[param_dict['param']] = param_dict['value'] del param_dict['param'] del param_dict['value'] new_params = _flatten_step_params(param_dict) return new_params
null
null
null
param_map dict
codeqa
def step parameters step param map legacy False param dict param map get step tool id {} copy if legacy param dict update param map get str step id {} else param dict update param map get str step order index {} step uuid step uuidif step uuid uuid params param map get str step uuid {} param dict update uuid params if param dict if 'param' in param dict and 'value' in param dict param dict[param dict['param']] param dict['value']del param dict['param']del param dict['value']new params flatten step params param dict return new params
null
null
null
null
Question: What do user provide ? Code: def _step_parameters(step, param_map, legacy=False): param_dict = param_map.get(step.tool_id, {}).copy() if legacy: param_dict.update(param_map.get(str(step.id), {})) else: param_dict.update(param_map.get(str(step.order_index), {})) step_uuid = step.uuid if step_uuid: uuid_params = param_map.get(str(step_uuid), {}) param_dict.update(uuid_params) if param_dict: if (('param' in param_dict) and ('value' in param_dict)): param_dict[param_dict['param']] = param_dict['value'] del param_dict['param'] del param_dict['value'] new_params = _flatten_step_params(param_dict) return new_params
null
null
null
How do the vagrant user run commands ?
@pytest.fixture(scope='session', autouse=True) def allow_sudo_user(setup_package): from fabtools.require import file as require_file require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
null
null
null
as root
codeqa
@pytest fixture scope 'session' autouse True def allow sudo user setup package from fabtools require import file as require filerequire file '/etc/sudoers d/fabtools' contents 'vagrant ALL ALL NOPASSWD ALL\n' owner 'root' mode '440 ' use sudo True
null
null
null
null
Question: How do the vagrant user run commands ? Code: @pytest.fixture(scope='session', autouse=True) def allow_sudo_user(setup_package): from fabtools.require import file as require_file require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
null
null
null
What allows the vagrant user to run commands as root only ?
@pytest.fixture(scope='session', autouse=True) def allow_sudo_user(setup_package): from fabtools.require import file as require_file require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
null
null
null
some vagrant boxes
codeqa
@pytest fixture scope 'session' autouse True def allow sudo user setup package from fabtools require import file as require filerequire file '/etc/sudoers d/fabtools' contents 'vagrant ALL ALL NOPASSWD ALL\n' owner 'root' mode '440 ' use sudo True
null
null
null
null
Question: What allows the vagrant user to run commands as root only ? Code: @pytest.fixture(scope='session', autouse=True) def allow_sudo_user(setup_package): from fabtools.require import file as require_file require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
null
null
null
What runs commands as root ?
@pytest.fixture(scope='session', autouse=True) def allow_sudo_user(setup_package): from fabtools.require import file as require_file require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
null
null
null
the vagrant user
codeqa
@pytest fixture scope 'session' autouse True def allow sudo user setup package from fabtools require import file as require filerequire file '/etc/sudoers d/fabtools' contents 'vagrant ALL ALL NOPASSWD ALL\n' owner 'root' mode '440 ' use sudo True
null
null
null
null
Question: What runs commands as root ? Code: @pytest.fixture(scope='session', autouse=True) def allow_sudo_user(setup_package): from fabtools.require import file as require_file require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
null
null
null
What do some vagrant boxes allow only ?
@pytest.fixture(scope='session', autouse=True) def allow_sudo_user(setup_package): from fabtools.require import file as require_file require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
null
null
null
the vagrant user to run commands as root
codeqa
@pytest fixture scope 'session' autouse True def allow sudo user setup package from fabtools require import file as require filerequire file '/etc/sudoers d/fabtools' contents 'vagrant ALL ALL NOPASSWD ALL\n' owner 'root' mode '440 ' use sudo True
null
null
null
null
Question: What do some vagrant boxes allow only ? Code: @pytest.fixture(scope='session', autouse=True) def allow_sudo_user(setup_package): from fabtools.require import file as require_file require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
null
null
null
What do the vagrant user run as root ?
@pytest.fixture(scope='session', autouse=True) def allow_sudo_user(setup_package): from fabtools.require import file as require_file require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
null
null
null
commands
codeqa
@pytest fixture scope 'session' autouse True def allow sudo user setup package from fabtools require import file as require filerequire file '/etc/sudoers d/fabtools' contents 'vagrant ALL ALL NOPASSWD ALL\n' owner 'root' mode '440 ' use sudo True
null
null
null
null
Question: What do the vagrant user run as root ? Code: @pytest.fixture(scope='session', autouse=True) def allow_sudo_user(setup_package): from fabtools.require import file as require_file require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
null
null
null
What may occur in more than one dict ?
def merge_with(func, *dicts, **kwargs): if ((len(dicts) == 1) and (not isinstance(dicts[0], dict))): dicts = dicts[0] factory = _get_factory(merge_with, kwargs) result = factory() for d in dicts: for (k, v) in iteritems(d): if (k not in result): result[k] = [v] else: result[k].append(v) return valmap(func, result, factory)
null
null
null
a key
codeqa
def merge with func *dicts **kwargs if len dicts 1 and not isinstance dicts[ 0 ] dict dicts dicts[ 0 ]factory get factory merge with kwargs result factory for d in dicts for k v in iteritems d if k not in result result[k] [v]else result[k] append v return valmap func result factory
null
null
null
null
Question: What may occur in more than one dict ? Code: def merge_with(func, *dicts, **kwargs): if ((len(dicts) == 1) and (not isinstance(dicts[0], dict))): dicts = dicts[0] factory = _get_factory(merge_with, kwargs) result = factory() for d in dicts: for (k, v) in iteritems(d): if (k not in result): result[k] = [v] else: result[k].append(v) return valmap(func, result, factory)
null
null
null
Where may a key occur ?
def merge_with(func, *dicts, **kwargs): if ((len(dicts) == 1) and (not isinstance(dicts[0], dict))): dicts = dicts[0] factory = _get_factory(merge_with, kwargs) result = factory() for d in dicts: for (k, v) in iteritems(d): if (k not in result): result[k] = [v] else: result[k].append(v) return valmap(func, result, factory)
null
null
null
in more than one dict
codeqa
def merge with func *dicts **kwargs if len dicts 1 and not isinstance dicts[ 0 ] dict dicts dicts[ 0 ]factory get factory merge with kwargs result factory for d in dicts for k v in iteritems d if k not in result result[k] [v]else result[k] append v return valmap func result factory
null
null
null
null
Question: Where may a key occur ? Code: def merge_with(func, *dicts, **kwargs): if ((len(dicts) == 1) and (not isinstance(dicts[0], dict))): dicts = dicts[0] factory = _get_factory(merge_with, kwargs) result = factory() for d in dicts: for (k, v) in iteritems(d): if (k not in result): result[k] = [v] else: result[k].append(v) return valmap(func, result, factory)
null
null
null
What does the code make ?
def MakeCASignedCert(common_name, private_key, ca_cert, ca_private_key, serial_number=2): public_key = private_key.GetPublicKey() builder = x509.CertificateBuilder() builder = builder.issuer_name(ca_cert.GetIssuer()) subject = x509.Name([x509.NameAttribute(oid.NameOID.COMMON_NAME, common_name)]) builder = builder.subject_name(subject) valid_from = (rdfvalue.RDFDatetime.Now() - rdfvalue.Duration('1d')) valid_until = (rdfvalue.RDFDatetime.Now() + rdfvalue.Duration('3650d')) builder = builder.not_valid_before(valid_from.AsDatetime()) builder = builder.not_valid_after(valid_until.AsDatetime()) builder = builder.serial_number(serial_number) builder = builder.public_key(public_key.GetRawPublicKey()) builder = builder.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) certificate = builder.sign(private_key=ca_private_key.GetRawPrivateKey(), algorithm=hashes.SHA256(), backend=openssl.backend) return rdf_crypto.RDFX509Cert(certificate)
null
null
null
a cert
codeqa
def Make CA Signed Cert common name private key ca cert ca private key serial number 2 public key private key Get Public Key builder x509 Certificate Builder builder builder issuer name ca cert Get Issuer subject x509 Name [x 509 Name Attribute oid Name OID COMMON NAME common name ] builder builder subject name subject valid from rdfvalue RDF Datetime Now - rdfvalue Duration '1 d' valid until rdfvalue RDF Datetime Now + rdfvalue Duration '3650 d' builder builder not valid before valid from As Datetime builder builder not valid after valid until As Datetime builder builder serial number serial number builder builder public key public key Get Raw Public Key builder builder add extension x509 Basic Constraints ca False path length None critical True certificate builder sign private key ca private key Get Raw Private Key algorithm hashes SHA 256 backend openssl backend return rdf crypto RDFX 509 Cert certificate
null
null
null
null
Question: What does the code make ? Code: def MakeCASignedCert(common_name, private_key, ca_cert, ca_private_key, serial_number=2): public_key = private_key.GetPublicKey() builder = x509.CertificateBuilder() builder = builder.issuer_name(ca_cert.GetIssuer()) subject = x509.Name([x509.NameAttribute(oid.NameOID.COMMON_NAME, common_name)]) builder = builder.subject_name(subject) valid_from = (rdfvalue.RDFDatetime.Now() - rdfvalue.Duration('1d')) valid_until = (rdfvalue.RDFDatetime.Now() + rdfvalue.Duration('3650d')) builder = builder.not_valid_before(valid_from.AsDatetime()) builder = builder.not_valid_after(valid_until.AsDatetime()) builder = builder.serial_number(serial_number) builder = builder.public_key(public_key.GetRawPublicKey()) builder = builder.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) certificate = builder.sign(private_key=ca_private_key.GetRawPrivateKey(), algorithm=hashes.SHA256(), backend=openssl.backend) return rdf_crypto.RDFX509Cert(certificate)
null
null
null
What must test raise ?
def raises(*exceptions): valid = ' or '.join([e.__name__ for e in exceptions]) def decorate(func): name = func.__name__ def newfunc(*arg, **kw): try: func(*arg, **kw) except exceptions: pass else: message = '{}() did not raise {}'.format(name, valid) raise AssertionError(message) newfunc = make_decorator(func)(newfunc) return newfunc return decorate
null
null
null
one of expected exceptions to pass
codeqa
def raises *exceptions valid 'or' join [e name for e in exceptions] def decorate func name func name def newfunc *arg **kw try func *arg **kw except exceptions passelse message '{} didnotraise{}' format name valid raise Assertion Error message newfunc make decorator func newfunc return newfuncreturn decorate
null
null
null
null
Question: What must test raise ? Code: def raises(*exceptions): valid = ' or '.join([e.__name__ for e in exceptions]) def decorate(func): name = func.__name__ def newfunc(*arg, **kw): try: func(*arg, **kw) except exceptions: pass else: message = '{}() did not raise {}'.format(name, valid) raise AssertionError(message) newfunc = make_decorator(func)(newfunc) return newfunc return decorate
null
null
null
What does the code ensure ?
def populate_project_info(attributes): if (('tenant_id' in attributes) and ('project_id' not in attributes)): attributes['project_id'] = attributes['tenant_id'] elif (('project_id' in attributes) and ('tenant_id' not in attributes)): attributes['tenant_id'] = attributes['project_id'] if (attributes.get('project_id') != attributes.get('tenant_id')): msg = _("'project_id' and 'tenant_id' do not match") raise webob.exc.HTTPBadRequest(msg) return attributes
null
null
null
that both project_id and tenant_id attributes are present
codeqa
def populate project info attributes if 'tenant id' in attributes and 'project id' not in attributes attributes['project id'] attributes['tenant id']elif 'project id' in attributes and 'tenant id' not in attributes attributes['tenant id'] attributes['project id']if attributes get 'project id' attributes get 'tenant id' msg "'project id'and'tenant id'donotmatch" raise webob exc HTTP Bad Request msg return attributes
null
null
null
null
Question: What does the code ensure ? Code: def populate_project_info(attributes): if (('tenant_id' in attributes) and ('project_id' not in attributes)): attributes['project_id'] = attributes['tenant_id'] elif (('project_id' in attributes) and ('tenant_id' not in attributes)): attributes['tenant_id'] = attributes['project_id'] if (attributes.get('project_id') != attributes.get('tenant_id')): msg = _("'project_id' and 'tenant_id' do not match") raise webob.exc.HTTPBadRequest(msg) return attributes
null
null
null
Where does the shortest path return from source to target ?
def bellman_ford_path(G, source, target, weight='weight'): (lengths, paths) = single_source_bellman_ford(G, source, target=target, weight=weight) try: return paths[target] except KeyError: raise nx.NetworkXNoPath(('Node %s not reachable from %s' % (source, target)))
null
null
null
in a weighted graph g
codeqa
def bellman ford path G source target weight 'weight' lengths paths single source bellman ford G source target target weight weight try return paths[target]except Key Error raise nx Network X No Path ' Node%snotreachablefrom%s' % source target
null
null
null
null
Question: Where does the shortest path return from source to target ? Code: def bellman_ford_path(G, source, target, weight='weight'): (lengths, paths) = single_source_bellman_ford(G, source, target=target, weight=weight) try: return paths[target] except KeyError: raise nx.NetworkXNoPath(('Node %s not reachable from %s' % (source, target)))
null
null
null
In which direction does the shortest path return in a weighted graph g ?
def bellman_ford_path(G, source, target, weight='weight'): (lengths, paths) = single_source_bellman_ford(G, source, target=target, weight=weight) try: return paths[target] except KeyError: raise nx.NetworkXNoPath(('Node %s not reachable from %s' % (source, target)))
null
null
null
from source to target
codeqa
def bellman ford path G source target weight 'weight' lengths paths single source bellman ford G source target target weight weight try return paths[target]except Key Error raise nx Network X No Path ' Node%snotreachablefrom%s' % source target
null
null
null
null
Question: In which direction does the shortest path return in a weighted graph g ? Code: def bellman_ford_path(G, source, target, weight='weight'): (lengths, paths) = single_source_bellman_ford(G, source, target=target, weight=weight) try: return paths[target] except KeyError: raise nx.NetworkXNoPath(('Node %s not reachable from %s' % (source, target)))
null
null
null
What returns in a weighted graph g ?
def bellman_ford_path(G, source, target, weight='weight'): (lengths, paths) = single_source_bellman_ford(G, source, target=target, weight=weight) try: return paths[target] except KeyError: raise nx.NetworkXNoPath(('Node %s not reachable from %s' % (source, target)))
null
null
null
the shortest path
codeqa
def bellman ford path G source target weight 'weight' lengths paths single source bellman ford G source target target weight weight try return paths[target]except Key Error raise nx Network X No Path ' Node%snotreachablefrom%s' % source target
null
null
null
null
Question: What returns in a weighted graph g ? Code: def bellman_ford_path(G, source, target, weight='weight'): (lengths, paths) = single_source_bellman_ford(G, source, target=target, weight=weight) try: return paths[target] except KeyError: raise nx.NetworkXNoPath(('Node %s not reachable from %s' % (source, target)))
null
null
null
What does the code escape from the path portion of a uniform resource identifier ?
def escape_uri_path(path): return quote(force_bytes(path), safe="/:@&+$,-_.!~*'()")
null
null
null
the unsafe characters
codeqa
def escape uri path path return quote force bytes path safe "/ @&+$ - ~*' "
null
null
null
null
Question: What does the code escape from the path portion of a uniform resource identifier ? Code: def escape_uri_path(path): return quote(force_bytes(path), safe="/:@&+$,-_.!~*'()")
null
null
null
What does the code get ?
def action_get_by_request_id(context, uuid, request_id): return IMPL.action_get_by_request_id(context, uuid, request_id)
null
null
null
the action
codeqa
def action get by request id context uuid request id return IMPL action get by request id context uuid request id
null
null
null
null
Question: What does the code get ? Code: def action_get_by_request_id(context, uuid, request_id): return IMPL.action_get_by_request_id(context, uuid, request_id)
null
null
null
What is existing on this computer ?
def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise StopIteration for i in itertools.count(): try: val = winreg.EnumValue(key, i) (yield str(val[1])) except EnvironmentError: break
null
null
null
serial ports
codeqa
def enumerate serial ports path 'HARDWARE\\DEVICEMAP\\SERIALCOMM'try key winreg Open Key winreg HKEY LOCAL MACHINE path except Windows Error raise Stop Iterationfor i in itertools count try val winreg Enum Value key i yield str val[ 1 ] except Environment Error break
null
null
null
null
Question: What is existing on this computer ? Code: def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise StopIteration for i in itertools.count(): try: val = winreg.EnumValue(key, i) (yield str(val[1])) except EnvironmentError: break
null
null
null
What does the code use the win32 registry ?
def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise StopIteration for i in itertools.count(): try: val = winreg.EnumValue(key, i) (yield str(val[1])) except EnvironmentError: break
null
null
null
to return an iterator of serial ports existing on this computer
codeqa
def enumerate serial ports path 'HARDWARE\\DEVICEMAP\\SERIALCOMM'try key winreg Open Key winreg HKEY LOCAL MACHINE path except Windows Error raise Stop Iterationfor i in itertools count try val winreg Enum Value key i yield str val[ 1 ] except Environment Error break
null
null
null
null
Question: What does the code use the win32 registry ? Code: def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise StopIteration for i in itertools.count(): try: val = winreg.EnumValue(key, i) (yield str(val[1])) except EnvironmentError: break
null
null
null
What does the code use to return an iterator of serial ports existing on this computer ?
def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise StopIteration for i in itertools.count(): try: val = winreg.EnumValue(key, i) (yield str(val[1])) except EnvironmentError: break
null
null
null
the win32 registry
codeqa
def enumerate serial ports path 'HARDWARE\\DEVICEMAP\\SERIALCOMM'try key winreg Open Key winreg HKEY LOCAL MACHINE path except Windows Error raise Stop Iterationfor i in itertools count try val winreg Enum Value key i yield str val[ 1 ] except Environment Error break
null
null
null
null
Question: What does the code use to return an iterator of serial ports existing on this computer ? Code: def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise StopIteration for i in itertools.count(): try: val = winreg.EnumValue(key, i) (yield str(val[1])) except EnvironmentError: break
null
null
null
Where do serial ports exist ?
def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise StopIteration for i in itertools.count(): try: val = winreg.EnumValue(key, i) (yield str(val[1])) except EnvironmentError: break
null
null
null
on this computer
codeqa
def enumerate serial ports path 'HARDWARE\\DEVICEMAP\\SERIALCOMM'try key winreg Open Key winreg HKEY LOCAL MACHINE path except Windows Error raise Stop Iterationfor i in itertools count try val winreg Enum Value key i yield str val[ 1 ] except Environment Error break
null
null
null
null
Question: Where do serial ports exist ? Code: def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise StopIteration for i in itertools.count(): try: val = winreg.EnumValue(key, i) (yield str(val[1])) except EnvironmentError: break
null
null
null
What does the code return ?
def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise StopIteration for i in itertools.count(): try: val = winreg.EnumValue(key, i) (yield str(val[1])) except EnvironmentError: break
null
null
null
an iterator of serial ports existing on this computer
codeqa
def enumerate serial ports path 'HARDWARE\\DEVICEMAP\\SERIALCOMM'try key winreg Open Key winreg HKEY LOCAL MACHINE path except Windows Error raise Stop Iterationfor i in itertools count try val winreg Enum Value key i yield str val[ 1 ] except Environment Error break
null
null
null
null
Question: What does the code return ? Code: def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise StopIteration for i in itertools.count(): try: val = winreg.EnumValue(key, i) (yield str(val[1])) except EnvironmentError: break
null
null
null
What does the code sanitize ?
def strip_html(unclean): if ((not isinstance(unclean, basestring)) and (not is_iterable(unclean)) and (unclean is not None)): return unclean return bleach.clean(unclean, strip=True, tags=[], attributes=[], styles=[])
null
null
null
a string
codeqa
def strip html unclean if not isinstance unclean basestring and not is iterable unclean and unclean is not None return uncleanreturn bleach clean unclean strip True tags [] attributes [] styles []
null
null
null
null
Question: What does the code sanitize ? Code: def strip_html(unclean): if ((not isinstance(unclean, basestring)) and (not is_iterable(unclean)) and (unclean is not None)): return unclean return bleach.clean(unclean, strip=True, tags=[], attributes=[], styles=[])
null
null
null
What does the code return ?
def tex_coords(top, bottom, side): top = tex_coord(*top) bottom = tex_coord(*bottom) side = tex_coord(*side) result = [] result.extend(top) result.extend(bottom) result.extend((side * 4)) return result
null
null
null
a list of the texture squares for the top
codeqa
def tex coords top bottom side top tex coord *top bottom tex coord *bottom side tex coord *side result []result extend top result extend bottom result extend side * 4 return result
null
null
null
null
Question: What does the code return ? Code: def tex_coords(top, bottom, side): top = tex_coord(*top) bottom = tex_coord(*bottom) side = tex_coord(*side) result = [] result.extend(top) result.extend(bottom) result.extend((side * 4)) return result
null
null
null
What has surpassed its pending time ?
def should_be_approved(pending_registration): return ((timezone.now() - pending_registration.initiation_date) >= settings.REGISTRATION_APPROVAL_TIME)
null
null
null
pending_registration
codeqa
def should be approved pending registration return timezone now - pending registration initiation date > settings REGISTRATION APPROVAL TIME
null
null
null
null
Question: What has surpassed its pending time ? Code: def should_be_approved(pending_registration): return ((timezone.now() - pending_registration.initiation_date) >= settings.REGISTRATION_APPROVAL_TIME)
null
null
null
What does the code make ?
def make_test_case(base_case): class FooTests(base_case, ): def test_something(self): pass return FooTests('test_something')
null
null
null
a single test that subclasses base_case and passes
codeqa
def make test case base case class Foo Tests base case def test something self passreturn Foo Tests 'test something'
null
null
null
null
Question: What does the code make ? Code: def make_test_case(base_case): class FooTests(base_case, ): def test_something(self): pass return FooTests('test_something')
null
null
null
How do cliques remove from the graph ?
def clique_removal(G): graph = G.copy(with_data=False) (c_i, i_i) = ramsey.ramsey_R2(graph) cliques = [c_i] isets = [i_i] while graph: graph.remove_nodes_from(c_i) (c_i, i_i) = ramsey.ramsey_R2(graph) if c_i: cliques.append(c_i) if i_i: isets.append(i_i) maxiset = max(isets, key=len) return (maxiset, cliques)
null
null
null
repeatedly
codeqa
def clique removal G graph G copy with data False c i i i ramsey ramsey R2 graph cliques [c i]isets [i i]while graph graph remove nodes from c i c i i i ramsey ramsey R2 graph if c i cliques append c i if i i isets append i i maxiset max isets key len return maxiset cliques
null
null
null
null
Question: How do cliques remove from the graph ? Code: def clique_removal(G): graph = G.copy(with_data=False) (c_i, i_i) = ramsey.ramsey_R2(graph) cliques = [c_i] isets = [i_i] while graph: graph.remove_nodes_from(c_i) (c_i, i_i) = ramsey.ramsey_R2(graph) if c_i: cliques.append(c_i) if i_i: isets.append(i_i) maxiset = max(isets, key=len) return (maxiset, cliques)
null
null
null
What casts wrapped arguments to a1 notation in range method calls ?
def cast_to_a1_notation(method): @wraps(method) def wrapper(self, *args, **kwargs): try: if len(args): int(args[0]) range_start = rowcol_to_a1(*args[:2]) range_end = rowcol_to_a1(*args[(-2):]) range_name = ':'.join((range_start, range_end)) args = ((range_name,) + args[4:]) except ValueError: pass return method(self, *args, **kwargs) return wrapper
null
null
null
decorator function
codeqa
def cast to a1 notation method @wraps method def wrapper self *args **kwargs try if len args int args[ 0 ] range start rowcol to a1 *args[ 2] range end rowcol to a1 *args[ -2 ] range name ' ' join range start range end args range name + args[ 4 ] except Value Error passreturn method self *args **kwargs return wrapper
null
null
null
null
Question: What casts wrapped arguments to a1 notation in range method calls ? Code: def cast_to_a1_notation(method): @wraps(method) def wrapper(self, *args, **kwargs): try: if len(args): int(args[0]) range_start = rowcol_to_a1(*args[:2]) range_end = rowcol_to_a1(*args[(-2):]) range_name = ':'.join((range_start, range_end)) args = ((range_name,) + args[4:]) except ValueError: pass return method(self, *args, **kwargs) return wrapper
null
null
null
What does decorator function cast to a1 notation in range method calls ?
def cast_to_a1_notation(method): @wraps(method) def wrapper(self, *args, **kwargs): try: if len(args): int(args[0]) range_start = rowcol_to_a1(*args[:2]) range_end = rowcol_to_a1(*args[(-2):]) range_name = ':'.join((range_start, range_end)) args = ((range_name,) + args[4:]) except ValueError: pass return method(self, *args, **kwargs) return wrapper
null
null
null
wrapped arguments
codeqa
def cast to a1 notation method @wraps method def wrapper self *args **kwargs try if len args int args[ 0 ] range start rowcol to a1 *args[ 2] range end rowcol to a1 *args[ -2 ] range name ' ' join range start range end args range name + args[ 4 ] except Value Error passreturn method self *args **kwargs return wrapper
null
null
null
null
Question: What does decorator function cast to a1 notation in range method calls ? Code: def cast_to_a1_notation(method): @wraps(method) def wrapper(self, *args, **kwargs): try: if len(args): int(args[0]) range_start = rowcol_to_a1(*args[:2]) range_end = rowcol_to_a1(*args[(-2):]) range_name = ':'.join((range_start, range_end)) args = ((range_name,) + args[4:]) except ValueError: pass return method(self, *args, **kwargs) return wrapper
null
null
null
What enables notifications for the authenticated user ?
@require_POST def ajax_enable(request): if (not request.user.is_authenticated()): raise PermissionDenied enable_notifications(request.user) return HttpResponse(status=204)
null
null
null
a view
codeqa
@require POS Tdef ajax enable request if not request user is authenticated raise Permission Deniedenable notifications request user return Http Response status 204
null
null
null
null
Question: What enables notifications for the authenticated user ? Code: @require_POST def ajax_enable(request): if (not request.user.is_authenticated()): raise PermissionDenied enable_notifications(request.user) return HttpResponse(status=204)
null
null
null
What does a view enable ?
@require_POST def ajax_enable(request): if (not request.user.is_authenticated()): raise PermissionDenied enable_notifications(request.user) return HttpResponse(status=204)
null
null
null
notifications for the authenticated user
codeqa
@require POS Tdef ajax enable request if not request user is authenticated raise Permission Deniedenable notifications request user return Http Response status 204
null
null
null
null
Question: What does a view enable ? Code: @require_POST def ajax_enable(request): if (not request.user.is_authenticated()): raise PermissionDenied enable_notifications(request.user) return HttpResponse(status=204)
null
null
null
What can edit documents ?
def create_document_editor_group(): (group, group_created) = Group.objects.get_or_create(name='editor') if group_created: actions = ('add', 'change', 'delete', 'view', 'restore') perms = [Permission.objects.get(codename=('%s_document' % action)) for action in actions] group.permissions = perms group.save() return group
null
null
null
a group
codeqa
def create document editor group group group created Group objects get or create name 'editor' if group created actions 'add' 'change' 'delete' 'view' 'restore' perms [ Permission objects get codename '%s document' % action for action in actions]group permissions permsgroup save return group
null
null
null
null
Question: What can edit documents ? Code: def create_document_editor_group(): (group, group_created) = Group.objects.get_or_create(name='editor') if group_created: actions = ('add', 'change', 'delete', 'view', 'restore') perms = [Permission.objects.get(codename=('%s_document' % action)) for action in actions] group.permissions = perms group.save() return group
null
null
null
What does the code get ?
def create_document_editor_group(): (group, group_created) = Group.objects.get_or_create(name='editor') if group_created: actions = ('add', 'change', 'delete', 'view', 'restore') perms = [Permission.objects.get(codename=('%s_document' % action)) for action in actions] group.permissions = perms group.save() return group
null
null
null
a group that can edit documents
codeqa
def create document editor group group group created Group objects get or create name 'editor' if group created actions 'add' 'change' 'delete' 'view' 'restore' perms [ Permission objects get codename '%s document' % action for action in actions]group permissions permsgroup save return group
null
null
null
null
Question: What does the code get ? Code: def create_document_editor_group(): (group, group_created) = Group.objects.get_or_create(name='editor') if group_created: actions = ('add', 'change', 'delete', 'view', 'restore') perms = [Permission.objects.get(codename=('%s_document' % action)) for action in actions] group.permissions = perms group.save() return group
null
null
null
What can a group edit ?
def create_document_editor_group(): (group, group_created) = Group.objects.get_or_create(name='editor') if group_created: actions = ('add', 'change', 'delete', 'view', 'restore') perms = [Permission.objects.get(codename=('%s_document' % action)) for action in actions] group.permissions = perms group.save() return group
null
null
null
documents
codeqa
def create document editor group group group created Group objects get or create name 'editor' if group created actions 'add' 'change' 'delete' 'view' 'restore' perms [ Permission objects get codename '%s document' % action for action in actions]group permissions permsgroup save return group
null
null
null
null
Question: What can a group edit ? Code: def create_document_editor_group(): (group, group_created) = Group.objects.get_or_create(name='editor') if group_created: actions = ('add', 'change', 'delete', 'view', 'restore') perms = [Permission.objects.get(codename=('%s_document' % action)) for action in actions] group.permissions = perms group.save() return group
null
null
null
What does the code move ?
def move_path_to_trash(path, preclean=True): for pkg_dir in context.pkgs_dirs: trash_dir = join(pkg_dir, u'.trash') try: makedirs(trash_dir) except (IOError, OSError) as e1: if (e1.errno != EEXIST): continue trash_file = join(trash_dir, text_type(uuid4())) try: rename(path, trash_file) except (IOError, OSError) as e: log.trace(u'Could not move %s to %s.\n%r', path, trash_file, e) else: log.trace(u'Moved to trash: %s', path) from ...core.linked_data import delete_prefix_from_linked_data delete_prefix_from_linked_data(path) return True return False
null
null
null
a path to the trash
codeqa
def move path to trash path preclean True for pkg dir in context pkgs dirs trash dir join pkg dir u' trash' try makedirs trash dir except IO Error OS Error as e1 if e1 errno EEXIST continuetrash file join trash dir text type uuid 4 try rename path trash file except IO Error OS Error as e log trace u' Couldnotmove%sto%s \n%r' path trash file e else log trace u' Movedtotrash %s' path from core linked data import delete prefix from linked datadelete prefix from linked data path return Truereturn False
null
null
null
null
Question: What does the code move ? Code: def move_path_to_trash(path, preclean=True): for pkg_dir in context.pkgs_dirs: trash_dir = join(pkg_dir, u'.trash') try: makedirs(trash_dir) except (IOError, OSError) as e1: if (e1.errno != EEXIST): continue trash_file = join(trash_dir, text_type(uuid4())) try: rename(path, trash_file) except (IOError, OSError) as e: log.trace(u'Could not move %s to %s.\n%r', path, trash_file, e) else: log.trace(u'Moved to trash: %s', path) from ...core.linked_data import delete_prefix_from_linked_data delete_prefix_from_linked_data(path) return True return False
null
null
null
What is handling this request ?
def get_backend(): return os.environ.get('BACKEND_ID', None)
null
null
null
the backend
codeqa
def get backend return os environ get 'BACKEND ID' None
null
null
null
null
Question: What is handling this request ? Code: def get_backend(): return os.environ.get('BACKEND_ID', None)
null
null
null
What does the code get ?
def get_backend(): return os.environ.get('BACKEND_ID', None)
null
null
null
the name of the backend handling this request
codeqa
def get backend return os environ get 'BACKEND ID' None
null
null
null
null
Question: What does the code get ? Code: def get_backend(): return os.environ.get('BACKEND_ID', None)
null
null
null
What does g have ?
@not_implemented_for('undirected') def dag_longest_path(G, weight='weight', default_weight=1): dist = {} for v in nx.topological_sort(G): us = [((dist[u][0] + data.get(weight, default_weight)), u) for (u, data) in G.pred[v].items()] maxu = (max(us, key=(lambda x: x[0])) if us else (0, v)) dist[v] = (maxu if (maxu[0] >= 0) else (0, v)) u = None v = max(dist, key=(lambda x: dist[x][0])) path = [] while (u != v): path.append(v) u = v v = dist[v][1] path.reverse() return path
null
null
null
edges with weight attribute
codeqa
@not implemented for 'undirected' def dag longest path G weight 'weight' default weight 1 dist {}for v in nx topological sort G us [ dist[u][ 0 ] + data get weight default weight u for u data in G pred[v] items ]maxu max us key lambda x x[ 0 ] if us else 0 v dist[v] maxu if maxu[ 0 ] > 0 else 0 v u Nonev max dist key lambda x dist[x][ 0 ] path []while u v path append v u vv dist[v][ 1 ]path reverse return path
null
null
null
null
Question: What does g have ? Code: @not_implemented_for('undirected') def dag_longest_path(G, weight='weight', default_weight=1): dist = {} for v in nx.topological_sort(G): us = [((dist[u][0] + data.get(weight, default_weight)), u) for (u, data) in G.pred[v].items()] maxu = (max(us, key=(lambda x: x[0])) if us else (0, v)) dist[v] = (maxu if (maxu[0] >= 0) else (0, v)) u = None v = max(dist, key=(lambda x: dist[x][0])) path = [] while (u != v): path.append(v) u = v v = dist[v][1] path.reverse() return path
null
null
null
What has edges with weight attribute ?
@not_implemented_for('undirected') def dag_longest_path(G, weight='weight', default_weight=1): dist = {} for v in nx.topological_sort(G): us = [((dist[u][0] + data.get(weight, default_weight)), u) for (u, data) in G.pred[v].items()] maxu = (max(us, key=(lambda x: x[0])) if us else (0, v)) dist[v] = (maxu if (maxu[0] >= 0) else (0, v)) u = None v = max(dist, key=(lambda x: dist[x][0])) path = [] while (u != v): path.append(v) u = v v = dist[v][1] path.reverse() return path
null
null
null
g
codeqa
@not implemented for 'undirected' def dag longest path G weight 'weight' default weight 1 dist {}for v in nx topological sort G us [ dist[u][ 0 ] + data get weight default weight u for u data in G pred[v] items ]maxu max us key lambda x x[ 0 ] if us else 0 v dist[v] maxu if maxu[ 0 ] > 0 else 0 v u Nonev max dist key lambda x dist[x][ 0 ] path []while u v path append v u vv dist[v][ 1 ]path reverse return path
null
null
null
null
Question: What has edges with weight attribute ? Code: @not_implemented_for('undirected') def dag_longest_path(G, weight='weight', default_weight=1): dist = {} for v in nx.topological_sort(G): us = [((dist[u][0] + data.get(weight, default_weight)), u) for (u, data) in G.pred[v].items()] maxu = (max(us, key=(lambda x: x[0])) if us else (0, v)) dist[v] = (maxu if (maxu[0] >= 0) else (0, v)) u = None v = max(dist, key=(lambda x: dist[x][0])) path = [] while (u != v): path.append(v) u = v v = dist[v][1] path.reverse() return path
null
null
null
What does the code return ?
def extract_tarfile(upload_file, extension='.shp', tempdir=None): absolute_base_file = None if (tempdir is None): tempdir = tempfile.mkdtemp() the_tar = tarfile.open(upload_file) the_tar.extractall(tempdir) for item in the_tar.getnames(): if item.endswith(extension): absolute_base_file = os.path.join(tempdir, item) return absolute_base_file
null
null
null
the full path of the
codeqa
def extract tarfile upload file extension ' shp' tempdir None absolute base file Noneif tempdir is None tempdir tempfile mkdtemp the tar tarfile open upload file the tar extractall tempdir for item in the tar getnames if item endswith extension absolute base file os path join tempdir item return absolute base file
null
null
null
null
Question: What does the code return ? Code: def extract_tarfile(upload_file, extension='.shp', tempdir=None): absolute_base_file = None if (tempdir is None): tempdir = tempfile.mkdtemp() the_tar = tarfile.open(upload_file) the_tar.extractall(tempdir) for item in the_tar.getnames(): if item.endswith(extension): absolute_base_file = os.path.join(tempdir, item) return absolute_base_file
null
null
null
What does the code get ?
def volume_get_active_by_window(context, begin, end=None, project_id=None): return IMPL.volume_get_active_by_window(context, begin, end, project_id)
null
null
null
all the volumes inside the window
codeqa
def volume get active by window context begin end None project id None return IMPL volume get active by window context begin end project id
null
null
null
null
Question: What does the code get ? Code: def volume_get_active_by_window(context, begin, end=None, project_id=None): return IMPL.volume_get_active_by_window(context, begin, end, project_id)
null
null
null
What does the code create ?
def new_figure_manager(num, *args, **kwargs): FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasQT(thisFig) manager = FigureManagerQT(canvas, num) return manager
null
null
null
a new figure manager instance
codeqa
def new figure manager num *args **kwargs Figure Class kwargs pop ' Figure Class' Figure this Fig Figure Class *args **kwargs canvas Figure Canvas QT this Fig manager Figure Manager QT canvas num return manager
null
null
null
null
Question: What does the code create ? Code: def new_figure_manager(num, *args, **kwargs): FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasQT(thisFig) manager = FigureManagerQT(canvas, num) return manager
null
null
null
What described in section 4 ?
def NDP_Attack_DAD_DoS_via_NA(iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): def na_reply_callback(req, reply_mac, iface): '\n Callback that reply to a NS with a NA\n ' mac = req[Ether].src dst = req[IPv6].dst tgt = req[ICMPv6ND_NS].tgt rep = (Ether(src=reply_mac) / IPv6(src=tgt, dst=dst)) rep /= ICMPv6ND_NA(tgt=tgt, S=0, R=0, O=1) rep /= ICMPv6NDOptDstLLAddr(lladdr=reply_mac) sendp(rep, iface=iface, verbose=0) print ('Reply NA for target address %s (received from %s)' % (tgt, mac)) _NDP_Attack_DAD_DoS(na_reply_callback, iface, mac_src_filter, tgt_filter, reply_mac)
null
null
null
ns
codeqa
def NDP Attack DAD Do S via NA iface None mac src filter None tgt filter None reply mac None def na reply callback req reply mac iface '\n Callbackthatreplytoa N Switha NA\n'mac req[ Ether] srcdst req[I Pv 6 ] dsttgt req[ICM Pv 6 ND NS] tgtrep Ether src reply mac / I Pv 6 src tgt dst dst rep / ICM Pv 6 ND NA tgt tgt S 0 R 0 O 1 rep / ICM Pv 6 ND Opt Dst LL Addr lladdr reply mac sendp rep iface iface verbose 0 print ' Reply N Afortargetaddress%s receivedfrom%s ' % tgt mac NDP Attack DAD Do S na reply callback iface mac src filter tgt filter reply mac
null
null
null
null
Question: What described in section 4 ? Code: def NDP_Attack_DAD_DoS_via_NA(iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): def na_reply_callback(req, reply_mac, iface): '\n Callback that reply to a NS with a NA\n ' mac = req[Ether].src dst = req[IPv6].dst tgt = req[ICMPv6ND_NS].tgt rep = (Ether(src=reply_mac) / IPv6(src=tgt, dst=dst)) rep /= ICMPv6ND_NA(tgt=tgt, S=0, R=0, O=1) rep /= ICMPv6NDOptDstLLAddr(lladdr=reply_mac) sendp(rep, iface=iface, verbose=0) print ('Reply NA for target address %s (received from %s)' % (tgt, mac)) _NDP_Attack_DAD_DoS(na_reply_callback, iface, mac_src_filter, tgt_filter, reply_mac)
null
null
null
How did the application specify ?
def compile_views(folder, skip_failed_views=False): path = pjoin(folder, 'views') failed_views = [] for fname in listdir(path, '^[\\w/\\-]+(\\.\\w+)*$'): try: data = parse_template(fname, path) except Exception as e: if skip_failed_views: failed_views.append(fname) else: raise Exception(('%s in %s' % (e, fname))) else: filename = ('views.%s.py' % fname.replace(os.path.sep, '.')) filename = pjoin(folder, 'compiled', filename) write_file(filename, data) save_pyc(filename) os.unlink(filename) return (failed_views if failed_views else None)
null
null
null
by folder
codeqa
def compile views folder skip failed views False path pjoin folder 'views' failed views []for fname in listdir path '^[\\w/\\-]+ \\ \\w+ *$' try data parse template fname path except Exception as e if skip failed views failed views append fname else raise Exception '%sin%s' % e fname else filename 'views %s py' % fname replace os path sep ' ' filename pjoin folder 'compiled' filename write file filename data save pyc filename os unlink filename return failed views if failed views else None
null
null
null
null
Question: How did the application specify ? Code: def compile_views(folder, skip_failed_views=False): path = pjoin(folder, 'views') failed_views = [] for fname in listdir(path, '^[\\w/\\-]+(\\.\\w+)*$'): try: data = parse_template(fname, path) except Exception as e: if skip_failed_views: failed_views.append(fname) else: raise Exception(('%s in %s' % (e, fname))) else: filename = ('views.%s.py' % fname.replace(os.path.sep, '.')) filename = pjoin(folder, 'compiled', filename) write_file(filename, data) save_pyc(filename) os.unlink(filename) return (failed_views if failed_views else None)
null
null
null
What does the code get ?
def get_slotname(slot, host=None, admin_username=None, admin_password=None): slots = list_slotnames(host=host, admin_username=admin_username, admin_password=admin_password) slot = str(slot) return slots[slot]['slotname']
null
null
null
the name of a slot number in the chassis
codeqa
def get slotname slot host None admin username None admin password None slots list slotnames host host admin username admin username admin password admin password slot str slot return slots[slot]['slotname']
null
null
null
null
Question: What does the code get ? Code: def get_slotname(slot, host=None, admin_username=None, admin_password=None): slots = list_slotnames(host=host, admin_username=admin_username, admin_password=admin_password) slot = str(slot) return slots[slot]['slotname']
null
null
null
What does the code delete from the given bucket returns if policy was not deleted ?
def delete_policy(Bucket, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_bucket_policy(Bucket=Bucket) return {'deleted': True, 'name': Bucket} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
null
null
null
the policy
codeqa
def delete policy Bucket region None key None keyid None profile None try conn get conn region region key key keyid keyid profile profile conn delete bucket policy Bucket Bucket return {'deleted' True 'name' Bucket}except Client Error as e return {'deleted' False 'error' utils ['boto 3 get error'] e }
null
null
null
null
Question: What does the code delete from the given bucket returns if policy was not deleted ? Code: def delete_policy(Bucket, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_bucket_policy(Bucket=Bucket) return {'deleted': True, 'name': Bucket} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
null
null
null
How do helper define a dictionary ?
def dictOf(key, value): return Dict(ZeroOrMore(Group((key + value))))
null
null
null
easily and clearly
codeqa
def dict Of key value return Dict Zero Or More Group key + value
null
null
null
null
Question: How do helper define a dictionary ? Code: def dictOf(key, value): return Dict(ZeroOrMore(Group((key + value))))
null
null
null
What has no profanities in it ?
def hasNoProfanities(field_data, all_data): field_data = field_data.lower() words_seen = [w for w in settings.PROFANITIES_LIST if (w in field_data)] if words_seen: from django.utils.text import get_text_list plural = (len(words_seen) > 1) raise ValidationError, (ngettext('Watch your mouth! The word %s is not allowed here.', 'Watch your mouth! The words %s are not allowed here.', plural) % get_text_list([('"%s%s%s"' % (i[0], ('-' * (len(i) - 2)), i[(-1)])) for i in words_seen], 'and'))
null
null
null
the given string
codeqa
def has No Profanities field data all data field data field data lower words seen [w for w in settings PROFANITIES LIST if w in field data ]if words seen from django utils text import get text listplural len words seen > 1 raise Validation Error ngettext ' Watchyourmouth Theword%sisnotallowedhere ' ' Watchyourmouth Thewords%sarenotallowedhere ' plural % get text list [ '"%s%s%s"' % i[ 0 ] '-' * len i - 2 i[ -1 ] for i in words seen] 'and'
null
null
null
null
Question: What has no profanities in it ? Code: def hasNoProfanities(field_data, all_data): field_data = field_data.lower() words_seen = [w for w in settings.PROFANITIES_LIST if (w in field_data)] if words_seen: from django.utils.text import get_text_list plural = (len(words_seen) > 1) raise ValidationError, (ngettext('Watch your mouth! The word %s is not allowed here.', 'Watch your mouth! The words %s are not allowed here.', plural) % get_text_list([('"%s%s%s"' % (i[0], ('-' * (len(i) - 2)), i[(-1)])) for i in words_seen], 'and'))
null
null
null
Where does the given string have no profanities ?
def hasNoProfanities(field_data, all_data): field_data = field_data.lower() words_seen = [w for w in settings.PROFANITIES_LIST if (w in field_data)] if words_seen: from django.utils.text import get_text_list plural = (len(words_seen) > 1) raise ValidationError, (ngettext('Watch your mouth! The word %s is not allowed here.', 'Watch your mouth! The words %s are not allowed here.', plural) % get_text_list([('"%s%s%s"' % (i[0], ('-' * (len(i) - 2)), i[(-1)])) for i in words_seen], 'and'))
null
null
null
in it
codeqa
def has No Profanities field data all data field data field data lower words seen [w for w in settings PROFANITIES LIST if w in field data ]if words seen from django utils text import get text listplural len words seen > 1 raise Validation Error ngettext ' Watchyourmouth Theword%sisnotallowedhere ' ' Watchyourmouth Thewords%sarenotallowedhere ' plural % get text list [ '"%s%s%s"' % i[ 0 ] '-' * len i - 2 i[ -1 ] for i in words seen] 'and'
null
null
null
null
Question: Where does the given string have no profanities ? Code: def hasNoProfanities(field_data, all_data): field_data = field_data.lower() words_seen = [w for w in settings.PROFANITIES_LIST if (w in field_data)] if words_seen: from django.utils.text import get_text_list plural = (len(words_seen) > 1) raise ValidationError, (ngettext('Watch your mouth! The word %s is not allowed here.', 'Watch your mouth! The words %s are not allowed here.', plural) % get_text_list([('"%s%s%s"' % (i[0], ('-' * (len(i) - 2)), i[(-1)])) for i in words_seen], 'and'))
null
null
null
What does the given string have in it ?
def hasNoProfanities(field_data, all_data): field_data = field_data.lower() words_seen = [w for w in settings.PROFANITIES_LIST if (w in field_data)] if words_seen: from django.utils.text import get_text_list plural = (len(words_seen) > 1) raise ValidationError, (ngettext('Watch your mouth! The word %s is not allowed here.', 'Watch your mouth! The words %s are not allowed here.', plural) % get_text_list([('"%s%s%s"' % (i[0], ('-' * (len(i) - 2)), i[(-1)])) for i in words_seen], 'and'))
null
null
null
no profanities
codeqa
def has No Profanities field data all data field data field data lower words seen [w for w in settings PROFANITIES LIST if w in field data ]if words seen from django utils text import get text listplural len words seen > 1 raise Validation Error ngettext ' Watchyourmouth Theword%sisnotallowedhere ' ' Watchyourmouth Thewords%sarenotallowedhere ' plural % get text list [ '"%s%s%s"' % i[ 0 ] '-' * len i - 2 i[ -1 ] for i in words seen] 'and'
null
null
null
null
Question: What does the given string have in it ? Code: def hasNoProfanities(field_data, all_data): field_data = field_data.lower() words_seen = [w for w in settings.PROFANITIES_LIST if (w in field_data)] if words_seen: from django.utils.text import get_text_list plural = (len(words_seen) > 1) raise ValidationError, (ngettext('Watch your mouth! The word %s is not allowed here.', 'Watch your mouth! The words %s are not allowed here.', plural) % get_text_list([('"%s%s%s"' % (i[0], ('-' * (len(i) - 2)), i[(-1)])) for i in words_seen], 'and'))
null
null
null
What do you wish ?
def reissue(csr_file, certificate_id, web_server_type, approver_email=None, http_dc_validation=False, **kwargs): return __get_certificates('namecheap.ssl.reissue', 'SSLReissueResult', csr_file, certificate_id, web_server_type, approver_email, http_dc_validation, kwargs)
null
null
null
to activate web_server_type
codeqa
def reissue csr file certificate id web server type approver email None http dc validation False **kwargs return get certificates 'namecheap ssl reissue' 'SSL Reissue Result' csr file certificate id web server type approver email http dc validation kwargs
null
null
null
null
Question: What do you wish ? Code: def reissue(csr_file, certificate_id, web_server_type, approver_email=None, http_dc_validation=False, **kwargs): return __get_certificates('namecheap.ssl.reissue', 'SSLReissueResult', csr_file, certificate_id, web_server_type, approver_email, http_dc_validation, kwargs)
null
null
null
What does the code render ?
def render(template_file, saltenv='base', sls='', context=None, tmplpath=None, **kws): tmp_data = salt.utils.templates.MAKO(template_file, to_str=True, salt=__salt__, grains=__grains__, opts=__opts__, pillar=__pillar__, saltenv=saltenv, sls=sls, context=context, tmplpath=tmplpath, **kws) if (not tmp_data.get('result', False)): raise SaltRenderError(tmp_data.get('data', 'Unknown render error in mako renderer')) return six.moves.StringIO(tmp_data['data'])
null
null
null
the template_file
codeqa
def render template file saltenv 'base' sls '' context None tmplpath None **kws tmp data salt utils templates MAKO template file to str True salt salt grains grains opts opts pillar pillar saltenv saltenv sls sls context context tmplpath tmplpath **kws if not tmp data get 'result' False raise Salt Render Error tmp data get 'data' ' Unknownrendererrorinmakorenderer' return six moves String IO tmp data['data']
null
null
null
null
Question: What does the code render ? Code: def render(template_file, saltenv='base', sls='', context=None, tmplpath=None, **kws): tmp_data = salt.utils.templates.MAKO(template_file, to_str=True, salt=__salt__, grains=__grains__, opts=__opts__, pillar=__pillar__, saltenv=saltenv, sls=sls, context=context, tmplpath=tmplpath, **kws) if (not tmp_data.get('result', False)): raise SaltRenderError(tmp_data.get('data', 'Unknown render error in mako renderer')) return six.moves.StringIO(tmp_data['data'])
null
null
null
For what purpose do a class node type return ?
def _class_type(klass, ancestors=None): if (klass._type is not None): return klass._type if _is_metaclass(klass): klass._type = 'metaclass' elif klass.name.endswith('Interface'): klass._type = 'interface' elif klass.name.endswith('Exception'): klass._type = 'exception' else: if (ancestors is None): ancestors = set() if (klass in ancestors): klass._type = 'class' return 'class' ancestors.add(klass) for base in klass.ancestors(recurs=False): name = _class_type(base, ancestors) if (name != 'class'): if ((name == 'metaclass') and (not _is_metaclass(klass))): continue klass._type = base.type break if (klass._type is None): klass._type = 'class' return klass._type
null
null
null
to differ metaclass
codeqa
def class type klass ancestors None if klass type is not None return klass typeif is metaclass klass klass type 'metaclass'elif klass name endswith ' Interface' klass type 'interface'elif klass name endswith ' Exception' klass type 'exception'else if ancestors is None ancestors set if klass in ancestors klass type 'class'return 'class'ancestors add klass for base in klass ancestors recurs False name class type base ancestors if name 'class' if name 'metaclass' and not is metaclass klass continueklass type base typebreakif klass type is None klass type 'class'return klass type
null
null
null
null
Question: For what purpose do a class node type return ? Code: def _class_type(klass, ancestors=None): if (klass._type is not None): return klass._type if _is_metaclass(klass): klass._type = 'metaclass' elif klass.name.endswith('Interface'): klass._type = 'interface' elif klass.name.endswith('Exception'): klass._type = 'exception' else: if (ancestors is None): ancestors = set() if (klass in ancestors): klass._type = 'class' return 'class' ancestors.add(klass) for base in klass.ancestors(recurs=False): name = _class_type(base, ancestors) if (name != 'class'): if ((name == 'metaclass') and (not _is_metaclass(klass))): continue klass._type = base.type break if (klass._type is None): klass._type = 'class' return klass._type