content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def to_settings(settings): """Return a dict of application settings. Args: settings (dict): Database-specific settings, formatted to use with :func:`connection_url`. Returns: dict: Application-level settings. """ return {'DATABASE_{}'.format(k.upper()): v for k, v in s...
a9cc486c07851a0019af63ec8bda4f763fe8ae30
679,970
def get_items_as_list(items,keys,items_names='styles'): """ Returns a dict with an item per key Parameters: ----------- items : string, list or dict Items (ie line styles) keys: list List of keys items_names : string Name of items """ if type(items)!=dict: if type(items)==list: if len(items...
5fe7f85a6b6b5b22ab2e12f3f00c1cd2fcbb83f2
679,972
def pystr(s): """Output a string as an eval'able representation of a Python string.""" return s.__repr__()
19d379871ab1f11fd8d338dfbc07756fcfc9062d
679,978
from typing import Any def sum_values(obj: Any) -> Any: """Return sum of the object's values.""" return sum(obj.values())
e4e083bbd33a99cbaa8a57b553febc01416b448e
679,983
def get_contact_indices(layer_0, layer_1): """Get counter that finds index pairs of all contacts between layers. Args: layer_0: String. Must be key in state. layer_1: String. Must be key in state. Returns: _call: Function state --> list, where the elements of the returned list ...
847c3308cd54ede495245f0077d26fded584ab23
679,987
def serialize_tree(root): """ Given a tree root node (some object with a 'data' attribute and a 'children' attribute which is a list of child nodes), serialize it to a list, each element of which is either a pair (data, has_children_flag), or None (which signals an end of a sibling chain). """ l...
830a0dcaad9921b7eae1714bd2c7758aa11c4ad0
679,991
def do_pick(pick_status : int): """ This function takes one integer type argument and returns a boolean. Pick Status = Even ==> return True (user's turn) Pick Status = Odd ==> return False (comp's turn) """ if (pick_status % 2) == 0: return True else: return False
752633fa65984463d2e7a251acb2c1e0b1bd7962
679,992
def search(key, table, prefix=True): """Search for `key` in `table`. :param key: str, The string to look for. :param table: dic, The table to look in. :param prefix: bool, So a prefix search. :returns: Value in table or None if it is a prefix search it returns the full key and the ...
9a5f677b66785c7b702e1e18633790e3e909d3cb
679,995
def get_list_url(list_name): """Get url from requested list name. Parameters ---------- list_name : str Name of the requested list. Valid names are: *nea_list, risk_list, risk_list_special, close_approaches_upcoming, close_approaches_recent, priority_list, priority_list_faint, ...
163f78223aaafa82b7e40ec53b37c1de6faabb51
679,996
def fake_train(lrate, batch_size, arch): """Optimum: lrate=0.2, batch_size=4, arch='conv'.""" f1 = ( (lrate - 0.2) ** 2 + (batch_size - 4) ** 2 + (0 if arch == "conv" else 10) ) return f1
9e6458fb79b697c4529d3f3b0fa39aad1b79810f
679,997
from contextlib import suppress import ipaddress def is_ip_address(value: str) -> bool: """Check if a value is a valid IPv4 or IPv6 address. :param value: value to check """ with suppress(ValueError): ipaddress.ip_address(value) return True return False
8522d946e637b466207fbccdb6d61e9bb485d1cf
679,999
from typing import Dict def get_example_brand_map() -> Dict[str, str]: """ Return notebooks brand mapping based on simple regex. The mapping is from patterns found in menu_items to the items brand. The returned dictionary {key, value} has the following structure: key is the regex search pattern ...
171a3b5de7c3a8f893a3b4f632f62072e38ca5d5
680,002
def append_write(filename="", text=""): """ Write a new file or append info if exists Args: filename: string containing the name or "" if not given. text: content of the file Return: number of chars written """ with open(filename, 'a', encoding="utf-8") a...
98f99d27f125048c81019483c2852e76cf773016
680,009
def ij_to_dxdy(start_idx, end_idx, _row_size=14): """ Helper function to calculate _x, _y, _dx, _dy given two indexes from the board Determine the row, change in column, and change in row # of the start/end point pair :param start_idx: starting index :param end_idx: ending index :param _row_...
9f946d6189d6149d2cb38223848569dd03d13a68
680,012
def price_in_usd(usdprice, amount, base, dest='USD'): # print(amount, base, dest) """ Return price of any "dest" currency normalized to USD """ return usdprice.convert(amount, base=base, dest=dest)
d847dd43b73e6e98ff7d8c4c7d52704d62657280
680,014
import logging def get_logfile_from_logger(logger): """Return the path to the log file if there is a logging.FileHandler""" try: file_handlers = [h for h in logger.handlers if type(h) == logging.FileHandler] except: pass else: if file_handlers: return file_handlers[...
ed23bba0b5ea384cef64c323d77fecfff62b8216
680,021
import torch def as_numpy(tensor_or_array): """ If given a tensor or numpy array returns that object cast numpy array """ if isinstance(tensor_or_array, torch.Tensor): tensor_or_array = tensor_or_array.cpu().detach().numpy() return tensor_or_array
e81e04bb9aeb5e72d684d22ecf790581f2edf098
680,022
def get_indicator_publication(indicator): """ Build publications grid field from the indicator external_references field Args: indicator: The indicator with publication field Returns: list. publications grid field """ publications = [] for external_reference in indicator.ge...
f932c1f46c969661d2b6843ef19743c14344d199
680,023
import pickle def load_obj(name): """ Method to load pickle objects. input: name: path with the name of the pickle without file extension. """ with open(name + '.pkl', 'rb') as file: return pickle.load(file)
edf99286bb0d2f66cfa3b7d47a7929c7ea86bf30
680,024
def _divide_with_ceil(a, b): """ Returns 'a' divided by 'b', with any remainder rounded up. """ if a % b: return (a // b) + 1 return a // b
345e3ba6631d686379e405fc205ac6620dcf7562
680,031
def isCST(foraValue): """returns whether a foraValue is a constant""" return foraValue.implVal_.isCST
bf0e17665cc40e3be8b983f4cf2e9360768e5df6
680,032
def filter_tagged_articles(articles, tagged_articles): """ Filter out those named entity tagged articles from the NLP pipeline which also appear in the evaluation set. :param articles: List of articles. :type articles: list :param tagged_articles: List of tagged articles. :type tagged_artic...
3d6cdf3f6464df92f1b1e063c5f1956e849c0c71
680,033
def update_max_accel(driver, ma): """ Updates the max accel of the driver :param driver: driver :param ma: new max accel :type driver: DriverProfile :return: updated driver profile """ return driver.update_max_accel(ma)
3424893a64c37d51c3fca1f99d6bc37689108c95
680,034
def castlingmove(movetuples): """Determine if we have a tuple of tuples or just a simple move.""" if isinstance(movetuples[0], tuple) and isinstance(movetuples[1], tuple): return True else: return False
e84e90d7bbb30b692fb3624baf5a43354a23338c
680,035
def readable_size(i, snapshot=False): """ Pretty-print the integer `i` as a human-readable size representation. """ degree = 0 while i > 1024: i = i / float(1024) degree += 1 scales = ["B", "KB", "MB", "GB", "TB", "EB"] if snapshot: return f"{i:+.2f}{scales[degree]:>5...
d15a58ee7c6fdb13f50408de479aae6d1001f43d
680,040
def num_explicit_hydrogens(a): """ Number of explicit hydrodgens """ return a.GetNumExplicitHs()
a6364c2515f3f32da3ca0c7ec9ad4a2a4c82eca0
680,043
def get_projects(conn, scenario_id, subscenarios, col, col_value): """ Get projects for which the column value of "col" is equal to "col_value". E.g. "get the projects of operational type gen_commit_lin". :param conn: database connection :param subscenarios: Subscenarios class objects :param col...
52d022b3e1862d66decc08fa4a687a141953898f
680,044
def introspection_query(description: bool = True) -> str: """ Return a generic introspection query to be used by GraphQL clients. Args: description: If ``True`` the query will require descriptions. Returns: Canonical introspection query """ return """ query IntrospectionQu...
26bf135d045071b14c77f41e9d37c1c33fe23605
680,045
def flatten_strokes(strokes): """ Flatten a list of strokes. Add stroke state in the process. For each point j, the stroke state is a tuple (pj, qj, rj) where: * pj=1 indicates the point is not the end of a stroke. * qj=1 indicates the point is the end of a stroke (but not the end of the drawin...
ecd1828ff013283486253b2a4dd73cc4cd3ef549
680,046
def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x
5a41b2fc4c22b050ad56a36455ca3e2d37a379f4
680,048
import copy import torch def get_printoptions() -> dict: """ Returns the currently configured printing options as key-value pairs. """ return copy.copy(torch._tensor_str.PRINT_OPTS.__dict__)
4d5bea94df1cabb99be851c7451defe2beba18d9
680,055
def get_cavity_phases(fn): """ Given an OPAL input file, extract phi1, phi2, phi3, phi4 (rad) """ with open (fn, 'r') as f: getvars = {'t_offset': None, 'dphi': None, 'phi_correction': None, 'phi0': None, 'phi1': None, ...
8c3574836bb7dee52aa5b41228325a6bfdeac701
680,058
def load_diachronic_dataset(datapath="data/nytimes_dataset.txt", start_date="2019-01-01", end_date="2020-12-31"): """ Read in a diachronic dataset with "%Y-%m-%d\tsentence" per line Inputs: - datapath [str]: path to a dataset with tab-separated dates (in the same format as start/end_date) ...
55913646163e5557b3c2b0dbccc72a5c7cc9c46e
680,061
import requests def make_request(url, headers=None): """ make an http request """ r = None try: r = requests.get(url, headers=headers) except Exception as e: raise e return r
9e7cfbc8941e983d968c2ba0515a0ce5db856400
680,064
def _is_ascii(text): """ Args: text (str): Text to check. Returns: bool: whether or not the text can be encoded in ascii. """ return all(ord(char) < 128 for char in text)
8fbdf88451665403d972f174b144796cf216690e
680,066
import math def attacker_success_probability(q: float, z: int): """ Compute the probability of an attacker to create a longer trusted chain :param q: probability the attacker finds the next block :param z: number of blocks behind :return: probability the attacker will ever catch up from z blocks b...
0636b86b7a4ec6cf8b619590773e992c56fceb3f
680,067
from torch import optim from functools import partial def get_optimizer(optimizer): """ Returns an optimizer according to the passed string. :param optimizer: The string representation of the optimizer. eg. 'adam' for Adam etc. :return: The proper nn.optim optimizer. """ _optim_dict = {'adam': partial(optim.Ad...
d7e30de7e7d19dbef3c2fd6475895b213913af4c
680,069
import logging def is_valid_dataset(platform): """Filters out datasets that can't be used because it is missing required data such as the release date or an original price. Other required data includes the name and abbreviation of the platform. """ if 'release_date' not in platform or not platfor...
715187e707e6e070bb170ebceedd5e05bd9124c9
680,070
from datetime import datetime def _zulu_to_epoch_time(zulu_time: str) -> float: """Auxiliary function to parse Zulu time into epoch time""" epoch = datetime(1970, 1, 1) time_as_date = datetime.strptime(zulu_time, "%Y-%m-%dT%H:%M:%SZ") return (time_as_date - epoch).total_seconds()
ea5ca60979f5c9f10f5a1a9d00e733de06f20a55
680,074
import functools def compose(*functions): """ Compose functions. """ return functools.reduce(lambda f, g: lambda x: g(f(x)), functions, lambda x: x)
5e8ee44e0833388f7e136095ca63c8538e9827e4
680,075
def _find_closest_year_row(df, year=2020): """Returns the row which is closest to the year specified (in either direction)""" df = df.copy() df['year'] = df['year'].sort_values(ascending=True) return df.loc[df['year'].map(lambda x: abs(x - 2020)).idxmin()]
30f254ef97e70907d8b1e7d05eeeda15151b95ea
680,078
import re def _fullmatch(pattern, text, *args, **kwargs): """re.fullmatch is not available on Python<3.4.""" match = re.match(pattern, text, *args, **kwargs) return match if match.group(0) == text else None
0e005cad29dfe836f7bdeb01bf140e4ed2c49b6e
680,084
def fixChars(text:str) -> str: """Fixes \\xa0 Latin1 (ISO 8859-1), \\x85, and \\r, replacing them with space""" text = text.replace(u'\xa0', u' ') text = text.replace(u'\x85', u' ') text = text.replace(u'\r', u' ') return text
2620a88e71641cb4863b914e9d913fb6247a3364
680,085
def get_metadata_value(structure_list, desc_metadata): """Retrieve a given metadata from a list of structures from the descriptor key""" desc_metadata_list = [] for structure in structure_list: desc_metadata_value = structure.info['descriptor'][str(desc_metadata)] desc_metadata_list.append(...
f14f5003cb31a576808b625403368a8b2ba59509
680,087
import ntpath import posixpath def to_posix(path): """ Return a path using the posix path separator given a path that may contain posix or windows separators, converting "\\" to "/". NB: this path will still be valid in the windows explorer (except for a UNC or share name). It will be a valid path...
6e11d24beda6316168462220a771ce90369e8eb0
680,090
def SafeToMerge(address, merge_target, check_addresses): """Determine if it's safe to merge address into merge target. Checks given address against merge target and a list of check_addresses if it's OK to roll address into merge target such that it not less specific than any of the check_addresses. See descrip...
152f4a52cdb03adcd86ff2f03578f15a9aa31f37
680,093
import string def fmt_to_name(format_string, num_to_name): """Try to map a format string to a single name. Parameters ---------- format_string : string num_to_name : dict A dictionary that maps from an integer to a column name. This enables mapping the format string to an integer...
3f8edb995c08a36e262aeaf8c9b5728c9c286db6
680,094
import re def _replacestrings(source): """Strip string lookup table (list) and replace values in source.""" match = re.search(r'var *(_\w+)\=\["(.*?)"\];', source, re.DOTALL) if match: varname, strings = match.groups() startpoint = len(match.group(0)) lookup = strings.split('","')...
4f839a39b82a17e5c73d577677e1e2f9c82659f0
680,095
def PNT2QM_Tv4(XA,chiA): """ TaylorT2 2PN Quadrupole Moment Coefficient, v^4 Timing Term. XA = mass fraction of object chiA = dimensionless spin of object """ return -10.*XA*XA*chiA*chiA
c9cbd371eea8c0838c1fc77906754a10e7a92092
680,096
import requests def get_students_registered_for_class(url, username, password, crn, term): """ Grabs the students registered for a course in a particular term Uses an API like https://boomi.som.yale.edu:9090/ws/rest/subscribers/klj39/CourseRoster/ Arguments: url {string} -- API URL, e...
ccd905bba80bc6bac4ab5d310b18274971716fbd
680,100
def computeEER(rates, withthresh=0): """Computes equal error rates from the list of (true pos, false pos) values. If withthresh is true (not the default), then returns (eer, index at which eer occurs).""" det, fpos = zip(*rates) fpos = map(float, fpos) npos = [1.0-f for f in fpos] difs = [(abs(d...
062e5c475023a7d359eb9debbf815344055f0568
680,101
def is_nonAA(residue): """ Parameters ---------- residue : a residue from a protein structure object made with PDBParser(). Returns ------- Boolean True if residue is hetero or water, False otherwise. """ residue_id = residue.get_id() hetfield = residue_id[0] return ...
f79ad24fa1e759998ad24c01e226f22e1ed03567
680,102
import string import random def key_generator(size=6, chars=string.ascii_uppercase + string.digits): """ Generates random strings for things that need keys. Allows variable size and character lists, if desired. NOT CRYPTOGRAPHICALLY SECURE :param size: Size of the key to generate :param ch...
b1f0beb2286841734145d97c6ce4f51ec8cce5e7
680,104
def all_columns(df, names): """ Test if df has all columns """ array = [name in df.columns for name in names] return sum(array) == len(array)
46d954e21492bbb56bc5eae78c14caa0510aa37a
680,105
from typing import Union def convert_memory_limit(memory: Union[str, int]) -> int: """Converts a provided memory limit with optional units into its equivalent in bytes. Args: memory: String or integer representation of memory limit. Returns: The provided memory in bytes. """ ...
2a0357cfee8c8124c99735d4ea814fa86ca0a3cd
680,108
def centroid_atmList(atmList): """Get centroid for list of atoms.""" i, x, y, z = 0, 0, 0, 0 for atm in atmList: x += atm["x"] y += atm["y"] z += atm["z"] i += 1 return x/i, y/i, z/i
b25af20d470246130990add7add974bdac72c951
680,110
def _process_parameters(parameters): """ Run over the parameters are extract parameter and column name. This function deals with figuring out if a requested parameter also has a user defined output name. .. note:: Function for internal use! :param parameters: list of tuples or strings cont...
2005c1841bbad5c1ac48f37b365102d04adf41ae
680,115
import configparser def import_test_configuration(config_file): """ Read the config file regarding the testing and import its content """ content = configparser.ConfigParser() content.read(config_file) config = {} config['gui'] = content['simulation'].getboolean('gui') config['max_step...
04ab5c49ffb4b44e4bce7c2bc96b6ea76407316c
680,117
def solve_modular_equation(a, b, c): """ Find solution of ax % b = c (a and b relative primes, ie assume gcd(a, b) == 1) pow(a, -1, mod=b) computes the modular multiplicative inverse for python >= 3.8 """ return (pow(a, -1, mod=b) * c) % b
ee2cc41ae8347f448e5eac1542c49d0e29bec84c
680,118
import requests from bs4 import BeautifulSoup def fetch_pkg_version(pkg_url: str) -> str: """ Find the version of package documentation :param pkg_url: Full URL of package documentation :return: version string of the package requested """ # fetch the page and parse version page = requests...
1c003678caed66d891844a5ddf093d7ebaba4512
680,122
def get_param(param, arguments, default=None): """ Get parameter from list of arguments. Arguments can be in following format: ['--parameter', 'param_value'] or ['--parameter=param_value'] Args: param (str): Name of parameter arguments (list): List of arguments from CLI default ...
1dddce2639d563de6bb9177d1fc0a87b22ee7b52
680,123
import string import random def random_id(size=8, chars=string.ascii_letters + string.digits): """Generates a random string of given size from the given chars. @param size: The size of the random string. @param chars: Constituent pool of characters to draw random characters from. @type size: number @type cha...
ccc89ef294e0d55f701bb678b3d2804ed78ec835
680,125
def type_of_exception(exception_object): """Get the type of an exception object as a string or None""" if isinstance(exception_object, Exception): return str(exception_object.__class__.__name__)
2cdf774fce1c2bb57a86d7ddbf0feddabdb82d26
680,126
def generate_bins() -> list: """ Generate color bins. :return: List of bins """ h_bins = [(x / 10.0, (x + 1) / 10.0) for x in range(0, 10)] h_bins[-1] = (h_bins[-1][0], 1.1) s_bins = [(0.0, 0.333), (0.333, 0.666), (0.666, 1.1)] l_bins = [(0.0, 0.333), (0.333, 0.666), (0.666, 1.1)] bi...
fa207596bc915f83145964d6a07b5140fb021e5d
680,128
def intermediate_text_filename_generation(cote, lang): """ Generate the name of a given intermediate text cote : the cote lang : the language to look for to create the texts. Must follow the Code convention ("f","l","t" or "a") Return : str """ lang_dict = {"f":"fr","a":"de","t":"it","l":"la...
9375d651cc4ea40dbb572237b93421dfbfcba1ac
680,129
def next_cma(new_value, list_len, old_cma): """ Calculate next cumulative moving average 'list_len' is the length of the currently being averaged list before adding the new value """ return (new_value + list_len * old_cma) / (list_len + 1)
a21791ac76f856881c0a9a869b3d7bbe8d0af6f9
680,134
def rubygems_api_url(name, version=None): """ Return a package API data URL given a name, an optional version and a base repo API URL. For instance: >>> url = rubygems_api_url(name='turbolinks', version='1.0.2') >>> assert url == 'https://rubygems.org/api/v2/rubygems/turbolinks/versions/1.0.2.j...
fe65efd39f4b1707588d1dc419fcc570070f6289
680,135
from io import StringIO def _join(args): """ Join the arguments with spaces, except newlines which don't need to be padded. """ result = StringIO() skipSpace = True for arg in args: if skipSpace: skipSpace = False else: result.write(' ') if a...
950a8e7ae23072ad8693609d73fff5c5a0508752
680,146
def keep_only_digits(input_string: str) -> str: """This function takes as input a string and returns the same string but only containing digits Args: input_string (str): the input string from which we want to remove non-digit characters Returns: output_string (str): the output string that on...
00feca8a43fd673ff6f650761dfa6861e29be88c
680,147
def create_files_dict(file_name, metadata_content, bitstream_content): """Create dict of files to upload to S3.""" package_files = [ { "file_name": f"{file_name}.json", "file_content": metadata_content, }, { "file_name": f"{file_name}.pdf", ...
5792f05076657163fb51d60fc8c1b2b4641fb5c4
680,148
def supra_adjacency_matrix(net,includeCouplings=True): """Returns the supra-adjacency matrix and a list of node-layer pairs. Parameters ---------- includeCoupings : bool If True, the inter-layer edges are included, if False, only intra-layer edges are included. Returns ------- ...
cc418073cf34530eee9745d9429c549cb78dd229
680,152
from typing import Union from pathlib import Path def expand_wildcards(paths: Union[str, Path]) -> list: """Expand the wildcards that may be present in Paths.""" path = Path(paths).expanduser() parts = path.parts[1:] if path.is_absolute() else path.parts return [f for f in Path(path.root).glob(str(Pat...
a326abe415b6f970ad53a8aef5c900c10dce048a
680,154
def test_arg_index_attrs() -> None: """Accessing argument index and attributes.""" assert "{0.real}, {0.imag}".format(3 - 5j) == "3.0, -5.0" class Point: """Point with x-y coordinates.""" def __init__(self, x: int, y: int) -> None: self.x = x self.y = y def...
e5fdf367b5fa1f073e0491ae12451d1b663f17f8
680,156
import torch def validate(model, testloader, criterion): """Validate the model Arguments: model -- The network to validate testloader -- Test data criterion -- Loss function to use """ test_loss = 0 accuracy = 0 for images, targets in testloader: images.resize_...
9efd8746ded637b6e2564a830e7ddccb00d1f71d
680,157
def add_integers(*args: int) -> int: """Sum integers. Arguments: *args: One or more integers. Returns: Sum of integers. Raises: TypeError: No argument was passed or a passed argument is not of type `int`. Example: >>> add_integers(3, 4) 7 "...
924c8bb13b9a5fc2387ee05b177d389853f2cddc
680,158
def select_by_year(year, D): """Select year from specification given in dictionary or list of ranges. Examples: >>> spec = {(..., 1990): 'foo', ... 1991: 'bar', ... (1992, 2000): 'foobar', ... (2001, ...): 'blah'} >>> select_by_year(1990, sp...
0c3eca376e4f06bf3d3f85308bf02c35ded21e9e
680,161
import re def md(MD_tag): """ Given MD tag and a sequence, find the number of matched, deletion, and substitution bps Return: 1-level dictionary """ #matchLens = re.sub("\D"," ",MD_tag).split() #replace non-digit chars by blanks #matchLens = map(int, matchLens) #length of the matches before...
18e11d7749f7ee362bcb8cbede42848839276830
680,162
import hashlib def sqlite_md5(text): """ md5 - Returns the md5 of the text """ if (text!=None): hash = hashlib.md5() hash.update(text.encode("utf-8")) return hash.hexdigest() return None
41875a9043923472b3b628cb3e727a574c66966f
680,164
import random def MERB_config(BIM): """ Rules to identify a HAZUS MERB configuration based on BIM data Parameters ---------- BIM: dictionary Information about the building characteristics. Returns ------- config: str A string that identifies a specific configration wi...
53ab72ed19ebeb3e55f83fcccb80bff665de955e
680,166
import torch def compute_accuracy(logits, ys_ref, pad): """Compute teacher-forcing accuracy. Args: logits (FloatTensor): `[B, T, vocab]` ys_ref (LongTensor): `[B, T]` pad (int): index for padding Returns: acc (float): teacher-forcing accuracy """ pad_pred = logits...
3f1af7d1fae95afd3b5c6567c345185b5ceeaa70
680,169
def length(iterable): """ Return number of items in the iterable. Attention: this function consumes the whole iterable and can never return if iterable has infinite number of items. :Example: >>> length(iter([0, 1])) 2 >>> length([0, 1, 2]) 3 """ try: return len(itera...
1c2963290d22b9076d3f8f51dd84e586de711b11
680,171
def process_dsn(dsn): """ Take a standard DSN-dict and return the args and kwargs that will be passed to the pgdb Connection constructor. """ dsn['password'] = dsn['passwd'] del dsn['passwd'] dsn['database'] = dsn['db'] del dsn['db'] return [], dsn
12e577848fa6f063a9bcc2264f02d2d4ff0ab4e0
680,174
import requests def get_request(url: str, headers: dict, path: str)->dict: """ Perform an HTTP GET request :param url: the url to request :param headers: a dict containing the ZT Auth header :param path: the path at the url to request :return: a dict representing the returned JSON object. ...
c597251cfa7477fdc9f9fb92313b4b14fff5dd43
680,175
def datetime_to_iso_8601(dt): """Format a datetime as an iso 8601 string - YYYY-MM-DDTHH:MM:SS with optional timezone +HH:MM.""" if dt: return dt.replace(microsecond=0).isoformat() else: return None
1f1610b6d34409a00f4a1b0d8d47caa5ec8e8ad8
680,177
from typing import Dict from typing import Any from typing import List def get_key_mapping(inverse_mapping: Dict[Any, List[str]]) -> Dict[str, Any]: """Returns the key mapping from the inverse mapping. Args: inverse_mapping: A mapping from the mapped input to the list of keys. Returns: a mapping from ...
213e5373953bab72682a41981d287c1b1bbb6e35
680,183
import itertools def combos(indices): """ Return all combinations of indices in a list of index sublists. Arguments: indices: list of int lists List of index lists. """ return list(itertools.product(*indices))
ad2bf7f98ee13496764c4fb3654071d8c4e40445
680,185
def setDefaults(configObj={}): """ Return a dictionary of the default parameters which also been updated with the user overrides. """ gain = 7 # Detector gain, e-/ADU grow = 1 # Radius around CR pixel to mask [default=1 for 3x3 for non-NICMOS] ctegrow = 0...
6d852af3db241345ace2a8f4fcaa066304492bef
680,186
def init_comm(base_comm, grid_shape): """Create an MPI communicator with a cartesian topology.""" return base_comm.Create_cart(grid_shape, len(grid_shape) * (False,), reorder=False)
c44beadaaeacbcadd634515a8c6c7041fdc5f8e4
680,188
def is_test(obj) -> bool: """Is the object a test, i.e. test_func()?""" assert hasattr(obj, "__name__") obj_name = obj.__name__.lower() patterns = ("test", "_test", "__test") return any(obj_name.startswith(pattern) for pattern in patterns)
7fa240b79833ba79bf0150c97a0c9081bc7c4cf7
680,192
def harm(x,y): """Harmonic mean of x and y""" return x*y/(x+y)
7054a8a05e6d20fa39efd31ac62a5d5c4c51f061
680,201
def remove_dups(lst): """ Inputs: lst - A list object Outputs: Returns a new list with the same elements in lst, in the same order, but without duplicates. Only the first element of each replicated element will appear in the output. """ result = [] dups = set() ...
21d0158e977847812d6ae944e5a39da5ef77951b
680,212
def normalize_service_argument(argument): """ normalize service name and set type: $object, $variable$ Examples: >>> normalize_service_argument('$Mongodb') ['Mongodb', 'object'] >>> normalize_service_argument('%batch_size%') ['batch_size', 'variable'] """ if isinstanc...
be2b1ed59f636c2aa2596877782e686ced045057
680,220
import re def camel_to_snake(camel): """ make a camelcase from a snakecase with a few things thrown in - we had a case where we were parsing a spreadsheet and using the headings as keys in an object one of the headings was "Who Uploads?" """ camel = camel.strip() camel = re.sub(' ', ''...
9d96a3597fcf9fd73248c315e224e55d5fd1f96c
680,221
from typing import List def format_board(board: List[str]) -> str: """Return the board formatted for output""" out_board = '' for i in range(0, len(board)): if i == 0 or i % 3 == 0: out_board += '\n' + '-------------' + '\n|' tic = board[i] if board[i] in 'XO' else i + 1 ...
f8450e2ba4f65beca9acc9811b9d3f8139430e34
680,222
import re def _include_exclude( dictionary: dict, include_pattern: str, exclude_pattern: str, ) -> bool: """ Filters the items of a dictionary based on a include / exclude regexp pair. Returns `True` if the size of the dictionary changed. """ incl, excl = re.compile(include_pattern), r...
c7b06f84463c7d003a6516d5fc943da12ac4968e
680,224
def fruity_file(models_path): """Return fruity sample data file as a Path object.""" return models_path.joinpath("fruity.txt")
3b32e5f52963b7d24ace1d4ad4745eeb00d3d49b
680,225
from pathlib import Path def _modified_date(f: Path) -> str: """Get the modified date of the file""" return str(f.stat().st_mtime)
2d4b6fcf19f2ecb3bf360b302a6a6a1c90acd831
680,229
def separate_gradients(gradients, weight_vars, input_vars): """ split the gradient dictionary up into one for input and one for weights. Parameters ---------- gradients: dict: dictionary of gradients. Should be str, list[Objective] key/value pairs. input_vars: list: the input va...
dd73c8f4860e5c7e2c98972c56c024959aba034f
680,230
import re def subject_id_of(path) -> str: """ Returns the subject ID closest to the end of the input string or Path. Inputs ------ path : str or Path String or Path containing the subject ID. Returns ------- str Subject ID found in the filename Raises ------ ...
e9dd8f93f6638a454d91d2aa719daec46c1ce9ac
680,232
import logging import inspect def get_file_logger( log_file=None, log_filemode='a', log_level=logging.INFO, log_msg_fmt='%(asctime)s %(levelname)s %(message)s', log_date_fmt='%a, %d %b %Y %H:%M:%S', log_prefix=None ): """ Purpose: Get Logger to file Args: log_level ...
f31321aef3bff1650f41957b2d3783168b440947
680,233