text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _moving_average(data, wind_size=3): """ ----- Brief ----- Application of a moving average filter for signal smoothing. ----------- Description ----------- In certain situations it will be interesting to simplify a signal, particularly in cases where some events with a random...
[ "def", "_moving_average", "(", "data", ",", "wind_size", "=", "3", ")", ":", "wind_size", "=", "int", "(", "wind_size", ")", "ret", "=", "numpy", ".", "cumsum", "(", "data", ",", "dtype", "=", "float", ")", "ret", "[", "wind_size", ":", "]", "=", "...
35.521739
0.005956
def write_to_file(self, filename, filetype=None): """Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or...
[ "def", "write_to_file", "(", "self", ",", "filename", ",", "filetype", "=", "None", ")", ":", "if", "filetype", "==", "\"txt\"", "and", "not", "filename", ".", "endswith", "(", "\".txt\"", ")", ":", "raise", "Exception", "(", "\"TXT files must have .txt extens...
47.145833
0.00303
def MI_invokeMethod(self, env, objectName, metaMethod, inputParams): # pylint: disable=invalid-name """Invoke an extrinsic method. Implements the InvokeMethod WBEM operation by calling the method on a derived class called cim_method_<method_name>, where <method_name> is the name...
[ "def", "MI_invokeMethod", "(", "self", ",", "env", ",", "objectName", ",", "metaMethod", ",", "inputParams", ")", ":", "# pylint: disable=invalid-name", "logger", "=", "env", ".", "get_logger", "(", ")", "logger", ".", "log_debug", "(", "'CIMProvider MI_invokeMeth...
43.185714
0.002264
def from_project_root(cls, project_root, cli_vars): """Create a project from a root directory. Reads in dbt_project.yml and packages.yml, if it exists. :param project_root str: The path to the project root to load. :raises DbtProjectError: If the project is missing or invalid, or if ...
[ "def", "from_project_root", "(", "cls", ",", "project_root", ",", "cli_vars", ")", ":", "project_root", "=", "os", ".", "path", ".", "normpath", "(", "project_root", ")", "project_yaml_filepath", "=", "os", ".", "path", ".", "join", "(", "project_root", ",",...
44.892857
0.001558
def angular_separation(self, lonp1, latp1, lonp2, latp2): """ Compute the angles between lon / lat points p1 and p2 given in radians. On the unit sphere, this also corresponds to the great circle distance. p1 and p2 can be numpy arrays of the same length. This method simply call...
[ "def", "angular_separation", "(", "self", ",", "lonp1", ",", "latp1", ",", "lonp2", ",", "latp2", ")", ":", "# Call the module-level function", "return", "angular_separation", "(", "lonp1", ",", "latp1", ",", "lonp2", ",", "latp2", ")" ]
51.769231
0.00292
def load(text, match=None): """This function reads a string that contains the XML of an Atom Feed, then returns the data in a native Python structure (a ``dict`` or ``list``). If you also provide a tag name or path to match, only the matching sub-elements are loaded. :param text: The XML te...
[ "def", "load", "(", "text", ",", "match", "=", "None", ")", ":", "if", "text", "is", "None", ":", "return", "None", "text", "=", "text", ".", "strip", "(", ")", "if", "len", "(", "text", ")", "==", "0", ":", "return", "None", "nametable", "=", ...
31.484848
0.008403
def distancePointToLine(point, line_start, line_end, perpendicular=False): """Return the minimum distance between point and the line (line_start, line_end)""" p1 = line_start p2 = line_end offset = lineOffsetWithMinimumDistanceToPoint( point, line_start, line_end, perpendicular) if offset ==...
[ "def", "distancePointToLine", "(", "point", ",", "line_start", ",", "line_end", ",", "perpendicular", "=", "False", ")", ":", "p1", "=", "line_start", "p2", "=", "line_end", "offset", "=", "lineOffsetWithMinimumDistanceToPoint", "(", "point", ",", "line_start", ...
44.615385
0.003378
def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None): """ Return the URL for a VCS requirement. Args: repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+"). project_name: the (unescaped) project name. """ egg_project_name = pkg_resources.to_filename(pr...
[ "def", "make_vcs_requirement_url", "(", "repo_url", ",", "rev", ",", "project_name", ",", "subdir", "=", "None", ")", ":", "egg_project_name", "=", "pkg_resources", ".", "to_filename", "(", "project_name", ")", "req", "=", "'{}@{}#egg={}'", ".", "format", "(", ...
33.071429
0.002101
def get(self, measurementId): """ Analyses the measurement with the given parameters :param measurementId: :return: """ logger.info('Analysing ' + measurementId) measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.COMPLETE) ...
[ "def", "get", "(", "self", ",", "measurementId", ")", ":", "logger", ".", "info", "(", "'Analysing '", "+", "measurementId", ")", "measurement", "=", "self", ".", "_measurementController", ".", "getMeasurement", "(", "measurementId", ",", "MeasurementStatus", "....
42.837838
0.001851
def as_dictionary(self): """ Convert this object to a dictionary with formatting appropriate for a PIF. :returns: Dictionary with the content of this object formatted for a PIF. """ return {to_camel_case(i): Serializable._convert_to_dictionary(self.__dict__[i]) f...
[ "def", "as_dictionary", "(", "self", ")", ":", "return", "{", "to_camel_case", "(", "i", ")", ":", "Serializable", ".", "_convert_to_dictionary", "(", "self", ".", "__dict__", "[", "i", "]", ")", "for", "i", "in", "self", ".", "__dict__", "if", "self", ...
45.875
0.013369
def metric_update(self, project, metric_name, filter_, description): """API call: update a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :type filter_: str...
[ "def", "metric_update", "(", "self", ",", "project", ",", "metric_name", ",", "filter_", ",", "description", ")", ":", "path", "=", "\"projects/%s/metrics/%s\"", "%", "(", "project", ",", "metric_name", ")", "metric_pb", "=", "LogMetric", "(", "name", "=", "...
40.384615
0.002791
def end_scan(self): """Ends an ongoing BLE scan started by :meth:`begin_scan`. Returns: a :class:`ScanResults` object containing the scan results. """ # TODO check states before/after self._set_state(self._STATE_GAP_END) self.api.ble_cmd_gap_end_procedure() ...
[ "def", "end_scan", "(", "self", ")", ":", "# TODO check states before/after", "self", ".", "_set_state", "(", "self", ".", "_STATE_GAP_END", ")", "self", ".", "api", ".", "ble_cmd_gap_end_procedure", "(", ")", "self", ".", "_wait_for_state", "(", "self", ".", ...
33.461538
0.004474
def check_release_number(release): """ Check to make sure a release is in the valid range of Ensembl releases. """ try: release = int(release) except: raise ValueError("Invalid Ensembl release: %s" % release) if release < MIN_ENSEMBL_RELEASE or release > MAX_ENSEMBL_RELEASE:...
[ "def", "check_release_number", "(", "release", ")", ":", "try", ":", "release", "=", "int", "(", "release", ")", "except", ":", "raise", "ValueError", "(", "\"Invalid Ensembl release: %s\"", "%", "release", ")", "if", "release", "<", "MIN_ENSEMBL_RELEASE", "or",...
32.8
0.003953
def add_file(self, git_path, content): """ Add a new file as blob in the storage and add its tree entry into the index. :param git_path: str :param content: str """ blob_id = self.write_blob(content) self.add_index('100644', blob_id, git_path)
[ "def", "add_file", "(", "self", ",", "git_path", ",", "content", ")", ":", "blob_id", "=", "self", ".", "write_blob", "(", "content", ")", "self", ".", "add_index", "(", "'100644'", ",", "blob_id", ",", "git_path", ")" ]
33.333333
0.012987
def disable_servicegroup_svc_checks(self, servicegroup): """Disable service checks for a servicegroup Format of the line that triggers function call:: DISABLE_SERVICEGROUP_SVC_CHECKS;<servicegroup_name> :param servicegroup: servicegroup to disable :type servicegroup: alignak.ob...
[ "def", "disable_servicegroup_svc_checks", "(", "self", ",", "servicegroup", ")", ":", "for", "service_id", "in", "servicegroup", ".", "get_services", "(", ")", ":", "self", ".", "disable_svc_check", "(", "self", ".", "daemon", ".", "services", "[", "service_id",...
41.5
0.003929
def set_left_margin(self, left_margin): """ Set the left margin of the menu. This will determine the number of spaces between the left edge of the screen and the left menu border. :param left_margin: an integer value """ self.__header.style.margins.left = left_margin ...
[ "def", "set_left_margin", "(", "self", ",", "left_margin", ")", ":", "self", ".", "__header", ".", "style", ".", "margins", ".", "left", "=", "left_margin", "self", ".", "__prologue", ".", "style", ".", "margins", ".", "left", "=", "left_margin", "self", ...
46.923077
0.004823
def parse_children(self, node): """ Parses <Children> @param node: Node containing the <Children> element @type node: xml.etree.Element """ if 'name' in node.lattrib: name = node.lattrib['name'] else: self.raise_error('<Children> must spe...
[ "def", "parse_children", "(", "self", ",", "node", ")", ":", "if", "'name'", "in", "node", ".", "lattrib", ":", "name", "=", "node", ".", "lattrib", "[", "'name'", "]", "else", ":", "self", ".", "raise_error", "(", "'<Children> must specify a name.'", ")",...
29.473684
0.00346
def set_cmap(cmap): ''' Set the color map of the current 'color' scale. ''' scale = _context['scales']['color'] for k, v in _process_cmap(cmap).items(): setattr(scale, k, v) return scale
[ "def", "set_cmap", "(", "cmap", ")", ":", "scale", "=", "_context", "[", "'scales'", "]", "[", "'color'", "]", "for", "k", ",", "v", "in", "_process_cmap", "(", "cmap", ")", ".", "items", "(", ")", ":", "setattr", "(", "scale", ",", "k", ",", "v"...
26.375
0.004587
def get_locations(self, ip, detailed=False): """Returns a list of dictionaries with location data or False on failure. Argument `ip` must be an iterable object. Amount of information about IP contained in the dictionary depends upon `detailed` flag state. """ if...
[ "def", "get_locations", "(", "self", ",", "ip", ",", "detailed", "=", "False", ")", ":", "if", "isinstance", "(", "ip", ",", "str", ")", ":", "ip", "=", "[", "ip", "]", "seek", "=", "map", "(", "self", ".", "_get_pos", ",", "ip", ")", "return", ...
38.923077
0.011583
def main_help_text(self, commands_only=False): """ Returns the script's main help text, as a string. """ if commands_only: usage = sorted(get_commands().keys()) else: usage = [ "", "Type '%s help <subcommand>' for help on a ...
[ "def", "main_help_text", "(", "self", ",", "commands_only", "=", "False", ")", ":", "if", "commands_only", ":", "usage", "=", "sorted", "(", "get_commands", "(", ")", ".", "keys", "(", ")", ")", "else", ":", "usage", "=", "[", "\"\"", ",", "\"Type '%s ...
41.205882
0.002092
def _get_help_for_modules(self, modules, prefix, include_special_flags): """Returns the help string for a list of modules. Private to absl.flags package. Args: modules: List[str], a list of modules to get the help string for. prefix: str, a string that is prepended to each generated help line....
[ "def", "_get_help_for_modules", "(", "self", ",", "modules", ",", "prefix", ",", "include_special_flags", ")", ":", "output_lines", "=", "[", "]", "for", "module", "in", "modules", ":", "self", ".", "_render_our_module_flags", "(", "module", ",", "output_lines",...
38.333333
0.004848
def build_dependencies(self) -> "Dependencies": """ Return `Dependencies` instance containing the build dependencies available on this Package. The ``Package`` class should provide access to the full dependency tree. .. code:: python >>> owned_package.build_dependencies['zep...
[ "def", "build_dependencies", "(", "self", ")", "->", "\"Dependencies\"", ":", "validate_build_dependencies_are_present", "(", "self", ".", "manifest", ")", "dependencies", "=", "self", ".", "manifest", "[", "\"build_dependencies\"", "]", "dependency_packages", "=", "{...
38.814815
0.004655
def CreateAttachmentAndUploadMedia(self, document_link, readable_stream, options=None): """Creates an attachment and upload media. :param str document_link: The link to the d...
[ "def", "CreateAttachmentAndUploadMedia", "(", "self", ",", "document_link", ",", "readable_stream", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "document_id", ",", "initial_headers", ",", "path", "=", ...
33.642857
0.007224
def finalize(self): """ Is called before destruction. Can be used to clean-up resources """ logger.debug("Finalizing: {}".format(self)) self.plotItem.scene().sigMouseMoved.disconnect(self.mouseMoved) self.plotItem.close() self.graphicsLayoutWidget.close()
[ "def", "finalize", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Finalizing: {}\"", ".", "format", "(", "self", ")", ")", "self", ".", "plotItem", ".", "scene", "(", ")", ".", "sigMouseMoved", ".", "disconnect", "(", "self", ".", "mouseMoved", ...
42.428571
0.006601
def handle_ans(self, ans_): """ preforms an actionm based on a user answer """ ans = ans_.strip(' ') def chack_if_answer_was(valid_keys): return any([ans == key or ans.startswith(key + ' ') for key in valid_keys]) # Custom interactions ...
[ "def", "handle_ans", "(", "self", ",", "ans_", ")", ":", "ans", "=", "ans_", ".", "strip", "(", "' '", ")", "def", "chack_if_answer_was", "(", "valid_keys", ")", ":", "return", "any", "(", "[", "ans", "==", "key", "or", "ans", ".", "startswith", "(",...
35.153846
0.006397
def add_agent_cloud(self, agent_cloud): """AddAgentCloud. [Preview API] :param :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>` agent_cloud: :rtype: :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>` """ content = ...
[ "def", "add_agent_cloud", "(", "self", ",", "agent_cloud", ")", ":", "content", "=", "self", ".", "_serialize", ".", "body", "(", "agent_cloud", ",", "'TaskAgentCloud'", ")", "response", "=", "self", ".", "_send", "(", "http_method", "=", "'POST'", ",", "l...
54.583333
0.007508
def PopEvent(self): """Pops an event from the heap. Returns: tuple: containing: int: event timestamp or None if the heap is empty bytes: serialized event or None if the heap is empty """ try: timestamp, serialized_event = heapq.heappop(self._heap) self.data_size -= l...
[ "def", "PopEvent", "(", "self", ")", ":", "try", ":", "timestamp", ",", "serialized_event", "=", "heapq", ".", "heappop", "(", "self", ".", "_heap", ")", "self", ".", "data_size", "-=", "len", "(", "serialized_event", ")", "return", "timestamp", ",", "se...
24.294118
0.011655
def get_tunnel_statistics_output_next_page_cursor(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_tunnel_statistics = ET.Element("get_tunnel_statistics") config = get_tunnel_statistics output = ET.SubElement(get_tunnel_statistics, "output") ...
[ "def", "get_tunnel_statistics_output_next_page_cursor", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_tunnel_statistics", "=", "ET", ".", "Element", "(", "\"get_tunnel_statistics\"", ")", "config"...
44.166667
0.003697
def is_number(num, if_bool=False): """ :return: True if num is either an actual number, or an object that converts to one """ if isinstance(num, bool): return if_bool elif isinstance(num, int): return True try: number = float(num) return not (isnan(number) or isinf(numbe...
[ "def", "is_number", "(", "num", ",", "if_bool", "=", "False", ")", ":", "if", "isinstance", "(", "num", ",", "bool", ")", ":", "return", "if_bool", "elif", "isinstance", "(", "num", ",", "int", ")", ":", "return", "True", "try", ":", "number", "=", ...
30.75
0.005263
def inspect(self): """ Fetches information about the container from the client. """ policy = self.policy config_id = self.config_id if self.config_id.config_type == ItemType.VOLUME: if self.container_map.use_attached_parent_name: container_name...
[ "def", "inspect", "(", "self", ")", ":", "policy", "=", "self", ".", "policy", "config_id", "=", "self", ".", "config_id", "if", "self", ".", "config_id", ".", "config_type", "==", "ItemType", ".", "VOLUME", ":", "if", "self", ".", "container_map", ".", ...
45.105263
0.005714
def is_empty(value, msg=None, except_=None, inc_zeros=True): ''' is defined, but null or empty like value ''' if hasattr(value, 'empty'): # dataframes must check for .empty # since they don't define truth value attr # take the negative, since below we're # checking for ca...
[ "def", "is_empty", "(", "value", ",", "msg", "=", "None", ",", "except_", "=", "None", ",", "inc_zeros", "=", "True", ")", ":", "if", "hasattr", "(", "value", ",", "'empty'", ")", ":", "# dataframes must check for .empty", "# since they don't define truth value ...
33.272727
0.001328
def p_LD_reg_val(p): """ asm : LD reg8 COMMA expr | LD reg8 COMMA pexpr | LD reg16 COMMA expr | LD reg8_hl COMMA expr | LD A COMMA expr | LD SP COMMA expr | LD reg8i COMMA expr """ s = 'LD %s,N' % p[2] if p[2] in REGS16: s +...
[ "def", "p_LD_reg_val", "(", "p", ")", ":", "s", "=", "'LD %s,N'", "%", "p", "[", "2", "]", "if", "p", "[", "2", "]", "in", "REGS16", ":", "s", "+=", "'N'", "p", "[", "0", "]", "=", "Asm", "(", "p", ".", "lineno", "(", "1", ")", ",", "s", ...
25
0.002755
def purge_duplicates(list_in): """Remove duplicates from list while preserving order. Parameters ---------- list_in: Iterable Returns ------- list List of first occurences in order """ _list = [] for item in list_in: if item not in _list: _list.appen...
[ "def", "purge_duplicates", "(", "list_in", ")", ":", "_list", "=", "[", "]", "for", "item", "in", "list_in", ":", "if", "item", "not", "in", "_list", ":", "_list", ".", "append", "(", "item", ")", "return", "_list" ]
19.294118
0.002907
def _cook_slots(period, increment): """ Prepare slots to be displayed on the left hand side calculate dimensions (in px) for each slot. Arguments: period - time period for the whole series increment - slot size in minutes """ tdiff = datetime.timedelta(minutes=increme...
[ "def", "_cook_slots", "(", "period", ",", "increment", ")", ":", "tdiff", "=", "datetime", ".", "timedelta", "(", "minutes", "=", "increment", ")", "num", "=", "int", "(", "(", "period", ".", "end", "-", "period", ".", "start", ")", ".", "total_seconds...
33.470588
0.003419
def _clear(self) -> None: """ Resets the internal state of the simulator, and sets the simulated clock back to 0.0. This discards all outstanding events and tears down hanging process instances. """ for _, event, _, _ in self.events(): if hasattr(event, "__self__") an...
[ "def", "_clear", "(", "self", ")", "->", "None", ":", "for", "_", ",", "event", ",", "_", ",", "_", "in", "self", ".", "events", "(", ")", ":", "if", "hasattr", "(", "event", ",", "\"__self__\"", ")", "and", "isinstance", "(", "event", ".", "__se...
52
0.009452
def Profiler_setSamplingInterval(self, interval): """ Function path: Profiler.setSamplingInterval Domain: Profiler Method name: setSamplingInterval Parameters: Required arguments: 'interval' (type: integer) -> New sampling interval in microseconds. No return value. Description: Changes...
[ "def", "Profiler_setSamplingInterval", "(", "self", ",", "interval", ")", ":", "assert", "isinstance", "(", "interval", ",", "(", "int", ",", ")", ")", ",", "\"Argument 'interval' must be of type '['int']'. Received type: '%s'\"", "%", "type", "(", "interval", ")", ...
34.421053
0.043155
def parse_version(ver, pre=False): """Parse version into a comparable Version tuple.""" m = RE_VER.match(ver) # Handle major, minor, micro major = int(m.group('major')) minor = int(m.group('minor')) if m.group('minor') else 0 micro = int(m.group('micro')) if m.group('micro') else 0 # Hand...
[ "def", "parse_version", "(", "ver", ",", "pre", "=", "False", ")", ":", "m", "=", "RE_VER", ".", "match", "(", "ver", ")", "# Handle major, minor, micro", "major", "=", "int", "(", "m", ".", "group", "(", "'major'", ")", ")", "minor", "=", "int", "("...
27.633333
0.001166
def fetch(self): """ Fetch a UserChannelInstance :returns: Fetched UserChannelInstance :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, ...
[ "def", "fetch", "(", "self", ")", ":", "params", "=", "values", ".", "of", "(", "{", "}", ")", "payload", "=", "self", ".", "_version", ".", "fetch", "(", "'GET'", ",", "self", ".", "_uri", ",", "params", "=", "params", ",", ")", "return", "UserC...
26.727273
0.004926
def export_json(self, filename): """ Export graph in JSON form to the given file. """ json_graph = self.to_json() with open(filename, 'wb') as f: f.write(json_graph.encode('utf-8'))
[ "def", "export_json", "(", "self", ",", "filename", ")", ":", "json_graph", "=", "self", ".", "to_json", "(", ")", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "json_graph", ".", "encode", "(", "'utf-8'",...
28.375
0.008547
def add_tags(self, tags, **kwargs): """ :param tags: Tags to add to the object :type tags: list of strings Adds each of the specified tags to the remote object. Takes no action for tags that are already listed for the object. The tags are added to the copy of the object...
[ "def", "add_tags", "(", "self", ",", "tags", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_add_tags", "(", "self", ".", "_dxid", ",", "{", "\"project\"", ":", "self", ".", "_proj", ",", "\"tags\"", ":", "tags", "}", ",", "*", "*", "kwargs", "...
31.933333
0.004057
def _closeResources(self): """ Closes the root Dataset. """ logger.info("Closing: {}".format(self._fileName)) self._ncGroup.close() self._ncGroup = None
[ "def", "_closeResources", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Closing: {}\"", ".", "format", "(", "self", ".", "_fileName", ")", ")", "self", ".", "_ncGroup", ".", "close", "(", ")", "self", ".", "_ncGroup", "=", "None" ]
31.166667
0.010417
def __batch_evaluate(self, test_events): """Evaluate the current model by using the given test events. Args: test_events (list of Event): Current model is evaluated by these events. Returns: float: Mean Percentile Rank for the test set. """ percentiles ...
[ "def", "__batch_evaluate", "(", "self", ",", "test_events", ")", ":", "percentiles", "=", "np", ".", "zeros", "(", "len", "(", "test_events", ")", ")", "all_items", "=", "set", "(", "self", ".", "item_buffer", ")", "for", "i", ",", "e", "in", "enumerat...
36.066667
0.0036
def get_key(self, section, key): """ Gets key value from settings file. :param section: Current section to retrieve key from. :type section: unicode :param key: Current key to retrieve. :type key: unicode :return: Current key value. :rtype: object ...
[ "def", "get_key", "(", "self", ",", "section", ",", "key", ")", ":", "LOGGER", ".", "debug", "(", "\"> Retrieving '{0}' in '{1}' section.\"", ".", "format", "(", "key", ",", "section", ")", ")", "self", ".", "__settings", ".", "beginGroup", "(", "section", ...
29.55
0.004918
def download_blood_vessels(): """data representing the bifurcation of blood vessels.""" local_path, _ = _download_file('pvtu_blood_vessels/blood_vessels.zip') filename = os.path.join(local_path, 'T0000000500.pvtu') mesh = vtki.read(filename) mesh.set_active_vectors('velocity') return mesh
[ "def", "download_blood_vessels", "(", ")", ":", "local_path", ",", "_", "=", "_download_file", "(", "'pvtu_blood_vessels/blood_vessels.zip'", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "local_path", ",", "'T0000000500.pvtu'", ")", "mesh", "=", "v...
43.857143
0.003195
def invoke(self, ctx): """Given a context, this invokes the attached callback (if it exists) in the right way. """ if self.callback is not None: loop = asyncio.get_event_loop() return loop.run_until_complete(self.async_invoke(ctx))
[ "def", "invoke", "(", "self", ",", "ctx", ")", ":", "if", "self", ".", "callback", "is", "not", "None", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "return", "loop", ".", "run_until_complete", "(", "self", ".", "async_invoke", "(", "c...
40.142857
0.006969
def exclude_field(self, field, value, new_group=False): """Exclude a ``field:value`` term from the query. Matches will NOT have the ``value`` in the ``field``. Arguments: field (str): The field to check for the value. The field must be namespaced according to Ela...
[ "def", "exclude_field", "(", "self", ",", "field", ",", "value", ",", "new_group", "=", "False", ")", ":", "# No-op on missing arguments", "if", "not", "field", "and", "not", "value", ":", "return", "self", "# If not the start of the query string, add an AND", "# OR...
41.740741
0.004337
def autosolve(equation): """ Automatically solve an easy maths problem. :type equation: string :param equation: The equation to calculate. >>> autosolve("300 + 600") 900 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[0]) except Value...
[ "def", "autosolve", "(", "equation", ")", ":", "try", ":", "# Try to set a variable to an integer", "num1", "=", "int", "(", "equation", ".", "split", "(", "\" \"", ")", "[", "0", "]", ")", "except", "ValueError", ":", "# Try to set a variable to a decimal", "nu...
28.033898
0.000584
def GetTSKFileByPathSpec(self, path_spec): """Retrieves the SleuthKit file object for a path specification. Args: path_spec (PathSpec): path specification. Returns: pytsk3.File: TSK file. Raises: PathSpecError: if the path specification is missing inode and location. """ # O...
[ "def", "GetTSKFileByPathSpec", "(", "self", ",", "path_spec", ")", ":", "# Opening a file by inode number is faster than opening a file", "# by location.", "inode", "=", "getattr", "(", "path_spec", ",", "'inode'", ",", "None", ")", "location", "=", "getattr", "(", "p...
29.615385
0.005031
def updateColumnWidths(tag, cw, options): """ Update the column width attributes for this tag's fields. """ longforms = {"med": "median", "ave": "average", "min": "min", "total": "total", "max": "max",} for category in ["time", "clock",...
[ "def", "updateColumnWidths", "(", "tag", ",", "cw", ",", "options", ")", ":", "longforms", "=", "{", "\"med\"", ":", "\"median\"", ",", "\"ave\"", ":", "\"average\"", ",", "\"min\"", ":", "\"min\"", ",", "\"total\"", ":", "\"total\"", ",", "\"max\"", ":", ...
49.857143
0.002812
def list_all_transactions(cls, **kwargs): """List Transactions Return a list of Transactions This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_transactions(async=True) >>> resul...
[ "def", "list_all_transactions", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_list_all_transactions_with_http_info", "("...
37.391304
0.002268
def patch(self, client=None): """Sends all changed properties in a PATCH request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ...
[ "def", "patch", "(", "self", ",", "client", "=", "None", ")", ":", "client", "=", "self", ".", "_require_client", "(", "client", ")", "query_params", "=", "self", ".", "_query_params", "# Pass '?projection=full' here because 'PATCH' documented not", "# to work properl...
39.214286
0.002667
def write(self, nml_path, force=False, sort=False): """Write Namelist to a Fortran 90 namelist file. >>> nml = f90nml.read('input.nml') >>> nml.write('out.nml') """ nml_is_file = hasattr(nml_path, 'read') if not force and not nml_is_file and os.path.isfile(nml_path): ...
[ "def", "write", "(", "self", ",", "nml_path", ",", "force", "=", "False", ",", "sort", "=", "False", ")", ":", "nml_is_file", "=", "hasattr", "(", "nml_path", ",", "'read'", ")", "if", "not", "force", "and", "not", "nml_is_file", "and", "os", ".", "p...
36.375
0.00335
def sens_power_board_encode(self, timestamp, pwr_brd_status, pwr_brd_led_status, pwr_brd_system_volt, pwr_brd_servo_volt, pwr_brd_mot_l_amp, pwr_brd_mot_r_amp, pwr_brd_servo_1_amp, pwr_brd_servo_2_amp, pwr_brd_servo_3_amp, pwr_brd_servo_4_amp, pwr_brd_aux_amp): ''' Monitoring of power bo...
[ "def", "sens_power_board_encode", "(", "self", ",", "timestamp", ",", "pwr_brd_status", ",", "pwr_brd_led_status", ",", "pwr_brd_system_volt", ",", "pwr_brd_servo_volt", ",", "pwr_brd_mot_l_amp", ",", "pwr_brd_mot_r_amp", ",", "pwr_brd_servo_1_amp", ",", "pwr_brd_servo_2_am...
84.842105
0.007362
def _is_dtype_type(arr_or_dtype, condition): """ Return a boolean if the condition is satisfied for the arr_or_dtype. Parameters ---------- arr_or_dtype : array-like The array-like or dtype object whose dtype we want to extract. condition : callable[Union[np.dtype, ExtensionDtypeType]] ...
[ "def", "_is_dtype_type", "(", "arr_or_dtype", ",", "condition", ")", ":", "if", "arr_or_dtype", "is", "None", ":", "return", "condition", "(", "type", "(", "None", ")", ")", "# fastpath", "if", "isinstance", "(", "arr_or_dtype", ",", "np", ".", "dtype", ")...
28.6
0.000751
def update_environment(lib_directory): """Run the App as a subprocess.""" # Use this if you want to include modules from a subfolder # lib_path = os.path.realpath( # os.path.abspath( # os.path.join( # os.path.split(inspect.getfile(inspect.currentfr...
[ "def", "update_environment", "(", "lib_directory", ")", ":", "# Use this if you want to include modules from a subfolder", "# lib_path = os.path.realpath(", "# os.path.abspath(", "# os.path.join(", "# os.path.split(inspect.getfile(inspect.currentframe()))[0], lib_director...
45.857143
0.00458
def _output_ret(self, ret, out, retcode=0): ''' Print the output from a single return to the terminal ''' import salt.output # Handle special case commands if self.config['fun'] == 'sys.doc' and not isinstance(ret, Exception): self._print_docs(ret) els...
[ "def", "_output_ret", "(", "self", ",", "ret", ",", "out", ",", "retcode", "=", "0", ")", ":", "import", "salt", ".", "output", "# Handle special case commands", "if", "self", ".", "config", "[", "'fun'", "]", "==", "'sys.doc'", "and", "not", "isinstance",...
39.764706
0.00289
def _rapRperiAxiFindStart(R,E,L,pot,rap=False,startsign=1.): """ NAME: _rapRperiAxiFindStart PURPOSE: Find adequate start or end points to solve for rap and rperi INPUT: R - Galactocentric radius E - energy L - angular momentum pot - potential rap - if Tr...
[ "def", "_rapRperiAxiFindStart", "(", "R", ",", "E", ",", "L", ",", "pot", ",", "rap", "=", "False", ",", "startsign", "=", "1.", ")", ":", "if", "rap", ":", "rtry", "=", "2.", "*", "R", "else", ":", "rtry", "=", "R", "/", "2.", "while", "starts...
27.34375
0.01766
def crypto_sign(message, sk): """ Signs the message ``message`` using the secret key ``sk`` and returns the signed message. :param message: bytes :param sk: bytes :rtype: bytes """ signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES) signed_len = ffi.new("unsigned l...
[ "def", "crypto_sign", "(", "message", ",", "sk", ")", ":", "signed", "=", "ffi", ".", "new", "(", "\"unsigned char[]\"", ",", "len", "(", "message", ")", "+", "crypto_sign_BYTES", ")", "signed_len", "=", "ffi", ".", "new", "(", "\"unsigned long long *\"", ...
29.611111
0.001818
def daemonize(self): """Double-fork magic""" if self.userid: uid = pwd.getpwnam(self.userid).pw_uid os.seteuid(uid) try: pid = os.fork() if pid > 0: sys.exit(0) except OSError as err: sys.stderr.write("First fork...
[ "def", "daemonize", "(", "self", ")", ":", "if", "self", ".", "userid", ":", "uid", "=", "pwd", ".", "getpwnam", "(", "self", ".", "userid", ")", ".", "pw_uid", "os", ".", "seteuid", "(", "uid", ")", "try", ":", "pid", "=", "os", ".", "fork", "...
29.725
0.003257
def effect_emd(d1, d2): """Compute the EMD between two effect repertoires. Because the nodes are independent, the EMD between effect repertoires is equal to the sum of the EMDs between the marginal distributions of each node, and the EMD between marginal distribution for a node is the absolute diff...
[ "def", "effect_emd", "(", "d1", ",", "d2", ")", ":", "return", "sum", "(", "abs", "(", "marginal_zero", "(", "d1", ",", "i", ")", "-", "marginal_zero", "(", "d2", ",", "i", ")", ")", "for", "i", "in", "range", "(", "d1", ".", "ndim", ")", ")" ]
37.352941
0.001536
def err(*output, **kwargs): """Writes output to stderr. :arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap the output. """ output = 'Error: ' + ' '.join([str(o) for o in output]) if kwargs.get('wrap') is not False: output = '\n'.join(wrap(output, kwargs.get('indent',...
[ "def", "err", "(", "*", "output", ",", "*", "*", "kwargs", ")", ":", "output", "=", "'Error: '", "+", "' '", ".", "join", "(", "[", "str", "(", "o", ")", "for", "o", "in", "output", "]", ")", "if", "kwargs", ".", "get", "(", "'wrap'", ")", "i...
34.428571
0.00202
def raw_send(self, destination, message, **kwargs): """Send a raw (unmangled) message to a queue. This may cause errors if the receiver expects a mangled message. :param destination: Queue name to send to :param message: Either a string or a serializable object to be sent :param ...
[ "def", "raw_send", "(", "self", ",", "destination", ",", "message", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_send", "(", "destination", ",", "message", ",", "*", "*", "kwargs", ")" ]
58.461538
0.003886
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated(): """Dilated hparams.""" hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan() hparams.gap_sizes = [0, 16, 64, 0, 16, 64, 128, 0] hparams.dec_attention_type = cia.AttentionType.DILATED hparams.block_length = 128 hparams.block_width = 128 hpara...
[ "def", "imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated", "(", ")", ":", "hparams", "=", "imagetransformer_base_8l_8h_big_cond_dr03_dan", "(", ")", "hparams", ".", "gap_sizes", "=", "[", "0", ",", "16", ",", "64", ",", "0", ",", "16", ",", "64", ",", "128"...
40.666667
0.024064
def GetSources(self, event): """Determines the the short and long source for an event object. Args: event (EventObject): event. Returns: tuple(str, str): short and long source string. Raises: WrongFormatter: if the event object cannot be formatted by the formatter. """ if se...
[ "def", "GetSources", "(", "self", ",", "event", ")", ":", "if", "self", ".", "DATA_TYPE", "!=", "event", ".", "data_type", ":", "raise", "errors", ".", "WrongFormatter", "(", "'Unsupported data type: {0:s}.'", ".", "format", "(", "event", ".", "data_type", "...
31.136364
0.004249
def load_metadata(self, data_dir, feature_name=None): """See base class for details.""" # Restore names if defined names_filepath = _get_names_filepath(data_dir, feature_name) if tf.io.gfile.exists(names_filepath): self.names = _load_names_from_file(names_filepath)
[ "def", "load_metadata", "(", "self", ",", "data_dir", ",", "feature_name", "=", "None", ")", ":", "# Restore names if defined", "names_filepath", "=", "_get_names_filepath", "(", "data_dir", ",", "feature_name", ")", "if", "tf", ".", "io", ".", "gfile", ".", "...
47
0.006969
def msg_warn(message): """ Log a warning message :param message: the message to be logged """ to_stdout(" (!) {message}".format(message=message), colorf=yellow, bold=True) if _logger: _logger.warn(message)
[ "def", "msg_warn", "(", "message", ")", ":", "to_stdout", "(", "\" (!) {message}\"", ".", "format", "(", "message", "=", "message", ")", ",", "colorf", "=", "yellow", ",", "bold", "=", "True", ")", "if", "_logger", ":", "_logger", ".", "warn", "(", "me...
24.3
0.003968
def find_and_read_ebins(hdulist): """ Reads and returns the energy bin edges. This works for both the CASE where the energies are in the ENERGIES HDU and the case where they are in the EBOUND HDU """ from fermipy import utils ebins = None if 'ENERGIES' in hdulist: hdu = hdulist['EN...
[ "def", "find_and_read_ebins", "(", "hdulist", ")", ":", "from", "fermipy", "import", "utils", "ebins", "=", "None", "if", "'ENERGIES'", "in", "hdulist", ":", "hdu", "=", "hdulist", "[", "'ENERGIES'", "]", "ectr", "=", "hdu", ".", "data", ".", "field", "(...
35.222222
0.001536
def any_ends_with(self, string_list, pattern): """Returns true iff one of the strings in string_list ends in pattern.""" try: s_base = basestring except: s_base = str is_string = isinstance(pattern, s_base) if not is_string: return Fal...
[ "def", "any_ends_with", "(", "self", ",", "string_list", ",", "pattern", ")", ":", "try", ":", "s_base", "=", "basestring", "except", ":", "s_base", "=", "str", "is_string", "=", "isinstance", "(", "pattern", ",", "s_base", ")", "if", "not", "is_string", ...
26.4375
0.006849
def sendmess(self, msgtype, payload, flags=0, size=0, offset=0, timeout=0): """ retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data """ flags |= self.flags assert not (flags & FLG_PERSISTENCE) with self._new_connection() as conn: ...
[ "def", "sendmess", "(", "self", ",", "msgtype", ",", "payload", ",", "flags", "=", "0", ",", "size", "=", "0", ",", "offset", "=", "0", ",", "timeout", "=", "0", ")", ":", "flags", "|=", "self", ".", "flags", "assert", "not", "(", "flags", "&", ...
33.230769
0.004505
def Search(self, text): """Search the text for our value.""" if isinstance(text, rdfvalue.RDFString): text = str(text) return self._regex.search(text)
[ "def", "Search", "(", "self", ",", "text", ")", ":", "if", "isinstance", "(", "text", ",", "rdfvalue", ".", "RDFString", ")", ":", "text", "=", "str", "(", "text", ")", "return", "self", ".", "_regex", ".", "search", "(", "text", ")" ]
27.333333
0.011834
def _register_blueprint(self, app, bp, bundle_path, child_path, description): """Register and return info about the registered blueprint :param bp: :class:`flask.Blueprint` object :param bundle_path: the URL prefix of the bundle :param child_path: blueprint relative to the bundle path ...
[ "def", "_register_blueprint", "(", "self", ",", "app", ",", "bp", ",", "bundle_path", ",", "child_path", ",", "description", ")", ":", "base_path", "=", "sanitize_path", "(", "self", ".", "_journey_path", "+", "bundle_path", "+", "child_path", ")", "app", "....
36.95
0.003958
def get_instance(self, payload): """ Build an instance of AuthCallsIpAccessControlListMappingInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsI...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "AuthCallsIpAccessControlListMappingInstance", "(", "self", ".", "_version", ",", "payload", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "domain_sid", ...
50
0.005236
def append_child ( self, object, child ): """ Appends a child to the object's children. """ if isinstance( child, Subgraph ): object.subgraphs.append( child ) elif isinstance( child, Cluster ): object.clusters.append( child ) elif isinstance( child, Node...
[ "def", "append_child", "(", "self", ",", "object", ",", "child", ")", ":", "if", "isinstance", "(", "child", ",", "Subgraph", ")", ":", "object", ".", "subgraphs", ".", "append", "(", "child", ")", "elif", "isinstance", "(", "child", ",", "Cluster", ")...
27.176471
0.043933
def router_added_to_hosting_device(self, context, router): """Notify cfg agent about router added to hosting device.""" self._notification(context, 'router_added_to_hosting_device', [router], operation=None, shuffle_agents=False)
[ "def", "router_added_to_hosting_device", "(", "self", ",", "context", ",", "router", ")", ":", "self", ".", "_notification", "(", "context", ",", "'router_added_to_hosting_device'", ",", "[", "router", "]", ",", "operation", "=", "None", ",", "shuffle_agents", "...
67.25
0.007353
def _authenticate(self): """Authenticate user and generate token.""" self.cleanup_headers() url = LOGIN_ENDPOINT data = self.query( url, method='POST', extra_params={ 'email': self.__username, 'password': self.__password...
[ "def", "_authenticate", "(", "self", ")", ":", "self", ".", "cleanup_headers", "(", ")", "url", "=", "LOGIN_ENDPOINT", "data", "=", "self", ".", "query", "(", "url", ",", "method", "=", "'POST'", ",", "extra_params", "=", "{", "'email'", ":", "self", "...
35.636364
0.002484
def _roundSlist(slist): """ Rounds a signed list over the last element and removes it. """ slist[-1] = 60 if slist[-1] >= 30 else 0 for i in range(len(slist)-1, 1, -1): if slist[i] == 60: slist[i] = 0 slist[i-1] += 1 return slist[:-1]
[ "def", "_roundSlist", "(", "slist", ")", ":", "slist", "[", "-", "1", "]", "=", "60", "if", "slist", "[", "-", "1", "]", ">=", "30", "else", "0", "for", "i", "in", "range", "(", "len", "(", "slist", ")", "-", "1", ",", "1", ",", "-", "1", ...
34.375
0.003546
def index_to_time_seg(time_seg_idx, slide_step): """ 将时间片索引值转换为时间片字符串 :param time_seg_idx: :param slide_step: :return: """ assert (time_seg_idx * slide_step < const.MINUTES_IN_A_DAY) return time_util.minutes_to_time_str(time_seg_idx * slide_step)
[ "def", "index_to_time_seg", "(", "time_seg_idx", ",", "slide_step", ")", ":", "assert", "(", "time_seg_idx", "*", "slide_step", "<", "const", ".", "MINUTES_IN_A_DAY", ")", "return", "time_util", ".", "minutes_to_time_str", "(", "time_seg_idx", "*", "slide_step", "...
30
0.003597
def get_upload_path(self): """Returns the uploaded file path from the storage backend. :returns: File path from the storage backend. :rtype: :py:class:`unicode` """ location = self.get_storage().location return self.cleaned_data['key_name'][len(location):]
[ "def", "get_upload_path", "(", "self", ")", ":", "location", "=", "self", ".", "get_storage", "(", ")", ".", "location", "return", "self", ".", "cleaned_data", "[", "'key_name'", "]", "[", "len", "(", "location", ")", ":", "]" ]
33.111111
0.006536
def bind(self, values): """ Binds a sequence of values for the prepared statement parameters and returns this instance. Note that `values` *must* be: * a sequence, even if you are only binding one value, or * a dict that relates 1-to-1 between dict keys and columns .. ...
[ "def", "bind", "(", "self", ",", "values", ")", ":", "if", "values", "is", "None", ":", "values", "=", "(", ")", "proto_version", "=", "self", ".", "prepared_statement", ".", "protocol_version", "col_meta", "=", "self", ".", "prepared_statement", ".", "col...
40.892857
0.003695
def get_item_prices(self, package_id): """Get item prices. Retrieve a SoftLayer_Product_Package item prices record. :param int package_id: package identifier. :returns: A list of price IDs associated with the given package. """ mask = 'mask[pricingLocationGroup[locatio...
[ "def", "get_item_prices", "(", "self", ",", "package_id", ")", ":", "mask", "=", "'mask[pricingLocationGroup[locations]]'", "prices", "=", "self", ".", "package_svc", ".", "getItemPrices", "(", "id", "=", "package_id", ",", "mask", "=", "mask", ")", "return", ...
31.538462
0.004739
def m2m_changed_handler(sender, *args, **kwargs): """ A model's save() never gets called on ManyToManyField changes, m2m_changed-signal is sent. sender = dynamically generated model in m2m-table instance = parent related_instance = instance being m2m'ed """ action = kwargs['action'] inst...
[ "def", "m2m_changed_handler", "(", "sender", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "action", "=", "kwargs", "[", "'action'", "]", "instance", "=", "kwargs", "[", "'instance'", "]", "logger", ".", "debug", "(", "\"m2m_changed: %s (%s) {%s}\"", ...
47.5
0.004052
def listFileParentsByLumi(self): """ IMPORTANT: This is ***WMAgent*** sepcial case API. It is not for others. API to list File Parentage for a given block with or w/o a list of LFN. It is used with the POST method of fileparents call. Using the child_lfn_list will significantly affect ...
[ "def", "listFileParentsByLumi", "(", "self", ")", ":", "try", ":", "body", "=", "request", ".", "body", ".", "read", "(", ")", "if", "body", ":", "data", "=", "cjson", ".", "decode", "(", "body", ")", "data", "=", "validateJSONInputNoCopy", "(", "'file...
52.938776
0.011734
def disconnect(self, cback, subscribers=None, instance=None): """Remove a previously added function or method from the set of the signal's handlers. :param cback: the callback (or *handler*) to be added to the set :returns: ``None`` or the value returned by the corresponding wrapper ...
[ "def", "disconnect", "(", "self", ",", "cback", ",", "subscribers", "=", "None", ",", "instance", "=", "None", ")", ":", "if", "subscribers", "is", "None", ":", "subscribers", "=", "self", ".", "subscribers", "# wrapper", "if", "self", ".", "_fdisconnect",...
40.851852
0.001771
def ltrim(self, key, start, stop): """Emulate ltrim.""" redis_list = self._get_list(key, 'LTRIM') if redis_list: start, stop = self._translate_range(len(redis_list), start, stop) self.redis[self._encode(key)] = redis_list[start:stop + 1] return True
[ "def", "ltrim", "(", "self", ",", "key", ",", "start", ",", "stop", ")", ":", "redis_list", "=", "self", ".", "_get_list", "(", "key", ",", "'LTRIM'", ")", "if", "redis_list", ":", "start", ",", "stop", "=", "self", ".", "_translate_range", "(", "len...
42.714286
0.006557
def _trim_env_off_path(paths, saltenv, trim_slash=False): ''' Return a list of file paths with the saltenv directory removed ''' env_len = None if _is_env_per_bucket() else len(saltenv) + 1 slash_len = -1 if trim_slash else None return [d[env_len:slash_len] for d in paths]
[ "def", "_trim_env_off_path", "(", "paths", ",", "saltenv", ",", "trim_slash", "=", "False", ")", ":", "env_len", "=", "None", "if", "_is_env_per_bucket", "(", ")", "else", "len", "(", "saltenv", ")", "+", "1", "slash_len", "=", "-", "1", "if", "trim_slas...
36.375
0.003356
def changed(self): """Returns dict of fields that changed since save (with old values)""" return dict( (field, self.previous(field)) for field in self.fields if self.has_changed(field) )
[ "def", "changed", "(", "self", ")", ":", "return", "dict", "(", "(", "field", ",", "self", ".", "previous", "(", "field", ")", ")", "for", "field", "in", "self", ".", "fields", "if", "self", ".", "has_changed", "(", "field", ")", ")" ]
34.285714
0.00813
def session_dump(self, cell, hash, fname_session): """ Dump ipython session to file :param hash: cell hash :param fname_session: output filename :return: """ logging.debug('Cell {}: Dumping session to {}'.format(hash, fname_session)) inject_code = ['impo...
[ "def", "session_dump", "(", "self", ",", "cell", ",", "hash", ",", "fname_session", ")", ":", "logging", ".", "debug", "(", "'Cell {}: Dumping session to {}'", ".", "format", "(", "hash", ",", "fname_session", ")", ")", "inject_code", "=", "[", "'import dill'"...
35
0.005213
def on_subscript(self, node): # ('value', 'slice', 'ctx') """Subscript handling -- one of the tricky parts.""" val = self.run(node.value) nslice = self.run(node.slice) ctx = node.ctx.__class__ if ctx in (ast.Load, ast.Store): if isinstance(node.slice, (ast.Index, a...
[ "def", "on_subscript", "(", "self", ",", "node", ")", ":", "# ('value', 'slice', 'ctx')", "val", "=", "self", ".", "run", "(", "node", ".", "value", ")", "nslice", "=", "self", ".", "run", "(", "node", ".", "slice", ")", "ctx", "=", "node", ".", "ctx...
44.846154
0.003361
def sync_heater_control(self, device_id, fan_status=None, power_status=None): """Set heater temps.""" loop = asyncio.get_event_loop() task = loop.create_task(self.heater_control(device_id, fan_status, ...
[ "def", "sync_heater_control", "(", "self", ",", "device_id", ",", "fan_status", "=", "None", ",", "power_status", "=", "None", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "task", "=", "loop", ".", "create_task", "(", "self", ".", "...
50.25
0.007335
def cli(ctx, id_number, new_key, metadata=""): """Update a canned key Output: an empty dictionary """ return ctx.gi.cannedkeys.update_key(id_number, new_key, metadata=metadata)
[ "def", "cli", "(", "ctx", ",", "id_number", ",", "new_key", ",", "metadata", "=", "\"\"", ")", ":", "return", "ctx", ".", "gi", ".", "cannedkeys", ".", "update_key", "(", "id_number", ",", "new_key", ",", "metadata", "=", "metadata", ")" ]
23.375
0.005155
def hacking_python3x_except_compatible(logical_line, noqa): r"""Check for except statements to be Python 3.x compatible As of Python 3.x, the construct 'except x,y:' has been removed. Use 'except x as y:' instead. Okay: try:\n pass\nexcept Exception:\n pass Okay: try:\n pass\nexcept (Exc...
[ "def", "hacking_python3x_except_compatible", "(", "logical_line", ",", "noqa", ")", ":", "if", "noqa", ":", "return", "def", "is_old_style_except", "(", "logical_line", ")", ":", "return", "(", "','", "in", "logical_line", "and", "')'", "not", "in", "logical_lin...
37.217391
0.001139
def triangle_plots(self, basename=None, format='png', **kwargs): """Returns two triangle plots, one with physical params, one observational :param basename: If basename is provided, then plots will be saved as "[basename]_physical.[format]" and "[basename]...
[ "def", "triangle_plots", "(", "self", ",", "basename", "=", "None", ",", "format", "=", "'png'", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "fit_for_distance", ":", "fig1", "=", "self", ".", "triangle", "(", "plot_datapoints", "=", "False", ...
39.102564
0.013436
def GetAll(cls, attr, value, e=0.000001, sort_by="__name__"): """Get all nested Constant class that met ``klass.attr == value``. :param attr: attribute name. :param value: value. :param e: used for float value comparison. :param sort_by: nested class is ordered by <sort_by> attr...
[ "def", "GetAll", "(", "cls", ",", "attr", ",", "value", ",", "e", "=", "0.000001", ",", "sort_by", "=", "\"__name__\"", ")", ":", "matched", "=", "list", "(", ")", "for", "_", ",", "klass", "in", "cls", ".", "Subclasses", "(", "sort_by", "=", "sort...
33.684211
0.004559
def _pack_cwl(unpacked_cwl): """Pack CWL into a single document for submission. """ out_file = "%s-pack%s" % os.path.splitext(unpacked_cwl) cmd = "cwltool --pack {unpacked_cwl} > {out_file}" _run_tool(cmd.format(**locals())) return out_file
[ "def", "_pack_cwl", "(", "unpacked_cwl", ")", ":", "out_file", "=", "\"%s-pack%s\"", "%", "os", ".", "path", ".", "splitext", "(", "unpacked_cwl", ")", "cmd", "=", "\"cwltool --pack {unpacked_cwl} > {out_file}\"", "_run_tool", "(", "cmd", ".", "format", "(", "*"...
36.857143
0.003788
def get_current(self): """ Returns the current ``UserSettings`` based on the SITE_ID in the project's settings. The ``UserSettings`` object is cached the first time it's retrieved from the database. """ from django.conf import settings try: site_id = s...
[ "def", "get_current", "(", "self", ")", ":", "from", "django", ".", "conf", "import", "settings", "try", ":", "site_id", "=", "settings", ".", "SITE_ID", "except", "AttributeError", ":", "raise", "ImproperlyConfigured", "(", "'You\\'re using the Django \"sites frame...
41.238095
0.002257
def mult(self, matrix): """ Multiply this frame, viewed as a matrix, by another matrix. :param matrix: another frame that you want to multiply the current frame by; must be compatible with the current frame (i.e. its number of rows must be the same as number of columns in the curren...
[ "def", "mult", "(", "self", ",", "matrix", ")", ":", "if", "self", ".", "ncols", "!=", "matrix", ".", "nrows", ":", "raise", "H2OValueError", "(", "\"Matrix is not compatible for multiplication with the current frame\"", ")", "return", "H2OFrame", ".", "_expr", "(...
57.818182
0.009288
def _get_port_speed_price_id(items, port_speed, no_public, location): """Choose a valid price id for port speed.""" for item in items: if utils.lookup(item, 'itemCategory', 'categoryCode') != 'port_speed': continue # Check for correct...
[ "def", "_get_port_speed_price_id", "(", "items", ",", "port_speed", ",", "no_public", ",", "location", ")", ":", "for", "item", "in", "items", ":", "if", "utils", ".", "lookup", "(", "item", ",", "'itemCategory'", ",", "'categoryCode'", ")", "!=", "'port_spe...
34.565217
0.001224
def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFlag=False): """ Extract keywords from sentence using TF-IDF algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (wo...
[ "def", "extract_tags", "(", "self", ",", "sentence", ",", "topK", "=", "20", ",", "withWeight", "=", "False", ",", "allowPOS", "=", "(", ")", ",", "withFlag", "=", "False", ")", ":", "if", "allowPOS", ":", "allowPOS", "=", "frozenset", "(", "allowPOS",...
41.761905
0.003343
def mix_columns(state): """ Transformation in the Cipher that takes all of the columns of the State and mixes their data (independently of one another) to produce new columns. """ state = state.reshape(4, 4, 8) return fcat( multiply(MA, state[0]), multiply(MA, state[1]), ...
[ "def", "mix_columns", "(", "state", ")", ":", "state", "=", "state", ".", "reshape", "(", "4", ",", "4", ",", "8", ")", "return", "fcat", "(", "multiply", "(", "MA", ",", "state", "[", "0", "]", ")", ",", "multiply", "(", "MA", ",", "state", "[...
30.833333
0.002625
def ite_burrowed(self): """ Returns an equivalent AST that "burrows" the ITE expressions as deep as possible into the ast, for simpler printing. """ if self._burrowed is None: self._burrowed = self._burrow_ite() # pylint:disable=attribute-defined-outside-init ...
[ "def", "ite_burrowed", "(", "self", ")", ":", "if", "self", ".", "_burrowed", "is", "None", ":", "self", ".", "_burrowed", "=", "self", ".", "_burrow_ite", "(", ")", "# pylint:disable=attribute-defined-outside-init", "self", ".", "_burrowed", ".", "_burrowed", ...
48.555556
0.011236