id_within_dataset int64 1 55.5k | snippet stringlengths 19 14.2k | tokens listlengths 6 1.63k | nl stringlengths 6 352 | split_within_dataset stringclasses 1 value | is_duplicated bool 2 classes |
|---|---|---|---|---|---|
51,300 | def euclidean(x, y):
return sqrt(sum((((a - b) ** 2) for (a, b) in zip(x, y))))
| [
"def",
"euclidean",
"(",
"x",
",",
"y",
")",
":",
"return",
"sqrt",
"(",
"sum",
"(",
"(",
"(",
"(",
"a",
"-",
"b",
")",
"**",
"2",
")",
"for",
"(",
"a",
",",
"b",
")",
"in",
"zip",
"(",
"x",
",",
"y",
")",
")",
")",
")"
] | returns the euclidean distance between the vectors x and y . | train | false |
51,302 | def isValidHostname(hostname):
if (len(hostname) > 255):
return False
if (hostname[(-1):] == '.'):
hostname = hostname[:(-1)]
allowed = re.compile('(?!-)[A-Z\\d-]{1,63}(?<!-)$', re.IGNORECASE)
return all((allowed.match(x) for x in hostname.split('.')))
| [
"def",
"isValidHostname",
"(",
"hostname",
")",
":",
"if",
"(",
"len",
"(",
"hostname",
")",
">",
"255",
")",
":",
"return",
"False",
"if",
"(",
"hostname",
"[",
"(",
"-",
"1",
")",
":",
"]",
"==",
"'.'",
")",
":",
"hostname",
"=",
"hostname",
"[... | try to validate the passed host name . | train | true |
51,303 | def cxUniformPartialyMatched(ind1, ind2, indpb):
size = min(len(ind1), len(ind2))
(p1, p2) = (([0] * size), ([0] * size))
for i in xrange(size):
p1[ind1[i]] = i
p2[ind2[i]] = i
for i in xrange(size):
if (random.random() < indpb):
temp1 = ind1[i]
temp2 = ind2[i]
(ind1[i], ind1[p1[temp2]]) = (temp2, temp1)
(ind2[i], ind2[p2[temp1]]) = (temp1, temp2)
(p1[temp1], p1[temp2]) = (p1[temp2], p1[temp1])
(p2[temp1], p2[temp2]) = (p2[temp2], p2[temp1])
return (ind1, ind2)
| [
"def",
"cxUniformPartialyMatched",
"(",
"ind1",
",",
"ind2",
",",
"indpb",
")",
":",
"size",
"=",
"min",
"(",
"len",
"(",
"ind1",
")",
",",
"len",
"(",
"ind2",
")",
")",
"(",
"p1",
",",
"p2",
")",
"=",
"(",
"(",
"[",
"0",
"]",
"*",
"size",
")... | executes a uniform partially matched crossover on the input individuals . | train | false |
51,304 | def IsCppString(line):
line = line.replace('\\\\', 'XX')
return ((((line.count('"') - line.count('\\"')) - line.count('\'"\'')) & 1) == 1)
| [
"def",
"IsCppString",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"'XX'",
")",
"return",
"(",
"(",
"(",
"(",
"line",
".",
"count",
"(",
"'\"'",
")",
"-",
"line",
".",
"count",
"(",
"'\\\\\"'",
")",
")",
"-"... | does line terminate so . | train | false |
51,305 | def sublist_reverse(lst, a, b):
while (b > a):
(lst[a], lst[b]) = (lst[b], lst[a])
b -= 1
a += 1
| [
"def",
"sublist_reverse",
"(",
"lst",
",",
"a",
",",
"b",
")",
":",
"while",
"(",
"b",
">",
"a",
")",
":",
"(",
"lst",
"[",
"a",
"]",
",",
"lst",
"[",
"b",
"]",
")",
"=",
"(",
"lst",
"[",
"b",
"]",
",",
"lst",
"[",
"a",
"]",
")",
"b",
... | reverses the elements lst[a:b] . | train | false |
51,307 | def build_network_settings(**settings):
current_network_settings = _parse_rh_config(_RH_NETWORK_FILE)
opts = _parse_network_settings(settings, current_network_settings)
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if settings['test']:
return _read_temp(network)
_write_file_network(network, _RH_NETWORK_FILE)
return _read_file(_RH_NETWORK_FILE)
| [
"def",
"build_network_settings",
"(",
"**",
"settings",
")",
":",
"current_network_settings",
"=",
"_parse_rh_config",
"(",
"_RH_NETWORK_FILE",
")",
"opts",
"=",
"_parse_network_settings",
"(",
"settings",
",",
"current_network_settings",
")",
"try",
":",
"template",
... | build the global network script . | train | true |
51,308 | def cache_model(model, timeout=None):
if hasattr(model, 'get_cached'):
return
def clear_cache(sender, instance, *args, **kwargs):
'\n Clears the cache for the given instance.\n '
delete_instance(sender, instance)
post_save.connect(clear_cache, sender=model, weak=False)
post_delete.connect(clear_cache, sender=model, weak=False)
@classmethod
def get(cls, pk, using=None):
'\n Returns the model for the given primary key (pk).\n '
if (pk is None):
return None
return get_instance(cls, pk, timeout, using)
model.get_cached = get
| [
"def",
"cache_model",
"(",
"model",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"model",
",",
"'get_cached'",
")",
":",
"return",
"def",
"clear_cache",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
... | adds utility methods to the given model to obtain foreignkey instances via the cache . | train | false |
51,309 | @login_required
def upload_manifest(*args, **kwargs):
return _upload_manifest(*args, **kwargs)
| [
"@",
"login_required",
"def",
"upload_manifest",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"_upload_manifest",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | wrapper function for _upload_manifest so we can keep the standalone validator separate from the manifest upload stuff . | train | false |
51,310 | @given(u'we have pgcli installed')
def step_install_cli(_):
dists = set([di.key for di in pip.get_installed_distributions()])
assert (u'pgcli' in dists)
| [
"@",
"given",
"(",
"u'we have pgcli installed'",
")",
"def",
"step_install_cli",
"(",
"_",
")",
":",
"dists",
"=",
"set",
"(",
"[",
"di",
".",
"key",
"for",
"di",
"in",
"pip",
".",
"get_installed_distributions",
"(",
")",
"]",
")",
"assert",
"(",
"u'pgcl... | check that pgcli is in installed modules . | train | false |
51,311 | def p_command_def_bad_rhs(p):
p[0] = 'BAD EXPRESSION IN DEF STATEMENT'
| [
"def",
"p_command_def_bad_rhs",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"'BAD EXPRESSION IN DEF STATEMENT'"
] | command : def id lparen id rparen equals error . | train | false |
51,312 | def track_from_id(identifier, timeout=DEFAULT_ASYNC_TIMEOUT):
param_dict = dict(id=identifier)
return _profile(param_dict, timeout)
| [
"def",
"track_from_id",
"(",
"identifier",
",",
"timeout",
"=",
"DEFAULT_ASYNC_TIMEOUT",
")",
":",
"param_dict",
"=",
"dict",
"(",
"id",
"=",
"identifier",
")",
"return",
"_profile",
"(",
"param_dict",
",",
"timeout",
")"
] | create a track object from an echo nest track id . | train | true |
51,313 | def get_taskqueue_nodes():
nodes = file_io.read(constants.TASKQUEUE_NODE_FILE)
nodes = nodes.split('\n')
if (nodes[(-1)] == ''):
nodes = nodes[:(-1)]
return nodes
| [
"def",
"get_taskqueue_nodes",
"(",
")",
":",
"nodes",
"=",
"file_io",
".",
"read",
"(",
"constants",
".",
"TASKQUEUE_NODE_FILE",
")",
"nodes",
"=",
"nodes",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"nodes",
"[",
"(",
"-",
"1",
")",
"]",
"==",
"''"... | returns a list of all the taskqueue nodes . | train | false |
51,314 | def inner(a, b):
a_ndim = a.ndim
b_ndim = b.ndim
if ((a_ndim == 0) or (b_ndim == 0)):
return cupy.multiply(a, b)
a_axis = (a_ndim - 1)
b_axis = (b_ndim - 1)
if (a.shape[(-1)] != b.shape[(-1)]):
raise ValueError('Axis dimension mismatch')
if a_axis:
a = cupy.rollaxis(a, a_axis, 0)
if b_axis:
b = cupy.rollaxis(b, b_axis, 0)
ret_shape = (a.shape[1:] + b.shape[1:])
k = a.shape[0]
n = (a.size // k)
m = (b.size // k)
return core.tensordot_core(a, b, None, n, m, k, ret_shape)
| [
"def",
"inner",
"(",
"a",
",",
"b",
")",
":",
"a_ndim",
"=",
"a",
".",
"ndim",
"b_ndim",
"=",
"b",
".",
"ndim",
"if",
"(",
"(",
"a_ndim",
"==",
"0",
")",
"or",
"(",
"b_ndim",
"==",
"0",
")",
")",
":",
"return",
"cupy",
".",
"multiply",
"(",
... | returns the inner product of two arrays . | train | false |
51,315 | def complete_course_mode_info(course_id, enrollment, modes=None):
if (modes is None):
modes = CourseMode.modes_for_course_dict(course_id)
mode_info = {'show_upsell': False, 'days_for_upsell': None}
if ((CourseMode.VERIFIED in modes) and (enrollment.mode in CourseMode.UPSELL_TO_VERIFIED_MODES)):
mode_info['show_upsell'] = True
mode_info['verified_sku'] = modes['verified'].sku
mode_info['verified_bulk_sku'] = modes['verified'].bulk_sku
if modes['verified'].expiration_datetime:
today = datetime.datetime.now(UTC).date()
mode_info['days_for_upsell'] = (modes['verified'].expiration_datetime.date() - today).days
return mode_info
| [
"def",
"complete_course_mode_info",
"(",
"course_id",
",",
"enrollment",
",",
"modes",
"=",
"None",
")",
":",
"if",
"(",
"modes",
"is",
"None",
")",
":",
"modes",
"=",
"CourseMode",
".",
"modes_for_course_dict",
"(",
"course_id",
")",
"mode_info",
"=",
"{",
... | we would like to compute some more information from the given course modes and the users current enrollment returns the given information: - whether to show the course upsell information - numbers of days until they cant upsell anymore . | train | false |
51,316 | def parse_qs(qs, keep_blank_values=0, strict_parsing=0, unquote=unquote):
d = {}
items = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
for item in items:
try:
(k, v) = item.split('=', 1)
except ValueError:
if strict_parsing:
raise
continue
if (v or keep_blank_values):
k = unquote(k.replace('+', ' '))
v = unquote(v.replace('+', ' '))
if (k in d):
d[k].append(v)
else:
d[k] = [v]
return d
| [
"def",
"parse_qs",
"(",
"qs",
",",
"keep_blank_values",
"=",
"0",
",",
"strict_parsing",
"=",
"0",
",",
"unquote",
"=",
"unquote",
")",
":",
"d",
"=",
"{",
"}",
"items",
"=",
"[",
"s2",
"for",
"s1",
"in",
"qs",
".",
"split",
"(",
"'&'",
")",
"for... | parse a query given as a string argument . | train | false |
51,317 | def _absolute_url_staticfile(is_secure, name):
url_path = staticfiles_storage.url(name)
if urlparse.urlparse(url_path).netloc:
return url_path
return _absolute_url(is_secure, url_path)
| [
"def",
"_absolute_url_staticfile",
"(",
"is_secure",
",",
"name",
")",
":",
"url_path",
"=",
"staticfiles_storage",
".",
"url",
"(",
"name",
")",
"if",
"urlparse",
".",
"urlparse",
"(",
"url_path",
")",
".",
"netloc",
":",
"return",
"url_path",
"return",
"_a... | construct an absolute url to a static resource on the site . | train | false |
51,318 | def ordered_set(iterable):
mmap = {}
ord_set = []
for item in iterable:
if (item not in mmap):
mmap[item] = 1
ord_set.append(item)
return ord_set
| [
"def",
"ordered_set",
"(",
"iterable",
")",
":",
"mmap",
"=",
"{",
"}",
"ord_set",
"=",
"[",
"]",
"for",
"item",
"in",
"iterable",
":",
"if",
"(",
"item",
"not",
"in",
"mmap",
")",
":",
"mmap",
"[",
"item",
"]",
"=",
"1",
"ord_set",
".",
"append"... | creates an ordered list from strings . | train | false |
51,319 | def has_nibabel(vox2ras_tkr=False):
try:
import nibabel
out = True
if vox2ras_tkr:
out = (getattr(getattr(getattr(nibabel, 'MGHImage', 0), 'header_class', 0), 'get_vox2ras_tkr', None) is not None)
return out
except ImportError:
return False
| [
"def",
"has_nibabel",
"(",
"vox2ras_tkr",
"=",
"False",
")",
":",
"try",
":",
"import",
"nibabel",
"out",
"=",
"True",
"if",
"vox2ras_tkr",
":",
"out",
"=",
"(",
"getattr",
"(",
"getattr",
"(",
"getattr",
"(",
"nibabel",
",",
"'MGHImage'",
",",
"0",
")... | determine if nibabel is installed . | train | false |
51,320 | def default_json_error(ex):
logger = get_logger()
logger.error('Uncaught error thrown by Flask/Werkzeug', exc_info=ex)
response = jsonify(message=str(ex), type='api_error')
response.status_code = (ex.code if isinstance(ex, HTTPException) else 500)
return response
| [
"def",
"default_json_error",
"(",
"ex",
")",
":",
"logger",
"=",
"get_logger",
"(",
")",
"logger",
".",
"error",
"(",
"'Uncaught error thrown by Flask/Werkzeug'",
",",
"exc_info",
"=",
"ex",
")",
"response",
"=",
"jsonify",
"(",
"message",
"=",
"str",
"(",
"... | exception -> flask json responder . | train | false |
51,321 | def get_user_objects(current_user, user):
objects = dict(USER_OBJECTS)
for key in objects:
if hasattr(user, key):
manager = getattr(user, key)
try:
manager = manager.filter(status__hidden=False)
except:
pass
objects[key]['objects'] = Object.filter_permitted(current_user, manager)
return objects
| [
"def",
"get_user_objects",
"(",
"current_user",
",",
"user",
")",
":",
"objects",
"=",
"dict",
"(",
"USER_OBJECTS",
")",
"for",
"key",
"in",
"objects",
":",
"if",
"hasattr",
"(",
"user",
",",
"key",
")",
":",
"manager",
"=",
"getattr",
"(",
"user",
","... | returns a dictionary with keys specified as contact attributes and values as dictionaries with labels and set of relevant objects . | train | false |
51,322 | @pytest.fixture(params=DISABLED_PROJECT_URL_PARAMS.keys())
def dp_view_urls(request, view_types):
kwargs = DISABLED_PROJECT_URL_PARAMS[request.param].copy()
view_name = kwargs.pop('view_name')
view_name = ('%s-%s' % (view_name, view_types))
return reverse(view_name, kwargs=kwargs)
| [
"@",
"pytest",
".",
"fixture",
"(",
"params",
"=",
"DISABLED_PROJECT_URL_PARAMS",
".",
"keys",
"(",
")",
")",
"def",
"dp_view_urls",
"(",
"request",
",",
"view_types",
")",
":",
"kwargs",
"=",
"DISABLED_PROJECT_URL_PARAMS",
"[",
"request",
".",
"param",
"]",
... | list of url params required for disabled project tests . | train | false |
51,323 | def length_gt(value, arg):
return (len(value) > int(arg))
| [
"def",
"length_gt",
"(",
"value",
",",
"arg",
")",
":",
"return",
"(",
"len",
"(",
"value",
")",
">",
"int",
"(",
"arg",
")",
")"
] | returns a boolean of whether the values length is greater than the argument . | train | false |
51,324 | def make_unifrac_metric(weighted, metric, is_symmetric):
def result(data, taxon_names, tree, sample_names, **kwargs):
' wraps the fast_unifrac fn to return just a matrix, in correct order\n\n sample_names: list of unique strings\n '
envs = make_envs_dict(data, sample_names, taxon_names)
unifrac_res = fast_unifrac(tree, envs, weighted=weighted, metric=metric, is_symmetric=is_symmetric, modes=['distance_matrix'], **kwargs)
dist_mtx = _reorder_unifrac_res(unifrac_res['distance_matrix'], sample_names)
return dist_mtx
return result
| [
"def",
"make_unifrac_metric",
"(",
"weighted",
",",
"metric",
",",
"is_symmetric",
")",
":",
"def",
"result",
"(",
"data",
",",
"taxon_names",
",",
"tree",
",",
"sample_names",
",",
"**",
"kwargs",
")",
":",
"envs",
"=",
"make_envs_dict",
"(",
"data",
",",... | make a unifrac-like metric . | train | false |
51,325 | def set_default_color_scheme(name, replace=True):
assert (name in sh.COLOR_SCHEME_NAMES)
set_color_scheme(name, sh.get_color_scheme(name), replace=replace)
| [
"def",
"set_default_color_scheme",
"(",
"name",
",",
"replace",
"=",
"True",
")",
":",
"assert",
"(",
"name",
"in",
"sh",
".",
"COLOR_SCHEME_NAMES",
")",
"set_color_scheme",
"(",
"name",
",",
"sh",
".",
"get_color_scheme",
"(",
"name",
")",
",",
"replace",
... | reset color scheme to default values . | train | true |
51,326 | def idd_findrank(eps, m, n, matvect):
(k, ra, ier) = _id.idd_findrank(eps, m, n, matvect)
if ier:
raise _RETCODE_ERROR
return k
| [
"def",
"idd_findrank",
"(",
"eps",
",",
"m",
",",
"n",
",",
"matvect",
")",
":",
"(",
"k",
",",
"ra",
",",
"ier",
")",
"=",
"_id",
".",
"idd_findrank",
"(",
"eps",
",",
"m",
",",
"n",
",",
"matvect",
")",
"if",
"ier",
":",
"raise",
"_RETCODE_ER... | estimate rank of a real matrix to a specified relative precision using random matrix-vector multiplication . | train | false |
51,327 | def print_formatters(title=None, stream=None):
from behave.formatter._registry import format_items
from operator import itemgetter
if (stream is None):
stream = sys.stdout
if title:
stream.write((u'%s\n' % title))
format_items = sorted(format_items(resolved=True), key=itemgetter(0))
format_names = [item[0] for item in format_items]
column_size = compute_words_maxsize(format_names)
schema = ((u' %-' + _text(column_size)) + 's %s\n')
for (name, formatter_class) in format_items:
formatter_description = getattr(formatter_class, 'description', '')
stream.write((schema % (name, formatter_description)))
| [
"def",
"print_formatters",
"(",
"title",
"=",
"None",
",",
"stream",
"=",
"None",
")",
":",
"from",
"behave",
".",
"formatter",
".",
"_registry",
"import",
"format_items",
"from",
"operator",
"import",
"itemgetter",
"if",
"(",
"stream",
"is",
"None",
")",
... | prints the list of available formatters and their description . | train | false |
51,328 | def inertia_of_point_mass(mass, pos_vec, frame):
return (mass * (((((frame.x | frame.x) + (frame.y | frame.y)) + (frame.z | frame.z)) * (pos_vec & pos_vec)) - (pos_vec | pos_vec)))
| [
"def",
"inertia_of_point_mass",
"(",
"mass",
",",
"pos_vec",
",",
"frame",
")",
":",
"return",
"(",
"mass",
"*",
"(",
"(",
"(",
"(",
"(",
"frame",
".",
"x",
"|",
"frame",
".",
"x",
")",
"+",
"(",
"frame",
".",
"y",
"|",
"frame",
".",
"y",
")",
... | inertia dyadic of a point mass relative to point o . | train | false |
51,329 | def _normalize_interval(start, end, value):
if (not isinstance(start, datetime)):
start = datetime.combine(start, START_OF_DAY)
end = datetime.combine(end, START_OF_DAY)
if (start.tzinfo is None):
start = pytz.UTC.localize(start)
end = pytz.UTC.localize(end)
else:
start = start.astimezone(pytz.UTC)
end = end.astimezone(pytz.UTC)
return (start, end)
| [
"def",
"_normalize_interval",
"(",
"start",
",",
"end",
",",
"value",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"start",
",",
"datetime",
")",
")",
":",
"start",
"=",
"datetime",
".",
"combine",
"(",
"start",
",",
"START_OF_DAY",
")",
"end",
"=",
... | normalize datetime intervals . | train | true |
51,330 | def _check_versions(current_release):
feconf_changed_version = []
git_show_cmd = (GIT_CMD_SHOW_FORMAT_STRING % current_release)
old_feconf = _run_cmd(git_show_cmd)
with open('feconf.py', 'r') as feconf:
new_feconf = feconf.read()
for variable in FECONF_VAR_NAMES:
old_version = re.findall((VERSION_RE_FORMAT_STRING % variable), old_feconf)[0]
new_version = re.findall((VERSION_RE_FORMAT_STRING % variable), new_feconf)[0]
if (old_version != new_version):
feconf_changed_version.append(variable)
return feconf_changed_version
| [
"def",
"_check_versions",
"(",
"current_release",
")",
":",
"feconf_changed_version",
"=",
"[",
"]",
"git_show_cmd",
"=",
"(",
"GIT_CMD_SHOW_FORMAT_STRING",
"%",
"current_release",
")",
"old_feconf",
"=",
"_run_cmd",
"(",
"git_show_cmd",
")",
"with",
"open",
"(",
... | checks if the versions for the exploration or collection schemas have changed . | train | false |
51,331 | def New_Page_Info(new_page):
dom = etree.HTML(new_page)
new_items = dom.xpath('//tr/td/a/text()')
new_urls = dom.xpath('//tr/td/a/@href')
assert (len(new_items) == len(new_urls))
return zip(new_items, new_urls)
| [
"def",
"New_Page_Info",
"(",
"new_page",
")",
":",
"dom",
"=",
"etree",
".",
"HTML",
"(",
"new_page",
")",
"new_items",
"=",
"dom",
".",
"xpath",
"(",
"'//tr/td/a/text()'",
")",
"new_urls",
"=",
"dom",
".",
"xpath",
"(",
"'//tr/td/a/@href'",
")",
"assert",... | regex or xpath . | train | false |
51,332 | def _write_credentials_file(credentials_file, credentials):
data = {'file_version': 2, 'credentials': {}}
for (key, credential) in iteritems(credentials):
credential_json = credential.to_json()
encoded_credential = _helpers._from_bytes(base64.b64encode(_helpers._to_bytes(credential_json)))
data['credentials'][key] = encoded_credential
credentials_file.seek(0)
json.dump(data, credentials_file)
credentials_file.truncate()
| [
"def",
"_write_credentials_file",
"(",
"credentials_file",
",",
"credentials",
")",
":",
"data",
"=",
"{",
"'file_version'",
":",
"2",
",",
"'credentials'",
":",
"{",
"}",
"}",
"for",
"(",
"key",
",",
"credential",
")",
"in",
"iteritems",
"(",
"credentials",... | writes credentials to a file . | train | true |
51,333 | def make_parser(parser_list=[]):
for parser_name in (parser_list + default_parser_list):
try:
return _create_parser(parser_name)
except ImportError as e:
import sys
if (parser_name in sys.modules):
raise
except SAXReaderNotAvailable:
pass
raise SAXReaderNotAvailable('No parsers found', None)
| [
"def",
"make_parser",
"(",
"parser_list",
"=",
"[",
"]",
")",
":",
"for",
"parser_name",
"in",
"(",
"parser_list",
"+",
"default_parser_list",
")",
":",
"try",
":",
"return",
"_create_parser",
"(",
"parser_name",
")",
"except",
"ImportError",
"as",
"e",
":",... | creates and returns a sax parser . | train | false |
51,334 | def raise_if_deadlock_error(operational_error, engine_name):
re = _DEADLOCK_RE_DB.get(engine_name)
if (re is None):
return
m = re.match(operational_error.message)
if (not m):
return
raise exception.DBDeadlock(operational_error)
| [
"def",
"raise_if_deadlock_error",
"(",
"operational_error",
",",
"engine_name",
")",
":",
"re",
"=",
"_DEADLOCK_RE_DB",
".",
"get",
"(",
"engine_name",
")",
"if",
"(",
"re",
"is",
"None",
")",
":",
"return",
"m",
"=",
"re",
".",
"match",
"(",
"operational_... | raise dbdeadlock exception if operationalerror contains a deadlock condition . | train | false |
51,335 | def _found_target_class(module, name):
members = inspect.getmembers(module, inspect.isclass)
return [x[1] for x in members if (x[0] == name.capitalize())][0]
| [
"def",
"_found_target_class",
"(",
"module",
",",
"name",
")",
":",
"members",
"=",
"inspect",
".",
"getmembers",
"(",
"module",
",",
"inspect",
".",
"isclass",
")",
"return",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"members",
"if",
"(",
"x",
"[",... | searches for a class with the specific name: it should be equal to capitalized $name . | train | false |
51,340 | def lqmn(m, n, z):
if ((not isscalar(m)) or (m < 0)):
raise ValueError('m must be a non-negative integer.')
if ((not isscalar(n)) or (n < 0)):
raise ValueError('n must be a non-negative integer.')
if (not isscalar(z)):
raise ValueError('z must be scalar.')
m = int(m)
n = int(n)
mm = max(1, m)
nn = max(1, n)
if iscomplex(z):
(q, qd) = specfun.clqmn(mm, nn, z)
else:
(q, qd) = specfun.lqmn(mm, nn, z)
return (q[:(m + 1), :(n + 1)], qd[:(m + 1), :(n + 1)])
| [
"def",
"lqmn",
"(",
"m",
",",
"n",
",",
"z",
")",
":",
"if",
"(",
"(",
"not",
"isscalar",
"(",
"m",
")",
")",
"or",
"(",
"m",
"<",
"0",
")",
")",
":",
"raise",
"ValueError",
"(",
"'m must be a non-negative integer.'",
")",
"if",
"(",
"(",
"not",
... | sequence of associated legendre functions of the second kind . | train | false |
51,341 | def pspace(expr):
expr = sympify(expr)
rvs = random_symbols(expr)
if (not rvs):
raise ValueError(('Expression containing Random Variable expected, not %s' % expr))
if all(((rv.pspace == rvs[0].pspace) for rv in rvs)):
return rvs[0].pspace
return ProductPSpace(*[rv.pspace for rv in rvs])
| [
"def",
"pspace",
"(",
"expr",
")",
":",
"expr",
"=",
"sympify",
"(",
"expr",
")",
"rvs",
"=",
"random_symbols",
"(",
"expr",
")",
"if",
"(",
"not",
"rvs",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Expression containing Random Variable expected, not %s'",
... | returns the underlying probability space of a random expression . | train | false |
51,342 | def get_object_as_xml(inst, cls=None, root_tag_name=None, no_namespace=False):
if (cls is None):
cls = inst.__class__
if ((cls.get_namespace() is None) and (no_namespace is None)):
no_namespace = True
if (no_namespace is None):
no_namespace = False
parent = etree.Element('parent')
xml_object.to_parent(None, cls, inst, parent, cls.get_namespace(), root_tag_name)
if no_namespace:
_dig(parent)
etree.cleanup_namespaces(parent)
return parent[0]
| [
"def",
"get_object_as_xml",
"(",
"inst",
",",
"cls",
"=",
"None",
",",
"root_tag_name",
"=",
"None",
",",
"no_namespace",
"=",
"False",
")",
":",
"if",
"(",
"cls",
"is",
"None",
")",
":",
"cls",
"=",
"inst",
".",
"__class__",
"if",
"(",
"(",
"cls",
... | returns an elementtree representation of a :class:spyne . | train | false |
51,344 | def convert_genepop_to_fdist(gp_rec, report_pops=None):
if hasattr(gp_rec, 'populations'):
return _convert_genepop_to_fdist(gp_rec)
else:
return _convert_genepop_to_fdist_big(gp_rec, report_pops)
| [
"def",
"convert_genepop_to_fdist",
"(",
"gp_rec",
",",
"report_pops",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"gp_rec",
",",
"'populations'",
")",
":",
"return",
"_convert_genepop_to_fdist",
"(",
"gp_rec",
")",
"else",
":",
"return",
"_convert_genepop_to_fdis... | converts a genepop record to a fdist one . | train | false |
51,345 | def test_preserve_refs():
text = u'la philologie mène au pire'
assert (strip_tags(text) == u'la philologie m\xe8ne au pire')
text = u'la philologie mène au pire'
assert (strip_tags(text) == u'la philologie m\xe8ne au pire')
text = u'veer & wander'
assert (strip_tags(text) == 'veer & wander')
| [
"def",
"test_preserve_refs",
"(",
")",
":",
"text",
"=",
"u'la philologie mène au pire'",
"assert",
"(",
"strip_tags",
"(",
"text",
")",
"==",
"u'la philologie m\\xe8ne au pire'",
")",
"text",
"=",
"u'la philologie mène au pire'",
"assert",
"(",
"strip_tags",
... | test that html character/entity references are preserved when we strip tags . | train | false |
51,347 | def set_output_volume(volume):
cmd = 'osascript -e "set volume output volume {0}"'.format(volume)
call = __salt__['cmd.run_all'](cmd, output_loglevel='debug', python_shell=False)
_check_cmd(call)
return get_output_volume()
| [
"def",
"set_output_volume",
"(",
"volume",
")",
":",
"cmd",
"=",
"'osascript -e \"set volume output volume {0}\"'",
".",
"format",
"(",
"volume",
")",
"call",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"output_loglevel",
"=",
"'debug'",
",",
"p... | set the volume of sound . | train | true |
51,348 | def components(f, x):
result = set()
if (x in f.free_symbols):
if f.is_Symbol:
result.add(f)
elif (f.is_Function or f.is_Derivative):
for g in f.args:
result |= components(g, x)
result.add(f)
elif f.is_Pow:
result |= components(f.base, x)
if (not f.exp.is_Integer):
if f.exp.is_Rational:
result.add((f.base ** Rational(1, f.exp.q)))
else:
result |= (components(f.exp, x) | {f})
else:
for g in f.args:
result |= components(g, x)
return result
| [
"def",
"components",
"(",
"f",
",",
"x",
")",
":",
"result",
"=",
"set",
"(",
")",
"if",
"(",
"x",
"in",
"f",
".",
"free_symbols",
")",
":",
"if",
"f",
".",
"is_Symbol",
":",
"result",
".",
"add",
"(",
"f",
")",
"elif",
"(",
"f",
".",
"is_Fun... | returns a set of all functional components of the given expression which includes symbols . | train | false |
51,349 | def knn_classify(k, labeled_points, new_point):
by_distance = sorted(labeled_points, key=(lambda (point, _): distance(point, new_point)))
k_nearest_labels = [label for (_, label) in by_distance[:k]]
return majority_vote(k_nearest_labels)
| [
"def",
"knn_classify",
"(",
"k",
",",
"labeled_points",
",",
"new_point",
")",
":",
"by_distance",
"=",
"sorted",
"(",
"labeled_points",
",",
"key",
"=",
"(",
"lambda",
"(",
"point",
",",
"_",
")",
":",
"distance",
"(",
"point",
",",
"new_point",
")",
... | each labeled point should be a pair . | train | false |
51,351 | def uptime(format=False):
uptime = (time() - SERVER_START_TIME)
if format:
return _format(uptime, 31536000, 2628000, 604800, 86400, 3600, 60)
return uptime
| [
"def",
"uptime",
"(",
"format",
"=",
"False",
")",
":",
"uptime",
"=",
"(",
"time",
"(",
")",
"-",
"SERVER_START_TIME",
")",
"if",
"format",
":",
"return",
"_format",
"(",
"uptime",
",",
"31536000",
",",
"2628000",
",",
"604800",
",",
"86400",
",",
"... | get system load average from startup . | train | false |
51,352 | def getInteriorOverhangRadians(elementNode):
return math.radians(getInteriorOverhangAngle(elementNode))
| [
"def",
"getInteriorOverhangRadians",
"(",
"elementNode",
")",
":",
"return",
"math",
".",
"radians",
"(",
"getInteriorOverhangAngle",
"(",
"elementNode",
")",
")"
] | get the interior overhang support angle in radians . | train | false |
51,354 | def revert_snapshot(name, snap_name, runas=None):
name = _sdecode(name)
snap_name = _validate_snap_name(name, snap_name, runas=runas)
args = [name, '--id', snap_name]
return prlctl('snapshot-switch', args, runas=runas)
| [
"def",
"revert_snapshot",
"(",
"name",
",",
"snap_name",
",",
"runas",
"=",
"None",
")",
":",
"name",
"=",
"_sdecode",
"(",
"name",
")",
"snap_name",
"=",
"_validate_snap_name",
"(",
"name",
",",
"snap_name",
",",
"runas",
"=",
"runas",
")",
"args",
"=",... | revert a vm to a snapshot . | train | false |
51,355 | def foreign(expr):
return _annotate_columns(expression._clause_element_as_expr(expr), {'foreign': True})
| [
"def",
"foreign",
"(",
"expr",
")",
":",
"return",
"_annotate_columns",
"(",
"expression",
".",
"_clause_element_as_expr",
"(",
"expr",
")",
",",
"{",
"'foreign'",
":",
"True",
"}",
")"
] | annotate a portion of a primaryjoin expression with a foreign annotation . | train | false |
51,356 | def recv(shape, dtype, source, tag):
return MPIRecvWait(tag)(*irecv(shape, dtype, source, tag))
| [
"def",
"recv",
"(",
"shape",
",",
"dtype",
",",
"source",
",",
"tag",
")",
":",
"return",
"MPIRecvWait",
"(",
"tag",
")",
"(",
"*",
"irecv",
"(",
"shape",
",",
"dtype",
",",
"source",
",",
"tag",
")",
")"
] | blocking receive . | train | false |
51,358 | def test_stratified_validation_shuffle_split():
skip_if_no_sklearn()
from pylearn2.cross_validation.subset_iterators import StratifiedValidationShuffleSplit
n = 60
y = np.concatenate((np.zeros((n / 2), dtype=int), np.ones((n / 2), dtype=int)))
cv = StratifiedValidationShuffleSplit(y)
for (train, valid, test) in cv:
assert (np.unique(np.concatenate((train, valid, test))).size == n)
assert (valid.size == (n * cv.test_size))
assert (test.size == (n * cv.test_size))
assert (np.count_nonzero(y[valid]) == ((n / 2) * cv.test_size))
assert (np.count_nonzero(y[test]) == ((n / 2) * cv.test_size))
| [
"def",
"test_stratified_validation_shuffle_split",
"(",
")",
":",
"skip_if_no_sklearn",
"(",
")",
"from",
"pylearn2",
".",
"cross_validation",
".",
"subset_iterators",
"import",
"StratifiedValidationShuffleSplit",
"n",
"=",
"60",
"y",
"=",
"np",
".",
"concatenate",
"(... | test stratifiedvalidationshufflesplit . | train | false |
51,360 | def feq(a, b):
t_float = Float('1.0E-10')
return ((- t_float) < (a - b) < t_float)
| [
"def",
"feq",
"(",
"a",
",",
"b",
")",
":",
"t_float",
"=",
"Float",
"(",
"'1.0E-10'",
")",
"return",
"(",
"(",
"-",
"t_float",
")",
"<",
"(",
"a",
"-",
"b",
")",
"<",
"t_float",
")"
] | test if two floating point values are equal . | train | false |
51,363 | def _stringify_na_values(na_values):
result = []
for x in na_values:
result.append(str(x))
result.append(x)
try:
v = float(x)
if (v == int(v)):
v = int(v)
result.append(('%s.0' % v))
result.append(str(v))
result.append(v)
except:
pass
try:
result.append(int(x))
except:
pass
return set(result)
| [
"def",
"_stringify_na_values",
"(",
"na_values",
")",
":",
"result",
"=",
"[",
"]",
"for",
"x",
"in",
"na_values",
":",
"result",
".",
"append",
"(",
"str",
"(",
"x",
")",
")",
"result",
".",
"append",
"(",
"x",
")",
"try",
":",
"v",
"=",
"float",
... | return a stringified and numeric for these values . | train | false |
51,364 | def checkDynParam(place, parameter, value):
if kb.redirectChoice:
return None
kb.matchRatio = None
dynResult = None
randInt = randomInt()
paramType = (conf.method if (conf.method not in (None, HTTPMETHOD.GET, HTTPMETHOD.POST)) else place)
infoMsg = ("testing if %s parameter '%s' is dynamic" % (paramType, parameter))
logger.info(infoMsg)
try:
payload = agent.payload(place, parameter, value, getUnicode(randInt))
dynResult = Request.queryPage(payload, place, raise404=False)
if (not dynResult):
infoMsg = ("confirming that %s parameter '%s' is dynamic" % (paramType, parameter))
logger.info(infoMsg)
randInt = randomInt()
payload = agent.payload(place, parameter, value, getUnicode(randInt))
dynResult = Request.queryPage(payload, place, raise404=False)
except SqlmapConnectionException:
pass
result = (None if (dynResult is None) else (not dynResult))
kb.dynamicParameter = result
return result
| [
"def",
"checkDynParam",
"(",
"place",
",",
"parameter",
",",
"value",
")",
":",
"if",
"kb",
".",
"redirectChoice",
":",
"return",
"None",
"kb",
".",
"matchRatio",
"=",
"None",
"dynResult",
"=",
"None",
"randInt",
"=",
"randomInt",
"(",
")",
"paramType",
... | this function checks if the url parameter is dynamic . | train | false |
51,365 | def get_ip_addresses(include_loopback=True):
system = platform.system()
if (system.lower() in ['linux', 'darwin', 'macosx']):
ips = [iface.get('inet') for iface in ifcfg.interfaces().values()]
elif (system.lower() == 'windows'):
ipconfig = os.popen('ipconfig /all').read()
ips = [match[1] for match in re.findall('IP(v4)? Address[\\.\\: ]+([\\d\\.]+)', ipconfig)]
else:
ips = []
ips = (set(ips) - set([None, '']))
if include_loopback:
ips = ips.union(['127.0.0.1'])
else:
ips = (ips - set(['127.0.0.1']))
return list(ips)
| [
"def",
"get_ip_addresses",
"(",
"include_loopback",
"=",
"True",
")",
":",
"system",
"=",
"platform",
".",
"system",
"(",
")",
"if",
"(",
"system",
".",
"lower",
"(",
")",
"in",
"[",
"'linux'",
",",
"'darwin'",
",",
"'macosx'",
"]",
")",
":",
"ips",
... | get a list of all the ip addresses for adapters on the local system . | train | false |
51,366 | def mock_render_to_response(*args, **kwargs):
return render_to_response(*args, **kwargs)
| [
"def",
"mock_render_to_response",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"render_to_response",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | mock the render_to_response function . | train | false |
51,367 | @cronjobs.register
def update_google_analytics(date=None):
if date:
date = datetime.datetime.strptime(date, '%Y-%m-%d').date()
else:
date = (datetime.date.today() - datetime.timedelta(days=1))
tasks.update_google_analytics.delay(date=date)
| [
"@",
"cronjobs",
".",
"register",
"def",
"update_google_analytics",
"(",
"date",
"=",
"None",
")",
":",
"if",
"date",
":",
"date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"date",
",",
"'%Y-%m-%d'",
")",
".",
"date",
"(",
")",
"else",
":... | update stats from google analytics . | train | false |
51,368 | def get_domain_info(libvirt, host, virt_dom):
def is_race(e):
code = e.get_error_code()
message = e.get_error_message()
return ((code == libvirt.VIR_ERR_OPERATION_FAILED) and ('cannot read cputime for domain' in message))
try:
return virt_dom.info()
except libvirt.libvirtError as e:
if ((not host.has_min_version((1, 2, 11))) and is_race(e)):
LOG.warning(_LW('Race detected in libvirt.virDomain.info, trying one more time'))
return virt_dom.info()
raise
| [
"def",
"get_domain_info",
"(",
"libvirt",
",",
"host",
",",
"virt_dom",
")",
":",
"def",
"is_race",
"(",
"e",
")",
":",
"code",
"=",
"e",
".",
"get_error_code",
"(",
")",
"message",
"=",
"e",
".",
"get_error_message",
"(",
")",
"return",
"(",
"(",
"c... | method virdomain . | train | false |
51,372 | def task_id_str(task_family, params):
param_str = json.dumps(params, separators=(',', ':'), sort_keys=True)
param_hash = hashlib.md5(param_str.encode('utf-8')).hexdigest()
param_summary = '_'.join((p[:TASK_ID_TRUNCATE_PARAMS] for p in (params[p] for p in sorted(params)[:TASK_ID_INCLUDE_PARAMS])))
param_summary = TASK_ID_INVALID_CHAR_REGEX.sub('_', param_summary)
return '{}_{}_{}'.format(task_family, param_summary, param_hash[:TASK_ID_TRUNCATE_HASH])
| [
"def",
"task_id_str",
"(",
"task_family",
",",
"params",
")",
":",
"param_str",
"=",
"json",
".",
"dumps",
"(",
"params",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
",",
"sort_keys",
"=",
"True",
")",
"param_hash",
"=",
"hashlib",
".",
"md5",... | returns a canonical string used to identify a particular task . | train | true |
51,373 | @utils.expects_func_args('migration')
def errors_out_migration(function):
@functools.wraps(function)
def decorated_function(self, context, *args, **kwargs):
try:
return function(self, context, *args, **kwargs)
except Exception as ex:
with excutils.save_and_reraise_exception():
wrapped_func = safe_utils.get_wrapped_function(function)
keyed_args = inspect.getcallargs(wrapped_func, self, context, *args, **kwargs)
migration = keyed_args['migration']
if (not isinstance(ex, exception.InstanceNotFound)):
status = migration.status
if (status not in ['migrating', 'post-migrating']):
return
migration.status = 'error'
try:
with migration.obj_as_admin():
migration.save()
except Exception:
LOG.debug('Error setting migration status for instance %s.', migration.instance_uuid, exc_info=True)
return decorated_function
| [
"@",
"utils",
".",
"expects_func_args",
"(",
"'migration'",
")",
"def",
"errors_out_migration",
"(",
"function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"def",
"decorated_function",
"(",
"self",
",",
"context",
",",
"*",
"args",
",",
... | decorator to error out migration on failure . | train | false |
51,374 | def test_finds_local_repo(tmpdir):
project_dir = repository.determine_repo_dir('tests/fake-repo', abbreviations={}, clone_to_dir=str(tmpdir), checkout=None, no_input=True)
assert ('tests/fake-repo' == project_dir)
| [
"def",
"test_finds_local_repo",
"(",
"tmpdir",
")",
":",
"project_dir",
"=",
"repository",
".",
"determine_repo_dir",
"(",
"'tests/fake-repo'",
",",
"abbreviations",
"=",
"{",
"}",
",",
"clone_to_dir",
"=",
"str",
"(",
"tmpdir",
")",
",",
"checkout",
"=",
"Non... | a valid local repository should be returned . | train | false |
51,375 | def color_func(func_name):
if str(func_name).isdigit():
return term_color(int(func_name))
return globals()[func_name]
| [
"def",
"color_func",
"(",
"func_name",
")",
":",
"if",
"str",
"(",
"func_name",
")",
".",
"isdigit",
"(",
")",
":",
"return",
"term_color",
"(",
"int",
"(",
"func_name",
")",
")",
"return",
"globals",
"(",
")",
"[",
"func_name",
"]"
] | call color function base on name . | train | true |
51,376 | def validate_config_section(filename, config, section):
if (not isinstance(config, dict)):
raise ConfigurationError(u"In file '{filename}', {section} must be a mapping, not {type}.".format(filename=filename, section=section, type=anglicize_json_type(python_type_to_yaml_type(config))))
for (key, value) in config.items():
if (not isinstance(key, six.string_types)):
raise ConfigurationError(u"In file '{filename}', the {section} name {name} must be a quoted string, i.e. '{name}'.".format(filename=filename, section=section, name=key))
if (not isinstance(value, (dict, type(None)))):
raise ConfigurationError(u"In file '{filename}', {section} '{name}' must be a mapping not {type}.".format(filename=filename, section=section, name=key, type=anglicize_json_type(python_type_to_yaml_type(value))))
| [
"def",
"validate_config_section",
"(",
"filename",
",",
"config",
",",
"section",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"config",
",",
"dict",
")",
")",
":",
"raise",
"ConfigurationError",
"(",
"u\"In file '{filename}', {section} must be a mapping, not {type}... | validate the structure of a configuration section . | train | false |
51,377 | def nn(model, text, vectors, query, k=5):
qf = encode(model, [query])
qf /= norm(qf)
scores = numpy.dot(qf, vectors.T).flatten()
sorted_args = numpy.argsort(scores)[::(-1)]
sentences = [text[a] for a in sorted_args[:k]]
print ('QUERY: ' + query)
print 'NEAREST: '
for (i, s) in enumerate(sentences):
print s, sorted_args[i]
| [
"def",
"nn",
"(",
"model",
",",
"text",
",",
"vectors",
",",
"query",
",",
"k",
"=",
"5",
")",
":",
"qf",
"=",
"encode",
"(",
"model",
",",
"[",
"query",
"]",
")",
"qf",
"/=",
"norm",
"(",
"qf",
")",
"scores",
"=",
"numpy",
".",
"dot",
"(",
... | return the nearest neighbour sentences to query text: list of sentences vectors: the corresponding representations for text query: a string to search . | train | false |
51,378 | def isLDAPUrl(s):
s_lower = s.lower()
return (s_lower.startswith('ldap://') or s_lower.startswith('ldaps://') or s_lower.startswith('ldapi://'))
| [
"def",
"isLDAPUrl",
"(",
"s",
")",
":",
"s_lower",
"=",
"s",
".",
"lower",
"(",
")",
"return",
"(",
"s_lower",
".",
"startswith",
"(",
"'ldap://'",
")",
"or",
"s_lower",
".",
"startswith",
"(",
"'ldaps://'",
")",
"or",
"s_lower",
".",
"startswith",
"("... | returns 1 if s is a ldap url . | train | false |
51,380 | def register_config_key(key, schema, required=False):
_root_config_schema[u'properties'][key] = schema
if required:
_root_config_schema.setdefault(u'required', []).append(key)
register_schema((u'/schema/config/%s' % key), schema)
| [
"def",
"register_config_key",
"(",
"key",
",",
"schema",
",",
"required",
"=",
"False",
")",
":",
"_root_config_schema",
"[",
"u'properties'",
"]",
"[",
"key",
"]",
"=",
"schema",
"if",
"required",
":",
"_root_config_schema",
".",
"setdefault",
"(",
"u'require... | registers a valid root level key for the config . | train | false |
51,381 | def _describe_volume(volume):
return {'id': volume.id, 'creation_time': _format_time(_get_volume_creation_time(volume)), 'provider': volume.driver.name, 'region': _get_volume_region(volume), 'extra': repr(volume.extra)}
| [
"def",
"_describe_volume",
"(",
"volume",
")",
":",
"return",
"{",
"'id'",
":",
"volume",
".",
"id",
",",
"'creation_time'",
":",
"_format_time",
"(",
"_get_volume_creation_time",
"(",
"volume",
")",
")",
",",
"'provider'",
":",
"volume",
".",
"driver",
".",... | create a dictionary giving lots of interesting details about a cloud volume . | train | false |
51,383 | def format_params(paramlist, otherlist=None):
hdr = u'Parameters'
delim = u'----------'
paramlist.insert(0, delim)
paramlist.insert(0, hdr)
params = u'\n'.join(paramlist)
otherparams = []
doc = u''.join(params)
if otherlist:
hdr = u'Others Parameters'
delim = u'-----------------'
otherlist.insert(0, delim)
otherlist.insert(0, hdr)
otherlist.insert(0, u'\n')
otherparams = u'\n'.join(otherlist)
doc = u''.join([doc, otherparams])
return doc
| [
"def",
"format_params",
"(",
"paramlist",
",",
"otherlist",
"=",
"None",
")",
":",
"hdr",
"=",
"u'Parameters'",
"delim",
"=",
"u'----------'",
"paramlist",
".",
"insert",
"(",
"0",
",",
"delim",
")",
"paramlist",
".",
"insert",
"(",
"0",
",",
"hdr",
")",... | format the parameters according to the nipy style conventions . | train | false |
51,384 | def WriteHeaders(headers, outfile, content_len=None):
wrote_content_length = False
for (header, value) in headers.iteritems():
if ((header.lower() == 'content-length') and (content_len is not None)):
value = content_len
wrote_content_length = True
outfile.write(('%s: %s\r\n' % (header, value)))
if ((not wrote_content_length) and content_len):
outfile.write(('Content-Length: %s\r\n' % content_len))
| [
"def",
"WriteHeaders",
"(",
"headers",
",",
"outfile",
",",
"content_len",
"=",
"None",
")",
":",
"wrote_content_length",
"=",
"False",
"for",
"(",
"header",
",",
"value",
")",
"in",
"headers",
".",
"iteritems",
"(",
")",
":",
"if",
"(",
"(",
"header",
... | write headers to the output file . | train | false |
51,385 | def _update_on_fields(prev_ele, new_ele):
return dict(((prop_name, prop_val) for (prop_name, prop_val) in six.iteritems(new_ele) if ((new_ele.get(prop_name) != prev_ele.get(prop_name)) or (prop_name in _MATCH_KEYS))))
| [
"def",
"_update_on_fields",
"(",
"prev_ele",
",",
"new_ele",
")",
":",
"return",
"dict",
"(",
"(",
"(",
"prop_name",
",",
"prop_val",
")",
"for",
"(",
"prop_name",
",",
"prop_val",
")",
"in",
"six",
".",
"iteritems",
"(",
"new_ele",
")",
"if",
"(",
"("... | return a dict with fields that differ between two dicts . | train | false |
51,386 | def get_vm_extra_config_spec(client_factory, extra_opts):
config_spec = client_factory.create('ns0:VirtualMachineConfigSpec')
extra_config = []
for (key, value) in extra_opts.items():
opt = client_factory.create('ns0:OptionValue')
opt.key = key
opt.value = value
extra_config.append(opt)
config_spec.extraConfig = extra_config
return config_spec
| [
"def",
"get_vm_extra_config_spec",
"(",
"client_factory",
",",
"extra_opts",
")",
":",
"config_spec",
"=",
"client_factory",
".",
"create",
"(",
"'ns0:VirtualMachineConfigSpec'",
")",
"extra_config",
"=",
"[",
"]",
"for",
"(",
"key",
",",
"value",
")",
"in",
"ex... | builds extra spec fields from a dictionary . | train | false |
51,388 | def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile)
if (not saml_provider_arn):
msg = 'SAML provider {0} not found.'
log.info(msg.format(name))
return True
conn.delete_saml_provider(saml_provider_arn)
msg = 'Successfully deleted {0} SAML provider.'
log.info(msg.format(name))
return True
except boto.exception.BotoServerError as e:
aws = __utils__['boto.get_error'](e)
log.debug(aws)
msg = 'Failed to delete {0} SAML provider.'
log.error(msg.format(name))
return False
| [
"def",
"delete_saml_provider",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
... | delete saml provider cli example: . | train | true |
51,389 | def get_user_specific_rating_for_exploration(user_id, exploration_id):
exp_user_data_model = user_models.ExplorationUserDataModel.get(user_id, exploration_id)
return (exp_user_data_model.rating if exp_user_data_model else None)
| [
"def",
"get_user_specific_rating_for_exploration",
"(",
"user_id",
",",
"exploration_id",
")",
":",
"exp_user_data_model",
"=",
"user_models",
".",
"ExplorationUserDataModel",
".",
"get",
"(",
"user_id",
",",
"exploration_id",
")",
"return",
"(",
"exp_user_data_model",
... | fetches a rating for the specified exploration from the specified user if one exists . | train | false |
51,390 | def datetime_to_utc_timestamp(timeval):
if (timeval is not None):
return (timegm(timeval.utctimetuple()) + (timeval.microsecond / 1000000))
| [
"def",
"datetime_to_utc_timestamp",
"(",
"timeval",
")",
":",
"if",
"(",
"timeval",
"is",
"not",
"None",
")",
":",
"return",
"(",
"timegm",
"(",
"timeval",
".",
"utctimetuple",
"(",
")",
")",
"+",
"(",
"timeval",
".",
"microsecond",
"/",
"1000000",
")",
... | converts a datetime instance to a timestamp . | train | false |
51,393 | def update_char_format(baseformat, color=None, background=None, weight=None, italic=None, underline=None, font=None):
charformat = QTextCharFormat(baseformat)
if (color is not None):
charformat.setForeground(color)
if (background is not None):
charformat.setBackground(background)
if (font is not None):
charformat.setFont(font)
else:
font = update_font(baseformat.font(), weight, italic, underline)
charformat.setFont(font)
return charformat
| [
"def",
"update_char_format",
"(",
"baseformat",
",",
"color",
"=",
"None",
",",
"background",
"=",
"None",
",",
"weight",
"=",
"None",
",",
"italic",
"=",
"None",
",",
"underline",
"=",
"None",
",",
"font",
"=",
"None",
")",
":",
"charformat",
"=",
"QT... | return a copy of baseformat :class:qtextcharformat with updated color . | train | false |
51,396 | def get_date_regex(timestring):
prev = ''
curr = ''
regex = ''
for s in range(0, len(timestring)):
curr = timestring[s]
if (curr == '%'):
pass
elif ((curr in settings.date_regex()) and (prev == '%')):
regex += (('\\d{' + settings.date_regex()[curr]) + '}')
elif (curr in ['.', '-']):
regex += ('\\' + curr)
else:
regex += curr
prev = curr
logger.debug('regex = {0}'.format(regex))
return regex
| [
"def",
"get_date_regex",
"(",
"timestring",
")",
":",
"prev",
"=",
"''",
"curr",
"=",
"''",
"regex",
"=",
"''",
"for",
"s",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"timestring",
")",
")",
":",
"curr",
"=",
"timestring",
"[",
"s",
"]",
"if",
"("... | return a regex string based on a provided strftime timestring . | train | false |
51,397 | def load_parser(grammar_url, trace=0, parser=None, chart_class=None, beam_size=0, **load_args):
grammar = load(grammar_url, **load_args)
if (not isinstance(grammar, CFG)):
raise ValueError('The grammar must be a CFG, or a subclass thereof.')
if isinstance(grammar, PCFG):
if (parser is None):
parser = InsideChartParser
return parser(grammar, trace=trace, beam_size=beam_size)
elif isinstance(grammar, FeatureGrammar):
if (parser is None):
parser = FeatureChartParser
if (chart_class is None):
chart_class = FeatureChart
return parser(grammar, trace=trace, chart_class=chart_class)
else:
if (parser is None):
parser = ChartParser
if (chart_class is None):
chart_class = Chart
return parser(grammar, trace=trace, chart_class=chart_class)
| [
"def",
"load_parser",
"(",
"grammar_url",
",",
"trace",
"=",
"0",
",",
"parser",
"=",
"None",
",",
"chart_class",
"=",
"None",
",",
"beam_size",
"=",
"0",
",",
"**",
"load_args",
")",
":",
"grammar",
"=",
"load",
"(",
"grammar_url",
",",
"**",
"load_ar... | load a grammar from a file . | train | false |
51,398 | def dev_from_index(if_index):
return IFACES.dev_from_index(if_index)
| [
"def",
"dev_from_index",
"(",
"if_index",
")",
":",
"return",
"IFACES",
".",
"dev_from_index",
"(",
"if_index",
")"
] | return windows adapter name for given windows interface index . | train | false |
51,399 | def convert_TextProperty(model, prop, kwargs):
return f.TextAreaField(**kwargs)
| [
"def",
"convert_TextProperty",
"(",
"model",
",",
"prop",
",",
"kwargs",
")",
":",
"return",
"f",
".",
"TextAreaField",
"(",
"**",
"kwargs",
")"
] | returns a form field for a db . | train | false |
51,402 | def collect_command(host, command, dest_path):
logging.info("Collecting '%s' ...", command)
devnull = open('/dev/null', 'w')
try:
result = host.run(command, stdout_tee=devnull).stdout
utils.open_write_close(dest_path, result)
except Exception as e:
logging.warning("Collection of '%s' failed:\n%s", command, e)
finally:
devnull.close()
| [
"def",
"collect_command",
"(",
"host",
",",
"command",
",",
"dest_path",
")",
":",
"logging",
".",
"info",
"(",
"\"Collecting '%s' ...\"",
",",
"command",
")",
"devnull",
"=",
"open",
"(",
"'/dev/null'",
",",
"'w'",
")",
"try",
":",
"result",
"=",
"host",
... | collects the result of a command on the remote machine . | train | false |
51,403 | def ValidatePropertyNothing(name, value):
pass
| [
"def",
"ValidatePropertyNothing",
"(",
"name",
",",
"value",
")",
":",
"pass"
] | no-op validation function . | train | false |
51,404 | def set_process_title(progname, info=None):
proctitle = ('[%s]' % progname)
proctitle = (('%s %s' % (proctitle, info)) if info else proctitle)
if _setproctitle:
_setproctitle.setproctitle(proctitle)
return proctitle
| [
"def",
"set_process_title",
"(",
"progname",
",",
"info",
"=",
"None",
")",
":",
"proctitle",
"=",
"(",
"'[%s]'",
"%",
"progname",
")",
"proctitle",
"=",
"(",
"(",
"'%s %s'",
"%",
"(",
"proctitle",
",",
"info",
")",
")",
"if",
"info",
"else",
"proctitl... | set the ps name for the currently running process . | train | false |
51,405 | def strip_ansi_codes(s):
return re.sub(u'\x1b\\[([0-9]+)(;[0-9]+)*m', u'', s)
| [
"def",
"strip_ansi_codes",
"(",
"s",
")",
":",
"return",
"re",
".",
"sub",
"(",
"u'\\x1b\\\\[([0-9]+)(;[0-9]+)*m'",
",",
"u''",
",",
"s",
")"
] | remove ansi color codes from the string . | train | false |
51,407 | @contextlib.contextmanager
def fpopen(*args, **kwargs):
uid = kwargs.pop('uid', (-1))
gid = kwargs.pop('gid', (-1))
mode = kwargs.pop('mode', None)
with fopen(*args, **kwargs) as fhandle:
path = args[0]
d_stat = os.stat(path)
if hasattr(os, 'chown'):
if (((d_stat.st_uid != uid) or (d_stat.st_gid != gid)) and [i for i in (uid, gid) if (i != (-1))]):
os.chown(path, uid, gid)
if (mode is not None):
mode_part = S_IMODE(d_stat.st_mode)
if (mode_part != mode):
os.chmod(path, ((d_stat.st_mode ^ mode_part) | mode))
(yield fhandle)
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"fpopen",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"uid",
"=",
"kwargs",
".",
"pop",
"(",
"'uid'",
",",
"(",
"-",
"1",
")",
")",
"gid",
"=",
"kwargs",
".",
"pop",
"(",
"'gid'",
",",
"(",
... | shortcut for fopen with extra uid . | train | true |
51,408 | def call_tesseract(input_filename, output_filename, bool_digits=False):
if bool_digits:
args = (((((tesseract_exe_name + ' ') + input_filename) + ' ') + output_filename) + ' -l test_digits -psm 7 nobatch')
else:
args = (((((tesseract_exe_name + ' ') + input_filename) + ' ') + output_filename) + ' -l eng -psm 7 nobatch eng_characters')
proc = subprocess.Popen(args, shell=True)
retcode = proc.wait()
if (retcode != 0):
errors.check_for_errors()
| [
"def",
"call_tesseract",
"(",
"input_filename",
",",
"output_filename",
",",
"bool_digits",
"=",
"False",
")",
":",
"if",
"bool_digits",
":",
"args",
"=",
"(",
"(",
"(",
"(",
"(",
"tesseract_exe_name",
"+",
"' '",
")",
"+",
"input_filename",
")",
"+",
"' '... | calls external tesseract . | train | false |
51,409 | def replace_pyzzer_entry_point_shebang(all_data, placeholder, new_prefix):
launcher = shebang = None
pos = all_data.rfind('PK\x05\x06')
if (pos >= 0):
end_cdr = all_data[(pos + 12):(pos + 20)]
(cdr_size, cdr_offset) = struct.unpack(u'<LL', end_cdr)
arc_pos = ((pos - cdr_size) - cdr_offset)
data = all_data[arc_pos:]
if (arc_pos > 0):
pos = all_data.rfind('#!', 0, arc_pos)
if (pos >= 0):
shebang = all_data[pos:arc_pos]
if (pos > 0):
launcher = all_data[:pos]
if (data and shebang and launcher):
if hasattr(placeholder, u'encode'):
placeholder = placeholder.encode(u'utf-8')
if hasattr(new_prefix, u'encode'):
new_prefix = new_prefix.encode(u'utf-8')
shebang = shebang.replace(placeholder, new_prefix)
all_data = ''.join([launcher, shebang, data])
return all_data
| [
"def",
"replace_pyzzer_entry_point_shebang",
"(",
"all_data",
",",
"placeholder",
",",
"new_prefix",
")",
":",
"launcher",
"=",
"shebang",
"=",
"None",
"pos",
"=",
"all_data",
".",
"rfind",
"(",
"'PK\\x05\\x06'",
")",
"if",
"(",
"pos",
">=",
"0",
")",
":",
... | code adapted from pyzzer . | train | false |
51,410 | def _parse_timespan(timespan):
if (timespan in ('', 'NOT_IMPLEMENTED', None)):
return None
else:
return sum((((60 ** x[0]) * int(x[1])) for x in enumerate(reversed(timespan.split(':')))))
| [
"def",
"_parse_timespan",
"(",
"timespan",
")",
":",
"if",
"(",
"timespan",
"in",
"(",
"''",
",",
"'NOT_IMPLEMENTED'",
",",
"None",
")",
")",
":",
"return",
"None",
"else",
":",
"return",
"sum",
"(",
"(",
"(",
"(",
"60",
"**",
"x",
"[",
"0",
"]",
... | parse a time-span into number of seconds . | train | false |
51,412 | def has_database_privileges(cursor, user, db, privs):
cur_privs = get_database_privileges(cursor, user, db)
have_currently = cur_privs.intersection(privs)
other_current = cur_privs.difference(privs)
desired = privs.difference(cur_privs)
return (have_currently, other_current, desired)
| [
"def",
"has_database_privileges",
"(",
"cursor",
",",
"user",
",",
"db",
",",
"privs",
")",
":",
"cur_privs",
"=",
"get_database_privileges",
"(",
"cursor",
",",
"user",
",",
"db",
")",
"have_currently",
"=",
"cur_privs",
".",
"intersection",
"(",
"privs",
"... | return the difference between the privileges that a user already has and the privileges that they desire to have . | train | false |
51,413 | @status('Docs modified', modal=True)
def docs_modified(file_paths):
for path in file_paths:
if path.startswith('Doc'):
return True
return False
| [
"@",
"status",
"(",
"'Docs modified'",
",",
"modal",
"=",
"True",
")",
"def",
"docs_modified",
"(",
"file_paths",
")",
":",
"for",
"path",
"in",
"file_paths",
":",
"if",
"path",
".",
"startswith",
"(",
"'Doc'",
")",
":",
"return",
"True",
"return",
"Fals... | report if any files in the docs directory . | train | false |
51,415 | def extract_num(buf, start, length):
val = 0
for i in range(start, (start + length)):
val <<= 8
val += ord(buf[i])
return val
| [
"def",
"extract_num",
"(",
"buf",
",",
"start",
",",
"length",
")",
":",
"val",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"start",
",",
"(",
"start",
"+",
"length",
")",
")",
":",
"val",
"<<=",
"8",
"val",
"+=",
"ord",
"(",
"buf",
"[",
"i",
"... | extracts a number from a raw byte string . | train | false |
51,416 | def _save_forum_role(course_key, name):
(role, created) = Role.objects.get_or_create(name=name, course_id=course_key)
if (created is False):
role.course_id = course_key
role.save()
return role
| [
"def",
"_save_forum_role",
"(",
"course_key",
",",
"name",
")",
":",
"(",
"role",
",",
"created",
")",
"=",
"Role",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"name",
",",
"course_id",
"=",
"course_key",
")",
"if",
"(",
"created",
"is",
"F... | save and update course_key for all roles which are already created to keep course_id same as actual passed course key . | train | false |
51,418 | def _formatSchema(data, incoming):
if incoming:
param = '<json'
else:
param = '>json'
if (data['type'] == 'array'):
param += 'arr'
for (prop, attr) in sorted(data[u'properties'].iteritems()):
if attr['required']:
required = '*(required)* '
else:
required = ''
if isinstance(attr['type'], list):
types = '|'.join(attr['type'])
else:
types = attr['type']
(yield (':%s %s %s: %s%s' % (param, types, prop, required, attr['title'])))
(yield '')
for line in attr['description']:
(yield (' ' + line))
| [
"def",
"_formatSchema",
"(",
"data",
",",
"incoming",
")",
":",
"if",
"incoming",
":",
"param",
"=",
"'<json'",
"else",
":",
"param",
"=",
"'>json'",
"if",
"(",
"data",
"[",
"'type'",
"]",
"==",
"'array'",
")",
":",
"param",
"+=",
"'arr'",
"for",
"("... | generate the rst associated to a json schema . | train | false |
51,419 | def copula_bv_max(u, v):
return np.maximum(((u + v) - 1), 0)
| [
"def",
"copula_bv_max",
"(",
"u",
",",
"v",
")",
":",
"return",
"np",
".",
"maximum",
"(",
"(",
"(",
"u",
"+",
"v",
")",
"-",
"1",
")",
",",
"0",
")"
] | countermonotonic bivariate copula . | train | false |
51,420 | def goto(dNorth, dEast, gotoFunction=vehicle.simple_goto):
currentLocation = vehicle.location.global_relative_frame
targetLocation = get_location_metres(currentLocation, dNorth, dEast)
targetDistance = get_distance_metres(currentLocation, targetLocation)
gotoFunction(targetLocation)
while (vehicle.mode.name == 'GUIDED'):
remainingDistance = get_distance_metres(vehicle.location.global_relative_frame, targetLocation)
print 'Distance to target: ', remainingDistance
if (remainingDistance <= (targetDistance * 0.01)):
print 'Reached target'
break
time.sleep(2)
| [
"def",
"goto",
"(",
"dNorth",
",",
"dEast",
",",
"gotoFunction",
"=",
"vehicle",
".",
"simple_goto",
")",
":",
"currentLocation",
"=",
"vehicle",
".",
"location",
".",
"global_relative_frame",
"targetLocation",
"=",
"get_location_metres",
"(",
"currentLocation",
"... | moves the vehicle to a position dnorth metres north and deast metres east of the current position . | train | true |
51,421 | def load_pixbuf(fname, size=0):
image = gtk.Image()
image.set_from_file(os.path.join(_pixmap_path, fname))
image = image.get_pixbuf()
if size:
aspect = (float(image.get_height()) / image.get_width())
image = image.scale_simple(size, int((aspect * size)), 2)
return image
| [
"def",
"load_pixbuf",
"(",
"fname",
",",
"size",
"=",
"0",
")",
":",
"image",
"=",
"gtk",
".",
"Image",
"(",
")",
"image",
".",
"set_from_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"_pixmap_path",
",",
"fname",
")",
")",
"image",
"=",
"image"... | load an image from a file as a pixbuf . | train | false |
51,423 | def read_simple_binding(jboss_config, binding_name, profile=None):
log.debug('======================== MODULE FUNCTION: jboss7.read_simple_binding, %s', binding_name)
return __read_simple_binding(jboss_config, binding_name, profile=profile)
| [
"def",
"read_simple_binding",
"(",
"jboss_config",
",",
"binding_name",
",",
"profile",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'======================== MODULE FUNCTION: jboss7.read_simple_binding, %s'",
",",
"binding_name",
")",
"return",
"__read_simple_binding"... | read jndi binding in the running jboss instance jboss_config configuration dictionary with properties specified above . | train | true |
51,424 | def ttest_1samp_no_p(X, sigma=0, method='relative'):
if (method not in ['absolute', 'relative']):
raise ValueError(('method must be "absolute" or "relative", not %s' % method))
var = np.var(X, axis=0, ddof=1)
if (sigma > 0):
limit = ((sigma * np.max(var)) if (method == 'relative') else sigma)
var += limit
return (np.mean(X, axis=0) / np.sqrt((var / X.shape[0])))
| [
"def",
"ttest_1samp_no_p",
"(",
"X",
",",
"sigma",
"=",
"0",
",",
"method",
"=",
"'relative'",
")",
":",
"if",
"(",
"method",
"not",
"in",
"[",
"'absolute'",
",",
"'relative'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'method must be \"absolute\" o... | perform t-test with variance adjustment and no p-value calculation . | train | false |
51,426 | def cert_from_instance(instance):
if instance.signature:
if instance.signature.key_info:
return cert_from_key_info(instance.signature.key_info, ignore_age=True)
return []
| [
"def",
"cert_from_instance",
"(",
"instance",
")",
":",
"if",
"instance",
".",
"signature",
":",
"if",
"instance",
".",
"signature",
".",
"key_info",
":",
"return",
"cert_from_key_info",
"(",
"instance",
".",
"signature",
".",
"key_info",
",",
"ignore_age",
"=... | find certificates that are part of an instance . | train | true |
51,428 | def _makep(array, descr_output, format, nrows=None):
_offset = 0
if (not nrows):
nrows = len(array)
data_output = _VLF(([None] * nrows), dtype=format.dtype)
if (format.dtype == 'a'):
_nbytes = 1
else:
_nbytes = np.array([], dtype=format.dtype).itemsize
for idx in range(nrows):
if (idx < len(array)):
rowval = array[idx]
elif (format.dtype == 'a'):
rowval = (' ' * data_output.max)
else:
rowval = ([0] * data_output.max)
if (format.dtype == 'a'):
data_output[idx] = chararray.array(encode_ascii(rowval), itemsize=1)
else:
data_output[idx] = np.array(rowval, dtype=format.dtype)
descr_output[(idx, 0)] = len(data_output[idx])
descr_output[(idx, 1)] = _offset
_offset += (len(data_output[idx]) * _nbytes)
return data_output
| [
"def",
"_makep",
"(",
"array",
",",
"descr_output",
",",
"format",
",",
"nrows",
"=",
"None",
")",
":",
"_offset",
"=",
"0",
"if",
"(",
"not",
"nrows",
")",
":",
"nrows",
"=",
"len",
"(",
"array",
")",
"data_output",
"=",
"_VLF",
"(",
"(",
"[",
"... | construct the p format column array . | train | false |
51,429 | def create_from_options(options, name='unknown'):
raise NotImplementedError
| [
"def",
"create_from_options",
"(",
"options",
",",
"name",
"=",
"'unknown'",
")",
":",
"raise",
"NotImplementedError"
] | factory using an options dictionary . | train | false |
51,430 | def is_started():
return (status() == 'running')
| [
"def",
"is_started",
"(",
")",
":",
"return",
"(",
"status",
"(",
")",
"==",
"'running'",
")"
] | check if the firewall is started . | train | false |
51,432 | def delslice(model, start, end):
if isinstance(model, PyListModel):
del model[start:end]
elif isinstance(model, QAbstractItemModel):
model.removeRows(start, (end - start))
else:
raise TypeError(type(model))
| [
"def",
"delslice",
"(",
"model",
",",
"start",
",",
"end",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"PyListModel",
")",
":",
"del",
"model",
"[",
"start",
":",
"end",
"]",
"elif",
"isinstance",
"(",
"model",
",",
"QAbstractItemModel",
")",
":",... | delete the start . | train | false |
51,435 | def _SynchronizeTxn(function):
def sync(txn, *args, **kwargs):
txn._lock.acquire()
try:
Check((txn._state is LiveTxn.ACTIVE), 'transaction closed')
return function(txn, *args, **kwargs)
finally:
txn._lock.release()
return sync
| [
"def",
"_SynchronizeTxn",
"(",
"function",
")",
":",
"def",
"sync",
"(",
"txn",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"txn",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"Check",
"(",
"(",
"txn",
".",
"_state",
"is",
"LiveTxn",
... | a decorator that locks a transaction during the function call . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.