content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_list_of_subsets(subset_task): """ Get the subsets to process for this analysis Parameters: ----------- subset_task: string string which specifies which subsets to use Results: -------- list of subset tasks """ # prefix for data and images if subset_task =...
c4d2e632bf4c70ef3232505694d86b1c48a9a0de
659,106
def mean_of_number_list(numbers, delim="_"): """Report arithmetic mean of a string of integers that are separated by a common delimiter. Used here to get mean of IES lengths reported in MILRAA output GFF attribute. Parameters ---------- numbers : str List of numbers separated by a commo...
2b1c04ba67ed0dac279fbc9ca6dd8458575f5f69
659,107
def loadLowFreqLabels(labelFilePath): """ Return dictionary of channel labels. :param labelFilePath: path to the data. The path should end with the folder containing all data for a specific house. :type labelFilePath: str :rparam: keys=channels_x - appliance name :rtype: dict """ ...
241ef9b58d01c24e36d28e855563af3b91e145f0
659,110
def rmpHomozygousWithTheta(theta, pu): """ Notation from Baldings and Nichols (1994) taken from Buckleton FSI Gen (23) 2016; 91-100 https://doi.org/10.1016/j.fsigen.2016.03.004 """ # 2theta + (1-theta)*pu numerator1 = (theta+theta) + (1-theta)*pu # 3theta + (1-theta)*pu == theta + numerator1 numerator...
4d51059c75bc357d96397165fe7df3b4b9eeee32
659,112
def bytes_to_gb(number: float) -> float: """ Convert bytes to gigabytes. Parameters ---------- number : float A ``float`` in bytes. Returns ------- float Returns a ``float`` of the number in gigabytes. """ return round(number * 1e-9, 3)
d97ac89429c7ebc321e44fe3d8b33c1a0f1288c7
659,115
import re def default_output_mixer_channel(discovery_props, output_channel=0): """Return an instrument's default output mixer channel based on the specified `devicetype` and `options` discovery properties and the hardware output channel. This utility function is used by the ziPython examples and retu...
5e927a8e2ff3596ea08d55b723b9d664531ca271
659,116
import torch def root_sum_of_squares(x, dim=0): """ Compute the root sum-of-squares (RSS) transform along a given dimension of a complex-valued tensor. """ assert x.size(-1) == 2 return torch.sqrt((x**2).sum(dim=-1).sum(dim))
e446eba20b70453630122a5543ae0f70b6063b5d
659,119
def build_links(tld, region_code, states): """ This will build start_urls, It needs to be available before the ChipotleSpider creation :param tld: 3rd level domain name to use for building the links e.g .co.uk :param region_code: region is an important url param required for the search :param state...
d42291356a149b3a8e411a0bfe715d522c03da4a
659,122
import six def _reset_cached_subgraph(func): """Resets cached subgraph after execution, in case it was affected.""" @six.wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) self._subgraph = None return result return wrapper
5cb500767cbed39ebdad3fede63b551e52c1747f
659,124
def dt_writer(obj): """Check to ensure conformance to dt_writer protocol. :returns: ``True`` if the object implements the required methods """ return hasattr(obj, "__dt_type__") and hasattr(obj, "__dt_write__")
fdb601d53bfe77b5732cbd0c5fe1108f20269841
659,125
def _aggregate_at_state(joint_policies, state, player): """Returns {action: prob} for `player` in `state` for all joint policies. Args: joint_policies: List of joint policies. state: Openspiel State player: Current Player Returns: {action: prob} for `player` in `state` for all joint policies. ...
b2bed9b7b2b48a4a73989fe9a3bd9b241c4a40ad
659,129
from typing import Tuple import torch from typing import List def cross_entropy_loss(batch: Tuple, model: torch.nn.Module) -> Tuple[float, Tuple[torch.Tensor, List]]: """ Calculate cross entropy loss for a batch and a model. Args: batch: batch of groundtruth data model: torch model R...
158f08353fe83125c20ba34313611f0023338326
659,130
from pathlib import Path import platform def get_py_prefix(venv_path: Path) -> Path: """Return the appropriate prefix for the virtual environment's Python. >>> # If platform.system() is 'Windows' >>> get_py_prefix(Path.cwd()/'.venv') Path('.venv/Scripts/python.exe') >>> # If platform.system() is...
a81a185d24f6d7fac52aa9e68512e193811b3407
659,131
import json def load_json(filename): """Returns students as a list of dicts from JSON file.""" with open(filename) as f: students = json.load(f) return students
9730ae02f2409518f594b3014702915cdda5ad03
659,133
import typing def flatten_list(list_of_lists: typing.List[typing.List[typing.Any]]) -> typing.List[typing.Any]: """flatten a 2 level deep nested list into a single list Parameters ---------- list_of_lists: typing.List[typing.List[typing.Any]] 2 level nested list Returns ------- ...
eab91121f66cefc1ab7e43f5644544360f1e678c
659,135
def sqliteRowsToDicts(sqliteRows): """ Unpacks sqlite rows as returned by fetchall into an array of simple dicts. :param sqliteRows: array of rows returned from fetchall DB call :return: array of dicts, keyed by the column names. """ return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)
93f897ca07db4edd14a303bef00e233b0a06a6e3
659,138
def class_name(self): """ Return the name of this class without qualification. eg. If the class name is "x.y.class" return only "class" """ return self.__class__.__name__.split('.')[-1]
562c956cbdc8e724eea2733697c479a82a0f936b
659,141
def add_season_steps(df, season_length): """ Adds a column to the DataFrame containing the season step depending on the given season_length. The season step determines the position of each column within a season. It ranges from 0 to season_length - 1. :param df: pandas DataFrame with a DateTime index a...
d24c6dfc49821d5fb849d298834f988355afe359
659,146
def _byte_string(s): """Cast a string or byte string to an ASCII byte string.""" return s.encode('ASCII')
db048e47ebbb964ee6d14d2c32a8d4dcd3b45ad4
659,150
def is_threaded_build(root): """ Check whether the tk build in use supports threading. :param root: the tk widget to be used as reference :return: ``1`` if threading is supported ``0`` otherwise """ return int(root.tk.eval("set tcl_platform(threaded)"))
554d92e51fabff650bf809662a16ca44f190c994
659,151
def bezierPoint(a, b, c, d, t): """Given the x or y coordinate of Bézier control points a,b,c,d and the value of the t parameter, return the corresponding coordinate of the point.""" u = 1.0 - t return a * u * u * u + b * 3 * u * u * t + c * 3 * t * t * u + d * t * t * t
1da9a9f0756b47c04ecd6f91f611d7c7d2f22760
659,152
def get_decoding_route_length(molecular_graph): """ Returns the number of subgraphs in the `molecular_graph`s decoding route, which is how many subgraphs would be formed in the process of deleting the last atom/bond in the molecule stepwise until only a single atom is left. Note that this is simply the ...
7e55e4d1a243a9bbb8352b95cd22066006e7060a
659,155
def get_texture_declaration(texture): """Return the GLSL texture declaration.""" declaration = "uniform sampler%dD %s;\n" % (texture["ndim"], texture["name"]) return declaration
625dbc7e84949b9bf8bbda6ca86244c681187825
659,157
def bin_coef_efficient(n: int, k: int) -> int: """ C(n, k) = C(n, n-k) # fact therefore, if k > n-k, change k for n-k (for easier calculation) i.e. C(n, k) = n! / (k! * (n-k)!) = [(n) * (n-1) * ... (n-k+1) / k!] => k terms above and k terms below Time Complexity: O(k) Space Complexity: O(...
09508012cc6f35320d5c8b27168f76f65e71a4a6
659,158
def ec2_inst_is_vpc(inst): """ Is this EC2 instance a VPC instance? """ return (inst.vpc_id is not None)
a7c53f0aea53e78ebcebba5023a85aeed0a56afb
659,159
def read_number_of_agents(dpomdp_file): """Returns the number of agents in a Dec-POMDP problem Keyword arguments: dpomdp_file -- path to problem file in the .dpomdp format """ with open(dpomdp_file) as file: for line in file: if line.startswith('agents:'): return int(line.split(':')[1]) raise V...
13f91b6f00b290783898928f287bcccb0e2f4b69
659,160
import io def _has_fileno(stream): """Returns whether the stream object seems to have a working fileno() Tells whether _redirect_stderr is likely to work. Parameters ---------- stream : IO stream object Returns ------- has_fileno : bool True if stream.fileno() exists and doe...
a725119eb2cce135e33adab11854f9da5e8af64d
659,161
def remap_gender(gender: str) -> str: """Map gender to standard notation. Args: gender (str): Original gender, eg male, girl, etc Returns: str: m, f or other """ if not isinstance(gender, str): return "other" gender = gender.strip().lower() if gender in ["man", "ma...
f0f0725f6379b1bdd1dfe39b98a4856400b337ed
659,173
def add(key=None, value=None, *, myst, getpass, **kwargs): """ Add a new key-value pair. Accepts a optional key and an optional value for the key. If the key or value is not entered, a secure input will be prompted to enter them. """ if not myst.mutable: return 'the myst is in read-only mode, us...
31114ff2dda7edbf393f031c73bf59f6f50e9ef8
659,177
import re def split_pem(data): """ Split a string of several PEM payloads to a list of strings. :param data: String :return: List of strings """ return re.split("\n(?=-----BEGIN )", data)
89e34875135406e66f7a3f536cf3909a6fc85b17
659,182
def get_cell(grid, y: int, x: int) -> str: """Returns the value of a cell""" return grid[y - 1][x - 1]
e1912ff4cee24371de57e93b7aa55dbb287540ee
659,188
def nsyll_word(word, vowels, sep=None): """ Count the number of syllables in a *word*, determined by the number of characters from the *vowels* list found in that word. If *sep* is defined, it will be used as the delimiter string (for example, with `sep="."`, the word "a.bc.de" will be treated as t...
cc722c0cf9b7845fb95e55d6717e35b1058e473d
659,189
def deriv(f,c,dx=0.0001): """ deriv(f,c,dx) --> float Returns f'(x), computed as a symmetric difference quotient. """ return (f(c+dx)-f(c-dx))/(2*dx)
8647945c4cd1b5bd37c46f1afe1dff645a5507a5
659,191
import math def distance(origin, destination): """ Haversince distance from https://gist.github.com/rochacbruno/2883505 Returns distance in kilometers """ lat1, lon1 = origin lat2, lon2 = destination radius = 6371 # km radius of Earth dlat = math.radians(lat2-lat1) dlon = math.rad...
5cbc59e8c0c8875fa0d03ecb2b673318b8bea01d
659,195
import torch def rgba_to_rgb(image): """ Convert an image from RGBA to RGB. """ if not isinstance(image, torch.Tensor): raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}") if len(image.shape) < 3 or image.shape[-3] != 4: raise ValueError(f"Input size must h...
a779503844e76fd5632385aa57519801afeb7e65
659,200
def pass_bot(func): """This decorator is deprecated, and it does nothing""" # What this decorator did is now done by default return func
b8043b87b762db9f7b78617ad253aaca9dcd4369
659,205
import logging def create_project_subnet(neutron_client, project_id, network, cidr, dhcp=True, subnet_name='private_subnet', domain=None, subnetpool=None, ip_version=4, prefix_len=24): """Create the project subnet. :param neutron_client: Authenticated neutr...
9d5deb2dfbda78800d9c6c3b35f8bf940a5909e2
659,206
def internal_pressure(P_d, P_h): """Return total internal pressure [Pa]. :param float P_d: Design pressure [Pa] :param float P_h: Pressure head [Pa] """ return P_d + P_h
d211f5cf7357cfa5281f77b33ac1c8fc1f9cac94
659,209
import random def keep_fraction(l, f): """Return fraction `f` of list `l`. Shuffles `l`.""" random.shuffle(l) count = int(f * len(l)) return l[:count]
b499d9c892bc17f4397b45adafaf67dfb9f6cd17
659,211
def list_to_space_string(l): """Return a space separated string from a list""" s = " ".join(l) return s
be558a1b97ee27a9e61c0efef3b50db30f9cc06a
659,214
def _ComplexSentenceAsFlatList(complex_sentence, prefix=""): """Expand complex_sentence into a flat list of strings e.g. ['NUMBERED'] ['IDS', 'INES'] ['SOLUTION'] to ['NUMBERED ID SOLUTION', 'NUMBERED INES SOLUTION'] """ results = [] next_start = complex_sentence[1:].find('[') if nex...
d3f8a7821da810feb03d5368df8c5eb06889cb1f
659,216
def arg_meta(*arg_flags, **arg_conf): """ Return a tuple `(arg_flags, arg_conf)` that contains argument flags & argument config. `arg_flags`: A tuple contains argument flags `arg_conf`: A dict containsf argument config """ return (arg_flags, arg_conf)
c626b4efe6338195253d58b759662398a1ecb9d1
659,220
def sec2HMS(sec): """Convert time in sec to H:M:S string :param sec: time in seconds :return: H:M:S string (to nearest 100th second) """ H = int(sec//3600) M = int(sec//60-H*60) S = sec-3600*H-60*M return '%d:%2d:%.2f'%(H,M,S)
216bb1ca1eb57ceea06d93ae8b83c752b9d42c8a
659,227
def dot_product(a, b): """ Return dot product between two vectors a & b. """ a1, a2, a3 = a b1, b2, b3 = b return a1 * b1 + a2 * b2 + a3 * b3
4f02efd1d0520284c547790faf3b1200812ebe67
659,228
def table_exists(cursor, table_name): """ Checks if the table table_name exists in the database. returns true if the table exists in the database, false otherwise. :param cursor: the cursor to the database's connection :type cursor: Cursor :param table_name: the name of the table searching for ...
230b250203a2d5ba5153b28f10154d8f947a4264
659,229
def _parse_commit_response(commit_response_pb): """Extract response data from a commit response. :type commit_response_pb: :class:`.datastore_pb2.CommitResponse` :param commit_response_pb: The protobuf response from a commit request. :rtype: tuple :returns: The pair of the number of index updates ...
dcb9083feb15233bf30d2b97599d08d7a7a611ee
659,231
import six def FormatDuration(duration): """Formats a duration argument to be a string with units. Args: duration (int): The duration in seconds. Returns: unicode: The formatted duration. """ return six.text_type(duration) + 's'
7221949968750ab543795a220ab30875840d8ec2
659,234
def object_is_valid_pipeline(o): """ Determines if object behaves like a scikit-learn pipeline. """ return ( o is not None and hasattr(o, "fit") and hasattr(o, "predict") and hasattr(o, "steps") )
dac937a63fd7ad3164b851e4a6e7d02c081ace28
659,240
def expand_address_range(address_range): """ Expand an address if bits are marked as optional Args: address_range (str): The address to expand Returns: list(str): A list of addresses this address has been expanded to """ if "X" in address_range: res = expand_address_ra...
25fb35b28541c5260b23b5829bf2c2ed2082fc86
659,241
def mandelbrotCalcRow(y, w, h, max_iteration = 1000): """ Calculate one row of the mandelbrot set with size wxh """ y0 = y * (2/float(h)) - 1 # rescale to -1 to 1 image_rows = {} for x in range(w): x0 = x * (3.5/float(w)) - 2.5 # rescale to -2.5 to 1 i, z = 0, 0 + 0j c...
21f285b9bc9da2888e95e190c2e32014162a519f
659,243
def mass_transfer_coefficient_mishra_kumar(wind_speed): """ Return the mass transfert coefficient [m/s] only from wind speed source:(Berry et al., 2012) Parameters ---------- wind_speed : Wind speed 10 meters above the surface [m/s] """ return 0.0025 * (wind_speed**0.78)
e65e035b0046c2e7fd351689a440e413ec8fc5c3
659,244
import time def mujoco_rgb_from_states(env, sim_states, time_delay=0.008): """ Given the states of the simulator, we can visualize the past Mujoco timesteps. - Simulator states are obtained via env.sim.get_state() """ rgb = [] for t in range(len(sim_states)): env.sim.set_state(sim_...
8988419cf2c4b981aa6bd611c40c06c031ddfe1d
659,247
def average(values): """Calculates the average value from a list of numbers Args: values (list) Returns: float: The average value""" if len(values) == 0: return None return sum(values)/len(values)
b5bd318e3e6dd0659aa3c62b1f28e3f6ce252015
659,248
import itertools def _group_insertions(sortedlist, keys): """ Given a list of keys to insert into sortedlist, returns the pair: [(index, count), ...] pairs for how many items to insert immediately before each index. ungroup(new_keys): a function that rearranges new keys to match the original keys. """ ...
ad51486e6e213db098c9549f6fa0817ef8a766b8
659,251
def ge(y): """ge(y)(x) = x > y >>> list(filter(ge(3), [1,2,3,4,5])) [3, 4, 5] """ return lambda x : x >= y
0a19da5e795b9b920e116ad6e25810b2e317ce9a
659,256
import struct def _read_header(data): """ Returns the header portion of the given data """ return struct.unpack('<BBBI', data[:7])
61324470885f1df613845cffce6300094acdeee0
659,257
def subListInSexp(sexp, xys): """Given a list of tuples of the form xys = [(x1, y1), ..., (xn, yn)] substitute (replace) `x` with `y` in `sexp` i.e. returns `sexp[y1/x1, ..., yn/xn]` """ d = dict(xys) if type(sexp) != list: return (d[sexp] if sexp in d else sexp) else: retur...
cfd90c1403a47c7b0a2266d09316350e87af24ef
659,258
def str2float(value: str): """ Change a string into a floating point number, or a None """ if value == 'None': return None return float(value)
00094612c7ea44bd68a7fb411fd22a7962a24874
659,261
def split_at(s: str, i: int): """Returns a tuple containing the part of the string before the specified index (non-inclusive) and the part after the index """ return (s[:i], s[i:])
a7a064c95c0fec94af03a1fa79c8225e0d9c4cf9
659,264
def octal_to_string(octal): """The octal_to_string function converts a permission in octal format into a string format.""" result = "" value_letters = [(4,"r"),(2,"w"),(1,"x")] for digit in [int(n) for n in str(octal)]: for value, letter in value_letters: if digit >= value: ...
3ed15831d37338e1e290f2e2afbeafd0a922e6a0
659,266
def item_at_index_or_none(indexable, index): """ Returns the item at a certain index, or None if that index doesn't exist Args: indexable (list or tuple): index (int): The index in the list or tuple Returns: The item at the given index, or None """ try: return i...
32ad95f8368067afe2966e04ec91d806344cc859
659,267
def dict_to_string(formula): """ Convert a dictionary formula to a string. Args: formula (dict): Dictionary formula representation Returns: fstr (str): String formula representation """ return ''.join(('{0}({1})'.format(key.title(), formula[key]) for key in sorted(formula.keys(...
48ac8fd9cec60e14e76417a12ce9c8ae22ef4052
659,268
def parse_color(color): """Take any css color definition and give back a tuple containing the r, g, b, a values along with a type which can be: #rgb, #rgba, #rrggbb, #rrggbbaa, rgb, rgba """ r = g = b = a = type = None if color.startswith('#'): color = color[1:] if len(color) == ...
f58331287e4ccc1f2459c1ffff4c0f3ec5f29d8b
659,269
def _parse_free_spaces(string): """ Parses the free spaces string and returns the free spaces as integer. Input example (without quotes): "Anzahl freie Parkpl&auml;tze: 134" """ last_space_index = string.rindex(" ") return int(string[last_space_index+1:])
21c599e7bc94d34d8dd6258d12443cc762d08cb2
659,270
from functools import reduce def flatten_shape(input_shape, axis=1, end_axis=-1): """ calculate the output shape of this layer using input shape Args: @input_shape (list of num): a list of number which represents the input shape @axis (int): parameter from caffe's Flatten layer @end_a...
4961d31ce6c40f2434a50f90e530226c9148ce5d
659,271
def int_def(value, default=0): """Parse the value into a int or return the default value. Parameters ---------- value : `str` the value to parse default : `int`, optional default value to return in case of pasring errors, by default 0 Returns ------- `int` the p...
b4394805007c9dcd8503d3062f76aa6840672604
659,272
def readline( file, skip_blank=False ): """Read a line from provided file, skipping any blank or comment lines""" while 1: line = file.readline() if not line: return None if line[0] != '#' and not ( skip_blank and line.isspace() ): return line
2350d9b5a8fbd449a1c70c8676865c15b4a56a4b
659,275
def compute_sum(v, fg): """Compute the sum of a variable v already marked to be summed. Sum over the given variable and update the factor connected to it. (akin to marginalization) Note that the variable v must have only one edge to a factor, so that the sum is forced to be a simple linear order c...
cbe5d2f1781a7fae65151c4f4d937269eef2ef59
659,276
def scan_cluster_parsing(inp, cluster_threshold_kruskal, cluster_threshold_beta, cluster_threshold_vip, cluster_threshold_vip_relevant, cluster_orientation, cluster_vip_top_number, cluster_mean_area, cluster_labelsize_cluster, cluster_figsize_cluster): """ Initialize cluster analysis. Initialization functi...
c2a9e3de143b5482c8c6ffb5274a6dd38e26fd99
659,277
from xdg.DesktopEntry import DesktopEntry def parse_linux_desktop_entry(fpath): """Load data from desktop entry with xdg specification.""" try: entry = DesktopEntry(fpath) entry_data = {} entry_data['name'] = entry.getName() entry_data['icon_path'] = entry.getIcon() en...
e3b43c3c1331bfee7f4dd244b8f8ba5344cefc09
659,279
import ssl def build_ssl_context(local_certs_file: str, ca_certs_file: str, key_file: str, ): """ :param local_certs_file: The filename of the certificate to present for authentication. :param ca_certs_file: The filename of the CA certificates as passed to ssl.SSLContext.load_verify_locations :param k...
1643fb82319e421ce87054f00d0a18a288e08dfa
659,280
import textwrap def to_curvedskip(of, to, angle=60, xoffset=0): """ Curved skip connection arrow. Optionally, set the angle (default=60) for out-going and in-coming arrow, and an x offset for where the arrow starts and ends. """ text = rf""" \draw [copyconnection] ([xshift=...
6e7ff9430d53690f327dec2da6da24be10a7c656
659,282
def extract_video_id_from_yturl(href): """ Extract a Youtube video id from a given URL Returns None on error or failure. """ video_id = None try: start = -1 if href.find('youtube.com/watch') != -1: start = href.find('v=') + 2 elif href.find('youtu.be/') != -1...
f5b31e11300abef58c1a3588c471f906c207a21f
659,288
def zone_bc_type_english(raw_table, base_index): """ Convert zone b/c type to English """ value = raw_table[base_index] if value == 0: return "NA" if value == 1: return "Direct" if value == 2: return "3WV" if value == 3: return "NA" if value == 4: ret...
d6fef02dd92ec1604b2bb892e6ad6dc00d5f889f
659,290
import uuid import hashlib def _create_token(user): """Create a unique token for a user. The token is created from the user id and a unique id generated from UUIDv4. Then both are hashed using MD5 digest algorithm. """ _id = f"{user.id}-{str(uuid.uuid4())}" _hash = hashlib.md5(_id.encode('as...
ea2458c45043ed9c0902b0a88d20c9c13ede00d0
659,292
def git_clone(repo, branch=None): """ Return the git command to clone a specified repository. Args: repo: string representing a git repo. branch: string representing a branch name. Returns: cmd: list containing the command line arguments to clone a git repo. """ cmd = [...
1f96df641285a98ad18e0de766c76f1ecc51c98c
659,293
def _extract_version(version_string, pattern): """ Extract the version from `version_string` using `pattern`. """ if version_string: match = pattern.match(version_string.strip()) if match: return match.group(1) return ""
5fcb5b60a7a3ae70ba2ad2c2bb7e9c92bf0db6d7
659,297
def prepend_dict_key(orig, prep_text, camel_case=False): """ Return a new dictionary for which every key is prepended with prep_text. """ if camel_case: return dict( (prep_text + str(k).title(), v) for k, v in orig.items() ) else: return dict((prep_text + str(k), ...
1c5ed248c24fe2b849451ef0f45bd88fa8d4556d
659,298
def int_check(input_value, warning_box): """Checks if input is a positive integer.""" try: int_value = int(input_value) if int_value > 0: warning_box.config(text="") return True else: warning_box.config(text="Please type a positive integer.") return False except ValueError: warning_box.config(tex...
bbd606380625b6ba8bd7195680feac49aa4e33d5
659,299
def is_win(matrix): """ is game win? return bool """ for item_list in matrix: if 2048 in item_list: return True return False
c5a77933037064f8330963ce8fe4cc49db8c909c
659,303
import sqlite3 def get_twinkles_visits(opsim_db_file, fieldID=1427): """ Return a sorted list of visits for a given fieldID from an OpSim db file. Parameters ---------- obsim_db_file : str Filename of the OpSim db sqlite file fieldID : int, optional ID number of the field ...
791f779cfba6125eaf7efea1930c6373f71e3efe
659,305
import string import random def random_string(string_length=20, punctuation=True): """ Create a random string that is quotable. Usable for basic passwords. Args: string_length - (optional) The number of characters to generate punctuation - (optional) True if the generated characters shoul...
09224f0dd520832eda6538d865e22f7446b92f5a
659,307
from pathlib import Path import json def read_authors(filename): """Read the list of authors from .zenodo.json file.""" with Path(filename).open() as file: info = json.load(file) authors = [] for author in info['creators']: name = ' '.join(author['name'].split(',')[::-1]).s...
b79602070a27495aa7bed3b5f004aece2e1ead29
659,309
import torch def get_center_block_mask(samples: torch.Tensor, mask_size: int, overlap: int): """ Mask out the center square region of samples provided as input. Parameters ---------- samples: torch.Tensor Batch of samples, e.g. images, which are passed through the network and for which sp...
9f020a5ce4f1128b3112e8106a9facd82e1af124
659,310
import re def hex2rgb(hex_code: str) -> tuple: """ Convert color given in hex code to RGB in ints. Result is returned inside 3-element tuple. :param hex_code: :return: tuple (R, G, B) """ pattern = re.compile(r'^#?[a-fA-F0-9]{6}$') if not re.match(pattern, hex_code): raise ValueEr...
ae855676d25c320a47ad6ee64e4669ea23e50a1d
659,311
def eh_posicao(pos): # universal -> booleano """ Indica se certo argumento e uma posicao ou nao. :param pos: posicao :return: True se o argumento for uma posicao, False caso contrario """ # uma posicao e um tuplo com dois elementos em que ambos variam de 0 a 2 if type(pos) != tuple or len(p...
036e6ce48b8c96dd2732d828225e84ceceb73a95
659,312
def _choose_num_bootstraps(sample_size, mean_size, fuel): """Choose how many bootstraps to do. The fuel is the total number floats we get to draw from `np.random.choice`, which is a proxy for the amount of time we're allowed to spend bootstrapping. We choose how many bootstraps to do to make sure we fit in ...
69f18667c5df7c2d3017a3ca8d573eb2e631731c
659,313
def add_totals_to_dataframe(df, row_name="Row total", col_name="Column total"): """Add row and column totals to dataframe""" df.loc[row_name]= df.sum(numeric_only=True, axis=0) df.loc[:,col_name] = df.sum(numeric_only=True, axis=1) return df
8babbf24ff436be9b0b1c36461c86961118f3478
659,315
import torch def segment2distance(points, segment, max_dis=None, eps=0.1): """Encode segment based on distances. Args: points (Tensor): Shape (n,), [center]. segment (Tensor): Shape (n, 2), "start, end" format max_dis (float): Upper bound of the distance. eps (float): a small ...
2d6c499b3eaa80a369724281382a1c36f73c5e61
659,317
def CreateOnHostMaintenanceMessage(messages, maintenance_policy): """Create on-host-maintenance message for VM.""" if maintenance_policy: on_host_maintenance = messages.Scheduling.OnHostMaintenanceValueValuesEnum( maintenance_policy) else: on_host_maintenance = None return on_host_maintenance
5daaf3baf6e2b33066e8febebd15a54402e1f081
659,318
import posixpath def ls(session, path): # pylint: disable=invalid-name """ List files on an iRODS server. Args: session (iRODS.session.iRODSSession): iRODS session path (String): path on iRODS server to list. Must be absolute. """ coll = session.collections.get(po...
4228d65551b9206b619c92cccd56a3d406327d9a
659,319
from typing import Mapping from typing import Optional from typing import Any from functools import reduce def get_value_by_dot_notation(dict_obj: Mapping, key: str, default: Optional[Any] = ...) -> Any: """ Return the value of a key in dot notation in a arbitrarily nested Mapping. dict_obj: Mapping k...
541438295d03ac7d987584c6a219158b12062bc3
659,320
import hashlib def get_md5_checksum_of_file(file_path): """ Get the md5 checksum of the local file. """ return hashlib.md5(open(file_path, 'rb').read()).hexdigest()
49dee23ed967c9c6b9a35260b9096a757ff9cc1f
659,321
def lF_value (ER,EF,dfnum,dfden): """ Returns an F-statistic given the following: ER = error associated with the null hypothesis (the Restricted model) EF = error associated with the alternate hypothesis (the Full model) dfR-dfF = degrees of freedom of the numerator dfF = degrees o...
063710899786bc7e5872a2980647f0b14a186183
659,322
def clamp(a, x, b): """ Ensures x lies in the closed interval [a, b] :param a: :param x: :param b: :return: """ if x > a: if x < b: return x else: return b else: return a
3c36572de64e4ecdaca0b9bd73a49ac04b088437
659,325
def calc_sidak_correction(alpha_value, num_total_tests): """ Calculates the Sidak correction for multiple hypothesis testing for a given alpha-value. See http://en.wikipedia.org/wiki/Bonferroni_correction#.C5.A0id.C3.A1k_correction for more detail. Returns the Sidak corrected p-value upon ...
5b9eb37930167ba01f441fc240add2f8035ed22d
659,326
def fuel_requirement(mass: int) -> int: """Base fuel requirements for a single module.""" return (mass // 3) - 2
fec5f5ca44a2b3f26f0f6578338bfbe07308c495
659,327
def kph2ms(v): """ This function converts velocity from kph to m/s. """ return v / 3.6
85e8f03030ee80ed5cb531ec8d142761edd9a72e
659,335
import importlib def _import_func(dotted_str): """ Imports function using dot-notation string. :param dotted_str: Dotted path to function like `module.submodule.func` :return: func """ module_name, factory = dotted_str.rsplit('.', 1) module = importlib.import_module(module_name) try: ...
5c09ff9e81fe91f98b8376bc3d6d8eebbddeb0aa
659,336
import random def weighted_choice(weight): """ Parameters ---------- weight: float Weight of choosing a chromosome Returns ------- Bool random (not uniform) choice """ # This help to don't generate individuals of the same size on average p = random.uniform(0, weig...
7a5a39f726ddef22110aa9a4c8821a0c6b5e278a
659,339