labNo
float64
1
10
taskNo
float64
0
4
questioner
stringclasses
2 values
question
stringlengths
9
201
code
stringlengths
18
30.3k
startLine
float64
0
192
endLine
float64
0
196
questionType
stringclasses
4 values
answer
stringlengths
2
905
src
stringclasses
3 values
code_processed
stringlengths
12
28.3k
id
stringlengths
2
5
raw_code
stringlengths
20
30.3k
raw_comment
stringlengths
10
242
comment
stringlengths
9
207
q_code
stringlengths
66
30.3k
null
null
null
What does this function do?
def CDL3STARSINSOUTH(barDs, count): return call_talib_with_ohlc(barDs, count, talib.CDL3STARSINSOUTH)
null
null
null
Three Stars In The South
pcsd
def CDL3STARSINSOUTH bar Ds count return call talib with ohlc bar Ds count talib CDL3STARSINSOUTH
5406
def CDL3STARSINSOUTH(barDs, count): return call_talib_with_ohlc(barDs, count, talib.CDL3STARSINSOUTH)
Three Stars In The South
three stars in the south
Question: What does this function do? Code: def CDL3STARSINSOUTH(barDs, count): return call_talib_with_ohlc(barDs, count, talib.CDL3STARSINSOUTH)
null
null
null
What does this function do?
def openExplorerPath(filename): if ((sys.platform == 'win32') or (sys.platform == 'cygwin')): subprocess.Popen(('explorer "%s"' % filename)) if (sys.platform == 'darwin'): subprocess.Popen(['open', filename]) if sys.platform.startswith('linux'): if os.path.isfile('/usr/bin/xdg-open'): subprocess.Popen(['/us...
null
null
null
Open a file dialog inside a directory, without selecting any file.
pcsd
def open Explorer Path filename if sys platform == 'win32' or sys platform == 'cygwin' subprocess Popen 'explorer "%s"' % filename if sys platform == 'darwin' subprocess Popen ['open' filename] if sys platform startswith 'linux' if os path isfile '/usr/bin/xdg-open' subprocess Popen ['/usr/bin/xdg-open' filename]
5411
def openExplorerPath(filename): if ((sys.platform == 'win32') or (sys.platform == 'cygwin')): subprocess.Popen(('explorer "%s"' % filename)) if (sys.platform == 'darwin'): subprocess.Popen(['open', filename]) if sys.platform.startswith('linux'): if os.path.isfile('/usr/bin/xdg-open'): subprocess.Popen(['/us...
Open a file dialog inside a directory, without selecting any file.
open a file dialog inside a directory , without selecting any file .
Question: What does this function do? Code: def openExplorerPath(filename): if ((sys.platform == 'win32') or (sys.platform == 'cygwin')): subprocess.Popen(('explorer "%s"' % filename)) if (sys.platform == 'darwin'): subprocess.Popen(['open', filename]) if sys.platform.startswith('linux'): if os.path.isfile(...
null
null
null
What does this function do?
def _long_to_bin(x, hex_format_string): return binascii.unhexlify((hex_format_string % x))
null
null
null
Convert a long integer into a binary string. hex_format_string is like "%020x" for padding 10 characters.
pcsd
def long to bin x hex format string return binascii unhexlify hex format string % x
5418
def _long_to_bin(x, hex_format_string): return binascii.unhexlify((hex_format_string % x))
Convert a long integer into a binary string. hex_format_string is like "%020x" for padding 10 characters.
convert a long integer into a binary string .
Question: What does this function do? Code: def _long_to_bin(x, hex_format_string): return binascii.unhexlify((hex_format_string % x))
null
null
null
What does this function do?
def hpauth(u, p): global hpuser, hppassword, mb_auth hpuser = u hppassword = p mb_auth = True
null
null
null
Set the username and password to be used in subsequent queries to the MusicBrainz XML API that require authentication.
pcsd
def hpauth u p global hpuser hppassword mb auth hpuser = u hppassword = p mb auth = True
5432
def hpauth(u, p): global hpuser, hppassword, mb_auth hpuser = u hppassword = p mb_auth = True
Set the username and password to be used in subsequent queries to the MusicBrainz XML API that require authentication.
set the username and password to be used in subsequent queries to the musicbrainz xml api that require authentication .
Question: What does this function do? Code: def hpauth(u, p): global hpuser, hppassword, mb_auth hpuser = u hppassword = p mb_auth = True
null
null
null
What does this function do?
def addHook(hook, func): if (not _hooks.get(hook, None)): _hooks[hook] = [] if (func not in _hooks[hook]): _hooks[hook].append(func)
null
null
null
Add a function to hook. Ignore if already on hook.
pcsd
def add Hook hook func if not hooks get hook None hooks[hook] = [] if func not in hooks[hook] hooks[hook] append func
5439
def addHook(hook, func): if (not _hooks.get(hook, None)): _hooks[hook] = [] if (func not in _hooks[hook]): _hooks[hook].append(func)
Add a function to hook. Ignore if already on hook.
add a function to hook .
Question: What does this function do? Code: def addHook(hook, func): if (not _hooks.get(hook, None)): _hooks[hook] = [] if (func not in _hooks[hook]): _hooks[hook].append(func)
null
null
null
What does this function do?
def assemble_distance_matrix(dm_components): data = {} for c in dm_components: col_ids = [] for line in c: fields = line.strip().split() if fields: if (not col_ids): col_ids = fields else: sid = fields[0] data[sid] = dict(zip(col_ids, fields[1:])) labels = data.keys() dm = [] for l...
null
null
null
assemble distance matrix components into a complete dm string
pcsd
def assemble distance matrix dm components data = {} for c in dm components col ids = [] for line in c fields = line strip split if fields if not col ids col ids = fields else sid = fields[0] data[sid] = dict zip col ids fields[1 ] labels = data keys dm = [] for l1 in labels dm append [float data[l1][l2] for l2 in labe...
5442
def assemble_distance_matrix(dm_components): data = {} for c in dm_components: col_ids = [] for line in c: fields = line.strip().split() if fields: if (not col_ids): col_ids = fields else: sid = fields[0] data[sid] = dict(zip(col_ids, fields[1:])) labels = data.keys() dm = [] for l...
assemble distance matrix components into a complete dm string
assemble distance matrix components into a complete dm string
Question: What does this function do? Code: def assemble_distance_matrix(dm_components): data = {} for c in dm_components: col_ids = [] for line in c: fields = line.strip().split() if fields: if (not col_ids): col_ids = fields else: sid = fields[0] data[sid] = dict(zip(col_ids, fie...
null
null
null
What does this function do?
def _is_namespace_visible(context, namespace): if context.is_admin: return True if (namespace.get('visibility', '') == 'public'): return True if (namespace['owner'] is None): return True if (context.owner is not None): if (context.owner == namespace['owner']): return True return False
null
null
null
Return true if namespace is visible in this context
pcsd
def is namespace visible context namespace if context is admin return True if namespace get 'visibility' '' == 'public' return True if namespace['owner'] is None return True if context owner is not None if context owner == namespace['owner'] return True return False
5455
def _is_namespace_visible(context, namespace): if context.is_admin: return True if (namespace.get('visibility', '') == 'public'): return True if (namespace['owner'] is None): return True if (context.owner is not None): if (context.owner == namespace['owner']): return True return False
Return true if namespace is visible in this context
return true if namespace is visible in this context
Question: What does this function do? Code: def _is_namespace_visible(context, namespace): if context.is_admin: return True if (namespace.get('visibility', '') == 'public'): return True if (namespace['owner'] is None): return True if (context.owner is not None): if (context.owner == namespace['owner']): ...
null
null
null
What does this function do?
def parse_plain_scalar_indent(TokenClass): def callback(lexer, match, context): text = match.group() if (len(text) <= context.indent): context.stack.pop() context.stack.pop() return if text: (yield (match.start(), TokenClass, text)) context.pos = match.end() return callback
null
null
null
Process indentation spaces in a plain scalar.
pcsd
def parse plain scalar indent Token Class def callback lexer match context text = match group if len text <= context indent context stack pop context stack pop return if text yield match start Token Class text context pos = match end return callback
5456
def parse_plain_scalar_indent(TokenClass): def callback(lexer, match, context): text = match.group() if (len(text) <= context.indent): context.stack.pop() context.stack.pop() return if text: (yield (match.start(), TokenClass, text)) context.pos = match.end() return callback
Process indentation spaces in a plain scalar.
process indentation spaces in a plain scalar .
Question: What does this function do? Code: def parse_plain_scalar_indent(TokenClass): def callback(lexer, match, context): text = match.group() if (len(text) <= context.indent): context.stack.pop() context.stack.pop() return if text: (yield (match.start(), TokenClass, text)) context.pos = matc...
null
null
null
What does this function do?
def person(): tablename = 'pr_person' table = s3db.pr_person s3db.configure(tablename, deletable=False) s3.crud_strings[tablename].update(title_upload=T('Import Members')) s3db.configure('member_membership', delete_next=URL('member', 'membership')) set_method = s3db.set_method set_method('pr', resourcename, meth...
null
null
null
Person Controller - used for Personal Profile & Imports - includes components relevant to Membership
pcsd
def person tablename = 'pr person' table = s3db pr person s3db configure tablename deletable=False s3 crud strings[tablename] update title upload=T 'Import Members' s3db configure 'member membership' delete next=URL 'member' 'membership' set method = s3db set method set method 'pr' resourcename method='contacts' action...
5463
def person(): tablename = 'pr_person' table = s3db.pr_person s3db.configure(tablename, deletable=False) s3.crud_strings[tablename].update(title_upload=T('Import Members')) s3db.configure('member_membership', delete_next=URL('member', 'membership')) set_method = s3db.set_method set_method('pr', resourcename, meth...
Person Controller - used for Personal Profile & Imports - includes components relevant to Membership
person controller - used for personal profile & imports - includes components relevant to membership
Question: What does this function do? Code: def person(): tablename = 'pr_person' table = s3db.pr_person s3db.configure(tablename, deletable=False) s3.crud_strings[tablename].update(title_upload=T('Import Members')) s3db.configure('member_membership', delete_next=URL('member', 'membership')) set_method = s3db....
null
null
null
What does this function do?
def variance(list): a = avg(list) return (_sum([((x - a) ** 2) for x in list]) / ((len(list) - 1) or 1))
null
null
null
Returns the variance of the given list of values. The variance is the average of squared deviations from the mean.
pcsd
def variance list a = avg list return sum [ x - a ** 2 for x in list] / len list - 1 or 1
5474
def variance(list): a = avg(list) return (_sum([((x - a) ** 2) for x in list]) / ((len(list) - 1) or 1))
Returns the variance of the given list of values. The variance is the average of squared deviations from the mean.
returns the variance of the given list of values .
Question: What does this function do? Code: def variance(list): a = avg(list) return (_sum([((x - a) ** 2) for x in list]) / ((len(list) - 1) or 1))
null
null
null
What does this function do?
def _solve_as_rational(f, symbol, domain): f = together(f, deep=True) (g, h) = fraction(f) if (not h.has(symbol)): return _solve_as_poly(g, symbol, domain) else: valid_solns = _solveset(g, symbol, domain) invalid_solns = _solveset(h, symbol, domain) return (valid_solns - invalid_solns)
null
null
null
solve rational functions
pcsd
def solve as rational f symbol domain f = together f deep=True g h = fraction f if not h has symbol return solve as poly g symbol domain else valid solns = solveset g symbol domain invalid solns = solveset h symbol domain return valid solns - invalid solns
5478
def _solve_as_rational(f, symbol, domain): f = together(f, deep=True) (g, h) = fraction(f) if (not h.has(symbol)): return _solve_as_poly(g, symbol, domain) else: valid_solns = _solveset(g, symbol, domain) invalid_solns = _solveset(h, symbol, domain) return (valid_solns - invalid_solns)
solve rational functions
solve rational functions
Question: What does this function do? Code: def _solve_as_rational(f, symbol, domain): f = together(f, deep=True) (g, h) = fraction(f) if (not h.has(symbol)): return _solve_as_poly(g, symbol, domain) else: valid_solns = _solveset(g, symbol, domain) invalid_solns = _solveset(h, symbol, domain) return (val...
null
null
null
What does this function do?
def get_file(src, dest, permissions=None): if (src == dest): return if is_url(src): urlretrieve(src, dest) else: shutil.copyfile(src, dest) if permissions: os.chmod(dest, permissions) return dest
null
null
null
Get a file from src, which can be local or a remote URL
pcsd
def get file src dest permissions=None if src == dest return if is url src urlretrieve src dest else shutil copyfile src dest if permissions os chmod dest permissions return dest
5498
def get_file(src, dest, permissions=None): if (src == dest): return if is_url(src): urlretrieve(src, dest) else: shutil.copyfile(src, dest) if permissions: os.chmod(dest, permissions) return dest
Get a file from src, which can be local or a remote URL
get a file from src , which can be local or a remote url
Question: What does this function do? Code: def get_file(src, dest, permissions=None): if (src == dest): return if is_url(src): urlretrieve(src, dest) else: shutil.copyfile(src, dest) if permissions: os.chmod(dest, permissions) return dest
null
null
null
What does this function do?
def select2_submodule_check(app_configs, **kwargs): errors = [] dal_select2_path = os.path.dirname(__file__) select2 = os.path.join(os.path.abspath(dal_select2_path), 'static/autocomplete_light/vendor/select2/dist/js/select2.min.js') if (not os.path.exists(select2)): errors.append(checks.Error('Select2 static fil...
null
null
null
Return an error if select2 is missing.
pcsd
def select2 submodule check app configs **kwargs errors = [] dal select2 path = os path dirname file select2 = os path join os path abspath dal select2 path 'static/autocomplete light/vendor/select2/dist/js/select2 min js' if not os path exists select2 errors append checks Error 'Select2 static files not checked out' h...
5503
def select2_submodule_check(app_configs, **kwargs): errors = [] dal_select2_path = os.path.dirname(__file__) select2 = os.path.join(os.path.abspath(dal_select2_path), 'static/autocomplete_light/vendor/select2/dist/js/select2.min.js') if (not os.path.exists(select2)): errors.append(checks.Error('Select2 static fil...
Return an error if select2 is missing.
return an error if select2 is missing .
Question: What does this function do? Code: def select2_submodule_check(app_configs, **kwargs): errors = [] dal_select2_path = os.path.dirname(__file__) select2 = os.path.join(os.path.abspath(dal_select2_path), 'static/autocomplete_light/vendor/select2/dist/js/select2.min.js') if (not os.path.exists(select2)): ...
null
null
null
What does this function do?
def make_socket(port=4050): sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect(('localhost', port)) return sockobj
null
null
null
Create a socket on localhost and return it.
pcsd
def make socket port=4050 sockobj = socket AF INET SOCK STREAM sockobj connect 'localhost' port return sockobj
5510
def make_socket(port=4050): sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect(('localhost', port)) return sockobj
Create a socket on localhost and return it.
create a socket on localhost and return it .
Question: What does this function do? Code: def make_socket(port=4050): sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect(('localhost', port)) return sockobj
null
null
null
What does this function do?
def detect_unboundedness(R, s, t): q = deque([s]) seen = set([s]) inf = R.graph['inf'] while q: u = q.popleft() for (v, attr) in R[u].items(): if ((attr['capacity'] == inf) and (v not in seen)): if (v == t): raise nx.NetworkXUnbounded('Infinite capacity path, flow unbounded above.') seen.add(v) ...
null
null
null
Detect an infinite-capacity s-t path in R.
pcsd
def detect unboundedness R s t q = deque [s] seen = set [s] inf = R graph['inf'] while q u = q popleft for v attr in R[u] items if attr['capacity'] == inf and v not in seen if v == t raise nx Network X Unbounded 'Infinite capacity path flow unbounded above ' seen add v q append v
5511
def detect_unboundedness(R, s, t): q = deque([s]) seen = set([s]) inf = R.graph['inf'] while q: u = q.popleft() for (v, attr) in R[u].items(): if ((attr['capacity'] == inf) and (v not in seen)): if (v == t): raise nx.NetworkXUnbounded('Infinite capacity path, flow unbounded above.') seen.add(v) ...
Detect an infinite-capacity s-t path in R.
detect an infinite - capacity s - t path in r .
Question: What does this function do? Code: def detect_unboundedness(R, s, t): q = deque([s]) seen = set([s]) inf = R.graph['inf'] while q: u = q.popleft() for (v, attr) in R[u].items(): if ((attr['capacity'] == inf) and (v not in seen)): if (v == t): raise nx.NetworkXUnbounded('Infinite capacity...
null
null
null
What does this function do?
def getSphericalByRadians(azimuthRadians, elevationRadians, radius=1.0): elevationComplex = euclidean.getWiddershinsUnitPolar(elevationRadians) azimuthComplex = (euclidean.getWiddershinsUnitPolar(azimuthRadians) * elevationComplex.real) return (Vector3(azimuthComplex.real, azimuthComplex.imag, elevationComplex.imag)...
null
null
null
Get the spherical vector3 unit by radians.
pcsd
def get Spherical By Radians azimuth Radians elevation Radians radius=1 0 elevation Complex = euclidean get Widdershins Unit Polar elevation Radians azimuth Complex = euclidean get Widdershins Unit Polar azimuth Radians * elevation Complex real return Vector3 azimuth Complex real azimuth Complex imag elevation Complex ...
5518
def getSphericalByRadians(azimuthRadians, elevationRadians, radius=1.0): elevationComplex = euclidean.getWiddershinsUnitPolar(elevationRadians) azimuthComplex = (euclidean.getWiddershinsUnitPolar(azimuthRadians) * elevationComplex.real) return (Vector3(azimuthComplex.real, azimuthComplex.imag, elevationComplex.imag)...
Get the spherical vector3 unit by radians.
get the spherical vector3 unit by radians .
Question: What does this function do? Code: def getSphericalByRadians(azimuthRadians, elevationRadians, radius=1.0): elevationComplex = euclidean.getWiddershinsUnitPolar(elevationRadians) azimuthComplex = (euclidean.getWiddershinsUnitPolar(azimuthRadians) * elevationComplex.real) return (Vector3(azimuthComplex.re...
null
null
null
What does this function do?
def TRIMA(ds, count, timeperiod=(- (2 ** 31))): return call_talib_with_ds(ds, count, talib.TRIMA, timeperiod)
null
null
null
Triangular Moving Average
pcsd
def TRIMA ds count timeperiod= - 2 ** 31 return call talib with ds ds count talib TRIMA timeperiod
5524
def TRIMA(ds, count, timeperiod=(- (2 ** 31))): return call_talib_with_ds(ds, count, talib.TRIMA, timeperiod)
Triangular Moving Average
triangular moving average
Question: What does this function do? Code: def TRIMA(ds, count, timeperiod=(- (2 ** 31))): return call_talib_with_ds(ds, count, talib.TRIMA, timeperiod)
null
null
null
What does this function do?
def volume_glance_metadata_list_get(context, volume_id_list): return IMPL.volume_glance_metadata_list_get(context, volume_id_list)
null
null
null
Return the glance metadata for a volume list.
pcsd
def volume glance metadata list get context volume id list return IMPL volume glance metadata list get context volume id list
5532
def volume_glance_metadata_list_get(context, volume_id_list): return IMPL.volume_glance_metadata_list_get(context, volume_id_list)
Return the glance metadata for a volume list.
return the glance metadata for a volume list .
Question: What does this function do? Code: def volume_glance_metadata_list_get(context, volume_id_list): return IMPL.volume_glance_metadata_list_get(context, volume_id_list)
null
null
null
What does this function do?
@pytest.mark.parametrize('mode, answer, signal_names', [(usertypes.PromptMode.text, 'foo', ['answered', 'completed']), (usertypes.PromptMode.yesno, True, ['answered', 'completed', 'answered_yes']), (usertypes.PromptMode.yesno, False, ['answered', 'completed', 'answered_no'])]) def test_done(mode, answer, signal_names, ...
null
null
null
Test the \'done\' method and completed/answered signals.
pcsd
@pytest mark parametrize 'mode answer signal names' [ usertypes Prompt Mode text 'foo' ['answered' 'completed'] usertypes Prompt Mode yesno True ['answered' 'completed' 'answered yes'] usertypes Prompt Mode yesno False ['answered' 'completed' 'answered no'] ] def test done mode answer signal names question qtbot questi...
5546
@pytest.mark.parametrize('mode, answer, signal_names', [(usertypes.PromptMode.text, 'foo', ['answered', 'completed']), (usertypes.PromptMode.yesno, True, ['answered', 'completed', 'answered_yes']), (usertypes.PromptMode.yesno, False, ['answered', 'completed', 'answered_no'])]) def test_done(mode, answer, signal_names, ...
Test the \'done\' method and completed/answered signals.
test the done method and completed / answered signals .
Question: What does this function do? Code: @pytest.mark.parametrize('mode, answer, signal_names', [(usertypes.PromptMode.text, 'foo', ['answered', 'completed']), (usertypes.PromptMode.yesno, True, ['answered', 'completed', 'answered_yes']), (usertypes.PromptMode.yesno, False, ['answered', 'completed', 'answered_no'...
null
null
null
What does this function do?
def clear_cache(): global FS_CACHE old = FS_CACHE FS_CACHE = {} return old
null
null
null
Clears internal cache. Returns something that can be given back to restore_cache.
pcsd
def clear cache global FS CACHE old = FS CACHE FS CACHE = {} return old
5547
def clear_cache(): global FS_CACHE old = FS_CACHE FS_CACHE = {} return old
Clears internal cache. Returns something that can be given back to restore_cache.
clears internal cache .
Question: What does this function do? Code: def clear_cache(): global FS_CACHE old = FS_CACHE FS_CACHE = {} return old
null
null
null
What does this function do?
def trace(context=1): return getinnerframes(sys.exc_info()[2], context)
null
null
null
Return a list of records for the stack below the current exception.
pcsd
def trace context=1 return getinnerframes sys exc info [2] context
5552
def trace(context=1): return getinnerframes(sys.exc_info()[2], context)
Return a list of records for the stack below the current exception.
return a list of records for the stack below the current exception .
Question: What does this function do? Code: def trace(context=1): return getinnerframes(sys.exc_info()[2], context)
null
null
null
What does this function do?
def transformPoints(elementNode, points, prefix): derivation = TransformDerivation(elementNode, prefix) if (derivation.transformTetragrid == None): print 'Warning, transformTetragrid was None in transform so nothing will be done for:' print elementNode return matrix.transformVector3sByMatrix(derivation.transfo...
null
null
null
Transform the points.
pcsd
def transform Points element Node points prefix derivation = Transform Derivation element Node prefix if derivation transform Tetragrid == None print 'Warning transform Tetragrid was None in transform so nothing will be done for ' print element Node return matrix transform Vector3s By Matrix derivation transform Tetrag...
5559
def transformPoints(elementNode, points, prefix): derivation = TransformDerivation(elementNode, prefix) if (derivation.transformTetragrid == None): print 'Warning, transformTetragrid was None in transform so nothing will be done for:' print elementNode return matrix.transformVector3sByMatrix(derivation.transfo...
Transform the points.
transform the points .
Question: What does this function do? Code: def transformPoints(elementNode, points, prefix): derivation = TransformDerivation(elementNode, prefix) if (derivation.transformTetragrid == None): print 'Warning, transformTetragrid was None in transform so nothing will be done for:' print elementNode return matr...
null
null
null
What does this function do?
def _make_voxel_ras_trans(move, ras, voxel_size): assert (voxel_size.ndim == 1) assert (voxel_size.size == 3) rot = (ras.T * voxel_size[np.newaxis, :]) assert (rot.ndim == 2) assert (rot.shape[0] == 3) assert (rot.shape[1] == 3) trans = np.c_[(np.r_[(rot, np.zeros((1, 3)))], np.r_[(move, 1.0)])] t = Transform('...
null
null
null
Make a transformation from MRI_VOXEL to MRI surface RAS (i.e. MRI).
pcsd
def make voxel ras trans move ras voxel size assert voxel size ndim == 1 assert voxel size size == 3 rot = ras T * voxel size[np newaxis ] assert rot ndim == 2 assert rot shape[0] == 3 assert rot shape[1] == 3 trans = np c [ np r [ rot np zeros 1 3 ] np r [ move 1 0 ] ] t = Transform 'mri voxel' 'mri' trans return t
5560
def _make_voxel_ras_trans(move, ras, voxel_size): assert (voxel_size.ndim == 1) assert (voxel_size.size == 3) rot = (ras.T * voxel_size[np.newaxis, :]) assert (rot.ndim == 2) assert (rot.shape[0] == 3) assert (rot.shape[1] == 3) trans = np.c_[(np.r_[(rot, np.zeros((1, 3)))], np.r_[(move, 1.0)])] t = Transform('...
Make a transformation from MRI_VOXEL to MRI surface RAS (i.e. MRI).
make a transformation from mri _ voxel to mri surface ras .
Question: What does this function do? Code: def _make_voxel_ras_trans(move, ras, voxel_size): assert (voxel_size.ndim == 1) assert (voxel_size.size == 3) rot = (ras.T * voxel_size[np.newaxis, :]) assert (rot.ndim == 2) assert (rot.shape[0] == 3) assert (rot.shape[1] == 3) trans = np.c_[(np.r_[(rot, np.zeros((...
null
null
null
What does this function do?
def getLoopListsByPath(derivation, endMultiplier, path, portionDirections): vertexes = [] loopLists = [[]] derivation.oldProjectiveSpace = None for portionDirectionIndex in xrange(len(portionDirections)): addLoop(derivation, endMultiplier, loopLists, path, portionDirectionIndex, portionDirections, vertexes) retu...
null
null
null
Get loop lists from path.
pcsd
def get Loop Lists By Path derivation end Multiplier path portion Directions vertexes = [] loop Lists = [[]] derivation old Projective Space = None for portion Direction Index in xrange len portion Directions add Loop derivation end Multiplier loop Lists path portion Direction Index portion Directions vertexes return l...
5571
def getLoopListsByPath(derivation, endMultiplier, path, portionDirections): vertexes = [] loopLists = [[]] derivation.oldProjectiveSpace = None for portionDirectionIndex in xrange(len(portionDirections)): addLoop(derivation, endMultiplier, loopLists, path, portionDirectionIndex, portionDirections, vertexes) retu...
Get loop lists from path.
get loop lists from path .
Question: What does this function do? Code: def getLoopListsByPath(derivation, endMultiplier, path, portionDirections): vertexes = [] loopLists = [[]] derivation.oldProjectiveSpace = None for portionDirectionIndex in xrange(len(portionDirections)): addLoop(derivation, endMultiplier, loopLists, path, portionDir...
null
null
null
What does this function do?
def field_isomorphism_factor(a, b): (_, factors) = factor_list(a.minpoly, extension=b) for (f, _) in factors: if (f.degree() == 1): coeffs = f.rep.TC().to_sympy_list() (d, terms) = ((len(coeffs) - 1), []) for (i, coeff) in enumerate(coeffs): terms.append((coeff * (b.root ** (d - i)))) root = Add(*te...
null
null
null
Construct field isomorphism via factorization.
pcsd
def field isomorphism factor a b factors = factor list a minpoly extension=b for f in factors if f degree == 1 coeffs = f rep TC to sympy list d terms = len coeffs - 1 [] for i coeff in enumerate coeffs terms append coeff * b root ** d - i root = Add *terms if a root - root evalf chop=True == 0 return coeffs if a root ...
5572
def field_isomorphism_factor(a, b): (_, factors) = factor_list(a.minpoly, extension=b) for (f, _) in factors: if (f.degree() == 1): coeffs = f.rep.TC().to_sympy_list() (d, terms) = ((len(coeffs) - 1), []) for (i, coeff) in enumerate(coeffs): terms.append((coeff * (b.root ** (d - i)))) root = Add(*te...
Construct field isomorphism via factorization.
construct field isomorphism via factorization .
Question: What does this function do? Code: def field_isomorphism_factor(a, b): (_, factors) = factor_list(a.minpoly, extension=b) for (f, _) in factors: if (f.degree() == 1): coeffs = f.rep.TC().to_sympy_list() (d, terms) = ((len(coeffs) - 1), []) for (i, coeff) in enumerate(coeffs): terms.append((...
null
null
null
What does this function do?
def _create_tmp_config_dir(): import getpass import tempfile from matplotlib.cbook import mkdirs try: tempdir = tempfile.gettempdir() except NotImplementedError: return None try: username = getpass.getuser() except KeyError: username = str(os.getuid()) tempdir = tempfile.mkdtemp(prefix=(u'matplotlib-%s-...
null
null
null
If the config directory can not be created, create a temporary directory. Returns None if a writable temporary directory could not be created.
pcsd
def create tmp config dir import getpass import tempfile from matplotlib cbook import mkdirs try tempdir = tempfile gettempdir except Not Implemented Error return None try username = getpass getuser except Key Error username = str os getuid tempdir = tempfile mkdtemp prefix= u'matplotlib-%s-' % username dir=tempdir os ...
5578
def _create_tmp_config_dir(): import getpass import tempfile from matplotlib.cbook import mkdirs try: tempdir = tempfile.gettempdir() except NotImplementedError: return None try: username = getpass.getuser() except KeyError: username = str(os.getuid()) tempdir = tempfile.mkdtemp(prefix=(u'matplotlib-%s-...
If the config directory can not be created, create a temporary directory. Returns None if a writable temporary directory could not be created.
if the config directory can not be created , create a temporary directory .
Question: What does this function do? Code: def _create_tmp_config_dir(): import getpass import tempfile from matplotlib.cbook import mkdirs try: tempdir = tempfile.gettempdir() except NotImplementedError: return None try: username = getpass.getuser() except KeyError: username = str(os.getuid()) temp...
null
null
null
What does this function do?
@cronjobs.register def update_monolith_stats(date=None): if date: date = datetime.datetime.strptime(date, '%Y-%m-%d').date() today = (date or datetime.date.today()) jobs = [{'metric': metric, 'date': today} for metric in tasks._get_monolith_jobs(date)] ts = [tasks.update_monolith_stats.subtask(kwargs=kw) for kw i...
null
null
null
Update monolith statistics.
pcsd
@cronjobs register def update monolith stats date=None if date date = datetime datetime strptime date '%Y-%m-%d' date today = date or datetime date today jobs = [{'metric' metric 'date' today} for metric in tasks get monolith jobs date ] ts = [tasks update monolith stats subtask kwargs=kw for kw in jobs] Task Set ts ap...
5579
@cronjobs.register def update_monolith_stats(date=None): if date: date = datetime.datetime.strptime(date, '%Y-%m-%d').date() today = (date or datetime.date.today()) jobs = [{'metric': metric, 'date': today} for metric in tasks._get_monolith_jobs(date)] ts = [tasks.update_monolith_stats.subtask(kwargs=kw) for kw i...
Update monolith statistics.
update monolith statistics .
Question: What does this function do? Code: @cronjobs.register def update_monolith_stats(date=None): if date: date = datetime.datetime.strptime(date, '%Y-%m-%d').date() today = (date or datetime.date.today()) jobs = [{'metric': metric, 'date': today} for metric in tasks._get_monolith_jobs(date)] ts = [tasks.up...
null
null
null
What does this function do?
def manipulator_valid_rel_key(f, self, field_data, all_data): klass = f.rel.to try: klass._default_manager.get(**{f.rel.field_name: field_data}) except klass.DoesNotExist: raise validators.ValidationError, (_('Please enter a valid %s.') % f.verbose_name)
null
null
null
Validates that the value is a valid foreign key
pcsd
def manipulator valid rel key f self field data all data klass = f rel to try klass default manager get **{f rel field name field data} except klass Does Not Exist raise validators Validation Error 'Please enter a valid %s ' % f verbose name
5582
def manipulator_valid_rel_key(f, self, field_data, all_data): klass = f.rel.to try: klass._default_manager.get(**{f.rel.field_name: field_data}) except klass.DoesNotExist: raise validators.ValidationError, (_('Please enter a valid %s.') % f.verbose_name)
Validates that the value is a valid foreign key
validates that the value is a valid foreign key
Question: What does this function do? Code: def manipulator_valid_rel_key(f, self, field_data, all_data): klass = f.rel.to try: klass._default_manager.get(**{f.rel.field_name: field_data}) except klass.DoesNotExist: raise validators.ValidationError, (_('Please enter a valid %s.') % f.verbose_name)
null
null
null
What does this function do?
def get_form_data(): if is_form_submitted(): formdata = request.form if request.files: formdata = formdata.copy() formdata.update(request.files) return formdata return None
null
null
null
If current method is PUT or POST, return concatenated `request.form` with `request.files` or `None` otherwise.
pcsd
def get form data if is form submitted formdata = request form if request files formdata = formdata copy formdata update request files return formdata return None
5587
def get_form_data(): if is_form_submitted(): formdata = request.form if request.files: formdata = formdata.copy() formdata.update(request.files) return formdata return None
If current method is PUT or POST, return concatenated `request.form` with `request.files` or `None` otherwise.
if current method is put or post , return concatenated request . form with request . files or none otherwise .
Question: What does this function do? Code: def get_form_data(): if is_form_submitted(): formdata = request.form if request.files: formdata = formdata.copy() formdata.update(request.files) return formdata return None
null
null
null
What does this function do?
def parse_args(): parser = argparse.ArgumentParser(description='Ansible FreeIPA/IPA inventory module') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--list', action='store_true', help='List active servers') group.add_argument('--host', help='List details about the specified host') ...
null
null
null
This function parses the arguments that were passed in via the command line. This function expects no arguments.
pcsd
def parse args parser = argparse Argument Parser description='Ansible Free IPA/IPA inventory module' group = parser add mutually exclusive group required=True group add argument '--list' action='store true' help='List active servers' group add argument '--host' help='List details about the specified host' return parser...
5589
def parse_args(): parser = argparse.ArgumentParser(description='Ansible FreeIPA/IPA inventory module') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--list', action='store_true', help='List active servers') group.add_argument('--host', help='List details about the specified host') ...
This function parses the arguments that were passed in via the command line. This function expects no arguments.
this function parses the arguments that were passed in via the command line .
Question: What does this function do? Code: def parse_args(): parser = argparse.ArgumentParser(description='Ansible FreeIPA/IPA inventory module') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--list', action='store_true', help='List active servers') group.add_argument('--host', ...
null
null
null
What does this function do?
def login(request, browser, app, attempt=1): success = False (provider_name, provider) = request.param log(1, provider_name, 'Attempt {0}'.format(attempt)) def wait(indent, seconds): seconds = (seconds or 0) seconds = (seconds * config.WAIT_MULTIPLIER) if (seconds < config.MIN_WAIT): seconds = config.MIN_W...
null
null
null
Runs for each provider.
pcsd
def login request browser app attempt=1 success = False provider name provider = request param log 1 provider name 'Attempt {0}' format attempt def wait indent seconds seconds = seconds or 0 seconds = seconds * config WAIT MULTIPLIER if seconds < config MIN WAIT seconds = config MIN WAIT if seconds log indent provider ...
5592
def login(request, browser, app, attempt=1): success = False (provider_name, provider) = request.param log(1, provider_name, 'Attempt {0}'.format(attempt)) def wait(indent, seconds): seconds = (seconds or 0) seconds = (seconds * config.WAIT_MULTIPLIER) if (seconds < config.MIN_WAIT): seconds = config.MIN_W...
Runs for each provider.
runs for each provider .
Question: What does this function do? Code: def login(request, browser, app, attempt=1): success = False (provider_name, provider) = request.param log(1, provider_name, 'Attempt {0}'.format(attempt)) def wait(indent, seconds): seconds = (seconds or 0) seconds = (seconds * config.WAIT_MULTIPLIER) if (second...
null
null
null
What does this function do?
def hooks_namespace(k, v): hookpoint = k.split('.', 1)[0] if isinstance(v, basestring): v = cherrypy.lib.attributes(v) if (not isinstance(v, Hook)): v = Hook(v) cherrypy.serving.request.hooks[hookpoint].append(v)
null
null
null
Attach bare hooks declared in config.
pcsd
def hooks namespace k v hookpoint = k split ' ' 1 [0] if isinstance v basestring v = cherrypy lib attributes v if not isinstance v Hook v = Hook v cherrypy serving request hooks[hookpoint] append v
5596
def hooks_namespace(k, v): hookpoint = k.split('.', 1)[0] if isinstance(v, basestring): v = cherrypy.lib.attributes(v) if (not isinstance(v, Hook)): v = Hook(v) cherrypy.serving.request.hooks[hookpoint].append(v)
Attach bare hooks declared in config.
attach bare hooks declared in config .
Question: What does this function do? Code: def hooks_namespace(k, v): hookpoint = k.split('.', 1)[0] if isinstance(v, basestring): v = cherrypy.lib.attributes(v) if (not isinstance(v, Hook)): v = Hook(v) cherrypy.serving.request.hooks[hookpoint].append(v)
null
null
null
What does this function do?
@decorator.decorator def add_mask_if_none(f, clip, *a, **k): if (clip.mask is None): clip = clip.add_mask() return f(clip, *a, **k)
null
null
null
Add a mask to the clip if there is none.
pcsd
@decorator decorator def add mask if none f clip *a **k if clip mask is None clip = clip add mask return f clip *a **k
5597
@decorator.decorator def add_mask_if_none(f, clip, *a, **k): if (clip.mask is None): clip = clip.add_mask() return f(clip, *a, **k)
Add a mask to the clip if there is none.
add a mask to the clip if there is none .
Question: What does this function do? Code: @decorator.decorator def add_mask_if_none(f, clip, *a, **k): if (clip.mask is None): clip = clip.add_mask() return f(clip, *a, **k)
null
null
null
What does this function do?
@commands(u'py') @example(u'.py len([1,2,3])', u'3') def py(bot, trigger): if (not trigger.group(2)): return bot.say(u'Need an expression to evaluate') query = trigger.group(2) uri = (BASE_TUMBOLIA_URI + u'py/') answer = web.get((uri + web.quote(query))) if answer: bot.reply(answer) else: bot.reply(u'Sorry,...
null
null
null
Evaluate a Python expression.
pcsd
@commands u'py' @example u' py len [1 2 3] ' u'3' def py bot trigger if not trigger group 2 return bot say u'Need an expression to evaluate' query = trigger group 2 uri = BASE TUMBOLIA URI + u'py/' answer = web get uri + web quote query if answer bot reply answer else bot reply u'Sorry no result '
5608
@commands(u'py') @example(u'.py len([1,2,3])', u'3') def py(bot, trigger): if (not trigger.group(2)): return bot.say(u'Need an expression to evaluate') query = trigger.group(2) uri = (BASE_TUMBOLIA_URI + u'py/') answer = web.get((uri + web.quote(query))) if answer: bot.reply(answer) else: bot.reply(u'Sorry,...
Evaluate a Python expression.
evaluate a python expression .
Question: What does this function do? Code: @commands(u'py') @example(u'.py len([1,2,3])', u'3') def py(bot, trigger): if (not trigger.group(2)): return bot.say(u'Need an expression to evaluate') query = trigger.group(2) uri = (BASE_TUMBOLIA_URI + u'py/') answer = web.get((uri + web.quote(query))) if answer: ...
null
null
null
What does this function do?
@with_setup(step_runner_environ) def test_failing_behave_as_step_raises_assertion(): runnable_step = Step.from_string('Given I have a step which calls the "other step fails" step with behave_as') assert_raises(AssertionError, runnable_step.run, True)
null
null
null
When a step definition calls another (failing) step definition with behave_as, that step should be marked a failure.
pcsd
@with setup step runner environ def test failing behave as step raises assertion runnable step = Step from string 'Given I have a step which calls the "other step fails" step with behave as' assert raises Assertion Error runnable step run True
5609
@with_setup(step_runner_environ) def test_failing_behave_as_step_raises_assertion(): runnable_step = Step.from_string('Given I have a step which calls the "other step fails" step with behave_as') assert_raises(AssertionError, runnable_step.run, True)
When a step definition calls another (failing) step definition with behave_as, that step should be marked a failure.
when a step definition calls another step definition with behave _ as , that step should be marked a failure .
Question: What does this function do? Code: @with_setup(step_runner_environ) def test_failing_behave_as_step_raises_assertion(): runnable_step = Step.from_string('Given I have a step which calls the "other step fails" step with behave_as') assert_raises(AssertionError, runnable_step.run, True)
null
null
null
What does this function do?
def bitsource(zcontext, url): zsock = zcontext.socket(zmq.PUB) zsock.bind(url) while True: zsock.send_string(ones_and_zeros((B * 2))) time.sleep(0.01)
null
null
null
Produce random points in the unit square.
pcsd
def bitsource zcontext url zsock = zcontext socket zmq PUB zsock bind url while True zsock send string ones and zeros B * 2 time sleep 0 01
5612
def bitsource(zcontext, url): zsock = zcontext.socket(zmq.PUB) zsock.bind(url) while True: zsock.send_string(ones_and_zeros((B * 2))) time.sleep(0.01)
Produce random points in the unit square.
produce random points in the unit square .
Question: What does this function do? Code: def bitsource(zcontext, url): zsock = zcontext.socket(zmq.PUB) zsock.bind(url) while True: zsock.send_string(ones_and_zeros((B * 2))) time.sleep(0.01)
null
null
null
What does this function do?
def update_last_login(sender, user, **kwargs): user.last_login = timezone.now() user.save(update_fields=[u'last_login'])
null
null
null
A signal receiver which updates the last_login date for the user logging in.
pcsd
def update last login sender user **kwargs user last login = timezone now user save update fields=[u'last login']
5614
def update_last_login(sender, user, **kwargs): user.last_login = timezone.now() user.save(update_fields=[u'last_login'])
A signal receiver which updates the last_login date for the user logging in.
a signal receiver which updates the last _ login date for the user logging in .
Question: What does this function do? Code: def update_last_login(sender, user, **kwargs): user.last_login = timezone.now() user.save(update_fields=[u'last_login'])
null
null
null
What does this function do?
def create_tmp_dir(function): @functools.wraps(function) def decorated_function(*args, **kwargs): tmp_dir_path = tempfile.mkdtemp() kwargs['tmp_dir_path'] = tmp_dir_path try: return function(*args, **kwargs) finally: utils.execute('rm', '-rf', tmp_dir_path) return decorated_function
null
null
null
Creates temporary directory for rsync purposes. Removes created directory in the end.
pcsd
def create tmp dir function @functools wraps function def decorated function *args **kwargs tmp dir path = tempfile mkdtemp kwargs['tmp dir path'] = tmp dir path try return function *args **kwargs finally utils execute 'rm' '-rf' tmp dir path return decorated function
5620
def create_tmp_dir(function): @functools.wraps(function) def decorated_function(*args, **kwargs): tmp_dir_path = tempfile.mkdtemp() kwargs['tmp_dir_path'] = tmp_dir_path try: return function(*args, **kwargs) finally: utils.execute('rm', '-rf', tmp_dir_path) return decorated_function
Creates temporary directory for rsync purposes. Removes created directory in the end.
creates temporary directory for rsync purposes .
Question: What does this function do? Code: def create_tmp_dir(function): @functools.wraps(function) def decorated_function(*args, **kwargs): tmp_dir_path = tempfile.mkdtemp() kwargs['tmp_dir_path'] = tmp_dir_path try: return function(*args, **kwargs) finally: utils.execute('rm', '-rf', tmp_dir_path)...
null
null
null
What does this function do?
def getHelixComplexPath(derivation, xmlElement): helixTypeFirstCharacter = derivation.helixType.lower()[:1] if (helixTypeFirstCharacter == 'b'): return [complex(), complex(1.0, 1.0)] if (helixTypeFirstCharacter == 'h'): return [complex(), complex(0.5, 0.5), complex(1.0, 0.0)] if (helixTypeFirstCharacter == 'p')...
null
null
null
Set gear helix path.
pcsd
def get Helix Complex Path derivation xml Element helix Type First Character = derivation helix Type lower [ 1] if helix Type First Character == 'b' return [complex complex 1 0 1 0 ] if helix Type First Character == 'h' return [complex complex 0 5 0 5 complex 1 0 0 0 ] if helix Type First Character == 'p' helix Complex...
5628
def getHelixComplexPath(derivation, xmlElement): helixTypeFirstCharacter = derivation.helixType.lower()[:1] if (helixTypeFirstCharacter == 'b'): return [complex(), complex(1.0, 1.0)] if (helixTypeFirstCharacter == 'h'): return [complex(), complex(0.5, 0.5), complex(1.0, 0.0)] if (helixTypeFirstCharacter == 'p')...
Set gear helix path.
set gear helix path .
Question: What does this function do? Code: def getHelixComplexPath(derivation, xmlElement): helixTypeFirstCharacter = derivation.helixType.lower()[:1] if (helixTypeFirstCharacter == 'b'): return [complex(), complex(1.0, 1.0)] if (helixTypeFirstCharacter == 'h'): return [complex(), complex(0.5, 0.5), complex(...
null
null
null
What does this function do?
@app.route('/libtoggle', methods=['POST']) def review(): if (not g.user): return 'NO' idvv = request.form['pid'] if (not isvalidid(idvv)): return 'NO' pid = strip_version(idvv) if (not (pid in db)): return 'NO' uid = session['user_id'] record = query_db('select * from library where\n user_id = ? a...
null
null
null
user wants to toggle a paper in his library
pcsd
@app route '/libtoggle' methods=['POST'] def review if not g user return 'NO' idvv = request form['pid'] if not isvalidid idvv return 'NO' pid = strip version idvv if not pid in db return 'NO' uid = session['user id'] record = query db 'select * from library where user id = ? and paper id = ?' [uid pid] one=True print ...
5629
@app.route('/libtoggle', methods=['POST']) def review(): if (not g.user): return 'NO' idvv = request.form['pid'] if (not isvalidid(idvv)): return 'NO' pid = strip_version(idvv) if (not (pid in db)): return 'NO' uid = session['user_id'] record = query_db('select * from library where\n user_id = ? a...
user wants to toggle a paper in his library
user wants to toggle a paper in his library
Question: What does this function do? Code: @app.route('/libtoggle', methods=['POST']) def review(): if (not g.user): return 'NO' idvv = request.form['pid'] if (not isvalidid(idvv)): return 'NO' pid = strip_version(idvv) if (not (pid in db)): return 'NO' uid = session['user_id'] record = query_db('selec...
null
null
null
What does this function do?
def blockList2Matrix(l): dims = [m.shape[0] for m in l] s = sum(dims) res = zeros((s, s)) index = 0 for i in range(len(l)): d = dims[i] m = l[i] res[index:(index + d), index:(index + d)] = m index += d return res
null
null
null
Converts a list of matrices into a corresponding big block-diagonal one.
pcsd
def block List2Matrix l dims = [m shape[0] for m in l] s = sum dims res = zeros s s index = 0 for i in range len l d = dims[i] m = l[i] res[index index + d index index + d ] = m index += d return res
5634
def blockList2Matrix(l): dims = [m.shape[0] for m in l] s = sum(dims) res = zeros((s, s)) index = 0 for i in range(len(l)): d = dims[i] m = l[i] res[index:(index + d), index:(index + d)] = m index += d return res
Converts a list of matrices into a corresponding big block-diagonal one.
converts a list of matrices into a corresponding big block - diagonal one .
Question: What does this function do? Code: def blockList2Matrix(l): dims = [m.shape[0] for m in l] s = sum(dims) res = zeros((s, s)) index = 0 for i in range(len(l)): d = dims[i] m = l[i] res[index:(index + d), index:(index + d)] = m index += d return res
null
null
null
What does this function do?
def which_bin(exes): if (not isinstance(exes, collections.Iterable)): return None for exe in exes: path = which(exe) if (not path): continue return path return None
null
null
null
Scan over some possible executables and return the first one that is found
pcsd
def which bin exes if not isinstance exes collections Iterable return None for exe in exes path = which exe if not path continue return path return None
5640
def which_bin(exes): if (not isinstance(exes, collections.Iterable)): return None for exe in exes: path = which(exe) if (not path): continue return path return None
Scan over some possible executables and return the first one that is found
scan over some possible executables and return the first one that is found
Question: What does this function do? Code: def which_bin(exes): if (not isinstance(exes, collections.Iterable)): return None for exe in exes: path = which(exe) if (not path): continue return path return None
null
null
null
What does this function do?
@check_login_required @check_local_site_access def group_list(request, local_site=None, template_name=u'datagrids/datagrid.html'): grid = GroupDataGrid(request, local_site=local_site) return grid.render_to_response(template_name)
null
null
null
Display a list of all review groups.
pcsd
@check login required @check local site access def group list request local site=None template name=u'datagrids/datagrid html' grid = Group Data Grid request local site=local site return grid render to response template name
5641
@check_login_required @check_local_site_access def group_list(request, local_site=None, template_name=u'datagrids/datagrid.html'): grid = GroupDataGrid(request, local_site=local_site) return grid.render_to_response(template_name)
Display a list of all review groups.
display a list of all review groups .
Question: What does this function do? Code: @check_login_required @check_local_site_access def group_list(request, local_site=None, template_name=u'datagrids/datagrid.html'): grid = GroupDataGrid(request, local_site=local_site) return grid.render_to_response(template_name)
null
null
null
What does this function do?
def sanitize_url(url, hide_fields): if isinstance(hide_fields, list): url_comps = splitquery(url) log_url = url_comps[0] if (len(url_comps) > 1): log_url += '?' for pair in url_comps[1:]: url_tmp = None for field in hide_fields: comps_list = pair.split('&') if url_tmp: url_tmp = url_tmp.s...
null
null
null
Make sure no secret fields show up in logs
pcsd
def sanitize url url hide fields if isinstance hide fields list url comps = splitquery url log url = url comps[0] if len url comps > 1 log url += '?' for pair in url comps[1 ] url tmp = None for field in hide fields comps list = pair split '&' if url tmp url tmp = url tmp split '&' url tmp = sanitize url components url...
5658
def sanitize_url(url, hide_fields): if isinstance(hide_fields, list): url_comps = splitquery(url) log_url = url_comps[0] if (len(url_comps) > 1): log_url += '?' for pair in url_comps[1:]: url_tmp = None for field in hide_fields: comps_list = pair.split('&') if url_tmp: url_tmp = url_tmp.s...
Make sure no secret fields show up in logs
make sure no secret fields show up in logs
Question: What does this function do? Code: def sanitize_url(url, hide_fields): if isinstance(hide_fields, list): url_comps = splitquery(url) log_url = url_comps[0] if (len(url_comps) > 1): log_url += '?' for pair in url_comps[1:]: url_tmp = None for field in hide_fields: comps_list = pair.spli...
null
null
null
What does this function do?
@require_POST @login_required @permission_required_or_403('forums_forum.thread_locked_forum', (Forum, 'slug__iexact', 'forum_slug')) def lock_thread(request, forum_slug, thread_id): forum = get_object_or_404(Forum, slug=forum_slug) thread = get_object_or_404(Thread, pk=thread_id, forum=forum) thread.is_locked = (not...
null
null
null
Lock/Unlock a thread.
pcsd
@require POST @login required @permission required or 403 'forums forum thread locked forum' Forum 'slug iexact' 'forum slug' def lock thread request forum slug thread id forum = get object or 404 Forum slug=forum slug thread = get object or 404 Thread pk=thread id forum=forum thread is locked = not thread is locked lo...
5659
@require_POST @login_required @permission_required_or_403('forums_forum.thread_locked_forum', (Forum, 'slug__iexact', 'forum_slug')) def lock_thread(request, forum_slug, thread_id): forum = get_object_or_404(Forum, slug=forum_slug) thread = get_object_or_404(Thread, pk=thread_id, forum=forum) thread.is_locked = (not...
Lock/Unlock a thread.
lock / unlock a thread .
Question: What does this function do? Code: @require_POST @login_required @permission_required_or_403('forums_forum.thread_locked_forum', (Forum, 'slug__iexact', 'forum_slug')) def lock_thread(request, forum_slug, thread_id): forum = get_object_or_404(Forum, slug=forum_slug) thread = get_object_or_404(Thread, pk=t...
null
null
null
What does this function do?
def _AddHasFieldMethod(message_descriptor, cls): singular_fields = {} for field in message_descriptor.fields: if (field.label != _FieldDescriptor.LABEL_REPEATED): singular_fields[field.name] = field def HasField(self, field_name): try: field = singular_fields[field_name] except KeyError: raise ValueEr...
null
null
null
Helper for _AddMessageMethods().
pcsd
def Add Has Field Method message descriptor cls singular fields = {} for field in message descriptor fields if field label != Field Descriptor LABEL REPEATED singular fields[field name] = field def Has Field self field name try field = singular fields[field name] except Key Error raise Value Error 'Protocol message has...
5670
def _AddHasFieldMethod(message_descriptor, cls): singular_fields = {} for field in message_descriptor.fields: if (field.label != _FieldDescriptor.LABEL_REPEATED): singular_fields[field.name] = field def HasField(self, field_name): try: field = singular_fields[field_name] except KeyError: raise ValueEr...
Helper for _AddMessageMethods().
helper for _ addmessagemethods ( ) .
Question: What does this function do? Code: def _AddHasFieldMethod(message_descriptor, cls): singular_fields = {} for field in message_descriptor.fields: if (field.label != _FieldDescriptor.LABEL_REPEATED): singular_fields[field.name] = field def HasField(self, field_name): try: field = singular_fields[...
null
null
null
What does this function do?
def addHeightsByBitmap(heights, textLines): for line in textLines[3:]: for integerWord in line.split(): heights.append(float(integerWord))
null
null
null
Add heights by bitmap.
pcsd
def add Heights By Bitmap heights text Lines for line in text Lines[3 ] for integer Word in line split heights append float integer Word
5671
def addHeightsByBitmap(heights, textLines): for line in textLines[3:]: for integerWord in line.split(): heights.append(float(integerWord))
Add heights by bitmap.
add heights by bitmap .
Question: What does this function do? Code: def addHeightsByBitmap(heights, textLines): for line in textLines[3:]: for integerWord in line.split(): heights.append(float(integerWord))
null
null
null
What does this function do?
def introduce_vdi(session, sr_ref, vdi_uuid=None, target_lun=None): try: vdi_ref = _get_vdi_ref(session, sr_ref, vdi_uuid, target_lun) if (vdi_ref is None): greenthread.sleep(CONF.xenserver.introduce_vdi_retry_wait) session.call_xenapi('SR.scan', sr_ref) vdi_ref = _get_vdi_ref(session, sr_ref, vdi_uuid, t...
null
null
null
Introduce VDI in the host.
pcsd
def introduce vdi session sr ref vdi uuid=None target lun=None try vdi ref = get vdi ref session sr ref vdi uuid target lun if vdi ref is None greenthread sleep CONF xenserver introduce vdi retry wait session call xenapi 'SR scan' sr ref vdi ref = get vdi ref session sr ref vdi uuid target lun except session Xen API Fa...
5676
def introduce_vdi(session, sr_ref, vdi_uuid=None, target_lun=None): try: vdi_ref = _get_vdi_ref(session, sr_ref, vdi_uuid, target_lun) if (vdi_ref is None): greenthread.sleep(CONF.xenserver.introduce_vdi_retry_wait) session.call_xenapi('SR.scan', sr_ref) vdi_ref = _get_vdi_ref(session, sr_ref, vdi_uuid, t...
Introduce VDI in the host.
introduce vdi in the host .
Question: What does this function do? Code: def introduce_vdi(session, sr_ref, vdi_uuid=None, target_lun=None): try: vdi_ref = _get_vdi_ref(session, sr_ref, vdi_uuid, target_lun) if (vdi_ref is None): greenthread.sleep(CONF.xenserver.introduce_vdi_retry_wait) session.call_xenapi('SR.scan', sr_ref) vdi_...
null
null
null
What does this function do?
def create_appscale_user(password, uaserver): does_user_exist = uaserver.does_user_exist(hermes_constants.USER_EMAIL, appscale_info.get_secret()) if (does_user_exist == 'true'): logging.debug('User {0} already exists, so not creating it again.'.format(hermes_constants.USER_EMAIL)) return True elif (uaserver.comm...
null
null
null
Creates the user account with the email address and password provided.
pcsd
def create appscale user password uaserver does user exist = uaserver does user exist hermes constants USER EMAIL appscale info get secret if does user exist == 'true' logging debug 'User {0} already exists so not creating it again ' format hermes constants USER EMAIL return True elif uaserver commit new user hermes co...
5679
def create_appscale_user(password, uaserver): does_user_exist = uaserver.does_user_exist(hermes_constants.USER_EMAIL, appscale_info.get_secret()) if (does_user_exist == 'true'): logging.debug('User {0} already exists, so not creating it again.'.format(hermes_constants.USER_EMAIL)) return True elif (uaserver.comm...
Creates the user account with the email address and password provided.
creates the user account with the email address and password provided .
Question: What does this function do? Code: def create_appscale_user(password, uaserver): does_user_exist = uaserver.does_user_exist(hermes_constants.USER_EMAIL, appscale_info.get_secret()) if (does_user_exist == 'true'): logging.debug('User {0} already exists, so not creating it again.'.format(hermes_constants....
null
null
null
What does this function do?
def randperm(n): r = range(n) x = [] while r: i = random.choice(r) x.append(i) r.remove(i) return x
null
null
null
Function returning a random permutation of range(n).
pcsd
def randperm n r = range n x = [] while r i = random choice r x append i r remove i return x
5681
def randperm(n): r = range(n) x = [] while r: i = random.choice(r) x.append(i) r.remove(i) return x
Function returning a random permutation of range(n).
function returning a random permutation of range ( n ) .
Question: What does this function do? Code: def randperm(n): r = range(n) x = [] while r: i = random.choice(r) x.append(i) r.remove(i) return x
null
null
null
What does this function do?
def _type_map(): global _cached_type_map if (_cached_type_map is None): _cached_type_map = {ffi.typeof('char'): types.char, ffi.typeof('short'): types.short, ffi.typeof('int'): types.intc, ffi.typeof('long'): types.long_, ffi.typeof('long long'): types.longlong, ffi.typeof('unsigned char'): types.uchar, ffi.typeof(...
null
null
null
Lazily compute type map, as calling ffi.typeof() involves costly parsing of C code...
pcsd
def type map global cached type map if cached type map is None cached type map = {ffi typeof 'char' types char ffi typeof 'short' types short ffi typeof 'int' types intc ffi typeof 'long' types long ffi typeof 'long long' types longlong ffi typeof 'unsigned char' types uchar ffi typeof 'unsigned short' types ushort ffi...
5682
def _type_map(): global _cached_type_map if (_cached_type_map is None): _cached_type_map = {ffi.typeof('char'): types.char, ffi.typeof('short'): types.short, ffi.typeof('int'): types.intc, ffi.typeof('long'): types.long_, ffi.typeof('long long'): types.longlong, ffi.typeof('unsigned char'): types.uchar, ffi.typeof(...
Lazily compute type map, as calling ffi.typeof() involves costly parsing of C code...
lazily compute type map , as calling ffi . typeof ( ) involves costly parsing of c code . . .
Question: What does this function do? Code: def _type_map(): global _cached_type_map if (_cached_type_map is None): _cached_type_map = {ffi.typeof('char'): types.char, ffi.typeof('short'): types.short, ffi.typeof('int'): types.intc, ffi.typeof('long'): types.long_, ffi.typeof('long long'): types.longlong, ffi.ty...
null
null
null
What does this function do?
def check_conflicts(unmerged): if prefs.check_conflicts(): unmerged = [path for path in unmerged if is_conflict_free(path)] return unmerged
null
null
null
Check paths for conflicts Conflicting files can be filtered out one-by-one.
pcsd
def check conflicts unmerged if prefs check conflicts unmerged = [path for path in unmerged if is conflict free path ] return unmerged
5683
def check_conflicts(unmerged): if prefs.check_conflicts(): unmerged = [path for path in unmerged if is_conflict_free(path)] return unmerged
Check paths for conflicts Conflicting files can be filtered out one-by-one.
check paths for conflicts
Question: What does this function do? Code: def check_conflicts(unmerged): if prefs.check_conflicts(): unmerged = [path for path in unmerged if is_conflict_free(path)] return unmerged
null
null
null
What does this function do?
def write_flv_header(stream): stream.write('FLV\x01') stream.write('\x05') stream.write('\x00\x00\x00 DCTB ') stream.write('\x00\x00\x00\x00')
null
null
null
Writes the FLV header to stream
pcsd
def write flv header stream stream write 'FLV\x01' stream write '\x05' stream write '\x00\x00\x00 DCTB ' stream write '\x00\x00\x00\x00'
5688
def write_flv_header(stream): stream.write('FLV\x01') stream.write('\x05') stream.write('\x00\x00\x00 DCTB ') stream.write('\x00\x00\x00\x00')
Writes the FLV header to stream
writes the flv header to stream
Question: What does this function do? Code: def write_flv_header(stream): stream.write('FLV\x01') stream.write('\x05') stream.write('\x00\x00\x00 DCTB ') stream.write('\x00\x00\x00\x00')
null
null
null
What does this function do?
def load_model(path_to_models, path_to_tables): path_to_umodel = (path_to_models + 'uni_skip.npz') path_to_bmodel = (path_to_models + 'bi_skip.npz') with open(('%s.pkl' % path_to_umodel), 'rb') as f: uoptions = pkl.load(f) with open(('%s.pkl' % path_to_bmodel), 'rb') as f: boptions = pkl.load(f) uparams = init...
null
null
null
Load the model with saved tables
pcsd
def load model path to models path to tables path to umodel = path to models + 'uni skip npz' path to bmodel = path to models + 'bi skip npz' with open '%s pkl' % path to umodel 'rb' as f uoptions = pkl load f with open '%s pkl' % path to bmodel 'rb' as f boptions = pkl load f uparams = init params uoptions uparams = l...
5694
def load_model(path_to_models, path_to_tables): path_to_umodel = (path_to_models + 'uni_skip.npz') path_to_bmodel = (path_to_models + 'bi_skip.npz') with open(('%s.pkl' % path_to_umodel), 'rb') as f: uoptions = pkl.load(f) with open(('%s.pkl' % path_to_bmodel), 'rb') as f: boptions = pkl.load(f) uparams = init...
Load the model with saved tables
load the model with saved tables
Question: What does this function do? Code: def load_model(path_to_models, path_to_tables): path_to_umodel = (path_to_models + 'uni_skip.npz') path_to_bmodel = (path_to_models + 'bi_skip.npz') with open(('%s.pkl' % path_to_umodel), 'rb') as f: uoptions = pkl.load(f) with open(('%s.pkl' % path_to_bmodel), 'rb')...
null
null
null
What does this function do?
def _MakeArgs(amazon_collection_map, google_collection_map): request_list = [] for (url, label) in amazon_collection_map.iteritems(): request_list.append(CloudMetadataRequest(bios_version_regex=AMAZON_BIOS_REGEX, service_name_regex=AMAZON_SERVICE_REGEX, instance_type='AMAZON', timeout=1.0, url=url, label=label)) f...
null
null
null
Build metadata requests list from collection maps.
pcsd
def Make Args amazon collection map google collection map request list = [] for url label in amazon collection map iteritems request list append Cloud Metadata Request bios version regex=AMAZON BIOS REGEX service name regex=AMAZON SERVICE REGEX instance type='AMAZON' timeout=1 0 url=url label=label for url label in goo...
5696
def _MakeArgs(amazon_collection_map, google_collection_map): request_list = [] for (url, label) in amazon_collection_map.iteritems(): request_list.append(CloudMetadataRequest(bios_version_regex=AMAZON_BIOS_REGEX, service_name_regex=AMAZON_SERVICE_REGEX, instance_type='AMAZON', timeout=1.0, url=url, label=label)) f...
Build metadata requests list from collection maps.
build metadata requests list from collection maps .
Question: What does this function do? Code: def _MakeArgs(amazon_collection_map, google_collection_map): request_list = [] for (url, label) in amazon_collection_map.iteritems(): request_list.append(CloudMetadataRequest(bios_version_regex=AMAZON_BIOS_REGEX, service_name_regex=AMAZON_SERVICE_REGEX, instance_type='...
null
null
null
What does this function do?
def get_role_ids(course_id): roles = Role.objects.filter(course_id=course_id).exclude(name=FORUM_ROLE_STUDENT) return dict([(role.name, list(role.users.values_list('id', flat=True))) for role in roles])
null
null
null
Returns a dictionary having role names as keys and a list of users as values
pcsd
def get role ids course id roles = Role objects filter course id=course id exclude name=FORUM ROLE STUDENT return dict [ role name list role users values list 'id' flat=True for role in roles]
5707
def get_role_ids(course_id): roles = Role.objects.filter(course_id=course_id).exclude(name=FORUM_ROLE_STUDENT) return dict([(role.name, list(role.users.values_list('id', flat=True))) for role in roles])
Returns a dictionary having role names as keys and a list of users as values
returns a dictionary having role names as keys and a list of users as values
Question: What does this function do? Code: def get_role_ids(course_id): roles = Role.objects.filter(course_id=course_id).exclude(name=FORUM_ROLE_STUDENT) return dict([(role.name, list(role.users.values_list('id', flat=True))) for role in roles])
null
null
null
What does this function do?
def control_queue_from_config(config): return Queue(('control.%s' % config.server_name), galaxy_exchange, routing_key='control')
null
null
null
Returns a Queue instance with the correct name and routing key for this galaxy process\'s config
pcsd
def control queue from config config return Queue 'control %s' % config server name galaxy exchange routing key='control'
5710
def control_queue_from_config(config): return Queue(('control.%s' % config.server_name), galaxy_exchange, routing_key='control')
Returns a Queue instance with the correct name and routing key for this galaxy process\'s config
returns a queue instance with the correct name and routing key for this galaxy processs config
Question: What does this function do? Code: def control_queue_from_config(config): return Queue(('control.%s' % config.server_name), galaxy_exchange, routing_key='control')
null
null
null
What does this function do?
def get_category_or_404(path): path_bits = [p for p in path.split('/') if p] return get_object_or_404(Category, slug=path_bits[(-1)])
null
null
null
Retrieve a Category instance by a path.
pcsd
def get category or 404 path path bits = [p for p in path split '/' if p] return get object or 404 Category slug=path bits[ -1 ]
5717
def get_category_or_404(path): path_bits = [p for p in path.split('/') if p] return get_object_or_404(Category, slug=path_bits[(-1)])
Retrieve a Category instance by a path.
retrieve a category instance by a path .
Question: What does this function do? Code: def get_category_or_404(path): path_bits = [p for p in path.split('/') if p] return get_object_or_404(Category, slug=path_bits[(-1)])
null
null
null
What does this function do?
def handle_empty_queue(): if (sabnzbd.nzbqueue.NzbQueue.do.actives() == 0): sabnzbd.save_state() logging.info('Queue has finished, launching: %s (%s)', sabnzbd.QUEUECOMPLETEACTION, sabnzbd.QUEUECOMPLETEARG) if sabnzbd.QUEUECOMPLETEARG: sabnzbd.QUEUECOMPLETEACTION(sabnzbd.QUEUECOMPLETEARG) else: Thread(ta...
null
null
null
Check if empty queue calls for action
pcsd
def handle empty queue if sabnzbd nzbqueue Nzb Queue do actives == 0 sabnzbd save state logging info 'Queue has finished launching %s %s ' sabnzbd QUEUECOMPLETEACTION sabnzbd QUEUECOMPLETEARG if sabnzbd QUEUECOMPLETEARG sabnzbd QUEUECOMPLETEACTION sabnzbd QUEUECOMPLETEARG else Thread target=sabnzbd QUEUECOMPLETEACTION ...
5718
def handle_empty_queue(): if (sabnzbd.nzbqueue.NzbQueue.do.actives() == 0): sabnzbd.save_state() logging.info('Queue has finished, launching: %s (%s)', sabnzbd.QUEUECOMPLETEACTION, sabnzbd.QUEUECOMPLETEARG) if sabnzbd.QUEUECOMPLETEARG: sabnzbd.QUEUECOMPLETEACTION(sabnzbd.QUEUECOMPLETEARG) else: Thread(ta...
Check if empty queue calls for action
check if empty queue calls for action
Question: What does this function do? Code: def handle_empty_queue(): if (sabnzbd.nzbqueue.NzbQueue.do.actives() == 0): sabnzbd.save_state() logging.info('Queue has finished, launching: %s (%s)', sabnzbd.QUEUECOMPLETEACTION, sabnzbd.QUEUECOMPLETEARG) if sabnzbd.QUEUECOMPLETEARG: sabnzbd.QUEUECOMPLETEACTION...
null
null
null
What does this function do?
def render_to_string(template_name, context=None, request=None, using=None): if isinstance(template_name, (list, tuple)): template = select_template(template_name, using=using) else: template = get_template(template_name, using=using) return template.render(context, request)
null
null
null
Loads a template and renders it with a context. Returns a string. template_name may be a string or a list of strings.
pcsd
def render to string template name context=None request=None using=None if isinstance template name list tuple template = select template template name using=using else template = get template template name using=using return template render context request
5721
def render_to_string(template_name, context=None, request=None, using=None): if isinstance(template_name, (list, tuple)): template = select_template(template_name, using=using) else: template = get_template(template_name, using=using) return template.render(context, request)
Loads a template and renders it with a context. Returns a string. template_name may be a string or a list of strings.
loads a template and renders it with a context .
Question: What does this function do? Code: def render_to_string(template_name, context=None, request=None, using=None): if isinstance(template_name, (list, tuple)): template = select_template(template_name, using=using) else: template = get_template(template_name, using=using) return template.render(context,...
null
null
null
What does this function do?
def is_categorical(array): return (isinstance(array, ABCCategorical) or is_categorical_dtype(array))
null
null
null
return if we are a categorical possibility
pcsd
def is categorical array return isinstance array ABC Categorical or is categorical dtype array
5722
def is_categorical(array): return (isinstance(array, ABCCategorical) or is_categorical_dtype(array))
return if we are a categorical possibility
return if we are a categorical possibility
Question: What does this function do? Code: def is_categorical(array): return (isinstance(array, ABCCategorical) or is_categorical_dtype(array))
null
null
null
What does this function do?
def grains(): refresh_needed = False refresh_needed = (refresh_needed or (not DETAILS.get('grains_cache', {}))) refresh_needed = (refresh_needed or (not DETAILS.get('grains_cache', {}).get('result', False))) refresh_needed = (refresh_needed or (not DETAILS.get('grains_cache', {}).get('out', {}))) if refresh_needed...
null
null
null
Retrieve facts from the network device.
pcsd
def grains refresh needed = False refresh needed = refresh needed or not DETAILS get 'grains cache' {} refresh needed = refresh needed or not DETAILS get 'grains cache' {} get 'result' False refresh needed = refresh needed or not DETAILS get 'grains cache' {} get 'out' {} if refresh needed facts = call 'get facts' **{}...
5725
def grains(): refresh_needed = False refresh_needed = (refresh_needed or (not DETAILS.get('grains_cache', {}))) refresh_needed = (refresh_needed or (not DETAILS.get('grains_cache', {}).get('result', False))) refresh_needed = (refresh_needed or (not DETAILS.get('grains_cache', {}).get('out', {}))) if refresh_needed...
Retrieve facts from the network device.
retrieve facts from the network device .
Question: What does this function do? Code: def grains(): refresh_needed = False refresh_needed = (refresh_needed or (not DETAILS.get('grains_cache', {}))) refresh_needed = (refresh_needed or (not DETAILS.get('grains_cache', {}).get('result', False))) refresh_needed = (refresh_needed or (not DETAILS.get('grains_...
null
null
null
What does this function do?
def random_func(lib, opts, args): query = decargs(args) if opts.album: objs = list(lib.albums(query)) else: objs = list(lib.items(query)) objs = random_objs(objs, opts.album, opts.number, opts.time, opts.equal_chance) for obj in objs: print_(format(obj))
null
null
null
Select some random items or albums and print the results.
pcsd
def random func lib opts args query = decargs args if opts album objs = list lib albums query else objs = list lib items query objs = random objs objs opts album opts number opts time opts equal chance for obj in objs print format obj
5736
def random_func(lib, opts, args): query = decargs(args) if opts.album: objs = list(lib.albums(query)) else: objs = list(lib.items(query)) objs = random_objs(objs, opts.album, opts.number, opts.time, opts.equal_chance) for obj in objs: print_(format(obj))
Select some random items or albums and print the results.
select some random items or albums and print the results .
Question: What does this function do? Code: def random_func(lib, opts, args): query = decargs(args) if opts.album: objs = list(lib.albums(query)) else: objs = list(lib.items(query)) objs = random_objs(objs, opts.album, opts.number, opts.time, opts.equal_chance) for obj in objs: print_(format(obj))
null
null
null
What does this function do?
def default_fused_keys_renamer(keys): typ = type(keys[0]) if ((typ is str) or (typ is unicode)): names = [key_split(x) for x in keys[:0:(-1)]] names.append(keys[0]) return '-'.join(names) elif ((typ is tuple) and (len(keys[0]) > 0) and isinstance(keys[0][0], (str, unicode))): names = [key_split(x) for x in k...
null
null
null
Create new keys for fused tasks
pcsd
def default fused keys renamer keys typ = type keys[0] if typ is str or typ is unicode names = [key split x for x in keys[ 0 -1 ]] names append keys[0] return '-' join names elif typ is tuple and len keys[0] > 0 and isinstance keys[0][0] str unicode names = [key split x for x in keys[ 0 -1 ]] names append keys[0][0] re...
5744
def default_fused_keys_renamer(keys): typ = type(keys[0]) if ((typ is str) or (typ is unicode)): names = [key_split(x) for x in keys[:0:(-1)]] names.append(keys[0]) return '-'.join(names) elif ((typ is tuple) and (len(keys[0]) > 0) and isinstance(keys[0][0], (str, unicode))): names = [key_split(x) for x in k...
Create new keys for fused tasks
create new keys for fused tasks
Question: What does this function do? Code: def default_fused_keys_renamer(keys): typ = type(keys[0]) if ((typ is str) or (typ is unicode)): names = [key_split(x) for x in keys[:0:(-1)]] names.append(keys[0]) return '-'.join(names) elif ((typ is tuple) and (len(keys[0]) > 0) and isinstance(keys[0][0], (str,...
null
null
null
What does this function do?
def arbitrary_address(family): if (family == 'AF_INET'): return ('localhost', 0) elif (family == 'AF_UNIX'): return tempfile.mktemp(prefix='listener-', dir=get_temp_dir()) elif (family == 'AF_PIPE'): return tempfile.mktemp(prefix=('\\\\.\\pipe\\pyc-%d-%d-' % (os.getpid(), _mmap_counter.next()))) else: raise...
null
null
null
Return an arbitrary free address for the given family
pcsd
def arbitrary address family if family == 'AF INET' return 'localhost' 0 elif family == 'AF UNIX' return tempfile mktemp prefix='listener-' dir=get temp dir elif family == 'AF PIPE' return tempfile mktemp prefix= '\\\\ \\pipe\\pyc-%d-%d-' % os getpid mmap counter next else raise Value Error 'unrecognized family'
5751
def arbitrary_address(family): if (family == 'AF_INET'): return ('localhost', 0) elif (family == 'AF_UNIX'): return tempfile.mktemp(prefix='listener-', dir=get_temp_dir()) elif (family == 'AF_PIPE'): return tempfile.mktemp(prefix=('\\\\.\\pipe\\pyc-%d-%d-' % (os.getpid(), _mmap_counter.next()))) else: raise...
Return an arbitrary free address for the given family
return an arbitrary free address for the given family
Question: What does this function do? Code: def arbitrary_address(family): if (family == 'AF_INET'): return ('localhost', 0) elif (family == 'AF_UNIX'): return tempfile.mktemp(prefix='listener-', dir=get_temp_dir()) elif (family == 'AF_PIPE'): return tempfile.mktemp(prefix=('\\\\.\\pipe\\pyc-%d-%d-' % (os.g...
null
null
null
What does this function do?
def _wrap_generator_with_readonly(generator): def wrapper_generator(*args, **kwargs): generator_obj = generator(*args, **kwargs) readonly_connection.connection().set_django_connection() try: first_value = generator_obj.next() finally: readonly_connection.connection().unset_django_connection() (yield fi...
null
null
null
We have to wrap generators specially. Assume it performs the query on the first call to next().
pcsd
def wrap generator with readonly generator def wrapper generator *args **kwargs generator obj = generator *args **kwargs readonly connection connection set django connection try first value = generator obj next finally readonly connection connection unset django connection yield first value while True yield generator o...
5754
def _wrap_generator_with_readonly(generator): def wrapper_generator(*args, **kwargs): generator_obj = generator(*args, **kwargs) readonly_connection.connection().set_django_connection() try: first_value = generator_obj.next() finally: readonly_connection.connection().unset_django_connection() (yield fi...
We have to wrap generators specially. Assume it performs the query on the first call to next().
we have to wrap generators specially .
Question: What does this function do? Code: def _wrap_generator_with_readonly(generator): def wrapper_generator(*args, **kwargs): generator_obj = generator(*args, **kwargs) readonly_connection.connection().set_django_connection() try: first_value = generator_obj.next() finally: readonly_connection.con...
null
null
null
What does this function do?
def _process_mass_form(f): def wrap(request, *args, **kwargs): 'Wrap' if ('massform' in request.POST): for key in request.POST: if ('mass-order' in key): try: order = SaleOrder.objects.get(pk=request.POST[key]) form = MassActionForm(request.user.profile, request.POST, instance=order) ...
null
null
null
Pre-process request to handle mass action form for Orders
pcsd
def process mass form f def wrap request *args **kwargs 'Wrap' if 'massform' in request POST for key in request POST if 'mass-order' in key try order = Sale Order objects get pk=request POST[key] form = Mass Action Form request user profile request POST instance=order if form is valid and request user profile has permi...
5765
def _process_mass_form(f): def wrap(request, *args, **kwargs): 'Wrap' if ('massform' in request.POST): for key in request.POST: if ('mass-order' in key): try: order = SaleOrder.objects.get(pk=request.POST[key]) form = MassActionForm(request.user.profile, request.POST, instance=order) ...
Pre-process request to handle mass action form for Orders
pre - process request to handle mass action form for orders
Question: What does this function do? Code: def _process_mass_form(f): def wrap(request, *args, **kwargs): 'Wrap' if ('massform' in request.POST): for key in request.POST: if ('mass-order' in key): try: order = SaleOrder.objects.get(pk=request.POST[key]) form = MassActionForm(request.use...
null
null
null
What does this function do?
def dump_student_extensions(course, student): data = [] header = [_('Unit'), _('Extended Due Date')] units = get_units_with_due_date(course) units = {u.location: u for u in units} query = StudentFieldOverride.objects.filter(course_id=course.id, student=student, field='due') for override in query: location = ove...
null
null
null
Dumps data about the due date extensions granted for a particular student in a particular course.
pcsd
def dump student extensions course student data = [] header = [ 'Unit' 'Extended Due Date' ] units = get units with due date course units = {u location u for u in units} query = Student Field Override objects filter course id=course id student=student field='due' for override in query location = override location repla...
5789
def dump_student_extensions(course, student): data = [] header = [_('Unit'), _('Extended Due Date')] units = get_units_with_due_date(course) units = {u.location: u for u in units} query = StudentFieldOverride.objects.filter(course_id=course.id, student=student, field='due') for override in query: location = ove...
Dumps data about the due date extensions granted for a particular student in a particular course.
dumps data about the due date extensions granted for a particular student in a particular course .
Question: What does this function do? Code: def dump_student_extensions(course, student): data = [] header = [_('Unit'), _('Extended Due Date')] units = get_units_with_due_date(course) units = {u.location: u for u in units} query = StudentFieldOverride.objects.filter(course_id=course.id, student=student, field=...
null
null
null
What does this function do?
def _get_cost_functions(): cost_fns_conf = CONF.least_cost_functions if (cost_fns_conf is None): fn_str = 'nova.scheduler.least_cost.compute_fill_first_cost_fn' cost_fns_conf = [fn_str] cost_fns = [] for cost_fn_str in cost_fns_conf: short_name = cost_fn_str.split('.')[(-1)] if (not (short_name.startswith('...
null
null
null
Returns a list of tuples containing weights and cost functions to use for weighing hosts
pcsd
def get cost functions cost fns conf = CONF least cost functions if cost fns conf is None fn str = 'nova scheduler least cost compute fill first cost fn' cost fns conf = [fn str] cost fns = [] for cost fn str in cost fns conf short name = cost fn str split ' ' [ -1 ] if not short name startswith 'compute ' or short nam...
5792
def _get_cost_functions(): cost_fns_conf = CONF.least_cost_functions if (cost_fns_conf is None): fn_str = 'nova.scheduler.least_cost.compute_fill_first_cost_fn' cost_fns_conf = [fn_str] cost_fns = [] for cost_fn_str in cost_fns_conf: short_name = cost_fn_str.split('.')[(-1)] if (not (short_name.startswith('...
Returns a list of tuples containing weights and cost functions to use for weighing hosts
returns a list of tuples containing weights and cost functions to use for weighing hosts
Question: What does this function do? Code: def _get_cost_functions(): cost_fns_conf = CONF.least_cost_functions if (cost_fns_conf is None): fn_str = 'nova.scheduler.least_cost.compute_fill_first_cost_fn' cost_fns_conf = [fn_str] cost_fns = [] for cost_fn_str in cost_fns_conf: short_name = cost_fn_str.spli...
null
null
null
What does this function do?
@click.command(u'setup-help') @pass_context def setup_help(context): from frappe.utils.help import sync for site in context.sites: try: frappe.init(site) frappe.connect() sync() finally: frappe.destroy()
null
null
null
Setup help table in the current site (called after migrate)
pcsd
@click command u'setup-help' @pass context def setup help context from frappe utils help import sync for site in context sites try frappe init site frappe connect sync finally frappe destroy
5795
@click.command(u'setup-help') @pass_context def setup_help(context): from frappe.utils.help import sync for site in context.sites: try: frappe.init(site) frappe.connect() sync() finally: frappe.destroy()
Setup help table in the current site (called after migrate)
setup help table in the current site
Question: What does this function do? Code: @click.command(u'setup-help') @pass_context def setup_help(context): from frappe.utils.help import sync for site in context.sites: try: frappe.init(site) frappe.connect() sync() finally: frappe.destroy()
null
null
null
What does this function do?
def is_bin_str(data): if ('\x00' in data): return True if (not data): return False text_characters = ''.join(([chr(x) for x in range(32, 127)] + list('\n\r DCTB \x08'))) if six.PY3: trans = ''.maketrans('', '', text_characters) nontext = data.translate(trans) else: trans = string.maketrans('', '') nont...
null
null
null
Detects if the passed string of data is bin or text
pcsd
def is bin str data if '\x00' in data return True if not data return False text characters = '' join [chr x for x in range 32 127 ] + list ' \r DCTB \x08' if six PY3 trans = '' maketrans '' '' text characters nontext = data translate trans else trans = string maketrans '' '' nontext = data translate trans text characte...
5796
def is_bin_str(data): if ('\x00' in data): return True if (not data): return False text_characters = ''.join(([chr(x) for x in range(32, 127)] + list('\n\r DCTB \x08'))) if six.PY3: trans = ''.maketrans('', '', text_characters) nontext = data.translate(trans) else: trans = string.maketrans('', '') nont...
Detects if the passed string of data is bin or text
detects if the passed string of data is bin or text
Question: What does this function do? Code: def is_bin_str(data): if ('\x00' in data): return True if (not data): return False text_characters = ''.join(([chr(x) for x in range(32, 127)] + list('\n\r DCTB \x08'))) if six.PY3: trans = ''.maketrans('', '', text_characters) nontext = data.translate(trans) ...
null
null
null
What does this function do?
def send_alert_confirmation(alert): ctx = Context({'alert': alert, 'site': Site.objects.get_current()}) subject_tpl = loader.get_template('customer/alerts/emails/confirmation_subject.txt') body_tpl = loader.get_template('customer/alerts/emails/confirmation_body.txt') mail.send_mail(subject_tpl.render(ctx).strip(), ...
null
null
null
Send an alert confirmation email.
pcsd
def send alert confirmation alert ctx = Context {'alert' alert 'site' Site objects get current } subject tpl = loader get template 'customer/alerts/emails/confirmation subject txt' body tpl = loader get template 'customer/alerts/emails/confirmation body txt' mail send mail subject tpl render ctx strip body tpl render c...
5797
def send_alert_confirmation(alert): ctx = Context({'alert': alert, 'site': Site.objects.get_current()}) subject_tpl = loader.get_template('customer/alerts/emails/confirmation_subject.txt') body_tpl = loader.get_template('customer/alerts/emails/confirmation_body.txt') mail.send_mail(subject_tpl.render(ctx).strip(), ...
Send an alert confirmation email.
send an alert confirmation email .
Question: What does this function do? Code: def send_alert_confirmation(alert): ctx = Context({'alert': alert, 'site': Site.objects.get_current()}) subject_tpl = loader.get_template('customer/alerts/emails/confirmation_subject.txt') body_tpl = loader.get_template('customer/alerts/emails/confirmation_body.txt') m...
null
null
null
What does this function do?
def ip_missing(mod_attr): IPY_SHOULD_IMPL.write((mod_attr + '\n')) IPY_SHOULD_IMPL.flush()
null
null
null
Logs a module or module attribute IP is missing.
pcsd
def ip missing mod attr IPY SHOULD IMPL write mod attr + ' ' IPY SHOULD IMPL flush
5799
def ip_missing(mod_attr): IPY_SHOULD_IMPL.write((mod_attr + '\n')) IPY_SHOULD_IMPL.flush()
Logs a module or module attribute IP is missing.
logs a module or module attribute ip is missing .
Question: What does this function do? Code: def ip_missing(mod_attr): IPY_SHOULD_IMPL.write((mod_attr + '\n')) IPY_SHOULD_IMPL.flush()
null
null
null
What does this function do?
def is_module_enabled(module): return is_link(('/etc/apache2/mods-enabled/%s.load' % module))
null
null
null
Check if an Apache module is enabled.
pcsd
def is module enabled module return is link '/etc/apache2/mods-enabled/%s load' % module
5804
def is_module_enabled(module): return is_link(('/etc/apache2/mods-enabled/%s.load' % module))
Check if an Apache module is enabled.
check if an apache module is enabled .
Question: What does this function do? Code: def is_module_enabled(module): return is_link(('/etc/apache2/mods-enabled/%s.load' % module))
null
null
null
What does this function do?
def get_page_models(): return PAGE_MODEL_CLASSES
null
null
null
Returns a list of all non-abstract Page model classes defined in this project.
pcsd
def get page models return PAGE MODEL CLASSES
5810
def get_page_models(): return PAGE_MODEL_CLASSES
Returns a list of all non-abstract Page model classes defined in this project.
returns a list of all non - abstract page model classes defined in this project .
Question: What does this function do? Code: def get_page_models(): return PAGE_MODEL_CLASSES
null
null
null
What does this function do?
@testing.requires_testing_data def test_basic(): raw = read_crop(raw_fname, (0.0, 1.0)) raw_err = read_crop(raw_fname).apply_proj() raw_erm = read_crop(erm_fname) assert_raises(RuntimeError, maxwell_filter, raw_err) assert_raises(TypeError, maxwell_filter, 1.0) assert_raises(ValueError, maxwell_filter, raw, int_o...
null
null
null
Test Maxwell filter basic version.
pcsd
@testing requires testing data def test basic raw = read crop raw fname 0 0 1 0 raw err = read crop raw fname apply proj raw erm = read crop erm fname assert raises Runtime Error maxwell filter raw err assert raises Type Error maxwell filter 1 0 assert raises Value Error maxwell filter raw int order=20 n int bases = in...
5811
@testing.requires_testing_data def test_basic(): raw = read_crop(raw_fname, (0.0, 1.0)) raw_err = read_crop(raw_fname).apply_proj() raw_erm = read_crop(erm_fname) assert_raises(RuntimeError, maxwell_filter, raw_err) assert_raises(TypeError, maxwell_filter, 1.0) assert_raises(ValueError, maxwell_filter, raw, int_o...
Test Maxwell filter basic version.
test maxwell filter basic version .
Question: What does this function do? Code: @testing.requires_testing_data def test_basic(): raw = read_crop(raw_fname, (0.0, 1.0)) raw_err = read_crop(raw_fname).apply_proj() raw_erm = read_crop(erm_fname) assert_raises(RuntimeError, maxwell_filter, raw_err) assert_raises(TypeError, maxwell_filter, 1.0) asser...
null
null
null
What does this function do?
def format_script_list(scripts): if (not scripts): return '<No scripts>' table = EvTable('{wdbref{n', '{wobj{n', '{wkey{n', '{wintval{n', '{wnext{n', '{wrept{n', '{wdb', '{wtypeclass{n', '{wdesc{n', align='r', border='tablecols') for script in scripts: nextrep = script.time_until_next_repeat() if (nextrep is N...
null
null
null
Takes a list of scripts and formats the output.
pcsd
def format script list scripts if not scripts return '<No scripts>' table = Ev Table '{wdbref{n' '{wobj{n' '{wkey{n' '{wintval{n' '{wnext{n' '{wrept{n' '{wdb' '{wtypeclass{n' '{wdesc{n' align='r' border='tablecols' for script in scripts nextrep = script time until next repeat if nextrep is None nextrep = 'PAUS' if scri...
5827
def format_script_list(scripts): if (not scripts): return '<No scripts>' table = EvTable('{wdbref{n', '{wobj{n', '{wkey{n', '{wintval{n', '{wnext{n', '{wrept{n', '{wdb', '{wtypeclass{n', '{wdesc{n', align='r', border='tablecols') for script in scripts: nextrep = script.time_until_next_repeat() if (nextrep is N...
Takes a list of scripts and formats the output.
takes a list of scripts and formats the output .
Question: What does this function do? Code: def format_script_list(scripts): if (not scripts): return '<No scripts>' table = EvTable('{wdbref{n', '{wobj{n', '{wkey{n', '{wintval{n', '{wnext{n', '{wrept{n', '{wdb', '{wtypeclass{n', '{wdesc{n', align='r', border='tablecols') for script in scripts: nextrep = scr...
null
null
null
What does this function do?
def get_recording_dirs(data_dir): filtered_recording_dirs = [] if is_pupil_rec_dir(data_dir): filtered_recording_dirs.append(data_dir) for (root, dirs, files) in os.walk(data_dir): filtered_recording_dirs += [os.path.join(root, d) for d in dirs if ((not d.startswith('.')) and is_pupil_rec_dir(os.path.join(root, ...
null
null
null
You can supply a data folder or any folder - all folders within will be checked for necessary files - in order to make a visualization
pcsd
def get recording dirs data dir filtered recording dirs = [] if is pupil rec dir data dir filtered recording dirs append data dir for root dirs files in os walk data dir filtered recording dirs += [os path join root d for d in dirs if not d startswith ' ' and is pupil rec dir os path join root d ] logger debug 'Filtere...
5832
def get_recording_dirs(data_dir): filtered_recording_dirs = [] if is_pupil_rec_dir(data_dir): filtered_recording_dirs.append(data_dir) for (root, dirs, files) in os.walk(data_dir): filtered_recording_dirs += [os.path.join(root, d) for d in dirs if ((not d.startswith('.')) and is_pupil_rec_dir(os.path.join(root, ...
You can supply a data folder or any folder - all folders within will be checked for necessary files - in order to make a visualization
you can supply a data folder or any folder - all folders within will be checked for necessary files - in order to make a visualization
Question: What does this function do? Code: def get_recording_dirs(data_dir): filtered_recording_dirs = [] if is_pupil_rec_dir(data_dir): filtered_recording_dirs.append(data_dir) for (root, dirs, files) in os.walk(data_dir): filtered_recording_dirs += [os.path.join(root, d) for d in dirs if ((not d.startswith...
null
null
null
What does this function do?
def assert_false(expr, msg=None): if expr: _report_failure(msg)
null
null
null
Fail the test if the expression is True.
pcsd
def assert false expr msg=None if expr report failure msg
5840
def assert_false(expr, msg=None): if expr: _report_failure(msg)
Fail the test if the expression is True.
fail the test if the expression is true .
Question: What does this function do? Code: def assert_false(expr, msg=None): if expr: _report_failure(msg)
null
null
null
What does this function do?
def inv_rheader(r): if ((r.representation != 'html') or (r.method == 'import')): return None (tablename, record) = s3_rheader_resource(r) if (not record): return None T = current.T s3db = current.s3db table = s3db.table(tablename) rheader = None if (tablename == 'inv_warehouse'): tabs = [(T('Basic Details...
null
null
null
Resource Header for Warehouses and Inventory Items
pcsd
def inv rheader r if r representation != 'html' or r method == 'import' return None tablename record = s3 rheader resource r if not record return None T = current T s3db = current s3db table = s3db table tablename rheader = None if tablename == 'inv warehouse' tabs = [ T 'Basic Details' None ] permit = current auth s3 ...
5848
def inv_rheader(r): if ((r.representation != 'html') or (r.method == 'import')): return None (tablename, record) = s3_rheader_resource(r) if (not record): return None T = current.T s3db = current.s3db table = s3db.table(tablename) rheader = None if (tablename == 'inv_warehouse'): tabs = [(T('Basic Details...
Resource Header for Warehouses and Inventory Items
resource header for warehouses and inventory items
Question: What does this function do? Code: def inv_rheader(r): if ((r.representation != 'html') or (r.method == 'import')): return None (tablename, record) = s3_rheader_resource(r) if (not record): return None T = current.T s3db = current.s3db table = s3db.table(tablename) rheader = None if (tablename =...
null
null
null
What does this function do?
def write_name_list(fid, kind, data): write_string(fid, kind, ':'.join(data))
null
null
null
Write a colon-separated list of names. Parameters data : list of strings
pcsd
def write name list fid kind data write string fid kind ' ' join data
5851
def write_name_list(fid, kind, data): write_string(fid, kind, ':'.join(data))
Write a colon-separated list of names. Parameters data : list of strings
write a colon - separated list of names .
Question: What does this function do? Code: def write_name_list(fid, kind, data): write_string(fid, kind, ':'.join(data))
null
null
null
What does this function do?
def predicative(adjective): return adjective
null
null
null
Returns the predicative adjective.
pcsd
def predicative adjective return adjective
5861
def predicative(adjective): return adjective
Returns the predicative adjective.
returns the predicative adjective .
Question: What does this function do? Code: def predicative(adjective): return adjective
null
null
null
What does this function do?
def templates_for_device(request, templates): from mezzanine.conf import settings if (not isinstance(templates, (list, tuple))): templates = [templates] device = device_from_request(request) device_templates = [] for template in templates: if device: device_templates.append((u'%s/%s' % (device, template))) ...
null
null
null
Given a template name (or list of them), returns the template names as a list, with each name prefixed with the device directory inserted before it\'s associate default in the list.
pcsd
def templates for device request templates from mezzanine conf import settings if not isinstance templates list tuple templates = [templates] device = device from request request device templates = [] for template in templates if device device templates append u'%s/%s' % device template if settings DEVICE DEFAULT and s...
5864
def templates_for_device(request, templates): from mezzanine.conf import settings if (not isinstance(templates, (list, tuple))): templates = [templates] device = device_from_request(request) device_templates = [] for template in templates: if device: device_templates.append((u'%s/%s' % (device, template))) ...
Given a template name (or list of them), returns the template names as a list, with each name prefixed with the device directory inserted before it\'s associate default in the list.
given a template name , returns the template names as a list , with each name prefixed with the device directory inserted before its associate default in the list .
Question: What does this function do? Code: def templates_for_device(request, templates): from mezzanine.conf import settings if (not isinstance(templates, (list, tuple))): templates = [templates] device = device_from_request(request) device_templates = [] for template in templates: if device: device_tem...
null
null
null
What does this function do?
def admin_media_prefix(): try: from django.conf import settings except ImportError: return '' return iri_to_uri(settings.ADMIN_MEDIA_PREFIX)
null
null
null
Returns the string contained in the setting ADMIN_MEDIA_PREFIX.
pcsd
def admin media prefix try from django conf import settings except Import Error return '' return iri to uri settings ADMIN MEDIA PREFIX
5865
def admin_media_prefix(): try: from django.conf import settings except ImportError: return '' return iri_to_uri(settings.ADMIN_MEDIA_PREFIX)
Returns the string contained in the setting ADMIN_MEDIA_PREFIX.
returns the string contained in the setting admin _ media _ prefix .
Question: What does this function do? Code: def admin_media_prefix(): try: from django.conf import settings except ImportError: return '' return iri_to_uri(settings.ADMIN_MEDIA_PREFIX)
null
null
null
What does this function do?
@treeio_login_required def help_page(request, url='/', response_format='html'): source = getattr(settings, 'HARDTREE_HELP_SOURCE', 'http://127.0.0.1:7000/help') if (not url): url = '/' body = '' try: body = urllib2.urlopen((((source + url) + '?domain=') + RequestSite(request).domain)).read() except: pass re...
null
null
null
Returns a Help page from Evergreen
pcsd
@treeio login required def help page request url='/' response format='html' source = getattr settings 'HARDTREE HELP SOURCE' 'http //127 0 0 1 7000/help' if not url url = '/' body = '' try body = urllib2 urlopen source + url + '?domain=' + Request Site request domain read except pass regexp = '<!-- module content inner...
5868
@treeio_login_required def help_page(request, url='/', response_format='html'): source = getattr(settings, 'HARDTREE_HELP_SOURCE', 'http://127.0.0.1:7000/help') if (not url): url = '/' body = '' try: body = urllib2.urlopen((((source + url) + '?domain=') + RequestSite(request).domain)).read() except: pass re...
Returns a Help page from Evergreen
returns a help page from evergreen
Question: What does this function do? Code: @treeio_login_required def help_page(request, url='/', response_format='html'): source = getattr(settings, 'HARDTREE_HELP_SOURCE', 'http://127.0.0.1:7000/help') if (not url): url = '/' body = '' try: body = urllib2.urlopen((((source + url) + '?domain=') + RequestSi...
null
null
null
What does this function do?
def get_url(handler_name, key_value, key_name='usage_key_string', kwargs=None): return reverse_url(handler_name, key_name, key_value, kwargs)
null
null
null
Helper function for getting HTML for a page in Studio and checking that it does not error.
pcsd
def get url handler name key value key name='usage key string' kwargs=None return reverse url handler name key name key value kwargs
5870
def get_url(handler_name, key_value, key_name='usage_key_string', kwargs=None): return reverse_url(handler_name, key_name, key_value, kwargs)
Helper function for getting HTML for a page in Studio and checking that it does not error.
helper function for getting html for a page in studio and checking that it does not error .
Question: What does this function do? Code: def get_url(handler_name, key_value, key_name='usage_key_string', kwargs=None): return reverse_url(handler_name, key_name, key_value, kwargs)
null
null
null
What does this function do?
@testing.requires_testing_data def test_make_inverse_operator_fixed(): fwd_1 = read_forward_solution_meg(fname_fwd, surf_ori=False, force_fixed=False) fwd_2 = read_forward_solution_meg(fname_fwd, surf_ori=False, force_fixed=True) evoked = _get_evoked() noise_cov = read_cov(fname_cov) assert_raises(ValueError, make...
null
null
null
Test MNE inverse computation (fixed orientation)
pcsd
@testing requires testing data def test make inverse operator fixed fwd 1 = read forward solution meg fname fwd surf ori=False force fixed=False fwd 2 = read forward solution meg fname fwd surf ori=False force fixed=True evoked = get evoked noise cov = read cov fname cov assert raises Value Error make inverse operator ...
5871
@testing.requires_testing_data def test_make_inverse_operator_fixed(): fwd_1 = read_forward_solution_meg(fname_fwd, surf_ori=False, force_fixed=False) fwd_2 = read_forward_solution_meg(fname_fwd, surf_ori=False, force_fixed=True) evoked = _get_evoked() noise_cov = read_cov(fname_cov) assert_raises(ValueError, make...
Test MNE inverse computation (fixed orientation)
test mne inverse computation
Question: What does this function do? Code: @testing.requires_testing_data def test_make_inverse_operator_fixed(): fwd_1 = read_forward_solution_meg(fname_fwd, surf_ori=False, force_fixed=False) fwd_2 = read_forward_solution_meg(fname_fwd, surf_ori=False, force_fixed=True) evoked = _get_evoked() noise_cov = read...
null
null
null
What does this function do?
def visiblename(name, all=None): _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__', '__module__', '__name__', '__slots__', '__package__', '__dict__', '__weakref__') if (name in _hidden_names): return 0 if (name.startswith('__') and name.endswith('__')): return 1 if (all is not None): return (...
null
null
null
Decide whether to show documentation on a variable.
pcsd
def visiblename name all=None hidden names = ' builtins ' ' doc ' ' file ' ' path ' ' module ' ' name ' ' slots ' ' package ' ' dict ' ' weakref ' if name in hidden names return 0 if name startswith ' ' and name endswith ' ' return 1 if all is not None return name in all elif name startswith ' handle ' return 1 else re...
5873
def visiblename(name, all=None): _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__', '__module__', '__name__', '__slots__', '__package__', '__dict__', '__weakref__') if (name in _hidden_names): return 0 if (name.startswith('__') and name.endswith('__')): return 1 if (all is not None): return (...
Decide whether to show documentation on a variable.
decide whether to show documentation on a variable .
Question: What does this function do? Code: def visiblename(name, all=None): _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__', '__module__', '__name__', '__slots__', '__package__', '__dict__', '__weakref__') if (name in _hidden_names): return 0 if (name.startswith('__') and name.endswith('__')...
null
null
null
What does this function do?
def syntax_file(gcs_uri): language_client = language.Client() document = language_client.document_from_url(gcs_uri) tokens = document.analyze_syntax() for token in tokens: print '{}: {}'.format(token.part_of_speech, token.text_content)
null
null
null
Detects syntax in the file located in Google Cloud Storage.
pcsd
def syntax file gcs uri language client = language Client document = language client document from url gcs uri tokens = document analyze syntax for token in tokens print '{} {}' format token part of speech token text content
5878
def syntax_file(gcs_uri): language_client = language.Client() document = language_client.document_from_url(gcs_uri) tokens = document.analyze_syntax() for token in tokens: print '{}: {}'.format(token.part_of_speech, token.text_content)
Detects syntax in the file located in Google Cloud Storage.
detects syntax in the file located in google cloud storage .
Question: What does this function do? Code: def syntax_file(gcs_uri): language_client = language.Client() document = language_client.document_from_url(gcs_uri) tokens = document.analyze_syntax() for token in tokens: print '{}: {}'.format(token.part_of_speech, token.text_content)
null
null
null
What does this function do?
@dispatch(object) def scrub_keys(o): raise NotImplementedError(('scrub_keys not implemented for type %r' % type(o).__name__))
null
null
null
Add an ascending sort key when pass a string, to make the MongoDB interface similar to SQL.
pcsd
@dispatch object def scrub keys o raise Not Implemented Error 'scrub keys not implemented for type %r' % type o name
5879
@dispatch(object) def scrub_keys(o): raise NotImplementedError(('scrub_keys not implemented for type %r' % type(o).__name__))
Add an ascending sort key when pass a string, to make the MongoDB interface similar to SQL.
add an ascending sort key when pass a string , to make the mongodb interface similar to sql .
Question: What does this function do? Code: @dispatch(object) def scrub_keys(o): raise NotImplementedError(('scrub_keys not implemented for type %r' % type(o).__name__))
null
null
null
What does this function do?
def ensure_dir_exists(dirname): try: os.makedirs(dirname) except OSError as e: if (e.errno != errno.EEXIST): raise
null
null
null
Ensure a directory exists, creating if necessary.
pcsd
def ensure dir exists dirname try os makedirs dirname except OS Error as e if e errno != errno EEXIST raise
5883
def ensure_dir_exists(dirname): try: os.makedirs(dirname) except OSError as e: if (e.errno != errno.EEXIST): raise
Ensure a directory exists, creating if necessary.
ensure a directory exists , creating if necessary .
Question: What does this function do? Code: def ensure_dir_exists(dirname): try: os.makedirs(dirname) except OSError as e: if (e.errno != errno.EEXIST): raise
null
null
null
What does this function do?
def common_environment(): env = dict(LC_ALL='en_US.UTF-8', PATH=os.environ.get('PATH', os.defpath)) required = ('HOME',) optional = ('HTTPTESTER', 'SSH_AUTH_SOCK') env.update(pass_vars(required=required, optional=optional)) return env
null
null
null
Common environment used for executing all programs.
pcsd
def common environment env = dict LC ALL='en US UTF-8' PATH=os environ get 'PATH' os defpath required = 'HOME' optional = 'HTTPTESTER' 'SSH AUTH SOCK' env update pass vars required=required optional=optional return env
5913
def common_environment(): env = dict(LC_ALL='en_US.UTF-8', PATH=os.environ.get('PATH', os.defpath)) required = ('HOME',) optional = ('HTTPTESTER', 'SSH_AUTH_SOCK') env.update(pass_vars(required=required, optional=optional)) return env
Common environment used for executing all programs.
common environment used for executing all programs .
Question: What does this function do? Code: def common_environment(): env = dict(LC_ALL='en_US.UTF-8', PATH=os.environ.get('PATH', os.defpath)) required = ('HOME',) optional = ('HTTPTESTER', 'SSH_AUTH_SOCK') env.update(pass_vars(required=required, optional=optional)) return env
null
null
null
What does this function do?
@testing.requires_testing_data def test_combine(): trans = read_trans(fname) inv = invert_transform(trans) combine_transforms(trans, inv, trans['from'], trans['from']) assert_raises(RuntimeError, combine_transforms, trans, inv, trans['to'], trans['from']) assert_raises(RuntimeError, combine_transforms, trans, inv,...
null
null
null
Test combining transforms
pcsd
@testing requires testing data def test combine trans = read trans fname inv = invert transform trans combine transforms trans inv trans['from'] trans['from'] assert raises Runtime Error combine transforms trans inv trans['to'] trans['from'] assert raises Runtime Error combine transforms trans inv trans['from'] trans['...
5918
@testing.requires_testing_data def test_combine(): trans = read_trans(fname) inv = invert_transform(trans) combine_transforms(trans, inv, trans['from'], trans['from']) assert_raises(RuntimeError, combine_transforms, trans, inv, trans['to'], trans['from']) assert_raises(RuntimeError, combine_transforms, trans, inv,...
Test combining transforms
test combining transforms
Question: What does this function do? Code: @testing.requires_testing_data def test_combine(): trans = read_trans(fname) inv = invert_transform(trans) combine_transforms(trans, inv, trans['from'], trans['from']) assert_raises(RuntimeError, combine_transforms, trans, inv, trans['to'], trans['from']) assert_raise...
null
null
null
What does this function do?
def get_node(conn, name): datacenter_id = get_datacenter_id() for item in conn.list_servers(datacenter_id)['items']: if (item['properties']['name'] == name): node = {'id': item['id']} node.update(item['properties']) return node
null
null
null
Return a node for the named VM
pcsd
def get node conn name datacenter id = get datacenter id for item in conn list servers datacenter id ['items'] if item['properties']['name'] == name node = {'id' item['id']} node update item['properties'] return node
5927
def get_node(conn, name): datacenter_id = get_datacenter_id() for item in conn.list_servers(datacenter_id)['items']: if (item['properties']['name'] == name): node = {'id': item['id']} node.update(item['properties']) return node
Return a node for the named VM
return a node for the named vm
Question: What does this function do? Code: def get_node(conn, name): datacenter_id = get_datacenter_id() for item in conn.list_servers(datacenter_id)['items']: if (item['properties']['name'] == name): node = {'id': item['id']} node.update(item['properties']) return node
null
null
null
What does this function do?
def _build_status(data, item): stream = item['stream'] if ('Running in' in stream): data.setdefault('Intermediate_Containers', []).append(stream.rstrip().split()[(-1)]) if ('Successfully built' in stream): data['Id'] = stream.rstrip().split()[(-1)]
null
null
null
Process a status update from a docker build, updating the data structure
pcsd
def build status data item stream = item['stream'] if 'Running in' in stream data setdefault 'Intermediate Containers' [] append stream rstrip split [ -1 ] if 'Successfully built' in stream data['Id'] = stream rstrip split [ -1 ]
5932
def _build_status(data, item): stream = item['stream'] if ('Running in' in stream): data.setdefault('Intermediate_Containers', []).append(stream.rstrip().split()[(-1)]) if ('Successfully built' in stream): data['Id'] = stream.rstrip().split()[(-1)]
Process a status update from a docker build, updating the data structure
process a status update from a docker build , updating the data structure
Question: What does this function do? Code: def _build_status(data, item): stream = item['stream'] if ('Running in' in stream): data.setdefault('Intermediate_Containers', []).append(stream.rstrip().split()[(-1)]) if ('Successfully built' in stream): data['Id'] = stream.rstrip().split()[(-1)]
null
null
null
What does this function do?
def _raise_error_routes(iface, option, expected): msg = _error_msg_routes(iface, option, expected) log.error(msg) raise AttributeError(msg)
null
null
null
Log and raise an error with a logical formatted message.
pcsd
def raise error routes iface option expected msg = error msg routes iface option expected log error msg raise Attribute Error msg
5939
def _raise_error_routes(iface, option, expected): msg = _error_msg_routes(iface, option, expected) log.error(msg) raise AttributeError(msg)
Log and raise an error with a logical formatted message.
log and raise an error with a logical formatted message .
Question: What does this function do? Code: def _raise_error_routes(iface, option, expected): msg = _error_msg_routes(iface, option, expected) log.error(msg) raise AttributeError(msg)
null
null
null
What does this function do?
def x10_command(command): return check_output((['heyu'] + command.split(' ')), stderr=STDOUT)
null
null
null
Execute X10 command and check output.
pcsd
def x10 command command return check output ['heyu'] + command split ' ' stderr=STDOUT
5951
def x10_command(command): return check_output((['heyu'] + command.split(' ')), stderr=STDOUT)
Execute X10 command and check output.
execute x10 command and check output .
Question: What does this function do? Code: def x10_command(command): return check_output((['heyu'] + command.split(' ')), stderr=STDOUT)
null
null
null
What does this function do?
def simplefilter(action, category=Warning, lineno=0, append=0): assert (action in ('error', 'ignore', 'always', 'default', 'module', 'once')), ('invalid action: %r' % (action,)) assert (isinstance(lineno, int) and (lineno >= 0)), 'lineno must be an int >= 0' item = (action, None, category, None, lineno) if append: ...
null
null
null
Insert a simple entry into the list of warnings filters (at the front). A simple filter matches all modules and messages.
pcsd
def simplefilter action category=Warning lineno=0 append=0 assert action in 'error' 'ignore' 'always' 'default' 'module' 'once' 'invalid action %r' % action assert isinstance lineno int and lineno >= 0 'lineno must be an int >= 0' item = action None category None lineno if append filters append item else filters insert...
5954
def simplefilter(action, category=Warning, lineno=0, append=0): assert (action in ('error', 'ignore', 'always', 'default', 'module', 'once')), ('invalid action: %r' % (action,)) assert (isinstance(lineno, int) and (lineno >= 0)), 'lineno must be an int >= 0' item = (action, None, category, None, lineno) if append: ...
Insert a simple entry into the list of warnings filters (at the front). A simple filter matches all modules and messages.
insert a simple entry into the list of warnings filters .
Question: What does this function do? Code: def simplefilter(action, category=Warning, lineno=0, append=0): assert (action in ('error', 'ignore', 'always', 'default', 'module', 'once')), ('invalid action: %r' % (action,)) assert (isinstance(lineno, int) and (lineno >= 0)), 'lineno must be an int >= 0' item = (act...
null
null
null
What does this function do?
def ErrorMsg(): import traceback type = value = tb = limit = None (type, value, tb) = sys.exc_info() list = (traceback.format_tb(tb, limit) + traceback.format_exception_only(type, value)) return ('Traceback (innermost last):\n' + ('%-20s %s' % (string.join(list[:(-1)], ''), list[(-1)])))
null
null
null
Helper to get a nice traceback as string
pcsd
def Error Msg import traceback type = value = tb = limit = None type value tb = sys exc info list = traceback format tb tb limit + traceback format exception only type value return 'Traceback innermost last ' + '%-20s %s' % string join list[ -1 ] '' list[ -1 ]
5957
def ErrorMsg(): import traceback type = value = tb = limit = None (type, value, tb) = sys.exc_info() list = (traceback.format_tb(tb, limit) + traceback.format_exception_only(type, value)) return ('Traceback (innermost last):\n' + ('%-20s %s' % (string.join(list[:(-1)], ''), list[(-1)])))
Helper to get a nice traceback as string
helper to get a nice traceback as string
Question: What does this function do? Code: def ErrorMsg(): import traceback type = value = tb = limit = None (type, value, tb) = sys.exc_info() list = (traceback.format_tb(tb, limit) + traceback.format_exception_only(type, value)) return ('Traceback (innermost last):\n' + ('%-20s %s' % (string.join(list[:(-1)]...
null
null
null
What does this function do?
@csrf_exempt @ratelimit('answer-vote', '10/d') def answer_vote(request, question_id, answer_id): answer = get_object_or_404(Answer, pk=answer_id, question=question_id, is_spam=False, question__is_spam=False) if (not answer.question.editable): raise PermissionDenied if request.limited: if request.is_ajax(): re...
null
null
null
Vote for Helpful/Not Helpful answers
pcsd
@csrf exempt @ratelimit 'answer-vote' '10/d' def answer vote request question id answer id answer = get object or 404 Answer pk=answer id question=question id is spam=False question is spam=False if not answer question editable raise Permission Denied if request limited if request is ajax return Http Response json dump...
5959
@csrf_exempt @ratelimit('answer-vote', '10/d') def answer_vote(request, question_id, answer_id): answer = get_object_or_404(Answer, pk=answer_id, question=question_id, is_spam=False, question__is_spam=False) if (not answer.question.editable): raise PermissionDenied if request.limited: if request.is_ajax(): re...
Vote for Helpful/Not Helpful answers
vote for helpful / not helpful answers
Question: What does this function do? Code: @csrf_exempt @ratelimit('answer-vote', '10/d') def answer_vote(request, question_id, answer_id): answer = get_object_or_404(Answer, pk=answer_id, question=question_id, is_spam=False, question__is_spam=False) if (not answer.question.editable): raise PermissionDenied if...