content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def status_request(token): """Create ACME "statusRequest" message. :param unicode token: Token provided in ACME "defer" message. :returns: ACME "statusRequest" message. :rtype: dict """ return { "type": "statusRequest", "token": token, }
eb63269820aff9ef84cb67ef3348d1121be051f5
383,637
import pathlib import click def get_filenames_from_template(photo, filename_template, original_name): """ get list of export filenames for a photo Args: photo: a PhotoInfo instance filename_template: a PhotoTemplate template string, may be None original_name: boolean; if True, use photo's original filename instead of current filename Returns: list of filenames Raises: click.BadOptionUsage if template is invalid """ if filename_template: photo_ext = pathlib.Path(photo.original_filename).suffix filenames, unmatched = photo.render_template(filename_template, path_sep="_") if not filenames or unmatched: raise click.BadOptionUsage( "filename_template", f"Invalid template '{filename_template}': results={filenames} unmatched={unmatched}", ) filenames = [f"{file_}{photo_ext}" for file_ in filenames] else: filenames = [photo.original_filename] if original_name else [photo.filename] return filenames
ce392d636262a59f8bc7cb6f14948c9bdb4f0acc
393,387
from pathlib import Path def path_join(*other): """Add each of other argumetns to path in turn""" return Path().joinpath(*other)
b1c71ddf423dd2852cb3de4f368761415a584be7
524,314
def first(element): """ A wrapper around element[0]. params: element: an element that implements __getitem__ """ return element[0]
e6014c95616e4a95644833deeed01a670649cc94
377,105
import typing def trace_lines_model_checking_mode(stdout) -> typing.List[typing.List[str]]: """ Returns list of lists. Each sublist is a list of lines that make a trace. Args: stdout : stdout of TLC execution run in model checking mode """ ret = [] lines = stdout.split("\n") header_open = False def is_header(line): """One line before the beginning of the trace.""" single_state_trace_header = "is violated by the initial state" in line mult_state_trace_header = line == "Error: The behavior up to this point is:" return single_state_trace_header or mult_state_trace_header def is_start_of_new_trace(line): """When there are multiple traces, closes the previous trace""" # when there are multiple violations, a new trace report starts with: continue_case = line.startswith("Error: Invariant") # when the first violation was in the init state, the second one starts with: init_state_continue_case = line.startswith("Finished computing initial states") return continue_case or init_state_continue_case def is_footer(line): multi_state_footer = ( ("states generated" in line) and ("distinct states found" in line) and ("states left on queue" in line) and (not line.startswith("Progress")) ) or ("Model checking completed" in line) single_state_footer = "Finished in" in line return single_state_footer or multi_state_footer header_cnt = 0 header_ix = -1 for i, line in enumerate(lines): if is_start_of_new_trace(line): header_open = True if 0 < header_cnt: trace = lines[header_ix + 1 : i] ret.append(trace) if is_header(line): header_cnt += 1 header_ix = i # we need boolean header_open because the footer the conditions for the footer # of a single state trace will be met also in the line after the footer of a multi-state trace if header_open and is_footer(line): header_open = False if 0 < header_cnt: trace = lines[header_ix + 1 : i] ret.append(trace) break return ret
26b57ee29370a764b51961d672c5969050dccb85
680,500
import click def format_options(original_function=None, headers=None): """Shared output format options.""" def _format_options(f): f = click.option('--format', '-f', 'fmt', default=None, type=click.Choice(['simple', 'table', 'csv']), help="Output format. Defaults to the value of " "'git config pw.format' else 'table'.")(f) if headers: f = click.option('--column', '-c', 'headers', metavar='COLUMN', multiple=True, default=headers, type=click.Choice(headers), help='Columns to be included in output.')(f) return f if original_function: return _format_options(original_function) return _format_options
c4caed905f16e570abda4893b6c49e9296991c73
261,502
def bbox_to_list(bbox_string): """ Convert bounding box passed in as string such as: "[0.536007, 0.434649, 0.635773, 0.543599]" to list of floats """ bbox = bbox_string.strip('][').split(', ') bbox = [float(x) for x in bbox] return bbox
a1d24730dad42312c9ef9f7541cbf906885202ca
266,406
def mydub(a): """Double a """ return a * 2
bf039316d510db53264ab435e5092477bd57e397
648,533
def R_curv(deltaT_sub, r_min, radius, Q_drop): """ thermal resistance due drop curvature Parameters ---------- deltaT_sub: float temperature difference to the cooled wall in K r_min: float minimum droplet radius in m radius: float radius of drop in m Q_drop: float rate of heat flow through drop in W Returns ---------- R_curv: float thermal resistance due drop curvature in K/W """ R_curv = (deltaT_sub*r_min / radius) / Q_drop return R_curv
176520b43184e879bb25bcecc50e64e6dabaa6cc
10,754
import torch import logging def get_device() -> torch.device: """Gets device to use for PyTorch. Returns: Device. """ use_cuda = torch.cuda.is_available() device = torch.device("cuda" if use_cuda else "cpu") logging.info("Model device: %s", device) return device
587c03df06dc38fe4cd939faa42aeb92377234ed
451,064
def _host_absolute(name): """ Ensure that hostname is absolute. Prevents us from making relative DNS records by mistake. """ if not name.endswith("."): name = name + "." return name
0569be8577063cbbecbed9bc860f686e2080c92b
209,694
def lookup_password(words, uhpd): """ lookup_password(words, (user, host, port, database)) -> password Where 'words' is the output from pgpass.parse() """ user, host, port, database = uhpd for word, (w_host, w_port, w_database, w_user) in words: if (w_user == '*' or w_user == user) and \ (w_host == '*' or w_host == host) and \ (w_port == '*' or w_port == port) and \ (w_database == '*' or w_database == database): return word
33f68e19e18faeef461c0e9c24f7df680c8b0945
112,122
def is_eligible_for_exam(mmtrack, course_run): """ Returns True if user is eligible exam authorization process. For that the course must have exam settings and user must have paid for it. Args: mmtrack (dashboard.utils.MMTrack): a instance of all user information about a program. course_run (courses.models.CourseRun): A CourseRun object. Returns: bool: whether user is eligible or not """ return course_run.has_future_exam and mmtrack.has_paid(course_run.edx_course_key)
2ee804ac8f338186bd543584b207cde440a109c5
678,337
def invert_mapping(kvp): """Inverts the mapping given by a dictionary. :param kvp: mapping to be inverted :returns: inverted mapping :rtype: dictionary """ return {v: k for k, v in list(kvp.items())}
62c16608b83d9a10fe30930add87b8d73ba5e1cd
63,516
def get_armstrong_value(num): """Return Armstrong value of a number, this is the sum of n**k for each digit, where k is the length of the numeral. I.e 54 -> 5**2 + 4**2 -> 41. Related to narcisstic numbers and pluperfect digital invariants. """ num = str(num) length = len(num) armstrong_value = 0 for char in num: armstrong_value += int(char)**length return armstrong_value
fd0692566ab0beffb785c1ac4fbd4aa27893cfbf
41,523
def get_element_text(element): """Builds the element text by iterating through child elements. Parameters ---------- element: lxml.Element The element for which to build text. Returns ------- text: str The inner text of the element. """ text = ''.join(element.itertext()) return text
41409e83a23927a5af0818c5f3faace0ca117751
17,234
def rc4(buffer, key): """ Encrypt / decrypt the content of `buffer` using RC4 algorithm. Parameters ---------- buffer : bytes The bytes sequence to encrypt or decrypt. key : bytes The key to be used to perform the cryptographic operation. Returns ------- A bytes sequence representing the transformed input. More information ---------------- Adapted from http://cypherpunks.venona.com/archive/1994/09/msg00304.html """ # Preparation step state = list(range(256)) x = 0 y = 0 index1 = 0 index2 = 0 for counter in range(256): index2 = (key[index1] + state[counter] + index2) % 256 state[counter], state[index2] = state[index2], state[counter] index1 = (index1 + 1) % len(key) # encryption / decryption step output = [0] * len(buffer) for i in range(len(buffer)): x = (x + 1) % 256 y = (state[x] + y) % 256 state[x], state[y] = state[y], state[x] xorIndex = (state[x] + state[y]) % 256 output[i] = buffer[i] ^ state[xorIndex] return bytes(output)
d6b737e74c1ed04f45f783781307e1f5aca58509
145,167
import math def floor(quantity, units): """Compute the floor of a quantity with units. :param quantity: the quantity to take the ceiling of :param units: the units to convert to before taking the ceiling, and of the result :returns: the ceiling of quantity, measured in units """ number = quantity.to(units).magnitude return math.floor(number) * units
723e4f2816c375b481b2fcf32be627a5f786d114
324,770
def case_sort(string): """ Here are some pointers on how the function should work: 1. Sort the string 2. Create an empty output list 3. Iterate over original string if the character is lower-case: pick lower-case character from sorted string to place in output list else: pick upper-case character from sorted string to place in output list Note: You can use Python's inbuilt ord() function to find the ASCII value of a character """ upper_ch_index = 0 lower_ch_index = 0 sorted_string = sorted(string) for index, character in enumerate(sorted_string): ascii_int = ord(character) if 97 <= ascii_int <= 122: lower_ch_index = index break output = [] for character in string: ascii_int = ord(character) # if character is lower case pick next lower_case character if 97 <= ascii_int <= 122: output.append(sorted_string[lower_ch_index]) lower_ch_index += 1 else: output.append(sorted_string[upper_ch_index]) upper_ch_index += 1 return "".join(output)
70391df1faaba08f0d596a6bd401c80d30fa8923
547,452
def is_mutating(status): """Determines if the statement is mutating based on the status.""" if not status: return False mutating = set(['insert', 'update', 'delete', 'alter', 'create', 'drop']) return status.split(None, 1)[0].lower() in mutating
76c45a300773afe1313c1be36c07bc23b37c06f3
448,047
def merge(dict1,dict2): """ Returns a new dictionary merging (joining keys) dict1 and dict2. If a key appears in only one of dict1 or dict2, the value is the value from that dictionary. If it is in both, the value is the sum of values. Example: merge({'a':1,'b':2},{'b':3,'c':4}) returns {'a':1,'b':5,'c':4} Parameter dict1: The first dictionary to merge Precondition: dict1 a dictionary with int or float values Parameter dict2: The second dictionary to merge Precondition: dict2 a dictionary with int or float values """ result = dict(dict1) # Makes a (shallow) copy for k in dict2: if k in dict1: result[k] = result[k]+1 else: result[k] = 1 return result
e542c33d84611485c8c18087d5bdad71e052749b
140,572
def _remove_lines_starting_with(string, start_char): """ Utility function that removes line starting with the given character in the provided str. :param data: the str to remove lines. :param start_char: the character to look for at the begining of a line. :returns: the string without the lines starting with start_char. """ data = "" for line in string.split('\n'): if not line.startswith(start_char): data += line + '\n' return data
59092b26601fe2b1e0038c21b1fc827dc8ce0fb8
60,458
def _default_converter(cls, value): """A default converter method that tries to deserialize objects.""" if isinstance(value, dict): return cls.from_jsonld(value) return value
12be1c65e413e2670e82a78dde096bb3a94f5078
552,935
def add_separator_argument(parser): """Add argument for setting table separator comma or tab """ parser.add_argument( '-s', '--sep', choices=['TAB', ','], default='TAB', help="Specify the field separator character in the library metadata file" ) return parser
ba90c3bfa746329d6f42ee4d5ba48eddfe1f9ac6
394,814
def get_log_extra_item(log, item): """Returns an extra item from the logging object.""" return log.extra.get(item, 'unknown')
6e60d685eb28c7a37984043e1bb28d546303aab7
285,275
import requests def gce_get_metadata(path): """Queries the GCE metadata server the specified value.""" return requests.get( 'http://metadata/computeMetadata/v1/{}'.format(path), headers={ 'Metadata-Flavor': 'Google' } ).text
4cc6952275e27ee1317f9b6a7c70fadf155235af
394,381
def luminance_newhall1943(V, **kwargs): """ Returns the *luminance* :math:`R_Y` of given *Munsell* value :math:`V` using *Sidney M. Newhall, Dorothy Nickerson, and Deane B. Judd (1943)* method. Parameters ---------- V : numeric *Munsell* value :math:`V`. \*\*kwargs : \*\*, optional Unused parameter provided for signature compatibility with other *luminance* computation objects. Returns ------- numeric *luminance* :math:`R_Y`. Notes ----- - Input *Munsell* value :math:`V` is in domain [0, 10]. - Output *luminance* :math:`R_Y` is in domain [0, 100]. References ---------- .. [1] **Sidney M. Newhall, Dorothy Nickerson, and Deane B. Judd**, *Final Report of the O.S.A. Subcommittee on the Spacing of the Munsell Colors*, *JOSA, Vol. 33, Issue 7, pp. 385-411 (1943)*, DOI: http://dx.doi.org/10.1364/JOSA.33.000385 Examples -------- >>> luminance_newhall1943(3.74629715382) # doctest: +ELLIPSIS 10.4089874... """ R_Y = 1.2219 * V - 0.23111 * (V * V) + 0.23951 * (V ** 3) - 0.021009 * ( V ** 4) + 0.0008404 * (V ** 5) return R_Y
3806a6957aaca700f3f3477eaa33746b37c33249
671,322
import typing from typing import TypeGuard import asyncio def is_async_iterator(obj: typing.Any) -> TypeGuard[typing.AsyncIterator[object]]: """Determine if the object is an async iterator or not.""" return asyncio.iscoroutinefunction(getattr(obj, "__anext__", None))
160d1dd2d5f1c9d6d2637e6006ae0ef268c7810f
32,050
import functools import time def profile(func): """Record the runtime of the decorated function""" @functools.wraps(func) def wrapper_timer(*args, **kwargs): start = time.perf_counter_ns() value = func(*args, **kwargs) stop = time.perf_counter_ns() print(f'{func.__name__} : {(stop - start)/1000_000_000} seconds') return value return wrapper_timer
d8b1d92c033a3033fd4171c5a3dda1087a7643f0
354,819
def ctof(temp_c): """Convert temperature from celsius to fahrenheit""" return temp_c * (9/5) + 32
4357cb6d355d14c11b21bfe0bd4efc5c1e3b4703
49,167
def human_readable_size(filesize=0): """ Converts number of bytes from *filesize* to human-readable format. e.g. 2048 is converted to "2 kB". # Parameters: filesize (int): The size of file in bytes. # Return: str: Human-readable size. """ for unit in ["", "k", "M", "G", "T", "P"]: if filesize < 1024: return "{} {}B".format( "{:.2f}".format(filesize).rstrip("0").rstrip("."), unit ) filesize = filesize / 1024 return "0 B"
37e54c9622394114c91059ed7c9236a8403c6a2f
144,217
def _create_database_sql(database_name): """Return a tuple of statements to create the database with the given name. :param database_name: Database name :type: str :rtype: tuple """ tmpl = "create database {} with owner = dcc_owner template = template0 " \ "encoding = 'UTF8' lc_collate = 'C' lc_ctype = 'C'" return tmpl.format(database_name),
48fc179d282750d162eb7544cf4b594d0e2f0729
645,176
import logging def logger() -> logging.Logger: """Initialize a default logger for tests.""" log = logging.getLogger("test-logger") log.setLevel(logging.CRITICAL) return log
5e9f16998ec674eac19d25fc3bc45e68b7f14670
528,792
def unhex(s): """unhex(s) -> str Hex-decodes a string. Example: >>> unhex("74657374") 'test' """ return s.decode('hex')
dcf2d6cd9c317b5eafd77e969272fcf753556403
694,014
def _column_number_to_letters(number): """ Converts given column number into a column letters. Right shifts the column index by 26 to find column letters in reverse order. These numbers are 1-based, and can be converted to ASCII ordinals by adding 64. Parameters ---------- number : int Column number to convert to column letters. Returns ------- unicode Column letters. References ---------- :cite:`OpenpyxlDevelopers2019` Examples -------- # Doctests skip for Python 2.x compatibility. >>> _column_number_to_letters(128) # doctest: +SKIP 'DX' """ assert 1 <= number <= 18278, ( 'Column number {0} must be in range [1, 18278]!'.format(number)) letters = [] while number > 0: number, remainder = divmod(number, 26) if remainder == 0: remainder = 26 number -= 1 letters.append(chr(remainder + 64)) return ''.join(reversed(letters))
c9a68bcd32c8f254af322bc61e447cfae61cb6d2
705,080
def wern_after_distillation(wA, wB): """Calculates the Werner parameter and success probabililty of distillation. Parameters ---------- wA : float Werner parameter of one of the two links. wB : float Werner parameter of the other link. Returns ------- Tuple (wern, prob) Tuple of the Werner paramter after successful distillation, and the probability that distillation is indeed successful. """ p_dist = (1 + wA * wB) / 2 w_dist = (1 + wA + wB + 5 * wA * wB) / (6 * p_dist) - 1/3 return w_dist, p_dist
5ec9a84f08e823160b1365fef1de8b1811d053c3
468,546
def matrix_dot(mat1, mat2): """Inner product for matrices Compute the inner product between matrices as: .. math:: \\mathrm{Trace}(M_1^T M_2) Parameters ---------- mat1: 2d array First matrix mat2: 2d matrix Second matrix Returns ------- dot: float The matrix inner product. """ return (mat1 * mat2).sum()
85581405b51c1c13efb57da80a22e88322a38cea
533,051
import socket def bindsocket(port, host=''): """ Creates a socket assigned to the IP address (host, port). Parameters ---------- port : int port assigned to the socket. host : str, optional host assigned to the socket. The default is ''. Returns ------- tcpsock : socket socket connected at (host, port). """ tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcpsock.bind((host, port)) return tcpsock
48be29952a3d35af0ec0886e3ca332f9280384f1
13,175
def get_folders_from_params(advanced_args): """ Extracts and returns the list of file hash IDs from the input `advanced_args`. `folders` is an expected property on `advanced_args`, if it does not exist, or it is empty, then an empty list is returned instead. """ try: if advanced_args['folders'] != '': return advanced_args['folders'].split(';') else: return [] except KeyError: return []
e74a57435c4e14c109f1c7905a65cb0315f7aa5f
196,211
def file_system_arn(arn): """ Converts an ARN to a file-system friendly string, so that it can be used for directory & file names """ for source, dest in {":": "#", "/": "_", " ": "_"}.items(): arn = arn.replace(source, dest) return arn
2c355a91e48a5ad87682e945d37f3b9c61311e46
44,528
def intensity( rgb ): """ Returns the average value of the rgb pixel data. Inputs: -- rgb: rgb pixel array in the form [b,g,r] Returns: average of the three values """ return int( (rgb[0] + rgb[1] + rgb[2])/3 )
31ee4138a9eca0d80e444bedd767c33e1911582f
443,262
def get_area_rect(length, width): """Returns area of rectangle >>> get_area_rect(5 , 5) 25 >>> get_area_rect(5 , 0) Traceback (most recent call last): ... ValueError >>> get_area_rect(5 , -1) Traceback (most recent call last): ... ValueError """ if(length <= 0) or (width <= 0): raise ValueError return length * width
6df6d1f075c4ff832800f88c0549555a29f65965
463,118
def reduceTuple(input_list): """ Idea taken from https://www.geeksforgeeks.org/python-group-tuples-in-list-with-same-first-value/ """ out = {} for elem in input_list: try: out[elem[0]].extend(elem[1:]) except KeyError: out[elem[0]] = list(elem) return [tuple(values) for values in out.values()]
099bee5a58ad70aa03123b28113c3c9d2170263a
552,808
def team_created_payload(team_default_payload): """Provide a team payload for creating a team.""" created_payload = team_default_payload created_payload["action"] = "created" return created_payload
105de6e28e2ff66f13289a5d67b406f3397f4fcf
335,483
from typing import Union def hex_colour(colour: Union[str, int]) -> str: """ Converts the given representation of a colour to its RGB hex string. As we are using a Discord dark theme analogue, black colours are returned as white instead. """ if isinstance(colour, str): colour = colour if colour.startswith("#") else f"#{colour}" else: colour = f"#{colour:0>6X}" return colour if colour != "#000000" else "#FFFFFF"
07512010c2b4a44ead8761b89ee648de7286dcf9
419,178
import torch def reserve_nn_scores(similarities, nn_num): """Reserver top-k nearest neighbors' similarity scores Args: similarities (Matrix): test_num * train_num Returns: nn_scores (Matrix): only keep the scores of the top-k nearest neighbors """ scores = torch.FloatTensor(similarities) # sorted each row, and get the index # ascending order sorted_scores, sorted_index = torch.sort(scores, 1, descending=True) nn_scores = sorted_scores[:, 0:nn_num] nn_index = sorted_index[:, 0:nn_num] # only accept float32 nn_scores = torch.zeros(scores.size()).scatter_(1, nn_index, nn_scores) # convert float32 to float64 return nn_scores.numpy().astype(float)
b3da2563c0ac56c9428167f7f6bb992556d826ce
60,195
def oneVoxelNoise(data, loc, scale=1.1): """applies 1-voxel scaling to the provided image matrix The noise introduced is equivalent to a point magnification at the location provided with scaled intensity equal to the value provided (default value is an increase in intensity by 10%). The location provided must be the same length or 1 fewer than the dimensions of the data. When the location provided contains fewer dimensions than the data matrix, the location is used to index the first dimensions, and noise is applied across the entire last dimension. Parameters ---------- data : ndarray Image to be perturbed with D dimensions. loc : list, tuple List of coordinate locations for applying noise. Must be length D or D-1 scale : float Multiplier for the signal at the target location. Default is 1.1 Returns ------- data : ndarray The perturbed data matrix with signal amplification by scale at location loc. """ loc = tuple(loc) # Lists cannot be used to index arrays, but tuples can if len(loc) < len(data.shape): # If fewer dimensions for location than data data[loc, :] = data[loc, :] * (scale) # Apply noise else: data[loc] = data[loc] * (scale) # Apply noise return data
eadf4383f5db6c7eb760f0acd6e487f5bb2fce5c
91,475
def _bytes_bytearray_to_str(s): """If s is bytes or bytearray, convert to a unicode string (PRIVATE).""" if isinstance(s, (bytes, bytearray)): return s.decode() return s
675c9658b3512dbb9facbf865fe416a27c6dfd07
261,013
def unquote(s): """Strip single quotes from the string. :param s: string to remove quotes from :return: string with quotes removed """ return s.strip("'")
15d29698e6a3db53243fc4d1f277184958092bc6
7,561
def get_daily_thread(subreddit): """return submission containing 'daily' in the title""" for submission in subreddit.hot(limit=5): if "daily" in submission.title.lower(): return submission
6935290237f1d6e414182c5592beecb455a410b2
342,208
def parse_host(host): """ Parse *host* in format ``"[hostname:]port"`` and return :class:`tuple` ``(address, port)``. >>> parse_host('localhost:4444') ('localhost', 4444) >>> parse_host(':4444') ('', 4444) >>> parse_host('4444') ('', 4444) >>> parse_host('2001:db8::1428:57ab:4444') ('2001:db8::1428:57ab', 4444) >>> parse_host('localhost') ValueError: Invalid port number 'localhost' """ parts = host.split(':') address = ':'.join(parts[:-1]) try: port = int(parts[-1]) except ValueError: port = None if not port or port < 1 or port > 65535: raise ValueError("Invalid port number '%s'" % port) return address, port
7afa0ae098ba8161cc561ea9c75b057f93878806
342,925
import math def radial_collide(item1, item2): """ item1 and item2 are 3-tuples in the format of (x, y, radius) for each object to test """ x_diff = item1[0] - item2[0] y_diff = item1[1] - item2[1] hit_radius = item1[2] + item2[2] return math.hypot(x_diff, y_diff) < hit_radius
0e58976d9eae2565a8af46159b33d8538682e400
154,755
def boolean_color(mask, true_color='black', false_color='white', name="face_color"): """Return a Series with colors replacing True and False.""" _mask = mask.copy() result = _mask.apply(lambda x: true_color if x == True else false_color) result.name = name return result
58c9b08e14d74cb244a42a39aa7513b26a706a66
317,205
def _compute_subprefix(attr): """ Get the part before the first '_' or the end of attr including the potential '_' """ return "".join((attr.split("_")[0], "_" if len(attr.split("_")) > 1 else ""))
9f91987a780d1d3c5d78745fd661608d22f247cf
247,502
import unicodedata def phonenumber_from_raw_contact(raw_phone_string): """Parses a phone number from a raw contact string, which could include unicode whitespaces. e.g. "&nbsp;&nbsp;&nbsp; /&nbsp;&nbsp; 555-555-1959" Arguments: raw_phone_string {str} -- Raw unicode string that includes a phone number. e.g. "&nbsp;&nbsp;&nbsp; /&nbsp;&nbsp; 555-555-1959" Returns: [str] -- Phone number as a string. """ phonenumber = unicodedata.normalize("NFKC", raw_phone_string).strip() # Some phone numbers are prefixed with "(cell)", get rid of that phonenumber = phonenumber.strip("(cell)") \ .strip(" – ") return phonenumber
6ec7a67178f85062d001f4907b404331906d700a
424,846
import re def only_numbers(string): """Return a string w only the numbers from the given string""" return re.sub("\D", "", string)
99bf3aeae8a462c5f6b2f217445d8d2fc616984e
646,158
import torch def rgb2yuv(rgb, device): """ Convert RGB image into YUV https://en.wikipedia.org/wiki/YUV """ rgb = ((rgb + 1) / 2) * 255.0 rgb_ = rgb.transpose(1, 3) # input is 3*n*n default A = torch.tensor([[0.299, -0.14714119, 0.61497538], [0.587, -0.28886916, -0.51496512], [0.114, 0.43601035, -0.10001026]]).to(device) # from Wikipedia yuv = torch.tensordot(rgb_, A, 1).transpose(1, 3) yuv = yuv / 255.0 return yuv
689990a31bc6d02348c6427c1478e09d26da7f1d
99,111
import math def lon2x(a): """ Converts longitudinal co-ordinate to its web mercator equivalent""" radius = 6378137.0 # in meters on the equator return math.radians(a) * radius
923e8f92ec34c722b1bfb7355b0282d4019c2901
318,605
def join_plus(xs, check_non_empty=False): """ Concatenate strings with '+' to form legend label. Parameters ---------- xs : list List of strings check_non_empty : bool If True, assert that len(xs) > 0 Returns ------- str Concatenation of xs (e.g., "CPU + GPU") Examples -------- >>> join_plus(["CPU", "GPU"]) "CPU + GPU" """ if check_non_empty: assert len(xs) != 0 return ' + '.join(sorted(xs)) # PROBLEM: this messes up the DQN plot for some reason... # return " +\n".join(sorted(xs))
9fc9a086f24bc95c6b3a921810c4e1a8ec1f2bba
187,351
def unique_paths_with_obstacles(obstacle_grid: list[list[int]]) -> int: """ >>> print(unique_paths_with_obstacles([[0,0,0],[0,1,0],[0,0,0]])) 2 >>> print(unique_paths_with_obstacles([[0,1],[0,0]])) 1 >>> print(unique_paths_with_obstacles([[0,1,0],[0,0,0],[0,0,1]])) 0 """ # If the obstacle grid is not given as input if not obstacle_grid: return 0 # If the starting tile is blocked there is no way to enter the grid if obstacle_grid[0][0] == 1: return 0 rows = len(obstacle_grid) cols = len(obstacle_grid[0]) # Creating a 2D list to memorise unique paths to a tile unique_paths = [[0 for col in range(cols)] for row in range(rows)] # There is only one way to reach the starting the tile unique_paths[0][0] = 1 # Finding no of ways to reach all the tiles in top row for col in range(1, cols): if obstacle_grid[0][col] == 1: unique_paths[0][col] = 0 else: unique_paths[0][col] = unique_paths[0][col - 1] # Finding no of ways to reach all the tiles in left most column for row in range(1, rows): if obstacle_grid[row][0] == 1: unique_paths[row][0] = 0 else: unique_paths[row][0] = unique_paths[row - 1][0] # Calculating no of unique paths for rest of the tiles for row in range(1, rows): for col in range(1, cols): if obstacle_grid[row][col] == 1: unique_paths[row][col] = 0 else: unique_paths[row][col] = ( unique_paths[row - 1][col] + unique_paths[row][col - 1] ) return unique_paths[-1][-1]
de854da00b5c7e8608dbc7f8a4d352fc61956f28
687,536
def id2num(s): """ spreadsheet column name to number http://stackoverflow.com/questions/7261936 :param s: str -- spreadsheet column alpha ID (i.e. A, B, ... AA, AB,...) :returns: int -- spreadsheet column number (zero-based index) >>> id2num('A') 0 >>> id2num('B') 1 >>> id2num('XFD') 16383 >>> """ n = 0 for ch in s.upper(): n = n * 26 + (ord(ch) - 65) + 1 return n - 1
a1966821557324a0e95568bf0f63207d8cd3f350
16,886
import math def length(k): """Finds length of k in bits Arguments: k {int} -- Integer number """ return int(math.log2(k) + 1)
801863f985d48881a687e339fe96b3725a59f3f6
530,582
import requests import json def create_network(platform, key, cli_id, desired_name, desired_type): """ Sends a post request containing the information required to create that new network. :param platform: URL for RiskSense Platform to be posted to :type platform: str :param key: API Key :type key: str :param cli_id: Client ID associated with the network to be created. :type cli_id: int :param desired_name: Desired name for the new network. :type desired_name: str :param desired_type: Type for the new network. "IP" or "HOSTNAME" :type desired_type: str :return: New network's attributes. :rtype: dict """ # Assemble the URL for the API call url = platform + "/api/v1/client/" + str(cli_id) + "/network/" # Define the header for the API call header = { "x-api-key": key, "content-type": "application/json", "Cache-Control": "no-cache" } # Define the body for the API call. This is where we define the name and # type of the network to be created. body = { "name": desired_name, "type": desired_type } # Send API request to the platform raw_response = requests.post(url, headers=header, data=json.dumps(body)) # If platform reports Success if raw_response and raw_response.status_code == 201: json_response = json.loads(raw_response.text) # If request is unsuccessful... else: print(f"There was an error creating the network.") print(f"Response Status Code: {raw_response.status_code}") print(f"Response Text: {raw_response.text}") exit(1) return json_response
c97adaf150cc798a7b8771c0b96338a9d611967b
540,635
def _get_reaction_key(functional_groups): """ Return a key for :data:`._reactions` Parameters ---------- functional_groups : :class:`iterable` An :class:`iterable` of :class:`.GenericFunctionalGroup`. The correct reaction must be selected for these functional groups. Returns ------- :class:`.frozenset` A key for :data:`_reactions`, which maps to the correct reaction. """ return frozenset( functional_group.get_num_bonders() for functional_group in functional_groups )
0dd855b6067830554332b5653410ed9940c0cd72
258,824
def delta(n_1, n_2) -> int: """Kronicka-delta function, yields 1 if indexing is the same, else zero.""" if n_1 == n_2: return 1 else: return 0
7ef01ef20ba0aff7f360eddb6d64873556116788
620,479
def second_smallest(numbers): """Find second smallest element of numbers.""" m1, m2 = float('inf'), float('inf') for x in numbers: if x <= m1: m1, m2 = x, m1 elif x < m2: m2 = x return m2
0ca7b297da68651e4a8b56377e08f09d4d82cfb7
706,279
from typing import Set def slate_teams(slate: dict) -> Set[str]: """Gets teams on given slate Args: slate (dict): the slate document Returns: Set[str] """ return set([sp['team'] for sp in slate['slatePlayers']])
96efae352a7094a1c0e7d339386b53adfe135ca4
110,453
def compute_M1_nl(formula, abundance): """Compute intensity of the second isotopologue M1. Handle element X with specific abundance. Parameters ---------- formula : pyteomics.mass.Composition Chemical formula, as a dict of the number of atoms for each element: {element_name: number_of_atoms, ...}. abundance : dict Dictionary of abundances of isotopes: {"element_name[isotope_number]": relative abundance, ..}. Returns ------- float Value of M1. Notes ----- X represents C with default isotopic abundance. """ M1_intensity = ( (formula["C"] * abundance["C[12]"]**(formula["C"]-1) * abundance["C[13]"] * abundance["X[12]"]**formula["X"] * abundance["H[1]"]**formula["H"] * abundance["N[14]"]**formula["N"] * abundance["O[16]"]**formula["O"] * abundance["S[32]"]**formula["S"]) + (formula["X"] * abundance["C[12]"]**formula["C"] * abundance["X[12]"]**(formula["X"]-1) * abundance["X[13]"] * abundance["H[1]"]**formula["H"] * abundance["N[14]"]**formula["N"] * abundance["O[16]"]**formula["O"] * abundance["S[32]"]**formula["S"]) + (formula["H"] * abundance["C[12]"]**formula["C"] * abundance["X[12]"]**formula["X"] * abundance["H[1]"]**(formula["H"]-1) * abundance["H[2]"] * abundance["N[14]"]**formula["N"] * abundance["O[16]"]**formula["O"] * abundance["S[32]"]**formula["S"]) + (formula["N"] * abundance["C[12]"]**formula["C"] * abundance["X[12]"]**formula["X"] * abundance["H[1]"]**formula["H"] * abundance["N[14]"]**(formula["N"]-1) * abundance["N[15]"] * abundance["O[16]"]**formula["O"] * abundance["S[32]"]**formula["S"]) + (formula["O"] * abundance["C[12]"]**formula["C"] * abundance["X[12]"]**formula["X"] * abundance["H[1]"]**formula["H"] * abundance["N[14]"]**formula["N"] * abundance["O[16]"]**(formula["O"]-1) * abundance["O[17]"] * abundance["S[32]"]**formula["S"]) + (formula["S"] * abundance["C[12]"]**formula["C"] * abundance["X[12]"]**formula["X"] * abundance["H[1]"]**formula["H"] * abundance["N[14]"]**formula["N"] * abundance["O[16]"]**formula["O"] * abundance["S[32]"]**(formula["S"]-1) * abundance["S[33]"]) ) return M1_intensity
8c1ec0f2bcdf5c097a500d57ab20ef03a6443a89
232,023
def vorf_str_to_set(vorf): """ Convert a Vorf string into a Python set with the Vorf values in it, appropriately quoted. """ bits = [x.strip() for x in vorf.split(',')] bits_str = ["'{}'".format(x) for x in bits] return "{%s}" % ', '.join(bits_str)
c3406422d0f214cd2298651e7cd324aeb8f4bb43
563,665
def describe_result(result): """ Describe the result from "import-results" """ status = result['status'] suite_name = result['suite-name'] return '%s %s' % (status, suite_name)
1c7daa6df6bc5ce2267dc602002da4ab741f407f
310,761
def getOrCreateNew(couchServer, dbName): """ Get a couch Database object given dbName. If dbName is not existed, create a new database. """ try: db = couchServer[dbName] except: # couchdb.http.ResourceNotFound db = couchServer.create(dbName) return db
54741eb436761dd1caccb320a6059584f31a5ad1
387,875
def get_primary_key_column_names(model): """ Returns the constituent column names for the primary key of the given model. Args: model (class or object): The given model class or model instance. Return: list: Primary key column names as a list of strings. """ return [column.name for column in model.__table__.primary_key.columns]
369bf25022458b9f861f0e1af695e2ce05dede1e
314,843
def unmap_address(library, session): """Unmap memory space previously mapped by map_address(). Corresponds to viUnmapAddress function of the VISA library. Parameters ---------- library : ctypes.WinDLL or ctypes.CDLL ctypes wrapped library. session : VISASession Unique logical identifier to a session. Returns ------- constants.StatusCode Return value of the library call. """ return library.viUnmapAddress(session)
6420df343a3704f9747a91289f3ebeb69866a310
469,238
import re def clean(s): """ Cleans given string from non-relevant information: links, punctuation, etc. :param s: raw string :return: cleaned string """ s = re.sub(r"https\S+", " ", s) s = re.sub(r"^\s+|\n|\r|\t|\s+$", " ", s) s = re.sub(r"[^\w\s\d]", " ", s) s = re.sub(r"\s{2,}", " ", s) return s.lower().strip()
4d5d0ab6119456d131e2cba58dfed77dc9c9bdaa
486,079
def count_distinct(collection, key, exclude=None): """Get the number of distinct values for key in the specified database collection""" values = collection.distinct(key) if exclude is not None and exclude in values: values.remove(exclude) return len(values)
894428df0a3d913963c33ce2940c01305a5b700e
625,073
def make_simple_preprocessor(obj): """Factory that makes a function that accepts (step, context) and returns the given obj as *args and no kwargs. :param obj: Any object. :return: A function that accepts (step, context) paramteres and returns a tuple (*args, **kwargs) in the following form: ( (obj,), {} ) """ return lambda step, context: ((obj,), {})
3b7ff8b9a92102480e2b0fb12b251863ec19d7ec
390,289
def left_part_of(txt, sub_txt, n=1): """ Return the left part before the nth of sub_txt appeared in txt. :param txt: text :param sub_txt: separate text :param n: the nth of sub_txt(default:1) """ parts = txt.split(sub_txt) return sub_txt.join(parts[:n])
af99d668038d62581792612ec189d15104b31cbf
620,309
def is_second_run(command): """It's second run of `fudge`?""" return command.script.startswith('fudge')
d89335c3390bef8dc9b295f6e982bb7295cd80c8
362,029
import random import string def random_string(size=60): """Generates a random alphanumeric string for a given size""" return ''.join(random.choice(string.ascii_letters + string.digits) for i in range(size))
0deae6d46bd09808df105e63a0e30323167fcc1f
239,744
from typing import Dict from typing import List def _continuous_columns(feature_types: Dict) -> List[str]: """ Parameters ---------- feature_types : Dict Column name mapping to list of feature types ordered by most to least relevant. Returns ------- List[str] List of columns that have continuous or ordinal in the feature type list. Note ____ if a column has both ordinal/continuous and categorical pick whichever comes first. """ continuous_cols = [] for col in feature_types: for feature_type in feature_types[col]: if feature_type == "continuous" or feature_type == "ordinal": continuous_cols.append(col) break if feature_type == "category": break return continuous_cols
d21b02f949a5c658defeaaa67a0abec916373f0d
689,242
def is_targeting_windows(pkg_vars): """Returns true if 'platform' in pkg_vars indicates Windows.""" return pkg_vars['platform'].startswith('windows-')
83ee031170327348c57b50c86739c876e9f9f8f4
617,551
import torch def check_GPU_availability(cuda_n=0): """ Checks if GPU is available :return: avilable device name """ if torch.cuda.is_available(): # Check we're using GPU torch.backends.cudnn.deterministic = True device = 'cuda:%s' %(cuda_n) else: device = 'cpu' return device
0b8edaa5dce24c1cfeba58e96e6923a883b24b84
238,645
def recursive_array_addition(l:list): """Sum an array of integers using recursion.""" if len(l) == 0: return 0 else: i = l.pop() return i + recursive_array_addition(l)
05b88afc8a2deadb9fafb4170aecc31128743cc3
584,139
def _process_imp(imp_df, imp_name): """ Preprocessing on the input feature importance dataframe :param imp_df: feature importance pandas dataframe :param imp_name: column name of the importance value :return: dataframe with relative_imp and feat_rank """ imp_df = imp_df.sort_values( by=imp_name, ascending=False).reset_index( drop=True) imp_df['relative_imp'] = imp_df[imp_name] * 1.0 / imp_df[imp_name].max() imp_df['relative_imp'] = imp_df['relative_imp'].apply( lambda x: round(x, 3)) imp_df['feat_rank'] = imp_df.index.values + 1 return imp_df
81a0253bee9c1aed746bf374ddf771ed691101a2
450,346
def _unary_apply(op, value): """ Constructs a Weld string to apply a unary function to a scalar. Examples -------- >>> _unary_apply("sqrt", "e") 'sqrt(e)' """ return "{op}({value})".format(op=op, value=value)
b5c69fc278e5b0453140e23ff21c1d1c8860ee2e
131,679
def calc_max_min_marks(marks): """ Function which returns the minimum(excluding 0) and maximum score of the class in the form of a list. """ result = [] marks.sort() min_max = [] min_max[:] = (value for value in marks if value != 0) least_score = min_max[0] highest_score = min_max[-1] result.append(least_score) result.append(highest_score) return result
92c6581ea2d967772cda043adee5c5d5ce893335
53,528
def elementwise_residual(true_val, pred_val): """The residual between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- residual : float The residual, true minus predicted """ return true_val - pred_val
e1eb2434b1d24032f3b7abc1233c165d7146ffff
71,487
import re def _SanitizeRepositoryName(name): """Sanitizes the given name to make it valid as an image repository. As explained in https://docs.docker.com/engine/reference/commandline/tag/#extended-description, Valid name may contain only lowercase letters, digits and separators. A separator is defined as a period, one or two underscores, or one or more dashes. A name component may not start or end with a separator. This method will replace the illegal characters in the given name and strip starting and ending separator characters. Args: name: str, the name to sanitize. Returns: A sanitized name. """ return re.sub("[._][._]+|[^a-z0-9._-]+", ".", name.lower()).strip("._-")
d6785746a85143a9aff97acbacf76347501c0f9d
169,052
def _CreateActionsText(text, igm_field, action_types): """Creates text presented at each wait operation for given IGM field. Args: text: the text associated with the field. igm_field: reference to a field in the Instance Group Manager. action_types: array with field values to be counted. Returns: A message with given field and action types count for IGM. """ actions = [] for action in action_types: action_count = getattr(igm_field, action, 0) if action_count > 0: actions.append('{0}: {1}'.format(action, action_count)) return text + ', '.join(actions) if actions else ''
2eb42dd58efccbc18dc827bb6582204eb7808144
609,513
def pick_latest_version(versions): """Returns the higher version available in the given list of versions. versions: Array of strings with the availalbe versions. """ def from_string(version): return tuple(int(part) for part in version.split('.')) def to_string(version): return '.'.join(str(part) for part in version) int_versions = [from_string(version) for version in versions] latest = max(int_versions) return to_string(latest)
550baba8d9d33dcff91f1572b046edfcb48deed5
245,006
import yaml def write_watchlist(watchlist): """ Writes the current watchlist to yaml file """ with open('data.yaml', 'w') as file: return yaml.dump(watchlist, file)
29e4bf0150220bf22a937666f1a4839b9997cda9
211,669
def calc_accu(a, b): """ Returns the accuracy (in %) between arrays <a> and <b>. The two arrays must be column/row vectors. """ a = a.flatten() b = b.flatten() accu = 100.0 * (a == b).sum() / len(a) return accu
3f91e0805b3fc950da0ae02b34c8c0fb383e78c6
668,067
def fix_bases_mask(bases_mask,barcode_sequence): """Adjust input bases mask to match actual barcode sequence lengths Updates the bases mask string extracted from RunInfo.xml so that the index read masks correspond to the index barcode sequence lengths given e.g. in the SampleSheet.csv file. For example: if the bases mask is 'y101,I7,y101' (i.e. assigning 7 cycles to the index read) but the barcode sequence is 'CGATGT' (i.e. only 6 bases) then the adjusted bases mask should be 'y101,I6n,y101'. Arguments: bases_mask: bases mask string e.g. 'y101,I7,y101','y250,I8,I8,y250' barcode_sequence: index barcode sequence e.g. 'CGATGT' (single index), 'TAAGGCGA-TAGATCGC' (dual index) Returns: Updated bases mask string. """ # Split barcode sequence string into components indexes = barcode_sequence.split('-') # Check input reads reads = [] i = 0 for read in bases_mask.split(','): new_read = read if read.startswith('I'): input_index_length = int(read[1:]) try: actual_index_length = len(indexes[i]) except IndexError: # No barcode for this read actual_index_length = 0 if actual_index_length > 0: new_read = "I%d" % actual_index_length else: new_read = "" if input_index_length > actual_index_length: # Actual index sequence is shorter so adjust # bases mask and pad with 'n's new_read = new_read + \ 'n'*(input_index_length-actual_index_length) i += 1 reads.append(new_read) # Assemble and return updated index tags return ','.join(reads)
ef3d7dd18ae338b6e4f92412085a2eb56c3e5514
486,999
def anagram(word_1: str, word_2: str) -> bool: """Anagram check example :param word_1: {str} :param word_2: {str} :return: {bool} """ word_1 = word_1.lower() word_2 = word_2.lower() return sorted(word_1) == sorted(word_2)
6e99ebb0659fb4f81414f2dd552f854d52d61a0d
669,562
import requests def _download_index(category, index_url): """ Download the index. :param category: suffixed category, e.g. 'filters', 'templates' :param index_url: url to the index. Default: 'https://raw.githubusercontent.com/pandoc-extras/packages/master/<category>.yaml' :return: the content of the index, which is in YAML """ if index_url is None: index_url = 'https://raw.githubusercontent.com/pandoc-extras/packages/master/{}.yaml' url = index_url.format(category) r = requests.get(url) if r.status_code != 200: raise IOError("Cannot download index, error {}".format(r.status_code)) return r.text
190a4b39f962cae43d281fa91d1614cbebaa681a
50,209
def temba_compare_contacts(first, second): """ Compares two Temba contacts to determine if there are differences. These two contacts are presumably referencing the same contact, but we need to see if there are any differences between them. Returns name of first difference found, one of 'name' or 'urns' or 'groups' or 'fields', or None if no differences were spotted. """ if first.uuid != second.uuid: # pragma: no cover raise ValueError("Can't compare contacts with different UUIDs") if first.name != second.name: return 'name' if sorted(first.urns) != sorted(second.urns): return 'urns' if sorted(first.groups) != sorted(second.groups): return 'groups' if first.fields != second.fields: return 'fields' return None
929460f61103ffda542f2e09c3d7dc0ff1e0d83a
451,787
def get_application_instance_name(application): """ Return the name of the application instance. """ return "{}-{}".format(application.image.project.name, application.name)
e877677b831740f7bd156dc840593e69e185e411
649,778
import string def first_int(s): """Return the first integer in a string, or None""" # This technique appears to be faster than the re-based method # by almost an order of magnitude. Prefer it ret = '' for c in s: if c in string.digits: ret += c else: break if len(ret) > 0: return int(ret) else: return None
63499dfd382836571690dc34c80d7a9b319ecb49
594,193
def hashable(x): """Check if an object is hashable. Hashable objects will usually be immutable though this is not guaranteed. Parameters ---------- x: object The item to check for hashability. Returns ------- bool: True if `x` is hashable (suggesting immutability), False otherwise. """ try: _ = hash(x) return True except TypeError: return False
81abc4ba519cf39c8447c17716bd723b81475b57
374,532
from io import StringIO import csv def data_to_string(data): """Write a list of dicts as a CSV string Args: data (list): A list of dicts, one per CSV row Returns: str: The stringified csv data, with a header row """ with StringIO() as fout: fieldnames = data[0].keys() writer = csv.DictWriter(fout, fieldnames=fieldnames) writer.writeheader() writer.writerows(data) return fout.getvalue()
416e285379244fd01463270899560fe3b11c9277
320,286