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
43,209
def current_umask(): mask = os.umask(0) os.umask(mask) return mask
[ "def", "current_umask", "(", ")", ":", "mask", "=", "os", ".", "umask", "(", "0", ")", "os", ".", "umask", "(", "mask", ")", "return", "mask" ]
get the current umask which involves having to set it temporarily .
train
false
43,210
def get_pack_ref_from_metadata(metadata, pack_directory_name=None): pack_ref = None if metadata.get('ref', None): pack_ref = metadata['ref'] elif (pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name)): pack_ref = pack_directory_name elif re.match(PACK_REF_WHITELIST_REGEX, metadata['name']): pack_ref = metadata['name'] else: msg = 'Pack name "%s" contains invalid characters and "ref" attribute is not available. You either need to add "ref" attribute which contains only word characters to the pack metadata file or update name attribute to contain onlyword characters.' raise ValueError((msg % metadata['name'])) return pack_ref
[ "def", "get_pack_ref_from_metadata", "(", "metadata", ",", "pack_directory_name", "=", "None", ")", ":", "pack_ref", "=", "None", "if", "metadata", ".", "get", "(", "'ref'", ",", "None", ")", ":", "pack_ref", "=", "metadata", "[", "'ref'", "]", "elif", "(", "pack_directory_name", "and", "re", ".", "match", "(", "PACK_REF_WHITELIST_REGEX", ",", "pack_directory_name", ")", ")", ":", "pack_ref", "=", "pack_directory_name", "elif", "re", ".", "match", "(", "PACK_REF_WHITELIST_REGEX", ",", "metadata", "[", "'name'", "]", ")", ":", "pack_ref", "=", "metadata", "[", "'name'", "]", "else", ":", "msg", "=", "'Pack name \"%s\" contains invalid characters and \"ref\" attribute is not available. You either need to add \"ref\" attribute which contains only word characters to the pack metadata file or update name attribute to contain onlyword characters.'", "raise", "ValueError", "(", "(", "msg", "%", "metadata", "[", "'name'", "]", ")", ")", "return", "pack_ref" ]
utility function which retrieves pack "ref" attribute from the pack metadata file .
train
false
43,211
def re_map_foreign_keys(data, table, field_name, related_table, verbose=False): lookup_table = id_maps[related_table] for item in data[table]: old_id = item[field_name] if (old_id in lookup_table): new_id = lookup_table[old_id] if verbose: logging.info(('Remapping %s%s from %s to %s' % (table, (field_name + '_id'), old_id, new_id))) else: new_id = old_id item[(field_name + '_id')] = new_id del item[field_name]
[ "def", "re_map_foreign_keys", "(", "data", ",", "table", ",", "field_name", ",", "related_table", ",", "verbose", "=", "False", ")", ":", "lookup_table", "=", "id_maps", "[", "related_table", "]", "for", "item", "in", "data", "[", "table", "]", ":", "old_id", "=", "item", "[", "field_name", "]", "if", "(", "old_id", "in", "lookup_table", ")", ":", "new_id", "=", "lookup_table", "[", "old_id", "]", "if", "verbose", ":", "logging", ".", "info", "(", "(", "'Remapping %s%s from %s to %s'", "%", "(", "table", ",", "(", "field_name", "+", "'_id'", ")", ",", "old_id", ",", "new_id", ")", ")", ")", "else", ":", "new_id", "=", "old_id", "item", "[", "(", "field_name", "+", "'_id'", ")", "]", "=", "new_id", "del", "item", "[", "field_name", "]" ]
we occasionally need to assign new ids to rows during the import/export process .
train
false
43,212
def test_fast_wait(): gevent.sleep(300)
[ "def", "test_fast_wait", "(", ")", ":", "gevent", ".", "sleep", "(", "300", ")" ]
annoy someone who causes fast-sleep test patching to regress .
train
false
43,213
def _render_blog_supernav(entry): return render_to_string('blogs/supernav.html', {'entry': entry})
[ "def", "_render_blog_supernav", "(", "entry", ")", ":", "return", "render_to_string", "(", "'blogs/supernav.html'", ",", "{", "'entry'", ":", "entry", "}", ")" ]
utility to make testing update_blogs management command easier .
train
false
43,217
def calculate_avail_vmem(mems): free = mems['MemFree:'] fallback = (free + mems.get('Cached:', 0)) try: lru_active_file = mems['Active(file):'] lru_inactive_file = mems['Inactive(file):'] slab_reclaimable = mems['SReclaimable:'] except KeyError: return fallback try: f = open_binary(('%s/zoneinfo' % get_procfs_path())) except IOError: return fallback watermark_low = 0 with f: for line in f: line = line.strip() if line.startswith('low'): watermark_low += int(line.split()[1]) watermark_low *= PAGESIZE watermark_low = watermark_low avail = (free - watermark_low) pagecache = (lru_active_file + lru_inactive_file) pagecache -= min((pagecache / 2), watermark_low) avail += pagecache avail += (slab_reclaimable - min((slab_reclaimable / 2.0), watermark_low)) return int(avail)
[ "def", "calculate_avail_vmem", "(", "mems", ")", ":", "free", "=", "mems", "[", "'MemFree:'", "]", "fallback", "=", "(", "free", "+", "mems", ".", "get", "(", "'Cached:'", ",", "0", ")", ")", "try", ":", "lru_active_file", "=", "mems", "[", "'Active(file):'", "]", "lru_inactive_file", "=", "mems", "[", "'Inactive(file):'", "]", "slab_reclaimable", "=", "mems", "[", "'SReclaimable:'", "]", "except", "KeyError", ":", "return", "fallback", "try", ":", "f", "=", "open_binary", "(", "(", "'%s/zoneinfo'", "%", "get_procfs_path", "(", ")", ")", ")", "except", "IOError", ":", "return", "fallback", "watermark_low", "=", "0", "with", "f", ":", "for", "line", "in", "f", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "startswith", "(", "'low'", ")", ":", "watermark_low", "+=", "int", "(", "line", ".", "split", "(", ")", "[", "1", "]", ")", "watermark_low", "*=", "PAGESIZE", "watermark_low", "=", "watermark_low", "avail", "=", "(", "free", "-", "watermark_low", ")", "pagecache", "=", "(", "lru_active_file", "+", "lru_inactive_file", ")", "pagecache", "-=", "min", "(", "(", "pagecache", "/", "2", ")", ",", "watermark_low", ")", "avail", "+=", "pagecache", "avail", "+=", "(", "slab_reclaimable", "-", "min", "(", "(", "slab_reclaimable", "/", "2.0", ")", ",", "watermark_low", ")", ")", "return", "int", "(", "avail", ")" ]
fallback for kernels < 3 .
train
false
43,218
def allocate_address(ec2, domain, reuse_existing_ip_allowed): if reuse_existing_ip_allowed: domain_filter = {'domain': (domain or 'standard')} all_addresses = ec2.get_all_addresses(filters=domain_filter) if (domain == 'vpc'): unassociated_addresses = [a for a in all_addresses if (not a.association_id)] else: unassociated_addresses = [a for a in all_addresses if (not a.instance_id)] if unassociated_addresses: return unassociated_addresses[0] return ec2.allocate_address(domain=domain)
[ "def", "allocate_address", "(", "ec2", ",", "domain", ",", "reuse_existing_ip_allowed", ")", ":", "if", "reuse_existing_ip_allowed", ":", "domain_filter", "=", "{", "'domain'", ":", "(", "domain", "or", "'standard'", ")", "}", "all_addresses", "=", "ec2", ".", "get_all_addresses", "(", "filters", "=", "domain_filter", ")", "if", "(", "domain", "==", "'vpc'", ")", ":", "unassociated_addresses", "=", "[", "a", "for", "a", "in", "all_addresses", "if", "(", "not", "a", ".", "association_id", ")", "]", "else", ":", "unassociated_addresses", "=", "[", "a", "for", "a", "in", "all_addresses", "if", "(", "not", "a", ".", "instance_id", ")", "]", "if", "unassociated_addresses", ":", "return", "unassociated_addresses", "[", "0", "]", "return", "ec2", ".", "allocate_address", "(", "domain", "=", "domain", ")" ]
allocate a new elastic ip address and return it .
train
false
43,219
def test_config_file_override_stack(script, virtualenv): (fd, config_file) = tempfile.mkstemp('-pip.cfg', 'test-') try: _test_config_file_override_stack(script, virtualenv, config_file) finally: os.close(fd) os.remove(config_file)
[ "def", "test_config_file_override_stack", "(", "script", ",", "virtualenv", ")", ":", "(", "fd", ",", "config_file", ")", "=", "tempfile", ".", "mkstemp", "(", "'-pip.cfg'", ",", "'test-'", ")", "try", ":", "_test_config_file_override_stack", "(", "script", ",", "virtualenv", ",", "config_file", ")", "finally", ":", "os", ".", "close", "(", "fd", ")", "os", ".", "remove", "(", "config_file", ")" ]
test config files .
train
false
43,224
def gen_random_state(): M1 = 2147483647 M2 = 2147462579 return (np.random.randint(0, M1, 3).tolist() + np.random.randint(0, M2, 3).tolist())
[ "def", "gen_random_state", "(", ")", ":", "M1", "=", "2147483647", "M2", "=", "2147462579", "return", "(", "np", ".", "random", ".", "randint", "(", "0", ",", "M1", ",", "3", ")", ".", "tolist", "(", ")", "+", "np", ".", "random", ".", "randint", "(", "0", ",", "M2", ",", "3", ")", ".", "tolist", "(", ")", ")" ]
helper to generate a random state for mrg_randomstreams .
train
false
43,226
def descriptor_global_handler_url(block, handler_name, suffix='', query='', thirdparty=False): raise NotImplementedError('Applications must monkey-patch this function before using handler_url for studio_view')
[ "def", "descriptor_global_handler_url", "(", "block", ",", "handler_name", ",", "suffix", "=", "''", ",", "query", "=", "''", ",", "thirdparty", "=", "False", ")", ":", "raise", "NotImplementedError", "(", "'Applications must monkey-patch this function before using handler_url for studio_view'", ")" ]
see :meth:xblock .
train
false
43,227
def filter_preconditions(classes, logger=None): filtered = [] for cls in classes: (status, message) = cls.check_precondition() if status: filtered.append(cls) elif (logger is not None): logger.warning('Disabling handler %s because preconditions not met: %s.', cls.name, message) return filtered
[ "def", "filter_preconditions", "(", "classes", ",", "logger", "=", "None", ")", ":", "filtered", "=", "[", "]", "for", "cls", "in", "classes", ":", "(", "status", ",", "message", ")", "=", "cls", ".", "check_precondition", "(", ")", "if", "status", ":", "filtered", ".", "append", "(", "cls", ")", "elif", "(", "logger", "is", "not", "None", ")", ":", "logger", ".", "warning", "(", "'Disabling handler %s because preconditions not met: %s.'", ",", "cls", ".", "name", ",", "message", ")", "return", "filtered" ]
filter handlers whose preconditions are not met classes: list of nogotofail handler classes to filter logger: logging .
train
false
43,228
def cookie_decode(data, key, digestmod=None): depr(0, 13, 'cookie_decode() will be removed soon.', 'Do not use this API directly.') data = tob(data) if cookie_is_encoded(data): (sig, msg) = data.split(tob('?'), 1) digestmod = (digestmod or hashlib.sha256) hashed = hmac.new(tob(key), msg, digestmod=digestmod).digest() if _lscmp(sig[1:], base64.b64encode(hashed)): return pickle.loads(base64.b64decode(msg)) return None
[ "def", "cookie_decode", "(", "data", ",", "key", ",", "digestmod", "=", "None", ")", ":", "depr", "(", "0", ",", "13", ",", "'cookie_decode() will be removed soon.'", ",", "'Do not use this API directly.'", ")", "data", "=", "tob", "(", "data", ")", "if", "cookie_is_encoded", "(", "data", ")", ":", "(", "sig", ",", "msg", ")", "=", "data", ".", "split", "(", "tob", "(", "'?'", ")", ",", "1", ")", "digestmod", "=", "(", "digestmod", "or", "hashlib", ".", "sha256", ")", "hashed", "=", "hmac", ".", "new", "(", "tob", "(", "key", ")", ",", "msg", ",", "digestmod", "=", "digestmod", ")", ".", "digest", "(", ")", "if", "_lscmp", "(", "sig", "[", "1", ":", "]", ",", "base64", ".", "b64encode", "(", "hashed", ")", ")", ":", "return", "pickle", ".", "loads", "(", "base64", ".", "b64decode", "(", "msg", ")", ")", "return", "None" ]
verify and decode an encoded string .
train
true
43,229
@_api_version(1.21) @_client_version('1.5.0') def disconnect_container_from_network(container, network_id): response = _client_wrapper('disconnect_container_from_network', container, network_id) _clear_context() return response
[ "@", "_api_version", "(", "1.21", ")", "@", "_client_version", "(", "'1.5.0'", ")", "def", "disconnect_container_from_network", "(", "container", ",", "network_id", ")", ":", "response", "=", "_client_wrapper", "(", "'disconnect_container_from_network'", ",", "container", ",", "network_id", ")", "_clear_context", "(", ")", "return", "response" ]
disconnect container from network .
train
false
43,230
def setup_testing_defaults(environ): environ.setdefault('SERVER_NAME', '127.0.0.1') environ.setdefault('SERVER_PROTOCOL', 'HTTP/1.0') environ.setdefault('HTTP_HOST', environ['SERVER_NAME']) environ.setdefault('REQUEST_METHOD', 'GET') if (('SCRIPT_NAME' not in environ) and ('PATH_INFO' not in environ)): environ.setdefault('SCRIPT_NAME', '') environ.setdefault('PATH_INFO', '/') environ.setdefault('wsgi.version', (1, 0)) environ.setdefault('wsgi.run_once', 0) environ.setdefault('wsgi.multithread', 0) environ.setdefault('wsgi.multiprocess', 0) from StringIO import StringIO environ.setdefault('wsgi.input', StringIO('')) environ.setdefault('wsgi.errors', StringIO()) environ.setdefault('wsgi.url_scheme', guess_scheme(environ)) if (environ['wsgi.url_scheme'] == 'http'): environ.setdefault('SERVER_PORT', '80') elif (environ['wsgi.url_scheme'] == 'https'): environ.setdefault('SERVER_PORT', '443')
[ "def", "setup_testing_defaults", "(", "environ", ")", ":", "environ", ".", "setdefault", "(", "'SERVER_NAME'", ",", "'127.0.0.1'", ")", "environ", ".", "setdefault", "(", "'SERVER_PROTOCOL'", ",", "'HTTP/1.0'", ")", "environ", ".", "setdefault", "(", "'HTTP_HOST'", ",", "environ", "[", "'SERVER_NAME'", "]", ")", "environ", ".", "setdefault", "(", "'REQUEST_METHOD'", ",", "'GET'", ")", "if", "(", "(", "'SCRIPT_NAME'", "not", "in", "environ", ")", "and", "(", "'PATH_INFO'", "not", "in", "environ", ")", ")", ":", "environ", ".", "setdefault", "(", "'SCRIPT_NAME'", ",", "''", ")", "environ", ".", "setdefault", "(", "'PATH_INFO'", ",", "'/'", ")", "environ", ".", "setdefault", "(", "'wsgi.version'", ",", "(", "1", ",", "0", ")", ")", "environ", ".", "setdefault", "(", "'wsgi.run_once'", ",", "0", ")", "environ", ".", "setdefault", "(", "'wsgi.multithread'", ",", "0", ")", "environ", ".", "setdefault", "(", "'wsgi.multiprocess'", ",", "0", ")", "from", "StringIO", "import", "StringIO", "environ", ".", "setdefault", "(", "'wsgi.input'", ",", "StringIO", "(", "''", ")", ")", "environ", ".", "setdefault", "(", "'wsgi.errors'", ",", "StringIO", "(", ")", ")", "environ", ".", "setdefault", "(", "'wsgi.url_scheme'", ",", "guess_scheme", "(", "environ", ")", ")", "if", "(", "environ", "[", "'wsgi.url_scheme'", "]", "==", "'http'", ")", ":", "environ", ".", "setdefault", "(", "'SERVER_PORT'", ",", "'80'", ")", "elif", "(", "environ", "[", "'wsgi.url_scheme'", "]", "==", "'https'", ")", ":", "environ", ".", "setdefault", "(", "'SERVER_PORT'", ",", "'443'", ")" ]
update environ with trivial defaults for testing purposes this adds various parameters required for wsgi .
train
false
43,231
def get_variables(scope=None, suffix=None): candidates = tf.get_collection(MODEL_VARIABLES, scope)[:] if (suffix is not None): candidates = [var for var in candidates if var.op.name.endswith(suffix)] return candidates
[ "def", "get_variables", "(", "scope", "=", "None", ",", "suffix", "=", "None", ")", ":", "candidates", "=", "tf", ".", "get_collection", "(", "MODEL_VARIABLES", ",", "scope", ")", "[", ":", "]", "if", "(", "suffix", "is", "not", "None", ")", ":", "candidates", "=", "[", "var", "for", "var", "in", "candidates", "if", "var", ".", "op", ".", "name", ".", "endswith", "(", "suffix", ")", "]", "return", "candidates" ]
gets the list of variables .
train
true
43,232
def _get_user_model(): custom_model = getattr(settings, setting_name('USER_MODEL'), None) if custom_model: return module_member(custom_model) try: from mongoengine.django.mongo_auth.models import get_user_document return get_user_document() except ImportError: return module_member('mongoengine.django.auth.User')
[ "def", "_get_user_model", "(", ")", ":", "custom_model", "=", "getattr", "(", "settings", ",", "setting_name", "(", "'USER_MODEL'", ")", ",", "None", ")", "if", "custom_model", ":", "return", "module_member", "(", "custom_model", ")", "try", ":", "from", "mongoengine", ".", "django", ".", "mongo_auth", ".", "models", "import", "get_user_document", "return", "get_user_document", "(", ")", "except", "ImportError", ":", "return", "module_member", "(", "'mongoengine.django.auth.User'", ")" ]
get the user document class user for mongoengine authentication .
train
false
43,233
def _find_monitor(cs, monitor): return utils.find_resource(cs.monitors, monitor)
[ "def", "_find_monitor", "(", "cs", ",", "monitor", ")", ":", "return", "utils", ".", "find_resource", "(", "cs", ".", "monitors", ",", "monitor", ")" ]
get a monitor by id .
train
false
43,235
def stack_partitions(dfs, divisions, join='outer'): meta = methods.concat([df._meta for df in dfs], join=join) empty = strip_unknown_categories(meta) name = 'concat-{0}'.format(tokenize(*dfs)) dsk = {} i = 0 for df in dfs: dsk.update(df.dask) try: (df._meta == meta) match = True except (ValueError, TypeError): match = False for key in df._keys(): if match: dsk[(name, i)] = key else: dsk[(name, i)] = (methods.concat, [empty, key], 0, join) i += 1 return new_dd_object(dsk, name, meta, divisions)
[ "def", "stack_partitions", "(", "dfs", ",", "divisions", ",", "join", "=", "'outer'", ")", ":", "meta", "=", "methods", ".", "concat", "(", "[", "df", ".", "_meta", "for", "df", "in", "dfs", "]", ",", "join", "=", "join", ")", "empty", "=", "strip_unknown_categories", "(", "meta", ")", "name", "=", "'concat-{0}'", ".", "format", "(", "tokenize", "(", "*", "dfs", ")", ")", "dsk", "=", "{", "}", "i", "=", "0", "for", "df", "in", "dfs", ":", "dsk", ".", "update", "(", "df", ".", "dask", ")", "try", ":", "(", "df", ".", "_meta", "==", "meta", ")", "match", "=", "True", "except", "(", "ValueError", ",", "TypeError", ")", ":", "match", "=", "False", "for", "key", "in", "df", ".", "_keys", "(", ")", ":", "if", "match", ":", "dsk", "[", "(", "name", ",", "i", ")", "]", "=", "key", "else", ":", "dsk", "[", "(", "name", ",", "i", ")", "]", "=", "(", "methods", ".", "concat", ",", "[", "empty", ",", "key", "]", ",", "0", ",", "join", ")", "i", "+=", "1", "return", "new_dd_object", "(", "dsk", ",", "name", ",", "meta", ",", "divisions", ")" ]
concatenate partitions on axis=0 by doing a simple stack .
train
false
43,236
def show_pillar(item=None): if item: return __salt__['pillar.get'](('oracle:' + item)) else: return __salt__['pillar.get']('oracle')
[ "def", "show_pillar", "(", "item", "=", "None", ")", ":", "if", "item", ":", "return", "__salt__", "[", "'pillar.get'", "]", "(", "(", "'oracle:'", "+", "item", ")", ")", "else", ":", "return", "__salt__", "[", "'pillar.get'", "]", "(", "'oracle'", ")" ]
show pillar segment oracle .
train
false
43,238
def is_array_scalar(x): return (np.size(x) == 1)
[ "def", "is_array_scalar", "(", "x", ")", ":", "return", "(", "np", ".", "size", "(", "x", ")", "==", "1", ")" ]
test whether x is either a scalar or an array scalar .
train
false
43,240
def export_pipeline(exported_pipeline): pipeline_tree = expr_to_tree(exported_pipeline) pipeline_text = generate_import_code(exported_pipeline) pipeline_text += pipeline_code_wrapper(generate_pipeline_code(pipeline_tree)) return pipeline_text
[ "def", "export_pipeline", "(", "exported_pipeline", ")", ":", "pipeline_tree", "=", "expr_to_tree", "(", "exported_pipeline", ")", "pipeline_text", "=", "generate_import_code", "(", "exported_pipeline", ")", "pipeline_text", "+=", "pipeline_code_wrapper", "(", "generate_pipeline_code", "(", "pipeline_tree", ")", ")", "return", "pipeline_text" ]
generates the source code of a tpot pipeline parameters exported_pipeline: deap .
train
false
43,241
def list_members_without_mfa(profile='github', ignore_cache=False): key = 'github.{0}:non_mfa_users'.format(_get_config_value(profile, 'org_name')) if ((key not in __context__) or ignore_cache): client = _get_client(profile) organization = client.get_organization(_get_config_value(profile, 'org_name')) filter_key = 'filter' if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key]
[ "def", "list_members_without_mfa", "(", "profile", "=", "'github'", ",", "ignore_cache", "=", "False", ")", ":", "key", "=", "'github.{0}:non_mfa_users'", ".", "format", "(", "_get_config_value", "(", "profile", ",", "'org_name'", ")", ")", "if", "(", "(", "key", "not", "in", "__context__", ")", "or", "ignore_cache", ")", ":", "client", "=", "_get_client", "(", "profile", ")", "organization", "=", "client", ".", "get_organization", "(", "_get_config_value", "(", "profile", ",", "'org_name'", ")", ")", "filter_key", "=", "'filter'", "if", "hasattr", "(", "github", ".", "Team", ".", "Team", ",", "'membership'", ")", ":", "filter_key", "=", "'filter_'", "__context__", "[", "key", "]", "=", "[", "m", ".", "login", ".", "lower", "(", ")", "for", "m", "in", "_get_members", "(", "organization", ",", "{", "filter_key", ":", "'2fa_disabled'", "}", ")", "]", "return", "__context__", "[", "key", "]" ]
list all members without mfa turned on .
train
true
43,242
def wordwrap(value, arg): from django.utils.text import wrap return wrap(value, int(arg))
[ "def", "wordwrap", "(", "value", ",", "arg", ")", ":", "from", "django", ".", "utils", ".", "text", "import", "wrap", "return", "wrap", "(", "value", ",", "int", "(", "arg", ")", ")" ]
wraps words at specified line length argument: number of characters to wrap the text at .
train
false
43,245
@task @set_modified_on def resize_icon(src, dst, locally=False, **kw): log.info(('[1@None] Resizing icon: %s' % dst)) try: resize_image(src, dst, (32, 32), locally=locally) return True except Exception as e: log.error(('Error saving collection icon: %s' % e))
[ "@", "task", "@", "set_modified_on", "def", "resize_icon", "(", "src", ",", "dst", ",", "locally", "=", "False", ",", "**", "kw", ")", ":", "log", ".", "info", "(", "(", "'[1@None] Resizing icon: %s'", "%", "dst", ")", ")", "try", ":", "resize_image", "(", "src", ",", "dst", ",", "(", "32", ",", "32", ")", ",", "locally", "=", "locally", ")", "return", "True", "except", "Exception", "as", "e", ":", "log", ".", "error", "(", "(", "'Error saving collection icon: %s'", "%", "e", ")", ")" ]
resizes collection icons to 32x32 .
train
false
43,246
def authenticationReject(): a = TpPd(pd=5) b = MessageType(mesType=17) packet = (a / b) return packet
[ "def", "authenticationReject", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "5", ")", "b", "=", "MessageType", "(", "mesType", "=", "17", ")", "packet", "=", "(", "a", "/", "b", ")", "return", "packet" ]
authentication reject section 9 .
train
true
43,247
@if_conch def generate_ssh_key(key_file): check_call(['ssh-keygen', '-f', key_file.path, '-N', '', '-q']) return Key.fromFile(key_file.path)
[ "@", "if_conch", "def", "generate_ssh_key", "(", "key_file", ")", ":", "check_call", "(", "[", "'ssh-keygen'", ",", "'-f'", ",", "key_file", ".", "path", ",", "'-N'", ",", "''", ",", "'-q'", "]", ")", "return", "Key", ".", "fromFile", "(", "key_file", ".", "path", ")" ]
generate a ssh key .
train
false
43,249
@keep_lazy_text def normalize_newlines(text): text = force_text(text) return re_newlines.sub('\n', text)
[ "@", "keep_lazy_text", "def", "normalize_newlines", "(", "text", ")", ":", "text", "=", "force_text", "(", "text", ")", "return", "re_newlines", ".", "sub", "(", "'\\n'", ",", "text", ")" ]
normalizes crlf and cr newlines to just lf .
train
false
43,251
def test_compound_custom_inverse(): poly = Polynomial1D(1, c0=1, c1=2) scale = Scale(1) shift = Shift(1) model1 = (poly | scale) model1.inverse = poly model2 = (shift | model1) assert_allclose(model2.inverse(1), (poly | shift.inverse)(1)) with pytest.raises(NotImplementedError): (shift + model1).inverse with pytest.raises(NotImplementedError): (model1 & poly).inverse
[ "def", "test_compound_custom_inverse", "(", ")", ":", "poly", "=", "Polynomial1D", "(", "1", ",", "c0", "=", "1", ",", "c1", "=", "2", ")", "scale", "=", "Scale", "(", "1", ")", "shift", "=", "Shift", "(", "1", ")", "model1", "=", "(", "poly", "|", "scale", ")", "model1", ".", "inverse", "=", "poly", "model2", "=", "(", "shift", "|", "model1", ")", "assert_allclose", "(", "model2", ".", "inverse", "(", "1", ")", ",", "(", "poly", "|", "shift", ".", "inverse", ")", "(", "1", ")", ")", "with", "pytest", ".", "raises", "(", "NotImplementedError", ")", ":", "(", "shift", "+", "model1", ")", ".", "inverse", "with", "pytest", ".", "raises", "(", "NotImplementedError", ")", ":", "(", "model1", "&", "poly", ")", ".", "inverse" ]
test that a compound model with a custom inverse has that inverse applied when the inverse of another model .
train
false
43,252
def _parse_file(document_file, validate, entry_class, entry_keyword='r', start_position=None, end_position=None, section_end_keywords=(), extra_args=()): if start_position: document_file.seek(start_position) else: start_position = document_file.tell() if section_end_keywords: first_keyword = None line_match = KEYWORD_LINE.match(stem.util.str_tools._to_unicode(document_file.readline())) if line_match: first_keyword = line_match.groups()[0] document_file.seek(start_position) if (first_keyword in section_end_keywords): return while ((end_position is None) or (document_file.tell() < end_position)): (desc_lines, ending_keyword) = _read_until_keywords(((entry_keyword,) + section_end_keywords), document_file, ignore_first=True, end_position=end_position, include_ending_keyword=True) desc_content = bytes.join('', desc_lines) if desc_content: (yield entry_class(desc_content, validate, *extra_args)) if (ending_keyword in section_end_keywords): break else: break
[ "def", "_parse_file", "(", "document_file", ",", "validate", ",", "entry_class", ",", "entry_keyword", "=", "'r'", ",", "start_position", "=", "None", ",", "end_position", "=", "None", ",", "section_end_keywords", "=", "(", ")", ",", "extra_args", "=", "(", ")", ")", ":", "if", "start_position", ":", "document_file", ".", "seek", "(", "start_position", ")", "else", ":", "start_position", "=", "document_file", ".", "tell", "(", ")", "if", "section_end_keywords", ":", "first_keyword", "=", "None", "line_match", "=", "KEYWORD_LINE", ".", "match", "(", "stem", ".", "util", ".", "str_tools", ".", "_to_unicode", "(", "document_file", ".", "readline", "(", ")", ")", ")", "if", "line_match", ":", "first_keyword", "=", "line_match", ".", "groups", "(", ")", "[", "0", "]", "document_file", ".", "seek", "(", "start_position", ")", "if", "(", "first_keyword", "in", "section_end_keywords", ")", ":", "return", "while", "(", "(", "end_position", "is", "None", ")", "or", "(", "document_file", ".", "tell", "(", ")", "<", "end_position", ")", ")", ":", "(", "desc_lines", ",", "ending_keyword", ")", "=", "_read_until_keywords", "(", "(", "(", "entry_keyword", ",", ")", "+", "section_end_keywords", ")", ",", "document_file", ",", "ignore_first", "=", "True", ",", "end_position", "=", "end_position", ",", "include_ending_keyword", "=", "True", ")", "desc_content", "=", "bytes", ".", "join", "(", "''", ",", "desc_lines", ")", "if", "desc_content", ":", "(", "yield", "entry_class", "(", "desc_content", ",", "validate", ",", "*", "extra_args", ")", ")", "if", "(", "ending_keyword", "in", "section_end_keywords", ")", ":", "break", "else", ":", "break" ]
iterates over a tordnsel file .
train
false
43,253
def _api_queue_priority(output, value, kwargs): value2 = kwargs.get('value2') if (value and value2): try: try: priority = int(value2) except: return report(output, _MSG_INT_VALUE) pos = set_priority(value, priority) return report(output, keyword='position', data=pos) except: return report(output, _MSG_NO_VALUE2) else: return report(output, _MSG_NO_VALUE2)
[ "def", "_api_queue_priority", "(", "output", ",", "value", ",", "kwargs", ")", ":", "value2", "=", "kwargs", ".", "get", "(", "'value2'", ")", "if", "(", "value", "and", "value2", ")", ":", "try", ":", "try", ":", "priority", "=", "int", "(", "value2", ")", "except", ":", "return", "report", "(", "output", ",", "_MSG_INT_VALUE", ")", "pos", "=", "set_priority", "(", "value", ",", "priority", ")", "return", "report", "(", "output", ",", "keyword", "=", "'position'", ",", "data", "=", "pos", ")", "except", ":", "return", "report", "(", "output", ",", "_MSG_NO_VALUE2", ")", "else", ":", "return", "report", "(", "output", ",", "_MSG_NO_VALUE2", ")" ]
api: accepts output .
train
false
43,254
def subnet_group_exists(name, tags=None, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if (not conn): return {'exists': bool(conn)} rds = conn.describe_db_subnet_groups(DBSubnetGroupName=name) return {'exists': bool(rds)} except ClientError as e: return {'error': salt.utils.boto3.get_error(e)}
[ "def", "subnet_group_exists", "(", "name", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "if", "(", "not", "conn", ")", ":", "return", "{", "'exists'", ":", "bool", "(", "conn", ")", "}", "rds", "=", "conn", ".", "describe_db_subnet_groups", "(", "DBSubnetGroupName", "=", "name", ")", "return", "{", "'exists'", ":", "bool", "(", "rds", ")", "}", "except", "ClientError", "as", "e", ":", "return", "{", "'error'", ":", "salt", ".", "utils", ".", "boto3", ".", "get_error", "(", "e", ")", "}" ]
check to see if an rds subnet group exists .
train
false
43,256
def pwd_from_uid(uid): global _uid_to_pwd_cache, _name_to_pwd_cache (entry, cached) = _cache_key_value(pwd.getpwuid, uid, _uid_to_pwd_cache) if (entry and (not cached)): _name_to_pwd_cache[entry.pw_name] = entry return entry
[ "def", "pwd_from_uid", "(", "uid", ")", ":", "global", "_uid_to_pwd_cache", ",", "_name_to_pwd_cache", "(", "entry", ",", "cached", ")", "=", "_cache_key_value", "(", "pwd", ".", "getpwuid", ",", "uid", ",", "_uid_to_pwd_cache", ")", "if", "(", "entry", "and", "(", "not", "cached", ")", ")", ":", "_name_to_pwd_cache", "[", "entry", ".", "pw_name", "]", "=", "entry", "return", "entry" ]
return password database entry for uid .
train
false
43,258
def must_have_addon(addon_name, model): def wrapper(func): @functools.wraps(func) @collect_auth def wrapped(*args, **kwargs): if (model == 'node'): _inject_nodes(kwargs) owner = kwargs['node'] elif (model == 'user'): auth = kwargs.get('auth') owner = (auth.user if auth else None) if (owner is None): raise HTTPError(http.UNAUTHORIZED) else: raise HTTPError(http.BAD_REQUEST) addon = owner.get_addon(addon_name) if (addon is None): raise HTTPError(http.BAD_REQUEST) kwargs['{0}_addon'.format(model)] = addon return func(*args, **kwargs) return wrapped return wrapper
[ "def", "must_have_addon", "(", "addon_name", ",", "model", ")", ":", "def", "wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "@", "collect_auth", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "model", "==", "'node'", ")", ":", "_inject_nodes", "(", "kwargs", ")", "owner", "=", "kwargs", "[", "'node'", "]", "elif", "(", "model", "==", "'user'", ")", ":", "auth", "=", "kwargs", ".", "get", "(", "'auth'", ")", "owner", "=", "(", "auth", ".", "user", "if", "auth", "else", "None", ")", "if", "(", "owner", "is", "None", ")", ":", "raise", "HTTPError", "(", "http", ".", "UNAUTHORIZED", ")", "else", ":", "raise", "HTTPError", "(", "http", ".", "BAD_REQUEST", ")", "addon", "=", "owner", ".", "get_addon", "(", "addon_name", ")", "if", "(", "addon", "is", "None", ")", ":", "raise", "HTTPError", "(", "http", ".", "BAD_REQUEST", ")", "kwargs", "[", "'{0}_addon'", ".", "format", "(", "model", ")", "]", "=", "addon", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapped", "return", "wrapper" ]
decorator factory that ensures that a given addon has been added to the target node .
train
false
43,259
def skip_if_disabled(func): @functools.wraps(func) def wrapped(*a, **kwargs): func.__test__ = False test_obj = a[0] message = getattr(test_obj, 'disabled_message', 'Test disabled') if getattr(test_obj, 'disabled', False): test_obj.skipTest(message) func(*a, **kwargs) return wrapped
[ "def", "skip_if_disabled", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "a", ",", "**", "kwargs", ")", ":", "func", ".", "__test__", "=", "False", "test_obj", "=", "a", "[", "0", "]", "message", "=", "getattr", "(", "test_obj", ",", "'disabled_message'", ",", "'Test disabled'", ")", "if", "getattr", "(", "test_obj", ",", "'disabled'", ",", "False", ")", ":", "test_obj", ".", "skipTest", "(", "message", ")", "func", "(", "*", "a", ",", "**", "kwargs", ")", "return", "wrapped" ]
decorator that skips a test if test case is disabled .
train
false
43,260
@register.inclusion_tag(u'includes/pagination.html', takes_context=True) def pagination_for(context, current_page, page_var=u'page', exclude_vars=u''): querystring = context[u'request'].GET.copy() exclude_vars = ([v for v in exclude_vars.split(u',') if v] + [page_var]) for exclude_var in exclude_vars: if (exclude_var in querystring): del querystring[exclude_var] querystring = querystring.urlencode() return {u'current_page': current_page, u'querystring': querystring, u'page_var': page_var}
[ "@", "register", ".", "inclusion_tag", "(", "u'includes/pagination.html'", ",", "takes_context", "=", "True", ")", "def", "pagination_for", "(", "context", ",", "current_page", ",", "page_var", "=", "u'page'", ",", "exclude_vars", "=", "u''", ")", ":", "querystring", "=", "context", "[", "u'request'", "]", ".", "GET", ".", "copy", "(", ")", "exclude_vars", "=", "(", "[", "v", "for", "v", "in", "exclude_vars", ".", "split", "(", "u','", ")", "if", "v", "]", "+", "[", "page_var", "]", ")", "for", "exclude_var", "in", "exclude_vars", ":", "if", "(", "exclude_var", "in", "querystring", ")", ":", "del", "querystring", "[", "exclude_var", "]", "querystring", "=", "querystring", ".", "urlencode", "(", ")", "return", "{", "u'current_page'", ":", "current_page", ",", "u'querystring'", ":", "querystring", ",", "u'page_var'", ":", "page_var", "}" ]
include the pagination template and data for persisting querystring in pagination links .
train
false
43,261
def get_stack_at_position(grammar, code_lines, module, pos): class EndMarkerReached(Exception, ): pass def tokenize_without_endmarker(code): tokens = tokenize.source_tokens(code, use_exact_op_types=True) for token_ in tokens: if (token_.string == safeword): raise EndMarkerReached() else: (yield token_) code = _get_code_for_stack(code_lines, module, pos) safeword = 'ZZZ_USER_WANTS_TO_COMPLETE_HERE_WITH_JEDI' code = (code + safeword) p = parser.ParserWithRecovery(grammar, code, start_parsing=False) try: p.parse(tokenizer=tokenize_without_endmarker(code)) except EndMarkerReached: return Stack(p.stack) raise SystemError("This really shouldn't happen. There's a bug in Jedi.")
[ "def", "get_stack_at_position", "(", "grammar", ",", "code_lines", ",", "module", ",", "pos", ")", ":", "class", "EndMarkerReached", "(", "Exception", ",", ")", ":", "pass", "def", "tokenize_without_endmarker", "(", "code", ")", ":", "tokens", "=", "tokenize", ".", "source_tokens", "(", "code", ",", "use_exact_op_types", "=", "True", ")", "for", "token_", "in", "tokens", ":", "if", "(", "token_", ".", "string", "==", "safeword", ")", ":", "raise", "EndMarkerReached", "(", ")", "else", ":", "(", "yield", "token_", ")", "code", "=", "_get_code_for_stack", "(", "code_lines", ",", "module", ",", "pos", ")", "safeword", "=", "'ZZZ_USER_WANTS_TO_COMPLETE_HERE_WITH_JEDI'", "code", "=", "(", "code", "+", "safeword", ")", "p", "=", "parser", ".", "ParserWithRecovery", "(", "grammar", ",", "code", ",", "start_parsing", "=", "False", ")", "try", ":", "p", ".", "parse", "(", "tokenizer", "=", "tokenize_without_endmarker", "(", "code", ")", ")", "except", "EndMarkerReached", ":", "return", "Stack", "(", "p", ".", "stack", ")", "raise", "SystemError", "(", "\"This really shouldn't happen. There's a bug in Jedi.\"", ")" ]
returns the possible node names .
train
false
43,262
def _create_diff(diff, fun, key, prev, curr): if (not fun(prev)): _create_diff_action(diff, 'added', key, curr) elif (fun(prev) and (not fun(curr))): _create_diff_action(diff, 'removed', key, prev) elif (not fun(curr)): _create_diff_action(diff, 'updated', key, curr)
[ "def", "_create_diff", "(", "diff", ",", "fun", ",", "key", ",", "prev", ",", "curr", ")", ":", "if", "(", "not", "fun", "(", "prev", ")", ")", ":", "_create_diff_action", "(", "diff", ",", "'added'", ",", "key", ",", "curr", ")", "elif", "(", "fun", "(", "prev", ")", "and", "(", "not", "fun", "(", "curr", ")", ")", ")", ":", "_create_diff_action", "(", "diff", ",", "'removed'", ",", "key", ",", "prev", ")", "elif", "(", "not", "fun", "(", "curr", ")", ")", ":", "_create_diff_action", "(", "diff", ",", "'updated'", ",", "key", ",", "curr", ")" ]
builds the diff dictionary .
train
true
43,263
def is_exe(filepath): return (os.path.exists(filepath) and os.access(filepath, os.X_OK))
[ "def", "is_exe", "(", "filepath", ")", ":", "return", "(", "os", ".", "path", ".", "exists", "(", "filepath", ")", "and", "os", ".", "access", "(", "filepath", ",", "os", ".", "X_OK", ")", ")" ]
test if a file is an executable .
train
false
43,264
def set_mako(mako, key=_registry_key, app=None): app = (app or webapp2.get_app()) app.registry[key] = mako
[ "def", "set_mako", "(", "mako", ",", "key", "=", "_registry_key", ",", "app", "=", "None", ")", ":", "app", "=", "(", "app", "or", "webapp2", ".", "get_app", "(", ")", ")", "app", ".", "registry", "[", "key", "]", "=", "mako" ]
sets an instance of :class:mako in the app registry .
train
false
43,265
def capacity_assessment_data(): return s3_rest_controller()
[ "def", "capacity_assessment_data", "(", ")", ":", "return", "s3_rest_controller", "(", ")" ]
restful crud controller - just used for the custom_report method .
train
false
43,268
@must_have_permission(ADMIN) @must_be_branched_from_node def draft_before_register_page(auth, node, draft, *args, **kwargs): ret = serialize_node(node, auth, primary=True) ret['draft'] = serialize_draft_registration(draft, auth) return ret
[ "@", "must_have_permission", "(", "ADMIN", ")", "@", "must_be_branched_from_node", "def", "draft_before_register_page", "(", "auth", ",", "node", ",", "draft", ",", "*", "args", ",", "**", "kwargs", ")", ":", "ret", "=", "serialize_node", "(", "node", ",", "auth", ",", "primary", "=", "True", ")", "ret", "[", "'draft'", "]", "=", "serialize_draft_registration", "(", "draft", ",", "auth", ")", "return", "ret" ]
allow the user to select an embargo period and confirm registration :return: serialized node + draftregistration :rtype: dict .
train
false
43,269
def getAnalyzePluginsDirectoryPath(subName=''): return getJoinedPath(getSkeinforgePluginsPath('analyze_plugins'), subName)
[ "def", "getAnalyzePluginsDirectoryPath", "(", "subName", "=", "''", ")", ":", "return", "getJoinedPath", "(", "getSkeinforgePluginsPath", "(", "'analyze_plugins'", ")", ",", "subName", ")" ]
get the analyze plugins directory path .
train
false
43,270
def _ns(tag, namespace=NAMESPACES['phy']): return ('{%s}%s' % (namespace, tag))
[ "def", "_ns", "(", "tag", ",", "namespace", "=", "NAMESPACES", "[", "'phy'", "]", ")", ":", "return", "(", "'{%s}%s'", "%", "(", "namespace", ",", "tag", ")", ")" ]
format an xml tag with the given namespace .
train
false
43,271
def decode_missing(line): result = {} parts = line.split() result['object_hash'] = urllib.parse.unquote(parts[0]) t_data = urllib.parse.unquote(parts[1]) result['ts_data'] = Timestamp(t_data) result['ts_meta'] = result['ts_ctype'] = result['ts_data'] if (len(parts) > 2): subparts = urllib.parse.unquote(parts[2]).split(',') for item in [subpart for subpart in subparts if (':' in subpart)]: (k, v) = item.split(':') if (k == 'm'): result['ts_meta'] = Timestamp(t_data, delta=int(v, 16)) elif (k == 't'): result['ts_ctype'] = Timestamp(t_data, delta=int(v, 16)) return result
[ "def", "decode_missing", "(", "line", ")", ":", "result", "=", "{", "}", "parts", "=", "line", ".", "split", "(", ")", "result", "[", "'object_hash'", "]", "=", "urllib", ".", "parse", ".", "unquote", "(", "parts", "[", "0", "]", ")", "t_data", "=", "urllib", ".", "parse", ".", "unquote", "(", "parts", "[", "1", "]", ")", "result", "[", "'ts_data'", "]", "=", "Timestamp", "(", "t_data", ")", "result", "[", "'ts_meta'", "]", "=", "result", "[", "'ts_ctype'", "]", "=", "result", "[", "'ts_data'", "]", "if", "(", "len", "(", "parts", ")", ">", "2", ")", ":", "subparts", "=", "urllib", ".", "parse", ".", "unquote", "(", "parts", "[", "2", "]", ")", ".", "split", "(", "','", ")", "for", "item", "in", "[", "subpart", "for", "subpart", "in", "subparts", "if", "(", "':'", "in", "subpart", ")", "]", ":", "(", "k", ",", "v", ")", "=", "item", ".", "split", "(", "':'", ")", "if", "(", "k", "==", "'m'", ")", ":", "result", "[", "'ts_meta'", "]", "=", "Timestamp", "(", "t_data", ",", "delta", "=", "int", "(", "v", ",", "16", ")", ")", "elif", "(", "k", "==", "'t'", ")", ":", "result", "[", "'ts_ctype'", "]", "=", "Timestamp", "(", "t_data", ",", "delta", "=", "int", "(", "v", ",", "16", ")", ")", "return", "result" ]
parse a string of the form generated by :py:func:~swift .
train
false
43,272
def EnumKey(key, index): regenumkeyex = advapi32['RegEnumKeyExW'] regenumkeyex.restype = ctypes.c_long regenumkeyex.argtypes = [ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.c_wchar_p, LPDWORD, LPDWORD, ctypes.c_wchar_p, LPDWORD, ctypes.POINTER(FileTime)] buf = ctypes.create_unicode_buffer(257) length = ctypes.wintypes.DWORD(257) rc = regenumkeyex(key.handle, index, ctypes.cast(buf, ctypes.c_wchar_p), ctypes.byref(length), LPDWORD(), ctypes.c_wchar_p(), LPDWORD(), ctypes.POINTER(FileTime)()) if (rc != 0): raise ctypes.WinError(2) return ctypes.wstring_at(buf, length.value).rstrip(u'\x00')
[ "def", "EnumKey", "(", "key", ",", "index", ")", ":", "regenumkeyex", "=", "advapi32", "[", "'RegEnumKeyExW'", "]", "regenumkeyex", ".", "restype", "=", "ctypes", ".", "c_long", "regenumkeyex", ".", "argtypes", "=", "[", "ctypes", ".", "c_void_p", ",", "ctypes", ".", "wintypes", ".", "DWORD", ",", "ctypes", ".", "c_wchar_p", ",", "LPDWORD", ",", "LPDWORD", ",", "ctypes", ".", "c_wchar_p", ",", "LPDWORD", ",", "ctypes", ".", "POINTER", "(", "FileTime", ")", "]", "buf", "=", "ctypes", ".", "create_unicode_buffer", "(", "257", ")", "length", "=", "ctypes", ".", "wintypes", ".", "DWORD", "(", "257", ")", "rc", "=", "regenumkeyex", "(", "key", ".", "handle", ",", "index", ",", "ctypes", ".", "cast", "(", "buf", ",", "ctypes", ".", "c_wchar_p", ")", ",", "ctypes", ".", "byref", "(", "length", ")", ",", "LPDWORD", "(", ")", ",", "ctypes", ".", "c_wchar_p", "(", ")", ",", "LPDWORD", "(", ")", ",", "ctypes", ".", "POINTER", "(", "FileTime", ")", "(", ")", ")", "if", "(", "rc", "!=", "0", ")", ":", "raise", "ctypes", ".", "WinError", "(", "2", ")", "return", "ctypes", ".", "wstring_at", "(", "buf", ",", "length", ".", "value", ")", ".", "rstrip", "(", "u'\\x00'", ")" ]
this calls the windows regenumkeyex function in a unicode safe way .
train
true
43,273
def get_acl_usr(msg): if hasattr(msg.frm, 'aclattr'): return msg.frm.aclattr return msg.frm.person
[ "def", "get_acl_usr", "(", "msg", ")", ":", "if", "hasattr", "(", "msg", ".", "frm", ",", "'aclattr'", ")", ":", "return", "msg", ".", "frm", ".", "aclattr", "return", "msg", ".", "frm", ".", "person" ]
return the acl attribute of the sender of the given message .
train
false
43,274
def get_device_count(verbose=False): try: import pycuda import pycuda.driver as drv except ImportError: if verbose: neon_logger.display('PyCUDA module not found') return 0 try: drv.init() except pycuda._driver.RuntimeError as e: neon_logger.display('PyCUDA Runtime error: {0}'.format(str(e))) return 0 count = drv.Device.count() if verbose: neon_logger.display('Found {} GPU(s)'.format(count)) return count
[ "def", "get_device_count", "(", "verbose", "=", "False", ")", ":", "try", ":", "import", "pycuda", "import", "pycuda", ".", "driver", "as", "drv", "except", "ImportError", ":", "if", "verbose", ":", "neon_logger", ".", "display", "(", "'PyCUDA module not found'", ")", "return", "0", "try", ":", "drv", ".", "init", "(", ")", "except", "pycuda", ".", "_driver", ".", "RuntimeError", "as", "e", ":", "neon_logger", ".", "display", "(", "'PyCUDA Runtime error: {0}'", ".", "format", "(", "str", "(", "e", ")", ")", ")", "return", "0", "count", "=", "drv", ".", "Device", ".", "count", "(", ")", "if", "verbose", ":", "neon_logger", ".", "display", "(", "'Found {} GPU(s)'", ".", "format", "(", "count", ")", ")", "return", "count" ]
query device count through pycuda .
train
false
43,275
def benchmark_influence(conf): prediction_times = [] prediction_powers = [] complexities = [] for param_value in conf['changing_param_values']: conf['tuned_params'][conf['changing_param']] = param_value estimator = conf['estimator'](**conf['tuned_params']) print ('Benchmarking %s' % estimator) estimator.fit(conf['data']['X_train'], conf['data']['y_train']) conf['postfit_hook'](estimator) complexity = conf['complexity_computer'](estimator) complexities.append(complexity) start_time = time.time() for _ in range(conf['n_samples']): y_pred = estimator.predict(conf['data']['X_test']) elapsed_time = ((time.time() - start_time) / float(conf['n_samples'])) prediction_times.append(elapsed_time) pred_score = conf['prediction_performance_computer'](conf['data']['y_test'], y_pred) prediction_powers.append(pred_score) print ('Complexity: %d | %s: %.4f | Pred. Time: %fs\n' % (complexity, conf['prediction_performance_label'], pred_score, elapsed_time)) return (prediction_powers, prediction_times, complexities)
[ "def", "benchmark_influence", "(", "conf", ")", ":", "prediction_times", "=", "[", "]", "prediction_powers", "=", "[", "]", "complexities", "=", "[", "]", "for", "param_value", "in", "conf", "[", "'changing_param_values'", "]", ":", "conf", "[", "'tuned_params'", "]", "[", "conf", "[", "'changing_param'", "]", "]", "=", "param_value", "estimator", "=", "conf", "[", "'estimator'", "]", "(", "**", "conf", "[", "'tuned_params'", "]", ")", "print", "(", "'Benchmarking %s'", "%", "estimator", ")", "estimator", ".", "fit", "(", "conf", "[", "'data'", "]", "[", "'X_train'", "]", ",", "conf", "[", "'data'", "]", "[", "'y_train'", "]", ")", "conf", "[", "'postfit_hook'", "]", "(", "estimator", ")", "complexity", "=", "conf", "[", "'complexity_computer'", "]", "(", "estimator", ")", "complexities", ".", "append", "(", "complexity", ")", "start_time", "=", "time", ".", "time", "(", ")", "for", "_", "in", "range", "(", "conf", "[", "'n_samples'", "]", ")", ":", "y_pred", "=", "estimator", ".", "predict", "(", "conf", "[", "'data'", "]", "[", "'X_test'", "]", ")", "elapsed_time", "=", "(", "(", "time", ".", "time", "(", ")", "-", "start_time", ")", "/", "float", "(", "conf", "[", "'n_samples'", "]", ")", ")", "prediction_times", ".", "append", "(", "elapsed_time", ")", "pred_score", "=", "conf", "[", "'prediction_performance_computer'", "]", "(", "conf", "[", "'data'", "]", "[", "'y_test'", "]", ",", "y_pred", ")", "prediction_powers", ".", "append", "(", "pred_score", ")", "print", "(", "'Complexity: %d | %s: %.4f | Pred. Time: %fs\\n'", "%", "(", "complexity", ",", "conf", "[", "'prediction_performance_label'", "]", ",", "pred_score", ",", "elapsed_time", ")", ")", "return", "(", "prediction_powers", ",", "prediction_times", ",", "complexities", ")" ]
benchmark influence of :changing_param: on both mse and latency .
train
false
43,276
def eligible_for_deletion(conf, namespace, force=False): if conf.agent_type: prefixes = NS_PREFIXES.get(conf.agent_type) else: prefixes = itertools.chain(*NS_PREFIXES.values()) ns_mangling_pattern = ('(%s%s)' % ('|'.join(prefixes), constants.UUID_PATTERN)) if (not re.match(ns_mangling_pattern, namespace)): return False ip = ip_lib.IPWrapper(namespace=namespace) return (force or ip.namespace_is_empty())
[ "def", "eligible_for_deletion", "(", "conf", ",", "namespace", ",", "force", "=", "False", ")", ":", "if", "conf", ".", "agent_type", ":", "prefixes", "=", "NS_PREFIXES", ".", "get", "(", "conf", ".", "agent_type", ")", "else", ":", "prefixes", "=", "itertools", ".", "chain", "(", "*", "NS_PREFIXES", ".", "values", "(", ")", ")", "ns_mangling_pattern", "=", "(", "'(%s%s)'", "%", "(", "'|'", ".", "join", "(", "prefixes", ")", ",", "constants", ".", "UUID_PATTERN", ")", ")", "if", "(", "not", "re", ".", "match", "(", "ns_mangling_pattern", ",", "namespace", ")", ")", ":", "return", "False", "ip", "=", "ip_lib", ".", "IPWrapper", "(", "namespace", "=", "namespace", ")", "return", "(", "force", "or", "ip", ".", "namespace_is_empty", "(", ")", ")" ]
determine whether a namespace is eligible for deletion .
train
false
43,277
def ll_op(left, right): if (len(left) > 0): ll_gate = left[0] ll_gate_is_unitary = is_scalar_matrix((Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True) if ((len(left) > 0) and ll_gate_is_unitary): new_left = left[1:len(left)] new_right = ((Dagger(ll_gate),) + right) return (new_left, new_right) return None
[ "def", "ll_op", "(", "left", ",", "right", ")", ":", "if", "(", "len", "(", "left", ")", ">", "0", ")", ":", "ll_gate", "=", "left", "[", "0", "]", "ll_gate_is_unitary", "=", "is_scalar_matrix", "(", "(", "Dagger", "(", "ll_gate", ")", ",", "ll_gate", ")", ",", "_get_min_qubits", "(", "ll_gate", ")", ",", "True", ")", "if", "(", "(", "len", "(", "left", ")", ">", "0", ")", "and", "ll_gate_is_unitary", ")", ":", "new_left", "=", "left", "[", "1", ":", "len", "(", "left", ")", "]", "new_right", "=", "(", "(", "Dagger", "(", "ll_gate", ")", ",", ")", "+", "right", ")", "return", "(", "new_left", ",", "new_right", ")", "return", "None" ]
perform a ll operation .
train
false
43,278
def example1(): l_in = lasagne.layers.InputLayer((100, 20)) l_hidden1 = lasagne.layers.DenseLayer(l_in, num_units=20) l_hidden1_dropout = lasagne.layers.DropoutLayer(l_hidden1) l_hidden2 = lasagne.layers.DenseLayer(l_hidden1_dropout, num_units=20) l_hidden2_dropout = lasagne.layers.DropoutLayer(l_hidden2) l_out = lasagne.layers.DenseLayer(l_hidden2_dropout, num_units=10) print get_network_str(l_out) return None
[ "def", "example1", "(", ")", ":", "l_in", "=", "lasagne", ".", "layers", ".", "InputLayer", "(", "(", "100", ",", "20", ")", ")", "l_hidden1", "=", "lasagne", ".", "layers", ".", "DenseLayer", "(", "l_in", ",", "num_units", "=", "20", ")", "l_hidden1_dropout", "=", "lasagne", ".", "layers", ".", "DropoutLayer", "(", "l_hidden1", ")", "l_hidden2", "=", "lasagne", ".", "layers", ".", "DenseLayer", "(", "l_hidden1_dropout", ",", "num_units", "=", "20", ")", "l_hidden2_dropout", "=", "lasagne", ".", "layers", ".", "DropoutLayer", "(", "l_hidden2", ")", "l_out", "=", "lasagne", ".", "layers", ".", "DenseLayer", "(", "l_hidden2_dropout", ",", "num_units", "=", "10", ")", "print", "get_network_str", "(", "l_out", ")", "return", "None" ]
sequential network .
train
false
43,279
def keys(name, basepath='/etc/pki'): ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} pillar = __salt__['pillar.ext']({'libvirt': '_'}) paths = {'serverkey': os.path.join(basepath, 'libvirt', 'private', 'serverkey.pem'), 'servercert': os.path.join(basepath, 'libvirt', 'servercert.pem'), 'clientkey': os.path.join(basepath, 'libvirt', 'private', 'clientkey.pem'), 'clientcert': os.path.join(basepath, 'libvirt', 'clientcert.pem'), 'cacert': os.path.join(basepath, 'CA', 'cacert.pem')} for key in paths: p_key = 'libvirt.{0}.pem'.format(key) if (p_key not in pillar): continue if (not os.path.exists(os.path.dirname(paths[key]))): os.makedirs(os.path.dirname(paths[key])) if os.path.isfile(paths[key]): with salt.utils.fopen(paths[key], 'r') as fp_: if (fp_.read() != pillar[p_key]): ret['changes'][key] = 'update' else: ret['changes'][key] = 'new' if (not ret['changes']): ret['comment'] = 'All keys are correct' elif __opts__['test']: ret['result'] = None ret['comment'] = 'Libvirt keys are set to be updated' ret['changes'] = {} else: for key in ret['changes']: with salt.utils.fopen(paths[key], 'w+') as fp_: fp_.write(pillar['libvirt.{0}.pem'.format(key)]) ret['comment'] = 'Updated libvirt certs and keys' return ret
[ "def", "keys", "(", "name", ",", "basepath", "=", "'/etc/pki'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "pillar", "=", "__salt__", "[", "'pillar.ext'", "]", "(", "{", "'libvirt'", ":", "'_'", "}", ")", "paths", "=", "{", "'serverkey'", ":", "os", ".", "path", ".", "join", "(", "basepath", ",", "'libvirt'", ",", "'private'", ",", "'serverkey.pem'", ")", ",", "'servercert'", ":", "os", ".", "path", ".", "join", "(", "basepath", ",", "'libvirt'", ",", "'servercert.pem'", ")", ",", "'clientkey'", ":", "os", ".", "path", ".", "join", "(", "basepath", ",", "'libvirt'", ",", "'private'", ",", "'clientkey.pem'", ")", ",", "'clientcert'", ":", "os", ".", "path", ".", "join", "(", "basepath", ",", "'libvirt'", ",", "'clientcert.pem'", ")", ",", "'cacert'", ":", "os", ".", "path", ".", "join", "(", "basepath", ",", "'CA'", ",", "'cacert.pem'", ")", "}", "for", "key", "in", "paths", ":", "p_key", "=", "'libvirt.{0}.pem'", ".", "format", "(", "key", ")", "if", "(", "p_key", "not", "in", "pillar", ")", ":", "continue", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "paths", "[", "key", "]", ")", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "paths", "[", "key", "]", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "paths", "[", "key", "]", ")", ":", "with", "salt", ".", "utils", ".", "fopen", "(", "paths", "[", "key", "]", ",", "'r'", ")", "as", "fp_", ":", "if", "(", "fp_", ".", "read", "(", ")", "!=", "pillar", "[", "p_key", "]", ")", ":", "ret", "[", "'changes'", "]", "[", "key", "]", "=", "'update'", "else", ":", "ret", "[", "'changes'", "]", "[", "key", "]", "=", "'new'", "if", "(", "not", "ret", "[", "'changes'", "]", ")", ":", "ret", "[", "'comment'", "]", "=", "'All keys are correct'", "elif", "__opts__", "[", "'test'", "]", ":", "ret", "[", "'result'", "]", "=", "None", "ret", "[", "'comment'", "]", "=", "'Libvirt keys are set to be updated'", "ret", "[", "'changes'", "]", "=", "{", "}", "else", ":", "for", "key", "in", "ret", "[", "'changes'", "]", ":", "with", "salt", ".", "utils", ".", "fopen", "(", "paths", "[", "key", "]", ",", "'w+'", ")", "as", "fp_", ":", "fp_", ".", "write", "(", "pillar", "[", "'libvirt.{0}.pem'", ".", "format", "(", "key", ")", "]", ")", "ret", "[", "'comment'", "]", "=", "'Updated libvirt certs and keys'", "return", "ret" ]
a context manager that sets up the correct keyczar environment for a test .
train
false
43,280
def varcorrection_unequal(var_all, nobs_all, df_all): var_all = np.asarray(var_all) var_over_n = ((var_all * 1.0) / nobs_all) varjoint = var_over_n.sum() dfjoint = ((varjoint ** 2) / ((var_over_n ** 2) * df_all).sum()) return (varjoint, dfjoint)
[ "def", "varcorrection_unequal", "(", "var_all", ",", "nobs_all", ",", "df_all", ")", ":", "var_all", "=", "np", ".", "asarray", "(", "var_all", ")", "var_over_n", "=", "(", "(", "var_all", "*", "1.0", ")", "/", "nobs_all", ")", "varjoint", "=", "var_over_n", ".", "sum", "(", ")", "dfjoint", "=", "(", "(", "varjoint", "**", "2", ")", "/", "(", "(", "var_over_n", "**", "2", ")", "*", "df_all", ")", ".", "sum", "(", ")", ")", "return", "(", "varjoint", ",", "dfjoint", ")" ]
return joint variance from samples with unequal variances and unequal sample sizes something is wrong parameters var_all : array_like the variance for each sample nobs_all : array_like the number of observations for each sample df_all : array_like degrees of freedom for each sample returns varjoint : float joint variance .
train
false
43,282
def get_manual_interface_attributes(interface, module): if (get_interface_type(interface) == 'svi'): command = ('show interface ' + interface) try: body = execute_modified_show_for_cli_text(command, module)[0] except (IndexError, ShellError): return None command_list = body.split('\n') desc = None admin_state = 'up' for each in command_list: if ('Description:' in each): line = each.split('Description:') desc = line[1].strip().split('MTU')[0].strip() elif ('Administratively down' in each): admin_state = 'down' return dict(description=desc, admin_state=admin_state) else: return None
[ "def", "get_manual_interface_attributes", "(", "interface", ",", "module", ")", ":", "if", "(", "get_interface_type", "(", "interface", ")", "==", "'svi'", ")", ":", "command", "=", "(", "'show interface '", "+", "interface", ")", "try", ":", "body", "=", "execute_modified_show_for_cli_text", "(", "command", ",", "module", ")", "[", "0", "]", "except", "(", "IndexError", ",", "ShellError", ")", ":", "return", "None", "command_list", "=", "body", ".", "split", "(", "'\\n'", ")", "desc", "=", "None", "admin_state", "=", "'up'", "for", "each", "in", "command_list", ":", "if", "(", "'Description:'", "in", "each", ")", ":", "line", "=", "each", ".", "split", "(", "'Description:'", ")", "desc", "=", "line", "[", "1", "]", ".", "strip", "(", ")", ".", "split", "(", "'MTU'", ")", "[", "0", "]", ".", "strip", "(", ")", "elif", "(", "'Administratively down'", "in", "each", ")", ":", "admin_state", "=", "'down'", "return", "dict", "(", "description", "=", "desc", ",", "admin_state", "=", "admin_state", ")", "else", ":", "return", "None" ]
gets admin state and description of a svi interface .
train
false
43,284
def get_nodes(node, klass): for child in node.children: if isinstance(child, klass): (yield child) for grandchild in get_nodes(child, klass): (yield grandchild)
[ "def", "get_nodes", "(", "node", ",", "klass", ")", ":", "for", "child", "in", "node", ".", "children", ":", "if", "isinstance", "(", "child", ",", "klass", ")", ":", "(", "yield", "child", ")", "for", "grandchild", "in", "get_nodes", "(", "child", ",", "klass", ")", ":", "(", "yield", "grandchild", ")" ]
return an iterator on all children node of the given klass .
train
false
43,286
@handle_response_format @treeio_login_required @_process_mass_form def index_assigned(request, response_format='html'): context = _get_default_context(request) agent = context['agent'] if agent: query = Q(assigned=agent) if request.GET: if (('status' in request.GET) and request.GET['status']): query = (query & _get_filter_query(request.GET)) else: query = ((query & Q(status__hidden=False)) & _get_filter_query(request.GET)) else: query = (query & Q(status__hidden=False)) tickets = Object.filter_by_request(request, Ticket.objects.filter(query)) else: return user_denied(request, 'You are not a Service Support Agent.', response_format=response_format) filters = FilterForm(request.user.profile, 'assigned', request.GET) context.update({'tickets': tickets, 'filters': filters}) return render_to_response('services/index_assigned', context, context_instance=RequestContext(request), response_format=response_format)
[ "@", "handle_response_format", "@", "treeio_login_required", "@", "_process_mass_form", "def", "index_assigned", "(", "request", ",", "response_format", "=", "'html'", ")", ":", "context", "=", "_get_default_context", "(", "request", ")", "agent", "=", "context", "[", "'agent'", "]", "if", "agent", ":", "query", "=", "Q", "(", "assigned", "=", "agent", ")", "if", "request", ".", "GET", ":", "if", "(", "(", "'status'", "in", "request", ".", "GET", ")", "and", "request", ".", "GET", "[", "'status'", "]", ")", ":", "query", "=", "(", "query", "&", "_get_filter_query", "(", "request", ".", "GET", ")", ")", "else", ":", "query", "=", "(", "(", "query", "&", "Q", "(", "status__hidden", "=", "False", ")", ")", "&", "_get_filter_query", "(", "request", ".", "GET", ")", ")", "else", ":", "query", "=", "(", "query", "&", "Q", "(", "status__hidden", "=", "False", ")", ")", "tickets", "=", "Object", ".", "filter_by_request", "(", "request", ",", "Ticket", ".", "objects", ".", "filter", "(", "query", ")", ")", "else", ":", "return", "user_denied", "(", "request", ",", "'You are not a Service Support Agent.'", ",", "response_format", "=", "response_format", ")", "filters", "=", "FilterForm", "(", "request", ".", "user", ".", "profile", ",", "'assigned'", ",", "request", ".", "GET", ")", "context", ".", "update", "(", "{", "'tickets'", ":", "tickets", ",", "'filters'", ":", "filters", "}", ")", "return", "render_to_response", "(", "'services/index_assigned'", ",", "context", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ",", "response_format", "=", "response_format", ")" ]
tickets assigned to current user .
train
false
43,287
def parse_host_list(list_of_hosts): p = set((m.group(1) for m in re.finditer('\\s*([^,\\s]+)\\s*,?\\s*', list_of_hosts))) return p
[ "def", "parse_host_list", "(", "list_of_hosts", ")", ":", "p", "=", "set", "(", "(", "m", ".", "group", "(", "1", ")", "for", "m", "in", "re", ".", "finditer", "(", "'\\\\s*([^,\\\\s]+)\\\\s*,?\\\\s*'", ",", "list_of_hosts", ")", ")", ")", "return", "p" ]
parse the comma separated list of hosts .
train
false
43,292
def getScalarMetricWithTimeOfDayAnomalyParams(metricData, minVal=None, maxVal=None, minResolution=None, tmImplementation='cpp'): if (minResolution is None): minResolution = 0.001 if ((minVal is None) or (maxVal is None)): (compMinVal, compMaxVal) = _rangeGen(metricData) if (minVal is None): minVal = compMinVal if (maxVal is None): maxVal = compMaxVal if (minVal == maxVal): maxVal = (minVal + 1) if (tmImplementation is 'cpp'): paramFileRelativePath = os.path.join('anomaly_params_random_encoder', 'best_single_metric_anomaly_params_cpp.json') elif (tmImplementation is 'tm_cpp'): paramFileRelativePath = os.path.join('anomaly_params_random_encoder', 'best_single_metric_anomaly_params_tm_cpp.json') else: raise ValueError('Invalid string for tmImplementation. Try cpp or tm_cpp') with resource_stream(__name__, paramFileRelativePath) as infile: paramSet = json.load(infile) _fixupRandomEncoderParams(paramSet, minVal, maxVal, minResolution) return paramSet
[ "def", "getScalarMetricWithTimeOfDayAnomalyParams", "(", "metricData", ",", "minVal", "=", "None", ",", "maxVal", "=", "None", ",", "minResolution", "=", "None", ",", "tmImplementation", "=", "'cpp'", ")", ":", "if", "(", "minResolution", "is", "None", ")", ":", "minResolution", "=", "0.001", "if", "(", "(", "minVal", "is", "None", ")", "or", "(", "maxVal", "is", "None", ")", ")", ":", "(", "compMinVal", ",", "compMaxVal", ")", "=", "_rangeGen", "(", "metricData", ")", "if", "(", "minVal", "is", "None", ")", ":", "minVal", "=", "compMinVal", "if", "(", "maxVal", "is", "None", ")", ":", "maxVal", "=", "compMaxVal", "if", "(", "minVal", "==", "maxVal", ")", ":", "maxVal", "=", "(", "minVal", "+", "1", ")", "if", "(", "tmImplementation", "is", "'cpp'", ")", ":", "paramFileRelativePath", "=", "os", ".", "path", ".", "join", "(", "'anomaly_params_random_encoder'", ",", "'best_single_metric_anomaly_params_cpp.json'", ")", "elif", "(", "tmImplementation", "is", "'tm_cpp'", ")", ":", "paramFileRelativePath", "=", "os", ".", "path", ".", "join", "(", "'anomaly_params_random_encoder'", ",", "'best_single_metric_anomaly_params_tm_cpp.json'", ")", "else", ":", "raise", "ValueError", "(", "'Invalid string for tmImplementation. Try cpp or tm_cpp'", ")", "with", "resource_stream", "(", "__name__", ",", "paramFileRelativePath", ")", "as", "infile", ":", "paramSet", "=", "json", ".", "load", "(", "infile", ")", "_fixupRandomEncoderParams", "(", "paramSet", ",", "minVal", ",", "maxVal", ",", "minResolution", ")", "return", "paramSet" ]
return a dict that can be used to create an anomaly model via opfs modelfactory .
train
true
43,293
def parse_response(resp, content, strict=False, content_type=None): if (not content_type): content_type = resp.headers.get('content-type', 'application/json') (ct, options) = parse_options_header(content_type) if (ct in ('application/json', 'text/javascript')): if (not content): return {} return json.loads(content) if (ct in ('application/xml', 'text/xml')): return get_etree().fromstring(content) if ((ct != 'application/x-www-form-urlencoded') and strict): return content charset = options.get('charset', 'utf-8') return url_decode(content, charset=charset).to_dict()
[ "def", "parse_response", "(", "resp", ",", "content", ",", "strict", "=", "False", ",", "content_type", "=", "None", ")", ":", "if", "(", "not", "content_type", ")", ":", "content_type", "=", "resp", ".", "headers", ".", "get", "(", "'content-type'", ",", "'application/json'", ")", "(", "ct", ",", "options", ")", "=", "parse_options_header", "(", "content_type", ")", "if", "(", "ct", "in", "(", "'application/json'", ",", "'text/javascript'", ")", ")", ":", "if", "(", "not", "content", ")", ":", "return", "{", "}", "return", "json", ".", "loads", "(", "content", ")", "if", "(", "ct", "in", "(", "'application/xml'", ",", "'text/xml'", ")", ")", ":", "return", "get_etree", "(", ")", ".", "fromstring", "(", "content", ")", "if", "(", "(", "ct", "!=", "'application/x-www-form-urlencoded'", ")", "and", "strict", ")", ":", "return", "content", "charset", "=", "options", ".", "get", "(", "'charset'", ",", "'utf-8'", ")", "return", "url_decode", "(", "content", ",", "charset", "=", "charset", ")", ".", "to_dict", "(", ")" ]
try and parse response as an http response .
train
true
43,294
def getKeyIsInPixelTableAddValue(key, pathIndexTable, pixelTable): if (key in pixelTable): value = pixelTable[key] if (value != None): pathIndexTable[value] = None return True return False
[ "def", "getKeyIsInPixelTableAddValue", "(", "key", ",", "pathIndexTable", ",", "pixelTable", ")", ":", "if", "(", "key", "in", "pixelTable", ")", ":", "value", "=", "pixelTable", "[", "key", "]", "if", "(", "value", "!=", "None", ")", ":", "pathIndexTable", "[", "value", "]", "=", "None", "return", "True", "return", "False" ]
determine if the key is in the pixel table .
train
false
43,295
def failureFromJSON(failureDict): newFailure = getattr(Failure, '__new__', None) if (newFailure is None): f = types.InstanceType(Failure) else: f = newFailure(Failure) if (not _PY3): failureDict = asBytes(failureDict) typeInfo = failureDict['type'] failureDict['type'] = type(typeInfo['__name__'], (), typeInfo) f.__dict__ = failureDict return f
[ "def", "failureFromJSON", "(", "failureDict", ")", ":", "newFailure", "=", "getattr", "(", "Failure", ",", "'__new__'", ",", "None", ")", "if", "(", "newFailure", "is", "None", ")", ":", "f", "=", "types", ".", "InstanceType", "(", "Failure", ")", "else", ":", "f", "=", "newFailure", "(", "Failure", ")", "if", "(", "not", "_PY3", ")", ":", "failureDict", "=", "asBytes", "(", "failureDict", ")", "typeInfo", "=", "failureDict", "[", "'type'", "]", "failureDict", "[", "'type'", "]", "=", "type", "(", "typeInfo", "[", "'__name__'", "]", ",", "(", ")", ",", "typeInfo", ")", "f", ".", "__dict__", "=", "failureDict", "return", "f" ]
load a l{failure} from a dictionary deserialized from json .
train
false
43,296
def ld_cifar10(test_only=False): file_urls = ['https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'] local_urls = maybe_download(file_urls, FLAGS.data_dir) dataset = extract_cifar10(local_urls[0], FLAGS.data_dir) (train_data, train_labels, test_data, test_labels) = dataset train_data = image_whitening(train_data) test_data = image_whitening(test_data) if test_only: return (test_data, test_labels) else: return (train_data, train_labels, test_data, test_labels)
[ "def", "ld_cifar10", "(", "test_only", "=", "False", ")", ":", "file_urls", "=", "[", "'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'", "]", "local_urls", "=", "maybe_download", "(", "file_urls", ",", "FLAGS", ".", "data_dir", ")", "dataset", "=", "extract_cifar10", "(", "local_urls", "[", "0", "]", ",", "FLAGS", ".", "data_dir", ")", "(", "train_data", ",", "train_labels", ",", "test_data", ",", "test_labels", ")", "=", "dataset", "train_data", "=", "image_whitening", "(", "train_data", ")", "test_data", "=", "image_whitening", "(", "test_data", ")", "if", "test_only", ":", "return", "(", "test_data", ",", "test_labels", ")", "else", ":", "return", "(", "train_data", ",", "train_labels", ",", "test_data", ",", "test_labels", ")" ]
load the original cifar10 data .
train
false
43,297
def CredibleInterval(pmf, percentage=90): cdf = pmf.MakeCdf() prob = ((1 - (percentage / 100.0)) / 2) interval = (cdf.Value(prob), cdf.Value((1 - prob))) return interval
[ "def", "CredibleInterval", "(", "pmf", ",", "percentage", "=", "90", ")", ":", "cdf", "=", "pmf", ".", "MakeCdf", "(", ")", "prob", "=", "(", "(", "1", "-", "(", "percentage", "/", "100.0", ")", ")", "/", "2", ")", "interval", "=", "(", "cdf", ".", "Value", "(", "prob", ")", ",", "cdf", ".", "Value", "(", "(", "1", "-", "prob", ")", ")", ")", "return", "interval" ]
computes a credible interval for a given distribution .
train
true
43,301
def webattack_vector(attack_vector): return {'1': 'java', '2': 'browser', '3': 'harvester', '4': 'tabnapping', '5': 'webjacking', '6': 'multiattack', '7': 'fsattack'}.get(attack_vector, 'ERROR')
[ "def", "webattack_vector", "(", "attack_vector", ")", ":", "return", "{", "'1'", ":", "'java'", ",", "'2'", ":", "'browser'", ",", "'3'", ":", "'harvester'", ",", "'4'", ":", "'tabnapping'", ",", "'5'", ":", "'webjacking'", ",", "'6'", ":", "'multiattack'", ",", "'7'", ":", "'fsattack'", "}", ".", "get", "(", "attack_vector", ",", "'ERROR'", ")" ]
receives the input given by the user from set .
train
false
43,302
def transform_column_source_data(data): data_copy = {} for key in iterkeys(data): if (pd and isinstance(data[key], (pd.Series, pd.Index))): data_copy[key] = transform_series(data[key]) elif isinstance(data[key], np.ndarray): data_copy[key] = transform_array(data[key]) else: data_copy[key] = traverse_data(data[key]) return data_copy
[ "def", "transform_column_source_data", "(", "data", ")", ":", "data_copy", "=", "{", "}", "for", "key", "in", "iterkeys", "(", "data", ")", ":", "if", "(", "pd", "and", "isinstance", "(", "data", "[", "key", "]", ",", "(", "pd", ".", "Series", ",", "pd", ".", "Index", ")", ")", ")", ":", "data_copy", "[", "key", "]", "=", "transform_series", "(", "data", "[", "key", "]", ")", "elif", "isinstance", "(", "data", "[", "key", "]", ",", "np", ".", "ndarray", ")", ":", "data_copy", "[", "key", "]", "=", "transform_array", "(", "data", "[", "key", "]", ")", "else", ":", "data_copy", "[", "key", "]", "=", "traverse_data", "(", "data", "[", "key", "]", ")", "return", "data_copy" ]
transform columnsourcedata data to a serialized format args: data : the mapping of names to data columns to transform returns: json compatible dict .
train
false
43,303
def patch_signal(): patch_module('signal')
[ "def", "patch_signal", "(", ")", ":", "patch_module", "(", "'signal'", ")" ]
make the signal .
train
false
43,309
def ConvertToNumber(value): try: return int(value) except: return float(value)
[ "def", "ConvertToNumber", "(", "value", ")", ":", "try", ":", "return", "int", "(", "value", ")", "except", ":", "return", "float", "(", "value", ")" ]
converts value .
train
false
43,310
def set_proxy(proxy, user=None, password=''): from nltk import compat if (proxy is None): try: proxy = getproxies()['http'] except KeyError: raise ValueError('Could not detect default proxy settings') proxy_handler = ProxyHandler({'http': proxy}) opener = build_opener(proxy_handler) if (user is not None): password_manager = HTTPPasswordMgrWithDefaultRealm() password_manager.add_password(realm=None, uri=proxy, user=user, passwd=password) opener.add_handler(ProxyBasicAuthHandler(password_manager)) opener.add_handler(ProxyDigestAuthHandler(password_manager)) install_opener(opener)
[ "def", "set_proxy", "(", "proxy", ",", "user", "=", "None", ",", "password", "=", "''", ")", ":", "from", "nltk", "import", "compat", "if", "(", "proxy", "is", "None", ")", ":", "try", ":", "proxy", "=", "getproxies", "(", ")", "[", "'http'", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Could not detect default proxy settings'", ")", "proxy_handler", "=", "ProxyHandler", "(", "{", "'http'", ":", "proxy", "}", ")", "opener", "=", "build_opener", "(", "proxy_handler", ")", "if", "(", "user", "is", "not", "None", ")", ":", "password_manager", "=", "HTTPPasswordMgrWithDefaultRealm", "(", ")", "password_manager", ".", "add_password", "(", "realm", "=", "None", ",", "uri", "=", "proxy", ",", "user", "=", "user", ",", "passwd", "=", "password", ")", "opener", ".", "add_handler", "(", "ProxyBasicAuthHandler", "(", "password_manager", ")", ")", "opener", ".", "add_handler", "(", "ProxyDigestAuthHandler", "(", "password_manager", ")", ")", "install_opener", "(", "opener", ")" ]
set the http proxy for python to download through .
train
false
43,311
def yaml_encode(data): yrepr = yaml.representer.SafeRepresenter() ynode = yrepr.represent_data(data) if (not isinstance(ynode, yaml.ScalarNode)): raise TypeError('yaml_encode() only works with YAML scalar data; failed for {0}'.format(type(data))) tag = ynode.tag.rsplit(':', 1)[(-1)] ret = ynode.value if (tag == 'str'): ret = yaml_dquote(ynode.value) return ret
[ "def", "yaml_encode", "(", "data", ")", ":", "yrepr", "=", "yaml", ".", "representer", ".", "SafeRepresenter", "(", ")", "ynode", "=", "yrepr", ".", "represent_data", "(", "data", ")", "if", "(", "not", "isinstance", "(", "ynode", ",", "yaml", ".", "ScalarNode", ")", ")", ":", "raise", "TypeError", "(", "'yaml_encode() only works with YAML scalar data; failed for {0}'", ".", "format", "(", "type", "(", "data", ")", ")", ")", "tag", "=", "ynode", ".", "tag", ".", "rsplit", "(", "':'", ",", "1", ")", "[", "(", "-", "1", ")", "]", "ret", "=", "ynode", ".", "value", "if", "(", "tag", "==", "'str'", ")", ":", "ret", "=", "yaml_dquote", "(", "ynode", ".", "value", ")", "return", "ret" ]
a simple yaml encode that can take a single-element datatype and return a string representation .
train
true
43,312
def ClientIdToHostname(client_id, token=None): client = OpenClient(client_id, token=token)[0] if (client and client.Get('Host')): return client.Get('Host').Summary()
[ "def", "ClientIdToHostname", "(", "client_id", ",", "token", "=", "None", ")", ":", "client", "=", "OpenClient", "(", "client_id", ",", "token", "=", "token", ")", "[", "0", "]", "if", "(", "client", "and", "client", ".", "Get", "(", "'Host'", ")", ")", ":", "return", "client", ".", "Get", "(", "'Host'", ")", ".", "Summary", "(", ")" ]
quick helper for scripts to get a hostname from a client id .
train
false
43,313
def _arg_combine(data, axis, argfunc, keepdims=False): axis = (None if ((len(axis) == data.ndim) or (data.ndim == 1)) else axis[0]) vals = data['vals'] arg = data['arg'] if (axis is None): local_args = argfunc(vals, axis=axis, keepdims=keepdims) vals = vals.ravel()[local_args] arg = arg.ravel()[local_args] else: local_args = argfunc(vals, axis=axis) inds = np.ogrid[tuple(map(slice, local_args.shape))] inds.insert(axis, local_args) vals = vals[inds] arg = arg[inds] if keepdims: vals = np.expand_dims(vals, axis) arg = np.expand_dims(arg, axis) return (arg, vals)
[ "def", "_arg_combine", "(", "data", ",", "axis", ",", "argfunc", ",", "keepdims", "=", "False", ")", ":", "axis", "=", "(", "None", "if", "(", "(", "len", "(", "axis", ")", "==", "data", ".", "ndim", ")", "or", "(", "data", ".", "ndim", "==", "1", ")", ")", "else", "axis", "[", "0", "]", ")", "vals", "=", "data", "[", "'vals'", "]", "arg", "=", "data", "[", "'arg'", "]", "if", "(", "axis", "is", "None", ")", ":", "local_args", "=", "argfunc", "(", "vals", ",", "axis", "=", "axis", ",", "keepdims", "=", "keepdims", ")", "vals", "=", "vals", ".", "ravel", "(", ")", "[", "local_args", "]", "arg", "=", "arg", ".", "ravel", "(", ")", "[", "local_args", "]", "else", ":", "local_args", "=", "argfunc", "(", "vals", ",", "axis", "=", "axis", ")", "inds", "=", "np", ".", "ogrid", "[", "tuple", "(", "map", "(", "slice", ",", "local_args", ".", "shape", ")", ")", "]", "inds", ".", "insert", "(", "axis", ",", "local_args", ")", "vals", "=", "vals", "[", "inds", "]", "arg", "=", "arg", "[", "inds", "]", "if", "keepdims", ":", "vals", "=", "np", ".", "expand_dims", "(", "vals", ",", "axis", ")", "arg", "=", "np", ".", "expand_dims", "(", "arg", ",", "axis", ")", "return", "(", "arg", ",", "vals", ")" ]
merge intermediate results from arg_* functions .
train
false
43,315
def info_installed(*names): ret = dict() for (pkg_name, pkg_nfo) in __salt__['lowpkg.info'](*names).items(): t_nfo = dict() for (key, value) in pkg_nfo.items(): if (key == 'source_rpm'): t_nfo['source'] = value else: t_nfo[key] = value ret[pkg_name] = t_nfo return ret
[ "def", "info_installed", "(", "*", "names", ")", ":", "ret", "=", "dict", "(", ")", "for", "(", "pkg_name", ",", "pkg_nfo", ")", "in", "__salt__", "[", "'lowpkg.info'", "]", "(", "*", "names", ")", ".", "items", "(", ")", ":", "t_nfo", "=", "dict", "(", ")", "for", "(", "key", ",", "value", ")", "in", "pkg_nfo", ".", "items", "(", ")", ":", "if", "(", "key", "==", "'source_rpm'", ")", ":", "t_nfo", "[", "'source'", "]", "=", "value", "else", ":", "t_nfo", "[", "key", "]", "=", "value", "ret", "[", "pkg_name", "]", "=", "t_nfo", "return", "ret" ]
return the information of the named package(s) .
train
false
43,316
def copy_virtual_disk(session, dc_ref, source, dest): LOG.debug('Copying Virtual Disk %(source)s to %(dest)s', {'source': source, 'dest': dest}) vim = session.vim vmdk_copy_task = session._call_method(vim, 'CopyVirtualDisk_Task', vim.service_content.virtualDiskManager, sourceName=source, sourceDatacenter=dc_ref, destName=dest) session._wait_for_task(vmdk_copy_task) LOG.debug('Copied Virtual Disk %(source)s to %(dest)s', {'source': source, 'dest': dest})
[ "def", "copy_virtual_disk", "(", "session", ",", "dc_ref", ",", "source", ",", "dest", ")", ":", "LOG", ".", "debug", "(", "'Copying Virtual Disk %(source)s to %(dest)s'", ",", "{", "'source'", ":", "source", ",", "'dest'", ":", "dest", "}", ")", "vim", "=", "session", ".", "vim", "vmdk_copy_task", "=", "session", ".", "_call_method", "(", "vim", ",", "'CopyVirtualDisk_Task'", ",", "vim", ".", "service_content", ".", "virtualDiskManager", ",", "sourceName", "=", "source", ",", "sourceDatacenter", "=", "dc_ref", ",", "destName", "=", "dest", ")", "session", ".", "_wait_for_task", "(", "vmdk_copy_task", ")", "LOG", ".", "debug", "(", "'Copied Virtual Disk %(source)s to %(dest)s'", ",", "{", "'source'", ":", "source", ",", "'dest'", ":", "dest", "}", ")" ]
copy a sparse virtual disk to a thin virtual disk .
train
false
43,317
def reset_indent(TokenClass): def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = (-1) context.next_indent = 0 context.block_scalar_indent = None (yield (match.start(), TokenClass, text)) context.pos = match.end() return callback
[ "def", "reset_indent", "(", "TokenClass", ")", ":", "def", "callback", "(", "lexer", ",", "match", ",", "context", ")", ":", "text", "=", "match", ".", "group", "(", ")", "context", ".", "indent_stack", "=", "[", "]", "context", ".", "indent", "=", "(", "-", "1", ")", "context", ".", "next_indent", "=", "0", "context", ".", "block_scalar_indent", "=", "None", "(", "yield", "(", "match", ".", "start", "(", ")", ",", "TokenClass", ",", "text", ")", ")", "context", ".", "pos", "=", "match", ".", "end", "(", ")", "return", "callback" ]
reset the indentation levels .
train
true
43,318
def get_request_ip(request): return (request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR') or request.META.get('HTTP_X_REAL_IP'))
[ "def", "get_request_ip", "(", "request", ")", ":", "return", "(", "request", ".", "META", ".", "get", "(", "'HTTP_X_FORWARDED_FOR'", ")", "or", "request", ".", "META", ".", "get", "(", "'REMOTE_ADDR'", ")", "or", "request", ".", "META", ".", "get", "(", "'HTTP_X_REAL_IP'", ")", ")" ]
return the ip address from a http request object .
train
false
43,319
def parse_set_header(value, on_update=None): if (not value): return HeaderSet(None, on_update) return HeaderSet(parse_list_header(value), on_update)
[ "def", "parse_set_header", "(", "value", ",", "on_update", "=", "None", ")", ":", "if", "(", "not", "value", ")", ":", "return", "HeaderSet", "(", "None", ",", "on_update", ")", "return", "HeaderSet", "(", "parse_list_header", "(", "value", ")", ",", "on_update", ")" ]
parse a set-like header and return a :class:~werkzeug .
train
true
43,320
def rm_host(ip, alias): if (not has_pair(ip, alias)): return True hfn = _get_or_create_hostfile() with salt.utils.fopen(hfn) as fp_: lines = fp_.readlines() for ind in range(len(lines)): tmpline = lines[ind].strip() if (not tmpline): continue if tmpline.startswith('#'): continue comps = tmpline.split() if (comps[0] == ip): newline = '{0} DCTB DCTB '.format(comps[0]) for existing in comps[1:]: if (existing == alias): continue newline += ' {0}'.format(existing) if (newline.strip() == ip): lines[ind] = '' else: lines[ind] = (newline + os.linesep) with salt.utils.fopen(hfn, 'w+') as ofile: ofile.writelines(lines) return True
[ "def", "rm_host", "(", "ip", ",", "alias", ")", ":", "if", "(", "not", "has_pair", "(", "ip", ",", "alias", ")", ")", ":", "return", "True", "hfn", "=", "_get_or_create_hostfile", "(", ")", "with", "salt", ".", "utils", ".", "fopen", "(", "hfn", ")", "as", "fp_", ":", "lines", "=", "fp_", ".", "readlines", "(", ")", "for", "ind", "in", "range", "(", "len", "(", "lines", ")", ")", ":", "tmpline", "=", "lines", "[", "ind", "]", ".", "strip", "(", ")", "if", "(", "not", "tmpline", ")", ":", "continue", "if", "tmpline", ".", "startswith", "(", "'#'", ")", ":", "continue", "comps", "=", "tmpline", ".", "split", "(", ")", "if", "(", "comps", "[", "0", "]", "==", "ip", ")", ":", "newline", "=", "'{0} DCTB DCTB '", ".", "format", "(", "comps", "[", "0", "]", ")", "for", "existing", "in", "comps", "[", "1", ":", "]", ":", "if", "(", "existing", "==", "alias", ")", ":", "continue", "newline", "+=", "' {0}'", ".", "format", "(", "existing", ")", "if", "(", "newline", ".", "strip", "(", ")", "==", "ip", ")", ":", "lines", "[", "ind", "]", "=", "''", "else", ":", "lines", "[", "ind", "]", "=", "(", "newline", "+", "os", ".", "linesep", ")", "with", "salt", ".", "utils", ".", "fopen", "(", "hfn", ",", "'w+'", ")", "as", "ofile", ":", "ofile", ".", "writelines", "(", "lines", ")", "return", "True" ]
remove a host entry from the hosts file cli example: .
train
false
43,321
@cronjobs.register def update_l10n_metric(): if settings.STAGE: return top_60_docs = _get_top_docs(60) end = (date.today() - timedelta(days=1)) start = (end - timedelta(days=30)) locale_visits = googleanalytics.visitors_by_locale(start, end) total_visits = sum(locale_visits.itervalues()) coverage = 0 for (locale, visits) in locale_visits.iteritems(): if (locale == settings.WIKI_DEFAULT_LANGUAGE): num_docs = MAX_DOCS_UP_TO_DATE up_to_date_docs = MAX_DOCS_UP_TO_DATE else: (up_to_date_docs, num_docs) = _get_up_to_date_count(top_60_docs, locale) if (num_docs and total_visits): coverage += ((float(up_to_date_docs) / num_docs) * (float(visits) / total_visits)) metric_kind = MetricKind.objects.get(code=L10N_METRIC_CODE) day = date.today() Metric.objects.create(kind=metric_kind, start=day, end=(day + timedelta(days=1)), value=int((coverage * 100)))
[ "@", "cronjobs", ".", "register", "def", "update_l10n_metric", "(", ")", ":", "if", "settings", ".", "STAGE", ":", "return", "top_60_docs", "=", "_get_top_docs", "(", "60", ")", "end", "=", "(", "date", ".", "today", "(", ")", "-", "timedelta", "(", "days", "=", "1", ")", ")", "start", "=", "(", "end", "-", "timedelta", "(", "days", "=", "30", ")", ")", "locale_visits", "=", "googleanalytics", ".", "visitors_by_locale", "(", "start", ",", "end", ")", "total_visits", "=", "sum", "(", "locale_visits", ".", "itervalues", "(", ")", ")", "coverage", "=", "0", "for", "(", "locale", ",", "visits", ")", "in", "locale_visits", ".", "iteritems", "(", ")", ":", "if", "(", "locale", "==", "settings", ".", "WIKI_DEFAULT_LANGUAGE", ")", ":", "num_docs", "=", "MAX_DOCS_UP_TO_DATE", "up_to_date_docs", "=", "MAX_DOCS_UP_TO_DATE", "else", ":", "(", "up_to_date_docs", ",", "num_docs", ")", "=", "_get_up_to_date_count", "(", "top_60_docs", ",", "locale", ")", "if", "(", "num_docs", "and", "total_visits", ")", ":", "coverage", "+=", "(", "(", "float", "(", "up_to_date_docs", ")", "/", "num_docs", ")", "*", "(", "float", "(", "visits", ")", "/", "total_visits", ")", ")", "metric_kind", "=", "MetricKind", ".", "objects", ".", "get", "(", "code", "=", "L10N_METRIC_CODE", ")", "day", "=", "date", ".", "today", "(", ")", "Metric", ".", "objects", ".", "create", "(", "kind", "=", "metric_kind", ",", "start", "=", "day", ",", "end", "=", "(", "day", "+", "timedelta", "(", "days", "=", "1", ")", ")", ",", "value", "=", "int", "(", "(", "coverage", "*", "100", ")", ")", ")" ]
calculate new l10n coverage numbers and save .
train
false
43,322
def create_event(name='TestEvent', creator_email=None, **kwargs): event = Event(name=name, start_time=datetime(2016, 4, 8, 12, 30, 45), end_time=datetime(2016, 4, 9, 12, 30, 45), **kwargs) if creator_email: event.creator = User.query.filter_by(email=creator_email).first() save_to_db(event, 'Event saved') copyright = Copyright(holder='copyright holder', event=event) save_to_db(copyright, 'Copyright saved') if creator_email: data = {'user_email': creator_email, 'user_role': ORGANIZER} DataManager.add_role_to_event(data, event.id, record=False) return event.id
[ "def", "create_event", "(", "name", "=", "'TestEvent'", ",", "creator_email", "=", "None", ",", "**", "kwargs", ")", ":", "event", "=", "Event", "(", "name", "=", "name", ",", "start_time", "=", "datetime", "(", "2016", ",", "4", ",", "8", ",", "12", ",", "30", ",", "45", ")", ",", "end_time", "=", "datetime", "(", "2016", ",", "4", ",", "9", ",", "12", ",", "30", ",", "45", ")", ",", "**", "kwargs", ")", "if", "creator_email", ":", "event", ".", "creator", "=", "User", ".", "query", ".", "filter_by", "(", "email", "=", "creator_email", ")", ".", "first", "(", ")", "save_to_db", "(", "event", ",", "'Event saved'", ")", "copyright", "=", "Copyright", "(", "holder", "=", "'copyright holder'", ",", "event", "=", "event", ")", "save_to_db", "(", "copyright", ",", "'Copyright saved'", ")", "if", "creator_email", ":", "data", "=", "{", "'user_email'", ":", "creator_email", ",", "'user_role'", ":", "ORGANIZER", "}", "DataManager", ".", "add_role_to_event", "(", "data", ",", "event", ".", "id", ",", "record", "=", "False", ")", "return", "event", ".", "id" ]
create an event on the victorops service .
train
false
43,323
def get_human_readable_disk_usage(d): if (platform.system() in ['Linux', 'FreeBSD']): try: return subprocess.Popen(['du', '-sh', d], stdout=subprocess.PIPE).communicate()[0].split()[0] except: raise CleanupException('rosclean is not supported on this platform') else: raise CleanupException('rosclean is not supported on this platform')
[ "def", "get_human_readable_disk_usage", "(", "d", ")", ":", "if", "(", "platform", ".", "system", "(", ")", "in", "[", "'Linux'", ",", "'FreeBSD'", "]", ")", ":", "try", ":", "return", "subprocess", ".", "Popen", "(", "[", "'du'", ",", "'-sh'", ",", "d", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "communicate", "(", ")", "[", "0", "]", ".", "split", "(", ")", "[", "0", "]", "except", ":", "raise", "CleanupException", "(", "'rosclean is not supported on this platform'", ")", "else", ":", "raise", "CleanupException", "(", "'rosclean is not supported on this platform'", ")" ]
get human-readable disk usage for directory .
train
false
43,324
def make_runserver(app_factory, hostname='localhost', port=5000, use_reloader=False, use_debugger=False, use_evalex=True, threaded=False, processes=1, static_files=None, extra_files=None, ssl_context=None): _deprecated() def action(hostname=('h', hostname), port=('p', port), reloader=use_reloader, debugger=use_debugger, evalex=use_evalex, threaded=threaded, processes=processes): 'Start a new development server.' from werkzeug.serving import run_simple app = app_factory() run_simple(hostname, port, app, use_reloader=reloader, use_debugger=debugger, use_evalex=evalex, extra_files=extra_files, reloader_interval=1, threaded=threaded, processes=processes, static_files=static_files, ssl_context=ssl_context) return action
[ "def", "make_runserver", "(", "app_factory", ",", "hostname", "=", "'localhost'", ",", "port", "=", "5000", ",", "use_reloader", "=", "False", ",", "use_debugger", "=", "False", ",", "use_evalex", "=", "True", ",", "threaded", "=", "False", ",", "processes", "=", "1", ",", "static_files", "=", "None", ",", "extra_files", "=", "None", ",", "ssl_context", "=", "None", ")", ":", "_deprecated", "(", ")", "def", "action", "(", "hostname", "=", "(", "'h'", ",", "hostname", ")", ",", "port", "=", "(", "'p'", ",", "port", ")", ",", "reloader", "=", "use_reloader", ",", "debugger", "=", "use_debugger", ",", "evalex", "=", "use_evalex", ",", "threaded", "=", "threaded", ",", "processes", "=", "processes", ")", ":", "from", "werkzeug", ".", "serving", "import", "run_simple", "app", "=", "app_factory", "(", ")", "run_simple", "(", "hostname", ",", "port", ",", "app", ",", "use_reloader", "=", "reloader", ",", "use_debugger", "=", "debugger", ",", "use_evalex", "=", "evalex", ",", "extra_files", "=", "extra_files", ",", "reloader_interval", "=", "1", ",", "threaded", "=", "threaded", ",", "processes", "=", "processes", ",", "static_files", "=", "static_files", ",", "ssl_context", "=", "ssl_context", ")", "return", "action" ]
returns an action callback that spawns a new development server .
train
true
43,326
def init(mpstate): return SerialModule(mpstate)
[ "def", "init", "(", "mpstate", ")", ":", "return", "SerialModule", "(", "mpstate", ")" ]
create a new git repository .
train
false
43,327
def user_deletemedia(mediaids, **connection_args): conn_args = _login(**connection_args) try: if conn_args: method = 'user.deletemedia' if (not isinstance(mediaids, list)): mediaids = [mediaids] params = mediaids ret = _query(method, params, conn_args['url'], conn_args['auth']) return ret['result']['mediaids'] else: raise KeyError except KeyError: return ret
[ "def", "user_deletemedia", "(", "mediaids", ",", "**", "connection_args", ")", ":", "conn_args", "=", "_login", "(", "**", "connection_args", ")", "try", ":", "if", "conn_args", ":", "method", "=", "'user.deletemedia'", "if", "(", "not", "isinstance", "(", "mediaids", ",", "list", ")", ")", ":", "mediaids", "=", "[", "mediaids", "]", "params", "=", "mediaids", "ret", "=", "_query", "(", "method", ",", "params", ",", "conn_args", "[", "'url'", "]", ",", "conn_args", "[", "'auth'", "]", ")", "return", "ret", "[", "'result'", "]", "[", "'mediaids'", "]", "else", ":", "raise", "KeyError", "except", "KeyError", ":", "return", "ret" ]
delete media by id .
train
true
43,328
def _format_return_data(retcode, stdout=None, stderr=None): ret = {'retcode': retcode} if (stdout is not None): ret['stdout'] = stdout if (stderr is not None): ret['stderr'] = stderr return ret
[ "def", "_format_return_data", "(", "retcode", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ")", ":", "ret", "=", "{", "'retcode'", ":", "retcode", "}", "if", "(", "stdout", "is", "not", "None", ")", ":", "ret", "[", "'stdout'", "]", "=", "stdout", "if", "(", "stderr", "is", "not", "None", ")", ":", "ret", "[", "'stderr'", "]", "=", "stderr", "return", "ret" ]
creates a dictionary from the parameters .
train
true
43,329
def MakeDestinationKey(directory, filename): return utils.SmartStr(utils.JoinPath(directory, filename)).lstrip('/')
[ "def", "MakeDestinationKey", "(", "directory", ",", "filename", ")", ":", "return", "utils", ".", "SmartStr", "(", "utils", ".", "JoinPath", "(", "directory", ",", "filename", ")", ")", ".", "lstrip", "(", "'/'", ")" ]
creates a name that identifies a database file .
train
true
43,330
def _servicegroup_get_servers(sg_name, **connection_args): nitro = _connect(**connection_args) if (nitro is None): return None sg = NSServiceGroup() sg.set_servicegroupname(sg_name) try: sg = NSServiceGroup.get_servers(nitro, sg) except NSNitroError as error: log.debug('netscaler module error - NSServiceGroup.get_servers failed(): {0}'.format(error)) sg = None _disconnect(nitro) return sg
[ "def", "_servicegroup_get_servers", "(", "sg_name", ",", "**", "connection_args", ")", ":", "nitro", "=", "_connect", "(", "**", "connection_args", ")", "if", "(", "nitro", "is", "None", ")", ":", "return", "None", "sg", "=", "NSServiceGroup", "(", ")", "sg", ".", "set_servicegroupname", "(", "sg_name", ")", "try", ":", "sg", "=", "NSServiceGroup", ".", "get_servers", "(", "nitro", ",", "sg", ")", "except", "NSNitroError", "as", "error", ":", "log", ".", "debug", "(", "'netscaler module error - NSServiceGroup.get_servers failed(): {0}'", ".", "format", "(", "error", ")", ")", "sg", "=", "None", "_disconnect", "(", "nitro", ")", "return", "sg" ]
returns a list of members of a servicegroup or none .
train
true
43,331
def solow_steady_state(g, n, s, alpha, delta): k_star = ((s / ((n + g) + delta)) ** (1 / (1 - alpha))) return k_star
[ "def", "solow_steady_state", "(", "g", ",", "n", ",", "s", ",", "alpha", ",", "delta", ")", ":", "k_star", "=", "(", "(", "s", "/", "(", "(", "n", "+", "g", ")", "+", "delta", ")", ")", "**", "(", "1", "/", "(", "1", "-", "alpha", ")", ")", ")", "return", "k_star" ]
steady-state level of capital stock .
train
false
43,332
def memoized(maxsize=1024): cache = SimpleCache(maxsize=maxsize) def decorator(obj): @wraps(obj) def new_callable(*a, **kw): def create_new(): return obj(*a, **kw) key = (a, tuple(kw.items())) return cache.get(key, create_new) return new_callable return decorator
[ "def", "memoized", "(", "maxsize", "=", "1024", ")", ":", "cache", "=", "SimpleCache", "(", "maxsize", "=", "maxsize", ")", "def", "decorator", "(", "obj", ")", ":", "@", "wraps", "(", "obj", ")", "def", "new_callable", "(", "*", "a", ",", "**", "kw", ")", ":", "def", "create_new", "(", ")", ":", "return", "obj", "(", "*", "a", ",", "**", "kw", ")", "key", "=", "(", "a", ",", "tuple", "(", "kw", ".", "items", "(", ")", ")", ")", "return", "cache", ".", "get", "(", "key", ",", "create_new", ")", "return", "new_callable", "return", "decorator" ]
decorator that caches function calls .
train
true
43,334
def wasLastResponseDelayed(): deviation = stdev(kb.responseTimes.get(kb.responseTimeMode, [])) threadData = getCurrentThreadData() if (deviation and (not conf.direct)): if (len(kb.responseTimes[kb.responseTimeMode]) < MIN_TIME_RESPONSES): warnMsg = 'time-based standard deviation method used on a model ' warnMsg += ('with less than %d response times' % MIN_TIME_RESPONSES) logger.warn(warnMsg) lowerStdLimit = (average(kb.responseTimes[kb.responseTimeMode]) + (TIME_STDEV_COEFF * deviation)) retVal = (threadData.lastQueryDuration >= max(MIN_VALID_DELAYED_RESPONSE, lowerStdLimit)) if ((not kb.testMode) and retVal): if (kb.adjustTimeDelay is None): msg = 'do you want sqlmap to try to optimize value(s) ' msg += "for DBMS delay responses (option '--time-sec')? [Y/n] " choice = readInput(msg, default='Y') kb.adjustTimeDelay = (ADJUST_TIME_DELAY.DISABLE if (choice.upper() == 'N') else ADJUST_TIME_DELAY.YES) if (kb.adjustTimeDelay is ADJUST_TIME_DELAY.YES): adjustTimeDelay(threadData.lastQueryDuration, lowerStdLimit) return retVal else: return ((threadData.lastQueryDuration - conf.timeSec) >= 0)
[ "def", "wasLastResponseDelayed", "(", ")", ":", "deviation", "=", "stdev", "(", "kb", ".", "responseTimes", ".", "get", "(", "kb", ".", "responseTimeMode", ",", "[", "]", ")", ")", "threadData", "=", "getCurrentThreadData", "(", ")", "if", "(", "deviation", "and", "(", "not", "conf", ".", "direct", ")", ")", ":", "if", "(", "len", "(", "kb", ".", "responseTimes", "[", "kb", ".", "responseTimeMode", "]", ")", "<", "MIN_TIME_RESPONSES", ")", ":", "warnMsg", "=", "'time-based standard deviation method used on a model '", "warnMsg", "+=", "(", "'with less than %d response times'", "%", "MIN_TIME_RESPONSES", ")", "logger", ".", "warn", "(", "warnMsg", ")", "lowerStdLimit", "=", "(", "average", "(", "kb", ".", "responseTimes", "[", "kb", ".", "responseTimeMode", "]", ")", "+", "(", "TIME_STDEV_COEFF", "*", "deviation", ")", ")", "retVal", "=", "(", "threadData", ".", "lastQueryDuration", ">=", "max", "(", "MIN_VALID_DELAYED_RESPONSE", ",", "lowerStdLimit", ")", ")", "if", "(", "(", "not", "kb", ".", "testMode", ")", "and", "retVal", ")", ":", "if", "(", "kb", ".", "adjustTimeDelay", "is", "None", ")", ":", "msg", "=", "'do you want sqlmap to try to optimize value(s) '", "msg", "+=", "\"for DBMS delay responses (option '--time-sec')? [Y/n] \"", "choice", "=", "readInput", "(", "msg", ",", "default", "=", "'Y'", ")", "kb", ".", "adjustTimeDelay", "=", "(", "ADJUST_TIME_DELAY", ".", "DISABLE", "if", "(", "choice", ".", "upper", "(", ")", "==", "'N'", ")", "else", "ADJUST_TIME_DELAY", ".", "YES", ")", "if", "(", "kb", ".", "adjustTimeDelay", "is", "ADJUST_TIME_DELAY", ".", "YES", ")", ":", "adjustTimeDelay", "(", "threadData", ".", "lastQueryDuration", ",", "lowerStdLimit", ")", "return", "retVal", "else", ":", "return", "(", "(", "threadData", ".", "lastQueryDuration", "-", "conf", ".", "timeSec", ")", ">=", "0", ")" ]
returns true if the last web request resulted in a time-delay .
train
false
43,335
def im_feeling_lucky_async(image_data, output_encoding=PNG, quality=None, correct_orientation=UNCHANGED_ORIENTATION, rpc=None, transparent_substitution_rgb=None): image = Image(image_data) image.im_feeling_lucky() image.set_correct_orientation(correct_orientation) return image.execute_transforms_async(output_encoding=output_encoding, quality=quality, rpc=rpc, transparent_substitution_rgb=transparent_substitution_rgb)
[ "def", "im_feeling_lucky_async", "(", "image_data", ",", "output_encoding", "=", "PNG", ",", "quality", "=", "None", ",", "correct_orientation", "=", "UNCHANGED_ORIENTATION", ",", "rpc", "=", "None", ",", "transparent_substitution_rgb", "=", "None", ")", ":", "image", "=", "Image", "(", "image_data", ")", "image", ".", "im_feeling_lucky", "(", ")", "image", ".", "set_correct_orientation", "(", "correct_orientation", ")", "return", "image", ".", "execute_transforms_async", "(", "output_encoding", "=", "output_encoding", ",", "quality", "=", "quality", ",", "rpc", "=", "rpc", ",", "transparent_substitution_rgb", "=", "transparent_substitution_rgb", ")" ]
automatically adjust image levels - async version .
train
false
43,336
def enough_disk_space(service): available_space = get_available_disk_space() logging.debug('Available space: {0}'.format(available_space)) backup_size = get_backup_size(service) logging.debug('Backup size: {0}'.format(backup_size)) if (backup_size > (available_space * PADDING_PERCENTAGE)): logging.warning('Not enough space for a backup.') return False return True
[ "def", "enough_disk_space", "(", "service", ")", ":", "available_space", "=", "get_available_disk_space", "(", ")", "logging", ".", "debug", "(", "'Available space: {0}'", ".", "format", "(", "available_space", ")", ")", "backup_size", "=", "get_backup_size", "(", "service", ")", "logging", ".", "debug", "(", "'Backup size: {0}'", ".", "format", "(", "backup_size", ")", ")", "if", "(", "backup_size", ">", "(", "available_space", "*", "PADDING_PERCENTAGE", ")", ")", ":", "logging", ".", "warning", "(", "'Not enough space for a backup.'", ")", "return", "False", "return", "True" ]
checks if theres enough available disk space for a new backup .
train
false
43,340
def is_proj_plane_distorted(wcs, maxerr=1e-05): cwcs = wcs.celestial return ((not _is_cd_orthogonal(cwcs.pixel_scale_matrix, maxerr)) or _has_distortion(cwcs))
[ "def", "is_proj_plane_distorted", "(", "wcs", ",", "maxerr", "=", "1e-05", ")", ":", "cwcs", "=", "wcs", ".", "celestial", "return", "(", "(", "not", "_is_cd_orthogonal", "(", "cwcs", ".", "pixel_scale_matrix", ",", "maxerr", ")", ")", "or", "_has_distortion", "(", "cwcs", ")", ")" ]
for a wcs returns false if square image pixels stay square when projected onto the "plane of intermediate world coordinates" as defined in greisen & calabretta 2002 .
train
false
43,343
@check_dataset_access_permission @check_dataset_edition_permission() def edit_coordinator_dataset(request, dataset): response = {'status': (-1), 'data': 'None'} if (request.method == 'POST'): dataset_form = DatasetForm(request.POST, instance=dataset, prefix='edit') if dataset_form.is_valid(): dataset = dataset_form.save() response['status'] = 0 response['data'] = (reverse('oozie:edit_coordinator', kwargs={'coordinator': dataset.coordinator.id}) + '#listDataset') request.info(_('Dataset modified')) if (dataset.start > dataset.coordinator.start): request.warn(_('Beware: dataset start date was after the coordinator start date.')) else: response['data'] = dataset_form.errors else: dataset_form = DatasetForm(instance=dataset, prefix='edit') if (response['status'] != 0): response['data'] = render('editor/edit_coordinator_dataset.mako', request, {'coordinator': dataset.coordinator, 'dataset_form': dataset_form, 'dataset': dataset, 'path': request.path}, force_template=True).content return JsonResponse(response, safe=False)
[ "@", "check_dataset_access_permission", "@", "check_dataset_edition_permission", "(", ")", "def", "edit_coordinator_dataset", "(", "request", ",", "dataset", ")", ":", "response", "=", "{", "'status'", ":", "(", "-", "1", ")", ",", "'data'", ":", "'None'", "}", "if", "(", "request", ".", "method", "==", "'POST'", ")", ":", "dataset_form", "=", "DatasetForm", "(", "request", ".", "POST", ",", "instance", "=", "dataset", ",", "prefix", "=", "'edit'", ")", "if", "dataset_form", ".", "is_valid", "(", ")", ":", "dataset", "=", "dataset_form", ".", "save", "(", ")", "response", "[", "'status'", "]", "=", "0", "response", "[", "'data'", "]", "=", "(", "reverse", "(", "'oozie:edit_coordinator'", ",", "kwargs", "=", "{", "'coordinator'", ":", "dataset", ".", "coordinator", ".", "id", "}", ")", "+", "'#listDataset'", ")", "request", ".", "info", "(", "_", "(", "'Dataset modified'", ")", ")", "if", "(", "dataset", ".", "start", ">", "dataset", ".", "coordinator", ".", "start", ")", ":", "request", ".", "warn", "(", "_", "(", "'Beware: dataset start date was after the coordinator start date.'", ")", ")", "else", ":", "response", "[", "'data'", "]", "=", "dataset_form", ".", "errors", "else", ":", "dataset_form", "=", "DatasetForm", "(", "instance", "=", "dataset", ",", "prefix", "=", "'edit'", ")", "if", "(", "response", "[", "'status'", "]", "!=", "0", ")", ":", "response", "[", "'data'", "]", "=", "render", "(", "'editor/edit_coordinator_dataset.mako'", ",", "request", ",", "{", "'coordinator'", ":", "dataset", ".", "coordinator", ",", "'dataset_form'", ":", "dataset_form", ",", "'dataset'", ":", "dataset", ",", "'path'", ":", "request", ".", "path", "}", ",", "force_template", "=", "True", ")", ".", "content", "return", "JsonResponse", "(", "response", ",", "safe", "=", "False", ")" ]
returns html for modal to edit datasets .
train
false
43,346
def texinfo_visit_inheritance_diagram(self, node): graph = node['graph'] graph_hash = get_graph_hash(node) name = ('inheritance%s' % graph_hash) dotcode = graph.generate_dot(name, env=self.builder.env, graph_attrs={'size': '"6.0,6.0"'}) render_dot_texinfo(self, node, dotcode, {}, 'inheritance') raise nodes.SkipNode
[ "def", "texinfo_visit_inheritance_diagram", "(", "self", ",", "node", ")", ":", "graph", "=", "node", "[", "'graph'", "]", "graph_hash", "=", "get_graph_hash", "(", "node", ")", "name", "=", "(", "'inheritance%s'", "%", "graph_hash", ")", "dotcode", "=", "graph", ".", "generate_dot", "(", "name", ",", "env", "=", "self", ".", "builder", ".", "env", ",", "graph_attrs", "=", "{", "'size'", ":", "'\"6.0,6.0\"'", "}", ")", "render_dot_texinfo", "(", "self", ",", "node", ",", "dotcode", ",", "{", "}", ",", "'inheritance'", ")", "raise", "nodes", ".", "SkipNode" ]
output the graph for texinfo .
train
true
43,347
def modifiers_dict(modifiers): return {mod[4:].lower(): ((modifiers & getattr(sys.modules[__name__], mod)) > 0) for mod in ['MOD_SHIFT', 'MOD_CTRL', 'MOD_ALT', 'MOD_CAPSLOCK', 'MOD_NUMLOCK', 'MOD_WINDOWS', 'MOD_COMMAND', 'MOD_OPTION', 'MOD_SCROLLLOCK']}
[ "def", "modifiers_dict", "(", "modifiers", ")", ":", "return", "{", "mod", "[", "4", ":", "]", ".", "lower", "(", ")", ":", "(", "(", "modifiers", "&", "getattr", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "mod", ")", ")", ">", "0", ")", "for", "mod", "in", "[", "'MOD_SHIFT'", ",", "'MOD_CTRL'", ",", "'MOD_ALT'", ",", "'MOD_CAPSLOCK'", ",", "'MOD_NUMLOCK'", ",", "'MOD_WINDOWS'", ",", "'MOD_COMMAND'", ",", "'MOD_OPTION'", ",", "'MOD_SCROLLLOCK'", "]", "}" ]
return dict where the key is a keyboard modifier flag and the value is the boolean state of that flag .
train
false
43,348
def RegisterRealUrlHandler(func): _realurl_handlers.append(func)
[ "def", "RegisterRealUrlHandler", "(", "func", ")", ":", "_realurl_handlers", ".", "append", "(", "func", ")" ]
handle函数接受一个参数url,返回真实下载地址字符串, 如果需要返回真实文件名,可以返回一个tuple 如果返回空则调用下个handle函数, .
train
false
43,349
def _replace(reps): if (not reps): return (lambda x: x) D = (lambda match: reps[match.group(0)]) pattern = _re.compile('|'.join([_re.escape(k) for (k, v) in reps.items()]), _re.M) return (lambda string: pattern.sub(D, string))
[ "def", "_replace", "(", "reps", ")", ":", "if", "(", "not", "reps", ")", ":", "return", "(", "lambda", "x", ":", "x", ")", "D", "=", "(", "lambda", "match", ":", "reps", "[", "match", ".", "group", "(", "0", ")", "]", ")", "pattern", "=", "_re", ".", "compile", "(", "'|'", ".", "join", "(", "[", "_re", ".", "escape", "(", "k", ")", "for", "(", "k", ",", "v", ")", "in", "reps", ".", "items", "(", ")", "]", ")", ",", "_re", ".", "M", ")", "return", "(", "lambda", "string", ":", "pattern", ".", "sub", "(", "D", ",", "string", ")", ")" ]
return a function that can make the replacements .
train
false
43,350
def _url(path=''): return (HTTP_BASE_URL + path)
[ "def", "_url", "(", "path", "=", "''", ")", ":", "return", "(", "HTTP_BASE_URL", "+", "path", ")" ]
helper method to generate urls .
train
false
43,351
def unquote_plus(string, encoding='utf-8', errors='replace'): string = string.replace('+', ' ') return unquote(string, encoding, errors)
[ "def", "unquote_plus", "(", "string", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'replace'", ")", ":", "string", "=", "string", ".", "replace", "(", "'+'", ",", "' '", ")", "return", "unquote", "(", "string", ",", "encoding", ",", "errors", ")" ]
like unquote() .
train
true
43,352
def setup_test_episode_file(): if (not os.path.exists(FILE_DIR)): os.makedirs(FILE_DIR) try: with open(FILE_PATH, 'wb') as ep_file: ep_file.write('foo bar') ep_file.flush() except Exception: print 'Unable to set up test episode' raise
[ "def", "setup_test_episode_file", "(", ")", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "FILE_DIR", ")", ")", ":", "os", ".", "makedirs", "(", "FILE_DIR", ")", "try", ":", "with", "open", "(", "FILE_PATH", ",", "'wb'", ")", "as", "ep_file", ":", "ep_file", ".", "write", "(", "'foo bar'", ")", "ep_file", ".", "flush", "(", ")", "except", "Exception", ":", "print", "'Unable to set up test episode'", "raise" ]
create a test episode directory with a test episode in it .
train
false