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 p_and_expression_1(t):
pass
| null | null | null | and_expression : equality_expression | pcsd | def p and expression 1 t pass | 13146 | def p_and_expression_1(t):
pass
| and_expression : equality_expression | and _ expression : equality _ expression | Question:
What does this function do?
Code:
def p_and_expression_1(t):
pass
|
null | null | null | What does this function do? | def group():
tablename = 'auth_group'
if (not auth.s3_has_role(ADMIN)):
s3db.configure(tablename, deletable=False, editable=False, insertable=False)
ADD_ROLE = T('Create Role')
s3.crud_strings[tablename] = Storage(label_create=ADD_ROLE, title_display=T('Role Details'), title_list=T('Roles'), title_update=T('Edit ... | null | null | null | RESTful CRUD controller
- used by role_required autocomplete | pcsd | def group tablename = 'auth group' if not auth s3 has role ADMIN s3db configure tablename deletable=False editable=False insertable=False ADD ROLE = T 'Create Role' s3 crud strings[tablename] = Storage label create=ADD ROLE title display=T 'Role Details' title list=T 'Roles' title update=T 'Edit Role' label list button... | 13158 | def group():
tablename = 'auth_group'
if (not auth.s3_has_role(ADMIN)):
s3db.configure(tablename, deletable=False, editable=False, insertable=False)
ADD_ROLE = T('Create Role')
s3.crud_strings[tablename] = Storage(label_create=ADD_ROLE, title_display=T('Role Details'), title_list=T('Roles'), title_update=T('Edit ... | RESTful CRUD controller
- used by role_required autocomplete | restful crud controller - used by role _ required autocomplete | Question:
What does this function do?
Code:
def group():
tablename = 'auth_group'
if (not auth.s3_has_role(ADMIN)):
s3db.configure(tablename, deletable=False, editable=False, insertable=False)
ADD_ROLE = T('Create Role')
s3.crud_strings[tablename] = Storage(label_create=ADD_ROLE, title_display=T('Role Details'... |
null | null | null | What does this function do? | def _link(token, result):
return None
| null | null | null | A dummy function to link results together in a graph
We use this to enforce an artificial sequential ordering on tasks that
don\'t explicitly pass around a shared resource | pcsd | def link token result return None | 13169 | def _link(token, result):
return None
| A dummy function to link results together in a graph
We use this to enforce an artificial sequential ordering on tasks that
don\'t explicitly pass around a shared resource | a dummy function to link results together in a graph | Question:
What does this function do?
Code:
def _link(token, result):
return None
|
null | null | null | What does this function do? | def _zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2):
maxiter = 10
i = 0
delta1 = 0.2
delta2 = 0.1
phi_rec = phi0
a_rec = 0
while True:
dalpha = (a_hi - a_lo)
if (dalpha < 0):
(a, b) = (a_hi, a_lo)
else:
(a, b) = (a_lo, a_hi)
if (i > 0):
cchk = (delta1 * dalpha)
... | null | null | null | Part of the optimization algorithm in `scalar_search_wolfe2`. | pcsd | def zoom a lo a hi phi lo phi hi derphi lo phi derphi phi0 derphi0 c1 c2 maxiter = 10 i = 0 delta1 = 0 2 delta2 = 0 1 phi rec = phi0 a rec = 0 while True dalpha = a hi - a lo if dalpha < 0 a b = a hi a lo else a b = a lo a hi if i > 0 cchk = delta1 * dalpha a j = cubicmin a lo phi lo derphi lo a hi phi hi a rec phi rec... | 13170 | def _zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2):
maxiter = 10
i = 0
delta1 = 0.2
delta2 = 0.1
phi_rec = phi0
a_rec = 0
while True:
dalpha = (a_hi - a_lo)
if (dalpha < 0):
(a, b) = (a_hi, a_lo)
else:
(a, b) = (a_lo, a_hi)
if (i > 0):
cchk = (delta1 * dalpha)
... | Part of the optimization algorithm in `scalar_search_wolfe2`. | part of the optimization algorithm in scalar _ search _ wolfe2 . | Question:
What does this function do?
Code:
def _zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2):
maxiter = 10
i = 0
delta1 = 0.2
delta2 = 0.1
phi_rec = phi0
a_rec = 0
while True:
dalpha = (a_hi - a_lo)
if (dalpha < 0):
(a, b) = (a_hi, a_lo)
else:
(a, b) = (a_lo, a_... |
null | null | null | What does this function do? | def _check_asset(location, asset_name):
content_location = StaticContent.compute_location(location.course_key, asset_name)
try:
contentstore().find(content_location)
except NotFoundError:
return False
else:
return True
| null | null | null | Check that asset with asset_name exists in assets. | pcsd | def check asset location asset name content location = Static Content compute location location course key asset name try contentstore find content location except Not Found Error return False else return True | 13177 | def _check_asset(location, asset_name):
content_location = StaticContent.compute_location(location.course_key, asset_name)
try:
contentstore().find(content_location)
except NotFoundError:
return False
else:
return True
| Check that asset with asset_name exists in assets. | check that asset with asset _ name exists in assets . | Question:
What does this function do?
Code:
def _check_asset(location, asset_name):
content_location = StaticContent.compute_location(location.course_key, asset_name)
try:
contentstore().find(content_location)
except NotFoundError:
return False
else:
return True
|
null | null | null | What does this function do? | @addon_view
@non_atomic_requests
def overview_series(request, addon, group, start, end, format):
date_range = check_series_params_or_404(group, start, end, format)
check_stats_permission(request, addon)
dls = get_series(DownloadCount, addon=addon.id, date__range=date_range)
updates = get_series(UpdateCount, addon=a... | null | null | null | Combines downloads_series and updates_series into one payload. | pcsd | @addon view @non atomic requests def overview series request addon group start end format date range = check series params or 404 group start end format check stats permission request addon dls = get series Download Count addon=addon id date range=date range updates = get series Update Count addon=addon id date range=d... | 13180 | @addon_view
@non_atomic_requests
def overview_series(request, addon, group, start, end, format):
date_range = check_series_params_or_404(group, start, end, format)
check_stats_permission(request, addon)
dls = get_series(DownloadCount, addon=addon.id, date__range=date_range)
updates = get_series(UpdateCount, addon=a... | Combines downloads_series and updates_series into one payload. | combines downloads _ series and updates _ series into one payload . | Question:
What does this function do?
Code:
@addon_view
@non_atomic_requests
def overview_series(request, addon, group, start, end, format):
date_range = check_series_params_or_404(group, start, end, format)
check_stats_permission(request, addon)
dls = get_series(DownloadCount, addon=addon.id, date__range=date_ra... |
null | null | null | What does this function do? | def available_calculators():
return CALCULATED_AGGREGATIONS.keys()
| null | null | null | Returns a list of available calculators. | pcsd | def available calculators return CALCULATED AGGREGATIONS keys | 13184 | def available_calculators():
return CALCULATED_AGGREGATIONS.keys()
| Returns a list of available calculators. | returns a list of available calculators . | Question:
What does this function do?
Code:
def available_calculators():
return CALCULATED_AGGREGATIONS.keys()
|
null | null | null | What does this function do? | @handle_response_format
@treeio_login_required
def contact_add_typed(request, type_id, response_format='html'):
contact_type = get_object_or_404(ContactType, pk=type_id)
if (not request.user.profile.has_permission(contact_type, mode='x')):
return user_denied(request, message=("You don't have access to create " + un... | null | null | null | Contact add with preselected type | pcsd | @handle response format @treeio login required def contact add typed request type id response format='html' contact type = get object or 404 Contact Type pk=type id if not request user profile has permission contact type mode='x' return user denied request message= "You don't have access to create " + unicode contact t... | 13197 | @handle_response_format
@treeio_login_required
def contact_add_typed(request, type_id, response_format='html'):
contact_type = get_object_or_404(ContactType, pk=type_id)
if (not request.user.profile.has_permission(contact_type, mode='x')):
return user_denied(request, message=("You don't have access to create " + un... | Contact add with preselected type | contact add with preselected type | Question:
What does this function do?
Code:
@handle_response_format
@treeio_login_required
def contact_add_typed(request, type_id, response_format='html'):
contact_type = get_object_or_404(ContactType, pk=type_id)
if (not request.user.profile.has_permission(contact_type, mode='x')):
return user_denied(request, m... |
null | null | null | What does this function do? | def _evaluate_for_annotation(evaluator, annotation, index=None):
if (annotation is not None):
definitions = evaluator.eval_element(_fix_forward_reference(evaluator, annotation))
if (index is not None):
definitions = list(itertools.chain.from_iterable((definition.py__getitem__(index) for definition in definition... | null | null | null | Evaluates a string-node, looking for an annotation
If index is not None, the annotation is expected to be a tuple
and we\'re interested in that index | pcsd | def evaluate for annotation evaluator annotation index=None if annotation is not None definitions = evaluator eval element fix forward reference evaluator annotation if index is not None definitions = list itertools chain from iterable definition py getitem index for definition in definitions if definition type == 'tup... | 13212 | def _evaluate_for_annotation(evaluator, annotation, index=None):
if (annotation is not None):
definitions = evaluator.eval_element(_fix_forward_reference(evaluator, annotation))
if (index is not None):
definitions = list(itertools.chain.from_iterable((definition.py__getitem__(index) for definition in definition... | Evaluates a string-node, looking for an annotation
If index is not None, the annotation is expected to be a tuple
and we\'re interested in that index | evaluates a string - node , looking for an annotation | Question:
What does this function do?
Code:
def _evaluate_for_annotation(evaluator, annotation, index=None):
if (annotation is not None):
definitions = evaluator.eval_element(_fix_forward_reference(evaluator, annotation))
if (index is not None):
definitions = list(itertools.chain.from_iterable((definition.py... |
null | null | null | What does this function do? | def read_file_content(fileName):
try:
with open(fileName, u'rU') as f:
content = f.read()
except IOError as reason:
raise NinjaIOException(reason)
except:
raise
return content
| null | null | null | Read a file content, this function is used to load Editor content. | pcsd | def read file content file Name try with open file Name u'r U' as f content = f read except IO Error as reason raise Ninja IO Exception reason except raise return content | 13213 | def read_file_content(fileName):
try:
with open(fileName, u'rU') as f:
content = f.read()
except IOError as reason:
raise NinjaIOException(reason)
except:
raise
return content
| Read a file content, this function is used to load Editor content. | read a file content , this function is used to load editor content . | Question:
What does this function do?
Code:
def read_file_content(fileName):
try:
with open(fileName, u'rU') as f:
content = f.read()
except IOError as reason:
raise NinjaIOException(reason)
except:
raise
return content
|
null | null | null | What does this function do? | def get_cert(zappa_instance, log=LOGGER, CA=DEFAULT_CA):
out = parse_account_key()
header = get_boulder_header(out)
accountkey_json = json.dumps(header['jwk'], sort_keys=True, separators=(',', ':'))
thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())
domains = parse_csr()
register_account()... | null | null | null | Call LE to get a new signed CA. | pcsd | def get cert zappa instance log=LOGGER CA=DEFAULT CA out = parse account key header = get boulder header out accountkey json = json dumps header['jwk'] sort keys=True separators= ' ' ' ' thumbprint = b64 hashlib sha256 accountkey json encode 'utf8' digest domains = parse csr register account for domain in domains log i... | 13214 | def get_cert(zappa_instance, log=LOGGER, CA=DEFAULT_CA):
out = parse_account_key()
header = get_boulder_header(out)
accountkey_json = json.dumps(header['jwk'], sort_keys=True, separators=(',', ':'))
thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())
domains = parse_csr()
register_account()... | Call LE to get a new signed CA. | call le to get a new signed ca . | Question:
What does this function do?
Code:
def get_cert(zappa_instance, log=LOGGER, CA=DEFAULT_CA):
out = parse_account_key()
header = get_boulder_header(out)
accountkey_json = json.dumps(header['jwk'], sort_keys=True, separators=(',', ':'))
thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).diges... |
null | null | null | What does this function do? | def _unpack_user(v):
uv = v.uservalue()
email = unicode(uv.email().decode('utf-8'))
auth_domain = unicode(uv.auth_domain().decode('utf-8'))
obfuscated_gaiaid = uv.obfuscated_gaiaid().decode('utf-8')
obfuscated_gaiaid = unicode(obfuscated_gaiaid)
federated_identity = None
if uv.has_federated_identity():
federat... | null | null | null | Internal helper to unpack a User value from a protocol buffer. | pcsd | def unpack user v uv = v uservalue email = unicode uv email decode 'utf-8' auth domain = unicode uv auth domain decode 'utf-8' obfuscated gaiaid = uv obfuscated gaiaid decode 'utf-8' obfuscated gaiaid = unicode obfuscated gaiaid federated identity = None if uv has federated identity federated identity = unicode uv fede... | 13215 | def _unpack_user(v):
uv = v.uservalue()
email = unicode(uv.email().decode('utf-8'))
auth_domain = unicode(uv.auth_domain().decode('utf-8'))
obfuscated_gaiaid = uv.obfuscated_gaiaid().decode('utf-8')
obfuscated_gaiaid = unicode(obfuscated_gaiaid)
federated_identity = None
if uv.has_federated_identity():
federat... | Internal helper to unpack a User value from a protocol buffer. | internal helper to unpack a user value from a protocol buffer . | Question:
What does this function do?
Code:
def _unpack_user(v):
uv = v.uservalue()
email = unicode(uv.email().decode('utf-8'))
auth_domain = unicode(uv.auth_domain().decode('utf-8'))
obfuscated_gaiaid = uv.obfuscated_gaiaid().decode('utf-8')
obfuscated_gaiaid = unicode(obfuscated_gaiaid)
federated_identity = ... |
null | null | null | What does this function do? | def ldapUrlEscape(s):
return quote(s).replace(',', '%2C').replace('/', '%2F')
| null | null | null | Returns URL encoding of string s | pcsd | def ldap Url Escape s return quote s replace ' ' '%2C' replace '/' '%2F' | 13217 | def ldapUrlEscape(s):
return quote(s).replace(',', '%2C').replace('/', '%2F')
| Returns URL encoding of string s | returns url encoding of string s | Question:
What does this function do?
Code:
def ldapUrlEscape(s):
return quote(s).replace(',', '%2C').replace('/', '%2F')
|
null | null | null | What does this function do? | def _cleaned(_dashboard):
dashboard = copy.deepcopy(_dashboard)
for ignored_dashboard_field in _IGNORED_DASHBOARD_FIELDS:
dashboard.pop(ignored_dashboard_field, None)
for row in dashboard.get('rows', []):
for ignored_row_field in _IGNORED_ROW_FIELDS:
row.pop(ignored_row_field, None)
for (i, panel) in enumer... | null | null | null | Return a copy without fields that can differ. | pcsd | def cleaned dashboard dashboard = copy deepcopy dashboard for ignored dashboard field in IGNORED DASHBOARD FIELDS dashboard pop ignored dashboard field None for row in dashboard get 'rows' [] for ignored row field in IGNORED ROW FIELDS row pop ignored row field None for i panel in enumerate row get 'panels' [] for igno... | 13232 | def _cleaned(_dashboard):
dashboard = copy.deepcopy(_dashboard)
for ignored_dashboard_field in _IGNORED_DASHBOARD_FIELDS:
dashboard.pop(ignored_dashboard_field, None)
for row in dashboard.get('rows', []):
for ignored_row_field in _IGNORED_ROW_FIELDS:
row.pop(ignored_row_field, None)
for (i, panel) in enumer... | Return a copy without fields that can differ. | return a copy without fields that can differ . | Question:
What does this function do?
Code:
def _cleaned(_dashboard):
dashboard = copy.deepcopy(_dashboard)
for ignored_dashboard_field in _IGNORED_DASHBOARD_FIELDS:
dashboard.pop(ignored_dashboard_field, None)
for row in dashboard.get('rows', []):
for ignored_row_field in _IGNORED_ROW_FIELDS:
row.pop(igno... |
null | null | null | What does this function do? | def extrapolate_statistics(scope):
c = {}
for (k, v) in list(scope.items()):
if isinstance(v, dict):
v = extrapolate_statistics(v)
elif isinstance(v, (list, tuple)):
v = [extrapolate_statistics(record) for record in v]
elif hasattr(v, '__call__'):
v = v(scope)
c[k] = v
return c
| null | null | null | Return an extrapolated copy of the given scope. | pcsd | def extrapolate statistics scope c = {} for k v in list scope items if isinstance v dict v = extrapolate statistics v elif isinstance v list tuple v = [extrapolate statistics record for record in v] elif hasattr v ' call ' v = v scope c[k] = v return c | 13236 | def extrapolate_statistics(scope):
c = {}
for (k, v) in list(scope.items()):
if isinstance(v, dict):
v = extrapolate_statistics(v)
elif isinstance(v, (list, tuple)):
v = [extrapolate_statistics(record) for record in v]
elif hasattr(v, '__call__'):
v = v(scope)
c[k] = v
return c
| Return an extrapolated copy of the given scope. | return an extrapolated copy of the given scope . | Question:
What does this function do?
Code:
def extrapolate_statistics(scope):
c = {}
for (k, v) in list(scope.items()):
if isinstance(v, dict):
v = extrapolate_statistics(v)
elif isinstance(v, (list, tuple)):
v = [extrapolate_statistics(record) for record in v]
elif hasattr(v, '__call__'):
v = v(sc... |
null | null | null | What does this function do? | def createForeignKeys(tables, ifNotExists=True):
errors = []
mapTables = {}
for table in tables:
mapTables[table._imdbpyName] = table
for table in tables:
_dbschema_logger.info('creating foreign keys for table %s', table._imdbpyName)
try:
table.addForeignKeys(mapTables, ifNotExists)
except Exception as e... | null | null | null | Create Foreign Keys.
Return a list of errors, if any. | pcsd | def create Foreign Keys tables if Not Exists=True errors = [] map Tables = {} for table in tables map Tables[table imdbpy Name] = table for table in tables dbschema logger info 'creating foreign keys for table %s' table imdbpy Name try table add Foreign Keys map Tables if Not Exists except Exception as e errors append ... | 13239 | def createForeignKeys(tables, ifNotExists=True):
errors = []
mapTables = {}
for table in tables:
mapTables[table._imdbpyName] = table
for table in tables:
_dbschema_logger.info('creating foreign keys for table %s', table._imdbpyName)
try:
table.addForeignKeys(mapTables, ifNotExists)
except Exception as e... | Create Foreign Keys.
Return a list of errors, if any. | create foreign keys . | Question:
What does this function do?
Code:
def createForeignKeys(tables, ifNotExists=True):
errors = []
mapTables = {}
for table in tables:
mapTables[table._imdbpyName] = table
for table in tables:
_dbschema_logger.info('creating foreign keys for table %s', table._imdbpyName)
try:
table.addForeignKeys(... |
null | null | null | What does this function do? | def getLoopsIntersection(importRadius, loopLists):
intercircle.directLoopLists(True, loopLists)
if (len(loopLists) < 1):
return []
if (len(loopLists) < 2):
return loopLists[0]
loopsIntersection = loopLists[0]
for loopList in loopLists[1:]:
loopsIntersection = getLoopsIntersectionByPair(importRadius, loopsInt... | null | null | null | Get intersection loops. | pcsd | def get Loops Intersection import Radius loop Lists intercircle direct Loop Lists True loop Lists if len loop Lists < 1 return [] if len loop Lists < 2 return loop Lists[0] loops Intersection = loop Lists[0] for loop List in loop Lists[1 ] loops Intersection = get Loops Intersection By Pair import Radius loops Intersec... | 13242 | def getLoopsIntersection(importRadius, loopLists):
intercircle.directLoopLists(True, loopLists)
if (len(loopLists) < 1):
return []
if (len(loopLists) < 2):
return loopLists[0]
loopsIntersection = loopLists[0]
for loopList in loopLists[1:]:
loopsIntersection = getLoopsIntersectionByPair(importRadius, loopsInt... | Get intersection loops. | get intersection loops . | Question:
What does this function do?
Code:
def getLoopsIntersection(importRadius, loopLists):
intercircle.directLoopLists(True, loopLists)
if (len(loopLists) < 1):
return []
if (len(loopLists) < 2):
return loopLists[0]
loopsIntersection = loopLists[0]
for loopList in loopLists[1:]:
loopsIntersection = ge... |
null | null | null | What does this function do? | def pipeline_factory_v21(loader, global_conf, **local_conf):
return _load_pipeline(loader, local_conf[CONF.api.auth_strategy].split())
| null | null | null | A paste pipeline replica that keys off of auth_strategy. | pcsd | def pipeline factory v21 loader global conf **local conf return load pipeline loader local conf[CONF api auth strategy] split | 13244 | def pipeline_factory_v21(loader, global_conf, **local_conf):
return _load_pipeline(loader, local_conf[CONF.api.auth_strategy].split())
| A paste pipeline replica that keys off of auth_strategy. | a paste pipeline replica that keys off of auth _ strategy . | Question:
What does this function do?
Code:
def pipeline_factory_v21(loader, global_conf, **local_conf):
return _load_pipeline(loader, local_conf[CONF.api.auth_strategy].split())
|
null | null | null | What does this function do? | def set_invalid_utime(path):
try:
os.utime(path, ((-1), (-100000000000)))
except (OSError, OverflowError):
os.utime(path, ((-1), (-1)))
| null | null | null | Helper function to set an invalid last modified time | pcsd | def set invalid utime path try os utime path -1 -100000000000 except OS Error Overflow Error os utime path -1 -1 | 13245 | def set_invalid_utime(path):
try:
os.utime(path, ((-1), (-100000000000)))
except (OSError, OverflowError):
os.utime(path, ((-1), (-1)))
| Helper function to set an invalid last modified time | helper function to set an invalid last modified time | Question:
What does this function do?
Code:
def set_invalid_utime(path):
try:
os.utime(path, ((-1), (-100000000000)))
except (OSError, OverflowError):
os.utime(path, ((-1), (-1)))
|
null | null | null | What does this function do? | def un_camel_case(s):
return re.sub('(?<=\\w)([A-Z])', ' \\1', s)
| null | null | null | Inserts spaces before the capital letters in a camel case string. | pcsd | def un camel case s return re sub ' ?<=\\w [A-Z] ' ' \\1' s | 13248 | def un_camel_case(s):
return re.sub('(?<=\\w)([A-Z])', ' \\1', s)
| Inserts spaces before the capital letters in a camel case string. | inserts spaces before the capital letters in a camel case string . | Question:
What does this function do?
Code:
def un_camel_case(s):
return re.sub('(?<=\\w)([A-Z])', ' \\1', s)
|
null | null | null | What does this function do? | def canonicalName(name):
if (name.find(', ') != (-1)):
return name
if isinstance(name, unicode):
joiner = u'%s, %s'
sur_joiner = u'%s %s'
sur_space = u' %s'
space = u' '
else:
joiner = '%s, %s'
sur_joiner = '%s %s'
sur_space = ' %s'
space = ' '
sname = name.split(' ')
snl = len(sname)
if (snl ==... | null | null | null | Return the given name in canonical "Surname, Name" format.
It assumes that name is in the \'Name Surname\' format. | pcsd | def canonical Name name if name find ' ' != -1 return name if isinstance name unicode joiner = u'%s %s' sur joiner = u'%s %s' sur space = u' %s' space = u' ' else joiner = '%s %s' sur joiner = '%s %s' sur space = ' %s' space = ' ' sname = name split ' ' snl = len sname if snl == 2 name = joiner % sname[1] sname[0] elif... | 13249 | def canonicalName(name):
if (name.find(', ') != (-1)):
return name
if isinstance(name, unicode):
joiner = u'%s, %s'
sur_joiner = u'%s %s'
sur_space = u' %s'
space = u' '
else:
joiner = '%s, %s'
sur_joiner = '%s %s'
sur_space = ' %s'
space = ' '
sname = name.split(' ')
snl = len(sname)
if (snl ==... | Return the given name in canonical "Surname, Name" format.
It assumes that name is in the \'Name Surname\' format. | return the given name in canonical " surname , name " format . | Question:
What does this function do?
Code:
def canonicalName(name):
if (name.find(', ') != (-1)):
return name
if isinstance(name, unicode):
joiner = u'%s, %s'
sur_joiner = u'%s %s'
sur_space = u' %s'
space = u' '
else:
joiner = '%s, %s'
sur_joiner = '%s %s'
sur_space = ' %s'
space = ' '
sname ... |
null | null | null | What does this function do? | def checksum_question(question, timestamp):
challenge = u''.join((settings.SECRET_KEY, question, timestamp))
sha = hashlib.sha1(challenge.encode(u'utf-8'))
return sha.hexdigest()
| null | null | null | Returns checksum for a question. | pcsd | def checksum question question timestamp challenge = u'' join settings SECRET KEY question timestamp sha = hashlib sha1 challenge encode u'utf-8' return sha hexdigest | 13251 | def checksum_question(question, timestamp):
challenge = u''.join((settings.SECRET_KEY, question, timestamp))
sha = hashlib.sha1(challenge.encode(u'utf-8'))
return sha.hexdigest()
| Returns checksum for a question. | returns checksum for a question . | Question:
What does this function do?
Code:
def checksum_question(question, timestamp):
challenge = u''.join((settings.SECRET_KEY, question, timestamp))
sha = hashlib.sha1(challenge.encode(u'utf-8'))
return sha.hexdigest()
|
null | null | null | What does this function do? | def random_distribution(size=vocabulary_size):
b = np.random.uniform(0.0, 1.0, size=[1, size])
return (b / np.sum(b, 1)[:, None])
| null | null | null | Generate a random column of probabilities. | pcsd | def random distribution size=vocabulary size b = np random uniform 0 0 1 0 size=[1 size] return b / np sum b 1 [ None] | 13261 | def random_distribution(size=vocabulary_size):
b = np.random.uniform(0.0, 1.0, size=[1, size])
return (b / np.sum(b, 1)[:, None])
| Generate a random column of probabilities. | generate a random column of probabilities . | Question:
What does this function do?
Code:
def random_distribution(size=vocabulary_size):
b = np.random.uniform(0.0, 1.0, size=[1, size])
return (b / np.sum(b, 1)[:, None])
|
null | null | null | What does this function do? | def _convert_to_varsSOP(minterm, variables):
temp = []
for (i, m) in enumerate(minterm):
if (m == 0):
temp.append(Not(variables[i]))
elif (m == 1):
temp.append(variables[i])
else:
pass
return And(*temp)
| null | null | null | Converts a term in the expansion of a function from binary to it\'s
variable form (for SOP). | pcsd | def convert to vars SOP minterm variables temp = [] for i m in enumerate minterm if m == 0 temp append Not variables[i] elif m == 1 temp append variables[i] else pass return And *temp | 13270 | def _convert_to_varsSOP(minterm, variables):
temp = []
for (i, m) in enumerate(minterm):
if (m == 0):
temp.append(Not(variables[i]))
elif (m == 1):
temp.append(variables[i])
else:
pass
return And(*temp)
| Converts a term in the expansion of a function from binary to it\'s
variable form (for SOP). | converts a term in the expansion of a function from binary to its variable form . | Question:
What does this function do?
Code:
def _convert_to_varsSOP(minterm, variables):
temp = []
for (i, m) in enumerate(minterm):
if (m == 0):
temp.append(Not(variables[i]))
elif (m == 1):
temp.append(variables[i])
else:
pass
return And(*temp)
|
null | null | null | What does this function do? | def c_login(client):
cname = (DUMMY_NAME % client.gid)
cpwd = (DUMMY_PWD % client.gid)
roomname = (ROOM_TEMPLATE % client.counter())
exitname1 = (EXIT_TEMPLATE % client.counter())
exitname2 = (EXIT_TEMPLATE % client.counter())
client.exits.extend([exitname1, exitname2])
cmds = (('create %s %s' % (cname, cpwd)), ... | null | null | null | logins to the game | pcsd | def c login client cname = DUMMY NAME % client gid cpwd = DUMMY PWD % client gid roomname = ROOM TEMPLATE % client counter exitname1 = EXIT TEMPLATE % client counter exitname2 = EXIT TEMPLATE % client counter client exits extend [exitname1 exitname2] cmds = 'create %s %s' % cname cpwd 'connect %s %s' % cname cpwd '@dig... | 13273 | def c_login(client):
cname = (DUMMY_NAME % client.gid)
cpwd = (DUMMY_PWD % client.gid)
roomname = (ROOM_TEMPLATE % client.counter())
exitname1 = (EXIT_TEMPLATE % client.counter())
exitname2 = (EXIT_TEMPLATE % client.counter())
client.exits.extend([exitname1, exitname2])
cmds = (('create %s %s' % (cname, cpwd)), ... | logins to the game | logins to the game | Question:
What does this function do?
Code:
def c_login(client):
cname = (DUMMY_NAME % client.gid)
cpwd = (DUMMY_PWD % client.gid)
roomname = (ROOM_TEMPLATE % client.counter())
exitname1 = (EXIT_TEMPLATE % client.counter())
exitname2 = (EXIT_TEMPLATE % client.counter())
client.exits.extend([exitname1, exitname... |
null | null | null | What does this function do? | @non_atomic_requests
def api_view(request, platform, version, list_type, api_version=1.5, format='json', content_type='application/json', compat_mode='strict'):
view = legacy_api_views.ListView()
(view.request, view.version) = (request, api_version)
(view.format, view.content_type) = (format, content_type)
r = view... | null | null | null | Wrapper for calling an API view. | pcsd | @non atomic requests def api view request platform version list type api version=1 5 format='json' content type='application/json' compat mode='strict' view = legacy api views List View view request view version = request api version view format view content type = format content type r = view process request list type... | 13275 | @non_atomic_requests
def api_view(request, platform, version, list_type, api_version=1.5, format='json', content_type='application/json', compat_mode='strict'):
view = legacy_api_views.ListView()
(view.request, view.version) = (request, api_version)
(view.format, view.content_type) = (format, content_type)
r = view... | Wrapper for calling an API view. | wrapper for calling an api view . | Question:
What does this function do?
Code:
@non_atomic_requests
def api_view(request, platform, version, list_type, api_version=1.5, format='json', content_type='application/json', compat_mode='strict'):
view = legacy_api_views.ListView()
(view.request, view.version) = (request, api_version)
(view.format, view.c... |
null | null | null | What does this function do? | def deploy_mission_hrquantity(row):
if hasattr(row, 'deploy_mission'):
row = row.deploy_mission
try:
mission_id = row.id
except AttributeError:
return 0
db = current.db
table = db.deploy_assignment
count = table.id.count()
row = db((table.mission_id == mission_id)).select(count).first()
if row:
return r... | null | null | null | Number of human resources deployed | pcsd | def deploy mission hrquantity row if hasattr row 'deploy mission' row = row deploy mission try mission id = row id except Attribute Error return 0 db = current db table = db deploy assignment count = table id count row = db table mission id == mission id select count first if row return row[count] else return 0 | 13277 | def deploy_mission_hrquantity(row):
if hasattr(row, 'deploy_mission'):
row = row.deploy_mission
try:
mission_id = row.id
except AttributeError:
return 0
db = current.db
table = db.deploy_assignment
count = table.id.count()
row = db((table.mission_id == mission_id)).select(count).first()
if row:
return r... | Number of human resources deployed | number of human resources deployed | Question:
What does this function do?
Code:
def deploy_mission_hrquantity(row):
if hasattr(row, 'deploy_mission'):
row = row.deploy_mission
try:
mission_id = row.id
except AttributeError:
return 0
db = current.db
table = db.deploy_assignment
count = table.id.count()
row = db((table.mission_id == mission... |
null | null | null | What does this function do? | def get_image_dimensions(file_or_path, close=False):
try:
from PIL import ImageFile as PILImageFile
except ImportError:
import ImageFile as PILImageFile
p = PILImageFile.Parser()
if hasattr(file_or_path, 'read'):
file = file_or_path
file_pos = file.tell()
file.seek(0)
else:
file = open(file_or_path, 'r... | null | null | null | Returns the (width, height) of an image, given an open file or a path. Set
\'close\' to True to close the file at the end if it is initially in an open
state. | pcsd | def get image dimensions file or path close=False try from PIL import Image File as PIL Image File except Import Error import Image File as PIL Image File p = PIL Image File Parser if hasattr file or path 'read' file = file or path file pos = file tell file seek 0 else file = open file or path 'rb' close = True try whi... | 13280 | def get_image_dimensions(file_or_path, close=False):
try:
from PIL import ImageFile as PILImageFile
except ImportError:
import ImageFile as PILImageFile
p = PILImageFile.Parser()
if hasattr(file_or_path, 'read'):
file = file_or_path
file_pos = file.tell()
file.seek(0)
else:
file = open(file_or_path, 'r... | Returns the (width, height) of an image, given an open file or a path. Set
\'close\' to True to close the file at the end if it is initially in an open
state. | returns the of an image , given an open file or a path . | Question:
What does this function do?
Code:
def get_image_dimensions(file_or_path, close=False):
try:
from PIL import ImageFile as PILImageFile
except ImportError:
import ImageFile as PILImageFile
p = PILImageFile.Parser()
if hasattr(file_or_path, 'read'):
file = file_or_path
file_pos = file.tell()
fil... |
null | null | null | What does this function do? | def connect_action(action, fn):
action.triggered[bool].connect((lambda x: fn()))
| null | null | null | Connect an action to a function | pcsd | def connect action action fn action triggered[bool] connect lambda x fn | 13281 | def connect_action(action, fn):
action.triggered[bool].connect((lambda x: fn()))
| Connect an action to a function | connect an action to a function | Question:
What does this function do?
Code:
def connect_action(action, fn):
action.triggered[bool].connect((lambda x: fn()))
|
null | null | null | What does this function do? | def getRotatedComplexes(planeAngle, points):
rotatedComplexes = []
for point in points:
rotatedComplexes.append((planeAngle * point))
return rotatedComplexes
| null | null | null | Get points rotated by the plane angle | pcsd | def get Rotated Complexes plane Angle points rotated Complexes = [] for point in points rotated Complexes append plane Angle * point return rotated Complexes | 13286 | def getRotatedComplexes(planeAngle, points):
rotatedComplexes = []
for point in points:
rotatedComplexes.append((planeAngle * point))
return rotatedComplexes
| Get points rotated by the plane angle | get points rotated by the plane angle | Question:
What does this function do?
Code:
def getRotatedComplexes(planeAngle, points):
rotatedComplexes = []
for point in points:
rotatedComplexes.append((planeAngle * point))
return rotatedComplexes
|
null | null | null | What does this function do? | def validate_integer(value, name, min_value=None, max_value=None):
try:
value = int(str(value))
except (ValueError, UnicodeEncodeError):
msg = _('%(value_name)s must be an integer')
raise exception.InvalidInput(reason=(msg % {'value_name': name}))
if (min_value is not None):
if (value < min_value):
msg = ... | null | null | null | Make sure that value is a valid integer, potentially within range. | pcsd | def validate integer value name min value=None max value=None try value = int str value except Value Error Unicode Encode Error msg = '% value name s must be an integer' raise exception Invalid Input reason= msg % {'value name' name} if min value is not None if value < min value msg = '% value name s must be >= % min v... | 13304 | def validate_integer(value, name, min_value=None, max_value=None):
try:
value = int(str(value))
except (ValueError, UnicodeEncodeError):
msg = _('%(value_name)s must be an integer')
raise exception.InvalidInput(reason=(msg % {'value_name': name}))
if (min_value is not None):
if (value < min_value):
msg = ... | Make sure that value is a valid integer, potentially within range. | make sure that value is a valid integer , potentially within range . | Question:
What does this function do?
Code:
def validate_integer(value, name, min_value=None, max_value=None):
try:
value = int(str(value))
except (ValueError, UnicodeEncodeError):
msg = _('%(value_name)s must be an integer')
raise exception.InvalidInput(reason=(msg % {'value_name': name}))
if (min_value is... |
null | null | null | What does this function do? | def get_sql_flush(style, tables, sequences):
if tables:
sql = ((['SET FOREIGN_KEY_CHECKS = 0;'] + [('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table)))) for table in tables]) + ['SET FOREIGN_KEY_CHECKS = 1;'])
sql.extend([('%s %s %s %s %s;' % (style.SQL_KEYWORD('ALTER'), style.SQL_KEYWOR... | null | null | null | Return a list of SQL statements required to remove all data from
all tables in the database (without actually removing the tables
themselves) and put the database in an empty \'initial\' state | pcsd | def get sql flush style tables sequences if tables sql = ['SET FOREIGN KEY CHECKS = 0 '] + [ '%s %s ' % style SQL KEYWORD 'TRUNCATE' style SQL FIELD quote name table for table in tables] + ['SET FOREIGN KEY CHECKS = 1 '] sql extend [ '%s %s %s %s %s ' % style SQL KEYWORD 'ALTER' style SQL KEYWORD 'TABLE' style SQL TABL... | 13306 | def get_sql_flush(style, tables, sequences):
if tables:
sql = ((['SET FOREIGN_KEY_CHECKS = 0;'] + [('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table)))) for table in tables]) + ['SET FOREIGN_KEY_CHECKS = 1;'])
sql.extend([('%s %s %s %s %s;' % (style.SQL_KEYWORD('ALTER'), style.SQL_KEYWOR... | Return a list of SQL statements required to remove all data from
all tables in the database (without actually removing the tables
themselves) and put the database in an empty \'initial\' state | return a list of sql statements required to remove all data from all tables in the database and put the database in an empty initial state | Question:
What does this function do?
Code:
def get_sql_flush(style, tables, sequences):
if tables:
sql = ((['SET FOREIGN_KEY_CHECKS = 0;'] + [('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table)))) for table in tables]) + ['SET FOREIGN_KEY_CHECKS = 1;'])
sql.extend([('%s %s %s %s %s;' ... |
null | null | null | What does this function do? | def output(string_):
context.output += str(string_)
| null | null | null | Appends `string_` to the response. | pcsd | def output string context output += str string | 13313 | def output(string_):
context.output += str(string_)
| Appends `string_` to the response. | appends string _ to the response . | Question:
What does this function do?
Code:
def output(string_):
context.output += str(string_)
|
null | null | null | What does this function do? | def get_head(repo_path):
try:
ref = open(os.path.join(repo_path, '.git', 'HEAD'), 'r').read().strip()[5:].split('/')
branch = ref[(-1)]
commit = open(os.path.join(repo_path, '.git', *ref), 'r').read().strip()[:7]
return (branch, commit)
except:
return None
| null | null | null | Get (branch, commit) from HEAD of a git repo. | pcsd | def get head repo path try ref = open os path join repo path ' git' 'HEAD' 'r' read strip [5 ] split '/' branch = ref[ -1 ] commit = open os path join repo path ' git' *ref 'r' read strip [ 7] return branch commit except return None | 13314 | def get_head(repo_path):
try:
ref = open(os.path.join(repo_path, '.git', 'HEAD'), 'r').read().strip()[5:].split('/')
branch = ref[(-1)]
commit = open(os.path.join(repo_path, '.git', *ref), 'r').read().strip()[:7]
return (branch, commit)
except:
return None
| Get (branch, commit) from HEAD of a git repo. | get from head of a git repo . | Question:
What does this function do?
Code:
def get_head(repo_path):
try:
ref = open(os.path.join(repo_path, '.git', 'HEAD'), 'r').read().strip()[5:].split('/')
branch = ref[(-1)]
commit = open(os.path.join(repo_path, '.git', *ref), 'r').read().strip()[:7]
return (branch, commit)
except:
return None
|
null | null | null | What does this function do? | def returner(ret):
try:
with _get_serv(ret, commit=True) as cur:
sql = 'INSERT INTO salt_returns\n (fun, jid, return, id, success, full_ret, alter_time)\n VALUES (%s, %s, %s, %s, %s, %s, %s)'
cur.execute(sql, (ret['fun'], ret['jid'], psycopg2.extras.Json(ret['return']), re... | null | null | null | Return data to a Pg server | pcsd | def returner ret try with get serv ret commit=True as cur sql = 'INSERT INTO salt returns fun jid return id success full ret alter time VALUES %s %s %s %s %s %s %s ' cur execute sql ret['fun'] ret['jid'] psycopg2 extras Json ret['return'] ret['id'] ret get 'success' False psycopg2 extras Json ret time strftime '%Y-%m-%... | 13319 | def returner(ret):
try:
with _get_serv(ret, commit=True) as cur:
sql = 'INSERT INTO salt_returns\n (fun, jid, return, id, success, full_ret, alter_time)\n VALUES (%s, %s, %s, %s, %s, %s, %s)'
cur.execute(sql, (ret['fun'], ret['jid'], psycopg2.extras.Json(ret['return']), re... | Return data to a Pg server | return data to a pg server | Question:
What does this function do?
Code:
def returner(ret):
try:
with _get_serv(ret, commit=True) as cur:
sql = 'INSERT INTO salt_returns\n (fun, jid, return, id, success, full_ret, alter_time)\n VALUES (%s, %s, %s, %s, %s, %s, %s)'
cur.execute(sql, (ret['fun'], ret[... |
null | null | null | What does this function do? | def askokcancel(title=None, message=None, **options):
s = _show(title, message, QUESTION, OKCANCEL, **options)
return (s == OK)
| null | null | null | Ask if operation should proceed; return true if the answer is ok | pcsd | def askokcancel title=None message=None **options s = show title message QUESTION OKCANCEL **options return s == OK | 13324 | def askokcancel(title=None, message=None, **options):
s = _show(title, message, QUESTION, OKCANCEL, **options)
return (s == OK)
| Ask if operation should proceed; return true if the answer is ok | ask if operation should proceed ; return true if the answer is ok | Question:
What does this function do?
Code:
def askokcancel(title=None, message=None, **options):
s = _show(title, message, QUESTION, OKCANCEL, **options)
return (s == OK)
|
null | null | null | What does this function do? | def check_incomplete_vs_complete():
complete = cfg.complete_dir.get_path()
if misc.same_file(cfg.download_dir.get_path(), complete):
if (misc.real_path('X', cfg.download_dir()) == cfg.download_dir()):
cfg.download_dir.set(os.path.join(complete, 'incomplete'))
else:
cfg.download_dir.set('incomplete')
| null | null | null | Make sure "incomplete" and "complete" are not identical | pcsd | def check incomplete vs complete complete = cfg complete dir get path if misc same file cfg download dir get path complete if misc real path 'X' cfg download dir == cfg download dir cfg download dir set os path join complete 'incomplete' else cfg download dir set 'incomplete' | 13330 | def check_incomplete_vs_complete():
complete = cfg.complete_dir.get_path()
if misc.same_file(cfg.download_dir.get_path(), complete):
if (misc.real_path('X', cfg.download_dir()) == cfg.download_dir()):
cfg.download_dir.set(os.path.join(complete, 'incomplete'))
else:
cfg.download_dir.set('incomplete')
| Make sure "incomplete" and "complete" are not identical | make sure " incomplete " and " complete " are not identical | Question:
What does this function do?
Code:
def check_incomplete_vs_complete():
complete = cfg.complete_dir.get_path()
if misc.same_file(cfg.download_dir.get_path(), complete):
if (misc.real_path('X', cfg.download_dir()) == cfg.download_dir()):
cfg.download_dir.set(os.path.join(complete, 'incomplete'))
else... |
null | null | null | What does this function do? | def __virtual__():
if salt.utils.which('rsync'):
return __virtualname__
return (False, 'The rsync execution module cannot be loaded: the rsync binary is not in the path.')
| null | null | null | Only load module if rsync binary is present | pcsd | def virtual if salt utils which 'rsync' return virtualname return False 'The rsync execution module cannot be loaded the rsync binary is not in the path ' | 13333 | def __virtual__():
if salt.utils.which('rsync'):
return __virtualname__
return (False, 'The rsync execution module cannot be loaded: the rsync binary is not in the path.')
| Only load module if rsync binary is present | only load module if rsync binary is present | Question:
What does this function do?
Code:
def __virtual__():
if salt.utils.which('rsync'):
return __virtualname__
return (False, 'The rsync execution module cannot be loaded: the rsync binary is not in the path.')
|
null | null | null | What does this function do? | def change_working_directory(directory):
try:
os.chdir(directory)
except Exception as exc:
error = DaemonOSEnvironmentError(('Unable to change working directory (%(exc)s)' % vars()))
raise error
| null | null | null | Change the working directory of this process. | pcsd | def change working directory directory try os chdir directory except Exception as exc error = Daemon OS Environment Error 'Unable to change working directory % exc s ' % vars raise error | 13341 | def change_working_directory(directory):
try:
os.chdir(directory)
except Exception as exc:
error = DaemonOSEnvironmentError(('Unable to change working directory (%(exc)s)' % vars()))
raise error
| Change the working directory of this process. | change the working directory of this process . | Question:
What does this function do?
Code:
def change_working_directory(directory):
try:
os.chdir(directory)
except Exception as exc:
error = DaemonOSEnvironmentError(('Unable to change working directory (%(exc)s)' % vars()))
raise error
|
null | null | null | What does this function do? | def routes():
ans = []
adapter_map = {a.if_index: a.name for a in adapters()}
with _get_forward_table() as p_forward_table:
if (p_forward_table is None):
return ans
forward_table = p_forward_table.contents
table = ctypes.cast(ctypes.addressof(forward_table.table), ctypes.POINTER((Win32_MIB_IPFORWARDROW * fo... | null | null | null | A list of routes on this machine | pcsd | def routes ans = [] adapter map = {a if index a name for a in adapters } with get forward table as p forward table if p forward table is None return ans forward table = p forward table contents table = ctypes cast ctypes addressof forward table table ctypes POINTER Win32 MIB IPFORWARDROW * forward table dw Num Entries ... | 13349 | def routes():
ans = []
adapter_map = {a.if_index: a.name for a in adapters()}
with _get_forward_table() as p_forward_table:
if (p_forward_table is None):
return ans
forward_table = p_forward_table.contents
table = ctypes.cast(ctypes.addressof(forward_table.table), ctypes.POINTER((Win32_MIB_IPFORWARDROW * fo... | A list of routes on this machine | a list of routes on this machine | Question:
What does this function do?
Code:
def routes():
ans = []
adapter_map = {a.if_index: a.name for a in adapters()}
with _get_forward_table() as p_forward_table:
if (p_forward_table is None):
return ans
forward_table = p_forward_table.contents
table = ctypes.cast(ctypes.addressof(forward_table.tabl... |
null | null | null | What does this function do? | def _modinv(e, m):
(x1, y1, x2, y2) = (1, 0, 0, 1)
(a, b) = (e, m)
while (b > 0):
(q, r) = divmod(a, b)
(xn, yn) = ((x1 - (q * x2)), (y1 - (q * y2)))
(a, b, x1, y1, x2, y2) = (b, r, x2, y2, xn, yn)
return (x1 % m)
| null | null | null | Modular Multiplicative Inverse. Returns x such that: (x*e) mod m == 1 | pcsd | def modinv e m x1 y1 x2 y2 = 1 0 0 1 a b = e m while b > 0 q r = divmod a b xn yn = x1 - q * x2 y1 - q * y2 a b x1 y1 x2 y2 = b r x2 y2 xn yn return x1 % m | 13350 | def _modinv(e, m):
(x1, y1, x2, y2) = (1, 0, 0, 1)
(a, b) = (e, m)
while (b > 0):
(q, r) = divmod(a, b)
(xn, yn) = ((x1 - (q * x2)), (y1 - (q * y2)))
(a, b, x1, y1, x2, y2) = (b, r, x2, y2, xn, yn)
return (x1 % m)
| Modular Multiplicative Inverse. Returns x such that: (x*e) mod m == 1 | modular multiplicative inverse . | Question:
What does this function do?
Code:
def _modinv(e, m):
(x1, y1, x2, y2) = (1, 0, 0, 1)
(a, b) = (e, m)
while (b > 0):
(q, r) = divmod(a, b)
(xn, yn) = ((x1 - (q * x2)), (y1 - (q * y2)))
(a, b, x1, y1, x2, y2) = (b, r, x2, y2, xn, yn)
return (x1 % m)
|
null | null | null | What does this function do? | def avail_images(conn=None):
return _query('os/list')
| null | null | null | Return available images | pcsd | def avail images conn=None return query 'os/list' | 13357 | def avail_images(conn=None):
return _query('os/list')
| Return available images | return available images | Question:
What does this function do?
Code:
def avail_images(conn=None):
return _query('os/list')
|
null | null | null | What does this function do? | def _str(s):
if isinstance(s, str):
return repr(s)
elif callable(s):
return get_callable_name(s)
elif isinstance(s, Node):
return str(s)
elif isinstance(s, (list, tuple)):
body = ', '.join((_str(x) for x in s))
return '({0})'.format((body if (len(s) > 1) else (body + ',')))
else:
return pformat(s).rstr... | null | null | null | Wrap single quotes around strings | pcsd | def str s if isinstance s str return repr s elif callable s return get callable name s elif isinstance s Node return str s elif isinstance s list tuple body = ' ' join str x for x in s return ' {0} ' format body if len s > 1 else body + ' ' else return pformat s rstrip | 13363 | def _str(s):
if isinstance(s, str):
return repr(s)
elif callable(s):
return get_callable_name(s)
elif isinstance(s, Node):
return str(s)
elif isinstance(s, (list, tuple)):
body = ', '.join((_str(x) for x in s))
return '({0})'.format((body if (len(s) > 1) else (body + ',')))
else:
return pformat(s).rstr... | Wrap single quotes around strings | wrap single quotes around strings | Question:
What does this function do?
Code:
def _str(s):
if isinstance(s, str):
return repr(s)
elif callable(s):
return get_callable_name(s)
elif isinstance(s, Node):
return str(s)
elif isinstance(s, (list, tuple)):
body = ', '.join((_str(x) for x in s))
return '({0})'.format((body if (len(s) > 1) else... |
null | null | null | What does this function do? | def GroupSizer(field_number, is_repeated, is_packed):
tag_size = (_TagSize(field_number) * 2)
assert (not is_packed)
if is_repeated:
def RepeatedFieldSize(value):
result = (tag_size * len(value))
for element in value:
result += element.ByteSize()
return result
return RepeatedFieldSize
else:
def F... | null | null | null | Returns a sizer for a group field. | pcsd | def Group Sizer field number is repeated is packed tag size = Tag Size field number * 2 assert not is packed if is repeated def Repeated Field Size value result = tag size * len value for element in value result += element Byte Size return result return Repeated Field Size else def Field Size value return tag size + va... | 13371 | def GroupSizer(field_number, is_repeated, is_packed):
tag_size = (_TagSize(field_number) * 2)
assert (not is_packed)
if is_repeated:
def RepeatedFieldSize(value):
result = (tag_size * len(value))
for element in value:
result += element.ByteSize()
return result
return RepeatedFieldSize
else:
def F... | Returns a sizer for a group field. | returns a sizer for a group field . | Question:
What does this function do?
Code:
def GroupSizer(field_number, is_repeated, is_packed):
tag_size = (_TagSize(field_number) * 2)
assert (not is_packed)
if is_repeated:
def RepeatedFieldSize(value):
result = (tag_size * len(value))
for element in value:
result += element.ByteSize()
return r... |
null | null | null | What does this function do? | def present(name, **kwargs):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': []}
current_beacons = __salt__['beacons.list'](return_yaml=False)
beacon_data = kwargs
if (name in current_beacons):
if (beacon_data == current_beacons[name]):
ret['comment'].append('Job {0} in correct state'.format(nam... | null | null | null | Ensure beacon is configured with the included beacon data.
name
The name of the beacon ensure is configured. | pcsd | def present name **kwargs ret = {'name' name 'result' True 'changes' {} 'comment' []} current beacons = salt ['beacons list'] return yaml=False beacon data = kwargs if name in current beacons if beacon data == current beacons[name] ret['comment'] append 'Job {0} in correct state' format name elif 'test' in opts and opt... | 13375 | def present(name, **kwargs):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': []}
current_beacons = __salt__['beacons.list'](return_yaml=False)
beacon_data = kwargs
if (name in current_beacons):
if (beacon_data == current_beacons[name]):
ret['comment'].append('Job {0} in correct state'.format(nam... | Ensure beacon is configured with the included beacon data.
name
The name of the beacon ensure is configured. | ensure beacon is configured with the included beacon data . | Question:
What does this function do?
Code:
def present(name, **kwargs):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': []}
current_beacons = __salt__['beacons.list'](return_yaml=False)
beacon_data = kwargs
if (name in current_beacons):
if (beacon_data == current_beacons[name]):
ret['comment... |
null | null | null | What does this function do? | def expectedFailureIf(condition):
if condition:
return expectedFailure
return (lambda func: func)
| null | null | null | Marks a test as an expected failure if ``condition`` is met. | pcsd | def expected Failure If condition if condition return expected Failure return lambda func func | 13378 | def expectedFailureIf(condition):
if condition:
return expectedFailure
return (lambda func: func)
| Marks a test as an expected failure if ``condition`` is met. | marks a test as an expected failure if condition is met . | Question:
What does this function do?
Code:
def expectedFailureIf(condition):
if condition:
return expectedFailure
return (lambda func: func)
|
null | null | null | What does this function do? | def _after(node):
try:
pos = node.treeposition()
tree = node.root()
except AttributeError:
return []
return [tree[x] for x in tree.treepositions() if (x[:len(pos)] > pos[:len(x)])]
| null | null | null | Returns the set of all nodes that are after the given node. | pcsd | def after node try pos = node treeposition tree = node root except Attribute Error return [] return [tree[x] for x in tree treepositions if x[ len pos ] > pos[ len x ] ] | 13381 | def _after(node):
try:
pos = node.treeposition()
tree = node.root()
except AttributeError:
return []
return [tree[x] for x in tree.treepositions() if (x[:len(pos)] > pos[:len(x)])]
| Returns the set of all nodes that are after the given node. | returns the set of all nodes that are after the given node . | Question:
What does this function do?
Code:
def _after(node):
try:
pos = node.treeposition()
tree = node.root()
except AttributeError:
return []
return [tree[x] for x in tree.treepositions() if (x[:len(pos)] > pos[:len(x)])]
|
null | null | null | What does this function do? | def fake_view(_request):
return HttpResponse()
| null | null | null | Fake view that returns an empty response. | pcsd | def fake view request return Http Response | 13382 | def fake_view(_request):
return HttpResponse()
| Fake view that returns an empty response. | fake view that returns an empty response . | Question:
What does this function do?
Code:
def fake_view(_request):
return HttpResponse()
|
null | null | null | What does this function do? | def saveAll():
for globalRepositoryDialogValue in getGlobalRepositoryDialogValues():
globalRepositoryDialogValue.save()
| null | null | null | Save all the dialogs. | pcsd | def save All for global Repository Dialog Value in get Global Repository Dialog Values global Repository Dialog Value save | 13384 | def saveAll():
for globalRepositoryDialogValue in getGlobalRepositoryDialogValues():
globalRepositoryDialogValue.save()
| Save all the dialogs. | save all the dialogs . | Question:
What does this function do?
Code:
def saveAll():
for globalRepositoryDialogValue in getGlobalRepositoryDialogValues():
globalRepositoryDialogValue.save()
|
null | null | null | What does this function do? | def p_jump_statement_2(t):
pass
| null | null | null | jump_statement : CONTINUE SEMI | pcsd | def p jump statement 2 t pass | 13386 | def p_jump_statement_2(t):
pass
| jump_statement : CONTINUE SEMI | jump _ statement : continue semi | Question:
What does this function do?
Code:
def p_jump_statement_2(t):
pass
|
null | null | null | What does this function do? | def write_file(content, output_path):
output_dir = os.path.dirname(output_path)
if (not os.path.exists(output_dir)):
os.makedirs(output_dir)
open(output_path, u'wb').write(content)
| null | null | null | Write content to output_path, making sure any parent directories exist. | pcsd | def write file content output path output dir = os path dirname output path if not os path exists output dir os makedirs output dir open output path u'wb' write content | 13390 | def write_file(content, output_path):
output_dir = os.path.dirname(output_path)
if (not os.path.exists(output_dir)):
os.makedirs(output_dir)
open(output_path, u'wb').write(content)
| Write content to output_path, making sure any parent directories exist. | write content to output _ path , making sure any parent directories exist . | Question:
What does this function do?
Code:
def write_file(content, output_path):
output_dir = os.path.dirname(output_path)
if (not os.path.exists(output_dir)):
os.makedirs(output_dir)
open(output_path, u'wb').write(content)
|
null | null | null | What does this function do? | @frappe.whitelist()
def get_users(doctype, name):
return frappe.db.sql(u'select\n DCTB DCTB DCTB `name`, `user`, `read`, `write`, `share`, `everyone`\n DCTB DCTB from\n DCTB DCTB DCTB tabDocShare\n DCTB DCTB where\n DCTB DCTB DCTB share_doctype=%s and share_name=%s', (doctype, name), as_dict=True)
| null | null | null | Get list of users with which this document is shared | pcsd | @frappe whitelist def get users doctype name return frappe db sql u'select DCTB DCTB DCTB `name` `user` `read` `write` `share` `everyone` DCTB DCTB from DCTB DCTB DCTB tab Doc Share DCTB DCTB where DCTB DCTB DCTB share doctype=%s and share name=%s' doctype name as dict=True | 13394 | @frappe.whitelist()
def get_users(doctype, name):
return frappe.db.sql(u'select\n DCTB DCTB DCTB `name`, `user`, `read`, `write`, `share`, `everyone`\n DCTB DCTB from\n DCTB DCTB DCTB tabDocShare\n DCTB DCTB where\n DCTB DCTB DCTB share_doctype=%s and share_name=%s', (doctype, name), as_dict=True)
| Get list of users with which this document is shared | get list of users with which this document is shared | Question:
What does this function do?
Code:
@frappe.whitelist()
def get_users(doctype, name):
return frappe.db.sql(u'select\n DCTB DCTB DCTB `name`, `user`, `read`, `write`, `share`, `everyone`\n DCTB DCTB from\n DCTB DCTB DCTB tabDocShare\n DCTB DCTB where\n DCTB DCTB DCTB share_doctype=%s and share_name=%... |
null | null | null | What does this function do? | def chi2p(x2, df=1, tail=UPPER):
return gammai((df * 0.5), (x2 * 0.5), tail)
| null | null | null | Returns p-value for given x2 and degrees of freedom. | pcsd | def chi2p x2 df=1 tail=UPPER return gammai df * 0 5 x2 * 0 5 tail | 13395 | def chi2p(x2, df=1, tail=UPPER):
return gammai((df * 0.5), (x2 * 0.5), tail)
| Returns p-value for given x2 and degrees of freedom. | returns p - value for given x2 and degrees of freedom . | Question:
What does this function do?
Code:
def chi2p(x2, df=1, tail=UPPER):
return gammai((df * 0.5), (x2 * 0.5), tail)
|
null | null | null | What does this function do? | def temperature_energy():
return [(si.K, si.eV, (lambda x: (x / (_si.e.value / _si.k_B))), (lambda x: (x * (_si.e.value / _si.k_B))))]
| null | null | null | Convert between Kelvin and keV(eV) to an equivalent amount. | pcsd | def temperature energy return [ si K si e V lambda x x / si e value / si k B lambda x x * si e value / si k B ] | 13398 | def temperature_energy():
return [(si.K, si.eV, (lambda x: (x / (_si.e.value / _si.k_B))), (lambda x: (x * (_si.e.value / _si.k_B))))]
| Convert between Kelvin and keV(eV) to an equivalent amount. | convert between kelvin and kev to an equivalent amount . | Question:
What does this function do?
Code:
def temperature_energy():
return [(si.K, si.eV, (lambda x: (x / (_si.e.value / _si.k_B))), (lambda x: (x * (_si.e.value / _si.k_B))))]
|
null | null | null | What does this function do? | def selinux_enforcing():
cmdresult = run('getenforce', ignore_status=True, verbose=False)
mobj = re.search('Enforcing', cmdresult.stdout)
return (mobj is not None)
| null | null | null | Returns True if SELinux is in enforcing mode, False if permissive/disabled | pcsd | def selinux enforcing cmdresult = run 'getenforce' ignore status=True verbose=False mobj = re search 'Enforcing' cmdresult stdout return mobj is not None | 13400 | def selinux_enforcing():
cmdresult = run('getenforce', ignore_status=True, verbose=False)
mobj = re.search('Enforcing', cmdresult.stdout)
return (mobj is not None)
| Returns True if SELinux is in enforcing mode, False if permissive/disabled | returns true if selinux is in enforcing mode , false if permissive / disabled | Question:
What does this function do?
Code:
def selinux_enforcing():
cmdresult = run('getenforce', ignore_status=True, verbose=False)
mobj = re.search('Enforcing', cmdresult.stdout)
return (mobj is not None)
|
null | null | null | What does this function do? | def permute_2d(m, p):
return m[p][:, p]
| null | null | null | Performs 2D permutation of matrix m according to p. | pcsd | def permute 2d m p return m[p][ p] | 13413 | def permute_2d(m, p):
return m[p][:, p]
| Performs 2D permutation of matrix m according to p. | performs 2d permutation of matrix m according to p . | Question:
What does this function do?
Code:
def permute_2d(m, p):
return m[p][:, p]
|
null | null | null | What does this function do? | def get_default_volume_type():
name = FLAGS.default_volume_type
vol_type = {}
if (name is not None):
ctxt = context.get_admin_context()
try:
vol_type = get_volume_type_by_name(ctxt, name)
except exception.VolumeTypeNotFoundByName as e:
LOG.exception(_('Default volume type is not found, please check defau... | null | null | null | Get the default volume type. | pcsd | def get default volume type name = FLAGS default volume type vol type = {} if name is not None ctxt = context get admin context try vol type = get volume type by name ctxt name except exception Volume Type Not Found By Name as e LOG exception 'Default volume type is not found please check default volume type config %s'... | 13416 | def get_default_volume_type():
name = FLAGS.default_volume_type
vol_type = {}
if (name is not None):
ctxt = context.get_admin_context()
try:
vol_type = get_volume_type_by_name(ctxt, name)
except exception.VolumeTypeNotFoundByName as e:
LOG.exception(_('Default volume type is not found, please check defau... | Get the default volume type. | get the default volume type . | Question:
What does this function do?
Code:
def get_default_volume_type():
name = FLAGS.default_volume_type
vol_type = {}
if (name is not None):
ctxt = context.get_admin_context()
try:
vol_type = get_volume_type_by_name(ctxt, name)
except exception.VolumeTypeNotFoundByName as e:
LOG.exception(_('Defau... |
null | null | null | What does this function do? | def helper_functions():
helpers.load_plugin_helpers()
return dict(h=helpers.helper_functions)
| null | null | null | Make helper functions (`h`) available to Flask templates | pcsd | def helper functions helpers load plugin helpers return dict h=helpers helper functions | 13419 | def helper_functions():
helpers.load_plugin_helpers()
return dict(h=helpers.helper_functions)
| Make helper functions (`h`) available to Flask templates | make helper functions ( h ) available to flask templates | Question:
What does this function do?
Code:
def helper_functions():
helpers.load_plugin_helpers()
return dict(h=helpers.helper_functions)
|
null | null | null | What does this function do? | def load_model(path_to_model, path_to_dictionary):
with open(path_to_dictionary, 'rb') as f:
worddict = pkl.load(f)
word_idict = dict()
for (kk, vv) in worddict.iteritems():
word_idict[vv] = kk
word_idict[0] = '<eos>'
word_idict[1] = 'UNK'
with open(('%s.pkl' % path_to_model), 'rb') as f:
options = pkl.load... | null | null | null | Load a trained model for decoding | pcsd | def load model path to model path to dictionary with open path to dictionary 'rb' as f worddict = pkl load f word idict = dict for kk vv in worddict iteritems word idict[vv] = kk word idict[0] = '<eos>' word idict[1] = 'UNK' with open '%s pkl' % path to model 'rb' as f options = pkl load f if 'doutput' not in options k... | 13422 | def load_model(path_to_model, path_to_dictionary):
with open(path_to_dictionary, 'rb') as f:
worddict = pkl.load(f)
word_idict = dict()
for (kk, vv) in worddict.iteritems():
word_idict[vv] = kk
word_idict[0] = '<eos>'
word_idict[1] = 'UNK'
with open(('%s.pkl' % path_to_model), 'rb') as f:
options = pkl.load... | Load a trained model for decoding | load a trained model for decoding | Question:
What does this function do?
Code:
def load_model(path_to_model, path_to_dictionary):
with open(path_to_dictionary, 'rb') as f:
worddict = pkl.load(f)
word_idict = dict()
for (kk, vv) in worddict.iteritems():
word_idict[vv] = kk
word_idict[0] = '<eos>'
word_idict[1] = 'UNK'
with open(('%s.pkl' % p... |
null | null | null | What does this function do? | def total_ordering(cls):
convert = {'__lt__': [('__gt__', (lambda self, other: (not ((self < other) or (self == other))))), ('__le__', (lambda self, other: ((self < other) or (self == other)))), ('__ge__', (lambda self, other: (not (self < other))))], '__le__': [('__ge__', (lambda self, other: ((not (self <= other)) o... | null | null | null | Class decorator that fills in missing ordering methods | pcsd | def total ordering cls convert = {' lt ' [ ' gt ' lambda self other not self < other or self == other ' le ' lambda self other self < other or self == other ' ge ' lambda self other not self < other ] ' le ' [ ' ge ' lambda self other not self <= other or self == other ' lt ' lambda self other self <= other and not sel... | 13427 | def total_ordering(cls):
convert = {'__lt__': [('__gt__', (lambda self, other: (not ((self < other) or (self == other))))), ('__le__', (lambda self, other: ((self < other) or (self == other)))), ('__ge__', (lambda self, other: (not (self < other))))], '__le__': [('__ge__', (lambda self, other: ((not (self <= other)) o... | Class decorator that fills in missing ordering methods | class decorator that fills in missing ordering methods | Question:
What does this function do?
Code:
def total_ordering(cls):
convert = {'__lt__': [('__gt__', (lambda self, other: (not ((self < other) or (self == other))))), ('__le__', (lambda self, other: ((self < other) or (self == other)))), ('__ge__', (lambda self, other: (not (self < other))))], '__le__': [('__ge__'... |
null | null | null | What does this function do? | def add_addon_author(original, copy):
author = original.listed_authors[0]
AddonUser.objects.create(addon=copy, user=author, listed=True)
return author
| null | null | null | Make both add-ons share an author. | pcsd | def add addon author original copy author = original listed authors[0] Addon User objects create addon=copy user=author listed=True return author | 13433 | def add_addon_author(original, copy):
author = original.listed_authors[0]
AddonUser.objects.create(addon=copy, user=author, listed=True)
return author
| Make both add-ons share an author. | make both add - ons share an author . | Question:
What does this function do?
Code:
def add_addon_author(original, copy):
author = original.listed_authors[0]
AddonUser.objects.create(addon=copy, user=author, listed=True)
return author
|
null | null | null | What does this function do? | def remove_taps(module, brew_path, taps):
(failed, unchanged, removed, msg) = (False, 0, 0, '')
for tap in taps:
(failed, changed, msg) = remove_tap(module, brew_path, tap)
if failed:
break
if changed:
removed += 1
else:
unchanged += 1
if failed:
msg = ('removed: %d, unchanged: %d, error: ' + msg)... | null | null | null | Removes one or more taps. | pcsd | def remove taps module brew path taps failed unchanged removed msg = False 0 0 '' for tap in taps failed changed msg = remove tap module brew path tap if failed break if changed removed += 1 else unchanged += 1 if failed msg = 'removed %d unchanged %d error ' + msg msg = msg % removed unchanged elif removed changed = T... | 13438 | def remove_taps(module, brew_path, taps):
(failed, unchanged, removed, msg) = (False, 0, 0, '')
for tap in taps:
(failed, changed, msg) = remove_tap(module, brew_path, tap)
if failed:
break
if changed:
removed += 1
else:
unchanged += 1
if failed:
msg = ('removed: %d, unchanged: %d, error: ' + msg)... | Removes one or more taps. | removes one or more taps . | Question:
What does this function do?
Code:
def remove_taps(module, brew_path, taps):
(failed, unchanged, removed, msg) = (False, 0, 0, '')
for tap in taps:
(failed, changed, msg) = remove_tap(module, brew_path, tap)
if failed:
break
if changed:
removed += 1
else:
unchanged += 1
if failed:
msg ... |
null | null | null | What does this function do? | def _get_shells():
start = time.time()
if ('sh.last_shells' in __context__):
if ((start - __context__['sh.last_shells']) > 5):
__context__['sh.last_shells'] = start
else:
__context__['sh.shells'] = __salt__['cmd.shells']()
else:
__context__['sh.last_shells'] = start
__context__['sh.shells'] = __salt__[... | null | null | null | Return the valid shells on this system | pcsd | def get shells start = time time if 'sh last shells' in context if start - context ['sh last shells'] > 5 context ['sh last shells'] = start else context ['sh shells'] = salt ['cmd shells'] else context ['sh last shells'] = start context ['sh shells'] = salt ['cmd shells'] return context ['sh shells'] | 13440 | def _get_shells():
start = time.time()
if ('sh.last_shells' in __context__):
if ((start - __context__['sh.last_shells']) > 5):
__context__['sh.last_shells'] = start
else:
__context__['sh.shells'] = __salt__['cmd.shells']()
else:
__context__['sh.last_shells'] = start
__context__['sh.shells'] = __salt__[... | Return the valid shells on this system | return the valid shells on this system | Question:
What does this function do?
Code:
def _get_shells():
start = time.time()
if ('sh.last_shells' in __context__):
if ((start - __context__['sh.last_shells']) > 5):
__context__['sh.last_shells'] = start
else:
__context__['sh.shells'] = __salt__['cmd.shells']()
else:
__context__['sh.last_shells']... |
null | null | null | What does this function do? | def getCubicPath(xmlElement):
end = evaluate.getVector3FromXMLElement(xmlElement)
previousXMLElement = xmlElement.getPreviousXMLElement()
if (previousXMLElement == None):
print 'Warning, can not get previousXMLElement in getCubicPath in cubic for:'
print xmlElement
return [end]
begin = xmlElement.getPreviousV... | null | null | null | Get the cubic path. | pcsd | def get Cubic Path xml Element end = evaluate get Vector3From XML Element xml Element previous XML Element = xml Element get Previous XML Element if previous XML Element == None print 'Warning can not get previous XML Element in get Cubic Path in cubic for ' print xml Element return [end] begin = xml Element get Previo... | 13451 | def getCubicPath(xmlElement):
end = evaluate.getVector3FromXMLElement(xmlElement)
previousXMLElement = xmlElement.getPreviousXMLElement()
if (previousXMLElement == None):
print 'Warning, can not get previousXMLElement in getCubicPath in cubic for:'
print xmlElement
return [end]
begin = xmlElement.getPreviousV... | Get the cubic path. | get the cubic path . | Question:
What does this function do?
Code:
def getCubicPath(xmlElement):
end = evaluate.getVector3FromXMLElement(xmlElement)
previousXMLElement = xmlElement.getPreviousXMLElement()
if (previousXMLElement == None):
print 'Warning, can not get previousXMLElement in getCubicPath in cubic for:'
print xmlElement
... |
null | null | null | What does this function do? | def get_tree(base, exclude):
tree = {}
coverage.get_ready()
runs = list(coverage.cexecuted.keys())
if runs:
for path in runs:
if ((not _skip_file(path, exclude)) and (not os.path.isdir(path))):
_graft(path, tree)
return tree
| null | null | null | Return covered module names as a nested dict. | pcsd | def get tree base exclude tree = {} coverage get ready runs = list coverage cexecuted keys if runs for path in runs if not skip file path exclude and not os path isdir path graft path tree return tree | 13454 | def get_tree(base, exclude):
tree = {}
coverage.get_ready()
runs = list(coverage.cexecuted.keys())
if runs:
for path in runs:
if ((not _skip_file(path, exclude)) and (not os.path.isdir(path))):
_graft(path, tree)
return tree
| Return covered module names as a nested dict. | return covered module names as a nested dict . | Question:
What does this function do?
Code:
def get_tree(base, exclude):
tree = {}
coverage.get_ready()
runs = list(coverage.cexecuted.keys())
if runs:
for path in runs:
if ((not _skip_file(path, exclude)) and (not os.path.isdir(path))):
_graft(path, tree)
return tree
|
null | null | null | What does this function do? | def print_list(extracted_list, file=None):
if (file is None):
file = sys.stderr
for (filename, lineno, name, line) in extracted_list:
_print(file, (' File "%s", line %d, in %s' % (filename, lineno, name)))
if line:
_print(file, (' %s' % line.strip()))
| null | null | null | Print the list of tuples as returned by extract_tb() or
extract_stack() as a formatted stack trace to the given file. | pcsd | def print list extracted list file=None if file is None file = sys stderr for filename lineno name line in extracted list print file ' File "%s" line %d in %s' % filename lineno name if line print file ' %s' % line strip | 13465 | def print_list(extracted_list, file=None):
if (file is None):
file = sys.stderr
for (filename, lineno, name, line) in extracted_list:
_print(file, (' File "%s", line %d, in %s' % (filename, lineno, name)))
if line:
_print(file, (' %s' % line.strip()))
| Print the list of tuples as returned by extract_tb() or
extract_stack() as a formatted stack trace to the given file. | print the list of tuples as returned by extract _ tb ( ) or extract _ stack ( ) as a formatted stack trace to the given file . | Question:
What does this function do?
Code:
def print_list(extracted_list, file=None):
if (file is None):
file = sys.stderr
for (filename, lineno, name, line) in extracted_list:
_print(file, (' File "%s", line %d, in %s' % (filename, lineno, name)))
if line:
_print(file, (' %s' % line.strip()))
|
null | null | null | What does this function do? | def spawn_personal_stream(args, stuff=None):
g['keyword'] = g['listname'] = ''
g['PREFIX'] = u2str(emojize(format_prefix()))
th = threading.Thread(target=stream, args=(c['USER_DOMAIN'], args, g['original_name']))
th.daemon = True
th.start()
| null | null | null | Spawn a new personal stream | pcsd | def spawn personal stream args stuff=None g['keyword'] = g['listname'] = '' g['PREFIX'] = u2str emojize format prefix th = threading Thread target=stream args= c['USER DOMAIN'] args g['original name'] th daemon = True th start | 13467 | def spawn_personal_stream(args, stuff=None):
g['keyword'] = g['listname'] = ''
g['PREFIX'] = u2str(emojize(format_prefix()))
th = threading.Thread(target=stream, args=(c['USER_DOMAIN'], args, g['original_name']))
th.daemon = True
th.start()
| Spawn a new personal stream | spawn a new personal stream | Question:
What does this function do?
Code:
def spawn_personal_stream(args, stuff=None):
g['keyword'] = g['listname'] = ''
g['PREFIX'] = u2str(emojize(format_prefix()))
th = threading.Thread(target=stream, args=(c['USER_DOMAIN'], args, g['original_name']))
th.daemon = True
th.start()
|
null | null | null | What does this function do? | def _retrive_branch(k, trie):
if (not k):
return None
for c in k:
child_branch = _get_child_branch(trie, c)
if (not child_branch):
return None
trie = child_branch
return trie
| null | null | null | Get branch matching the key word | pcsd | def retrive branch k trie if not k return None for c in k child branch = get child branch trie c if not child branch return None trie = child branch return trie | 13469 | def _retrive_branch(k, trie):
if (not k):
return None
for c in k:
child_branch = _get_child_branch(trie, c)
if (not child_branch):
return None
trie = child_branch
return trie
| Get branch matching the key word | get branch matching the key word | Question:
What does this function do?
Code:
def _retrive_branch(k, trie):
if (not k):
return None
for c in k:
child_branch = _get_child_branch(trie, c)
if (not child_branch):
return None
trie = child_branch
return trie
|
null | null | null | What does this function do? | def plain(text):
return re.sub('.\x08', '', text)
| null | null | null | Remove boldface formatting from text. | pcsd | def plain text return re sub ' \x08' '' text | 13475 | def plain(text):
return re.sub('.\x08', '', text)
| Remove boldface formatting from text. | remove boldface formatting from text . | Question:
What does this function do?
Code:
def plain(text):
return re.sub('.\x08', '', text)
|
null | null | null | What does this function do? | def get_pull_request_files(project, num, auth=False):
url = 'https://api.github.com/repos/{project}/pulls/{num}/files'.format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
return get_paged_request(url, headers=header)
| null | null | null | get list of files in a pull request | pcsd | def get pull request files project num auth=False url = 'https //api github com/repos/{project}/pulls/{num}/files' format project=project num=num if auth header = make auth header else header = None return get paged request url headers=header | 13487 | def get_pull_request_files(project, num, auth=False):
url = 'https://api.github.com/repos/{project}/pulls/{num}/files'.format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
return get_paged_request(url, headers=header)
| get list of files in a pull request | get list of files in a pull request | Question:
What does this function do?
Code:
def get_pull_request_files(project, num, auth=False):
url = 'https://api.github.com/repos/{project}/pulls/{num}/files'.format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
return get_paged_request(url, headers=header)
|
null | null | null | What does this function do? | def getGeometryOutputByManipulation(elementNode, sideLoop):
sideLoop.loop = euclidean.getLoopWithoutCloseSequentialPoints(sideLoop.close, sideLoop.loop)
return sideLoop.getManipulationPluginLoops(elementNode)
| null | null | null | Get geometry output by manipulation. | pcsd | def get Geometry Output By Manipulation element Node side Loop side Loop loop = euclidean get Loop Without Close Sequential Points side Loop close side Loop loop return side Loop get Manipulation Plugin Loops element Node | 13488 | def getGeometryOutputByManipulation(elementNode, sideLoop):
sideLoop.loop = euclidean.getLoopWithoutCloseSequentialPoints(sideLoop.close, sideLoop.loop)
return sideLoop.getManipulationPluginLoops(elementNode)
| Get geometry output by manipulation. | get geometry output by manipulation . | Question:
What does this function do?
Code:
def getGeometryOutputByManipulation(elementNode, sideLoop):
sideLoop.loop = euclidean.getLoopWithoutCloseSequentialPoints(sideLoop.close, sideLoop.loop)
return sideLoop.getManipulationPluginLoops(elementNode)
|
null | null | null | What does this function do? | def add_items(widget, items):
for item in items:
if (item is None):
continue
widget.addItem(item)
| null | null | null | Adds items to a widget. | pcsd | def add items widget items for item in items if item is None continue widget add Item item | 13492 | def add_items(widget, items):
for item in items:
if (item is None):
continue
widget.addItem(item)
| Adds items to a widget. | adds items to a widget . | Question:
What does this function do?
Code:
def add_items(widget, items):
for item in items:
if (item is None):
continue
widget.addItem(item)
|
null | null | null | What does this function do? | def split_seq(curr_seq, barcode_len, primer_seq_len):
curr_barcode = curr_seq[0:barcode_len]
rest_of_seq = curr_seq[barcode_len:]
primer_seq = rest_of_seq[0:primer_seq_len]
rest_of_seq = rest_of_seq[primer_seq_len:]
return (curr_barcode, primer_seq, rest_of_seq)
| null | null | null | Split sequence into parts barcode, primer and remainder | pcsd | def split seq curr seq barcode len primer seq len curr barcode = curr seq[0 barcode len] rest of seq = curr seq[barcode len ] primer seq = rest of seq[0 primer seq len] rest of seq = rest of seq[primer seq len ] return curr barcode primer seq rest of seq | 13494 | def split_seq(curr_seq, barcode_len, primer_seq_len):
curr_barcode = curr_seq[0:barcode_len]
rest_of_seq = curr_seq[barcode_len:]
primer_seq = rest_of_seq[0:primer_seq_len]
rest_of_seq = rest_of_seq[primer_seq_len:]
return (curr_barcode, primer_seq, rest_of_seq)
| Split sequence into parts barcode, primer and remainder | split sequence into parts barcode , primer and remainder | Question:
What does this function do?
Code:
def split_seq(curr_seq, barcode_len, primer_seq_len):
curr_barcode = curr_seq[0:barcode_len]
rest_of_seq = curr_seq[barcode_len:]
primer_seq = rest_of_seq[0:primer_seq_len]
rest_of_seq = rest_of_seq[primer_seq_len:]
return (curr_barcode, primer_seq, rest_of_seq)
|
null | null | null | What does this function do? | def OpenDocumentSpreadsheet():
doc = OpenDocument('application/vnd.oasis.opendocument.spreadsheet')
doc.spreadsheet = Spreadsheet()
doc.body.addElement(doc.spreadsheet)
return doc
| null | null | null | Creates a spreadsheet document | pcsd | def Open Document Spreadsheet doc = Open Document 'application/vnd oasis opendocument spreadsheet' doc spreadsheet = Spreadsheet doc body add Element doc spreadsheet return doc | 13498 | def OpenDocumentSpreadsheet():
doc = OpenDocument('application/vnd.oasis.opendocument.spreadsheet')
doc.spreadsheet = Spreadsheet()
doc.body.addElement(doc.spreadsheet)
return doc
| Creates a spreadsheet document | creates a spreadsheet document | Question:
What does this function do?
Code:
def OpenDocumentSpreadsheet():
doc = OpenDocument('application/vnd.oasis.opendocument.spreadsheet')
doc.spreadsheet = Spreadsheet()
doc.body.addElement(doc.spreadsheet)
return doc
|
null | null | null | What does this function do? | def display_page(request, virtual_path):
page = None
for page_model in AbstractPage.__subclasses__():
try:
page = page_model.objects.live(request.user).get(virtual_path=virtual_path)
except ObjectDoesNotExist:
pass
if (page is None):
raise Http404
if page.url:
return redirect(page.url)
template_name ... | null | null | null | Displays an active page defined in `virtual_path`. | pcsd | def display page request virtual path page = None for page model in Abstract Page subclasses try page = page model objects live request user get virtual path=virtual path except Object Does Not Exist pass if page is None raise Http404 if page url return redirect page url template name = 'staticpages/page display html' ... | 13501 | def display_page(request, virtual_path):
page = None
for page_model in AbstractPage.__subclasses__():
try:
page = page_model.objects.live(request.user).get(virtual_path=virtual_path)
except ObjectDoesNotExist:
pass
if (page is None):
raise Http404
if page.url:
return redirect(page.url)
template_name ... | Displays an active page defined in `virtual_path`. | displays an active page defined in virtual _ path . | Question:
What does this function do?
Code:
def display_page(request, virtual_path):
page = None
for page_model in AbstractPage.__subclasses__():
try:
page = page_model.objects.live(request.user).get(virtual_path=virtual_path)
except ObjectDoesNotExist:
pass
if (page is None):
raise Http404
if page.u... |
null | null | null | What does this function do? | def upcaseTokens(s, l, t):
return map(str.upper, t)
| null | null | null | Helper parse action to convert tokens to upper case. | pcsd | def upcase Tokens s l t return map str upper t | 13502 | def upcaseTokens(s, l, t):
return map(str.upper, t)
| Helper parse action to convert tokens to upper case. | helper parse action to convert tokens to upper case . | Question:
What does this function do?
Code:
def upcaseTokens(s, l, t):
return map(str.upper, t)
|
null | null | null | What does this function do? | def fire_exception(exc, opts, job=None, node='minion'):
if (job is None):
job = {}
event = salt.utils.event.SaltEvent(node, opts=opts, listen=False)
event.fire_event(pack_exception(exc), '_salt_error')
| null | null | null | Fire raw exception across the event bus | pcsd | def fire exception exc opts job=None node='minion' if job is None job = {} event = salt utils event Salt Event node opts=opts listen=False event fire event pack exception exc ' salt error' | 13505 | def fire_exception(exc, opts, job=None, node='minion'):
if (job is None):
job = {}
event = salt.utils.event.SaltEvent(node, opts=opts, listen=False)
event.fire_event(pack_exception(exc), '_salt_error')
| Fire raw exception across the event bus | fire raw exception across the event bus | Question:
What does this function do?
Code:
def fire_exception(exc, opts, job=None, node='minion'):
if (job is None):
job = {}
event = salt.utils.event.SaltEvent(node, opts=opts, listen=False)
event.fire_event(pack_exception(exc), '_salt_error')
|
null | null | null | What does this function do? | @frappe.whitelist()
def get_filter_dashboard_data(stats, doctype, filters=[]):
import json
tags = json.loads(stats)
if filters:
filters = json.loads(filters)
stats = {}
columns = frappe.db.get_table_columns(doctype)
for tag in tags:
if (not (tag[u'name'] in columns)):
continue
tagcount = []
if (tag[u't... | null | null | null | get tags info | pcsd | @frappe whitelist def get filter dashboard data stats doctype filters=[] import json tags = json loads stats if filters filters = json loads filters stats = {} columns = frappe db get table columns doctype for tag in tags if not tag[u'name'] in columns continue tagcount = [] if tag[u'type'] not in [u'Date' u'Datetime']... | 13507 | @frappe.whitelist()
def get_filter_dashboard_data(stats, doctype, filters=[]):
import json
tags = json.loads(stats)
if filters:
filters = json.loads(filters)
stats = {}
columns = frappe.db.get_table_columns(doctype)
for tag in tags:
if (not (tag[u'name'] in columns)):
continue
tagcount = []
if (tag[u't... | get tags info | get tags info | Question:
What does this function do?
Code:
@frappe.whitelist()
def get_filter_dashboard_data(stats, doctype, filters=[]):
import json
tags = json.loads(stats)
if filters:
filters = json.loads(filters)
stats = {}
columns = frappe.db.get_table_columns(doctype)
for tag in tags:
if (not (tag[u'name'] in colum... |
null | null | null | What does this function do? | def get_monitor_adapter():
tmp = init_app('iwconfig', True)
for line in tmp.split('\n'):
if line.startswith(' '):
continue
elif (len(line.split(' ')[0]) > 1):
if ('Mode:Monitor' in line):
return line.split(' ')[0]
return None
| null | null | null | Try and automatically detect which adapter is in monitor mode.
NONE if there are none. | pcsd | def get monitor adapter tmp = init app 'iwconfig' True for line in tmp split ' ' if line startswith ' ' continue elif len line split ' ' [0] > 1 if 'Mode Monitor' in line return line split ' ' [0] return None | 13509 | def get_monitor_adapter():
tmp = init_app('iwconfig', True)
for line in tmp.split('\n'):
if line.startswith(' '):
continue
elif (len(line.split(' ')[0]) > 1):
if ('Mode:Monitor' in line):
return line.split(' ')[0]
return None
| Try and automatically detect which adapter is in monitor mode.
NONE if there are none. | try and automatically detect which adapter is in monitor mode . | Question:
What does this function do?
Code:
def get_monitor_adapter():
tmp = init_app('iwconfig', True)
for line in tmp.split('\n'):
if line.startswith(' '):
continue
elif (len(line.split(' ')[0]) > 1):
if ('Mode:Monitor' in line):
return line.split(' ')[0]
return None
|
null | null | null | What does this function do? | def get_hostname(config, method=None):
method = (method or config.get('hostname_method', 'smart'))
method = method.lower()
if (('hostname' in config) and (method != 'shell')):
return config['hostname']
if (method in get_hostname.cached_results):
return get_hostname.cached_results[method]
if (method == 'shell')... | null | null | null | Returns a hostname as configured by the user | pcsd | def get hostname config method=None method = method or config get 'hostname method' 'smart' method = method lower if 'hostname' in config and method != 'shell' return config['hostname'] if method in get hostname cached results return get hostname cached results[method] if method == 'shell' if 'hostname' not in config r... | 13532 | def get_hostname(config, method=None):
method = (method or config.get('hostname_method', 'smart'))
method = method.lower()
if (('hostname' in config) and (method != 'shell')):
return config['hostname']
if (method in get_hostname.cached_results):
return get_hostname.cached_results[method]
if (method == 'shell')... | Returns a hostname as configured by the user | returns a hostname as configured by the user | Question:
What does this function do?
Code:
def get_hostname(config, method=None):
method = (method or config.get('hostname_method', 'smart'))
method = method.lower()
if (('hostname' in config) and (method != 'shell')):
return config['hostname']
if (method in get_hostname.cached_results):
return get_hostname... |
null | null | null | What does this function do? | @pytest.yield_fixture(params=[None, tdata])
def temp_server_with_excfmt(request):
data = request.param
log_format_exc = (lambda tb: 'CUSTOM TRACEBACK')
stream = StringIO()
s = Server(copy(data), formats=all_formats, allow_add=True, logfile=stream, log_exception_formatter=log_format_exc)
s.app.testing = True
with ... | null | null | null | With a custom log exception formatter | pcsd | @pytest yield fixture params=[None tdata] def temp server with excfmt request data = request param log format exc = lambda tb 'CUSTOM TRACEBACK' stream = String IO s = Server copy data formats=all formats allow add=True logfile=stream log exception formatter=log format exc s app testing = True with s app test client as... | 13537 | @pytest.yield_fixture(params=[None, tdata])
def temp_server_with_excfmt(request):
data = request.param
log_format_exc = (lambda tb: 'CUSTOM TRACEBACK')
stream = StringIO()
s = Server(copy(data), formats=all_formats, allow_add=True, logfile=stream, log_exception_formatter=log_format_exc)
s.app.testing = True
with ... | With a custom log exception formatter | with a custom log exception formatter | Question:
What does this function do?
Code:
@pytest.yield_fixture(params=[None, tdata])
def temp_server_with_excfmt(request):
data = request.param
log_format_exc = (lambda tb: 'CUSTOM TRACEBACK')
stream = StringIO()
s = Server(copy(data), formats=all_formats, allow_add=True, logfile=stream, log_exception_formatt... |
null | null | null | What does this function do? | def _regexp_path(name, *names):
return os.path.join(name, *names).replace('\\', '\\\\')
| null | null | null | Join two or more path components and create a regexp that will match that
path. | pcsd | def regexp path name *names return os path join name *names replace '\\' '\\\\' | 13541 | def _regexp_path(name, *names):
return os.path.join(name, *names).replace('\\', '\\\\')
| Join two or more path components and create a regexp that will match that
path. | join two or more path components and create a regexp that will match that path . | Question:
What does this function do?
Code:
def _regexp_path(name, *names):
return os.path.join(name, *names).replace('\\', '\\\\')
|
null | null | null | What does this function do? | def getGeometryOutputByManipulation(sideLoop, xmlElement):
sideLoop.loop = euclidean.getLoopWithoutCloseSequentialPoints(sideLoop.close, sideLoop.loop)
return sideLoop.getManipulationPluginLoops(xmlElement)
| null | null | null | Get geometry output by manipulation. | pcsd | def get Geometry Output By Manipulation side Loop xml Element side Loop loop = euclidean get Loop Without Close Sequential Points side Loop close side Loop loop return side Loop get Manipulation Plugin Loops xml Element | 13549 | def getGeometryOutputByManipulation(sideLoop, xmlElement):
sideLoop.loop = euclidean.getLoopWithoutCloseSequentialPoints(sideLoop.close, sideLoop.loop)
return sideLoop.getManipulationPluginLoops(xmlElement)
| Get geometry output by manipulation. | get geometry output by manipulation . | Question:
What does this function do?
Code:
def getGeometryOutputByManipulation(sideLoop, xmlElement):
sideLoop.loop = euclidean.getLoopWithoutCloseSequentialPoints(sideLoop.close, sideLoop.loop)
return sideLoop.getManipulationPluginLoops(xmlElement)
|
null | null | null | What does this function do? | def parse_version(version):
version_tuple = parse_semantic(version)
if (not version_tuple):
version_tuple = parse_legacy(version)
return version_tuple
| null | null | null | Attempts to parse SemVer, fallbacks on legacy | pcsd | def parse version version version tuple = parse semantic version if not version tuple version tuple = parse legacy version return version tuple | 13555 | def parse_version(version):
version_tuple = parse_semantic(version)
if (not version_tuple):
version_tuple = parse_legacy(version)
return version_tuple
| Attempts to parse SemVer, fallbacks on legacy | attempts to parse semver , fallbacks on legacy | Question:
What does this function do?
Code:
def parse_version(version):
version_tuple = parse_semantic(version)
if (not version_tuple):
version_tuple = parse_legacy(version)
return version_tuple
|
null | null | null | What does this function do? | def transform_key(key, seed, rounds):
cipher = AES.new(seed, AES.MODE_ECB)
for n in range(0, rounds):
key = cipher.encrypt(key)
return sha256(key)
| null | null | null | Transform `key` with `seed` `rounds` times using AES ECB. | pcsd | def transform key key seed rounds cipher = AES new seed AES MODE ECB for n in range 0 rounds key = cipher encrypt key return sha256 key | 13556 | def transform_key(key, seed, rounds):
cipher = AES.new(seed, AES.MODE_ECB)
for n in range(0, rounds):
key = cipher.encrypt(key)
return sha256(key)
| Transform `key` with `seed` `rounds` times using AES ECB. | transform key with seed rounds times using aes ecb . | Question:
What does this function do?
Code:
def transform_key(key, seed, rounds):
cipher = AES.new(seed, AES.MODE_ECB)
for n in range(0, rounds):
key = cipher.encrypt(key)
return sha256(key)
|
null | null | null | What does this function do? | def hash_user_password(user):
try:
password = user['password']
except KeyError:
return user
else:
return dict(user, password=hash_password(password))
| null | null | null | Hash a user dict\'s password without modifying the passed-in dict | pcsd | def hash user password user try password = user['password'] except Key Error return user else return dict user password=hash password password | 13559 | def hash_user_password(user):
try:
password = user['password']
except KeyError:
return user
else:
return dict(user, password=hash_password(password))
| Hash a user dict\'s password without modifying the passed-in dict | hash a user dicts password without modifying the passed - in dict | Question:
What does this function do?
Code:
def hash_user_password(user):
try:
password = user['password']
except KeyError:
return user
else:
return dict(user, password=hash_password(password))
|
null | null | null | What does this function do? | def is_exp_summary_editable(exp_summary, user_id=None):
return ((user_id is not None) and ((user_id in exp_summary.editor_ids) or (user_id in exp_summary.owner_ids) or exp_summary.community_owned))
| null | null | null | Checks if a given user may edit an exploration by checking
the given domain object. | pcsd | def is exp summary editable exp summary user id=None return user id is not None and user id in exp summary editor ids or user id in exp summary owner ids or exp summary community owned | 13563 | def is_exp_summary_editable(exp_summary, user_id=None):
return ((user_id is not None) and ((user_id in exp_summary.editor_ids) or (user_id in exp_summary.owner_ids) or exp_summary.community_owned))
| Checks if a given user may edit an exploration by checking
the given domain object. | checks if a given user may edit an exploration by checking the given domain object . | Question:
What does this function do?
Code:
def is_exp_summary_editable(exp_summary, user_id=None):
return ((user_id is not None) and ((user_id in exp_summary.editor_ids) or (user_id in exp_summary.owner_ids) or exp_summary.community_owned))
|
null | null | null | What does this function do? | def mw_search(server, query, num):
search_url = (u'http://%s/w/api.php?format=json&action=query&list=search&srlimit=%d&srprop=timestamp&srwhat=text&srsearch=' % (server, num))
search_url += query
query = json.loads(web.get(search_url))
if (u'query' in query):
query = query[u'query'][u'search']
return [r[u'title... | null | null | null | Searches the specified MediaWiki server for the given query, and returns
the specified number of results. | pcsd | def mw search server query num search url = u'http //%s/w/api php?format=json&action=query&list=search&srlimit=%d&srprop=timestamp&srwhat=text&srsearch=' % server num search url += query query = json loads web get search url if u'query' in query query = query[u'query'][u'search'] return [r[u'title'] for r in query] els... | 13564 | def mw_search(server, query, num):
search_url = (u'http://%s/w/api.php?format=json&action=query&list=search&srlimit=%d&srprop=timestamp&srwhat=text&srsearch=' % (server, num))
search_url += query
query = json.loads(web.get(search_url))
if (u'query' in query):
query = query[u'query'][u'search']
return [r[u'title... | Searches the specified MediaWiki server for the given query, and returns
the specified number of results. | searches the specified mediawiki server for the given query , and returns the specified number of results . | Question:
What does this function do?
Code:
def mw_search(server, query, num):
search_url = (u'http://%s/w/api.php?format=json&action=query&list=search&srlimit=%d&srprop=timestamp&srwhat=text&srsearch=' % (server, num))
search_url += query
query = json.loads(web.get(search_url))
if (u'query' in query):
query =... |
null | null | null | What does this function do? | def do_block(parser, token):
bits = token.contents.split()
if (len(bits) != 2):
raise TemplateSyntaxError, ("'%s' tag takes only one argument" % bits[0])
block_name = bits[1]
try:
if (block_name in parser.__loaded_blocks):
raise TemplateSyntaxError, ("'%s' tag with name '%s' appears more than once" % (bits[0... | null | null | null | Define a block that can be overridden by child templates. | pcsd | def do block parser token bits = token contents split if len bits != 2 raise Template Syntax Error "'%s' tag takes only one argument" % bits[0] block name = bits[1] try if block name in parser loaded blocks raise Template Syntax Error "'%s' tag with name '%s' appears more than once" % bits[0] block name parser loaded b... | 13572 | def do_block(parser, token):
bits = token.contents.split()
if (len(bits) != 2):
raise TemplateSyntaxError, ("'%s' tag takes only one argument" % bits[0])
block_name = bits[1]
try:
if (block_name in parser.__loaded_blocks):
raise TemplateSyntaxError, ("'%s' tag with name '%s' appears more than once" % (bits[0... | Define a block that can be overridden by child templates. | define a block that can be overridden by child templates . | Question:
What does this function do?
Code:
def do_block(parser, token):
bits = token.contents.split()
if (len(bits) != 2):
raise TemplateSyntaxError, ("'%s' tag takes only one argument" % bits[0])
block_name = bits[1]
try:
if (block_name in parser.__loaded_blocks):
raise TemplateSyntaxError, ("'%s' tag w... |
null | null | null | What does this function do? | def _is_xfce():
try:
return _readfrom((_get_x11_vars() + 'xprop -root _DT_SAVE_MODE'), shell=1).strip().endswith(' = "xfce4"')
except OSError:
return 0
| null | null | null | Return whether XFCE is in use. | pcsd | def is xfce try return readfrom get x11 vars + 'xprop -root DT SAVE MODE' shell=1 strip endswith ' = "xfce4"' except OS Error return 0 | 13589 | def _is_xfce():
try:
return _readfrom((_get_x11_vars() + 'xprop -root _DT_SAVE_MODE'), shell=1).strip().endswith(' = "xfce4"')
except OSError:
return 0
| Return whether XFCE is in use. | return whether xfce is in use . | Question:
What does this function do?
Code:
def _is_xfce():
try:
return _readfrom((_get_x11_vars() + 'xprop -root _DT_SAVE_MODE'), shell=1).strip().endswith(' = "xfce4"')
except OSError:
return 0
|
null | null | null | What does this function do? | def service_stop(name):
r = salt.utils.http.query(((DETAILS['url'] + 'service/stop/') + name), decode_type='json', decode=True)
return r['dict']
| null | null | null | Stop a "service" on the REST server | pcsd | def service stop name r = salt utils http query DETAILS['url'] + 'service/stop/' + name decode type='json' decode=True return r['dict'] | 13590 | def service_stop(name):
r = salt.utils.http.query(((DETAILS['url'] + 'service/stop/') + name), decode_type='json', decode=True)
return r['dict']
| Stop a "service" on the REST server | stop a " service " on the rest server | Question:
What does this function do?
Code:
def service_stop(name):
r = salt.utils.http.query(((DETAILS['url'] + 'service/stop/') + name), decode_type='json', decode=True)
return r['dict']
|
null | null | null | What does this function do? | def rws(t):
for c in ['\n', ' DCTB ', ' ']:
t = t.replace(c, '')
return t
| null | null | null | Remove white spaces, tabs, and new lines from a string | pcsd | def rws t for c in [' ' ' DCTB ' ' '] t = t replace c '' return t | 13598 | def rws(t):
for c in ['\n', ' DCTB ', ' ']:
t = t.replace(c, '')
return t
| Remove white spaces, tabs, and new lines from a string | remove white spaces , tabs , and new lines from a string | Question:
What does this function do?
Code:
def rws(t):
for c in ['\n', ' DCTB ', ' ']:
t = t.replace(c, '')
return t
|
null | null | null | What does this function do? | def discretize_integrate_2D(model, x_range, y_range):
from scipy.integrate import dblquad
x = np.arange((x_range[0] - 0.5), (x_range[1] + 0.5))
y = np.arange((y_range[0] - 0.5), (y_range[1] + 0.5))
values = np.empty(((y.size - 1), (x.size - 1)))
for i in range((x.size - 1)):
for j in range((y.size - 1)):
valu... | null | null | null | Discretize model by integrating the model over the pixel. | pcsd | def discretize integrate 2D model x range y range from scipy integrate import dblquad x = np arange x range[0] - 0 5 x range[1] + 0 5 y = np arange y range[0] - 0 5 y range[1] + 0 5 values = np empty y size - 1 x size - 1 for i in range x size - 1 for j in range y size - 1 values[ j i ] = dblquad model x[i] x[ i + 1 ] ... | 13602 | def discretize_integrate_2D(model, x_range, y_range):
from scipy.integrate import dblquad
x = np.arange((x_range[0] - 0.5), (x_range[1] + 0.5))
y = np.arange((y_range[0] - 0.5), (y_range[1] + 0.5))
values = np.empty(((y.size - 1), (x.size - 1)))
for i in range((x.size - 1)):
for j in range((y.size - 1)):
valu... | Discretize model by integrating the model over the pixel. | discretize model by integrating the model over the pixel . | Question:
What does this function do?
Code:
def discretize_integrate_2D(model, x_range, y_range):
from scipy.integrate import dblquad
x = np.arange((x_range[0] - 0.5), (x_range[1] + 0.5))
y = np.arange((y_range[0] - 0.5), (y_range[1] + 0.5))
values = np.empty(((y.size - 1), (x.size - 1)))
for i in range((x.size... |
null | null | null | What does this function do? | def load_from_library(library, label, names):
subset = Library()
for name in names:
found = False
if (name in library.tags):
found = True
subset.tags[name] = library.tags[name]
if (name in library.filters):
found = True
subset.filters[name] = library.filters[name]
if (found is False):
raise Tem... | null | null | null | Return a subset of tags and filters from a library. | pcsd | def load from library library label names subset = Library for name in names found = False if name in library tags found = True subset tags[name] = library tags[name] if name in library filters found = True subset filters[name] = library filters[name] if found is False raise Template Syntax Error "'%s' is not a valid t... | 13615 | def load_from_library(library, label, names):
subset = Library()
for name in names:
found = False
if (name in library.tags):
found = True
subset.tags[name] = library.tags[name]
if (name in library.filters):
found = True
subset.filters[name] = library.filters[name]
if (found is False):
raise Tem... | Return a subset of tags and filters from a library. | return a subset of tags and filters from a library . | Question:
What does this function do?
Code:
def load_from_library(library, label, names):
subset = Library()
for name in names:
found = False
if (name in library.tags):
found = True
subset.tags[name] = library.tags[name]
if (name in library.filters):
found = True
subset.filters[name] = library.fi... |
null | null | null | What does this function do? | def _symlink_check(name, target, force, user, group):
pchanges = {}
if ((not os.path.exists(name)) and (not __salt__['file.is_link'](name))):
pchanges['new'] = name
return (None, 'Symlink {0} to {1} is set for creation'.format(name, target), pchanges)
if __salt__['file.is_link'](name):
if (__salt__['file.readl... | null | null | null | Check the symlink function | pcsd | def symlink check name target force user group pchanges = {} if not os path exists name and not salt ['file is link'] name pchanges['new'] = name return None 'Symlink {0} to {1} is set for creation' format name target pchanges if salt ['file is link'] name if salt ['file readlink'] name != target pchanges['change'] = n... | 13620 | def _symlink_check(name, target, force, user, group):
pchanges = {}
if ((not os.path.exists(name)) and (not __salt__['file.is_link'](name))):
pchanges['new'] = name
return (None, 'Symlink {0} to {1} is set for creation'.format(name, target), pchanges)
if __salt__['file.is_link'](name):
if (__salt__['file.readl... | Check the symlink function | check the symlink function | Question:
What does this function do?
Code:
def _symlink_check(name, target, force, user, group):
pchanges = {}
if ((not os.path.exists(name)) and (not __salt__['file.is_link'](name))):
pchanges['new'] = name
return (None, 'Symlink {0} to {1} is set for creation'.format(name, target), pchanges)
if __salt__['f... |
null | null | null | What does this function do? | def _find_all_simple(path):
results = (os.path.join(base, file) for (base, dirs, files) in os.walk(path, followlinks=True) for file in files)
return filter(os.path.isfile, results)
| null | null | null | Find all files under \'path\' | pcsd | def find all simple path results = os path join base file for base dirs files in os walk path followlinks=True for file in files return filter os path isfile results | 13647 | def _find_all_simple(path):
results = (os.path.join(base, file) for (base, dirs, files) in os.walk(path, followlinks=True) for file in files)
return filter(os.path.isfile, results)
| Find all files under \'path\' | find all files under path | Question:
What does this function do?
Code:
def _find_all_simple(path):
results = (os.path.join(base, file) for (base, dirs, files) in os.walk(path, followlinks=True) for file in files)
return filter(os.path.isfile, results)
|
null | null | null | What does this function do? | def mocked_exception(*args, **kwargs):
raise OSError
| null | null | null | Mock exception thrown by requests.get. | pcsd | def mocked exception *args **kwargs raise OS Error | 13648 | def mocked_exception(*args, **kwargs):
raise OSError
| Mock exception thrown by requests.get. | mock exception thrown by requests . get . | Question:
What does this function do?
Code:
def mocked_exception(*args, **kwargs):
raise OSError
|
null | null | null | What does this function do? | @slow_test
@testing.requires_testing_data
def test_make_forward_solution():
fwd_py = make_forward_solution(fname_raw, fname_trans, fname_src, fname_bem, mindist=5.0, eeg=True, meg=True)
assert_true(isinstance(fwd_py, Forward))
fwd = read_forward_solution(fname_meeg)
assert_true(isinstance(fwd, Forward))
_compare_f... | null | null | null | Test making M-EEG forward solution from python | pcsd | @slow test @testing requires testing data def test make forward solution fwd py = make forward solution fname raw fname trans fname src fname bem mindist=5 0 eeg=True meg=True assert true isinstance fwd py Forward fwd = read forward solution fname meeg assert true isinstance fwd Forward compare forwards fwd fwd py 366 ... | 13649 | @slow_test
@testing.requires_testing_data
def test_make_forward_solution():
fwd_py = make_forward_solution(fname_raw, fname_trans, fname_src, fname_bem, mindist=5.0, eeg=True, meg=True)
assert_true(isinstance(fwd_py, Forward))
fwd = read_forward_solution(fname_meeg)
assert_true(isinstance(fwd, Forward))
_compare_f... | Test making M-EEG forward solution from python | test making m - eeg forward solution from python | Question:
What does this function do?
Code:
@slow_test
@testing.requires_testing_data
def test_make_forward_solution():
fwd_py = make_forward_solution(fname_raw, fname_trans, fname_src, fname_bem, mindist=5.0, eeg=True, meg=True)
assert_true(isinstance(fwd_py, Forward))
fwd = read_forward_solution(fname_meeg)
as... |
null | null | null | What does this function do? | def require_target_existed(targets):
if (not targets['list']):
msg = output_log(MSG.NO_CONNECTED_TARGET)
raise exception.VSPError(msg)
| null | null | null | Check if the target list includes one or more members. | pcsd | def require target existed targets if not targets['list'] msg = output log MSG NO CONNECTED TARGET raise exception VSP Error msg | 13653 | def require_target_existed(targets):
if (not targets['list']):
msg = output_log(MSG.NO_CONNECTED_TARGET)
raise exception.VSPError(msg)
| Check if the target list includes one or more members. | check if the target list includes one or more members . | Question:
What does this function do?
Code:
def require_target_existed(targets):
if (not targets['list']):
msg = output_log(MSG.NO_CONNECTED_TARGET)
raise exception.VSPError(msg)
|
null | null | null | What does this function do? | def is_image_visible(context, image, status=None):
if context.is_admin:
return True
if (image['owner'] is None):
return True
if image['is_public']:
return True
if (context.owner is not None):
if (context.owner == image['owner']):
return True
members = image_member_find(context, image_id=image['id'], me... | null | null | null | Return True if the image is visible in this context. | pcsd | def is image visible context image status=None if context is admin return True if image['owner'] is None return True if image['is public'] return True if context owner is not None if context owner == image['owner'] return True members = image member find context image id=image['id'] member=context owner status=status i... | 13656 | def is_image_visible(context, image, status=None):
if context.is_admin:
return True
if (image['owner'] is None):
return True
if image['is_public']:
return True
if (context.owner is not None):
if (context.owner == image['owner']):
return True
members = image_member_find(context, image_id=image['id'], me... | Return True if the image is visible in this context. | return true if the image is visible in this context . | Question:
What does this function do?
Code:
def is_image_visible(context, image, status=None):
if context.is_admin:
return True
if (image['owner'] is None):
return True
if image['is_public']:
return True
if (context.owner is not None):
if (context.owner == image['owner']):
return True
members = imag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.