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 |
|---|---|---|---|---|---|
14,339 | def generate_album_info(album_id, track_ids):
tracks = [generate_track_info(id) for id in track_ids]
album = AlbumInfo(album_id=u'album info', album=u'album info', artist=u'album info', artist_id=u'album info', tracks=tracks)
for field in ALBUM_INFO_FIELDS:
setattr(album, field, u'album info')
return album
| [
"def",
"generate_album_info",
"(",
"album_id",
",",
"track_ids",
")",
":",
"tracks",
"=",
"[",
"generate_track_info",
"(",
"id",
")",
"for",
"id",
"in",
"track_ids",
"]",
"album",
"=",
"AlbumInfo",
"(",
"album_id",
"=",
"u'album info'",
",",
"album",
"=",
"u'album info'",
",",
"artist",
"=",
"u'album info'",
",",
"artist_id",
"=",
"u'album info'",
",",
"tracks",
"=",
"tracks",
")",
"for",
"field",
"in",
"ALBUM_INFO_FIELDS",
":",
"setattr",
"(",
"album",
",",
"field",
",",
"u'album info'",
")",
"return",
"album"
] | return albuminfo populated with mock data . | train | false |
14,340 | def project_jnap_opts():
T = current.T
return {1: T('JNAP-1: Strategic Area 1: Governance'), 2: T('JNAP-2: Strategic Area 2: Monitoring'), 3: T('JNAP-3: Strategic Area 3: Disaster Management'), 4: T('JNAP-4: Strategic Area 4: Risk Reduction and Climate Change Adaptation')}
| [
"def",
"project_jnap_opts",
"(",
")",
":",
"T",
"=",
"current",
".",
"T",
"return",
"{",
"1",
":",
"T",
"(",
"'JNAP-1: Strategic Area 1: Governance'",
")",
",",
"2",
":",
"T",
"(",
"'JNAP-2: Strategic Area 2: Monitoring'",
")",
",",
"3",
":",
"T",
"(",
"'JNAP-3: Strategic Area 3: Disaster Management'",
")",
",",
"4",
":",
"T",
"(",
"'JNAP-4: Strategic Area 4: Risk Reduction and Climate Change Adaptation'",
")",
"}"
] | provide the options for the jnap filter jnap : applies to cook islands only . | train | false |
14,343 | def read_int(s, start_position):
m = _READ_INT_RE.match(s, start_position)
if (not m):
raise ReadError('integer', start_position)
return (int(m.group()), m.end())
| [
"def",
"read_int",
"(",
"s",
",",
"start_position",
")",
":",
"m",
"=",
"_READ_INT_RE",
".",
"match",
"(",
"s",
",",
"start_position",
")",
"if",
"(",
"not",
"m",
")",
":",
"raise",
"ReadError",
"(",
"'integer'",
",",
"start_position",
")",
"return",
"(",
"int",
"(",
"m",
".",
"group",
"(",
")",
")",
",",
"m",
".",
"end",
"(",
")",
")"
] | reads n ints from a file . | train | false |
14,344 | @api_wrapper
def create_filesystem(module, system):
if (not module.check_mode):
filesystem = system.filesystems.create(name=module.params['name'], pool=get_pool(module, system))
if module.params['size']:
size = Capacity(module.params['size']).roundup((64 * KiB))
filesystem.update_size(size)
module.exit_json(changed=True)
| [
"@",
"api_wrapper",
"def",
"create_filesystem",
"(",
"module",
",",
"system",
")",
":",
"if",
"(",
"not",
"module",
".",
"check_mode",
")",
":",
"filesystem",
"=",
"system",
".",
"filesystems",
".",
"create",
"(",
"name",
"=",
"module",
".",
"params",
"[",
"'name'",
"]",
",",
"pool",
"=",
"get_pool",
"(",
"module",
",",
"system",
")",
")",
"if",
"module",
".",
"params",
"[",
"'size'",
"]",
":",
"size",
"=",
"Capacity",
"(",
"module",
".",
"params",
"[",
"'size'",
"]",
")",
".",
"roundup",
"(",
"(",
"64",
"*",
"KiB",
")",
")",
"filesystem",
".",
"update_size",
"(",
"size",
")",
"module",
".",
"exit_json",
"(",
"changed",
"=",
"True",
")"
] | create filesystem . | train | false |
14,348 | def unchanged_required(argument):
if (argument is None):
raise ValueError('argument required but none supplied')
else:
return argument
| [
"def",
"unchanged_required",
"(",
"argument",
")",
":",
"if",
"(",
"argument",
"is",
"None",
")",
":",
"raise",
"ValueError",
"(",
"'argument required but none supplied'",
")",
"else",
":",
"return",
"argument"
] | return the argument text . | train | false |
14,349 | @pytest.mark.parametrize('sep', [None, ' sep '])
def test_str_cat(sep):
if (sep is None):
expr = t_str_cat.name.str_cat(t_str_cat.comment)
expected = '\n SELECT accounts2.name || accounts2.comment\n AS anon_1 FROM accounts2\n '
else:
expr = t_str_cat.name.str_cat(t_str_cat.comment, sep=sep)
expected = '\n SELECT accounts2.name || :name_1 || accounts2.comment\n AS anon_1 FROM accounts2\n '
result = str(compute(expr, s_str_cat, return_type='native'))
assert (normalize(result) == normalize(expected))
| [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'sep'",
",",
"[",
"None",
",",
"' sep '",
"]",
")",
"def",
"test_str_cat",
"(",
"sep",
")",
":",
"if",
"(",
"sep",
"is",
"None",
")",
":",
"expr",
"=",
"t_str_cat",
".",
"name",
".",
"str_cat",
"(",
"t_str_cat",
".",
"comment",
")",
"expected",
"=",
"'\\n SELECT accounts2.name || accounts2.comment\\n AS anon_1 FROM accounts2\\n '",
"else",
":",
"expr",
"=",
"t_str_cat",
".",
"name",
".",
"str_cat",
"(",
"t_str_cat",
".",
"comment",
",",
"sep",
"=",
"sep",
")",
"expected",
"=",
"'\\n SELECT accounts2.name || :name_1 || accounts2.comment\\n AS anon_1 FROM accounts2\\n '",
"result",
"=",
"str",
"(",
"compute",
"(",
"expr",
",",
"s_str_cat",
",",
"return_type",
"=",
"'native'",
")",
")",
"assert",
"(",
"normalize",
"(",
"result",
")",
"==",
"normalize",
"(",
"expected",
")",
")"
] | need at least two string columns to test str_cat . | train | false |
14,350 | def test_classification_report_imbalanced_multiclass_with_long_string_label():
(y_true, y_pred, _) = make_prediction(binary=False)
labels = np.array(['blue', ('green' * 5), 'red'])
y_true = labels[y_true]
y_pred = labels[y_pred]
expected_report = 'pre rec spe f1 geo iba sup blue 0.83 0.79 0.92 0.81 0.86 0.74 24 greengreengreengreengreen 0.33 0.10 0.86 0.15 0.44 0.19 31 red 0.42 0.90 0.55 0.57 0.63 0.37 20 avg / total 0.51 0.53 0.80 0.47 0.62 0.41 75'
report = classification_report_imbalanced(y_true, y_pred)
assert_equal(_format_report(report), expected_report)
| [
"def",
"test_classification_report_imbalanced_multiclass_with_long_string_label",
"(",
")",
":",
"(",
"y_true",
",",
"y_pred",
",",
"_",
")",
"=",
"make_prediction",
"(",
"binary",
"=",
"False",
")",
"labels",
"=",
"np",
".",
"array",
"(",
"[",
"'blue'",
",",
"(",
"'green'",
"*",
"5",
")",
",",
"'red'",
"]",
")",
"y_true",
"=",
"labels",
"[",
"y_true",
"]",
"y_pred",
"=",
"labels",
"[",
"y_pred",
"]",
"expected_report",
"=",
"'pre rec spe f1 geo iba sup blue 0.83 0.79 0.92 0.81 0.86 0.74 24 greengreengreengreengreen 0.33 0.10 0.86 0.15 0.44 0.19 31 red 0.42 0.90 0.55 0.57 0.63 0.37 20 avg / total 0.51 0.53 0.80 0.47 0.62 0.41 75'",
"report",
"=",
"classification_report_imbalanced",
"(",
"y_true",
",",
"y_pred",
")",
"assert_equal",
"(",
"_format_report",
"(",
"report",
")",
",",
"expected_report",
")"
] | test classification report with long string label . | train | false |
14,351 | @with_session
def config_changed(task=None, session=None):
log.debug((u'Marking config for %s as changed.' % (task or u'all tasks')))
task_hash = session.query(TaskConfigHash)
if task:
task_hash = task_hash.filter((TaskConfigHash.task == task))
task_hash.delete()
| [
"@",
"with_session",
"def",
"config_changed",
"(",
"task",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"(",
"u'Marking config for %s as changed.'",
"%",
"(",
"task",
"or",
"u'all tasks'",
")",
")",
")",
"task_hash",
"=",
"session",
".",
"query",
"(",
"TaskConfigHash",
")",
"if",
"task",
":",
"task_hash",
"=",
"task_hash",
".",
"filter",
"(",
"(",
"TaskConfigHash",
".",
"task",
"==",
"task",
")",
")",
"task_hash",
".",
"delete",
"(",
")"
] | returns true if config has changed . | train | false |
14,353 | def _get_decimal128(data, position, dummy0, dummy1, dummy2):
end = (position + 16)
return (Decimal128.from_bid(data[position:end]), end)
| [
"def",
"_get_decimal128",
"(",
"data",
",",
"position",
",",
"dummy0",
",",
"dummy1",
",",
"dummy2",
")",
":",
"end",
"=",
"(",
"position",
"+",
"16",
")",
"return",
"(",
"Decimal128",
".",
"from_bid",
"(",
"data",
"[",
"position",
":",
"end",
"]",
")",
",",
"end",
")"
] | decode a bson decimal128 to bson . | train | true |
14,354 | def get_note_message(note):
assert (note <= 10), ("Note is %.2f. Either you cheated, or pylint's broken!" % note)
if (note < 0):
msg = 'You have to do something quick !'
elif (note < 1):
msg = 'Hey! This is really dreadful. Or maybe pylint is buggy?'
elif (note < 2):
msg = "Come on! You can't be proud of this code"
elif (note < 3):
msg = 'Hum... Needs work.'
elif (note < 4):
msg = "Wouldn't you be a bit lazy?"
elif (note < 5):
msg = 'A little more work would make it acceptable.'
elif (note < 6):
msg = 'Just the bare minimum. Give it a bit more polish. '
elif (note < 7):
msg = "This is okay-ish, but I'm sure you can do better."
elif (note < 8):
msg = 'If you commit now, people should not be making nasty comments about you on c.l.py'
elif (note < 9):
msg = "That's pretty good. Good work mate."
elif (note < 10):
msg = 'So close to being perfect...'
else:
msg = 'Wow ! Now this deserves our uttermost respect.\nPlease send your code to python-projects@logilab.org'
return msg
| [
"def",
"get_note_message",
"(",
"note",
")",
":",
"assert",
"(",
"note",
"<=",
"10",
")",
",",
"(",
"\"Note is %.2f. Either you cheated, or pylint's broken!\"",
"%",
"note",
")",
"if",
"(",
"note",
"<",
"0",
")",
":",
"msg",
"=",
"'You have to do something quick !'",
"elif",
"(",
"note",
"<",
"1",
")",
":",
"msg",
"=",
"'Hey! This is really dreadful. Or maybe pylint is buggy?'",
"elif",
"(",
"note",
"<",
"2",
")",
":",
"msg",
"=",
"\"Come on! You can't be proud of this code\"",
"elif",
"(",
"note",
"<",
"3",
")",
":",
"msg",
"=",
"'Hum... Needs work.'",
"elif",
"(",
"note",
"<",
"4",
")",
":",
"msg",
"=",
"\"Wouldn't you be a bit lazy?\"",
"elif",
"(",
"note",
"<",
"5",
")",
":",
"msg",
"=",
"'A little more work would make it acceptable.'",
"elif",
"(",
"note",
"<",
"6",
")",
":",
"msg",
"=",
"'Just the bare minimum. Give it a bit more polish. '",
"elif",
"(",
"note",
"<",
"7",
")",
":",
"msg",
"=",
"\"This is okay-ish, but I'm sure you can do better.\"",
"elif",
"(",
"note",
"<",
"8",
")",
":",
"msg",
"=",
"'If you commit now, people should not be making nasty comments about you on c.l.py'",
"elif",
"(",
"note",
"<",
"9",
")",
":",
"msg",
"=",
"\"That's pretty good. Good work mate.\"",
"elif",
"(",
"note",
"<",
"10",
")",
":",
"msg",
"=",
"'So close to being perfect...'",
"else",
":",
"msg",
"=",
"'Wow ! Now this deserves our uttermost respect.\\nPlease send your code to python-projects@logilab.org'",
"return",
"msg"
] | return a message according to note note is a float < 10 . | train | false |
14,355 | def b64_string(input_string):
return b64encode(input_string.encode('utf-8')).decode('utf-8')
| [
"def",
"b64_string",
"(",
"input_string",
")",
":",
"return",
"b64encode",
"(",
"input_string",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | return a base64 encoded string from input_string . | train | false |
14,357 | def joined(subset=None, show_ipv4=False):
return list_state(subset=subset, show_ipv4=show_ipv4, state='joined')
| [
"def",
"joined",
"(",
"subset",
"=",
"None",
",",
"show_ipv4",
"=",
"False",
")",
":",
"return",
"list_state",
"(",
"subset",
"=",
"subset",
",",
"show_ipv4",
"=",
"show_ipv4",
",",
"state",
"=",
"'joined'",
")"
] | ensure the current node joined to a cluster with node user@host name irrelevant . | train | false |
14,358 | def _check_instance_uid_match(user):
return (os.geteuid() == __salt__['file.user_to_uid'](user))
| [
"def",
"_check_instance_uid_match",
"(",
"user",
")",
":",
"return",
"(",
"os",
".",
"geteuid",
"(",
")",
"==",
"__salt__",
"[",
"'file.user_to_uid'",
"]",
"(",
"user",
")",
")"
] | returns true if running instances uid matches the specified user uid . | train | false |
14,359 | def pre_begin(opt):
global options
options = opt
for fn in pre_configure:
fn(options, file_config)
| [
"def",
"pre_begin",
"(",
"opt",
")",
":",
"global",
"options",
"options",
"=",
"opt",
"for",
"fn",
"in",
"pre_configure",
":",
"fn",
"(",
"options",
",",
"file_config",
")"
] | things to set up early . | train | false |
14,360 | def confidence_interval_dichotomous(point_estimate, sample_size, confidence=0.95, bias=False, percentage=True, **kwargs):
alpha = ppf(((confidence + 1) / 2), (sample_size - 1))
p = point_estimate
if percentage:
p /= 100
margin = sqrt(((p * (1 - p)) / sample_size))
if bias:
margin += (0.5 / sample_size)
if percentage:
margin *= 100
return ((point_estimate - (alpha * margin)), (point_estimate + (alpha * margin)))
| [
"def",
"confidence_interval_dichotomous",
"(",
"point_estimate",
",",
"sample_size",
",",
"confidence",
"=",
"0.95",
",",
"bias",
"=",
"False",
",",
"percentage",
"=",
"True",
",",
"**",
"kwargs",
")",
":",
"alpha",
"=",
"ppf",
"(",
"(",
"(",
"confidence",
"+",
"1",
")",
"/",
"2",
")",
",",
"(",
"sample_size",
"-",
"1",
")",
")",
"p",
"=",
"point_estimate",
"if",
"percentage",
":",
"p",
"/=",
"100",
"margin",
"=",
"sqrt",
"(",
"(",
"(",
"p",
"*",
"(",
"1",
"-",
"p",
")",
")",
"/",
"sample_size",
")",
")",
"if",
"bias",
":",
"margin",
"+=",
"(",
"0.5",
"/",
"sample_size",
")",
"if",
"percentage",
":",
"margin",
"*=",
"100",
"return",
"(",
"(",
"point_estimate",
"-",
"(",
"alpha",
"*",
"margin",
")",
")",
",",
"(",
"point_estimate",
"+",
"(",
"alpha",
"*",
"margin",
")",
")",
")"
] | dichotomous confidence interval from sample size and maybe a bias . | train | true |
14,362 | def pre_prompt_hook(self):
return None
| [
"def",
"pre_prompt_hook",
"(",
"self",
")",
":",
"return",
"None"
] | run before displaying the next prompt use this e . | train | false |
14,365 | @handle_response_format
@treeio_login_required
def equity_add(request, response_format='html'):
equities = Object.filter_by_request(request, Equity.objects, mode='r')
if request.POST:
if ('cancel' not in request.POST):
equity = Equity()
form = EquityForm(request.user.profile, request.POST, instance=equity)
if form.is_valid():
equity = form.save()
equity.set_user_from_request(request)
return HttpResponseRedirect(reverse('finance_equity_view', args=[equity.id]))
else:
return HttpResponseRedirect(reverse('finance_index_equities'))
else:
form = EquityForm(request.user.profile)
return render_to_response('finance/equity_add', {'form': form, 'equities': equities}, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"handle_response_format",
"@",
"treeio_login_required",
"def",
"equity_add",
"(",
"request",
",",
"response_format",
"=",
"'html'",
")",
":",
"equities",
"=",
"Object",
".",
"filter_by_request",
"(",
"request",
",",
"Equity",
".",
"objects",
",",
"mode",
"=",
"'r'",
")",
"if",
"request",
".",
"POST",
":",
"if",
"(",
"'cancel'",
"not",
"in",
"request",
".",
"POST",
")",
":",
"equity",
"=",
"Equity",
"(",
")",
"form",
"=",
"EquityForm",
"(",
"request",
".",
"user",
".",
"profile",
",",
"request",
".",
"POST",
",",
"instance",
"=",
"equity",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"equity",
"=",
"form",
".",
"save",
"(",
")",
"equity",
".",
"set_user_from_request",
"(",
"request",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'finance_equity_view'",
",",
"args",
"=",
"[",
"equity",
".",
"id",
"]",
")",
")",
"else",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'finance_index_equities'",
")",
")",
"else",
":",
"form",
"=",
"EquityForm",
"(",
"request",
".",
"user",
".",
"profile",
")",
"return",
"render_to_response",
"(",
"'finance/equity_add'",
",",
"{",
"'form'",
":",
"form",
",",
"'equities'",
":",
"equities",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] | new equity form . | train | false |
14,367 | @register.simple_tag(takes_context=True)
def pageurl(context, page):
return page.relative_url(context[u'request'].site)
| [
"@",
"register",
".",
"simple_tag",
"(",
"takes_context",
"=",
"True",
")",
"def",
"pageurl",
"(",
"context",
",",
"page",
")",
":",
"return",
"page",
".",
"relative_url",
"(",
"context",
"[",
"u'request'",
"]",
".",
"site",
")"
] | outputs a pages url as relative if its within the same site as the current page . | train | false |
14,371 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get the repository constructor . | train | false |
14,372 | def ensure_metadata_ip():
_execute('ip', 'addr', 'add', '169.254.169.254/32', 'scope', 'link', 'dev', 'lo', run_as_root=True, check_exit_code=[0, 2, 254])
| [
"def",
"ensure_metadata_ip",
"(",
")",
":",
"_execute",
"(",
"'ip'",
",",
"'addr'",
",",
"'add'",
",",
"'169.254.169.254/32'",
",",
"'scope'",
",",
"'link'",
",",
"'dev'",
",",
"'lo'",
",",
"run_as_root",
"=",
"True",
",",
"check_exit_code",
"=",
"[",
"0",
",",
"2",
",",
"254",
"]",
")"
] | sets up local metadata ip . | train | false |
14,373 | def expand_db_html(html, for_editor=False):
def replace_a_tag(m):
attrs = extract_attrs(m.group(1))
if (u'linktype' not in attrs):
return m.group(0)
handler = get_link_handler(attrs[u'linktype'])
return handler.expand_db_attributes(attrs, for_editor)
def replace_embed_tag(m):
attrs = extract_attrs(m.group(1))
handler = get_embed_handler(attrs[u'embedtype'])
return handler.expand_db_attributes(attrs, for_editor)
html = FIND_A_TAG.sub(replace_a_tag, html)
html = FIND_EMBED_TAG.sub(replace_embed_tag, html)
return html
| [
"def",
"expand_db_html",
"(",
"html",
",",
"for_editor",
"=",
"False",
")",
":",
"def",
"replace_a_tag",
"(",
"m",
")",
":",
"attrs",
"=",
"extract_attrs",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"if",
"(",
"u'linktype'",
"not",
"in",
"attrs",
")",
":",
"return",
"m",
".",
"group",
"(",
"0",
")",
"handler",
"=",
"get_link_handler",
"(",
"attrs",
"[",
"u'linktype'",
"]",
")",
"return",
"handler",
".",
"expand_db_attributes",
"(",
"attrs",
",",
"for_editor",
")",
"def",
"replace_embed_tag",
"(",
"m",
")",
":",
"attrs",
"=",
"extract_attrs",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"handler",
"=",
"get_embed_handler",
"(",
"attrs",
"[",
"u'embedtype'",
"]",
")",
"return",
"handler",
".",
"expand_db_attributes",
"(",
"attrs",
",",
"for_editor",
")",
"html",
"=",
"FIND_A_TAG",
".",
"sub",
"(",
"replace_a_tag",
",",
"html",
")",
"html",
"=",
"FIND_EMBED_TAG",
".",
"sub",
"(",
"replace_embed_tag",
",",
"html",
")",
"return",
"html"
] | expand database-representation html into proper html usable in either templates or the rich text editor . | train | false |
14,375 | def pretty_xml(container, name, raw):
root = container.parse_xml(raw)
if (name == container.opf_name):
pretty_opf(root)
pretty_xml_tree(root)
return serialize(root, u'text/xml')
| [
"def",
"pretty_xml",
"(",
"container",
",",
"name",
",",
"raw",
")",
":",
"root",
"=",
"container",
".",
"parse_xml",
"(",
"raw",
")",
"if",
"(",
"name",
"==",
"container",
".",
"opf_name",
")",
":",
"pretty_opf",
"(",
"root",
")",
"pretty_xml_tree",
"(",
"root",
")",
"return",
"serialize",
"(",
"root",
",",
"u'text/xml'",
")"
] | pretty print the xml represented as a string in raw . | train | false |
14,376 | def _notifications_from_dashboard_activity_list(user_dict, since):
context = {'model': model, 'session': model.Session, 'user': user_dict['id']}
activity_list = logic.get_action('dashboard_activity_list')(context, {})
activity_list = [activity for activity in activity_list if (activity['user_id'] != user_dict['id'])]
strptime = datetime.datetime.strptime
fmt = '%Y-%m-%dT%H:%M:%S.%f'
activity_list = [activity for activity in activity_list if (strptime(activity['timestamp'], fmt) > since)]
return _notifications_for_activities(activity_list, user_dict)
| [
"def",
"_notifications_from_dashboard_activity_list",
"(",
"user_dict",
",",
"since",
")",
":",
"context",
"=",
"{",
"'model'",
":",
"model",
",",
"'session'",
":",
"model",
".",
"Session",
",",
"'user'",
":",
"user_dict",
"[",
"'id'",
"]",
"}",
"activity_list",
"=",
"logic",
".",
"get_action",
"(",
"'dashboard_activity_list'",
")",
"(",
"context",
",",
"{",
"}",
")",
"activity_list",
"=",
"[",
"activity",
"for",
"activity",
"in",
"activity_list",
"if",
"(",
"activity",
"[",
"'user_id'",
"]",
"!=",
"user_dict",
"[",
"'id'",
"]",
")",
"]",
"strptime",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"fmt",
"=",
"'%Y-%m-%dT%H:%M:%S.%f'",
"activity_list",
"=",
"[",
"activity",
"for",
"activity",
"in",
"activity_list",
"if",
"(",
"strptime",
"(",
"activity",
"[",
"'timestamp'",
"]",
",",
"fmt",
")",
">",
"since",
")",
"]",
"return",
"_notifications_for_activities",
"(",
"activity_list",
",",
"user_dict",
")"
] | return any email notifications from the given users dashboard activity list since since . | train | false |
14,377 | def dump_neigh_entries(ip_version, device=None, namespace=None, **kwargs):
return list(privileged.dump_neigh_entries(ip_version, device, namespace, **kwargs))
| [
"def",
"dump_neigh_entries",
"(",
"ip_version",
",",
"device",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"return",
"list",
"(",
"privileged",
".",
"dump_neigh_entries",
"(",
"ip_version",
",",
"device",
",",
"namespace",
",",
"**",
"kwargs",
")",
")"
] | dump all neighbour entries . | train | false |
14,379 | def disable_share(cookie, tokens, shareid_list):
url = ''.join([const.PAN_URL, 'share/cancel?channel=chunlei&clienttype=0&web=1', '&bdstoken=', tokens['bdstoken']])
data = ('shareid_list=' + encoder.encode_uri(json.dumps(shareid_list)))
req = net.urlopen(url, headers={'Cookie': cookie.header_output(), 'Content-type': const.CONTENT_FORM_UTF8}, data=data.encode())
if req:
content = req.data
return json.loads(content.decode())
else:
return None
| [
"def",
"disable_share",
"(",
"cookie",
",",
"tokens",
",",
"shareid_list",
")",
":",
"url",
"=",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PAN_URL",
",",
"'share/cancel?channel=chunlei&clienttype=0&web=1'",
",",
"'&bdstoken='",
",",
"tokens",
"[",
"'bdstoken'",
"]",
"]",
")",
"data",
"=",
"(",
"'shareid_list='",
"+",
"encoder",
".",
"encode_uri",
"(",
"json",
".",
"dumps",
"(",
"shareid_list",
")",
")",
")",
"req",
"=",
"net",
".",
"urlopen",
"(",
"url",
",",
"headers",
"=",
"{",
"'Cookie'",
":",
"cookie",
".",
"header_output",
"(",
")",
",",
"'Content-type'",
":",
"const",
".",
"CONTENT_FORM_UTF8",
"}",
",",
"data",
"=",
"data",
".",
"encode",
"(",
")",
")",
"if",
"req",
":",
"content",
"=",
"req",
".",
"data",
"return",
"json",
".",
"loads",
"(",
"content",
".",
"decode",
"(",
")",
")",
"else",
":",
"return",
"None"
] | shareid_list 是一个list . | train | true |
14,380 | def get_data_from_request():
return {'request': {'url': ('%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path'])), 'query_string': web.ctx.query, 'method': web.ctx.method, 'data': web.data(), 'headers': dict(get_headers(web.ctx.environ)), 'env': dict(get_environ(web.ctx.environ))}}
| [
"def",
"get_data_from_request",
"(",
")",
":",
"return",
"{",
"'request'",
":",
"{",
"'url'",
":",
"(",
"'%s://%s%s'",
"%",
"(",
"web",
".",
"ctx",
"[",
"'protocol'",
"]",
",",
"web",
".",
"ctx",
"[",
"'host'",
"]",
",",
"web",
".",
"ctx",
"[",
"'path'",
"]",
")",
")",
",",
"'query_string'",
":",
"web",
".",
"ctx",
".",
"query",
",",
"'method'",
":",
"web",
".",
"ctx",
".",
"method",
",",
"'data'",
":",
"web",
".",
"data",
"(",
")",
",",
"'headers'",
":",
"dict",
"(",
"get_headers",
"(",
"web",
".",
"ctx",
".",
"environ",
")",
")",
",",
"'env'",
":",
"dict",
"(",
"get_environ",
"(",
"web",
".",
"ctx",
".",
"environ",
")",
")",
"}",
"}"
] | returns request data extracted from web . | train | true |
14,381 | def compute_cluster_state(node_state, additional_node_states, nonmanifest_datasets):
return DeploymentState(nodes=({node_state} | additional_node_states), nonmanifest_datasets={dataset.dataset_id: dataset for dataset in nonmanifest_datasets})
| [
"def",
"compute_cluster_state",
"(",
"node_state",
",",
"additional_node_states",
",",
"nonmanifest_datasets",
")",
":",
"return",
"DeploymentState",
"(",
"nodes",
"=",
"(",
"{",
"node_state",
"}",
"|",
"additional_node_states",
")",
",",
"nonmanifest_datasets",
"=",
"{",
"dataset",
".",
"dataset_id",
":",
"dataset",
"for",
"dataset",
"in",
"nonmanifest_datasets",
"}",
")"
] | computes the cluster_state from the passed in arguments . | train | false |
14,382 | @library.filter
def datetime(value, kind=u'datetime', format=u'medium', tz=True):
locale = get_current_babel_locale()
if (type(value) is date):
return format_date(value, format=format, locale=locale)
if tz:
value = localtime(value, (None if (tz is True) else tz))
if (kind == u'datetime'):
return format_datetime(value, format=format, locale=locale)
elif (kind == u'date'):
return format_date(value, format=format, locale=locale)
elif (kind == u'time'):
return format_time(value, format=format, locale=locale)
else:
raise ValueError((u'Unknown `datetime` kind: %r' % kind))
| [
"@",
"library",
".",
"filter",
"def",
"datetime",
"(",
"value",
",",
"kind",
"=",
"u'datetime'",
",",
"format",
"=",
"u'medium'",
",",
"tz",
"=",
"True",
")",
":",
"locale",
"=",
"get_current_babel_locale",
"(",
")",
"if",
"(",
"type",
"(",
"value",
")",
"is",
"date",
")",
":",
"return",
"format_date",
"(",
"value",
",",
"format",
"=",
"format",
",",
"locale",
"=",
"locale",
")",
"if",
"tz",
":",
"value",
"=",
"localtime",
"(",
"value",
",",
"(",
"None",
"if",
"(",
"tz",
"is",
"True",
")",
"else",
"tz",
")",
")",
"if",
"(",
"kind",
"==",
"u'datetime'",
")",
":",
"return",
"format_datetime",
"(",
"value",
",",
"format",
"=",
"format",
",",
"locale",
"=",
"locale",
")",
"elif",
"(",
"kind",
"==",
"u'date'",
")",
":",
"return",
"format_date",
"(",
"value",
",",
"format",
"=",
"format",
",",
"locale",
"=",
"locale",
")",
"elif",
"(",
"kind",
"==",
"u'time'",
")",
":",
"return",
"format_time",
"(",
"value",
",",
"format",
"=",
"format",
",",
"locale",
"=",
"locale",
")",
"else",
":",
"raise",
"ValueError",
"(",
"(",
"u'Unknown `datetime` kind: %r'",
"%",
"kind",
")",
")"
] | format a datetime for human consumption . | train | false |
14,384 | def PossessiveRepeat(element, min_count, max_count):
return Atomic(GreedyRepeat(element, min_count, max_count))
| [
"def",
"PossessiveRepeat",
"(",
"element",
",",
"min_count",
",",
"max_count",
")",
":",
"return",
"Atomic",
"(",
"GreedyRepeat",
"(",
"element",
",",
"min_count",
",",
"max_count",
")",
")"
] | builds a possessive repeat . | train | false |
14,386 | def submit_detailed_enrollment_features_csv(request, course_key):
task_type = 'detailed_enrollment_report'
task_class = enrollment_report_features_csv
task_input = {}
task_key = ''
return submit_task(request, task_type, task_class, course_key, task_input, task_key)
| [
"def",
"submit_detailed_enrollment_features_csv",
"(",
"request",
",",
"course_key",
")",
":",
"task_type",
"=",
"'detailed_enrollment_report'",
"task_class",
"=",
"enrollment_report_features_csv",
"task_input",
"=",
"{",
"}",
"task_key",
"=",
"''",
"return",
"submit_task",
"(",
"request",
",",
"task_type",
",",
"task_class",
",",
"course_key",
",",
"task_input",
",",
"task_key",
")"
] | submits a task to generate a csv containing detailed enrollment info . | train | false |
14,388 | def longest_line_length(code):
return max((len(line) for line in code.splitlines()))
| [
"def",
"longest_line_length",
"(",
"code",
")",
":",
"return",
"max",
"(",
"(",
"len",
"(",
"line",
")",
"for",
"line",
"in",
"code",
".",
"splitlines",
"(",
")",
")",
")"
] | return length of longest line . | train | false |
14,389 | def combine_xyz(vec, square=False):
if (vec.ndim != 2):
raise ValueError('Input must be 2D')
if ((vec.shape[0] % 3) != 0):
raise ValueError('Input must have 3N rows')
(n, p) = vec.shape
if np.iscomplexobj(vec):
vec = np.abs(vec)
comb = (vec[0::3] ** 2)
comb += (vec[1::3] ** 2)
comb += (vec[2::3] ** 2)
if (not square):
comb = np.sqrt(comb)
return comb
| [
"def",
"combine_xyz",
"(",
"vec",
",",
"square",
"=",
"False",
")",
":",
"if",
"(",
"vec",
".",
"ndim",
"!=",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'Input must be 2D'",
")",
"if",
"(",
"(",
"vec",
".",
"shape",
"[",
"0",
"]",
"%",
"3",
")",
"!=",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'Input must have 3N rows'",
")",
"(",
"n",
",",
"p",
")",
"=",
"vec",
".",
"shape",
"if",
"np",
".",
"iscomplexobj",
"(",
"vec",
")",
":",
"vec",
"=",
"np",
".",
"abs",
"(",
"vec",
")",
"comb",
"=",
"(",
"vec",
"[",
"0",
":",
":",
"3",
"]",
"**",
"2",
")",
"comb",
"+=",
"(",
"vec",
"[",
"1",
":",
":",
"3",
"]",
"**",
"2",
")",
"comb",
"+=",
"(",
"vec",
"[",
"2",
":",
":",
"3",
"]",
"**",
"2",
")",
"if",
"(",
"not",
"square",
")",
":",
"comb",
"=",
"np",
".",
"sqrt",
"(",
"comb",
")",
"return",
"comb"
] | compute the three cartesian components of a vector or matrix together . | train | false |
14,390 | def ssh_main():
ip = raw_input('Enter IP Address: ')
username = 'pyclass'
password = getpass()
test_device = NetworkDevice(ip, username, password)
(remote_conn_pre, remote_conn, _) = ssh.establish_connection(ip, username, password)
ssh.disable_paging(remote_conn)
remote_conn.send('\n')
remote_conn.send('show version\n')
test_device.show_version = ssh.read_ssh_data(remote_conn)
remote_conn_pre.close()
process_show_version(test_device)
net_device_verification(test_device)
with open('ssh_file.pkl', 'wb') as f:
pickle.dump(test_device, f)
| [
"def",
"ssh_main",
"(",
")",
":",
"ip",
"=",
"raw_input",
"(",
"'Enter IP Address: '",
")",
"username",
"=",
"'pyclass'",
"password",
"=",
"getpass",
"(",
")",
"test_device",
"=",
"NetworkDevice",
"(",
"ip",
",",
"username",
",",
"password",
")",
"(",
"remote_conn_pre",
",",
"remote_conn",
",",
"_",
")",
"=",
"ssh",
".",
"establish_connection",
"(",
"ip",
",",
"username",
",",
"password",
")",
"ssh",
".",
"disable_paging",
"(",
"remote_conn",
")",
"remote_conn",
".",
"send",
"(",
"'\\n'",
")",
"remote_conn",
".",
"send",
"(",
"'show version\\n'",
")",
"test_device",
".",
"show_version",
"=",
"ssh",
".",
"read_ssh_data",
"(",
"remote_conn",
")",
"remote_conn_pre",
".",
"close",
"(",
")",
"process_show_version",
"(",
"test_device",
")",
"net_device_verification",
"(",
"test_device",
")",
"with",
"open",
"(",
"'ssh_file.pkl'",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"test_device",
",",
"f",
")"
] | process show version using ssh . | train | false |
14,391 | def naughty_strings(filepath=FILEPATH):
strings = []
with open(filepath, 'r') as f:
strings = f.readlines()
strings = [x.strip(u'\n') for x in strings]
strings = [x for x in strings if (x and (not x.startswith(u'#')))]
strings.insert(0, u'')
return strings
| [
"def",
"naughty_strings",
"(",
"filepath",
"=",
"FILEPATH",
")",
":",
"strings",
"=",
"[",
"]",
"with",
"open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"f",
":",
"strings",
"=",
"f",
".",
"readlines",
"(",
")",
"strings",
"=",
"[",
"x",
".",
"strip",
"(",
"u'\\n'",
")",
"for",
"x",
"in",
"strings",
"]",
"strings",
"=",
"[",
"x",
"for",
"x",
"in",
"strings",
"if",
"(",
"x",
"and",
"(",
"not",
"x",
".",
"startswith",
"(",
"u'#'",
")",
")",
")",
"]",
"strings",
".",
"insert",
"(",
"0",
",",
"u''",
")",
"return",
"strings"
] | get the list of naughty_strings . | train | false |
14,392 | def trimmed_mean_ci(data, limits=(0.2, 0.2), inclusive=(True, True), alpha=0.05, axis=None):
data = ma.array(data, copy=False)
trimmed = mstats.trimr(data, limits=limits, inclusive=inclusive, axis=axis)
tmean = trimmed.mean(axis)
tstde = mstats.trimmed_stde(data, limits=limits, inclusive=inclusive, axis=axis)
df = (trimmed.count(axis) - 1)
tppf = t.ppf((1 - (alpha / 2.0)), df)
return np.array(((tmean - (tppf * tstde)), (tmean + (tppf * tstde))))
| [
"def",
"trimmed_mean_ci",
"(",
"data",
",",
"limits",
"=",
"(",
"0.2",
",",
"0.2",
")",
",",
"inclusive",
"=",
"(",
"True",
",",
"True",
")",
",",
"alpha",
"=",
"0.05",
",",
"axis",
"=",
"None",
")",
":",
"data",
"=",
"ma",
".",
"array",
"(",
"data",
",",
"copy",
"=",
"False",
")",
"trimmed",
"=",
"mstats",
".",
"trimr",
"(",
"data",
",",
"limits",
"=",
"limits",
",",
"inclusive",
"=",
"inclusive",
",",
"axis",
"=",
"axis",
")",
"tmean",
"=",
"trimmed",
".",
"mean",
"(",
"axis",
")",
"tstde",
"=",
"mstats",
".",
"trimmed_stde",
"(",
"data",
",",
"limits",
"=",
"limits",
",",
"inclusive",
"=",
"inclusive",
",",
"axis",
"=",
"axis",
")",
"df",
"=",
"(",
"trimmed",
".",
"count",
"(",
"axis",
")",
"-",
"1",
")",
"tppf",
"=",
"t",
".",
"ppf",
"(",
"(",
"1",
"-",
"(",
"alpha",
"/",
"2.0",
")",
")",
",",
"df",
")",
"return",
"np",
".",
"array",
"(",
"(",
"(",
"tmean",
"-",
"(",
"tppf",
"*",
"tstde",
")",
")",
",",
"(",
"tmean",
"+",
"(",
"tppf",
"*",
"tstde",
")",
")",
")",
")"
] | selected confidence interval of the trimmed mean along the given axis . | train | false |
14,393 | def Delete(keys, **kwargs):
return DeleteAsync(keys, **kwargs).get_result()
| [
"def",
"Delete",
"(",
"keys",
",",
"**",
"kwargs",
")",
":",
"return",
"DeleteAsync",
"(",
"keys",
",",
"**",
"kwargs",
")",
".",
"get_result",
"(",
")"
] | deletes one or more entities from the datastore . | train | false |
14,395 | def p_initializer_2(t):
pass
| [
"def",
"p_initializer_2",
"(",
"t",
")",
":",
"pass"
] | initializer : lbrace initializer_list rbrace | lbrace initializer_list comma rbrace . | train | false |
14,396 | def underscore(text):
return UNDERSCORE[1].sub('\\1_\\2', UNDERSCORE[0].sub('\\1_\\2', text)).lower()
| [
"def",
"underscore",
"(",
"text",
")",
":",
"return",
"UNDERSCORE",
"[",
"1",
"]",
".",
"sub",
"(",
"'\\\\1_\\\\2'",
",",
"UNDERSCORE",
"[",
"0",
"]",
".",
"sub",
"(",
"'\\\\1_\\\\2'",
",",
"text",
")",
")",
".",
"lower",
"(",
")"
] | convert dots to underscore in a string . | train | true |
14,397 | def _invert(eq, *symbols, **kwargs):
eq = sympify(eq)
free = eq.free_symbols
if (not symbols):
symbols = free
if (not (free & set(symbols))):
return (eq, S.Zero)
dointpow = bool(kwargs.get('integer_power', False))
lhs = eq
rhs = S.Zero
while True:
was = lhs
while True:
(indep, dep) = lhs.as_independent(*symbols)
if lhs.is_Add:
if (indep is S.Zero):
break
lhs = dep
rhs -= indep
else:
if (indep is S.One):
break
lhs = dep
rhs /= indep
if lhs.is_Add:
terms = {}
for a in lhs.args:
(i, d) = a.as_independent(*symbols)
terms.setdefault(d, []).append(i)
if any(((len(v) > 1) for v in terms.values())):
args = []
for (d, i) in terms.items():
if (len(i) > 1):
args.append((Add(*i) * d))
else:
args.append((i[0] * d))
lhs = Add(*args)
if (lhs.is_Add and (not rhs) and (len(lhs.args) == 2) and (not lhs.is_polynomial(*symbols))):
(a, b) = ordered(lhs.args)
(ai, ad) = a.as_independent(*symbols)
(bi, bd) = b.as_independent(*symbols)
if any((_ispow(i) for i in (ad, bd))):
(a_base, a_exp) = ad.as_base_exp()
(b_base, b_exp) = bd.as_base_exp()
if (a_base == b_base):
lhs = powsimp(powdenest((ad / bd)))
rhs = ((- bi) / ai)
else:
rat = (ad / bd)
_lhs = powsimp((ad / bd))
if (_lhs != rat):
lhs = _lhs
rhs = ((- bi) / ai)
if ((ai * bi) is S.NegativeOne):
if (all((isinstance(i, Function) for i in (ad, bd))) and (ad.func == bd.func) and (len(ad.args) == len(bd.args))):
if (len(ad.args) == 1):
lhs = (ad.args[0] - bd.args[0])
else:
raise NotImplementedError('equal function with more than 1 argument')
elif (lhs.is_Mul and any((_ispow(a) for a in lhs.args))):
lhs = powsimp(powdenest(lhs))
if lhs.is_Function:
if (hasattr(lhs, 'inverse') and (len(lhs.args) == 1)):
rhs = lhs.inverse()(rhs)
lhs = lhs.args[0]
elif (lhs.func is atan2):
(y, x) = lhs.args
lhs = (2 * atan((y / (sqrt(((x ** 2) + (y ** 2))) + x))))
if (rhs and lhs.is_Pow and lhs.exp.is_Integer and (lhs.exp < 0)):
lhs = (1 / lhs)
rhs = (1 / rhs)
if (lhs.is_Pow and ((lhs.exp.is_Integer and dointpow) or ((not lhs.exp.is_Integer) and (len(symbols) > 1) and (len((lhs.base.free_symbols & set(symbols))) > 1)))):
rhs = (rhs ** (1 / lhs.exp))
lhs = lhs.base
if (lhs == was):
break
return (rhs, lhs)
| [
"def",
"_invert",
"(",
"eq",
",",
"*",
"symbols",
",",
"**",
"kwargs",
")",
":",
"eq",
"=",
"sympify",
"(",
"eq",
")",
"free",
"=",
"eq",
".",
"free_symbols",
"if",
"(",
"not",
"symbols",
")",
":",
"symbols",
"=",
"free",
"if",
"(",
"not",
"(",
"free",
"&",
"set",
"(",
"symbols",
")",
")",
")",
":",
"return",
"(",
"eq",
",",
"S",
".",
"Zero",
")",
"dointpow",
"=",
"bool",
"(",
"kwargs",
".",
"get",
"(",
"'integer_power'",
",",
"False",
")",
")",
"lhs",
"=",
"eq",
"rhs",
"=",
"S",
".",
"Zero",
"while",
"True",
":",
"was",
"=",
"lhs",
"while",
"True",
":",
"(",
"indep",
",",
"dep",
")",
"=",
"lhs",
".",
"as_independent",
"(",
"*",
"symbols",
")",
"if",
"lhs",
".",
"is_Add",
":",
"if",
"(",
"indep",
"is",
"S",
".",
"Zero",
")",
":",
"break",
"lhs",
"=",
"dep",
"rhs",
"-=",
"indep",
"else",
":",
"if",
"(",
"indep",
"is",
"S",
".",
"One",
")",
":",
"break",
"lhs",
"=",
"dep",
"rhs",
"/=",
"indep",
"if",
"lhs",
".",
"is_Add",
":",
"terms",
"=",
"{",
"}",
"for",
"a",
"in",
"lhs",
".",
"args",
":",
"(",
"i",
",",
"d",
")",
"=",
"a",
".",
"as_independent",
"(",
"*",
"symbols",
")",
"terms",
".",
"setdefault",
"(",
"d",
",",
"[",
"]",
")",
".",
"append",
"(",
"i",
")",
"if",
"any",
"(",
"(",
"(",
"len",
"(",
"v",
")",
">",
"1",
")",
"for",
"v",
"in",
"terms",
".",
"values",
"(",
")",
")",
")",
":",
"args",
"=",
"[",
"]",
"for",
"(",
"d",
",",
"i",
")",
"in",
"terms",
".",
"items",
"(",
")",
":",
"if",
"(",
"len",
"(",
"i",
")",
">",
"1",
")",
":",
"args",
".",
"append",
"(",
"(",
"Add",
"(",
"*",
"i",
")",
"*",
"d",
")",
")",
"else",
":",
"args",
".",
"append",
"(",
"(",
"i",
"[",
"0",
"]",
"*",
"d",
")",
")",
"lhs",
"=",
"Add",
"(",
"*",
"args",
")",
"if",
"(",
"lhs",
".",
"is_Add",
"and",
"(",
"not",
"rhs",
")",
"and",
"(",
"len",
"(",
"lhs",
".",
"args",
")",
"==",
"2",
")",
"and",
"(",
"not",
"lhs",
".",
"is_polynomial",
"(",
"*",
"symbols",
")",
")",
")",
":",
"(",
"a",
",",
"b",
")",
"=",
"ordered",
"(",
"lhs",
".",
"args",
")",
"(",
"ai",
",",
"ad",
")",
"=",
"a",
".",
"as_independent",
"(",
"*",
"symbols",
")",
"(",
"bi",
",",
"bd",
")",
"=",
"b",
".",
"as_independent",
"(",
"*",
"symbols",
")",
"if",
"any",
"(",
"(",
"_ispow",
"(",
"i",
")",
"for",
"i",
"in",
"(",
"ad",
",",
"bd",
")",
")",
")",
":",
"(",
"a_base",
",",
"a_exp",
")",
"=",
"ad",
".",
"as_base_exp",
"(",
")",
"(",
"b_base",
",",
"b_exp",
")",
"=",
"bd",
".",
"as_base_exp",
"(",
")",
"if",
"(",
"a_base",
"==",
"b_base",
")",
":",
"lhs",
"=",
"powsimp",
"(",
"powdenest",
"(",
"(",
"ad",
"/",
"bd",
")",
")",
")",
"rhs",
"=",
"(",
"(",
"-",
"bi",
")",
"/",
"ai",
")",
"else",
":",
"rat",
"=",
"(",
"ad",
"/",
"bd",
")",
"_lhs",
"=",
"powsimp",
"(",
"(",
"ad",
"/",
"bd",
")",
")",
"if",
"(",
"_lhs",
"!=",
"rat",
")",
":",
"lhs",
"=",
"_lhs",
"rhs",
"=",
"(",
"(",
"-",
"bi",
")",
"/",
"ai",
")",
"if",
"(",
"(",
"ai",
"*",
"bi",
")",
"is",
"S",
".",
"NegativeOne",
")",
":",
"if",
"(",
"all",
"(",
"(",
"isinstance",
"(",
"i",
",",
"Function",
")",
"for",
"i",
"in",
"(",
"ad",
",",
"bd",
")",
")",
")",
"and",
"(",
"ad",
".",
"func",
"==",
"bd",
".",
"func",
")",
"and",
"(",
"len",
"(",
"ad",
".",
"args",
")",
"==",
"len",
"(",
"bd",
".",
"args",
")",
")",
")",
":",
"if",
"(",
"len",
"(",
"ad",
".",
"args",
")",
"==",
"1",
")",
":",
"lhs",
"=",
"(",
"ad",
".",
"args",
"[",
"0",
"]",
"-",
"bd",
".",
"args",
"[",
"0",
"]",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'equal function with more than 1 argument'",
")",
"elif",
"(",
"lhs",
".",
"is_Mul",
"and",
"any",
"(",
"(",
"_ispow",
"(",
"a",
")",
"for",
"a",
"in",
"lhs",
".",
"args",
")",
")",
")",
":",
"lhs",
"=",
"powsimp",
"(",
"powdenest",
"(",
"lhs",
")",
")",
"if",
"lhs",
".",
"is_Function",
":",
"if",
"(",
"hasattr",
"(",
"lhs",
",",
"'inverse'",
")",
"and",
"(",
"len",
"(",
"lhs",
".",
"args",
")",
"==",
"1",
")",
")",
":",
"rhs",
"=",
"lhs",
".",
"inverse",
"(",
")",
"(",
"rhs",
")",
"lhs",
"=",
"lhs",
".",
"args",
"[",
"0",
"]",
"elif",
"(",
"lhs",
".",
"func",
"is",
"atan2",
")",
":",
"(",
"y",
",",
"x",
")",
"=",
"lhs",
".",
"args",
"lhs",
"=",
"(",
"2",
"*",
"atan",
"(",
"(",
"y",
"/",
"(",
"sqrt",
"(",
"(",
"(",
"x",
"**",
"2",
")",
"+",
"(",
"y",
"**",
"2",
")",
")",
")",
"+",
"x",
")",
")",
")",
")",
"if",
"(",
"rhs",
"and",
"lhs",
".",
"is_Pow",
"and",
"lhs",
".",
"exp",
".",
"is_Integer",
"and",
"(",
"lhs",
".",
"exp",
"<",
"0",
")",
")",
":",
"lhs",
"=",
"(",
"1",
"/",
"lhs",
")",
"rhs",
"=",
"(",
"1",
"/",
"rhs",
")",
"if",
"(",
"lhs",
".",
"is_Pow",
"and",
"(",
"(",
"lhs",
".",
"exp",
".",
"is_Integer",
"and",
"dointpow",
")",
"or",
"(",
"(",
"not",
"lhs",
".",
"exp",
".",
"is_Integer",
")",
"and",
"(",
"len",
"(",
"symbols",
")",
">",
"1",
")",
"and",
"(",
"len",
"(",
"(",
"lhs",
".",
"base",
".",
"free_symbols",
"&",
"set",
"(",
"symbols",
")",
")",
")",
">",
"1",
")",
")",
")",
")",
":",
"rhs",
"=",
"(",
"rhs",
"**",
"(",
"1",
"/",
"lhs",
".",
"exp",
")",
")",
"lhs",
"=",
"lhs",
".",
"base",
"if",
"(",
"lhs",
"==",
"was",
")",
":",
"break",
"return",
"(",
"rhs",
",",
"lhs",
")"
] | reduce the complex valued equation f(x) = y to a set of equations {g(x) = h_1(y) . | train | false |
14,398 | def _CheckStatus(status):
if (status.code() != search_service_pb.SearchServiceError.OK):
if (status.code() in _ERROR_MAP):
raise _ERROR_MAP[status.code()](status.error_detail())
else:
raise InternalError(status.error_detail())
| [
"def",
"_CheckStatus",
"(",
"status",
")",
":",
"if",
"(",
"status",
".",
"code",
"(",
")",
"!=",
"search_service_pb",
".",
"SearchServiceError",
".",
"OK",
")",
":",
"if",
"(",
"status",
".",
"code",
"(",
")",
"in",
"_ERROR_MAP",
")",
":",
"raise",
"_ERROR_MAP",
"[",
"status",
".",
"code",
"(",
")",
"]",
"(",
"status",
".",
"error_detail",
"(",
")",
")",
"else",
":",
"raise",
"InternalError",
"(",
"status",
".",
"error_detail",
"(",
")",
")"
] | checks whether a requeststatus has a value of ok . | train | false |
14,399 | def addVector3Loop(loop, loops, vertexes, z):
vector3Loop = []
for point in loop:
vector3Index = Vector3Index(len(vertexes), point.real, point.imag, z)
vector3Loop.append(vector3Index)
vertexes.append(vector3Index)
if (len(vector3Loop) > 0):
loops.append(vector3Loop)
| [
"def",
"addVector3Loop",
"(",
"loop",
",",
"loops",
",",
"vertexes",
",",
"z",
")",
":",
"vector3Loop",
"=",
"[",
"]",
"for",
"point",
"in",
"loop",
":",
"vector3Index",
"=",
"Vector3Index",
"(",
"len",
"(",
"vertexes",
")",
",",
"point",
".",
"real",
",",
"point",
".",
"imag",
",",
"z",
")",
"vector3Loop",
".",
"append",
"(",
"vector3Index",
")",
"vertexes",
".",
"append",
"(",
"vector3Index",
")",
"if",
"(",
"len",
"(",
"vector3Loop",
")",
">",
"0",
")",
":",
"loops",
".",
"append",
"(",
"vector3Loop",
")"
] | add vector3loop to loops if there is something in it . | train | false |
14,400 | def setup_console_logger(log_level='error', log_format=None, date_format=None):
if is_console_configured():
logging.getLogger(__name__).warning('Console logging already configured')
return
__remove_temp_logging_handler()
if (log_level is None):
log_level = 'warning'
level = LOG_LEVELS.get(log_level.lower(), logging.ERROR)
setLogRecordFactory(SaltColorLogRecord)
handler = None
for handler in logging.root.handlers:
if (handler is LOGGING_STORE_HANDLER):
continue
if (not hasattr(handler, 'stream')):
continue
if (handler.stream is sys.stderr):
break
else:
handler = StreamHandler(sys.stderr)
handler.setLevel(level)
if (not log_format):
log_format = '[%(levelname)-8s] %(message)s'
if (not date_format):
date_format = '%H:%M:%S'
formatter = logging.Formatter(log_format, datefmt=date_format)
handler.setFormatter(formatter)
logging.root.addHandler(handler)
global __CONSOLE_CONFIGURED
global __LOGGING_CONSOLE_HANDLER
__CONSOLE_CONFIGURED = True
__LOGGING_CONSOLE_HANDLER = handler
| [
"def",
"setup_console_logger",
"(",
"log_level",
"=",
"'error'",
",",
"log_format",
"=",
"None",
",",
"date_format",
"=",
"None",
")",
":",
"if",
"is_console_configured",
"(",
")",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"warning",
"(",
"'Console logging already configured'",
")",
"return",
"__remove_temp_logging_handler",
"(",
")",
"if",
"(",
"log_level",
"is",
"None",
")",
":",
"log_level",
"=",
"'warning'",
"level",
"=",
"LOG_LEVELS",
".",
"get",
"(",
"log_level",
".",
"lower",
"(",
")",
",",
"logging",
".",
"ERROR",
")",
"setLogRecordFactory",
"(",
"SaltColorLogRecord",
")",
"handler",
"=",
"None",
"for",
"handler",
"in",
"logging",
".",
"root",
".",
"handlers",
":",
"if",
"(",
"handler",
"is",
"LOGGING_STORE_HANDLER",
")",
":",
"continue",
"if",
"(",
"not",
"hasattr",
"(",
"handler",
",",
"'stream'",
")",
")",
":",
"continue",
"if",
"(",
"handler",
".",
"stream",
"is",
"sys",
".",
"stderr",
")",
":",
"break",
"else",
":",
"handler",
"=",
"StreamHandler",
"(",
"sys",
".",
"stderr",
")",
"handler",
".",
"setLevel",
"(",
"level",
")",
"if",
"(",
"not",
"log_format",
")",
":",
"log_format",
"=",
"'[%(levelname)-8s] %(message)s'",
"if",
"(",
"not",
"date_format",
")",
":",
"date_format",
"=",
"'%H:%M:%S'",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"log_format",
",",
"datefmt",
"=",
"date_format",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"logging",
".",
"root",
".",
"addHandler",
"(",
"handler",
")",
"global",
"__CONSOLE_CONFIGURED",
"global",
"__LOGGING_CONSOLE_HANDLER",
"__CONSOLE_CONFIGURED",
"=",
"True",
"__LOGGING_CONSOLE_HANDLER",
"=",
"handler"
] | setup the console logger . | train | true |
14,403 | def load_soups(config):
soups = {}
for (page, path) in config[u'sources'].items():
with open(path, u'rb') as orig_file:
soups[page] = beautiful_soup(orig_file.read().decode(u'utf-8'))
return soups
| [
"def",
"load_soups",
"(",
"config",
")",
":",
"soups",
"=",
"{",
"}",
"for",
"(",
"page",
",",
"path",
")",
"in",
"config",
"[",
"u'sources'",
"]",
".",
"items",
"(",
")",
":",
"with",
"open",
"(",
"path",
",",
"u'rb'",
")",
"as",
"orig_file",
":",
"soups",
"[",
"page",
"]",
"=",
"beautiful_soup",
"(",
"orig_file",
".",
"read",
"(",
")",
".",
"decode",
"(",
"u'utf-8'",
")",
")",
"return",
"soups"
] | generate beautifulsoup ast for each page listed in config . | train | false |
14,404 | def must_answer_survey(course_descriptor, user):
if (not is_survey_required_for_course(course_descriptor)):
return False
survey = SurveyForm.get(course_descriptor.course_survey_name)
has_staff_access = has_access(user, 'staff', course_descriptor)
answered_survey = SurveyAnswer.do_survey_answers_exist(survey, user)
return ((not answered_survey) and (not has_staff_access))
| [
"def",
"must_answer_survey",
"(",
"course_descriptor",
",",
"user",
")",
":",
"if",
"(",
"not",
"is_survey_required_for_course",
"(",
"course_descriptor",
")",
")",
":",
"return",
"False",
"survey",
"=",
"SurveyForm",
".",
"get",
"(",
"course_descriptor",
".",
"course_survey_name",
")",
"has_staff_access",
"=",
"has_access",
"(",
"user",
",",
"'staff'",
",",
"course_descriptor",
")",
"answered_survey",
"=",
"SurveyAnswer",
".",
"do_survey_answers_exist",
"(",
"survey",
",",
"user",
")",
"return",
"(",
"(",
"not",
"answered_survey",
")",
"and",
"(",
"not",
"has_staff_access",
")",
")"
] | returns whether a user needs to answer a required survey . | train | false |
14,405 | def device_exists(device):
(_out, err) = _execute('ip', 'link', 'show', 'dev', device, check_exit_code=False, run_as_root=True)
return (not err)
| [
"def",
"device_exists",
"(",
"device",
")",
":",
"(",
"_out",
",",
"err",
")",
"=",
"_execute",
"(",
"'ip'",
",",
"'link'",
",",
"'show'",
",",
"'dev'",
",",
"device",
",",
"check_exit_code",
"=",
"False",
",",
"run_as_root",
"=",
"True",
")",
"return",
"(",
"not",
"err",
")"
] | return true if the device exists in the namespace . | train | false |
14,406 | def print_duration(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print ('%r %2.2f sec' % (method.__name__, (te - ts)))
return result
return timed
| [
"def",
"print_duration",
"(",
"method",
")",
":",
"def",
"timed",
"(",
"*",
"args",
",",
"**",
"kw",
")",
":",
"ts",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"method",
"(",
"*",
"args",
",",
"**",
"kw",
")",
"te",
"=",
"time",
".",
"time",
"(",
")",
"print",
"(",
"'%r %2.2f sec'",
"%",
"(",
"method",
".",
"__name__",
",",
"(",
"te",
"-",
"ts",
")",
")",
")",
"return",
"result",
"return",
"timed"
] | prints out the runtime duration of a method in seconds . | train | true |
14,407 | def _runMultiple(tupleList):
for (f, args, kwargs) in tupleList:
f(*args, **kwargs)
| [
"def",
"_runMultiple",
"(",
"tupleList",
")",
":",
"for",
"(",
"f",
",",
"args",
",",
"kwargs",
")",
"in",
"tupleList",
":",
"f",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | run a list of functions . | train | false |
14,408 | def _string_to_record_type(string):
string = string.upper()
record_type = getattr(RecordType, string)
return record_type
| [
"def",
"_string_to_record_type",
"(",
"string",
")",
":",
"string",
"=",
"string",
".",
"upper",
"(",
")",
"record_type",
"=",
"getattr",
"(",
"RecordType",
",",
"string",
")",
"return",
"record_type"
] | return a string representation of a dns record type to a libcloud recordtype enum . | train | true |
14,409 | def _restore_str(unused_name, value):
return (None if (value == 'None') else value)
| [
"def",
"_restore_str",
"(",
"unused_name",
",",
"value",
")",
":",
"return",
"(",
"None",
"if",
"(",
"value",
"==",
"'None'",
")",
"else",
"value",
")"
] | restores an string key-value pair from a renewal config file . | train | false |
14,410 | def test_saving_state_exclude_domains(hass_recorder):
hass = hass_recorder({'exclude': {'domains': 'test'}})
states = _add_entities(hass, ['test.recorder', 'test2.recorder'])
assert (len(states) == 1)
assert (hass.states.get('test2.recorder') == states[0])
| [
"def",
"test_saving_state_exclude_domains",
"(",
"hass_recorder",
")",
":",
"hass",
"=",
"hass_recorder",
"(",
"{",
"'exclude'",
":",
"{",
"'domains'",
":",
"'test'",
"}",
"}",
")",
"states",
"=",
"_add_entities",
"(",
"hass",
",",
"[",
"'test.recorder'",
",",
"'test2.recorder'",
"]",
")",
"assert",
"(",
"len",
"(",
"states",
")",
"==",
"1",
")",
"assert",
"(",
"hass",
".",
"states",
".",
"get",
"(",
"'test2.recorder'",
")",
"==",
"states",
"[",
"0",
"]",
")"
] | test saving and restoring a state . | train | false |
14,411 | def test_make_imbalance_bad_ratio():
min_c_ = 1
ratio = 0.0
assert_raises(ValueError, make_imbalance, X, Y, ratio, min_c_)
ratio = (-2.0)
assert_raises(ValueError, make_imbalance, X, Y, ratio, min_c_)
ratio = 2.0
assert_raises(ValueError, make_imbalance, X, Y, ratio, min_c_)
ratio = [0.5, 0.5]
assert_raises(ValueError, make_imbalance, X, Y, ratio, min_c_)
| [
"def",
"test_make_imbalance_bad_ratio",
"(",
")",
":",
"min_c_",
"=",
"1",
"ratio",
"=",
"0.0",
"assert_raises",
"(",
"ValueError",
",",
"make_imbalance",
",",
"X",
",",
"Y",
",",
"ratio",
",",
"min_c_",
")",
"ratio",
"=",
"(",
"-",
"2.0",
")",
"assert_raises",
"(",
"ValueError",
",",
"make_imbalance",
",",
"X",
",",
"Y",
",",
"ratio",
",",
"min_c_",
")",
"ratio",
"=",
"2.0",
"assert_raises",
"(",
"ValueError",
",",
"make_imbalance",
",",
"X",
",",
"Y",
",",
"ratio",
",",
"min_c_",
")",
"ratio",
"=",
"[",
"0.5",
",",
"0.5",
"]",
"assert_raises",
"(",
"ValueError",
",",
"make_imbalance",
",",
"X",
",",
"Y",
",",
"ratio",
",",
"min_c_",
")"
] | test either if an error is raised with bad ratio argument . | train | false |
14,412 | def multiset_partitions_baseline(multiplicities, components):
canon = []
for (ct, elem) in zip(multiplicities, components):
canon.extend(([elem] * ct))
cache = set()
n = len(canon)
for (nc, q) in _set_partitions(n):
rv = [[] for i in range(nc)]
for i in range(n):
rv[q[i]].append(canon[i])
canonical = tuple(sorted([tuple(p) for p in rv]))
cache.add(canonical)
return cache
| [
"def",
"multiset_partitions_baseline",
"(",
"multiplicities",
",",
"components",
")",
":",
"canon",
"=",
"[",
"]",
"for",
"(",
"ct",
",",
"elem",
")",
"in",
"zip",
"(",
"multiplicities",
",",
"components",
")",
":",
"canon",
".",
"extend",
"(",
"(",
"[",
"elem",
"]",
"*",
"ct",
")",
")",
"cache",
"=",
"set",
"(",
")",
"n",
"=",
"len",
"(",
"canon",
")",
"for",
"(",
"nc",
",",
"q",
")",
"in",
"_set_partitions",
"(",
"n",
")",
":",
"rv",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"nc",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"rv",
"[",
"q",
"[",
"i",
"]",
"]",
".",
"append",
"(",
"canon",
"[",
"i",
"]",
")",
"canonical",
"=",
"tuple",
"(",
"sorted",
"(",
"[",
"tuple",
"(",
"p",
")",
"for",
"p",
"in",
"rv",
"]",
")",
")",
"cache",
".",
"add",
"(",
"canonical",
")",
"return",
"cache"
] | enumerates partitions of a multiset parameters multiplicities list of integer multiplicities of the components of the multiset . | train | false |
14,413 | def config_java(bin=None, options=None, verbose=False):
global _java_bin, _java_options
_java_bin = find_binary('java', bin, env_vars=['JAVAHOME', 'JAVA_HOME'], verbose=verbose, binary_names=['java.exe'])
if (options is not None):
if isinstance(options, compat.string_types):
options = options.split()
_java_options = list(options)
| [
"def",
"config_java",
"(",
"bin",
"=",
"None",
",",
"options",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"global",
"_java_bin",
",",
"_java_options",
"_java_bin",
"=",
"find_binary",
"(",
"'java'",
",",
"bin",
",",
"env_vars",
"=",
"[",
"'JAVAHOME'",
",",
"'JAVA_HOME'",
"]",
",",
"verbose",
"=",
"verbose",
",",
"binary_names",
"=",
"[",
"'java.exe'",
"]",
")",
"if",
"(",
"options",
"is",
"not",
"None",
")",
":",
"if",
"isinstance",
"(",
"options",
",",
"compat",
".",
"string_types",
")",
":",
"options",
"=",
"options",
".",
"split",
"(",
")",
"_java_options",
"=",
"list",
"(",
"options",
")"
] | configure nltks java interface . | train | false |
14,415 | def membership_type():
if (not auth.s3_has_role(ADMIN)):
s3.filter = auth.filter_by_root_org(s3db.member_membership_type)
output = s3_rest_controller()
return output
| [
"def",
"membership_type",
"(",
")",
":",
"if",
"(",
"not",
"auth",
".",
"s3_has_role",
"(",
"ADMIN",
")",
")",
":",
"s3",
".",
"filter",
"=",
"auth",
".",
"filter_by_root_org",
"(",
"s3db",
".",
"member_membership_type",
")",
"output",
"=",
"s3_rest_controller",
"(",
")",
"return",
"output"
] | rest controller . | train | false |
14,417 | def populate_project_info(attributes):
if (('tenant_id' in attributes) and ('project_id' not in attributes)):
attributes['project_id'] = attributes['tenant_id']
elif (('project_id' in attributes) and ('tenant_id' not in attributes)):
attributes['tenant_id'] = attributes['project_id']
if (attributes.get('project_id') != attributes.get('tenant_id')):
msg = _("'project_id' and 'tenant_id' do not match")
raise webob.exc.HTTPBadRequest(msg)
return attributes
| [
"def",
"populate_project_info",
"(",
"attributes",
")",
":",
"if",
"(",
"(",
"'tenant_id'",
"in",
"attributes",
")",
"and",
"(",
"'project_id'",
"not",
"in",
"attributes",
")",
")",
":",
"attributes",
"[",
"'project_id'",
"]",
"=",
"attributes",
"[",
"'tenant_id'",
"]",
"elif",
"(",
"(",
"'project_id'",
"in",
"attributes",
")",
"and",
"(",
"'tenant_id'",
"not",
"in",
"attributes",
")",
")",
":",
"attributes",
"[",
"'tenant_id'",
"]",
"=",
"attributes",
"[",
"'project_id'",
"]",
"if",
"(",
"attributes",
".",
"get",
"(",
"'project_id'",
")",
"!=",
"attributes",
".",
"get",
"(",
"'tenant_id'",
")",
")",
":",
"msg",
"=",
"_",
"(",
"\"'project_id' and 'tenant_id' do not match\"",
")",
"raise",
"webob",
".",
"exc",
".",
"HTTPBadRequest",
"(",
"msg",
")",
"return",
"attributes"
] | ensure that both project_id and tenant_id attributes are present . | train | false |
14,419 | def enable_color():
global LIGHT_GREEN
LIGHT_GREEN = '\x1b[1;32m'
global LIGHT_RED
LIGHT_RED = '\x1b[1;31m'
global LIGHT_BLUE
LIGHT_BLUE = '\x1b[1;34m'
global DARK_RED
DARK_RED = '\x1b[0;31m'
global END_COLOR
END_COLOR = '\x1b[0m'
| [
"def",
"enable_color",
"(",
")",
":",
"global",
"LIGHT_GREEN",
"LIGHT_GREEN",
"=",
"'\\x1b[1;32m'",
"global",
"LIGHT_RED",
"LIGHT_RED",
"=",
"'\\x1b[1;31m'",
"global",
"LIGHT_BLUE",
"LIGHT_BLUE",
"=",
"'\\x1b[1;34m'",
"global",
"DARK_RED",
"DARK_RED",
"=",
"'\\x1b[0;31m'",
"global",
"END_COLOR",
"END_COLOR",
"=",
"'\\x1b[0m'"
] | enable colors by setting colour code constants to ansi color codes . | train | false |
14,420 | def prop_show(prop, extra_args=None, cibfile=None):
return item_show(item='property', item_id=prop, extra_args=extra_args, cibfile=cibfile)
| [
"def",
"prop_show",
"(",
"prop",
",",
"extra_args",
"=",
"None",
",",
"cibfile",
"=",
"None",
")",
":",
"return",
"item_show",
"(",
"item",
"=",
"'property'",
",",
"item_id",
"=",
"prop",
",",
"extra_args",
"=",
"extra_args",
",",
"cibfile",
"=",
"cibfile",
")"
] | show the value of a cluster property prop name of the property extra_args additional options for the pcs property command cibfile use cibfile instead of the live cib cli example: . | train | true |
14,421 | def check_net_address(addr, family):
if (enum and PY3):
assert isinstance(family, enum.IntEnum), family
if (family == AF_INET):
octs = [int(x) for x in addr.split('.')]
assert (len(octs) == 4), addr
for num in octs:
assert (0 <= num <= 255), addr
if (not PY3):
addr = unicode(addr)
ipaddress.IPv4Address(addr)
elif (family == AF_INET6):
assert isinstance(addr, str), addr
if (not PY3):
addr = unicode(addr)
ipaddress.IPv6Address(addr)
elif (family == psutil.AF_LINK):
assert (re.match('([a-fA-F0-9]{2}[:|\\-]?){6}', addr) is not None), addr
else:
raise ValueError('unknown family %r', family)
| [
"def",
"check_net_address",
"(",
"addr",
",",
"family",
")",
":",
"if",
"(",
"enum",
"and",
"PY3",
")",
":",
"assert",
"isinstance",
"(",
"family",
",",
"enum",
".",
"IntEnum",
")",
",",
"family",
"if",
"(",
"family",
"==",
"AF_INET",
")",
":",
"octs",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"addr",
".",
"split",
"(",
"'.'",
")",
"]",
"assert",
"(",
"len",
"(",
"octs",
")",
"==",
"4",
")",
",",
"addr",
"for",
"num",
"in",
"octs",
":",
"assert",
"(",
"0",
"<=",
"num",
"<=",
"255",
")",
",",
"addr",
"if",
"(",
"not",
"PY3",
")",
":",
"addr",
"=",
"unicode",
"(",
"addr",
")",
"ipaddress",
".",
"IPv4Address",
"(",
"addr",
")",
"elif",
"(",
"family",
"==",
"AF_INET6",
")",
":",
"assert",
"isinstance",
"(",
"addr",
",",
"str",
")",
",",
"addr",
"if",
"(",
"not",
"PY3",
")",
":",
"addr",
"=",
"unicode",
"(",
"addr",
")",
"ipaddress",
".",
"IPv6Address",
"(",
"addr",
")",
"elif",
"(",
"family",
"==",
"psutil",
".",
"AF_LINK",
")",
":",
"assert",
"(",
"re",
".",
"match",
"(",
"'([a-fA-F0-9]{2}[:|\\\\-]?){6}'",
",",
"addr",
")",
"is",
"not",
"None",
")",
",",
"addr",
"else",
":",
"raise",
"ValueError",
"(",
"'unknown family %r'",
",",
"family",
")"
] | check a net address validity . | train | false |
14,422 | def getUserContact(master, contact_types, uid):
d = master.db.users.getUser(uid)
d.addCallback(_extractContact, contact_types, uid)
return d
| [
"def",
"getUserContact",
"(",
"master",
",",
"contact_types",
",",
"uid",
")",
":",
"d",
"=",
"master",
".",
"db",
".",
"users",
".",
"getUser",
"(",
"uid",
")",
"d",
".",
"addCallback",
"(",
"_extractContact",
",",
"contact_types",
",",
"uid",
")",
"return",
"d"
] | this is a simple getter function that returns a user attribute that matches the contact_types argument . | train | true |
14,423 | def check_dna_chars_primers(header, mapping_data, errors, disable_primer_check=False):
valid_dna_chars = DNASequence.iupac_characters()
valid_dna_chars.add(',')
header_fields_to_check = ['ReversePrimer']
if (not disable_primer_check):
header_fields_to_check.append('LinkerPrimerSequence')
check_indices = []
for curr_field in range(len(header)):
if (header[curr_field] in header_fields_to_check):
check_indices.append(curr_field)
correction_ix = 1
for curr_data in range(len(mapping_data)):
for curr_ix in check_indices:
if (len(mapping_data[curr_data][curr_ix]) == 0):
errors.append(('Missing expected DNA sequence DCTB %d,%d' % ((curr_data + correction_ix), curr_ix)))
for curr_data in range(len(mapping_data)):
for curr_ix in check_indices:
for curr_nt in mapping_data[curr_data][curr_ix]:
if (curr_nt not in valid_dna_chars):
errors.append(('Invalid DNA sequence detected: %s DCTB %d,%d' % (mapping_data[curr_data][curr_ix], (curr_data + correction_ix), curr_ix)))
continue
return errors
| [
"def",
"check_dna_chars_primers",
"(",
"header",
",",
"mapping_data",
",",
"errors",
",",
"disable_primer_check",
"=",
"False",
")",
":",
"valid_dna_chars",
"=",
"DNASequence",
".",
"iupac_characters",
"(",
")",
"valid_dna_chars",
".",
"add",
"(",
"','",
")",
"header_fields_to_check",
"=",
"[",
"'ReversePrimer'",
"]",
"if",
"(",
"not",
"disable_primer_check",
")",
":",
"header_fields_to_check",
".",
"append",
"(",
"'LinkerPrimerSequence'",
")",
"check_indices",
"=",
"[",
"]",
"for",
"curr_field",
"in",
"range",
"(",
"len",
"(",
"header",
")",
")",
":",
"if",
"(",
"header",
"[",
"curr_field",
"]",
"in",
"header_fields_to_check",
")",
":",
"check_indices",
".",
"append",
"(",
"curr_field",
")",
"correction_ix",
"=",
"1",
"for",
"curr_data",
"in",
"range",
"(",
"len",
"(",
"mapping_data",
")",
")",
":",
"for",
"curr_ix",
"in",
"check_indices",
":",
"if",
"(",
"len",
"(",
"mapping_data",
"[",
"curr_data",
"]",
"[",
"curr_ix",
"]",
")",
"==",
"0",
")",
":",
"errors",
".",
"append",
"(",
"(",
"'Missing expected DNA sequence DCTB %d,%d'",
"%",
"(",
"(",
"curr_data",
"+",
"correction_ix",
")",
",",
"curr_ix",
")",
")",
")",
"for",
"curr_data",
"in",
"range",
"(",
"len",
"(",
"mapping_data",
")",
")",
":",
"for",
"curr_ix",
"in",
"check_indices",
":",
"for",
"curr_nt",
"in",
"mapping_data",
"[",
"curr_data",
"]",
"[",
"curr_ix",
"]",
":",
"if",
"(",
"curr_nt",
"not",
"in",
"valid_dna_chars",
")",
":",
"errors",
".",
"append",
"(",
"(",
"'Invalid DNA sequence detected: %s DCTB %d,%d'",
"%",
"(",
"mapping_data",
"[",
"curr_data",
"]",
"[",
"curr_ix",
"]",
",",
"(",
"curr_data",
"+",
"correction_ix",
")",
",",
"curr_ix",
")",
")",
")",
"continue",
"return",
"errors"
] | checks for valid dna characters in primer fields also flags empty fields as errors unless flags are passed to suppress barcode or primer checks . | train | false |
14,425 | def denormalize_form_dict(data_dict, form, attr_list):
assert isinstance(form, forms.Form)
res = django.http.QueryDict('', mutable=True)
for attr in attr_list:
try:
res[str(form.add_prefix(attr))] = data_dict[attr]
except KeyError:
pass
return res
| [
"def",
"denormalize_form_dict",
"(",
"data_dict",
",",
"form",
",",
"attr_list",
")",
":",
"assert",
"isinstance",
"(",
"form",
",",
"forms",
".",
"Form",
")",
"res",
"=",
"django",
".",
"http",
".",
"QueryDict",
"(",
"''",
",",
"mutable",
"=",
"True",
")",
"for",
"attr",
"in",
"attr_list",
":",
"try",
":",
"res",
"[",
"str",
"(",
"form",
".",
"add_prefix",
"(",
"attr",
")",
")",
"]",
"=",
"data_dict",
"[",
"attr",
"]",
"except",
"KeyError",
":",
"pass",
"return",
"res"
] | denormalize_form_dict -> a querydict with the attributes set . | train | false |
14,426 | def find_python_files(path):
try:
return sorted([file[:(-3)] for file in os.listdir(path) if ((not file.startswith(('_', '.'))) and file.endswith('.py'))])
except OSError:
return []
| [
"def",
"find_python_files",
"(",
"path",
")",
":",
"try",
":",
"return",
"sorted",
"(",
"[",
"file",
"[",
":",
"(",
"-",
"3",
")",
"]",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"if",
"(",
"(",
"not",
"file",
".",
"startswith",
"(",
"(",
"'_'",
",",
"'.'",
")",
")",
")",
"and",
"file",
".",
"endswith",
"(",
"'.py'",
")",
")",
"]",
")",
"except",
"OSError",
":",
"return",
"[",
"]"
] | return a list of the python files in a directory . | train | false |
14,427 | @treeio_login_required
@handle_response_format
def service_record_edit(request, service_record_id, response_format='html'):
service_record = get_object_or_404(ItemServicing, pk=service_record_id)
if (not request.user.profile.has_permission(service_record, mode='w')):
return user_denied(request, message="You don't have write access to this ServiceRecord", response_format=response_format)
if request.POST:
if ('cancel' not in request.POST):
form = ServiceRecordForm(request.user.profile, None, request.POST, instance=service_record)
if form.is_valid():
service_record = form.save(request)
return HttpResponseRedirect(reverse('infrastructure_service_record_view', args=[service_record.id]))
else:
return HttpResponseRedirect(reverse('infrastructure_service_record_view', args=[service_record.id]))
else:
form = ServiceRecordForm(request.user.profile, None, instance=service_record)
context = _get_default_context(request)
context.update({'service_record': service_record, 'form': form})
return render_to_response('infrastructure/service_record_edit', context, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"treeio_login_required",
"@",
"handle_response_format",
"def",
"service_record_edit",
"(",
"request",
",",
"service_record_id",
",",
"response_format",
"=",
"'html'",
")",
":",
"service_record",
"=",
"get_object_or_404",
"(",
"ItemServicing",
",",
"pk",
"=",
"service_record_id",
")",
"if",
"(",
"not",
"request",
".",
"user",
".",
"profile",
".",
"has_permission",
"(",
"service_record",
",",
"mode",
"=",
"'w'",
")",
")",
":",
"return",
"user_denied",
"(",
"request",
",",
"message",
"=",
"\"You don't have write access to this ServiceRecord\"",
",",
"response_format",
"=",
"response_format",
")",
"if",
"request",
".",
"POST",
":",
"if",
"(",
"'cancel'",
"not",
"in",
"request",
".",
"POST",
")",
":",
"form",
"=",
"ServiceRecordForm",
"(",
"request",
".",
"user",
".",
"profile",
",",
"None",
",",
"request",
".",
"POST",
",",
"instance",
"=",
"service_record",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"service_record",
"=",
"form",
".",
"save",
"(",
"request",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'infrastructure_service_record_view'",
",",
"args",
"=",
"[",
"service_record",
".",
"id",
"]",
")",
")",
"else",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'infrastructure_service_record_view'",
",",
"args",
"=",
"[",
"service_record",
".",
"id",
"]",
")",
")",
"else",
":",
"form",
"=",
"ServiceRecordForm",
"(",
"request",
".",
"user",
".",
"profile",
",",
"None",
",",
"instance",
"=",
"service_record",
")",
"context",
"=",
"_get_default_context",
"(",
"request",
")",
"context",
".",
"update",
"(",
"{",
"'service_record'",
":",
"service_record",
",",
"'form'",
":",
"form",
"}",
")",
"return",
"render_to_response",
"(",
"'infrastructure/service_record_edit'",
",",
"context",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] | servicerecord edit page . | train | false |
14,428 | def topological_sort(graph, key=None):
(V, E) = graph
L = []
S = set(V)
E = list(E)
for (v, u) in E:
S.discard(u)
if (key is None):
key = (lambda value: value)
S = sorted(S, key=key, reverse=True)
while S:
node = S.pop()
L.append(node)
for (u, v) in list(E):
if (u == node):
E.remove((u, v))
for (_u, _v) in E:
if (v == _v):
break
else:
kv = key(v)
for (i, s) in enumerate(S):
ks = key(s)
if (kv > ks):
S.insert(i, v)
break
else:
S.append(v)
if E:
raise ValueError('cycle detected')
else:
return L
| [
"def",
"topological_sort",
"(",
"graph",
",",
"key",
"=",
"None",
")",
":",
"(",
"V",
",",
"E",
")",
"=",
"graph",
"L",
"=",
"[",
"]",
"S",
"=",
"set",
"(",
"V",
")",
"E",
"=",
"list",
"(",
"E",
")",
"for",
"(",
"v",
",",
"u",
")",
"in",
"E",
":",
"S",
".",
"discard",
"(",
"u",
")",
"if",
"(",
"key",
"is",
"None",
")",
":",
"key",
"=",
"(",
"lambda",
"value",
":",
"value",
")",
"S",
"=",
"sorted",
"(",
"S",
",",
"key",
"=",
"key",
",",
"reverse",
"=",
"True",
")",
"while",
"S",
":",
"node",
"=",
"S",
".",
"pop",
"(",
")",
"L",
".",
"append",
"(",
"node",
")",
"for",
"(",
"u",
",",
"v",
")",
"in",
"list",
"(",
"E",
")",
":",
"if",
"(",
"u",
"==",
"node",
")",
":",
"E",
".",
"remove",
"(",
"(",
"u",
",",
"v",
")",
")",
"for",
"(",
"_u",
",",
"_v",
")",
"in",
"E",
":",
"if",
"(",
"v",
"==",
"_v",
")",
":",
"break",
"else",
":",
"kv",
"=",
"key",
"(",
"v",
")",
"for",
"(",
"i",
",",
"s",
")",
"in",
"enumerate",
"(",
"S",
")",
":",
"ks",
"=",
"key",
"(",
"s",
")",
"if",
"(",
"kv",
">",
"ks",
")",
":",
"S",
".",
"insert",
"(",
"i",
",",
"v",
")",
"break",
"else",
":",
"S",
".",
"append",
"(",
"v",
")",
"if",
"E",
":",
"raise",
"ValueError",
"(",
"'cycle detected'",
")",
"else",
":",
"return",
"L"
] | returns a depth first sorted order if depth_first is true . | train | false |
14,429 | @login_required
def edxnotes(request, course_id):
course_key = CourseKey.from_string(course_id)
course = get_course_with_access(request.user, 'load', course_key)
if (not is_feature_enabled(course)):
raise Http404
notes_info = get_notes(request, course)
has_notes = (len(notes_info.get('results')) > 0)
context = {'course': course, 'notes_endpoint': reverse('notes', kwargs={'course_id': course_id}), 'notes': notes_info, 'page_size': DEFAULT_PAGE_SIZE, 'debug': settings.DEBUG, 'position': None, 'disabled_tabs': settings.NOTES_DISABLED_TABS, 'has_notes': has_notes}
if (not has_notes):
field_data_cache = FieldDataCache.cache_for_descriptor_descendents(course.id, request.user, course, depth=2)
course_module = get_module_for_descriptor(request.user, request, course, field_data_cache, course_key, course=course)
position = get_course_position(course_module)
if position:
context.update({'position': position})
return render_to_response('edxnotes/edxnotes.html', context)
| [
"@",
"login_required",
"def",
"edxnotes",
"(",
"request",
",",
"course_id",
")",
":",
"course_key",
"=",
"CourseKey",
".",
"from_string",
"(",
"course_id",
")",
"course",
"=",
"get_course_with_access",
"(",
"request",
".",
"user",
",",
"'load'",
",",
"course_key",
")",
"if",
"(",
"not",
"is_feature_enabled",
"(",
"course",
")",
")",
":",
"raise",
"Http404",
"notes_info",
"=",
"get_notes",
"(",
"request",
",",
"course",
")",
"has_notes",
"=",
"(",
"len",
"(",
"notes_info",
".",
"get",
"(",
"'results'",
")",
")",
">",
"0",
")",
"context",
"=",
"{",
"'course'",
":",
"course",
",",
"'notes_endpoint'",
":",
"reverse",
"(",
"'notes'",
",",
"kwargs",
"=",
"{",
"'course_id'",
":",
"course_id",
"}",
")",
",",
"'notes'",
":",
"notes_info",
",",
"'page_size'",
":",
"DEFAULT_PAGE_SIZE",
",",
"'debug'",
":",
"settings",
".",
"DEBUG",
",",
"'position'",
":",
"None",
",",
"'disabled_tabs'",
":",
"settings",
".",
"NOTES_DISABLED_TABS",
",",
"'has_notes'",
":",
"has_notes",
"}",
"if",
"(",
"not",
"has_notes",
")",
":",
"field_data_cache",
"=",
"FieldDataCache",
".",
"cache_for_descriptor_descendents",
"(",
"course",
".",
"id",
",",
"request",
".",
"user",
",",
"course",
",",
"depth",
"=",
"2",
")",
"course_module",
"=",
"get_module_for_descriptor",
"(",
"request",
".",
"user",
",",
"request",
",",
"course",
",",
"field_data_cache",
",",
"course_key",
",",
"course",
"=",
"course",
")",
"position",
"=",
"get_course_position",
"(",
"course_module",
")",
"if",
"position",
":",
"context",
".",
"update",
"(",
"{",
"'position'",
":",
"position",
"}",
")",
"return",
"render_to_response",
"(",
"'edxnotes/edxnotes.html'",
",",
"context",
")"
] | decorator that makes components annotatable . | train | false |
14,431 | def get_num_cpus():
return multiprocessing.cpu_count()
| [
"def",
"get_num_cpus",
"(",
")",
":",
"return",
"multiprocessing",
".",
"cpu_count",
"(",
")"
] | get the number of cpu processes on the current machine . | train | false |
14,432 | def isProfileSetting(name):
global settingsDictionary
if ((name in settingsDictionary) and settingsDictionary[name].isProfile()):
return True
return False
| [
"def",
"isProfileSetting",
"(",
"name",
")",
":",
"global",
"settingsDictionary",
"if",
"(",
"(",
"name",
"in",
"settingsDictionary",
")",
"and",
"settingsDictionary",
"[",
"name",
"]",
".",
"isProfile",
"(",
")",
")",
":",
"return",
"True",
"return",
"False"
] | check if a certain key name is actually a profile value . | train | false |
14,433 | def SizeToReadableString(filesize):
for x in ['bytes', 'KiB', 'MiB', 'GiB', 'TiB']:
if (filesize < 1000.0):
return ('%3.1f %s' % (filesize, x))
filesize /= 1000.0
| [
"def",
"SizeToReadableString",
"(",
"filesize",
")",
":",
"for",
"x",
"in",
"[",
"'bytes'",
",",
"'KiB'",
",",
"'MiB'",
",",
"'GiB'",
",",
"'TiB'",
"]",
":",
"if",
"(",
"filesize",
"<",
"1000.0",
")",
":",
"return",
"(",
"'%3.1f %s'",
"%",
"(",
"filesize",
",",
"x",
")",
")",
"filesize",
"/=",
"1000.0"
] | turn a filesize int into a human readable filesize . | train | false |
14,434 | def _make_query(client, query, submission_type='Execute', udfs=None, settings=None, resources=[], wait=False, name=None, desc=None, local=True, is_parameterized=True, max=30.0, database='default', email_notify=False, **kwargs):
res = make_query(client, query, submission_type, udfs, settings, resources, wait, name, desc, local, is_parameterized, max, database, email_notify, **kwargs)
if (submission_type == 'Execute'):
fragment = collapse_whitespace(smart_str(query[:20]))
verify_history(client, fragment=fragment)
return res
| [
"def",
"_make_query",
"(",
"client",
",",
"query",
",",
"submission_type",
"=",
"'Execute'",
",",
"udfs",
"=",
"None",
",",
"settings",
"=",
"None",
",",
"resources",
"=",
"[",
"]",
",",
"wait",
"=",
"False",
",",
"name",
"=",
"None",
",",
"desc",
"=",
"None",
",",
"local",
"=",
"True",
",",
"is_parameterized",
"=",
"True",
",",
"max",
"=",
"30.0",
",",
"database",
"=",
"'default'",
",",
"email_notify",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"res",
"=",
"make_query",
"(",
"client",
",",
"query",
",",
"submission_type",
",",
"udfs",
",",
"settings",
",",
"resources",
",",
"wait",
",",
"name",
",",
"desc",
",",
"local",
",",
"is_parameterized",
",",
"max",
",",
"database",
",",
"email_notify",
",",
"**",
"kwargs",
")",
"if",
"(",
"submission_type",
"==",
"'Execute'",
")",
":",
"fragment",
"=",
"collapse_whitespace",
"(",
"smart_str",
"(",
"query",
"[",
":",
"20",
"]",
")",
")",
"verify_history",
"(",
"client",
",",
"fragment",
"=",
"fragment",
")",
"return",
"res"
] | wrapper around the real make_query . | train | false |
14,436 | def write_float(fid, kind, data):
data_size = 4
data = np.array(data, dtype='>f4').T
_write(fid, data, kind, data_size, FIFF.FIFFT_FLOAT, '>f4')
| [
"def",
"write_float",
"(",
"fid",
",",
"kind",
",",
"data",
")",
":",
"data_size",
"=",
"4",
"data",
"=",
"np",
".",
"array",
"(",
"data",
",",
"dtype",
"=",
"'>f4'",
")",
".",
"T",
"_write",
"(",
"fid",
",",
"data",
",",
"kind",
",",
"data_size",
",",
"FIFF",
".",
"FIFFT_FLOAT",
",",
"'>f4'",
")"
] | write a single-precision floating point tag to a fif file . | train | false |
14,439 | def downsize_quota_delta(context, instance):
old_flavor = instance.get_flavor('old')
new_flavor = instance.get_flavor('new')
return resize_quota_delta(context, new_flavor, old_flavor, 1, (-1))
| [
"def",
"downsize_quota_delta",
"(",
"context",
",",
"instance",
")",
":",
"old_flavor",
"=",
"instance",
".",
"get_flavor",
"(",
"'old'",
")",
"new_flavor",
"=",
"instance",
".",
"get_flavor",
"(",
"'new'",
")",
"return",
"resize_quota_delta",
"(",
"context",
",",
"new_flavor",
",",
"old_flavor",
",",
"1",
",",
"(",
"-",
"1",
")",
")"
] | calculate deltas required to adjust quota for an instance downsize . | train | false |
14,441 | def get_server_messages(app):
messages = []
for (basepath, folders, files) in os.walk(frappe.get_pymodule_path(app)):
for dontwalk in (u'.git', u'public', u'locale'):
if (dontwalk in folders):
folders.remove(dontwalk)
for f in files:
if (f.endswith(u'.py') or f.endswith(u'.html') or f.endswith(u'.js')):
messages.extend(get_messages_from_file(os.path.join(basepath, f)))
return messages
| [
"def",
"get_server_messages",
"(",
"app",
")",
":",
"messages",
"=",
"[",
"]",
"for",
"(",
"basepath",
",",
"folders",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"frappe",
".",
"get_pymodule_path",
"(",
"app",
")",
")",
":",
"for",
"dontwalk",
"in",
"(",
"u'.git'",
",",
"u'public'",
",",
"u'locale'",
")",
":",
"if",
"(",
"dontwalk",
"in",
"folders",
")",
":",
"folders",
".",
"remove",
"(",
"dontwalk",
")",
"for",
"f",
"in",
"files",
":",
"if",
"(",
"f",
".",
"endswith",
"(",
"u'.py'",
")",
"or",
"f",
".",
"endswith",
"(",
"u'.html'",
")",
"or",
"f",
".",
"endswith",
"(",
"u'.js'",
")",
")",
":",
"messages",
".",
"extend",
"(",
"get_messages_from_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"basepath",
",",
"f",
")",
")",
")",
"return",
"messages"
] | extracts all translatable strings from python modules inside an app . | train | false |
14,442 | def butter_lp(n, Wn):
zeros = []
poles = _butter_analog_poles(n)
k = 1
fs = 2
warped = ((2 * fs) * mpmath.tan(((mpmath.pi * Wn) / fs)))
(z, p, k) = _zpklp2lp(zeros, poles, k, wo=warped)
(z, p, k) = _zpkbilinear(z, p, k, fs=fs)
return (z, p, k)
| [
"def",
"butter_lp",
"(",
"n",
",",
"Wn",
")",
":",
"zeros",
"=",
"[",
"]",
"poles",
"=",
"_butter_analog_poles",
"(",
"n",
")",
"k",
"=",
"1",
"fs",
"=",
"2",
"warped",
"=",
"(",
"(",
"2",
"*",
"fs",
")",
"*",
"mpmath",
".",
"tan",
"(",
"(",
"(",
"mpmath",
".",
"pi",
"*",
"Wn",
")",
"/",
"fs",
")",
")",
")",
"(",
"z",
",",
"p",
",",
"k",
")",
"=",
"_zpklp2lp",
"(",
"zeros",
",",
"poles",
",",
"k",
",",
"wo",
"=",
"warped",
")",
"(",
"z",
",",
"p",
",",
"k",
")",
"=",
"_zpkbilinear",
"(",
"z",
",",
"p",
",",
"k",
",",
"fs",
"=",
"fs",
")",
"return",
"(",
"z",
",",
"p",
",",
"k",
")"
] | lowpass butterworth digital filter design . | train | false |
14,444 | def read_packed_refs_with_peeled(f):
last = None
for l in f:
if (l[0] == '#'):
continue
l = l.rstrip('\r\n')
if l.startswith('^'):
if (not last):
raise PackedRefsException('unexpected peeled ref line')
if (not valid_hexsha(l[1:])):
raise PackedRefsException(('Invalid hex sha %r' % l[1:]))
(sha, name) = _split_ref_line(last)
last = None
(yield (sha, name, l[1:]))
else:
if last:
(sha, name) = _split_ref_line(last)
(yield (sha, name, None))
last = l
if last:
(sha, name) = _split_ref_line(last)
(yield (sha, name, None))
| [
"def",
"read_packed_refs_with_peeled",
"(",
"f",
")",
":",
"last",
"=",
"None",
"for",
"l",
"in",
"f",
":",
"if",
"(",
"l",
"[",
"0",
"]",
"==",
"'#'",
")",
":",
"continue",
"l",
"=",
"l",
".",
"rstrip",
"(",
"'\\r\\n'",
")",
"if",
"l",
".",
"startswith",
"(",
"'^'",
")",
":",
"if",
"(",
"not",
"last",
")",
":",
"raise",
"PackedRefsException",
"(",
"'unexpected peeled ref line'",
")",
"if",
"(",
"not",
"valid_hexsha",
"(",
"l",
"[",
"1",
":",
"]",
")",
")",
":",
"raise",
"PackedRefsException",
"(",
"(",
"'Invalid hex sha %r'",
"%",
"l",
"[",
"1",
":",
"]",
")",
")",
"(",
"sha",
",",
"name",
")",
"=",
"_split_ref_line",
"(",
"last",
")",
"last",
"=",
"None",
"(",
"yield",
"(",
"sha",
",",
"name",
",",
"l",
"[",
"1",
":",
"]",
")",
")",
"else",
":",
"if",
"last",
":",
"(",
"sha",
",",
"name",
")",
"=",
"_split_ref_line",
"(",
"last",
")",
"(",
"yield",
"(",
"sha",
",",
"name",
",",
"None",
")",
")",
"last",
"=",
"l",
"if",
"last",
":",
"(",
"sha",
",",
"name",
")",
"=",
"_split_ref_line",
"(",
"last",
")",
"(",
"yield",
"(",
"sha",
",",
"name",
",",
"None",
")",
")"
] | read a packed refs file including peeled refs . | train | false |
14,445 | def is_hex_digits(entry, count):
try:
if (len(entry) != count):
return False
int(entry, 16)
return True
except (ValueError, TypeError):
return False
| [
"def",
"is_hex_digits",
"(",
"entry",
",",
"count",
")",
":",
"try",
":",
"if",
"(",
"len",
"(",
"entry",
")",
"!=",
"count",
")",
":",
"return",
"False",
"int",
"(",
"entry",
",",
"16",
")",
"return",
"True",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"False"
] | checks if a string is the given number of hex digits . | train | false |
14,446 | def dmp_degree(f, u):
if dmp_zero_p(f, u):
return (- oo)
else:
return (len(f) - 1)
| [
"def",
"dmp_degree",
"(",
"f",
",",
"u",
")",
":",
"if",
"dmp_zero_p",
"(",
"f",
",",
"u",
")",
":",
"return",
"(",
"-",
"oo",
")",
"else",
":",
"return",
"(",
"len",
"(",
"f",
")",
"-",
"1",
")"
] | return the leading degree of f in x_0 in k[x] . | train | false |
14,447 | def MakeCASignedCert(common_name, private_key, ca_cert, ca_private_key, serial_number=2):
public_key = private_key.GetPublicKey()
builder = x509.CertificateBuilder()
builder = builder.issuer_name(ca_cert.GetIssuer())
subject = x509.Name([x509.NameAttribute(oid.NameOID.COMMON_NAME, common_name)])
builder = builder.subject_name(subject)
valid_from = (rdfvalue.RDFDatetime.Now() - rdfvalue.Duration('1d'))
valid_until = (rdfvalue.RDFDatetime.Now() + rdfvalue.Duration('3650d'))
builder = builder.not_valid_before(valid_from.AsDatetime())
builder = builder.not_valid_after(valid_until.AsDatetime())
builder = builder.serial_number(serial_number)
builder = builder.public_key(public_key.GetRawPublicKey())
builder = builder.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
certificate = builder.sign(private_key=ca_private_key.GetRawPrivateKey(), algorithm=hashes.SHA256(), backend=openssl.backend)
return rdf_crypto.RDFX509Cert(certificate)
| [
"def",
"MakeCASignedCert",
"(",
"common_name",
",",
"private_key",
",",
"ca_cert",
",",
"ca_private_key",
",",
"serial_number",
"=",
"2",
")",
":",
"public_key",
"=",
"private_key",
".",
"GetPublicKey",
"(",
")",
"builder",
"=",
"x509",
".",
"CertificateBuilder",
"(",
")",
"builder",
"=",
"builder",
".",
"issuer_name",
"(",
"ca_cert",
".",
"GetIssuer",
"(",
")",
")",
"subject",
"=",
"x509",
".",
"Name",
"(",
"[",
"x509",
".",
"NameAttribute",
"(",
"oid",
".",
"NameOID",
".",
"COMMON_NAME",
",",
"common_name",
")",
"]",
")",
"builder",
"=",
"builder",
".",
"subject_name",
"(",
"subject",
")",
"valid_from",
"=",
"(",
"rdfvalue",
".",
"RDFDatetime",
".",
"Now",
"(",
")",
"-",
"rdfvalue",
".",
"Duration",
"(",
"'1d'",
")",
")",
"valid_until",
"=",
"(",
"rdfvalue",
".",
"RDFDatetime",
".",
"Now",
"(",
")",
"+",
"rdfvalue",
".",
"Duration",
"(",
"'3650d'",
")",
")",
"builder",
"=",
"builder",
".",
"not_valid_before",
"(",
"valid_from",
".",
"AsDatetime",
"(",
")",
")",
"builder",
"=",
"builder",
".",
"not_valid_after",
"(",
"valid_until",
".",
"AsDatetime",
"(",
")",
")",
"builder",
"=",
"builder",
".",
"serial_number",
"(",
"serial_number",
")",
"builder",
"=",
"builder",
".",
"public_key",
"(",
"public_key",
".",
"GetRawPublicKey",
"(",
")",
")",
"builder",
"=",
"builder",
".",
"add_extension",
"(",
"x509",
".",
"BasicConstraints",
"(",
"ca",
"=",
"False",
",",
"path_length",
"=",
"None",
")",
",",
"critical",
"=",
"True",
")",
"certificate",
"=",
"builder",
".",
"sign",
"(",
"private_key",
"=",
"ca_private_key",
".",
"GetRawPrivateKey",
"(",
")",
",",
"algorithm",
"=",
"hashes",
".",
"SHA256",
"(",
")",
",",
"backend",
"=",
"openssl",
".",
"backend",
")",
"return",
"rdf_crypto",
".",
"RDFX509Cert",
"(",
"certificate",
")"
] | make a cert and sign it with the cas private key . | train | true |
14,448 | @pytest.mark.network
def test_install_with_ignoreinstalled_requested(script):
script.pip('install', 'INITools==0.1', expect_error=True)
result = script.pip('install', '-I', 'INITools==0.3', expect_error=True)
assert result.files_created, 'pip install -I did not install'
assert os.path.exists(((script.site_packages_path / 'INITools-0.1-py%s.egg-info') % pyversion))
assert os.path.exists(((script.site_packages_path / 'INITools-0.3-py%s.egg-info') % pyversion))
| [
"@",
"pytest",
".",
"mark",
".",
"network",
"def",
"test_install_with_ignoreinstalled_requested",
"(",
"script",
")",
":",
"script",
".",
"pip",
"(",
"'install'",
",",
"'INITools==0.1'",
",",
"expect_error",
"=",
"True",
")",
"result",
"=",
"script",
".",
"pip",
"(",
"'install'",
",",
"'-I'",
",",
"'INITools==0.3'",
",",
"expect_error",
"=",
"True",
")",
"assert",
"result",
".",
"files_created",
",",
"'pip install -I did not install'",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"(",
"(",
"script",
".",
"site_packages_path",
"/",
"'INITools-0.1-py%s.egg-info'",
")",
"%",
"pyversion",
")",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"(",
"(",
"script",
".",
"site_packages_path",
"/",
"'INITools-0.3-py%s.egg-info'",
")",
"%",
"pyversion",
")",
")"
] | test old conflicting package is completely ignored . | train | false |
14,452 | def call_tadm(args):
if isinstance(args, compat.string_types):
raise TypeError(u'args should be a list of strings')
if (_tadm_bin is None):
config_tadm()
cmd = ([_tadm_bin] + args)
p = subprocess.Popen(cmd, stdout=sys.stdout)
(stdout, stderr) = p.communicate()
if (p.returncode != 0):
print()
print(stderr)
raise OSError(u'tadm command failed!')
| [
"def",
"call_tadm",
"(",
"args",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"compat",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"u'args should be a list of strings'",
")",
"if",
"(",
"_tadm_bin",
"is",
"None",
")",
":",
"config_tadm",
"(",
")",
"cmd",
"=",
"(",
"[",
"_tadm_bin",
"]",
"+",
"args",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"sys",
".",
"stdout",
")",
"(",
"stdout",
",",
"stderr",
")",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"(",
"p",
".",
"returncode",
"!=",
"0",
")",
":",
"print",
"(",
")",
"print",
"(",
"stderr",
")",
"raise",
"OSError",
"(",
"u'tadm command failed!'",
")"
] | call the tadm binary with the given arguments . | train | false |
14,456 | def expm(A, q=None):
if (q is not None):
msg = 'argument q=... in scipy.linalg.expm is deprecated.'
warnings.warn(msg, DeprecationWarning)
import scipy.sparse.linalg
return scipy.sparse.linalg.expm(A)
| [
"def",
"expm",
"(",
"A",
",",
"q",
"=",
"None",
")",
":",
"if",
"(",
"q",
"is",
"not",
"None",
")",
":",
"msg",
"=",
"'argument q=... in scipy.linalg.expm is deprecated.'",
"warnings",
".",
"warn",
"(",
"msg",
",",
"DeprecationWarning",
")",
"import",
"scipy",
".",
"sparse",
".",
"linalg",
"return",
"scipy",
".",
"sparse",
".",
"linalg",
".",
"expm",
"(",
"A",
")"
] | compute the matrix exponential using pade approximation . | train | false |
14,457 | def setup_default_session(**kwargs):
global DEFAULT_SESSION
DEFAULT_SESSION = Session(**kwargs)
| [
"def",
"setup_default_session",
"(",
"**",
"kwargs",
")",
":",
"global",
"DEFAULT_SESSION",
"DEFAULT_SESSION",
"=",
"Session",
"(",
"**",
"kwargs",
")"
] | set up a default session . | train | false |
14,458 | def displayFiles(filenames):
for filename in filenames:
displayFile(filename)
| [
"def",
"displayFiles",
"(",
"filenames",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"displayFile",
"(",
"filename",
")"
] | parse gcode files and display the commands . | train | false |
14,461 | def can_create_more(data):
data = dict(data)
user = data['user']
course_key = data['usage_key'].course_key
if (Bookmark.objects.filter(user=user, course_key=course_key).count() >= settings.MAX_BOOKMARKS_PER_COURSE):
return False
return True
| [
"def",
"can_create_more",
"(",
"data",
")",
":",
"data",
"=",
"dict",
"(",
"data",
")",
"user",
"=",
"data",
"[",
"'user'",
"]",
"course_key",
"=",
"data",
"[",
"'usage_key'",
"]",
".",
"course_key",
"if",
"(",
"Bookmark",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"user",
",",
"course_key",
"=",
"course_key",
")",
".",
"count",
"(",
")",
">=",
"settings",
".",
"MAX_BOOKMARKS_PER_COURSE",
")",
":",
"return",
"False",
"return",
"True"
] | determine if a new bookmark can be created for the course based on limit defined in django . | train | false |
14,462 | def plat_specific_errors(*errnames):
errno_names = dir(errno)
nums = [getattr(errno, k) for k in errnames if (k in errno_names)]
return list(dict.fromkeys(nums).keys())
| [
"def",
"plat_specific_errors",
"(",
"*",
"errnames",
")",
":",
"errno_names",
"=",
"dir",
"(",
"errno",
")",
"nums",
"=",
"[",
"getattr",
"(",
"errno",
",",
"k",
")",
"for",
"k",
"in",
"errnames",
"if",
"(",
"k",
"in",
"errno_names",
")",
"]",
"return",
"list",
"(",
"dict",
".",
"fromkeys",
"(",
"nums",
")",
".",
"keys",
"(",
")",
")"
] | return error numbers for all errors in errnames on this platform . | train | true |
14,463 | def assert_table_name_col_equal(t, name, col):
if isinstance(col, coordinates.SkyCoord):
assert np.all((t[name].ra == col.ra))
assert np.all((t[name].dec == col.dec))
elif isinstance(col, u.Quantity):
if (type(t) is QTable):
assert np.all((t[name].value == col.value))
elif isinstance(col, table_helpers.ArrayWrapper):
assert np.all((t[name].data == col.data))
else:
assert np.all((t[name] == col))
| [
"def",
"assert_table_name_col_equal",
"(",
"t",
",",
"name",
",",
"col",
")",
":",
"if",
"isinstance",
"(",
"col",
",",
"coordinates",
".",
"SkyCoord",
")",
":",
"assert",
"np",
".",
"all",
"(",
"(",
"t",
"[",
"name",
"]",
".",
"ra",
"==",
"col",
".",
"ra",
")",
")",
"assert",
"np",
".",
"all",
"(",
"(",
"t",
"[",
"name",
"]",
".",
"dec",
"==",
"col",
".",
"dec",
")",
")",
"elif",
"isinstance",
"(",
"col",
",",
"u",
".",
"Quantity",
")",
":",
"if",
"(",
"type",
"(",
"t",
")",
"is",
"QTable",
")",
":",
"assert",
"np",
".",
"all",
"(",
"(",
"t",
"[",
"name",
"]",
".",
"value",
"==",
"col",
".",
"value",
")",
")",
"elif",
"isinstance",
"(",
"col",
",",
"table_helpers",
".",
"ArrayWrapper",
")",
":",
"assert",
"np",
".",
"all",
"(",
"(",
"t",
"[",
"name",
"]",
".",
"data",
"==",
"col",
".",
"data",
")",
")",
"else",
":",
"assert",
"np",
".",
"all",
"(",
"(",
"t",
"[",
"name",
"]",
"==",
"col",
")",
")"
] | assert all . | train | false |
14,465 | def get_email_backend(real_email=False):
if (real_email or settings.SEND_REAL_EMAIL):
backend = None
else:
backend = 'olympia.amo.mail.DevEmailBackend'
return django.core.mail.get_connection(backend)
| [
"def",
"get_email_backend",
"(",
"real_email",
"=",
"False",
")",
":",
"if",
"(",
"real_email",
"or",
"settings",
".",
"SEND_REAL_EMAIL",
")",
":",
"backend",
"=",
"None",
"else",
":",
"backend",
"=",
"'olympia.amo.mail.DevEmailBackend'",
"return",
"django",
".",
"core",
".",
"mail",
".",
"get_connection",
"(",
"backend",
")"
] | get a connection to an email backend . | train | false |
14,466 | def _doc_link(rawtext, text, options={}, content=[]):
(has_explicit_title, title, slug) = split_explicit_title(text)
twin_slugs = False
post = None
for p in doc_role.site.timeline:
if (p.meta('slug') == slug):
if (post is None):
post = p
else:
twin_slugs = True
break
try:
if (post is None):
raise ValueError
except ValueError:
return (False, False, None, None, slug)
if (not has_explicit_title):
title = post.title()
permalink = post.permalink()
return (True, twin_slugs, title, permalink, slug)
| [
"def",
"_doc_link",
"(",
"rawtext",
",",
"text",
",",
"options",
"=",
"{",
"}",
",",
"content",
"=",
"[",
"]",
")",
":",
"(",
"has_explicit_title",
",",
"title",
",",
"slug",
")",
"=",
"split_explicit_title",
"(",
"text",
")",
"twin_slugs",
"=",
"False",
"post",
"=",
"None",
"for",
"p",
"in",
"doc_role",
".",
"site",
".",
"timeline",
":",
"if",
"(",
"p",
".",
"meta",
"(",
"'slug'",
")",
"==",
"slug",
")",
":",
"if",
"(",
"post",
"is",
"None",
")",
":",
"post",
"=",
"p",
"else",
":",
"twin_slugs",
"=",
"True",
"break",
"try",
":",
"if",
"(",
"post",
"is",
"None",
")",
":",
"raise",
"ValueError",
"except",
"ValueError",
":",
"return",
"(",
"False",
",",
"False",
",",
"None",
",",
"None",
",",
"slug",
")",
"if",
"(",
"not",
"has_explicit_title",
")",
":",
"title",
"=",
"post",
".",
"title",
"(",
")",
"permalink",
"=",
"post",
".",
"permalink",
"(",
")",
"return",
"(",
"True",
",",
"twin_slugs",
",",
"title",
",",
"permalink",
",",
"slug",
")"
] | handle the doc role . | train | false |
14,467 | def rich_text_publisher(registry, xml_parent, data):
parsers = ['HTML', 'Confluence', 'WikiText']
reporter = XML.SubElement(xml_parent, 'org.korosoft.jenkins.plugin.rtp.RichTextPublisher')
reporter.set('plugin', 'rich-text-publisher-plugin')
mappings = [('stable-text', 'stableText', None), ('unstable-text', 'unstableText', ''), ('failed-text', 'failedText', ''), ('unstable-as-stable', 'unstableAsStable', True), ('failed-as-stable', 'failedAsStable', True), ('parser-name', 'parserName', 'WikiText', parsers)]
helpers.convert_mapping_to_xml(reporter, data, mappings, fail_required=True)
| [
"def",
"rich_text_publisher",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"parsers",
"=",
"[",
"'HTML'",
",",
"'Confluence'",
",",
"'WikiText'",
"]",
"reporter",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'org.korosoft.jenkins.plugin.rtp.RichTextPublisher'",
")",
"reporter",
".",
"set",
"(",
"'plugin'",
",",
"'rich-text-publisher-plugin'",
")",
"mappings",
"=",
"[",
"(",
"'stable-text'",
",",
"'stableText'",
",",
"None",
")",
",",
"(",
"'unstable-text'",
",",
"'unstableText'",
",",
"''",
")",
",",
"(",
"'failed-text'",
",",
"'failedText'",
",",
"''",
")",
",",
"(",
"'unstable-as-stable'",
",",
"'unstableAsStable'",
",",
"True",
")",
",",
"(",
"'failed-as-stable'",
",",
"'failedAsStable'",
",",
"True",
")",
",",
"(",
"'parser-name'",
",",
"'parserName'",
",",
"'WikiText'",
",",
"parsers",
")",
"]",
"helpers",
".",
"convert_mapping_to_xml",
"(",
"reporter",
",",
"data",
",",
"mappings",
",",
"fail_required",
"=",
"True",
")"
] | yaml: rich-text-publisher this plugin puts custom rich text message to the build pages and job main page . | train | false |
14,468 | def mplot2d(f, var, show=True):
import warnings
warnings.filterwarnings('ignore', 'Could not match \\S')
p = import_module('pylab')
if (not p):
sys.exit('Matplotlib is required to use mplot2d.')
if (not is_sequence(f)):
f = [f]
for f_i in f:
(x, y) = sample(f_i, var)
p.plot(x, y)
p.draw()
if show:
p.show()
| [
"def",
"mplot2d",
"(",
"f",
",",
"var",
",",
"show",
"=",
"True",
")",
":",
"import",
"warnings",
"warnings",
".",
"filterwarnings",
"(",
"'ignore'",
",",
"'Could not match \\\\S'",
")",
"p",
"=",
"import_module",
"(",
"'pylab'",
")",
"if",
"(",
"not",
"p",
")",
":",
"sys",
".",
"exit",
"(",
"'Matplotlib is required to use mplot2d.'",
")",
"if",
"(",
"not",
"is_sequence",
"(",
"f",
")",
")",
":",
"f",
"=",
"[",
"f",
"]",
"for",
"f_i",
"in",
"f",
":",
"(",
"x",
",",
"y",
")",
"=",
"sample",
"(",
"f_i",
",",
"var",
")",
"p",
".",
"plot",
"(",
"x",
",",
"y",
")",
"p",
".",
"draw",
"(",
")",
"if",
"show",
":",
"p",
".",
"show",
"(",
")"
] | plot a 2d function using matplotlib/tk . | train | false |
14,469 | @pytest.fixture
def po_directory(request, po_test_dir, settings):
from pootle_store.models import fs
translation_directory = settings.POOTLE_TRANSLATION_DIRECTORY
settings.POOTLE_TRANSLATION_DIRECTORY = po_test_dir
fs.location = po_test_dir
def _cleanup():
settings.POOTLE_TRANSLATION_DIRECTORY = translation_directory
request.addfinalizer(_cleanup)
| [
"@",
"pytest",
".",
"fixture",
"def",
"po_directory",
"(",
"request",
",",
"po_test_dir",
",",
"settings",
")",
":",
"from",
"pootle_store",
".",
"models",
"import",
"fs",
"translation_directory",
"=",
"settings",
".",
"POOTLE_TRANSLATION_DIRECTORY",
"settings",
".",
"POOTLE_TRANSLATION_DIRECTORY",
"=",
"po_test_dir",
"fs",
".",
"location",
"=",
"po_test_dir",
"def",
"_cleanup",
"(",
")",
":",
"settings",
".",
"POOTLE_TRANSLATION_DIRECTORY",
"=",
"translation_directory",
"request",
".",
"addfinalizer",
"(",
"_cleanup",
")"
] | sets up a tmp directory for po files . | train | false |
14,471 | def customConvertJson(value):
if isinstance(value, float):
return int(value)
elif isinstance(value, unicode):
return str(value)
elif isinstance(value, list):
return [customConvertJson(item) for item in value]
elif isinstance(value, dict):
new_dict = {}
for (key, val) in value.iteritems():
new_key = customConvertJson(key)
new_val = customConvertJson(val)
new_dict[new_key] = new_val
return new_dict
else:
return value
| [
"def",
"customConvertJson",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"return",
"int",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"[",
"customConvertJson",
"(",
"item",
")",
"for",
"item",
"in",
"value",
"]",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"(",
"key",
",",
"val",
")",
"in",
"value",
".",
"iteritems",
"(",
")",
":",
"new_key",
"=",
"customConvertJson",
"(",
"key",
")",
"new_val",
"=",
"customConvertJson",
"(",
"val",
")",
"new_dict",
"[",
"new_key",
"]",
"=",
"new_val",
"return",
"new_dict",
"else",
":",
"return",
"value"
] | recursively process json values and do type conversions . | train | false |
14,472 | @utils.arg('flavor', metavar='<flavor>', help=_('Name or ID of flavor.'))
def do_flavor_show(cs, args):
flavor = _find_flavor(cs, args.flavor)
_print_flavor(flavor)
| [
"@",
"utils",
".",
"arg",
"(",
"'flavor'",
",",
"metavar",
"=",
"'<flavor>'",
",",
"help",
"=",
"_",
"(",
"'Name or ID of flavor.'",
")",
")",
"def",
"do_flavor_show",
"(",
"cs",
",",
"args",
")",
":",
"flavor",
"=",
"_find_flavor",
"(",
"cs",
",",
"args",
".",
"flavor",
")",
"_print_flavor",
"(",
"flavor",
")"
] | show details about the given flavor . | train | false |
14,474 | def idd_diffsnorm(m, n, matvect, matvect2, matvec, matvec2, its=20):
return _id.idd_diffsnorm(m, n, matvect, matvect2, matvec, matvec2, its)
| [
"def",
"idd_diffsnorm",
"(",
"m",
",",
"n",
",",
"matvect",
",",
"matvect2",
",",
"matvec",
",",
"matvec2",
",",
"its",
"=",
"20",
")",
":",
"return",
"_id",
".",
"idd_diffsnorm",
"(",
"m",
",",
"n",
",",
"matvect",
",",
"matvect2",
",",
"matvec",
",",
"matvec2",
",",
"its",
")"
] | estimate spectral norm of the difference of two real matrices by the randomized power method . | train | false |
14,475 | def encrypt_header_val(crypto, value, key):
if (not value):
raise ValueError('empty value is not acceptable')
crypto_meta = crypto.create_crypto_meta()
crypto_ctxt = crypto.create_encryption_ctxt(key, crypto_meta['iv'])
enc_val = base64.b64encode(crypto_ctxt.update(value))
return (enc_val, crypto_meta)
| [
"def",
"encrypt_header_val",
"(",
"crypto",
",",
"value",
",",
"key",
")",
":",
"if",
"(",
"not",
"value",
")",
":",
"raise",
"ValueError",
"(",
"'empty value is not acceptable'",
")",
"crypto_meta",
"=",
"crypto",
".",
"create_crypto_meta",
"(",
")",
"crypto_ctxt",
"=",
"crypto",
".",
"create_encryption_ctxt",
"(",
"key",
",",
"crypto_meta",
"[",
"'iv'",
"]",
")",
"enc_val",
"=",
"base64",
".",
"b64encode",
"(",
"crypto_ctxt",
".",
"update",
"(",
"value",
")",
")",
"return",
"(",
"enc_val",
",",
"crypto_meta",
")"
] | encrypt a header value using the supplied key . | train | false |
14,476 | def authen():
twitter_credential = ((os.environ.get('HOME', os.environ.get('USERPROFILE', '')) + os.sep) + '.rainbow_oauth')
if (not os.path.exists(twitter_credential)):
oauth_dance('Rainbow Stream', CONSUMER_KEY, CONSUMER_SECRET, twitter_credential)
(oauth_token, oauth_token_secret) = read_token_file(twitter_credential)
return OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)
| [
"def",
"authen",
"(",
")",
":",
"twitter_credential",
"=",
"(",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'HOME'",
",",
"os",
".",
"environ",
".",
"get",
"(",
"'USERPROFILE'",
",",
"''",
")",
")",
"+",
"os",
".",
"sep",
")",
"+",
"'.rainbow_oauth'",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"twitter_credential",
")",
")",
":",
"oauth_dance",
"(",
"'Rainbow Stream'",
",",
"CONSUMER_KEY",
",",
"CONSUMER_SECRET",
",",
"twitter_credential",
")",
"(",
"oauth_token",
",",
"oauth_token_secret",
")",
"=",
"read_token_file",
"(",
"twitter_credential",
")",
"return",
"OAuth",
"(",
"oauth_token",
",",
"oauth_token_secret",
",",
"CONSUMER_KEY",
",",
"CONSUMER_SECRET",
")"
] | authenticate with twitter oauth . | train | false |
14,477 | def getUserDocumentsPath():
if sys.platform.startswith('win'):
if sys.platform.startswith('win32'):
try:
from win32com.shell import shell
alt = False
except ImportError:
try:
import ctypes
dll = ctypes.windll.shell32
alt = True
except:
raise Exception("Could not find 'My Documents'")
else:
alt = True
if (not alt):
df = shell.SHGetDesktopFolder()
pidl = df.ParseDisplayName(0, None, '::{450d8fba-ad25-11d0-98a8-0800361b1103}')[1]
path = shell.SHGetPathFromIDList(pidl)
else:
buf = ctypes.create_string_buffer(300)
dll.SHGetSpecialFolderPathA(None, buf, 5, False)
path = buf.value
elif sys.platform.startswith('darwin'):
from Carbon import Folder, Folders
folderref = Folder.FSFindFolder(Folders.kUserDomain, Folders.kDocumentsFolderType, False)
path = folderref.as_pathname()
else:
path = os.getenv('HOME')
return path
| [
"def",
"getUserDocumentsPath",
"(",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win32'",
")",
":",
"try",
":",
"from",
"win32com",
".",
"shell",
"import",
"shell",
"alt",
"=",
"False",
"except",
"ImportError",
":",
"try",
":",
"import",
"ctypes",
"dll",
"=",
"ctypes",
".",
"windll",
".",
"shell32",
"alt",
"=",
"True",
"except",
":",
"raise",
"Exception",
"(",
"\"Could not find 'My Documents'\"",
")",
"else",
":",
"alt",
"=",
"True",
"if",
"(",
"not",
"alt",
")",
":",
"df",
"=",
"shell",
".",
"SHGetDesktopFolder",
"(",
")",
"pidl",
"=",
"df",
".",
"ParseDisplayName",
"(",
"0",
",",
"None",
",",
"'::{450d8fba-ad25-11d0-98a8-0800361b1103}'",
")",
"[",
"1",
"]",
"path",
"=",
"shell",
".",
"SHGetPathFromIDList",
"(",
"pidl",
")",
"else",
":",
"buf",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"300",
")",
"dll",
".",
"SHGetSpecialFolderPathA",
"(",
"None",
",",
"buf",
",",
"5",
",",
"False",
")",
"path",
"=",
"buf",
".",
"value",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'darwin'",
")",
":",
"from",
"Carbon",
"import",
"Folder",
",",
"Folders",
"folderref",
"=",
"Folder",
".",
"FSFindFolder",
"(",
"Folders",
".",
"kUserDomain",
",",
"Folders",
".",
"kDocumentsFolderType",
",",
"False",
")",
"path",
"=",
"folderref",
".",
"as_pathname",
"(",
")",
"else",
":",
"path",
"=",
"os",
".",
"getenv",
"(",
"'HOME'",
")",
"return",
"path"
] | find the users "documents" directory . | train | false |
14,480 | def checkAlias(alias):
if (',' in alias):
raise AXError(('Alias %r must not contain comma' % (alias,)))
if ('.' in alias):
raise AXError(('Alias %r must not contain period' % (alias,)))
| [
"def",
"checkAlias",
"(",
"alias",
")",
":",
"if",
"(",
"','",
"in",
"alias",
")",
":",
"raise",
"AXError",
"(",
"(",
"'Alias %r must not contain comma'",
"%",
"(",
"alias",
",",
")",
")",
")",
"if",
"(",
"'.'",
"in",
"alias",
")",
":",
"raise",
"AXError",
"(",
"(",
"'Alias %r must not contain period'",
"%",
"(",
"alias",
",",
")",
")",
")"
] | check an alias for invalid characters; raise axerror if any are found . | train | false |
14,481 | def _preprocess_for_cut(x):
x_is_series = isinstance(x, Series)
series_index = None
name = None
if x_is_series:
series_index = x.index
name = x.name
x = np.asarray(x)
return (x_is_series, series_index, name, x)
| [
"def",
"_preprocess_for_cut",
"(",
"x",
")",
":",
"x_is_series",
"=",
"isinstance",
"(",
"x",
",",
"Series",
")",
"series_index",
"=",
"None",
"name",
"=",
"None",
"if",
"x_is_series",
":",
"series_index",
"=",
"x",
".",
"index",
"name",
"=",
"x",
".",
"name",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"return",
"(",
"x_is_series",
",",
"series_index",
",",
"name",
",",
"x",
")"
] | handles preprocessing for cut where we convert passed input to array . | train | false |
14,483 | def GetAllClients(token=None):
index = client_index.CreateClientIndex(token=token)
return index.LookupClients(['.'])
| [
"def",
"GetAllClients",
"(",
"token",
"=",
"None",
")",
":",
"index",
"=",
"client_index",
".",
"CreateClientIndex",
"(",
"token",
"=",
"token",
")",
"return",
"index",
".",
"LookupClients",
"(",
"[",
"'.'",
"]",
")"
] | return a list of all client urns . | train | false |
14,484 | def gpke(bw, data, data_predict, var_type, ckertype='gaussian', okertype='wangryzin', ukertype='aitchisonaitken', tosum=True):
kertypes = dict(c=ckertype, o=okertype, u=ukertype)
Kval = np.empty(data.shape)
for (ii, vtype) in enumerate(var_type):
func = kernel_func[kertypes[vtype]]
Kval[:, ii] = func(bw[ii], data[:, ii], data_predict[ii])
iscontinuous = np.array([(c == 'c') for c in var_type])
dens = (Kval.prod(axis=1) / np.prod(bw[iscontinuous]))
if tosum:
return dens.sum(axis=0)
else:
return dens
| [
"def",
"gpke",
"(",
"bw",
",",
"data",
",",
"data_predict",
",",
"var_type",
",",
"ckertype",
"=",
"'gaussian'",
",",
"okertype",
"=",
"'wangryzin'",
",",
"ukertype",
"=",
"'aitchisonaitken'",
",",
"tosum",
"=",
"True",
")",
":",
"kertypes",
"=",
"dict",
"(",
"c",
"=",
"ckertype",
",",
"o",
"=",
"okertype",
",",
"u",
"=",
"ukertype",
")",
"Kval",
"=",
"np",
".",
"empty",
"(",
"data",
".",
"shape",
")",
"for",
"(",
"ii",
",",
"vtype",
")",
"in",
"enumerate",
"(",
"var_type",
")",
":",
"func",
"=",
"kernel_func",
"[",
"kertypes",
"[",
"vtype",
"]",
"]",
"Kval",
"[",
":",
",",
"ii",
"]",
"=",
"func",
"(",
"bw",
"[",
"ii",
"]",
",",
"data",
"[",
":",
",",
"ii",
"]",
",",
"data_predict",
"[",
"ii",
"]",
")",
"iscontinuous",
"=",
"np",
".",
"array",
"(",
"[",
"(",
"c",
"==",
"'c'",
")",
"for",
"c",
"in",
"var_type",
"]",
")",
"dens",
"=",
"(",
"Kval",
".",
"prod",
"(",
"axis",
"=",
"1",
")",
"/",
"np",
".",
"prod",
"(",
"bw",
"[",
"iscontinuous",
"]",
")",
")",
"if",
"tosum",
":",
"return",
"dens",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"else",
":",
"return",
"dens"
] | returns the non-normalized generalized product kernel estimator parameters bw: 1-d ndarray the user-specified bandwidth parameters . | train | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.