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 _retrieve_dummy(job_path): pass
null
null
null
Dummy function for retrieving host and logs
pcsd
def retrieve dummy job path pass
8136
def _retrieve_dummy(job_path): pass
Dummy function for retrieving host and logs
dummy function for retrieving host and logs
Question: What does this function do? Code: def _retrieve_dummy(job_path): pass
null
null
null
What does this function do?
def get_ipython_package_dir(): ipdir = os.path.dirname(IPython.__file__) return py3compat.cast_unicode(ipdir, fs_encoding)
null
null
null
Get the base directory where IPython itself is installed.
pcsd
def get ipython package dir ipdir = os path dirname I Python file return py3compat cast unicode ipdir fs encoding
8144
def get_ipython_package_dir(): ipdir = os.path.dirname(IPython.__file__) return py3compat.cast_unicode(ipdir, fs_encoding)
Get the base directory where IPython itself is installed.
get the base directory where ipython itself is installed .
Question: What does this function do? Code: def get_ipython_package_dir(): ipdir = os.path.dirname(IPython.__file__) return py3compat.cast_unicode(ipdir, fs_encoding)
null
null
null
What does this function do?
def skipUnless(condition, reason): if (not condition): return skip(reason) return _id
null
null
null
Skip a test unless the condition is true.
pcsd
def skip Unless condition reason if not condition return skip reason return id
8153
def skipUnless(condition, reason): if (not condition): return skip(reason) return _id
Skip a test unless the condition is true.
skip a test unless the condition is true .
Question: What does this function do? Code: def skipUnless(condition, reason): if (not condition): return skip(reason) return _id
null
null
null
What does this function do?
def _get_solids(tri_rrs, fros): tot_angle = np.zeros(len(fros)) slices = np.r_[(np.arange(0, len(fros), 100), [len(fros)])] for (i1, i2) in zip(slices[:(-1)], slices[1:]): v1 = (fros[i1:i2] - tri_rrs[:, 0, :][:, np.newaxis]) v2 = (fros[i1:i2] - tri_rrs[:, 1, :][:, np.newaxis]) v3 = (fros[i1:i2] - tri_rrs[:, 2,...
null
null
null
Compute _sum_solids_div total angle in chunks.
pcsd
def get solids tri rrs fros tot angle = np zeros len fros slices = np r [ np arange 0 len fros 100 [len fros ] ] for i1 i2 in zip slices[ -1 ] slices[1 ] v1 = fros[i1 i2] - tri rrs[ 0 ][ np newaxis] v2 = fros[i1 i2] - tri rrs[ 1 ][ np newaxis] v3 = fros[i1 i2] - tri rrs[ 2 ][ np newaxis] triples = fast cross nd sum v1 ...
8156
def _get_solids(tri_rrs, fros): tot_angle = np.zeros(len(fros)) slices = np.r_[(np.arange(0, len(fros), 100), [len(fros)])] for (i1, i2) in zip(slices[:(-1)], slices[1:]): v1 = (fros[i1:i2] - tri_rrs[:, 0, :][:, np.newaxis]) v2 = (fros[i1:i2] - tri_rrs[:, 1, :][:, np.newaxis]) v3 = (fros[i1:i2] - tri_rrs[:, 2,...
Compute _sum_solids_div total angle in chunks.
compute _ sum _ solids _ div total angle in chunks .
Question: What does this function do? Code: def _get_solids(tri_rrs, fros): tot_angle = np.zeros(len(fros)) slices = np.r_[(np.arange(0, len(fros), 100), [len(fros)])] for (i1, i2) in zip(slices[:(-1)], slices[1:]): v1 = (fros[i1:i2] - tri_rrs[:, 0, :][:, np.newaxis]) v2 = (fros[i1:i2] - tri_rrs[:, 1, :][:, n...
null
null
null
What does this function do?
def verify_signed_data(token, data): if data.startswith(MAC_MARKER): try: data = data[len(MAC_MARKER):] mac_data = json.loads(base64.b64decode(data)) mac = compute_mac(token, mac_data['serialized_data']) if (mac != mac_data['mac']): raise InvalidMacError(('invalid MAC; expect=%s, actual=%s' % (mac_da...
null
null
null
Verify data integrity by ensuring MAC is valid.
pcsd
def verify signed data token data if data startswith MAC MARKER try data = data[len MAC MARKER ] mac data = json loads base64 b64decode data mac = compute mac token mac data['serialized data'] if mac != mac data['mac'] raise Invalid Mac Error 'invalid MAC expect=%s actual=%s' % mac data['mac'] mac return json loads mac...
8161
def verify_signed_data(token, data): if data.startswith(MAC_MARKER): try: data = data[len(MAC_MARKER):] mac_data = json.loads(base64.b64decode(data)) mac = compute_mac(token, mac_data['serialized_data']) if (mac != mac_data['mac']): raise InvalidMacError(('invalid MAC; expect=%s, actual=%s' % (mac_da...
Verify data integrity by ensuring MAC is valid.
verify data integrity by ensuring mac is valid .
Question: What does this function do? Code: def verify_signed_data(token, data): if data.startswith(MAC_MARKER): try: data = data[len(MAC_MARKER):] mac_data = json.loads(base64.b64decode(data)) mac = compute_mac(token, mac_data['serialized_data']) if (mac != mac_data['mac']): raise InvalidMacError...
null
null
null
What does this function do?
@require_POST @login_required def edit_priority(request, pk): source = get_object_or_404(Source, pk=pk) if (not can_edit_priority(request.user, source.subproject.project)): raise PermissionDenied() form = PriorityForm(request.POST) if form.is_valid(): source.priority = form.cleaned_data['priority'] source.sav...
null
null
null
Change source string priority.
pcsd
@require POST @login required def edit priority request pk source = get object or 404 Source pk=pk if not can edit priority request user source subproject project raise Permission Denied form = Priority Form request POST if form is valid source priority = form cleaned data['priority'] source save else messages error re...
8166
@require_POST @login_required def edit_priority(request, pk): source = get_object_or_404(Source, pk=pk) if (not can_edit_priority(request.user, source.subproject.project)): raise PermissionDenied() form = PriorityForm(request.POST) if form.is_valid(): source.priority = form.cleaned_data['priority'] source.sav...
Change source string priority.
change source string priority .
Question: What does this function do? Code: @require_POST @login_required def edit_priority(request, pk): source = get_object_or_404(Source, pk=pk) if (not can_edit_priority(request.user, source.subproject.project)): raise PermissionDenied() form = PriorityForm(request.POST) if form.is_valid(): source.priori...
null
null
null
What does this function do?
def getmembers(object, predicate=None): results = [] for key in dir(object): try: value = getattr(object, key) except AttributeError: continue if ((not predicate) or predicate(value)): results.append((key, value)) results.sort() return results
null
null
null
Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.
pcsd
def getmembers object predicate=None results = [] for key in dir object try value = getattr object key except Attribute Error continue if not predicate or predicate value results append key value results sort return results
8172
def getmembers(object, predicate=None): results = [] for key in dir(object): try: value = getattr(object, key) except AttributeError: continue if ((not predicate) or predicate(value)): results.append((key, value)) results.sort() return results
Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.
return all members of an object as pairs sorted by name .
Question: What does this function do? Code: def getmembers(object, predicate=None): results = [] for key in dir(object): try: value = getattr(object, key) except AttributeError: continue if ((not predicate) or predicate(value)): results.append((key, value)) results.sort() return results
null
null
null
What does this function do?
def _get_record(gcdns, zone, record_type, record_name): record_id = ('%s:%s' % (record_type, record_name)) try: return gcdns.get_record(zone.id, record_id) except RecordDoesNotExistError: return None
null
null
null
Gets the record object for a given FQDN.
pcsd
def get record gcdns zone record type record name record id = '%s %s' % record type record name try return gcdns get record zone id record id except Record Does Not Exist Error return None
8174
def _get_record(gcdns, zone, record_type, record_name): record_id = ('%s:%s' % (record_type, record_name)) try: return gcdns.get_record(zone.id, record_id) except RecordDoesNotExistError: return None
Gets the record object for a given FQDN.
gets the record object for a given fqdn .
Question: What does this function do? Code: def _get_record(gcdns, zone, record_type, record_name): record_id = ('%s:%s' % (record_type, record_name)) try: return gcdns.get_record(zone.id, record_id) except RecordDoesNotExistError: return None
null
null
null
What does this function do?
def highlight_string(source, unit): if (unit is None): return [] highlights = [] for check in CHECKS: if (not CHECKS[check].target): continue highlights += CHECKS[check].check_highlight(source, unit) highlights.sort(key=(lambda x: x[0])) for hl_idx in range(0, len(highlights)): if (hl_idx >= len(highlig...
null
null
null
Returns highlights for a string
pcsd
def highlight string source unit if unit is None return [] highlights = [] for check in CHECKS if not CHECKS[check] target continue highlights += CHECKS[check] check highlight source unit highlights sort key= lambda x x[0] for hl idx in range 0 len highlights if hl idx >= len highlights break elref = highlights[hl idx]...
8185
def highlight_string(source, unit): if (unit is None): return [] highlights = [] for check in CHECKS: if (not CHECKS[check].target): continue highlights += CHECKS[check].check_highlight(source, unit) highlights.sort(key=(lambda x: x[0])) for hl_idx in range(0, len(highlights)): if (hl_idx >= len(highlig...
Returns highlights for a string
returns highlights for a string
Question: What does this function do? Code: def highlight_string(source, unit): if (unit is None): return [] highlights = [] for check in CHECKS: if (not CHECKS[check].target): continue highlights += CHECKS[check].check_highlight(source, unit) highlights.sort(key=(lambda x: x[0])) for hl_idx in range(0...
null
null
null
What does this function do?
@synchronized(IO_LOCK) def remove_data(_id, path): path = os.path.join(path, _id) try: if os.path.exists(path): os.remove(path) logging.info('%s removed', path) except: logging.debug('Failed to remove %s', path)
null
null
null
Remove admin file
pcsd
@synchronized IO LOCK def remove data id path path = os path join path id try if os path exists path os remove path logging info '%s removed' path except logging debug 'Failed to remove %s' path
8193
@synchronized(IO_LOCK) def remove_data(_id, path): path = os.path.join(path, _id) try: if os.path.exists(path): os.remove(path) logging.info('%s removed', path) except: logging.debug('Failed to remove %s', path)
Remove admin file
remove admin file
Question: What does this function do? Code: @synchronized(IO_LOCK) def remove_data(_id, path): path = os.path.join(path, _id) try: if os.path.exists(path): os.remove(path) logging.info('%s removed', path) except: logging.debug('Failed to remove %s', path)
null
null
null
What does this function do?
def setRawInputMode(raw): pass
null
null
null
Sets the raw input mode, in windows.
pcsd
def set Raw Input Mode raw pass
8200
def setRawInputMode(raw): pass
Sets the raw input mode, in windows.
sets the raw input mode , in windows .
Question: What does this function do? Code: def setRawInputMode(raw): pass
null
null
null
What does this function do?
def _add_p_tags(raw_body): return '<p>{raw_body}</p>'.format(raw_body=raw_body)
null
null
null
Return raw_body surrounded by p tags
pcsd
def add p tags raw body return '<p>{raw body}</p>' format raw body=raw body
8207
def _add_p_tags(raw_body): return '<p>{raw_body}</p>'.format(raw_body=raw_body)
Return raw_body surrounded by p tags
return raw _ body surrounded by p tags
Question: What does this function do? Code: def _add_p_tags(raw_body): return '<p>{raw_body}</p>'.format(raw_body=raw_body)
null
null
null
What does this function do?
def list_frameworks(): sys.stdout.write(('Testable frameworks: %s\n\nNote that membership in this list means the framework can be tested with\nPyMongo, not necessarily that it is officially supported.\n' % ', '.join(sorted(FRAMEWORKS))))
null
null
null
Tell the user what framework names are valid.
pcsd
def list frameworks sys stdout write 'Testable frameworks %s Note that membership in this list means the framework can be tested with Py Mongo not necessarily that it is officially supported ' % ' ' join sorted FRAMEWORKS
8211
def list_frameworks(): sys.stdout.write(('Testable frameworks: %s\n\nNote that membership in this list means the framework can be tested with\nPyMongo, not necessarily that it is officially supported.\n' % ', '.join(sorted(FRAMEWORKS))))
Tell the user what framework names are valid.
tell the user what framework names are valid .
Question: What does this function do? Code: def list_frameworks(): sys.stdout.write(('Testable frameworks: %s\n\nNote that membership in this list means the framework can be tested with\nPyMongo, not necessarily that it is officially supported.\n' % ', '.join(sorted(FRAMEWORKS))))
null
null
null
What does this function do?
def prepare(annotations): def expand_annotation(annotation): if isinstance(annotation, dict): return MapAnnotation(annotation) elif isinstance(annotation, string_t): return mlazy(instantiate, annotation) return annotation if (annotations is None): return () elif (not isinstance(annotations, (list, tupl...
null
null
null
Expand the :setting:`task_annotations` setting.
pcsd
def prepare annotations def expand annotation annotation if isinstance annotation dict return Map Annotation annotation elif isinstance annotation string t return mlazy instantiate annotation return annotation if annotations is None return elif not isinstance annotations list tuple annotations = annotations return [exp...
8216
def prepare(annotations): def expand_annotation(annotation): if isinstance(annotation, dict): return MapAnnotation(annotation) elif isinstance(annotation, string_t): return mlazy(instantiate, annotation) return annotation if (annotations is None): return () elif (not isinstance(annotations, (list, tupl...
Expand the :setting:`task_annotations` setting.
expand the : setting : task _ annotations setting .
Question: What does this function do? Code: def prepare(annotations): def expand_annotation(annotation): if isinstance(annotation, dict): return MapAnnotation(annotation) elif isinstance(annotation, string_t): return mlazy(instantiate, annotation) return annotation if (annotations is None): return ()...
null
null
null
What does this function do?
def assert_attribute_matches(output, path, attribute, expression): xml = xml_find(output, path) attribute_value = xml.attrib[attribute] if (re.match(expression, attribute_value) is None): errmsg = ("Expected attribute '%s' on element with path '%s' to match '%s', instead attribute value was '%s'." % (attribute, pa...
null
null
null
Asserts the specified attribute of the first element matching the specified path matches the specified regular expression.
pcsd
def assert attribute matches output path attribute expression xml = xml find output path attribute value = xml attrib[attribute] if re match expression attribute value is None errmsg = "Expected attribute '%s' on element with path '%s' to match '%s' instead attribute value was '%s' " % attribute path expression attribu...
8218
def assert_attribute_matches(output, path, attribute, expression): xml = xml_find(output, path) attribute_value = xml.attrib[attribute] if (re.match(expression, attribute_value) is None): errmsg = ("Expected attribute '%s' on element with path '%s' to match '%s', instead attribute value was '%s'." % (attribute, pa...
Asserts the specified attribute of the first element matching the specified path matches the specified regular expression.
asserts the specified attribute of the first element matching the specified path matches the specified regular expression .
Question: What does this function do? Code: def assert_attribute_matches(output, path, attribute, expression): xml = xml_find(output, path) attribute_value = xml.attrib[attribute] if (re.match(expression, attribute_value) is None): errmsg = ("Expected attribute '%s' on element with path '%s' to match '%s', inst...
null
null
null
What does this function do?
def get_num_cat(sample_by_cat, samples_in_otus): num_cat = defaultdict(int) for (cat, samples) in sample_by_cat.items(): num_samples = len((set(samples_in_otus) & set(samples))) num_cat[cat[0]] += ((num_samples * (num_samples - 1)) / 2) return num_cat
null
null
null
Builds a dictionary of numbers of samples keyed by metadata value
pcsd
def get num cat sample by cat samples in otus num cat = defaultdict int for cat samples in sample by cat items num samples = len set samples in otus & set samples num cat[cat[0]] += num samples * num samples - 1 / 2 return num cat
8221
def get_num_cat(sample_by_cat, samples_in_otus): num_cat = defaultdict(int) for (cat, samples) in sample_by_cat.items(): num_samples = len((set(samples_in_otus) & set(samples))) num_cat[cat[0]] += ((num_samples * (num_samples - 1)) / 2) return num_cat
Builds a dictionary of numbers of samples keyed by metadata value
builds a dictionary of numbers of samples keyed by metadata value
Question: What does this function do? Code: def get_num_cat(sample_by_cat, samples_in_otus): num_cat = defaultdict(int) for (cat, samples) in sample_by_cat.items(): num_samples = len((set(samples_in_otus) & set(samples))) num_cat[cat[0]] += ((num_samples * (num_samples - 1)) / 2) return num_cat
null
null
null
What does this function do?
def load_check_from_places(check_config, check_name, checks_places, agentConfig): (load_success, load_failure) = ({}, {}) for check_path_builder in checks_places: check_path = check_path_builder(check_name) if (not os.path.exists(check_path)): continue (check_is_valid, check_class, load_failure) = get_valid_...
null
null
null
Find a check named check_name in the given checks_places and try to initialize it with the given check_config. A failure (`load_failure`) can happen when the check class can\'t be validated or when the check can\'t be initialized.
pcsd
def load check from places check config check name checks places agent Config load success load failure = {} {} for check path builder in checks places check path = check path builder check name if not os path exists check path continue check is valid check class load failure = get valid check class check name check pa...
8222
def load_check_from_places(check_config, check_name, checks_places, agentConfig): (load_success, load_failure) = ({}, {}) for check_path_builder in checks_places: check_path = check_path_builder(check_name) if (not os.path.exists(check_path)): continue (check_is_valid, check_class, load_failure) = get_valid_...
Find a check named check_name in the given checks_places and try to initialize it with the given check_config. A failure (`load_failure`) can happen when the check class can\'t be validated or when the check can\'t be initialized.
find a check named check _ name in the given checks _ places and try to initialize it with the given check _ config .
Question: What does this function do? Code: def load_check_from_places(check_config, check_name, checks_places, agentConfig): (load_success, load_failure) = ({}, {}) for check_path_builder in checks_places: check_path = check_path_builder(check_name) if (not os.path.exists(check_path)): continue (check_is...
null
null
null
What does this function do?
def getStrokeRadius(elementNode): return (0.5 * getRightStripAlphabetPercent(getStyleValue('1.0', elementNode, 'stroke-width')))
null
null
null
Get the stroke radius.
pcsd
def get Stroke Radius element Node return 0 5 * get Right Strip Alphabet Percent get Style Value '1 0' element Node 'stroke-width'
8229
def getStrokeRadius(elementNode): return (0.5 * getRightStripAlphabetPercent(getStyleValue('1.0', elementNode, 'stroke-width')))
Get the stroke radius.
get the stroke radius .
Question: What does this function do? Code: def getStrokeRadius(elementNode): return (0.5 * getRightStripAlphabetPercent(getStyleValue('1.0', elementNode, 'stroke-width')))
null
null
null
What does this function do?
def manage_recurring_documents(doctype, next_date=None, commit=True): next_date = (next_date or nowdate()) date_field = date_field_map[doctype] condition = (u" and ifnull(status, '') != 'Closed'" if (doctype in (u'Sales Order', u'Purchase Order')) else u'') recurring_documents = frappe.db.sql(u"select name, recurri...
null
null
null
Create recurring documents on specific date by copying the original one and notify the concerned people
pcsd
def manage recurring documents doctype next date=None commit=True next date = next date or nowdate date field = date field map[doctype] condition = u" and ifnull status '' != 'Closed'" if doctype in u'Sales Order' u'Purchase Order' else u'' recurring documents = frappe db sql u"select name recurring id DCTB DCTB from `...
8231
def manage_recurring_documents(doctype, next_date=None, commit=True): next_date = (next_date or nowdate()) date_field = date_field_map[doctype] condition = (u" and ifnull(status, '') != 'Closed'" if (doctype in (u'Sales Order', u'Purchase Order')) else u'') recurring_documents = frappe.db.sql(u"select name, recurri...
Create recurring documents on specific date by copying the original one and notify the concerned people
create recurring documents on specific date by copying the original one and notify the concerned people
Question: What does this function do? Code: def manage_recurring_documents(doctype, next_date=None, commit=True): next_date = (next_date or nowdate()) date_field = date_field_map[doctype] condition = (u" and ifnull(status, '') != 'Closed'" if (doctype in (u'Sales Order', u'Purchase Order')) else u'') recurring_d...
null
null
null
What does this function do?
def getRightStripAlphabetPercent(word): word = word.strip() for characterIndex in xrange((len(word) - 1), (-1), (-1)): character = word[characterIndex] if ((not character.isalpha()) and (not (character == '%'))): return float(word[:(characterIndex + 1)]) return None
null
null
null
Get word with alphabet characters and the percent sign stripped from the right.
pcsd
def get Right Strip Alphabet Percent word word = word strip for character Index in xrange len word - 1 -1 -1 character = word[character Index] if not character isalpha and not character == '%' return float word[ character Index + 1 ] return None
8238
def getRightStripAlphabetPercent(word): word = word.strip() for characterIndex in xrange((len(word) - 1), (-1), (-1)): character = word[characterIndex] if ((not character.isalpha()) and (not (character == '%'))): return float(word[:(characterIndex + 1)]) return None
Get word with alphabet characters and the percent sign stripped from the right.
get word with alphabet characters and the percent sign stripped from the right .
Question: What does this function do? Code: def getRightStripAlphabetPercent(word): word = word.strip() for characterIndex in xrange((len(word) - 1), (-1), (-1)): character = word[characterIndex] if ((not character.isalpha()) and (not (character == '%'))): return float(word[:(characterIndex + 1)]) return N...
null
null
null
What does this function do?
def _filter_domain_id_from_parents(domain_id, tree): new_tree = None if tree: (parent, children) = next(iter(tree.items())) if (parent != domain_id): new_tree = {parent: _filter_domain_id_from_parents(domain_id, children)} return new_tree
null
null
null
Removes the domain_id from the tree if present
pcsd
def filter domain id from parents domain id tree new tree = None if tree parent children = next iter tree items if parent != domain id new tree = {parent filter domain id from parents domain id children } return new tree
8248
def _filter_domain_id_from_parents(domain_id, tree): new_tree = None if tree: (parent, children) = next(iter(tree.items())) if (parent != domain_id): new_tree = {parent: _filter_domain_id_from_parents(domain_id, children)} return new_tree
Removes the domain_id from the tree if present
removes the domain _ id from the tree if present
Question: What does this function do? Code: def _filter_domain_id_from_parents(domain_id, tree): new_tree = None if tree: (parent, children) = next(iter(tree.items())) if (parent != domain_id): new_tree = {parent: _filter_domain_id_from_parents(domain_id, children)} return new_tree
null
null
null
What does this function do?
def template(pattern, flags=0): return _compile(pattern, (flags | TEMPLATE))
null
null
null
Compile a template pattern, returning a pattern object.
pcsd
def template pattern flags=0 return compile pattern flags | TEMPLATE
8257
def template(pattern, flags=0): return _compile(pattern, (flags | TEMPLATE))
Compile a template pattern, returning a pattern object.
compile a template pattern , returning a pattern object .
Question: What does this function do? Code: def template(pattern, flags=0): return _compile(pattern, (flags | TEMPLATE))
null
null
null
What does this function do?
@gen.coroutine def ping(): while True: (yield gen.sleep(0.25)) print '.'
null
null
null
print dots to indicate idleness
pcsd
@gen coroutine def ping while True yield gen sleep 0 25 print ' '
8259
@gen.coroutine def ping(): while True: (yield gen.sleep(0.25)) print '.'
print dots to indicate idleness
print dots to indicate idleness
Question: What does this function do? Code: @gen.coroutine def ping(): while True: (yield gen.sleep(0.25)) print '.'
null
null
null
What does this function do?
def __validate__(config): if (not isinstance(config, dict)): return (False, 'Configuration for network_settings beacon must be a dictionary.') else: for item in config: if (item == 'coalesce'): continue if (not isinstance(config[item], dict)): return (False, 'Configuration for network_settings beaco...
null
null
null
Validate the beacon configuration
pcsd
def validate config if not isinstance config dict return False 'Configuration for network settings beacon must be a dictionary ' else for item in config if item == 'coalesce' continue if not isinstance config[item] dict return False 'Configuration for network settings beacon must be a dictionary of dictionaries ' elif ...
8264
def __validate__(config): if (not isinstance(config, dict)): return (False, 'Configuration for network_settings beacon must be a dictionary.') else: for item in config: if (item == 'coalesce'): continue if (not isinstance(config[item], dict)): return (False, 'Configuration for network_settings beaco...
Validate the beacon configuration
validate the beacon configuration
Question: What does this function do? Code: def __validate__(config): if (not isinstance(config, dict)): return (False, 'Configuration for network_settings beacon must be a dictionary.') else: for item in config: if (item == 'coalesce'): continue if (not isinstance(config[item], dict)): return (F...
null
null
null
What does this function do?
def edit_language(): app = get_app() filename = '/'.join(request.args) response.title = request.args[(-1)] strings = read_dict(apath(filename, r=request)) if ('__corrupted__' in strings): form = SPAN(strings['__corrupted__'], _class='error') return dict(filename=filename, form=form) keys = sorted(strings.keys...
null
null
null
Edit language file
pcsd
def edit language app = get app filename = '/' join request args response title = request args[ -1 ] strings = read dict apath filename r=request if ' corrupted ' in strings form = SPAN strings[' corrupted '] class='error' return dict filename=filename form=form keys = sorted strings keys lambda x y cmp unicode x 'utf-...
8268
def edit_language(): app = get_app() filename = '/'.join(request.args) response.title = request.args[(-1)] strings = read_dict(apath(filename, r=request)) if ('__corrupted__' in strings): form = SPAN(strings['__corrupted__'], _class='error') return dict(filename=filename, form=form) keys = sorted(strings.keys...
Edit language file
edit language file
Question: What does this function do? Code: def edit_language(): app = get_app() filename = '/'.join(request.args) response.title = request.args[(-1)] strings = read_dict(apath(filename, r=request)) if ('__corrupted__' in strings): form = SPAN(strings['__corrupted__'], _class='error') return dict(filename=f...
null
null
null
What does this function do?
@testing.requires_testing_data def test_edf_overlapping_annotations(): n_warning = 2 with warnings.catch_warnings(record=True) as w: read_raw_edf(edf_overlap_annot_path, preload=True, verbose=True) assert_equal(sum((('overlapping' in str(ww.message)) for ww in w)), n_warning)
null
null
null
Test EDF with overlapping annotations.
pcsd
@testing requires testing data def test edf overlapping annotations n warning = 2 with warnings catch warnings record=True as w read raw edf edf overlap annot path preload=True verbose=True assert equal sum 'overlapping' in str ww message for ww in w n warning
8274
@testing.requires_testing_data def test_edf_overlapping_annotations(): n_warning = 2 with warnings.catch_warnings(record=True) as w: read_raw_edf(edf_overlap_annot_path, preload=True, verbose=True) assert_equal(sum((('overlapping' in str(ww.message)) for ww in w)), n_warning)
Test EDF with overlapping annotations.
test edf with overlapping annotations .
Question: What does this function do? Code: @testing.requires_testing_data def test_edf_overlapping_annotations(): n_warning = 2 with warnings.catch_warnings(record=True) as w: read_raw_edf(edf_overlap_annot_path, preload=True, verbose=True) assert_equal(sum((('overlapping' in str(ww.message)) for ww in w)), n...
null
null
null
What does this function do?
def discardLogs(): global logfile logfile = NullFile()
null
null
null
Throw away all logs.
pcsd
def discard Logs global logfile logfile = Null File
8286
def discardLogs(): global logfile logfile = NullFile()
Throw away all logs.
throw away all logs .
Question: What does this function do? Code: def discardLogs(): global logfile logfile = NullFile()
null
null
null
What does this function do?
def get_cert_file(): try: current_path = os.path.realpath(__file__) ca_cert_path = os.path.join(current_path, '..', '..', '..', 'conf', 'cacert.pem') return os.path.abspath(ca_cert_path) except Exception: return None
null
null
null
Get the cert file location or bail
pcsd
def get cert file try current path = os path realpath file ca cert path = os path join current path ' ' ' ' ' ' 'conf' 'cacert pem' return os path abspath ca cert path except Exception return None
8289
def get_cert_file(): try: current_path = os.path.realpath(__file__) ca_cert_path = os.path.join(current_path, '..', '..', '..', 'conf', 'cacert.pem') return os.path.abspath(ca_cert_path) except Exception: return None
Get the cert file location or bail
get the cert file location or bail
Question: What does this function do? Code: def get_cert_file(): try: current_path = os.path.realpath(__file__) ca_cert_path = os.path.join(current_path, '..', '..', '..', 'conf', 'cacert.pem') return os.path.abspath(ca_cert_path) except Exception: return None
null
null
null
What does this function do?
def emptytrash(): finder = _getfinder() args = {} attrs = {} args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form='prop', seld=aetypes.Type('trsh'), fr=None) (_reply, args, attrs) = finder.send('fndr', 'empt', args, attrs) if ('errn' in args): raise aetools.Error, aetools.decodeerror(args)
null
null
null
empty the trash
pcsd
def emptytrash finder = getfinder args = {} attrs = {} args['----'] = aetypes Object Specifier want=aetypes Type 'prop' form='prop' seld=aetypes Type 'trsh' fr=None reply args attrs = finder send 'fndr' 'empt' args attrs if 'errn' in args raise aetools Error aetools decodeerror args
8299
def emptytrash(): finder = _getfinder() args = {} attrs = {} args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form='prop', seld=aetypes.Type('trsh'), fr=None) (_reply, args, attrs) = finder.send('fndr', 'empt', args, attrs) if ('errn' in args): raise aetools.Error, aetools.decodeerror(args)
empty the trash
empty the trash
Question: What does this function do? Code: def emptytrash(): finder = _getfinder() args = {} attrs = {} args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form='prop', seld=aetypes.Type('trsh'), fr=None) (_reply, args, attrs) = finder.send('fndr', 'empt', args, attrs) if ('errn' in args): rai...
null
null
null
What does this function do?
@pytest.mark.parametrize(u'mode', modes) def test_gaussian_eval_1D(mode): model = Gaussian1D(1, 0, 20) x = np.arange((-100), 101) values = model(x) disc_values = discretize_model(model, ((-100), 101), mode=mode) assert_allclose(values, disc_values, atol=0.001)
null
null
null
Discretize Gaussian with different modes and check if result is at least similar to Gaussian1D.eval().
pcsd
@pytest mark parametrize u'mode' modes def test gaussian eval 1D mode model = Gaussian1D 1 0 20 x = np arange -100 101 values = model x disc values = discretize model model -100 101 mode=mode assert allclose values disc values atol=0 001
8303
@pytest.mark.parametrize(u'mode', modes) def test_gaussian_eval_1D(mode): model = Gaussian1D(1, 0, 20) x = np.arange((-100), 101) values = model(x) disc_values = discretize_model(model, ((-100), 101), mode=mode) assert_allclose(values, disc_values, atol=0.001)
Discretize Gaussian with different modes and check if result is at least similar to Gaussian1D.eval().
discretize gaussian with different modes and check if result is at least similar to gaussian1d . eval ( ) .
Question: What does this function do? Code: @pytest.mark.parametrize(u'mode', modes) def test_gaussian_eval_1D(mode): model = Gaussian1D(1, 0, 20) x = np.arange((-100), 101) values = model(x) disc_values = discretize_model(model, ((-100), 101), mode=mode) assert_allclose(values, disc_values, atol=0.001)
null
null
null
What does this function do?
def clear_trans_cache(): global _SKIN_CACHE dummy = _SKIN_CACHE _SKIN_CACHE = {} del dummy sabnzbd.WEBUI_READY = True
null
null
null
Clean cache for skin translations
pcsd
def clear trans cache global SKIN CACHE dummy = SKIN CACHE SKIN CACHE = {} del dummy sabnzbd WEBUI READY = True
8309
def clear_trans_cache(): global _SKIN_CACHE dummy = _SKIN_CACHE _SKIN_CACHE = {} del dummy sabnzbd.WEBUI_READY = True
Clean cache for skin translations
clean cache for skin translations
Question: What does this function do? Code: def clear_trans_cache(): global _SKIN_CACHE dummy = _SKIN_CACHE _SKIN_CACHE = {} del dummy sabnzbd.WEBUI_READY = True
null
null
null
What does this function do?
def select_row(view, row): selmodel = view.selectionModel() selmodel.select(view.model().index(row, 0), QItemSelectionModel.ClearAndSelect)
null
null
null
Select a `row` in an item view
pcsd
def select row view row selmodel = view selection Model selmodel select view model index row 0 Q Item Selection Model Clear And Select
8314
def select_row(view, row): selmodel = view.selectionModel() selmodel.select(view.model().index(row, 0), QItemSelectionModel.ClearAndSelect)
Select a `row` in an item view
select a row in an item view
Question: What does this function do? Code: def select_row(view, row): selmodel = view.selectionModel() selmodel.select(view.model().index(row, 0), QItemSelectionModel.ClearAndSelect)
null
null
null
What does this function do?
def escape(text): def fixup(m): ch = m.group(0) return (('&#' + str(ord(ch))) + ';') text = re.sub('[^ -~]|[&"]', fixup, text) return (text if isinstance(text, str) else str(text))
null
null
null
Use XML character references to escape characters. Use XML character references for unprintable or non-ASCII characters, double quotes and ampersands in a string
pcsd
def escape text def fixup m ch = m group 0 return '&#' + str ord ch + ' ' text = re sub '[^ -~]|[&"]' fixup text return text if isinstance text str else str text
8326
def escape(text): def fixup(m): ch = m.group(0) return (('&#' + str(ord(ch))) + ';') text = re.sub('[^ -~]|[&"]', fixup, text) return (text if isinstance(text, str) else str(text))
Use XML character references to escape characters. Use XML character references for unprintable or non-ASCII characters, double quotes and ampersands in a string
use xml character references to escape characters .
Question: What does this function do? Code: def escape(text): def fixup(m): ch = m.group(0) return (('&#' + str(ord(ch))) + ';') text = re.sub('[^ -~]|[&"]', fixup, text) return (text if isinstance(text, str) else str(text))
null
null
null
What does this function do?
def remove_course_milestones(course_key, user, relationship): if (not settings.FEATURES.get('MILESTONES_APP')): return None course_milestones = milestones_api.get_course_milestones(course_key=course_key, relationship=relationship) for milestone in course_milestones: milestones_api.remove_user_milestone({'id': us...
null
null
null
Remove all user milestones for the course specified by course_key.
pcsd
def remove course milestones course key user relationship if not settings FEATURES get 'MILESTONES APP' return None course milestones = milestones api get course milestones course key=course key relationship=relationship for milestone in course milestones milestones api remove user milestone {'id' user id} milestone
8333
def remove_course_milestones(course_key, user, relationship): if (not settings.FEATURES.get('MILESTONES_APP')): return None course_milestones = milestones_api.get_course_milestones(course_key=course_key, relationship=relationship) for milestone in course_milestones: milestones_api.remove_user_milestone({'id': us...
Remove all user milestones for the course specified by course_key.
remove all user milestones for the course specified by course _ key .
Question: What does this function do? Code: def remove_course_milestones(course_key, user, relationship): if (not settings.FEATURES.get('MILESTONES_APP')): return None course_milestones = milestones_api.get_course_milestones(course_key=course_key, relationship=relationship) for milestone in course_milestones: ...
null
null
null
What does this function do?
def get_basename(fileName): if fileName.endswith(os.path.sep): fileName = fileName[:(-1)] return os.path.basename(fileName)
null
null
null
Get the name of a file or folder specified in a path.
pcsd
def get basename file Name if file Name endswith os path sep file Name = file Name[ -1 ] return os path basename file Name
8342
def get_basename(fileName): if fileName.endswith(os.path.sep): fileName = fileName[:(-1)] return os.path.basename(fileName)
Get the name of a file or folder specified in a path.
get the name of a file or folder specified in a path .
Question: What does this function do? Code: def get_basename(fileName): if fileName.endswith(os.path.sep): fileName = fileName[:(-1)] return os.path.basename(fileName)
null
null
null
What does this function do?
def bins(data, values=None, column=None, bins=None, labels=None, **kwargs): if isinstance(data, str): column = data values = None else: column = None return Bins(values=values, column=column, bins=bins, **kwargs)
null
null
null
Specify binning or bins to be used for column or values.
pcsd
def bins data values=None column=None bins=None labels=None **kwargs if isinstance data str column = data values = None else column = None return Bins values=values column=column bins=bins **kwargs
8346
def bins(data, values=None, column=None, bins=None, labels=None, **kwargs): if isinstance(data, str): column = data values = None else: column = None return Bins(values=values, column=column, bins=bins, **kwargs)
Specify binning or bins to be used for column or values.
specify binning or bins to be used for column or values .
Question: What does this function do? Code: def bins(data, values=None, column=None, bins=None, labels=None, **kwargs): if isinstance(data, str): column = data values = None else: column = None return Bins(values=values, column=column, bins=bins, **kwargs)
null
null
null
What does this function do?
def deserialize_instance(model, data={}): ret = model() for (k, v) in data.items(): if (v is not None): try: f = model._meta.get_field(k) if isinstance(f, DateTimeField): v = dateparse.parse_datetime(v) elif isinstance(f, TimeField): v = dateparse.parse_time(v) elif isinstance(f, DateFi...
null
null
null
Translate raw data into a model instance.
pcsd
def deserialize instance model data={} ret = model for k v in data items if v is not None try f = model meta get field k if isinstance f Date Time Field v = dateparse parse datetime v elif isinstance f Time Field v = dateparse parse time v elif isinstance f Date Field v = dateparse parse date v except Field Does Not Ex...
8351
def deserialize_instance(model, data={}): ret = model() for (k, v) in data.items(): if (v is not None): try: f = model._meta.get_field(k) if isinstance(f, DateTimeField): v = dateparse.parse_datetime(v) elif isinstance(f, TimeField): v = dateparse.parse_time(v) elif isinstance(f, DateFi...
Translate raw data into a model instance.
translate raw data into a model instance .
Question: What does this function do? Code: def deserialize_instance(model, data={}): ret = model() for (k, v) in data.items(): if (v is not None): try: f = model._meta.get_field(k) if isinstance(f, DateTimeField): v = dateparse.parse_datetime(v) elif isinstance(f, TimeField): v = datepa...
null
null
null
What does this function do?
def getipbyhost(hostname): return socket.gethostbyname(hostname)
null
null
null
return the IP address for a hostname
pcsd
def getipbyhost hostname return socket gethostbyname hostname
8352
def getipbyhost(hostname): return socket.gethostbyname(hostname)
return the IP address for a hostname
return the ip address for a hostname
Question: What does this function do? Code: def getipbyhost(hostname): return socket.gethostbyname(hostname)
null
null
null
What does this function do?
def main(): global signal_received collection_interval = DEFAULT_COLLECTION_INTERVAL report_capacity_every_x_times = DEFAULT_REPORT_CAPACITY_EVERY_X_TIMES report_disks_in_vdevs = DEFAULT_REPORT_DISKS_IN_VDEVS if zfsiostats_conf: config = zfsiostats_conf.get_config() collection_interval = config['collection_int...
null
null
null
zfsiostats main loop
pcsd
def main global signal received collection interval = DEFAULT COLLECTION INTERVAL report capacity every x times = DEFAULT REPORT CAPACITY EVERY X TIMES report disks in vdevs = DEFAULT REPORT DISKS IN VDEVS if zfsiostats conf config = zfsiostats conf get config collection interval = config['collection interval'] report ...
8363
def main(): global signal_received collection_interval = DEFAULT_COLLECTION_INTERVAL report_capacity_every_x_times = DEFAULT_REPORT_CAPACITY_EVERY_X_TIMES report_disks_in_vdevs = DEFAULT_REPORT_DISKS_IN_VDEVS if zfsiostats_conf: config = zfsiostats_conf.get_config() collection_interval = config['collection_int...
zfsiostats main loop
zfsiostats main loop
Question: What does this function do? Code: def main(): global signal_received collection_interval = DEFAULT_COLLECTION_INTERVAL report_capacity_every_x_times = DEFAULT_REPORT_CAPACITY_EVERY_X_TIMES report_disks_in_vdevs = DEFAULT_REPORT_DISKS_IN_VDEVS if zfsiostats_conf: config = zfsiostats_conf.get_config()...
null
null
null
What does this function do?
def add(a, b): return (a + b)
null
null
null
Same as a + b.
pcsd
def add a b return a + b
8364
def add(a, b): return (a + b)
Same as a + b.
same as a + b .
Question: What does this function do? Code: def add(a, b): return (a + b)
null
null
null
What does this function do?
def connect(address): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(address) sock.setblocking(0) return sock
null
null
null
Connect to the given server and return a non-blocking socket.
pcsd
def connect address sock = socket socket socket AF INET socket SOCK STREAM sock connect address sock setblocking 0 return sock
8368
def connect(address): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(address) sock.setblocking(0) return sock
Connect to the given server and return a non-blocking socket.
connect to the given server and return a non - blocking socket .
Question: What does this function do? Code: def connect(address): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(address) sock.setblocking(0) return sock
null
null
null
What does this function do?
@pytest.mark.cmd @pytest.mark.django_db def __test_update_tmserver_noargs(capfd, tp0, settings): from pootle_store.models import Unit units_qs = Unit.objects.exclude(target_f__isnull=True).exclude(target_f__exact='') settings.POOTLE_TM_SERVER = {'local': {'ENGINE': 'pootle.core.search.backends.ElasticSearchBackend',...
null
null
null
Load TM from the database
pcsd
@pytest mark cmd @pytest mark django db def test update tmserver noargs capfd tp0 settings from pootle store models import Unit units qs = Unit objects exclude target f isnull=True exclude target f exact='' settings POOTLE TM SERVER = {'local' {'ENGINE' 'pootle core search backends Elastic Search Backend' 'HOST' 'local...
8370
@pytest.mark.cmd @pytest.mark.django_db def __test_update_tmserver_noargs(capfd, tp0, settings): from pootle_store.models import Unit units_qs = Unit.objects.exclude(target_f__isnull=True).exclude(target_f__exact='') settings.POOTLE_TM_SERVER = {'local': {'ENGINE': 'pootle.core.search.backends.ElasticSearchBackend',...
Load TM from the database
load tm from the database
Question: What does this function do? Code: @pytest.mark.cmd @pytest.mark.django_db def __test_update_tmserver_noargs(capfd, tp0, settings): from pootle_store.models import Unit units_qs = Unit.objects.exclude(target_f__isnull=True).exclude(target_f__exact='') settings.POOTLE_TM_SERVER = {'local': {'ENGINE': 'poo...
null
null
null
What does this function do?
def load_images(img_names): if (img_names[0] == ''): return {} for image_name in img_names: img = open(image_name) loaded_imgs = {} img_list = '' img_line = ' ' name = img.readline().replace('\n', '') name = name[1:] while True: img_line = img.readline() if (img_line == ''): break img_lin...
null
null
null
loads user images from given file(s)
pcsd
def load images img names if img names[0] == '' return {} for image name in img names img = open image name loaded imgs = {} img list = '' img line = ' ' name = img readline replace ' ' '' name = name[1 ] while True img line = img readline if img line == '' break img line replace ' ' '' if img line[0] == ' ' loaded img...
8377
def load_images(img_names): if (img_names[0] == ''): return {} for image_name in img_names: img = open(image_name) loaded_imgs = {} img_list = '' img_line = ' ' name = img.readline().replace('\n', '') name = name[1:] while True: img_line = img.readline() if (img_line == ''): break img_lin...
loads user images from given file(s)
loads user images from given file ( s )
Question: What does this function do? Code: def load_images(img_names): if (img_names[0] == ''): return {} for image_name in img_names: img = open(image_name) loaded_imgs = {} img_list = '' img_line = ' ' name = img.readline().replace('\n', '') name = name[1:] while True: img_line = img.readline...
null
null
null
What does this function do?
def build_request_repr(request, path_override=None, GET_override=None, POST_override=None, COOKIES_override=None, META_override=None): try: get = (pformat(GET_override) if (GET_override is not None) else pformat(request.GET)) except: get = '<could not parse>' if request._post_parse_error: post = '<could not pa...
null
null
null
Builds and returns the request\'s representation string. The request\'s attributes may be overridden by pre-processed values.
pcsd
def build request repr request path override=None GET override=None POST override=None COOKIES override=None META override=None try get = pformat GET override if GET override is not None else pformat request GET except get = '<could not parse>' if request post parse error post = '<could not parse>' else try post = pfor...
8380
def build_request_repr(request, path_override=None, GET_override=None, POST_override=None, COOKIES_override=None, META_override=None): try: get = (pformat(GET_override) if (GET_override is not None) else pformat(request.GET)) except: get = '<could not parse>' if request._post_parse_error: post = '<could not pa...
Builds and returns the request\'s representation string. The request\'s attributes may be overridden by pre-processed values.
builds and returns the requests representation string .
Question: What does this function do? Code: def build_request_repr(request, path_override=None, GET_override=None, POST_override=None, COOKIES_override=None, META_override=None): try: get = (pformat(GET_override) if (GET_override is not None) else pformat(request.GET)) except: get = '<could not parse>' if req...
null
null
null
What does this function do?
def removeElementFromDictionary(dictionary, key): if (key in dictionary): del dictionary[key]
null
null
null
Remove element from the dictionary.
pcsd
def remove Element From Dictionary dictionary key if key in dictionary del dictionary[key]
8399
def removeElementFromDictionary(dictionary, key): if (key in dictionary): del dictionary[key]
Remove element from the dictionary.
remove element from the dictionary .
Question: What does this function do? Code: def removeElementFromDictionary(dictionary, key): if (key in dictionary): del dictionary[key]
null
null
null
What does this function do?
def _parse_list_rule(rule): if (not rule): return TrueCheck() or_list = [] for inner_rule in rule: if (not inner_rule): continue if isinstance(inner_rule, basestring): inner_rule = [inner_rule] and_list = [_parse_check(r) for r in inner_rule] if (len(and_list) == 1): or_list.append(and_list[0]) ...
null
null
null
Provided for backwards compatibility. Translates the old list-of-lists syntax into a tree of Check objects.
pcsd
def parse list rule rule if not rule return True Check or list = [] for inner rule in rule if not inner rule continue if isinstance inner rule basestring inner rule = [inner rule] and list = [ parse check r for r in inner rule] if len and list == 1 or list append and list[0] else or list append And Check and list if le...
8418
def _parse_list_rule(rule): if (not rule): return TrueCheck() or_list = [] for inner_rule in rule: if (not inner_rule): continue if isinstance(inner_rule, basestring): inner_rule = [inner_rule] and_list = [_parse_check(r) for r in inner_rule] if (len(and_list) == 1): or_list.append(and_list[0]) ...
Provided for backwards compatibility. Translates the old list-of-lists syntax into a tree of Check objects.
provided for backwards compatibility .
Question: What does this function do? Code: def _parse_list_rule(rule): if (not rule): return TrueCheck() or_list = [] for inner_rule in rule: if (not inner_rule): continue if isinstance(inner_rule, basestring): inner_rule = [inner_rule] and_list = [_parse_check(r) for r in inner_rule] if (len(and...
null
null
null
What does this function do?
def randstr(length, alphabet='abcdefghijklmnopqrstuvwxyz0123456789'): return ''.join((random.choice(alphabet) for _ in xrange(length)))
null
null
null
Return a string made up of random chars from alphabet.
pcsd
def randstr length alphabet='abcdefghijklmnopqrstuvwxyz0123456789' return '' join random choice alphabet for in xrange length
8421
def randstr(length, alphabet='abcdefghijklmnopqrstuvwxyz0123456789'): return ''.join((random.choice(alphabet) for _ in xrange(length)))
Return a string made up of random chars from alphabet.
return a string made up of random chars from alphabet .
Question: What does this function do? Code: def randstr(length, alphabet='abcdefghijklmnopqrstuvwxyz0123456789'): return ''.join((random.choice(alphabet) for _ in xrange(length)))
null
null
null
What does this function do?
def freeze(obj): if isinstance(obj, dict): return ImmutableDict(obj) if isinstance(obj, list): return ImmutableList(obj) if isinstance(obj, set): return ImmutableSet(obj) return obj
null
null
null
Freeze python types by turning them into immutable structures.
pcsd
def freeze obj if isinstance obj dict return Immutable Dict obj if isinstance obj list return Immutable List obj if isinstance obj set return Immutable Set obj return obj
8427
def freeze(obj): if isinstance(obj, dict): return ImmutableDict(obj) if isinstance(obj, list): return ImmutableList(obj) if isinstance(obj, set): return ImmutableSet(obj) return obj
Freeze python types by turning them into immutable structures.
freeze python types by turning them into immutable structures .
Question: What does this function do? Code: def freeze(obj): if isinstance(obj, dict): return ImmutableDict(obj) if isinstance(obj, list): return ImmutableList(obj) if isinstance(obj, set): return ImmutableSet(obj) return obj
null
null
null
What does this function do?
def absolute_path_link(path): if os.path.islink(path): link = os.readlink(path) if (not os.path.isabs(link)): link = os.path.join(os.path.dirname(path), link) else: link = os.path.abspath(path) return link
null
null
null
Returns an absolute path for the destination of a symlink
pcsd
def absolute path link path if os path islink path link = os readlink path if not os path isabs link link = os path join os path dirname path link else link = os path abspath path return link
8429
def absolute_path_link(path): if os.path.islink(path): link = os.readlink(path) if (not os.path.isabs(link)): link = os.path.join(os.path.dirname(path), link) else: link = os.path.abspath(path) return link
Returns an absolute path for the destination of a symlink
returns an absolute path for the destination of a symlink
Question: What does this function do? Code: def absolute_path_link(path): if os.path.islink(path): link = os.readlink(path) if (not os.path.isabs(link)): link = os.path.join(os.path.dirname(path), link) else: link = os.path.abspath(path) return link
null
null
null
What does this function do?
def detect_text(path): vision_client = vision.Client() with io.open(path, 'rb') as image_file: content = image_file.read() image = vision_client.image(content=content) texts = image.detect_text() print 'Texts:' for text in texts: print text.description
null
null
null
Detects text in the file.
pcsd
def detect text path vision client = vision Client with io open path 'rb' as image file content = image file read image = vision client image content=content texts = image detect text print 'Texts ' for text in texts print text description
8432
def detect_text(path): vision_client = vision.Client() with io.open(path, 'rb') as image_file: content = image_file.read() image = vision_client.image(content=content) texts = image.detect_text() print 'Texts:' for text in texts: print text.description
Detects text in the file.
detects text in the file .
Question: What does this function do? Code: def detect_text(path): vision_client = vision.Client() with io.open(path, 'rb') as image_file: content = image_file.read() image = vision_client.image(content=content) texts = image.detect_text() print 'Texts:' for text in texts: print text.description
null
null
null
What does this function do?
def _traverse_results(value, fields, row, path): for (f, v) in value.iteritems(): field_name = ('{path}.{name}'.format(path=path, name=f) if path else f) if (not isinstance(v, (dict, list, tuple))): if (field_name in fields): row[fields.index(field_name)] = ensure_utf(v) elif (isinstance(v, dict) and (f !...
null
null
null
Helper method for parse_results(). Traverses through ordered dict and recursively calls itself when encountering a dictionary
pcsd
def traverse results value fields row path for f v in value iteritems field name = '{path} {name}' format path=path name=f if path else f if not isinstance v dict list tuple if field name in fields row[fields index field name ] = ensure utf v elif isinstance v dict and f != 'attributes' traverse results v fields row fi...
8439
def _traverse_results(value, fields, row, path): for (f, v) in value.iteritems(): field_name = ('{path}.{name}'.format(path=path, name=f) if path else f) if (not isinstance(v, (dict, list, tuple))): if (field_name in fields): row[fields.index(field_name)] = ensure_utf(v) elif (isinstance(v, dict) and (f !...
Helper method for parse_results(). Traverses through ordered dict and recursively calls itself when encountering a dictionary
helper method for parse _ results ( ) .
Question: What does this function do? Code: def _traverse_results(value, fields, row, path): for (f, v) in value.iteritems(): field_name = ('{path}.{name}'.format(path=path, name=f) if path else f) if (not isinstance(v, (dict, list, tuple))): if (field_name in fields): row[fields.index(field_name)] = ens...
null
null
null
What does this function do?
def _read_channel(fid): ch = dict() ch['sensor_type_index'] = _read_int2(fid) ch['original_run_no'] = _read_int2(fid) ch['coil_type'] = _read_int(fid) ch['proper_gain'] = _read_double(fid)[0] ch['qgain'] = _read_double(fid)[0] ch['io_gain'] = _read_double(fid)[0] ch['io_offset'] = _read_double(fid)[0] ch['num_...
null
null
null
Read channel information.
pcsd
def read channel fid ch = dict ch['sensor type index'] = read int2 fid ch['original run no'] = read int2 fid ch['coil type'] = read int fid ch['proper gain'] = read double fid [0] ch['qgain'] = read double fid [0] ch['io gain'] = read double fid [0] ch['io offset'] = read double fid [0] ch['num coils'] = read int2 fid ...
8447
def _read_channel(fid): ch = dict() ch['sensor_type_index'] = _read_int2(fid) ch['original_run_no'] = _read_int2(fid) ch['coil_type'] = _read_int(fid) ch['proper_gain'] = _read_double(fid)[0] ch['qgain'] = _read_double(fid)[0] ch['io_gain'] = _read_double(fid)[0] ch['io_offset'] = _read_double(fid)[0] ch['num_...
Read channel information.
read channel information .
Question: What does this function do? Code: def _read_channel(fid): ch = dict() ch['sensor_type_index'] = _read_int2(fid) ch['original_run_no'] = _read_int2(fid) ch['coil_type'] = _read_int(fid) ch['proper_gain'] = _read_double(fid)[0] ch['qgain'] = _read_double(fid)[0] ch['io_gain'] = _read_double(fid)[0] c...
null
null
null
What does this function do?
def GetInvisibleSpecialPropertyNames(): invisible_names = [] for (name, value) in _SPECIAL_PROPERTY_MAP.items(): (is_visible, is_stored, property_func) = value if (not is_visible): invisible_names.append(name) return invisible_names
null
null
null
Gets the names of all non user-visible special properties.
pcsd
def Get Invisible Special Property Names invisible names = [] for name value in SPECIAL PROPERTY MAP items is visible is stored property func = value if not is visible invisible names append name return invisible names
8449
def GetInvisibleSpecialPropertyNames(): invisible_names = [] for (name, value) in _SPECIAL_PROPERTY_MAP.items(): (is_visible, is_stored, property_func) = value if (not is_visible): invisible_names.append(name) return invisible_names
Gets the names of all non user-visible special properties.
gets the names of all non user - visible special properties .
Question: What does this function do? Code: def GetInvisibleSpecialPropertyNames(): invisible_names = [] for (name, value) in _SPECIAL_PROPERTY_MAP.items(): (is_visible, is_stored, property_func) = value if (not is_visible): invisible_names.append(name) return invisible_names
null
null
null
What does this function do?
def urlopen(url, data=None, proxies=None): from warnings import warnpy3k warnpy3k('urllib.urlopen() has been removed in Python 3.0 in favor of urllib2.urlopen()', stacklevel=2) global _urlopener if (proxies is not None): opener = FancyURLopener(proxies=proxies) elif (not _urlopener): opener = FancyURLopener() ...
null
null
null
Create a file-like object for the specified URL to read from.
pcsd
def urlopen url data=None proxies=None from warnings import warnpy3k warnpy3k 'urllib urlopen has been removed in Python 3 0 in favor of urllib2 urlopen ' stacklevel=2 global urlopener if proxies is not None opener = Fancy UR Lopener proxies=proxies elif not urlopener opener = Fancy UR Lopener urlopener = opener else o...
8464
def urlopen(url, data=None, proxies=None): from warnings import warnpy3k warnpy3k('urllib.urlopen() has been removed in Python 3.0 in favor of urllib2.urlopen()', stacklevel=2) global _urlopener if (proxies is not None): opener = FancyURLopener(proxies=proxies) elif (not _urlopener): opener = FancyURLopener() ...
Create a file-like object for the specified URL to read from.
create a file - like object for the specified url to read from .
Question: What does this function do? Code: def urlopen(url, data=None, proxies=None): from warnings import warnpy3k warnpy3k('urllib.urlopen() has been removed in Python 3.0 in favor of urllib2.urlopen()', stacklevel=2) global _urlopener if (proxies is not None): opener = FancyURLopener(proxies=proxies) elif...
null
null
null
What does this function do?
def get_setup_section(app, module, label, icon): config = get_config(app, module) for section in config: if (section.get(u'label') == _(u'Setup')): return {u'label': label, u'icon': icon, u'items': section[u'items']}
null
null
null
Get the setup section from each module (for global Setup page).
pcsd
def get setup section app module label icon config = get config app module for section in config if section get u'label' == u'Setup' return {u'label' label u'icon' icon u'items' section[u'items']}
8471
def get_setup_section(app, module, label, icon): config = get_config(app, module) for section in config: if (section.get(u'label') == _(u'Setup')): return {u'label': label, u'icon': icon, u'items': section[u'items']}
Get the setup section from each module (for global Setup page).
get the setup section from each module .
Question: What does this function do? Code: def get_setup_section(app, module, label, icon): config = get_config(app, module) for section in config: if (section.get(u'label') == _(u'Setup')): return {u'label': label, u'icon': icon, u'items': section[u'items']}
null
null
null
What does this function do?
def main(): startLogging(stdout) factory = PBClientFactory() reactor.connectTCP('localhost', 8800, factory) anonymousLogin = factory.login(Anonymous()) anonymousLogin.addCallback(connected) anonymousLogin.addErrback(error, 'Anonymous login failed') usernameLogin = factory.login(UsernamePassword('user1', 'pass1')...
null
null
null
Connect to a PB server running on port 8800 on localhost and log in to it, both anonymously and using a username/password it will recognize.
pcsd
def main start Logging stdout factory = PB Client Factory reactor connect TCP 'localhost' 8800 factory anonymous Login = factory login Anonymous anonymous Login add Callback connected anonymous Login add Errback error 'Anonymous login failed' username Login = factory login Username Password 'user1' 'pass1' username Log...
8475
def main(): startLogging(stdout) factory = PBClientFactory() reactor.connectTCP('localhost', 8800, factory) anonymousLogin = factory.login(Anonymous()) anonymousLogin.addCallback(connected) anonymousLogin.addErrback(error, 'Anonymous login failed') usernameLogin = factory.login(UsernamePassword('user1', 'pass1')...
Connect to a PB server running on port 8800 on localhost and log in to it, both anonymously and using a username/password it will recognize.
connect to a pb server running on port 8800 on localhost and log in to it , both anonymously and using a username / password it will recognize .
Question: What does this function do? Code: def main(): startLogging(stdout) factory = PBClientFactory() reactor.connectTCP('localhost', 8800, factory) anonymousLogin = factory.login(Anonymous()) anonymousLogin.addCallback(connected) anonymousLogin.addErrback(error, 'Anonymous login failed') usernameLogin = f...
null
null
null
What does this function do?
def scan(options): addrs = get_details_for_etag(options) if (addrs is None): addrs = options.scanplan if (options.maxfails > 0): addrs = addrs[:options.maxfails] else: logging.info(('--scan initiated against a known version: Only ' + 'sending one scan (expect success!)')) logging.debug((('scanplan = [' + '...
null
null
null
Scan for which vulnerability / stack address to use
pcsd
def scan options addrs = get details for etag options if addrs is None addrs = options scanplan if options maxfails > 0 addrs = addrs[ options maxfails] else logging info '--scan initiated against a known version Only ' + 'sending one scan expect success! ' logging debug 'scanplan = [' + ' ' join [ ' %s %s ' % x['actio...
8488
def scan(options): addrs = get_details_for_etag(options) if (addrs is None): addrs = options.scanplan if (options.maxfails > 0): addrs = addrs[:options.maxfails] else: logging.info(('--scan initiated against a known version: Only ' + 'sending one scan (expect success!)')) logging.debug((('scanplan = [' + '...
Scan for which vulnerability / stack address to use
scan for which vulnerability / stack address to use
Question: What does this function do? Code: def scan(options): addrs = get_details_for_etag(options) if (addrs is None): addrs = options.scanplan if (options.maxfails > 0): addrs = addrs[:options.maxfails] else: logging.info(('--scan initiated against a known version: Only ' + 'sending one scan (expect s...
null
null
null
What does this function do?
def handle404(request): return render(request, 'handlers/404.html', status=404)
null
null
null
A handler for 404s
pcsd
def handle404 request return render request 'handlers/404 html' status=404
8497
def handle404(request): return render(request, 'handlers/404.html', status=404)
A handler for 404s
a handler for 404s
Question: What does this function do? Code: def handle404(request): return render(request, 'handlers/404.html', status=404)
null
null
null
What does this function do?
def parse_boundary_stream(stream, max_header_size): chunk = stream.read(max_header_size) header_end = chunk.find('\r\n\r\n') def _parse_header(line): (main_value_pair, params) = parse_header(line) try: (name, value) = main_value_pair.split(u':', 1) except: raise ValueError((u'Invalid header: %r' % line))...
null
null
null
Parses one and exactly one stream that encapsulates a boundary.
pcsd
def parse boundary stream stream max header size chunk = stream read max header size header end = chunk find '\r \r ' def parse header line main value pair params = parse header line try name value = main value pair split u' ' 1 except raise Value Error u'Invalid header %r' % line return name value params if header end...
8498
def parse_boundary_stream(stream, max_header_size): chunk = stream.read(max_header_size) header_end = chunk.find('\r\n\r\n') def _parse_header(line): (main_value_pair, params) = parse_header(line) try: (name, value) = main_value_pair.split(u':', 1) except: raise ValueError((u'Invalid header: %r' % line))...
Parses one and exactly one stream that encapsulates a boundary.
parses one and exactly one stream that encapsulates a boundary .
Question: What does this function do? Code: def parse_boundary_stream(stream, max_header_size): chunk = stream.read(max_header_size) header_end = chunk.find('\r\n\r\n') def _parse_header(line): (main_value_pair, params) = parse_header(line) try: (name, value) = main_value_pair.split(u':', 1) except: r...
null
null
null
What does this function do?
def _assert_required_roles(cls, roles, methods): if (('appender' not in roles) or (not hasattr(cls, roles['appender']))): raise sa_exc.ArgumentError(('Type %s must elect an appender method to be a collection class' % cls.__name__)) elif ((roles['appender'] not in methods) and (not hasattr(getattr(cls, roles['append...
null
null
null
ensure all roles are present, and apply implicit instrumentation if needed
pcsd
def assert required roles cls roles methods if 'appender' not in roles or not hasattr cls roles['appender'] raise sa exc Argument Error 'Type %s must elect an appender method to be a collection class' % cls name elif roles['appender'] not in methods and not hasattr getattr cls roles['appender'] ' sa instrumented' metho...
8499
def _assert_required_roles(cls, roles, methods): if (('appender' not in roles) or (not hasattr(cls, roles['appender']))): raise sa_exc.ArgumentError(('Type %s must elect an appender method to be a collection class' % cls.__name__)) elif ((roles['appender'] not in methods) and (not hasattr(getattr(cls, roles['append...
ensure all roles are present, and apply implicit instrumentation if needed
ensure all roles are present , and apply implicit instrumentation if needed
Question: What does this function do? Code: def _assert_required_roles(cls, roles, methods): if (('appender' not in roles) or (not hasattr(cls, roles['appender']))): raise sa_exc.ArgumentError(('Type %s must elect an appender method to be a collection class' % cls.__name__)) elif ((roles['appender'] not in metho...
null
null
null
What does this function do?
def on_loop(notifier, counter): if (counter.count > 4): sys.stdout.write('Exit\n') notifier.stop() sys.exit(0) else: sys.stdout.write(('Loop %d\n' % counter.count)) counter.plusone()
null
null
null
Dummy function called after each event loop, this method only ensures the child process eventually exits (after 5 iterations).
pcsd
def on loop notifier counter if counter count > 4 sys stdout write 'Exit ' notifier stop sys exit 0 else sys stdout write 'Loop %d ' % counter count counter plusone
8510
def on_loop(notifier, counter): if (counter.count > 4): sys.stdout.write('Exit\n') notifier.stop() sys.exit(0) else: sys.stdout.write(('Loop %d\n' % counter.count)) counter.plusone()
Dummy function called after each event loop, this method only ensures the child process eventually exits (after 5 iterations).
dummy function called after each event loop , this method only ensures the child process eventually exits .
Question: What does this function do? Code: def on_loop(notifier, counter): if (counter.count > 4): sys.stdout.write('Exit\n') notifier.stop() sys.exit(0) else: sys.stdout.write(('Loop %d\n' % counter.count)) counter.plusone()
null
null
null
What does this function do?
@contextfilter def httime(context, time, timeformat='TIME_FORMAT'): if (not time): return '' lang = translation.get_language() localeformat = timeformat formatspath = getattr(settings, 'FORMAT_MODULE_PATH', 'treeio.formats') try: modulepath = (((formatspath + '.') + lang) + '.formats') module = __import__(mo...
null
null
null
Render time in the current locale
pcsd
@contextfilter def httime context time timeformat='TIME FORMAT' if not time return '' lang = translation get language localeformat = timeformat formatspath = getattr settings 'FORMAT MODULE PATH' 'treeio formats' try modulepath = formatspath + ' ' + lang + ' formats' module = import modulepath fromlist=[str modulepath ...
8515
@contextfilter def httime(context, time, timeformat='TIME_FORMAT'): if (not time): return '' lang = translation.get_language() localeformat = timeformat formatspath = getattr(settings, 'FORMAT_MODULE_PATH', 'treeio.formats') try: modulepath = (((formatspath + '.') + lang) + '.formats') module = __import__(mo...
Render time in the current locale
render time in the current locale
Question: What does this function do? Code: @contextfilter def httime(context, time, timeformat='TIME_FORMAT'): if (not time): return '' lang = translation.get_language() localeformat = timeformat formatspath = getattr(settings, 'FORMAT_MODULE_PATH', 'treeio.formats') try: modulepath = (((formatspath + '.')...
null
null
null
What does this function do?
@pytest.fixture() def filepath(): def make_filepath(filename): return os.path.join(FILES_DIR, filename) return make_filepath
null
null
null
Returns full file path for test files.
pcsd
@pytest fixture def filepath def make filepath filename return os path join FILES DIR filename return make filepath
8519
@pytest.fixture() def filepath(): def make_filepath(filename): return os.path.join(FILES_DIR, filename) return make_filepath
Returns full file path for test files.
returns full file path for test files .
Question: What does this function do? Code: @pytest.fixture() def filepath(): def make_filepath(filename): return os.path.join(FILES_DIR, filename) return make_filepath
null
null
null
What does this function do?
def update_index(quiet=True): manager = MANAGER if quiet: with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True): run_as_root(('%(manager)s --sync' % locals())) else: run_as_root(('%(manager)s --sync' % locals()))
null
null
null
Update Portage package definitions.
pcsd
def update index quiet=True manager = MANAGER if quiet with settings hide 'running' 'stdout' 'stderr' 'warnings' warn only=True run as root '% manager s --sync' % locals else run as root '% manager s --sync' % locals
8520
def update_index(quiet=True): manager = MANAGER if quiet: with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True): run_as_root(('%(manager)s --sync' % locals())) else: run_as_root(('%(manager)s --sync' % locals()))
Update Portage package definitions.
update portage package definitions .
Question: What does this function do? Code: def update_index(quiet=True): manager = MANAGER if quiet: with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True): run_as_root(('%(manager)s --sync' % locals())) else: run_as_root(('%(manager)s --sync' % locals()))
null
null
null
What does this function do?
def CleanupVcproj(node): for sub_node in node.childNodes: AbsoluteNode(sub_node) CleanupVcproj(sub_node) for sub_node in node.childNodes: if (sub_node.nodeType == Node.TEXT_NODE): sub_node.data = sub_node.data.replace('\r', '') sub_node.data = sub_node.data.replace('\n', '') sub_node.data = sub_node.da...
null
null
null
For each sub node, we call recursively this function.
pcsd
def Cleanup Vcproj node for sub node in node child Nodes Absolute Node sub node Cleanup Vcproj sub node for sub node in node child Nodes if sub node node Type == Node TEXT NODE sub node data = sub node data replace '\r' '' sub node data = sub node data replace ' ' '' sub node data = sub node data rstrip if node attribu...
8521
def CleanupVcproj(node): for sub_node in node.childNodes: AbsoluteNode(sub_node) CleanupVcproj(sub_node) for sub_node in node.childNodes: if (sub_node.nodeType == Node.TEXT_NODE): sub_node.data = sub_node.data.replace('\r', '') sub_node.data = sub_node.data.replace('\n', '') sub_node.data = sub_node.da...
For each sub node, we call recursively this function.
for each sub node , we call recursively this function .
Question: What does this function do? Code: def CleanupVcproj(node): for sub_node in node.childNodes: AbsoluteNode(sub_node) CleanupVcproj(sub_node) for sub_node in node.childNodes: if (sub_node.nodeType == Node.TEXT_NODE): sub_node.data = sub_node.data.replace('\r', '') sub_node.data = sub_node.data.r...
null
null
null
What does this function do?
def profile(func, stream=None): def wrapper(*args, **kwargs): prof = LineProfiler() val = prof(func)(*args, **kwargs) show_results(prof, stream=stream) return val return wrapper
null
null
null
Decorator that will run the function and print a line-by-line profile
pcsd
def profile func stream=None def wrapper *args **kwargs prof = Line Profiler val = prof func *args **kwargs show results prof stream=stream return val return wrapper
8528
def profile(func, stream=None): def wrapper(*args, **kwargs): prof = LineProfiler() val = prof(func)(*args, **kwargs) show_results(prof, stream=stream) return val return wrapper
Decorator that will run the function and print a line-by-line profile
decorator that will run the function and print a line - by - line profile
Question: What does this function do? Code: def profile(func, stream=None): def wrapper(*args, **kwargs): prof = LineProfiler() val = prof(func)(*args, **kwargs) show_results(prof, stream=stream) return val return wrapper
null
null
null
What does this function do?
@pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): outcome = (yield) if (call.when not in ['call', 'teardown']): return report = outcome.get_result() if report.passed: return if ((not hasattr(report.longrepr, 'addsection')) or (not hasattr(report, 'scenario'))): return if (sys.std...
null
null
null
Add a BDD section to the test output.
pcsd
@pytest hookimpl hookwrapper=True def pytest runtest makereport item call outcome = yield if call when not in ['call' 'teardown'] return report = outcome get result if report passed return if not hasattr report longrepr 'addsection' or not hasattr report 'scenario' return if sys stdout isatty and item config getoption ...
8536
@pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): outcome = (yield) if (call.when not in ['call', 'teardown']): return report = outcome.get_result() if report.passed: return if ((not hasattr(report.longrepr, 'addsection')) or (not hasattr(report, 'scenario'))): return if (sys.std...
Add a BDD section to the test output.
add a bdd section to the test output .
Question: What does this function do? Code: @pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): outcome = (yield) if (call.when not in ['call', 'teardown']): return report = outcome.get_result() if report.passed: return if ((not hasattr(report.longrepr, 'addsection')) or (not hasat...
null
null
null
What does this function do?
@command('c\\s?(\\d{1,4})') def comments(number): if (g.browse_mode == 'normal'): item = g.model[(int(number) - 1)] fetch_comments(item) else: g.content = generate_songlist_display() g.message = 'Comments only available for video items'
null
null
null
Receive use request to view comments.
pcsd
@command 'c\\s? \\d{1 4} ' def comments number if g browse mode == 'normal' item = g model[ int number - 1 ] fetch comments item else g content = generate songlist display g message = 'Comments only available for video items'
8537
@command('c\\s?(\\d{1,4})') def comments(number): if (g.browse_mode == 'normal'): item = g.model[(int(number) - 1)] fetch_comments(item) else: g.content = generate_songlist_display() g.message = 'Comments only available for video items'
Receive use request to view comments.
receive use request to view comments .
Question: What does this function do? Code: @command('c\\s?(\\d{1,4})') def comments(number): if (g.browse_mode == 'normal'): item = g.model[(int(number) - 1)] fetch_comments(item) else: g.content = generate_songlist_display() g.message = 'Comments only available for video items'
null
null
null
What does this function do?
def execute_locked(request, obj, message, call, *args, **kwargs): try: result = call(*args, **kwargs) if ((result is None) or result): messages.success(request, message) except FileLockException as error: messages.error(request, _('Failed to lock the repository, another operation in progress.')) report_err...
null
null
null
Helper function to catch possible lock exception.
pcsd
def execute locked request obj message call *args **kwargs try result = call *args **kwargs if result is None or result messages success request message except File Lock Exception as error messages error request 'Failed to lock the repository another operation in progress ' report error error sys exc info return redire...
8538
def execute_locked(request, obj, message, call, *args, **kwargs): try: result = call(*args, **kwargs) if ((result is None) or result): messages.success(request, message) except FileLockException as error: messages.error(request, _('Failed to lock the repository, another operation in progress.')) report_err...
Helper function to catch possible lock exception.
helper function to catch possible lock exception .
Question: What does this function do? Code: def execute_locked(request, obj, message, call, *args, **kwargs): try: result = call(*args, **kwargs) if ((result is None) or result): messages.success(request, message) except FileLockException as error: messages.error(request, _('Failed to lock the repository,...
null
null
null
What does this function do?
def _MPpow(x, y, z): return MP(pow(x, y, z))
null
null
null
Return the MP version of C{(x ** y) % z}.
pcsd
def M Ppow x y z return MP pow x y z
8541
def _MPpow(x, y, z): return MP(pow(x, y, z))
Return the MP version of C{(x ** y) % z}.
return the mp version of c { % z } .
Question: What does this function do? Code: def _MPpow(x, y, z): return MP(pow(x, y, z))
null
null
null
What does this function do?
def setGridLogger(): setLoggerClass(GridLogger)
null
null
null
Use GridLogger for all logging events.
pcsd
def set Grid Logger set Logger Class Grid Logger
8544
def setGridLogger(): setLoggerClass(GridLogger)
Use GridLogger for all logging events.
use gridlogger for all logging events .
Question: What does this function do? Code: def setGridLogger(): setLoggerClass(GridLogger)
null
null
null
What does this function do?
def _StartBabysitter(servers): import daemon from viewfinder.backend.prod import babysitter os.mkdir('logs') context = daemon.DaemonContext(working_directory=os.getcwd(), stdout=open(os.path.join(os.getcwd(), 'logs', 'STDOUT'), 'w+'), stderr=open(os.path.join(os.getcwd(), 'logs', 'STDERR'), 'w+'), umask=2) context...
null
null
null
Runs the babysitter as a daemon process.
pcsd
def Start Babysitter servers import daemon from viewfinder backend prod import babysitter os mkdir 'logs' context = daemon Daemon Context working directory=os getcwd stdout=open os path join os getcwd 'logs' 'STDOUT' 'w+' stderr=open os path join os getcwd 'logs' 'STDERR' 'w+' umask=2 context signal map = {signal SIGTE...
8546
def _StartBabysitter(servers): import daemon from viewfinder.backend.prod import babysitter os.mkdir('logs') context = daemon.DaemonContext(working_directory=os.getcwd(), stdout=open(os.path.join(os.getcwd(), 'logs', 'STDOUT'), 'w+'), stderr=open(os.path.join(os.getcwd(), 'logs', 'STDERR'), 'w+'), umask=2) context...
Runs the babysitter as a daemon process.
runs the babysitter as a daemon process .
Question: What does this function do? Code: def _StartBabysitter(servers): import daemon from viewfinder.backend.prod import babysitter os.mkdir('logs') context = daemon.DaemonContext(working_directory=os.getcwd(), stdout=open(os.path.join(os.getcwd(), 'logs', 'STDOUT'), 'w+'), stderr=open(os.path.join(os.getcwd...
null
null
null
What does this function do?
def random_ascii(length=20, ascii_only=False): return _join_chars(string.ascii_letters, length)
null
null
null
Generates a random name; useful for testing. Returns a string of the specified length containing only ASCII characters.
pcsd
def random ascii length=20 ascii only=False return join chars string ascii letters length
8556
def random_ascii(length=20, ascii_only=False): return _join_chars(string.ascii_letters, length)
Generates a random name; useful for testing. Returns a string of the specified length containing only ASCII characters.
generates a random name ; useful for testing .
Question: What does this function do? Code: def random_ascii(length=20, ascii_only=False): return _join_chars(string.ascii_letters, length)
null
null
null
What does this function do?
def _print_tree(node, level=0): if (type(node) is list): neon_logger.display(((' ' * level) + ', '.join((native_str(s) for s in node[0:3])))) if (len(node) > 3): _print_tree(node[3], (level + 1)) if (len(node) > 4): _print_tree(node[4], (level + 1)) else: neon_logger.display(((' ' * level) + nativ...
null
null
null
print tree with indentation
pcsd
def print tree node level=0 if type node is list neon logger display ' ' * level + ' ' join native str s for s in node[0 3] if len node > 3 print tree node[3] level + 1 if len node > 4 print tree node[4] level + 1 else neon logger display ' ' * level + native str node
8558
def _print_tree(node, level=0): if (type(node) is list): neon_logger.display(((' ' * level) + ', '.join((native_str(s) for s in node[0:3])))) if (len(node) > 3): _print_tree(node[3], (level + 1)) if (len(node) > 4): _print_tree(node[4], (level + 1)) else: neon_logger.display(((' ' * level) + nativ...
print tree with indentation
print tree with indentation
Question: What does this function do? Code: def _print_tree(node, level=0): if (type(node) is list): neon_logger.display(((' ' * level) + ', '.join((native_str(s) for s in node[0:3])))) if (len(node) > 3): _print_tree(node[3], (level + 1)) if (len(node) > 4): _print_tree(node[4], (level + 1)) else: ...
null
null
null
What does this function do?
def makeStack(element): layers = [] for child in element.childNodes: if (child.nodeType == child.ELEMENT_NODE): if (child.tagName == 'stack'): stack = makeStack(child) layers.append(stack) elif (child.tagName == 'layer'): layer = makeLayer(child) layers.append(layer) else: raise Excepti...
null
null
null
Build a Stack object from an XML element, deprecated for the next version.
pcsd
def make Stack element layers = [] for child in element child Nodes if child node Type == child ELEMENT NODE if child tag Name == 'stack' stack = make Stack child layers append stack elif child tag Name == 'layer' layer = make Layer child layers append layer else raise Exception 'Unknown element "%s"' % child tag Name ...
8567
def makeStack(element): layers = [] for child in element.childNodes: if (child.nodeType == child.ELEMENT_NODE): if (child.tagName == 'stack'): stack = makeStack(child) layers.append(stack) elif (child.tagName == 'layer'): layer = makeLayer(child) layers.append(layer) else: raise Excepti...
Build a Stack object from an XML element, deprecated for the next version.
build a stack object from an xml element , deprecated for the next version .
Question: What does this function do? Code: def makeStack(element): layers = [] for child in element.childNodes: if (child.nodeType == child.ELEMENT_NODE): if (child.tagName == 'stack'): stack = makeStack(child) layers.append(stack) elif (child.tagName == 'layer'): layer = makeLayer(child) ...
null
null
null
What does this function do?
def run(command): termAddress = AE.AECreateDesc(typeApplicationBundleID, 'com.apple.Terminal') theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress, kAutoGenerateReturnID, kAnyTransactionID) commandDesc = AE.AECreateDesc(typeChar, command) theEvent.AEPutParamDesc(kAECommandClass, commandDesc) tr...
null
null
null
Run a shell command in a new Terminal.app window.
pcsd
def run command term Address = AE AE Create Desc type Application Bundle ID 'com apple Terminal' the Event = AE AE Create Apple Event k AE Core Suite k AE Do Script term Address k Auto Generate Return ID k Any Transaction ID command Desc = AE AE Create Desc type Char command the Event AE Put Param Desc k AE Command Cla...
8569
def run(command): termAddress = AE.AECreateDesc(typeApplicationBundleID, 'com.apple.Terminal') theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress, kAutoGenerateReturnID, kAnyTransactionID) commandDesc = AE.AECreateDesc(typeChar, command) theEvent.AEPutParamDesc(kAECommandClass, commandDesc) tr...
Run a shell command in a new Terminal.app window.
run a shell command in a new terminal . app window .
Question: What does this function do? Code: def run(command): termAddress = AE.AECreateDesc(typeApplicationBundleID, 'com.apple.Terminal') theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress, kAutoGenerateReturnID, kAnyTransactionID) commandDesc = AE.AECreateDesc(typeChar, command) theEvent.A...
null
null
null
What does this function do?
def read_named_ranges(xml_source, workbook): named_ranges = [] root = fromstring(xml_source) names_root = root.find(QName('http://schemas.openxmlformats.org/spreadsheetml/2006/main', 'definedNames').text) if (names_root is not None): for name_node in names_root.getchildren(): range_name = name_node.get('name')...
null
null
null
Read named ranges, excluding poorly defined ranges.
pcsd
def read named ranges xml source workbook named ranges = [] root = fromstring xml source names root = root find Q Name 'http //schemas openxmlformats org/spreadsheetml/2006/main' 'defined Names' text if names root is not None for name node in names root getchildren range name = name node get 'name' if name node get 'hi...
8570
def read_named_ranges(xml_source, workbook): named_ranges = [] root = fromstring(xml_source) names_root = root.find(QName('http://schemas.openxmlformats.org/spreadsheetml/2006/main', 'definedNames').text) if (names_root is not None): for name_node in names_root.getchildren(): range_name = name_node.get('name')...
Read named ranges, excluding poorly defined ranges.
read named ranges , excluding poorly defined ranges .
Question: What does this function do? Code: def read_named_ranges(xml_source, workbook): named_ranges = [] root = fromstring(xml_source) names_root = root.find(QName('http://schemas.openxmlformats.org/spreadsheetml/2006/main', 'definedNames').text) if (names_root is not None): for name_node in names_root.getch...
null
null
null
What does this function do?
def get_info_filename(base_path): base_file = os.path.basename(base_path) return (CONF.libvirt.image_info_filename_pattern % {'image': base_file})
null
null
null
Construct a filename for storing additional information about a base image. Returns a filename.
pcsd
def get info filename base path base file = os path basename base path return CONF libvirt image info filename pattern % {'image' base file}
8575
def get_info_filename(base_path): base_file = os.path.basename(base_path) return (CONF.libvirt.image_info_filename_pattern % {'image': base_file})
Construct a filename for storing additional information about a base image. Returns a filename.
construct a filename for storing additional information about a base image .
Question: What does this function do? Code: def get_info_filename(base_path): base_file = os.path.basename(base_path) return (CONF.libvirt.image_info_filename_pattern % {'image': base_file})
null
null
null
What does this function do?
def buildNestedNetwork(): N = FeedForwardNetwork('outer') a = LinearLayer(1, name='a') b = LinearLayer(2, name='b') c = buildNetwork(2, 3, 1) c.name = 'inner' N.addInputModule(a) N.addModule(c) N.addOutputModule(b) N.addConnection(FullConnection(a, b)) N.addConnection(FullConnection(b, c)) N.sortModules() r...
null
null
null
build a nested network.
pcsd
def build Nested Network N = Feed Forward Network 'outer' a = Linear Layer 1 name='a' b = Linear Layer 2 name='b' c = build Network 2 3 1 c name = 'inner' N add Input Module a N add Module c N add Output Module b N add Connection Full Connection a b N add Connection Full Connection b c N sort Modules return N
8590
def buildNestedNetwork(): N = FeedForwardNetwork('outer') a = LinearLayer(1, name='a') b = LinearLayer(2, name='b') c = buildNetwork(2, 3, 1) c.name = 'inner' N.addInputModule(a) N.addModule(c) N.addOutputModule(b) N.addConnection(FullConnection(a, b)) N.addConnection(FullConnection(b, c)) N.sortModules() r...
build a nested network.
build a nested network .
Question: What does this function do? Code: def buildNestedNetwork(): N = FeedForwardNetwork('outer') a = LinearLayer(1, name='a') b = LinearLayer(2, name='b') c = buildNetwork(2, 3, 1) c.name = 'inner' N.addInputModule(a) N.addModule(c) N.addOutputModule(b) N.addConnection(FullConnection(a, b)) N.addConne...
null
null
null
What does this function do?
def _prepare(values, clip=True, out=None): if clip: return np.clip(values, 0.0, 1.0, out=out) elif (out is None): return np.array(values, copy=True) else: out[:] = np.asarray(values) return out
null
null
null
Prepare the data by optionally clipping and copying, and return the array that should be subsequently used for in-place calculations.
pcsd
def prepare values clip=True out=None if clip return np clip values 0 0 1 0 out=out elif out is None return np array values copy=True else out[ ] = np asarray values return out
8596
def _prepare(values, clip=True, out=None): if clip: return np.clip(values, 0.0, 1.0, out=out) elif (out is None): return np.array(values, copy=True) else: out[:] = np.asarray(values) return out
Prepare the data by optionally clipping and copying, and return the array that should be subsequently used for in-place calculations.
prepare the data by optionally clipping and copying , and return the array that should be subsequently used for in - place calculations .
Question: What does this function do? Code: def _prepare(values, clip=True, out=None): if clip: return np.clip(values, 0.0, 1.0, out=out) elif (out is None): return np.array(values, copy=True) else: out[:] = np.asarray(values) return out
null
null
null
What does this function do?
def layout_title(layout): for child in layout.children: if isinstance(child, Title): return u' '.join([node.data for node in get_nodes(child, Text)])
null
null
null
try to return the layout\'s title as string, return None if not found
pcsd
def layout title layout for child in layout children if isinstance child Title return u' ' join [node data for node in get nodes child Text ]
8597
def layout_title(layout): for child in layout.children: if isinstance(child, Title): return u' '.join([node.data for node in get_nodes(child, Text)])
try to return the layout\'s title as string, return None if not found
try to return the layouts title as string , return none if not found
Question: What does this function do? Code: def layout_title(layout): for child in layout.children: if isinstance(child, Title): return u' '.join([node.data for node in get_nodes(child, Text)])
null
null
null
What does this function do?
def morsel_to_cookie(morsel): expires = None if morsel['max-age']: expires = (time.time() + morsel['max-age']) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = (time.mktime(time.strptime(morsel['expires'], time_template)) - time.timezone) return create_cookie(comment=morsel['comme...
null
null
null
Convert a Morsel object into a Cookie containing the one k/v pair.
pcsd
def morsel to cookie morsel expires = None if morsel['max-age'] expires = time time + morsel['max-age'] elif morsel['expires'] time template = '%a %d-%b-%Y %H %M %S GMT' expires = time mktime time strptime morsel['expires'] time template - time timezone return create cookie comment=morsel['comment'] comment url=bool mo...
8607
def morsel_to_cookie(morsel): expires = None if morsel['max-age']: expires = (time.time() + morsel['max-age']) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = (time.mktime(time.strptime(morsel['expires'], time_template)) - time.timezone) return create_cookie(comment=morsel['comme...
Convert a Morsel object into a Cookie containing the one k/v pair.
convert a morsel object into a cookie containing the one k / v pair .
Question: What does this function do? Code: def morsel_to_cookie(morsel): expires = None if morsel['max-age']: expires = (time.time() + morsel['max-age']) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = (time.mktime(time.strptime(morsel['expires'], time_template)) - time.timezo...
null
null
null
What does this function do?
def petersen_graph(create_using=None): description = ['adjacencylist', 'Petersen Graph', 10, [[2, 5, 6], [1, 3, 7], [2, 4, 8], [3, 5, 9], [4, 1, 10], [1, 8, 9], [2, 9, 10], [3, 6, 10], [4, 6, 7], [5, 7, 8]]] G = make_small_undirected_graph(description, create_using) return G
null
null
null
Return the Petersen graph.
pcsd
def petersen graph create using=None description = ['adjacencylist' 'Petersen Graph' 10 [[2 5 6] [1 3 7] [2 4 8] [3 5 9] [4 1 10] [1 8 9] [2 9 10] [3 6 10] [4 6 7] [5 7 8]]] G = make small undirected graph description create using return G
8611
def petersen_graph(create_using=None): description = ['adjacencylist', 'Petersen Graph', 10, [[2, 5, 6], [1, 3, 7], [2, 4, 8], [3, 5, 9], [4, 1, 10], [1, 8, 9], [2, 9, 10], [3, 6, 10], [4, 6, 7], [5, 7, 8]]] G = make_small_undirected_graph(description, create_using) return G
Return the Petersen graph.
return the petersen graph .
Question: What does this function do? Code: def petersen_graph(create_using=None): description = ['adjacencylist', 'Petersen Graph', 10, [[2, 5, 6], [1, 3, 7], [2, 4, 8], [3, 5, 9], [4, 1, 10], [1, 8, 9], [2, 9, 10], [3, 6, 10], [4, 6, 7], [5, 7, 8]]] G = make_small_undirected_graph(description, create_using) ret...
null
null
null
What does this function do?
def to_progress_instance(progress): if callable(progress): return CallableRemoteProgress(progress) elif (progress is None): return RemoteProgress() else: return progress
null
null
null
Given the \'progress\' return a suitable object derived from RemoteProgress().
pcsd
def to progress instance progress if callable progress return Callable Remote Progress progress elif progress is None return Remote Progress else return progress
8620
def to_progress_instance(progress): if callable(progress): return CallableRemoteProgress(progress) elif (progress is None): return RemoteProgress() else: return progress
Given the \'progress\' return a suitable object derived from RemoteProgress().
given the progress return a suitable object derived from
Question: What does this function do? Code: def to_progress_instance(progress): if callable(progress): return CallableRemoteProgress(progress) elif (progress is None): return RemoteProgress() else: return progress
null
null
null
What does this function do?
def staff_org_site_json(): table = s3db.hrm_human_resource otable = s3db.org_organisation query = ((table.person_id == request.args[0]) & (table.organisation_id == otable.id)) records = db(query).select(table.site_id, otable.id, otable.name) response.headers['Content-Type'] = 'application/json' return records.jso...
null
null
null
Used by the Asset - Assign to Person page
pcsd
def staff org site json table = s3db hrm human resource otable = s3db org organisation query = table person id == request args[0] & table organisation id == otable id records = db query select table site id otable id otable name response headers['Content-Type'] = 'application/json' return records json
8621
def staff_org_site_json(): table = s3db.hrm_human_resource otable = s3db.org_organisation query = ((table.person_id == request.args[0]) & (table.organisation_id == otable.id)) records = db(query).select(table.site_id, otable.id, otable.name) response.headers['Content-Type'] = 'application/json' return records.jso...
Used by the Asset - Assign to Person page
used by the asset - assign to person page
Question: What does this function do? Code: def staff_org_site_json(): table = s3db.hrm_human_resource otable = s3db.org_organisation query = ((table.person_id == request.args[0]) & (table.organisation_id == otable.id)) records = db(query).select(table.site_id, otable.id, otable.name) response.headers['Content-...
null
null
null
What does this function do?
def _get_zone(gcdns, zone_name): available_zones = gcdns.iterate_zones() found_zone = None for zone in available_zones: if (zone.domain == zone_name): found_zone = zone break return found_zone
null
null
null
Gets the zone object for a given domain name.
pcsd
def get zone gcdns zone name available zones = gcdns iterate zones found zone = None for zone in available zones if zone domain == zone name found zone = zone break return found zone
8623
def _get_zone(gcdns, zone_name): available_zones = gcdns.iterate_zones() found_zone = None for zone in available_zones: if (zone.domain == zone_name): found_zone = zone break return found_zone
Gets the zone object for a given domain name.
gets the zone object for a given domain name .
Question: What does this function do? Code: def _get_zone(gcdns, zone_name): available_zones = gcdns.iterate_zones() found_zone = None for zone in available_zones: if (zone.domain == zone_name): found_zone = zone break return found_zone
null
null
null
What does this function do?
def points_for_interval(interval): range = time_range_by_interval[interval] interval = timedelta_by_name(interval) return (range.total_seconds() / interval.total_seconds())
null
null
null
Calculate the number of data points to render for a given interval.
pcsd
def points for interval interval range = time range by interval[interval] interval = timedelta by name interval return range total seconds / interval total seconds
8630
def points_for_interval(interval): range = time_range_by_interval[interval] interval = timedelta_by_name(interval) return (range.total_seconds() / interval.total_seconds())
Calculate the number of data points to render for a given interval.
calculate the number of data points to render for a given interval .
Question: What does this function do? Code: def points_for_interval(interval): range = time_range_by_interval[interval] interval = timedelta_by_name(interval) return (range.total_seconds() / interval.total_seconds())
null
null
null
What does this function do?
def filter_section(context, section): return False
null
null
null
Test Filter Section
pcsd
def filter section context section return False
8635
def filter_section(context, section): return False
Test Filter Section
test filter section
Question: What does this function do? Code: def filter_section(context, section): return False
null
null
null
What does this function do?
def isCommaSeparatedEmailList(field_data, all_data): for supposed_email in field_data.split(','): try: isValidEmail(supposed_email.strip(), '') except ValidationError: raise ValidationError, gettext('Enter valid e-mail addresses separated by commas.')
null
null
null
Checks that field_data is a string of e-mail addresses separated by commas. Blank field_data values will not throw a validation error, and whitespace is allowed around the commas.
pcsd
def is Comma Separated Email List field data all data for supposed email in field data split ' ' try is Valid Email supposed email strip '' except Validation Error raise Validation Error gettext 'Enter valid e-mail addresses separated by commas '
8639
def isCommaSeparatedEmailList(field_data, all_data): for supposed_email in field_data.split(','): try: isValidEmail(supposed_email.strip(), '') except ValidationError: raise ValidationError, gettext('Enter valid e-mail addresses separated by commas.')
Checks that field_data is a string of e-mail addresses separated by commas. Blank field_data values will not throw a validation error, and whitespace is allowed around the commas.
checks that field _ data is a string of e - mail addresses separated by commas .
Question: What does this function do? Code: def isCommaSeparatedEmailList(field_data, all_data): for supposed_email in field_data.split(','): try: isValidEmail(supposed_email.strip(), '') except ValidationError: raise ValidationError, gettext('Enter valid e-mail addresses separated by commas.')
null
null
null
What does this function do?
def checkFloat(s): try: float(s) return True except ValueError: return False
null
null
null
Check if input string is a float
pcsd
def check Float s try float s return True except Value Error return False
8641
def checkFloat(s): try: float(s) return True except ValueError: return False
Check if input string is a float
check if input string is a float
Question: What does this function do? Code: def checkFloat(s): try: float(s) return True except ValueError: return False
null
null
null
What does this function do?
def GetInfo(userName=None): if (userName is None): userName = win32api.GetUserName() print 'Dumping level 3 information about user' info = win32net.NetUserGetInfo(server, userName, 3) for (key, val) in info.items(): verbose(('%s=%s' % (key, val)))
null
null
null
Dumps level 3 information about the current user
pcsd
def Get Info user Name=None if user Name is None user Name = win32api Get User Name print 'Dumping level 3 information about user' info = win32net Net User Get Info server user Name 3 for key val in info items verbose '%s=%s' % key val
8649
def GetInfo(userName=None): if (userName is None): userName = win32api.GetUserName() print 'Dumping level 3 information about user' info = win32net.NetUserGetInfo(server, userName, 3) for (key, val) in info.items(): verbose(('%s=%s' % (key, val)))
Dumps level 3 information about the current user
dumps level 3 information about the current user
Question: What does this function do? Code: def GetInfo(userName=None): if (userName is None): userName = win32api.GetUserName() print 'Dumping level 3 information about user' info = win32net.NetUserGetInfo(server, userName, 3) for (key, val) in info.items(): verbose(('%s=%s' % (key, val)))
null
null
null
What does this function do?
@click.command(name='allocation') @click.option('--key', type=str, required=True, help='Node identification tag') @click.option('--value', type=str, required=True, help='Value associated with --key') @click.option('--allocation_type', type=str, help='Must be one of: require, include, or exclude') @click.option('--wait_...
null
null
null
Shard Routing Allocation
pcsd
@click command name='allocation' @click option '--key' type=str required=True help='Node identification tag' @click option '--value' type=str required=True help='Value associated with --key' @click option '--allocation type' type=str help='Must be one of require include or exclude' @click option '--wait for completion'...
8654
@click.command(name='allocation') @click.option('--key', type=str, required=True, help='Node identification tag') @click.option('--value', type=str, required=True, help='Value associated with --key') @click.option('--allocation_type', type=str, help='Must be one of: require, include, or exclude') @click.option('--wait_...
Shard Routing Allocation
shard routing allocation
Question: What does this function do? Code: @click.command(name='allocation') @click.option('--key', type=str, required=True, help='Node identification tag') @click.option('--value', type=str, required=True, help='Value associated with --key') @click.option('--allocation_type', type=str, help='Must be one of: requir...
null
null
null
What does this function do?
def RSI(ds, count, timeperiod=(- (2 ** 31))): return call_talib_with_ds(ds, count, talib.RSI, timeperiod)
null
null
null
Relative Strength Index
pcsd
def RSI ds count timeperiod= - 2 ** 31 return call talib with ds ds count talib RSI timeperiod
8656
def RSI(ds, count, timeperiod=(- (2 ** 31))): return call_talib_with_ds(ds, count, talib.RSI, timeperiod)
Relative Strength Index
relative strength index
Question: What does this function do? Code: def RSI(ds, count, timeperiod=(- (2 ** 31))): return call_talib_with_ds(ds, count, talib.RSI, timeperiod)
null
null
null
What does this function do?
def _FormatEta(eta_usec): eta = datetime.datetime.utcfromtimestamp(_UsecToSec(eta_usec)) return eta.strftime('%Y/%m/%d %H:%M:%S')
null
null
null
Formats a task ETA as a date string in UTC.
pcsd
def Format Eta eta usec eta = datetime datetime utcfromtimestamp Usec To Sec eta usec return eta strftime '%Y/%m/%d %H %M %S'
8657
def _FormatEta(eta_usec): eta = datetime.datetime.utcfromtimestamp(_UsecToSec(eta_usec)) return eta.strftime('%Y/%m/%d %H:%M:%S')
Formats a task ETA as a date string in UTC.
formats a task eta as a date string in utc .
Question: What does this function do? Code: def _FormatEta(eta_usec): eta = datetime.datetime.utcfromtimestamp(_UsecToSec(eta_usec)) return eta.strftime('%Y/%m/%d %H:%M:%S')
null
null
null
What does this function do?
def _detect_unboundedness(R): s = generate_unique_node() G = nx.DiGraph() G.add_nodes_from(R) inf = R.graph['inf'] f_inf = float('inf') for u in R: for (v, e) in R[u].items(): w = f_inf for (k, e) in e.items(): if (e['capacity'] == inf): w = min(w, e['weight']) if (w != f_inf): G.add_edge(...
null
null
null
Detect infinite-capacity negative cycles.
pcsd
def detect unboundedness R s = generate unique node G = nx Di Graph G add nodes from R inf = R graph['inf'] f inf = float 'inf' for u in R for v e in R[u] items w = f inf for k e in e items if e['capacity'] == inf w = min w e['weight'] if w != f inf G add edge u v weight=w if nx negative edge cycle G raise nx Network X...
8666
def _detect_unboundedness(R): s = generate_unique_node() G = nx.DiGraph() G.add_nodes_from(R) inf = R.graph['inf'] f_inf = float('inf') for u in R: for (v, e) in R[u].items(): w = f_inf for (k, e) in e.items(): if (e['capacity'] == inf): w = min(w, e['weight']) if (w != f_inf): G.add_edge(...
Detect infinite-capacity negative cycles.
detect infinite - capacity negative cycles .
Question: What does this function do? Code: def _detect_unboundedness(R): s = generate_unique_node() G = nx.DiGraph() G.add_nodes_from(R) inf = R.graph['inf'] f_inf = float('inf') for u in R: for (v, e) in R[u].items(): w = f_inf for (k, e) in e.items(): if (e['capacity'] == inf): w = min(w, e...
null
null
null
What does this function do?
def putProfileSetting(name, value): global settingsDictionary if ((name in settingsDictionary) and settingsDictionary[name].isProfile()): settingsDictionary[name].setValue(value)
null
null
null
Store a certain value in a profile setting.
pcsd
def put Profile Setting name value global settings Dictionary if name in settings Dictionary and settings Dictionary[name] is Profile settings Dictionary[name] set Value value
8667
def putProfileSetting(name, value): global settingsDictionary if ((name in settingsDictionary) and settingsDictionary[name].isProfile()): settingsDictionary[name].setValue(value)
Store a certain value in a profile setting.
store a certain value in a profile setting .
Question: What does this function do? Code: def putProfileSetting(name, value): global settingsDictionary if ((name in settingsDictionary) and settingsDictionary[name].isProfile()): settingsDictionary[name].setValue(value)
null
null
null
What does this function do?
@utils.arg('secgroup', metavar='<secgroup>', help=_('ID or name of security group.')) @deprecated_network def do_secgroup_list_rules(cs, args): secgroup = _get_secgroup(cs, args.secgroup) _print_secgroup_rules(secgroup.rules)
null
null
null
List rules for a security group.
pcsd
@utils arg 'secgroup' metavar='<secgroup>' help= 'ID or name of security group ' @deprecated network def do secgroup list rules cs args secgroup = get secgroup cs args secgroup print secgroup rules secgroup rules
8671
@utils.arg('secgroup', metavar='<secgroup>', help=_('ID or name of security group.')) @deprecated_network def do_secgroup_list_rules(cs, args): secgroup = _get_secgroup(cs, args.secgroup) _print_secgroup_rules(secgroup.rules)
List rules for a security group.
list rules for a security group .
Question: What does this function do? Code: @utils.arg('secgroup', metavar='<secgroup>', help=_('ID or name of security group.')) @deprecated_network def do_secgroup_list_rules(cs, args): secgroup = _get_secgroup(cs, args.secgroup) _print_secgroup_rules(secgroup.rules)
null
null
null
What does this function do?
@receiver(badge_was_awarded) def notify_award_recipient(sender, award, **kwargs): if (not settings.STAGE): send_award_notification.delay(award)
null
null
null
Notifies award recipient that he/she has an award!
pcsd
@receiver badge was awarded def notify award recipient sender award **kwargs if not settings STAGE send award notification delay award
8675
@receiver(badge_was_awarded) def notify_award_recipient(sender, award, **kwargs): if (not settings.STAGE): send_award_notification.delay(award)
Notifies award recipient that he/she has an award!
notifies award recipient that he / she has an award !
Question: What does this function do? Code: @receiver(badge_was_awarded) def notify_award_recipient(sender, award, **kwargs): if (not settings.STAGE): send_award_notification.delay(award)
null
null
null
What does this function do?
def main(): usage = '%s [-k] [-o output_file_path] [-i input_file_path] [-r scriptfile [args]]' parser = optparse.OptionParser(usage=(usage % sys.argv[0])) parser.allow_interspersed_args = False parser.add_option('-o', '--outfile', dest='outfile', help='Save calltree stats to <outfile>', default=None) parser.add_o...
null
null
null
Execute the converter using parameters provided on the command line
pcsd
def main usage = '%s [-k] [-o output file path] [-i input file path] [-r scriptfile [args]]' parser = optparse Option Parser usage= usage % sys argv[0] parser allow interspersed args = False parser add option '-o' '--outfile' dest='outfile' help='Save calltree stats to <outfile>' default=None parser add option '-i' '--...
8688
def main(): usage = '%s [-k] [-o output_file_path] [-i input_file_path] [-r scriptfile [args]]' parser = optparse.OptionParser(usage=(usage % sys.argv[0])) parser.allow_interspersed_args = False parser.add_option('-o', '--outfile', dest='outfile', help='Save calltree stats to <outfile>', default=None) parser.add_o...
Execute the converter using parameters provided on the command line
execute the converter using parameters provided on the command line
Question: What does this function do? Code: def main(): usage = '%s [-k] [-o output_file_path] [-i input_file_path] [-r scriptfile [args]]' parser = optparse.OptionParser(usage=(usage % sys.argv[0])) parser.allow_interspersed_args = False parser.add_option('-o', '--outfile', dest='outfile', help='Save calltree s...
null
null
null
What does this function do?
def verify_cert_chain(chain): cert_num = len(chain) x509_chain = [] for i in range(cert_num): x = x509.X509(bytearray(chain[i])) x509_chain.append(x) if (i == 0): x.check_date() elif (not x.check_ca()): raise BaseException('ERROR: Supplied CA Certificate Error') if (not (cert_num > 1)): raise BaseEx...
null
null
null
Verify a chain of certificates. The last certificate is the CA
pcsd
def verify cert chain chain cert num = len chain x509 chain = [] for i in range cert num x = x509 X509 bytearray chain[i] x509 chain append x if i == 0 x check date elif not x check ca raise Base Exception 'ERROR Supplied CA Certificate Error' if not cert num > 1 raise Base Exception 'ERROR CA Certificate Chain Not Pro...
8690
def verify_cert_chain(chain): cert_num = len(chain) x509_chain = [] for i in range(cert_num): x = x509.X509(bytearray(chain[i])) x509_chain.append(x) if (i == 0): x.check_date() elif (not x.check_ca()): raise BaseException('ERROR: Supplied CA Certificate Error') if (not (cert_num > 1)): raise BaseEx...
Verify a chain of certificates. The last certificate is the CA
verify a chain of certificates .
Question: What does this function do? Code: def verify_cert_chain(chain): cert_num = len(chain) x509_chain = [] for i in range(cert_num): x = x509.X509(bytearray(chain[i])) x509_chain.append(x) if (i == 0): x.check_date() elif (not x.check_ca()): raise BaseException('ERROR: Supplied CA Certificate E...