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
23,089
@transaction.non_atomic_requests @ensure_csrf_cookie @cache_control(no_cache=True, no_store=True, must_revalidate=True) @require_level('staff') def get_issued_certificates(request, course_id): course_key = CourseKey.from_string(course_id) csv_required = request.GET.get('csv', 'false') query_features = ['course_id', 'mode', 'total_issued_certificate', 'report_run_date'] query_features_names = [('course_id', _('CourseID')), ('mode', _('Certificate Type')), ('total_issued_certificate', _('Total Certificates Issued')), ('report_run_date', _('Date Report Run'))] certificates_data = instructor_analytics.basic.issued_certificates(course_key, query_features) if (csv_required.lower() == 'true'): (__, data_rows) = instructor_analytics.csvs.format_dictlist(certificates_data, query_features) return instructor_analytics.csvs.create_csv_response('issued_certificates.csv', [col_header for (__, col_header) in query_features_names], data_rows) else: response_payload = {'certificates': certificates_data, 'queried_features': query_features, 'feature_names': dict(query_features_names)} return JsonResponse(response_payload)
[ "@", "transaction", ".", "non_atomic_requests", "@", "ensure_csrf_cookie", "@", "cache_control", "(", "no_cache", "=", "True", ",", "no_store", "=", "True", ",", "must_revalidate", "=", "True", ")", "@", "require_level", "(", "'staff'", ")", "def", "get_issued_certificates", "(", "request", ",", "course_id", ")", ":", "course_key", "=", "CourseKey", ".", "from_string", "(", "course_id", ")", "csv_required", "=", "request", ".", "GET", ".", "get", "(", "'csv'", ",", "'false'", ")", "query_features", "=", "[", "'course_id'", ",", "'mode'", ",", "'total_issued_certificate'", ",", "'report_run_date'", "]", "query_features_names", "=", "[", "(", "'course_id'", ",", "_", "(", "'CourseID'", ")", ")", ",", "(", "'mode'", ",", "_", "(", "'Certificate Type'", ")", ")", ",", "(", "'total_issued_certificate'", ",", "_", "(", "'Total Certificates Issued'", ")", ")", ",", "(", "'report_run_date'", ",", "_", "(", "'Date Report Run'", ")", ")", "]", "certificates_data", "=", "instructor_analytics", ".", "basic", ".", "issued_certificates", "(", "course_key", ",", "query_features", ")", "if", "(", "csv_required", ".", "lower", "(", ")", "==", "'true'", ")", ":", "(", "__", ",", "data_rows", ")", "=", "instructor_analytics", ".", "csvs", ".", "format_dictlist", "(", "certificates_data", ",", "query_features", ")", "return", "instructor_analytics", ".", "csvs", ".", "create_csv_response", "(", "'issued_certificates.csv'", ",", "[", "col_header", "for", "(", "__", ",", "col_header", ")", "in", "query_features_names", "]", ",", "data_rows", ")", "else", ":", "response_payload", "=", "{", "'certificates'", ":", "certificates_data", ",", "'queried_features'", ":", "query_features", ",", "'feature_names'", ":", "dict", "(", "query_features_names", ")", "}", "return", "JsonResponse", "(", "response_payload", ")" ]
responds with json if csv is not required .
train
false
23,090
def try_coerce_ascii(string_utf8): try: string_utf8.decode('ascii') except UnicodeDecodeError: return return string_utf8
[ "def", "try_coerce_ascii", "(", "string_utf8", ")", ":", "try", ":", "string_utf8", ".", "decode", "(", "'ascii'", ")", "except", "UnicodeDecodeError", ":", "return", "return", "string_utf8" ]
attempts to decode the given utf8-encoded string as ascii after coercing it to utf-8 .
train
false
23,091
def organization_activity_list_html(context, data_dict): activity_stream = organization_activity_list(context, data_dict) offset = int(data_dict.get('offset', 0)) extra_vars = {'controller': 'organization', 'action': 'activity', 'id': data_dict['id'], 'offset': offset} return activity_streams.activity_list_to_html(context, activity_stream, extra_vars)
[ "def", "organization_activity_list_html", "(", "context", ",", "data_dict", ")", ":", "activity_stream", "=", "organization_activity_list", "(", "context", ",", "data_dict", ")", "offset", "=", "int", "(", "data_dict", ".", "get", "(", "'offset'", ",", "0", ")", ")", "extra_vars", "=", "{", "'controller'", ":", "'organization'", ",", "'action'", ":", "'activity'", ",", "'id'", ":", "data_dict", "[", "'id'", "]", ",", "'offset'", ":", "offset", "}", "return", "activity_streams", ".", "activity_list_to_html", "(", "context", ",", "activity_stream", ",", "extra_vars", ")" ]
return a organizations activity stream as html .
train
false
23,092
def _urllib2Opener(): debugMsg = 'creating HTTP requests opener object' logger.debug(debugMsg) handlers = [proxyHandler, authHandler, redirectHandler, rangeHandler, httpsHandler] if (not conf.dropSetCookie): if (not conf.loadCookies): conf.cj = cookielib.CookieJar() else: conf.cj = cookielib.MozillaCookieJar() resetCookieJar(conf.cj) handlers.append(urllib2.HTTPCookieProcessor(conf.cj)) if conf.keepAlive: warnMsg = 'persistent HTTP(s) connections, Keep-Alive, has ' warnMsg += 'been disabled because of its incompatibility ' if conf.proxy: warnMsg += 'with HTTP(s) proxy' logger.warn(warnMsg) elif conf.authType: warnMsg += 'with authentication methods' logger.warn(warnMsg) else: handlers.append(keepAliveHandler) opener = urllib2.build_opener(*handlers) urllib2.install_opener(opener)
[ "def", "_urllib2Opener", "(", ")", ":", "debugMsg", "=", "'creating HTTP requests opener object'", "logger", ".", "debug", "(", "debugMsg", ")", "handlers", "=", "[", "proxyHandler", ",", "authHandler", ",", "redirectHandler", ",", "rangeHandler", ",", "httpsHandler", "]", "if", "(", "not", "conf", ".", "dropSetCookie", ")", ":", "if", "(", "not", "conf", ".", "loadCookies", ")", ":", "conf", ".", "cj", "=", "cookielib", ".", "CookieJar", "(", ")", "else", ":", "conf", ".", "cj", "=", "cookielib", ".", "MozillaCookieJar", "(", ")", "resetCookieJar", "(", "conf", ".", "cj", ")", "handlers", ".", "append", "(", "urllib2", ".", "HTTPCookieProcessor", "(", "conf", ".", "cj", ")", ")", "if", "conf", ".", "keepAlive", ":", "warnMsg", "=", "'persistent HTTP(s) connections, Keep-Alive, has '", "warnMsg", "+=", "'been disabled because of its incompatibility '", "if", "conf", ".", "proxy", ":", "warnMsg", "+=", "'with HTTP(s) proxy'", "logger", ".", "warn", "(", "warnMsg", ")", "elif", "conf", ".", "authType", ":", "warnMsg", "+=", "'with authentication methods'", "logger", ".", "warn", "(", "warnMsg", ")", "else", ":", "handlers", ".", "append", "(", "keepAliveHandler", ")", "opener", "=", "urllib2", ".", "build_opener", "(", "*", "handlers", ")", "urllib2", ".", "install_opener", "(", "opener", ")" ]
this function creates the urllib2 openerdirector .
train
false
23,093
def _AddToDependencyMap(names): curName = names[0] _topLevelNames.add(curName) for name in names[1:]: _dependencyMap.setdefault(curName, set()).add(name) curName = '.'.join([curName, name])
[ "def", "_AddToDependencyMap", "(", "names", ")", ":", "curName", "=", "names", "[", "0", "]", "_topLevelNames", ".", "add", "(", "curName", ")", "for", "name", "in", "names", "[", "1", ":", "]", ":", "_dependencyMap", ".", "setdefault", "(", "curName", ",", "set", "(", ")", ")", ".", "add", "(", "name", ")", "curName", "=", "'.'", ".", "join", "(", "[", "curName", ",", "name", "]", ")" ]
note: must be holding the _lazylock .
train
true
23,095
def get_database_size(): db_name = frappe.conf.db_name db_size = frappe.db.sql(u'\n DCTB DCTB SELECT table_schema "database_name", sum( data_length + index_length ) / 1024 / 1024 "database_size"\n DCTB DCTB FROM information_schema.TABLES WHERE table_schema = %s GROUP BY table_schema', db_name, as_dict=True) return flt(db_size[0].get(u'database_size'), 2)
[ "def", "get_database_size", "(", ")", ":", "db_name", "=", "frappe", ".", "conf", ".", "db_name", "db_size", "=", "frappe", ".", "db", ".", "sql", "(", "u'\\n DCTB DCTB SELECT table_schema \"database_name\", sum( data_length + index_length ) / 1024 / 1024 \"database_size\"\\n DCTB DCTB FROM information_schema.TABLES WHERE table_schema = %s GROUP BY table_schema'", ",", "db_name", ",", "as_dict", "=", "True", ")", "return", "flt", "(", "db_size", "[", "0", "]", ".", "get", "(", "u'database_size'", ")", ",", "2", ")" ]
returns approximate database size in mb .
train
false
23,096
def _generateMetricSpecString(inferenceElement, metric, params=None, field=None, returnLabel=False): metricSpecArgs = dict(metric=metric, field=field, params=params, inferenceElement=inferenceElement) metricSpecAsString = ('MetricSpec(%s)' % ', '.join([('%s=%r' % (item[0], item[1])) for item in metricSpecArgs.iteritems()])) if (not returnLabel): return metricSpecAsString spec = MetricSpec(**metricSpecArgs) metricLabel = spec.getLabel() return (metricSpecAsString, metricLabel)
[ "def", "_generateMetricSpecString", "(", "inferenceElement", ",", "metric", ",", "params", "=", "None", ",", "field", "=", "None", ",", "returnLabel", "=", "False", ")", ":", "metricSpecArgs", "=", "dict", "(", "metric", "=", "metric", ",", "field", "=", "field", ",", "params", "=", "params", ",", "inferenceElement", "=", "inferenceElement", ")", "metricSpecAsString", "=", "(", "'MetricSpec(%s)'", "%", "', '", ".", "join", "(", "[", "(", "'%s=%r'", "%", "(", "item", "[", "0", "]", ",", "item", "[", "1", "]", ")", ")", "for", "item", "in", "metricSpecArgs", ".", "iteritems", "(", ")", "]", ")", ")", "if", "(", "not", "returnLabel", ")", ":", "return", "metricSpecAsString", "spec", "=", "MetricSpec", "(", "**", "metricSpecArgs", ")", "metricLabel", "=", "spec", ".", "getLabel", "(", ")", "return", "(", "metricSpecAsString", ",", "metricLabel", ")" ]
generates the string representation of a metricspec object .
train
true
23,097
def unscale_by_constant(builder, val, factor): return builder.sdiv(val, Constant.int(TIMEDELTA64, factor))
[ "def", "unscale_by_constant", "(", "builder", ",", "val", ",", "factor", ")", ":", "return", "builder", ".", "sdiv", "(", "val", ",", "Constant", ".", "int", "(", "TIMEDELTA64", ",", "factor", ")", ")" ]
divide *val* by the constant *factor* .
train
false
23,098
def get_jobconf(jt, jobid): jid = jt.thriftjobid_from_string(jobid) xml_data = jt.get_job_xml(jid) return confparse.ConfParse(xml_data)
[ "def", "get_jobconf", "(", "jt", ",", "jobid", ")", ":", "jid", "=", "jt", ".", "thriftjobid_from_string", "(", "jobid", ")", "xml_data", "=", "jt", ".", "get_job_xml", "(", "jid", ")", "return", "confparse", ".", "ConfParse", "(", "xml_data", ")" ]
returns a dict representation of the jobconf for the job corresponding to jobid .
train
false
23,099
@require_POST def ajax_disable(request): if (not request.user.is_authenticated()): raise PermissionDenied delete_user_preference(request.user, NOTIFICATION_PREF_KEY) return HttpResponse(status=204)
[ "@", "require_POST", "def", "ajax_disable", "(", "request", ")", ":", "if", "(", "not", "request", ".", "user", ".", "is_authenticated", "(", ")", ")", ":", "raise", "PermissionDenied", "delete_user_preference", "(", "request", ".", "user", ",", "NOTIFICATION_PREF_KEY", ")", "return", "HttpResponse", "(", "status", "=", "204", ")" ]
a view that disables notifications for the authenticated user this view should be invoked by an ajax post call .
train
false
23,100
def save_py_data_struct(filename, data): dirname = os.path.dirname(filename) if (not os.path.exists(dirname)): os.makedirs(dirname) if is_py2: import codecs f = codecs.open(filename, 'w', encoding='utf-8') else: f = open(filename, 'w', encoding='utf-8') with f: pprint.pprint(data, f)
[ "def", "save_py_data_struct", "(", "filename", ",", "data", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "if", "is_py2", ":", "import", "codecs", "f", "=", "codecs", ".", "open", "(", "filename", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "else", ":", "f", "=", "open", "(", "filename", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "with", "f", ":", "pprint", ".", "pprint", "(", "data", ",", "f", ")" ]
save data into text file as python data structure .
train
false
23,101
def test_record_mode_bad(): output = StringIO() recorder = Record(file_object=output, replay=False) record_mode = RecordMode(recorder) i = iscalar() f = function([i], i, mode=record_mode, name='f') num_lines = 10 for i in xrange(num_lines): recorder.handle_line((str(i) + '\n')) f(i) output_value = output.getvalue() output = StringIO(output_value) playback_checker = Record(file_object=output, replay=True) playback_mode = RecordMode(playback_checker) i = iscalar() f = function([i], i, mode=playback_mode, name='f') for i in xrange((num_lines // 2)): playback_checker.handle_line((str(i) + '\n')) f(i) try: f(0) except MismatchError: return raise AssertionError('Failed to detect a mismatch.')
[ "def", "test_record_mode_bad", "(", ")", ":", "output", "=", "StringIO", "(", ")", "recorder", "=", "Record", "(", "file_object", "=", "output", ",", "replay", "=", "False", ")", "record_mode", "=", "RecordMode", "(", "recorder", ")", "i", "=", "iscalar", "(", ")", "f", "=", "function", "(", "[", "i", "]", ",", "i", ",", "mode", "=", "record_mode", ",", "name", "=", "'f'", ")", "num_lines", "=", "10", "for", "i", "in", "xrange", "(", "num_lines", ")", ":", "recorder", ".", "handle_line", "(", "(", "str", "(", "i", ")", "+", "'\\n'", ")", ")", "f", "(", "i", ")", "output_value", "=", "output", ".", "getvalue", "(", ")", "output", "=", "StringIO", "(", "output_value", ")", "playback_checker", "=", "Record", "(", "file_object", "=", "output", ",", "replay", "=", "True", ")", "playback_mode", "=", "RecordMode", "(", "playback_checker", ")", "i", "=", "iscalar", "(", ")", "f", "=", "function", "(", "[", "i", "]", ",", "i", ",", "mode", "=", "playback_mode", ",", "name", "=", "'f'", ")", "for", "i", "in", "xrange", "(", "(", "num_lines", "//", "2", ")", ")", ":", "playback_checker", ".", "handle_line", "(", "(", "str", "(", "i", ")", "+", "'\\n'", ")", ")", "f", "(", "i", ")", "try", ":", "f", "(", "0", ")", "except", "MismatchError", ":", "return", "raise", "AssertionError", "(", "'Failed to detect a mismatch.'", ")" ]
like test_record_bad .
train
false
23,102
def realpath(filename): if isabs(filename): bits = (['/'] + filename.split('/')[1:]) else: bits = ([''] + filename.split('/')) for i in range(2, (len(bits) + 1)): component = join(*bits[0:i]) if islink(component): resolved = _resolve_link(component) if (resolved is None): return abspath(join(*([component] + bits[i:]))) else: newpath = join(*([resolved] + bits[i:])) return realpath(newpath) return abspath(filename)
[ "def", "realpath", "(", "filename", ")", ":", "if", "isabs", "(", "filename", ")", ":", "bits", "=", "(", "[", "'/'", "]", "+", "filename", ".", "split", "(", "'/'", ")", "[", "1", ":", "]", ")", "else", ":", "bits", "=", "(", "[", "''", "]", "+", "filename", ".", "split", "(", "'/'", ")", ")", "for", "i", "in", "range", "(", "2", ",", "(", "len", "(", "bits", ")", "+", "1", ")", ")", ":", "component", "=", "join", "(", "*", "bits", "[", "0", ":", "i", "]", ")", "if", "islink", "(", "component", ")", ":", "resolved", "=", "_resolve_link", "(", "component", ")", "if", "(", "resolved", "is", "None", ")", ":", "return", "abspath", "(", "join", "(", "*", "(", "[", "component", "]", "+", "bits", "[", "i", ":", "]", ")", ")", ")", "else", ":", "newpath", "=", "join", "(", "*", "(", "[", "resolved", "]", "+", "bits", "[", "i", ":", "]", ")", ")", "return", "realpath", "(", "newpath", ")", "return", "abspath", "(", "filename", ")" ]
return the canonical path of the specified filename .
train
false
23,103
def normalize_image(image): return ':'.join(get_split_image_tag(image))
[ "def", "normalize_image", "(", "image", ")", ":", "return", "':'", ".", "join", "(", "get_split_image_tag", "(", "image", ")", ")" ]
normalize a docker image name to include the implied :latest tag .
train
false
23,105
def test_multi(): multi_type = hug.types.multi(hug.types.json, hug.types.smart_boolean) assert (multi_type({'this': 'works'}) == {'this': 'works'}) assert (multi_type(json.dumps({'this': 'works'})) == {'this': 'works'}) assert multi_type('t') with pytest.raises(ValueError): multi_type('Bacon!')
[ "def", "test_multi", "(", ")", ":", "multi_type", "=", "hug", ".", "types", ".", "multi", "(", "hug", ".", "types", ".", "json", ",", "hug", ".", "types", ".", "smart_boolean", ")", "assert", "(", "multi_type", "(", "{", "'this'", ":", "'works'", "}", ")", "==", "{", "'this'", ":", "'works'", "}", ")", "assert", "(", "multi_type", "(", "json", ".", "dumps", "(", "{", "'this'", ":", "'works'", "}", ")", ")", "==", "{", "'this'", ":", "'works'", "}", ")", "assert", "multi_type", "(", "'t'", ")", "with", "pytest", ".", "raises", "(", "ValueError", ")", ":", "multi_type", "(", "'Bacon!'", ")" ]
test to ensure that the multi type correctly handles a variety of value types .
train
false
23,106
def _partial_fit_ovo_binary(estimator, X, y, i, j): cond = np.logical_or((y == i), (y == j)) y = y[cond] y_binary = np.zeros_like(y) y_binary[(y == j)] = 1 return _partial_fit_binary(estimator, X[cond], y_binary)
[ "def", "_partial_fit_ovo_binary", "(", "estimator", ",", "X", ",", "y", ",", "i", ",", "j", ")", ":", "cond", "=", "np", ".", "logical_or", "(", "(", "y", "==", "i", ")", ",", "(", "y", "==", "j", ")", ")", "y", "=", "y", "[", "cond", "]", "y_binary", "=", "np", ".", "zeros_like", "(", "y", ")", "y_binary", "[", "(", "y", "==", "j", ")", "]", "=", "1", "return", "_partial_fit_binary", "(", "estimator", ",", "X", "[", "cond", "]", ",", "y_binary", ")" ]
partially fit a single binary estimator .
train
false
23,108
def prepend_scheme_if_needed(url, new_scheme): (scheme, netloc, path, params, query, fragment) = urlparse(url, new_scheme) if (not netloc): (netloc, path) = (path, netloc) return urlunparse((scheme, netloc, path, params, query, fragment))
[ "def", "prepend_scheme_if_needed", "(", "url", ",", "new_scheme", ")", ":", "(", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", ")", "=", "urlparse", "(", "url", ",", "new_scheme", ")", "if", "(", "not", "netloc", ")", ":", "(", "netloc", ",", "path", ")", "=", "(", "path", ",", "netloc", ")", "return", "urlunparse", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", ")", ")" ]
given a url that may or may not have a scheme .
train
true
23,109
def websafe(val): if (val is None): return u'' if PY2: if isinstance(val, str): val = val.decode('utf-8') elif (not isinstance(val, unicode)): val = unicode(val) elif isinstance(val, bytes): val = val.decode('utf-8') elif (not isinstance(val, str)): val = str(val) return htmlquote(val)
[ "def", "websafe", "(", "val", ")", ":", "if", "(", "val", "is", "None", ")", ":", "return", "u''", "if", "PY2", ":", "if", "isinstance", "(", "val", ",", "str", ")", ":", "val", "=", "val", ".", "decode", "(", "'utf-8'", ")", "elif", "(", "not", "isinstance", "(", "val", ",", "unicode", ")", ")", ":", "val", "=", "unicode", "(", "val", ")", "elif", "isinstance", "(", "val", ",", "bytes", ")", ":", "val", "=", "val", ".", "decode", "(", "'utf-8'", ")", "elif", "(", "not", "isinstance", "(", "val", ",", "str", ")", ")", ":", "val", "=", "str", "(", "val", ")", "return", "htmlquote", "(", "val", ")" ]
converts val so that it is safe for use in unicode html .
train
false
23,111
def attr_eq(accessing_obj, accessed_obj, *args, **kwargs): return attr(accessing_obj, accessed_obj, *args, **kwargs)
[ "def", "attr_eq", "(", "accessing_obj", ",", "accessed_obj", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "attr", "(", "accessing_obj", ",", "accessed_obj", ",", "*", "args", ",", "**", "kwargs", ")" ]
usage: attr_gt .
train
false
23,112
def accept_connections_forever(listener): while True: (sock, address) = listener.accept() print 'Accepted connection from {}'.format(address) handle_conversation(sock, address)
[ "def", "accept_connections_forever", "(", "listener", ")", ":", "while", "True", ":", "(", "sock", ",", "address", ")", "=", "listener", ".", "accept", "(", ")", "print", "'Accepted connection from {}'", ".", "format", "(", "address", ")", "handle_conversation", "(", "sock", ",", "address", ")" ]
forever answer incoming connections on a listening socket .
train
false
23,113
def _weight_function(G, weight): if callable(weight): return weight if G.is_multigraph(): return (lambda u, v, d: min((attr.get(weight, 1) for attr in d.values()))) return (lambda u, v, data: data.get(weight, 1))
[ "def", "_weight_function", "(", "G", ",", "weight", ")", ":", "if", "callable", "(", "weight", ")", ":", "return", "weight", "if", "G", ".", "is_multigraph", "(", ")", ":", "return", "(", "lambda", "u", ",", "v", ",", "d", ":", "min", "(", "(", "attr", ".", "get", "(", "weight", ",", "1", ")", "for", "attr", "in", "d", ".", "values", "(", ")", ")", ")", ")", "return", "(", "lambda", "u", ",", "v", ",", "data", ":", "data", ".", "get", "(", "weight", ",", "1", ")", ")" ]
returns a function that returns the weight of an edge .
train
false
23,114
def create_https_certificates(ssl_cert, ssl_key): from headphones import logger from OpenSSL import crypto from certgen import createKeyPair, createCertRequest, createCertificate, TYPE_RSA, serial cakey = createKeyPair(TYPE_RSA, 2048) careq = createCertRequest(cakey, CN='Certificate Authority') cacert = createCertificate(careq, (careq, cakey), serial, (0, ((((60 * 60) * 24) * 365) * 10))) pkey = createKeyPair(TYPE_RSA, 2048) req = createCertRequest(pkey, CN='Headphones') cert = createCertificate(req, (cacert, cakey), serial, (0, ((((60 * 60) * 24) * 365) * 10))) try: with open(ssl_key, 'w') as fp: fp.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) with open(ssl_cert, 'w') as fp: fp.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) except IOError as e: logger.error('Error creating SSL key and certificate: %s', e) return False return True
[ "def", "create_https_certificates", "(", "ssl_cert", ",", "ssl_key", ")", ":", "from", "headphones", "import", "logger", "from", "OpenSSL", "import", "crypto", "from", "certgen", "import", "createKeyPair", ",", "createCertRequest", ",", "createCertificate", ",", "TYPE_RSA", ",", "serial", "cakey", "=", "createKeyPair", "(", "TYPE_RSA", ",", "2048", ")", "careq", "=", "createCertRequest", "(", "cakey", ",", "CN", "=", "'Certificate Authority'", ")", "cacert", "=", "createCertificate", "(", "careq", ",", "(", "careq", ",", "cakey", ")", ",", "serial", ",", "(", "0", ",", "(", "(", "(", "(", "60", "*", "60", ")", "*", "24", ")", "*", "365", ")", "*", "10", ")", ")", ")", "pkey", "=", "createKeyPair", "(", "TYPE_RSA", ",", "2048", ")", "req", "=", "createCertRequest", "(", "pkey", ",", "CN", "=", "'Headphones'", ")", "cert", "=", "createCertificate", "(", "req", ",", "(", "cacert", ",", "cakey", ")", ",", "serial", ",", "(", "0", ",", "(", "(", "(", "(", "60", "*", "60", ")", "*", "24", ")", "*", "365", ")", "*", "10", ")", ")", ")", "try", ":", "with", "open", "(", "ssl_key", ",", "'w'", ")", "as", "fp", ":", "fp", ".", "write", "(", "crypto", ".", "dump_privatekey", "(", "crypto", ".", "FILETYPE_PEM", ",", "pkey", ")", ")", "with", "open", "(", "ssl_cert", ",", "'w'", ")", "as", "fp", ":", "fp", ".", "write", "(", "crypto", ".", "dump_certificate", "(", "crypto", ".", "FILETYPE_PEM", ",", "cert", ")", ")", "except", "IOError", "as", "e", ":", "logger", ".", "error", "(", "'Error creating SSL key and certificate: %s'", ",", "e", ")", "return", "False", "return", "True" ]
create self-signed https certificates and store in paths ssl_cert and ssl_key .
train
false
23,115
def open_archive_entry(entry): arch = None try: archive_path = entry[u'location'] arch = archive.open_archive(archive_path) except KeyError: log.error(u'Entry does not appear to represent a local file.') except archive.BadArchive as error: fail_entry_with_error(entry, (u'Bad archive: %s (%s)' % (archive_path, error))) except archive.NeedFirstVolume: log.error(u'Not the first volume: %s', archive_path) except archive.ArchiveError as error: fail_entry_with_error(entry, (u'Failed to open Archive: %s (%s)' % (archive_path, error))) return arch
[ "def", "open_archive_entry", "(", "entry", ")", ":", "arch", "=", "None", "try", ":", "archive_path", "=", "entry", "[", "u'location'", "]", "arch", "=", "archive", ".", "open_archive", "(", "archive_path", ")", "except", "KeyError", ":", "log", ".", "error", "(", "u'Entry does not appear to represent a local file.'", ")", "except", "archive", ".", "BadArchive", "as", "error", ":", "fail_entry_with_error", "(", "entry", ",", "(", "u'Bad archive: %s (%s)'", "%", "(", "archive_path", ",", "error", ")", ")", ")", "except", "archive", ".", "NeedFirstVolume", ":", "log", ".", "error", "(", "u'Not the first volume: %s'", ",", "archive_path", ")", "except", "archive", ".", "ArchiveError", "as", "error", ":", "fail_entry_with_error", "(", "entry", ",", "(", "u'Failed to open Archive: %s (%s)'", "%", "(", "archive_path", ",", "error", ")", ")", ")", "return", "arch" ]
convenience method for opening archives from entries .
train
false
23,116
def get_public_ip_block(module, driver, network_domain, block_id=False, base_ip=False): if (block_id is not False): try: block = driver.ex_get_public_ip_block(block_id) except DimensionDataAPIException: e = get_exception() if ((e.code == 'RESOURCE_NOT_FOUND') or (e.code == 'UNEXPECTED_ERROR')): module.exit_json(changed=False, msg='Public IP Block does not exist') else: module.fail_json(msg=('Unexpected error while retrieving block: %s' % e.code)) module.fail_json(msg=('Error retreving Public IP Block ' + ("'%s': %s" % (block.id, e.message)))) else: blocks = list_public_ip_blocks(module, driver, network_domain) if (blocks is not False): block = next((block for block in blocks if (block.base_ip == base_ip))) else: module.exit_json(changed=False, msg=("IP block starting with '%s' does not exist." % base_ip)) return block
[ "def", "get_public_ip_block", "(", "module", ",", "driver", ",", "network_domain", ",", "block_id", "=", "False", ",", "base_ip", "=", "False", ")", ":", "if", "(", "block_id", "is", "not", "False", ")", ":", "try", ":", "block", "=", "driver", ".", "ex_get_public_ip_block", "(", "block_id", ")", "except", "DimensionDataAPIException", ":", "e", "=", "get_exception", "(", ")", "if", "(", "(", "e", ".", "code", "==", "'RESOURCE_NOT_FOUND'", ")", "or", "(", "e", ".", "code", "==", "'UNEXPECTED_ERROR'", ")", ")", ":", "module", ".", "exit_json", "(", "changed", "=", "False", ",", "msg", "=", "'Public IP Block does not exist'", ")", "else", ":", "module", ".", "fail_json", "(", "msg", "=", "(", "'Unexpected error while retrieving block: %s'", "%", "e", ".", "code", ")", ")", "module", ".", "fail_json", "(", "msg", "=", "(", "'Error retreving Public IP Block '", "+", "(", "\"'%s': %s\"", "%", "(", "block", ".", "id", ",", "e", ".", "message", ")", ")", ")", ")", "else", ":", "blocks", "=", "list_public_ip_blocks", "(", "module", ",", "driver", ",", "network_domain", ")", "if", "(", "blocks", "is", "not", "False", ")", ":", "block", "=", "next", "(", "(", "block", "for", "block", "in", "blocks", "if", "(", "block", ".", "base_ip", "==", "base_ip", ")", ")", ")", "else", ":", "module", ".", "exit_json", "(", "changed", "=", "False", ",", "msg", "=", "(", "\"IP block starting with '%s' does not exist.\"", "%", "base_ip", ")", ")", "return", "block" ]
get public ip block details .
train
false
23,117
def _configs_from_dir(conf_dir): for filename in sorted(os.listdir(conf_dir)): if (filename.startswith('.') or (not filename.endswith('.ini'))): continue LOG.debug(('Loading configuration from: %s' % filename)) try: conf = configobj.ConfigObj(os.path.join(conf_dir, filename)) except configobj.ConfigObjError as ex: LOG.error(("Error in configuration file '%s': %s" % (os.path.join(conf_dir, filename), ex))) raise conf['DEFAULT'] = dict(desktop_root=get_desktop_root(), build_dir=get_build_dir()) (yield conf)
[ "def", "_configs_from_dir", "(", "conf_dir", ")", ":", "for", "filename", "in", "sorted", "(", "os", ".", "listdir", "(", "conf_dir", ")", ")", ":", "if", "(", "filename", ".", "startswith", "(", "'.'", ")", "or", "(", "not", "filename", ".", "endswith", "(", "'.ini'", ")", ")", ")", ":", "continue", "LOG", ".", "debug", "(", "(", "'Loading configuration from: %s'", "%", "filename", ")", ")", "try", ":", "conf", "=", "configobj", ".", "ConfigObj", "(", "os", ".", "path", ".", "join", "(", "conf_dir", ",", "filename", ")", ")", "except", "configobj", ".", "ConfigObjError", "as", "ex", ":", "LOG", ".", "error", "(", "(", "\"Error in configuration file '%s': %s\"", "%", "(", "os", ".", "path", ".", "join", "(", "conf_dir", ",", "filename", ")", ",", "ex", ")", ")", ")", "raise", "conf", "[", "'DEFAULT'", "]", "=", "dict", "(", "desktop_root", "=", "get_desktop_root", "(", ")", ",", "build_dir", "=", "get_build_dir", "(", ")", ")", "(", "yield", "conf", ")" ]
generator to load configurations from a directory .
train
false
23,118
def assert_dicts_equal_ignoring_ordering(dict1, dict2): dicts = [copy.deepcopy(dict1), copy.deepcopy(dict2)] for d in dicts: d = change_lists_to_sets(d) assert_equal(dicts[0], dicts[1])
[ "def", "assert_dicts_equal_ignoring_ordering", "(", "dict1", ",", "dict2", ")", ":", "dicts", "=", "[", "copy", ".", "deepcopy", "(", "dict1", ")", ",", "copy", ".", "deepcopy", "(", "dict2", ")", "]", "for", "d", "in", "dicts", ":", "d", "=", "change_lists_to_sets", "(", "d", ")", "assert_equal", "(", "dicts", "[", "0", "]", ",", "dicts", "[", "1", "]", ")" ]
assert that dict1 and dict2 are equal .
train
false
23,125
def to_aware_utc_dt(dt): if (not isinstance(dt, datetime)): raise TypeError('Arg must be type datetime') if (dt.tzinfo is None): return pytz.utc.localize(dt) return dt.astimezone(pytz.utc)
[ "def", "to_aware_utc_dt", "(", "dt", ")", ":", "if", "(", "not", "isinstance", "(", "dt", ",", "datetime", ")", ")", ":", "raise", "TypeError", "(", "'Arg must be type datetime'", ")", "if", "(", "dt", ".", "tzinfo", "is", "None", ")", ":", "return", "pytz", ".", "utc", ".", "localize", "(", "dt", ")", "return", "dt", ".", "astimezone", "(", "pytz", ".", "utc", ")" ]
convert an inbound datetime into a timezone aware datetime in utc as follows: if inbound is naive .
train
false
23,127
@log_call def metadef_resource_type_create(context, values): global DATA resource_type_values = copy.deepcopy(values) resource_type_name = resource_type_values['name'] allowed_attrubites = ['name', 'protected'] for resource_type in DATA['metadef_resource_types']: if (resource_type['name'] == resource_type_name): raise exception.Duplicate() incorrect_keys = (set(resource_type_values.keys()) - set(allowed_attrubites)) if incorrect_keys: raise exception.Invalid(('The keys %s are not valid' % str(incorrect_keys))) resource_type = _format_resource_type(resource_type_values) DATA['metadef_resource_types'].append(resource_type) return resource_type
[ "@", "log_call", "def", "metadef_resource_type_create", "(", "context", ",", "values", ")", ":", "global", "DATA", "resource_type_values", "=", "copy", ".", "deepcopy", "(", "values", ")", "resource_type_name", "=", "resource_type_values", "[", "'name'", "]", "allowed_attrubites", "=", "[", "'name'", ",", "'protected'", "]", "for", "resource_type", "in", "DATA", "[", "'metadef_resource_types'", "]", ":", "if", "(", "resource_type", "[", "'name'", "]", "==", "resource_type_name", ")", ":", "raise", "exception", ".", "Duplicate", "(", ")", "incorrect_keys", "=", "(", "set", "(", "resource_type_values", ".", "keys", "(", ")", ")", "-", "set", "(", "allowed_attrubites", ")", ")", "if", "incorrect_keys", ":", "raise", "exception", ".", "Invalid", "(", "(", "'The keys %s are not valid'", "%", "str", "(", "incorrect_keys", ")", ")", ")", "resource_type", "=", "_format_resource_type", "(", "resource_type_values", ")", "DATA", "[", "'metadef_resource_types'", "]", ".", "append", "(", "resource_type", ")", "return", "resource_type" ]
create a resource_type .
train
false
23,128
def _get_release_date_from(xblock): return _xblock_type_and_display_name(find_release_date_source(xblock))
[ "def", "_get_release_date_from", "(", "xblock", ")", ":", "return", "_xblock_type_and_display_name", "(", "find_release_date_source", "(", "xblock", ")", ")" ]
returns a string representation of the section or subsection that sets the xblocks release date .
train
false
23,129
def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id
[ "def", "_get_resource_id", "(", "resource", ",", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "_id", "=", "_cache_id", "(", "name", ",", "sub_resource", "=", "resource", ",", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "if", "_id", ":", "return", "_id", "r", "=", "_get_resource", "(", "resource", ",", "name", "=", "name", ",", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "if", "r", ":", "return", "r", ".", "id" ]
helper method to find the resource id .
train
true
23,130
def encode_point(point, point_format=0): pLen = len(binrepr(point.curve().p())) x = pkcs_i2osp(point.x(), math.ceil((pLen / 8))) y = pkcs_i2osp(point.y(), math.ceil((pLen / 8))) if (point_format == 0): frmt = '\x04' elif (point_format == 1): frmt = chr((2 + (y % 2))) y = '' else: raise Exception(('No support for point_format %d' % point_format)) return ((frmt + x) + y)
[ "def", "encode_point", "(", "point", ",", "point_format", "=", "0", ")", ":", "pLen", "=", "len", "(", "binrepr", "(", "point", ".", "curve", "(", ")", ".", "p", "(", ")", ")", ")", "x", "=", "pkcs_i2osp", "(", "point", ".", "x", "(", ")", ",", "math", ".", "ceil", "(", "(", "pLen", "/", "8", ")", ")", ")", "y", "=", "pkcs_i2osp", "(", "point", ".", "y", "(", ")", ",", "math", ".", "ceil", "(", "(", "pLen", "/", "8", ")", ")", ")", "if", "(", "point_format", "==", "0", ")", ":", "frmt", "=", "'\\x04'", "elif", "(", "point_format", "==", "1", ")", ":", "frmt", "=", "chr", "(", "(", "2", "+", "(", "y", "%", "2", ")", ")", ")", "y", "=", "''", "else", ":", "raise", "Exception", "(", "(", "'No support for point_format %d'", "%", "point_format", ")", ")", "return", "(", "(", "frmt", "+", "x", ")", "+", "y", ")" ]
return a string representation of the point p .
train
false
23,133
def get_mac_address(iface): proc = Popen(['ifconfig', iface], stdout=PIPE, stderr=DN) proc.wait() mac = '' first_line = proc.communicate()[0].split('\n')[0] for word in first_line.split(' '): if (word != ''): mac = word if (mac.find('-') != (-1)): mac = mac.replace('-', ':') if (len(mac) > 17): mac = mac[0:17] return mac
[ "def", "get_mac_address", "(", "iface", ")", ":", "proc", "=", "Popen", "(", "[", "'ifconfig'", ",", "iface", "]", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "DN", ")", "proc", ".", "wait", "(", ")", "mac", "=", "''", "first_line", "=", "proc", ".", "communicate", "(", ")", "[", "0", "]", ".", "split", "(", "'\\n'", ")", "[", "0", "]", "for", "word", "in", "first_line", ".", "split", "(", "' '", ")", ":", "if", "(", "word", "!=", "''", ")", ":", "mac", "=", "word", "if", "(", "mac", ".", "find", "(", "'-'", ")", "!=", "(", "-", "1", ")", ")", ":", "mac", "=", "mac", ".", "replace", "(", "'-'", ",", "':'", ")", "if", "(", "len", "(", "mac", ")", ">", "17", ")", ":", "mac", "=", "mac", "[", "0", ":", "17", "]", "return", "mac" ]
returns mac address of "iface" .
train
false
23,134
def _slow_calculate_normals(rr, tris): rr = rr.astype(np.float64) r1 = rr[tris[:, 0], :] r2 = rr[tris[:, 1], :] r3 = rr[tris[:, 2], :] tri_nn = np.cross((r2 - r1), (r3 - r1)) size = np.sqrt(np.sum((tri_nn * tri_nn), axis=1)) zidx = np.where((size == 0))[0] size[zidx] = 1.0 tri_nn /= size[:, np.newaxis] nn = np.zeros((len(rr), 3)) for (p, verts) in enumerate(tris): nn[verts] += tri_nn[p, :] size = np.sqrt(np.sum((nn * nn), axis=1)) size[(size == 0)] = 1.0 nn /= size[:, np.newaxis] return nn
[ "def", "_slow_calculate_normals", "(", "rr", ",", "tris", ")", ":", "rr", "=", "rr", ".", "astype", "(", "np", ".", "float64", ")", "r1", "=", "rr", "[", "tris", "[", ":", ",", "0", "]", ",", ":", "]", "r2", "=", "rr", "[", "tris", "[", ":", ",", "1", "]", ",", ":", "]", "r3", "=", "rr", "[", "tris", "[", ":", ",", "2", "]", ",", ":", "]", "tri_nn", "=", "np", ".", "cross", "(", "(", "r2", "-", "r1", ")", ",", "(", "r3", "-", "r1", ")", ")", "size", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "tri_nn", "*", "tri_nn", ")", ",", "axis", "=", "1", ")", ")", "zidx", "=", "np", ".", "where", "(", "(", "size", "==", "0", ")", ")", "[", "0", "]", "size", "[", "zidx", "]", "=", "1.0", "tri_nn", "/=", "size", "[", ":", ",", "np", ".", "newaxis", "]", "nn", "=", "np", ".", "zeros", "(", "(", "len", "(", "rr", ")", ",", "3", ")", ")", "for", "(", "p", ",", "verts", ")", "in", "enumerate", "(", "tris", ")", ":", "nn", "[", "verts", "]", "+=", "tri_nn", "[", "p", ",", ":", "]", "size", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "nn", "*", "nn", ")", ",", "axis", "=", "1", ")", ")", "size", "[", "(", "size", "==", "0", ")", "]", "=", "1.0", "nn", "/=", "size", "[", ":", ",", "np", ".", "newaxis", "]", "return", "nn" ]
efficiently compute vertex normals for triangulated surface .
train
false
23,136
def singleton(cls): instances = {} def getinstance(): if (cls not in instances): instances[cls] = cls() return instances[cls] return getinstance
[ "def", "singleton", "(", "cls", ")", ":", "instances", "=", "{", "}", "def", "getinstance", "(", ")", ":", "if", "(", "cls", "not", "in", "instances", ")", ":", "instances", "[", "cls", "]", "=", "cls", "(", ")", "return", "instances", "[", "cls", "]", "return", "getinstance" ]
simple wrapper for classes that should only have a single instance .
train
true
23,137
@contextmanager def extend_sys_path(*paths): _orig_sys_path = sys.path[:] sys.path.extend(paths) try: (yield) finally: sys.path = _orig_sys_path
[ "@", "contextmanager", "def", "extend_sys_path", "(", "*", "paths", ")", ":", "_orig_sys_path", "=", "sys", ".", "path", "[", ":", "]", "sys", ".", "path", ".", "extend", "(", "paths", ")", "try", ":", "(", "yield", ")", "finally", ":", "sys", ".", "path", "=", "_orig_sys_path" ]
context manager to temporarily add paths to sys .
train
false
23,138
def temporary_directory(parent_path=None): mkdtemp_args = {} if (parent_path is not None): mkdtemp_args['dir'] = parent_path.path return _TemporaryPath(path=FilePath(mkdtemp(**mkdtemp_args)))
[ "def", "temporary_directory", "(", "parent_path", "=", "None", ")", ":", "mkdtemp_args", "=", "{", "}", "if", "(", "parent_path", "is", "not", "None", ")", ":", "mkdtemp_args", "[", "'dir'", "]", "=", "parent_path", ".", "path", "return", "_TemporaryPath", "(", "path", "=", "FilePath", "(", "mkdtemp", "(", "**", "mkdtemp_args", ")", ")", ")" ]
require a temporary directory .
train
false
23,140
def ssl_options_to_context(ssl_options): if isinstance(ssl_options, dict): assert all(((k in _SSL_CONTEXT_KEYWORDS) for k in ssl_options)), ssl_options if ((not hasattr(ssl, 'SSLContext')) or isinstance(ssl_options, ssl.SSLContext)): return ssl_options context = ssl.SSLContext(ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23)) if ('certfile' in ssl_options): context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None)) if ('cert_reqs' in ssl_options): context.verify_mode = ssl_options['cert_reqs'] if ('ca_certs' in ssl_options): context.load_verify_locations(ssl_options['ca_certs']) if ('ciphers' in ssl_options): context.set_ciphers(ssl_options['ciphers']) if hasattr(ssl, 'OP_NO_COMPRESSION'): context.options |= ssl.OP_NO_COMPRESSION return context
[ "def", "ssl_options_to_context", "(", "ssl_options", ")", ":", "if", "isinstance", "(", "ssl_options", ",", "dict", ")", ":", "assert", "all", "(", "(", "(", "k", "in", "_SSL_CONTEXT_KEYWORDS", ")", "for", "k", "in", "ssl_options", ")", ")", ",", "ssl_options", "if", "(", "(", "not", "hasattr", "(", "ssl", ",", "'SSLContext'", ")", ")", "or", "isinstance", "(", "ssl_options", ",", "ssl", ".", "SSLContext", ")", ")", ":", "return", "ssl_options", "context", "=", "ssl", ".", "SSLContext", "(", "ssl_options", ".", "get", "(", "'ssl_version'", ",", "ssl", ".", "PROTOCOL_SSLv23", ")", ")", "if", "(", "'certfile'", "in", "ssl_options", ")", ":", "context", ".", "load_cert_chain", "(", "ssl_options", "[", "'certfile'", "]", ",", "ssl_options", ".", "get", "(", "'keyfile'", ",", "None", ")", ")", "if", "(", "'cert_reqs'", "in", "ssl_options", ")", ":", "context", ".", "verify_mode", "=", "ssl_options", "[", "'cert_reqs'", "]", "if", "(", "'ca_certs'", "in", "ssl_options", ")", ":", "context", ".", "load_verify_locations", "(", "ssl_options", "[", "'ca_certs'", "]", ")", "if", "(", "'ciphers'", "in", "ssl_options", ")", ":", "context", ".", "set_ciphers", "(", "ssl_options", "[", "'ciphers'", "]", ")", "if", "hasattr", "(", "ssl", ",", "'OP_NO_COMPRESSION'", ")", ":", "context", ".", "options", "|=", "ssl", ".", "OP_NO_COMPRESSION", "return", "context" ]
try to convert an ssl_options dictionary to an ~ssl .
train
true
23,142
def generate_session_id(secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()): secret_key = _ensure_bytes(secret_key) if signed: base_id = _get_random_string(secret_key=secret_key) return ((base_id + '-') + _signature(base_id, secret_key)) else: return _get_random_string(secret_key=secret_key)
[ "def", "generate_session_id", "(", "secret_key", "=", "settings", ".", "secret_key_bytes", "(", ")", ",", "signed", "=", "settings", ".", "sign_sessions", "(", ")", ")", ":", "secret_key", "=", "_ensure_bytes", "(", "secret_key", ")", "if", "signed", ":", "base_id", "=", "_get_random_string", "(", "secret_key", "=", "secret_key", ")", "return", "(", "(", "base_id", "+", "'-'", ")", "+", "_signature", "(", "base_id", ",", "secret_key", ")", ")", "else", ":", "return", "_get_random_string", "(", "secret_key", "=", "secret_key", ")" ]
generate a random session id .
train
true
23,144
def listdict2envdict(listdict): for key in listdict: if isinstance(listdict[key], list): listdict[key] = os.path.pathsep.join(listdict[key]) return listdict
[ "def", "listdict2envdict", "(", "listdict", ")", ":", "for", "key", "in", "listdict", ":", "if", "isinstance", "(", "listdict", "[", "key", "]", ",", "list", ")", ":", "listdict", "[", "key", "]", "=", "os", ".", "path", ".", "pathsep", ".", "join", "(", "listdict", "[", "key", "]", ")", "return", "listdict" ]
dict of lists --> dict .
train
true
23,146
def save_context(context): file_path = _get_context_filepath() content = format_to_http_prompt(context, excluded_options=EXCLUDED_OPTIONS) with io.open(file_path, 'w', encoding='utf-8') as f: f.write(content)
[ "def", "save_context", "(", "context", ")", ":", "file_path", "=", "_get_context_filepath", "(", ")", "content", "=", "format_to_http_prompt", "(", "context", ",", "excluded_options", "=", "EXCLUDED_OPTIONS", ")", "with", "io", ".", "open", "(", "file_path", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "content", ")" ]
save a context object to user data directory .
train
true
23,147
def yn_zeros(n, nt): return jnyn_zeros(n, nt)[2]
[ "def", "yn_zeros", "(", "n", ",", "nt", ")", ":", "return", "jnyn_zeros", "(", "n", ",", "nt", ")", "[", "2", "]" ]
compute zeros of integer-order bessel function yn(x) .
train
false
23,148
@jit(nopython=True, cache=True) def next_k_combination(x): u = (x & (- x)) v = (u + x) return (v + (((v ^ x) // u) >> 2))
[ "@", "jit", "(", "nopython", "=", "True", ",", "cache", "=", "True", ")", "def", "next_k_combination", "(", "x", ")", ":", "u", "=", "(", "x", "&", "(", "-", "x", ")", ")", "v", "=", "(", "u", "+", "x", ")", "return", "(", "v", "+", "(", "(", "(", "v", "^", "x", ")", "//", "u", ")", ">>", "2", ")", ")" ]
find the next k-combination .
train
false
23,150
def _get_api_url(): api_url = (__salt__['config.get']('mattermost.api_url') or __salt__['config.get']('mattermost:api_url')) if (not api_url): raise SaltInvocationError('No Mattermost API URL found') return api_url
[ "def", "_get_api_url", "(", ")", ":", "api_url", "=", "(", "__salt__", "[", "'config.get'", "]", "(", "'mattermost.api_url'", ")", "or", "__salt__", "[", "'config.get'", "]", "(", "'mattermost:api_url'", ")", ")", "if", "(", "not", "api_url", ")", ":", "raise", "SaltInvocationError", "(", "'No Mattermost API URL found'", ")", "return", "api_url" ]
retrieves and return the mattermosts configured api url :return: string: the api url string .
train
false
23,152
def find_triples(tokens, left_dependency_label='NSUBJ', head_part_of_speech='VERB', right_dependency_label='DOBJ'): for (head, token) in enumerate(tokens): if (token['partOfSpeech']['tag'] == head_part_of_speech): children = dependents(tokens, head) left_deps = [] right_deps = [] for child in children: child_token = tokens[child] child_dep_label = child_token['dependencyEdge']['label'] if (child_dep_label == left_dependency_label): left_deps.append(child) elif (child_dep_label == right_dependency_label): right_deps.append(child) for left_dep in left_deps: for right_dep in right_deps: (yield (left_dep, head, right_dep))
[ "def", "find_triples", "(", "tokens", ",", "left_dependency_label", "=", "'NSUBJ'", ",", "head_part_of_speech", "=", "'VERB'", ",", "right_dependency_label", "=", "'DOBJ'", ")", ":", "for", "(", "head", ",", "token", ")", "in", "enumerate", "(", "tokens", ")", ":", "if", "(", "token", "[", "'partOfSpeech'", "]", "[", "'tag'", "]", "==", "head_part_of_speech", ")", ":", "children", "=", "dependents", "(", "tokens", ",", "head", ")", "left_deps", "=", "[", "]", "right_deps", "=", "[", "]", "for", "child", "in", "children", ":", "child_token", "=", "tokens", "[", "child", "]", "child_dep_label", "=", "child_token", "[", "'dependencyEdge'", "]", "[", "'label'", "]", "if", "(", "child_dep_label", "==", "left_dependency_label", ")", ":", "left_deps", ".", "append", "(", "child", ")", "elif", "(", "child_dep_label", "==", "right_dependency_label", ")", ":", "right_deps", ".", "append", "(", "child", ")", "for", "left_dep", "in", "left_deps", ":", "for", "right_dep", "in", "right_deps", ":", "(", "yield", "(", "left_dep", ",", "head", ",", "right_dep", ")", ")" ]
generator function that searches the given tokens with the given part of speech tag .
train
false
23,153
def Gumbel(name, beta, mu): return rv(name, GumbelDistribution, (beta, mu))
[ "def", "Gumbel", "(", "name", ",", "beta", ",", "mu", ")", ":", "return", "rv", "(", "name", ",", "GumbelDistribution", ",", "(", "beta", ",", "mu", ")", ")" ]
create a continuous random variable with gumbel distribution .
train
false
23,154
def from_table(table, table_id=None): return tree.VOTableFile.from_table(table, table_id=table_id)
[ "def", "from_table", "(", "table", ",", "table_id", "=", "None", ")", ":", "return", "tree", ".", "VOTableFile", ".", "from_table", "(", "table", ",", "table_id", "=", "table_id", ")" ]
given an ~astropy .
train
false
23,156
def tensor4(name=None, dtype=None): if (dtype is None): dtype = config.floatX type = TensorType(dtype, (False, False, False, False)) return type(name)
[ "def", "tensor4", "(", "name", "=", "None", ",", "dtype", "=", "None", ")", ":", "if", "(", "dtype", "is", "None", ")", ":", "dtype", "=", "config", ".", "floatX", "type", "=", "TensorType", "(", "dtype", ",", "(", "False", ",", "False", ",", "False", ",", "False", ")", ")", "return", "type", "(", "name", ")" ]
return a symbolic 4-d variable .
train
false
23,159
def _iter_chunked(x0, x1, chunksize=4, inc=1): if (inc == 0): raise ValueError('Cannot increment by zero.') if (chunksize <= 0): raise ValueError(('Chunk size must be positive; got %s.' % chunksize)) s = (1 if (inc > 0) else (-1)) stepsize = abs((chunksize * inc)) x = x0 while (((x - x1) * inc) < 0): delta = min(stepsize, abs((x - x1))) step = (delta * s) supp = np.arange(x, (x + step), inc) x += step (yield supp)
[ "def", "_iter_chunked", "(", "x0", ",", "x1", ",", "chunksize", "=", "4", ",", "inc", "=", "1", ")", ":", "if", "(", "inc", "==", "0", ")", ":", "raise", "ValueError", "(", "'Cannot increment by zero.'", ")", "if", "(", "chunksize", "<=", "0", ")", ":", "raise", "ValueError", "(", "(", "'Chunk size must be positive; got %s.'", "%", "chunksize", ")", ")", "s", "=", "(", "1", "if", "(", "inc", ">", "0", ")", "else", "(", "-", "1", ")", ")", "stepsize", "=", "abs", "(", "(", "chunksize", "*", "inc", ")", ")", "x", "=", "x0", "while", "(", "(", "(", "x", "-", "x1", ")", "*", "inc", ")", "<", "0", ")", ":", "delta", "=", "min", "(", "stepsize", ",", "abs", "(", "(", "x", "-", "x1", ")", ")", ")", "step", "=", "(", "delta", "*", "s", ")", "supp", "=", "np", ".", "arange", "(", "x", ",", "(", "x", "+", "step", ")", ",", "inc", ")", "x", "+=", "step", "(", "yield", "supp", ")" ]
iterate from x0 to x1 in chunks of chunksize and steps inc .
train
false
23,160
def _has_access_location(user, action, location, course_key): checkers = {'staff': (lambda : _has_staff_access_to_location(user, location, course_key))} return _dispatch(checkers, action, user, location)
[ "def", "_has_access_location", "(", "user", ",", "action", ",", "location", ",", "course_key", ")", ":", "checkers", "=", "{", "'staff'", ":", "(", "lambda", ":", "_has_staff_access_to_location", "(", "user", ",", "location", ",", "course_key", ")", ")", "}", "return", "_dispatch", "(", "checkers", ",", "action", ",", "user", ",", "location", ")" ]
check if user has access to this location .
train
false
23,162
def set_lcd_filter_weights(a, b, c, d, e): if (version() >= (2, 4, 0)): library = get_handle() weights = FT_Char(5)(a, b, c, d, e) error = FT_Library_SetLcdFilterWeights(library, weights) if error: raise FT_Exception(error) else: raise RuntimeError, 'set_lcd_filter_weights require freetype > 2.4.0'
[ "def", "set_lcd_filter_weights", "(", "a", ",", "b", ",", "c", ",", "d", ",", "e", ")", ":", "if", "(", "version", "(", ")", ">=", "(", "2", ",", "4", ",", "0", ")", ")", ":", "library", "=", "get_handle", "(", ")", "weights", "=", "FT_Char", "(", "5", ")", "(", "a", ",", "b", ",", "c", ",", "d", ",", "e", ")", "error", "=", "FT_Library_SetLcdFilterWeights", "(", "library", ",", "weights", ")", "if", "error", ":", "raise", "FT_Exception", "(", "error", ")", "else", ":", "raise", "RuntimeError", ",", "'set_lcd_filter_weights require freetype > 2.4.0'" ]
use this function to override the filter weights selected by ft_library_setlcdfilter .
train
false
23,163
def _create_gradient_image(size, color_from, color_to, rotation): rgb_arrays = [np.linspace(color_from[x], color_to[x], size).astype('uint8') for x in range(3)] gradient = np.concatenate(rgb_arrays) picture = np.repeat(gradient, size) picture.shape = (3, size, size) image = PIL.Image.fromarray(picture.T) image = image.rotate(rotation) return image
[ "def", "_create_gradient_image", "(", "size", ",", "color_from", ",", "color_to", ",", "rotation", ")", ":", "rgb_arrays", "=", "[", "np", ".", "linspace", "(", "color_from", "[", "x", "]", ",", "color_to", "[", "x", "]", ",", "size", ")", ".", "astype", "(", "'uint8'", ")", "for", "x", "in", "range", "(", "3", ")", "]", "gradient", "=", "np", ".", "concatenate", "(", "rgb_arrays", ")", "picture", "=", "np", ".", "repeat", "(", "gradient", ",", "size", ")", "picture", ".", "shape", "=", "(", "3", ",", "size", ",", "size", ")", "image", "=", "PIL", ".", "Image", ".", "fromarray", "(", "picture", ".", "T", ")", "image", "=", "image", ".", "rotate", "(", "rotation", ")", "return", "image" ]
make an image with a color gradient with a specific rotation .
train
false
23,165
def get_icon_url(base_url_format, obj, size, default_format='default-{size}.png'): if (not obj.icon_type): return '{path}/{name}'.format(path=static_url('ICONS_DEFAULT_URL'), name=default_format.format(size=size)) else: suffix = (obj.icon_hash or 'never') if storage_is_remote(): path = ('%s/%s-%s.png' % (obj.get_icon_dir(), obj.pk, size)) return ('%s?modified=%s' % (public_storage.url(path), suffix)) split_id = re.match('((\\d*?)\\d{1,3})$', str(obj.pk)) return (base_url_format % ((split_id.group(2) or 0), obj.pk, size, suffix))
[ "def", "get_icon_url", "(", "base_url_format", ",", "obj", ",", "size", ",", "default_format", "=", "'default-{size}.png'", ")", ":", "if", "(", "not", "obj", ".", "icon_type", ")", ":", "return", "'{path}/{name}'", ".", "format", "(", "path", "=", "static_url", "(", "'ICONS_DEFAULT_URL'", ")", ",", "name", "=", "default_format", ".", "format", "(", "size", "=", "size", ")", ")", "else", ":", "suffix", "=", "(", "obj", ".", "icon_hash", "or", "'never'", ")", "if", "storage_is_remote", "(", ")", ":", "path", "=", "(", "'%s/%s-%s.png'", "%", "(", "obj", ".", "get_icon_dir", "(", ")", ",", "obj", ".", "pk", ",", "size", ")", ")", "return", "(", "'%s?modified=%s'", "%", "(", "public_storage", ".", "url", "(", "path", ")", ",", "suffix", ")", ")", "split_id", "=", "re", ".", "match", "(", "'((\\\\d*?)\\\\d{1,3})$'", ",", "str", "(", "obj", ".", "pk", ")", ")", "return", "(", "base_url_format", "%", "(", "(", "split_id", ".", "group", "(", "2", ")", "or", "0", ")", ",", "obj", ".", "pk", ",", "size", ",", "suffix", ")", ")" ]
returns either the icon url for a given .
train
false
23,166
def lazify(dsk): return valmap(lazify_task, dsk)
[ "def", "lazify", "(", "dsk", ")", ":", "return", "valmap", "(", "lazify_task", ",", "dsk", ")" ]
remove unnecessary calls to list in tasks see also dask .
train
false
23,168
def enable_profiling(profile, signal, frame): profile.enable()
[ "def", "enable_profiling", "(", "profile", ",", "signal", ",", "frame", ")", ":", "profile", ".", "enable", "(", ")" ]
enable profiling of a flocker service .
train
false
23,170
def normalize_multiline(line): if (line.startswith(u'def ') and line.rstrip().endswith(u':')): return (line + u' pass') elif line.startswith(u'return '): return (u'def _(): ' + line) elif line.startswith(u'@'): return (line + u'def _(): pass') elif line.startswith(u'class '): return (line + u' pass') elif line.startswith((u'if ', u'elif ', u'for ', u'while ')): return (line + u' pass') else: return line
[ "def", "normalize_multiline", "(", "line", ")", ":", "if", "(", "line", ".", "startswith", "(", "u'def '", ")", "and", "line", ".", "rstrip", "(", ")", ".", "endswith", "(", "u':'", ")", ")", ":", "return", "(", "line", "+", "u' pass'", ")", "elif", "line", ".", "startswith", "(", "u'return '", ")", ":", "return", "(", "u'def _(): '", "+", "line", ")", "elif", "line", ".", "startswith", "(", "u'@'", ")", ":", "return", "(", "line", "+", "u'def _(): pass'", ")", "elif", "line", ".", "startswith", "(", "u'class '", ")", ":", "return", "(", "line", "+", "u' pass'", ")", "elif", "line", ".", "startswith", "(", "(", "u'if '", ",", "u'elif '", ",", "u'for '", ",", "u'while '", ")", ")", ":", "return", "(", "line", "+", "u' pass'", ")", "else", ":", "return", "line" ]
normalize multiline-related code that will cause syntax error .
train
false
23,172
def in6_ismlladdr(str): return in6_isincluded(str, 'ff02::', 16)
[ "def", "in6_ismlladdr", "(", "str", ")", ":", "return", "in6_isincluded", "(", "str", ",", "'ff02::'", ",", "16", ")" ]
returns true if address balongs to link-local multicast address space .
train
false
23,173
@with_environment def test_get_home_dir_3(): env['HOME'] = HOME_TEST_DIR home_dir = path.get_home_dir(True) nt.assert_equal(home_dir, os.path.realpath(env['HOME']))
[ "@", "with_environment", "def", "test_get_home_dir_3", "(", ")", ":", "env", "[", "'HOME'", "]", "=", "HOME_TEST_DIR", "home_dir", "=", "path", ".", "get_home_dir", "(", "True", ")", "nt", ".", "assert_equal", "(", "home_dir", ",", "os", ".", "path", ".", "realpath", "(", "env", "[", "'HOME'", "]", ")", ")" ]
get_home_dir() uses $home if set .
train
false
23,174
def openFile(filename, mode='r', encoding=UNICODE_ENCODING, errors='replace', buffering=1): try: return codecs.open(filename, mode, encoding, errors, buffering) except IOError: errMsg = ("there has been a file opening error for filename '%s'. " % filename) errMsg += ('Please check %s permissions on a file ' % ('write' if (mode and (('w' in mode) or ('a' in mode) or ('+' in mode))) else 'read')) errMsg += "and that it's not locked by another process." raise SqlmapSystemException(errMsg)
[ "def", "openFile", "(", "filename", ",", "mode", "=", "'r'", ",", "encoding", "=", "UNICODE_ENCODING", ",", "errors", "=", "'replace'", ",", "buffering", "=", "1", ")", ":", "try", ":", "return", "codecs", ".", "open", "(", "filename", ",", "mode", ",", "encoding", ",", "errors", ",", "buffering", ")", "except", "IOError", ":", "errMsg", "=", "(", "\"there has been a file opening error for filename '%s'. \"", "%", "filename", ")", "errMsg", "+=", "(", "'Please check %s permissions on a file '", "%", "(", "'write'", "if", "(", "mode", "and", "(", "(", "'w'", "in", "mode", ")", "or", "(", "'a'", "in", "mode", ")", "or", "(", "'+'", "in", "mode", ")", ")", ")", "else", "'read'", ")", ")", "errMsg", "+=", "\"and that it's not locked by another process.\"", "raise", "SqlmapSystemException", "(", "errMsg", ")" ]
returns file handle of a given filename .
train
false
23,175
def read_bin_lush_matrix(filepath): f = open(filepath, 'rb') try: magic = read_int(f) except ValueError: reraise_as("Couldn't read magic number") ndim = read_int(f) if (ndim == 0): shape = () else: shape = read_int(f, max(3, ndim)) total_elems = 1 for dim in shape: total_elems *= dim try: dtype = lush_magic[magic] except KeyError: reraise_as(ValueError(('Unrecognized lush magic number ' + str(magic)))) rval = np.fromfile(file=f, dtype=dtype, count=total_elems) excess = f.read((-1)) if excess: raise ValueError((str(len(excess)) + ' extra bytes found at end of file. This indicates mismatch between header and content')) rval = rval.reshape(*shape) f.close() return rval
[ "def", "read_bin_lush_matrix", "(", "filepath", ")", ":", "f", "=", "open", "(", "filepath", ",", "'rb'", ")", "try", ":", "magic", "=", "read_int", "(", "f", ")", "except", "ValueError", ":", "reraise_as", "(", "\"Couldn't read magic number\"", ")", "ndim", "=", "read_int", "(", "f", ")", "if", "(", "ndim", "==", "0", ")", ":", "shape", "=", "(", ")", "else", ":", "shape", "=", "read_int", "(", "f", ",", "max", "(", "3", ",", "ndim", ")", ")", "total_elems", "=", "1", "for", "dim", "in", "shape", ":", "total_elems", "*=", "dim", "try", ":", "dtype", "=", "lush_magic", "[", "magic", "]", "except", "KeyError", ":", "reraise_as", "(", "ValueError", "(", "(", "'Unrecognized lush magic number '", "+", "str", "(", "magic", ")", ")", ")", ")", "rval", "=", "np", ".", "fromfile", "(", "file", "=", "f", ",", "dtype", "=", "dtype", ",", "count", "=", "total_elems", ")", "excess", "=", "f", ".", "read", "(", "(", "-", "1", ")", ")", "if", "excess", ":", "raise", "ValueError", "(", "(", "str", "(", "len", "(", "excess", ")", ")", "+", "' extra bytes found at end of file. This indicates mismatch between header and content'", ")", ")", "rval", "=", "rval", ".", "reshape", "(", "*", "shape", ")", "f", ".", "close", "(", ")", "return", "rval" ]
reads a binary matrix saved by the lush library .
train
true
23,176
def print_tensor(x, message=''): p_op = Print(message) return p_op(x)
[ "def", "print_tensor", "(", "x", ",", "message", "=", "''", ")", ":", "p_op", "=", "Print", "(", "message", ")", "return", "p_op", "(", "x", ")" ]
print the message and the tensor when evaluated and return the same tensor .
train
false
23,177
@pytest.mark.django_db def test_delete_mark_obsolete(project0_nongnu, project0, store0): tp = TranslationProjectFactory(project=project0, language=LanguageDBFactory()) store = StoreDBFactory(translation_project=tp, parent=tp.directory) store.update(store.deserialize(store0.serialize())) store.sync() pootle_path = store.pootle_path os.remove(store.file.path) tp.scan_files() updated_store = Store.objects.get(pootle_path=pootle_path) assert updated_store.obsolete assert (not updated_store.units.exists()) assert updated_store.unit_set.filter(state=OBSOLETE).exists()
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_delete_mark_obsolete", "(", "project0_nongnu", ",", "project0", ",", "store0", ")", ":", "tp", "=", "TranslationProjectFactory", "(", "project", "=", "project0", ",", "language", "=", "LanguageDBFactory", "(", ")", ")", "store", "=", "StoreDBFactory", "(", "translation_project", "=", "tp", ",", "parent", "=", "tp", ".", "directory", ")", "store", ".", "update", "(", "store", ".", "deserialize", "(", "store0", ".", "serialize", "(", ")", ")", ")", "store", ".", "sync", "(", ")", "pootle_path", "=", "store", ".", "pootle_path", "os", ".", "remove", "(", "store", ".", "file", ".", "path", ")", "tp", ".", "scan_files", "(", ")", "updated_store", "=", "Store", ".", "objects", ".", "get", "(", "pootle_path", "=", "pootle_path", ")", "assert", "updated_store", ".", "obsolete", "assert", "(", "not", "updated_store", ".", "units", ".", "exists", "(", ")", ")", "assert", "updated_store", ".", "unit_set", ".", "filter", "(", "state", "=", "OBSOLETE", ")", ".", "exists", "(", ")" ]
tests that the in-db store and directory are marked as obsolete after the on-disk file ceased to exist .
train
false
23,178
@pytest.mark.network def test_download_editable_to_custom_path(script, tmpdir): script.scratch_path.join('customdl').mkdir() result = script.pip('install', '-e', ('%s#egg=initools-dev' % local_checkout('svn+http://svn.colorstudy.com/INITools/trunk', tmpdir.join('cache'))), '--src', 'customsrc', '--download', 'customdl', expect_stderr=True) customsrc = ((Path('scratch') / 'customsrc') / 'initools') assert (customsrc in result.files_created), sorted(result.files_created.keys()) assert ((customsrc / 'setup.py') in result.files_created), sorted(result.files_created.keys()) customdl = ((Path('scratch') / 'customdl') / 'initools') customdl_files_created = [filename for filename in result.files_created if filename.startswith(customdl)] assert customdl_files_created assert ('DEPRECATION: pip install --download has been deprecated and will be removed in the future. Pip now has a download command that should be used instead.' in result.stderr)
[ "@", "pytest", ".", "mark", ".", "network", "def", "test_download_editable_to_custom_path", "(", "script", ",", "tmpdir", ")", ":", "script", ".", "scratch_path", ".", "join", "(", "'customdl'", ")", ".", "mkdir", "(", ")", "result", "=", "script", ".", "pip", "(", "'install'", ",", "'-e'", ",", "(", "'%s#egg=initools-dev'", "%", "local_checkout", "(", "'svn+http://svn.colorstudy.com/INITools/trunk'", ",", "tmpdir", ".", "join", "(", "'cache'", ")", ")", ")", ",", "'--src'", ",", "'customsrc'", ",", "'--download'", ",", "'customdl'", ",", "expect_stderr", "=", "True", ")", "customsrc", "=", "(", "(", "Path", "(", "'scratch'", ")", "/", "'customsrc'", ")", "/", "'initools'", ")", "assert", "(", "customsrc", "in", "result", ".", "files_created", ")", ",", "sorted", "(", "result", ".", "files_created", ".", "keys", "(", ")", ")", "assert", "(", "(", "customsrc", "/", "'setup.py'", ")", "in", "result", ".", "files_created", ")", ",", "sorted", "(", "result", ".", "files_created", ".", "keys", "(", ")", ")", "customdl", "=", "(", "(", "Path", "(", "'scratch'", ")", "/", "'customdl'", ")", "/", "'initools'", ")", "customdl_files_created", "=", "[", "filename", "for", "filename", "in", "result", ".", "files_created", "if", "filename", ".", "startswith", "(", "customdl", ")", "]", "assert", "customdl_files_created", "assert", "(", "'DEPRECATION: pip install --download has been deprecated and will be removed in the future. Pip now has a download command that should be used instead.'", "in", "result", ".", "stderr", ")" ]
test downloading an editable using a relative custom src folder .
train
false
23,181
def is_square(n, prep=True): if prep: n = as_int(n) if (n < 0): return False if (n in [0, 1]): return True m = (n & 127) if (not (((m * 2344881533) & (m * 2716005841)) & 1311242)): m = (n % 63) if (not (((m * 1028201975) & (m * 3357846009)) & 284246024)): from sympy.ntheory import perfect_power if perfect_power(n, [2]): return True return False
[ "def", "is_square", "(", "n", ",", "prep", "=", "True", ")", ":", "if", "prep", ":", "n", "=", "as_int", "(", "n", ")", "if", "(", "n", "<", "0", ")", ":", "return", "False", "if", "(", "n", "in", "[", "0", ",", "1", "]", ")", ":", "return", "True", "m", "=", "(", "n", "&", "127", ")", "if", "(", "not", "(", "(", "(", "m", "*", "2344881533", ")", "&", "(", "m", "*", "2716005841", ")", ")", "&", "1311242", ")", ")", ":", "m", "=", "(", "n", "%", "63", ")", "if", "(", "not", "(", "(", "(", "m", "*", "1028201975", ")", "&", "(", "m", "*", "3357846009", ")", ")", "&", "284246024", ")", ")", ":", "from", "sympy", ".", "ntheory", "import", "perfect_power", "if", "perfect_power", "(", "n", ",", "[", "2", "]", ")", ":", "return", "True", "return", "False" ]
return true if n == a * a for some integer a .
train
false
23,182
def request_uri(environ, include_query=1): url = application_uri(environ) from urllib import quote path_info = quote(environ.get('PATH_INFO', '')) if (not environ.get('SCRIPT_NAME')): url += path_info[1:] else: url += path_info if (include_query and environ.get('QUERY_STRING')): url += ('?' + environ['QUERY_STRING']) return url
[ "def", "request_uri", "(", "environ", ",", "include_query", "=", "1", ")", ":", "url", "=", "application_uri", "(", "environ", ")", "from", "urllib", "import", "quote", "path_info", "=", "quote", "(", "environ", ".", "get", "(", "'PATH_INFO'", ",", "''", ")", ")", "if", "(", "not", "environ", ".", "get", "(", "'SCRIPT_NAME'", ")", ")", ":", "url", "+=", "path_info", "[", "1", ":", "]", "else", ":", "url", "+=", "path_info", "if", "(", "include_query", "and", "environ", ".", "get", "(", "'QUERY_STRING'", ")", ")", ":", "url", "+=", "(", "'?'", "+", "environ", "[", "'QUERY_STRING'", "]", ")", "return", "url" ]
return the full request uri .
train
false
23,183
def test_lex_expression_float(): objs = tokenize('(foo 2.)') assert (objs == [HyExpression([HySymbol('foo'), HyFloat(2.0)])]) objs = tokenize('(foo -0.5)') assert (objs == [HyExpression([HySymbol('foo'), HyFloat((-0.5))])]) objs = tokenize('(foo 1.e7)') assert (objs == [HyExpression([HySymbol('foo'), HyFloat(10000000.0)])])
[ "def", "test_lex_expression_float", "(", ")", ":", "objs", "=", "tokenize", "(", "'(foo 2.)'", ")", "assert", "(", "objs", "==", "[", "HyExpression", "(", "[", "HySymbol", "(", "'foo'", ")", ",", "HyFloat", "(", "2.0", ")", "]", ")", "]", ")", "objs", "=", "tokenize", "(", "'(foo -0.5)'", ")", "assert", "(", "objs", "==", "[", "HyExpression", "(", "[", "HySymbol", "(", "'foo'", ")", ",", "HyFloat", "(", "(", "-", "0.5", ")", ")", "]", ")", "]", ")", "objs", "=", "tokenize", "(", "'(foo 1.e7)'", ")", "assert", "(", "objs", "==", "[", "HyExpression", "(", "[", "HySymbol", "(", "'foo'", ")", ",", "HyFloat", "(", "10000000.0", ")", "]", ")", "]", ")" ]
make sure expressions can produce floats .
train
false
23,184
def _clean_missing(resource_id, items, user): key = (('#' + unicode(resource_id)) + '.') contacts = Object.filter_permitted(user, Contact.objects).filter(nuvius_resource__contains=key) if (not (len(contacts) == len(items))): candidates = [] for contact in contacts: found = False for item in items: itemkey = (key + unicode(item.id.raw)) if (itemkey in contact.nuvius_resource): found = True if (not found): candidates.append(contact) for victim in candidates: victim.subscribers.clear() victim.delete()
[ "def", "_clean_missing", "(", "resource_id", ",", "items", ",", "user", ")", ":", "key", "=", "(", "(", "'#'", "+", "unicode", "(", "resource_id", ")", ")", "+", "'.'", ")", "contacts", "=", "Object", ".", "filter_permitted", "(", "user", ",", "Contact", ".", "objects", ")", ".", "filter", "(", "nuvius_resource__contains", "=", "key", ")", "if", "(", "not", "(", "len", "(", "contacts", ")", "==", "len", "(", "items", ")", ")", ")", ":", "candidates", "=", "[", "]", "for", "contact", "in", "contacts", ":", "found", "=", "False", "for", "item", "in", "items", ":", "itemkey", "=", "(", "key", "+", "unicode", "(", "item", ".", "id", ".", "raw", ")", ")", "if", "(", "itemkey", "in", "contact", ".", "nuvius_resource", ")", ":", "found", "=", "True", "if", "(", "not", "found", ")", ":", "candidates", ".", "append", "(", "contact", ")", "for", "victim", "in", "candidates", ":", "victim", ".", "subscribers", ".", "clear", "(", ")", "victim", ".", "delete", "(", ")" ]
clean items missing from data of their original resource .
train
false
23,185
def spatial_inter_hemi_connectivity(src, dist, verbose=None): from scipy.spatial.distance import cdist src = _ensure_src(src, kind='surf') conn = cdist(src[0]['rr'][src[0]['vertno']], src[1]['rr'][src[1]['vertno']]) conn = sparse.csr_matrix((conn <= dist), dtype=int) empties = [sparse.csr_matrix((nv, nv), dtype=int) for nv in conn.shape] conn = sparse.vstack([sparse.hstack([empties[0], conn]), sparse.hstack([conn.T, empties[1]])]) return conn
[ "def", "spatial_inter_hemi_connectivity", "(", "src", ",", "dist", ",", "verbose", "=", "None", ")", ":", "from", "scipy", ".", "spatial", ".", "distance", "import", "cdist", "src", "=", "_ensure_src", "(", "src", ",", "kind", "=", "'surf'", ")", "conn", "=", "cdist", "(", "src", "[", "0", "]", "[", "'rr'", "]", "[", "src", "[", "0", "]", "[", "'vertno'", "]", "]", ",", "src", "[", "1", "]", "[", "'rr'", "]", "[", "src", "[", "1", "]", "[", "'vertno'", "]", "]", ")", "conn", "=", "sparse", ".", "csr_matrix", "(", "(", "conn", "<=", "dist", ")", ",", "dtype", "=", "int", ")", "empties", "=", "[", "sparse", ".", "csr_matrix", "(", "(", "nv", ",", "nv", ")", ",", "dtype", "=", "int", ")", "for", "nv", "in", "conn", ".", "shape", "]", "conn", "=", "sparse", ".", "vstack", "(", "[", "sparse", ".", "hstack", "(", "[", "empties", "[", "0", "]", ",", "conn", "]", ")", ",", "sparse", ".", "hstack", "(", "[", "conn", ".", "T", ",", "empties", "[", "1", "]", "]", ")", "]", ")", "return", "conn" ]
get vertices on each hemisphere that are close to the other hemisphere .
train
false
23,187
def _save_password_in_keyring(credential_id, username, password): try: import keyring return keyring.set_password(credential_id, username, password) except ImportError: log.error('Tried to store password in keyring, but no keyring module is installed') return False
[ "def", "_save_password_in_keyring", "(", "credential_id", ",", "username", ",", "password", ")", ":", "try", ":", "import", "keyring", "return", "keyring", ".", "set_password", "(", "credential_id", ",", "username", ",", "password", ")", "except", "ImportError", ":", "log", ".", "error", "(", "'Tried to store password in keyring, but no keyring module is installed'", ")", "return", "False" ]
saves provider password in system keyring .
train
true
23,188
def up(iface, iface_type): if (iface_type not in ['slave']): return __salt__['cmd.run']('ifup {0}'.format(iface)) return None
[ "def", "up", "(", "iface", ",", "iface_type", ")", ":", "if", "(", "iface_type", "not", "in", "[", "'slave'", "]", ")", ":", "return", "__salt__", "[", "'cmd.run'", "]", "(", "'ifup {0}'", ".", "format", "(", "iface", ")", ")", "return", "None" ]
start up a network interface cli example: .
train
false
23,189
def closewindow(object): finder = _getfinder() object = Carbon.File.FSRef(object) object_alias = object.FSNewAliasMinimal() args = {} attrs = {} _code = 'core' _subcode = 'clos' aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form='alis', seld=object_alias, fr=None) args['----'] = aeobj_0 (_reply, args, attrs) = finder.send(_code, _subcode, args, attrs) if ('errn' in args): raise Error, aetools.decodeerror(args)
[ "def", "closewindow", "(", "object", ")", ":", "finder", "=", "_getfinder", "(", ")", "object", "=", "Carbon", ".", "File", ".", "FSRef", "(", "object", ")", "object_alias", "=", "object", ".", "FSNewAliasMinimal", "(", ")", "args", "=", "{", "}", "attrs", "=", "{", "}", "_code", "=", "'core'", "_subcode", "=", "'clos'", "aeobj_0", "=", "aetypes", ".", "ObjectSpecifier", "(", "want", "=", "aetypes", ".", "Type", "(", "'cfol'", ")", ",", "form", "=", "'alis'", ",", "seld", "=", "object_alias", ",", "fr", "=", "None", ")", "args", "[", "'----'", "]", "=", "aeobj_0", "(", "_reply", ",", "args", ",", "attrs", ")", "=", "finder", ".", "send", "(", "_code", ",", "_subcode", ",", "args", ",", "attrs", ")", "if", "(", "'errn'", "in", "args", ")", ":", "raise", "Error", ",", "aetools", ".", "decodeerror", "(", "args", ")" ]
close a finder window for folder .
train
false
23,190
def wrappertask(task): @six.wraps(task) def wrapper(*args, **kwargs): parent = task(*args, **kwargs) try: subtask = next(parent) except StopIteration: return while True: try: if isinstance(subtask, types.GeneratorType): subtask_running = True try: step = next(subtask) except StopIteration: subtask_running = False while subtask_running: try: (yield step) except GeneratorExit: subtask.close() raise except: try: step = subtask.throw(*sys.exc_info()) except StopIteration: subtask_running = False else: try: step = next(subtask) except StopIteration: subtask_running = False else: (yield subtask) except GeneratorExit: parent.close() raise except: try: subtask = parent.throw(*sys.exc_info()) except StopIteration: return else: try: subtask = next(parent) except StopIteration: return return wrapper
[ "def", "wrappertask", "(", "task", ")", ":", "@", "six", ".", "wraps", "(", "task", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "parent", "=", "task", "(", "*", "args", ",", "**", "kwargs", ")", "try", ":", "subtask", "=", "next", "(", "parent", ")", "except", "StopIteration", ":", "return", "while", "True", ":", "try", ":", "if", "isinstance", "(", "subtask", ",", "types", ".", "GeneratorType", ")", ":", "subtask_running", "=", "True", "try", ":", "step", "=", "next", "(", "subtask", ")", "except", "StopIteration", ":", "subtask_running", "=", "False", "while", "subtask_running", ":", "try", ":", "(", "yield", "step", ")", "except", "GeneratorExit", ":", "subtask", ".", "close", "(", ")", "raise", "except", ":", "try", ":", "step", "=", "subtask", ".", "throw", "(", "*", "sys", ".", "exc_info", "(", ")", ")", "except", "StopIteration", ":", "subtask_running", "=", "False", "else", ":", "try", ":", "step", "=", "next", "(", "subtask", ")", "except", "StopIteration", ":", "subtask_running", "=", "False", "else", ":", "(", "yield", "subtask", ")", "except", "GeneratorExit", ":", "parent", ".", "close", "(", ")", "raise", "except", ":", "try", ":", "subtask", "=", "parent", ".", "throw", "(", "*", "sys", ".", "exc_info", "(", ")", ")", "except", "StopIteration", ":", "return", "else", ":", "try", ":", "subtask", "=", "next", "(", "parent", ")", "except", "StopIteration", ":", "return", "return", "wrapper" ]
decorator for a task that needs to drive a subtask .
train
false
23,191
def print_output(results): print '\nSuccessful devices:' for a_dict in results: for (identifier, val) in a_dict.iteritems(): (success, out_string) = val if success: print '\n\n' print ('#' * 80) print 'Device = {0}\n'.format(identifier) print out_string print ('#' * 80) print '\n\nFailed devices:\n' for a_dict in results: for (identifier, val) in a_dict.iteritems(): (success, out_string) = val if (not success): print 'Device failed = {0}'.format(identifier) print ('\nEnd time: ' + str(datetime.now())) print
[ "def", "print_output", "(", "results", ")", ":", "print", "'\\nSuccessful devices:'", "for", "a_dict", "in", "results", ":", "for", "(", "identifier", ",", "val", ")", "in", "a_dict", ".", "iteritems", "(", ")", ":", "(", "success", ",", "out_string", ")", "=", "val", "if", "success", ":", "print", "'\\n\\n'", "print", "(", "'#'", "*", "80", ")", "print", "'Device = {0}\\n'", ".", "format", "(", "identifier", ")", "print", "out_string", "print", "(", "'#'", "*", "80", ")", "print", "'\\n\\nFailed devices:\\n'", "for", "a_dict", "in", "results", ":", "for", "(", "identifier", ",", "val", ")", "in", "a_dict", ".", "iteritems", "(", ")", ":", "(", "success", ",", "out_string", ")", "=", "val", "if", "(", "not", "success", ")", ":", "print", "'Device failed = {0}'", ".", "format", "(", "identifier", ")", "print", "(", "'\\nEnd time: '", "+", "str", "(", "datetime", ".", "now", "(", ")", ")", ")", "print" ]
display output .
train
false
23,192
def _iqr_nanpercentile(x, q, axis=None, interpolation='linear', keepdims=False, contains_nan=False): if hasattr(np, 'nanpercentile'): result = np.nanpercentile(x, q, axis=axis, interpolation=interpolation, keepdims=keepdims) if ((result.ndim > 1) and (NumpyVersion(np.__version__) < '1.11.0a')): axis = np.asarray(axis) if (axis.size == 1): if (axis.ndim == 0): axis = axis[None] result = np.rollaxis(result, axis[0]) else: result = np.rollaxis(result, (-1)) else: msg = "Keyword nan_policy='omit' not correctly supported for numpy versions < 1.9.x. The default behavior of numpy.percentile will be used." warnings.warn(msg, RuntimeWarning) result = _iqr_percentile(x, q, axis=axis) return result
[ "def", "_iqr_nanpercentile", "(", "x", ",", "q", ",", "axis", "=", "None", ",", "interpolation", "=", "'linear'", ",", "keepdims", "=", "False", ",", "contains_nan", "=", "False", ")", ":", "if", "hasattr", "(", "np", ",", "'nanpercentile'", ")", ":", "result", "=", "np", ".", "nanpercentile", "(", "x", ",", "q", ",", "axis", "=", "axis", ",", "interpolation", "=", "interpolation", ",", "keepdims", "=", "keepdims", ")", "if", "(", "(", "result", ".", "ndim", ">", "1", ")", "and", "(", "NumpyVersion", "(", "np", ".", "__version__", ")", "<", "'1.11.0a'", ")", ")", ":", "axis", "=", "np", ".", "asarray", "(", "axis", ")", "if", "(", "axis", ".", "size", "==", "1", ")", ":", "if", "(", "axis", ".", "ndim", "==", "0", ")", ":", "axis", "=", "axis", "[", "None", "]", "result", "=", "np", ".", "rollaxis", "(", "result", ",", "axis", "[", "0", "]", ")", "else", ":", "result", "=", "np", ".", "rollaxis", "(", "result", ",", "(", "-", "1", ")", ")", "else", ":", "msg", "=", "\"Keyword nan_policy='omit' not correctly supported for numpy versions < 1.9.x. The default behavior of numpy.percentile will be used.\"", "warnings", ".", "warn", "(", "msg", ",", "RuntimeWarning", ")", "result", "=", "_iqr_percentile", "(", "x", ",", "q", ",", "axis", "=", "axis", ")", "return", "result" ]
private wrapper that works around the following: 1 .
train
false
23,195
def _host_url_property(): def getter(self): if ('HTTP_HOST' in self.environ): host = self.environ['HTTP_HOST'] else: host = ('%s:%s' % (self.environ['SERVER_NAME'], self.environ['SERVER_PORT'])) scheme = self.environ.get('wsgi.url_scheme', 'http') if ((scheme == 'http') and host.endswith(':80')): (host, port) = host.rsplit(':', 1) elif ((scheme == 'https') and host.endswith(':443')): (host, port) = host.rsplit(':', 1) return ('%s://%s' % (scheme, host)) return property(getter, doc='Get url for request/response up to path')
[ "def", "_host_url_property", "(", ")", ":", "def", "getter", "(", "self", ")", ":", "if", "(", "'HTTP_HOST'", "in", "self", ".", "environ", ")", ":", "host", "=", "self", ".", "environ", "[", "'HTTP_HOST'", "]", "else", ":", "host", "=", "(", "'%s:%s'", "%", "(", "self", ".", "environ", "[", "'SERVER_NAME'", "]", ",", "self", ".", "environ", "[", "'SERVER_PORT'", "]", ")", ")", "scheme", "=", "self", ".", "environ", ".", "get", "(", "'wsgi.url_scheme'", ",", "'http'", ")", "if", "(", "(", "scheme", "==", "'http'", ")", "and", "host", ".", "endswith", "(", "':80'", ")", ")", ":", "(", "host", ",", "port", ")", "=", "host", ".", "rsplit", "(", "':'", ",", "1", ")", "elif", "(", "(", "scheme", "==", "'https'", ")", "and", "host", ".", "endswith", "(", "':443'", ")", ")", ":", "(", "host", ",", "port", ")", "=", "host", ".", "rsplit", "(", "':'", ",", "1", ")", "return", "(", "'%s://%s'", "%", "(", "scheme", ",", "host", ")", ")", "return", "property", "(", "getter", ",", "doc", "=", "'Get url for request/response up to path'", ")" ]
retrieves the best guess that can be made for an absolute location up to the path .
train
false
23,196
def init(mpstate): return SerialModule(mpstate)
[ "def", "init", "(", "mpstate", ")", ":", "return", "SerialModule", "(", "mpstate", ")" ]
initialise module .
train
false
23,197
def gilsleep(t): code = '\n'.join(['from posix cimport unistd', 'unistd.sleep(t)']) while True: inline(code, quiet=True, t=t) print time.time() sys.stdout.flush()
[ "def", "gilsleep", "(", "t", ")", ":", "code", "=", "'\\n'", ".", "join", "(", "[", "'from posix cimport unistd'", ",", "'unistd.sleep(t)'", "]", ")", "while", "True", ":", "inline", "(", "code", ",", "quiet", "=", "True", ",", "t", "=", "t", ")", "print", "time", ".", "time", "(", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
gil-holding sleep with cython .
train
false
23,199
def read_raw_kit(input_fname, mrk=None, elp=None, hsp=None, stim='>', slope='-', stimthresh=1, preload=False, stim_code='binary', verbose=None): return RawKIT(input_fname=input_fname, mrk=mrk, elp=elp, hsp=hsp, stim=stim, slope=slope, stimthresh=stimthresh, preload=preload, stim_code=stim_code, verbose=verbose)
[ "def", "read_raw_kit", "(", "input_fname", ",", "mrk", "=", "None", ",", "elp", "=", "None", ",", "hsp", "=", "None", ",", "stim", "=", "'>'", ",", "slope", "=", "'-'", ",", "stimthresh", "=", "1", ",", "preload", "=", "False", ",", "stim_code", "=", "'binary'", ",", "verbose", "=", "None", ")", ":", "return", "RawKIT", "(", "input_fname", "=", "input_fname", ",", "mrk", "=", "mrk", ",", "elp", "=", "elp", ",", "hsp", "=", "hsp", ",", "stim", "=", "stim", ",", "slope", "=", "slope", ",", "stimthresh", "=", "stimthresh", ",", "preload", "=", "preload", ",", "stim_code", "=", "stim_code", ",", "verbose", "=", "verbose", ")" ]
reader function for kit conversion to fif .
train
false
23,201
def datetime_from_uuid1(uuid_arg): return datetime_from_timestamp(unix_time_from_uuid1(uuid_arg))
[ "def", "datetime_from_uuid1", "(", "uuid_arg", ")", ":", "return", "datetime_from_timestamp", "(", "unix_time_from_uuid1", "(", "uuid_arg", ")", ")" ]
creates a timezone-agnostic datetime from the timestamp in the specified type-1 uuid .
train
false
23,204
def create_network_spec(client_factory, vif_info): network_spec = client_factory.create('ns0:VirtualDeviceConfigSpec') network_spec.operation = 'add' net_device = client_factory.create('ns0:VirtualPCNet32') network_ref = vif_info['network_ref'] network_name = vif_info['network_name'] mac_address = vif_info['mac_address'] backing = None if (network_ref and (network_ref['type'] == 'DistributedVirtualPortgroup')): backing_name = ''.join(['ns0:VirtualEthernetCardDistributed', 'VirtualPortBackingInfo']) backing = client_factory.create(backing_name) portgroup = client_factory.create('ns0:DistributedVirtualSwitchPortConnection') portgroup.switchUuid = network_ref['dvsw'] portgroup.portgroupKey = network_ref['dvpg'] backing.port = portgroup else: backing = client_factory.create('ns0:VirtualEthernetCardNetworkBackingInfo') backing.deviceName = network_name connectable_spec = client_factory.create('ns0:VirtualDeviceConnectInfo') connectable_spec.startConnected = True connectable_spec.allowGuestControl = True connectable_spec.connected = True net_device.connectable = connectable_spec net_device.backing = backing net_device.key = (-47) net_device.addressType = 'manual' net_device.macAddress = mac_address net_device.wakeOnLanEnabled = True network_spec.device = net_device return network_spec
[ "def", "create_network_spec", "(", "client_factory", ",", "vif_info", ")", ":", "network_spec", "=", "client_factory", ".", "create", "(", "'ns0:VirtualDeviceConfigSpec'", ")", "network_spec", ".", "operation", "=", "'add'", "net_device", "=", "client_factory", ".", "create", "(", "'ns0:VirtualPCNet32'", ")", "network_ref", "=", "vif_info", "[", "'network_ref'", "]", "network_name", "=", "vif_info", "[", "'network_name'", "]", "mac_address", "=", "vif_info", "[", "'mac_address'", "]", "backing", "=", "None", "if", "(", "network_ref", "and", "(", "network_ref", "[", "'type'", "]", "==", "'DistributedVirtualPortgroup'", ")", ")", ":", "backing_name", "=", "''", ".", "join", "(", "[", "'ns0:VirtualEthernetCardDistributed'", ",", "'VirtualPortBackingInfo'", "]", ")", "backing", "=", "client_factory", ".", "create", "(", "backing_name", ")", "portgroup", "=", "client_factory", ".", "create", "(", "'ns0:DistributedVirtualSwitchPortConnection'", ")", "portgroup", ".", "switchUuid", "=", "network_ref", "[", "'dvsw'", "]", "portgroup", ".", "portgroupKey", "=", "network_ref", "[", "'dvpg'", "]", "backing", ".", "port", "=", "portgroup", "else", ":", "backing", "=", "client_factory", ".", "create", "(", "'ns0:VirtualEthernetCardNetworkBackingInfo'", ")", "backing", ".", "deviceName", "=", "network_name", "connectable_spec", "=", "client_factory", ".", "create", "(", "'ns0:VirtualDeviceConnectInfo'", ")", "connectable_spec", ".", "startConnected", "=", "True", "connectable_spec", ".", "allowGuestControl", "=", "True", "connectable_spec", ".", "connected", "=", "True", "net_device", ".", "connectable", "=", "connectable_spec", "net_device", ".", "backing", "=", "backing", "net_device", ".", "key", "=", "(", "-", "47", ")", "net_device", ".", "addressType", "=", "'manual'", "net_device", ".", "macAddress", "=", "mac_address", "net_device", ".", "wakeOnLanEnabled", "=", "True", "network_spec", ".", "device", "=", "net_device", "return", "network_spec" ]
builds a config spec for the addition of a new network adapter to the vm .
train
false
23,205
def spline_filter1d(input, order=3, axis=(-1), output=numpy.float64): if ((order < 0) or (order > 5)): raise RuntimeError('spline order not supported') input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') (output, return_value) = _ni_support._get_output(output, input) if (order in [0, 1]): output[...] = numpy.array(input) else: axis = _ni_support._check_axis(axis, input.ndim) _nd_image.spline_filter1d(input, order, axis, output) return return_value
[ "def", "spline_filter1d", "(", "input", ",", "order", "=", "3", ",", "axis", "=", "(", "-", "1", ")", ",", "output", "=", "numpy", ".", "float64", ")", ":", "if", "(", "(", "order", "<", "0", ")", "or", "(", "order", ">", "5", ")", ")", ":", "raise", "RuntimeError", "(", "'spline order not supported'", ")", "input", "=", "numpy", ".", "asarray", "(", "input", ")", "if", "numpy", ".", "iscomplexobj", "(", "input", ")", ":", "raise", "TypeError", "(", "'Complex type not supported'", ")", "(", "output", ",", "return_value", ")", "=", "_ni_support", ".", "_get_output", "(", "output", ",", "input", ")", "if", "(", "order", "in", "[", "0", ",", "1", "]", ")", ":", "output", "[", "...", "]", "=", "numpy", ".", "array", "(", "input", ")", "else", ":", "axis", "=", "_ni_support", ".", "_check_axis", "(", "axis", ",", "input", ".", "ndim", ")", "_nd_image", ".", "spline_filter1d", "(", "input", ",", "order", ",", "axis", ",", "output", ")", "return", "return_value" ]
calculates a one-dimensional spline filter along the given axis .
train
false
23,206
@evalcontextfilter def do_replace(eval_ctx, s, old, new, count=None): if (count is None): count = (-1) if (not eval_ctx.autoescape): return text_type(s).replace(text_type(old), text_type(new), count) if (hasattr(old, '__html__') or (hasattr(new, '__html__') and (not hasattr(s, '__html__')))): s = escape(s) else: s = soft_unicode(s) return s.replace(soft_unicode(old), soft_unicode(new), count)
[ "@", "evalcontextfilter", "def", "do_replace", "(", "eval_ctx", ",", "s", ",", "old", ",", "new", ",", "count", "=", "None", ")", ":", "if", "(", "count", "is", "None", ")", ":", "count", "=", "(", "-", "1", ")", "if", "(", "not", "eval_ctx", ".", "autoescape", ")", ":", "return", "text_type", "(", "s", ")", ".", "replace", "(", "text_type", "(", "old", ")", ",", "text_type", "(", "new", ")", ",", "count", ")", "if", "(", "hasattr", "(", "old", ",", "'__html__'", ")", "or", "(", "hasattr", "(", "new", ",", "'__html__'", ")", "and", "(", "not", "hasattr", "(", "s", ",", "'__html__'", ")", ")", ")", ")", ":", "s", "=", "escape", "(", "s", ")", "else", ":", "s", "=", "soft_unicode", "(", "s", ")", "return", "s", ".", "replace", "(", "soft_unicode", "(", "old", ")", ",", "soft_unicode", "(", "new", ")", ",", "count", ")" ]
return a copy of the value with all occurrences of a substring replaced with a new one .
train
false
23,207
@flaskbb.command('shell', short_help='Runs a shell in the app context.') @with_appcontext def shell_command(): import code banner = ('Python %s on %s\nInstance Path: %s' % (sys.version, sys.platform, current_app.instance_path)) ctx = {'db': db} startup = os.environ.get('PYTHONSTARTUP') if (startup and os.path.isfile(startup)): with open(startup, 'r') as f: eval(compile(f.read(), startup, 'exec'), ctx) ctx.update(current_app.make_shell_context()) try: import IPython IPython.embed(banner1=banner, user_ns=ctx) except ImportError: code.interact(banner=banner, local=ctx)
[ "@", "flaskbb", ".", "command", "(", "'shell'", ",", "short_help", "=", "'Runs a shell in the app context.'", ")", "@", "with_appcontext", "def", "shell_command", "(", ")", ":", "import", "code", "banner", "=", "(", "'Python %s on %s\\nInstance Path: %s'", "%", "(", "sys", ".", "version", ",", "sys", ".", "platform", ",", "current_app", ".", "instance_path", ")", ")", "ctx", "=", "{", "'db'", ":", "db", "}", "startup", "=", "os", ".", "environ", ".", "get", "(", "'PYTHONSTARTUP'", ")", "if", "(", "startup", "and", "os", ".", "path", ".", "isfile", "(", "startup", ")", ")", ":", "with", "open", "(", "startup", ",", "'r'", ")", "as", "f", ":", "eval", "(", "compile", "(", "f", ".", "read", "(", ")", ",", "startup", ",", "'exec'", ")", ",", "ctx", ")", "ctx", ".", "update", "(", "current_app", ".", "make_shell_context", "(", ")", ")", "try", ":", "import", "IPython", "IPython", ".", "embed", "(", "banner1", "=", "banner", ",", "user_ns", "=", "ctx", ")", "except", "ImportError", ":", "code", ".", "interact", "(", "banner", "=", "banner", ",", "local", "=", "ctx", ")" ]
runs an interactive python shell in the context of a given flask application .
train
false
23,209
def output_log(msg_enum, **kwargs): return msg_enum.output_log(**kwargs)
[ "def", "output_log", "(", "msg_enum", ",", "**", "kwargs", ")", ":", "return", "msg_enum", ".", "output_log", "(", "**", "kwargs", ")" ]
output the specified message to the log file and return the message .
train
false
23,210
def point(point): poly = toolpath.Polygon() (x, y) = point poly.addPoint(toolpath.Point(x, y)) return poly
[ "def", "point", "(", "point", ")", ":", "poly", "=", "toolpath", ".", "Polygon", "(", ")", "(", "x", ",", "y", ")", "=", "point", "poly", ".", "addPoint", "(", "toolpath", ".", "Point", "(", "x", ",", "y", ")", ")", "return", "poly" ]
returns polygon for point as a polygon object .
train
false
23,211
def make_hastie_10_2(n_samples=12000, random_state=None): rs = check_random_state(random_state) shape = (n_samples, 10) X = rs.normal(size=shape).reshape(shape) y = ((X ** 2.0).sum(axis=1) > 9.34).astype(np.float64) y[(y == 0.0)] = (-1.0) return (X, y)
[ "def", "make_hastie_10_2", "(", "n_samples", "=", "12000", ",", "random_state", "=", "None", ")", ":", "rs", "=", "check_random_state", "(", "random_state", ")", "shape", "=", "(", "n_samples", ",", "10", ")", "X", "=", "rs", ".", "normal", "(", "size", "=", "shape", ")", ".", "reshape", "(", "shape", ")", "y", "=", "(", "(", "X", "**", "2.0", ")", ".", "sum", "(", "axis", "=", "1", ")", ">", "9.34", ")", ".", "astype", "(", "np", ".", "float64", ")", "y", "[", "(", "y", "==", "0.0", ")", "]", "=", "(", "-", "1.0", ")", "return", "(", "X", ",", "y", ")" ]
generates data for binary classification used in hastie et al .
train
false
23,212
def gen_extractors(): return [klass() for klass in _ALL_CLASSES]
[ "def", "gen_extractors", "(", ")", ":", "return", "[", "klass", "(", ")", "for", "klass", "in", "_ALL_CLASSES", "]" ]
return a list of an instance of every supported extractor .
train
false
23,213
def pelican_init(pelicanobj): try: import markdown from plantuml_md import PlantUMLMarkdownExtension except: logger.debug('[plantuml] Markdown support not available') return config = {'siteurl': pelicanobj.settings['SITEURL']} try: pelicanobj.settings['MD_EXTENSIONS'].append(PlantUMLMarkdownExtension(config)) except: logger.error('[plantuml] Unable to configure plantuml markdown extension')
[ "def", "pelican_init", "(", "pelicanobj", ")", ":", "try", ":", "import", "markdown", "from", "plantuml_md", "import", "PlantUMLMarkdownExtension", "except", ":", "logger", ".", "debug", "(", "'[plantuml] Markdown support not available'", ")", "return", "config", "=", "{", "'siteurl'", ":", "pelicanobj", ".", "settings", "[", "'SITEURL'", "]", "}", "try", ":", "pelicanobj", ".", "settings", "[", "'MD_EXTENSIONS'", "]", ".", "append", "(", "PlantUMLMarkdownExtension", "(", "config", ")", ")", "except", ":", "logger", ".", "error", "(", "'[plantuml] Unable to configure plantuml markdown extension'", ")" ]
prepare configurations for the md plugin .
train
false
23,214
def _read_id_struct(fid, tag, shape, rlims): return dict(version=int(np.fromstring(fid.read(4), dtype='>i4')), machid=np.fromstring(fid.read(8), dtype='>i4'), secs=int(np.fromstring(fid.read(4), dtype='>i4')), usecs=int(np.fromstring(fid.read(4), dtype='>i4')))
[ "def", "_read_id_struct", "(", "fid", ",", "tag", ",", "shape", ",", "rlims", ")", ":", "return", "dict", "(", "version", "=", "int", "(", "np", ".", "fromstring", "(", "fid", ".", "read", "(", "4", ")", ",", "dtype", "=", "'>i4'", ")", ")", ",", "machid", "=", "np", ".", "fromstring", "(", "fid", ".", "read", "(", "8", ")", ",", "dtype", "=", "'>i4'", ")", ",", "secs", "=", "int", "(", "np", ".", "fromstring", "(", "fid", ".", "read", "(", "4", ")", ",", "dtype", "=", "'>i4'", ")", ")", ",", "usecs", "=", "int", "(", "np", ".", "fromstring", "(", "fid", ".", "read", "(", "4", ")", ",", "dtype", "=", "'>i4'", ")", ")", ")" ]
read id struct tag .
train
false
23,215
def _center_scale_xy(X, Y, scale=True): x_mean = X.mean(axis=0) X -= x_mean y_mean = Y.mean(axis=0) Y -= y_mean if scale: x_std = X.std(axis=0, ddof=1) x_std[(x_std == 0.0)] = 1.0 X /= x_std y_std = Y.std(axis=0, ddof=1) y_std[(y_std == 0.0)] = 1.0 Y /= y_std else: x_std = np.ones(X.shape[1]) y_std = np.ones(Y.shape[1]) return (X, Y, x_mean, y_mean, x_std, y_std)
[ "def", "_center_scale_xy", "(", "X", ",", "Y", ",", "scale", "=", "True", ")", ":", "x_mean", "=", "X", ".", "mean", "(", "axis", "=", "0", ")", "X", "-=", "x_mean", "y_mean", "=", "Y", ".", "mean", "(", "axis", "=", "0", ")", "Y", "-=", "y_mean", "if", "scale", ":", "x_std", "=", "X", ".", "std", "(", "axis", "=", "0", ",", "ddof", "=", "1", ")", "x_std", "[", "(", "x_std", "==", "0.0", ")", "]", "=", "1.0", "X", "/=", "x_std", "y_std", "=", "Y", ".", "std", "(", "axis", "=", "0", ",", "ddof", "=", "1", ")", "y_std", "[", "(", "y_std", "==", "0.0", ")", "]", "=", "1.0", "Y", "/=", "y_std", "else", ":", "x_std", "=", "np", ".", "ones", "(", "X", ".", "shape", "[", "1", "]", ")", "y_std", "=", "np", ".", "ones", "(", "Y", ".", "shape", "[", "1", "]", ")", "return", "(", "X", ",", "Y", ",", "x_mean", ",", "y_mean", ",", "x_std", ",", "y_std", ")" ]
center x .
train
false
23,216
def logbasechange(a, b): return (np.log(b) / np.log(a))
[ "def", "logbasechange", "(", "a", ",", "b", ")", ":", "return", "(", "np", ".", "log", "(", "b", ")", "/", "np", ".", "log", "(", "a", ")", ")" ]
there is a one-to-one transformation of the entropy value from a log base b to a log base a : h_{b}(x)=log_{b}(a)[h_{a}(x)] returns log_{b}(a) .
train
false
23,217
def errors_from_serialization_exceptions(exceptions, included=False): _to_error = partial(error_from_serialization_exception, included=included) errors = list(map(_to_error, exceptions)) return errors_response(500, errors)
[ "def", "errors_from_serialization_exceptions", "(", "exceptions", ",", "included", "=", "False", ")", ":", "_to_error", "=", "partial", "(", "error_from_serialization_exception", ",", "included", "=", "included", ")", "errors", "=", "list", "(", "map", "(", "_to_error", ",", "exceptions", ")", ")", "return", "errors_response", "(", "500", ",", "errors", ")" ]
returns an errors response object .
train
false
23,218
def mark_positive(builder, load): upper_bound = ((1 << (load.type.width - 1)) - 1) set_range_metadata(builder, load, 0, upper_bound)
[ "def", "mark_positive", "(", "builder", ",", "load", ")", ":", "upper_bound", "=", "(", "(", "1", "<<", "(", "load", ".", "type", ".", "width", "-", "1", ")", ")", "-", "1", ")", "set_range_metadata", "(", "builder", ",", "load", ",", "0", ",", "upper_bound", ")" ]
mark the result of a load instruction as positive .
train
false
23,219
def svn_tags_param(registry, xml_parent, data): pdef = base_param(registry, xml_parent, data, True, 'hudson.scm.listtagsparameter.ListSubversionTagsParameterDefinition') XML.SubElement(pdef, 'tagsDir').text = data['url'] XML.SubElement(pdef, 'tagsFilter').text = data.get('filter', None) XML.SubElement(pdef, 'reverseByDate').text = 'true' XML.SubElement(pdef, 'reverseByName').text = 'false' XML.SubElement(pdef, 'maxTags').text = '100' XML.SubElement(pdef, 'uuid').text = '1-1-1-1-1'
[ "def", "svn_tags_param", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "pdef", "=", "base_param", "(", "registry", ",", "xml_parent", ",", "data", ",", "True", ",", "'hudson.scm.listtagsparameter.ListSubversionTagsParameterDefinition'", ")", "XML", ".", "SubElement", "(", "pdef", ",", "'tagsDir'", ")", ".", "text", "=", "data", "[", "'url'", "]", "XML", ".", "SubElement", "(", "pdef", ",", "'tagsFilter'", ")", ".", "text", "=", "data", ".", "get", "(", "'filter'", ",", "None", ")", "XML", ".", "SubElement", "(", "pdef", ",", "'reverseByDate'", ")", ".", "text", "=", "'true'", "XML", ".", "SubElement", "(", "pdef", ",", "'reverseByName'", ")", ".", "text", "=", "'false'", "XML", ".", "SubElement", "(", "pdef", ",", "'maxTags'", ")", ".", "text", "=", "'100'", "XML", ".", "SubElement", "(", "pdef", ",", "'uuid'", ")", ".", "text", "=", "'1-1-1-1-1'" ]
yaml: svn-tags a svn tag parameter requires the jenkins :jenkins-wiki .
train
false
23,220
def _tag_retriables_as_unretriable(f): @six.wraps(f) def wrapped(*args, **kwargs): try: return f(*args, **kwargs) except Exception as e: with excutils.save_and_reraise_exception(): if is_retriable(e): setattr(e, '_RETRY_EXCEEDED', True) return wrapped
[ "def", "_tag_retriables_as_unretriable", "(", "f", ")", ":", "@", "six", ".", "wraps", "(", "f", ")", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "f", "(", "*", "args", ",", "**", "kwargs", ")", "except", "Exception", "as", "e", ":", "with", "excutils", ".", "save_and_reraise_exception", "(", ")", ":", "if", "is_retriable", "(", "e", ")", ":", "setattr", "(", "e", ",", "'_RETRY_EXCEEDED'", ",", "True", ")", "return", "wrapped" ]
puts a flag on retriable exceptions so is_retriable returns false .
train
false
23,221
def format_mapping_file(headers, mapping_data, comments=None): result = [] result.append(('#' + ' DCTB '.join(headers))) if (comments is not None): for comment in comments: result.append(('#' + comment)) for mapping_line in mapping_data: if (not (len(mapping_line) == len(headers))): raise RuntimeError(('error formatting mapping file, does each ' + 'sample have the same length of data as the headers?')) result.append(' DCTB '.join(mapping_line)) str_result = '\n'.join(result) return str_result
[ "def", "format_mapping_file", "(", "headers", ",", "mapping_data", ",", "comments", "=", "None", ")", ":", "result", "=", "[", "]", "result", ".", "append", "(", "(", "'#'", "+", "' DCTB '", ".", "join", "(", "headers", ")", ")", ")", "if", "(", "comments", "is", "not", "None", ")", ":", "for", "comment", "in", "comments", ":", "result", ".", "append", "(", "(", "'#'", "+", "comment", ")", ")", "for", "mapping_line", "in", "mapping_data", ":", "if", "(", "not", "(", "len", "(", "mapping_line", ")", "==", "len", "(", "headers", ")", ")", ")", ":", "raise", "RuntimeError", "(", "(", "'error formatting mapping file, does each '", "+", "'sample have the same length of data as the headers?'", ")", ")", "result", ".", "append", "(", "' DCTB '", ".", "join", "(", "mapping_line", ")", ")", "str_result", "=", "'\\n'", ".", "join", "(", "result", ")", "return", "str_result" ]
returns a large formatted string representing the entire mapping file each input is a list .
train
false
23,222
@default_selem @pad_for_eccentric_selems def closing(image, selem=None, out=None): dilated = dilation(image, selem) out = erosion(dilated, selem, out=out, shift_x=True, shift_y=True) return out
[ "@", "default_selem", "@", "pad_for_eccentric_selems", "def", "closing", "(", "image", ",", "selem", "=", "None", ",", "out", "=", "None", ")", ":", "dilated", "=", "dilation", "(", "image", ",", "selem", ")", "out", "=", "erosion", "(", "dilated", ",", "selem", ",", "out", "=", "out", ",", "shift_x", "=", "True", ",", "shift_y", "=", "True", ")", "return", "out" ]
return greyscale morphological closing of an image .
train
false
23,224
def capture_transaction_exceptions(func): def raise_the_exception(conn, exc): if ('current transaction is aborted, commands ignored until end of transaction block' in six.text_type(exc)): exc_info = getattr(conn, '_last_exception', None) if (exc_info is None): raise new_exc = TransactionAborted(sys.exc_info(), exc_info) six.reraise(new_exc.__class__, new_exc, exc_info[2]) conn._last_exception = sys.exc_info() raise @wraps(func) def inner(self, *args, **kwargs): try: return func(self, *args, **kwargs) except Exception as e: raise_the_exception(self.db, e) return inner
[ "def", "capture_transaction_exceptions", "(", "func", ")", ":", "def", "raise_the_exception", "(", "conn", ",", "exc", ")", ":", "if", "(", "'current transaction is aborted, commands ignored until end of transaction block'", "in", "six", ".", "text_type", "(", "exc", ")", ")", ":", "exc_info", "=", "getattr", "(", "conn", ",", "'_last_exception'", ",", "None", ")", "if", "(", "exc_info", "is", "None", ")", ":", "raise", "new_exc", "=", "TransactionAborted", "(", "sys", ".", "exc_info", "(", ")", ",", "exc_info", ")", "six", ".", "reraise", "(", "new_exc", ".", "__class__", ",", "new_exc", ",", "exc_info", "[", "2", "]", ")", "conn", ".", "_last_exception", "=", "sys", ".", "exc_info", "(", ")", "raise", "@", "wraps", "(", "func", ")", "def", "inner", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "except", "Exception", "as", "e", ":", "raise_the_exception", "(", "self", ".", "db", ",", "e", ")", "return", "inner" ]
catches database errors and reraises them on subsequent errors that throw some cruft about transaction aborted .
train
false
23,225
def test_currentitem(objects): assert (objects.history.currentItemIndex() == 1)
[ "def", "test_currentitem", "(", "objects", ")", ":", "assert", "(", "objects", ".", "history", ".", "currentItemIndex", "(", ")", "==", "1", ")" ]
check if the current item index was loaded correctly .
train
false
23,228
def libvlc_vlm_change_media(p_instance, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop): f = (_Cfunctions.get('libvlc_vlm_change_media', None) or _Cfunction('libvlc_vlm_change_media', ((1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p), ctypes.c_int, ctypes.c_int)) return f(p_instance, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop)
[ "def", "libvlc_vlm_change_media", "(", "p_instance", ",", "psz_name", ",", "psz_input", ",", "psz_output", ",", "i_options", ",", "ppsz_options", ",", "b_enabled", ",", "b_loop", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_vlm_change_media'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_vlm_change_media'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", "(", "1", ",", ")", ")", ",", "None", ",", "ctypes", ".", "c_int", ",", "Instance", ",", "ctypes", ".", "c_char_p", ",", "ctypes", ".", "c_char_p", ",", "ctypes", ".", "c_char_p", ",", "ctypes", ".", "c_int", ",", "ListPOINTER", "(", "ctypes", ".", "c_char_p", ")", ",", "ctypes", ".", "c_int", ",", "ctypes", ".", "c_int", ")", ")", "return", "f", "(", "p_instance", ",", "psz_name", ",", "psz_input", ",", "psz_output", ",", "i_options", ",", "ppsz_options", ",", "b_enabled", ",", "b_loop", ")" ]
edit the parameters of a media .
train
true
23,229
def extras_require(): return {x: extras((x + '.txt')) for x in EXTENSIONS}
[ "def", "extras_require", "(", ")", ":", "return", "{", "x", ":", "extras", "(", "(", "x", "+", "'.txt'", ")", ")", "for", "x", "in", "EXTENSIONS", "}" ]
get map of all extra requirements .
train
false