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 |
|---|---|---|---|---|---|
38,596 | def _exception_handler(debugger, exc_info):
tb = exc_info[2]
ignored_traceback = get_ignored_traceback(tb)
if ignored_traceback:
tb = FilteredTraceback(tb, ignored_traceback)
traceback.print_exception(exc_info[0], exc_info[1], tb)
debugger.post_mortem(tb)
| [
"def",
"_exception_handler",
"(",
"debugger",
",",
"exc_info",
")",
":",
"tb",
"=",
"exc_info",
"[",
"2",
"]",
"ignored_traceback",
"=",
"get_ignored_traceback",
"(",
"tb",
")",
"if",
"ignored_traceback",
":",
"tb",
"=",
"FilteredTraceback",
"(",
"tb",
",",
"ignored_traceback",
")",
"traceback",
".",
"print_exception",
"(",
"exc_info",
"[",
"0",
"]",
",",
"exc_info",
"[",
"1",
"]",
",",
"tb",
")",
"debugger",
".",
"post_mortem",
"(",
"tb",
")"
] | exception handler enabling post-mortem debugging . | train | false |
38,597 | def clock():
return load('clock_motion.png')
| [
"def",
"clock",
"(",
")",
":",
"return",
"load",
"(",
"'clock_motion.png'",
")"
] | motion blurred clock . | train | false |
38,598 | def volume_name(base):
return (base + _dmcrypt_suffix)
| [
"def",
"volume_name",
"(",
"base",
")",
":",
"return",
"(",
"base",
"+",
"_dmcrypt_suffix",
")"
] | returns the suffixed dmcrypt volume name . | train | false |
38,602 | def pathlist_to_str(paths, escape_backslashes=True):
path = u' and '.join(paths)
if (on_win and escape_backslashes):
path = re.sub(u'(?<!\\\\)\\\\(?!\\\\)', u'\\\\\\\\', path)
else:
path = path.replace(u'\\\\', u'\\')
return path
| [
"def",
"pathlist_to_str",
"(",
"paths",
",",
"escape_backslashes",
"=",
"True",
")",
":",
"path",
"=",
"u' and '",
".",
"join",
"(",
"paths",
")",
"if",
"(",
"on_win",
"and",
"escape_backslashes",
")",
":",
"path",
"=",
"re",
".",
"sub",
"(",
"u'(?<!\\\\\\\\)\\\\\\\\(?!\\\\\\\\)'",
",",
"u'\\\\\\\\\\\\\\\\'",
",",
"path",
")",
"else",
":",
"path",
"=",
"path",
".",
"replace",
"(",
"u'\\\\\\\\'",
",",
"u'\\\\'",
")",
"return",
"path"
] | format a path list . | train | false |
38,603 | def _get_instance_list(mig, field='name', filter_list=['NONE']):
return [x[field] for x in mig.list_managed_instances() if (x['currentAction'] in filter_list)]
| [
"def",
"_get_instance_list",
"(",
"mig",
",",
"field",
"=",
"'name'",
",",
"filter_list",
"=",
"[",
"'NONE'",
"]",
")",
":",
"return",
"[",
"x",
"[",
"field",
"]",
"for",
"x",
"in",
"mig",
".",
"list_managed_instances",
"(",
")",
"if",
"(",
"x",
"[",
"'currentAction'",
"]",
"in",
"filter_list",
")",
"]"
] | helper to grab field from instances response . | train | false |
38,604 | def get_image_back(releaseid, size=None):
return get_image(releaseid, 'back', size=size)
| [
"def",
"get_image_back",
"(",
"releaseid",
",",
"size",
"=",
"None",
")",
":",
"return",
"get_image",
"(",
"releaseid",
",",
"'back'",
",",
"size",
"=",
"size",
")"
] | download the back cover art for a release . | train | false |
38,605 | def getUnboundVertexElement(vertex):
vertexElement = xml_simple_reader.ElementNode()
addVertexToAttributes(vertexElement.attributes, vertex)
vertexElement.localName = 'vertex'
return vertexElement
| [
"def",
"getUnboundVertexElement",
"(",
"vertex",
")",
":",
"vertexElement",
"=",
"xml_simple_reader",
".",
"ElementNode",
"(",
")",
"addVertexToAttributes",
"(",
"vertexElement",
".",
"attributes",
",",
"vertex",
")",
"vertexElement",
".",
"localName",
"=",
"'vertex'",
"return",
"vertexElement"
] | add vertex element to an xml element . | train | false |
38,606 | def create_cow_image(backing_file, path, size=None):
base_cmd = ['qemu-img', 'create', '-f', 'qcow2']
cow_opts = []
if backing_file:
cow_opts += [('backing_file=%s' % backing_file)]
base_details = images.qemu_img_info(backing_file)
else:
base_details = None
if (base_details and (base_details.cluster_size is not None)):
cow_opts += [('cluster_size=%s' % base_details.cluster_size)]
if (base_details and base_details.encryption):
cow_opts += [('encryption=%s' % base_details.encryption)]
if (size is not None):
cow_opts += [('size=%s' % size)]
if cow_opts:
csv_opts = ','.join(cow_opts)
cow_opts = ['-o', csv_opts]
cmd = ((base_cmd + cow_opts) + [path])
execute(*cmd)
| [
"def",
"create_cow_image",
"(",
"backing_file",
",",
"path",
",",
"size",
"=",
"None",
")",
":",
"base_cmd",
"=",
"[",
"'qemu-img'",
",",
"'create'",
",",
"'-f'",
",",
"'qcow2'",
"]",
"cow_opts",
"=",
"[",
"]",
"if",
"backing_file",
":",
"cow_opts",
"+=",
"[",
"(",
"'backing_file=%s'",
"%",
"backing_file",
")",
"]",
"base_details",
"=",
"images",
".",
"qemu_img_info",
"(",
"backing_file",
")",
"else",
":",
"base_details",
"=",
"None",
"if",
"(",
"base_details",
"and",
"(",
"base_details",
".",
"cluster_size",
"is",
"not",
"None",
")",
")",
":",
"cow_opts",
"+=",
"[",
"(",
"'cluster_size=%s'",
"%",
"base_details",
".",
"cluster_size",
")",
"]",
"if",
"(",
"base_details",
"and",
"base_details",
".",
"encryption",
")",
":",
"cow_opts",
"+=",
"[",
"(",
"'encryption=%s'",
"%",
"base_details",
".",
"encryption",
")",
"]",
"if",
"(",
"size",
"is",
"not",
"None",
")",
":",
"cow_opts",
"+=",
"[",
"(",
"'size=%s'",
"%",
"size",
")",
"]",
"if",
"cow_opts",
":",
"csv_opts",
"=",
"','",
".",
"join",
"(",
"cow_opts",
")",
"cow_opts",
"=",
"[",
"'-o'",
",",
"csv_opts",
"]",
"cmd",
"=",
"(",
"(",
"base_cmd",
"+",
"cow_opts",
")",
"+",
"[",
"path",
"]",
")",
"execute",
"(",
"*",
"cmd",
")"
] | create cow image creates a cow image with the given backing file . | train | false |
38,607 | @manager.option('-a', '--accounts', dest='accounts', type=unicode, default=u'all')
@manager.option('-m', '--monitors', dest='monitors', type=unicode, default=u'all')
@manager.option('-r', '--send_report', dest='send_report', type=bool, default=False)
def audit_changes(accounts, monitors, send_report):
monitor_names = _parse_tech_names(monitors)
account_names = _parse_accounts(accounts)
sm_audit_changes(account_names, monitor_names, send_report)
| [
"@",
"manager",
".",
"option",
"(",
"'-a'",
",",
"'--accounts'",
",",
"dest",
"=",
"'accounts'",
",",
"type",
"=",
"unicode",
",",
"default",
"=",
"u'all'",
")",
"@",
"manager",
".",
"option",
"(",
"'-m'",
",",
"'--monitors'",
",",
"dest",
"=",
"'monitors'",
",",
"type",
"=",
"unicode",
",",
"default",
"=",
"u'all'",
")",
"@",
"manager",
".",
"option",
"(",
"'-r'",
",",
"'--send_report'",
",",
"dest",
"=",
"'send_report'",
",",
"type",
"=",
"bool",
",",
"default",
"=",
"False",
")",
"def",
"audit_changes",
"(",
"accounts",
",",
"monitors",
",",
"send_report",
")",
":",
"monitor_names",
"=",
"_parse_tech_names",
"(",
"monitors",
")",
"account_names",
"=",
"_parse_accounts",
"(",
"accounts",
")",
"sm_audit_changes",
"(",
"account_names",
",",
"monitor_names",
",",
"send_report",
")"
] | runs auditors . | train | false |
38,610 | def getEvaluatedFloatDefault(defaultFloat, key, xmlElement=None):
evaluatedFloat = getEvaluatedFloat(key, xmlElement)
if (evaluatedFloat == None):
return defaultFloat
return evaluatedFloat
| [
"def",
"getEvaluatedFloatDefault",
"(",
"defaultFloat",
",",
"key",
",",
"xmlElement",
"=",
"None",
")",
":",
"evaluatedFloat",
"=",
"getEvaluatedFloat",
"(",
"key",
",",
"xmlElement",
")",
"if",
"(",
"evaluatedFloat",
"==",
"None",
")",
":",
"return",
"defaultFloat",
"return",
"evaluatedFloat"
] | get the evaluated value as a float . | train | false |
38,613 | def notify_follow(e):
target = e['target']
if (target['screen_name'] != c['original_name']):
return
source = e['source']
created_at = e['created_at']
source_user = (cycle_color(source['name']) + color_func(c['NOTIFICATION']['source_nick'])((' @' + source['screen_name'])))
notify = color_func(c['NOTIFICATION']['notify'])('followed you')
date = parser.parse(created_at)
clock = fallback_humanize(date)
clock = color_func(c['NOTIFICATION']['clock'])(clock)
meta = c['NOTIFY_FORMAT']
meta = source_user.join(meta.split('#source_user'))
meta = notify.join(meta.split('#notify'))
meta = clock.join(meta.split('#clock'))
meta = emojize(meta)
printNicely('')
printNicely(meta)
| [
"def",
"notify_follow",
"(",
"e",
")",
":",
"target",
"=",
"e",
"[",
"'target'",
"]",
"if",
"(",
"target",
"[",
"'screen_name'",
"]",
"!=",
"c",
"[",
"'original_name'",
"]",
")",
":",
"return",
"source",
"=",
"e",
"[",
"'source'",
"]",
"created_at",
"=",
"e",
"[",
"'created_at'",
"]",
"source_user",
"=",
"(",
"cycle_color",
"(",
"source",
"[",
"'name'",
"]",
")",
"+",
"color_func",
"(",
"c",
"[",
"'NOTIFICATION'",
"]",
"[",
"'source_nick'",
"]",
")",
"(",
"(",
"' @'",
"+",
"source",
"[",
"'screen_name'",
"]",
")",
")",
")",
"notify",
"=",
"color_func",
"(",
"c",
"[",
"'NOTIFICATION'",
"]",
"[",
"'notify'",
"]",
")",
"(",
"'followed you'",
")",
"date",
"=",
"parser",
".",
"parse",
"(",
"created_at",
")",
"clock",
"=",
"fallback_humanize",
"(",
"date",
")",
"clock",
"=",
"color_func",
"(",
"c",
"[",
"'NOTIFICATION'",
"]",
"[",
"'clock'",
"]",
")",
"(",
"clock",
")",
"meta",
"=",
"c",
"[",
"'NOTIFY_FORMAT'",
"]",
"meta",
"=",
"source_user",
".",
"join",
"(",
"meta",
".",
"split",
"(",
"'#source_user'",
")",
")",
"meta",
"=",
"notify",
".",
"join",
"(",
"meta",
".",
"split",
"(",
"'#notify'",
")",
")",
"meta",
"=",
"clock",
".",
"join",
"(",
"meta",
".",
"split",
"(",
"'#clock'",
")",
")",
"meta",
"=",
"emojize",
"(",
"meta",
")",
"printNicely",
"(",
"''",
")",
"printNicely",
"(",
"meta",
")"
] | notify a follow event . | train | false |
38,614 | @contextmanager
def check_mongo_calls_range(max_finds=float('inf'), min_finds=0, max_sends=None, min_sends=None):
with check_sum_of_calls(pymongo.message, ['query', 'get_more'], max_finds, min_finds):
if ((max_sends is not None) or (min_sends is not None)):
with check_sum_of_calls(pymongo.message, ['insert', 'update', 'delete', '_do_batched_write_command', '_do_batched_insert'], (max_sends if (max_sends is not None) else float('inf')), (min_sends if (min_sends is not None) else 0)):
(yield)
else:
(yield)
| [
"@",
"contextmanager",
"def",
"check_mongo_calls_range",
"(",
"max_finds",
"=",
"float",
"(",
"'inf'",
")",
",",
"min_finds",
"=",
"0",
",",
"max_sends",
"=",
"None",
",",
"min_sends",
"=",
"None",
")",
":",
"with",
"check_sum_of_calls",
"(",
"pymongo",
".",
"message",
",",
"[",
"'query'",
",",
"'get_more'",
"]",
",",
"max_finds",
",",
"min_finds",
")",
":",
"if",
"(",
"(",
"max_sends",
"is",
"not",
"None",
")",
"or",
"(",
"min_sends",
"is",
"not",
"None",
")",
")",
":",
"with",
"check_sum_of_calls",
"(",
"pymongo",
".",
"message",
",",
"[",
"'insert'",
",",
"'update'",
",",
"'delete'",
",",
"'_do_batched_write_command'",
",",
"'_do_batched_insert'",
"]",
",",
"(",
"max_sends",
"if",
"(",
"max_sends",
"is",
"not",
"None",
")",
"else",
"float",
"(",
"'inf'",
")",
")",
",",
"(",
"min_sends",
"if",
"(",
"min_sends",
"is",
"not",
"None",
")",
"else",
"0",
")",
")",
":",
"(",
"yield",
")",
"else",
":",
"(",
"yield",
")"
] | instruments the given store to count the number of calls to find and the number of calls to send_message which is for insert . | train | false |
38,615 | def clean_old_files(directory):
for (root, dirs, files) in os.walk(directory, topdown=False):
for f in files:
if fnmatch(f, '*.package-control-old'):
path = os.path.join(root, f)
try:
os.remove(path)
except OSError as e:
console_write(u'\n Error removing old file "%s": %s\n ', (path, unicode_from_os(e)))
| [
"def",
"clean_old_files",
"(",
"directory",
")",
":",
"for",
"(",
"root",
",",
"dirs",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"directory",
",",
"topdown",
"=",
"False",
")",
":",
"for",
"f",
"in",
"files",
":",
"if",
"fnmatch",
"(",
"f",
",",
"'*.package-control-old'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
"try",
":",
"os",
".",
"remove",
"(",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"console_write",
"(",
"u'\\n Error removing old file \"%s\": %s\\n '",
",",
"(",
"path",
",",
"unicode_from_os",
"(",
"e",
")",
")",
")"
] | goes through a folder and removes all . | train | false |
38,618 | def onReadyForLogin(isBootstrap):
return 1.0
| [
"def",
"onReadyForLogin",
"(",
"isBootstrap",
")",
":",
"return",
"1.0"
] | kbengine method . | train | false |
38,619 | def norm_l2inf(A, n_orient, copy=True):
if (A.size == 0):
return 0.0
if copy:
A = A.copy()
return sqrt(np.max(groups_norm2(A, n_orient)))
| [
"def",
"norm_l2inf",
"(",
"A",
",",
"n_orient",
",",
"copy",
"=",
"True",
")",
":",
"if",
"(",
"A",
".",
"size",
"==",
"0",
")",
":",
"return",
"0.0",
"if",
"copy",
":",
"A",
"=",
"A",
".",
"copy",
"(",
")",
"return",
"sqrt",
"(",
"np",
".",
"max",
"(",
"groups_norm2",
"(",
"A",
",",
"n_orient",
")",
")",
")"
] | l2-inf norm . | train | false |
38,622 | def _is_zero(x):
if (not hasattr(x, 'type')):
return np.all((x == 0.0))
if isinstance(x.type, NullType):
return 'no'
if isinstance(x.type, DisconnectedType):
return 'yes'
no_constant_value = True
try:
constant_value = theano.get_scalar_constant_value(x)
no_constant_value = False
except theano.tensor.basic.NotScalarConstantError:
pass
if no_constant_value:
return 'maybe'
if (constant_value != 0.0):
return 'no'
return 'yes'
| [
"def",
"_is_zero",
"(",
"x",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"x",
",",
"'type'",
")",
")",
":",
"return",
"np",
".",
"all",
"(",
"(",
"x",
"==",
"0.0",
")",
")",
"if",
"isinstance",
"(",
"x",
".",
"type",
",",
"NullType",
")",
":",
"return",
"'no'",
"if",
"isinstance",
"(",
"x",
".",
"type",
",",
"DisconnectedType",
")",
":",
"return",
"'yes'",
"no_constant_value",
"=",
"True",
"try",
":",
"constant_value",
"=",
"theano",
".",
"get_scalar_constant_value",
"(",
"x",
")",
"no_constant_value",
"=",
"False",
"except",
"theano",
".",
"tensor",
".",
"basic",
".",
"NotScalarConstantError",
":",
"pass",
"if",
"no_constant_value",
":",
"return",
"'maybe'",
"if",
"(",
"constant_value",
"!=",
"0.0",
")",
":",
"return",
"'no'",
"return",
"'yes'"
] | returns yes . | train | false |
38,623 | def hit(filenames, method, *args, **kwargs):
try:
medium = method(*args, **kwargs)
assert medium.exists
except ValueError:
return False
except:
print('Error while processing', method, args, kwargs)
raise
try:
filenames.remove(medium.path)
except KeyError:
pass
return True
| [
"def",
"hit",
"(",
"filenames",
",",
"method",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"medium",
"=",
"method",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"assert",
"medium",
".",
"exists",
"except",
"ValueError",
":",
"return",
"False",
"except",
":",
"print",
"(",
"'Error while processing'",
",",
"method",
",",
"args",
",",
"kwargs",
")",
"raise",
"try",
":",
"filenames",
".",
"remove",
"(",
"medium",
".",
"path",
")",
"except",
"KeyError",
":",
"pass",
"return",
"True"
] | run the given accessor method with args & kwargs; if found remove the result path from filenames and return true . | train | false |
38,625 | def terminate_and_clean(instances):
volumes_to_delete = []
for instance in instances:
for bdmap in instance.block_device_mappings:
if ('Ebs' in bdmap.keys()):
if (not bdmap['Ebs']['DeleteOnTermination']):
volumes_to_delete.append(bdmap['Ebs']['VolumeId'])
for instance in instances:
instance.terminate()
_ids = [instance.id for instance in instances]
all_terminated = False
while (not all_terminated):
all_terminated = True
for _id in _ids:
inst = EC2.Instance(id=_id)
if (inst.state['Name'] != 'terminated'):
all_terminated = False
time.sleep(5)
for vol_id in volumes_to_delete:
volume = EC2.Volume(id=vol_id)
volume.delete()
return volumes_to_delete
| [
"def",
"terminate_and_clean",
"(",
"instances",
")",
":",
"volumes_to_delete",
"=",
"[",
"]",
"for",
"instance",
"in",
"instances",
":",
"for",
"bdmap",
"in",
"instance",
".",
"block_device_mappings",
":",
"if",
"(",
"'Ebs'",
"in",
"bdmap",
".",
"keys",
"(",
")",
")",
":",
"if",
"(",
"not",
"bdmap",
"[",
"'Ebs'",
"]",
"[",
"'DeleteOnTermination'",
"]",
")",
":",
"volumes_to_delete",
".",
"append",
"(",
"bdmap",
"[",
"'Ebs'",
"]",
"[",
"'VolumeId'",
"]",
")",
"for",
"instance",
"in",
"instances",
":",
"instance",
".",
"terminate",
"(",
")",
"_ids",
"=",
"[",
"instance",
".",
"id",
"for",
"instance",
"in",
"instances",
"]",
"all_terminated",
"=",
"False",
"while",
"(",
"not",
"all_terminated",
")",
":",
"all_terminated",
"=",
"True",
"for",
"_id",
"in",
"_ids",
":",
"inst",
"=",
"EC2",
".",
"Instance",
"(",
"id",
"=",
"_id",
")",
"if",
"(",
"inst",
".",
"state",
"[",
"'Name'",
"]",
"!=",
"'terminated'",
")",
":",
"all_terminated",
"=",
"False",
"time",
".",
"sleep",
"(",
"5",
")",
"for",
"vol_id",
"in",
"volumes_to_delete",
":",
"volume",
"=",
"EC2",
".",
"Volume",
"(",
"id",
"=",
"vol_id",
")",
"volume",
".",
"delete",
"(",
")",
"return",
"volumes_to_delete"
] | some amis specify ebs stores that wont delete on instance termination . | train | false |
38,626 | def _compute_message_type(frame_tuple):
(frame, _, line, func, _, _) = frame_tuple
return u':'.join([getmodule(frame).__name__, func, unicode(line)])
| [
"def",
"_compute_message_type",
"(",
"frame_tuple",
")",
":",
"(",
"frame",
",",
"_",
",",
"line",
",",
"func",
",",
"_",
",",
"_",
")",
"=",
"frame_tuple",
"return",
"u':'",
".",
"join",
"(",
"[",
"getmodule",
"(",
"frame",
")",
".",
"__name__",
",",
"func",
",",
"unicode",
"(",
"line",
")",
"]",
")"
] | constructs a human readable message type from a frame of a traceback . | train | false |
38,627 | def codecover(registry, xml_parent, data):
codecover = XML.SubElement(xml_parent, 'hudson.plugins.codecover.CodeCoverPublisher')
codecover.set('plugin', 'codecover')
XML.SubElement(codecover, 'includes').text = str(data.get('include', ''))
health_report = XML.SubElement(codecover, 'healthReports')
mapping = [('min-statement', 'minStatement', 0), ('max-statement', 'maxStatement', 90), ('min-branch', 'minBranch', 0), ('max-branch', 'maxBranch', 80), ('min-loop', 'minLoop', 0), ('max-loop', 'maxLoop', 50), ('min-condition', 'minCondition', 0), ('max-condition', 'maxCondition', 50)]
helpers.convert_mapping_to_xml(health_report, data, mapping, fail_required=True)
| [
"def",
"codecover",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"codecover",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'hudson.plugins.codecover.CodeCoverPublisher'",
")",
"codecover",
".",
"set",
"(",
"'plugin'",
",",
"'codecover'",
")",
"XML",
".",
"SubElement",
"(",
"codecover",
",",
"'includes'",
")",
".",
"text",
"=",
"str",
"(",
"data",
".",
"get",
"(",
"'include'",
",",
"''",
")",
")",
"health_report",
"=",
"XML",
".",
"SubElement",
"(",
"codecover",
",",
"'healthReports'",
")",
"mapping",
"=",
"[",
"(",
"'min-statement'",
",",
"'minStatement'",
",",
"0",
")",
",",
"(",
"'max-statement'",
",",
"'maxStatement'",
",",
"90",
")",
",",
"(",
"'min-branch'",
",",
"'minBranch'",
",",
"0",
")",
",",
"(",
"'max-branch'",
",",
"'maxBranch'",
",",
"80",
")",
",",
"(",
"'min-loop'",
",",
"'minLoop'",
",",
"0",
")",
",",
"(",
"'max-loop'",
",",
"'maxLoop'",
",",
"50",
")",
",",
"(",
"'min-condition'",
",",
"'minCondition'",
",",
"0",
")",
",",
"(",
"'max-condition'",
",",
"'maxCondition'",
",",
"50",
")",
"]",
"helpers",
".",
"convert_mapping_to_xml",
"(",
"health_report",
",",
"data",
",",
"mapping",
",",
"fail_required",
"=",
"True",
")"
] | yaml: codecover this plugin allows you to capture code coverage report from codecover . | train | false |
38,628 | def _transform_ssl_error(strerror):
if (strerror is None):
return 'Unknown connection error'
elif strerror.endswith('certificate verify failed'):
return 'SMTP server SSL certificate verify failed'
else:
return strerror
| [
"def",
"_transform_ssl_error",
"(",
"strerror",
")",
":",
"if",
"(",
"strerror",
"is",
"None",
")",
":",
"return",
"'Unknown connection error'",
"elif",
"strerror",
".",
"endswith",
"(",
"'certificate verify failed'",
")",
":",
"return",
"'SMTP server SSL certificate verify failed'",
"else",
":",
"return",
"strerror"
] | clean up errors like: _ssl . | train | false |
38,629 | def default_nodename(hostname):
(name, host) = nodesplit((hostname or u''))
return nodename((name or NODENAME_DEFAULT), (host or gethostname()))
| [
"def",
"default_nodename",
"(",
"hostname",
")",
":",
"(",
"name",
",",
"host",
")",
"=",
"nodesplit",
"(",
"(",
"hostname",
"or",
"u''",
")",
")",
"return",
"nodename",
"(",
"(",
"name",
"or",
"NODENAME_DEFAULT",
")",
",",
"(",
"host",
"or",
"gethostname",
"(",
")",
")",
")"
] | return the default nodename for this process . | train | false |
38,630 | def details_multiple(output_lines, with_label=False):
items = []
tables_ = tables(output_lines)
for table_ in tables_:
if (('Property' not in table_['headers']) or ('Value' not in table_['headers'])):
raise exceptions.InvalidStructure()
item = {}
for value in table_['values']:
item[value[0]] = value[1]
if with_label:
item['__label'] = table_['label']
items.append(item)
return items
| [
"def",
"details_multiple",
"(",
"output_lines",
",",
"with_label",
"=",
"False",
")",
":",
"items",
"=",
"[",
"]",
"tables_",
"=",
"tables",
"(",
"output_lines",
")",
"for",
"table_",
"in",
"tables_",
":",
"if",
"(",
"(",
"'Property'",
"not",
"in",
"table_",
"[",
"'headers'",
"]",
")",
"or",
"(",
"'Value'",
"not",
"in",
"table_",
"[",
"'headers'",
"]",
")",
")",
":",
"raise",
"exceptions",
".",
"InvalidStructure",
"(",
")",
"item",
"=",
"{",
"}",
"for",
"value",
"in",
"table_",
"[",
"'values'",
"]",
":",
"item",
"[",
"value",
"[",
"0",
"]",
"]",
"=",
"value",
"[",
"1",
"]",
"if",
"with_label",
":",
"item",
"[",
"'__label'",
"]",
"=",
"table_",
"[",
"'label'",
"]",
"items",
".",
"append",
"(",
"item",
")",
"return",
"items"
] | return list of dicts with item details from cli output tables . | train | false |
38,632 | def GetWSAActionFault(operation, name):
attr = operation.faults[name].action
if (attr is not None):
return attr
return WSA.FAULT
| [
"def",
"GetWSAActionFault",
"(",
"operation",
",",
"name",
")",
":",
"attr",
"=",
"operation",
".",
"faults",
"[",
"name",
"]",
".",
"action",
"if",
"(",
"attr",
"is",
"not",
"None",
")",
":",
"return",
"attr",
"return",
"WSA",
".",
"FAULT"
] | find wsa:action attribute . | train | true |
38,633 | def test_analyze_syntax_utf8():
test_string = u'a \xe3 \u0201 \U0001f636 b'
byte_array = test_string.encode('utf8')
result = analyze.analyze_syntax(test_string, encoding='UTF8')
tokens = result['tokens']
assert (tokens[0]['text']['content'] == 'a')
offset = tokens[0]['text'].get('beginOffset', 0)
assert (byte_array[offset:(offset + 1)].decode('utf8') == tokens[0]['text']['content'])
assert (tokens[1]['text']['content'] == u'\xe3')
offset = tokens[1]['text'].get('beginOffset', 0)
assert (byte_array[offset:(offset + 2)].decode('utf8') == tokens[1]['text']['content'])
assert (tokens[2]['text']['content'] == u'\u0201')
offset = tokens[2]['text'].get('beginOffset', 0)
assert (byte_array[offset:(offset + 2)].decode('utf8') == tokens[2]['text']['content'])
assert (tokens[3]['text']['content'] == u'\U0001f636')
offset = tokens[3]['text'].get('beginOffset', 0)
assert (byte_array[offset:(offset + 4)].decode('utf8') == tokens[3]['text']['content'])
assert (tokens[4]['text']['content'] == u'b')
offset = tokens[4]['text'].get('beginOffset', 0)
assert (byte_array[offset:(offset + 1)].decode('utf8') == tokens[4]['text']['content'])
| [
"def",
"test_analyze_syntax_utf8",
"(",
")",
":",
"test_string",
"=",
"u'a \\xe3 \\u0201 \\U0001f636 b'",
"byte_array",
"=",
"test_string",
".",
"encode",
"(",
"'utf8'",
")",
"result",
"=",
"analyze",
".",
"analyze_syntax",
"(",
"test_string",
",",
"encoding",
"=",
"'UTF8'",
")",
"tokens",
"=",
"result",
"[",
"'tokens'",
"]",
"assert",
"(",
"tokens",
"[",
"0",
"]",
"[",
"'text'",
"]",
"[",
"'content'",
"]",
"==",
"'a'",
")",
"offset",
"=",
"tokens",
"[",
"0",
"]",
"[",
"'text'",
"]",
".",
"get",
"(",
"'beginOffset'",
",",
"0",
")",
"assert",
"(",
"byte_array",
"[",
"offset",
":",
"(",
"offset",
"+",
"1",
")",
"]",
".",
"decode",
"(",
"'utf8'",
")",
"==",
"tokens",
"[",
"0",
"]",
"[",
"'text'",
"]",
"[",
"'content'",
"]",
")",
"assert",
"(",
"tokens",
"[",
"1",
"]",
"[",
"'text'",
"]",
"[",
"'content'",
"]",
"==",
"u'\\xe3'",
")",
"offset",
"=",
"tokens",
"[",
"1",
"]",
"[",
"'text'",
"]",
".",
"get",
"(",
"'beginOffset'",
",",
"0",
")",
"assert",
"(",
"byte_array",
"[",
"offset",
":",
"(",
"offset",
"+",
"2",
")",
"]",
".",
"decode",
"(",
"'utf8'",
")",
"==",
"tokens",
"[",
"1",
"]",
"[",
"'text'",
"]",
"[",
"'content'",
"]",
")",
"assert",
"(",
"tokens",
"[",
"2",
"]",
"[",
"'text'",
"]",
"[",
"'content'",
"]",
"==",
"u'\\u0201'",
")",
"offset",
"=",
"tokens",
"[",
"2",
"]",
"[",
"'text'",
"]",
".",
"get",
"(",
"'beginOffset'",
",",
"0",
")",
"assert",
"(",
"byte_array",
"[",
"offset",
":",
"(",
"offset",
"+",
"2",
")",
"]",
".",
"decode",
"(",
"'utf8'",
")",
"==",
"tokens",
"[",
"2",
"]",
"[",
"'text'",
"]",
"[",
"'content'",
"]",
")",
"assert",
"(",
"tokens",
"[",
"3",
"]",
"[",
"'text'",
"]",
"[",
"'content'",
"]",
"==",
"u'\\U0001f636'",
")",
"offset",
"=",
"tokens",
"[",
"3",
"]",
"[",
"'text'",
"]",
".",
"get",
"(",
"'beginOffset'",
",",
"0",
")",
"assert",
"(",
"byte_array",
"[",
"offset",
":",
"(",
"offset",
"+",
"4",
")",
"]",
".",
"decode",
"(",
"'utf8'",
")",
"==",
"tokens",
"[",
"3",
"]",
"[",
"'text'",
"]",
"[",
"'content'",
"]",
")",
"assert",
"(",
"tokens",
"[",
"4",
"]",
"[",
"'text'",
"]",
"[",
"'content'",
"]",
"==",
"u'b'",
")",
"offset",
"=",
"tokens",
"[",
"4",
"]",
"[",
"'text'",
"]",
".",
"get",
"(",
"'beginOffset'",
",",
"0",
")",
"assert",
"(",
"byte_array",
"[",
"offset",
":",
"(",
"offset",
"+",
"1",
")",
"]",
".",
"decode",
"(",
"'utf8'",
")",
"==",
"tokens",
"[",
"4",
"]",
"[",
"'text'",
"]",
"[",
"'content'",
"]",
")"
] | demonstrate the interpretation of the offsets when encoding=utf8 . | train | false |
38,634 | def swfverify(url):
res = urlopen(url)
swf = swfdecompress(res.content)
h = hmac.new(SWF_KEY, swf, hashlib.sha256)
return (h.hexdigest(), len(swf))
| [
"def",
"swfverify",
"(",
"url",
")",
":",
"res",
"=",
"urlopen",
"(",
"url",
")",
"swf",
"=",
"swfdecompress",
"(",
"res",
".",
"content",
")",
"h",
"=",
"hmac",
".",
"new",
"(",
"SWF_KEY",
",",
"swf",
",",
"hashlib",
".",
"sha256",
")",
"return",
"(",
"h",
".",
"hexdigest",
"(",
")",
",",
"len",
"(",
"swf",
")",
")"
] | this function is deprecated . | train | false |
38,635 | def jaccard_distance(label1, label2):
return ((len(label1.union(label2)) - len(label1.intersection(label2))) / len(label1.union(label2)))
| [
"def",
"jaccard_distance",
"(",
"label1",
",",
"label2",
")",
":",
"return",
"(",
"(",
"len",
"(",
"label1",
".",
"union",
"(",
"label2",
")",
")",
"-",
"len",
"(",
"label1",
".",
"intersection",
"(",
"label2",
")",
")",
")",
"/",
"len",
"(",
"label1",
".",
"union",
"(",
"label2",
")",
")",
")"
] | distance metric comparing set-similarity . | train | false |
38,636 | def _giant_steps(target):
res = giant_steps(2, target)
if (res[0] != 2):
res = ([2] + res)
return res
| [
"def",
"_giant_steps",
"(",
"target",
")",
":",
"res",
"=",
"giant_steps",
"(",
"2",
",",
"target",
")",
"if",
"(",
"res",
"[",
"0",
"]",
"!=",
"2",
")",
":",
"res",
"=",
"(",
"[",
"2",
"]",
"+",
"res",
")",
"return",
"res"
] | return a list of precision steps for the newtons method . | train | false |
38,637 | def _unconvert_string_array(data, nan_rep=None, encoding=None):
shape = data.shape
data = np.asarray(data.ravel(), dtype=object)
encoding = _ensure_encoding(encoding)
if ((encoding is not None) and len(data)):
itemsize = lib.max_len_string_array(_ensure_object(data))
if compat.PY3:
dtype = 'U{0}'.format(itemsize)
else:
dtype = 'S{0}'.format(itemsize)
if isinstance(data[0], compat.binary_type):
data = Series(data).str.decode(encoding).values
else:
data = data.astype(dtype, copy=False).astype(object, copy=False)
if (nan_rep is None):
nan_rep = 'nan'
data = lib.string_array_replace_from_nan_rep(data, nan_rep)
return data.reshape(shape)
| [
"def",
"_unconvert_string_array",
"(",
"data",
",",
"nan_rep",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"shape",
"=",
"data",
".",
"shape",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
".",
"ravel",
"(",
")",
",",
"dtype",
"=",
"object",
")",
"encoding",
"=",
"_ensure_encoding",
"(",
"encoding",
")",
"if",
"(",
"(",
"encoding",
"is",
"not",
"None",
")",
"and",
"len",
"(",
"data",
")",
")",
":",
"itemsize",
"=",
"lib",
".",
"max_len_string_array",
"(",
"_ensure_object",
"(",
"data",
")",
")",
"if",
"compat",
".",
"PY3",
":",
"dtype",
"=",
"'U{0}'",
".",
"format",
"(",
"itemsize",
")",
"else",
":",
"dtype",
"=",
"'S{0}'",
".",
"format",
"(",
"itemsize",
")",
"if",
"isinstance",
"(",
"data",
"[",
"0",
"]",
",",
"compat",
".",
"binary_type",
")",
":",
"data",
"=",
"Series",
"(",
"data",
")",
".",
"str",
".",
"decode",
"(",
"encoding",
")",
".",
"values",
"else",
":",
"data",
"=",
"data",
".",
"astype",
"(",
"dtype",
",",
"copy",
"=",
"False",
")",
".",
"astype",
"(",
"object",
",",
"copy",
"=",
"False",
")",
"if",
"(",
"nan_rep",
"is",
"None",
")",
":",
"nan_rep",
"=",
"'nan'",
"data",
"=",
"lib",
".",
"string_array_replace_from_nan_rep",
"(",
"data",
",",
"nan_rep",
")",
"return",
"data",
".",
"reshape",
"(",
"shape",
")"
] | inverse of _convert_string_array parameters data : fixed length string dtyped array nan_rep : the storage repr of nan . | train | false |
38,638 | def validate_unicode_decode_error_handler(dummy, value):
if (value not in _UNICODE_DECODE_ERROR_HANDLERS):
raise ValueError(('%s is an invalid Unicode decode error handler. Must be one of %s' % (value, tuple(_UNICODE_DECODE_ERROR_HANDLERS))))
return value
| [
"def",
"validate_unicode_decode_error_handler",
"(",
"dummy",
",",
"value",
")",
":",
"if",
"(",
"value",
"not",
"in",
"_UNICODE_DECODE_ERROR_HANDLERS",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'%s is an invalid Unicode decode error handler. Must be one of %s'",
"%",
"(",
"value",
",",
"tuple",
"(",
"_UNICODE_DECODE_ERROR_HANDLERS",
")",
")",
")",
")",
"return",
"value"
] | validate the unicode decode error handler option of codecoptions . | train | true |
38,640 | @pytest.mark.skipif((noboto3 or (not fakes3)), reason=u'boto3 or fakes3 library is not available')
def test_aws_keys_from_env():
ds = nio.DataSink()
aws_access_key_id = u'ABCDACCESS'
aws_secret_access_key = u'DEFGSECRET'
os.environ[u'AWS_ACCESS_KEY_ID'] = aws_access_key_id
os.environ[u'AWS_SECRET_ACCESS_KEY'] = aws_secret_access_key
(access_key_test, secret_key_test) = ds._return_aws_keys()
assert (aws_access_key_id == access_key_test)
assert (aws_secret_access_key == secret_key_test)
| [
"@",
"pytest",
".",
"mark",
".",
"skipif",
"(",
"(",
"noboto3",
"or",
"(",
"not",
"fakes3",
")",
")",
",",
"reason",
"=",
"u'boto3 or fakes3 library is not available'",
")",
"def",
"test_aws_keys_from_env",
"(",
")",
":",
"ds",
"=",
"nio",
".",
"DataSink",
"(",
")",
"aws_access_key_id",
"=",
"u'ABCDACCESS'",
"aws_secret_access_key",
"=",
"u'DEFGSECRET'",
"os",
".",
"environ",
"[",
"u'AWS_ACCESS_KEY_ID'",
"]",
"=",
"aws_access_key_id",
"os",
".",
"environ",
"[",
"u'AWS_SECRET_ACCESS_KEY'",
"]",
"=",
"aws_secret_access_key",
"(",
"access_key_test",
",",
"secret_key_test",
")",
"=",
"ds",
".",
"_return_aws_keys",
"(",
")",
"assert",
"(",
"aws_access_key_id",
"==",
"access_key_test",
")",
"assert",
"(",
"aws_secret_access_key",
"==",
"secret_key_test",
")"
] | function to ensure the datasink can successfully read in aws credentials from the environment variables . | train | false |
38,643 | def add_move(move):
setattr(_MovedItems, move.name, move)
| [
"def",
"add_move",
"(",
"move",
")",
":",
"setattr",
"(",
"_MovedItems",
",",
"move",
".",
"name",
",",
"move",
")"
] | add an item to six . | train | false |
38,644 | def scope_to_list(scope):
if isinstance(scope, list):
return [unicode_type(s) for s in scope]
if isinstance(scope, set):
scope_to_list(list(scope))
elif (scope is None):
return None
else:
return scope.split(u' ')
| [
"def",
"scope_to_list",
"(",
"scope",
")",
":",
"if",
"isinstance",
"(",
"scope",
",",
"list",
")",
":",
"return",
"[",
"unicode_type",
"(",
"s",
")",
"for",
"s",
"in",
"scope",
"]",
"if",
"isinstance",
"(",
"scope",
",",
"set",
")",
":",
"scope_to_list",
"(",
"list",
"(",
"scope",
")",
")",
"elif",
"(",
"scope",
"is",
"None",
")",
":",
"return",
"None",
"else",
":",
"return",
"scope",
".",
"split",
"(",
"u' '",
")"
] | convert a space separated string to a list of scopes . | train | false |
38,645 | def linspace(count):
return list(map(float, numpy.linspace(0.0, 1.0, (count + 2), endpoint=True)[1:(-1)]))
| [
"def",
"linspace",
"(",
"count",
")",
":",
"return",
"list",
"(",
"map",
"(",
"float",
",",
"numpy",
".",
"linspace",
"(",
"0.0",
",",
"1.0",
",",
"(",
"count",
"+",
"2",
")",
",",
"endpoint",
"=",
"True",
")",
"[",
"1",
":",
"(",
"-",
"1",
")",
"]",
")",
")"
] | return count evenly spaced points from 0 . | train | false |
38,646 | @pytest.mark.skipif((not product_details.last_update), reason="We don't want to download product_details on travis")
def test_spotcheck():
languages = product_details.languages
assert (languages['el']['English'] == 'Greek')
assert (languages['el']['native'] == u'\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac')
assert (product_details.firefox_history_major_releases['1.0'] == '2004-11-09')
| [
"@",
"pytest",
".",
"mark",
".",
"skipif",
"(",
"(",
"not",
"product_details",
".",
"last_update",
")",
",",
"reason",
"=",
"\"We don't want to download product_details on travis\"",
")",
"def",
"test_spotcheck",
"(",
")",
":",
"languages",
"=",
"product_details",
".",
"languages",
"assert",
"(",
"languages",
"[",
"'el'",
"]",
"[",
"'English'",
"]",
"==",
"'Greek'",
")",
"assert",
"(",
"languages",
"[",
"'el'",
"]",
"[",
"'native'",
"]",
"==",
"u'\\u0395\\u03bb\\u03bb\\u03b7\\u03bd\\u03b9\\u03ba\\u03ac'",
")",
"assert",
"(",
"product_details",
".",
"firefox_history_major_releases",
"[",
"'1.0'",
"]",
"==",
"'2004-11-09'",
")"
] | check a couple product-details files to make sure theyre available . | train | false |
38,647 | @patch('os.path.exists')
def test_resolve_interpreter_with_absolute_path(mock_exists):
mock_exists.return_value = True
virtualenv.is_executable = Mock(return_value=True)
test_abs_path = os.path.abspath('/usr/bin/python53')
exe = virtualenv.resolve_interpreter(test_abs_path)
assert (exe == test_abs_path), 'Absolute path should return as is'
mock_exists.assert_called_with(test_abs_path)
virtualenv.is_executable.assert_called_with(test_abs_path)
| [
"@",
"patch",
"(",
"'os.path.exists'",
")",
"def",
"test_resolve_interpreter_with_absolute_path",
"(",
"mock_exists",
")",
":",
"mock_exists",
".",
"return_value",
"=",
"True",
"virtualenv",
".",
"is_executable",
"=",
"Mock",
"(",
"return_value",
"=",
"True",
")",
"test_abs_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'/usr/bin/python53'",
")",
"exe",
"=",
"virtualenv",
".",
"resolve_interpreter",
"(",
"test_abs_path",
")",
"assert",
"(",
"exe",
"==",
"test_abs_path",
")",
",",
"'Absolute path should return as is'",
"mock_exists",
".",
"assert_called_with",
"(",
"test_abs_path",
")",
"virtualenv",
".",
"is_executable",
".",
"assert_called_with",
"(",
"test_abs_path",
")"
] | should return absolute path if given and exists . | train | false |
38,648 | def _AddUnicodeMethod(unused_message_descriptor, cls):
def __unicode__(self):
return text_format.MessageToString(self, as_utf8=True).decode('utf-8')
cls.__unicode__ = __unicode__
| [
"def",
"_AddUnicodeMethod",
"(",
"unused_message_descriptor",
",",
"cls",
")",
":",
"def",
"__unicode__",
"(",
"self",
")",
":",
"return",
"text_format",
".",
"MessageToString",
"(",
"self",
",",
"as_utf8",
"=",
"True",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"cls",
".",
"__unicode__",
"=",
"__unicode__"
] | helper for _addmessagemethods() . | train | true |
38,652 | def fixup_namespace_packages(path_item, parent=None):
imp.acquire_lock()
try:
for package in _namespace_packages.get(parent, ()):
subpath = _handle_ns(package, path_item)
if subpath:
fixup_namespace_packages(subpath, package)
finally:
imp.release_lock()
| [
"def",
"fixup_namespace_packages",
"(",
"path_item",
",",
"parent",
"=",
"None",
")",
":",
"imp",
".",
"acquire_lock",
"(",
")",
"try",
":",
"for",
"package",
"in",
"_namespace_packages",
".",
"get",
"(",
"parent",
",",
"(",
")",
")",
":",
"subpath",
"=",
"_handle_ns",
"(",
"package",
",",
"path_item",
")",
"if",
"subpath",
":",
"fixup_namespace_packages",
"(",
"subpath",
",",
"package",
")",
"finally",
":",
"imp",
".",
"release_lock",
"(",
")"
] | ensure that previously-declared namespace packages include path_item . | train | true |
38,653 | def test_find_all_candidates_nothing(data):
finder = PackageFinder([], [], session=PipSession())
assert (not finder.find_all_candidates('pip'))
| [
"def",
"test_find_all_candidates_nothing",
"(",
"data",
")",
":",
"finder",
"=",
"PackageFinder",
"(",
"[",
"]",
",",
"[",
"]",
",",
"session",
"=",
"PipSession",
"(",
")",
")",
"assert",
"(",
"not",
"finder",
".",
"find_all_candidates",
"(",
"'pip'",
")",
")"
] | find nothing without anything . | train | false |
38,654 | def provider_fw_rule_get_all(context):
return IMPL.provider_fw_rule_get_all(context)
| [
"def",
"provider_fw_rule_get_all",
"(",
"context",
")",
":",
"return",
"IMPL",
".",
"provider_fw_rule_get_all",
"(",
"context",
")"
] | get all provider-level firewall rules . | train | false |
38,657 | def _ensure_element(tup, elem):
try:
return (tup, tup.index(elem))
except ValueError:
return (tuple(chain(tup, (elem,))), len(tup))
| [
"def",
"_ensure_element",
"(",
"tup",
",",
"elem",
")",
":",
"try",
":",
"return",
"(",
"tup",
",",
"tup",
".",
"index",
"(",
"elem",
")",
")",
"except",
"ValueError",
":",
"return",
"(",
"tuple",
"(",
"chain",
"(",
"tup",
",",
"(",
"elem",
",",
")",
")",
")",
",",
"len",
"(",
"tup",
")",
")"
] | create a tuple containing all elements of tup . | train | true |
38,658 | def convertElementNodeByPath(elementNode, geometryOutput):
createLinkPath(elementNode)
elementNode.xmlObject.vertexes = geometryOutput
vertex.addGeometryList(elementNode, geometryOutput)
| [
"def",
"convertElementNodeByPath",
"(",
"elementNode",
",",
"geometryOutput",
")",
":",
"createLinkPath",
"(",
"elementNode",
")",
"elementNode",
".",
"xmlObject",
".",
"vertexes",
"=",
"geometryOutput",
"vertex",
".",
"addGeometryList",
"(",
"elementNode",
",",
"geometryOutput",
")"
] | convert the xml element to a path xml element . | train | false |
38,661 | def get_setting_name_and_refid(node):
(entry_type, info, refid) = node['entries'][0][:3]
return (info.replace('; setting', ''), refid)
| [
"def",
"get_setting_name_and_refid",
"(",
"node",
")",
":",
"(",
"entry_type",
",",
"info",
",",
"refid",
")",
"=",
"node",
"[",
"'entries'",
"]",
"[",
"0",
"]",
"[",
":",
"3",
"]",
"return",
"(",
"info",
".",
"replace",
"(",
"'; setting'",
",",
"''",
")",
",",
"refid",
")"
] | extract setting name from directive index node . | train | false |
38,662 | def _pick_aux_channels(info, exclude='bads'):
return pick_types(info, meg=False, eog=True, ecg=True, emg=True, bio=True, ref_meg=False, exclude=exclude)
| [
"def",
"_pick_aux_channels",
"(",
"info",
",",
"exclude",
"=",
"'bads'",
")",
":",
"return",
"pick_types",
"(",
"info",
",",
"meg",
"=",
"False",
",",
"eog",
"=",
"True",
",",
"ecg",
"=",
"True",
",",
"emg",
"=",
"True",
",",
"bio",
"=",
"True",
",",
"ref_meg",
"=",
"False",
",",
"exclude",
"=",
"exclude",
")"
] | pick only auxiliary channels . | train | false |
38,663 | def process_package_source(target, source, env):
shutil.copy2(str(source[0]), str(target[0]))
return None
| [
"def",
"process_package_source",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"shutil",
".",
"copy2",
"(",
"str",
"(",
"source",
"[",
"0",
"]",
")",
",",
"str",
"(",
"target",
"[",
"0",
"]",
")",
")",
"return",
"None"
] | copy source file into . | train | false |
38,666 | @handle_dashboard_error
@require_POST
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
@require_post_params('student')
def show_student_extensions(request, course_id):
student = require_student_from_identifier(request.POST.get('student'))
course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
return JsonResponse(dump_student_extensions(course, student))
| [
"@",
"handle_dashboard_error",
"@",
"require_POST",
"@",
"ensure_csrf_cookie",
"@",
"cache_control",
"(",
"no_cache",
"=",
"True",
",",
"no_store",
"=",
"True",
",",
"must_revalidate",
"=",
"True",
")",
"@",
"require_level",
"(",
"'staff'",
")",
"@",
"require_post_params",
"(",
"'student'",
")",
"def",
"show_student_extensions",
"(",
"request",
",",
"course_id",
")",
":",
"student",
"=",
"require_student_from_identifier",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'student'",
")",
")",
"course",
"=",
"get_course_by_id",
"(",
"SlashSeparatedCourseKey",
".",
"from_deprecated_string",
"(",
"course_id",
")",
")",
"return",
"JsonResponse",
"(",
"dump_student_extensions",
"(",
"course",
",",
"student",
")",
")"
] | shows all of the due date extensions granted to a particular student in a particular course . | train | false |
38,668 | def emailUser(profile, SUBJECT='', BODY=''):
def generateSMSEmail(profile):
"\n Generates an email from a user's phone number based on their carrier.\n "
if ((profile['carrier'] is None) or (not profile['phone_number'])):
return None
return ((str(profile['phone_number']) + '@') + profile['carrier'])
if (profile['prefers_email'] and profile['gmail_address']):
if BODY:
BODY = ((profile['first_name'] + ',<br><br>Here are your top headlines:') + BODY)
BODY += '<br>Sent from your Jasper'
recipient = profile['gmail_address']
if (profile['first_name'] and profile['last_name']):
recipient = (((profile['first_name'] + ' ') + profile['last_name']) + (' <%s>' % recipient))
else:
recipient = generateSMSEmail(profile)
if (not recipient):
return False
try:
if ('mailgun' in profile):
user = profile['mailgun']['username']
password = profile['mailgun']['password']
server = 'smtp.mailgun.org'
else:
user = profile['gmail_address']
password = profile['gmail_password']
server = 'smtp.gmail.com'
sendEmail(SUBJECT, BODY, recipient, user, 'Jasper <jasper>', password, server)
return True
except:
return False
| [
"def",
"emailUser",
"(",
"profile",
",",
"SUBJECT",
"=",
"''",
",",
"BODY",
"=",
"''",
")",
":",
"def",
"generateSMSEmail",
"(",
"profile",
")",
":",
"if",
"(",
"(",
"profile",
"[",
"'carrier'",
"]",
"is",
"None",
")",
"or",
"(",
"not",
"profile",
"[",
"'phone_number'",
"]",
")",
")",
":",
"return",
"None",
"return",
"(",
"(",
"str",
"(",
"profile",
"[",
"'phone_number'",
"]",
")",
"+",
"'@'",
")",
"+",
"profile",
"[",
"'carrier'",
"]",
")",
"if",
"(",
"profile",
"[",
"'prefers_email'",
"]",
"and",
"profile",
"[",
"'gmail_address'",
"]",
")",
":",
"if",
"BODY",
":",
"BODY",
"=",
"(",
"(",
"profile",
"[",
"'first_name'",
"]",
"+",
"',<br><br>Here are your top headlines:'",
")",
"+",
"BODY",
")",
"BODY",
"+=",
"'<br>Sent from your Jasper'",
"recipient",
"=",
"profile",
"[",
"'gmail_address'",
"]",
"if",
"(",
"profile",
"[",
"'first_name'",
"]",
"and",
"profile",
"[",
"'last_name'",
"]",
")",
":",
"recipient",
"=",
"(",
"(",
"(",
"profile",
"[",
"'first_name'",
"]",
"+",
"' '",
")",
"+",
"profile",
"[",
"'last_name'",
"]",
")",
"+",
"(",
"' <%s>'",
"%",
"recipient",
")",
")",
"else",
":",
"recipient",
"=",
"generateSMSEmail",
"(",
"profile",
")",
"if",
"(",
"not",
"recipient",
")",
":",
"return",
"False",
"try",
":",
"if",
"(",
"'mailgun'",
"in",
"profile",
")",
":",
"user",
"=",
"profile",
"[",
"'mailgun'",
"]",
"[",
"'username'",
"]",
"password",
"=",
"profile",
"[",
"'mailgun'",
"]",
"[",
"'password'",
"]",
"server",
"=",
"'smtp.mailgun.org'",
"else",
":",
"user",
"=",
"profile",
"[",
"'gmail_address'",
"]",
"password",
"=",
"profile",
"[",
"'gmail_password'",
"]",
"server",
"=",
"'smtp.gmail.com'",
"sendEmail",
"(",
"SUBJECT",
",",
"BODY",
",",
"recipient",
",",
"user",
",",
"'Jasper <jasper>'",
",",
"password",
",",
"server",
")",
"return",
"True",
"except",
":",
"return",
"False"
] | sends an email . | train | false |
38,671 | def unmount_share(mount_path, export_path):
try:
utils.execute('umount', mount_path, run_as_root=True, attempts=3, delay_on_retry=True)
except processutils.ProcessExecutionError as exc:
if ('target is busy' in six.text_type(exc)):
LOG.debug('The share %s is still in use.', export_path)
else:
LOG.exception(_LE("Couldn't unmount the share %s"), export_path)
| [
"def",
"unmount_share",
"(",
"mount_path",
",",
"export_path",
")",
":",
"try",
":",
"utils",
".",
"execute",
"(",
"'umount'",
",",
"mount_path",
",",
"run_as_root",
"=",
"True",
",",
"attempts",
"=",
"3",
",",
"delay_on_retry",
"=",
"True",
")",
"except",
"processutils",
".",
"ProcessExecutionError",
"as",
"exc",
":",
"if",
"(",
"'target is busy'",
"in",
"six",
".",
"text_type",
"(",
"exc",
")",
")",
":",
"LOG",
".",
"debug",
"(",
"'The share %s is still in use.'",
",",
"export_path",
")",
"else",
":",
"LOG",
".",
"exception",
"(",
"_LE",
"(",
"\"Couldn't unmount the share %s\"",
")",
",",
"export_path",
")"
] | unmount a remote share . | train | false |
38,672 | def nri(distmat, marginals, group, iters):
group_marginals = [marginals.index(i) for i in group]
mn_x_obs = mpd(reduce_mtx(distmat, group_marginals))
(mn_x_n, sd_x_n) = random_mpd(distmat, len(group_marginals), iters)
if (abs(sd_x_n) < 1e-05):
raise ValueError(((('The standard deviation of the means of the random' + ' draws from the distance matrix was less than .00001. This is') + ' likely do to a phylogeny with distances to all tips equal.') + ' This phylogeny is not suitable for NRI/NTI analysis.'))
return ((-1.0) * ((mn_x_obs - mn_x_n) / sd_x_n))
| [
"def",
"nri",
"(",
"distmat",
",",
"marginals",
",",
"group",
",",
"iters",
")",
":",
"group_marginals",
"=",
"[",
"marginals",
".",
"index",
"(",
"i",
")",
"for",
"i",
"in",
"group",
"]",
"mn_x_obs",
"=",
"mpd",
"(",
"reduce_mtx",
"(",
"distmat",
",",
"group_marginals",
")",
")",
"(",
"mn_x_n",
",",
"sd_x_n",
")",
"=",
"random_mpd",
"(",
"distmat",
",",
"len",
"(",
"group_marginals",
")",
",",
"iters",
")",
"if",
"(",
"abs",
"(",
"sd_x_n",
")",
"<",
"1e-05",
")",
":",
"raise",
"ValueError",
"(",
"(",
"(",
"(",
"'The standard deviation of the means of the random'",
"+",
"' draws from the distance matrix was less than .00001. This is'",
")",
"+",
"' likely do to a phylogeny with distances to all tips equal.'",
")",
"+",
"' This phylogeny is not suitable for NRI/NTI analysis.'",
")",
")",
"return",
"(",
"(",
"-",
"1.0",
")",
"*",
"(",
"(",
"mn_x_obs",
"-",
"mn_x_n",
")",
"/",
"sd_x_n",
")",
")"
] | calculate the nri of the selected group . | train | false |
38,674 | def file_uri(fname):
if (os.name == 'nt'):
if re.search('^[a-zA-Z]:', fname):
return ('file:///' + fname)
else:
return ('file://' + fname)
else:
return ('file://' + fname)
| [
"def",
"file_uri",
"(",
"fname",
")",
":",
"if",
"(",
"os",
".",
"name",
"==",
"'nt'",
")",
":",
"if",
"re",
".",
"search",
"(",
"'^[a-zA-Z]:'",
",",
"fname",
")",
":",
"return",
"(",
"'file:///'",
"+",
"fname",
")",
"else",
":",
"return",
"(",
"'file://'",
"+",
"fname",
")",
"else",
":",
"return",
"(",
"'file://'",
"+",
"fname",
")"
] | select the right file uri scheme according to the operating system . | train | true |
38,675 | def extract_svhn(local_url):
with gfile.Open(local_url, mode='r') as file_obj:
dict = loadmat(file_obj)
(data, labels) = (dict['X'], dict['y'])
data = np.asarray(data, dtype=np.float32)
labels = np.asarray(labels, dtype=np.int32)
data = data.transpose(3, 0, 1, 2)
labels[(labels == 10)] = 0
labels = labels.reshape(len(labels))
return (data, labels)
| [
"def",
"extract_svhn",
"(",
"local_url",
")",
":",
"with",
"gfile",
".",
"Open",
"(",
"local_url",
",",
"mode",
"=",
"'r'",
")",
"as",
"file_obj",
":",
"dict",
"=",
"loadmat",
"(",
"file_obj",
")",
"(",
"data",
",",
"labels",
")",
"=",
"(",
"dict",
"[",
"'X'",
"]",
",",
"dict",
"[",
"'y'",
"]",
")",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"labels",
"=",
"np",
".",
"asarray",
"(",
"labels",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"data",
"=",
"data",
".",
"transpose",
"(",
"3",
",",
"0",
",",
"1",
",",
"2",
")",
"labels",
"[",
"(",
"labels",
"==",
"10",
")",
"]",
"=",
"0",
"labels",
"=",
"labels",
".",
"reshape",
"(",
"len",
"(",
"labels",
")",
")",
"return",
"(",
"data",
",",
"labels",
")"
] | extract a matlab matrix into two numpy arrays with data and labels . | train | false |
38,676 | def libvlc_video_get_crop_geometry(p_mi):
f = (_Cfunctions.get('libvlc_video_get_crop_geometry', None) or _Cfunction('libvlc_video_get_crop_geometry', ((1,),), string_result, ctypes.c_void_p, MediaPlayer))
return f(p_mi)
| [
"def",
"libvlc_video_get_crop_geometry",
"(",
"p_mi",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_video_get_crop_geometry'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_video_get_crop_geometry'",
",",
"(",
"(",
"1",
",",
")",
",",
")",
",",
"string_result",
",",
"ctypes",
".",
"c_void_p",
",",
"MediaPlayer",
")",
")",
"return",
"f",
"(",
"p_mi",
")"
] | get current crop filter geometry . | train | true |
38,677 | def _normalize_locations(context, image, force_show_deleted=False):
if ((image['status'] == 'deactivated') and (not context.is_admin)):
image['locations'] = []
return image
if force_show_deleted:
locations = image['locations']
else:
locations = [x for x in image['locations'] if (not x.deleted)]
image['locations'] = [{'id': loc['id'], 'url': loc['value'], 'metadata': loc['meta_data'], 'status': loc['status']} for loc in locations]
return image
| [
"def",
"_normalize_locations",
"(",
"context",
",",
"image",
",",
"force_show_deleted",
"=",
"False",
")",
":",
"if",
"(",
"(",
"image",
"[",
"'status'",
"]",
"==",
"'deactivated'",
")",
"and",
"(",
"not",
"context",
".",
"is_admin",
")",
")",
":",
"image",
"[",
"'locations'",
"]",
"=",
"[",
"]",
"return",
"image",
"if",
"force_show_deleted",
":",
"locations",
"=",
"image",
"[",
"'locations'",
"]",
"else",
":",
"locations",
"=",
"[",
"x",
"for",
"x",
"in",
"image",
"[",
"'locations'",
"]",
"if",
"(",
"not",
"x",
".",
"deleted",
")",
"]",
"image",
"[",
"'locations'",
"]",
"=",
"[",
"{",
"'id'",
":",
"loc",
"[",
"'id'",
"]",
",",
"'url'",
":",
"loc",
"[",
"'value'",
"]",
",",
"'metadata'",
":",
"loc",
"[",
"'meta_data'",
"]",
",",
"'status'",
":",
"loc",
"[",
"'status'",
"]",
"}",
"for",
"loc",
"in",
"locations",
"]",
"return",
"image"
] | generate suitable dictionary list for locations field of image . | train | false |
38,678 | def get_multi(keys):
assert isinstance(keys, list)
result = memcache.get_multi(keys)
return result
| [
"def",
"get_multi",
"(",
"keys",
")",
":",
"assert",
"isinstance",
"(",
"keys",
",",
"list",
")",
"result",
"=",
"memcache",
".",
"get_multi",
"(",
"keys",
")",
"return",
"result"
] | looks up a list of keys in memcache . | train | false |
38,679 | @app.route('/<path>')
def static_file(path):
url = app.config['SERVICE_MAP']['static']
res = requests.get(((url + '/') + path))
return (res.content, 200, {'Content-Type': res.headers['Content-Type']})
| [
"@",
"app",
".",
"route",
"(",
"'/<path>'",
")",
"def",
"static_file",
"(",
"path",
")",
":",
"url",
"=",
"app",
".",
"config",
"[",
"'SERVICE_MAP'",
"]",
"[",
"'static'",
"]",
"res",
"=",
"requests",
".",
"get",
"(",
"(",
"(",
"url",
"+",
"'/'",
")",
"+",
"path",
")",
")",
"return",
"(",
"res",
".",
"content",
",",
"200",
",",
"{",
"'Content-Type'",
":",
"res",
".",
"headers",
"[",
"'Content-Type'",
"]",
"}",
")"
] | serves static files required by index . | train | false |
38,680 | def test_complete():
K4 = nx.complete_graph(4)
assert_equal(len(nx.dominating_set(K4)), 1)
K5 = nx.complete_graph(5)
assert_equal(len(nx.dominating_set(K5)), 1)
| [
"def",
"test_complete",
"(",
")",
":",
"K4",
"=",
"nx",
".",
"complete_graph",
"(",
"4",
")",
"assert_equal",
"(",
"len",
"(",
"nx",
".",
"dominating_set",
"(",
"K4",
")",
")",
",",
"1",
")",
"K5",
"=",
"nx",
".",
"complete_graph",
"(",
"5",
")",
"assert_equal",
"(",
"len",
"(",
"nx",
".",
"dominating_set",
"(",
"K5",
")",
")",
",",
"1",
")"
] | in complete graphs each node is a dominating set . | train | false |
38,681 | def _fill_measurement_info(info, fwd, sfreq):
sel = pick_channels(info['ch_names'], fwd['sol']['row_names'])
info = pick_info(info, sel)
info['bads'] = []
info['meas_id'] = fwd['info']['meas_id']
info['file_id'] = info['meas_id']
now = time()
sec = np.floor(now)
usec = (1000000.0 * (now - sec))
info['meas_date'] = np.array([sec, usec], dtype=np.int32)
info['highpass'] = 0.0
info['lowpass'] = (sfreq / 2.0)
info['sfreq'] = sfreq
info['projs'] = []
return info
| [
"def",
"_fill_measurement_info",
"(",
"info",
",",
"fwd",
",",
"sfreq",
")",
":",
"sel",
"=",
"pick_channels",
"(",
"info",
"[",
"'ch_names'",
"]",
",",
"fwd",
"[",
"'sol'",
"]",
"[",
"'row_names'",
"]",
")",
"info",
"=",
"pick_info",
"(",
"info",
",",
"sel",
")",
"info",
"[",
"'bads'",
"]",
"=",
"[",
"]",
"info",
"[",
"'meas_id'",
"]",
"=",
"fwd",
"[",
"'info'",
"]",
"[",
"'meas_id'",
"]",
"info",
"[",
"'file_id'",
"]",
"=",
"info",
"[",
"'meas_id'",
"]",
"now",
"=",
"time",
"(",
")",
"sec",
"=",
"np",
".",
"floor",
"(",
"now",
")",
"usec",
"=",
"(",
"1000000.0",
"*",
"(",
"now",
"-",
"sec",
")",
")",
"info",
"[",
"'meas_date'",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"sec",
",",
"usec",
"]",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"info",
"[",
"'highpass'",
"]",
"=",
"0.0",
"info",
"[",
"'lowpass'",
"]",
"=",
"(",
"sfreq",
"/",
"2.0",
")",
"info",
"[",
"'sfreq'",
"]",
"=",
"sfreq",
"info",
"[",
"'projs'",
"]",
"=",
"[",
"]",
"return",
"info"
] | fill the measurement info of a raw or evoked object . | train | false |
38,684 | def _augknt(x, k):
return np.r_[(((x[0],) * k), x, ((x[(-1)],) * k))]
| [
"def",
"_augknt",
"(",
"x",
",",
"k",
")",
":",
"return",
"np",
".",
"r_",
"[",
"(",
"(",
"(",
"x",
"[",
"0",
"]",
",",
")",
"*",
"k",
")",
",",
"x",
",",
"(",
"(",
"x",
"[",
"(",
"-",
"1",
")",
"]",
",",
")",
"*",
"k",
")",
")",
"]"
] | construct a knot vector appropriate for the order-k interpolation . | train | false |
38,685 | def _save_activity_rights(committer_id, activity_rights, activity_type, commit_message, commit_cmds):
activity_rights.validate()
if (activity_type == feconf.ACTIVITY_TYPE_EXPLORATION):
model_cls = exp_models.ExplorationRightsModel
elif (activity_type == feconf.ACTIVITY_TYPE_COLLECTION):
model_cls = collection_models.CollectionRightsModel
model = model_cls.get(activity_rights.id, strict=False)
model.owner_ids = activity_rights.owner_ids
model.editor_ids = activity_rights.editor_ids
model.viewer_ids = activity_rights.viewer_ids
model.community_owned = activity_rights.community_owned
model.status = activity_rights.status
model.viewable_if_private = activity_rights.viewable_if_private
model.first_published_msec = activity_rights.first_published_msec
model.commit(committer_id, commit_message, commit_cmds)
| [
"def",
"_save_activity_rights",
"(",
"committer_id",
",",
"activity_rights",
",",
"activity_type",
",",
"commit_message",
",",
"commit_cmds",
")",
":",
"activity_rights",
".",
"validate",
"(",
")",
"if",
"(",
"activity_type",
"==",
"feconf",
".",
"ACTIVITY_TYPE_EXPLORATION",
")",
":",
"model_cls",
"=",
"exp_models",
".",
"ExplorationRightsModel",
"elif",
"(",
"activity_type",
"==",
"feconf",
".",
"ACTIVITY_TYPE_COLLECTION",
")",
":",
"model_cls",
"=",
"collection_models",
".",
"CollectionRightsModel",
"model",
"=",
"model_cls",
".",
"get",
"(",
"activity_rights",
".",
"id",
",",
"strict",
"=",
"False",
")",
"model",
".",
"owner_ids",
"=",
"activity_rights",
".",
"owner_ids",
"model",
".",
"editor_ids",
"=",
"activity_rights",
".",
"editor_ids",
"model",
".",
"viewer_ids",
"=",
"activity_rights",
".",
"viewer_ids",
"model",
".",
"community_owned",
"=",
"activity_rights",
".",
"community_owned",
"model",
".",
"status",
"=",
"activity_rights",
".",
"status",
"model",
".",
"viewable_if_private",
"=",
"activity_rights",
".",
"viewable_if_private",
"model",
".",
"first_published_msec",
"=",
"activity_rights",
".",
"first_published_msec",
"model",
".",
"commit",
"(",
"committer_id",
",",
"commit_message",
",",
"commit_cmds",
")"
] | saves an explorationrights or collectionrights domain object to the datastore . | train | false |
38,686 | def zscore(a, axis=0, ddof=0):
a = np.asanyarray(a)
mns = a.mean(axis=axis)
sstd = a.std(axis=axis, ddof=ddof)
if (axis and (mns.ndim < a.ndim)):
return ((a - np.expand_dims(mns, axis=axis)) / np.expand_dims(sstd, axis=axis))
else:
return ((a - mns) / sstd)
| [
"def",
"zscore",
"(",
"a",
",",
"axis",
"=",
"0",
",",
"ddof",
"=",
"0",
")",
":",
"a",
"=",
"np",
".",
"asanyarray",
"(",
"a",
")",
"mns",
"=",
"a",
".",
"mean",
"(",
"axis",
"=",
"axis",
")",
"sstd",
"=",
"a",
".",
"std",
"(",
"axis",
"=",
"axis",
",",
"ddof",
"=",
"ddof",
")",
"if",
"(",
"axis",
"and",
"(",
"mns",
".",
"ndim",
"<",
"a",
".",
"ndim",
")",
")",
":",
"return",
"(",
"(",
"a",
"-",
"np",
".",
"expand_dims",
"(",
"mns",
",",
"axis",
"=",
"axis",
")",
")",
"/",
"np",
".",
"expand_dims",
"(",
"sstd",
",",
"axis",
"=",
"axis",
")",
")",
"else",
":",
"return",
"(",
"(",
"a",
"-",
"mns",
")",
"/",
"sstd",
")"
] | calculates the z score of each value in the sample . | train | true |
38,687 | def get_ccx_from_ccx_locator(course_id):
ccx_id = getattr(course_id, 'ccx', None)
ccx = None
if ccx_id:
ccx = CustomCourseForEdX.objects.filter(id=ccx_id)
if (not ccx):
log.warning('CCX does not exist for course with id %s', course_id)
return None
return ccx[0]
| [
"def",
"get_ccx_from_ccx_locator",
"(",
"course_id",
")",
":",
"ccx_id",
"=",
"getattr",
"(",
"course_id",
",",
"'ccx'",
",",
"None",
")",
"ccx",
"=",
"None",
"if",
"ccx_id",
":",
"ccx",
"=",
"CustomCourseForEdX",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"ccx_id",
")",
"if",
"(",
"not",
"ccx",
")",
":",
"log",
".",
"warning",
"(",
"'CCX does not exist for course with id %s'",
",",
"course_id",
")",
"return",
"None",
"return",
"ccx",
"[",
"0",
"]"
] | helper function to allow querying ccx fields from templates . | train | false |
38,688 | def kill_raspistill(*args):
subprocess.Popen(['killall', 'raspistill'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
| [
"def",
"kill_raspistill",
"(",
"*",
"args",
")",
":",
"subprocess",
".",
"Popen",
"(",
"[",
"'killall'",
",",
"'raspistill'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"DEVNULL",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")"
] | kill any previously running raspistill process . | train | false |
38,689 | def rgbcie2rgb(rgbcie):
return _convert(rgb_from_rgbcie, rgbcie)
| [
"def",
"rgbcie2rgb",
"(",
"rgbcie",
")",
":",
"return",
"_convert",
"(",
"rgb_from_rgbcie",
",",
"rgbcie",
")"
] | rgb cie to rgb color space conversion . | train | false |
38,690 | def cluster_position():
return s3_rest_controller()
| [
"def",
"cluster_position",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | volunteer group positions controller . | train | false |
38,691 | def PercentileRow(array, p):
(rows, cols) = array.shape
index = int(((rows * p) / 100))
return array[(index,)]
| [
"def",
"PercentileRow",
"(",
"array",
",",
"p",
")",
":",
"(",
"rows",
",",
"cols",
")",
"=",
"array",
".",
"shape",
"index",
"=",
"int",
"(",
"(",
"(",
"rows",
"*",
"p",
")",
"/",
"100",
")",
")",
"return",
"array",
"[",
"(",
"index",
",",
")",
"]"
] | selects the row from a sorted array that maps to percentile p . | train | false |
38,692 | def invalidate_hash(suffix_dir):
suffix = basename(suffix_dir)
partition_dir = dirname(suffix_dir)
invalidations_file = join(partition_dir, HASH_INVALIDATIONS_FILE)
with lock_path(partition_dir):
with open(invalidations_file, 'ab') as inv_fh:
inv_fh.write((suffix + '\n'))
| [
"def",
"invalidate_hash",
"(",
"suffix_dir",
")",
":",
"suffix",
"=",
"basename",
"(",
"suffix_dir",
")",
"partition_dir",
"=",
"dirname",
"(",
"suffix_dir",
")",
"invalidations_file",
"=",
"join",
"(",
"partition_dir",
",",
"HASH_INVALIDATIONS_FILE",
")",
"with",
"lock_path",
"(",
"partition_dir",
")",
":",
"with",
"open",
"(",
"invalidations_file",
",",
"'ab'",
")",
"as",
"inv_fh",
":",
"inv_fh",
".",
"write",
"(",
"(",
"suffix",
"+",
"'\\n'",
")",
")"
] | invalidates the hash for a suffix_dir in the partitions hashes file . | train | false |
38,693 | def circular_layout(G, scale=1, center=None, dim=2):
import numpy as np
(G, center) = _process_params(G, center, dim)
if (len(G) == 0):
pos = {}
elif (len(G) == 1):
pos = {nx.utils.arbitrary_element(G): center}
else:
theta = ((np.linspace(0, 1, (len(G) + 1))[:(-1)] * 2) * np.pi)
theta = theta.astype(np.float32)
pos = np.column_stack([np.cos(theta), np.sin(theta)])
pos = (rescale_layout(pos, scale=scale) + center)
pos = dict(zip(G, pos))
return pos
| [
"def",
"circular_layout",
"(",
"G",
",",
"scale",
"=",
"1",
",",
"center",
"=",
"None",
",",
"dim",
"=",
"2",
")",
":",
"import",
"numpy",
"as",
"np",
"(",
"G",
",",
"center",
")",
"=",
"_process_params",
"(",
"G",
",",
"center",
",",
"dim",
")",
"if",
"(",
"len",
"(",
"G",
")",
"==",
"0",
")",
":",
"pos",
"=",
"{",
"}",
"elif",
"(",
"len",
"(",
"G",
")",
"==",
"1",
")",
":",
"pos",
"=",
"{",
"nx",
".",
"utils",
".",
"arbitrary_element",
"(",
"G",
")",
":",
"center",
"}",
"else",
":",
"theta",
"=",
"(",
"(",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"(",
"len",
"(",
"G",
")",
"+",
"1",
")",
")",
"[",
":",
"(",
"-",
"1",
")",
"]",
"*",
"2",
")",
"*",
"np",
".",
"pi",
")",
"theta",
"=",
"theta",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"pos",
"=",
"np",
".",
"column_stack",
"(",
"[",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"np",
".",
"sin",
"(",
"theta",
")",
"]",
")",
"pos",
"=",
"(",
"rescale_layout",
"(",
"pos",
",",
"scale",
"=",
"scale",
")",
"+",
"center",
")",
"pos",
"=",
"dict",
"(",
"zip",
"(",
"G",
",",
"pos",
")",
")",
"return",
"pos"
] | position nodes on a circle . | train | false |
38,694 | def LabelFromString(xml_string):
return atom.CreateClassFromXMLString(Label, xml_string)
| [
"def",
"LabelFromString",
"(",
"xml_string",
")",
":",
"return",
"atom",
".",
"CreateClassFromXMLString",
"(",
"Label",
",",
"xml_string",
")"
] | parse in the mailitemproperty from the xml definition . | train | false |
38,695 | def test_can_parse_keys_from_table():
step = Step.from_string(I_HAVE_TASTY_BEVERAGES)
assert_equals(step.keys, ('Name', 'Type', 'Price'))
| [
"def",
"test_can_parse_keys_from_table",
"(",
")",
":",
"step",
"=",
"Step",
".",
"from_string",
"(",
"I_HAVE_TASTY_BEVERAGES",
")",
"assert_equals",
"(",
"step",
".",
"keys",
",",
"(",
"'Name'",
",",
"'Type'",
",",
"'Price'",
")",
")"
] | it should take the keys from the step . | train | false |
38,696 | def test_attribute_empty():
cant_compile(u'.')
cant_compile(u'foo.')
cant_compile(u'.foo')
cant_compile(u'"bar".foo')
cant_compile(u'[2].foo')
| [
"def",
"test_attribute_empty",
"(",
")",
":",
"cant_compile",
"(",
"u'.'",
")",
"cant_compile",
"(",
"u'foo.'",
")",
"cant_compile",
"(",
"u'.foo'",
")",
"cant_compile",
"(",
"u'\"bar\".foo'",
")",
"cant_compile",
"(",
"u'[2].foo'",
")"
] | ensure using dot notation with a non-expression is an error . | train | false |
38,697 | def parse_scheme(scheme, stream, error_handler=None, allow_pickle_data=False):
warnings.warn("Use 'scheme_load' instead", DeprecationWarning, stacklevel=2)
doc = parse(stream)
scheme_el = doc.getroot()
version = scheme_el.attrib.get('version', None)
if (version is None):
if (scheme_el.find('widgets') is not None):
version = '1.0'
else:
version = '2.0'
if (error_handler is None):
def error_handler(exc):
raise exc
if (version == '1.0'):
parse_scheme_v_1_0(doc, scheme, error_handler=error_handler, allow_pickle_data=allow_pickle_data)
return scheme
else:
parse_scheme_v_2_0(doc, scheme, error_handler=error_handler, allow_pickle_data=allow_pickle_data)
return scheme
| [
"def",
"parse_scheme",
"(",
"scheme",
",",
"stream",
",",
"error_handler",
"=",
"None",
",",
"allow_pickle_data",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use 'scheme_load' instead\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"doc",
"=",
"parse",
"(",
"stream",
")",
"scheme_el",
"=",
"doc",
".",
"getroot",
"(",
")",
"version",
"=",
"scheme_el",
".",
"attrib",
".",
"get",
"(",
"'version'",
",",
"None",
")",
"if",
"(",
"version",
"is",
"None",
")",
":",
"if",
"(",
"scheme_el",
".",
"find",
"(",
"'widgets'",
")",
"is",
"not",
"None",
")",
":",
"version",
"=",
"'1.0'",
"else",
":",
"version",
"=",
"'2.0'",
"if",
"(",
"error_handler",
"is",
"None",
")",
":",
"def",
"error_handler",
"(",
"exc",
")",
":",
"raise",
"exc",
"if",
"(",
"version",
"==",
"'1.0'",
")",
":",
"parse_scheme_v_1_0",
"(",
"doc",
",",
"scheme",
",",
"error_handler",
"=",
"error_handler",
",",
"allow_pickle_data",
"=",
"allow_pickle_data",
")",
"return",
"scheme",
"else",
":",
"parse_scheme_v_2_0",
"(",
"doc",
",",
"scheme",
",",
"error_handler",
"=",
"error_handler",
",",
"allow_pickle_data",
"=",
"allow_pickle_data",
")",
"return",
"scheme"
] | parse a saved scheme from stream and populate a scheme instance . | train | false |
38,698 | def _lowess_mycube(t):
t2 = (t * t)
t *= t2
| [
"def",
"_lowess_mycube",
"(",
"t",
")",
":",
"t2",
"=",
"(",
"t",
"*",
"t",
")",
"t",
"*=",
"t2"
] | fast matrix cube parameters t : ndarray array that is cubed . | train | false |
38,699 | def _sparse_argmax_nnz_row(csr_mat):
n_rows = csr_mat.shape[0]
idx = np.empty(n_rows, dtype=np.int)
for k in range(n_rows):
row = csr_mat[k].tocoo()
idx[k] = row.col[np.argmax(row.data)]
return idx
| [
"def",
"_sparse_argmax_nnz_row",
"(",
"csr_mat",
")",
":",
"n_rows",
"=",
"csr_mat",
".",
"shape",
"[",
"0",
"]",
"idx",
"=",
"np",
".",
"empty",
"(",
"n_rows",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"for",
"k",
"in",
"range",
"(",
"n_rows",
")",
":",
"row",
"=",
"csr_mat",
"[",
"k",
"]",
".",
"tocoo",
"(",
")",
"idx",
"[",
"k",
"]",
"=",
"row",
".",
"col",
"[",
"np",
".",
"argmax",
"(",
"row",
".",
"data",
")",
"]",
"return",
"idx"
] | return index of the maximum non-zero index in each row . | train | false |
38,700 | def algorithm_to_text(value):
text = _algorithm_by_value.get(value)
if (text is None):
text = str(value)
return text
| [
"def",
"algorithm_to_text",
"(",
"value",
")",
":",
"text",
"=",
"_algorithm_by_value",
".",
"get",
"(",
"value",
")",
"if",
"(",
"text",
"is",
"None",
")",
":",
"text",
"=",
"str",
"(",
"value",
")",
"return",
"text"
] | convert a dnssec algorithm value to text @rtype: string . | train | true |
38,701 | def fresnel_zeros(nt):
if ((floor(nt) != nt) or (nt <= 0) or (not isscalar(nt))):
raise ValueError('Argument must be positive scalar integer.')
return (specfun.fcszo(2, nt), specfun.fcszo(1, nt))
| [
"def",
"fresnel_zeros",
"(",
"nt",
")",
":",
"if",
"(",
"(",
"floor",
"(",
"nt",
")",
"!=",
"nt",
")",
"or",
"(",
"nt",
"<=",
"0",
")",
"or",
"(",
"not",
"isscalar",
"(",
"nt",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Argument must be positive scalar integer.'",
")",
"return",
"(",
"specfun",
".",
"fcszo",
"(",
"2",
",",
"nt",
")",
",",
"specfun",
".",
"fcszo",
"(",
"1",
",",
"nt",
")",
")"
] | compute nt complex zeros of sine and cosine fresnel integrals s(z) and c(z) . | train | false |
38,702 | def guess_net_inet_tcp_recvbuf_max():
return (16 * MB)
| [
"def",
"guess_net_inet_tcp_recvbuf_max",
"(",
")",
":",
"return",
"(",
"16",
"*",
"MB",
")"
] | maximum size for tcp receive buffers see guess_kern_ipc_maxsockbuf() . | train | false |
38,704 | def _make_typed_value(value):
typed_value_map = {bool: 'boolValue', int: 'int64Value', float: 'doubleValue', str: 'stringValue', dict: 'distributionValue'}
type_ = typed_value_map[type(value)]
if (type_ == 'int64Value'):
value = str(value)
return {type_: value}
| [
"def",
"_make_typed_value",
"(",
"value",
")",
":",
"typed_value_map",
"=",
"{",
"bool",
":",
"'boolValue'",
",",
"int",
":",
"'int64Value'",
",",
"float",
":",
"'doubleValue'",
",",
"str",
":",
"'stringValue'",
",",
"dict",
":",
"'distributionValue'",
"}",
"type_",
"=",
"typed_value_map",
"[",
"type",
"(",
"value",
")",
"]",
"if",
"(",
"type_",
"==",
"'int64Value'",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"return",
"{",
"type_",
":",
"value",
"}"
] | create a dict representing a typedvalue api object . | train | false |
38,706 | def ipv6_address(addr):
if (not isinstance(addr, basestring)):
raise CX('Invalid input, addr must be a string')
else:
addr = addr.strip()
if (addr == ''):
return addr
if (not netaddr.valid_ipv6(addr)):
raise CX(('Invalid IPv6 address format (%s)' % addr))
return addr
| [
"def",
"ipv6_address",
"(",
"addr",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"addr",
",",
"basestring",
")",
")",
":",
"raise",
"CX",
"(",
"'Invalid input, addr must be a string'",
")",
"else",
":",
"addr",
"=",
"addr",
".",
"strip",
"(",
")",
"if",
"(",
"addr",
"==",
"''",
")",
":",
"return",
"addr",
"if",
"(",
"not",
"netaddr",
".",
"valid_ipv6",
"(",
"addr",
")",
")",
":",
"raise",
"CX",
"(",
"(",
"'Invalid IPv6 address format (%s)'",
"%",
"addr",
")",
")",
"return",
"addr"
] | validate an ipv6 address . | train | false |
38,708 | def make_user_copy(module_name, user):
standard_name = frappe.db.get_value(u'Desktop Icon', {u'module_name': module_name, u'standard': 1})
if (not standard_name):
frappe.throw(u'{0} not found'.format(module_name), frappe.DoesNotExistError)
original = frappe.get_doc(u'Desktop Icon', standard_name)
desktop_icon = frappe.get_doc({u'doctype': u'Desktop Icon', u'standard': 0, u'owner': user, u'module_name': module_name})
for key in (u'app', u'label', u'route', u'type', u'_doctype', u'idx', u'reverse', u'force_show'):
if original.get(key):
desktop_icon.set(key, original.get(key))
desktop_icon.insert(ignore_permissions=True)
return desktop_icon
| [
"def",
"make_user_copy",
"(",
"module_name",
",",
"user",
")",
":",
"standard_name",
"=",
"frappe",
".",
"db",
".",
"get_value",
"(",
"u'Desktop Icon'",
",",
"{",
"u'module_name'",
":",
"module_name",
",",
"u'standard'",
":",
"1",
"}",
")",
"if",
"(",
"not",
"standard_name",
")",
":",
"frappe",
".",
"throw",
"(",
"u'{0} not found'",
".",
"format",
"(",
"module_name",
")",
",",
"frappe",
".",
"DoesNotExistError",
")",
"original",
"=",
"frappe",
".",
"get_doc",
"(",
"u'Desktop Icon'",
",",
"standard_name",
")",
"desktop_icon",
"=",
"frappe",
".",
"get_doc",
"(",
"{",
"u'doctype'",
":",
"u'Desktop Icon'",
",",
"u'standard'",
":",
"0",
",",
"u'owner'",
":",
"user",
",",
"u'module_name'",
":",
"module_name",
"}",
")",
"for",
"key",
"in",
"(",
"u'app'",
",",
"u'label'",
",",
"u'route'",
",",
"u'type'",
",",
"u'_doctype'",
",",
"u'idx'",
",",
"u'reverse'",
",",
"u'force_show'",
")",
":",
"if",
"original",
".",
"get",
"(",
"key",
")",
":",
"desktop_icon",
".",
"set",
"(",
"key",
",",
"original",
".",
"get",
"(",
"key",
")",
")",
"desktop_icon",
".",
"insert",
"(",
"ignore_permissions",
"=",
"True",
")",
"return",
"desktop_icon"
] | insert and return the user copy of a standard desktop icon . | train | false |
38,709 | def datetime_to_time(x):
if isinstance(x, datetime):
return x.time()
return x
| [
"def",
"datetime_to_time",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"datetime",
")",
":",
"return",
"x",
".",
"time",
"(",
")",
"return",
"x"
] | convert a datetime into a time . | train | false |
38,711 | @pytest.yield_fixture
def storage():
root = join(dirname(__file__), u'..', u'app', u'templates')
(yield FileSystemStorage(location=root, base_url=u'/baseurl/'))
| [
"@",
"pytest",
".",
"yield_fixture",
"def",
"storage",
"(",
")",
":",
"root",
"=",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"u'..'",
",",
"u'app'",
",",
"u'templates'",
")",
"(",
"yield",
"FileSystemStorage",
"(",
"location",
"=",
"root",
",",
"base_url",
"=",
"u'/baseurl/'",
")",
")"
] | provide a storage that exposes the test templates . | train | false |
38,712 | def disable_ssh():
_current = global_settings()
if (_current['Global Settings']['SSH_STATUS']['VALUE'] == 'N'):
return True
_xml = '<RIBCL VERSION="2.0">\n <LOGIN USER_LOGIN="adminname" PASSWORD="password">\n <RIB_INFO MODE="write">\n <MOD_GLOBAL_SETTINGS>\n <SSH_STATUS value="No"/>\n </MOD_GLOBAL_SETTINGS>\n </RIB_INFO>\n </LOGIN>\n </RIBCL>'
return __execute_cmd('Disable_SSH', _xml)
| [
"def",
"disable_ssh",
"(",
")",
":",
"_current",
"=",
"global_settings",
"(",
")",
"if",
"(",
"_current",
"[",
"'Global Settings'",
"]",
"[",
"'SSH_STATUS'",
"]",
"[",
"'VALUE'",
"]",
"==",
"'N'",
")",
":",
"return",
"True",
"_xml",
"=",
"'<RIBCL VERSION=\"2.0\">\\n <LOGIN USER_LOGIN=\"adminname\" PASSWORD=\"password\">\\n <RIB_INFO MODE=\"write\">\\n <MOD_GLOBAL_SETTINGS>\\n <SSH_STATUS value=\"No\"/>\\n </MOD_GLOBAL_SETTINGS>\\n </RIB_INFO>\\n </LOGIN>\\n </RIBCL>'",
"return",
"__execute_cmd",
"(",
"'Disable_SSH'",
",",
"_xml",
")"
] | disable the ssh daemon cli example: . | train | false |
38,714 | def module_required(fn):
@wraps(fn)
def wrapper(self, *args, **kwargs):
if (not self.current_module):
print_error("You have to activate any module with 'use' command.")
return
return fn(self, *args, **kwargs)
try:
name = 'module_required'
wrapper.__decorators__.append(name)
except AttributeError:
wrapper.__decorators__ = [name]
return wrapper
| [
"def",
"module_required",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"not",
"self",
".",
"current_module",
")",
":",
"print_error",
"(",
"\"You have to activate any module with 'use' command.\"",
")",
"return",
"return",
"fn",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"try",
":",
"name",
"=",
"'module_required'",
"wrapper",
".",
"__decorators__",
".",
"append",
"(",
"name",
")",
"except",
"AttributeError",
":",
"wrapper",
".",
"__decorators__",
"=",
"[",
"name",
"]",
"return",
"wrapper"
] | checks if module is loaded . | train | false |
38,716 | def tools_binskim():
binskim_nuget = CONFIG['binskim']['nuget']
mobsf_subdir_tools = CONFIG['MobSF']['tools']
nuget = (mobsf_subdir_tools + CONFIG['nuget']['file'])
print '[*] Downloading and installing Binskim...'
output = subprocess.check_output([nuget, 'install', binskim_nuget, '-Pre', '-o', mobsf_subdir_tools])
folder = re.search('Microsoft\\.CodeAnalysis\\.BinSkim\\..*(\'|") ', output)
try:
if (sys.version_info.major == 3):
folder = str(folder.group(0)[:(-2)])[2:(-1)]
else:
folder = folder.group(0)[:(-2)]
except AttributeError:
print '[!] Unable to parse folder from binskim nuget installation.'
sys.exit()
binaries = _find_exe((mobsf_subdir_tools + folder), [])
if (len(binaries) != 2):
print '[!] Found more than 2 exes for binskim, panic!'
sys.exit()
if ('x86' in binaries[0]):
CONFIG['binskim']['file_x86'] = binaries[0]
CONFIG['binskim']['file_x64'] = binaries[1]
else:
CONFIG['binskim']['file_x86'] = binaries[1]
CONFIG['binskim']['file_x64'] = binaries[0]
with open(os.path.join(CONFIG_PATH, CONFIG_FILE), 'w') as configfile:
CONFIG.write(configfile)
| [
"def",
"tools_binskim",
"(",
")",
":",
"binskim_nuget",
"=",
"CONFIG",
"[",
"'binskim'",
"]",
"[",
"'nuget'",
"]",
"mobsf_subdir_tools",
"=",
"CONFIG",
"[",
"'MobSF'",
"]",
"[",
"'tools'",
"]",
"nuget",
"=",
"(",
"mobsf_subdir_tools",
"+",
"CONFIG",
"[",
"'nuget'",
"]",
"[",
"'file'",
"]",
")",
"print",
"'[*] Downloading and installing Binskim...'",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"nuget",
",",
"'install'",
",",
"binskim_nuget",
",",
"'-Pre'",
",",
"'-o'",
",",
"mobsf_subdir_tools",
"]",
")",
"folder",
"=",
"re",
".",
"search",
"(",
"'Microsoft\\\\.CodeAnalysis\\\\.BinSkim\\\\..*(\\'|\") '",
",",
"output",
")",
"try",
":",
"if",
"(",
"sys",
".",
"version_info",
".",
"major",
"==",
"3",
")",
":",
"folder",
"=",
"str",
"(",
"folder",
".",
"group",
"(",
"0",
")",
"[",
":",
"(",
"-",
"2",
")",
"]",
")",
"[",
"2",
":",
"(",
"-",
"1",
")",
"]",
"else",
":",
"folder",
"=",
"folder",
".",
"group",
"(",
"0",
")",
"[",
":",
"(",
"-",
"2",
")",
"]",
"except",
"AttributeError",
":",
"print",
"'[!] Unable to parse folder from binskim nuget installation.'",
"sys",
".",
"exit",
"(",
")",
"binaries",
"=",
"_find_exe",
"(",
"(",
"mobsf_subdir_tools",
"+",
"folder",
")",
",",
"[",
"]",
")",
"if",
"(",
"len",
"(",
"binaries",
")",
"!=",
"2",
")",
":",
"print",
"'[!] Found more than 2 exes for binskim, panic!'",
"sys",
".",
"exit",
"(",
")",
"if",
"(",
"'x86'",
"in",
"binaries",
"[",
"0",
"]",
")",
":",
"CONFIG",
"[",
"'binskim'",
"]",
"[",
"'file_x86'",
"]",
"=",
"binaries",
"[",
"0",
"]",
"CONFIG",
"[",
"'binskim'",
"]",
"[",
"'file_x64'",
"]",
"=",
"binaries",
"[",
"1",
"]",
"else",
":",
"CONFIG",
"[",
"'binskim'",
"]",
"[",
"'file_x86'",
"]",
"=",
"binaries",
"[",
"1",
"]",
"CONFIG",
"[",
"'binskim'",
"]",
"[",
"'file_x64'",
"]",
"=",
"binaries",
"[",
"0",
"]",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CONFIG_PATH",
",",
"CONFIG_FILE",
")",
",",
"'w'",
")",
"as",
"configfile",
":",
"CONFIG",
".",
"write",
"(",
"configfile",
")"
] | download and extract binskim . | train | false |
38,717 | def default_extension(environ=None):
return zipline_path(['extension.py'], environ=environ)
| [
"def",
"default_extension",
"(",
"environ",
"=",
"None",
")",
":",
"return",
"zipline_path",
"(",
"[",
"'extension.py'",
"]",
",",
"environ",
"=",
"environ",
")"
] | get the path to the default zipline extension file . | train | false |
38,718 | def sort_nested_dict(value):
result = OrderedDict()
for (key, value) in sorted(value.items(), key=sort_key_by_numeric_other):
if isinstance(value, (dict, OrderedDict)):
result[key] = sort_nested_dict(value)
else:
result[key] = value
return result
| [
"def",
"sort_nested_dict",
"(",
"value",
")",
":",
"result",
"=",
"OrderedDict",
"(",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"sorted",
"(",
"value",
".",
"items",
"(",
")",
",",
"key",
"=",
"sort_key_by_numeric_other",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"dict",
",",
"OrderedDict",
")",
")",
":",
"result",
"[",
"key",
"]",
"=",
"sort_nested_dict",
"(",
"value",
")",
"else",
":",
"result",
"[",
"key",
"]",
"=",
"value",
"return",
"result"
] | recursively sort a nested dict . | train | false |
38,719 | def notify_owner(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
'\n if request.args.get(\'confirmed\') == "true":\n dag_id = request.args.get(\'dag_id\')\n task_id = request.args.get(\'task_id\')\n dagbag = models.DagBag(\n os.path.expanduser(configuration.get(\'core\', \'DAGS_FOLDER\')))\n\n dag = dagbag.get_dag(dag_id)\n task = dag.get_task(task_id)\n\n if current_user and hasattr(current_user, \'username\'):\n user = current_user.username\n else:\n user = \'anonymous\'\n\n if task.owner != user:\n subject = (\n \'Actions taken on DAG {0} by {1}\'.format(\n dag_id, user))\n items = request.args.items()\n content = Template(\'\'\'\n action: <i>{{ f.__name__ }}</i><br>\n <br>\n <b>Parameters</b>:<br>\n <table>\n {% for k, v in items %}\n {% if k != \'origin\' %}\n <tr>\n <td>{{ k }}</td>\n <td>{{ v }}</td>\n </tr>\n {% endif %}\n {% endfor %}\n </table>\n \'\'\').render(**locals())\n if task.email:\n send_email(task.email, subject, content)\n '
return f(*args, **kwargs)
return wrapper
| [
"def",
"notify_owner",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"f",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"wrapper"
] | a decorator for mutating methods of property container classes that notifies owners of the property container about mutating changes . | train | false |
38,720 | def get_package_version(pypiConn, pkg_name):
pkg_result = [v for v in pypiConn.package_releases(pkg_name, True) if (not PRE_RELEASE_RE.search(v))]
if pkg_result:
pkg_version = pkg_result[0]
else:
pkg_version = 'Not available.'
return pkg_version
| [
"def",
"get_package_version",
"(",
"pypiConn",
",",
"pkg_name",
")",
":",
"pkg_result",
"=",
"[",
"v",
"for",
"v",
"in",
"pypiConn",
".",
"package_releases",
"(",
"pkg_name",
",",
"True",
")",
"if",
"(",
"not",
"PRE_RELEASE_RE",
".",
"search",
"(",
"v",
")",
")",
"]",
"if",
"pkg_result",
":",
"pkg_version",
"=",
"pkg_result",
"[",
"0",
"]",
"else",
":",
"pkg_version",
"=",
"'Not available.'",
"return",
"pkg_version"
] | return the review board version as a python package version string . | train | false |
38,721 | def test_merge_id_schema(hass):
types = {'panel_custom': 'list', 'group': 'dict', 'script': 'dict', 'input_boolean': 'dict', 'shell_command': 'dict', 'qwikswitch': ''}
for (name, expected_type) in types.items():
module = config_util.get_component(name)
(typ, _) = config_util._identify_config_schema(module)
assert (typ == expected_type), '{} expected {}, got {}'.format(name, expected_type, typ)
| [
"def",
"test_merge_id_schema",
"(",
"hass",
")",
":",
"types",
"=",
"{",
"'panel_custom'",
":",
"'list'",
",",
"'group'",
":",
"'dict'",
",",
"'script'",
":",
"'dict'",
",",
"'input_boolean'",
":",
"'dict'",
",",
"'shell_command'",
":",
"'dict'",
",",
"'qwikswitch'",
":",
"''",
"}",
"for",
"(",
"name",
",",
"expected_type",
")",
"in",
"types",
".",
"items",
"(",
")",
":",
"module",
"=",
"config_util",
".",
"get_component",
"(",
"name",
")",
"(",
"typ",
",",
"_",
")",
"=",
"config_util",
".",
"_identify_config_schema",
"(",
"module",
")",
"assert",
"(",
"typ",
"==",
"expected_type",
")",
",",
"'{} expected {}, got {}'",
".",
"format",
"(",
"name",
",",
"expected_type",
",",
"typ",
")"
] | test if we identify the config schemas correctly . | train | false |
38,722 | def libvlc_media_release(p_md):
f = (_Cfunctions.get('libvlc_media_release', None) or _Cfunction('libvlc_media_release', ((1,),), None, None, Media))
return f(p_md)
| [
"def",
"libvlc_media_release",
"(",
"p_md",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_release'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_release'",
",",
"(",
"(",
"1",
",",
")",
",",
")",
",",
"None",
",",
"None",
",",
"Media",
")",
")",
"return",
"f",
"(",
"p_md",
")"
] | decrement the reference count of a media descriptor object . | train | false |
38,724 | def ishex(c):
return (('0' <= c <= '9') or ('a' <= c <= 'f') or ('A' <= c <= 'F'))
| [
"def",
"ishex",
"(",
"c",
")",
":",
"return",
"(",
"(",
"'0'",
"<=",
"c",
"<=",
"'9'",
")",
"or",
"(",
"'a'",
"<=",
"c",
"<=",
"'f'",
")",
"or",
"(",
"'A'",
"<=",
"c",
"<=",
"'F'",
")",
")"
] | return true if the byte ordinal c is a hexadecimal digit in ascii . | train | false |
38,725 | def test_scharr_v_mask():
np.random.seed(0)
result = filters.scharr_v(np.random.uniform(size=(10, 10)), np.zeros((10, 10), bool))
assert_allclose(result, 0)
| [
"def",
"test_scharr_v_mask",
"(",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"0",
")",
"result",
"=",
"filters",
".",
"scharr_v",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"(",
"10",
",",
"10",
")",
")",
",",
"np",
".",
"zeros",
"(",
"(",
"10",
",",
"10",
")",
",",
"bool",
")",
")",
"assert_allclose",
"(",
"result",
",",
"0",
")"
] | vertical scharr on a masked array should be zero . | train | false |
38,726 | def add_permalink_option_defaults(pelicon_inst):
pelicon_inst.settings.setdefault('PERMALINK_PATH', 'permalinks')
pelicon_inst.settings.setdefault('PERMALINK_ID_METADATA_KEY', 'permalink_id')
| [
"def",
"add_permalink_option_defaults",
"(",
"pelicon_inst",
")",
":",
"pelicon_inst",
".",
"settings",
".",
"setdefault",
"(",
"'PERMALINK_PATH'",
",",
"'permalinks'",
")",
"pelicon_inst",
".",
"settings",
".",
"setdefault",
"(",
"'PERMALINK_ID_METADATA_KEY'",
",",
"'permalink_id'",
")"
] | add perlican defaults . | train | false |
38,727 | @celery_app.task(base=ArchiverTask, ignore_result=False)
@logged('archive_node')
def archive_node(stat_results, job_pk):
create_app_context()
job = ArchiveJob.load(job_pk)
(src, dst, user) = job.info()
logger.info('Archiving node: {0}'.format(src._id))
if (not isinstance(stat_results, list)):
stat_results = [stat_results]
stat_result = AggregateStatResult(dst._id, dst.title, targets=stat_results)
if ((NO_ARCHIVE_LIMIT not in job.initiator.system_tags) and (stat_result.disk_usage > settings.MAX_ARCHIVE_SIZE)):
raise ArchiverSizeExceeded(result=stat_result)
else:
if (not stat_result.targets):
job.status = ARCHIVER_SUCCESS
job.save()
for result in stat_result.targets:
if (not result.num_files):
job.update_target(result.target_name, ARCHIVER_SUCCESS)
else:
archive_addon.delay(addon_short_name=result.target_name, job_pk=job_pk, stat_result=result)
project_signals.archive_callback.send(dst)
| [
"@",
"celery_app",
".",
"task",
"(",
"base",
"=",
"ArchiverTask",
",",
"ignore_result",
"=",
"False",
")",
"@",
"logged",
"(",
"'archive_node'",
")",
"def",
"archive_node",
"(",
"stat_results",
",",
"job_pk",
")",
":",
"create_app_context",
"(",
")",
"job",
"=",
"ArchiveJob",
".",
"load",
"(",
"job_pk",
")",
"(",
"src",
",",
"dst",
",",
"user",
")",
"=",
"job",
".",
"info",
"(",
")",
"logger",
".",
"info",
"(",
"'Archiving node: {0}'",
".",
"format",
"(",
"src",
".",
"_id",
")",
")",
"if",
"(",
"not",
"isinstance",
"(",
"stat_results",
",",
"list",
")",
")",
":",
"stat_results",
"=",
"[",
"stat_results",
"]",
"stat_result",
"=",
"AggregateStatResult",
"(",
"dst",
".",
"_id",
",",
"dst",
".",
"title",
",",
"targets",
"=",
"stat_results",
")",
"if",
"(",
"(",
"NO_ARCHIVE_LIMIT",
"not",
"in",
"job",
".",
"initiator",
".",
"system_tags",
")",
"and",
"(",
"stat_result",
".",
"disk_usage",
">",
"settings",
".",
"MAX_ARCHIVE_SIZE",
")",
")",
":",
"raise",
"ArchiverSizeExceeded",
"(",
"result",
"=",
"stat_result",
")",
"else",
":",
"if",
"(",
"not",
"stat_result",
".",
"targets",
")",
":",
"job",
".",
"status",
"=",
"ARCHIVER_SUCCESS",
"job",
".",
"save",
"(",
")",
"for",
"result",
"in",
"stat_result",
".",
"targets",
":",
"if",
"(",
"not",
"result",
".",
"num_files",
")",
":",
"job",
".",
"update_target",
"(",
"result",
".",
"target_name",
",",
"ARCHIVER_SUCCESS",
")",
"else",
":",
"archive_addon",
".",
"delay",
"(",
"addon_short_name",
"=",
"result",
".",
"target_name",
",",
"job_pk",
"=",
"job_pk",
",",
"stat_result",
"=",
"result",
")",
"project_signals",
".",
"archive_callback",
".",
"send",
"(",
"dst",
")"
] | first use the results of #stat_node to check disk usage of the initiated registration . | train | false |
38,728 | @pytest.mark.parametrize('text, expected', [('f<oo>bar', 'fo|obar'), ('|foobar', '|foobar')])
def test_rl_backward_char(text, expected, lineedit, bridge):
lineedit.set_aug_text(text)
bridge.rl_backward_char()
assert (lineedit.aug_text() == expected)
| [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'text, expected'",
",",
"[",
"(",
"'f<oo>bar'",
",",
"'fo|obar'",
")",
",",
"(",
"'|foobar'",
",",
"'|foobar'",
")",
"]",
")",
"def",
"test_rl_backward_char",
"(",
"text",
",",
"expected",
",",
"lineedit",
",",
"bridge",
")",
":",
"lineedit",
".",
"set_aug_text",
"(",
"text",
")",
"bridge",
".",
"rl_backward_char",
"(",
")",
"assert",
"(",
"lineedit",
".",
"aug_text",
"(",
")",
"==",
"expected",
")"
] | test rl_backward_char . | train | false |
38,731 | def child_fd_list_remove(fd):
global child_fd_list
try:
child_fd_list.remove(fd)
except Exception:
pass
| [
"def",
"child_fd_list_remove",
"(",
"fd",
")",
":",
"global",
"child_fd_list",
"try",
":",
"child_fd_list",
".",
"remove",
"(",
"fd",
")",
"except",
"Exception",
":",
"pass"
] | remove a file descriptor to list to be closed in child processes . | train | false |
38,732 | def filter_thing(x):
return x.thing
| [
"def",
"filter_thing",
"(",
"x",
")",
":",
"return",
"x",
".",
"thing"
] | return "thing" from a proxy object . | train | false |
38,733 | def iterpairs(seq):
seq_it = iter(seq)
seq_it_next = iter(seq)
next(seq_it_next)
return zip(seq_it, seq_it_next)
| [
"def",
"iterpairs",
"(",
"seq",
")",
":",
"seq_it",
"=",
"iter",
"(",
"seq",
")",
"seq_it_next",
"=",
"iter",
"(",
"seq",
")",
"next",
"(",
"seq_it_next",
")",
"return",
"zip",
"(",
"seq_it",
",",
"seq_it_next",
")"
] | parameters seq : sequence returns iterator returning overlapping pairs of elements examples . | train | false |
38,734 | def addXIntersectionIndexesFromLoopsY(loops, solidIndex, xIntersectionIndexList, y):
for loop in loops:
addXIntersectionIndexesFromLoopY(loop, solidIndex, xIntersectionIndexList, y)
| [
"def",
"addXIntersectionIndexesFromLoopsY",
"(",
"loops",
",",
"solidIndex",
",",
"xIntersectionIndexList",
",",
"y",
")",
":",
"for",
"loop",
"in",
"loops",
":",
"addXIntersectionIndexesFromLoopY",
"(",
"loop",
",",
"solidIndex",
",",
"xIntersectionIndexList",
",",
"y",
")"
] | add the x intersection indexes for the loops . | train | false |
38,735 | def get_random_choice(alist):
assert (isinstance(alist, list) and (len(alist) > 0))
index = get_random_int(len(alist))
return alist[index]
| [
"def",
"get_random_choice",
"(",
"alist",
")",
":",
"assert",
"(",
"isinstance",
"(",
"alist",
",",
"list",
")",
"and",
"(",
"len",
"(",
"alist",
")",
">",
"0",
")",
")",
"index",
"=",
"get_random_int",
"(",
"len",
"(",
"alist",
")",
")",
"return",
"alist",
"[",
"index",
"]"
] | gets a random element from a list . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.