text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def terminate(self): '''Kills the work unit. This is called by the standard worker system, but only in response to an operating system signal. If the job does setup such as creating a child process, its terminate function should kill that child process. More specifically, this...
[ "def", "terminate", "(", "self", ")", ":", "terminate_function_name", "=", "self", ".", "spec", ".", "get", "(", "'terminate_function'", ")", "if", "not", "terminate_function_name", ":", "logger", ".", "error", "(", "'tried to terminate WorkUnit(%r) but no '", "'fun...
45.516129
0.001388
def __allocate_clusters(self): """! @brief Performs cluster analysis using formed CLIQUE blocks. """ for cell in self.__cells: if cell.visited is False: self.__expand_cluster(cell)
[ "def", "__allocate_clusters", "(", "self", ")", ":", "for", "cell", "in", "self", ".", "__cells", ":", "if", "cell", ".", "visited", "is", "False", ":", "self", ".", "__expand_cluster", "(", "cell", ")" ]
30.125
0.008065
def unsurt(surt): """ # Simple surt >>> unsurt('com,example)/') 'example.com/' # Broken surt >>> unsurt('com,example)') 'com,example)' # Long surt >>> unsurt('suffix,domain,sub,subsub,another,subdomain)/path/file/\ index.html?a=b?c=)/') 'subdomain.another.subsub.sub.domain.suff...
[ "def", "unsurt", "(", "surt", ")", ":", "try", ":", "index", "=", "surt", ".", "index", "(", "')/'", ")", "parts", "=", "surt", "[", "0", ":", "index", "]", ".", "split", "(", "','", ")", "parts", ".", "reverse", "(", ")", "host", "=", "'.'", ...
22.407407
0.001585
def accessor(parser, token): """This template tag is used to do complex nested attribute accessing of an object. The first parameter is the object being accessed, subsequent paramters are one of: * a variable in the template context * a literal in the template context * either of the above su...
[ "def", "accessor", "(", "parser", ",", "token", ")", ":", "contents", "=", "token", ".", "split_contents", "(", ")", "tag", "=", "contents", "[", "0", "]", "if", "len", "(", "contents", ")", "<", "3", ":", "raise", "template", ".", "TemplateSyntaxError...
32.044444
0.002019
def readValuesBigWigToWig(self, reference, start, end): """ Read a bigwig file and return a protocol object with values within the query range. This method uses the bigWigToWig command line tool from UCSC GoldenPath. The tool is used to return values within a query region. ...
[ "def", "readValuesBigWigToWig", "(", "self", ",", "reference", ",", "start", ",", "end", ")", ":", "if", "not", "self", ".", "checkReference", "(", "reference", ")", ":", "raise", "exceptions", ".", "ReferenceNameNotFoundException", "(", "reference", ")", "if"...
41.725
0.001756
def GetArtifactCollectorArgs(flow_args, knowledge_base): """Prepare bundle of artifacts and their dependencies for the client. Args: flow_args: An `ArtifactCollectorFlowArgs` instance. knowledge_base: contains information about the client Returns: rdf value object containing a list of extended artif...
[ "def", "GetArtifactCollectorArgs", "(", "flow_args", ",", "knowledge_base", ")", ":", "args", "=", "rdf_artifacts", ".", "ClientArtifactCollectorArgs", "(", ")", "args", ".", "knowledge_base", "=", "knowledge_base", "args", ".", "apply_parsers", "=", "flow_args", "....
38.837838
0.010862
def load(self, days=PRELOAD_DAYS, only_cameras=None, date_from=None, date_to=None, limit=None): """Load Arlo videos from the given criteria :param days: number of days to retrieve :param only_cameras: retrieve only <ArloCamera> on that list :param date_from: refine from in...
[ "def", "load", "(", "self", ",", "days", "=", "PRELOAD_DAYS", ",", "only_cameras", "=", "None", ",", "date_from", "=", "None", ",", "date_to", "=", "None", ",", "limit", "=", "None", ")", ":", "videos", "=", "[", "]", "url", "=", "LIBRARY_ENDPOINT", ...
36.78
0.001589
def expand(self): """Expand each matrix element distributively. Returns: Matrix: Expanded matrix. """ return self.element_wise( lambda o: o.expand() if isinstance(o, QuantumExpression) else o)
[ "def", "expand", "(", "self", ")", ":", "return", "self", ".", "element_wise", "(", "lambda", "o", ":", "o", ".", "expand", "(", ")", "if", "isinstance", "(", "o", ",", "QuantumExpression", ")", "else", "o", ")" ]
30.25
0.008032
def create_results_dir(self): """Ensure that the empty results directory and a stable symlink exist for these versioned targets.""" self._current_results_dir = self._cache_manager._results_dir_path(self.cache_key, stable=False) self._results_dir = self._cache_manager._results_dir_path(self.cache_key, stable...
[ "def", "create_results_dir", "(", "self", ")", ":", "self", ".", "_current_results_dir", "=", "self", ".", "_cache_manager", ".", "_results_dir_path", "(", "self", ".", "cache_key", ",", "stable", "=", "False", ")", "self", ".", "_results_dir", "=", "self", ...
48.454545
0.01105
def _parse_annotations(sbase): """Parses cobra annotations from a given SBase object. Annotations are dictionaries with the providers as keys. Parameters ---------- sbase : libsbml.SBase SBase from which the SBML annotations are read Returns ------- dict (annotation dictionary...
[ "def", "_parse_annotations", "(", "sbase", ")", ":", "annotation", "=", "{", "}", "# SBO term", "if", "sbase", ".", "isSetSBOTerm", "(", ")", ":", "# FIXME: correct handling of annotations", "annotation", "[", "\"sbo\"", "]", "=", "sbase", ".", "getSBOTermID", "...
31.865385
0.000585
def provision_machine(self): """Perform the initial provisioning of the target machine. :return: bool: The client.AddMachineParams :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails """ params = client.AddMachineParams() if ...
[ "def", "provision_machine", "(", "self", ")", ":", "params", "=", "client", ".", "AddMachineParams", "(", ")", "if", "self", ".", "_init_ubuntu_user", "(", ")", ":", "try", ":", "ssh", "=", "self", ".", "_get_ssh_client", "(", "self", ".", "host", ",", ...
32.928571
0.001404
def sample_surface_even(mesh, count): """ Sample the surface of a mesh, returning samples which are approximately evenly spaced. Parameters --------- mesh: Trimesh object count: number of points to return Returns --------- samples: (count,3) points in space on the surface of m...
[ "def", "sample_surface_even", "(", "mesh", ",", "count", ")", ":", "from", ".", "points", "import", "remove_close", "radius", "=", "np", ".", "sqrt", "(", "mesh", ".", "area", "/", "(", "2", "*", "count", ")", ")", "samples", ",", "ids", "=", "sample...
24.5
0.001637
def gridsearch_color_plot(model, x_param, y_param, X=None, y=None, ax=None, **kwargs): """Quick method: Create a color plot showing the best grid search scores across two parameters. This helper function is a quick wrapper to utilize GridSearchColorPlot for one-off analysi...
[ "def", "gridsearch_color_plot", "(", "model", ",", "x_param", ",", "y_param", ",", "X", "=", "None", ",", "y", "=", "None", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Instantiate the visualizer", "visualizer", "=", "GridSearchColorPlot", ...
32.107143
0.00054
def lookup_effective_breakpoint(cls, file_name, line_number, frame): """ Checks if there is an enabled breakpoint at given file_name and line_number. Check breakpoint condition if any. :return: found, enabled and condition verified breakpoint or None :rtype: IKPdbBreakpoint or ...
[ "def", "lookup_effective_breakpoint", "(", "cls", ",", "file_name", ",", "line_number", ",", "frame", ")", ":", "bp", "=", "cls", ".", "breakpoints_by_file_and_line", ".", "get", "(", "(", "file_name", ",", "line_number", ")", ",", "None", ")", "if", "not", ...
33.954545
0.010417
def set_distribute_verbatim(self, distribute_verbatim=None): """Sets the distribution rights. :param distribute_verbatim: right to distribute verbatim copies :type distribute_verbatim: ``boolean`` :raise: ``InvalidArgument`` -- ``distribute_verbatim`` is invalid :raise: ``NoAcce...
[ "def", "set_distribute_verbatim", "(", "self", ",", "distribute_verbatim", "=", "None", ")", ":", "if", "distribute_verbatim", "is", "None", ":", "raise", "NullArgument", "(", ")", "metadata", "=", "Metadata", "(", "*", "*", "settings", ".", "METADATA", "[", ...
41.05
0.002381
def pprint_arg(vnames, value): """ pretty print argument :param vnames: :param value: :return: """ ret = '' for name, v in zip(vnames, value): ret += '%s=%s;' % (name, str(v)) return ret;
[ "def", "pprint_arg", "(", "vnames", ",", "value", ")", ":", "ret", "=", "''", "for", "name", ",", "v", "in", "zip", "(", "vnames", ",", "value", ")", ":", "ret", "+=", "'%s=%s;'", "%", "(", "name", ",", "str", "(", "v", ")", ")", "return", "ret...
20.090909
0.008658
def convert_cygwin_path(path): """Convert Unix path from Cygwin to Windows path.""" try: win_path = subprocess.check_output(["cygpath", "-aw", path], universal_newlines=True).strip() except (FileNotFoundError, subprocess.CalledProcessError): logger.exception("Call to cygpath failed.") raise return win_path
[ "def", "convert_cygwin_path", "(", "path", ")", ":", "try", ":", "win_path", "=", "subprocess", ".", "check_output", "(", "[", "\"cygpath\"", ",", "\"-aw\"", ",", "path", "]", ",", "universal_newlines", "=", "True", ")", ".", "strip", "(", ")", "except", ...
31
0.028213
def error_name(self) : "the error name for a DBUS.MESSAGE_TYPE_ERROR message." result = dbus.dbus_message_get_error_name(self._dbobj) if result != None : result = result.decode() #end if return \ result
[ "def", "error_name", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_get_error_name", "(", "self", ".", "_dbobj", ")", "if", "result", "!=", "None", ":", "result", "=", "result", ".", "decode", "(", ")", "#end if", "return", "result" ]
32.375
0.022556
def d2AIbr_dV2(self, dIbr_dVa, dIbr_dVm, Ibr, Ybr, V, lam): """ Based on d2AIbr_dV2.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @rtype: tuple @return: The 2nd derivatives of |complex current|**...
[ "def", "d2AIbr_dV2", "(", "self", ",", "dIbr_dVa", ",", "dIbr_dVm", ",", "Ibr", ",", "Ybr", ",", "V", ",", "lam", ")", ":", "il", "=", "range", "(", "len", "(", "lam", ")", ")", "diaglam", "=", "csr_matrix", "(", "(", "lam", ",", "(", "il", ","...
40.619048
0.011455
def mv_to_pypsa(network): """Translate MV grid topology representation to PyPSA format MV grid topology translated here includes * MV station (no transformer, see :meth:`~.grid.network.EDisGo.analyze`) * Loads, Generators, Lines, Storages, Branch Tees of MV grid level as well as LV stations. LV ...
[ "def", "mv_to_pypsa", "(", "network", ")", ":", "generators", "=", "network", ".", "mv_grid", ".", "generators", "loads", "=", "network", ".", "mv_grid", ".", "graph", ".", "nodes_by_attribute", "(", "'load'", ")", "branch_tees", "=", "network", ".", "mv_gri...
34.263374
0.000467
def render(self, *args, **kwargs): ''' Creates a <title> tag if not present and renders the DOCTYPE and tag tree. ''' r = [] #Validates the tag tree and adds the doctype if one was set if self.doctype: r.append(self.doctype) r.append('\n') r.append(super(document, self).render(*...
[ "def", "render", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "r", "=", "[", "]", "#Validates the tag tree and adds the doctype if one was set", "if", "self", ".", "doctype", ":", "r", ".", "append", "(", "self", ".", "doctype", ")", ...
26.769231
0.011111
def setup_context_menu(self): """Reimplement PythonShellWidget method""" PythonShellWidget.setup_context_menu(self) self.help_action = create_action(self, _("Help..."), icon=ima.icon('DialogHelpButton'), triggered=self.help) sel...
[ "def", "setup_context_menu", "(", "self", ")", ":", "PythonShellWidget", ".", "setup_context_menu", "(", "self", ")", "self", ".", "help_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Help...\"", ")", ",", "icon", "=", "ima", ".", "icon", "(...
49.714286
0.011299
def get_changeform_initial_data(self, request): '''Copy initial data from parent''' initial = super(PageAdmin, self).get_changeform_initial_data(request) if ('translation_of' in request.GET): original = self.model._tree_manager.get( pk=request.GET.get('translation_of'...
[ "def", "get_changeform_initial_data", "(", "self", ",", "request", ")", ":", "initial", "=", "super", "(", "PageAdmin", ",", "self", ")", ".", "get_changeform_initial_data", "(", "request", ")", "if", "(", "'translation_of'", "in", "request", ".", "GET", ")", ...
42.95
0.002278
def qapplication(translate=True, test_time=3): """Return QApplication instance Creates it if it doesn't already exist""" app = QApplication.instance() if app is None: app = QApplication(['Conda-Manager']) app.setApplicationName('Conda-Manager') if translate: install_t...
[ "def", "qapplication", "(", "translate", "=", "True", ",", "test_time", "=", "3", ")", ":", "app", "=", "QApplication", ".", "instance", "(", ")", "if", "app", "is", "None", ":", "app", "=", "QApplication", "(", "[", "'Conda-Manager'", "]", ")", "app",...
34.6875
0.001754
def addNewTopology(self, state_manager, topologyName): """ Adds a topology in the local cache, and sets a watch on any changes on the topology. """ topology = Topology(topologyName, state_manager.name) Log.info("Adding new topology: %s, state_manager: %s", topologyName, state_manage...
[ "def", "addNewTopology", "(", "self", ",", "state_manager", ",", "topologyName", ")", ":", "topology", "=", "Topology", "(", "topologyName", ",", "state_manager", ".", "name", ")", "Log", ".", "info", "(", "\"Adding new topology: %s, state_manager: %s\"", ",", "to...
38.636364
0.011473
def getLocalIPaddress(): """visible to other machines on LAN""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('google.com', 0)) my_local_ip = s.getsockname()[0] # takes ~0.005s #from netifaces import interfaces, ifaddresses, AF_INET #full solution i...
[ "def", "getLocalIPaddress", "(", ")", ":", "try", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "s", ".", "connect", "(", "(", "'google.com'", ",", "0", ")", ")", "my_local_ip", "=", "s"...
44.235294
0.009115
def title(self, txt=None): u'''Set/get title.''' if txt: System.Console.Title = txt else: return System.Console.Title
[ "def", "title", "(", "self", ",", "txt", "=", "None", ")", ":", "if", "txt", ":", "System", ".", "Console", ".", "Title", "=", "txt", "else", ":", "return", "System", ".", "Console", ".", "Title" ]
27.5
0.011765
def _get_aggregated_object(self, composite_key): """ method talks with the map of instances of aggregated objects :param composite_key presents tuple, comprising of domain_name and timeperiod""" if composite_key not in self.aggregated_objects: self.aggregated_objects[composite_ke...
[ "def", "_get_aggregated_object", "(", "self", ",", "composite_key", ")", ":", "if", "composite_key", "not", "in", "self", ".", "aggregated_objects", ":", "self", ".", "aggregated_objects", "[", "composite_key", "]", "=", "self", ".", "_init_sink_object", "(", "c...
68.5
0.009615
def log_to_syslog(): """ Configure logging to syslog. """ # Get root logger rl = logging.getLogger() rl.setLevel('INFO') # Stderr gets critical messages (mostly config/setup issues) # only when not daemonized stderr = logging.StreamHandler(stream=sys.stderr) stderr.setLevel(l...
[ "def", "log_to_syslog", "(", ")", ":", "# Get root logger", "rl", "=", "logging", ".", "getLogger", "(", ")", "rl", ".", "setLevel", "(", "'INFO'", ")", "# Stderr gets critical messages (mostly config/setup issues)", "# only when not daemonized", "stderr", "=", "loggi...
33.045455
0.001337
def issue_post_delete(instance, *args, **kwargs): """ Used to do reindex layers/services when a issue is removed form them. """ LOGGER.debug('Re-adding layer/service to search engine index') if isinstance(instance.content_object, Service): if not settings.REGISTRY_SKIP_CELERY: in...
[ "def", "issue_post_delete", "(", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "LOGGER", ".", "debug", "(", "'Re-adding layer/service to search engine index'", ")", "if", "isinstance", "(", "instance", ".", "content_object", ",", "Service", ")...
39.933333
0.001631
def _parse_entities(self): """enrich the babelfied data with the text an the isEntity items set self._entities with the enriched data """ entities = list() for result in self._data: entity = dict() char_fragment = result.get('charFragment') st...
[ "def", "_parse_entities", "(", "self", ")", ":", "entities", "=", "list", "(", ")", "for", "result", "in", "self", ".", "_data", ":", "entity", "=", "dict", "(", ")", "char_fragment", "=", "result", ".", "get", "(", "'charFragment'", ")", "start", "=",...
39.095238
0.002378
def delete_hc(kwargs=None, call=None): ''' Permanently delete a health check. CLI Example: .. code-block:: bash salt-cloud -f delete_hc gce name=hc ''' if call != 'function': raise SaltCloudSystemExit( 'The delete_hc function must be called with -f or --function.' ...
[ "def", "delete_hc", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The delete_hc function must be called with -f or --function.'", ")", "if", "not", "kwargs", "or", "'na...
23.719298
0.00071
def check_lazy_load_wegsegment(f): ''' Decorator function to lazy load a :class:`Wegsegment`. ''' def wrapper(*args): wegsegment = args[0] if ( wegsegment._methode_id is None or wegsegment._geometrie is None or wegsegment._metadata is None ): ...
[ "def", "check_lazy_load_wegsegment", "(", "f", ")", ":", "def", "wrapper", "(", "*", "args", ")", ":", "wegsegment", "=", "args", "[", "0", "]", "if", "(", "wegsegment", ".", "_methode_id", "is", "None", "or", "wegsegment", ".", "_geometrie", "is", "None...
35.105263
0.00146
def plot_lines(x, fsamps, ax=None, downsample=100, **kwargs): """ Plot function samples as a set of line plots. Parameters ---------- x: 1D array-like x values to plot fsamps: 2D array-like set of functions to plot at each x. As returned by :func:`fgivenx.compute_sample...
[ "def", "plot_lines", "(", "x", ",", "fsamps", ",", "ax", "=", "None", ",", "downsample", "=", "100", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "matplotlib", ".", "pyplot", ".", "gca", "(", ")", "if", "downsample...
30.322581
0.001031
def image2working(self,i): """Transform images i provided into the specified working color space.""" return self.colorspace.convert(self.image_space, self.working_space, i)
[ "def", "image2working", "(", "self", ",", "i", ")", ":", "return", "self", ".", "colorspace", ".", "convert", "(", "self", ".", "image_space", ",", "self", ".", "working_space", ",", "i", ")" ]
46.2
0.012766
def circular_annular(cls, shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec, centre=(0., 0.), invert=False): """Setup a mask where unmasked pixels are within an annulus of input inner and outer arc second radii and \ centre. Parameters ---------- ...
[ "def", "circular_annular", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "inner_radius_arcsec", ",", "outer_radius_arcsec", ",", "centre", "=", "(", "0.", ",", "0.", ")", ",", "invert", "=", "False", ")", ":", "mask", "=", "mask_util", ".", "mask_circ...
53.954545
0.008278
def istransposeable(new, old): """ Check to see if a proposed tuple of axes is a valid permutation of an old set of axes. Checks length, axis repetion, and bounds. Parameters ---------- new : tuple tuple of proposed axes old : tuple tuple of old axes """ new, old =...
[ "def", "istransposeable", "(", "new", ",", "old", ")", ":", "new", ",", "old", "=", "tupleize", "(", "new", ")", ",", "tupleize", "(", "old", ")", "if", "not", "len", "(", "new", ")", "==", "len", "(", "old", ")", ":", "raise", "ValueError", "(",...
25.25
0.00159
def appendSubgraph(self, parent_name, graph_name, graph): """Utility method to associate Subgraph Instance to Root Graph Instance. This utility method is for use in constructor of child classes for associating a MuninGraph Subgraph instance with a Root Graph instance. @param ...
[ "def", "appendSubgraph", "(", "self", ",", "parent_name", ",", "graph_name", ",", "graph", ")", ":", "if", "not", "self", ".", "isMultigraph", ":", "raise", "AttributeError", "(", "\"Simple Munin Plugins cannot have subgraphs.\"", ")", "if", "self", ".", "_graphDi...
47
0.008531
def mediate_transfer( state: MediatorTransferState, possible_routes: List['RouteState'], payer_channel: NettingChannelState, channelidentifiers_to_channels: ChannelMap, nodeaddresses_to_networkstates: NodeNetworkStateMap, pseudo_random_generator: random.Random, pa...
[ "def", "mediate_transfer", "(", "state", ":", "MediatorTransferState", ",", "possible_routes", ":", "List", "[", "'RouteState'", "]", ",", "payer_channel", ":", "NettingChannelState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "nodeaddresses_to_network...
33.070423
0.000827
def get_full_url(self, parsed_url): """ Returns url path with querystring """ full_path = parsed_url.path if parsed_url.query: full_path = '%s?%s' % (full_path, parsed_url.query) return full_path
[ "def", "get_full_url", "(", "self", ",", "parsed_url", ")", ":", "full_path", "=", "parsed_url", ".", "path", "if", "parsed_url", ".", "query", ":", "full_path", "=", "'%s?%s'", "%", "(", "full_path", ",", "parsed_url", ".", "query", ")", "return", "full_p...
39
0.008368
def delete(self, *args, **kwargs): """Delete the data model.""" # Store ids in memory as relations are also deleted with the Data object. storage_ids = list(self.storages.values_list('pk', flat=True)) # pylint: disable=no-member super().delete(*args, **kwargs) Storage.objects....
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Store ids in memory as relations are also deleted with the Data object.", "storage_ids", "=", "list", "(", "self", ".", "storages", ".", "values_list", "(", "'pk'", ",", "flat", ...
44.875
0.010929
def _get_request_timeout_hints(self, name=None, timeout=None): """Get request timeout hints from device Parameters ========= name : str or None, optional Name of the request or None to get all request timeout hints. timeout : float seconds Timeout for ?re...
[ "def", "_get_request_timeout_hints", "(", "self", ",", "name", "=", "None", ",", "timeout", "=", "None", ")", ":", "timeout_hints", "=", "{", "}", "req_msg_args", "=", "[", "'request-timeout-hint'", "]", "if", "name", ":", "req_msg_args", ".", "append", "(",...
35.533333
0.001217
def load_module_from_definition( definition: dict, parent: Location) -> \ Union[ModuleGeometry, ThermocyclerGeometry]: """ Return a :py:class:`ModuleGeometry` object from a specified definition :param definition: A dict representing all required data for a module's ...
[ "def", "load_module_from_definition", "(", "definition", ":", "dict", ",", "parent", ":", "Location", ")", "->", "Union", "[", "ModuleGeometry", ",", "ThermocyclerGeometry", "]", ":", "mod_name", "=", "definition", "[", "'loadName'", "]", "if", "mod_name", "==",...
43.55
0.001124
def partitioned_repertoire(self, direction, partition): """Compute the repertoire over the partition in the given direction.""" system = self.system[direction] return system.partitioned_repertoire(direction, partition)
[ "def", "partitioned_repertoire", "(", "self", ",", "direction", ",", "partition", ")", ":", "system", "=", "self", ".", "system", "[", "direction", "]", "return", "system", ".", "partitioned_repertoire", "(", "direction", ",", "partition", ")" ]
59.75
0.008264
def create_hipersocket(self, properties): """ Create and configure a HiperSockets Adapter in this CPC. Authorization requirements: * Object-access permission to the scoping CPC. * Task permission to the "Create HiperSockets Adapter" task. Parameters: propert...
[ "def", "create_hipersocket", "(", "self", ",", "properties", ")", ":", "result", "=", "self", ".", "session", ".", "post", "(", "self", ".", "cpc", ".", "uri", "+", "'/adapters'", ",", "body", "=", "properties", ")", "# There should not be overlaps, but just i...
36.384615
0.001373
def get_jump_target_maps(code, opc): """Returns a dictionary where the key is an offset and the values are a list of instruction offsets which can get run before that instruction. This includes jump instructions as well as non-jump instructions. Therefore, the keys of the dictionary are reachible in...
[ "def", "get_jump_target_maps", "(", "code", ",", "opc", ")", ":", "offset2prev", "=", "{", "}", "prev_offset", "=", "-", "1", "for", "offset", ",", "op", ",", "arg", "in", "unpack_opargs_wordcode", "(", "code", ",", "opc", ")", ":", "if", "prev_offset", ...
40.172414
0.000838
def exercise_callback_factory(match, url_template, mc_client=None, token=None, mml_url=None): """Create a callback function to replace an exercise by fetching from a server.""" def _replace_exercises(elem): item_code = elem.get('href')[len(match):] url = url_te...
[ "def", "exercise_callback_factory", "(", "match", ",", "url_template", ",", "mc_client", "=", "None", ",", "token", "=", "None", ",", "mml_url", "=", "None", ")", ":", "def", "_replace_exercises", "(", "elem", ")", ":", "item_code", "=", "elem", ".", "get"...
40.9375
0.000373
def logs(self): """ Returns the list of :class:`~explauto.experiment.log.ExperimentLog`. .. note:: The logs will be returned as a vector if repeat was set as one in the :meth:`~explauto.experiment.pool.ExperimentPool.run` method else it will be a matrix where each rows represents the n repetitions of a...
[ "def", "logs", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_logs'", ")", ":", "raise", "ValueError", "(", "'You have to run the pool of experiments first!'", ")", "logs", "=", "self", ".", "_logs", ".", "reshape", "(", "-", "1", ")",...
51.545455
0.008666
def find_interior_point( distribution, parameters=None, cache=None, iterations=1000, retall=False, seed=None, ): """ Find interior point of the distribution where forward evaluation is guarantied to be both ``distribution.fwd(xloc) > 0`` and ``distribution...
[ "def", "find_interior_point", "(", "distribution", ",", "parameters", "=", "None", ",", "cache", "=", "None", ",", "iterations", "=", "1000", ",", "retall", "=", "False", ",", "seed", "=", "None", ",", ")", ":", "random_state", "=", "numpy", ".", "random...
32.219298
0.000264
def nativeCliqueEmbed(self, width): """Compute a maximum-sized native clique embedding in an induced subgraph of chimera with chainsize ``width+1``. If possible, returns a uniform choice among all largest cliques. INPUTS: width: width of the squares to search, also `chainle...
[ "def", "nativeCliqueEmbed", "(", "self", ",", "width", ")", ":", "def", "f", "(", "x", ")", ":", "return", "x", ".", "nativeCliqueEmbed", "(", "width", ")", "objective", "=", "self", ".", "_objective_bestscore", "return", "self", ".", "_translate", "(", ...
38.44
0.00203
def doWaitWebRequest(url, method="GET", data=None, headers={}): """ Same as doWebRequest, but with built in wait-looping """ completed = False while not completed: completed = True try: response, content = doWebRequest(url, method, data, headers) except urllib2.U...
[ "def", "doWaitWebRequest", "(", "url", ",", "method", "=", "\"GET\"", ",", "data", "=", "None", ",", "headers", "=", "{", "}", ")", ":", "completed", "=", "False", "while", "not", "completed", ":", "completed", "=", "True", "try", ":", "response", ",",...
28.714286
0.00241
def populate_records(self): """ Switches the original queryset to a ``ValuesQuerySet``, selecting values according to what each column has declared in its :py:attr:`~datatableview.columns.Column.sources` list. """ self.object_list = self.get_valuesqueryset(self.object_list) ...
[ "def", "populate_records", "(", "self", ")", ":", "self", ".", "object_list", "=", "self", ".", "get_valuesqueryset", "(", "self", ".", "object_list", ")", "super", "(", "ValuesDatatable", ",", "self", ")", ".", "populate_records", "(", ")" ]
45.5
0.010782
def state_shapes(self, batch_size: int, target_max_length: int, source_encoded_max_length: int, source_encoded_depth: int) -> List[mx.io.DataDesc]: """ Returns a list of shape descriptions given batch size, encoded sourc...
[ "def", "state_shapes", "(", "self", ",", "batch_size", ":", "int", ",", "target_max_length", ":", "int", ",", "source_encoded_max_length", ":", "int", ",", "source_encoded_depth", ":", "int", ")", "->", "List", "[", "mx", ".", "io", ".", "DataDesc", "]", "...
43.75
0.00979
def render(template=None, ostr=None, **kwargs): """Generate report from a campaign :param template: Jinja template to use, ``DEFAULT_TEMPLATE`` is used if not specified :param ostr: output file or filename. Default is standard output """ jinja_environment.filters['texscape'] = tex_escape te...
[ "def", "render", "(", "template", "=", "None", ",", "ostr", "=", "None", ",", "*", "*", "kwargs", ")", ":", "jinja_environment", ".", "filters", "[", "'texscape'", "]", "=", "tex_escape", "template", "=", "template", "or", "DEFAULT_TEMPLATE", "ostr", "=", ...
40.416667
0.002016
def delete(self, id): """ delete a time entry. """ path = partial(_path, self.adapter) path = path(id) return self._delete(path)
[ "def", "delete", "(", "self", ",", "id", ")", ":", "path", "=", "partial", "(", "_path", ",", "self", ".", "adapter", ")", "path", "=", "path", "(", "id", ")", "return", "self", ".", "_delete", "(", "path", ")" ]
31.2
0.0125
def process_generic(self, kind, context): """Transform otherwise unhandled kinds of chunks by calling an underscore prefixed function by that name.""" result = None while True: chunk = yield result if chunk is None: return result = chunk.clone(line='_' + kind + '(' + chunk.line + ')')
[ "def", "process_generic", "(", "self", ",", "kind", ",", "context", ")", ":", "result", "=", "None", "while", "True", ":", "chunk", "=", "yield", "result", "if", "chunk", "is", "None", ":", "return", "result", "=", "chunk", ".", "clone", "(", "line", ...
25.583333
0.056604
def listen_until_return(self, *temporary_handlers, timeout=0): """Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.""" start = time.time() w...
[ "def", "listen_until_return", "(", "self", ",", "*", "temporary_handlers", ",", "timeout", "=", "0", ")", ":", "start", "=", "time", ".", "time", "(", ")", "while", "timeout", "==", "0", "or", "time", ".", "time", "(", ")", "-", "start", "<", "timeou...
52.555556
0.008316
def read(self, size=None): """Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all re...
[ "def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "if", "not", "self", ".", "_is_open", ":", "raise", "IOError", "(", "'Not opened.'", ")", "if", "self", ".", "_current_offset", "<", "0", ":", "raise", "IOError", "(", "'Invalid current offs...
28.582278
0.010274
def grid_situate(self, current_idx, layout_type, subgrid_width): """ Situate the current AdjointLayoutPlot in a LayoutPlot. The LayoutPlot specifies a layout_type into which the AdjointLayoutPlot must be embedded. This enclosing layout is guaranteed to have enough cells to displa...
[ "def", "grid_situate", "(", "self", ",", "current_idx", ",", "layout_type", ",", "subgrid_width", ")", ":", "# Set the layout configuration as situated in a NdLayout", "if", "layout_type", "==", "'Single'", ":", "start", ",", "inds", "=", "current_idx", "+", "1", ",...
46.28125
0.001984
def apply(self, img, factor=0, **params): """ Args: factor (int): number of times the input will be rotated by 90 degrees. """ return np.ascontiguousarray(np.rot90(img, factor))
[ "def", "apply", "(", "self", ",", "img", ",", "factor", "=", "0", ",", "*", "*", "params", ")", ":", "return", "np", ".", "ascontiguousarray", "(", "np", ".", "rot90", "(", "img", ",", "factor", ")", ")" ]
36
0.013575
def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): """Check if line contains a redundant "override" or "final" virt-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. er...
[ "def", "CheckRedundantOverrideOrFinal", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Look for closing parenthesis nearby. We need one to confirm where", "# the declarator ends and where the virt-specifier starts to avoid", "# false positives.", "line...
39.851852
0.011797
def fmt(self, fills): """Format identifier args: fills (dict): replacements returns: str (CSS) """ name = ',$$'.join(''.join(p).strip() for p in self.parsed) name = re.sub('\?(.)\?', '%(ws)s\\1%(ws)s', name) % fills return name.replace('$$'...
[ "def", "fmt", "(", "self", ",", "fills", ")", ":", "name", "=", "',$$'", ".", "join", "(", "''", ".", "join", "(", "p", ")", ".", "strip", "(", ")", "for", "p", "in", "self", ".", "parsed", ")", "name", "=", "re", ".", "sub", "(", "'\\?(.)\\?...
34.4
0.011331
def source_cmd(args, stdin=None): """Simple cmd.exe-specific wrapper around source-foreign. returns a dict to be used as a new environment """ args = list(args) fpath = locate_binary(args[0]) args[0] = fpath if fpath else args[0] if not os.path.isfile(args[0]): raise RuntimeError("C...
[ "def", "source_cmd", "(", "args", ",", "stdin", "=", "None", ")", ":", "args", "=", "list", "(", "args", ")", "fpath", "=", "locate_binary", "(", "args", "[", "0", "]", ")", "args", "[", "0", "]", "=", "fpath", "if", "fpath", "else", "args", "[",...
37.428571
0.001241
def get(self, prefix, url, schema_version=None): """ Get the cached object """ if not self.cache_dir: return None filename = self._get_cache_file(prefix, url) try: with open(filename, 'rb') as file: item = pickle.load(file) if schema_...
[ "def", "get", "(", "self", ",", "prefix", ",", "url", ",", "schema_version", "=", "None", ")", ":", "if", "not", "self", ".", "cache_dir", ":", "return", "None", "filename", "=", "self", ".", "_get_cache_file", "(", "prefix", ",", "url", ")", "try", ...
35.173913
0.002407
def getOverlayTransformOverlayRelative(self, ulOverlayHandle): """Gets the transform if it is relative to another overlay. Returns an error if the transform is some other type.""" fn = self.function_table.getOverlayTransformOverlayRelative ulOverlayHandleParent = VROverlayHandle_t() pma...
[ "def", "getOverlayTransformOverlayRelative", "(", "self", ",", "ulOverlayHandle", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getOverlayTransformOverlayRelative", "ulOverlayHandleParent", "=", "VROverlayHandle_t", "(", ")", "pmatParentOverlayToOverlayTransform",...
69.5
0.008881
def _parse_output(self, output_xml): """Parses an output, which is generally a switch controlling a set of lights/outlets, etc.""" output = Output(self._lutron, name=output_xml.get('Name'), watts=int(output_xml.get('Wattage')), output_type=output_x...
[ "def", "_parse_output", "(", "self", ",", "output_xml", ")", ":", "output", "=", "Output", "(", "self", ".", "_lutron", ",", "name", "=", "output_xml", ".", "get", "(", "'Name'", ")", ",", "watts", "=", "int", "(", "output_xml", ".", "get", "(", "'Wa...
47.111111
0.002315
def NewFromCmy(c, m, y, alpha=1.0, wref=_DEFAULT_WREF): '''Create a new instance based on the specifed CMY values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :alpha: The ...
[ "def", "NewFromCmy", "(", "c", ",", "m", ",", "y", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "Color", ".", "CmyToRgb", "(", "c", ",", "m", ",", "y", ")", ",", "'rgb'", ",", "alpha", ",", "wre...
25.88
0.00149
def pivot(df, index: List[str], column: str, value: str, agg_function: str = 'mean'): """ Pivot the data. Reverse operation of melting --- ### Parameters *mandatory :* - `index` (*list*): names of index columns. - `column` (*str*): column name to pivot on - `value` (*str*): column nam...
[ "def", "pivot", "(", "df", ",", "index", ":", "List", "[", "str", "]", ",", "column", ":", "str", ",", "value", ":", "str", ",", "agg_function", ":", "str", "=", "'mean'", ")", ":", "if", "df", ".", "dtypes", "[", "value", "]", ".", "type", "==...
27.584906
0.001982
def post_process_fieldsets(context, fieldset): """ Removes a few fields from FeinCMS admin inlines, those being ``id``, ``DELETE`` and ``ORDER`` currently. Additionally, it ensures that dynamically added fields (i.e. ``ApplicationContent``'s ``admin_fields`` option) are shown. """ # abort if...
[ "def", "post_process_fieldsets", "(", "context", ",", "fieldset", ")", ":", "# abort if fieldset is customized", "if", "fieldset", ".", "model_admin", ".", "fieldsets", ":", "return", "fieldset", "fields_to_include", "=", "set", "(", "fieldset", ".", "form", ".", ...
32.155556
0.000671
def fetch_token(self, **kwargs): """Completes the Authorization Flow and obtains an access token. This is the final step in the OAuth 2.0 Authorization Flow. This is called after the user consents. This method calls :meth:`requests_oauthlib.OAuth2Session.fetch_token` an...
[ "def", "fetch_token", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'client_secret'", ",", "self", ".", "client_config", "[", "'client_secret'", "]", ")", "return", "self", ".", "oauth2session", ".", "fetch_token", "(", ...
42.307692
0.001778
def merge_ordered(left, right, on=None, left_on=None, right_on=None, left_by=None, right_by=None, fill_method=None, suffixes=('_x', '_y'), how='outer'): """Perform merge with optional filling/interpolation designed for ordered data like tim...
[ "def", "merge_ordered", "(", "left", ",", "right", ",", "on", "=", "None", ",", "left_on", "=", "None", ",", "right_on", "=", "None", ",", "left_by", "=", "None", ",", "right_by", "=", "None", ",", "fill_method", "=", "None", ",", "suffixes", "=", "(...
38.735294
0.000247
def add_tracked_motors(self, tracked_motors): """Add new motors to the recording""" new_mockup_motors = map(self.get_mockup_motor, tracked_motors) self.tracked_motors = list(set(self.tracked_motors + new_mockup_motors))
[ "def", "add_tracked_motors", "(", "self", ",", "tracked_motors", ")", ":", "new_mockup_motors", "=", "map", "(", "self", ".", "get_mockup_motor", ",", "tracked_motors", ")", "self", ".", "tracked_motors", "=", "list", "(", "set", "(", "self", ".", "tracked_mot...
60
0.012346
def get_csv_import_info(self, path): """Launches the csv dialog and returns csv_info csv_info is a tuple of dialect, has_header, digest_types Parameters ---------- path: String \tFile path of csv file """ csvfilename = os.path.split(path)[1] ...
[ "def", "get_csv_import_info", "(", "self", ",", "path", ")", ":", "csvfilename", "=", "os", ".", "path", ".", "split", "(", "path", ")", "[", "1", "]", "try", ":", "filterdlg", "=", "CsvImportDialog", "(", "self", ".", "main_window", ",", "csvfilepath", ...
26.325581
0.001704
def eval_Rf(self, Vf): """Evaluate smooth term in Vf.""" return sl.inner(self.Df, Vf, axis=self.cri.axisM) - self.Sf
[ "def", "eval_Rf", "(", "self", ",", "Vf", ")", ":", "return", "sl", ".", "inner", "(", "self", ".", "Df", ",", "Vf", ",", "axis", "=", "self", ".", "cri", ".", "axisM", ")", "-", "self", ".", "Sf" ]
32.5
0.015038
def parse_superbox(self, fptr): """Parse a superbox (box consisting of nothing but other boxes. Parameters ---------- fptr : file Open file object. Returns ------- list List of top-level boxes in the JPEG 2000 file. """ s...
[ "def", "parse_superbox", "(", "self", ",", "fptr", ")", ":", "superbox", "=", "[", "]", "start", "=", "fptr", ".", "tell", "(", ")", "while", "True", ":", "# Are we at the end of the superbox?", "if", "start", ">=", "self", ".", "offset", "+", "self", "....
34.565217
0.000815
async def spawn(self, coro, *args): '''Create a new task that’s part of the group. Returns a Task instance. ''' task = await spawn(coro, *args, report_crash=False) self._add_task(task) return task
[ "async", "def", "spawn", "(", "self", ",", "coro", ",", "*", "args", ")", ":", "task", "=", "await", "spawn", "(", "coro", ",", "*", "args", ",", "report_crash", "=", "False", ")", "self", ".", "_add_task", "(", "task", ")", "return", "task" ]
34
0.008197
def autodiscover(site=None): """ Auto-discover INSTALLED_APPS nexus.py modules and fail silently when not present. This forces an import on them to register any api bits they may want. Specifying ``site`` will register all auto discovered modules with the new site. """ # Bail out if autodis...
[ "def", "autodiscover", "(", "site", "=", "None", ")", ":", "# Bail out if autodiscover didn't finish loading from a previous call so", "# that we avoid running autodiscover again when the URLconf is loaded by", "# the exception handler to resolve the handler500 view. This prevents an", "# adm...
38.262295
0.000835
def getTzid(tzid, smart=True): """Return the tzid if it exists, or None.""" tz = __tzidMap.get(toUnicode(tzid), None) if smart and tzid and not tz: try: from pytz import timezone, UnknownTimeZoneError try: tz = timezone(tzid) registerTzid(toUni...
[ "def", "getTzid", "(", "tzid", ",", "smart", "=", "True", ")", ":", "tz", "=", "__tzidMap", ".", "get", "(", "toUnicode", "(", "tzid", ")", ",", "None", ")", "if", "smart", "and", "tzid", "and", "not", "tz", ":", "try", ":", "from", "pytz", "impo...
31.642857
0.002193
def invoke_controller(self, controller, args, kwargs, state): ''' The main request handler for Pecan applications. ''' cfg = _cfg(controller) content_types = cfg.get('content_types', {}) req = state.request resp = state.response pecan_state = req.pecan ...
[ "def", "invoke_controller", "(", "self", ",", "controller", ",", "args", ",", "kwargs", ",", "state", ")", ":", "cfg", "=", "_cfg", "(", "controller", ")", "content_types", "=", "cfg", ".", "get", "(", "'content_types'", ",", "{", "}", ")", "req", "=",...
36.173913
0.00078
def parsePermission3Char(permission): """ 'rwx' 形式のアクセス権限文字列 permission を8進数形式に変換する :return: :rtype: int """ if len(permission) != 3: raise ValueError(permission) permission_int = 0 if permission[0] == "r": permission_int += 4 if permission[1] == "w": permi...
[ "def", "parsePermission3Char", "(", "permission", ")", ":", "if", "len", "(", "permission", ")", "!=", "3", ":", "raise", "ValueError", "(", "permission", ")", "permission_int", "=", "0", "if", "permission", "[", "0", "]", "==", "\"r\"", ":", "permission_i...
19.95
0.002392
def getAllSavedQueries(self, projectarea_id=None, projectarea_name=None, creator=None, saved_query_name=None): """Get all saved queries created by somebody (optional) in a certain project area (optional, either `projectarea_id` or `projectarea_name` is needed if specif...
[ "def", "getAllSavedQueries", "(", "self", ",", "projectarea_id", "=", "None", ",", "projectarea_name", "=", "None", ",", "creator", "=", "None", ",", "saved_query_name", "=", "None", ")", ":", "pa_id", "=", "(", "self", ".", "rtc_obj", ".", "_pre_get_resourc...
44.254545
0.001206
def is_mouse_over(self, event): """ Check whether a MouseEvent is over thus scroll bar. :param event: The MouseEvent to check. :returns: True if the mouse event is over the scroll bar. """ return event.x == self._x and self._y <= event.y < self._y + self._height
[ "def", "is_mouse_over", "(", "self", ",", "event", ")", ":", "return", "event", ".", "x", "==", "self", ".", "_x", "and", "self", ".", "_y", "<=", "event", ".", "y", "<", "self", ".", "_y", "+", "self", ".", "_height" ]
33.777778
0.009615
def updateframe(t, raw, wavelen, cam, ax, fg): showcb = False ttxt = f'Cam {cam.name}: ' if raw.ndim == 3: frame = raw[t, ...] elif raw.ndim == 2: frame = raw elif raw.ndim == 1: # GeoData frame = raw.reshape((sqrt(raw.size), -1)) else: raise ValueError('ndim==...
[ "def", "updateframe", "(", "t", ",", "raw", ",", "wavelen", ",", "cam", ",", "ax", ",", "fg", ")", ":", "showcb", "=", "False", "ttxt", "=", "f'Cam {cam.name}: '", "if", "raw", ".", "ndim", "==", "3", ":", "frame", "=", "raw", "[", "t", ",", "......
34.268817
0.002135
def temporal_efficiency(tnet=None, paths=None, calc='global'): r""" Returns temporal efficiency estimate. BU networks only. Parameters ---------- Input should be *either* tnet or paths. data : array or dict Temporal network input (graphlet or contact). nettype: 'bu', 'bd'. paths ...
[ "def", "temporal_efficiency", "(", "tnet", "=", "None", ",", "paths", "=", "None", ",", "calc", "=", "'global'", ")", ":", "if", "tnet", "is", "not", "None", "and", "paths", "is", "not", "None", ":", "raise", "ValueError", "(", "'Only network or path input...
32.365385
0.00173
def hook(name): ''' Decorator used to tag a method that should be used as a hook for the specified `name` hook type. ''' def hookTarget(wrapped): if not hasattr(wrapped, '__hook__'): wrapped.__hook__ = [name] else: wrapped.__hook__.append(name) return wrapped return hookTarget
[ "def", "hook", "(", "name", ")", ":", "def", "hookTarget", "(", "wrapped", ")", ":", "if", "not", "hasattr", "(", "wrapped", ",", "'__hook__'", ")", ":", "wrapped", ".", "__hook__", "=", "[", "name", "]", "else", ":", "wrapped", ".", "__hook__", ".",...
25.166667
0.019169
def get_python_datastructure_sizes(): """ References: http://stackoverflow.com/questions/1331471/in-memory-size-of-python-stucture CommandLine: python -m utool.util_resources --test-get_python_datastructure_sizes Example: >>> # ENABLE_DOCTEST >>> from utool.util_resourc...
[ "def", "get_python_datastructure_sizes", "(", ")", ":", "import", "sys", "import", "decimal", "import", "six", "empty_types", "=", "{", "'int'", ":", "0", ",", "'float'", ":", "0.0", ",", "'dict'", ":", "dict", "(", ")", ",", "'set'", ":", "set", "(", ...
27.8
0.010924
def two_qubit_matrix_to_operations(q0: ops.Qid, q1: ops.Qid, mat: np.ndarray, allow_partial_czs: bool, atol: float = 1e-8, clean_operations: bool...
[ "def", "two_qubit_matrix_to_operations", "(", "q0", ":", "ops", ".", "Qid", ",", "q1", ":", "ops", ".", "Qid", ",", "mat", ":", "np", ".", "ndarray", ",", "allow_partial_czs", ":", "bool", ",", "atol", ":", "float", "=", "1e-8", ",", "clean_operations", ...
42.793103
0.000788
def generate_synthObs(self, bases_wave, bases_flux, basesCoeff, Av_star, z_star, sigma_star, resample_range = None, resample_int = 1): '''basesWave: Bases wavelength must be at rest''' nbases = basesCoeff.shape[0] bases_wave_resam = arange(int(resample_range[0]),...
[ "def", "generate_synthObs", "(", "self", ",", "bases_wave", ",", "bases_flux", ",", "basesCoeff", ",", "Av_star", ",", "z_star", ",", "sigma_star", ",", "resample_range", "=", "None", ",", "resample_int", "=", "1", ")", ":", "nbases", "=", "basesCoeff", ".",...
54.456522
0.025882
async def refresh_token(loader, client_configuration=None, interval=60): """Refresh token if necessary, updates the token in client configurarion :param loader: KubeConfigLoader returned by load_kube_config :param client_configuration: The kubernetes.client.Configuration to set configs to. ...
[ "async", "def", "refresh_token", "(", "loader", ",", "client_configuration", "=", "None", ",", "interval", "=", "60", ")", ":", "if", "loader", ".", "provider", "!=", "'gcp'", ":", "return", "if", "client_configuration", "is", "None", ":", "client_configuratio...
34.631579
0.001479
def get_local_client( c_path=os.path.join(syspaths.CONFIG_DIR, 'master'), mopts=None, skip_perm_errors=False, io_loop=None, auto_reconnect=False): ''' .. versionadded:: 2014.7.0 Read in the config and return the correct LocalClient object based on the configured ...
[ "def", "get_local_client", "(", "c_path", "=", "os", ".", "path", ".", "join", "(", "syspaths", ".", "CONFIG_DIR", ",", "'master'", ")", ",", "mopts", "=", "None", ",", "skip_perm_errors", "=", "False", ",", "io_loop", "=", "None", ",", "auto_reconnect", ...
31.967742
0.000979
def count_elements_in_dataset(ds, batch_size=1*1024, parallel_batch=8): """Count and return all the elements in the given dataset. Debugging function. The elements in a dataset cannot be counted without enumerating all of them. By counting in batch and in parallel, this method allows rapid traversal ...
[ "def", "count_elements_in_dataset", "(", "ds", ",", "batch_size", "=", "1", "*", "1024", ",", "parallel_batch", "=", "8", ")", ":", "with", "tf", ".", "Session", "(", ")", "as", "sess", ":", "dsc", "=", "ds", ".", "apply", "(", "tf", ".", "contrib", ...
40.823529
0.000704
def num_valid_substrings(self, path_to_words): """ For each string, find the count of all possible substrings with 2 characters or more that are contained in the line-separated text file whose path is given. :param str path_to_words: Path to file that contains a line-separated list of s...
[ "def", "num_valid_substrings", "(", "self", ",", "path_to_words", ")", ":", "assert_is_type", "(", "path_to_words", ",", "str", ")", "fr", "=", "H2OFrame", ".", "_expr", "(", "expr", "=", "ExprNode", "(", "\"num_valid_substrings\"", ",", "self", ",", "path_to_...
51.923077
0.008734
def load(cls, cache_file, backend=None): """Instantiate AsyncResult from dumped `cache_file`. This is the inverse of :meth:`dump`. Parameters ---------- cache_file: str Name of file from which the run should be read. backend: clusterjob.backen...
[ "def", "load", "(", "cls", ",", "cache_file", ",", "backend", "=", "None", ")", ":", "with", "open", "(", "cache_file", ",", "'rb'", ")", "as", "pickle_fh", ":", "(", "remote", ",", "backend_name", ",", "max_sleep_interval", ",", "job_id", ",", "status",...
38.884615
0.001931
def parse_args(args): ''' Parse an argument string http://stackoverflow.com/questions/18160078/ how-do-you-write-tests-for-the-argparse-portion-of-a-python-module ''' parser = argparse.ArgumentParser() parser.add_argument('config_file', nargs='?', help='Configura...
[ "def", "parse_args", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'config_file'", ",", "nargs", "=", "'?'", ",", "help", "=", "'Configuration yaml file'", ",", "default", "=", "None",...
38.833333
0.001397
def addReferences(self, reference, service_uids): """ Add reference analyses to reference """ # TODO Workflow - Analyses. Assignment of refanalysis to Instrument addedanalyses = [] wf = getToolByName(self, 'portal_workflow') bsc = getToolByName(self, 'bika_setup_catalog')...
[ "def", "addReferences", "(", "self", ",", "reference", ",", "service_uids", ")", ":", "# TODO Workflow - Analyses. Assignment of refanalysis to Instrument", "addedanalyses", "=", "[", "]", "wf", "=", "getToolByName", "(", "self", ",", "'portal_workflow'", ")", "bsc", ...
43.095238
0.002161
def _ping(self, peerid, callid): """ Called from remote to ask if a call made to here is still in progress. """ if not (peerid, callid) in self._remote_to_local: logger.warn("No remote call %s from %s. Might just be unfoutunate timing." % (callid, peerid))
[ "def", "_ping", "(", "self", ",", "peerid", ",", "callid", ")", ":", "if", "not", "(", "peerid", ",", "callid", ")", "in", "self", ".", "_remote_to_local", ":", "logger", ".", "warn", "(", "\"No remote call %s from %s. Might just be unfoutunate timing.\"", "%", ...
49.166667
0.01
def area(poly): """ calculate the area of polygon Keyword arguments: poly -- polygon geojson object return polygon area """ poly_area = 0 # TODO: polygon holes at coordinates[1] points = poly['coordinates'][0] j = len(points) - 1 count = len(points) for i in range(0, c...
[ "def", "area", "(", "poly", ")", ":", "poly_area", "=", "0", "# TODO: polygon holes at coordinates[1]", "points", "=", "poly", "[", "'coordinates'", "]", "[", "0", "]", "j", "=", "len", "(", "points", ")", "-", "1", "count", "=", "len", "(", "points", ...
19.777778
0.001786
def resource_associate_permission(self, token, id, name, scopes, **kwargs): """ Associates a permission with a Resource. https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api :param str token: client access token :param str...
[ "def", "resource_associate_permission", "(", "self", ",", "token", ",", "id", ",", "name", ",", "scopes", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_realm", ".", "client", ".", "post", "(", "'{}/{}'", ".", "format", "(", "self", ".", ...
39.545455
0.002245
def from_dict(self, d): """ Create a Task from a dictionary. The change is in inplace. :argument: python dictionary :return: None """ if 'uid' in d: if d['uid']: self._uid = d['uid'] if 'name' in d: if d['name']: ...
[ "def", "from_dict", "(", "self", ",", "d", ")", ":", "if", "'uid'", "in", "d", ":", "if", "d", "[", "'uid'", "]", ":", "self", ".", "_uid", "=", "d", "[", "'uid'", "]", "if", "'name'", "in", "d", ":", "if", "d", "[", "'name'", "]", ":", "se...
38.338798
0.001806
def clone_data( self, source ): """Clone data from another Block. source Block instance to copy from. """ klass = self.__class__ assert isinstance( source, klass ) for name in klass._fields: self._field_data[name] = getattr( source, name )
[ "def", "clone_data", "(", "self", ",", "source", ")", ":", "klass", "=", "self", ".", "__class__", "assert", "isinstance", "(", "source", ",", "klass", ")", "for", "name", "in", "klass", ".", "_fields", ":", "self", ".", "_field_data", "[", "name", "]"...
27.545455
0.025559