content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Mapping def is_mapping(obj): """Check if object is mapping.""" return isinstance(obj, Mapping)
6c0934c3331d65ee6ffdab79b9502acb00e8b968
651,674
import torch def full_pose_3d(pose): """Expand (B, 12) pose to (B, 4, 4) transformation matrix.""" shape = list(pose.shape[:-1]) shape += [3, 4] pose = torch.reshape(pose, shape) zeros = torch.zeros_like(pose[..., :1, 0]) last = torch.stack([zeros, zeros, zeros, zeros + 1], -1) full_pose = torch.ca...
5584148de473496db28d687efdf51b58fa6bd0ce
651,676
import six def unpack_dd(buf, offset=0): """ unpack up to 32-bits using the IDA-specific data packing format. Args: buf (bytes): the region to parse. offset (int): the offset into the region from which to unpack. default: 0. Returns: (int, int): the parsed dword, and the number of ...
478ea18629c1ce3f5c4b461dd4fd21cdd4938f6d
651,677
import shlex def shell_split(st): """ Split a string correctly according to the quotes around the elements. :param str st: The string to split. :return: A list of the different of the string. :rtype: :py:class:`list` >>> shell_split('"sdf 1" "toto 2"') ['sdf 1', 'toto 2'] """ ...
30f5ce93aa58d1c984eb2562293f9e7009f9e041
651,678
def to_millis(secs, nanos): """Combine seconds and nanoseconds and convert them to milliseconds.""" return 1000 * secs + nanos / 1000000
0c09b48e038de4c216f02bee1cd0f5e1ea64fc45
651,682
def split_by_label(data, targets, labels): """ Given a data matrix and the targets for the data, the method splits the data by class :return: a dict with the data separeted by label, each label is a key of the dict """ d = dict() for cl in labels: d[cl] = data[targets == cl] return d
ba3521b2833897790b81d7818672a2dae70c258a
651,685
def expected_count(af, effective_mutation_rate): """Calculate the expected number of somatic variants greater than a given allele frequency given an effective mutation rate, according to the model of Williams et al. Nature Genetics 2016""" return effective_mutation_rate * (1.0 / af - 1.0)
92a6802df93260777d9ecdd90376ba03495e6400
651,687
def cycspec(self, label="", node="", item="", comp="", **kwargs): """Defines the set of result items for a subsequent CYCCALC command in APDL Command: CYCSPEC postprocessing a cyclic harmonic mode-superposition analysis. Parameters ---------- label One of the following labels: ...
4a8d0f6d6bbb55e9b7c23689f9db5aa9b0e3554d
651,690
def add_to_existing_groups(no_people, existing_groups, max_size): """ Attempts to add the given number of people to the list of existing groups without exceeding the maximum group size. Modifies the list of existing groups. Returns the number of people remaining after the attempt. ...
7b9b0c4f0318d3d873f9a2d6288bcee63966b944
651,691
def stci(ds): """Calculate the Subtropical Cell Index (STCI) according to Duteil et al. 2014 Parameters ---------- ds : xr.Dataset Input dataset. Needs to have a variable `psi` which represents the meridional mass overturning streamfunction Returns ------- xr.Dataset The ST...
8a02306c4ddd04e09bfa15ebe47b29a11edf449a
651,695
def applyOrderList(order, aList): """ Apply order to aList. An order of the form [2,0,1] means that the first element should be the 3rd element of aList, and so on. """ if order==[]: return aList else: return map(lambda v:aList[v], order)
4daacf5ee553cd57aa0e6b38e621f28505d26cfa
651,702
def rec_repr(record): """Return the string representation of the consumer record. :param record: Record fetched from the Kafka topic. :type record: kafka.consumer.fetcher.ConsumerRecord :return: String representation of the consumer record. :rtype: str | unicode """ return 'Record(topic={},...
c0046b7450d7d025cd0c2e41252ae58b5658b744
651,704
def standard_rb(x, baseline, amplitude, decay): """ Fitting function for randomized benchmarking. :param numpy.ndarray x: Independent variable :param float baseline: Offset value :param float amplitude: Amplitude of exponential decay :param float decay: Decay parameter :return: Fit function...
60d67143e16307ebd2fa8581d269570590ae6774
651,705
import math def num_buses(n): """ (int) -> int Precondition: n >= 0 Return the minimum number of buses required to transport n people. Each bus can hold 50 people. >>> num_buses(75) 2 >>> num_buses(100) 2 >>> num_buses(101) 3 >>> num_buses(1) 1 >>> num_buses(0) ...
b22e49655ba7170070f00634cc47117124a5c88d
651,706
import pathlib def list_images(directory): """Generates a list of all .tif and/or .tiff files in a directory. Parameters ---------- directory : str The directory in which the function will recursively search for .tif and .tiff files. Returns ------- list A list of pathlib...
a174b30328dde171e6e15d59abaddd14be50defb
651,707
def d2dms(d, delimiter=':', precision=6): """ Convert decimal degrees to dd:mm:ss """ inverse = '' if d < 0: inverse = '-' minutes, seconds = divmod(abs(d) * 3600, 60) degrees, minutes = divmod(minutes, 60) return '{0:s}{1:.0f}{4}{2:02.0f}{4}{3:0{5:d}.{6:d}f}'\ .format(i...
0d4289965431fbec87f164a7541a8bd4e5f5a27e
651,713
def lookup(collection, key): """ Lookup a key in a dictionary or list. Returns None if dictionary is None or key is not found. Arguments: dictionary (dict|list) key (str|int) Returns: object """ if collection: try: return collection[key] except ...
9f714f80d7846ceb6b25fa486ed501ccd5bac2da
651,719
from typing import Optional def _find_mark(instrumented_config: dict, path: str) -> Optional[dict]: """ Find mark in instrumented config by path :param instrumented_config: { field1: 'a', field2: 'b', '__line__': 0, '__field1__': { 'start': {'line': 1, 'column': 1}, 'end': {...} }} :param ...
54d9b444afc5ad2da6042d71e2a209a5ad0dcd25
651,720
from typing import List from typing import Any from typing import Dict def transformUserIDs(userID: str, args: List[Any]) -> str: """Transform user IDs.""" userIDMap: Dict[str, str] = args[0] return userIDMap[userID]
de417dd886325f41ef37010f88e80e6ada429db8
651,721
def abbrev_timestr(s): """Chop milliseconds off of a time string, if present.""" arr = s.split("s") if len(arr) < 3: return "0s" return arr[0]+"s"
e0e49fa0489a351e21ea8f1076bf234d54dd8da2
651,723
import json def read_template(template): """ Read and return template file as JSON Parameters ------------ template: string template name returns: dictionary JSON parsed as dictionary """ data = None with open(template) as data_file: data = json.load(data...
9708b1947998301ae2426bf30d375feb915bba3e
651,724
def _check_empty_script(filename, message, expect_fail): """Returns a script check that checks for empty diagnostics in a file. Args: filename: name of file containing diagnostic output. message: message to print when there are unexpected findings. message may be multiline. expect_fai...
982ce1cdef9e729c079aa74a9a692af2cdb32fc2
651,726
def project(position_current, velocity_current, acceleration_current, use_acceleration, delta_t): """ This module estimates the projected position of a particle. :param position_current: The position of the particle at time "t". It must be a numpy array. :param velocity_current: The velocity of the par...
41f49f90eb2eacbad8ec3b68bbe75a9eef47b8c3
651,729
def calc_salary(s_from, s_to): """Calc salary. First modify salary to get 'from', 'to' :param s_from: int, salary from :param s_to: int, salary to :return: int or None, size of salary by 'from' and 'to' """ if (s_from is not None and s_to is not None): return (s_from + s_to) / 2 ...
f9468e9f0c0db67bee7fa2285e5662f04dacfb62
651,730
def upsert_record(client, zoneid, record_name, value, record_type='A', ttl=300): """Updates or Creates the specified AWS Route 53 domain resource record Parameters ---------- client: boto3.client The boto3 'route53' client to utilize for the update request zoneid: str The Route 53 H...
e71cf391dfa2093f74929c6fecd9c36b5af622c6
651,732
def check_for_age_range(child_age, age_range): """ check if input child age is in the query's age range :param child_age: the age to check (int) :param age_range: the age range (list) :return: True if the age is in the range, else False """ return True if min(age_range) <= child_age <= max(a...
6d86cc56b57a0148d2736c97c30b123ed2a4166b
651,735
def get_padded_filename(num_pad, idx): """ Get the filename padded with 0. """ file_len = len("%d" % (idx)) filename = "0" * (num_pad - file_len) + "%d" % (idx) return filename
91ccb54951ea091603c5fbacb4f28013fa371e51
651,736
def decSinglVal(v): """Return first item in list v.""" return v[0]
747f66d136428461001ea76a1727865f46331c1e
651,738
import re def get_variable(config_text, variable): """ Get the value of a variable in config text :param config_text: str :param variable: str :return: value """ pat = re.compile(variable) for line in config_text.splitlines(): altered_line = line if pat.match(line): ...
506239777f3c23d9e6f617ae564f8489542e08c7
651,745
def dummy_dataset_paths_no_valid(tmpdir_factory): """Creates and returns the path to a temporary dataset folder, and train, and test files. """ # create a dummy dataset folder dummy_dir = tmpdir_factory.mktemp('dummy_dataset') # create train, valid and train partitions in this folder train_file ...
b73d73c0ac46498565ca6bba410b2d48089703d5
651,746
def _vector_neg(x): """Take the negation of a vector over Z_2, i.e. swap 1 and 0.""" return [1-a for a in x]
73f447f8ea5c8f9749a6a68d576aacbc11b1ad1c
651,748
def get_children(self): """ Creates a ``QuerySet`` containing the immediate children of this model instance, in tree order. The benefit of using this method over the reverse relation provided by the ORM to the instance's children is that a database query can be avoided in the case where the ins...
dba97203d8ef630b1fb6cef0a9977d0100f1d24f
651,749
def _grad_j(q_j, A_j, b_j, b_j_norm, a_1_j, a_2_j, m): """Compute the gradient with respect to one of the coefficients.""" return (A_j.t() @ q_j / (-m)) + (b_j * (a_1_j / b_j_norm + a_2_j))
d051883d848386af9eeb40a10029351158b075c0
651,750
def perimeter_square(length): """ .. math:: perimeter = 4 * length Parameters ---------- length: float length of one side of a square Returns ------- perimeter: float perimeter of the square """ return length * 4
07b8eefed384636a254c1ca84d861bebf80782ec
651,751
from typing import Union def game_of_life_rule(cell: bool, neighbors: int) -> Union[bool, None]: """Classic rule of John Conway's Game of Life.\n Common notation: `B3/S23`. """ # A low cell switches to high state if is has 3 neighbors if not cell and neighbors == 3: return True # A hig...
9e5c2ee31842ab397f4b3c62367732d006463eea
651,756
import csv def write_dataset(dataset, dataset_file: str) -> bool: """ Writes a dataset to a csv file. Args: dataset: the data in list[dict] format dataset_file: str, the path to the csv file Returns: bool: True if succeeds. """ assert len(dataset) > 0, "The anonymized dat...
6082f29ab2a87ad62b4b944ff55483da62989004
651,760
import random def modify_rate(rate, change): """ Calculate a random value within change of the given rate Args: rate: the initial rate to change from change: the maximum amount to add or subtract from the rate Returns: random value within change of the given rate Explanati...
09f3f47de58de786b06584bde80be56367c61435
651,763
import unicodedata def _preprocess_text(inputs, lower=False, remove_space=True, keep_accents=False): """Remove space, convert to lower case, keep accents. Parameters ---------- inputs: str input string lower: bool If convert the input string to lower case. remove_space: bool ...
47e256fb5640c14467038e514efdf6f0372d59cf
651,768
def make_ordinal(n): """ Convert an integer into its ordinal representation:: make_ordinal(0) => '0th' make_ordinal(3) => '3rd' make_ordinal(122) => '122nd' make_ordinal(213) => '213th' """ n = int(n) suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)] if...
fc66f85d6f1d745b89f7e89f3684365e92305b53
651,769
def generate_data(function, xdata, func_params): """Create a data set using a given function and independent variable(s). Parameters ---------- function : callable A function to use to generate data points from input values. xdata : array_like An array of values of shape (N, M) wher...
2aaa7bf0f46a3c6ede360b46cf873e2a1aa844da
651,772
def to_camel_case(input_string): """ Based on https://stackoverflow.com/a/19053800 Args: input_string (str): Returns: (str): """ if "-" in input_string: components = input_string.split('-') elif "_" in input_string: components = input_string.split('_') e...
a5e2676baf92ddf1f52a371732fa4697c067e3c3
651,773
def compare_graphs(before, after): """ Compare two (sub)graphs. Note: a == b != b == a! :param before: A networkx (sub)graph. :param after: A networkx (sub)graph. :returns: A dict with changes. """ res = {'added': [], 'removed': [], 'added_edge': [], 'r...
ee89a35da1bb74a42c93787ec138ee416a04c831
651,777
import re from typing import Counter def extract(text_list, regex, key_name, extracted=None, **kwargs): """Return a summary dictionary about arbitrary matches in ``text_list``. This function is used by other specialized functions to extract certain elements (hashtags, mentions, emojis, etc.). It can ...
0b7c0caa736bd68ffe7497dc3f4526735968b385
651,778
import hashlib def hash_sha512(*indata): """Create SHA512 hash for input arguments.""" hasher = hashlib.sha512() for data in indata: if isinstance(data, str): hasher.update(data.encode('utf-8')) elif isinstance(data, bytes): hasher.update(data) else: ...
e301dd99d91ea57388f8e165791b4e822ca0c582
651,779
import typing def read_exact(stream: typing.BinaryIO, byte_count: int) -> bytes: """Read byte_count bytes from the stream and raise an exception if too few bytes are read (i. e. if EOF was hit prematurely). :param stream: The stream to read from. :param byte_count: The number of bytes to read. :return: The read...
29f9d5659a6a55191ee4ba5ae5f1ee1c9f03da3d
651,783
def CEN_misclassification_calc( table, TOP, P, i, j, subject_class, modified=False): """ Calculate misclassification probability of classifying. :param table: input matrix :type table : dict :param TOP: test outcome positive :type TOP : in...
239f11c109a86bddfef3e44df8b05690ce6bfcae
651,787
def _transpose(mat): """ Transpose matrice made of lists INPUTS ------ mat: iterable 2d list like OUTPUTS ------- r: list of list, 2d list like transposed matrice """ r = [ [x[i] for x in mat] for i in range(len(mat[0])) ] return r
ce884d2f0a0f2a43ec87a6955a4a0d8499fce846
651,788
def getFileData(fileName): """ Open a file, and read the contents. The with..open operation will auto-close the file as well. """ with open(fileName) as handle: data = handle.read() return data
b9f8f58246ee59e4377acd60d5a4d3fe2244914c
651,789
def scale_to(x, from_max, to_min, to_max): """Scale a value from range [0, from_max] to range [to_min, to_max].""" return x / from_max * (to_max - to_min) + to_min
e48e1f6556ee39fbdbba3cf2aa62e4efbcefba1c
651,793
def int_to_bits_indexes(n): """Return the list of bits indexes set to 1. :param n: the int to convert :type n: int :return: a list of the indexes of bites sets to 1 :rtype: list """ L = [] i = 0 while n: if n % 2: L.append(i) n //= 2 i += 1 ...
03f14c3eaca1f45090de94e1884ad207d6f4a502
651,794
def getDistances(digraph, path): """Returns total & outdoor distances for given path.""" total_dist = 0 outdoor_dist = 0 for i in range(len(path) - 1): for node, edge in digraph.edges[path[i]]: if node == path[i + 1]: total_dist += edge.getTotalDistance() ...
c0578d7254cb78425e460348876f9d773c7d8d0a
651,797
def header_format(morsels): """Convert list of morsels to a header string.""" return '; '.join(f'{m["name"]}={m["value"]}' for m in morsels)
727c794a095d1e7714047f4fa219aeb4b32e63fe
651,798
def app_name_from_ini_parser(ini_parser): """ Returns the name of the main application from the given ini file parser. The name is found as follows: * If the ini file contains only one app:<app name> section, return this app name; * Else, if the ini file contains a pipeline:main section, us...
1d68cbcd036a6c5ff89728e427e073bee3d99356
651,801
def smoothbknpo_n(x, p): """ Generalised smooth broken power law. Note: for p[4] == 2 the function is the same as 'smoothbknpo' Args: x: (non-zero) frequencies. p[0]: Normalization. p[1]: power law index for f--> 0. p[2]: power law index for f--> oo. ...
7fcad3273f97323c48475a7f79912f5af1b09d13
651,802
def rep0(s): """REGEX: build repeat 0 or more.""" return s + '*'
6d92f89d3707452e0ca71e73db318bd9c9b79838
651,803
def get_axes(self): """Return axes list. Parameters ---------- self: DataND a DataND object Returns ------- axes_list """ return self.axes
12a89faa91d932abf614e3ab8d8813174c6e83c6
651,805
import math def euclidean_distance_native(u, v): """Computes the Euclidean distance between two vectors, represented as Python lists. Args: u (List[float]): A vector, represented as a list of floats. v (List[float]): A vector, represented as a list of floats. Returns: float: ...
df39309f463ffe1901831cbf32eab142caaad0f0
651,807
def del_pos(s): """ Deletes part-of-speech encoding from an entity string, if present. :param s: Entity string. :return: Entity string with part-of-speech encoding removed. """ if s.endswith("/n") or s.endswith("/a") or s.endswith("/v") or s.endswith("/r"): s = s[:-2] return s
ee0930ce32b8e32893fff5bfe25cd67712ae7f2b
651,808
def _sortValue_familyName(font): """ Returns font.info.familyName. """ value = font.info.familyName if value is None: value = "" return value
58d85b95eff2a6ac1a5958456d87aa7a03350df6
651,812
import builtins def builtin_target(obj): """Returns mock target string of a builtin""" return f"{builtins.__name__}.{obj.__name__}"
0e21e170897a2b7a2f757bd54cf6392f03660db3
651,813
from functools import reduce def bits_to_int(list_): """ Converts a big-endian bit string to its integer representation. >>> bits_to_int([1, 0, 1]) 5 """ return reduce( lambda a, x: a | (1 << x[1]) if x[0] == 1 else a, zip(list_, range(len(list_) - 1, -1, -1)), 0, ...
b555eb7fb3482dfaebf762d5a3a502ad62d23252
651,816
def tier_from_site_name(s): """ Splits site name by _ (underscore), and takes only the first part that represents tier. """ split = s.split('_') tier = str(split[0]) return tier
9fb6c531ee413b0a8411d1568d4058572d408a35
651,819
def _get_line_index(line_or_func, lines): """Return the appropriate line index, depending on ``line_or_func`` which can be either a function, a positive or negative int, or None. """ if hasattr(line_or_func, '__call__'): return line_or_func(lines) elif line_or_func: if line_or_func ...
ed82c9d84d25e6f6cdb7a5738bc8498a93bbe09a
651,820
def ToString(bval): """Convert a bytes type into a str type Args: bval: bytes value to convert Returns: Python 3: A bytes type Python 2: A string type """ return bval.decode('utf-8')
978284dcb33bbf3449eed76ba7e0e320305477e7
651,825
def parse_image_size(image_size): """Parse "100x100" like string into a tuple.""" return tuple(map(int, image_size.split("x")))
2712ab9b756db2a2b62ef908b34404d6dc4fd410
651,826
def unwrap_model(model_wrapper): """Remove model's wrapper.""" model = model_wrapper.module return model
ea184f522350e726786961182ccde24e246c6e5e
651,829
import torch def torch_multinomial(input, num_samples, replacement=False): """ Like `torch.multinomial()` but works with cuda tensors. Does not support keyword argument `out`. """ if input.is_cuda: return torch_multinomial(input.cpu(), num_samples, replacement).cuda() else: ret...
bed9ac316c6f54f429d3da86a91d2337cd3b4e22
651,830
def dna_2_rna(dna_str): """ Transcribes DNA into RNA RNA differs from DNA in that it contains a base called uracil in place of thymine. An RNA string is formed by replacing all occurrences of 'T' in the DNA string with 'U'. Params: ------- dna_str: (str) DNA string. For example: "GATGGAACTTGACTACGTAAATT"...
420b6de3def169d43618a18cdc86f119c4b7fae3
651,833
def _translation_vectors(mtps, vector_table): """For a set of maximally translatable patterns, returns the set of translation vectors for the MTPs. Finds the common translation vectors for each note of a MTP, enabling finding all occurrences of the MTP. Args: mtps: All MTPs of a point set vector_table: Vecto...
5a78fb74d7d8792e030de94a1ca9d07d16abd98f
651,834
import re def __get_auth_api_url(module, url): """ Return the parsed URL of the specific authentication API. :param AnsibleModule module: the ansible module :param str url: the initial URL of API :rtype: str """ # format the input for zmd_port if module.params['zmf_port'] is None: ...
92b7fa2a71140b100d5d38ec78bae45d4076cd05
651,836
def calc_temp_overlap(start_1, end_1, start_2, end_2): """ Calculate the portion of the first time span that overlaps with the second Parameters ---------- start_1: datetime start of first time span end_1: datetime end of first time span start_2: datetime start of se...
2fa9882a90628056fba615c58f2ad8907c4d8315
651,837
import socket def is_port_in_use(port: int) -> bool: """ Check if a porty is in use. """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(('localhost', port)) == 0
201cbfa3458b1002d975b2abca6b8908ea387e29
651,840
def process_fieldmap_solrf(data): """ Processes array of raw data from a rfdataX file into a dict. From the documentation: Here, the rfdataV5 file contains the Fourier coefficients for both E fields and B fields. The first half contains E fields, and the second half contains B fields. See m...
4d4aacd0153368c2fbc9938b03e6e0cd51ab419e
651,842
def utf8(s): """Convert to UTF-8.""" return s.encode("UTF-8")
7d532c16d144fd307f3a38cb4ec5785c4a95de64
651,844
def element_is_scrolled_to_left(element): """ Is the element scrolled to the left? :param element: :return: Boolean """ return int(element.get_property('scrollLeft')) == 0
3d77d1ec73e86ab87811ffde95d3cc2a14e2c90f
651,845
import pathlib def as_uri(path): """ Converts the supplied path to file URI :param path: Path to be converted :return: Path as a fille URI """ p = pathlib.Path(path) return p.as_uri()
172428ffb0e54159d73d8479598e652b7530e09f
651,846
def parse_proasis(input_string): """ Parse proasis contact strings :param input_string: the Proasis contact string to parse :return: a tuple of res_name, res_num, chain_id """ return ( input_string[:3].strip(), int(input_string[5:].strip()), input_string[3:5].strip(), ...
628679e3f8ca4b06ff3dea8429bec623f7dc610c
651,848
import torch def _tuple_splice_range(inputs, start, end): """ Splices each tensor element of given tuple (inputs) from range start (inclusive) to end (non-inclusive) on its first dimension. If element is not a Tensor, it is left unchanged. It is assumed that all tensor elements have the same first...
97cda7293986e72650432eeba679bb3e84eb09a4
651,851
import uuid def is_uuid(id): """Verify if a string is an UUID""" try: v = uuid.UUID(id) except ValueError: v = None return isinstance(v, uuid.UUID)
d00c0633d308c95755eeefc6d55218dd173653fa
651,853
import secrets def pick(s, n): """Return a string with n randomly picked characters from string s.""" return "".join(secrets.choice(s) for i in range(n))
4a04fcf7b0175f7406a52237b43c906b54bfdb70
651,856
import json import re def uri_twitch(bot, response, matches): """ Extract Twitch.tv channel information. """ channel = json.loads(response.text) title = channel['status'].replace('\n', ' ') title = re.sub(r'\s+', ' ', title).strip() game = channel['game'].replace('\n', ' ') game = re.sub(r'\s...
b211c9fbd4fc3074125c0b7e6cf488c0ca251be7
651,861
def delete(flavor_id, **kwargs): """Delete flavor.""" # NOTE: flavor_id can be any string, don't convert flavor name to uuid url = '/flavors/{flavor_id}'.format(flavor_id=flavor_id) return url, {}
46208cf3bd57f297626f19d1f3e72de490db22e0
651,864
def compute_denominator(log_strike, variance, deriv_1, deriv_2): """ Compute denominator in local vol equation. Args: log_strike: The log-strike. variance: The variance. deriv_1: The first derivative of variance wrt log strike. deriv_2: The second derivative of variance wrt...
ad34e8a7390878ebfba9c12701e83d76f00fcfbc
651,865
def _LookupTargets(names, mapping): """Returns a list of the mapping[name] for each value in |names| that is in |mapping|.""" return [mapping[name] for name in names if name in mapping]
03a038150f7f757a99e9cfbb9cdaf6e98f441d57
651,868
import requests def connect_to_endpoint(url, headers): """Fetches latest information of a Twitter handle Args: url: URL to make a GET call headers: Headers need for authentication Returns: List of tweets in json format """ response = requests.request("GET", url, headers=he...
f66b9079c72956dbca1be1be92015a065f0e157c
651,869
def rotate(x, y, ctx, cty, ang) : """ Rotate catalog x,y against center (ctx,cty), using specified rotate angle args: x: ndarray of x, or scalar y: ndarray of y ctx: center x, scalar cty: center y ang: rotate angle, 0-7 0 keep original 1 CW 90 deg ...
540376d71d41d18b0126706222e63fef1020c72b
651,870
def rank_order(df, rank_column, ascending=False): """ Given dataframe with a column of numerical values, order and rank those values. Allows for ties if a value is the same as the previous value. """ df = df.sort_values(rank_column, ascending=ascending).reset_index().drop('index', axis=1) ranki...
0797fe1d2ff9029241ed50eef0b454ac4a3ec30b
651,879
import copy def get_descendants(node, include_self=True): """ Return a flat list including `node` and all its descendants. Nodes returned are modified to remove the tree structure between them (set `children=[]`). """ results = [] if include_self: node_copy = copy.deepcopy(node) ...
0c6f2ac11eb2a8f636da63b3a7b3853f79fe0324
651,881
def get_max_value(array): """ Finds (the first occurence of) maximum value in a 1D array. :param array: 1D array (there is no safety check on that) :return: (index, value) index Index of the maximum element. value Value of the maximum element. """ max_val = max(array) ...
ff4103d209dfd45606404cad6226d0e3424f0670
651,896
def add_lowercase_context_to_sequences(seq, uc_s, uc_e, convert_to_rna=False): """ Given a sequence and uppercase middle region start (uc_s) and end (uc_e), make context region upstream + downstream lowercase. Two coordinates should be one-based. Return lowerca...
8fff58cb27fb03059b4323458d5e744443f6559d
651,898
from pathlib import Path import re def guess_file(path: Path) -> str: """Guess the type of a file and return the corresponding file extension.""" lines = path.read_text().splitlines() MAX_LINES = 500 # noqa: N806 f77ish = True f90ish = False for i, line in enumerate(lines): if i >=...
f23ad6217ca06730c0f7b802f3fab78f54615b02
651,899
def check_model_termination(ClockStruct,InitCond): """ Function to check and declare model termination *Arguments:*\n `ClockStruct` : `ClockStructClass` : model time paramaters `InitCond` : `InitCondClass` : containing current model paramaters *Returns:* `ClockStruct` : `ClockStructC...
6e25a41a92b64b13f3d2db424a9fbe082d31bf24
651,908
def gtk_false(*args): """ GTK False default handler """ return False
0d99aa7fb121e3210d1bd3401aa15b48238a7da4
651,916
def int_or_none(value): """ Returns int or none if int could not be converted """ try: return int(value) except ValueError: return None
7bc702089d855fd9859dce0aca1c1e36628faf0e
651,918
def avg_item_count_character(cursor): """Returns the average number of items per character from sqlite cursor. Args: cursor (sqlite3.Cursor): cursor to sqlite database Returns: (float) Average number of items per character """ return cursor.execute("""SELECT AVG(item_ct) FROM( ...
4d3a7ebbd07fec822fd609e6cee7ddfde79cb7e5
651,921
def parse_uri(uri): """Extracts the host, port and db from an uri""" host, port, db = uri, 6379, 0 if len(host.split('/')) == 2: host, db = host.split('/') if len(host.split(':')) == 2: host, port = host.split(':') return host, int(port), int(db)
52750de603818952530b9418441130d69ce40d1a
651,922
def distribution_to_particle(predictions, n_particles=50): """ Convert a distribution prediction to a particle prediction Args: predictions (Distribution): a batch of distribution predictions. n_particles (int): the number of particles to sample. """ return predictions.sample...
cc4c9dbb9d735db5e094e87c177156717bbf3a6c
651,924
def nulls(data): """Returns keys of values that are null (but not bool)""" return [k for k in data.keys() if not isinstance(data[k], bool) and not data[k]]
0dcdd0f98467e85bc99b8d9ffb2a45e25172f82a
651,929
def _process_ratios(value): """Helper function to convert the GPS ratios in float format""" return float(value[0])/float(value[1])
3066a891014a38954d45587ca067ec4e6a224904
651,931
def normalize_path(path): """ Returns a normalized path from a `path` string. """ return "/" + path.strip("/")
fd7e4956bb09e048b32670b6050f51fa3183431b
651,932