content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
from typing import Tuple import ipaddress def validate_ipv4_net(network: str) -> Tuple[bool, str]: """ Checks if string is a valid IPv4 network :param network: string representation of IPv4 network :return: tuple of (bool, str). (True, msg) if valid; (False, msg) if invalid """ try: ipaddress.IPv4Network(network) except (ipaddress.AddressValueError, ipaddress.NetmaskValueError, ValueError) as e: valid = False msg = "Provided string is not a valid network: {}.".format(e) else: valid = True msg = "String is a network." return valid, msg
53908b5907eb52b2249edf1a03aa26bba6ebba56
542,082
import struct def serialize_port(port): """Serializes a port number according to the DNSCrypt specification""" return struct.pack('!H', port)
51463af3eea8161d96110a71e59af7c4ebbe18de
321,535
def check_int(school, international): """ Checks if a school is an international school based on a school list and other criteria Parameters ---------- school: current school being checked international: AP/IB school list Returns ------- Y or N """ # list of criteria that could qualify a school as an international school even if it is not on the school lists int_criteria = ["International Baccalaureate", "IBDP", "IB", "IB Score", "A Level", "A-Level", "French Baccalaureate", "A Levels", "A*"] school_name = school['name'] degree_name = school['degree'] if degree_name is None: degree_name = '' field_of_study = school['field_of_study'] if field_of_study is None: field_of_study = '' grades = school['grades'] if grades is None: grades = '' if any(element.lower() == school_name.lower() for element in international["AP"]): int_hs = 'Y (AP)' elif any(element.lower() == school_name.lower() for element in international["IB"]): int_hs = 'Y (IB)' elif any(element.lower() in school_name.lower() for element in int_criteria) or \ any(element.lower() in degree_name.lower() for element in int_criteria) or \ any(element.lower() in field_of_study.lower() for element in int_criteria) or \ any(element.lower() in grades.lower() for element in int_criteria): int_hs = 'Y' else: int_hs = 'N' return int_hs
5dd3d6152ad8ac55c70bb508e9b15f1c9a7f5e1b
193,614
def dehom(x): """ Convert homogeneous points to affine coordinates """ return x[0:-1, :] / x[-1, :]
14e3c6b484513f8633457e7b7a64318040ec24c7
417,522
def composite(image1, image2, mask): """ Create composite image by blending images using a transparency mask. :param image1: The first image. :param image2: The second image. Must have the same mode and size as the first image. :param mask: A mask image. This image can have mode "1", "L", or "RGBA", and must have the same size as the other two images. """ image = image2.copy() image.paste(image1, None, mask) return image
cce01353bde95b88b81110befcea98f0915abc7c
119,177
def sql_timestamp_pretty_print(ts, lang: str = 'en', humanize: bool = True, with_exact_time: bool = False): """ Pretty printing for sql timestamp in dependence of the language. :param ts: timestamp (arrow) as string :param lang: language :param humanize: Boolean :param with_exact_time: Boolean :return: String """ if humanize: # if lang == 'de': ts = ts.to('Europe/Berlin') # else: # ts = ts.to('US/Pacific') return ts.humanize(locale=lang) else: if lang == 'de': return ts.format('DD.MM.YYYY' + (', HH:mm:ss ' if with_exact_time else '')) else: return ts.format('YYYY-MM-DD' + (', HH:mm:ss ' if with_exact_time else ''))
79efcf545dceb3e6df58fde9f23b8fb023aa974c
292,346
def geoIsOnSegment(loc, line): """ Determine if loc is on line segment Parameters ---------- loc: list First location, in [lat, lon] format line: list of lists Line segment, in [[lat,lon], [lat,lon]] format Return ------ boolean True if loc is on line segment, including two edge vertices """ [y1, x1] = [line[0][0], line[0][1]] [y2, x2] = [loc[0], loc[1]] [y3, x3] = [line[1][0], line[1][1]] val = (x2 * y3 + x3 * y1 + x1 * y2) - (x2 * y1 + x3 * y2 + x1 * y3) if (val == 0 and x2 >= min(x1, x3) and x2 <= max(x1, x3) and y2 >= min(y1, y3) and y2 <= max(y1, y3)): onSegment = True else: onSegment = False return onSegment
435b5fd64ae0057fd60eeec84138c20903881748
477,809
def calculate_bmi(weight, height): """ Given weight (pounds), height (inches) Return BMI """ return (weight / (height * height)) * 703.
f9574c127f91a6209c19e4329aa2a1eb371933bb
199,304
def page_not_found(error): """ Handles 404 errors by simply just returning the code and no page rendering""" return "", 404
8776b26997aca654a1281274d0ed8f35e1a0d8b6
496,818
def create_error_payload(exception, message, endpoint_id): """ Creates an error payload to be send as a response in case of failure """ print(f'{exception}: {message}') error_payload = { 'status': 'MESSAGE_NOT_SENT', 'endpointId': endpoint_id if endpoint_id else 'NO_ENDPOINT_ID', 'message': f'{exception}: {message}' } return error_payload
90f266d22429d385e828dcdd92fca3d7b2e6df48
4,728
def is_pythonfile(file): """Returns True if file extension is py and if not then false.""" if file.endswith('py'): return True else: return False
4f7e1609e3d17d7ca58cdf31bebc27761d1d3fb1
437,291
def convert_comma_separated_integer_to_float(comma_separated_number_string): """Converts a string of the form 'x,xxx,xxx' to its equivalent float value. :param comma_separated_number_string: A string in comma-separated float form to be converted. :returns: A float representing the comma-separated number. """ return float(comma_separated_number_string.replace(',', ''))
daddeaa78a3efb8ffd2d5eac122757f041da5f97
694,860
def pointToGridIndex(x, y, z, sx=1.0, sy=1.0, sz=1.0, ox=0.0, oy=0.0, oz=0.0): """ Convert real point coordinates to index grid: :param x, y, z: (float) coordinates of a point :param nx, ny, nz: (int) number of grid cells in each direction :param sx, sy, sz: (float) cell size in each direction :param ox, oy, oz: (float) origin of the grid (bottom-lower-left corner) :return: ix, iy, iz: (3-tuple) grid node index in x-, y-, z-axis direction respectively Warning: no check if the node is within the grid """ jx = (x-ox)/sx jy = (y-oy)/sy jz = (z-oz)/sz ix = int(jx) iy = int(jy) iz = int(jz) # round to lower index if between two grid node if ix == jx and ix > 0: ix = ix -1 if iy == jy and iy > 0: iy = iy -1 if iz == jz and iz > 0: iz = iz -1 return ix, iy, iz
8df63aa196ed3bec7bcc0ae6478b51308a2a0ab9
619,278
import click def click_option_expand(f): """Add expand option to command.""" return click.option( '--expand', is_flag=True, help="Display associated assets details" )(f)
9f2a6edd30649817df28eff57e804f4c851070da
266,130
def read_str(data, start, length): """Extract a string from a position in a sequence.""" return data[start:start+length].decode('utf-8')
a2d5426937a9a2e61fe5a993951f7275ca50a460
186,236
def calc_mean_score(movies): """Helper method to calculate mean of list of Movie namedtuples, round the mean to 1 decimal place""" scores = [movie.score for movie in movies] return round(sum(scores) / len(scores), 1)
f2923c8dd583b1e4aa54dfd4191c5a7aa5484b88
612,681
def compose_preprocess_fn(*functions): """Compose two or more preprocessing functions. Args: *functions: Sequence of preprocess functions to compose. Returns: The composed function. """ def _composed_fn(x): for fn in functions: if fn is not None: # Note: If one function is None, equiv. to identity. x = fn(x) return x return _composed_fn
5fde96f972d0d730981e88e44ff4c220c242bcfd
304,366
def normalize(sentence_sets, word2id, max_sent_len): """Normalize the sentences by the following procedure - word to index - add unk - pad/ cut the sentence length - record the sentence length Args: sentence_sets: the set of sentence paraphrase, a list of sentence list word2id: word index, a dictionary max_sent_len: maximum sentence length, a integer """ sent_sets = [] sent_len_sets = [] max_sent_len = max_sent_len + 1 for st in sentence_sets: st_ = [] st_len = [] for s in st: s_ = [word2id["_GOO"]] for w in s: if(w in word2id): s_.append(word2id[w]) else: s_.append(word2id["_UNK"]) s_.append(word2id["_EOS"]) s_ = s_[: max_sent_len] if(len(s_) < max_sent_len): s_len = len(s_) - 1 for i in range(max_sent_len - len(s_)): s_.append(word2id["_PAD"]) else: s_[-1] = word2id["_EOS"] s_len = max_sent_len - 1 st_.append(s_) st_len.append(s_len) sent_sets.append(st_) sent_len_sets.append(st_len) return sent_sets, sent_len_sets
a931e07cf9a4a0d04fa68e7ad28b57c7cdcf37d6
502,844
def get_mdict_item_or_list(mdict, key): """ Return the value for the given key of the multidict. A werkzeug.datastructures.multidict can have a single value or a list of items. If there is only one item, return only this item, else the whole list as a tuple :param mdict: Multidict to search for the key :type mdict: werkzeug.datastructures.multidict :param key: key to look for :return: the value for the key or None if the Key has not be found """ if hasattr(mdict, "getlist"): v = mdict.getlist(key) if len(v) == 1: value = v[0] # Special case for empty strings, treat them as "no-value" if value == "": value = None return value elif len(v) == 0: return None else: return tuple(v) return None
d330d3555a989f4b7f0b3e9b17cf5190f9244b70
519,390
def parse(afile, sep=' '): """Parse contact file. @param afile contact file @param sep separator of contact file (default=' ') Ensures: Output is sorted by confidence score. @return [(score, residue a, residue b)] """ contacts = [] for aline in afile: if aline.strip() != '': line_arr = aline.strip().split(sep) if line_arr[0].startswith('E'): continue i = int(line_arr[0]) j = int(line_arr[1]) score = float(line_arr[-1]) if abs(i - j) > 4: contacts.append((score, i, j)) afile.close() contacts.sort(key=lambda x: x[0], reverse=True) return contacts
1dcf1bea41d4b79c297f29485e8f053c55052d3e
269,924
def split(array, n): """ Splits an array into two pieces. Args: array: The array to be split. n: An integer or float. If n is an integer, one of the arrays will contain n elements, the other will contain every other element. If n is a float, it needs to be between 0 and 1. The split will be such that one of the arrays will contain n*len(array) elements, the other will contain every other element. Returns: Two lists a, b. a is the list with the specified size. b is the list with all the other elements. """ array = list(array) if isinstance(n, float): length = len(array) n = int(n * length) return array[:n], array[n:]
095dab4f6f88bf3bb132771bf3d20abd9d239c49
512,324
def _get_session_id_from_cookie(request, cookie_name, cookie_signer): """ Attempts to retrieve and return a session ID from a session cookie in the current request. Returns None if the cookie isn't found or the value cannot be deserialized for any reason. """ cookieval = request.cookies.get(cookie_name) if cookieval is not None: try: session_id = cookie_signer.loads(cookieval) return session_id except ValueError: pass return None
e88e186a7e0e38984706454b4cf9936ef1b639da
113,376
def mask_data(ds, mask_mapping): """ Mask data values according to the mask_mapping parameter """ for var, missing_value in mask_mapping.items(): ds[var] = ds[var].where(ds[var] != missing_value) return ds
f1e745aa33ee58b16cdc27b0c7a0f74bf99dc941
520,397
def twos_complement(value: int) -> int: """ This method returns the 16-bit two's complement of a positive number (used for sending negative values to the controller). It raises an error if the argument is too large or is negative. """ assert value.bit_length() <= 16, "Value too large!" assert value > 0, "Value is negative!" return (2 ** 16) - value
58a48d6fa436c79158ba1e8de4a036acc712832e
218,066
def is_content_authored_by(content, user): """ Return True if the author is this content is the passed user, else False """ try: return int(content.get('user_id')) == user.id except (ValueError, TypeError): return False
9a6846b04bce0066973aac3e3a5dfda2db2b1663
53,742
def _has_alternative_alignments(aligned_segment): """Return true if read has alternative alignments""" tags = aligned_segment.get_tags() return "XA" in [x[0] for x in tags]
74a383afa42988adeca15c63f78ed10eb2deb8ed
523,072
def single_pcrosstalk(total_pcrosstalk: float) -> float: """ Inverse formula to ``total_pcrosstalk'' Parameters ---------- total_pcrosstalk : float The probability of total crosstalk events. Returns ------- p_crosstalk : float The probability of a single crosstalk event. """ return 1 - (1 - total_pcrosstalk) ** 0.25
401934183dd50dfad5f15ca91a183054e756e4e7
570,721
def format_bird_bgp_community(target): """Convert from standard community format to BIRD format. Args: target {str} -- Query Target Returns: {str} -- Formatted target """ parts = target.split(":") return f'({",".join(parts)})'
fc9339e3e0ffde33b6d7330d0f74c3cdee465aab
523,493
def format_coefficient(model): """ Formats the coefficient of a model for display. :param model: A linear model :type model: sklearn.linear_model.LinearRegression :return: The formatted coefficient :rtype: str """ return "{:,}".format(round(model.coef_.tolist()[0][0], 2))
e006ed5bde24f76fc2a980c679455f8fae65d83f
280,554
def get_chess_square_reverse(size, x, y): """ Returns the coordinates of the start of the square block on the board given the block's coordinates """ return (x * size // 8, y * size // 8)
083b9bee26b70f4704ed0182fb1e4a2baeb01c4b
419,068
from typing import Tuple def xgcd(a: int, b: int) -> Tuple[int, int, int]: """Extended Euclidean algorithm. Finds :code:`gcd(a,b)` along with coefficients :code:`x`, :code:`y` such that :code:`ax + by = gcd(a,b)`. Args: a: first number b: second number Returns: gcd(a,b), x, y """ x, y, u, v = 0, 1, 1, 0 while a != 0: q, r = b // a, b % a m, n = x - u * q, y - v * q b, a, x, y, u, v = a, r, u, v, m, n return b, x, y
6d8764e21511b473b968b24d6783ac97ead0a180
669,732
def _isnumeric(var) : """ Test if var is numeric, only integers are allowed """ return type(var) is int
51c29247a5d4531f565534afe7750a13138c110e
692,960
def tlv_string_xml_mapped() -> str: """Return the mapped XML data for the test tree as string.""" return """<Tlv> <ConstructedTagE1> <PrimitiveTag9F1E>16021437</PrimitiveTag9F1E> <ConstructedTagEF> <PrimitiveTagDF0D>M000-MPI</PrimitiveTagDF0D> <PrimitiveTagDF7F>1-22</PrimitiveTagDF7F> </ConstructedTagEF> <ConstructedTagEF> <PrimitiveTagDF0D>M000-TESTOS</PrimitiveTagDF0D> <PrimitiveTagDF7F>6-5</PrimitiveTagDF7F> </ConstructedTagEF> </ConstructedTagE1> </Tlv>"""
d30e1af8adaea971fd64bc9152d72b8626d55927
471,332
def extract_machine_code(assembly_lines): """ Extract machine code from assembly line dictionaries. Args: assembly_lines (list(dict)): List of assembly line info dictionaries to extract machine code from. See :func:`~.get_assembly_line_template` for details on what those dictionaries contain. Returns: list(str): List of bit strings for the machine code. """ machine_code = [] for assembly_line in assembly_lines: if assembly_line["has_machine_code"]: for mc_byte in assembly_line["mc_bytes"]: machine_code.append(mc_byte["bitstring"]) return machine_code
757dd311e13a5c73fb3715b7195349555c02aab4
589,582
def send_request(client, post_data, **kwargs): """uses a dict to create a request on dataforSeo api parameters: client : Restclient object created with create_request post_data: dict created with create_request Optional parameters: server: server to use for request returns json style list""" # set optional arguments server = kwargs.get("server", "/v3/serp/google/organic/task_post") response_ready = client.post(server, post_data) return response_ready
973fef88a77a592c8129ad5e409430173da08d69
648,639
def get_keys(d, value): """Renvoie la liste des clés de d ayant la valeur value.""" t = [] for k in d: if d[k] == value: t.append(k) return t
fe68795007e1fa749da4acbd2935cdaee162ff38
434,409
def move_axis(data, label, new_position): """Moves a named axis to a new position in an xarray DataArray object. Args: data (DataArray): Object with named axes label (str): Name of the axis to move new_position (int): Numerical new position of the axis. Negative indices are accepted. Returns: data with axis in new position """ # find current position of axis try: pos = data.dims.index(label) except ValueError as e: raise ValueError(f"Axis name {label} does not exist in input data") from e # create list of labels with new ordering axis_labels = list(data.dims) # the new position will be _before_ the given index, so will fail with a negative index # convert to a positive index in that case if new_position < 0: new_position += len(axis_labels) axis_labels.insert(new_position, axis_labels.pop(pos)) # do the move return data.transpose(*axis_labels)
da58b00560032ded1847066222f50da50ff7c171
559,658
import torch def subsequent_mask(seq_len): """ ## Subsequent mask to mask out data from future (subsequent) time steps """ mask = torch.tril(torch.ones(seq_len, seq_len)).to(torch.bool).unsqueeze(-1) return mask
43cace3a2d4cc32a43136cf36766f280707ee677
160,642
def time_until_next_event(prng, net_rate): """Compute the time at which the next event is due to occur. All events are modeled as Poisson processes with exponentially distributed waiting times. Units of time are chosen such that the average time it takes for a given cell to divide is 1. """ return prng.standard_exponential() / net_rate
d429006563ab0ead27ec019f002665d77ec7dd9e
391,101
def _update_dtypes(candidate_model): """Update dtypes of specific columns from float to int. Updates dtypes of *candidate_model* so that columns representing integer are set to integers. Args: candidate_model (pd.DataFrame): Data frame representing a causal forest model, which might have columns that represent integer dtypes but are stored as floats. Returns: fitted_model (pd.DataFrame): Updated model. """ columns_to_int = [ "left_child", "right_child", "level", "split_feat", ] fitted_model = candidate_model.copy() fitted_model[columns_to_int] = fitted_model[columns_to_int].astype("Int64") return fitted_model
b0186ed415ad5dd7907ad10c1a000b2784d69285
157,258
import re def filter_by_category(result, name_filter=None): """ Filter by category name the result returned from ZIA. :param result: Dict of categories from ZIA response. :param name_filter: A regex string used to filter result. :return: Filtered result. """ categories = result.get("categories", []) regex = r'{}'.format(name_filter) # Add category total and filtered counts to result. result.update({ "category_counts": { "total": len(categories), "filtered": len(categories) } }) if name_filter: filtered_categories = [c for c in categories if re.search(regex, c.get("configuredName", ''), re.I)] result["categories"] = filtered_categories result["category_counts"]["filtered"] = len(filtered_categories) return result
da5e1c716a86907bb953abf8821962e76094de9d
77,509
def ipkg_meta_from_pkg(pkg): """Return meta dict for Installed pkg from a PackageDescription instance.""" meta = {} for m in ["name", "version", "summary", "url", "author", "author_email", "license", "download_url", "description", "platforms", "classifiers", "install_requires", "top_levels"]: meta[m] = getattr(pkg, m) return meta
7c73546854fe022005bb7cd65711d850fc744645
692,799
import copy import random def pick_random_idx(idices, num, seed=0): """ Pop the "num" number of random samples from the sequence "indices" Args: idices (Sequence): num (Int): The number to pop up the samples from the "idices" seed(Int): Random seed Returns: remaining_sequences, pop-upped sequences """ shuffled_idx = copy.deepcopy(idices) random.Random(seed).shuffle(shuffled_idx) picked_idx = shuffled_idx[:num] remain_idx = shuffled_idx[num:] return remain_idx, picked_idx
45840fa4a2cb4991022caea67e3ba8a5ce713ce9
429,463
def _to_latex(string): """Latex-decorate a string.""" return ('$' + string + '$')
fc03b93086393c772aa932a37560f472d0624c6f
126,334
def itoa(num, base=10): """ Convert a decimal number to its equivalent in another base. This is essentially the inverse of int(num, base). """ negative = num < 0 if negative: num = -num digits = [] while num > 0: num, last_digit = divmod(num, base) digits.append('0123456789abcdefghijklmnopqrstuvwxyz'[last_digit]) if negative: digits.append('-') digits.reverse() return ''.join(digits)
297bc917d689c7ca7065d9e53d62efeb84208cf8
568,533
def round(x: int, divisor: int) -> int: """Round x to the multiplicity of divisor not greater than x""" return int(x / divisor) * divisor
e598827058d5c7c37e32f8d213690875403fbe8d
52,251
def unwrap_twist(twist): """ Unwraps geometry_msgs/Twist into two tuples of linear and angular velocities """ l_x = twist.linear.x l_y = twist.linear.y l_z = twist.linear.z a_x = twist.angular.x a_y = twist.angular.y a_z = twist.angular.z return (l_x, l_y, l_z), (a_x, a_y, a_z)
66c4eceeea7791790252ea01c7e8aabe28ea9be0
33,852
def antipode_v(ll): """Antipodes of points given by longitude and latitude.""" antipode = ll.copy() antipode[0] -= 180 index = antipode[0] < -180 antipode[0, index] += 360 antipode[1] *= -1 return antipode
0775c1b5d9ec77a0866708a072a08081077669d9
220,384
def where_above(list, limit): """ where_above behaves like table.where(column, are.above(limit)). The analogy is completed if you think of a column of a table as a list and return the filtered column instead of the entire table. >>> where_above([1, 2, 3], 2) [3] >>> where_above(range(13), 10) [11, 12] >>> where_above(range(123), 120) [121, 122] """ return [x for x in list if x > limit]
fe02f5d88aff90cac4041fdf71b7fbfc2ed4a978
403,761
def funding_rate(self, symbol: str, **kwargs): """funding Rate history GET /fapi/v1/fundingRate https://binance-docs.github.io/apidocs/futures/en/#get-funding-rate-history Args: symbol (str, optional): the trading symbol Keyword Args: limit (int, optional): limit the results. Default 100; max 1000. startTime (int, optional): Start Time. endTime (int, optional): End Time. If startTime and endTime are not sent, the most recent limit datas are returned. If the number of data between startTime and endTime is larger than limit, return as startTime + limit. In ascending order. """ params = {"symbol": symbol, **kwargs} return self.query("/fapi/v1/fundingRate", params)
f76b3d8d93d34164e0397c86bb18a1eb674612eb
103,195
def has_attribute(object, name): """Check if the given object has an attribute (variable or method) with the given name""" return hasattr(object, name)
44f0cd1cc54fe61b755d94629e623afe234fe99d
682,145
import re def format_gid(gid): """Internal function to strip transcript dot-notation from IDs.""" return re.sub(r"\.\d*", "", gid)
f994298f8f9ef659f459cea678787d0cd661b6da
529,380
def construct_dom_id_filter(dom_resource_subclass, dom_id_value): """ Returns a new dict w/ one entry: { <dom-id-key>: <dom-id-value>} The dom-id-key is name of the ID field/attribute for the given type of DOM resource (a subclass of pvc_nova.objects.dom.Resource). The dom-id-key is obtained from a class-method 'get_id_attr_name()', which should be defined on the given DOM Resource subclass. """ return {dom_resource_subclass.get_id_attr_name(): dom_id_value}
dfcb55672f301fbb19f082f89d590f7333be37b4
150,609
def _simple_string_value(tree, kind, name): """ base function for extracting a simple parameter value. :param tree: the parameters tree. :param kind: the xml-tag name of the parameter. :param name: the name of the parameter. :returns value: the content of the parameter 'Value' as string.""" query = ".//{kind}[@Name='{name}']/Value".format(kind=kind, name=name) return tree.find(query).text
473919cc08fb0b1fd0b73dcdcdc730affd29daff
103,987
def find_optional_start(line): """Find the starting position of the optional fields on the given line.""" pos = 0 for i in range(0, 11): pos = line.find("\t", pos) if -1 == pos: return -1 pos += 1 return pos
c10886a1768566c5ed8011a48fc8783dff12de1a
297,776
def chirp_mass(mass1, mass2): """ Takes two masses and calculates the corresponding chirpmass. Args: mass1: Mass 1 mass2: Mass 2 Returns: chirpmass: The chirpmass that corresponds to mass1, mass2 """ return (mass1 * mass2) ** (3 / 5) / (mass1 + mass2) ** (1 / 5)
41ccb3e573f361538c7591942b445e629b4c6c84
184,679
def _find_line_containing(source, index): """Find (line number, line, offset) triple for an index into a string.""" lines = source.splitlines() if not lines: # Special case: empty program return 1, '', 0 this_line_start = 0 for zero_index_line_number, line in enumerate(lines): next_line_start = this_line_start + len(line) + 1 if next_line_start > index: return zero_index_line_number + 1, line, index - this_line_start this_line_start = next_line_start # Must be at the end of file raise AssertionError("index >> len(source)")
8c90e0989b1e073a7c0df65b32778040890b21bb
195,885
from pathlib import Path def get_file_id(fname): """Returns the Gutenberg File ID""" pth = Path(fname) # as per file structure the filename has some variations but the parent folder is always the ID return pth.parent.name
4cfa633937ea7baa0fe0f9390fdab59630437525
342,417
def length(seq): """ Returns the length of the sequence `seq`. """ return len(seq)
20e9ed2148e14c90b47ba6559312250ba5e03a51
421,574
def override(left, right, key, default): """Returns right[key] if exists, else left[key].""" return right.get(key, left.get(key, default))
f6f5da1840aa4fa70fe0db400be9bebd2f21e383
674,561
def get_syst ( syst , *index ) : """Helper function to decode the systematic uncertainties Systematic could be - just a string - an object with index: obj [ibin] - a kind of function: func (ibin) """ if isinstance ( syst , str ) : return syst elif syst and hasattr ( syst , '__getitem__' ) : return str ( syst [ index ] ) elif syst and callable ( syst ) : return str ( syst ( *index ) ) elif syst : raise AttributeError("Invalid systematic %s/%s" % ( syst , type( syst ) ) ) return ''
37b2b39245587da16345752e02759d2c94c93415
702,800
def isSignatureValid(expected, received): """ Verifies that the received signature matches the expected value """ if expected: if not received or expected != received: return False else: if received: return False return True
f911521998e45dfc3804039e9105a921e33e9a67
204,446
def get_attributes(aspect, id): """Return the attributes pointing to a given ID in a given aspect.""" attributes = {} for entry in aspect: if entry['po'] == id: attributes[entry['n']] = entry['v'] return attributes
2f1d1c006e7df700da9fff8e5238c93b20eed8c5
395,068
def diff_month(date1, date2): """Counts the number of months between two dates Args: d1 - date to d2 - date from Returns: number of months between two dates """ return (date1.year - date2.year) * 12 + date1.month - date2.month
2e224f9432cb4a2da7ad0b492d8acb9b4948f1af
551,825
def boxBasics(box): """basic statistics of box. Returns (mean,var)""" mean=box.box_data.mean() var=box.box_data.var() return (mean,var)
0e9493722637adef80e606225bd712546c998470
671,622
def _resort_categorical_level(col_mapping): """ Resort the levels in the categorical encoders if all levels can be converted to numbers (integer or float). Args: col_mapping: the dictionary that maps level string to int Returns: New col_mapping if all levels can be converted to numbers, otherwise the original col_mapping """ def is_number(string): try: float(string) return True except ValueError: return False if all(map(is_number, col_mapping.keys())): key_tuples = [(k, float(k)) for k in col_mapping.keys()] sorted_key_tuples = sorted(key_tuples, key=lambda x: x[1]) new_mapping = {} value = 1 for t in sorted_key_tuples: new_mapping[t[0]] = value value += 1 return new_mapping else: return col_mapping
0740b4bb210637a144e00e29ff023af375801c56
285,832
def OR(bools): """Logical OR.""" if True in bools: return True return False
200e78e6ef1ce91ad36301cea0b8f56dc7301219
647,078
def ether2wei(ether: float): """Converts units of wei to Ether (1e18 * wei).""" return ether * 1e18
b826daaa171d24b43b7f901b6498f24f5481ed1c
41,448
def GetDimensions(nc): """Returns a dictionary describing the dimensions in a netCDF file.""" return({name: { "size": dim.size, "UNLIMITED": True} if dim.isunlimited() else { "size": dim.size, "UNLIMITED": False} for name, dim in nc.dimensions.items()})
a8da5e01745962949fc9b098c4949ae7d6f558dc
303,522
def _calculate_num_runs_failures(list_of_results): """Caculate number of runs and failures for a particular test. Args: list_of_results: (List) of JobResult object. Returns: A tuple of total number of runs and failures. """ num_runs = len(list_of_results) # By default, there is 1 run per JobResult. num_failures = 0 for jobresult in list_of_results: if jobresult.retries > 0: num_runs += jobresult.retries if jobresult.num_failures > 0: num_failures += jobresult.num_failures return num_runs, num_failures
f67a6b1fa6a5aefc19bfe7e99ed77473801e6b83
48,193
def check_padding(pads, dim, padval): """Check each padding start/end value and set the sufficient pad value. If we have asymmetry padding, we will return True to indicate the need for a separate padding function""" asymmetry = False for i in range(dim): s = pads[i] e = pads[i+dim] if s == e: padval.append(s) else: asymmetry = True # We must add a separate pad function for asymmetry padding. # Since the pad function will do all the padding, # we will remove all padding here. del padval[:] padval.extend([0]*dim) break return asymmetry
3841eda76f09910dbc4199123a723bcd017ee21e
198,046
def cap_feature_values(df, feature, cap_n=10): """Cap the values of a given feature, in order to reduce the effect of outliers. For example, set NUMBER_OF_HABITABLE_ROOMS values that are greater/equal to 10 to "10+". Paramters ---------- df : pandas.DataFrame Given dataframe. feature : str Feature for which values are capped. cap_n : int, default=10 At which value to cap. Return --------- df : pandas.DataFrame Dataframe with capped values.""" # Cap at given limit (i.e. 10) df.loc[(df[feature] >= cap_n), feature] = cap_n # str(cap_n) + "+" return df
273e755ec1b677b662732c8ae598581c01a25a53
118,786
def parse_title(raw_title): """ Format the title associated with a link. This format a title associated with a link. Some of them include some bad html elements/characters. :param raw_title: A raw title :type raw_title: str :return: A formated title :rtype: str """ title = raw_title.replace('<strong>', '') title = title.replace('</strong>', '') title = title.replace('&nbsp;', ' ') return title
5f459aa852861637997a03e4b9d5e6557d6d8d65
383,536
def flatten(in_list): """Flatten list. >>> flatten([]) [] >>> flatten([1, 2, 3]) [1, 2, 3] >>> flatten(([[1], [2, 3]])) [1, 2, 3] >>> flatten([1, [[2], 3]]) [1, 2, 3] """ def flatten_generator(in_list_inner): for item in in_list_inner: try: for inner_item in flatten_generator(item): yield inner_item except TypeError: yield item return list(flatten_generator(in_list_inner=in_list))
d862a2daa508ca56f210a41573fb5ba8ac3877b9
256,130
def sql_from_filename(filename): """ Given a filename return the SQL it contains. This function exists to support unit testing. :param filename: path to exiting file containing SQL :return: str: sql commands to execute """ with open(filename, 'r') as infile: return infile.read() + "\n"
da965543f6ed2fafdb3717237c80457bf690e3ff
99,138
def replace_null(x, replace = None): """ Replace null values Parameters ---------- x : Expr, Series Column to operate on Examples -------- >>> df = tp.Tibble(x = [0, None], y = [None, None]) >>> df.mutate(x = tp.replace_null(col('x'), 1)) """ if replace == None: return x return x.fill_null(replace)
6aa7906524b40633bf05ca0178891da249310fff
508,326
def compute_offsets(task, nc_per_task, is_cifar): """ Compute offsets for cifar to determine which outputs to select for a given task. """ if is_cifar: offset1 = task * nc_per_task offset2 = (task + 1) * nc_per_task else: offset1 = 0 offset2 = nc_per_task return offset1, offset2
300eab41a67f084b7c0ea172fc682e138192d87a
514,900
def is_prime(number): """checks if a given number is prime""" prime = True for n in range(2, number): if prime and number % n == 0: prime = False print("The number is not prime") if prime: print("The number is prime") return prime
a6119b54e3ff16d7e94ad4ac06e224c623ee5dd1
648,361
def _ReadFileAndPrependLines(file_path): """Reads the contents of a file and prepends the line number to every line.""" with open(file_path) as f: return "".join("{}${}".format(line_number, line) for line_number, line in enumerate(f, 1))
59c7d03710b7c06ad43fc989166d7a021ee45827
234,668
def recurse_combine(combo_items: list, idx: int = 0) -> list: """Recursively expands 'combo_items' into a list of permutations. For example recurse_combine([[A, B, C], [D, E], [F]]) returns [[A, D, F], [A, E, F], [B, D, F], [B, E, F], [C, D, F], [C, E, F]] """ result = [] if idx < len(combo_items): recurse_result = recurse_combine(combo_items, idx + 1) for item in combo_items[idx]: for sub_item in recurse_result: sub_result = [item] sub_result.extend(sub_item) result.append(sub_result) if len(recurse_result) == 0: result.append([item]) return result
effab4c6f29e353d19f88b23f7d2a3bfa854d431
674,653
import base64 def decode_to_bytes(data: str) -> bytes: """ Decodes a base64-encoded string and returns a sequence of bytes. :param data: The base64-encoded string to decode :return: decoded bytes """ data_bytes = bytes(data, "utf-8") data_decoded_bytes = base64.b64decode(data_bytes) return data_decoded_bytes
f2d4453c0129924b81d5ea2e5c1578bea72944ee
496,780
def rubygems_download_url(name, version, platform=None, repo='https://rubygems.org/downloads'): """ Return a .gem download URL given a name, version, and optional platform (e.g. java) and a base repo URL. For example: https://rubygems.org/downloads/mocha-1.7.0.gem """ if not name or not version: return repo = repo.rstrip('/') name = name.strip().strip('/') version = version.strip().strip('/') version_plat = version if platform and platform != 'ruby': version_plat = '{version}-{platform}'.format(**locals()) return '{repo}/{name}-{version_plat}.gem'.format(**locals())
b6cfe7050bf30695bbeab621b2a3cc7f9c662817
422,110
def normalizeScifloArgs(args): """Normalize sciflo args to either a list or dict.""" if isinstance(args, dict) or \ (isinstance(args, (list, tuple)) and (len(args) != 1)): return args elif isinstance(args, (list, tuple)): if isinstance(args[0], (list, tuple, dict)): return args[0] else: return args else: raise RuntimeError( "Unrecognized type for sciflo args: %s" % type(args))
49d4528b6ac05f7864f7b1c38f4cfe079b451870
227,872
def hexdecode(value): """ Decodes string value from hex to plain format >>> hexdecode('666f6f626172') 'foobar' """ value = value.lower() return (value[2:] if value.startswith("0x") else value).decode("hex")
b91af6ef77fa1bc8270b62dc72ed7c7a07d96aa9
609,319
def get_ami_info(ec2, ami_id): """ Returns information about the specified AMI. Parameters ---------- ec2 : botocore.client.EC2 AWS EC2 client. ami_id : str AMI ID. Returns ------- dict """ resp = ec2.describe_images(ImageIds=[ami_id]) return resp['Images'][0]
cdb1d05afae5bf0c76df0aa7eca5208771fd2923
593,379
from typing import Dict from typing import Optional def weighted_average( distribution: Dict[str, float], weights: Dict[str, float], rounding: Optional[int] = None, ) -> float: """ Calculate a weighted average from dictionaries with the same keys, representing the values and the weights. Args: distribution: The values weights: The weights rounding: Whether to round off the result Returns: The weighted average """ msg = "Attempting to calculate weighted average over two dictionaries that do not share keys" assert distribution.keys() == weights.keys(), msg numerator = sum([distribution[i] * weights[i] for i in distribution.keys()]) denominator = sum(weights.values()) fraction = numerator / denominator result = round(fraction, rounding) if rounding else fraction return result
b6c710fc8039b79637c8d45329eb90cc0d1bb264
678,674
import torch def rel2abs_traj(rel_pose): """Convert a given relative pose sequences to absolute pose sequences. Args: rel_pose (torch.Tensor): Relative pose sequence in the form of homogenous transformation matrix. Shape: [N,4,4] Returns: torch.Tensor: Absolute pose sequence in the form of homogenous transformation matrix. Shape: [N,4,4] """ global_pose = torch.eye(4, dtype=rel_pose.dtype, device=rel_pose.device) abs_pose = torch.zeros_like(rel_pose) for i in range(rel_pose.shape[0]): global_pose = global_pose @ rel_pose[i] abs_pose[i] = global_pose return abs_pose
b2533d65262da65d80eb4869afde7b1256a8ec52
128,893
def find_exec_in_executions(searched_exec, executions): """ Search if exec is contained in the executions. :param searched_exec: Execution to search for. :param executions: List of executions. :return: Index of the execution, -1 if not found.. """ for i, existing_exec in enumerate(executions, start=0): if ("providerId" in existing_exec and "providerId" in searched_exec and existing_exec["providerId"] == searched_exec["providerId"] or "displayName" in existing_exec and "displayName" in searched_exec and existing_exec["displayName"] == searched_exec["displayName"]): return i return -1
6d2dd2931742a1395a81462643afdbef2b49087e
601,069
def get_aso_idx_from_id(df, aso_id): """Converts an ASO UUID to the corresponding array index in the orbital prediction numpy array :param df: The orbital prediction DataFrame :type df: pandas.DataFrame :param aso_id: The UUID of the ASO found in the `aso_id` column of the provided `df` DataFrame :type aso_id: str :return: The corresponding index in the orbital prediction numpy array constructed by `get_orbit_preds` :rtype: int """ return df.index[df.aso_id == aso_id][0]
0042c71eda7c98fd86894912606c6eb9cc2df383
334,426
def word_to_put_req(word_vectors_map, word): """ Translate a word to a PUT request to be sent to DynamoDB """ return { 'PutRequest': { 'Item': { 'word': { 'S': word }, 'vector': { 'L': [{'N': str(n)} for n in word_vectors_map[word]] } } } }
1734463d60869c4c51ba40f61ad19e16ead75345
38,422
import re def apply_cigar(cigar, seq, qual, pos=0, clip_from=0, clip_to=None): """ Applies a cigar string to recreate a read, then clips the read. Use CIGAR string (Compact Idiosyncratic Gapped Alignment Report) in SAM data to apply soft clips, insertions, and deletions to the read sequence. Any insertions relative to the sample consensus sequence are removed to enforce a strict pairwise alignment, and returned separately in a dict object. @param cigar: a string in the CIGAR format, describing the relationship between the read sequence and the consensus sequence @param seq: the sequence that was read @param qual: quality codes for each base in the read @param pos: first position of the read, given in zero-based consensus coordinates @param clip_from: first position to include after clipping, given in zero-based consensus coordinates @param clip_to: last position to include after clipping, given in zero-based consensus coordinates, None means no clipping at the end @return: (sequence, quality, {pos: (insert_seq, insert_qual)}) - the new sequence, the new quality string, and a dictionary of insertions with the zero-based coordinate in the new sequence that follows each insertion as the key, and the insertion sequence and quality strings as the value. If none of the read was within the clipped range, then both strings will be blank and the dictionary will be empty. """ newseq = '-' * int(pos) # pad on left newqual = '!' * int(pos) insertions = {} is_valid = re.match(r'^((\d+)([MIDNSHPX=]))*$', cigar) tokens = re.findall(r' (\d+)([MIDNSHPX=])', cigar, re.VERBOSE) if not is_valid: raise RuntimeError('Invalid CIGAR string: {!r}.'.format(cigar)) end = None if clip_to is None else clip_to + 1 left = 0 for token in tokens: length, operation = token length = int(length) # Matching sequence: carry it over if operation == 'M': newseq += seq[left:(left+length)] newqual += qual[left:(left+length)] left += length # Deletion relative to reference: pad with gaps elif operation == 'D': newseq += '-'*length newqual += ' '*length # Assign fake placeholder score (Q=-1) # Insertion relative to reference elif operation == 'I': if end is None or left+pos < end: insertions[left+pos-clip_from] = (seq[left:(left+length)], qual[left:(left+length)]) left += length # Soft clipping leaves the sequence in the SAM - so we should skip it elif operation == 'S': left += length else: raise RuntimeError('Unsupported CIGAR token: {!r}.'.format( ''.join(token))) if left > len(seq): raise RuntimeError( 'CIGAR string {!r} is too long for sequence {!r}.'.format(cigar, seq)) if left < len(seq): raise RuntimeError( 'CIGAR string {!r} is too short for sequence {!r}.'.format(cigar, seq)) return newseq[clip_from:end], newqual[clip_from:end], insertions
4f69386c370bff76314d055da123c3185d2768de
360,094
import re def make_xlat(*args, **kwds): """ Auxuliary function to define a translator that applies multiple character substitutions at once. Taken from "Python Cookbook, 2nd Edition by David Ascher, Anna Ravenscroft, Alex Martelli", Section 1.18 :param args: Dictionary :param kwds: :return: A function that uses the given dictionary to apply multiple changes to a string """ adict = dict(*args, **kwds) rx = re.compile('|'.join(map(re.escape, adict))) def one_xlat(match): return adict[match.group(0)] def xlat(text): return rx.sub(one_xlat, text) return xlat
a8c4f9a0a293479000d7947932c7fe9b9616e05e
502,154
def unique_elements_lists(list_in): """return the unique elements in a list""" return list(dict.fromkeys(list_in))
dc893f678f079322b198894621d1c9b401b8878f
172,541
from pathlib import Path def is_raster_format (image_path: str) -> bool: """ Is the file at the provided path a raster image? Parameters: image_path (str): Path to file. Returns: bool: Whether the file is a raster image. """ RASTER_FORMATS = [".jpg", ".jpeg", ".tif", ".tiff"] format = Path(image_path).suffix.lower() return format in RASTER_FORMATS
9817c1d08f0b8cd4a01073d03f753577106b1c54
91,151
import types def is_function(tup): """ Takes (name, object) tuple, returns True if it is a function. """ name, item = tup return isinstance(item, types.FunctionType) # def _start(self, spin): # for args, kwargs in self.subscribers: # self.subscribers_init.append(rospy.Subscriber(*args, **kwargs)) # is_func = isinstance(self.cl, types.FunctionType
e49e0973828d0eea848d29b8a1b954119f1fe490
592,682
def grids(dims, blocks): """ Determine the grid size, given space dimensions sizes and blocks Parameters ---------- dims : tuple of ints `(x, y, z)` tuple Returns ------- tuple `(x, y, z)` grid size tuple """ if not len(dims) == 3: raise ValueError("dims must be an (x, y, z) tuple. " "CUDA dimension ordering is inverted compared " "to NumPy") if not len(blocks) == 3: raise ValueError("blocks must be an (x, y, z) tuple. " "CUDA dimension ordering is inverted compared " "to NumPy") return tuple((d + b - 1) // b for d, b in zip(dims, blocks))
c2bfb27c5df4849a267233ff18327e4cfe2a6e7e
214,367
from typing import Any from typing import Union from typing import List def isType(val: Any, typeArr: Union[List[Any], Any]) -> bool: """Helper that checks if the supplied value `val` is of a specific type or of a type present in `typeArr`""" if isinstance(typeArr, List): anyMatched = False for type in typeArr: if isinstance(val, type): anyMatched = True return anyMatched else: if not isinstance(val, typeArr): return False return True
e4faecf10edffa81b6680d55fa91ea6714a8f1df
512,715
def get_vehicle_mass(vehicle_info): """ Get the mass of a carla vehicle (defaults to 1500kg) :param vehicle_info: the vehicle info :type vehicle_info: carla_ros_bridge.CarlaEgoVehicleInfo :return: mass of a carla vehicle [kg] :rtype: float64 """ mass = 1500.0 if vehicle_info.mass: mass = vehicle_info.mass return mass
216f109e9f963ba6de92cf168055b1a7e516d777
13,555
def split_repo_name(repository): """Take a string of the form user/repo, and return the tuple (user, repo). If the string does not contain the username, then just return None for the user.""" nameparts = repository.split('/', 1) if len(nameparts) == 1: return (None, nameparts[0]) else: return (nameparts[0], nameparts[1])
3740b80c2658315a27498b05832b120a937e053b
621,659
import re from datetime import datetime def matroska_date_to_datetime(date): """ Converts a date in Matroska's date format to a python datetime object. Returns the given date string if it could not be converted. """ # From the specs: # The fields with dates should have the following format: YYYY-MM-DD # HH:MM:SS.MSS [...] To store less accuracy, you remove items starting # from the right. To store only the year, you would use, "2004". To store # a specific day such as May 1st, 2003, you would use "2003-05-01". format = re.split(r'([-:. ])', '%Y-%m-%d %H:%M:%S.%f') while format: try: return datetime.strptime(date, ''.join(format)) except ValueError: format = format[:-2] return date
8805d6c0015b518433302bd88ac7d17eb52fd687
445,790