content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def create_wiki_url(page: str) -> str: """Creates canonical URL to `page` on wiki Args: page (str): subject page Returns: str: canonical URL """ return f"https://genshin-impact.fandom.com{page}"
4dc7e9eeb77e0345ec4f066627f7c6664143d65e
666,803
import itertools def get_flattened_subclasses(cls): """ Returns all the given subclasses and their subclasses recursively for the given class :param cls: Class to check :type cls: Type :return: Flattened list of subclasses and their subclasses """ classes = cls.__subclasses__() return ...
c9b0eef89f499f34c7e6ffa02ee3267657d1fff7
666,804
def accuracy(labels, scores, threshold=0.5): """ Computes accuracy from scores and labels. Assumes binary classification. """ return ((scores >= threshold) == labels).mean()
e0603cfea4ce69a57e116ac62e46efb1aed133a9
666,805
def deal_hands(deck, start): """ Deal hands from the deck starting at index i """ return ( [deck[start], deck[start + 2]], [deck[start + 1], deck[start + 3]], )
53c3c32eb8188d012cea2d9046c64f68a5cd28a8
666,806
def set_training_mode_for_dropout(net, training=True): """Set Dropout mode to train or eval.""" for m in net.modules(): # print(m.__class__.__name__) if m.__class__.__name__.startswith('Dropout'): if training==True: m.train() else: m.eval()...
4a0f7b9a2442032fafd9d597efe0e1463344c3ff
666,811
import pickle def load_object(filename): """ Load python object ------------------------------------------- Inputs: filename: name of pickle file I want to load. Example: 'dump_file.pkl' ------------------------------------------- Output: loaded object """ with open(filename, "...
700012eca7175992eeac07d93d1ebfd307f5f4ae
666,818
def mean_dim(tensor, dim=None, keepdims=False): """Take the mean along multiple dimensions. Args: tensor (torch.Tensor): Tensor of values to average. dim (list): List of dimensions along which to take the mean. keepdims (bool): Keep dimensions rather than squeezing. Returns: ...
d47a131ecff97ff597ea19f310c1330a6e426122
666,820
def humanize_time(secs): """ Takes *secs* and returns a nicely formatted string """ mins, secs = divmod(secs, 60) hours, mins = divmod(mins, 60) return "%02d:%02d:%02d" % (hours, mins, secs)
8b450b2add2ce4da5432e52fee8ac9ff98e2b0e5
666,823
def get_first_and_last_names(user): """ Returns a the most reliable values we have for a user's first and last name based on what they have entered for their legal address and profile. Args: user (django.contrib.auth.models.User): Returns: (str or None, str or None): A tuple contai...
6968b7b9f472a85930f661d6472d503c7045c969
666,825
def _reorder(xs, indexes): """Reorder list xs by indexes""" if not len(indexes) == len(xs): raise ValueError("xs and indexes must be the same size") ys = [None] * len(xs) for i, j in enumerate(indexes): ys[j] = xs[i] return ys
1106354917f3358971fe532f8b1fc5163a10b0cd
666,827
def error_applookuprecord_unknown(value:str) -> str: """ Return an error message for a unknown record identifier. Used when setting the field of an applookup control to a record identifier that can't be found in the target app. """ return f"Record with id {value!r} unknown."
47872e250a7d03c97cad47c00d6d46e3fdabc8c1
666,829
def digest_repr(obj): """ Return a short digest of a possibly deeply nested (JSON) object. """ if isinstance(obj, (tuple, list, set, dict)): def nesting(collection): "Helper" if isinstance(collection, dict): collection = collection.values() if isin...
5d08c6a1683e659e44297783de1c59e8e291e2f9
666,830
def collection_attribs(col): """Returns a list of the unique non-subscripted attributes of items in `col`.""" attribs = (attrib for item in col for attrib in item.__dict__ if attrib[0] != '_') return list(set(attribs))
dbbd1c09e8dba064efa0ac6534cfd4348875bf6c
666,835
def f_to_c(f): """ Convert fahrenheit to celcius """ return (f - 32.0) / 1.8
12df6accdfd901e35c3ddd4086b98f6d0cce79ef
666,836
import math def e_dist(p1,p2): """ Takes two points and returns the euclidian distance """ x1,y1=p1 x2,y2=p2 distance = math.sqrt((x1-x2)**2+(y1-y2)**2) return int(distance)
6d98e613d5d367d47dfbd123cc424331e768b921
666,838
import json def serialize(d): """ Serialize a dict as a json string. To be used in client requests """ return json.dumps(d)
63be596eb576ba6f844e8a82baa3cac6863e0738
666,839
def power(n): """Return 2 to the n'th power""" return 2 ** n
94c50cc9694c5b66fc8dc16fc7e1057d78121ba3
666,840
def flipBit(int_type, offset): """Flips the bit at position offset in the integer int_type.""" mask = 1 << offset return(int_type ^ mask)
f94d8b6eb6d9053a224b9cfc054b3a590af097d3
666,842
def expand_pv(pv): """ Returns the LCS Process Variable in full syntax AADDDNNNCMM as a string where AA is two character area, DD is device type, NNN is device number, C is channel type, MM is channel number Returns partial PVs when input string is incomplete. ...
f41dc8cf20dd55ed1cb0103c42ce67301ec93372
666,846
import random def generate_equations(allowed_operators, dataset_size, min_value, max_value): """Generates pairs of equations and solutions to them. Each equation has a form of two integers with an operator in between. Each solution is an integer with the result of the operaion. allowed_ope...
7a098aaf4fbfc55840ff21d946d474db54c07c1c
666,847
def parsedFile(file): """Take a parsed file and return the list Of Chords and Interval Vectors. The file was already parsed possibly from corpus. Then with chordify and PC-Set we compute a list of PC-chords and Interval Vectors. """ mChords = file.chordify() chordList = [] chordVectors = []...
0f4b6424429c52aa53f1271f478693f5607b0218
666,849
def grab_job_links(soup): """ Grab all non-sponsored job posting links from a Indeed search result page using the given soup object Parameters: soup: the soup object corresponding to a search result page e.g. https://ca.indeed.com/jobs?q=data+scientist&l=Toronto&start=20 ...
159b3d768266900446bc17326aeb41bfd048b267
666,852
def gene2bin(parameters, gene, geneType): """ geneBin = gene2bin(parameters, gene, geneType) Turns genes into the binary-string form gene: integer geneType: string geneBin: string, of all ones and zeros >>> geneType = 'repn' >>> parameters = {'genetics': {geneT...
bf919c9da48d162621e73e593308d3e31bc19368
666,853
def unique_items(seq): """A function that returns all unique items of a list in an order-preserving way""" id_fn = lambda x: x seen_items = {} result = [] for item in seq: marker = id_fn(item) if marker in seen_items: continue seen_items[marker] = 1 result.append(item...
b0e04c1f46e9758b2f1582c7fa47dfc72d26293c
666,854
def checkComp(parts, ind, wmap): """ Finds longest compound terms from list of tokens starting at an index. :param parts: List of tokens :param ind: Index of the current token :param wmap: Dictionary mapping token to lemma :returns: Longest compound term, index after the longest compound ter...
07507c4b8b3f0869047920d2b2d74b4b12dca7fa
666,855
def rgb_to_hex(rgb): """Returns the hex color code for the rgb tuple.""" hexcodes = ("%02x" % int(v * 255) for v in rgb) return "#%s" % "".join(hexcodes)
b4f1b0e5491546732fe29e020320c7acddca2619
666,856
def _num_frame_valid(nsp_src, nsp_win, len_hop): """Computes the number of frames with 'valid' setting""" return (nsp_src - (nsp_win - len_hop)) // len_hop
eeaa97c550018125d0e07c0a4d3c103f83f427b7
666,859
def slice(ds, idx_start, idx_stop): """Retrieve a slice of the dataset.""" if type(ds) != tuple: raise TypeError("'ds' isn't a tuple") if len(ds) != 2: raise ValueError("'ds' isn't a 2-element tuple") if idx_stop < idx_start: raise RuntimeError("'idx_start' value of the range has a greater value then 'i...
b90ac1eb5ffcd380fedbd6aa813614a2034efa9f
666,865
import hashlib def keyhash(string): """Hash the string using sha-1 and output a hex digest. Helpful for anonymizing known_mods.""" return hashlib.sha1(string.encode('utf-8')).hexdigest()
0e32320597d273f509cc3ab69980196129651586
666,869
def remove_query_string(url): """ Removes query string from a url :param url: string with a url :return: clean base url """ if not isinstance(url, str): raise TypeError('Argument must be a string') return url.split('?')[0]
3aca0acfb898b5bd23535e128c0a487aca1220df
666,870
def file_mode_converter(num: int): """ 十进制mode 转 user:group:other mode 0444 <--> 292 444 --> 100 100 100(2) --> 292(10) :param num: 十进制数字 :return: ser:group:other mode 格式:0ugo """ # 数字转二进制字符串 user = (num & 0b111000000) >> 6 group = (num & 0b111000) >> 3 other = n...
266971fbef2655428cba13fa8f32f92903b5f899
666,871
def listify(i): """ Iterable to list. """ return list(i)
4500b0488d99bfc37a376edbbd29a57e7b312c8b
666,872
def aztec_xihuitl_date(month, day): """Return an Aztec xihuitl date data structure.""" return [month, day]
ad12ae0222aaef89accf1dc3c3af55bff0cf6c93
666,874
def intersect_bounds( bbox0: tuple[float, float, float, float], bbox1: tuple[float, float, float, float] ) -> tuple[float, float, float, float]: """Get the intersection in w s e n Parameters: bbox0: bounding coordinates bbox1: bounding coordinates Returns: intersection coor...
a0318f72edca084c800999c9393203364de5d791
666,875
def bar(self, *args, **kwargs): """ Make a bar plot Wraps matplotlib bar() See plot documentation in matplotlib for accepted keyword arguments. """ if len(self.dims) > 1: raise NotImplementedError("plot can only be called up to one-dimensional array.") return self._plot1D('bar',*args, *...
2cb12d50e5c48e6d2b06c4947a1bea5e645f0e99
666,876
def auth_path(index, height): """Return the authentication path for a leaf at the given index. Keyword arguments: index -- the leaf's index, in range [0, 2^height - 1] height -- the height of the binary hash tree Returns: The authentication path of the leaf at the given index as a list of nod...
ee17ebcae1bca3f89d72c545989c77c3e41d1c3f
666,877
def scene_to_dict(scene, use_base64=False): """ Export a Scene object as a dict. Parameters ------------- scene : trimesh.Scene Scene object to be exported Returns ------------- as_dict : dict Scene as a dict """ # save some basic data about the scene export = ...
b0bdda831ad0be259268c0c17eef83ee0eb6a0cc
666,878
def get_environment(hostname): """Get whether dev or qa environment from Keeper server hostname hostname(str): The hostname component of the Keeper server URL Returns one of 'DEV', 'QA', or None """ environment = None if hostname: if hostname.startswith('dev.'): environment ...
b5965347cd60f8a49b038ba6558cd1d2e3a24446
666,879
def _import_string(names): """return a list of (name, asname) formatted as a string""" _names = [] for name, asname in names: if asname is not None: _names.append(f"{name} as {asname}") else: _names.append(name) return ", ".join(_names)
f2081ba174e7383dbf2c88e66e7905e3f6e42a50
666,880
def _eff_2_nom(effective_rate, piy): """Convert an effective rate to a nominal rate. :effective_rate: effective rate to be changed :piy: number of periods in a year for the effective rate """ return effective_rate * piy
06663b1a49934e308bd44efe6055d416dcb4d59e
666,887
def is_fasta_label(x): """Checks if x looks like a FASTA label line.""" return x.startswith(">")
43f45397dfb10d67d2bc8517ab07c2fb09067f06
666,888
def keep_firstn(lst, n): """Keep only the first n elems in a list.""" if len(lst) <= n: return lst else: return lst[:n]
02035b28223d07857173b337fa142816e0a4bb17
666,891
import torch def combine_obj_pixels(obj_pix, obj_dim): """Combine obj-split pixels into a single image. Args: obj_pix: B, ..., Nobj, ..., C, H, W obj_dim: The dimension to reduce over -- which corresponds to objs Returns B, ..., ..., C, H, W """ if obj_pix is None: ...
c0a47d2cf11609b7a905de9d88eb048cabb30216
666,892
def _svg_convert_size(size): """ Convert svg size to the px version :param size: String with the size """ # https://www.w3.org/TR/SVG/coords.html#Units conversion_table = { "pt": 1.25, "pc": 15, "mm": 3.543307, "cm": 35.43307, "in": 90 } if len(si...
6c3a1e70c4bc2b342bf6f09e6e9f9f5a6b890d30
666,893
import re def parse_ticket_links(raw_links): # type: (str) -> list """ Parses the link IDs from the ticket link response An example to an expected 'raw_links' is: "RT/4.4.4 200 Ok id: ticket/68315/links Members: some-url.com/ticket/65461, some-url.com/ticket/65462, ...
4e5fe0bb6a6521f341cfd7556280373884af47af
666,899
def calculate_dbot_score(score: int) -> int: """Transforms cyber risk score (reputation) from SOCRadar API to DBot Score and using threshold. Args: score: Cyber risk score (reputation) from SOCRadar API Returns: Score representation in DBot """ return_score = 0 # Malicious ...
3bea0dee5376dc72e7303d652a4ffb1eba70386e
666,903
def tolerance_tests_to_report(test_list_instance): """return tolerance tests to be reported for this test_list_instance""" return test_list_instance.tolerance_tests()
1398add29a3c09702b4f581878c03895124cc871
666,908
def parse_like_term(term): """ Parse search term into (operation, term) tuple. Recognizes operators in the beginning of the search term. * = case insensitive (can precede other operators) ^ = starts with = = exact :param term: Search term """ cas...
9980d54125f1e11930526700951772fdfcddc44d
666,909
import re def _get_first_sentence(s): """ Get the first sentence from a string and remove any carriage returns. """ x = re.match(".*?\S\.\s", s) if x is not None: s = x.group(0) return s.replace('\n', ' ')
d95d52e003e9b9560d1a8b9d0b081bb2fcbc1e7f
666,912
def get_binding_data_vars(ds, coord, as_names=False): """Get the data_vars that have this coordinate Parameters ---------- ds: xarray.Dataset coord_name: str Return ------ list List of data_var names """ if not isinstance(coord, str): coord = coord.name out ...
8d6a7aef3af0b01028b315efa4995eae31c46e0a
666,913
import calendar def leap_years_between(year1: int, year2: int) -> int: """ determine how many leap years there will be between the years year1 and year2 inclusive >>> leap_years_between(2018,2020) 1 >>> leap_years_between(2017,2022) 1 >>> leap_years_between(2000,2020) 6 """ retur...
a608e8013b0d534e5490b1681e0549ece76505f0
666,916
def clamp(x, _min, _max): """Clamp a value between a minimum and a maximum""" return min(_max, max(_min, x))
fe9979a329cb130ebc9ecb7b812882770c962652
666,921
def cytoscape_element_from_client(client): """Generates a cytoscape element from a Client proto. Args: client: A Client proto. Returns: A cytoscape element dictionary with values derived from the proto. """ client_element = { "data": { "id": client.name, ...
871c48223abb08f10108d59167f110d8ae9a3183
666,922
def kv_parser(inp): """ Converts a url-encoded string to a dictionary object. """ return {obj[0]:obj[1] for obj in (obj.split('=') for obj in inp.split('&')) if len(obj) == 2}
49ea6721c31e5db0367a3e822b4309fd91f459c1
666,925
def postorder_optimised(preorder: list, length: int) -> list: """ Use a static index pre_index to iterate over the list items one by one when the loop returns, store the root item in list. Time Complexity: O(n) Space Complexity: O(n) """ min_val, max_val, pre_index = -1000_000, 1000_000, 0 ...
f729fc2f4b0aa3816841850426a74581c8ca6b8c
666,926
import string import random def rndstr(size=16): """ Returns a string of random ascii characters or digits :param size: The length of the string :return: string """ _basech = string.ascii_letters + string.digits return "".join([random.choice(_basech) for _ in range(size)])
af168eeaa354d7acf2443774d5764f00cffeb780
666,929
import re def clean_html(raw_html): """ Utility function for replace HTML tags from string. """ ltgt = re.compile('<.*?>') whitespace = re.compile('\s+') clean_text = whitespace.sub(" ", ltgt.sub("", raw_html)).replace("\n", " ") return clean_text
ed3dca2eacd3adca321ab7480a72540cdd546e57
666,930
import json def load_json(file_name_template, record_id): """Helper function to return JSON data saved to an external file. file_name_template -- Template for building file name. Expected to contain a string substitution element whose value is specified by the record_id parameter. e.g. 'json/s...
8feddf064343dee51dd9f952c77a32d9d904c2b3
666,931
import requests def get_tag_list_from_docker_hub(repo, **kwargs): """Retrieves the list of tags from a docker repository on Docker Hub.""" docker_token_url = "https://auth.docker.io/token" docker_token_url += "?service=registry.docker.io&scope=repository:{}:pull" def get_token_from_docker_hub(repo, *...
3a5b6baef1bc5452de6a0bdc352fa3ce282db7c1
666,933
from typing import List from typing import Tuple def filter_multiple_pronunications( lexicon: List[Tuple[str, List[str]]] ) -> List[Tuple[str, List[str]]]: """Remove multiple pronunciations of words from a lexicon. If a word has more than one pronunciation in the lexicon, only the first one is kept, ...
faa106c3b16e7efbcd49471714260cb734f72385
666,935
import copy def get_category_obj(data, category_name): """Extract obj with `name` == `category_name` from `data`.""" cats = copy.copy(data) while(cats): cat = cats.pop() if cat['name'] == category_name: return cat if 'children' in cat: cats.extend(cat['child...
82782dba9ae9374abc5e3f510ba53f9e03e14a62
666,937
def skip_comments(lines): """Filter out lines starting with a #.""" return (line for line in lines if not line.startswith('#'))
c91426a14adcd8dcc8aa8564523d3c9650fd77d4
666,943
def format_number(num): """ Formats a one or two digit integer to fit in four spaces. Returns a string of the formatted number string. """ result = " " + str(num) + " " if num < 10: result = result + " " return result
7aad542a65e7c661fc0769e43d701a3764b7f8f3
666,944
def extract_spec_norm_kwargs(kwargs): """Extracts spectral normalization configs from a given kwarg.""" return dict( iteration=kwargs.pop("iteration", 1), norm_multiplier=kwargs.pop("norm_multiplier", .99))
3262d4d9152a3a12e8f24580620e0c344f71d951
666,945
def parse_in(line): """Parse an incoming IRC message.""" prefix = '' trailing = [] if not line: print("Bad IRC message: ", line) return None if line[0] == ':': prefix, line = line[1:].split(' ', 1) if line.find(' :') != -1: line, trailing = line.split(' :', 1) ...
649d9dab68239e8819c7e40fc46804e73993f498
666,946
def name_blob(mosaic_info, item_info): """ Generate the name for a data file in Azure Blob Storage. This follows the pattern {kind}/{mosaic-id}/{item-id}/data.tif where kind is either analytic or visual. """ prefix = "analytic" if "analytic" in mosaic_info["name"] else "visual" return f"{pr...
4dd17ec49eae5db887fcf30c0696f1233c825fb7
666,952
def optional(**kwargs) -> dict: """Given a dictionary, this filters out all values that are ``None``. Useful for routes where certain parameters are optional. """ return { key: value for key, value in kwargs.items() if value is not None }
db34838108b88397f9ed2cd231a4b148b0d488bf
666,953
def drop_engine_after(prev_engine): """ Removes an engine from the singly-linked list of engines. Args: prev_engine (projectq.cengines.BasicEngine): The engine just before the engine to drop. Returns: Engine: The dropped engine. """ dropped_engine = prev_engine.next_...
9369fea7cdb35a446a6016967157f66a6f8e9513
666,955
def _get_material_sets(cell_sets): """Get the cell sets that are materials.""" material_names = [] material_cells = [] if cell_sets: set_names = list(cell_sets.keys()) for set_name in set_names: if "MATERIAL" in set_name.upper(): material_names.append(set_name...
abd17165dd62b38f6ccae5aadf4bfee2cced11fa
666,957
def unit_name(unit): """ Return name of unit (must of course match unit_t in opendps/uui.h) """ if unit == 0: return "unitless" # none if unit == 1: return "A" # ampere if unit == 2: return "V" # volt if unit == 3: return "W" # watt if unit == 4: ...
7600e6b3e6b1f5f3d4ab845c1be1f7a36ad27b54
666,958
def headers(token=None): """ Creates a dict of headers with JSON content-type and token, if supplied. :param token: access token for account :return: dictionary of headers """ data = {'Content-Type': 'application/json'} if token: data['Token'] = token return data
425f0137b50999dfd38a1a6b28628bb8d762a402
666,960
def bmatrix(arr): """ Converts a numpy array (matrix) to a LaTeX bmatrix Args: arr: Array Returns: LaTeX bmatrix as a string Raises: ValueError: If the array has more than two dimensions """ if len(arr.shape) > 2: raise ValueError('bmatrix can at most displa...
5382c8c623f7e4e2114949c254b8516c3fb798b3
666,962
def get_cookie(self, name, default=False): """Gets the value of the cookie with the given name,else default.""" if name in self.request.cookies: return self.request.cookies[name] return default
0831ec3c42433bdb10261a6fa0a71f239866c0d1
666,966
def XML_calib(calib_data: list, cf: int = 1): """Transforms a calibration array of floats into a .xml formatation. Args: calib_data (list): list of the calibration data for the microphone. Returns: str: string of calibration data in a .xml format. """ new_pos = '<pos\tName="Point {...
cb72fd6b6b2b1d5384e271363f9e13ed39c7ba06
666,967
def quadratic_cutoff(r_cut: float, ri: float, ci: float): """A quadratic cutoff that goes to zero smoothly at the cutoff boundary. Args: r_cut (float): Cutoff value (in angstrom). ri (float): Interatomic distance. ci (float): Cartesian coordinate divided by the distance. Returns: ...
c7e58dda5738a335659ec9f044d0fa41032d801e
666,969
import requests def get_number_of_records(parameters): """ :param parameters: Dictionary with parameters of query to Zenodo API (dict) :return: Number of records retrieved from the query (int) """ response_hits = requests.get('https://zenodo.org/api/records/', params=parameters) hits = respons...
6fd13e13526c5bf4d4c035fdf08ec4d4c575659a
666,971
import token import requests def get_payment_details(trans_id: str) -> dict: """ Takes the transaction_id from the request and returns the status info in json. It transaction_id is different from the transaction_ref so it should be grabbed from the request in the redirect url """ url = f"https://a...
340ebf60f82c24663c134a1d5d6e45f762764bf6
666,972
def _deep_map(func, *args): """Like map, but recursively enters iterables Ex: >>> _deep_map(lambda a, b: a + b, (1, 2, (3, (4,), 5)), (10, 20, (30, (40,), 50))) [11, 22, [33, [44], 55]] """ try: return [_deep_map(func, *z) for z in z...
709679408cfeca47e25d975974b3b219945a2f59
666,978
def get_review_request_id(regex, commit_message): """Returns the review request ID referenced in the commit message. We assume there is at most one review request associated with each commit. If a matching review request cannot be found, we return 0. """ match = regex.search(commit_message) ret...
a16866334259e50670f1af3cba3ff9e1b549a918
666,979
import re def get_version_parts(version, for_sorting=False): """Returns a list containing the components of the version string as numeric values. This function can be used for numeric sorting of version strings such as '2.6.0-rc1' and '2.4.0' when the 'for_sorting' parameter is specified as true.""" ...
0528bb020ecb940763d39f6f141894fe2458721a
666,980
def _compressed_suffix(compression): """Returns a suitable suffix (including leading dot, eg ".bz2") for the selected compression method.""" if compression is True: # select best compression -- but is xz always the best? return ".xz" elif compression in ("xz", "bz2", "gz"): # valid compression i...
5584928e335456969c59a85fe98c29a04ece1e33
666,983
def sort_by(comparator, list): """Sorts the list according to the supplied function""" return sorted(list, key=comparator)
3b50ddd1bf5e16b513cc9376cf5ee7363682fd40
666,987
def ramp(duration, initial, final): """Defines a linear ramp. f(t) = (final - initial)*t/duration + initial Args: duration (float): Duration of ramp initial (float): Starting value of ramp final (float): Ending value of ramp Returns: func: Function that takes a single ...
707a01542f90eea66ed4158f759cfd0a6b931d7a
666,988
import csv def csv_to_list(filename): """ creates a list of the contents of the csv """ out = [] with open(filename, newline = '') as f: #open csv file containing names reader = csv.reader(f) #read the file for row in reader: #loop over rows of the file out += row #add co...
698ffe07a10ef64fb83bcd0d1e0477cca5fc0441
666,990
from functools import reduce def arr2(value, *forms): """ Clojure's second threading macro implementation. The logic is the same as `thread_first`, but puts the value at the end of each form. See https://clojuredocs.org/clojure.core/->> :param value: Initial value to process. :type valu...
56dbefe686300ff0f9173d4b5c4c195486cb8178
666,995
def get_atoms_per_fu(doc): """ Calculate and return the number of atoms per formula unit. Parameters: doc (list/dict): structure to evaluate OR matador-style stoichiometry. """ if 'stoichiometry' in doc: return sum([elem[1] for elem in doc['stoichiometry']]) return sum([elem[1] for...
211ec973f27ee1ad4b3a8b37efa3027887423f6b
666,996
def batch_to_single_instance(X): """ Take the first instance of an array that contains a batch of items. Parameters ---------- X : nd array, shape: [batch_size, \\*instance_shape] A numpy array whose first axis is the batch axis. Returns ------- x : (n-1)d array, shape: [\\*in...
07e9b19211dcf9cc01b76174c62159925f3c3cdc
667,000
def _unpack_one_element_list(scalar_or_list): """If the value is a list and it only has one value, we unpack it; otherwise, we keep the list. This is used for size parameter inside tf.io.SparseFeature. """ if isinstance(scalar_or_list, list) and len(scalar_or_list) == 1: return scalar_or_lis...
67937c1abf2cf1bc6df7af8a48565884bccd8d69
667,001
import re def humansorted_strings(l): """Sort a list of strings like a human Parameters ---------- l : list A list of strings Returns ------- list The sorted list """ def alphanum_key(s): key = re.split(r'(\d+)', s) key[1::2] = map(int, key[1::2]) ...
d29f2e6b9b8a187531ea58529efdcb13c5890950
667,002
def make_ratings_hash(ratings): """ Make a hashtable of ratings indexed by (userid,itemid) @param ratings: pandas.DataFrame of ratings @return a hashed version of the input ratings, which maps (userid, itemid) tuples to the relevant rating. """ rhash = {} # for every 3-colu...
f9eae9b6b392fba101ebe41a133cc7c1cc9bd258
667,004
def argmax(list, score_func=None): """ If a score function is provided, the element with the highest score AND the score is returned. If not, the index of highest element in the list is returned. If the list is empty, None is returned. """ if len(list) == 0: return None scores = list...
566550aacf639121ddf96022e3154ba45d7cb4af
667,007
def get_loc_11(number=1): """Turn the the number for loc_11 into a string""" n = str(number) return n
3f7e492794bf017cbe95fb2e4d82f8f779c15438
667,008
def mark_backend_unsupported(func): """Mark a method as being not supported by a backend.""" func._oculy_backend_unsupported = True return func
5d1053dfcfeaf7a078a0b8cb87321152d9ee1111
667,009
import io def fetch_image(session, url, timeout=10): """download the satellite image for a tile. Args: session: the HTTP session to download the image from url: the tile imagery's url to download the image from timeout: the HTTP timeout in seconds. Returns: The satellite ...
399d24be9a9ecad8d6d3f84da80243643bf23a1d
667,012
def make_double_digit_str(num: int) -> str: """ useful for file names, turns 9 into "09" but keeps 15 as "15" :param num: one or two digit number :return: two digit number string """ return str(num) if num > 9 else "0" + str(num)
8e07b2bdcc6d1cf7bbbc344ab1ed240000e23210
667,017
import math def get_es(temp): """ Reference page number: 29 Parameters ------------------------------ temp: (``float``) Air temperature in degrees Celcius Returns ------------------------------ es: (``float``) The saturation vapour pressure """ es = 0.6108 * mat...
df10dbc77df76095d2c5133d1386c5a0696ec363
667,018
def upper(name: str) -> str: """Convert the name value to uppercase. Arguments: name: name of the attr. Returns: The uppercase value. """ return name.upper()
435d1b81fbec5401a0c942be9a56c2afb7fb113d
667,020
def bubble_sort(some_list): """ https://en.wikipedia.org/wiki/Bubble_sort We continuously loop through the data set, swapping next-door-neighbors that are out of order. In this way, values will BUBBLE one spot towards their correct positions once per loop. O(N^2) """ iters = 0 did_swap ...
746930b4c083b803f64aa4afa6a461123f92e66f
667,021
def get_selected_tests(args, tests, sources): """Return the selected tests.""" for exclude_test in args.exclude: tests_copy = tests[:] for i, test in enumerate(tests_copy): if test.startswith(exclude_test): tests.pop(i) sources.pop(i) return tests,...
bdcc861610ed28bdeee49bcfcae8f37bf59150f5
667,024
def read_file(path): """ Return the contents of a file Arguments: - path: path to the file Returns: - contents of the file """ with open(path, "r") as desc_file: return desc_file.read().rstrip()
146863066db83943d79de1ce6c43acecb46c8bac
667,030