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 response_authenticate(): response = HttpResponse(status=401) response['WWW-Authenticate'] = 'Basic realm="Git"' return response
null
null
null
Returns 401 response with authenticate header.
pcsd
def response authenticate response = Http Response status=401 response['WWW-Authenticate'] = 'Basic realm="Git"' return response
10372
def response_authenticate(): response = HttpResponse(status=401) response['WWW-Authenticate'] = 'Basic realm="Git"' return response
Returns 401 response with authenticate header.
returns 401 response with authenticate header .
Question: What does this function do? Code: def response_authenticate(): response = HttpResponse(status=401) response['WWW-Authenticate'] = 'Basic realm="Git"' return response
null
null
null
What does this function do?
def _track_from_response(result, timeout): response = result['response'] status = response['track']['status'].lower() if (status == 'pending'): result = _wait_for_pending_track(response['track']['id'], timeout) response = result['response'] status = response['track']['status'].lower() if (not (status == 'comp...
null
null
null
This is the function that actually creates the track object
pcsd
def track from response result timeout response = result['response'] status = response['track']['status'] lower if status == 'pending' result = wait for pending track response['track']['id'] timeout response = result['response'] status = response['track']['status'] lower if not status == 'complete' track id = response[...
10378
def _track_from_response(result, timeout): response = result['response'] status = response['track']['status'].lower() if (status == 'pending'): result = _wait_for_pending_track(response['track']['id'], timeout) response = result['response'] status = response['track']['status'].lower() if (not (status == 'comp...
This is the function that actually creates the track object
this is the function that actually creates the track object
Question: What does this function do? Code: def _track_from_response(result, timeout): response = result['response'] status = response['track']['status'].lower() if (status == 'pending'): result = _wait_for_pending_track(response['track']['id'], timeout) response = result['response'] status = response['trac...
null
null
null
What does this function do?
def MigrateObjectsLabels(root_urn, obj_type, label_suffix=None, token=None): root = aff4.FACTORY.Create(root_urn, aff4.AFF4Volume, mode='r', token=token) children_urns = list(root.ListChildren()) if label_suffix: children_urns = [urn.Add(label_suffix) for urn in children_urns] print ('Found %d children.' % len(ch...
null
null
null
Migrates labels of object under given root (non-recursive).
pcsd
def Migrate Objects Labels root urn obj type label suffix=None token=None root = aff4 FACTORY Create root urn aff4 AFF4Volume mode='r' token=token children urns = list root List Children if label suffix children urns = [urn Add label suffix for urn in children urns] print 'Found %d children ' % len children urns update...
10386
def MigrateObjectsLabels(root_urn, obj_type, label_suffix=None, token=None): root = aff4.FACTORY.Create(root_urn, aff4.AFF4Volume, mode='r', token=token) children_urns = list(root.ListChildren()) if label_suffix: children_urns = [urn.Add(label_suffix) for urn in children_urns] print ('Found %d children.' % len(ch...
Migrates labels of object under given root (non-recursive).
migrates labels of object under given root .
Question: What does this function do? Code: def MigrateObjectsLabels(root_urn, obj_type, label_suffix=None, token=None): root = aff4.FACTORY.Create(root_urn, aff4.AFF4Volume, mode='r', token=token) children_urns = list(root.ListChildren()) if label_suffix: children_urns = [urn.Add(label_suffix) for urn in child...
null
null
null
What does this function do?
def send(message, subject, sender, recipients, host): msg = MIMEText(message) msg['Subject'] = subject msg['From'] = sender msg['To'] = ', '.join(recipients) dfr = sendmail(host, sender, recipients, msg.as_string()) def success(r): reactor.stop() def error(e): print(e) reactor.stop() dfr.addCallback(succe...
null
null
null
Send email to one or more addresses.
pcsd
def send message subject sender recipients host msg = MIME Text message msg['Subject'] = subject msg['From'] = sender msg['To'] = ' ' join recipients dfr = sendmail host sender recipients msg as string def success r reactor stop def error e print e reactor stop dfr add Callback success dfr add Errback error reactor run
10389
def send(message, subject, sender, recipients, host): msg = MIMEText(message) msg['Subject'] = subject msg['From'] = sender msg['To'] = ', '.join(recipients) dfr = sendmail(host, sender, recipients, msg.as_string()) def success(r): reactor.stop() def error(e): print(e) reactor.stop() dfr.addCallback(succe...
Send email to one or more addresses.
send email to one or more addresses .
Question: What does this function do? Code: def send(message, subject, sender, recipients, host): msg = MIMEText(message) msg['Subject'] = subject msg['From'] = sender msg['To'] = ', '.join(recipients) dfr = sendmail(host, sender, recipients, msg.as_string()) def success(r): reactor.stop() def error(e): p...
null
null
null
What does this function do?
def main(): argument_spec = dict(src=dict(type='path'), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block']), multilin...
null
null
null
main entry point for module execution
pcsd
def main argument spec = dict src=dict type='path' lines=dict aliases=['commands'] type='list' parents=dict type='list' before=dict type='list' after=dict type='list' match=dict default='line' choices=['line' 'strict' 'exact' 'none'] replace=dict default='line' choices=['line' 'block'] multiline delimiter=dict default=...
10398
def main(): argument_spec = dict(src=dict(type='path'), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block']), multilin...
main entry point for module execution
main entry point for module execution
Question: What does this function do? Code: def main(): argument_spec = dict(src=dict(type='path'), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(defau...
null
null
null
What does this function do?
def analyze_file(filename): bps = 0 seqs = 0 input_iter = screed.open(filename) for record in input_iter: if ((seqs % 100000) == 0): print('...', filename, seqs, file=sys.stderr) bps += len(record.sequence) seqs += 1 return (bps, seqs)
null
null
null
Run over the given file and count base pairs and sequences.
pcsd
def analyze file filename bps = 0 seqs = 0 input iter = screed open filename for record in input iter if seqs % 100000 == 0 print ' ' filename seqs file=sys stderr bps += len record sequence seqs += 1 return bps seqs
10405
def analyze_file(filename): bps = 0 seqs = 0 input_iter = screed.open(filename) for record in input_iter: if ((seqs % 100000) == 0): print('...', filename, seqs, file=sys.stderr) bps += len(record.sequence) seqs += 1 return (bps, seqs)
Run over the given file and count base pairs and sequences.
run over the given file and count base pairs and sequences .
Question: What does this function do? Code: def analyze_file(filename): bps = 0 seqs = 0 input_iter = screed.open(filename) for record in input_iter: if ((seqs % 100000) == 0): print('...', filename, seqs, file=sys.stderr) bps += len(record.sequence) seqs += 1 return (bps, seqs)
null
null
null
What does this function do?
def _get_linux_adapter_name_and_ip_address(mac_address): network_adapters = _get_linux_network_adapters() return _get_adapter_name_and_ip_address(network_adapters, mac_address)
null
null
null
Get Linux network adapter name.
pcsd
def get linux adapter name and ip address mac address network adapters = get linux network adapters return get adapter name and ip address network adapters mac address
10408
def _get_linux_adapter_name_and_ip_address(mac_address): network_adapters = _get_linux_network_adapters() return _get_adapter_name_and_ip_address(network_adapters, mac_address)
Get Linux network adapter name.
get linux network adapter name .
Question: What does this function do? Code: def _get_linux_adapter_name_and_ip_address(mac_address): network_adapters = _get_linux_network_adapters() return _get_adapter_name_and_ip_address(network_adapters, mac_address)
null
null
null
What does this function do?
def _router_default(): router = Storage(default_application='init', applications='ALL', default_controller='default', controllers='DEFAULT', default_function='index', functions=dict(), default_language=None, languages=None, root_static=['favicon.ico', 'robots.txt'], map_static=None, domains=None, exclusive_domain=Fals...
null
null
null
Returns new copy of default base router
pcsd
def router default router = Storage default application='init' applications='ALL' default controller='default' controllers='DEFAULT' default function='index' functions=dict default language=None languages=None root static=['favicon ico' 'robots txt'] map static=None domains=None exclusive domain=False map hyphen=False ...
10412
def _router_default(): router = Storage(default_application='init', applications='ALL', default_controller='default', controllers='DEFAULT', default_function='index', functions=dict(), default_language=None, languages=None, root_static=['favicon.ico', 'robots.txt'], map_static=None, domains=None, exclusive_domain=Fals...
Returns new copy of default base router
returns new copy of default base router
Question: What does this function do? Code: def _router_default(): router = Storage(default_application='init', applications='ALL', default_controller='default', controllers='DEFAULT', default_function='index', functions=dict(), default_language=None, languages=None, root_static=['favicon.ico', 'robots.txt'], map_s...
null
null
null
What does this function do?
@register.filter def sort_by(items, attr): def key_func(item): try: return getattr(item, attr) except AttributeError: try: return item[attr] except TypeError: getattr(item, attr) return sorted(items, key=key_func)
null
null
null
General sort filter - sorts by either attribute or key.
pcsd
@register filter def sort by items attr def key func item try return getattr item attr except Attribute Error try return item[attr] except Type Error getattr item attr return sorted items key=key func
10446
@register.filter def sort_by(items, attr): def key_func(item): try: return getattr(item, attr) except AttributeError: try: return item[attr] except TypeError: getattr(item, attr) return sorted(items, key=key_func)
General sort filter - sorts by either attribute or key.
general sort filter - sorts by either attribute or key .
Question: What does this function do? Code: @register.filter def sort_by(items, attr): def key_func(item): try: return getattr(item, attr) except AttributeError: try: return item[attr] except TypeError: getattr(item, attr) return sorted(items, key=key_func)
null
null
null
What does this function do?
def getSliceElementZ(sliceElement): idValue = sliceElement.attributeDictionary['id'].strip() return float(idValue[len('z:'):].strip())
null
null
null
Get the slice element z.
pcsd
def get Slice Element Z slice Element id Value = slice Element attribute Dictionary['id'] strip return float id Value[len 'z ' ] strip
10450
def getSliceElementZ(sliceElement): idValue = sliceElement.attributeDictionary['id'].strip() return float(idValue[len('z:'):].strip())
Get the slice element z.
get the slice element z .
Question: What does this function do? Code: def getSliceElementZ(sliceElement): idValue = sliceElement.attributeDictionary['id'].strip() return float(idValue[len('z:'):].strip())
null
null
null
What does this function do?
def get_page_info(path, app, basepath=None, app_path=None, fname=None): if (not fname): fname = os.path.basename(path) if (not app_path): app_path = frappe.get_app_path(app) if (not basepath): basepath = os.path.dirname(path) (page_name, extn) = fname.rsplit(u'.', 1) page_info = frappe._dict() page_info.bas...
null
null
null
Load page info
pcsd
def get page info path app basepath=None app path=None fname=None if not fname fname = os path basename path if not app path app path = frappe get app path app if not basepath basepath = os path dirname path page name extn = fname rsplit u' ' 1 page info = frappe dict page info basename = page name if extn in u'html' u...
10453
def get_page_info(path, app, basepath=None, app_path=None, fname=None): if (not fname): fname = os.path.basename(path) if (not app_path): app_path = frappe.get_app_path(app) if (not basepath): basepath = os.path.dirname(path) (page_name, extn) = fname.rsplit(u'.', 1) page_info = frappe._dict() page_info.bas...
Load page info
load page info
Question: What does this function do? Code: def get_page_info(path, app, basepath=None, app_path=None, fname=None): if (not fname): fname = os.path.basename(path) if (not app_path): app_path = frappe.get_app_path(app) if (not basepath): basepath = os.path.dirname(path) (page_name, extn) = fname.rsplit(u'.'...
null
null
null
What does this function do?
def _module_to_dict(module, omittable=(lambda k: k.startswith('_'))): return dict([(k, repr(v)) for (k, v) in module.__dict__.items() if (not omittable(k))])
null
null
null
Converts a module namespace to a Python dictionary. Used by get_settings_diff.
pcsd
def module to dict module omittable= lambda k k startswith ' ' return dict [ k repr v for k v in module dict items if not omittable k ]
10454
def _module_to_dict(module, omittable=(lambda k: k.startswith('_'))): return dict([(k, repr(v)) for (k, v) in module.__dict__.items() if (not omittable(k))])
Converts a module namespace to a Python dictionary. Used by get_settings_diff.
converts a module namespace to a python dictionary .
Question: What does this function do? Code: def _module_to_dict(module, omittable=(lambda k: k.startswith('_'))): return dict([(k, repr(v)) for (k, v) in module.__dict__.items() if (not omittable(k))])
null
null
null
What does this function do?
def can_delete(cc_content, context): return _is_author_or_privileged(cc_content, context)
null
null
null
Return True if the requester can delete the given content, False otherwise
pcsd
def can delete cc content context return is author or privileged cc content context
10456
def can_delete(cc_content, context): return _is_author_or_privileged(cc_content, context)
Return True if the requester can delete the given content, False otherwise
return true if the requester can delete the given content , false otherwise
Question: What does this function do? Code: def can_delete(cc_content, context): return _is_author_or_privileged(cc_content, context)
null
null
null
What does this function do?
@skip('silverlight') def test_iteration_no_mutation_bad_hash(): import random class c(object, ): def __hash__(self): return int((random.random() * 200)) l = [c() for i in xrange(1000)] b = set(l) for x in b: pass
null
null
null
create a set w/ objects with a bad hash and enumerate through it. No exceptions should be thrown
pcsd
@skip 'silverlight' def test iteration no mutation bad hash import random class c object def hash self return int random random * 200 l = [c for i in xrange 1000 ] b = set l for x in b pass
10461
@skip('silverlight') def test_iteration_no_mutation_bad_hash(): import random class c(object, ): def __hash__(self): return int((random.random() * 200)) l = [c() for i in xrange(1000)] b = set(l) for x in b: pass
create a set w/ objects with a bad hash and enumerate through it. No exceptions should be thrown
create a set w / objects with a bad hash and enumerate through it .
Question: What does this function do? Code: @skip('silverlight') def test_iteration_no_mutation_bad_hash(): import random class c(object, ): def __hash__(self): return int((random.random() * 200)) l = [c() for i in xrange(1000)] b = set(l) for x in b: pass
null
null
null
What does this function do?
def get_values_of_matching_keys(pattern_dict, user_name): ret = [] for expr in pattern_dict: if expr_match(user_name, expr): ret.extend(pattern_dict[expr]) return ret
null
null
null
Check a whitelist and/or blacklist to see if the value matches it.
pcsd
def get values of matching keys pattern dict user name ret = [] for expr in pattern dict if expr match user name expr ret extend pattern dict[expr] return ret
10463
def get_values_of_matching_keys(pattern_dict, user_name): ret = [] for expr in pattern_dict: if expr_match(user_name, expr): ret.extend(pattern_dict[expr]) return ret
Check a whitelist and/or blacklist to see if the value matches it.
check a whitelist and / or blacklist to see if the value matches it .
Question: What does this function do? Code: def get_values_of_matching_keys(pattern_dict, user_name): ret = [] for expr in pattern_dict: if expr_match(user_name, expr): ret.extend(pattern_dict[expr]) return ret
null
null
null
What does this function do?
def asset_controller(): s3db = current.s3db s3 = current.response.s3 def prep(r): current.s3db.gis_location_filter(r) if (r.component_name == 'log'): asset_log_prep(r) return True s3.prep = prep def import_prep(data): '\n Flag that this is an Import (to distinguish from Sync)\n @To...
null
null
null
RESTful CRUD controller
pcsd
def asset controller s3db = current s3db s3 = current response s3 def prep r current s3db gis location filter r if r component name == 'log' asset log prep r return True s3 prep = prep def import prep data ' Flag that this is an Import to distinguish from Sync @To Do Find Person records from their email addresses ' cur...
10472
def asset_controller(): s3db = current.s3db s3 = current.response.s3 def prep(r): current.s3db.gis_location_filter(r) if (r.component_name == 'log'): asset_log_prep(r) return True s3.prep = prep def import_prep(data): '\n Flag that this is an Import (to distinguish from Sync)\n @To...
RESTful CRUD controller
restful crud controller
Question: What does this function do? Code: def asset_controller(): s3db = current.s3db s3 = current.response.s3 def prep(r): current.s3db.gis_location_filter(r) if (r.component_name == 'log'): asset_log_prep(r) return True s3.prep = prep def import_prep(data): '\n Flag that this is an Imp...
null
null
null
What does this function do?
def _getitem_array1d(context, builder, arrayty, array, idx, wraparound): ptr = cgutils.get_item_pointer(builder, arrayty, array, [idx], wraparound=wraparound) return load_item(context, builder, arrayty, ptr)
null
null
null
Look up and return an element from a 1D array.
pcsd
def getitem array1d context builder arrayty array idx wraparound ptr = cgutils get item pointer builder arrayty array [idx] wraparound=wraparound return load item context builder arrayty ptr
10473
def _getitem_array1d(context, builder, arrayty, array, idx, wraparound): ptr = cgutils.get_item_pointer(builder, arrayty, array, [idx], wraparound=wraparound) return load_item(context, builder, arrayty, ptr)
Look up and return an element from a 1D array.
look up and return an element from a 1d array .
Question: What does this function do? Code: def _getitem_array1d(context, builder, arrayty, array, idx, wraparound): ptr = cgutils.get_item_pointer(builder, arrayty, array, [idx], wraparound=wraparound) return load_item(context, builder, arrayty, ptr)
null
null
null
What does this function do?
def get_repository_dict(url, repository_dict): error_message = '' if (not isinstance(repository_dict, dict)): error_message = ('Invalid repository_dict received: %s' % str(repository_dict)) return (None, error_message) repository_id = repository_dict.get('repository_id', None) if (repository_id is None): erro...
null
null
null
Send a request to the Tool Shed to get additional information about the repository defined by the received repository_dict. Add the information to the repository_dict and return it.
pcsd
def get repository dict url repository dict error message = '' if not isinstance repository dict dict error message = 'Invalid repository dict received %s' % str repository dict return None error message repository id = repository dict get 'repository id' None if repository id is None error message = 'Invalid repositor...
10478
def get_repository_dict(url, repository_dict): error_message = '' if (not isinstance(repository_dict, dict)): error_message = ('Invalid repository_dict received: %s' % str(repository_dict)) return (None, error_message) repository_id = repository_dict.get('repository_id', None) if (repository_id is None): erro...
Send a request to the Tool Shed to get additional information about the repository defined by the received repository_dict. Add the information to the repository_dict and return it.
send a request to the tool shed to get additional information about the repository defined by the received repository _ dict .
Question: What does this function do? Code: def get_repository_dict(url, repository_dict): error_message = '' if (not isinstance(repository_dict, dict)): error_message = ('Invalid repository_dict received: %s' % str(repository_dict)) return (None, error_message) repository_id = repository_dict.get('repository...
null
null
null
What does this function do?
def parse_cookie(value): if (not value): return None return value
null
null
null
Parses and verifies a cookie value from set_cookie
pcsd
def parse cookie value if not value return None return value
10481
def parse_cookie(value): if (not value): return None return value
Parses and verifies a cookie value from set_cookie
parses and verifies a cookie value from set _ cookie
Question: What does this function do? Code: def parse_cookie(value): if (not value): return None return value
null
null
null
What does this function do?
def post_download(project, filename, name=None, description=''): if (name is None): name = os.path.basename(filename) with open(filename, 'rb') as f: filedata = f.read() url = 'https://api.github.com/repos/{project}/downloads'.format(project=project) payload = json.dumps(dict(name=name, size=len(filedata), desc...
null
null
null
Upload a file to the GitHub downloads area
pcsd
def post download project filename name=None description='' if name is None name = os path basename filename with open filename 'rb' as f filedata = f read url = 'https //api github com/repos/{project}/downloads' format project=project payload = json dumps dict name=name size=len filedata description=description respon...
10488
def post_download(project, filename, name=None, description=''): if (name is None): name = os.path.basename(filename) with open(filename, 'rb') as f: filedata = f.read() url = 'https://api.github.com/repos/{project}/downloads'.format(project=project) payload = json.dumps(dict(name=name, size=len(filedata), desc...
Upload a file to the GitHub downloads area
upload a file to the github downloads area
Question: What does this function do? Code: def post_download(project, filename, name=None, description=''): if (name is None): name = os.path.basename(filename) with open(filename, 'rb') as f: filedata = f.read() url = 'https://api.github.com/repos/{project}/downloads'.format(project=project) payload = json...
null
null
null
What does this function do?
def plainpager(text): sys.stdout.write(plain(text))
null
null
null
Simply print unformatted text. This is the ultimate fallback.
pcsd
def plainpager text sys stdout write plain text
10496
def plainpager(text): sys.stdout.write(plain(text))
Simply print unformatted text. This is the ultimate fallback.
simply print unformatted text .
Question: What does this function do? Code: def plainpager(text): sys.stdout.write(plain(text))
null
null
null
What does this function do?
@task def test_module(ctx, module=None): import pytest args = ['-s'] modules = ([module] if isinstance(module, basestring) else module) args.extend(modules) retcode = pytest.main(args) sys.exit(retcode)
null
null
null
Helper for running tests.
pcsd
@task def test module ctx module=None import pytest args = ['-s'] modules = [module] if isinstance module basestring else module args extend modules retcode = pytest main args sys exit retcode
10497
@task def test_module(ctx, module=None): import pytest args = ['-s'] modules = ([module] if isinstance(module, basestring) else module) args.extend(modules) retcode = pytest.main(args) sys.exit(retcode)
Helper for running tests.
helper for running tests .
Question: What does this function do? Code: @task def test_module(ctx, module=None): import pytest args = ['-s'] modules = ([module] if isinstance(module, basestring) else module) args.extend(modules) retcode = pytest.main(args) sys.exit(retcode)
null
null
null
What does this function do?
def _generative(*assertions): @util.decorator def generate(fn, *args, **kw): self = args[0]._clone() for assertion in assertions: assertion(self, fn.__name__) fn(self, *args[1:], **kw) return self return generate
null
null
null
Mark a method as generative, e.g. method-chained.
pcsd
def generative *assertions @util decorator def generate fn *args **kw self = args[0] clone for assertion in assertions assertion self fn name fn self *args[1 ] **kw return self return generate
10500
def _generative(*assertions): @util.decorator def generate(fn, *args, **kw): self = args[0]._clone() for assertion in assertions: assertion(self, fn.__name__) fn(self, *args[1:], **kw) return self return generate
Mark a method as generative, e.g. method-chained.
mark a method as generative , e . g . method - chained .
Question: What does this function do? Code: def _generative(*assertions): @util.decorator def generate(fn, *args, **kw): self = args[0]._clone() for assertion in assertions: assertion(self, fn.__name__) fn(self, *args[1:], **kw) return self return generate
null
null
null
What does this function do?
def _preprocess_widget(widget, name): module_name = widget['module_name'] import_name = (module_name + '.views') module_views = __import__(import_name, fromlist=[str(module_name)]) if hasattr(module_views, name): if ('title' not in widget): widget['title'] = getattr(module_views, name).__doc__ widget = copy....
null
null
null
Populates widget with missing fields
pcsd
def preprocess widget widget name module name = widget['module name'] import name = module name + ' views' module views = import import name fromlist=[str module name ] if hasattr module views name if 'title' not in widget widget['title'] = getattr module views name doc widget = copy deepcopy widget if 'view' not in wi...
10501
def _preprocess_widget(widget, name): module_name = widget['module_name'] import_name = (module_name + '.views') module_views = __import__(import_name, fromlist=[str(module_name)]) if hasattr(module_views, name): if ('title' not in widget): widget['title'] = getattr(module_views, name).__doc__ widget = copy....
Populates widget with missing fields
populates widget with missing fields
Question: What does this function do? Code: def _preprocess_widget(widget, name): module_name = widget['module_name'] import_name = (module_name + '.views') module_views = __import__(import_name, fromlist=[str(module_name)]) if hasattr(module_views, name): if ('title' not in widget): widget['title'] = getat...
null
null
null
What does this function do?
def helpModule(module): t = module.split('.') importName = ((('from ' + '.'.join(t[:(-1)])) + ' import ') + t[(-1)]) exec importName moduleName = t[(-1)] functions = [locals()[moduleName].__dict__.get(a) for a in dir(locals()[moduleName]) if isinstance(locals()[moduleName].__dict__.get(a), types.FunctionType)] fo...
null
null
null
Print the first text chunk for each established method in a module. module: module to write output from, format "folder.folder.module"
pcsd
def help Module module t = module split ' ' import Name = 'from ' + ' ' join t[ -1 ] + ' import ' + t[ -1 ] exec import Name module Name = t[ -1 ] functions = [locals [module Name] dict get a for a in dir locals [module Name] if isinstance locals [module Name] dict get a types Function Type ] for function in functions ...
10503
def helpModule(module): t = module.split('.') importName = ((('from ' + '.'.join(t[:(-1)])) + ' import ') + t[(-1)]) exec importName moduleName = t[(-1)] functions = [locals()[moduleName].__dict__.get(a) for a in dir(locals()[moduleName]) if isinstance(locals()[moduleName].__dict__.get(a), types.FunctionType)] fo...
Print the first text chunk for each established method in a module. module: module to write output from, format "folder.folder.module"
print the first text chunk for each established method in a module .
Question: What does this function do? Code: def helpModule(module): t = module.split('.') importName = ((('from ' + '.'.join(t[:(-1)])) + ' import ') + t[(-1)]) exec importName moduleName = t[(-1)] functions = [locals()[moduleName].__dict__.get(a) for a in dir(locals()[moduleName]) if isinstance(locals()[module...
null
null
null
What does this function do?
def is_abstract(node): return ABSTRACT.match(node.name)
null
null
null
return true if the given class node correspond to an abstract class definition
pcsd
def is abstract node return ABSTRACT match node name
10506
def is_abstract(node): return ABSTRACT.match(node.name)
return true if the given class node correspond to an abstract class definition
return true if the given class node correspond to an abstract class definition
Question: What does this function do? Code: def is_abstract(node): return ABSTRACT.match(node.name)
null
null
null
What does this function do?
def _get_server_status_code(url): (host, path, params, query) = urlparse.urlparse(url)[1:5] try: conn = httplib.HTTPConnection(host) conn.request('HEAD', ((path + '?') + query)) return conn.getresponse().status except StandardError: return None
null
null
null
Download just the header of a URL and return the server\'s status code.
pcsd
def get server status code url host path params query = urlparse urlparse url [1 5] try conn = httplib HTTP Connection host conn request 'HEAD' path + '?' + query return conn getresponse status except Standard Error return None
10519
def _get_server_status_code(url): (host, path, params, query) = urlparse.urlparse(url)[1:5] try: conn = httplib.HTTPConnection(host) conn.request('HEAD', ((path + '?') + query)) return conn.getresponse().status except StandardError: return None
Download just the header of a URL and return the server\'s status code.
download just the header of a url and return the servers status code .
Question: What does this function do? Code: def _get_server_status_code(url): (host, path, params, query) = urlparse.urlparse(url)[1:5] try: conn = httplib.HTTPConnection(host) conn.request('HEAD', ((path + '?') + query)) return conn.getresponse().status except StandardError: return None
null
null
null
What does this function do?
def get_recipients(doc, fetched_from_email_account=False): recipients = split_emails(doc.recipients) if recipients: recipients = filter_email_list(doc, recipients, []) return recipients
null
null
null
Build a list of email addresses for To
pcsd
def get recipients doc fetched from email account=False recipients = split emails doc recipients if recipients recipients = filter email list doc recipients [] return recipients
10520
def get_recipients(doc, fetched_from_email_account=False): recipients = split_emails(doc.recipients) if recipients: recipients = filter_email_list(doc, recipients, []) return recipients
Build a list of email addresses for To
build a list of email addresses for to
Question: What does this function do? Code: def get_recipients(doc, fetched_from_email_account=False): recipients = split_emails(doc.recipients) if recipients: recipients = filter_email_list(doc, recipients, []) return recipients
null
null
null
What does this function do?
def get_safe_settings(): settings_dict = {} for k in dir(settings): if k.isupper(): settings_dict[k] = cleanse_setting(k, getattr(settings, k)) return settings_dict
null
null
null
Returns a dictionary of the settings module, with sensitive settings blurred out.
pcsd
def get safe settings settings dict = {} for k in dir settings if k isupper settings dict[k] = cleanse setting k getattr settings k return settings dict
10524
def get_safe_settings(): settings_dict = {} for k in dir(settings): if k.isupper(): settings_dict[k] = cleanse_setting(k, getattr(settings, k)) return settings_dict
Returns a dictionary of the settings module, with sensitive settings blurred out.
returns a dictionary of the settings module , with sensitive settings blurred out .
Question: What does this function do? Code: def get_safe_settings(): settings_dict = {} for k in dir(settings): if k.isupper(): settings_dict[k] = cleanse_setting(k, getattr(settings, k)) return settings_dict
null
null
null
What does this function do?
@utils.service_type('monitor') def do_extra_specs_list(cs, args): vtypes = cs.monitor_types.list() _print_type_and_extra_specs_list(vtypes)
null
null
null
Print a list of current \'monitor types and extra specs\' (Admin Only).
pcsd
@utils service type 'monitor' def do extra specs list cs args vtypes = cs monitor types list print type and extra specs list vtypes
10532
@utils.service_type('monitor') def do_extra_specs_list(cs, args): vtypes = cs.monitor_types.list() _print_type_and_extra_specs_list(vtypes)
Print a list of current \'monitor types and extra specs\' (Admin Only).
print a list of current monitor types and extra specs .
Question: What does this function do? Code: @utils.service_type('monitor') def do_extra_specs_list(cs, args): vtypes = cs.monitor_types.list() _print_type_and_extra_specs_list(vtypes)
null
null
null
What does this function do?
@require_POST @login_required def watch_ready(request, product=None): if (request.LANGUAGE_CODE != settings.WIKI_DEFAULT_LANGUAGE): raise Http404 kwargs = {} if (product is not None): kwargs['product'] = product ReadyRevisionEvent.notify(request.user, **kwargs) statsd.incr('wiki.watches.ready') return HttpRes...
null
null
null
Start watching ready-for-l10n revisions for given product.
pcsd
@require POST @login required def watch ready request product=None if request LANGUAGE CODE != settings WIKI DEFAULT LANGUAGE raise Http404 kwargs = {} if product is not None kwargs['product'] = product Ready Revision Event notify request user **kwargs statsd incr 'wiki watches ready' return Http Response
10536
@require_POST @login_required def watch_ready(request, product=None): if (request.LANGUAGE_CODE != settings.WIKI_DEFAULT_LANGUAGE): raise Http404 kwargs = {} if (product is not None): kwargs['product'] = product ReadyRevisionEvent.notify(request.user, **kwargs) statsd.incr('wiki.watches.ready') return HttpRes...
Start watching ready-for-l10n revisions for given product.
start watching ready - for - l10n revisions for given product .
Question: What does this function do? Code: @require_POST @login_required def watch_ready(request, product=None): if (request.LANGUAGE_CODE != settings.WIKI_DEFAULT_LANGUAGE): raise Http404 kwargs = {} if (product is not None): kwargs['product'] = product ReadyRevisionEvent.notify(request.user, **kwargs) st...
null
null
null
What does this function do?
@pytest.mark.parametrize('parallel', [True, False]) def test_comment(parallel, read_basic): table = read_basic('# comment\nA B C\n # another comment\n1 2 3\n4 5 6', parallel=parallel) expected = Table([[1, 4], [2, 5], [3, 6]], names=('A', 'B', 'C')) assert_table_equal(table, expected)
null
null
null
Make sure that line comments are ignored by the C reader.
pcsd
@pytest mark parametrize 'parallel' [True False] def test comment parallel read basic table = read basic '# comment A B C # another comment 1 2 3 4 5 6' parallel=parallel expected = Table [[1 4] [2 5] [3 6]] names= 'A' 'B' 'C' assert table equal table expected
10538
@pytest.mark.parametrize('parallel', [True, False]) def test_comment(parallel, read_basic): table = read_basic('# comment\nA B C\n # another comment\n1 2 3\n4 5 6', parallel=parallel) expected = Table([[1, 4], [2, 5], [3, 6]], names=('A', 'B', 'C')) assert_table_equal(table, expected)
Make sure that line comments are ignored by the C reader.
make sure that line comments are ignored by the c reader .
Question: What does this function do? Code: @pytest.mark.parametrize('parallel', [True, False]) def test_comment(parallel, read_basic): table = read_basic('# comment\nA B C\n # another comment\n1 2 3\n4 5 6', parallel=parallel) expected = Table([[1, 4], [2, 5], [3, 6]], names=('A', 'B', 'C')) assert_table_equal(t...
null
null
null
What does this function do?
@pytest.mark.django_db def test_root_view_permissions(po_directory, nobody, default, admin, view, no_projects, no_permission_sets, project_foo, project_bar, root): ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username='foo') bar_user = UserFactory.create(username='bar') _require...
null
null
null
Tests user-accessible projects with view permissions at the root.
pcsd
@pytest mark django db def test root view permissions po directory nobody default admin view no projects no permission sets project foo project bar root ALL PROJECTS = [project foo code project bar code] foo user = User Factory create username='foo' bar user = User Factory create username='bar' require permission set b...
10540
@pytest.mark.django_db def test_root_view_permissions(po_directory, nobody, default, admin, view, no_projects, no_permission_sets, project_foo, project_bar, root): ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username='foo') bar_user = UserFactory.create(username='bar') _require...
Tests user-accessible projects with view permissions at the root.
tests user - accessible projects with view permissions at the root .
Question: What does this function do? Code: @pytest.mark.django_db def test_root_view_permissions(po_directory, nobody, default, admin, view, no_projects, no_permission_sets, project_foo, project_bar, root): ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username='foo') bar_user...
null
null
null
What does this function do?
def activity_funding(): return s3_rest_controller()
null
null
null
Activity Funding Proposals: RESTful CRUD Controller
pcsd
def activity funding return s3 rest controller
10550
def activity_funding(): return s3_rest_controller()
Activity Funding Proposals: RESTful CRUD Controller
activity funding proposals : restful crud controller
Question: What does this function do? Code: def activity_funding(): return s3_rest_controller()
null
null
null
What does this function do?
def _dict_reorder(rep, gens, new_gens): gens = list(gens) monoms = rep.keys() coeffs = rep.values() new_monoms = [[] for _ in range(len(rep))] used_indices = set() for gen in new_gens: try: j = gens.index(gen) used_indices.add(j) for (M, new_M) in zip(monoms, new_monoms): new_M.append(M[j]) excep...
null
null
null
Reorder levels using dict representation.
pcsd
def dict reorder rep gens new gens gens = list gens monoms = rep keys coeffs = rep values new monoms = [[] for in range len rep ] used indices = set for gen in new gens try j = gens index gen used indices add j for M new M in zip monoms new monoms new M append M[j] except Value Error for new M in new monoms new M appen...
10552
def _dict_reorder(rep, gens, new_gens): gens = list(gens) monoms = rep.keys() coeffs = rep.values() new_monoms = [[] for _ in range(len(rep))] used_indices = set() for gen in new_gens: try: j = gens.index(gen) used_indices.add(j) for (M, new_M) in zip(monoms, new_monoms): new_M.append(M[j]) excep...
Reorder levels using dict representation.
reorder levels using dict representation .
Question: What does this function do? Code: def _dict_reorder(rep, gens, new_gens): gens = list(gens) monoms = rep.keys() coeffs = rep.values() new_monoms = [[] for _ in range(len(rep))] used_indices = set() for gen in new_gens: try: j = gens.index(gen) used_indices.add(j) for (M, new_M) in zip(mono...
null
null
null
What does this function do?
@require_POST @csrf_protect def generic_save(request, what): if (not test_user_authenticated(request)): return login(request, next=('/cobbler_web/%s/list' % what), expired=True) editmode = request.POST.get('editmode', 'edit') obj_name = request.POST.get('name', '') subobject = request.POST.get('subobject', 'False...
null
null
null
Saves an object back using the cobbler API after clearing any \'generic_edit\' page.
pcsd
@require POST @csrf protect def generic save request what if not test user authenticated request return login request next= '/cobbler web/%s/list' % what expired=True editmode = request POST get 'editmode' 'edit' obj name = request POST get 'name' '' subobject = request POST get 'subobject' 'False' if subobject == 'Fal...
10554
@require_POST @csrf_protect def generic_save(request, what): if (not test_user_authenticated(request)): return login(request, next=('/cobbler_web/%s/list' % what), expired=True) editmode = request.POST.get('editmode', 'edit') obj_name = request.POST.get('name', '') subobject = request.POST.get('subobject', 'False...
Saves an object back using the cobbler API after clearing any \'generic_edit\' page.
saves an object back using the cobbler api after clearing any generic _ edit page .
Question: What does this function do? Code: @require_POST @csrf_protect def generic_save(request, what): if (not test_user_authenticated(request)): return login(request, next=('/cobbler_web/%s/list' % what), expired=True) editmode = request.POST.get('editmode', 'edit') obj_name = request.POST.get('name', '') s...
null
null
null
What does this function do?
def get_toolbar_item_for_plugins(): global TOOLBAR_ITEMS_PLUGINS return TOOLBAR_ITEMS_PLUGINS
null
null
null
Returns the toolbar actions set by plugins
pcsd
def get toolbar item for plugins global TOOLBAR ITEMS PLUGINS return TOOLBAR ITEMS PLUGINS
10566
def get_toolbar_item_for_plugins(): global TOOLBAR_ITEMS_PLUGINS return TOOLBAR_ITEMS_PLUGINS
Returns the toolbar actions set by plugins
returns the toolbar actions set by plugins
Question: What does this function do? Code: def get_toolbar_item_for_plugins(): global TOOLBAR_ITEMS_PLUGINS return TOOLBAR_ITEMS_PLUGINS
null
null
null
What does this function do?
def tile_key(layer, coord, format, rev, key_prefix): name = layer.name() tile = ('%(zoom)d/%(column)d/%(row)d' % coord.__dict__) return str(('%(key_prefix)s/%(rev)s/%(name)s/%(tile)s.%(format)s' % locals()))
null
null
null
Return a tile key string.
pcsd
def tile key layer coord format rev key prefix name = layer name tile = '% zoom d/% column d/% row d' % coord dict return str '% key prefix s/% rev s/% name s/% tile s % format s' % locals
10569
def tile_key(layer, coord, format, rev, key_prefix): name = layer.name() tile = ('%(zoom)d/%(column)d/%(row)d' % coord.__dict__) return str(('%(key_prefix)s/%(rev)s/%(name)s/%(tile)s.%(format)s' % locals()))
Return a tile key string.
return a tile key string .
Question: What does this function do? Code: def tile_key(layer, coord, format, rev, key_prefix): name = layer.name() tile = ('%(zoom)d/%(column)d/%(row)d' % coord.__dict__) return str(('%(key_prefix)s/%(rev)s/%(name)s/%(tile)s.%(format)s' % locals()))
null
null
null
What does this function do?
def _tupleize(dct): return [(key, val) for (key, val) in dct.items()]
null
null
null
Take the dict of options and convert to the 2-tuple format.
pcsd
def tupleize dct return [ key val for key val in dct items ]
10572
def _tupleize(dct): return [(key, val) for (key, val) in dct.items()]
Take the dict of options and convert to the 2-tuple format.
take the dict of options and convert to the 2 - tuple format .
Question: What does this function do? Code: def _tupleize(dct): return [(key, val) for (key, val) in dct.items()]
null
null
null
What does this function do?
def block_until_instance_ready(booting_instance, wait_time=5, extra_wait_time=20): _id = booting_instance.id _instance = EC2.Instance(id=_id) _state = _instance.state['Name'] _ip = _instance.public_ip_address while ((_state != 'running') or (_ip is None)): time.sleep(wait_time) _instance = EC2.Instance(id=_id)...
null
null
null
Blocks booting_instance until AWS EC2 instance is ready to accept SSH connections
pcsd
def block until instance ready booting instance wait time=5 extra wait time=20 id = booting instance id instance = EC2 Instance id= id state = instance state['Name'] ip = instance public ip address while state != 'running' or ip is None time sleep wait time instance = EC2 Instance id= id state = instance state['Name'] ...
10578
def block_until_instance_ready(booting_instance, wait_time=5, extra_wait_time=20): _id = booting_instance.id _instance = EC2.Instance(id=_id) _state = _instance.state['Name'] _ip = _instance.public_ip_address while ((_state != 'running') or (_ip is None)): time.sleep(wait_time) _instance = EC2.Instance(id=_id)...
Blocks booting_instance until AWS EC2 instance is ready to accept SSH connections
blocks booting _ instance until aws ec2 instance is ready to accept ssh connections
Question: What does this function do? Code: def block_until_instance_ready(booting_instance, wait_time=5, extra_wait_time=20): _id = booting_instance.id _instance = EC2.Instance(id=_id) _state = _instance.state['Name'] _ip = _instance.public_ip_address while ((_state != 'running') or (_ip is None)): time.slee...
null
null
null
What does this function do?
def set_stay_open(new_stay_open): global stay_open stay_open = new_stay_open
null
null
null
Set stay_open variable.
pcsd
def set stay open new stay open global stay open stay open = new stay open
10596
def set_stay_open(new_stay_open): global stay_open stay_open = new_stay_open
Set stay_open variable.
set stay _ open variable .
Question: What does this function do? Code: def set_stay_open(new_stay_open): global stay_open stay_open = new_stay_open
null
null
null
What does this function do?
def dump(): global CONFIG table = [['Key', 'Value']] for i in CONFIG.opts.keys(): table.append([i, str(CONFIG.opts[i]['value'])]) pptable(table)
null
null
null
Dumps out the current settings in a pretty table
pcsd
def dump global CONFIG table = [['Key' 'Value']] for i in CONFIG opts keys table append [i str CONFIG opts[i]['value'] ] pptable table
10598
def dump(): global CONFIG table = [['Key', 'Value']] for i in CONFIG.opts.keys(): table.append([i, str(CONFIG.opts[i]['value'])]) pptable(table)
Dumps out the current settings in a pretty table
dumps out the current settings in a pretty table
Question: What does this function do? Code: def dump(): global CONFIG table = [['Key', 'Value']] for i in CONFIG.opts.keys(): table.append([i, str(CONFIG.opts[i]['value'])]) pptable(table)
null
null
null
What does this function do?
def extract_data(filename, num_images): print('Extracting', filename) with gzip.open(filename) as bytestream: bytestream.read(16) buf = bytestream.read((((IMAGE_SIZE * IMAGE_SIZE) * num_images) * NUM_CHANNELS)) data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32) data = ((data - (PIXEL_DEPTH / 2.0)) /...
null
null
null
Extract the images into a 4D tensor [image index, y, x, channels]. Values are rescaled from [0, 255] down to [-0.5, 0.5].
pcsd
def extract data filename num images print 'Extracting' filename with gzip open filename as bytestream bytestream read 16 buf = bytestream read IMAGE SIZE * IMAGE SIZE * num images * NUM CHANNELS data = np frombuffer buf dtype=np uint8 astype np float32 data = data - PIXEL DEPTH / 2 0 / PIXEL DEPTH data = data reshape ...
10614
def extract_data(filename, num_images): print('Extracting', filename) with gzip.open(filename) as bytestream: bytestream.read(16) buf = bytestream.read((((IMAGE_SIZE * IMAGE_SIZE) * num_images) * NUM_CHANNELS)) data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32) data = ((data - (PIXEL_DEPTH / 2.0)) /...
Extract the images into a 4D tensor [image index, y, x, channels]. Values are rescaled from [0, 255] down to [-0.5, 0.5].
extract the images into a 4d tensor [ image index , y , x , channels ] .
Question: What does this function do? Code: def extract_data(filename, num_images): print('Extracting', filename) with gzip.open(filename) as bytestream: bytestream.read(16) buf = bytestream.read((((IMAGE_SIZE * IMAGE_SIZE) * num_images) * NUM_CHANNELS)) data = np.frombuffer(buf, dtype=np.uint8).astype(np.fl...
null
null
null
What does this function do?
def parse_file(arguments): input_file = arguments[0] output_file = arguments[1] row_limit = arguments[2] output_path = '.' with open(input_file, 'r') as input_csv: datareader = csv.reader(input_csv) all_rows = [] for row in datareader: all_rows.append(row) header = all_rows.pop(0) current_chunk = 1 ...
null
null
null
Splits the CSV into multiple files or chunks based on the row_limit. Then create new CSV files.
pcsd
def parse file arguments input file = arguments[0] output file = arguments[1] row limit = arguments[2] output path = ' ' with open input file 'r' as input csv datareader = csv reader input csv all rows = [] for row in datareader all rows append row header = all rows pop 0 current chunk = 1 for i in range 0 len all rows...
10619
def parse_file(arguments): input_file = arguments[0] output_file = arguments[1] row_limit = arguments[2] output_path = '.' with open(input_file, 'r') as input_csv: datareader = csv.reader(input_csv) all_rows = [] for row in datareader: all_rows.append(row) header = all_rows.pop(0) current_chunk = 1 ...
Splits the CSV into multiple files or chunks based on the row_limit. Then create new CSV files.
splits the csv into multiple files or chunks based on the row _ limit .
Question: What does this function do? Code: def parse_file(arguments): input_file = arguments[0] output_file = arguments[1] row_limit = arguments[2] output_path = '.' with open(input_file, 'r') as input_csv: datareader = csv.reader(input_csv) all_rows = [] for row in datareader: all_rows.append(row) ...
null
null
null
What does this function do?
def get_mock_request(user=None): request = RequestFactory().get('/') if (user is not None): request.user = user else: request.user = AnonymousUser() request.is_secure = (lambda : True) request.get_host = (lambda : 'edx.org') crum.set_current_request(request) return request
null
null
null
Create a request object for the user, if specified.
pcsd
def get mock request user=None request = Request Factory get '/' if user is not None request user = user else request user = Anonymous User request is secure = lambda True request get host = lambda 'edx org' crum set current request request return request
10623
def get_mock_request(user=None): request = RequestFactory().get('/') if (user is not None): request.user = user else: request.user = AnonymousUser() request.is_secure = (lambda : True) request.get_host = (lambda : 'edx.org') crum.set_current_request(request) return request
Create a request object for the user, if specified.
create a request object for the user , if specified .
Question: What does this function do? Code: def get_mock_request(user=None): request = RequestFactory().get('/') if (user is not None): request.user = user else: request.user = AnonymousUser() request.is_secure = (lambda : True) request.get_host = (lambda : 'edx.org') crum.set_current_request(request) ret...
null
null
null
What does this function do?
@main.command() @url_option @click.option(u'--all', u'-a', is_flag=True, help=u'Empty all queues') @click.argument(u'queues', nargs=(-1)) def empty(url, all, queues): conn = connect(url) if all: queues = Queue.all(connection=conn) else: queues = [Queue(queue, connection=conn) for queue in queues] if (not queues...
null
null
null
Empty given queues.
pcsd
@main command @url option @click option u'--all' u'-a' is flag=True help=u'Empty all queues' @click argument u'queues' nargs= -1 def empty url all queues conn = connect url if all queues = Queue all connection=conn else queues = [Queue queue connection=conn for queue in queues] if not queues click echo u'Nothing to do'...
10630
@main.command() @url_option @click.option(u'--all', u'-a', is_flag=True, help=u'Empty all queues') @click.argument(u'queues', nargs=(-1)) def empty(url, all, queues): conn = connect(url) if all: queues = Queue.all(connection=conn) else: queues = [Queue(queue, connection=conn) for queue in queues] if (not queues...
Empty given queues.
empty given queues .
Question: What does this function do? Code: @main.command() @url_option @click.option(u'--all', u'-a', is_flag=True, help=u'Empty all queues') @click.argument(u'queues', nargs=(-1)) def empty(url, all, queues): conn = connect(url) if all: queues = Queue.all(connection=conn) else: queues = [Queue(queue, connec...
null
null
null
What does this function do?
def generate_targets(target_source): target_source = os.path.abspath(target_source) if os.path.isdir(target_source): target_source_files = glob.glob((target_source + '/*.tsv')) else: target_source_files = [target_source] for target_source_file in target_source_files: with open(target_source_file, 'r') as f: ...
null
null
null
Generate all targets from TSV files in specified file or directory.
pcsd
def generate targets target source target source = os path abspath target source if os path isdir target source target source files = glob glob target source + '/* tsv' else target source files = [target source] for target source file in target source files with open target source file 'r' as f for line in f readlines ...
10636
def generate_targets(target_source): target_source = os.path.abspath(target_source) if os.path.isdir(target_source): target_source_files = glob.glob((target_source + '/*.tsv')) else: target_source_files = [target_source] for target_source_file in target_source_files: with open(target_source_file, 'r') as f: ...
Generate all targets from TSV files in specified file or directory.
generate all targets from tsv files in specified file or directory .
Question: What does this function do? Code: def generate_targets(target_source): target_source = os.path.abspath(target_source) if os.path.isdir(target_source): target_source_files = glob.glob((target_source + '/*.tsv')) else: target_source_files = [target_source] for target_source_file in target_source_file...
null
null
null
What does this function do?
def accuracy(classify=(lambda document: False), documents=[], average=None): return test(classify, documents, average)[0]
null
null
null
Returns the percentage of correct classifications (true positives + true negatives).
pcsd
def accuracy classify= lambda document False documents=[] average=None return test classify documents average [0]
10639
def accuracy(classify=(lambda document: False), documents=[], average=None): return test(classify, documents, average)[0]
Returns the percentage of correct classifications (true positives + true negatives).
returns the percentage of correct classifications .
Question: What does this function do? Code: def accuracy(classify=(lambda document: False), documents=[], average=None): return test(classify, documents, average)[0]
null
null
null
What does this function do?
def generateUi(opts): widget = QtGui.QWidget() l = QtGui.QFormLayout() l.setSpacing(0) widget.setLayout(l) ctrls = {} row = 0 for opt in opts: if (len(opt) == 2): (k, t) = opt o = {} elif (len(opt) == 3): (k, t, o) = opt else: raise Exception('Widget specification must be (name, type) or (name,...
null
null
null
Convenience function for generating common UI types
pcsd
def generate Ui opts widget = Qt Gui Q Widget l = Qt Gui Q Form Layout l set Spacing 0 widget set Layout l ctrls = {} row = 0 for opt in opts if len opt == 2 k t = opt o = {} elif len opt == 3 k t o = opt else raise Exception 'Widget specification must be name type or name type {opts} ' if t == 'int Spin' w = Qt Gui Q ...
10644
def generateUi(opts): widget = QtGui.QWidget() l = QtGui.QFormLayout() l.setSpacing(0) widget.setLayout(l) ctrls = {} row = 0 for opt in opts: if (len(opt) == 2): (k, t) = opt o = {} elif (len(opt) == 3): (k, t, o) = opt else: raise Exception('Widget specification must be (name, type) or (name,...
Convenience function for generating common UI types
convenience function for generating common ui types
Question: What does this function do? Code: def generateUi(opts): widget = QtGui.QWidget() l = QtGui.QFormLayout() l.setSpacing(0) widget.setLayout(l) ctrls = {} row = 0 for opt in opts: if (len(opt) == 2): (k, t) = opt o = {} elif (len(opt) == 3): (k, t, o) = opt else: raise Exception('Widg...
null
null
null
What does this function do?
def get_content(b=None, c=request.controller, f=request.function, l='en', format='markmin'): def openfile(): import os path = os.path.join(request.folder, 'private', 'content', l, c, f, ((b + '.') + format)) return open_file(path, mode='r') try: openedfile = openfile() except (Exception, IOError): l = 'en'...
null
null
null
Gets and renders the file in <app>/private/content/<lang>/<controller>/<function>/<block>.<format>
pcsd
def get content b=None c=request controller f=request function l='en' format='markmin' def openfile import os path = os path join request folder 'private' 'content' l c f b + ' ' + format return open file path mode='r' try openedfile = openfile except Exception IO Error l = 'en' openedfile = openfile if format == 'mark...
10653
def get_content(b=None, c=request.controller, f=request.function, l='en', format='markmin'): def openfile(): import os path = os.path.join(request.folder, 'private', 'content', l, c, f, ((b + '.') + format)) return open_file(path, mode='r') try: openedfile = openfile() except (Exception, IOError): l = 'en'...
Gets and renders the file in <app>/private/content/<lang>/<controller>/<function>/<block>.<format>
gets and renders the file in / private / content / / / / .
Question: What does this function do? Code: def get_content(b=None, c=request.controller, f=request.function, l='en', format='markmin'): def openfile(): import os path = os.path.join(request.folder, 'private', 'content', l, c, f, ((b + '.') + format)) return open_file(path, mode='r') try: openedfile = open...
null
null
null
What does this function do?
def prettify(jsonobj, prettify=True): if (not prettify): return json.dumps(jsonobj) json_str = json.dumps(jsonobj, indent=2, sort_keys=True) if pygments: try: lexer = get_lexer_for_mimetype('application/json') return pygments.highlight(json_str, lexer, TerminalFormatter()) except: pass return json_st...
null
null
null
prettiffy JSON output
pcsd
def prettify jsonobj prettify=True if not prettify return json dumps jsonobj json str = json dumps jsonobj indent=2 sort keys=True if pygments try lexer = get lexer for mimetype 'application/json' return pygments highlight json str lexer Terminal Formatter except pass return json str
10654
def prettify(jsonobj, prettify=True): if (not prettify): return json.dumps(jsonobj) json_str = json.dumps(jsonobj, indent=2, sort_keys=True) if pygments: try: lexer = get_lexer_for_mimetype('application/json') return pygments.highlight(json_str, lexer, TerminalFormatter()) except: pass return json_st...
prettiffy JSON output
prettiffy json output
Question: What does this function do? Code: def prettify(jsonobj, prettify=True): if (not prettify): return json.dumps(jsonobj) json_str = json.dumps(jsonobj, indent=2, sort_keys=True) if pygments: try: lexer = get_lexer_for_mimetype('application/json') return pygments.highlight(json_str, lexer, Termina...
null
null
null
What does this function do?
@require_POST @login_required def unwatch_approved(request, product=None): if (request.LANGUAGE_CODE not in settings.SUMO_LANGUAGES): raise Http404 kwargs = {'locale': request.LANGUAGE_CODE} if (product is not None): kwargs['product'] = product ApproveRevisionInLocaleEvent.stop_notifying(request.user, **kwargs)...
null
null
null
Stop watching approved revisions for a given product.
pcsd
@require POST @login required def unwatch approved request product=None if request LANGUAGE CODE not in settings SUMO LANGUAGES raise Http404 kwargs = {'locale' request LANGUAGE CODE} if product is not None kwargs['product'] = product Approve Revision In Locale Event stop notifying request user **kwargs return Http Res...
10661
@require_POST @login_required def unwatch_approved(request, product=None): if (request.LANGUAGE_CODE not in settings.SUMO_LANGUAGES): raise Http404 kwargs = {'locale': request.LANGUAGE_CODE} if (product is not None): kwargs['product'] = product ApproveRevisionInLocaleEvent.stop_notifying(request.user, **kwargs)...
Stop watching approved revisions for a given product.
stop watching approved revisions for a given product .
Question: What does this function do? Code: @require_POST @login_required def unwatch_approved(request, product=None): if (request.LANGUAGE_CODE not in settings.SUMO_LANGUAGES): raise Http404 kwargs = {'locale': request.LANGUAGE_CODE} if (product is not None): kwargs['product'] = product ApproveRevisionInLoc...
null
null
null
What does this function do?
def wait_for_occupied_port(host, port, timeout=None): if (not host): raise ValueError("Host values of '' or None are not allowed.") if (timeout is None): timeout = occupied_port_timeout for trial in range(50): try: check_port(host, port, timeout=timeout) except IOError: return else: time.sleep(tim...
null
null
null
Wait for the specified port to become active (receive requests).
pcsd
def wait for occupied port host port timeout=None if not host raise Value Error "Host values of '' or None are not allowed " if timeout is None timeout = occupied port timeout for trial in range 50 try check port host port timeout=timeout except IO Error return else time sleep timeout raise IO Error 'Port %r not bound ...
10663
def wait_for_occupied_port(host, port, timeout=None): if (not host): raise ValueError("Host values of '' or None are not allowed.") if (timeout is None): timeout = occupied_port_timeout for trial in range(50): try: check_port(host, port, timeout=timeout) except IOError: return else: time.sleep(tim...
Wait for the specified port to become active (receive requests).
wait for the specified port to become active .
Question: What does this function do? Code: def wait_for_occupied_port(host, port, timeout=None): if (not host): raise ValueError("Host values of '' or None are not allowed.") if (timeout is None): timeout = occupied_port_timeout for trial in range(50): try: check_port(host, port, timeout=timeout) exce...
null
null
null
What does this function do?
def ext_pillar(minion_id, pillar, command): try: command = command.replace('%s', minion_id) return yaml.safe_load(__salt__['cmd.run_stdout']('{0}'.format(command), python_shell=True)) except Exception: log.critical('YAML data from {0} failed to parse'.format(command)) return {}
null
null
null
Execute a command and read the output as YAML
pcsd
def ext pillar minion id pillar command try command = command replace '%s' minion id return yaml safe load salt ['cmd run stdout'] '{0}' format command python shell=True except Exception log critical 'YAML data from {0} failed to parse' format command return {}
10664
def ext_pillar(minion_id, pillar, command): try: command = command.replace('%s', minion_id) return yaml.safe_load(__salt__['cmd.run_stdout']('{0}'.format(command), python_shell=True)) except Exception: log.critical('YAML data from {0} failed to parse'.format(command)) return {}
Execute a command and read the output as YAML
execute a command and read the output as yaml
Question: What does this function do? Code: def ext_pillar(minion_id, pillar, command): try: command = command.replace('%s', minion_id) return yaml.safe_load(__salt__['cmd.run_stdout']('{0}'.format(command), python_shell=True)) except Exception: log.critical('YAML data from {0} failed to parse'.format(comman...
null
null
null
What does this function do?
def _extract_nodes(html_tree, filename): search_expr = _XPATH_FIND_NODES for name in _IGNORE_NODES: search_expr += ('[not(ancestor-or-self::%s)]' % name) return html_tree.xpath(search_expr)
null
null
null
Extract all the i18n-able nodes out of a file.
pcsd
def extract nodes html tree filename search expr = XPATH FIND NODES for name in IGNORE NODES search expr += '[not ancestor-or-self %s ]' % name return html tree xpath search expr
10675
def _extract_nodes(html_tree, filename): search_expr = _XPATH_FIND_NODES for name in _IGNORE_NODES: search_expr += ('[not(ancestor-or-self::%s)]' % name) return html_tree.xpath(search_expr)
Extract all the i18n-able nodes out of a file.
extract all the i18n - able nodes out of a file .
Question: What does this function do? Code: def _extract_nodes(html_tree, filename): search_expr = _XPATH_FIND_NODES for name in _IGNORE_NODES: search_expr += ('[not(ancestor-or-self::%s)]' % name) return html_tree.xpath(search_expr)
null
null
null
What does this function do?
def send_tcp(data, host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.sendall(data) response = sock.recv(8192) length = struct.unpack('!H', bytes(response[:2]))[0] while ((len(response) - 2) < length): response += sock.recv(8192) sock.close() return response
null
null
null
Helper function to send/receive DNS TCP request (in/out packets will have prepended TCP length header)
pcsd
def send tcp data host port sock = socket socket socket AF INET socket SOCK STREAM sock connect host port sock sendall data response = sock recv 8192 length = struct unpack '!H' bytes response[ 2] [0] while len response - 2 < length response += sock recv 8192 sock close return response
10676
def send_tcp(data, host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.sendall(data) response = sock.recv(8192) length = struct.unpack('!H', bytes(response[:2]))[0] while ((len(response) - 2) < length): response += sock.recv(8192) sock.close() return response
Helper function to send/receive DNS TCP request (in/out packets will have prepended TCP length header)
helper function to send / receive dns tcp request
Question: What does this function do? Code: def send_tcp(data, host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.sendall(data) response = sock.recv(8192) length = struct.unpack('!H', bytes(response[:2]))[0] while ((len(response) - 2) < length): response += ...
null
null
null
What does this function do?
def _unique_partition_id(course): used_ids = set((p.id for p in course.user_partitions)) return generate_int_id(used_ids=used_ids)
null
null
null
Return a unique user partition ID for the course.
pcsd
def unique partition id course used ids = set p id for p in course user partitions return generate int id used ids=used ids
10693
def _unique_partition_id(course): used_ids = set((p.id for p in course.user_partitions)) return generate_int_id(used_ids=used_ids)
Return a unique user partition ID for the course.
return a unique user partition id for the course .
Question: What does this function do? Code: def _unique_partition_id(course): used_ids = set((p.id for p in course.user_partitions)) return generate_int_id(used_ids=used_ids)
null
null
null
What does this function do?
def p_expression_name(t): try: t[0] = names[t[1]] except LookupError: print ("Undefined name '%s'" % t[1]) t[0] = 0
null
null
null
expression : NAME
pcsd
def p expression name t try t[0] = names[t[1]] except Lookup Error print "Undefined name '%s'" % t[1] t[0] = 0
10695
def p_expression_name(t): try: t[0] = names[t[1]] except LookupError: print ("Undefined name '%s'" % t[1]) t[0] = 0
expression : NAME
expression : name
Question: What does this function do? Code: def p_expression_name(t): try: t[0] = names[t[1]] except LookupError: print ("Undefined name '%s'" % t[1]) t[0] = 0
null
null
null
What does this function do?
def config_settings_loader(request=None): conf = SPConfig() conf.load(copy.deepcopy(settings.SAML_CONFIG)) return conf
null
null
null
Utility function to load the pysaml2 configuration. This is also the default config loader.
pcsd
def config settings loader request=None conf = SP Config conf load copy deepcopy settings SAML CONFIG return conf
10724
def config_settings_loader(request=None): conf = SPConfig() conf.load(copy.deepcopy(settings.SAML_CONFIG)) return conf
Utility function to load the pysaml2 configuration. This is also the default config loader.
utility function to load the pysaml2 configuration .
Question: What does this function do? Code: def config_settings_loader(request=None): conf = SPConfig() conf.load(copy.deepcopy(settings.SAML_CONFIG)) return conf
null
null
null
What does this function do?
def find_checks(argument_name): checks = [] function_type = type(find_checks) for (name, function) in globals().iteritems(): if (type(function) is function_type): args = inspect.getargspec(function)[0] if ((len(args) >= 1) and args[0].startswith(argument_name)): checks.append((name, function, args)) che...
null
null
null
Find all globally visible functions where the first argument name starts with argument_name.
pcsd
def find checks argument name checks = [] function type = type find checks for name function in globals iteritems if type function is function type args = inspect getargspec function [0] if len args >= 1 and args[0] startswith argument name checks append name function args checks sort return checks
10725
def find_checks(argument_name): checks = [] function_type = type(find_checks) for (name, function) in globals().iteritems(): if (type(function) is function_type): args = inspect.getargspec(function)[0] if ((len(args) >= 1) and args[0].startswith(argument_name)): checks.append((name, function, args)) che...
Find all globally visible functions where the first argument name starts with argument_name.
find all globally visible functions where the first argument name starts with argument _ name .
Question: What does this function do? Code: def find_checks(argument_name): checks = [] function_type = type(find_checks) for (name, function) in globals().iteritems(): if (type(function) is function_type): args = inspect.getargspec(function)[0] if ((len(args) >= 1) and args[0].startswith(argument_name)):...
null
null
null
What does this function do?
def get_temp_imagefilename(url): img = _urlopen(url).read() im = Image.open(BytesIO(img)) f = tempfile.NamedTemporaryFile(delete=False, suffix='.png') fname = f.name f.close() im.save(fname, 'PNG') return fname
null
null
null
Returns filename of temporary file containing downloaded image. Create a new temporary file to hold the image file at the passed URL and return the filename.
pcsd
def get temp imagefilename url img = urlopen url read im = Image open Bytes IO img f = tempfile Named Temporary File delete=False suffix=' png' fname = f name f close im save fname 'PNG' return fname
10727
def get_temp_imagefilename(url): img = _urlopen(url).read() im = Image.open(BytesIO(img)) f = tempfile.NamedTemporaryFile(delete=False, suffix='.png') fname = f.name f.close() im.save(fname, 'PNG') return fname
Returns filename of temporary file containing downloaded image. Create a new temporary file to hold the image file at the passed URL and return the filename.
returns filename of temporary file containing downloaded image .
Question: What does this function do? Code: def get_temp_imagefilename(url): img = _urlopen(url).read() im = Image.open(BytesIO(img)) f = tempfile.NamedTemporaryFile(delete=False, suffix='.png') fname = f.name f.close() im.save(fname, 'PNG') return fname
null
null
null
What does this function do?
def do_aggregate_list(cs, args): aggregates = cs.aggregates.list() columns = ['Id', 'Name', 'Availability Zone'] if (cs.api_version >= api_versions.APIVersion('2.41')): columns.append('UUID') utils.print_list(aggregates, columns)
null
null
null
Print a list of all aggregates.
pcsd
def do aggregate list cs args aggregates = cs aggregates list columns = ['Id' 'Name' 'Availability Zone'] if cs api version >= api versions API Version '2 41' columns append 'UUID' utils print list aggregates columns
10728
def do_aggregate_list(cs, args): aggregates = cs.aggregates.list() columns = ['Id', 'Name', 'Availability Zone'] if (cs.api_version >= api_versions.APIVersion('2.41')): columns.append('UUID') utils.print_list(aggregates, columns)
Print a list of all aggregates.
print a list of all aggregates .
Question: What does this function do? Code: def do_aggregate_list(cs, args): aggregates = cs.aggregates.list() columns = ['Id', 'Name', 'Availability Zone'] if (cs.api_version >= api_versions.APIVersion('2.41')): columns.append('UUID') utils.print_list(aggregates, columns)
null
null
null
What does this function do?
def disk_io_counters(): def get_partitions(): partitions = [] with open_text(('%s/partitions' % get_procfs_path())) as f: lines = f.readlines()[2:] for line in reversed(lines): (_, _, _, name) = line.split() if name[(-1)].isdigit(): partitions.append(name) elif ((not partitions) or (not partition...
null
null
null
Return disk I/O statistics for every disk installed on the system as a dict of raw tuples.
pcsd
def disk io counters def get partitions partitions = [] with open text '%s/partitions' % get procfs path as f lines = f readlines [2 ] for line in reversed lines name = line split if name[ -1 ] isdigit partitions append name elif not partitions or not partitions[ -1 ] startswith name partitions append name return parti...
10734
def disk_io_counters(): def get_partitions(): partitions = [] with open_text(('%s/partitions' % get_procfs_path())) as f: lines = f.readlines()[2:] for line in reversed(lines): (_, _, _, name) = line.split() if name[(-1)].isdigit(): partitions.append(name) elif ((not partitions) or (not partition...
Return disk I/O statistics for every disk installed on the system as a dict of raw tuples.
return disk i / o statistics for every disk installed on the system as a dict of raw tuples .
Question: What does this function do? Code: def disk_io_counters(): def get_partitions(): partitions = [] with open_text(('%s/partitions' % get_procfs_path())) as f: lines = f.readlines()[2:] for line in reversed(lines): (_, _, _, name) = line.split() if name[(-1)].isdigit(): partitions.append(na...
null
null
null
What does this function do?
def getClosestPointOnSegment(segmentBegin, segmentEnd, point): segmentDifference = (segmentEnd - segmentBegin) if (abs(segmentDifference) <= 0.0): return segmentBegin pointMinusSegmentBegin = (point - segmentBegin) beginPlaneDot = getDotProduct(pointMinusSegmentBegin, segmentDifference) differencePlaneDot = getD...
null
null
null
Get the closest point on the segment.
pcsd
def get Closest Point On Segment segment Begin segment End point segment Difference = segment End - segment Begin if abs segment Difference <= 0 0 return segment Begin point Minus Segment Begin = point - segment Begin begin Plane Dot = get Dot Product point Minus Segment Begin segment Difference difference Plane Dot = ...
10736
def getClosestPointOnSegment(segmentBegin, segmentEnd, point): segmentDifference = (segmentEnd - segmentBegin) if (abs(segmentDifference) <= 0.0): return segmentBegin pointMinusSegmentBegin = (point - segmentBegin) beginPlaneDot = getDotProduct(pointMinusSegmentBegin, segmentDifference) differencePlaneDot = getD...
Get the closest point on the segment.
get the closest point on the segment .
Question: What does this function do? Code: def getClosestPointOnSegment(segmentBegin, segmentEnd, point): segmentDifference = (segmentEnd - segmentBegin) if (abs(segmentDifference) <= 0.0): return segmentBegin pointMinusSegmentBegin = (point - segmentBegin) beginPlaneDot = getDotProduct(pointMinusSegmentBegin...
null
null
null
What does this function do?
def run(): for chunk in chunked(Webapp.objects.all(), 50): for app in chunk: for slug in SIZE_SLUGS: assets = ImageAsset.objects.filter(addon=app, slug=slug) for asset in assets[1:]: asset.delete()
null
null
null
Delete duplicate image assets.
pcsd
def run for chunk in chunked Webapp objects all 50 for app in chunk for slug in SIZE SLUGS assets = Image Asset objects filter addon=app slug=slug for asset in assets[1 ] asset delete
10743
def run(): for chunk in chunked(Webapp.objects.all(), 50): for app in chunk: for slug in SIZE_SLUGS: assets = ImageAsset.objects.filter(addon=app, slug=slug) for asset in assets[1:]: asset.delete()
Delete duplicate image assets.
delete duplicate image assets .
Question: What does this function do? Code: def run(): for chunk in chunked(Webapp.objects.all(), 50): for app in chunk: for slug in SIZE_SLUGS: assets = ImageAsset.objects.filter(addon=app, slug=slug) for asset in assets[1:]: asset.delete()
null
null
null
What does this function do?
def all_collectors(): return COLLECTORS.itervalues()
null
null
null
Generator to return all collectors.
pcsd
def all collectors return COLLECTORS itervalues
10745
def all_collectors(): return COLLECTORS.itervalues()
Generator to return all collectors.
generator to return all collectors .
Question: What does this function do? Code: def all_collectors(): return COLLECTORS.itervalues()
null
null
null
What does this function do?
def biDiText(text): text = s3_unicode(text) if (biDiImported and current.deployment_settings.get_pdf_bidi()): isArabic = False isBidi = False for c in text: cat = unicodedata.bidirectional(c) if (cat in ('AL', 'AN')): isArabic = True isBidi = True break elif (cat in ('R', 'RLE', 'RLO')): ...
null
null
null
Ensure that RTL text is rendered RTL & also that Arabic text is rewritten to use the joined format.
pcsd
def bi Di Text text text = s3 unicode text if bi Di Imported and current deployment settings get pdf bidi is Arabic = False is Bidi = False for c in text cat = unicodedata bidirectional c if cat in 'AL' 'AN' is Arabic = True is Bidi = True break elif cat in 'R' 'RLE' 'RLO' is Bidi = True if is Arabic text = arabic resh...
10750
def biDiText(text): text = s3_unicode(text) if (biDiImported and current.deployment_settings.get_pdf_bidi()): isArabic = False isBidi = False for c in text: cat = unicodedata.bidirectional(c) if (cat in ('AL', 'AN')): isArabic = True isBidi = True break elif (cat in ('R', 'RLE', 'RLO')): ...
Ensure that RTL text is rendered RTL & also that Arabic text is rewritten to use the joined format.
ensure that rtl text is rendered rtl & also that arabic text is rewritten to use the joined format .
Question: What does this function do? Code: def biDiText(text): text = s3_unicode(text) if (biDiImported and current.deployment_settings.get_pdf_bidi()): isArabic = False isBidi = False for c in text: cat = unicodedata.bidirectional(c) if (cat in ('AL', 'AN')): isArabic = True isBidi = True ...
null
null
null
What does this function do?
def membership_required(function=None): def decorator(request, *args, **kwargs): group = get_object_or_404(Group, slug=kwargs['slug']) if request.user.is_anonymous(): return HttpResponseRedirect(reverse('django.contrib.auth.views.login')) if GroupMember.objects.is_member(group, request.user): return functi...
null
null
null
Decorator for views that require user to be a member of a group, redirecting to the group join page if necessary.
pcsd
def membership required function=None def decorator request *args **kwargs group = get object or 404 Group slug=kwargs['slug'] if request user is anonymous return Http Response Redirect reverse 'django contrib auth views login' if Group Member objects is member group request user return function request *args **kwargs ...
10754
def membership_required(function=None): def decorator(request, *args, **kwargs): group = get_object_or_404(Group, slug=kwargs['slug']) if request.user.is_anonymous(): return HttpResponseRedirect(reverse('django.contrib.auth.views.login')) if GroupMember.objects.is_member(group, request.user): return functi...
Decorator for views that require user to be a member of a group, redirecting to the group join page if necessary.
decorator for views that require user to be a member of a group , redirecting to the group join page if necessary .
Question: What does this function do? Code: def membership_required(function=None): def decorator(request, *args, **kwargs): group = get_object_or_404(Group, slug=kwargs['slug']) if request.user.is_anonymous(): return HttpResponseRedirect(reverse('django.contrib.auth.views.login')) if GroupMember.objects.i...
null
null
null
What does this function do?
def get_upload_pipeline(in_fd, out_fd, rate_limit=None, gpg_key=None, lzop=True): commands = [] if (rate_limit is not None): commands.append(PipeViewerRateLimitFilter(rate_limit)) if lzop: commands.append(LZOCompressionFilter()) if (gpg_key is not None): commands.append(GPGEncryptionFilter(gpg_key)) return P...
null
null
null
Create a UNIX pipeline to process a file for uploading. (Compress, and optionally encrypt)
pcsd
def get upload pipeline in fd out fd rate limit=None gpg key=None lzop=True commands = [] if rate limit is not None commands append Pipe Viewer Rate Limit Filter rate limit if lzop commands append LZO Compression Filter if gpg key is not None commands append GPG Encryption Filter gpg key return Pipeline commands in fd ...
10761
def get_upload_pipeline(in_fd, out_fd, rate_limit=None, gpg_key=None, lzop=True): commands = [] if (rate_limit is not None): commands.append(PipeViewerRateLimitFilter(rate_limit)) if lzop: commands.append(LZOCompressionFilter()) if (gpg_key is not None): commands.append(GPGEncryptionFilter(gpg_key)) return P...
Create a UNIX pipeline to process a file for uploading. (Compress, and optionally encrypt)
create a unix pipeline to process a file for uploading .
Question: What does this function do? Code: def get_upload_pipeline(in_fd, out_fd, rate_limit=None, gpg_key=None, lzop=True): commands = [] if (rate_limit is not None): commands.append(PipeViewerRateLimitFilter(rate_limit)) if lzop: commands.append(LZOCompressionFilter()) if (gpg_key is not None): commands...
null
null
null
What does this function do?
def main(): module = AnsibleModule(argument_spec=dict(pn_cliusername=dict(required=True, type='str'), pn_clipassword=dict(required=True, type='str', no_log=True), pn_cliswitch=dict(required=False, type='str'), pn_command=dict(required=True, type='str'), pn_parameters=dict(default='all', type='str'), pn_options=dict(ty...
null
null
null
This section is for arguments parsing
pcsd
def main module = Ansible Module argument spec=dict pn cliusername=dict required=True type='str' pn clipassword=dict required=True type='str' no log=True pn cliswitch=dict required=False type='str' pn command=dict required=True type='str' pn parameters=dict default='all' type='str' pn options=dict type='str' command = ...
10763
def main(): module = AnsibleModule(argument_spec=dict(pn_cliusername=dict(required=True, type='str'), pn_clipassword=dict(required=True, type='str', no_log=True), pn_cliswitch=dict(required=False, type='str'), pn_command=dict(required=True, type='str'), pn_parameters=dict(default='all', type='str'), pn_options=dict(ty...
This section is for arguments parsing
this section is for arguments parsing
Question: What does this function do? Code: def main(): module = AnsibleModule(argument_spec=dict(pn_cliusername=dict(required=True, type='str'), pn_clipassword=dict(required=True, type='str', no_log=True), pn_cliswitch=dict(required=False, type='str'), pn_command=dict(required=True, type='str'), pn_parameters=dict...
null
null
null
What does this function do?
def build_traversal_spec(client_factory, name, spec_type, path, skip, select_set): traversal_spec = client_factory.create('ns0:TraversalSpec') traversal_spec.name = name traversal_spec.type = spec_type traversal_spec.path = path traversal_spec.skip = skip traversal_spec.selectSet = select_set return traversal_sp...
null
null
null
Builds the traversal spec object.
pcsd
def build traversal spec client factory name spec type path skip select set traversal spec = client factory create 'ns0 Traversal Spec' traversal spec name = name traversal spec type = spec type traversal spec path = path traversal spec skip = skip traversal spec select Set = select set return traversal spec
10764
def build_traversal_spec(client_factory, name, spec_type, path, skip, select_set): traversal_spec = client_factory.create('ns0:TraversalSpec') traversal_spec.name = name traversal_spec.type = spec_type traversal_spec.path = path traversal_spec.skip = skip traversal_spec.selectSet = select_set return traversal_sp...
Builds the traversal spec object.
builds the traversal spec object .
Question: What does this function do? Code: def build_traversal_spec(client_factory, name, spec_type, path, skip, select_set): traversal_spec = client_factory.create('ns0:TraversalSpec') traversal_spec.name = name traversal_spec.type = spec_type traversal_spec.path = path traversal_spec.skip = skip traversal_s...
null
null
null
What does this function do?
def get_unit_status(code): output = check_output(('heyu onstate ' + code), shell=True) return int(output.decode('utf-8')[0])
null
null
null
Get on/off status for given unit.
pcsd
def get unit status code output = check output 'heyu onstate ' + code shell=True return int output decode 'utf-8' [0]
10771
def get_unit_status(code): output = check_output(('heyu onstate ' + code), shell=True) return int(output.decode('utf-8')[0])
Get on/off status for given unit.
get on / off status for given unit .
Question: What does this function do? Code: def get_unit_status(code): output = check_output(('heyu onstate ' + code), shell=True) return int(output.decode('utf-8')[0])
null
null
null
What does this function do?
@register.simple_tag def locale_align(): return ((trans_real.get_language_bidi() and 'right') or 'left')
null
null
null
Returns current locale\'s default alignment.
pcsd
@register simple tag def locale align return trans real get language bidi and 'right' or 'left'
10776
@register.simple_tag def locale_align(): return ((trans_real.get_language_bidi() and 'right') or 'left')
Returns current locale\'s default alignment.
returns current locales default alignment .
Question: What does this function do? Code: @register.simple_tag def locale_align(): return ((trans_real.get_language_bidi() and 'right') or 'left')
null
null
null
What does this function do?
def reset_docker_settings(): DockerUtil().set_docker_settings({}, {})
null
null
null
Populate docker settings with default, dummy settings
pcsd
def reset docker settings Docker Util set docker settings {} {}
10787
def reset_docker_settings(): DockerUtil().set_docker_settings({}, {})
Populate docker settings with default, dummy settings
populate docker settings with default , dummy settings
Question: What does this function do? Code: def reset_docker_settings(): DockerUtil().set_docker_settings({}, {})
null
null
null
What does this function do?
def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): (event_source_obj, ctx, funk) = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) funk.arn = lambda_arn if (not dry): rule_response = event_source_obj.remove(funk) return rule_response ...
null
null
null
Given an event_source dictionary, create the object and remove the event source.
pcsd
def remove event source event source lambda arn target function boto session dry=False event source obj ctx funk = get event source event source lambda arn target function boto session dry=False funk arn = lambda arn if not dry rule response = event source obj remove funk return rule response else return event source o...
10799
def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): (event_source_obj, ctx, funk) = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) funk.arn = lambda_arn if (not dry): rule_response = event_source_obj.remove(funk) return rule_response ...
Given an event_source dictionary, create the object and remove the event source.
given an event _ source dictionary , create the object and remove the event source .
Question: What does this function do? Code: def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): (event_source_obj, ctx, funk) = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) funk.arn = lambda_arn if (not dry): rule_response = event_...
null
null
null
What does this function do?
@cache_permission def can_suggest(user, translation): if (not translation.subproject.enable_suggestions): return False if has_group_perm(user, 'trans.add_suggestion', translation): return True return check_permission(user, translation.subproject.project, 'trans.add_suggestion')
null
null
null
Checks whether user can add suggestions to given translation.
pcsd
@cache permission def can suggest user translation if not translation subproject enable suggestions return False if has group perm user 'trans add suggestion' translation return True return check permission user translation subproject project 'trans add suggestion'
10800
@cache_permission def can_suggest(user, translation): if (not translation.subproject.enable_suggestions): return False if has_group_perm(user, 'trans.add_suggestion', translation): return True return check_permission(user, translation.subproject.project, 'trans.add_suggestion')
Checks whether user can add suggestions to given translation.
checks whether user can add suggestions to given translation .
Question: What does this function do? Code: @cache_permission def can_suggest(user, translation): if (not translation.subproject.enable_suggestions): return False if has_group_perm(user, 'trans.add_suggestion', translation): return True return check_permission(user, translation.subproject.project, 'trans.add_...
null
null
null
What does this function do?
def _wait(jid): if (jid is None): jid = salt.utils.jid.gen_jid() states = _prior_running_states(jid) while states: time.sleep(1) states = _prior_running_states(jid)
null
null
null
Wait for all previously started state jobs to finish running
pcsd
def wait jid if jid is None jid = salt utils jid gen jid states = prior running states jid while states time sleep 1 states = prior running states jid
10809
def _wait(jid): if (jid is None): jid = salt.utils.jid.gen_jid() states = _prior_running_states(jid) while states: time.sleep(1) states = _prior_running_states(jid)
Wait for all previously started state jobs to finish running
wait for all previously started state jobs to finish running
Question: What does this function do? Code: def _wait(jid): if (jid is None): jid = salt.utils.jid.gen_jid() states = _prior_running_states(jid) while states: time.sleep(1) states = _prior_running_states(jid)
null
null
null
What does this function do?
def _calc_array_sizeof(ndim): ctx = cpu_target.target_context return ctx.calc_array_sizeof(ndim)
null
null
null
Use the ABI size in the CPU target
pcsd
def calc array sizeof ndim ctx = cpu target target context return ctx calc array sizeof ndim
10814
def _calc_array_sizeof(ndim): ctx = cpu_target.target_context return ctx.calc_array_sizeof(ndim)
Use the ABI size in the CPU target
use the abi size in the cpu target
Question: What does this function do? Code: def _calc_array_sizeof(ndim): ctx = cpu_target.target_context return ctx.calc_array_sizeof(ndim)
null
null
null
What does this function do?
def dup_jacobi(n, a, b, K): seq = [[K.one], [(((a + b) + K(2)) / K(2)), ((a - b) / K(2))]] for i in range(2, (n + 1)): den = ((K(i) * ((a + b) + i)) * (((a + b) + (K(2) * i)) - K(2))) f0 = (((((a + b) + (K(2) * i)) - K.one) * ((a * a) - (b * b))) / (K(2) * den)) f1 = ((((((a + b) + (K(2) * i)) - K.one) * (((a +...
null
null
null
Low-level implementation of Jacobi polynomials.
pcsd
def dup jacobi n a b K seq = [[K one] [ a + b + K 2 / K 2 a - b / K 2 ]] for i in range 2 n + 1 den = K i * a + b + i * a + b + K 2 * i - K 2 f0 = a + b + K 2 * i - K one * a * a - b * b / K 2 * den f1 = a + b + K 2 * i - K one * a + b + K 2 * i - K 2 * a + b + K 2 * i / K 2 * den f2 = a + i - K one * b + i - K one * a...
10816
def dup_jacobi(n, a, b, K): seq = [[K.one], [(((a + b) + K(2)) / K(2)), ((a - b) / K(2))]] for i in range(2, (n + 1)): den = ((K(i) * ((a + b) + i)) * (((a + b) + (K(2) * i)) - K(2))) f0 = (((((a + b) + (K(2) * i)) - K.one) * ((a * a) - (b * b))) / (K(2) * den)) f1 = ((((((a + b) + (K(2) * i)) - K.one) * (((a +...
Low-level implementation of Jacobi polynomials.
low - level implementation of jacobi polynomials .
Question: What does this function do? Code: def dup_jacobi(n, a, b, K): seq = [[K.one], [(((a + b) + K(2)) / K(2)), ((a - b) / K(2))]] for i in range(2, (n + 1)): den = ((K(i) * ((a + b) + i)) * (((a + b) + (K(2) * i)) - K(2))) f0 = (((((a + b) + (K(2) * i)) - K.one) * ((a * a) - (b * b))) / (K(2) * den)) f1...
null
null
null
What does this function do?
def main(): module = AnsibleModule(argument_spec=dict(pn_cliusername=dict(required=False, type='str'), pn_clipassword=dict(required=False, type='str', no_log=True), pn_cliswitch=dict(required=False, type='str', default='local'), state=dict(required=True, type='str', choices=['present', 'absent', 'update']), pn_name=di...
null
null
null
This section is for argument parsing
pcsd
def main module = Ansible Module argument spec=dict pn cliusername=dict required=False type='str' pn clipassword=dict required=False type='str' no log=True pn cliswitch=dict required=False type='str' default='local' state=dict required=True type='str' choices=['present' 'absent' 'update'] pn name=dict required=True typ...
10823
def main(): module = AnsibleModule(argument_spec=dict(pn_cliusername=dict(required=False, type='str'), pn_clipassword=dict(required=False, type='str', no_log=True), pn_cliswitch=dict(required=False, type='str', default='local'), state=dict(required=True, type='str', choices=['present', 'absent', 'update']), pn_name=di...
This section is for argument parsing
this section is for argument parsing
Question: What does this function do? Code: def main(): module = AnsibleModule(argument_spec=dict(pn_cliusername=dict(required=False, type='str'), pn_clipassword=dict(required=False, type='str', no_log=True), pn_cliswitch=dict(required=False, type='str', default='local'), state=dict(required=True, type='str', choic...
null
null
null
What does this function do?
def getPathsByLists(vertexLists): vector3Lists = getVector3ListsRecursively(vertexLists) paths = [] addToPathsRecursively(paths, vector3Lists) return paths
null
null
null
Get paths by lists.
pcsd
def get Paths By Lists vertex Lists vector3Lists = get Vector3Lists Recursively vertex Lists paths = [] add To Paths Recursively paths vector3Lists return paths
10827
def getPathsByLists(vertexLists): vector3Lists = getVector3ListsRecursively(vertexLists) paths = [] addToPathsRecursively(paths, vector3Lists) return paths
Get paths by lists.
get paths by lists .
Question: What does this function do? Code: def getPathsByLists(vertexLists): vector3Lists = getVector3ListsRecursively(vertexLists) paths = [] addToPathsRecursively(paths, vector3Lists) return paths
null
null
null
What does this function do?
def get_bracket_regions(settings, minimap): styles = settings.get('bracket_styles', DEFAULT_STYLES) icon_path = 'Packages/BracketHighlighter/icons' for (key, value) in DEFAULT_STYLES.items(): if (key not in styles): styles[key] = value continue for (k, v) in value.items(): if (k not in styles[key]): ...
null
null
null
Get styled regions for brackets to use.
pcsd
def get bracket regions settings minimap styles = settings get 'bracket styles' DEFAULT STYLES icon path = 'Packages/Bracket Highlighter/icons' for key value in DEFAULT STYLES items if key not in styles styles[key] = value continue for k v in value items if k not in styles[key] styles[key][k] = v default settings = sty...
10829
def get_bracket_regions(settings, minimap): styles = settings.get('bracket_styles', DEFAULT_STYLES) icon_path = 'Packages/BracketHighlighter/icons' for (key, value) in DEFAULT_STYLES.items(): if (key not in styles): styles[key] = value continue for (k, v) in value.items(): if (k not in styles[key]): ...
Get styled regions for brackets to use.
get styled regions for brackets to use .
Question: What does this function do? Code: def get_bracket_regions(settings, minimap): styles = settings.get('bracket_styles', DEFAULT_STYLES) icon_path = 'Packages/BracketHighlighter/icons' for (key, value) in DEFAULT_STYLES.items(): if (key not in styles): styles[key] = value continue for (k, v) in v...
null
null
null
What does this function do?
def addToThreadsFromLoop(extrusionHalfWidth, gcodeType, loop, oldOrderedLocation, skein): loop = getLoopStartingNearest(extrusionHalfWidth, oldOrderedLocation.dropAxis(2), loop) oldOrderedLocation.x = loop[0].real oldOrderedLocation.y = loop[0].imag gcodeTypeStart = gcodeType if isWiddershins(loop): skein.distan...
null
null
null
Add to threads from the last location from loop.
pcsd
def add To Threads From Loop extrusion Half Width gcode Type loop old Ordered Location skein loop = get Loop Starting Nearest extrusion Half Width old Ordered Location drop Axis 2 loop old Ordered Location x = loop[0] real old Ordered Location y = loop[0] imag gcode Type Start = gcode Type if is Widdershins loop skein ...
10832
def addToThreadsFromLoop(extrusionHalfWidth, gcodeType, loop, oldOrderedLocation, skein): loop = getLoopStartingNearest(extrusionHalfWidth, oldOrderedLocation.dropAxis(2), loop) oldOrderedLocation.x = loop[0].real oldOrderedLocation.y = loop[0].imag gcodeTypeStart = gcodeType if isWiddershins(loop): skein.distan...
Add to threads from the last location from loop.
add to threads from the last location from loop .
Question: What does this function do? Code: def addToThreadsFromLoop(extrusionHalfWidth, gcodeType, loop, oldOrderedLocation, skein): loop = getLoopStartingNearest(extrusionHalfWidth, oldOrderedLocation.dropAxis(2), loop) oldOrderedLocation.x = loop[0].real oldOrderedLocation.y = loop[0].imag gcodeTypeStart = gc...
null
null
null
What does this function do?
@testing.requires_testing_data def test_tfr_with_inverse_operator(): (tmin, tmax, event_id) = ((-0.2), 0.5, 1) raw = read_raw_fif(fname_data) events = find_events(raw, stim_channel='STI 014') inverse_operator = read_inverse_operator(fname_inv) inv = prepare_inverse_operator(inverse_operator, nave=1, lambda2=(1.0 /...
null
null
null
Test time freq with MNE inverse computation.
pcsd
@testing requires testing data def test tfr with inverse operator tmin tmax event id = -0 2 0 5 1 raw = read raw fif fname data events = find events raw stim channel='STI 014' inverse operator = read inverse operator fname inv inv = prepare inverse operator inverse operator nave=1 lambda2= 1 0 / 9 0 method='d SPM' raw ...
10835
@testing.requires_testing_data def test_tfr_with_inverse_operator(): (tmin, tmax, event_id) = ((-0.2), 0.5, 1) raw = read_raw_fif(fname_data) events = find_events(raw, stim_channel='STI 014') inverse_operator = read_inverse_operator(fname_inv) inv = prepare_inverse_operator(inverse_operator, nave=1, lambda2=(1.0 /...
Test time freq with MNE inverse computation.
test time freq with mne inverse computation .
Question: What does this function do? Code: @testing.requires_testing_data def test_tfr_with_inverse_operator(): (tmin, tmax, event_id) = ((-0.2), 0.5, 1) raw = read_raw_fif(fname_data) events = find_events(raw, stim_channel='STI 014') inverse_operator = read_inverse_operator(fname_inv) inv = prepare_inverse_op...
null
null
null
What does this function do?
def p_declaration_list_1(t): pass
null
null
null
declaration_list : declaration
pcsd
def p declaration list 1 t pass
10836
def p_declaration_list_1(t): pass
declaration_list : declaration
declaration _ list : declaration
Question: What does this function do? Code: def p_declaration_list_1(t): pass
null
null
null
What does this function do?
def _parse_signature(func): if hasattr(func, 'im_func'): func = func.im_func parse = _signature_cache.get(func) if (parse is not None): return parse (positional, vararg_var, kwarg_var, defaults) = inspect.getargspec(func) defaults = (defaults or ()) arg_count = len(positional) arguments = [] for (idx, name)...
null
null
null
Return a signature object for the function.
pcsd
def parse signature func if hasattr func 'im func' func = func im func parse = signature cache get func if parse is not None return parse positional vararg var kwarg var defaults = inspect getargspec func defaults = defaults or arg count = len positional arguments = [] for idx name in enumerate positional if isinstance...
10839
def _parse_signature(func): if hasattr(func, 'im_func'): func = func.im_func parse = _signature_cache.get(func) if (parse is not None): return parse (positional, vararg_var, kwarg_var, defaults) = inspect.getargspec(func) defaults = (defaults or ()) arg_count = len(positional) arguments = [] for (idx, name)...
Return a signature object for the function.
return a signature object for the function .
Question: What does this function do? Code: def _parse_signature(func): if hasattr(func, 'im_func'): func = func.im_func parse = _signature_cache.get(func) if (parse is not None): return parse (positional, vararg_var, kwarg_var, defaults) = inspect.getargspec(func) defaults = (defaults or ()) arg_count = l...
null
null
null
What does this function do?
@pytest.mark.django_db @pytest.mark.parametrize('show_all_pages', [True, False]) def test_page_links_plugin_hide_expired(show_all_pages): context = get_jinja_context() page = create_page(eternal=True, visible_in_menu=True) another_page = create_page(eternal=True, visible_in_menu=True) plugin = PageLinksPlugin({'pag...
null
null
null
Make sure plugin correctly filters out expired pages based on plugin configuration
pcsd
@pytest mark django db @pytest mark parametrize 'show all pages' [True False] def test page links plugin hide expired show all pages context = get jinja context page = create page eternal=True visible in menu=True another page = create page eternal=True visible in menu=True plugin = Page Links Plugin {'pages' [page pk ...
10843
@pytest.mark.django_db @pytest.mark.parametrize('show_all_pages', [True, False]) def test_page_links_plugin_hide_expired(show_all_pages): context = get_jinja_context() page = create_page(eternal=True, visible_in_menu=True) another_page = create_page(eternal=True, visible_in_menu=True) plugin = PageLinksPlugin({'pag...
Make sure plugin correctly filters out expired pages based on plugin configuration
make sure plugin correctly filters out expired pages based on plugin configuration
Question: What does this function do? Code: @pytest.mark.django_db @pytest.mark.parametrize('show_all_pages', [True, False]) def test_page_links_plugin_hide_expired(show_all_pages): context = get_jinja_context() page = create_page(eternal=True, visible_in_menu=True) another_page = create_page(eternal=True, visibl...
null
null
null
What does this function do?
def _track_certificate_events(request, context, course, user, user_certificate): course_key = course.location.course_key if ('evidence_visit' in request.GET): badge_class = get_completion_badge(course_key, user) if (not badge_class): log.warning('Visit to evidence URL for badge, but badges not configured for c...
null
null
null
Tracks web certificate view related events.
pcsd
def track certificate events request context course user user certificate course key = course location course key if 'evidence visit' in request GET badge class = get completion badge course key user if not badge class log warning 'Visit to evidence URL for badge but badges not configured for course "%s"' course key ba...
10844
def _track_certificate_events(request, context, course, user, user_certificate): course_key = course.location.course_key if ('evidence_visit' in request.GET): badge_class = get_completion_badge(course_key, user) if (not badge_class): log.warning('Visit to evidence URL for badge, but badges not configured for c...
Tracks web certificate view related events.
tracks web certificate view related events .
Question: What does this function do? Code: def _track_certificate_events(request, context, course, user, user_certificate): course_key = course.location.course_key if ('evidence_visit' in request.GET): badge_class = get_completion_badge(course_key, user) if (not badge_class): log.warning('Visit to evidence...
null
null
null
What does this function do?
def isValid(text): return bool(re.search('\\bemail\\b', text, re.IGNORECASE))
null
null
null
Returns True if the input is related to email. Arguments: text -- user-input, typically transcribed speech
pcsd
def is Valid text return bool re search '\\bemail\\b' text re IGNORECASE
10852
def isValid(text): return bool(re.search('\\bemail\\b', text, re.IGNORECASE))
Returns True if the input is related to email. Arguments: text -- user-input, typically transcribed speech
returns true if the input is related to email .
Question: What does this function do? Code: def isValid(text): return bool(re.search('\\bemail\\b', text, re.IGNORECASE))
null
null
null
What does this function do?
def unquote(s): mychr = chr myatoi = int list = s.split('_') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend((mychr(myatoi(item[:2], 16)) + item[2:])) except ValueError: myappend(('_' + item)) else: myappend(('_' + item)) return ''.join(res)
null
null
null
Undo the effects of quote(). Based heavily on urllib.unquote().
pcsd
def unquote s mychr = chr myatoi = int list = s split ' ' res = [list[0]] myappend = res append del list[0] for item in list if item[1 2] try myappend mychr myatoi item[ 2] 16 + item[2 ] except Value Error myappend ' ' + item else myappend ' ' + item return '' join res
10861
def unquote(s): mychr = chr myatoi = int list = s.split('_') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend((mychr(myatoi(item[:2], 16)) + item[2:])) except ValueError: myappend(('_' + item)) else: myappend(('_' + item)) return ''.join(res)
Undo the effects of quote(). Based heavily on urllib.unquote().
undo the effects of quote ( ) .
Question: What does this function do? Code: def unquote(s): mychr = chr myatoi = int list = s.split('_') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend((mychr(myatoi(item[:2], 16)) + item[2:])) except ValueError: myappend(('_' + item)) else: ...
null
null
null
What does this function do?
def indexmarkup_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): env = inliner.document.settings.env if (not typ): typ = env.config.default_role else: typ = typ.lower() (has_explicit_title, title, target) = split_explicit_title(text) title = utils.unescape(title) target = utils.unescape(targ...
null
null
null
Role for PEP/RFC references that generate an index entry.
pcsd
def indexmarkup role typ rawtext text lineno inliner options={} content=[] env = inliner document settings env if not typ typ = env config default role else typ = typ lower has explicit title title target = split explicit title text title = utils unescape title target = utils unescape target targetid = 'index-%s' % env...
10874
def indexmarkup_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): env = inliner.document.settings.env if (not typ): typ = env.config.default_role else: typ = typ.lower() (has_explicit_title, title, target) = split_explicit_title(text) title = utils.unescape(title) target = utils.unescape(targ...
Role for PEP/RFC references that generate an index entry.
role for pep / rfc references that generate an index entry .
Question: What does this function do? Code: def indexmarkup_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): env = inliner.document.settings.env if (not typ): typ = env.config.default_role else: typ = typ.lower() (has_explicit_title, title, target) = split_explicit_title(text) title = util...
null
null
null
What does this function do?
def _check_guts_eq(attr, old, new, last_build): if (old != new): logger.info('Building because %s changed', attr) return True return False
null
null
null
rebuild is required if values differ
pcsd
def check guts eq attr old new last build if old != new logger info 'Building because %s changed' attr return True return False
10884
def _check_guts_eq(attr, old, new, last_build): if (old != new): logger.info('Building because %s changed', attr) return True return False
rebuild is required if values differ
rebuild is required if values differ
Question: What does this function do? Code: def _check_guts_eq(attr, old, new, last_build): if (old != new): logger.info('Building because %s changed', attr) return True return False
null
null
null
What does this function do?
def find_executable_linenos(filename): try: prog = open(filename, 'rU').read() except IOError as err: print >>sys.stderr, ('Not printing coverage data for %r: %s' % (filename, err)) return {} code = compile(prog, filename, 'exec') strs = find_strings(filename) return find_lines(code, strs)
null
null
null
Return dict where keys are line numbers in the line number table.
pcsd
def find executable linenos filename try prog = open filename 'r U' read except IO Error as err print >>sys stderr 'Not printing coverage data for %r %s' % filename err return {} code = compile prog filename 'exec' strs = find strings filename return find lines code strs
10889
def find_executable_linenos(filename): try: prog = open(filename, 'rU').read() except IOError as err: print >>sys.stderr, ('Not printing coverage data for %r: %s' % (filename, err)) return {} code = compile(prog, filename, 'exec') strs = find_strings(filename) return find_lines(code, strs)
Return dict where keys are line numbers in the line number table.
return dict where keys are line numbers in the line number table .
Question: What does this function do? Code: def find_executable_linenos(filename): try: prog = open(filename, 'rU').read() except IOError as err: print >>sys.stderr, ('Not printing coverage data for %r: %s' % (filename, err)) return {} code = compile(prog, filename, 'exec') strs = find_strings(filename) r...
null
null
null
What does this function do?
def XcodeVersion(): global XCODE_VERSION_CACHE if XCODE_VERSION_CACHE: return XCODE_VERSION_CACHE try: version_list = GetStdout(['xcodebuild', '-version']).splitlines() if (len(version_list) < 2): raise GypError('xcodebuild returned unexpected results') except: version = CLTVersion() if version: ver...
null
null
null
Returns a tuple of version and build version of installed Xcode.
pcsd
def Xcode Version global XCODE VERSION CACHE if XCODE VERSION CACHE return XCODE VERSION CACHE try version list = Get Stdout ['xcodebuild' '-version'] splitlines if len version list < 2 raise Gyp Error 'xcodebuild returned unexpected results' except version = CLT Version if version version = re match ' \\d\\ \\d\\ ?\\d...
10891
def XcodeVersion(): global XCODE_VERSION_CACHE if XCODE_VERSION_CACHE: return XCODE_VERSION_CACHE try: version_list = GetStdout(['xcodebuild', '-version']).splitlines() if (len(version_list) < 2): raise GypError('xcodebuild returned unexpected results') except: version = CLTVersion() if version: ver...
Returns a tuple of version and build version of installed Xcode.
returns a tuple of version and build version of installed xcode .
Question: What does this function do? Code: def XcodeVersion(): global XCODE_VERSION_CACHE if XCODE_VERSION_CACHE: return XCODE_VERSION_CACHE try: version_list = GetStdout(['xcodebuild', '-version']).splitlines() if (len(version_list) < 2): raise GypError('xcodebuild returned unexpected results') except...
null
null
null
What does this function do?
def form_hmac(form): data = [] for bf in form: if (form.empty_permitted and (not form.has_changed())): value = (bf.data or '') else: value = (bf.field.clean(bf.data) or '') if isinstance(value, basestring): value = value.strip() data.append((bf.name, value)) pickled = pickle.dumps(data, pickle.HIGHE...
null
null
null
Calculates a security hash for the given Form instance.
pcsd
def form hmac form data = [] for bf in form if form empty permitted and not form has changed value = bf data or '' else value = bf field clean bf data or '' if isinstance value basestring value = value strip data append bf name value pickled = pickle dumps data pickle HIGHEST PROTOCOL key salt = 'django contrib formtoo...
10897
def form_hmac(form): data = [] for bf in form: if (form.empty_permitted and (not form.has_changed())): value = (bf.data or '') else: value = (bf.field.clean(bf.data) or '') if isinstance(value, basestring): value = value.strip() data.append((bf.name, value)) pickled = pickle.dumps(data, pickle.HIGHE...
Calculates a security hash for the given Form instance.
calculates a security hash for the given form instance .
Question: What does this function do? Code: def form_hmac(form): data = [] for bf in form: if (form.empty_permitted and (not form.has_changed())): value = (bf.data or '') else: value = (bf.field.clean(bf.data) or '') if isinstance(value, basestring): value = value.strip() data.append((bf.name, val...
null
null
null
What does this function do?
def disciplinary_type(): mode = session.s3.hrm.mode def prep(r): if (mode is not None): auth.permission.fail() return True s3.prep = prep output = s3_rest_controller() return output
null
null
null
Disciplinary Type Controller
pcsd
def disciplinary type mode = session s3 hrm mode def prep r if mode is not None auth permission fail return True s3 prep = prep output = s3 rest controller return output
10898
def disciplinary_type(): mode = session.s3.hrm.mode def prep(r): if (mode is not None): auth.permission.fail() return True s3.prep = prep output = s3_rest_controller() return output
Disciplinary Type Controller
disciplinary type controller
Question: What does this function do? Code: def disciplinary_type(): mode = session.s3.hrm.mode def prep(r): if (mode is not None): auth.permission.fail() return True s3.prep = prep output = s3_rest_controller() return output
null
null
null
What does this function do?
def LocalGroupEnum(): resume = 0 nmembers = 0 while 1: (data, total, resume) = win32net.NetLocalGroupEnum(server, 1, resume) for group in data: verbose(('Found group %(name)s:%(comment)s ' % group)) memberresume = 0 while 1: (memberdata, total, memberresume) = win32net.NetLocalGroupGetMembers(server...
null
null
null
Enumerates all the local groups
pcsd
def Local Group Enum resume = 0 nmembers = 0 while 1 data total resume = win32net Net Local Group Enum server 1 resume for group in data verbose 'Found group % name s % comment s ' % group memberresume = 0 while 1 memberdata total memberresume = win32net Net Local Group Get Members server group['name'] 2 resume for mem...
10899
def LocalGroupEnum(): resume = 0 nmembers = 0 while 1: (data, total, resume) = win32net.NetLocalGroupEnum(server, 1, resume) for group in data: verbose(('Found group %(name)s:%(comment)s ' % group)) memberresume = 0 while 1: (memberdata, total, memberresume) = win32net.NetLocalGroupGetMembers(server...
Enumerates all the local groups
enumerates all the local groups
Question: What does this function do? Code: def LocalGroupEnum(): resume = 0 nmembers = 0 while 1: (data, total, resume) = win32net.NetLocalGroupEnum(server, 1, resume) for group in data: verbose(('Found group %(name)s:%(comment)s ' % group)) memberresume = 0 while 1: (memberdata, total, memberre...
null
null
null
What does this function do?
def get_app_qt4(*args, **kwargs): from IPython.external.qt_for_kernel import QtGui app = QtGui.QApplication.instance() if (app is None): if (not args): args = ([''],) app = QtGui.QApplication(*args, **kwargs) return app
null
null
null
Create a new qt4 app or return an existing one.
pcsd
def get app qt4 *args **kwargs from I Python external qt for kernel import Qt Gui app = Qt Gui Q Application instance if app is None if not args args = [''] app = Qt Gui Q Application *args **kwargs return app
10901
def get_app_qt4(*args, **kwargs): from IPython.external.qt_for_kernel import QtGui app = QtGui.QApplication.instance() if (app is None): if (not args): args = ([''],) app = QtGui.QApplication(*args, **kwargs) return app
Create a new qt4 app or return an existing one.
create a new qt4 app or return an existing one .
Question: What does this function do? Code: def get_app_qt4(*args, **kwargs): from IPython.external.qt_for_kernel import QtGui app = QtGui.QApplication.instance() if (app is None): if (not args): args = ([''],) app = QtGui.QApplication(*args, **kwargs) return app
null
null
null
What does this function do?
@command('(mv|sw)\\s*(\\d{1,4})\\s*[\\s,]\\s*(\\d{1,4})') def songlist_mv_sw(action, a, b): (i, j) = ((int(a) - 1), (int(b) - 1)) if (action == 'mv'): g.model.songs.insert(j, g.model.songs.pop(i)) g.message = (util.F('song move') % (g.model[j].title, b)) elif (action == 'sw'): (g.model[i], g.model[j]) = (g.mod...
null
null
null
Move a song or swap two songs.
pcsd
@command ' mv|sw \\s* \\d{1 4} \\s*[\\s ]\\s* \\d{1 4} ' def songlist mv sw action a b i j = int a - 1 int b - 1 if action == 'mv' g model songs insert j g model songs pop i g message = util F 'song move' % g model[j] title b elif action == 'sw' g model[i] g model[j] = g model[j] g model[i] g message = util F 'song sw'...
10902
@command('(mv|sw)\\s*(\\d{1,4})\\s*[\\s,]\\s*(\\d{1,4})') def songlist_mv_sw(action, a, b): (i, j) = ((int(a) - 1), (int(b) - 1)) if (action == 'mv'): g.model.songs.insert(j, g.model.songs.pop(i)) g.message = (util.F('song move') % (g.model[j].title, b)) elif (action == 'sw'): (g.model[i], g.model[j]) = (g.mod...
Move a song or swap two songs.
move a song or swap two songs .
Question: What does this function do? Code: @command('(mv|sw)\\s*(\\d{1,4})\\s*[\\s,]\\s*(\\d{1,4})') def songlist_mv_sw(action, a, b): (i, j) = ((int(a) - 1), (int(b) - 1)) if (action == 'mv'): g.model.songs.insert(j, g.model.songs.pop(i)) g.message = (util.F('song move') % (g.model[j].title, b)) elif (actio...
null
null
null
What does this function do?
@bp.route('/delete', methods=['GET', 'POST']) @require_login def delete(): return 'not ready'
null
null
null
Delete the account. This will not delete the data related to the user, such as topics and replies.
pcsd
@bp route '/delete' methods=['GET' 'POST'] @require login def delete return 'not ready'
10908
@bp.route('/delete', methods=['GET', 'POST']) @require_login def delete(): return 'not ready'
Delete the account. This will not delete the data related to the user, such as topics and replies.
delete the account .
Question: What does this function do? Code: @bp.route('/delete', methods=['GET', 'POST']) @require_login def delete(): return 'not ready'