content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import List import hashlib def hashes() -> List[str]: """ Return a list of available hashing algorithms. :rtype: list of strings """ t = [] if 'md5' in dir(hashlib): t = ['MD5'] if 'md2' in dir(hashlib): t += ['MD2'] hashes = ['SHA-' + h[3:] for h in dir(hashlib) if h.startswith('sha')] return t + hashes
4077694caa1200e923821515a3ec77e720fe755c
37,096
from math import sqrt, ceil def grid_shape(i, max_x=4): """Return a good grid shape, in x,y, for a number if items i""" x = round(sqrt(i)) if x > max_x: x = max_x y = ceil(i / x) return x, y
e0f5109dc410f2dae632e002600e1c0094585b29
37,097
def scene_element_slicer(r_i, c_i, scene_element_position_dict, scene_element_dimension, as_slice=False): """ Returns the starting and ending row and column indices needed to slice pixels from a scene element. Parameters ---------- r_i Scene element row c_i Scene element column scene_element_position_dict Lookup table scene_element_dimension Size of scene element as_slice Whether to return as an actual slice, or just the start/end indices Returns ------- row, col slices """ dx = scene_element_dimension // 2 row, col = scene_element_position_dict[r_i, c_i] r1, r2 = int(row) - dx, int(row) + dx + 1 c1, c2 = int(col) - dx, int(col) + dx + 1 if as_slice: return slice(r1, r2), slice(c1, c2) else: return r1, r2, c1, c2
0dfa1611eb56865507e6be78dd5a31b72c95d7a7
37,100
def psfScale(D, wavelength, pixSize): """ Return the PSF scale appropriate for the required pixel size, wavelength and telescope diameter The aperture is padded by this amount; resultant pix scale is lambda/D/psf_scale, so for instance full frame 256 pix for 3.5 m at 532 nm is 256*5.32e-7/3.5/3 = 2.67 arcsec for psf_scale = 3 Args: D (real): telescope diameter in m wavelength (real): wavelength in Angstrom pixSize (real): pixel size in arcsec Returns: real: psf scale """ DInCm = D * 100.0 wavelengthInCm = wavelength * 1e-8 return 206265.0 * wavelengthInCm / (DInCm * pixSize)
cbd98743f8716bfe935daeaa0a11f87daeb873f3
37,105
def _render_namespace_prefix(namespace): """Returns namespace rendered as a prefix, like ::foo::bar::baz.""" return "".join(["::" + n for n in namespace])
68e20189cdfd47872b9e9db34451da15b036d280
37,107
from typing import FrozenSet import dateutil def get_known_timezones() -> FrozenSet[str]: """ Return a cached set of the known timezones. This actually pulls its list from the internal database inside `dateutil` as there doesn't seem to be a nice way to pull the data from the system. These are expected to change sufficiently infrequently that this is ok. In any case, `dateutil` falls back to using this data source anyway, so at worst this is a strict subset of the available timezones. """ # Get a non-cached copy of the `ZoneInfoFile`, not because we care about # the cache being out of date, but so that we're not stuck with a MB of # redundant memory usage. # ignore types because `dateutil.zoneinfo` isn't present in the typeshed info = dateutil.zoneinfo.ZoneInfoFile( # type: ignore dateutil.zoneinfo.getzoneinfofile_stream(), # type: ignore ) return frozenset(info.zones.keys())
ad149814bf72ea8dd13eebd9c0affc4eabf90c76
37,110
def _checkNconvertStr(texts): """ Checks whether input is a string or if it can be casted into one :param texts: A string or a type which can be converted into one :return: Text as a string if successful otherwise nothing (exception) """ concatTextLst = [] for text in texts: # Test texts elements tempText = str(text) if type(tempText) is not str: raise TypeError("Input type must be a string or convertible into a string") concatTextLst.append(str(text)) return " ".join(concatTextLst) # Preserve whitespaces when using multiple text elements
430157ecf0f404f77fef497c39d4b0525b1b4f71
37,113
from typing import List from typing import Any def getListDifference(listOne: List[Any], listTwo: List[Any]) -> List[Any]: """ Return difference (items that are unique just to a one of given lists) of a given lists. Note: Operation does not necessary maintain items order! Args: listOne: first list to compare. listTwo: second list to compare. """ difference = list(set(listOne).symmetric_difference(set(listTwo))) return difference
5839988761a8f242828c8526d75e2b7ea8aea2f3
37,114
def _get(isamAppliance, id): """ Internal function to get data using "id" - used to avoid extra calls :param isamAppliance: :param id: :return: """ return isamAppliance.invoke_get("Retrieve a specific mapping rule", "/iam/access/v8/mapping-rules/{0}".format(id))
fbaccf5cf8a0b1b8f4be12e07d0ac2bf7dd20463
37,118
from typing import Iterable def dedupe(iterable: Iterable) -> Iterable: """ Removes duplicates. In python 3.6+, this algorithm preserves order of the underlying iterable. """ return iter(dict.fromkeys(iterable))
67c46849b279a1423f81aaa64e0e2d80c4900aa5
37,119
import time def create_export_file(converted_posts): """ Create a Ghost import json from a list of Ghost post documents. :param converted_posts: Ghost formatted python docs. :return: A Dict representation of a ghost export file you can dump to json. """ return { "db": [ { "meta": { "exported_on": int(time.time()), "version": "2.18.3" }, "data": { "posts": converted_posts } } ] }
e0ee20a9b61ea6e86e3efb96fbe95085a2a9b2d0
37,124
def get_prots(docked_prot_file): """ gets list of all protein, target ligands, and starting ligands in the index file :param docked_prot_file: (string) file listing proteins to process :return: process (list) list of all protein, target ligands, and starting ligands to process """ process = [] with open(docked_prot_file) as fp: for line in fp: if line[0] == '#': continue protein, target, start = line.strip().split() process.append((protein, target, start)) return process
17b31a045004d19f5b79345cb53eded38df1a8e5
37,126
from pathlib import Path def relative_to(path: Path, root: Path) -> Path: """Returns a path to `path` relative to `root` Postcondition: (root / relative_to(path, root)).resolve() = path.resolve() """ while True: try: return path.relative_to(root) except ValueError: return ".." / relative_to(path, (root / "..").resolve())
5a1091ba87d45917302778b4cee8b30a6d9f6bf9
37,127
def strip_quotes(arg): """ Strip outer quotes from a string. Applies to both single and double quotes. :param arg: str - string to strip outer quotes from :return str - same string with potentially outer quotes stripped """ quote_chars = '"' + "'" if len(arg) > 1 and arg[0] == arg[-1] and arg[0] in quote_chars: arg = arg[1:-1] return arg
97c8cefe2d0de2b3cecb8b6ed94a40ce4be89b94
37,134
import math def BytesPerRowBMP(width, bpp): """Computes the number of bytes per row in a Windows BMP image.""" # width * bpp / 8, rounded up to the nearest multiple of 4. return int(math.ceil(width * bpp / 32.0)) * 4
72f0df2951a27905bbf5b612d3f328696b6434f4
37,135
def str_to_bool(str_): """Convert string to bool.""" if str_ == "True": return True elif str_ == "False": return False else: raise TypeError(str_)
929a2fe459e43751a90f1bd918ef6447eb2b68c2
37,137
def generate_name(route, deployment): """ Generate the name for a route in a given deployment :param route: the id of the route :param deployment: the id of the route :return: the unique name for the route """ return f"{route}_{deployment}"
4f957cea79e5dc05af7cef5a490a56c2690c09ed
37,138
def limit(val: int) -> int: """ = min(max(val, 0), 255) """ tmp = 255 if val>255 else val return 0 if tmp<0 else tmp
d69f236f4635d1a91a253dfe614e8a786c08753d
37,147
import itertools def normalize_padding(padding, rank): """ normalized format of padding should have length equal to rank+2 And the order should follow the order of dimension ex. Conv2d (rank=2) it's normalized format length:2+2 ==>(left, right,top bottom) Args: padding (None, int, tuple): rank (int): Returns: the normalized format of padding Examples: >>> normalize_padding(((1,0),(1,0)),2) (1, 0, 1, 0) >>> normalize_padding((1,0),2) (0, 0, 1, 1) """ if padding is None: padding = (0,) * (2 * rank) elif isinstance(padding, int): padding = (padding,) * (2 * rank) elif isinstance(padding, (list, tuple)) and len(padding) == 1: padding = padding * (2 * rank) elif isinstance(padding, (list, tuple)) and len(padding) == rank and isinstance(padding[0], int): # rank=2 (1,1)=>(1,1,1,1) (1,0)=>(0,0,1,1) reversed_padding = list(padding) reversed_padding.reverse() return_padding = [] for i in range(rank): return_padding.append(reversed_padding[i]) return_padding.append(reversed_padding[i]) padding = tuple(return_padding) elif isinstance(padding, (list, tuple)) and len(padding) == rank and isinstance(padding[0], (list, tuple)): # rank=2 ((1,0),(1,0)=>(1,0,1,0) padding = tuple(list(itertools.chain(*list(padding)))) elif isinstance(padding, (list, tuple)) and len(padding) == 2 * rank and isinstance(padding[0], int): padding = padding return padding
6e67d1a7ff408c013fe7fc122a0b0320025e2373
37,154
import string import secrets def get_alphanumeric_unique_tag(tag_length: int) -> str: """Generates a random alphanumeric string (a-z0-9) of a specified length""" if tag_length < 1: raise ValueError("Unique tag length should be 1 or greater.") use_chars = string.ascii_lowercase + string.digits short_id = "".join([secrets.choice(use_chars) for i in range(tag_length)]) return short_id
098c9888790faf6b771062e13a31f5e8f6eba4e0
37,156
from typing import Any from typing import TypeGuard import numbers def is_complex(x: Any) -> TypeGuard[complex]: """Return true if x is complex.""" return isinstance(x, numbers.Complex)
fc1c98d9d8074ce5ffc1729a44d4daf463052e69
37,157
def is_obj(x): """ A quick (but maybe not perfect) check for object types Returns: bool: True if the object has __dict__ attribute, otherwise False """ try: getattr(x, '__dict__') return True except: return False
324dccfd2d2c436940e5347055ec1b5aa5f021c0
37,158
from typing import Any from typing import Callable def verify_operands_classes_and_forward_to_callable( x_operand: Any, y_operand: Any, operand_class: type, function: Callable[[Any, Any], Any], ) -> Any: """ verify_operands_classes_and_forward_to_callable verifies both operands are of type operand_class before calling function. :param x_operand: First operand. :type x_operand: Any :param y_operand: Second operand. :type y_operand: Any :param operand_class: type to compare against. :type operand_class: type :param function: callable to call. :type function: Callable[[Any, Any], Any] :raises TypeError: if either operand is not of operand_class. :return: The return value of the callable, in any. :rtype: Any """ if isinstance(x_operand, operand_class) and isinstance(y_operand, operand_class): return function(x_operand, y_operand) raise TypeError("x_operand and y_operand are not both ", operand_class)
8553b0ae796641226724cc9b0557b59dfe7a8fbf
37,161
from typing import List def staircase(size: int) -> List[str]: """ >>> staircase(4) [' #', ' ##', ' ###', '####'] """ # ret = [f"{'#' * i:>{size}}" for i in range(1, size+1)] ret = [('#' * i).rjust(size) for i in range(1, size+1)] return ret
e75508019be90223a49aa5161876e34018b387e5
37,165
from pathlib import Path def load_groups(input_path: Path) -> list: """ Load in the customs quesetionarre response data into a buffer and group together the responses that are associated with a single group. Responses belonging to a single group are on contiguous lines, and groups are separated by a blank line. Splitting by "\n\n" will break apart the responses from separate groups, and then removing the "\n" characters from in-group responses should then just give us the specific responses void of whitespace characters. Remove empty characters per line and also empty groups. Args: input_path [pathlib.Path]: path to input data Returns: list of lists: [ [group-responses] ] """ with open(input_path, "r") as infile: groups = list( filter( None, [ list( filter( None, [line.strip() for line in group.split("\n") if line != ""], ) ) for group in infile.read().split("\n\n") ], ) ) return groups
f23eb0398757e749786a7ba1fdcb8dede18736fd
37,170
def get_trip_distance(distances_matrix, path): """ :param distances_matrix: Matrix of distances between cities :param path: List of city indices :return: Trip distance """ distance = 0 for index in range(len(path))[1:]: distance += distances_matrix[path[index - 1], path[index]] return distance
aabb74cb8b876911e384eceb86c33f4114327fb2
37,175
def gift_list(number): """Generates the list of gifts for a given verse Parameters ---------- number: Integer The number of the verse we want the list for Returns ------- string The list of gifts """ gifts = { 1: 'a Partridge in a Pear Tree', 2: 'two Turtle Doves', 3: 'three French Hens', 4: 'four Calling Birds', 5: 'five Gold Rings', 6: 'six Geese-a-Laying', 7: 'seven Swans-a-Swimming', 8: 'eight Maids-a-Milking', 9: 'nine Ladies Dancing', 10: 'ten Lords-a-Leaping', 11: 'eleven Pipers Piping', 12: 'twelve Drummers Drumming' } return gifts[1] if number == 1 \ else ', '.join([gifts[n] for n in reversed(range(2, number+1))]) + \ f', and {gifts[1]}'
20c9cf10f80e8ee0650721253b31554ed0cda6a4
37,179
def get_adjusted_unsuccessful(row, outcome_col, num_unsuccess_col): """ Returns adjusted number of unsuccesful contacts given column of outcome and num_unsuccess """ outcome = row[outcome_col] num_unsuccess = row[num_unsuccess_col] if outcome == 0: adj_num_unsuccess = num_unsuccess - 3 if num_unsuccess >= 3 else 0 else: adj_num_unsuccess = num_unsuccess return adj_num_unsuccess
77f0b0d46269bfe299d8791c04a152a1d2df27ed
37,180
def triangular_force(t_start, t_max, t_end, f_max): """ Returns a triangular force: f_max at t_max /\ / \ / \ / \ ---- ----- | | | |__ t_end |__ t_start Parameters ---------- t_start: float time where triangular force starts to raise t_max: float time where force reaches maximum t_end: float time where force is gone to zero again f_max: float maximum value of force Returns ------- f: callable function f(t) """ def f(t): if t_start < t <= t_max: return f_max * (t-t_start) / (t_max-t_start) elif t_max < t < t_end: return f_max * (1.0 - (t - t_max) / (t_end - t_max)) else: return 0.0 return f
91a69292b9ff641a9b47c280438f64c13ba89bc9
37,181
from datetime import datetime def FormattedTime(DateTimeObject = None) -> str: """Returns a formatted time string.""" if DateTimeObject == None: DateTimeObject = datetime.now() return DateTimeObject.strftime("%H:%M:%S")
51d431e40691371579530419aebd19de4655455c
37,185
import re import click def parse_port(port: str) -> str: """Check if port is valid. Parameters ---------- port : str Possible port name. Returns ------- port : str Valid port name Raises ------ click.BadParameter If ``port`` is not a four-digit number not starting with zero. """ if re.fullmatch(r'^[1-9][0-9]{,3}', port): return port else: raise click.BadParameter( 'ERROR: Use up to four digits not starting with zero.')
e6acb439117f0d30ec161875371aa7e7b9f10c76
37,187
def get_nlp_bib_neotoma(nlp_sentences, bibliography, neotoma_summary): """ Uses all main datasets to create preprocessed_df dataframe Parameters ---------- nlp_sentences : pd.DataFrame pd.DataFrame with all NLP Sentences database information bibliography : pd.DataFrame pd.DataFrame with all Bibliography database information neotoma_summary : pd.DataFrame pd.DataFrame with all neotoma_summary database information Returns ------- nlp_bib : pd.DataFrame pd.DataFrame with summarized merged nlp sentences and bibliography information preprocessed_df : pd.DataFrame pd.DataFrame with summarized NLP, Bibliography and Neotoma database information """ nlp_bib = nlp_sentences.merge(bibliography, on='gddid') preprocessed_df = nlp_bib.merge(neotoma_summary, on='doi') return nlp_bib, preprocessed_df
0c706502b79de5e10736192dfd6e6aa05593e61d
37,196
def find_link_joints(model, link_name): """Find the joints attached to a given link Parameters ---------- model : <ModelSDF> SDF model link_name : <str> Name of the link in the sdf Returns ------- out : <tuple> Tuple of joint names attached to the link """ return tuple([ joint.name for joint in model.joints if joint.parent == link_name ])
1d09cdf09889e19b7d8b911686ce90765d772a1c
37,203
def polyfill_filename(api): """Gets the filename associated with an API polyfill. Args: api: String name of API. Returns: Filename of API polyfill. """ return "{}.polyfill.js".format(api)
efb54fddafb846985c77e44837f7a24c57596581
37,204
def standardize_survey_list(row): """This function takes in a list for a given row of a survey result and will lower-case it and strip out white space from left and right of the string. Args: row (list): A list of survey results Returns: list: standardized survey results """ # lowers all strings and strips whitespace clean_row = [x.lower().strip() for x in row] return list(set(clean_row))
cf1e627e25a1dc98d8748a8bc1e0b78e420eb043
37,205
def make_ucsc_chr(interval): """ Converts interval from ENSEMBL chroms to UCSC chroms (appends str to each chrom) """ interval.chrom = "chr" + interval.chrom return interval
d5878670494dc51e29922d43a605634f26cd8e00
37,207
from typing import Any def verbatim(text: Any) -> str: """ Returns the main string argument as-is. It produces a TypeError if input text is not a string. """ if not isinstance(text, str): raise TypeError("argument to verbatim must be string") return text
0f735833f1514f0f5bd45efc07af783ffc72cbd3
37,210
def format_bool(value): """Converts boolean to yes/no string.""" return 'bez dat' if value is None else ('Ano' if value else 'Ne')
04aa58c8d280bc90c52169bf563650075963d6a2
37,211
def get_mappings(all_tweets_itr): """Returns a tuple with two dictionaries. The first is a mapping username -> userid, where username is the one @foo, with @. The second is a mapping tweetid -> userid of the creator""" map_usrname_usrid = {} map_twtid_usrid = {} print(" [*] Extracting user mappings") for tweet in all_tweets_itr: map_usrname_usrid["@"+tweet["user"]["screen_name"]] = tweet["user"]["id"] map_twtid_usrid[tweet["id"]] = tweet["user"]["id"] return map_usrname_usrid, map_twtid_usrid
7794676f45a9610b48e569c2c115faa04dc48904
37,214
def get_message_source_from_event(event): """ Helper function to get the message source from an EventHub message """ return event.message.annotations["iothub-message-source".encode()].decode()
37d8c0aa2304f930c8e1507bf5a2355e3ccb66e9
37,215
def recover_bps(delt, bps, bps_star): """ delt, bps, bps_star - seqlen+1 x bsz x K returns: bsz-length list of lists with (start_idx, end_idx, label) entries """ seqlenp1, bsz, K = delt.size() seqlen = seqlenp1 - 1 seqs = [] for b in range(bsz): seq = [] _, last_lab = delt[seqlen][b].max(0) last_lab = last_lab.item() curr_idx = seqlen # 1-indexed while True: last_len = bps[curr_idx][b][last_lab] last_len = int(last_len) seq.append((curr_idx-last_len, curr_idx, last_lab)) # start_idx, end_idx, label, 0-idxd # print((curr_idx-last_len, curr_idx, last_lab)) curr_idx -= last_len if curr_idx == 0: break last_lab = bps_star[curr_idx][b][last_lab] seqs.append(seq[::-1]) return seqs
1f0adca5aa25ae818b8738ef0bfefb0a6f44fe6c
37,220
def _ops_equal(op1, op2): """Checks if two operators are equal up to class, data, hyperparameters, and wires""" return ( op1.__class__ is op2.__class__ and (op1.data == op2.data) and (op1.hyperparameters == op2.hyperparameters) and (op1.wires == op2.wires) )
dd73cc9f89ec0fc8540043b7982a6c5b6fc8609b
37,222
import requests def extract_wiki_text(wikipedia_title, language='en'): """Get the text of the given wikipedia article.""" base_url = ('https://' + language + '.wikipedia.org/w/api.php?action=query' + '&prop=extracts&format=json&explaintext=' + '&exsectionformat=plain&titles=') text = '' r = requests.get(base_url + wikipedia_title) if r.status_code == 200: pages = r.json()['query']['pages'] for (id, page) in pages.items(): text += page['extract'] return text
231bfec347c0a92b19081bb852feb3b6c7674413
37,225
from typing import Dict from typing import Any import torch def load_to_cpu(path: str) -> Dict[str, Any]: """ This is just fairseq's utils.load_checkpoint_to_cpu(), except we don't try to upgrade the state dict for backward compatibility - to make cases where we only care about loading the model params easier to unit test. """ state = torch.load( path, map_location=( lambda s, _: torch.serialization.default_restore_location(s, "cpu") ), ) return state
aa30621b7230a3f22afbfd3db50f74d8f385493a
37,226
def bootstrap_predictions(train_x, train_y, test_x, model, boot_idx=None, permute_idx=None): """ fits a model to training data and predicts output using test data. features are selected with boot_idx. Optional permutation of rows for significant testing. train_x, test_x: dataframes containing train and test data train_y: target value for model fitting model: sklearn regressor object, or Pipeline boot_idx: features to use for model permute_idx: permutation index to shuffle training data returns: pred: bootstrapped predictions of test data """ # fit model with bootstrapped genes if boot_idx is None: if permute_idx is None: model.fit(train_x, train_y) else: model.fit(train_x.iloc[permute_idx,:], train_y) pred = model.predict(test_x) else: if permute_idx is None: model.fit(train_x.iloc[:,boot_idx], train_y) pred = model.predict(test_x.iloc[:,boot_idx]) else: model.fit(train_x.iloc[permute_idx,boot_idx], train_y) pred = model.predict(test_x.iloc[:,boot_idx]) return pred
dbe328094a2eda06a048f0d3cdcee182e8558db2
37,232
def bag_of_words(text): """Returns bag-of-words representation of the input text. Args: text: A string containing the text. Returns: A dictionary of strings to integers. """ bag = {} for word in text.lower().split(): bag[word] = bag.get(word, 0) + 1 return bag
75993f3bd5fb20e3015afee499a14bf1574902ca
37,234
def find_list_string(name, str_list, case_sensitive=True, as_prefix=False, first_matched=False): """ Find `name` in the string list. Comparison parameters are defined in :func:`string_equal`. If ``first_matched==True``, stop at the first match; otherwise if multiple occurrences happen, raise :exc:`ValueError`. Returns: tuple ``(index, value)``. """ if not case_sensitive: lookup_name=name.lower() else: lookup_name=name found_name=None for i,s in enumerate(str_list): if not case_sensitive: lookup_s=s.lower() else: lookup_s=s if as_prefix: sat=lookup_s.startswith(lookup_name) else: sat=(lookup_s==lookup_name) if sat: if found_name is None: found_name=(i,s) if first_matched: break else: raise ValueError("{0} and {1} both satisfy name {2}".format(found_name[1],s,name)) if found_name is None: raise KeyError("can't find name in the container: {0}".format(name)) return found_name
f485ae3cdebcee9e4cfe85378c38f7f27d737b96
37,236
def rmRTs(tokens) : """Remove RTs""" return [x for x in tokens if x != "rt"]
00df94bcfba29784bae736bb41c964cea7589657
37,237
def test_attr(attr, typ, name): """Tests attribute. This function tests if the attribute ``attr`` belongs to the type ``typ``, if not it gives an error message informing the name of the variable. """ try: return typ(attr) except: raise TypeError('"{}" keyword must be a {} object'.format(name, typ))
28e0bdad00117cca25a67057db2f1525387cf39d
37,241
def get_phylogenetic_weight(node): """Calculate the weight at a phylogenetic node. Args: node (`Node`): The phylogenetic node. Returns: float: (weight of the parent) / (number of siblings + 1). """ if node.parent is None: return 1.0 return 1.0*get_phylogenetic_weight(node.parent)/len(node.parent.children)
2a57eb9cac2f5939d13552ea1e99e8dc99313db9
37,242
import json def create_button(action, payload, label, display_mode='popup', disabled=False): """ This function creates an HTML button the user can interact with from a CloudWatch custom widget. Parameters: action (string): The ARN of a lambda function to call when clicking on this button payload (string): A JSON formatted string that will be passed as argument to the lambda function used as endpoint for this button label (string): The label to use on the button display_mode (string): Can either be `popup` (display the result in a popup) or `widget` (to replace the content of the current widget by the output of the Lambda function used as endpoint). Defaults to `popup` disabled (boolean): Set to True to display a disabled button Returns: string: an HTML string with the button to display """ if disabled: button_style = 'awsui-button-disabled' disabled = 'disabled=""' else: button_style = 'awsui-button awsui-button-variant-primary' disabled = "" button = ( f'<a class="btn {button_style}" {disabled}>{label}</a>\n' '<cwdb-action ' f'action="call" ' f'endpoint="{action}" ' f'display="{display_mode}">' f'{json.dumps(payload)}' '</cwdb-action>\n' ) return button
33d7255888b956275e9783ee91c297b81fdc6ae7
37,246
def order_validation(order): """ Validate the order. If it's under 2 then raise a ValueError """ if order < 2: raise ValueError("An order lower than two is not allowed.") else: return order
ee9f9c64c30a9625246d5e139c94a53d144270db
37,247
import requests import io import zipfile def download_zip(url, to_path): """Download zipfile from url and extract it to to_path. Returns the path of extraction. """ filename = url.split('/')[-1] r = requests.get(url) r.raise_for_status() content = io.BytesIO(r.content) with zipfile.ZipFile(content) as z: z.extractall(to_path) return to_path
904a4a0082040ec40e09f8cac8275c36943a3acc
37,251
def to_gib(bytes, factor=2**30, suffix="GiB"): """ Convert a number of bytes to Gibibytes Ex : 1073741824 bytes = 1073741824/2**30 = 1GiB """ return "%0.2f%s" % (bytes / factor, suffix)
1006d69275c212d978b06ab248f02ea966f1490e
37,255
def fn_middleware(get_response): """Function factory middleware.""" def mw(request): response = get_response(request) return response return mw
e4261f99c2acd939dfb6198f1e253a680c2d9184
37,258
def include_key_in_value_list(dictio): """ Returns a list that contains the cases in the log, starting from the dictionary returned by PM4Py Parameters --------------- dictio Dictionary of cases Returns --------------- list_cases List of cases """ ret = [] for key in dictio: val = dictio[key] val["caseId"] = key ret.append(val) return ret
917cf7a280daad5372ff9ac312d96dc46fdcc5e6
37,259
def var_number(i, j, d, k): """ Convert possible values into propositional vars :param i: row number 1 - 9 :param j: col number 1 - 9 :param d: digit 1 - 9 :param k: size of suduko :return: variable number 1- 729 """ return (k ** 2 * k ** 2) * (i - 1) + (k ** 2) * (j - 1) + d
676bd8c4e67466926b21542bad96c9864ca6da2c
37,261
import pickle def load(input_filename): """unpickle an object from a file""" with open(input_filename, "rb") as input_file: res = pickle.load(input_file) return res
7401114353e671fa52a035159dd564882b771bc3
37,266
def s3_object_exists(s3): """Provide a function to verify that a particular object exists in an expected bucket.""" def check(bucket_name, key): bucket_names = [ bucket_info["Name"] for bucket_info in s3.list_buckets()["Buckets"] ] if not bucket_names: return False object_names = [ contents["Key"] for contents in s3.list_objects(Bucket=bucket_name)["Contents"] ] return key in object_names return check
a0f549de4b2acc3fbbc4077d31f4feca9eec5cae
37,272
def binary(i, width): """ >>> binary(0, 5) [0, 0, 0, 0, 0] >>> binary(15, 4) [1, 1, 1, 1] >>> binary(14, 4) [1, 1, 1, 0] """ bs = bin(i)[2:] bs = ("0" * width + bs)[-width:] b = [int(c) for c in bs] return b
0a9ee440d14cc0fccc8b3d7c83c36582a4583749
37,280
def price_index(price_of_product_x, price_of_product_y): """Return the price index of product X over product Y. Args: price_of_product_x (float): Price of product X. price_of_product_y (float): Price of product Y. Returns: price_index (float): Price of X / Price of Y """ return (price_of_product_x / price_of_product_y) * 100
e3f6eeec3395cf039e037eca97bca5e1b7eb55ca
37,281
def kelvin_to_level(kelvin): """Convert kelvin temperature to a USAI level.""" if kelvin < 2200: return 0 if kelvin > 6000: return 100.0 return (kelvin-2200)/(6000-2200) * 100
993cce9c7b85dea718a0eb21fd1e20a088a403f9
37,286
def hexinv(hexstring): """ Convenience function to calculate the inverse color (opposite on the color wheel). e.g.: hexinv('#FF0000') = '#00FFFF' Parameters ---------- hexstring : str Hexadecimal string such as '#FF0000' Returns ------- str Hexadecimal string such as '#00FFFF' """ if hexstring[0]=='#': hexstring=hexstring.lstrip('#') hexcolor=int(hexstring,16) color_comp=0xFFFFFF^hexcolor hexcolor_comp="#%06X"%color_comp return hexcolor_comp
a38f1bc031ddc7f15fa462c32de4af93fa42a6c3
37,290
def has_changes(statements): """ See if a list of SQL statements has any lines that are not just comments """ for stmt in statements: if not stmt.startswith('--') and not stmt.startswith('\n\n--'): return True return False
d357443e34a575af2cb1827064fa372668097895
37,296
def disconnect(signal, slot): """Disconnect a Qt signal from a slot. This method augments Qt's Signal.disconnect(): * Return bool indicating whether disconnection was successful, rather than raising an exception * Attempt to disconnect prior versions of the slot when using pg.reload """ try: signal.disconnect(slot) return True except (TypeError, RuntimeError): return False
6aee43431c153a48111f21541448009496f27dd3
37,297
from typing import Dict from typing import List from typing import Optional import queue def find_node_distance( i: int, vertex_connections: Dict[int, List[int]], target: Optional[int] = None ): """ Finds the distances from one node to all others. Args: i: starting vertex idx vertex_connections: expects the vertices to be in a range starting from zero. target: Returns: distance between vertex i and target, if target is not None. Otherwise the distance to every other node. """ # visited[n] for keeping track of visited node in BFS visited = [False] * len(vertex_connections.keys()) # Initialize distances as 0 distance = [0] * len(vertex_connections.keys()) # queue to do BFS queue_: queue.Queue = queue.Queue() distance[i] = 0 queue_.put(i) visited[i] = True while not queue_.empty(): x = queue_.get() for i in range(len(vertex_connections[x])): if visited[vertex_connections[x][i]]: continue # update distance for i distance[vertex_connections[x][i]] = distance[x] + 1 queue_.put(vertex_connections[x][i]) visited[vertex_connections[x][i]] = True if target is not None: return distance[target] else: return distance
38f68e536d1863e1f00d5b429ce1ba359ff65977
37,301
import _warnings def discard_short_fixations(fixation_sequence, threshold=50): """ Deprecated in 0.4. Use `eyekit.fixation.FixationSequence.discard_short_fixations()`. """ _warnings.warn( "eyekit.tools.discard_short_fixations() is deprecated, use FixationSequence.discard_short_fixations() instead", FutureWarning, ) return fixation_sequence.discard_short_fixations(threshold)
dfd09cc1db421e480e569d94caf479c4d496906b
37,304
def sort_notes_into_folders(notes, folders): """ sorts notes into a dictionary with the folder names as the key :param notes: A list of notes objects :param folders: a list of tuples with each tuple holding (folder_id, folder_name) :return: a dictionary with all the notes, sorted into their folders as well as a all key which stores all the notes Note 1: the values in the keys is a list of note objects that is correlated to the folder name Eg. { 'test_folder': [Note_obj_1, Note_obj_2, ...], 'all': [all_note_objs] } """ # so that when the note gets appended to the dictionary, it will already be sorted notes.sort(key=lambda note: note.last_edited, reverse=True) folders = dict(folders) notes_sorted_by_folders = {'All':[]} # to store all the folder_names even when it has no notes for folder_id in folders: folder_name = folders[folder_id] notes_sorted_by_folders.setdefault(folder_name, []) for note in notes: if note.parent_folder_id != 0: # note has a folder folder_name = folders[str(note.parent_folder_id)] notes_sorted_by_folders[folder_name].append(note) notes_sorted_by_folders['All'].append(note) return notes_sorted_by_folders
fb4d788e59b2796c6a01a0b9ad132f44bb1693c1
37,305
def get_url(post): """ Gets the url of the actual JPG file from the post object. """ url = post['data']['url'] if url.endswith == 'jpg': return url elif url.endswith == '/': return url.strip('/') + '.jpg' else: return url + '.jpg'
f4a953a1602e80fff50e0e2730f4976ffb79ff78
37,308
def cleanString(s): """converts a string with leading and trailing and intermittent whitespace into a string that is stripped and has only single spaces between words >>> cleanString('foo bar') u'foo bar' >>> cleanString('foo bar') u'foo bar' >>> cleanString('\\n foo \\n\\n bar ') u'foo bar' >>> cleanString('') u'' """ return ' '.join(map(lambda x: x.strip(), s.split()))
5a816b6bb0b93e869b2ce144cf8aaed305c0e9e8
37,310
def get_short_name(full_path): """ Returns the short name of an operation or service, without the full path to it. """ return full_path.rsplit('/')[-1]
820a2e8444cecbd7f164563ecd8887dc122bd126
37,315
from typing import Any from typing import OrderedDict def getvalue(object: Any, key: Any) -> Any: """Access a dict or class instance attribute value in a unified way""" if type(object) == dict or type(object) == OrderedDict: # Dict or OrderedDict return object.get(key) else: # Class instance if hasattr(object, key): return getattr(object, key) else: return None
e9e278c184771efa3505d266b6b7f2b50a8217f0
37,316
def parse_test_id(test_id): """ Parse a test ID into useful parts. Takes a test ID and parses out useful parts of it:: > parse_test_id('foo.bar.baz.test_mod.MyTestClass.test_method') { 'scope': 'foo', 'type': 'bar', 'accreditation': 'baz', 'file': 'test_mod', 'class': 'MyTestClass', 'method': 'test_method', 'class_path': 'foo.bar.baz.test_mod.MyTestClass.test_method' } Note: scope/type/accreditation might not be returned if your path structure is different from the suggested one. """ parts = test_id.split('.') full_path = len(parts) == 6 return { 'scope': full_path and parts[0], 'type': full_path and parts[1], 'accreditation': full_path and parts[2], 'file': parts[-3], 'class': parts[-2], 'method': parts[-1], 'class_path': '.'.join(parts[0:-1]) }
facd326fb5e31b72369fa1fc0dc17506ce128af1
37,322
def parse_cellType(file_name): """ Parsing file_name and extracting cell-type input file must be EXPERIMENT_AREA_CELL-TYPE.bam so bamtools create EXPERIMENT_AREA_CELL-TYPE.REF_chrN.PEAK :param file_name: :return: cell_type """ parse = file_name.split('.')[0].rsplit('_') return parse[len(parse)-1]
872886d5f267452b105794e6befc9c88946350b0
37,325
def point_num_to_text(num_fita): """ Transform point's order number into text """ num_fita = int(num_fita) num_fita_str = str(num_fita) if len(num_fita_str) == 1: num_fita_txt = "00" + num_fita_str elif len(num_fita_str) == 2: num_fita_txt = "0" + num_fita_str else: num_fita_txt = num_fita_str return num_fita_txt
5042a7c200c4987748f825213f08788b44b091c1
37,326
def merge_dictionaries(dictionaries): """ Merge a sequence of dictionaries safely. This function merges dictionaries together, but ensures that there are not same keys which point to different values. That is, merge_dictionaries({'alpha':True}, {'alpha':True}) is OK, but merge_dictionaries({'alpha':True}, {'alpha':False}) will raise an exception """ res = {} for dct in dictionaries: for (k, v) in dct.iteritems(): if k in res: assert res[k] == v res[k] = v return res
b536f68d79e1e55d2d1fa8f2ed4e26c5452003ad
37,327
import asyncio async def my_task(seconds): """ A task to do for a number of seconds """ print('This task is taking {} seconds to complete'.format(seconds)) await asyncio.sleep(seconds) return 'task finished'
25decc9efbbd47a99cfe698a5565a689f9cc5a00
37,331
def hash_to_dir(hash): """ Transforms a given hash to a relative path and filename ex: '002badb952000339cdcf1b61a3205b221766bf49' -> '00/2badb952000339cdcf1b61a3205b221766bf49' :param hash: the hash to split :rtype: string """ return hash[:2]+'/'+hash[2:]
c3800e89da7ab6319076e45cbd051a84a55ff9f7
37,332
def ReadBBoxPredictFile(file_path): """ Args: file path : str File format: image_name:<image_name.jpg> (percentage) (abs) <class_name>,<confidence>,<x1>,<y1>,<x2>,<y2> ... end example: image_name:a.jpg full,98%,19,30,37,50 ... end Returns: imgs_bbox : dict {img_name1: [bbox1, bbox2, ...], img_name2: [bbox1, bbox2, ...], ... } """ f = open(file_path, 'r') imgs_bbox = {} img_bbox = [] imgs_name = [] for l in f: if 'image_name:' in l or 'end' in l: if len(img_bbox) != 0: img_bbox.sort(key = lambda x: x['conf'], reverse=True) imgs_bbox[l] = img_bbox.copy() img_bbox = [] # record image name img_name = l.split(':')[-1] imgs_name.append(img_name) else: # Read bboxes! l = l.split(',') bbox = dict() bbox['label'] = l[0] bbox['conf'] = float(l[1].split('%')[0]) bbox['x1'] = int(l[2]) bbox['y1'] = int(l[3]) bbox['x2'] = int(l[4]) bbox['y2'] = int(l[5]) img_bbox.append(bbox) return imgs_bbox
086865ca68bd3387f090ffd5cdedac659cd10bbf
37,333
def element_to_set_distance(v, s): """Returns shortest distance of some value to any element of a set.""" return min([abs(v-x) for x in s])
af77a125773312fd815cbad639b81601c427cf6b
37,338
import re def find(seq, pattern, matcher=re.match): """ Search pattern in each element in sequence and return the first element that matches the pattern. (Like re.search but for lists.) """ for elem in seq: if matcher(pattern, elem) is not None: return elem
956c640d52ab2161cf4cf8f5b270511fb514d4a8
37,339
def _get_shading(idf): """Get the shading surfaces from the IDF.""" shading_types = ["SHADING:ZONE:DETAILED", "SHADING:SITE:DETAILED"] shading = [] for shading_type in shading_types: shading.extend(idf.idfobjects[shading_type]) return shading
48a212035dae232265a1bb7979d11a0cd1b70d41
37,341
def compute_taw(fc, pwp, depth, fraction): """ Compute total available water :param fc: Field capacity :param pwp: permanent wilting point :param depth: depth of soil in mm :param fraction: float value :return: a float value for TAW """ return depth * fraction * (fc - pwp)
d97a1e4cc918228fc7b0e457f1fac3ce2502f62e
37,346
def parse_list_arg(args): """ Parse a list of newline-delimited arguments, returning a list of strings with leading and trailing whitespace stripped. Parameters ---------- args : str the arguments Returns ------- list[str] the parsed arguments """ return [u.strip() for u in args.split("\n") if u.strip()]
5df3a59b4ced466e4107f494b8ed0e2fc6de917c
37,349
def after_n_iterations(n): """Return a stop criterion that stops after `n` iterations. Internally, the ``n_iter`` field of the climin info dictionary is inspected; if the value in there exceeds ``n`` by one, the criterion returns ``True``. Parameters ---------- n : int Number of iterations to perform. Returns ------- f : function Stopping criterion function. Examples -------- >>> S.after_n_iterations(10)({'n_iter': 10}) True >>> S.after_n_iterations(10)({'n_iter': 5}) False >>> S.after_n_iterations(10)({'n_iter': 9}) True """ def inner(info): return info['n_iter'] >= n - 1 return inner
134da90fa5890055417a3f89d185f74b082906d1
37,350
def _encode_asn1_str(backend, data): """ Create an ASN1_OCTET_STRING from a Python byte string. """ s = backend._lib.ASN1_OCTET_STRING_new() res = backend._lib.ASN1_OCTET_STRING_set(s, data, len(data)) backend.openssl_assert(res == 1) return s
2b673060b2793c740b0111e8280fd92a9b291fec
37,353
import re def ignore_template_file(filename): """ Ignore these files in template dir """ pattern = re.compile('^\..*|.*\.cache$|.*~$') return pattern.match(filename)
0a9402e968cd3cc8a2ca7839c7d7100206ee663f
37,354
from typing import List def dna_union( start, end, audio_length: int, do_not_align_segments: List[dict], ) -> List[dict]: """ Return the DNA list to include [start,end] and exclude do_not_align_segments Given time range [start, end] to keep, and a list of do-not-align-segments to exclude, calculate the equivalent do-not-align-segment list to keeping only what's in [start, end], and removing both what's outside [start, end] and do_not_align_segments. Args: start (Optional[int]): the start time of the range to keep, None meaning 0, i.e., the beginning of the audio file end (Optional[int]): the end of the range to keep, None meaning the end of the audio file audio_length (int): the full length of the audio file do_not_align_segments (List[dict]): the original list of DNA segments Returns: List[dict]: the union of DNA lists [[0, start], [end, audio_length]] and do_not_align_segments """ current_list = do_not_align_segments if start: new_list = [] new_list.append({"begin": 0, "end": start}) for seg in current_list: if seg["end"] <= start: pass # dna segments that end before start are subsumed by [0,start) elif seg["begin"] <= start: start = seg["end"] new_list[0]["end"] = start else: new_list.append(seg) current_list = new_list if end: new_list = [] for seg in current_list: if seg["begin"] >= end: pass # dna segments after end are subsumed by [end, audio_length) elif seg["end"] >= end: end = seg["begin"] else: new_list.append(seg) new_list.append({"begin": end, "end": audio_length}) current_list = new_list return current_list
efabb0391187500cb157bae20b2720028676c50b
37,359
def dict_updater(source: dict, dest: dict) -> dict: """ Updates source dict with target dict values creating new dict and returning it """ target = dest.copy() for k, v in source.items(): if isinstance(v, dict) and k in dest: target[k] = dict_updater(v, dest[k]) else: target[k] = v return target
cf2aa4aa238b4d7a8057fc8c29fd6755eaf02ff4
37,361
def function_star(list): """Call a function (first item in list) with a list of arguments. The * will unpack list[1:] to use in the actual function """ fn = list.pop(0) return fn(*list)
5ff784703b9238bf5d99dd4a0e1313ed8f97df88
37,362
def _pdf_url_to_filename(url: str) -> str: """ Convert a PDF URL like 'https://www.mass.gov/doc/weekly-inmate-count-4202020/download' into a filename like 'weekly-inmate-count-4202020.pdf' """ name_part = url[25:-9] return f"{name_part}.pdf"
45d4e6608813161227a19bbc29b611d6568c8d23
37,364
def get_freq_weights(label_freq): """ Goal is to give more weight to the classes with less samples so as to match the ones with the higher frequencies. We achieve this by dividing the total frequency by the freq of each label to calculate its weight. """ total_size = 0 for lf in label_freq.values(): total_size += lf weighted_slots = {label: (total_size / (len(label_freq) * freq)) for label, freq in label_freq.items()} return weighted_slots
7e0275365eb014806a6cf7c8f69415f243301d35
37,365
def subtract_number(x, y): """This function will subtract 2 numbers""" return x - y
32868ec101c36f5fb7267361a6da4eb017e38a47
37,367
def nearest(array, pivot): """find the nearest value to a given one Args: array (np.array): sorted array with values pivot: value to find Returns: value with smallest distance """ return min(array, key=lambda x: abs(x - pivot))
75d468613a766425346ae980cef3ab0bd19d5e1c
37,373
import logging def get_builder_log(name): """Get a logging object, in the right place in the hierarchy, for a given builder. :param name: Builder name, e.g. 'my_builder' :type name: str :returns: New logger :rtype: logging.Logger """ return logging.getLogger("mg.builders." + name)
2a158c3cff310f005fd42f8b9ee9ad61d68e08be
37,374
def replace_redundant_grammemes(tag_str): """ Replace 'loc1', 'gen1' and 'acc1' grammemes in ``tag_str`` """ return tag_str.replace('loc1', 'loct').replace('gen1', 'gent').replace('acc1', 'accs')
5469efb333a8c0174d4696d6559442f77a1fb6da
37,376
def seating_rule(max_neighbours): """ If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied. If a seat is occupied (#) and max_neighbours or more seats adjacent to it are also occupied, the seat becomes empty. Otherwise, the seat's state does not change. Floor (.) never changes; seats don't move, and nobody sits on the floor. """ def rule(state, neighbours): occupied_neighbours = sum(n == '#' for n in neighbours) if state == 'L' and not occupied_neighbours: return '#' if state == '#' and occupied_neighbours >= max_neighbours: return 'L' return state return rule
7011b060d8ccfb378ccf15225af081ae09454e7f
37,380
def crossProduct(p1, p2, p3): """ Cross product implementation: (P2 - P1) X (P3 - P2) :param p1: Point #1 :param p2: Point #2 :param p3: Point #3 :return: Cross product """ v1 = [p2[0] - p1[0], p2[1] - p1[1]] v2 = [p3[0] - p2[0], p3[1] - p2[1]] return v1[0] * v2[1] - v1[1] * v2[0]
4faf8f1d63192913c6a3abf726e343e377e9622a
37,383
from datetime import datetime def date_passed(value): """ Checks if the embargoded date is greater than the current date args: value (str): Date in the format yyy-mm-dd that needs to be checked returns: (bool): If the given date is less than the current date or not """ value_date = datetime.strptime(value, "%Y-%m-%d") current_date = datetime.now() return value_date.date() < current_date.date()
fa3b3a47265dd15c6a9a6ba1820a3e7e61bbe945
37,385
from typing import Dict from typing import Any def value_from_dot_notation(data: Dict[str, Any], path: str) -> Any: """Take a dictionary `data` and get keys by the `path` parameter, this path parameter will use the dots (.) as delimiter. """ for key in path.split('.'): data = data[key] return data
847f08c3132d17da9923d5a78a06f6f831be34c8
37,389