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 this function do?
def has_subdirectories(path, include, exclude, show_all): try: return (len(listdir(path, include, exclude, show_all, folders_only=True)) > 1) except (IOError, OSError): return False
null
null
null
Return True if path has subdirectories
pcsd
def has subdirectories path include exclude show all try return len listdir path include exclude show all folders only=True > 1 except IO Error OS Error return False
10917
def has_subdirectories(path, include, exclude, show_all): try: return (len(listdir(path, include, exclude, show_all, folders_only=True)) > 1) except (IOError, OSError): return False
Return True if path has subdirectories
return true if path has subdirectories
Question: What does this function do? Code: def has_subdirectories(path, include, exclude, show_all): try: return (len(listdir(path, include, exclude, show_all, folders_only=True)) > 1) except (IOError, OSError): return False
null
null
null
What does this function do?
def _check_to_native(self, in_string, encoding, py2_expected, py3_expected): if PY3: self.assertEqual(to_native(in_string, encoding), py3_expected) else: self.assertEqual(to_native(in_string, encoding), py2_expected)
null
null
null
test happy path of encoding to native strings
pcsd
def check to native self in string encoding py2 expected py3 expected if PY3 self assert Equal to native in string encoding py3 expected else self assert Equal to native in string encoding py2 expected
10926
def _check_to_native(self, in_string, encoding, py2_expected, py3_expected): if PY3: self.assertEqual(to_native(in_string, encoding), py3_expected) else: self.assertEqual(to_native(in_string, encoding), py2_expected)
test happy path of encoding to native strings
test happy path of encoding to native strings
Question: What does this function do? Code: def _check_to_native(self, in_string, encoding, py2_expected, py3_expected): if PY3: self.assertEqual(to_native(in_string, encoding), py3_expected) else: self.assertEqual(to_native(in_string, encoding), py2_expected)
null
null
null
What does this function do?
def print_queries(): for query in connection.queries: print (query['sql'] + ';\n')
null
null
null
Print all SQL queries executed so far. Useful for debugging failing tests - you can call it from tearDown(), and then execute the single test case of interest from the command line.
pcsd
def print queries for query in connection queries print query['sql'] + ' '
10927
def print_queries(): for query in connection.queries: print (query['sql'] + ';\n')
Print all SQL queries executed so far. Useful for debugging failing tests - you can call it from tearDown(), and then execute the single test case of interest from the command line.
print all sql queries executed so far .
Question: What does this function do? Code: def print_queries(): for query in connection.queries: print (query['sql'] + ';\n')
null
null
null
What does this function do?
def _plugin_replace_role(name, contents, plugins): for p in plugins: role_hook = p.get_role_hook(name) if role_hook: return role_hook(contents) return ':{0}:`{1}`'.format(name, contents)
null
null
null
The first plugin that handles this role is used.
pcsd
def plugin replace role name contents plugins for p in plugins role hook = p get role hook name if role hook return role hook contents return ' {0} `{1}`' format name contents
10929
def _plugin_replace_role(name, contents, plugins): for p in plugins: role_hook = p.get_role_hook(name) if role_hook: return role_hook(contents) return ':{0}:`{1}`'.format(name, contents)
The first plugin that handles this role is used.
the first plugin that handles this role is used .
Question: What does this function do? Code: def _plugin_replace_role(name, contents, plugins): for p in plugins: role_hook = p.get_role_hook(name) if role_hook: return role_hook(contents) return ':{0}:`{1}`'.format(name, contents)
null
null
null
What does this function do?
def wrap_things(*things): if (not things): return [] wrapped = [Wrapped(thing) for thing in things] if hasattr(things[0], 'add_props'): things[0].add_props(c.user, wrapped) return wrapped
null
null
null
Instantiate Wrapped for each thing, calling add_props if available.
pcsd
def wrap things *things if not things return [] wrapped = [Wrapped thing for thing in things] if hasattr things[0] 'add props' things[0] add props c user wrapped return wrapped
10931
def wrap_things(*things): if (not things): return [] wrapped = [Wrapped(thing) for thing in things] if hasattr(things[0], 'add_props'): things[0].add_props(c.user, wrapped) return wrapped
Instantiate Wrapped for each thing, calling add_props if available.
instantiate wrapped for each thing , calling add _ props if available .
Question: What does this function do? Code: def wrap_things(*things): if (not things): return [] wrapped = [Wrapped(thing) for thing in things] if hasattr(things[0], 'add_props'): things[0].add_props(c.user, wrapped) return wrapped
null
null
null
What does this function do?
def _get_echo_exe_path(): if (sys.platform == 'win32'): return os.path.join(utils.abs_datapath(), 'userscripts', 'echo.bat') else: return 'echo'
null
null
null
Return the path to an echo-like command, depending on the system. Return: Path to the "echo"-utility.
pcsd
def get echo exe path if sys platform == 'win32' return os path join utils abs datapath 'userscripts' 'echo bat' else return 'echo'
10939
def _get_echo_exe_path(): if (sys.platform == 'win32'): return os.path.join(utils.abs_datapath(), 'userscripts', 'echo.bat') else: return 'echo'
Return the path to an echo-like command, depending on the system. Return: Path to the "echo"-utility.
return the path to an echo - like command , depending on the system .
Question: What does this function do? Code: def _get_echo_exe_path(): if (sys.platform == 'win32'): return os.path.join(utils.abs_datapath(), 'userscripts', 'echo.bat') else: return 'echo'
null
null
null
What does this function do?
def delete(request, course_id, note_id): try: note = Note.objects.get(id=note_id) except Note.DoesNotExist: return ApiResponse(http_response=HttpResponse('', status=404), data=None) if (note.user.id != request.user.id): return ApiResponse(http_response=HttpResponse('', status=403), data=None) note.delete() r...
null
null
null
Deletes the annotation object and returns a 204 with no content.
pcsd
def delete request course id note id try note = Note objects get id=note id except Note Does Not Exist return Api Response http response=Http Response '' status=404 data=None if note user id != request user id return Api Response http response=Http Response '' status=403 data=None note delete return Api Response http r...
10942
def delete(request, course_id, note_id): try: note = Note.objects.get(id=note_id) except Note.DoesNotExist: return ApiResponse(http_response=HttpResponse('', status=404), data=None) if (note.user.id != request.user.id): return ApiResponse(http_response=HttpResponse('', status=403), data=None) note.delete() r...
Deletes the annotation object and returns a 204 with no content.
deletes the annotation object and returns a 204 with no content .
Question: What does this function do? Code: def delete(request, course_id, note_id): try: note = Note.objects.get(id=note_id) except Note.DoesNotExist: return ApiResponse(http_response=HttpResponse('', status=404), data=None) if (note.user.id != request.user.id): return ApiResponse(http_response=HttpRespons...
null
null
null
What does this function do?
def _is_xfce(): try: return _readfrom((_get_x11_vars() + 'xprop -root _DT_SAVE_MODE'), shell=1).decode('utf-8').strip().endswith(' = "xfce4"') except OSError: return 0
null
null
null
Return whether XFCE is in use.
pcsd
def is xfce try return readfrom get x11 vars + 'xprop -root DT SAVE MODE' shell=1 decode 'utf-8' strip endswith ' = "xfce4"' except OS Error return 0
10944
def _is_xfce(): try: return _readfrom((_get_x11_vars() + 'xprop -root _DT_SAVE_MODE'), shell=1).decode('utf-8').strip().endswith(' = "xfce4"') except OSError: return 0
Return whether XFCE is in use.
return whether xfce is in use .
Question: What does this function do? Code: def _is_xfce(): try: return _readfrom((_get_x11_vars() + 'xprop -root _DT_SAVE_MODE'), shell=1).decode('utf-8').strip().endswith(' = "xfce4"') except OSError: return 0
null
null
null
What does this function do?
def backend_cache_page(handler, cache_time=None, cache_name=None): if (not cache_time): cache_time = settings.CACHE_TIME if (not cache_name): cache_name = 'default' if caching_is_enabled(): @condition(last_modified_func=partial(calc_last_modified, cache_name=cache_name)) @cache_control(no_cache=True) @cach...
null
null
null
Applies all logic for getting a page to cache in our backend, and never in the browser, so we can control things from Django/Python. This function does this all with the settings we want, specified in settings.
pcsd
def backend cache page handler cache time=None cache name=None if not cache time cache time = settings CACHE TIME if not cache name cache name = 'default' if caching is enabled @condition last modified func=partial calc last modified cache name=cache name @cache control no cache=True @cache page cache time cache=cache ...
10949
def backend_cache_page(handler, cache_time=None, cache_name=None): if (not cache_time): cache_time = settings.CACHE_TIME if (not cache_name): cache_name = 'default' if caching_is_enabled(): @condition(last_modified_func=partial(calc_last_modified, cache_name=cache_name)) @cache_control(no_cache=True) @cach...
Applies all logic for getting a page to cache in our backend, and never in the browser, so we can control things from Django/Python. This function does this all with the settings we want, specified in settings.
applies all logic for getting a page to cache in our backend , and never in the browser , so we can control things from django / python .
Question: What does this function do? Code: def backend_cache_page(handler, cache_time=None, cache_name=None): if (not cache_time): cache_time = settings.CACHE_TIME if (not cache_name): cache_name = 'default' if caching_is_enabled(): @condition(last_modified_func=partial(calc_last_modified, cache_name=cache...
null
null
null
What does this function do?
def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None): token = _get_token() username = __opts__.get('rallydev', {}).get('username', None) password = __opts__.get('rallydev', {}).get('password', None) path = 'https://rally1.rallydev.com/slm/webservice/v2.0/' if action: path +...
null
null
null
Make a web call to RallyDev.
pcsd
def query action=None command=None args=None method='GET' header dict=None data=None token = get token username = opts get 'rallydev' {} get 'username' None password = opts get 'rallydev' {} get 'password' None path = 'https //rally1 rallydev com/slm/webservice/v2 0/' if action path += action if command path += '/{0}' ...
10951
def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None): token = _get_token() username = __opts__.get('rallydev', {}).get('username', None) password = __opts__.get('rallydev', {}).get('password', None) path = 'https://rally1.rallydev.com/slm/webservice/v2.0/' if action: path +...
Make a web call to RallyDev.
make a web call to rallydev .
Question: What does this function do? Code: def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None): token = _get_token() username = __opts__.get('rallydev', {}).get('username', None) password = __opts__.get('rallydev', {}).get('password', None) path = 'https://rally1.rallydev...
null
null
null
What does this function do?
def validate_commit_message(val): try: (val % {'language': 'cs', 'language_name': 'Czech', 'project': 'Weblate', 'subproject': 'master', 'total': 200, 'fuzzy': 20, 'fuzzy_percent': 10.0, 'translated': 40, 'translated_percent': 20.0}) except Exception as error: raise ValidationError((_('Bad format string (%s)') % ...
null
null
null
Validates that commit message is a valid format string.
pcsd
def validate commit message val try val % {'language' 'cs' 'language name' 'Czech' 'project' 'Weblate' 'subproject' 'master' 'total' 200 'fuzzy' 20 'fuzzy percent' 10 0 'translated' 40 'translated percent' 20 0} except Exception as error raise Validation Error 'Bad format string %s ' % str error
10958
def validate_commit_message(val): try: (val % {'language': 'cs', 'language_name': 'Czech', 'project': 'Weblate', 'subproject': 'master', 'total': 200, 'fuzzy': 20, 'fuzzy_percent': 10.0, 'translated': 40, 'translated_percent': 20.0}) except Exception as error: raise ValidationError((_('Bad format string (%s)') % ...
Validates that commit message is a valid format string.
validates that commit message is a valid format string .
Question: What does this function do? Code: def validate_commit_message(val): try: (val % {'language': 'cs', 'language_name': 'Czech', 'project': 'Weblate', 'subproject': 'master', 'total': 200, 'fuzzy': 20, 'fuzzy_percent': 10.0, 'translated': 40, 'translated_percent': 20.0}) except Exception as error: raise ...
null
null
null
What does this function do?
def _make_image_mask(outlines, pos, res): mask_ = np.c_[outlines['mask_pos']] (xmin, xmax) = (np.min(np.r_[(np.inf, mask_[:, 0])]), np.max(np.r_[((- np.inf), mask_[:, 0])])) (ymin, ymax) = (np.min(np.r_[(np.inf, mask_[:, 1])]), np.max(np.r_[((- np.inf), mask_[:, 1])])) if (outlines.get('autoshrink', False) is not F...
null
null
null
Make an image mask.
pcsd
def make image mask outlines pos res mask = np c [outlines['mask pos']] xmin xmax = np min np r [ np inf mask [ 0] ] np max np r [ - np inf mask [ 0] ] ymin ymax = np min np r [ np inf mask [ 1] ] np max np r [ - np inf mask [ 1] ] if outlines get 'autoshrink' False is not False inside = inside contour pos mask outside...
10962
def _make_image_mask(outlines, pos, res): mask_ = np.c_[outlines['mask_pos']] (xmin, xmax) = (np.min(np.r_[(np.inf, mask_[:, 0])]), np.max(np.r_[((- np.inf), mask_[:, 0])])) (ymin, ymax) = (np.min(np.r_[(np.inf, mask_[:, 1])]), np.max(np.r_[((- np.inf), mask_[:, 1])])) if (outlines.get('autoshrink', False) is not F...
Make an image mask.
make an image mask .
Question: What does this function do? Code: def _make_image_mask(outlines, pos, res): mask_ = np.c_[outlines['mask_pos']] (xmin, xmax) = (np.min(np.r_[(np.inf, mask_[:, 0])]), np.max(np.r_[((- np.inf), mask_[:, 0])])) (ymin, ymax) = (np.min(np.r_[(np.inf, mask_[:, 1])]), np.max(np.r_[((- np.inf), mask_[:, 1])])) ...
null
null
null
What does this function do?
def _record_from_json(value, field): if _not_null(value, field): record = {} record_iter = zip(field.fields, value['f']) for (subfield, cell) in record_iter: converter = _CELLDATA_FROM_JSON[subfield.field_type] if (subfield.mode == 'REPEATED'): value = [converter(item['v'], subfield) for item in cell['...
null
null
null
Coerce \'value\' to a mapping, if set or not nullable.
pcsd
def record from json value field if not null value field record = {} record iter = zip field fields value['f'] for subfield cell in record iter converter = CELLDATA FROM JSON[subfield field type] if subfield mode == 'REPEATED' value = [converter item['v'] subfield for item in cell['v']] else value = converter cell['v']...
10965
def _record_from_json(value, field): if _not_null(value, field): record = {} record_iter = zip(field.fields, value['f']) for (subfield, cell) in record_iter: converter = _CELLDATA_FROM_JSON[subfield.field_type] if (subfield.mode == 'REPEATED'): value = [converter(item['v'], subfield) for item in cell['...
Coerce \'value\' to a mapping, if set or not nullable.
coerce value to a mapping , if set or not nullable .
Question: What does this function do? Code: def _record_from_json(value, field): if _not_null(value, field): record = {} record_iter = zip(field.fields, value['f']) for (subfield, cell) in record_iter: converter = _CELLDATA_FROM_JSON[subfield.field_type] if (subfield.mode == 'REPEATED'): value = [co...
null
null
null
What does this function do?
def settings(request=None): from mezzanine.conf import settings allowed_settings = settings.TEMPLATE_ACCESSIBLE_SETTINGS template_settings = TemplateSettings(settings, allowed_settings) template_settings.update(DEPRECATED) admin_prefix = (u'grappelli/' if settings.GRAPPELLI_INSTALLED else u'admin/') template_sett...
null
null
null
Add the settings object to the template context.
pcsd
def settings request=None from mezzanine conf import settings allowed settings = settings TEMPLATE ACCESSIBLE SETTINGS template settings = Template Settings settings allowed settings template settings update DEPRECATED admin prefix = u'grappelli/' if settings GRAPPELLI INSTALLED else u'admin/' template settings[u'MEZZA...
10967
def settings(request=None): from mezzanine.conf import settings allowed_settings = settings.TEMPLATE_ACCESSIBLE_SETTINGS template_settings = TemplateSettings(settings, allowed_settings) template_settings.update(DEPRECATED) admin_prefix = (u'grappelli/' if settings.GRAPPELLI_INSTALLED else u'admin/') template_sett...
Add the settings object to the template context.
add the settings object to the template context .
Question: What does this function do? Code: def settings(request=None): from mezzanine.conf import settings allowed_settings = settings.TEMPLATE_ACCESSIBLE_SETTINGS template_settings = TemplateSettings(settings, allowed_settings) template_settings.update(DEPRECATED) admin_prefix = (u'grappelli/' if settings.GRA...
null
null
null
What does this function do?
def change_settings(new_settings={}, file=None): gl = globals() if (file is not None): execfile(file) gl.update(locals()) gl.update(new_settings)
null
null
null
Changes the value of configuration variables.
pcsd
def change settings new settings={} file=None gl = globals if file is not None execfile file gl update locals gl update new settings
10968
def change_settings(new_settings={}, file=None): gl = globals() if (file is not None): execfile(file) gl.update(locals()) gl.update(new_settings)
Changes the value of configuration variables.
changes the value of configuration variables .
Question: What does this function do? Code: def change_settings(new_settings={}, file=None): gl = globals() if (file is not None): execfile(file) gl.update(locals()) gl.update(new_settings)
null
null
null
What does this function do?
def cleanQuery(query): retVal = query for sqlStatements in SQL_STATEMENTS.values(): for sqlStatement in sqlStatements: sqlStatementEsc = sqlStatement.replace('(', '\\(') queryMatch = re.search(('(%s)' % sqlStatementEsc), query, re.I) if (queryMatch and ('sys_exec' not in query)): retVal = retVal.replac...
null
null
null
Switch all SQL statement (alike) keywords to upper case
pcsd
def clean Query query ret Val = query for sql Statements in SQL STATEMENTS values for sql Statement in sql Statements sql Statement Esc = sql Statement replace ' ' '\\ ' query Match = re search ' %s ' % sql Statement Esc query re I if query Match and 'sys exec' not in query ret Val = ret Val replace query Match group 1...
10974
def cleanQuery(query): retVal = query for sqlStatements in SQL_STATEMENTS.values(): for sqlStatement in sqlStatements: sqlStatementEsc = sqlStatement.replace('(', '\\(') queryMatch = re.search(('(%s)' % sqlStatementEsc), query, re.I) if (queryMatch and ('sys_exec' not in query)): retVal = retVal.replac...
Switch all SQL statement (alike) keywords to upper case
switch all sql statement keywords to upper case
Question: What does this function do? Code: def cleanQuery(query): retVal = query for sqlStatements in SQL_STATEMENTS.values(): for sqlStatement in sqlStatements: sqlStatementEsc = sqlStatement.replace('(', '\\(') queryMatch = re.search(('(%s)' % sqlStatementEsc), query, re.I) if (queryMatch and ('sys_e...
null
null
null
What does this function do?
@register.inclusion_tag(u'admin/actions.html', takes_context=True) def admin_actions(context): context[u'action_index'] = (context.get(u'action_index', (-1)) + 1) return context
null
null
null
Track the number of times the action field has been rendered on the page, so we know which value to use.
pcsd
@register inclusion tag u'admin/actions html' takes context=True def admin actions context context[u'action index'] = context get u'action index' -1 + 1 return context
10975
@register.inclusion_tag(u'admin/actions.html', takes_context=True) def admin_actions(context): context[u'action_index'] = (context.get(u'action_index', (-1)) + 1) return context
Track the number of times the action field has been rendered on the page, so we know which value to use.
track the number of times the action field has been rendered on the page , so we know which value to use .
Question: What does this function do? Code: @register.inclusion_tag(u'admin/actions.html', takes_context=True) def admin_actions(context): context[u'action_index'] = (context.get(u'action_index', (-1)) + 1) return context
null
null
null
What does this function do?
def getGeometryOutputByArguments(arguments, elementNode): evaluate.setAttributesByArguments(['start', 'end', 'step'], arguments, elementNode) return getGeometryOutput(None, elementNode)
null
null
null
Get vector3 vertexes from attribute dictionary by arguments.
pcsd
def get Geometry Output By Arguments arguments element Node evaluate set Attributes By Arguments ['start' 'end' 'step'] arguments element Node return get Geometry Output None element Node
10977
def getGeometryOutputByArguments(arguments, elementNode): evaluate.setAttributesByArguments(['start', 'end', 'step'], arguments, elementNode) return getGeometryOutput(None, elementNode)
Get vector3 vertexes from attribute dictionary by arguments.
get vector3 vertexes from attribute dictionary by arguments .
Question: What does this function do? Code: def getGeometryOutputByArguments(arguments, elementNode): evaluate.setAttributesByArguments(['start', 'end', 'step'], arguments, elementNode) return getGeometryOutput(None, elementNode)
null
null
null
What does this function do?
def _get_version_from_pkg_info(package_name): try: pkg_info_file = open('PKG-INFO', 'r') except (IOError, OSError): return None try: pkg_info = email.message_from_file(pkg_info_file) except email.MessageError: return None if (pkg_info.get('Name', None) != package_name): return None return pkg_info.get('...
null
null
null
Get the version from PKG-INFO file if we can.
pcsd
def get version from pkg info package name try pkg info file = open 'PKG-INFO' 'r' except IO Error OS Error return None try pkg info = email message from file pkg info file except email Message Error return None if pkg info get 'Name' None != package name return None return pkg info get 'Version' None
10979
def _get_version_from_pkg_info(package_name): try: pkg_info_file = open('PKG-INFO', 'r') except (IOError, OSError): return None try: pkg_info = email.message_from_file(pkg_info_file) except email.MessageError: return None if (pkg_info.get('Name', None) != package_name): return None return pkg_info.get('...
Get the version from PKG-INFO file if we can.
get the version from pkg - info file if we can .
Question: What does this function do? Code: def _get_version_from_pkg_info(package_name): try: pkg_info_file = open('PKG-INFO', 'r') except (IOError, OSError): return None try: pkg_info = email.message_from_file(pkg_info_file) except email.MessageError: return None if (pkg_info.get('Name', None) != pack...
null
null
null
What does this function do?
def reduce_list(data_set): seen = set() return [item for item in data_set if ((item not in seen) and (not seen.add(item)))]
null
null
null
Reduce duplicate items in a list and preserve order
pcsd
def reduce list data set seen = set return [item for item in data set if item not in seen and not seen add item ]
10986
def reduce_list(data_set): seen = set() return [item for item in data_set if ((item not in seen) and (not seen.add(item)))]
Reduce duplicate items in a list and preserve order
reduce duplicate items in a list and preserve order
Question: What does this function do? Code: def reduce_list(data_set): seen = set() return [item for item in data_set if ((item not in seen) and (not seen.add(item)))]
null
null
null
What does this function do?
def _init_log(log_dir): desktop.log.basic_logging(PROC_NAME, log_dir) if (os.geteuid() == 0): desktop.log.chown_log_dir(g_user_uid, g_user_gid)
null
null
null
Initialize logging configuration
pcsd
def init log log dir desktop log basic logging PROC NAME log dir if os geteuid == 0 desktop log chown log dir g user uid g user gid
10997
def _init_log(log_dir): desktop.log.basic_logging(PROC_NAME, log_dir) if (os.geteuid() == 0): desktop.log.chown_log_dir(g_user_uid, g_user_gid)
Initialize logging configuration
initialize logging configuration
Question: What does this function do? Code: def _init_log(log_dir): desktop.log.basic_logging(PROC_NAME, log_dir) if (os.geteuid() == 0): desktop.log.chown_log_dir(g_user_uid, g_user_gid)
null
null
null
What does this function do?
def _get_status(status): if (status not in STATUS_CODES): raise ValueError('Unknown status code') return STATUS_CODES[status]
null
null
null
Get status code. @see: L{STATUS_CODES}
pcsd
def get status status if status not in STATUS CODES raise Value Error 'Unknown status code' return STATUS CODES[status]
11000
def _get_status(status): if (status not in STATUS_CODES): raise ValueError('Unknown status code') return STATUS_CODES[status]
Get status code. @see: L{STATUS_CODES}
get status code .
Question: What does this function do? Code: def _get_status(status): if (status not in STATUS_CODES): raise ValueError('Unknown status code') return STATUS_CODES[status]
null
null
null
What does this function do?
@receiver(pre_delete, sender=GoldUser) def delete_customer(sender, instance, **__): if ((sender == GoldUser) and (instance.stripe_id is not None)): utils.delete_customer(instance.stripe_id)
null
null
null
On Gold subscription deletion, remove the customer from Stripe
pcsd
@receiver pre delete sender=Gold User def delete customer sender instance ** if sender == Gold User and instance stripe id is not None utils delete customer instance stripe id
11001
@receiver(pre_delete, sender=GoldUser) def delete_customer(sender, instance, **__): if ((sender == GoldUser) and (instance.stripe_id is not None)): utils.delete_customer(instance.stripe_id)
On Gold subscription deletion, remove the customer from Stripe
on gold subscription deletion , remove the customer from stripe
Question: What does this function do? Code: @receiver(pre_delete, sender=GoldUser) def delete_customer(sender, instance, **__): if ((sender == GoldUser) and (instance.stripe_id is not None)): utils.delete_customer(instance.stripe_id)
null
null
null
What does this function do?
def match_str(filter_str, dct): return all((_match_one(filter_part, dct) for filter_part in filter_str.split(u'&')))
null
null
null
Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false
pcsd
def match str filter str dct return all match one filter part dct for filter part in filter str split u'&'
11005
def match_str(filter_str, dct): return all((_match_one(filter_part, dct) for filter_part in filter_str.split(u'&')))
Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false
filter a dictionary with a simple string syntax .
Question: What does this function do? Code: def match_str(filter_str, dct): return all((_match_one(filter_part, dct) for filter_part in filter_str.split(u'&')))
null
null
null
What does this function do?
def auto_through(field): return ((not field.rel.through) or getattr(getattr(field.rel.through, '_meta', None), 'auto_created', False))
null
null
null
Returns if the M2M class passed in has an autogenerated through table or not.
pcsd
def auto through field return not field rel through or getattr getattr field rel through ' meta' None 'auto created' False
11011
def auto_through(field): return ((not field.rel.through) or getattr(getattr(field.rel.through, '_meta', None), 'auto_created', False))
Returns if the M2M class passed in has an autogenerated through table or not.
returns if the m2m class passed in has an autogenerated through table or not .
Question: What does this function do? Code: def auto_through(field): return ((not field.rel.through) or getattr(getattr(field.rel.through, '_meta', None), 'auto_created', False))
null
null
null
What does this function do?
def st_mode_to_octal(mode): try: return oct(mode)[(-4):] except (TypeError, IndexError): return ''
null
null
null
Convert the st_mode value from a stat(2) call (as returned from os.stat()) to an octal mode.
pcsd
def st mode to octal mode try return oct mode [ -4 ] except Type Error Index Error return ''
11013
def st_mode_to_octal(mode): try: return oct(mode)[(-4):] except (TypeError, IndexError): return ''
Convert the st_mode value from a stat(2) call (as returned from os.stat()) to an octal mode.
convert the st _ mode value from a stat ( 2 ) call ( as returned from os . stat ( ) ) to an octal mode .
Question: What does this function do? Code: def st_mode_to_octal(mode): try: return oct(mode)[(-4):] except (TypeError, IndexError): return ''
null
null
null
What does this function do?
def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): data = json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': rpcmethod, 'params': [session_id, subsystem, method, params]}) try: res = requests.post(url, data=data, timeout=5) except requests.exceptions.Timeout: return if (res.status_code ==...
null
null
null
Perform one JSON RPC operation.
pcsd
def req json rpc url session id rpcmethod subsystem method **params data = json dumps {'jsonrpc' '2 0' 'id' 1 'method' rpcmethod 'params' [session id subsystem method params]} try res = requests post url data=data timeout=5 except requests exceptions Timeout return if res status code == 200 response = res json if rpcme...
11016
def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): data = json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': rpcmethod, 'params': [session_id, subsystem, method, params]}) try: res = requests.post(url, data=data, timeout=5) except requests.exceptions.Timeout: return if (res.status_code ==...
Perform one JSON RPC operation.
perform one json rpc operation .
Question: What does this function do? Code: def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): data = json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': rpcmethod, 'params': [session_id, subsystem, method, params]}) try: res = requests.post(url, data=data, timeout=5) except requests.excep...
null
null
null
What does this function do?
def event_elapsed_time(evtstart, evtend): msec = c_float() driver.cuEventElapsedTime(byref(msec), evtstart.handle, evtend.handle) return msec.value
null
null
null
Compute the elapsed time between two events in milliseconds.
pcsd
def event elapsed time evtstart evtend msec = c float driver cu Event Elapsed Time byref msec evtstart handle evtend handle return msec value
11019
def event_elapsed_time(evtstart, evtend): msec = c_float() driver.cuEventElapsedTime(byref(msec), evtstart.handle, evtend.handle) return msec.value
Compute the elapsed time between two events in milliseconds.
compute the elapsed time between two events in milliseconds .
Question: What does this function do? Code: def event_elapsed_time(evtstart, evtend): msec = c_float() driver.cuEventElapsedTime(byref(msec), evtstart.handle, evtend.handle) return msec.value
null
null
null
What does this function do?
def InstallModule(conf_module_name, params, options, log=(lambda *args: None)): if (not hasattr(sys, 'frozen')): conf_module_name = os.path.abspath(conf_module_name) if (not os.path.isfile(conf_module_name)): raise ConfigurationError(('%s does not exist' % (conf_module_name,))) loader_dll = GetLoaderModuleName...
null
null
null
Install the extension
pcsd
def Install Module conf module name params options log= lambda *args None if not hasattr sys 'frozen' conf module name = os path abspath conf module name if not os path isfile conf module name raise Configuration Error '%s does not exist' % conf module name loader dll = Get Loader Module Name conf module name Patch Par...
11031
def InstallModule(conf_module_name, params, options, log=(lambda *args: None)): if (not hasattr(sys, 'frozen')): conf_module_name = os.path.abspath(conf_module_name) if (not os.path.isfile(conf_module_name)): raise ConfigurationError(('%s does not exist' % (conf_module_name,))) loader_dll = GetLoaderModuleName...
Install the extension
install the extension
Question: What does this function do? Code: def InstallModule(conf_module_name, params, options, log=(lambda *args: None)): if (not hasattr(sys, 'frozen')): conf_module_name = os.path.abspath(conf_module_name) if (not os.path.isfile(conf_module_name)): raise ConfigurationError(('%s does not exist' % (conf_mo...
null
null
null
What does this function do?
def get_script_header(script_text, executable=sys_executable, wininst=False): from distutils.command.build_scripts import first_line_re if (not isinstance(first_line_re.pattern, str)): first_line_re = re.compile(first_line_re.pattern.decode()) first = (script_text + '\n').splitlines()[0] match = first_line_re.mat...
null
null
null
Create a #! line, getting options (if any) from script_text
pcsd
def get script header script text executable=sys executable wininst=False from distutils command build scripts import first line re if not isinstance first line re pattern str first line re = re compile first line re pattern decode first = script text + ' ' splitlines [0] match = first line re match first options = '' ...
11032
def get_script_header(script_text, executable=sys_executable, wininst=False): from distutils.command.build_scripts import first_line_re if (not isinstance(first_line_re.pattern, str)): first_line_re = re.compile(first_line_re.pattern.decode()) first = (script_text + '\n').splitlines()[0] match = first_line_re.mat...
Create a #! line, getting options (if any) from script_text
create a # ! line , getting options from script _ text
Question: What does this function do? Code: def get_script_header(script_text, executable=sys_executable, wininst=False): from distutils.command.build_scripts import first_line_re if (not isinstance(first_line_re.pattern, str)): first_line_re = re.compile(first_line_re.pattern.decode()) first = (script_text + '...
null
null
null
What does this function do?
def get_user_model(): if hasattr(django.contrib.auth, 'get_user_model'): return django.contrib.auth.get_user_model() else: return django.contrib.auth.models.User
null
null
null
For Django < 1.5 backward compatibility
pcsd
def get user model if hasattr django contrib auth 'get user model' return django contrib auth get user model else return django contrib auth models User
11034
def get_user_model(): if hasattr(django.contrib.auth, 'get_user_model'): return django.contrib.auth.get_user_model() else: return django.contrib.auth.models.User
For Django < 1.5 backward compatibility
for django < 1 . 5 backward compatibility
Question: What does this function do? Code: def get_user_model(): if hasattr(django.contrib.auth, 'get_user_model'): return django.contrib.auth.get_user_model() else: return django.contrib.auth.models.User
null
null
null
What does this function do?
def default_stream_factory(total_content_length, filename, content_type, content_length=None): if (total_content_length > (1024 * 500)): return TemporaryFile('wb+') return BytesIO()
null
null
null
The stream factory that is used per default.
pcsd
def default stream factory total content length filename content type content length=None if total content length > 1024 * 500 return Temporary File 'wb+' return Bytes IO
11050
def default_stream_factory(total_content_length, filename, content_type, content_length=None): if (total_content_length > (1024 * 500)): return TemporaryFile('wb+') return BytesIO()
The stream factory that is used per default.
the stream factory that is used per default .
Question: What does this function do? Code: def default_stream_factory(total_content_length, filename, content_type, content_length=None): if (total_content_length > (1024 * 500)): return TemporaryFile('wb+') return BytesIO()
null
null
null
What does this function do?
def config_from_file(filename, config=None): if config: try: with open(filename, 'w') as fdesc: fdesc.write(json.dumps(config)) except IOError as error: _LOGGER.error('Saving config file failed: %s', error) return False return True elif os.path.isfile(filename): try: with open(filename, 'r') a...
null
null
null
Small configuration file management function.
pcsd
def config from file filename config=None if config try with open filename 'w' as fdesc fdesc write json dumps config except IO Error as error LOGGER error 'Saving config file failed %s' error return False return True elif os path isfile filename try with open filename 'r' as fdesc return json loads fdesc read except I...
11056
def config_from_file(filename, config=None): if config: try: with open(filename, 'w') as fdesc: fdesc.write(json.dumps(config)) except IOError as error: _LOGGER.error('Saving config file failed: %s', error) return False return True elif os.path.isfile(filename): try: with open(filename, 'r') a...
Small configuration file management function.
small configuration file management function .
Question: What does this function do? Code: def config_from_file(filename, config=None): if config: try: with open(filename, 'w') as fdesc: fdesc.write(json.dumps(config)) except IOError as error: _LOGGER.error('Saving config file failed: %s', error) return False return True elif os.path.isfile(...
null
null
null
What does this function do?
def print_col(text, color): if use_color: fg = _esc(fg_colors[color.lower()]) reset = _esc(fg_colors['reset']) print ''.join([fg, text, reset]) else: print text
null
null
null
Print a colorized text.
pcsd
def print col text color if use color fg = esc fg colors[color lower ] reset = esc fg colors['reset'] print '' join [fg text reset] else print text
11057
def print_col(text, color): if use_color: fg = _esc(fg_colors[color.lower()]) reset = _esc(fg_colors['reset']) print ''.join([fg, text, reset]) else: print text
Print a colorized text.
print a colorized text .
Question: What does this function do? Code: def print_col(text, color): if use_color: fg = _esc(fg_colors[color.lower()]) reset = _esc(fg_colors['reset']) print ''.join([fg, text, reset]) else: print text
null
null
null
What does this function do?
def code_analysis(app_dir, md5, perms, typ): try: print '[INFO] Static Android Code Analysis Started' code = {key: [] for key in ('inf_act', 'inf_ser', 'inf_bro', 'log', 'fileio', 'rand', 'd_hcode', 'd_app_tamper', 'dex_cert', 'dex_tamper', 'd_rootcheck', 'd_root', 'd_ssl_pin', 'dex_root', 'dex_debug_key', 'dex_de...
null
null
null
Perform the code analysis.
pcsd
def code analysis app dir md5 perms typ try print '[INFO] Static Android Code Analysis Started' code = {key [] for key in 'inf act' 'inf ser' 'inf bro' 'log' 'fileio' 'rand' 'd hcode' 'd app tamper' 'dex cert' 'dex tamper' 'd rootcheck' 'd root' 'd ssl pin' 'dex root' 'dex debug key' 'dex debug' 'dex debug con' 'dex em...
11062
def code_analysis(app_dir, md5, perms, typ): try: print '[INFO] Static Android Code Analysis Started' code = {key: [] for key in ('inf_act', 'inf_ser', 'inf_bro', 'log', 'fileio', 'rand', 'd_hcode', 'd_app_tamper', 'dex_cert', 'dex_tamper', 'd_rootcheck', 'd_root', 'd_ssl_pin', 'dex_root', 'dex_debug_key', 'dex_de...
Perform the code analysis.
perform the code analysis .
Question: What does this function do? Code: def code_analysis(app_dir, md5, perms, typ): try: print '[INFO] Static Android Code Analysis Started' code = {key: [] for key in ('inf_act', 'inf_ser', 'inf_bro', 'log', 'fileio', 'rand', 'd_hcode', 'd_app_tamper', 'dex_cert', 'dex_tamper', 'd_rootcheck', 'd_root', 'd...
null
null
null
What does this function do?
def _make_subtarget(targetctx, flags): subtargetoptions = {} if flags.boundcheck: subtargetoptions['enable_boundcheck'] = True if flags.nrt: subtargetoptions['enable_nrt'] = True error_model = callconv.create_error_model(flags.error_model, targetctx) subtargetoptions['error_model'] = error_model return target...
null
null
null
Make a new target context from the given target context and flags.
pcsd
def make subtarget targetctx flags subtargetoptions = {} if flags boundcheck subtargetoptions['enable boundcheck'] = True if flags nrt subtargetoptions['enable nrt'] = True error model = callconv create error model flags error model targetctx subtargetoptions['error model'] = error model return targetctx subtarget **su...
11064
def _make_subtarget(targetctx, flags): subtargetoptions = {} if flags.boundcheck: subtargetoptions['enable_boundcheck'] = True if flags.nrt: subtargetoptions['enable_nrt'] = True error_model = callconv.create_error_model(flags.error_model, targetctx) subtargetoptions['error_model'] = error_model return target...
Make a new target context from the given target context and flags.
make a new target context from the given target context and flags .
Question: What does this function do? Code: def _make_subtarget(targetctx, flags): subtargetoptions = {} if flags.boundcheck: subtargetoptions['enable_boundcheck'] = True if flags.nrt: subtargetoptions['enable_nrt'] = True error_model = callconv.create_error_model(flags.error_model, targetctx) subtargetopti...
null
null
null
What does this function do?
def _restore_service(service): _apply_service(service, SonosDevice.restore)
null
null
null
Restore a snapshot.
pcsd
def restore service service apply service service Sonos Device restore
11065
def _restore_service(service): _apply_service(service, SonosDevice.restore)
Restore a snapshot.
restore a snapshot .
Question: What does this function do? Code: def _restore_service(service): _apply_service(service, SonosDevice.restore)
null
null
null
What does this function do?
def setEpisodeToWanted(show, s, e): epObj = show.getEpisode(s, e) if epObj: with epObj.lock: if ((epObj.status != SKIPPED) or (epObj.airdate == datetime.date.fromordinal(1))): return logger.log(u'Setting episode {show} {ep} to wanted'.format(show=show.name, ep=episode_num(s, e))) epObj.status = WANTED ...
null
null
null
Sets an episode to wanted, only if it is currently skipped
pcsd
def set Episode To Wanted show s e ep Obj = show get Episode s e if ep Obj with ep Obj lock if ep Obj status != SKIPPED or ep Obj airdate == datetime date fromordinal 1 return logger log u'Setting episode {show} {ep} to wanted' format show=show name ep=episode num s e ep Obj status = WANTED ep Obj save To DB cur backlo...
11071
def setEpisodeToWanted(show, s, e): epObj = show.getEpisode(s, e) if epObj: with epObj.lock: if ((epObj.status != SKIPPED) or (epObj.airdate == datetime.date.fromordinal(1))): return logger.log(u'Setting episode {show} {ep} to wanted'.format(show=show.name, ep=episode_num(s, e))) epObj.status = WANTED ...
Sets an episode to wanted, only if it is currently skipped
sets an episode to wanted , only if it is currently skipped
Question: What does this function do? Code: def setEpisodeToWanted(show, s, e): epObj = show.getEpisode(s, e) if epObj: with epObj.lock: if ((epObj.status != SKIPPED) or (epObj.airdate == datetime.date.fromordinal(1))): return logger.log(u'Setting episode {show} {ep} to wanted'.format(show=show.name, e...
null
null
null
What does this function do?
def empty_cell(empty=True): def f(): print a if (not empty): a = 1729 return f.__closure__[0]
null
null
null
Create an empty cell.
pcsd
def empty cell empty=True def f print a if not empty a = 1729 return f closure [0]
11079
def empty_cell(empty=True): def f(): print a if (not empty): a = 1729 return f.__closure__[0]
Create an empty cell.
create an empty cell .
Question: What does this function do? Code: def empty_cell(empty=True): def f(): print a if (not empty): a = 1729 return f.__closure__[0]
null
null
null
What does this function do?
def _read_segments_file(raw, data, idx, fi, start, stop, cals, mult, dtype='<i2', n_channels=None, offset=0, trigger_ch=None): if (n_channels is None): n_channels = raw.info['nchan'] n_bytes = np.dtype(dtype).itemsize data_offset = (((n_channels * start) * n_bytes) + offset) data_left = ((stop - start) * n_channe...
null
null
null
Read a chunk of raw data.
pcsd
def read segments file raw data idx fi start stop cals mult dtype='<i2' n channels=None offset=0 trigger ch=None if n channels is None n channels = raw info['nchan'] n bytes = np dtype dtype itemsize data offset = n channels * start * n bytes + offset data left = stop - start * n channels block size = int 100000000 0 /...
11085
def _read_segments_file(raw, data, idx, fi, start, stop, cals, mult, dtype='<i2', n_channels=None, offset=0, trigger_ch=None): if (n_channels is None): n_channels = raw.info['nchan'] n_bytes = np.dtype(dtype).itemsize data_offset = (((n_channels * start) * n_bytes) + offset) data_left = ((stop - start) * n_channe...
Read a chunk of raw data.
read a chunk of raw data .
Question: What does this function do? Code: def _read_segments_file(raw, data, idx, fi, start, stop, cals, mult, dtype='<i2', n_channels=None, offset=0, trigger_ch=None): if (n_channels is None): n_channels = raw.info['nchan'] n_bytes = np.dtype(dtype).itemsize data_offset = (((n_channels * start) * n_bytes) + ...
null
null
null
What does this function do?
def dev_required(owner_for_post=False, allow_editors=False, theme=False, submitting=False): def decorator(f): @addon_view_factory(qs=Addon.objects.all) @login_required @functools.wraps(f) def wrapper(request, addon, *args, **kw): if theme: kw['theme'] = addon.is_persona() elif addon.is_persona(): ...
null
null
null
Requires user to be add-on owner or admin. When allow_editors is True, an editor can view the page.
pcsd
def dev required owner for post=False allow editors=False theme=False submitting=False def decorator f @addon view factory qs=Addon objects all @login required @functools wraps f def wrapper request addon *args **kw if theme kw['theme'] = addon is persona elif addon is persona raise http Http404 def fun return f reques...
11089
def dev_required(owner_for_post=False, allow_editors=False, theme=False, submitting=False): def decorator(f): @addon_view_factory(qs=Addon.objects.all) @login_required @functools.wraps(f) def wrapper(request, addon, *args, **kw): if theme: kw['theme'] = addon.is_persona() elif addon.is_persona(): ...
Requires user to be add-on owner or admin. When allow_editors is True, an editor can view the page.
requires user to be add - on owner or admin .
Question: What does this function do? Code: def dev_required(owner_for_post=False, allow_editors=False, theme=False, submitting=False): def decorator(f): @addon_view_factory(qs=Addon.objects.all) @login_required @functools.wraps(f) def wrapper(request, addon, *args, **kw): if theme: kw['theme'] = add...
null
null
null
What does this function do?
def install_atlas(): chdir(SRC_DIR) apt_command('build-dep atlas') if glob.glob('*atlas*.deb'): run_command('dpkg -i *atlas*.deb') return apt_command('source atlas') chdir('atlas-*') run_command('fakeroot debian/rules custom') run_command('dpkg -i ../*atlas*.deb')
null
null
null
docstring for install_atlas
pcsd
def install atlas chdir SRC DIR apt command 'build-dep atlas' if glob glob '*atlas* deb' run command 'dpkg -i *atlas* deb' return apt command 'source atlas' chdir 'atlas-*' run command 'fakeroot debian/rules custom' run command 'dpkg -i /*atlas* deb'
11091
def install_atlas(): chdir(SRC_DIR) apt_command('build-dep atlas') if glob.glob('*atlas*.deb'): run_command('dpkg -i *atlas*.deb') return apt_command('source atlas') chdir('atlas-*') run_command('fakeroot debian/rules custom') run_command('dpkg -i ../*atlas*.deb')
docstring for install_atlas
docstring for install _ atlas
Question: What does this function do? Code: def install_atlas(): chdir(SRC_DIR) apt_command('build-dep atlas') if glob.glob('*atlas*.deb'): run_command('dpkg -i *atlas*.deb') return apt_command('source atlas') chdir('atlas-*') run_command('fakeroot debian/rules custom') run_command('dpkg -i ../*atlas*.deb...
null
null
null
What does this function do?
def encrypt(journal, filename=None): password = util.getpass(u'Enter new password: ') journal.make_key(password) journal.config[u'encrypt'] = True journal.write(filename) if util.yesno(u'Do you want to store the password in your keychain?', default=True): util.set_keychain(journal.name, password) util.prompt(u'...
null
null
null
Encrypt into new file. If filename is not set, we encrypt the journal file itself.
pcsd
def encrypt journal filename=None password = util getpass u'Enter new password ' journal make key password journal config[u'encrypt'] = True journal write filename if util yesno u'Do you want to store the password in your keychain?' default=True util set keychain journal name password util prompt u'Journal encrypted to...
11104
def encrypt(journal, filename=None): password = util.getpass(u'Enter new password: ') journal.make_key(password) journal.config[u'encrypt'] = True journal.write(filename) if util.yesno(u'Do you want to store the password in your keychain?', default=True): util.set_keychain(journal.name, password) util.prompt(u'...
Encrypt into new file. If filename is not set, we encrypt the journal file itself.
encrypt into new file .
Question: What does this function do? Code: def encrypt(journal, filename=None): password = util.getpass(u'Enter new password: ') journal.make_key(password) journal.config[u'encrypt'] = True journal.write(filename) if util.yesno(u'Do you want to store the password in your keychain?', default=True): util.set_k...
null
null
null
What does this function do?
def send_message(client, message): print message client.send('HTTP/1.1 200 OK\r\n\r\n{}'.format(message).encode('utf-8')) client.close()
null
null
null
Send message to client and close the connection.
pcsd
def send message client message print message client send 'HTTP/1 1 200 OK\r \r {}' format message encode 'utf-8' client close
11115
def send_message(client, message): print message client.send('HTTP/1.1 200 OK\r\n\r\n{}'.format(message).encode('utf-8')) client.close()
Send message to client and close the connection.
send message to client and close the connection .
Question: What does this function do? Code: def send_message(client, message): print message client.send('HTTP/1.1 200 OK\r\n\r\n{}'.format(message).encode('utf-8')) client.close()
null
null
null
What does this function do?
def org_customise_org_resource_fields(method): s3db = current.s3db table = s3db.org_resource table.location_id.represent = s3db.gis_LocationRepresent(sep=' | ') list_fields = ['organisation_id', 'location_id', 'parameter_id', 'value', 'comments'] if (method in ('datalist', 'profile')): table.modified_by.represen...
null
null
null
Customize org_resource fields for Profile widgets and \'more\' popups
pcsd
def org customise org resource fields method s3db = current s3db table = s3db org resource table location id represent = s3db gis Location Represent sep=' | ' list fields = ['organisation id' 'location id' 'parameter id' 'value' 'comments'] if method in 'datalist' 'profile' table modified by represent = s3 auth user re...
11119
def org_customise_org_resource_fields(method): s3db = current.s3db table = s3db.org_resource table.location_id.represent = s3db.gis_LocationRepresent(sep=' | ') list_fields = ['organisation_id', 'location_id', 'parameter_id', 'value', 'comments'] if (method in ('datalist', 'profile')): table.modified_by.represen...
Customize org_resource fields for Profile widgets and \'more\' popups
customize org _ resource fields for profile widgets and more popups
Question: What does this function do? Code: def org_customise_org_resource_fields(method): s3db = current.s3db table = s3db.org_resource table.location_id.represent = s3db.gis_LocationRepresent(sep=' | ') list_fields = ['organisation_id', 'location_id', 'parameter_id', 'value', 'comments'] if (method in ('datal...
null
null
null
What does this function do?
def init_mappings(mappings): for (sectname, section) in mappings.items(): for (optname, mapping) in section.items(): default = mapping.save_default() log.config.vdebug('Saved default for {} -> {}: {!r}'.format(sectname, optname, default)) value = config.get(sectname, optname) log.config.vdebug('Setting {...
null
null
null
Initialize all settings based on a settings mapping.
pcsd
def init mappings mappings for sectname section in mappings items for optname mapping in section items default = mapping save default log config vdebug 'Saved default for {} -> {} {!r}' format sectname optname default value = config get sectname optname log config vdebug 'Setting {} -> {} to {!r}' format sectname optna...
11124
def init_mappings(mappings): for (sectname, section) in mappings.items(): for (optname, mapping) in section.items(): default = mapping.save_default() log.config.vdebug('Saved default for {} -> {}: {!r}'.format(sectname, optname, default)) value = config.get(sectname, optname) log.config.vdebug('Setting {...
Initialize all settings based on a settings mapping.
initialize all settings based on a settings mapping .
Question: What does this function do? Code: def init_mappings(mappings): for (sectname, section) in mappings.items(): for (optname, mapping) in section.items(): default = mapping.save_default() log.config.vdebug('Saved default for {} -> {}: {!r}'.format(sectname, optname, default)) value = config.get(sec...
null
null
null
What does this function do?
def see_other(location): to(location, falcon.HTTP_303)
null
null
null
Redirects to the specified location using HTTP 303 status code
pcsd
def see other location to location falcon HTTP 303
11125
def see_other(location): to(location, falcon.HTTP_303)
Redirects to the specified location using HTTP 303 status code
redirects to the specified location using http 303 status code
Question: What does this function do? Code: def see_other(location): to(location, falcon.HTTP_303)
null
null
null
What does this function do?
def extract_parameters_for_action_alias_db(action_alias_db, format_str, param_stream): formats = [] formats = action_alias_db.get_format_strings() if (format_str not in formats): raise ValueError(('Format string "%s" is not available on the alias "%s"' % (format_str, action_alias_db.name))) result = extract_param...
null
null
null
Extract parameters from the user input based on the provided format string. Note: This function makes sure that the provided format string is indeed available in the action_alias_db.formats.
pcsd
def extract parameters for action alias db action alias db format str param stream formats = [] formats = action alias db get format strings if format str not in formats raise Value Error 'Format string "%s" is not available on the alias "%s"' % format str action alias db name result = extract parameters format str=for...
11139
def extract_parameters_for_action_alias_db(action_alias_db, format_str, param_stream): formats = [] formats = action_alias_db.get_format_strings() if (format_str not in formats): raise ValueError(('Format string "%s" is not available on the alias "%s"' % (format_str, action_alias_db.name))) result = extract_param...
Extract parameters from the user input based on the provided format string. Note: This function makes sure that the provided format string is indeed available in the action_alias_db.formats.
extract parameters from the user input based on the provided format string .
Question: What does this function do? Code: def extract_parameters_for_action_alias_db(action_alias_db, format_str, param_stream): formats = [] formats = action_alias_db.get_format_strings() if (format_str not in formats): raise ValueError(('Format string "%s" is not available on the alias "%s"' % (format_str, ...
null
null
null
What does this function do?
def _minpoly_exp(ex, x): (c, a) = ex.args[0].as_coeff_Mul() p = sympify(c.p) q = sympify(c.q) if (a == (I * pi)): if c.is_rational: if ((c.p == 1) or (c.p == (-1))): if (q == 3): return (((x ** 2) - x) + 1) if (q == 4): return ((x ** 4) + 1) if (q == 6): return (((x ** 4) - (x ** 2))...
null
null
null
Returns the minimal polynomial of ``exp(ex)``
pcsd
def minpoly exp ex x c a = ex args[0] as coeff Mul p = sympify c p q = sympify c q if a == I * pi if c is rational if c p == 1 or c p == -1 if q == 3 return x ** 2 - x + 1 if q == 4 return x ** 4 + 1 if q == 6 return x ** 4 - x ** 2 + 1 if q == 8 return x ** 8 + 1 if q == 9 return x ** 6 - x ** 3 + 1 if q == 10 return ...
11149
def _minpoly_exp(ex, x): (c, a) = ex.args[0].as_coeff_Mul() p = sympify(c.p) q = sympify(c.q) if (a == (I * pi)): if c.is_rational: if ((c.p == 1) or (c.p == (-1))): if (q == 3): return (((x ** 2) - x) + 1) if (q == 4): return ((x ** 4) + 1) if (q == 6): return (((x ** 4) - (x ** 2))...
Returns the minimal polynomial of ``exp(ex)``
returns the minimal polynomial of exp
Question: What does this function do? Code: def _minpoly_exp(ex, x): (c, a) = ex.args[0].as_coeff_Mul() p = sympify(c.p) q = sympify(c.q) if (a == (I * pi)): if c.is_rational: if ((c.p == 1) or (c.p == (-1))): if (q == 3): return (((x ** 2) - x) + 1) if (q == 4): return ((x ** 4) + 1) ...
null
null
null
What does this function do?
@as_op(itypes=[tt.lscalar, tt.dscalar, tt.dscalar], otypes=[tt.dvector]) def rateFunc(switchpoint, early_mean, late_mean): out = empty(years) out[:switchpoint] = early_mean out[switchpoint:] = late_mean return out
null
null
null
Concatenate Poisson means
pcsd
@as op itypes=[tt lscalar tt dscalar tt dscalar] otypes=[tt dvector] def rate Func switchpoint early mean late mean out = empty years out[ switchpoint] = early mean out[switchpoint ] = late mean return out
11160
@as_op(itypes=[tt.lscalar, tt.dscalar, tt.dscalar], otypes=[tt.dvector]) def rateFunc(switchpoint, early_mean, late_mean): out = empty(years) out[:switchpoint] = early_mean out[switchpoint:] = late_mean return out
Concatenate Poisson means
concatenate poisson means
Question: What does this function do? Code: @as_op(itypes=[tt.lscalar, tt.dscalar, tt.dscalar], otypes=[tt.dvector]) def rateFunc(switchpoint, early_mean, late_mean): out = empty(years) out[:switchpoint] = early_mean out[switchpoint:] = late_mean return out
null
null
null
What does this function do?
def person(): table = s3db.pr_person s3.crud_strings['pr_person'].update(title_display=T('Missing Person Details'), title_list=T('Missing Persons'), label_list_button=T('List Missing Persons'), msg_list_empty=T('No Persons found'), msg_no_match=T('No Persons currently reported missing')) s3db.configure('pr_group_mem...
null
null
null
Missing Persons Registry (Match Finder)
pcsd
def person table = s3db pr person s3 crud strings['pr person'] update title display=T 'Missing Person Details' title list=T 'Missing Persons' label list button=T 'List Missing Persons' msg list empty=T 'No Persons found' msg no match=T 'No Persons currently reported missing' s3db configure 'pr group membership' list fi...
11163
def person(): table = s3db.pr_person s3.crud_strings['pr_person'].update(title_display=T('Missing Person Details'), title_list=T('Missing Persons'), label_list_button=T('List Missing Persons'), msg_list_empty=T('No Persons found'), msg_no_match=T('No Persons currently reported missing')) s3db.configure('pr_group_mem...
Missing Persons Registry (Match Finder)
missing persons registry
Question: What does this function do? Code: def person(): table = s3db.pr_person s3.crud_strings['pr_person'].update(title_display=T('Missing Person Details'), title_list=T('Missing Persons'), label_list_button=T('List Missing Persons'), msg_list_empty=T('No Persons found'), msg_no_match=T('No Persons currently re...
null
null
null
What does this function do?
def getTokenEnd(characterIndex, fileText, token): tokenIndex = fileText.find(token, characterIndex) if (tokenIndex == (-1)): return (-1) return (tokenIndex + len(token))
null
null
null
Get the token end index for the file text and token.
pcsd
def get Token End character Index file Text token token Index = file Text find token character Index if token Index == -1 return -1 return token Index + len token
11167
def getTokenEnd(characterIndex, fileText, token): tokenIndex = fileText.find(token, characterIndex) if (tokenIndex == (-1)): return (-1) return (tokenIndex + len(token))
Get the token end index for the file text and token.
get the token end index for the file text and token .
Question: What does this function do? Code: def getTokenEnd(characterIndex, fileText, token): tokenIndex = fileText.find(token, characterIndex) if (tokenIndex == (-1)): return (-1) return (tokenIndex + len(token))
null
null
null
What does this function do?
def _atanh(p, x, prec): R = p.ring one = R(1) c = [one] p2 = rs_square(p, x, prec) for k in range(1, prec): c.append((one / ((2 * k) + 1))) s = rs_series_from_list(p2, c, x, prec) s = rs_mul(s, p, x, prec) return s
null
null
null
Expansion using formula Faster for very small and univariate series
pcsd
def atanh p x prec R = p ring one = R 1 c = [one] p2 = rs square p x prec for k in range 1 prec c append one / 2 * k + 1 s = rs series from list p2 c x prec s = rs mul s p x prec return s
11177
def _atanh(p, x, prec): R = p.ring one = R(1) c = [one] p2 = rs_square(p, x, prec) for k in range(1, prec): c.append((one / ((2 * k) + 1))) s = rs_series_from_list(p2, c, x, prec) s = rs_mul(s, p, x, prec) return s
Expansion using formula Faster for very small and univariate series
expansion using formula
Question: What does this function do? Code: def _atanh(p, x, prec): R = p.ring one = R(1) c = [one] p2 = rs_square(p, x, prec) for k in range(1, prec): c.append((one / ((2 * k) + 1))) s = rs_series_from_list(p2, c, x, prec) s = rs_mul(s, p, x, prec) return s
null
null
null
What does this function do?
@cache_page((60 * 15)) def suggestions(request): content_type = 'application/x-suggestions+json' term = request.GET.get('q') if (not term): return HttpResponseBadRequest(content_type=content_type) results = [] return HttpResponse(json.dumps(results), content_type=content_type)
null
null
null
Return empty array until we restore internal search system.
pcsd
@cache page 60 * 15 def suggestions request content type = 'application/x-suggestions+json' term = request GET get 'q' if not term return Http Response Bad Request content type=content type results = [] return Http Response json dumps results content type=content type
11188
@cache_page((60 * 15)) def suggestions(request): content_type = 'application/x-suggestions+json' term = request.GET.get('q') if (not term): return HttpResponseBadRequest(content_type=content_type) results = [] return HttpResponse(json.dumps(results), content_type=content_type)
Return empty array until we restore internal search system.
return empty array until we restore internal search system .
Question: What does this function do? Code: @cache_page((60 * 15)) def suggestions(request): content_type = 'application/x-suggestions+json' term = request.GET.get('q') if (not term): return HttpResponseBadRequest(content_type=content_type) results = [] return HttpResponse(json.dumps(results), content_type=co...
null
null
null
What does this function do?
def _collect_delete_commands(base_mapper, uowtransaction, table, states_to_delete): delete = util.defaultdict(list) for (state, state_dict, mapper, has_identity, connection) in states_to_delete: if ((not has_identity) or (table not in mapper._pks_by_table)): continue params = {} delete[connection].append(par...
null
null
null
Identify values to use in DELETE statements for a list of states to be deleted.
pcsd
def collect delete commands base mapper uowtransaction table states to delete delete = util defaultdict list for state state dict mapper has identity connection in states to delete if not has identity or table not in mapper pks by table continue params = {} delete[connection] append params for col in mapper pks by tabl...
11191
def _collect_delete_commands(base_mapper, uowtransaction, table, states_to_delete): delete = util.defaultdict(list) for (state, state_dict, mapper, has_identity, connection) in states_to_delete: if ((not has_identity) or (table not in mapper._pks_by_table)): continue params = {} delete[connection].append(par...
Identify values to use in DELETE statements for a list of states to be deleted.
identify values to use in delete statements for a list of states to be deleted .
Question: What does this function do? Code: def _collect_delete_commands(base_mapper, uowtransaction, table, states_to_delete): delete = util.defaultdict(list) for (state, state_dict, mapper, has_identity, connection) in states_to_delete: if ((not has_identity) or (table not in mapper._pks_by_table)): continu...
null
null
null
What does this function do?
def activateAaPdpContextReject(ProtocolConfigurationOptions_presence=0): a = TpPd(pd=8) b = MessageType(mesType=82) c = SmCause() packet = ((a / b) / c) if (ProtocolConfigurationOptions_presence is 1): d = ProtocolConfigurationOptions(ieiPCO=39) packet = (packet / d) return packet
null
null
null
ACTIVATE AA PDP CONTEXT REJECT Section 9.5.12
pcsd
def activate Aa Pdp Context Reject Protocol Configuration Options presence=0 a = Tp Pd pd=8 b = Message Type mes Type=82 c = Sm Cause packet = a / b / c if Protocol Configuration Options presence is 1 d = Protocol Configuration Options iei PCO=39 packet = packet / d return packet
11192
def activateAaPdpContextReject(ProtocolConfigurationOptions_presence=0): a = TpPd(pd=8) b = MessageType(mesType=82) c = SmCause() packet = ((a / b) / c) if (ProtocolConfigurationOptions_presence is 1): d = ProtocolConfigurationOptions(ieiPCO=39) packet = (packet / d) return packet
ACTIVATE AA PDP CONTEXT REJECT Section 9.5.12
activate aa pdp context reject section 9 . 5 . 12
Question: What does this function do? Code: def activateAaPdpContextReject(ProtocolConfigurationOptions_presence=0): a = TpPd(pd=8) b = MessageType(mesType=82) c = SmCause() packet = ((a / b) / c) if (ProtocolConfigurationOptions_presence is 1): d = ProtocolConfigurationOptions(ieiPCO=39) packet = (packet /...
null
null
null
What does this function do?
def image_to_display(path, start=None, length=None): (rows, columns) = os.popen('stty size', 'r').read().split() if (not start): start = IMAGE_SHIFT if (not length): length = (int(columns) - (2 * start)) i = Image.open(path) i = i.convert('RGBA') (w, h) = i.size i.load() width = min(w, length) height = int...
null
null
null
Display an image
pcsd
def image to display path start=None length=None rows columns = os popen 'stty size' 'r' read split if not start start = IMAGE SHIFT if not length length = int columns - 2 * start i = Image open path i = i convert 'RGBA' w h = i size i load width = min w length height = int float h * float width / float w height //= 2 ...
11198
def image_to_display(path, start=None, length=None): (rows, columns) = os.popen('stty size', 'r').read().split() if (not start): start = IMAGE_SHIFT if (not length): length = (int(columns) - (2 * start)) i = Image.open(path) i = i.convert('RGBA') (w, h) = i.size i.load() width = min(w, length) height = int...
Display an image
display an image
Question: What does this function do? Code: def image_to_display(path, start=None, length=None): (rows, columns) = os.popen('stty size', 'r').read().split() if (not start): start = IMAGE_SHIFT if (not length): length = (int(columns) - (2 * start)) i = Image.open(path) i = i.convert('RGBA') (w, h) = i.size ...
null
null
null
What does this function do?
def save_file_dialog(default_format='png'): filename = QtGui.QFileDialog.getSaveFileName() filename = _format_filename(filename) if (filename is None): return None (basename, ext) = os.path.splitext(filename) if (not ext): filename = ('%s.%s' % (filename, default_format)) return filename
null
null
null
Return user-selected file path.
pcsd
def save file dialog default format='png' filename = Qt Gui Q File Dialog get Save File Name filename = format filename filename if filename is None return None basename ext = os path splitext filename if not ext filename = '%s %s' % filename default format return filename
11201
def save_file_dialog(default_format='png'): filename = QtGui.QFileDialog.getSaveFileName() filename = _format_filename(filename) if (filename is None): return None (basename, ext) = os.path.splitext(filename) if (not ext): filename = ('%s.%s' % (filename, default_format)) return filename
Return user-selected file path.
return user - selected file path .
Question: What does this function do? Code: def save_file_dialog(default_format='png'): filename = QtGui.QFileDialog.getSaveFileName() filename = _format_filename(filename) if (filename is None): return None (basename, ext) = os.path.splitext(filename) if (not ext): filename = ('%s.%s' % (filename, default_...
null
null
null
What does this function do?
def create(vm_): try: if (vm_['profile'] and (config.is_profile_configured(__opts__, (__active_provider_name__ or 'rackspace'), vm_['profile'], vm_=vm_) is False)): return False except AttributeError: pass __utils__['cloud.fire_event']('event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']),...
null
null
null
Create a single VM from a data dict
pcsd
def create vm try if vm ['profile'] and config is profile configured opts active provider name or 'rackspace' vm ['profile'] vm =vm is False return False except Attribute Error pass utils ['cloud fire event'] 'event' 'starting create' 'salt/cloud/{0}/creating' format vm ['name'] args={'name' vm ['name'] 'profile' vm ['...
11211
def create(vm_): try: if (vm_['profile'] and (config.is_profile_configured(__opts__, (__active_provider_name__ or 'rackspace'), vm_['profile'], vm_=vm_) is False)): return False except AttributeError: pass __utils__['cloud.fire_event']('event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']),...
Create a single VM from a data dict
create a single vm from a data dict
Question: What does this function do? Code: def create(vm_): try: if (vm_['profile'] and (config.is_profile_configured(__opts__, (__active_provider_name__ or 'rackspace'), vm_['profile'], vm_=vm_) is False)): return False except AttributeError: pass __utils__['cloud.fire_event']('event', 'starting create',...
null
null
null
What does this function do?
def salt(): letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.' return '$6${0}'.format(''.join([random.choice(letters) for i in range(16)]))
null
null
null
Returns a string of 2 random letters. Taken from Eli Carter\'s htpasswd.py
pcsd
def salt letters = 'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/ ' return '$6${0}' format '' join [random choice letters for i in range 16 ]
11214
def salt(): letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.' return '$6${0}'.format(''.join([random.choice(letters) for i in range(16)]))
Returns a string of 2 random letters. Taken from Eli Carter\'s htpasswd.py
returns a string of 2 random letters .
Question: What does this function do? Code: def salt(): letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.' return '$6${0}'.format(''.join([random.choice(letters) for i in range(16)]))
null
null
null
What does this function do?
def enable_nat(interface): run(settings.iptables, '-t', 'nat', '-A', 'POSTROUTING', '-o', interface, '-j', 'MASQUERADE')
null
null
null
Enable NAT on this interface.
pcsd
def enable nat interface run settings iptables '-t' 'nat' '-A' 'POSTROUTING' '-o' interface '-j' 'MASQUERADE'
11222
def enable_nat(interface): run(settings.iptables, '-t', 'nat', '-A', 'POSTROUTING', '-o', interface, '-j', 'MASQUERADE')
Enable NAT on this interface.
enable nat on this interface .
Question: What does this function do? Code: def enable_nat(interface): run(settings.iptables, '-t', 'nat', '-A', 'POSTROUTING', '-o', interface, '-j', 'MASQUERADE')
null
null
null
What does this function do?
def MessageSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) local_VarintSize = _VarintSize assert (not is_packed) if is_repeated: def RepeatedFieldSize(value): result = (tag_size * len(value)) for element in value: l = element.ByteSize() result += (local_VarintSize(l) +...
null
null
null
Returns a sizer for a message field.
pcsd
def Message Sizer field number is repeated is packed tag size = Tag Size field number local Varint Size = Varint Size assert not is packed if is repeated def Repeated Field Size value result = tag size * len value for element in value l = element Byte Size result += local Varint Size l + l return result return Repeated...
11227
def MessageSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) local_VarintSize = _VarintSize assert (not is_packed) if is_repeated: def RepeatedFieldSize(value): result = (tag_size * len(value)) for element in value: l = element.ByteSize() result += (local_VarintSize(l) +...
Returns a sizer for a message field.
returns a sizer for a message field .
Question: What does this function do? Code: def MessageSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) local_VarintSize = _VarintSize assert (not is_packed) if is_repeated: def RepeatedFieldSize(value): result = (tag_size * len(value)) for element in value: l = element....
null
null
null
What does this function do?
def _ip_range_splitter(ips, block_size=256): out = [] count = 0 for ip in ips: out.append(ip['address']) count += 1 if (count > (block_size - 1)): (yield out) out = [] count = 0 if out: (yield out)
null
null
null
Yields blocks of IPs no more than block_size elements long.
pcsd
def ip range splitter ips block size=256 out = [] count = 0 for ip in ips out append ip['address'] count += 1 if count > block size - 1 yield out out = [] count = 0 if out yield out
11229
def _ip_range_splitter(ips, block_size=256): out = [] count = 0 for ip in ips: out.append(ip['address']) count += 1 if (count > (block_size - 1)): (yield out) out = [] count = 0 if out: (yield out)
Yields blocks of IPs no more than block_size elements long.
yields blocks of ips no more than block _ size elements long .
Question: What does this function do? Code: def _ip_range_splitter(ips, block_size=256): out = [] count = 0 for ip in ips: out.append(ip['address']) count += 1 if (count > (block_size - 1)): (yield out) out = [] count = 0 if out: (yield out)
null
null
null
What does this function do?
def addRackHole(derivation, vector3RackProfiles, x, xmlElement): rackHole = euclidean.getComplexPolygon(complex(x, (- derivation.rackHoleBelow)), derivation.rackHoleRadius, (-13)) vector3RackProfiles.append(euclidean.getVector3Path(rackHole))
null
null
null
Add rack hole to vector3RackProfiles.
pcsd
def add Rack Hole derivation vector3Rack Profiles x xml Element rack Hole = euclidean get Complex Polygon complex x - derivation rack Hole Below derivation rack Hole Radius -13 vector3Rack Profiles append euclidean get Vector3Path rack Hole
11234
def addRackHole(derivation, vector3RackProfiles, x, xmlElement): rackHole = euclidean.getComplexPolygon(complex(x, (- derivation.rackHoleBelow)), derivation.rackHoleRadius, (-13)) vector3RackProfiles.append(euclidean.getVector3Path(rackHole))
Add rack hole to vector3RackProfiles.
add rack hole to vector3rackprofiles .
Question: What does this function do? Code: def addRackHole(derivation, vector3RackProfiles, x, xmlElement): rackHole = euclidean.getComplexPolygon(complex(x, (- derivation.rackHoleBelow)), derivation.rackHoleRadius, (-13)) vector3RackProfiles.append(euclidean.getVector3Path(rackHole))
null
null
null
What does this function do?
def services_for_instance(instance_id): ec2 = boto.ec2.connect_to_region(REGION) reservations = ec2.get_all_instances(instance_ids=[instance_id]) for reservation in reservations: for instance in reservation.instances: if (instance.id == instance_id): try: services = instance.tags['services'].split(',')...
null
null
null
Get the list of all services named by the services tag in this instance\'s tags.
pcsd
def services for instance instance id ec2 = boto ec2 connect to region REGION reservations = ec2 get all instances instance ids=[instance id] for reservation in reservations for instance in reservation instances if instance id == instance id try services = instance tags['services'] split ' ' except Key Error as ke msg ...
11236
def services_for_instance(instance_id): ec2 = boto.ec2.connect_to_region(REGION) reservations = ec2.get_all_instances(instance_ids=[instance_id]) for reservation in reservations: for instance in reservation.instances: if (instance.id == instance_id): try: services = instance.tags['services'].split(',')...
Get the list of all services named by the services tag in this instance\'s tags.
get the list of all services named by the services tag in this instances tags .
Question: What does this function do? Code: def services_for_instance(instance_id): ec2 = boto.ec2.connect_to_region(REGION) reservations = ec2.get_all_instances(instance_ids=[instance_id]) for reservation in reservations: for instance in reservation.instances: if (instance.id == instance_id): try: ...
null
null
null
What does this function do?
def impl_ret_untracked(ctx, builder, retty, ret): return ret
null
null
null
The return type is not a NRT object.
pcsd
def impl ret untracked ctx builder retty ret return ret
11238
def impl_ret_untracked(ctx, builder, retty, ret): return ret
The return type is not a NRT object.
the return type is not a nrt object .
Question: What does this function do? Code: def impl_ret_untracked(ctx, builder, retty, ret): return ret
null
null
null
What does this function do?
def early_stopping_monitor(i, est, locals): if (i == 9): return True else: return False
null
null
null
Returns True on the 10th iteration.
pcsd
def early stopping monitor i est locals if i == 9 return True else return False
11239
def early_stopping_monitor(i, est, locals): if (i == 9): return True else: return False
Returns True on the 10th iteration.
returns true on the 10th iteration .
Question: What does this function do? Code: def early_stopping_monitor(i, est, locals): if (i == 9): return True else: return False
null
null
null
What does this function do?
def usage(): print 'AppScale Server' print print 'Options:' print ((' DCTB --type=<' + ','.join(dbconstants.VALID_DATASTORES)) + '>') print ' DCTB --no_encryption' print ' DCTB --port'
null
null
null
Prints the usage for this web service.
pcsd
def usage print 'App Scale Server' print print 'Options ' print ' DCTB --type=<' + ' ' join dbconstants VALID DATASTORES + '>' print ' DCTB --no encryption' print ' DCTB --port'
11244
def usage(): print 'AppScale Server' print print 'Options:' print ((' DCTB --type=<' + ','.join(dbconstants.VALID_DATASTORES)) + '>') print ' DCTB --no_encryption' print ' DCTB --port'
Prints the usage for this web service.
prints the usage for this web service .
Question: What does this function do? Code: def usage(): print 'AppScale Server' print print 'Options:' print ((' DCTB --type=<' + ','.join(dbconstants.VALID_DATASTORES)) + '>') print ' DCTB --no_encryption' print ' DCTB --port'
null
null
null
What does this function do?
def _get_presser(fig): callbacks = fig.canvas.callbacks.callbacks['button_press_event'] func = None for (key, val) in callbacks.items(): if (val.func.__class__.__name__ == 'partial'): func = val.func break assert (func is not None) return func
null
null
null
Get our press callback.
pcsd
def get presser fig callbacks = fig canvas callbacks callbacks['button press event'] func = None for key val in callbacks items if val func class name == 'partial' func = val func break assert func is not None return func
11247
def _get_presser(fig): callbacks = fig.canvas.callbacks.callbacks['button_press_event'] func = None for (key, val) in callbacks.items(): if (val.func.__class__.__name__ == 'partial'): func = val.func break assert (func is not None) return func
Get our press callback.
get our press callback .
Question: What does this function do? Code: def _get_presser(fig): callbacks = fig.canvas.callbacks.callbacks['button_press_event'] func = None for (key, val) in callbacks.items(): if (val.func.__class__.__name__ == 'partial'): func = val.func break assert (func is not None) return func
null
null
null
What does this function do?
def flatten_dict(d, parent_key=''): items = [] for (k, v) in d.items(): new_key = (((parent_key + '.') + k) if parent_key else k) if isinstance(v, collections.MutableMapping): items.extend(list(flatten_dict(v, new_key).items())) else: items.append((new_key, v)) return dict(items)
null
null
null
Flatten a nested dictionary. Converts a dictionary with nested values to a single level flat dictionary, with dotted notation for each key.
pcsd
def flatten dict d parent key='' items = [] for k v in d items new key = parent key + ' ' + k if parent key else k if isinstance v collections Mutable Mapping items extend list flatten dict v new key items else items append new key v return dict items
11249
def flatten_dict(d, parent_key=''): items = [] for (k, v) in d.items(): new_key = (((parent_key + '.') + k) if parent_key else k) if isinstance(v, collections.MutableMapping): items.extend(list(flatten_dict(v, new_key).items())) else: items.append((new_key, v)) return dict(items)
Flatten a nested dictionary. Converts a dictionary with nested values to a single level flat dictionary, with dotted notation for each key.
flatten a nested dictionary .
Question: What does this function do? Code: def flatten_dict(d, parent_key=''): items = [] for (k, v) in d.items(): new_key = (((parent_key + '.') + k) if parent_key else k) if isinstance(v, collections.MutableMapping): items.extend(list(flatten_dict(v, new_key).items())) else: items.append((new_key, v...
null
null
null
What does this function do?
def trim_str(string, max_len, concat_char): if (len(string) > max_len): return (string[:(max_len - len(concat_char))] + concat_char) return string
null
null
null
Truncates the given string for display.
pcsd
def trim str string max len concat char if len string > max len return string[ max len - len concat char ] + concat char return string
11261
def trim_str(string, max_len, concat_char): if (len(string) > max_len): return (string[:(max_len - len(concat_char))] + concat_char) return string
Truncates the given string for display.
truncates the given string for display .
Question: What does this function do? Code: def trim_str(string, max_len, concat_char): if (len(string) > max_len): return (string[:(max_len - len(concat_char))] + concat_char) return string
null
null
null
What does this function do?
@library.global_function def profile_url(user, edit=False): if edit: return reverse('users.edit_profile', args=[user.username]) return reverse('users.profile', args=[user.username])
null
null
null
Return a URL to the user\'s profile.
pcsd
@library global function def profile url user edit=False if edit return reverse 'users edit profile' args=[user username] return reverse 'users profile' args=[user username]
11279
@library.global_function def profile_url(user, edit=False): if edit: return reverse('users.edit_profile', args=[user.username]) return reverse('users.profile', args=[user.username])
Return a URL to the user\'s profile.
return a url to the users profile .
Question: What does this function do? Code: @library.global_function def profile_url(user, edit=False): if edit: return reverse('users.edit_profile', args=[user.username]) return reverse('users.profile', args=[user.username])
null
null
null
What does this function do?
def seed_milestone_relationship_types(): if (not settings.FEATURES.get('MILESTONES_APP')): return None MilestoneRelationshipType.objects.create(name='requires') MilestoneRelationshipType.objects.create(name='fulfills')
null
null
null
Helper method to pre-populate MRTs so the tests can run
pcsd
def seed milestone relationship types if not settings FEATURES get 'MILESTONES APP' return None Milestone Relationship Type objects create name='requires' Milestone Relationship Type objects create name='fulfills'
11281
def seed_milestone_relationship_types(): if (not settings.FEATURES.get('MILESTONES_APP')): return None MilestoneRelationshipType.objects.create(name='requires') MilestoneRelationshipType.objects.create(name='fulfills')
Helper method to pre-populate MRTs so the tests can run
helper method to pre - populate mrts so the tests can run
Question: What does this function do? Code: def seed_milestone_relationship_types(): if (not settings.FEATURES.get('MILESTONES_APP')): return None MilestoneRelationshipType.objects.create(name='requires') MilestoneRelationshipType.objects.create(name='fulfills')
null
null
null
What does this function do?
@_FFI.callback(u'void(ExternContext*, Handle*, uint64_t)') def extern_drop_handles(context_handle, handles_ptr, handles_len): c = _FFI.from_handle(context_handle) handles = _FFI.unpack(handles_ptr, handles_len) c.drop_handles(handles)
null
null
null
Drop the given Handles.
pcsd
@ FFI callback u'void Extern Context* Handle* uint64 t ' def extern drop handles context handle handles ptr handles len c = FFI from handle context handle handles = FFI unpack handles ptr handles len c drop handles handles
11285
@_FFI.callback(u'void(ExternContext*, Handle*, uint64_t)') def extern_drop_handles(context_handle, handles_ptr, handles_len): c = _FFI.from_handle(context_handle) handles = _FFI.unpack(handles_ptr, handles_len) c.drop_handles(handles)
Drop the given Handles.
drop the given handles .
Question: What does this function do? Code: @_FFI.callback(u'void(ExternContext*, Handle*, uint64_t)') def extern_drop_handles(context_handle, handles_ptr, handles_len): c = _FFI.from_handle(context_handle) handles = _FFI.unpack(handles_ptr, handles_len) c.drop_handles(handles)
null
null
null
What does this function do?
def get_network_adapter_type(adapter_type): if (adapter_type == 'vmxnet'): return vim.vm.device.VirtualVmxnet() elif (adapter_type == 'vmxnet2'): return vim.vm.device.VirtualVmxnet2() elif (adapter_type == 'vmxnet3'): return vim.vm.device.VirtualVmxnet3() elif (adapter_type == 'e1000'): return vim.vm.device...
null
null
null
Return the network adapter type. adpater_type The adapter type from which to obtain the network adapter type.
pcsd
def get network adapter type adapter type if adapter type == 'vmxnet' return vim vm device Virtual Vmxnet elif adapter type == 'vmxnet2' return vim vm device Virtual Vmxnet2 elif adapter type == 'vmxnet3' return vim vm device Virtual Vmxnet3 elif adapter type == 'e1000' return vim vm device Virtual E1000 elif adapter t...
11293
def get_network_adapter_type(adapter_type): if (adapter_type == 'vmxnet'): return vim.vm.device.VirtualVmxnet() elif (adapter_type == 'vmxnet2'): return vim.vm.device.VirtualVmxnet2() elif (adapter_type == 'vmxnet3'): return vim.vm.device.VirtualVmxnet3() elif (adapter_type == 'e1000'): return vim.vm.device...
Return the network adapter type. adpater_type The adapter type from which to obtain the network adapter type.
return the network adapter type .
Question: What does this function do? Code: def get_network_adapter_type(adapter_type): if (adapter_type == 'vmxnet'): return vim.vm.device.VirtualVmxnet() elif (adapter_type == 'vmxnet2'): return vim.vm.device.VirtualVmxnet2() elif (adapter_type == 'vmxnet3'): return vim.vm.device.VirtualVmxnet3() elif (a...
null
null
null
What does this function do?
def itervalues(d, **kw): return iter(getattr(d, _itervalues)(**kw))
null
null
null
Return an iterator over the values of a dictionary.
pcsd
def itervalues d **kw return iter getattr d itervalues **kw
11295
def itervalues(d, **kw): return iter(getattr(d, _itervalues)(**kw))
Return an iterator over the values of a dictionary.
return an iterator over the values of a dictionary .
Question: What does this function do? Code: def itervalues(d, **kw): return iter(getattr(d, _itervalues)(**kw))
null
null
null
What does this function do?
def server(request): return direct_to_template(request, 'server/index.html', {'user_url': getViewURL(request, idPage), 'server_xrds_url': getViewURL(request, idpXrds)})
null
null
null
Respond to requests for the server\'s primary web page.
pcsd
def server request return direct to template request 'server/index html' {'user url' get View URL request id Page 'server xrds url' get View URL request idp Xrds }
11308
def server(request): return direct_to_template(request, 'server/index.html', {'user_url': getViewURL(request, idPage), 'server_xrds_url': getViewURL(request, idpXrds)})
Respond to requests for the server\'s primary web page.
respond to requests for the servers primary web page .
Question: What does this function do? Code: def server(request): return direct_to_template(request, 'server/index.html', {'user_url': getViewURL(request, idPage), 'server_xrds_url': getViewURL(request, idpXrds)})
null
null
null
What does this function do?
@require_POST @csrf_exempt @ratelimit('document-vote', '10/d') def helpful_vote(request, document_slug): if ('revision_id' not in request.POST): return HttpResponseBadRequest() revision = get_object_or_404(Revision, id=smart_int(request.POST['revision_id'])) survey = None if (revision.document.category == TEMPLAT...
null
null
null
Vote for Helpful/Not Helpful document
pcsd
@require POST @csrf exempt @ratelimit 'document-vote' '10/d' def helpful vote request document slug if 'revision id' not in request POST return Http Response Bad Request revision = get object or 404 Revision id=smart int request POST['revision id'] survey = None if revision document category == TEMPLATES CATEGORY retur...
11314
@require_POST @csrf_exempt @ratelimit('document-vote', '10/d') def helpful_vote(request, document_slug): if ('revision_id' not in request.POST): return HttpResponseBadRequest() revision = get_object_or_404(Revision, id=smart_int(request.POST['revision_id'])) survey = None if (revision.document.category == TEMPLAT...
Vote for Helpful/Not Helpful document
vote for helpful / not helpful document
Question: What does this function do? Code: @require_POST @csrf_exempt @ratelimit('document-vote', '10/d') def helpful_vote(request, document_slug): if ('revision_id' not in request.POST): return HttpResponseBadRequest() revision = get_object_or_404(Revision, id=smart_int(request.POST['revision_id'])) survey = ...
null
null
null
What does this function do?
def pre_queue(name, pp, cat, script, priority, size, groups): def fix(p): if ((not p) or (str(p).lower() == 'none')): return '' else: return UNTRANS(str(p)) values = [1, name, pp, cat, script, priority, None] script_path = make_script_path(cfg.pre_script()) if script_path: command = [script_path, name, ...
null
null
null
Run pre-queue script (if any) and process results
pcsd
def pre queue name pp cat script priority size groups def fix p if not p or str p lower == 'none' return '' else return UNTRANS str p values = [1 name pp cat script priority None] script path = make script path cfg pre script if script path command = [script path name fix pp fix cat fix script fix priority str size ' '...
11316
def pre_queue(name, pp, cat, script, priority, size, groups): def fix(p): if ((not p) or (str(p).lower() == 'none')): return '' else: return UNTRANS(str(p)) values = [1, name, pp, cat, script, priority, None] script_path = make_script_path(cfg.pre_script()) if script_path: command = [script_path, name, ...
Run pre-queue script (if any) and process results
run pre - queue script and process results
Question: What does this function do? Code: def pre_queue(name, pp, cat, script, priority, size, groups): def fix(p): if ((not p) or (str(p).lower() == 'none')): return '' else: return UNTRANS(str(p)) values = [1, name, pp, cat, script, priority, None] script_path = make_script_path(cfg.pre_script()) i...
null
null
null
What does this function do?
def guard_fsys_type(): sabnzbd.encoding.change_fsys(cfg.fsys_type())
null
null
null
Callback for change of file system naming type
pcsd
def guard fsys type sabnzbd encoding change fsys cfg fsys type
11327
def guard_fsys_type(): sabnzbd.encoding.change_fsys(cfg.fsys_type())
Callback for change of file system naming type
callback for change of file system naming type
Question: What does this function do? Code: def guard_fsys_type(): sabnzbd.encoding.change_fsys(cfg.fsys_type())
null
null
null
What does this function do?
def organisation_needs_skill(): s3.prep = (lambda r: ((r.method == 'options') and (r.representation == 's3json'))) return s3_rest_controller()
null
null
null
RESTful controller for option lookups
pcsd
def organisation needs skill s3 prep = lambda r r method == 'options' and r representation == 's3json' return s3 rest controller
11329
def organisation_needs_skill(): s3.prep = (lambda r: ((r.method == 'options') and (r.representation == 's3json'))) return s3_rest_controller()
RESTful controller for option lookups
restful controller for option lookups
Question: What does this function do? Code: def organisation_needs_skill(): s3.prep = (lambda r: ((r.method == 'options') and (r.representation == 's3json'))) return s3_rest_controller()
null
null
null
What does this function do?
def _get_baseline_from_tag(config, tag): last_snapshot = None for snapshot in __salt__['snapper.list_snapshots'](config): if (tag == snapshot['userdata'].get('baseline_tag')): if ((not last_snapshot) or (last_snapshot['timestamp'] < snapshot['timestamp'])): last_snapshot = snapshot return last_snapshot
null
null
null
Returns the last created baseline snapshot marked with `tag`
pcsd
def get baseline from tag config tag last snapshot = None for snapshot in salt ['snapper list snapshots'] config if tag == snapshot['userdata'] get 'baseline tag' if not last snapshot or last snapshot['timestamp'] < snapshot['timestamp'] last snapshot = snapshot return last snapshot
11330
def _get_baseline_from_tag(config, tag): last_snapshot = None for snapshot in __salt__['snapper.list_snapshots'](config): if (tag == snapshot['userdata'].get('baseline_tag')): if ((not last_snapshot) or (last_snapshot['timestamp'] < snapshot['timestamp'])): last_snapshot = snapshot return last_snapshot
Returns the last created baseline snapshot marked with `tag`
returns the last created baseline snapshot marked with tag
Question: What does this function do? Code: def _get_baseline_from_tag(config, tag): last_snapshot = None for snapshot in __salt__['snapper.list_snapshots'](config): if (tag == snapshot['userdata'].get('baseline_tag')): if ((not last_snapshot) or (last_snapshot['timestamp'] < snapshot['timestamp'])): last...
null
null
null
What does this function do?
def action_event_start(context, values): convert_datetimes(values, 'start_time') session = get_session() with session.begin(): action = _action_get_by_request_id(context, values['instance_uuid'], values['request_id'], session) if (not action): raise exception.InstanceActionNotFound(request_id=values['request_...
null
null
null
Start an event on an instance action.
pcsd
def action event start context values convert datetimes values 'start time' session = get session with session begin action = action get by request id context values['instance uuid'] values['request id'] session if not action raise exception Instance Action Not Found request id=values['request id'] instance uuid=values...
11350
def action_event_start(context, values): convert_datetimes(values, 'start_time') session = get_session() with session.begin(): action = _action_get_by_request_id(context, values['instance_uuid'], values['request_id'], session) if (not action): raise exception.InstanceActionNotFound(request_id=values['request_...
Start an event on an instance action.
start an event on an instance action .
Question: What does this function do? Code: def action_event_start(context, values): convert_datetimes(values, 'start_time') session = get_session() with session.begin(): action = _action_get_by_request_id(context, values['instance_uuid'], values['request_id'], session) if (not action): raise exception.Ins...
null
null
null
What does this function do?
def _jinja_env(): loader = jinja2.PackageLoader('cubes', 'templates') env = jinja2.Environment(loader=loader) return env
null
null
null
Create and return cubes jinja2 environment
pcsd
def jinja env loader = jinja2 Package Loader 'cubes' 'templates' env = jinja2 Environment loader=loader return env
11351
def _jinja_env(): loader = jinja2.PackageLoader('cubes', 'templates') env = jinja2.Environment(loader=loader) return env
Create and return cubes jinja2 environment
create and return cubes jinja2 environment
Question: What does this function do? Code: def _jinja_env(): loader = jinja2.PackageLoader('cubes', 'templates') env = jinja2.Environment(loader=loader) return env
null
null
null
What does this function do?
def _set_to_get(set_cmd, module): set_cmd = truncate_before(set_cmd, ' option:') get_cmd = set_cmd.split(' ') (key, value) = get_cmd[(-1)].split('=') module.log(('get commands %s ' % key)) return (((['--', 'get'] + get_cmd[:(-1)]) + [key]), value)
null
null
null
Convert set command to get command and set value. return tuple (get command, set value)
pcsd
def set to get set cmd module set cmd = truncate before set cmd ' option ' get cmd = set cmd split ' ' key value = get cmd[ -1 ] split '=' module log 'get commands %s ' % key return ['--' 'get'] + get cmd[ -1 ] + [key] value
11355
def _set_to_get(set_cmd, module): set_cmd = truncate_before(set_cmd, ' option:') get_cmd = set_cmd.split(' ') (key, value) = get_cmd[(-1)].split('=') module.log(('get commands %s ' % key)) return (((['--', 'get'] + get_cmd[:(-1)]) + [key]), value)
Convert set command to get command and set value. return tuple (get command, set value)
convert set command to get command and set value .
Question: What does this function do? Code: def _set_to_get(set_cmd, module): set_cmd = truncate_before(set_cmd, ' option:') get_cmd = set_cmd.split(' ') (key, value) = get_cmd[(-1)].split('=') module.log(('get commands %s ' % key)) return (((['--', 'get'] + get_cmd[:(-1)]) + [key]), value)
null
null
null
What does this function do?
@gen.coroutine def FinishServerLog(): if hasattr(LogBatchPersistor, '_instance'): (yield gen.Task(LogBatchPersistor.Instance().close)) delattr(LogBatchPersistor, '_instance')
null
null
null
Flushes server log to object store with a timeout.
pcsd
@gen coroutine def Finish Server Log if hasattr Log Batch Persistor ' instance' yield gen Task Log Batch Persistor Instance close delattr Log Batch Persistor ' instance'
11358
@gen.coroutine def FinishServerLog(): if hasattr(LogBatchPersistor, '_instance'): (yield gen.Task(LogBatchPersistor.Instance().close)) delattr(LogBatchPersistor, '_instance')
Flushes server log to object store with a timeout.
flushes server log to object store with a timeout .
Question: What does this function do? Code: @gen.coroutine def FinishServerLog(): if hasattr(LogBatchPersistor, '_instance'): (yield gen.Task(LogBatchPersistor.Instance().close)) delattr(LogBatchPersistor, '_instance')
null
null
null
What does this function do?
def _convert_comp_data(res4): if (res4['ncomp'] == 0): return res4['comp'] = sorted(res4['comp'], key=_comp_sort_keys) _check_comp(res4['comp']) first = 0 kind = (-1) comps = list() for k in range(len(res4['comp'])): if (res4['comp'][k]['coeff_type'] != kind): if (k > 0): comps.append(_conv_comp(res4[...
null
null
null
Convert the compensation data into named matrices.
pcsd
def convert comp data res4 if res4['ncomp'] == 0 return res4['comp'] = sorted res4['comp'] key= comp sort keys check comp res4['comp'] first = 0 kind = -1 comps = list for k in range len res4['comp'] if res4['comp'][k]['coeff type'] != kind if k > 0 comps append conv comp res4['comp'] first k - 1 res4['chs'] kind = res...
11360
def _convert_comp_data(res4): if (res4['ncomp'] == 0): return res4['comp'] = sorted(res4['comp'], key=_comp_sort_keys) _check_comp(res4['comp']) first = 0 kind = (-1) comps = list() for k in range(len(res4['comp'])): if (res4['comp'][k]['coeff_type'] != kind): if (k > 0): comps.append(_conv_comp(res4[...
Convert the compensation data into named matrices.
convert the compensation data into named matrices .
Question: What does this function do? Code: def _convert_comp_data(res4): if (res4['ncomp'] == 0): return res4['comp'] = sorted(res4['comp'], key=_comp_sort_keys) _check_comp(res4['comp']) first = 0 kind = (-1) comps = list() for k in range(len(res4['comp'])): if (res4['comp'][k]['coeff_type'] != kind): ...
null
null
null
What does this function do?
def retry_facebook_invite(modeladmin, request, queryset): invites = list(queryset) user_invites = defaultdict(list) for invite in invites: user_invites[invite.user].append(invite) for (user, invites) in user_invites.items(): profile = get_profile(user) graph = profile.get_offline_graph() if (not graph): ...
null
null
null
Retries sending the invite to the users wall
pcsd
def retry facebook invite modeladmin request queryset invites = list queryset user invites = defaultdict list for invite in invites user invites[invite user] append invite for user invites in user invites items profile = get profile user graph = profile get offline graph if not graph error message = 'couldnt connect to...
11362
def retry_facebook_invite(modeladmin, request, queryset): invites = list(queryset) user_invites = defaultdict(list) for invite in invites: user_invites[invite.user].append(invite) for (user, invites) in user_invites.items(): profile = get_profile(user) graph = profile.get_offline_graph() if (not graph): ...
Retries sending the invite to the users wall
retries sending the invite to the users wall
Question: What does this function do? Code: def retry_facebook_invite(modeladmin, request, queryset): invites = list(queryset) user_invites = defaultdict(list) for invite in invites: user_invites[invite.user].append(invite) for (user, invites) in user_invites.items(): profile = get_profile(user) graph = pr...
null
null
null
What does this function do?
def imax(*args): np = import_module('numpy') if (not all((isinstance(arg, (int, float, interval)) for arg in args))): return NotImplementedError else: new_args = [a for a in args if (isinstance(a, (int, float)) or a.is_valid)] if (len(new_args) == 0): if all(((a.is_valid is False) for a in args)): retur...
null
null
null
Evaluates the maximum of a list of intervals
pcsd
def imax *args np = import module 'numpy' if not all isinstance arg int float interval for arg in args return Not Implemented Error else new args = [a for a in args if isinstance a int float or a is valid ] if len new args == 0 if all a is valid is False for a in args return interval - np inf np inf is valid=False else...
11368
def imax(*args): np = import_module('numpy') if (not all((isinstance(arg, (int, float, interval)) for arg in args))): return NotImplementedError else: new_args = [a for a in args if (isinstance(a, (int, float)) or a.is_valid)] if (len(new_args) == 0): if all(((a.is_valid is False) for a in args)): retur...
Evaluates the maximum of a list of intervals
evaluates the maximum of a list of intervals
Question: What does this function do? Code: def imax(*args): np = import_module('numpy') if (not all((isinstance(arg, (int, float, interval)) for arg in args))): return NotImplementedError else: new_args = [a for a in args if (isinstance(a, (int, float)) or a.is_valid)] if (len(new_args) == 0): if all(((...
null
null
null
What does this function do?
def _split_ref_line(line): fields = line.rstrip('\n\r').split(' ') if (len(fields) != 2): raise PackedRefsException(('invalid ref line %r' % line)) (sha, name) = fields if (not valid_hexsha(sha)): raise PackedRefsException(('Invalid hex sha %r' % sha)) if (not check_ref_format(name)): raise PackedRefsExcepti...
null
null
null
Split a single ref line into a tuple of SHA1 and name.
pcsd
def split ref line line fields = line rstrip ' \r' split ' ' if len fields != 2 raise Packed Refs Exception 'invalid ref line %r' % line sha name = fields if not valid hexsha sha raise Packed Refs Exception 'Invalid hex sha %r' % sha if not check ref format name raise Packed Refs Exception 'invalid ref name %r' % name ...
11370
def _split_ref_line(line): fields = line.rstrip('\n\r').split(' ') if (len(fields) != 2): raise PackedRefsException(('invalid ref line %r' % line)) (sha, name) = fields if (not valid_hexsha(sha)): raise PackedRefsException(('Invalid hex sha %r' % sha)) if (not check_ref_format(name)): raise PackedRefsExcepti...
Split a single ref line into a tuple of SHA1 and name.
split a single ref line into a tuple of sha1 and name .
Question: What does this function do? Code: def _split_ref_line(line): fields = line.rstrip('\n\r').split(' ') if (len(fields) != 2): raise PackedRefsException(('invalid ref line %r' % line)) (sha, name) = fields if (not valid_hexsha(sha)): raise PackedRefsException(('Invalid hex sha %r' % sha)) if (not che...
null
null
null
What does this function do?
def loopbackUNIX(server, client, noisy=True): path = tempfile.mktemp() from twisted.internet import reactor f = policies.WrappingFactory(protocol.Factory()) serverWrapper = _FireOnClose(f, server) f.noisy = noisy f.buildProtocol = (lambda addr: serverWrapper) serverPort = reactor.listenUNIX(path, f) clientF = L...
null
null
null
Run session between server and client protocol instances over UNIX socket.
pcsd
def loopback UNIX server client noisy=True path = tempfile mktemp from twisted internet import reactor f = policies Wrapping Factory protocol Factory server Wrapper = Fire On Close f server f noisy = noisy f build Protocol = lambda addr server Wrapper server Port = reactor listen UNIX path f client F = Loopback Client ...
11382
def loopbackUNIX(server, client, noisy=True): path = tempfile.mktemp() from twisted.internet import reactor f = policies.WrappingFactory(protocol.Factory()) serverWrapper = _FireOnClose(f, server) f.noisy = noisy f.buildProtocol = (lambda addr: serverWrapper) serverPort = reactor.listenUNIX(path, f) clientF = L...
Run session between server and client protocol instances over UNIX socket.
run session between server and client protocol instances over unix socket .
Question: What does this function do? Code: def loopbackUNIX(server, client, noisy=True): path = tempfile.mktemp() from twisted.internet import reactor f = policies.WrappingFactory(protocol.Factory()) serverWrapper = _FireOnClose(f, server) f.noisy = noisy f.buildProtocol = (lambda addr: serverWrapper) server...
null
null
null
What does this function do?
def enforce_state(module, params): user = params['user'] key = params['key'] path = params.get('path', None) manage_dir = params.get('manage_dir', True) state = params.get('state', 'present') key_options = params.get('key_options', None) exclusive = params.get('exclusive', False) error_msg = 'Error getting key ...
null
null
null
Add or remove key.
pcsd
def enforce state module params user = params['user'] key = params['key'] path = params get 'path' None manage dir = params get 'manage dir' True state = params get 'state' 'present' key options = params get 'key options' None exclusive = params get 'exclusive' False error msg = 'Error getting key from %s' if key start...
11383
def enforce_state(module, params): user = params['user'] key = params['key'] path = params.get('path', None) manage_dir = params.get('manage_dir', True) state = params.get('state', 'present') key_options = params.get('key_options', None) exclusive = params.get('exclusive', False) error_msg = 'Error getting key ...
Add or remove key.
add or remove key .
Question: What does this function do? Code: def enforce_state(module, params): user = params['user'] key = params['key'] path = params.get('path', None) manage_dir = params.get('manage_dir', True) state = params.get('state', 'present') key_options = params.get('key_options', None) exclusive = params.get('excl...
null
null
null
What does this function do?
@pytest.mark.django_db def test_plugin_renders_absolute_links(): context = get_jinja_context() page = create_page(eternal=True, visible_in_menu=True) absolute_link = ('/%s' % page.url) plugin = PageLinksPlugin({'show_all_pages': True}) assert (absolute_link in plugin.render(context))
null
null
null
Test that the plugin renders only absolute links.
pcsd
@pytest mark django db def test plugin renders absolute links context = get jinja context page = create page eternal=True visible in menu=True absolute link = '/%s' % page url plugin = Page Links Plugin {'show all pages' True} assert absolute link in plugin render context
11386
@pytest.mark.django_db def test_plugin_renders_absolute_links(): context = get_jinja_context() page = create_page(eternal=True, visible_in_menu=True) absolute_link = ('/%s' % page.url) plugin = PageLinksPlugin({'show_all_pages': True}) assert (absolute_link in plugin.render(context))
Test that the plugin renders only absolute links.
test that the plugin renders only absolute links .
Question: What does this function do? Code: @pytest.mark.django_db def test_plugin_renders_absolute_links(): context = get_jinja_context() page = create_page(eternal=True, visible_in_menu=True) absolute_link = ('/%s' % page.url) plugin = PageLinksPlugin({'show_all_pages': True}) assert (absolute_link in plugin....
null
null
null
What does this function do?
def _get_user_info(user=None): if (not user): user = __salt__['config.option']('user') userinfo = __salt__['user.info'](user) if (not userinfo): if (user == 'salt'): userinfo = _get_user_info() else: raise SaltInvocationError('User {0} does not exist'.format(user)) return userinfo
null
null
null
Wrapper for user.info Salt function
pcsd
def get user info user=None if not user user = salt ['config option'] 'user' userinfo = salt ['user info'] user if not userinfo if user == 'salt' userinfo = get user info else raise Salt Invocation Error 'User {0} does not exist' format user return userinfo
11387
def _get_user_info(user=None): if (not user): user = __salt__['config.option']('user') userinfo = __salt__['user.info'](user) if (not userinfo): if (user == 'salt'): userinfo = _get_user_info() else: raise SaltInvocationError('User {0} does not exist'.format(user)) return userinfo
Wrapper for user.info Salt function
wrapper for user . info salt function
Question: What does this function do? Code: def _get_user_info(user=None): if (not user): user = __salt__['config.option']('user') userinfo = __salt__['user.info'](user) if (not userinfo): if (user == 'salt'): userinfo = _get_user_info() else: raise SaltInvocationError('User {0} does not exist'.format...
null
null
null
What does this function do?
def is_template_file(path): ext = os.path.splitext(path)[1].lower() return (ext in [u'.html', u'.htm', u'.xml'])
null
null
null
Return True if the given file path is an HTML file.
pcsd
def is template file path ext = os path splitext path [1] lower return ext in [u' html' u' htm' u' xml']
11390
def is_template_file(path): ext = os.path.splitext(path)[1].lower() return (ext in [u'.html', u'.htm', u'.xml'])
Return True if the given file path is an HTML file.
return true if the given file path is an html file .
Question: What does this function do? Code: def is_template_file(path): ext = os.path.splitext(path)[1].lower() return (ext in [u'.html', u'.htm', u'.xml'])
null
null
null
What does this function do?
def getRandomComplex(begin, end): endMinusBegin = (end - begin) return (begin + complex((random.random() * endMinusBegin.real), (random.random() * endMinusBegin.imag)))
null
null
null
Get random complex.
pcsd
def get Random Complex begin end end Minus Begin = end - begin return begin + complex random random * end Minus Begin real random random * end Minus Begin imag
11393
def getRandomComplex(begin, end): endMinusBegin = (end - begin) return (begin + complex((random.random() * endMinusBegin.real), (random.random() * endMinusBegin.imag)))
Get random complex.
get random complex .
Question: What does this function do? Code: def getRandomComplex(begin, end): endMinusBegin = (end - begin) return (begin + complex((random.random() * endMinusBegin.real), (random.random() * endMinusBegin.imag)))
null
null
null
What does this function do?
def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement): if (len(loop) < 3): return [loop] radius = lineation.getRadiusByPrefix(prefix, sideLength, xmlElement) if (radius == 0.0): return loop bevelLoop = [] for pointIndex in xrange(len(loop)): begin = loop[(((pointIndex + len(loop)) - 1) % len(l...
null
null
null
Get bevel loop.
pcsd
def get Manipulated Paths close loop prefix side Length xml Element if len loop < 3 return [loop] radius = lineation get Radius By Prefix prefix side Length xml Element if radius == 0 0 return loop bevel Loop = [] for point Index in xrange len loop begin = loop[ point Index + len loop - 1 % len loop ] center = loop[poi...
11397
def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement): if (len(loop) < 3): return [loop] radius = lineation.getRadiusByPrefix(prefix, sideLength, xmlElement) if (radius == 0.0): return loop bevelLoop = [] for pointIndex in xrange(len(loop)): begin = loop[(((pointIndex + len(loop)) - 1) % len(l...
Get bevel loop.
get bevel loop .
Question: What does this function do? Code: def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement): if (len(loop) < 3): return [loop] radius = lineation.getRadiusByPrefix(prefix, sideLength, xmlElement) if (radius == 0.0): return loop bevelLoop = [] for pointIndex in xrange(len(loop)): begin...
null
null
null
What does this function do?
def _if_unmodified_since_passes(last_modified, if_unmodified_since): return (last_modified and (last_modified <= if_unmodified_since))
null
null
null
Test the If-Unmodified-Since comparison as defined in section 3.4 of RFC 7232.
pcsd
def if unmodified since passes last modified if unmodified since return last modified and last modified <= if unmodified since
11401
def _if_unmodified_since_passes(last_modified, if_unmodified_since): return (last_modified and (last_modified <= if_unmodified_since))
Test the If-Unmodified-Since comparison as defined in section 3.4 of RFC 7232.
test the if - unmodified - since comparison as defined in section 3 . 4 of
Question: What does this function do? Code: def _if_unmodified_since_passes(last_modified, if_unmodified_since): return (last_modified and (last_modified <= if_unmodified_since))
null
null
null
What does this function do?
def endsInNewline(s): return (s[(- len('\n')):] == '\n')
null
null
null
Returns C{True} if this string ends in a newline.
pcsd
def ends In Newline s return s[ - len ' ' ] == ' '
11403
def endsInNewline(s): return (s[(- len('\n')):] == '\n')
Returns C{True} if this string ends in a newline.
returns c { true } if this string ends in a newline .
Question: What does this function do? Code: def endsInNewline(s): return (s[(- len('\n')):] == '\n')
null
null
null
What does this function do?
def _valid_device(value, device_type): config = OrderedDict() for (key, device) in value.items(): if ('packetid' in device.keys()): msg = (('You are using an outdated configuration of the rfxtrx ' + 'device, {}.'.format(key)) + ' Your new config should be:\n {}: \n name: {}'.format(device.get('packetid...
null
null
null
Validate a dictionary of devices definitions.
pcsd
def valid device value device type config = Ordered Dict for key device in value items if 'packetid' in device keys msg = 'You are using an outdated configuration of the rfxtrx ' + 'device {} ' format key + ' Your new config should be {} name {}' format device get 'packetid' device get ATTR NAME 'deivce name' LOGGER wa...
11405
def _valid_device(value, device_type): config = OrderedDict() for (key, device) in value.items(): if ('packetid' in device.keys()): msg = (('You are using an outdated configuration of the rfxtrx ' + 'device, {}.'.format(key)) + ' Your new config should be:\n {}: \n name: {}'.format(device.get('packetid...
Validate a dictionary of devices definitions.
validate a dictionary of devices definitions .
Question: What does this function do? Code: def _valid_device(value, device_type): config = OrderedDict() for (key, device) in value.items(): if ('packetid' in device.keys()): msg = (('You are using an outdated configuration of the rfxtrx ' + 'device, {}.'.format(key)) + ' Your new config should be:\n {}: ...