content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def find_error_line(view, after): """Returns the first error after the given point.""" error_linenumbers = view.find_by_selector("constant.numeric.linenumber.error") if not error_linenumbers: return None for region in error_linenumbers: if region.begin() > after: return region # Go back to the ...
94ba3966c0355e4ca3cdb0d4636a70e4c0764d6c
596,018
def list_to_indices(index_string): """ Return an integer list from a string representing indices. e.g. index_string = '1-3, 5-6, 8-13, 15, 20' indices = [1, 2, 3, 5, 6, 8, 9, 10, 11, 12, 13, 15, 20] Args: index_string (string): condensed string representation of integer list. Retu...
b22fe70fb60a12685aa127cddb8718744a593bd9
596,024
def exponential_power_calculation(base, exponent=1.0): """ Calculation of exponential power of number i.e. base^exponent. Parameters ---------- base : float Base number. exponent : float, optional Exponent of the base. The default is 1.0. Returns ------- value : flo...
c4c6f22683ee90b0d905d112266d65c054fe8d5a
596,040
def write_input(program: list, noun: int = 12, verb: int = 2) -> list: """Write to the second and third positions of a program :param program: Intcode program to write to :param noun: int to write to the first position :param verb: int to write to the second position :return: Modified Intcode progr...
eba70ee97f6d27f5019affa16a91953ef04a5f78
596,050
def skeaf_code(aiida_local_code_factory): """Get a skeaf code.""" return aiida_local_code_factory(executable="diff", entry_point="skeaf")
7aa3b904796ad6f38e1abfda96959269732c3f93
596,051
def find_stages(document): """ Find **stages** in document. Args: document (dict): validated spline document loaded from a yaml file. Returns: list: stages as a part of the spline document or an empty list if not given. >>> find_stages({'pipeline': [{'stage(Prepare)':1}, {'stage(...
d4e6b2a483729a5b028651040b75e74e390b8835
596,057
import socket def get_open_port() -> int: """ Gets a PORT that will (probably) be available on the machine. It is possible that in-between the time in which the open PORT of found and when it is used, another process may bind to it instead. :return: the (probably) available PORT """ free_s...
bc4d90cf63a0c5d72b6fed3235c451514caed06d
596,060
def get_five_percent_duration(video_source) -> float: """ Returns a duration corresponding to five percent of the video source's duration """ return video_source.segment.duration * 0.05
fdeaa80994f8898a92d75d1cea2a8bb982fe4ca7
596,064
def play_and_train_with_replay(env, agent, replay=None, t_max=10**4, replay_batch_size=32): """ This function should - run a full game, actions given by agent.get_action(s) - train agent using agent.update(...) whenever possible - return total reward :param replay...
159057f670f3afb8c14b473bc883a3785a7a3125
596,071
def normalize(minimum: float, maximum: float, value: float) -> float: """ Takes a minimum, maximum, and input value and converts the input value to a normalized value on a scale from 0 to 1. :param minimum: the minimum value from the set of values containing the input value :param maximum: the maxim...
5dd35d1790d1d72940538b81410a92c0b3acd8c2
596,073
import requests def curl(url, data=None, method='get'): """Download one file from a web URL. The request is stateless, just like what the cURL tool would do. Args: url (str): URL to request data (dict): data to pass on into the request, such as the post body method (str): one of t...
25a65ce557233709a2454110cf1100e7a67ff583
596,074
def is_polarization_problem(output_path): """ Check the presence of polarization errors. """ thefile = open(output_path) lines = thefile.read().split('\n') for line in lines: if "POLARIZATION: Iteration to find the polarization" in line: return True return False
2a8980d59dc65c3ab73c04174b881ff88fc5cf00
596,078
def read_n_return(filename): """Reads and returns the content of a file.""" with open(filename,"r") as file: all_content = file.read() return all_content
a4e1a8029501c9f42fe2df16317097232f8ce014
596,080
from typing import Mapping from typing import List from typing import Dict def episode_metadata(mask: Mapping[str, List[str]], episode_key: str) -> Dict[str, bool]: """Builds the metadata of an episode. Args: mask: A dict that maps flags to the list of episodes for which this flag ...
cdbf5d8f2a25d0381f4fe4d139ba5f3750beae56
596,081
def dummy_application(create_application): """Return a dummy application.""" return create_application(name='dummy')
934978f6c75964c3e8bc7e125b949c770eaa6820
596,082
import re def _tokenizeGlm(inputStr, filePath=True): """ Turn a GLM file/string into a linked list of tokens. E.g. turn a string like this: clock {clockey valley;}; object house {name myhouse; object ZIPload {inductance bigind; power newpower;}; size 234sqft;}; Into a Python list like this: ...
14fb31a9f68b36fac2d1ad87baf84326c247efe0
596,084
def distance_2(pos_1, pos_2): """ This functions gives the square distance between two positions. :param pos_1: First position. :type pos_1: Position :param pos_2: Second position. :type pos_2: Position :return: Square distance :rtype: float """ return (pos_2.x - pos_1.x)**2 + (p...
ab83814611fb98c08dba4edda2ffdf7b6f957890
596,086
def getLegendTexts(ax): """ Return all texts for items in legend. An empty list signifies no legend or no labeled objects. """ lgd = ax.get_legend() if lgd is None: return [] return [item.get_text() for item in lgd.get_texts()]
ec50f2269e6cbae5497bb7c208eb94cea8af577a
596,087
def block(CLIENT) -> dict: """Returns most recent block. """ return CLIENT.get_block()
89b826f2c08780b80b09f734e3c76f1ff30a0a30
596,089
import re def match_email(text): """Given a string, tries to find a regex match for an email.""" email_regex = r'(.+\s+)*(<)*\s*(?P<email>\w+(?:.+\w+)*@\w+(?:.+\w+)' + \ r'(?:\.\w+)+)(>)*' match = re.match(email_regex, text) if match: return match.group('email')
0e888af8366062f1af789b12b5e3792ba492fd92
596,096
def path_duration(path): """ Computes the timespan of a given path. Parameters ---------- path : a path list of interactions forming a path among a node pair Returns -------- duration: int The duration of the path Examples ...
e7b298b0c4624aca264813ebaf4ce53d4690fef0
596,097
def trim_beats(beats, min_beat_time=5.): """Removes beats before min_beat_time. A common preprocessing step. Parameters ---------- beats : np.ndarray Array of beat times in seconds. min_beat_time : float Minimum beat time to allow (Default value = 5.) Returns -----...
a2c54620a294cee47a3c19ebd8221699be8ca861
596,098
def format_hex_width(value, width): """! @brief Formats the value as hex of the specified bit width. @param value Integer value to be formatted. @param width Bit width, must be one of 8, 16, 32, 64. @return String with (width / 8) hex digits. Does not have a "0x" prefix. """ if width == 8: ...
ea9491e5982099b302987dacff154c728a7f9973
596,106
from datetime import datetime def get_filename(ext='.out'): """ Return a file name which contains date-time string. """ return datetime.now().strftime("%Y%m%d-%H%M%S") + ext
c260f7e7072723eb97889d9ea969c36795a68c75
596,107
from typing import Dict from typing import Any async def index() -> Dict[str, Any]: """root path, returns some API paths Returns: Dict[str, Any]: Api routes """ return { "detail": "Welcome to FastAPI", "apis": ["/api/v1/users"], "fake_data": "/data", "docs": ["...
decde1cb6d99ea084007a4ae66d70856e85518d1
596,109
def get_reverse(sequence): """Reverse orientation of `sequence`. Returns a string with `sequence` in the reverse order. If `sequence` is empty, an empty string is returned. """ #force upppercase sequence=sequence.upper() #if an empty string, will evaluate to false and move to else statemen...
217a25e9246376bd276c46b50d6c2091d1371b69
596,110
import math def cubic_roots(a, b, c, d): """ Compute the roots of a cubic equation. Only real roots are returned. This works properly with lesser degree equations if the higher order coefficients are set to zero. Enter: a, b, c, d: coefficients of the cubic equation. These are of ...
c1ae1a8e4bcbe6471e418aa143bc6774852e1d40
596,117
import calendar def UtcToTimestamp(dt): """Converts a UTC datetime object to a scalar POSIX timestamp.""" return calendar.timegm(dt.utctimetuple()) + dt.microsecond / 1e6
29de514b76343157c4c15ee51fdb45711982c4cf
596,118
def file_to_dict(filename): """ Reads a file where each line is 'k,v' and returns a dictionary of k,v. """ dic = dict() with open(filename, 'r') as f: lines = f.readlines() for l in lines: l = l.strip('\n') li = l.split(',') dic[li[0]] = li[1] ...
3feff6507acf0934fa2bc777e53fcdc15ffe23c2
596,128
def avp_from_twet_tdry(twet, tdry, svp_twet, psy_const): """ Estimate actual vapour pressure (*ea*) from wet and dry bulb temperature. Based on equation 15 in Allen et al (1998). As the dewpoint temperature is the temperature to which air needs to be cooled to make it saturated, the actual vapour pr...
bf66e8015fbdc35ea23ba34f194257d98a14027e
596,131
from typing import Dict from typing import Union from typing import List def create_single_host_list(ip_and_range_lists: Dict[str, Union[str, List]]) -> List[str]: """ Creates a single list containing both single ips and ranges of ips Args: ip_and_range_lists: A dictionary that can have either a s...
903d7739e2ad6ead4a68910e4884162e02e7deff
596,132
def abs_target(target, default_module=None): """Determines the canonical representation of a target, while allowing syntactic sugar for the user. Params: target: e.g. "src=com/yext/subscriptions:app", src/com/yext/subscriptions:app" default_module: optional module that can be used to resolve a ...
2fc33bab78089fc3cd24bf65b0803ec457c71b4c
596,133
def point_msg_2_arr(pntMsg): """ Return an array representing 'geometry_msgs/Point' """ return [pntMsg.x, pntMsg.y, pntMsg.z]
d65d6920d292203e7449cf3884bc2503c5b5d320
596,134
def get_image_region(image, x1, y1, x2, y2): """ Return image subregion defined by (x1, y1) and (x2, y2) rectangle. """ return image[y1:y2, x1:x2]
241ced93d0c1ba5d6f6e25cbbe6e0f8db02a9dd8
596,141
def gold_labels(span_indices, spans, span_labels): """ Organizing gold labels and indices :param span_indices: :param spans: :param span_labels: :return: gold_indices: gold_labels: """ # gold span labels gold_indices, gold_labels = [], [] for batch_idx, indices in...
b227b1959c18b1cfb9592b56e02e27e59a9c2e5d
596,142
from typing import Type def get_description_from_payload(payload): """ Return description from a single row. We only return the name, type (inferred from the data) and if the values can be NULL. String columns in Druid are NULLable. Numeric columns are NOT NULL. """ return [ ( ...
50a2124b39fcc881e73408bb8d69a573805fa7f5
596,143
def convert_to_coordinate(raw_data:float, sec_delim:str, min_delim:str, deg_delim:str) -> str: """ Description: Converts converts float value to the geographical data (for example, 27°16'37.9") Arguments: - raw_data : `float` value as degree - sec_del...
df1a7bde98f879f3dd1091f4d70e471627485084
596,145
import math def is_coprime(num: int, larger_num: int) -> bool: """Determine if num is a coprime to larger_num.""" return math.gcd(num, larger_num) == 1
2a240dd87554bd67bc73ae63d981a32a8fe78abc
596,146
import torch def build_group_od_mask(origin_vs, grid_x_max, grid_y_max): """Creates mask with the OD dimensions (grid_num = grid_x_max * grid_y_max). Assigns 0 to the cells for which the origin square does not belong to the given group. Assigns 1 to the cels for which the origin square belongs to the give...
bf611d77958b34a3209f315c721d30bf83ceb44e
596,147
import re def path_signature(method): """Returns the most specific path signature derivable from method. Returns path with all braced variable names removed. The braces, and the "+" prefix for multi-segment variables, are left in place. If method contains "flatPath", that is used in place of "path"....
f16275a0b6fa096d347eaa51deb223cc268f55ef
596,149
import re def validate_slicing_string(slicing_string): """Validate a slicing string. Check if the input string contains only brackets, digits, commas and colons that are valid characters in numpy-style array slicing. Args: slicing_string: (str) Input slicing string to be validated. Returns: (bool...
ab006dc3f6cca7c48fbe2e872854e30cff297804
596,150
def sum_digits(n): """Sum the digits of N.""" L = [] for s in str(n): L.append(int(s)) return sum(L)
4815fc9da3b3b9c18858bcb643bb17f05e051359
596,153
def subset_catalog(intake_esm_catalog, search_dict): """ Subsets an intake-esm catalog given a search dictionary Parameters ---------- intake_esm_catalog: intake_esm.Catalog search_dict: dict, dictionary to use for searching the catalog Returns ------- catalog_subset: intake_esm.C...
3cff0b556cd0bf89d855a8009aab96de63baa754
596,154
import six def get_body_from_env(env): """Exctracts request body from wsgi environment variable""" content_length = env.get('CONTENT_LENGTH') body = '' if content_length: # detects None, 0 or '' values of CONTENT_LENGTH key length = int(content_length) body = env['wsgi.input'].read(l...
2539cc7d39b9659973f754a9fefdb6bcfc4a910f
596,155
def load_shefcodefirst_python_members(file_path): """Given the `file_path` to the file containing a list of #ShefCodeFirst Python course members, this function loads them into a list and return such list back.""" # Explicitly open file with the UTF-8 encoding to ensure non-standard English characters ...
a40f492935f6ccd74df3f8fabe43e650f08dbecc
596,157
def get_resource_timestamp(pefile_object): """ Retrieves timestamps from resource directory entries, if available. :param pefile.PE pefile_object: pefile object. :return: Recovered timestamp from PE resource table entry (if present) :rtype: int """ timestamp = 0 if hasattr(pefile_objec...
7e759f353476058d2dd2a0defd3b827fb862fec6
596,158
def _rrv_contains_ ( var , value ) : """check if the given value is in the range of RooRealVar >>> mass_range = ... >>> if v in mass_range : ... """ if var.hasMin() and value < var.getMin() : return False if var.hasMax() and value > var.getMax() : return False return True
283ef9df61f5c4ad8230b7eb77e11836e02734fd
596,160
def wbgt(twb, tg, tdb=None, with_solar_load=False, **kwargs): """ Calculates the Wet Bulb Globe Temperature (WBGT) index calculated in compliance with the ISO 7243 [11]_. The WBGT is a heat stress index that measures the thermal environment to which a person is exposed. In most situations, this index is...
a0ae327932bc8553472e3628c51e21e7df81a500
596,163
def progress(value, total, width, symbol='#', empty=' '): """Get a string representing the progress.""" frac = 1. * value / total pixels = round(frac * width) left_pixels = width - pixels return '[' + (symbol * pixels) + (empty * left_pixels) + ']'
98e19574055fa682c0e469819d3b8cf1abcda601
596,165
def _get_reason(cluster_or_step): """Get state change reason message.""" # StateChangeReason is {} before the first state change return cluster_or_step["Status"]["StateChangeReason"].get("Message", "")
bb18c94b2647bb0cc0234c218281d900b48119fe
596,167
def static_div(divisor): """ >>> class A: ... m = static_div(10) ... >>> a = A() >>> a.m(12345) 1234 """ def func(divident): return divident // divisor return staticmethod(func)
af73500608ef82aa1ff05e338fcf7338de201cc7
596,170
from datetime import datetime def parse_datetime(timestamp): """Parses a timestamp in the format 2006-01-02T15:04:05Z.""" # This way is about 31x faster than arrow.get() # and 6.5x faster than datetime.strptime() year = int(timestamp[0:4]) month = int(timestamp[5:7]) day = int(timestamp[8:10])...
a40c62a89a0678092c3e78ebe87dc679f50db33b
596,171
def update_fields(fields, row): """ This function updates the fields with the values in row. """ for key in fields: fields[key][0] = row[key][0] return fields
6e4d69b853b5081ef9028a973dc4217203fd853f
596,177
def get_default_attr(obj, attr, default_value=None): """ Get attribute by name. If does not exist, set it. >>> class Klass: pass >>> a = Klass() >>> hasattr(a, "answer") False >>> get_default_attr(a, "answer", 42) 42 >>> a.answer 42 """ if not hasattr(obj, attr): ...
63651aed81564d015dad65920a2de4c0d3c10fbf
596,183
from typing import List def sort_audio_by_number(audio_files: List[str]) -> List[str]: """ Sorts the audio files based on the files number :param audio_files: a list of every audio file :return: the audio files sorted on their audio number (ex: media1.sound, media2.sound) """ # since the file ...
9ceca859e645f67fdf6c38cfdecf0d92153e819e
596,184
def _PropSatisfies(spec, candidate): """Determines whether candidate property meets requirements given by spec.""" if spec.name != candidate.name or spec.mode != candidate.mode: return False return True if spec.direction is None else ( spec.direction == candidate.direction)
2afb58e3823f835cb898817668f2fafe484f64c1
596,185
def compute_form_forcescale(form): """Calculate an appropriate scale to the thickness of the forces in the form diagram. Parameters ---------- form: :class:`compas_ags.rhino.FormObject` Returns ------- scale: float Appropriate scale factor to thickness of form diagram lines. ""...
fab2489d191db0b7caece92c33e610a81cdcc576
596,187
import jinja2 def render_template(template, **kwargs): """Render a jinaj2 template.""" t = jinja2.Environment() t = t.from_string(template) return t.render(kwargs)
111d6b3e9dc1090c79cfe699f3878489c74397e3
596,189
def lsb(n): """Extract the least significant byte from n.""" return n & 255
4db74d54409e6d9f8572a2e7720a1e48e7e6a40f
596,195
def safe_encode(txt): """Return encoded text if it's not already str.""" try: return txt.encode() except AttributeError: return txt
b0b25eb5fa1e70a1a96cb4533ac53379463a37f0
596,203
def CRLF(text): """Convert Unix line endings to CRLF, which is required by the POST data mime-types application/x-www-form-urlencoded and multipart/form-data. Parameters ---------- text : :class:`str` Text to convert. Returns ------- :class:`str` Input text converted to...
18edf872b56081d676b0a21cde818ff26a1bb5fc
596,212
def ltattr(self, other, *fields, t=None): """Allows to avoid repeating implementation of __lt__, where fields of an object are simply compared in order Missing fields (None) arbitrarily are considered < all others Args: self: Object issuing the comparison other: Object 'self' is being compa...
9af76344623a5177d7c5cebfafbcd4ab4df73db8
596,216
import csv def get_data_from_file(csvfile): """return the data from a csvfile as a list, without header line arguments: csvfile -- the path of csvfile to load """ with open(csvfile) as cf: reader = csv.reader(cf, delimiter=',', quotechar='"') data = [row for row in reader][1:] ...
8047560fb07e7d4792c6c6b876d19ac12d858c89
596,221
def expand_string_interval(interval: str): """ Given a string interval, returns the unit of time and the number of units. For example, "3DAY" should return (3, "DAY") """ num = [c for c in interval if c.isdigit()] value = int("".join(num)) unit = interval[len(num) :] return value, unit
6f226608ec3316deb517154de5c5cce6d1038714
596,222
async def is_guild_owner(ctx): """ Checks if invoker is the owner of the guild. parameter: ctx [commands.Context]: discord Context object returns: boolean: True if invoker is owner of guild """ return ctx.author == ctx.guild.owner
902e49718ad29036d93fbeb4e1087f0ff90f5d58
596,230
from typing import Union from pathlib import Path def check_size(path: Union[str, Path], size: int): """Check if the size of a file matches the expected one. Parameters ---------- path : str or Path Path to the file. size : str Expected size of the file. """ return Path(p...
50d1480f60ffdb81992ff897304363b466cfb078
596,238
import itertools def get_backup_files(backup_info, selected_kinds=None): """Returns the backup filenames for selected kinds or all if None/Empty.""" if backup_info.blob_files: return backup_info.blob_files else: kinds_backup_files = backup_info.get_kind_backup_files(selected_kinds) return list(iter...
422b1b1a2118356aad0d52fb37e2c602b052a3ca
596,243
def _fill_col1_val_where_col2_notna(col1, col2, val): """Set col1 to val where col2 is not NA if col1 is not set.""" fill_ser = col1.copy() fill_ser[col2.notna()] = val return col1.fillna(fill_ser)
e8008f50e5f90bff9b54315235c68eaafd296a89
596,244
import hashlib def hash_text(text, algo='sha1'): """Return the hash value for the text.""" h = hashlib.new(algo) h.update(text) return h.hexdigest()
330ea67d3291ddfc1d227697a62efcc848a5c447
596,247
def expand_range(val): """Expands the Haskell-like range given as a parameter into Python's `range` object. The range must be finite. Args: val (str): a range to expand. Returns: range: resulting range. Raises: ValueError: if given an invalid Haskell-like range. >>> e...
7dafcd27c236c4569ffb0d532ce1867aabb4fe4b
596,250
def dequote(text): """ If text has single or double quotes around it, remove them. Make sure the pair of quotes match. If a matching pair of quotes is not found, return the text unchanged. """ if (text[0] == text[-1]) and text.startswith(("'", '"')): return text[1:-1] return text
c52f32acb1f2d6260536e8deaf75ff86bce36191
596,253
def get_delay(num_try, delay, backoff): """Compute backoff delay.""" return delay * (backoff**(num_try - 1))
eff6d41dd044da6ef40bcfe68cb0cb4a99eceb0f
596,261
def largeur_image(image): """ Retourne la largeur de l'image ``image`` (en pixels). Arguments : img : nom de la variable Python contenant l'image """ return image.size[0]
e16f9a5927b11d8b752eb53fba39691997b6e764
596,262
import requests def get_content_from_url(url): """Get the content of the page from the URL as a string""" r = requests.get(url) return r.text
c8f3f65490d4ae32b03b0567882f792a18db51dd
596,265
def ais_step(pot_pre, pot_new, sample_pre, log_weight_pre, mcmc_kernel): """ Compute log Z(p*) = \sum log_avg_exp(log w_T(x_i)) + log Z(p_0). It includes two steps: 1) update w(x_i) by the ratio of two adjacent annealing distribution log w_{t}(x_i^t) = log w_{t-1}(x_i^{t-1}) + log p^*_{t}(x_i^{t-1})...
f85b3bd1aa924c0c01125341d1e3e43853318d73
596,267
def convert_bpe_word(bpe_sent, word_sent): """ Given a sentence made of BPE subwords and words (as a string), returns a list of lists where each sub-list contains BPE subwordss for the correponding word. """ splited_bpe_sent = bpe_sent.split() word_sent = word_sent.split() word_to_bpe ...
d59214cdf64a42d4e34ac6faac9e77fc56e8df17
596,268
import torch def mdot(a, b): """Compute the Frobenius inner product of two matrices Parameters ---------- a : (..., N, M) tensor Left matrix b : (..., N, M) tensor Rightmatrix Returns ------- dot : (...) tensor Matrix inner product References --------...
6dea5642c6feaa1d888894841218e1de8c084d48
596,269
import re def flatten(py_array): """ Takes a python array and flattens it's 'dimensions'. """ flattened = re.sub(r'[\[,\]]', '', str(py_array)).split() return [float(i) for i in flattened]
bbea533385f642853f68c2b085a80998d1451ea7
596,272
def reverse_complement(seq): """ Reverse compliment a DNA sequenec Credit: https://bioinformatics.stackexchange.com/a/3585 """ tab = str.maketrans("ACTG", "TGAC") return seq.translate(tab)[::-1]
f4135a45c6f3e9dbc0b092e12ff4df5d5d3adc74
596,274
def set_bit(bitmask: int, bit: int, flag: bool = True) -> int: """ Set a bit in a bitmask. :param bitmask: The initial bitmask. :param bit: The bit to be set. :param flag: True to set the bit high, False to set the bit low. :returns: The updated bitmask. """ ...
fdc036bbd7f0514340a01a695cbd7ad1ba7de8bc
596,279
def _get_cqlsh_for_query(query: str): """ Creates a `cqlsh` command for given query that will be executed over a TLS connection. """ return 'cqlsh --cqlshrc="$MESOS_SANDBOX/cqlshrc" --ssl -e "{query}"'.format( query=query)
4fe1f60d6a52d8a015cd1f0979d34779305f52eb
596,287
import re def github_username(s): """Is this a valid GitHub username?""" # Usernames can have "[bot]" at the end for bots. suffixes = ["[bot]", "%5Bbot%5D"] for suffix in suffixes: if s.endswith(suffix): s = s[:-len(suffix)] break # For Anant, we added a star just t...
7255267da6f41c46f9401b9cd9cb0a42cd33cdb5
596,289
def to_unicode_str(byte_string, errors="replace"): """Turn a byte string into a unicode string. Should be used everywhere where the input byte string might not be trusted and may contain invalid unicode values. Args: byte_string (bytes): The bytestring that will be converted to a native ...
6d2dc4c36dd560f1f9a304b13431ed2cc1c9afe1
596,292
def filter_by_extension(filenames, extensions): """Takes two lists of strings. Return only strings that end with any of the strings in extensions. """ filtered = [] for extension in extensions: filtered = filtered + [f for f in filenames if f.endswith(extension)] return filtered
f0df3bbdc3946c887e516e179c43892a07c43270
596,308
def map(function, iterable): """ map(function, iterable) -> list Applies function to each element of iterable, returning a list of the resulting values. Basically, this is like the builtin map function, except we only take a single iterable and there's none of that map(None, ...) nonsense. ...
fbe08265cddf4f7078867d0de9427cf5735236e7
596,313
def get_overlap_time(begin_at_infected, end_at_infected, begin_at_contact, end_at_contact): """ Calculates the overlap time between 2 login sessions. Arguments: begin_at_infected: (datetime) begin time of infected person. end_at_infected: (datetime) end time of infected person. begin_at_contact: (datetime) be...
8628e9d4a13582dc9fc36061cf68a1596c25f107
596,314
def prob_win_deuce(p: float) -> float: """Given probability, p, that server wins a point, returns the probability that the server will win deuce if it happens Args: p (float): probability server wins a point Returns: float: probability that server will win deuce """ # returns t...
7019ebaf867185870b4d4b6f9d9f620e750128fa
596,320
from datetime import datetime def get_age_in_model_year(dob, model_year): """Gets the age of a patient relative to Feb 1 of a given model year Arguments: dob {datetime.datetime | string} -- dob as a datetime or string in format 'YYYY-MM-DD' model_year {int} -- Year as Returns: in...
2bb60608e4c2bc3128382bf6a6b9e18519267b12
596,324
import copy def remove_index_from_both_if_equals_zero(a, b): """ Scans over two lists. If any elements equal False/None, then remove that index from both lists. Arguments --------- a : list (of integers usually) b : list (of integers usually) Returns ------- a : list b : ...
5115e23d57af914e2589d25aed2259cb2b4ca5da
596,327
def resolve_exp_resp_string_as_list(element): """ User given comma separated data is converted into a list. If no data is given, then an empty list is formed. """ if element is not None and element is not False: if element == "": element = [] else: temp_list = ele...
980136e1e21dedd5274ac7bd9e690780877f3646
596,332
def scale_list( input_list, # pylint: disable=R0913 min_val, max_val, new_range: int, offset=0, adjust_amount=None): """ Scales a list to fit within a new range the new range is a number defining the new max, and the offset defines the new minumum passi...
8344f7e613e2db06baec117754d0f95eaa2e65e6
596,335
def get_primary_keys(model): """Get primary key properties for a SQLAlchemy model. :param model: SQLAlchemy model class """ mapper = model.__mapper__ return tuple(( mapper.get_property_by_column(column) for column in mapper.primary_key ))
cc69ca1bdc6fba4fa3e5c275d6c15e430d0543f2
596,337
import collections def _compute_pctls(measures): """Return 50pctl, 90pctl, 99pctl, and 999pctl in a dict for the given dissymetries.""" # If measures is empty, then one of the diffables was empty and not the other, # so the dissymmetry pctls should all be set at 100% if not measures: return No...
d0bfbfd547c7d7e7627cd1d9831143f7fb928de3
596,338
import re def safe_filename(filename): """ Given a value, turn it into a valid filename. 1. Remove the spaces 2. Replace anything not alpha, '-', '_', or '.' with '_' 3. Remove duplicate '_' """ string = str(filename).strip().replace(" ", "_") string = re.sub(r"(?u)[^-\w.]", "_", stri...
abe262f30d476ec9e4789f584cad28c08b4167cb
596,342
def create_chunks(sequence, size): """Generate chunks from a sequence. Parameters ---------- sequence : iterable Any iterable object size : int The chunksize to be returned """ return (sequence[p:p + size] for p in range(0, len(sequence), size))
59253fd0fcdbceaff6a7080e3c00cbda1a12abcc
596,349
def dhcp(request): """Specify if dhcp is to be used.""" return request.config.getoption('--dhcp')
2a4212cec6e14518c46534610fae0b2f03c98672
596,350
def octetsToOct(octets): """ convert a string of octets to a string of octal digits """ result = '' while octets: byte = octets[0] octets = octets[1:] result += "%.4s," % oct(ord(byte)) return result
7eb8792f1d8c55c6be84eaad950656bfd438999d
596,352
import csv def read_csv(filepath, encoding='utf-8', newline='', delimiter=','): """ Reads a CSV file, parsing row values per the provided delimiter. Returns a list of lists, wherein each nested list represents a single row from the input file. WARN: If a byte order mark (BOM) is encountered at the be...
929b8a2d3207309afdda399e0950f0f4c4cd476d
596,361
def _make_final(environment): """ Determine the final environment's section """ if environment is None: return 'final' else: return f"{environment}.final"
0b02159ca5308c8fe725d6a425138c0c7fc5dfae
596,366
from typing import List def add_to_k(A: List[int], k: int) -> bool: """We scan the array and add each element to the set. As we traverse the array, we record each element and check to see if the element's complement has already been seen (k - element). If it has been seen, then we know that there are ...
591429d10b80b7fd793f2f638304e1d40ec9ba19
596,367