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 __virtual__():
if (salt.utils.is_windows() and HAS_WINDOWS_MODULES):
return __virtualname__
return False
| null | null | null | Only works on Windows systems | pcsd | def virtual if salt utils is windows and HAS WINDOWS MODULES return virtualname return False | 11406 | def __virtual__():
if (salt.utils.is_windows() and HAS_WINDOWS_MODULES):
return __virtualname__
return False
| Only works on Windows systems | only works on windows systems | Question:
What does this function do?
Code:
def __virtual__():
if (salt.utils.is_windows() and HAS_WINDOWS_MODULES):
return __virtualname__
return False
|
null | null | null | What does this function do? | def compare(name, first, second, bfr):
o = bfr[first.begin:first.end]
c = bfr[second.begin:second.end]
match = False
if ((o == 'if') and (c == 'fi')):
match = True
elif ((o in BASH_KEYWORDS) and (c == 'done')):
match = True
elif ((o == 'case') and (c == 'esac')):
match = True
return match
| null | null | null | Ensure correct open is paired with correct close. | pcsd | def compare name first second bfr o = bfr[first begin first end] c = bfr[second begin second end] match = False if o == 'if' and c == 'fi' match = True elif o in BASH KEYWORDS and c == 'done' match = True elif o == 'case' and c == 'esac' match = True return match | 11418 | def compare(name, first, second, bfr):
o = bfr[first.begin:first.end]
c = bfr[second.begin:second.end]
match = False
if ((o == 'if') and (c == 'fi')):
match = True
elif ((o in BASH_KEYWORDS) and (c == 'done')):
match = True
elif ((o == 'case') and (c == 'esac')):
match = True
return match
| Ensure correct open is paired with correct close. | ensure correct open is paired with correct close . | Question:
What does this function do?
Code:
def compare(name, first, second, bfr):
o = bfr[first.begin:first.end]
c = bfr[second.begin:second.end]
match = False
if ((o == 'if') and (c == 'fi')):
match = True
elif ((o in BASH_KEYWORDS) and (c == 'done')):
match = True
elif ((o == 'case') and (c == 'esac')):... |
null | null | null | What does this function do? | def _service(service, action):
if (distrib_family() != 'gentoo'):
status = run_as_root(('service %(service)s %(action)s' % locals()), pty=False)
else:
status = run_as_root(('/etc/init.d/%(service)s %(action)s' % locals()), pty=False)
return status
| null | null | null | Compatibility layer for distros that use ``service`` and those that don\'t. | pcsd | def service service action if distrib family != 'gentoo' status = run as root 'service % service s % action s' % locals pty=False else status = run as root '/etc/init d/% service s % action s' % locals pty=False return status | 11420 | def _service(service, action):
if (distrib_family() != 'gentoo'):
status = run_as_root(('service %(service)s %(action)s' % locals()), pty=False)
else:
status = run_as_root(('/etc/init.d/%(service)s %(action)s' % locals()), pty=False)
return status
| Compatibility layer for distros that use ``service`` and those that don\'t. | compatibility layer for distros that use service and those that dont . | Question:
What does this function do?
Code:
def _service(service, action):
if (distrib_family() != 'gentoo'):
status = run_as_root(('service %(service)s %(action)s' % locals()), pty=False)
else:
status = run_as_root(('/etc/init.d/%(service)s %(action)s' % locals()), pty=False)
return status
|
null | null | null | What does this function do? | def get_analysis():
analyzers = {}
filters = {}
snowball_langs = {'eu': 'Basque', 'ca': 'Catalan', 'da': 'Danish', 'nl': 'Dutch', 'en-US': 'English', 'fi': 'Finnish', 'fr': 'French', 'de': 'German', 'hu': 'Hungarian', 'it': 'Italian', 'no': 'Norwegian', 'pt-BR': 'Portuguese', 'ro': 'Romanian', 'ru': 'Russian', 'es':... | null | null | null | Generate all our custom analyzers, tokenizers, and filters
These are variants of the Snowball analyzer for various languages,
but could also include custom analyzers if the need arises. | pcsd | def get analysis analyzers = {} filters = {} snowball langs = {'eu' 'Basque' 'ca' 'Catalan' 'da' 'Danish' 'nl' 'Dutch' 'en-US' 'English' 'fi' 'Finnish' 'fr' 'French' 'de' 'German' 'hu' 'Hungarian' 'it' 'Italian' 'no' 'Norwegian' 'pt-BR' 'Portuguese' 'ro' 'Romanian' 'ru' 'Russian' 'es' 'Spanish' 'sv' 'Swedish' 'tr' 'Tur... | 11421 | def get_analysis():
analyzers = {}
filters = {}
snowball_langs = {'eu': 'Basque', 'ca': 'Catalan', 'da': 'Danish', 'nl': 'Dutch', 'en-US': 'English', 'fi': 'Finnish', 'fr': 'French', 'de': 'German', 'hu': 'Hungarian', 'it': 'Italian', 'no': 'Norwegian', 'pt-BR': 'Portuguese', 'ro': 'Romanian', 'ru': 'Russian', 'es':... | Generate all our custom analyzers, tokenizers, and filters
These are variants of the Snowball analyzer for various languages,
but could also include custom analyzers if the need arises. | generate all our custom analyzers , tokenizers , and filters | Question:
What does this function do?
Code:
def get_analysis():
analyzers = {}
filters = {}
snowball_langs = {'eu': 'Basque', 'ca': 'Catalan', 'da': 'Danish', 'nl': 'Dutch', 'en-US': 'English', 'fi': 'Finnish', 'fr': 'French', 'de': 'German', 'hu': 'Hungarian', 'it': 'Italian', 'no': 'Norwegian', 'pt-BR': 'Portug... |
null | null | null | What does this function do? | def __call__(self, func):
return FunctionMaker.create(func, 'with _self_: return _func_(%(shortsignature)s)', dict(_self_=self, _func_=func), __wrapped__=func)
| null | null | null | Context manager decorator | pcsd | def call self func return Function Maker create func 'with self return func % shortsignature s ' dict self =self func =func wrapped =func | 11441 | def __call__(self, func):
return FunctionMaker.create(func, 'with _self_: return _func_(%(shortsignature)s)', dict(_self_=self, _func_=func), __wrapped__=func)
| Context manager decorator | context manager decorator | Question:
What does this function do?
Code:
def __call__(self, func):
return FunctionMaker.create(func, 'with _self_: return _func_(%(shortsignature)s)', dict(_self_=self, _func_=func), __wrapped__=func)
|
null | null | null | What does this function do? | def config(settings):
settings.base.prepopulate.append('locations/MM')
settings.gis.countries.append('MM')
settings.L10n.languages['my'] = '\xe1\x80\x99\xe1\x80\xbc\xe1\x80\x94\xe1\x80\xba\xe1\x80\x99\xe1\x80\xac\xe1\x80\x85\xe1\x80\xac'
settings.L10n.utc_offset = '+0630'
settings.L10n.default_country_code = 95
s... | null | null | null | Template settings for Myanmar
- designed to be used in a Cascade with an application template | pcsd | def config settings settings base prepopulate append 'locations/MM' settings gis countries append 'MM' settings L10n languages['my'] = '\xe1\x80\x99\xe1\x80\xbc\xe1\x80\x94\xe1\x80\xba\xe1\x80\x99\xe1\x80\xac\xe1\x80\x85\xe1\x80\xac' settings L10n utc offset = '+0630' settings L10n default country code = 95 settings fi... | 11450 | def config(settings):
settings.base.prepopulate.append('locations/MM')
settings.gis.countries.append('MM')
settings.L10n.languages['my'] = '\xe1\x80\x99\xe1\x80\xbc\xe1\x80\x94\xe1\x80\xba\xe1\x80\x99\xe1\x80\xac\xe1\x80\x85\xe1\x80\xac'
settings.L10n.utc_offset = '+0630'
settings.L10n.default_country_code = 95
s... | Template settings for Myanmar
- designed to be used in a Cascade with an application template | template settings for myanmar - designed to be used in a cascade with an application template | Question:
What does this function do?
Code:
def config(settings):
settings.base.prepopulate.append('locations/MM')
settings.gis.countries.append('MM')
settings.L10n.languages['my'] = '\xe1\x80\x99\xe1\x80\xbc\xe1\x80\x94\xe1\x80\xba\xe1\x80\x99\xe1\x80\xac\xe1\x80\x85\xe1\x80\xac'
settings.L10n.utc_offset = '+06... |
null | null | null | What does this function do? | def imread(fname, dtype=None):
ds = gdal.Open(fname)
return ds.ReadAsArray().astype(dtype)
| null | null | null | Load an image from file. | pcsd | def imread fname dtype=None ds = gdal Open fname return ds Read As Array astype dtype | 11451 | def imread(fname, dtype=None):
ds = gdal.Open(fname)
return ds.ReadAsArray().astype(dtype)
| Load an image from file. | load an image from file . | Question:
What does this function do?
Code:
def imread(fname, dtype=None):
ds = gdal.Open(fname)
return ds.ReadAsArray().astype(dtype)
|
null | null | null | What does this function do? | def static_with_version(path):
path_re = re.compile('(.*)/([^/]*$)')
return re.sub(path_re, ('\\1/%s/\\2' % cms.__version__), path)
| null | null | null | Changes provided path from `path/to/filename.ext` to `path/to/$CMS_VERSION/filename.ext` | pcsd | def static with version path path re = re compile ' * / [^/]*$ ' return re sub path re '\\1/%s/\\2' % cms version path | 11463 | def static_with_version(path):
path_re = re.compile('(.*)/([^/]*$)')
return re.sub(path_re, ('\\1/%s/\\2' % cms.__version__), path)
| Changes provided path from `path/to/filename.ext` to `path/to/$CMS_VERSION/filename.ext` | changes provided path from path / to / filename . ext to path / to / $ cms _ version / filename . ext | Question:
What does this function do?
Code:
def static_with_version(path):
path_re = re.compile('(.*)/([^/]*$)')
return re.sub(path_re, ('\\1/%s/\\2' % cms.__version__), path)
|
null | null | null | What does this function do? | def returner(load):
for returner_ in __opts__[CONFIG_KEY]:
_mminion().returners['{0}.returner'.format(returner_)](load)
| null | null | null | Write return to all returners in multi_returner | pcsd | def returner load for returner in opts [CONFIG KEY] mminion returners['{0} returner' format returner ] load | 11470 | def returner(load):
for returner_ in __opts__[CONFIG_KEY]:
_mminion().returners['{0}.returner'.format(returner_)](load)
| Write return to all returners in multi_returner | write return to all returners in multi _ returner | Question:
What does this function do?
Code:
def returner(load):
for returner_ in __opts__[CONFIG_KEY]:
_mminion().returners['{0}.returner'.format(returner_)](load)
|
null | null | null | What does this function do? | def teardown():
db_teardown()
| null | null | null | Common teardown function. | pcsd | def teardown db teardown | 11480 | def teardown():
db_teardown()
| Common teardown function. | common teardown function . | Question:
What does this function do?
Code:
def teardown():
db_teardown()
|
null | null | null | What does this function do? | @register.inclusion_tag(u'modeladmin/includes/result_list.html', takes_context=True)
def result_list(context):
view = context[u'view']
object_list = context[u'object_list']
headers = list(result_headers(view))
num_sorted_fields = 0
for h in headers:
if (h[u'sortable'] and h[u'sorted']):
num_sorted_fields += 1... | null | null | null | Displays the headers and data list together | pcsd | @register inclusion tag u'modeladmin/includes/result list html' takes context=True def result list context view = context[u'view'] object list = context[u'object list'] headers = list result headers view num sorted fields = 0 for h in headers if h[u'sortable'] and h[u'sorted'] num sorted fields += 1 context update {u'r... | 11483 | @register.inclusion_tag(u'modeladmin/includes/result_list.html', takes_context=True)
def result_list(context):
view = context[u'view']
object_list = context[u'object_list']
headers = list(result_headers(view))
num_sorted_fields = 0
for h in headers:
if (h[u'sortable'] and h[u'sorted']):
num_sorted_fields += 1... | Displays the headers and data list together | displays the headers and data list together | Question:
What does this function do?
Code:
@register.inclusion_tag(u'modeladmin/includes/result_list.html', takes_context=True)
def result_list(context):
view = context[u'view']
object_list = context[u'object_list']
headers = list(result_headers(view))
num_sorted_fields = 0
for h in headers:
if (h[u'sortable... |
null | null | null | What does this function do? | def TagBytes(field_number, wire_type):
return _VarintBytes(wire_format.PackTag(field_number, wire_type))
| null | null | null | Encode the given tag and return the bytes. Only called at startup. | pcsd | def Tag Bytes field number wire type return Varint Bytes wire format Pack Tag field number wire type | 11489 | def TagBytes(field_number, wire_type):
return _VarintBytes(wire_format.PackTag(field_number, wire_type))
| Encode the given tag and return the bytes. Only called at startup. | encode the given tag and return the bytes . | Question:
What does this function do?
Code:
def TagBytes(field_number, wire_type):
return _VarintBytes(wire_format.PackTag(field_number, wire_type))
|
null | null | null | What does this function do? | def isiterable(obj):
return hasattr(obj, '__iter__')
| null | null | null | Check if object is iterable (string excluded) | pcsd | def isiterable obj return hasattr obj ' iter ' | 11491 | def isiterable(obj):
return hasattr(obj, '__iter__')
| Check if object is iterable (string excluded) | check if object is iterable | Question:
What does this function do?
Code:
def isiterable(obj):
return hasattr(obj, '__iter__')
|
null | null | null | What does this function do? | def run_suite(*modules):
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for name in modules:
path = ('applications.%s.modules.unit_tests.%s' % (current.request.application, name))
tests = loader.loadTestsFromName(path)
suite.addTests(tests)
if (suite is not None):
result = unittest.TextTestRunn... | null | null | null | Run the test suite | pcsd | def run suite *modules loader = unittest Test Loader suite = unittest Test Suite for name in modules path = 'applications %s modules unit tests %s' % current request application name tests = loader load Tests From Name path suite add Tests tests if suite is not None result = unittest Text Test Runner verbosity=2 run su... | 11494 | def run_suite(*modules):
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for name in modules:
path = ('applications.%s.modules.unit_tests.%s' % (current.request.application, name))
tests = loader.loadTestsFromName(path)
suite.addTests(tests)
if (suite is not None):
result = unittest.TextTestRunn... | Run the test suite | run the test suite | Question:
What does this function do?
Code:
def run_suite(*modules):
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for name in modules:
path = ('applications.%s.modules.unit_tests.%s' % (current.request.application, name))
tests = loader.loadTestsFromName(path)
suite.addTests(tests)
if (suite... |
null | null | null | What does this function do? | def build_inlinepatterns(md_instance, **kwargs):
inlinePatterns = odict.OrderedDict()
inlinePatterns[u'backtick'] = BacktickPattern(BACKTICK_RE)
inlinePatterns[u'escape'] = EscapePattern(ESCAPE_RE, md_instance)
inlinePatterns[u'reference'] = ReferencePattern(REFERENCE_RE, md_instance)
inlinePatterns[u'link'] = Lin... | null | null | null | Build the default set of inline patterns for Markdown. | pcsd | def build inlinepatterns md instance **kwargs inline Patterns = odict Ordered Dict inline Patterns[u'backtick'] = Backtick Pattern BACKTICK RE inline Patterns[u'escape'] = Escape Pattern ESCAPE RE md instance inline Patterns[u'reference'] = Reference Pattern REFERENCE RE md instance inline Patterns[u'link'] = Link Patt... | 11504 | def build_inlinepatterns(md_instance, **kwargs):
inlinePatterns = odict.OrderedDict()
inlinePatterns[u'backtick'] = BacktickPattern(BACKTICK_RE)
inlinePatterns[u'escape'] = EscapePattern(ESCAPE_RE, md_instance)
inlinePatterns[u'reference'] = ReferencePattern(REFERENCE_RE, md_instance)
inlinePatterns[u'link'] = Lin... | Build the default set of inline patterns for Markdown. | build the default set of inline patterns for markdown . | Question:
What does this function do?
Code:
def build_inlinepatterns(md_instance, **kwargs):
inlinePatterns = odict.OrderedDict()
inlinePatterns[u'backtick'] = BacktickPattern(BACKTICK_RE)
inlinePatterns[u'escape'] = EscapePattern(ESCAPE_RE, md_instance)
inlinePatterns[u'reference'] = ReferencePattern(REFERENCE_... |
null | null | null | What does this function do? | def person():
return s3db.vol_person_controller()
| null | null | null | RESTful controller for Community Volunteers | pcsd | def person return s3db vol person controller | 11513 | def person():
return s3db.vol_person_controller()
| RESTful controller for Community Volunteers | restful controller for community volunteers | Question:
What does this function do?
Code:
def person():
return s3db.vol_person_controller()
|
null | null | null | What does this function do? | def get_static_page_by_path(path):
if (path == 'index_2.html'):
return get_static_index_page(False)
elif (path == 'index.html'):
return get_static_index_page(True)
elif (path == 'NLTK Wordnet Browser Database Info.html'):
return 'Display of Wordnet Database Statistics is not supported'
elif (path == 'upper_2.... | null | null | null | Return a static HTML page from the path given. | pcsd | def get static page by path path if path == 'index 2 html' return get static index page False elif path == 'index html' return get static index page True elif path == 'NLTK Wordnet Browser Database Info html' return 'Display of Wordnet Database Statistics is not supported' elif path == 'upper 2 html' return get static ... | 11516 | def get_static_page_by_path(path):
if (path == 'index_2.html'):
return get_static_index_page(False)
elif (path == 'index.html'):
return get_static_index_page(True)
elif (path == 'NLTK Wordnet Browser Database Info.html'):
return 'Display of Wordnet Database Statistics is not supported'
elif (path == 'upper_2.... | Return a static HTML page from the path given. | return a static html page from the path given . | Question:
What does this function do?
Code:
def get_static_page_by_path(path):
if (path == 'index_2.html'):
return get_static_index_page(False)
elif (path == 'index.html'):
return get_static_index_page(True)
elif (path == 'NLTK Wordnet Browser Database Info.html'):
return 'Display of Wordnet Database Statis... |
null | null | null | What does this function do? | def _getAccessibleAttribute(attributeName, dictionaryObject):
if (attributeName in globalNativeFunctionSet):
return getattr(dictionaryObject, attributeName, None)
if (attributeName in globalGetAccessibleAttributeSet):
stringAttribute = DictionaryAttribute(dictionaryObject)
return getattr(stringAttribute, attrib... | null | null | null | Get the accessible attribute. | pcsd | def get Accessible Attribute attribute Name dictionary Object if attribute Name in global Native Function Set return getattr dictionary Object attribute Name None if attribute Name in global Get Accessible Attribute Set string Attribute = Dictionary Attribute dictionary Object return getattr string Attribute attribute ... | 11517 | def _getAccessibleAttribute(attributeName, dictionaryObject):
if (attributeName in globalNativeFunctionSet):
return getattr(dictionaryObject, attributeName, None)
if (attributeName in globalGetAccessibleAttributeSet):
stringAttribute = DictionaryAttribute(dictionaryObject)
return getattr(stringAttribute, attrib... | Get the accessible attribute. | get the accessible attribute . | Question:
What does this function do?
Code:
def _getAccessibleAttribute(attributeName, dictionaryObject):
if (attributeName in globalNativeFunctionSet):
return getattr(dictionaryObject, attributeName, None)
if (attributeName in globalGetAccessibleAttributeSet):
stringAttribute = DictionaryAttribute(dictionaryO... |
null | null | null | What does this function do? | def _untranslate_snapshot_summary_view(context, snapshot):
d = {}
d['id'] = snapshot.id
d['status'] = snapshot.status
d['progress'] = snapshot.progress
d['size'] = snapshot.size
d['created_at'] = snapshot.created_at
d['display_name'] = snapshot.name
d['display_description'] = snapshot.description
d['volume_id'... | null | null | null | Maps keys for snapshots summary view. | pcsd | def untranslate snapshot summary view context snapshot d = {} d['id'] = snapshot id d['status'] = snapshot status d['progress'] = snapshot progress d['size'] = snapshot size d['created at'] = snapshot created at d['display name'] = snapshot name d['display description'] = snapshot description d['volume id'] = snapshot ... | 11521 | def _untranslate_snapshot_summary_view(context, snapshot):
d = {}
d['id'] = snapshot.id
d['status'] = snapshot.status
d['progress'] = snapshot.progress
d['size'] = snapshot.size
d['created_at'] = snapshot.created_at
d['display_name'] = snapshot.name
d['display_description'] = snapshot.description
d['volume_id'... | Maps keys for snapshots summary view. | maps keys for snapshots summary view . | Question:
What does this function do?
Code:
def _untranslate_snapshot_summary_view(context, snapshot):
d = {}
d['id'] = snapshot.id
d['status'] = snapshot.status
d['progress'] = snapshot.progress
d['size'] = snapshot.size
d['created_at'] = snapshot.created_at
d['display_name'] = snapshot.name
d['display_desc... |
null | null | null | What does this function do? | def main():
config.parse_args(sys.argv, default_config_files=jsonutils.loads(os.environ['CONFIG_FILE']))
logging.setup(CONF, 'nova')
global LOG
LOG = logging.getLogger('nova.dhcpbridge')
if (CONF.action.name == 'old'):
return
objects.register_all()
cmd_common.block_db_access('nova-dhcpbridge')
objects_base.No... | null | null | null | Parse environment and arguments and call the appropriate action. | pcsd | def main config parse args sys argv default config files=jsonutils loads os environ['CONFIG FILE'] logging setup CONF 'nova' global LOG LOG = logging get Logger 'nova dhcpbridge' if CONF action name == 'old' return objects register all cmd common block db access 'nova-dhcpbridge' objects base Nova Object indirection ap... | 11522 | def main():
config.parse_args(sys.argv, default_config_files=jsonutils.loads(os.environ['CONFIG_FILE']))
logging.setup(CONF, 'nova')
global LOG
LOG = logging.getLogger('nova.dhcpbridge')
if (CONF.action.name == 'old'):
return
objects.register_all()
cmd_common.block_db_access('nova-dhcpbridge')
objects_base.No... | Parse environment and arguments and call the appropriate action. | parse environment and arguments and call the appropriate action . | Question:
What does this function do?
Code:
def main():
config.parse_args(sys.argv, default_config_files=jsonutils.loads(os.environ['CONFIG_FILE']))
logging.setup(CONF, 'nova')
global LOG
LOG = logging.getLogger('nova.dhcpbridge')
if (CONF.action.name == 'old'):
return
objects.register_all()
cmd_common.bloc... |
null | null | null | What does this function do? | def main():
for filename in sys.argv[1:]:
rewrite_file(filename)
| null | null | null | Rewrites all PB2 files. | pcsd | def main for filename in sys argv[1 ] rewrite file filename | 11523 | def main():
for filename in sys.argv[1:]:
rewrite_file(filename)
| Rewrites all PB2 files. | rewrites all pb2 files . | Question:
What does this function do?
Code:
def main():
for filename in sys.argv[1:]:
rewrite_file(filename)
|
null | null | null | What does this function do? | def __virtual__():
if (__grains__['os'] == 'FreeBSD'):
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: only available on FreeBSD systems.')
| null | null | null | Only runs on FreeBSD systems | pcsd | def virtual if grains ['os'] == 'Free BSD' return virtualname return False 'The freebsdports execution module cannot be loaded only available on Free BSD systems ' | 11526 | def __virtual__():
if (__grains__['os'] == 'FreeBSD'):
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: only available on FreeBSD systems.')
| Only runs on FreeBSD systems | only runs on freebsd systems | Question:
What does this function do?
Code:
def __virtual__():
if (__grains__['os'] == 'FreeBSD'):
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: only available on FreeBSD systems.')
|
null | null | null | What does this function do? | def map_keys(dikt, func):
return dict(((func(key), value) for (key, value) in six.iteritems(dikt)))
| null | null | null | Map dictionary keys. | pcsd | def map keys dikt func return dict func key value for key value in six iteritems dikt | 11534 | def map_keys(dikt, func):
return dict(((func(key), value) for (key, value) in six.iteritems(dikt)))
| Map dictionary keys. | map dictionary keys . | Question:
What does this function do?
Code:
def map_keys(dikt, func):
return dict(((func(key), value) for (key, value) in six.iteritems(dikt)))
|
null | null | null | What does this function do? | @slow_test
@testing.requires_testing_data
def test_morphed_source_space_return():
data = rng.randn(20484, 1)
(tmin, tstep) = (0, 1.0)
src_fs = read_source_spaces(fname_fs)
stc_fs = SourceEstimate(data, [s['vertno'] for s in src_fs], tmin, tstep, 'fsaverage')
src_morph = morph_source_spaces(src_fs, 'sample', subjec... | null | null | null | Test returning a morphed source space to the original subject | pcsd | @slow test @testing requires testing data def test morphed source space return data = rng randn 20484 1 tmin tstep = 0 1 0 src fs = read source spaces fname fs stc fs = Source Estimate data [s['vertno'] for s in src fs] tmin tstep 'fsaverage' src morph = morph source spaces src fs 'sample' subjects dir=subjects dir stc... | 11544 | @slow_test
@testing.requires_testing_data
def test_morphed_source_space_return():
data = rng.randn(20484, 1)
(tmin, tstep) = (0, 1.0)
src_fs = read_source_spaces(fname_fs)
stc_fs = SourceEstimate(data, [s['vertno'] for s in src_fs], tmin, tstep, 'fsaverage')
src_morph = morph_source_spaces(src_fs, 'sample', subjec... | Test returning a morphed source space to the original subject | test returning a morphed source space to the original subject | Question:
What does this function do?
Code:
@slow_test
@testing.requires_testing_data
def test_morphed_source_space_return():
data = rng.randn(20484, 1)
(tmin, tstep) = (0, 1.0)
src_fs = read_source_spaces(fname_fs)
stc_fs = SourceEstimate(data, [s['vertno'] for s in src_fs], tmin, tstep, 'fsaverage')
src_morph... |
null | null | null | What does this function do? | def versioned_bucket_lister(bucket, prefix='', delimiter='', key_marker='', version_id_marker='', headers=None, encoding_type=None):
more_results = True
k = None
while more_results:
rs = bucket.get_all_versions(prefix=prefix, key_marker=key_marker, version_id_marker=version_id_marker, delimiter=delimiter, headers=... | null | null | null | A generator function for listing versions in a bucket. | pcsd | def versioned bucket lister bucket prefix='' delimiter='' key marker='' version id marker='' headers=None encoding type=None more results = True k = None while more results rs = bucket get all versions prefix=prefix key marker=key marker version id marker=version id marker delimiter=delimiter headers=headers max keys=9... | 11546 | def versioned_bucket_lister(bucket, prefix='', delimiter='', key_marker='', version_id_marker='', headers=None, encoding_type=None):
more_results = True
k = None
while more_results:
rs = bucket.get_all_versions(prefix=prefix, key_marker=key_marker, version_id_marker=version_id_marker, delimiter=delimiter, headers=... | A generator function for listing versions in a bucket. | a generator function for listing versions in a bucket . | Question:
What does this function do?
Code:
def versioned_bucket_lister(bucket, prefix='', delimiter='', key_marker='', version_id_marker='', headers=None, encoding_type=None):
more_results = True
k = None
while more_results:
rs = bucket.get_all_versions(prefix=prefix, key_marker=key_marker, version_id_marker=v... |
null | null | null | What does this function do? | @public
def legendre_poly(n, x=None, **args):
if (n < 0):
raise ValueError(("can't generate Legendre polynomial of degree %s" % n))
poly = DMP(dup_legendre(int(n), QQ), QQ)
if (x is not None):
poly = Poly.new(poly, x)
else:
poly = PurePoly.new(poly, Dummy('x'))
if (not args.get('polys', False)):
return pol... | null | null | null | Generates Legendre polynomial of degree `n` in `x`. | pcsd | @public def legendre poly n x=None **args if n < 0 raise Value Error "can't generate Legendre polynomial of degree %s" % n poly = DMP dup legendre int n QQ QQ 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 | 11554 | @public
def legendre_poly(n, x=None, **args):
if (n < 0):
raise ValueError(("can't generate Legendre polynomial of degree %s" % n))
poly = DMP(dup_legendre(int(n), QQ), QQ)
if (x is not None):
poly = Poly.new(poly, x)
else:
poly = PurePoly.new(poly, Dummy('x'))
if (not args.get('polys', False)):
return pol... | Generates Legendre polynomial of degree `n` in `x`. | generates legendre polynomial of degree n in x . | Question:
What does this function do?
Code:
@public
def legendre_poly(n, x=None, **args):
if (n < 0):
raise ValueError(("can't generate Legendre polynomial of degree %s" % n))
poly = DMP(dup_legendre(int(n), QQ), QQ)
if (x is not None):
poly = Poly.new(poly, x)
else:
poly = PurePoly.new(poly, Dummy('x'))
... |
null | null | null | What does this function do? | def probability_of(qty, user_settings):
if (qty in ['exercise', 'video']):
return sqrt(((user_settings['effort_level'] * 3) * user_settings['time_in_program']))
if (qty == 'completed'):
return ((((0.33 * user_settings['effort_level']) + (0.66 * user_settings['speed_of_learning'])) * 2) * user_settings['time_in_pr... | null | null | null | Share some probabilities across exercise and video logs | pcsd | def probability of qty user settings if qty in ['exercise' 'video'] return sqrt user settings['effort level'] * 3 * user settings['time in program'] if qty == 'completed' return 0 33 * user settings['effort level'] + 0 66 * user settings['speed of learning'] * 2 * user settings['time in program'] if qty == 'attempts' r... | 11559 | def probability_of(qty, user_settings):
if (qty in ['exercise', 'video']):
return sqrt(((user_settings['effort_level'] * 3) * user_settings['time_in_program']))
if (qty == 'completed'):
return ((((0.33 * user_settings['effort_level']) + (0.66 * user_settings['speed_of_learning'])) * 2) * user_settings['time_in_pr... | Share some probabilities across exercise and video logs | share some probabilities across exercise and video logs | Question:
What does this function do?
Code:
def probability_of(qty, user_settings):
if (qty in ['exercise', 'video']):
return sqrt(((user_settings['effort_level'] * 3) * user_settings['time_in_program']))
if (qty == 'completed'):
return ((((0.33 * user_settings['effort_level']) + (0.66 * user_settings['speed_o... |
null | null | null | What does this function do? | @handle_response_format
@treeio_login_required
def item_add(request, response_format='html'):
items = Object.filter_permitted(manager=KnowledgeItem.objects, user=request.user.profile, mode='r')
if request.POST:
if ('cancel' not in request.POST):
item = KnowledgeItem()
form = KnowledgeItemForm(request.user.pro... | null | null | null | Add new knowledge item | pcsd | @handle response format @treeio login required def item add request response format='html' items = Object filter permitted manager=Knowledge Item objects user=request user profile mode='r' if request POST if 'cancel' not in request POST item = Knowledge Item form = Knowledge Item Form request user profile None request ... | 11561 | @handle_response_format
@treeio_login_required
def item_add(request, response_format='html'):
items = Object.filter_permitted(manager=KnowledgeItem.objects, user=request.user.profile, mode='r')
if request.POST:
if ('cancel' not in request.POST):
item = KnowledgeItem()
form = KnowledgeItemForm(request.user.pro... | Add new knowledge item | add new knowledge item | Question:
What does this function do?
Code:
@handle_response_format
@treeio_login_required
def item_add(request, response_format='html'):
items = Object.filter_permitted(manager=KnowledgeItem.objects, user=request.user.profile, mode='r')
if request.POST:
if ('cancel' not in request.POST):
item = KnowledgeItem... |
null | null | null | What does this function do? | @testing.requires_testing_data
@requires_freesurfer
@requires_nibabel()
def test_read_volume_from_src():
aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz')
labels_vol = ['Left-Amygdala', 'Brain-Stem', 'Right-Amygdala']
src = read_source_spaces(fname)
vol_src = setup_volume_source_space('sample', mri=as... | null | null | null | Test reading volumes from a mixed source space | pcsd | @testing requires testing data @requires freesurfer @requires nibabel def test read volume from src aseg fname = op join subjects dir 'sample' 'mri' 'aseg mgz' labels vol = ['Left-Amygdala' 'Brain-Stem' 'Right-Amygdala'] src = read source spaces fname vol src = setup volume source space 'sample' mri=aseg fname pos=5 0 ... | 11568 | @testing.requires_testing_data
@requires_freesurfer
@requires_nibabel()
def test_read_volume_from_src():
aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz')
labels_vol = ['Left-Amygdala', 'Brain-Stem', 'Right-Amygdala']
src = read_source_spaces(fname)
vol_src = setup_volume_source_space('sample', mri=as... | Test reading volumes from a mixed source space | test reading volumes from a mixed source space | Question:
What does this function do?
Code:
@testing.requires_testing_data
@requires_freesurfer
@requires_nibabel()
def test_read_volume_from_src():
aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz')
labels_vol = ['Left-Amygdala', 'Brain-Stem', 'Right-Amygdala']
src = read_source_spaces(fname)
vol_s... |
null | null | null | What does this function do? | def substrings(word, from_beginning_only=False):
w_len = len(word)
w_len_plus_1 = (w_len + 1)
i = 0
while (i < w_len):
j = (i + 2)
while (j < w_len_plus_1):
(yield word[i:j])
j += 1
if from_beginning_only:
return
i += 1
| null | null | null | A generator of all substrings in `word`
greater than 1 character in length. | pcsd | def substrings word from beginning only=False w len = len word w len plus 1 = w len + 1 i = 0 while i < w len j = i + 2 while j < w len plus 1 yield word[i j] j += 1 if from beginning only return i += 1 | 11578 | def substrings(word, from_beginning_only=False):
w_len = len(word)
w_len_plus_1 = (w_len + 1)
i = 0
while (i < w_len):
j = (i + 2)
while (j < w_len_plus_1):
(yield word[i:j])
j += 1
if from_beginning_only:
return
i += 1
| A generator of all substrings in `word`
greater than 1 character in length. | a generator of all substrings in word greater than 1 character in length . | Question:
What does this function do?
Code:
def substrings(word, from_beginning_only=False):
w_len = len(word)
w_len_plus_1 = (w_len + 1)
i = 0
while (i < w_len):
j = (i + 2)
while (j < w_len_plus_1):
(yield word[i:j])
j += 1
if from_beginning_only:
return
i += 1
|
null | null | null | What does this function do? | @check_login_required
@check_local_site_access
def search(*args, **kwargs):
search_view = RBSearchView()
return search_view(*args, **kwargs)
| null | null | null | Provide results for a given search. | pcsd | @check login required @check local site access def search *args **kwargs search view = RB Search View return search view *args **kwargs | 11589 | @check_login_required
@check_local_site_access
def search(*args, **kwargs):
search_view = RBSearchView()
return search_view(*args, **kwargs)
| Provide results for a given search. | provide results for a given search . | Question:
What does this function do?
Code:
@check_login_required
@check_local_site_access
def search(*args, **kwargs):
search_view = RBSearchView()
return search_view(*args, **kwargs)
|
null | null | null | What does this function do? | def legacy_path(path):
return urljoin(LEGACY_PYTHON_DOMAIN, path)
| null | null | null | Build a path to the same path under the legacy.python.org domain. | pcsd | def legacy path path return urljoin LEGACY PYTHON DOMAIN path | 11595 | def legacy_path(path):
return urljoin(LEGACY_PYTHON_DOMAIN, path)
| Build a path to the same path under the legacy.python.org domain. | build a path to the same path under the legacy . python . org domain . | Question:
What does this function do?
Code:
def legacy_path(path):
return urljoin(LEGACY_PYTHON_DOMAIN, path)
|
null | null | null | What does this function do? | @receiver(models.signals.post_save, sender=CreditProvider)
@receiver(models.signals.post_delete, sender=CreditProvider)
def invalidate_provider_cache(sender, **kwargs):
cache.delete(CreditProvider.CREDIT_PROVIDERS_CACHE_KEY)
| null | null | null | Invalidate the cache of credit providers. | pcsd | @receiver models signals post save sender=Credit Provider @receiver models signals post delete sender=Credit Provider def invalidate provider cache sender **kwargs cache delete Credit Provider CREDIT PROVIDERS CACHE KEY | 11602 | @receiver(models.signals.post_save, sender=CreditProvider)
@receiver(models.signals.post_delete, sender=CreditProvider)
def invalidate_provider_cache(sender, **kwargs):
cache.delete(CreditProvider.CREDIT_PROVIDERS_CACHE_KEY)
| Invalidate the cache of credit providers. | invalidate the cache of credit providers . | Question:
What does this function do?
Code:
@receiver(models.signals.post_save, sender=CreditProvider)
@receiver(models.signals.post_delete, sender=CreditProvider)
def invalidate_provider_cache(sender, **kwargs):
cache.delete(CreditProvider.CREDIT_PROVIDERS_CACHE_KEY)
|
null | null | null | What does this function do? | def new_session(engine, versioned=True):
session = Session(bind=engine, autoflush=True, autocommit=False)
if versioned:
configure_versioning(session)
transaction_start_map = {}
(frame, modname) = find_first_app_frame_and_name(ignores=['sqlalchemy', 'inbox.models.session', 'nylas.logging', 'contextlib'])
funcn... | null | null | null | Returns a session bound to the given engine. | pcsd | def new session engine versioned=True session = Session bind=engine autoflush=True autocommit=False if versioned configure versioning session transaction start map = {} frame modname = find first app frame and name ignores=['sqlalchemy' 'inbox models session' 'nylas logging' 'contextlib'] funcname = frame f code co nam... | 11613 | def new_session(engine, versioned=True):
session = Session(bind=engine, autoflush=True, autocommit=False)
if versioned:
configure_versioning(session)
transaction_start_map = {}
(frame, modname) = find_first_app_frame_and_name(ignores=['sqlalchemy', 'inbox.models.session', 'nylas.logging', 'contextlib'])
funcn... | Returns a session bound to the given engine. | returns a session bound to the given engine . | Question:
What does this function do?
Code:
def new_session(engine, versioned=True):
session = Session(bind=engine, autoflush=True, autocommit=False)
if versioned:
configure_versioning(session)
transaction_start_map = {}
(frame, modname) = find_first_app_frame_and_name(ignores=['sqlalchemy', 'inbox.models.se... |
null | null | null | What does this function do? | def processElse(elementNode):
evaluate.processCondition(elementNode)
| null | null | null | Process the else statement. | pcsd | def process Else element Node evaluate process Condition element Node | 11614 | def processElse(elementNode):
evaluate.processCondition(elementNode)
| Process the else statement. | process the else statement . | Question:
What does this function do?
Code:
def processElse(elementNode):
evaluate.processCondition(elementNode)
|
null | null | null | What does this function do? | def lookup(session, name_label):
vm_refs = session.call_xenapi('VM.get_by_name_label', name_label)
n = len(vm_refs)
if (n == 0):
return None
elif (n > 1):
raise exception.InstanceExists(name=name_label)
else:
return vm_refs[0]
| null | null | null | Look the instance up and return it if available. | pcsd | def lookup session name label vm refs = session call xenapi 'VM get by name label' name label n = len vm refs if n == 0 return None elif n > 1 raise exception Instance Exists name=name label else return vm refs[0] | 11621 | def lookup(session, name_label):
vm_refs = session.call_xenapi('VM.get_by_name_label', name_label)
n = len(vm_refs)
if (n == 0):
return None
elif (n > 1):
raise exception.InstanceExists(name=name_label)
else:
return vm_refs[0]
| Look the instance up and return it if available. | look the instance up and return it if available . | Question:
What does this function do?
Code:
def lookup(session, name_label):
vm_refs = session.call_xenapi('VM.get_by_name_label', name_label)
n = len(vm_refs)
if (n == 0):
return None
elif (n > 1):
raise exception.InstanceExists(name=name_label)
else:
return vm_refs[0]
|
null | null | null | What does this function do? | def stringc(text, color):
if ANSIBLE_COLOR:
return '\n'.join([(u'\x1b[%sm%s\x1b[0m' % (codeCodes[color], t)) for t in text.split('\n')])
else:
return text
| null | null | null | String in color. | pcsd | def stringc text color if ANSIBLE COLOR return ' ' join [ u'\x1b[%sm%s\x1b[0m' % code Codes[color] t for t in text split ' ' ] else return text | 11626 | def stringc(text, color):
if ANSIBLE_COLOR:
return '\n'.join([(u'\x1b[%sm%s\x1b[0m' % (codeCodes[color], t)) for t in text.split('\n')])
else:
return text
| String in color. | string in color . | Question:
What does this function do?
Code:
def stringc(text, color):
if ANSIBLE_COLOR:
return '\n'.join([(u'\x1b[%sm%s\x1b[0m' % (codeCodes[color], t)) for t in text.split('\n')])
else:
return text
|
null | null | null | What does this function do? | @app.route('/stats', methods=['GET'])
def stats():
stats = get_engines_stats()
return render('stats.html', stats=stats)
| null | null | null | Render engine statistics page. | pcsd | @app route '/stats' methods=['GET'] def stats stats = get engines stats return render 'stats html' stats=stats | 11631 | @app.route('/stats', methods=['GET'])
def stats():
stats = get_engines_stats()
return render('stats.html', stats=stats)
| Render engine statistics page. | render engine statistics page . | Question:
What does this function do?
Code:
@app.route('/stats', methods=['GET'])
def stats():
stats = get_engines_stats()
return render('stats.html', stats=stats)
|
null | null | null | What does this function do? | def headersParser(headers):
if (not kb.headerPaths):
kb.headerPaths = {'cookie': os.path.join(paths.SQLMAP_XML_BANNER_PATH, 'cookie.xml'), 'microsoftsharepointteamservices': os.path.join(paths.SQLMAP_XML_BANNER_PATH, 'sharepoint.xml'), 'server': os.path.join(paths.SQLMAP_XML_BANNER_PATH, 'server.xml'), 'servlet-engi... | null | null | null | This function calls a class that parses the input HTTP headers to
fingerprint the back-end database management system operating system
and the web application technology | pcsd | def headers Parser headers if not kb header Paths kb header Paths = {'cookie' os path join paths SQLMAP XML BANNER PATH 'cookie xml' 'microsoftsharepointteamservices' os path join paths SQLMAP XML BANNER PATH 'sharepoint xml' 'server' os path join paths SQLMAP XML BANNER PATH 'server xml' 'servlet-engine' os path join ... | 11657 | def headersParser(headers):
if (not kb.headerPaths):
kb.headerPaths = {'cookie': os.path.join(paths.SQLMAP_XML_BANNER_PATH, 'cookie.xml'), 'microsoftsharepointteamservices': os.path.join(paths.SQLMAP_XML_BANNER_PATH, 'sharepoint.xml'), 'server': os.path.join(paths.SQLMAP_XML_BANNER_PATH, 'server.xml'), 'servlet-engi... | This function calls a class that parses the input HTTP headers to
fingerprint the back-end database management system operating system
and the web application technology | this function calls a class that parses the input http headers to fingerprint the back - end database management system operating system and the web application technology | Question:
What does this function do?
Code:
def headersParser(headers):
if (not kb.headerPaths):
kb.headerPaths = {'cookie': os.path.join(paths.SQLMAP_XML_BANNER_PATH, 'cookie.xml'), 'microsoftsharepointteamservices': os.path.join(paths.SQLMAP_XML_BANNER_PATH, 'sharepoint.xml'), 'server': os.path.join(paths.SQLMA... |
null | null | null | What does this function do? | def load_tables(path_to_tables):
words = []
utable = numpy.load((path_to_tables + 'utable.npy'))
btable = numpy.load((path_to_tables + 'btable.npy'))
f = open((path_to_tables + 'dictionary.txt'), 'rb')
for line in f:
words.append(line.decode('utf-8').strip())
f.close()
utable = OrderedDict(zip(words, utable))
... | null | null | null | Load the tables | pcsd | def load tables path to tables words = [] utable = numpy load path to tables + 'utable npy' btable = numpy load path to tables + 'btable npy' f = open path to tables + 'dictionary txt' 'rb' for line in f words append line decode 'utf-8' strip f close utable = Ordered Dict zip words utable btable = Ordered Dict zip word... | 11662 | def load_tables(path_to_tables):
words = []
utable = numpy.load((path_to_tables + 'utable.npy'))
btable = numpy.load((path_to_tables + 'btable.npy'))
f = open((path_to_tables + 'dictionary.txt'), 'rb')
for line in f:
words.append(line.decode('utf-8').strip())
f.close()
utable = OrderedDict(zip(words, utable))
... | Load the tables | load the tables | Question:
What does this function do?
Code:
def load_tables(path_to_tables):
words = []
utable = numpy.load((path_to_tables + 'utable.npy'))
btable = numpy.load((path_to_tables + 'btable.npy'))
f = open((path_to_tables + 'dictionary.txt'), 'rb')
for line in f:
words.append(line.decode('utf-8').strip())
f.clo... |
null | null | null | What does this function do? | def safe_mkdir(dir):
try:
os.mkdir(dir)
except OSError as err:
if (err.errno != errno.EEXIST):
raise
| null | null | null | Convenience function for creating a directory | pcsd | def safe mkdir dir try os mkdir dir except OS Error as err if err errno != errno EEXIST raise | 11665 | def safe_mkdir(dir):
try:
os.mkdir(dir)
except OSError as err:
if (err.errno != errno.EEXIST):
raise
| Convenience function for creating a directory | convenience function for creating a directory | Question:
What does this function do?
Code:
def safe_mkdir(dir):
try:
os.mkdir(dir)
except OSError as err:
if (err.errno != errno.EEXIST):
raise
|
null | null | null | What does this function do? | @require_context
def instance_type_get_by_name(context, name, session=None):
result = _instance_type_get_query(context, session=session).filter_by(name=name).first()
if (not result):
raise exception.InstanceTypeNotFoundByName(instance_type_name=name)
return _dict_with_extra_specs(result)
| null | null | null | Returns a dict describing specific instance_type. | pcsd | @require context def instance type get by name context name session=None result = instance type get query context session=session filter by name=name first if not result raise exception Instance Type Not Found By Name instance type name=name return dict with extra specs result | 11666 | @require_context
def instance_type_get_by_name(context, name, session=None):
result = _instance_type_get_query(context, session=session).filter_by(name=name).first()
if (not result):
raise exception.InstanceTypeNotFoundByName(instance_type_name=name)
return _dict_with_extra_specs(result)
| Returns a dict describing specific instance_type. | returns a dict describing specific instance _ type . | Question:
What does this function do?
Code:
@require_context
def instance_type_get_by_name(context, name, session=None):
result = _instance_type_get_query(context, session=session).filter_by(name=name).first()
if (not result):
raise exception.InstanceTypeNotFoundByName(instance_type_name=name)
return _dict_with... |
null | null | null | What does this function do? | def is_css_file(path):
ext = os.path.splitext(path)[1].lower()
return (ext in [u'.css'])
| null | null | null | Return True if the given file path is a CSS file. | pcsd | def is css file path ext = os path splitext path [1] lower return ext in [u' css'] | 11670 | def is_css_file(path):
ext = os.path.splitext(path)[1].lower()
return (ext in [u'.css'])
| Return True if the given file path is a CSS file. | return true if the given file path is a css file . | Question:
What does this function do?
Code:
def is_css_file(path):
ext = os.path.splitext(path)[1].lower()
return (ext in [u'.css'])
|
null | null | null | What does this function do? | def getCraftSequence():
return 'cleave,preface,coil,flow,feed,home,lash,fillet,limit,dimension,unpause,export'.split(',')
| null | null | null | Get the winding craft sequence. | pcsd | def get Craft Sequence return 'cleave preface coil flow feed home lash fillet limit dimension unpause export' split ' ' | 11671 | def getCraftSequence():
return 'cleave,preface,coil,flow,feed,home,lash,fillet,limit,dimension,unpause,export'.split(',')
| Get the winding craft sequence. | get the winding craft sequence . | Question:
What does this function do?
Code:
def getCraftSequence():
return 'cleave,preface,coil,flow,feed,home,lash,fillet,limit,dimension,unpause,export'.split(',')
|
null | null | null | What does this function do? | def color(color_):
if settings.no_colors:
return ''
else:
return color_
| null | null | null | Utility for ability to disabling colored output. | pcsd | def color color if settings no colors return '' else return color | 11672 | def color(color_):
if settings.no_colors:
return ''
else:
return color_
| Utility for ability to disabling colored output. | utility for ability to disabling colored output . | Question:
What does this function do?
Code:
def color(color_):
if settings.no_colors:
return ''
else:
return color_
|
null | null | null | What does this function do? | def _es_documents_for(locale, topics=None, products=None):
s = DocumentMappingType.search().values_dict('id', 'document_title', 'url', 'document_parent_id', 'document_summary').filter(document_locale=locale, document_is_archived=False, document_category__in=settings.IA_DEFAULT_CATEGORIES)
for topic in (topics or []):... | null | null | null | ES implementation of documents_for. | pcsd | def es documents for locale topics=None products=None s = Document Mapping Type search values dict 'id' 'document title' 'url' 'document parent id' 'document summary' filter document locale=locale document is archived=False document category in=settings IA DEFAULT CATEGORIES for topic in topics or [] s = s filter topic... | 11678 | def _es_documents_for(locale, topics=None, products=None):
s = DocumentMappingType.search().values_dict('id', 'document_title', 'url', 'document_parent_id', 'document_summary').filter(document_locale=locale, document_is_archived=False, document_category__in=settings.IA_DEFAULT_CATEGORIES)
for topic in (topics or []):... | ES implementation of documents_for. | es implementation of documents _ for . | Question:
What does this function do?
Code:
def _es_documents_for(locale, topics=None, products=None):
s = DocumentMappingType.search().values_dict('id', 'document_title', 'url', 'document_parent_id', 'document_summary').filter(document_locale=locale, document_is_archived=False, document_category__in=settings.IA_DE... |
null | null | null | What does this function do? | def put_object(url, **kwargs):
client = SimpleClient(url=url)
client.retry_request('PUT', **kwargs)
| null | null | null | For usage with container sync | pcsd | def put object url **kwargs client = Simple Client url=url client retry request 'PUT' **kwargs | 11681 | def put_object(url, **kwargs):
client = SimpleClient(url=url)
client.retry_request('PUT', **kwargs)
| For usage with container sync | for usage with container sync | Question:
What does this function do?
Code:
def put_object(url, **kwargs):
client = SimpleClient(url=url)
client.retry_request('PUT', **kwargs)
|
null | null | null | What does this function do? | def read_uic_tag(fh, tagid, plane_count, offset):
def read_int(count=1):
value = struct.unpack(('<%iI' % count), fh.read((4 * count)))
return (value[0] if (count == 1) else value)
try:
(name, dtype) = UIC_TAGS[tagid]
except KeyError:
return (('_tagid_%i' % tagid), read_int())
if offset:
pos = fh.tell()
... | null | null | null | Read a single UIC tag value from file and return tag name and value.
UIC1Tags use an offset. | pcsd | def read uic tag fh tagid plane count offset def read int count=1 value = struct unpack '<%i I' % count fh read 4 * count return value[0] if count == 1 else value try name dtype = UIC TAGS[tagid] except Key Error return ' tagid %i' % tagid read int if offset pos = fh tell if dtype not in int None off = read int if off ... | 11688 | def read_uic_tag(fh, tagid, plane_count, offset):
def read_int(count=1):
value = struct.unpack(('<%iI' % count), fh.read((4 * count)))
return (value[0] if (count == 1) else value)
try:
(name, dtype) = UIC_TAGS[tagid]
except KeyError:
return (('_tagid_%i' % tagid), read_int())
if offset:
pos = fh.tell()
... | Read a single UIC tag value from file and return tag name and value.
UIC1Tags use an offset. | read a single uic tag value from file and return tag name and value . | Question:
What does this function do?
Code:
def read_uic_tag(fh, tagid, plane_count, offset):
def read_int(count=1):
value = struct.unpack(('<%iI' % count), fh.read((4 * count)))
return (value[0] if (count == 1) else value)
try:
(name, dtype) = UIC_TAGS[tagid]
except KeyError:
return (('_tagid_%i' % tagid... |
null | null | null | What does this function do? | def upload_blob(bucket_name, source_file_name, destination_blob_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print 'File {} uploaded to {}.'.format(source_file_name, destination_blob_na... | null | null | null | Uploads a file to the bucket. | pcsd | def upload blob bucket name source file name destination blob name storage client = storage Client bucket = storage client get bucket bucket name blob = bucket blob destination blob name blob upload from filename source file name print 'File {} uploaded to {} ' format source file name destination blob name | 11696 | def upload_blob(bucket_name, source_file_name, destination_blob_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print 'File {} uploaded to {}.'.format(source_file_name, destination_blob_na... | Uploads a file to the bucket. | uploads a file to the bucket . | Question:
What does this function do?
Code:
def upload_blob(bucket_name, source_file_name, destination_blob_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print 'File {} uploaded to {}... |
null | null | null | What does this function do? | def get_quote_by_chan(db, chan, num=False):
count_query = select([qtable]).where((qtable.c.deleted != 1)).where((qtable.c.chan == chan)).count()
count = db.execute(count_query).fetchall()[0][0]
try:
num = get_quote_num(num, count, chan)
except Exception as error_message:
return error_message
query = select([qt... | null | null | null | Returns a formatted quote from a channel, random or selected by number | pcsd | def get quote by chan db chan num=False count query = select [qtable] where qtable c deleted != 1 where qtable c chan == chan count count = db execute count query fetchall [0][0] try num = get quote num num count chan except Exception as error message return error message query = select [qtable c time qtable c nick qta... | 11699 | def get_quote_by_chan(db, chan, num=False):
count_query = select([qtable]).where((qtable.c.deleted != 1)).where((qtable.c.chan == chan)).count()
count = db.execute(count_query).fetchall()[0][0]
try:
num = get_quote_num(num, count, chan)
except Exception as error_message:
return error_message
query = select([qt... | Returns a formatted quote from a channel, random or selected by number | returns a formatted quote from a channel , random or selected by number | Question:
What does this function do?
Code:
def get_quote_by_chan(db, chan, num=False):
count_query = select([qtable]).where((qtable.c.deleted != 1)).where((qtable.c.chan == chan)).count()
count = db.execute(count_query).fetchall()[0][0]
try:
num = get_quote_num(num, count, chan)
except Exception as error_mess... |
null | null | null | What does this function do? | def redirect_output(path):
outfile = open(path, 'a')
sys.stdout = outfile
sys.stderr = outfile
| null | null | null | Redirect stdout and stderr to a file. | pcsd | def redirect output path outfile = open path 'a' sys stdout = outfile sys stderr = outfile | 11700 | def redirect_output(path):
outfile = open(path, 'a')
sys.stdout = outfile
sys.stderr = outfile
| Redirect stdout and stderr to a file. | redirect stdout and stderr to a file . | Question:
What does this function do?
Code:
def redirect_output(path):
outfile = open(path, 'a')
sys.stdout = outfile
sys.stderr = outfile
|
null | null | null | What does this function do? | def AumSortedConcatenate():
def step(ctxt, ndx, author, sort, link):
if (author is not None):
ctxt[ndx] = u':::'.join((author, sort, link))
def finalize(ctxt):
keys = list(ctxt.iterkeys())
l = len(keys)
if (l == 0):
return None
if (l == 1):
return ctxt[keys[0]]
return u':#:'.join([ctxt[v] for v i... | null | null | null | String concatenation aggregator for the author sort map | pcsd | def Aum Sorted Concatenate def step ctxt ndx author sort link if author is not None ctxt[ndx] = u' ' join author sort link def finalize ctxt keys = list ctxt iterkeys l = len keys if l == 0 return None if l == 1 return ctxt[keys[0]] return u' # ' join [ctxt[v] for v in sorted keys ] return {} step finalize | 11707 | def AumSortedConcatenate():
def step(ctxt, ndx, author, sort, link):
if (author is not None):
ctxt[ndx] = u':::'.join((author, sort, link))
def finalize(ctxt):
keys = list(ctxt.iterkeys())
l = len(keys)
if (l == 0):
return None
if (l == 1):
return ctxt[keys[0]]
return u':#:'.join([ctxt[v] for v i... | String concatenation aggregator for the author sort map | string concatenation aggregator for the author sort map | Question:
What does this function do?
Code:
def AumSortedConcatenate():
def step(ctxt, ndx, author, sort, link):
if (author is not None):
ctxt[ndx] = u':::'.join((author, sort, link))
def finalize(ctxt):
keys = list(ctxt.iterkeys())
l = len(keys)
if (l == 0):
return None
if (l == 1):
return ctxt... |
null | null | null | What does this function do? | def drk_dvr_rheader(r, tabs=[]):
if (r.representation != 'html'):
return None
from s3 import s3_rheader_resource, S3ResourceHeader, s3_fullname, s3_yes_no_represent
(tablename, record) = s3_rheader_resource(r)
if (tablename != r.tablename):
resource = current.s3db.resource(tablename, id=record.id)
else:
reso... | null | null | null | DVR custom resource headers | pcsd | def drk dvr rheader r tabs=[] if r representation != 'html' return None from s3 import s3 rheader resource S3Resource Header s3 fullname s3 yes no represent tablename record = s3 rheader resource r if tablename != r tablename resource = current s3db resource tablename id=record id else resource = r resource rheader = N... | 11727 | def drk_dvr_rheader(r, tabs=[]):
if (r.representation != 'html'):
return None
from s3 import s3_rheader_resource, S3ResourceHeader, s3_fullname, s3_yes_no_represent
(tablename, record) = s3_rheader_resource(r)
if (tablename != r.tablename):
resource = current.s3db.resource(tablename, id=record.id)
else:
reso... | DVR custom resource headers | dvr custom resource headers | Question:
What does this function do?
Code:
def drk_dvr_rheader(r, tabs=[]):
if (r.representation != 'html'):
return None
from s3 import s3_rheader_resource, S3ResourceHeader, s3_fullname, s3_yes_no_represent
(tablename, record) = s3_rheader_resource(r)
if (tablename != r.tablename):
resource = current.s3db.... |
null | null | null | What does this function do? | def ffmpeg_resize(video, output, size):
cmd = [get_setting('FFMPEG_BINARY'), '-i', video, '-vf', ('scale=%d:%d' % (res[0], res[1])), output]
subprocess_call(cmd)
| null | null | null | resizes ``video`` to new size ``size`` and write the result
in file ``output``. | pcsd | def ffmpeg resize video output size cmd = [get setting 'FFMPEG BINARY' '-i' video '-vf' 'scale=%d %d' % res[0] res[1] output] subprocess call cmd | 11731 | def ffmpeg_resize(video, output, size):
cmd = [get_setting('FFMPEG_BINARY'), '-i', video, '-vf', ('scale=%d:%d' % (res[0], res[1])), output]
subprocess_call(cmd)
| resizes ``video`` to new size ``size`` and write the result
in file ``output``. | resizes video to new size size and write the result in file output . | Question:
What does this function do?
Code:
def ffmpeg_resize(video, output, size):
cmd = [get_setting('FFMPEG_BINARY'), '-i', video, '-vf', ('scale=%d:%d' % (res[0], res[1])), output]
subprocess_call(cmd)
|
null | null | null | What does this function do? | def sort_key_by_numeric_other(key_value):
return tuple((((int(numeric) if numeric else None), (INSTANCE_SIZES.index(alpha) if (alpha in INSTANCE_SIZES) else alpha), other) for (numeric, alpha, other) in RE_NUMERIC_OTHER.findall(key_value[0])))
| null | null | null | Split key into numeric, alpha and other part and sort accordingly. | pcsd | def sort key by numeric other key value return tuple int numeric if numeric else None INSTANCE SIZES index alpha if alpha in INSTANCE SIZES else alpha other for numeric alpha other in RE NUMERIC OTHER findall key value[0] | 11735 | def sort_key_by_numeric_other(key_value):
return tuple((((int(numeric) if numeric else None), (INSTANCE_SIZES.index(alpha) if (alpha in INSTANCE_SIZES) else alpha), other) for (numeric, alpha, other) in RE_NUMERIC_OTHER.findall(key_value[0])))
| Split key into numeric, alpha and other part and sort accordingly. | split key into numeric , alpha and other part and sort accordingly . | Question:
What does this function do?
Code:
def sort_key_by_numeric_other(key_value):
return tuple((((int(numeric) if numeric else None), (INSTANCE_SIZES.index(alpha) if (alpha in INSTANCE_SIZES) else alpha), other) for (numeric, alpha, other) in RE_NUMERIC_OTHER.findall(key_value[0])))
|
null | null | null | What does this function do? | def render_to_text(*args, **kwargs):
return HttpResponse(loader.render_to_string(*args, **kwargs), mimetype='text/plain')
| null | null | null | Renders the response using the MIME type for plain text. | pcsd | def render to text *args **kwargs return Http Response loader render to string *args **kwargs mimetype='text/plain' | 11747 | def render_to_text(*args, **kwargs):
return HttpResponse(loader.render_to_string(*args, **kwargs), mimetype='text/plain')
| Renders the response using the MIME type for plain text. | renders the response using the mime type for plain text . | Question:
What does this function do?
Code:
def render_to_text(*args, **kwargs):
return HttpResponse(loader.render_to_string(*args, **kwargs), mimetype='text/plain')
|
null | null | null | What does this function do? | def list_unsubscribe(t):
(owner, slug) = get_slug()
try:
t.lists.subscribers.destroy(slug=slug, owner_screen_name=owner)
printNicely(green('Done.'))
except:
debug_option()
printNicely(light_magenta("I'm sorry you can not unsubscribe to this list."))
| null | null | null | Unsubscribe a list | pcsd | def list unsubscribe t owner slug = get slug try t lists subscribers destroy slug=slug owner screen name=owner print Nicely green 'Done ' except debug option print Nicely light magenta "I'm sorry you can not unsubscribe to this list " | 11752 | def list_unsubscribe(t):
(owner, slug) = get_slug()
try:
t.lists.subscribers.destroy(slug=slug, owner_screen_name=owner)
printNicely(green('Done.'))
except:
debug_option()
printNicely(light_magenta("I'm sorry you can not unsubscribe to this list."))
| Unsubscribe a list | unsubscribe a list | Question:
What does this function do?
Code:
def list_unsubscribe(t):
(owner, slug) = get_slug()
try:
t.lists.subscribers.destroy(slug=slug, owner_screen_name=owner)
printNicely(green('Done.'))
except:
debug_option()
printNicely(light_magenta("I'm sorry you can not unsubscribe to this list."))
|
null | null | null | What does this function do? | @click.command('download-translations')
def download_translations():
from bench.utils import download_translations_p
download_translations_p()
| null | null | null | Download latest translations | pcsd | @click command 'download-translations' def download translations from bench utils import download translations p download translations p | 11758 | @click.command('download-translations')
def download_translations():
from bench.utils import download_translations_p
download_translations_p()
| Download latest translations | download latest translations | Question:
What does this function do?
Code:
@click.command('download-translations')
def download_translations():
from bench.utils import download_translations_p
download_translations_p()
|
null | null | null | What does this function do? | def api_wrapper(func):
@wraps(func)
def __wrapper(*args, **kwargs):
module = args[0]
try:
return func(*args, **kwargs)
except core.exceptions.APICommandException as e:
module.fail_json(msg=e.message)
except core.exceptions.SystemNotFoundException as e:
module.fail_json(msg=e.message)
except:
rai... | null | null | null | Catch API Errors Decorator | pcsd | def api wrapper func @wraps func def wrapper *args **kwargs module = args[0] try return func *args **kwargs except core exceptions API Command Exception as e module fail json msg=e message except core exceptions System Not Found Exception as e module fail json msg=e message except raise return wrapper | 11762 | def api_wrapper(func):
@wraps(func)
def __wrapper(*args, **kwargs):
module = args[0]
try:
return func(*args, **kwargs)
except core.exceptions.APICommandException as e:
module.fail_json(msg=e.message)
except core.exceptions.SystemNotFoundException as e:
module.fail_json(msg=e.message)
except:
rai... | Catch API Errors Decorator | catch api errors decorator | Question:
What does this function do?
Code:
def api_wrapper(func):
@wraps(func)
def __wrapper(*args, **kwargs):
module = args[0]
try:
return func(*args, **kwargs)
except core.exceptions.APICommandException as e:
module.fail_json(msg=e.message)
except core.exceptions.SystemNotFoundException as e:
m... |
null | null | null | What does this function do? | def bytes(phenny, input):
b = input.bytes
phenny.reply(('%r' % b[(b.find(' ') + 1):]))
| null | null | null | Show the input as pretty printed bytes. | pcsd | def bytes phenny input b = input bytes phenny reply '%r' % b[ b find ' ' + 1 ] | 11768 | def bytes(phenny, input):
b = input.bytes
phenny.reply(('%r' % b[(b.find(' ') + 1):]))
| Show the input as pretty printed bytes. | show the input as pretty printed bytes . | Question:
What does this function do?
Code:
def bytes(phenny, input):
b = input.bytes
phenny.reply(('%r' % b[(b.find(' ') + 1):]))
|
null | null | null | What does this function do? | def disconnect_all(signal=Any, sender=Any):
for receiver in liveReceivers(getAllReceivers(sender, signal)):
disconnect(receiver, signal=signal, sender=sender)
| null | null | null | Disconnect all signal handlers. Useful for cleaning up after running
tests | pcsd | def disconnect all signal=Any sender=Any for receiver in live Receivers get All Receivers sender signal disconnect receiver signal=signal sender=sender | 11771 | def disconnect_all(signal=Any, sender=Any):
for receiver in liveReceivers(getAllReceivers(sender, signal)):
disconnect(receiver, signal=signal, sender=sender)
| Disconnect all signal handlers. Useful for cleaning up after running
tests | disconnect all signal handlers . | Question:
What does this function do?
Code:
def disconnect_all(signal=Any, sender=Any):
for receiver in liveReceivers(getAllReceivers(sender, signal)):
disconnect(receiver, signal=signal, sender=sender)
|
null | null | null | What does this function do? | def instantiateShootCallback():
d = defer.Deferred()
d.callback(1)
| null | null | null | Create a deferred and give it a normal result | pcsd | def instantiate Shoot Callback d = defer Deferred d callback 1 | 11774 | def instantiateShootCallback():
d = defer.Deferred()
d.callback(1)
| Create a deferred and give it a normal result | create a deferred and give it a normal result | Question:
What does this function do?
Code:
def instantiateShootCallback():
d = defer.Deferred()
d.callback(1)
|
null | null | null | What does this function do? | def stubout_attach_disks(stubs):
def f(*args):
raise XenAPI.Failure('Test Exception raised by fake _attach_disks')
stubs.Set(vmops.VMOps, '_attach_disks', f)
| null | null | null | Simulates a failure in _attach_disks. | pcsd | def stubout attach disks stubs def f *args raise Xen API Failure 'Test Exception raised by fake attach disks' stubs Set vmops VM Ops ' attach disks' f | 11775 | def stubout_attach_disks(stubs):
def f(*args):
raise XenAPI.Failure('Test Exception raised by fake _attach_disks')
stubs.Set(vmops.VMOps, '_attach_disks', f)
| Simulates a failure in _attach_disks. | simulates a failure in _ attach _ disks . | Question:
What does this function do?
Code:
def stubout_attach_disks(stubs):
def f(*args):
raise XenAPI.Failure('Test Exception raised by fake _attach_disks')
stubs.Set(vmops.VMOps, '_attach_disks', f)
|
null | null | null | What does this function do? | def get_scheduler_lock(get=None, collection=None):
actual_get = effective_get(get, collection)
if (actual_get == multiprocessing.get):
return mp.Manager().Lock()
return SerializableLock()
| null | null | null | Get an instance of the appropriate lock for a certain situation based on
scheduler used. | pcsd | def get scheduler lock get=None collection=None actual get = effective get get collection if actual get == multiprocessing get return mp Manager Lock return Serializable Lock | 11776 | def get_scheduler_lock(get=None, collection=None):
actual_get = effective_get(get, collection)
if (actual_get == multiprocessing.get):
return mp.Manager().Lock()
return SerializableLock()
| Get an instance of the appropriate lock for a certain situation based on
scheduler used. | get an instance of the appropriate lock for a certain situation based on scheduler used . | Question:
What does this function do?
Code:
def get_scheduler_lock(get=None, collection=None):
actual_get = effective_get(get, collection)
if (actual_get == multiprocessing.get):
return mp.Manager().Lock()
return SerializableLock()
|
null | null | null | What does this function do? | def build_queue_header(prim, webdir='', search=None, start=0, limit=0):
header = build_header(prim, webdir)
bytespersec = BPSMeter.do.get_bps()
qnfo = NzbQueue.do.queue_info(search=search, start=start, limit=limit)
bytesleft = qnfo.bytes_left
bytes = qnfo.bytes
header['kbpersec'] = ('%.2f' % (bytespersec / KIBI))... | null | null | null | Build full queue header | pcsd | def build queue header prim webdir='' search=None start=0 limit=0 header = build header prim webdir bytespersec = BPS Meter do get bps qnfo = Nzb Queue do queue info search=search start=start limit=limit bytesleft = qnfo bytes left bytes = qnfo bytes header['kbpersec'] = '% 2f' % bytespersec / KIBI header['speed'] = to... | 11782 | def build_queue_header(prim, webdir='', search=None, start=0, limit=0):
header = build_header(prim, webdir)
bytespersec = BPSMeter.do.get_bps()
qnfo = NzbQueue.do.queue_info(search=search, start=start, limit=limit)
bytesleft = qnfo.bytes_left
bytes = qnfo.bytes
header['kbpersec'] = ('%.2f' % (bytespersec / KIBI))... | Build full queue header | build full queue header | Question:
What does this function do?
Code:
def build_queue_header(prim, webdir='', search=None, start=0, limit=0):
header = build_header(prim, webdir)
bytespersec = BPSMeter.do.get_bps()
qnfo = NzbQueue.do.queue_info(search=search, start=start, limit=limit)
bytesleft = qnfo.bytes_left
bytes = qnfo.bytes
heade... |
null | null | null | What does this function do? | def entry_choices(user, page):
for entry in wizard_pool.get_entries():
if entry.user_has_add_permission(user, page=page):
(yield (entry.id, entry.title))
| null | null | null | Yields a list of wizard entries that the current user can use based on their
permission to add instances of the underlying model objects. | pcsd | def entry choices user page for entry in wizard pool get entries if entry user has add permission user page=page yield entry id entry title | 11786 | def entry_choices(user, page):
for entry in wizard_pool.get_entries():
if entry.user_has_add_permission(user, page=page):
(yield (entry.id, entry.title))
| Yields a list of wizard entries that the current user can use based on their
permission to add instances of the underlying model objects. | yields a list of wizard entries that the current user can use based on their permission to add instances of the underlying model objects . | Question:
What does this function do?
Code:
def entry_choices(user, page):
for entry in wizard_pool.get_entries():
if entry.user_has_add_permission(user, page=page):
(yield (entry.id, entry.title))
|
null | null | null | What does this function do? | @register.inclusion_tag('addons/tags_box.html')
@jinja2.contextfunction
def tags_box(context, addon, tags=None):
c = dict(context.items())
c.update({'addon': addon, 'tags': tags})
return c
| null | null | null | Details page: Show a box with existing tags along with a form to add new
ones. | pcsd | @register inclusion tag 'addons/tags box html' @jinja2 contextfunction def tags box context addon tags=None c = dict context items c update {'addon' addon 'tags' tags} return c | 11790 | @register.inclusion_tag('addons/tags_box.html')
@jinja2.contextfunction
def tags_box(context, addon, tags=None):
c = dict(context.items())
c.update({'addon': addon, 'tags': tags})
return c
| Details page: Show a box with existing tags along with a form to add new
ones. | details page : show a box with existing tags along with a form to add new ones . | Question:
What does this function do?
Code:
@register.inclusion_tag('addons/tags_box.html')
@jinja2.contextfunction
def tags_box(context, addon, tags=None):
c = dict(context.items())
c.update({'addon': addon, 'tags': tags})
return c
|
null | null | null | What does this function do? | def vulnerability_callback(id, type, server_addr, server_port, applications):
logger.critical(('Vulnerability %s in connection %s to %s:%s by %s' % (type, id, server_addr, server_port, ', '.join((('%s version %s' % (app.application, app.version)) for app in applications)))))
| null | null | null | Called when a vulnerability is reported | pcsd | def vulnerability callback id type server addr server port applications logger critical 'Vulnerability %s in connection %s to %s %s by %s' % type id server addr server port ' ' join '%s version %s' % app application app version for app in applications | 11797 | def vulnerability_callback(id, type, server_addr, server_port, applications):
logger.critical(('Vulnerability %s in connection %s to %s:%s by %s' % (type, id, server_addr, server_port, ', '.join((('%s version %s' % (app.application, app.version)) for app in applications)))))
| Called when a vulnerability is reported | called when a vulnerability is reported | Question:
What does this function do?
Code:
def vulnerability_callback(id, type, server_addr, server_port, applications):
logger.critical(('Vulnerability %s in connection %s to %s:%s by %s' % (type, id, server_addr, server_port, ', '.join((('%s version %s' % (app.application, app.version)) for app in applications))... |
null | null | null | What does this function do? | def stripNameSpace(xml):
r = re.compile('^(<?[^>]+?>\\s*)(<\\w+) xmlns=[\'"](http://[^\'"]+)[\'"](.*)', re.MULTILINE)
if r.match(xml):
xmlns = r.match(xml).groups()[2]
xml = r.sub('\\1\\2\\4', xml)
else:
xmlns = None
return (xml, xmlns)
| null | null | null | removeNameSpace(xml) -- remove top-level AWS namespace | pcsd | def strip Name Space xml r = re compile '^ <?[^>]+?>\\s* <\\w+ xmlns=[\'"] http //[^\'"]+ [\'"] * ' re MULTILINE if r match xml xmlns = r match xml groups [2] xml = r sub '\\1\\2\\4' xml else xmlns = None return xml xmlns | 11800 | def stripNameSpace(xml):
r = re.compile('^(<?[^>]+?>\\s*)(<\\w+) xmlns=[\'"](http://[^\'"]+)[\'"](.*)', re.MULTILINE)
if r.match(xml):
xmlns = r.match(xml).groups()[2]
xml = r.sub('\\1\\2\\4', xml)
else:
xmlns = None
return (xml, xmlns)
| removeNameSpace(xml) -- remove top-level AWS namespace | removenamespace - - remove top - level aws namespace | Question:
What does this function do?
Code:
def stripNameSpace(xml):
r = re.compile('^(<?[^>]+?>\\s*)(<\\w+) xmlns=[\'"](http://[^\'"]+)[\'"](.*)', re.MULTILINE)
if r.match(xml):
xmlns = r.match(xml).groups()[2]
xml = r.sub('\\1\\2\\4', xml)
else:
xmlns = None
return (xml, xmlns)
|
null | null | null | What does this function do? | def eval_sort(sorttype, expression, name=None, multipart=''):
from sabnzbd.api import Ttemplate
path = ''
name = sanitize_foldername(name)
if (sorttype == 'series'):
name = (name or ('%s S01E05 - %s [DTS]' % (Ttemplate('show-name'), Ttemplate('ep-name'))))
sorter = sabnzbd.tvsort.SeriesSorter(None, name, path, ... | null | null | null | Preview a sort expression, to be used by API | pcsd | def eval sort sorttype expression name=None multipart='' from sabnzbd api import Ttemplate path = '' name = sanitize foldername name if sorttype == 'series' name = name or '%s S01E05 - %s [DTS]' % Ttemplate 'show-name' Ttemplate 'ep-name' sorter = sabnzbd tvsort Series Sorter None name path 'tv' elif sorttype == 'gener... | 11802 | def eval_sort(sorttype, expression, name=None, multipart=''):
from sabnzbd.api import Ttemplate
path = ''
name = sanitize_foldername(name)
if (sorttype == 'series'):
name = (name or ('%s S01E05 - %s [DTS]' % (Ttemplate('show-name'), Ttemplate('ep-name'))))
sorter = sabnzbd.tvsort.SeriesSorter(None, name, path, ... | Preview a sort expression, to be used by API | preview a sort expression , to be used by api | Question:
What does this function do?
Code:
def eval_sort(sorttype, expression, name=None, multipart=''):
from sabnzbd.api import Ttemplate
path = ''
name = sanitize_foldername(name)
if (sorttype == 'series'):
name = (name or ('%s S01E05 - %s [DTS]' % (Ttemplate('show-name'), Ttemplate('ep-name'))))
sorter =... |
null | null | null | What does this function do? | def calculated_hp(base_stat, level, iv, effort, nature=None):
if (base_stat == 1):
return 1
return (((((((base_stat * 2) + iv) + (effort // 4)) * level) // 100) + 10) + level)
| null | null | null | Similar to `calculated_stat`, except with a slightly different formula
used specifically for HP. | pcsd | def calculated hp base stat level iv effort nature=None if base stat == 1 return 1 return base stat * 2 + iv + effort // 4 * level // 100 + 10 + level | 11811 | def calculated_hp(base_stat, level, iv, effort, nature=None):
if (base_stat == 1):
return 1
return (((((((base_stat * 2) + iv) + (effort // 4)) * level) // 100) + 10) + level)
| Similar to `calculated_stat`, except with a slightly different formula
used specifically for HP. | similar to calculated _ stat , except with a slightly different formula used specifically for hp . | Question:
What does this function do?
Code:
def calculated_hp(base_stat, level, iv, effort, nature=None):
if (base_stat == 1):
return 1
return (((((((base_stat * 2) + iv) + (effort // 4)) * level) // 100) + 10) + level)
|
null | null | null | What does this function do? | def p_enumerator_list_2(t):
pass
| null | null | null | enumerator_list : enumerator_list COMMA enumerator | pcsd | def p enumerator list 2 t pass | 11816 | def p_enumerator_list_2(t):
pass
| enumerator_list : enumerator_list COMMA enumerator | enumerator _ list : enumerator _ list comma enumerator | Question:
What does this function do?
Code:
def p_enumerator_list_2(t):
pass
|
null | null | null | What does this function do? | def withparent(meth):
def wrapped(self, *args, **kwargs):
res = meth(self, *args, **kwargs)
if (getattr(self, 'parent', None) is not None):
getattr(self.parent, meth.__name__)(*args, **kwargs)
return res
wrapped.__name__ = meth.__name__
return wrapped
| null | null | null | Helper wrapper that passes calls to parent\'s instance | pcsd | def withparent meth def wrapped self *args **kwargs res = meth self *args **kwargs if getattr self 'parent' None is not None getattr self parent meth name *args **kwargs return res wrapped name = meth name return wrapped | 11829 | def withparent(meth):
def wrapped(self, *args, **kwargs):
res = meth(self, *args, **kwargs)
if (getattr(self, 'parent', None) is not None):
getattr(self.parent, meth.__name__)(*args, **kwargs)
return res
wrapped.__name__ = meth.__name__
return wrapped
| Helper wrapper that passes calls to parent\'s instance | helper wrapper that passes calls to parents instance | Question:
What does this function do?
Code:
def withparent(meth):
def wrapped(self, *args, **kwargs):
res = meth(self, *args, **kwargs)
if (getattr(self, 'parent', None) is not None):
getattr(self.parent, meth.__name__)(*args, **kwargs)
return res
wrapped.__name__ = meth.__name__
return wrapped
|
null | null | null | What does this function do? | def assert_array_identical(a, b):
assert_array_equal(a, b)
assert_equal(a.dtype.type, b.dtype.type)
| null | null | null | Assert whether values AND type are the same | pcsd | def assert array identical a b assert array equal a b assert equal a dtype type b dtype type | 11839 | def assert_array_identical(a, b):
assert_array_equal(a, b)
assert_equal(a.dtype.type, b.dtype.type)
| Assert whether values AND type are the same | assert whether values and type are the same | Question:
What does this function do?
Code:
def assert_array_identical(a, b):
assert_array_equal(a, b)
assert_equal(a.dtype.type, b.dtype.type)
|
null | null | null | What does this function do? | def cleanpath(path):
items = path.split('.')
if (len(items) > 1):
path = re.sub('[^\\w\\.]+', '_', (('_'.join(items[:(-1)]) + '.') + ''.join(items[(-1):])))
else:
path = re.sub('[^\\w\\.]+', '_', ''.join(items[(-1):]))
return path
| null | null | null | Turns any expression/path into a valid filename. replaces / with _ and
removes special characters. | pcsd | def cleanpath path items = path split ' ' if len items > 1 path = re sub '[^\\w\\ ]+' ' ' ' ' join items[ -1 ] + ' ' + '' join items[ -1 ] else path = re sub '[^\\w\\ ]+' ' ' '' join items[ -1 ] return path | 11854 | def cleanpath(path):
items = path.split('.')
if (len(items) > 1):
path = re.sub('[^\\w\\.]+', '_', (('_'.join(items[:(-1)]) + '.') + ''.join(items[(-1):])))
else:
path = re.sub('[^\\w\\.]+', '_', ''.join(items[(-1):]))
return path
| Turns any expression/path into a valid filename. replaces / with _ and
removes special characters. | turns any expression / path into a valid filename . | Question:
What does this function do?
Code:
def cleanpath(path):
items = path.split('.')
if (len(items) > 1):
path = re.sub('[^\\w\\.]+', '_', (('_'.join(items[:(-1)]) + '.') + ''.join(items[(-1):])))
else:
path = re.sub('[^\\w\\.]+', '_', ''.join(items[(-1):]))
return path
|
null | null | null | What does this function do? | def reverse_bisect_left(a, x, lo=0, hi=None):
if (lo < 0):
raise ValueError('lo must be non-negative')
if (hi is None):
hi = len(a)
while (lo < hi):
mid = ((lo + hi) // 2)
if (x > a[mid]):
hi = mid
else:
lo = (mid + 1)
return lo
| null | null | null | same as python bisect.bisect_left but for
lists with reversed order | pcsd | def reverse bisect left a x lo=0 hi=None if lo < 0 raise Value Error 'lo must be non-negative' if hi is None hi = len a while lo < hi mid = lo + hi // 2 if x > a[mid] hi = mid else lo = mid + 1 return lo | 11876 | def reverse_bisect_left(a, x, lo=0, hi=None):
if (lo < 0):
raise ValueError('lo must be non-negative')
if (hi is None):
hi = len(a)
while (lo < hi):
mid = ((lo + hi) // 2)
if (x > a[mid]):
hi = mid
else:
lo = (mid + 1)
return lo
| same as python bisect.bisect_left but for
lists with reversed order | same as python bisect . bisect _ left but for lists with reversed order | Question:
What does this function do?
Code:
def reverse_bisect_left(a, x, lo=0, hi=None):
if (lo < 0):
raise ValueError('lo must be non-negative')
if (hi is None):
hi = len(a)
while (lo < hi):
mid = ((lo + hi) // 2)
if (x > a[mid]):
hi = mid
else:
lo = (mid + 1)
return lo
|
null | null | null | What does this function do? | def get_installed_categories(shop):
return (configuration.get(shop, SAMPLE_CATEGORIES_KEY) or [])
| null | null | null | Returns the installed categories samples list | pcsd | def get installed categories shop return configuration get shop SAMPLE CATEGORIES KEY or [] | 11883 | def get_installed_categories(shop):
return (configuration.get(shop, SAMPLE_CATEGORIES_KEY) or [])
| Returns the installed categories samples list | returns the installed categories samples list | Question:
What does this function do?
Code:
def get_installed_categories(shop):
return (configuration.get(shop, SAMPLE_CATEGORIES_KEY) or [])
|
null | null | null | What does this function do? | def debugger():
rdb = _current[0]
if ((rdb is None) or (not rdb.active)):
rdb = _current[0] = Rdb()
return rdb
| null | null | null | Return the current debugger instance, or create if none. | pcsd | def debugger rdb = current[0] if rdb is None or not rdb active rdb = current[0] = Rdb return rdb | 11886 | def debugger():
rdb = _current[0]
if ((rdb is None) or (not rdb.active)):
rdb = _current[0] = Rdb()
return rdb
| Return the current debugger instance, or create if none. | return the current debugger instance , or create if none . | Question:
What does this function do?
Code:
def debugger():
rdb = _current[0]
if ((rdb is None) or (not rdb.active)):
rdb = _current[0] = Rdb()
return rdb
|
null | null | null | What does this function do? | def make_variant_item_code(template_item_code, variant):
if variant.item_code:
return
abbreviations = []
for attr in variant.attributes:
item_attribute = frappe.db.sql(u'select i.numeric_values, v.abbr\n DCTB DCTB DCTB from `tabItem Attribute` i left join `tabItem Attribute Value` v\n DCTB DCTB DCTB DCTB on... | null | null | null | Uses template\'s item code and abbreviations to make variant\'s item code | pcsd | def make variant item code template item code variant if variant item code return abbreviations = [] for attr in variant attributes item attribute = frappe db sql u'select i numeric values v abbr DCTB DCTB DCTB from `tab Item Attribute` i left join `tab Item Attribute Value` v DCTB DCTB DCTB DCTB on i name=v parent DCT... | 11890 | def make_variant_item_code(template_item_code, variant):
if variant.item_code:
return
abbreviations = []
for attr in variant.attributes:
item_attribute = frappe.db.sql(u'select i.numeric_values, v.abbr\n DCTB DCTB DCTB from `tabItem Attribute` i left join `tabItem Attribute Value` v\n DCTB DCTB DCTB DCTB on... | Uses template\'s item code and abbreviations to make variant\'s item code | uses templates item code and abbreviations to make variants item code | Question:
What does this function do?
Code:
def make_variant_item_code(template_item_code, variant):
if variant.item_code:
return
abbreviations = []
for attr in variant.attributes:
item_attribute = frappe.db.sql(u'select i.numeric_values, v.abbr\n DCTB DCTB DCTB from `tabItem Attribute` i left join `tabItem... |
null | null | null | What does this function do? | def _get_branch(repo, name):
try:
return [x for x in _all_branches(repo) if (x[0] == name)][0]
except IndexError:
return False
| null | null | null | Find the requested branch in the specified repo | pcsd | def get branch repo name try return [x for x in all branches repo if x[0] == name ][0] except Index Error return False | 11894 | def _get_branch(repo, name):
try:
return [x for x in _all_branches(repo) if (x[0] == name)][0]
except IndexError:
return False
| Find the requested branch in the specified repo | find the requested branch in the specified repo | Question:
What does this function do?
Code:
def _get_branch(repo, name):
try:
return [x for x in _all_branches(repo) if (x[0] == name)][0]
except IndexError:
return False
|
null | null | null | What does this function do? | def path_to_uri(path, scheme=Extension.ext_name):
assert isinstance(path, bytes), u'Mopidy paths should be bytes'
uripath = quote_from_bytes(os.path.normpath(path))
return urlunsplit((scheme, None, uripath, None, None))
| null | null | null | Convert file path to URI. | pcsd | def path to uri path scheme=Extension ext name assert isinstance path bytes u'Mopidy paths should be bytes' uripath = quote from bytes os path normpath path return urlunsplit scheme None uripath None None | 11897 | def path_to_uri(path, scheme=Extension.ext_name):
assert isinstance(path, bytes), u'Mopidy paths should be bytes'
uripath = quote_from_bytes(os.path.normpath(path))
return urlunsplit((scheme, None, uripath, None, None))
| Convert file path to URI. | convert file path to uri . | Question:
What does this function do?
Code:
def path_to_uri(path, scheme=Extension.ext_name):
assert isinstance(path, bytes), u'Mopidy paths should be bytes'
uripath = quote_from_bytes(os.path.normpath(path))
return urlunsplit((scheme, None, uripath, None, None))
|
null | null | null | What does this function do? | @pytest.mark.network
def test_upgrade_from_reqs_file(script):
script.scratch_path.join('test-req.txt').write(textwrap.dedent(' PyLogo<0.4\n # and something else to test out:\n INITools==0.3\n '))
install_result = script.pip('install', '-r', (script.scratch_path / 'test-req.txt'))
script.s... | null | null | null | Upgrade from a requirements file. | pcsd | @pytest mark network def test upgrade from reqs file script script scratch path join 'test-req txt' write textwrap dedent ' Py Logo<0 4 # and something else to test out INI Tools==0 3 ' install result = script pip 'install' '-r' script scratch path / 'test-req txt' script scratch path join 'test-req txt' write textwrap... | 11902 | @pytest.mark.network
def test_upgrade_from_reqs_file(script):
script.scratch_path.join('test-req.txt').write(textwrap.dedent(' PyLogo<0.4\n # and something else to test out:\n INITools==0.3\n '))
install_result = script.pip('install', '-r', (script.scratch_path / 'test-req.txt'))
script.s... | Upgrade from a requirements file. | upgrade from a requirements file . | Question:
What does this function do?
Code:
@pytest.mark.network
def test_upgrade_from_reqs_file(script):
script.scratch_path.join('test-req.txt').write(textwrap.dedent(' PyLogo<0.4\n # and something else to test out:\n INITools==0.3\n '))
install_result = script.pip('install', '-r', (s... |
null | null | null | What does this function do? | def _factor_indexer(shape, labels):
mult = np.array(shape)[::(-1)].cumprod()[::(-1)]
return _ensure_platform_int(np.sum((np.array(labels).T * np.append(mult, [1])), axis=1).T)
| null | null | null | given a tuple of shape and a list of Categorical labels, return the
expanded label indexer | pcsd | def factor indexer shape labels mult = np array shape [ -1 ] cumprod [ -1 ] return ensure platform int np sum np array labels T * np append mult [1] axis=1 T | 11905 | def _factor_indexer(shape, labels):
mult = np.array(shape)[::(-1)].cumprod()[::(-1)]
return _ensure_platform_int(np.sum((np.array(labels).T * np.append(mult, [1])), axis=1).T)
| given a tuple of shape and a list of Categorical labels, return the
expanded label indexer | given a tuple of shape and a list of categorical labels , return the expanded label indexer | Question:
What does this function do?
Code:
def _factor_indexer(shape, labels):
mult = np.array(shape)[::(-1)].cumprod()[::(-1)]
return _ensure_platform_int(np.sum((np.array(labels).T * np.append(mult, [1])), axis=1).T)
|
null | null | null | What does this function do? | def addPillarFromConvexLoopsGridTop(faces, indexedGridTop, indexedLoops):
addFacesByLoopReversed(faces, indexedLoops[0])
addFacesByConvexLoops(faces, indexedLoops)
addFacesByGrid(faces, indexedGridTop)
| null | null | null | Add pillar from convex loops and grid top. | pcsd | def add Pillar From Convex Loops Grid Top faces indexed Grid Top indexed Loops add Faces By Loop Reversed faces indexed Loops[0] add Faces By Convex Loops faces indexed Loops add Faces By Grid faces indexed Grid Top | 11917 | def addPillarFromConvexLoopsGridTop(faces, indexedGridTop, indexedLoops):
addFacesByLoopReversed(faces, indexedLoops[0])
addFacesByConvexLoops(faces, indexedLoops)
addFacesByGrid(faces, indexedGridTop)
| Add pillar from convex loops and grid top. | add pillar from convex loops and grid top . | Question:
What does this function do?
Code:
def addPillarFromConvexLoopsGridTop(faces, indexedGridTop, indexedLoops):
addFacesByLoopReversed(faces, indexedLoops[0])
addFacesByConvexLoops(faces, indexedLoops)
addFacesByGrid(faces, indexedGridTop)
|
null | null | null | What does this function do? | def volume_glance_metadata_bulk_create(context, volume_id, metadata):
return IMPL.volume_glance_metadata_bulk_create(context, volume_id, metadata)
| null | null | null | Add Glance metadata for specified volume (multiple pairs). | pcsd | def volume glance metadata bulk create context volume id metadata return IMPL volume glance metadata bulk create context volume id metadata | 11923 | def volume_glance_metadata_bulk_create(context, volume_id, metadata):
return IMPL.volume_glance_metadata_bulk_create(context, volume_id, metadata)
| Add Glance metadata for specified volume (multiple pairs). | add glance metadata for specified volume . | Question:
What does this function do?
Code:
def volume_glance_metadata_bulk_create(context, volume_id, metadata):
return IMPL.volume_glance_metadata_bulk_create(context, volume_id, metadata)
|
null | null | null | What does this function do? | def minimax(val, default, low, high):
val = to_int(val, default=default)
if (val < low):
return low
if (val > high):
return high
return val
| null | null | null | Return value forced within range | pcsd | def minimax val default low high val = to int val default=default if val < low return low if val > high return high return val | 11926 | def minimax(val, default, low, high):
val = to_int(val, default=default)
if (val < low):
return low
if (val > high):
return high
return val
| Return value forced within range | return value forced within range | Question:
What does this function do?
Code:
def minimax(val, default, low, high):
val = to_int(val, default=default)
if (val < low):
return low
if (val > high):
return high
return val
|
null | null | null | What does this function do? | def delayed_import():
global _ServerSession, _PlayerDB, _ServerConfig, _ScriptDB
if (not _ServerSession):
(modulename, classname) = settings.SERVER_SESSION_CLASS.rsplit('.', 1)
_ServerSession = variable_from_module(modulename, classname)
if (not _PlayerDB):
from evennia.players.models import PlayerDB as _Playe... | null | null | null | Helper method for delayed import of all needed entities. | pcsd | def delayed import global Server Session Player DB Server Config Script DB if not Server Session modulename classname = settings SERVER SESSION CLASS rsplit ' ' 1 Server Session = variable from module modulename classname if not Player DB from evennia players models import Player DB as Player DB if not Server Config fr... | 11928 | def delayed_import():
global _ServerSession, _PlayerDB, _ServerConfig, _ScriptDB
if (not _ServerSession):
(modulename, classname) = settings.SERVER_SESSION_CLASS.rsplit('.', 1)
_ServerSession = variable_from_module(modulename, classname)
if (not _PlayerDB):
from evennia.players.models import PlayerDB as _Playe... | Helper method for delayed import of all needed entities. | helper method for delayed import of all needed entities . | Question:
What does this function do?
Code:
def delayed_import():
global _ServerSession, _PlayerDB, _ServerConfig, _ScriptDB
if (not _ServerSession):
(modulename, classname) = settings.SERVER_SESSION_CLASS.rsplit('.', 1)
_ServerSession = variable_from_module(modulename, classname)
if (not _PlayerDB):
from e... |
null | null | null | What does this function do? | @contextmanager
def patched_input(code):
def lines():
for line in code.splitlines():
(yield line)
raise EOFError()
def patch_raw_input(lines=lines()):
return next(lines)
try:
raw_input = yapf.py3compat.raw_input
yapf.py3compat.raw_input = patch_raw_input
(yield)
finally:
yapf.py3compat.raw_input = ... | null | null | null | Monkey patch code as though it were coming from stdin. | pcsd | @contextmanager def patched input code def lines for line in code splitlines yield line raise EOF Error def patch raw input lines=lines return next lines try raw input = yapf py3compat raw input yapf py3compat raw input = patch raw input yield finally yapf py3compat raw input = raw input | 11932 | @contextmanager
def patched_input(code):
def lines():
for line in code.splitlines():
(yield line)
raise EOFError()
def patch_raw_input(lines=lines()):
return next(lines)
try:
raw_input = yapf.py3compat.raw_input
yapf.py3compat.raw_input = patch_raw_input
(yield)
finally:
yapf.py3compat.raw_input = ... | Monkey patch code as though it were coming from stdin. | monkey patch code as though it were coming from stdin . | Question:
What does this function do?
Code:
@contextmanager
def patched_input(code):
def lines():
for line in code.splitlines():
(yield line)
raise EOFError()
def patch_raw_input(lines=lines()):
return next(lines)
try:
raw_input = yapf.py3compat.raw_input
yapf.py3compat.raw_input = patch_raw_input
... |
null | null | null | What does this function do? | def iter_slices(string, slice_length):
pos = 0
if ((slice_length is None) or (slice_length <= 0)):
slice_length = len(string)
while (pos < len(string)):
(yield string[pos:(pos + slice_length)])
pos += slice_length
| null | null | null | Iterate over slices of a string. | pcsd | def iter slices string slice length pos = 0 if slice length is None or slice length <= 0 slice length = len string while pos < len string yield string[pos pos + slice length ] pos += slice length | 11937 | def iter_slices(string, slice_length):
pos = 0
if ((slice_length is None) or (slice_length <= 0)):
slice_length = len(string)
while (pos < len(string)):
(yield string[pos:(pos + slice_length)])
pos += slice_length
| Iterate over slices of a string. | iterate over slices of a string . | Question:
What does this function do?
Code:
def iter_slices(string, slice_length):
pos = 0
if ((slice_length is None) or (slice_length <= 0)):
slice_length = len(string)
while (pos < len(string)):
(yield string[pos:(pos + slice_length)])
pos += slice_length
|
null | null | null | What does this function do? | def update_node_links(designated_node, target_node_ids, description):
logger.info('Repopulating {} with latest {} nodes.'.format(designated_node._id, description))
user = designated_node.creator
auth = Auth(user)
for pointer in designated_node.nodes_pointer:
designated_node.rm_pointer(pointer, auth)
for n_id in ... | null | null | null | Takes designated node, removes current node links and replaces them with node links to target nodes | pcsd | def update node links designated node target node ids description logger info 'Repopulating {} with latest {} nodes ' format designated node id description user = designated node creator auth = Auth user for pointer in designated node nodes pointer designated node rm pointer pointer auth for n id in target node ids n =... | 11946 | def update_node_links(designated_node, target_node_ids, description):
logger.info('Repopulating {} with latest {} nodes.'.format(designated_node._id, description))
user = designated_node.creator
auth = Auth(user)
for pointer in designated_node.nodes_pointer:
designated_node.rm_pointer(pointer, auth)
for n_id in ... | Takes designated node, removes current node links and replaces them with node links to target nodes | takes designated node , removes current node links and replaces them with node links to target nodes | Question:
What does this function do?
Code:
def update_node_links(designated_node, target_node_ids, description):
logger.info('Repopulating {} with latest {} nodes.'.format(designated_node._id, description))
user = designated_node.creator
auth = Auth(user)
for pointer in designated_node.nodes_pointer:
designat... |
null | null | null | What does this function do? | def get_masquerade_role(user, course_key):
course_masquerade = get_course_masquerade(user, course_key)
return (course_masquerade.role if course_masquerade else None)
| null | null | null | Returns the role that the user is masquerading as, or None if no masquerade is in effect. | pcsd | def get masquerade role user course key course masquerade = get course masquerade user course key return course masquerade role if course masquerade else None | 11953 | def get_masquerade_role(user, course_key):
course_masquerade = get_course_masquerade(user, course_key)
return (course_masquerade.role if course_masquerade else None)
| Returns the role that the user is masquerading as, or None if no masquerade is in effect. | returns the role that the user is masquerading as , or none if no masquerade is in effect . | Question:
What does this function do?
Code:
def get_masquerade_role(user, course_key):
course_masquerade = get_course_masquerade(user, course_key)
return (course_masquerade.role if course_masquerade else None)
|
null | null | null | What does this function do? | def supply_item_entity_status(row):
if hasattr(row, 'supply_item_entity'):
row = row.supply_item_entity
else:
return None
db = current.db
s3db = current.s3db
etable = s3db.supply_item_entity
ekey = etable._id.name
try:
instance_type = row.instance_type
except AttributeError:
return None
try:
entity_i... | null | null | null | Virtual field: status | pcsd | def supply item entity status row if hasattr row 'supply item entity' row = row supply item entity else return None db = current db s3db = current s3db etable = s3db supply item entity ekey = etable id name try instance type = row instance type except Attribute Error return None try entity id = row[ekey] except Attribu... | 11955 | def supply_item_entity_status(row):
if hasattr(row, 'supply_item_entity'):
row = row.supply_item_entity
else:
return None
db = current.db
s3db = current.s3db
etable = s3db.supply_item_entity
ekey = etable._id.name
try:
instance_type = row.instance_type
except AttributeError:
return None
try:
entity_i... | Virtual field: status | virtual field : status | Question:
What does this function do?
Code:
def supply_item_entity_status(row):
if hasattr(row, 'supply_item_entity'):
row = row.supply_item_entity
else:
return None
db = current.db
s3db = current.s3db
etable = s3db.supply_item_entity
ekey = etable._id.name
try:
instance_type = row.instance_type
except... |
null | null | null | What does this function do? | def validate_bool(b):
if (type(b) is str):
b = b.lower()
if (b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True)):
return True
elif (b in ('f', 'n', 'no', 'off', 'false', '0', 0, False)):
return False
else:
raise ValueError(('Could not convert "%s" to boolean' % b))
| null | null | null | Convert b to a boolean or raise | pcsd | def validate bool b if type b is str b = b lower if b in 't' 'y' 'yes' 'on' 'true' '1' 1 True return True elif b in 'f' 'n' 'no' 'off' 'false' '0' 0 False return False else raise Value Error 'Could not convert "%s" to boolean' % b | 11958 | def validate_bool(b):
if (type(b) is str):
b = b.lower()
if (b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True)):
return True
elif (b in ('f', 'n', 'no', 'off', 'false', '0', 0, False)):
return False
else:
raise ValueError(('Could not convert "%s" to boolean' % b))
| Convert b to a boolean or raise | convert b to a boolean or raise | Question:
What does this function do?
Code:
def validate_bool(b):
if (type(b) is str):
b = b.lower()
if (b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True)):
return True
elif (b in ('f', 'n', 'no', 'off', 'false', '0', 0, False)):
return False
else:
raise ValueError(('Could not convert "%s" to boolean' %... |
null | null | null | What does this function do? | def getTransferredSurroundingLoops(insides, loop):
transferredSurroundings = []
for insideIndex in xrange((len(insides) - 1), (-1), (-1)):
insideSurrounding = insides[insideIndex]
if isPathInsideLoop(loop, insideSurrounding.boundary):
transferredSurroundings.append(insideSurrounding)
del insides[insideIndex... | null | null | null | Get transferred paths from inside surrounding loops. | pcsd | def get Transferred Surrounding Loops insides loop transferred Surroundings = [] for inside Index in xrange len insides - 1 -1 -1 inside Surrounding = insides[inside Index] if is Path Inside Loop loop inside Surrounding boundary transferred Surroundings append inside Surrounding del insides[inside Index] return transfe... | 11959 | def getTransferredSurroundingLoops(insides, loop):
transferredSurroundings = []
for insideIndex in xrange((len(insides) - 1), (-1), (-1)):
insideSurrounding = insides[insideIndex]
if isPathInsideLoop(loop, insideSurrounding.boundary):
transferredSurroundings.append(insideSurrounding)
del insides[insideIndex... | Get transferred paths from inside surrounding loops. | get transferred paths from inside surrounding loops . | Question:
What does this function do?
Code:
def getTransferredSurroundingLoops(insides, loop):
transferredSurroundings = []
for insideIndex in xrange((len(insides) - 1), (-1), (-1)):
insideSurrounding = insides[insideIndex]
if isPathInsideLoop(loop, insideSurrounding.boundary):
transferredSurroundings.appen... |
null | null | null | What does this function do? | def get_same_name_files(files_path_list, filename):
same_name_files = []
for fname in files_path_list:
if (filename == os.path.basename(fname)):
same_name_files.append(path_components(fname))
return same_name_files
| null | null | null | Get a list of the path components of the files with the same name. | pcsd | def get same name files files path list filename same name files = [] for fname in files path list if filename == os path basename fname same name files append path components fname return same name files | 11962 | def get_same_name_files(files_path_list, filename):
same_name_files = []
for fname in files_path_list:
if (filename == os.path.basename(fname)):
same_name_files.append(path_components(fname))
return same_name_files
| Get a list of the path components of the files with the same name. | get a list of the path components of the files with the same name . | Question:
What does this function do?
Code:
def get_same_name_files(files_path_list, filename):
same_name_files = []
for fname in files_path_list:
if (filename == os.path.basename(fname)):
same_name_files.append(path_components(fname))
return same_name_files
|
null | null | null | What does this function do? | def _shorten_line_at_tokens(tokens, source, indentation, indent_word, key_token_strings, aggressive):
offsets = []
for (index, _t) in enumerate(token_offsets(tokens)):
(token_type, token_string, start_offset, end_offset) = _t
assert (token_type != token.INDENT)
if (token_string in key_token_strings):
unwante... | null | null | null | Separate line by breaking at tokens in key_token_strings.
The input is expected to be free of newlines except for inside
multiline strings and at the end. | pcsd | def shorten line at tokens tokens source indentation indent word key token strings aggressive offsets = [] for index t in enumerate token offsets tokens token type token string start offset end offset = t assert token type != token INDENT if token string in key token strings unwanted next token = {u' ' u' ' u'[' u']' u... | 11969 | def _shorten_line_at_tokens(tokens, source, indentation, indent_word, key_token_strings, aggressive):
offsets = []
for (index, _t) in enumerate(token_offsets(tokens)):
(token_type, token_string, start_offset, end_offset) = _t
assert (token_type != token.INDENT)
if (token_string in key_token_strings):
unwante... | Separate line by breaking at tokens in key_token_strings.
The input is expected to be free of newlines except for inside
multiline strings and at the end. | separate line by breaking at tokens in key _ token _ strings . | Question:
What does this function do?
Code:
def _shorten_line_at_tokens(tokens, source, indentation, indent_word, key_token_strings, aggressive):
offsets = []
for (index, _t) in enumerate(token_offsets(tokens)):
(token_type, token_string, start_offset, end_offset) = _t
assert (token_type != token.INDENT)
if ... |
null | null | null | What does this function do? | def format_group(group, show_url=True):
out = '\x02{}\x02'.format(group['name'])
if group['description']:
out += ': "{}"'.format(formatting.truncate(group['description']))
out += ' - Owned by \x02{}\x02.'.format(group['creator']['username'])
if show_url:
out += ' - {}'.format(web.try_shorten(group['permalink_ur... | null | null | null | Takes a SoundCloud group and returns a formatting string. | pcsd | def format group group show url=True out = '\x02{}\x02' format group['name'] if group['description'] out += ' "{}"' format formatting truncate group['description'] out += ' - Owned by \x02{}\x02 ' format group['creator']['username'] if show url out += ' - {}' format web try shorten group['permalink url'] return out | 11973 | def format_group(group, show_url=True):
out = '\x02{}\x02'.format(group['name'])
if group['description']:
out += ': "{}"'.format(formatting.truncate(group['description']))
out += ' - Owned by \x02{}\x02.'.format(group['creator']['username'])
if show_url:
out += ' - {}'.format(web.try_shorten(group['permalink_ur... | Takes a SoundCloud group and returns a formatting string. | takes a soundcloud group and returns a formatting string . | Question:
What does this function do?
Code:
def format_group(group, show_url=True):
out = '\x02{}\x02'.format(group['name'])
if group['description']:
out += ': "{}"'.format(formatting.truncate(group['description']))
out += ' - Owned by \x02{}\x02.'.format(group['creator']['username'])
if show_url:
out += ' -... |
null | null | null | What does this function do? | def avail_images(kwargs=None, call=None):
if (call == 'action'):
raise SaltCloudSystemExit('The avail_images function must be called with -f or --function, or with the --list-images option')
if (not isinstance(kwargs, dict)):
kwargs = {}
if ('owner' in kwargs):
owner = kwargs['owner']
else:
provider = get_c... | null | null | null | Return a dict of all available VM images on the cloud provider. | pcsd | def avail images kwargs=None call=None if call == 'action' raise Salt Cloud System Exit 'The avail images function must be called with -f or --function or with the --list-images option' if not isinstance kwargs dict kwargs = {} if 'owner' in kwargs owner = kwargs['owner'] else provider = get configured provider owner =... | 11979 | def avail_images(kwargs=None, call=None):
if (call == 'action'):
raise SaltCloudSystemExit('The avail_images function must be called with -f or --function, or with the --list-images option')
if (not isinstance(kwargs, dict)):
kwargs = {}
if ('owner' in kwargs):
owner = kwargs['owner']
else:
provider = get_c... | Return a dict of all available VM images on the cloud provider. | return a dict of all available vm images on the cloud provider . | Question:
What does this function do?
Code:
def avail_images(kwargs=None, call=None):
if (call == 'action'):
raise SaltCloudSystemExit('The avail_images function must be called with -f or --function, or with the --list-images option')
if (not isinstance(kwargs, dict)):
kwargs = {}
if ('owner' in kwargs):
ow... |
null | null | null | What does this function do? | def disable_trace():
global app_or_default
app_or_default = _app_or_default
| null | null | null | Disable tracing of app instances. | pcsd | def disable trace global app or default app or default = app or default | 11991 | def disable_trace():
global app_or_default
app_or_default = _app_or_default
| Disable tracing of app instances. | disable tracing of app instances . | Question:
What does this function do?
Code:
def disable_trace():
global app_or_default
app_or_default = _app_or_default
|
null | null | null | What does this function do? | def find_all_tests(suite):
suites = [suite]
while suites:
s = suites.pop()
try:
suites.extend(s)
except TypeError:
(yield (s, ('%s.%s.%s' % (s.__class__.__module__, s.__class__.__name__, s._testMethodName))))
| null | null | null | Yields all the tests and their names from a given suite. | pcsd | def find all tests suite suites = [suite] while suites s = suites pop try suites extend s except Type Error yield s '%s %s %s' % s class module s class name s test Method Name | 11998 | def find_all_tests(suite):
suites = [suite]
while suites:
s = suites.pop()
try:
suites.extend(s)
except TypeError:
(yield (s, ('%s.%s.%s' % (s.__class__.__module__, s.__class__.__name__, s._testMethodName))))
| Yields all the tests and their names from a given suite. | yields all the tests and their names from a given suite . | Question:
What does this function do?
Code:
def find_all_tests(suite):
suites = [suite]
while suites:
s = suites.pop()
try:
suites.extend(s)
except TypeError:
(yield (s, ('%s.%s.%s' % (s.__class__.__module__, s.__class__.__name__, s._testMethodName))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.