text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _openResources(self): """ Uses numpy.load to open the underlying file """ arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE) check_is_an_array(arr) self._array = arr
[ "def", "_openResources", "(", "self", ")", ":", "arr", "=", "np", ".", "load", "(", "self", ".", "_fileName", ",", "allow_pickle", "=", "ALLOW_PICKLE", ")", "check_is_an_array", "(", "arr", ")", "self", ".", "_array", "=", "arr" ]
35
0.009302
def check_call_arguments(to_call, kwargs): """ Check the call signature against a dictionary of proposed arguments, raising an informative exception in the case of mismatch. Parameters ---------- to_call : class or callable Function or class to examine (in the case of classes, the ...
[ "def", "check_call_arguments", "(", "to_call", ",", "kwargs", ")", ":", "if", "'self'", "in", "kwargs", ".", "keys", "(", ")", ":", "raise", "TypeError", "(", "\"Your dictionary includes an entry for 'self', \"", "\"which is just asking for trouble\"", ")", "orig_to_cal...
40.901408
0.002017
def extrap1d(Z,mask): """ EXTRAP1D : Extrapolate values from a 1D vector at its beginning and end using reversal of this array @note : gaps in vector Z should be filled first as values from the vector are replicated out of edges @note : if isinstance(Z,np.ma.masked_array) : mask = Z.mask ...
[ "def", "extrap1d", "(", "Z", ",", "mask", ")", ":", "Zout", "=", "Z", ".", "copy", "(", ")", "N", "=", "len", "(", "Zout", ")", "ind", "=", "np", ".", "arange", "(", "N", ")", "xout", "=", "ind", "[", "mask", "]", "hist", "=", "(", "~", "...
32.259259
0.0301
def draw_line(start, size, slope): """ Draws a line from the starting point with the given slope, until the line goes out of the given bounds. :param start: The starting point (x, y) for the line :param size: The size of the image as (width, height). This determined the bounds for the image. :param ...
[ "def", "draw_line", "(", "start", ",", "size", ",", "slope", ")", ":", "error", "=", "-", "1.0", "if", "abs", "(", "slope", ")", ">", "1", ":", "slope", "=", "1", "/", "slope", "switch_xy", "=", "True", "else", ":", "switch_xy", "=", "False", "sl...
37.178571
0.004682
def getBucketValues(self): """ See the function description in base.py """ if self._bucketValues is None: numBuckets = len(self.encoder.getBucketValues()) self._bucketValues = [] for bucketIndex in range(numBuckets): self._bucketValues.append(self.getBucketInfo([bucketIndex])[0].value...
[ "def", "getBucketValues", "(", "self", ")", ":", "if", "self", ".", "_bucketValues", "is", "None", ":", "numBuckets", "=", "len", "(", "self", ".", "encoder", ".", "getBucketValues", "(", ")", ")", "self", ".", "_bucketValues", "=", "[", "]", "for", "b...
34.3
0.011364
def SetSourceInformation( self, source_path, source_type, artifact_filters=None, filter_file=None): """Sets the source information. Args: source_path (str): path of the source. source_type (str): source type. artifact_filters (Optional[list[str]]): names of artifact definitions to ...
[ "def", "SetSourceInformation", "(", "self", ",", "source_path", ",", "source_type", ",", "artifact_filters", "=", "None", ",", "filter_file", "=", "None", ")", ":", "self", ".", "_artifact_filters", "=", "artifact_filters", "self", ".", "_filter_file", "=", "fil...
38.066667
0.001709
def _database_exists(self): """ Check if the database exists. """ con = psycopg2.connect(host=self.host, database="postgres", user=self.user, password=self.password, port=self.port) query_check = "select datname from pg_catalog.pg_database" query_check += " w...
[ "def", "_database_exists", "(", "self", ")", ":", "con", "=", "psycopg2", ".", "connect", "(", "host", "=", "self", ".", "host", ",", "database", "=", "\"postgres\"", ",", "user", "=", "self", ".", "user", ",", "password", "=", "self", ".", "password",...
33.8
0.005758
def register(email): ''' Register a new user account CLI Example: .. code-block:: bash salt-run venafi.register email@example.com ''' data = __utils__['http.query']( '{0}/useraccounts'.format(_base_url()), method='POST', data=salt.utils.json.dumps({ ...
[ "def", "register", "(", "email", ")", ":", "data", "=", "__utils__", "[", "'http.query'", "]", "(", "'{0}/useraccounts'", ".", "format", "(", "_base_url", "(", ")", ")", ",", "method", "=", "'POST'", ",", "data", "=", "salt", ".", "utils", ".", "json",...
25.833333
0.002488
def clicks(annotation, sr=22050, length=None, **kwargs): '''Sonify events with clicks. This uses mir_eval.sonify.clicks, and is appropriate for instantaneous events such as beats or segment boundaries. ''' interval, _ = annotation.to_interval_values() return filter_kwargs(mir_eval.sonify.clic...
[ "def", "clicks", "(", "annotation", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "*", "*", "kwargs", ")", ":", "interval", ",", "_", "=", "annotation", ".", "to_interval_values", "(", ")", "return", "filter_kwargs", "(", "mir_eval", ".", "...
35.090909
0.002525
def set(self, value): """ Set a new value for this thing. value -- value to set """ if self.value_forwarder is not None: self.value_forwarder(value) self.notify_of_external_update(value)
[ "def", "set", "(", "self", ",", "value", ")", ":", "if", "self", ".", "value_forwarder", "is", "not", "None", ":", "self", ".", "value_forwarder", "(", "value", ")", "self", ".", "notify_of_external_update", "(", "value", ")" ]
23.9
0.008065
def maximum_flow(graph, source, sink, caps = None): """ Find a maximum flow and minimum cut of a directed graph by the Edmonds-Karp algorithm. @type graph: digraph @param graph: Graph @type source: node @param source: Source of the flow @type sink: node @param sink: Sink of the flow ...
[ "def", "maximum_flow", "(", "graph", ",", "source", ",", "sink", ",", "caps", "=", "None", ")", ":", "#handle optional argument, if weights are available, use them, if not, assume one", "if", "caps", "==", "None", ":", "caps", "=", "{", "}", "for", "edge", "in", ...
31.565217
0.017028
def _calibrate_quantized_sym(qsym, th_dict): """Given a dictionary containing the thresholds for quantizing the layers, set the thresholds into the quantized symbol as the params of requantize operators. """ if th_dict is None or len(th_dict) == 0: return qsym num_layer_outputs = len(th_dict...
[ "def", "_calibrate_quantized_sym", "(", "qsym", ",", "th_dict", ")", ":", "if", "th_dict", "is", "None", "or", "len", "(", "th_dict", ")", "==", "0", ":", "return", "qsym", "num_layer_outputs", "=", "len", "(", "th_dict", ")", "layer_output_names", "=", "[...
45.956522
0.006487
def _empty_cache(self, termlist=None): """Empty the cache associated with each `Term` instance. This method is called when merging Ontologies or including new terms in the Ontology to make sure the cache of each term is cleaned and avoid returning wrong memoized values (such as ...
[ "def", "_empty_cache", "(", "self", ",", "termlist", "=", "None", ")", ":", "if", "termlist", "is", "None", ":", "for", "term", "in", "six", ".", "itervalues", "(", "self", ".", "terms", ")", ":", "term", ".", "_empty_cache", "(", ")", "else", ":", ...
40.388889
0.002688
def last_versions_with_age(self, col_name='age'): ''' Leaves only the latest version for each object. Adds a new column which represents age. The age is computed by subtracting _start of the oldest version from one of these possibilities:: # psuedo-code i...
[ "def", "last_versions_with_age", "(", "self", ",", "col_name", "=", "'age'", ")", ":", "min_start_map", "=", "{", "}", "max_start_map", "=", "{", "}", "max_start_ser_map", "=", "{", "}", "cols", "=", "self", ".", "columns", ".", "tolist", "(", ")", "i_oi...
34.320755
0.001069
def artifact_quality(self, artifact_quality): """ Sets the artifact_quality of this ArtifactRest. :param artifact_quality: The artifact_quality of this ArtifactRest. :type: str """ allowed_values = ["NEW", "VERIFIED", "TESTED", "DEPRECATED", "BLACKLISTED", "DELETED", "TE...
[ "def", "artifact_quality", "(", "self", ",", "artifact_quality", ")", ":", "allowed_values", "=", "[", "\"NEW\"", ",", "\"VERIFIED\"", ",", "\"TESTED\"", ",", "\"DEPRECATED\"", ",", "\"BLACKLISTED\"", ",", "\"DELETED\"", ",", "\"TEMPORARY\"", "]", "if", "artifact_...
40
0.006515
def calculate_file_md5(filepath, blocksize=2 ** 20): """Calculate an MD5 hash for a file.""" checksum = hashlib.md5() with click.open_file(filepath, "rb") as f: def update_chunk(): """Add chunk to checksum.""" buf = f.read(blocksize) if buf: chec...
[ "def", "calculate_file_md5", "(", "filepath", ",", "blocksize", "=", "2", "**", "20", ")", ":", "checksum", "=", "hashlib", ".", "md5", "(", ")", "with", "click", ".", "open_file", "(", "filepath", ",", "\"rb\"", ")", "as", "f", ":", "def", "update_chu...
25.294118
0.002242
def run(self, fetch_image=True, **kwargs): """ Create the container and start it. Similar to ``docker run``. :param fetch_image: Whether to try pull the image if it's not found. The behaviour here is similar to ``docker run`` and this parameter defaults to ``...
[ "def", "run", "(", "self", ",", "fetch_image", "=", "True", ",", "*", "*", "kwargs", ")", ":", "self", ".", "create", "(", "fetch_image", "=", "fetch_image", ",", "*", "*", "kwargs", ")", "self", ".", "start", "(", ")" ]
39.5
0.004124
def log(obj1, obj2, sym, cname=None, aname=None, result=None): # pylint: disable=R0913 """Log the objects being compared and the result. When no result object is specified, subsequence calls will have an increased indentation level. The indentation level is decreased once a result obje...
[ "def", "log", "(", "obj1", ",", "obj2", ",", "sym", ",", "cname", "=", "None", ",", "aname", "=", "None", ",", "result", "=", "None", ")", ":", "# pylint: disable=R0913", "fmt", "=", "\"{o1} {sym} {o2} : {r}\"", "if", "cname", "or", "aname", ":", "assert...
37.032258
0.002547
def iso_register(iso_code): """ Registers Calendar class as country or region in IsoRegistry. Registered country must set class variables ``iso`` using this decorator. >>> from workalendar.core import Calendar >>> @iso_register('MC-MR') >>> class MyRegion(Calendar): >>> 'My Region' ...
[ "def", "iso_register", "(", "iso_code", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "registry", ".", "register", "(", "iso_code", ",", "cls", ")", "return", "cls", "return", "wrapper" ]
27.368421
0.001859
def _build_common_attributes(self, operation_policy_name=None): ''' Build a list of common attributes that are shared across symmetric as well as asymmetric objects ''' common_attributes = [] if operation_policy_name: common_attributes.append( ...
[ "def", "_build_common_attributes", "(", "self", ",", "operation_policy_name", "=", "None", ")", ":", "common_attributes", "=", "[", "]", "if", "operation_policy_name", ":", "common_attributes", ".", "append", "(", "self", ".", "attribute_factory", ".", "create_attri...
32.4375
0.003745
def copy(self, new_name=None): """ Returns a deep copy of the system Parameters ----------- new_name: str, optional Set a new meta name parameter. Default: <old_name>_copy """ _tmp = copy.deepcopy(self) if not new_name: new_na...
[ "def", "copy", "(", "self", ",", "new_name", "=", "None", ")", ":", "_tmp", "=", "copy", ".", "deepcopy", "(", "self", ")", "if", "not", "new_name", ":", "new_name", "=", "self", ".", "name", "+", "'_copy'", "if", "str", "(", "type", "(", "self", ...
32.65
0.002976
def _remote_download(self, url): """To download the remote plugin package, there are four methods of setting filename according to priority, each of which stops setting when a qualified filename is obtained, and an exception is triggered when a qualified valid filename is ultimately ...
[ "def", "_remote_download", "(", "self", ",", "url", ")", ":", "#: Try to set filename in advance based on the previous two steps\r", "if", "self", ".", "__isValidUrl", "(", "url", ")", ":", "filename", "=", "self", ".", "__getFilename", "(", "url", ",", "scene", "...
48.418605
0.002825
def notification_redirect(request, ctx): """ Helper to handle HTTP response after an action is performed on notification :param request: HTTP request context of the notification :param ctx: context to be returned when a AJAX call is made. :returns: Either JSON for AJAX or redirects to the calcula...
[ "def", "notification_redirect", "(", "request", ",", "ctx", ")", ":", "if", "request", ".", "is_ajax", "(", ")", ":", "return", "JsonResponse", "(", "ctx", ")", "else", ":", "next_page", "=", "request", ".", "POST", ".", "get", "(", "'next'", ",", "rev...
36.1
0.00135
def error_string(mqtt_errno): """Return the error string associated with an mqtt error number.""" if mqtt_errno == MQTT_ERR_SUCCESS: return "No error." elif mqtt_errno == MQTT_ERR_NOMEM: return "Out of memory." elif mqtt_errno == MQTT_ERR_PROTOCOL: return "A network protocol erro...
[ "def", "error_string", "(", "mqtt_errno", ")", ":", "if", "mqtt_errno", "==", "MQTT_ERR_SUCCESS", ":", "return", "\"No error.\"", "elif", "mqtt_errno", "==", "MQTT_ERR_NOMEM", ":", "return", "\"Out of memory.\"", "elif", "mqtt_errno", "==", "MQTT_ERR_PROTOCOL", ":", ...
41.294118
0.001392
def anopheles(self): """ :rtype: Anopheles """ list_of_anopheles = [] desc = self.et.find("description") if desc is not None: for anopheles in desc.findall("anopheles"): list_of_anopheles.append(Anopheles(anopheles)) return list_of_an...
[ "def", "anopheles", "(", "self", ")", ":", "list_of_anopheles", "=", "[", "]", "desc", "=", "self", ".", "et", ".", "find", "(", "\"description\"", ")", "if", "desc", "is", "not", "None", ":", "for", "anopheles", "in", "desc", ".", "findall", "(", "\...
26.333333
0.006116
def cleanup(): """Delete standard installation directories.""" for install_dir in linters.INSTALL_DIRS: try: shutil.rmtree(install_dir, ignore_errors=True) except Exception: print( "{0}\nFailed to delete {1}".format( ...
[ "def", "cleanup", "(", ")", ":", "for", "install_dir", "in", "linters", ".", "INSTALL_DIRS", ":", "try", ":", "shutil", ".", "rmtree", "(", "install_dir", ",", "ignore_errors", "=", "True", ")", "except", "Exception", ":", "print", "(", "\"{0}\\nFailed to de...
36
0.004515
def coerce(self, value): """Coerce a single value according to this parameter's settings. @param value: A L{str}, or L{None}. If L{None} is passed - meaning no value is avalable at all, not even the empty string - and this parameter is optional, L{self.default} will be returned....
[ "def", "coerce", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "if", "self", ".", "optional", ":", "return", "self", ".", "default", "else", ":", "value", "=", "\"\"", "if", "value", "==", "\"\"", ":", "if", "not", "self", ...
38.965517
0.001727
def load_rank(self, region, season=-1): """|coro| Loads the players rank for this region and season Parameters ---------- region : str the name of the region you want to get the rank for season : Optional[int] the season you want to get the rank f...
[ "def", "load_rank", "(", "self", ",", "region", ",", "season", "=", "-", "1", ")", ":", "data", "=", "yield", "from", "self", ".", "auth", ".", "get", "(", "\"https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/r6karma/players?board_id=pvp_ranked&profile_ids=%s...
44.26087
0.004808
def to_df(self, variables=None, format='wide', sparse=True, sampling_rate=None, include_sparse=True, include_dense=True, **kwargs): ''' Merge columns into a single pandas DataFrame. Args: variables (list): Optional list of variable names to retain; ...
[ "def", "to_df", "(", "self", ",", "variables", "=", "None", ",", "format", "=", "'wide'", ",", "sparse", "=", "True", ",", "sampling_rate", "=", "None", ",", "include_sparse", "=", "True", ",", "include_dense", "=", "True", ",", "*", "*", "kwargs", ")"...
46.741935
0.001352
def fs_obj_remove_array(self, path): """Removes multiple file system objects (files, directories, symlinks, etc) in the guest. Use with caution. This method is not implemented yet and will return E_NOTIMPL. This method will remove symbolic links in the final path ...
[ "def", "fs_obj_remove_array", "(", "self", ",", "path", ")", ":", "if", "not", "isinstance", "(", "path", ",", "list", ")", ":", "raise", "TypeError", "(", "\"path can only be an instance of type list\"", ")", "for", "a", "in", "path", "[", ":", "10", "]", ...
38.275862
0.00703
def set_index_edited(self, index, edited): """Set whether the conf was edited or not. Edited files will be displayed with a \'*\' :param index: the index that was edited :type index: QModelIndex :param edited: if the file was edited, set edited to True, else False :type...
[ "def", "set_index_edited", "(", "self", ",", "index", ",", "edited", ")", ":", "self", ".", "__edited", "[", "index", ".", "row", "(", ")", "]", "=", "edited", "self", ".", "dataChanged", ".", "emit", "(", "index", ",", "index", ")" ]
32.333333
0.004008
def delete_resource(resource_id): """Delete a resource.""" resource_obj = app.db.resource(resource_id) try: os.remove(resource_obj.path) except OSError as err: app.logger.debug(err.message) app.db.delete_resource(resource_id) return redirect(request.referrer)
[ "def", "delete_resource", "(", "resource_id", ")", ":", "resource_obj", "=", "app", ".", "db", ".", "resource", "(", "resource_id", ")", "try", ":", "os", ".", "remove", "(", "resource_obj", ".", "path", ")", "except", "OSError", "as", "err", ":", "app",...
29.1
0.003333
def _set_summary(self, v, load=False): """ Setter method for summary, mapped from YANG variable /mpls_state/summary (container) If this variable is read-only (config: false) in the source YANG file, then _set_summary is considered as a private method. Backends looking to populate this variable shoul...
[ "def", "_set_summary", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base",...
69.833333
0.005886
def enable_busy_cursor(self): """Set the hourglass enabled.""" QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor) )
[ "def", "enable_busy_cursor", "(", "self", ")", ":", "QgsApplication", ".", "instance", "(", ")", ".", "setOverrideCursor", "(", "QtGui", ".", "QCursor", "(", "QtCore", ".", "Qt", ".", "WaitCursor", ")", ")" ]
35.4
0.01105
def reconnect(self): """ Invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ # This is the old connection IOLoop instance, stop its ioloop self._connection.ioloop.stop() if not self._closing: # Create a ne...
[ "def", "reconnect", "(", "self", ")", ":", "# This is the old connection IOLoop instance, stop its ioloop", "self", ".", "_connection", ".", "ioloop", ".", "stop", "(", ")", "if", "not", "self", ".", "_closing", ":", "# Create a new connection", "self", ".", "_conne...
37
0.004057
def adjust_ip (self, ip=None): """Called to explicitely fixup an associated IP header The function adjusts the IP header based on conformance rules and the group address encoded in the IGMP message. The rules are: 1. Send General Group Query to 224.0.0.1 (all systems) 2. Send Leave Group to 22...
[ "def", "adjust_ip", "(", "self", ",", "ip", "=", "None", ")", ":", "if", "ip", "!=", "None", "and", "ip", ".", "haslayer", "(", "IP", ")", ":", "if", "(", "self", ".", "type", "==", "0x11", ")", ":", "if", "(", "self", ".", "gaddr", "==", "\"...
40.525
0.016265
def take_ordereds_out_of_turn(self) -> tuple: """ Takes all Ordered messages from outbox out of turn """ for replica in self._replicas.values(): yield replica.instId, replica._remove_ordered_from_queue()
[ "def", "take_ordereds_out_of_turn", "(", "self", ")", "->", "tuple", ":", "for", "replica", "in", "self", ".", "_replicas", ".", "values", "(", ")", ":", "yield", "replica", ".", "instId", ",", "replica", ".", "_remove_ordered_from_queue", "(", ")" ]
40.333333
0.008097
def get_form(self, **kwargs): """Returns the form for registering or inviting a user""" if not hasattr(self, "form_class"): raise AttributeError(_("You must define a form_class")) return self.form_class(**kwargs)
[ "def", "get_form", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"form_class\"", ")", ":", "raise", "AttributeError", "(", "_", "(", "\"You must define a form_class\"", ")", ")", "return", "self", ".", "form_cl...
48.8
0.008065
def get_attrname_by_colname(instance, name): """ Get value from SQLAlchemy instance by column name :Parameters: - `instance`: SQLAlchemy model instance. - `name`: Column name :Examples: >>> from sqlalchemy import Column, Integer >>> from sqlalchemy.ext.declarative import declarat...
[ "def", "get_attrname_by_colname", "(", "instance", ",", "name", ")", ":", "for", "attr", ",", "column", "in", "list", "(", "sqlalchemy", ".", "inspect", "(", "instance", ".", "__class__", ")", ".", "c", ".", "items", "(", ")", ")", ":", "if", "column",...
33.136364
0.001333
def extract_links_from_reference(self, short_id): """ Return a dictionary with supplement files (pdf, csv, zip, ipynb, html and so on) extracted from supplement page. @return: @see CourseraOnDemand._extract_links_from_text """ logging.debug('Gathering resource URLs for s...
[ "def", "extract_links_from_reference", "(", "self", ",", "short_id", ")", ":", "logging", ".", "debug", "(", "'Gathering resource URLs for short_id <%s>.'", ",", "short_id", ")", "try", ":", "dom", "=", "get_page", "(", "self", ".", "_session", ",", "OPENCOURSE_RE...
41.318182
0.001612
def _compute_predicates(table_op, predicates, data, scope, **kwargs): """Compute the predicates for a table operation. Parameters ---------- table_op : TableNode predicates : List[ir.ColumnExpr] data : pd.DataFrame scope : dict kwargs : dict Returns ------- computed_predica...
[ "def", "_compute_predicates", "(", "table_op", ",", "predicates", ",", "data", ",", "scope", ",", "*", "*", "kwargs", ")", ":", "for", "predicate", "in", "predicates", ":", "# Map each root table of the predicate to the data so that we compute", "# predicates on the resul...
32.477273
0.000679
def modify_write(self, write_pb, **unused_kwargs): """Modify a ``Write`` protobuf based on the state of this write option. If: * ``exists=True``, adds a precondition that requires existence * ``exists=False``, adds a precondition that requires non-existence Args: w...
[ "def", "modify_write", "(", "self", ",", "write_pb", ",", "*", "*", "unused_kwargs", ")", ":", "current_doc", "=", "types", ".", "Precondition", "(", "exists", "=", "self", ".", "_exists", ")", "write_pb", ".", "current_document", ".", "CopyFrom", "(", "cu...
44.294118
0.002601
def download_feed_posts(self, max_count: int = None, fast_update: bool = False, post_filter: Optional[Callable[[Post], bool]] = None) -> None: """ Download pictures from the user's feed. Example to download up to the 20 pics the user last liked:: loader ...
[ "def", "download_feed_posts", "(", "self", ",", "max_count", ":", "int", "=", "None", ",", "fast_update", ":", "bool", "=", "False", ",", "post_filter", ":", "Optional", "[", "Callable", "[", "[", "Post", "]", ",", "bool", "]", "]", "=", "None", ")", ...
48.741935
0.004543
def timezone(client, location, timestamp=None, language=None): """Get time zone for a location on the earth, as well as that location's time offset from UTC. :param location: The latitude/longitude value representing the location to look up. :type location: string, dict, list, or tuple :pa...
[ "def", "timezone", "(", "client", ",", "location", ",", "timestamp", "=", "None", ",", "language", "=", "None", ")", ":", "params", "=", "{", "\"location\"", ":", "convert", ".", "latlng", "(", "location", ")", ",", "\"timestamp\"", ":", "convert", ".", ...
34.633333
0.001873
def readline(self, size=None): """ Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the tr...
[ "def", "readline", "(", "self", ",", "size", "=", "None", ")", ":", "# it's almost silly how complex this function is.", "if", "self", ".", "_closed", ":", "raise", "IOError", "(", "'File is closed'", ")", "if", "not", "(", "self", ".", "_flags", "&", "self", ...
44.695122
0.001335
def get_historic_trades(self, start, end, granularity, product_id='BTC-USD'): """`<https://docs.exchange.coinbase.com/#get-historic-rates>`_ :param start: either datetime.datetime or str in ISO 8601 :param end: either datetime.datetime or str in ISO 8601 :pram int granularity: desired timeslice in seco...
[ "def", "get_historic_trades", "(", "self", ",", "start", ",", "end", ",", "granularity", ",", "product_id", "=", "'BTC-USD'", ")", ":", "params", "=", "{", "'start'", ":", "self", ".", "_format_iso_time", "(", "start", ")", ",", "'end'", ":", "self", "."...
36.866667
0.007055
def ssh(cls, vm_id, login, identity, args=None): """Spawn an ssh session to virtual machine.""" cmd = ['ssh'] if identity: cmd.extend(('-i', identity,)) version, ip_addr = cls.vm_ip(vm_id) if version == 6: cmd.append('-6') if not ip_addr: ...
[ "def", "ssh", "(", "cls", ",", "vm_id", ",", "login", ",", "identity", ",", "args", "=", "None", ")", ":", "cmd", "=", "[", "'ssh'", "]", "if", "identity", ":", "cmd", ".", "extend", "(", "(", "'-i'", ",", "identity", ",", ")", ")", "version", ...
28
0.003289
def from_json(cls, json_data): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: json_data: string or bytes, JSON to deserialize. Returns: An instance of a Credential...
[ "def", "from_json", "(", "cls", ",", "json_data", ")", ":", "data", "=", "json", ".", "loads", "(", "_helpers", ".", "_from_bytes", "(", "json_data", ")", ")", "if", "(", "data", ".", "get", "(", "'token_expiry'", ")", "and", "not", "isinstance", "(", ...
38.342857
0.001453
def _check_types(self) -> None: """ Check that all the instances have the same types. """ all_instance_fields_and_types: List[Dict[str, str]] = [{k: v.__class__.__name__ for k, v in x.fields.items()} ...
[ "def", "_check_types", "(", "self", ")", "->", "None", ":", "all_instance_fields_and_types", ":", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", "=", "[", "{", "k", ":", "v", ".", "__class__", ".", "__name__", "for", "k", ",", "v", "in", "x...
66
0.011958
def get(self, key): """Get a value from the cache. Returns None if the key is not in the cache. """ value = redis_conn.get(key) if value is not None: value = pickle.loads(value) return value
[ "def", "get", "(", "self", ",", "key", ")", ":", "value", "=", "redis_conn", ".", "get", "(", "key", ")", "if", "value", "is", "not", "None", ":", "value", "=", "pickle", ".", "loads", "(", "value", ")", "return", "value" ]
22.090909
0.007905
def get_special_folder(self, name): """ Returns the specified Special Folder :return: a special Folder :rtype: drive.Folder """ name = name if \ isinstance(name, OneDriveWellKnowFolderNames) \ else OneDriveWellKnowFolderNames(name.lower()) name =...
[ "def", "get_special_folder", "(", "self", ",", "name", ")", ":", "name", "=", "name", "if", "isinstance", "(", "name", ",", "OneDriveWellKnowFolderNames", ")", "else", "OneDriveWellKnowFolderNames", "(", "name", ".", "lower", "(", ")", ")", "name", "=", "nam...
34.322581
0.001828
def set_current_context(self, name): """Set the current context in kubeconfig.""" if self.context_exists(name): self.data['current-context'] = name else: raise KubeConfError("Context does not exist.")
[ "def", "set_current_context", "(", "self", ",", "name", ")", ":", "if", "self", ".", "context_exists", "(", "name", ")", ":", "self", ".", "data", "[", "'current-context'", "]", "=", "name", "else", ":", "raise", "KubeConfError", "(", "\"Context does not exi...
40.5
0.008065
def call(exe, *argv): """ Run a command, returning its output, or None if it fails. """ exes = which(exe) if not exes: returnValue(None) stdout, stderr, value = yield getProcessOutputAndValue( exes[0], argv, env=os.environ.copy() ) if value: returnValue(None) ...
[ "def", "call", "(", "exe", ",", "*", "argv", ")", ":", "exes", "=", "which", "(", "exe", ")", "if", "not", "exes", ":", "returnValue", "(", "None", ")", "stdout", ",", "stderr", ",", "value", "=", "yield", "getProcessOutputAndValue", "(", "exes", "["...
27.384615
0.002717
def parse_nexus(self): "get newick data from NEXUS" if self.data[0].strip().upper() == "#NEXUS": nex = NexusParser(self.data) self.data = nex.newicks self.tdict = nex.tdict
[ "def", "parse_nexus", "(", "self", ")", ":", "if", "self", ".", "data", "[", "0", "]", ".", "strip", "(", ")", ".", "upper", "(", ")", "==", "\"#NEXUS\"", ":", "nex", "=", "NexusParser", "(", "self", ".", "data", ")", "self", ".", "data", "=", ...
36.5
0.008929
def notebook_substitute_ref_with_url(ntbk, cr): """ In markdown cells of notebook object `ntbk`, replace sphinx cross-references with links to online docs. Parameter `cr` is a CrossReferenceLookup object. """ # Iterate over cells in notebook for n in range(len(ntbk['cells'])): # Onl...
[ "def", "notebook_substitute_ref_with_url", "(", "ntbk", ",", "cr", ")", ":", "# Iterate over cells in notebook", "for", "n", "in", "range", "(", "len", "(", "ntbk", "[", "'cells'", "]", ")", ")", ":", "# Only process cells of type 'markdown'", "if", "ntbk", "[", ...
41.529412
0.001385
def _operator(attr): """Defers an operator overload to `attr`. Args: attr: Operator attribute to use. Returns: Function calling operator attribute. """ @functools.wraps(attr) def func(a, *args): return attr(a.value, *args) return func
[ "def", "_operator", "(", "attr", ")", ":", "@", "functools", ".", "wraps", "(", "attr", ")", "def", "func", "(", "a", ",", "*", "args", ")", ":", "return", "attr", "(", "a", ".", "value", ",", "*", "args", ")", "return", "func" ]
19.230769
0.019084
def parallel_coordinates(X, y, ax=None, features=None, classes=None, normalize=None, sample=1.0, color=None, colormap=None, alpha=None, fast=False, vlines=True, vlines_kwds=None, **kwargs): """Displays each feature as a vertical axis and eac...
[ "def", "parallel_coordinates", "(", "X", ",", "y", ",", "ax", "=", "None", ",", "features", "=", "None", ",", "classes", "=", "None", ",", "normalize", "=", "None", ",", "sample", "=", "1.0", ",", "color", "=", "None", ",", "colormap", "=", "None", ...
39.211111
0.000276
def _process_batch(self): """Process only a single batch group of data""" if self.block_id == len(self.tgroups): return None, None tgroup = self.tgroups[self.block_id] psize = self.chunk_tsamples[self.block_id] mid = self.mids[self.block_id] stilde = self.dat...
[ "def", "_process_batch", "(", "self", ")", ":", "if", "self", ".", "block_id", "==", "len", "(", "self", ".", "tgroups", ")", ":", "return", "None", ",", "None", "tgroup", "=", "self", ".", "tgroups", "[", "self", ".", "block_id", "]", "psize", "=", ...
32.882353
0.002431
def vclose(L, V): """ gets the closest vector """ lam, X = 0, [] for k in range(3): lam = lam + V[k] * L[k] beta = np.sqrt(1. - lam**2) for k in range(3): X.append((old_div((V[k] - lam * L[k]), beta))) return X
[ "def", "vclose", "(", "L", ",", "V", ")", ":", "lam", ",", "X", "=", "0", ",", "[", "]", "for", "k", "in", "range", "(", "3", ")", ":", "lam", "=", "lam", "+", "V", "[", "k", "]", "*", "L", "[", "k", "]", "beta", "=", "np", ".", "sqrt...
22.545455
0.003876
def _new_from_rft(self, base_template, rft_file): """Append a new file from .rft entry to the journal. This instructs Revit to create a new model based on the provided .rft template. Args: base_template (str): new file journal template from rmj.templates rft_fil...
[ "def", "_new_from_rft", "(", "self", ",", "base_template", ",", "rft_file", ")", ":", "self", ".", "_add_entry", "(", "base_template", ")", "self", ".", "_add_entry", "(", "templates", ".", "NEW_FROM_RFT", ".", "format", "(", "rft_file_path", "=", "rft_file", ...
42.5
0.003289
def _container_candidates(self): """Generate container candidate list Returns: tuple list: [(width1, height1), (width2, height2), ...] """ if not self._rectangles: return [] if self._rotation: sides = sorted(side for rect in self._r...
[ "def", "_container_candidates", "(", "self", ")", ":", "if", "not", "self", ".", "_rectangles", ":", "return", "[", "]", "if", "self", ".", "_rotation", ":", "sides", "=", "sorted", "(", "side", "for", "rect", "in", "self", ".", "_rectangles", "for", "...
34.45283
0.007987
def _handle_api_call(self, url): """ Handle the return call from the api and return a data and meta_data object. It raises a ValueError on problems Keyword Arguments: url: The url of the service data_key: The key for getting the data from the jso object me...
[ "def", "_handle_api_call", "(", "self", ",", "url", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "proxies", "=", "self", ".", "proxy", ")", "if", "'json'", "in", "self", ".", "output_format", ".", "lower", "(", ")", "or", "'pan...
47.444444
0.002295
def open(self): """ Setup serial port and set is as escpos device """ if self.device is not None and self.device.is_open: self.close() self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity...
[ "def", "open", "(", "self", ")", ":", "if", "self", ".", "device", "is", "not", "None", "and", "self", ".", "device", ".", "is_open", ":", "self", ".", "close", "(", ")", "self", ".", "device", "=", "serial", ".", "Serial", "(", "port", "=", "sel...
49.923077
0.006051
def __check_logging_rules(configuration): """ Check that the logging values are proper """ valid_log_levels = [ 'debug', 'info', 'warning', 'error' ] if configuration['logging']['log_level'].lower() not in valid_log_levels: print('Log level must be one of {0}'.for...
[ "def", "__check_logging_rules", "(", "configuration", ")", ":", "valid_log_levels", "=", "[", "'debug'", ",", "'info'", ",", "'warning'", ",", "'error'", "]", "if", "configuration", "[", "'logging'", "]", "[", "'log_level'", "]", ".", "lower", "(", ")", "not...
31.25
0.002591
def _compile_fdpf(self): """Fast Decoupled Power Flow execution: Implement g(y) """ string = '"""\n' string += 'system.dae.init_g()\n' for pflow, gcall, call in zip(self.pflow, self.gcall, self.gcalls): if pflow and gcall: string += call string...
[ "def", "_compile_fdpf", "(", "self", ")", ":", "string", "=", "'\"\"\"\\n'", "string", "+=", "'system.dae.init_g()\\n'", "for", "pflow", ",", "gcall", ",", "call", "in", "zip", "(", "self", ".", "pflow", ",", "self", ".", "gcall", ",", "self", ".", "gcal...
37
0.004396
def create_environment(self, environment): """ Method to create environment """ uri = 'api/v3/environment/' data = dict() data['environments'] = list() data['environments'].append(environment) return super(ApiEnvironment, self).post(uri, data)
[ "def", "create_environment", "(", "self", ",", "environment", ")", ":", "uri", "=", "'api/v3/environment/'", "data", "=", "dict", "(", ")", "data", "[", "'environments'", "]", "=", "list", "(", ")", "data", "[", "'environments'", "]", ".", "append", "(", ...
24.916667
0.006452
def duration(self): """Get or set the duration of the todo. | Will return a timedelta object. | May be set to anything that timedelta() understands. | May be set with a dict ({"days":2, "hours":6}). | If set to a non null value, removes any already existing end t...
[ "def", "duration", "(", "self", ")", ":", "if", "self", ".", "_duration", ":", "return", "self", ".", "_duration", "elif", "self", ".", "due", ":", "return", "self", ".", "due", "-", "self", ".", "begin", "else", ":", "# todo has neither due, nor start and...
33.9375
0.003584
def normalizeGlyphUnicodes(value): """ Normalizes glyph unicodes. * **value** must be a ``list``. * **value** items must normalize as glyph unicodes with :func:`normalizeGlyphUnicode`. * **value** must not repeat unicode values. * Returned value will be a ``tuple`` of ints. """ if...
[ "def", "normalizeGlyphUnicodes", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "tuple", ",", "list", ")", ")", ":", "raise", "TypeError", "(", "\"Glyph unicodes must be a list, not %s.\"", "%", "type", "(", "value", ")", ".", "__...
39.222222
0.001383
def _set_vpnv6_unicast(self, v, load=False): """ Setter method for vpnv6_unicast, mapped from YANG variable /routing_system/router/router_bgp/address_family/vpnv6/vpnv6_unicast (container) If this variable is read-only (config: false) in the source YANG file, then _set_vpnv6_unicast is considered as a p...
[ "def", "_set_vpnv6_unicast", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "...
88.136364
0.005102
def do_some_work( self, work_dict): """do_some_work :param work_dict: dictionary for key/values """ label = "do_some_work" log.info(("task - {} - start " "work_dict={}") .format(label, work_dict)) ret_data = { "job_resul...
[ "def", "do_some_work", "(", "self", ",", "work_dict", ")", ":", "label", "=", "\"do_some_work\"", "log", ".", "info", "(", "(", "\"task - {} - start \"", "\"work_dict={}\"", ")", ".", "format", "(", "label", ",", "work_dict", ")", ")", "ret_data", "=", "{", ...
20.192308
0.001818
def get_edge_mask(self, subdomain=None): """Get faces which are fully in subdomain. """ if subdomain is None: # https://stackoverflow.com/a/42392791/353337 return numpy.s_[:] if subdomain not in self.subdomains: self._mark_vertices(subdomain) ...
[ "def", "get_edge_mask", "(", "self", ",", "subdomain", "=", "None", ")", ":", "if", "subdomain", "is", "None", ":", "# https://stackoverflow.com/a/42392791/353337", "return", "numpy", ".", "s_", "[", ":", "]", "if", "subdomain", "not", "in", "self", ".", "su...
34.904762
0.002656
def check_log_file_size(self): """如果日志文件超过100M,先保存源文件,再将原日志文件名后加“_时间戳”保存,再 重新以原文件名以追加模式创建,这样就实现了,只要日志文件超过100M就自动备份。 从而实现了控制日志文件大小的效果,由于在多线程进行同一个文件写入的时候,如果 文件大小超过了100m,而这一时刻,也有很多线程监测到了文件大小超限制,所以这时 那些知道超过了限制的线程就会改名文件,然后以追加方式重新打开文件,这样就会造成 改名后的文件的大小有的字节数在0字节这个范围,所以,我引入了锁来控制。 ...
[ "def", "check_log_file_size", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "getsize", "(", "self", ".", "fileName", ")", ">=", "1024", "*", "1024", "*", "1024", ":", "# 关闭文件", "self", ".", "__f", ".", "close", "(", ")", "# 改名", "r...
40.3125
0.004545
def top_priority_effect_for_single_gene(effects): """ For effects which are from the same gene, check to see if there is a canonical transcript with both the maximum length CDS and maximum length full transcript sequence. If not, then use number of exons and transcript name as tie-breaking feat...
[ "def", "top_priority_effect_for_single_gene", "(", "effects", ")", ":", "# first filter effects to keep those on", "# 1) maximum priority effects", "# 2) protein coding genes", "# 3) protein coding transcripts", "# 4) complete transcripts", "#", "# If any of these filters drop all the effect...
34.090909
0.000972
def from_sequence(cls, *args): """ from_sequence(start=0, stop) Create an SArray from sequence .. sourcecode:: python Construct an SArray of integer values from 0 to 999 >>> tc.SArray.from_sequence(1000) This is equivalent, but more efficient than...
[ "def", "from_sequence", "(", "cls", ",", "*", "args", ")", ":", "start", "=", "None", "stop", "=", "None", "# fill with args. This checks for from_sequence(100), from_sequence(10,100)", "if", "len", "(", "args", ")", "==", "1", ":", "stop", "=", "args", "[", "...
28.603774
0.001913
def print(self): """ prints to terminal the summray statistics """ print("TOTALS -------------------------------------------") print(json.dumps(self.counts, indent=4, sort_keys=True)) if self.sub_total: print("\nSUB TOTALS --- based on '%s' ---------" % self.s...
[ "def", "print", "(", "self", ")", ":", "print", "(", "\"TOTALS -------------------------------------------\"", ")", "print", "(", "json", ".", "dumps", "(", "self", ".", "counts", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", ")", "if", "sel...
43.25
0.003774
def get_args(self, client): """ Builds final set of XML-RPC method arguments based on the method's arguments, any default arguments, and their defined respective ordering. """ default_args = self.default_args(client) if self.method_args or self.optional_a...
[ "def", "get_args", "(", "self", ",", "client", ")", ":", "default_args", "=", "self", ".", "default_args", "(", "client", ")", "if", "self", ".", "method_args", "or", "self", ".", "optional_args", ":", "optional_args", "=", "getattr", "(", "self", ",", "...
35.782609
0.002367
def Engauge_2d_parser(lines, flat=False): '''Not exposed function to read a 2D file generated by engauge-digitizer; for curve fitting. ''' z_values = [] x_lists = [] y_lists = [] working_xs = [] working_ys = [] new_curve = True for line in lines: if line.strip() == '...
[ "def", "Engauge_2d_parser", "(", "lines", ",", "flat", "=", "False", ")", ":", "z_values", "=", "[", "]", "x_lists", "=", "[", "]", "y_lists", "=", "[", "]", "working_xs", "=", "[", "]", "working_ys", "=", "[", "]", "new_curve", "=", "True", "for", ...
27.97619
0.002467
def image(self, s=0, c=0, z=0, t=0): """Return image as a :class:`jicimagelib.image.Image`. :param s: series :param c: channel :param z: zslice :param t: timepoint :returns: :class:`jicimagelib.image.Image` """ return self.proxy_image(s=s, c=c, z=...
[ "def", "image", "(", "self", ",", "s", "=", "0", ",", "c", "=", "0", ",", "z", "=", "0", ",", "t", "=", "0", ")", ":", "return", "self", ".", "proxy_image", "(", "s", "=", "s", ",", "c", "=", "c", ",", "z", "=", "z", ",", "t", "=", "t...
32.4
0.009009
def format(self): """Return the format attribute of the BFD file being processed.""" if not self._ptr: raise BfdException("BFD not initialized") return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.FORMAT)
[ "def", "format", "(", "self", ")", ":", "if", "not", "self", ".", "_ptr", ":", "raise", "BfdException", "(", "\"BFD not initialized\"", ")", "return", "_bfd", ".", "get_bfd_attribute", "(", "self", ".", "_ptr", ",", "BfdAttributes", ".", "FORMAT", ")" ]
39.833333
0.008197
def _ParseMRUListEntryValue( self, parser_mediator, registry_key, entry_index, entry_letter, codepage='cp1252', **kwargs): """Parses the MRUList entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs...
[ "def", "_ParseMRUListEntryValue", "(", "self", ",", "parser_mediator", ",", "registry_key", ",", "entry_index", ",", "entry_letter", ",", "codepage", "=", "'cp1252'", ",", "*", "*", "kwargs", ")", ":", "value_string", "=", "''", "value", "=", "registry_key", "...
36.615385
0.004775
def _label_desc(self, label, desc, label_color=''): ''' Generic styler for a line consisting of a label and description. ''' return self.BRIGHT + label_color + label + self.RESET + desc
[ "def", "_label_desc", "(", "self", ",", "label", ",", "desc", ",", "label_color", "=", "''", ")", ":", "return", "self", ".", "BRIGHT", "+", "label_color", "+", "label", "+", "self", ".", "RESET", "+", "desc" ]
66.666667
0.019802
def edit(self, resource): """Edit a job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job """ schema = JobSchema(exclude=('id', 'status', 'options', 'package_name', 'config_name', 'device_name', 'result_id...
[ "def", "edit", "(", "self", ",", "resource", ")", ":", "schema", "=", "JobSchema", "(", "exclude", "=", "(", "'id'", ",", "'status'", ",", "'options'", ",", "'package_name'", ",", "'config_name'", ",", "'device_name'", ",", "'result_id'", ",", "'user_id'", ...
43.384615
0.005208
def replace_route(DryRun=None, RouteTableId=None, DestinationCidrBlock=None, GatewayId=None, DestinationIpv6CidrBlock=None, EgressOnlyInternetGatewayId=None, InstanceId=None, NetworkInterfaceId=None, VpcPeeringConnectionId=None, NatGatewayId=None): """ Replaces an existing route within a route table in a VPC. Y...
[ "def", "replace_route", "(", "DryRun", "=", "None", ",", "RouteTableId", "=", "None", ",", "DestinationCidrBlock", "=", "None", ",", "GatewayId", "=", "None", ",", "DestinationIpv6CidrBlock", "=", "None", ",", "EgressOnlyInternetGatewayId", "=", "None", ",", "In...
44.19403
0.005616
def fetch(): """ Fetches the latest exchange rate info from the European Central Bank. These rates need to be used for displaying invoices since some countries require local currency be quoted. Also useful to store the GBP rate of the VAT collected at time of purchase to prevent fluctuations in exch...
[ "def", "fetch", "(", ")", ":", "response", "=", "urlopen", "(", "'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'", ")", "_", ",", "params", "=", "cgi", ".", "parse_header", "(", "response", ".", "headers", "[", "'Content-Type'", "]", ")", "if", "...
36.849624
0.00159
def remove_license(self, name=None, url=None): """Remove all licenses matching both key and value. :param str name: Name of the license. :param str url: URL of the license. """ for k, v in self.licenses[:]: if (name is None or name == k) and (url is None or url == v)...
[ "def", "remove_license", "(", "self", ",", "name", "=", "None", ",", "url", "=", "None", ")", ":", "for", "k", ",", "v", "in", "self", ".", "licenses", "[", ":", "]", ":", "if", "(", "name", "is", "None", "or", "name", "==", "k", ")", "and", ...
41.888889
0.005195
def to_json(self, indent=2): """ Return self formatted as JSON. """ return json.dumps(self, default=json_encode_for_printing, indent=indent)
[ "def", "to_json", "(", "self", ",", "indent", "=", "2", ")", ":", "return", "json", ".", "dumps", "(", "self", ",", "default", "=", "json_encode_for_printing", ",", "indent", "=", "indent", ")" ]
51.333333
0.019231
def kelvin_to_rgb(kelvin): """ Convert a color temperature given in kelvin to an approximate RGB value. :param kelvin: Color temp in K :return: Tuple of (r, g, b), equivalent color for the temperature """ temp = kelvin / 100.0 # Calculate Red: if temp <= 66: red = 255 else:...
[ "def", "kelvin_to_rgb", "(", "kelvin", ")", ":", "temp", "=", "kelvin", "/", "100.0", "# Calculate Red:", "if", "temp", "<=", "66", ":", "red", "=", "255", "else", ":", "red", "=", "329.698727446", "*", "(", "(", "temp", "-", "60", ")", "**", "-", ...
24.967742
0.002488
def num_data(self): """Get the number of rows in the Dataset. Returns ------- number_of_rows : int The number of rows in the Dataset. """ if self.handle is not None: ret = ctypes.c_int() _safe_call(_LIB.LGBM_DatasetGetNumData(self.hand...
[ "def", "num_data", "(", "self", ")", ":", "if", "self", ".", "handle", "is", "not", "None", ":", "ret", "=", "ctypes", ".", "c_int", "(", ")", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetGetNumData", "(", "self", ".", "handle", ",", "ctypes", ".", "...
33.533333
0.003868
def parse_mime_version(value): """ mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS] """ # The [CFWS] is implicit in the RFC 2045 BNF. # XXX: This routine is a bit verbose, should factor out a get_int method. mime_version = MIMEVersion() if not value: mime_version.defects.a...
[ "def", "parse_mime_version", "(", "value", ")", ":", "# The [CFWS] is implicit in the RFC 2045 BNF.", "# XXX: This routine is a bit verbose, should factor out a get_int method.", "mime_version", "=", "MIMEVersion", "(", ")", "if", "not", "value", ":", "mime_version", ".", "defe...
41.791045
0.001047
def get_distribution(name, region=None, key=None, keyid=None, profile=None): ''' Get information about a CloudFront distribution (configuration, tags) with a given name. name Name of the CloudFront distribution region Region to connect to key Secret key to use keyid ...
[ "def", "get_distribution", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "distribution", "=", "_cache_id", "(", "'cloudfront'", ",", "sub_resource", "=", "name", ",", ...
27.561644
0.00144
def splitValues(textStr): """Splits a comma-separated number sequence into a list (of floats). """ vals = textStr.split(",") nums = [] for v in vals: nums.append(float(v)) return nums
[ "def", "splitValues", "(", "textStr", ")", ":", "vals", "=", "textStr", ".", "split", "(", "\",\"", ")", "nums", "=", "[", "]", "for", "v", "in", "vals", ":", "nums", ".", "append", "(", "float", "(", "v", ")", ")", "return", "nums" ]
26
0.004651
def dead_code(): """ This also finds code you are working on today! """ with safe_cd(SRC): if IS_TRAVIS: command = "{0} vulture {1}".format(PYTHON, PROJECT_NAME).strip().split() else: command = "{0} vulture {1}".format(PIPENV, PROJECT_NAME).strip().split() ...
[ "def", "dead_code", "(", ")", ":", "with", "safe_cd", "(", "SRC", ")", ":", "if", "IS_TRAVIS", ":", "command", "=", "\"{0} vulture {1}\"", ".", "format", "(", "PYTHON", ",", "PROJECT_NAME", ")", ".", "strip", "(", ")", ".", "split", "(", ")", "else", ...
36.15
0.005391
def _is_valid_dist_file(filename, filetype): """ Perform some basic checks to see whether the indicated file could be a valid distribution file. """ # If our file is a zipfile, then ensure that it's members are only # compressed with supported compression methods. if zipfile.is_zipfile(file...
[ "def", "_is_valid_dist_file", "(", "filename", ",", "filetype", ")", ":", "# If our file is a zipfile, then ensure that it's members are only", "# compressed with supported compression methods.", "if", "zipfile", ".", "is_zipfile", "(", "filename", ")", ":", "with", "zipfile", ...
41.654321
0.00029
def is_connected(self): """ Test if the graph is connected. Return True if connected, False otherwise """ try: return nx.is_weakly_connected(self.graph) except nx.exception.NetworkXException: return False
[ "def", "is_connected", "(", "self", ")", ":", "try", ":", "return", "nx", ".", "is_weakly_connected", "(", "self", ".", "graph", ")", "except", "nx", ".", "exception", ".", "NetworkXException", ":", "return", "False" ]
26.8
0.00722
def bbox(img): """Find the bounding box around nonzero elements in the given array Copied from https://stackoverflow.com/a/31402351/5703449 . Returns: rowmin, rowmax, colmin, colmax """ rows = np.any(img, axis=1) cols = np.any(img, axis=0) rmin, rmax = np.where(rows)[0][[0, -1]] ...
[ "def", "bbox", "(", "img", ")", ":", "rows", "=", "np", ".", "any", "(", "img", ",", "axis", "=", "1", ")", "cols", "=", "np", ".", "any", "(", "img", ",", "axis", "=", "0", ")", "rmin", ",", "rmax", "=", "np", ".", "where", "(", "rows", ...
27.357143
0.002525
def set_progress(how): """ Enables or disables the progress bars for the loading, writing and downloading of datasets :param how: True if you want the progress bar, False otherwise :return: None Example:: import gmql as gl gl.set_progress(True) # abilitates progress bars ...
[ "def", "set_progress", "(", "how", ")", ":", "global", "__progress_bar", "if", "isinstance", "(", "how", ",", "bool", ")", ":", "__progress_bar", "=", "how", "else", ":", "raise", "ValueError", "(", "\"how must be a boolean. {} was found\"", ".", "format", "(", ...
27.545455
0.00319
def init(directory): """Init the config fle.""" username = click.prompt("Input your username") password = click.prompt("Input your password", hide_input=True, confirmation_prompt=True) log_directory = click.prompt("Input your log directory") if not path.exists(log_direct...
[ "def", "init", "(", "directory", ")", ":", "username", "=", "click", ".", "prompt", "(", "\"Input your username\"", ")", "password", "=", "click", ".", "prompt", "(", "\"Input your password\"", ",", "hide_input", "=", "True", ",", "confirmation_prompt", "=", "...
37.578947
0.001366
def bfs(self): ''' Breadth-first search generator. Yields `(node, parent)` for every node in the tree, beginning with `(self.root, None)`. ''' yield (self.root, None) todo = deque([(self.root[char], self.root) for char in self.root]) while todo: curre...
[ "def", "bfs", "(", "self", ")", ":", "yield", "(", "self", ".", "root", ",", "None", ")", "todo", "=", "deque", "(", "[", "(", "self", ".", "root", "[", "char", "]", ",", "self", ".", "root", ")", "for", "char", "in", "self", ".", "root", "]"...
38.25
0.004255
def _ParseContainerConfigJSON(self, parser_mediator, file_object): """Extracts events from a Docker container configuration file. The path of each container config file is: DOCKER_DIR/containers/<container_id>/config.json Args: parser_mediator (ParserMediator): mediates interactions between pars...
[ "def", "_ParseContainerConfigJSON", "(", "self", ",", "parser_mediator", ",", "file_object", ")", ":", "file_content", "=", "file_object", ".", "read", "(", ")", "file_content", "=", "codecs", ".", "decode", "(", "file_content", ",", "self", ".", "_ENCODING", ...
40.961538
0.005501
def check_and_adjust_sighandler(self, signame, sigs): """ Check to see if a single signal handler that we are interested in has changed or has not been set initially. On return self.sigs[signame] should have our signal handler. True is returned if the same or adjusted, False or N...
[ "def", "check_and_adjust_sighandler", "(", "self", ",", "signame", ",", "sigs", ")", ":", "signum", "=", "lookup_signum", "(", "signame", ")", "try", ":", "old_handler", "=", "signal", ".", "getsignal", "(", "signum", ")", "except", "ValueError", ":", "# On ...
37.756757
0.001396