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?
@click.group(invoke_without_command=True) @click.option('-c', '--config', callback=read_config, type=click.File('r'), help='a json file with default values for subcommands. {"webui": {"port":5001}}') @click.option('--logging-config', default=os.path.join(os.path.dirname(__file__), 'logging.conf'), help='logging config ...
null
null
null
A powerful spider system in python.
pcsd
@click group invoke without command=True @click option '-c' '--config' callback=read config type=click File 'r' help='a json file with default values for subcommands {"webui" {"port" 5001}}' @click option '--logging-config' default=os path join os path dirname file 'logging conf' help='logging config file for built-in ...
4211
@click.group(invoke_without_command=True) @click.option('-c', '--config', callback=read_config, type=click.File('r'), help='a json file with default values for subcommands. {"webui": {"port":5001}}') @click.option('--logging-config', default=os.path.join(os.path.dirname(__file__), 'logging.conf'), help='logging config ...
A powerful spider system in python.
a powerful spider system in python .
Question: What does this function do? Code: @click.group(invoke_without_command=True) @click.option('-c', '--config', callback=read_config, type=click.File('r'), help='a json file with default values for subcommands. {"webui": {"port":5001}}') @click.option('--logging-config', default=os.path.join(os.path.dirname(__...
null
null
null
What does this function do?
def srun(cmd, **kwargs): return run(('sudo ' + cmd), **kwargs)
null
null
null
Run + sudo
pcsd
def srun cmd **kwargs return run 'sudo ' + cmd **kwargs
4215
def srun(cmd, **kwargs): return run(('sudo ' + cmd), **kwargs)
Run + sudo
run + sudo
Question: What does this function do? Code: def srun(cmd, **kwargs): return run(('sudo ' + cmd), **kwargs)
null
null
null
What does this function do?
def assert_mail_count(count, msg=None): if (msg is None): msg = ', '.join([e.subject for e in mail.outbox]) msg = ('%d != %d %s' % (len(mail.outbox), count, msg)) assert_equals(len(mail.outbox), count, msg)
null
null
null
Assert the number of emails sent. The message here tends to be long, so allow for replacing the whole thing instead of prefixing.
pcsd
def assert mail count count msg=None if msg is None msg = ' ' join [e subject for e in mail outbox] msg = '%d != %d %s' % len mail outbox count msg assert equals len mail outbox count msg
4222
def assert_mail_count(count, msg=None): if (msg is None): msg = ', '.join([e.subject for e in mail.outbox]) msg = ('%d != %d %s' % (len(mail.outbox), count, msg)) assert_equals(len(mail.outbox), count, msg)
Assert the number of emails sent. The message here tends to be long, so allow for replacing the whole thing instead of prefixing.
assert the number of emails sent .
Question: What does this function do? Code: def assert_mail_count(count, msg=None): if (msg is None): msg = ', '.join([e.subject for e in mail.outbox]) msg = ('%d != %d %s' % (len(mail.outbox), count, msg)) assert_equals(len(mail.outbox), count, msg)
null
null
null
What does this function do?
@requires_application() @requires_scipy() def test_reactive_draw(): pos = np.array([[(-0.1), 0.5, 0], [0.1, 0.5, 0], [0.1, (-0.5), 0], [(-0.1), (-0.5), 0]]) with TestingCanvas() as c: polygon = visuals.Polygon(pos=pos, color='yellow', parent=c.scene) polygon.transform = transforms.STTransform(scale=(50, 50), tran...
null
null
null
Test reactive polygon attributes
pcsd
@requires application @requires scipy def test reactive draw pos = np array [[ -0 1 0 5 0] [0 1 0 5 0] [0 1 -0 5 0] [ -0 1 -0 5 0]] with Testing Canvas as c polygon = visuals Polygon pos=pos color='yellow' parent=c scene polygon transform = transforms ST Transform scale= 50 50 translate= 50 50 polygon pos += [0 1 -0 1 ...
4223
@requires_application() @requires_scipy() def test_reactive_draw(): pos = np.array([[(-0.1), 0.5, 0], [0.1, 0.5, 0], [0.1, (-0.5), 0], [(-0.1), (-0.5), 0]]) with TestingCanvas() as c: polygon = visuals.Polygon(pos=pos, color='yellow', parent=c.scene) polygon.transform = transforms.STTransform(scale=(50, 50), tran...
Test reactive polygon attributes
test reactive polygon attributes
Question: What does this function do? Code: @requires_application() @requires_scipy() def test_reactive_draw(): pos = np.array([[(-0.1), 0.5, 0], [0.1, 0.5, 0], [0.1, (-0.5), 0], [(-0.1), (-0.5), 0]]) with TestingCanvas() as c: polygon = visuals.Polygon(pos=pos, color='yellow', parent=c.scene) polygon.transfor...
null
null
null
What does this function do?
def compile(pattern, flags=0, **kwargs): return _compile(pattern, flags, kwargs)
null
null
null
Compile a regular expression pattern, returning a pattern object.
pcsd
def compile pattern flags=0 **kwargs return compile pattern flags kwargs
4231
def compile(pattern, flags=0, **kwargs): return _compile(pattern, flags, kwargs)
Compile a regular expression pattern, returning a pattern object.
compile a regular expression pattern , returning a pattern object .
Question: What does this function do? Code: def compile(pattern, flags=0, **kwargs): return _compile(pattern, flags, kwargs)
null
null
null
What does this function do?
def set_emulated_double(number): double = np.array([number, 0], dtype=np.float32) double[1] = (number - double[0]) return double
null
null
null
Emulate a double using two numbers of type float32.
pcsd
def set emulated double number double = np array [number 0] dtype=np float32 double[1] = number - double[0] return double
4243
def set_emulated_double(number): double = np.array([number, 0], dtype=np.float32) double[1] = (number - double[0]) return double
Emulate a double using two numbers of type float32.
emulate a double using two numbers of type float32 .
Question: What does this function do? Code: def set_emulated_double(number): double = np.array([number, 0], dtype=np.float32) double[1] = (number - double[0]) return double
null
null
null
What does this function do?
def save_as(filename, title=u'Save As...'): result = compat.getsavefilename(parent=active_window(), caption=title, basedir=filename) return result[0]
null
null
null
Creates a Save File dialog and returns a filename.
pcsd
def save as filename title=u'Save As ' result = compat getsavefilename parent=active window caption=title basedir=filename return result[0]
4244
def save_as(filename, title=u'Save As...'): result = compat.getsavefilename(parent=active_window(), caption=title, basedir=filename) return result[0]
Creates a Save File dialog and returns a filename.
creates a save file dialog and returns a filename .
Question: What does this function do? Code: def save_as(filename, title=u'Save As...'): result = compat.getsavefilename(parent=active_window(), caption=title, basedir=filename) return result[0]
null
null
null
What does this function do?
def _password_digest(username, password): if (not isinstance(password, string_type)): raise TypeError(('password must be an instance of %s' % (string_type.__name__,))) if (len(password) == 0): raise ValueError("password can't be empty") if (not isinstance(username, string_type)): raise TypeError(('password mus...
null
null
null
Get a password digest to use for authentication.
pcsd
def password digest username password if not isinstance password string type raise Type Error 'password must be an instance of %s' % string type name if len password == 0 raise Value Error "password can't be empty" if not isinstance username string type raise Type Error 'password must be an instance of %s' % string typ...
4249
def _password_digest(username, password): if (not isinstance(password, string_type)): raise TypeError(('password must be an instance of %s' % (string_type.__name__,))) if (len(password) == 0): raise ValueError("password can't be empty") if (not isinstance(username, string_type)): raise TypeError(('password mus...
Get a password digest to use for authentication.
get a password digest to use for authentication .
Question: What does this function do? Code: def _password_digest(username, password): if (not isinstance(password, string_type)): raise TypeError(('password must be an instance of %s' % (string_type.__name__,))) if (len(password) == 0): raise ValueError("password can't be empty") if (not isinstance(username, ...
null
null
null
What does this function do?
def delete(section, keyword): try: database[section][keyword].delete() except KeyError: return
null
null
null
Delete specific config item
pcsd
def delete section keyword try database[section][keyword] delete except Key Error return
4253
def delete(section, keyword): try: database[section][keyword].delete() except KeyError: return
Delete specific config item
delete specific config item
Question: What does this function do? Code: def delete(section, keyword): try: database[section][keyword].delete() except KeyError: return
null
null
null
What does this function do?
def inline_markdown_extension(pelicanobj, config): try: pelicanobj.settings['MD_EXTENSIONS'].append(PelicanInlineMarkdownExtension(config)) except: sys.excepthook(*sys.exc_info()) sys.stderr.write('\nError - the pelican Markdown extension failed to configure. Inline Markdown extension is non-functional.\n') s...
null
null
null
Instantiates a customized Markdown extension
pcsd
def inline markdown extension pelicanobj config try pelicanobj settings['MD EXTENSIONS'] append Pelican Inline Markdown Extension config except sys excepthook *sys exc info sys stderr write ' Error - the pelican Markdown extension failed to configure Inline Markdown extension is non-functional ' sys stderr flush
4254
def inline_markdown_extension(pelicanobj, config): try: pelicanobj.settings['MD_EXTENSIONS'].append(PelicanInlineMarkdownExtension(config)) except: sys.excepthook(*sys.exc_info()) sys.stderr.write('\nError - the pelican Markdown extension failed to configure. Inline Markdown extension is non-functional.\n') s...
Instantiates a customized Markdown extension
instantiates a customized markdown extension
Question: What does this function do? Code: def inline_markdown_extension(pelicanobj, config): try: pelicanobj.settings['MD_EXTENSIONS'].append(PelicanInlineMarkdownExtension(config)) except: sys.excepthook(*sys.exc_info()) sys.stderr.write('\nError - the pelican Markdown extension failed to configure. Inlin...
null
null
null
What does this function do?
def get_volume_type_from_volume(volume): type_id = volume.get('volume_type_id') if (type_id is None): return {} ctxt = context.get_admin_context() return volume_types.get_volume_type(ctxt, type_id)
null
null
null
Provides volume type associated with volume.
pcsd
def get volume type from volume volume type id = volume get 'volume type id' if type id is None return {} ctxt = context get admin context return volume types get volume type ctxt type id
4256
def get_volume_type_from_volume(volume): type_id = volume.get('volume_type_id') if (type_id is None): return {} ctxt = context.get_admin_context() return volume_types.get_volume_type(ctxt, type_id)
Provides volume type associated with volume.
provides volume type associated with volume .
Question: What does this function do? Code: def get_volume_type_from_volume(volume): type_id = volume.get('volume_type_id') if (type_id is None): return {} ctxt = context.get_admin_context() return volume_types.get_volume_type(ctxt, type_id)
null
null
null
What does this function do?
def activities_from_everything_followed_by_user(user_id, limit, offset): q = _activities_from_everything_followed_by_user_query(user_id, (limit + offset)) return _activities_at_offset(q, limit, offset)
null
null
null
Return activities from everything that the given user is following. Returns all activities where the object of the activity is anything (user, dataset, group...) that the given user is following.
pcsd
def activities from everything followed by user user id limit offset q = activities from everything followed by user query user id limit + offset return activities at offset q limit offset
4267
def activities_from_everything_followed_by_user(user_id, limit, offset): q = _activities_from_everything_followed_by_user_query(user_id, (limit + offset)) return _activities_at_offset(q, limit, offset)
Return activities from everything that the given user is following. Returns all activities where the object of the activity is anything (user, dataset, group...) that the given user is following.
return activities from everything that the given user is following .
Question: What does this function do? Code: def activities_from_everything_followed_by_user(user_id, limit, offset): q = _activities_from_everything_followed_by_user_query(user_id, (limit + offset)) return _activities_at_offset(q, limit, offset)
null
null
null
What does this function do?
def openable(string, **kwargs): f = tempfile.NamedTemporaryFile(**kwargs) f.write(string) f.seek(0) _TEMPORARY_FILES.append(f) return f.name
null
null
null
Returns the path to a temporary file that contains the given string.
pcsd
def openable string **kwargs f = tempfile Named Temporary File **kwargs f write string f seek 0 TEMPORARY FILES append f return f name
4272
def openable(string, **kwargs): f = tempfile.NamedTemporaryFile(**kwargs) f.write(string) f.seek(0) _TEMPORARY_FILES.append(f) return f.name
Returns the path to a temporary file that contains the given string.
returns the path to a temporary file that contains the given string .
Question: What does this function do? Code: def openable(string, **kwargs): f = tempfile.NamedTemporaryFile(**kwargs) f.write(string) f.seek(0) _TEMPORARY_FILES.append(f) return f.name
null
null
null
What does this function do?
@mobile_template('questions/{mobile/}marketplace_success.html') def marketplace_success(request, template=None): return render(request, template)
null
null
null
Confirmation of ticket submitted successfully.
pcsd
@mobile template 'questions/{mobile/}marketplace success html' def marketplace success request template=None return render request template
4278
@mobile_template('questions/{mobile/}marketplace_success.html') def marketplace_success(request, template=None): return render(request, template)
Confirmation of ticket submitted successfully.
confirmation of ticket submitted successfully .
Question: What does this function do? Code: @mobile_template('questions/{mobile/}marketplace_success.html') def marketplace_success(request, template=None): return render(request, template)
null
null
null
What does this function do?
def elastic_search(request): query = request.GET.get('q') type = request.GET.get('type', 'project') project = request.GET.get('project') version = request.GET.get('version', LATEST) taxonomy = request.GET.get('taxonomy') language = request.GET.get('language') results = '' facets = {} if query: if (type == 'p...
null
null
null
Use elastic search for global search
pcsd
def elastic search request query = request GET get 'q' type = request GET get 'type' 'project' project = request GET get 'project' version = request GET get 'version' LATEST taxonomy = request GET get 'taxonomy' language = request GET get 'language' results = '' facets = {} if query if type == 'project' results = searc...
4279
def elastic_search(request): query = request.GET.get('q') type = request.GET.get('type', 'project') project = request.GET.get('project') version = request.GET.get('version', LATEST) taxonomy = request.GET.get('taxonomy') language = request.GET.get('language') results = '' facets = {} if query: if (type == 'p...
Use elastic search for global search
use elastic search for global search
Question: What does this function do? Code: def elastic_search(request): query = request.GET.get('q') type = request.GET.get('type', 'project') project = request.GET.get('project') version = request.GET.get('version', LATEST) taxonomy = request.GET.get('taxonomy') language = request.GET.get('language') result...
null
null
null
What does this function do?
def template(): atable = s3db.cap_alert s3.filter = (atable.is_template == True) viewing = request.vars['viewing'] tablename = 'cap_alert' if viewing: (table, _id) = viewing.strip().split('.') if (table == tablename): redirect(URL(c='cap', f='template', args=[_id])) def prep(r): list_fields = ['template_...
null
null
null
REST controller for CAP templates
pcsd
def template atable = s3db cap alert s3 filter = atable is template == True viewing = request vars['viewing'] tablename = 'cap alert' if viewing table id = viewing strip split ' ' if table == tablename redirect URL c='cap' f='template' args=[ id] def prep r list fields = ['template title' 'identifier' 'event type id' '...
4287
def template(): atable = s3db.cap_alert s3.filter = (atable.is_template == True) viewing = request.vars['viewing'] tablename = 'cap_alert' if viewing: (table, _id) = viewing.strip().split('.') if (table == tablename): redirect(URL(c='cap', f='template', args=[_id])) def prep(r): list_fields = ['template_...
REST controller for CAP templates
rest controller for cap templates
Question: What does this function do? Code: def template(): atable = s3db.cap_alert s3.filter = (atable.is_template == True) viewing = request.vars['viewing'] tablename = 'cap_alert' if viewing: (table, _id) = viewing.strip().split('.') if (table == tablename): redirect(URL(c='cap', f='template', args=[_...
null
null
null
What does this function do?
def int_to_base36(i): digits = u'0123456789abcdefghijklmnopqrstuvwxyz' factor = 0 if (i < 0): raise ValueError(u'Negative base36 conversion input.') if six.PY2: if (not isinstance(i, six.integer_types)): raise TypeError(u'Non-integer base36 conversion input.') if (i > sys.maxint): raise ValueError(u'Bas...
null
null
null
Converts an integer to a base36 string
pcsd
def int to base36 i digits = u'0123456789abcdefghijklmnopqrstuvwxyz' factor = 0 if i < 0 raise Value Error u'Negative base36 conversion input ' if six PY2 if not isinstance i six integer types raise Type Error u'Non-integer base36 conversion input ' if i > sys maxint raise Value Error u'Base36 conversion input too larg...
4300
def int_to_base36(i): digits = u'0123456789abcdefghijklmnopqrstuvwxyz' factor = 0 if (i < 0): raise ValueError(u'Negative base36 conversion input.') if six.PY2: if (not isinstance(i, six.integer_types)): raise TypeError(u'Non-integer base36 conversion input.') if (i > sys.maxint): raise ValueError(u'Bas...
Converts an integer to a base36 string
converts an integer to a base36 string
Question: What does this function do? Code: def int_to_base36(i): digits = u'0123456789abcdefghijklmnopqrstuvwxyz' factor = 0 if (i < 0): raise ValueError(u'Negative base36 conversion input.') if six.PY2: if (not isinstance(i, six.integer_types)): raise TypeError(u'Non-integer base36 conversion input.') ...
null
null
null
What does this function do?
def process_attribute_value(key, value): if (not cfg.CONF.log.mask_secrets): return value if isinstance(value, SIMPLE_TYPES): if (key in MASKED_ATTRIBUTES_BLACKLIST): value = MASKED_ATTRIBUTE_VALUE elif isinstance(value, dict): value = copy.deepcopy(value) for (dict_key, dict_value) in six.iteritems(value...
null
null
null
Format and process the extra attribute value.
pcsd
def process attribute value key value if not cfg CONF log mask secrets return value if isinstance value SIMPLE TYPES if key in MASKED ATTRIBUTES BLACKLIST value = MASKED ATTRIBUTE VALUE elif isinstance value dict value = copy deepcopy value for dict key dict value in six iteritems value value[dict key] = process attrib...
4305
def process_attribute_value(key, value): if (not cfg.CONF.log.mask_secrets): return value if isinstance(value, SIMPLE_TYPES): if (key in MASKED_ATTRIBUTES_BLACKLIST): value = MASKED_ATTRIBUTE_VALUE elif isinstance(value, dict): value = copy.deepcopy(value) for (dict_key, dict_value) in six.iteritems(value...
Format and process the extra attribute value.
format and process the extra attribute value .
Question: What does this function do? Code: def process_attribute_value(key, value): if (not cfg.CONF.log.mask_secrets): return value if isinstance(value, SIMPLE_TYPES): if (key in MASKED_ATTRIBUTES_BLACKLIST): value = MASKED_ATTRIBUTE_VALUE elif isinstance(value, dict): value = copy.deepcopy(value) fo...
null
null
null
What does this function do?
def assert_phase_almost_equal(a, b, *args, **kwargs): shift = ((2 * np.pi) * np.round(((b.mean() - a.mean()) / (2 * np.pi)))) with warnings.catch_warnings(): warnings.simplefilter('ignore') print('assert_phase_allclose, abs', np.max(np.abs((a - (b - shift))))) print('assert_phase_allclose, rel', np.max(np.abs((...
null
null
null
An assert_almost_equal insensitive to phase shifts of n*2*pi.
pcsd
def assert phase almost equal a b *args **kwargs shift = 2 * np pi * np round b mean - a mean / 2 * np pi with warnings catch warnings warnings simplefilter 'ignore' print 'assert phase allclose abs' np max np abs a - b - shift print 'assert phase allclose rel' np max np abs a - b - shift / a if np ma is Masked Array a...
4310
def assert_phase_almost_equal(a, b, *args, **kwargs): shift = ((2 * np.pi) * np.round(((b.mean() - a.mean()) / (2 * np.pi)))) with warnings.catch_warnings(): warnings.simplefilter('ignore') print('assert_phase_allclose, abs', np.max(np.abs((a - (b - shift))))) print('assert_phase_allclose, rel', np.max(np.abs((...
An assert_almost_equal insensitive to phase shifts of n*2*pi.
an assert _ almost _ equal insensitive to phase shifts of n * 2 * pi .
Question: What does this function do? Code: def assert_phase_almost_equal(a, b, *args, **kwargs): shift = ((2 * np.pi) * np.round(((b.mean() - a.mean()) / (2 * np.pi)))) with warnings.catch_warnings(): warnings.simplefilter('ignore') print('assert_phase_allclose, abs', np.max(np.abs((a - (b - shift))))) prin...
null
null
null
What does this function do?
@require_POST @login_required def move_thread(request, forum_slug, thread_id): forum = get_object_or_404(Forum, slug=forum_slug) thread = get_object_or_404(Thread, pk=thread_id, forum=forum) user = request.user new_forum_id = request.POST.get('forum') new_forum = get_object_or_404(Forum, id=new_forum_id) if (not ...
null
null
null
Move a thread.
pcsd
@require POST @login required def move thread request forum slug thread id forum = get object or 404 Forum slug=forum slug thread = get object or 404 Thread pk=thread id forum=forum user = request user new forum id = request POST get 'forum' new forum = get object or 404 Forum id=new forum id if not forum allows viewin...
4313
@require_POST @login_required def move_thread(request, forum_slug, thread_id): forum = get_object_or_404(Forum, slug=forum_slug) thread = get_object_or_404(Thread, pk=thread_id, forum=forum) user = request.user new_forum_id = request.POST.get('forum') new_forum = get_object_or_404(Forum, id=new_forum_id) if (not ...
Move a thread.
move a thread .
Question: What does this function do? Code: @require_POST @login_required def move_thread(request, forum_slug, thread_id): forum = get_object_or_404(Forum, slug=forum_slug) thread = get_object_or_404(Thread, pk=thread_id, forum=forum) user = request.user new_forum_id = request.POST.get('forum') new_forum = get_...
null
null
null
What does this function do?
def _init_nt(): g = {} g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1) g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1) g['INCLUDEPY'] = get_python_inc(plat_specific=0) g['EXT_SUFFIX'] = _imp.extension_suffixes()[0] g['EXE'] = '.exe' g['VERSION'] = get_python_version().replace('.'...
null
null
null
Initialize the module as appropriate for NT
pcsd
def init nt g = {} g['LIBDEST'] = get python lib plat specific=0 standard lib=1 g['BINLIBDEST'] = get python lib plat specific=1 standard lib=1 g['INCLUDEPY'] = get python inc plat specific=0 g['EXT SUFFIX'] = imp extension suffixes [0] g['EXE'] = ' exe' g['VERSION'] = get python version replace ' ' '' g['BINDIR'] = os...
4316
def _init_nt(): g = {} g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1) g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1) g['INCLUDEPY'] = get_python_inc(plat_specific=0) g['EXT_SUFFIX'] = _imp.extension_suffixes()[0] g['EXE'] = '.exe' g['VERSION'] = get_python_version().replace('.'...
Initialize the module as appropriate for NT
initialize the module as appropriate for nt
Question: What does this function do? Code: def _init_nt(): g = {} g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1) g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1) g['INCLUDEPY'] = get_python_inc(plat_specific=0) g['EXT_SUFFIX'] = _imp.extension_suffixes()[0] g['EXE'] = '.exe' ...
null
null
null
What does this function do?
def _write_instance_repr(out, visited, name, pyop_attrdict, address): out.write('<') out.write(name) if isinstance(pyop_attrdict, PyDictObjectPtr): out.write('(') first = True for (pyop_arg, pyop_val) in pyop_attrdict.items(): if (not first): out.write(', ') first = False out.write(pyop_arg.proxyv...
null
null
null
Shared code for use by old-style and new-style classes: write a representation to file-like object "out"
pcsd
def write instance repr out visited name pyop attrdict address out write '<' out write name if isinstance pyop attrdict Py Dict Object Ptr out write ' ' first = True for pyop arg pyop val in pyop attrdict items if not first out write ' ' first = False out write pyop arg proxyval visited out write '=' pyop val write rep...
4320
def _write_instance_repr(out, visited, name, pyop_attrdict, address): out.write('<') out.write(name) if isinstance(pyop_attrdict, PyDictObjectPtr): out.write('(') first = True for (pyop_arg, pyop_val) in pyop_attrdict.items(): if (not first): out.write(', ') first = False out.write(pyop_arg.proxyv...
Shared code for use by old-style and new-style classes: write a representation to file-like object "out"
shared code for use by old - style and new - style classes : write a representation to file - like object " out "
Question: What does this function do? Code: def _write_instance_repr(out, visited, name, pyop_attrdict, address): out.write('<') out.write(name) if isinstance(pyop_attrdict, PyDictObjectPtr): out.write('(') first = True for (pyop_arg, pyop_val) in pyop_attrdict.items(): if (not first): out.write(', '...
null
null
null
What does this function do?
def authorized_keys(name): ssh_dir = posixpath.join(home_directory(name), '.ssh') authorized_keys_filename = posixpath.join(ssh_dir, 'authorized_keys') return uncommented_lines(authorized_keys_filename, use_sudo=True)
null
null
null
Get the list of authorized SSH public keys for the user
pcsd
def authorized keys name ssh dir = posixpath join home directory name ' ssh' authorized keys filename = posixpath join ssh dir 'authorized keys' return uncommented lines authorized keys filename use sudo=True
4332
def authorized_keys(name): ssh_dir = posixpath.join(home_directory(name), '.ssh') authorized_keys_filename = posixpath.join(ssh_dir, 'authorized_keys') return uncommented_lines(authorized_keys_filename, use_sudo=True)
Get the list of authorized SSH public keys for the user
get the list of authorized ssh public keys for the user
Question: What does this function do? Code: def authorized_keys(name): ssh_dir = posixpath.join(home_directory(name), '.ssh') authorized_keys_filename = posixpath.join(ssh_dir, 'authorized_keys') return uncommented_lines(authorized_keys_filename, use_sudo=True)
null
null
null
What does this function do?
def volume_admin_metadata_update(context, volume_id, metadata, delete, add=True, update=True): return IMPL.volume_admin_metadata_update(context, volume_id, metadata, delete, add, update)
null
null
null
Update metadata if it exists, otherwise create it.
pcsd
def volume admin metadata update context volume id metadata delete add=True update=True return IMPL volume admin metadata update context volume id metadata delete add update
4343
def volume_admin_metadata_update(context, volume_id, metadata, delete, add=True, update=True): return IMPL.volume_admin_metadata_update(context, volume_id, metadata, delete, add, update)
Update metadata if it exists, otherwise create it.
update metadata if it exists , otherwise create it .
Question: What does this function do? Code: def volume_admin_metadata_update(context, volume_id, metadata, delete, add=True, update=True): return IMPL.volume_admin_metadata_update(context, volume_id, metadata, delete, add, update)
null
null
null
What does this function do?
def insert_enterprise_pipeline_elements(pipeline): if (not enterprise_enabled()): return additional_elements = ('enterprise.tpa_pipeline.set_data_sharing_consent_record', 'enterprise.tpa_pipeline.verify_data_sharing_consent') insert_point = pipeline.index('social.pipeline.social_auth.load_extra_data') for (index,...
null
null
null
If the enterprise app is enabled, insert additional elements into the pipeline so that data sharing consent views are used.
pcsd
def insert enterprise pipeline elements pipeline if not enterprise enabled return additional elements = 'enterprise tpa pipeline set data sharing consent record' 'enterprise tpa pipeline verify data sharing consent' insert point = pipeline index 'social pipeline social auth load extra data' for index element in enumera...
4353
def insert_enterprise_pipeline_elements(pipeline): if (not enterprise_enabled()): return additional_elements = ('enterprise.tpa_pipeline.set_data_sharing_consent_record', 'enterprise.tpa_pipeline.verify_data_sharing_consent') insert_point = pipeline.index('social.pipeline.social_auth.load_extra_data') for (index,...
If the enterprise app is enabled, insert additional elements into the pipeline so that data sharing consent views are used.
if the enterprise app is enabled , insert additional elements into the pipeline so that data sharing consent views are used .
Question: What does this function do? Code: def insert_enterprise_pipeline_elements(pipeline): if (not enterprise_enabled()): return additional_elements = ('enterprise.tpa_pipeline.set_data_sharing_consent_record', 'enterprise.tpa_pipeline.verify_data_sharing_consent') insert_point = pipeline.index('social.pipe...
null
null
null
What does this function do?
def export_languages_json(): languages = frappe.db.get_all(u'Language', fields=[u'name', u'language_name']) languages = [{u'name': d.language_name, u'code': d.name} for d in languages] languages.sort((lambda a, b: (1 if (a[u'code'] > b[u'code']) else (-1)))) with open(frappe.get_app_path(u'frappe', u'geo', u'langua...
null
null
null
Export list of all languages
pcsd
def export languages json languages = frappe db get all u'Language' fields=[u'name' u'language name'] languages = [{u'name' d language name u'code' d name} for d in languages] languages sort lambda a b 1 if a[u'code'] > b[u'code'] else -1 with open frappe get app path u'frappe' u'geo' u'languages json' u'w' as f f writ...
4358
def export_languages_json(): languages = frappe.db.get_all(u'Language', fields=[u'name', u'language_name']) languages = [{u'name': d.language_name, u'code': d.name} for d in languages] languages.sort((lambda a, b: (1 if (a[u'code'] > b[u'code']) else (-1)))) with open(frappe.get_app_path(u'frappe', u'geo', u'langua...
Export list of all languages
export list of all languages
Question: What does this function do? Code: def export_languages_json(): languages = frappe.db.get_all(u'Language', fields=[u'name', u'language_name']) languages = [{u'name': d.language_name, u'code': d.name} for d in languages] languages.sort((lambda a, b: (1 if (a[u'code'] > b[u'code']) else (-1)))) with open(...
null
null
null
What does this function do?
def getInsetSeparateLoopsFromAroundLoops(loops, radius, radiusAround, thresholdRatio=0.9): if (radius == 0.0): return loops isInset = (radius > 0) insetSeparateLoops = [] radius = abs(radius) radiusAround = max(abs(radiusAround), radius) points = getPointsFromLoops(loops, radiusAround, thresholdRatio) centers ...
null
null
null
Get the separate inset loops.
pcsd
def get Inset Separate Loops From Around Loops loops radius radius Around threshold Ratio=0 9 if radius == 0 0 return loops is Inset = radius > 0 inset Separate Loops = [] radius = abs radius radius Around = max abs radius Around radius points = get Points From Loops loops radius Around threshold Ratio centers = get Ce...
4360
def getInsetSeparateLoopsFromAroundLoops(loops, radius, radiusAround, thresholdRatio=0.9): if (radius == 0.0): return loops isInset = (radius > 0) insetSeparateLoops = [] radius = abs(radius) radiusAround = max(abs(radiusAround), radius) points = getPointsFromLoops(loops, radiusAround, thresholdRatio) centers ...
Get the separate inset loops.
get the separate inset loops .
Question: What does this function do? Code: def getInsetSeparateLoopsFromAroundLoops(loops, radius, radiusAround, thresholdRatio=0.9): if (radius == 0.0): return loops isInset = (radius > 0) insetSeparateLoops = [] radius = abs(radius) radiusAround = max(abs(radiusAround), radius) points = getPointsFromLoops...
null
null
null
What does this function do?
def shorten_line(tokens, source, indentation, indent_word, max_line_length, aggressive=False, experimental=False, previous_line=u''): for candidate in _shorten_line(tokens=tokens, source=source, indentation=indentation, indent_word=indent_word, aggressive=aggressive, previous_line=previous_line): (yield candidate) ...
null
null
null
Separate line at OPERATOR. Multiple candidates will be yielded.
pcsd
def shorten line tokens source indentation indent word max line length aggressive=False experimental=False previous line=u'' for candidate in shorten line tokens=tokens source=source indentation=indentation indent word=indent word aggressive=aggressive previous line=previous line yield candidate if aggressive for key t...
4361
def shorten_line(tokens, source, indentation, indent_word, max_line_length, aggressive=False, experimental=False, previous_line=u''): for candidate in _shorten_line(tokens=tokens, source=source, indentation=indentation, indent_word=indent_word, aggressive=aggressive, previous_line=previous_line): (yield candidate) ...
Separate line at OPERATOR. Multiple candidates will be yielded.
separate line at operator .
Question: What does this function do? Code: def shorten_line(tokens, source, indentation, indent_word, max_line_length, aggressive=False, experimental=False, previous_line=u''): for candidate in _shorten_line(tokens=tokens, source=source, indentation=indentation, indent_word=indent_word, aggressive=aggressive, prev...
null
null
null
What does this function do?
def redirect_param(location, params, *args, **kwargs): return HttpResponseRedirect((resolve_url(location, *args, **kwargs) + params))
null
null
null
Redirects to a URL with parameters.
pcsd
def redirect param location params *args **kwargs return Http Response Redirect resolve url location *args **kwargs + params
4363
def redirect_param(location, params, *args, **kwargs): return HttpResponseRedirect((resolve_url(location, *args, **kwargs) + params))
Redirects to a URL with parameters.
redirects to a url with parameters .
Question: What does this function do? Code: def redirect_param(location, params, *args, **kwargs): return HttpResponseRedirect((resolve_url(location, *args, **kwargs) + params))
null
null
null
What does this function do?
def get_inventory(service_instance): return service_instance.RetrieveContent()
null
null
null
Return the inventory of a Service Instance Object. service_instance The Service Instance Object for which to obtain inventory.
pcsd
def get inventory service instance return service instance Retrieve Content
4364
def get_inventory(service_instance): return service_instance.RetrieveContent()
Return the inventory of a Service Instance Object. service_instance The Service Instance Object for which to obtain inventory.
return the inventory of a service instance object .
Question: What does this function do? Code: def get_inventory(service_instance): return service_instance.RetrieveContent()
null
null
null
What does this function do?
def inverse_permutation(perm): return permute_row_elements(arange(perm.shape[(-1)], dtype=perm.dtype), perm, inverse=True)
null
null
null
Computes the inverse of permutations. Each row of input should contain a permutation of the first integers.
pcsd
def inverse permutation perm return permute row elements arange perm shape[ -1 ] dtype=perm dtype perm inverse=True
4369
def inverse_permutation(perm): return permute_row_elements(arange(perm.shape[(-1)], dtype=perm.dtype), perm, inverse=True)
Computes the inverse of permutations. Each row of input should contain a permutation of the first integers.
computes the inverse of permutations .
Question: What does this function do? Code: def inverse_permutation(perm): return permute_row_elements(arange(perm.shape[(-1)], dtype=perm.dtype), perm, inverse=True)
null
null
null
What does this function do?
def _parse_id(s): match = re.search(u'[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) if match: return match.group()
null
null
null
Search for a MusicBrainz ID in the given string and return it. If no ID can be found, return None.
pcsd
def parse id s match = re search u'[a-f0-9]{8} -[a-f0-9]{4} {3}-[a-f0-9]{12}' s if match return match group
4370
def _parse_id(s): match = re.search(u'[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) if match: return match.group()
Search for a MusicBrainz ID in the given string and return it. If no ID can be found, return None.
search for a musicbrainz id in the given string and return it .
Question: What does this function do? Code: def _parse_id(s): match = re.search(u'[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) if match: return match.group()
null
null
null
What does this function do?
def dump_threads_on_sigquit(signum, frame): dump_traceback()
null
null
null
Dump out the threads to stderr
pcsd
def dump threads on sigquit signum frame dump traceback
4377
def dump_threads_on_sigquit(signum, frame): dump_traceback()
Dump out the threads to stderr
dump out the threads to stderr
Question: What does this function do? Code: def dump_threads_on_sigquit(signum, frame): dump_traceback()
null
null
null
What does this function do?
def import_class(import_path, base_class=None): try: (module, class_name) = import_path.rsplit('.', 1) except ValueError: raise ImportError(("%s isn't a Python path." % import_path)) try: mod = import_module(module) except ImportError as e: raise ImportError(('Error importing module %s: "%s"' % (module, e))...
null
null
null
Imports and returns the class described by import_path, where import_path is the full Python path to the class.
pcsd
def import class import path base class=None try module class name = import path rsplit ' ' 1 except Value Error raise Import Error "%s isn't a Python path " % import path try mod = import module module except Import Error as e raise Import Error 'Error importing module %s "%s"' % module e try class = getattr mod class...
4381
def import_class(import_path, base_class=None): try: (module, class_name) = import_path.rsplit('.', 1) except ValueError: raise ImportError(("%s isn't a Python path." % import_path)) try: mod = import_module(module) except ImportError as e: raise ImportError(('Error importing module %s: "%s"' % (module, e))...
Imports and returns the class described by import_path, where import_path is the full Python path to the class.
imports and returns the class described by import _ path , where import _ path is the full python path to the class .
Question: What does this function do? Code: def import_class(import_path, base_class=None): try: (module, class_name) = import_path.rsplit('.', 1) except ValueError: raise ImportError(("%s isn't a Python path." % import_path)) try: mod = import_module(module) except ImportError as e: raise ImportError(('...
null
null
null
What does this function do?
def empty_str(in_str): if ((in_str is not None) and (not isinstance(in_str, string_types))): raise TypeError('Arg must be None or a string type') return ((in_str is None) or (len(in_str.strip()) == 0))
null
null
null
Simple helper to return True if the passed string reference is None or \'\' or all whitespace
pcsd
def empty str in str if in str is not None and not isinstance in str string types raise Type Error 'Arg must be None or a string type' return in str is None or len in str strip == 0
4396
def empty_str(in_str): if ((in_str is not None) and (not isinstance(in_str, string_types))): raise TypeError('Arg must be None or a string type') return ((in_str is None) or (len(in_str.strip()) == 0))
Simple helper to return True if the passed string reference is None or \'\' or all whitespace
simple helper to return true if the passed string reference is none or or all whitespace
Question: What does this function do? Code: def empty_str(in_str): if ((in_str is not None) and (not isinstance(in_str, string_types))): raise TypeError('Arg must be None or a string type') return ((in_str is None) or (len(in_str.strip()) == 0))
null
null
null
What does this function do?
def send_email_for_expired_orders(email, event_name, invoice_id, order_url): send_email(to=email, action=MAIL_TO_EXPIRED_ORDERS, subject=MAILS[MAIL_TO_EXPIRED_ORDERS]['subject'].format(event_name=event_name), html=MAILS[MAIL_TO_EXPIRED_ORDERS]['message'].format(invoice_id=invoice_id, order_url=order_url))
null
null
null
Send email with order invoice link after purchase
pcsd
def send email for expired orders email event name invoice id order url send email to=email action=MAIL TO EXPIRED ORDERS subject=MAILS[MAIL TO EXPIRED ORDERS]['subject'] format event name=event name html=MAILS[MAIL TO EXPIRED ORDERS]['message'] format invoice id=invoice id order url=order url
4399
def send_email_for_expired_orders(email, event_name, invoice_id, order_url): send_email(to=email, action=MAIL_TO_EXPIRED_ORDERS, subject=MAILS[MAIL_TO_EXPIRED_ORDERS]['subject'].format(event_name=event_name), html=MAILS[MAIL_TO_EXPIRED_ORDERS]['message'].format(invoice_id=invoice_id, order_url=order_url))
Send email with order invoice link after purchase
send email with order invoice link after purchase
Question: What does this function do? Code: def send_email_for_expired_orders(email, event_name, invoice_id, order_url): send_email(to=email, action=MAIL_TO_EXPIRED_ORDERS, subject=MAILS[MAIL_TO_EXPIRED_ORDERS]['subject'].format(event_name=event_name), html=MAILS[MAIL_TO_EXPIRED_ORDERS]['message'].format(invoice_id...
null
null
null
What does this function do?
def vdot(m1, m2): err_code = ct.c_int(0) res = _eigenmat.vdot(m1.p_mat, m2.p_mat, ct.byref(err_code)) if err_code: raise generate_exception(err_code.value) return res
null
null
null
Compute the vector dot product of matrices m1 and m2.
pcsd
def vdot m1 m2 err code = ct c int 0 res = eigenmat vdot m1 p mat m2 p mat ct byref err code if err code raise generate exception err code value return res
4400
def vdot(m1, m2): err_code = ct.c_int(0) res = _eigenmat.vdot(m1.p_mat, m2.p_mat, ct.byref(err_code)) if err_code: raise generate_exception(err_code.value) return res
Compute the vector dot product of matrices m1 and m2.
compute the vector dot product of matrices m1 and m2 .
Question: What does this function do? Code: def vdot(m1, m2): err_code = ct.c_int(0) res = _eigenmat.vdot(m1.p_mat, m2.p_mat, ct.byref(err_code)) if err_code: raise generate_exception(err_code.value) return res
null
null
null
What does this function do?
def getNewRepository(): return VectorwriteRepository()
null
null
null
Get new repository.
pcsd
def get New Repository return Vectorwrite Repository
4401
def getNewRepository(): return VectorwriteRepository()
Get new repository.
get new repository .
Question: What does this function do? Code: def getNewRepository(): return VectorwriteRepository()
null
null
null
What does this function do?
def register_opts(config): config.register_opts(METER_PUBLISH_OPTS, group='publisher_rpc')
null
null
null
Register the options for publishing metering messages.
pcsd
def register opts config config register opts METER PUBLISH OPTS group='publisher rpc'
4405
def register_opts(config): config.register_opts(METER_PUBLISH_OPTS, group='publisher_rpc')
Register the options for publishing metering messages.
register the options for publishing metering messages .
Question: What does this function do? Code: def register_opts(config): config.register_opts(METER_PUBLISH_OPTS, group='publisher_rpc')
null
null
null
What does this function do?
def slugize(name): if (TEAM_NAME_PATTERN.match(name) is None): raise InvalidTeamName slug = name.strip() for c in (u',', u' '): slug = slug.replace(c, u'-') while (u'--' in slug): slug = slug.replace(u'--', u'-') slug = slug.strip(u'-') return slug
null
null
null
Create a slug from a team name.
pcsd
def slugize name if TEAM NAME PATTERN match name is None raise Invalid Team Name slug = name strip for c in u' ' u' ' slug = slug replace c u'-' while u'--' in slug slug = slug replace u'--' u'-' slug = slug strip u'-' return slug
4407
def slugize(name): if (TEAM_NAME_PATTERN.match(name) is None): raise InvalidTeamName slug = name.strip() for c in (u',', u' '): slug = slug.replace(c, u'-') while (u'--' in slug): slug = slug.replace(u'--', u'-') slug = slug.strip(u'-') return slug
Create a slug from a team name.
create a slug from a team name .
Question: What does this function do? Code: def slugize(name): if (TEAM_NAME_PATTERN.match(name) is None): raise InvalidTeamName slug = name.strip() for c in (u',', u' '): slug = slug.replace(c, u'-') while (u'--' in slug): slug = slug.replace(u'--', u'-') slug = slug.strip(u'-') return slug
null
null
null
What does this function do?
def rewriter(field, rules): def fieldfunc(item): value = item._values_fixed[field] for (pattern, replacement) in rules: if pattern.match(value.lower()): return replacement return value return fieldfunc
null
null
null
Create a template field function that rewrites the given field with the given rewriting rules. ``rules`` must be a list of (pattern, replacement) pairs.
pcsd
def rewriter field rules def fieldfunc item value = item values fixed[field] for pattern replacement in rules if pattern match value lower return replacement return value return fieldfunc
4420
def rewriter(field, rules): def fieldfunc(item): value = item._values_fixed[field] for (pattern, replacement) in rules: if pattern.match(value.lower()): return replacement return value return fieldfunc
Create a template field function that rewrites the given field with the given rewriting rules. ``rules`` must be a list of (pattern, replacement) pairs.
create a template field function that rewrites the given field with the given rewriting rules .
Question: What does this function do? Code: def rewriter(field, rules): def fieldfunc(item): value = item._values_fixed[field] for (pattern, replacement) in rules: if pattern.match(value.lower()): return replacement return value return fieldfunc
null
null
null
What does this function do?
def load_model(path_to_model): with open(('%s.dictionary.pkl' % path_to_model), 'rb') as f: worddict = pkl.load(f) word_idict = dict() for (kk, vv) in worddict.iteritems(): word_idict[vv] = kk word_idict[0] = '<eos>' word_idict[1] = 'UNK' with open(('%s.pkl' % path_to_model), 'rb') as f: options = pkl.load(...
null
null
null
Load all model components
pcsd
def load model path to model with open '%s dictionary pkl' % path to model 'rb' as f worddict = pkl load f word idict = dict for kk vv in worddict iteritems word idict[vv] = kk word idict[0] = '<eos>' word idict[1] = 'UNK' with open '%s pkl' % path to model 'rb' as f options = pkl load f params = init params options pa...
4430
def load_model(path_to_model): with open(('%s.dictionary.pkl' % path_to_model), 'rb') as f: worddict = pkl.load(f) word_idict = dict() for (kk, vv) in worddict.iteritems(): word_idict[vv] = kk word_idict[0] = '<eos>' word_idict[1] = 'UNK' with open(('%s.pkl' % path_to_model), 'rb') as f: options = pkl.load(...
Load all model components
load all model components
Question: What does this function do? Code: def load_model(path_to_model): with open(('%s.dictionary.pkl' % path_to_model), 'rb') as f: worddict = pkl.load(f) word_idict = dict() for (kk, vv) in worddict.iteritems(): word_idict[vv] = kk word_idict[0] = '<eos>' word_idict[1] = 'UNK' with open(('%s.pkl' % pa...
null
null
null
What does this function do?
def api_calls_left(user, domain='all'): max_window = _rules_for_user(user)[(-1)][0] max_calls = _rules_for_user(user)[(-1)][1] return _get_api_calls_left(user, domain, max_window, max_calls)
null
null
null
Returns how many API calls in this range this client has, as well as when the rate-limit will be reset to 0
pcsd
def api calls left user domain='all' max window = rules for user user [ -1 ][0] max calls = rules for user user [ -1 ][1] return get api calls left user domain max window max calls
4431
def api_calls_left(user, domain='all'): max_window = _rules_for_user(user)[(-1)][0] max_calls = _rules_for_user(user)[(-1)][1] return _get_api_calls_left(user, domain, max_window, max_calls)
Returns how many API calls in this range this client has, as well as when the rate-limit will be reset to 0
returns how many api calls in this range this client has , as well as when the rate - limit will be reset to 0
Question: What does this function do? Code: def api_calls_left(user, domain='all'): max_window = _rules_for_user(user)[(-1)][0] max_calls = _rules_for_user(user)[(-1)][1] return _get_api_calls_left(user, domain, max_window, max_calls)
null
null
null
What does this function do?
def xml(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]): return Text(string, token).xml
null
null
null
Transforms the output of parse() into XML. The token parameter lists the order of tags in each token in the input string.
pcsd
def xml string token=[WORD POS CHUNK PNP REL ANCHOR LEMMA] return Text string token xml
4434
def xml(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]): return Text(string, token).xml
Transforms the output of parse() into XML. The token parameter lists the order of tags in each token in the input string.
transforms the output of parse ( ) into xml .
Question: What does this function do? Code: def xml(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]): return Text(string, token).xml
null
null
null
What does this function do?
@login_required @view def importer(request, test_js=False): person = request.user.get_profile() data = get_personal_data(person) data['citation_form'] = mysite.profile.forms.ManuallyAddACitationForm(auto_id=False) data['test_js'] = (test_js or request.GET.get('test', None)) return (request, 'profile/importer.html'...
null
null
null
Get the logged-in user\'s profile. Pass them to the template.
pcsd
@login required @view def importer request test js=False person = request user get profile data = get personal data person data['citation form'] = mysite profile forms Manually Add A Citation Form auto id=False data['test js'] = test js or request GET get 'test' None return request 'profile/importer html' data
4437
@login_required @view def importer(request, test_js=False): person = request.user.get_profile() data = get_personal_data(person) data['citation_form'] = mysite.profile.forms.ManuallyAddACitationForm(auto_id=False) data['test_js'] = (test_js or request.GET.get('test', None)) return (request, 'profile/importer.html'...
Get the logged-in user\'s profile. Pass them to the template.
get the logged - in users profile .
Question: What does this function do? Code: @login_required @view def importer(request, test_js=False): person = request.user.get_profile() data = get_personal_data(person) data['citation_form'] = mysite.profile.forms.ManuallyAddACitationForm(auto_id=False) data['test_js'] = (test_js or request.GET.get('test', N...
null
null
null
What does this function do?
def get_sql_flush(style, tables, sequences): sql = [('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table)))) for table in tables]
null
null
null
Return a list of SQL statements required to remove all data from all tables in the database (without actually removing the tables themselves) and put the database in an empty \'initial\' state
pcsd
def get sql flush style tables sequences sql = [ '%s %s ' % style SQL KEYWORD 'TRUNCATE' style SQL FIELD quote name table for table in tables]
4439
def get_sql_flush(style, tables, sequences): sql = [('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table)))) for table in tables]
Return a list of SQL statements required to remove all data from all tables in the database (without actually removing the tables themselves) and put the database in an empty \'initial\' state
return a list of sql statements required to remove all data from all tables in the database and put the database in an empty initial state
Question: What does this function do? Code: def get_sql_flush(style, tables, sequences): sql = [('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table)))) for table in tables]
null
null
null
What does this function do?
@click.command('update_bench_on_update') @click.argument('state', type=click.Choice(['on', 'off'])) def config_update_bench_on_update(state): state = (True if (state == 'on') else False) update_config({'update_bench_on_update': state})
null
null
null
Enable/Disable bench updates on running bench update
pcsd
@click command 'update bench on update' @click argument 'state' type=click Choice ['on' 'off'] def config update bench on update state state = True if state == 'on' else False update config {'update bench on update' state}
4441
@click.command('update_bench_on_update') @click.argument('state', type=click.Choice(['on', 'off'])) def config_update_bench_on_update(state): state = (True if (state == 'on') else False) update_config({'update_bench_on_update': state})
Enable/Disable bench updates on running bench update
enable / disable bench updates on running bench update
Question: What does this function do? Code: @click.command('update_bench_on_update') @click.argument('state', type=click.Choice(['on', 'off'])) def config_update_bench_on_update(state): state = (True if (state == 'on') else False) update_config({'update_bench_on_update': state})
null
null
null
What does this function do?
def get_application(): return tornado.web.Application([('/?', MainHandler, dict(backup_recovery_service=BackupService()))])
null
null
null
Retrieves the application to feed into tornado.
pcsd
def get application return tornado web Application [ '/?' Main Handler dict backup recovery service=Backup Service ]
4453
def get_application(): return tornado.web.Application([('/?', MainHandler, dict(backup_recovery_service=BackupService()))])
Retrieves the application to feed into tornado.
retrieves the application to feed into tornado .
Question: What does this function do? Code: def get_application(): return tornado.web.Application([('/?', MainHandler, dict(backup_recovery_service=BackupService()))])
null
null
null
What does this function do?
def _system_state_change(state, device): if (state == 'present'): if device: return False return True if (state == 'absent'): if device: return True return False return False
null
null
null
Check if system state would change.
pcsd
def system state change state device if state == 'present' if device return False return True if state == 'absent' if device return True return False return False
4455
def _system_state_change(state, device): if (state == 'present'): if device: return False return True if (state == 'absent'): if device: return True return False return False
Check if system state would change.
check if system state would change .
Question: What does this function do? Code: def _system_state_change(state, device): if (state == 'present'): if device: return False return True if (state == 'absent'): if device: return True return False return False
null
null
null
What does this function do?
def index(): module_name = settings.modules[module].name_nice response.title = module_name output = {'module_name': module_name} from s3 import FS define_resource = s3db.resource total_households = define_resource('po_household').count() total_referrals = define_resource('po_organisation_household').count() tot...
null
null
null
Module\'s Home Page
pcsd
def index module name = settings modules[module] name nice response title = module name output = {'module name' module name} from s3 import FS define resource = s3db resource total households = define resource 'po household' count total referrals = define resource 'po organisation household' count total agencies = defi...
4459
def index(): module_name = settings.modules[module].name_nice response.title = module_name output = {'module_name': module_name} from s3 import FS define_resource = s3db.resource total_households = define_resource('po_household').count() total_referrals = define_resource('po_organisation_household').count() tot...
Module\'s Home Page
modules home page
Question: What does this function do? Code: def index(): module_name = settings.modules[module].name_nice response.title = module_name output = {'module_name': module_name} from s3 import FS define_resource = s3db.resource total_households = define_resource('po_household').count() total_referrals = define_res...
null
null
null
What does this function do?
def Probability2(yes, no): return (yes / (yes + no))
null
null
null
Computes the probability corresponding to given odds. Example: yes=2, no=1 means 2:1 odds in favor, or 2/3 probability. yes, no: int or float odds in favor
pcsd
def Probability2 yes no return yes / yes + no
4460
def Probability2(yes, no): return (yes / (yes + no))
Computes the probability corresponding to given odds. Example: yes=2, no=1 means 2:1 odds in favor, or 2/3 probability. yes, no: int or float odds in favor
computes the probability corresponding to given odds .
Question: What does this function do? Code: def Probability2(yes, no): return (yes / (yes + no))
null
null
null
What does this function do?
@ssl_required def aaq_step3(request, product_key, category_key): return aaq(request, product_key=product_key, category_key=category_key, step=1)
null
null
null
Step 3: The product and category is selected.
pcsd
@ssl required def aaq step3 request product key category key return aaq request product key=product key category key=category key step=1
4471
@ssl_required def aaq_step3(request, product_key, category_key): return aaq(request, product_key=product_key, category_key=category_key, step=1)
Step 3: The product and category is selected.
step 3 : the product and category is selected .
Question: What does this function do? Code: @ssl_required def aaq_step3(request, product_key, category_key): return aaq(request, product_key=product_key, category_key=category_key, step=1)
null
null
null
What does this function do?
@with_setup(prepare_stdout) def test_background_with_header(): from lettuce import step, world @step(u'the variable "(\\w+)" holds (\\d+)') def set_variable(step, name, value): setattr(world, name, int(value)) @step(u'the variable "(\\w+)" is equal to (\\d+)') def check_variable(step, name, expected): expected...
null
null
null
Running background with header
pcsd
@with setup prepare stdout def test background with header from lettuce import step world @step u'the variable " \\w+ " holds \\d+ ' def set variable step name value setattr world name int value @step u'the variable " \\w+ " is equal to \\d+ ' def check variable step name expected expected = int expected expect world t...
4479
@with_setup(prepare_stdout) def test_background_with_header(): from lettuce import step, world @step(u'the variable "(\\w+)" holds (\\d+)') def set_variable(step, name, value): setattr(world, name, int(value)) @step(u'the variable "(\\w+)" is equal to (\\d+)') def check_variable(step, name, expected): expected...
Running background with header
running background with header
Question: What does this function do? Code: @with_setup(prepare_stdout) def test_background_with_header(): from lettuce import step, world @step(u'the variable "(\\w+)" holds (\\d+)') def set_variable(step, name, value): setattr(world, name, int(value)) @step(u'the variable "(\\w+)" is equal to (\\d+)') def c...
null
null
null
What does this function do?
def is_threshold_graph(G): return is_threshold_sequence(list((d for (n, d) in G.degree())))
null
null
null
Returns True if G is a threshold graph.
pcsd
def is threshold graph G return is threshold sequence list d for n d in G degree
4488
def is_threshold_graph(G): return is_threshold_sequence(list((d for (n, d) in G.degree())))
Returns True if G is a threshold graph.
returns true if g is a threshold graph .
Question: What does this function do? Code: def is_threshold_graph(G): return is_threshold_sequence(list((d for (n, d) in G.degree())))
null
null
null
What does this function do?
def get_preferred_file_contents_encoding(): return (locale.getpreferredencoding() or u'utf-8')
null
null
null
Get encoding preferred for file contents
pcsd
def get preferred file contents encoding return locale getpreferredencoding or u'utf-8'
4489
def get_preferred_file_contents_encoding(): return (locale.getpreferredencoding() or u'utf-8')
Get encoding preferred for file contents
get encoding preferred for file contents
Question: What does this function do? Code: def get_preferred_file_contents_encoding(): return (locale.getpreferredencoding() or u'utf-8')
null
null
null
What does this function do?
def normalize_letters(one_letter_code): if (one_letter_code == '.'): return 'X' else: return one_letter_code.upper()
null
null
null
Convert RAF one-letter amino acid codes into IUPAC standard codes. Letters are uppercased, and "." ("Unknown") is converted to "X".
pcsd
def normalize letters one letter code if one letter code == ' ' return 'X' else return one letter code upper
4490
def normalize_letters(one_letter_code): if (one_letter_code == '.'): return 'X' else: return one_letter_code.upper()
Convert RAF one-letter amino acid codes into IUPAC standard codes. Letters are uppercased, and "." ("Unknown") is converted to "X".
convert raf one - letter amino acid codes into iupac standard codes .
Question: What does this function do? Code: def normalize_letters(one_letter_code): if (one_letter_code == '.'): return 'X' else: return one_letter_code.upper()
null
null
null
What does this function do?
def pathstrip(path, n): pathlist = [path] while (os.path.dirname(pathlist[0]) != ''): pathlist[0:1] = os.path.split(pathlist[0]) return '/'.join(pathlist[n:])
null
null
null
Strip n leading components from the given path
pcsd
def pathstrip path n pathlist = [path] while os path dirname pathlist[0] != '' pathlist[0 1] = os path split pathlist[0] return '/' join pathlist[n ]
4501
def pathstrip(path, n): pathlist = [path] while (os.path.dirname(pathlist[0]) != ''): pathlist[0:1] = os.path.split(pathlist[0]) return '/'.join(pathlist[n:])
Strip n leading components from the given path
strip n leading components from the given path
Question: What does this function do? Code: def pathstrip(path, n): pathlist = [path] while (os.path.dirname(pathlist[0]) != ''): pathlist[0:1] = os.path.split(pathlist[0]) return '/'.join(pathlist[n:])
null
null
null
What does this function do?
@pick_context_manager_writer def action_event_finish(context, values): convert_objects_related_datetimes(values, 'start_time', 'finish_time') action = _action_get_by_request_id(context, values['instance_uuid'], values['request_id']) if ((not action) and (not context.project_id)): action = _action_get_last_created_...
null
null
null
Finish an event on an instance action.
pcsd
@pick context manager writer def action event finish context values convert objects related datetimes values 'start time' 'finish time' action = action get by request id context values['instance uuid'] values['request id'] if not action and not context project id action = action get last created by instance uuid contex...
4506
@pick_context_manager_writer def action_event_finish(context, values): convert_objects_related_datetimes(values, 'start_time', 'finish_time') action = _action_get_by_request_id(context, values['instance_uuid'], values['request_id']) if ((not action) and (not context.project_id)): action = _action_get_last_created_...
Finish an event on an instance action.
finish an event on an instance action .
Question: What does this function do? Code: @pick_context_manager_writer def action_event_finish(context, values): convert_objects_related_datetimes(values, 'start_time', 'finish_time') action = _action_get_by_request_id(context, values['instance_uuid'], values['request_id']) if ((not action) and (not context.pro...
null
null
null
What does this function do?
def extract_deps(fname, legal_deps): deps = {} for line in open(fname).readlines(): if (line[:8] != '#include'): continue inc = _re_include.match(line).group(1) if (inc in legal_deps.keys()): deps[inc] = legal_deps[inc] return deps
null
null
null
Extract the headers this file includes.
pcsd
def extract deps fname legal deps deps = {} for line in open fname readlines if line[ 8] != '#include' continue inc = re include match line group 1 if inc in legal deps keys deps[inc] = legal deps[inc] return deps
4532
def extract_deps(fname, legal_deps): deps = {} for line in open(fname).readlines(): if (line[:8] != '#include'): continue inc = _re_include.match(line).group(1) if (inc in legal_deps.keys()): deps[inc] = legal_deps[inc] return deps
Extract the headers this file includes.
extract the headers this file includes .
Question: What does this function do? Code: def extract_deps(fname, legal_deps): deps = {} for line in open(fname).readlines(): if (line[:8] != '#include'): continue inc = _re_include.match(line).group(1) if (inc in legal_deps.keys()): deps[inc] = legal_deps[inc] return deps
null
null
null
What does this function do?
def generateOnlyInterface(list, int): for n in list: if int.providedBy(n): (yield n)
null
null
null
Filters items in a list by class
pcsd
def generate Only Interface list int for n in list if int provided By n yield n
4534
def generateOnlyInterface(list, int): for n in list: if int.providedBy(n): (yield n)
Filters items in a list by class
filters items in a list by class
Question: What does this function do? Code: def generateOnlyInterface(list, int): for n in list: if int.providedBy(n): (yield n)
null
null
null
What does this function do?
def full_path_split(path): (rest, tail) = os.path.split(path) if ((not rest) or (rest == os.path.sep)): return (tail,) return (full_path_split(rest) + (tail,))
null
null
null
Function to do a full split on a path.
pcsd
def full path split path rest tail = os path split path if not rest or rest == os path sep return tail return full path split rest + tail
4535
def full_path_split(path): (rest, tail) = os.path.split(path) if ((not rest) or (rest == os.path.sep)): return (tail,) return (full_path_split(rest) + (tail,))
Function to do a full split on a path.
function to do a full split on a path .
Question: What does this function do? Code: def full_path_split(path): (rest, tail) = os.path.split(path) if ((not rest) or (rest == os.path.sep)): return (tail,) return (full_path_split(rest) + (tail,))
null
null
null
What does this function do?
def reload_theme(value, prev): if (value != prev): config = (((os.path.dirname(__file__) + '/colorset/') + value) + '.json') data = load_config(config) if data: for d in data: c[d] = data[d] start_cycle() set_config('THEME', value) return value return prev
null
null
null
Check current theme and update if necessary
pcsd
def reload theme value prev if value != prev config = os path dirname file + '/colorset/' + value + ' json' data = load config config if data for d in data c[d] = data[d] start cycle set config 'THEME' value return value return prev
4536
def reload_theme(value, prev): if (value != prev): config = (((os.path.dirname(__file__) + '/colorset/') + value) + '.json') data = load_config(config) if data: for d in data: c[d] = data[d] start_cycle() set_config('THEME', value) return value return prev
Check current theme and update if necessary
check current theme and update if necessary
Question: What does this function do? Code: def reload_theme(value, prev): if (value != prev): config = (((os.path.dirname(__file__) + '/colorset/') + value) + '.json') data = load_config(config) if data: for d in data: c[d] = data[d] start_cycle() set_config('THEME', value) return value return ...
null
null
null
What does this function do?
def get_image_properties_table(meta): (define_image_properties_table,) = from_migration_import('002_add_image_properties_table', ['define_image_properties_table']) image_properties = define_image_properties_table(meta) return image_properties
null
null
null
No changes to the image properties table from 002...
pcsd
def get image properties table meta define image properties table = from migration import '002 add image properties table' ['define image properties table'] image properties = define image properties table meta return image properties
4546
def get_image_properties_table(meta): (define_image_properties_table,) = from_migration_import('002_add_image_properties_table', ['define_image_properties_table']) image_properties = define_image_properties_table(meta) return image_properties
No changes to the image properties table from 002...
no changes to the image properties table from 002 . . .
Question: What does this function do? Code: def get_image_properties_table(meta): (define_image_properties_table,) = from_migration_import('002_add_image_properties_table', ['define_image_properties_table']) image_properties = define_image_properties_table(meta) return image_properties
null
null
null
What does this function do?
def compile_template(template, renderers, default, blacklist, whitelist, saltenv='base', sls='', input_data='', **kwargs): ret = {} log.debug('compile template: {0}'.format(template)) if ('env' in kwargs): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is n...
null
null
null
Take the path to a template and return the high data structure derived from the template.
pcsd
def compile template template renderers default blacklist whitelist saltenv='base' sls='' input data='' **kwargs ret = {} log debug 'compile template {0}' format template if 'env' in kwargs salt utils warn until 'Oxygen' "Parameter 'env' has been detected in the argument list This parameter is no longer used and has be...
4548
def compile_template(template, renderers, default, blacklist, whitelist, saltenv='base', sls='', input_data='', **kwargs): ret = {} log.debug('compile template: {0}'.format(template)) if ('env' in kwargs): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is n...
Take the path to a template and return the high data structure derived from the template.
take the path to a template and return the high data structure derived from the template .
Question: What does this function do? Code: def compile_template(template, renderers, default, blacklist, whitelist, saltenv='base', sls='', input_data='', **kwargs): ret = {} log.debug('compile template: {0}'.format(template)) if ('env' in kwargs): salt.utils.warn_until('Oxygen', "Parameter 'env' has been dete...
null
null
null
What does this function do?
def tearDownModule(): hass.stop()
null
null
null
Stop everything that was started.
pcsd
def tear Down Module hass stop
4553
def tearDownModule(): hass.stop()
Stop everything that was started.
stop everything that was started .
Question: What does this function do? Code: def tearDownModule(): hass.stop()
null
null
null
What does this function do?
def main(): argument_spec = dict(netconf_port=dict(type='int', default=830, aliases=['listens_on']), state=dict(default='present', choices=['present', 'absent']), transport=dict(default='cli', choices=['cli'])) module = NetworkModule(argument_spec=argument_spec, supports_check_mode=True) state = module.params['state...
null
null
null
main entry point for module execution
pcsd
def main argument spec = dict netconf port=dict type='int' default=830 aliases=['listens on'] state=dict default='present' choices=['present' 'absent'] transport=dict default='cli' choices=['cli'] module = Network Module argument spec=argument spec supports check mode=True state = module params['state'] port = module p...
4554
def main(): argument_spec = dict(netconf_port=dict(type='int', default=830, aliases=['listens_on']), state=dict(default='present', choices=['present', 'absent']), transport=dict(default='cli', choices=['cli'])) module = NetworkModule(argument_spec=argument_spec, supports_check_mode=True) state = module.params['state...
main entry point for module execution
main entry point for module execution
Question: What does this function do? Code: def main(): argument_spec = dict(netconf_port=dict(type='int', default=830, aliases=['listens_on']), state=dict(default='present', choices=['present', 'absent']), transport=dict(default='cli', choices=['cli'])) module = NetworkModule(argument_spec=argument_spec, supports...
null
null
null
What does this function do?
def getComplexPolygonByStartEnd(endAngle, radius, sides, startAngle=0.0): angleExtent = (endAngle - startAngle) sideAngle = ((2.0 * math.pi) / float(sides)) sides = int(math.ceil(abs((angleExtent / sideAngle)))) sideAngle = (angleExtent / float(sides)) complexPolygon = [] for side in xrange((abs(sides) + 1)): u...
null
null
null
Get the complex polygon by start and end angle.
pcsd
def get Complex Polygon By Start End end Angle radius sides start Angle=0 0 angle Extent = end Angle - start Angle side Angle = 2 0 * math pi / float sides sides = int math ceil abs angle Extent / side Angle side Angle = angle Extent / float sides complex Polygon = [] for side in xrange abs sides + 1 unit Polar = get W...
4560
def getComplexPolygonByStartEnd(endAngle, radius, sides, startAngle=0.0): angleExtent = (endAngle - startAngle) sideAngle = ((2.0 * math.pi) / float(sides)) sides = int(math.ceil(abs((angleExtent / sideAngle)))) sideAngle = (angleExtent / float(sides)) complexPolygon = [] for side in xrange((abs(sides) + 1)): u...
Get the complex polygon by start and end angle.
get the complex polygon by start and end angle .
Question: What does this function do? Code: def getComplexPolygonByStartEnd(endAngle, radius, sides, startAngle=0.0): angleExtent = (endAngle - startAngle) sideAngle = ((2.0 * math.pi) / float(sides)) sides = int(math.ceil(abs((angleExtent / sideAngle)))) sideAngle = (angleExtent / float(sides)) complexPolygon ...
null
null
null
What does this function do?
def main(photo_file): credentials = GoogleCredentials.get_application_default() service = discovery.build('vision', 'v1', credentials=credentials) with open(photo_file, 'rb') as image: image_content = base64.b64encode(image.read()) service_request = service.images().annotate(body={'requests': [{'image': {'conten...
null
null
null
Run a label request on a single image
pcsd
def main photo file credentials = Google Credentials get application default service = discovery build 'vision' 'v1' credentials=credentials with open photo file 'rb' as image image content = base64 b64encode image read service request = service images annotate body={'requests' [{'image' {'content' image content decode...
4571
def main(photo_file): credentials = GoogleCredentials.get_application_default() service = discovery.build('vision', 'v1', credentials=credentials) with open(photo_file, 'rb') as image: image_content = base64.b64encode(image.read()) service_request = service.images().annotate(body={'requests': [{'image': {'conten...
Run a label request on a single image
run a label request on a single image
Question: What does this function do? Code: def main(photo_file): credentials = GoogleCredentials.get_application_default() service = discovery.build('vision', 'v1', credentials=credentials) with open(photo_file, 'rb') as image: image_content = base64.b64encode(image.read()) service_request = service.images()...
null
null
null
What does this function do?
def ini_format(stream, options, encoding): for (optname, optdict, value) in options: value = format_option_value(optdict, value) help = optdict.get('help') if help: help = normalize_text(help, line_len=79, indent='# ') print(file=stream) print(_encode(help, encoding), file=stream) else: print(file=...
null
null
null
format options using the INI format
pcsd
def ini format stream options encoding for optname optdict value in options value = format option value optdict value help = optdict get 'help' if help help = normalize text help line len=79 indent='# ' print file=stream print encode help encoding file=stream else print file=stream if value is None print '#%s=' % optna...
4573
def ini_format(stream, options, encoding): for (optname, optdict, value) in options: value = format_option_value(optdict, value) help = optdict.get('help') if help: help = normalize_text(help, line_len=79, indent='# ') print(file=stream) print(_encode(help, encoding), file=stream) else: print(file=...
format options using the INI format
format options using the ini format
Question: What does this function do? Code: def ini_format(stream, options, encoding): for (optname, optdict, value) in options: value = format_option_value(optdict, value) help = optdict.get('help') if help: help = normalize_text(help, line_len=79, indent='# ') print(file=stream) print(_encode(help,...
null
null
null
What does this function do?
def _get_existing_regions(): existing_regions = [] possible_files = os.listdir(os.path.expanduser('~')) for f in possible_files: something = re.search('\\.bees\\.(.*)', f) (existing_regions.append(something.group(1)) if something else 'no') return existing_regions
null
null
null
return a list of zone name strings from looking at existing region ~/.bees.* files
pcsd
def get existing regions existing regions = [] possible files = os listdir os path expanduser '~' for f in possible files something = re search '\\ bees\\ * ' f existing regions append something group 1 if something else 'no' return existing regions
4575
def _get_existing_regions(): existing_regions = [] possible_files = os.listdir(os.path.expanduser('~')) for f in possible_files: something = re.search('\\.bees\\.(.*)', f) (existing_regions.append(something.group(1)) if something else 'no') return existing_regions
return a list of zone name strings from looking at existing region ~/.bees.* files
return a list of zone name strings from looking at existing region ~ / . bees . * files
Question: What does this function do? Code: def _get_existing_regions(): existing_regions = [] possible_files = os.listdir(os.path.expanduser('~')) for f in possible_files: something = re.search('\\.bees\\.(.*)', f) (existing_regions.append(something.group(1)) if something else 'no') return existing_regions
null
null
null
What does this function do?
def init(opts): proxy_dict = opts.get('proxy', {}) NETWORK_DEVICE['HOSTNAME'] = (proxy_dict.get('host') or proxy_dict.get('hostname')) NETWORK_DEVICE['USERNAME'] = (proxy_dict.get('username') or proxy_dict.get('user')) NETWORK_DEVICE['DRIVER_NAME'] = (proxy_dict.get('driver') or proxy_dict.get('os')) NETWORK_DEVIC...
null
null
null
Opens the connection with the network device.
pcsd
def init opts proxy dict = opts get 'proxy' {} NETWORK DEVICE['HOSTNAME'] = proxy dict get 'host' or proxy dict get 'hostname' NETWORK DEVICE['USERNAME'] = proxy dict get 'username' or proxy dict get 'user' NETWORK DEVICE['DRIVER NAME'] = proxy dict get 'driver' or proxy dict get 'os' NETWORK DEVICE['PASSWORD'] = proxy...
4588
def init(opts): proxy_dict = opts.get('proxy', {}) NETWORK_DEVICE['HOSTNAME'] = (proxy_dict.get('host') or proxy_dict.get('hostname')) NETWORK_DEVICE['USERNAME'] = (proxy_dict.get('username') or proxy_dict.get('user')) NETWORK_DEVICE['DRIVER_NAME'] = (proxy_dict.get('driver') or proxy_dict.get('os')) NETWORK_DEVIC...
Opens the connection with the network device.
opens the connection with the network device .
Question: What does this function do? Code: def init(opts): proxy_dict = opts.get('proxy', {}) NETWORK_DEVICE['HOSTNAME'] = (proxy_dict.get('host') or proxy_dict.get('hostname')) NETWORK_DEVICE['USERNAME'] = (proxy_dict.get('username') or proxy_dict.get('user')) NETWORK_DEVICE['DRIVER_NAME'] = (proxy_dict.get('d...
null
null
null
What does this function do?
def _get_score_from_submissions(submissions_scores, block): if submissions_scores: submission_value = submissions_scores.get(unicode(block.location)) if submission_value: attempted = True (weighted_earned, weighted_possible) = submission_value assert ((weighted_earned >= 0.0) and (weighted_possible > 0.0)...
null
null
null
Returns the score values from the submissions API if found.
pcsd
def get score from submissions submissions scores block if submissions scores submission value = submissions scores get unicode block location if submission value attempted = True weighted earned weighted possible = submission value assert weighted earned >= 0 0 and weighted possible > 0 0 return None None + weighted e...
4596
def _get_score_from_submissions(submissions_scores, block): if submissions_scores: submission_value = submissions_scores.get(unicode(block.location)) if submission_value: attempted = True (weighted_earned, weighted_possible) = submission_value assert ((weighted_earned >= 0.0) and (weighted_possible > 0.0)...
Returns the score values from the submissions API if found.
returns the score values from the submissions api if found .
Question: What does this function do? Code: def _get_score_from_submissions(submissions_scores, block): if submissions_scores: submission_value = submissions_scores.get(unicode(block.location)) if submission_value: attempted = True (weighted_earned, weighted_possible) = submission_value assert ((weight...
null
null
null
What does this function do?
def _require_language(code, fullname, plurals=2, plural_equation='(n != 1)'): from pootle_language.models import Language criteria = {'code': code, 'fullname': fullname, 'nplurals': plurals, 'pluralequation': plural_equation} (language, created) = Language.objects.get_or_create(**criteria) if created: language.sa...
null
null
null
Helper to get/create a new language.
pcsd
def require language code fullname plurals=2 plural equation=' n != 1 ' from pootle language models import Language criteria = {'code' code 'fullname' fullname 'nplurals' plurals 'pluralequation' plural equation} language created = Language objects get or create **criteria if created language save return language
4610
def _require_language(code, fullname, plurals=2, plural_equation='(n != 1)'): from pootle_language.models import Language criteria = {'code': code, 'fullname': fullname, 'nplurals': plurals, 'pluralequation': plural_equation} (language, created) = Language.objects.get_or_create(**criteria) if created: language.sa...
Helper to get/create a new language.
helper to get / create a new language .
Question: What does this function do? Code: def _require_language(code, fullname, plurals=2, plural_equation='(n != 1)'): from pootle_language.models import Language criteria = {'code': code, 'fullname': fullname, 'nplurals': plurals, 'pluralequation': plural_equation} (language, created) = Language.objects.get_o...
null
null
null
What does this function do?
def verify_oauth_request(request, oauth_request, consumer, token=None): from treeio.core.api.auth.store import store if (not store.check_nonce(request, oauth_request, oauth_request['oauth_nonce'])): return False try: oauth_server = oauth.Server() oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA...
null
null
null
Helper function to verify requests.
pcsd
def verify oauth request request oauth request consumer token=None from treeio core api auth store import store if not store check nonce request oauth request oauth request['oauth nonce'] return False try oauth server = oauth Server oauth server add signature method oauth Signature Method HMAC SHA1 oauth server add sig...
4616
def verify_oauth_request(request, oauth_request, consumer, token=None): from treeio.core.api.auth.store import store if (not store.check_nonce(request, oauth_request, oauth_request['oauth_nonce'])): return False try: oauth_server = oauth.Server() oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA...
Helper function to verify requests.
helper function to verify requests .
Question: What does this function do? Code: def verify_oauth_request(request, oauth_request, consumer, token=None): from treeio.core.api.auth.store import store if (not store.check_nonce(request, oauth_request, oauth_request['oauth_nonce'])): return False try: oauth_server = oauth.Server() oauth_server.add_...
null
null
null
What does this function do?
def render_response(body=None, status=None, headers=None, method=None): if (headers is None): headers = [] else: headers = list(headers) headers.append(('Vary', 'X-Auth-Token')) if (body is None): body = '' status = (status or (http_client.NO_CONTENT, http_client.responses[http_client.NO_CONTENT])) else: ...
null
null
null
Form a WSGI response.
pcsd
def render response body=None status=None headers=None method=None if headers is None headers = [] else headers = list headers headers append 'Vary' 'X-Auth-Token' if body is None body = '' status = status or http client NO CONTENT http client responses[http client NO CONTENT] else content types = [v for h v in headers...
4631
def render_response(body=None, status=None, headers=None, method=None): if (headers is None): headers = [] else: headers = list(headers) headers.append(('Vary', 'X-Auth-Token')) if (body is None): body = '' status = (status or (http_client.NO_CONTENT, http_client.responses[http_client.NO_CONTENT])) else: ...
Form a WSGI response.
form a wsgi response .
Question: What does this function do? Code: def render_response(body=None, status=None, headers=None, method=None): if (headers is None): headers = [] else: headers = list(headers) headers.append(('Vary', 'X-Auth-Token')) if (body is None): body = '' status = (status or (http_client.NO_CONTENT, http_clie...
null
null
null
What does this function do?
def getInteriorSegments(loops, segments): interiorSegments = [] for segment in segments: center = (0.5 * (segment[0].point + segment[1].point)) if euclidean.getIsInFilledRegion(loops, center): interiorSegments.append(segment) return interiorSegments
null
null
null
Get segments inside the loops.
pcsd
def get Interior Segments loops segments interior Segments = [] for segment in segments center = 0 5 * segment[0] point + segment[1] point if euclidean get Is In Filled Region loops center interior Segments append segment return interior Segments
4641
def getInteriorSegments(loops, segments): interiorSegments = [] for segment in segments: center = (0.5 * (segment[0].point + segment[1].point)) if euclidean.getIsInFilledRegion(loops, center): interiorSegments.append(segment) return interiorSegments
Get segments inside the loops.
get segments inside the loops .
Question: What does this function do? Code: def getInteriorSegments(loops, segments): interiorSegments = [] for segment in segments: center = (0.5 * (segment[0].point + segment[1].point)) if euclidean.getIsInFilledRegion(loops, center): interiorSegments.append(segment) return interiorSegments
null
null
null
What does this function do?
@pytest.fixture(scope='module') def resource(request): local_path = os.path.dirname(request.module.__file__) return (lambda *args: get_resource_path(args, local_path))
null
null
null
Provides a function that returns the full path to a local or global testing resource
pcsd
@pytest fixture scope='module' def resource request local path = os path dirname request module file return lambda *args get resource path args local path
4643
@pytest.fixture(scope='module') def resource(request): local_path = os.path.dirname(request.module.__file__) return (lambda *args: get_resource_path(args, local_path))
Provides a function that returns the full path to a local or global testing resource
provides a function that returns the full path to a local or global testing resource
Question: What does this function do? Code: @pytest.fixture(scope='module') def resource(request): local_path = os.path.dirname(request.module.__file__) return (lambda *args: get_resource_path(args, local_path))
null
null
null
What does this function do?
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('attachment_id', metavar='<attachment>', help=_('Attachment ID of the volume.')) @utils.arg('new_volume', metavar='<volume>', help=_('ID of the volume to attach.')) def do_volume_update(cs, args): cs.volumes.update_server_volume(_find...
null
null
null
Update volume attachment.
pcsd
@utils arg 'server' metavar='<server>' help= 'Name or ID of server ' @utils arg 'attachment id' metavar='<attachment>' help= 'Attachment ID of the volume ' @utils arg 'new volume' metavar='<volume>' help= 'ID of the volume to attach ' def do volume update cs args cs volumes update server volume find server cs args serv...
4685
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('attachment_id', metavar='<attachment>', help=_('Attachment ID of the volume.')) @utils.arg('new_volume', metavar='<volume>', help=_('ID of the volume to attach.')) def do_volume_update(cs, args): cs.volumes.update_server_volume(_find...
Update volume attachment.
update volume attachment .
Question: What does this function do? Code: @utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('attachment_id', metavar='<attachment>', help=_('Attachment ID of the volume.')) @utils.arg('new_volume', metavar='<volume>', help=_('ID of the volume to attach.')) def do_volume_update(cs...
null
null
null
What does this function do?
def write_version_py(filename=None): doc = '"""\nThis is a VERSION file and should NOT be manually altered\n"""' doc += ("\nversion = '%s'" % VERSION) if (not filename): filename = os.path.join(os.path.dirname(__file__), 'quantecon', 'version.py') fl = open(filename, 'w') try: fl.write(doc) finally: fl.clos...
null
null
null
This constructs a version file for the project
pcsd
def write version py filename=None doc = '""" This is a VERSION file and should NOT be manually altered """' doc += " version = '%s'" % VERSION if not filename filename = os path join os path dirname file 'quantecon' 'version py' fl = open filename 'w' try fl write doc finally fl close
4686
def write_version_py(filename=None): doc = '"""\nThis is a VERSION file and should NOT be manually altered\n"""' doc += ("\nversion = '%s'" % VERSION) if (not filename): filename = os.path.join(os.path.dirname(__file__), 'quantecon', 'version.py') fl = open(filename, 'w') try: fl.write(doc) finally: fl.clos...
This constructs a version file for the project
this constructs a version file for the project
Question: What does this function do? Code: def write_version_py(filename=None): doc = '"""\nThis is a VERSION file and should NOT be manually altered\n"""' doc += ("\nversion = '%s'" % VERSION) if (not filename): filename = os.path.join(os.path.dirname(__file__), 'quantecon', 'version.py') fl = open(filename,...
null
null
null
What does this function do?
@cronjobs.register def reload_question_traffic_stats(): if settings.STAGE: return QuestionVisits.reload_from_analytics(verbose=settings.DEBUG)
null
null
null
Reload question views from the analytics.
pcsd
@cronjobs register def reload question traffic stats if settings STAGE return Question Visits reload from analytics verbose=settings DEBUG
4690
@cronjobs.register def reload_question_traffic_stats(): if settings.STAGE: return QuestionVisits.reload_from_analytics(verbose=settings.DEBUG)
Reload question views from the analytics.
reload question views from the analytics .
Question: What does this function do? Code: @cronjobs.register def reload_question_traffic_stats(): if settings.STAGE: return QuestionVisits.reload_from_analytics(verbose=settings.DEBUG)
null
null
null
What does this function do?
def get_scheme_names(): return tuple(sorted(_INSTALL_SCHEMES))
null
null
null
Return a tuple containing the schemes names.
pcsd
def get scheme names return tuple sorted INSTALL SCHEMES
4698
def get_scheme_names(): return tuple(sorted(_INSTALL_SCHEMES))
Return a tuple containing the schemes names.
return a tuple containing the schemes names .
Question: What does this function do? Code: def get_scheme_names(): return tuple(sorted(_INSTALL_SCHEMES))
null
null
null
What does this function do?
def constant(x, axis, depth, value): chunks = list(x.chunks) chunks[axis] = (depth,) c = wrap.full(tuple(map(sum, chunks)), value, chunks=tuple(chunks), dtype=x.dtype) return concatenate([c, x, c], axis=axis)
null
null
null
Add constant slice to either side of array
pcsd
def constant x axis depth value chunks = list x chunks chunks[axis] = depth c = wrap full tuple map sum chunks value chunks=tuple chunks dtype=x dtype return concatenate [c x c] axis=axis
4703
def constant(x, axis, depth, value): chunks = list(x.chunks) chunks[axis] = (depth,) c = wrap.full(tuple(map(sum, chunks)), value, chunks=tuple(chunks), dtype=x.dtype) return concatenate([c, x, c], axis=axis)
Add constant slice to either side of array
add constant slice to either side of array
Question: What does this function do? Code: def constant(x, axis, depth, value): chunks = list(x.chunks) chunks[axis] = (depth,) c = wrap.full(tuple(map(sum, chunks)), value, chunks=tuple(chunks), dtype=x.dtype) return concatenate([c, x, c], axis=axis)
null
null
null
What does this function do?
def obtain_device_type(model): if ('881' in model): return 'router' else: return None
null
null
null
Determine the device_type based on the model
pcsd
def obtain device type model if '881' in model return 'router' else return None
4706
def obtain_device_type(model): if ('881' in model): return 'router' else: return None
Determine the device_type based on the model
determine the device _ type based on the model
Question: What does this function do? Code: def obtain_device_type(model): if ('881' in model): return 'router' else: return None
null
null
null
What does this function do?
def get_static_index_page(with_shutdown): template = '\n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">\n<HTML>\n <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser\n Copyright (C) 2001-2017 NLTK Project\n Author:...
null
null
null
Get the static index page.
pcsd
def get static index page with shutdown template = ' <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 01 Frameset//EN" "http //www w3 org/TR/html4/frameset dtd"> <HTML> <!-- Natural Language Toolkit Wordnet Interface Graphical Wordnet Browser Copyright C 2001-2017 NLTK Project Author Jussi Salmela <jtsalmela@users sourceforge...
4708
def get_static_index_page(with_shutdown): template = '\n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">\n<HTML>\n <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser\n Copyright (C) 2001-2017 NLTK Project\n Author:...
Get the static index page.
get the static index page .
Question: What does this function do? Code: def get_static_index_page(with_shutdown): template = '\n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">\n<HTML>\n <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser\n Copyright ...
null
null
null
What does this function do?
@register.filter(is_safe=True) @stringfilter def force_escape(value): return mark_safe(escape(value))
null
null
null
Escapes a string\'s HTML. This returns a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping).
pcsd
@register filter is safe=True @stringfilter def force escape value return mark safe escape value
4710
@register.filter(is_safe=True) @stringfilter def force_escape(value): return mark_safe(escape(value))
Escapes a string\'s HTML. This returns a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping).
escapes a strings html .
Question: What does this function do? Code: @register.filter(is_safe=True) @stringfilter def force_escape(value): return mark_safe(escape(value))
null
null
null
What does this function do?
@auth.s3_requires_membership(1) def tag(): tablename = ('%s_%s' % (module, resourcename)) table = s3db[tablename] s3db.load_all_models() table.resource.requires = IS_IN_SET(db.tables) s3db.configure(tablename, listadd=False) return s3_rest_controller()
null
null
null
RESTful CRUD controller
pcsd
@auth s3 requires membership 1 def tag tablename = '%s %s' % module resourcename table = s3db[tablename] s3db load all models table resource requires = IS IN SET db tables s3db configure tablename listadd=False return s3 rest controller
4717
@auth.s3_requires_membership(1) def tag(): tablename = ('%s_%s' % (module, resourcename)) table = s3db[tablename] s3db.load_all_models() table.resource.requires = IS_IN_SET(db.tables) s3db.configure(tablename, listadd=False) return s3_rest_controller()
RESTful CRUD controller
restful crud controller
Question: What does this function do? Code: @auth.s3_requires_membership(1) def tag(): tablename = ('%s_%s' % (module, resourcename)) table = s3db[tablename] s3db.load_all_models() table.resource.requires = IS_IN_SET(db.tables) s3db.configure(tablename, listadd=False) return s3_rest_controller()
null
null
null
What does this function do?
def tokey(*args): salt = u'||'.join([force_text(arg) for arg in args]) hash_ = hashlib.md5(encode(salt)) return hash_.hexdigest()
null
null
null
Computes a unique key from arguments given.
pcsd
def tokey *args salt = u'||' join [force text arg for arg in args] hash = hashlib md5 encode salt return hash hexdigest
4737
def tokey(*args): salt = u'||'.join([force_text(arg) for arg in args]) hash_ = hashlib.md5(encode(salt)) return hash_.hexdigest()
Computes a unique key from arguments given.
computes a unique key from arguments given .
Question: What does this function do? Code: def tokey(*args): salt = u'||'.join([force_text(arg) for arg in args]) hash_ = hashlib.md5(encode(salt)) return hash_.hexdigest()
null
null
null
What does this function do?
def softmax(p): if p: v = p.values() m = max(v) e = map((lambda x: exp((x - m))), v) s = sum(e) v = map((lambda x: (x / s)), e) p = defaultdict(float, zip(p.keys(), v)) return p
null
null
null
Returns a dict with float values that sum to 1.0 (using generalized logistic regression).
pcsd
def softmax p if p v = p values m = max v e = map lambda x exp x - m v s = sum e v = map lambda x x / s e p = defaultdict float zip p keys v return p
4741
def softmax(p): if p: v = p.values() m = max(v) e = map((lambda x: exp((x - m))), v) s = sum(e) v = map((lambda x: (x / s)), e) p = defaultdict(float, zip(p.keys(), v)) return p
Returns a dict with float values that sum to 1.0 (using generalized logistic regression).
returns a dict with float values that sum to 1 . 0 .
Question: What does this function do? Code: def softmax(p): if p: v = p.values() m = max(v) e = map((lambda x: exp((x - m))), v) s = sum(e) v = map((lambda x: (x / s)), e) p = defaultdict(float, zip(p.keys(), v)) return p
null
null
null
What does this function do?
def CreateSitemapFromFile(configpath, suppress_notify): num_errors = output.num_errors sitemap = Sitemap(suppress_notify) try: output.Log(('Reading configuration file: %s' % configpath), 0) xml.sax.parse(configpath, sitemap) except IOError: output.Error(('Cannot read configuration file: %s' % configpath)) ex...
null
null
null
Sets up a new Sitemap object from the specified configuration file.
pcsd
def Create Sitemap From File configpath suppress notify num errors = output num errors sitemap = Sitemap suppress notify try output Log 'Reading configuration file %s' % configpath 0 xml sax parse configpath sitemap except IO Error output Error 'Cannot read configuration file %s' % configpath except xml sax exceptions ...
4744
def CreateSitemapFromFile(configpath, suppress_notify): num_errors = output.num_errors sitemap = Sitemap(suppress_notify) try: output.Log(('Reading configuration file: %s' % configpath), 0) xml.sax.parse(configpath, sitemap) except IOError: output.Error(('Cannot read configuration file: %s' % configpath)) ex...
Sets up a new Sitemap object from the specified configuration file.
sets up a new sitemap object from the specified configuration file .
Question: What does this function do? Code: def CreateSitemapFromFile(configpath, suppress_notify): num_errors = output.num_errors sitemap = Sitemap(suppress_notify) try: output.Log(('Reading configuration file: %s' % configpath), 0) xml.sax.parse(configpath, sitemap) except IOError: output.Error(('Cannot ...
null
null
null
What does this function do?
def connect_to_cloudservers(region=None, context=None, verify_ssl=None, **kwargs): context = (context or identity) _cs_auth_plugin.discover_auth_systems() id_type = get_setting('identity_type') if (id_type != 'keystone'): auth_plugin = _cs_auth_plugin.load_plugin(id_type) else: auth_plugin = None region = _sa...
null
null
null
Creates a client for working with cloud servers.
pcsd
def connect to cloudservers region=None context=None verify ssl=None **kwargs context = context or identity cs auth plugin discover auth systems id type = get setting 'identity type' if id type != 'keystone' auth plugin = cs auth plugin load plugin id type else auth plugin = None region = safe region region context=con...
4747
def connect_to_cloudservers(region=None, context=None, verify_ssl=None, **kwargs): context = (context or identity) _cs_auth_plugin.discover_auth_systems() id_type = get_setting('identity_type') if (id_type != 'keystone'): auth_plugin = _cs_auth_plugin.load_plugin(id_type) else: auth_plugin = None region = _sa...
Creates a client for working with cloud servers.
creates a client for working with cloud servers .
Question: What does this function do? Code: def connect_to_cloudservers(region=None, context=None, verify_ssl=None, **kwargs): context = (context or identity) _cs_auth_plugin.discover_auth_systems() id_type = get_setting('identity_type') if (id_type != 'keystone'): auth_plugin = _cs_auth_plugin.load_plugin(id_...
null
null
null
What does this function do?
def write_requirements(sources=None, fixed_requirements=None, output_file=None, skip=None): skip = (skip or []) requirements = merge_source_requirements(sources) fixed = load_requirements(locate_file(fixed_requirements, must_exist=True)) fixedreq_hash = {} for req in fixed: project_name = req.name if (not req....
null
null
null
Write resulting requirements taking versions from the fixed_requirements.
pcsd
def write requirements sources=None fixed requirements=None output file=None skip=None skip = skip or [] requirements = merge source requirements sources fixed = load requirements locate file fixed requirements must exist=True fixedreq hash = {} for req in fixed project name = req name if not req req continue if projec...
4760
def write_requirements(sources=None, fixed_requirements=None, output_file=None, skip=None): skip = (skip or []) requirements = merge_source_requirements(sources) fixed = load_requirements(locate_file(fixed_requirements, must_exist=True)) fixedreq_hash = {} for req in fixed: project_name = req.name if (not req....
Write resulting requirements taking versions from the fixed_requirements.
write resulting requirements taking versions from the fixed _ requirements .
Question: What does this function do? Code: def write_requirements(sources=None, fixed_requirements=None, output_file=None, skip=None): skip = (skip or []) requirements = merge_source_requirements(sources) fixed = load_requirements(locate_file(fixed_requirements, must_exist=True)) fixedreq_hash = {} for req in ...
null
null
null
What does this function do?
def auto_auth(browser, username, email, staff, course_id): AutoAuthPage(browser, username=username, email=email, course_id=course_id, staff=staff).visit()
null
null
null
Logout and login with given credentials.
pcsd
def auto auth browser username email staff course id Auto Auth Page browser username=username email=email course id=course id staff=staff visit
4768
def auto_auth(browser, username, email, staff, course_id): AutoAuthPage(browser, username=username, email=email, course_id=course_id, staff=staff).visit()
Logout and login with given credentials.
logout and login with given credentials .
Question: What does this function do? Code: def auto_auth(browser, username, email, staff, course_id): AutoAuthPage(browser, username=username, email=email, course_id=course_id, staff=staff).visit()
null
null
null
What does this function do?
@step('{word:w} step passes') def step_passes(context, word): pass
null
null
null
Step that always fails, mostly needed in examples.
pcsd
@step '{word w} step passes' def step passes context word pass
4770
@step('{word:w} step passes') def step_passes(context, word): pass
Step that always fails, mostly needed in examples.
step that always fails , mostly needed in examples .
Question: What does this function do? Code: @step('{word:w} step passes') def step_passes(context, word): pass
null
null
null
What does this function do?
def _is_ipv6_enabled(): if socket.has_ipv6: sock = None try: sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.bind((HOSTv6, 0)) return True except socket.error: pass finally: if sock: sock.close() return False
null
null
null
Check whether IPv6 is enabled on this host.
pcsd
def is ipv6 enabled if socket has ipv6 sock = None try sock = socket socket socket AF INET6 socket SOCK STREAM sock bind HOS Tv6 0 return True except socket error pass finally if sock sock close return False
4771
def _is_ipv6_enabled(): if socket.has_ipv6: sock = None try: sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.bind((HOSTv6, 0)) return True except socket.error: pass finally: if sock: sock.close() return False
Check whether IPv6 is enabled on this host.
check whether ipv6 is enabled on this host .
Question: What does this function do? Code: def _is_ipv6_enabled(): if socket.has_ipv6: sock = None try: sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.bind((HOSTv6, 0)) return True except socket.error: pass finally: if sock: sock.close() return False
null
null
null
What does this function do?
@content_type('application/x-www-form-urlencoded') def urlencoded(body, charset='ascii', **kwargs): return parse_query_string(text(body, charset=charset), False)
null
null
null
Converts query strings into native Python objects
pcsd
@content type 'application/x-www-form-urlencoded' def urlencoded body charset='ascii' **kwargs return parse query string text body charset=charset False
4773
@content_type('application/x-www-form-urlencoded') def urlencoded(body, charset='ascii', **kwargs): return parse_query_string(text(body, charset=charset), False)
Converts query strings into native Python objects
converts query strings into native python objects
Question: What does this function do? Code: @content_type('application/x-www-form-urlencoded') def urlencoded(body, charset='ascii', **kwargs): return parse_query_string(text(body, charset=charset), False)
null
null
null
What does this function do?
def _lenient_lowercase(lst): lowered = [] for value in lst: try: lowered.append(value.lower()) except AttributeError: lowered.append(value) return lowered
null
null
null
Lowercase elements of a list. If an element is not a string, pass it through untouched.
pcsd
def lenient lowercase lst lowered = [] for value in lst try lowered append value lower except Attribute Error lowered append value return lowered
4785
def _lenient_lowercase(lst): lowered = [] for value in lst: try: lowered.append(value.lower()) except AttributeError: lowered.append(value) return lowered
Lowercase elements of a list. If an element is not a string, pass it through untouched.
lowercase elements of a list .
Question: What does this function do? Code: def _lenient_lowercase(lst): lowered = [] for value in lst: try: lowered.append(value.lower()) except AttributeError: lowered.append(value) return lowered
null
null
null
What does this function do?
def cancel_subscription(customer_id, subscription_id): try: customer = stripe.Customer.retrieve(customer_id) if hasattr(customer, 'subscriptions'): subscription = customer.subscriptions.retrieve(subscription_id) return subscription.delete() except stripe.error.StripeError: pass
null
null
null
Cancel Stripe subscription, if it exists
pcsd
def cancel subscription customer id subscription id try customer = stripe Customer retrieve customer id if hasattr customer 'subscriptions' subscription = customer subscriptions retrieve subscription id return subscription delete except stripe error Stripe Error pass
4790
def cancel_subscription(customer_id, subscription_id): try: customer = stripe.Customer.retrieve(customer_id) if hasattr(customer, 'subscriptions'): subscription = customer.subscriptions.retrieve(subscription_id) return subscription.delete() except stripe.error.StripeError: pass
Cancel Stripe subscription, if it exists
cancel stripe subscription , if it exists
Question: What does this function do? Code: def cancel_subscription(customer_id, subscription_id): try: customer = stripe.Customer.retrieve(customer_id) if hasattr(customer, 'subscriptions'): subscription = customer.subscriptions.retrieve(subscription_id) return subscription.delete() except stripe.error....
null
null
null
What does this function do?
def authenticate(endpoint, token, login_user, login_password, login_tenant_name): if token: return client.Client(endpoint=endpoint, token=token) else: return client.Client(auth_url=endpoint, username=login_user, password=login_password, tenant_name=login_tenant_name)
null
null
null
Return a keystone client object
pcsd
def authenticate endpoint token login user login password login tenant name if token return client Client endpoint=endpoint token=token else return client Client auth url=endpoint username=login user password=login password tenant name=login tenant name
4799
def authenticate(endpoint, token, login_user, login_password, login_tenant_name): if token: return client.Client(endpoint=endpoint, token=token) else: return client.Client(auth_url=endpoint, username=login_user, password=login_password, tenant_name=login_tenant_name)
Return a keystone client object
return a keystone client object
Question: What does this function do? Code: def authenticate(endpoint, token, login_user, login_password, login_tenant_name): if token: return client.Client(endpoint=endpoint, token=token) else: return client.Client(auth_url=endpoint, username=login_user, password=login_password, tenant_name=login_tenant_name)...
null
null
null
What does this function do?
def get_temperature_from_humidity(): return _sensehat.get_temperature_from_humidity()
null
null
null
Gets the temperature in degrees Celsius from the humidity sensor.
pcsd
def get temperature from humidity return sensehat get temperature from humidity
4801
def get_temperature_from_humidity(): return _sensehat.get_temperature_from_humidity()
Gets the temperature in degrees Celsius from the humidity sensor.
gets the temperature in degrees celsius from the humidity sensor .
Question: What does this function do? Code: def get_temperature_from_humidity(): return _sensehat.get_temperature_from_humidity()
null
null
null
What does this function do?
def _proj_equal(a, b, check_active=True): equal = (((a['active'] == b['active']) or (not check_active)) and (a['kind'] == b['kind']) and (a['desc'] == b['desc']) and (a['data']['col_names'] == b['data']['col_names']) and (a['data']['row_names'] == b['data']['row_names']) and (a['data']['ncol'] == b['data']['ncol']) an...
null
null
null
Test if two projectors are equal.
pcsd
def proj equal a b check active=True equal = a['active'] == b['active'] or not check active and a['kind'] == b['kind'] and a['desc'] == b['desc'] and a['data']['col names'] == b['data']['col names'] and a['data']['row names'] == b['data']['row names'] and a['data']['ncol'] == b['data']['ncol'] and a['data']['nrow'] == ...
4802
def _proj_equal(a, b, check_active=True): equal = (((a['active'] == b['active']) or (not check_active)) and (a['kind'] == b['kind']) and (a['desc'] == b['desc']) and (a['data']['col_names'] == b['data']['col_names']) and (a['data']['row_names'] == b['data']['row_names']) and (a['data']['ncol'] == b['data']['ncol']) an...
Test if two projectors are equal.
test if two projectors are equal .
Question: What does this function do? Code: def _proj_equal(a, b, check_active=True): equal = (((a['active'] == b['active']) or (not check_active)) and (a['kind'] == b['kind']) and (a['desc'] == b['desc']) and (a['data']['col_names'] == b['data']['col_names']) and (a['data']['row_names'] == b['data']['row_names']) ...