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
16,300
def descriptor_global_local_resource_url(block, uri): raise NotImplementedError('Applications must monkey-patch this function before using local_resource_url for studio_view')
[ "def", "descriptor_global_local_resource_url", "(", "block", ",", "uri", ")", ":", "raise", "NotImplementedError", "(", "'Applications must monkey-patch this function before using local_resource_url for studio_view'", ")" ]
see :meth:xblock .
train
false
16,301
def block_device_mapping_get_all_by_volume_id(context, volume_id, columns_to_join=None): return IMPL.block_device_mapping_get_all_by_volume_id(context, volume_id, columns_to_join)
[ "def", "block_device_mapping_get_all_by_volume_id", "(", "context", ",", "volume_id", ",", "columns_to_join", "=", "None", ")", ":", "return", "IMPL", ".", "block_device_mapping_get_all_by_volume_id", "(", "context", ",", "volume_id", ",", "columns_to_join", ")" ]
get block device mapping for a given volume .
train
false
16,302
def has_exec(cmd): return (which(cmd) is not None)
[ "def", "has_exec", "(", "cmd", ")", ":", "return", "(", "which", "(", "cmd", ")", "is", "not", "None", ")" ]
returns true if the executable is available on the minion .
train
false
16,303
def get_meta_entry(dist, name): meta = get_dist_meta(dist) return meta.get(name)
[ "def", "get_meta_entry", "(", "dist", ",", "name", ")", ":", "meta", "=", "get_dist_meta", "(", "dist", ")", "return", "meta", ".", "get", "(", "name", ")" ]
get the contents of the named entry from the distributions pkg-info file .
train
false
16,305
@utils.positional(1) def transaction_async(callback, **ctx_options): from . import tasklets return tasklets.get_context().transaction(callback, **ctx_options)
[ "@", "utils", ".", "positional", "(", "1", ")", "def", "transaction_async", "(", "callback", ",", "**", "ctx_options", ")", ":", "from", ".", "import", "tasklets", "return", "tasklets", ".", "get_context", "(", ")", ".", "transaction", "(", "callback", ","...
run a callback in a transaction .
train
false
16,306
def htmldiff_tokens(html1_tokens, html2_tokens): s = InsensitiveSequenceMatcher(a=html1_tokens, b=html2_tokens) commands = s.get_opcodes() result = [] for (command, i1, i2, j1, j2) in commands: if (command == 'equal'): result.extend(expand_tokens(html2_tokens[j1:j2], equal=True)) continue if ((command == 'insert') or (command == 'replace')): ins_tokens = expand_tokens(html2_tokens[j1:j2]) merge_insert(ins_tokens, result) if ((command == 'delete') or (command == 'replace')): del_tokens = expand_tokens(html1_tokens[i1:i2]) merge_delete(del_tokens, result) result = cleanup_delete(result) return result
[ "def", "htmldiff_tokens", "(", "html1_tokens", ",", "html2_tokens", ")", ":", "s", "=", "InsensitiveSequenceMatcher", "(", "a", "=", "html1_tokens", ",", "b", "=", "html2_tokens", ")", "commands", "=", "s", ".", "get_opcodes", "(", ")", "result", "=", "[", ...
does a diff on the tokens themselves .
train
true
16,307
def __get_size(conn, vm_): size = config.get_cloud_config_value('size', vm_, __opts__, default='n1-standard-1', search_global=False) return conn.ex_get_size(size, __get_location(conn, vm_))
[ "def", "__get_size", "(", "conn", ",", "vm_", ")", ":", "size", "=", "config", ".", "get_cloud_config_value", "(", "'size'", ",", "vm_", ",", "__opts__", ",", "default", "=", "'n1-standard-1'", ",", "search_global", "=", "False", ")", "return", "conn", "."...
need to override libcloud to find the machine type in the proper zone .
train
true
16,308
def _get_admin_info(command, host=None, core_name=None): url = _format_url('admin/{0}'.format(command), host, core_name=core_name) resp = _http_request(url) return resp
[ "def", "_get_admin_info", "(", "command", ",", "host", "=", "None", ",", "core_name", "=", "None", ")", ":", "url", "=", "_format_url", "(", "'admin/{0}'", ".", "format", "(", "command", ")", ",", "host", ",", "core_name", "=", "core_name", ")", "resp", ...
private method calls the _http_request method and passes the admin command to execute and stores the data .
train
true
16,309
def Deserializer(stream_or_string, **options): if isinstance(stream_or_string, basestring): stream = StringIO(stream_or_string) else: stream = stream_or_string for obj in PythonDeserializer(yaml.load(stream), **options): (yield obj)
[ "def", "Deserializer", "(", "stream_or_string", ",", "**", "options", ")", ":", "if", "isinstance", "(", "stream_or_string", ",", "basestring", ")", ":", "stream", "=", "StringIO", "(", "stream_or_string", ")", "else", ":", "stream", "=", "stream_or_string", "...
deserialize a stream or string of yaml data .
train
false
16,310
def generateCookieSecret(): return base64.b64encode((uuid.uuid4().bytes + uuid.uuid4().bytes))
[ "def", "generateCookieSecret", "(", ")", ":", "return", "base64", ".", "b64encode", "(", "(", "uuid", ".", "uuid4", "(", ")", ".", "bytes", "+", "uuid", ".", "uuid4", "(", ")", ".", "bytes", ")", ")" ]
generate a new cookie secret .
train
false
16,311
def check_state_result(running, recurse=False): if (not isinstance(running, dict)): return False if (not running): return False ret = True for state_result in six.itervalues(running): if ((not recurse) and (not isinstance(state_result, dict))): ret = False if (ret and isinstance(state_result, dict)): result = state_result.get('result', _empty) if (result is False): ret = False elif ((result is _empty) and isinstance(state_result, dict) and ret): ret = check_state_result(state_result, recurse=True) if (not ret): break return ret
[ "def", "check_state_result", "(", "running", ",", "recurse", "=", "False", ")", ":", "if", "(", "not", "isinstance", "(", "running", ",", "dict", ")", ")", ":", "return", "False", "if", "(", "not", "running", ")", ":", "return", "False", "ret", "=", ...
check the total return value of the run and determine if the running dict has any issues .
train
false
16,312
def _set_msg_reply(msg_reply): def _set_cls_msg_reply(cls): cls.cls_msg_reply = msg_reply return cls return _set_cls_msg_reply
[ "def", "_set_msg_reply", "(", "msg_reply", ")", ":", "def", "_set_cls_msg_reply", "(", "cls", ")", ":", "cls", ".", "cls_msg_reply", "=", "msg_reply", "return", "cls", "return", "_set_cls_msg_reply" ]
annotate ofp reply message class .
train
false
16,313
def osf_storage_root(addon_config, node_settings, auth, **kwargs): node = node_settings.owner root = rubeus.build_addon_root(node_settings=node_settings, name=u'', permissions=auth, user=auth.user, nodeUrl=node.url, nodeApiUrl=node.api_url) return [root]
[ "def", "osf_storage_root", "(", "addon_config", ",", "node_settings", ",", "auth", ",", "**", "kwargs", ")", ":", "node", "=", "node_settings", ".", "owner", "root", "=", "rubeus", ".", "build_addon_root", "(", "node_settings", "=", "node_settings", ",", "name...
build hgrid json for root node .
train
false
16,314
def p_item_string_expr(p): p[0] = (p[1][1:(-1)], p[2])
[ "def", "p_item_string_expr", "(", "p", ")", ":", "p", "[", "0", "]", "=", "(", "p", "[", "1", "]", "[", "1", ":", "(", "-", "1", ")", "]", ",", "p", "[", "2", "]", ")" ]
pitem : string expr .
train
false
16,316
def random_variables(): return tf.get_collection(RANDOM_VARIABLE_COLLECTION)
[ "def", "random_variables", "(", ")", ":", "return", "tf", ".", "get_collection", "(", "RANDOM_VARIABLE_COLLECTION", ")" ]
return all random variables in the tensorflow graph .
train
false
16,317
def OSVersion(flavor): urlbase = path.basename(isoURLs.get(flavor, 'unknown')) return path.splitext(urlbase)[0]
[ "def", "OSVersion", "(", "flavor", ")", ":", "urlbase", "=", "path", ".", "basename", "(", "isoURLs", ".", "get", "(", "flavor", ",", "'unknown'", ")", ")", "return", "path", ".", "splitext", "(", "urlbase", ")", "[", "0", "]" ]
return full os version string for build flavor .
train
false
16,319
def IndexXmlForQuery(kind, ancestor, props): serialized_xml = [] serialized_xml.append((' <datastore-index kind="%s" ancestor="%s">' % (kind, ('true' if ancestor else 'false')))) for (name, direction) in props: serialized_xml.append((' <property name="%s" direction="%s" />' % (name, ('asc' if (direction == ASCENDING) else 'desc')))) serialized_xml.append(' </datastore-index>') return '\n'.join(serialized_xml)
[ "def", "IndexXmlForQuery", "(", "kind", ",", "ancestor", ",", "props", ")", ":", "serialized_xml", "=", "[", "]", "serialized_xml", ".", "append", "(", "(", "' <datastore-index kind=\"%s\" ancestor=\"%s\">'", "%", "(", "kind", ",", "(", "'true'", "if", "ancesto...
return the composite index definition xml needed for a query .
train
false
16,320
def xframe_allow_whitelisted(view_func): def wrapped_view(request, *args, **kwargs): ' Modify the response with the correct X-Frame-Options. ' resp = view_func(request, *args, **kwargs) x_frame_option = 'DENY' if settings.FEATURES['ENABLE_THIRD_PARTY_AUTH']: referer = request.META.get('HTTP_REFERER') if (referer is not None): parsed_url = urlparse(referer) hostname = parsed_url.hostname if LTIProviderConfig.objects.current_set().filter(lti_hostname=hostname, enabled=True).exists(): x_frame_option = 'ALLOW' resp['X-Frame-Options'] = x_frame_option return resp return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
[ "def", "xframe_allow_whitelisted", "(", "view_func", ")", ":", "def", "wrapped_view", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "resp", "=", "view_func", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", "x_frame_option", ...
modifies a view function so that its response has the x-frame-options http header set to deny if the request http referrer is not from a whitelisted hostname .
train
false
16,322
def test_no_data_with_no_values_with_include_x_axis(Chart): chart = Chart(include_x_axis=True) q = chart.render_pyquery() assert (q('.text-overlay text').text() == 'No data')
[ "def", "test_no_data_with_no_values_with_include_x_axis", "(", "Chart", ")", ":", "chart", "=", "Chart", "(", "include_x_axis", "=", "True", ")", "q", "=", "chart", ".", "render_pyquery", "(", ")", "assert", "(", "q", "(", "'.text-overlay text'", ")", ".", "te...
test no data and include_x_axis .
train
false
16,323
@register_stabilize @register_canonicalize @local_optimizer([Solve]) def tag_solve_triangular(node): if (node.op == solve): if (node.op.A_structure == 'general'): (A, b) = node.inputs if (A.owner and isinstance(A.owner.op, type(cholesky))): if A.owner.op.lower: return [Solve('lower_triangular')(A, b)] else: return [Solve('upper_triangular')(A, b)] if (A.owner and isinstance(A.owner.op, DimShuffle) and (A.owner.op.new_order == (1, 0))): (A_T,) = A.owner.inputs if (A_T.owner and isinstance(A_T.owner.op, type(cholesky))): if A_T.owner.op.lower: return [Solve('upper_triangular')(A, b)] else: return [Solve('lower_triangular')(A, b)]
[ "@", "register_stabilize", "@", "register_canonicalize", "@", "local_optimizer", "(", "[", "Solve", "]", ")", "def", "tag_solve_triangular", "(", "node", ")", ":", "if", "(", "node", ".", "op", "==", "solve", ")", ":", "if", "(", "node", ".", "op", ".", ...
if a general solve() is applied to the output of a cholesky op .
train
false
16,324
def evaluation_data(): return s3_rest_controller()
[ "def", "evaluation_data", "(", ")", ":", "return", "s3_rest_controller", "(", ")" ]
restful crud controller .
train
false
16,326
def vserver_servicegroup_delete(v_name, sg_name, **connection_args): ret = True if (not vserver_servicegroup_exists(v_name, sg_name, **connection_args)): return False nitro = _connect(**connection_args) if (nitro is None): return False vsg = NSLBVServerServiceGroupBinding() vsg.set_name(v_name) vsg.set_servicegroupname(sg_name) try: NSLBVServerServiceGroupBinding.delete(nitro, vsg) except NSNitroError as error: log.debug('netscaler module error - NSLBVServerServiceGroupBinding.delete() failed: {0}'.format(error)) ret = False _disconnect(nitro) return ret
[ "def", "vserver_servicegroup_delete", "(", "v_name", ",", "sg_name", ",", "**", "connection_args", ")", ":", "ret", "=", "True", "if", "(", "not", "vserver_servicegroup_exists", "(", "v_name", ",", "sg_name", ",", "**", "connection_args", ")", ")", ":", "retur...
unbind a servicegroup from a vserver cli example: .
train
true
16,328
def matchFirst(string, *args): for patternlist in args: for pattern in patternlist: r = pattern.search(string) if (r is not None): name = r.group(1) return name return string
[ "def", "matchFirst", "(", "string", ",", "*", "args", ")", ":", "for", "patternlist", "in", "args", ":", "for", "pattern", "in", "patternlist", ":", "r", "=", "pattern", ".", "search", "(", "string", ")", "if", "(", "r", "is", "not", "None", ")", "...
matches against list of regexp and returns first match .
train
false
16,329
def write_bem_surfaces(fname, surfs): if isinstance(surfs, dict): surfs = [surfs] with start_file(fname) as fid: start_block(fid, FIFF.FIFFB_BEM) write_int(fid, FIFF.FIFF_BEM_COORD_FRAME, surfs[0]['coord_frame']) _write_bem_surfaces_block(fid, surfs) end_block(fid, FIFF.FIFFB_BEM) end_file(fid)
[ "def", "write_bem_surfaces", "(", "fname", ",", "surfs", ")", ":", "if", "isinstance", "(", "surfs", ",", "dict", ")", ":", "surfs", "=", "[", "surfs", "]", "with", "start_file", "(", "fname", ")", "as", "fid", ":", "start_block", "(", "fid", ",", "F...
write bem surfaces to a fiff file .
train
false
16,330
def disconnected_grad(x): return disconnected_grad_(x)
[ "def", "disconnected_grad", "(", "x", ")", ":", "return", "disconnected_grad_", "(", "x", ")" ]
consider an expression constant when computing gradients .
train
false
16,332
def makedirs_(path, user=None, group=None, mode=None): path = os.path.expanduser(path) dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): msg = "Directory '{0}' already exists".format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = "The path '{0}' already exists and is not a directory".format(dirname) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if (current_dirname == dirname): raise SaltInvocationError("Recursive creation for path '{0}' would result in an infinite loop. Please use an absolute path.".format(dirname)) directories_to_create.reverse() for directory_to_create in directories_to_create: log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode)
[ "def", "makedirs_", "(", "path", ",", "user", "=", "None", ",", "group", "=", "None", ",", "mode", "=", "None", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "dirname", "=", "os", ".", "path", ".", "normpath", "("...
ensure that the directory containing this path is available .
train
true
16,333
def missing_node_cache(prov_dir, node_list, provider, opts): cached_nodes = [] for node in os.listdir(prov_dir): cached_nodes.append(os.path.splitext(node)[0]) for node in cached_nodes: if (node not in node_list): delete_minion_cachedir(node, provider, opts) if (('diff_cache_events' in opts) and opts['diff_cache_events']): fire_event('event', 'cached node missing from provider', 'salt/cloud/{0}/cache_node_missing'.format(node), args={'missing node': node}, sock_dir=opts.get('sock_dir', os.path.join(__opts__['sock_dir'], 'master')), transport=opts.get('transport', 'zeromq'))
[ "def", "missing_node_cache", "(", "prov_dir", ",", "node_list", ",", "provider", ",", "opts", ")", ":", "cached_nodes", "=", "[", "]", "for", "node", "in", "os", ".", "listdir", "(", "prov_dir", ")", ":", "cached_nodes", ".", "append", "(", "os", ".", ...
check list of nodes to see if any nodes which were previously known about in the cache have been removed from the node list .
train
true
16,335
def checked(response): status_code = int(response['status'][:3]) if (status_code == 401): raise Unauthorized if (status_code == 406): raise NoSession if (status_code == 407): raise DownloadLimitReached if (status_code == 413): raise InvalidImdbid if (status_code == 414): raise UnknownUserAgent if (status_code == 415): raise DisabledUserAgent if (status_code == 503): raise ServiceUnavailable if (status_code != 200): raise OpenSubtitlesError(response['status']) return response
[ "def", "checked", "(", "response", ")", ":", "status_code", "=", "int", "(", "response", "[", "'status'", "]", "[", ":", "3", "]", ")", "if", "(", "status_code", "==", "401", ")", ":", "raise", "Unauthorized", "if", "(", "status_code", "==", "406", "...
check a response status before returning it .
train
true
16,336
def queries(): out = {} for plugin in find_plugins(): out.update(plugin.queries()) return out
[ "def", "queries", "(", ")", ":", "out", "=", "{", "}", "for", "plugin", "in", "find_plugins", "(", ")", ":", "out", ".", "update", "(", "plugin", ".", "queries", "(", ")", ")", "return", "out" ]
returns a dict mapping prefix strings to query subclasses all loaded plugins .
train
false
16,337
def format_display_date(date): return date.strftime(DISPLAY_DATE_FORMAT)
[ "def", "format_display_date", "(", "date", ")", ":", "return", "date", ".", "strftime", "(", "DISPLAY_DATE_FORMAT", ")" ]
returns a formatted date string meant for cli output .
train
false
16,339
def get_wms(version='1.1.1', type_name=None): url = (GEOSERVER_URL + ('%s/wms?request=getcapabilities' % type_name.replace(':', '/'))) return WebMapService(url, version=version, username=GEOSERVER_USER, password=GEOSERVER_PASSWD)
[ "def", "get_wms", "(", "version", "=", "'1.1.1'", ",", "type_name", "=", "None", ")", ":", "url", "=", "(", "GEOSERVER_URL", "+", "(", "'%s/wms?request=getcapabilities'", "%", "type_name", ".", "replace", "(", "':'", ",", "'/'", ")", ")", ")", "return", ...
function to return an owslib wms object .
train
false
16,340
def get_extension(extension_id): for extension in get_extensions(): if (extension.get_id() == extension_id): return extension return None
[ "def", "get_extension", "(", "extension_id", ")", ":", "for", "extension", "in", "get_extensions", "(", ")", ":", "if", "(", "extension", ".", "get_id", "(", ")", "==", "extension_id", ")", ":", "return", "extension", "return", "None" ]
get the extension of a given url .
train
false
16,341
@handle_response_format @treeio_login_required def index_assets(request, response_format='html'): if request.GET: query = _get_filter_query(Asset, request.GET) else: query = Q() filters = AssetFilterForm(request.user.profile, 'title', request.GET) assets = Object.filter_by_request(request, Asset.objects.filter(query), mode='r') return render_to_response('finance/index_assets', {'assets': assets, 'filters': filters}, context_instance=RequestContext(request), response_format=response_format)
[ "@", "handle_response_format", "@", "treeio_login_required", "def", "index_assets", "(", "request", ",", "response_format", "=", "'html'", ")", ":", "if", "request", ".", "GET", ":", "query", "=", "_get_filter_query", "(", "Asset", ",", "request", ".", "GET", ...
index_assets page: displays all assets .
train
false
16,342
def _init_stylesheet(profile): old_script = profile.scripts().findScript('_qute_stylesheet') if (not old_script.isNull()): profile.scripts().remove(old_script) css = shared.get_user_stylesheet() source = "\n (function() {{\n var css = document.createElement('style');\n css.setAttribute('type', 'text/css');\n css.appendChild(document.createTextNode('{}'));\n document.getElementsByTagName('head')[0].appendChild(css);\n }})()\n ".format(javascript.string_escape(css)) script = QWebEngineScript() script.setName('_qute_stylesheet') script.setInjectionPoint(QWebEngineScript.DocumentReady) script.setWorldId(QWebEngineScript.ApplicationWorld) script.setRunsOnSubFrames(True) script.setSourceCode(source) profile.scripts().insert(script)
[ "def", "_init_stylesheet", "(", "profile", ")", ":", "old_script", "=", "profile", ".", "scripts", "(", ")", ".", "findScript", "(", "'_qute_stylesheet'", ")", "if", "(", "not", "old_script", ".", "isNull", "(", ")", ")", ":", "profile", ".", "scripts", ...
initialize custom stylesheets .
train
false
16,343
def RemoveLinkDependenciesFromNoneTargets(targets): for (target_name, target_dict) in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if (target_dict.get('type', None) == 'none'): if targets[t].get('variables', {}).get('link_dependency', 0): target_dict[dependency_key] = Filter(target_dict[dependency_key], t)
[ "def", "RemoveLinkDependenciesFromNoneTargets", "(", "targets", ")", ":", "for", "(", "target_name", ",", "target_dict", ")", "in", "targets", ".", "iteritems", "(", ")", ":", "for", "dependency_key", "in", "dependency_sections", ":", "dependencies", "=", "target_...
remove dependencies having the link_dependency attribute from the none targets .
train
false
16,344
def spring(): rc(u'image', cmap=u'spring') im = gci() if (im is not None): im.set_cmap(cm.spring)
[ "def", "spring", "(", ")", ":", "rc", "(", "u'image'", ",", "cmap", "=", "u'spring'", ")", "im", "=", "gci", "(", ")", "if", "(", "im", "is", "not", "None", ")", ":", "im", ".", "set_cmap", "(", "cm", ".", "spring", ")" ]
set the default colormap to spring and apply to current image if any .
train
false
16,345
def detect_landmarks(path): vision_client = vision.Client() with io.open(path, 'rb') as image_file: content = image_file.read() image = vision_client.image(content=content) landmarks = image.detect_landmarks() print 'Landmarks:' for landmark in landmarks: print landmark.description
[ "def", "detect_landmarks", "(", "path", ")", ":", "vision_client", "=", "vision", ".", "Client", "(", ")", "with", "io", ".", "open", "(", "path", ",", "'rb'", ")", "as", "image_file", ":", "content", "=", "image_file", ".", "read", "(", ")", "image", ...
detects landmarks in the file .
train
false
16,346
def Win32RawInput(prompt=None): try: sys.stdout.flush() sys.stderr.flush() except: pass if (prompt is None): prompt = '' ret = dialog.GetSimpleInput(prompt) if (ret == None): raise KeyboardInterrupt('operation cancelled') return ret
[ "def", "Win32RawInput", "(", "prompt", "=", "None", ")", ":", "try", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "except", ":", "pass", "if", "(", "prompt", "is", "None", ")", ":", "prompt", "=...
provide raw_input() for gui apps .
train
false
16,348
@profiler.trace def network_create(request, **kwargs): LOG.debug(('network_create(): kwargs = %s' % kwargs)) if ('net_profile_id' in kwargs): kwargs['n1kv:profile'] = kwargs.pop('net_profile_id') if ('tenant_id' not in kwargs): kwargs['tenant_id'] = request.user.project_id body = {'network': kwargs} network = neutronclient(request).create_network(body=body).get('network') return Network(network)
[ "@", "profiler", ".", "trace", "def", "network_create", "(", "request", ",", "**", "kwargs", ")", ":", "LOG", ".", "debug", "(", "(", "'network_create(): kwargs = %s'", "%", "kwargs", ")", ")", "if", "(", "'net_profile_id'", "in", "kwargs", ")", ":", "kwar...
create private network cli example: .
train
true
16,349
def wheels(opts, whitelist=None): return LazyLoader(_module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist)
[ "def", "wheels", "(", "opts", ",", "whitelist", "=", "None", ")", ":", "return", "LazyLoader", "(", "_module_dirs", "(", "opts", ",", "'wheel'", ")", ",", "opts", ",", "tag", "=", "'wheel'", ",", "whitelist", "=", "whitelist", ")" ]
returns the wheels modules .
train
false
16,350
def _is_fromfile_compatible(stream): if (sys.version_info[0] < 3): return True bad_cls = [] try: import gzip bad_cls.append(gzip.GzipFile) except ImportError: pass try: import bz2 bad_cls.append(bz2.BZ2File) except ImportError: pass bad_cls = tuple(bad_cls) return (not isinstance(stream, bad_cls))
[ "def", "_is_fromfile_compatible", "(", "stream", ")", ":", "if", "(", "sys", ".", "version_info", "[", "0", "]", "<", "3", ")", ":", "return", "True", "bad_cls", "=", "[", "]", "try", ":", "import", "gzip", "bad_cls", ".", "append", "(", "gzip", ".",...
check whether stream is compatible with numpy .
train
false
16,351
def test_http_header_encoding(): mocked_socket = mock.MagicMock() mocked_socket.sendall = mock.MagicMock() mocked_request = mock.MagicMock() response = Response(mocked_request, mocked_socket, None) response.headers.append(('foo', u'h\xe4der')) with pytest.raises(UnicodeEncodeError): response.send_headers() tosend = response.default_headers() tosend.extend([('%s: %s\r\n' % (k, v)) for (k, v) in response.headers]) header_str = ('%s\r\n' % ''.join(tosend)) with pytest.raises(UnicodeEncodeError): mocked_socket.sendall(util.to_bytestring(header_str, 'ascii'))
[ "def", "test_http_header_encoding", "(", ")", ":", "mocked_socket", "=", "mock", ".", "MagicMock", "(", ")", "mocked_socket", ".", "sendall", "=", "mock", ".", "MagicMock", "(", ")", "mocked_request", "=", "mock", ".", "MagicMock", "(", ")", "response", "=",...
tests whether http response headers are usascii encoded .
train
false
16,352
def multiple_file_normalize_CSS(input_dir, output_dir, output_CSS_statistics): if (not exists(output_dir)): makedirs(output_dir) file_names = [fname for fname in listdir(input_dir) if (not (fname.startswith('.') or isdir(fname)))] for fname in file_names: (base_fname, ext) = splitext(fname) original_fname = (base_fname + '.biom') hdf5_infile = join(input_dir, original_fname) tmp_bt = load_table(hdf5_infile) outfile = join(output_dir, (('CSS_' + base_fname) + '.biom')) if output_CSS_statistics: output_CSS_statistics = join(output_dir, (('CSS_statistics_' + base_fname) + '.txt')) with tempfile.NamedTemporaryFile(dir=get_qiime_temp_dir(), prefix='QIIME-normalize-table-temp-table-', suffix='.biom') as temp_fh: temp_fh.write(tmp_bt.to_json('forR')) temp_fh.flush() run_CSS(temp_fh.name, outfile, output_CSS_statistics=output_CSS_statistics)
[ "def", "multiple_file_normalize_CSS", "(", "input_dir", ",", "output_dir", ",", "output_CSS_statistics", ")", ":", "if", "(", "not", "exists", "(", "output_dir", ")", ")", ":", "makedirs", "(", "output_dir", ")", "file_names", "=", "[", "fname", "for", "fname"...
performs metagenomeseqs css normalization on a directory of raw abundance otu matrices .
train
false
16,353
def kodi_to_config(MASTER_SETTINGS, config, new_settings): for (setting, new_value) in new_settings.iteritems(): setting_protocols = MASTER_SETTINGS.get(setting, None) if (setting_protocols == None): continue config = general_config_set(config, new_settings, new_value, **setting_protocols) return config
[ "def", "kodi_to_config", "(", "MASTER_SETTINGS", ",", "config", ",", "new_settings", ")", ":", "for", "(", "setting", ",", "new_value", ")", "in", "new_settings", ".", "iteritems", "(", ")", ":", "setting_protocols", "=", "MASTER_SETTINGS", ".", "get", "(", ...
takes the existing config .
train
false
16,356
def directLoop(isWiddershins, loop): if (euclidean.isWiddershins(loop) != isWiddershins): loop.reverse()
[ "def", "directLoop", "(", "isWiddershins", ",", "loop", ")", ":", "if", "(", "euclidean", ".", "isWiddershins", "(", "loop", ")", "!=", "isWiddershins", ")", ":", "loop", ".", "reverse", "(", ")" ]
direct the loop .
train
false
16,357
def remove_reqs_readonly(): if (not os.path.isdir(REQS_DIR)): return os.chmod(REQS_DIR, 493) for (root, dirs, files) in os.walk(REQS_DIR): for d in dirs: os.chmod(os.path.join(root, d), 493) for f in files: os.chmod(os.path.join(root, f), 493)
[ "def", "remove_reqs_readonly", "(", ")", ":", "if", "(", "not", "os", ".", "path", ".", "isdir", "(", "REQS_DIR", ")", ")", ":", "return", "os", ".", "chmod", "(", "REQS_DIR", ",", "493", ")", "for", "(", "root", ",", "dirs", ",", "files", ")", "...
workaround for issue #569 .
train
false
16,358
def _summary_judgment(rec): if config['import']['quiet']: if (rec == Recommendation.strong): return importer.action.APPLY else: action = config['import']['quiet_fallback'].as_choice({'skip': importer.action.SKIP, 'asis': importer.action.ASIS}) elif (rec == Recommendation.none): action = config['import']['none_rec_action'].as_choice({'skip': importer.action.SKIP, 'asis': importer.action.ASIS, 'ask': None}) else: return None if (action == importer.action.SKIP): print_(u'Skipping.') elif (action == importer.action.ASIS): print_(u'Importing as-is.') return action
[ "def", "_summary_judgment", "(", "rec", ")", ":", "if", "config", "[", "'import'", "]", "[", "'quiet'", "]", ":", "if", "(", "rec", "==", "Recommendation", ".", "strong", ")", ":", "return", "importer", ".", "action", ".", "APPLY", "else", ":", "action...
determines whether a decision should be made without even asking the user .
train
false
16,359
def center_text(text, length=80, left_edge='|', right_edge='|', text_length=None): if (text_length is None): text_length = get_text_length(text) output = [] char_start = (((length // 2) - (text_length // 2)) - 1) output.append(((left_edge + (' ' * char_start)) + text)) length_so_far = ((get_text_length(left_edge) + char_start) + text_length) right_side_spaces = ((length - get_text_length(right_edge)) - length_so_far) output.append((' ' * right_side_spaces)) output.append(right_edge) final = ''.join(output) return final
[ "def", "center_text", "(", "text", ",", "length", "=", "80", ",", "left_edge", "=", "'|'", ",", "right_edge", "=", "'|'", ",", "text_length", "=", "None", ")", ":", "if", "(", "text_length", "is", "None", ")", ":", "text_length", "=", "get_text_length", ...
center text with specified edge chars .
train
false
16,360
def xblock_local_resource_url(block, uri): xblock_class = getattr(block.__class__, 'unmixed_class', block.__class__) if (settings.PIPELINE_ENABLED or (not settings.REQUIRE_DEBUG)): return staticfiles_storage.url('xblock/resources/{package_name}/{path}'.format(package_name=xblock_class.__module__, path=uri)) else: return reverse('xblock_resource_url', kwargs={'block_type': block.scope_ids.block_type, 'uri': uri})
[ "def", "xblock_local_resource_url", "(", "block", ",", "uri", ")", ":", "xblock_class", "=", "getattr", "(", "block", ".", "__class__", ",", "'unmixed_class'", ",", "block", ".", "__class__", ")", "if", "(", "settings", ".", "PIPELINE_ENABLED", "or", "(", "n...
returns the url for an xblocks local resource .
train
false
16,361
def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only): matrix = represent(Mul(*circuit), nqubits=nqubits) if isinstance(matrix, Number): return ((matrix == 1) if identity_only else True) else: matrix_trace = matrix.trace() adjusted_matrix_trace = ((matrix_trace / matrix[0]) if (not identity_only) else matrix_trace) is_identity = ((matrix[0] == 1.0) if identity_only else True) has_correct_trace = (adjusted_matrix_trace == pow(2, nqubits)) return bool((matrix.is_diagonal() and has_correct_trace and is_identity))
[ "def", "is_scalar_nonsparse_matrix", "(", "circuit", ",", "nqubits", ",", "identity_only", ")", ":", "matrix", "=", "represent", "(", "Mul", "(", "*", "circuit", ")", ",", "nqubits", "=", "nqubits", ")", "if", "isinstance", "(", "matrix", ",", "Number", ")...
checks if a given circuit .
train
false
16,363
@requires_sklearn def test_spatio_temporal_tris_connectivity(): tris = np.array([[0, 1, 2], [3, 4, 5]]) connectivity = spatio_temporal_tris_connectivity(tris, 2) x = [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] components = stats.cluster_level._get_components(np.array(x), connectivity) old_fmt = [0, 0, (-2), (-2), (-2), (-2), 0, (-2), (-2), (-2), (-2), 1] new_fmt = np.array(old_fmt) new_fmt = [np.nonzero((new_fmt == v))[0] for v in np.unique(new_fmt[(new_fmt >= 0)])] assert_true(len(new_fmt), len(components)) for (c, n) in zip(components, new_fmt): assert_array_equal(c, n)
[ "@", "requires_sklearn", "def", "test_spatio_temporal_tris_connectivity", "(", ")", ":", "tris", "=", "np", ".", "array", "(", "[", "[", "0", ",", "1", ",", "2", "]", ",", "[", "3", ",", "4", ",", "5", "]", "]", ")", "connectivity", "=", "spatio_temp...
test spatio-temporal connectivity from triangles .
train
false
16,366
def upload(): os.system('cd build/html; rsync -avz . pandas@pandas.pydata.org:/usr/share/nginx/pandas/pandas-docs/vbench/ -essh')
[ "def", "upload", "(", ")", ":", "os", ".", "system", "(", "'cd build/html; rsync -avz . pandas@pandas.pydata.org:/usr/share/nginx/pandas/pandas-docs/vbench/ -essh'", ")" ]
upload handler .
train
false
16,367
def getProcessOutputAndValue(executable, args=(), env={}, path=None, reactor=None): return _callProtocolWithDeferred(_EverythingGetter, executable, args, env, path, reactor)
[ "def", "getProcessOutputAndValue", "(", "executable", ",", "args", "=", "(", ")", ",", "env", "=", "{", "}", ",", "path", "=", "None", ",", "reactor", "=", "None", ")", ":", "return", "_callProtocolWithDeferred", "(", "_EverythingGetter", ",", "executable", ...
spawn a process and returns a deferred that will be called back with its output and its exit code as if a signal is raised .
train
false
16,368
def corr_ar(k_vars, ar): from scipy.linalg import toeplitz if (len(ar) < k_vars): ar_ = np.zeros(k_vars) ar_[:len(ar)] = ar ar = ar_ return toeplitz(ar)
[ "def", "corr_ar", "(", "k_vars", ",", "ar", ")", ":", "from", "scipy", ".", "linalg", "import", "toeplitz", "if", "(", "len", "(", "ar", ")", "<", "k_vars", ")", ":", "ar_", "=", "np", ".", "zeros", "(", "k_vars", ")", "ar_", "[", ":", "len", "...
create autoregressive correlation matrix this might be ma .
train
false
16,369
def RecordFromLine(line): try: (created, level, unused_source_location, message) = _StrictParseLogEntry(line, clean_message=False) message = Stripnl(message) return LoggingRecord(level, created, message, None) except ValueError: return StderrRecord(line)
[ "def", "RecordFromLine", "(", "line", ")", ":", "try", ":", "(", "created", ",", "level", ",", "unused_source_location", ",", "message", ")", "=", "_StrictParseLogEntry", "(", "line", ",", "clean_message", "=", "False", ")", "message", "=", "Stripnl", "(", ...
create the correct type of record based on what the line looks like .
train
false
16,370
def GetSigner(secret): return GetSecretsManagerForSecret(secret).GetSigner(secret)
[ "def", "GetSigner", "(", "secret", ")", ":", "return", "GetSecretsManagerForSecret", "(", "secret", ")", ".", "GetSigner", "(", "secret", ")" ]
returns the keyczar signer object returned by the secrets manager instance getsigner method .
train
false
16,371
def _portsnap(): ret = ['portsnap'] if (float(__grains__['osrelease']) >= 10): ret.append('--interactive') return ret
[ "def", "_portsnap", "(", ")", ":", "ret", "=", "[", "'portsnap'", "]", "if", "(", "float", "(", "__grains__", "[", "'osrelease'", "]", ")", ">=", "10", ")", ":", "ret", ".", "append", "(", "'--interactive'", ")", "return", "ret" ]
return portsnap --interactive for freebsd 10 .
train
false
16,372
def isscalarlike(x): return (np.isscalar(x) or (isdense(x) and (x.ndim == 0)))
[ "def", "isscalarlike", "(", "x", ")", ":", "return", "(", "np", ".", "isscalar", "(", "x", ")", "or", "(", "isdense", "(", "x", ")", "and", "(", "x", ".", "ndim", "==", "0", ")", ")", ")" ]
is x either a scalar .
train
false
16,373
def xfs_mkfs_options(tune2fs_dict, mkfs_option): xfs_mapping = {'meta-data: isize': '-i size', 'meta-data: agcount': '-d agcount', 'meta-data: sectsz': '-s size', 'meta-data: attr': '-i attr', 'data: bsize': '-b size', 'data: imaxpct': '-i maxpct', 'data: sunit': '-d sunit', 'data: swidth': '-d swidth', 'data: unwritten': '-d unwritten', 'naming: version': '-n version', 'naming: bsize': '-n size', 'log: version': '-l version', 'log: sectsz': '-l sectsize', 'log: sunit': '-l sunit', 'log: lazy-count': '-l lazy-count', 'realtime: extsz': '-r extsize', 'realtime: blocks': '-r size', 'realtime: rtextents': '-r rtdev'} mkfs_option['-l size'] = (tune2fs_dict['log: bsize'] * tune2fs_dict['log: blocks']) for (key, value) in xfs_mapping.iteritems(): mkfs_option[value] = tune2fs_dict[key]
[ "def", "xfs_mkfs_options", "(", "tune2fs_dict", ",", "mkfs_option", ")", ":", "xfs_mapping", "=", "{", "'meta-data: isize'", ":", "'-i size'", ",", "'meta-data: agcount'", ":", "'-d agcount'", ",", "'meta-data: sectsz'", ":", "'-s size'", ",", "'meta-data: attr'", ":"...
maps filesystem tunables to their corresponding mkfs options .
train
false
16,374
def format_add_taxa_summary_mapping(summary, tax_order, mapping, header, delimiter=';'): tax_order = [delimiter.join(tax) for tax in tax_order] header.extend(tax_order) (yield ('#%s\n' % ' DCTB '.join(header))) for row in mapping: sample_id = row[0] if (sample_id not in summary): continue row.extend(map(str, summary[sample_id])) (yield ('%s\n' % ' DCTB '.join(row)))
[ "def", "format_add_taxa_summary_mapping", "(", "summary", ",", "tax_order", ",", "mapping", ",", "header", ",", "delimiter", "=", "';'", ")", ":", "tax_order", "=", "[", "delimiter", ".", "join", "(", "tax", ")", "for", "tax", "in", "tax_order", "]", "head...
formats a summarized taxonomy with mapping information .
train
false
16,375
@aborts def test_aborts_on_nonexistent_roles(): merge([], ['badrole'], [], {})
[ "@", "aborts", "def", "test_aborts_on_nonexistent_roles", "(", ")", ":", "merge", "(", "[", "]", ",", "[", "'badrole'", "]", ",", "[", "]", ",", "{", "}", ")" ]
aborts if any given roles arent found .
train
false
16,376
def link_fd_to_path(fd, target_path, dirs_created=0, retries=2, fsync=True): dirpath = os.path.dirname(target_path) for _junk in range(0, retries): try: linkat(linkat.AT_FDCWD, ('/proc/self/fd/%d' % fd), linkat.AT_FDCWD, target_path, linkat.AT_SYMLINK_FOLLOW) break except IOError as err: if (err.errno == errno.ENOENT): dirs_created = makedirs_count(dirpath) elif (err.errno == errno.EEXIST): try: os.unlink(target_path) except OSError as e: if (e.errno != errno.ENOENT): raise else: raise if fsync: for i in range(0, (dirs_created + 1)): fsync_dir(dirpath) dirpath = os.path.dirname(dirpath)
[ "def", "link_fd_to_path", "(", "fd", ",", "target_path", ",", "dirs_created", "=", "0", ",", "retries", "=", "2", ",", "fsync", "=", "True", ")", ":", "dirpath", "=", "os", ".", "path", ".", "dirname", "(", "target_path", ")", "for", "_junk", "in", "...
creates a link to file descriptor at target_path specified .
train
false
16,380
def reprogress(): if (_last_progress and _last_progress.endswith('\r')): progress(_last_progress)
[ "def", "reprogress", "(", ")", ":", "if", "(", "_last_progress", "and", "_last_progress", ".", "endswith", "(", "'\\r'", ")", ")", ":", "progress", "(", "_last_progress", ")" ]
calls progress() to redisplay the most recent progress message .
train
false
16,381
def with_timeout(seconds, function, *args, **kwds): timeout_value = kwds.pop('timeout_value', _NONE) timeout = Timeout.start_new(seconds) try: return function(*args, **kwds) except Timeout: if ((sys.exc_info()[1] is timeout) and (timeout_value is not _NONE)): return timeout_value raise finally: timeout.cancel()
[ "def", "with_timeout", "(", "seconds", ",", "function", ",", "*", "args", ",", "**", "kwds", ")", ":", "timeout_value", "=", "kwds", ".", "pop", "(", "'timeout_value'", ",", "_NONE", ")", "timeout", "=", "Timeout", ".", "start_new", "(", "seconds", ")", ...
wraps a .
train
false
16,382
def validate_fields_spec(cls, model, opts, flds, label): for fields in flds: if (type(fields) != tuple): fields = (fields,) for field in fields: if (field in cls.readonly_fields): continue check_formfield(cls, model, opts, label, field) try: f = opts.get_field(field) except models.FieldDoesNotExist: continue if (isinstance(f, models.ManyToManyField) and (not f.rel.through._meta.auto_created)): raise ImproperlyConfigured(("'%s.%s' can't include the ManyToManyField field '%s' because '%s' manually specifies a 'through' model." % (cls.__name__, label, field, field)))
[ "def", "validate_fields_spec", "(", "cls", ",", "model", ",", "opts", ",", "flds", ",", "label", ")", ":", "for", "fields", "in", "flds", ":", "if", "(", "type", "(", "fields", ")", "!=", "tuple", ")", ":", "fields", "=", "(", "fields", ",", ")", ...
validate the fields specification in flds from a modeladmin subclass cls for the model model .
train
false
16,383
@pytest.fixture def install_egg(modules_tmpdir, monkeypatch): def inner(name, base=modules_tmpdir): if (not isinstance(name, str)): raise ValueError(name) base.join(name).ensure_dir() base.join(name).join('__init__.py').ensure() egg_setup = base.join('setup.py') egg_setup.write(textwrap.dedent("\n from setuptools import setup\n setup(name='{0}',\n version='1.0',\n packages=['site_egg'],\n zip_safe=True)\n ".format(name))) import subprocess subprocess.check_call([sys.executable, 'setup.py', 'bdist_egg'], cwd=str(modules_tmpdir)) (egg_path,) = modules_tmpdir.join('dist/').listdir() monkeypatch.syspath_prepend(str(egg_path)) return egg_path return inner
[ "@", "pytest", ".", "fixture", "def", "install_egg", "(", "modules_tmpdir", ",", "monkeypatch", ")", ":", "def", "inner", "(", "name", ",", "base", "=", "modules_tmpdir", ")", ":", "if", "(", "not", "isinstance", "(", "name", ",", "str", ")", ")", ":",...
generate egg from package name inside base and put the egg into sys .
train
false
16,384
def system_script_extension(system=None): exts = {'windows': '.bat', 'darwin': '.command', 'linux': '.sh'} system = (system or platform.system()) return exts.get(system.lower(), '.sh')
[ "def", "system_script_extension", "(", "system", "=", "None", ")", ":", "exts", "=", "{", "'windows'", ":", "'.bat'", ",", "'darwin'", ":", "'.command'", ",", "'linux'", ":", "'.sh'", "}", "system", "=", "(", "system", "or", "platform", ".", "system", "(...
the extension for the one script that could be considered "the os script" for the given system .
train
false
16,388
def test_seeg_ecog(): (n_epochs, n_channels, n_times, sfreq) = (5, 10, 20, 1000.0) data = np.ones((n_epochs, n_channels, n_times)) events = np.array([np.arange(n_epochs), ([0] * n_epochs), ([1] * n_epochs)]).T pick_dict = dict(meg=False, exclude=[]) for key in ('seeg', 'ecog'): info = create_info(n_channels, sfreq, key) epochs = EpochsArray(data, info, events) pick_dict.update({key: True}) picks = pick_types(epochs.info, **pick_dict) del pick_dict[key] assert_equal(len(picks), n_channels)
[ "def", "test_seeg_ecog", "(", ")", ":", "(", "n_epochs", ",", "n_channels", ",", "n_times", ",", "sfreq", ")", "=", "(", "5", ",", "10", ",", "20", ",", "1000.0", ")", "data", "=", "np", ".", "ones", "(", "(", "n_epochs", ",", "n_channels", ",", ...
test the compatibility of the epoch object with seeg and ecog data .
train
false
16,391
def pillar(tgt, delimiter=DEFAULT_TARGET_DELIM): matcher = salt.minion.Matcher({'pillar': __pillar__}, __salt__) try: return matcher.pillar_match(tgt, delimiter=delimiter) except Exception as exc: log.exception(exc) return False
[ "def", "pillar", "(", "tgt", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ")", ":", "matcher", "=", "salt", ".", "minion", ".", "Matcher", "(", "{", "'pillar'", ":", "__pillar__", "}", ",", "__salt__", ")", "try", ":", "return", "matcher", ".", "pillar...
return true if the minion matches the given pillar target .
train
false
16,392
def get_pk_columns(cls): retval = [] for (k, v) in cls.get_flat_type_info(cls).items(): if ((v.Attributes.sqla_column_args is not None) and v.Attributes.sqla_column_args[(-1)].get('primary_key', False)): retval.append((k, v)) return (tuple(retval) if (len(retval) > 0) else None)
[ "def", "get_pk_columns", "(", "cls", ")", ":", "retval", "=", "[", "]", "for", "(", "k", ",", "v", ")", "in", "cls", ".", "get_flat_type_info", "(", "cls", ")", ".", "items", "(", ")", ":", "if", "(", "(", "v", ".", "Attributes", ".", "sqla_colum...
return primary key fields of a spyne object .
train
false
16,393
def display_upstream_changes(registry, xml_parent, data): XML.SubElement(xml_parent, 'jenkins.plugins.displayupstreamchanges.DisplayUpstreamChangesRecorder')
[ "def", "display_upstream_changes", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "XML", ".", "SubElement", "(", "xml_parent", ",", "'jenkins.plugins.displayupstreamchanges.DisplayUpstreamChangesRecorder'", ")" ]
yaml: display-upstream-changes display scm changes of upstream jobs .
train
false
16,395
def read_error_handler(func): @wraps(func) def error_handler_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception: return (args[0], '') return error_handler_wrapper
[ "def", "read_error_handler", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "error_handler_wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "except", "...
ignores exceptions by always returning the filename and an empty string as read file content .
train
false
16,396
def load_square_sprite_image(img_path, n_sprites): (tile_rows, tile_cols) = get_tiles_height_width(n_sprites) return load_sprite_image(img_path, (tile_rows, tile_cols), n_sprites=n_sprites)
[ "def", "load_square_sprite_image", "(", "img_path", ",", "n_sprites", ")", ":", "(", "tile_rows", ",", "tile_cols", ")", "=", "get_tiles_height_width", "(", "n_sprites", ")", "return", "load_sprite_image", "(", "img_path", ",", "(", "tile_rows", ",", "tile_cols", ...
just like load_sprite_image but assumes tiled image is square .
train
false
16,397
def max_none(data): if (not data): return max(data) non_none_data = [] for d in data: if (d is not None): non_none_data.append(d) return (max(non_none_data) if non_none_data else None)
[ "def", "max_none", "(", "data", ")", ":", "if", "(", "not", "data", ")", ":", "return", "max", "(", "data", ")", "non_none_data", "=", "[", "]", "for", "d", "in", "data", ":", "if", "(", "d", "is", "not", "None", ")", ":", "non_none_data", ".", ...
given a list of data .
train
false
16,399
def getargtxt(obj, one_arg_per_line=True): args = getargs(obj) if args: sep = ', ' textlist = None for (i_arg, arg) in enumerate(args): if (textlist is None): textlist = [''] textlist[(-1)] += arg if (i_arg < (len(args) - 1)): textlist[(-1)] += sep if ((len(textlist[(-1)]) >= 32) or one_arg_per_line): textlist.append('') if (inspect.isclass(obj) or inspect.ismethod(obj)): if (len(textlist) == 1): return None if (('self' + sep) in textlist): textlist.remove(('self' + sep)) return textlist
[ "def", "getargtxt", "(", "obj", ",", "one_arg_per_line", "=", "True", ")", ":", "args", "=", "getargs", "(", "obj", ")", "if", "args", ":", "sep", "=", "', '", "textlist", "=", "None", "for", "(", "i_arg", ",", "arg", ")", "in", "enumerate", "(", "...
get the names and default values of a functions arguments return list with separators formatted for calltips .
train
true
16,400
def get_role(trans, id): id = trans.security.decode_id(id) role = trans.sa_session.query(trans.model.Role).get(id) if (not role): return trans.show_error_message(('Role not found for id (%s)' % str(id))) return role
[ "def", "get_role", "(", "trans", ",", "id", ")", ":", "id", "=", "trans", ".", "security", ".", "decode_id", "(", "id", ")", "role", "=", "trans", ".", "sa_session", ".", "query", "(", "trans", ".", "model", ".", "Role", ")", ".", "get", "(", "id...
retrieve a role by name .
train
false
16,401
@bdd.given('I have a fresh instance') def fresh_instance(quteproc): quteproc.terminate() quteproc.start()
[ "@", "bdd", ".", "given", "(", "'I have a fresh instance'", ")", "def", "fresh_instance", "(", "quteproc", ")", ":", "quteproc", ".", "terminate", "(", ")", "quteproc", ".", "start", "(", ")" ]
restart qutebrowser instance for tests needing a fresh state .
train
false
16,402
def to_categorical(y, nb_classes): y = np.asarray(y, dtype='int32') if (not nb_classes): nb_classes = (np.max(y) + 1) Y = np.zeros((len(y), nb_classes)) for i in range(len(y)): Y[(i, y[i])] = 1.0 return Y
[ "def", "to_categorical", "(", "y", ",", "nb_classes", ")", ":", "y", "=", "np", ".", "asarray", "(", "y", ",", "dtype", "=", "'int32'", ")", "if", "(", "not", "nb_classes", ")", ":", "nb_classes", "=", "(", "np", ".", "max", "(", "y", ")", "+", ...
converts a class vector to binary class matrix .
train
false
16,403
def perform_reset(request, obj): return execute_locked(request, obj, _('All repositories have been reset.'), obj.do_reset, request)
[ "def", "perform_reset", "(", "request", ",", "obj", ")", ":", "return", "execute_locked", "(", "request", ",", "obj", ",", "_", "(", "'All repositories have been reset.'", ")", ",", "obj", ".", "do_reset", ",", "request", ")" ]
helper function to do the repository reset .
train
false
16,404
def check_access(action, context, data_dict=None): try: audit = context.get('__auth_audit', [])[(-1)] except IndexError: audit = '' if (audit and (audit[0] == action)): context['__auth_audit'].pop() user = context.get('user') try: if ('auth_user_obj' not in context): context['auth_user_obj'] = None if (not context.get('ignore_auth')): if (not context.get('__auth_user_obj_checked')): if (context.get('user') and (not context.get('auth_user_obj'))): context['auth_user_obj'] = model.User.by_name(context['user']) context['__auth_user_obj_checked'] = True context = _prepopulate_context(context) logic_authorization = authz.is_authorized(action, context, data_dict) if (not logic_authorization['success']): msg = logic_authorization.get('msg', '') raise NotAuthorized(msg) except NotAuthorized as e: log.debug(u'check access NotAuthorized - %s user=%s "%s"', action, user, unicode(e)) raise log.debug('check access OK - %s user=%s', action, user) return True
[ "def", "check_access", "(", "action", ",", "context", ",", "data_dict", "=", "None", ")", ":", "try", ":", "audit", "=", "context", ".", "get", "(", "'__auth_audit'", ",", "[", "]", ")", "[", "(", "-", "1", ")", "]", "except", "IndexError", ":", "a...
check if external address is allowed given access_type access_type: 1=nzb .
train
false
16,405
def waterbutler_url_for(request_type, provider, path, node_id, token, obj_args=None, **query): url = furl.furl(website_settings.WATERBUTLER_URL) url.path.segments.append(request_type) url.args.update({'path': path, 'nid': node_id, 'provider': provider}) if (token is not None): url.args['cookie'] = token if ('view_only' in obj_args): url.args['view_only'] = obj_args['view_only'] url.args.update(query) return url.url
[ "def", "waterbutler_url_for", "(", "request_type", ",", "provider", ",", "path", ",", "node_id", ",", "token", ",", "obj_args", "=", "None", ",", "**", "query", ")", ":", "url", "=", "furl", ".", "furl", "(", "website_settings", ".", "WATERBUTLER_URL", ")"...
reverse url lookup for waterbutler routes .
train
false
16,406
def monitorFiles(outfiles, seconds, timeoutms): devnull = open('/dev/null', 'w') (tails, fdToFile, fdToHost) = ({}, {}, {}) for (h, outfile) in outfiles.iteritems(): tail = Popen(['tail', '-f', outfile], stdout=PIPE, stderr=devnull) fd = tail.stdout.fileno() tails[h] = tail fdToFile[fd] = tail.stdout fdToHost[fd] = h readable = poll() for t in tails.values(): readable.register(t.stdout.fileno(), POLLIN) endTime = (time() + seconds) while (time() < endTime): fdlist = readable.poll(timeoutms) if fdlist: for (fd, _flags) in fdlist: f = fdToFile[fd] host = fdToHost[fd] line = f.readline().strip() (yield (host, line)) else: (yield (None, '')) for t in tails.values(): t.terminate() devnull.close()
[ "def", "monitorFiles", "(", "outfiles", ",", "seconds", ",", "timeoutms", ")", ":", "devnull", "=", "open", "(", "'/dev/null'", ",", "'w'", ")", "(", "tails", ",", "fdToFile", ",", "fdToHost", ")", "=", "(", "{", "}", ",", "{", "}", ",", "{", "}", ...
monitor set of files and return [ .
train
false
16,407
def get_debug_count(environ): if ('paste.evalexception.debug_count' in environ): return environ['paste.evalexception.debug_count'] else: environ['paste.evalexception.debug_count'] = next = six.next(debug_counter) return next
[ "def", "get_debug_count", "(", "environ", ")", ":", "if", "(", "'paste.evalexception.debug_count'", "in", "environ", ")", ":", "return", "environ", "[", "'paste.evalexception.debug_count'", "]", "else", ":", "environ", "[", "'paste.evalexception.debug_count'", "]", "=...
return the unique debug count for the current request .
train
false
16,409
def _primitive_root_prime_iter(p): p = as_int(p) v = [((p - 1) // i) for i in factorint((p - 1)).keys()] a = 2 while (a < p): for pw in v: if (pow(a, pw, p) == 1): break else: (yield a) a += 1
[ "def", "_primitive_root_prime_iter", "(", "p", ")", ":", "p", "=", "as_int", "(", "p", ")", "v", "=", "[", "(", "(", "p", "-", "1", ")", "//", "i", ")", "for", "i", "in", "factorint", "(", "(", "p", "-", "1", ")", ")", ".", "keys", "(", ")"...
generates the primitive roots for a prime p references .
train
false
16,412
def _parse_circ_path(path): if path: try: return [_parse_circ_entry(entry) for entry in path.split(',')] except stem.ProtocolError as exc: raise stem.ProtocolError(('%s: %s' % (exc, path))) else: return []
[ "def", "_parse_circ_path", "(", "path", ")", ":", "if", "path", ":", "try", ":", "return", "[", "_parse_circ_entry", "(", "entry", ")", "for", "entry", "in", "path", ".", "split", "(", "','", ")", "]", "except", "stem", ".", "ProtocolError", "as", "exc...
parses a circuit path as a list of **** tuples .
train
false
16,413
def server_powerstatus(host=None, admin_username=None, admin_password=None, module=None): ret = __execute_ret('serveraction powerstatus', host=host, admin_username=admin_username, admin_password=admin_password, module=module) result = {'retcode': 0} if (ret['stdout'] == 'ON'): result['status'] = True result['comment'] = 'Power is on' if (ret['stdout'] == 'OFF'): result['status'] = False result['comment'] = 'Power is on' if ret['stdout'].startswith('ERROR'): result['status'] = False result['comment'] = ret['stdout'] return result
[ "def", "server_powerstatus", "(", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ",", "module", "=", "None", ")", ":", "ret", "=", "__execute_ret", "(", "'serveraction powerstatus'", ",", "host", "=", "host", ","...
return the power status for the passed module cli example: .
train
true
16,414
def libvlc_vprinterr(fmt, ap): f = (_Cfunctions.get('libvlc_vprinterr', None) or _Cfunction('libvlc_vprinterr', ((1,), (1,)), None, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p)) return f(fmt, ap)
[ "def", "libvlc_vprinterr", "(", "fmt", ",", "ap", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_vprinterr'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_vprinterr'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ...
sets the libvlc error status and message for the current thread .
train
true
16,415
def do_hypervisor_stats(cs, args): stats = cs.hypervisor_stats.statistics() utils.print_dict(stats.to_dict())
[ "def", "do_hypervisor_stats", "(", "cs", ",", "args", ")", ":", "stats", "=", "cs", ".", "hypervisor_stats", ".", "statistics", "(", ")", "utils", ".", "print_dict", "(", "stats", ".", "to_dict", "(", ")", ")" ]
get hypervisor statistics over all compute nodes .
train
false
16,416
def KAMA(ds, count, timeperiod=(- (2 ** 31))): return call_talib_with_ds(ds, count, talib.KAMA, timeperiod)
[ "def", "KAMA", "(", "ds", ",", "count", ",", "timeperiod", "=", "(", "-", "(", "2", "**", "31", ")", ")", ")", ":", "return", "call_talib_with_ds", "(", "ds", ",", "count", ",", "talib", ".", "KAMA", ",", "timeperiod", ")" ]
kaufman adaptive moving average .
train
false
16,418
def CheckRequirements(filename): from pip.req import parse_requirements errors = [] for req in parse_requirements(filename): req.check_if_exists() if (not req.satisfied_by): errors.append(req) if errors: raise RuntimeError(('Requirements not installed: %s' % [str(e) for e in errors]))
[ "def", "CheckRequirements", "(", "filename", ")", ":", "from", "pip", ".", "req", "import", "parse_requirements", "errors", "=", "[", "]", "for", "req", "in", "parse_requirements", "(", "filename", ")", ":", "req", ".", "check_if_exists", "(", ")", "if", "...
parse a pip requirements .
train
false
16,419
def _mod_bufsize_linux(iface, *args, **kwargs): ret = {'result': False, 'comment': 'Requires rx=<val> tx==<val> rx-mini=<val> and/or rx-jumbo=<val>'} cmd = ('/sbin/ethtool -G ' + iface) if (not kwargs): return ret if args: ret['comment'] = ('Unknown arguments: ' + ' '.join([str(item) for item in args])) return ret eargs = '' for kw in ['rx', 'tx', 'rx-mini', 'rx-jumbo']: value = kwargs.get(kw) if (value is not None): eargs += (((' ' + kw) + ' ') + str(value)) if (not eargs): return ret cmd += eargs out = __salt__['cmd.run'](cmd) if out: ret['comment'] = out else: ret['comment'] = eargs.strip() ret['result'] = True return ret
[ "def", "_mod_bufsize_linux", "(", "iface", ",", "*", "args", ",", "**", "kwargs", ")", ":", "ret", "=", "{", "'result'", ":", "False", ",", "'comment'", ":", "'Requires rx=<val> tx==<val> rx-mini=<val> and/or rx-jumbo=<val>'", "}", "cmd", "=", "(", "'/sbin/ethtool...
modify network interface buffer sizes using ethtool .
train
true
16,420
def reset(): _runtime.reset()
[ "def", "reset", "(", ")", ":", "_runtime", ".", "reset", "(", ")" ]
set the enrollments and courses arrays to be empty .
train
false
16,421
def build_authenticate_header(realm=''): return {'WWW-Authenticate': ('OAuth realm="%s"' % realm)}
[ "def", "build_authenticate_header", "(", "realm", "=", "''", ")", ":", "return", "{", "'WWW-Authenticate'", ":", "(", "'OAuth realm=\"%s\"'", "%", "realm", ")", "}" ]
optional www-authenticate header .
train
false
16,422
def harvest_lettuces(only_the_apps=None, avoid_apps=None, path='features'): apps = get_apps() if (isinstance(only_the_apps, (list, tuple)) and any(only_the_apps)): def _filter_only_specified(module): return (module.__name__ in only_the_apps) apps = filter(_filter_only_specified, apps) else: apps = filter(_filter_bultins, apps) apps = filter(_filter_configured_apps, apps) apps = filter(_filter_configured_avoids, apps) if (isinstance(avoid_apps, (list, tuple)) and any(avoid_apps)): def _filter_avoid(module): return (module.__name__ not in avoid_apps) apps = filter(_filter_avoid, apps) joinpath = (lambda app: (join(dirname(app.__file__), path), app)) return map(joinpath, apps)
[ "def", "harvest_lettuces", "(", "only_the_apps", "=", "None", ",", "avoid_apps", "=", "None", ",", "path", "=", "'features'", ")", ":", "apps", "=", "get_apps", "(", ")", "if", "(", "isinstance", "(", "only_the_apps", ",", "(", "list", ",", "tuple", ")",...
gets all installed apps that are not from django .
train
false
16,423
def _get_ico_surface(grade, patch_stats=False): from .bem import read_bem_surfaces ico_file_name = op.join(op.dirname(__file__), 'data', 'icos.fif.gz') ico = read_bem_surfaces(ico_file_name, patch_stats, s_id=(9000 + grade), verbose=False) return ico
[ "def", "_get_ico_surface", "(", "grade", ",", "patch_stats", "=", "False", ")", ":", "from", ".", "bem", "import", "read_bem_surfaces", "ico_file_name", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "__file__", ")", ",", "'data'", ",", "'icos.fif...
return an icosahedral surface of the desired grade .
train
false
16,425
def _GetIncludeDirs(config): include_dirs = (config.get('include_dirs', []) + config.get('msvs_system_include_dirs', [])) midl_include_dirs = (config.get('midl_include_dirs', []) + config.get('msvs_system_include_dirs', [])) resource_include_dirs = config.get('resource_include_dirs', include_dirs) include_dirs = _FixPaths(include_dirs) midl_include_dirs = _FixPaths(midl_include_dirs) resource_include_dirs = _FixPaths(resource_include_dirs) return (include_dirs, midl_include_dirs, resource_include_dirs)
[ "def", "_GetIncludeDirs", "(", "config", ")", ":", "include_dirs", "=", "(", "config", ".", "get", "(", "'include_dirs'", ",", "[", "]", ")", "+", "config", ".", "get", "(", "'msvs_system_include_dirs'", ",", "[", "]", ")", ")", "midl_include_dirs", "=", ...
returns the list of directories to be used for #include directives .
train
false
16,426
def make_interp_full_matr(x, y, t, k): assert (x.size == y.size) assert (t.size == ((x.size + k) + 1)) n = x.size A = np.zeros((n, n), dtype=np.float_) for j in range(n): xval = x[j] if (xval == t[k]): left = k else: left = (np.searchsorted(t, xval) - 1) bb = _bspl.evaluate_all_bspl(t, k, xval, left) A[j, (left - k):(left + 1)] = bb c = sl.solve(A, y) return c
[ "def", "make_interp_full_matr", "(", "x", ",", "y", ",", "t", ",", "k", ")", ":", "assert", "(", "x", ".", "size", "==", "y", ".", "size", ")", "assert", "(", "t", ".", "size", "==", "(", "(", "x", ".", "size", "+", "k", ")", "+", "1", ")",...
assemble an spline order k with knots t to interpolate y(x) using full matrices .
train
false
16,428
def rol(value, count): for y in range(count): value *= 2 if (value > 18446744073709551615L): value -= 18446744073709551616L value += 1 return value
[ "def", "rol", "(", "value", ",", "count", ")", ":", "for", "y", "in", "range", "(", "count", ")", ":", "value", "*=", "2", "if", "(", "value", ">", "18446744073709551615", "L", ")", ":", "value", "-=", "18446744073709551616", "L", "value", "+=", "1",...
returns a rotation by k of n .
train
false
16,430
def _convert_for_comparison(self, other, equality_op=False): if isinstance(other, Decimal): return (self, other) if isinstance(other, _numbers.Rational): if (not self._is_special): self = _dec_from_triple(self._sign, str((int(self._int) * other.denominator)), self._exp) return (self, Decimal(other.numerator)) if (equality_op and isinstance(other, _numbers.Complex) and (other.imag == 0)): other = other.real if isinstance(other, float): context = getcontext() if equality_op: context.flags[FloatOperation] = 1 else: context._raise_error(FloatOperation, 'strict semantics for mixing floats and Decimals are enabled') return (self, Decimal.from_float(other)) return (NotImplemented, NotImplemented)
[ "def", "_convert_for_comparison", "(", "self", ",", "other", ",", "equality_op", "=", "False", ")", ":", "if", "isinstance", "(", "other", ",", "Decimal", ")", ":", "return", "(", "self", ",", "other", ")", "if", "isinstance", "(", "other", ",", "_number...
given a decimal instance self and a python object other .
train
false
16,431
def make_cache_table(metadata, table_name='beaker_cache'): return sa.Table(table_name, metadata, sa.Column('namespace', sa.String(255), primary_key=True), sa.Column('accessed', sa.DateTime, nullable=False), sa.Column('created', sa.DateTime, nullable=False), sa.Column('data', sa.PickleType, nullable=False))
[ "def", "make_cache_table", "(", "metadata", ",", "table_name", "=", "'beaker_cache'", ")", ":", "return", "sa", ".", "Table", "(", "table_name", ",", "metadata", ",", "sa", ".", "Column", "(", "'namespace'", ",", "sa", ".", "String", "(", "255", ")", ","...
return a table object suitable for storing cached values for the namespace manager .
train
false