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? | @safe_filter(error_output=False)
@register.filter
def is_portrait(file_):
if sorl_settings.THUMBNAIL_DUMMY:
return (sorl_settings.THUMBNAIL_DUMMY_RATIO < 1)
if (not file_):
return False
image_file = default.kvstore.get_or_set(ImageFile(file_))
return image_file.is_portrait()
| null | null | null | A very handy filter to determine if an image is portrait or landscape. | pcsd | @safe filter error output=False @register filter def is portrait file if sorl settings THUMBNAIL DUMMY return sorl settings THUMBNAIL DUMMY RATIO < 1 if not file return False image file = default kvstore get or set Image File file return image file is portrait | 14788 | @safe_filter(error_output=False)
@register.filter
def is_portrait(file_):
if sorl_settings.THUMBNAIL_DUMMY:
return (sorl_settings.THUMBNAIL_DUMMY_RATIO < 1)
if (not file_):
return False
image_file = default.kvstore.get_or_set(ImageFile(file_))
return image_file.is_portrait()
| A very handy filter to determine if an image is portrait or landscape. | a very handy filter to determine if an image is portrait or landscape . | Question:
What does this function do?
Code:
@safe_filter(error_output=False)
@register.filter
def is_portrait(file_):
if sorl_settings.THUMBNAIL_DUMMY:
return (sorl_settings.THUMBNAIL_DUMMY_RATIO < 1)
if (not file_):
return False
image_file = default.kvstore.get_or_set(ImageFile(file_))
return image_file.is_... |
null | null | null | What does this function do? | def remove_samples(path):
RE_SAMPLE = re.compile(sample_match, re.I)
for (root, _dirs, files) in os.walk(path):
for file_ in files:
if RE_SAMPLE.search(file_):
path = os.path.join(root, file_)
try:
logging.info('Removing unwanted sample file %s', path)
os.remove(path)
except:
logging.e... | null | null | null | Remove all files that match the sample pattern | pcsd | def remove samples path RE SAMPLE = re compile sample match re I for root dirs files in os walk path for file in files if RE SAMPLE search file path = os path join root file try logging info 'Removing unwanted sample file %s' path os remove path except logging error T 'Removing %s failed' clip path path logging info 'T... | 14794 | def remove_samples(path):
RE_SAMPLE = re.compile(sample_match, re.I)
for (root, _dirs, files) in os.walk(path):
for file_ in files:
if RE_SAMPLE.search(file_):
path = os.path.join(root, file_)
try:
logging.info('Removing unwanted sample file %s', path)
os.remove(path)
except:
logging.e... | Remove all files that match the sample pattern | remove all files that match the sample pattern | Question:
What does this function do?
Code:
def remove_samples(path):
RE_SAMPLE = re.compile(sample_match, re.I)
for (root, _dirs, files) in os.walk(path):
for file_ in files:
if RE_SAMPLE.search(file_):
path = os.path.join(root, file_)
try:
logging.info('Removing unwanted sample file %s', path)
... |
null | null | null | What does this function do? | def split_addresses(email_string_list):
return [f for f in [s.strip() for s in email_string_list.split(u',')] if f]
| null | null | null | Converts a string containing comma separated email addresses
into a list of email addresses. | pcsd | def split addresses email string list return [f for f in [s strip for s in email string list split u' ' ] if f] | 14797 | def split_addresses(email_string_list):
return [f for f in [s.strip() for s in email_string_list.split(u',')] if f]
| Converts a string containing comma separated email addresses
into a list of email addresses. | converts a string containing comma separated email addresses into a list of email addresses . | Question:
What does this function do?
Code:
def split_addresses(email_string_list):
return [f for f in [s.strip() for s in email_string_list.split(u',')] if f]
|
null | null | null | What does this function do? | def desktop_name_dlgproc(hwnd, msg, wparam, lparam):
if (msg in (win32con.WM_CLOSE, win32con.WM_DESTROY)):
win32gui.DestroyWindow(hwnd)
elif (msg == win32con.WM_COMMAND):
if (wparam == win32con.IDOK):
desktop_name = win32gui.GetDlgItemText(hwnd, 72)
print 'new desktop name: ', desktop_name
win32gui.Destr... | null | null | null | Handles messages from the desktop name dialog box | pcsd | def desktop name dlgproc hwnd msg wparam lparam if msg in win32con WM CLOSE win32con WM DESTROY win32gui Destroy Window hwnd elif msg == win32con WM COMMAND if wparam == win32con IDOK desktop name = win32gui Get Dlg Item Text hwnd 72 print 'new desktop name ' desktop name win32gui Destroy Window hwnd create desktop des... | 14806 | def desktop_name_dlgproc(hwnd, msg, wparam, lparam):
if (msg in (win32con.WM_CLOSE, win32con.WM_DESTROY)):
win32gui.DestroyWindow(hwnd)
elif (msg == win32con.WM_COMMAND):
if (wparam == win32con.IDOK):
desktop_name = win32gui.GetDlgItemText(hwnd, 72)
print 'new desktop name: ', desktop_name
win32gui.Destr... | Handles messages from the desktop name dialog box | handles messages from the desktop name dialog box | Question:
What does this function do?
Code:
def desktop_name_dlgproc(hwnd, msg, wparam, lparam):
if (msg in (win32con.WM_CLOSE, win32con.WM_DESTROY)):
win32gui.DestroyWindow(hwnd)
elif (msg == win32con.WM_COMMAND):
if (wparam == win32con.IDOK):
desktop_name = win32gui.GetDlgItemText(hwnd, 72)
print 'new ... |
null | null | null | What does this function do? | @requires_application()
def test_functionality_proxy():
_test_functionality('gl2 debug')
| null | null | null | Test GL proxy class for full functionality. | pcsd | @requires application def test functionality proxy test functionality 'gl2 debug' | 14812 | @requires_application()
def test_functionality_proxy():
_test_functionality('gl2 debug')
| Test GL proxy class for full functionality. | test gl proxy class for full functionality . | Question:
What does this function do?
Code:
@requires_application()
def test_functionality_proxy():
_test_functionality('gl2 debug')
|
null | null | null | What does this function do? | def _import_by_name(name):
try:
name_parts = name.split('.')
modname = '.'.join(name_parts[:(-1)])
if modname:
try:
__import__(modname)
mod = sys.modules[modname]
return (getattr(mod, name_parts[(-1)]), mod, modname)
except (ImportError, IndexError, AttributeError):
pass
last_j = 0
modn... | null | null | null | Import a Python object given its full name. | pcsd | def import by name name try name parts = name split ' ' modname = ' ' join name parts[ -1 ] if modname try import modname mod = sys modules[modname] return getattr mod name parts[ -1 ] mod modname except Import Error Index Error Attribute Error pass last j = 0 modname = None for j in reversed range 1 len name parts + 1... | 14814 | def _import_by_name(name):
try:
name_parts = name.split('.')
modname = '.'.join(name_parts[:(-1)])
if modname:
try:
__import__(modname)
mod = sys.modules[modname]
return (getattr(mod, name_parts[(-1)]), mod, modname)
except (ImportError, IndexError, AttributeError):
pass
last_j = 0
modn... | Import a Python object given its full name. | import a python object given its full name . | Question:
What does this function do?
Code:
def _import_by_name(name):
try:
name_parts = name.split('.')
modname = '.'.join(name_parts[:(-1)])
if modname:
try:
__import__(modname)
mod = sys.modules[modname]
return (getattr(mod, name_parts[(-1)]), mod, modname)
except (ImportError, IndexError... |
null | null | null | What does this function do? | def create_lport(cluster, lswitch_uuid, tenant_id, quantum_port_id, display_name, device_id, admin_status_enabled, mac_address=None, fixed_ips=None, port_security_enabled=None, security_profiles=None, queue_id=None):
hashed_device_id = hashlib.sha1(device_id).hexdigest()
display_name = _check_and_truncate_name(displa... | null | null | null | Creates a logical port on the assigned logical switch | pcsd | def create lport cluster lswitch uuid tenant id quantum port id display name device id admin status enabled mac address=None fixed ips=None port security enabled=None security profiles=None queue id=None hashed device id = hashlib sha1 device id hexdigest display name = check and truncate name display name lport obj = ... | 14835 | def create_lport(cluster, lswitch_uuid, tenant_id, quantum_port_id, display_name, device_id, admin_status_enabled, mac_address=None, fixed_ips=None, port_security_enabled=None, security_profiles=None, queue_id=None):
hashed_device_id = hashlib.sha1(device_id).hexdigest()
display_name = _check_and_truncate_name(displa... | Creates a logical port on the assigned logical switch | creates a logical port on the assigned logical switch | Question:
What does this function do?
Code:
def create_lport(cluster, lswitch_uuid, tenant_id, quantum_port_id, display_name, device_id, admin_status_enabled, mac_address=None, fixed_ips=None, port_security_enabled=None, security_profiles=None, queue_id=None):
hashed_device_id = hashlib.sha1(device_id).hexdigest()
... |
null | null | null | What does this function do? | def write_int_matrix(fid, kind, mat):
FIFFT_MATRIX = (1 << 30)
FIFFT_MATRIX_INT = (FIFF.FIFFT_INT | FIFFT_MATRIX)
data_size = ((4 * mat.size) + (4 * 3))
fid.write(np.array(kind, dtype='>i4').tostring())
fid.write(np.array(FIFFT_MATRIX_INT, dtype='>i4').tostring())
fid.write(np.array(data_size, dtype='>i4').tostri... | null | null | null | Write integer 32 matrix tag. | pcsd | def write int matrix fid kind mat FIFFT MATRIX = 1 << 30 FIFFT MATRIX INT = FIFF FIFFT INT | FIFFT MATRIX data size = 4 * mat size + 4 * 3 fid write np array kind dtype='>i4' tostring fid write np array FIFFT MATRIX INT dtype='>i4' tostring fid write np array data size dtype='>i4' tostring fid write np array FIFF FIFFV... | 14837 | def write_int_matrix(fid, kind, mat):
FIFFT_MATRIX = (1 << 30)
FIFFT_MATRIX_INT = (FIFF.FIFFT_INT | FIFFT_MATRIX)
data_size = ((4 * mat.size) + (4 * 3))
fid.write(np.array(kind, dtype='>i4').tostring())
fid.write(np.array(FIFFT_MATRIX_INT, dtype='>i4').tostring())
fid.write(np.array(data_size, dtype='>i4').tostri... | Write integer 32 matrix tag. | write integer 32 matrix tag . | Question:
What does this function do?
Code:
def write_int_matrix(fid, kind, mat):
FIFFT_MATRIX = (1 << 30)
FIFFT_MATRIX_INT = (FIFF.FIFFT_INT | FIFFT_MATRIX)
data_size = ((4 * mat.size) + (4 * 3))
fid.write(np.array(kind, dtype='>i4').tostring())
fid.write(np.array(FIFFT_MATRIX_INT, dtype='>i4').tostring())
fi... |
null | null | null | What does this function do? | def fitLine(pts):
n = len(pts)
if (n < 1):
return ((0, 0), (0, 0))
a = np.zeros(((n - 1), 2))
for i in range((n - 1)):
v = (pts[i] - pts[(i + 1)])
a[i] = (v / np.linalg.norm(v))
direction = np.mean(a[1:(-1)], axis=0)
start = np.mean(pts[1:(-1)], axis=0)
return (start, (start + direction))
| null | null | null | returns a start vector and direction vector
Assumes points segments that already form a somewhat smooth line | pcsd | def fit Line pts n = len pts if n < 1 return 0 0 0 0 a = np zeros n - 1 2 for i in range n - 1 v = pts[i] - pts[ i + 1 ] a[i] = v / np linalg norm v direction = np mean a[1 -1 ] axis=0 start = np mean pts[1 -1 ] axis=0 return start start + direction | 14839 | def fitLine(pts):
n = len(pts)
if (n < 1):
return ((0, 0), (0, 0))
a = np.zeros(((n - 1), 2))
for i in range((n - 1)):
v = (pts[i] - pts[(i + 1)])
a[i] = (v / np.linalg.norm(v))
direction = np.mean(a[1:(-1)], axis=0)
start = np.mean(pts[1:(-1)], axis=0)
return (start, (start + direction))
| returns a start vector and direction vector
Assumes points segments that already form a somewhat smooth line | returns a start vector and direction vector | Question:
What does this function do?
Code:
def fitLine(pts):
n = len(pts)
if (n < 1):
return ((0, 0), (0, 0))
a = np.zeros(((n - 1), 2))
for i in range((n - 1)):
v = (pts[i] - pts[(i + 1)])
a[i] = (v / np.linalg.norm(v))
direction = np.mean(a[1:(-1)], axis=0)
start = np.mean(pts[1:(-1)], axis=0)
return... |
null | null | null | What does this function do? | def worker_update(context, id, filters=None, orm_worker=None, **values):
return IMPL.worker_update(context, id, filters=filters, orm_worker=orm_worker, **values)
| null | null | null | Update a worker with given values. | pcsd | def worker update context id filters=None orm worker=None **values return IMPL worker update context id filters=filters orm worker=orm worker **values | 14840 | def worker_update(context, id, filters=None, orm_worker=None, **values):
return IMPL.worker_update(context, id, filters=filters, orm_worker=orm_worker, **values)
| Update a worker with given values. | update a worker with given values . | Question:
What does this function do?
Code:
def worker_update(context, id, filters=None, orm_worker=None, **values):
return IMPL.worker_update(context, id, filters=filters, orm_worker=orm_worker, **values)
|
null | null | null | What does this function do? | def getInstanceState(inst, jellier):
if hasattr(inst, '__getstate__'):
state = inst.__getstate__()
else:
state = inst.__dict__
sxp = jellier.prepare(inst)
sxp.extend([qual(inst.__class__).encode('utf-8'), jellier.jelly(state)])
return jellier.preserve(inst, sxp)
| null | null | null | Utility method to default to \'normal\' state rules in serialization. | pcsd | def get Instance State inst jellier if hasattr inst ' getstate ' state = inst getstate else state = inst dict sxp = jellier prepare inst sxp extend [qual inst class encode 'utf-8' jellier jelly state ] return jellier preserve inst sxp | 14843 | def getInstanceState(inst, jellier):
if hasattr(inst, '__getstate__'):
state = inst.__getstate__()
else:
state = inst.__dict__
sxp = jellier.prepare(inst)
sxp.extend([qual(inst.__class__).encode('utf-8'), jellier.jelly(state)])
return jellier.preserve(inst, sxp)
| Utility method to default to \'normal\' state rules in serialization. | utility method to default to normal state rules in serialization . | Question:
What does this function do?
Code:
def getInstanceState(inst, jellier):
if hasattr(inst, '__getstate__'):
state = inst.__getstate__()
else:
state = inst.__dict__
sxp = jellier.prepare(inst)
sxp.extend([qual(inst.__class__).encode('utf-8'), jellier.jelly(state)])
return jellier.preserve(inst, sxp)
|
null | null | null | What does this function do? | def map_references(value, field, actual_course_key):
if (not value):
return value
if isinstance(field, Reference):
return value.map_into_course(actual_course_key)
if isinstance(field, ReferenceList):
return [sub.map_into_course(actual_course_key) for sub in value]
if isinstance(field, ReferenceValueDict):
r... | null | null | null | Map the references in value to actual_course_key and return value | pcsd | def map references value field actual course key if not value return value if isinstance field Reference return value map into course actual course key if isinstance field Reference List return [sub map into course actual course key for sub in value] if isinstance field Reference Value Dict return {key ele map into cou... | 14846 | def map_references(value, field, actual_course_key):
if (not value):
return value
if isinstance(field, Reference):
return value.map_into_course(actual_course_key)
if isinstance(field, ReferenceList):
return [sub.map_into_course(actual_course_key) for sub in value]
if isinstance(field, ReferenceValueDict):
r... | Map the references in value to actual_course_key and return value | map the references in value to actual _ course _ key and return value | Question:
What does this function do?
Code:
def map_references(value, field, actual_course_key):
if (not value):
return value
if isinstance(field, Reference):
return value.map_into_course(actual_course_key)
if isinstance(field, ReferenceList):
return [sub.map_into_course(actual_course_key) for sub in value]... |
null | null | null | What does this function do? | def all_suffixes():
return ((SOURCE_SUFFIXES + BYTECODE_SUFFIXES) + EXTENSION_SUFFIXES)
| null | null | null | Returns a list of all recognized module suffixes for this process | pcsd | def all suffixes return SOURCE SUFFIXES + BYTECODE SUFFIXES + EXTENSION SUFFIXES | 14859 | def all_suffixes():
return ((SOURCE_SUFFIXES + BYTECODE_SUFFIXES) + EXTENSION_SUFFIXES)
| Returns a list of all recognized module suffixes for this process | returns a list of all recognized module suffixes for this process | Question:
What does this function do?
Code:
def all_suffixes():
return ((SOURCE_SUFFIXES + BYTECODE_SUFFIXES) + EXTENSION_SUFFIXES)
|
null | null | null | What does this function do? | def get_args():
parser = argparse.ArgumentParser(description='Process args for streaming property changes', epilog='\nExample usage:\nwaitforupdates.py -k -s vcenter -u root -p vmware -i 1 -P\nVirtualMachine:name,summary.config.numCpu,runtime.powerState,config.uuid -P\n-P Datacenter:name -- This will fetch and print a... | null | null | null | Supports the command-line arguments listed below. | pcsd | def get args parser = argparse Argument Parser description='Process args for streaming property changes' epilog=' Example usage waitforupdates py -k -s vcenter -u root -p vmware -i 1 -P Virtual Machine name summary config num Cpu runtime power State config uuid -P -P Datacenter name -- This will fetch and print a few V... | 14861 | def get_args():
parser = argparse.ArgumentParser(description='Process args for streaming property changes', epilog='\nExample usage:\nwaitforupdates.py -k -s vcenter -u root -p vmware -i 1 -P\nVirtualMachine:name,summary.config.numCpu,runtime.powerState,config.uuid -P\n-P Datacenter:name -- This will fetch and print a... | Supports the command-line arguments listed below. | supports the command - line arguments listed below . | Question:
What does this function do?
Code:
def get_args():
parser = argparse.ArgumentParser(description='Process args for streaming property changes', epilog='\nExample usage:\nwaitforupdates.py -k -s vcenter -u root -p vmware -i 1 -P\nVirtualMachine:name,summary.config.numCpu,runtime.powerState,config.uuid -P\n-P... |
null | null | null | What does this function do? | def AutoProxy(token, serializer, manager=None, authkey=None, exposed=None, incref=True):
_Client = listener_client[serializer][1]
if (exposed is None):
conn = _Client(token.address, authkey=authkey)
try:
exposed = dispatch(conn, None, 'get_methods', (token,))
finally:
conn.close()
if ((authkey is None) a... | null | null | null | Return an auto-proxy for `token` | pcsd | def Auto Proxy token serializer manager=None authkey=None exposed=None incref=True Client = listener client[serializer][1] if exposed is None conn = Client token address authkey=authkey try exposed = dispatch conn None 'get methods' token finally conn close if authkey is None and manager is not None authkey = manager a... | 14868 | def AutoProxy(token, serializer, manager=None, authkey=None, exposed=None, incref=True):
_Client = listener_client[serializer][1]
if (exposed is None):
conn = _Client(token.address, authkey=authkey)
try:
exposed = dispatch(conn, None, 'get_methods', (token,))
finally:
conn.close()
if ((authkey is None) a... | Return an auto-proxy for `token` | return an auto - proxy for token | Question:
What does this function do?
Code:
def AutoProxy(token, serializer, manager=None, authkey=None, exposed=None, incref=True):
_Client = listener_client[serializer][1]
if (exposed is None):
conn = _Client(token.address, authkey=authkey)
try:
exposed = dispatch(conn, None, 'get_methods', (token,))
fi... |
null | null | null | What does this function do? | def find_resource(manager, name_or_id, wrap_exception=True, **find_args):
if getattr(manager, 'is_alphanum_id_allowed', False):
try:
return manager.get(name_or_id)
except exceptions.NotFound:
pass
try:
tmp_id = encodeutils.safe_encode(name_or_id)
if six.PY3:
tmp_id = tmp_id.decode()
uuid.UUID(tmp_i... | null | null | null | Helper for the _find_* methods. | pcsd | def find resource manager name or id wrap exception=True **find args if getattr manager 'is alphanum id allowed' False try return manager get name or id except exceptions Not Found pass try tmp id = encodeutils safe encode name or id if six PY3 tmp id = tmp id decode uuid UUID tmp id return manager get tmp id except Ty... | 14871 | def find_resource(manager, name_or_id, wrap_exception=True, **find_args):
if getattr(manager, 'is_alphanum_id_allowed', False):
try:
return manager.get(name_or_id)
except exceptions.NotFound:
pass
try:
tmp_id = encodeutils.safe_encode(name_or_id)
if six.PY3:
tmp_id = tmp_id.decode()
uuid.UUID(tmp_i... | Helper for the _find_* methods. | helper for the _ find _ * methods . | Question:
What does this function do?
Code:
def find_resource(manager, name_or_id, wrap_exception=True, **find_args):
if getattr(manager, 'is_alphanum_id_allowed', False):
try:
return manager.get(name_or_id)
except exceptions.NotFound:
pass
try:
tmp_id = encodeutils.safe_encode(name_or_id)
if six.PY3... |
null | null | null | What does this function do? | def _get_G(k_params):
I = np.eye(k_params)
A = np.concatenate(((- I), (- I)), axis=1)
B = np.concatenate((I, (- I)), axis=1)
C = np.concatenate((A, B), axis=0)
return matrix(C)
| null | null | null | The linear inequality constraint matrix. | pcsd | def get G k params I = np eye k params A = np concatenate - I - I axis=1 B = np concatenate I - I axis=1 C = np concatenate A B axis=0 return matrix C | 14873 | def _get_G(k_params):
I = np.eye(k_params)
A = np.concatenate(((- I), (- I)), axis=1)
B = np.concatenate((I, (- I)), axis=1)
C = np.concatenate((A, B), axis=0)
return matrix(C)
| The linear inequality constraint matrix. | the linear inequality constraint matrix . | Question:
What does this function do?
Code:
def _get_G(k_params):
I = np.eye(k_params)
A = np.concatenate(((- I), (- I)), axis=1)
B = np.concatenate((I, (- I)), axis=1)
C = np.concatenate((A, B), axis=0)
return matrix(C)
|
null | null | null | What does this function do? | def clear():
_get_manager().clear()
| null | null | null | Clear all callbacks. | pcsd | def clear get manager clear | 14876 | def clear():
_get_manager().clear()
| Clear all callbacks. | clear all callbacks . | Question:
What does this function do?
Code:
def clear():
_get_manager().clear()
|
null | null | null | What does this function do? | @require_admin_context
def instance_type_destroy(context, name):
session = get_session()
with session.begin():
instance_type_ref = instance_type_get_by_name(context, name, session=session)
instance_type_id = instance_type_ref['id']
session.query(models.InstanceTypes).filter_by(id=instance_type_id).soft_delete()... | null | null | null | Marks specific instance_type as deleted. | pcsd | @require admin context def instance type destroy context name session = get session with session begin instance type ref = instance type get by name context name session=session instance type id = instance type ref['id'] session query models Instance Types filter by id=instance type id soft delete session query models ... | 14879 | @require_admin_context
def instance_type_destroy(context, name):
session = get_session()
with session.begin():
instance_type_ref = instance_type_get_by_name(context, name, session=session)
instance_type_id = instance_type_ref['id']
session.query(models.InstanceTypes).filter_by(id=instance_type_id).soft_delete()... | Marks specific instance_type as deleted. | marks specific instance _ type as deleted . | Question:
What does this function do?
Code:
@require_admin_context
def instance_type_destroy(context, name):
session = get_session()
with session.begin():
instance_type_ref = instance_type_get_by_name(context, name, session=session)
instance_type_id = instance_type_ref['id']
session.query(models.InstanceType... |
null | null | null | What does this function do? | def is_user_context(context):
if (not context):
return False
if context.is_admin:
return False
if ((not context.user_id) or (not context.project_id)):
return False
return True
| null | null | null | Indicates if the request context is a normal user. | pcsd | def is user context context if not context return False if context is admin return False if not context user id or not context project id return False return True | 14883 | def is_user_context(context):
if (not context):
return False
if context.is_admin:
return False
if ((not context.user_id) or (not context.project_id)):
return False
return True
| Indicates if the request context is a normal user. | indicates if the request context is a normal user . | Question:
What does this function do?
Code:
def is_user_context(context):
if (not context):
return False
if context.is_admin:
return False
if ((not context.user_id) or (not context.project_id)):
return False
return True
|
null | null | null | What does this function do? | def create_message(request, message):
assert hasattr(request, 'session'), "django-session-messages requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
try:
request.session['messages'].append(message)
except KeyError:
... | null | null | null | Create a message in the current session. | pcsd | def create message request message assert hasattr request 'session' "django-session-messages requires session middleware to be installed Edit your MIDDLEWARE CLASSES setting to insert 'django contrib sessions middleware Session Middleware' " try request session['messages'] append message except Key Error request sessio... | 14888 | def create_message(request, message):
assert hasattr(request, 'session'), "django-session-messages requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
try:
request.session['messages'].append(message)
except KeyError:
... | Create a message in the current session. | create a message in the current session . | Question:
What does this function do?
Code:
def create_message(request, message):
assert hasattr(request, 'session'), "django-session-messages requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
try:
request.session[... |
null | null | null | What does this function do? | def _printinfo(message, quiet):
if (not quiet):
print message
| null | null | null | Helper to print messages | pcsd | def printinfo message quiet if not quiet print message | 14890 | def _printinfo(message, quiet):
if (not quiet):
print message
| Helper to print messages | helper to print messages | Question:
What does this function do?
Code:
def _printinfo(message, quiet):
if (not quiet):
print message
|
null | null | null | What does this function do? | def rearrange_by_column_disk(df, column, npartitions=None, compute=False):
if (npartitions is None):
npartitions = df.npartitions
token = tokenize(df, column, npartitions)
always_new_token = uuid.uuid1().hex
p = (('zpartd-' + always_new_token),)
dsk1 = {p: (maybe_buffered_partd(),)}
name = ('shuffle-partition-'... | null | null | null | Shuffle using local disk | pcsd | def rearrange by column disk df column npartitions=None compute=False if npartitions is None npartitions = df npartitions token = tokenize df column npartitions always new token = uuid uuid1 hex p = 'zpartd-' + always new token dsk1 = {p maybe buffered partd } name = 'shuffle-partition-' + always new token dsk2 = { nam... | 14893 | def rearrange_by_column_disk(df, column, npartitions=None, compute=False):
if (npartitions is None):
npartitions = df.npartitions
token = tokenize(df, column, npartitions)
always_new_token = uuid.uuid1().hex
p = (('zpartd-' + always_new_token),)
dsk1 = {p: (maybe_buffered_partd(),)}
name = ('shuffle-partition-'... | Shuffle using local disk | shuffle using local disk | Question:
What does this function do?
Code:
def rearrange_by_column_disk(df, column, npartitions=None, compute=False):
if (npartitions is None):
npartitions = df.npartitions
token = tokenize(df, column, npartitions)
always_new_token = uuid.uuid1().hex
p = (('zpartd-' + always_new_token),)
dsk1 = {p: (maybe_bu... |
null | null | null | What does this function do? | def wsgi_path_item(environ, name):
try:
return environ['wsgiorg.routing_args'][1][name]
except (KeyError, IndexError):
return None
| null | null | null | Extract the value of a named field in a URL.
Return None if the name is not present or there are no path items. | pcsd | def wsgi path item environ name try return environ['wsgiorg routing args'][1][name] except Key Error Index Error return None | 14897 | def wsgi_path_item(environ, name):
try:
return environ['wsgiorg.routing_args'][1][name]
except (KeyError, IndexError):
return None
| Extract the value of a named field in a URL.
Return None if the name is not present or there are no path items. | extract the value of a named field in a url . | Question:
What does this function do?
Code:
def wsgi_path_item(environ, name):
try:
return environ['wsgiorg.routing_args'][1][name]
except (KeyError, IndexError):
return None
|
null | null | null | What does this function do? | def execute(*cmd, **kwargs):
process_input = kwargs.pop('process_input', None)
run_as_root = kwargs.pop('run_as_root', True)
ret = 0
try:
if ((len(cmd) > 3) and (cmd[0] == 'raidcom') and (cmd[1] == '-login')):
(stdout, stderr) = cinder_utils.execute(process_input=process_input, run_as_root=run_as_root, logleve... | null | null | null | Run the specified command and return its results. | pcsd | def execute *cmd **kwargs process input = kwargs pop 'process input' None run as root = kwargs pop 'run as root' True ret = 0 try if len cmd > 3 and cmd[0] == 'raidcom' and cmd[1] == '-login' stdout stderr = cinder utils execute process input=process input run as root=run as root loglevel=base logging NOTSET *cmd [ 2] ... | 14900 | def execute(*cmd, **kwargs):
process_input = kwargs.pop('process_input', None)
run_as_root = kwargs.pop('run_as_root', True)
ret = 0
try:
if ((len(cmd) > 3) and (cmd[0] == 'raidcom') and (cmd[1] == '-login')):
(stdout, stderr) = cinder_utils.execute(process_input=process_input, run_as_root=run_as_root, logleve... | Run the specified command and return its results. | run the specified command and return its results . | Question:
What does this function do?
Code:
def execute(*cmd, **kwargs):
process_input = kwargs.pop('process_input', None)
run_as_root = kwargs.pop('run_as_root', True)
ret = 0
try:
if ((len(cmd) > 3) and (cmd[0] == 'raidcom') and (cmd[1] == '-login')):
(stdout, stderr) = cinder_utils.execute(process_input=... |
null | null | null | What does this function do? | def leave_transaction_management(using=None):
get_connection(using).leave_transaction_management()
| null | null | null | Leaves transaction management for a running thread. A dirty flag is carried
over to the surrounding block, as a commit will commit all changes, even
those from outside. (Commits are on connection level.) | pcsd | def leave transaction management using=None get connection using leave transaction management | 14903 | def leave_transaction_management(using=None):
get_connection(using).leave_transaction_management()
| Leaves transaction management for a running thread. A dirty flag is carried
over to the surrounding block, as a commit will commit all changes, even
those from outside. (Commits are on connection level.) | leaves transaction management for a running thread . | Question:
What does this function do?
Code:
def leave_transaction_management(using=None):
get_connection(using).leave_transaction_management()
|
null | null | null | What does this function do? | def catalog_item():
return s3_rest_controller()
| null | null | null | RESTful CRUD controller | pcsd | def catalog item return s3 rest controller | 14906 | def catalog_item():
return s3_rest_controller()
| RESTful CRUD controller | restful crud controller | Question:
What does this function do?
Code:
def catalog_item():
return s3_rest_controller()
|
null | null | null | What does this function do? | @register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def linenumbers(value, autoescape=None):
lines = value.split(u'\n')
width = unicode(len(unicode(len(lines))))
if ((not autoescape) or isinstance(value, SafeData)):
for (i, line) in enumerate(lines):
lines[i] = (((u'%0' + width) + u'd. %s') % ((... | null | null | null | Displays text with line numbers. | pcsd | @register filter is safe=True needs autoescape=True @stringfilter def linenumbers value autoescape=None lines = value split u' ' width = unicode len unicode len lines if not autoescape or isinstance value Safe Data for i line in enumerate lines lines[i] = u'%0' + width + u'd %s' % i + 1 line else for i line in enumerat... | 14910 | @register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def linenumbers(value, autoescape=None):
lines = value.split(u'\n')
width = unicode(len(unicode(len(lines))))
if ((not autoescape) or isinstance(value, SafeData)):
for (i, line) in enumerate(lines):
lines[i] = (((u'%0' + width) + u'd. %s') % ((... | Displays text with line numbers. | displays text with line numbers . | Question:
What does this function do?
Code:
@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def linenumbers(value, autoescape=None):
lines = value.split(u'\n')
width = unicode(len(unicode(len(lines))))
if ((not autoescape) or isinstance(value, SafeData)):
for (i, line) in enumerate(lines):
... |
null | null | null | What does this function do? | def definite_article(word):
return 'the'
| null | null | null | Returns the definite article for a given word. | pcsd | def definite article word return 'the' | 14917 | def definite_article(word):
return 'the'
| Returns the definite article for a given word. | returns the definite article for a given word . | Question:
What does this function do?
Code:
def definite_article(word):
return 'the'
|
null | null | null | What does this function do? | @with_setup(step_runner_environ)
def test_count_raised_exceptions_as_failing_steps():
try:
f = Feature.from_string(FEATURE8)
feature_result = f.run()
scenario_result = feature_result.scenario_results[0]
assert_equals(len(scenario_result.steps_failed), 1)
finally:
registry.clear()
| null | null | null | When a step definition raises an exception, it is marked as a failed step. | pcsd | @with setup step runner environ def test count raised exceptions as failing steps try f = Feature from string FEATURE8 feature result = f run scenario result = feature result scenario results[0] assert equals len scenario result steps failed 1 finally registry clear | 14930 | @with_setup(step_runner_environ)
def test_count_raised_exceptions_as_failing_steps():
try:
f = Feature.from_string(FEATURE8)
feature_result = f.run()
scenario_result = feature_result.scenario_results[0]
assert_equals(len(scenario_result.steps_failed), 1)
finally:
registry.clear()
| When a step definition raises an exception, it is marked as a failed step. | when a step definition raises an exception , it is marked as a failed step . | Question:
What does this function do?
Code:
@with_setup(step_runner_environ)
def test_count_raised_exceptions_as_failing_steps():
try:
f = Feature.from_string(FEATURE8)
feature_result = f.run()
scenario_result = feature_result.scenario_results[0]
assert_equals(len(scenario_result.steps_failed), 1)
finally:... |
null | null | null | What does this function do? | def _service_by_name(name):
services = _available_services()
name = name.lower()
if (name in services):
return services[name]
for service in six.itervalues(services):
if (service['file_path'].lower() == name):
return service
(basename, ext) = os.path.splitext(service['filename'])
if (basename.lower() == ... | null | null | null | Return the service info for a service by label, filename or path | pcsd | def service by name name services = available services name = name lower if name in services return services[name] for service in six itervalues services if service['file path'] lower == name return service basename ext = os path splitext service['filename'] if basename lower == name return service return False | 14936 | def _service_by_name(name):
services = _available_services()
name = name.lower()
if (name in services):
return services[name]
for service in six.itervalues(services):
if (service['file_path'].lower() == name):
return service
(basename, ext) = os.path.splitext(service['filename'])
if (basename.lower() == ... | Return the service info for a service by label, filename or path | return the service info for a service by label , filename or path | Question:
What does this function do?
Code:
def _service_by_name(name):
services = _available_services()
name = name.lower()
if (name in services):
return services[name]
for service in six.itervalues(services):
if (service['file_path'].lower() == name):
return service
(basename, ext) = os.path.splitext(... |
null | null | null | What does this function do? | def items_for_result(cl, result, form):
first = True
pk = cl.lookup_opts.pk.attname
for field_name in cl.list_display:
row_class = u''
try:
(f, attr, value) = lookup_field(field_name, result, cl.model_admin)
except ObjectDoesNotExist:
result_repr = EMPTY_CHANGELIST_VALUE
else:
if (f is None):
if... | null | null | null | Generates the actual list of data. | pcsd | def items for result cl result form first = True pk = cl lookup opts pk attname for field name in cl list display row class = u'' try f attr value = lookup field field name result cl model admin except Object Does Not Exist result repr = EMPTY CHANGELIST VALUE else if f is None if field name == u'action checkbox' row c... | 14939 | def items_for_result(cl, result, form):
first = True
pk = cl.lookup_opts.pk.attname
for field_name in cl.list_display:
row_class = u''
try:
(f, attr, value) = lookup_field(field_name, result, cl.model_admin)
except ObjectDoesNotExist:
result_repr = EMPTY_CHANGELIST_VALUE
else:
if (f is None):
if... | Generates the actual list of data. | generates the actual list of data . | Question:
What does this function do?
Code:
def items_for_result(cl, result, form):
first = True
pk = cl.lookup_opts.pk.attname
for field_name in cl.list_display:
row_class = u''
try:
(f, attr, value) = lookup_field(field_name, result, cl.model_admin)
except ObjectDoesNotExist:
result_repr = EMPTY_CHA... |
null | null | null | What does this function do? | def send_with_template(prefix, parm, test=None):
parm['from'] = cfg.email_from()
parm['date'] = get_email_date()
lst = []
path = cfg.email_dir.get_path()
if (path and os.path.exists(path)):
try:
lst = glob.glob(os.path.join(path, ('%s-*.tmpl' % prefix)))
except:
logging.error(T('Cannot find email templat... | null | null | null | Send an email using template | pcsd | def send with template prefix parm test=None parm['from'] = cfg email from parm['date'] = get email date lst = [] path = cfg email dir get path if path and os path exists path try lst = glob glob os path join path '%s-* tmpl' % prefix except logging error T 'Cannot find email templates in %s' path else path = os path j... | 14946 | def send_with_template(prefix, parm, test=None):
parm['from'] = cfg.email_from()
parm['date'] = get_email_date()
lst = []
path = cfg.email_dir.get_path()
if (path and os.path.exists(path)):
try:
lst = glob.glob(os.path.join(path, ('%s-*.tmpl' % prefix)))
except:
logging.error(T('Cannot find email templat... | Send an email using template | send an email using template | Question:
What does this function do?
Code:
def send_with_template(prefix, parm, test=None):
parm['from'] = cfg.email_from()
parm['date'] = get_email_date()
lst = []
path = cfg.email_dir.get_path()
if (path and os.path.exists(path)):
try:
lst = glob.glob(os.path.join(path, ('%s-*.tmpl' % prefix)))
except... |
null | null | null | What does this function do? | def dump_files():
for file_path in FILES_LIST:
log.info('PLS IMPLEMENT DUMP, want to dump %s', file_path)
| null | null | null | Dump all the dropped files. | pcsd | def dump files for file path in FILES LIST log info 'PLS IMPLEMENT DUMP want to dump %s' file path | 14949 | def dump_files():
for file_path in FILES_LIST:
log.info('PLS IMPLEMENT DUMP, want to dump %s', file_path)
| Dump all the dropped files. | dump all the dropped files . | Question:
What does this function do?
Code:
def dump_files():
for file_path in FILES_LIST:
log.info('PLS IMPLEMENT DUMP, want to dump %s', file_path)
|
null | null | null | What does this function do? | @login_required
def edit_media(request, media_id, media_type='image'):
(media, media_format) = _get_media_info(media_id, media_type)
check_media_permissions(media, request.user, 'change')
if (media_type == 'image'):
media_form = _init_media_form(ImageForm, request, media, ('locale', 'title'))
else:
raise Http40... | null | null | null | Edit media means only changing the description, for now. | pcsd | @login required def edit media request media id media type='image' media media format = get media info media id media type check media permissions media request user 'change' if media type == 'image' media form = init media form Image Form request media 'locale' 'title' else raise Http404 if request method == 'POST' an... | 14953 | @login_required
def edit_media(request, media_id, media_type='image'):
(media, media_format) = _get_media_info(media_id, media_type)
check_media_permissions(media, request.user, 'change')
if (media_type == 'image'):
media_form = _init_media_form(ImageForm, request, media, ('locale', 'title'))
else:
raise Http40... | Edit media means only changing the description, for now. | edit media means only changing the description , for now . | Question:
What does this function do?
Code:
@login_required
def edit_media(request, media_id, media_type='image'):
(media, media_format) = _get_media_info(media_id, media_type)
check_media_permissions(media, request.user, 'change')
if (media_type == 'image'):
media_form = _init_media_form(ImageForm, request, me... |
null | null | null | What does this function do? | def perform_push(request, obj):
return execute_locked(request, obj, _('All repositories were pushed.'), obj.do_push, request)
| null | null | null | Helper function to do the repository push. | pcsd | def perform push request obj return execute locked request obj 'All repositories were pushed ' obj do push request | 14954 | def perform_push(request, obj):
return execute_locked(request, obj, _('All repositories were pushed.'), obj.do_push, request)
| Helper function to do the repository push. | helper function to do the repository push . | Question:
What does this function do?
Code:
def perform_push(request, obj):
return execute_locked(request, obj, _('All repositories were pushed.'), obj.do_push, request)
|
null | null | null | What does this function do? | def _get_pkgng_version(jail=None, chroot=None, root=None):
cmd = (_pkg(jail, chroot, root) + ['--version'])
return __salt__['cmd.run'](cmd).strip()
| null | null | null | return the version of \'pkg\' | pcsd | def get pkgng version jail=None chroot=None root=None cmd = pkg jail chroot root + ['--version'] return salt ['cmd run'] cmd strip | 14957 | def _get_pkgng_version(jail=None, chroot=None, root=None):
cmd = (_pkg(jail, chroot, root) + ['--version'])
return __salt__['cmd.run'](cmd).strip()
| return the version of \'pkg\' | return the version of pkg | Question:
What does this function do?
Code:
def _get_pkgng_version(jail=None, chroot=None, root=None):
cmd = (_pkg(jail, chroot, root) + ['--version'])
return __salt__['cmd.run'](cmd).strip()
|
null | null | null | What does this function do? | @typeof_impl.register(type)
def typeof_type(val, c):
if issubclass(val, BaseException):
return types.ExceptionClass(val)
if (issubclass(val, tuple) and hasattr(val, '_asdict')):
return types.NamedTupleClass(val)
| null | null | null | Type various specific Python types. | pcsd | @typeof impl register type def typeof type val c if issubclass val Base Exception return types Exception Class val if issubclass val tuple and hasattr val ' asdict' return types Named Tuple Class val | 14968 | @typeof_impl.register(type)
def typeof_type(val, c):
if issubclass(val, BaseException):
return types.ExceptionClass(val)
if (issubclass(val, tuple) and hasattr(val, '_asdict')):
return types.NamedTupleClass(val)
| Type various specific Python types. | type various specific python types . | Question:
What does this function do?
Code:
@typeof_impl.register(type)
def typeof_type(val, c):
if issubclass(val, BaseException):
return types.ExceptionClass(val)
if (issubclass(val, tuple) and hasattr(val, '_asdict')):
return types.NamedTupleClass(val)
|
null | null | null | What does this function do? | def MGF1(mgfSeed, maskLen, hash):
T = b('')
for counter in xrange(ceil_div(maskLen, hash.digest_size)):
c = long_to_bytes(counter, 4)
hobj = hash.new()
hobj.update((mgfSeed + c))
T = (T + hobj.digest())
assert (len(T) >= maskLen)
return T[:maskLen]
| null | null | null | Mask Generation Function, described in B.2.1 | pcsd | def MGF1 mgf Seed mask Len hash T = b '' for counter in xrange ceil div mask Len hash digest size c = long to bytes counter 4 hobj = hash new hobj update mgf Seed + c T = T + hobj digest assert len T >= mask Len return T[ mask Len] | 14976 | def MGF1(mgfSeed, maskLen, hash):
T = b('')
for counter in xrange(ceil_div(maskLen, hash.digest_size)):
c = long_to_bytes(counter, 4)
hobj = hash.new()
hobj.update((mgfSeed + c))
T = (T + hobj.digest())
assert (len(T) >= maskLen)
return T[:maskLen]
| Mask Generation Function, described in B.2.1 | mask generation function , described in b . 2 . 1 | Question:
What does this function do?
Code:
def MGF1(mgfSeed, maskLen, hash):
T = b('')
for counter in xrange(ceil_div(maskLen, hash.digest_size)):
c = long_to_bytes(counter, 4)
hobj = hash.new()
hobj.update((mgfSeed + c))
T = (T + hobj.digest())
assert (len(T) >= maskLen)
return T[:maskLen]
|
null | null | null | What does this function do? | @then(u'we see record updated')
def step_see_record_updated(context):
_expect_exact(context, u'UPDATE 1', timeout=2)
| null | null | null | Wait to see update output. | pcsd | @then u'we see record updated' def step see record updated context expect exact context u'UPDATE 1' timeout=2 | 14980 | @then(u'we see record updated')
def step_see_record_updated(context):
_expect_exact(context, u'UPDATE 1', timeout=2)
| Wait to see update output. | wait to see update output . | Question:
What does this function do?
Code:
@then(u'we see record updated')
def step_see_record_updated(context):
_expect_exact(context, u'UPDATE 1', timeout=2)
|
null | null | null | What does this function do? | def handle_var(value, context):
if (isinstance(value, FilterExpression) or isinstance(value, Variable)):
return value.resolve(context)
stringval = QUOTED_STRING.search(value)
if stringval:
return stringval.group(u'noquotes')
try:
return Variable(value).resolve(context)
except VariableDoesNotExist:
return v... | null | null | null | Handle template tag variable | pcsd | def handle var value context if isinstance value Filter Expression or isinstance value Variable return value resolve context stringval = QUOTED STRING search value if stringval return stringval group u'noquotes' try return Variable value resolve context except Variable Does Not Exist return value | 14981 | def handle_var(value, context):
if (isinstance(value, FilterExpression) or isinstance(value, Variable)):
return value.resolve(context)
stringval = QUOTED_STRING.search(value)
if stringval:
return stringval.group(u'noquotes')
try:
return Variable(value).resolve(context)
except VariableDoesNotExist:
return v... | Handle template tag variable | handle template tag variable | Question:
What does this function do?
Code:
def handle_var(value, context):
if (isinstance(value, FilterExpression) or isinstance(value, Variable)):
return value.resolve(context)
stringval = QUOTED_STRING.search(value)
if stringval:
return stringval.group(u'noquotes')
try:
return Variable(value).resolve(co... |
null | null | null | What does this function do? | def primarykeys(conn, table):
rows = query(conn, "\n SELECT COLS.COLUMN_NAME\n FROM USER_CONSTRAINTS CONS, ALL_CONS_COLUMNS COLS\n WHERE COLS.TABLE_NAME = :t\n AND CONS.CONSTRAINT_TYPE = 'P'\n AND CONS.OWNER = COLS.OWNER\n AND CONS.CONSTRAINT_NAME = COLS.CONSTRAINT... | null | null | null | Find primary keys | pcsd | def primarykeys conn table rows = query conn " SELECT COLS COLUMN NAME FROM USER CONSTRAINTS CONS ALL CONS COLUMNS COLS WHERE COLS TABLE NAME = t AND CONS CONSTRAINT TYPE = 'P' AND CONS OWNER = COLS OWNER AND CONS CONSTRAINT NAME = COLS CONSTRAINT NAME " table return [row['COLUMN NAME'] for row in rows] | 14998 | def primarykeys(conn, table):
rows = query(conn, "\n SELECT COLS.COLUMN_NAME\n FROM USER_CONSTRAINTS CONS, ALL_CONS_COLUMNS COLS\n WHERE COLS.TABLE_NAME = :t\n AND CONS.CONSTRAINT_TYPE = 'P'\n AND CONS.OWNER = COLS.OWNER\n AND CONS.CONSTRAINT_NAME = COLS.CONSTRAINT... | Find primary keys | find primary keys | Question:
What does this function do?
Code:
def primarykeys(conn, table):
rows = query(conn, "\n SELECT COLS.COLUMN_NAME\n FROM USER_CONSTRAINTS CONS, ALL_CONS_COLUMNS COLS\n WHERE COLS.TABLE_NAME = :t\n AND CONS.CONSTRAINT_TYPE = 'P'\n AND CONS.OWNER = COLS.OWNER\n ... |
null | null | null | What does this function do? | def sync_rheader(r, tabs=[]):
if (r.representation == 'html'):
if (r.tablename == 'sync_repository'):
T = current.T
repository = r.record
if (r.component and (r.component_name == 'log') and (not r.component_id)):
purge_log = A(T('Remove all log entries'), _href=r.url(method='delete'))
else:
purge... | null | null | null | Synchronization resource headers | pcsd | def sync rheader r tabs=[] if r representation == 'html' if r tablename == 'sync repository' T = current T repository = r record if r component and r component name == 'log' and not r component id purge log = A T 'Remove all log entries' href=r url method='delete' else purge log = '' if repository if repository url or ... | 15009 | def sync_rheader(r, tabs=[]):
if (r.representation == 'html'):
if (r.tablename == 'sync_repository'):
T = current.T
repository = r.record
if (r.component and (r.component_name == 'log') and (not r.component_id)):
purge_log = A(T('Remove all log entries'), _href=r.url(method='delete'))
else:
purge... | Synchronization resource headers | synchronization resource headers | Question:
What does this function do?
Code:
def sync_rheader(r, tabs=[]):
if (r.representation == 'html'):
if (r.tablename == 'sync_repository'):
T = current.T
repository = r.record
if (r.component and (r.component_name == 'log') and (not r.component_id)):
purge_log = A(T('Remove all log entries'), _... |
null | null | null | What does this function do? | def var_to_list(var):
if isinstance(var, list):
return var
if (not var):
return []
return [var]
| null | null | null | change the var to be a list. | pcsd | def var to list var if isinstance var list return var if not var return [] return [var] | 15013 | def var_to_list(var):
if isinstance(var, list):
return var
if (not var):
return []
return [var]
| change the var to be a list. | change the var to be a list . | Question:
What does this function do?
Code:
def var_to_list(var):
if isinstance(var, list):
return var
if (not var):
return []
return [var]
|
null | null | null | What does this function do? | @contextfilter
def number_format(context, value):
value = str(value)
negative = False
addzero = None
if (value[0] == '-'):
value = value[1:]
negative = True
if ('.' in value):
point = value.rindex('.')
if (point == (len(value) - 2)):
addzero = True
else:
point = len(value)
while (point < (len(value)... | null | null | null | Enforces 2 decimal places after a number if only one is given (adds a zero)
also formats comma separators every 3rd digit before decimal place. | pcsd | @contextfilter def number format context value value = str value negative = False addzero = None if value[0] == '-' value = value[1 ] negative = True if ' ' in value point = value rindex ' ' if point == len value - 2 addzero = True else point = len value while point < len value - 3 if value[ len value - 1 ] == '0' valu... | 15024 | @contextfilter
def number_format(context, value):
value = str(value)
negative = False
addzero = None
if (value[0] == '-'):
value = value[1:]
negative = True
if ('.' in value):
point = value.rindex('.')
if (point == (len(value) - 2)):
addzero = True
else:
point = len(value)
while (point < (len(value)... | Enforces 2 decimal places after a number if only one is given (adds a zero)
also formats comma separators every 3rd digit before decimal place. | enforces 2 decimal places after a number if only one is given also formats comma separators every 3rd digit before decimal place . | Question:
What does this function do?
Code:
@contextfilter
def number_format(context, value):
value = str(value)
negative = False
addzero = None
if (value[0] == '-'):
value = value[1:]
negative = True
if ('.' in value):
point = value.rindex('.')
if (point == (len(value) - 2)):
addzero = True
else:
... |
null | null | null | What does this function do? | def send_email_after_account_create(form):
send_email(to=form['email'], action=USER_REGISTER, subject=MAILS[USER_REGISTER]['subject'].format(app_name=get_settings()['app_name']), html=MAILS[USER_REGISTER]['message'].format(email=form['email']))
| null | null | null | Send email after account create | pcsd | def send email after account create form send email to=form['email'] action=USER REGISTER subject=MAILS[USER REGISTER]['subject'] format app name=get settings ['app name'] html=MAILS[USER REGISTER]['message'] format email=form['email'] | 15050 | def send_email_after_account_create(form):
send_email(to=form['email'], action=USER_REGISTER, subject=MAILS[USER_REGISTER]['subject'].format(app_name=get_settings()['app_name']), html=MAILS[USER_REGISTER]['message'].format(email=form['email']))
| Send email after account create | send email after account create | Question:
What does this function do?
Code:
def send_email_after_account_create(form):
send_email(to=form['email'], action=USER_REGISTER, subject=MAILS[USER_REGISTER]['subject'].format(app_name=get_settings()['app_name']), html=MAILS[USER_REGISTER]['message'].format(email=form['email']))
|
null | null | null | What does this function do? | def _service_is_upstart(name):
return (HAS_UPSTART and os.path.exists('/etc/init/{0}.conf'.format(name)))
| null | null | null | Return True if the service is an upstart service, otherwise return False. | pcsd | def service is upstart name return HAS UPSTART and os path exists '/etc/init/{0} conf' format name | 15051 | def _service_is_upstart(name):
return (HAS_UPSTART and os.path.exists('/etc/init/{0}.conf'.format(name)))
| Return True if the service is an upstart service, otherwise return False. | return true if the service is an upstart service , otherwise return false . | Question:
What does this function do?
Code:
def _service_is_upstart(name):
return (HAS_UPSTART and os.path.exists('/etc/init/{0}.conf'.format(name)))
|
null | null | null | What does this function do? | def detect_text_cloud_storage(uri):
vision_client = vision.Client()
image = vision_client.image(source_uri=uri)
texts = image.detect_text()
print 'Texts:'
for text in texts:
print text.description
| null | null | null | Detects text in the file located in Google Cloud Storage. | pcsd | def detect text cloud storage uri vision client = vision Client image = vision client image source uri=uri texts = image detect text print 'Texts ' for text in texts print text description | 15055 | def detect_text_cloud_storage(uri):
vision_client = vision.Client()
image = vision_client.image(source_uri=uri)
texts = image.detect_text()
print 'Texts:'
for text in texts:
print text.description
| Detects text in the file located in Google Cloud Storage. | detects text in the file located in google cloud storage . | Question:
What does this function do?
Code:
def detect_text_cloud_storage(uri):
vision_client = vision.Client()
image = vision_client.image(source_uri=uri)
texts = image.detect_text()
print 'Texts:'
for text in texts:
print text.description
|
null | null | null | What does this function do? | def unescape(text):
if isinstance(text, str):
text = text.decode('utf8', 'ignore')
out = text.replace(u' ', u' ')
def replchar(m):
num = m.group(1)
return unichr(int(num))
out = re.sub(u'&#(\\d+);', replchar, out)
return out
| null | null | null | Resolves &#xxx; HTML entities (and some others). | pcsd | def unescape text if isinstance text str text = text decode 'utf8' 'ignore' out = text replace u'  ' u' ' def replchar m num = m group 1 return unichr int num out = re sub u'&# \\d+ ' replchar out return out | 15057 | def unescape(text):
if isinstance(text, str):
text = text.decode('utf8', 'ignore')
out = text.replace(u' ', u' ')
def replchar(m):
num = m.group(1)
return unichr(int(num))
out = re.sub(u'&#(\\d+);', replchar, out)
return out
| Resolves &#xxx; HTML entities (and some others). | resolves & # xxx ; html entities . | Question:
What does this function do?
Code:
def unescape(text):
if isinstance(text, str):
text = text.decode('utf8', 'ignore')
out = text.replace(u' ', u' ')
def replchar(m):
num = m.group(1)
return unichr(int(num))
out = re.sub(u'&#(\\d+);', replchar, out)
return out
|
null | null | null | What does this function do? | def get_stack_events(cfn, stack_name):
ret = {'events': [], 'log': []}
try:
events = cfn.describe_stack_events(StackName=stack_name)
except (botocore.exceptions.ValidationError, botocore.exceptions.ClientError) as err:
error_msg = boto_exception(err)
if ('does not exist' in error_msg):
ret['log'].append('St... | null | null | null | This event data was never correct, it worked as a side effect. So the v2.3 format is different. | pcsd | def get stack events cfn stack name ret = {'events' [] 'log' []} try events = cfn describe stack events Stack Name=stack name except botocore exceptions Validation Error botocore exceptions Client Error as err error msg = boto exception err if 'does not exist' in error msg ret['log'] append 'Stack does not exist ' retu... | 15070 | def get_stack_events(cfn, stack_name):
ret = {'events': [], 'log': []}
try:
events = cfn.describe_stack_events(StackName=stack_name)
except (botocore.exceptions.ValidationError, botocore.exceptions.ClientError) as err:
error_msg = boto_exception(err)
if ('does not exist' in error_msg):
ret['log'].append('St... | This event data was never correct, it worked as a side effect. So the v2.3 format is different. | this event data was never correct , it worked as a side effect . | Question:
What does this function do?
Code:
def get_stack_events(cfn, stack_name):
ret = {'events': [], 'log': []}
try:
events = cfn.describe_stack_events(StackName=stack_name)
except (botocore.exceptions.ValidationError, botocore.exceptions.ClientError) as err:
error_msg = boto_exception(err)
if ('does not... |
null | null | null | What does this function do? | @pytest.mark.django_db
def test_toggle_quality_check(rf, admin):
qc_filter = dict(false_positive=False, unit__state=TRANSLATED, unit__store__translation_project__project__disabled=False)
qc = QualityCheck.objects.filter(**qc_filter).first()
unit = qc.unit
data = 'mute='
request = create_api_request(rf, method='pos... | null | null | null | Tests the view that mutes/unmutes quality checks. | pcsd | @pytest mark django db def test toggle quality check rf admin qc filter = dict false positive=False unit state=TRANSLATED unit store translation project project disabled=False qc = Quality Check objects filter **qc filter first unit = qc unit data = 'mute=' request = create api request rf method='post' user=admin data=... | 15075 | @pytest.mark.django_db
def test_toggle_quality_check(rf, admin):
qc_filter = dict(false_positive=False, unit__state=TRANSLATED, unit__store__translation_project__project__disabled=False)
qc = QualityCheck.objects.filter(**qc_filter).first()
unit = qc.unit
data = 'mute='
request = create_api_request(rf, method='pos... | Tests the view that mutes/unmutes quality checks. | tests the view that mutes / unmutes quality checks . | Question:
What does this function do?
Code:
@pytest.mark.django_db
def test_toggle_quality_check(rf, admin):
qc_filter = dict(false_positive=False, unit__state=TRANSLATED, unit__store__translation_project__project__disabled=False)
qc = QualityCheck.objects.filter(**qc_filter).first()
unit = qc.unit
data = 'mute=... |
null | null | null | What does this function do? | def activate(language):
if (isinstance(language, basestring) and (language == 'no')):
warnings.warn("The use of the language code 'no' is deprecated. Please use the 'nb' translation instead.", DeprecationWarning)
_active.value = translation(language)
| null | null | null | Fetches the translation object for a given tuple of application name and
language and installs it as the current translation object for the current
thread. | pcsd | def activate language if isinstance language basestring and language == 'no' warnings warn "The use of the language code 'no' is deprecated Please use the 'nb' translation instead " Deprecation Warning active value = translation language | 15083 | def activate(language):
if (isinstance(language, basestring) and (language == 'no')):
warnings.warn("The use of the language code 'no' is deprecated. Please use the 'nb' translation instead.", DeprecationWarning)
_active.value = translation(language)
| Fetches the translation object for a given tuple of application name and
language and installs it as the current translation object for the current
thread. | fetches the translation object for a given tuple of application name and language and installs it as the current translation object for the current thread . | Question:
What does this function do?
Code:
def activate(language):
if (isinstance(language, basestring) and (language == 'no')):
warnings.warn("The use of the language code 'no' is deprecated. Please use the 'nb' translation instead.", DeprecationWarning)
_active.value = translation(language)
|
null | null | null | What does this function do? | def get_metrics(params):
global METRICS
if ((time.time() - METRICS['time']) > METRICS_CACHE_MAX):
new_metrics = {}
units = {}
command = [params['timeout_bin'], '3', params['ipmitool_bin'], '-H', params['ipmi_ip'], '-U', params['username'], '-P', params['password'], '-L', params['level'], 'sensor']
p = subproc... | null | null | null | Return all metrics | pcsd | def get metrics params global METRICS if time time - METRICS['time'] > METRICS CACHE MAX new metrics = {} units = {} command = [params['timeout bin'] '3' params['ipmitool bin'] '-H' params['ipmi ip'] '-U' params['username'] '-P' params['password'] '-L' params['level'] 'sensor'] p = subprocess Popen command stdout=subpr... | 15085 | def get_metrics(params):
global METRICS
if ((time.time() - METRICS['time']) > METRICS_CACHE_MAX):
new_metrics = {}
units = {}
command = [params['timeout_bin'], '3', params['ipmitool_bin'], '-H', params['ipmi_ip'], '-U', params['username'], '-P', params['password'], '-L', params['level'], 'sensor']
p = subproc... | Return all metrics | return all metrics | Question:
What does this function do?
Code:
def get_metrics(params):
global METRICS
if ((time.time() - METRICS['time']) > METRICS_CACHE_MAX):
new_metrics = {}
units = {}
command = [params['timeout_bin'], '3', params['ipmitool_bin'], '-H', params['ipmi_ip'], '-U', params['username'], '-P', params['password'],... |
null | null | null | What does this function do? | def own_metadata(module):
return module.get_explicitly_set_fields_by_scope(Scope.settings)
| null | null | null | Return a JSON-friendly dictionary that contains only non-inherited field
keys, mapped to their serialized values | pcsd | def own metadata module return module get explicitly set fields by scope Scope settings | 15086 | def own_metadata(module):
return module.get_explicitly_set_fields_by_scope(Scope.settings)
| Return a JSON-friendly dictionary that contains only non-inherited field
keys, mapped to their serialized values | return a json - friendly dictionary that contains only non - inherited field keys , mapped to their serialized values | Question:
What does this function do?
Code:
def own_metadata(module):
return module.get_explicitly_set_fields_by_scope(Scope.settings)
|
null | null | null | What does this function do? | def directional_variance_i(x_i, w):
return (dot(x_i, direction(w)) ** 2)
| null | null | null | the variance of the row x_i in the direction w | pcsd | def directional variance i x i w return dot x i direction w ** 2 | 15088 | def directional_variance_i(x_i, w):
return (dot(x_i, direction(w)) ** 2)
| the variance of the row x_i in the direction w | the variance of the row x _ i in the direction w | Question:
What does this function do?
Code:
def directional_variance_i(x_i, w):
return (dot(x_i, direction(w)) ** 2)
|
null | null | null | What does this function do? | def bygroups(*args):
def callback(lexer, match, ctx=None):
for (i, action) in enumerate(args):
if (action is None):
continue
elif (type(action) is _TokenType):
data = match.group((i + 1))
if data:
(yield (match.start((i + 1)), action, data))
else:
data = match.group((i + 1))
if (dat... | null | null | null | Callback that yields multiple actions for each group in the match. | pcsd | def bygroups *args def callback lexer match ctx=None for i action in enumerate args if action is None continue elif type action is Token Type data = match group i + 1 if data yield match start i + 1 action data else data = match group i + 1 if data is not None if ctx ctx pos = match start i + 1 for item in action lexer... | 15098 | def bygroups(*args):
def callback(lexer, match, ctx=None):
for (i, action) in enumerate(args):
if (action is None):
continue
elif (type(action) is _TokenType):
data = match.group((i + 1))
if data:
(yield (match.start((i + 1)), action, data))
else:
data = match.group((i + 1))
if (dat... | Callback that yields multiple actions for each group in the match. | callback that yields multiple actions for each group in the match . | Question:
What does this function do?
Code:
def bygroups(*args):
def callback(lexer, match, ctx=None):
for (i, action) in enumerate(args):
if (action is None):
continue
elif (type(action) is _TokenType):
data = match.group((i + 1))
if data:
(yield (match.start((i + 1)), action, data))
el... |
null | null | null | What does this function do? | def _tupleize(d):
return [(key, value) for (key, value) in d.items()]
| null | null | null | Convert a dict of options to the 2-tuple format. | pcsd | def tupleize d return [ key value for key value in d items ] | 15104 | def _tupleize(d):
return [(key, value) for (key, value) in d.items()]
| Convert a dict of options to the 2-tuple format. | convert a dict of options to the 2 - tuple format . | Question:
What does this function do?
Code:
def _tupleize(d):
return [(key, value) for (key, value) in d.items()]
|
null | null | null | What does this function do? | def mod_watch(name, user=None, **kwargs):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
if (kwargs['sfun'] == 'mounted'):
out = __salt__['mount.remount'](name, kwargs['device'], False, kwargs['fstype'], kwargs['opts'], user=user)
if out:
ret['comment'] = '{0} remounted'.format(name)
else... | null | null | null | The mounted watcher, called to invoke the watch command.
name
The name of the mount point | pcsd | def mod watch name user=None **kwargs ret = {'name' name 'changes' {} 'result' True 'comment' ''} if kwargs['sfun'] == 'mounted' out = salt ['mount remount'] name kwargs['device'] False kwargs['fstype'] kwargs['opts'] user=user if out ret['comment'] = '{0} remounted' format name else ret['result'] = False ret['comment'... | 15105 | def mod_watch(name, user=None, **kwargs):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
if (kwargs['sfun'] == 'mounted'):
out = __salt__['mount.remount'](name, kwargs['device'], False, kwargs['fstype'], kwargs['opts'], user=user)
if out:
ret['comment'] = '{0} remounted'.format(name)
else... | The mounted watcher, called to invoke the watch command.
name
The name of the mount point | the mounted watcher , called to invoke the watch command . | Question:
What does this function do?
Code:
def mod_watch(name, user=None, **kwargs):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
if (kwargs['sfun'] == 'mounted'):
out = __salt__['mount.remount'](name, kwargs['device'], False, kwargs['fstype'], kwargs['opts'], user=user)
if out:
ret['... |
null | null | null | What does this function do? | def getInsetPointsByInsetLoop(insetLoop, inside, loops, radius):
insetPointsByInsetLoop = []
for pointIndex in xrange(len(insetLoop)):
pointBegin = insetLoop[(((pointIndex + len(insetLoop)) - 1) % len(insetLoop))]
pointCenter = insetLoop[pointIndex]
pointEnd = insetLoop[((pointIndex + 1) % len(insetLoop))]
if... | null | null | null | Get the inset points of the inset loop inside the loops. | pcsd | def get Inset Points By Inset Loop inset Loop inside loops radius inset Points By Inset Loop = [] for point Index in xrange len inset Loop point Begin = inset Loop[ point Index + len inset Loop - 1 % len inset Loop ] point Center = inset Loop[point Index] point End = inset Loop[ point Index + 1 % len inset Loop ] if ge... | 15106 | def getInsetPointsByInsetLoop(insetLoop, inside, loops, radius):
insetPointsByInsetLoop = []
for pointIndex in xrange(len(insetLoop)):
pointBegin = insetLoop[(((pointIndex + len(insetLoop)) - 1) % len(insetLoop))]
pointCenter = insetLoop[pointIndex]
pointEnd = insetLoop[((pointIndex + 1) % len(insetLoop))]
if... | Get the inset points of the inset loop inside the loops. | get the inset points of the inset loop inside the loops . | Question:
What does this function do?
Code:
def getInsetPointsByInsetLoop(insetLoop, inside, loops, radius):
insetPointsByInsetLoop = []
for pointIndex in xrange(len(insetLoop)):
pointBegin = insetLoop[(((pointIndex + len(insetLoop)) - 1) % len(insetLoop))]
pointCenter = insetLoop[pointIndex]
pointEnd = inse... |
null | null | null | What does this function do? | def add_translation(key, translation):
if (not hasattr(_to_save, 'translations')):
_to_save.translations = {}
_to_save.translations.setdefault(key, [])
_to_save.translations[key].append(translation)
| null | null | null | Queue a translation that needs to be saved for a particular object. To
generate the key, call make_key. | pcsd | def add translation key translation if not hasattr to save 'translations' to save translations = {} to save translations setdefault key [] to save translations[key] append translation | 15108 | def add_translation(key, translation):
if (not hasattr(_to_save, 'translations')):
_to_save.translations = {}
_to_save.translations.setdefault(key, [])
_to_save.translations[key].append(translation)
| Queue a translation that needs to be saved for a particular object. To
generate the key, call make_key. | queue a translation that needs to be saved for a particular object . | Question:
What does this function do?
Code:
def add_translation(key, translation):
if (not hasattr(_to_save, 'translations')):
_to_save.translations = {}
_to_save.translations.setdefault(key, [])
_to_save.translations[key].append(translation)
|
null | null | null | What does this function do? | def technical_404_response(request, exception):
try:
tried = exception.args[0][u'tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried):
return empty_urlconf(request)
urlconf = getattr(request, u'urlconf', settings.ROOT_URLCONF)
if isinstance(urlconf, types.ModuleType):
urlcon... | null | null | null | Create a technical 404 error response. The exception should be the Http404. | pcsd | def technical 404 response request exception try tried = exception args[0][u'tried'] except Index Error Type Error Key Error tried = [] else if not tried return empty urlconf request urlconf = getattr request u'urlconf' settings ROOT URLCONF if isinstance urlconf types Module Type urlconf = urlconf name t = Template TE... | 15118 | def technical_404_response(request, exception):
try:
tried = exception.args[0][u'tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried):
return empty_urlconf(request)
urlconf = getattr(request, u'urlconf', settings.ROOT_URLCONF)
if isinstance(urlconf, types.ModuleType):
urlcon... | Create a technical 404 error response. The exception should be the Http404. | create a technical 404 error response . | Question:
What does this function do?
Code:
def technical_404_response(request, exception):
try:
tried = exception.args[0][u'tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried):
return empty_urlconf(request)
urlconf = getattr(request, u'urlconf', settings.ROOT_URLCONF)
if ... |
null | null | null | What does this function do? | def make_image_dict(image):
def _fetch_attrs(d, attrs):
return {a: d[a] for a in attrs if (a in d.keys())}
properties = {p['name']: p['value'] for p in image['properties'] if (not p['deleted'])}
image_dict = _fetch_attrs(image, glance.db.IMAGE_ATTRS)
image_dict['properties'] = properties
_limit_locations(image_d... | null | null | null | Create a dict representation of an image which we can use to
serialize the image. | pcsd | def make image dict image def fetch attrs d attrs return {a d[a] for a in attrs if a in d keys } properties = {p['name'] p['value'] for p in image['properties'] if not p['deleted'] } image dict = fetch attrs image glance db IMAGE ATTRS image dict['properties'] = properties limit locations image dict return image dict | 15121 | def make_image_dict(image):
def _fetch_attrs(d, attrs):
return {a: d[a] for a in attrs if (a in d.keys())}
properties = {p['name']: p['value'] for p in image['properties'] if (not p['deleted'])}
image_dict = _fetch_attrs(image, glance.db.IMAGE_ATTRS)
image_dict['properties'] = properties
_limit_locations(image_d... | Create a dict representation of an image which we can use to
serialize the image. | create a dict representation of an image which we can use to serialize the image . | Question:
What does this function do?
Code:
def make_image_dict(image):
def _fetch_attrs(d, attrs):
return {a: d[a] for a in attrs if (a in d.keys())}
properties = {p['name']: p['value'] for p in image['properties'] if (not p['deleted'])}
image_dict = _fetch_attrs(image, glance.db.IMAGE_ATTRS)
image_dict['prop... |
null | null | null | What does this function do? | @image_comparison(baseline_images=[u'legend_auto1'], remove_text=True)
def test_legend_auto1():
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(100)
ax.plot(x, (50 - x), u'o', label=u'y=1')
ax.plot(x, (x - 50), u'o', label=u'y=-1')
ax.legend(loc=0)
| null | null | null | Test automatic legend placement | pcsd | @image comparison baseline images=[u'legend auto1'] remove text=True def test legend auto1 fig = plt figure ax = fig add subplot 111 x = np arange 100 ax plot x 50 - x u'o' label=u'y=1' ax plot x x - 50 u'o' label=u'y=-1' ax legend loc=0 | 15123 | @image_comparison(baseline_images=[u'legend_auto1'], remove_text=True)
def test_legend_auto1():
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(100)
ax.plot(x, (50 - x), u'o', label=u'y=1')
ax.plot(x, (x - 50), u'o', label=u'y=-1')
ax.legend(loc=0)
| Test automatic legend placement | test automatic legend placement | Question:
What does this function do?
Code:
@image_comparison(baseline_images=[u'legend_auto1'], remove_text=True)
def test_legend_auto1():
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(100)
ax.plot(x, (50 - x), u'o', label=u'y=1')
ax.plot(x, (x - 50), u'o', label=u'y=-1')
ax.legend(loc=0)
|
null | null | null | What does this function do? | def getChainTextFromProcedures(fileName, procedures, text):
lastProcedureTime = time.time()
for procedure in procedures:
craftModule = getCraftModule(procedure)
if (craftModule != None):
text = craftModule.getCraftedText(fileName, text)
if gcodec.isProcedureDone(text, procedure):
print ('%s procedure to... | null | null | null | Get a crafted shape file from a list of procedures. | pcsd | def get Chain Text From Procedures file Name procedures text last Procedure Time = time time for procedure in procedures craft Module = get Craft Module procedure if craft Module != None text = craft Module get Crafted Text file Name text if gcodec is Procedure Done text procedure print '%s procedure took %s ' % proced... | 15127 | def getChainTextFromProcedures(fileName, procedures, text):
lastProcedureTime = time.time()
for procedure in procedures:
craftModule = getCraftModule(procedure)
if (craftModule != None):
text = craftModule.getCraftedText(fileName, text)
if gcodec.isProcedureDone(text, procedure):
print ('%s procedure to... | Get a crafted shape file from a list of procedures. | get a crafted shape file from a list of procedures . | Question:
What does this function do?
Code:
def getChainTextFromProcedures(fileName, procedures, text):
lastProcedureTime = time.time()
for procedure in procedures:
craftModule = getCraftModule(procedure)
if (craftModule != None):
text = craftModule.getCraftedText(fileName, text)
if gcodec.isProcedureDon... |
null | null | null | What does this function do? | def byte_to_int(b):
if (sys.version_info >= (3, 0)):
return b
return ord(b)
| null | null | null | Given an element in a binary buffer, return its integer value | pcsd | def byte to int b if sys version info >= 3 0 return b return ord b | 15128 | def byte_to_int(b):
if (sys.version_info >= (3, 0)):
return b
return ord(b)
| Given an element in a binary buffer, return its integer value | given an element in a binary buffer , return its integer value | Question:
What does this function do?
Code:
def byte_to_int(b):
if (sys.version_info >= (3, 0)):
return b
return ord(b)
|
null | null | null | What does this function do? | @register.filter(is_safe=True)
@stringfilter
def truncatechars(value, arg):
try:
length = int(arg)
except ValueError:
return value
return Truncator(value).chars(length)
| null | null | null | Truncates a string after a certain number of characters.
Argument: Number of characters to truncate after. | pcsd | @register filter is safe=True @stringfilter def truncatechars value arg try length = int arg except Value Error return value return Truncator value chars length | 15131 | @register.filter(is_safe=True)
@stringfilter
def truncatechars(value, arg):
try:
length = int(arg)
except ValueError:
return value
return Truncator(value).chars(length)
| Truncates a string after a certain number of characters.
Argument: Number of characters to truncate after. | truncates a string after a certain number of characters . | Question:
What does this function do?
Code:
@register.filter(is_safe=True)
@stringfilter
def truncatechars(value, arg):
try:
length = int(arg)
except ValueError:
return value
return Truncator(value).chars(length)
|
null | null | null | What does this function do? | def _merge_aa2re(aa1, aa2, shift_val, aa2re, reid):
def get_aa_from_codonre(re_aa):
aas = []
m = 0
for i in re_aa:
if (i == '['):
m = (-1)
aas.append('')
elif (i == ']'):
m = 0
continue
elif (m == (-1)):
aas[(-1)] = (aas[(-1)] + i)
elif (m == 0):
aas.append(i)
return aas
sc... | null | null | null | Function to merge two amino acids based on detected frame shift
value. | pcsd | def merge aa2re aa1 aa2 shift val aa2re reid def get aa from codonre re aa aas = [] m = 0 for i in re aa if i == '[' m = -1 aas append '' elif i == ']' m = 0 continue elif m == -1 aas[ -1 ] = aas[ -1 ] + i elif m == 0 aas append i return aas scodon = list map get aa from codonre aa2re[aa1] aa2re[aa2] if shift val == 1 ... | 15134 | def _merge_aa2re(aa1, aa2, shift_val, aa2re, reid):
def get_aa_from_codonre(re_aa):
aas = []
m = 0
for i in re_aa:
if (i == '['):
m = (-1)
aas.append('')
elif (i == ']'):
m = 0
continue
elif (m == (-1)):
aas[(-1)] = (aas[(-1)] + i)
elif (m == 0):
aas.append(i)
return aas
sc... | Function to merge two amino acids based on detected frame shift
value. | function to merge two amino acids based on detected frame shift value . | Question:
What does this function do?
Code:
def _merge_aa2re(aa1, aa2, shift_val, aa2re, reid):
def get_aa_from_codonre(re_aa):
aas = []
m = 0
for i in re_aa:
if (i == '['):
m = (-1)
aas.append('')
elif (i == ']'):
m = 0
continue
elif (m == (-1)):
aas[(-1)] = (aas[(-1)] + i)
el... |
null | null | null | What does this function do? | @pytest.fixture
def topic_moderator(forum, moderator_user):
topic = Topic(title='Test Topic Moderator')
post = Post(content='Test Content Moderator')
return topic.save(forum=forum, user=moderator_user, post=post)
| null | null | null | A topic by a user with moderator permissions. | pcsd | @pytest fixture def topic moderator forum moderator user topic = Topic title='Test Topic Moderator' post = Post content='Test Content Moderator' return topic save forum=forum user=moderator user post=post | 15138 | @pytest.fixture
def topic_moderator(forum, moderator_user):
topic = Topic(title='Test Topic Moderator')
post = Post(content='Test Content Moderator')
return topic.save(forum=forum, user=moderator_user, post=post)
| A topic by a user with moderator permissions. | a topic by a user with moderator permissions . | Question:
What does this function do?
Code:
@pytest.fixture
def topic_moderator(forum, moderator_user):
topic = Topic(title='Test Topic Moderator')
post = Post(content='Test Content Moderator')
return topic.save(forum=forum, user=moderator_user, post=post)
|
null | null | null | What does this function do? | def store_token(mx_id, token):
AUTH_TOKENS[mx_id] = token
with open(SESSION_FILE, 'w') as handle:
handle.write(json.dumps(AUTH_TOKENS))
| null | null | null | Store authentication token to session and persistent storage. | pcsd | def store token mx id token AUTH TOKENS[mx id] = token with open SESSION FILE 'w' as handle handle write json dumps AUTH TOKENS | 15139 | def store_token(mx_id, token):
AUTH_TOKENS[mx_id] = token
with open(SESSION_FILE, 'w') as handle:
handle.write(json.dumps(AUTH_TOKENS))
| Store authentication token to session and persistent storage. | store authentication token to session and persistent storage . | Question:
What does this function do?
Code:
def store_token(mx_id, token):
AUTH_TOKENS[mx_id] = token
with open(SESSION_FILE, 'w') as handle:
handle.write(json.dumps(AUTH_TOKENS))
|
null | null | null | What does this function do? | def ModularIntegerFactory(_mod, _dom, _sym, parent):
try:
_mod = _dom.convert(_mod)
except CoercionFailed:
ok = False
else:
ok = True
if ((not ok) or (_mod < 1)):
raise ValueError(('modulus must be a positive integer, got %s' % _mod))
key = (_mod, _dom, _sym)
try:
cls = _modular_integer_cache[key]
exce... | null | null | null | Create custom class for specific integer modulus. | pcsd | def Modular Integer Factory mod dom sym parent try mod = dom convert mod except Coercion Failed ok = False else ok = True if not ok or mod < 1 raise Value Error 'modulus must be a positive integer got %s' % mod key = mod dom sym try cls = modular integer cache[key] except Key Error class cls Modular Integer mod dom sym... | 15148 | def ModularIntegerFactory(_mod, _dom, _sym, parent):
try:
_mod = _dom.convert(_mod)
except CoercionFailed:
ok = False
else:
ok = True
if ((not ok) or (_mod < 1)):
raise ValueError(('modulus must be a positive integer, got %s' % _mod))
key = (_mod, _dom, _sym)
try:
cls = _modular_integer_cache[key]
exce... | Create custom class for specific integer modulus. | create custom class for specific integer modulus . | Question:
What does this function do?
Code:
def ModularIntegerFactory(_mod, _dom, _sym, parent):
try:
_mod = _dom.convert(_mod)
except CoercionFailed:
ok = False
else:
ok = True
if ((not ok) or (_mod < 1)):
raise ValueError(('modulus must be a positive integer, got %s' % _mod))
key = (_mod, _dom, _sym)
... |
null | null | null | What does this function do? | def _get_key_id(alias, region=None, key=None, keyid=None, profile=None):
key_metadata = describe_key(alias, region, key, keyid, profile)['key_metadata']
return key_metadata['KeyId']
| null | null | null | From an alias, get a key_id. | pcsd | def get key id alias region=None key=None keyid=None profile=None key metadata = describe key alias region key keyid profile ['key metadata'] return key metadata['Key Id'] | 15161 | def _get_key_id(alias, region=None, key=None, keyid=None, profile=None):
key_metadata = describe_key(alias, region, key, keyid, profile)['key_metadata']
return key_metadata['KeyId']
| From an alias, get a key_id. | from an alias , get a key _ id . | Question:
What does this function do?
Code:
def _get_key_id(alias, region=None, key=None, keyid=None, profile=None):
key_metadata = describe_key(alias, region, key, keyid, profile)['key_metadata']
return key_metadata['KeyId']
|
null | null | null | What does this function do? | def copula_bv_ev(u, v, transform, args=()):
return np.exp((np.log((u * v)) * transform((np.log(v) / np.log((u * v))), *args)))
| null | null | null | generic bivariate extreme value copula | pcsd | def copula bv ev u v transform args= return np exp np log u * v * transform np log v / np log u * v *args | 15163 | def copula_bv_ev(u, v, transform, args=()):
return np.exp((np.log((u * v)) * transform((np.log(v) / np.log((u * v))), *args)))
| generic bivariate extreme value copula | generic bivariate extreme value copula | Question:
What does this function do?
Code:
def copula_bv_ev(u, v, transform, args=()):
return np.exp((np.log((u * v)) * transform((np.log(v) / np.log((u * v))), *args)))
|
null | null | null | What does this function do? | def cmdLineParser(argv=None):
if (not argv):
argv = sys.argv
checkSystemEncoding()
_ = getUnicode(os.path.basename(argv[0]), encoding=(sys.getfilesystemencoding() or UNICODE_ENCODING))
usage = ('%s%s [options]' % (('python ' if (not IS_WIN) else ''), (('"%s"' % _) if (' ' in _) else _)))
parser = OptionParser(us... | null | null | null | This function parses the command line parameters and arguments | pcsd | def cmd Line Parser argv=None if not argv argv = sys argv check System Encoding = get Unicode os path basename argv[0] encoding= sys getfilesystemencoding or UNICODE ENCODING usage = '%s%s [options]' % 'python ' if not IS WIN else '' '"%s"' % if ' ' in else parser = Option Parser usage=usage try parser add option '--hh... | 15170 | def cmdLineParser(argv=None):
if (not argv):
argv = sys.argv
checkSystemEncoding()
_ = getUnicode(os.path.basename(argv[0]), encoding=(sys.getfilesystemencoding() or UNICODE_ENCODING))
usage = ('%s%s [options]' % (('python ' if (not IS_WIN) else ''), (('"%s"' % _) if (' ' in _) else _)))
parser = OptionParser(us... | This function parses the command line parameters and arguments | this function parses the command line parameters and arguments | Question:
What does this function do?
Code:
def cmdLineParser(argv=None):
if (not argv):
argv = sys.argv
checkSystemEncoding()
_ = getUnicode(os.path.basename(argv[0]), encoding=(sys.getfilesystemencoding() or UNICODE_ENCODING))
usage = ('%s%s [options]' % (('python ' if (not IS_WIN) else ''), (('"%s"' % _) if... |
null | null | null | What does this function do? | def getTwistPrecisionRadians(elementNode):
return math.radians(getTwistPrecision(elementNode))
| null | null | null | Get the twist precision in radians. | pcsd | def get Twist Precision Radians element Node return math radians get Twist Precision element Node | 15171 | def getTwistPrecisionRadians(elementNode):
return math.radians(getTwistPrecision(elementNode))
| Get the twist precision in radians. | get the twist precision in radians . | Question:
What does this function do?
Code:
def getTwistPrecisionRadians(elementNode):
return math.radians(getTwistPrecision(elementNode))
|
null | null | null | What does this function do? | def update_site_backward(apps, schema_editor):
Site = apps.get_model(u'sites', u'Site')
Site.objects.update_or_create(id=settings.SITE_ID, defaults={u'domain': u'example.com', u'name': u'example.com'})
| null | null | null | Revert site domain and name to default. | pcsd | def update site backward apps schema editor Site = apps get model u'sites' u'Site' Site objects update or create id=settings SITE ID defaults={u'domain' u'example com' u'name' u'example com'} | 15179 | def update_site_backward(apps, schema_editor):
Site = apps.get_model(u'sites', u'Site')
Site.objects.update_or_create(id=settings.SITE_ID, defaults={u'domain': u'example.com', u'name': u'example.com'})
| Revert site domain and name to default. | revert site domain and name to default . | Question:
What does this function do?
Code:
def update_site_backward(apps, schema_editor):
Site = apps.get_model(u'sites', u'Site')
Site.objects.update_or_create(id=settings.SITE_ID, defaults={u'domain': u'example.com', u'name': u'example.com'})
|
null | null | null | What does this function do? | def get_next_redirect_url(request, redirect_field_name='next'):
redirect_to = get_request_param(request, redirect_field_name)
if (not get_adapter(request).is_safe_url(redirect_to)):
redirect_to = None
return redirect_to
| null | null | null | Returns the next URL to redirect to, if it was explicitly passed
via the request. | pcsd | def get next redirect url request redirect field name='next' redirect to = get request param request redirect field name if not get adapter request is safe url redirect to redirect to = None return redirect to | 15190 | def get_next_redirect_url(request, redirect_field_name='next'):
redirect_to = get_request_param(request, redirect_field_name)
if (not get_adapter(request).is_safe_url(redirect_to)):
redirect_to = None
return redirect_to
| Returns the next URL to redirect to, if it was explicitly passed
via the request. | returns the next url to redirect to , if it was explicitly passed via the request . | Question:
What does this function do?
Code:
def get_next_redirect_url(request, redirect_field_name='next'):
redirect_to = get_request_param(request, redirect_field_name)
if (not get_adapter(request).is_safe_url(redirect_to)):
redirect_to = None
return redirect_to
|
null | null | null | What does this function do? | def patch_sessions():
from openedx.core.djangoapps.safe_sessions.testing import safe_cookie_test_session_patch
safe_cookie_test_session_patch()
| null | null | null | Override the Test Client\'s session and login to support safe cookies. | pcsd | def patch sessions from openedx core djangoapps safe sessions testing import safe cookie test session patch safe cookie test session patch | 15200 | def patch_sessions():
from openedx.core.djangoapps.safe_sessions.testing import safe_cookie_test_session_patch
safe_cookie_test_session_patch()
| Override the Test Client\'s session and login to support safe cookies. | override the test clients session and login to support safe cookies . | Question:
What does this function do?
Code:
def patch_sessions():
from openedx.core.djangoapps.safe_sessions.testing import safe_cookie_test_session_patch
safe_cookie_test_session_patch()
|
null | null | null | What does this function do? | def subscribe_to_collection(user_id, collection_id):
subscriptions_model = user_models.UserSubscriptionsModel.get(user_id, strict=False)
if (not subscriptions_model):
subscriptions_model = user_models.UserSubscriptionsModel(id=user_id)
if (collection_id not in subscriptions_model.collection_ids):
subscriptions_m... | null | null | null | Subscribes a user to a collection.
Callers of this function should ensure that the user_id and collection_id
are valid. | pcsd | def subscribe to collection user id collection id subscriptions model = user models User Subscriptions Model get user id strict=False if not subscriptions model subscriptions model = user models User Subscriptions Model id=user id if collection id not in subscriptions model collection ids subscriptions model collection... | 15216 | def subscribe_to_collection(user_id, collection_id):
subscriptions_model = user_models.UserSubscriptionsModel.get(user_id, strict=False)
if (not subscriptions_model):
subscriptions_model = user_models.UserSubscriptionsModel(id=user_id)
if (collection_id not in subscriptions_model.collection_ids):
subscriptions_m... | Subscribes a user to a collection.
Callers of this function should ensure that the user_id and collection_id
are valid. | subscribes a user to a collection . | Question:
What does this function do?
Code:
def subscribe_to_collection(user_id, collection_id):
subscriptions_model = user_models.UserSubscriptionsModel.get(user_id, strict=False)
if (not subscriptions_model):
subscriptions_model = user_models.UserSubscriptionsModel(id=user_id)
if (collection_id not in subscri... |
null | null | null | What does this function do? | def filter_parsedate(val):
return datetime.fromtimestamp(mktime(parsedate(val)))
| null | null | null | Attempts to parse a date according to the rules in RFC 2822 | pcsd | def filter parsedate val return datetime fromtimestamp mktime parsedate val | 15218 | def filter_parsedate(val):
return datetime.fromtimestamp(mktime(parsedate(val)))
| Attempts to parse a date according to the rules in RFC 2822 | attempts to parse a date according to the rules in rfc 2822 | Question:
What does this function do?
Code:
def filter_parsedate(val):
return datetime.fromtimestamp(mktime(parsedate(val)))
|
null | null | null | What does this function do? | def _enclosure(post, lang):
enclosure = post.meta(u'enclosure', lang)
if enclosure:
try:
length = int((post.meta(u'enclosure_length', lang) or 0))
except KeyError:
length = 0
except ValueError:
utils.LOGGER.warn(u'Invalid enclosure length for post {0}'.format(post.source_path))
length = 0
url = en... | null | null | null | Add an enclosure to RSS. | pcsd | def enclosure post lang enclosure = post meta u'enclosure' lang if enclosure try length = int post meta u'enclosure length' lang or 0 except Key Error length = 0 except Value Error utils LOGGER warn u'Invalid enclosure length for post {0}' format post source path length = 0 url = enclosure mime = mimetypes guess type u... | 15219 | def _enclosure(post, lang):
enclosure = post.meta(u'enclosure', lang)
if enclosure:
try:
length = int((post.meta(u'enclosure_length', lang) or 0))
except KeyError:
length = 0
except ValueError:
utils.LOGGER.warn(u'Invalid enclosure length for post {0}'.format(post.source_path))
length = 0
url = en... | Add an enclosure to RSS. | add an enclosure to rss . | Question:
What does this function do?
Code:
def _enclosure(post, lang):
enclosure = post.meta(u'enclosure', lang)
if enclosure:
try:
length = int((post.meta(u'enclosure_length', lang) or 0))
except KeyError:
length = 0
except ValueError:
utils.LOGGER.warn(u'Invalid enclosure length for post {0}'.for... |
null | null | null | What does this function do? | def returner(load):
serial = salt.payload.Serial(__opts__)
if (load['jid'] == 'req'):
load['jid'] = prep_jid(nocache=load.get('nocache', False))
jid_dir = salt.utils.jid.jid_dir(load['jid'], _job_dir(), __opts__['hash_type'])
if os.path.exists(os.path.join(jid_dir, 'nocache')):
return
hn_dir = os.path.join(jid... | null | null | null | Return data to the local job cache | pcsd | def returner load serial = salt payload Serial opts if load['jid'] == 'req' load['jid'] = prep jid nocache=load get 'nocache' False jid dir = salt utils jid jid dir load['jid'] job dir opts ['hash type'] if os path exists os path join jid dir 'nocache' return hn dir = os path join jid dir load['id'] try os makedirs hn ... | 15229 | def returner(load):
serial = salt.payload.Serial(__opts__)
if (load['jid'] == 'req'):
load['jid'] = prep_jid(nocache=load.get('nocache', False))
jid_dir = salt.utils.jid.jid_dir(load['jid'], _job_dir(), __opts__['hash_type'])
if os.path.exists(os.path.join(jid_dir, 'nocache')):
return
hn_dir = os.path.join(jid... | Return data to the local job cache | return data to the local job cache | Question:
What does this function do?
Code:
def returner(load):
serial = salt.payload.Serial(__opts__)
if (load['jid'] == 'req'):
load['jid'] = prep_jid(nocache=load.get('nocache', False))
jid_dir = salt.utils.jid.jid_dir(load['jid'], _job_dir(), __opts__['hash_type'])
if os.path.exists(os.path.join(jid_dir, '... |
null | null | null | What does this function do? | def sql_create(app, style, connection):
if (connection.settings_dict['ENGINE'] == 'django.db.backends.dummy'):
raise CommandError(((("Django doesn't know which syntax to use for your SQL statements,\n" + "because you haven't specified the ENGINE setting for the database.\n") + "Edit your settings file and change DAT... | null | null | null | Returns a list of the CREATE TABLE SQL statements for the given app. | pcsd | def sql create app style connection if connection settings dict['ENGINE'] == 'django db backends dummy' raise Command Error "Django doesn't know which syntax to use for your SQL statements " + "because you haven't specified the ENGINE setting for the database " + "Edit your settings file and change DATBASES['default'][... | 15240 | def sql_create(app, style, connection):
if (connection.settings_dict['ENGINE'] == 'django.db.backends.dummy'):
raise CommandError(((("Django doesn't know which syntax to use for your SQL statements,\n" + "because you haven't specified the ENGINE setting for the database.\n") + "Edit your settings file and change DAT... | Returns a list of the CREATE TABLE SQL statements for the given app. | returns a list of the create table sql statements for the given app . | Question:
What does this function do?
Code:
def sql_create(app, style, connection):
if (connection.settings_dict['ENGINE'] == 'django.db.backends.dummy'):
raise CommandError(((("Django doesn't know which syntax to use for your SQL statements,\n" + "because you haven't specified the ENGINE setting for the database... |
null | null | null | What does this function do? | def NO_MERGE(writer, segments):
return segments
| null | null | null | This policy does not merge any existing segments. | pcsd | def NO MERGE writer segments return segments | 15245 | def NO_MERGE(writer, segments):
return segments
| This policy does not merge any existing segments. | this policy does not merge any existing segments . | Question:
What does this function do?
Code:
def NO_MERGE(writer, segments):
return segments
|
null | null | null | What does this function do? | def OpenHelpFile(fileName, helpCmd=None, helpArg=None):
win32ui.DoWaitCursor(1)
try:
if (helpCmd is None):
helpCmd = win32con.HELP_CONTENTS
ext = os.path.splitext(fileName)[1].lower()
if (ext == '.hlp'):
win32api.WinHelp(win32ui.GetMainFrame().GetSafeHwnd(), fileName, helpCmd, helpArg)
elif (0 and (ext ... | null | null | null | Open a help file, given a full path | pcsd | def Open Help File file Name help Cmd=None help Arg=None win32ui Do Wait Cursor 1 try if help Cmd is None help Cmd = win32con HELP CONTENTS ext = os path splitext file Name [1] lower if ext == ' hlp' win32api Win Help win32ui Get Main Frame Get Safe Hwnd file Name help Cmd help Arg elif 0 and ext == ' chm' import win32... | 15247 | def OpenHelpFile(fileName, helpCmd=None, helpArg=None):
win32ui.DoWaitCursor(1)
try:
if (helpCmd is None):
helpCmd = win32con.HELP_CONTENTS
ext = os.path.splitext(fileName)[1].lower()
if (ext == '.hlp'):
win32api.WinHelp(win32ui.GetMainFrame().GetSafeHwnd(), fileName, helpCmd, helpArg)
elif (0 and (ext ... | Open a help file, given a full path | open a help file , given a full path | Question:
What does this function do?
Code:
def OpenHelpFile(fileName, helpCmd=None, helpArg=None):
win32ui.DoWaitCursor(1)
try:
if (helpCmd is None):
helpCmd = win32con.HELP_CONTENTS
ext = os.path.splitext(fileName)[1].lower()
if (ext == '.hlp'):
win32api.WinHelp(win32ui.GetMainFrame().GetSafeHwnd(), ... |
null | null | null | What does this function do? | @hook.command('spotify', 'sptrack')
def spotify(text):
params = {'q': text.strip()}
request = requests.get('http://ws.spotify.com/search/1/track.json', params=params)
if (request.status_code != requests.codes.ok):
return 'Could not get track information: {}'.format(request.status_code)
data = request.json()
try:... | null | null | null | spotify <song> -- Search Spotify for <song> | pcsd | @hook command 'spotify' 'sptrack' def spotify text params = {'q' text strip } request = requests get 'http //ws spotify com/search/1/track json' params=params if request status code != requests codes ok return 'Could not get track information {}' format request status code data = request json try type id = data['tracks... | 15248 | @hook.command('spotify', 'sptrack')
def spotify(text):
params = {'q': text.strip()}
request = requests.get('http://ws.spotify.com/search/1/track.json', params=params)
if (request.status_code != requests.codes.ok):
return 'Could not get track information: {}'.format(request.status_code)
data = request.json()
try:... | spotify <song> -- Search Spotify for <song> | spotify - - search spotify for | Question:
What does this function do?
Code:
@hook.command('spotify', 'sptrack')
def spotify(text):
params = {'q': text.strip()}
request = requests.get('http://ws.spotify.com/search/1/track.json', params=params)
if (request.status_code != requests.codes.ok):
return 'Could not get track information: {}'.format(re... |
null | null | null | What does this function do? | def MAX(ds, count, timeperiod=(- (2 ** 31))):
return call_talib_with_ds(ds, count, talib.MAX, timeperiod)
| null | null | null | Highest value over a specified period | pcsd | def MAX ds count timeperiod= - 2 ** 31 return call talib with ds ds count talib MAX timeperiod | 15253 | def MAX(ds, count, timeperiod=(- (2 ** 31))):
return call_talib_with_ds(ds, count, talib.MAX, timeperiod)
| Highest value over a specified period | highest value over a specified period | Question:
What does this function do?
Code:
def MAX(ds, count, timeperiod=(- (2 ** 31))):
return call_talib_with_ds(ds, count, talib.MAX, timeperiod)
|
null | null | null | What does this function do? | def phone2numeric(value):
from google.appengine._internal.django.utils.text import phone2numeric
return phone2numeric(value)
| null | null | null | Takes a phone number and converts it in to its numerical equivalent. | pcsd | def phone2numeric value from google appengine internal django utils text import phone2numeric return phone2numeric value | 15254 | def phone2numeric(value):
from google.appengine._internal.django.utils.text import phone2numeric
return phone2numeric(value)
| Takes a phone number and converts it in to its numerical equivalent. | takes a phone number and converts it in to its numerical equivalent . | Question:
What does this function do?
Code:
def phone2numeric(value):
from google.appengine._internal.django.utils.text import phone2numeric
return phone2numeric(value)
|
null | null | null | What does this function do? | def S_ISFIFO(mode):
return (S_IFMT(mode) == S_IFIFO)
| null | null | null | Return True if mode is from a FIFO (named pipe). | pcsd | def S ISFIFO mode return S IFMT mode == S IFIFO | 15259 | def S_ISFIFO(mode):
return (S_IFMT(mode) == S_IFIFO)
| Return True if mode is from a FIFO (named pipe). | return true if mode is from a fifo . | Question:
What does this function do?
Code:
def S_ISFIFO(mode):
return (S_IFMT(mode) == S_IFIFO)
|
null | null | null | What does this function do? | def successResponse(response):
response = str(response)
return ('+OK %s\r\n' % (response,))
| null | null | null | Format the given object as a positive response. | pcsd | def success Response response response = str response return '+OK %s\r ' % response | 15262 | def successResponse(response):
response = str(response)
return ('+OK %s\r\n' % (response,))
| Format the given object as a positive response. | format the given object as a positive response . | Question:
What does this function do?
Code:
def successResponse(response):
response = str(response)
return ('+OK %s\r\n' % (response,))
|
null | null | null | What does this function do? | @contextfunction
def administration_user_list(context, users, skip_group=False):
request = context['request']
response_format = 'html'
if ('response_format' in context):
response_format = context['response_format']
return Markup(render_to_string('core/administration/tags/user_list', {'users': users, 'skip_group':... | null | null | null | Print a list of users | pcsd | @contextfunction def administration user list context users skip group=False request = context['request'] response format = 'html' if 'response format' in context response format = context['response format'] return Markup render to string 'core/administration/tags/user list' {'users' users 'skip group' skip group} cont... | 15264 | @contextfunction
def administration_user_list(context, users, skip_group=False):
request = context['request']
response_format = 'html'
if ('response_format' in context):
response_format = context['response_format']
return Markup(render_to_string('core/administration/tags/user_list', {'users': users, 'skip_group':... | Print a list of users | print a list of users | Question:
What does this function do?
Code:
@contextfunction
def administration_user_list(context, users, skip_group=False):
request = context['request']
response_format = 'html'
if ('response_format' in context):
response_format = context['response_format']
return Markup(render_to_string('core/administration/... |
null | null | null | What does this function do? | def get_poem():
def canceler(d):
delayed_call.cancel()
d = Deferred(canceler)
from twisted.internet import reactor
delayed_call = reactor.callLater(5, send_poem, d)
return d
| null | null | null | Return a poem 5 seconds later. | pcsd | def get poem def canceler d delayed call cancel d = Deferred canceler from twisted internet import reactor delayed call = reactor call Later 5 send poem d return d | 15272 | def get_poem():
def canceler(d):
delayed_call.cancel()
d = Deferred(canceler)
from twisted.internet import reactor
delayed_call = reactor.callLater(5, send_poem, d)
return d
| Return a poem 5 seconds later. | return a poem 5 seconds later . | Question:
What does this function do?
Code:
def get_poem():
def canceler(d):
delayed_call.cancel()
d = Deferred(canceler)
from twisted.internet import reactor
delayed_call = reactor.callLater(5, send_poem, d)
return d
|
null | null | null | What does this function do? | def update_package_db(module, opkg_path):
(rc, out, err) = module.run_command(('%s update' % opkg_path))
if (rc != 0):
module.fail_json(msg='could not update package db')
| null | null | null | Updates packages list. | pcsd | def update package db module opkg path rc out err = module run command '%s update' % opkg path if rc != 0 module fail json msg='could not update package db' | 15280 | def update_package_db(module, opkg_path):
(rc, out, err) = module.run_command(('%s update' % opkg_path))
if (rc != 0):
module.fail_json(msg='could not update package db')
| Updates packages list. | updates packages list . | Question:
What does this function do?
Code:
def update_package_db(module, opkg_path):
(rc, out, err) = module.run_command(('%s update' % opkg_path))
if (rc != 0):
module.fail_json(msg='could not update package db')
|
null | null | null | What does this function do? | def __virtual__():
if (not HAS_JUNOS):
return (False, "Missing dependency: The junos proxy minion requires the 'jnpr' Python module.")
return __virtualname__
| null | null | null | Only return if all the modules are available | pcsd | def virtual if not HAS JUNOS return False "Missing dependency The junos proxy minion requires the 'jnpr' Python module " return virtualname | 15296 | def __virtual__():
if (not HAS_JUNOS):
return (False, "Missing dependency: The junos proxy minion requires the 'jnpr' Python module.")
return __virtualname__
| Only return if all the modules are available | only return if all the modules are available | Question:
What does this function do?
Code:
def __virtual__():
if (not HAS_JUNOS):
return (False, "Missing dependency: The junos proxy minion requires the 'jnpr' Python module.")
return __virtualname__
|
null | null | null | What does this function do? | def use_rand_uuid_instead_of_uuid4(logical_line, filename):
if ('tempest/lib/' in filename):
return
if ('uuid.uuid4()' not in logical_line):
return
msg = 'T113: Tests should use data_utils.rand_uuid()/rand_uuid_hex() instead of uuid.uuid4()/uuid.uuid4().hex'
(yield (0, msg))
| null | null | null | Check that tests use data_utils.rand_uuid() instead of uuid.uuid4()
T113 | pcsd | def use rand uuid instead of uuid4 logical line filename if 'tempest/lib/' in filename return if 'uuid uuid4 ' not in logical line return msg = 'T113 Tests should use data utils rand uuid /rand uuid hex instead of uuid uuid4 /uuid uuid4 hex' yield 0 msg | 15308 | def use_rand_uuid_instead_of_uuid4(logical_line, filename):
if ('tempest/lib/' in filename):
return
if ('uuid.uuid4()' not in logical_line):
return
msg = 'T113: Tests should use data_utils.rand_uuid()/rand_uuid_hex() instead of uuid.uuid4()/uuid.uuid4().hex'
(yield (0, msg))
| Check that tests use data_utils.rand_uuid() instead of uuid.uuid4()
T113 | check that tests use data _ utils . rand _ uuid ( ) instead of uuid . uuid4 ( ) | Question:
What does this function do?
Code:
def use_rand_uuid_instead_of_uuid4(logical_line, filename):
if ('tempest/lib/' in filename):
return
if ('uuid.uuid4()' not in logical_line):
return
msg = 'T113: Tests should use data_utils.rand_uuid()/rand_uuid_hex() instead of uuid.uuid4()/uuid.uuid4().hex'
(yield... |
null | null | null | What does this function do? | def forgiving_round(value, precision=0):
try:
value = round(float(value), precision)
return (int(value) if (precision == 0) else value)
except (ValueError, TypeError):
return value
| null | null | null | Rounding filter that accepts strings. | pcsd | def forgiving round value precision=0 try value = round float value precision return int value if precision == 0 else value except Value Error Type Error return value | 15315 | def forgiving_round(value, precision=0):
try:
value = round(float(value), precision)
return (int(value) if (precision == 0) else value)
except (ValueError, TypeError):
return value
| Rounding filter that accepts strings. | rounding filter that accepts strings . | Question:
What does this function do?
Code:
def forgiving_round(value, precision=0):
try:
value = round(float(value), precision)
return (int(value) if (precision == 0) else value)
except (ValueError, TypeError):
return value
|
null | null | null | What does this function do? | def parameter_bank_names(device, bank_name_dict=BANK_NAME_DICT):
if (device != None):
if (device.class_name in bank_name_dict.keys()):
return bank_name_dict[device.class_name]
banks = number_of_parameter_banks(device)
def _default_bank_name(bank_index):
return ('Bank ' + str((bank_index + 1)))
if ((devic... | null | null | null | Determine the bank names to use for a device | pcsd | def parameter bank names device bank name dict=BANK NAME DICT if device != None if device class name in bank name dict keys return bank name dict[device class name] banks = number of parameter banks device def default bank name bank index return 'Bank ' + str bank index + 1 if device class name in MAX DEVICES and banks... | 15316 | def parameter_bank_names(device, bank_name_dict=BANK_NAME_DICT):
if (device != None):
if (device.class_name in bank_name_dict.keys()):
return bank_name_dict[device.class_name]
banks = number_of_parameter_banks(device)
def _default_bank_name(bank_index):
return ('Bank ' + str((bank_index + 1)))
if ((devic... | Determine the bank names to use for a device | determine the bank names to use for a device | Question:
What does this function do?
Code:
def parameter_bank_names(device, bank_name_dict=BANK_NAME_DICT):
if (device != None):
if (device.class_name in bank_name_dict.keys()):
return bank_name_dict[device.class_name]
banks = number_of_parameter_banks(device)
def _default_bank_name(bank_index):
return... |
null | null | null | What does this function do? | @utils.arg('id', metavar='<id>', help='Unique ID of the monitor type to delete')
@utils.service_type('monitor')
def do_type_delete(cs, args):
cs.monitor_types.delete(args.id)
| null | null | null | Delete a specific monitor type | pcsd | @utils arg 'id' metavar='<id>' help='Unique ID of the monitor type to delete' @utils service type 'monitor' def do type delete cs args cs monitor types delete args id | 15320 | @utils.arg('id', metavar='<id>', help='Unique ID of the monitor type to delete')
@utils.service_type('monitor')
def do_type_delete(cs, args):
cs.monitor_types.delete(args.id)
| Delete a specific monitor type | delete a specific monitor type | Question:
What does this function do?
Code:
@utils.arg('id', metavar='<id>', help='Unique ID of the monitor type to delete')
@utils.service_type('monitor')
def do_type_delete(cs, args):
cs.monitor_types.delete(args.id)
|
null | null | null | What does this function do? | def parse_domain(value):
value = strip_spaces_and_quotes(value)
if (value and (value[0] == '.')):
value = value[1:]
if value:
assert valid_domain(value)
return value
| null | null | null | Parse and validate an incoming Domain attribute value. | pcsd | def parse domain value value = strip spaces and quotes value if value and value[0] == ' ' value = value[1 ] if value assert valid domain value return value | 15329 | def parse_domain(value):
value = strip_spaces_and_quotes(value)
if (value and (value[0] == '.')):
value = value[1:]
if value:
assert valid_domain(value)
return value
| Parse and validate an incoming Domain attribute value. | parse and validate an incoming domain attribute value . | Question:
What does this function do?
Code:
def parse_domain(value):
value = strip_spaces_and_quotes(value)
if (value and (value[0] == '.')):
value = value[1:]
if value:
assert valid_domain(value)
return value
|
null | null | null | What does this function do? | @cronjobs.register
def clean_old_signed(seconds=(60 * 60)):
log.info('Removing old apps signed for reviewers')
root = settings.SIGNED_APPS_REVIEWER_PATH
now = (datetime.utcnow if storage_is_remote() else datetime.now)
for (nextroot, dirs, files) in walk_storage(root, storage=private_storage):
for fn in files:
... | null | null | null | Clean out apps signed for reviewers. | pcsd | @cronjobs register def clean old signed seconds= 60 * 60 log info 'Removing old apps signed for reviewers' root = settings SIGNED APPS REVIEWER PATH now = datetime utcnow if storage is remote else datetime now for nextroot dirs files in walk storage root storage=private storage for fn in files full = os path join nextr... | 15335 | @cronjobs.register
def clean_old_signed(seconds=(60 * 60)):
log.info('Removing old apps signed for reviewers')
root = settings.SIGNED_APPS_REVIEWER_PATH
now = (datetime.utcnow if storage_is_remote() else datetime.now)
for (nextroot, dirs, files) in walk_storage(root, storage=private_storage):
for fn in files:
... | Clean out apps signed for reviewers. | clean out apps signed for reviewers . | Question:
What does this function do?
Code:
@cronjobs.register
def clean_old_signed(seconds=(60 * 60)):
log.info('Removing old apps signed for reviewers')
root = settings.SIGNED_APPS_REVIEWER_PATH
now = (datetime.utcnow if storage_is_remote() else datetime.now)
for (nextroot, dirs, files) in walk_storage(root, s... |
null | null | null | What does this function do? | def mutSet(individual):
if (random.random() < 0.5):
if (len(individual) > 0):
individual.remove(random.choice(sorted(tuple(individual))))
else:
individual.add(random.randrange(NBR_ITEMS))
return (individual,)
| null | null | null | Mutation that pops or add an element. | pcsd | def mut Set individual if random random < 0 5 if len individual > 0 individual remove random choice sorted tuple individual else individual add random randrange NBR ITEMS return individual | 15336 | def mutSet(individual):
if (random.random() < 0.5):
if (len(individual) > 0):
individual.remove(random.choice(sorted(tuple(individual))))
else:
individual.add(random.randrange(NBR_ITEMS))
return (individual,)
| Mutation that pops or add an element. | mutation that pops or add an element . | Question:
What does this function do?
Code:
def mutSet(individual):
if (random.random() < 0.5):
if (len(individual) > 0):
individual.remove(random.choice(sorted(tuple(individual))))
else:
individual.add(random.randrange(NBR_ITEMS))
return (individual,)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.