content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def create_list(value, sublist_nb, sublist_size): """ Create a list of len sublist_size, filled with sublist_nb sublists. Each sublist is filled with the value value """ out = [] tmp = [] for i in range(sublist_nb): for j in range(sublist_size): tmp.append(value) out.append(tmp) tmp = [] return out
1ecf6c88390167584d1835430c359a7ed6d6b40b
5,264
def getGpsTime(dt): """_getGpsTime returns gps time (seconds since midnight Sat/Sun) for a datetime """ total = 0 days = (dt.weekday()+ 1) % 7 # this makes Sunday = 0, Monday = 1, etc. total += days*3600*24 total += dt.hour * 3600 total += dt.minute * 60 total += dt.second return(total)
16caa558741d8d65b4b058cf48a591ca09f82234
5,266
def _round_to_4(v): """Rounds up for aligning to the 4-byte word boundary.""" return (v + 3) & ~3
c79736b4fe9e6e447b59d9ab033181317e0b80de
5,267
def lower_threshold_projection(projection, thresh=1e3): """ An ugly but effective work around to get a higher-resolution curvature of the great-circle paths. This is useful when plotting the great-circle paths in a relatively small region. Parameters ---------- projection : class Should be one of the cartopy projection classes, e.g., cartopy.crs.Mercator thresh : float Smaller values achieve higher resolutions. Default is 1e3 Returns ------- Instance of the input (`projection`) class Example ------- proj = lower_threshold_projection(cartopy.crs.Mercator, thresh=1e3) Note that the cartopy.crs.Mercator was not initialized (i.e., there are no brackets after the word `Mercator`) """ class LowerThresholdProjection(projection): @property def threshold(self): return thresh return LowerThresholdProjection()
165c657f1ec875f23df21ef412135e27e9e443c6
5,269
def has_param(param): """ Generate function, which will check `param` is in html element. This function can be used as parameter for .find() method in HTMLElement. """ def has_param_closure(element): """ Look for `param` in `element`. """ if element.params.get(param, "").strip(): return True return False return has_param_closure
6800725c378714b5161772f0a2f9ef89ae278400
5,273
def get_all_keys(data): """Get all keys from json data file""" all_keys = set(data[0].keys()) for row in data: all_keys = set.union(all_keys, set(row.keys())) return list(all_keys)
5532af993f87bf4e00c7bec13eb971e0114e736c
5,274
def _ngl_write_atom( num, species, x, y, z, group=None, num2=None, occupancy=1.0, temperature_factor=0.0, ): """ Writes a PDB-formatted line to represent an atom. Args: num (int): Atomic index. species (str): Elemental species. x, y, z (float): Cartesian coordinates of the atom. group (str): A...group name? (Default is None, repeat elemental species.) num2 (int): An "alternate" index. (Don't ask me...) (Default is None, repeat first number.) occupancy (float): PDB occupancy parameter. (Default is 1.) temperature_factor (float): PDB temperature factor parameter. (Default is 0. Returns: (str): The line defining an atom in PDB format Warnings: * The [PDB docs](https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/tutorials/pdbintro.html) indicate that the xyz coordinates might need to be in some sort of orthogonal basis. If you have weird behaviour, this might be a good place to investigate. """ if group is None: group = species if num2 is None: num2 = num return "ATOM {:>6} {:>4} {:>4} {:>5} {:10.3f} {:7.3f} {:7.3f} {:5.2f} {:5.2f} {:>11} \n".format( num, species, group, num2, x, y, z, occupancy, temperature_factor, species )
92a5d62f3c4f6d927aa5a6010b217344d0d241d3
5,275
def get_insert_components(options): """ Takes a list of 2-tuple in the form (option, value) and returns a triplet (colnames, placeholders, values) that permits making a database query as follows: c.execute('INSERT INTO Table ({colnames}) VALUES {placeholders}', values). """ col_names = ','.join(opt[0] for opt in options) placeholders = ','.join('?' for i in range(len(options))) if len(col_names) > 0: col_names = ',' + col_names if len(placeholders) > 0: placeholders = ',' + placeholders values = tuple(opt[1] for opt in options) return col_names, placeholders, values
3e1deecd39b0e519124278f47713d5b3a1571815
5,276
import torch def add_dims_right(tensor, ndims, right_indent=0): """ Add empty dimensions to the right of tensor shape """ assert right_indent >= 0 for i in range(ndims): tensor = torch.unsqueeze(tensor, -1-right_indent) return tensor
7d4c1b47eb659f0bcfc9dbcf7f7b04c1ccbafb80
5,279
def get_submodel_name(history = 60, lag = 365, num_neighbors = 20, margin_in_days = None, metric = "cos"): """Returns submodel name for a given setting of model parameters """ submodel_name = '{}-autoknn-hist{}-nbrs{}-margin{}-lag{}'.format(metric, history, num_neighbors, margin_in_days, lag) return submodel_name
69fa276a86c39f342ffceba72408ab6970dd0a41
5,280
import csv def create_column_dicts(path_to_input): """Creates dictionaries: {column_index, column_name} and {column_name, column_index}""" cols = {} with open(path_to_input, newline="") as csvfile: inputreader = csv.reader(csvfile, delimiter=",") row = next(inputreader) for i, col in enumerate(row): cols[i] = col # reverse dictionary: {column_name, column_index} cols_inds = {v: k for k, v in cols.items()} return cols, cols_inds
13bf2e3c99fea9b1d2580b7bfc34e445af8b7e98
5,285
import string def get_sentiment(text, word_map): """ Identifies the overall sentiment of the text by taking the average of each word. Note: Words not found in the word_map dict are give zero value. """ # remove all punctuation text = text.translate(str.maketrans("", "", string.punctuation)) # split into tokens text = text.split() total_score, length = 0, 0 # get score for each word, put zero if not found scores = (word_map.get(token.lower(), 0) for token in text) # find average score for score in scores: total_score += score length += 1 return total_score / length
ee9e57c999539c0126e5c0d38711a617e82dab10
5,286
def read_warfle_text(path: str) -> str: """Returns text from *.warfle files""" try: with open(path, "r") as text: return text.read() except Exception as e: raise Exception(e)
ba15fe6a62fbefe492054b0899dcdbff35462154
5,294
def units_to_msec(units, resolution): """Convert BLE specific units to milliseconds.""" time_ms = units * float(resolution) / 1000 return time_ms
49588d7961593b2ba2e57e1481d6e1430b4a3671
5,300
def is_data(data): """ Check if a packet is a data packet. """ return len(data) > 26 and ord(data[25]) == 0x08 and ord(data[26]) in [0x42, 0x62]
edb2a6b69fde42aef75923a2afbd5736d1aca660
5,302
def get_tf_metric(text): """ Computes the tf metric Params: text (tuple): tuple of words Returns: tf_text: format: ((word1, word2, ...), (tf1, tf2, ...)) """ counts = [text.count(word) for word in text] max_count = max(counts) tf = [counts[i]/max_count for i in range(0, len(counts))] return text, tf
6397e150fa55a056358f4b28cdf8a74abdc7fdb6
5,303
import struct def incdata(data, s): """ add 's' to each byte. This is useful for finding the correct shift from an incorrectly shifted chunk. """ return b"".join(struct.pack("<B", (_ + s) & 0xFF) for _ in data)
89633d232d655183bee7a20bd0e1c5a4a2cc7c05
5,308
import math def tangent_circle(dist, radius): """ return tangent angle to a circle placed at (dist, 0.0) with radius=radius For non-existing tangent use 100 degrees. """ if dist >= radius: return math.asin(radius/float(dist)) return math.radians(100)
bcde88456a267239566f22bb6ea5cf00f64fa08e
5,310
import re def server_version(headers): """Extract the firmware version from HTTP headers.""" version_re = re.compile(r"ServerTech-AWS/v(?P<version>\d+\.\d+\w+)") if headers.get("Server"): match = version_re.match(headers["Server"]) if match: return match.group("version")
24151f3898430f5395e69b4dd7c42bd678626381
5,314
def parse_locator(src): """ (src:str) -> [pathfile:str, label:either(str, None)] """ pathfile_label = src.split('#') if len(pathfile_label)==1: pathfile_label.append(None) if len(pathfile_label)!=2: raise ValueError('Malformed src: %s' % (src)) return pathfile_label
970bc1e2e60eec4a54cd00fc5984d22ebc2b8c7a
5,317
from typing import List from typing import Optional def check(s: str) -> None: """ Checks if the given input string of brackets are balanced or not Args: s (str): The input string """ stack: List[str] = [] def get_opening(char: str) -> Optional[str]: """ Gets the corresponding opening braces of the given input character. Args: char (str): The closing braces Returns: str: The corresponding open braces. """ if char == ")": return "(" if char == "]": return "[" if char == "}": return "{" return None # for every character in the given input string for char in s: # if the string is an opening brace, push to stack if char in ("(", "{", "["): stack.append(char) else: try: # if the top element of the stack is the same as # the corresponding opening bracket of the current # character, pop the element if get_opening(char) == stack[-1]: stack.pop() # else, the input string is unbalanced, break out of the # loop else: break except IndexError: break else: # if the loop terminated normally, and stack is empty, print success message if len(stack) == 0: print("Balanced.") # else print unsuccessful message else: print("Not balanced.") return # since at this point the loop terminated abnormally, # print unsuccessful message print("Not balanced.")
720018e5b39e070f48e18c502e8a842feef32840
5,319
def format_address(msisdn): """ Format a normalized MSISDN as a URI that ParlayX will accept. """ if not msisdn.startswith('+'): raise ValueError('Only international format addresses are supported') return 'tel:' + msisdn[1:]
f5a5cc9f8bcf77f1185003cfd523d7d6f1212bd8
5,320
import math def ellipse_properties(x, y, w): """ Given a the (x,y) locations of the foci of the ellipse and the width return the center of the ellipse, width, height, and angle relative to the x-axis. :param double x: x-coordinates of the foci :param double y: y-coordinates of the foci :param double w: width of the ellipse :rtype: tuple of doubles :returns: (center_coordinates, width, height, angle_in_rads) """ p1 = [x[0], y[0]] p2 = [x[1], y[1]] #center point xy = [(p1[0] + p2[0])/2, (p1[1] + p2[1])/2] #distance between points d = ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**(0.5) #theta to positive Xaxis angle = math.atan((p1[1] - p2[1])/(p1[0] - p2[0])) #sin = math.sin(-angle) #cos = math.cos(-angle) #width will be the axis the points lie on width = 2*((0.5*d)**2 + (0.5*w)**2)**(0.5) height = w return (xy, width, height, angle*180/math.pi)
95864eac0feb9c34546eefed5ca158f330f88e3d
5,324
def _get_precision_type(network_el): """Given a network element from a VRP-REP instance, returns its precision type: floor, ceil, or decimals. If no such precision type is present, returns None. """ if 'decimals' in network_el: return 'decimals' if 'floor' in network_el: return 'floor' if 'ceil' in network_el: return 'ceil' return None
b3b451a26ec50ce5f2424ea7a3652123ae96321d
5,327
def collections(id=None): """ Return Collections Parameters ---------- id : STR, optional The default is None, which returns all know collections. You can provide a ICOS URI or DOI to filter for a specifict collection Returns ------- query : STR A query, which can be run against the SPARQL endpoint. """ if not id: coll = '' # create an empyt string insert into sparql query else: coll = ''.join(['FILTER(str(?collection) = "' + id+ '" || ?doi = "' + id + '") .']) query = """ prefix cpmeta: <http://meta.icos-cp.eu/ontologies/cpmeta/> prefix dcterms: <http://purl.org/dc/terms/> select * where{ ?collection a cpmeta:Collection . %s OPTIONAL{?collection cpmeta:hasDoi ?doi} . ?collection dcterms:title ?title . OPTIONAL{?collection dcterms:description ?description} FILTER NOT EXISTS {[] cpmeta:isNextVersionOf ?collection} } order by ?title """ % coll return query
0cd1704d2ac43f34d6e83a3f9e9ead39db390c2e
5,331
def bib_to_string(bibliography): """ dict of dict -> str Take a biblatex bibliography represented as a dictionary and return a string representing it as a biblatex file. """ string = '' for entry in bibliography: string += '\n@{}{{{},\n'.format( bibliography[entry]['type'], bibliography[entry]['id'] ) for field in bibliography[entry]: if field != 'id' and field != 'type': string += '\t{} = {{{}}},\n'.format( field, bibliography[entry][field] ) string = string[:-2] + '}\n' return string
c8fc4247210f74309929fdf9b210cd6f1e2ece3f
5,335
def get_tile_prefix(rasterFileName): """ Returns 'rump' of raster file name, to be used as prefix for tile files. rasterFileName is <date>_<time>_<sat. ID>_<product type>_<asset type>.tif(f) where asset type can be any of ["AnalyticMS","AnalyticMS_SR","Visual","newVisual"] The rump is defined as <date>_<time>_<sat. ID>_<product type> """ return rasterFileName.rsplit("_", 1)[0].rsplit("_AnalyticMS")[0]
15b517e5ba83b2cfb5f3b0014d800402c9683815
5,339
import re def MatchNameComponent(key, name_list, case_sensitive=True): """Try to match a name against a list. This function will try to match a name like test1 against a list like C{['test1.example.com', 'test2.example.com', ...]}. Against this list, I{'test1'} as well as I{'test1.example'} will match, but not I{'test1.ex'}. A multiple match will be considered as no match at all (e.g. I{'test1'} against C{['test1.example.com', 'test1.example.org']}), except when the key fully matches an entry (e.g. I{'test1'} against C{['test1', 'test1.example.com']}). @type key: str @param key: the name to be searched @type name_list: list @param name_list: the list of strings against which to search the key @type case_sensitive: boolean @param case_sensitive: whether to provide a case-sensitive match @rtype: None or str @return: None if there is no match I{or} if there are multiple matches, otherwise the element from the list which matches """ if key in name_list: return key re_flags = 0 if not case_sensitive: re_flags |= re.IGNORECASE key = key.upper() name_re = re.compile(r"^%s(\..*)?$" % re.escape(key), re_flags) names_filtered = [] string_matches = [] for name in name_list: if name_re.match(name) is not None: names_filtered.append(name) if not case_sensitive and key == name.upper(): string_matches.append(name) if len(string_matches) == 1: return string_matches[0] if len(names_filtered) == 1: return names_filtered[0] return None
ad522feba9cabb3407e3b8e1e8c221f3e9800e16
5,342
def _non_overlapping_chunks(seq, size): """ This function takes an input sequence and produces chunks of chosen size that strictly do not overlap. This is a much faster implemetnation than _overlapping_chunks and should be preferred if running on very large seq. Parameters ---------- seq : tuple or list Sequence of integers. size : int Length of each produced chunk. Returns ------- zip zip object that produces chunks of specified size, one at a time. """ return zip(*[iter(seq)] * size)
15b5d2b4a7d8df9785ccc02b5369a3f162704e9e
5,344
def neighbour(x,y,image): """Return 8-neighbours of image point P1(x,y), in a clockwise order""" img = image.copy() x_1, y_1, x1, y1 = x-1, y-1, x+1, y+1; return [img[x_1][y], img[x_1][y1], img[x][y1], img[x1][y1], img[x1][y], img[x1][y_1], img[x][y_1], img[x_1][y_1]]
8e645f7634d089a0e65335f6ea3363d4ed66235b
5,348
def gravity_effect(position, other_position): """Return effect other_position has on position.""" if position == other_position: return 0 elif position > other_position: return -1 return 1
25130c253cb888057e9b52817cac9cf3778a4c69
5,350
import fnmatch def ignore_paths(path_list, ignore_patterns, process=str): """ Go through the `path_list` and ignore any paths that match the patterns in `ignore_patterns` :param path_list: List of file/directory paths. :param ignore_patterns: List of nukeignore patterns. :param process: Function to apply to every element in the path list before performing match. :return: The updated path list """ for pattern in ignore_patterns: path_list = [ n for n in path_list if not fnmatch.fnmatch(process(n), pattern) ] return path_list
63196e54eb4505cbe12ebf77d2a42fede68c1d0b
5,351
def reachable(Adj, s, t): """ Adj is adjacency list rep of graph Return True if edges in Adj have directed path from s to t. Note that this routine is one of the most-used and most time-consuming of this whole procedure, which is why it is passed an adjacency list rep rather than a list of vertices and edges, since the adjacency list rep is easy to update when a new edge is committed to in RP. """ # search for path Q = [ s ] # vertices to expand R = set([s]) # reachable while Q: i = Q.pop() for j in Adj[i]: if j == t: return True if j not in R: R.add(j) Q.append(j) return False
dc0ea0c6d2314fa1c40c3f3aa257a1c77892141f
5,353
def concatenate_unique(la, lb): """Add all the elements of `lb` to `la` if they are not there already. The elements added to `la` maintain ordering with respect to `lb`. Args: la: List of Python objects. lb: List of Python objects. Returns: `la`: The list `la` with missing elements from `lb`. """ la_set = set(la) for l in lb: if l not in la_set: la.append(l) la_set.add(l) return la
307fde291233727c59e2211afc3e0eed7c8ea092
5,354
def create_feature_indices(header): """ Function to return unique features along with respective column indices for each feature in the final numpy array Args: header (list[str]): description of each feature's possible values Returns: feature_indices (dict): unique feature names as keys with value types (dicrete or continuous) and data column indices where present """ feature_indices = {} for i, head in enumerate(header): current = head.split("->") str_name = current[0].replace(" ", "_") if current[0] == "mask": feature_indices["presence_" + current[1].replace(" ", "_")] = ["discrete", i] elif feature_indices == {} or str_name not in feature_indices: if len(current) > 1: feature_indices[str_name] = ["discrete", i] else: feature_indices[str_name] = ["continuous", i] elif str_name in feature_indices: feature_indices[str_name].extend([i]) return feature_indices
a29d8c4c8f3a31ad516216756b7eba7eb4110946
5,364
def lower(word): """Sets all characters in a word to their lowercase value""" return word.lower()
f96b1470b3ab1e31cd1875ad9cbf9ed017aa0158
5,365
def _in_dir(obj, attr): """Simpler hasattr() function without side effects.""" return attr in dir(obj)
f95e265d278e3014e8e683a872cd3b70ef6133c9
5,366
def get_element_parts( original_list: list, splitter_character: str, split_index: int ) -> list: """ Split all elements of the passed list on the passed splitter_character. Return the element at the passed index. Parameters ---------- original_list : list List of strings to be split. splitter_character : str Character to split the strings on. split_index : int Index of the element to be returned. Returns ------- list List with the elements at the passed index. """ new_list = [] for element in original_list: temp_element = element.rsplit(splitter_character)[split_index] # split element temp_element = temp_element.strip() # clean data temp_element = temp_element.casefold() # force lower case new_list.append(temp_element) return new_list
8c663fd64ebb1b2c53a64a17f7d63e842b457652
5,380
from typing import Tuple from typing import Dict def parse_line_protocol_stat_key(key: str) -> Tuple[str, Dict[str, str]]: """Parseline protocolish key to stat prefix and key. Examples: SNMP_WORKER;hostname=abc.com,worker=snmp-mti will become: ("SNMP_WORKER", {"hostname": "abc.com", "worker": "snmp-mti"}) """ try: prefix, raw_labels = key.split(";", 1) labels = dict(raw_label.split("=", 1) for raw_label in raw_labels.split(",")) return prefix, labels except ValueError: return key, {}
a6806f7dd67fb2a4734caca94bff3d974923f4b2
5,382
def zero_at(pos, size=8): """ Create a size-bit int which only has one '0' bit at specific position. :param int pos: Position of '0' bit. :param int size: Length of value by bit. :rtype: int """ assert 0 <= pos < size return 2**size - 2**(size - pos - 1) - 1
7ebdcc1ac9db4ad934108f67a751b336b4f18011
5,391
def unpack_uid(uid): """ Convert packed PFile UID to standard DICOM UID. Parameters ---------- uid : str packed PFile UID as a string Returns ------- uid : str unpacked PFile UID as string """ return ''.join([str(i-1) if i < 11 else '.' for pair in [(ord(c) >> 4, ord(c) & 15) for c in uid] for i in pair if i > 0])
cb131f3df386c40382cf70ddee5125f901de5fa8
5,398
from typing import Counter def generate_samples(n_samples, func, *args, **kwargs): """Call a function a bunch of times and count the results. Args: n_samples: Number of time to call the function. func: The function results are counted from. *args **args: The arguments to pass to func. Returns: Counter containing results. """ samples = Counter() for _ in range(n_samples): res = func(*args, **kwargs) samples[res] += 1 return samples
625c2bf6713420e26704d2c2842504343be09434
5,400
def capitalize_1(string): """ Capitalizes a string using a combination of the upper and lower methods. :author: jrg94 :param string: any string :return: a string with the first character capitalized and the rest lowercased """ return string[0].upper() + string[1:].lower()
9ad830a6d38e19b195cd3dff9a38fe89c49bd5c8
5,401
def get_url_and_token(string): """ extract url and token from API format """ try: [token, api] = string.split(":", 1) [_, _, addr, _, port, proto] = api.split("/", 5) url = f"{proto}://{addr}:{port}/rpc/v0" except Exception: raise ValueError(f"malformed API string : {string}") return (url, token)
f3abd327c9de2d098100e539f701bf2fff1742f5
5,403
import json def handle_error(ex, hed_info=None, title=None, return_as_str=True): """Handles an error by returning a dictionary or simple string Parameters ---------- ex: Exception The exception raised. hed_info: dict A dictionary of information. title: str A title to be included with the message. return_as_str: bool If true return as string otherwise as dictionary Returns ------- str or dict """ if not hed_info: hed_info = {} if hasattr(ex, 'error_type'): error_code = ex.error_type else: error_code = type(ex).__name__ if not title: title = '' if hasattr(ex, 'message'): message = ex.message else: message = str(ex) hed_info['message'] = f"{title}[{error_code}: {message}]" if return_as_str: return json.dumps(hed_info) else: return hed_info
4b7bc24c9b4fd83d39f4447e29e383d1769e6b0f
5,405
def command(cmd, label, env={}): """Create a Benchpress command, which define a single benchmark execution This is a help function to create a Benchpress command, which is a Python `dict` of the parameters given. Parameters ---------- cmd : str The bash string that makes up the command label : str The human readable label of the command env : dict The Python dictionary of environment variables to define before execution' Returns ------- command : dict The created Benchpress command """ return {'cmd': cmd, 'label': label, 'env': env}
487e7b8518ae202756177fc103561ea03ded7470
5,409
import struct def decode_ia(ia: int) -> str: """ Decode an individual address into human readable string representation >>> decode_ia(4606) '1.1.254' See also: http://www.openremote.org/display/knowledge/KNX+Individual+Address """ if not isinstance(ia, int): ia = struct.unpack('>H', ia)[0] return '{}.{}.{}'.format((ia >> 12) & 0x1f, (ia >> 8) & 0x07, (ia) & 0xff)
6f107f47110a59ca16fe8cf1a7ef8f061bf117c7
5,411
from pathlib import Path def _validate_magics_flake8_warnings(actual: str, test_nb_path: Path) -> bool: """Validate the results of notebooks with warnings.""" expected = ( f"{str(test_nb_path)}:cell_1:1:1: F401 'random.randint' imported but unused\n" f"{str(test_nb_path)}:cell_1:2:1: F401 'IPython.get_ipython' imported but unused\n" f"{str(test_nb_path)}:cell_3:6:21: E231 missing whitespace after ','\n" f"{str(test_nb_path)}:cell_3:11:10: E231 missing whitespace after ','\n" ) return actual == expected
4baa419ad4e95bf8cc794298e70211c0fa148e5b
5,412
def _split_uri(uri): """ Get slash-delimited parts of a ConceptNet URI. Args: uri (str) Returns: List[str] """ uri = uri.lstrip("/") if not uri: return [] return uri.split("/")
91b48fff83041fe225a851a9e3016e3722bd9771
5,413
import re def split_range_str(range_str): """ Split the range string to bytes, start and end. :param range_str: Range request string :return: tuple of (bytes, start, end) or None """ re_matcher = re.fullmatch(r'([a-z]+)=(\d+)?-(\d+)?', range_str) if not re_matcher or len(re_matcher.groups()) != 3: return None unit, start, end = re_matcher.groups() start = int(start) if type(start) == str else None end = int(end) if type(end) == str else None return unit, start, end
a6817017d708abf774277bf8d9360b63af78860d
5,428
def min_equals_max(min, max): """ Return True if minimium value equals maximum value Return False if not, or if maximum or minimum value is not defined """ return min is not None and max is not None and min == max
1078e9ed6905ab8b31b7725cc678b2021fc3bc62
5,433
import socket def validate_args(args): """ Checks if the arguments are valid or not. """ # Is the number of sockets positive ? if not args.number > 0: print("[ERROR] Number of sockets should be positive. Received %d" % args.number) exit(1) # Is a valid IP address or valid name ? try: servers = socket.getaddrinfo(args.address, args.port, proto=socket.IPPROTO_TCP) return servers[0] except socket.gaierror as error: print(error) print("Please, provide a valid IPv4, IPv6 address or a valid domain name.") exit(1)
37a77f59ae78e3692e08742fab07f35cf6801e54
5,439
def fibonacci(n: int) -> int: """ Calculate the nth Fibonacci number using naive recursive implementation. :param n: the index into the sequence :return: The nth Fibonacci number is returned. """ if n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2)
08de1ff55f7cada6a940b4fb0ffe6ba44972b42d
5,443
def AverageZComparison(x, y): """ Take the average of second and third element in an array and compare which is bigger. To be used in conjunction with the sort function. """ xsum = x[1]+x[2] ysum = y[1]+y[2] if xsum < ysum: return -1 if xsum > ysum: return 1 return 0
84c9e7b92df4b3e4914c769293f71790def5e4dd
5,450
from pathlib import Path def parse_taxid_names(file_path): """ Parse the names.dmp file and output a dictionary mapping names to taxids (multiple different keys) and taxids to scientific names. Parameters ---------- file_path : str The path to the names.dmp file. Returns ------- name2taxid : dict Keys are all possible names and values are taxids. taxid2name : dict Keys are taxids and values are scientific names. """ names = Path(file_path) with names.open() as f: lines_processed = 0 name2taxid = {} taxid2name = {} for line in f: lines_processed += 1 if lines_processed % 1000000 == 0: print('processing line', str(lines_processed)) entries = [entry.strip() for entry in line.split('|')] name2taxid[entries[1]] = entries[0] if 'scientific name' in line: taxid2name[entries[0]] = entries[1] return name2taxid, taxid2name
1d136f73a56ac8d3c02fd53c6e7928a39440e27a
5,451
from typing import List def count_pairs(array: List[int], difference: int) -> int: """ Given an array of integers, count the number of unique pairs of integers that have a given difference. These pairs are stored in a set in order to remove duplicates. Time complexity: O(n^2). :param array: is the array to count. :param difference: is the difference between two elements. :return: the number of unique pairs of integers that have a given difference. """ pairs = set() for i in range(len(array)): for j in range(len(array)): if array[i] - array[j] == difference: pairs.add((array[i], array[j])) return len(pairs)
e027e8885f4c4531da9b7dab7de8e84a7004c913
5,457
def binary_tail(n: int) -> int: """ The last 1 digit and the following 0s of a binary representation, as a number """ return ((n ^ (n - 1)) + 1) >> 1
63460cef7b39b7e7ee2ec880810ff71d82be01e9
5,459
from datetime import datetime def time_left(expire_date): """Return remaining days before feature expiration or 0 if expired.""" today_dt = datetime.today() expire_dt = datetime.strptime(expire_date, "%d-%b-%Y") # Calculate remaining days before expiration days_left_td = expire_dt - today_dt days_left = days_left_td.days if days_left <= 0: days_left = 0 return days_left
652acd27b0d4fa9b21321df4ff8ce6ce15b97ed6
5,460
def video_id(video_id_or_url): """ Returns video id from given video id or url Parameters: ----------- video_id_or_url: str - either a video id or url Returns: -------- the video id """ if 'watch?v=' in video_id_or_url: return video_id_or_url.split('watch?v=')[1] else: # assume we already have an video id return video_id_or_url
9f680ac621e1f5c6314a6a3e97093d786fa7ea33
5,461
import importlib def _bot_exists(botname): """ Utility method to import a bot. """ module = None try: module = importlib.import_module('%s.%s' % (botname, botname)) except ImportError as e: quit('Unable to import bot "%s.%s": %s' % (botname, botname, str(e))) return module
c091be6d586faa8aacd48b30f4ce2f4fcc665e0b
5,467
def _format_exponent_notation(input_number, precision, num_exponent_digits): """ Format the exponent notation. Python's exponent notation doesn't allow for a user-defined number of exponent digits. Based on [Anurag Uniyal's answer][answer] to the StackOverflow question ['Python - number of digits in exponent'][question] [question]: http://stackoverflow.com/q/9910972/95592 [answer]: http://stackoverflow.com/a/9911741/95592 """ python_exponent_notation = '{number:.{precision}e}'.format( number=input_number, precision=precision) mantissa, exponent = python_exponent_notation.split('e') # Add 1 to the desired number of exponenent digits to account for the sign return '{mantissa}e{exponent:+0{exp_num}d}'.format( mantissa=mantissa, exponent=int(exponent), exp_num=num_exponent_digits+1)
59f61897c70ca1d9f95412b2892d5c9592e51561
5,468
def npv(ico, nci, r, n): """ This capital budgeting function computes the net present value on a cash flow generating investment. ico = Initial Capital Outlay nci = net cash inflows per period r = discounted rate n = number of periods Example: npv(100000, 15000, .03, 10) """ pv_nci = 0 for x in range(n): pv_nci = pv_nci + (nci/((1 + r) ** (x + 1))) return pv_nci - ico
fa3128de0fe8a2f7b8bbe754f0e1b1e1a0eb222d
5,470
def maybe_flip_x_across_antimeridian(x: float) -> float: """Flips a longitude across the antimeridian if needed.""" if x > 90: return (-180 * 2) + x else: return x
50fac7a92d0ebfcd003fb478183b05668b9c909c
5,479
import collections def _group_by(input_list, key_fn): """Group a list according to a key function (with a hashable range).""" result = collections.defaultdict(list) for x in input_list: result[key_fn(x)].append(x) return result
288c108588f9e4ea60c4dac6ff656c8c8ffde580
5,484
def multiply_values(dictionary: dict, num: int) -> dict: """Multiplies each value in `dictionary` by `num` Args: dictionary (dict): subject dictionary num (int): multiplier Returns: dict: mapping of keys to values multiplied by multiplier """ return ( {key: value * num for key, value in dictionary.items()} if dictionary is not None else {} )
16eb87d60da64d648113858ba5cb4308137e0a14
5,488
from typing import Any def desg_to_prefix(desg: str) -> Any: """Convert small body designation to file prefix.""" return (desg.replace('/', '').replace(' ', '') .replace('(', '_').replace(')', '_'))
badde1e3ec9c3f669c7cce8aa55646b15cc5f4c8
5,489
def field2nullable(field, **kwargs): """Return the dictionary of swagger field attributes for a nullable field. :param Field field: A marshmallow field. :rtype: dict """ attributes = {} if field.allow_none: omv = kwargs['openapi_major_version'] attributes['x-nullable' if omv < 3 else 'nullable'] = True return attributes
dd5d4cd63aeede4ef9356baa9fe9a48bd5f87841
5,490
def get_chrom_start_end_from_string(s): """Get chrom name, int(start), int(end) from a string '{chrom}__substr__{start}_{end}' ...doctest: >>> get_chrom_start_end_from_string('chr01__substr__11838_13838') ('chr01', 11838, 13838) """ try: chrom, s_e = s.split('__substr__') start, end = s_e.split('_') return chrom, int(start), int(end) except Exception: raise ValueError("String %s must be of format '{chrom}__substr__{start}_{end}'" % s)
5dbce8eb33188c7f06665cf92de455e1c705f38b
5,498
def is_multioutput(y): """Whether the target y is multi-output (or multi-index)""" return hasattr(y, "shape") and y.ndim == 2 and y.shape[1] > 1
bcdaa46c304fec50c173dffca5f1f1d5d8871a58
5,515
from typing import Optional def prepare_error_message(message: str, error_context: Optional[str] = None) -> str: """ If `error_context` is not None prepend that to error message. """ if error_context is not None: return error_context + ": " + message else: return message
ea95d40797fcc431412990706d5c098a07986156
5,521
from datetime import datetime def calcular_diferencia_dias(fin_dia): """ Obtiene la diferencia de dias entre una fecha y hoy """ hoy = datetime.now() end = datetime.strptime(str(fin_dia), '%Y-%m-%d') return abs(end - hoy).days
41b732f3bb09d2deca4be034273a5fed74971386
5,526
def pairwise_list(a_list): """ list转换为成对list "s -> (s0,s1), (s1,s2), (s2, s3), ..." :param a_list: list :return: 成对list """ if len(a_list) % 2 != 0: raise Exception("pairwise_list error!") r_list = [] for i in range(0, len(a_list) - 1, 2): r_list.append([a_list[i], a_list[i + 1]]) return r_list
5142fb2e00c931ab57fc9028eb9b6df5a98c0342
5,530
from datetime import datetime def read_hotfilm_from_lvm(filename, dt=1e-3): """Reads 2-channel hotfilm data from a Labview text file.""" times = [] ch1 = [] ch2 = [] data = [line.rstrip() for line in open(filename).readlines()] line = data[0].split(',')[1:] t = [int(float(n)) for n in line[:5]] seconds = float(line[5]) useconds = int(1e6 * (seconds - int(seconds))) start_time = datetime(t[0], t[1], t[2], t[3], t[4], int(seconds), useconds) seconds = 0 for line in data: line = line.split(',')[1:] ch1.append(float(line[6])) ch2.append(float(line[7])) times.append(seconds) seconds += dt return start_time, times, ch1, ch2
e0dadac656120173e5833e6eb36498943613e8f5
5,532
def draft_github_comment(template, result): """ Use a template to draft a GitHub comment :template: (str) the name of the template file :result: (ContentError) the error to display in the comment """ # start with template with open(template, 'r') as f: contents = f.read() # replace variables in template with ContentError values for var in vars(result).keys(): contents = contents.replace(f'{{{{ {var} }}}}', str(getattr(result, var))) return contents
42842b7af06da8a54c0647e5aac079132e82de5a
5,536
import csv def get_zip_rate_areas(file_path): """ reads zips.csv file and returns the content as a dictionary Args: file_path: the path to zips.csv file Returns: a dictionary mapping each zip code into a set of rate areas """ zip_rate_areas = dict() with open(file_path, "r") as zip_codes_file: csv_reader = csv.DictReader(zip_codes_file, delimiter=",") for line in csv_reader: zipcode = line["zipcode"] rate_area = f"{line['state']} {line['rate_area']}" if zipcode not in zip_rate_areas: zip_rate_areas[zipcode] = set() zip_rate_areas[zipcode].add(rate_area) return zip_rate_areas
d8405bc466e7bbe949fded4360d4f184024653d2
5,537
def get_file_encoding(filename): """ Get the file encoding for the file with the given filename """ with open(filename, 'rb') as fp: # The encoding is usually specified on the second line txt = fp.read().splitlines()[1] txt = txt.decode('utf-8') if 'encoding' in txt: encoding = txt.split()[-1] else: encoding = 'utf-8' # default return str(encoding)
c91a8f71429ed5f6eccd7379c66b4ee4c2d73989
5,539
from typing import List import logging def get_all_loggers() -> List: """Return list of all registered loggers.""" logger_dict = logging.root.manager.loggerDict # type: ignore loggers = [logging.getLogger(name) for name in logger_dict] return loggers
97059a78925ff669a841644b186e39ccd366472d
5,544
import typing def intensity(pixel: typing.Tuple[int, int, int]) -> int: """Sort by the intensity of a pixel, i.e. the sum of all the RGB values.""" return pixel[0] + pixel[1] + pixel[2]
5ba060d409a2f0df148cdc50684b80f920cf314f
5,547
def get_boundary_from_response(response): """ Parses the response header and returns the boundary. :param response: response containing the header that contains the boundary :return: a binary string of the boundary """ # Read only the first value with key 'content-type' (duplicate keys are allowed) content = response.headers.pop('content-type')[0] # Find the start and end index of the boundary b_start = content.find(b'boundary=') b_end = content[b_start:].find(b';') # Separate out boundary if b_end == -1: # If the end point is not found, just go to the end of the content string boundary = content[b_start+9:] else: boundary = content[b_start+9:b_start+b_end] return boundary
66a0112598b2210cca1a2210f6af963dfee641f7
5,553
import re def to_alu_hlu_map(input_str): """Converter for alu hlu map Convert following input into a alu -> hlu map: Sample input: ``` HLU Number ALU Number ---------- ---------- 0 12 1 23 ``` ALU stands for array LUN number hlu stands for host LUN number :param input_str: raw input from naviseccli :return: alu -> hlu map """ ret = {} if input_str is not None: pattern = re.compile(r'(\d+)\s*(\d+)') for line in input_str.split('\n'): line = line.strip() if len(line) == 0: continue matched = re.search(pattern, line) if matched is None or len(matched.groups()) < 2: continue else: hlu = matched.group(1) alu = matched.group(2) ret[int(alu)] = int(hlu) return ret
8e211b7efa3f8dd23c042f046d881daf987062bc
5,558
def _default_value(argument, default): """Returns ``default`` if ``argument`` is ``None``""" if argument is None: return default else: return argument
52eed8ddaf3c52adba69044cc462fc11279670c5
5,564
def is_constant_type(expression_type): """Returns True if expression_type is inhabited by a single value.""" return (expression_type.integer.modulus == "infinity" or expression_type.boolean.HasField("value") or expression_type.enumeration.HasField("value"))
66a3237971299df3c7370f039d87a8b5f4ae2be5
5,565
def check_strand(strand): """ Check the strand format. Return error message if the format is not as expected. """ if (strand != '-' and strand != '+'): return "Strand is not in the expected format (+ or -)"
9c2e720069ad8dcc8f867a37925f6e27e91dcb3f
5,575
def _copy_df(df): """ Copy a DataFrame """ return df.copy() if df is not None else None
263bf1cf9cbdae371ea3e4685b4638e8a5714d7f
5,576
def autosolve(equation): """ Automatically solve an easy maths problem. :type equation: string :param equation: The equation to calculate. >>> autosolve("300 + 600") 900 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[0]) except ValueError: # Try to set a variable to a decimal num1 = float(equation.split(" ")[0]) try: # Try to set a variable to an integer num2 = int(equation.split(" ")[2]) except ValueError: # Try to set a variable to a decimal num2 = float(equation.split(" ")[2]) # If the lowercase version of the operator is '+', 'plus' or 'add' if equation.split(" ")[1].lower() in ["+", "plus", "add"]: # Return the answer return num1 + num2 # If the lowercase version of the operator is '-', 'minus' or 'subtract' elif equation.split(" ")[1].lower() in ["-", "minus", "subtract"]: # Return the answer return num1 - num2 # If the lowercase version of the operator is '*', 'times', 'multiply' elif equation.split(" ")[1].lower() in ["*", "times", "multiply"]: # Return the answer return num1 * num2 # If the lowercase version of the operator is '/', 'divide' or 'quotient' elif equation.split(" ")[1].lower() in ["/", "divide", "quotient"]: # Return the answer return num1 / num2 # If the lowercase version of the operator is '%, 'remainder' or 'rem' elif equation.split(" ")[1].lower() in ["%", "remainder", "rem"]: # Return the answer return num1 % num2 # Raise a warning raise ValueError("Invalid operation provided.")
a4db1dedffdccc44d7747c4743f4f2eaf8dbd81a
5,577
def api_url(service: str = "IPublishedFileService", function: str = "QueryFiles", version: str = "v1") -> str: """ Builds a steam web API url. :param service: The steam service to attach to. :param function: The function to call. :param version: The API version. :return: The built URL. """ return "https://api.steampowered.com/%s/%s/%s/" % ( service, function, version )
2538ab8c8035c491611585089ddd3a1625e423cc
5,578
def cleaned_reviews_dataframe(reviews_df): """ Remove newline "\n" from titles and descriptions, as well as the "Unnamed: 0" column generated when loading DataFrame from CSV. This is the only cleaning required prior to NLP preprocessing. INPUT: Pandas DataFrame with 'title' and 'desc' column names OUTPUT: Cleaned DataFrame with combined 'title_desc' column """ reviews_df['title'] = reviews_df['title'].str.replace('\n', '') reviews_df['desc'] = reviews_df['desc'].str.replace('\n','') reviews_df['title_desc'] = reviews_df['title'] + reviews_df['desc'] if 'Unnamed: 0' in set(reviews_df.columns): reviews_df = reviews_df.drop('Unnamed: 0', axis=1) return reviews_df
8f805f556667f5d734d4d272a2194784d37ce99c
5,581
def not_list(l): """Return the element wise negation of a list of booleans""" assert all([isinstance(it, bool) for it in l]) return [not it for it in l]
6d30f5dd587cdc69dc3db94abae92a7a8a7c610d
5,582
def line_edit_style_factory(txt_color='white', tgt_layer_color='white', bg_color='#232323'): """Generates a string of a qss style sheet for a line edit. Colors can be supplied as strings of color name or hex value. If a color arg receives a tuple we assume it is either an rgb or rgba tuple. :param txt_color: Color the text of the line edit should be. :param tgt_layer_color: The color of the current target layer. :param bg_color: The color that will fill the background of the line eidit. :return: string of qss """ def handle_rgb(color_tuple): """Assumes the tuple is rgba or rgb (len 4 or 3)""" val = ','.join([str(i) for i in color_tuple]) if len(color_tuple) == 4: rgb = 'rgba({})'.format(val) else: rgb = 'rgb({})'.format(val) return rgb if isinstance(bg_color, tuple): bg_color = handle_rgb(bg_color) style = ''' QTextEdit, QLineEdit { border-radius: 11px; border: 1px solid transparent; background-color: %s; color: %s } QTextEdit:hover, QLineEdit:hover { border: 1px solid %s } QTextEdit:focus, QLineEdit:focus { border: 2px solid %s } ''' % (bg_color, txt_color, tgt_layer_color, tgt_layer_color) return style
10670afc32ec1c19d09dd72fc0e23bb1583ba3af
5,587
def CallCountsToMockFunctions(mock_function): """A decorator that passes a call count to the function it decorates. Examples: @CallCountsToMockFunctions def foo(call_count): return call_count ... ... [foo(), foo(), foo()] [0, 1, 2] """ counter = [0] def Result(*args, **kwargs): # For some values of `counter`, the mock function would simulate raising # an exception, so let the test case catch the exception via # `unittest.TestCase.assertRaises()` and to also handle recursive functions. prev_counter = counter[0] counter[0] += 1 ret_value = mock_function(prev_counter, *args, **kwargs) return ret_value return Result
cc621cabdf87ff554bb02c25282e99fadcaaa833
5,589
async def ping(): """ .ping: respond with pong """ return "pong"
988165efb5087fd838a2930dbe4ed540b2d70037
5,590
def merge_sort(array): """ Merge Sort Complexity: O(NlogN) """ if len(array) > 1: mid = len(array) // 2 left = array[:mid] right = array[mid:] left = merge_sort(left) right = merge_sort(right) array = [] # This is a queue implementation. We can also use # a deque but slicing it needs the itertools slice # function which I didn't want to use. More on that # in the stacks and queues chapter. l1 = l2 = 0 while len(left) > l1 and len(right) > l2: if left[l1] < right[l2]: array.append(left[l1]) l1 += 1 else: array.append(right[l2]) l2 += 1 while len(left) > l1: array.append(left[l1]) l1 += 1 while len(right) > l2: array.append(right[l2]) l2 += 1 return array
73b3ac5b950f5788cbc3e7c98d2a4d5aac427929
5,593
def ErrorCorrect(val,fEC): """ Calculates the error correction parameter \lambda_{EC}. Typical val is 1.16. Defined in Sec. IV of [1]. Parameters ---------- val : float Error correction factor. fEC : float Error correction efficiency. Returns ------- float Error correction parameter. """ return val * fEC
83c4483c56c7c3b79060dd070ec68f6dfd5ee749
5,595
def are_in_file(file_path, strs_to_find): """Returns true if every string in the given strs_to_find array is found in at least one line in the given file. In particular, returns true if strs_to_find is empty. Note that the strs_to_find parameter is mutated.""" infile = open(file_path) for line in infile: if len(strs_to_find) == 0: return True index = 0 while index < len(strs_to_find): if strs_to_find[index] in line: del strs_to_find[index] else: index = index + 1 return len(strs_to_find) == 0
474234a35bf885c5f659f32a25c23580f2014cc2
5,597
def text_box_end_pos(pos, text_box, border=0): """ Calculates end pos for a text box for cv2 images. :param pos: Position of text (same as for cv2 image) :param text_box: Size of text (same as for cv2 image) :param border: Outside padding of textbox :return box_end_pos: End xy coordinates for text box (end_point for cv2.rectangel()) """ box_x, box_y = pos text_w, text_h = text_box box_end_pos = (box_x + text_w + border, box_y + text_h + border) return box_end_pos
5bd2b46fe3456ccdef1407b90256edeb310d92bc
5,604
from typing import List from typing import Tuple def cnf_rep_to_text(cnf_rep: List[List[Tuple[str, bool]]]) -> str: """ Converts a CNF representation to a text. :param cnf_rep: The CNF representation to convert. :return: The text representation of the CNF. """ lines = [] for sentence in cnf_rep: sentence_str = '' first_in_clause = True for atom in sentence: if first_in_clause: first_in_clause = False else: sentence_str += ' ' if atom[1]: sentence_str += atom[0] else: sentence_str += '!' + atom[0] lines.append(sentence_str) return '\n'.join(lines)
dec3754493cfb0bd9fb5e68d2bab92a40bd0f294
5,605
def reshape_for_linear(images): """Reshape the images for the linear model Our linear model requires that the images be reshaped as a 1D tensor """ n_images, n_rgb, img_height, img_width = images.shape return images.reshape(n_images, n_rgb * img_height * img_width)
dffc5e7d0f96c4494443a7480be081b8fe6b4abd
5,606
from json import load import logging def read_drive_properties(path_name): """ Reads drive properties from json formatted file. Takes (str) path_name as argument. Returns (dict) with (bool) status, (str) msg, (dict) conf """ try: with open(path_name) as json_file: conf = load(json_file) return {"status": True, "msg": f"Read from file: {path_name}", "conf": conf} except (IOError, ValueError, EOFError, TypeError) as error: logging.error(str(error)) return {"status": False, "msg": str(error)} except: logging.error("Could not read file: %s", path_name) return {"status": False, "msg": f"Could not read file: {path_name}"}
18b9051801b032f5aa5532da0cfcca8793be8c91
5,608
def _get_variable_names(expression): """Return the list of variable names in the Numexpr `expression`.""" names = [] stack = [expression] while stack: node = stack.pop() if node.astType == 'variable': names.append(node.value) elif hasattr(node, 'children'): stack.extend(node.children) return list(set(names))
db75b0066b89bc7a6a022a56b28981910836524c
5,611
def get_boundary_levels(eris): """Get boundary levels for eris.""" return [func(eris.keys()) for func in (min, max)]
20d98447e600fecc3b9495e9fb5e5d09ff3b3c1e
5,613