content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import torch import itertools def get_targs_preds(model, dl): """ get the prediction and the targets Args: model, dataloader Returns: two lists with prediction and the targets """ preds = [] targs = [] device = 'cuda' if torch.cuda.is_available() else 'cpu' model.to(device) fo...
7d6055ff204cc54b2e40d89ea413ab2416a16f1c
588,568
def loadArticle(filename): """ 加载文章 :param filename: 文件路径 :return: 文章内容 """ artical = [] with open(filename, encoding='utf8') as f: for line in f.readlines(): line = line.strip() if not line: continue # 将该行放入文章列表中 artic...
c650cf2d13b53d1d5cabcee51ffe6540b6dae5db
588,569
from typing import List def generate_conclusion(definition: str) -> List[str]: """Generate header file conclusion lines""" return [ '\n', '#ifdef __cplusplus\n', '}\n', '#endif\n', '\n', f'#endif // {definition}\n' ]
e94714bdc9c8efe47e8d97b9029b9e8bed92bab7
588,571
import string def simplestring(length, offset=0): """ Deterministically generates a string. Args: length: Length of the string offset: Offset of the string Returns: A string formed of lowercase ASCII characters. """ return "".join( [ string.ascii_lo...
8e1fb53b7790d8a9b95815cc861c47d5f5281c1d
588,572
def _search_line_for_cmd_start(line: str, start: int, valid_commands: dict) -> int: """Scan `line` for a string matching any key in `valid_commands`. Start searching from `start`. Commands escaped with `\` (E.g. `\DexLabel('a')`) are ignored. Returns: int: the index of the first character of t...
0729ab885e8b10720cf9dec972d4be1486be9a53
588,573
def _InsertQuotes(string, left_index, right_index): """Insert quotes in the passed string. Args: string: A string in which quotes will be inserted. left_index: An integer representing the index where starting quote will be inserted. right_index: An integer representing the index where closi...
6b01eb6178c36ef250bb3efc312f1fb8e1f96adb
588,576
def to_number(s): """Takes str s and returns int (preferentially) or float.""" if s.find(".") > -1: return float(s) return int(s)
f1282df0552a3cca229cdc0e038b6fbc3293ff03
588,579
def insertion_sort(L): """ Insertion sort is a simple algorithm which builds the final sorted list 1 item at a time. It compares the current element with it's neighbor to the left. If the current element is smaller than the neighbor, it then compares with the neighbor before that and so on unti...
efd321e9a2c2f27c3ec62d2fdd8701d9cf8e724d
588,580
def get_style(is_white_cell, is_white_piece, is_selected, is_targeted): """Returns the associated style for the provided combination of piece and cell""" if is_white_cell: return 'white_cell' elif is_targeted: return 'magenta_cell' elif is_selected: if is_white_piece: return 'red_cell_white_piec...
c595350ae26b00665451053586474d8a86ab9304
588,582
from typing import Any import importlib def get_class(module_name: str) -> Any: """ Given the name of a module, this function will import the module and return the object "cls". :param module_name: Module containing the target class. :return: The "cls" class from the specified module. """ ret...
dfbcbea11ec018940131c3f2b194ffcf163067b2
588,586
import torch def from_mag_and_phase(mag, phase, dim=-2): """ Return a complex-like torch tensor from magnitude and phase components. Args: mag (torch.tensor): magnitude of the tensor. phase (torch.tensor): angle of the tensor dim(int, optional): the frequency (or equivalent) dimension...
51f4b64644acf687816a814e54dacd7f97a05c81
588,587
def failure_message_from_response(response): """ Given EMR response, returns a descriptive error message """ fail_details = response['Step']['Status'].get('FailureDetails') if fail_details: return 'for reason {} with message {} and log file {}'\ .format( fail_deta...
a9f0e78bb1683773bf9fbb8b0779b0a2ca4af56b
588,590
def get_observation_shape(x): """ Get observation shape for each key (recursive) Args: x: dictionary of observation Returns: dictionary of shape """ d = {} if isinstance(x, dict): for k in x.keys(): d[k] = get_observation_shape(x[k]) else: r...
051acc2b32a030160f4f365ed56212afd231d5d8
588,591
def lchop(s, sub): """Chop ``sub`` off the front of ``s`` if present. >>> lchop("##This is a comment.##", "##") 'This is a comment.##' The difference between ``lchop`` and ``s.lstrip`` is that ``lchop`` strips only the exact prefix, while ``s.lstrip`` treats the argument as a set of leading ch...
44774664741a8e1e123598cf86f2015f10877ab2
588,592
def company_serializer(company): """ Returns company object as a python dictionary. """ return {"name": company.name, "size": company.size, "logo": company.logo, "link": company.link, "description": company.description, "count": company.count}
289243a7825b313b67d16cf1191c20be84a7027e
588,595
def add_offside_variable(df_events): """ This function removes the offside events in the Wyscout event data and adds sets offside to 1 for the previous event (if this was a passing event) Args: df_events (pd.DataFrame): Wyscout event dataframe Returns: pd.DataFrame: Wyscout event dataframe...
bb73f4b05fed5db54d890456fcb9c198884b0c39
588,596
def get_module(indir, toc_file): """The NetBeans module containing the toc_file. Assuming indir is the root directory of the NetBeans project, the module is the top-most directory of the toc_file under indir. """ return toc_file.relative_to(indir).parts[0]
54ab7f80d1487f7a703d6063e9fb9871a490ca16
588,597
def bestAlgorithm_(sequencingChemistries): """ Identify the (de novo) consensus algorithm we expect to deliver the best results, given the sequencing chemistries represented in an alignment file. We key off the sequencing chemistries as follows: - Just RS chemistry data? Then use quiver (at l...
25b73bbba48d1a58b6c31645f04f810dc025178c
588,599
def getPublicAttributes(obj): """Return a list of public attribute names.""" attrs = [] for attr in dir(obj): if attr.startswith('_'): continue try: getattr(obj, attr) except AttributeError: continue attrs.append(attr) return attrs
7930384687e71ddb16f416358ff5993bb3178b06
588,603
def customer_email(obj): """ Returns a string representation of the customer's email.""" return str(obj.customer.subscriber.email)
6c6a35846a532e5d197fa5d95b115b4e62008e94
588,610
def get_display_text_for_event(event): """ Takes an event from a collection exercise and returns a version of it that can be displayed to the user. If the string isn't found in the map, it just returns the string the function was given. :param event: A name of an event from a collection exercise :t...
9634391bda3de743a76b221b42aa7ad529df04d9
588,616
def parse_frequency(variant, info_key): """Parse any frequency from the info dict Args: variant(cyvcf2.Variant) info_key(str) Returns: frequency(float): or None if frequency does not exist """ raw_annotation = variant.INFO.get(info_key) raw_annotation = None if ...
2f889e3c9ecc756a3e79f91b5520acd732063dd2
588,617
from typing import Any def closest_obs_blender(low_value: Any, high_value: Any, coeff: float): """Choosing the high or low value based on coefficient value.""" return low_value if coeff < 0.5 else high_value
1f70a932e0c5eb924a4b8ac89a4237f280bd660c
588,619
import torch def mae(target, predictions: list, total=True): """ Calculates mean absolute error MAE is different from MAPE in that the average of mean error is normalized over the average of all the actual values Parameters ---------- target : torch.Tensor true values of the target va...
815f803b3719d01357e5a439f23d316394bb72c3
588,624
def _replacer(x) -> str: """ Replace a number with its hexadecimal representation. Used to tag temporary variables with their calling scope's id. """ # get the hex repr of the binary char and remove 0x and pad by pad_size # zeros try: hexin = ord(x) except TypeError: # by...
0a695c2518240411696e4fb4412f6eebc26faaae
588,629
def merge_two_dicts(x, y): """ Given two dicts, merge them into a new dict as a shallow copy. Any overlapping keys in `y` will override the values in `x`. Taken from https://stackoverflow.com/questions/38987/ how-to-merge-two-python-dictionaries-in-a-single-expression Parameters: x, y:...
20563bc8c581db6b6890634d2cc9792496aa2bce
588,630
def get_callback_list_entry(name, **params): """ Builds an entry of a callback specification, i.e., a tuple (callback_name, **callback_params) Parameters ---------- name: the name of a callback generator function params: parameters to the callback generator function Returns ---...
6b947e6b84c2cb9124238b7e076c06b352481471
588,639
def diminuir(num, porcentagem): """ -> Calcula o valor reduzido de uma determinada porcentagem :param num: numero que será acrescido da porcentagem :param porcentagem: valor da porcentagem a ser calculada :return: o resultado do cálculo """ resultado = num - (num * (porcentagem / 100)) r...
c4515886adb6be846710b964dccc6c55ce982ab9
588,644
def saltWaterSolubility(X, sWSP): """ saltWaterSolubility(X, sWSP) saltWaterSolubility (ppm by wt) = 10**(A + B*X + C*X**2) Parameters X, concentration of NaCl in water at 25 Deg. C in ppm by wt sWSP, A=sWSP[0], B=sWSP[1], C=sWSP[2] A, B, and C are regression coefficients ...
8100163b7f6250600b23bc0398b57484d58dcc3e
588,647
def common(dicts, f): """Returns common result of f across an iterable of dicts, or None. Call f for each dict and return its result if the same across all dicts. """ values = (f(d) for d in dicts) first_value = next(values) if all(value == first_value for value in values): return first...
da1de8829a1b6ccedef7b93d8ee9ba477c34c6ea
588,649
import posixpath import base64 def resolve_path(name: str, url: str) -> str: """Transform a URL into a filesystem-safe filename.""" url_base = posixpath.dirname(url) return '.'.join(( name, str(base64.b64encode(bytes(url_base, 'utf-8')), 'utf-8'), 'inv'))
911cee6afdff8e08dc8da39f74917d802ef4fa1d
588,650
import math def first_digit(value): """ Return the first digit position of the given value, as an integer. 0 is the digit just before the decimal point. Digits to the right of the decimal point have a negative position. Return 0 for a null value. """ try: return int(math.floor(ma...
3d417155473bf469e4afbd56b48575f4d81d3461
588,651
def set_floating_point_behaviour_options(opts, inv=True, div0=True, oflo=True, esr=True, nanoo=True): """Set the ...
5de7a94831dc6f5a8b3bb641aebb383c031d342b
588,652
import tempfile import shutil def tmp_dir_path(request): """ Give a path for a temporary directory The directory is destroyed at the end of the test. """ # Temporary directory. tmp_dir = tempfile.mkdtemp() def teardown(): # Delete the whole directory: shutil.rmtree(tmp_dir...
6ac0ca9808a482f768c8a9a29046279e4ca8afe0
588,654
def angular_distance(a1: float, a2: float) -> float: """Calculates the angular distance between two angles in degrees.""" phi = abs(a2 - a1) % 360; distance = 360 - phi if phi > 180 else phi; return distance;
1853667dc7f1d8c22c058ceb18b891a45b201663
588,656
from typing import Set def read_requirements(filepath) -> Set[str]: """Reads a standard requirements.txt file.""" with open(filepath) as fh: raw = fh.readlines() raw = [x.strip() for x in raw] raw = [x for x in raw if x and x[0] != "#"] return set(raw)
5eff896a517220b548f1e390a00d94891e7f9697
588,657
def matches_genome(genome1, genome2, symmetric=False): """ expects two dictionaries or iterables of ('name', length) tells you if genome1 matches genome2 (not all the entries in genome2 need to be matched, but all the entries in genome1 must be) symmetric=True means matches(genome1,genome2) and...
bbdb24d56298f0496b1a67cb6f2ae3271bf21d0e
588,660
from typing import Tuple from typing import Optional def parse_repository(name: str) -> Tuple[str, Optional[str]]: """Parse repository image name from tag or digest Returns: item 1: repository name item 2: Either digest and tag, tag, or None """ # split image name and digest eleme...
722e09755688f03c712d8adfe9d93533729c0689
588,661
def no_data_message(metric: str, financial_year: str) -> list[str]: """Message for when selection does not provide data.""" return [ f"The selection you have made has no data for {metric.lower()}. ", f"This is probably because data has not been published for {financial_year}, ", "please ...
75c914d256a8ed16d18870f6e532318267255bb8
588,665
import json def get_duration(match_config_path): """ Returns a match duration from a match configuration JSON file (batch_input.json or freeplay.json). """ with open(match_config_path) as config_file: config_json = json.loads(config_file.read()) return config_json["D...
9acbcb47c6279daa5d556c54ea19afc729e7a19e
588,666
def search_ancestor(node, node_type_or_types): """ Recursively looks at the parents of a node and checks if the type names match. :param node: The node that is looked at. :param node_type_or_types: A tuple or a string of type names that are searched for. """ if not isinstance(node_t...
5a40baad702cdb9bf8119b4f0b65fc3b484bc3e6
588,667
def FormatAnchor(label): """Format a label as an Envoy API RST anchor.""" return '.. _%s:\n\n' % label
7c75d8d702ba8388cc4828ca15ff4d7642665858
588,668
def iif(f): """ Immediately-invoked function. Replaces the decorated function with its return value. """ return f()
2d00ee5fca25455c25319ad36f21b84034b85d17
588,670
def cast_iops_as_float(iops_all_dict): """ Convert IOPS values from str to float :param iops_all_dict: IOPS dict to convert. :return: IOPS values as float """ iops_all_dict_float = {} for key, value in iops_all_dict.items(): try: iops_all_dict_float[key] = float(value) ...
3ec807d9115a7fdb108d58a699e7a8784b07c5fe
588,671
import re def spliceDictName(dict_fname): """------------------------------------------------------------------- Function: [spliceDictName] Description: Extracts data from a given dictionary (.dict) filename Input: [dict_fname] Dictionary filename of the form <Series>_<Host>_<Code>.dict Return: A 3-t...
c4e54ecd652ff4ef55d16b2afcd9edb2ddbc3544
588,672
def get_id_or_email_identifier(**kwargs): """Return id or email identifier.""" identifier = None for k in ['id', 'email']: identifier = kwargs.get(k, None) if identifier is not None: break return identifier
5336f178c2979065ff977df517b87708ab1c8e66
588,677
def factorial(integer: int) -> int: """Return the factorial of a given integer. Args: integer (int): the integer whose factorial is going to be calculated Returns: int: the factorial of the provided integer """ if integer in {0, 1}: return 1 return integer * factorial(...
4d6457f5c3651d21ba6d831956e26e7522de553a
588,679
def get_list_change_date(card, list_before_name, list_after_name): """ Return the date of when a list changed from the specified before & after lists. """ if not card.actions: return for action in card.actions: if all(key in action['data'] for key in ['listBefore', 'listAfter']): ...
7eb30d63d327baf663676edfd0218088a3a7c870
588,681
from typing import Tuple from typing import Dict def next_state( coord: Tuple[int, int, int], grid: Dict[Tuple[int, int, int], bool] ) -> bool: """Apply rules in 3D space - If a coordinate is active and has 2 or 3 active neighbors, it stays active (off otherwise) - If a coordinate is inactive, it onl...
b3e364251526dbadedfd6232834810da4e49fdb4
588,684
def unzip_dict(list_of_dicts): """ Converts a list of dictionaries to a dictionary of lists. Useful to transform the outcomes of a simulation """ return {key: [d[key] for d in list_of_dicts] for key in list_of_dicts[0]}
51f5996f289fca23062b0e6b07dc19f8efce2afc
588,686
def one(elements): """Returns True if only one element is not None, false otherwise""" return sum([False if e is None else True for e in elements]) == 1
4fc254155488c222f39f4a362a7233de42c3d932
588,692
def classes(*args, **kwargs): """Helper function for dynamically assembling a list of CSS class names in templates. Any positional arguments are added to the list of class names. All positional arguments must be strings: >>> classes('foo', 'bar') u'foo bar' In addition, the names of any s...
2bba98760ef7f50bcb82175e4efd9507e564a888
588,694
import math def f(r): """ Return (circumference, area) of a circle of radius r """ c = 2 * math.pi * r a = math.pi * r * r return (c, a)
162371453af74d6db4260bbdac74aed93b2a2e5b
588,697
def format_checksum(checksum_pyxb): """Create string representation of a PyXB Checksum object. Args: PyXB Checksum object Returns: str : Combined hexadecimal value and algorithm name. """ return "{}/{}".format( checksum_pyxb.algorithm.upper().replace("-", ""), checksum_pyxb.va...
b8b4252a27d824b954b635f878ad4cab88ab54f0
588,698
def swap_bbox_format(bbox_tuple): """Swap between (row0, col0, row1, col1) and (x0, y0, x1, y1) formats.""" assert len(bbox_tuple) == 4 return (bbox_tuple[1], bbox_tuple[0], bbox_tuple[3], bbox_tuple[2])
70f25efdde490acee7442a29f76117615fb1125c
588,699
def _cut(x: str) -> str: """helper function for Doc.__repr__()""" if len(x) < 20: return x else: return x[:20] + "…"
0e892a0e60b8a9fe355acf008cc6074111d69eea
588,704
def vents_diagram(input_data: list[tuple]) -> list[list[int]]: """ Creates a vents' diagram using only vertical or horizontal lines. Numbers >=0 represent vents, zeroes represent no vents. Args: input_data (list[tuple]): tuple of start/end coordinates [int] Returns: list[int]: 2D lis...
cb60ab66fb6dd9ae08b0668287db10f9c99a9aea
588,705
import math def GetShallowBranchingFactor(min_value, max_value, max_branching_factor=100): """Compute the branching factor that gives the most shallow tree. Using max_branching_factor would give a tree of minimal depth. However, that may waste space. This function computes the branching factor that gives the ...
9da934cbd5c15495860a9507d5b4615aa58d2b2a
588,710
def get_is_view_of_type(view, typ): """ Determine if view is of specified type. """ return not not view.settings().get("git_savvy.{}_view".format(typ))
5d9a5f220bdda3b1b2cc3bda27e38f7fcfc95cc5
588,718
def _findall(s, item): """Return index of each element equal to item in s""" return [i for i,x in enumerate(s) if x == item]
4e912e2467ef9de88e74bdde28b6d787fc8ede76
588,719
import re def searchCustomEmoji(string: str): """ Searches for a custom emoji in a specific ``str`` and returns it or None if nothing found. The custom emoji can either be animated or not. Params: string: The string which should get searched for a custom emoji. Returns: The custom emoji ...
f33274899cddb8fbbb0539c3123c1628fc5ff666
588,722
import csv def sniff_delimiter(input_file: str): """Detect the delimiter in a file""" sniffer = csv.Sniffer() with open(input_file, "rt") as f: first_line = f.readline().strip() dialect = sniffer.sniff(first_line) if dialect.delimiter not in [",", " ", "\t"]: raise ValueError("De...
ca4ce153ae6bb099f2a2dd3a996dfb6a855642a9
588,727
def add_defaults_to_kwargs(defaults, **kwargs): """Updates `kwargs` with dict of `defaults` Args: defaults: A dictionary of keys and values **kwargs: The kwargs to update. Returns: The updated kwargs. """ defaults = dict(defaults) defaults.update(kwargs) return defa...
3c9ae3076b9e93b243e4f2d7a7b9286cf3d848c4
588,730
import torch def truncate(matrix: torch.Tensor, rank: int) -> torch.Tensor: """Truncate the rank of the matrix by zeroing out singular values. Args: matrix (torch.Tensor): The matrix to truncate. rank (int): The rank to truncate the matrix to. Returns: torch.Tensor: The truncated...
6851e707bc6a29af1b845c0d83a86d803e28c27a
588,732
import hashlib def create_hash(value: str, algorithm: str) -> str: """ Returns the hash value for a given string value with the given algorithm. Supported hash algorithms can be seen with following lines of code: import hashlib print(hashlib.algorithms_available) """ encoded_value...
78065dad4f4a4c03ba8adc8439d756cf3b633538
588,734
def _remove_edge(x, N): """ Calculate the number of points to remove for edge artifacts x : array time series to remove edge artifacts from N : int length of filter """ N = int(N) return x[N:-N]
275491c0dd262ec1b80acc40a4b0eab955910f6d
588,736
def _parse_tags(tags): """Parse tags from CSV into a list.""" return [x.strip() for x in (tags or "").split(",")]
121bbbace43efc6724cce88b17b1090174fe0e50
588,740
def _decode_options(options): """Parse options given in str. When options = 'cutoff = 4.0', options is converted to {'cutoff': 4.0}. In this implementation (can be modified), using phonopy command line options, ``options`` is passed by --fc-calc-opt such as:: phonopy --hiphiveph --fc-calc-opt...
2b05eb8afb487c8bff22d1cb71c8bcda32cc18f3
588,741
from typing import List from typing import Tuple def dict_to_paired_list( in_dict: dict, sort: bool = False, reverse: bool = False ) -> List[ Tuple ]: """ Simple method to take a dictionary of { key : value } and return a list of tuples of ( key, value ). If sort = True is passed, the list will attem...
7569e4ec02b772fee4244de4df8533723f6a7de4
588,742
import pathlib def get_apofile(name): """convert name of data file to a path use standard name if empty """ return pathlib.Path(name or 'apropos').with_suffix('.apo')
35b277d1b7b4237d51ba2c5c303feefd6b573fcd
588,743
import json def parsePostData(data): """Parses the data submitted by the camera to the portal url Returns: { 'accountinfo': { 'signinid': 'appstore email address', 'accountid': 'appstore portal id', 'registered': '1', }, 'applications': [{ 'name': 'application name', 'version': 'appl...
0caa3af70090d85e11256b2659916ab297962614
588,744
def crop_rect_coords(image, vertical1, horizontal1, vertical2, horizontal2): """Crops a rectangle out of the image through two coords. params: image: A numpy ndarray, which has 2 or 3 dimensions vertical1: An integer, which is the vertical coord for the top left of the rectang...
654862be84c4f41b421b7e5614bd44958dbdef24
588,745
def is_nestable(x): """ Returns 1 if x is a tuple or list (sequence types that can nest) Returns 0 otherwise >>> is_nestable("string") 0 >>> is_nestable((0,)) 1 >>> is_nestable(range(5)) 1 """ return isinstance(x, (tuple, list))
f379bf2208315a97ae21290d4fe4deb51a63eba4
588,750
def get_list_of_uses_in_case_study(building_typology_df): """ validates lists of uses in case study. refactored from archetypes_mapper function :param building_typology_df: dataframe of occupancy.dbf input (can be read in archetypes-mapper or in building-properties) :type building_typology_df: pand...
7a8f2cc9f279a436f18b4d8a414afc9362f7ff23
588,751
def top_brands(data, topn=50): """ get top brands dataframe (review count 기준) :param data: total dataframe :param topn: num of top brands :return: top brands data, top brands list """ grouped = data.groupby('brand') s = grouped.count() brand_name = s.sort_values('asin', ascending=Fal...
4ad823329c4ab8cfa256aa020b3a20210806a409
588,753
def manhattan_distance(a, b): """ Calculates the Manhattan (L1) distance between the values in two libraries. The union of the keys of both a and b are used, with the default value 0. """ return sum([abs(a.get(k, 0) - b.get(k, 0)) for k in set().union(a, b)])
a0b18f18a4317c9a439a7eb8d5eb97f0adfdcbda
588,754
import csv def csv_to_list(filepath): """Reads a list from a csv file Args: filepath: Full path of file to write to Returns: list: the list of rows as a list of cells """ rows = [] # Open the file and use csv reader to parse with open(filepath, newlin...
c5213d782e35855af8f37fe9e0a097f5f8dafd91
588,756
def get_average_score(vector1, vector2): """ Calculate average (element-wise average) for vector1 and vector2. Note the result is not a scalar, it has dimension same as vector1 or vector2. """ return (vector1 + vector2)/2
02385914d93f2375693c5d0f7de1f73e5fbc3eda
588,762
def get_valid_input(question:str, validation_function) -> str: """ Will get valid input from the user and return it. :param validation_function: python function object used to validate input """ while True: inp = input(question).strip() if validation_function(inp): break else...
57e0806b03e4d7d7794da33cd9927f5e63ab0bea
588,766
def str2boolean(string): """ Converts the parameter to a boolean value by recognising different truth literals. """ return (string.lower() in ('yes', 'true', '1'))
489521a4af89b061674e69de483b6f51b87cea34
588,767
import re def remove_non_path_from_url(url): """ Remove everything from URL after path. """ url = url.split('?', 1)[0] # query url = url.split('#', 1)[0] # fragment identifier url = re.sub(r"/+$", "", url) # trailing slashes return url
6c7efc94cce44398008fc6908f093f829cccad3c
588,773
import torch def count_duplicates(cover_index: torch.LongTensor, normalize=False): """Count the number of node repetitions in the cover sets. Args: cover_index (torch.LongTensor): Cover assignment matrix, in sparse coordinate form. normalize (bool, optional): Normalize the re...
bb53f6d5ae2af7cce980bacd95277837aac65953
588,774
def get_ind_name_from_db2(db2_name: str): """Get an individual name json from a DB2 legacy name.""" last = db2_name[0:24].strip() first = db2_name[25:].strip() middle = None if len(db2_name) > 40: first = db2_name[25:38].strip() middle = db2_name[39:].strip() name = { 'fi...
add366ebb32d086b3b32186cf8946fa6a5babcfa
588,776
def adjust_points(points, adjust_x, adjust_y): """Adjust points based by adjust_x and adjust_y.""" adjusted = [] for point_x, point_y in points: adjusted.append((point_x - adjust_x, point_y - adjust_y)) return adjusted
e0520f1e5930c56856f1b5c07778114dd52c81b5
588,777
import random def random_policy(state): """ Ignore the state, move randomly. """ action = { 'command': random.randint(0, 1) } return action
675e489f3490ebe4e0279c1704536ba6282767f9
588,780
def __team_fixt_res_str(win,draw,lose): """ returns the textual result of a team fixture, given win/draw/lose boolean info of a match """ return '%s%s%s' %('G' if win==1 else '', 'N' if draw==1 else '', 'P' if lose==1 else '')
447be52c4508bf00ad475454896994706f979eb1
588,783
from struct import pack def mk_header(image): """ Create a La Palma format header of an image array Parameters ---------- image : ndarray 2D or 3D image array in La Palma ordering (nx, ny, nt) Returns ------- header : str header of the cube """ ss = image.sha...
10d3ab1735f2bd3db4a128189c0826c56274ba48
588,785
def generate_game_url(season, season_segment, game_number): """ Generates the url for a particular nhl game. The url is a concatenation of the year, season type, and game number. Inputs: :param season: the year in which the season started :param season_segment: 1 = preseason, 2 = regular seaso...
09f285112cc481ced48b4a119a2890fb65179f34
588,786
def _extrapolate(x1, y1, slope, x0, x2): """ Extrapolate from pivot point to the ends :param x1: :param y1: :param slope: :param x0: :param x2: :return: tuple containing low and high end points """ y0 = int(slope * (x0 - x1) + y1) y2 = int(slope * (x2 - x1) + y1) return (...
a7083273c61141c3eca5e23b6246cf80ffa6889f
588,788
import re def title_except(s, exceptions): """ Titlelize a string with exceptions. """ word_list = re.split(' ', s.lower()) #re.split behaves as expected final = [word_list[0].capitalize()] for word in word_list[1:]: final.append(word in exceptions and word or word.capitalize()) return " ".join(final)
5a4c00c439470b06ea6ba0cef4ef594a7bebabb4
588,793
def fahrenheitToCelcius(fahrenheit:float, ndigits = 2)->float: """ Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Celsius """ return round((float(f...
5ba96c918a26cedbb872321c3c22fa4598e2b5b9
588,797
def test_var(test_ds): """Provide a standard, parsed, variable for testing.""" return test_ds.metpy.parse_cf('Temperature')
90e1fb9aea0a89644d31300bb5d2a3d70457413a
588,799
from typing import Counter def sorted_count_of_values(cards): """ Takes a tuple of pokertools.Card objects and returns a sorted list of counts of the card ranks. For example, consider this hand: hand('7h Ks 7d 7c Kd') Its corresponding list of numerical ranks is: [7, 13, 7, 7, 13]...
1e6db3e6fabeaeee8cb2ef459f743a4d9624ee83
588,800
from datetime import datetime def is_not_datetime(value): """ Checks if a value can be converted to datetime. :param value: string to convert. :return True or False. """ try: datetime.strptime(value, "%H:%M:%S").date() return False except ValueError: return True
eed34183b55e111e6a383b51465add82268a52f6
588,802
import torch def skew_symmetric(v): """Create a skew-symmetric matrix from a (batched) vector of size (..., 3). """ z = torch.zeros_like(v[..., 0]) M = torch.stack([ z, -v[..., 2], v[..., 1], v[..., 2], z, -v[..., 0], -v[..., 1], v[..., 0], z, ], dim=-1).reshape(v.shape[:-1...
cacf58a9489b156426fad43461d57177d49eb5e4
588,803
def ds2423(rd_val): """Converts the counter.ALL file value of the DS2423 dual counter to an A and a B counter reading. """ a_ct, b_ct = rd_val.split(',') return [ (int(a_ct), 'A'), (int(b_ct), 'B') ]
13de983d5227bc42f2a70308d25c4629039a1796
588,804
def button_web_url(title, url): """ Creates a dict to send a web_url, can be used with generic_elements or send_buttons :param title: Content to show the receiver :return: dict """ return { 'type': 'web_url', 'url': url, 'title': title }
9ea1e80c23de509485e3e46101a024174a67a58b
588,806
def filter_results(df, column_name, params): """ Filtered the data based on specific values. Args: df (table): pandas table column_name (string): pandas column names params (list): value names to filters """ filters = df[column_name].isin(params) filtered_results = df[...
0cffece5eda4ebc7c889b157a024cba9eb989657
588,808
def sub(a,b): """ This function finds the difference between two numbers """ return a-b
559306cedca5768714dd4649632a59ef3ca7cd0e
588,813
import re def create_valid_filename(name): """Return a valid filename from a string. See https://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename for what 'valid' means in this context Args: name (str): A name (usually a page or image title) Returns: str: A...
2d095d7e4354a7d3f32872c80ba9c8d93fe94563
588,814