content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Any def is_same(value1: Any, value2: Any) -> bool: """ Checks to see if 2 values are the same .. note:: this method is used by almost every card when printing """ if isinstance(value1, str) or value1 is None: return value1 == value2 if value1 == value2: retu...
e492e9ff821ca8183bbfe7d633f9c35f1f538a53
566,493
def get_intersection(df, comparator1, comparator2): """ Return a dataframe with only the columns found in a comparative dataframe. Parameters ---------- comparator1: DataFrame DataFrame to preform comparison on. comparator2: DataFrame DataFrame to compare with. Returns ...
5e4b51be839ea49e69935babcfc72727e064eb92
566,495
import hashlib def sha3_256(data): """Get hash value using sha3_256 hash function. :param data: :return: 256bit hash value (32 bytes). type(bytes) """ return hashlib.sha3_256(data).digest()
ed1625472ee5e2af062a34799b38a61aa1cbfd3a
566,496
def box_iou(box1_pts, box2_pts): """Calculate IoU of box1 and box2 Args: box1_pts (list): [left, top, right, bottom] (xyrb) box2_pts (list): [left, top, right, bottom] (xyrb) Returns: float: IoU of box1 and box2 """ box_intersection_pts = [ max(box1_pts[0], box2_pts...
1baafa0d8c8d9d8c526f88b7d41ba4c5b4e19468
566,498
from typing import Tuple from typing import List import math def get_batch_resources(sh_num_arms: list, eta: int) -> Tuple[int, List[int]]: """Compute the number of batches & iterations per batch Args: sh_num_arms (list): List of number of arms per iteration eta (int): Halving parameter ...
3376697a8088f5afb52b024d9f245215e1809880
566,499
import base64 def decodebase64(inputStr, decodeFlag=True): """ Decode base64 to real format """ if decodeFlag and inputStr: return base64.b64decode(inputStr) return inputStr
92047f7e1c798d3d0ca6a0a0f8f8d78fbecd1204
566,501
import re def words(text): """A list of all the alphabetic words in text, ignoring non-letters.""" return re.findall(r'[a-zA-Z]+', text)
ef503633681d689aa2cf2547b09c03b23d1b8df1
566,502
def bool_yes_no(process, longname, flag, value): """ Phrase Boolean values as 'YES' or 'NO' """ if value==True: return "YES" if value==False: return "NO" # Anything else wasn't a bool! raise ValueError("Flag value '%s' wasn't boolean." % repr(value))
b6b5d63eb56284c3ccd475ad8b666727bda186ca
566,508
def is_reproducible(item): """Return True if the testcase is reproducible by checking the one_time_crasher_flag.""" return not item.one_time_crasher_flag
eede7695563a6d459c717298b3eace02ef163b05
566,509
def get_key_index(keyboard, key): """ get the x, y postition of a specific key on the keyboard """ for y, row in enumerate(keyboard): for x, item in enumerate(row): if item == key: return (x, y)
f1f5792e853b8065473aafe3c1eb6763a3dcc787
566,511
import re def pdf_has_images(path: str) -> bool: """Check raw PDF for embedded images. We need to check if a PDF contains any images. If a PDF contains images it likely has content that needs to be scanned. :param path: Location of PDF to process. :return: Does the PDF contain images? :type...
2b5f01d872ee53459772751ac0e77e2ca2d9251e
566,512
def null_query(x): """ Returns false regardless of the document passed to the function. """ return False
cd64cb092a03991ee45aa0a58c9bbfd708b19b5b
566,514
import itertools def _chunk(iterable, size): """Split an iterable into chunks of a fixed size.""" # We're going to use some star magic to chunk the iterable. We create a # copy of the iterator size times, then pull a value from each to form a # chunk. The last chunk may have some trailing Nones if the...
eb418877683bd67460a9363010284498adc935f2
566,516
def isiterable(x): """Determine if object is iterable.""" # good enough, don't want to match strings return isinstance(x, (list, tuple))
b518ba20b25476f9b9763d1e70867c219c42d182
566,517
def decode_read_data(read: list, encoding='utf-8'): """ Interprets bytes under the specified encoding, to produce a decoded string. """ decoded = "" try: decoded = bytes(read).decode(encoding).rstrip('\0') except UnicodeDecodeError: return decoded return decoded
8598ca5fbf2d31fa822ba41062a8a39c5ac21fd1
566,518
def gr_to_bv(g, r): """ From https://www.sdss3.org/dr8/algorithms/sdssUBVRITransform.php Returns the B-V value and the RMS error. """ return .62*(g - r) + .15, .07
b665a5a52611e89cb36895dc89be6e3461ec14ba
566,519
def handle_validation_errors(obj, msg): """Wrap validation errors. """ obj.check_pass = False obj.check_msg = msg return obj.check_pass, obj.check_msg
9f95ad5efa8895042abb920a1056ea9c9baf37bf
566,526
def sls_cmd(command, spec): """Returns a shell command string for a given Serverless Framework `command` in the given `spec` context. Configures environment variables (envs).""" envs = ( f"STAGE={spec['stage']} " f"REGION={spec['region']} " f"MEMORY_SIZE={spec['memory_size']} " )...
11d55f92e7dd34676666dfbfb8068490a33fb282
566,533
def recycle_palette(palette, size): """Cycle through a palette (list) until it reaches desired length (int).""" length = len(palette) nrepeat = (size // length) + 1 out = palette * nrepeat return out[0:size]
96cf3e1f5c208f6961854c52e84da6048c57e236
566,534
from typing import List from typing import Dict from typing import Set def get_unique_related_host_ids(security_problems: List[Dict]) -> Set[str]: """Extract all unique related host IDs from a list of security problems. :param security_problems: the security problems, parsed from JSON to Dicts of Dicts :r...
b45a8603ef8a5712ee18da3421339a180524040f
566,537
def convert_str_tolist(astring): """Convert a string into a list, splitting each value by comma.""" return map(str.strip, astring.strip(',').split(','))
a60ee7e0aa2df57a727bcdcb61ebd3b99a395752
566,540
def _is_under_dir(file_name: str, dir_name: str) -> bool: """ Return whether a file is under the given directory. """ subdir_names = file_name.split("/") return dir_name in subdir_names
04628976736f719e08b046d3a012f8931d4e5cc5
566,541
import torch def conv1x1(in_planes: int, out_planes: int, stride: int = 1): """ 1x1 convolution without padding. Args: in_planes (int): The number of input channels. out_planes (int): The number of output channels. stride (int): The convolution stride. Controls the stride for the ...
f09e75dfda34801a355501dc4de76f392c861eda
566,542
def abfFileFormat(fb): """ This function returns 1 or 2 if the ABF file is v1 or v2. This function returns False if the file is not an ABF file. The first few characters of an ABF file tell you its format. Storage of this variable is superior to reading the ABF header because the file forma...
e30d3eae3d53e2915a7c7e7ddc04f5d4e2712ae1
566,545
from typing import List from typing import Tuple def read_lines( src_translations_path: str, trg_translations_path: str ) -> List[Tuple[str, str]]: """ Read in lines from two separate text files the form the tokenized paralell corpus Return a list of tuples contained in the sentence pa...
7f42782178722889dfc11585b04524af318742e1
566,547
def sanitize_fb_return_data(results): """ Sometimes integers are returned as string try to sanitize this a bit Parameters ---------- results: dict dict of results from fritzconnection call Returns ------- dict: sanitized version of results """ return_results = {} ...
f4605943a30fa0fc36552de9a1f9d156940a1bef
566,550
def get_column(table, col) : """Get values in given column""" values = list() for row in range(len(table)) : if table[row][1] == 'Locked' : values.append(table[row][col]) return values
5e17deeeecfd02f8a83bbd64138b151993a32d07
566,554
def value_to_wep(confidence_value): """ This method will transform an integer value into the WEP scale string representation. The scale for this confidence representation is the following: .. list-table:: STIX Confidence to WEP :header-rows: 1 * - Range of Values - WEP ...
75046ccc1b9da3fd90eaa6da883f26e40cd0bfc1
566,557
def force_noslashend(path): """ Return ``path`` with any trailing ``/`` removed. """ if path.endswith('/'): path = path.rstrip('/') return path
87f53dfae819823fcf2d6e7fd668012608759a76
566,559
def line_to_int_list(line): """ Args: line: A string of integers. Ex: '1 3 5\n' Returns: A list of integers. Ex: [1, 3, 5] """ data = line.split(' ') data = filter(None, data) data = [int(x.strip('\n')) for x in data] return data
0ba3f984704219f134185a80d7858e176679e8bf
566,560
def has_loops(path): """Returns True if this path has a loop in it, i.e. if it visits a node more than once. Returns False otherwise.""" visited = {} for node in path: if node not in visited: visited[node] = 0 else: return True return False
64e2a85510d4f6bc49ddf012f0a208811187da71
566,561
from typing import Any def isint(x: Any) -> bool: """Return true iff argument is an integer.""" return isinstance(x, int) and not isinstance(x, bool)
6fdb1e7054cba5320400687d805b1bdcb4cc3d88
566,562
import math def joint_distance(j1, j2) -> float: """ Compute Euclidean distance between two Kinect joints :param j1: joint 1 :param j2: joint 1 :return: distance """ x = (j1.Position.x - j2.Position.x)**2 y = (j1.Position.y - j2.Position.y)**2 z = (j1.Position.z - j2.Position.z)**...
1c32a4f35a716c495c2c316d0843e3a81f788df2
566,567
def roundup_to_integer_multiple(x, factor): """Round up integer x to the nearest integer multiple of integer factor. Returns x if factor is set to -1. Both x and factor must otherwise be positive.""" # ensure integers assert int(x) == x, "The input x is not an integer." assert int(factor) == fac...
1088fee469d4be343d8016ead16e7b533c84f4e5
566,569
import csv def get_type_efficacies(csv_dir, pkm_types): """Get information to build pokediadb.models.TypeEfficacy objects. Args: csv_dir (pathlib.Path): Path to csv directory. pkm_types (dict): Dict of dict containing type infos. Returns: list: Dict containing infos to build ...
e413fc9ef78a69df4d23a1aa30dd724aa48e13b5
566,571
import re def get_version_from_href(href): """Returns the api version in the href. Returns the api version in the href. If no version is found, 1.0 is returned Given: 'http://www.nova.com/123' Returns: '1.0' Given: 'http://www.nova.com/v1.1' Returns: '1.1' """ try: #fin...
7c0d727c0ffc799a8301b41f67f1ac667fc4708a
566,574
def _group_name(group_email): """Gets an IAM member string for a group email.""" return 'group:{}'.format(group_email)
70766eb629aaaf8c43c0ae4aa4e88feb738c8e11
566,576
import torch def predict_nationality(surname, classifier, vectorizer): """Predict the nationality from a new surname Args: surname (str): the surname to classifier classifier (SurnameClassifer): an instance of the classifier vectorizer (SurnameVectorizer): the corresponding vectorizer...
c7c92804e6eefaa8b110d2fef2ce5e33769b3606
566,578
def exposure_index_values(H_a): """ Computes the exposure index values :math:`I_{EI}` from given focal plane exposure :math:`H_a`. Parameters ---------- H_a : array_like Focal plane exposure :math:`H_a`. Returns ------- ndarray Exposure index values :math:`I_{EI}`. ...
e552b101c5e10157abcc204ac5d1860b0b2067d8
566,579
def create_token_request_payload(auth_code, redirect_uri, optional_token_request_params): """ Construct payload for access token request """ token_request_payload = { # Don't include client_id param: Verizon doesn't like it 'grant_type': 'authorization_code', 'code': auth_code, ...
d61708ec69913fcc52ec3538a240633716e36377
566,580
def factorial(n): """Compute basic factorial function Parameters ---------- n : integer Specifies the number to be factorial Returns ------- Float value of the product for all n """ if n == 0: return 1.0 else: return float(n) * f...
5f2ed21090414fd31b8ccc7d22a4e81feb4c091c
566,583
def get_repository_heads( repo ): """Return current repository heads, which are changesets with no child changesets.""" heads = [ repo[ h ] for h in repo.heads( None ) ] return heads
a5a3cfc34534ba60c29deb360d14125d31d23c71
566,584
def _overlap (case, space): """ This is a private method used only by the Maximal Rectangle algorithms that follow. Given a case and a space, it controls if the case partially overlap with the space. If this happens, the overlap is returned. :param case: The case :param space: The space :r...
dbe7ffcfcebb900632b5f581ea13ac38b9eec2ff
566,589
from typing import List def find_min_conquered(lst: List[int]) -> int: """ Return the smallest value in <lst>. Can also be designed with parameters b, and e, rather than slicing the lists in the current algorithm. O(lg(n)) >>> find_min_conquered([3, 4, 5, 6, 7]) 3 >>> find_min_conquered([5, 6...
7d95a17a5867866508b8aeb049dab83ee20118e7
566,591
def get_api_url(method): """ Returns API URL for the given method. :param method: Method name :type method: str :returns: API URL for the given method :rtype: str """ return 'https://slack.com/api/{}'.format(method)
07601a55f74b6e5c957cfe3c93935301f2fd4145
566,592
def _get_profile_version(_fs, kind): """Returns available raw profiles from the give filesystem :param fs.base.FS _fs: filesystem instance :param str kind: *'demand'*, *'hydro'*, *'solar'* or *'wind'*. :return: (*list*) -- available profile version. """ matching = [f for f in _fs.listdir(".") if...
90fe55c2684628a7001a2bc6bbd49a5077da2b31
566,595
def pkcs7_pad(message, block_size): """Pads the given message with the PKCS 7 padding format for the given block size.""" # If the length of the given message is already equal to the block size, there is no need to pad if len(message) == block_size: return message # Otherwise compute the paddi...
a27b2105aa954e599fd8e88dd1b4806a881efd3e
566,597
def down_sample(sound, sample_rate_out): """Downsample audio Args: sound (pydub.AudioSegment): Sound imported as a AudioSegment object sample_rate_out (int): Final sample rate for output data Returns: pydub.AudioSegment: Downsampled audio """ # Manually override the fra...
53883088ddcbe99456f517a951e2d0e1b827b7d4
566,598
import re def squeeze(value): """Replace all sequences of whitespace chars with a single space.""" return re.sub(r"[\x00-\x20]+", " ", value).strip()
305058579738e06cebf024db517fa60ea599912c
566,604
def is_valid_action(action): """Return whether or not the action function is a valid detcord action Args: action (function): the function to check Returns: bool: Whether or not the action is valid """ return getattr(action, 'detcord_action', False) != False
a5b6b0790f7aa7069a4f955dbb85b6bb4d52f9f3
566,605
def paren_matcher(s: str, open_index: int) -> int: """ Solution: Iterate through the s from the open_paren index, keeping track of how many remaining open parens there are. When we get to 0, return the index. Complexity: Time: O(n) - Iterate through our string once Space: O(n) - We take a slice of the input s ...
5dbdbfa305d7ce946cdf05a202f8622801ed0a7c
566,606
def get_comma_separated_values(values): """Return the values as a comma-separated string""" # Make sure values is a list or tuple if not isinstance(values, list) and not isinstance(values, tuple): values = [values] return ','.join(values)
a2c7148f4cd67636bf5f918a3bcbd5a1e95d8942
566,609
def url_for(path=''): """Simple function to generate URLs with the base GitHub URL.""" return 'https://api.github.com/' + path.strip('/')
d661fd6d21ccb4bec6107c3d5bc4d1d6badc38ca
566,611
import mimetypes def _is_image(url): """ Checks whether a normal url contains an image. Params: (str) url: the url for the image Returns: (bool): True if url contains an image, False otherwise. """ mimetype, encoding = mimetypes.guess_type(url) return (mimetype and mimetyp...
32110d546abc67a067e80d499c6fd567e329bba1
566,614
import functools def compose(*functions): """Compose two or more functions.""" def compose2(f, g): return lambda x: f(g(x)) return functools.reduce(compose2, functions, lambda x: x)
27c509632b19f6d6ae954af0efbb05ba724e8340
566,618
def axis(name=None, cols=None, values=None, units=None): """Convenience function for generating axis descriptions when defining MetaArrays Example:: MetaArray([...], info=[ axis('Time', values=[0.0, 0.1, 0.2, 0.3], units='s'), axis('Signal', cols=[('V0', 'V', 'Voltage0'), ('V1', 'V', 'Voltage1'), ...
bd8b17289539f5c3c286cff0c8ef68af663e4560
566,625
def insertSort(sortList): """ 插入排序 :param sortList: 排序的列表 :return: 排序后的列表 """ for index in range(1, len(sortList)): currentValue = sortList[index] position = index while position > 0 and sortList[position-1] > currentValue: sortList[position] = sortList[posi...
cbbba449339f53bde19cd7c0b9218a260af9dff2
566,626
import base64 def encode_key(key: int) -> bytes: """ Encodes an integer key into a fixed length string """ return base64.b64encode( key.to_bytes(8, byteorder='little') )
ca768a40975f0b52026040d8e6a15c7d1f837a17
566,628
def _to_ffmpeg_time(n): """ Format number of seconds to time expected by FFMPEG. :param n: Time in seconds to format. :returns: Formatted time in FFMPEG format. """ m, s = divmod(n, 60) h, m = divmod(m, 60) return '%d:%02d:%09.6f' % (h, m, s)
b97702e3d0723efb8300759688e019a0e41392f8
566,631
def salpeter1955(libitem, index): """ Initial mass function from Salpeter (1955) https://ui.adsabs.harvard.edu/abs/1955ApJ...121..161S """ return libitem["massini"][index] ** (-2.35)
a66a487539985d52bde10d3ca3683dfdb16fd00b
566,635
def render_PendingUser_avatar(self, h, comp, model, *args): """Render a user's avatar""" with h.span(class_='avatar', title='%s' % (self.username)): h << h.i(class_='ico-btn icon-mail2') return h.root
d8a606c814c0cb16d715375cb385a1ef122fadc8
566,643
def get_attribute(obj, attr): """ Return object attribute value, if it exists. Arguments: obj (object): The object. attr (str): The name of the object attribute. """ at = getattr(obj, attr, None) if at: return at else: return None
b4fec78ea304b63e9b11c0be3edf7bda864cc8f5
566,645
def print_counter(i: int) -> None: """Print a counter. """ print('\n') print('Counter updated at each iteration over the children:') print('i = ', i) print('\n') return None
795c84739a17a27bd783b4faabc7129fbd65c159
566,646
import asyncio def prepare_repair_loop_callback_done_future(session): """Creates future that Awaits for session.repair_loop_task to be completed and returns value of session.closing""" loop = asyncio.get_running_loop() future = loop.create_future() repair_loop_task = session.repair_loop_task def ...
d0400d4f497161876d7a30c2e96cae6bb1ce7101
566,647
import time def getTime(start, digits=2): """Get and return the time elapsed since start to now (in seconds, to digits decimal places).""" end = time.time() f = "{:." + str(digits) + "f}" return f.format(end-start)
a6c1eba010bb475343a329a47e05e3cb5509d98d
566,648
def atomic_min(ary, i, v): """ Atomically, perform `ary[i] = min(ary[i], v)` and return the previous value of `ary[i]`. This operation does not support floating-point values. i must be a simple index for a single element of ary. Broadcasting and vector operations are not supported. This should be ...
e8fbd4c193d9526a386e431aea41415fe3975a22
566,653
from typing import Union def sum_arithmetic_series(a: Union[int, float], d: Union[int, float], n: int) -> float: """Get sum of first `n` terms of arithmetic series Args: a: First number in series d: Common difference of series n: Number of terms in series Examples: >>> pr...
e677956c8972e7f1f6d1407f66a25128435176d7
566,654
def get_leaf_decision(l_yes, l_no, parent_decision) -> int: """returns leaf decision with majority decision if not equal else returns it's parent decision""" leaf_value = 0 if l_yes > l_no: leaf_value = 1 elif l_yes == l_no: leaf_value = 1 if parent_decision else 0 return leaf_value
6e065617fbdbbf963a7e103a8154972e317dd586
566,656
import math def _find_closest_prefix_power(number: float) -> int: """Return the closest power associated with an SI prefix. Args: number (float): A number to find the prefix power for. Returns: int: The closest SI prefix power. """ return ( max(min(math.floor(math.log10(a...
bab265ba9fe5c335fb503d9fc8f0cd3ace2eb7e6
566,657
import turtle import math def drawHouse(unit): """ Draws the house on the screen :pre: (relative) pos (0,0), heading (east), down :post: (relative) pos (0,0), heading (east), up :param unit: constant required to build the walls and roof of the house :return: wood required to build the house ...
accfe7b85fa18b996ba290b7e0652173a6547825
566,660
def escape_squared_brackets(string: str) -> str: """Escape squared brackets which would be accidentally parsed by rich. An example are the ids of parametrized tasks which are suffixed with squared brackets surrounding string representations of the parametrized arguments. Example ------- >>> es...
851e8016149de8f0a62922f9adb3568d33921916
566,666
import itertools def merge_event_pages(event_pages): """ Combines a iterable of event_pages to a single event_page. Parameters ---------- event_pages: Iterabile An iterable of event_pages Returns ------ event_page : dict """ pages = list(event_pages) if len(pages)...
913b924d2f2218b32bfc34eb3fca86047b28071a
566,667
def num_digits(n): """ Given a number n, this function returns its number of digits in base 10. """ return len(str(n))
7c8a275e637445c79ae0454b7351b2cd40f8c800
566,669
def _chnops_sort(ion_elements): """ Reorder elements to be consistently ordered per the method in pyMSpec """ return [ *'CHNOPS', *sorted(key for key in ion_elements.keys() if len(key) > 1 or key not in 'CHNOPS'), ]
abf98f1189628b92abaa51c0dfad6d55cb386562
566,672
import pathlib def get_creation_timestamp(filename): """Get creation timestamp for a file""" filen = pathlib.Path(filename) assert filen.exists() return filen.stat().st_ctime
aa8b8b1efa24c0449c7d53eb4bb15de4c51cbea2
566,673
import json def get_pretty_json(dictionary, spaces=4): """ Makes JSON output prettuer and readable. :return: stringified JSON """ return json.dumps(dictionary, indent=spaces)
d33ef80412329d5b1a8e940d08c737777a9bf4ad
566,676
def delete(sentence, mainword, **kwargs): #Done with testing """Delete entire sentence if <mainword> is present""" if mainword not in sentence: return False, sentence else: return True, ''
848334b65d506a44321639d6ae97259dc29c573d
566,677
def offset_to_line(filename, offsets): """Convert a list of offsets in a file to a dictionary of line, column. [ offset ] -> { offset: (line,column) } """ if not filename: return {offset: (0, 0) for offset in offsets} offsets = sorted(set(offsets)) line = 1 mappings = {} file_off...
447c9781dba673bcb57dfe000891f5851050e10e
566,678
def binarize_labels_nosaic_mnist(labels): """Change labels like even (class 0) vs odd (class 1) numbers """ labels = labels % 2 return labels
0381a2d13af32b943355adc89dae827d0951df3c
566,679
def is_reference_html_file(filename): """Return true if the filename points to a reference HTML file.""" if (filename.endswith('-expected.html') or filename.endswith('-expected-mismatch.html')): return True return False
72c635528fb96d6a5c475c348df03c3b44147fbf
566,682
def get_progressive_min(array): """Returns an array representing the closest to zero so far in the given array. Specifically, output value at index i will equal `min(abs(array[:i+1]))`. Parameters ---------- array : list of :obj:`~numbers.Number` or :obj:`numpy.array` Input ...
f278e5481280662d3cc663b91290d1ce2b62b8e1
566,686
import re def get_matches(regex: str, string: str) -> list: """ Get the matches from applying a regex on a string. """ matches = re.finditer(regex, string, re.MULTILINE) lt_matches = [] for match in matches: lt_matches += [match.group()] return lt_matches
9de5d16e94477676affcbe0c67ac8868503c2587
566,687
from typing import List from typing import Any def remove_empty_str(list_in: List[Any]) -> List[Any]: """ Remove empty strings ('' or ' ' or ' ') from list.""" out = [] for obj in list_in: if isinstance(obj, str): obj.strip() if obj.strip() != "": out.app...
76311805bdeae5b4c66b552f95fa5d84ca74df63
566,689
import json def read_json(file: str) -> dict: """ Read JSON file :param file :type file: str :raises IOError, JSONDecodeError :returns dict """ hnd = open(file, 'r') data = hnd.read() hnd.close() return json.loads(data)
eee360a22bd19dc19adcb02f21350917b9983849
566,692
import json def load_results(output_dir): """Load the results file""" results_file = output_dir / "search_results.json" if results_file.exists(): with open(results_file, encoding="utf8") as f: return json.load(f) else: return {}
19c5a994060b283b67ea8a691934760416bdd294
566,697
def filename2format(fn, places=3): """Converts a filename to a format string capable of adding an index after the basename""" index = "{:0" + str(places) + "d}" if places else "{}" last_dot = fn.rfind(".") if last_dot < 0: # not found return fn + index else: return fn[0:last_dot] + i...
fd38dcd452fec754cdd2f9f5a6f8ef8105456b15
566,703
from typing import Dict from typing import Any def _worker_group_index(raycluster: Dict[str, Any], group_name: str) -> int: """Extract worker group index from RayCluster.""" group_names = [spec["groupName"] for spec in raycluster["spec"]["workerGroupSpecs"]] return group_names.index(group_name)
80d1321c33d74f3f578c8c61c111405fc9bc3005
566,704
import re def normalize_token(token): """ Convert symbols to avoid collisions with reserved punctuation in NLTK and coq. To avoid collisions with reserved words, we prefix each token with an underscore '_'. """ normalized = token normalized = re.sub(r'\.', '_DOT', normalized) norma...
788ac634a86f408b2b86bd8bd31e6061db6cb768
566,710
import math def star_symbol(p): """Significance symbol under violin plot""" if p > 0.05: return "ns" else: l = -math.log10(p) nstar = math.floor(l) if nstar > 4: nstar = 4 return "*"*nstar
850f885f7c2193de48f57b7036911ce302e9fe6f
566,714
from pathlib import Path def convert_to_valid_tracking_uri(mlflow_dir): """ Converts from a windows path like 'C:/example/mlflow' to a valid mlflow tracking uri. """ mlflow_dir = Path(mlflow_dir) tracking_uri = f"file:///{(mlflow_dir / 'mlruns').as_posix()}" return tracking_uri
655d7e3cf2fd2e4dd6ddd3bda1ca5290c4a53329
566,721
def _cnt_stat(a_gold_segs, a_pred_segs): """Estimate the number of true pos, false pos, and false neg. Args: a_gold_segs (iterable): gold segments a_pred_segs (iterable): predicted segments Returns: tuple: true positives, false positives, and false negatives """ tp = fp = fn = 0 ...
18852be4cfb8cd8fbaa3f38f45108e2da7743ed3
566,726
from typing import Optional from typing import Union def int_or_float_type(value: str) -> Optional[Union[int, float]]: """ Converts a string value into an integer or a float value between 0.0 and 1.0 (inclusive). Parameters ---------- value : str The string value to be converted Retu...
20da2689a3cb79cb4c192a20b43bcd42d7573c7b
566,729
from typing import Iterable from typing import Hashable from typing import Mapping def all_equal(x: Iterable[Hashable]) -> bool: """ Checks if all elements in `x` are equal. Returns `False` if `x` is empty. Defined to improve readability. Examples: >>> all_equal((1, 1, 1, 1)) True ...
ce3328c986b1ebc0722ed86406aee920cd5ff070
566,731
def formatter(log: dict) -> str: """ Format log colors based on level. :param log: Logged event stored as map containing contextual metadata. :type log: dict :returns: str """ if log["level"].name == "WARNING": return ( "<light-cyan>{time:MM-DD-YYYY HH:mm:ss}</light-cyan...
8a0e5b5e2b675d78314f0de71009ad54b03795aa
566,732
def _unixypath_to_uri(path): """Converts a unix-style path to a file: URL.""" return '//' + path
296ea0184f18af1638f737da656f496f6fc97702
566,734
from functools import reduce def min_from_iterable(iterable): """ Return the min in the iterable >>> min_from_iterable([1, -2, 35, 11, 28]) -2 """ return reduce(min, iterable)
ac7aaa4c521a3f326029d604736efc4de46cb2da
566,737
import re def get_http_contlength(http_request): """Given a HTTP request, return the Content-Length value.""" re_match = re.search( r"Content-length\s*:\s*(\d+)", http_request, flags=re.IGNORECASE ) return int(re_match.group(1)) if re_match else 0
fcfade213118b4a627b6dacfac7d5c0c8f548cb4
566,738
def qualname(cls): """ Similar to the Python 3.3+ __qualname__ attribute. >>> qualname(C) 'C' >>> qualname(C.f) 'C.f' >>> qualname(C.D) 'C.D' >>> qualname(C.D.g) 'C.D.g' """ return '%s.%s' % (cls.__module__, cls.__name__)
4807b88f7e16279ee5e8105a98e82fcf25351593
566,740
def _find_scope_defining_line(line_index, file_content): """Finds the scope defining line for the line on the specified index. The scope defining line is the last line containing `{` that was not closed afterwards. If the scope defining line could not be found, returns (`-1`, `None`). Args: l...
d5dbe3dabc14c9c45080c40e9e8ea04ee0ef88bf
566,741
import torch def normalize_embeddings(embeddings, dim=0, order=2) -> torch.nn.Embedding: """Normalize embeddings in the specified dimension Parameters ---------- embeddings : torch.nn.Embedding dim : int, optional order : float, optional Returns ------- torch.nn.Parameter(torch.n...
7a5a76b18cc7e3e69e613d5a84956f198f5e5503
566,742