text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def getFileInfos(self): """Return a list of FileInfo objects""" data = self.searchIndex(False) self.data = data self.printd(" ") fileInfos = [] for datum in data: try: fileInfo = self.getFileInfo(datum[0], datum[1]) fileInfos.append(fileInfo) except NotImplementedError: self.printd("Error:...
[ "def", "getFileInfos", "(", "self", ")", ":", "data", "=", "self", ".", "searchIndex", "(", "False", ")", "self", ".", "data", "=", "data", "self", ".", "printd", "(", "\" \"", ")", "fileInfos", "=", "[", "]", "for", "datum", "in", "data", ":", "tr...
28.5
19.142857
def absent(name, **kwargs): ''' Make sure that the named file or directory is absent. If it exists, it will be deleted. This will work to reverse any of the functions in the file state module. If a directory is supplied, it will be recursively deleted. name The path which should ...
[ "def", "absent", "(", "name", ",", "*", "*", "kwargs", ")", ":", "name", "=", "os", ".", "path", ".", "expanduser", "(", "name", ")", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'...
35.148148
20.333333
def __cqt_filter_fft(sr, fmin, n_bins, bins_per_octave, tuning, filter_scale, norm, sparsity, hop_length=None, window='hann'): '''Generate the frequency domain constant-Q filter basis.''' basis, lengths = filters.constant_q(sr, f...
[ "def", "__cqt_filter_fft", "(", "sr", ",", "fmin", ",", "n_bins", ",", "bins_per_octave", ",", "tuning", ",", "filter_scale", ",", "norm", ",", "sparsity", ",", "hop_length", "=", "None", ",", "window", "=", "'hann'", ")", ":", "basis", ",", "lengths", "...
39.705882
22.176471
def fix_type(typ, size, additional=None): """Fix up creating the appropriate struct type based on the information in the column.""" if additional is not None: my_types = types + additional else: my_types = types for t, info in my_types: if callable(t): matches = t(ty...
[ "def", "fix_type", "(", "typ", ",", "size", ",", "additional", "=", "None", ")", ":", "if", "additional", "is", "not", "None", ":", "my_types", "=", "types", "+", "additional", "else", ":", "my_types", "=", "types", "for", "t", ",", "info", "in", "my...
34.173913
19
def works(self, member_id): """ This method retrieve a iterable of Works of the given member. args: Member ID (Integer) return: Works() """ context = '%s/%s' % (self.ENDPOINT, str(member_id)) return Works(context=context)
[ "def", "works", "(", "self", ",", "member_id", ")", ":", "context", "=", "'%s/%s'", "%", "(", "self", ".", "ENDPOINT", ",", "str", "(", "member_id", ")", ")", "return", "Works", "(", "context", "=", "context", ")" ]
27
16.8
def _connectionEstablished(self, transport): '''Store a reference to our transport and write an open frame.''' self.transport = transport self.transport.writeOpen() self.heartbeater.schedule()
[ "def", "_connectionEstablished", "(", "self", ",", "transport", ")", ":", "self", ".", "transport", "=", "transport", "self", ".", "transport", ".", "writeOpen", "(", ")", "self", ".", "heartbeater", ".", "schedule", "(", ")" ]
44
10.8
def resetToDefault(self, resetChildren=True): """ Resets the data to the default data. By default the children will be reset as well """ self.data = self.defaultData if resetChildren: for child in self.childItems: child.resetToDefault(resetChildren=True)
[ "def", "resetToDefault", "(", "self", ",", "resetChildren", "=", "True", ")", ":", "self", ".", "data", "=", "self", ".", "defaultData", "if", "resetChildren", ":", "for", "child", "in", "self", ".", "childItems", ":", "child", ".", "resetToDefault", "(", ...
44
5.857143
def bump(component='patch', exact=None): # type: (str, str) -> Tuple[str, str] """ Bump the given version component. Args: component (str): What part of the version should be bumped. Can be one of: - major - minor - patch exact (str): ...
[ "def", "bump", "(", "component", "=", "'patch'", ",", "exact", "=", "None", ")", ":", "# type: (str, str) -> Tuple[str, str]", "old_ver", "=", "current", "(", ")", "if", "exact", "is", "None", ":", "new_ver", "=", "_bump_version", "(", "old_ver", ",", "compo...
23.071429
22.857143
def __assign_vertex_pair(block): """ Assigns usual BreakpointGraph type vertices to supplied block. Vertices are labeled as "block_name" + "h" and "block_name" + "t" according to blocks orientation. :param block: information about a genomic block to create a pair of vertices for in a format of...
[ "def", "__assign_vertex_pair", "(", "block", ")", ":", "sign", ",", "name", "=", "block", "data", "=", "name", ".", "split", "(", "BlockVertex", ".", "NAME_SEPARATOR", ")", "root_name", ",", "data", "=", "data", "[", "0", "]", ",", "data", "[", "1", ...
47.814815
20.444444
def _kip(self, cycle_end, mix_thresh, xaxis, sparse): """ *** Should be used with care, therefore has been flagged as a private routine *** This function uses a threshold diffusion coefficient, above which the the shell is considered to be convective, to plot a Kippenhahn...
[ "def", "_kip", "(", "self", ",", "cycle_end", ",", "mix_thresh", ",", "xaxis", ",", "sparse", ")", ":", "original_cyclelist", "=", "self", ".", "se", ".", "cycles", "cyclelist", "=", "original_cyclelist", "[", "0", ":", "cycle_end", ":", "sparse", "]", "...
36.605042
18.504202
def create_bucket(self, source): '''Use the create_bucket API to create a new bucket''' s3url = S3URL(source) message('Creating %s', source) if not self.opt.dry_run: resp = self.s3.create_bucket(Bucket=s3url.bucket) if resp['ResponseMetadata']["HTTPStatusCode"] == 200: message('Done...
[ "def", "create_bucket", "(", "self", ",", "source", ")", ":", "s3url", "=", "S3URL", "(", "source", ")", "message", "(", "'Creating %s'", ",", "source", ")", "if", "not", "self", ".", "opt", ".", "dry_run", ":", "resp", "=", "self", ".", "s3", ".", ...
35.090909
18
def get_groups_of_user(self, user_id, **kwargs): # noqa: E501 """Get groups of the user. # noqa: E501 An endpoint for retrieving groups of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -H 'Authorization: Bearer API_KEY'` # noqa: E501 This ...
[ "def", "get_groups_of_user", "(", "self", ",", "user_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ".", "g...
58.68
31.36
def read_authorized_keys(username=None): """Read public keys from specified user's authorized_keys file. args: username (str): username. returns: list: Authorised keys for the specified user. """ authorized_keys_path = '{0}/.ssh/authorized_keys'.format(os.path.expanduser('~{0}'.for...
[ "def", "read_authorized_keys", "(", "username", "=", "None", ")", ":", "authorized_keys_path", "=", "'{0}/.ssh/authorized_keys'", ".", "format", "(", "os", ".", "path", ".", "expanduser", "(", "'~{0}'", ".", "format", "(", "username", ")", ")", ")", "rnd_chars...
52.8
27.84
def lowpass(data,filterSize=None): """ minimal complexity low-pass filtering. Filter size is how "wide" the filter will be. Sigma will be 1/10 of this filter width. If filter size isn't given, it will be 1/10 of the data size. """ if filterSize is None: filterSize=len(data)/10 ke...
[ "def", "lowpass", "(", "data", ",", "filterSize", "=", "None", ")", ":", "if", "filterSize", "is", "None", ":", "filterSize", "=", "len", "(", "data", ")", "/", "10", "kernel", "=", "kernel_gaussian", "(", "size", "=", "filterSize", ")", "data", "=", ...
36
10.5
def diff(ctx, files, metrics, all, detail): """Show the differences in metrics for each file.""" config = ctx.obj["CONFIG"] if not exists(config): handle_no_cache(ctx) if not metrics: metrics = get_default_metrics(config) logger.info(f"Using default metrics {metrics}") else...
[ "def", "diff", "(", "ctx", ",", "files", ",", "metrics", ",", "all", ",", "detail", ")", ":", "config", "=", "ctx", ".", "obj", "[", "\"CONFIG\"", "]", "if", "not", "exists", "(", "config", ")", ":", "handle_no_cache", "(", "ctx", ")", "if", "not",...
30.5
21.6
def __import_vars(self, env_file): """Actual importing function.""" with open(env_file, "r") as f: # pylint: disable=invalid-name for line in f: try: line = line.lstrip() if line.startswith('export'): line = lin...
[ "def", "__import_vars", "(", "self", ",", "env_file", ")", ":", "with", "open", "(", "env_file", ",", "\"r\"", ")", "as", "f", ":", "# pylint: disable=invalid-name", "for", "line", "in", "f", ":", "try", ":", "line", "=", "line", ".", "lstrip", "(", ")...
47.291667
14.458333
def record(self): # type: () -> bytes ''' Generate a string representing the Rock Ridge System Terminator record. Parameters: None. Returns: String containing the Rock Ridge record. ''' if not self._initialized: raise pycdlib...
[ "def", "record", "(", "self", ")", ":", "# type: () -> bytes", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'ST record not yet initialized!'", ")", "return", "b'ST'", "+", "struct", ".", "pack", "("...
30.133333
27.066667
def get_history_entry_record(endianess, hist_date_time_flag, tm_format, event_number_flag, hist_seq_nbr_flag, data): """ Return data formatted into a log entry. :param str endianess: The endianess to use when packing values ('>' or '<') :param bool hist_date_time_flag: Whether or not a time stamp is included. :pa...
[ "def", "get_history_entry_record", "(", "endianess", ",", "hist_date_time_flag", ",", "tm_format", ",", "event_number_flag", ",", "hist_seq_nbr_flag", ",", "data", ")", ":", "rcd", "=", "{", "}", "if", "hist_date_time_flag", ":", "tmstmp", "=", "format_ltime", "("...
44.066667
26.933333
def postprocess_authors_full(self, entry): """ If only a single author was found, ensure that ``authors_full`` is nonetheless a list. """ if type(entry.authors_full) is not list: entry.authors_full = [entry.authors_full]
[ "def", "postprocess_authors_full", "(", "self", ",", "entry", ")", ":", "if", "type", "(", "entry", ".", "authors_full", ")", "is", "not", "list", ":", "entry", ".", "authors_full", "=", "[", "entry", ".", "authors_full", "]" ]
38
10
def write_filter(script, filter_xml): """ Write filter to FilterScript object or filename Args: script (FilterScript object or filename str): the FilterScript object or script filename to write the filter to. filter_xml (str): the xml filter string """ if isinstance(script,...
[ "def", "write_filter", "(", "script", ",", "filter_xml", ")", ":", "if", "isinstance", "(", "script", ",", "mlx", ".", "FilterScript", ")", ":", "script", ".", "filters", ".", "append", "(", "filter_xml", ")", "elif", "isinstance", "(", "script", ",", "s...
30.888889
15.111111
def encrypt(user=None, recipients=None, text=None, filename=None, output=None, sign=None, use_passphrase=False, gnupghome=None, bare=False): ''' Encrypt a message or file user Which user's keychain to ac...
[ "def", "encrypt", "(", "user", "=", "None", ",", "recipients", "=", "None", ",", "text", "=", "None", ",", "filename", "=", "None", ",", "output", "=", "None", ",", "sign", "=", "None", ",", "use_passphrase", "=", "False", ",", "gnupghome", "=", "Non...
31.461538
27.615385
def do_check_artifact_cache(self, vts, post_process_cached_vts=None): """Checks the artifact cache for the specified list of VersionedTargetSets. Returns a tuple (cached, uncached, uncached_causes) of VersionedTargets that were satisfied/unsatisfied from the cache. """ if not vts: return [], ...
[ "def", "do_check_artifact_cache", "(", "self", ",", "vts", ",", "post_process_cached_vts", "=", "None", ")", ":", "if", "not", "vts", ":", "return", "[", "]", ",", "[", "]", ",", "[", "]", "read_cache", "=", "self", ".", "_cache_factory", ".", "get_read_...
41
23.333333
def parse_kal_scan(kal_out): """Parse kal band scan output.""" kal_data = [] scan_band = determine_scan_band(kal_out) scan_gain = determine_scan_gain(kal_out) scan_device = determine_device(kal_out) sample_rate = determine_sample_rate(kal_out) chan_detect_threshold = determine_chan_detect_th...
[ "def", "parse_kal_scan", "(", "kal_out", ")", ":", "kal_data", "=", "[", "]", "scan_band", "=", "determine_scan_band", "(", "kal_out", ")", "scan_gain", "=", "determine_scan_gain", "(", "kal_out", ")", "scan_device", "=", "determine_device", "(", "kal_out", ")",...
43.545455
9.454545
def malware(self, malware, password, file_name): """ Uploads to malware vault. Args: malware: password: file_name: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) self._data['malware'] = malware ...
[ "def", "malware", "(", "self", ",", "malware", ",", "password", ",", "file_name", ")", ":", "if", "not", "self", ".", "can_update", "(", ")", ":", "self", ".", "_tcex", ".", "handle_error", "(", "910", ",", "[", "self", ".", "type", "]", ")", "self...
33.352941
17.823529
def connect_head_node_proxy_with_path(self, name, path, **kwargs): # noqa: E501 """connect_head_node_proxy_with_path # noqa: E501 connect HEAD requests to proxy of Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please ...
[ "def", "connect_head_node_proxy_with_path", "(", "self", ",", "name", ",", "path", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "retu...
50.478261
25.478261
def count_in_date(x='date_time', filter_dict=None, model=DEFAULT_MODEL, app=DEFAULT_APP, sort=True, limit=100000): """ Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. >>> from django.db import transaction >>> ...
[ "def", "count_in_date", "(", "x", "=", "'date_time'", ",", "filter_dict", "=", "None", ",", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "DEFAULT_APP", ",", "sort", "=", "True", ",", "limit", "=", "100000", ")", ":", "sort", "=", "sort_prefix", "(", ...
43.147059
27.441176
def brew_innuendo(args): """Brews a given list of processes according to the recipe Parameters ---------- args : argparse.Namespace The arguments passed through argparser that will be used to check the the recipe, tasks and brew the process Returns ------- str The f...
[ "def", "brew_innuendo", "(", "args", ")", ":", "# Create recipe class instance", "automatic_pipeline", "=", "Innuendo", "(", ")", "if", "not", "args", ".", "tasks", ":", "input_processes", "=", "\" \"", ".", "join", "(", "automatic_pipeline", ".", "process_descrip...
27.029412
21.352941
def _get_indexer(self, key): """ Get indexer for rasterio array. Parameter --------- key: tuple of int Returns ------- band_key: an indexer for the 1st dimension window: two tuples. Each consists of (start, stop). squeeze_axis: axes to be squeeze...
[ "def", "_get_indexer", "(", "self", ",", "key", ")", ":", "assert", "len", "(", "key", ")", "==", "3", ",", "'rasterio datasets should always be 3D'", "# bands cannot be windowed but they can be listed", "band_key", "=", "key", "[", "0", "]", "np_inds", "=", "[", ...
36.071429
18
def readall(cls, member, size): ''' Parse variable metadata for a XPORT file member. ''' fp = member.library.fp LINE = member.library.LINE n = cls.header_match(fp.read(LINE)) namestrs = [fp.read(size) for i in range(n)] # Each namestr field is 140 bytes ...
[ "def", "readall", "(", "cls", ",", "member", ",", "size", ")", ":", "fp", "=", "member", ".", "library", ".", "fp", "LINE", "=", "member", ".", "library", ".", "LINE", "n", "=", "cls", ".", "header_match", "(", "fp", ".", "read", "(", "LINE", ")"...
34.692308
19.230769
def copy_from(self, src, dest): """ copy a file or a directory from container or image to host system. :param src: str, path to a file or a directory within container or image :param dest: str, path to a file or a directory on host system :return: None """ logger...
[ "def", "copy_from", "(", "self", ",", "src", ",", "dest", ")", ":", "logger", ".", "debug", "(", "\"copying %s from host to container at %s\"", ",", "src", ",", "dest", ")", "cmd", "=", "[", "\"machinectl\"", ",", "\"--no-pager\"", ",", "\"copy-from\"", ",", ...
42.636364
23.909091
def _copy_sources_to_generated_destination(self): """ Copies all project files to specified directory - generated dir """ files = [] for key in FILES_EXTENSIONS.keys(): if type(self.project['export'][key]) is dict: for k,v in self.project['export'][key].items(): ...
[ "def", "_copy_sources_to_generated_destination", "(", "self", ")", ":", "files", "=", "[", "]", "for", "key", "in", "FILES_EXTENSIONS", ".", "keys", "(", ")", ":", "if", "type", "(", "self", ".", "project", "[", "'export'", "]", "[", "key", "]", ")", "...
43.96
17.52
def from_dict(data, ctx): """ Instantiate a new GuaranteedStopLossOrderEntryData from a dict (generally from loading a JSON response). The data used to instantiate the GuaranteedStopLossOrderEntryData is a shallow copy of the dict passed in, with any complex child types instantia...
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "if", "data", ".", "get", "(", "'minimumDistance'", ")", "is", "not", "None", ":", "data", "[", "'minimumDistance'", "]", "=", "ctx", ".", "convert_dec...
36.444444
21.62963
def zeros(dur=None): """ Zeros/zeroes stream generator. You may sum your endless stream by this to enforce an end to it. Parameters ---------- dur : Duration, in number of samples; endless if not given. Returns ------- Stream that repeats "0.0" during a given time duration (if any) or endlessl...
[ "def", "zeros", "(", "dur", "=", "None", ")", ":", "if", "dur", "is", "None", "or", "(", "isinf", "(", "dur", ")", "and", "dur", ">", "0", ")", ":", "while", "True", ":", "yield", "0.0", "for", "x", "in", "xrange", "(", "int", "(", ".5", "+",...
20.714286
23.190476
def unpack_log_data(self, log_data, timestamp): """Unpack received logging data so it represent real values according to the configuration in the entry""" ret_data = {} data_index = 0 for var in self.variables: size = LogTocElement.get_size_from_id(var.fetch_as) ...
[ "def", "unpack_log_data", "(", "self", ",", "log_data", ",", "timestamp", ")", ":", "ret_data", "=", "{", "}", "data_index", "=", "0", "for", "var", "in", "self", ".", "variables", ":", "size", "=", "LogTocElement", ".", "get_size_from_id", "(", "var", "...
44.133333
13.266667
def measures(*measurements, **kwargs): """Decorator-maker used to declare measurements for phases. See the measurements module docstring for examples of usage. Args: measurements: Measurement objects to declare, or a string name from which to create a Measurement. kwargs: Keyword arguments to pa...
[ "def", "measures", "(", "*", "measurements", ",", "*", "*", "kwargs", ")", ":", "def", "_maybe_make", "(", "meas", ")", ":", "\"\"\"Turn strings into Measurement objects if necessary.\"\"\"", "if", "isinstance", "(", "meas", ",", "Measurement", ")", ":", "return",...
40.877551
23
def make_payment_script(address, blockchain='bitcoin', **blockchain_opts): """ High-level API call (meant to be blockchain agnostic) Make a pay-to-address script. """ if blockchain == 'bitcoin': return btc_make_payment_script(address, **blockchain_opts) else: raise ValueErro...
[ "def", "make_payment_script", "(", "address", ",", "blockchain", "=", "'bitcoin'", ",", "*", "*", "blockchain_opts", ")", ":", "if", "blockchain", "==", "'bitcoin'", ":", "return", "btc_make_payment_script", "(", "address", ",", "*", "*", "blockchain_opts", ")",...
35.8
19
def read_packages(reqs_file): """ Generator yielding one Package instance for every corresponing line in a requirements file """ for line in stream_file_lines(reqs_file): line = line.strip() if not line.startswith(('#', '--hash')): match = DEP_PATTERN.match(line) ...
[ "def", "read_packages", "(", "reqs_file", ")", ":", "for", "line", "in", "stream_file_lines", "(", "reqs_file", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", ".", "startswith", "(", "(", "'#'", ",", "'--hash'", ")", ")", ...
37
12.833333
def flatten_urls(self, urls): """ Function flatten urls for route grouping feature of glim. Args ---- urls (dict): a dict of url definitions. current_key (unknown type): a dict or a string marking the current key that is used for recursive calls. ...
[ "def", "flatten_urls", "(", "self", ",", "urls", ")", ":", "available_methods", "=", "[", "'POST'", ",", "'PUT'", ",", "'OPTIONS'", ",", "'GET'", ",", "'DELETE'", ",", "'TRACE'", ",", "'COPY'", "]", "ruleset", "=", "[", "]", "for", "route", ",", "endpo...
37.111111
17.422222
def check_messages(msgs, cmd, value=None): """Check if specific message is present. Parameters ---------- cmd : string Command to check for in bytestring from microscope CAM interface. If ``value`` is falsey, value of received command does not matter. value : string Check if...
[ "def", "check_messages", "(", "msgs", ",", "cmd", ",", "value", "=", "None", ")", ":", "for", "msg", "in", "msgs", ":", "if", "value", "and", "msg", ".", "get", "(", "cmd", ")", "==", "value", ":", "return", "msg", "if", "not", "value", "and", "m...
26.869565
20.478261
def VerifyServerControlResponse(self, http_object): """Verify the server response to a 'control' endpoint POST message. We consider the message correct if and only if we can decrypt it properly. Note that in practice we can not use the HTTP status to figure out if the request worked because captive pro...
[ "def", "VerifyServerControlResponse", "(", "self", ",", "http_object", ")", ":", "if", "http_object", ".", "code", "!=", "200", ":", "return", "False", "# Try to decrypt the message into the http_object.", "try", ":", "http_object", ".", "messages", ",", "http_object"...
34.83871
25.290323
def extract_domain(var_name, output): """ Extracts just the domain name from an URL and adds it to a list """ var = getenv(var_name) if var: p = urlparse(var) output.append(p.hostname)
[ "def", "extract_domain", "(", "var_name", ",", "output", ")", ":", "var", "=", "getenv", "(", "var_name", ")", "if", "var", ":", "p", "=", "urlparse", "(", "var", ")", "output", ".", "append", "(", "p", ".", "hostname", ")" ]
21.3
17.5
def p_elseif_list(p): '''elseif_list : empty | elseif_list ELSEIF LPAREN expr RPAREN statement''' if len(p) == 2: p[0] = [] else: p[0] = p[1] + [ast.ElseIf(p[4], p[6], lineno=p.lineno(2))]
[ "def", "p_elseif_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "[", "]", "else", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "ast", ".", "ElseIf", "(", "p", "[", "4", "...
32.714286
23.571429
def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None): """Random hue color generation. Default coloring method. This just picks a random hue with value 80% and lumination 50%. Parameters ---------- word, font_...
[ "def", "random_color_func", "(", "word", "=", "None", ",", "font_size", "=", "None", ",", "position", "=", "None", ",", "orientation", "=", "None", ",", "font_path", "=", "None", ",", "random_state", "=", "None", ")", ":", "if", "random_state", "is", "No...
33.105263
24.368421
def create(cls, amount, counterparty_alias, description, monetary_account_id=None, attachment=None, merchant_reference=None, allow_bunqto=None, custom_headers=None): """ Create a new Payment. :type user_id: int :type monetary_account_id: int :param ...
[ "def", "create", "(", "cls", ",", "amount", ",", "counterparty_alias", ",", "description", ",", "monetary_account_id", "=", "None", ",", "attachment", "=", "None", ",", "merchant_reference", "=", "None", ",", "allow_bunqto", "=", "None", ",", "custom_headers", ...
45.338983
22.288136
def _find_pkg_info(self): """ Find information about the installed package from pkg_resources. :returns: information from pkg_resources about ``self.package_name`` :rtype: dict """ dist = pkg_resources.require(self.package_name)[0] self._pkg_resources_locations =...
[ "def", "_find_pkg_info", "(", "self", ")", ":", "dist", "=", "pkg_resources", ".", "require", "(", "self", ".", "package_name", ")", "[", "0", "]", "self", ".", "_pkg_resources_locations", "=", "[", "dist", ".", "location", "]", "ver", ",", "url", "=", ...
38
16.909091
def overlap_size(self,tx2): """Return the number of overlapping base pairs between two transcripts :param tx2: Another transcript :type tx2: Transcript :return: overlap size in base pairs :rtype: int """ total = 0 for e1 in self.exons: for e2 in tx2.exons: total += e1.over...
[ "def", "overlap_size", "(", "self", ",", "tx2", ")", ":", "total", "=", "0", "for", "e1", "in", "self", ".", "exons", ":", "for", "e2", "in", "tx2", ".", "exons", ":", "total", "+=", "e1", ".", "overlap_size", "(", "e2", ")", "return", "total" ]
25.923077
14.153846
def ip_hide_ext_community_list_holder_extcommunity_list_extcommunity_list_num(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") hide_ext_community_list_holder = ET.SubElement...
[ "def", "ip_hide_ext_community_list_holder_extcommunity_list_extcommunity_list_num", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ip", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ip\"", ","...
62
33.916667
def get(self, endpoint, params=None, version='1.1'): """Shortcut for GET requests via :class:`request`""" return self.request(endpoint, params=params, version=version)
[ "def", "get", "(", "self", ",", "endpoint", ",", "params", "=", "None", ",", "version", "=", "'1.1'", ")", ":", "return", "self", ".", "request", "(", "endpoint", ",", "params", "=", "params", ",", "version", "=", "version", ")" ]
60.333333
13.666667
def remove_user_permission(rid, uid, action='full'): """ Removes user permission on a given resource. :param uid: user id :type uid: str :param rid: resource ID :type rid: str :param action: read, write, update, delete or full :type action: str """ rid = rid....
[ "def", "remove_user_permission", "(", "rid", ",", "uid", ",", "action", "=", "'full'", ")", ":", "rid", "=", "rid", ".", "replace", "(", "'/'", ",", "'%252F'", ")", "try", ":", "acl_url", "=", "urljoin", "(", "_acl_url", "(", ")", ",", "'acls/{}/users/...
30.684211
16.210526
def detect(self, G): """Detect a single core-periphery pair using the Borgatti-Everett algorithm. Parameters ---------- G : NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx.karate_club_graph() # load the karate club network. >>> spr = ...
[ "def", "detect", "(", "self", ",", "G", ")", ":", "nodes", "=", "G", ".", "nodes", "(", ")", "N", "=", "len", "(", "nodes", ")", "Cbest", "=", "np", ".", "zeros", "(", "N", ")", "qbest", "=", "0", "for", "it", "in", "range", "(", "self", "....
20.472222
22.555556
def _check_filter_specific_tag(self, specific_tag: list): """Check if specific_tag parameter is valid. :param list specific_tag: list of specific tag to check """ if isinstance(specific_tag, list): if len(specific_tag) > 0: specific_tag = ",".join(specific_ta...
[ "def", "_check_filter_specific_tag", "(", "self", ",", "specific_tag", ":", "list", ")", ":", "if", "isinstance", "(", "specific_tag", ",", "list", ")", ":", "if", "len", "(", "specific_tag", ")", ">", "0", ":", "specific_tag", "=", "\",\"", ".", "join", ...
35.769231
14.461538
def update(self, other, inplace=None): """Update this dataset's variables with those from another dataset. Parameters ---------- other : Dataset or castable to Dataset Dataset or variables with which to update this dataset. inplace : bool, optional If Tru...
[ "def", "update", "(", "self", ",", "other", ",", "inplace", "=", "None", ")", ":", "inplace", "=", "_check_inplace", "(", "inplace", ",", "default", "=", "True", ")", "variables", ",", "coord_names", ",", "dims", "=", "dataset_update_method", "(", "self", ...
33.703704
22
def is_optional_type(tp): """Returns `True` if the type is `type(None)`, or is a direct `Union` to `type(None)`, such as `Optional[T]`. NOTE: this method inspects nested `Union` arguments but not `TypeVar` definitions (`bound`/`constraint`). So it will return `False` if - `tp` is a `TypeVar` bound, or...
[ "def", "is_optional_type", "(", "tp", ")", ":", "if", "tp", "is", "type", "(", "None", ")", ":", "return", "True", "elif", "is_union_type", "(", "tp", ")", ":", "return", "any", "(", "is_optional_type", "(", "tt", ")", "for", "tt", "in", "get_args", ...
45.578947
29.789474
def __construct_from_components(self, ns_uri, prefix=None, schema_location=None): """Initialize this instance from a namespace URI, and optional prefix and schema location URI.""" assert ns_uri # other fields are optional self.uri = ns_uri self.schema_location = schema_locatio...
[ "def", "__construct_from_components", "(", "self", ",", "ns_uri", ",", "prefix", "=", "None", ",", "schema_location", "=", "None", ")", ":", "assert", "ns_uri", "# other fields are optional", "self", ".", "uri", "=", "ns_uri", "self", ".", "schema_location", "="...
35.307692
18.076923
def get_related_galleries(gallery, count=5): """ Gets latest related galleries from same section as originating gallery. Count defaults to five but can be overridden. Usage: {% get_related_galleries gallery <10> %} """ # just get the first cat. If they assigned to more than one, tough try:...
[ "def", "get_related_galleries", "(", "gallery", ",", "count", "=", "5", ")", ":", "# just get the first cat. If they assigned to more than one, tough", "try", ":", "cat", "=", "gallery", ".", "sections", ".", "all", "(", ")", "[", "0", "]", "related", "=", "cat"...
37.133333
22.866667
def sink(wrapped): """Creates an SPL operator with a single input port. A SPL operator with a single input port and no output ports. For each tuple on the input port the decorated function is called passing the contents of the tuple. .. deprecated:: 1.8 Recommended to use :py:class:`@spl.f...
[ "def", "sink", "(", "wrapped", ")", ":", "if", "not", "inspect", ".", "isfunction", "(", "wrapped", ")", ":", "raise", "TypeError", "(", "'A function is required'", ")", "return", "_wrapforsplop", "(", "_OperatorType", ".", "Sink", ",", "wrapped", ",", "'pos...
36.214286
20.285714
def fits_finder_chart( fitsfile, outfile, fitsext=0, wcsfrom=None, scale=ZScaleInterval(), stretch=LinearStretch(), colormap=plt.cm.gray_r, findersize=None, finder_coordlimits=None, overlay_ra=None, overlay_decl=None, overla...
[ "def", "fits_finder_chart", "(", "fitsfile", ",", "outfile", ",", "fitsext", "=", "0", ",", "wcsfrom", "=", "None", ",", "scale", "=", "ZScaleInterval", "(", ")", ",", "stretch", "=", "LinearStretch", "(", ")", ",", "colormap", "=", "plt", ".", "cm", "...
33.167347
22.489796
def _register_task(self, output_type, rule, union_rules): """Register the given TaskRule with the native scheduler.""" func = Function(self._to_key(rule.func)) self._native.lib.tasks_task_begin(self._tasks, func, self._to_type(output_type), rule.cacheable) for selector in rule.input_selectors: sel...
[ "def", "_register_task", "(", "self", ",", "output_type", ",", "rule", ",", "union_rules", ")", ":", "func", "=", "Function", "(", "self", ".", "_to_key", "(", "rule", ".", "func", ")", ")", "self", ".", "_native", ".", "lib", ".", "tasks_task_begin", ...
50.285714
25.52381
def ret_nodegroup_minions(self): ''' Return minions which match the special list-only groups defined by ssh_list_nodegroups ''' nodegroup = __opts__.get('ssh_list_nodegroups', {}).get(self.tgt, []) nodegroup = _tgt_set(nodegroup) return self._ret_minions(nodegroup...
[ "def", "ret_nodegroup_minions", "(", "self", ")", ":", "nodegroup", "=", "__opts__", ".", "get", "(", "'ssh_list_nodegroups'", ",", "{", "}", ")", ".", "get", "(", "self", ".", "tgt", ",", "[", "]", ")", "nodegroup", "=", "_tgt_set", "(", "nodegroup", ...
40.875
20.875
def is_sqlserver_2008_or_later(engine: "Engine") -> bool: """ Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server, version 2008 or later? """ if not is_sqlserver(engine): return False version_tuple = get_sqlserver_product_version(engine) return version_tuple >= (SQL...
[ "def", "is_sqlserver_2008_or_later", "(", "engine", ":", "\"Engine\"", ")", "->", "bool", ":", "if", "not", "is_sqlserver", "(", "engine", ")", ":", "return", "False", "version_tuple", "=", "get_sqlserver_product_version", "(", "engine", ")", "return", "version_tu...
37.777778
14.444444
def watch(self, filepath, func=None, delay=None): """Add the given filepath for watcher list. Once you have intialized a server, watch file changes before serve the server:: server.watch('static/*.stylus', 'make static') def alert(): print('foo') ...
[ "def", "watch", "(", "self", ",", "filepath", ",", "func", "=", "None", ",", "delay", "=", "None", ")", ":", "if", "isinstance", "(", "func", ",", "string_types", ")", ":", "func", "=", "shell", "(", "func", ")", "self", ".", "watcher", ".", "watch...
40.28
19.8
def _histplot_op(ax, data, **kwargs): """Add a histogram for the data to the axes.""" bins = get_bins(data) ax.hist(data, bins=bins, align="left", density=True, **kwargs) return ax
[ "def", "_histplot_op", "(", "ax", ",", "data", ",", "*", "*", "kwargs", ")", ":", "bins", "=", "get_bins", "(", "data", ")", "ax", ".", "hist", "(", "data", ",", "bins", "=", "bins", ",", "align", "=", "\"left\"", ",", "density", "=", "True", ","...
38.4
14.2
def update(self, spec, document, upsert=False, manipulate=False, safe=True, multi=False, callback=None, **kwargs): """Update a document(s) in this collection. Raises :class:`TypeError` if either `spec` or `document` is not an instance of ``dict`` or `upsert` is not an ins...
[ "def", "update", "(", "self", ",", "spec", ",", "document", ",", "upsert", "=", "False", ",", "manipulate", "=", "False", ",", "safe", "=", "True", ",", "multi", "=", "False", ",", "callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", ...
45.43299
21.164948
def flip(f): """Flip the order of positonal arguments of given function.""" ensure_callable(f) result = lambda *args, **kwargs: f(*reversed(args), **kwargs) functools.update_wrapper(result, f, ('__name__', '__module__')) return result
[ "def", "flip", "(", "f", ")", ":", "ensure_callable", "(", "f", ")", "result", "=", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "f", "(", "*", "reversed", "(", "args", ")", ",", "*", "*", "kwargs", ")", "functools", ".", "update_wrapper", ...
35.571429
23
def sort_against(list1, list2, reverse=False): """ Arrange items of list1 in the same order as sorted(list2). In other words, apply to list1 the permutation which takes list2 to sorted(list2, reverse). """ try: return [item for _, item in sorted(zip(list2, list1), key=...
[ "def", "sort_against", "(", "list1", ",", "list2", ",", "reverse", "=", "False", ")", ":", "try", ":", "return", "[", "item", "for", "_", ",", "item", "in", "sorted", "(", "zip", "(", "list2", ",", "list1", ")", ",", "key", "=", "lambda", "x", ":...
31.25
19.25
def _load_greedy(self, module_name, dependencies, recursive): """Keeps loading modules in the filepaths dictionary until all have been loaded or the module is found.""" found = module_name in self.modules allmodules = list(self._pathfiles.keys()) i = 0 while not found an...
[ "def", "_load_greedy", "(", "self", ",", "module_name", ",", "dependencies", ",", "recursive", ")", ":", "found", "=", "module_name", "in", "self", ".", "modules", "allmodules", "=", "list", "(", "self", ".", "_pathfiles", ".", "keys", "(", ")", ")", "i"...
45.642857
16.142857
def _get_files(): """General script to download file from online sources. Each remote file should be specified in the list of dict REMOTE_FILES. Each entry in REMOTE_FILES contains: filename : the filename which is used by the test scripts cached : the filename which is stored in the cache directory...
[ "def", "_get_files", "(", ")", ":", "for", "remote", "in", "REMOTE_FILES", ":", "final_file", "=", "DATA_PATH", "/", "remote", "[", "'filename'", "]", "if", "not", "final_file", ".", "exists", "(", ")", ":", "temp_file", "=", "DOWNLOADS_PATH", "/", "remote...
40.37037
23.12963
def set_timeout(self, state, function, newtimeout): """ Workaround to change timeout values in the ATMT.timeout class method. self.timeout format is:: {'STATE': [ (TIMEOUT0, <function foo>), (TIMEOUT1, <function bar>)), (None, None) ...
[ "def", "set_timeout", "(", "self", ",", "state", ",", "function", ",", "newtimeout", ")", ":", "state", "=", "STATES2NAMES", "[", "state", "]", "for", "timeout_fn_t", "in", "self", ".", "timeout", "[", "state", "]", ":", "# access the function name", "if", ...
37.413793
17.137931
def get(self, uri): """ Return node for uri or None if not exists: {uri: x, content: y} """ cache_key = self._build_cache_key(uri) value = self._get(cache_key) if value is not None: return self._decode_node(uri, value)
[ "def", "get", "(", "self", ",", "uri", ")", ":", "cache_key", "=", "self", ".", "_build_cache_key", "(", "uri", ")", "value", "=", "self", ".", "_get", "(", "cache_key", ")", "if", "value", "is", "not", "None", ":", "return", "self", ".", "_decode_no...
31.333333
7.555556
def normalised_autocorrelation_function(chain, index=0, burn=None, limit=None, fig=None, figsize=None): """ Plot the autocorrelation function for each parameter of a sampler chain. :param chain: The sampled parameter values. :type chain: :class:`numpy.ndarray` :param index: [...
[ "def", "normalised_autocorrelation_function", "(", "chain", ",", "index", "=", "0", ",", "burn", "=", "None", ",", "limit", "=", "None", ",", "fig", "=", "None", ",", "figsize", "=", "None", ")", ":", "factor", "=", "2.0", "lbdim", "=", "0.2", "*", "...
25.46988
22.289157
def _put_file(self, file): """Send PUT request to S3 with file contents""" post_params = { 'file_size': file.size, 'file_hash': file.md5hash(), 'content_type': self._get_content_type(file), } headers = self._request_headers('PUT', file.prefixed_name...
[ "def", "_put_file", "(", "self", ",", "file", ")", ":", "post_params", "=", "{", "'file_size'", ":", "file", ".", "size", ",", "'file_hash'", ":", "file", ".", "md5hash", "(", ")", ",", "'content_type'", ":", "self", ".", "_get_content_type", "(", "file"...
36.130435
20.086957
def edit_filter(self): """Edit name filters""" filters, valid = QInputDialog.getText(self, _('Edit filename filters'), _('Name filters:'), QLineEdit.Normal, ", "...
[ "def", "edit_filter", "(", "self", ")", ":", "filters", ",", "valid", "=", "QInputDialog", ".", "getText", "(", "self", ",", "_", "(", "'Edit filename filters'", ")", ",", "_", "(", "'Name filters:'", ")", ",", "QLineEdit", ".", "Normal", ",", "\", \"", ...
55.9
24.5
def fwdl_status_output_fwdl_state(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fwdl_status = ET.Element("fwdl_status") config = fwdl_status output = ET.SubElement(fwdl_status, "output") fwdl_state = ET.SubElement(output, "fwdl-state") ...
[ "def", "fwdl_status_output_fwdl_state", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "fwdl_status", "=", "ET", ".", "Element", "(", "\"fwdl_status\"", ")", "config", "=", "fwdl_status", "output"...
37.5
11.416667
def subfield_get(self, obj, type=None): """ Verbatim copy from: https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38 """ if obj is None: return self return obj.__dict__[self.field.name]
[ "def", "subfield_get", "(", "self", ",", "obj", ",", "type", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "return", "self", "return", "obj", ".", "__dict__", "[", "self", ".", "field", ".", "name", "]" ]
30.625
13.875
def _create_index_content(words): """Create html string of index file. Parameters ---------- words : list of str List of cached words. Returns ------- str html string. """ content = ["<h1>Index</h1>", "<ul>"] for word in words: content.append( ...
[ "def", "_create_index_content", "(", "words", ")", ":", "content", "=", "[", "\"<h1>Index</h1>\"", ",", "\"<ul>\"", "]", "for", "word", "in", "words", ":", "content", ".", "append", "(", "'<li><a href=\"translations/{word}.html\">{word}</a></li>'", ".", "format", "(...
21.75
22.375
def parse_json_form(dictionary, prefix=''): """ Parse an HTML JSON form submission as per the W3C Draft spec An implementation of "The application/json encoding algorithm" http://www.w3.org/TR/html-json-forms/ """ # Step 1: Initialize output object output = {} for name, value in get_all_...
[ "def", "parse_json_form", "(", "dictionary", ",", "prefix", "=", "''", ")", ":", "# Step 1: Initialize output object", "output", "=", "{", "}", "for", "name", ",", "value", "in", "get_all_items", "(", "dictionary", ")", ":", "# TODO: implement is_file flag", "# St...
32.375
14.775
def int2mjd(d, loc): """ Function to convert segment+integration into mjd seconds. """ # needs to take merge pkl dict if len(loc): intcol = d['featureind'].index('int') segmentcol = d['featureind'].index('segment') if d.has_key('segmenttimesdict'): # using merged pkl ...
[ "def", "int2mjd", "(", "d", ",", "loc", ")", ":", "# needs to take merge pkl dict", "if", "len", "(", "loc", ")", ":", "intcol", "=", "d", "[", "'featureind'", "]", ".", "index", "(", "'int'", ")", "segmentcol", "=", "d", "[", "'featureind'", "]", ".",...
37.764706
21.882353
def find_include_path(): """Find MXNet included header files. Returns ------- incl_path : string Path to the header files. """ incl_from_env = os.environ.get('MXNET_INCLUDE_PATH') if incl_from_env: if os.path.isdir(incl_from_env): if not os.path.isabs(incl_from_e...
[ "def", "find_include_path", "(", ")", ":", "incl_from_env", "=", "os", ".", "environ", ".", "get", "(", "'MXNET_INCLUDE_PATH'", ")", "if", "incl_from_env", ":", "if", "os", ".", "path", ".", "isdir", "(", "incl_from_env", ")", ":", "if", "not", "os", "."...
37.28125
19.625
def tornadopath2openapi(urlspec, method): """Convert Tornado URLSpec to OpenAPI-compliant path. :param urlspec: :type urlspec: URLSpec :param method: Handler http method :type method: function """ if sys.version_info >= (3, 3): args = list(inspect.sig...
[ "def", "tornadopath2openapi", "(", "urlspec", ",", "method", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "3", ")", ":", "args", "=", "list", "(", "inspect", ".", "signature", "(", "method", ")", ".", "parameters", ".", "keys", "(...
36.478261
12.217391
def executor(func_or_executor: Union[Executor, str, Callable[..., T_Retval]]) -> \ Union[WrappedCallable, Callable[..., WrappedCallable]]: """ Decorate a function to run in an executor. If no executor (or ``None``) is given, the current event loop's default executor is used. Otherwise, the argu...
[ "def", "executor", "(", "func_or_executor", ":", "Union", "[", "Executor", ",", "str", ",", "Callable", "[", "...", ",", "T_Retval", "]", "]", ")", "->", "Union", "[", "WrappedCallable", ",", "Callable", "[", "...", ",", "WrappedCallable", "]", "]", ":",...
39.628571
24.257143
def queryset(self, request, **kwargs): """ Returns the queryset (along with ordering) to be used when retrieving object(s). """ qs = self.model._default_manager.all() if self.ordering: qs = qs.order_by(*self.ordering) return qs
[ "def", "queryset", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "qs", "=", "self", ".", "model", ".", "_default_manager", ".", "all", "(", ")", "if", "self", ".", "ordering", ":", "qs", "=", "qs", ".", "order_by", "(", "*", "se...
35
12.25
def positional(max_pos_args): """A decorator to declare that only the first N arguments may be positional. Note that for methods, n includes 'self'. """ __ndb_debug__ = 'SKIP' def positional_decorator(wrapped): if not DEBUG: return wrapped __ndb_debug__ = 'SKIP' @wrapping(wrapped) def...
[ "def", "positional", "(", "max_pos_args", ")", ":", "__ndb_debug__", "=", "'SKIP'", "def", "positional_decorator", "(", "wrapped", ")", ":", "if", "not", "DEBUG", ":", "return", "wrapped", "__ndb_debug__", "=", "'SKIP'", "@", "wrapping", "(", "wrapped", ")", ...
29.24
15.76
def report_alerts(alerts, output_format='table'): """ Print our alerts in the given format. """ num_alerts = len(alerts) if output_format == 'json': click.echo(json.dumps(alerts, indent=4)) else: console.info('Issues found: {0}'.format(num_alerts)) if num_alerts > 0: ...
[ "def", "report_alerts", "(", "alerts", ",", "output_format", "=", "'table'", ")", ":", "num_alerts", "=", "len", "(", "alerts", ")", "if", "output_format", "==", "'json'", ":", "click", ".", "echo", "(", "json", ".", "dumps", "(", "alerts", ",", "indent"...
38.076923
19.461538
def get_password(self): """ If password is not provided will look in environment variables for username+'password'. """ if self.password is None: if os.environ.get(self.username+'password'): self.password = os.environ.get(self.username+'password') ...
[ "def", "get_password", "(", "self", ")", ":", "if", "self", ".", "password", "is", "None", ":", "if", "os", ".", "environ", ".", "get", "(", "self", ".", "username", "+", "'password'", ")", ":", "self", ".", "password", "=", "os", ".", "environ", "...
37.5
14.3
def read(self, entity=None, attrs=None, ignore=None, params=None): """Provide a default value for ``entity``. By default, ``nailgun.entity_mixins.EntityReadMixin.read`` provides a default value for ``entity`` like so:: entity = type(self)() However, :class:`Interface` requ...
[ "def", "read", "(", "self", ",", "entity", "=", "None", ",", "attrs", "=", "None", ",", "ignore", "=", "None", ",", "params", "=", "None", ")", ":", "# read() should not change the state of the object it's called on, but", "# super() alters the attributes of any entity ...
38.466667
19.022222
def to_cloudformation(self, **kwargs): """Returns the CloudWatch Logs Subscription Filter and Lambda Permission to which this CloudWatch Logs event source corresponds. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to ...
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "function", "=", "kwargs", ".", "get", "(", "'function'", ")", "if", "not", "function", ":", "raise", "TypeError", "(", "\"Missing required keyword argument: function\"", ")", "source_ar...
41.736842
23.526316
def p_scalar__literal(self, p): """ scalar : B_LITERAL_START scalar_group B_LITERAL_END """ scalar_group = ''.join(p[2]) p[0] = ScalarDispatch('%s\n' % dedent(scalar_group).replace('\n\n\n', '\n'), cast='str')
[ "def", "p_scalar__literal", "(", "self", ",", "p", ")", ":", "scalar_group", "=", "''", ".", "join", "(", "p", "[", "2", "]", ")", "p", "[", "0", "]", "=", "ScalarDispatch", "(", "'%s\\n'", "%", "dedent", "(", "scalar_group", ")", ".", "replace", "...
40.833333
14.833333
def match(self, a, b): """Determine if two unique identities are the same. This method compares the email addresses or the names of each identity to check if the given unique identities are the same. When the given unique identities are the same object or share the same UUID, th...
[ "def", "match", "(", "self", ",", "a", ",", "b", ")", ":", "if", "not", "isinstance", "(", "a", ",", "UniqueIdentity", ")", ":", "raise", "ValueError", "(", "\"<a> is not an instance of UniqueIdentity\"", ")", "if", "not", "isinstance", "(", "b", ",", "Uni...
37.5
20.833333
def _main(args): """Batch compression. args contains: * input - path to input directory * output - path to output directory or None * apikey - TinyPNG API key * overwrite - boolean flag """ if not args.apikey: print("\nPlease provide TinyPNG API key") print("To obta...
[ "def", "_main", "(", "args", ")", ":", "if", "not", "args", ".", "apikey", ":", "print", "(", "\"\\nPlease provide TinyPNG API key\"", ")", "print", "(", "\"To obtain key visit https://api.tinypng.com/developers\\n\"", ")", "sys", ".", "exit", "(", "1", ")", "inpu...
25.8125
19.8125
def convert_reshape(net, node, module, builder): """Converts a reshape layer from mxnet to coreml. This doesn't currently handle the deprecated parameters for the reshape layer. Parameters ---------- net: network An mxnet network object. node: layer Node to convert. modul...
[ "def", "convert_reshape", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "param", "=", "_get_attr", ...
34.72973
25.810811
def add_path_to_sys_path(self): """Add Spyder path to sys.path""" for path in reversed(self.get_spyder_pythonpath()): sys.path.insert(1, path)
[ "def", "add_path_to_sys_path", "(", "self", ")", ":", "for", "path", "in", "reversed", "(", "self", ".", "get_spyder_pythonpath", "(", ")", ")", ":", "sys", ".", "path", ".", "insert", "(", "1", ",", "path", ")" ]
42.5
8
def _Decode(self, codec_name, data): """Decode data with the given codec name.""" try: return data.decode(codec_name, "replace") except LookupError: raise RuntimeError("Codec could not be found.") except AssertionError: raise RuntimeError("Codec failed to decode")
[ "def", "_Decode", "(", "self", ",", "codec_name", ",", "data", ")", ":", "try", ":", "return", "data", ".", "decode", "(", "codec_name", ",", "\"replace\"", ")", "except", "LookupError", ":", "raise", "RuntimeError", "(", "\"Codec could not be found.\"", ")", ...
36.375
12.125
def hyperparameters(self): """Return hyperparameters used by your custom TensorFlow code during model training.""" hyperparameters = super(RLEstimator, self).hyperparameters() additional_hyperparameters = {SAGEMAKER_OUTPUT_LOCATION: self.output_path, # TODO...
[ "def", "hyperparameters", "(", "self", ")", ":", "hyperparameters", "=", "super", "(", "RLEstimator", ",", "self", ")", ".", "hyperparameters", "(", ")", "additional_hyperparameters", "=", "{", "SAGEMAKER_OUTPUT_LOCATION", ":", "self", ".", "output_path", ",", "...
56.8
32.1
def write_contents(self, table, reader): """Write the data contents of `table` to the output file. :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:cla...
[ "def", "write_contents", "(", "self", ",", "table", ",", "reader", ")", ":", "# start variable optimiztions", "pr", "=", "self", ".", "process_row", "f_write", "=", "self", ".", "f", ".", "write", "verbose", "=", "self", ".", "verbose", "# end variable optimiz...
36.244898
20.571429
def update_value_map(layer, exposure_key=None): """Assign inasafe values according to definitions for a vector layer. :param layer: The vector layer. :type layer: QgsVectorLayer :param exposure_key: The exposure key. :type exposure_key: str :return: The classified vector layer. :rtype: Qg...
[ "def", "update_value_map", "(", "layer", ",", "exposure_key", "=", "None", ")", ":", "output_layer_name", "=", "assign_inasafe_values_steps", "[", "'output_layer_name'", "]", "output_layer_name", "=", "output_layer_name", "%", "layer", ".", "keywords", "[", "'layer_pu...
33.417476
18.854369
def getInstalled(): """ Returns a list of strings representing the installed wxPython versions that are found on the system. """ installed = _find_installed() return [os.path.basename(p.pathname)[3:] for p in installed]
[ "def", "getInstalled", "(", ")", ":", "installed", "=", "_find_installed", "(", ")", "return", "[", "os", ".", "path", ".", "basename", "(", "p", ".", "pathname", ")", "[", "3", ":", "]", "for", "p", "in", "installed", "]" ]
33.857143
11.285714
def authorize(self, email, permission_type='read', cloud=None, api_key=None, version=None, **kwargs): """ This API endpoint allows you to authorize another user to access your model in a read or write capacity. Before calling authorize, you must first make sure your model has been registered. ...
[ "def", "authorize", "(", "self", ",", "email", ",", "permission_type", "=", "'read'", ",", "cloud", "=", "None", ",", "api_key", "=", "None", ",", "version", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'permission_type'", "]", "=", ...
69.8
40.1
def count_jobs_to_dequeue(self): """ Returns the number of jobs that can be dequeued right now from the queue. """ # timed ZSET if self.is_timed: return context.connections.redis.zcount( self.redis_key, "-inf", time.time()) # ...
[ "def", "count_jobs_to_dequeue", "(", "self", ")", ":", "# timed ZSET", "if", "self", ".", "is_timed", ":", "return", "context", ".", "connections", ".", "redis", ".", "zcount", "(", "self", ".", "redis_key", ",", "\"-inf\"", ",", "time", ".", "time", "(", ...
30.538462
17.230769
def Cov(self): """ calculate the covariance matrix of the tips assuming variance has accumulated along branches of the tree accoriding to the the provided Returns ------- M : (np.array) covariance matrix with tips arranged standard transersal order. ...
[ "def", "Cov", "(", "self", ")", ":", "# accumulate the covariance matrix by adding 'squares'", "M", "=", "np", ".", "zeros", "(", "(", "self", ".", "N", ",", "self", ".", "N", ")", ")", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")...
33.555556
19
def is_modern_windows_install(version): """ The 2.1 release line was when Cassandra received beta windows support. Many features are gated based on that added compatibility. Handles floats, strings, and LooseVersions by first converting all three types to a string, then to a LooseVersion. """ v...
[ "def", "is_modern_windows_install", "(", "version", ")", ":", "version", "=", "LooseVersion", "(", "str", "(", "version", ")", ")", "if", "is_win", "(", ")", "and", "version", ">=", "LooseVersion", "(", "'2.1'", ")", ":", "return", "True", "else", ":", "...
37.25
21.583333