content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
from typing import List def prime_factorization(N: int) -> List[int]: """Get list of prime factors of `N` in ascending order""" factors = [] p = 2 while p * p <= N: while N % p == 0: factors.append(p) N //= p p += 1 if N > 1: # any left-over factor must be prime itself factors.append(N) return factors
c7a91ff819f5bb3d33058d5da2af9734abebba47
145,329
def unique_path(path): """Generate an unused filename that looks like `path`""" # this adds ".1", ".2" etc. before the extension orig_suffix = path.suffix orig_name = path number = 1 while path.exists(): path = orig_name.with_suffix(f'.{number}{orig_suffix}') number += 1 return path
4034815c2203321ed5e875f0ee93d280e7bc4ef3
189,329
def get_property(config_values, path): """ Safely retrieve a config value by a list-defined config key path. :param config_values: Dictionary of config values. :param path: List of strings representing nested keys into the dictionary. :return: The value of the requested path, or None if it does not exist. """ if not config_values or not path: return None if len(path) == 1: return config_values.get(path[0]) if path[0] else config_values return get_property(config_values.get(path[0]), path[1:])
bd370845833e2b582077123bf1aee72ddd69bb26
206,055
def of_type(*classinfo, **kwargs): """Returns a validator for a JSON property that requires it to have a value of the specified type. If optional=True, () is also allowed. The meaning of classinfo is the same as for isinstance(). """ assert len(classinfo) optional = kwargs.pop("optional", False) assert not len(kwargs) def validate(value): if (optional and value == ()) or isinstance(value, classinfo): return value else: if not optional and value == (): raise ValueError("must be specified") raise TypeError("must be " + " or ".join(t.__name__ for t in classinfo)) return validate
ca5a202ef3ae61f8aa366494607abc2f12a44b35
557,341
import torch def clsmap2scoremap(cls_maps, use_softmax=False, Cat=80, Anchor=9, score_shel=0): """ :param cls_maps: Cat * Anchor x H x W :param use_softmax: score如果使用了sigmoid,就可以不进行softmax操作, use_softmax可以设置为False :param Cat: 类别 :param Anchor: Anchor个数 :param score_shel: score threshold :return: score_maps: Anchor x H x W,每个anchor的最大score cat_maps: Cat x H x W,每个anchor的最大score对应的category """ map = torch.Tensor(cls_maps) assert map.shape[0] == Cat * Anchor _, H, W = cls_maps.shape score_maps = torch.zeros(Anchor, H, W) cat_maps = torch.zeros(Anchor, H, W) # 将map的每一个Anchor对应的那些channel转换为one_hot编码,并且滤除掉小于指定阈值的位置 for a in range(Anchor): score_map = map[a * Cat: (a + 1) * Cat] if use_softmax: score_map = score_map.softmax(0) (max_score, ind) = torch.max(score_map, 0) cat_maps[a] = ind max_score[max_score <= score_shel] = 0 score_maps[a] = max_score return score_maps, cat_maps
d0f6527a2c1ef0c1296d408d5cc05ca1b25580e1
377,013
def simulate_multiline(string): """Return simulated multiline input for given string.""" counter = 0 strings = string.split("\n") def simulated_input(*args): nonlocal counter if counter == len(strings): return "" value = strings[counter] counter += 1 return value return simulated_input
06e9f2b73e736809ad2569bf44c8b36fa2c6bfc7
614,039
def checkEmblFile(filin): """Check EMBL annotation file given by user""" line = filin.readline() # TEST 'ID' if line[0:2] != 'ID': return 1 else: return 0
8087a78a35193545070f76dbd969b617c7c92b0c
22,717
from typing import Optional def extract_lineage_from_line(line: str, exclude_withdrawn=True) -> Optional[str]: """ Extracts the lineage name from one of the lineage_notes.txt lines. Most lines look like this Q.3 Alias of B.1.1.7.3, USA lineage, from pango-designation issue #92 (note, that's a tab character after `Q.3`) Some lineages are "Withdrawn". This is denoted by a `*` at lineage start *B.1.1.156 Withdrawn: South African lineage (note, that's a tab character after `*B.1.1.156`) In general, from talking with Alli Black, it appears that we should be fine to only ever care about non-withdrawn lineages. Similarly, we can ignore any "alias" names mentioned (eg, `B.1.1.7.3` above), the alias name is more of an academic understanding, not something used for identification. Returns: str OR None: Lineage for the line OR None if line should be ignored """ lineage_chunk = line.split()[0] if exclude_withdrawn and lineage_chunk[0] == "*": return None return lineage_chunk
2fb87ed19ad22f24c8a5066f60a9d19bb9621617
525,106
def get_user_input(username, session_id): """ Prompt and get a command from the user. Arguments: :username: The username of the user. :session_id: The session number incremented each time asking for inputing a command. Returns: The string command the user entered. """ print('\nrf [n]: read file content [with last n lines], q: quit') return input(f'[{session_id:^3}@{username}] $ ')
53be7f822de04ccaf66a2481f3cdb808a44c2ef2
451,455
def space_tokenizer(sequence): """ Splits sequence based on spaces. """ if sequence: return sequence.split(' ')
539809996bfe16faebad8abd29bcec46e88a8283
81,562
def skip_n_lines_in_file(file_path, num_lines): """ Remove the initial num_lines of text from a file. :param file_path: The path to the file that needs initial lines removed. :param num_lines: The number of initial text lines to remove from the file at file_path. :return: The path to a new temporary file that is the same as the file at file_path, except with the initial num_lines of text removed. Create a temporary text file. Give it a '.txt' extension since all we can assume about it is that it is a text file. Open file_path, read num_lines from it without copying any, then read the rest of the lines from the file and write them to the temp file. Close the temp file and return the path to it. """ temp_file_path = '__temp_skipped_lines_file__.txt' temp_file = open(temp_file_path, 'w') with open(file_path) as orig_file: for i in range(0, num_lines): orig_file.readline() for line in orig_file: temp_file.write(line) temp_file.close() return temp_file_path
42a51d264085edeade267163254e8bf49777d98e
241,902
from typing import Any def fixture_labels_file_sync(tmpdir: Any) -> str: """Return a filepath to an existing labels file for the sync test.""" return "tests/sync.toml"
3d4624bf7cd555a4bbf2acdf4e477adec7cdd10c
495,105
import time def get_timestamp(with_milliseconds=True): """Get current timestamp. Returns: Str of current time in seconds since the Epoch. Examples: >>> get_timestamp() '1639108065.941239' >>> get_timestamp(with_milliseconds=False) '1639108065' """ t = str(time.time()) if not with_milliseconds: t = t.split(".")[0] return t
1e9fbba08244cd8f9df00b94cd69ba10bf7e5e8b
59,410
def CodepointsToUTF16CodeUnits( line_value, codepoint_offset ): """Return the 1-based UTF-16 code unit offset equivalent to the 1-based unicode codepoint offset |codepoint_offset| in the Unicode string |line_value|""" # Language server protocol requires offsets to be in utf16 code _units_. # Each code unit is 2 bytes. # So we re-encode the line as utf-16 and divide the length in bytes by 2. # # Of course, this is a terrible API, but until all the servers support any # change out of # https://github.com/Microsoft/language-server-protocol/issues/376 then we # have to jump through hoops. if codepoint_offset > len( line_value ): return ( len( line_value.encode( 'utf-16-le' ) ) + 2 ) // 2 value_as_utf16 = line_value[ : codepoint_offset ].encode( 'utf-16-le' ) return len( value_as_utf16 ) // 2
976daeb55916dbfeeff7f92e5352ee3ab135a608
679,794
from typing import List def bubble_sort(arr: List[int]) -> List[int]: """Sort a list of integers in ascending order. Args: arr (List[int]): List of integers to be sorted. Returns: List[int]: Ordered list of integers. """ s = n = len(arr) - 1 for i in range(n): a, b = 0, 1 for j in range(s): if arr[a] > arr[b]: arr[a], arr[b] = arr[b], arr[a] a, b = b, b + 1 s -= 1 return arr
e85f32c6e134a808b7f68391dfd3cc1231a73a44
220,943
def passport_valid( passport: str, required_fields: tuple[str, str, str, str, str, str, str] = ( "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", ), ) -> bool: """Check is a passport is valid, by having all required fields in it.""" fields_in_passport = [field in passport for field in required_fields] return all(fields_in_passport)
338eaeff7c88f47fa295404de8adc25c84aa5429
95,382
def get_like_status(like_status, arg_1, arg_2): """ Fetches a string for a particluar like_status args: like_status(boolean): It's either a True for a like or False for a dislike arg_1(str) arg_2(str) Returns: arg_1(str): Incase the like_status is True arg_2(str): Incase the like_status is False """ return arg_1 if like_status else arg_2
b8d975bf90386bf0f2fa3a3b96d3d3a83862f36b
594,737
def url_parse_server_protocol(settings_dict): """Return the public HTTP protocol, given the public base URL >>> url_parse_server_protocol({'USE_SSL': True}) 'https' >>> url_parse_server_protocol({'USE_SSL': False}) 'http' """ return "https" if settings_dict["USE_SSL"] else "http"
705e458e78258cd6825c57f33fc2edcc3ac1f60b
270,465
import inspect def get_linenumbers(functions, module, searchstr='def {}(image):\n'): """Returns a dictionary which maps function names to line numbers. Args: functions: a list of function names module: the module to look the functions up searchstr: the string to search for Returns: A dictionary with functions as keys and their line numbers as values. """ lines = inspect.getsourcelines(module)[0] line_numbers = {} for function in functions: try: line_numbers[function] = lines.index( searchstr.format(function)) + 1 except ValueError: print(r'Can not find `{}`'.format(searchstr.format(function))) line_numbers[function] = 0 return line_numbers
b2cc1bc104cdae6bbbfb3680ac940540396db08a
695,893
def encode_matrix_parameters(parameters): """ Performs encoding of url matrix parameters from dictionary to a string. See http://www.w3.org/DesignIssues/MatrixURIs.html for specs. """ result = [] for param in iter(sorted(parameters)): if isinstance(parameters[param], (list, tuple)): value = (';%s=' % (param)).join(parameters[param]) else: value = parameters[param] result.append("%s=%s" % (param, value)) return ';'.join(result)
d54643e25f37106d6fabc820f6e091693bf29bdd
412,890
import torch def space_motor_to_img(pt): """ Translate all control points from spline space to image space. Changes all points (x, -y) -> (y, x) Parameters ---------- pt : torch.Tensor (..., 2) spline point sequence for each sub-stroke Returns ------- new_pt : torch.Tensor (..., 2) image point sequence for each sub-stroke """ assert torch.is_tensor(pt) space_flip = torch.tensor([-1.,1.], device=pt.device) new_pt = torch.flip(pt, dims=[-1]) * space_flip return new_pt
6c1510b3b58d2864db90c739d4afb202314e0a33
350,827
def extract_guest_restraints( structure, restraints, guest_resname, dummy_prefix="DM", return_type="dict" ): """ Utility function to extract the guest restraints from a list of restraints and return individual restraints in the form ``[r, theta, phi, alpha, beta, gamma]``. If there is no restraint applied to a particular reaction coordinate a ``None`` will be inserted. This function is useful for parsing guest restraints during analysis when computing ``ref_state_work``. Parameters ---------- structure : :class:`parmed.Structure` The molecular structure of the system. restraints : list List of :class:`paprika.restraints.DAT_restraint` restraints. guest_resname : str Residue name of the guest molecule. dummy_prefix : str, optional, default="DM" The prefix for the dummy atoms residue name. return_type : str, optional, default="dict" Option to return guest restraints as a list or a dict Returns ------- guest_restraints : list or dict list of guest-specific :class:`paprika.restraints.DAT_restraint` restraints. Examples -------- Extract guest restraints from a list of restraints and compute the work for reference state >>> guest_restraints = extract_guest_restraints(structure, restraints, "BEN") >>> >>> free_energy = analysis.fe_calc() >>> free_energy.compute_ref_state_work(guest_restraints) >>> print(free_energy["ref_state_work"]) """ # Check input argument return_type = return_type.lower() if return_type not in ["list", "dict"]: raise ValueError( 'Function argument `return_type` can only take values "list" or "dict" as input.' ) guest_resname = guest_resname.upper() DM1 = f"{dummy_prefix}1" DM2 = f"{dummy_prefix}2" DM3 = f"{dummy_prefix}3" r = None theta = None phi = None alpha = None beta = None gamma = None for restraint in restraints: mask2_residue_name = structure[restraint.mask2].residues[0].name # Distance if ( DM1 in restraint.mask1 and guest_resname in mask2_residue_name and not restraint.mask3 and not restraint.mask4 ): r = restraint # Angle if restraint.mask3 and not restraint.mask4: mask3_residue_name = structure[restraint.mask3].residues[0].name if ( DM2 in restraint.mask1 and DM1 in restraint.mask2 and guest_resname in mask3_residue_name ): theta = restraint if ( DM1 in restraint.mask1 and guest_resname in mask2_residue_name and guest_resname in mask3_residue_name ): beta = restraint # Dihedral if restraint.mask4: mask3_residue_name = structure[restraint.mask3].residues[0].name mask4_residue_name = structure[restraint.mask4].residues[0].name if ( DM3 in restraint.mask1 and DM2 in restraint.mask2 and DM1 in restraint.mask3 and guest_resname in mask4_residue_name ): phi = restraint if ( DM2 in restraint.mask1 and DM1 in restraint.mask2 and guest_resname in mask3_residue_name and guest_resname in mask4_residue_name ): alpha = restraint if ( DM1 in restraint.mask1 and guest_resname in mask2_residue_name and guest_resname in mask3_residue_name and guest_resname in mask4_residue_name ): gamma = restraint if return_type == "list": guest_restraints = [r, theta, phi, alpha, beta, gamma] elif return_type == "dict": guest_restraints = { "r": r, "theta": theta, "phi": phi, "alpha": alpha, "beta": beta, "gamma": gamma, } else: raise KeyError( "`return_type` argument not valid. Only `list` or `dict` are accepted." ) return guest_restraints
339e6c24a03edfa8dffa314bd00560ce87546bf8
375,582
def collect_all_links(soup): """Finds all links on the page and returns them as a list :param soup: The BeautifulSoup object :type soup: BeautifulSoup object :returns: List with URLs """ links = [] for link in soup.find_all('a'): links.append(link.get('href')) return links
b78f8146db1f352c1c85117d336dac7612f0cb62
236,884
def _page_to_text(page): """Extract the text from a page. Args: page: a unicode string Returns: a unicode string """ # text start tag looks like "<text ..otherstuff>" start_pos = page.find(u"<text") assert start_pos != -1 end_tag_pos = page.find(u">", start_pos) assert end_tag_pos != -1 end_tag_pos += len(u">") end_pos = page.find(u"</text>") if end_pos == -1: return u"" return page[end_tag_pos:end_pos]
d4ef3ea9365260972605ce1b35dbc457e7080e8a
390,763
def stack_is_failing(events): """iterate stack events, determine if resource creation failed""" failed = False failure_modes = ('CREATE_FAILED', 'UPDATE_ROLLBACK_IN_PROGRESS') for event in events['StackEvents']: if event['ResourceStatus'] in failure_modes: failed = True if event.get('ResourceStatusReason') == "User Initiated": break return failed
95be398f3f6df51b58738e4d4a30224a3bc9af40
171,298
import socket def GetHostName(useFqdn=False): """Returns the host name, and with FQDN if specified.""" thisHost = "localhost" if useFqdn: thisHost = socket.getfqdn() # If the server is configured correctly getfqdn() works fine, but it might # take what's in /etc/hosts first, so double check to see if # hostname is more appropriate to avoid using localhost or something else if thisHost == "localhost" or thisHost == "127.0.0.1" or thisHost == "127.0.1.1" or "." not in thisHost: thisHost = socket.gethostname() else: # hostname itself could be set to FQDN too, so it could be the same as above thisHost = socket.gethostname() return thisHost
6610f0b12c625b57e6b1b7964e60c42d915bdcc3
448,648
def escapeName(name): """Escape a name such that it is safe to use for files and anchors.""" escape = '_' xs = [] for c in name: if c.isalpha() or c in ['-']: xs.append(c) else: xs += [escape, str(ord(c))] return ''.join(xs)
7b0dd8273dbbeacee754a1fdc36a2b20e6620380
545,342
def get_path_indices(not_dones): """ Returns list of tuples of the form: (agent index, time index start, time index end + 1) For each path seen in the not_dones array of shape (# agents, # time steps) E.g. if we have an not_dones of composition: tensor([[1, 1, 0, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 0, 1, 1, 0, 1]], dtype=torch.uint8) Then we would return: [(0, 0, 3), (0, 3, 10), (1, 0, 3), (1, 3, 5), (1, 5, 9), (1, 9, 10)] """ indices = [] num_timesteps = not_dones.shape[1] for actor in range(not_dones.shape[0]): last_index = 0 for i in range(num_timesteps): if not_dones[actor, i] == 0.: indices.append((actor, last_index, i + 1)) last_index = i + 1 if last_index != num_timesteps: indices.append((actor, last_index, num_timesteps)) return indices
39733f53c594389e83eb1609ab121ac3acbcb536
455,786
def query_newer_than(timestamp): """ Return a query string for later than "timestamp" :param timestamp: CloudGenix timestamp :return: Dictionary of the query """ return { "query_params": { "_updated_on_utc": { "gt": timestamp } }, "sort_params": { "id": "desc" } }
84d089ffca7f405714f3020f81500ee739d75cc9
404,627
def get_spin_link_dict(peaklist): """ Map each unique spin link to all of its corresponding peaks. NOESY peak lists represent spin links between Hydrogen atoms. Whether 2D, 3D or 4D, each peak in a NOESY peak list has exactly two Hydrogen spins. Here, a spin link is represented by a frozenset containing the spin.assignment tuples for each Hydrogen atom. This function returns a dictionary mapping each unique spin link to a list of the Peaks in the PeakList that contain those two Hydrogen atoms. Examples -------- >>> spin_link_dict = peaklist.spin_link_dict() >>> spin_link, peaks = spin_link_dict.popitem() >>> spin_link frozenset([Assignment(res_type='Q', res_num=21, atom='HN'), Assignment( res_type='G', res_num=17, atom='HN')]) >>> print(peaks[0]) Peak(spins=[ Spin(res_type=G, res_num=17, atom=HN), Spin(res_type=G, res_num=17, atom=N), Spin(res_type=Q, res_num=21, atom=HN)]) >>> print(peaks[1]) Peak(spins=[ Spin(res_type=Q, res_num=21, atom=HN), Spin(res_type=Q, res_num=21, atom=N), Spin(res_type=G, res_num=17, atom=HN)]) Returns ------- out : dictionary Each key is a frozenset made from two Hydrogen spin.assignment tuples. Each value is a list of peaks containing those two Hydrogen spins. """ spin_link_dict = {} for peak in peaklist: spins = [spin for spin in peak if spin.atom is not None and spin.atom[0] == 'H'] if len(spins) != 2: err = ('expected 2 Hydrogens in each peak, ' 'found %d' % len(spins)) raise ValueError(err) link = frozenset(spin.assignment for spin in spins) spin_link_dict.setdefault(link, []).append(peak) return spin_link_dict
c9ce2d919c57f86467ef33a558c37dd539e3a7ef
259,461
import hashlib def double_sha256(string, as_hex=False): """ Get double SHA256 hash of string :param string: String to be hashed :type string: bytes :param as_hex: Return value as hexadecimal string. Default is False :type as_hex :return bytes, str: """ if not as_hex: return hashlib.sha256(hashlib.sha256(string).digest()).digest() else: return hashlib.sha256(hashlib.sha256(string).digest()).hexdigest()
bce1607fbbab0c3c9a3b3dd2dcd2e74b6cb84f87
690,194
def has_tag(ds, tag): """ Returns whether or not the specified tag is present in the specified dataset. :param ds: The dataset to search. :param tag: The tag to search for. :return: Whether or not a DICOM tag is present. """ return tag.value in ds
04747d1d4263dd46a54a8443908fb231e90046e7
397,421
def linearsearch(A, elem): """ Linear Search Algorithm that searches for an element in an array with O(n) time complexity. inputs: Array A and element e, that has to be searched output: True/False """ for a in A: if a==elem: return True return False
5372e23eba64cacb59532a126b5aac6fdc9efe8f
650,745
def count_lines(in_path): """Counts the number of lines of a file""" with open(in_path, 'r', encoding='utf-8') as in_file: i = 0 for line in in_file: i += 1 return i
848d6cf870f449a7ba9b9c249461f0438c62a7b0
654,239
def getIndentation(text): """Get the leading whitespace of a string.""" for i in range(len(text)): if not text[i].isspace(): return text[:i]
c0565a4ab257dbdaadd7f8271173e52168afdbb6
469,225
def label_scoped_path(ctx, path): """Return the path scoped to target's label.""" return ctx.label.name + "/" + path.lstrip("/")
6b61bec030ce77dfb559ada1c694510a93cb2b21
532,849
def search(x, thing): """Search for x in thing. True iff found. Utility used only for tests in this file.""" if isinstance(thing, dict): for y in thing.values(): if search(x, y): return True elif isinstance(thing, list): for y in thing: if search(x, y): return True else: return x == thing
bb58a69f43ea41e35414f98925945fe9fc4d872f
562,486
def xfail(reason, strict=False): """ Mark a testcase/testsuit as XFail(known to fail) when not possible to fix immediately. This decorator mandates a reason that explains why the test is marked as passed. XFail testcases will be highlighted as amber on testplan report. By default, should the test pass while we expect it to fail, the report will mark it as failed. For unstable tests, set ``strict`` to ``False``. Note that doing so decreases the value of the test. :param reason: Explains why the test is marked as passed. :type reason: ``str`` :param strict: Should the test pass while we expect it to fail, the report will mark it as failed if strict is True, default is True. :type strict: ``bool`` :return: """ def _xfail_test(test): test.__xfail__ = {"reason": reason, "strict": strict} return test return _xfail_test
b5d511236980d17f999f343bcdeaaf6eff1b5c9d
404,572
from datetime import datetime from pathlib import Path def create_datetime_subdir(dir_path): """ Create subdirectory named after the current date and time. Args: dir_path (Path): Path to directory. Raises: ValueError: If `dir_path` exists, but is not a directory. Returns: dir_path (Path): New path to subdirectory. """ if not dir_path.is_dir(): if dir_path.exists(): raise ValueError(f"Not a directory: '{dir_path}'") # Create dir dir_path.mkdir(parents=True, exist_ok=True) # Create subdirectory named after the current date and time date_time = datetime.now().strftime("%Y-%m-%d_%H.%M.%S") dir_path = Path(dir_path / date_time) dir_path.mkdir() return dir_path
74df542e541faf7b93276f6d84806e3766df9c40
437,434
def asst70_variation_descriptors(moa_vid70): """Create assertion70 variation_descriptors test fixture.""" return [moa_vid70]
1e8d1fc13a55b173674c60c339f6d6a13945ca6f
69,673
def is_pulsemap_check(table_name: str) -> bool: """Check whether `table_name` corresponds to a pulsemap, and not a truth or RETRO table.""" if "retro" in table_name.lower() or "truth" in table_name.lower(): return False else: # Could have to include the lower case word 'pulse'? return True
8a467580c0ad50c357ff50d17a4ebf7e34633c09
613,366
import re def parse_show_lacp_interface(raw_result): """ Parse the 'show lacp interface' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show lacp interface command in a \ dictionary of the form: :: { 'lag_id': '100', 'local_port_id': '17' 'remote_port_id': '0' 'local_port_priority': '1' 'remote_port_priority': '0' 'local_key': '100' 'remote_key': '0' 'local_state': { 'active': True, 'short_time': False, 'collecting': False, 'state_expired': False, 'passive': False, 'long_timeout': True, 'distributing': False, 'aggregable': True, 'in_sync': False, 'neighbor_state': True, 'individual': False, 'out_sync': True }, 'remote_state': { 'active': False, 'short_time': False, 'collecting': False, 'state_expired': False, 'passive': True, 'long_timeout': True, 'distributing': False, 'aggregable': True, 'in_sync': False, 'neighbor_state': False, 'individual': False, 'out_sync': True }, 'local_system_id': '70:72:cf:52:54:84', 'remote_system_id': '00:00:00:00:00:00', 'local_system_priority': '65534', 'remote_system_priority': '0' } """ lacp_re = ( r'Aggregate-name\s*:\s*[lag]*(?P<lag_id>\w*)?[\s \S]*' r'Port-id\s*\|\s*(?P<local_port_id>\d*)?\s*\|' r'\s*(?P<remote_port_id>\d*)?\s+' r'Port-priority\s*\|\s*(?P<local_port_priority>\d*)?\s*\|' r'\s*(?P<remote_port_priority>\d*)?\s+' r'Key\s*\|\s*(?P<local_key>\d*)?\s*\|' r'\s*(?P<remote_key>\d*)?\s+' r'State\s*\|\s*(?P<local_state>[APFISLNOCDXE]*)?\s*\|' r'\s*(?P<remote_state>[APFISLNOCDXE]*)?\s+' r'System-id\s*\|\s*' r'(?P<local_system_id>([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2})?\s*\|' r'\s*(?P<remote_system_id>([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2})?\s+' r'System-priority\s*\|\s*(?P<local_system_priority>\d*)?\s*\|' r'\s*(?P<remote_system_priority>\d*)?\s+' ) re_result = re.search(lacp_re, raw_result) assert re_result result = re_result.groupdict() for state in ['local_state', 'remote_state']: tmp_dict = { 'active': 'A' in result[state], 'short_time': 'S' in result[state], 'collecting': 'C' in result[state], 'state_expired': 'X' in result[state], 'passive': 'P' in result[state], 'long_timeout': 'L' in result[state], 'distributing': 'D' in result[state], 'aggregable': 'F' in result[state], 'in_sync': 'N' in result[state], 'neighbor_state': 'E' in result[state], 'individual': 'I' in result[state], 'out_sync': 'O' in result[state] } result[state] = tmp_dict return result
a093c0912742c0bc7e538c8ec59757b370cb24de
88,662
def bonferroni_correction(pvals): """ Bonferroni correction. Reference: http://en.wikipedia.org/wiki/Bonferroni_correction """ n = len(pvals) return [min(x * n , 1.0) for x in pvals]
f57ffd6b77a0a74a61904334604d1cb0eb08f8ff
706,275
def _chao1_var_uncorrected(singles, doubles): """Calculates chao1, uncorrected. From EstimateS manual, equation 5. """ r = singles / doubles return doubles * (.5 * r ** 2 + r ** 3 + .24 * r ** 4)
96c5017fb3bef7dfca3f541dce087fe6a6cabfa2
207,846
def get_week_day(integer): """ Getting weekday given an integer """ if integer == 0: return "Monday" if integer == 1: return "Tuesday" if integer == 2: return "Wednesday" if integer == 3: return "Thursday" if integer == 4: return "Friday" if integer == 5: return "Saturday" if integer == 6: return "Sunday"
5bd0431e8598d56e99f970da738e532630665163
15,180
def attack(p, m1, c1, d1, c2, d2): """ Recovers a secret plaintext encrypted using the same nonce as a previous, known plaintext. :param p: the prime used in the ElGamal scheme :param m1: the known plaintext :param c1: the ciphertext of the known plaintext :param d1: the ciphertext of the known plaintext :param c2: the ciphertext of the secret plaintext :param d2: the ciphertext of the secret plaintext :return: the secret plaintext """ return int(pow(d1, -1, p) * d2 * m1 % p)
a538f9ec358dde85267db2900aeef21b5e91dc1b
541,465
def find_closest(numb, list_of_values, periodic=False): """For a given number, return the closest value(s) from a given list""" all_dist = [] for value in list_of_values: if periodic: all_dist.append(min(abs(numb-value), (360-abs(numb-value)))) else: all_dist.append(abs(numb-value)) m = min(all_dist) closest_ind = [i for i, j in enumerate(all_dist) if j == m] closest = [] for ind in closest_ind: closest.append(list_of_values[ind]) return closest
c9150d33b497a4967c343c224875f7fa7a7d26b1
135,868
def check_not_present(context, raw_data, raw_field): """ Verifies that a specified field is not present in a raw data structure. Args: context (str): The context of the comparison, used for printing error messages. raw_data (dict): Raw data structure we're checking a field from. raw_field (str): Name of the raw field we're verifying is not present. Returns: True if the field was not present, False if it was. """ if raw_field not in raw_data: return True print(f"field value {raw_field} should be absent from {context}, but is not") return False
a8a1d505689c14a55ad26c5d59e146568c62d361
375,399
def parse_line(line): """Parse instruction and return it as tuple of operator and value""" op, val = line.split() val = int(val) return op, val
e4963becf24beb7b998e969f7301d06744dd107e
595,036
def get_union(*args): """Return unioin of multiple input lists. """ return list(set().union(*args))
18025cfd37d64f15daf92aa2ae3e81176cae6e39
5,786
from typing import Counter def filter_min(counter: Counter, min_freq: int): """ Filter counter by min frequency """ return Counter({t: c for t, c in counter.items() if c >= min_freq})
56b77dc486ad41fc7004b1db10f85a4813f835b3
687,572
def by_locale(value_for_us, value_for_international): """ Return a dictionary mapping "us" and "international" to the two values. This is used to create locale-specific values within our UNITS. """ return {"us" : value_for_us, "international" : value_for_international}
94477ffaa40b0ed8d433d2c7a4cc94e0fb3b4f7f
383,109
import keyword def attr_str(attr_name): # type: (str) -> str """Gets the string to use when accessing an attribute on an object. Handles case where the attribute name collides with a keyword and would therefore be illegal to access with dot notation. """ if keyword.iskeyword(attr_name): return 'getattr(obj, "{0}")'.format(attr_name) return 'obj.{0}'.format(attr_name)
fdf6319e022c0db28d000a0c8545df8ada9b80fd
185,693
def numpy_ndarray(pd_ser, nan_to_null=False): """Return numpy.ndarray view of a pandas.Series """ return pd_ser.to_numpy()
4f1e073fc8f92f51da5390fcf0de6d9f2c559e51
174,578
import pathlib from typing import List def _get_all_directories(root: pathlib.Path) -> List[pathlib.Path]: """Walk the directory tree and return all the folders.""" all_files_and_folders = root.glob("**/*") return [path for path in all_files_and_folders if path.is_dir()]
911dc7b14629e6b929f8aa9b96b9ba72406f36ee
591,377
def last_replace(s, old, new, number_of_occurrences): """ Replaces last n occurrences of the old string with the new one within the string provided :param s: string to replace occurrences with :param old: old string :param new: new string :param number_of_occurrences: how many occurrences should be replaced :return: string with last n occurrences replaced """ list_of_components = s.rsplit(old, number_of_occurrences) return new.join(list_of_components)
0cfa60e46694cb28f731c4adb0d912af3bf6bd06
632,609
def remove_padding(im, pad): """ Function for removing padding from an image. :param im: image to remove padding from :param pad: number of pixels of padding to remove :return: """ return im[pad:-pad, pad:-pad]
58d822dc9ab587f63d1a98eb19e17268d75b2ab4
686,436
def print_pauli_list_grouped(pauli_list_grouped): """Print a list of Pauli operators which has been grouped into tensor product basis (tpb) sets. Args: pauli_list_grouped (list of lists of (coeff, pauli) tuples): the list of Pauli operators grouped into tpb sets Returns: None """ for i in range(len(pauli_list_grouped)): print('Post Rotations of TPB set ' + str(i) + ':') print(pauli_list_grouped[i][0][1].to_label()) print(str(pauli_list_grouped[i][0][0]) + '\n') for j in range((len(pauli_list_grouped[i]) - 1)): print(pauli_list_grouped[i][j + 1][1].to_label()) print(pauli_list_grouped[i][j + 1][0]) print('\n') return None
cc58f5a9dce2ee77fdf46d9801f617ca85cf6306
605,617
def _intersects_bounds(a, b): """ Return true if two bounding boxes intersect. """ aminx, aminy, amaxx, amaxy = a bminx, bminy, bmaxx, bmaxy = b if aminx > bmaxx or amaxx < bminx: return False elif aminy > bmaxy or amaxy < bminy: return False return True
e6016e6e90e6df95b9c826928dc58913dbfc9faf
162,924
from datetime import datetime import pytz def localized_date_to_utc(date): """ Return a timezone-unaware UTC time from a timezone-aware localized datetime object. """ if not isinstance(date, datetime): return date return date.astimezone(pytz.utc).replace(tzinfo=None)
63ccd11c27645d56b479b01245703038d58d215e
58,662
def norm_isbn_str(s): """ Given an ISBN string, normalize the string so that it only contains the relevant digits. This function drops all ASCII whitespace characters (tab, space, carriage return, line feed) and all ASCII characters that are not alphanumeric. It also converts all ASCII letters to uppercase. Note that ISBN-10 numbers may have an "X" as their check digit! This function does NOT guarantee that the value it returns is a valid ISBN. Passing a non-string as the parameter is equivalent to passing an empty string. Parameters: s : str | mixed - the ISBN number string to normalize Return: the normalized ISBN string, which is NOT guaranteed to be valid """ # If non-string passed, replace with empty string if not isinstance(s, str): s = '' # Begin with an empty result isbn = '' # Go through each character of the string for cc in s: # Get current character code c = ord(cc) # Handle based on character type if (c >= ord('a')) and (c <= ord('z')): # Lowercase letter, so transfer uppercase to normalized ISBN isbn = isbn + chr(c - 0x20) elif (c >= ord('A')) and (c <= ord('Z')): # Uppercase letter, so transfer to normalized ISBN isbn = isbn + chr(c) elif (c >= ord('0')) and (c <= ord('9')): # Digit, so transfer to normalized ISBN isbn = isbn + chr(c) elif (c >= 0x21) and (c <= 0x7e): # Non-alphanumeric symbol, so don't transfer pass elif (c == ord('\t')) or (c == ord('\r')) or \ (c == ord('\n')) or (c == ord(' ')): # Whitespace, so don't transfer pass else: # Control or extended character, so transfer to normalized isbn = isbn + chr(c) # Return normalized string return isbn
890d010f8361524be44ebaf783d8b6c7d0541b2b
223,269
def simtelTelescopeConfigFileName( site, telescopeModelName, modelVersion, label, extraLabel ): """ sim_telarray config file name for a telescope. Parameters ---------- site: str South or North. telescopeModelName: str LST-1, MST-FlashCam, ... modelVersion: str Version of the model. label: str Instance label. extraLabel: str Extra label in case of multiple telescope config files. Returns ------- str File name. """ name = "CTA-{}-{}-{}".format(site, telescopeModelName, modelVersion) name += "_{}".format(label) if label is not None else "" name += "_{}".format(extraLabel) if extraLabel is not None else "" name += ".cfg" return name
e5ae27857c5615bedeb11ca9698355ba8f03ce70
97,649
import functools import tempfile import pathlib import shutil def with_tempdir(wrapped): """Creates a temporary directory for the function, cleaning up after it returns normally. When the wrapped function raises an exception, the contents of the temporary directory remain available for manual inspection. The wrapped function is called with an extra positional argument containing the pathlib.Path() of the temporary directory. """ @functools.wraps(wrapped) def decorator(*args, **kwargs): dirname = tempfile.mkdtemp(prefix='blender-collada-test') #print("Using tempdir %s" % dirname) try: retval = wrapped(*args, pathlib.Path(dirname), **kwargs) except: print('Exception in %s, not cleaning up temporary directory %s' % (wrapped, dirname)) raise else: shutil.rmtree(dirname) return retval return decorator
9a8f7e745aae4ceb78793b8e14f8a0386bafad3a
436,772
def how_many_bytes(bits: int) -> int: """ how_many_bytes calculates how many bytes are needed to to hold the given number of bits E.g. => how_many_bytes(bits=0) == 0 => how_many_bytes(bits=8) == 1 => how_many_bytes(bits=9) == 2 Args: bits (int): The number of bits Returns: int: The number of bytes """ return (bits + 7) // 8
9308b429659c0f17e8f7d1325109d851eee1f1ed
273,958
import torch def apply_weight_norm(w, input_dims=(1, 2, 3), eps=1e-8): """ Applies the "demodulation" operation from StyleGAN2 as a form of normalization. :param w: Weights :return: Normed weights """ divisor = torch.sqrt((w ** 2).sum(dim=input_dims, keepdim=True) + eps) return w / divisor
5b9bdca5af181b309a37d2f873bb401741fc98d8
182,907
import random import string def gen_dummy_object(class_, doc): """Create a dummy object based on the definitions in the API Doc.""" object_ = { "@type": class_ } if class_ in doc.parsed_classes: for prop in doc.parsed_classes[class_]["class"].supportedProperty: if "vocab:" in prop.prop: prop_class = prop.prop.replace("vocab:", "") object_[prop.title] = gen_dummy_object(prop_class, doc) else: object_[prop.title] = ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(6)) return object_
86e981c7f62ccddda0463145c825d43dc1c3c476
693,072
def vec_leq(vec1, vec2): """ Check that vec1 is less than vec2 elemtwise """ assert isinstance(vec1, list), "Only work with lists" assert isinstance(vec2, list), "Only work with lists" assert len(vec1) == len(vec2), "Vector lengths should be the same" for x, y in zip(vec1, vec2): # if a coordinate is greater, returning false if x > y: return False # returning True if all xs are <= than ys return True
59803934ee083243b20f6c30478a5108e7072f91
560,644
from typing import Counter import math def unigram_task_score(X): """ Given a list of strings, X, calculate the maximum log-likelihood per character for a unigram model over characters (including STOP symbol) """ c = Counter(x for s in X for x in s) c.update("end" for s in X) n = sum(c.values()) logp = {x:math.log(c[x]/n) for x in c} return sum(c[x]*logp[x] for x in c)/n
694396779d73415971e3062afbaa6bb65d1d0cf1
478,862
import time def encode_date (date): """Encodes a datetime in TiddlyWiki format.""" return time.strftime('%Y%m%d%H%M', date)
3e9b0315476e740d2f902666e91d94f8eeeb2ef0
371,535
def confirm(message: str) -> bool: """ Confirms action by requesting right input from user :param message: :return: """ return input(message) == 'Y'
1556e8fc8734442e82751e0578ab7712442f04e3
261,859
def nonlocals(dynamicscope): """Access the nonlocals of a dynamic scope. """ return dynamicscope[0]['nonlocals']
99647f0e23e2fdb8435f54c737c02259c1688b73
549,442
def get_ds_capacity(datastore): """ Get vsphere datastore capacity size :param datastore: vsphere datastore object :return: datastore capacity size """ capacity_size = datastore.summary.capacity return capacity_size
38cbae4aec571449e448002a8dd5b57af8ad71a6
434,984
from typing import Union from typing import Any def type_to_str(type_annotation: Union[type, Any]) -> str: """Gets a string representation of the provided type. :param type_annotation: A type annotation, which is either a built-in type or a typing type. :return: A string representation of the type annotation. """ # Built-in type if type(type_annotation) == type: return type_annotation.__name__ # Typing type return str(type_annotation).replace('typing.', '')
ce2adebf95503aed61a0e7c8877a0cdb9b8d104e
426,567
import re def get_postcode(address_string): """ Takes an address and returns the postcode, or None if no postcode is found. """ address_string = address_string.upper() pc_regex = "([A-PR-UWYZ]([1-9]([0-9]|[A-HJKSTUW])?|[A-HK-Y][1-9]([0-9]|[ABEHMNPRVWXY])?) *[0-9][ABD-HJLNP-UW-Z]{2}|GIR *0AA)" matches = re.search(pc_regex, address_string) if matches: return matches.group(1) else: return None
bad2bf8a03eebea3c034a402c665a7b9cae9df26
218,453
def count_parameters(net): """Counts the parameters of a given PyTorch model.""" return sum([p.numel() for p in list(net.parameters())])
1d1dc1b36d573ae2427cc2ab4f70e4bc7a7b8f00
522,468
def clean_dict(d): """ clean dictionary object to str :param dict: dictionary """ new = {} for k, v in d.items(): if isinstance(v, dict): v = clean_dict(v) new[k] = v else: new[k] = str(v) return new
e9a61a83b5367fc86badcacf58a63e672c0fb941
134,818
def baseline_grid_consistent_with_prevents(baseline_grid, element, at_root=False): """ Checks whether the baseline grid is not prevented by the locks an on element """ if "prevents" in element and "baseline_grid" in element["prevents"]: bg_value = element["prevented_values"]["baseline_grid"] if baseline_grid in bg_value: return False return True
dce2e991d838b94ea58891a87b966e6773b0f81b
166,399
def image_filter(input_stream, image_stream_index, x, y, t_start, t_end, output_stream): """Generate a ffmeg filter specification for an image input. Arguments: input_stream -- name of the input stream image_stream_index -- index of the input image among the -i arguments x, y -- position where to overlay the image on the video t_start, t_end -- start and end time of the image's appearance output_stream -- name of the output stream """ out_str = '' if output_stream is None else ('[' + output_stream + ']') return ('[' + input_stream + '][' + str(image_stream_index) + ':v] ' 'overlay=' + str(x) + ':' + str(y) + ':' 'enable=\'between(t,' + str(t_start) + ',' + str(t_end) + ')\' ' + out_str)
20ddd75b1ab97f43eeb59deb3ec058b844c82e35
266,100
import re def stringify_arg(value): """ Gets rid of the CDATA xml part of the string. :param value: a possibly unicode element :return: unicode value without the CDATA information """ patt = re.compile(r"<!\[CDATA\[(.+)\]\]") if value is None: value = "null" m = patt.search(value) if not m: arg = value.strip() else: arg = m.groups()[0].strip() text = arg.encode('utf-8', 'ignore') return text
bf8ff8b3e0b0b24b8fabcbac1fb51d74ceffcfed
425,258
def identity(x): """Identity activation Layer A placeholder identity operator that is argument-insensitive. Args: x (np.ndarray): input tensor. Returns: (np.ndarray): output tensor and have same shape with x. Examples: >>> identity(np.array([-3.0, -1.0, 0.0, 2.0])) tensor([-3.0, -1.0, 0.0, 2.0]) """ return x
e3486b83b083348f2d252fee49fef7cace0a54dc
217,712
def sign(x): """Returns sign of x""" if x==0: return 0 return x/abs(x)
677dfd796b0ee354fbcaf78b58cf7a5a660446b5
705,300
from typing import Any def verify_assign_and_read(obj: Any, attr: str, value: Any) -> Any: """ Assign value to attribute, read and return result. Assert that values can be mutated and read before and after mutation. """ try: setattr(obj, attr, value) except AttributeError: raise AssertionError(f"error mutating obj.{attr}") try: return getattr(obj, attr) except AttributeError: raise AssertionError(f"obj.{attr} does not exist even after assignment")
b7ae561c3cee9d9f379a6c0883a6f3bdb5861768
669,900
def indent(value, n=2, character=' '): """ Indent a value by `n` `character`s :param value: string to indent :param n: number of characters to indent by :param character: character to indent with """ prefix = n * character return '\n'.join(prefix + line for line in value.splitlines())
895559983bf02c90c030d33d1f95ba4ac3814394
223,923
def convertToCamelCase(input, firstIsLowercase=False): """Given an input string of words (separated by space), converts it back to camel case. 'Foo Bar' (firstIsLowercase=False) --> 'FooBar' 'Foo Bar' (firstIsLowercase=True) --> 'fooBar' 'foo bar' (firstIsLowercase=False) --> 'FooBar' Args: input (str): The string of words to convert firstIsLowercase (bool, optional): By default, title cases all words in the input string (i.e. 'foo bar' will become 'FooBar' rather than 'fooBar'). If True, the first word is forced to become lowercase Returns: str: The camelcased string """ words = input.split() for i, word in enumerate(words): if i == 0 and firstIsLowercase: words[0] = words[0].lower() else: words[i] = words[i].title() return ''.join(words)
a27a0ff9163917973e3ad21e4c892080fcccac14
212,273
def dashcount(entry): """ Counts the number of dashes at the beginning of a string. This is needed to determine the depth of options in categories. Args: entry (str): String to count the dashes at the start of Returns: dashes (int): Number of dashes at the start """ dashes = 0 for char in entry: if char == "-": dashes += 1 else: return dashes return dashes
9a096f6da8e44cb8f8daf310f454543b322df654
475,789
def user_dir_path(instance, filename): """ files will be uploaded to MEDIA_ROOT/user_<id>/filename """ return 'user_{0}/reports/{1}'.format(instance.visit_id.user_id, filename)
c286dada6d995ed4d38b49a3e46890e7d08898be
168,614
def round_exp(x,n): """Round floating point number to *n* decimal digits in the mantissa""" return float(("%."+str(n)+"g") % x)
d101d0839f4e12e511d222a3758adfadb7165184
146,819
def premium(q,par): """ Returns the (minimum) premium that an insurance company would take Args: q (float): coverage par (namespace): parameter values Returns: (float): premium """ return par.p*q
2166bc6e16577a26d3adc17afe5929bf8fca073b
33,739
def get_user_groups(db, user_id=None): """Retrieves the existing user groups, if member_is is provided returns only the groups associated to the user_id Args: db (object): The db object user_id (int): User ID Returns: The user groups """ sql = '''SELECT id, name, description FROM user_group ug ''' if user_id is not None: sql += '''JOIN user_group_has_user ughu ON ughu.user_group_id = ug.id WHERE ughu.user_id=?''' args = (user_id,) if user_id is not None else None return db.select(sql, args)
469f3793efdfebc88f989a2ed5961eb2ed4398d6
496,111
import re def trim_ansi_tags(data_str): """ Trim all ANSI tags :param data_str: input data string to trim :return: Trimmed string >>> trim_ansi_tags('') '' >>> trim_ansi_tags(u'') '' >>> trim_ansi_tags(u'hello world') 'hello world' >>> trim_ansi_tags('hello world') 'hello world' >>> trim_ansi_tags(u'hello world'.encode('utf-8')) 'hello world' >>> trim_ansi_tags('2019/02/11 09:34:37 GMT: \x1B[32mSTATE: Started\x1B[0m') '2019/02/11 09:34:37 GMT: STATE: Started' >>> trim_ansi_tags('2019/02/11 09:34:37 GMT: \x1B[32mSTATE: Started\x1B[0m'.encode('utf-8')) '2019/02/11 09:34:37 GMT: STATE: Started' >>> trim_ansi_tags(b'2019/02/11 09:34:37 GMT: \x1B[33mBlue/green swap aborted for [ghost-testing/test/webfront] : Blue/green is not enabled on this app or not well configured\x1B[0m') '2019/02/11 09:34:37 GMT: Blue/green swap aborted for [ghost-testing/test/webfront] : Blue/green is not enabled on this app or not well configured' """ # Remove ANSI escape sequences # https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python try: data_str = data_str.decode('utf-8') except AttributeError: pass return re.sub(r'\x1B\[[0-?]*[ -/]*[@-~]', '', data_str)
a78493aba53230494b24a9b27afc76dcc8616639
340,059
def ispalindrome(n): """ checks whether the integer n is a palindrome """ s = str(n) return s == s[::-1]
47b1cadb203fddd0509357135c71b94b989b982c
117,562
def hex_to_long(hex_string: str): """Convert hex to long.""" return int(hex_string, 16)
c9a88a1c6d30afe8b8aab6c0c303e8e467fe6b26
431,518
def notas(* n, sit=False): """ -> Função para analisar notas e situação de vários alunos :param n: um ou mais notas dos alunos (aceita várias) :param sit: (opcional) indica se deve ou não adicionar a situação :return: dicionário com várias informações sobre o desempenho da turma """ desempenho = {} total = len(n) maior = max(n) menor = min(n) media = sum(n) / len(n) if media >= 7: situacao = 'BOM' elif 6 < media < 7: situacao = 'RAZOÁVEL' else: situacao = 'RUIM' desempenho['total'] = total desempenho['maior'] = maior desempenho['menor'] = menor desempenho['media'] = media if sit: desempenho['situacao'] = situacao return desempenho
56d43d412417964dce9f7eb59a6f00a9ec0b267c
506,707
import math def electrode_distance(latlong_a, latlong_b, radius=100.0): """ geodesic (great-circle) distance between two electrodes, A and B :param latlong_a: spherical coordinates of electrode A :param latlong_b: spherical coordinates of electrode B :return: distance """ lat1, lon1 = latlong_a lat2, lon2 = latlong_b dLat = math.radians(lat2 - lat1) dLon = math.radians(lon2 - lon1) a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.cos( math.radians(lat1) ) * math.cos(math.radians(lat2)) * math.sin(dLon / 2) * math.sin(dLon / 2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) d = radius * c return d
99ae372ff17678c545ce48dac085b865f8fe3b88
172,443
import json def write_json(file_path, json_obj): """Write JSON string. # Arguments file_path: `str`<br/> the absolute path to the JSON string. json_obj: `dict`<br/> a dictionary # Returns flag : bool True if saved successfully False otherwise """ try: with open(file_path, "w") as f: json.dump(json_obj, f) f.close() return True except IOError: return False
3f212d2271e3b29e68d64510974b4ad1c50f7a99
663,456
def cat_lists(*list_args): """ Given any number of lists, concatinate onto a new list """ result = [] for List in list_args: result.extend(List) return result
3dd43be591e8112dbe3906d89b065e7a177208c8
301,298
import time def ms_time_to_srt_time_format(d: int) -> str: """Convert decimal durations into proper srt format. ms_time_to_srt_time_format(3890) -> '00:00:03,890' """ sec, ms = d // 1000, d % 1000 time_fmt = time.strftime("%H:%M:%S", time.gmtime(sec)) # if ms < 100 we get ...,00 or ...,0 when expected ...,000 ms = "0" * (3 - len(str(ms))) + str(ms) return f"{time_fmt},{ms}"
3ca2713615b7fb8ef1ea9e9712e0b26b23c5f7e1
35,616
def min_max_norm(x): """ Performs min-max normalization --> scales values in range between 1 and 0 :param x (1-D array like) :return: (1-D np.array) min-max normalized input """ mini = min(x) maxi = max(x) return (x - mini) / (maxi - mini)
72b19fb7e5bf47fcf78d51676a9b89c3694bee44
623,166
def _reformat_spectrometer_df(spectrometer_df_with_clean_header): """ Reformats a df of spectrometer data with many wavelength columns to a more useful format with 2 columns Args: spectrometer_df_with_clean_header: a pandas df of spectrometer data, cleaned up with _clean_up_spectrometer_df_header() Return: A pandas df, indexed by timestamp, with 2 columns: wavelength and intensity """ n_timestamp_columns = 1 wavelength_columns = spectrometer_df_with_clean_header.columns[n_timestamp_columns:] # Melt function is a pivot and turns 3648 columns, each one wavelength, into one column reformatted_spectrometer_df = spectrometer_df_with_clean_header.melt( id_vars=["timestamp"], value_vars=wavelength_columns, var_name="wavelength", value_name="intensity", ) reformatted_spectrometer_df["wavelength"] = reformatted_spectrometer_df[ "wavelength" ].astype(float) return reformatted_spectrometer_df.set_index(["timestamp"])
f926ee35bcbaa282bf1d116e9b3282d491d0de52
251,405
def decimal(anon, obj, field, val): """ Returns a random decimal """ return anon.faker.decimal(field=field)
9ca0d3fab6c5f1862ce01bb3008ab82eccdfd865
458,727