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 did the code compose ?
| def _get_filter_query(args, model=SaleOrder):
query = Q()
for arg in args:
if args[arg]:
if (hasattr(model, arg) or (arg == 'products_interested')):
kwargs = {str((arg + '__id')): long(args[arg])}
query = (query & Q(**kwargs))
return query
| null | null | null | a filter query based on filter form submission
| codeqa | def get filter query args model Sale Order query Q for arg in args if args[arg] if hasattr model arg or arg 'products interested' kwargs {str arg + ' id' long args[arg] }query query & Q **kwargs return query
| null | null | null | null | Question:
What did the code compose ?
Code:
def _get_filter_query(args, model=SaleOrder):
query = Q()
for arg in args:
if args[arg]:
if (hasattr(model, arg) or (arg == 'products_interested')):
kwargs = {str((arg + '__id')): long(args[arg])}
query = (query & Q(**kwargs))
return query
|
null | null | null | What have they finished ?
| def _get_next(request):
next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', None)))
if (not next):
next = request.path
return next
| null | null | null | computation
| codeqa | def get next request next request POST get 'next' request GET get 'next' request META get 'HTTP REFERER' None if not next next request pathreturn next
| null | null | null | null | Question:
What have they finished ?
Code:
def _get_next(request):
next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', None)))
if (not next):
next = request.path
return next
|
null | null | null | Who have finished computation ?
| def _get_next(request):
next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', None)))
if (not next):
next = request.path
return next
| null | null | null | they
| codeqa | def get next request next request POST get 'next' request GET get 'next' request META get 'HTTP REFERER' None if not next next request pathreturn next
| null | null | null | null | Question:
Who have finished computation ?
Code:
def _get_next(request):
next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', None)))
if (not next):
next = request.path
return next
|
null | null | null | Who determine their redirects how after they have finished computation ?
| def _get_next(request):
next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', None)))
if (not next):
next = request.path
return next
| null | null | null | they
| codeqa | def get next request next request POST get 'next' request GET get 'next' request META get 'HTTP REFERER' None if not next next request pathreturn next
| null | null | null | null | Question:
Who determine their redirects how after they have finished computation ?
Code:
def _get_next(request):
next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', None)))
if (not next):
next = request.path
return next
|
null | null | null | What does the code generate ?
| def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options):
rules_filename = ('%s%s.rules' % (spec['target_name'], options.suffix))
rules_file = MSVSToolFile.Writer(os.path.join(output_dir, rules_filename), spec['target_name'])
for r in rules:
rule_name = r['rule_name']
rule_ext = r['extension']
inpu... | null | null | null | a native rules file
| codeqa | def Generate Native Rules For MSVS p rules output dir spec options rules filename '%s%s rules' % spec['target name'] options suffix rules file MSVS Tool File Writer os path join output dir rules filename spec['target name'] for r in rules rule name r['rule name']rule ext r['extension']inputs Fix Paths r get 'inputs' []... | null | null | null | null | Question:
What does the code generate ?
Code:
def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options):
rules_filename = ('%s%s.rules' % (spec['target_name'], options.suffix))
rules_file = MSVSToolFile.Writer(os.path.join(output_dir, rules_filename), spec['target_name'])
for r in rules:
rule_name =... |
null | null | null | What is containing models ?
| def get_models(app_mod=None):
app_list = get_apps()
if app_mod:
return _app_models.get(app_mod.__name__.split('.')[(-2)], {}).values()
else:
model_list = []
for app_mod in app_list:
model_list.extend(get_models(app_mod))
return model_list
| null | null | null | a module
| codeqa | def get models app mod None app list get apps if app mod return app models get app mod name split ' ' [ -2 ] {} values else model list []for app mod in app list model list extend get models app mod return model list
| null | null | null | null | Question:
What is containing models ?
Code:
def get_models(app_mod=None):
app_list = get_apps()
if app_mod:
return _app_models.get(app_mod.__name__.split('.')[(-2)], {}).values()
else:
model_list = []
for app_mod in app_list:
model_list.extend(get_models(app_mod))
return model_list
|
null | null | null | What does the code generate ?
| def _build_schema_resource(fields):
infos = []
for field in fields:
info = {'name': field.name, 'type': field.field_type, 'mode': field.mode}
if (field.description is not None):
info['description'] = field.description
if (field.fields is not None):
info['fields'] = _build_schema_resource(field.fields)
i... | null | null | null | a resource fragment for a schema
| codeqa | def build schema resource fields infos []for field in fields info {'name' field name 'type' field field type 'mode' field mode}if field description is not None info['description'] field descriptionif field fields is not None info['fields'] build schema resource field fields infos append info return infos
| null | null | null | null | Question:
What does the code generate ?
Code:
def _build_schema_resource(fields):
infos = []
for field in fields:
info = {'name': field.name, 'type': field.field_type, 'mode': field.mode}
if (field.description is not None):
info['description'] = field.description
if (field.fields is not None):
info['f... |
null | null | null | What does the code compare ?
| def test_multiset_partitions_versions():
multiplicities = [5, 2, 2, 1]
m = MultisetPartitionTraverser()
for (s1, s2) in zip_longest(m.enum_all(multiplicities), multiset_partitions_taocp(multiplicities)):
assert compare_multiset_states(s1, s2)
| null | null | null | knuth - based versions of multiset_partitions
| codeqa | def test multiset partitions versions multiplicities [5 2 2 1]m Multiset Partition Traverser for s1 s2 in zip longest m enum all multiplicities multiset partitions taocp multiplicities assert compare multiset states s1 s2
| null | null | null | null | Question:
What does the code compare ?
Code:
def test_multiset_partitions_versions():
multiplicities = [5, 2, 2, 1]
m = MultisetPartitionTraverser()
for (s1, s2) in zip_longest(m.enum_all(multiplicities), multiset_partitions_taocp(multiplicities)):
assert compare_multiset_states(s1, s2)
|
null | null | null | What does the code return ?
| def map_fn(fn, elems, name=None):
return tf.map_fn(fn, elems, name=name)
| null | null | null | the outputs
| codeqa | def map fn fn elems name None return tf map fn fn elems name name
| null | null | null | null | Question:
What does the code return ?
Code:
def map_fn(fn, elems, name=None):
return tf.map_fn(fn, elems, name=name)
|
null | null | null | What does the code create ?
| def create_user(profile='grafana', **kwargs):
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
response = requests.post('{0}/api/admin/users'.format(profile['grafana_url']), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get('grafana_timeout', ... | null | null | null | a new user
| codeqa | def create user profile 'grafana' **kwargs if isinstance profile string types profile salt ['config option'] profile response requests post '{ 0 }/api/admin/users' format profile['grafana url'] json kwargs auth get auth profile headers get headers profile timeout profile get 'grafana timeout' 3 if response status code ... | null | null | null | null | Question:
What does the code create ?
Code:
def create_user(profile='grafana', **kwargs):
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
response = requests.post('{0}/api/admin/users'.format(profile['grafana_url']), json=kwargs, auth=_get_auth(profile), headers=_get_headers(p... |
null | null | null | What does the code rewrite if it contains to be a valid identifier ?
| def valid_identifier(s):
if isinstance(s, _strtypes):
if ((not s) or s[0].isdigit()):
return
return s.replace(' ', '_').replace('.', '_').replace('-', '_')
return s
| null | null | null | a string
| codeqa | def valid identifier s if isinstance s strtypes if not s or s[ 0 ] isdigit returnreturn s replace '' ' ' replace ' ' ' ' replace '-' ' ' return s
| null | null | null | null | Question:
What does the code rewrite if it contains to be a valid identifier ?
Code:
def valid_identifier(s):
if isinstance(s, _strtypes):
if ((not s) or s[0].isdigit()):
return
return s.replace(' ', '_').replace('.', '_').replace('-', '_')
return s
|
null | null | null | For what purpose does the code rewrite a string if it contains ?
| def valid_identifier(s):
if isinstance(s, _strtypes):
if ((not s) or s[0].isdigit()):
return
return s.replace(' ', '_').replace('.', '_').replace('-', '_')
return s
| null | null | null | to be a valid identifier
| codeqa | def valid identifier s if isinstance s strtypes if not s or s[ 0 ] isdigit returnreturn s replace '' ' ' replace ' ' ' ' replace '-' ' ' return s
| null | null | null | null | Question:
For what purpose does the code rewrite a string if it contains ?
Code:
def valid_identifier(s):
if isinstance(s, _strtypes):
if ((not s) or s[0].isdigit()):
return
return s.replace(' ', '_').replace('.', '_').replace('-', '_')
return s
|
null | null | null | What does recursive call handle also ?
| def traverse(roots, parent='', verbose=False):
for root in roots:
if root.method_map:
print('->', ((parent + '/') + root.raw_segment))
if verbose:
for (method, func) in root.method_map.items():
if (func.__name__ != 'method_not_allowed'):
print('-->{0} {1}:{2}'.format(method, inspect.getsourcefi... | null | null | null | printing output
| codeqa | def traverse roots parent '' verbose False for root in roots if root method map print '->' parent + '/' + root raw segment if verbose for method func in root method map items if func name 'method not allowed' print '-->{ 0 }{ 1 } {2 }' format method inspect getsourcefile func inspect getsourcelines func [1 ] if root ch... | null | null | null | null | Question:
What does recursive call handle also ?
Code:
def traverse(roots, parent='', verbose=False):
for root in roots:
if root.method_map:
print('->', ((parent + '/') + root.raw_segment))
if verbose:
for (method, func) in root.method_map.items():
if (func.__name__ != 'method_not_allowed'):
... |
null | null | null | What holds identical elements ?
| def equal(seq):
return (len(set(seq)) <= 1)
| null | null | null | a sequence
| codeqa | def equal seq return len set seq < 1
| null | null | null | null | Question:
What holds identical elements ?
Code:
def equal(seq):
return (len(set(seq)) <= 1)
|
null | null | null | What does the code add to the menu ?
| def addMenuEntitiesToMenuFrameable(menu, menuEntities):
for menuEntity in menuEntities:
menuEntity.addToMenuFrameable(menu)
| null | null | null | the menu entities
| codeqa | def add Menu Entities To Menu Frameable menu menu Entities for menu Entity in menu Entities menu Entity add To Menu Frameable menu
| null | null | null | null | Question:
What does the code add to the menu ?
Code:
def addMenuEntitiesToMenuFrameable(menu, menuEntities):
for menuEntity in menuEntities:
menuEntity.addToMenuFrameable(menu)
|
null | null | null | When is this called ?
| def at_server_cold_stop():
pass
| null | null | null | only when the server goes down due to a shutdown or reset
| codeqa | def at server cold stop pass
| null | null | null | null | Question:
When is this called ?
Code:
def at_server_cold_stop():
pass
|
null | null | null | In which direction did the server go due to a shutdown or reset when ?
| def at_server_cold_stop():
pass
| null | null | null | down
| codeqa | def at server cold stop pass
| null | null | null | null | Question:
In which direction did the server go due to a shutdown or reset when ?
Code:
def at_server_cold_stop():
pass
|
null | null | null | Why did the server go down when ?
| def at_server_cold_stop():
pass
| null | null | null | due to a shutdown or reset
| codeqa | def at server cold stop pass
| null | null | null | null | Question:
Why did the server go down when ?
Code:
def at_server_cold_stop():
pass
|
null | null | null | What is concerning a job ?
| def send_job_review_message(job, user, subject_template_path, message_template_path):
subject_template = loader.get_template(subject_template_path)
message_template = loader.get_template(message_template_path)
if (user.first_name or user.last_name):
reviewer_name = '{} {}'.format(user.first_name, user.last_name)
... | null | null | null | the review message
| codeqa | def send job review message job user subject template path message template path subject template loader get template subject template path message template loader get template message template path if user first name or user last name reviewer name '{}{}' format user first name user last name else reviewer name ' Comm... | null | null | null | null | Question:
What is concerning a job ?
Code:
def send_job_review_message(job, user, subject_template_path, message_template_path):
subject_template = loader.get_template(subject_template_path)
message_template = loader.get_template(message_template_path)
if (user.first_name or user.last_name):
reviewer_name = '{... |
null | null | null | When do necessary paths and never none contain ?
| def _GetDefaultParams(template_params):
if (not template_params):
template_params = {}
template_params.update({'base_path': config.BASE_PATH, 'mapreduce_path': config.MAPREDUCE_PATH})
return template_params
| null | null | null | always
| codeqa | def Get Default Params template params if not template params template params {}template params update {'base path' config BASE PATH 'mapreduce path' config MAPREDUCE PATH} return template params
| null | null | null | null | Question:
When do necessary paths and never none contain ?
Code:
def _GetDefaultParams(template_params):
if (not template_params):
template_params = {}
template_params.update({'base_path': config.BASE_PATH, 'mapreduce_path': config.MAPREDUCE_PATH})
return template_params
|
null | null | null | What converts to int ?
| def makeNumeric(s):
if checkInt(s):
return int(s)
elif checkFloat(s):
return float(s)
else:
return s
| null | null | null | string
| codeqa | def make Numeric s if check Int s return int s elif check Float s return float s else return s
| null | null | null | null | Question:
What converts to int ?
Code:
def makeNumeric(s):
if checkInt(s):
return int(s)
elif checkFloat(s):
return float(s)
else:
return s
|
null | null | null | What do string convert ?
| def makeNumeric(s):
if checkInt(s):
return int(s)
elif checkFloat(s):
return float(s)
else:
return s
| null | null | null | to int
| codeqa | def make Numeric s if check Int s return int s elif check Float s return float s else return s
| null | null | null | null | Question:
What do string convert ?
Code:
def makeNumeric(s):
if checkInt(s):
return int(s)
elif checkFloat(s):
return float(s)
else:
return s
|
null | null | null | What does the code get ?
| def get_device_counters(**kwargs):
assert ((('zone' in kwargs) + ('devices' in kwargs)) == 1), 'Must specify zone or devices, and not both.'
from ..devices.models import Device
devices = (kwargs.get('devices') or Device.all_objects.by_zone(kwargs['zone']))
device_counters = {}
for device in list(devices):
... | null | null | null | device counters
| codeqa | def get device counters **kwargs assert 'zone' in kwargs + 'devices' in kwargs 1 ' Mustspecifyzoneordevices andnotboth 'from devices models import Devicedevices kwargs get 'devices' or Device all objects by zone kwargs['zone'] device counters {}for device in list devices if device id not in device counters device count... | null | null | null | null | Question:
What does the code get ?
Code:
def get_device_counters(**kwargs):
assert ((('zone' in kwargs) + ('devices' in kwargs)) == 1), 'Must specify zone or devices, and not both.'
from ..devices.models import Device
devices = (kwargs.get('devices') or Device.all_objects.by_zone(kwargs['zone']))
device_... |
null | null | null | What does the code get ?
| def get_project_root():
django_settings_module = os.environ.get('DJANGO_SETTINGS_MODULE')
if (not django_settings_module):
module_str = settings.SETTINGS_MODULE
else:
module_str = django_settings_module.split('.')[0]
mod = import_module(module_str)
return os.path.dirname(os.path.abspath(mod.__file__))
| null | null | null | the project root directory
| codeqa | def get project root django settings module os environ get 'DJANGO SETTINGS MODULE' if not django settings module module str settings SETTINGS MODUL Eelse module str django settings module split ' ' [0 ]mod import module module str return os path dirname os path abspath mod file
| null | null | null | null | Question:
What does the code get ?
Code:
def get_project_root():
django_settings_module = os.environ.get('DJANGO_SETTINGS_MODULE')
if (not django_settings_module):
module_str = settings.SETTINGS_MODULE
else:
module_str = django_settings_module.split('.')[0]
mod = import_module(module_str)
return os.path.di... |
null | null | null | What restricts non - login access to views sets ?
| def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
message = 'Authentication credentials not found'
success = False
try:
auth_jwt()
success = True
except JWTError as e:
if ((e.headers is not None) and ('WWW-Authenticate' not in e.headers)):
raise NotAuthorizedError(message=((e.err... | null | null | null | custom decorator
| codeqa | def requires auth f @wraps f def decorated *args **kwargs message ' Authenticationcredentialsnotfound'success Falsetry auth jwt success Trueexcept JWT Error as e if e headers is not None and 'WWW- Authenticate' not in e headers raise Not Authorized Error message e error + ' ' + e description if not success results auth... | null | null | null | null | Question:
What restricts non - login access to views sets ?
Code:
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
message = 'Authentication credentials not found'
success = False
try:
auth_jwt()
success = True
except JWTError as e:
if ((e.headers is not None) and ('WWW-Authenti... |
null | null | null | What do custom decorator restrict ?
| def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
message = 'Authentication credentials not found'
success = False
try:
auth_jwt()
success = True
except JWTError as e:
if ((e.headers is not None) and ('WWW-Authenticate' not in e.headers)):
raise NotAuthorizedError(message=((e.err... | null | null | null | non - login access to views sets
| codeqa | def requires auth f @wraps f def decorated *args **kwargs message ' Authenticationcredentialsnotfound'success Falsetry auth jwt success Trueexcept JWT Error as e if e headers is not None and 'WWW- Authenticate' not in e headers raise Not Authorized Error message e error + ' ' + e description if not success results auth... | null | null | null | null | Question:
What do custom decorator restrict ?
Code:
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
message = 'Authentication credentials not found'
success = False
try:
auth_jwt()
success = True
except JWTError as e:
if ((e.headers is not None) and ('WWW-Authenticate' not in e... |
null | null | null | What does the listing post ?
| def post_listing_to_slack(sc, listing):
desc = '{0} | {1} | {2} | {3} | <{4}>'.format(listing['area'], listing['price'], listing['bart_dist'], listing['name'], listing['url'])
sc.api_call('chat.postMessage', channel=settings.SLACK_CHANNEL, text=desc, username='pybot', icon_emoji=':robot_face:')
| null | null | null | to slack
| codeqa | def post listing to slack sc listing desc '{ 0 } {1 } {2 } {3 } <{ 4 }>' format listing['area'] listing['price'] listing['bart dist'] listing['name'] listing['url'] sc api call 'chat post Message' channel settings SLACK CHANNEL text desc username 'pybot' icon emoji ' robot face '
| null | null | null | null | Question:
What does the listing post ?
Code:
def post_listing_to_slack(sc, listing):
desc = '{0} | {1} | {2} | {3} | <{4}>'.format(listing['area'], listing['price'], listing['bart_dist'], listing['name'], listing['url'])
sc.api_call('chat.postMessage', channel=settings.SLACK_CHANNEL, text=desc, username='... |
null | null | null | What posts to slack ?
| def post_listing_to_slack(sc, listing):
desc = '{0} | {1} | {2} | {3} | <{4}>'.format(listing['area'], listing['price'], listing['bart_dist'], listing['name'], listing['url'])
sc.api_call('chat.postMessage', channel=settings.SLACK_CHANNEL, text=desc, username='pybot', icon_emoji=':robot_face:')
| null | null | null | the listing
| codeqa | def post listing to slack sc listing desc '{ 0 } {1 } {2 } {3 } <{ 4 }>' format listing['area'] listing['price'] listing['bart dist'] listing['name'] listing['url'] sc api call 'chat post Message' channel settings SLACK CHANNEL text desc username 'pybot' icon emoji ' robot face '
| null | null | null | null | Question:
What posts to slack ?
Code:
def post_listing_to_slack(sc, listing):
desc = '{0} | {1} | {2} | {3} | <{4}>'.format(listing['area'], listing['price'], listing['bart_dist'], listing['name'], listing['url'])
sc.api_call('chat.postMessage', channel=settings.SLACK_CHANNEL, text=desc, username='pybot',... |
null | null | null | What do we find ?
| def egg_link_path(dist):
return (os.path.join(site_packages, dist.project_name) + '.egg-link')
| null | null | null | a
| codeqa | def egg link path dist return os path join site packages dist project name + ' egg-link'
| null | null | null | null | Question:
What do we find ?
Code:
def egg_link_path(dist):
return (os.path.join(site_packages, dist.project_name) + '.egg-link')
|
null | null | null | Where d we expect to find a ?
| def egg_link_path(dist):
return (os.path.join(site_packages, dist.project_name) + '.egg-link')
| null | null | null | the path
| codeqa | def egg link path dist return os path join site packages dist project name + ' egg-link'
| null | null | null | null | Question:
Where d we expect to find a ?
Code:
def egg_link_path(dist):
return (os.path.join(site_packages, dist.project_name) + '.egg-link')
|
null | null | null | What d we expect the path ?
| def egg_link_path(dist):
return (os.path.join(site_packages, dist.project_name) + '.egg-link')
| null | null | null | to find a
| codeqa | def egg link path dist return os path join site packages dist project name + ' egg-link'
| null | null | null | null | Question:
What d we expect the path ?
Code:
def egg_link_path(dist):
return (os.path.join(site_packages, dist.project_name) + '.egg-link')
|
null | null | null | When do backwards - compatibility preserve ?
| def commit_on_success_unless_managed(using=None, savepoint=False):
connection = get_connection(using)
if (connection.get_autocommit() or connection.in_atomic_block):
return atomic(using, savepoint)
else:
def entering(using):
pass
def exiting(exc_type, using):
set_dirty(using=using)
return _transaction_... | null | null | null | while refactoring
| codeqa | def commit on success unless managed using None savepoint False connection get connection using if connection get autocommit or connection in atomic block return atomic using savepoint else def entering using passdef exiting exc type using set dirty using using return transaction func entering exiting using
| null | null | null | null | Question:
When do backwards - compatibility preserve ?
Code:
def commit_on_success_unless_managed(using=None, savepoint=False):
connection = get_connection(using)
if (connection.get_autocommit() or connection.in_atomic_block):
return atomic(using, savepoint)
else:
def entering(using):
pass
def exiting(e... |
null | null | null | What does the code get from attribute dictionary ?
| def getGeometryOutput(derivation, elementNode):
if (derivation == None):
derivation = TeardropDerivation(elementNode)
teardropPath = getTeardropPath(derivation.inclination, derivation.overhangRadians, derivation.overhangSpan, derivation.radiusArealized, derivation.sides)
return lineation.getGeometryOutputByLoop(el... | null | null | null | vector3 vertexes
| codeqa | def get Geometry Output derivation element Node if derivation None derivation Teardrop Derivation element Node teardrop Path get Teardrop Path derivation inclination derivation overhang Radians derivation overhang Span derivation radius Arealized derivation sides return lineation get Geometry Output By Loop element Nod... | null | null | null | null | Question:
What does the code get from attribute dictionary ?
Code:
def getGeometryOutput(derivation, elementNode):
if (derivation == None):
derivation = TeardropDerivation(elementNode)
teardropPath = getTeardropPath(derivation.inclination, derivation.overhangRadians, derivation.overhangSpan, derivation.radiusAr... |
null | null | null | What do requests expect ?
| def expect_json(view_function):
@wraps(view_function)
def parse_json_into_request(request, *args, **kwargs):
if (('application/json' in request.META.get('CONTENT_TYPE', '')) and request.body):
try:
request.json = json.loads(request.body)
except ValueError:
return JsonResponseBadRequest({'error': 'Inva... | null | null | null | json
| codeqa | def expect json view function @wraps view function def parse json into request request *args **kwargs if 'application/json' in request META get 'CONTENT TYPE' '' and request body try request json json loads request body except Value Error return Json Response Bad Request {'error' ' Invalid JSON'} else request json {}re... | null | null | null | null | Question:
What do requests expect ?
Code:
def expect_json(view_function):
@wraps(view_function)
def parse_json_into_request(request, *args, **kwargs):
if (('application/json' in request.META.get('CONTENT_TYPE', '')) and request.body):
try:
request.json = json.loads(request.body)
except ValueError:
... |
null | null | null | What does the code clean into something somewhat readable by mere humans ?
| def simplify_regex(pattern):
pattern = optional_group_matcher.sub((lambda m: ('[%s]' % m.group(1))), pattern)
pattern = named_group_matcher.sub((lambda m: ('{%s}' % m.group(1))), pattern)
pattern = non_named_group_matcher.sub('{var}', pattern)
pattern = either_option_matcher.sub((lambda m: m.group(1)), pattern)
pa... | null | null | null | urlpattern regexes
| codeqa | def simplify regex pattern pattern optional group matcher sub lambda m '[%s]' % m group 1 pattern pattern named group matcher sub lambda m '{%s}' % m group 1 pattern pattern non named group matcher sub '{var}' pattern pattern either option matcher sub lambda m m group 1 pattern pattern pattern replace '^' '' replace '$... | null | null | null | null | Question:
What does the code clean into something somewhat readable by mere humans ?
Code:
def simplify_regex(pattern):
pattern = optional_group_matcher.sub((lambda m: ('[%s]' % m.group(1))), pattern)
pattern = named_group_matcher.sub((lambda m: ('{%s}' % m.group(1))), pattern)
pattern = non_named_group_matcher.... |
null | null | null | What does the code extract from a course structure ?
| def get_course_chapters(course_key):
if (course_key is None):
return
try:
course_obj = CourseStructure.objects.get(course_id=course_key)
except CourseStructure.DoesNotExist:
return
course_struct = course_obj.structure
try:
return course_struct['blocks'][course_struct['root']].get('children', [])
except Ke... | null | null | null | the chapters
| codeqa | def get course chapters course key if course key is None returntry course obj Course Structure objects get course id course key except Course Structure Does Not Exist returncourse struct course obj structuretry return course struct['blocks'][course struct['root']] get 'children' [] except Key Error return []
| null | null | null | null | Question:
What does the code extract from a course structure ?
Code:
def get_course_chapters(course_key):
if (course_key is None):
return
try:
course_obj = CourseStructure.objects.get(course_id=course_key)
except CourseStructure.DoesNotExist:
return
course_struct = course_obj.structure
try:
return cour... |
null | null | null | What does the code convert ?
| def flatten_response(content):
return ''.join((_force_utf8(x) for x in tup(content) if x))
| null | null | null | a content iterable to a string
| codeqa | def flatten response content return '' join force utf 8 x for x in tup content if x
| null | null | null | null | Question:
What does the code convert ?
Code:
def flatten_response(content):
return ''.join((_force_utf8(x) for x in tup(content) if x))
|
null | null | null | When is a port free ?
| def get_free_namespace_port(protocol, namespace=None, start=1024, end=None):
if (protocol == n_const.PROTO_NAME_TCP):
param = '-tna'
elif (protocol == n_const.PROTO_NAME_UDP):
param = '-una'
else:
raise ValueError(('Unsupported protocol %s' % protocol))
ip_wrapper = ip_lib.IPWrapper(namespace=namespace)
ou... | null | null | null | at the execution time of this function
| codeqa | def get free namespace port protocol namespace None start 1024 end None if protocol n const PROTO NAME TCP param '-tna'elif protocol n const PROTO NAME UDP param '-una'else raise Value Error ' Unsupportedprotocol%s' % protocol ip wrapper ip lib IP Wrapper namespace namespace output ip wrapper netns execute ['ss' param]... | null | null | null | null | Question:
When is a port free ?
Code:
def get_free_namespace_port(protocol, namespace=None, start=1024, end=None):
if (protocol == n_const.PROTO_NAME_TCP):
param = '-tna'
elif (protocol == n_const.PROTO_NAME_UDP):
param = '-una'
else:
raise ValueError(('Unsupported protocol %s' % protocol))
ip_wrapper =... |
null | null | null | What does the stable log sum exp match ?
| def test_log_sum_exp_1():
rng = np.random.RandomState([2015, 2, 9])
x = (1.0 + (rng.randn(5) / 10.0))
naive = np.log(np.exp(x).sum())
x = sharedX(x)
stable = log_sum_exp(x).eval()
assert np.allclose(naive, stable)
| null | null | null | the naive one for values near 1
| codeqa | def test log sum exp 1 rng np random Random State [2015 2 9] x 1 0 + rng randn 5 / 10 0 naive np log np exp x sum x shared X x stable log sum exp x eval assert np allclose naive stable
| null | null | null | null | Question:
What does the stable log sum exp match ?
Code:
def test_log_sum_exp_1():
rng = np.random.RandomState([2015, 2, 9])
x = (1.0 + (rng.randn(5) / 10.0))
naive = np.log(np.exp(x).sum())
x = sharedX(x)
stable = log_sum_exp(x).eval()
assert np.allclose(naive, stable)
|
null | null | null | What matches the naive one for values near 1 ?
| def test_log_sum_exp_1():
rng = np.random.RandomState([2015, 2, 9])
x = (1.0 + (rng.randn(5) / 10.0))
naive = np.log(np.exp(x).sum())
x = sharedX(x)
stable = log_sum_exp(x).eval()
assert np.allclose(naive, stable)
| null | null | null | the stable log sum exp
| codeqa | def test log sum exp 1 rng np random Random State [2015 2 9] x 1 0 + rng randn 5 / 10 0 naive np log np exp x sum x shared X x stable log sum exp x eval assert np allclose naive stable
| null | null | null | null | Question:
What matches the naive one for values near 1 ?
Code:
def test_log_sum_exp_1():
rng = np.random.RandomState([2015, 2, 9])
x = (1.0 + (rng.randn(5) / 10.0))
naive = np.log(np.exp(x).sum())
x = sharedX(x)
stable = log_sum_exp(x).eval()
assert np.allclose(naive, stable)
|
null | null | null | When does a list return ?
| def returns_typeclass_list(method):
def func(self, *args, **kwargs):
self.__doc__ = method.__doc__
raw_queryset = kwargs.pop('raw_queryset', False)
result = method(self, *args, **kwargs)
if raw_queryset:
return result
else:
return list(result)
return update_wrapper(func, method)
| null | null | null | always
| codeqa | def returns typeclass list method def func self *args **kwargs self doc method doc raw queryset kwargs pop 'raw queryset' False result method self *args **kwargs if raw queryset return resultelse return list result return update wrapper func method
| null | null | null | null | Question:
When does a list return ?
Code:
def returns_typeclass_list(method):
def func(self, *args, **kwargs):
self.__doc__ = method.__doc__
raw_queryset = kwargs.pop('raw_queryset', False)
result = method(self, *args, **kwargs)
if raw_queryset:
return result
else:
return list(result)
return updat... |
null | null | null | What does a class provide ?
| def make_istatechange_tests(klass, kwargs1, kwargs2):
def instance(kwargs):
if isinstance(kwargs, dict):
return klass(**kwargs)
return klass(**kwargs())
class Tests(make_comparison_tests(klass, kwargs1, kwargs2), ):
def test_interface(self):
'\n The class implements ``IStateChange``.\n ... | null | null | null | istatechange
| codeqa | def make istatechange tests klass kwargs 1 kwargs 2 def instance kwargs if isinstance kwargs dict return klass **kwargs return klass **kwargs class Tests make comparison tests klass kwargs 1 kwargs 2 def test interface self '\n Theclassimplements``I State Change`` \n'self assert True verify Object I State Change instan... | null | null | null | null | Question:
What does a class provide ?
Code:
def make_istatechange_tests(klass, kwargs1, kwargs2):
def instance(kwargs):
if isinstance(kwargs, dict):
return klass(**kwargs)
return klass(**kwargs())
class Tests(make_comparison_tests(klass, kwargs1, kwargs2), ):
def test_interface(self):
'\n ... |
null | null | null | For what purpose do tests create ?
| def make_istatechange_tests(klass, kwargs1, kwargs2):
def instance(kwargs):
if isinstance(kwargs, dict):
return klass(**kwargs)
return klass(**kwargs())
class Tests(make_comparison_tests(klass, kwargs1, kwargs2), ):
def test_interface(self):
'\n The class implements ``IStateChange``.\n ... | null | null | null | to verify a class
| codeqa | def make istatechange tests klass kwargs 1 kwargs 2 def instance kwargs if isinstance kwargs dict return klass **kwargs return klass **kwargs class Tests make comparison tests klass kwargs 1 kwargs 2 def test interface self '\n Theclassimplements``I State Change`` \n'self assert True verify Object I State Change instan... | null | null | null | null | Question:
For what purpose do tests create ?
Code:
def make_istatechange_tests(klass, kwargs1, kwargs2):
def instance(kwargs):
if isinstance(kwargs, dict):
return klass(**kwargs)
return klass(**kwargs())
class Tests(make_comparison_tests(klass, kwargs1, kwargs2), ):
def test_interface(self):
'\n ... |
null | null | null | How does a function return ?
| def return_future(f):
replacer = ArgReplacer(f, 'callback')
@functools.wraps(f)
def wrapper(*args, **kwargs):
future = TracebackFuture()
(callback, args, kwargs) = replacer.replace((lambda value=_NO_RESULT: future.set_result(value)), args, kwargs)
def handle_error(typ, value, tb):
future.set_exc_info((typ, ... | null | null | null | via callback
| codeqa | def return future f replacer Arg Replacer f 'callback' @functools wraps f def wrapper *args **kwargs future Traceback Future callback args kwargs replacer replace lambda value NO RESULT future set result value args kwargs def handle error typ value tb future set exc info typ value tb return Trueexc info Nonewith Except... | null | null | null | null | Question:
How does a function return ?
Code:
def return_future(f):
replacer = ArgReplacer(f, 'callback')
@functools.wraps(f)
def wrapper(*args, **kwargs):
future = TracebackFuture()
(callback, args, kwargs) = replacer.replace((lambda value=_NO_RESULT: future.set_result(value)), args, kwargs)
def handle_err... |
null | null | null | What does the code delete ?
| def delete_user(user_name, region=None, key=None, keyid=None, profile=None):
if (not get_user(user_name, region, key, keyid, profile)):
return True
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn.delete_user(user_name)
log.info('Deleted user : {0} .'.format(user_name))
re... | null | null | null | a user
| codeqa | def delete user user name region None key None keyid None profile None if not get user user name region key keyid profile return Trueconn get conn region region key key keyid keyid profile profile try conn delete user user name log info ' Deleteduser {0 } ' format user name return Trueexcept boto exception Boto Server ... | null | null | null | null | Question:
What does the code delete ?
Code:
def delete_user(user_name, region=None, key=None, keyid=None, profile=None):
if (not get_user(user_name, region, key, keyid, profile)):
return True
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn.delete_user(user_name)
log.info('D... |
null | null | null | How does the code destroy a machine ?
| def destroy(name, call=None):
if (call == 'function'):
raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.')
__utils__['cloud.fire_event']('event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_d... | null | null | null | by name
| codeqa | def destroy name call None if call 'function' raise Salt Cloud System Exit ' Thedestroyactionmustbecalledwith-d --destroy -aor--action ' utils ['cloud fire event'] 'event' 'destroyinginstance' 'salt/cloud/{ 0 }/destroying' format name args {'name' name} sock dir opts ['sock dir'] transport opts ['transport'] node get n... | null | null | null | null | Question:
How does the code destroy a machine ?
Code:
def destroy(name, call=None):
if (call == 'function'):
raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.')
__utils__['cloud.fire_event']('event', 'destroying instance', 'salt/cloud/{0}/destroying'.fo... |
null | null | null | What does the code destroy by name ?
| def destroy(name, call=None):
if (call == 'function'):
raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.')
__utils__['cloud.fire_event']('event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_d... | null | null | null | a machine
| codeqa | def destroy name call None if call 'function' raise Salt Cloud System Exit ' Thedestroyactionmustbecalledwith-d --destroy -aor--action ' utils ['cloud fire event'] 'event' 'destroyinginstance' 'salt/cloud/{ 0 }/destroying' format name args {'name' name} sock dir opts ['sock dir'] transport opts ['transport'] node get n... | null | null | null | null | Question:
What does the code destroy by name ?
Code:
def destroy(name, call=None):
if (call == 'function'):
raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.')
__utils__['cloud.fire_event']('event', 'destroying instance', 'salt/cloud/{0}/destroying'.for... |
null | null | null | What read a line ?
| def read_and_call_until(uhandle, method, **keywds):
nlines = 0
while True:
line = safe_readline(uhandle)
if (not _fails_conditions(*(line,), **keywds)):
uhandle.saveline(line)
break
method(line)
nlines = (nlines + 1)
return nlines
| null | null | null | number of lines
| codeqa | def read and call until uhandle method **keywds nlines 0while True line safe readline uhandle if not fails conditions * line **keywds uhandle saveline line breakmethod line nlines nlines + 1 return nlines
| null | null | null | null | Question:
What read a line ?
Code:
def read_and_call_until(uhandle, method, **keywds):
nlines = 0
while True:
line = safe_readline(uhandle)
if (not _fails_conditions(*(line,), **keywds)):
uhandle.saveline(line)
break
method(line)
nlines = (nlines + 1)
return nlines
|
null | null | null | What do sass directories need ?
| def get_watcher_dirs(theme_dirs=None, themes=None):
dirs = []
dirs.extend(COMMON_LOOKUP_PATHS)
if (theme_dirs and themes):
themes = get_theme_paths(themes=themes, theme_dirs=theme_dirs)
for theme in themes:
for _dir in (get_sass_directories('lms', theme) + get_sass_directories('cms', theme)):
dirs.append(... | null | null | null | to be added to sass watcher
| codeqa | def get watcher dirs theme dirs None themes None dirs []dirs extend COMMON LOOKUP PATHS if theme dirs and themes themes get theme paths themes themes theme dirs theme dirs for theme in themes for dir in get sass directories 'lms' theme + get sass directories 'cms' theme dirs append dir['sass source dir'] dirs extend di... | null | null | null | null | Question:
What do sass directories need ?
Code:
def get_watcher_dirs(theme_dirs=None, themes=None):
dirs = []
dirs.extend(COMMON_LOOKUP_PATHS)
if (theme_dirs and themes):
themes = get_theme_paths(themes=themes, theme_dirs=theme_dirs)
for theme in themes:
for _dir in (get_sass_directories('lms', theme) + g... |
null | null | null | What does the code raise ?
| def construction_error(tot_items, block_shape, axes, e=None):
passed = tuple(map(int, ([tot_items] + list(block_shape))))
implied = tuple(map(int, [len(ax) for ax in axes]))
if ((passed == implied) and (e is not None)):
raise e
if (block_shape[0] == 0):
raise ValueError('Empty data passed with indices spec... | null | null | null | a helpful message about our construction
| codeqa | def construction error tot items block shape axes e None passed tuple map int [tot items] + list block shape implied tuple map int [len ax for ax in axes] if passed implied and e is not None raise eif block shape[ 0 ] 0 raise Value Error ' Emptydatapassedwithindicesspecified ' raise Value Error ' Shapeofpassedvaluesis{... | null | null | null | null | Question:
What does the code raise ?
Code:
def construction_error(tot_items, block_shape, axes, e=None):
passed = tuple(map(int, ([tot_items] + list(block_shape))))
implied = tuple(map(int, [len(ax) for ax in axes]))
if ((passed == implied) and (e is not None)):
raise e
if (block_shape[0] == 0):
raise Value... |
null | null | null | What does the code find ?
| def differential_evolution(func, bounds, args=(), strategy='best1bin', maxiter=1000, popsize=15, tol=0.01, mutation=(0.5, 1), recombination=0.7, seed=None, callback=None, disp=False, polish=True, init='latinhypercube', atol=0):
solver = DifferentialEvolutionSolver(func, bounds, args=args, strategy=strategy, maxiter=ma... | null | null | null | the global minimum of a multivariate function
| codeqa | def differential evolution func bounds args strategy 'best 1 bin' maxiter 1000 popsize 15 tol 0 01 mutation 0 5 1 recombination 0 7 seed None callback None disp False polish True init 'latinhypercube' atol 0 solver Differential Evolution Solver func bounds args args strategy strategy maxiter maxiter popsize popsize tol... | null | null | null | null | Question:
What does the code find ?
Code:
def differential_evolution(func, bounds, args=(), strategy='best1bin', maxiter=1000, popsize=15, tol=0.01, mutation=(0.5, 1), recombination=0.7, seed=None, callback=None, disp=False, polish=True, init='latinhypercube', atol=0):
solver = DifferentialEvolutionSolver(func, bo... |
null | null | null | When do the max length of a feature consider ?
| def test_feature_max_length_on_scenario():
feature = Feature.from_string(FEATURE1)
assert_equals(feature.max_length, 76)
| null | null | null | when the scenario is longer than the remaining things
| codeqa | def test feature max length on scenario feature Feature from string FEATURE 1 assert equals feature max length 76
| null | null | null | null | Question:
When do the max length of a feature consider ?
Code:
def test_feature_max_length_on_scenario():
feature = Feature.from_string(FEATURE1)
assert_equals(feature.max_length, 76)
|
null | null | null | What does the code ask interactively ?
| def ask(message, options):
while 1:
if os.environ.get('PIP_NO_INPUT'):
raise Exception(('No input was expected ($PIP_NO_INPUT set); question: %s' % message))
response = input(message)
response = response.strip().lower()
if (response not in options):
print ('Your response (%r) was not one of ... | null | null | null | the message
| codeqa | def ask message options while 1 if os environ get 'PIP NO INPUT' raise Exception ' Noinputwasexpected $PIP NO INPU Tset question %s' % message response input message response response strip lower if response not in options print ' Yourresponse %r wasnotoneoftheexpectedresponses %s' % response ' ' join options else retu... | null | null | null | null | Question:
What does the code ask interactively ?
Code:
def ask(message, options):
while 1:
if os.environ.get('PIP_NO_INPUT'):
raise Exception(('No input was expected ($PIP_NO_INPUT set); question: %s' % message))
response = input(message)
response = response.strip().lower()
if (response not in op... |
null | null | null | How does the code ask the message ?
| def ask(message, options):
while 1:
if os.environ.get('PIP_NO_INPUT'):
raise Exception(('No input was expected ($PIP_NO_INPUT set); question: %s' % message))
response = input(message)
response = response.strip().lower()
if (response not in options):
print ('Your response (%r) was not one of ... | null | null | null | interactively
| codeqa | def ask message options while 1 if os environ get 'PIP NO INPUT' raise Exception ' Noinputwasexpected $PIP NO INPU Tset question %s' % message response input message response response strip lower if response not in options print ' Yourresponse %r wasnotoneoftheexpectedresponses %s' % response ' ' join options else retu... | null | null | null | null | Question:
How does the code ask the message ?
Code:
def ask(message, options):
while 1:
if os.environ.get('PIP_NO_INPUT'):
raise Exception(('No input was expected ($PIP_NO_INPUT set); question: %s' % message))
response = input(message)
response = response.strip().lower()
if (response not in optio... |
null | null | null | What has the code delete if someone else has it ?
| def force_unlock():
get_lock(min_wait=0, max_wait=0.001, timeout=0)
release_lock()
| null | null | null | the compilation lock
| codeqa | def force unlock get lock min wait 0 max wait 0 001 timeout 0 release lock
| null | null | null | null | Question:
What has the code delete if someone else has it ?
Code:
def force_unlock():
get_lock(min_wait=0, max_wait=0.001, timeout=0)
release_lock()
|
null | null | null | What has it ?
| def force_unlock():
get_lock(min_wait=0, max_wait=0.001, timeout=0)
release_lock()
| null | null | null | someone else
| codeqa | def force unlock get lock min wait 0 max wait 0 001 timeout 0 release lock
| null | null | null | null | Question:
What has it ?
Code:
def force_unlock():
get_lock(min_wait=0, max_wait=0.001, timeout=0)
release_lock()
|
null | null | null | What does the code find ?
| def plurality(xs):
from collections import defaultdict
counts = defaultdict(int)
for x in xs:
counts[x] += 1
maxv = max(counts.values())
for (k, v) in counts.items():
if (v == maxv):
return k
| null | null | null | the most common element in a collection
| codeqa | def plurality xs from collections import defaultdictcounts defaultdict int for x in xs counts[x] + 1maxv max counts values for k v in counts items if v maxv return k
| null | null | null | null | Question:
What does the code find ?
Code:
def plurality(xs):
from collections import defaultdict
counts = defaultdict(int)
for x in xs:
counts[x] += 1
maxv = max(counts.values())
for (k, v) in counts.items():
if (v == maxv):
return k
|
null | null | null | What dumps the configuration ?
| def main():
if (not os.getenv('SERVER_SOFTWARE', '').startswith('Dev')):
from google.appengine.api import users
if (not users.is_current_user_admin()):
if (users.get_current_user() is None):
print 'Status: 302'
print 'Location:', users.create_login_url(os.getenv('PATH_INFO', ''))
else:
print 'St... | null | null | null | cgi - style request handler
| codeqa | def main if not os getenv 'SERVER SOFTWARE' '' startswith ' Dev' from google appengine api import usersif not users is current user admin if users get current user is None print ' Status 302 'print ' Location ' users create login url os getenv 'PATH INFO' '' else print ' Status 403 'printprint ' Forbidden'returnprint '... | null | null | null | null | Question:
What dumps the configuration ?
Code:
def main():
if (not os.getenv('SERVER_SOFTWARE', '').startswith('Dev')):
from google.appengine.api import users
if (not users.is_current_user_admin()):
if (users.get_current_user() is None):
print 'Status: 302'
print 'Location:', users.create_login_url... |
null | null | null | What does the code get an enrollment ?
| def _get_fake_enrollment(student_id, course_id):
for enrollment in _ENROLLMENTS:
if ((student_id == enrollment['student']) and (course_id == enrollment['course']['course_id'])):
return enrollment
| null | null | null | from the enrollments array
| codeqa | def get fake enrollment student id course id for enrollment in ENROLLMENTS if student id enrollment['student'] and course id enrollment['course']['course id'] return enrollment
| null | null | null | null | Question:
What does the code get an enrollment ?
Code:
def _get_fake_enrollment(student_id, course_id):
for enrollment in _ENROLLMENTS:
if ((student_id == enrollment['student']) and (course_id == enrollment['course']['course_id'])):
return enrollment
|
null | null | null | What is deciding what is to be updated when ?
| def _diff_cache_cluster(current, desired):
if (current.get('SecurityGroups') is not None):
current['SecurityGroupIds'] = [s['SecurityGroupId'] for s in current['SecurityGroups']]
if (current.get('CacheSecurityGroups') is not None):
current['CacheSecurityGroupNames'] = [c['CacheSecurityGroupName'] for c in current... | null | null | null | modify_cache_cluster
| codeqa | def diff cache cluster current desired if current get ' Security Groups' is not None current[' Security Group Ids'] [s[' Security Group Id'] for s in current[' Security Groups']]if current get ' Cache Security Groups' is not None current[' Cache Security Group Names'] [c[' Cache Security Group Name'] for c in current['... | null | null | null | null | Question:
What is deciding what is to be updated when ?
Code:
def _diff_cache_cluster(current, desired):
if (current.get('SecurityGroups') is not None):
current['SecurityGroupIds'] = [s['SecurityGroupId'] for s in current['SecurityGroups']]
if (current.get('CacheSecurityGroups') is not None):
current['CacheSe... |
null | null | null | When does modify_cache_cluster consider what ?
| def _diff_cache_cluster(current, desired):
if (current.get('SecurityGroups') is not None):
current['SecurityGroupIds'] = [s['SecurityGroupId'] for s in current['SecurityGroups']]
if (current.get('CacheSecurityGroups') is not None):
current['CacheSecurityGroupNames'] = [c['CacheSecurityGroupName'] for c in current... | null | null | null | when deciding what is to be updated
| codeqa | def diff cache cluster current desired if current get ' Security Groups' is not None current[' Security Group Ids'] [s[' Security Group Id'] for s in current[' Security Groups']]if current get ' Cache Security Groups' is not None current[' Cache Security Group Names'] [c[' Cache Security Group Name'] for c in current['... | null | null | null | null | Question:
When does modify_cache_cluster consider what ?
Code:
def _diff_cache_cluster(current, desired):
if (current.get('SecurityGroups') is not None):
current['SecurityGroupIds'] = [s['SecurityGroupId'] for s in current['SecurityGroups']]
if (current.get('CacheSecurityGroups') is not None):
current['CacheS... |
null | null | null | Where is a process listening already ?
| def already_listening(port, renewer=False):
if USE_PSUTIL:
return already_listening_psutil(port, renewer=renewer)
else:
logger.debug('Psutil not found, using simple socket check.')
return already_listening_socket(port, renewer=renewer)
| null | null | null | on the port
| codeqa | def already listening port renewer False if USE PSUTIL return already listening psutil port renewer renewer else logger debug ' Psutilnotfound usingsimplesocketcheck ' return already listening socket port renewer renewer
| null | null | null | null | Question:
Where is a process listening already ?
Code:
def already_listening(port, renewer=False):
if USE_PSUTIL:
return already_listening_psutil(port, renewer=renewer)
else:
logger.debug('Psutil not found, using simple socket check.')
return already_listening_socket(port, renewer=renewer)
|
null | null | null | What is listening on the port ?
| def already_listening(port, renewer=False):
if USE_PSUTIL:
return already_listening_psutil(port, renewer=renewer)
else:
logger.debug('Psutil not found, using simple socket check.')
return already_listening_socket(port, renewer=renewer)
| null | null | null | a process
| codeqa | def already listening port renewer False if USE PSUTIL return already listening psutil port renewer renewer else logger debug ' Psutilnotfound usingsimplesocketcheck ' return already listening socket port renewer renewer
| null | null | null | null | Question:
What is listening on the port ?
Code:
def already_listening(port, renewer=False):
if USE_PSUTIL:
return already_listening_psutil(port, renewer=renewer)
else:
logger.debug('Psutil not found, using simple socket check.')
return already_listening_socket(port, renewer=renewer)
|
null | null | null | When is a process listening on the port ?
| def already_listening(port, renewer=False):
if USE_PSUTIL:
return already_listening_psutil(port, renewer=renewer)
else:
logger.debug('Psutil not found, using simple socket check.')
return already_listening_socket(port, renewer=renewer)
| null | null | null | already
| codeqa | def already listening port renewer False if USE PSUTIL return already listening psutil port renewer renewer else logger debug ' Psutilnotfound usingsimplesocketcheck ' return already listening socket port renewer renewer
| null | null | null | null | Question:
When is a process listening on the port ?
Code:
def already_listening(port, renewer=False):
if USE_PSUTIL:
return already_listening_psutil(port, renewer=renewer)
else:
logger.debug('Psutil not found, using simple socket check.')
return already_listening_socket(port, renewer=renewer)
|
null | null | null | What does the code get ?
| def get_connection_helper(reactor, address, username, port):
try:
agentEndpoint = UNIXClientEndpoint(reactor, os.environ['SSH_AUTH_SOCK'])
except KeyError:
agentEndpoint = None
return _NewConnectionHelper(reactor, address, port, None, username, keys=None, password=None, agentEndpoint=agentEndpoint, knownHosts=Kn... | null | null | null | a : class : twisted
| codeqa | def get connection helper reactor address username port try agent Endpoint UNIX Client Endpoint reactor os environ['SSH AUTH SOCK'] except Key Error agent Endpoint Nonereturn New Connection Helper reactor address port None username keys None password None agent Endpoint agent Endpoint known Hosts Known Hosts File from ... | null | null | null | null | Question:
What does the code get ?
Code:
def get_connection_helper(reactor, address, username, port):
try:
agentEndpoint = UNIXClientEndpoint(reactor, os.environ['SSH_AUTH_SOCK'])
except KeyError:
agentEndpoint = None
return _NewConnectionHelper(reactor, address, port, None, username, keys=None, password=Non... |
null | null | null | What does the code get ?
| def getSelectedPluginName(plugins):
for plugin in plugins:
if plugin.value:
return plugin.name
return ''
| null | null | null | the selected plugin name
| codeqa | def get Selected Plugin Name plugins for plugin in plugins if plugin value return plugin namereturn ''
| null | null | null | null | Question:
What does the code get ?
Code:
def getSelectedPluginName(plugins):
for plugin in plugins:
if plugin.value:
return plugin.name
return ''
|
null | null | null | What does this function perform ?
| def s_one_one(topics):
s_one_one = []
for top_words in topics:
s_one_one_t = []
for (w_prime_index, w_prime) in enumerate(top_words):
for (w_star_index, w_star) in enumerate(top_words):
if (w_prime_index == w_star_index):
continue
else:
s_one_one_t.append((w_prime, w_star))
s_one_one.append... | null | null | null | s_one_one segmentation on a list of topics
| codeqa | def s one one topics s one one []for top words in topics s one one t []for w prime index w prime in enumerate top words for w star index w star in enumerate top words if w prime index w star index continueelse s one one t append w prime w star s one one append s one one t return s one one
| null | null | null | null | Question:
What does this function perform ?
Code:
def s_one_one(topics):
s_one_one = []
for top_words in topics:
s_one_one_t = []
for (w_prime_index, w_prime) in enumerate(top_words):
for (w_star_index, w_star) in enumerate(top_words):
if (w_prime_index == w_star_index):
continue
else:
s_... |
null | null | null | What does the code get from the filename and folder name ?
| def getModuleWithDirectoryPath(directoryPath, fileName):
if (fileName == ''):
print 'The file name in getModule in archive was empty.'
return None
originalSystemPath = sys.path[:]
try:
sys.path.insert(0, directoryPath)
folderPluginsModule = __import__(fileName)
sys.path = originalSystemPath
retur... | null | null | null | the module
| codeqa | def get Module With Directory Path directory Path file Name if file Name '' print ' Thefilenameinget Moduleinarchivewasempty 'return Noneoriginal System Path sys path[ ]try sys path insert 0 directory Path folder Plugins Module import file Name sys path original System Pathreturn folder Plugins Moduleexcept sys path or... | null | null | null | null | Question:
What does the code get from the filename and folder name ?
Code:
def getModuleWithDirectoryPath(directoryPath, fileName):
if (fileName == ''):
print 'The file name in getModule in archive was empty.'
return None
originalSystemPath = sys.path[:]
try:
sys.path.insert(0, directoryPath)
fol... |
null | null | null | What does the code write to a file ?
| def writeSettings(repository):
profilesDirectoryPath = archive.getProfilesPath(getProfileBaseName(repository))
archive.makeDirectory(os.path.dirname(profilesDirectoryPath))
archive.writeFileText(profilesDirectoryPath, getRepositoryText(repository))
| null | null | null | the settings
| codeqa | def write Settings repository profiles Directory Path archive get Profiles Path get Profile Base Name repository archive make Directory os path dirname profiles Directory Path archive write File Text profiles Directory Path get Repository Text repository
| null | null | null | null | Question:
What does the code write to a file ?
Code:
def writeSettings(repository):
profilesDirectoryPath = archive.getProfilesPath(getProfileBaseName(repository))
archive.makeDirectory(os.path.dirname(profilesDirectoryPath))
archive.writeFileText(profilesDirectoryPath, getRepositoryText(repository))
|
null | null | null | What have decorator declare ?
| def delay_denial(func):
func.delay_denial = True
@functools.wraps(func)
def wrapped(*a, **kw):
return func(*a, **kw)
return wrapped
| null | null | null | which methods should have any swift
| codeqa | def delay denial func func delay denial True@functools wraps func def wrapped *a **kw return func *a **kw return wrapped
| null | null | null | null | Question:
What have decorator declare ?
Code:
def delay_denial(func):
func.delay_denial = True
@functools.wraps(func)
def wrapped(*a, **kw):
return func(*a, **kw)
return wrapped
|
null | null | null | What should have any swift ?
| def delay_denial(func):
func.delay_denial = True
@functools.wraps(func)
def wrapped(*a, **kw):
return func(*a, **kw)
return wrapped
| null | null | null | which methods
| codeqa | def delay denial func func delay denial True@functools wraps func def wrapped *a **kw return func *a **kw return wrapped
| null | null | null | null | Question:
What should have any swift ?
Code:
def delay_denial(func):
func.delay_denial = True
@functools.wraps(func)
def wrapped(*a, **kw):
return func(*a, **kw)
return wrapped
|
null | null | null | Where does a reset operation perform ?
| def server_hardreset(host=None, admin_username=None, admin_password=None, module=None):
return __execute_cmd('serveraction hardreset', host=host, admin_username=admin_username, admin_password=admin_password, module=module)
| null | null | null | on the managed server
| codeqa | def server hardreset host None admin username None admin password None module None return execute cmd 'serveractionhardreset' host host admin username admin username admin password admin password module module
| null | null | null | null | Question:
Where does a reset operation perform ?
Code:
def server_hardreset(host=None, admin_username=None, admin_password=None, module=None):
return __execute_cmd('serveraction hardreset', host=host, admin_username=admin_username, admin_password=admin_password, module=module)
|
null | null | null | What performs on the managed server ?
| def server_hardreset(host=None, admin_username=None, admin_password=None, module=None):
return __execute_cmd('serveraction hardreset', host=host, admin_username=admin_username, admin_password=admin_password, module=module)
| null | null | null | a reset operation
| codeqa | def server hardreset host None admin username None admin password None module None return execute cmd 'serveractionhardreset' host host admin username admin username admin password admin password module module
| null | null | null | null | Question:
What performs on the managed server ?
Code:
def server_hardreset(host=None, admin_username=None, admin_password=None, module=None):
return __execute_cmd('serveraction hardreset', host=host, admin_username=admin_username, admin_password=admin_password, module=module)
|
null | null | null | What do we specify for everything ?
| def _pecan_generator_wrapper(func, *args, **kwargs):
kwargs.setdefault('content_type', 'application/json')
kwargs.setdefault('template', 'json')
return _composed(_protect_original_resources, db_api.retry_db_errors, func(*args, **kwargs))
| null | null | null | json
| codeqa | def pecan generator wrapper func *args **kwargs kwargs setdefault 'content type' 'application/json' kwargs setdefault 'template' 'json' return composed protect original resources db api retry db errors func *args **kwargs
| null | null | null | null | Question:
What do we specify for everything ?
Code:
def _pecan_generator_wrapper(func, *args, **kwargs):
kwargs.setdefault('content_type', 'application/json')
kwargs.setdefault('template', 'json')
return _composed(_protect_original_resources, db_api.retry_db_errors, func(*args, **kwargs))
|
null | null | null | What did the code set ?
| def _setwindowposition(folder_alias, (x, y)):
finder = _getfinder()
args = {}
attrs = {}
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form='alis', seld=folder_alias, fr=None)
aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form='prop', seld=aetypes.Type('cwnd'), fr=aeobj_0)
aeobj_2 = ... | null | null | null | the size of a finder window for folder to
| codeqa | def setwindowposition folder alias x y finder getfinder args {}attrs {}aeobj 0 aetypes Object Specifier want aetypes Type 'cfol' form 'alis' seld folder alias fr None aeobj 1 aetypes Object Specifier want aetypes Type 'prop' form 'prop' seld aetypes Type 'cwnd' fr aeobj 0 aeobj 2 aetypes Object Specifier want aetypes T... | null | null | null | null | Question:
What did the code set ?
Code:
def _setwindowposition(folder_alias, (x, y)):
finder = _getfinder()
args = {}
attrs = {}
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form='alis', seld=folder_alias, fr=None)
aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form='prop', seld=a... |
null | null | null | What does the code add ?
| def add_new_message(id, user, user_profile, text):
try:
if (not verification_user(id, user)):
return get_new_message_for_user(user)
if checking_conference(id):
conferences = get_memcached(get_key('conferences'))
for key in conferences[id]['users'].keys():
conferences[id]['users'][key]['messages'].appe... | null | null | null | new message
| codeqa | def add new message id user user profile text try if not verification user id user return get new message for user user if checking conference id conferences get memcached get key 'conferences' for key in conferences[id]['users'] keys conferences[id]['users'][key]['messages'] append dict user user text text time strfti... | null | null | null | null | Question:
What does the code add ?
Code:
def add_new_message(id, user, user_profile, text):
try:
if (not verification_user(id, user)):
return get_new_message_for_user(user)
if checking_conference(id):
conferences = get_memcached(get_key('conferences'))
for key in conferences[id]['users'].keys():
c... |
null | null | null | What does the code define ?
| def define_task(name, tick_script, task_type='stream', database=None, retention_policy='default'):
if (version() < '0.13'):
cmd = 'kapacitor define -name {0}'.format(name)
else:
cmd = 'kapacitor define {0}'.format(name)
if tick_script.startswith('salt://'):
tick_script = __salt__['cp.cache_file'](tick_scr... | null | null | null | a task
| codeqa | def define task name tick script task type 'stream' database None retention policy 'default' if version < '0 13 ' cmd 'kapacitordefine-name{ 0 }' format name else cmd 'kapacitordefine{ 0 }' format name if tick script startswith 'salt //' tick script salt ['cp cache file'] tick script env cmd + '-tick{ 0 }' format tick ... | null | null | null | null | Question:
What does the code define ?
Code:
def define_task(name, tick_script, task_type='stream', database=None, retention_policy='default'):
if (version() < '0.13'):
cmd = 'kapacitor define -name {0}'.format(name)
else:
cmd = 'kapacitor define {0}'.format(name)
if tick_script.startswith('salt://'):
... |
null | null | null | What does the code create ?
| @utils.arg('label', metavar='<network_label>', help=_('Network label (ex. my_new_network)'))
@utils.arg('cidr', metavar='<cidr>', help=_('IP block to allocate from (ex. 172.16.0.0/24 or 2001:DB8::/64)'))
@shell.deprecated_network
def do_tenant_network_create(cs, args):
network = cs.tenant_networks.create(ar... | null | null | null | a tenant network
| codeqa | @utils arg 'label' metavar '<network label>' help ' Networklabel ex my new network ' @utils arg 'cidr' metavar '<cidr>' help 'I Pblocktoallocatefrom ex 172 16 0 0/ 24 or 2001 DB 8 /64 ' @shell deprecated networkdef do tenant network create cs args network cs tenant networks create args label args cidr utils print dict ... | null | null | null | null | Question:
What does the code create ?
Code:
@utils.arg('label', metavar='<network_label>', help=_('Network label (ex. my_new_network)'))
@utils.arg('cidr', metavar='<cidr>', help=_('IP block to allocate from (ex. 172.16.0.0/24 or 2001:DB8::/64)'))
@shell.deprecated_network
def do_tenant_network_create(cs... |
null | null | null | What does the code encode ?
| def interval_encode(seconds, include_sign=False):
s = ''
orig = seconds
seconds = abs(seconds)
for (char, amount) in timeOrdered:
if (seconds >= amount):
(i, seconds) = divmod(seconds, amount)
s += ('%i%s' % (i, char))
if (orig < 0):
s = ('-' + s)
elif (not orig):
return '0'
elif include_sign:
s = ... | null | null | null | a number of seconds into a form like 1h2d3s
| codeqa | def interval encode seconds include sign False s ''orig secondsseconds abs seconds for char amount in time Ordered if seconds > amount i seconds divmod seconds amount s + '%i%s' % i char if orig < 0 s '-' + s elif not orig return '0 'elif include sign s '+' + s return s
| null | null | null | null | Question:
What does the code encode ?
Code:
def interval_encode(seconds, include_sign=False):
s = ''
orig = seconds
seconds = abs(seconds)
for (char, amount) in timeOrdered:
if (seconds >= amount):
(i, seconds) = divmod(seconds, amount)
s += ('%i%s' % (i, char))
if (orig < 0):
s = ('-' + s)
elif (no... |
null | null | null | What did the code use ?
| def agent_service_maintenance(consul_url=None, serviceid=None, **kwargs):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not serviceid):
... | null | null | null | to place a service into maintenance mode
| codeqa | def agent service maintenance consul url None serviceid None **kwargs ret {}query params {}if not consul url consul url get config if not consul url log error ' No Consul UR Lfound ' ret['message'] ' No Consul UR Lfound 'ret['res'] Falsereturn retif not serviceid raise Salt Invocation Error ' Requiredargument"serviceid... | null | null | null | null | Question:
What did the code use ?
Code:
def agent_service_maintenance(consul_url=None, serviceid=None, **kwargs):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res']... |
null | null | null | What does the code discover ?
| def rescan_iscsi_hba(session, cluster=None):
host_mor = vm_util.get_host_ref(session, cluster)
storage_system_mor = session._call_method(vim_util, 'get_dynamic_property', host_mor, 'HostSystem', 'configManager.storageSystem')
hbas_ret = session._call_method(vim_util, 'get_dynamic_property', storage_system_mor, 'Host... | null | null | null | iscsi targets
| codeqa | def rescan iscsi hba session cluster None host mor vm util get host ref session cluster storage system mor session call method vim util 'get dynamic property' host mor ' Host System' 'config Manager storage System' hbas ret session call method vim util 'get dynamic property' storage system mor ' Host Storage System' 's... | null | null | null | null | Question:
What does the code discover ?
Code:
def rescan_iscsi_hba(session, cluster=None):
host_mor = vm_util.get_host_ref(session, cluster)
storage_system_mor = session._call_method(vim_util, 'get_dynamic_property', host_mor, 'HostSystem', 'configManager.storageSystem')
hbas_ret = session._call_method(vim_util,... |
null | null | null | What are we running ?
| def is_py3():
import sys
return (sys.version_info[0] == 3)
| null | null | null | python 3
| codeqa | def is py 3 import sysreturn sys version info[ 0 ] 3
| null | null | null | null | Question:
What are we running ?
Code:
def is_py3():
import sys
return (sys.version_info[0] == 3)
|
null | null | null | What did the code rename to new ?
| def rename(old, new):
def rename_field(key, data, errors, context):
index = max(([int(k[1]) for k in data.keys() if ((len(k) == 3) and (k[0] == new))] + [(-1)]))
for field_name in data.keys():
if ((field_name[0] == old) and data.get(field_name)):
new_field_name = list(field_name)
new_field_name[0] = new... | null | null | null | a schema field
| codeqa | def rename old new def rename field key data errors context index max [int k[ 1 ] for k in data keys if len k 3 and k[ 0 ] new ] + [ -1 ] for field name in data keys if field name[ 0 ] old and data get field name new field name list field name new field name[ 0 ] newif len new field name > 1 new field name[ 1 ] int new... | null | null | null | null | Question:
What did the code rename to new ?
Code:
def rename(old, new):
def rename_field(key, data, errors, context):
index = max(([int(k[1]) for k in data.keys() if ((len(k) == 3) and (k[0] == new))] + [(-1)]))
for field_name in data.keys():
if ((field_name[0] == old) and data.get(field_name)):
new_fie... |
null | null | null | What does the code install ?
| def install(pkg=None, pkgs=None, user=None, install_global=False, env=None):
cmd = ['cabal install']
if install_global:
cmd.append('--global')
if pkg:
cmd.append('"{0}"'.format(pkg))
elif pkgs:
cmd.append('"{0}"'.format('" "'.join(pkgs)))
result = __salt__['cmd.run_all'](' '.join(cmd), runas=user, env=env... | null | null | null | a cabal package
| codeqa | def install pkg None pkgs None user None install global False env None cmd ['cabalinstall']if install global cmd append '--global' if pkg cmd append '"{ 0 }"' format pkg elif pkgs cmd append '"{ 0 }"' format '""' join pkgs result salt ['cmd run all'] '' join cmd runas user env env if result['retcode'] 0 raise Command E... | null | null | null | null | Question:
What does the code install ?
Code:
def install(pkg=None, pkgs=None, user=None, install_global=False, env=None):
cmd = ['cabal install']
if install_global:
cmd.append('--global')
if pkg:
cmd.append('"{0}"'.format(pkg))
elif pkgs:
cmd.append('"{0}"'.format('" "'.join(pkgs)))
result = __salt__['... |
null | null | null | For what purpose are packages marked ?
| def _find_unpurge_targets(desired):
return [x for x in desired if (x in __salt__['pkg.list_pkgs'](purge_desired=True))]
| null | null | null | to be purged
| codeqa | def find unpurge targets desired return [x for x in desired if x in salt ['pkg list pkgs'] purge desired True ]
| null | null | null | null | Question:
For what purpose are packages marked ?
Code:
def _find_unpurge_targets(desired):
return [x for x in desired if (x in __salt__['pkg.list_pkgs'](purge_desired=True))]
|
null | null | null | What do you want when ?
| def to_javascript(obj):
return json.dumps(obj).replace(u'</', u'<\\/')
| null | null | null | to inject an object into a < script > tag
| codeqa | def to javascript obj return json dumps obj replace u'</' u'<\\/'
| null | null | null | null | Question:
What do you want when ?
Code:
def to_javascript(obj):
return json.dumps(obj).replace(u'</', u'<\\/')
|
null | null | null | What do you inject into a < script > tag ?
| def to_javascript(obj):
return json.dumps(obj).replace(u'</', u'<\\/')
| null | null | null | an object
| codeqa | def to javascript obj return json dumps obj replace u'</' u'<\\/'
| null | null | null | null | Question:
What do you inject into a < script > tag ?
Code:
def to_javascript(obj):
return json.dumps(obj).replace(u'</', u'<\\/')
|
null | null | null | What does the code get ?
| @task
def get_previous_version_tag():
shortversion = get_sympy_short_version()
curcommit = 'HEAD'
with cd('/home/vagrant/repos/sympy'):
while True:
curtag = run(('git describe --abbrev=0 --tags ' + curcommit)).strip()
if (shortversion in curtag):
parents = local(('git rev-list --parents -n 1 ' +... | null | null | null | the version of the previous release
| codeqa | @taskdef get previous version tag shortversion get sympy short version curcommit 'HEAD'with cd '/home/vagrant/repos/sympy' while True curtag run 'gitdescribe--abbrev 0--tags' + curcommit strip if shortversion in curtag parents local 'gitrev-list--parents-n 1 ' + curtag capture True strip split assert len parents 2 curt... | null | null | null | null | Question:
What does the code get ?
Code:
@task
def get_previous_version_tag():
shortversion = get_sympy_short_version()
curcommit = 'HEAD'
with cd('/home/vagrant/repos/sympy'):
while True:
curtag = run(('git describe --abbrev=0 --tags ' + curcommit)).strip()
if (shortversion in curtag):
parents =... |
null | null | null | What does the code generate ?
| def get_seqs_to_keep_lookup_from_seq_id_file(id_to_keep_f):
return set([l.split()[0].strip() for l in id_to_keep_f if (l.strip() and (not l.startswith('#')))])
| null | null | null | a lookup dict of chimeras in chimera file
| codeqa | def get seqs to keep lookup from seq id file id to keep f return set [l split [0 ] strip for l in id to keep f if l strip and not l startswith '#' ]
| null | null | null | null | Question:
What does the code generate ?
Code:
def get_seqs_to_keep_lookup_from_seq_id_file(id_to_keep_f):
return set([l.split()[0].strip() for l in id_to_keep_f if (l.strip() and (not l.startswith('#')))])
|
null | null | null | What did the code set on an instance ?
| def instance_update(context, instance_uuid, values, update_cells=True):
rv = IMPL.instance_update(context, instance_uuid, values)
if update_cells:
try:
cells_rpcapi.CellsAPI().instance_update_at_top(context, rv)
except Exception:
LOG.exception(_('Failed to notify cells of instance update'))
return rv... | null | null | null | the given properties
| codeqa | def instance update context instance uuid values update cells True rv IMPL instance update context instance uuid values if update cells try cells rpcapi Cells API instance update at top context rv except Exception LOG exception ' Failedtonotifycellsofinstanceupdate' return rv
| null | null | null | null | Question:
What did the code set on an instance ?
Code:
def instance_update(context, instance_uuid, values, update_cells=True):
rv = IMPL.instance_update(context, instance_uuid, values)
if update_cells:
try:
cells_rpcapi.CellsAPI().instance_update_at_top(context, rv)
except Exception:
LOG.exception(_('Fa... |
null | null | null | What does the code remove from the given certificate store ?
| def remove_cert(thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE):
thumbprint = thumbprint.upper()
store_path = 'Cert:\\{0}\\{1}'.format(context, store)
cert_path = '{0}\\{1}'.format(store_path, thumbprint)
cmd = "Remove-Item -Path '{0}'".format(cert_path)
current_certs = get_certs(context=context, sto... | null | null | null | the certificate
| codeqa | def remove cert thumbprint context DEFAULT CONTEXT store DEFAULT STORE thumbprint thumbprint upper store path ' Cert \\{ 0 }\\{ 1 }' format context store cert path '{ 0 }\\{ 1 }' format store path thumbprint cmd " Remove- Item- Path'{ 0 }'" format cert path current certs get certs context context store store if thumbpr... | null | null | null | null | Question:
What does the code remove from the given certificate store ?
Code:
def remove_cert(thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE):
thumbprint = thumbprint.upper()
store_path = 'Cert:\\{0}\\{1}'.format(context, store)
cert_path = '{0}\\{1}'.format(store_path, thumbprint)
cmd = "Remove-Item... |
null | null | null | What did a client connection give ?
| def interface(host):
if (host == '0.0.0.0'):
return '127.0.0.1'
if (host == '::'):
return '::1'
return host
| null | null | null | the server host
| codeqa | def interface host if host '0 0 0 0' return '127 0 0 1'if host ' ' return ' 1'return host
| null | null | null | null | Question:
What did a client connection give ?
Code:
def interface(host):
if (host == '0.0.0.0'):
return '127.0.0.1'
if (host == '::'):
return '::1'
return host
|
null | null | null | What given the server host ?
| def interface(host):
if (host == '0.0.0.0'):
return '127.0.0.1'
if (host == '::'):
return '::1'
return host
| null | null | null | a client connection
| codeqa | def interface host if host '0 0 0 0' return '127 0 0 1'if host ' ' return ' 1'return host
| null | null | null | null | Question:
What given the server host ?
Code:
def interface(host):
if (host == '0.0.0.0'):
return '127.0.0.1'
if (host == '::'):
return '::1'
return host
|
null | null | null | What does the code return ?
| def _ListUnion(list_1, list_2):
if (not (isinstance(list_1, list) and isinstance(list_2, list))):
raise TypeError('Arguments must be lists.')
union = []
for x in (list_1 + list_2):
if (x not in union):
union.append(x)
return union
| null | null | null | the union of two lists
| codeqa | def List Union list 1 list 2 if not isinstance list 1 list and isinstance list 2 list raise Type Error ' Argumentsmustbelists ' union []for x in list 1 + list 2 if x not in union union append x return union
| null | null | null | null | Question:
What does the code return ?
Code:
def _ListUnion(list_1, list_2):
if (not (isinstance(list_1, list) and isinstance(list_2, list))):
raise TypeError('Arguments must be lists.')
union = []
for x in (list_1 + list_2):
if (x not in union):
union.append(x)
return union
|
null | null | null | What does the code reboot into rescue mode ?
| @utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
@utils.arg('--password', metavar='<password>', dest='password', help=_('The admin password to be set in the rescue environment.'))
@utils.arg('--image', metavar='<image>', dest='image', help=_('The image to rescue with.'))
def do... | null | null | null | a server
| codeqa | @utils arg 'server' metavar '<server>' help ' Nameor I Dofserver ' @utils arg '--password' metavar '<password>' dest 'password' help ' Theadminpasswordtobesetintherescueenvironment ' @utils arg '--image' metavar '<image>' dest 'image' help ' Theimagetorescuewith ' def do rescue cs args kwargs {}if args image kwargs['im... | null | null | null | null | Question:
What does the code reboot into rescue mode ?
Code:
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
@utils.arg('--password', metavar='<password>', dest='password', help=_('The admin password to be set in the rescue environment.'))
@utils.arg('--image', metavar='<image... |
null | null | null | What do campfire send build notifications ?
| def campfire(registry, xml_parent, data):
root = XML.SubElement(xml_parent, 'hudson.plugins.campfire.CampfireNotifier')
campfire = XML.SubElement(root, 'campfire')
if (('subdomain' in data) and data['subdomain']):
subdomain = XML.SubElement(campfire, 'subdomain')
subdomain.text = data['subdomain']
if (('token' ... | null | null | null | to campfire rooms
| codeqa | def campfire registry xml parent data root XML Sub Element xml parent 'hudson plugins campfire Campfire Notifier' campfire XML Sub Element root 'campfire' if 'subdomain' in data and data['subdomain'] subdomain XML Sub Element campfire 'subdomain' subdomain text data['subdomain']if 'token' in data and data['token'] toke... | null | null | null | null | Question:
What do campfire send build notifications ?
Code:
def campfire(registry, xml_parent, data):
root = XML.SubElement(xml_parent, 'hudson.plugins.campfire.CampfireNotifier')
campfire = XML.SubElement(root, 'campfire')
if (('subdomain' in data) and data['subdomain']):
subdomain = XML.SubElement(campfire, ... |
null | null | null | What do campfire send to campfire rooms ?
| def campfire(registry, xml_parent, data):
root = XML.SubElement(xml_parent, 'hudson.plugins.campfire.CampfireNotifier')
campfire = XML.SubElement(root, 'campfire')
if (('subdomain' in data) and data['subdomain']):
subdomain = XML.SubElement(campfire, 'subdomain')
subdomain.text = data['subdomain']
if (('token' ... | null | null | null | build notifications
| codeqa | def campfire registry xml parent data root XML Sub Element xml parent 'hudson plugins campfire Campfire Notifier' campfire XML Sub Element root 'campfire' if 'subdomain' in data and data['subdomain'] subdomain XML Sub Element campfire 'subdomain' subdomain text data['subdomain']if 'token' in data and data['token'] toke... | null | null | null | null | Question:
What do campfire send to campfire rooms ?
Code:
def campfire(registry, xml_parent, data):
root = XML.SubElement(xml_parent, 'hudson.plugins.campfire.CampfireNotifier')
campfire = XML.SubElement(root, 'campfire')
if (('subdomain' in data) and data['subdomain']):
subdomain = XML.SubElement(campfire, 's... |
null | null | null | What send build notifications to campfire rooms ?
| def campfire(registry, xml_parent, data):
root = XML.SubElement(xml_parent, 'hudson.plugins.campfire.CampfireNotifier')
campfire = XML.SubElement(root, 'campfire')
if (('subdomain' in data) and data['subdomain']):
subdomain = XML.SubElement(campfire, 'subdomain')
subdomain.text = data['subdomain']
if (('token' ... | null | null | null | campfire
| codeqa | def campfire registry xml parent data root XML Sub Element xml parent 'hudson plugins campfire Campfire Notifier' campfire XML Sub Element root 'campfire' if 'subdomain' in data and data['subdomain'] subdomain XML Sub Element campfire 'subdomain' subdomain text data['subdomain']if 'token' in data and data['token'] toke... | null | null | null | null | Question:
What send build notifications to campfire rooms ?
Code:
def campfire(registry, xml_parent, data):
root = XML.SubElement(xml_parent, 'hudson.plugins.campfire.CampfireNotifier')
campfire = XML.SubElement(root, 'campfire')
if (('subdomain' in data) and data['subdomain']):
subdomain = XML.SubElement(camp... |
null | null | null | What does the code fetch ?
| @require_context
def volume_attachment_get_all_by_instance_uuid(context, instance_uuid):
session = get_session()
with session.begin():
result = model_query(context, models.VolumeAttachment, session=session).filter_by(instance_uuid=instance_uuid).filter((models.VolumeAttachment.attach_status != fields.VolumeAttachSt... | null | null | null | all attachment records associated with the specified instance
| codeqa | @require contextdef volume attachment get all by instance uuid context instance uuid session get session with session begin result model query context models Volume Attachment session session filter by instance uuid instance uuid filter models Volume Attachment attach status fields Volume Attach Status DETACHED options... | null | null | null | null | Question:
What does the code fetch ?
Code:
@require_context
def volume_attachment_get_all_by_instance_uuid(context, instance_uuid):
session = get_session()
with session.begin():
result = model_query(context, models.VolumeAttachment, session=session).filter_by(instance_uuid=instance_uuid).filter((models.VolumeAt... |
null | null | null | What does the code get ?
| def get_tempo(artist, title):
results = song.search(artist=artist, title=title, results=1, buckets=['audio_summary'])
if (len(results) > 0):
return results[0].audio_summary['tempo']
else:
return None
| null | null | null | the tempo for a song
| codeqa | def get tempo artist title results song search artist artist title title results 1 buckets ['audio summary'] if len results > 0 return results[ 0 ] audio summary['tempo']else return None
| null | null | null | null | Question:
What does the code get ?
Code:
def get_tempo(artist, title):
results = song.search(artist=artist, title=title, results=1, buckets=['audio_summary'])
if (len(results) > 0):
return results[0].audio_summary['tempo']
else:
return None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.