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 getCascadeFloatWithoutSelf(defaultFloat, elementNode, key):
if (key in elementNode.attributes):
value = elementNode.attributes[key]
functionName = (('get' + key[0].upper()) + key[1:])
if (functionName in value):
if (elementNode.parentNode == None):
return defaultFloat
else:
elementNode = elemen... | null | null | null | Get the cascade float. | pcsd | def get Cascade Float Without Self default Float element Node key if key in element Node attributes value = element Node attributes[key] function Name = 'get' + key[0] upper + key[1 ] if function Name in value if element Node parent Node == None return default Float else element Node = element Node parent Node return e... | 16395 | def getCascadeFloatWithoutSelf(defaultFloat, elementNode, key):
if (key in elementNode.attributes):
value = elementNode.attributes[key]
functionName = (('get' + key[0].upper()) + key[1:])
if (functionName in value):
if (elementNode.parentNode == None):
return defaultFloat
else:
elementNode = elemen... | Get the cascade float. | get the cascade float . | Question:
What does this function do?
Code:
def getCascadeFloatWithoutSelf(defaultFloat, elementNode, key):
if (key in elementNode.attributes):
value = elementNode.attributes[key]
functionName = (('get' + key[0].upper()) + key[1:])
if (functionName in value):
if (elementNode.parentNode == None):
return... |
null | null | null | What does this function do? | def getInstanceState(inst, jellier):
if hasattr(inst, '__getstate__'):
state = inst.__getstate__()
else:
state = inst.__dict__
sxp = jellier.prepare(inst)
sxp.extend([qual(inst.__class__), jellier.jelly(state)])
return jellier.preserve(inst, sxp)
| null | null | null | Utility method to default to \'normal\' state rules in serialization. | pcsd | def get Instance State inst jellier if hasattr inst ' getstate ' state = inst getstate else state = inst dict sxp = jellier prepare inst sxp extend [qual inst class jellier jelly state ] return jellier preserve inst sxp | 16398 | def getInstanceState(inst, jellier):
if hasattr(inst, '__getstate__'):
state = inst.__getstate__()
else:
state = inst.__dict__
sxp = jellier.prepare(inst)
sxp.extend([qual(inst.__class__), jellier.jelly(state)])
return jellier.preserve(inst, sxp)
| Utility method to default to \'normal\' state rules in serialization. | utility method to default to normal state rules in serialization . | Question:
What does this function do?
Code:
def getInstanceState(inst, jellier):
if hasattr(inst, '__getstate__'):
state = inst.__getstate__()
else:
state = inst.__dict__
sxp = jellier.prepare(inst)
sxp.extend([qual(inst.__class__), jellier.jelly(state)])
return jellier.preserve(inst, sxp)
|
null | null | null | What does this function do? | def dictadd(dict_a, dict_b):
result = {}
result.update(dict_a)
result.update(dict_b)
return result
| null | null | null | Returns a dictionary consisting of the keys in `a` and `b`.
If they share a key, the value from b is used. | pcsd | def dictadd dict a dict b result = {} result update dict a result update dict b return result | 16399 | def dictadd(dict_a, dict_b):
result = {}
result.update(dict_a)
result.update(dict_b)
return result
| Returns a dictionary consisting of the keys in `a` and `b`.
If they share a key, the value from b is used. | returns a dictionary consisting of the keys in a and b . | Question:
What does this function do?
Code:
def dictadd(dict_a, dict_b):
result = {}
result.update(dict_a)
result.update(dict_b)
return result
|
null | null | null | What does this function do? | def get_access_key():
return environ.get('HTTP_ACCESSKEY', '')
| null | null | null | Return access_key of your app | pcsd | def get access key return environ get 'HTTP ACCESSKEY' '' | 16402 | def get_access_key():
return environ.get('HTTP_ACCESSKEY', '')
| Return access_key of your app | return access _ key of your app | Question:
What does this function do?
Code:
def get_access_key():
return environ.get('HTTP_ACCESSKEY', '')
|
null | null | null | What does this function do? | def print_hits(results):
print_search_stats(results)
for hit in results['hits']['hits']:
created_at = parse_date(hit['_source'].get('created_at', hit['_source']['authored_date']))
print(('/%s/%s/%s (%s): %s' % (hit['_index'], hit['_type'], hit['_id'], created_at.strftime('%Y-%m-%d'), hit['_source']['description']... | null | null | null | Simple utility function to print results of a search query. | pcsd | def print hits results print search stats results for hit in results['hits']['hits'] created at = parse date hit[' source'] get 'created at' hit[' source']['authored date'] print '/%s/%s/%s %s %s' % hit[' index'] hit[' type'] hit[' id'] created at strftime '%Y-%m-%d' hit[' source']['description'] replace ' ' ' ' print ... | 16423 | def print_hits(results):
print_search_stats(results)
for hit in results['hits']['hits']:
created_at = parse_date(hit['_source'].get('created_at', hit['_source']['authored_date']))
print(('/%s/%s/%s (%s): %s' % (hit['_index'], hit['_type'], hit['_id'], created_at.strftime('%Y-%m-%d'), hit['_source']['description']... | Simple utility function to print results of a search query. | simple utility function to print results of a search query . | Question:
What does this function do?
Code:
def print_hits(results):
print_search_stats(results)
for hit in results['hits']['hits']:
created_at = parse_date(hit['_source'].get('created_at', hit['_source']['authored_date']))
print(('/%s/%s/%s (%s): %s' % (hit['_index'], hit['_type'], hit['_id'], created_at.strf... |
null | null | null | What does this function do? | def stZCR(frame):
count = len(frame)
countZ = (numpy.sum(numpy.abs(numpy.diff(numpy.sign(frame)))) / 2)
return (numpy.float64(countZ) / numpy.float64((count - 1.0)))
| null | null | null | Computes zero crossing rate of frame | pcsd | def st ZCR frame count = len frame count Z = numpy sum numpy abs numpy diff numpy sign frame / 2 return numpy float64 count Z / numpy float64 count - 1 0 | 16428 | def stZCR(frame):
count = len(frame)
countZ = (numpy.sum(numpy.abs(numpy.diff(numpy.sign(frame)))) / 2)
return (numpy.float64(countZ) / numpy.float64((count - 1.0)))
| Computes zero crossing rate of frame | computes zero crossing rate of frame | Question:
What does this function do?
Code:
def stZCR(frame):
count = len(frame)
countZ = (numpy.sum(numpy.abs(numpy.diff(numpy.sign(frame)))) / 2)
return (numpy.float64(countZ) / numpy.float64((count - 1.0)))
|
null | null | null | What does this function do? | @downgrades(3)
def _downgrade_v3(op):
op.create_table('_new_equities', sa.Column('sid', sa.Integer, unique=True, nullable=False, primary_key=True), sa.Column('symbol', sa.Text), sa.Column('company_symbol', sa.Text), sa.Column('share_class_symbol', sa.Text), sa.Column('fuzzy_symbol', sa.Text), sa.Column('asset_name', s... | null | null | null | Downgrade assets db by adding a not null constraint on
``equities.first_traded`` | pcsd | @downgrades 3 def downgrade v3 op op create table ' new equities' sa Column 'sid' sa Integer unique=True nullable=False primary key=True sa Column 'symbol' sa Text sa Column 'company symbol' sa Text sa Column 'share class symbol' sa Text sa Column 'fuzzy symbol' sa Text sa Column 'asset name' sa Text sa Column 'start d... | 16431 | @downgrades(3)
def _downgrade_v3(op):
op.create_table('_new_equities', sa.Column('sid', sa.Integer, unique=True, nullable=False, primary_key=True), sa.Column('symbol', sa.Text), sa.Column('company_symbol', sa.Text), sa.Column('share_class_symbol', sa.Text), sa.Column('fuzzy_symbol', sa.Text), sa.Column('asset_name', s... | Downgrade assets db by adding a not null constraint on
``equities.first_traded`` | downgrade assets db by adding a not null constraint on equities . first _ traded | Question:
What does this function do?
Code:
@downgrades(3)
def _downgrade_v3(op):
op.create_table('_new_equities', sa.Column('sid', sa.Integer, unique=True, nullable=False, primary_key=True), sa.Column('symbol', sa.Text), sa.Column('company_symbol', sa.Text), sa.Column('share_class_symbol', sa.Text), sa.Column('fuz... |
null | null | null | What does this function do? | def getStyleValue(defaultValue, elementNode, key):
if ('style' in elementNode.attributes):
line = elementNode.attributes['style']
strokeIndex = line.find(key)
if (strokeIndex > (-1)):
words = line[strokeIndex:].replace(':', ' ').replace(';', ' ').split()
if (len(words) > 1):
return words[1]
if (key in... | null | null | null | Get the stroke value string. | pcsd | def get Style Value default Value element Node key if 'style' in element Node attributes line = element Node attributes['style'] stroke Index = line find key if stroke Index > -1 words = line[stroke Index ] replace ' ' ' ' replace ' ' ' ' split if len words > 1 return words[1] if key in element Node attributes return e... | 16437 | def getStyleValue(defaultValue, elementNode, key):
if ('style' in elementNode.attributes):
line = elementNode.attributes['style']
strokeIndex = line.find(key)
if (strokeIndex > (-1)):
words = line[strokeIndex:].replace(':', ' ').replace(';', ' ').split()
if (len(words) > 1):
return words[1]
if (key in... | Get the stroke value string. | get the stroke value string . | Question:
What does this function do?
Code:
def getStyleValue(defaultValue, elementNode, key):
if ('style' in elementNode.attributes):
line = elementNode.attributes['style']
strokeIndex = line.find(key)
if (strokeIndex > (-1)):
words = line[strokeIndex:].replace(':', ' ').replace(';', ' ').split()
if (l... |
null | null | null | What does this function do? | def get_data(url, gallery_dir):
if ((sys.version_info[0] == 2) and isinstance(url, unicode)):
url = url.encode('utf-8')
cached_file = os.path.join(gallery_dir, 'searchindex')
search_index = shelve.open(cached_file)
if (url in search_index):
data = search_index[url]
else:
data = _get_data(url)
search_index[... | null | null | null | Persistent dictionary usage to retrieve the search indexes | pcsd | def get data url gallery dir if sys version info[0] == 2 and isinstance url unicode url = url encode 'utf-8' cached file = os path join gallery dir 'searchindex' search index = shelve open cached file if url in search index data = search index[url] else data = get data url search index[url] = data search index close re... | 16446 | def get_data(url, gallery_dir):
if ((sys.version_info[0] == 2) and isinstance(url, unicode)):
url = url.encode('utf-8')
cached_file = os.path.join(gallery_dir, 'searchindex')
search_index = shelve.open(cached_file)
if (url in search_index):
data = search_index[url]
else:
data = _get_data(url)
search_index[... | Persistent dictionary usage to retrieve the search indexes | persistent dictionary usage to retrieve the search indexes | Question:
What does this function do?
Code:
def get_data(url, gallery_dir):
if ((sys.version_info[0] == 2) and isinstance(url, unicode)):
url = url.encode('utf-8')
cached_file = os.path.join(gallery_dir, 'searchindex')
search_index = shelve.open(cached_file)
if (url in search_index):
data = search_index[url]... |
null | null | null | What does this function do? | def _count_newlines_from_end(in_str):
try:
i = len(in_str)
j = (i - 1)
while (in_str[j] == '\n'):
j -= 1
return ((i - 1) - j)
except IndexError:
return i
| null | null | null | Counts the number of newlines at the end of a string. This is used during
the jinja2 templating to ensure the count matches the input, since some newlines
may be thrown away during the templating. | pcsd | def count newlines from end in str try i = len in str j = i - 1 while in str[j] == ' ' j -= 1 return i - 1 - j except Index Error return i | 16454 | def _count_newlines_from_end(in_str):
try:
i = len(in_str)
j = (i - 1)
while (in_str[j] == '\n'):
j -= 1
return ((i - 1) - j)
except IndexError:
return i
| Counts the number of newlines at the end of a string. This is used during
the jinja2 templating to ensure the count matches the input, since some newlines
may be thrown away during the templating. | counts the number of newlines at the end of a string . | Question:
What does this function do?
Code:
def _count_newlines_from_end(in_str):
try:
i = len(in_str)
j = (i - 1)
while (in_str[j] == '\n'):
j -= 1
return ((i - 1) - j)
except IndexError:
return i
|
null | null | null | What does this function do? | def single_tab(pl, segment_info, mode):
return (len(list_tabpages()) == 1)
| null | null | null | Returns True if Vim has only one tab opened | pcsd | def single tab pl segment info mode return len list tabpages == 1 | 16459 | def single_tab(pl, segment_info, mode):
return (len(list_tabpages()) == 1)
| Returns True if Vim has only one tab opened | returns true if vim has only one tab opened | Question:
What does this function do?
Code:
def single_tab(pl, segment_info, mode):
return (len(list_tabpages()) == 1)
|
null | null | null | What does this function do? | def make_pad_velocity_curve_message(index, velocities):
raise ((len(velocities) == PAD_VELOCITY_CURVE_CHUNK_SIZE) or AssertionError)
return make_message(32, ((index,) + tuple(velocities)))
| null | null | null | Updates a chunk of velocities in the voltage to velocity table.
The index refers to the first entry in the velocities list. | pcsd | def make pad velocity curve message index velocities raise len velocities == PAD VELOCITY CURVE CHUNK SIZE or Assertion Error return make message 32 index + tuple velocities | 16473 | def make_pad_velocity_curve_message(index, velocities):
raise ((len(velocities) == PAD_VELOCITY_CURVE_CHUNK_SIZE) or AssertionError)
return make_message(32, ((index,) + tuple(velocities)))
| Updates a chunk of velocities in the voltage to velocity table.
The index refers to the first entry in the velocities list. | updates a chunk of velocities in the voltage to velocity table . | Question:
What does this function do?
Code:
def make_pad_velocity_curve_message(index, velocities):
raise ((len(velocities) == PAD_VELOCITY_CURVE_CHUNK_SIZE) or AssertionError)
return make_message(32, ((index,) + tuple(velocities)))
|
null | null | null | What does this function do? | def bootstrap_app():
from salt.netapi.rest_cherrypy import app
import salt.config
__opts__ = salt.config.client_config(os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
return app.get_app(__opts__)
| null | null | null | Grab the opts dict of the master config by trying to import Salt | pcsd | def bootstrap app from salt netapi rest cherrypy import app import salt config opts = salt config client config os environ get 'SALT MASTER CONFIG' '/etc/salt/master' return app get app opts | 16478 | def bootstrap_app():
from salt.netapi.rest_cherrypy import app
import salt.config
__opts__ = salt.config.client_config(os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
return app.get_app(__opts__)
| Grab the opts dict of the master config by trying to import Salt | grab the opts dict of the master config by trying to import salt | Question:
What does this function do?
Code:
def bootstrap_app():
from salt.netapi.rest_cherrypy import app
import salt.config
__opts__ = salt.config.client_config(os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
return app.get_app(__opts__)
|
null | null | null | What does this function do? | @public
def hermite_poly(n, x=None, **args):
if (n < 0):
raise ValueError(("can't generate Hermite polynomial of degree %s" % n))
poly = DMP(dup_hermite(int(n), ZZ), ZZ)
if (x is not None):
poly = Poly.new(poly, x)
else:
poly = PurePoly.new(poly, Dummy('x'))
if (not args.get('polys', False)):
return poly.a... | null | null | null | Generates Hermite polynomial of degree `n` in `x`. | pcsd | @public def hermite poly n x=None **args if n < 0 raise Value Error "can't generate Hermite polynomial of degree %s" % n poly = DMP dup hermite int n ZZ ZZ if x is not None poly = Poly new poly x else poly = Pure Poly new poly Dummy 'x' if not args get 'polys' False return poly as expr else return poly | 16488 | @public
def hermite_poly(n, x=None, **args):
if (n < 0):
raise ValueError(("can't generate Hermite polynomial of degree %s" % n))
poly = DMP(dup_hermite(int(n), ZZ), ZZ)
if (x is not None):
poly = Poly.new(poly, x)
else:
poly = PurePoly.new(poly, Dummy('x'))
if (not args.get('polys', False)):
return poly.a... | Generates Hermite polynomial of degree `n` in `x`. | generates hermite polynomial of degree n in x . | Question:
What does this function do?
Code:
@public
def hermite_poly(n, x=None, **args):
if (n < 0):
raise ValueError(("can't generate Hermite polynomial of degree %s" % n))
poly = DMP(dup_hermite(int(n), ZZ), ZZ)
if (x is not None):
poly = Poly.new(poly, x)
else:
poly = PurePoly.new(poly, Dummy('x'))
if ... |
null | null | null | What does this function do? | def _is_descriptor(obj):
return (hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__'))
| null | null | null | Returns True if obj is a descriptor, False otherwise. | pcsd | def is descriptor obj return hasattr obj ' get ' or hasattr obj ' set ' or hasattr obj ' delete ' | 16495 | def _is_descriptor(obj):
return (hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__'))
| Returns True if obj is a descriptor, False otherwise. | returns true if obj is a descriptor , false otherwise . | Question:
What does this function do?
Code:
def _is_descriptor(obj):
return (hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__'))
|
null | null | null | What does this function do? | def colorize(color, text):
if config['color']:
return _colorize(color, text)
else:
return text
| null | null | null | Colorize text if colored output is enabled. (Like _colorize but
conditional.) | pcsd | def colorize color text if config['color'] return colorize color text else return text | 16499 | def colorize(color, text):
if config['color']:
return _colorize(color, text)
else:
return text
| Colorize text if colored output is enabled. (Like _colorize but
conditional.) | colorize text if colored output is enabled . | Question:
What does this function do?
Code:
def colorize(color, text):
if config['color']:
return _colorize(color, text)
else:
return text
|
null | null | null | What does this function do? | def get_last_day(dt):
return (get_first_day(dt, 0, 1) + datetime.timedelta((-1)))
| null | null | null | Returns last day of the month using:
`get_first_day(dt, 0, 1) + datetime.timedelta(-1)` | pcsd | def get last day dt return get first day dt 0 1 + datetime timedelta -1 | 16507 | def get_last_day(dt):
return (get_first_day(dt, 0, 1) + datetime.timedelta((-1)))
| Returns last day of the month using:
`get_first_day(dt, 0, 1) + datetime.timedelta(-1)` | returns last day of the month using : get _ first _ day + datetime . timedelta | Question:
What does this function do?
Code:
def get_last_day(dt):
return (get_first_day(dt, 0, 1) + datetime.timedelta((-1)))
|
null | null | null | What does this function do? | def poisson2d(N, dtype='d', format=None):
if (N == 1):
diags = asarray([[4]], dtype=dtype)
return dia_matrix((diags, [0]), shape=(1, 1)).asformat(format)
offsets = array([0, (- N), N, (-1), 1])
diags = empty((5, (N ** 2)), dtype=dtype)
diags[0] = 4
diags[1:] = (-1)
diags[3, (N - 1)::N] = 0
diags[4, N::N] = 0... | null | null | null | Return a sparse matrix for the 2D Poisson problem
with standard 5-point finite difference stencil on a
square N-by-N grid. | pcsd | def poisson2d N dtype='d' format=None if N == 1 diags = asarray [[4]] dtype=dtype return dia matrix diags [0] shape= 1 1 asformat format offsets = array [0 - N N -1 1] diags = empty 5 N ** 2 dtype=dtype diags[0] = 4 diags[1 ] = -1 diags[3 N - 1 N] = 0 diags[4 N N] = 0 return dia matrix diags offsets shape= N ** 2 N ** ... | 16510 | def poisson2d(N, dtype='d', format=None):
if (N == 1):
diags = asarray([[4]], dtype=dtype)
return dia_matrix((diags, [0]), shape=(1, 1)).asformat(format)
offsets = array([0, (- N), N, (-1), 1])
diags = empty((5, (N ** 2)), dtype=dtype)
diags[0] = 4
diags[1:] = (-1)
diags[3, (N - 1)::N] = 0
diags[4, N::N] = 0... | Return a sparse matrix for the 2D Poisson problem
with standard 5-point finite difference stencil on a
square N-by-N grid. | return a sparse matrix for the 2d poisson problem with standard 5 - point finite difference stencil on a square n - by - n grid . | Question:
What does this function do?
Code:
def poisson2d(N, dtype='d', format=None):
if (N == 1):
diags = asarray([[4]], dtype=dtype)
return dia_matrix((diags, [0]), shape=(1, 1)).asformat(format)
offsets = array([0, (- N), N, (-1), 1])
diags = empty((5, (N ** 2)), dtype=dtype)
diags[0] = 4
diags[1:] = (-1... |
null | null | null | What does this function do? | def aggregate_values_from_key(host_state, key_name):
aggrlist = host_state.aggregates
return {aggr.metadata[key_name] for aggr in aggrlist if (key_name in aggr.metadata)}
| null | null | null | Returns a set of values based on a metadata key for a specific host. | pcsd | def aggregate values from key host state key name aggrlist = host state aggregates return {aggr metadata[key name] for aggr in aggrlist if key name in aggr metadata } | 16518 | def aggregate_values_from_key(host_state, key_name):
aggrlist = host_state.aggregates
return {aggr.metadata[key_name] for aggr in aggrlist if (key_name in aggr.metadata)}
| Returns a set of values based on a metadata key for a specific host. | returns a set of values based on a metadata key for a specific host . | Question:
What does this function do?
Code:
def aggregate_values_from_key(host_state, key_name):
aggrlist = host_state.aggregates
return {aggr.metadata[key_name] for aggr in aggrlist if (key_name in aggr.metadata)}
|
null | null | null | What does this function do? | def lineno():
import inspect
print ('%s DCTB %s' % (datetime.now(), inspect.currentframe().f_back.f_lineno))
| null | null | null | Returns the current line number in our program. | pcsd | def lineno import inspect print '%s DCTB %s' % datetime now inspect currentframe f back f lineno | 16523 | def lineno():
import inspect
print ('%s DCTB %s' % (datetime.now(), inspect.currentframe().f_back.f_lineno))
| Returns the current line number in our program. | returns the current line number in our program . | Question:
What does this function do?
Code:
def lineno():
import inspect
print ('%s DCTB %s' % (datetime.now(), inspect.currentframe().f_back.f_lineno))
|
null | null | null | What does this function do? | @verbose
def _get_partitions_from_connectivity(connectivity, n_times, verbose=None):
if isinstance(connectivity, list):
test = np.ones(len(connectivity))
test_conn = np.zeros((len(connectivity), len(connectivity)), dtype='bool')
for vi in range(len(connectivity)):
test_conn[(connectivity[vi], vi)] = True
te... | null | null | null | Specify disjoint subsets (e.g., hemispheres) based on connectivity. | pcsd | @verbose def get partitions from connectivity connectivity n times verbose=None if isinstance connectivity list test = np ones len connectivity test conn = np zeros len connectivity len connectivity dtype='bool' for vi in range len connectivity test conn[ connectivity[vi] vi ] = True test conn = sparse coo matrix test ... | 16530 | @verbose
def _get_partitions_from_connectivity(connectivity, n_times, verbose=None):
if isinstance(connectivity, list):
test = np.ones(len(connectivity))
test_conn = np.zeros((len(connectivity), len(connectivity)), dtype='bool')
for vi in range(len(connectivity)):
test_conn[(connectivity[vi], vi)] = True
te... | Specify disjoint subsets (e.g., hemispheres) based on connectivity. | specify disjoint subsets based on connectivity . | Question:
What does this function do?
Code:
@verbose
def _get_partitions_from_connectivity(connectivity, n_times, verbose=None):
if isinstance(connectivity, list):
test = np.ones(len(connectivity))
test_conn = np.zeros((len(connectivity), len(connectivity)), dtype='bool')
for vi in range(len(connectivity)):
... |
null | null | null | What does this function do? | def deactivate_all():
_active.value = gettext_module.NullTranslations()
| null | null | null | Makes the active translation object a NullTranslations() instance. This is
useful when we want delayed translations to appear as the original string
for some reason. | pcsd | def deactivate all active value = gettext module Null Translations | 16532 | def deactivate_all():
_active.value = gettext_module.NullTranslations()
| Makes the active translation object a NullTranslations() instance. This is
useful when we want delayed translations to appear as the original string
for some reason. | makes the active translation object a nulltranslations ( ) instance . | Question:
What does this function do?
Code:
def deactivate_all():
_active.value = gettext_module.NullTranslations()
|
null | null | null | What does this function do? | def wrap(action, fn, decorator=None):
if (decorator is None):
decorator = _decorator_noop
@functools.wraps(fn)
def wrapped(*args, **kwargs):
return decorator(fn(action(*args, **kwargs)))
return wrapped
| null | null | null | Wrap arguments with `action`, optionally decorate the result | pcsd | def wrap action fn decorator=None if decorator is None decorator = decorator noop @functools wraps fn def wrapped *args **kwargs return decorator fn action *args **kwargs return wrapped | 16533 | def wrap(action, fn, decorator=None):
if (decorator is None):
decorator = _decorator_noop
@functools.wraps(fn)
def wrapped(*args, **kwargs):
return decorator(fn(action(*args, **kwargs)))
return wrapped
| Wrap arguments with `action`, optionally decorate the result | wrap arguments with action , optionally decorate the result | Question:
What does this function do?
Code:
def wrap(action, fn, decorator=None):
if (decorator is None):
decorator = _decorator_noop
@functools.wraps(fn)
def wrapped(*args, **kwargs):
return decorator(fn(action(*args, **kwargs)))
return wrapped
|
null | null | null | What does this function do? | def bzr_wc_target_exists_no_update():
test = 'bzr_wc_target_exists_no_update'
wt = ('%s-test-%s' % (DIR, test))
puts(magenta(('Executing test: %s' % test)))
from fabric.api import run
from fabtools.files import is_dir
from fabtools import require
assert (not is_dir(wt))
require.bazaar.working_copy(REMOTE_URL, w... | null | null | null | Test creating a working copy when target already exists and updating was
not requested. | pcsd | def bzr wc target exists no update test = 'bzr wc target exists no update' wt = '%s-test-%s' % DIR test puts magenta 'Executing test %s' % test from fabric api import run from fabtools files import is dir from fabtools import require assert not is dir wt require bazaar working copy REMOTE URL wt version='2' require baz... | 16539 | def bzr_wc_target_exists_no_update():
test = 'bzr_wc_target_exists_no_update'
wt = ('%s-test-%s' % (DIR, test))
puts(magenta(('Executing test: %s' % test)))
from fabric.api import run
from fabtools.files import is_dir
from fabtools import require
assert (not is_dir(wt))
require.bazaar.working_copy(REMOTE_URL, w... | Test creating a working copy when target already exists and updating was
not requested. | test creating a working copy when target already exists and updating was not requested . | Question:
What does this function do?
Code:
def bzr_wc_target_exists_no_update():
test = 'bzr_wc_target_exists_no_update'
wt = ('%s-test-%s' % (DIR, test))
puts(magenta(('Executing test: %s' % test)))
from fabric.api import run
from fabtools.files import is_dir
from fabtools import require
assert (not is_dir(... |
null | null | null | What does this function do? | def update_package_db(module, port_path):
(rc, out, err) = module.run_command(('%s sync' % port_path))
if (rc != 0):
module.fail_json(msg='could not update package db')
| null | null | null | Updates packages list. | pcsd | def update package db module port path rc out err = module run command '%s sync' % port path if rc != 0 module fail json msg='could not update package db' | 16544 | def update_package_db(module, port_path):
(rc, out, err) = module.run_command(('%s sync' % port_path))
if (rc != 0):
module.fail_json(msg='could not update package db')
| Updates packages list. | updates packages list . | Question:
What does this function do?
Code:
def update_package_db(module, port_path):
(rc, out, err) = module.run_command(('%s sync' % port_path))
if (rc != 0):
module.fail_json(msg='could not update package db')
|
null | null | null | What does this function do? | def create(context, name, group_specs=None, is_public=True, projects=None, description=None):
group_specs = (group_specs or {})
projects = (projects or [])
elevated = (context if context.is_admin else context.elevated())
try:
type_ref = db.group_type_create(elevated, dict(name=name, group_specs=group_specs, is_pu... | null | null | null | Creates group types. | pcsd | def create context name group specs=None is public=True projects=None description=None group specs = group specs or {} projects = projects or [] elevated = context if context is admin else context elevated try type ref = db group type create elevated dict name=name group specs=group specs is public=is public descriptio... | 16549 | def create(context, name, group_specs=None, is_public=True, projects=None, description=None):
group_specs = (group_specs or {})
projects = (projects or [])
elevated = (context if context.is_admin else context.elevated())
try:
type_ref = db.group_type_create(elevated, dict(name=name, group_specs=group_specs, is_pu... | Creates group types. | creates group types . | Question:
What does this function do?
Code:
def create(context, name, group_specs=None, is_public=True, projects=None, description=None):
group_specs = (group_specs or {})
projects = (projects or [])
elevated = (context if context.is_admin else context.elevated())
try:
type_ref = db.group_type_create(elevated,... |
null | null | null | What does this function do? | def dvr_due_followups():
r = S3Request('dvr', 'case_activity', args=[], get_vars={})
r.customise_resource()
resource = r.resource
query = ((((FS('followup') == True) & (FS('followup_date') <= datetime.datetime.utcnow().date())) & (FS('completed') != True)) & (FS('person_id$dvr_case.archived') == False))
resource.a... | null | null | null | Number of due follow-ups | pcsd | def dvr due followups r = S3Request 'dvr' 'case activity' args=[] get vars={} r customise resource resource = r resource query = FS 'followup' == True & FS 'followup date' <= datetime datetime utcnow date & FS 'completed' != True & FS 'person id$dvr case archived' == False resource add filter query return resource coun... | 16566 | def dvr_due_followups():
r = S3Request('dvr', 'case_activity', args=[], get_vars={})
r.customise_resource()
resource = r.resource
query = ((((FS('followup') == True) & (FS('followup_date') <= datetime.datetime.utcnow().date())) & (FS('completed') != True)) & (FS('person_id$dvr_case.archived') == False))
resource.a... | Number of due follow-ups | number of due follow - ups | Question:
What does this function do?
Code:
def dvr_due_followups():
r = S3Request('dvr', 'case_activity', args=[], get_vars={})
r.customise_resource()
resource = r.resource
query = ((((FS('followup') == True) & (FS('followup_date') <= datetime.datetime.utcnow().date())) & (FS('completed') != True)) & (FS('perso... |
null | null | null | What does this function do? | def round_corner(radius, fill):
corner = Image.new(u'L', (radius, radius), 0)
draw = ImageDraw.Draw(corner)
draw.pieslice((0, 0, (radius * 2), (radius * 2)), 180, 270, fill=fill)
return corner
| null | null | null | Draw a round corner | pcsd | def round corner radius fill corner = Image new u'L' radius radius 0 draw = Image Draw Draw corner draw pieslice 0 0 radius * 2 radius * 2 180 270 fill=fill return corner | 16576 | def round_corner(radius, fill):
corner = Image.new(u'L', (radius, radius), 0)
draw = ImageDraw.Draw(corner)
draw.pieslice((0, 0, (radius * 2), (radius * 2)), 180, 270, fill=fill)
return corner
| Draw a round corner | draw a round corner | Question:
What does this function do?
Code:
def round_corner(radius, fill):
corner = Image.new(u'L', (radius, radius), 0)
draw = ImageDraw.Draw(corner)
draw.pieslice((0, 0, (radius * 2), (radius * 2)), 180, 270, fill=fill)
return corner
|
null | null | null | What does this function do? | def image_tag_get_all(context, image_id, session=None):
_check_image_id(image_id)
session = (session or get_session())
tags = session.query(models.ImageTag.value).filter_by(image_id=image_id).filter_by(deleted=False).all()
return [tag[0] for tag in tags]
| null | null | null | Get a list of tags for a specific image. | pcsd | def image tag get all context image id session=None check image id image id session = session or get session tags = session query models Image Tag value filter by image id=image id filter by deleted=False all return [tag[0] for tag in tags] | 16583 | def image_tag_get_all(context, image_id, session=None):
_check_image_id(image_id)
session = (session or get_session())
tags = session.query(models.ImageTag.value).filter_by(image_id=image_id).filter_by(deleted=False).all()
return [tag[0] for tag in tags]
| Get a list of tags for a specific image. | get a list of tags for a specific image . | Question:
What does this function do?
Code:
def image_tag_get_all(context, image_id, session=None):
_check_image_id(image_id)
session = (session or get_session())
tags = session.query(models.ImageTag.value).filter_by(image_id=image_id).filter_by(deleted=False).all()
return [tag[0] for tag in tags]
|
null | null | null | What does this function do? | def action_peek_json(body):
try:
decoded = jsonutils.loads(body)
except ValueError:
msg = _('cannot understand JSON')
raise exception.MalformedRequestBody(reason=msg)
if (len(decoded) != 1):
msg = _('too many body keys')
raise exception.MalformedRequestBody(reason=msg)
return decoded.keys()[0]
| null | null | null | Determine action to invoke. | pcsd | def action peek json body try decoded = jsonutils loads body except Value Error msg = 'cannot understand JSON' raise exception Malformed Request Body reason=msg if len decoded != 1 msg = 'too many body keys' raise exception Malformed Request Body reason=msg return decoded keys [0] | 16585 | def action_peek_json(body):
try:
decoded = jsonutils.loads(body)
except ValueError:
msg = _('cannot understand JSON')
raise exception.MalformedRequestBody(reason=msg)
if (len(decoded) != 1):
msg = _('too many body keys')
raise exception.MalformedRequestBody(reason=msg)
return decoded.keys()[0]
| Determine action to invoke. | determine action to invoke . | Question:
What does this function do?
Code:
def action_peek_json(body):
try:
decoded = jsonutils.loads(body)
except ValueError:
msg = _('cannot understand JSON')
raise exception.MalformedRequestBody(reason=msg)
if (len(decoded) != 1):
msg = _('too many body keys')
raise exception.MalformedRequestBody(re... |
null | null | null | What does this function do? | def mobify_image(data):
fmt = what(None, data)
if (fmt == u'png'):
from PIL import Image
im = Image.open(BytesIO(data))
buf = BytesIO()
im.save(buf, u'gif')
data = buf.getvalue()
return data
| null | null | null | Convert PNG images to GIF as the idiotic Kindle cannot display some PNG | pcsd | def mobify image data fmt = what None data if fmt == u'png' from PIL import Image im = Image open Bytes IO data buf = Bytes IO im save buf u'gif' data = buf getvalue return data | 16598 | def mobify_image(data):
fmt = what(None, data)
if (fmt == u'png'):
from PIL import Image
im = Image.open(BytesIO(data))
buf = BytesIO()
im.save(buf, u'gif')
data = buf.getvalue()
return data
| Convert PNG images to GIF as the idiotic Kindle cannot display some PNG | convert png images to gif as the idiotic kindle cannot display some png | Question:
What does this function do?
Code:
def mobify_image(data):
fmt = what(None, data)
if (fmt == u'png'):
from PIL import Image
im = Image.open(BytesIO(data))
buf = BytesIO()
im.save(buf, u'gif')
data = buf.getvalue()
return data
|
null | null | null | What does this function do? | def create_resource():
deserializer = CachedImageDeserializer()
serializer = CachedImageSerializer()
return wsgi.Resource(Controller(), deserializer, serializer)
| null | null | null | Cached Images resource factory method | pcsd | def create resource deserializer = Cached Image Deserializer serializer = Cached Image Serializer return wsgi Resource Controller deserializer serializer | 16603 | def create_resource():
deserializer = CachedImageDeserializer()
serializer = CachedImageSerializer()
return wsgi.Resource(Controller(), deserializer, serializer)
| Cached Images resource factory method | cached images resource factory method | Question:
What does this function do?
Code:
def create_resource():
deserializer = CachedImageDeserializer()
serializer = CachedImageSerializer()
return wsgi.Resource(Controller(), deserializer, serializer)
|
null | null | null | What does this function do? | def _unquote_match(match):
s = match.group(0)
return unquote(s)
| null | null | null | Turn a match in the form =AB to the ASCII character with value 0xab | pcsd | def unquote match match s = match group 0 return unquote s | 16610 | def _unquote_match(match):
s = match.group(0)
return unquote(s)
| Turn a match in the form =AB to the ASCII character with value 0xab | turn a match in the form = ab to the ascii character with value 0xab | Question:
What does this function do?
Code:
def _unquote_match(match):
s = match.group(0)
return unquote(s)
|
null | null | null | What does this function do? | def decimal_to_float(x):
if isinstance(x, Decimal):
return float(x)
return x
| null | null | null | Cast Decimal values to float | pcsd | def decimal to float x if isinstance x Decimal return float x return x | 16621 | def decimal_to_float(x):
if isinstance(x, Decimal):
return float(x)
return x
| Cast Decimal values to float | cast decimal values to float | Question:
What does this function do?
Code:
def decimal_to_float(x):
if isinstance(x, Decimal):
return float(x)
return x
|
null | null | null | What does this function do? | def getNewRepository():
return skeinforge_meta.MetaRepository()
| null | null | null | Get the repository constructor. | pcsd | def get New Repository return skeinforge meta Meta Repository | 16623 | def getNewRepository():
return skeinforge_meta.MetaRepository()
| Get the repository constructor. | get the repository constructor . | Question:
What does this function do?
Code:
def getNewRepository():
return skeinforge_meta.MetaRepository()
|
null | null | null | What does this function do? | def create_python_script_action(parent, text, icon, package, module, args=[]):
if is_text_string(icon):
icon = get_icon(icon)
if programs.python_script_exists(package, module):
return create_action(parent, text, icon=icon, triggered=(lambda : programs.run_python_script(package, module, args)))
| null | null | null | Create action to run a GUI based Python script | pcsd | def create python script action parent text icon package module args=[] if is text string icon icon = get icon icon if programs python script exists package module return create action parent text icon=icon triggered= lambda programs run python script package module args | 16625 | def create_python_script_action(parent, text, icon, package, module, args=[]):
if is_text_string(icon):
icon = get_icon(icon)
if programs.python_script_exists(package, module):
return create_action(parent, text, icon=icon, triggered=(lambda : programs.run_python_script(package, module, args)))
| Create action to run a GUI based Python script | create action to run a gui based python script | Question:
What does this function do?
Code:
def create_python_script_action(parent, text, icon, package, module, args=[]):
if is_text_string(icon):
icon = get_icon(icon)
if programs.python_script_exists(package, module):
return create_action(parent, text, icon=icon, triggered=(lambda : programs.run_python_scri... |
null | null | null | What does this function do? | def isAdminFromPrivileges(privileges):
retVal = (Backend.isDbms(DBMS.PGSQL) and ('super' in privileges))
retVal |= (Backend.isDbms(DBMS.ORACLE) and ('DBA' in privileges))
retVal |= (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema and ('SUPER' in privileges))
retVal |= (Backend.isDbms(DBMS.MYSQL) and (... | null | null | null | Inspects privileges to see if those are coming from an admin user | pcsd | def is Admin From Privileges privileges ret Val = Backend is Dbms DBMS PGSQL and 'super' in privileges ret Val |= Backend is Dbms DBMS ORACLE and 'DBA' in privileges ret Val |= Backend is Dbms DBMS MYSQL and kb data has information schema and 'SUPER' in privileges ret Val |= Backend is Dbms DBMS MYSQL and not kb data h... | 16628 | def isAdminFromPrivileges(privileges):
retVal = (Backend.isDbms(DBMS.PGSQL) and ('super' in privileges))
retVal |= (Backend.isDbms(DBMS.ORACLE) and ('DBA' in privileges))
retVal |= (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema and ('SUPER' in privileges))
retVal |= (Backend.isDbms(DBMS.MYSQL) and (... | Inspects privileges to see if those are coming from an admin user | inspects privileges to see if those are coming from an admin user | Question:
What does this function do?
Code:
def isAdminFromPrivileges(privileges):
retVal = (Backend.isDbms(DBMS.PGSQL) and ('super' in privileges))
retVal |= (Backend.isDbms(DBMS.ORACLE) and ('DBA' in privileges))
retVal |= (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema and ('SUPER' in privileges... |
null | null | null | What does this function do? | def excel_to_db(excel_file):
try:
data = xlrd.open_workbook(filename=None, file_contents=excel_file.read())
except Exception as e:
return False
else:
table = data.sheets()[0]
rows = table.nrows
for row_num in range(1, rows):
row = table.row_values(row_num)
if row:
group_instance = []
(ip, por... | null | null | null | Asset add batch function | pcsd | def excel to db excel file try data = xlrd open workbook filename=None file contents=excel file read except Exception as e return False else table = data sheets [0] rows = table nrows for row num in range 1 rows row = table row values row num if row group instance = [] ip port hostname use default auth username passwor... | 16629 | def excel_to_db(excel_file):
try:
data = xlrd.open_workbook(filename=None, file_contents=excel_file.read())
except Exception as e:
return False
else:
table = data.sheets()[0]
rows = table.nrows
for row_num in range(1, rows):
row = table.row_values(row_num)
if row:
group_instance = []
(ip, por... | Asset add batch function | asset add batch function | Question:
What does this function do?
Code:
def excel_to_db(excel_file):
try:
data = xlrd.open_workbook(filename=None, file_contents=excel_file.read())
except Exception as e:
return False
else:
table = data.sheets()[0]
rows = table.nrows
for row_num in range(1, rows):
row = table.row_values(row_num)
... |
null | null | null | What does this function do? | def denormalize(host_string):
from fabric.state import env
r = parse_host_string(host_string)
user = ''
if ((r['user'] is not None) and (r['user'] != env.user)):
user = (r['user'] + '@')
port = ''
if ((r['port'] is not None) and (r['port'] != '22')):
port = (':' + r['port'])
host = r['host']
host = (('[%s]'... | null | null | null | Strips out default values for the given host string.
If the user part is the default user, it is removed;
if the port is port 22, it also is removed. | pcsd | def denormalize host string from fabric state import env r = parse host string host string user = '' if r['user'] is not None and r['user'] != env user user = r['user'] + '@' port = '' if r['port'] is not None and r['port'] != '22' port = ' ' + r['port'] host = r['host'] host = '[%s]' % host if port and host count ' ' ... | 16630 | def denormalize(host_string):
from fabric.state import env
r = parse_host_string(host_string)
user = ''
if ((r['user'] is not None) and (r['user'] != env.user)):
user = (r['user'] + '@')
port = ''
if ((r['port'] is not None) and (r['port'] != '22')):
port = (':' + r['port'])
host = r['host']
host = (('[%s]'... | Strips out default values for the given host string.
If the user part is the default user, it is removed;
if the port is port 22, it also is removed. | strips out default values for the given host string . | Question:
What does this function do?
Code:
def denormalize(host_string):
from fabric.state import env
r = parse_host_string(host_string)
user = ''
if ((r['user'] is not None) and (r['user'] != env.user)):
user = (r['user'] + '@')
port = ''
if ((r['port'] is not None) and (r['port'] != '22')):
port = (':' ... |
null | null | null | What does this function do? | def new_figure_manager(num, *args, **kwargs):
if _debug:
print ('%s.%s()' % (self.__class__.__name__, _fn_name()))
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
canvas = FigureCanvasCairo(thisFig)
manager = FigureManagerBase(canvas, num)
return manager
| null | null | null | Create a new figure manager instance | pcsd | def new figure manager num *args **kwargs if debug print '%s %s ' % self class name fn name Figure Class = kwargs pop 'Figure Class' Figure this Fig = Figure Class *args **kwargs canvas = Figure Canvas Cairo this Fig manager = Figure Manager Base canvas num return manager | 16634 | def new_figure_manager(num, *args, **kwargs):
if _debug:
print ('%s.%s()' % (self.__class__.__name__, _fn_name()))
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
canvas = FigureCanvasCairo(thisFig)
manager = FigureManagerBase(canvas, num)
return manager
| Create a new figure manager instance | create a new figure manager instance | Question:
What does this function do?
Code:
def new_figure_manager(num, *args, **kwargs):
if _debug:
print ('%s.%s()' % (self.__class__.__name__, _fn_name()))
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
canvas = FigureCanvasCairo(thisFig)
manager = FigureManagerBase(... |
null | null | null | What does this function do? | @check_simple_wiki_locale
@mobile_template('products/{mobile/}products.html')
def product_list(request, template):
products = Product.objects.filter(visible=True)
return render(request, template, {'products': products})
| null | null | null | The product picker page. | pcsd | @check simple wiki locale @mobile template 'products/{mobile/}products html' def product list request template products = Product objects filter visible=True return render request template {'products' products} | 16638 | @check_simple_wiki_locale
@mobile_template('products/{mobile/}products.html')
def product_list(request, template):
products = Product.objects.filter(visible=True)
return render(request, template, {'products': products})
| The product picker page. | the product picker page . | Question:
What does this function do?
Code:
@check_simple_wiki_locale
@mobile_template('products/{mobile/}products.html')
def product_list(request, template):
products = Product.objects.filter(visible=True)
return render(request, template, {'products': products})
|
null | null | null | What does this function do? | def get_minions():
log.debug('sqlite3 returner <get_minions> called')
conn = _get_conn(ret=None)
cur = conn.cursor()
sql = 'SELECT DISTINCT id FROM salt_returns'
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
_close_conn(conn)
return ret
| null | null | null | Return a list of minions | pcsd | def get minions log debug 'sqlite3 returner <get minions> called' conn = get conn ret=None cur = conn cursor sql = 'SELECT DISTINCT id FROM salt returns' cur execute sql data = cur fetchall ret = [] for minion in data ret append minion[0] close conn conn return ret | 16641 | def get_minions():
log.debug('sqlite3 returner <get_minions> called')
conn = _get_conn(ret=None)
cur = conn.cursor()
sql = 'SELECT DISTINCT id FROM salt_returns'
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
_close_conn(conn)
return ret
| Return a list of minions | return a list of minions | Question:
What does this function do?
Code:
def get_minions():
log.debug('sqlite3 returner <get_minions> called')
conn = _get_conn(ret=None)
cur = conn.cursor()
sql = 'SELECT DISTINCT id FROM salt_returns'
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
_close_con... |
null | null | null | What does this function do? | def _get_dir_list(load):
if ('env' in load):
salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will be removed in Salt Oxygen.")
load.pop('env')
if (('saltenv' not in loa... | null | null | null | Get a list of all directories on the master | pcsd | def get dir list load if 'env' in load salt utils warn until 'Oxygen' "Parameter 'env' has been detected in the argument list This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016 11 0 This warning will be removed in Salt Oxygen " load pop 'env' if 'saltenv' not in load or load['saltenv'] ... | 16644 | def _get_dir_list(load):
if ('env' in load):
salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will be removed in Salt Oxygen.")
load.pop('env')
if (('saltenv' not in loa... | Get a list of all directories on the master | get a list of all directories on the master | Question:
What does this function do?
Code:
def _get_dir_list(load):
if ('env' in load):
salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will be removed in Salt Oxygen.... |
null | null | null | What does this function do? | def _get_new_state_file_name(zone):
return ((STATE_FILENAME + '.') + zone)
| null | null | null | take zone and return multi regional bee file,
from ~/.bees to ~/.bees.${region} | pcsd | def get new state file name zone return STATE FILENAME + ' ' + zone | 16652 | def _get_new_state_file_name(zone):
return ((STATE_FILENAME + '.') + zone)
| take zone and return multi regional bee file,
from ~/.bees to ~/.bees.${region} | take zone and return multi regional bee file , from ~ / . bees to ~ / . bees . $ { region } | Question:
What does this function do?
Code:
def _get_new_state_file_name(zone):
return ((STATE_FILENAME + '.') + zone)
|
null | null | null | What does this function do? | def get_default_fetch_deadline():
return getattr(_thread_local_settings, 'default_fetch_deadline', None)
| null | null | null | Get the default value for create_rpc()\'s deadline parameter. | pcsd | def get default fetch deadline return getattr thread local settings 'default fetch deadline' None | 16670 | def get_default_fetch_deadline():
return getattr(_thread_local_settings, 'default_fetch_deadline', None)
| Get the default value for create_rpc()\'s deadline parameter. | get the default value for create _ rpc ( ) s deadline parameter . | Question:
What does this function do?
Code:
def get_default_fetch_deadline():
return getattr(_thread_local_settings, 'default_fetch_deadline', None)
|
null | null | null | What does this function do? | def current_time():
return time.time()
| null | null | null | Retrieve the current time. This function is mocked out in unit testing. | pcsd | def current time return time time | 16679 | def current_time():
return time.time()
| Retrieve the current time. This function is mocked out in unit testing. | retrieve the current time . | Question:
What does this function do?
Code:
def current_time():
return time.time()
|
null | null | null | What does this function do? | def sentence_position(i, size):
normalized = ((i * 1.0) / size)
if (normalized > 1.0):
return 0
elif (normalized > 0.9):
return 0.15
elif (normalized > 0.8):
return 0.04
elif (normalized > 0.7):
return 0.04
elif (normalized > 0.6):
return 0.06
elif (normalized > 0.5):
return 0.04
elif (normalized > ... | null | null | null | Different sentence positions indicate different
probability of being an important sentence. | pcsd | def sentence position i size normalized = i * 1 0 / size if normalized > 1 0 return 0 elif normalized > 0 9 return 0 15 elif normalized > 0 8 return 0 04 elif normalized > 0 7 return 0 04 elif normalized > 0 6 return 0 06 elif normalized > 0 5 return 0 04 elif normalized > 0 4 return 0 05 elif normalized > 0 3 return 0... | 16682 | def sentence_position(i, size):
normalized = ((i * 1.0) / size)
if (normalized > 1.0):
return 0
elif (normalized > 0.9):
return 0.15
elif (normalized > 0.8):
return 0.04
elif (normalized > 0.7):
return 0.04
elif (normalized > 0.6):
return 0.06
elif (normalized > 0.5):
return 0.04
elif (normalized > ... | Different sentence positions indicate different
probability of being an important sentence. | different sentence positions indicate different probability of being an important sentence . | Question:
What does this function do?
Code:
def sentence_position(i, size):
normalized = ((i * 1.0) / size)
if (normalized > 1.0):
return 0
elif (normalized > 0.9):
return 0.15
elif (normalized > 0.8):
return 0.04
elif (normalized > 0.7):
return 0.04
elif (normalized > 0.6):
return 0.06
elif (normal... |
null | null | null | What does this function do? | @library.filter
def label_with_help(f):
label = u'<label for="%s" title="%s">%s</label>'
return jinja2.Markup((label % (f.auto_id, f.help_text, f.label)))
| null | null | null | Print the label tag for a form field, including the help_text
value as a title attribute. | pcsd | @library filter def label with help f label = u'<label for="%s" title="%s">%s</label>' return jinja2 Markup label % f auto id f help text f label | 16684 | @library.filter
def label_with_help(f):
label = u'<label for="%s" title="%s">%s</label>'
return jinja2.Markup((label % (f.auto_id, f.help_text, f.label)))
| Print the label tag for a form field, including the help_text
value as a title attribute. | print the label tag for a form field , including the help _ text value as a title attribute . | Question:
What does this function do?
Code:
@library.filter
def label_with_help(f):
label = u'<label for="%s" title="%s">%s</label>'
return jinja2.Markup((label % (f.auto_id, f.help_text, f.label)))
|
null | null | null | What does this function do? | @when(u'we create database')
def step_db_create(context):
context.cli.sendline(u'create database {0};'.format(context.conf[u'dbname_tmp']))
context.response = {u'database_name': context.conf[u'dbname_tmp']}
| null | null | null | Send create database. | pcsd | @when u'we create database' def step db create context context cli sendline u'create database {0} ' format context conf[u'dbname tmp'] context response = {u'database name' context conf[u'dbname tmp']} | 16701 | @when(u'we create database')
def step_db_create(context):
context.cli.sendline(u'create database {0};'.format(context.conf[u'dbname_tmp']))
context.response = {u'database_name': context.conf[u'dbname_tmp']}
| Send create database. | send create database . | Question:
What does this function do?
Code:
@when(u'we create database')
def step_db_create(context):
context.cli.sendline(u'create database {0};'.format(context.conf[u'dbname_tmp']))
context.response = {u'database_name': context.conf[u'dbname_tmp']}
|
null | null | null | What does this function do? | def _process_mass_form(f):
def wrap(request, *args, **kwargs):
'Wrap'
user = request.user.profile
if ('massform' in request.POST):
for key in request.POST:
if ('mass-message' in key):
try:
message = Message.objects.get(pk=request.POST[key])
form = MassActionForm(user, request.POST, instan... | null | null | null | Pre-process request to handle mass action form for Messages | pcsd | def process mass form f def wrap request *args **kwargs 'Wrap' user = request user profile if 'massform' in request POST for key in request POST if 'mass-message' in key try message = Message objects get pk=request POST[key] form = Mass Action Form user request POST instance=message if form is valid and user has permis... | 16705 | def _process_mass_form(f):
def wrap(request, *args, **kwargs):
'Wrap'
user = request.user.profile
if ('massform' in request.POST):
for key in request.POST:
if ('mass-message' in key):
try:
message = Message.objects.get(pk=request.POST[key])
form = MassActionForm(user, request.POST, instan... | Pre-process request to handle mass action form for Messages | pre - process request to handle mass action form for messages | Question:
What does this function do?
Code:
def _process_mass_form(f):
def wrap(request, *args, **kwargs):
'Wrap'
user = request.user.profile
if ('massform' in request.POST):
for key in request.POST:
if ('mass-message' in key):
try:
message = Message.objects.get(pk=request.POST[key])
f... |
null | null | null | What does this function do? | def get_vol_list(ip, user, passwd):
cmd = 'showvv'
showvv_list = run_ssh_thread(ip, user, passwd, cmd)
vol_list = []
line_num = 0
for line in showvv_list:
line_num += 1
if ('-------------------------' in line):
break
if (('-----' in line) or ('rcpy.' in line) or ('.srdata' in line) or ('0 admin' in line))... | null | null | null | Get a list of volumes to build metric definitions with | pcsd | def get vol list ip user passwd cmd = 'showvv' showvv list = run ssh thread ip user passwd cmd vol list = [] line num = 0 for line in showvv list line num += 1 if '-------------------------' in line break if '-----' in line or 'rcpy ' in line or ' srdata' in line or '0 admin' in line continue if line num >= 4 vol stats... | 16714 | def get_vol_list(ip, user, passwd):
cmd = 'showvv'
showvv_list = run_ssh_thread(ip, user, passwd, cmd)
vol_list = []
line_num = 0
for line in showvv_list:
line_num += 1
if ('-------------------------' in line):
break
if (('-----' in line) or ('rcpy.' in line) or ('.srdata' in line) or ('0 admin' in line))... | Get a list of volumes to build metric definitions with | get a list of volumes to build metric definitions with | Question:
What does this function do?
Code:
def get_vol_list(ip, user, passwd):
cmd = 'showvv'
showvv_list = run_ssh_thread(ip, user, passwd, cmd)
vol_list = []
line_num = 0
for line in showvv_list:
line_num += 1
if ('-------------------------' in line):
break
if (('-----' in line) or ('rcpy.' in line)... |
null | null | null | What does this function do? | def email_channel():
if (not auth.s3_has_role(ADMIN)):
auth.permission.fail()
tablename = 'msg_email_channel'
table = s3db[tablename]
table.server.label = T('Server')
table.protocol.label = T('Protocol')
table.use_ssl.label = 'SSL'
table.port.label = T('Port')
table.username.label = T('Username')
table.passw... | null | null | null | RESTful CRUD controller for Inbound Email channels
- appears in the administration menu | pcsd | def email channel if not auth s3 has role ADMIN auth permission fail tablename = 'msg email channel' table = s3db[tablename] table server label = T 'Server' table protocol label = T 'Protocol' table use ssl label = 'SSL' table port label = T 'Port' table username label = T 'Username' table password label = T 'Password'... | 16719 | def email_channel():
if (not auth.s3_has_role(ADMIN)):
auth.permission.fail()
tablename = 'msg_email_channel'
table = s3db[tablename]
table.server.label = T('Server')
table.protocol.label = T('Protocol')
table.use_ssl.label = 'SSL'
table.port.label = T('Port')
table.username.label = T('Username')
table.passw... | RESTful CRUD controller for Inbound Email channels
- appears in the administration menu | restful crud controller for inbound email channels - appears in the administration menu | Question:
What does this function do?
Code:
def email_channel():
if (not auth.s3_has_role(ADMIN)):
auth.permission.fail()
tablename = 'msg_email_channel'
table = s3db[tablename]
table.server.label = T('Server')
table.protocol.label = T('Protocol')
table.use_ssl.label = 'SSL'
table.port.label = T('Port')
ta... |
null | null | null | What does this function do? | def get_random_string(length=12, allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
if (not using_sysrandom):
random.seed(hashlib.sha256((u'%s%s%s' % (random.getstate(), time.time(), UNSECURE_RANDOM_STRING))).digest())
return u''.join([random.choice(allowed_chars) for i in range(lengt... | null | null | null | Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits | pcsd | def get random string length=12 allowed chars=u'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' if not using sysrandom random seed hashlib sha256 u'%s%s%s' % random getstate time time UNSECURE RANDOM STRING digest return u'' join [random choice allowed chars for i in range length ] | 16746 | def get_random_string(length=12, allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
if (not using_sysrandom):
random.seed(hashlib.sha256((u'%s%s%s' % (random.getstate(), time.time(), UNSECURE_RANDOM_STRING))).digest())
return u''.join([random.choice(allowed_chars) for i in range(lengt... | Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits | returns a securely generated random string . | Question:
What does this function do?
Code:
def get_random_string(length=12, allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
if (not using_sysrandom):
random.seed(hashlib.sha256((u'%s%s%s' % (random.getstate(), time.time(), UNSECURE_RANDOM_STRING))).digest())
return u''.join([ra... |
null | null | null | What does this function do? | def getManipulatedPaths(close, elementNode, loop, prefix, sideLength):
rotatePoints(elementNode, loop, prefix)
return [loop]
| null | null | null | Get equated paths. | pcsd | def get Manipulated Paths close element Node loop prefix side Length rotate Points element Node loop prefix return [loop] | 16749 | def getManipulatedPaths(close, elementNode, loop, prefix, sideLength):
rotatePoints(elementNode, loop, prefix)
return [loop]
| Get equated paths. | get equated paths . | Question:
What does this function do?
Code:
def getManipulatedPaths(close, elementNode, loop, prefix, sideLength):
rotatePoints(elementNode, loop, prefix)
return [loop]
|
null | null | null | What does this function do? | @require_POST
@login_required
@permitted
def vote_for_comment(request, course_id, comment_id, value):
comment = cc.Comment.find(comment_id)
result = _vote_or_unvote(request, course_id, comment, value)
comment_voted.send(sender=None, user=request.user, post=comment)
return result
| null | null | null | Given a course_id and comment_id, vote for this response. AJAX only. | pcsd | @require POST @login required @permitted def vote for comment request course id comment id value comment = cc Comment find comment id result = vote or unvote request course id comment value comment voted send sender=None user=request user post=comment return result | 16758 | @require_POST
@login_required
@permitted
def vote_for_comment(request, course_id, comment_id, value):
comment = cc.Comment.find(comment_id)
result = _vote_or_unvote(request, course_id, comment, value)
comment_voted.send(sender=None, user=request.user, post=comment)
return result
| Given a course_id and comment_id, vote for this response. AJAX only. | given a course _ id and comment _ id , vote for this response . | Question:
What does this function do?
Code:
@require_POST
@login_required
@permitted
def vote_for_comment(request, course_id, comment_id, value):
comment = cc.Comment.find(comment_id)
result = _vote_or_unvote(request, course_id, comment, value)
comment_voted.send(sender=None, user=request.user, post=comment)
ret... |
null | null | null | What does this function do? | @never_cache
def filterchain_all(request, app, model, field, foreign_key_app_name, foreign_key_model_name, foreign_key_field_name, value):
model_class = get_model(app, model)
keywords = get_keywords(field, value)
limit_choices_to = get_limit_choices_to(foreign_key_app_name, foreign_key_model_name, foreign_key_field_... | null | null | null | Returns filtered results followed by excluded results below. | pcsd | @never cache def filterchain all request app model field foreign key app name foreign key model name foreign key field name value model class = get model app model keywords = get keywords field value limit choices to = get limit choices to foreign key app name foreign key model name foreign key field name queryset = ge... | 16768 | @never_cache
def filterchain_all(request, app, model, field, foreign_key_app_name, foreign_key_model_name, foreign_key_field_name, value):
model_class = get_model(app, model)
keywords = get_keywords(field, value)
limit_choices_to = get_limit_choices_to(foreign_key_app_name, foreign_key_model_name, foreign_key_field_... | Returns filtered results followed by excluded results below. | returns filtered results followed by excluded results below . | Question:
What does this function do?
Code:
@never_cache
def filterchain_all(request, app, model, field, foreign_key_app_name, foreign_key_model_name, foreign_key_field_name, value):
model_class = get_model(app, model)
keywords = get_keywords(field, value)
limit_choices_to = get_limit_choices_to(foreign_key_app_n... |
null | null | null | What does this function do? | def core_requirements():
with open('setup.py') as inp:
reqs_raw = re.search('REQUIRES = \\[(.*?)\\]', inp.read(), re.S).group(1)
return re.findall("'(.*?)'", reqs_raw)
| null | null | null | Gather core requirements out of setup.py. | pcsd | def core requirements with open 'setup py' as inp reqs raw = re search 'REQUIRES = \\[ *? \\]' inp read re S group 1 return re findall "' *? '" reqs raw | 16774 | def core_requirements():
with open('setup.py') as inp:
reqs_raw = re.search('REQUIRES = \\[(.*?)\\]', inp.read(), re.S).group(1)
return re.findall("'(.*?)'", reqs_raw)
| Gather core requirements out of setup.py. | gather core requirements out of setup . py . | Question:
What does this function do?
Code:
def core_requirements():
with open('setup.py') as inp:
reqs_raw = re.search('REQUIRES = \\[(.*?)\\]', inp.read(), re.S).group(1)
return re.findall("'(.*?)'", reqs_raw)
|
null | null | null | What does this function do? | def empty_list(lineno=None, col=None):
return ast.List(elts=[], ctx=ast.Load(), lineno=lineno, col_offset=col)
| null | null | null | Creates the AST node for an empty list. | pcsd | def empty list lineno=None col=None return ast List elts=[] ctx=ast Load lineno=lineno col offset=col | 16776 | def empty_list(lineno=None, col=None):
return ast.List(elts=[], ctx=ast.Load(), lineno=lineno, col_offset=col)
| Creates the AST node for an empty list. | creates the ast node for an empty list . | Question:
What does this function do?
Code:
def empty_list(lineno=None, col=None):
return ast.List(elts=[], ctx=ast.Load(), lineno=lineno, col_offset=col)
|
null | null | null | What does this function do? | def group_type_access_add(context, type_id, project_id):
return IMPL.group_type_access_add(context, type_id, project_id)
| null | null | null | Add group type access for project. | pcsd | def group type access add context type id project id return IMPL group type access add context type id project id | 16780 | def group_type_access_add(context, type_id, project_id):
return IMPL.group_type_access_add(context, type_id, project_id)
| Add group type access for project. | add group type access for project . | Question:
What does this function do?
Code:
def group_type_access_add(context, type_id, project_id):
return IMPL.group_type_access_add(context, type_id, project_id)
|
null | null | null | What does this function do? | def messageTypeNames():
def typeNames():
for types in registry.values():
for typ in types:
(yield typ.typeName)
return set(typeNames())
| null | null | null | Builds set of message type names.
@return set of all message type names as strings | pcsd | def message Type Names def type Names for types in registry values for typ in types yield typ type Name return set type Names | 16794 | def messageTypeNames():
def typeNames():
for types in registry.values():
for typ in types:
(yield typ.typeName)
return set(typeNames())
| Builds set of message type names.
@return set of all message type names as strings | builds set of message type names . | Question:
What does this function do?
Code:
def messageTypeNames():
def typeNames():
for types in registry.values():
for typ in types:
(yield typ.typeName)
return set(typeNames())
|
null | null | null | What does this function do? | @login_required
def api_request(request, course_id, **kwargs):
assert isinstance(course_id, basestring)
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
if (not api_enabled(request, course_key)):
log.debug('Notes are disabled for course: {0}'.format(course_id))
raise Http404
resource_map =... | null | null | null | Routes API requests to the appropriate action method and returns JSON.
Raises a 404 if the requested resource does not exist or notes are
disabled for the course. | pcsd | @login required def api request request course id **kwargs assert isinstance course id basestring course key = Slash Separated Course Key from deprecated string course id if not api enabled request course key log debug 'Notes are disabled for course {0}' format course id raise Http404 resource map = API SETTINGS get 'R... | 16819 | @login_required
def api_request(request, course_id, **kwargs):
assert isinstance(course_id, basestring)
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
if (not api_enabled(request, course_key)):
log.debug('Notes are disabled for course: {0}'.format(course_id))
raise Http404
resource_map =... | Routes API requests to the appropriate action method and returns JSON.
Raises a 404 if the requested resource does not exist or notes are
disabled for the course. | routes api requests to the appropriate action method and returns json . | Question:
What does this function do?
Code:
@login_required
def api_request(request, course_id, **kwargs):
assert isinstance(course_id, basestring)
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
if (not api_enabled(request, course_key)):
log.debug('Notes are disabled for course: {0}'.for... |
null | null | null | What does this function do? | def delete(filename):
MP4(filename).delete()
| null | null | null | Remove tags from a file. | pcsd | def delete filename MP4 filename delete | 16837 | def delete(filename):
MP4(filename).delete()
| Remove tags from a file. | remove tags from a file . | Question:
What does this function do?
Code:
def delete(filename):
MP4(filename).delete()
|
null | null | null | What does this function do? | def getLogRecordFactory():
return _logRecordFactory
| null | null | null | Return the factory to be used when instantiating a log record. | pcsd | def get Log Record Factory return log Record Factory | 16845 | def getLogRecordFactory():
return _logRecordFactory
| Return the factory to be used when instantiating a log record. | return the factory to be used when instantiating a log record . | Question:
What does this function do?
Code:
def getLogRecordFactory():
return _logRecordFactory
|
null | null | null | What does this function do? | def DeepDependencyTargets(target_dicts, roots):
dependencies = set()
pending = set(roots)
while pending:
r = pending.pop()
if (r in dependencies):
continue
dependencies.add(r)
spec = target_dicts[r]
pending.update(set(spec.get('dependencies', [])))
pending.update(set(spec.get('dependencies_original', ... | null | null | null | Returns the recursive list of target dependencies. | pcsd | def Deep Dependency Targets target dicts roots dependencies = set pending = set roots while pending r = pending pop if r in dependencies continue dependencies add r spec = target dicts[r] pending update set spec get 'dependencies' [] pending update set spec get 'dependencies original' [] return list dependencies - set ... | 16864 | def DeepDependencyTargets(target_dicts, roots):
dependencies = set()
pending = set(roots)
while pending:
r = pending.pop()
if (r in dependencies):
continue
dependencies.add(r)
spec = target_dicts[r]
pending.update(set(spec.get('dependencies', [])))
pending.update(set(spec.get('dependencies_original', ... | Returns the recursive list of target dependencies. | returns the recursive list of target dependencies . | Question:
What does this function do?
Code:
def DeepDependencyTargets(target_dicts, roots):
dependencies = set()
pending = set(roots)
while pending:
r = pending.pop()
if (r in dependencies):
continue
dependencies.add(r)
spec = target_dicts[r]
pending.update(set(spec.get('dependencies', [])))
pendin... |
null | null | null | What does this function do? | def technical_500_response(request, exc_type, exc_value, tb):
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
if request.is_ajax():
text = reporter.get_traceback_text()
return HttpResponseServerError(text, content_type=u'text/plain')
else:
html = reporter.get_traceback_html()
return HttpRespon... | null | null | null | Create a technical server error response. The last three arguments are
the values returned from sys.exc_info() and friends. | pcsd | def technical 500 response request exc type exc value tb reporter = Exception Reporter request exc type exc value tb if request is ajax text = reporter get traceback text return Http Response Server Error text content type=u'text/plain' else html = reporter get traceback html return Http Response Server Error html cont... | 16869 | def technical_500_response(request, exc_type, exc_value, tb):
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
if request.is_ajax():
text = reporter.get_traceback_text()
return HttpResponseServerError(text, content_type=u'text/plain')
else:
html = reporter.get_traceback_html()
return HttpRespon... | Create a technical server error response. The last three arguments are
the values returned from sys.exc_info() and friends. | create a technical server error response . | Question:
What does this function do?
Code:
def technical_500_response(request, exc_type, exc_value, tb):
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
if request.is_ajax():
text = reporter.get_traceback_text()
return HttpResponseServerError(text, content_type=u'text/plain')
else:
html = re... |
null | null | null | What does this function do? | @runs_last
def code_cleanup():
fprint('Cleaning up local code')
local('rm -f hg_revision.txt viewfinder.*.tar.gz')
| null | null | null | Delete the generated tarball and revision file. | pcsd | @runs last def code cleanup fprint 'Cleaning up local code' local 'rm -f hg revision txt viewfinder * tar gz' | 16881 | @runs_last
def code_cleanup():
fprint('Cleaning up local code')
local('rm -f hg_revision.txt viewfinder.*.tar.gz')
| Delete the generated tarball and revision file. | delete the generated tarball and revision file . | Question:
What does this function do?
Code:
@runs_last
def code_cleanup():
fprint('Cleaning up local code')
local('rm -f hg_revision.txt viewfinder.*.tar.gz')
|
null | null | null | What does this function do? | def _generate_fat_jar(target, deps_jar, env):
target_dir = os.path.dirname(target)
if (not os.path.exists(target_dir)):
os.makedirs(target_dir)
target_fat_jar = zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED)
zip_path_dict = {}
zip_path_conflicts = 0
for dep_jar in deps_jar:
jar = zipfile.ZipFile(dep_jar, ... | null | null | null | Generate a fat jar containing the contents of all the jar dependencies. | pcsd | def generate fat jar target deps jar env target dir = os path dirname target if not os path exists target dir os makedirs target dir target fat jar = zipfile Zip File target 'w' zipfile ZIP DEFLATED zip path dict = {} zip path conflicts = 0 for dep jar in deps jar jar = zipfile Zip File dep jar 'r' name list = jar name... | 16891 | def _generate_fat_jar(target, deps_jar, env):
target_dir = os.path.dirname(target)
if (not os.path.exists(target_dir)):
os.makedirs(target_dir)
target_fat_jar = zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED)
zip_path_dict = {}
zip_path_conflicts = 0
for dep_jar in deps_jar:
jar = zipfile.ZipFile(dep_jar, ... | Generate a fat jar containing the contents of all the jar dependencies. | generate a fat jar containing the contents of all the jar dependencies . | Question:
What does this function do?
Code:
def _generate_fat_jar(target, deps_jar, env):
target_dir = os.path.dirname(target)
if (not os.path.exists(target_dir)):
os.makedirs(target_dir)
target_fat_jar = zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED)
zip_path_dict = {}
zip_path_conflicts = 0
for dep_jar... |
null | null | null | What does this function do? | def hierarchical(vectors, k=1, iterations=1000, distance=COSINE, **kwargs):
id = sequence()
features = kwargs.get('features', _features(vectors))
clusters = Cluster((v for v in shuffled(vectors)))
centroids = [(next(id), v) for v in clusters]
map = {}
for _ in range(iterations):
if (len(clusters) <= max(k, 1)):... | null | null | null | Returns a Cluster containing k items (vectors or clusters with nested items).
With k=1, the top-level cluster contains a single cluster. | pcsd | def hierarchical vectors k=1 iterations=1000 distance=COSINE **kwargs id = sequence features = kwargs get 'features' features vectors clusters = Cluster v for v in shuffled vectors centroids = [ next id v for v in clusters] map = {} for in range iterations if len clusters <= max k 1 break nearest d0 = None None for i i... | 16910 | def hierarchical(vectors, k=1, iterations=1000, distance=COSINE, **kwargs):
id = sequence()
features = kwargs.get('features', _features(vectors))
clusters = Cluster((v for v in shuffled(vectors)))
centroids = [(next(id), v) for v in clusters]
map = {}
for _ in range(iterations):
if (len(clusters) <= max(k, 1)):... | Returns a Cluster containing k items (vectors or clusters with nested items).
With k=1, the top-level cluster contains a single cluster. | returns a cluster containing k items . | Question:
What does this function do?
Code:
def hierarchical(vectors, k=1, iterations=1000, distance=COSINE, **kwargs):
id = sequence()
features = kwargs.get('features', _features(vectors))
clusters = Cluster((v for v in shuffled(vectors)))
centroids = [(next(id), v) for v in clusters]
map = {}
for _ in range(... |
null | null | null | What does this function do? | def create_role(name, description=None):
if (name in SystemRole.get_valid_values()):
raise ValueError(('"%s" role name is blacklisted' % name))
role_db = RoleDB(name=name, description=description)
role_db = Role.add_or_update(role_db)
return role_db
| null | null | null | Create a new role. | pcsd | def create role name description=None if name in System Role get valid values raise Value Error '"%s" role name is blacklisted' % name role db = Role DB name=name description=description role db = Role add or update role db return role db | 16912 | def create_role(name, description=None):
if (name in SystemRole.get_valid_values()):
raise ValueError(('"%s" role name is blacklisted' % name))
role_db = RoleDB(name=name, description=description)
role_db = Role.add_or_update(role_db)
return role_db
| Create a new role. | create a new role . | Question:
What does this function do?
Code:
def create_role(name, description=None):
if (name in SystemRole.get_valid_values()):
raise ValueError(('"%s" role name is blacklisted' % name))
role_db = RoleDB(name=name, description=description)
role_db = Role.add_or_update(role_db)
return role_db
|
null | null | null | What does this function do? | def reformat_comment(data, limit, comment_header):
lc = len(comment_header)
data = '\n'.join((line[lc:] for line in data.split('\n')))
format_width = max((limit - len(comment_header)), 20)
newdata = reformat_paragraph(data, format_width)
newdata = newdata.split('\n')
block_suffix = ''
if (not newdata[(-1)]):
b... | null | null | null | Return data reformatted to specified width with comment header. | pcsd | def reformat comment data limit comment header lc = len comment header data = ' ' join line[lc ] for line in data split ' ' format width = max limit - len comment header 20 newdata = reformat paragraph data format width newdata = newdata split ' ' block suffix = '' if not newdata[ -1 ] block suffix = ' ' newdata = newd... | 16931 | def reformat_comment(data, limit, comment_header):
lc = len(comment_header)
data = '\n'.join((line[lc:] for line in data.split('\n')))
format_width = max((limit - len(comment_header)), 20)
newdata = reformat_paragraph(data, format_width)
newdata = newdata.split('\n')
block_suffix = ''
if (not newdata[(-1)]):
b... | Return data reformatted to specified width with comment header. | return data reformatted to specified width with comment header . | Question:
What does this function do?
Code:
def reformat_comment(data, limit, comment_header):
lc = len(comment_header)
data = '\n'.join((line[lc:] for line in data.split('\n')))
format_width = max((limit - len(comment_header)), 20)
newdata = reformat_paragraph(data, format_width)
newdata = newdata.split('\n')
... |
null | null | null | What does this function do? | def log_post_trace(trace, model):
return np.vstack(([obs.logp_elemwise(pt) for obs in model.observed_RVs] for pt in trace))
| null | null | null | Calculate the elementwise log-posterior for the sampled trace. | pcsd | def log post trace trace model return np vstack [obs logp elemwise pt for obs in model observed R Vs] for pt in trace | 16942 | def log_post_trace(trace, model):
return np.vstack(([obs.logp_elemwise(pt) for obs in model.observed_RVs] for pt in trace))
| Calculate the elementwise log-posterior for the sampled trace. | calculate the elementwise log - posterior for the sampled trace . | Question:
What does this function do?
Code:
def log_post_trace(trace, model):
return np.vstack(([obs.logp_elemwise(pt) for obs in model.observed_RVs] for pt in trace))
|
null | null | null | What does this function do? | def _connect(**kwargs):
connargs = {}
for name in ['uri', 'server', 'port', 'tls', 'no_verify', 'binddn', 'bindpw', 'anonymous']:
connargs[name] = _config(name, **kwargs)
return _LDAPConnection(**connargs).ldap
| null | null | null | Instantiate LDAP Connection class and return an LDAP connection object | pcsd | def connect **kwargs connargs = {} for name in ['uri' 'server' 'port' 'tls' 'no verify' 'binddn' 'bindpw' 'anonymous'] connargs[name] = config name **kwargs return LDAP Connection **connargs ldap | 16955 | def _connect(**kwargs):
connargs = {}
for name in ['uri', 'server', 'port', 'tls', 'no_verify', 'binddn', 'bindpw', 'anonymous']:
connargs[name] = _config(name, **kwargs)
return _LDAPConnection(**connargs).ldap
| Instantiate LDAP Connection class and return an LDAP connection object | instantiate ldap connection class and return an ldap connection object | Question:
What does this function do?
Code:
def _connect(**kwargs):
connargs = {}
for name in ['uri', 'server', 'port', 'tls', 'no_verify', 'binddn', 'bindpw', 'anonymous']:
connargs[name] = _config(name, **kwargs)
return _LDAPConnection(**connargs).ldap
|
null | null | null | What does this function do? | def getCraftPluginsDirectoryPath(subName=''):
return getJoinedPath(getSkeinforgePluginsPath('craft_plugins'), subName)
| null | null | null | Get the craft plugins directory path. | pcsd | def get Craft Plugins Directory Path sub Name='' return get Joined Path get Skeinforge Plugins Path 'craft plugins' sub Name | 16965 | def getCraftPluginsDirectoryPath(subName=''):
return getJoinedPath(getSkeinforgePluginsPath('craft_plugins'), subName)
| Get the craft plugins directory path. | get the craft plugins directory path . | Question:
What does this function do?
Code:
def getCraftPluginsDirectoryPath(subName=''):
return getJoinedPath(getSkeinforgePluginsPath('craft_plugins'), subName)
|
null | null | null | What does this function do? | def isInferenceAvailable():
return any((isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.BOOLEAN, PAYLOAD.TECHNIQUE.STACKED, PAYLOAD.TECHNIQUE.TIME)))
| null | null | null | Returns True whether techniques using inference technique are available | pcsd | def is Inference Available return any is Technique Available for in PAYLOAD TECHNIQUE BOOLEAN PAYLOAD TECHNIQUE STACKED PAYLOAD TECHNIQUE TIME | 16966 | def isInferenceAvailable():
return any((isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.BOOLEAN, PAYLOAD.TECHNIQUE.STACKED, PAYLOAD.TECHNIQUE.TIME)))
| Returns True whether techniques using inference technique are available | returns true whether techniques using inference technique are available | Question:
What does this function do?
Code:
def isInferenceAvailable():
return any((isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.BOOLEAN, PAYLOAD.TECHNIQUE.STACKED, PAYLOAD.TECHNIQUE.TIME)))
|
null | null | null | What does this function do? | def python_to_workflow(as_python, galaxy_interface, workflow_directory):
if (workflow_directory is None):
workflow_directory = os.path.abspath('.')
conversion_context = ConversionContext(galaxy_interface, workflow_directory)
return _python_to_workflow(as_python, conversion_context)
| null | null | null | Convert a Format 2 workflow into standard Galaxy format from supplied dictionary. | pcsd | def python to workflow as python galaxy interface workflow directory if workflow directory is None workflow directory = os path abspath ' ' conversion context = Conversion Context galaxy interface workflow directory return python to workflow as python conversion context | 16970 | def python_to_workflow(as_python, galaxy_interface, workflow_directory):
if (workflow_directory is None):
workflow_directory = os.path.abspath('.')
conversion_context = ConversionContext(galaxy_interface, workflow_directory)
return _python_to_workflow(as_python, conversion_context)
| Convert a Format 2 workflow into standard Galaxy format from supplied dictionary. | convert a format 2 workflow into standard galaxy format from supplied dictionary . | Question:
What does this function do?
Code:
def python_to_workflow(as_python, galaxy_interface, workflow_directory):
if (workflow_directory is None):
workflow_directory = os.path.abspath('.')
conversion_context = ConversionContext(galaxy_interface, workflow_directory)
return _python_to_workflow(as_python, conve... |
null | null | null | What does this function do? | def _generateInferenceArgs(options, tokenReplacements):
inferenceType = options['inferenceType']
optionInferenceArgs = options.get('inferenceArgs', None)
resultInferenceArgs = {}
predictedField = _getPredictedField(options)[0]
if (inferenceType in (InferenceType.TemporalNextStep, InferenceType.TemporalAnomaly)):
... | null | null | null | Generates the token substitutions related to the predicted field
and the supplemental arguments for prediction | pcsd | def generate Inference Args options token Replacements inference Type = options['inference Type'] option Inference Args = options get 'inference Args' None result Inference Args = {} predicted Field = get Predicted Field options [0] if inference Type in Inference Type Temporal Next Step Inference Type Temporal Anomaly ... | 16971 | def _generateInferenceArgs(options, tokenReplacements):
inferenceType = options['inferenceType']
optionInferenceArgs = options.get('inferenceArgs', None)
resultInferenceArgs = {}
predictedField = _getPredictedField(options)[0]
if (inferenceType in (InferenceType.TemporalNextStep, InferenceType.TemporalAnomaly)):
... | Generates the token substitutions related to the predicted field
and the supplemental arguments for prediction | generates the token substitutions related to the predicted field and the supplemental arguments for prediction | Question:
What does this function do?
Code:
def _generateInferenceArgs(options, tokenReplacements):
inferenceType = options['inferenceType']
optionInferenceArgs = options.get('inferenceArgs', None)
resultInferenceArgs = {}
predictedField = _getPredictedField(options)[0]
if (inferenceType in (InferenceType.Tempo... |
null | null | null | What does this function do? | def _set_radio_button(idx, params):
radio = params['fig_selection'].radio
radio.circles[radio._active_idx].set_facecolor((1.0, 1.0, 1.0, 1.0))
radio.circles[idx].set_facecolor((0.0, 0.0, 1.0, 1.0))
_radio_clicked(radio.labels[idx]._text, params)
| null | null | null | Helper for setting radio button. | pcsd | def set radio button idx params radio = params['fig selection'] radio radio circles[radio active idx] set facecolor 1 0 1 0 1 0 1 0 radio circles[idx] set facecolor 0 0 0 0 1 0 1 0 radio clicked radio labels[idx] text params | 16974 | def _set_radio_button(idx, params):
radio = params['fig_selection'].radio
radio.circles[radio._active_idx].set_facecolor((1.0, 1.0, 1.0, 1.0))
radio.circles[idx].set_facecolor((0.0, 0.0, 1.0, 1.0))
_radio_clicked(radio.labels[idx]._text, params)
| Helper for setting radio button. | helper for setting radio button . | Question:
What does this function do?
Code:
def _set_radio_button(idx, params):
radio = params['fig_selection'].radio
radio.circles[radio._active_idx].set_facecolor((1.0, 1.0, 1.0, 1.0))
radio.circles[idx].set_facecolor((0.0, 0.0, 1.0, 1.0))
_radio_clicked(radio.labels[idx]._text, params)
|
null | null | null | What does this function do? | def getargsfromdoc(obj):
if (obj.__doc__ is not None):
return getargsfromtext(obj.__doc__, obj.__name__)
| null | null | null | Get arguments from object doc | pcsd | def getargsfromdoc obj if obj doc is not None return getargsfromtext obj doc obj name | 16980 | def getargsfromdoc(obj):
if (obj.__doc__ is not None):
return getargsfromtext(obj.__doc__, obj.__name__)
| Get arguments from object doc | get arguments from object doc | Question:
What does this function do?
Code:
def getargsfromdoc(obj):
if (obj.__doc__ is not None):
return getargsfromtext(obj.__doc__, obj.__name__)
|
null | null | null | What does this function do? | def get_db():
top = _app_ctx_stack.top
if (not hasattr(top, 'sqlite_db')):
top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
top.sqlite_db.row_factory = sqlite3.Row
return top.sqlite_db
| null | null | null | Opens a new database connection if there is none yet for the
current application context. | pcsd | def get db top = app ctx stack top if not hasattr top 'sqlite db' top sqlite db = sqlite3 connect app config['DATABASE'] top sqlite db row factory = sqlite3 Row return top sqlite db | 16986 | def get_db():
top = _app_ctx_stack.top
if (not hasattr(top, 'sqlite_db')):
top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
top.sqlite_db.row_factory = sqlite3.Row
return top.sqlite_db
| Opens a new database connection if there is none yet for the
current application context. | opens a new database connection if there is none yet for the current application context . | Question:
What does this function do?
Code:
def get_db():
top = _app_ctx_stack.top
if (not hasattr(top, 'sqlite_db')):
top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
top.sqlite_db.row_factory = sqlite3.Row
return top.sqlite_db
|
null | null | null | What does this function do? | def ajax_content_response(request, course_key, content):
user_info = cc.User.from_django_user(request.user).to_dict()
annotated_content_info = get_annotated_content_info(course_key, content, request.user, user_info)
return JsonResponse({'content': prepare_content(content, course_key), 'annotated_content_info': annot... | null | null | null | Standard AJAX response returning the content hierarchy of the current thread. | pcsd | def ajax content response request course key content user info = cc User from django user request user to dict annotated content info = get annotated content info course key content request user user info return Json Response {'content' prepare content content course key 'annotated content info' annotated content info} | 16989 | def ajax_content_response(request, course_key, content):
user_info = cc.User.from_django_user(request.user).to_dict()
annotated_content_info = get_annotated_content_info(course_key, content, request.user, user_info)
return JsonResponse({'content': prepare_content(content, course_key), 'annotated_content_info': annot... | Standard AJAX response returning the content hierarchy of the current thread. | standard ajax response returning the content hierarchy of the current thread . | Question:
What does this function do?
Code:
def ajax_content_response(request, course_key, content):
user_info = cc.User.from_django_user(request.user).to_dict()
annotated_content_info = get_annotated_content_info(course_key, content, request.user, user_info)
return JsonResponse({'content': prepare_content(conten... |
null | null | null | What does this function do? | def main():
try:
(opts, args) = getopt.getopt(sys.argv[1:], '', ['consumer_key=', 'consumer_secret='])
except getopt.error as msg:
print 'python oauth_example.py --consumer_key [consumer_key] --consumer_secret [consumer_secret] '
sys.exit(2)
consumer_key = ''
consumer_secret = ''
for (option, arg) in opts:
... | null | null | null | Demonstrates usage of OAuth authentication mode.
Prints a list of documents. This demo uses HMAC-SHA1 signature method. | pcsd | def main try opts args = getopt getopt sys argv[1 ] '' ['consumer key=' 'consumer secret='] except getopt error as msg print 'python oauth example py --consumer key [consumer key] --consumer secret [consumer secret] ' sys exit 2 consumer key = '' consumer secret = '' for option arg in opts if option == '--consumer key'... | 17006 | def main():
try:
(opts, args) = getopt.getopt(sys.argv[1:], '', ['consumer_key=', 'consumer_secret='])
except getopt.error as msg:
print 'python oauth_example.py --consumer_key [consumer_key] --consumer_secret [consumer_secret] '
sys.exit(2)
consumer_key = ''
consumer_secret = ''
for (option, arg) in opts:
... | Demonstrates usage of OAuth authentication mode.
Prints a list of documents. This demo uses HMAC-SHA1 signature method. | demonstrates usage of oauth authentication mode . | Question:
What does this function do?
Code:
def main():
try:
(opts, args) = getopt.getopt(sys.argv[1:], '', ['consumer_key=', 'consumer_secret='])
except getopt.error as msg:
print 'python oauth_example.py --consumer_key [consumer_key] --consumer_secret [consumer_secret] '
sys.exit(2)
consumer_key = ''
con... |
null | null | null | What does this function do? | def persist_uploads(params):
if ('files' in params):
new_files = []
for upload_dataset in params['files']:
f = upload_dataset['file_data']
if isinstance(f, FieldStorage):
assert (not isinstance(f.file, StringIO))
assert (f.file.name != '<fdopen>')
local_filename = util.mkstemp_ln(f.file.name, 'up... | null | null | null | Turn any uploads in the submitted form to persisted files. | pcsd | def persist uploads params if 'files' in params new files = [] for upload dataset in params['files'] f = upload dataset['file data'] if isinstance f Field Storage assert not isinstance f file String IO assert f file name != '<fdopen>' local filename = util mkstemp ln f file name 'upload file data ' f file close upload ... | 17011 | def persist_uploads(params):
if ('files' in params):
new_files = []
for upload_dataset in params['files']:
f = upload_dataset['file_data']
if isinstance(f, FieldStorage):
assert (not isinstance(f.file, StringIO))
assert (f.file.name != '<fdopen>')
local_filename = util.mkstemp_ln(f.file.name, 'up... | Turn any uploads in the submitted form to persisted files. | turn any uploads in the submitted form to persisted files . | Question:
What does this function do?
Code:
def persist_uploads(params):
if ('files' in params):
new_files = []
for upload_dataset in params['files']:
f = upload_dataset['file_data']
if isinstance(f, FieldStorage):
assert (not isinstance(f.file, StringIO))
assert (f.file.name != '<fdopen>')
lo... |
null | null | null | What does this function do? | def __get_username():
if (sys.platform == 'win32'):
return getpass.getuser()
import pwd
return pwd.getpwuid(os.geteuid()).pw_name
| null | null | null | Returns the effective username of the current process. | pcsd | def get username if sys platform == 'win32' return getpass getuser import pwd return pwd getpwuid os geteuid pw name | 17019 | def __get_username():
if (sys.platform == 'win32'):
return getpass.getuser()
import pwd
return pwd.getpwuid(os.geteuid()).pw_name
| Returns the effective username of the current process. | returns the effective username of the current process . | Question:
What does this function do?
Code:
def __get_username():
if (sys.platform == 'win32'):
return getpass.getuser()
import pwd
return pwd.getpwuid(os.geteuid()).pw_name
|
null | null | null | What does this function do? | def contact_autocreate_handler(sender, instance, created, **kwargs):
if created:
try:
contact_type = ContactType.objects.filter((models.Q(name='Person') | models.Q(slug='person')))[0]
contact = Contact(contact_type=contact_type, name=instance.name, related_user=instance)
contact.save()
except:
pass
| null | null | null | When a User is created, automatically create a Contact of type Person | pcsd | def contact autocreate handler sender instance created **kwargs if created try contact type = Contact Type objects filter models Q name='Person' | models Q slug='person' [0] contact = Contact contact type=contact type name=instance name related user=instance contact save except pass | 17029 | def contact_autocreate_handler(sender, instance, created, **kwargs):
if created:
try:
contact_type = ContactType.objects.filter((models.Q(name='Person') | models.Q(slug='person')))[0]
contact = Contact(contact_type=contact_type, name=instance.name, related_user=instance)
contact.save()
except:
pass
| When a User is created, automatically create a Contact of type Person | when a user is created , automatically create a contact of type person | Question:
What does this function do?
Code:
def contact_autocreate_handler(sender, instance, created, **kwargs):
if created:
try:
contact_type = ContactType.objects.filter((models.Q(name='Person') | models.Q(slug='person')))[0]
contact = Contact(contact_type=contact_type, name=instance.name, related_user=in... |
null | null | null | What does this function do? | def get_indexes_async(**kwargs):
def extra_hook(indexes):
return [(_index_converter(index), state) for (index, state) in indexes]
return datastore.GetIndexesAsync(extra_hook=extra_hook, **kwargs)
| null | null | null | Asynchronously retrieves the application indexes and their states.
Identical to get_indexes() except returns an asynchronous object. Call
get_result() on the return value to block on the call and get the results. | pcsd | def get indexes async **kwargs def extra hook indexes return [ index converter index state for index state in indexes] return datastore Get Indexes Async extra hook=extra hook **kwargs | 17033 | def get_indexes_async(**kwargs):
def extra_hook(indexes):
return [(_index_converter(index), state) for (index, state) in indexes]
return datastore.GetIndexesAsync(extra_hook=extra_hook, **kwargs)
| Asynchronously retrieves the application indexes and their states.
Identical to get_indexes() except returns an asynchronous object. Call
get_result() on the return value to block on the call and get the results. | asynchronously retrieves the application indexes and their states . | Question:
What does this function do?
Code:
def get_indexes_async(**kwargs):
def extra_hook(indexes):
return [(_index_converter(index), state) for (index, state) in indexes]
return datastore.GetIndexesAsync(extra_hook=extra_hook, **kwargs)
|
null | null | null | What does this function do? | def _bgp_capability_dispatcher(payload):
cls = _capabilities_registry['BGPCapGeneric']
if (payload is None):
cls = _capabilities_registry['BGPCapGeneric']
else:
length = len(payload)
if (length >= _BGP_CAPABILITY_MIN_SIZE):
code = struct.unpack('!B', payload[0])[0]
cls = _get_cls(_capabilities_objects.ge... | null | null | null | Returns the right class for a given BGP capability. | pcsd | def bgp capability dispatcher payload cls = capabilities registry['BGP Cap Generic'] if payload is None cls = capabilities registry['BGP Cap Generic'] else length = len payload if length >= BGP CAPABILITY MIN SIZE code = struct unpack '!B' payload[0] [0] cls = get cls capabilities objects get code 'BGP Cap Generic' ret... | 17037 | def _bgp_capability_dispatcher(payload):
cls = _capabilities_registry['BGPCapGeneric']
if (payload is None):
cls = _capabilities_registry['BGPCapGeneric']
else:
length = len(payload)
if (length >= _BGP_CAPABILITY_MIN_SIZE):
code = struct.unpack('!B', payload[0])[0]
cls = _get_cls(_capabilities_objects.ge... | Returns the right class for a given BGP capability. | returns the right class for a given bgp capability . | Question:
What does this function do?
Code:
def _bgp_capability_dispatcher(payload):
cls = _capabilities_registry['BGPCapGeneric']
if (payload is None):
cls = _capabilities_registry['BGPCapGeneric']
else:
length = len(payload)
if (length >= _BGP_CAPABILITY_MIN_SIZE):
code = struct.unpack('!B', payload[0]... |
null | null | null | What does this function do? | def dump_objects():
blocks = []
lines = []
blocks.append(('global', global_registry.dump_objects()))
for win_id in window_registry:
registry = _get_registry('window', window=win_id)
blocks.append(('window-{}'.format(win_id), registry.dump_objects()))
tab_registry = get('tab-registry', scope='window', window=w... | null | null | null | Get all registered objects in all registries as a string. | pcsd | def dump objects blocks = [] lines = [] blocks append 'global' global registry dump objects for win id in window registry registry = get registry 'window' window=win id blocks append 'window-{}' format win id registry dump objects tab registry = get 'tab-registry' scope='window' window=win id for tab id tab in tab regi... | 17040 | def dump_objects():
blocks = []
lines = []
blocks.append(('global', global_registry.dump_objects()))
for win_id in window_registry:
registry = _get_registry('window', window=win_id)
blocks.append(('window-{}'.format(win_id), registry.dump_objects()))
tab_registry = get('tab-registry', scope='window', window=w... | Get all registered objects in all registries as a string. | get all registered objects in all registries as a string . | Question:
What does this function do?
Code:
def dump_objects():
blocks = []
lines = []
blocks.append(('global', global_registry.dump_objects()))
for win_id in window_registry:
registry = _get_registry('window', window=win_id)
blocks.append(('window-{}'.format(win_id), registry.dump_objects()))
tab_registry... |
null | null | null | What does this function do? | def getNewRepository():
return skeinforge_craft.CraftRepository()
| null | null | null | Get the repository constructor. | pcsd | def get New Repository return skeinforge craft Craft Repository | 17050 | def getNewRepository():
return skeinforge_craft.CraftRepository()
| Get the repository constructor. | get the repository constructor . | Question:
What does this function do?
Code:
def getNewRepository():
return skeinforge_craft.CraftRepository()
|
null | null | null | What does this function do? | def maybe_unwrap_results(results):
return getattr(results, '_results', results)
| null | null | null | Gets raw results back from wrapped results.
Can be used in plotting functions or other post-estimation type
routines. | pcsd | def maybe unwrap results results return getattr results ' results' results | 17058 | def maybe_unwrap_results(results):
return getattr(results, '_results', results)
| Gets raw results back from wrapped results.
Can be used in plotting functions or other post-estimation type
routines. | gets raw results back from wrapped results . | Question:
What does this function do?
Code:
def maybe_unwrap_results(results):
return getattr(results, '_results', results)
|
null | null | null | What does this function do? | def _roll_vectorized(M, roll_indices, axis):
assert (axis in [0, 1])
ndim = M.ndim
assert (ndim == 3)
ndim_roll = roll_indices.ndim
assert (ndim_roll == 1)
sh = M.shape
(r, c) = sh[(-2):]
assert (sh[0] == roll_indices.shape[0])
vec_indices = np.arange(sh[0], dtype=np.int32)
M_roll = np.empty_like(M)
if (axis... | null | null | null | Rolls an array of matrices along an axis according to an array of indices
*roll_indices*
*axis* can be either 0 (rolls rows) or 1 (rolls columns). | pcsd | def roll vectorized M roll indices axis assert axis in [0 1] ndim = M ndim assert ndim == 3 ndim roll = roll indices ndim assert ndim roll == 1 sh = M shape r c = sh[ -2 ] assert sh[0] == roll indices shape[0] vec indices = np arange sh[0] dtype=np int32 M roll = np empty like M if axis == 0 for ir in range r for ic in... | 17063 | def _roll_vectorized(M, roll_indices, axis):
assert (axis in [0, 1])
ndim = M.ndim
assert (ndim == 3)
ndim_roll = roll_indices.ndim
assert (ndim_roll == 1)
sh = M.shape
(r, c) = sh[(-2):]
assert (sh[0] == roll_indices.shape[0])
vec_indices = np.arange(sh[0], dtype=np.int32)
M_roll = np.empty_like(M)
if (axis... | Rolls an array of matrices along an axis according to an array of indices
*roll_indices*
*axis* can be either 0 (rolls rows) or 1 (rolls columns). | rolls an array of matrices along an axis according to an array of indices roll _ indices * axis * can be either 0 or 1 . | Question:
What does this function do?
Code:
def _roll_vectorized(M, roll_indices, axis):
assert (axis in [0, 1])
ndim = M.ndim
assert (ndim == 3)
ndim_roll = roll_indices.ndim
assert (ndim_roll == 1)
sh = M.shape
(r, c) = sh[(-2):]
assert (sh[0] == roll_indices.shape[0])
vec_indices = np.arange(sh[0], dtype... |
null | null | null | What does this function do? | def SecurityCheck(func):
def Wrapper(request, *args, **kwargs):
'Wrapping function.'
if (WEBAUTH_MANAGER is None):
raise RuntimeError('Attempt to initialize before WEBAUTH_MANAGER set.')
return WEBAUTH_MANAGER.SecurityCheck(func, request, *args, **kwargs)
return Wrapper
| null | null | null | A decorator applied to protected web handlers. | pcsd | def Security Check func def Wrapper request *args **kwargs 'Wrapping function ' if WEBAUTH MANAGER is None raise Runtime Error 'Attempt to initialize before WEBAUTH MANAGER set ' return WEBAUTH MANAGER Security Check func request *args **kwargs return Wrapper | 17066 | def SecurityCheck(func):
def Wrapper(request, *args, **kwargs):
'Wrapping function.'
if (WEBAUTH_MANAGER is None):
raise RuntimeError('Attempt to initialize before WEBAUTH_MANAGER set.')
return WEBAUTH_MANAGER.SecurityCheck(func, request, *args, **kwargs)
return Wrapper
| A decorator applied to protected web handlers. | a decorator applied to protected web handlers . | Question:
What does this function do?
Code:
def SecurityCheck(func):
def Wrapper(request, *args, **kwargs):
'Wrapping function.'
if (WEBAUTH_MANAGER is None):
raise RuntimeError('Attempt to initialize before WEBAUTH_MANAGER set.')
return WEBAUTH_MANAGER.SecurityCheck(func, request, *args, **kwargs)
return... |
null | null | null | What does this function do? | def cpu_count():
if (sys.platform == 'win32'):
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = 0
elif (sys.platform == 'darwin'):
try:
num = int(command_output(['sysctl', '-n', 'hw.ncpu']))
except ValueError:
num = 0
else:
try:
num = os.sysconf('SC_NPR... | null | null | null | Return the number of hardware thread contexts (cores or SMT
threads) in the system. | pcsd | def cpu count if sys platform == 'win32' try num = int os environ['NUMBER OF PROCESSORS'] except Value Error Key Error num = 0 elif sys platform == 'darwin' try num = int command output ['sysctl' '-n' 'hw ncpu'] except Value Error num = 0 else try num = os sysconf 'SC NPROCESSORS ONLN' except Value Error OS Error Attri... | 17079 | def cpu_count():
if (sys.platform == 'win32'):
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = 0
elif (sys.platform == 'darwin'):
try:
num = int(command_output(['sysctl', '-n', 'hw.ncpu']))
except ValueError:
num = 0
else:
try:
num = os.sysconf('SC_NPR... | Return the number of hardware thread contexts (cores or SMT
threads) in the system. | return the number of hardware thread contexts in the system . | Question:
What does this function do?
Code:
def cpu_count():
if (sys.platform == 'win32'):
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = 0
elif (sys.platform == 'darwin'):
try:
num = int(command_output(['sysctl', '-n', 'hw.ncpu']))
except ValueError:
nu... |
null | null | null | What does this function do? | def restart(force=False):
global __PARMS, SCHEDULE_GUARD_FLAG
if force:
SCHEDULE_GUARD_FLAG = True
elif SCHEDULE_GUARD_FLAG:
SCHEDULE_GUARD_FLAG = False
stop()
analyse(sabnzbd.downloader.Downloader.do.paused)
init()
start()
| null | null | null | Stop and start scheduler | pcsd | def restart force=False global PARMS SCHEDULE GUARD FLAG if force SCHEDULE GUARD FLAG = True elif SCHEDULE GUARD FLAG SCHEDULE GUARD FLAG = False stop analyse sabnzbd downloader Downloader do paused init start | 17089 | def restart(force=False):
global __PARMS, SCHEDULE_GUARD_FLAG
if force:
SCHEDULE_GUARD_FLAG = True
elif SCHEDULE_GUARD_FLAG:
SCHEDULE_GUARD_FLAG = False
stop()
analyse(sabnzbd.downloader.Downloader.do.paused)
init()
start()
| Stop and start scheduler | stop and start scheduler | Question:
What does this function do?
Code:
def restart(force=False):
global __PARMS, SCHEDULE_GUARD_FLAG
if force:
SCHEDULE_GUARD_FLAG = True
elif SCHEDULE_GUARD_FLAG:
SCHEDULE_GUARD_FLAG = False
stop()
analyse(sabnzbd.downloader.Downloader.do.paused)
init()
start()
|
null | null | null | What does this function do? | def raw_post_data(request):
return HttpResponse(request.raw_post_data)
| null | null | null | A view that is requested with GET and accesses request.raw_post_data. Refs #14753. | pcsd | def raw post data request return Http Response request raw post data | 17094 | def raw_post_data(request):
return HttpResponse(request.raw_post_data)
| A view that is requested with GET and accesses request.raw_post_data. Refs #14753. | a view that is requested with get and accesses request . raw _ post _ data . | Question:
What does this function do?
Code:
def raw_post_data(request):
return HttpResponse(request.raw_post_data)
|
null | null | null | What does this function do? | def p_function_type(p):
if (p[1] == 'void'):
p[0] = TType.VOID
else:
p[0] = p[1]
| null | null | null | function_type : field_type
| VOID | pcsd | def p function type p if p[1] == 'void' p[0] = T Type VOID else p[0] = p[1] | 17096 | def p_function_type(p):
if (p[1] == 'void'):
p[0] = TType.VOID
else:
p[0] = p[1]
| function_type : field_type
| VOID | function _ type : field _ type | void | Question:
What does this function do?
Code:
def p_function_type(p):
if (p[1] == 'void'):
p[0] = TType.VOID
else:
p[0] = p[1]
|
null | null | null | What does this function do? | def person_search():
s3.filter = (FS('human_resource.type') == 2)
s3.prep = (lambda r: (r.method == 'search_ac'))
return s3_rest_controller('pr', 'person')
| null | null | null | Person REST controller
- limited to just search_ac for use in Autocompletes
- allows differential access permissions | pcsd | def person search s3 filter = FS 'human resource type' == 2 s3 prep = lambda r r method == 'search ac' return s3 rest controller 'pr' 'person' | 17106 | def person_search():
s3.filter = (FS('human_resource.type') == 2)
s3.prep = (lambda r: (r.method == 'search_ac'))
return s3_rest_controller('pr', 'person')
| Person REST controller
- limited to just search_ac for use in Autocompletes
- allows differential access permissions | person rest controller - limited to just search _ ac for use in autocompletes - allows differential access permissions | Question:
What does this function do?
Code:
def person_search():
s3.filter = (FS('human_resource.type') == 2)
s3.prep = (lambda r: (r.method == 'search_ac'))
return s3_rest_controller('pr', 'person')
|
null | null | null | What does this function do? | def list_networks(call=None, kwargs=None):
if (call == 'action'):
raise SaltCloudSystemExit('The avail_sizes function must be called with -f or --function, or with the --list-sizes option')
global netconn
if (not netconn):
netconn = get_conn(NetworkManagementClient)
region = get_location()
bank = 'cloud/metada... | null | null | null | List virtual networks | pcsd | def list networks call=None kwargs=None if call == 'action' raise Salt Cloud System Exit 'The avail sizes function must be called with -f or --function or with the --list-sizes option' global netconn if not netconn netconn = get conn Network Management Client region = get location bank = 'cloud/metadata/azurearm/{0}/vi... | 17112 | def list_networks(call=None, kwargs=None):
if (call == 'action'):
raise SaltCloudSystemExit('The avail_sizes function must be called with -f or --function, or with the --list-sizes option')
global netconn
if (not netconn):
netconn = get_conn(NetworkManagementClient)
region = get_location()
bank = 'cloud/metada... | List virtual networks | list virtual networks | Question:
What does this function do?
Code:
def list_networks(call=None, kwargs=None):
if (call == 'action'):
raise SaltCloudSystemExit('The avail_sizes function must be called with -f or --function, or with the --list-sizes option')
global netconn
if (not netconn):
netconn = get_conn(NetworkManagementClient)... |
null | null | null | What does this function do? | def lowstate_file_refs(chunks):
refs = {}
for chunk in chunks:
saltenv = 'base'
crefs = []
for state in chunk:
if (state == '__env__'):
saltenv = chunk[state]
elif (state == 'saltenv'):
saltenv = chunk[state]
elif state.startswith('__'):
continue
crefs.extend(salt_refs(chunk[state]))
i... | null | null | null | Create a list of file ref objects to reconcile | pcsd | def lowstate file refs chunks refs = {} for chunk in chunks saltenv = 'base' crefs = [] for state in chunk if state == ' env ' saltenv = chunk[state] elif state == 'saltenv' saltenv = chunk[state] elif state startswith ' ' continue crefs extend salt refs chunk[state] if crefs if saltenv not in refs refs[saltenv] = [] r... | 17113 | def lowstate_file_refs(chunks):
refs = {}
for chunk in chunks:
saltenv = 'base'
crefs = []
for state in chunk:
if (state == '__env__'):
saltenv = chunk[state]
elif (state == 'saltenv'):
saltenv = chunk[state]
elif state.startswith('__'):
continue
crefs.extend(salt_refs(chunk[state]))
i... | Create a list of file ref objects to reconcile | create a list of file ref objects to reconcile | Question:
What does this function do?
Code:
def lowstate_file_refs(chunks):
refs = {}
for chunk in chunks:
saltenv = 'base'
crefs = []
for state in chunk:
if (state == '__env__'):
saltenv = chunk[state]
elif (state == 'saltenv'):
saltenv = chunk[state]
elif state.startswith('__'):
contin... |
null | null | null | What does this function do? | def SetIfNotNone(dict, attr_name, value):
if (value is not None):
dict[attr_name] = value
| null | null | null | If "value" is not None, then set the specified attribute of "dict"
to its value. | pcsd | def Set If Not None dict attr name value if value is not None dict[attr name] = value | 17114 | def SetIfNotNone(dict, attr_name, value):
if (value is not None):
dict[attr_name] = value
| If "value" is not None, then set the specified attribute of "dict"
to its value. | if " value " is not none , then set the specified attribute of " dict " to its value . | Question:
What does this function do?
Code:
def SetIfNotNone(dict, attr_name, value):
if (value is not None):
dict[attr_name] = value
|
null | null | null | What does this function do? | def get_block_device_mapping(image):
bdm_dict = dict()
bdm = getattr(image, 'block_device_mapping')
for device_name in bdm.keys():
bdm_dict[device_name] = {'size': bdm[device_name].size, 'snapshot_id': bdm[device_name].snapshot_id, 'volume_type': bdm[device_name].volume_type, 'encrypted': bdm[device_name].encrypte... | null | null | null | Retrieves block device mapping from AMI | pcsd | def get block device mapping image bdm dict = dict bdm = getattr image 'block device mapping' for device name in bdm keys bdm dict[device name] = {'size' bdm[device name] size 'snapshot id' bdm[device name] snapshot id 'volume type' bdm[device name] volume type 'encrypted' bdm[device name] encrypted 'delete on terminat... | 17122 | def get_block_device_mapping(image):
bdm_dict = dict()
bdm = getattr(image, 'block_device_mapping')
for device_name in bdm.keys():
bdm_dict[device_name] = {'size': bdm[device_name].size, 'snapshot_id': bdm[device_name].snapshot_id, 'volume_type': bdm[device_name].volume_type, 'encrypted': bdm[device_name].encrypte... | Retrieves block device mapping from AMI | retrieves block device mapping from ami | Question:
What does this function do?
Code:
def get_block_device_mapping(image):
bdm_dict = dict()
bdm = getattr(image, 'block_device_mapping')
for device_name in bdm.keys():
bdm_dict[device_name] = {'size': bdm[device_name].size, 'snapshot_id': bdm[device_name].snapshot_id, 'volume_type': bdm[device_name].volu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.