content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
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 shoul...
0cfa60e46694cb28f731c4adb0d912af3bf6bd06
632,609
import torch def rgb_to_rgba(rgb: torch.Tensor, fill: float = 1.0): """ Converts tensor from 4 channels into 3. Alpha layer will be filled with 1 by default, but can also be specified. [... 3 H W] -> [... 4 H W] """ alpha_channel = torch.full_like(rgb[..., :1, :, :], fill_value=fill) retur...
89f7cdaca63194eaa1ec5fd61133448a8db1584a
632,612
def link(href, text): """Generate a link""" return '<a href="' + href + '">' + text + '</a>'
09348acd2eac36dbb1cb769533f11d5816724744
632,616
def getDuplicateElements(lst): """ Return the elements that are duplicated in list """ if lst == None or type(lst) != list: raise ValueError("lst must be a list.") return list(set([x for x in lst if lst.count(x) > 1]))
b7a17120e2394094a0d94cbfa21434f0b66d40e8
632,619
def std(image): """The standard deviation of pixel intensities""" return image.std()
10bb9e0d2df7b5ba1821b5c8e2318ea30dd80249
632,621
def copy_docstring(source): """Decorator function to copy a docstring from a `source` function to a `target` function. The docstring is only copied if a docstring is present in `source`, and if none is present in `target`. Takes inspiration from similar in `matplotlib`. Parameters ---------- ...
0f78b2a04f1e4a082c88e4f89ee525d0d27ed6bc
632,626
from typing import Mapping from typing import Any def update_analytics_params(stream_slice: Mapping[str, Any]) -> Mapping[str, Any]: """ Produces the date range parameters from input stream_slice """ return { # Start date range "dateRange.start.day": stream_slice["dateRange"]["start.da...
ce3f4938dae50cae35f6f83c6e3f6e621e7db0cf
632,627
def _mesh_to_surf_cards(mesh, divs): """Prepares the surface cards for mesh_to_geom.""" surf_cards = "" count = 1 for i, dim in enumerate("xyz"): for div in divs[i]: surf_cards += "{0} p{1} {2}\n".format(count, dim, div) count += 1 return surf_cards
911e14db3e0b5fb6a1f8fec76cae9e6c20be50c0
632,628
from typing import Counter def to_inttuple(bitstr): """Convert from bit string likes '01011' to int tuple likes (0, 1, 0, 1, 1) Args: bitstr (str, Counter, dict): String which is written in "0" or "1". If all keys are bitstr, Counter or dict are also can be converted by this function. ...
d67417120c890ed1bc0f16066cb75d767b0c3e10
632,629
def normalize_component(value): """Normalize component to be in the 0 - 255 range""" if value < 0: return 0 if value > 255: return 255 return value
3e09599ac2407c440f5e01f260dba762371ed195
632,632
def move_matrix(coef,mat_1,mat_2,add_mat): """ Do matrix calculations without messing with numpy. Inputs: coef: coefficient for the current matrix combination centroid: the centroid matrix point: the point by which to alter the centroid Output: a single combined matrix, represe...
c84970db7cfda4fb7ecb94178df6efa4fd139262
632,633
def remove_empty_fields(obj: dict) -> dict: """ Removes empty fields from NetBox objects. This ensures NetBox objects do not return invalid None values in fields. :param obj: A NetBox formatted object """ return {k: v for k, v in obj.items() if v is not None}
984a02de6891bf8a73b9db60ca713db2641080c0
632,635
import logging def dataset_factory(*args, **kwargs): """Factory to get correct dataset class based on name Parameters ---------- dataset_class_name : str Class name Default value "None" Raises ------ NameError Class does not exists Returns ------- Dat...
4374ea73fc3ea301506a00f0bf37937bdb975bc6
632,638
def _popcount(int): """Returns the number of 1 bits in the input.""" count = 0 for bit in range(0, 32): count = count + ((int >> bit) & 1) return count
ebb44b854796a2d764d0269c09bc5bf0670d5cc1
632,639
import torch def try_gpu(i=0): """ Return gpu(i) if exists, otherwise return cpu(). Extracted from https://github.com/d2l-ai/d2l-en/blob/master/d2l/torch.py """ if torch.cuda.device_count() >= i + 1: return torch.device(f'cuda:{i}') return torch.device('cpu')
6873cde1b824cfdea2687d821076bb8d450e49d8
632,640
from typing import Sequence def array_to_sentence_string( array: Sequence[str], connector: str = "and", ) -> str: """Join an array of things into a string by separating with commas and the word "and" for the last one. Args: array: The Array of Strings to join. connector: Word used...
52562b2c30968034ca83e77acdca516ef19909f4
632,642
import io def image_models_to_csv(images: list): """ Given a list of Image models, convert the result to an in-memory CSV. This allows faster transfers to the database via COPY FROM. """ csv_images = io.StringIO() for image in images: row = '\t'.join(list(image.values())) + '\n' ...
dbb7a28e51196c4a2159f62a7afb41218ca44577
632,644
def sort_values(df, columns, order='asc'): """ Sort DataFrame :param df: DataFrame :param columns: name of the columns to sort :param order: asc or desc :return: DataFrame """ ascending = order != 'desc' return df.sort_values(columns, ascending=ascending)
0d9498ca04ac8730548c1e54de0fbb79f6a97889
632,645
def batch_matrix(w, batch_size): """ batch a weight matrix :param w: [M, N] :param batch_size: B :return: [B, M, N] """ return w.unsqueeze(0).expand(batch_size, -1, -1)
c13e3f83cb72b5c4b24166df5ad58697660fc8e4
632,652
def diff_dicts(dicts, ignore=None): """ Given a sequence of dicts, returns common, [difference1, difference2, ...] where `commmon` is a dict containing items in all dicts, and `differenceN` is a dict containing keys unique to the corresponding dict in `dicts`, ignor...
b457894020c0b47e1fdabcd20d9e1af5aec0617d
632,653
def formartweek(week_num): """ 格式化周期数,如1是周日 :param week_num: 数值 :return: 返回中文周 """ week=['周日','周一','周二','周三','周四','周五','周六'] return week[week_num-1]
18b4b18c4ab33384dcaf4dde646894836396e528
632,655
def get_driver_readiness(config: dict) -> str: """Get the code_readiness config setting.""" return config.get("code_readiness", "Release")
43728632dde9e9235019dd06ffbc62ce9cf8679c
632,656
def format_direction(direction): """ Examples -------- >>> format_direction('ra') 'ra' >>> format_direction('el') 'alat' >>> format_direction('az') 'alon' """ lowerdir = direction.lower() if lowerdir == 'el': return 'alat' elif lowerdir == 'az': return...
d961ff38fd68b19a8a5975cb2fe1a80af09d8c56
632,661
def get_soundex(name): """Get the soundex code for the string""" name = name.upper() soundex = "" soundex += name[0] dictionary = {"BFPV": "1", "CGJKQSXZ":"2", "DT":"3", "L":"4", "MN":"5", "R":"6", "AEIOUHWY":"."} for char in name[1:]: for key in dictionary.keys(): if char in...
251bef216c0338bd8b060a079799b9b424faa9ef
632,662
def is_subsequence(subtext: str, text: str) -> bool: """ >>> is_subsequence('pe', 'apple') True >>> is_subsequence('ep', 'apple') False """ if len(subtext) == 0: return True i = 0 for symbol in text: if symbol == subtext[i]: i += 1 if i == len(...
e0edd404af29cbfb1b6a510dcda3316701b369d9
632,667
import posixpath def posix_relpath(path, root): """posix.relpath() that keeps trailing slash.""" out = posixpath.relpath(path, root) if path.endswith('/'): out += '/' return out
38857168397f3e1fd9d26e106abf1582b9145831
632,673
import itertools def combichem(reactant_1_SMILES: list, reactant_2_SMILES: list): """ " Gets all possible combinations between two uneven lists of reactants Args: reactant_1_SMILES (list): List of reactant one smiles reactant_2_SMILES (list): List of reactant two smiles Returns: ...
bc28038dfb67374fdffaaa4b523b2e444d1eeab9
632,674
def get_subsecond_component(frac_seconds, frac_seconds_exponent, subsec_component_exponent, upper_exponent_limit): """Return the number of subseconds from frac_seconds * (10**frac_seconds_exponent) corresponding to subsec_component_exponent that does not exceed upper_exponent_lim...
5922cb41a6a9dcf0874ff353f657de062b8763f8
632,675
def flatten(x): """ Collapse image data from (C, H, W) to (C, H * W) """ return x.view(x.size(0), -1)
0f8f47c249e3bdf8707672c66c68fdc07334a3e3
632,680
def get_device(module): """Returns the device of the module's parameters.""" device = None for param in module.parameters(): if device is None: device = param.device continue if device != param.device: raise ValueError("Parameters are allocated on differen...
bafe31920af4c4a7b2a853193a3924e78b0321a7
632,688
def get_model_constants(model_settings): """ Read constants from model settings file Returns ------- constants : dict dictionary of constants to add to locals for use by expressions in model spec """ return model_settings.get('CONSTANTS', {})
1cc1ab41242a34f06f71bc7ee12404093233228d
632,691
def trim_suffix(s, suffix): """Removes a suffix from a string if it exists""" return s[: -len(suffix)] if s.endswith(suffix) else s
604e8d1dc8e65e9bf80f46c5e3e05e844ecc12f9
632,692
def _HexAddressRegexpFor(android_abi): """Return a regexp matching hexadecimal addresses for a given Android ABI.""" if android_abi in ['x86_64', 'arm64-v8a', 'mips64']: width = 16 else: width = 8 return '[0-9a-f]{%d}' % width
7bd2dca89dcfe95a44e5a35c947fb158d2e97755
632,693
def _fbeta_score(beta, p, r): """Compute the F-beta score for a given precision and recall.""" return (1 + beta ** 2) * (p * r) / ((beta ** 2 * p) + r + 1e-100)
ab76859c8fd199c0882ff2a0f65428d845d0bcdc
632,695
def LineIsComment(line): """Whether this entire line is a comment (and whitespace). Note: This doesn't handle inline comments like: [ # Blah blah. But we discourage those in general, so shouldn't be a problem. """ return line.lstrip().startswith('#')
4ff54a136b59541d95d33fd24c4edb703a7c6bcb
632,699
def _attributeLinesToDict(attributeLines): """Converts a list of obo 'Term' lines to a dictionary. :param attributeLines: a list of obo 'Term' lines. Each line contains a key and a value part which are separated by a ':'. :return: a dictionary containing the attributes of an obo 'Term' entry. ...
ee73851222e0af97654d4db6853226969bd59c01
632,700
def remove_letter(letter, string): """Removes all occurrences of a given letter from a string.""" string_without_letter = string.replace(letter, '') return string_without_letter
175b29138a534e45e413da58f4b5cca5dbfdf425
632,709
def dummy_training_data(dummy_dataset): """Returns training data from `dummy_dataset`. """ training_data = {'x_train': [dummy_dataset.idx_seq['train']['word'], dummy_dataset.idx_seq['train']['char']], 'x_valid': None, 'x_test': None,...
88aadbd07b26293f831c8c1fed75d1982305c906
632,710
def get_role(username, role_db): """Take username from user and return its role. """ return role_db.query.filter(role_db.username == username).first()
2a6ab43fad76d8b41b0d20730bf03b2699573709
632,714
def remove_empty_parameters(data): """Accepts a dictionary and returns a dict with only the key, values where the values are not None.""" return {key: value for key, value in data.items() if value is not None}
4448556ffd3fe20a651986396c6b724ce6157f4f
632,716
def find_sponsor(sponsorid, sponsor_dictionary): """ Given a sponsorid, find the org with that sponsor. Return True and URI if found. Return false and None if not found """ try: uri = sponsor_dictionary[sponsorid] found = True except: uri = None found = False ...
390b1473c577f788c15394f0e4ce9d0ab2478c18
632,723
def qmf(h): """Returns the quadrature mirror filter of a given filter""" g = h[::-1] g = g.at[1::2].set(-g[1::2]) return g
03ccf8078a192ff191cb0228d170426fbe53b7f1
632,730
def opacity_button(data_ix, mean_ix): """Configures opacity drop down menu. Args: data_ix: iterable with data index at 1 and mean index at 0. mean_ix: iterable with data index at 0 and mean index at 1. Returns: opacity_menu: config dict for layout """ reset_opac = [1] * le...
6363d6c445b38acb85f10c73ba260a48156dc401
632,732
def _format_block_id(chunk_num): # type: (int) -> str """Create a block id given a block (chunk) number :param int chunk_num: chunk number :rtype: str :return: block id """ return '{0:08d}'.format(chunk_num)
84599f595974c2c8528445cfa89c175a47f19337
632,734
from typing import Callable def similarize_distance(distance_measure: Callable) -> Callable: """ Takes a distance measure and converts it into a information_density measure. Args: distance_measure: The distance measure to be converted into information_density measure. Returns: The in...
f35a81e2cbc011f2559e0eb7e25cc45400a11fc0
632,741
def mat_tris(mesh): """Returns dict: mat_name -> list_of_triangle_indices""" m_ps = {} idx_tri = 0 for p in mesh.polygons: mat = mesh.materials[p.material_index] if mesh.materials else None mat_name = mat.name if mat else "__BDX_DEFAULT" if not mat_name in m_ps: m_p...
28bafb86c6127567eed78a08ba69d9fe2cb6d777
632,743
import re def parse_range(range_str): """ Generates an object of type range for the specified range. Parameters ---------- range_str : str A string indicating a range. Corresponds to either of the following formats. * '[0-9]+' * '[0-9]+-[0-9]+' Returns --...
c6cff389a80ff05af5b409194476dadadfe92358
632,749
def getsize(data): """ return smallest possible integer size for the given array """ maxdata = max(data) assert maxdata < 2**32 if maxdata < 256: return 1 elif maxdata < 65536: return 2 else: return 4
530f58a3ab53ad163b9624c5a1a90d7932a7ed9b
632,751
import torch def sequence_mask(lengths, max_seq_length=None, dtype=torch.bool): """ Returns a mask tensor representing the first N positions of each cell. lengths: integer tensor, all its values <= maxlen. max_seq_length: scalar integer tensor, size of last dimension of returned tensor. Default is the ma...
2f6261c37c2a3ccc32d615e314e3251333f258c9
632,756
import typing def canonicalize_headers( headers: typing.Union[typing.Dict[str, str], typing.List[typing.Tuple[str, str]]] ) -> typing.Dict[str, typing.List[str]]: """ HTTP headers are case-insensitive. Join equivalent headers together. """ if isinstance(headers, dict): headers = [ ...
32d6a7218e8f56c97e132f89ed5e2084b1d9fb9f
632,759
def weight_path(spec_path, element_path): """Determine the weighting number for a matchingRule path spec applied to an actual element path from a response body. Both paths are passed in as lists which represent the paths split per split_path() In spec version 2 paths should always start with ['$', 'bo...
e788062422db9c247c94cac1ca367774c318b227
632,763
import platform import struct def _ioc_encode(direction, number, structure): """ ioctl command encoding helper function Calculates the appropriate spidev ioctl op argument given the direction, command number, and argument structure in python's struct.pack format. Returns a tuple of the calculated op and the...
b3f8ac548f767cdb86fbcd0e9819a2d693d24bc9
632,764
def pluralize(text: str, amount: int) -> str: """'Pluralizes' a string if a given amount is plural. Example: pluralize('egg', 2) -> 'eggs' pluralize('python', 1) -> """ return text + 's' if amount > 1 else text
6b2c758e769c97dd8ed5f16fd35ea7bbe93ad0e5
632,765
def remove_rows_matching(df, column, match): """ Return a ``DataFrame`` with rows where `column` values match `match` are removed. The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared to `match`, and those rows that match are removed from the DataFrame. :param ...
47bf68cb638329d3632670fbad84d0acd8ce8ef5
632,770
def export_network(name: str, batch_size: int, *args, **kwargs) -> str: """ Exports a network by name and returns the path to the output file. @param name Network name (options: simple_cnn, deep_mnist, resnet, wide_resnet). @param batch_size Minibatch size to use @param args Other arguments...
5a0fe120f5c0cf0388b1b857d4a0a86156e22586
632,773
import torch def heaviside(data): """ A `heaviside step function <https://en.wikipedia.org/wiki/Heaviside_step_function>`_ that truncates numbers <= 0 to 0 and everything else to 1. """ return torch.where( data <= torch.zeros_like(data), torch.zeros_like(data), torch.ones_l...
ee30354de0ccb40dc9b2b9cf9559328891ab7f4e
632,775
def expand_cli_args(args): """ Expand a list of possibly comma separated arguments, removing duplicates. :param args: The list of arguments to expand. :return: The set of unique arguments. """ items = set() for arg in args: # "a.jpg,b.png" for arg_ in [n.strip() for n in arg.split(...
531e005fffd6bf0d9f7607faac17560c94be656a
632,776
def tx_capacity_cost_rule(mod, g, p): """ Capacity cost for new builds in each period (sum over all vintages operational in current period). """ return sum( mod.TxNewLin_Build_MW[g, v] * mod.tx_new_lin_annualized_real_cost_per_mw_yr[g, v] for (gen, v) in mod.TX_NEW_LIN_VNTS_O...
b973293d05f4113d215a545a3815b3d825b75e22
632,785
from typing import Tuple def get_int_bounds(type_str: str) -> Tuple[int, int]: """Returns the lower and upper bound for an integer type.""" size = int(type_str.strip("uint") or 256) if size < 8 or size > 256 or size % 8: raise ValueError(f"Invalid type: {type_str}") if type_str.startswith("u")...
a749ae63c278e74dac818dc387618d5003326d53
632,786
def tf_to_10(x): """ Maps true/false to 1/0 """ if x == True: return 1 elif x == False: return 0 return x
8cec080002f6c6c41ba64a40fcea324658df1701
632,787
def _is_unpoly(self) -> bool: """Request is triggered by Unpoly""" return ( 'HTTP_X_UP_VERSION' in self.META or 'HTTP_X_UP_MODE' in self.META or 'HTTP_X_UP_TARGET' in self.META or 'HTTP_X_UP_VALIDATE' in self.META )
b203678a4fe0cadef120c8cb259d9287418e54d8
632,789
def get_directed_and_undirected_edges(adjacency_matrix): """ Given an adjacency matrix, which contains both directed and undirected edges, this function returns two adjancy matrices containing directed and undirected edges separately. Useful for plotting the difference causal graph. Parameters ...
01ba23d40ddf0866332163583f9aa16cc6bd95d9
632,790
import itertools def sort_and_groupby(l, key=None): """Returns a generator of (key, list), sorting and grouping list by key.""" l.sort(key=key) return ((k, list(g)) for k, g in itertools.groupby(l, key))
54640d9d6bd7828ac938298db3d0328d2b70f895
632,793
def objVal(c, v, s, l, Q, order, demand, objType): """ calculate the objective value given the sample probability of each demand :param c: purchase cost :param v: salvage value :param s: selling price :param l: cost of lost sale :param Q: true distribution of demand scenarios :param order: ...
740740c7ca4f6179a6fda94bf7b5fa86054606a1
632,794
def is_query(parsed_sql): """ Determine if the input SQL statement is a query. Parameters ---------- parsed_sql: sqlparse.sql.Statement SQL statement that has been parsed with ``sqlparse.parse()``. Returns ------- bool True if statement type is SELECT and the second non...
315baa60fa49a612c1f828135b3eab9c57e6c5ef
632,795
def BitStringToByteString(bs): """Convert a pyasn1.type.univ.BitString object to a string of bytes.""" def BitsToInt(bits): return sum(v * (2 ** (7 - j)) for j, v in enumerate(bits)) return bytes( bytearray([BitsToInt(bs[i:i + 8]) for i in range(0, len(bs), 8)]))
2434b9546fb3227266c64a1ac8e5171d42f38001
632,799
def getTransientStates(m): """Returns a list with the indices of the non-absorbing states of the matrix m""" t= list(range(len(m))) for r in range(len(m)): if(sum(m[r])==0): t.remove(r) return t
6e824bc1815bd2e4682b49daa3c1aaaddff4544b
632,802
def lerp(a, b, t): """ blend the value from start to end based on the weight :param a: start value :type a: float :param b: end value :type b: float :param t: the weight :type t: float :return: the value in between :rtype: float """ return a * (1 - t) + b * t
127ff551f81423c299e4434841dd141d449d57d1
632,806
def process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (dictionary) raw structured data to process Returns: List of dictionaries. Structured data with the following schema: [ { "line": integer, "c...
55725a2475190b393de90c2ec5acbcf51e63af15
632,812
def format_slack_message(table_name, metric, avg_time, increase, stddev, stddev_old): """ Formats slack message using slack emojis. :param table_name: BigQuery table name that was analysed. :param metric: string with metric name. :param avg_time: calculated average time for recent data of given metric....
67a188c48eb10790b5f36de3ffa914c5ee195e87
632,814
def comp_radius(self): """Compute the radius of the two circle that contains all the ventilation ducts Parameters ---------- self : VentilationPolar A VentilationPolar object Returns ------- (Rmin, Rmax): tuple Tuple of circle radius [m] """ self.check() ...
1eb79db6409bf76db3e5c91d9c4d68b02d0a62fd
632,815
def frequency_table(text, k): """returns frequency table for k_mers of length k in the text""" d = {} i = 0 while i <= len(text)-k: pattern = text[i:i+k] d[pattern] = d.get(pattern, 0) + 1 i = i+1 return d
2e95d338a716345504245e52f377691c1c1d1b40
632,816
def process_data(employee_list): """ Takes the employee list built by read_employees() and does a count of the Department data """ department_list = [] for employee_data in employee_list: department_list.append(employee_data['Department']) department_data = {} for department_name ...
a7196226729a349d465e17334de66dadce42a6d4
632,818
def is_tribe(parcels): """ Dummy for tribal areas. """ tribal_mpas = ['AK', 'FM', 'GR', 'SA', 'SN', 'TC'] return parcels['mpa'].isin(tribal_mpas).astype(int)
bc8074a881e196d2c5c8134a22da9eec1f2cf64d
632,821
from typing import List import textwrap def generate_build_file_contents(name: str, dependencies: List[str]) -> str: """Generate a BUILD file for an unzipped Wheel Args: name: the target name of the py_library dependencies: a list of Bazel labels pointing to dependencies of the library R...
6714a8e214eb4d89614702643f5d900d864cbe53
632,825
def get_list_of_active_skills(utterances): """ Extract list of active skills names Args: utterances: utterances, the first one is user's reply Returns: list of string skill names """ result = [] for uttr in utterances: if "active_skill" in uttr: result....
129902a69a387fbf4601737dee67db28d8cf856a
632,827
import math def switchSymmetry(mlist, upperToLower=True): """ A symmetric 2-d NxN array can be stored in memory as a list of (N*(N+1)/2) numbers. The order depends on whether the upper-diagonal or lower-diagonal portion of the array is being stored. This method switches between the two representation...
f749690f3b2e5144833771d9cd1bd5481c08b321
632,831
def get_and_update_or_create(model, filter_params, defaults): """ get or create with default values applied to existing instances {model}.objects.get_or_create(*{filter_params}, defaults={defaults}) Arguments: model {django.db.models.Model} -- The model the queryset gets applied to fil...
3bea14911f6a690606813aa29caa8a463918564a
632,838
def byte_to_int16(lsb, msb): """ Converts two bytes (lsb, msb) to an int16 :param lsb: Least significant bit :param msb: Most significant bit :return: the 16 bit integer from the two bytes """ return (msb << 8) | lsb
483a7205e57d615bf0122b437a5c000d9e859620
632,842
def generate_number_lines(number_of_lines=6, start=0, end=20): """ Generates number lines as a tool for practicing mathematics such as addition or subtraction. :param number_of_lines: Specify the number of lines to have on the page :param start: start value for the number line as an integer :param e...
173aae03162e5d5717078e872051bc11e1e56057
632,848
import re def get_indentation(keyword, search_str): """ In a multi-line string with new line characters, find the indentation of a search string. Currently assumes that spaces are used for indentation and the search string directly follows the indent. Args: keyword (string): The keyword t...
1e645bbb0d23b39d0e4a2f1545c80fa458a19683
632,849
def generate_importer_base_name(dependent_task_name: str, input_name: str) -> str: """Generates the base name of an importer node. The base name is formed by connecting the dependent task name and the input artifact name. It's used to form task name, component ref, and executor la...
4839b99d38f6073275e1e6091b602e6d61f91ce6
632,855
def smart_split(line): """ split string like: "C C 0.0033 0.0016 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'" in the list like: ['C', 'C', '0.0033', '0.0016', 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'] """ flag_in = False l_val, val = [], [] for hh in line.s...
7249b6598f93c93ba17f668e5d0554ebae31a100
632,857
import random def method_1(num_chars: int): """ Hand Implemented Method to generate a random password of num_chars long Args: num_chars (int): Number of Characters the password will be Returns: string: The generated password """ lower = "abcdefghijklmnopqrstuvwxyz" up...
a13d317eed5e85957b173ca07df190a8038f05d5
632,858
def clip_boxes_opr(boxes, im_info): """ Clip the boxes into the image region.""" w = im_info[1] - 1 h = im_info[0] - 1 boxes[:, 0::4] = boxes[:, 0::4].clamp(min=0, max=w) boxes[:, 1::4] = boxes[:, 1::4].clamp(min=0, max=h) boxes[:, 2::4] = boxes[:, 2::4].clamp(min=0, max=w) boxes[:, 3::4] = ...
dd8161e0265778b60473ab3edef0c76c866e7f0b
632,860
def parse_mappings(mapping_list): """Parse mapping devices list parses mapping device list in the form: physnet:pci_dev_1,pci_dev_2 or function:pci_dev_1,pci_dev_2 :param mapping_list: list of string pairs in "key:value" format the key part represents the physnet or function nam...
8be2105255bad7e7b9a1923c0ec92677753fd5e6
632,861
import math def part2(data): """Return least fuel to move all submarines to same position. Fuel to go from current to desired position is 1 + 2 + ... + abs(d - c). """ numbers = list(map(int, data.split(','))) # puzzle has 100s of numbers in a range of 1000, so brute-force is OK min_fuel = ma...
95c07b37171c2e71258cdb3f02ff6e726cf999c1
632,865
import math def compute_distance(loc1, loc2): """ params: - loc1 (location of start vertex) - loc2 (location of destination vertex) output: euclidean distance between the two vertices """ distance = math.sqrt(math.pow((loc1[0]-loc2[0]),2) + math.pow((loc1[1]-loc2[1]),2)) ...
f624c2967d78162d3f65f046f6e938d813009eb9
632,866
def extract_document_size(block_data): """ Args: block_data(str): A data block with an entanglement header Returns: int: The size of the original document """ if not block_data or not isinstance(block_data, str): raise ValueError("argument block_data must be a non-empty seque...
bbb056923d53ce852612ee50af49db2e28ad4b3a
632,867
import requests def aggregate_urns(urnlist): """Sum up word frequencies across urns""" if isinstance(urnlist[0], list): urnlist = [u[0] for u in urnlist] r = requests.post("https://api.nb.no/ngram/book_aggregates", json={'urns':urnlist}) return r.json()
632dcc1bf912546322dde079dc77d6ef638e686b
632,868
def create_dict(keys_list): """ Creates a dictionary from a given list of keys """ dict_ = {} for key_ in keys_list: dict_[key_] = [] return dict_
33c4d0fbf389d4b968e68ad76406a169010b3db6
632,870
def get_app_instances_ids(instances): """ Accepts a dictionary of id: AppInstance and returns a set of keys """ return set(instances.keys())
6dde1bd996782b8a2ae897cb10851080c0ee4a22
632,871
def layer_output(model, layer_name=None): """Output tensor of a specific layer in a model. """ conv_index = -1 for i in range(len(model.layers) - 1, -1, -1): layer = model.layers[i] if layer_name in layer.name: conv_index = i break if conv_index < 0: print('Error: could not find the interested layer...
e3f693d8d5759f1ec1d6aab84e5cc85e9764cebc
632,873
def unpack_lemma_batch(batch, use_cuda): """ Unpack a batch from the data loader. """ if use_cuda: inputs = [b.cuda() if b is not None else None for b in batch[:6]] else: inputs = [b if b is not None else None for b in batch[:6]] orig_idx = batch[6] return inputs, orig_idx
c0d95e2dbccfefaaf0468e106fd4fc7ed753d444
632,881
def fillNaToMode(data): """Iterates through NA values and changes them to the mode Parameters: dataset (pd.Dataset): Both datasets Returns: data (pd.Dataset) : Dataset with any NA values in the columns listed changed to the mode """ columns = ["MSZoning", "Functional", "Electrical", "Kitch...
6d8ec04da66b7463e69fdda3ff6665b3ce2bbde8
632,886
def _csize(counter): """ Computes the size of (number of elements in) a given Counter. Parameters ---------- counter : Counter The counter to get the size of. Returns ------- int """ return len(list(counter.elements()))
7a2857011ded59790e3f5bfd40b6230f2dfc1324
632,888
def list_to_hp(li: list) -> str: """ Converts a list (used for toolz get_in, assoc_in, update_in) to a hp (hierarchy path). Input: ['root', 0, 'thing',2] Output: /root/0/thing/2 """ assert isinstance(li, list), "The input type for li must be a list." assert "/" not in li, "Can't have ...
02c50a4aad7bfe5a3b403b6805f729b824d8e43b
632,890
def l2s(x): """ [1,2,3,4,5,6,7,8] -> '1,2,...,7,8' """ if len(x)>5: x = x[:2] + ['...'] + x[-2:] y = [str(z) for z in x] # convert to list of strings, eg if list of int y = ",".join(y) return y
a7d0d5147912c6d671ee3475591d7207066a0a1a
632,891
def count_word_occurrence_in_string(text, word): """ Counts how often word appears in text. Example: if text is "one two one two three four" and word is "one", then this function returns 2 """ words = text.split() return words.count(word)
0a0b27b2f28c8b939423276e2509480462a7702f
632,892
import ipaddress import re def host_valid(host): """Return True if hostname or IP address is valid.""" try: if ipaddress.ip_address(host).version == (4 or 6): return True except ValueError: disallowed = re.compile(r"[^a-zA-Z\d\-]") return all(x and not disallowed.search...
60591d9bfd5b095ed947abaaee18fbc891d4d47c
632,897