content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def mask_to_surface_type(ds, surface_type, surface_type_var="land_sea_mask"): """ Args: ds: xarray dataset, must have variable slmsk surface_type: one of ['sea', 'land', 'seaice', 'global'] Returns: input dataset masked to the surface_type specified """ if surface_type == "global": return ds elif surface_type not in ["sea", "land", "seaice"]: raise ValueError( "Must mask to surface_type in ['sea', 'land', 'seaice', 'global']." ) surface_type_codes = {"sea": 0, "land": 1, "seaice": 2} mask = ds[surface_type_var].astype(int) == surface_type_codes[surface_type] ds_masked = ds.where(mask) return ds_masked
0ee07b852c142d0041841288c54bbc68afdd65f8
16,108
def clip(value, lower, upper): """ clip a value between lower and upper """ if upper < lower: lower, upper = upper, lower # Swap variables return min(max(value, lower), upper)
c7324ecd1e6e734a613071c26c2c00c33d2c487e
16,112
import asyncio async def do_after_sleep(delay: float, coro, *args, **kwargs): """ Performs an action after a set amount of time. This function only calls the coroutine after the delay, preventing asyncio complaints about destroyed coros. :param delay: Time in seconds :param coro: Coroutine to run :param args: Arguments to pass to coroutine :param kwargs: Keyword arguments to pass to coroutine :return: Whatever the coroutine returned. """ await asyncio.sleep(delay) return await coro(*args, **kwargs)
913998318c8438b2afaf9fcb6e687c4e4a8149e6
16,115
from typing import Dict def extract_tags(repo_info: Dict) -> Dict: """Extracts the tags from a repository's metadata. Args: repo_info: The repository's metadata. Returns: The repository's tags. """ tags = {} repo_tags = repo_info.get("tags") if repo_tags: for repo_tag in repo_tags: # Restrict splitting to the first ":" in case the value also contains a ":" split_tags = repo_tag.split(":", maxsplit=1) if len(split_tags) == 2: tags[split_tags[0]] = split_tags[1] return tags
108e343a84e7a076a6d42e4a3c2cdf0c12389e6b
16,117
def xgcd(a: int, b: int) -> tuple: """Extended Euclidean (GCD) algorithm gcd(a, b) = u*a + v*b Returns gdc, u, v """ x, x1, y, y1 = 1, 0, 0, 1 while b: q, a, b = a // b, b, a % b x, x1 = x1, x - q * x1 y, y1 = y1, y - q * y1 return a, x, y
3dba9fee305f2c423f84607177ca1b9025d33978
16,118
def flatten(data): """Recursively flatten lists""" result = [] for item in data: if isinstance(item, list): result.append(flatten(item)) else: result.append(item) return result
bb4a7a91f921f67bed3d70e74246e1cc8eec825c
16,120
def get_train_test_modifiers(modifier=None): """Append the modifier to 'train' and 'test'""" modifier_train = 'train' modifier_test = 'test' if modifier is not None: modifier_train = modifier_train + '_' + modifier modifier_test = modifier_test + '_' + modifier return modifier_train, modifier_test
6adb8e2a6bb427de059ef7cd127476342ba39a3f
16,123
def logp_gradient(variable, calculation_set=None): """ Calculates the gradient of the joint log posterior with respect to variable. Calculation of the log posterior is restricted to the variables in calculation_set. """ return variable.logp_partial_gradient(variable, calculation_set) + sum( [child.logp_partial_gradient(variable, calculation_set) for child in variable.children])
8c1dd9207e1c08826d51053cb887a86d06306367
16,124
def mock_db_url(tmpdir): """Fixture to provide mock db url This url is intended to be the location of where to place the local sqlite databases for each unit test""" dbname="dcae_cli.test.db" config_dir = tmpdir.mkdir("config") return "/".join(["sqlite://", str(config_dir), dbname])
a6f06b15edfb685ebb0ff38ae421091f06039563
16,125
def reproject_extent(extent, current_extent): """ Changes an extent from its current spatial reference to the spatial reference on another extent object :param extent: :param current_extent: :return: """ return extent.projectAs(current_extent.spatialReference)
b64e98c15cda62e1a4855050a63b7ff7fcd38610
16,129
def _get_feature_help(module: object) -> str: """ Get the docstring of the imported module :param module: the imported module object :return: The docstring as string """ return module.__doc__ or "[ERROR] Missing the module docstring"
804f3586137adf7a22231225bd326fff2fcbd704
16,130
def get_model_parameters(model): """FUNCTION::GET_MODEL_PARAMETERS: Gets all the parameters of a model. --- Arguments: --- >- model {keras.Model} -- The model to analyze. Returns: --- >- {list[string]} -- layer Names >- {list[np.array]} -- layer Weights >- {list[tensor]} -- layer Outputs >- {list[tensor]} -- layer Activations.""" layerNames = []; layerOutputs = []; layerWeights = []; layerAct = [] for layer in model.layers: layerNames.append(layer.name) layerOutputs.append(layer.output) layerAct.append(layer.activation) layerWeights.append(layer.get_weights) return layerNames,layerWeights,layerOutputs,layerAct
96341de438b0359425381ebed400ab38da35304a
16,132
def two_letter_language_code(feed): """ feed.language conforms to http://www.rssboard.org/rss-language-codes sometimes it is of the form de-de, de-au providing a hint of dialect thus, we only pick the first two letters of this code :param feed: :return: """ return feed.language[:2]
f4da54d15e73a1c317a90cce08de4a44d55ae273
16,135
from typing import Type import importlib def _string_to_class(string: str) -> Type: """ Parse a string into a Python class. Args: string: a fully qualified string of a class, e.g. 'mypackage.foo.MyClass'. Returns: The class. """ components = string.split(".") class_name = components[-1] module_name = ".".join(components[:-1]) module = importlib.import_module(module_name) cls = getattr(module, class_name) assert isinstance(cls, type) return cls
e756b35a5d34aaeffa8ddc4e96130da3a3bc5d04
16,137
def roundup(val, width): """roundup a value to N x width-bits""" x = (width >> 3) - 1 return (val + x) & ~x
45a303ca8f2ba5312fe89e73542606dbe68ed627
16,142
def sum_keep_digits(m: int, n: int, digit_count: int) -> int: """Finds the last base-10 digits of the sum of two non-negative integers. Args: m: The first non-negative integer addend. n: The second non-negative integer addend. digit_count: The number of least significant digits of the resulting sum that should be preserved. Returns: An integer consisting of the last ``digit_count`` digits (from most to least significant) of the sum ``m + n`` when written in base 10. """ mod = 10**digit_count return ((m % mod) + (n % mod)) % mod
c09bf6a9bf681deae133bb787e2f1b50711dd24a
16,150
def split_layouts_by_arrow(s: str) -> tuple: """ Splits a layout string by first arrow (->). :param s: string to split :return: tuple containing source and target layouts """ arrow = s.find('->') if arrow != -1: source_layout = s[:arrow] target_layout = s[arrow + 2:] if source_layout == '': source_layout = None if target_layout == '': target_layout = None return source_layout, target_layout else: return s, None
30781f9a5d7b8b342c2a7d9fefb2085b2e990994
16,157
import pathlib def parse_bind_volume(bind_arg): """unpack volume bind bind_arg (e.g., /foo:/bar) to dict where the key is a resolve pathlib.Path and the value is an unresolved (in-container) pathlib.PosixPath.""" # can be up to three, but we only want the first two bind_arg = bind_arg.split(":") src, dst = bind_arg[:2] assert len(bind_arg) < 4, "unexpected number of bind_arg" return {pathlib.Path(src).resolve(): pathlib.PosixPath(dst)}
ea2b4ac8ba03e3829ab4db69684ebf49767e0c94
16,158
def strip_lines(s, side='r'): """ Splits the given string into lines (at newlines), strips each line and rejoins. Is careful about last newline and default to stripping on the right only (side='r'). Use 'l' for left strip or anything else to strip both sides. """ strip = (str.rstrip if side == 'r' else str.lstrip if side == 'l' else str.strip) end = '\n' if s.endswith('\n') else '' return '\n'.join([strip(line) for line in s.splitlines()]) + end
4995710e9df31e7e210621b3f9be0af38642324e
16,160
def _draw_bbox_pil(canvas, bbox, color, stroke): """Draws BBox onto PIL.ImageDraw :param bbox: BBoxDiim :param color: Color :param stroke: int :returns PIL.ImageDraw """ xyxy = bbox.xyxy_int if stroke == -1: canvas.rectangle(xyxy, fill=color.rgb_int) else: canvas.rectangle(xyxy, outline=color.rgb_int, width=stroke) return canvas
a5dd958cd18a9f9129567af55d5057b105d4fe59
16,162
def _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit): """ Constructs dict with URL params :param tile_id: original tile identification string provided by ESA (e.g. 'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01') :type tile_id: str :param bbox: bounding box of requested area in WGS84 CRS :type bbox: common.BBox :param start_date: beginning of time range in ISO8601 format :type start_date: str :param end_date: end of time range in ISO8601 format :type end_date: str :param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA :type absolute_orbit: int :return: dictionary with parameters as properties when arguments not None :rtype: dict """ url_params = { 'identifier': tile_id, 'startDate': start_date, 'completionDate': end_date, 'orbitNumber': absolute_orbit, 'box': bbox } return {key: str(value) for key, value in url_params.items() if value}
029d6b2ecd0871fde521a98d3edb09f2a6bf947b
16,164
def padding_string(pad, pool_size): """Get string defining the border mode. Parameters ---------- pad: tuple[int] Zero-padding in x- and y-direction. pool_size: list[int] Size of kernel. Returns ------- padding: str Border mode identifier. """ if pad == (0, 0): padding = 'valid' elif pad == (pool_size[0] // 2, pool_size[1] // 2): padding = 'same' elif pad == (pool_size[0] - 1, pool_size[1] - 1): padding = 'full' else: raise NotImplementedError( "Padding {} could not be interpreted as any of the ".format(pad) + "supported border modes 'valid', 'same' or 'full'.") return padding
985828faf9c072b623776be23e8ef0b7c680aba8
16,166
def apply_eqn(x, eqn): """ Given a value "x" and an equation tuple in the format: (m, b) where m is the slope and b is the y-intercept, return the "y" generated by: y = mx + b """ m, b = eqn return (m * x) + b
1d5078905a20e6b83c2186f6aefbedaa70863fea
16,167
def ext_euclid_alg (m, n): """ Extended Euclidean algorithm for gcd. Finds the greatest common divisor of two integers a and bm and solves for integer x, y such that ax + by = 1. From Knuth, TAOCP vol. I, p. 14. Variables -- q, r -- quotient and remainder a, b -- am + bn = gcd apme, bpme -- a prime and b prime t -- temporary """ m, n = abs(m), abs(n) q, r = m // n, m % n apme = b = 1 a = bpme = 0 while r != 0: m, n = n, r t = apme apme = a a = t - q * a t = bpme bpme = b b = t - q * b """ reset q and r """ q, r = m // n, m % n return (n, a, b)
f6ee18c045dd6c26023ff70ab43dde550071023c
16,168
import torch def get_prior_precision(args, device): """ Obtain the prior precision parameter from the cmd arguments """ if type(args.prior_precision) is str: # file path prior_precision = torch.load(args.prior_precision, map_location=device) elif type(args.prior_precision) is float: prior_precision = args.prior_precision else: raise ValueError('Algorithm not happy with inputs prior precision :(') return prior_precision
b3a34d3831c42b490f1750c47de06743e5ff0b8a
16,170
def to_redfish_version(ver32): """ Converts a PLDM ver32 number to a Redfish version in the format vMajor_Minor_Errata """ if ver32 == 0xFFFFFFFF: # un-versioned return '' else: return 'v'+str((ver32 >> 24) & 0x0F)+'_'+str((ver32 >> 16) & 0x0F)+'_'+str((ver32 >> 8) & 0x0F)
56ccd29c01b7307fa8ee47ae5e7fa4fb89163523
16,185
def restrictToHostsOnCurrentStage(statsboardData, hostsOnCurrentStage): """ Removes data for hosts not on current stage from statsboardData, and returns the new version. :param statsboardData: :param hostsOnCurrentStage: :return: """ # NOTE: can be optimized if necessary. newData = [] for dataSlice in statsboardData: if "tags" in dataSlice: if "host" in dataSlice["tags"]: if dataSlice["tags"]["host"] in hostsOnCurrentStage: newData.append(dataSlice) return newData
740f2c55a14472c36b3f6109fe2e89ef5880e04b
16,187
def POUF_unblind(params, ai, zi): """ Unblind the messages to recover the raw outputs of the POUF """ G, g, o = params xi = [a.mod_inverse(o) * z for a,z in zip(ai, zi)] return xi
2fb5d1e2d758422dd7df9ff16baa1c834e320f7b
16,188
from typing import List def align_lines(lines: list, column_separator: str = "|") -> List[str]: """ Pads lines so that all rows in single column match. Columns separated by '|' in every line. :param lines: list of lines :param column_separator: column separator. default is '|' :return: list of lines """ rows = [] col_len: List[int] = [] for line in lines: line = str(line) cols = [] for col_index, col in enumerate(line.split(column_separator)): col = str(col).strip() cols.append(col) if col_index >= len(col_len): col_len.append(0) col_len[col_index] = max(col_len[col_index], len(col)) rows.append(cols) lines_out: List[str] = [] for row in rows: cols_out = [] for col_index, col in enumerate(row): if col_index == 0: col = col.ljust(col_len[col_index]) else: col = col.rjust(col_len[col_index]) cols_out.append(col) lines_out.append(" ".join(cols_out)) return lines_out
2ec537752bfce3d261d7202e9b9266a9ae0dd87f
16,189
from typing import SupportsIndex def ireplace(text: str, old_: str, new_: str, count_: SupportsIndex = -1) -> str: """Case-insensitive :py:meth:`str.replace` alternative. :param text: String to search through. :param old_: Case-insensitive substring to look for. :param new_: Case-sensitive substring to replace with. :param count_: Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences. :return: A string with all substrings matching old_ replaced with new_. """ index: int = 0 if not old_: return text.replace('', new_) if text.lower() == old_.lower() and count_.__index__() != 0: return new_ while index < len(text) and count_.__index__() < 0: index_l = text.lower().find(old_.lower(), index) if index_l == -1: return text text = text[:index_l] + new_ + text[index_l + len(old_):] index = index_l + len(new_) return text
8509314192458c867b6471a381dc6470a2546902
16,192
def alpha(requestContext, seriesList, alpha): """ Assigns the given alpha transparency setting to the series. Takes a float value between 0 and 1. """ for series in seriesList: series.options['alpha'] = alpha return seriesList
25ef9bad1b39549585bdb175e487236591d0816f
16,194
def ask_yes_no_question(question): """Prints a question on the CLI that the user must respond with a yes or no. :param question: Text of the question. Include question mark on it. :type question: str :return: Whether the user said 'y' (True) or 'n' (False). :rtype: bool """ answer = '' while answer not in ('y', 'n'): print(f'{question} [y/n](n):') answer = input() if not answer: answer = 'n' if answer == 'y': return True return False
6a70b135879e0fcd27ba6bc7fbc330a0660bd729
16,196
def akmcsInfocheck(akmcsInfo): """ Helper function to check the AKMCS dictionary. Checks akmcsInfo dict and sets default values, if required parameters are not supplied. Args: akmcsInfo (dict): Dictionary that contains AKMCS information. Returns: akmcsInfo: Checked/Modified AKMCS Information. """ if "init_samp" not in akmcsInfo: raise ValueError('akmcsInfo["init_samp"] must be defined') else: pass if "maxupdate" not in akmcsInfo: akmcsInfo["maxupdate"] = 120 print("Maximum update is set to ", akmcsInfo["maxupdate"]) else: print("Maximum update is set to ", akmcsInfo["maxupdate"], " by user.") if "problem" not in akmcsInfo: raise ValueError('akmcsInfo["problem"] must be defined') else: pass return akmcsInfo
5e70785cb2c6050f9e10b8936e64ed19b71cf4d5
16,204
def is_null(value, replace: str = ""): """ Checks if something is empty and will replace it with the given value Parameters ---------- value A thing to check if empty replace : string The thing to replace it with """ return value if value else replace
ae81cf7842de03653b7496984f577d67c3edecf2
16,205
def mean(values): """ Mean function. """ m = 0.0 for value in values: m = m + value/len(values) return m
4415b4f9aa373b54418683301ffe751249270d4c
16,207
def set_pianoroll_shape(pianoroll, data_shape): """Set the pianoroll shape and return the pianoroll.""" pianoroll.set_shape(data_shape) return pianoroll
ca326624a83252411aa996b31bd6cfd8dd6c5baa
16,209
def evs_to_policy(search_policy_evs, *, temperature=1.0, use_softmax=True): """Compute policy targets from EVs. Args: search_policy_evs: Float tensor [T, B, 7, max_actions]. Invalid values are marked with -1. temperature: temperature for softmax. Ignored if softmax is not used. use_softmax: whether to apply exp() before normalizing. Returns: search_policy_probs: Float tensor [T, B, 7, max_actions]. """ search_policy_probs = search_policy_evs.clone().float() invalid_mask = search_policy_evs < -0.5 if use_softmax: search_policy_probs /= temperature # Using -1e8 instead of -inf so that softmax is defined even if all # orders are masked out. search_policy_probs[invalid_mask] = -1e8 search_policy_probs = search_policy_probs.softmax(-1) else: search_policy_probs.masked_fill_(invalid_mask, 0.0) search_policy_probs /= (invalid_mask + 1e-20).sum(-1, keepdim=True) return search_policy_probs.to(search_policy_evs.dtype)
46ac6e9fee0a8c010aef23519cbc594f0c0eb09d
16,210
def extract_list (data_str, to_float=False): """ Extract a list of floating point values from a string """ split_str = data_str.split(',') if to_float == True: split_str = [float(x) for x in split_str] return split_str
09825f9d7533bfbe9812bd6956b096cc33cb0be1
16,211
def prompt(message, values=None): """Prompt a message and return the user input. Set values to None for binary input ('y' or 'n'), to 0 for integer input, or to a list of possible inputs. """ if values is None: message += ' (y/n)' message += ' > ' while 1: ans = input(message) if values is None: if ans.lower() == 'y': return True elif ans.lower() == 'n': return False elif values == 0: try: read = int(ans) except: continue return read elif ans in values: return ans
4d6b87b84ed1dfd95722e0055a8df3b1b34f1e84
16,212
def words_vec(w2v, words, use_norm=False): """ Return a dict that maps the given words to their embeddings. """ if callable(getattr(w2v, 'words_vec', None)): return w2v.words_vec(words, use_norm) return {word: w2v.wv.word_vec(word, use_norm) for word in words if word in w2v.wv}
46447f389800e36d7149da245fb0d38be24bbbe3
16,213
import asyncio def in_async_call(loop, default=False): """Whether this call is currently within an async call""" try: return loop.asyncio_loop is asyncio.get_running_loop() except RuntimeError: # No *running* loop in thread. If the event loop isn't running, it # _could_ be started later in this thread though. Return the default. if not loop.asyncio_loop.is_running(): return default return False
9ed888e0d8ee27d18c843a184071d9596880c039
16,216
def dictlist_lookup(dictlist, key, value): """ From a list of dicts, retrieve those elements for which <key> is <value>. """ return [el for el in dictlist if el.get(key)==value]
94e90b29c8f4034357be2b8683115f725c24b374
16,218
def df_to_geojson(df, geometry, coordinates, properties): """ Convert a pandas DataFrame to a GeoJson dictionary. Parameters ---------- df : pandas DataFrame DataFrame containing the geojson's informations. geometry : String The type of the geometry (Point, Polygon, etc.). coordinates : String The DataFrame column's name of the coordinates. properties : list of String eelements. The DataFrame column's names of the properties attributes. Returns ------- geojson : Dict GeoJson dictionary with the geometry, coordinates, and properties elements. """ geojson = {'type': 'FeatureCollection', 'features': []} for _, row in df.iterrows(): feature = {'type':'Feature', 'properties':{}, 'geometry': {'type': geometry, 'coordinates': coordinates}} for prop in properties: normalize_prop = prop.lower().split('.')[-1] feature['properties'][normalize_prop] = row[prop] geojson['features'].append(feature) return geojson
75fa808dca18b89e2e259425b9b9e67bb8ac2415
16,221
def get_bytes(block_nums): """ Takes an array of block integers and turns them back into a bytes object. Decodes using base 256. :param block_nums: Blocks (list of ints) :return: Original data (bytes) """ message = [] for block in block_nums: block_text = [] while block: message_num = block % 256 block = block // 256 block_text.append(bytes([message_num])) block_text.reverse() message.extend(block_text) return b''.join(message)
429325cd37a3f821b751237659626907eb19d4a9
16,222
def check_positive_int(string): """Convert a string to integer and check if it's positive. Raise an error if not. Return the int. """ if int(string) > 0: return int(string) else: raise RuntimeError("Integer must be positive.")
1e32994a2d9d58b1361a9228b78210398c19c94e
16,225
def clamp_value(my_value, min_value, max_value): """Limit value by min_value and max_value.""" return max(min(my_value, max_value), min_value)
f3478b08f3e2e38ba3459d487adc9c462468c32e
16,226
def _buses_with_gens(gens): """ Return a list of buses with generators """ buses_with_gens = list() for gen_name, gen in gens.items(): if not gen['bus'] in buses_with_gens: buses_with_gens.append(gen['bus']) return buses_with_gens
5cf9e918a55e140053bceb538cd1f15b331c253d
16,229
import hashlib def get_key(model_params, mw_range, bins): """ Generate a hash key based on the model parameters used and the fited mw_range and number of bins. """ hasher = hashlib.md5() hasher.update(bytes(str(model_params), 'ASCII')) hasher.update(bytes(str(mw_range), 'ASCII')) hasher.update(bytes(str(bins), 'ASCII')) key = hasher.hexdigest() return key
50fe5d13bf9f897c76ee144c576212ec483e1948
16,230
from typing import Any import hashlib def md5(item: Any) -> str: """Compute the MD5 hash of an object. Args: item: The object to compute the MD5 hash on. Returns: The MD5 hash of the object. """ return hashlib.md5(str(item).encode()).hexdigest()
5589eb0a38b9f099a7f4b418d719b9c089110d5a
16,237
def SortLists(sortbylist,otherlists,reverse=False): """This function sorts lists similar to each list being a column of data in a spreadsheet program and choosing one column to sort by. The sortbylist is the column or list that you wish to sort by and otherlists is a list of the other lists or columns to sort. Reverse is passed to the sort method of sortbylist.""" newlist=sortbylist[:] newlist.sort(reverse=reverse) bigoutlist=[] for list in otherlists: curlist=[] for curitem in newlist: ind=sortbylist.index(curitem) curlist.append(list[ind]) bigoutlist.append(curlist) return (newlist,)+tuple(bigoutlist)
132678fa35f008e4f987ffca57e729840438ca72
16,244
from typing import Any def is_json_string(value: Any) -> bool: """Check if the provided string looks like json.""" # NOTE: we do not use json.loads here as it is not strict enough return isinstance(value, str) and value.startswith("{") and value.endswith("}")
16418c37fc1d348e4d1e5805c485f181e514d537
16,249
def get_filediff_encodings(filediff, encoding_list=None): """Return a list of encodings to try for a FileDiff's source text. If the FileDiff already has a known encoding stored, then it will take priority. The provided encoding list, or the repository's list of configured encodingfs, will be provided as fallbacks. Args: filediff (reviewboard.diffviewer.models.filediff.FileDiff): The FileDiff to return encodings for. encoding_list (list of unicode, optional): An explicit list of encodings to try. If not provided, the repository's list of encodings will be used instead (which is generally preferred). Returns: list of unicode: The list of encodings to try for the source file. """ filediff_encoding = filediff.encoding encodings = [] if encoding_list is None: encoding_list = filediff.get_repository().get_encoding_list() if filediff_encoding: encodings.append(filediff_encoding) encodings += [ encoding for encoding in encoding_list if encoding != filediff_encoding ] else: encodings += encoding_list return encodings
5c951bbc6266daa058de58bdeb1382ea6dc93ada
16,254
def get_group_command_url(environment: str, enterprise_id: str, group_id: str) -> str: """ Build and return pipeline url for scapi endpoint :param environment: :param enterprise_id: :param group_id: :return: Url """ url = f'https://{environment}-api.esper.cloud/api/enterprise/{enterprise_id}/devicegroup/{group_id}/command/' return url
34402dbe263ddd5cd4b04b247beb09701f2b2cc6
16,256
def mutate_query_params(request, mutations): """ Return a mutated version of the query string of the request. The values of the `mutations` dict are interpreted thus: * `None`, `False`: Remove the key. * Any other value: Replace with this value. :param request: A HTTP request. :type request: django.http.HttpRequest :param mutations: A mutation dict. :type mutations: dict[str, object] :return: query string """ new_qs = request.GET.copy() for key, value in mutations.items(): if value in (None, False): new_qs.pop(key, None) else: new_qs[key] = value return new_qs.urlencode()
215a79ce82859eb415454876c1c80cdfdb34d7f6
16,257
import math import random def Move(Location, xT): """ This function will return the new location (as a tuple) of a particle after it has isotropically scattered Location: Location of particle before scattering xT: Total cross section of medium """ # Sample distance to collision Distance = (1/xT)*math.log(random.random()) # Sample new direction phi = 2*math.pi*random.random() u = 2*random.random() - 1 v = math.sqrt(1-u*u)*math.cos(phi) w = math.sqrt(1-u*u)*math.sin(phi) # Move particle x = Location[0] + Distance*u y = Location[1] + Distance*v z = Location[2] + Distance*w return (x, y, z)
5902de845db37e5848fbf64954f971fcdce60c89
16,258
def get_color(col, color): """Function needed for backwards compatibility with the old "col" argument in plt functions. It returns the default color 'C0' if both arguments are None. If 'color' is not None, it always uses that. If 'color' is None and 'col' is an integer, it returns the corresponding 'CN' color. If 'col' is neither None nor integer, an error is raised.""" if color is None and col is None: return 'C0' if col is None: return color if not isinstance(col, int): raise ValueError("`col` must be an integer. Consider using `color` instead.") return 'C{}'.format(col)
b4e7cbeacca0e730cb2fa5f320318da83cabfc1a
16,261
def stations_by_river(stations): """Creates a dictionary of stations that are located on the same river. The river is the key for this dictionary""" river_dictionary = {} for i in stations: station_list = [] for j in stations: if i.river == j.river: station_list.append(j.name) river_dictionary[i.river] = station_list return river_dictionary
cf6d324c10ecb756dfa4c506adbbd16316a0d500
16,267
def get_margin(length): """Add enough tabs to align in two columns""" if length > 23: margin_left = "\t" chars = 1 elif length > 15: margin_left = "\t\t" chars = 2 elif length > 7: margin_left = "\t\t\t" chars = 3 else: margin_left = "\t\t\t\t" chars = 4 return margin_left
c50b1253a737d787f696216a22250fb2268216ab
16,275
def unique_list(it): """ Create a list from an iterable with only unique element and where the order is preserved. Parameters ---------- it : iterable Items should be hashable and comparable Returns : list All items in the list is unique and the order of the iterable is preserved. """ unique = set() return [i for i in it if i not in unique and unique.add(i) is None]
5122b3fdb7a489df856ad6ff4a17da58a99a8160
16,277
def f4(x): """Evaluate the estimate x**4+x**3+x**2+x.""" return x*(x*(x*x+x)+x)+x
6a5e258d77992e8c15a6dddb04627a7d5c8467d9
16,278
import re def _is_private_name(name): """ Return true if the given variable name is considered private. Parameters ---------- name : str Variable name to check """ # e.g. __name__ is considered public. is_reserved_public_name = re.match(r"__[a-zA-Z0-9_]+__$", name) is not None return name.startswith("_") and not is_reserved_public_name
1232f6a52ffc9d07d7ed286771c3c75bc80db8b7
16,280
import shlex def shell_join(argv, delim=" "): """Join strings together in a way that is an inverse of `shlex` shell parsing into `argv`. Basically, if the resulting string is passed as a command line argument then `sys.argv` will equal `argv`. Parameters ---------- argv : list(str) List of arguments to collect into command line string. It will be escaped accordingly. delim : str Whitespace delimiter to join the strings. Returns ------- cmd : str Properly escaped and joined command line string. """ vv = [shlex.quote(vv) for vv in argv] cmd = delim.join(vv) assert shlex.split(cmd) == list(argv) return cmd
d58fb2d899bc1f72adf0dd22bdc55ddc9ffeecfb
16,282
def inverted_index_add(inverted, doc_id, doc_index): """ Add Invertd-Index doc_index of the document doc_id to the Multi-Document Inverted-Index (inverted), using doc_id as document identifier. {word:{doc_id:[locations]}} """ for word, locations in doc_index.items(): indices = inverted.setdefault(word, {}) indices[doc_id] = locations return inverted
4ef0cad9892a09dfaeb730487f413836ba72b7d3
16,283
def append(xs, ys): """ Adds all the elements of xs and ys and returns a combined list. """ return xs + ys
e629ece09214a88465d780bb82f2b6f1a82af18a
16,289
import re def get_all_text(elem): """Returns all texts in the subtree of the lxml.etree._Element, which is returned by Document.cssselect() etc. """ text = ''.join(elem.itertext()) return re.sub(r'\s+', ' ', text).strip()
1c8e2e8743147fd3b09488445d8578a89f5346d7
16,294
def _collect_mexp_symbols(value): """Get symbols in a math expression. :param value: The math expression. :rtype : list of str :return: A list of symbols. """ # Get symbols. fsm = value.free_symbols # Initialize symbol list. ret = [] # Pop symbols. while len(fsm) != 0: ret.append(fsm.pop().name) return ret
c031212e3af5bd485dc572c4cf9bb31cfc2be3db
16,297
def _inBoundaries(value, bounds): """ Tell if an integer value is within a range. Parameters ---------- value : int A value to be tested. bounds : int | tuple(int, int) Low boundary of the range, or a tuple of the form (low, high+1). Returns ------- boolean Whether or not the value fell within the range """ if type(bounds) is tuple: assert 2 == len(bounds) return bounds[0] <= value < bounds[1] else: assert type(bounds) is int return bounds <= value
dcc9fcf993ee7b25bb0f6b8cb8acea7b0474fad5
16,298
def has_neighbor(prop1: str, prop2: str) -> str: """ Builds the statements required for: The person who `prop1` has a neighbor who `prop2`. For example, "The Norwegian lives next to the Blue house." We can solve this by doing a disjunction of all satisfying possibilities. Because we've previously stated that, for example, there's only one Norwegian and only one blue house, we don't need to conjoin to prevent duplicates. Thus, we can say: ```ignore (assert (or (and (norwegian 1) (blue 2)) (and (norwegian 2) (blue 1)) (and (norwegian 2) (blue 3)) (and (norwegian 3) (blue 2)) (and (norwegian 3) (blue 4)) ... )) ``` """ ands = [] for i in range(1, 6): for j in range(1, 6): if abs(i-j) == 1: ands.append(f' (and ({prop1} {i}) ({prop2} {j}))') return '(assert (or\n' \ + '\n'.join(ands) \ + '))\n'
d63dd6e09ce822cdcd87970dd205ee34857ad8f4
16,300
def bl_little_mock(url, request): """ Mock for bundle lookup, small output. """ littlebody = b'<?xml version="1.0" encoding="UTF-8"?><availableBundlesResponse version="1.0.0" sessionId="7762de1a-909c-4afb-88fe-57acb69e9049"><data authEchoTS="1366644680359"><status code="0"><friendlyMessage>Success</friendlyMessage><technicalMessage>Success</technicalMessage></status><content><bundle version="10.3.1.2726"><type>system:os</type><type>system:radio</type><type>application</type></bundle></content></data><signature><root><cipher>EC521R1</cipher><shaType>SHA512</shaType><sigR>AN80t5quXy/WiTy0Lw0llAIGmRVogdfRttDOCbWh6uUquvAvAt2YAN1OOCLJbOOFn5SppytUJi34wXOxiopv2RjX</sigR><sigS>APPbsvblhDzEhpef8wQBgxCrTJ851e/BeVBLUzlGG7ovy220QdQHeG8ahk9bMeoTmnIkWc6f/kCs+h7hGkel+OYT</sigS></root><chain ordinal="1"><cipher>EC521R1</cipher><shaType>SHA512</shaType><publicKey notValidUntil="1434252700605" notValidAfter="1434684700605">BAHbALLG0oyfF7ZvmxOjz1NFODaTEd9gvdqaqgSwuTi39Jv87q0ZWfY7kVSxWAyuumQYfIpy+9ruTd4z7cNvXJ0u8ACJvuo3xzNpgCah74Wpqcvr+EuNGkVe0IAZDXZSGPeZC739vkPitYiqJDP8joOuFTIdpUop/qJj+YckijR9RujdUw==</publicKey><sigR>Aaou0PAOGD7njwYckvvAGlepOmDSbRV2clsaskubz01+sQ9YlLhwctCAPS9n9kpdnnYbg2TDvh6XN3lUFgmfGvJl</sigR><sigS>AN34KjWeSGVIBz4KTlHzMGMpKfDKsOQPT5UVsy+tczBhKdAeDYGaU5Yc/YFaAOz7RuxjIbHkohuHESqDcXCnvif6</sigS></chain></signature></availableBundlesResponse>' return {'status_code': 200, 'content': littlebody}
0b35d1e30c32b89351341103ba9013ca95c0ba2e
16,307
from typing import Optional def _transform_op(op: Optional[str]) -> str: """Transforms an operator for MongoDB compatibility. This method takes an operator (as specified in a keyword argument) and transforms it to a ``$`` prefixed camel case operator for MongoDB. """ if op is None: return "$eq" camel = op[0].lower() + op.title()[1:].replace("_", "") return f"${camel}"
6168e84387ade258b2907445e5d3536228053521
16,309
def stop_server(proc): """ Stop server process. proc: ShellProc Process of server to stop. """ return proc.terminate(timeout=10)
c126ca840b56407f1eea8af943f4602532df13df
16,318
def get_oct(value): """ Convert an integer number to an octal string. """ try: return oct(value) except: return value
0e07b02f7a727c5942c1f6f1d7d1ca12506328f4
16,327
import torch def compute_distance_histograms(a, dx, b, dy): """ Computes the squared distance between histograms of distance of two mm-spaces. The histograms are obtained by normalising measures to be probabilities. Parameters ---------- a: torch.Tensor of size [Batch, size_X] Input measure of the first mm-space. dx: torch.Tensor of size [Batch, size_X, size_X] Input metric of the first mm-space. b: torch.Tensor of size [Batch, size_Y] Input measure of the second mm-space. dy: torch.Tensor of size [Batch, size_X, size_X] Input metric of the first mm-space. Returns ------- lcost: torch.Tensor of size [size_X, size_Y] distances between metric histograms """ h_x = torch.einsum('ij, j->i', dx, a / a.sum()) h_y = torch.einsum('ij, j->i', dy, b / b.sum()) lcost = (h_x ** 2)[:, None] + (h_y ** 2)[None, :] lcost = lcost - 2 * h_x[:, None] * h_y[None, :] return lcost
7758c15cea89d9eabba2fbf95decd6252bec532d
16,329
def gather_3rd(params, indices): """Special case of tf.gather_nd where indices.shape[-1] == 3 Check https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/gather_nd for details. Args: params: Tensor, shaped [B, d_1, ..., d_i], di >= 2 indices: LongTensor, shaped [B, i_1, ...,i_{k-1}, 3] Returns: Tensor, of shape indices.shape[:-1] + params.shape[indices.shape[-1]:] """ return params[indices[..., 0], indices[..., 1], indices[..., 2]]
948acdbb83b283cc0bef743d679e7d30fbaa0ad6
16,330
def apply_date_format(in_data): """ This routine adds the default UTC zone format to the input date time string If a timezone (strting with + or -) is found, all the following chars are replaced by +00, otherwise +00 is added. Note: if the input zone is +02:00 no date conversion is done, at the time being this routine expects UTC date time values. Examples: 2018-05-28 16:56:55 ==> 2018-05-28 16:56:55.000000+00 2018-05-28 13:42:28.84 ==> 2018-05-28 13:42:28.840000+00 2018-03-22 17:17:17.166347 ==> 2018-03-22 17:17:17.166347+00 2018-03-22 17:17:17.166347+00:00 ==> 2018-03-22 17:17:17.166347+00 2018-03-22 17:17:17.166347+00 ==> 2018-03-22 17:17:17.166347+00 2018-03-22 17:17:17.166347+02:00 ==> 2018-03-22 17:17:17.166347+00 Args: the date time string to format Returns: the newly formatted datetime string """ # Look for timezone start with '-' a the end of the date (-XY:WZ) zone_index = in_data.rfind("-") # If index is less than 10 we don't have the trailing zone with - if (zone_index < 10): # Look for timezone start with '+' (+XY:ZW) zone_index = in_data.rfind("+") if zone_index == -1: if in_data.rfind(".") == -1: # there are no milliseconds in the date in_data += ".000000" # Pads with 0 if needed in_data = in_data.ljust(26, '0') # Just add +00 timestamp = in_data + "+00" else: # Remove everything after - or + and add +00 timestamp = in_data[:zone_index] + "+00" return timestamp
2a9cd63f1b0a341c3c859d80b538af5ecf56d21d
16,332
def near(array, value): """Find the nearest point within the array and return its index""" idx = (abs(array - value)).argmin() return idx
0e683e8a94a54cd4e53f6d147ca8d4d907ec84c2
16,338
import time def bench_from_sample( distribution, sample, n=1000 ): """Bench the training of a probability distribution.""" tic = time.time() for i in range(n): distribution.summarize( sample ) return time.time() - tic
c9d97badda06a9b5340dc360e1ba7d043a6e2c29
16,339
def packal_username(author): """Format usernames for Packal.""" user = author.lower() user = user.replace(" ", "-") return user
c8f9c5ab67deb95775a787a5cb8cceab67ea73f1
16,341
def _get_all_nearest_neighbors(method, structure): """Get the nearest neighbor list of a structure Args: method (NearNeighbor) - Method used to compute nearest neighbors structure (IStructure) - Structure to study Returns: Output of `method.get_all_nn_info(structure)` """ return method.get_all_nn_info(structure)
5e1e33c7b06951933d8603a75006c6895b742293
16,345
def rolling_average(n, data): """ Function to calculate an n day rolling average given a list of covid data pts @param n: an int representing the number of points to average into the past @param data: a list of dictionaries representing covid data pts @return: the n day death, death increase, infected, and infected increase averages """ # 10 day rolling average data death_total, inc_death_total, inf_total, inc_inf_total = 0,0,0,0 # Get the last n days and add to total counters for i in range(n): curr = data[i] death_total += curr['death'] inc_death_total += curr['deathIncrease'] inf_total += curr['positive'] inc_inf_total += curr['positiveIncrease'] # Divide total counters by n to get n-day average return death_total/n, inc_death_total/n, inf_total/n, inc_inf_total/n
ba02b006176d8b37ed53e5f2cd46c64a92b7dcc2
16,353
def checkPW(md5str: str, USER_PASSWD: str): """检查本地数据库中密码和计算后的密码是否一致 :param md5str: 计算后的密码(字符串) :param USER_PASSWD: 本地的存的密码(字符串) :return: bool """ return md5str == USER_PASSWD
2bbe3864493700ff907b00ff9f82c45723e1a2d7
16,355
def count_letters(word,find): """ Example function with types documented in the docstring. Ce code doit retourner le nombre d'occurences d'un caractère passé en paramètre dans un mot donné également Parameters ---------- param1 : str Le 1er paramètre est une chaine de caractères param2 : char Le 2ème paramètre est un caractère Returns ------- int Nombre d'occurences du caractère Exemples -------- >>> count_letters(abracadabra,a) 5 >>> count_letters(momomotus,u) 1 """ count=0 for i in range(len(word)): if word.find(find,i)!=0: count+=1 return count
327e6b4fd99d03b27473b9620d6147909d0cf6e4
16,357
def one_space(value): """"Removes empty spaces, tabs and new lines from a string and adds a space between words when necessary. Example: >>> from phanterpwa.tools import one_space >>> one_space(" My long \r\n text. \tTabulation, spaces, spaces. ") 'My long text. Tabulation, spaces, spaces.' """ result = "" if isinstance(value, str): value = value.strip() value = value.replace("\n", " ").replace("\t", " ").replace("\r", " ") spl = value.split(" ") result = " ".join([x for x in spl if x]) return result
ff3ce941437186c734bd2815fff9d23ba581bec7
16,360
def small_push_dir(tmpdir): """Create a small pg data directory-alike""" contents = 'abcdefghijlmnopqrstuvwxyz\n' * 10000 push_dir = tmpdir.join('push-from').ensure(dir=True) push_dir.join('arbitrary-file').write(contents) # Construct a symlink a non-existent path. This provoked a crash # at one time. push_dir.join('pg_xlog').mksymlinkto('/tmp/wal-e-test-must-not-exist') # Holy crap, the tar segmentation code relies on the directory # containing files without a common prefix...the first character # of two files must be distinct! push_dir.join('holy-smokes').ensure() return push_dir
6f3fa0f6b291f4d18a8f33624ad55045c45b7261
16,361
def create_cmnd( analysis, sim_start_date, sim_end_date, use_sim_manager, attributes, no_close ): """Create a command string for automatic processing.""" args = [] if use_sim_manager: args.append("UseSimManager") if sim_start_date: args.append(f"SimStartDate {sim_start_date[0]} {sim_start_date[1]}") if sim_end_date: args.append(f"SimEndDate {sim_end_date[0]} {sim_end_date[1]}") if attributes: args.extend([f"ChangeAttributeValue {attr} {val}" for attr, val in attributes]) if no_close: args.extend(["NoClose"]) types = { "eplus": "miGSS", "sbem": "miGCalculate", "dsm": "miGCalculate", # not working } if analysis == "none": # this is used for cases when it's desired # only to update bunch of models pass else: try: args.append(types[analysis]) except KeyError: raise KeyError("Incorrect analysis type: '{}'.".format(analysis)) args.append("miTUpdate") if len(args) == 1: cmnd = "/process=" + args[0] else: cmnd = "/process=" + ", ".join(args) print(f"Running batch using '{cmnd}' command args. ") return cmnd
b95fc466a9c61a125bf09d6fc5dd77bf4575756d
16,365
def SplitCoordinates(xyz_str): """ Function to split coord. str in float list xyz_str: (str) a list input of "x,y,z" coordinates """ xyz = [] for i in range (len(xyz_str)): x_,y_,z_ = xyz_str[i].split(",") xyz.append([float(x_),float(y_),float(z_)]) return(xyz)
808a3c73783d8f36a2ecd70d128fca49fc7f7e1e
16,368
def vectorOFRightDirection(OFvect, FOE): """Returns True if OF vector is pointing away from the FOE, False otherwise.""" # Get points of optical flow vector a1, b1, c1, d1 = OFvect # If left side of FOE if a1 <= FOE[0]: if c1 <= a1: return False # If right side of FOE else: if c1 >= a1: return False return True
febe984f172ffbcf6557bbad0829d52e83c94dd7
16,372
def get_best_model(comparison_result, metric="fmeasure", reverse=False): """ Returns the model row in dataframe which has the best performance on a given metric :param comparison_result: a dataframe containing evaluation info about various models :param metric: metric on which a comparison is be made, defaults to "fmeasure" :return: a dataframe row corresponding to the model which has the best score on the given metric """ if reverse: model_row = comparison_result[ comparison_result[metric] == comparison_result[metric].min() ] else: model_row = comparison_result[ comparison_result[metric] == comparison_result[metric].max() ] return model_row.iloc[0]
fd4deb629386c537b59552528e99ee27391d7aa3
16,374
import re def is_timeline_speed_request(text): """ Returns true if the specified text requests the home timeline speed. """ tlspeed_re = '流速' return not re.search(tlspeed_re, text) is None
9c14ed5f095043dd02aa8fc254a45e702925eeef
16,376
def wprota(self, thxy="", thyz="", thzx="", **kwargs): """Rotates the working plane. APDL Command: WPROTA Parameters ---------- thxy First rotation about the working plane Z axis (positive X toward Y). thyz Second rotation about working plane X axis (positive Y toward Z). thzx Third rotation about working plane Y axis (positive Z toward X). Notes ----- The specified angles (in degrees) are relative to the orientation of the working plane. This command is valid in any processor. """ command = f"WPROTA,{thxy},{thyz},{thzx}" return self.run(command, **kwargs)
ef0dd188ad663d190f85490d9229d28bdb5b3fce
16,379
from typing import List import itertools def generate_combinations(urls: List[str], params: List[dict]) -> List[tuple]: """ Private method to combine urls and parameter dictionaries in tuples to pass to the download method. Args: - urls (List[str]): list of urls - params (List[dict]): list of parameter dictionaries Returns: List[tuple]: list of tuples in the format (url, parameters) """ # assert len(urls) == len(params) return list(itertools.product(urls, params))
4e24e85a49a685c810b3d4089886abac7c785bfb
16,383
from typing import Union from typing import Tuple from typing import List from typing import Any def deep_tuple_to_list(inp: Union[Tuple, List]) -> List[Any]: """Transform a nested tuple to a nested list. Parameters ---------- inp: Union[Tuple, List] The input object. Returns ------- ret: List[Any] The nested list. """ return list(map(deep_tuple_to_list, inp)) if isinstance(inp, (list, tuple)) else inp
770b4f653b734ecd2caf1d6b56ac090e4ffe3208
16,387
from pathlib import Path from typing import Dict import json def make_temporary_features_json( make_temporary_folders_and_files: Path, test_input_json: Dict, test_input_json_filename: str, ) -> Path: """Make a temporary features JSON file.""" # Define the list of folders and filenames for possible removal # Define the file path for the temporary features JSON file, then write its contents temp_json_path = make_temporary_folders_and_files.joinpath(test_input_json_filename) temp_json_path.touch() with open(temp_json_path, "w", encoding="utf-8") as f: json.dump(test_input_json, f) return temp_json_path
5e7274e33d5ca6cda29798c6e80f782129788a9b
16,388
def word16be(data): """return data[0] and data[1] as a 16-bit Big Ended Word""" return (data[1] << 8) | data[0]
4f9c05993980ed95ffdd6fe26389a9025c41f7c9
16,389
def is_latitude_norther_than(lat_a, lat_b): """ Check if lat_a is norther than lat_b """ is_latitude_a_negative = lat_a < 0 is_latitude_b_negative = lat_b < 0 same_sign = is_latitude_a_negative == is_latitude_b_negative if not is_latitude_a_negative and is_latitude_b_negative: return True if is_latitude_a_negative and not is_latitude_b_negative: return False if same_sign: return lat_a > lat_b return lat_a < lat_b
290c0a4f298290bb375170c6748515b7a7218d95
16,392
from typing import Tuple from typing import List def get_metadata(description: str) -> Tuple[str, List[str], str]: """Returns a tuple of (description, tags, category) from a docstring. metadata should be of the form key: value, e.g. category: Category Name""" tags: List[str] = [] category: str = "" lines: List[str] = description.split("\n") description_trimmed: List[str] = [] for index, line in enumerate(lines): line_stripped: str = line.strip().lower() if line_stripped.startswith("tags:"): tags = line[line.find(":") + 1 :].split(",") tags = list(map(lambda t: t.strip(), tags)) continue elif line_stripped.startswith("category:"): category = line[line.find(":") + 1 :].strip() continue else: description_trimmed.append(line) return "\n".join(description_trimmed), tags, category
21e28d7a3c802d2513f2bf8eaeccc215070a2e24
16,394
def get_repo_dicts(r): """Return a set of dicts representing the most popular repositories.""" response_dict = r.json() repo_dicts = response_dict['items'] return repo_dicts
822a0dc0674b2eda5210fdd88257d894c3dc902c
16,398
def _partition(array, low, high): """Choose the first element of `array`, put to the left of it all elements which are smaller, and to the right all elements which are bigger than it. Return the final position of this element. """ if low >= high: return i = low + 1 j = high while i <= j: if array[i] <= array[low]: i += 1 else: array[i], array[j] = array[j], array[i] j -= 1 array[low], array[j] = array[j], array[low] return j
89f23c2e0c14c9a516e8b895e888936773fbfe94
16,400
def db_to_power(decibel): """ Returns power value from a decibel value. """ return 10**(decibel/10)
5188d8d646f2421546cf894ad45d2bdd30d97e53
16,402
def _get_rid_for_name(entries, name): """Get the rid of the entry with the given name.""" for entry in entries.values(): if entry['name'] == name: return entry['rid'] raise ValueError(u'No entry with name {} found in entries {}'.format(name, entries))
0791f3185404ca59417fd9196467c8aef69c429c
16,404