text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def StartsWith(self, value): """Sets the type of the WHERE clause as "starts with". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, 'STARTS_WITH') return ...
[ "def", "StartsWith", "(", "self", ",", "value", ")", ":", "self", ".", "_awql", "=", "self", ".", "_CreateSingleValueCondition", "(", "value", ",", "'STARTS_WITH'", ")", "return", "self", ".", "_query_builder" ]
29.909091
0.00295
def _replace_global_vars(xs, global_vars): """Replace globally shared names from input header with value. The value of the `algorithm` item may be a pointer to a real file specified in the `global` section. If found, replace with the full value. """ if isinstance(xs, (list, tuple)): ret...
[ "def", "_replace_global_vars", "(", "xs", ",", "global_vars", ")", ":", "if", "isinstance", "(", "xs", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "_replace_global_vars", "(", "x", ")", "for", "x", "in", "xs", "]", "elif", "isinstance...
33.555556
0.00161
def write_hfb_template(m): """write a template file for an hfb (yuck!) Parameters ---------- m : flopy.modflow.Modflow instance with an HFB file Returns ------- (tpl_filename, df) : (str, pandas.DataFrame) the name of the template file and a dataframe with useful info. ...
[ "def", "write_hfb_template", "(", "m", ")", ":", "assert", "m", ".", "hfb6", "is", "not", "None", "hfb_file", "=", "os", ".", "path", ".", "join", "(", "m", ".", "model_ws", ",", "m", ".", "hfb6", ".", "file_name", "[", "0", "]", ")", "assert", "...
31.26087
0.016629
def asDictionary(self): """ returns the envelope as a dictionary """ template = { "xmin" : self._xmin, "ymin" : self._ymin, "xmax" : self._xmax, "ymax" : self._ymax, "spatialReference" : self.spatialReference } if self._zmax is ...
[ "def", "asDictionary", "(", "self", ")", ":", "template", "=", "{", "\"xmin\"", ":", "self", ".", "_xmin", ",", "\"ymin\"", ":", "self", ".", "_ymin", ",", "\"xmax\"", ":", "self", ".", "_xmax", ",", "\"ymax\"", ":", "self", ".", "_ymax", ",", "\"spa...
30.95
0.010972
def is_result_edition_allowed(self, analysis_brain): """Checks if the edition of the result field is allowed :param analysis_brain: Brain that represents an analysis :return: True if the user can edit the result field, otherwise False """ # Always check general edition first ...
[ "def", "is_result_edition_allowed", "(", "self", ",", "analysis_brain", ")", ":", "# Always check general edition first", "if", "not", "self", ".", "is_analysis_edition_allowed", "(", "analysis_brain", ")", ":", "return", "False", "# Get the ananylsis object", "obj", "=",...
35.16
0.002215
def get_neighbour_keys(self, bucket_key, k): """ The computing complexity is O( np*beam*log(np*beam) ) where, np = number of permutations beam = self.beam_size Make sure np*beam is much less than the number of bucket keys, otherwise we could use brute-force to ge...
[ "def", "get_neighbour_keys", "(", "self", ",", "bucket_key", ",", "k", ")", ":", "# convert query_key into bitarray", "query_key", "=", "bitarray", "(", "bucket_key", ")", "topk", "=", "set", "(", ")", "for", "i", "in", "xrange", "(", "len", "(", "self", "...
37.230769
0.003021
def _toState(self, state, *args, **kwargs): """ Transition to the next state. @param state: Name of the next state. """ try: method = getattr(self, '_state_%s' % state) except AttributeError: raise ValueError("No such state %r" % state) l...
[ "def", "_toState", "(", "self", ",", "state", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "method", "=", "getattr", "(", "self", ",", "'_state_%s'", "%", "state", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", ...
30.5
0.004545
def consistency_point(self): """ Collector for getting count of consistancy points """ cp_delta = {} xml_path = 'instances/instance-data/counters' netapp_api = NaElement('perf-object-get-instances') netapp_api.child_add_string('objectname', 'wafl') instance = NaE...
[ "def", "consistency_point", "(", "self", ")", ":", "cp_delta", "=", "{", "}", "xml_path", "=", "'instances/instance-data/counters'", "netapp_api", "=", "NaElement", "(", "'perf-object-get-instances'", ")", "netapp_api", ".", "child_add_string", "(", "'objectname'", ",...
32.857143
0.000844
def run_query_segments(doc, proc_id, engine, gps_start_time, gps_end_time, included_segments_string, excluded_segments_string = None, write_segments = True, start_pad = 0, end_pad = 0): """Runs a segment query. This was originally part of ligolw_query_segments, but now is also used by ligolw_segments_from_cats...
[ "def", "run_query_segments", "(", "doc", ",", "proc_id", ",", "engine", ",", "gps_start_time", ",", "gps_end_time", ",", "included_segments_string", ",", "excluded_segments_string", "=", "None", ",", "write_segments", "=", "True", ",", "start_pad", "=", "0", ",", ...
41.369565
0.012834
def _extract_spi_args(self, **kwargs): """ Given a set of keyword arguments, splits it into those relevant to SPI implementations and all the rest. SPI arguments are augmented with defaults and converted into the pin format (from the port/device format) if necessary. Ret...
[ "def", "_extract_spi_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "dev_defaults", "=", "{", "'port'", ":", "0", ",", "'device'", ":", "0", ",", "}", "default_hw", "=", "SPI_HARDWARE_PINS", "[", "dev_defaults", "[", "'port'", "]", "]", "pin_defa...
39.803279
0.001206
def _ExtractGoogleDocsSearchQuery(self, url): """Extracts a search query from a Google docs URL. Google Docs: https://docs.google.com/.*/u/0/?q=query Args: url (str): URL. Returns: str: search query or None if no query was found. """ if 'q=' not in url: return None lin...
[ "def", "_ExtractGoogleDocsSearchQuery", "(", "self", ",", "url", ")", ":", "if", "'q='", "not", "in", "url", ":", "return", "None", "line", "=", "self", ".", "_GetBetweenQEqualsAndAmpersand", "(", "url", ")", "if", "not", "line", ":", "return", "None", "re...
21.894737
0.006912
async def send_job_result(self, job_id: BackendJobId, result: str, text: str = "", grade: float = None, problems: Dict[str, SPResult] = None, tests: Dict[str, Any] = None, custom: Dict[str, Any] = None, state: str = "", archive: Optional[bytes] = None, stdout:...
[ "async", "def", "send_job_result", "(", "self", ",", "job_id", ":", "BackendJobId", ",", "result", ":", "str", ",", "text", ":", "str", "=", "\"\"", ",", "grade", ":", "float", "=", "None", ",", "problems", ":", "Dict", "[", "str", ",", "SPResult", "...
49.166667
0.008313
def angular_separation(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. """ xp1, yp1, zp1 = lonlat2xyz(lonp1, latp1) ...
[ "def", "angular_separation", "(", "lonp1", ",", "latp1", ",", "lonp2", ",", "latp2", ")", ":", "xp1", ",", "yp1", ",", "zp1", "=", "lonlat2xyz", "(", "lonp1", ",", "latp1", ")", "xp2", ",", "yp2", ",", "zp2", "=", "lonlat2xyz", "(", "lonp2", ",", "...
30.294118
0.00565
async def download_file(self, url: str) -> bytes: """ Download a file from the content repository. See also: `API reference`_ Args: url: The MXC URI to download. Returns: The raw downloaded data. .. _API reference: https://matrix.org/docs/spe...
[ "async", "def", "download_file", "(", "self", ",", "url", ":", "str", ")", "->", "bytes", ":", "await", "self", ".", "ensure_registered", "(", ")", "url", "=", "self", ".", "client", ".", "get_download_url", "(", "url", ")", "async", "with", "self", "....
34.117647
0.003356
def consistent_with(event, evidence): "Is event consistent with the given evidence?" return every(lambda (k, v): evidence.get(k, v) == v, event.items())
[ "def", "consistent_with", "(", "event", ",", "evidence", ")", ":", "return", "every", "(", "lambda", "(", "k", ",", "v", ")", ":", "evidence", ".", "get", "(", "k", ",", "v", ")", "==", "v", ",", "event", ".", "items", "(", ")", ")" ]
43.5
0.00565
def enable(self): """Enable the stream thread This operation will ensure that the thread that is responsible for connecting to the WVA and triggering event callbacks is started. This thread will continue to run and do what it needs to do to maintain a connection to the WVA. ...
[ "def", "enable", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_event_listener_thread", "is", "None", ":", "self", ".", "_event_listener_thread", "=", "WVAEventListenerThread", "(", "self", ",", "self", ".", "_http_client", ")...
44.214286
0.006329
def get(self, request, pk): """ Handles GET requests. """ self.forum = get_object_or_404(Forum, pk=pk) return super().get(request, pk)
[ "def", "get", "(", "self", ",", "request", ",", "pk", ")", ":", "self", ".", "forum", "=", "get_object_or_404", "(", "Forum", ",", "pk", "=", "pk", ")", "return", "super", "(", ")", ".", "get", "(", "request", ",", "pk", ")" ]
38.75
0.012658
def get_cheapest_price_by_date(self, **params): """ {API_HOST}/apiservices/browsedates/v1.0/{market}/{currency}/{locale}/ {originPlace}/{destinationPlace}/ {outboundPartialDate}/{inboundPartialDate} ?apiKey={apiKey} """ service_url = "{url}/{params_path}".format( ...
[ "def", "get_cheapest_price_by_date", "(", "self", ",", "*", "*", "params", ")", ":", "service_url", "=", "\"{url}/{params_path}\"", ".", "format", "(", "url", "=", "self", ".", "BROWSE_DATES_SERVICE_URL", ",", "params_path", "=", "self", ".", "_construct_params", ...
33.055556
0.003268
def copy_submission_to_destination(self, src_filename, dst_subdir, submission_id): """Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be...
[ "def", "copy_submission_to_destination", "(", "self", ",", "src_filename", ",", "dst_subdir", ",", "submission_id", ")", ":", "extension", "=", "[", "e", "for", "e", "in", "ALLOWED_EXTENSIONS", "if", "src_filename", ".", "endswith", "(", "e", ")", "]", "if", ...
41.73913
0.00611
def config_dir_setup(filename): """ sets the config file and makes sure the directory exists if it has not yet been created. :param filename: :return: """ path = os.path.dirname(filename) if not os.path.isdir(path): Shell.mkdir(path)
[ "def", "config_dir_setup", "(", "filename", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "Shell", ".", "mkdir", "(", "path", ")" ]
29.222222
0.01476
def poll(self, id): """ Fetch information about the poll with the given id Returns a `poll dict`_. """ id = self.__unpack_id(id) url = '/api/v1/polls/{0}'.format(str(id)) return self.__api_request('GET', url)
[ "def", "poll", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/polls/{0}'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'GET'", ",", "u...
28.555556
0.007547
def reload_if_changed(self, force=False): """If the file(s) being watched by this object have changed, their configuration will be loaded again using `config_loader`. Otherwise this is a noop. :param force: If True ignore the `min_interval` and proceed to file modified compa...
[ "def", "reload_if_changed", "(", "self", ",", "force", "=", "False", ")", ":", "if", "(", "force", "or", "self", ".", "should_check", ")", "and", "self", ".", "file_modified", "(", ")", ":", "return", "self", ".", "reload", "(", ")" ]
44.363636
0.004016
def merkle_pair(hashes, hash_f): """Take a list of hashes, and return the parent row in the tree of merkle hashes.""" if len(hashes) % 2 == 1: hashes = list(hashes) hashes.append(hashes[-1]) items = [] for i in range(0, len(hashes), 2): items.append(hash_f(hashes[i] + hashes[i+1]...
[ "def", "merkle_pair", "(", "hashes", ",", "hash_f", ")", ":", "if", "len", "(", "hashes", ")", "%", "2", "==", "1", ":", "hashes", "=", "list", "(", "hashes", ")", "hashes", ".", "append", "(", "hashes", "[", "-", "1", "]", ")", "items", "=", "...
36.777778
0.0059
def load_data(self): """ Loads data files and stores the output in the data attribute. """ data = [] valid_dates = [] mrms_files = np.array(sorted(os.listdir(self.path + self.variable + "/"))) mrms_file_dates = np.array([m_file.split("_")[-2].split("-")[0] ...
[ "def", "load_data", "(", "self", ")", ":", "data", "=", "[", "]", "valid_dates", "=", "[", "]", "mrms_files", "=", "np", ".", "array", "(", "sorted", "(", "os", ".", "listdir", "(", "self", ".", "path", "+", "self", ".", "variable", "+", "\"/\"", ...
47.102564
0.0064
def parse_compound_table_file(path, f): """Parse a tab-separated file containing compound IDs and properties The compound properties are parsed according to the header which specifies which property is contained in each column. """ context = FilePathContext(path) for i, row in enumerate(csv.D...
[ "def", "parse_compound_table_file", "(", "path", ",", "f", ")", ":", "context", "=", "FilePathContext", "(", "path", ")", "for", "i", ",", "row", "in", "enumerate", "(", "csv", ".", "DictReader", "(", "f", ",", "delimiter", "=", "str", "(", "'\\t'", ")...
35.05
0.001389
def rescan_file(self, resource, date='', period='', repeat='', notify_url='', notify_changes_only='', timeout=None): """ Rescan a previously submitted filed or schedule an scan to be performed in the future. This API allows you to rescan files present in VirusTotal's file store without having to ...
[ "def", "rescan_file", "(", "self", ",", "resource", ",", "date", "=", "''", ",", "period", "=", "''", ",", "repeat", "=", "''", ",", "notify_url", "=", "''", ",", "notify_changes_only", "=", "''", ",", "timeout", "=", "None", ")", ":", "params", "=",...
67.970588
0.008532
def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params): """Train survival model on given data and return its score on test data""" X_train, y_train = _safe_split(est, x, y, train_index) train_params = fit_params.copy() # Training est.set_params(**para...
[ "def", "_fit_and_score", "(", "est", ",", "x", ",", "y", ",", "scorer", ",", "train_index", ",", "test_index", ",", "parameters", ",", "fit_params", ",", "predict_params", ")", ":", "X_train", ",", "y_train", "=", "_safe_split", "(", "est", ",", "x", ","...
39.315789
0.002614
def set_value(self, qsid, new): # Set value & encode new to be passed to QSUSB """Set a value.""" try: dev = self[qsid] except KeyError: raise KeyError("Device {} not found".format(qsid)) if new < 0: new = 0 if new == dev.value: ...
[ "def", "set_value", "(", "self", ",", "qsid", ",", "new", ")", ":", "# Set value & encode new to be passed to QSUSB", "try", ":", "dev", "=", "self", "[", "qsid", "]", "except", "KeyError", ":", "raise", "KeyError", "(", "\"Device {} not found\"", ".", "format",...
33.807692
0.003319
def get_period_options(self): """ Given the current setting in report_period_type, returns a list of options (suitable for select) as an array or pairs telling the valid periods to select. :return: An array of period options. """ if self.report_period_type == 'ago': ...
[ "def", "get_period_options", "(", "self", ")", ":", "if", "self", ".", "report_period_type", "==", "'ago'", ":", "return", "PERIOD_AGO_LOOKUPS", "elif", "self", ".", "report_period_type", "==", "'current'", ":", "return", "PERIOD_CURRENT_LOOKUPS", "elif", "self", ...
43.8
0.005961
def write_cyc(fn, this, conv=1.0): """ Write the lattice information to a cyc.dat file (i.e., tblmd input file) """ lattice = this.get_cell() f = paropen(fn, "w") f.write("<------- Simulation box definition\n") f.write("<------- Barostat (on = 1, off = 0)\n") f.write(" 0\n") f.write("...
[ "def", "write_cyc", "(", "fn", ",", "this", ",", "conv", "=", "1.0", ")", ":", "lattice", "=", "this", ".", "get_cell", "(", ")", "f", "=", "paropen", "(", "fn", ",", "\"w\"", ")", "f", ".", "write", "(", "\"<------- Simulation box definition\\n\"", ")...
47.655172
0.006383
def _suffix_rules(token, tag="NN"): """ Default morphological tagging rules for English, based on word suffixes. """ if isinstance(token, (list, tuple)): token, tag = token if token.endswith("ing"): tag = "VBG" if token.endswith("ly"): tag = "RB" if token.endswith("s") an...
[ "def", "_suffix_rules", "(", "token", ",", "tag", "=", "\"NN\"", ")", ":", "if", "isinstance", "(", "token", ",", "(", "list", ",", "tuple", ")", ")", ":", "token", ",", "tag", "=", "token", "if", "token", ".", "endswith", "(", "\"ing\"", ")", ":",...
35.777778
0.004539
def encrypt(self, key=None, iv="", cek="", **kwargs): """ Produces a JWE as defined in RFC7516 using an Elliptic curve key :param key: *Not used>, only there to present the same API as JWE_RSA and JWE_SYM :param iv: Initialization vector :param cek: Content master ke...
[ "def", "encrypt", "(", "self", ",", "key", "=", "None", ",", "iv", "=", "\"\"", ",", "cek", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "_msg", "=", "as_bytes", "(", "self", ".", "msg", ")", "_args", "=", "self", ".", "_dict", "try", ":", ...
35.382353
0.001618
def hacking_python3x_metaclass(logical_line, noqa): r"""Check for metaclass to be Python 3.x compatible. Okay: @six.add_metaclass(Meta)\nclass Foo(object):\n pass Okay: @six.with_metaclass(Meta)\nclass Foo(object):\n pass Okay: class Foo(object):\n '''docstring\n\n __metaclass__ = Meta\n'''...
[ "def", "hacking_python3x_metaclass", "(", "logical_line", ",", "noqa", ")", ":", "if", "noqa", ":", "return", "split_line", "=", "logical_line", ".", "split", "(", ")", "if", "(", "len", "(", "split_line", ")", ">", "2", "and", "split_line", "[", "0", "]...
47.8
0.001026
def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents ...
[ "def", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", ":", "prevlinenum", "=", "linenum", "-", "1", "while", "prevlinenum", ">=", "0", ":", "prevline", "=", "clean_lines", ".", "elided", "[", "prevlinenum", "]", "if", "not", "IsBlankLine",...
35.952381
0.007742
def _deserialize_dict_attributes(cls, cls_context, dict_): """ :type cls_context: type :type dict_: dict :rtype: dict """ dict_deserialized = {} for key in dict_.keys(): key_deserialized = cls._deserialize_key(key) value_specs = cls._get...
[ "def", "_deserialize_dict_attributes", "(", "cls", ",", "cls_context", ",", "dict_", ")", ":", "dict_deserialized", "=", "{", "}", "for", "key", "in", "dict_", ".", "keys", "(", ")", ":", "key_deserialized", "=", "cls", ".", "_deserialize_key", "(", "key", ...
28.521739
0.00295
def mac_to_ipv6_linklocal(mac,prefix="fe80::"): """ Translate a MAC address into an IPv6 address in the prefixed network. This function calculates the EUI (Extended Unique Identifier) from the given MAC address and prepend the needed prefix to come up with a valid IPv6 address. The default prefix is th...
[ "def", "mac_to_ipv6_linklocal", "(", "mac", ",", "prefix", "=", "\"fe80::\"", ")", ":", "# Remove the most common delimiters; dots, dashes, etc.", "mac_value", "=", "int", "(", "mac", ".", "translate", "(", "str", ".", "maketrans", "(", "dict", "(", "[", "(", "x...
40.296296
0.008977
def latex_defs_to_katex_macros(defs): r'''Converts LaTeX \def statements to KaTeX macros. This is a helper function that can be used in conf.py to translate your already specified LaTeX definitions. https://github.com/Khan/KaTeX#rendering-options, e.g. `\def \e #1{\mathrm{e}^{#1}}` => `"\\e:" "\\m...
[ "def", "latex_defs_to_katex_macros", "(", "defs", ")", ":", "# Remove empty lines", "defs", "=", "defs", ".", "strip", "(", ")", "tmp", "=", "[", "]", "for", "line", "in", "defs", ".", "splitlines", "(", ")", ":", "# Remove spaces from every line", "line", "...
35.918919
0.000733
def add_gene_ids(self, genes_list): """Add gene IDs manually into the GEM-PRO project. Args: genes_list (list): List of gene IDs as strings. """ orig_num_genes = len(self.genes) for g in list(set(genes_list)): if not self.genes.has_id(g): ...
[ "def", "add_gene_ids", "(", "self", ",", "genes_list", ")", ":", "orig_num_genes", "=", "len", "(", "self", ".", "genes", ")", "for", "g", "in", "list", "(", "set", "(", "genes_list", ")", ")", ":", "if", "not", "self", ".", "genes", ".", "has_id", ...
35.388889
0.006116
def get_next_step(self): """Find the proper step when user clicks the Next button. :returns: The step to be switched to :rtype: WizardStep instance or None """ layer_mode = self.parent.step_kw_layermode.selected_layermode() if layer_mode == layer_mode_classified: ...
[ "def", "get_next_step", "(", "self", ")", ":", "layer_mode", "=", "self", ".", "parent", ".", "step_kw_layermode", ".", "selected_layermode", "(", ")", "if", "layer_mode", "==", "layer_mode_classified", ":", "new_step", "=", "self", ".", "parent", ".", "step_k...
40.666667
0.003205
def coerce(self, value, resource): """Convert a list of objects in a list of dicts. Arguments --------- value : iterable The list (or other iterable) to get values to get some resources from. resource : dataql.resources.List The ``List`` object used to ob...
[ "def", "coerce", "(", "self", ",", "value", ",", "resource", ")", ":", "if", "not", "isinstance", "(", "value", ",", "Iterable", ")", ":", "raise", "NotIterable", "(", "resource", ",", "self", ".", "registry", "[", "value", "]", ")", "# Case #1: we only ...
37.95122
0.006266
def calculate_polychrome_pinhole_psf(x, y, z, normalize=False, kfki=0.889, sigkf=0.1, zint=100., nkpts=3, dist_type='gaussian', **kwargs): """ Calculates the perfect-pinhole PSF, for a set of points (x,y,z). Parameters ----------- x : numpy.ndarray The x-coordinate of the PS...
[ "def", "calculate_polychrome_pinhole_psf", "(", "x", ",", "y", ",", "z", ",", "normalize", "=", "False", ",", "kfki", "=", "0.889", ",", "sigkf", "=", "0.1", ",", "zint", "=", "100.", ",", "nkpts", "=", "3", ",", "dist_type", "=", "'gaussian'", ",", ...
36.6
0.002993
def run_normalization(self): """ Run the normalization procedures """ for index, media_file in enumerate( tqdm( self.media_files, desc="File", disable=not self.progress, position=0 ...
[ "def", "run_normalization", "(", "self", ")", ":", "for", "index", ",", "media_file", "in", "enumerate", "(", "tqdm", "(", "self", ".", "media_files", ",", "desc", "=", "\"File\"", ",", "disable", "=", "not", "self", ".", "progress", ",", "position", "="...
34.4375
0.007067
def _reconnect_cb(self): """Callback to reconnect to the server.""" @asyncio.coroutine def try_reconnect(): """Actual coroutine ro try to reconnect or reschedule.""" try: yield from self._do_connect() except IOError: self._loop....
[ "def", "_reconnect_cb", "(", "self", ")", ":", "@", "asyncio", ".", "coroutine", "def", "try_reconnect", "(", ")", ":", "\"\"\"Actual coroutine ro try to reconnect or reschedule.\"\"\"", "try", ":", "yield", "from", "self", ".", "_do_connect", "(", ")", "except", ...
40.818182
0.004357
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available bundle matches and the bundle name :param prompt: Shell prompt string :param session: Current shell session (for ...
[ "def", "display_hook", "(", "prompt", ",", "session", ",", "context", ",", "matches", ",", "longest_match_len", ")", ":", "# type: (str, ShellSession, BundleContext, List[str], int) -> None", "# Prepare a line pattern for each match", "match_pattern", "=", "\"{{0: >{}}}: {{1}}\""...
40.740741
0.002664
def _collect_from_package(self, module, type_checker: Optional[FunctionType] = None, ) -> Dict[str, Any]: """ Discover objects passing :meth:`type_check` by walking through all the child modules/packages in the given module (ie, do not ...
[ "def", "_collect_from_package", "(", "self", ",", "module", ",", "type_checker", ":", "Optional", "[", "FunctionType", "]", "=", "None", ",", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "type_checker", "=", "type_checker", "or", "self", ".", "ty...
50.3
0.004878
def _traverse_parent(node, objtypes): """ Traverse up the node's parents until you hit the ``objtypes`` referenced. Can either be a single type, or a tuple of types. """ curr_node = node.parent while curr_node is not None: if isinstance(curr_node, objtypes): return curr_...
[ "def", "_traverse_parent", "(", "node", ",", "objtypes", ")", ":", "curr_node", "=", "node", ".", "parent", "while", "curr_node", "is", "not", "None", ":", "if", "isinstance", "(", "curr_node", ",", "objtypes", ")", ":", "return", "curr_node", "curr_node", ...
28.076923
0.002653
def edit(self, name=None, description=None, start_date=None, due_date=None, status=None, tags=None, team=None, options=None, **kwargs): """Edit the details of a scope. :param name: (optionally) edit the name of the scope :type name: basestring or None :param description: (o...
[ "def", "edit", "(", "self", ",", "name", "=", "None", ",", "description", "=", "None", ",", "start_date", "=", "None", ",", "due_date", "=", "None", ",", "status", "=", "None", ",", "tags", "=", "None", ",", "team", "=", "None", ",", "options", "="...
49.572581
0.005104
def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('c...
[ "def", "insert", "(", "self", ",", "table", ",", "row", ")", ":", "(", "sql", ",", "values", ")", "=", "sqlinsert", "(", "table", ",", "row", ")", "self", ".", "execute", "(", "sql", ",", "values", ")" ]
32.947368
0.003106
def status(self, status, headers=None): ''' Respond with given status and no content :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule ...
[ "def", "status", "(", "self", ",", "status", ",", "headers", "=", "None", ")", ":", "self", ".", "response", "=", "_Response", "(", "status", ",", "headers", ")", "return", "self" ]
25.466667
0.005051
def plot_fiber_slice(self, plane=None, index=None, fig=None): r""" Plot one slice from the fiber image Parameters ---------- plane : array_like List of 3 values, [x,y,z], 2 must be zero and the other must be between zero and one representing the fraction of the d...
[ "def", "plot_fiber_slice", "(", "self", ",", "plane", "=", "None", ",", "index", "=", "None", ",", "fig", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "'_fiber_image'", ")", "is", "False", ":", "logger", ".", "warning", "(", "'This method ...
34.923077
0.002144
def get_stp_mst_detail_output_cist_port_transmitted_stp_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
[ "def", "get_stp_mst_detail_output_cist_port_transmitted_stp_type", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_stp_mst_detail", "=", "ET", ".", "Element", "(", "\"get_stp_mst_detail\"", ")", "co...
44.928571
0.003115
def append(self, png, **options): """Append one frame. :arg PNG png: Append a :class:`PNG` as a frame. :arg dict options: The options for :class:`FrameControl`. """ if not isinstance(png, PNG): raise TypeError("Expect an instance of `PNG` but got `{}`".format(png)) control = FrameControl(**options) ...
[ "def", "append", "(", "self", ",", "png", ",", "*", "*", "options", ")", ":", "if", "not", "isinstance", "(", "png", ",", "PNG", ")", ":", "raise", "TypeError", "(", "\"Expect an instance of `PNG` but got `{}`\"", ".", "format", "(", "png", ")", ")", "co...
32.714286
0.03397
def tarbz(source_directory_path, output_file_full_path, silent=False): """ Tars and bzips a directory, preserving as much metadata as possible. Adds '.tbz' to the provided output file name. """ output_directory_path = output_file_full_path.rsplit("/", 1)[0] create_folders(output_directory_path) ...
[ "def", "tarbz", "(", "source_directory_path", ",", "output_file_full_path", ",", "silent", "=", "False", ")", ":", "output_directory_path", "=", "output_file_full_path", ".", "rsplit", "(", "\"/\"", ",", "1", ")", "[", "0", "]", "create_folders", "(", "output_di...
56.5
0.003264
def add_torrent_task(self, torrent_path, save_path='/', selected_idx=(), **kwargs): """ 添加本地BT任务 :param torrent_path: 本地种子的路径 :param save_path: 远程保存路径 :param selected_idx: 要下载的文件序号 —— 集合为空下载所有,非空集合指定序号集合,空串下载默认 :return: requests.Response .. note:: ...
[ "def", "add_torrent_task", "(", "self", ",", "torrent_path", ",", "save_path", "=", "'/'", ",", "selected_idx", "=", "(", ")", ",", "*", "*", "kwargs", ")", ":", "# 上传种子文件", "torrent_handler", "=", "open", "(", "torrent_path", ",", "'rb'", ")", "basename",...
31.482759
0.002655
def delete(gandi, resource, force): """ Delete a hosted certificate. Resource can be a FQDN or an ID """ infos = gandi.hostedcert.infos(resource) if not infos: return if not force: proceed = click.confirm('Are you sure to delete the following hosted ' ...
[ "def", "delete", "(", "gandi", ",", "resource", ",", "force", ")", ":", "infos", "=", "gandi", ".", "hostedcert", ".", "infos", "(", "resource", ")", "if", "not", "infos", ":", "return", "if", "not", "force", ":", "proceed", "=", "click", ".", "confi...
32.15
0.001511
def is_datetimelike_v_object(a, b): """ Check if we are comparing a datetime-like object to an object instance. Parameters ---------- a : array-like, scalar The first object to check. b : array-like, scalar The second object to check. Returns ------- boolean ...
[ "def", "is_datetimelike_v_object", "(", "a", ",", "b", ")", ":", "if", "not", "hasattr", "(", "a", ",", "'dtype'", ")", ":", "a", "=", "np", ".", "asarray", "(", "a", ")", "if", "not", "hasattr", "(", "b", ",", "'dtype'", ")", ":", "b", "=", "n...
27.156863
0.000697
def pprint_value_string(self, value): """Pretty print the dimension value and unit. Args: value: Dimension value to format Returns: Formatted dimension value string with unit """ unit = '' if self.unit is None else ' ' + bytes_to_unicode(self.unit) ...
[ "def", "pprint_value_string", "(", "self", ",", "value", ")", ":", "unit", "=", "''", "if", "self", ".", "unit", "is", "None", "else", "' '", "+", "bytes_to_unicode", "(", "self", ".", "unit", ")", "value", "=", "self", ".", "pprint_value", "(", "value...
36.333333
0.006711
def getLocalParameters(self): """ Retrieve the ICE parameters of the ICE gatherer. :rtype: RTCIceParameters """ return RTCIceParameters( usernameFragment=self._connection.local_username, password=self._connection.local_password)
[ "def", "getLocalParameters", "(", "self", ")", ":", "return", "RTCIceParameters", "(", "usernameFragment", "=", "self", ".", "_connection", ".", "local_username", ",", "password", "=", "self", ".", "_connection", ".", "local_password", ")" ]
31.666667
0.006826
def group_samaccountnames(self, base_dn): """For the current ADUser instance, determine which groups the user is a member of and convert the group DistinguishedNames to sAMAccountNames. The resulting list of groups may not be complete if explicit_membership_only was set to ...
[ "def", "group_samaccountnames", "(", "self", ",", "base_dn", ")", ":", "#pylint: disable=no-member", "mappings", "=", "self", ".", "samaccountnames", "(", "base_dn", ",", "self", ".", "memberof", ")", "#pylint: enable=no-member", "groups", "=", "[", "samaccountname"...
43.086957
0.004936
def process_notebook(self, disable_warnings=True): """Process the notebook and create all the pictures and files This method runs the notebook using the :mod:`nbconvert` and :mod:`nbformat` modules. It creates the :attr:`outfile` notebook, a python and a rst file""" infile = sel...
[ "def", "process_notebook", "(", "self", ",", "disable_warnings", "=", "True", ")", ":", "infile", "=", "self", ".", "infile", "outfile", "=", "self", ".", "outfile", "in_dir", "=", "os", ".", "path", ".", "dirname", "(", "infile", ")", "+", "os", ".", ...
37.603175
0.000823
def get_type_hierarchy(s): """Get the sequence of parents from `s` to Statement. Parameters ---------- s : a class or instance of a child of Statement For example the statement `Phosphorylation(MEK(), ERK())` or just the class `Phosphorylation`. Returns ------- parent_list ...
[ "def", "get_type_hierarchy", "(", "s", ")", ":", "tp", "=", "type", "(", "s", ")", "if", "not", "isinstance", "(", "s", ",", "type", ")", "else", "s", "p_list", "=", "[", "tp", "]", "for", "p", "in", "tp", ".", "__bases__", ":", "if", "p", "is"...
29.2
0.001105
def nl_pad(self, value): """Pad setter.""" self.bytearray[self._get_slicers(1)] = bytearray(c_ushort(value or 0))
[ "def", "nl_pad", "(", "self", ",", "value", ")", ":", "self", ".", "bytearray", "[", "self", ".", "_get_slicers", "(", "1", ")", "]", "=", "bytearray", "(", "c_ushort", "(", "value", "or", "0", ")", ")" ]
42.333333
0.015504
def retract_vote( self, chat_id: Union[int, str], message_id: id ) -> bool: """Use this method to retract your vote in a poll. Args: chat_id (``int`` | ``str``): Unique identifier (int) or username (str) of the target chat. For you...
[ "def", "retract_vote", "(", "self", ",", "chat_id", ":", "Union", "[", "int", ",", "str", "]", ",", "message_id", ":", "id", ")", "->", "bool", ":", "self", ".", "send", "(", "functions", ".", "messages", ".", "SendVote", "(", "peer", "=", "self", ...
30.774194
0.006098
def _make_item(self, item): ''' make Item class ''' for field in self._item_class.fields: if (field in item) and ('dblite_serializer' in self._item_class.fields[field]): serializer = self._item_class.fields[field]['dblite_serializer'] item[field] = ser...
[ "def", "_make_item", "(", "self", ",", "item", ")", ":", "for", "field", "in", "self", ".", "_item_class", ".", "fields", ":", "if", "(", "field", "in", "item", ")", "and", "(", "'dblite_serializer'", "in", "self", ".", "_item_class", ".", "fields", "[...
47.125
0.010417
def TruncatedNormal(shape, dtype, seed): """ Standard (mu=0, sigma=1) gaussian op with truncation above 2 sigma. """ if seed: np.random.seed(seed) n = reduce(mul, shape) r = np.empty(n, dtype=dtype_map[dtype]) idxs = np.ones(n, dtype=np.bool) while n: r[idxs] = np.random....
[ "def", "TruncatedNormal", "(", "shape", ",", "dtype", ",", "seed", ")", ":", "if", "seed", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "n", "=", "reduce", "(", "mul", ",", "shape", ")", "r", "=", "np", ".", "empty", "(", "n", ",", ...
28.857143
0.002398
def _tweak_lane(lane_details, dname): """Potentially tweak lane information to handle custom processing, reading a lane_config.yaml file. """ tweak_config_file = os.path.join(dname, "lane_config.yaml") if os.path.exists(tweak_config_file): with open(tweak_config_file) as in_handle: t...
[ "def", "_tweak_lane", "(", "lane_details", ",", "dname", ")", ":", "tweak_config_file", "=", "os", ".", "path", ".", "join", "(", "dname", ",", "\"lane_config.yaml\"", ")", "if", "os", ".", "path", ".", "exists", "(", "tweak_config_file", ")", ":", "with",...
42.285714
0.003306
def _index_list(key_or_list, direction=None): """Helper to generate a list of (key, direction) pairs. Takes such a list, or a single key, or a single key and direction. """ if direction is not None: return [(key_or_list, direction)] else: if isinstance(key_or_list, string_type): ...
[ "def", "_index_list", "(", "key_or_list", ",", "direction", "=", "None", ")", ":", "if", "direction", "is", "not", "None", ":", "return", "[", "(", "key_or_list", ",", "direction", ")", "]", "else", ":", "if", "isinstance", "(", "key_or_list", ",", "stri...
40.357143
0.00173
def make_zip(folder_path, output_filename): """将目录中除zip之外的文件打包成zip文件(包括子文件夹) 空文件夹不会被打包 example ---------------- make_zip('results','zips//招标信息结果_2017-05-09.zip') """ cwd = os.getcwd() # 获取需要打包的文件列表 file_lists = [] for root, dirs, files in os.walk(folder_path): for file ...
[ "def", "make_zip", "(", "folder_path", ",", "output_filename", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "# 获取需要打包的文件列表", "file_lists", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "folder_path", ")"...
25.346154
0.001462
def _validate_empty(self, empty, field, value): """ {'type': 'boolean'} """ if isinstance(value, Iterable) and len(value) == 0: self._drop_remaining_rules( 'allowed', 'forbidden', 'items', 'minlength', 'maxlength', 'regex', 'validator') if not empt...
[ "def", "_validate_empty", "(", "self", ",", "empty", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Iterable", ")", "and", "len", "(", "value", ")", "==", "0", ":", "self", ".", "_drop_remaining_rules", "(", "'allowed'", ...
47
0.005222
def get_config_set(self, section, option): """Returns a set with each value per config file in it. """ values = set() for cp, filename, fp in self.layers: filename = filename # pylint fp = fp # pylint if cp.has_option(section, option): values.add(cp.get(section, option)) return values
[ "def", "get_config_set", "(", "self", ",", "section", ",", "option", ")", ":", "values", "=", "set", "(", ")", "for", "cp", ",", "filename", ",", "fp", "in", "self", ".", "layers", ":", "filename", "=", "filename", "# pylint", "fp", "=", "fp", "# pyl...
29.9
0.042208
def com_google_fonts_check_metadata_italic_style(ttFont, font_metadata): """METADATA.pb font.style "italic" matches font internals?""" from fontbakery.utils import get_name_entry_strings from fontbakery.constants import MacStyle if font_metadata.style != "italic": yield SKIP, "This check only applies to it...
[ "def", "com_google_fonts_check_metadata_italic_style", "(", "ttFont", ",", "font_metadata", ")", ":", "from", "fontbakery", ".", "utils", "import", "get_name_entry_strings", "from", "fontbakery", ".", "constants", "import", "MacStyle", "if", "font_metadata", ".", "style...
49.272727
0.010253
def py_to_weld_type(self, obj): """Summary Args: obj (TYPE): Description Returns: TYPE: Description Raises: Exception: Description """ if isinstance(obj, np.ndarray): dtype = str(obj.dtype) if dtype == 'int16'...
[ "def", "py_to_weld_type", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "dtype", "=", "str", "(", "obj", ".", "dtype", ")", "if", "dtype", "==", "'int16'", ":", "base", "=", "WeldInt16", "("...
28.885714
0.001914
def _deconv_rl_np_fft(data, h, Niter=10, h_is_fftshifted=False): """ deconvolves data with given psf (kernel) h data and h have to be same shape via lucy richardson deconvolution """ if data.shape!=h.shape: raise ValueError("data and h have to be same shape") i...
[ "def", "_deconv_rl_np_fft", "(", "data", ",", "h", ",", "Niter", "=", "10", ",", "h_is_fftshifted", "=", "False", ")", ":", "if", "data", ".", "shape", "!=", "h", ".", "shape", ":", "raise", "ValueError", "(", "\"data and h have to be same shape\"", ")", "...
25.38
0.001517
def nav_filter_bias_encode(self, usec, accel_0, accel_1, accel_2, gyro_0, gyro_1, gyro_2): ''' Accelerometer and Gyro biases from the navigation filter usec : Timestamp (microseconds) (uint64_t) accel_0 : b_f[0] (flo...
[ "def", "nav_filter_bias_encode", "(", "self", ",", "usec", ",", "accel_0", ",", "accel_1", ",", "accel_2", ",", "gyro_0", ",", "gyro_1", ",", "gyro_2", ")", ":", "return", "MAVLink_nav_filter_bias_message", "(", "usec", ",", "accel_0", ",", "accel_1", ",", "...
52.714286
0.005326
def _task_to_dict(task): """Converts a WorkQueue to a JSON-able dictionary.""" payload = task.payload if payload and task.content_type == 'application/json': payload = json.loads(payload) return dict( task_id=task.task_id, queue_name=task.queue_name, eta=_datetime_to_epo...
[ "def", "_task_to_dict", "(", "task", ")", ":", "payload", "=", "task", ".", "payload", "if", "payload", "and", "task", ".", "content_type", "==", "'application/json'", ":", "payload", "=", "json", ".", "loads", "(", "payload", ")", "return", "dict", "(", ...
36.5625
0.001667
def _init_randgen(self): """ Initialise random generator to be used for picking elements. With the current implementation in tohu (where we pick elements from generators individually instead of in bulk), it is faster to `use random.Random` than `numpy.random.RandomState` (it is ...
[ "def", "_init_randgen", "(", "self", ")", ":", "if", "self", ".", "p", "is", "None", ":", "self", ".", "randgen", "=", "Random", "(", ")", "self", ".", "func_random_choice", "=", "self", ".", "randgen", ".", "choice", "else", ":", "self", ".", "randg...
50.863636
0.001754
def load_templates(self, name): '''load a particular template based on a name. We look for a name IN data, so the query name can be a partial string of the full name. Parameters ========== name: the name of a template to look up ''' configs = self._get_templates() templates ...
[ "def", "load_templates", "(", "self", ",", "name", ")", ":", "configs", "=", "self", ".", "_get_templates", "(", ")", "templates", "=", "[", "]", "# The user wants to retrieve a particular configuration", "matches", "=", "[", "x", "for", "x", "in", "configs", ...
32.1
0.003026
def _walk_directories(self, vd, extent_to_ptr, extent_to_inode, path_table_records): # type: (headervd.PrimaryOrSupplementaryVD, Dict[int, path_table_record.PathTableRecord], Dict[int, inode.Inode], List[path_table_record.PathTableRecord]) -> Tuple[int, int] ''' An internal method to walk the di...
[ "def", "_walk_directories", "(", "self", ",", "vd", ",", "extent_to_ptr", ",", "extent_to_inode", ",", "path_table_records", ")", ":", "# type: (headervd.PrimaryOrSupplementaryVD, Dict[int, path_table_record.PathTableRecord], Dict[int, inode.Inode], List[path_table_record.PathTableRecord...
53.390244
0.00305
def check_and_update_action_task_group_id(parent_link, decision_link, rebuilt_definitions): """Update the ``ACTION_TASK_GROUP_ID`` of an action after verifying. Actions have varying ``ACTION_TASK_GROUP_ID`` behavior. Release Promotion action tasks set the ``ACTION_TASK_GROUP_ID`` to match the action ``tas...
[ "def", "check_and_update_action_task_group_id", "(", "parent_link", ",", "decision_link", ",", "rebuilt_definitions", ")", ":", "rebuilt_gid", "=", "rebuilt_definitions", "[", "'tasks'", "]", "[", "0", "]", "[", "'payload'", "]", "[", "'env'", "]", "[", "'ACTION_T...
48.25641
0.003646
def _check_state(self): """Check if this instance can model and/or can invert """ if(self.grid is not None and self.configs.configs is not None and self.assignments['forward_model'] is not None): self.can_model = True if(self.grid is not None and ...
[ "def", "_check_state", "(", "self", ")", ":", "if", "(", "self", ".", "grid", "is", "not", "None", "and", "self", ".", "configs", ".", "configs", "is", "not", "None", "and", "self", ".", "assignments", "[", "'forward_model'", "]", "is", "not", "None", ...
36
0.004926
async def getWorkerType(self, *args, **kwargs): """ Get a worker-type Get a worker-type from a provisioner. This method gives output: ``v1/workertype-response.json#`` This method is ``experimental`` """ return await self._makeApiCall(self.funcinfo["getWorkerTy...
[ "async", "def", "getWorkerType", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"getWorkerType\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ...
27.583333
0.008772
def add_event_detect(channel, trigger, callback=None, bouncetime=None): """ This function is designed to be used in a loop with other things, but unlike polling it is not going to miss the change in state of an input while the CPU is busy working on other things. This could be useful when using some...
[ "def", "add_event_detect", "(", "channel", ",", "trigger", ",", "callback", "=", "None", ",", "bouncetime", "=", "None", ")", ":", "_check_configured", "(", "channel", ",", "direction", "=", "IN", ")", "if", "bouncetime", "is", "not", "None", ":", "if", ...
45.166667
0.003613
def generate(env): """Add Builders and construction variables for dvipdf to an Environment.""" global PDFAction if PDFAction is None: PDFAction = SCons.Action.Action('$DVIPDFCOM', '$DVIPDFCOMSTR') global DVIPDFAction if DVIPDFAction is None: DVIPDFAction = SCons.Action.Action(DviPdf...
[ "def", "generate", "(", "env", ")", ":", "global", "PDFAction", "if", "PDFAction", "is", "None", ":", "PDFAction", "=", "SCons", ".", "Action", ".", "Action", "(", "'$DVIPDFCOM'", ",", "'$DVIPDFCOMSTR'", ")", "global", "DVIPDFAction", "if", "DVIPDFAction", "...
32.434783
0.010417
def stop(name): """ Stop project's container. """ container_name = get_container_name(name) client = docker.Client() try: client.stop(container_name) except docker.errors.NotFound: pass except docker.errors.APIError as error: die(error.explanation.decode())
[ "def", "stop", "(", "name", ")", ":", "container_name", "=", "get_container_name", "(", "name", ")", "client", "=", "docker", ".", "Client", "(", ")", "try", ":", "client", ".", "stop", "(", "container_name", ")", "except", "docker", ".", "errors", ".", ...
25.166667
0.003195
def set_qword_at_offset(self, offset, qword): """Set the quad-word value at the given file offset.""" return self.set_bytes_at_offset(offset, self.get_data_from_qword(qword))
[ "def", "set_qword_at_offset", "(", "self", ",", "offset", ",", "qword", ")", ":", "return", "self", ".", "set_bytes_at_offset", "(", "offset", ",", "self", ".", "get_data_from_qword", "(", "qword", ")", ")" ]
62.666667
0.015789
def read_setup_py(self): # type: ()-> Dict[str,str] """ Extract from setup.py's setup() arg list. :return: """ found = {} # type: Dict[str,str] setup_py = os.path.join("setup.py") if not os.path.isfile(setup_py): if self.strict: logg...
[ "def", "read_setup_py", "(", "self", ")", ":", "# type: ()-> Dict[str,str]", "found", "=", "{", "}", "# type: Dict[str,str]", "setup_py", "=", "os", ".", "path", ".", "join", "(", "\"setup.py\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "se...
34.777778
0.002486
def video_l1_top(body_output, targets, model_hparams, vocab_size): """Top transformation for video.""" del targets, vocab_size # unused arg num_channels = model_hparams.problem.num_channels num_frames = model_hparams.video_num_target_frames with tf.variable_scope("rgb"): body_output_shape = common_layers...
[ "def", "video_l1_top", "(", "body_output", ",", "targets", ",", "model_hparams", ",", "vocab_size", ")", ":", "del", "targets", ",", "vocab_size", "# unused arg", "num_channels", "=", "model_hparams", ".", "problem", ".", "num_channels", "num_frames", "=", "model_...
47.647059
0.009685
def _split_qname(self, name, is_element): """Split an element of attribute qname into namespace and local name. :Parameters: - `name`: element or attribute QName - `is_element`: `True` for an element, `False` for an attribute :Types: - `name`: `unicod...
[ "def", "_split_qname", "(", "self", ",", "name", ",", "is_element", ")", ":", "if", "name", ".", "startswith", "(", "u\"{\"", ")", ":", "namespace", ",", "name", "=", "name", "[", "1", ":", "]", ".", "split", "(", "u\"}\"", ",", "1", ")", "if", "...
35.818182
0.002472
def uri_to_regexp(self, uri): """converts uri w/ placeholder to regexp '/cars/{carName}/drivers/{DriverName}' -> '^/cars/.*/drivers/[^/]*$' '/cars/{carName}/drivers/{DriverName}/drive' -> '^/cars/.*/drivers/.*/drive$' """ def _convert(elem, is_last): ...
[ "def", "uri_to_regexp", "(", "self", ",", "uri", ")", ":", "def", "_convert", "(", "elem", ",", "is_last", ")", ":", "if", "not", "re", ".", "match", "(", "'^{.*}$'", ",", "elem", ")", ":", "return", "elem", "name", "=", "elem", ".", "replace", "("...
34.761905
0.004
def create_api_interface_request(self): """Get an instance of Api Vip Requests services facade.""" return ApiInterfaceRequest( self.networkapi_url, self.user, self.password, self.user_ldap)
[ "def", "create_api_interface_request", "(", "self", ")", ":", "return", "ApiInterfaceRequest", "(", "self", ".", "networkapi_url", ",", "self", ".", "user", ",", "self", ".", "password", ",", "self", ".", "user_ldap", ")" ]
30.875
0.007874
def detectUbuntuTablet(self): """Return detection of an Ubuntu Mobile OS tablet Detects a tablet running the Ubuntu Mobile OS. """ if UAgentInfo.deviceUbuntu in self.__userAgent \ and UAgentInfo.deviceTablet in self.__userAgent: return True return False
[ "def", "detectUbuntuTablet", "(", "self", ")", ":", "if", "UAgentInfo", ".", "deviceUbuntu", "in", "self", ".", "__userAgent", "and", "UAgentInfo", ".", "deviceTablet", "in", "self", ".", "__userAgent", ":", "return", "True", "return", "False" ]
30.9
0.006289
def salt_support(): ''' Run Salt Support that collects system data, logs etc for debug and support purposes. :return: ''' import salt.cli.support.collector if '' in sys.path: sys.path.remove('') client = salt.cli.support.collector.SaltSupport() _install_signal_handlers(client) ...
[ "def", "salt_support", "(", ")", ":", "import", "salt", ".", "cli", ".", "support", ".", "collector", "if", "''", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "remove", "(", "''", ")", "client", "=", "salt", ".", "cli", ".", "support", ...
27
0.00597
def add_config(self, logconf): """Add a log configuration to the logging framework. When doing this the contents of the log configuration will be validated and listeners for new log configurations will be notified. When validating the configuration the variables are checked against the ...
[ "def", "add_config", "(", "self", ",", "logconf", ")", ":", "if", "not", "self", ".", "cf", ".", "link", ":", "logger", ".", "error", "(", "'Cannot add configs without being connected to a '", "'Crazyflie!'", ")", "return", "# If the log configuration contains variabl...
47.711864
0.000696
def GenerateCalendarDatesFieldValuesTuples(self): """Generates tuples of calendar_dates.txt values. Yield zero tuples if this ServicePeriod should not be in calendar_dates.txt .""" for date, (exception_type, _) in self.date_exceptions.items(): yield (self.service_id, date, unicode(exception_type))
[ "def", "GenerateCalendarDatesFieldValuesTuples", "(", "self", ")", ":", "for", "date", ",", "(", "exception_type", ",", "_", ")", "in", "self", ".", "date_exceptions", ".", "items", "(", ")", ":", "yield", "(", "self", ".", "service_id", ",", "date", ",", ...
62.4
0.006329
def google_get_data(self, config, response): """Make request to Google API to get profile data for the user.""" params = { 'access_token': response['access_token'], } payload = urlencode(params) url = self.google_api_url + 'userinfo?' + payload req = Request(u...
[ "def", "google_get_data", "(", "self", ",", "config", ",", "response", ")", ":", "params", "=", "{", "'access_token'", ":", "response", "[", "'access_token'", "]", ",", "}", "payload", "=", "urlencode", "(", "params", ")", "url", "=", "self", ".", "googl...
40.5
0.004831
def view_for_image_named(image_name): """Create an ImageView for the given image.""" image = resource.get_image(image_name) if not image: return None return ImageView(pygame.Rect(0, 0, 0, 0), image)
[ "def", "view_for_image_named", "(", "image_name", ")", ":", "image", "=", "resource", ".", "get_image", "(", "image_name", ")", "if", "not", "image", ":", "return", "None", "return", "ImageView", "(", "pygame", ".", "Rect", "(", "0", ",", "0", ",", "0", ...
24.111111
0.004444
def _translate(env, target=None, source=SCons.Environment._null, *args, **kw): """ Function for `Translate()` pseudo-builder """ if target is None: target = [] pot = env.POTUpdate(None, source, *args, **kw) po = env.POUpdate(target, pot, *args, **kw) return po
[ "def", "_translate", "(", "env", ",", "target", "=", "None", ",", "source", "=", "SCons", ".", "Environment", ".", "_null", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "target", "is", "None", ":", "target", "=", "[", "]", "pot", "=", ...
45.833333
0.007143
def get_device_by_name(self, device_name): """Search the list of connected devices by name. device_name param is the string name of the device """ # Find the device for the vera device name we are interested in found_device = None for device in self.get_devices(): ...
[ "def", "get_device_by_name", "(", "self", ",", "device_name", ")", ":", "# Find the device for the vera device name we are interested in", "found_device", "=", "None", "for", "device", "in", "self", ".", "get_devices", "(", ")", ":", "if", "device", ".", "name", "==...
33.888889
0.007974
def get_yaml_parser_roundtrip_for_context(): """Create a yaml parser that can serialize the pypyr Context. Create yaml parser with get_yaml_parser_roundtrip, adding Context. This allows the yaml parser to serialize the pypyr Context. """ yaml_writer = get_yaml_parser_roundtrip() # Context is a...
[ "def", "get_yaml_parser_roundtrip_for_context", "(", ")", ":", "yaml_writer", "=", "get_yaml_parser_roundtrip", "(", ")", "# Context is a dict data structure, so can just use a dict representer", "yaml_writer", ".", "Representer", ".", "add_representer", "(", "Context", ",", "y...
36.642857
0.001901
def build_tree(self): """ Build chaid tree """ self._tree_store = [] self.node(np.arange(0, self.data_size, dtype=np.int), self.vectorised_array, self.observed)
[ "def", "build_tree", "(", "self", ")", ":", "self", ".", "_tree_store", "=", "[", "]", "self", ".", "node", "(", "np", ".", "arange", "(", "0", ",", "self", ".", "data_size", ",", "dtype", "=", "np", ".", "int", ")", ",", "self", ".", "vectorised...
45.25
0.016304