content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def mlist(self, node1="", node2="", ninc="", **kwargs): """Lists the MDOF of freedom. APDL Command: MLIST Parameters ---------- node1, node2, ninc List master degrees of freedom from NODE1 to NODE2 (defaults toNODE1) in steps of NINC (defaults to 1). If NODE1 = ALL (default), NODE2 and NINC are ignored and masters for all selected nodes [NSEL] are listed. If NODE1 = P, graphical picking is enabled and all remaining command fields are ignored (valid only in the GUI). A component name may also be substituted for NODE1 (NODE2 and NINC are ignored). Notes ----- Lists the master degrees of freedom. """ command = f"MLIST,{node1},{node2},{ninc}" return self.run(command, **kwargs)
611cd462d34cd4de0e34cb262549fc6cff40127d
11,292
def formatstr(text): """Extract all letters from a string and make them uppercase""" return "".join([t.upper() for t in text if t.isalpha()])
749aeec962e3e39760c028bfb3e3a27ad8c10188
11,294
def form2_list_comprehension(items): """ Remove duplicates using list comprehension. :return: list with unique items. """ return [i for n, i in enumerate(items) if i not in items[n + 1:]]
02d095c86de1b7d52d53cdb4bfe77db08523ea3a
11,296
def calcMass(volume, density): """ Calculates the mass of a given volume from its density Args: volume (float): in m^3 density (float): in kg/m^3 Returns: :class:`float` mass in kg """ mass = volume * density return mass
38f0ef780704c634e572c092eab5b92347edccd3
11,297
def rescale(arr, vmin, vmax): """ Rescale uniform values Rescale the sampled values between 0 and 1 towards the real boundaries of the parameter. Parameters ----------- arr : array array of the sampled values vmin : float minimal value to rescale to vmax : float maximum value to rescale to """ arrout = (vmax - vmin)*arr + vmin return arrout
d6debc0eeccd9fe19ed72d869d0de270559c9ce8
11,298
import socket def check_port_occupied(port, address="127.0.0.1"): """ Check if a port is occupied by attempting to bind the socket :return: socket.error if the port is in use, otherwise False """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((address, port)) except socket.error as e: return e finally: s.close() return False
5919e228c835ceb96e62507b9891c6a1ce5948fa
11,301
import csv def write_rows(rows, filename, sep="\t"): """Given a list of lists, write to a tab separated file""" with open(filename, "w", newline="") as csvfile: writer = csv.writer( csvfile, delimiter=sep, quotechar="|", quoting=csv.QUOTE_MINIMAL ) for row in rows: writer.writerow(row) return filename
41e04ee6203baf7db2d08722aed76dfacbc9e838
11,309
def HKL2string(hkl): """ convert hkl into string [-10.0,-0.0,5.0] -> '-10,0,5' """ res = "" for elem in hkl: ind = int(elem) strind = str(ind) if strind == "-0": # removing sign before 0 strind = "0" res += strind + "," return res[:-1]
325ddfcb2243ce9a30328c5b21626a4c93a219de
11,313
from typing import List def should_expand_range(numbers: List[int], street_is_even_odd: bool) -> bool: """Decides if an x-y range should be expanded.""" if len(numbers) != 2: return False if numbers[1] < numbers[0]: # E.g. 42-1, -1 is just a suffix to be ignored. numbers[1] = 0 return True # If there is a parity mismatch, ignore. if street_is_even_odd and numbers[0] % 2 != numbers[1] % 2: return False # Assume that 0 is just noise. if numbers[0] == 0: return False # Ranges larger than this are typically just noise in the input data. if numbers[1] > 1000 or numbers[1] - numbers[0] > 24: return False return True
fcd5a8e027120ef5cc52d23f67de4ab149b19a2c
11,316
def zyx_to_yxz_dimension_only(data, z=0, y=0, x=0): """ Creates a tuple containing the shape of a conversion if it were to happen. :param data: :param z: :param y: :param x: :return: """ z = data[0] if z == 0 else z y = data[1] if y == 0 else y x = data[2] if x == 0 else x return (y, x, z)
2477976f795f5650e45214c24aaf73e40d9fa4eb
11,317
def gen_anonymous_varname(column_number: int) -> str: """Generate a Stata varname based on the column number. Stata columns are 1-indexed. """ return f'v{column_number}'
f0e150300f7d767112d2d9e9a1b139f3e0e07878
11,318
def create_city_map(n: int) -> set: """ Generate city map with coordinates :param n: defines the size of the city that Bassi needs to hide in, in other words the side length of the square grid :return: """ return set((row, col) for row in range(0, n) for col in range(0, n))
fd30b936647bae64ccf2894ffbb68d9ad7ec9c6b
11,320
def nullable(datatype): """Return the signature of a scalar value that is allowed to be NULL (in SQL parlance). Parameters ---------- datatype : ibis.expr.datatypes.DataType Returns ------- Tuple[Type] """ return (type(None),) if datatype.nullable else ()
fe5935d1b4b1df736933455e97da29a901d6acb1
11,322
from typing import Dict def make_country_dict( csv_file:str = 'data/country_list.csv') -> Dict[str, str]: """Make a dictionary containing the ISO 3166 two-letter code as the key and the country name as the value. The data is read from a csv file. """ country_dict = {} with open(csv_file, encoding='utf-8') as country_csv: for line in country_csv: key, value = line.strip().split(',') country_dict[key] = value return country_dict
0334a2b2c918f407d1df682f56c14943f1e66c43
11,325
from typing import List def get_reputation_data_statuses(reputation_data: List) -> List[str]: """ collects reported statuses of reputation data Args: reputation_data: returned data list of a certain reputation command Returns: a list of reported statuses """ reputation_statuses = [status for data_entry in reputation_data if (status := data_entry.get('status'))] return reputation_statuses
2c41344f2970243af83521aecb8a9374f74a40ac
11,328
def is_number(val): """Check if a value is a number by attempting to cast to ``float``. Args: val: Value to check. Returns: True if the value was successfully cast to ``float``; False otherwise. """ try: float(val) return True except (ValueError, TypeError): return False
89728d3d199c3ef5885529da5a2d13dd94fa590f
11,329
def format_rfc3339(datetime_instance): """Formats a datetime per RFC 3339.""" return datetime_instance.isoformat("T") + "Z"
ad60a9e306e82554601efc1ae317296a59b009b0
11,331
def get_metadata_keys(options): """ Return a list of metadata keys to be extracted. """ keyfile = options.get("keyfile") if (keyfile): with open(keyfile, "r") as mdkeys_file: return mdkeys_file.read().splitlines() else: return None
2451d54ae49690691e5b0ce019178fd119e3d269
11,332
def _remove_self(d): """Return a copy of d without the 'self' entry.""" d = d.copy() del d['self'] return d
a80eca3886d0499d1871998501c19e9cdae93673
11,338
def deltanpq(phino, phinoopt=0.2): """Calculate deltaNPQ deltaNPQ = (1/phinoopt) - (1/phino) :param phino: PhiNO :param phinoopt: Optimum PhiNO (default: 0.2) :returns: deltaNPQ (float) """ return (1/phinoopt) - (1/phino)
34d44a732bd87eb78e8ddee92b4555bea67789be
11,339
def opt_in_argv_tail(argv_tail, concise, mnemonic): """Say if an optional argument is plainly present""" # Give me a concise "-" dash opt, or a "--" double-dash opt, or both assert concise or mnemonic if concise: assert concise.startswith("-") and not concise.startswith("--") if mnemonic: assert mnemonic.startswith("--") and not mnemonic.startswith("---") # Detect the plain use of the concise or mnemonic opts # Drop the ambiguities silently, like see "-xh" always as "-x '-h'" never as "-x -h" for arg in argv_tail: if mnemonic.startswith(arg) and (arg > "--"): return True if arg.startswith(concise) and not arg.startswith("--"): return True return False
17333a2a526799d6db5e78746d3ecb7111cd8cd6
11,343
def split_by_unicode_char(input_strs): """ Split utf-8 strings to unicode characters """ out = [] for s in input_strs: out.append([c for c in s]) return out
290bb5ec82c78e9ec23ee1269fe9227c5198405e
11,347
def get_lr(optimizer): """get learning rate from optimizer Args: optimizer (torch.optim.Optimizer): the optimizer Returns: float: the learning rate """ for param_group in optimizer.param_groups: return param_group['lr']
fc8293cc29c2aff01ca98e568515b6943e93ea50
11,358
def find_changes(vals, threshold=None, change_pct=0.02, max_interval=None): """Returns an array of index values that point at the values in the 'vals' array that represent signficant changes. 'threshold' is the absolute amount that a value must change before being included. If 'threshold' is None, 'change_pct' is used to determine a threshold change by multiplying 'change_pct' by the difference between the minimum and maximum value. If 'max_interval' is provided, it will be the maximum allowed separation between returned index values. This forces some some points to be returned even if no signficant change has occurred. Index 0, pointing at the first value is always returned. """ # special case of no values passed if len(vals) == 0: return [] if threshold is None: # compute the threshold difference that constitutes a change # from the change_pct parameter threshold = (max(vals) - min(vals)) * change_pct if threshold == 0.0: threshold = 0.01 # keep it from showing every point # Start with the first value final_ixs = [0] last_val = vals[0] last_ix = 0 for ix in range(1, len(vals)): v = vals[ix] include_this_index = False if abs(v - last_val) >= threshold: # if the prior value was not included, include it if last_ix != ix - 1: final_ixs.append(ix - 1) include_this_index = True elif max_interval is not None and ix - last_ix >= max_interval: include_this_index = True if include_this_index: final_ixs.append(ix) last_val = v last_ix = ix return final_ixs
e6c66d3636f80ee310dcb7ae790bb30a27598aaa
11,366
def data_value(value: str) -> float: """Convert to a float; some trigger values are strings, rather than numbers (ex. indicating the letter); convert these to 1.0.""" if value: try: return float(value) except ValueError: return 1.0 else: # empty string return 0.0
24087c1733be5932428a63811abbb54686836036
11,370
from typing import Tuple import logging async def mark_next_person(queue_array: list) -> Tuple[list, int]: """Mark next person in the queue (transfers current_turn to them). Parameters ---------- queue_array : list This array represents the queue Returns ------- Tuple[list, int] The modified queue_array & the id of the person marked """ for index, member in enumerate(queue_array): if member["current_turn"]: queue_array[index]["current_turn"] = False # shouldnt fail when next person is at the beginning of the # queue next_person_pos = (index + 1) % len(queue_array) queue_array[next_person_pos]["current_turn"] = True return (queue_array, queue_array[next_person_pos]["user_id"]) logging.error("Failed to find next person in the queue") return ([], 0)
e792dbf2ac10f44bda53a6429ba43180bdefd144
11,371
from typing import Dict from typing import Any def map_key(dictionary: Dict, search: Any) -> Any: """Find and return they key for given search value.""" for key, value in dictionary.items(): if value == search: return key return None
c9e200bb352b68c7468ae0511f11f7eff5e46b52
11,379
def get_requirements(filename): """ Get requirements file content by filename. :param filename: Name of requirements file. :return: Content of requirements file. """ return open("requirements/" + filename).read().splitlines()
3dab39352bb69798e076a9d97077902580f50640
11,380
def is_operator(token): """Checks if token is an operator '-+/*'.""" return token in '-+/*'
24b57d2a299df263c900cc94e2e18a9fc7d026b1
11,382
def add_date_end(record: dict): """ Function to make ``date_end`` ``date_start`` if ``measure_stage`` is "Lift" Parameters ---------- record : dict Input record. Returns ------- type Record with date_end changed conditionally, or original record. """ if record['measure_stage'] == 'Lift': record['date_end'] = record['date_start'] return(record)
67f6ae063aabdf7a7d456ed0ce9660a75b37b6c2
11,385
def multy(b: int) -> int: """2**b via naive recursion. >>> multy(17)-1 131071 """ if b == 0: return 1 return 2*multy(b-1)
272cd138de2209093c0a32e1c7b2f1c08d0dc2be
11,386
def get_ens(sets): """ Puts all entities appeared in interpretation sets in one set. :param sets: [{en1, en2, ...}, {en3, ..}, ...] :return: set {en1, en2, en3, ...} """ ens = set() for en_set in sets: for en in en_set: ens.add(en) return ens
7f5b59d6f5786ee9506bda72a4ee3f8cdf787c33
11,387
def is_in_group(user, group_name): """ Check if a user in a group named ``group_name``. :param user User: The auth.User object :param group_name str: The name of the group :returns: bool """ return user.groups.filter(name__exact=group_name).exists()
25e51e483b0c18c03f8e897725f07e9e63cc160a
11,389
def strip_email(s: str) -> str: """ Filter which extracts the first part of an email to make an shorthand for user. :param s: Input email (or any string). :type s: str :return: A shorthand extracted. :rtype: str """ return s.split('@', 1)[0]
36ea94b9eb12e0e64b78965c66233578790e6a13
11,395
def name_item_info(mosaic_info, item_info): """ Generate the name for a mosaic metadata file in Azure Blob Storage. This follows the pattern `metadata/quad/{mosaic-id}/{item-id}.json`. """ return f"metadata/quad/{mosaic_info['id']}/{item_info['id']}.json"
db78eb175f6530ace2037ed89cb090591c82147f
11,396
def ptfhost(testbed_devices): """ Shortcut fixture for getting PTF host """ return testbed_devices["ptf"]
25fdbc9520c4cda9719887ff213ccb2b88918dcc
11,397
from datetime import datetime def add_current_time_to_state(state): """Annotate state with the latest server time""" state['currentTime'] = datetime.now().timestamp() return state
f61fa2d7b127fbebb22fc277e16f2f79cdd4acd3
11,398
import re def normalize_rgb_colors_to_hex(css): """Convert `rgb(51,102,153)` to `#336699`.""" regex = re.compile(r"rgb\s*\(\s*([0-9,\s]+)\s*\)") match = regex.search(css) while match: colors = map(lambda s: s.strip(), match.group(1).split(",")) hexcolor = '#%.2x%.2x%.2x' % tuple(map(int, colors)) css = css.replace(match.group(), hexcolor) match = regex.search(css) return css
e3650f525d1d9c1e7bbf7d5b4161712a7439b529
11,401
def shape_to_spacing(region, shape, pixel_register=False): """ Calculate the spacing of a grid given region and shape. Parameters ---------- region : list = [W, E, S, N] The boundaries of a given region in Cartesian or geographic coordinates. shape : tuple = (n_north, n_east) or None The number of points in the South-North and West-East directions, respectively. pixel_register : bool If True, the coordinates will refer to the center of each grid pixel instead of the grid lines. In practice, this means that there will be one less element per dimension of the grid when compared to grid line registered (only if given *spacing* and not *shape*). Default is False. Returns ------- spacing : tuple = (s_north, s_east) The grid spacing in the South-North and West-East directions, respectively. Examples -------- >>> spacing = shape_to_spacing([0, 10, -5, 1], (7, 11)) >>> print("{:.1f}, {:.1f}".format(*spacing)) 1.0, 1.0 >>> spacing = shape_to_spacing([0, 10, -5, 1], (14, 11)) >>> print("{:.1f}, {:.1f}".format(*spacing)) 0.5, 1.0 >>> spacing = shape_to_spacing([0, 10, -5, 1], (7, 21)) >>> print("{:.1f}, {:.1f}".format(*spacing)) 1.0, 0.5 >>> spacing = shape_to_spacing( ... [-0.5, 10.5, -5.5, 1.5], (7, 11), pixel_register=True, ... ) >>> print("{:.1f}, {:.1f}".format(*spacing)) 1.0, 1.0 >>> spacing = shape_to_spacing( ... [-0.25, 10.25, -5.5, 1.5], (7, 21), pixel_register=True, ... ) >>> print("{:.1f}, {:.1f}".format(*spacing)) 1.0, 0.5 """ spacing = [] for i, n_points in enumerate(reversed(shape)): if not pixel_register: n_points -= 1 spacing.append((region[2 * i + 1] - region[2 * i]) / n_points) return tuple(reversed(spacing))
bc943f55330c17295bdb078d732c6ebc9f8cecfe
11,410
import math def choose_grid_size(train_inputs, ratio=1.0, kronecker_structure=True): """ Given some training inputs, determine a good grid size for KISS-GP. :param x: the input data :type x: torch.Tensor (... x n x d) :param ratio: Amount of grid points per data point (default: 1.) :type ratio: float, optional :param kronecker_structure: Whether or not the model will use Kronecker structure in the grid (set to True unless there is an additive or product decomposition in the prior) :type kronecker_structure: bool, optional :return: Grid size :rtype: int """ # Scale features so they fit inside grid bounds num_data = train_inputs.numel() if train_inputs.dim() == 1 else train_inputs.size(-2) num_dim = 1 if train_inputs.dim() == 1 else train_inputs.size(-1) if kronecker_structure: return int(ratio * math.pow(num_data, 1.0 / num_dim)) else: return ratio * num_data
1d3e30a6b7b419a1e2fcdc245830aa00d1ba493d
11,411
def parameter_tuple_parser(parameter_tuple, code_list, relative_base): """ Accepts parameter_tuple, code_list, and relative_base. Returns parameter for use in intcode operation. """ if parameter_tuple[0] == 0: return code_list[parameter_tuple[1]] elif parameter_tuple[0] == 1: return parameter_tuple[1] elif parameter_tuple[0] == 2: return code_list[parameter_tuple[1] + relative_base] else: print('And I oop.... parameter_tuple_parser')
f869240666f2adca0551a3620644023b88930a5a
11,417
def _compute_padding_to_prevent_task_description_from_moving(unfinished_tasks): """Compute the padding to have task descriptions with the same length. Some task names are longer than others. The tqdm progress bar would be constantly adjusting if more space is available. Instead, we compute the length of the longest task name and add whitespace to the right. Example ------- >>> unfinished_tasks = ["short_name", "long_task_name"] >>> _compute_padding_to_prevent_task_description_from_moving(unfinished_tasks) 14 """ len_task_names = list(map(len, unfinished_tasks)) padding = max(len_task_names) if len_task_names else 0 return padding
82a2fffa0a35036901affe11fdf98d875445ffea
11,420
import math def float_in_range(value: float, lower: float, upper: float) -> bool: """Checks if a float is within a range. In addition to checking if lower < value < upper, checks if value is close to the end points; if so, returns True. This is to account for the vageries of floating point precision. args: value: The value to check. lower: The lower bound of the range. upper: The upper bound of the range. return: _: The value is in the range. """ return ( (lower <= value <= upper) or math.isclose(value, lower) or math.isclose(value, upper) )
e971c082e8019f545c9ccc1024f37d3bab61b64e
11,421
def flat_list(source): """Make sure `source` is a list, else wrap it, and return a flat list. :param source: source list :returns: flat list """ if not isinstance(source, (list, tuple)): source = [source] r = [] list(map(lambda x: r.extend(x) if isinstance(x, (list, tuple)) else r.append(x), source)) return r
d118388794cdef72200ad43ab88d9f964b633851
11,426
def git_ref_from_eups_version(version: str) -> str: """Given a version string from the EUPS tag file, find something that looks like a Git ref. """ return version.split("+")[0]
c6a429878c2150ce58b262e9f1fb187226336b0b
11,427
def collapse(iter_flow_result:dict)->list: """ Return iter_flow dict result as a single flat list""" nested_lists = [iter_flow_result[k] for k in iter_flow_result.keys()] flat_list = [item for sublist in nested_lists for item in sublist] return(flat_list)
ada0d654ed36df8168b4835fbde3b91b7f56fb72
11,431
from typing import Union from pathlib import Path def relative_to( path: Union[str, Path], source: Union[str, Path], include_source: bool = True ) -> Union[str, Path]: """Make a path relative to another path. In contrast to :meth:`pathlib.Path.relative_to`, this function allows to keep the name of the source path. Examples -------- The default behavior of :mod:`pathlib` is to exclude the source path from the relative path. >>> relative_to("folder/file.py", "folder", False).as_posix() 'file.py' To provide relative locations to users, it is sometimes more helpful to provide the source as an orientation. >>> relative_to("folder/file.py", "folder").as_posix() 'folder/file.py' """ source_name = Path(source).name if include_source else "" return Path(source_name, Path(path).relative_to(source))
26caa33770617361406915c9b301b5fe1a0ba9ef
11,437
def get_creds(filename): """ Read credentials from a file. Format is: URL USERNAME PASSWORD Parameters ---------- filename: string path to the file with the credentials Returns ------- list as [URL, USERNAME, PASSWORD] """ f = open(filename, "r") lines = f.readlines() if len(lines) != 3: raise ValueError("Not a valid credentials file.") # strip out newline chars content = [x.rstrip() for x in lines] return content
7b308a2e140a809e0bb11804750370bb4326796d
11,441
def uri_base(uri): """ Get the base URI from the supplied URI by removing any parameters and/or fragments. """ base_uri = uri.split("#", 1)[0] base_uri = base_uri.split("?", 1)[0] return base_uri
8655b8717261dcd419f1c3ac0153ec51d348ca57
11,443
def sequalsci(val, compareto) -> bool: """Takes two strings, lowercases them, and returns True if they are equal, False otherwise.""" if isinstance(val, str) and isinstance(compareto, str): return val.lower() == compareto.lower() else: return False
5e96233ead44608ce70ad95e936c707af8bcb130
11,444
def n_rots(request): """Number of rotations in random layer.""" return request.param
93d55281a83be9e4acba951d1de8a9e7d5081182
11,445
from typing import Any def try_to_cuda(t: Any) -> Any: """ Try to move the input variable `t` to a cuda device. Args: t: Input. Returns: t_cuda: `t` moved to a cuda device, if supported. """ try: t = t.cuda() except AttributeError: pass return t
9b6643f169c1eb8fc65de8b1bff55668f8cba950
11,446
def group(seq, groupSize, noneFill=True): """Groups a given sequence into sublists of length groupSize.""" ret = [] L = [] i = groupSize for elt in seq: if i > 0: L.append(elt) else: ret.append(L) i = groupSize L = [] L.append(elt) i -= 1 if L: if noneFill: while len(L) < groupSize: L.append(None) ret.append(L) return ret
a7314803cb3b26c9bd69a2dbc2c0594181085c2c
11,451
def not_safe_gerone(a, b, c): """ Compute triangle area from valid sides lengths :param float a: first side length :param float b: second side length :param float c: third side length :return: float -- triangle area >>> not_safe_gerone(3, 4, 5) 6.0 """ p = (a+b+c)/2 return (p*(p-a)*(p-b)*(p-c))**(1/2)
499cf398158d170363ea22096b44ea16e402a23a
11,465
def sqs_lookup_url(session, queue_name): """Lookup up SQS url given a name. Args: session (Session) : Boto3 session used to lookup information in AWS. queue_name (string) : Name of the queue to lookup. Returns: (string) : URL for the queue. Raises: (boto3.ClientError): If queue not found. """ client = session.client('sqs') resp = client.get_queue_url(QueueName=queue_name) return resp['QueueUrl']
4f7bfb98d10a372b3b07f270e2a25e3227732f41
11,474
def get_government_factions(electoral_term): """Get the government factions for the given electoral_term""" government_electoral_term = { 1: ["CDU/CSU", "FDP", "DP"], 2: ["CDU/CSU", "FDP", "DP"], 3: ["CDU/CSU", "DP"], 4: ["CDU/CSU", "FDP"], 5: ["CDU/CSU", "SPD"], 6: ["SPD", "FDP"], 7: ["SPD", "FDP"], 8: ["SPD", "FDP"], 9: ["SPD", "FDP"], 10: ["CDU/CSU", "FDP"], 11: ["CDU/CSU", "FDP"], 12: ["CDU/CSU", "FDP"], 13: ["CDU/CSU", "FDP"], 14: ["SPD", "BÜNDNIS 90/DIE GRÜNEN"], 15: ["SPD", "BÜNDNIS 90/DIE GRÜNEN"], 16: ["CDU/CSU", "SPD"], 17: ["CDU/CSU", "FDP"], 18: ["CDU/CSU", "SPD"], 19: ["CDU/CSU", "SPD"], } return government_electoral_term[electoral_term]
cfd502f81ebb0536432da4974ab9f25724dc83df
11,475
def VectorVector_scalar(vectorA, vectorB): """ N diemnsional. Return a float as a scalar resulting from vectorA * vectorB""" result = 0 for i in range(0, len(vectorA)): result += vectorA[i] * vectorB[i] return result
c7f0448a05573b8ddba63ed7a8262072ffcda38f
11,476
def eval_shift_distance(shift, reg_matches): """ Compute the distance in characters a match has been shifted over. "reg_matches" is the set of regular matches as returned by find_regular_matches(). The distance is defined as the number of characters between the shifted match and the closest regular match. """ mid_matches = sorted(m for m in reg_matches if (m[0] < shift[0] and m[1] > shift[1]) or (m[0] > shift[0] and m[1] < shift[1])) return (-(shift[0] - mid_matches[0][0]) if mid_matches[0][0] < shift[0] else (mid_matches[-1][0] + len(mid_matches[-1][2]) - (shift[0] + len(shift[2]))))
aceb705d0f89cacb6f7738667e6dfaf803bed85c
11,478
def get_common_basename(paths): """ Return common "basename" (or "suffix"; is the last component of path) in list "paths". Or return None if all elements in paths do not share a common last component. Generate an error if any path ends with a slash.""" if len(paths) == 0: return None # get suffix of first element: first_path = paths[0] first_suffix = first_path.rsplit('/', 1)[-1] assert first_suffix !='', "Invalid path, has trailing slash: %s" % first_path match = True for path in paths: prefix, suffix = path.rsplit('/', 1) assert suffix !='', "Invalid path, has trailing slash: %s" % path if suffix != first_suffix: match = False break if not match: # suffixes do not match return None # suffixes match return first_suffix
e2189244ef556038caea24ba6aa85792f34868db
11,479
def contains_all_required_firewalls(firewall, topology): """ Check that the list of firewall settings contains all necessary firewall settings """ for src, row in enumerate(topology): for dest, col in enumerate(row): if src == dest: continue if col == 1 and (str((src, dest)) not in firewall or str((dest, src)) not in firewall): return False return True
a4dbbb5833909e816c5b7568cf75da68c06d9e4c
11,487
def _get_upload_headers(first_byte, file_size, chunk_size): """Prepare the string for the POST request's headers.""" content_range = 'bytes ' + \ str(first_byte) + \ '-' + \ str(first_byte + chunk_size - 1) + \ '/' + \ str(file_size) return {'Content-Range': content_range}
3ccfec747ce8f8f31b97489005b1ac421f7c9024
11,490
def format_uptime(uptime_in_seconds): """Format number of seconds into human-readable string. :param uptime_in_seconds: The server uptime in seconds. :returns: A human-readable string representing the uptime. >>> uptime = format_uptime('56892') >>> print(uptime) 15 hours 48 min 12 sec """ m, s = divmod(int(uptime_in_seconds), 60) h, m = divmod(m, 60) d, h = divmod(h, 24) uptime_values = [] for value, unit in ((d, 'days'), (h, 'hours'), (m, 'min'), (s, 'sec')): if value == 0 and not uptime_values: # Don't include a value/unit if the unit isn't applicable to # the uptime. E.g. don't do 0 days 0 hours 1 min 30 sec. continue elif value == 1 and unit.endswith('s'): # Remove the "s" if the unit is singular. unit = unit[:-1] uptime_values.append('{0} {1}'.format(value, unit)) uptime = ' '.join(uptime_values) return uptime
a6a4544b6754113d0c5ed13a18838770448be6a8
11,495
def chunker(arrays, chunk_size): """Split the arrays into equally sized chunks :param arrays: (N * L np.array) arrays of sentences :param chunk_size: (int) size of the chunks :return chunks: (list) list of the chunks, numpy arrays""" chunks = [] # sentence length sent_len = len(arrays[0]) # chunk the arrays over the sentence in chunk sizes for pos in range(0, sent_len, chunk_size): chunk = [] for array in arrays: chunk.append(array[pos: pos+chunk_size]) chunks.append(chunk) return chunks
42a6867464e32d59a50927e8e88d067fc86f4fa1
11,497
import requests import json def get_device_response(ctx): """Return the deserialized JSON response for /stat/device (devices)""" r = requests.get( ctx.obj["URL"] + "stat/device", verify=ctx.obj["VERIFY"], cookies=ctx.obj["COOKIES"], ) return json.loads(r.text)
a763e3a5aedb0b2124244424f44fe7aa56bb8963
11,500
import math def calculate_ransac_iterations(min_points_per_sample, outlier_rate, desired_success_probability): """Estimates how many RANSAC iterations you should run. Args: min_points_per_sample: Minimum number of points to build a model hypothesis. outlier_rate: Float, 0-1, how often outliers are expected. desired_success_probability: Float, 0-1 exclusive, desired certainty that the RANSAC run will find the correct model. Higher certainty requires more iterations. Returns: Number of iterations. """ if not 0 < desired_success_probability < 1: raise ValueError('desired_success_probability should fall between 0 and 1, exclusive.') if not 0 <= outlier_rate <= 1: raise ValueError('outlier_rate should fall between 0 and 1.') if min_points_per_sample <= 0: raise ValueError('min_points_per_sample must be a positive integer.') assert 0 < desired_success_probability < 1 return math.ceil(math.log(1 - desired_success_probability) / math.log((1 - (1 - outlier_rate) ** min_points_per_sample)))
cafca93f052770f695f90d5f37e088e880fd0c45
11,506
def generate_graph(data, course_to_id): """ Method to read the JSON and build the directed graph of courses (= DAG of course IDs) The graph is represented in an adjacency list format :return: A graph in adjacency list format, with vertices as course IDs and directed edges implying prerequisite relation :rtype: List[List[int]] """ graph = [] * len(course_to_id) ctr = 0 for obj in data: graph.append([]) for prereq in obj["prerequisites"]: graph[ctr].append(course_to_id[prereq.strip()]) ctr += 1 return graph
0a6fe305e39bd812e000a1d22d2374636a7900b2
11,513
from typing import Optional import math def round_for_theta( v: float, theta: Optional[float] ) -> float: """ Round a value based on the precision of theta. :param v: Value. :param theta: Theta. :return: Rounded value. """ if theta is None: return v else: return round(v, int(abs(math.log10(theta)) - 1))
ef6d18df588df8a80be9dc6c9b7f9104e3109d69
11,514
from typing import List def split_badge_list(badges: str, separator: str) -> List[str]: """ Splits a string of badges into a list, removing all empty badges. """ if badges is None: return [] return [badge for badge in badges.split(separator) if badge]
6dc53d45cc8390422e5a511e39475ae969bf37c9
11,516
def column(matrix, col): """Returns a column from a matrix given the (0-indexed) column number.""" res = [] for r in range(len(matrix)): res.append(matrix[r][col]) return res
f5214b5a41bf265f6892fdfd9422061b02f61c63
11,523
import re def parse_scenario_gtest_name(name): """Parse scenario name to form acceptable by gtest""" # strip name = name.strip() # space and tab to _ name = name.replace(" ", "_").replace("\t", "_") # remove dots. commas name = re.sub('[^a-zA-Z_]+', '', name) # make lower name = name.lower() return name
faca8406a6b033536c3f9e0da21d9dc818fd2a7e
11,524
import json def load_json(filepath): """Load a json file. Args: filepath (str): A path to an input json file. Returns: dict: A dictionary data loaded from a json file. """ with open(filepath, 'r') as f: ret = json.load(f) return ret
c64fec0c861d223e28001051906e32d3aa9ffc7a
11,525
def statement(prop, value, source): """ Returns a statement in the QuickStatements experted format """ return "LAST\t{}\t{}\tS854\t\"{}\"".format(prop, value, source)
2c0b6ea8f757c8586ca462d85fca3b9d281adb26
11,529
import json def get_config_db_json_obj(dut): """ Get config_db content from dut Args: dut (SonicHost): The target device """ config_db_json = dut.shell("sudo sonic-cfggen -d --print-data")["stdout"] return json.loads(config_db_json)
92920197b2056d889ffb76ff66e01061f0654032
11,530
def check_sender(tx: dict, sender: str) -> bool: """ :param tx: transaction dictionary :param sender: string containing sender's address :return: boolean """ if tx["events"][0]["sub"][0]["sender"][0]["account"]["id"] == sender: return True return False
785c8453b876a2ca2b14f374836987c77a01f882
11,534
def is_prime_det(n): """ Returns <True> if <n> is a prime number, returns <False> otherwise. It uses an (optimized) deterministic method to guarantee that the result will be 100% correct. """ # 2 and 3 are prime numbers if (n <= 3): return (n > 1) # Corner cases to speed up the next loop if (n % 2 == 0) or (n % 3 == 0): return False # Using (6k-1) and (6k+1) optimization i = 5 while (i * i <= n): if (n % i == 0) or (n % (i + 2) == 0): # Not a prime number return False i += 6 return True
65ee46364510f45485c7d95ee0973d42ebc81d34
11,535
def zippify(iterable, len=2, cat=False): """ Zips an iterable with arbitrary length pieces e.g. to create a moving window with len n Example: zippify('abcd',2, cat=False) --> [('a', 'b'), ('b', 'c'), ('c', 'd')] If cat = True, joins the moving windows together zippify('abcd',2, cat=True) --> ['ab', 'bc', 'cd'] """ iterable_collection = [iterable[i:] for i in range(len)] res = list(zip(*iterable_collection)) return [''.join(r) for r in res] if cat else res
def01ff9f940009f80c312fe9ee07b282733d99b
11,540
def sanitize_int(value): """ Sanitize an input value to an integer. :param value: Input value to be sanitized to an integer :return: Integer, or None of the value cannot be sanitized :rtype: int or None """ if isinstance(value, str): try: return int(value) except ValueError: return None elif isinstance(value, int): return value
5c0481c0c7414f5fdba946f66346b3233ffe6644
11,542
def _get_dir_names(param): """Gets the names of the directories for testing the given parameter :param param: The parameter triple to be tested. :returns: A list of directories names to be used to test the given parameter. """ return [ '-'.join([param[0], str(i)]) for i in range(0, 5) ]
8ef2ad44127402987a26ec0bc6bfffc372f3c64d
11,548
def bool_converter(value: str) -> bool: """ :param value: a string to convert to bool. :return: False if lower case value in "0", "n", "no" and "false", otherwise, returns the value returned by the bool builtin function. """ if value.lower() in ['n', '0', 'no', 'false']: return False return bool(value)
10251dfbb0200297d191dce1eb20237aed9e5ac9
11,550
def heat_stor(cp, spm, tdif): """ Calculate the heat storage Args: cp: specific heat of layer (J/kg K) spm: layer specific mass (kg/m^2) tdif: temperature change (K) """ return cp * spm * tdif
397736e091a2cea09328cbf7f6e81c99db6fe384
11,551
from typing import Any from typing import Optional from typing import IO import yaml def dump_yaml(data: Any, stream: Optional[IO[str]] = None) -> Optional[str]: """Dump YAML to stream or return as string.""" if stream is not None: return yaml.safe_dump(data, stream, default_flow_style=False) else: return yaml.safe_dump(data, default_flow_style=False)
7ff998722e5d7754f83e960127bbed39d4a8d728
11,552
def get_link_to_referenced_comment(subreddit_name, user_note): """Extracts the id of the comment referenced by the usernote and formats it as a reddit-internal link""" link_code_segments = user_note['l'].split(',') if len(link_code_segments) == 3: submission_id = link_code_segments[1] comment_id = link_code_segments[2] return '/r/{0}/comments/{1}/x/{2}/?context=3'.format(subreddit_name, submission_id, comment_id) else: return None
cb41189bc05962e37fdf91aa3e5c53c64acb9400
11,553
def _detects_peaks(ecg_integrated, sample_rate): """ Detects peaks from local maximum ---------- Parameters ---------- ecg_integrated : ndarray Array that contains the samples of the integrated signal. sample_rate : int Sampling rate at which the acquisition took place. Returns ------- choosen_peaks : list List of local maximums that pass the first stage of conditions needed to be considered as a R peak. possible_peaks : list List with all the local maximums in the signal. """ # Minimum RR interval = 200 ms min_rr = (sample_rate / 1000) * 200 # Computes all possible peaks and their amplitudes possible_peaks = [i for i in range(0, len(ecg_integrated)-1) if ecg_integrated[i-1] < ecg_integrated[i] and ecg_integrated[i] > ecg_integrated[i+1]] possible_amplitudes = [ecg_integrated[k] for k in possible_peaks] chosen_peaks = [] # Starts with first peak if not possible_peaks: raise Exception("No Peaks Detected.") peak_candidate_i = possible_peaks[0] peak_candidate_amp = possible_amplitudes[0] for peak_i, peak_amp in zip(possible_peaks, possible_amplitudes): if peak_i - peak_candidate_i <= min_rr and peak_amp > peak_candidate_amp: peak_candidate_i = peak_i peak_candidate_amp = peak_amp elif peak_i - peak_candidate_i > min_rr: chosen_peaks += [peak_candidate_i - 6] # Delay of 6 samples peak_candidate_i = peak_i peak_candidate_amp = peak_amp else: pass return chosen_peaks, possible_peaks
ab9dd461f65095f048942ab8b8c069c456ea4933
11,554
import itertools def normalise_text(text): """ Removes leading and trailing whitespace from each line of text. Removes leading and trailing blank lines from text. """ stripped = text.strip() stripped_lines = [line.strip() for line in text.split("\n")] # remove leading and trailing empty lines stripped_head = list(itertools.dropwhile(lambda s: not s, stripped_lines)) stripped_tail = itertools.dropwhile(lambda s: not s, reversed(stripped_head)) return "\n".join(reversed(list(stripped_tail)))
52ab40cfa4c39ed194fa71aa28d70f5fa737d70c
11,560
import sqlite3 def sqlite3get_table_names(sql_conn: sqlite3.Connection): """For a given sqlite3 database connection object, returns the table names within that database. Examples: >>> db_conn = sqlite3.connect('places.sqlite')\n >>> sqlite3get_table_names(db_conn)\n ['moz_origins', 'moz_places', 'moz_historyvisits', 'moz_inputhistory', 'moz_bookmarks', 'moz_bookmarks_deleted', 'moz_keywords', 'moz_anno_attributes', 'moz_annos', 'moz_items_annos', 'moz_meta', 'sqlite_stat1'] References: # How to list tables for a given database:\n https://techoverflow.net/2019/10/14/how-to-list-tables-in-sqlite3-database-in-python/\n # Firefox forensics - what sqlite databases store which artifacts\n https://www.foxtonforensics.com/browser-history-examiner/firefox-history-location\n Args: sql_conn (sqlite3.Connection): Reference an existing slite3 Connection object. Returns: list: Returns a list of the table names in the database. """ cursor = sql_conn.execute("SELECT name FROM sqlite_master WHERE type='table';") table_names = [ name[0] for name in cursor.fetchall() if name[0] != 'sqlite_sequence' ] cursor.close() return table_names
0cb1ba2ba475268d39fef8bdbe044436f51c4f07
11,563
from typing import List from typing import Any def sort(xs: List[Any]) -> List[Any]: """ Sort the list `xs` with the python `sort` function and return the sorted function. The given list is not modified. Parameters ---------- xs A list. Returns ------- xs_sorted A sorted copy of `xs`. """ xs_copy = xs.copy() xs_copy.sort() return xs_copy
706190a533c19b6a7ea4baf540823ca73406560b
11,566
import pickle def read_solver(filename): """ This function reads a .pk1 file. Parameters: filename (str): A file name or path to file excluding file extension. Returns: Content of the loaded .pk1 file. """ try: file = open(filename+'.pk1', 'rb') except IOError: print('unable to open file') return False else: solver_obj = pickle.load(file) file.close() return solver_obj
da7bcfb75af1edde3d43091fdbc5c1829c13e5e0
11,570
import inspect def get_argument_help_string(param: inspect.Parameter) -> str: """Get a default help string for a parameter :param param: Parameter object :type param: inspect.Parameter :return: String describing the parameter based on the annotation and default value :rtype: str """ help_str = "" if param.annotation is not param.empty: help_str = inspect.formatannotation(param.annotation) if param.default is not param.empty: if param.annotation is not param.empty: help_str += ", " help_str = f"{help_str}defaults to {param.default!r}" return help_str
7381591ce45591bf1aef62280fc4b98e57969576
11,573
def nested_select(d, v, default_selected=True): """ Nestedly select part of the object d with indicator v. If d is a dictionary, it will continue to select the child values. The function will return the selected parts as well as the dropped parts. :param d: The dictionary to be selected :param v: The indicator showing which part should be selected :param default_selected: Specify whether an entry is selected by default :return: A tuple of two elements, the selected part and the dropped part Examples: >>> person = {'profile': {'name': 'john', 'age': 16, 'weight': 85}, \ 'relatives': {'father': 'bob', 'mother': 'alice'}} >>> nested_select(person, True) ({'profile': {'name': 'john', 'age': 16, 'weight': 85}, 'relatives': {'father': 'bob', 'mother': 'alice'}}, {}) >>> nested_select(person, {'profile': False}) ({'relatives': {'father': 'bob', 'mother': 'alice'}}, {'profile': {'name': 'john', 'age': 16, 'weight': 85}}) >>> nested_select(person, {'profile': {'name': False}, 'relatives': {'mother': False}}) ({'profile': {'age': 16, 'weight': 85}, 'relatives': {'father': 'bob'}}, {'profile': {'name': 'john'}, 'relatives': {'mother': 'alice'}}) """ if isinstance(v, dict): assert isinstance(d, dict) choosed = d.__class__() dropped = d.__class__() for k in d: if k not in v: if default_selected: choosed.setdefault(k, d[k]) else: dropped.setdefault(k, d[k]) continue if isinstance(v[k], dict): assert isinstance(d[k], dict) child_choosed, child_dropped = nested_select(d[k], v[k]) if child_choosed: choosed.setdefault(k, child_choosed) if child_dropped: dropped.setdefault(k, child_dropped) else: if v[k]: choosed.setdefault(k, d[k]) else: dropped.setdefault(k, d[k]) return choosed, dropped else: other = d.__class__() if isinstance(d, dict) else None return (d, other) if v else (other, d)
84aa16adfb324fef8452966087cbf446d57893d2
11,575
def is_trans(reaction): """Check if a reaction is a transporter.""" return len(reaction.metabolites) == 1
a0b9be30b4a88156e7a89cf48b8ecb76345e4cab
11,578
def format_tile(tile, tile_format, format_str='{x} {y} {z}'): """Convert tile to necessary format. Parameters ---------- tile: pygeotile.tile.Tile Tile object to be formatted. tile_format: str Desired tile format. `google`, `tms`, or `quad_tree` format_str: str String to guide formatting. Only used for `google` or `tms` (as quad_tree is one value). Default: "{x} {y} {z}". Example: "{z}-{x}-{y}" """ if tile_format == 'google': td = {key: val for key, val in zip(['x', 'y', 'z'], list(tile.google) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'tms': td = {key: val for key, val in zip(['x', 'y', 'z'], list(tile.tms) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'quad_tree': return tile.quad_tree else: raise ValueError('`tile_format`: {} not recognized'.format(tile_format))
e7ce2653f49f0c535bb3ea0a0c4bec3b48a74331
11,579
def percent(a, b): """ Given a and b, this function returns a% of b """ return (a/100)*b
d8adae353bb1b7aba6eb0149af065182bf752449
11,580
import math def filter_none(mongo_dict): """Function to filter out Nones and NaN from a dict.""" for key in list(mongo_dict.keys()): val = mongo_dict[key] try: if val is None or math.isnan(val): mongo_dict.pop(key) except Exception: continue return mongo_dict
6853a7153f98466dc00d262bfaf4a63db1b0cd5c
11,581
import re def fetch_geneid(fn): """ fetch gene id from GTF records gene_id "FBgn0267431"; gene_name "Myo81F"; gene_source "FlyBase"; gene_biotype "protein_coding"; """ assert isinstance(fn, str) ps = fn.split(';') dn = {} for i in fn.split(';'): if len(i) < 8: # shortest field continue id = i.strip().split(' ') id = re.sub('"', '', id[1]) if 'gene_id' in i: dn['gene_id'] = id elif 'gene_name' in i: dn['gene_name'] = id elif 'transcript_id' in i: dn['transcript_id'] = id elif 'transcript_name' in i: dn['transcript_name'] = id elif 'exon_id' in i: dn['exon_id'] = id elif 'gene_biotype' in i: dn['gene_biotype'] = id else: pass return dn
c3ddb9c5c820799800131c6e11dc2ef91d4556c1
11,587
def fieldsMatch(f0, f1): """ Checks whether any entry in one list appears in a second list. """ for f in f0: if f in f1: return True return False
172772fca613fe97e32bb6860c3bd217b643fe2d
11,588
def list_to_str(lst): """convert list/tuple to string split by space""" result = " ".join(str(i) for i in lst) return result
1e6c59f834b98b1d49ca1c0919d2d976fd1de1de
11,589
def extract_bias_diagonal(module, S, sum_batch=True): """Extract diagonal of ``(Jᵀ S) (Jᵀ S)ᵀ`` where ``J`` is the bias Jacobian. Args: module (torch.nn.Conv1d or torch.nn.Conv2d or torch.nn.Conv3d): Convolution layer for which the diagonal is extracted w.r.t. the bias. S (torch.Tensor): Backpropagated (symmetric factorization) of the loss Hessian. Has shape ``(V, *module.output.shape)``. sum_batch (bool, optional): Sum out the batch dimension of the bias diagonals. Default value: ``True``. Returns: torch.Tensor: Per-sample bias diagonal if ``sum_batch=False`` (shape ``(N, module.bias.shape)`` with batch size ``N``) or summed bias diagonal if ``sum_batch=True`` (shape ``module.bias.shape``). """ start_spatial = 3 sum_before = list(range(start_spatial, S.dim())) sum_after = [0, 1] if sum_batch else [0] return S.sum(sum_before).pow_(2).sum(sum_after)
b2f8aaefa22d1ae915c59f80f98341059a4d1ad3
11,590
from gzip import GzipFile from typing import Any import json def gzip_load_var(gzip_file:str) -> Any: """ Load variable from .json.gz file (arbitrary extension!) Parameters ---------- gzip_file : str Filename containing the gzipped JSON variable Returns ------- var : Any Variable as decoded from gzipped JSON content """ # IMPORT DONE HERE TO SAVE TIME AT MODULE INIT try: with GzipFile(gzip_file, 'r') as gzip_in: json_var = json.loads(gzip_in.read().decode('utf-8')) except: raise return json_var
b9f6fbad33b40bb18a1418f3134b0889d5344183
11,595
def category_table_build(osm_table_name, categorysql): """ Returns an SQL OSM category table builder Args: osm_table_name (string): a OSM PostGIS table name Returns: sql (string): a sql statement """ sql = ("INSERT INTO category_%s (osm_id, cat) " "SELECT DISTINCT osm_id, " "%s as cat " "FROM %s as osm") sql = sql % (osm_table_name, categorysql, osm_table_name) return sql
147812bb68845e3fd0dca7e805f610d26428eac3
11,601
def count_helices(d): """Return the helix count from structure freq data.""" return d.get('H', 0) + d.get('G', 0) + d.get('I', 0)
8469adabac42937009a1f8257f15668d630a7ca8
11,603