content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def sanitize_dict(obj): """Convert all dict values in str. Parameters ---------- obj : dict Returns ------- new_obj : dict with all values as str """ new_obj = dict([(k, str(v)) for k, v in obj.items()]) return new_obj
3af5f179b991b1aa221fc6b88f2eceac7229e6a7
583,010
def goal_error(name): """Adds a string which occurs in the output of coq if a goal is admitted. Arguments: - `name`: a goal name """ return "*** [ {0!s}".format(name)
85d2fc3ece04e4f43a60736acc388437d65a5d68
583,011
def bbands_inside_kchannels(dataframe_name): """Creates signals for long position Args: dataframe_name (df): Dataframe containing indicator data for Bollinger Bands and Keltner Channels Returns: A dataframe of: original data passed to function, bbkc_squeeze (flt): Sig...
9f7bbc5da186183eae1e9d1808edbc3d4df0e1e0
583,016
def pare_dict(d, ref, strict_b=False, **kw): """Pare down a dict D according to a reference dict REF. Returns a dict, a pared-down version of D. Any item in D that matches an item in REF is removed from the output dict. Arguments: D: the dict to be pared down REF: ...
a8884f804c9e4c954060e9593d742f784b683562
583,017
def total_layer_values(layer_values_dict, layer_count): """ Calculate the total cycle/energy value of a network by summing up the values for each unique layer, multiplied by the number of times a layer with those dimensions appears in the network. """ total = 0 for layer in layer_values_dict: ...
bf75dc6c115f54d03f6090bde0d04f2a61db8362
583,020
def total_node_hours(pt_df, cpu_factor=8, cores_per_node=68, memory_per_node=96, memory_min=10): """ Estimate the total number of node hours to do an image processing run. Parameters ---------- pt_df : pandas.DataFrame DataFrame containing the number of instances, t...
151fcdc722a70dc96cee902751645ffe6a18f042
583,026
def sort_points_by_Y(list_of_points): """Given a list of 2D points (represented as Point objects), uses "sorted" with the "key" argument to create and return a list of the points sorted in increasing order based on their Y coordinates, without modifying the original list.""" sorting_func = lambda po...
c60c16a179b4dd7eebec9d16c90eb47c8b6dbd5a
583,027
def is_true(value): """ Check wether value contains the string 'true' in a variety of capitalizations (e.g. "True" or "TRUE"). """ return value.lower() == 'true'
51cc0ba42bfef3a8206d4a294364aca0708aa054
583,030
def exp2(p): """Return 2^p""" return 2**p
521bf813b9475286e0d2e3ff86ca9dfb472a2d8e
583,031
import json def main(value: str) -> str: """Get a summary of the results of the predictions. Parameters ---------- value: str List-formatted string of the predictions Returns ------- str JSON-formatted string representing the summary of predictions """ results = j...
7a12cc934d630bde0d1d6441696b8792bd5b7e42
583,033
import json def create_json(api_key, event_type, payload): """Create event json using the provided api key, event type and event payload""" json_dict = dict(api_key=api_key, event_type=event_type, payload=payload) return json.dumps(json_dict)
a641dd3edaa692afac12f8373868958ab005ce5a
583,034
def _number_of_vars(line): """Count the number of variables in the line, excluding comments denoted by # and the first word which is expected to be the variable name""" ncommands = 0 for word in line: if word[0] != '#': ncommands += 1 else: break ncommands -= 1 ...
48cf3657953cfbc16e33138c00e56839c49afc56
583,036
import torch def get_image(width, height, grayscale=False): """Generate image Tensor, returns CHW""" channels = 1 if grayscale else 3 numel = width * height * channels img = torch.arange(numel, dtype=torch.int64) % 256 img = img.reshape(channels, height, width).to(torch.uint8) return img
9353036f3f4a0d16767803dab1b1830e35f2a5de
583,038
def files_have_same_dtype(las_files): """Returns true if all the files have the same numpy datatype""" dtypes = {las.points.dtype for las in las_files} return len(dtypes) == 1
0fa3eab9df8c73b58865e11acebc74a9251ceb5d
583,040
def _lowest_version_interpreter(interpreters): """Given a list of interpreters, return the one with the lowest version.""" lowest = interpreters[0] for i in interpreters[1:]: lowest = lowest if lowest < i else i return lowest
4c314fb8eba84c378df43b91ddffc06b0d9f6e35
583,043
def fix_aips_header(header): """ Search through an image header. If the keywords BMAJ/BMIN/BPA are not set, but there are AIPS history cards, then we can populate the BMAJ/BMIN/BPA. Fix the header if possible, otherwise don't. Either way, don't complain. Parameters ---------- header : :cla...
7a44915ca7181209f07f449f261b80d5cb88d401
583,045
import requests import json def get_latest_btc_prices(days_of_prices): """Fetches the latest daily Bitcoin prices up to days_of_prices days in the past. Parameters ---------- days_of_prices : int Number of days in the past, to fetch BTC prices from. """ response = r...
87768f7bb7f782d779b31a547e261c02cf5687fe
583,046
def clean_path(path:str)->str: """ Removes redundant quotes/apostrophes from the provided path. (In case a user has typed/pasted the path with quotes) :param path: 'raw' path :type path: str :return: path without redundant quotes :rtype: str | """ if ord(path[0]) == 34 or ord(p...
e2167fd3714e538ccfe8a7c9fc4d4a4affd00dbd
583,049
def process_input(puzzle_input, u_input, target_loc): """Records the passed u_input in the location specified, and returns the resulting puzzle input """ puzzle_input[0, target_loc] = u_input return puzzle_input
56c723c239b697ec67a81247a1c8ad452c266a4f
583,051
def get_request_url(base_url, resource_path, query): """Helper method to construct the Url for a server request. Combined the base Url with the resource path and appends the query parameters (if not empty). Parameters ---------- base_url: string Base Url for the server resource_path...
c56dfb35b9d458ba3f70529fc99aaabfad3efc36
583,052
def findFeature(cov, chrom, start, end): """ Judge if the target region overlap with features. """ if chrom not in cov: return False for t in range(start, end): if t in cov[chrom]: return True return False
0737dce3d2a61a6268331021d089c50745eb3fd6
583,055
def get_member(obj, dotted, default=None): """ Return member or member of a member of the object specified. :param obj: object to get member from. :param dotted: dotted string representing the member or member of a member. :param default: any object. :return: whatever the method returns or defau...
cf249e49a160a69a2b5a84f06b41e987786292ea
583,061
def _make_radio_btn_group_dict(radio_btn_groups): """ Creates a dictionary that associates each given radio button group with its name. The name is a property of class RadioBtnGroup. Args: radio_btn_groups: a list, set or tuple that contains instances of RadioBtnGroup Returns: dict: Its keys are the group...
7e6dea89a6a6c1a66d780acfda64b8adad4133dd
583,070
from pathlib import Path def get_hook_path(repository, name: str) -> Path: """Return path to the given named hook in the given repository.""" return repository.path / ".git" / "hooks" / name
270b9ad8583d0b66d96e046ab395bfb2f8ae71c4
583,072
def to_int_save(value): """Converts string to int, returns -1 if no int.""" try: return int(value) except ValueError: return -1
d748a6f95576d68888bafc35ea8b6cc345476440
583,075
def format_arguments(arguments): """Returns numerical arguments as int type, or None if not set.""" formated_arguments = [] for argument in arguments: if argument: argument = int(argument) formated_arguments.append(argument) return formated_arguments
a2889bf1cf947147f65277427c676401cc13434e
583,076
def rgb_to_hex(*args: float) -> str: # pragma: no cover """Convert RGB colors into hexadecimal notation. Args: *args: percentages (0% - 100%) for the RGB channels Returns: hexadecimal_representation """ red, green, blue = ( int(255 * args[0]), int(255 * args[1]), ...
c5f27bb3e5a09db0c18263b055be1bbb48906219
583,079
from pathlib import Path import yaml def load_search_conf(path): """ Load a yaml file in `path` Args: path (str | pathlib.Path): path to yaml file Returns: any: python native variable loaded by PyYaml """ print(path) print() path = Path(path) assert path.exists() ...
1e3769cdb69a56eba64d52d26c71f575056676e3
583,080
import socket def check_ip(ip, last=False): """ Checks to see if the given IP is v4 or v6 Args: ip: The ip string to be checked last: A base case to stop recursion Returns: If IP is matched as either v4 or v6 a string is returned, else False """ ip_type = (socket.AF_I...
5efa02f479f670d4180d77e4a80a54b1d4cd9a2f
583,087
import torch def generate_const_input(model, device): """Return constant inputs shape = (n_different_inputs, input_size)""" return torch.eye(model.input_size, dtype=torch.float32, device=device)
107225d3df621c370269f3f650a7a192d39532ec
583,088
import torch def transform_model_input_data_type(model_input, input_type: str): """ Default model input follow RGB format. Based the model input specified, change the type. Supported types: RGB, BGR, LAB """ model_output = model_input # In case the model takes BGR input type, we convert the RG...
d51bcd274a3c92af7ee1bb093a2aa7fe5238a94f
583,090
def decode(value): """ Decode UTF8. :param bytes value: an encoded content :return: the decoded content :rtype: str """ return value.decode('utf-8')
a276f61138d02939cfc78fe808892b7d8ed3f87e
583,091
def order(x): """ Return the order of ``x``. If ``x`` is a ring or module element, this is the additive order of ``x``. EXAMPLES:: sage: C = CyclicPermutationGroup(10) sage: order(C) 10 sage: F = GF(7) sage: order(F) 7 """ return x.order()
f2e333f8e89ccfc78ba46c4377e00548f6ee29a1
583,096
import json import tempfile def _modify_json_with(json_filename, modifier_func): """ Given a modifier_func which modifies the data in the given file, updates the json file and returns a Tempfile holding the new data """ # Update the sidecar data with open(json_filename, 'r+', encoding='utf-8')...
1daec729dc526131df9637f834ddb21407619124
583,098
def calculate_average_coverage(pol): """Calculate average coverage for a sample""" return pol["total_bases"].mean()
ea20105cc54aa828dabb4fa1005e4ca165457e1f
583,099
def get_main_version(version): """Return main version (X.Y[.Z]).""" parts = 2 if version[2] == 0 else 3 return '.'.join(str(x) for x in version[:parts])
ac17a7ccaf0ac4a5ff7830e88c3229fc103537a7
583,100
from typing import Counter def percent_repeated_blocks(text: str, block_length: int = 16) -> float: """ Checks how many repeating blocks there are in the text, which is a indication/vulnerability of ECB encryption. :param text The text in question we are checking for encryption. :param block_length ...
4ff0bb16ae03509e2b1e1360a16f13a4b4e53666
583,101
import math def round_significant(x, n): """ Rounds `x` to `n` significant digits (not the same as `n` decimal places!). """ if x==0.: return 0. exp10=10**int(math.ceil(math.log10(abs(x)))) return exp10*round(x/exp10,n)
efb02a65cbbc18fa1cdcab5813fa759ab0346fdf
583,105
from typing import Dict import requests def get_intent_probabilities(sentence: str, endpoint: str = 'http://localhost:8080/api/intent') -> Dict[str, float]: """ Return the probabilities for each intent for the specified sentence. It raises a RuntimeError if the status code to the GET request is anything o...
2ec56cb8c5080084efea43ea4e0b2dcacb28297e
583,107
def merge_groupby_dicts_inplace(left, right): """ Merges one internal groupby dictionary (right) into another one (left) and returns the merging result. Used for aggregating partial dicts into single result. """ if not right: return left for key, right_group_list in right.items(): left...
76f2abda2c7115a22be536c548b888857aefcb0d
583,110
def normalize(A): """Normalize matrix columns.""" return A / A.sum(axis=0)
7f8bb9402fe382169bf92def7556dfc7767a9d61
583,114
def chars_to_line(keys_pressed): """ Used to convert the input characters, into a string Arguments: keys_pressed - List of keys pressed Returns: line - converted list of character, into a single line """ line = '' for key in keys_pressed: line += key return line
f34c1c1f746669417d53241873f10a3ebe022720
583,119
def uniform(graph, testset, priorities): """ This function produces a uniform probability distribution for the testset. The function does not use the graph nor priorities parameters and is deterministic based on the length of the testset. :param graph: unused :param testset: list of probing tes...
0d68d0f7cb3dcf7127b5f7a8721039ebf916547f
583,125
def calculate_compare_time_difference(algorithm_time, default_time, algorithm): """Calculate the difference between a custom algorithms time taken to sort, and pythons sorted() function time taken to sort the same list, returns a readable string detailing which was faster. """ difference = algorithm...
36814d6ed19ef6421783ac66fb4d1135ca94a079
583,127
def _clean_name(name: str) -> (str): """Clean a name up for consistency and usability (as a python attr).""" replacements = { " ": "_", "-": "", "'": "", '"': "", } for find, replace in replacements.items(): name = name.replace(find, replace) return name.lowe...
598cdf788ff25c757c7a8691723d2f4fc69e312b
583,129
def find_ar_max(_ar, _ib=0, _ie=-1, _min=False): """ Finds array (or list) maximum (or minimum), index and value :param _ar: array (or list) to find max. or min. :param _ib: array index to start search :param _ie: array index to finish search :param _min: switch specifying that minimum (rather ...
013b98f2919a56ab739479a217d8c7b1e0eeb541
583,133
import re def _get_ical_event_meta(ical_event): """ Splits the 'UID' tag on the format: "event-12@abakus.no", into ["event", 12, "abakus.no"] usage: eventType, pk, domain = _get_ical_event_meta(ical_event) """ return re.split("-|@", ical_event["UID"])
e7eb2ed5c9b029efc116b4210bf9ec4b8d724dad
583,141
def _(dtobj, fmt='%Y-%m-%d') -> str: """Get date str from datetime obj""" return dtobj.strftime(fmt)
1a0e7e95b5c7be38e72e91b73904d652398596a0
583,144
def makeControlDict(name, min, max): """Generate control dictionary. Args: name: string min: int max: int Returns: dictionary """ return {"name": name, "min": min, "max": max}
f8e6ed7e9029e455a8c60cd4ecd4742b7a5aff6b
583,148
def comma_format(value): """Formats value with commas and returns new value.""" return f"{value:,}"
f47f3cad6a78bccbed3ad19b9457228481881cb0
583,151
from typing import Union def percentile_rank(scores: list, your_score: Union[int, float]) -> Union[int, float]: """获取百分等级 百分等级就是原始分数不 高于你的人在全部考试人数中所占的比例再乘以100。 如果你 在 90 百分位数,那就是说你比 90% 的人成绩好,或者至少不比 90% 的考试人员差。 Args: scores (list): 分数列表 your_score (int or float): 考察对象的分数 Returns:...
c257fb7959c46d9c65c40208d26abfec11c0993a
583,152
import csv def load_data(filename): """ Load gene and trait data from a file into a dictionary. File assumed to be a CSV containing fields name, mother, father, trait. mother, father must both be blank, or both be valid names in the CSV. trait should be 0 or 1 if trait is known, blank otherwise. ...
718a6fb1d3eb9a13ecae8b2438ce31cb88b88b45
583,155
def unignore(bot, input): """makes bot stop ignoring user, admins only""" if not input.admin: return False bot.config.set_del('ignore',input.group(2).lower()) bot.reply("Unignored {0}".format(input.group(2)))
8d9b11c642dce4fef5b783818f62a9172341298e
583,161
from unittest.mock import call def PresentDialog_Confirm_Call( message ): """Return a mock.call object for a call to vimsupport.PresentDialog, as called why vimsupport.Confirm with the supplied confirmation message""" return call( message, [ 'Ok', 'Cancel' ] )
065de0fe38c39bc58a203c959fbf13af5cd61539
583,162
def read_graph(lines, base=True): """Given the lines of a digraph file, return the graph data. :param lines: a sequence of lines :type lines: [str, ...] :param base: Shall I consider base edges? :type base: bool :return: front edges, background edges, total weight and root ve...
5ebce61e287a379e0ea91cebe7f2d6b77ef55c5d
583,163
def build_update_mask(params): """Creates an update mask list from the given dictionary.""" mask = [] for key, value in params.items(): if isinstance(value, dict): child_mask = build_update_mask(value) for child in child_mask: mask.append('{0}.{1}'.format(key,...
3490274ca88f2034c536ad558680d7c9bc6857e9
583,164
def _extract_tags(cluster): """Pull the tags from a cluster, as a dict.""" return {t['Key']: t['Value'] for t in cluster.get('Tags') or []}
54eb4e18cc207c9e6490c5ff24f178fe071d8659
583,166
def binary_search(arr, low, high): """ Purpose : This function find the smallest element using Binary search Input : arr : The array from which the smallest element has to be returned low : Starting index of the array high : End index of the array Output : ...
8c26377e2da2aa1a014cacb942b0239c205590c4
583,167
def spin(programs, move): """Spin, written sX, makes X programs move from the end to the front, but maintain their order otherwise. (For example, s3 on abcde produces cdeab).""" move_ = int(move[1:]) return programs[len(programs) - move_:] + programs[:len(programs) - move_]
74c0e51b1c3c1b08834a1598cac99597e67ff10f
583,168
def pupil_json_to_opencv(pupil): """Convert pupil loaded from json file to the format used by OpenCV, i.e. ((cx, cy), (ax, ay), angle) Returns: Tuple containing ((cx, cy), (ax, ay), angle) """ p = pupil return ((p['cx'], p['cy']), (p['ax'], p['ay']), p['angle'])
d2e459b40390e48796f6de3555ce825d1b83a560
583,184
def has_disk_at(board, position): """ Check whether a disk is stored at the given position on the given board. - The function returns false if no disk can be obtained from the given board at the given position. ASSUMPTIONS - The given board is a proper board and the given p...
2a6e1898583c5e57183b243e788b51eb6a3fe215
583,185
def square_root_3param(t, a, b, t0): """t^1/2 fit w/ 3 params: slope a, horizontal shift t0, & vertical shift b.""" return a*(t-t0)**(0.5) + b
4fb1717bb8991409ac2818eff982b5d29721c2fb
583,187
def sorted_by_name(list_): """Helper to sort lists-of-dicts """ return sorted(list_, key=lambda d: d['name'])
a002c8bdf18b85d64c17d78e69b706a4fd47c6aa
583,188
import locale def decode_output(output: bytes) -> str: """Try to decode the given bytes with encodings from the system. :param output: output to decode :raises UnicodeDecodeError: if all encodings fail :return: decoded string """ try: return output.decode("utf-8") except UnicodeDe...
2ef184e3f2acf1ce6b07d165dbf056089407174f
583,192
def _generate_table_urls(base_url: str, n_records: int, odata_version: str) -> list: """Creates a list of urls for parallel fetching. Given a base url, this function creates a list of multiple urls, with query parameters added to the base url, each reading "$skip={i}" where i is a multiplication of 10,000 ...
cfd1a158cb9c63f28a94f9174a5c45ca86aeeefb
583,193
def get_source_id(sl): """sl is list of sources in form: ns:id. Return the ns and id of the last entry""" source = sl[len(sl) - 1] # get last source item ns, id = source.split(':') return (ns, id)
7bb38c901213607aa9aa13b9e8c46660cb6eab05
583,197
from pathlib import Path def get_project_dir() -> Path: """ Returns the project directory Path object :return: Path """ return Path(__file__).parent.parent.absolute()
82e07dab73d1cfee18ec77663d22caa992d10f6c
583,198
def get_unique(l): """ Get unique values from list Placed outside the class beacuse `list` conflicts our internal method with the same name. """ return list(set(l))
6451ad4e6f8e38f7d16ef582c2dcb97dc2f6eaeb
583,201
def _format_firewall_stdout(cmd_ret): """ Helper function to format the stdout from the get_firewall_status function. cmd_ret The return dictionary that comes from a cmd.run_all call. """ ret_dict = {"success": True, "rulesets": {}} for line in cmd_ret["stdout"].splitlines(): if...
677193e72e3e8b5ceb2f8fa25942527449383599
583,204
from math import pi, cos, radians def reproject(latitude, longitude): """Returns the x & y coordinates in meters using a sinusoidal projection""" earth_radius = 6371009 # in meters lat_dist = pi * earth_radius / 180.0 y = [lat * lat_dist for lat in latitude] x = [longe * lat_dist * cos(radians(la...
d85d91f5282bb0a5c2b3074f923ae7f7d4ed01fb
583,210
def num_batches(n, batch_size): """Compute the number of mini-batches required to cover a data set of size `n` using batches of size `batch_size`. Parameters ---------- n: int the number of samples in the data set batch_size: int the mini-batch size Returns ------- ...
60fee68f98f2bd39672c43b2b2e6546c89a22034
583,213
def dir_ls(conn, segments = 1, mirror=None): """Show distinct directory names, looking only on the first path components. Manually, this could be done in the following way: select distinct array_to_string((string_to_array(path, '/'))[0:2], '/') from filearr """ query = """SELECT DISTINCT array_to_...
623e40d6911c92a2cabb159e778a65ae218a03a7
583,218
import re def _CanonicalizePath(secret_path): """Canonicalizes secret path to the form `/mount_path:/secret_file_path`. Gcloud secret path is more restrictive than the backend (shortn/_bwgb3xdRxL). Paths are reduced to their canonical forms before the request is made. Args: secret_path: Complete path to...
23172730253065d846e2124af191203e7849e59f
583,222
def new_constant(const_name): """ Returns an SMT command to declare a new integer constant """ return "(declare-const " + const_name + " Int)\n"
43c03796b7816d17ffa8a8133ca6b18c0e6b50f4
583,224
def _process_labels(labels, signal, length): """Process time response signal labels. Parameters ---------- labels : list of str or dict Description of the labels for the signal. This can be a list of strings or a dict giving the index of each signal (used in iosys). signal : str ...
99700f317872086982c46599f41dbd1e6577e96b
583,227
def column(matrix, i): #select i columns of array. """Select ith column of np.array object""" return [row[i] for row in matrix]
e2b6c820b5aeeecbb0f85b7ad0ed6903fca5faf9
583,229
from io import StringIO def shellish_split(string: str) -> list[str]: """Perform shell-like word splitting on the given string. A bit more arbitrary and simplistic compared to ``shlex``, as it does *too* much for ZeroBot's command needs. Only a limited set of escape sequences have an effect, the rest...
4c7a45e204f38e0bafe2279859a16b89c98e2fbf
583,232
def dbuv_to_dmw_per_sq_m(dbuv): """ Convert dB(uV) to dB(mW/m^2) from http://www.ahsystems.com/notes/RFconversions.php: dBmW/m2 = dBmV/m - 115.8 @param dbuv : dB(uV) @type dbuv : float @return: dBm/m^2 as float """ return dbuv - 115.8
295340dd67ae60c389de1828c46b2a5d11b17509
583,233
import types def _type_repr(obj): """Return the repr() of an object, special-casing types (internal helper). If obj is a type, we return a shorter version than the default type.__repr__, based on the module and qualified name, which is typically enough to uniquely identify a type. For everything ...
1da7d3af3a2fa31e909c2c00f59e92af32dfbf4e
583,234
def target_unique_name(hs, name_prefix): """Make a target-unique name. `name_prefix` is made target-unique by adding a rule name suffix to it. This means that given two different rules, the same `name_prefix` is distinct. Note that this is does not disambiguate two names within the same rule. Given...
9695c2074db9bfca6d4860b523aedf8344782c36
583,237
def angular_kinetic_energy(i, w): """ Calculates the angular kinetic energy of an object with moment of inertia 'I' and angular velocity 'w' Parameters ---------- i : float w: float Returns ------- float """ return (1/2) ...
1d0d5c58662e5e258b82a9b80e6321f02e071dd7
583,241
import binascii def hexlify(data: bytes, with_prefix=False) -> str: """Convert bytes data to hexadecimal string.""" encoded = binascii.hexlify(data).decode('ascii') if with_prefix: return '0x' + encoded return encoded
81341215865f0498ca7b8b8b9fff40f827b6a51b
583,244
def verify_boolean(value): """Throws an exception if value is not a bool """ if type(value)!=bool: raise ValueError("expected boolean value.") return value
8ecc16328c5fb038ff3cd2d06f9a55b046c85582
583,247
def iou(a,b): """ Description ----------- Calculates intersection over union for all sets of boxes in a and b Parameters ---------- a : tensor of size [batch_size,4] bounding boxes b : tensor of size [batch_size,4] bounding bo...
620aff899b67724ae475fef8c9960df8d5ca9f02
583,250
def find_quarter(fields): """Find the fields with project quarters""" return [field for field in fields if field.startswith("Q")]
960b670b37ec22fc19ec1e550cd513f58e4f09ab
583,251
def clean_section_name(section: str) -> str: """Make a section name suitable to be used in the INI, since it can't have starting "[" or a trailing "]". Unfortuantly, ConfigObj doesn't do this for us.""" new_section_name = section.strip("[]") if not new_section_name: raise ValueError("Invalid...
84ad5b21b42babd405cfdaca9f467fd8ba5e5510
583,254
def line_at_point(self, point): """ Shorthand string extraction method. """ return self.view.substr(self.view.line(point))
a5c484a9d6130cb095673c35138954276a1cc4ea
583,255
def remove_umlaut(string): """ Removes umlauts from strings and replaces them with the letter+e convention :param string: string to remove umlauts from :return: unumlauted string """ u = 'ü'.encode() U = 'Ü'.encode() a = 'ä'.encode() A = 'Ä'.encode() o = 'ö'.encode() O = 'Ö'....
a6fae0e15cb3f196c3bdbe87bc90d4af04eb9f7c
583,259
def remove_comments(string: str): """ :param string: Must be a string of lines :return: A string representing the lines without comments (c or $) """ return ' '.join([line.split('$')[0].strip() for line in string.splitlines() if line[0].lower() != 'c'])
b4064603b8a019cf9bbef575eb21b090761dd25c
583,263
def skip_common_stack_elements(stacktrace, base_case): """Skips items that the target stacktrace shares with the base stacktrace.""" for i, (trace, base) in enumerate(zip(stacktrace, base_case)): if trace != base: return stacktrace[i:] return stacktrace[-1:]
dbd5d625aaa0a1edba0d8cf3468848e471fada54
583,264
def mean(arr, NaN=False): """Take a mean of array. If NaN==True, NaNs are excluded""" if NaN: c = sum(map(lambda x: x==x, arr)) s = sum(map(lambda x: (x==x) and x or 0, arr)) try: return 1.0*s/c except ZeroDivisionError: return float('na...
77d9a3b770bdb8ad6fd70e9bb04640fe0101db83
583,265
import logging def get_instance_template_to_delete(key): """Returns the URL of the instance template to delete. Args: key: ndb.Key for a models.InstanceTemplateRevision entity. Returns: The URL of the instance template to delete, or None if there isn't one. """ instance_template_revision = key.get...
66afb85d0c8646b7214f718805c58aefc57a685a
583,268
import typing def decode_bool(as_bytes: typing.List[int]) -> bool: """Decodes a boolean. """ return bool(as_bytes[0])
01f933ed62b5e18a33e68e279bbba65e69c20c50
583,272
import re def snake_casify(name): """Turns the given name to follow snake_case convention.""" name = re.sub('\W+', '', name).split() name = [s.lower() for s in name] return '_'.join(name)
27f1333e1eede40735d0ad8c03e30ad242ac5394
583,274
def extract_ccs_path(file_path): """Extracts and returns the ccs path from file path. Args: file_path (str): full path of file Returns: str: ccs path (contained in 'file_path') """ file_path = file_path.replace('\\', '/') index = file_path.index('ccsv') end = file_path.inde...
9e27cb56f6a272c089b3d4e75d6511dbcf2116a9
583,278
def lerp(low: float, high: float, x: float): """Linear interpolation from [0, 1] → [low, high] (`low + (high - low) * x`)""" return low + (high - low) * x
9c3b046f9a2001f8f38f83e7d01abce4de0570cb
583,283
def setup_apply_cmd(parser): """ Sets up an 'apply' command for a strategy command parser. ex: sw-manager patch-strategy apply <some args> :param parser: the strategy parser to register the command under """ apply_cmd = parser.add_parser('apply', help='Apply a...
818b7f89aed6679e346266f51e07fbef7bb9c4f5
583,287
import six def isstr(x): """Returns True if x is a string""" return isinstance(x, six.string_types)
30c6c42e2d4395f7c016ba4ae20e6473d9b22e4d
583,288
from typing import Dict def parse_commit_message(commit_message: str) -> Dict[str, str]: """ 解析提交信息 :param commit_message: git提交信息 :return: 写入yaml的结构 """ commit_type, commit_content = commit_message.split(":", maxsplit=1) return {"commit_type": commit_type.strip(), "commit_content": commit...
4c27c4d688d525ff06b27ba6cff6b4aa387d4edb
583,289
def motif2regex(motif): """Converts a protein motif query to a regex search""" return motif.replace('X', '.').replace('x', '.').replace('(', '{').replace(')', '}')
6215e53be7d64712a01d9589270180047dfd1667
583,292