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
17,252
def get_entrance_exam_content(user, course): required_content = get_required_content(course, user) exam_module = None for content in required_content: usage_key = course.id.make_usage_key_from_deprecated_string(content) module_item = modulestore().get_item(usage_key) if ((not module_item.hide_from_toc) and module_item.is_entrance_exam): exam_module = module_item break return exam_module
[ "def", "get_entrance_exam_content", "(", "user", ",", "course", ")", ":", "required_content", "=", "get_required_content", "(", "course", ",", "user", ")", "exam_module", "=", "None", "for", "content", "in", "required_content", ":", "usage_key", "=", "course", ".", "id", ".", "make_usage_key_from_deprecated_string", "(", "content", ")", "module_item", "=", "modulestore", "(", ")", ".", "get_item", "(", "usage_key", ")", "if", "(", "(", "not", "module_item", ".", "hide_from_toc", ")", "and", "module_item", ".", "is_entrance_exam", ")", ":", "exam_module", "=", "module_item", "break", "return", "exam_module" ]
get the entrance exam content information .
train
false
17,253
@error.context_aware def lv_mount(vg_name, lv_name, mount_loc, create_filesystem=''): error.context('Mounting the logical volume', logging.info) try: if create_filesystem: result = utils.run(('mkfs.%s /dev/%s/%s' % (create_filesystem, vg_name, lv_name))) logging.debug(result.stdout.rstrip()) result = utils.run(('mount /dev/%s/%s %s' % (vg_name, lv_name, mount_loc))) except error.CmdError as ex: logging.warning(ex) return False return True
[ "@", "error", ".", "context_aware", "def", "lv_mount", "(", "vg_name", ",", "lv_name", ",", "mount_loc", ",", "create_filesystem", "=", "''", ")", ":", "error", ".", "context", "(", "'Mounting the logical volume'", ",", "logging", ".", "info", ")", "try", ":", "if", "create_filesystem", ":", "result", "=", "utils", ".", "run", "(", "(", "'mkfs.%s /dev/%s/%s'", "%", "(", "create_filesystem", ",", "vg_name", ",", "lv_name", ")", ")", ")", "logging", ".", "debug", "(", "result", ".", "stdout", ".", "rstrip", "(", ")", ")", "result", "=", "utils", ".", "run", "(", "(", "'mount /dev/%s/%s %s'", "%", "(", "vg_name", ",", "lv_name", ",", "mount_loc", ")", ")", ")", "except", "error", ".", "CmdError", "as", "ex", ":", "logging", ".", "warning", "(", "ex", ")", "return", "False", "return", "True" ]
mount a logical volume to a mount location .
train
false
17,254
@keras_test def test_image_classification(): np.random.seed(1337) input_shape = (16, 16, 3) ((X_train, y_train), (X_test, y_test)) = get_test_data(nb_train=500, nb_test=200, input_shape=input_shape, classification=True, nb_class=4) y_train = to_categorical(y_train) y_test = to_categorical(y_test) nb_conv = 3 nb_pool = 2 model = Sequential([Convolution2D(nb_filter=8, nb_row=nb_conv, nb_col=nb_conv, input_shape=input_shape), MaxPooling2D(pool_size=(nb_pool, nb_pool)), Flatten(), Activation('relu'), Dense(y_test.shape[(-1)], activation='softmax')]) model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) history = model.fit(X_train, y_train, nb_epoch=10, batch_size=16, validation_data=(X_test, y_test), verbose=0) assert (history.history['val_acc'][(-1)] > 0.85)
[ "@", "keras_test", "def", "test_image_classification", "(", ")", ":", "np", ".", "random", ".", "seed", "(", "1337", ")", "input_shape", "=", "(", "16", ",", "16", ",", "3", ")", "(", "(", "X_train", ",", "y_train", ")", ",", "(", "X_test", ",", "y_test", ")", ")", "=", "get_test_data", "(", "nb_train", "=", "500", ",", "nb_test", "=", "200", ",", "input_shape", "=", "input_shape", ",", "classification", "=", "True", ",", "nb_class", "=", "4", ")", "y_train", "=", "to_categorical", "(", "y_train", ")", "y_test", "=", "to_categorical", "(", "y_test", ")", "nb_conv", "=", "3", "nb_pool", "=", "2", "model", "=", "Sequential", "(", "[", "Convolution2D", "(", "nb_filter", "=", "8", ",", "nb_row", "=", "nb_conv", ",", "nb_col", "=", "nb_conv", ",", "input_shape", "=", "input_shape", ")", ",", "MaxPooling2D", "(", "pool_size", "=", "(", "nb_pool", ",", "nb_pool", ")", ")", ",", "Flatten", "(", ")", ",", "Activation", "(", "'relu'", ")", ",", "Dense", "(", "y_test", ".", "shape", "[", "(", "-", "1", ")", "]", ",", "activation", "=", "'softmax'", ")", "]", ")", "model", ".", "compile", "(", "loss", "=", "'categorical_crossentropy'", ",", "optimizer", "=", "'rmsprop'", ",", "metrics", "=", "[", "'accuracy'", "]", ")", "history", "=", "model", ".", "fit", "(", "X_train", ",", "y_train", ",", "nb_epoch", "=", "10", ",", "batch_size", "=", "16", ",", "validation_data", "=", "(", "X_test", ",", "y_test", ")", ",", "verbose", "=", "0", ")", "assert", "(", "history", ".", "history", "[", "'val_acc'", "]", "[", "(", "-", "1", ")", "]", ">", "0.85", ")" ]
classify random 16x16 color images into several classes using logistic regression with convolutional hidden layer .
train
false
17,257
def implemented_function(symfunc, implementation): from sympy.core.function import UndefinedFunction if isinstance(symfunc, string_types): symfunc = UndefinedFunction(symfunc) elif (not isinstance(symfunc, UndefinedFunction)): raise ValueError('symfunc should be either a string or an UndefinedFunction instance.') symfunc._imp_ = staticmethod(implementation) return symfunc
[ "def", "implemented_function", "(", "symfunc", ",", "implementation", ")", ":", "from", "sympy", ".", "core", ".", "function", "import", "UndefinedFunction", "if", "isinstance", "(", "symfunc", ",", "string_types", ")", ":", "symfunc", "=", "UndefinedFunction", "(", "symfunc", ")", "elif", "(", "not", "isinstance", "(", "symfunc", ",", "UndefinedFunction", ")", ")", ":", "raise", "ValueError", "(", "'symfunc should be either a string or an UndefinedFunction instance.'", ")", "symfunc", ".", "_imp_", "=", "staticmethod", "(", "implementation", ")", "return", "symfunc" ]
add numerical implementation to function symfunc .
train
false
17,259
def strip_html_comments(text): lines = text.splitlines(True) new_lines = filter((lambda line: (not line.startswith('<!--'))), lines) return ''.join(new_lines)
[ "def", "strip_html_comments", "(", "text", ")", ":", "lines", "=", "text", ".", "splitlines", "(", "True", ")", "new_lines", "=", "filter", "(", "(", "lambda", "line", ":", "(", "not", "line", ".", "startswith", "(", "'<!--'", ")", ")", ")", ",", "lines", ")", "return", "''", ".", "join", "(", "new_lines", ")" ]
strip html comments from a unicode string .
train
true
17,261
def get_default_compiler(osname=None, platform=None): if (osname is None): osname = os.name if (platform is None): platform = sys.platform for (pattern, compiler) in _default_compilers: if ((re.match(pattern, platform) is not None) or (re.match(pattern, osname) is not None)): return compiler return 'unix'
[ "def", "get_default_compiler", "(", "osname", "=", "None", ",", "platform", "=", "None", ")", ":", "if", "(", "osname", "is", "None", ")", ":", "osname", "=", "os", ".", "name", "if", "(", "platform", "is", "None", ")", ":", "platform", "=", "sys", ".", "platform", "for", "(", "pattern", ",", "compiler", ")", "in", "_default_compilers", ":", "if", "(", "(", "re", ".", "match", "(", "pattern", ",", "platform", ")", "is", "not", "None", ")", "or", "(", "re", ".", "match", "(", "pattern", ",", "osname", ")", "is", "not", "None", ")", ")", ":", "return", "compiler", "return", "'unix'" ]
determine the default compiler to use for the given platform .
train
false
17,263
def _list_users(source=None): if acl.get_limited_to_project(flask.request.headers): users = [flask.request.headers.get('X-User-id')] else: users = flask.request.storage_conn.get_users(source=source) return flask.jsonify(users=list(users))
[ "def", "_list_users", "(", "source", "=", "None", ")", ":", "if", "acl", ".", "get_limited_to_project", "(", "flask", ".", "request", ".", "headers", ")", ":", "users", "=", "[", "flask", ".", "request", ".", "headers", ".", "get", "(", "'X-User-id'", ")", "]", "else", ":", "users", "=", "flask", ".", "request", ".", "storage_conn", ".", "get_users", "(", "source", "=", "source", ")", "return", "flask", ".", "jsonify", "(", "users", "=", "list", "(", "users", ")", ")" ]
return a list of user names .
train
false
17,266
def r_argmax(v): if (len(v) == 1): return 0 maxbid = max(v) maxbidders = [i for (i, b) in enumerate(v) if (b == maxbid)] return choice(maxbidders)
[ "def", "r_argmax", "(", "v", ")", ":", "if", "(", "len", "(", "v", ")", "==", "1", ")", ":", "return", "0", "maxbid", "=", "max", "(", "v", ")", "maxbidders", "=", "[", "i", "for", "(", "i", ",", "b", ")", "in", "enumerate", "(", "v", ")", "if", "(", "b", "==", "maxbid", ")", "]", "return", "choice", "(", "maxbidders", ")" ]
acts like scipy argmax .
train
false
17,267
def get_http_status(status_code, default_reason='Unknown'): try: code = float(status_code) code = int(code) if (code < 100): raise ValueError except ValueError: raise ValueError('get_http_status failed: "%s" is not a valid status code', status_code) try: return getattr(status_codes, ('HTTP_' + str(code))) except AttributeError: return ((str(code) + ' ') + default_reason)
[ "def", "get_http_status", "(", "status_code", ",", "default_reason", "=", "'Unknown'", ")", ":", "try", ":", "code", "=", "float", "(", "status_code", ")", "code", "=", "int", "(", "code", ")", "if", "(", "code", "<", "100", ")", ":", "raise", "ValueError", "except", "ValueError", ":", "raise", "ValueError", "(", "'get_http_status failed: \"%s\" is not a valid status code'", ",", "status_code", ")", "try", ":", "return", "getattr", "(", "status_codes", ",", "(", "'HTTP_'", "+", "str", "(", "code", ")", ")", ")", "except", "AttributeError", ":", "return", "(", "(", "str", "(", "code", ")", "+", "' '", ")", "+", "default_reason", ")" ]
gets both the http status code and description from just a code args: status_code: integer or string that can be converted to an integer default_reason: default text to be appended to the status_code if the lookup does not find a result returns: str: status code e .
train
false
17,268
def isotime(at=None, subsecond=False): if (not at): at = utcnow() st = at.strftime((_ISO8601_TIME_FORMAT if (not subsecond) else _ISO8601_TIME_FORMAT_SUBSECOND)) tz = (at.tzinfo.tzname(None) if at.tzinfo else 'UTC') st += ('Z' if (tz == 'UTC') else tz) return st
[ "def", "isotime", "(", "at", "=", "None", ",", "subsecond", "=", "False", ")", ":", "if", "(", "not", "at", ")", ":", "at", "=", "utcnow", "(", ")", "st", "=", "at", ".", "strftime", "(", "(", "_ISO8601_TIME_FORMAT", "if", "(", "not", "subsecond", ")", "else", "_ISO8601_TIME_FORMAT_SUBSECOND", ")", ")", "tz", "=", "(", "at", ".", "tzinfo", ".", "tzname", "(", "None", ")", "if", "at", ".", "tzinfo", "else", "'UTC'", ")", "st", "+=", "(", "'Z'", "if", "(", "tz", "==", "'UTC'", ")", "else", "tz", ")", "return", "st" ]
stringify utc time in iso 8601 format .
train
true
17,269
def make_random_password(length=None, choice_fn=random.SystemRandom().choice): length = (length if (length is not None) else _DEFAULT_RANDOM_PASSWORD_LENGTH) return ''.join((choice_fn(_PASSWORD_CHARSET) for _ in xrange(length)))
[ "def", "make_random_password", "(", "length", "=", "None", ",", "choice_fn", "=", "random", ".", "SystemRandom", "(", ")", ".", "choice", ")", ":", "length", "=", "(", "length", "if", "(", "length", "is", "not", "None", ")", "else", "_DEFAULT_RANDOM_PASSWORD_LENGTH", ")", "return", "''", ".", "join", "(", "(", "choice_fn", "(", "_PASSWORD_CHARSET", ")", "for", "_", "in", "xrange", "(", "length", ")", ")", ")" ]
makes a random password .
train
false
17,270
def python_3000_has_key(logical_line, noqa): pos = logical_line.find('.has_key(') if ((pos > (-1)) and (not noqa)): (yield (pos, "W601 .has_key() is deprecated, use 'in'"))
[ "def", "python_3000_has_key", "(", "logical_line", ",", "noqa", ")", ":", "pos", "=", "logical_line", ".", "find", "(", "'.has_key('", ")", "if", "(", "(", "pos", ">", "(", "-", "1", ")", ")", "and", "(", "not", "noqa", ")", ")", ":", "(", "yield", "(", "pos", ",", "\"W601 .has_key() is deprecated, use 'in'\"", ")", ")" ]
the {} .
train
false
17,271
def user_messages(request): return {'user_messages': get_messages(request)}
[ "def", "user_messages", "(", "request", ")", ":", "return", "{", "'user_messages'", ":", "get_messages", "(", "request", ")", "}" ]
returns session messages for the current session .
train
false
17,272
def wollist(maclist, bcast='255.255.255.255', destport=9): ret = [] try: with salt.utils.fopen(maclist, 'r') as ifile: for mac in ifile: wol(mac.strip(), bcast, destport) print('Waking up {0}'.format(mac.strip())) ret.append(mac) except Exception as err: __jid_event__.fire_event({'error': 'Failed to open the MAC file. Error: {0}'.format(err)}, 'progress') return [] return ret
[ "def", "wollist", "(", "maclist", ",", "bcast", "=", "'255.255.255.255'", ",", "destport", "=", "9", ")", ":", "ret", "=", "[", "]", "try", ":", "with", "salt", ".", "utils", ".", "fopen", "(", "maclist", ",", "'r'", ")", "as", "ifile", ":", "for", "mac", "in", "ifile", ":", "wol", "(", "mac", ".", "strip", "(", ")", ",", "bcast", ",", "destport", ")", "print", "(", "'Waking up {0}'", ".", "format", "(", "mac", ".", "strip", "(", ")", ")", ")", "ret", ".", "append", "(", "mac", ")", "except", "Exception", "as", "err", ":", "__jid_event__", ".", "fire_event", "(", "{", "'error'", ":", "'Failed to open the MAC file. Error: {0}'", ".", "format", "(", "err", ")", "}", ",", "'progress'", ")", "return", "[", "]", "return", "ret" ]
send a "magic packet" to wake up a list of minions .
train
true
17,276
def getLoopLayers(archivableObjects, importRadius, layerHeight, maximumZ, shouldPrintWarning, z, zoneArrangement): loopLayers = [] while (z <= maximumZ): triangle_mesh.getLoopLayerAppend(loopLayers, z).loops = getEmptyZLoops(archivableObjects, importRadius, True, z, zoneArrangement) z += layerHeight return loopLayers
[ "def", "getLoopLayers", "(", "archivableObjects", ",", "importRadius", ",", "layerHeight", ",", "maximumZ", ",", "shouldPrintWarning", ",", "z", ",", "zoneArrangement", ")", ":", "loopLayers", "=", "[", "]", "while", "(", "z", "<=", "maximumZ", ")", ":", "triangle_mesh", ".", "getLoopLayerAppend", "(", "loopLayers", ",", "z", ")", ".", "loops", "=", "getEmptyZLoops", "(", "archivableObjects", ",", "importRadius", ",", "True", ",", "z", ",", "zoneArrangement", ")", "z", "+=", "layerHeight", "return", "loopLayers" ]
get loop layers .
train
false
17,277
def find_top_level_loops(cfg): blocks_in_loop = set() for loop in cfg.loops().values(): insiders = ((set(loop.body) | set(loop.entries)) | set(loop.exits)) insiders.discard(loop.header) blocks_in_loop |= insiders for loop in cfg.loops().values(): if (loop.header not in blocks_in_loop): (yield loop)
[ "def", "find_top_level_loops", "(", "cfg", ")", ":", "blocks_in_loop", "=", "set", "(", ")", "for", "loop", "in", "cfg", ".", "loops", "(", ")", ".", "values", "(", ")", ":", "insiders", "=", "(", "(", "set", "(", "loop", ".", "body", ")", "|", "set", "(", "loop", ".", "entries", ")", ")", "|", "set", "(", "loop", ".", "exits", ")", ")", "insiders", ".", "discard", "(", "loop", ".", "header", ")", "blocks_in_loop", "|=", "insiders", "for", "loop", "in", "cfg", ".", "loops", "(", ")", ".", "values", "(", ")", ":", "if", "(", "loop", ".", "header", "not", "in", "blocks_in_loop", ")", ":", "(", "yield", "loop", ")" ]
a generator that yields toplevel loops given a control-flow-graph .
train
false
17,279
def _get_values(profile=None): profile = (profile or {}) serializers = salt.loader.serializers(__opts__) ret = {} for fname in profile.get('files', []): try: with salt.utils.flopen(fname) as f: contents = serializers.yaml.deserialize(f) ret = salt.utils.dictupdate.merge(ret, contents, **profile.get('merge', {})) except IOError: log.error("File not found '{0}'".format(fname)) except TypeError: log.error("Error deserializing sdb file '{0}'".format(fname)) return ret
[ "def", "_get_values", "(", "profile", "=", "None", ")", ":", "profile", "=", "(", "profile", "or", "{", "}", ")", "serializers", "=", "salt", ".", "loader", ".", "serializers", "(", "__opts__", ")", "ret", "=", "{", "}", "for", "fname", "in", "profile", ".", "get", "(", "'files'", ",", "[", "]", ")", ":", "try", ":", "with", "salt", ".", "utils", ".", "flopen", "(", "fname", ")", "as", "f", ":", "contents", "=", "serializers", ".", "yaml", ".", "deserialize", "(", "f", ")", "ret", "=", "salt", ".", "utils", ".", "dictupdate", ".", "merge", "(", "ret", ",", "contents", ",", "**", "profile", ".", "get", "(", "'merge'", ",", "{", "}", ")", ")", "except", "IOError", ":", "log", ".", "error", "(", "\"File not found '{0}'\"", ".", "format", "(", "fname", ")", ")", "except", "TypeError", ":", "log", ".", "error", "(", "\"Error deserializing sdb file '{0}'\"", ".", "format", "(", "fname", ")", ")", "return", "ret" ]
retrieve all the referenced files .
train
true
17,280
def has_configuration_override(name): configuration = get_current_site_configuration() if (configuration and (name in configuration.values)): return True return False
[ "def", "has_configuration_override", "(", "name", ")", ":", "configuration", "=", "get_current_site_configuration", "(", ")", "if", "(", "configuration", "and", "(", "name", "in", "configuration", ".", "values", ")", ")", ":", "return", "True", "return", "False" ]
returns true/false whether a site configuration has a definition for the specified key .
train
false
17,283
@pytest.mark.network def test_upgrade_vcs_req_with_no_dists_found(script, tmpdir): req = ('%s#egg=pip-test-package' % local_checkout('git+http://github.com/pypa/pip-test-package.git', tmpdir.join('cache'))) script.pip('install', req) result = script.pip('install', '-U', req) assert (not result.returncode)
[ "@", "pytest", ".", "mark", ".", "network", "def", "test_upgrade_vcs_req_with_no_dists_found", "(", "script", ",", "tmpdir", ")", ":", "req", "=", "(", "'%s#egg=pip-test-package'", "%", "local_checkout", "(", "'git+http://github.com/pypa/pip-test-package.git'", ",", "tmpdir", ".", "join", "(", "'cache'", ")", ")", ")", "script", ".", "pip", "(", "'install'", ",", "req", ")", "result", "=", "script", ".", "pip", "(", "'install'", ",", "'-U'", ",", "req", ")", "assert", "(", "not", "result", ".", "returncode", ")" ]
it can upgrade a vcs requirement that has no distributions otherwise .
train
false
17,284
def _get_by_name(context, name, session): try: query = session.query(models.MetadefNamespace).filter_by(namespace=name) namespace_rec = query.one() except sa_orm.exc.NoResultFound: LOG.debug('Metadata definition namespace=%s was not found.', name) raise exc.MetadefNamespaceNotFound(namespace_name=name) if (not _is_namespace_visible(context, namespace_rec.to_dict())): LOG.debug('Forbidding request, metadata definition namespace=%s is not visible.', name) emsg = (_('Forbidding request, metadata definition namespace=%s is not visible.') % name) raise exc.MetadefForbidden(emsg) return namespace_rec
[ "def", "_get_by_name", "(", "context", ",", "name", ",", "session", ")", ":", "try", ":", "query", "=", "session", ".", "query", "(", "models", ".", "MetadefNamespace", ")", ".", "filter_by", "(", "namespace", "=", "name", ")", "namespace_rec", "=", "query", ".", "one", "(", ")", "except", "sa_orm", ".", "exc", ".", "NoResultFound", ":", "LOG", ".", "debug", "(", "'Metadata definition namespace=%s was not found.'", ",", "name", ")", "raise", "exc", ".", "MetadefNamespaceNotFound", "(", "namespace_name", "=", "name", ")", "if", "(", "not", "_is_namespace_visible", "(", "context", ",", "namespace_rec", ".", "to_dict", "(", ")", ")", ")", ":", "LOG", ".", "debug", "(", "'Forbidding request, metadata definition namespace=%s is not visible.'", ",", "name", ")", "emsg", "=", "(", "_", "(", "'Forbidding request, metadata definition namespace=%s is not visible.'", ")", "%", "name", ")", "raise", "exc", ".", "MetadefForbidden", "(", "emsg", ")", "return", "namespace_rec" ]
get a property; raise if ns not found/visible or property not found .
train
false
17,285
@utils.arg('domain', metavar='<domain>', help=_('DNS domain.')) @utils.arg('--project', metavar='<project>', help=_('Limit access to this domain to users of the specified project.'), default=None) @deprecated_network def do_dns_create_public_domain(cs, args): cs.dns_domains.create_public(args.domain, args.project)
[ "@", "utils", ".", "arg", "(", "'domain'", ",", "metavar", "=", "'<domain>'", ",", "help", "=", "_", "(", "'DNS domain.'", ")", ")", "@", "utils", ".", "arg", "(", "'--project'", ",", "metavar", "=", "'<project>'", ",", "help", "=", "_", "(", "'Limit access to this domain to users of the specified project.'", ")", ",", "default", "=", "None", ")", "@", "deprecated_network", "def", "do_dns_create_public_domain", "(", "cs", ",", "args", ")", ":", "cs", ".", "dns_domains", ".", "create_public", "(", "args", ".", "domain", ",", "args", ".", "project", ")" ]
create the specified dns domain .
train
false
17,286
def basename(p): return split(p)[1]
[ "def", "basename", "(", "p", ")", ":", "return", "split", "(", "p", ")", "[", "1", "]" ]
an os .
train
false
17,287
def get_signing_policy(signing_policy_name): signing_policy = _get_signing_policy(signing_policy_name) if (not signing_policy): return 'Signing policy {0} does not exist.'.format(signing_policy_name) if isinstance(signing_policy, list): dict_ = {} for item in signing_policy: dict_.update(item) signing_policy = dict_ try: del signing_policy['signing_private_key'] except KeyError: pass try: signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE') except KeyError: pass return signing_policy
[ "def", "get_signing_policy", "(", "signing_policy_name", ")", ":", "signing_policy", "=", "_get_signing_policy", "(", "signing_policy_name", ")", "if", "(", "not", "signing_policy", ")", ":", "return", "'Signing policy {0} does not exist.'", ".", "format", "(", "signing_policy_name", ")", "if", "isinstance", "(", "signing_policy", ",", "list", ")", ":", "dict_", "=", "{", "}", "for", "item", "in", "signing_policy", ":", "dict_", ".", "update", "(", "item", ")", "signing_policy", "=", "dict_", "try", ":", "del", "signing_policy", "[", "'signing_private_key'", "]", "except", "KeyError", ":", "pass", "try", ":", "signing_policy", "[", "'signing_cert'", "]", "=", "get_pem_entry", "(", "signing_policy", "[", "'signing_cert'", "]", ",", "'CERTIFICATE'", ")", "except", "KeyError", ":", "pass", "return", "signing_policy" ]
returns the details of a names signing policy .
train
true
17,288
def _create_secret(namespace, name, data, apiserver_url): url = '{0}/api/v1/namespaces/{1}/secrets'.format(apiserver_url, namespace) request = {'apiVersion': 'v1', 'kind': 'Secret', 'metadata': {'name': name, 'namespace': namespace}, 'data': data} ret = _kpost(url, request) return ret
[ "def", "_create_secret", "(", "namespace", ",", "name", ",", "data", ",", "apiserver_url", ")", ":", "url", "=", "'{0}/api/v1/namespaces/{1}/secrets'", ".", "format", "(", "apiserver_url", ",", "namespace", ")", "request", "=", "{", "'apiVersion'", ":", "'v1'", ",", "'kind'", ":", "'Secret'", ",", "'metadata'", ":", "{", "'name'", ":", "name", ",", "'namespace'", ":", "namespace", "}", ",", "'data'", ":", "data", "}", "ret", "=", "_kpost", "(", "url", ",", "request", ")", "return", "ret" ]
create namespace on the defined k8s cluster .
train
true
17,290
def getPointPlusSegmentWithLength(length, point, segment): return (((segment * length) / abs(segment)) + point)
[ "def", "getPointPlusSegmentWithLength", "(", "length", ",", "point", ",", "segment", ")", ":", "return", "(", "(", "(", "segment", "*", "length", ")", "/", "abs", "(", "segment", ")", ")", "+", "point", ")" ]
get point plus a segment scaled to a given length .
train
false
17,291
@pytest.mark.parametrize(u'text1,prob1,text2,prob2', [(u'NOUN', (-1), u'opera', (-2))]) def test_vocab_lexeme_lt(en_vocab, text1, text2, prob1, prob2): lex1 = en_vocab[text1] lex1.prob = prob1 lex2 = en_vocab[text2] lex2.prob = prob2 assert (lex1 < lex2) assert (lex2 > lex1)
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "u'text1,prob1,text2,prob2'", ",", "[", "(", "u'NOUN'", ",", "(", "-", "1", ")", ",", "u'opera'", ",", "(", "-", "2", ")", ")", "]", ")", "def", "test_vocab_lexeme_lt", "(", "en_vocab", ",", "text1", ",", "text2", ",", "prob1", ",", "prob2", ")", ":", "lex1", "=", "en_vocab", "[", "text1", "]", "lex1", ".", "prob", "=", "prob1", "lex2", "=", "en_vocab", "[", "text2", "]", "lex2", ".", "prob", "=", "prob2", "assert", "(", "lex1", "<", "lex2", ")", "assert", "(", "lex2", ">", "lex1", ")" ]
more frequent is l .
train
false
17,292
def test_cubic(Chart, datas): chart = Chart(interpolate='cubic') chart = make_data(chart, datas) assert chart.render()
[ "def", "test_cubic", "(", "Chart", ",", "datas", ")", ":", "chart", "=", "Chart", "(", "interpolate", "=", "'cubic'", ")", "chart", "=", "make_data", "(", "chart", ",", "datas", ")", "assert", "chart", ".", "render", "(", ")" ]
test cubic interpolation .
train
false
17,293
def _evaluate_usecols(usecols, names): if callable(usecols): return set([i for (i, name) in enumerate(names) if usecols(name)]) return usecols
[ "def", "_evaluate_usecols", "(", "usecols", ",", "names", ")", ":", "if", "callable", "(", "usecols", ")", ":", "return", "set", "(", "[", "i", "for", "(", "i", ",", "name", ")", "in", "enumerate", "(", "names", ")", "if", "usecols", "(", "name", ")", "]", ")", "return", "usecols" ]
check whether or not the usecols parameter is a callable .
train
true
17,294
def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True, convert_axes=True, convert_dates=True, keep_default_dates=True, numpy=False, precise_float=False, date_unit=None, encoding=None, lines=False): (filepath_or_buffer, _, _) = get_filepath_or_buffer(path_or_buf, encoding=encoding) if isinstance(filepath_or_buffer, compat.string_types): try: exists = os.path.exists(filepath_or_buffer) except (TypeError, ValueError): exists = False if exists: (fh, handles) = _get_handle(filepath_or_buffer, 'r', encoding=encoding) json = fh.read() fh.close() else: json = filepath_or_buffer elif hasattr(filepath_or_buffer, 'read'): json = filepath_or_buffer.read() else: json = filepath_or_buffer if lines: lines = list(StringIO(json.strip())) json = (('[' + ','.join(lines)) + ']') obj = None if (typ == 'frame'): obj = FrameParser(json, orient, dtype, convert_axes, convert_dates, keep_default_dates, numpy, precise_float, date_unit).parse() if ((typ == 'series') or (obj is None)): if (not isinstance(dtype, bool)): dtype = dict(data=dtype) obj = SeriesParser(json, orient, dtype, convert_axes, convert_dates, keep_default_dates, numpy, precise_float, date_unit).parse() return obj
[ "def", "read_json", "(", "path_or_buf", "=", "None", ",", "orient", "=", "None", ",", "typ", "=", "'frame'", ",", "dtype", "=", "True", ",", "convert_axes", "=", "True", ",", "convert_dates", "=", "True", ",", "keep_default_dates", "=", "True", ",", "numpy", "=", "False", ",", "precise_float", "=", "False", ",", "date_unit", "=", "None", ",", "encoding", "=", "None", ",", "lines", "=", "False", ")", ":", "(", "filepath_or_buffer", ",", "_", ",", "_", ")", "=", "get_filepath_or_buffer", "(", "path_or_buf", ",", "encoding", "=", "encoding", ")", "if", "isinstance", "(", "filepath_or_buffer", ",", "compat", ".", "string_types", ")", ":", "try", ":", "exists", "=", "os", ".", "path", ".", "exists", "(", "filepath_or_buffer", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "exists", "=", "False", "if", "exists", ":", "(", "fh", ",", "handles", ")", "=", "_get_handle", "(", "filepath_or_buffer", ",", "'r'", ",", "encoding", "=", "encoding", ")", "json", "=", "fh", ".", "read", "(", ")", "fh", ".", "close", "(", ")", "else", ":", "json", "=", "filepath_or_buffer", "elif", "hasattr", "(", "filepath_or_buffer", ",", "'read'", ")", ":", "json", "=", "filepath_or_buffer", ".", "read", "(", ")", "else", ":", "json", "=", "filepath_or_buffer", "if", "lines", ":", "lines", "=", "list", "(", "StringIO", "(", "json", ".", "strip", "(", ")", ")", ")", "json", "=", "(", "(", "'['", "+", "','", ".", "join", "(", "lines", ")", ")", "+", "']'", ")", "obj", "=", "None", "if", "(", "typ", "==", "'frame'", ")", ":", "obj", "=", "FrameParser", "(", "json", ",", "orient", ",", "dtype", ",", "convert_axes", ",", "convert_dates", ",", "keep_default_dates", ",", "numpy", ",", "precise_float", ",", "date_unit", ")", ".", "parse", "(", ")", "if", "(", "(", "typ", "==", "'series'", ")", "or", "(", "obj", "is", "None", ")", ")", ":", "if", "(", "not", "isinstance", "(", "dtype", ",", "bool", ")", ")", ":", "dtype", "=", "dict", "(", "data", "=", "dtype", ")", "obj", "=", "SeriesParser", "(", "json", ",", "orient", ",", "dtype", ",", "convert_axes", ",", "convert_dates", ",", "keep_default_dates", ",", "numpy", ",", "precise_float", ",", "date_unit", ")", ".", "parse", "(", ")", "return", "obj" ]
read a json file if path is a file .
train
true
17,295
def path_elements(path): for p in path.split(path_separator()): (yield p)
[ "def", "path_elements", "(", "path", ")", ":", "for", "p", "in", "path", ".", "split", "(", "path_separator", "(", ")", ")", ":", "(", "yield", "p", ")" ]
given a path string value .
train
false
17,297
def _random_subset(seq, m): targets = set() while (len(targets) < m): x = random.choice(seq) targets.add(x) return targets
[ "def", "_random_subset", "(", "seq", ",", "m", ")", ":", "targets", "=", "set", "(", ")", "while", "(", "len", "(", "targets", ")", "<", "m", ")", ":", "x", "=", "random", ".", "choice", "(", "seq", ")", "targets", ".", "add", "(", "x", ")", "return", "targets" ]
return m unique elements from seq .
train
false
17,298
def _get_portage(): return reload(portage)
[ "def", "_get_portage", "(", ")", ":", "return", "reload", "(", "portage", ")" ]
portage module must be reloaded or it cant catch the changes in portage .
train
false
17,299
def int2gray(i): return (i ^ (i >> 1))
[ "def", "int2gray", "(", "i", ")", ":", "return", "(", "i", "^", "(", "i", ">>", "1", ")", ")" ]
returns the value of an integer in gray encoding .
train
false
17,300
@register.filter(name='str_to_dic') def str_to_dic(info): if ('{' in info): info_dic = ast.literal_eval(info).iteritems() else: info_dic = {} return info_dic
[ "@", "register", ".", "filter", "(", "name", "=", "'str_to_dic'", ")", "def", "str_to_dic", "(", "info", ")", ":", "if", "(", "'{'", "in", "info", ")", ":", "info_dic", "=", "ast", ".", "literal_eval", "(", "info", ")", ".", "iteritems", "(", ")", "else", ":", "info_dic", "=", "{", "}", "return", "info_dic" ]
str to list .
train
false
17,301
@skip('win32') def test_reflected_extension_property_ops(): t_list = [(complex.__dict__['real'], 'complex', 'float', 'real'), (complex.__dict__['imag'], 'complex', 'float', 'imag')] for (stuff, typename, returnType, propName) in t_list: expected = (((((('Get: ' + propName) + '(self: ') + typename) + ') -> ') + returnType) + newline) Assert(stuff.__doc__.startswith(expected), stuff.__doc__)
[ "@", "skip", "(", "'win32'", ")", "def", "test_reflected_extension_property_ops", "(", ")", ":", "t_list", "=", "[", "(", "complex", ".", "__dict__", "[", "'real'", "]", ",", "'complex'", ",", "'float'", ",", "'real'", ")", ",", "(", "complex", ".", "__dict__", "[", "'imag'", "]", ",", "'complex'", ",", "'float'", ",", "'imag'", ")", "]", "for", "(", "stuff", ",", "typename", ",", "returnType", ",", "propName", ")", "in", "t_list", ":", "expected", "=", "(", "(", "(", "(", "(", "(", "'Get: '", "+", "propName", ")", "+", "'(self: '", ")", "+", "typename", ")", "+", "') -> '", ")", "+", "returnType", ")", "+", "newline", ")", "Assert", "(", "stuff", ".", "__doc__", ".", "startswith", "(", "expected", ")", ",", "stuff", ".", "__doc__", ")" ]
test to hit ironpython .
train
false
17,302
def create_recurring_run(job_id, start_date, loop_period, loop_count): owner = models.User.current_user().login job = models.Job.objects.get(id=job_id) return job.create_recurring_job(start_date=start_date, loop_period=loop_period, loop_count=loop_count, owner=owner)
[ "def", "create_recurring_run", "(", "job_id", ",", "start_date", ",", "loop_period", ",", "loop_count", ")", ":", "owner", "=", "models", ".", "User", ".", "current_user", "(", ")", ".", "login", "job", "=", "models", ".", "Job", ".", "objects", ".", "get", "(", "id", "=", "job_id", ")", "return", "job", ".", "create_recurring_job", "(", "start_date", "=", "start_date", ",", "loop_period", "=", "loop_period", ",", "loop_count", "=", "loop_count", ",", "owner", "=", "owner", ")" ]
create a recurring job .
train
false
17,304
@requires_version('scipy', '0.10') def test_plot_raw_filtered(): raw = _get_raw() assert_raises(ValueError, raw.plot, lowpass=(raw.info['sfreq'] / 2.0)) assert_raises(ValueError, raw.plot, highpass=0) assert_raises(ValueError, raw.plot, lowpass=1, highpass=1) assert_raises(ValueError, raw.plot, lowpass=1, filtorder=0) assert_raises(ValueError, raw.plot, clipping='foo') raw.plot(lowpass=1, clipping='transparent') raw.plot(highpass=1, clipping='clamp') raw.plot(highpass=1, lowpass=2)
[ "@", "requires_version", "(", "'scipy'", ",", "'0.10'", ")", "def", "test_plot_raw_filtered", "(", ")", ":", "raw", "=", "_get_raw", "(", ")", "assert_raises", "(", "ValueError", ",", "raw", ".", "plot", ",", "lowpass", "=", "(", "raw", ".", "info", "[", "'sfreq'", "]", "/", "2.0", ")", ")", "assert_raises", "(", "ValueError", ",", "raw", ".", "plot", ",", "highpass", "=", "0", ")", "assert_raises", "(", "ValueError", ",", "raw", ".", "plot", ",", "lowpass", "=", "1", ",", "highpass", "=", "1", ")", "assert_raises", "(", "ValueError", ",", "raw", ".", "plot", ",", "lowpass", "=", "1", ",", "filtorder", "=", "0", ")", "assert_raises", "(", "ValueError", ",", "raw", ".", "plot", ",", "clipping", "=", "'foo'", ")", "raw", ".", "plot", "(", "lowpass", "=", "1", ",", "clipping", "=", "'transparent'", ")", "raw", ".", "plot", "(", "highpass", "=", "1", ",", "clipping", "=", "'clamp'", ")", "raw", ".", "plot", "(", "highpass", "=", "1", ",", "lowpass", "=", "2", ")" ]
test filtering of raw plots .
train
false
17,305
def test_scenario_fr_from_string(): lang = Language('fr') scenario = Scenario.from_string(SCENARIO, language=lang) assert_equals(scenario.name, u'Ajout de plusieurs cursus dans la base de mon universit\xe9') assert_equals(scenario.steps[0].hashes, [{'Nom': u"Science de l'Informatique", u'Dur\xe9e': '5 ans'}, {'Nom': u'Nutrition', u'Dur\xe9e': '4 ans'}])
[ "def", "test_scenario_fr_from_string", "(", ")", ":", "lang", "=", "Language", "(", "'fr'", ")", "scenario", "=", "Scenario", ".", "from_string", "(", "SCENARIO", ",", "language", "=", "lang", ")", "assert_equals", "(", "scenario", ".", "name", ",", "u'Ajout de plusieurs cursus dans la base de mon universit\\xe9'", ")", "assert_equals", "(", "scenario", ".", "steps", "[", "0", "]", ".", "hashes", ",", "[", "{", "'Nom'", ":", "u\"Science de l'Informatique\"", ",", "u'Dur\\xe9e'", ":", "'5 ans'", "}", ",", "{", "'Nom'", ":", "u'Nutrition'", ",", "u'Dur\\xe9e'", ":", "'4 ans'", "}", "]", ")" ]
language: fr -> scenario .
train
false
17,306
def extension(filename): return os.path.splitext(filename)[1]
[ "def", "extension", "(", "filename", ")", ":", "return", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]" ]
returns the extension in the given filename: "cat .
train
false
17,307
def View(env, resp): posts = forumdb.GetAllPosts() headers = [('Content-type', 'text/html')] resp('200 OK', headers) return [(HTML_WRAP % ''.join(((POST % p) for p in posts)))]
[ "def", "View", "(", "env", ",", "resp", ")", ":", "posts", "=", "forumdb", ".", "GetAllPosts", "(", ")", "headers", "=", "[", "(", "'Content-type'", ",", "'text/html'", ")", "]", "resp", "(", "'200 OK'", ",", "headers", ")", "return", "[", "(", "HTML_WRAP", "%", "''", ".", "join", "(", "(", "(", "POST", "%", "p", ")", "for", "p", "in", "posts", ")", ")", ")", "]" ]
view is the main page of the forum .
train
false
17,308
def _computeAllowedMethods(resource): allowedMethods = [] for name in prefixedMethodNames(resource.__class__, 'render_'): allowedMethods.append(name) return allowedMethods
[ "def", "_computeAllowedMethods", "(", "resource", ")", ":", "allowedMethods", "=", "[", "]", "for", "name", "in", "prefixedMethodNames", "(", "resource", ".", "__class__", ",", "'render_'", ")", ":", "allowedMethods", ".", "append", "(", "name", ")", "return", "allowedMethods" ]
compute the allowed methods on a c{resource} based on defined render_foo methods .
train
false
17,310
def _getExcludedTLSProtocols(oldest, newest): versions = list(TLSVersion.iterconstants()) excludedVersions = [x for x in versions[:versions.index(oldest)]] if newest: excludedVersions.extend([x for x in versions[versions.index(newest):]]) return excludedVersions
[ "def", "_getExcludedTLSProtocols", "(", "oldest", ",", "newest", ")", ":", "versions", "=", "list", "(", "TLSVersion", ".", "iterconstants", "(", ")", ")", "excludedVersions", "=", "[", "x", "for", "x", "in", "versions", "[", ":", "versions", ".", "index", "(", "oldest", ")", "]", "]", "if", "newest", ":", "excludedVersions", ".", "extend", "(", "[", "x", "for", "x", "in", "versions", "[", "versions", ".", "index", "(", "newest", ")", ":", "]", "]", ")", "return", "excludedVersions" ]
given a pair of l{tlsversion} constants .
train
false
17,311
def custom_analyze_title(title): nt = title.split(' aka ')[0] if nt: title = nt if (not title): return {} return analyze_title(title)
[ "def", "custom_analyze_title", "(", "title", ")", ":", "nt", "=", "title", ".", "split", "(", "' aka '", ")", "[", "0", "]", "if", "nt", ":", "title", "=", "nt", "if", "(", "not", "title", ")", ":", "return", "{", "}", "return", "analyze_title", "(", "title", ")" ]
remove garbage notes after the .
train
false
17,313
def _find_network_id(cs, net_name): if cs.has_neutron(): return _find_network_id_neutron(cs, net_name) else: want_version = api_versions.APIVersion('2.35') cur_version = cs.api_version if (cs.api_version > want_version): cs.api_version = want_version try: return _find_network_id_novanet(cs, net_name) finally: cs.api_version = cur_version
[ "def", "_find_network_id", "(", "cs", ",", "net_name", ")", ":", "if", "cs", ".", "has_neutron", "(", ")", ":", "return", "_find_network_id_neutron", "(", "cs", ",", "net_name", ")", "else", ":", "want_version", "=", "api_versions", ".", "APIVersion", "(", "'2.35'", ")", "cur_version", "=", "cs", ".", "api_version", "if", "(", "cs", ".", "api_version", ">", "want_version", ")", ":", "cs", ".", "api_version", "=", "want_version", "try", ":", "return", "_find_network_id_novanet", "(", "cs", ",", "net_name", ")", "finally", ":", "cs", ".", "api_version", "=", "cur_version" ]
find the network id for a network name .
train
false
17,314
def CCI(barDs, count, timeperiod=(- (2 ** 31))): return call_talib_with_hlc(barDs, count, talib.CCI, timeperiod)
[ "def", "CCI", "(", "barDs", ",", "count", ",", "timeperiod", "=", "(", "-", "(", "2", "**", "31", ")", ")", ")", ":", "return", "call_talib_with_hlc", "(", "barDs", ",", "count", ",", "talib", ".", "CCI", ",", "timeperiod", ")" ]
commodity channel index .
train
false
17,315
def _make_tensor_descriptor_array(xs): descs = [] for x in xs: if (x.ndim < 3): shape = (x.shape + ((1,) * (3 - x.ndim))) x = x.reshape(shape) desc = cudnn.create_tensor_nd_descriptor(x) descs.append(desc) return PointerArray([d.value for d in descs], descs)
[ "def", "_make_tensor_descriptor_array", "(", "xs", ")", ":", "descs", "=", "[", "]", "for", "x", "in", "xs", ":", "if", "(", "x", ".", "ndim", "<", "3", ")", ":", "shape", "=", "(", "x", ".", "shape", "+", "(", "(", "1", ",", ")", "*", "(", "3", "-", "x", ".", "ndim", ")", ")", ")", "x", "=", "x", ".", "reshape", "(", "shape", ")", "desc", "=", "cudnn", ".", "create_tensor_nd_descriptor", "(", "x", ")", "descs", ".", "append", "(", "desc", ")", "return", "PointerArray", "(", "[", "d", ".", "value", "for", "d", "in", "descs", "]", ",", "descs", ")" ]
make an array of pointers denoting pointers of tensor descriptors .
train
false
17,316
@profiler.trace def firewall_list_for_tenant(request, tenant_id, **kwargs): return firewall_list(request, tenant_id=tenant_id, **kwargs)
[ "@", "profiler", ".", "trace", "def", "firewall_list_for_tenant", "(", "request", ",", "tenant_id", ",", "**", "kwargs", ")", ":", "return", "firewall_list", "(", "request", ",", "tenant_id", "=", "tenant_id", ",", "**", "kwargs", ")" ]
return a firewall list available for the tenant .
train
false
17,317
def register_tag(cls): json_tags[(TAG_PREFIX + getattr(cls, 'json_tag'))] = cls return cls
[ "def", "register_tag", "(", "cls", ")", ":", "json_tags", "[", "(", "TAG_PREFIX", "+", "getattr", "(", "cls", ",", "'json_tag'", ")", ")", "]", "=", "cls", "return", "cls" ]
decorates a class to register its json tag .
train
false
17,318
def internal_wininst_name(arch): ext = '.exe' return ('scipy-%s-%s%s' % (FULLVERSION, arch, ext))
[ "def", "internal_wininst_name", "(", "arch", ")", ":", "ext", "=", "'.exe'", "return", "(", "'scipy-%s-%s%s'", "%", "(", "FULLVERSION", ",", "arch", ",", "ext", ")", ")" ]
return the name of the wininst as it will be inside the superpack (i .
train
false
17,319
def _is_port_name(name): port_name = re.compile('^[a-z0-9]{1,15}$') if port_name.match(name): return True else: return False
[ "def", "_is_port_name", "(", "name", ")", ":", "port_name", "=", "re", ".", "compile", "(", "'^[a-z0-9]{1,15}$'", ")", "if", "port_name", ".", "match", "(", "name", ")", ":", "return", "True", "else", ":", "return", "False" ]
check that name is iana service: an alphanumeric string .
train
true
17,320
def check_set(set=None, family='ipv4'): if (not set): return 'Error: Set needs to be specified' setinfo = _find_set_info(set) if (not setinfo): return False return True
[ "def", "check_set", "(", "set", "=", "None", ",", "family", "=", "'ipv4'", ")", ":", "if", "(", "not", "set", ")", ":", "return", "'Error: Set needs to be specified'", "setinfo", "=", "_find_set_info", "(", "set", ")", "if", "(", "not", "setinfo", ")", ":", "return", "False", "return", "True" ]
check that given ipset set exists .
train
true
17,321
def _bti_open(fname, *args, **kwargs): if isinstance(fname, six.string_types): return open(fname, *args, **kwargs) elif isinstance(fname, six.BytesIO): return _bytes_io_mock_context(fname) else: raise RuntimeError('Cannot mock this.')
[ "def", "_bti_open", "(", "fname", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "isinstance", "(", "fname", ",", "six", ".", "string_types", ")", ":", "return", "open", "(", "fname", ",", "*", "args", ",", "**", "kwargs", ")", "elif", "isinstance", "(", "fname", ",", "six", ".", "BytesIO", ")", ":", "return", "_bytes_io_mock_context", "(", "fname", ")", "else", ":", "raise", "RuntimeError", "(", "'Cannot mock this.'", ")" ]
handle bytesio .
train
false
17,322
def test_gcrs_self_transform_closeby(): t = Time(u'2014-12-25T07:00') moon_geocentric = SkyCoord(GCRS((318.10579159 * u.deg), ((-11.65281165) * u.deg), (365042.64880308 * u.km), obstime=t)) obsgeoloc = ([(-5592982.59658935), (-63054.1948592), 3059763.90102216] * u.m) obsgeovel = (([4.59798494, (-407.84677071), 0.0] * u.m) / u.s) moon_lapalma = SkyCoord(GCRS((318.7048445 * u.deg), ((-11.98761996) * u.deg), (369722.8231031 * u.km), obstime=t, obsgeoloc=obsgeoloc, obsgeovel=obsgeovel)) transformed = moon_geocentric.transform_to(moon_lapalma.frame) delta = transformed.separation_3d(moon_lapalma) assert_allclose(delta, (0.0 * u.m), atol=(1 * u.m))
[ "def", "test_gcrs_self_transform_closeby", "(", ")", ":", "t", "=", "Time", "(", "u'2014-12-25T07:00'", ")", "moon_geocentric", "=", "SkyCoord", "(", "GCRS", "(", "(", "318.10579159", "*", "u", ".", "deg", ")", ",", "(", "(", "-", "11.65281165", ")", "*", "u", ".", "deg", ")", ",", "(", "365042.64880308", "*", "u", ".", "km", ")", ",", "obstime", "=", "t", ")", ")", "obsgeoloc", "=", "(", "[", "(", "-", "5592982.59658935", ")", ",", "(", "-", "63054.1948592", ")", ",", "3059763.90102216", "]", "*", "u", ".", "m", ")", "obsgeovel", "=", "(", "(", "[", "4.59798494", ",", "(", "-", "407.84677071", ")", ",", "0.0", "]", "*", "u", ".", "m", ")", "/", "u", ".", "s", ")", "moon_lapalma", "=", "SkyCoord", "(", "GCRS", "(", "(", "318.7048445", "*", "u", ".", "deg", ")", ",", "(", "(", "-", "11.98761996", ")", "*", "u", ".", "deg", ")", ",", "(", "369722.8231031", "*", "u", ".", "km", ")", ",", "obstime", "=", "t", ",", "obsgeoloc", "=", "obsgeoloc", ",", "obsgeovel", "=", "obsgeovel", ")", ")", "transformed", "=", "moon_geocentric", ".", "transform_to", "(", "moon_lapalma", ".", "frame", ")", "delta", "=", "transformed", ".", "separation_3d", "(", "moon_lapalma", ")", "assert_allclose", "(", "delta", ",", "(", "0.0", "*", "u", ".", "m", ")", ",", "atol", "=", "(", "1", "*", "u", ".", "m", ")", ")" ]
tests gcrs self transform for objects which are nearby and thus have reasonable parallax .
train
false
17,323
def safer_yield_per(query, id_field, start_id, count): cur_id = start_id while True: results = query.filter((id_field >= cur_id)).order_by(id_field).limit(count).all() if (not results): return for result in results: (yield result) cur_id = (results[(-1)].id + 1)
[ "def", "safer_yield_per", "(", "query", ",", "id_field", ",", "start_id", ",", "count", ")", ":", "cur_id", "=", "start_id", "while", "True", ":", "results", "=", "query", ".", "filter", "(", "(", "id_field", ">=", "cur_id", ")", ")", ".", "order_by", "(", "id_field", ")", ".", "limit", "(", "count", ")", ".", "all", "(", ")", "if", "(", "not", "results", ")", ":", "return", "for", "result", "in", "results", ":", "(", "yield", "result", ")", "cur_id", "=", "(", "results", "[", "(", "-", "1", ")", "]", ".", "id", "+", "1", ")" ]
incautious execution of for result in query .
train
false
17,324
def add_s(i): if (i > 1): return 's' else: return ''
[ "def", "add_s", "(", "i", ")", ":", "if", "(", "i", ">", "1", ")", ":", "return", "'s'", "else", ":", "return", "''" ]
return an "s" when i > 1 .
train
false
17,325
def auth_sysadmins_check(action): @functools.wraps(action) def wrapper(context, data_dict): return action(context, data_dict) wrapper.auth_sysadmins_check = True return wrapper
[ "def", "auth_sysadmins_check", "(", "action", ")", ":", "@", "functools", ".", "wraps", "(", "action", ")", "def", "wrapper", "(", "context", ",", "data_dict", ")", ":", "return", "action", "(", "context", ",", "data_dict", ")", "wrapper", ".", "auth_sysadmins_check", "=", "True", "return", "wrapper" ]
a decorator that prevents sysadmins from being automatically authorized to call an action function .
train
false
17,326
def unix_path_to_win(path, root_prefix=u''): if ((len(path) > 1) and ((u';' in path) or ((path[1] == u':') and (path.count(u':') == 1)))): return path.replace(u'/', u'\\') path_re = (root_prefix + u'/([a-zA-Z])(/(?:(?![:\\s]/)[^:*?"<>])*)') def _translation(found_path): return u'{0}:{1}'.format(found_path.group(1), found_path.group(2).replace(u'/', u'\\')) path = re.sub(path_re, _translation, path) path = re.sub(u':([a-zA-Z]):\\\\', u';\\1:\\\\', path) return path
[ "def", "unix_path_to_win", "(", "path", ",", "root_prefix", "=", "u''", ")", ":", "if", "(", "(", "len", "(", "path", ")", ">", "1", ")", "and", "(", "(", "u';'", "in", "path", ")", "or", "(", "(", "path", "[", "1", "]", "==", "u':'", ")", "and", "(", "path", ".", "count", "(", "u':'", ")", "==", "1", ")", ")", ")", ")", ":", "return", "path", ".", "replace", "(", "u'/'", ",", "u'\\\\'", ")", "path_re", "=", "(", "root_prefix", "+", "u'/([a-zA-Z])(/(?:(?![:\\\\s]/)[^:*?\"<>])*)'", ")", "def", "_translation", "(", "found_path", ")", ":", "return", "u'{0}:{1}'", ".", "format", "(", "found_path", ".", "group", "(", "1", ")", ",", "found_path", ".", "group", "(", "2", ")", ".", "replace", "(", "u'/'", ",", "u'\\\\'", ")", ")", "path", "=", "re", ".", "sub", "(", "path_re", ",", "_translation", ",", "path", ")", "path", "=", "re", ".", "sub", "(", "u':([a-zA-Z]):\\\\\\\\'", ",", "u';\\\\1:\\\\\\\\'", ",", "path", ")", "return", "path" ]
convert a path or :-separated string of paths into a windows representation does not add cygdrive .
train
false
17,327
def transfer_get_all_by_project(context, project_id): return IMPL.transfer_get_all_by_project(context, project_id)
[ "def", "transfer_get_all_by_project", "(", "context", ",", "project_id", ")", ":", "return", "IMPL", ".", "transfer_get_all_by_project", "(", "context", ",", "project_id", ")" ]
get all volume transfer records for specified project .
train
false
17,329
def list_srv_types(package, include_depends): types = roslib.resources.list_package_resources(package, include_depends, 'srv', _srv_filter) return [x[:(- len(EXT))] for x in types]
[ "def", "list_srv_types", "(", "package", ",", "include_depends", ")", ":", "types", "=", "roslib", ".", "resources", ".", "list_package_resources", "(", "package", ",", "include_depends", ",", "'srv'", ",", "_srv_filter", ")", "return", "[", "x", "[", ":", "(", "-", "len", "(", "EXT", ")", ")", "]", "for", "x", "in", "types", "]" ]
list all services in the specified package .
train
false
17,331
@register(u'forward-word') def forward_word(event): buff = event.current_buffer pos = buff.document.find_next_word_ending(count=event.arg) if pos: buff.cursor_position += pos
[ "@", "register", "(", "u'forward-word'", ")", "def", "forward_word", "(", "event", ")", ":", "buff", "=", "event", ".", "current_buffer", "pos", "=", "buff", ".", "document", ".", "find_next_word_ending", "(", "count", "=", "event", ".", "arg", ")", "if", "pos", ":", "buff", ".", "cursor_position", "+=", "pos" ]
move forward to the end of the next word .
train
true
17,332
def has_x11(): try: from AnyQt.QtX11Extras import QX11Info return True except ImportError: return False
[ "def", "has_x11", "(", ")", ":", "try", ":", "from", "AnyQt", ".", "QtX11Extras", "import", "QX11Info", "return", "True", "except", "ImportError", ":", "return", "False" ]
is qt build against x11 server .
train
false
17,333
def uniform_layout_helper(items, contents_rect, expanding, spacing): if (len(items) == 0): return spacing_space = ((len(items) - 1) * spacing) if (expanding == Qt.Horizontal): space = (contents_rect.width() - spacing_space) setter = (lambda w, s: w.setFixedWidth(max(s, 0))) else: space = (contents_rect.height() - spacing_space) setter = (lambda w, s: w.setFixedHeight(max(s, 0))) base_size = (space / len(items)) remainder = (space % len(items)) for (i, item) in enumerate(items): item_size = (base_size + (1 if (i < remainder) else 0)) setter(item, item_size)
[ "def", "uniform_layout_helper", "(", "items", ",", "contents_rect", ",", "expanding", ",", "spacing", ")", ":", "if", "(", "len", "(", "items", ")", "==", "0", ")", ":", "return", "spacing_space", "=", "(", "(", "len", "(", "items", ")", "-", "1", ")", "*", "spacing", ")", "if", "(", "expanding", "==", "Qt", ".", "Horizontal", ")", ":", "space", "=", "(", "contents_rect", ".", "width", "(", ")", "-", "spacing_space", ")", "setter", "=", "(", "lambda", "w", ",", "s", ":", "w", ".", "setFixedWidth", "(", "max", "(", "s", ",", "0", ")", ")", ")", "else", ":", "space", "=", "(", "contents_rect", ".", "height", "(", ")", "-", "spacing_space", ")", "setter", "=", "(", "lambda", "w", ",", "s", ":", "w", ".", "setFixedHeight", "(", "max", "(", "s", ",", "0", ")", ")", ")", "base_size", "=", "(", "space", "/", "len", "(", "items", ")", ")", "remainder", "=", "(", "space", "%", "len", "(", "items", ")", ")", "for", "(", "i", ",", "item", ")", "in", "enumerate", "(", "items", ")", ":", "item_size", "=", "(", "base_size", "+", "(", "1", "if", "(", "i", "<", "remainder", ")", "else", "0", ")", ")", "setter", "(", "item", ",", "item_size", ")" ]
set fixed sizes on items so they can be laid out in contents_rect and fill the whole space .
train
false
17,334
def update_hook(node_settings): logger.warn('Updating GitHub hook on node {0}'.format(node_settings.owner._id)) connection = GitHub.from_settings(node_settings.user_settings) repo = connection.repo(node_settings.user, node_settings.repo) hook = repo.hook(node_settings.hook_id) if (hook is None): logger.warn('Hook {0} not found'.format(node_settings.hook_id)) return secret = utils.make_hook_secret() config = hook.config config['content_type'] = github_settings.HOOK_CONTENT_TYPE config['secret'] = secret hook.edit(config=config) node_settings.hook_secret = secret node_settings.save()
[ "def", "update_hook", "(", "node_settings", ")", ":", "logger", ".", "warn", "(", "'Updating GitHub hook on node {0}'", ".", "format", "(", "node_settings", ".", "owner", ".", "_id", ")", ")", "connection", "=", "GitHub", ".", "from_settings", "(", "node_settings", ".", "user_settings", ")", "repo", "=", "connection", ".", "repo", "(", "node_settings", ".", "user", ",", "node_settings", ".", "repo", ")", "hook", "=", "repo", ".", "hook", "(", "node_settings", ".", "hook_id", ")", "if", "(", "hook", "is", "None", ")", ":", "logger", ".", "warn", "(", "'Hook {0} not found'", ".", "format", "(", "node_settings", ".", "hook_id", ")", ")", "return", "secret", "=", "utils", ".", "make_hook_secret", "(", ")", "config", "=", "hook", ".", "config", "config", "[", "'content_type'", "]", "=", "github_settings", ".", "HOOK_CONTENT_TYPE", "config", "[", "'secret'", "]", "=", "secret", "hook", ".", "edit", "(", "config", "=", "config", ")", "node_settings", ".", "hook_secret", "=", "secret", "node_settings", ".", "save", "(", ")" ]
discard the existing webhook for a github node add-on and create a new one .
train
false
17,335
def _is_complete_graph(G): if (G.number_of_selfloops() > 0): raise nx.NetworkXError('Self loop found in _is_complete_graph()') n = G.number_of_nodes() if (n < 2): return True e = G.number_of_edges() max_edges = ((n * (n - 1)) / 2) return (e == max_edges)
[ "def", "_is_complete_graph", "(", "G", ")", ":", "if", "(", "G", ".", "number_of_selfloops", "(", ")", ">", "0", ")", ":", "raise", "nx", ".", "NetworkXError", "(", "'Self loop found in _is_complete_graph()'", ")", "n", "=", "G", ".", "number_of_nodes", "(", ")", "if", "(", "n", "<", "2", ")", ":", "return", "True", "e", "=", "G", ".", "number_of_edges", "(", ")", "max_edges", "=", "(", "(", "n", "*", "(", "n", "-", "1", ")", ")", "/", "2", ")", "return", "(", "e", "==", "max_edges", ")" ]
returns true if g is a complete graph .
train
false
17,336
def validate_date(year, month, day, hour, minute): valid = True if (year < 0): valid = False if ((month < 1) or (month > 12)): valid = False if ((day < 1) or (day > 31)): valid = False if ((hour < 0) or (hour > 23)): valid = False if ((minute < 0) or (minute > 59)): valid = False return valid
[ "def", "validate_date", "(", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ")", ":", "valid", "=", "True", "if", "(", "year", "<", "0", ")", ":", "valid", "=", "False", "if", "(", "(", "month", "<", "1", ")", "or", "(", "month", ">", "12", ")", ")", ":", "valid", "=", "False", "if", "(", "(", "day", "<", "1", ")", "or", "(", "day", ">", "31", ")", ")", ":", "valid", "=", "False", "if", "(", "(", "hour", "<", "0", ")", "or", "(", "hour", ">", "23", ")", ")", ":", "valid", "=", "False", "if", "(", "(", "minute", "<", "0", ")", "or", "(", "minute", ">", "59", ")", ")", ":", "valid", "=", "False", "return", "valid" ]
avoid corrupting db if bad dates come in .
train
false
17,338
def hrm_credential_controller(): if (current.session.s3.hrm.mode is not None): current.session.error = current.T('Access denied') redirect(URL(f='index')) s3 = current.response.s3 def prep(r): table = r.table if (r.method in ('create', 'create.popup', 'update', 'update.popup')): person_id = r.get_vars.get('~.person_id', None) if person_id: field = table.person_id field.default = person_id field.readable = field.writable = False if r.record: table.person_id.comment = None table.person_id.writable = False return True s3.prep = prep return current.rest_controller('hrm', 'credential')
[ "def", "hrm_credential_controller", "(", ")", ":", "if", "(", "current", ".", "session", ".", "s3", ".", "hrm", ".", "mode", "is", "not", "None", ")", ":", "current", ".", "session", ".", "error", "=", "current", ".", "T", "(", "'Access denied'", ")", "redirect", "(", "URL", "(", "f", "=", "'index'", ")", ")", "s3", "=", "current", ".", "response", ".", "s3", "def", "prep", "(", "r", ")", ":", "table", "=", "r", ".", "table", "if", "(", "r", ".", "method", "in", "(", "'create'", ",", "'create.popup'", ",", "'update'", ",", "'update.popup'", ")", ")", ":", "person_id", "=", "r", ".", "get_vars", ".", "get", "(", "'~.person_id'", ",", "None", ")", "if", "person_id", ":", "field", "=", "table", ".", "person_id", "field", ".", "default", "=", "person_id", "field", ".", "readable", "=", "field", ".", "writable", "=", "False", "if", "r", ".", "record", ":", "table", ".", "person_id", ".", "comment", "=", "None", "table", ".", "person_id", ".", "writable", "=", "False", "return", "True", "s3", ".", "prep", "=", "prep", "return", "current", ".", "rest_controller", "(", "'hrm'", ",", "'credential'", ")" ]
restful crud controller - could be used for searching for people by skill - used for adding/editing on profile page .
train
false
17,340
def start_web_view(options, experiment_config, chooser): from spearmint.web.app import app port = get_available_port(options.web_status_port) print ('Using port: ' + str(port)) if options.web_status_host: print ('Listening at: ' + str(options.web_status_host)) app.set_experiment_config(experiment_config) app.set_chooser(options.chooser_module, chooser) debug = (options.verbose == True) start_web_app = (lambda : app.run(debug=debug, port=port, host=options.web_status_host)) proc = multiprocessing.Process(target=start_web_app) proc.start() return proc
[ "def", "start_web_view", "(", "options", ",", "experiment_config", ",", "chooser", ")", ":", "from", "spearmint", ".", "web", ".", "app", "import", "app", "port", "=", "get_available_port", "(", "options", ".", "web_status_port", ")", "print", "(", "'Using port: '", "+", "str", "(", "port", ")", ")", "if", "options", ".", "web_status_host", ":", "print", "(", "'Listening at: '", "+", "str", "(", "options", ".", "web_status_host", ")", ")", "app", ".", "set_experiment_config", "(", "experiment_config", ")", "app", ".", "set_chooser", "(", "options", ".", "chooser_module", ",", "chooser", ")", "debug", "=", "(", "options", ".", "verbose", "==", "True", ")", "start_web_app", "=", "(", "lambda", ":", "app", ".", "run", "(", "debug", "=", "debug", ",", "port", "=", "port", ",", "host", "=", "options", ".", "web_status_host", ")", ")", "proc", "=", "multiprocessing", ".", "Process", "(", "target", "=", "start_web_app", ")", "proc", ".", "start", "(", ")", "return", "proc" ]
start the web view in a separate process .
train
false
17,343
@login_required def complete_associate(request, redirect_field_name=REDIRECT_FIELD_NAME, template_failure='authopenid/associate.html', openid_form=AssociateOpenID, redirect_name=None, on_success=associate_success, on_failure=associate_failure, send_email=True, extra_context=None): return complete(request, on_success, on_failure, (get_url_host(request) + reverse('user_complete_associate')), redirect_field_name=redirect_field_name, openid_form=openid_form, template_failure=template_failure, redirect_name=redirect_name, send_email=send_email, extra_context=extra_context)
[ "@", "login_required", "def", "complete_associate", "(", "request", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ",", "template_failure", "=", "'authopenid/associate.html'", ",", "openid_form", "=", "AssociateOpenID", ",", "redirect_name", "=", "None", ",", "on_success", "=", "associate_success", ",", "on_failure", "=", "associate_failure", ",", "send_email", "=", "True", ",", "extra_context", "=", "None", ")", ":", "return", "complete", "(", "request", ",", "on_success", ",", "on_failure", ",", "(", "get_url_host", "(", "request", ")", "+", "reverse", "(", "'user_complete_associate'", ")", ")", ",", "redirect_field_name", "=", "redirect_field_name", ",", "openid_form", "=", "openid_form", ",", "template_failure", "=", "template_failure", ",", "redirect_name", "=", "redirect_name", ",", "send_email", "=", "send_email", ",", "extra_context", "=", "extra_context", ")" ]
in case of complete association with openid .
train
false
17,344
@pytest.mark.cmd @pytest.mark.django_db def test_export_path_unknown(): with pytest.raises(CommandError) as e: call_command('export', '--path=/af/unknown') assert ("Could not find store matching '/af/unknown'" in str(e))
[ "@", "pytest", ".", "mark", ".", "cmd", "@", "pytest", ".", "mark", ".", "django_db", "def", "test_export_path_unknown", "(", ")", ":", "with", "pytest", ".", "raises", "(", "CommandError", ")", "as", "e", ":", "call_command", "(", "'export'", ",", "'--path=/af/unknown'", ")", "assert", "(", "\"Could not find store matching '/af/unknown'\"", "in", "str", "(", "e", ")", ")" ]
export an unknown path .
train
false
17,345
def generate_unique_node(): return str(uuid.uuid1())
[ "def", "generate_unique_node", "(", ")", ":", "return", "str", "(", "uuid", ".", "uuid1", "(", ")", ")" ]
generate a unique node label .
train
false
17,346
def _format_optvalue(value, script=False): if script: value = _stringify(value) elif isinstance(value, (list, tuple)): value = _join(value) return value
[ "def", "_format_optvalue", "(", "value", ",", "script", "=", "False", ")", ":", "if", "script", ":", "value", "=", "_stringify", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "value", "=", "_join", "(", "value", ")", "return", "value" ]
internal function .
train
false
17,347
def get_cpu_vendor_name(): vendors_map = {'intel': ('GenuineIntel',), 'amd': ('AMD',), 'power7': ('POWER7',)} cpu_info = get_cpu_info() for (vendor, identifiers) in vendors_map.items(): for identifier in identifiers: if list_grep(cpu_info, identifier): return vendor return None
[ "def", "get_cpu_vendor_name", "(", ")", ":", "vendors_map", "=", "{", "'intel'", ":", "(", "'GenuineIntel'", ",", ")", ",", "'amd'", ":", "(", "'AMD'", ",", ")", ",", "'power7'", ":", "(", "'POWER7'", ",", ")", "}", "cpu_info", "=", "get_cpu_info", "(", ")", "for", "(", "vendor", ",", "identifiers", ")", "in", "vendors_map", ".", "items", "(", ")", ":", "for", "identifier", "in", "identifiers", ":", "if", "list_grep", "(", "cpu_info", ",", "identifier", ")", ":", "return", "vendor", "return", "None" ]
get the current cpu vendor name :returns: string intel or amd or power7 depending on the current cpu architecture .
train
false
17,348
def find_descriptor(desc, find_all=False, custom_match=None, **args): def desc_iter(**kwargs): for d in desc: tests = ((val == getattr(d, key)) for (key, val) in kwargs.items()) if (_interop._all(tests) and ((custom_match is None) or custom_match(d))): (yield d) if find_all: return desc_iter(**args) else: try: return _interop._next(desc_iter(**args)) except StopIteration: return None
[ "def", "find_descriptor", "(", "desc", ",", "find_all", "=", "False", ",", "custom_match", "=", "None", ",", "**", "args", ")", ":", "def", "desc_iter", "(", "**", "kwargs", ")", ":", "for", "d", "in", "desc", ":", "tests", "=", "(", "(", "val", "==", "getattr", "(", "d", ",", "key", ")", ")", "for", "(", "key", ",", "val", ")", "in", "kwargs", ".", "items", "(", ")", ")", "if", "(", "_interop", ".", "_all", "(", "tests", ")", "and", "(", "(", "custom_match", "is", "None", ")", "or", "custom_match", "(", "d", ")", ")", ")", ":", "(", "yield", "d", ")", "if", "find_all", ":", "return", "desc_iter", "(", "**", "args", ")", "else", ":", "try", ":", "return", "_interop", ".", "_next", "(", "desc_iter", "(", "**", "args", ")", ")", "except", "StopIteration", ":", "return", "None" ]
find an inner descriptor .
train
true
17,349
def on_reply_save(sender, instance, created, **kwargs): answer = instance year = answer.created.year creator = answer.creator if created: from kitsune.questions.tasks import maybe_award_badge maybe_award_badge.delay(QUESTIONS_BADGES['answer-badge'], year, creator)
[ "def", "on_reply_save", "(", "sender", ",", "instance", ",", "created", ",", "**", "kwargs", ")", ":", "answer", "=", "instance", "year", "=", "answer", ".", "created", ".", "year", "creator", "=", "answer", ".", "creator", "if", "created", ":", "from", "kitsune", ".", "questions", ".", "tasks", "import", "maybe_award_badge", "maybe_award_badge", ".", "delay", "(", "QUESTIONS_BADGES", "[", "'answer-badge'", "]", ",", "year", ",", "creator", ")" ]
handle the reply save signal .
train
false
17,350
def _epochs_axes_onclick(event, params): reject_color = (0.8, 0.8, 0.8) ax = event.inaxes if (event.inaxes is None): return p = params here = vars(ax)[p['axes_handler'][0]] if (here.get('reject', None) is False): idx = here['idx'] if (idx not in p['reject_idx']): p['reject_idx'].append(idx) for l in ax.lines: l.set_color(reject_color) here['reject'] = True elif (here.get('reject', None) is True): idx = here['idx'] if (idx in p['reject_idx']): p['reject_idx'].pop(p['reject_idx'].index(idx)) good_lines = [ax.lines[k] for k in p['good_ch_idx']] for l in good_lines: l.set_color('k') if (p['bad_ch_idx'] is not None): bad_lines = ax.lines[(- len(p['bad_ch_idx'])):] for l in bad_lines: l.set_color('r') here['reject'] = False ax.get_figure().canvas.draw()
[ "def", "_epochs_axes_onclick", "(", "event", ",", "params", ")", ":", "reject_color", "=", "(", "0.8", ",", "0.8", ",", "0.8", ")", "ax", "=", "event", ".", "inaxes", "if", "(", "event", ".", "inaxes", "is", "None", ")", ":", "return", "p", "=", "params", "here", "=", "vars", "(", "ax", ")", "[", "p", "[", "'axes_handler'", "]", "[", "0", "]", "]", "if", "(", "here", ".", "get", "(", "'reject'", ",", "None", ")", "is", "False", ")", ":", "idx", "=", "here", "[", "'idx'", "]", "if", "(", "idx", "not", "in", "p", "[", "'reject_idx'", "]", ")", ":", "p", "[", "'reject_idx'", "]", ".", "append", "(", "idx", ")", "for", "l", "in", "ax", ".", "lines", ":", "l", ".", "set_color", "(", "reject_color", ")", "here", "[", "'reject'", "]", "=", "True", "elif", "(", "here", ".", "get", "(", "'reject'", ",", "None", ")", "is", "True", ")", ":", "idx", "=", "here", "[", "'idx'", "]", "if", "(", "idx", "in", "p", "[", "'reject_idx'", "]", ")", ":", "p", "[", "'reject_idx'", "]", ".", "pop", "(", "p", "[", "'reject_idx'", "]", ".", "index", "(", "idx", ")", ")", "good_lines", "=", "[", "ax", ".", "lines", "[", "k", "]", "for", "k", "in", "p", "[", "'good_ch_idx'", "]", "]", "for", "l", "in", "good_lines", ":", "l", ".", "set_color", "(", "'k'", ")", "if", "(", "p", "[", "'bad_ch_idx'", "]", "is", "not", "None", ")", ":", "bad_lines", "=", "ax", ".", "lines", "[", "(", "-", "len", "(", "p", "[", "'bad_ch_idx'", "]", ")", ")", ":", "]", "for", "l", "in", "bad_lines", ":", "l", ".", "set_color", "(", "'r'", ")", "here", "[", "'reject'", "]", "=", "False", "ax", ".", "get_figure", "(", ")", ".", "canvas", ".", "draw", "(", ")" ]
handle epochs axes click .
train
false
17,351
def get_phantomjs_screenshot(url, screenshot_path, wait, width=1000, height=1000): phantomjs = pytest.config.getoption('phantomjs') cmd = [phantomjs, join(dirname(__file__), 'phantomjs_screenshot.js'), url, screenshot_path, str(wait), str(width), str(height)] info(('Running command: %s' % ' '.join(cmd))) try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.wait() except OSError: fail(('Failed to run: %s' % ' '.join(cmd))) sys.exit(1) return json.loads(proc.stdout.read().decode('utf-8'))
[ "def", "get_phantomjs_screenshot", "(", "url", ",", "screenshot_path", ",", "wait", ",", "width", "=", "1000", ",", "height", "=", "1000", ")", ":", "phantomjs", "=", "pytest", ".", "config", ".", "getoption", "(", "'phantomjs'", ")", "cmd", "=", "[", "phantomjs", ",", "join", "(", "dirname", "(", "__file__", ")", ",", "'phantomjs_screenshot.js'", ")", ",", "url", ",", "screenshot_path", ",", "str", "(", "wait", ")", ",", "str", "(", "width", ")", ",", "str", "(", "height", ")", "]", "info", "(", "(", "'Running command: %s'", "%", "' '", ".", "join", "(", "cmd", ")", ")", ")", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "proc", ".", "wait", "(", ")", "except", "OSError", ":", "fail", "(", "(", "'Failed to run: %s'", "%", "' '", ".", "join", "(", "cmd", ")", ")", ")", "sys", ".", "exit", "(", "1", ")", "return", "json", ".", "loads", "(", "proc", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")" ]
wait is in milliseconds .
train
false
17,353
def DEFINE_constant_string(name, default, help): CONFIG.AddOption(type_info.String(name=name, default=(default or ''), description=help), constant=True)
[ "def", "DEFINE_constant_string", "(", "name", ",", "default", ",", "help", ")", ":", "CONFIG", ".", "AddOption", "(", "type_info", ".", "String", "(", "name", "=", "name", ",", "default", "=", "(", "default", "or", "''", ")", ",", "description", "=", "help", ")", ",", "constant", "=", "True", ")" ]
a helper for defining constant strings .
train
true
17,356
def table(contents, heading=True, colw=None, cwunit='dxa', tblw=0, twunit='auto', borders={}, celstyle=None): table = makeelement('tbl') columns = len(contents[0]) tableprops = makeelement('tblPr') tablestyle = makeelement('tblStyle', attributes={'val': ''}) tableprops.append(tablestyle) tablewidth = makeelement('tblW', attributes={'w': str(tblw), 'type': str(twunit)}) tableprops.append(tablewidth) if len(borders.keys()): tableborders = makeelement('tblBorders') for b in ['top', 'left', 'bottom', 'right', 'insideH', 'insideV']: if ((b in borders.keys()) or ('all' in borders.keys())): k = ('all' if ('all' in borders.keys()) else b) attrs = {} for a in borders[k].keys(): attrs[a] = unicode(borders[k][a]) borderelem = makeelement(b, attributes=attrs) tableborders.append(borderelem) tableprops.append(tableborders) tablelook = makeelement('tblLook', attributes={'val': '0400'}) tableprops.append(tablelook) table.append(tableprops) tablegrid = makeelement('tblGrid') for i in range(columns): attrs = {'w': (str(colw[i]) if colw else '2390')} tablegrid.append(makeelement('gridCol', attributes=attrs)) table.append(tablegrid) row = makeelement('tr') rowprops = makeelement('trPr') cnfStyle = makeelement('cnfStyle', attributes={'val': '000000100000'}) rowprops.append(cnfStyle) row.append(rowprops) if heading: i = 0 for heading in contents[0]: cell = makeelement('tc') cellprops = makeelement('tcPr') if colw: wattr = {'w': str(colw[i]), 'type': cwunit} else: wattr = {'w': '0', 'type': 'auto'} cellwidth = makeelement('tcW', attributes=wattr) cellstyle = makeelement('shd', attributes={'val': 'clear', 'color': 'auto', 'fill': 'FFFFFF', 'themeFill': 'text2', 'themeFillTint': '99'}) cellprops.append(cellwidth) cellprops.append(cellstyle) cell.append(cellprops) if (not isinstance(heading, (list, tuple))): heading = [heading] for h in heading: if isinstance(h, etree._Element): cell.append(h) else: cell.append(paragraph(h, jc='center')) row.append(cell) i += 1 table.append(row) for contentrow in contents[(1 if heading else 0):]: row = makeelement('tr') i = 0 for content in contentrow: cell = makeelement('tc') cellprops = makeelement('tcPr') if colw: wattr = {'w': str(colw[i]), 'type': cwunit} else: wattr = {'w': '0', 'type': 'auto'} cellwidth = makeelement('tcW', attributes=wattr) cellprops.append(cellwidth) cell.append(cellprops) if (not isinstance(content, (list, tuple))): content = [content] for c in content: if isinstance(c, etree._Element): cell.append(c) else: if (celstyle and ('align' in celstyle[i].keys())): align = celstyle[i]['align'] else: align = 'left' cell.append(paragraph(c, jc=align)) row.append(cell) i += 1 table.append(row) return table
[ "def", "table", "(", "contents", ",", "heading", "=", "True", ",", "colw", "=", "None", ",", "cwunit", "=", "'dxa'", ",", "tblw", "=", "0", ",", "twunit", "=", "'auto'", ",", "borders", "=", "{", "}", ",", "celstyle", "=", "None", ")", ":", "table", "=", "makeelement", "(", "'tbl'", ")", "columns", "=", "len", "(", "contents", "[", "0", "]", ")", "tableprops", "=", "makeelement", "(", "'tblPr'", ")", "tablestyle", "=", "makeelement", "(", "'tblStyle'", ",", "attributes", "=", "{", "'val'", ":", "''", "}", ")", "tableprops", ".", "append", "(", "tablestyle", ")", "tablewidth", "=", "makeelement", "(", "'tblW'", ",", "attributes", "=", "{", "'w'", ":", "str", "(", "tblw", ")", ",", "'type'", ":", "str", "(", "twunit", ")", "}", ")", "tableprops", ".", "append", "(", "tablewidth", ")", "if", "len", "(", "borders", ".", "keys", "(", ")", ")", ":", "tableborders", "=", "makeelement", "(", "'tblBorders'", ")", "for", "b", "in", "[", "'top'", ",", "'left'", ",", "'bottom'", ",", "'right'", ",", "'insideH'", ",", "'insideV'", "]", ":", "if", "(", "(", "b", "in", "borders", ".", "keys", "(", ")", ")", "or", "(", "'all'", "in", "borders", ".", "keys", "(", ")", ")", ")", ":", "k", "=", "(", "'all'", "if", "(", "'all'", "in", "borders", ".", "keys", "(", ")", ")", "else", "b", ")", "attrs", "=", "{", "}", "for", "a", "in", "borders", "[", "k", "]", ".", "keys", "(", ")", ":", "attrs", "[", "a", "]", "=", "unicode", "(", "borders", "[", "k", "]", "[", "a", "]", ")", "borderelem", "=", "makeelement", "(", "b", ",", "attributes", "=", "attrs", ")", "tableborders", ".", "append", "(", "borderelem", ")", "tableprops", ".", "append", "(", "tableborders", ")", "tablelook", "=", "makeelement", "(", "'tblLook'", ",", "attributes", "=", "{", "'val'", ":", "'0400'", "}", ")", "tableprops", ".", "append", "(", "tablelook", ")", "table", ".", "append", "(", "tableprops", ")", "tablegrid", "=", "makeelement", "(", "'tblGrid'", ")", "for", "i", "in", "range", "(", "columns", ")", ":", "attrs", "=", "{", "'w'", ":", "(", "str", "(", "colw", "[", "i", "]", ")", "if", "colw", "else", "'2390'", ")", "}", "tablegrid", ".", "append", "(", "makeelement", "(", "'gridCol'", ",", "attributes", "=", "attrs", ")", ")", "table", ".", "append", "(", "tablegrid", ")", "row", "=", "makeelement", "(", "'tr'", ")", "rowprops", "=", "makeelement", "(", "'trPr'", ")", "cnfStyle", "=", "makeelement", "(", "'cnfStyle'", ",", "attributes", "=", "{", "'val'", ":", "'000000100000'", "}", ")", "rowprops", ".", "append", "(", "cnfStyle", ")", "row", ".", "append", "(", "rowprops", ")", "if", "heading", ":", "i", "=", "0", "for", "heading", "in", "contents", "[", "0", "]", ":", "cell", "=", "makeelement", "(", "'tc'", ")", "cellprops", "=", "makeelement", "(", "'tcPr'", ")", "if", "colw", ":", "wattr", "=", "{", "'w'", ":", "str", "(", "colw", "[", "i", "]", ")", ",", "'type'", ":", "cwunit", "}", "else", ":", "wattr", "=", "{", "'w'", ":", "'0'", ",", "'type'", ":", "'auto'", "}", "cellwidth", "=", "makeelement", "(", "'tcW'", ",", "attributes", "=", "wattr", ")", "cellstyle", "=", "makeelement", "(", "'shd'", ",", "attributes", "=", "{", "'val'", ":", "'clear'", ",", "'color'", ":", "'auto'", ",", "'fill'", ":", "'FFFFFF'", ",", "'themeFill'", ":", "'text2'", ",", "'themeFillTint'", ":", "'99'", "}", ")", "cellprops", ".", "append", "(", "cellwidth", ")", "cellprops", ".", "append", "(", "cellstyle", ")", "cell", ".", "append", "(", "cellprops", ")", "if", "(", "not", "isinstance", "(", "heading", ",", "(", "list", ",", "tuple", ")", ")", ")", ":", "heading", "=", "[", "heading", "]", "for", "h", "in", "heading", ":", "if", "isinstance", "(", "h", ",", "etree", ".", "_Element", ")", ":", "cell", ".", "append", "(", "h", ")", "else", ":", "cell", ".", "append", "(", "paragraph", "(", "h", ",", "jc", "=", "'center'", ")", ")", "row", ".", "append", "(", "cell", ")", "i", "+=", "1", "table", ".", "append", "(", "row", ")", "for", "contentrow", "in", "contents", "[", "(", "1", "if", "heading", "else", "0", ")", ":", "]", ":", "row", "=", "makeelement", "(", "'tr'", ")", "i", "=", "0", "for", "content", "in", "contentrow", ":", "cell", "=", "makeelement", "(", "'tc'", ")", "cellprops", "=", "makeelement", "(", "'tcPr'", ")", "if", "colw", ":", "wattr", "=", "{", "'w'", ":", "str", "(", "colw", "[", "i", "]", ")", ",", "'type'", ":", "cwunit", "}", "else", ":", "wattr", "=", "{", "'w'", ":", "'0'", ",", "'type'", ":", "'auto'", "}", "cellwidth", "=", "makeelement", "(", "'tcW'", ",", "attributes", "=", "wattr", ")", "cellprops", ".", "append", "(", "cellwidth", ")", "cell", ".", "append", "(", "cellprops", ")", "if", "(", "not", "isinstance", "(", "content", ",", "(", "list", ",", "tuple", ")", ")", ")", ":", "content", "=", "[", "content", "]", "for", "c", "in", "content", ":", "if", "isinstance", "(", "c", ",", "etree", ".", "_Element", ")", ":", "cell", ".", "append", "(", "c", ")", "else", ":", "if", "(", "celstyle", "and", "(", "'align'", "in", "celstyle", "[", "i", "]", ".", "keys", "(", ")", ")", ")", ":", "align", "=", "celstyle", "[", "i", "]", "[", "'align'", "]", "else", ":", "align", "=", "'left'", "cell", ".", "append", "(", "paragraph", "(", "c", ",", "jc", "=", "align", ")", ")", "row", ".", "append", "(", "cell", ")", "i", "+=", "1", "table", ".", "append", "(", "row", ")", "return", "table" ]
restful crud controller for dynamic table contents nb: first argument is the resource name .
train
true
17,357
def test_typical_memory_error(): try: raise TypicalMemoryError('test') except TypicalMemoryError as e: pass
[ "def", "test_typical_memory_error", "(", ")", ":", "try", ":", "raise", "TypicalMemoryError", "(", "'test'", ")", "except", "TypicalMemoryError", "as", "e", ":", "pass" ]
a dummy test that instantiates a typicalmemoryerror to see if there is no bugs .
train
false
17,358
def registration_codes_csv(file_name, codes_list, csv_type=None): query_features = ['code', 'redeem_code_url', 'course_id', 'company_name', 'created_by', 'redeemed_by', 'invoice_id', 'purchaser', 'customer_reference_number', 'internal_reference', 'is_valid'] registration_codes = instructor_analytics.basic.course_registration_features(query_features, codes_list, csv_type) (header, data_rows) = instructor_analytics.csvs.format_dictlist(registration_codes, query_features) return instructor_analytics.csvs.create_csv_response(file_name, header, data_rows)
[ "def", "registration_codes_csv", "(", "file_name", ",", "codes_list", ",", "csv_type", "=", "None", ")", ":", "query_features", "=", "[", "'code'", ",", "'redeem_code_url'", ",", "'course_id'", ",", "'company_name'", ",", "'created_by'", ",", "'redeemed_by'", ",", "'invoice_id'", ",", "'purchaser'", ",", "'customer_reference_number'", ",", "'internal_reference'", ",", "'is_valid'", "]", "registration_codes", "=", "instructor_analytics", ".", "basic", ".", "course_registration_features", "(", "query_features", ",", "codes_list", ",", "csv_type", ")", "(", "header", ",", "data_rows", ")", "=", "instructor_analytics", ".", "csvs", ".", "format_dictlist", "(", "registration_codes", ",", "query_features", ")", "return", "instructor_analytics", ".", "csvs", ".", "create_csv_response", "(", "file_name", ",", "header", ",", "data_rows", ")" ]
respond with the csv headers and data rows given a dict of codes list .
train
false
17,359
def get_supported_locales(manifest): return sorted(filter(None, map(find_language, set(manifest.get('locales', {}).keys()))))
[ "def", "get_supported_locales", "(", "manifest", ")", ":", "return", "sorted", "(", "filter", "(", "None", ",", "map", "(", "find_language", ",", "set", "(", "manifest", ".", "get", "(", "'locales'", ",", "{", "}", ")", ".", "keys", "(", ")", ")", ")", ")", ")" ]
returns a list of all the supported locale codes .
train
false
17,360
def count_tied_groups(x, use_missing=False): nmasked = ma.getmask(x).sum() data = ma.compressed(x).copy() (ties, counts) = find_repeats(data) nties = {} if len(ties): nties = dict(zip(np.unique(counts), itertools.repeat(1))) nties.update(dict(zip(*find_repeats(counts)))) if (nmasked and use_missing): try: nties[nmasked] += 1 except KeyError: nties[nmasked] = 1 return nties
[ "def", "count_tied_groups", "(", "x", ",", "use_missing", "=", "False", ")", ":", "nmasked", "=", "ma", ".", "getmask", "(", "x", ")", ".", "sum", "(", ")", "data", "=", "ma", ".", "compressed", "(", "x", ")", ".", "copy", "(", ")", "(", "ties", ",", "counts", ")", "=", "find_repeats", "(", "data", ")", "nties", "=", "{", "}", "if", "len", "(", "ties", ")", ":", "nties", "=", "dict", "(", "zip", "(", "np", ".", "unique", "(", "counts", ")", ",", "itertools", ".", "repeat", "(", "1", ")", ")", ")", "nties", ".", "update", "(", "dict", "(", "zip", "(", "*", "find_repeats", "(", "counts", ")", ")", ")", ")", "if", "(", "nmasked", "and", "use_missing", ")", ":", "try", ":", "nties", "[", "nmasked", "]", "+=", "1", "except", "KeyError", ":", "nties", "[", "nmasked", "]", "=", "1", "return", "nties" ]
counts the number of tied values .
train
false
17,362
def brackets(): a_string = input('Please enter a string to process: ') brac_dict = {'}': '{', ']': '[', ')': '('} brac_store = [] for i in a_string: if (i in brac_dict.values()): brac_store.append(i) elif (i in brac_dict.keys()): if (len(brac_store) == 0): return False if (brac_dict[i] == brac_store[(-1)]): del brac_store[(-1)] else: return False if (len(brac_store) > 0): return False else: return True
[ "def", "brackets", "(", ")", ":", "a_string", "=", "input", "(", "'Please enter a string to process: '", ")", "brac_dict", "=", "{", "'}'", ":", "'{'", ",", "']'", ":", "'['", ",", "')'", ":", "'('", "}", "brac_store", "=", "[", "]", "for", "i", "in", "a_string", ":", "if", "(", "i", "in", "brac_dict", ".", "values", "(", ")", ")", ":", "brac_store", ".", "append", "(", "i", ")", "elif", "(", "i", "in", "brac_dict", ".", "keys", "(", ")", ")", ":", "if", "(", "len", "(", "brac_store", ")", "==", "0", ")", ":", "return", "False", "if", "(", "brac_dict", "[", "i", "]", "==", "brac_store", "[", "(", "-", "1", ")", "]", ")", ":", "del", "brac_store", "[", "(", "-", "1", ")", "]", "else", ":", "return", "False", "if", "(", "len", "(", "brac_store", ")", ">", "0", ")", ":", "return", "False", "else", ":", "return", "True" ]
asks for a string and returns true/false .
train
false
17,363
def _shift_selem(selem, shift_x, shift_y): if (selem.ndim > 2): return selem (m, n) = selem.shape if ((m % 2) == 0): extra_row = np.zeros((1, n), selem.dtype) if shift_x: selem = np.vstack((selem, extra_row)) else: selem = np.vstack((extra_row, selem)) m += 1 if ((n % 2) == 0): extra_col = np.zeros((m, 1), selem.dtype) if shift_y: selem = np.hstack((selem, extra_col)) else: selem = np.hstack((extra_col, selem)) return selem
[ "def", "_shift_selem", "(", "selem", ",", "shift_x", ",", "shift_y", ")", ":", "if", "(", "selem", ".", "ndim", ">", "2", ")", ":", "return", "selem", "(", "m", ",", "n", ")", "=", "selem", ".", "shape", "if", "(", "(", "m", "%", "2", ")", "==", "0", ")", ":", "extra_row", "=", "np", ".", "zeros", "(", "(", "1", ",", "n", ")", ",", "selem", ".", "dtype", ")", "if", "shift_x", ":", "selem", "=", "np", ".", "vstack", "(", "(", "selem", ",", "extra_row", ")", ")", "else", ":", "selem", "=", "np", ".", "vstack", "(", "(", "extra_row", ",", "selem", ")", ")", "m", "+=", "1", "if", "(", "(", "n", "%", "2", ")", "==", "0", ")", ":", "extra_col", "=", "np", ".", "zeros", "(", "(", "m", ",", "1", ")", ",", "selem", ".", "dtype", ")", "if", "shift_y", ":", "selem", "=", "np", ".", "hstack", "(", "(", "selem", ",", "extra_col", ")", ")", "else", ":", "selem", "=", "np", ".", "hstack", "(", "(", "extra_col", ",", "selem", ")", ")", "return", "selem" ]
shift the binary image selem in the left and/or up .
train
false
17,364
def var_loglike(resid, omega, nobs): logdet = logdet_symm(np.asarray(omega)) neqs = len(omega) part1 = ((- ((nobs * neqs) / 2)) * np.log((2 * np.pi))) part2 = ((- (nobs / 2)) * (logdet + neqs)) return (part1 + part2)
[ "def", "var_loglike", "(", "resid", ",", "omega", ",", "nobs", ")", ":", "logdet", "=", "logdet_symm", "(", "np", ".", "asarray", "(", "omega", ")", ")", "neqs", "=", "len", "(", "omega", ")", "part1", "=", "(", "(", "-", "(", "(", "nobs", "*", "neqs", ")", "/", "2", ")", ")", "*", "np", ".", "log", "(", "(", "2", "*", "np", ".", "pi", ")", ")", ")", "part2", "=", "(", "(", "-", "(", "nobs", "/", "2", ")", ")", "*", "(", "logdet", "+", "neqs", ")", ")", "return", "(", "part1", "+", "part2", ")" ]
returns the value of the var(p) log-likelihood .
train
false
17,365
def getdtype(dtype, a=None, default=None): if (dtype is None): try: newdtype = a.dtype except AttributeError: if (default is not None): newdtype = np.dtype(default) else: raise TypeError('could not interpret data type') else: newdtype = np.dtype(dtype) if (newdtype == np.object_): warnings.warn('object dtype is not supported by sparse matrices') return newdtype
[ "def", "getdtype", "(", "dtype", ",", "a", "=", "None", ",", "default", "=", "None", ")", ":", "if", "(", "dtype", "is", "None", ")", ":", "try", ":", "newdtype", "=", "a", ".", "dtype", "except", "AttributeError", ":", "if", "(", "default", "is", "not", "None", ")", ":", "newdtype", "=", "np", ".", "dtype", "(", "default", ")", "else", ":", "raise", "TypeError", "(", "'could not interpret data type'", ")", "else", ":", "newdtype", "=", "np", ".", "dtype", "(", "dtype", ")", "if", "(", "newdtype", "==", "np", ".", "object_", ")", ":", "warnings", ".", "warn", "(", "'object dtype is not supported by sparse matrices'", ")", "return", "newdtype" ]
function used to simplify argument processing .
train
false
17,366
def get_working_if(): ifaces = get_working_ifaces() if (not ifaces): return LOOPBACK_NAME return ifaces[0][0]
[ "def", "get_working_if", "(", ")", ":", "ifaces", "=", "get_working_ifaces", "(", ")", "if", "(", "not", "ifaces", ")", ":", "return", "LOOPBACK_NAME", "return", "ifaces", "[", "0", "]", "[", "0", "]" ]
returns the first interface than can be used with bpf .
train
false
17,368
def quote_escape(value, lf='&mjf-lf;', quot='&mjf-quot;'): if ('\n' in value): value = value.replace('\n', lf) if (("'" in value) and ('"' in value)): value = value.replace('"', quot) return value
[ "def", "quote_escape", "(", "value", ",", "lf", "=", "'&mjf-lf;'", ",", "quot", "=", "'&mjf-quot;'", ")", ":", "if", "(", "'\\n'", "in", "value", ")", ":", "value", "=", "value", ".", "replace", "(", "'\\n'", ",", "lf", ")", "if", "(", "(", "\"'\"", "in", "value", ")", "and", "(", "'\"'", "in", "value", ")", ")", ":", "value", "=", "value", ".", "replace", "(", "'\"'", ",", "quot", ")", "return", "value" ]
escape a string so that it can safely be quoted .
train
false
17,369
@with_session def from_cache(session=None, search_params=None, cache_type=None): if (not any(search_params.values())): raise LookupError(u'No parameters sent for cache lookup') else: log.debug(u'searching db {0} for the values {1}'.format(cache_type.__tablename__, list(search_params.items()))) result = session.query(cache_type).filter(or_(((getattr(cache_type, col) == val) for (col, val) in search_params.items() if val))).first() return result
[ "@", "with_session", "def", "from_cache", "(", "session", "=", "None", ",", "search_params", "=", "None", ",", "cache_type", "=", "None", ")", ":", "if", "(", "not", "any", "(", "search_params", ".", "values", "(", ")", ")", ")", ":", "raise", "LookupError", "(", "u'No parameters sent for cache lookup'", ")", "else", ":", "log", ".", "debug", "(", "u'searching db {0} for the values {1}'", ".", "format", "(", "cache_type", ".", "__tablename__", ",", "list", "(", "search_params", ".", "items", "(", ")", ")", ")", ")", "result", "=", "session", ".", "query", "(", "cache_type", ")", ".", "filter", "(", "or_", "(", "(", "(", "getattr", "(", "cache_type", ",", "col", ")", "==", "val", ")", "for", "(", "col", ",", "val", ")", "in", "search_params", ".", "items", "(", ")", "if", "val", ")", ")", ")", ".", "first", "(", ")", "return", "result" ]
returns a result from requested table based on search params .
train
false
17,370
def _parse_read_preference(options): if ('read_preference' in options): return options['read_preference'] mode = options.get('readpreference', 0) tags = options.get('readpreferencetags') max_staleness = options.get('maxstalenessseconds', (-1)) return make_read_preference(mode, tags, max_staleness)
[ "def", "_parse_read_preference", "(", "options", ")", ":", "if", "(", "'read_preference'", "in", "options", ")", ":", "return", "options", "[", "'read_preference'", "]", "mode", "=", "options", ".", "get", "(", "'readpreference'", ",", "0", ")", "tags", "=", "options", ".", "get", "(", "'readpreferencetags'", ")", "max_staleness", "=", "options", ".", "get", "(", "'maxstalenessseconds'", ",", "(", "-", "1", ")", ")", "return", "make_read_preference", "(", "mode", ",", "tags", ",", "max_staleness", ")" ]
parse read preference options .
train
false
17,372
def tstd_pdf(x, df): r = np.array((df * 1.0)) Px = (np.exp((special.gammaln(((r + 1) / 2.0)) - special.gammaln((r / 2.0)))) / np.sqrt(((r - 2) * pi))) Px /= ((1 + ((x ** 2) / (r - 2))) ** ((r + 1) / 2.0)) return Px
[ "def", "tstd_pdf", "(", "x", ",", "df", ")", ":", "r", "=", "np", ".", "array", "(", "(", "df", "*", "1.0", ")", ")", "Px", "=", "(", "np", ".", "exp", "(", "(", "special", ".", "gammaln", "(", "(", "(", "r", "+", "1", ")", "/", "2.0", ")", ")", "-", "special", ".", "gammaln", "(", "(", "r", "/", "2.0", ")", ")", ")", ")", "/", "np", ".", "sqrt", "(", "(", "(", "r", "-", "2", ")", "*", "pi", ")", ")", ")", "Px", "/=", "(", "(", "1", "+", "(", "(", "x", "**", "2", ")", "/", "(", "r", "-", "2", ")", ")", ")", "**", "(", "(", "r", "+", "1", ")", "/", "2.0", ")", ")", "return", "Px" ]
pdf for standardized t distribution .
train
false
17,373
def get_dynamic_descriptor_children(descriptor, user_id, module_creator=None, usage_key_filter=None): module_children = [] if descriptor.has_dynamic_children(): module = None if (descriptor.scope_ids.user_id and (user_id == descriptor.scope_ids.user_id)): module = descriptor elif module_creator: module = module_creator(descriptor) if module: module_children = module.get_child_descriptors() else: module_children = descriptor.get_children(usage_key_filter) return module_children
[ "def", "get_dynamic_descriptor_children", "(", "descriptor", ",", "user_id", ",", "module_creator", "=", "None", ",", "usage_key_filter", "=", "None", ")", ":", "module_children", "=", "[", "]", "if", "descriptor", ".", "has_dynamic_children", "(", ")", ":", "module", "=", "None", "if", "(", "descriptor", ".", "scope_ids", ".", "user_id", "and", "(", "user_id", "==", "descriptor", ".", "scope_ids", ".", "user_id", ")", ")", ":", "module", "=", "descriptor", "elif", "module_creator", ":", "module", "=", "module_creator", "(", "descriptor", ")", "if", "module", ":", "module_children", "=", "module", ".", "get_child_descriptors", "(", ")", "else", ":", "module_children", "=", "descriptor", ".", "get_children", "(", "usage_key_filter", ")", "return", "module_children" ]
returns the children of the given descriptor .
train
false
17,374
def corpus_to_vw(corpus): for entries in corpus: line = [u'|'] for (word_id, count) in entries: line.append(u'{0}:{1}'.format(word_id, count)) (yield u' '.join(line))
[ "def", "corpus_to_vw", "(", "corpus", ")", ":", "for", "entries", "in", "corpus", ":", "line", "=", "[", "u'|'", "]", "for", "(", "word_id", ",", "count", ")", "in", "entries", ":", "line", ".", "append", "(", "u'{0}:{1}'", ".", "format", "(", "word_id", ",", "count", ")", ")", "(", "yield", "u' '", ".", "join", "(", "line", ")", ")" ]
iterate over corpus .
train
false
17,375
def has_user_permission_for_some_org(user_name, permission): user_id = get_user_id_for_username(user_name, allow_none=True) if (not user_id): return False roles = get_roles_with_permission(permission) if (not roles): return False q = model.Session.query(model.Member).filter((model.Member.table_name == 'user')).filter((model.Member.state == 'active')).filter(model.Member.capacity.in_(roles)).filter((model.Member.table_id == user_id)) group_ids = [] for row in q.all(): group_ids.append(row.group_id) if (not group_ids): return False q = model.Session.query(model.Group).filter((model.Group.is_organization == True)).filter((model.Group.state == 'active')).filter(model.Group.id.in_(group_ids)) return bool(q.count())
[ "def", "has_user_permission_for_some_org", "(", "user_name", ",", "permission", ")", ":", "user_id", "=", "get_user_id_for_username", "(", "user_name", ",", "allow_none", "=", "True", ")", "if", "(", "not", "user_id", ")", ":", "return", "False", "roles", "=", "get_roles_with_permission", "(", "permission", ")", "if", "(", "not", "roles", ")", ":", "return", "False", "q", "=", "model", ".", "Session", ".", "query", "(", "model", ".", "Member", ")", ".", "filter", "(", "(", "model", ".", "Member", ".", "table_name", "==", "'user'", ")", ")", ".", "filter", "(", "(", "model", ".", "Member", ".", "state", "==", "'active'", ")", ")", ".", "filter", "(", "model", ".", "Member", ".", "capacity", ".", "in_", "(", "roles", ")", ")", ".", "filter", "(", "(", "model", ".", "Member", ".", "table_id", "==", "user_id", ")", ")", "group_ids", "=", "[", "]", "for", "row", "in", "q", ".", "all", "(", ")", ":", "group_ids", ".", "append", "(", "row", ".", "group_id", ")", "if", "(", "not", "group_ids", ")", ":", "return", "False", "q", "=", "model", ".", "Session", ".", "query", "(", "model", ".", "Group", ")", ".", "filter", "(", "(", "model", ".", "Group", ".", "is_organization", "==", "True", ")", ")", ".", "filter", "(", "(", "model", ".", "Group", ".", "state", "==", "'active'", ")", ")", ".", "filter", "(", "model", ".", "Group", ".", "id", ".", "in_", "(", "group_ids", ")", ")", "return", "bool", "(", "q", ".", "count", "(", ")", ")" ]
check if the user has the given permission for any organization .
train
false
17,376
def pyUnitTests(): s = unittest.TestSuite() for (filename, test_num, expected, case) in getCases(): s.addTest(_TestCase(filename, str(test_num), expected, case)) return s
[ "def", "pyUnitTests", "(", ")", ":", "s", "=", "unittest", ".", "TestSuite", "(", ")", "for", "(", "filename", ",", "test_num", ",", "expected", ",", "case", ")", "in", "getCases", "(", ")", ":", "s", ".", "addTest", "(", "_TestCase", "(", "filename", ",", "str", "(", "test_num", ")", ",", "expected", ",", "case", ")", ")", "return", "s" ]
make a pyunit testsuite from a file defining test cases .
train
false
17,377
def zx_basis_transform(self, format='sympy'): return matrix_cache.get_matrix('ZX', format)
[ "def", "zx_basis_transform", "(", "self", ",", "format", "=", "'sympy'", ")", ":", "return", "matrix_cache", ".", "get_matrix", "(", "'ZX'", ",", "format", ")" ]
transformation matrix from z to x basis .
train
false
17,378
def test_inverse_quantity(): q = u.Quantity(4.0, (u.meter / u.second)) qot = (q / 2) toq = (2 / q) npqot = (q / np.array(2)) assert (npqot.value == 2.0) assert (npqot.unit == (u.meter / u.second)) assert (qot.value == 2.0) assert (qot.unit == (u.meter / u.second)) assert (toq.value == 0.5) assert (toq.unit == (u.second / u.meter))
[ "def", "test_inverse_quantity", "(", ")", ":", "q", "=", "u", ".", "Quantity", "(", "4.0", ",", "(", "u", ".", "meter", "/", "u", ".", "second", ")", ")", "qot", "=", "(", "q", "/", "2", ")", "toq", "=", "(", "2", "/", "q", ")", "npqot", "=", "(", "q", "/", "np", ".", "array", "(", "2", ")", ")", "assert", "(", "npqot", ".", "value", "==", "2.0", ")", "assert", "(", "npqot", ".", "unit", "==", "(", "u", ".", "meter", "/", "u", ".", "second", ")", ")", "assert", "(", "qot", ".", "value", "==", "2.0", ")", "assert", "(", "qot", ".", "unit", "==", "(", "u", ".", "meter", "/", "u", ".", "second", ")", ")", "assert", "(", "toq", ".", "value", "==", "0.5", ")", "assert", "(", "toq", ".", "unit", "==", "(", "u", ".", "second", "/", "u", ".", "meter", ")", ")" ]
regression test from issue #679 .
train
false
17,380
@_file_loader def load_region(fileobj): return MCRFileReader(fileobj)
[ "@", "_file_loader", "def", "load_region", "(", "fileobj", ")", ":", "return", "MCRFileReader", "(", "fileobj", ")" ]
reads in the given file as a mcr region .
train
false
17,381
def toggle_set_term_title(val): global ignore_termtitle ignore_termtitle = (not val)
[ "def", "toggle_set_term_title", "(", "val", ")", ":", "global", "ignore_termtitle", "ignore_termtitle", "=", "(", "not", "val", ")" ]
control whether set_term_title is active or not .
train
false
17,382
def _parseSSL(factory, port, privateKey='server.pem', certKey=None, sslmethod=None, interface='', backlog=50, extraCertChain=None, dhParameters=None): from twisted.internet import ssl if (certKey is None): certKey = privateKey kw = {} if (sslmethod is not None): kw['method'] = getattr(ssl.SSL, sslmethod) certPEM = FilePath(certKey).getContent() keyPEM = FilePath(privateKey).getContent() privateCertificate = ssl.PrivateCertificate.loadPEM((certPEM + keyPEM)) if (extraCertChain is not None): matches = re.findall('(-----BEGIN CERTIFICATE-----\\n.+?\\n-----END CERTIFICATE-----)', nativeString(FilePath(extraCertChain).getContent()), flags=re.DOTALL) chainCertificates = [ssl.Certificate.loadPEM(chainCertPEM).original for chainCertPEM in matches] if (not chainCertificates): raise ValueError(("Specified chain file '%s' doesn't contain any valid certificates in PEM format." % (extraCertChain,))) else: chainCertificates = None if (dhParameters is not None): dhParameters = ssl.DiffieHellmanParameters.fromFile(FilePath(dhParameters)) cf = ssl.CertificateOptions(privateKey=privateCertificate.privateKey.original, certificate=privateCertificate.original, extraCertChain=chainCertificates, dhParameters=dhParameters, **kw) return ((int(port), factory, cf), {'interface': interface, 'backlog': int(backlog)})
[ "def", "_parseSSL", "(", "factory", ",", "port", ",", "privateKey", "=", "'server.pem'", ",", "certKey", "=", "None", ",", "sslmethod", "=", "None", ",", "interface", "=", "''", ",", "backlog", "=", "50", ",", "extraCertChain", "=", "None", ",", "dhParameters", "=", "None", ")", ":", "from", "twisted", ".", "internet", "import", "ssl", "if", "(", "certKey", "is", "None", ")", ":", "certKey", "=", "privateKey", "kw", "=", "{", "}", "if", "(", "sslmethod", "is", "not", "None", ")", ":", "kw", "[", "'method'", "]", "=", "getattr", "(", "ssl", ".", "SSL", ",", "sslmethod", ")", "certPEM", "=", "FilePath", "(", "certKey", ")", ".", "getContent", "(", ")", "keyPEM", "=", "FilePath", "(", "privateKey", ")", ".", "getContent", "(", ")", "privateCertificate", "=", "ssl", ".", "PrivateCertificate", ".", "loadPEM", "(", "(", "certPEM", "+", "keyPEM", ")", ")", "if", "(", "extraCertChain", "is", "not", "None", ")", ":", "matches", "=", "re", ".", "findall", "(", "'(-----BEGIN CERTIFICATE-----\\\\n.+?\\\\n-----END CERTIFICATE-----)'", ",", "nativeString", "(", "FilePath", "(", "extraCertChain", ")", ".", "getContent", "(", ")", ")", ",", "flags", "=", "re", ".", "DOTALL", ")", "chainCertificates", "=", "[", "ssl", ".", "Certificate", ".", "loadPEM", "(", "chainCertPEM", ")", ".", "original", "for", "chainCertPEM", "in", "matches", "]", "if", "(", "not", "chainCertificates", ")", ":", "raise", "ValueError", "(", "(", "\"Specified chain file '%s' doesn't contain any valid certificates in PEM format.\"", "%", "(", "extraCertChain", ",", ")", ")", ")", "else", ":", "chainCertificates", "=", "None", "if", "(", "dhParameters", "is", "not", "None", ")", ":", "dhParameters", "=", "ssl", ".", "DiffieHellmanParameters", ".", "fromFile", "(", "FilePath", "(", "dhParameters", ")", ")", "cf", "=", "ssl", ".", "CertificateOptions", "(", "privateKey", "=", "privateCertificate", ".", "privateKey", ".", "original", ",", "certificate", "=", "privateCertificate", ".", "original", ",", "extraCertChain", "=", "chainCertificates", ",", "dhParameters", "=", "dhParameters", ",", "**", "kw", ")", "return", "(", "(", "int", "(", "port", ")", ",", "factory", ",", "cf", ")", ",", "{", "'interface'", ":", "interface", ",", "'backlog'", ":", "int", "(", "backlog", ")", "}", ")" ]
internal parser function for l{_parseserver} to convert the string arguments for an ssl stream endpoint into the structured arguments .
train
false