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 echo_to_hierarchy(text_object): parent = text_object while parent._parent: parent = parent._parent def _do_print(text_object, indent=''): 'prints recursively.' debug((indent + as_unicode(text_object))) try: for child in text_object._children: _do_print(child, indent=(indent + ' ')) except Attri...
null
null
null
Outputs the given \'text_object\' and its children hierarchically.
pcsd
def echo to hierarchy text object parent = text object while parent parent parent = parent parent def do print text object indent='' 'prints recursively ' debug indent + as unicode text object try for child in text object children do print child indent= indent + ' ' except Attribute Error pass do print parent
3082
def echo_to_hierarchy(text_object): parent = text_object while parent._parent: parent = parent._parent def _do_print(text_object, indent=''): 'prints recursively.' debug((indent + as_unicode(text_object))) try: for child in text_object._children: _do_print(child, indent=(indent + ' ')) except Attri...
Outputs the given \'text_object\' and its children hierarchically.
outputs the given text _ object and its children hierarchically .
Question: What does this function do? Code: def echo_to_hierarchy(text_object): parent = text_object while parent._parent: parent = parent._parent def _do_print(text_object, indent=''): 'prints recursively.' debug((indent + as_unicode(text_object))) try: for child in text_object._children: _do_prin...
null
null
null
What does this function do?
@with_setup(state.setup, state.teardown) def test_subunit_output_with_one_error(): state.expect = [Includes({'status': 'success', 'details': Keys('stdout', 'stderr', 'steps')}), Includes({'status': 'fail', 'details': Keys('stdout', 'stderr', 'traceback', 'steps')})] runner = Runner(feature_name('error_traceback'), en...
null
null
null
Test Subunit output with one error
pcsd
@with setup state setup state teardown def test subunit output with one error state expect = [Includes {'status' 'success' 'details' Keys 'stdout' 'stderr' 'steps' } Includes {'status' 'fail' 'details' Keys 'stdout' 'stderr' 'traceback' 'steps' } ] runner = Runner feature name 'error traceback' enable subunit=True runn...
3088
@with_setup(state.setup, state.teardown) def test_subunit_output_with_one_error(): state.expect = [Includes({'status': 'success', 'details': Keys('stdout', 'stderr', 'steps')}), Includes({'status': 'fail', 'details': Keys('stdout', 'stderr', 'traceback', 'steps')})] runner = Runner(feature_name('error_traceback'), en...
Test Subunit output with one error
test subunit output with one error
Question: What does this function do? Code: @with_setup(state.setup, state.teardown) def test_subunit_output_with_one_error(): state.expect = [Includes({'status': 'success', 'details': Keys('stdout', 'stderr', 'steps')}), Includes({'status': 'fail', 'details': Keys('stdout', 'stderr', 'traceback', 'steps')})] runn...
null
null
null
What does this function do?
def exactly_n(l, n=1): i = iter(l) return (all((any(i) for j in range(n))) and (not any(i)))
null
null
null
Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0).
pcsd
def exactly n l n=1 i = iter l return all any i for j in range n and not any i
3089
def exactly_n(l, n=1): i = iter(l) return (all((any(i) for j in range(n))) and (not any(i)))
Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0).
tests that exactly n items in an iterable are " truthy " ( neither none ,
Question: What does this function do? Code: def exactly_n(l, n=1): i = iter(l) return (all((any(i) for j in range(n))) and (not any(i)))
null
null
null
What does this function do?
def _net_lock(network_id): lock_name = ('dhcp-agent-network-lock-%s' % network_id) return lockutils.lock(lock_name, utils.SYNCHRONIZED_PREFIX)
null
null
null
Returns a context manager lock based on network_id.
pcsd
def net lock network id lock name = 'dhcp-agent-network-lock-%s' % network id return lockutils lock lock name utils SYNCHRONIZED PREFIX
3095
def _net_lock(network_id): lock_name = ('dhcp-agent-network-lock-%s' % network_id) return lockutils.lock(lock_name, utils.SYNCHRONIZED_PREFIX)
Returns a context manager lock based on network_id.
returns a context manager lock based on network _ id .
Question: What does this function do? Code: def _net_lock(network_id): lock_name = ('dhcp-agent-network-lock-%s' % network_id) return lockutils.lock(lock_name, utils.SYNCHRONIZED_PREFIX)
null
null
null
What does this function do?
def make_pretty_name(method): meth_pieces = [method.__name__] if (hasattr(method, '__self__') and (method.__self__ is not None)): try: meth_pieces.insert(0, method.__self__.__class__.__name__) except AttributeError: pass return '.'.join(meth_pieces)
null
null
null
Makes a pretty name for a function/method.
pcsd
def make pretty name method meth pieces = [method name ] if hasattr method ' self ' and method self is not None try meth pieces insert 0 method self class name except Attribute Error pass return ' ' join meth pieces
3101
def make_pretty_name(method): meth_pieces = [method.__name__] if (hasattr(method, '__self__') and (method.__self__ is not None)): try: meth_pieces.insert(0, method.__self__.__class__.__name__) except AttributeError: pass return '.'.join(meth_pieces)
Makes a pretty name for a function/method.
makes a pretty name for a function / method .
Question: What does this function do? Code: def make_pretty_name(method): meth_pieces = [method.__name__] if (hasattr(method, '__self__') and (method.__self__ is not None)): try: meth_pieces.insert(0, method.__self__.__class__.__name__) except AttributeError: pass return '.'.join(meth_pieces)
null
null
null
What does this function do?
@image_comparison(baseline_images=[u'tight_layout8']) def test_tight_layout8(): fig = plt.figure() fig.set_tight_layout({u'pad': 0.1}) ax = fig.add_subplot(111) example_plot(ax, fontsize=24)
null
null
null
Test automatic use of tight_layout
pcsd
@image comparison baseline images=[u'tight layout8'] def test tight layout8 fig = plt figure fig set tight layout {u'pad' 0 1} ax = fig add subplot 111 example plot ax fontsize=24
3105
@image_comparison(baseline_images=[u'tight_layout8']) def test_tight_layout8(): fig = plt.figure() fig.set_tight_layout({u'pad': 0.1}) ax = fig.add_subplot(111) example_plot(ax, fontsize=24)
Test automatic use of tight_layout
test automatic use of tight _ layout
Question: What does this function do? Code: @image_comparison(baseline_images=[u'tight_layout8']) def test_tight_layout8(): fig = plt.figure() fig.set_tight_layout({u'pad': 0.1}) ax = fig.add_subplot(111) example_plot(ax, fontsize=24)
null
null
null
What does this function do?
@task(ignore_result=False) def check_celery(): pass
null
null
null
Dummy celery task to check that everything runs smoothly.
pcsd
@task ignore result=False def check celery pass
3106
@task(ignore_result=False) def check_celery(): pass
Dummy celery task to check that everything runs smoothly.
dummy celery task to check that everything runs smoothly .
Question: What does this function do? Code: @task(ignore_result=False) def check_celery(): pass
null
null
null
What does this function do?
def gitCommit(name): commit = check_output(['git', 'show', name], universal_newlines=True).split('\n')[0] assert (commit[:7] == 'commit ') return commit[7:]
null
null
null
Return the commit ID for the given name.
pcsd
def git Commit name commit = check output ['git' 'show' name] universal newlines=True split ' ' [0] assert commit[ 7] == 'commit ' return commit[7 ]
3118
def gitCommit(name): commit = check_output(['git', 'show', name], universal_newlines=True).split('\n')[0] assert (commit[:7] == 'commit ') return commit[7:]
Return the commit ID for the given name.
return the commit id for the given name .
Question: What does this function do? Code: def gitCommit(name): commit = check_output(['git', 'show', name], universal_newlines=True).split('\n')[0] assert (commit[:7] == 'commit ') return commit[7:]
null
null
null
What does this function do?
@gen.engine def RunOnce(client, job, callback): merged_store = ObjectStore.GetInstance(logs_util.UserAnalyticsLogsPaths.MERGED_LOGS_BUCKET) start_date = options.options.start_date if options.options.smart_scan: last_run = (yield gen.Task(job.FindLastSuccess, with_payload_key='stats.last_day')) if (last_run is No...
null
null
null
Get list of files and call processing function.
pcsd
@gen engine def Run Once client job callback merged store = Object Store Get Instance logs util User Analytics Logs Paths MERGED LOGS BUCKET start date = options options start date if options options smart scan last run = yield gen Task job Find Last Success with payload key='stats last day' if last run is None logging...
3123
@gen.engine def RunOnce(client, job, callback): merged_store = ObjectStore.GetInstance(logs_util.UserAnalyticsLogsPaths.MERGED_LOGS_BUCKET) start_date = options.options.start_date if options.options.smart_scan: last_run = (yield gen.Task(job.FindLastSuccess, with_payload_key='stats.last_day')) if (last_run is No...
Get list of files and call processing function.
get list of files and call processing function .
Question: What does this function do? Code: @gen.engine def RunOnce(client, job, callback): merged_store = ObjectStore.GetInstance(logs_util.UserAnalyticsLogsPaths.MERGED_LOGS_BUCKET) start_date = options.options.start_date if options.options.smart_scan: last_run = (yield gen.Task(job.FindLastSuccess, with_payl...
null
null
null
What does this function do?
def new_message(from_email, to_email): from email.mime.text import MIMEText msg = MIMEText('Testing') msg['Subject'] = uuid.uuid4().hex[:8] msg['From'] = from_email msg['To'] = to_email return (msg.as_string(), msg['subject'])
null
null
null
Creates an email (headers & body) with a random subject
pcsd
def new message from email to email from email mime text import MIME Text msg = MIME Text 'Testing' msg['Subject'] = uuid uuid4 hex[ 8] msg['From'] = from email msg['To'] = to email return msg as string msg['subject']
3126
def new_message(from_email, to_email): from email.mime.text import MIMEText msg = MIMEText('Testing') msg['Subject'] = uuid.uuid4().hex[:8] msg['From'] = from_email msg['To'] = to_email return (msg.as_string(), msg['subject'])
Creates an email (headers & body) with a random subject
creates an email with a random subject
Question: What does this function do? Code: def new_message(from_email, to_email): from email.mime.text import MIMEText msg = MIMEText('Testing') msg['Subject'] = uuid.uuid4().hex[:8] msg['From'] = from_email msg['To'] = to_email return (msg.as_string(), msg['subject'])
null
null
null
What does this function do?
@contextmanager def random_seed(seed): state = random.getstate() random.seed(seed) try: (yield) finally: random.setstate(state)
null
null
null
Temporarily change the seed of the random number generator.
pcsd
@contextmanager def random seed seed state = random getstate random seed seed try yield finally random setstate state
3128
@contextmanager def random_seed(seed): state = random.getstate() random.seed(seed) try: (yield) finally: random.setstate(state)
Temporarily change the seed of the random number generator.
temporarily change the seed of the random number generator .
Question: What does this function do? Code: @contextmanager def random_seed(seed): state = random.getstate() random.seed(seed) try: (yield) finally: random.setstate(state)
null
null
null
What does this function do?
def _hash_of_file(path, algorithm): with open(path, 'rb') as archive: hash = hashlib.new(algorithm) for chunk in read_chunks(archive): hash.update(chunk) return hash.hexdigest()
null
null
null
Return the hash digest of a file.
pcsd
def hash of file path algorithm with open path 'rb' as archive hash = hashlib new algorithm for chunk in read chunks archive hash update chunk return hash hexdigest
3131
def _hash_of_file(path, algorithm): with open(path, 'rb') as archive: hash = hashlib.new(algorithm) for chunk in read_chunks(archive): hash.update(chunk) return hash.hexdigest()
Return the hash digest of a file.
return the hash digest of a file .
Question: What does this function do? Code: def _hash_of_file(path, algorithm): with open(path, 'rb') as archive: hash = hashlib.new(algorithm) for chunk in read_chunks(archive): hash.update(chunk) return hash.hexdigest()
null
null
null
What does this function do?
def longToString(l): result = '' while (l > 0L): result = (chr((l % 256)) + result) l = (l / 256L) return result
null
null
null
Convert long to digest
pcsd
def long To String l result = '' while l > 0L result = chr l % 256 + result l = l / 256L return result
3133
def longToString(l): result = '' while (l > 0L): result = (chr((l % 256)) + result) l = (l / 256L) return result
Convert long to digest
convert long to digest
Question: What does this function do? Code: def longToString(l): result = '' while (l > 0L): result = (chr((l % 256)) + result) l = (l / 256L) return result
null
null
null
What does this function do?
def list_queues(): queues = _list_queues() return queues
null
null
null
Return a list of Salt Queues on the Salt Master
pcsd
def list queues queues = list queues return queues
3139
def list_queues(): queues = _list_queues() return queues
Return a list of Salt Queues on the Salt Master
return a list of salt queues on the salt master
Question: What does this function do? Code: def list_queues(): queues = _list_queues() return queues
null
null
null
What does this function do?
def rotate_token(request): request.META.update({u'CSRF_COOKIE_USED': True, u'CSRF_COOKIE': _get_new_csrf_key()})
null
null
null
Changes the CSRF token in use for a request - should be done on login for security purposes.
pcsd
def rotate token request request META update {u'CSRF COOKIE USED' True u'CSRF COOKIE' get new csrf key }
3149
def rotate_token(request): request.META.update({u'CSRF_COOKIE_USED': True, u'CSRF_COOKIE': _get_new_csrf_key()})
Changes the CSRF token in use for a request - should be done on login for security purposes.
changes the csrf token in use for a request - should be done on login for security purposes .
Question: What does this function do? Code: def rotate_token(request): request.META.update({u'CSRF_COOKIE_USED': True, u'CSRF_COOKIE': _get_new_csrf_key()})
null
null
null
What does this function do?
def only_ci(decorated_func): @wraps(decorated_func) def _inner_func(*args, **kwds): if is_running_on_ci(): return decorated_func(*args, **kwds) return _inner_func
null
null
null
This decorator runs the function that\'s being decorated only if the code is being run in CI environment.
pcsd
def only ci decorated func @wraps decorated func def inner func *args **kwds if is running on ci return decorated func *args **kwds return inner func
3156
def only_ci(decorated_func): @wraps(decorated_func) def _inner_func(*args, **kwds): if is_running_on_ci(): return decorated_func(*args, **kwds) return _inner_func
This decorator runs the function that\'s being decorated only if the code is being run in CI environment.
this decorator runs the function thats being decorated only if the code is being run in ci environment .
Question: What does this function do? Code: def only_ci(decorated_func): @wraps(decorated_func) def _inner_func(*args, **kwds): if is_running_on_ci(): return decorated_func(*args, **kwds) return _inner_func
null
null
null
What does this function do?
def log_buffer_contents(): return logs_buffer().contents()
null
null
null
Returns the contents of the logs buffer.
pcsd
def log buffer contents return logs buffer contents
3173
def log_buffer_contents(): return logs_buffer().contents()
Returns the contents of the logs buffer.
returns the contents of the logs buffer .
Question: What does this function do? Code: def log_buffer_contents(): return logs_buffer().contents()
null
null
null
What does this function do?
def password_change_email(user): from r2.lib.pages import PasswordChangeEmail return _system_email(user.email, PasswordChangeEmail(user=user).render(style='email'), Email.Kind.PASSWORD_CHANGE, user=user)
null
null
null
Queues a system email for a password change notification.
pcsd
def password change email user from r2 lib pages import Password Change Email return system email user email Password Change Email user=user render style='email' Email Kind PASSWORD CHANGE user=user
3179
def password_change_email(user): from r2.lib.pages import PasswordChangeEmail return _system_email(user.email, PasswordChangeEmail(user=user).render(style='email'), Email.Kind.PASSWORD_CHANGE, user=user)
Queues a system email for a password change notification.
queues a system email for a password change notification .
Question: What does this function do? Code: def password_change_email(user): from r2.lib.pages import PasswordChangeEmail return _system_email(user.email, PasswordChangeEmail(user=user).render(style='email'), Email.Kind.PASSWORD_CHANGE, user=user)
null
null
null
What does this function do?
def exit_gracefully(code=0): global RUN_CONFIG if os.path.exists(RUN_CONFIG.temp): for f in os.listdir(RUN_CONFIG.temp): os.remove((RUN_CONFIG.temp + f)) os.rmdir(RUN_CONFIG.temp) disable_monitor_mode() mac_change_back() print (((GR + ' [+]') + W) + ' quitting') print '' exit(code)
null
null
null
We may exit the program at any time. We want to remove the temp folder and any files contained within it. Removes the temp files/folder and exists with error code "code".
pcsd
def exit gracefully code=0 global RUN CONFIG if os path exists RUN CONFIG temp for f in os listdir RUN CONFIG temp os remove RUN CONFIG temp + f os rmdir RUN CONFIG temp disable monitor mode mac change back print GR + ' [+]' + W + ' quitting' print '' exit code
3183
def exit_gracefully(code=0): global RUN_CONFIG if os.path.exists(RUN_CONFIG.temp): for f in os.listdir(RUN_CONFIG.temp): os.remove((RUN_CONFIG.temp + f)) os.rmdir(RUN_CONFIG.temp) disable_monitor_mode() mac_change_back() print (((GR + ' [+]') + W) + ' quitting') print '' exit(code)
We may exit the program at any time. We want to remove the temp folder and any files contained within it. Removes the temp files/folder and exists with error code "code".
we may exit the program at any time .
Question: What does this function do? Code: def exit_gracefully(code=0): global RUN_CONFIG if os.path.exists(RUN_CONFIG.temp): for f in os.listdir(RUN_CONFIG.temp): os.remove((RUN_CONFIG.temp + f)) os.rmdir(RUN_CONFIG.temp) disable_monitor_mode() mac_change_back() print (((GR + ' [+]') + W) + ' quitting'...
null
null
null
What does this function do?
def connect_entry_signals(): post_save.connect(ping_directories_handler, sender=Entry, dispatch_uid=ENTRY_PS_PING_DIRECTORIES) post_save.connect(ping_external_urls_handler, sender=Entry, dispatch_uid=ENTRY_PS_PING_EXTERNAL_URLS) post_save.connect(flush_similar_cache_handler, sender=Entry, dispatch_uid=ENTRY_PS_FLUSH...
null
null
null
Connect all the signals on Entry model.
pcsd
def connect entry signals post save connect ping directories handler sender=Entry dispatch uid=ENTRY PS PING DIRECTORIES post save connect ping external urls handler sender=Entry dispatch uid=ENTRY PS PING EXTERNAL URLS post save connect flush similar cache handler sender=Entry dispatch uid=ENTRY PS FLUSH SIMILAR CACHE...
3184
def connect_entry_signals(): post_save.connect(ping_directories_handler, sender=Entry, dispatch_uid=ENTRY_PS_PING_DIRECTORIES) post_save.connect(ping_external_urls_handler, sender=Entry, dispatch_uid=ENTRY_PS_PING_EXTERNAL_URLS) post_save.connect(flush_similar_cache_handler, sender=Entry, dispatch_uid=ENTRY_PS_FLUSH...
Connect all the signals on Entry model.
connect all the signals on entry model .
Question: What does this function do? Code: def connect_entry_signals(): post_save.connect(ping_directories_handler, sender=Entry, dispatch_uid=ENTRY_PS_PING_DIRECTORIES) post_save.connect(ping_external_urls_handler, sender=Entry, dispatch_uid=ENTRY_PS_PING_EXTERNAL_URLS) post_save.connect(flush_similar_cache_han...
null
null
null
What does this function do?
@testing.requires_testing_data def test_cross_talk(): raw = read_crop(raw_fname, (0.0, 1.0)) raw.info['bads'] = bads sss_ctc = read_crop(sss_ctc_fname) raw_sss = maxwell_filter(raw, cross_talk=ctc_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore') assert_meg_snr(raw_sss, sss_ctc, 275.0) py_ctc...
null
null
null
Test Maxwell filter cross-talk cancellation.
pcsd
@testing requires testing data def test cross talk raw = read crop raw fname 0 0 1 0 raw info['bads'] = bads sss ctc = read crop sss ctc fname raw sss = maxwell filter raw cross talk=ctc fname origin=mf head origin regularize=None bad condition='ignore' assert meg snr raw sss sss ctc 275 0 py ctc = raw sss info['proc h...
3186
@testing.requires_testing_data def test_cross_talk(): raw = read_crop(raw_fname, (0.0, 1.0)) raw.info['bads'] = bads sss_ctc = read_crop(sss_ctc_fname) raw_sss = maxwell_filter(raw, cross_talk=ctc_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore') assert_meg_snr(raw_sss, sss_ctc, 275.0) py_ctc...
Test Maxwell filter cross-talk cancellation.
test maxwell filter cross - talk cancellation .
Question: What does this function do? Code: @testing.requires_testing_data def test_cross_talk(): raw = read_crop(raw_fname, (0.0, 1.0)) raw.info['bads'] = bads sss_ctc = read_crop(sss_ctc_fname) raw_sss = maxwell_filter(raw, cross_talk=ctc_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore') ...
null
null
null
What does this function do?
def generate_dummy_image(_unused): return ContentFile(ImageField()._make_data({'color': 'blue', 'width': 50, 'height': 50, 'format': 'PNG'}), 'test.png')
null
null
null
Used for image fields to create a sane default.
pcsd
def generate dummy image unused return Content File Image Field make data {'color' 'blue' 'width' 50 'height' 50 'format' 'PNG'} 'test png'
3191
def generate_dummy_image(_unused): return ContentFile(ImageField()._make_data({'color': 'blue', 'width': 50, 'height': 50, 'format': 'PNG'}), 'test.png')
Used for image fields to create a sane default.
used for image fields to create a sane default .
Question: What does this function do? Code: def generate_dummy_image(_unused): return ContentFile(ImageField()._make_data({'color': 'blue', 'width': 50, 'height': 50, 'format': 'PNG'}), 'test.png')
null
null
null
What does this function do?
@frappe.whitelist() def get_all_nodes(tree_method, tree_args, parent): tree_method = frappe.get_attr(tree_method) if (not (tree_method in frappe.whitelisted)): frappe.throw(_(u'Not Permitted'), frappe.PermissionError) frappe.local.form_dict = frappe._dict(json.loads(tree_args)) frappe.local.form_dict.parent = par...
null
null
null
Recursively gets all data from tree nodes
pcsd
@frappe whitelist def get all nodes tree method tree args parent tree method = frappe get attr tree method if not tree method in frappe whitelisted frappe throw u'Not Permitted' frappe Permission Error frappe local form dict = frappe dict json loads tree args frappe local form dict parent = parent data = tree method ou...
3204
@frappe.whitelist() def get_all_nodes(tree_method, tree_args, parent): tree_method = frappe.get_attr(tree_method) if (not (tree_method in frappe.whitelisted)): frappe.throw(_(u'Not Permitted'), frappe.PermissionError) frappe.local.form_dict = frappe._dict(json.loads(tree_args)) frappe.local.form_dict.parent = par...
Recursively gets all data from tree nodes
recursively gets all data from tree nodes
Question: What does this function do? Code: @frappe.whitelist() def get_all_nodes(tree_method, tree_args, parent): tree_method = frappe.get_attr(tree_method) if (not (tree_method in frappe.whitelisted)): frappe.throw(_(u'Not Permitted'), frappe.PermissionError) frappe.local.form_dict = frappe._dict(json.loads(t...
null
null
null
What does this function do?
def getAbs(value): return abs(value)
null
null
null
Get the abs.
pcsd
def get Abs value return abs value
3213
def getAbs(value): return abs(value)
Get the abs.
get the abs .
Question: What does this function do? Code: def getAbs(value): return abs(value)
null
null
null
What does this function do?
def spawn_list_stream(args, stuff=None): try: (owner, slug) = check_slug(stuff) except: (owner, slug) = get_slug() listname = '/'.join([owner, slug]) g['listname'] = listname g['keyword'] = '' g['PREFIX'] = g['cmd'] = u2str(emojize(format_prefix(listname=g['listname']))) printNicely(light_yellow('getting lis...
null
null
null
Spawn a new list stream
pcsd
def spawn list stream args stuff=None try owner slug = check slug stuff except owner slug = get slug listname = '/' join [owner slug] g['listname'] = listname g['keyword'] = '' g['PREFIX'] = g['cmd'] = u2str emojize format prefix listname=g['listname'] print Nicely light yellow 'getting list members ' t = Twitter auth=...
3217
def spawn_list_stream(args, stuff=None): try: (owner, slug) = check_slug(stuff) except: (owner, slug) = get_slug() listname = '/'.join([owner, slug]) g['listname'] = listname g['keyword'] = '' g['PREFIX'] = g['cmd'] = u2str(emojize(format_prefix(listname=g['listname']))) printNicely(light_yellow('getting lis...
Spawn a new list stream
spawn a new list stream
Question: What does this function do? Code: def spawn_list_stream(args, stuff=None): try: (owner, slug) = check_slug(stuff) except: (owner, slug) = get_slug() listname = '/'.join([owner, slug]) g['listname'] = listname g['keyword'] = '' g['PREFIX'] = g['cmd'] = u2str(emojize(format_prefix(listname=g['listn...
null
null
null
What does this function do?
def sig_mult(s, m): return sig(monomial_mul(s[0], m), s[1])
null
null
null
Multiply a signature by a monomial. The product of a signature (m, i) and a monomial n is defined as (m * t, i).
pcsd
def sig mult s m return sig monomial mul s[0] m s[1]
3224
def sig_mult(s, m): return sig(monomial_mul(s[0], m), s[1])
Multiply a signature by a monomial. The product of a signature (m, i) and a monomial n is defined as (m * t, i).
multiply a signature by a monomial .
Question: What does this function do? Code: def sig_mult(s, m): return sig(monomial_mul(s[0], m), s[1])
null
null
null
What does this function do?
def getConcatenatedList(originalLists): concatenatedList = [] for originalList in originalLists: concatenatedList += originalList return concatenatedList
null
null
null
Get the lists as one concatenated list.
pcsd
def get Concatenated List original Lists concatenated List = [] for original List in original Lists concatenated List += original List return concatenated List
3228
def getConcatenatedList(originalLists): concatenatedList = [] for originalList in originalLists: concatenatedList += originalList return concatenatedList
Get the lists as one concatenated list.
get the lists as one concatenated list .
Question: What does this function do? Code: def getConcatenatedList(originalLists): concatenatedList = [] for originalList in originalLists: concatenatedList += originalList return concatenatedList
null
null
null
What does this function do?
def is_public_volume_type(context, volume_type_id): volume_type = db.volume_type_get(context, volume_type_id) return volume_type['is_public']
null
null
null
Return is_public boolean value of volume type
pcsd
def is public volume type context volume type id volume type = db volume type get context volume type id return volume type['is public']
3233
def is_public_volume_type(context, volume_type_id): volume_type = db.volume_type_get(context, volume_type_id) return volume_type['is_public']
Return is_public boolean value of volume type
return is _ public boolean value of volume type
Question: What does this function do? Code: def is_public_volume_type(context, volume_type_id): volume_type = db.volume_type_get(context, volume_type_id) return volume_type['is_public']
null
null
null
What does this function do?
def _cleanup_callback(option, opt_str, value, parser): result = [] for choice in value.split(','): if (choice in CLEANUP_CHOICES): result.append(choice) else: parser.error(('%s got %s, which is not one of: %s' % (opt_str, choice, ', '.join(CLEANUP_CHOICES)))) if (('NONE' in result) and (len(set(result)) >...
null
null
null
callback to parse a comma-separated list of cleanup constants.
pcsd
def cleanup callback option opt str value parser result = [] for choice in value split ' ' if choice in CLEANUP CHOICES result append choice else parser error '%s got %s which is not one of %s' % opt str choice ' ' join CLEANUP CHOICES if 'NONE' in result and len set result > 1 parser error '%s Cannot clean up both not...
3246
def _cleanup_callback(option, opt_str, value, parser): result = [] for choice in value.split(','): if (choice in CLEANUP_CHOICES): result.append(choice) else: parser.error(('%s got %s, which is not one of: %s' % (opt_str, choice, ', '.join(CLEANUP_CHOICES)))) if (('NONE' in result) and (len(set(result)) >...
callback to parse a comma-separated list of cleanup constants.
callback to parse a comma - separated list of cleanup constants .
Question: What does this function do? Code: def _cleanup_callback(option, opt_str, value, parser): result = [] for choice in value.split(','): if (choice in CLEANUP_CHOICES): result.append(choice) else: parser.error(('%s got %s, which is not one of: %s' % (opt_str, choice, ', '.join(CLEANUP_CHOICES)))) ...
null
null
null
What does this function do?
def init(): if qtutils.version_check('5.3.0'): default_ciphers = QSslSocket.defaultCiphers() log.init.debug('Default Qt ciphers: {}'.format(', '.join((c.name() for c in default_ciphers)))) else: default_ciphers = QSslSocket.supportedCiphers() log.init.debug('Supported Qt ciphers: {}'.format(', '.join((c.name(...
null
null
null
Disable insecure SSL ciphers on old Qt versions.
pcsd
def init if qtutils version check '5 3 0' default ciphers = Q Ssl Socket default Ciphers log init debug 'Default Qt ciphers {}' format ' ' join c name for c in default ciphers else default ciphers = Q Ssl Socket supported Ciphers log init debug 'Supported Qt ciphers {}' format ' ' join c name for c in default ciphers g...
3249
def init(): if qtutils.version_check('5.3.0'): default_ciphers = QSslSocket.defaultCiphers() log.init.debug('Default Qt ciphers: {}'.format(', '.join((c.name() for c in default_ciphers)))) else: default_ciphers = QSslSocket.supportedCiphers() log.init.debug('Supported Qt ciphers: {}'.format(', '.join((c.name(...
Disable insecure SSL ciphers on old Qt versions.
disable insecure ssl ciphers on old qt versions .
Question: What does this function do? Code: def init(): if qtutils.version_check('5.3.0'): default_ciphers = QSslSocket.defaultCiphers() log.init.debug('Default Qt ciphers: {}'.format(', '.join((c.name() for c in default_ciphers)))) else: default_ciphers = QSslSocket.supportedCiphers() log.init.debug('Supp...
null
null
null
What does this function do?
def permission_required(perm, login_url=None): return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
null
null
null
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary.
pcsd
def permission required perm login url=None return user passes test lambda u u has perm perm login url=login url
3254
def permission_required(perm, login_url=None): return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary.
decorator for views that checks whether a user has a particular permission enabled , redirecting to the log - in page if necessary .
Question: What does this function do? Code: def permission_required(perm, login_url=None): return user_passes_test((lambda u: u.has_perm(perm)), login_url=login_url)
null
null
null
What does this function do?
def scale_by_constant(builder, val, factor): return builder.mul(val, Constant.int(TIMEDELTA64, factor))
null
null
null
Multiply *val* by the constant *factor*.
pcsd
def scale by constant builder val factor return builder mul val Constant int TIMEDELTA64 factor
3255
def scale_by_constant(builder, val, factor): return builder.mul(val, Constant.int(TIMEDELTA64, factor))
Multiply *val* by the constant *factor*.
multiply * val * by the constant * factor * .
Question: What does this function do? Code: def scale_by_constant(builder, val, factor): return builder.mul(val, Constant.int(TIMEDELTA64, factor))
null
null
null
What does this function do?
def wrap_with_safe_string(value, no_wrap_classes=None): def __do_wrap(value): if isinstance(value, SafeStringWrapper): return value if isinstance(value, collections.Callable): safe_class = CallableSafeStringWrapper else: safe_class = SafeStringWrapper if isinstance(value, no_wrap_classes): return v...
null
null
null
Recursively wrap values that should be wrapped.
pcsd
def wrap with safe string value no wrap classes=None def do wrap value if isinstance value Safe String Wrapper return value if isinstance value collections Callable safe class = Callable Safe String Wrapper else safe class = Safe String Wrapper if isinstance value no wrap classes return value if isinstance value DONT W...
3256
def wrap_with_safe_string(value, no_wrap_classes=None): def __do_wrap(value): if isinstance(value, SafeStringWrapper): return value if isinstance(value, collections.Callable): safe_class = CallableSafeStringWrapper else: safe_class = SafeStringWrapper if isinstance(value, no_wrap_classes): return v...
Recursively wrap values that should be wrapped.
recursively wrap values that should be wrapped .
Question: What does this function do? Code: def wrap_with_safe_string(value, no_wrap_classes=None): def __do_wrap(value): if isinstance(value, SafeStringWrapper): return value if isinstance(value, collections.Callable): safe_class = CallableSafeStringWrapper else: safe_class = SafeStringWrapper if ...
null
null
null
What does this function do?
def hierarchy(): s3db.gis_hierarchy_form_setup() return s3_rest_controller()
null
null
null
RESTful CRUD controller
pcsd
def hierarchy s3db gis hierarchy form setup return s3 rest controller
3257
def hierarchy(): s3db.gis_hierarchy_form_setup() return s3_rest_controller()
RESTful CRUD controller
restful crud controller
Question: What does this function do? Code: def hierarchy(): s3db.gis_hierarchy_form_setup() return s3_rest_controller()
null
null
null
What does this function do?
def _parse_jp2_header(fp): header = None while True: (lbox, tbox) = struct.unpack('>I4s', fp.read(8)) if (lbox == 1): lbox = struct.unpack('>Q', fp.read(8))[0] hlen = 16 else: hlen = 8 if (lbox < hlen): raise SyntaxError('Invalid JP2 header length') if (tbox == 'jp2h'): header = fp.read((lbox...
null
null
null
Parse the JP2 header box to extract size, component count and color space information, returning a PIL (size, mode) tuple.
pcsd
def parse jp2 header fp header = None while True lbox tbox = struct unpack '>I4s' fp read 8 if lbox == 1 lbox = struct unpack '>Q' fp read 8 [0] hlen = 16 else hlen = 8 if lbox < hlen raise Syntax Error 'Invalid JP2 header length' if tbox == 'jp2h' header = fp read lbox - hlen break else fp seek lbox - hlen os SEEK CUR...
3279
def _parse_jp2_header(fp): header = None while True: (lbox, tbox) = struct.unpack('>I4s', fp.read(8)) if (lbox == 1): lbox = struct.unpack('>Q', fp.read(8))[0] hlen = 16 else: hlen = 8 if (lbox < hlen): raise SyntaxError('Invalid JP2 header length') if (tbox == 'jp2h'): header = fp.read((lbox...
Parse the JP2 header box to extract size, component count and color space information, returning a PIL (size, mode) tuple.
parse the jp2 header box to extract size , component count and color space information , returning a pil tuple .
Question: What does this function do? Code: def _parse_jp2_header(fp): header = None while True: (lbox, tbox) = struct.unpack('>I4s', fp.read(8)) if (lbox == 1): lbox = struct.unpack('>Q', fp.read(8))[0] hlen = 16 else: hlen = 8 if (lbox < hlen): raise SyntaxError('Invalid JP2 header length') ...
null
null
null
What does this function do?
def _tofloat(value): if isiterable(value): try: value = np.array(value, dtype=np.float) except (TypeError, ValueError): raise InputParameterError(u'Parameter of {0} could not be converted to float'.format(type(value))) elif isinstance(value, np.ndarray): value = float(value.item()) elif isinstance(value,...
null
null
null
Convert a parameter to float or float array
pcsd
def tofloat value if isiterable value try value = np array value dtype=np float except Type Error Value Error raise Input Parameter Error u'Parameter of {0} could not be converted to float' format type value elif isinstance value np ndarray value = float value item elif isinstance value numbers Number np number value =...
3283
def _tofloat(value): if isiterable(value): try: value = np.array(value, dtype=np.float) except (TypeError, ValueError): raise InputParameterError(u'Parameter of {0} could not be converted to float'.format(type(value))) elif isinstance(value, np.ndarray): value = float(value.item()) elif isinstance(value,...
Convert a parameter to float or float array
convert a parameter to float or float array
Question: What does this function do? Code: def _tofloat(value): if isiterable(value): try: value = np.array(value, dtype=np.float) except (TypeError, ValueError): raise InputParameterError(u'Parameter of {0} could not be converted to float'.format(type(value))) elif isinstance(value, np.ndarray): valu...
null
null
null
What does this function do?
def truncate(string, index): if ((len(string) > index) and (index > 0)): string = (string[:(index - 1)] + u('\xe2\x80\xa6')) return string
null
null
null
Truncate a string at index and add ...
pcsd
def truncate string index if len string > index and index > 0 string = string[ index - 1 ] + u '\xe2\x80\xa6' return string
3286
def truncate(string, index): if ((len(string) > index) and (index > 0)): string = (string[:(index - 1)] + u('\xe2\x80\xa6')) return string
Truncate a string at index and add ...
truncate a string at index and add . . .
Question: What does this function do? Code: def truncate(string, index): if ((len(string) > index) and (index > 0)): string = (string[:(index - 1)] + u('\xe2\x80\xa6')) return string
null
null
null
What does this function do?
@require_POST @login_required @ensure_csrf_cookie def change_email_settings(request): user = request.user course_id = request.POST.get('course_id') course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id) receive_emails = request.POST.get('receive_emails') if receive_emails: optout_object = Optout....
null
null
null
Modify logged-in user\'s setting for receiving emails from a course.
pcsd
@require POST @login required @ensure csrf cookie def change email settings request user = request user course id = request POST get 'course id' course key = Slash Separated Course Key from deprecated string course id receive emails = request POST get 'receive emails' if receive emails optout object = Optout objects fi...
3291
@require_POST @login_required @ensure_csrf_cookie def change_email_settings(request): user = request.user course_id = request.POST.get('course_id') course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id) receive_emails = request.POST.get('receive_emails') if receive_emails: optout_object = Optout....
Modify logged-in user\'s setting for receiving emails from a course.
modify logged - in users setting for receiving emails from a course .
Question: What does this function do? Code: @require_POST @login_required @ensure_csrf_cookie def change_email_settings(request): user = request.user course_id = request.POST.get('course_id') course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id) receive_emails = request.POST.get('receive_emails'...
null
null
null
What does this function do?
def fake_get_vmdk_size_and_properties(context, image_id, instance): props = {'vmware_ostype': 'otherGuest', 'vmware_adaptertype': 'lsiLogic'} return (_FAKE_FILE_SIZE, props)
null
null
null
Fakes the file size and properties fetch for the image file.
pcsd
def fake get vmdk size and properties context image id instance props = {'vmware ostype' 'other Guest' 'vmware adaptertype' 'lsi Logic'} return FAKE FILE SIZE props
3292
def fake_get_vmdk_size_and_properties(context, image_id, instance): props = {'vmware_ostype': 'otherGuest', 'vmware_adaptertype': 'lsiLogic'} return (_FAKE_FILE_SIZE, props)
Fakes the file size and properties fetch for the image file.
fakes the file size and properties fetch for the image file .
Question: What does this function do? Code: def fake_get_vmdk_size_and_properties(context, image_id, instance): props = {'vmware_ostype': 'otherGuest', 'vmware_adaptertype': 'lsiLogic'} return (_FAKE_FILE_SIZE, props)
null
null
null
What does this function do?
def Filter(l, item): res = {} return [res.setdefault(e, e) for e in l if (e != item)]
null
null
null
Removes item from l.
pcsd
def Filter l item res = {} return [res setdefault e e for e in l if e != item ]
3295
def Filter(l, item): res = {} return [res.setdefault(e, e) for e in l if (e != item)]
Removes item from l.
removes item from l .
Question: What does this function do? Code: def Filter(l, item): res = {} return [res.setdefault(e, e) for e in l if (e != item)]
null
null
null
What does this function do?
def get_session(stored_access_token): return get_oauth_service().get_session(json.loads(stored_access_token))
null
null
null
called in main extension script to actually get a usable session
pcsd
def get session stored access token return get oauth service get session json loads stored access token
3296
def get_session(stored_access_token): return get_oauth_service().get_session(json.loads(stored_access_token))
called in main extension script to actually get a usable session
called in main extension script to actually get a usable session
Question: What does this function do? Code: def get_session(stored_access_token): return get_oauth_service().get_session(json.loads(stored_access_token))
null
null
null
What does this function do?
def badrequest(): ctx.status = '400 Bad Request' header('Content-Type', 'text/html') return output('bad request')
null
null
null
Return a `400 Bad Request` error.
pcsd
def badrequest ctx status = '400 Bad Request' header 'Content-Type' 'text/html' return output 'bad request'
3299
def badrequest(): ctx.status = '400 Bad Request' header('Content-Type', 'text/html') return output('bad request')
Return a `400 Bad Request` error.
return a 400 bad request error .
Question: What does this function do? Code: def badrequest(): ctx.status = '400 Bad Request' header('Content-Type', 'text/html') return output('bad request')
null
null
null
What does this function do?
def uniform_cdf(x): if (x < 0): return 0 elif (x < 1): return x else: return 1
null
null
null
returns the probability that a uniform random variable is less than x
pcsd
def uniform cdf x if x < 0 return 0 elif x < 1 return x else return 1
3302
def uniform_cdf(x): if (x < 0): return 0 elif (x < 1): return x else: return 1
returns the probability that a uniform random variable is less than x
returns the probability that a uniform random variable is less than x
Question: What does this function do? Code: def uniform_cdf(x): if (x < 0): return 0 elif (x < 1): return x else: return 1
null
null
null
What does this function do?
def _format_range_unified(start, stop): beginning = (start + 1) length = (stop - start) if (length == 1): return '{}'.format(beginning) if (not length): beginning -= 1 return '{},{}'.format(beginning, length)
null
null
null
Convert range to the "ed" format
pcsd
def format range unified start stop beginning = start + 1 length = stop - start if length == 1 return '{}' format beginning if not length beginning -= 1 return '{} {}' format beginning length
3304
def _format_range_unified(start, stop): beginning = (start + 1) length = (stop - start) if (length == 1): return '{}'.format(beginning) if (not length): beginning -= 1 return '{},{}'.format(beginning, length)
Convert range to the "ed" format
convert range to the " ed " format
Question: What does this function do? Code: def _format_range_unified(start, stop): beginning = (start + 1) length = (stop - start) if (length == 1): return '{}'.format(beginning) if (not length): beginning -= 1 return '{},{}'.format(beginning, length)
null
null
null
What does this function do?
def get_client(options): return glance.image_cache.client.get_client(host=options.host, port=options.port, username=options.os_username, password=options.os_password, tenant=options.os_tenant_name, auth_url=options.os_auth_url, auth_strategy=options.os_auth_strategy, auth_token=options.os_auth_token, region=options.os...
null
null
null
Return a new client object to a Glance server. specified by the --host and --port options supplied to the CLI
pcsd
def get client options return glance image cache client get client host=options host port=options port username=options os username password=options os password tenant=options os tenant name auth url=options os auth url auth strategy=options os auth strategy auth token=options os auth token region=options os region nam...
3314
def get_client(options): return glance.image_cache.client.get_client(host=options.host, port=options.port, username=options.os_username, password=options.os_password, tenant=options.os_tenant_name, auth_url=options.os_auth_url, auth_strategy=options.os_auth_strategy, auth_token=options.os_auth_token, region=options.os...
Return a new client object to a Glance server. specified by the --host and --port options supplied to the CLI
return a new client object to a glance server .
Question: What does this function do? Code: def get_client(options): return glance.image_cache.client.get_client(host=options.host, port=options.port, username=options.os_username, password=options.os_password, tenant=options.os_tenant_name, auth_url=options.os_auth_url, auth_strategy=options.os_auth_strategy, auth...
null
null
null
What does this function do?
def interleave(inter, f, seq): seq = iter(seq) try: f(next(seq)) except StopIteration: pass else: for x in seq: inter() f(x)
null
null
null
Call f on each item in seq, calling inter() in between.
pcsd
def interleave inter f seq seq = iter seq try f next seq except Stop Iteration pass else for x in seq inter f x
3318
def interleave(inter, f, seq): seq = iter(seq) try: f(next(seq)) except StopIteration: pass else: for x in seq: inter() f(x)
Call f on each item in seq, calling inter() in between.
call f on each item in seq , calling inter ( ) in between .
Question: What does this function do? Code: def interleave(inter, f, seq): seq = iter(seq) try: f(next(seq)) except StopIteration: pass else: for x in seq: inter() f(x)
null
null
null
What does this function do?
@require_GET def contributors(request): product = _get_product(request) category = _get_category(request) return render_readouts(request, CONTRIBUTOR_READOUTS, 'contributors.html', locale=settings.WIKI_DEFAULT_LANGUAGE, product=product, extra_data={'overview_rows': kb_overview_rows(locale=request.LANGUAGE_CODE, prod...
null
null
null
Render aggregate data about the articles in the default locale.
pcsd
@require GET def contributors request product = get product request category = get category request return render readouts request CONTRIBUTOR READOUTS 'contributors html' locale=settings WIKI DEFAULT LANGUAGE product=product extra data={'overview rows' kb overview rows locale=request LANGUAGE CODE product=product mode...
3321
@require_GET def contributors(request): product = _get_product(request) category = _get_category(request) return render_readouts(request, CONTRIBUTOR_READOUTS, 'contributors.html', locale=settings.WIKI_DEFAULT_LANGUAGE, product=product, extra_data={'overview_rows': kb_overview_rows(locale=request.LANGUAGE_CODE, prod...
Render aggregate data about the articles in the default locale.
render aggregate data about the articles in the default locale .
Question: What does this function do? Code: @require_GET def contributors(request): product = _get_product(request) category = _get_category(request) return render_readouts(request, CONTRIBUTOR_READOUTS, 'contributors.html', locale=settings.WIKI_DEFAULT_LANGUAGE, product=product, extra_data={'overview_rows': kb_o...
null
null
null
What does this function do?
def is_python_file(filename): if filename.endswith(u'.py'): return True try: with open_with_encoding(filename) as f: first_line = f.readlines(1)[0] except (IOError, IndexError): return False if (not PYTHON_SHEBANG_REGEX.match(first_line)): return False return True
null
null
null
Return True if filename is Python file.
pcsd
def is python file filename if filename endswith u' py' return True try with open with encoding filename as f first line = f readlines 1 [0] except IO Error Index Error return False if not PYTHON SHEBANG REGEX match first line return False return True
3325
def is_python_file(filename): if filename.endswith(u'.py'): return True try: with open_with_encoding(filename) as f: first_line = f.readlines(1)[0] except (IOError, IndexError): return False if (not PYTHON_SHEBANG_REGEX.match(first_line)): return False return True
Return True if filename is Python file.
return true if filename is python file .
Question: What does this function do? Code: def is_python_file(filename): if filename.endswith(u'.py'): return True try: with open_with_encoding(filename) as f: first_line = f.readlines(1)[0] except (IOError, IndexError): return False if (not PYTHON_SHEBANG_REGEX.match(first_line)): return False retu...
null
null
null
What does this function do?
def _make_update_dict(update): return {'id': update['id'], 'date': update['date'], 'content': update['content']}
null
null
null
Return course update item as a dictionary with required keys (\'id\', "date" and "content").
pcsd
def make update dict update return {'id' update['id'] 'date' update['date'] 'content' update['content']}
3333
def _make_update_dict(update): return {'id': update['id'], 'date': update['date'], 'content': update['content']}
Return course update item as a dictionary with required keys (\'id\', "date" and "content").
return course update item as a dictionary with required keys .
Question: What does this function do? Code: def _make_update_dict(update): return {'id': update['id'], 'date': update['date'], 'content': update['content']}
null
null
null
What does this function do?
def volume_attach(context, values): return IMPL.volume_attach(context, values)
null
null
null
Attach a volume.
pcsd
def volume attach context values return IMPL volume attach context values
3353
def volume_attach(context, values): return IMPL.volume_attach(context, values)
Attach a volume.
attach a volume .
Question: What does this function do? Code: def volume_attach(context, values): return IMPL.volume_attach(context, values)
null
null
null
What does this function do?
def auth_basic(check, realm='private', text='Access denied'): def decorator(func): def wrapper(*a, **ka): (user, password) = (request.auth or (None, None)) if ((user is None) or (not check(user, password))): response.headers['WWW-Authenticate'] = ('Basic realm="%s"' % realm) return HTTPError(401, text)...
null
null
null
Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
pcsd
def auth basic check realm='private' text='Access denied' def decorator func def wrapper *a **ka user password = request auth or None None if user is None or not check user password response headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm return HTTP Error 401 text return func *a **ka return wrapper return dec...
3355
def auth_basic(check, realm='private', text='Access denied'): def decorator(func): def wrapper(*a, **ka): (user, password) = (request.auth or (None, None)) if ((user is None) or (not check(user, password))): response.headers['WWW-Authenticate'] = ('Basic realm="%s"' % realm) return HTTPError(401, text)...
Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
callback decorator to require http auth .
Question: What does this function do? Code: def auth_basic(check, realm='private', text='Access denied'): def decorator(func): def wrapper(*a, **ka): (user, password) = (request.auth or (None, None)) if ((user is None) or (not check(user, password))): response.headers['WWW-Authenticate'] = ('Basic realm...
null
null
null
What does this function do?
def as_url(scheme, host=None, port=None, user=None, password=None, path=None, query=None, sanitize=False, mask=u'**'): parts = [u'{0}://'.format(scheme)] if (user or password): if user: parts.append(safequote(user)) if password: if sanitize: parts.extend(([u':', mask] if mask else [u':'])) else: ...
null
null
null
Generate URL from component parts.
pcsd
def as url scheme host=None port=None user=None password=None path=None query=None sanitize=False mask=u'**' parts = [u'{0} //' format scheme ] if user or password if user parts append safequote user if password if sanitize parts extend [u' ' mask] if mask else [u' '] else parts extend [u' ' safequote password ] parts ...
3360
def as_url(scheme, host=None, port=None, user=None, password=None, path=None, query=None, sanitize=False, mask=u'**'): parts = [u'{0}://'.format(scheme)] if (user or password): if user: parts.append(safequote(user)) if password: if sanitize: parts.extend(([u':', mask] if mask else [u':'])) else: ...
Generate URL from component parts.
generate url from component parts .
Question: What does this function do? Code: def as_url(scheme, host=None, port=None, user=None, password=None, path=None, query=None, sanitize=False, mask=u'**'): parts = [u'{0}://'.format(scheme)] if (user or password): if user: parts.append(safequote(user)) if password: if sanitize: parts.extend(([...
null
null
null
What does this function do?
def _write_batch_lmdb(db, batch, image_count): try: with db.begin(write=True) as lmdb_txn: for (i, datum) in enumerate(batch): key = ('%08d_%d' % ((image_count + i), datum.label)) lmdb_txn.put(key, datum.SerializeToString()) except lmdb.MapFullError: curr_limit = db.info()['map_size'] new_limit = (cu...
null
null
null
Write a batch to an LMDB database
pcsd
def write batch lmdb db batch image count try with db begin write=True as lmdb txn for i datum in enumerate batch key = '%08d %d' % image count + i datum label lmdb txn put key datum Serialize To String except lmdb Map Full Error curr limit = db info ['map size'] new limit = curr limit * 2 try db set mapsize new limit ...
3362
def _write_batch_lmdb(db, batch, image_count): try: with db.begin(write=True) as lmdb_txn: for (i, datum) in enumerate(batch): key = ('%08d_%d' % ((image_count + i), datum.label)) lmdb_txn.put(key, datum.SerializeToString()) except lmdb.MapFullError: curr_limit = db.info()['map_size'] new_limit = (cu...
Write a batch to an LMDB database
write a batch to an lmdb database
Question: What does this function do? Code: def _write_batch_lmdb(db, batch, image_count): try: with db.begin(write=True) as lmdb_txn: for (i, datum) in enumerate(batch): key = ('%08d_%d' % ((image_count + i), datum.label)) lmdb_txn.put(key, datum.SerializeToString()) except lmdb.MapFullError: curr_...
null
null
null
What does this function do?
@Profiler.profile def test_orm_columns(n): sess = Session(engine) for row in sess.query(Customer.id, Customer.name, Customer.description).yield_per(10000).limit(n): pass
null
null
null
Load individual columns into named tuples using the ORM.
pcsd
@Profiler profile def test orm columns n sess = Session engine for row in sess query Customer id Customer name Customer description yield per 10000 limit n pass
3367
@Profiler.profile def test_orm_columns(n): sess = Session(engine) for row in sess.query(Customer.id, Customer.name, Customer.description).yield_per(10000).limit(n): pass
Load individual columns into named tuples using the ORM.
load individual columns into named tuples using the orm .
Question: What does this function do? Code: @Profiler.profile def test_orm_columns(n): sess = Session(engine) for row in sess.query(Customer.id, Customer.name, Customer.description).yield_per(10000).limit(n): pass
null
null
null
What does this function do?
def get_view_id_list(user, site, check_global=True, use_cache=True): page_ids = _get_page_ids_for_action(user=user, site=site, action='view_page', check_global=check_global, use_cache=use_cache) return page_ids
null
null
null
Give a list of pages which user can view.
pcsd
def get view id list user site check global=True use cache=True page ids = get page ids for action user=user site=site action='view page' check global=check global use cache=use cache return page ids
3369
def get_view_id_list(user, site, check_global=True, use_cache=True): page_ids = _get_page_ids_for_action(user=user, site=site, action='view_page', check_global=check_global, use_cache=use_cache) return page_ids
Give a list of pages which user can view.
give a list of pages which user can view .
Question: What does this function do? Code: def get_view_id_list(user, site, check_global=True, use_cache=True): page_ids = _get_page_ids_for_action(user=user, site=site, action='view_page', check_global=check_global, use_cache=use_cache) return page_ids
null
null
null
What does this function do?
@transaction_task def send_first_edit_email(revision_pk): revision = Revision.objects.get(pk=revision_pk) (user, doc) = (revision.creator, revision.document) subject = (u'[MDN] [%(loc)s] %(user)s made their first edit, to: %(doc)s' % {'loc': doc.locale, 'user': user.username, 'doc': doc.title}) message = render_to_...
null
null
null
Make an \'edited\' notification email for first-time editors
pcsd
@transaction task def send first edit email revision pk revision = Revision objects get pk=revision pk user doc = revision creator revision document subject = u'[MDN] [% loc s] % user s made their first edit to % doc s' % {'loc' doc locale 'user' user username 'doc' doc title} message = render to string 'wiki/email/edi...
3370
@transaction_task def send_first_edit_email(revision_pk): revision = Revision.objects.get(pk=revision_pk) (user, doc) = (revision.creator, revision.document) subject = (u'[MDN] [%(loc)s] %(user)s made their first edit, to: %(doc)s' % {'loc': doc.locale, 'user': user.username, 'doc': doc.title}) message = render_to_...
Make an \'edited\' notification email for first-time editors
make an edited notification email for first - time editors
Question: What does this function do? Code: @transaction_task def send_first_edit_email(revision_pk): revision = Revision.objects.get(pk=revision_pk) (user, doc) = (revision.creator, revision.document) subject = (u'[MDN] [%(loc)s] %(user)s made their first edit, to: %(doc)s' % {'loc': doc.locale, 'user': user.use...
null
null
null
What does this function do?
def bind(uuid, version): (major, minor) = version.split('.') major = struct.pack('<H', int(major)) minor = struct.pack('<H', int(minor)) bind = '\x05\x00' bind += '\x0b' bind += '\x03' bind += '\x10\x00\x00\x00' bind += 'H\x00' bind += '\x00\x00' bind += '\x00\x00\x00\x00' bind += '\xb8\x10' bind += '\xb8\x...
null
null
null
Generate the data necessary to bind to the specified interface.
pcsd
def bind uuid version major minor = version split ' ' major = struct pack '<H' int major minor = struct pack '<H' int minor bind = '\x05\x00' bind += '\x0b' bind += '\x03' bind += '\x10\x00\x00\x00' bind += 'H\x00' bind += '\x00\x00' bind += '\x00\x00\x00\x00' bind += '\xb8\x10' bind += '\xb8\x10' bind += '\x00\x00\x00...
3374
def bind(uuid, version): (major, minor) = version.split('.') major = struct.pack('<H', int(major)) minor = struct.pack('<H', int(minor)) bind = '\x05\x00' bind += '\x0b' bind += '\x03' bind += '\x10\x00\x00\x00' bind += 'H\x00' bind += '\x00\x00' bind += '\x00\x00\x00\x00' bind += '\xb8\x10' bind += '\xb8\x...
Generate the data necessary to bind to the specified interface.
generate the data necessary to bind to the specified interface .
Question: What does this function do? Code: def bind(uuid, version): (major, minor) = version.split('.') major = struct.pack('<H', int(major)) minor = struct.pack('<H', int(minor)) bind = '\x05\x00' bind += '\x0b' bind += '\x03' bind += '\x10\x00\x00\x00' bind += 'H\x00' bind += '\x00\x00' bind += '\x00\x0...
null
null
null
What does this function do?
def print_tensor(x, message=''): return tf.Print(x, [x], message)
null
null
null
Print the message and the tensor when evaluated and return the same tensor.
pcsd
def print tensor x message='' return tf Print x [x] message
3383
def print_tensor(x, message=''): return tf.Print(x, [x], message)
Print the message and the tensor when evaluated and return the same tensor.
print the message and the tensor when evaluated and return the same tensor .
Question: What does this function do? Code: def print_tensor(x, message=''): return tf.Print(x, [x], message)
null
null
null
What does this function do?
def create(vm_): try: if (vm_['profile'] and (config.is_profile_configured(__opts__, (__active_provider_name__ or 'digital_ocean'), vm_['profile'], vm_=vm_) is False)): return False except AttributeError: pass __utils__['cloud.fire_event']('event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name...
null
null
null
Create a single VM from a data dict
pcsd
def create vm try if vm ['profile'] and config is profile configured opts active provider name or 'digital ocean' vm ['profile'] vm =vm is False return False except Attribute Error pass utils ['cloud fire event'] 'event' 'starting create' 'salt/cloud/{0}/creating' format vm ['name'] args={'name' vm ['name'] 'profile' v...
3385
def create(vm_): try: if (vm_['profile'] and (config.is_profile_configured(__opts__, (__active_provider_name__ or 'digital_ocean'), vm_['profile'], vm_=vm_) is False)): return False except AttributeError: pass __utils__['cloud.fire_event']('event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name...
Create a single VM from a data dict
create a single vm from a data dict
Question: What does this function do? Code: def create(vm_): try: if (vm_['profile'] and (config.is_profile_configured(__opts__, (__active_provider_name__ or 'digital_ocean'), vm_['profile'], vm_=vm_) is False)): return False except AttributeError: pass __utils__['cloud.fire_event']('event', 'starting crea...
null
null
null
What does this function do?
def CallSetAllowedModule(name, desired): if (USING_SDK and (name == 'django')): sys.path[:] = [dirname for dirname in sys.path if (not dirname.startswith(os.path.join(PYTHON_LIB, 'lib', 'django')))] if (desired in ('0.96', '1.2', '1.3')): sys.path.insert(1, os.path.join(PYTHON_LIB, 'lib', ('django-' + desired))...
null
null
null
Helper to call SetAllowedModule(name), after special-casing Django.
pcsd
def Call Set Allowed Module name desired if USING SDK and name == 'django' sys path[ ] = [dirname for dirname in sys path if not dirname startswith os path join PYTHON LIB 'lib' 'django' ] if desired in '0 96' '1 2' '1 3' sys path insert 1 os path join PYTHON LIB 'lib' 'django-' + desired Set Allowed Module name
3397
def CallSetAllowedModule(name, desired): if (USING_SDK and (name == 'django')): sys.path[:] = [dirname for dirname in sys.path if (not dirname.startswith(os.path.join(PYTHON_LIB, 'lib', 'django')))] if (desired in ('0.96', '1.2', '1.3')): sys.path.insert(1, os.path.join(PYTHON_LIB, 'lib', ('django-' + desired))...
Helper to call SetAllowedModule(name), after special-casing Django.
helper to call setallowedmodule , after special - casing django .
Question: What does this function do? Code: def CallSetAllowedModule(name, desired): if (USING_SDK and (name == 'django')): sys.path[:] = [dirname for dirname in sys.path if (not dirname.startswith(os.path.join(PYTHON_LIB, 'lib', 'django')))] if (desired in ('0.96', '1.2', '1.3')): sys.path.insert(1, os.path...
null
null
null
What does this function do?
def require_playable(handler): def test_can_play(self, exploration_id, **kwargs): if (exploration_id in feconf.DISABLED_EXPLORATION_IDS): self.render_template('pages/error/disabled_exploration.html', iframe_restriction=None) return if ((feconf.EXPLORATION_URL_EMBED_PREFIX in self.request.uri) or self.request...
null
null
null
Decorator that checks if the user can play the given exploration.
pcsd
def require playable handler def test can play self exploration id **kwargs if exploration id in feconf DISABLED EXPLORATION IDS self render template 'pages/error/disabled exploration html' iframe restriction=None return if feconf EXPLORATION URL EMBED PREFIX in self request uri or self request get 'iframed' self value...
3399
def require_playable(handler): def test_can_play(self, exploration_id, **kwargs): if (exploration_id in feconf.DISABLED_EXPLORATION_IDS): self.render_template('pages/error/disabled_exploration.html', iframe_restriction=None) return if ((feconf.EXPLORATION_URL_EMBED_PREFIX in self.request.uri) or self.request...
Decorator that checks if the user can play the given exploration.
decorator that checks if the user can play the given exploration .
Question: What does this function do? Code: def require_playable(handler): def test_can_play(self, exploration_id, **kwargs): if (exploration_id in feconf.DISABLED_EXPLORATION_IDS): self.render_template('pages/error/disabled_exploration.html', iframe_restriction=None) return if ((feconf.EXPLORATION_URL_EM...
null
null
null
What does this function do?
def addFeatures(features): simplify = GIS.simplify _f = [] append = _f.append for feature in features: geojson = simplify(feature, output='geojson') if geojson: f = dict(type='Feature', geometry=json.loads(geojson)) append(f) return _f
null
null
null
Add Simple Features to the Draft layer - used by S3LocationSelectorWidget
pcsd
def add Features features simplify = GIS simplify f = [] append = f append for feature in features geojson = simplify feature output='geojson' if geojson f = dict type='Feature' geometry=json loads geojson append f return f
3400
def addFeatures(features): simplify = GIS.simplify _f = [] append = _f.append for feature in features: geojson = simplify(feature, output='geojson') if geojson: f = dict(type='Feature', geometry=json.loads(geojson)) append(f) return _f
Add Simple Features to the Draft layer - used by S3LocationSelectorWidget
add simple features to the draft layer - used by s3locationselectorwidget
Question: What does this function do? Code: def addFeatures(features): simplify = GIS.simplify _f = [] append = _f.append for feature in features: geojson = simplify(feature, output='geojson') if geojson: f = dict(type='Feature', geometry=json.loads(geojson)) append(f) return _f
null
null
null
What does this function do?
def setup_fog(): glEnable(GL_FOG) glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1)) glHint(GL_FOG_HINT, GL_DONT_CARE) glFogi(GL_FOG_MODE, GL_LINEAR) glFogf(GL_FOG_START, 20.0) glFogf(GL_FOG_END, 60.0)
null
null
null
Configure the OpenGL fog properties.
pcsd
def setup fog gl Enable GL FOG gl Fogfv GL FOG COLOR G Lfloat * 4 0 5 0 69 1 0 1 gl Hint GL FOG HINT GL DONT CARE gl Fogi GL FOG MODE GL LINEAR gl Fogf GL FOG START 20 0 gl Fogf GL FOG END 60 0
3405
def setup_fog(): glEnable(GL_FOG) glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1)) glHint(GL_FOG_HINT, GL_DONT_CARE) glFogi(GL_FOG_MODE, GL_LINEAR) glFogf(GL_FOG_START, 20.0) glFogf(GL_FOG_END, 60.0)
Configure the OpenGL fog properties.
configure the opengl fog properties .
Question: What does this function do? Code: def setup_fog(): glEnable(GL_FOG) glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1)) glHint(GL_FOG_HINT, GL_DONT_CARE) glFogi(GL_FOG_MODE, GL_LINEAR) glFogf(GL_FOG_START, 20.0) glFogf(GL_FOG_END, 60.0)
null
null
null
What does this function do?
def _fwd_bem_linear_collocation_solution(m): for surf in m['surfs']: complete_surface_info(surf, copy=False, verbose=False) logger.info('Computing the linear collocation solution...') logger.info(' Matrix coefficients...') coeff = _fwd_bem_lin_pot_coeff(m['surfs']) m['nsol'] = len(coeff) logger.info(' Inv...
null
null
null
Compute the linear collocation potential solution.
pcsd
def fwd bem linear collocation solution m for surf in m['surfs'] complete surface info surf copy=False verbose=False logger info 'Computing the linear collocation solution ' logger info ' Matrix coefficients ' coeff = fwd bem lin pot coeff m['surfs'] m['nsol'] = len coeff logger info ' Inverting the coefficient matrix ...
3407
def _fwd_bem_linear_collocation_solution(m): for surf in m['surfs']: complete_surface_info(surf, copy=False, verbose=False) logger.info('Computing the linear collocation solution...') logger.info(' Matrix coefficients...') coeff = _fwd_bem_lin_pot_coeff(m['surfs']) m['nsol'] = len(coeff) logger.info(' Inv...
Compute the linear collocation potential solution.
compute the linear collocation potential solution .
Question: What does this function do? Code: def _fwd_bem_linear_collocation_solution(m): for surf in m['surfs']: complete_surface_info(surf, copy=False, verbose=False) logger.info('Computing the linear collocation solution...') logger.info(' Matrix coefficients...') coeff = _fwd_bem_lin_pot_coeff(m['surfs']...
null
null
null
What does this function do?
@blueprint.route('/jobs/<job_id>', methods=['GET']) def show_job(job_id): job = scheduler.get_job(job_id) if (job is None): raise werkzeug.exceptions.NotFound('Job not found') if isinstance(job, dataset.DatasetJob): return flask.redirect(flask.url_for('digits.dataset.views.show', job_id=job_id)) if isinstance(j...
null
null
null
Redirects to the appropriate /datasets/ or /models/ page
pcsd
@blueprint route '/jobs/<job id>' methods=['GET'] def show job job id job = scheduler get job job id if job is None raise werkzeug exceptions Not Found 'Job not found' if isinstance job dataset Dataset Job return flask redirect flask url for 'digits dataset views show' job id=job id if isinstance job model Model Job re...
3417
@blueprint.route('/jobs/<job_id>', methods=['GET']) def show_job(job_id): job = scheduler.get_job(job_id) if (job is None): raise werkzeug.exceptions.NotFound('Job not found') if isinstance(job, dataset.DatasetJob): return flask.redirect(flask.url_for('digits.dataset.views.show', job_id=job_id)) if isinstance(j...
Redirects to the appropriate /datasets/ or /models/ page
redirects to the appropriate / datasets / or / models / page
Question: What does this function do? Code: @blueprint.route('/jobs/<job_id>', methods=['GET']) def show_job(job_id): job = scheduler.get_job(job_id) if (job is None): raise werkzeug.exceptions.NotFound('Job not found') if isinstance(job, dataset.DatasetJob): return flask.redirect(flask.url_for('digits.datase...
null
null
null
What does this function do?
def gettempdirb(): return _os.fsencode(gettempdir())
null
null
null
A bytes version of tempfile.gettempdir().
pcsd
def gettempdirb return os fsencode gettempdir
3418
def gettempdirb(): return _os.fsencode(gettempdir())
A bytes version of tempfile.gettempdir().
a bytes version of tempfile . gettempdir ( ) .
Question: What does this function do? Code: def gettempdirb(): return _os.fsencode(gettempdir())
null
null
null
What does this function do?
def get_service_module_name(service_model): name = service_model.metadata.get('serviceAbbreviation', service_model.metadata.get('serviceFullName', service_model.service_name)) name = name.replace('Amazon', '') name = name.replace('AWS', '') name = re.sub('\\W+', '', name) return name
null
null
null
Returns the module name for a service This is the value used in both the documentation and client class name
pcsd
def get service module name service model name = service model metadata get 'service Abbreviation' service model metadata get 'service Full Name' service model service name name = name replace 'Amazon' '' name = name replace 'AWS' '' name = re sub '\\W+' '' name return name
3433
def get_service_module_name(service_model): name = service_model.metadata.get('serviceAbbreviation', service_model.metadata.get('serviceFullName', service_model.service_name)) name = name.replace('Amazon', '') name = name.replace('AWS', '') name = re.sub('\\W+', '', name) return name
Returns the module name for a service This is the value used in both the documentation and client class name
returns the module name for a service
Question: What does this function do? Code: def get_service_module_name(service_model): name = service_model.metadata.get('serviceAbbreviation', service_model.metadata.get('serviceFullName', service_model.service_name)) name = name.replace('Amazon', '') name = name.replace('AWS', '') name = re.sub('\\W+', '', na...
null
null
null
What does this function do?
def get_version(version=None): if (version is None): version = VERSION assert (len(version) == 5) assert (version[3] in ('alpha', 'beta', 'rc', 'final')) parts = (2 if (version[2] == 0) else 3) main = '.'.join((str(x) for x in version[:parts])) sub = '' if ((version[3] == 'alpha') and (version[4] == 0)): fro...
null
null
null
Derives a PEP386-compliant version number from VERSION.
pcsd
def get version version=None if version is None version = VERSION assert len version == 5 assert version[3] in 'alpha' 'beta' 'rc' 'final' parts = 2 if version[2] == 0 else 3 main = ' ' join str x for x in version[ parts] sub = '' if version[3] == 'alpha' and version[4] == 0 from django utils version import get svn rev...
3434
def get_version(version=None): if (version is None): version = VERSION assert (len(version) == 5) assert (version[3] in ('alpha', 'beta', 'rc', 'final')) parts = (2 if (version[2] == 0) else 3) main = '.'.join((str(x) for x in version[:parts])) sub = '' if ((version[3] == 'alpha') and (version[4] == 0)): fro...
Derives a PEP386-compliant version number from VERSION.
derives a pep386 - compliant version number from version .
Question: What does this function do? Code: def get_version(version=None): if (version is None): version = VERSION assert (len(version) == 5) assert (version[3] in ('alpha', 'beta', 'rc', 'final')) parts = (2 if (version[2] == 0) else 3) main = '.'.join((str(x) for x in version[:parts])) sub = '' if ((versi...
null
null
null
What does this function do?
def reversed_arguments(func): def wrapped(*args): return func(*reversed(args)) return wrapped
null
null
null
Return a function with reversed argument order.
pcsd
def reversed arguments func def wrapped *args return func *reversed args return wrapped
3436
def reversed_arguments(func): def wrapped(*args): return func(*reversed(args)) return wrapped
Return a function with reversed argument order.
return a function with reversed argument order .
Question: What does this function do? Code: def reversed_arguments(func): def wrapped(*args): return func(*reversed(args)) return wrapped
null
null
null
What does this function do?
def get_darwin_arches(major, minor, machine): arches = [] def _supports_arch(major, minor, arch): if (arch == 'ppc'): return ((major, minor) <= (10, 5)) if (arch == 'ppc64'): return ((major, minor) == (10, 5)) if (arch == 'i386'): return ((major, minor) >= (10, 4)) if (arch == 'x86_64'): return ((...
null
null
null
Return a list of supported arches (including group arches) for the given major, minor and machine architecture of an macOS machine.
pcsd
def get darwin arches major minor machine arches = [] def supports arch major minor arch if arch == 'ppc' return major minor <= 10 5 if arch == 'ppc64' return major minor == 10 5 if arch == 'i386' return major minor >= 10 4 if arch == 'x86 64' return major minor >= 10 5 if arch in groups for garch in groups[arch] if su...
3438
def get_darwin_arches(major, minor, machine): arches = [] def _supports_arch(major, minor, arch): if (arch == 'ppc'): return ((major, minor) <= (10, 5)) if (arch == 'ppc64'): return ((major, minor) == (10, 5)) if (arch == 'i386'): return ((major, minor) >= (10, 4)) if (arch == 'x86_64'): return ((...
Return a list of supported arches (including group arches) for the given major, minor and machine architecture of an macOS machine.
return a list of supported arches for the given major , minor and machine architecture of an macos machine .
Question: What does this function do? Code: def get_darwin_arches(major, minor, machine): arches = [] def _supports_arch(major, minor, arch): if (arch == 'ppc'): return ((major, minor) <= (10, 5)) if (arch == 'ppc64'): return ((major, minor) == (10, 5)) if (arch == 'i386'): return ((major, minor) >=...
null
null
null
What does this function do?
def DEFINE_float(name, default, help): CONFIG.AddOption(type_info.Float(name=name, default=default, description=help))
null
null
null
A helper for defining float options.
pcsd
def DEFINE float name default help CONFIG Add Option type info Float name=name default=default description=help
3442
def DEFINE_float(name, default, help): CONFIG.AddOption(type_info.Float(name=name, default=default, description=help))
A helper for defining float options.
a helper for defining float options .
Question: What does this function do? Code: def DEFINE_float(name, default, help): CONFIG.AddOption(type_info.Float(name=name, default=default, description=help))
null
null
null
What does this function do?
def renew_hook(config, domains, lineage_path): if config.renew_hook: if (not config.dry_run): os.environ['RENEWED_DOMAINS'] = ' '.join(domains) os.environ['RENEWED_LINEAGE'] = lineage_path logger.info('Running renew-hook command: %s', config.renew_hook) _run_hook(config.renew_hook) else: logger.warn...
null
null
null
Run post-renewal hook if defined.
pcsd
def renew hook config domains lineage path if config renew hook if not config dry run os environ['RENEWED DOMAINS'] = ' ' join domains os environ['RENEWED LINEAGE'] = lineage path logger info 'Running renew-hook command %s' config renew hook run hook config renew hook else logger warning 'Dry run skipping renewal hook ...
3447
def renew_hook(config, domains, lineage_path): if config.renew_hook: if (not config.dry_run): os.environ['RENEWED_DOMAINS'] = ' '.join(domains) os.environ['RENEWED_LINEAGE'] = lineage_path logger.info('Running renew-hook command: %s', config.renew_hook) _run_hook(config.renew_hook) else: logger.warn...
Run post-renewal hook if defined.
run post - renewal hook if defined .
Question: What does this function do? Code: def renew_hook(config, domains, lineage_path): if config.renew_hook: if (not config.dry_run): os.environ['RENEWED_DOMAINS'] = ' '.join(domains) os.environ['RENEWED_LINEAGE'] = lineage_path logger.info('Running renew-hook command: %s', config.renew_hook) _run...
null
null
null
What does this function do?
def fix_code(source, options=None, encoding=None, apply_config=False): options = _get_options(options, apply_config) if (not isinstance(source, unicode)): source = source.decode((encoding or get_encoding())) sio = io.StringIO(source) return fix_lines(sio.readlines(), options=options)
null
null
null
Return fixed source code. "encoding" will be used to decode "source" if it is a byte string.
pcsd
def fix code source options=None encoding=None apply config=False options = get options options apply config if not isinstance source unicode source = source decode encoding or get encoding sio = io String IO source return fix lines sio readlines options=options
3452
def fix_code(source, options=None, encoding=None, apply_config=False): options = _get_options(options, apply_config) if (not isinstance(source, unicode)): source = source.decode((encoding or get_encoding())) sio = io.StringIO(source) return fix_lines(sio.readlines(), options=options)
Return fixed source code. "encoding" will be used to decode "source" if it is a byte string.
return fixed source code .
Question: What does this function do? Code: def fix_code(source, options=None, encoding=None, apply_config=False): options = _get_options(options, apply_config) if (not isinstance(source, unicode)): source = source.decode((encoding or get_encoding())) sio = io.StringIO(source) return fix_lines(sio.readlines(),...
null
null
null
What does this function do?
def strip_headers(post): if ('\n\n' in post): (headers, body) = post.split('\n\n', 1) return body.lower() else: return post.lower()
null
null
null
Find the first blank line and drop the headers to keep the body
pcsd
def strip headers post if ' ' in post headers body = post split ' ' 1 return body lower else return post lower
3457
def strip_headers(post): if ('\n\n' in post): (headers, body) = post.split('\n\n', 1) return body.lower() else: return post.lower()
Find the first blank line and drop the headers to keep the body
find the first blank line and drop the headers to keep the body
Question: What does this function do? Code: def strip_headers(post): if ('\n\n' in post): (headers, body) = post.split('\n\n', 1) return body.lower() else: return post.lower()
null
null
null
What does this function do?
@bdd.when(bdd.parsers.re('I press the keys? "(?P<keys>[^"]*)"')) def press_keys(quteproc, keys): quteproc.press_keys(keys)
null
null
null
Send the given fake keys to qutebrowser.
pcsd
@bdd when bdd parsers re 'I press the keys? " ?P<keys>[^"]* "' def press keys quteproc keys quteproc press keys keys
3461
@bdd.when(bdd.parsers.re('I press the keys? "(?P<keys>[^"]*)"')) def press_keys(quteproc, keys): quteproc.press_keys(keys)
Send the given fake keys to qutebrowser.
send the given fake keys to qutebrowser .
Question: What does this function do? Code: @bdd.when(bdd.parsers.re('I press the keys? "(?P<keys>[^"]*)"')) def press_keys(quteproc, keys): quteproc.press_keys(keys)
null
null
null
What does this function do?
@login_required @require_POST @process_document_path def quick_review(request, document_slug, document_locale): doc = get_object_or_404(Document, locale=document_locale, slug=document_slug) if (not doc.allows_revision_by(request.user)): raise PermissionDenied rev_id = request.POST.get('revision_id') if (not rev_i...
null
null
null
Quickly mark a revision as no longer needing a particular type of review.
pcsd
@login required @require POST @process document path def quick review request document slug document locale doc = get object or 404 Document locale=document locale slug=document slug if not doc allows revision by request user raise Permission Denied rev id = request POST get 'revision id' if not rev id raise Http404 re...
3464
@login_required @require_POST @process_document_path def quick_review(request, document_slug, document_locale): doc = get_object_or_404(Document, locale=document_locale, slug=document_slug) if (not doc.allows_revision_by(request.user)): raise PermissionDenied rev_id = request.POST.get('revision_id') if (not rev_i...
Quickly mark a revision as no longer needing a particular type of review.
quickly mark a revision as no longer needing a particular type of review .
Question: What does this function do? Code: @login_required @require_POST @process_document_path def quick_review(request, document_slug, document_locale): doc = get_object_or_404(Document, locale=document_locale, slug=document_slug) if (not doc.allows_revision_by(request.user)): raise PermissionDenied rev_id =...
null
null
null
What does this function do?
@ioflo.base.deeding.deedify('SaltRaetEventReturnFork', ioinits={'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def event_return_fork(self): self.proc_mgr.value.add_process(salt.utils.event.EventReturn, args=(self.opts.value,))
null
null
null
Add a reactor object to the process manager
pcsd
@ioflo base deeding deedify 'Salt Raet Event Return Fork' ioinits={'opts' ' salt opts' 'proc mgr' ' salt usr proc mgr'} def event return fork self self proc mgr value add process salt utils event Event Return args= self opts value
3468
@ioflo.base.deeding.deedify('SaltRaetEventReturnFork', ioinits={'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def event_return_fork(self): self.proc_mgr.value.add_process(salt.utils.event.EventReturn, args=(self.opts.value,))
Add a reactor object to the process manager
add a reactor object to the process manager
Question: What does this function do? Code: @ioflo.base.deeding.deedify('SaltRaetEventReturnFork', ioinits={'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def event_return_fork(self): self.proc_mgr.value.add_process(salt.utils.event.EventReturn, args=(self.opts.value,))
null
null
null
What does this function do?
def isLineIntersectingInsideXSegment(beginComplex, endComplex, segmentFirstX, segmentSecondX, y): xIntersection = getXIntersectionIfExists(beginComplex, endComplex, y) if (xIntersection == None): return False if (xIntersection < min(segmentFirstX, segmentSecondX)): return False return (xIntersection <= max(segm...
null
null
null
Determine if the line is crossing inside the x segment.
pcsd
def is Line Intersecting Inside X Segment begin Complex end Complex segment First X segment Second X y x Intersection = get X Intersection If Exists begin Complex end Complex y if x Intersection == None return False if x Intersection < min segment First X segment Second X return False return x Intersection <= max segme...
3475
def isLineIntersectingInsideXSegment(beginComplex, endComplex, segmentFirstX, segmentSecondX, y): xIntersection = getXIntersectionIfExists(beginComplex, endComplex, y) if (xIntersection == None): return False if (xIntersection < min(segmentFirstX, segmentSecondX)): return False return (xIntersection <= max(segm...
Determine if the line is crossing inside the x segment.
determine if the line is crossing inside the x segment .
Question: What does this function do? Code: def isLineIntersectingInsideXSegment(beginComplex, endComplex, segmentFirstX, segmentSecondX, y): xIntersection = getXIntersectionIfExists(beginComplex, endComplex, y) if (xIntersection == None): return False if (xIntersection < min(segmentFirstX, segmentSecondX)): ...
null
null
null
What does this function do?
def references(conn, table, field): rows1 = query(conn, "\n SELECT k.table_name, k.column_name, k.constraint_name,\n r.update_rule, r.delete_rule, k.ordinal_position\n FROM information_schema.key_column_usage k\n INNER JOIN information_schema.referential_constraints r\n ON (k....
null
null
null
Find a FK (fails if multiple)
pcsd
def references conn table field rows1 = query conn " SELECT k table name k column name k constraint name r update rule r delete rule k ordinal position FROM information schema key column usage k INNER JOIN information schema referential constraints r ON k CONSTRAINT CATALOG = r CONSTRAINT CATALOG AND k CONSTRAINT NAME ...
3477
def references(conn, table, field): rows1 = query(conn, "\n SELECT k.table_name, k.column_name, k.constraint_name,\n r.update_rule, r.delete_rule, k.ordinal_position\n FROM information_schema.key_column_usage k\n INNER JOIN information_schema.referential_constraints r\n ON (k....
Find a FK (fails if multiple)
find a fk
Question: What does this function do? Code: def references(conn, table, field): rows1 = query(conn, "\n SELECT k.table_name, k.column_name, k.constraint_name,\n r.update_rule, r.delete_rule, k.ordinal_position\n FROM information_schema.key_column_usage k\n INNER JOIN information_s...
null
null
null
What does this function do?
def catalog(): global _default t = getattr(_active, 'value', None) if (t is not None): return t if (_default is None): from django.conf import settings _default = translation(settings.LANGUAGE_CODE) return _default
null
null
null
Returns the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string.
pcsd
def catalog global default t = getattr active 'value' None if t is not None return t if default is None from django conf import settings default = translation settings LANGUAGE CODE return default
3478
def catalog(): global _default t = getattr(_active, 'value', None) if (t is not None): return t if (_default is None): from django.conf import settings _default = translation(settings.LANGUAGE_CODE) return _default
Returns the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string.
returns the current active catalog for further processing .
Question: What does this function do? Code: def catalog(): global _default t = getattr(_active, 'value', None) if (t is not None): return t if (_default is None): from django.conf import settings _default = translation(settings.LANGUAGE_CODE) return _default
null
null
null
What does this function do?
def CreateCGate(name, latexname=None): if (not latexname): latexname = name onequbitgate = CreateOneQubitGate(name, latexname) def ControlledGate(ctrls, target): return CGate(tuple(ctrls), onequbitgate(target)) return ControlledGate
null
null
null
Use a lexical closure to make a controlled gate.
pcsd
def Create C Gate name latexname=None if not latexname latexname = name onequbitgate = Create One Qubit Gate name latexname def Controlled Gate ctrls target return C Gate tuple ctrls onequbitgate target return Controlled Gate
3505
def CreateCGate(name, latexname=None): if (not latexname): latexname = name onequbitgate = CreateOneQubitGate(name, latexname) def ControlledGate(ctrls, target): return CGate(tuple(ctrls), onequbitgate(target)) return ControlledGate
Use a lexical closure to make a controlled gate.
use a lexical closure to make a controlled gate .
Question: What does this function do? Code: def CreateCGate(name, latexname=None): if (not latexname): latexname = name onequbitgate = CreateOneQubitGate(name, latexname) def ControlledGate(ctrls, target): return CGate(tuple(ctrls), onequbitgate(target)) return ControlledGate
null
null
null
What does this function do?
def generate_dataset(): return (np.vstack((np.vstack((_generate_vector(), (_generate_vector() + 100))).T, np.vstack((_generate_vector(), _generate_vector())).T)), np.hstack((np.zeros(1000), np.ones(1000))))
null
null
null
This dataset is two lines with a slope ~ 1, where one has a y offset of ~100
pcsd
def generate dataset return np vstack np vstack generate vector generate vector + 100 T np vstack generate vector generate vector T np hstack np zeros 1000 np ones 1000
3509
def generate_dataset(): return (np.vstack((np.vstack((_generate_vector(), (_generate_vector() + 100))).T, np.vstack((_generate_vector(), _generate_vector())).T)), np.hstack((np.zeros(1000), np.ones(1000))))
This dataset is two lines with a slope ~ 1, where one has a y offset of ~100
this dataset is two lines with a slope ~ 1 , where one has a y offset of ~ 100
Question: What does this function do? Code: def generate_dataset(): return (np.vstack((np.vstack((_generate_vector(), (_generate_vector() + 100))).T, np.vstack((_generate_vector(), _generate_vector())).T)), np.hstack((np.zeros(1000), np.ones(1000))))
null
null
null
What does this function do?
def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False): pattern_list = filter.split('.') if (len(pattern_list) == 1): return filter_ns(namespace, name_pattern=pattern_list[0], type_pattern=type_pattern, ignore_case=ignore_case, show_all=show_all) else: filtered = filter_ns(namespa...
null
null
null
Return dictionary of all objects in a namespace dictionary that match type_pattern and filter.
pcsd
def list namespace namespace type pattern filter ignore case=False show all=False pattern list = filter split ' ' if len pattern list == 1 return filter ns namespace name pattern=pattern list[0] type pattern=type pattern ignore case=ignore case show all=show all else filtered = filter ns namespace name pattern=pattern ...
3510
def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False): pattern_list = filter.split('.') if (len(pattern_list) == 1): return filter_ns(namespace, name_pattern=pattern_list[0], type_pattern=type_pattern, ignore_case=ignore_case, show_all=show_all) else: filtered = filter_ns(namespa...
Return dictionary of all objects in a namespace dictionary that match type_pattern and filter.
return dictionary of all objects in a namespace dictionary that match type _ pattern and filter .
Question: What does this function do? Code: def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False): pattern_list = filter.split('.') if (len(pattern_list) == 1): return filter_ns(namespace, name_pattern=pattern_list[0], type_pattern=type_pattern, ignore_case=ignore_case, show_all=...
null
null
null
What does this function do?
def main(): if (len(sys.argv) > 1): writeOutput(' '.join(sys.argv[1:])) else: settings.startMainLoopFromConstructor(getNewRepository())
null
null
null
Display the outset dialog.
pcsd
def main if len sys argv > 1 write Output ' ' join sys argv[1 ] else settings start Main Loop From Constructor get New Repository
3511
def main(): if (len(sys.argv) > 1): writeOutput(' '.join(sys.argv[1:])) else: settings.startMainLoopFromConstructor(getNewRepository())
Display the outset dialog.
display the outset dialog .
Question: What does this function do? Code: def main(): if (len(sys.argv) > 1): writeOutput(' '.join(sys.argv[1:])) else: settings.startMainLoopFromConstructor(getNewRepository())
null
null
null
What does this function do?
def update_kb_contributors_metric(day=None): if day: start = end = day else: latest_metric = _get_latest_metric(KB_ENUS_CONTRIBUTORS_METRIC_CODE) if (latest_metric is not None): start = (latest_metric.end + timedelta(days=1)) else: start = date(2011, 1, 1) end = (date.today() - timedelta(days=1)) day...
null
null
null
Calculate and save the KB (en-US and L10n) contributor counts. A KB contributor is a user that has edited or reviewed a Revision in the last 30 days.
pcsd
def update kb contributors metric day=None if day start = end = day else latest metric = get latest metric KB ENUS CONTRIBUTORS METRIC CODE if latest metric is not None start = latest metric end + timedelta days=1 else start = date 2011 1 1 end = date today - timedelta days=1 day = start while day <= end thirty days ba...
3512
def update_kb_contributors_metric(day=None): if day: start = end = day else: latest_metric = _get_latest_metric(KB_ENUS_CONTRIBUTORS_METRIC_CODE) if (latest_metric is not None): start = (latest_metric.end + timedelta(days=1)) else: start = date(2011, 1, 1) end = (date.today() - timedelta(days=1)) day...
Calculate and save the KB (en-US and L10n) contributor counts. A KB contributor is a user that has edited or reviewed a Revision in the last 30 days.
calculate and save the kb contributor counts .
Question: What does this function do? Code: def update_kb_contributors_metric(day=None): if day: start = end = day else: latest_metric = _get_latest_metric(KB_ENUS_CONTRIBUTORS_METRIC_CODE) if (latest_metric is not None): start = (latest_metric.end + timedelta(days=1)) else: start = date(2011, 1, 1) ...
null
null
null
What does this function do?
def _parse_homehub_response(data_str): root = ET.fromstring(data_str) dirty_json = root.find('known_device_list').get('value') clean_json = unquote(dirty_json.replace("'", '"').replace('{', '{"').replace(':"', '":"').replace('",', '","')) known_devices = [x for x in json.loads(clean_json) if x] devices = {} for d...
null
null
null
Parse the BT Home Hub 5 data format.
pcsd
def parse homehub response data str root = ET fromstring data str dirty json = root find 'known device list' get 'value' clean json = unquote dirty json replace "'" '"' replace '{' '{"' replace ' "' '" "' replace '" ' '" "' known devices = [x for x in json loads clean json if x] devices = {} for device in known devices...
3519
def _parse_homehub_response(data_str): root = ET.fromstring(data_str) dirty_json = root.find('known_device_list').get('value') clean_json = unquote(dirty_json.replace("'", '"').replace('{', '{"').replace(':"', '":"').replace('",', '","')) known_devices = [x for x in json.loads(clean_json) if x] devices = {} for d...
Parse the BT Home Hub 5 data format.
parse the bt home hub 5 data format .
Question: What does this function do? Code: def _parse_homehub_response(data_str): root = ET.fromstring(data_str) dirty_json = root.find('known_device_list').get('value') clean_json = unquote(dirty_json.replace("'", '"').replace('{', '{"').replace(':"', '":"').replace('",', '","')) known_devices = [x for x in js...
null
null
null
What does this function do?
def _many_to_one(input_dict): return dict(((key, val) for (keys, val) in input_dict.items() for key in keys))
null
null
null
Convert a many-to-one mapping to a one-to-one mapping
pcsd
def many to one input dict return dict key val for keys val in input dict items for key in keys
3523
def _many_to_one(input_dict): return dict(((key, val) for (keys, val) in input_dict.items() for key in keys))
Convert a many-to-one mapping to a one-to-one mapping
convert a many - to - one mapping to a one - to - one mapping
Question: What does this function do? Code: def _many_to_one(input_dict): return dict(((key, val) for (keys, val) in input_dict.items() for key in keys))
null
null
null
What does this function do?
def require_collection_playable(handler): def test_can_play(self, collection_id, **kwargs): 'Check if the current user can play the collection.' actor = rights_manager.Actor(self.user_id) can_play = actor.can_play(feconf.ACTIVITY_TYPE_COLLECTION, collection_id) can_view = actor.can_view(feconf.ACTIVITY_TYPE_CO...
null
null
null
Decorator that checks if the user can play the given collection.
pcsd
def require collection playable handler def test can play self collection id **kwargs 'Check if the current user can play the collection ' actor = rights manager Actor self user id can play = actor can play feconf ACTIVITY TYPE COLLECTION collection id can view = actor can view feconf ACTIVITY TYPE COLLECTION collectio...
3527
def require_collection_playable(handler): def test_can_play(self, collection_id, **kwargs): 'Check if the current user can play the collection.' actor = rights_manager.Actor(self.user_id) can_play = actor.can_play(feconf.ACTIVITY_TYPE_COLLECTION, collection_id) can_view = actor.can_view(feconf.ACTIVITY_TYPE_CO...
Decorator that checks if the user can play the given collection.
decorator that checks if the user can play the given collection .
Question: What does this function do? Code: def require_collection_playable(handler): def test_can_play(self, collection_id, **kwargs): 'Check if the current user can play the collection.' actor = rights_manager.Actor(self.user_id) can_play = actor.can_play(feconf.ACTIVITY_TYPE_COLLECTION, collection_id) ca...
null
null
null
What does this function do?
def req_factory_factory(url, user=None, post=False, data=None, session=None): req = RequestFactory() if post: req = req.post(url, (data or {})) else: req = req.get(url, (data or {})) if user: req.user = UserProfile.objects.get(id=user.id) else: req.user = AnonymousUser() if (session is not None): req.se...
null
null
null
Creates a request factory, logged in with the user.
pcsd
def req factory factory url user=None post=False data=None session=None req = Request Factory if post req = req post url data or {} else req = req get url data or {} if user req user = User Profile objects get id=user id else req user = Anonymous User if session is not None req session = session req APP = None req chec...
3534
def req_factory_factory(url, user=None, post=False, data=None, session=None): req = RequestFactory() if post: req = req.post(url, (data or {})) else: req = req.get(url, (data or {})) if user: req.user = UserProfile.objects.get(id=user.id) else: req.user = AnonymousUser() if (session is not None): req.se...
Creates a request factory, logged in with the user.
creates a request factory , logged in with the user .
Question: What does this function do? Code: def req_factory_factory(url, user=None, post=False, data=None, session=None): req = RequestFactory() if post: req = req.post(url, (data or {})) else: req = req.get(url, (data or {})) if user: req.user = UserProfile.objects.get(id=user.id) else: req.user = Anon...
null
null
null
What does this function do?
def add_problem_to_course(course, problem_type, extra_meta=None): assert (problem_type in PROBLEM_DICT) factory_dict = PROBLEM_DICT[problem_type] problem_xml = factory_dict['factory'].build_xml(**factory_dict['kwargs']) metadata = ({'rerandomize': 'always'} if ('metadata' not in factory_dict) else factory_dict['met...
null
null
null
Add a problem to the course we have created using factories.
pcsd
def add problem to course course problem type extra meta=None assert problem type in PROBLEM DICT factory dict = PROBLEM DICT[problem type] problem xml = factory dict['factory'] build xml **factory dict['kwargs'] metadata = {'rerandomize' 'always'} if 'metadata' not in factory dict else factory dict['metadata'] if extr...
3536
def add_problem_to_course(course, problem_type, extra_meta=None): assert (problem_type in PROBLEM_DICT) factory_dict = PROBLEM_DICT[problem_type] problem_xml = factory_dict['factory'].build_xml(**factory_dict['kwargs']) metadata = ({'rerandomize': 'always'} if ('metadata' not in factory_dict) else factory_dict['met...
Add a problem to the course we have created using factories.
add a problem to the course we have created using factories .
Question: What does this function do? Code: def add_problem_to_course(course, problem_type, extra_meta=None): assert (problem_type in PROBLEM_DICT) factory_dict = PROBLEM_DICT[problem_type] problem_xml = factory_dict['factory'].build_xml(**factory_dict['kwargs']) metadata = ({'rerandomize': 'always'} if ('metada...
null
null
null
What does this function do?
def maybe_ref(ref): if (not isinstance(ref, str)): return ref return ref_to_obj(ref)
null
null
null
Returns the object that the given reference points to, if it is indeed a reference. If it is not a reference, the object is returned as-is.
pcsd
def maybe ref ref if not isinstance ref str return ref return ref to obj ref
3537
def maybe_ref(ref): if (not isinstance(ref, str)): return ref return ref_to_obj(ref)
Returns the object that the given reference points to, if it is indeed a reference. If it is not a reference, the object is returned as-is.
returns the object that the given reference points to , if it is indeed a reference .
Question: What does this function do? Code: def maybe_ref(ref): if (not isinstance(ref, str)): return ref return ref_to_obj(ref)
null
null
null
What does this function do?
def getRightStripMinusSplit(lineString): oldLineStringLength = (-1) while (oldLineStringLength < len(lineString)): oldLineStringLength = len(lineString) lineString = lineString.replace('- ', '-') return lineString.split()
null
null
null
Get string with spaces after the minus sign stripped.
pcsd
def get Right Strip Minus Split line String old Line String Length = -1 while old Line String Length < len line String old Line String Length = len line String line String = line String replace '- ' '-' return line String split
3545
def getRightStripMinusSplit(lineString): oldLineStringLength = (-1) while (oldLineStringLength < len(lineString)): oldLineStringLength = len(lineString) lineString = lineString.replace('- ', '-') return lineString.split()
Get string with spaces after the minus sign stripped.
get string with spaces after the minus sign stripped .
Question: What does this function do? Code: def getRightStripMinusSplit(lineString): oldLineStringLength = (-1) while (oldLineStringLength < len(lineString)): oldLineStringLength = len(lineString) lineString = lineString.replace('- ', '-') return lineString.split()
null
null
null
What does this function do?
def dispatch(environ): method = environ['REQUEST_METHOD'].upper() if (method == 'GET'): return "They found me. I don't know how, but they found me. Run for it, Marty!" elif (method == 'POST'): data = get_json(environ) return run_chunk(environ, data) else: raise HTTPError(405, 'Method Not Allowed')
null
null
null
Do any path/method dispatching here and return a JSON-serializable data structure appropriate for the response
pcsd
def dispatch environ method = environ['REQUEST METHOD'] upper if method == 'GET' return "They found me I don't know how but they found me Run for it Marty!" elif method == 'POST' data = get json environ return run chunk environ data else raise HTTP Error 405 'Method Not Allowed'
3551
def dispatch(environ): method = environ['REQUEST_METHOD'].upper() if (method == 'GET'): return "They found me. I don't know how, but they found me. Run for it, Marty!" elif (method == 'POST'): data = get_json(environ) return run_chunk(environ, data) else: raise HTTPError(405, 'Method Not Allowed')
Do any path/method dispatching here and return a JSON-serializable data structure appropriate for the response
do any path / method dispatching here and return a json - serializable data structure appropriate for the response
Question: What does this function do? Code: def dispatch(environ): method = environ['REQUEST_METHOD'].upper() if (method == 'GET'): return "They found me. I don't know how, but they found me. Run for it, Marty!" elif (method == 'POST'): data = get_json(environ) return run_chunk(environ, data) else: raise...
null
null
null
What does this function do?
@verbose def _assemble_kernel(inv, label, method, pick_ori, verbose=None): eigen_leads = inv['eigen_leads']['data'] source_cov = inv['source_cov']['data'][:, None] if (method != 'MNE'): noise_norm = inv['noisenorm'][:, None] src = inv['src'] vertno = _get_vertno(src) if (label is not None): (vertno, src_sel) ...
null
null
null
Assemble the kernel.
pcsd
@verbose def assemble kernel inv label method pick ori verbose=None eigen leads = inv['eigen leads']['data'] source cov = inv['source cov']['data'][ None] if method != 'MNE' noise norm = inv['noisenorm'][ None] src = inv['src'] vertno = get vertno src if label is not None vertno src sel = label src vertno sel label inv...
3567
@verbose def _assemble_kernel(inv, label, method, pick_ori, verbose=None): eigen_leads = inv['eigen_leads']['data'] source_cov = inv['source_cov']['data'][:, None] if (method != 'MNE'): noise_norm = inv['noisenorm'][:, None] src = inv['src'] vertno = _get_vertno(src) if (label is not None): (vertno, src_sel) ...
Assemble the kernel.
assemble the kernel .
Question: What does this function do? Code: @verbose def _assemble_kernel(inv, label, method, pick_ori, verbose=None): eigen_leads = inv['eigen_leads']['data'] source_cov = inv['source_cov']['data'][:, None] if (method != 'MNE'): noise_norm = inv['noisenorm'][:, None] src = inv['src'] vertno = _get_vertno(src...
null
null
null
What does this function do?
def local_job(cmd, pollpath, name, queue): to_submit = ('%s; echo $? > %s' % (cmd, pollpath)) return to_submit
null
null
null
make a local job
pcsd
def local job cmd pollpath name queue to submit = '%s echo $? > %s' % cmd pollpath return to submit
3571
def local_job(cmd, pollpath, name, queue): to_submit = ('%s; echo $? > %s' % (cmd, pollpath)) return to_submit
make a local job
make a local job
Question: What does this function do? Code: def local_job(cmd, pollpath, name, queue): to_submit = ('%s; echo $? > %s' % (cmd, pollpath)) return to_submit
null
null
null
What does this function do?
def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets, data): qualified_root_targets = [] for target in root_targets: target = target.strip() qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list) if (not qualified_targets): raise GypError(('Could not find target %s' % t...
null
null
null
Return only the targets that are deep dependencies of |root_targets|.
pcsd
def Prune Unwanted Targets targets flat list dependency nodes root targets data qualified root targets = [] for target in root targets target = target strip qualified targets = gyp common Find Qualified Targets target flat list if not qualified targets raise Gyp Error 'Could not find target %s' % target qualified root ...
3572
def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets, data): qualified_root_targets = [] for target in root_targets: target = target.strip() qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list) if (not qualified_targets): raise GypError(('Could not find target %s' % t...
Return only the targets that are deep dependencies of |root_targets|.
return only the targets that are deep dependencies of | root _ targets | .
Question: What does this function do? Code: def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets, data): qualified_root_targets = [] for target in root_targets: target = target.strip() qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list) if (not qualified_targets): ...
null
null
null
What does this function do?
def _Connect(region): ec2_region = None for r in regions(): if (r.name == region): ec2_region = r break assert (ec2_region is not None), ('"%s" not in the list of ec2 regions: %s' % (region, ', '.join(kValidRegions))) return boto.connect_ec2(region=ec2_region)
null
null
null
Verify region and return an EC2 connection object.
pcsd
def Connect region ec2 region = None for r in regions if r name == region ec2 region = r break assert ec2 region is not None '"%s" not in the list of ec2 regions %s' % region ' ' join k Valid Regions return boto connect ec2 region=ec2 region
3575
def _Connect(region): ec2_region = None for r in regions(): if (r.name == region): ec2_region = r break assert (ec2_region is not None), ('"%s" not in the list of ec2 regions: %s' % (region, ', '.join(kValidRegions))) return boto.connect_ec2(region=ec2_region)
Verify region and return an EC2 connection object.
verify region and return an ec2 connection object .
Question: What does this function do? Code: def _Connect(region): ec2_region = None for r in regions(): if (r.name == region): ec2_region = r break assert (ec2_region is not None), ('"%s" not in the list of ec2 regions: %s' % (region, ', '.join(kValidRegions))) return boto.connect_ec2(region=ec2_region)
null
null
null
What does this function do?
def logo(col=None, version=''): col = (col if col else random.choice((c.g, c.r, c.y, c.b, c.p, c.w))) logo_txt = " _ _\n _ __ ___ _ __ ___ _ _ ___ _ _| |_ _ _| |__ ___\n| '_ ` _ \\| '_ \\/ __|_____| | | |/ _ \\| | | | __| | | | '_ \\ / _ \\\n| | | ...
null
null
null
Return text logo.
pcsd
def logo col=None version='' col = col if col else random choice c g c r c y c b c p c w logo txt = " | | | | | ' ` \\| ' \\/ | | | | |/ \\| | | | | | | | ' \\ / \\ | | | | | | | \\ \\ | | | | | | | | | | | | | | | / | | | | | | /| / \\ |\\ / \\ |\\ |\\ | / \\ | | | | /" version = ' v' + version if version else '' logo...
3586
def logo(col=None, version=''): col = (col if col else random.choice((c.g, c.r, c.y, c.b, c.p, c.w))) logo_txt = " _ _\n _ __ ___ _ __ ___ _ _ ___ _ _| |_ _ _| |__ ___\n| '_ ` _ \\| '_ \\/ __|_____| | | |/ _ \\| | | | __| | | | '_ \\ / _ \\\n| | | ...
Return text logo.
return text logo .
Question: What does this function do? Code: def logo(col=None, version=''): col = (col if col else random.choice((c.g, c.r, c.y, c.b, c.p, c.w))) logo_txt = " _ _\n _ __ ___ _ __ ___ _ _ ___ _ _| |_ _ _| |__ ___\n| '_ ` _ \\| '_ \\/ __|_____| | ...
null
null
null
What does this function do?
def _read_images(): sprites = dict() files = tf.gfile.Glob(tf.flags.FLAGS.data_filepattern) for f in files: image = scipy.misc.imread(f) m = re.search('image_([0-9]+)_([0-9]+)_([0-9]+).jpg', os.path.basename(f)) if (m.group(1) not in sprites): sprites[m.group(1)] = dict() character = sprites[m.group(1)] ...
null
null
null
Read images from image files into data structure.
pcsd
def read images sprites = dict files = tf gfile Glob tf flags FLAGS data filepattern for f in files image = scipy misc imread f m = re search 'image [0-9]+ [0-9]+ [0-9]+ jpg' os path basename f if m group 1 not in sprites sprites[m group 1 ] = dict character = sprites[m group 1 ] if m group 2 not in character character...
3607
def _read_images(): sprites = dict() files = tf.gfile.Glob(tf.flags.FLAGS.data_filepattern) for f in files: image = scipy.misc.imread(f) m = re.search('image_([0-9]+)_([0-9]+)_([0-9]+).jpg', os.path.basename(f)) if (m.group(1) not in sprites): sprites[m.group(1)] = dict() character = sprites[m.group(1)] ...
Read images from image files into data structure.
read images from image files into data structure .
Question: What does this function do? Code: def _read_images(): sprites = dict() files = tf.gfile.Glob(tf.flags.FLAGS.data_filepattern) for f in files: image = scipy.misc.imread(f) m = re.search('image_([0-9]+)_([0-9]+)_([0-9]+).jpg', os.path.basename(f)) if (m.group(1) not in sprites): sprites[m.group(1...
null
null
null
What does this function do?
def user_password_not_empty(key, data, errors, context): if ((data.get(('password_hash',), missing) is not missing) and authz.is_sysadmin(context.get('user'))): return if ((not (('password1',) in data)) and (not (('password2',) in data))): password = data.get(('password',), None) if (not password): errors[ke...
null
null
null
Only check if password is present if the user is created via action API. If not, user_both_passwords_entered will handle the validation
pcsd
def user password not empty key data errors context if data get 'password hash' missing is not missing and authz is sysadmin context get 'user' return if not 'password1' in data and not 'password2' in data password = data get 'password' None if not password errors[key] append 'Missing value'
3610
def user_password_not_empty(key, data, errors, context): if ((data.get(('password_hash',), missing) is not missing) and authz.is_sysadmin(context.get('user'))): return if ((not (('password1',) in data)) and (not (('password2',) in data))): password = data.get(('password',), None) if (not password): errors[ke...
Only check if password is present if the user is created via action API. If not, user_both_passwords_entered will handle the validation
only check if password is present if the user is created via action api .
Question: What does this function do? Code: def user_password_not_empty(key, data, errors, context): if ((data.get(('password_hash',), missing) is not missing) and authz.is_sysadmin(context.get('user'))): return if ((not (('password1',) in data)) and (not (('password2',) in data))): password = data.get(('passw...