content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import textwrap import re def pytd_src(text): """Add a typing.Union import if needed.""" text = textwrap.dedent(text) if "Union" in text and not re.search("typing.*Union", text): return "from typing import Union\n" + text else: return text
5d5c9019f5cfde866a6b05e0f48febc17bfb1c09
667,033
import torch def KLD(mean, log_std): """ Calculates the Kullback-Leibler divergence of given distributions to unit Gaussians over the last dimension. See Section 1.3 for the formula. Inputs: mean - Tensor of arbitrary shape and range, denoting the mean of the distributions. log_std - T...
58a98846cf646c5f33079bdf438ed41833277152
667,034
def has_duplicates(lst: list) -> bool: """Checks if a list has duplicate values""" return len(lst) != len(set(lst))
6f6ac90894a96900af92177898d7e1a0151b2d03
667,037
from dateutil import tz def datetime_to_isodate(datetime_): """Convert Python datetime to GitHub date string. :param str datetime_: datetime object to convert .. note:: Supports naive and timezone-aware datetimes """ if not datetime_.tzinfo: datetime_ = datetime_.replace(tzinfo=tz.tzutc(...
a2365e7d74fe3cf5aca96ceccb93020400f18700
667,042
def _encode_csv(iterable_items): """ Encodes CSVs with special characters escaped, and surrounded in quotes if it contains any of these or spaces, with a space after each comma. """ cleaned_items = [] need_escape_chars = '"\\' need_space_chars = ' ,' for item in iterable_items: n...
85978f2e7dad2eb56108c636545611f38e4a24d6
667,044
def acquisitions_from_ifg_dates(ifg_dates): """Given a list of ifg dates in the form YYYYMMDD_YYYYMMDD, get the uniqu YYYYMMDDs that acquisitions were made on. Inputs: ifg_dates | list | of strings in form YYYYMMDD_YYYYMMDD. Called imdates in LiCSBAS nomenclature. Returns: acq_dates | l...
7ee5a0bec594c9257bcfb0c61db3e8a8f6791ecb
667,046
def merge_dicts_into(target, *dicts): """Merge the provided dicts into the target dict.""" for d in dicts: target.update(d) return target
c2ff91a3f43158350150f223ee6987c75250a4ca
667,047
from typing import Tuple def check_on_grid(position: Tuple[int, int]) -> bool: """Checks if a given position is on the grid.""" return all([-1 < coord < 10 for coord in position])
3143d25a604cb32dc92fc74f4da0dfb7a2944bb2
667,052
import pathlib def git_repo_kwargs(repos_path: pathlib.Path, git_dummy_repo_dir): """Return kwargs for :func:`create_project_from_pip_url`.""" return { "url": "git+file://" + git_dummy_repo_dir, "parent_dir": str(repos_path), "name": "repo_name", }
d3b48b23984f6a91130deb1ff4cc3d239e2dc03b
667,053
def _decrement_lower_bound(interval): """ Decrement the lower bound of a possibly inverted interval. i.e. turn (1, 5) into (0, 5) and (5, 1) into (5, 0). Intervals in m8 alignment files can be inverted. """ (bound_one, bound_two) = interval if bound_one < bound_two: return (bound_one...
d6e3581e8568ca021d7efd7e47892ab49a43fe2f
667,054
def fetch_object(service, obj_type, obj_name, create=False, create_args={}, **fetch_args): """Helper function to fetch objects from the Watson services. Params ====== - service: a Watson service instance - obj_type: object type, one of: "environment", "configuration", "collection", "workspace" ...
46885b465c1dfe415ba48433856fd5144546030c
667,059
def atof(text): """ helper for natural_keys attempt to convert text to float, or return text :param text: arbitrary text :return: float if succeeded to convert, the input text as is otherwise """ try: retval = float(text) except ValueError: retval = text return retval
c71568d1c9b37f271a82a9891c282c52786d90c5
667,062
def bgr_to_rbg(img): """Given a BGR (cv2) numpy array, returns a RBG (standard) array.""" dimensions = len(img.shape) if dimensions == 2: return img return img[..., ::-1]
b4b25566129a620905d429cc7f90e4bc0c31b467
667,063
def filter_instances(instances, filter_expr): """Filter instances using a lambda filter function.""" return list(filter(filter_expr, instances))
5003888f1536788fe8e4b2d1430f962983edee70
667,064
def denormalize(x,centroid,scale): """Denormalize a point set from saved centroid and scale.""" x = x*scale + centroid return x
01ccf107edf569b771a9e97928ed49fc8184ff11
667,069
def minmaxrescale(x, a=0, b=1): """ Performs a MinMax Rescaling on an array `x` to a generic range :math:`[a,b]`. """ xresc = (b - a) * (x - x.min()) / (x.max() - x.min()) + a return xresc
114b8f3f67338be432af82ab36769618c3140c51
667,072
from pathlib import Path def test_data_root_dir() -> Path: """Return the absolute path to the root directory for test data.""" return Path(__file__).resolve().parent / "test_data"
08a17b2c10ddec5ee4f3e21382f11723f90651c5
667,073
from typing import List from typing import Tuple def flat(data: List[Tuple]): """ Removes unnecessary nesting from list. Ex: [(1,), {2,}, {3,}] return [1, 2, 3] """ if not data: return data return [d for d, in data]
0adea0c16cc7266cfba22b5afd2497192cc66eb3
667,075
def is_number(num): """Tests to see if arg is number. """ try: #Try to convert the input. float(num) #If successful, returns true. return True except: #Silently ignores any exception. pass #If this point was reached, the i...
4a743c79fb94a24b5bf589a112145468ea23f59f
667,077
def subset(data, size): """Get a subset of the dataset.""" return { 'data': data['data'][:size, :], 'labels': data['labels'][:size], }
dc5116a7a84b49a516e18427ba373c5de2f03a15
667,082
def compute2x2(obs, pred): """Compute stats for a 2x2 table derived from observed and predicted data vectors Parameters ---------- obs,pred : np.ndarray or pd.Series of shape (n,) Returns ------- a : int True positives b : int False positives c : int Fal...
79c0483719d8f96b3895da25cab2d8fd27293bf6
667,083
import six def morph_dict(d, convert_function): """ Convert a nested dictionary from one convention to another. Args: d (dict): dictionary (nested or not) to be converted. convert_function (func): function that takes the string in one convention and returns it in the other one. ...
47e7c74f68b0eab57934449c9028b04f06a677b9
667,084
def fixture_family_tag_name() -> str: """Return a tag named 'family'""" return "family"
fe55bb8fabf2888b0576320ea269f5aa122460dc
667,086
def conslice(sim_mat, sep): """Slices a confusion matrix out of similarity matrix based on sep""" images = sim_mat[:sep] slices = [] for i in range(len(images)): slices.append(images[i][sep:]) return slices
62e7591015beb317fab694089f5253f97cda7f34
667,087
def decode_word(word): """ Return the decoding of a run-length encoded string """ idx = 0 res = [] while idx < len(word): count = int(word[idx]) char = word[idx+1] res.append(char * count) idx += 2 return ''.join(res)
6288e9dabbb44626487f0ce1d733ad471676eedd
667,091
def _extents(f): """Helper function to determine axis extents based off of the bin edges""" delta = f[1] - f[0] return [f[0] - delta/2, f[-1] + delta/2]
5250cf68196a330dcc563d3d388b26cd5ccb1447
667,093
def remove_oneof(data): """ Removes oneOf key from a dict and recursively calls this function on other dict values. """ if 'oneOf' in data: del data['oneOf'] for key in data: if isinstance(data[key], dict): remove_oneof(data[key]) return data
8f43890c971464c186eb4c7ec1f098a99cae21f3
667,095
import re def clean_string_whitespace(text: str) -> str: """Clean whitespace from text that should only be a single paragraph. 1. Apply ``str.strip`` method 2. Apply regular expression substitution of the ``\\s`` whitespace character group with `` `` (a single whitespace). """ text = text....
7105129d461d827fba88b29d12ef89141772d305
667,098
def find_item(items, key, value): """Find an item with key or attributes in an object list.""" filtered = [ item for item in items if (item[key] if isinstance(item, dict) else getattr(item, key)) == value ] if len(filtered) == 0: return None return filtered[0]
b892353fab9cbdc7dba73b06f6a533b734aeb402
667,104
def get_collected_vertex_list_name(full_path_name): """Return the name of the list generated by folding vertices with name full_path_name.""" return "collected_" + full_path_name
46f3488ec47dab181df159e33d81d09fa91442a2
667,105
def has_won(player): """ Test to see if the player has won. Returns true if the player has the gold and is also at the tile (0,0). """ return player.x == 0 and player.y == 0 and player.has_gold
523fc89099099865a7a65c8250d62cc07c5268d1
667,106
def normalize_unit_box(V, margin = 0.0): """ NORMALIZE_UNIT_BOX normalize a set of points to a unit bounding box with a user-specified margin Input: V: (n,3) numpy array of point locations margin: a constant of user specified margin Output: V: (n,3) numpy array of point locations bounded by margin ~ 1-...
9a23967b6f472a808c2dfa193c09b4a712b63628
667,108
def get_form_weight(form): """Try to get form weight attribute""" try: return form.weight except AttributeError: return 0
c85a172846e793ae7cf2180413ed654d706bd01d
667,112
def create_delete_marker_msg(id): """ Creates a delete marker message. Marker with the given id will be delete, -1 deletes all markers Args: id (int): Identifier of the marker Returns: dict: JSON message to be emitted as socketio event """ return {'id': id}
519ab5e4040b39eb6e2bc2c7736be323052a1282
667,120
def multi_to_one_dim(in_shape, in_index): """ Convert an index from a multi-dimension into the corresponding index in flat array """ out_index = 0 for dim, index in zip(in_shape, in_index): out_index = dim * out_index + index return out_index
b1a38f72225b354a4c8a0ca93f016ac77752bc98
667,125
def scc(graph): """ Finds what strongly connected components each node is a part of in a directed graph, it also finds a weak topological ordering of the nodes """ n = len(graph) comp = [-1] * n top_order = [] Q = [] stack = [] new_node = None for root in range(n): ...
85a9f7fef226b3047ab43934127bb2f00831a248
667,129
def sort_012(nums): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: nums(list): List to be sorted Returns: Sorted nums """ # Linear search, O(1) in time, O(1) in space pos0, pos2 = 0, len(nums)-1 i = 0 while i <= pos2 and p...
0a485a59f851c6a454fee21dec0ed195f7d21e1c
667,130
def max_chan_width(ref_freq, fractional_bandwidth): """ Derive max_πž“πΌ, the maximum change in bandwidth before decorrelation occurs in frequency Fractional Bandwidth is defined by https://en.wikipedia.org/wiki/Bandwidth_(signal_processing) for Wideband Antennas as: (1) πž“πΌ/𝝼 = fb = (fh...
a72cbafde5af02c4baa50ea64a12fa50adca8869
667,131
def build_request_url(method, output_format='tsv'): """Create url to query the string database Allows us to create stubs for querying the string api with various methods Parameters ---------- method: str options - get_string_ids, network, interaction_partners, homology, homology_best, ...
5f0d4abd97233ecd3efd98d8f38af6e9c66b9694
667,132
def _add_formset_field_ids(form_field_ids, formset): """ Add all input fields of a given form set to the list of all field ids in order to avoid keyboard navigation while entering text in form fields. """ for i, form in enumerate(formset): for field in form.base_fields.keys(): f...
a5ab6983259f72f6c27668472af68fcc7b864c84
667,137
def check_brackets_match(text): """ Checks, whether brackets in the given string are in correct sequence. Any opening bracket should have closing bracket of the same type. Bracket pairs should not overlap, though they could be nested. Returns true if bracket sequence is correct, false otherwise. ...
df1167fbcacf8f6b0f9691042d1fd7ff6f23d7d7
667,138
def GetBaseResourceId(resource_id): """Removes common suffixes from a resource ID. Removes suffixies that may be added by macros like IMAGE_GRID or IMAGE_BORDER. For example, converts IDR_FOO_LEFT and IDR_FOO_RIGHT to just IDR_FOO. Args: resource_id: String resource ID. Returns: A string with the b...
70f46f9bdedeb927f0aa23e0ee9297ca3aeb710e
667,140
def add_additional_columns(data): """ adds "highlighted" and "profile_selected" column :param data: ptcf data frane :return: ptcf data frame with additional information """ highlighted = [True] * len(data.index) data['highlighted'] = highlighted profile_selected = [False] * len(data.index) da...
a511f62b438ca7885ba8b168e5aae534b9f222ac
667,142
def is_hidden_file(filename): """Does the filename start with a period?""" return filename[0] == '.'
534d3afe9b45393fb35866014b11eac55100d6ae
667,143
def do_nothing_decorator(*_args, **_kws): """ Callable decorator that does nothing. Arguments are catched, but ignored. This is very useful to provide proxy for decorators that may not be defined. Args: *_args: Positional arguments. **_kws: Keyword arguments. Returns: ...
8b8dff61d9248c767025e65fb5771b73e9c661c1
667,144
import struct def unpack_dint(st): """unpack 4 bytes little endian to int""" return int(struct.unpack('<i', st[0:4])[0])
8924e18537dc4b25cb48a74bcaad3b01991c426e
667,145
import torch def scale_boxes(bboxes, scale): """Expand an array of boxes by a given scale. Args: bboxes (Tensor): shape (m, 4) scale (float): the scale factor of bboxes Returns: (Tensor): shape (m, 4) scaled bboxes """ w_half = (bboxes[:, 2] - bboxe...
7f8e99f67a7b6945a82eef6ade3f7d6c6c24afce
667,147
def seismic_suspension_fitered(sus, in_trans): """Seismic displacement noise for single suspended test mass. :sus: gwinc suspension structure :in_trans: input translational displacement spectrum :returns: tuple of displacement noise power spectrum at :f:, and horizontal and vertical components. ...
38515f96dceeb66e100645658211ecfdc2177489
667,148
import re def clean_string(t, keep_dot=False, space_to_underscore=True, case="lower"): """Sanitising text: - Keeps only [a-zA-Z0-9] - Optional to retain dot - Spaces to underscore - Removes multiple spaces , trims - Optional to lowercase The purpose is just for easier typing, exporting, sa...
36d72799c5ad4df6f64b3a7ba387adbc45ae645a
667,149
def only_letter(s: str) -> str: """Filter out letters in the string.""" return ''.join([c for c in s if c.isalpha()])
a754578aaffce8299387db669874a9e2c63a1130
667,150
def test_begin_str(test_name,max_len=40): """ Use with test_end_str(test_name) to make string like this:\n ******** Test Begin ********\n ******** Test End ********** """ if (len(test_name)%2==1): star_len=(max_len-len(test_name))//2+1 return '*'*star_len+" "+test_name+" Begin "+...
46e5872899458803a5db134307d68b651168bea7
667,151
import time def time_func_call(func): """ Prints the processing time of the wrapped function after its context is left. :param func: Function to be wrapped. Usage: @time_func_call def func(): pass """ def wrapped_func(*args, **kwargs): start = time.process_time() ...
61b2a11b07ea65b7d3d67cc26033d54e21c80d46
667,158
def phase_rms(antbl, scale_prms = 1.0, nu_scale = None): """Function that computes phase rms for a given baseline. The structure function here gives 30 deg phase rms at 10000m = 10km, which is the limit "go" conditions when performing a go-nogo at ALMA. Args: antbl: Antenna baseline in m...
b081379924bd2cd7ebb227297d6d3aa100ed8fb5
667,162
def set_shape_element(shape, index, value): """Set element of shape tuple, adding ones if necessary. Examples: set_shape_element((2,3),2,4)=(2,3,1,4) set_shape_element((2,3),-4,4)=(4,1,2,3) """ if index >= 0: return shape[:index] + (1,)*(index - len(shape)) + (value,) + shape[ind...
beb7668a2c5dc51cbef3b13cfaf0e740c3fbe1cb
667,165
def GetNextTokenIndex(tokens, pos): """Get the index of the next token after pos.""" for index, token in enumerate(tokens): if (token.lineno, token.column) >= pos: return index return None
fca0bd994bbe5fadac1db22f8960ae2d8f08f9fc
667,169
def eq_column(table, column, value): """column == value""" return getattr(table.c, column) == value
07484686e725cab4933e5d0af51ebfc8e115dda7
667,175
def func_with_args(a: int, b: int, c: int = 3) -> int: """ This function has some args. # Parameters a : `int` A number. b : `int` Another number. c : `int`, optional (default = `3`) Yet another number. Notes ----- These are some notes. # Returns ...
f899eb562d872437e0cb05e7285fc3a2df1d057c
667,176
def compute_total_unique_words_fraction(sentence_list): """ Compute fraction os unique words :param sentence_list: a list of sentences, each being a list of words :return: the fraction of unique words in the sentences """ all_words = [word for word_list in sentence_list for word in word_list] ...
4b2a9cbef50a1195abc14760d7d2ebf0216ba63b
667,178
def factorialFinderLoops(n): """Returns the factorial of the positive integer n using loops.""" if not isinstance(n, int): raise TypeError('n should be a positive integer.') return None if n < 0: raise ValueError('n should be a positive integer.') return None resul...
75a258f05230818f3ce00648d3af154315083341
667,181
def string_to_interactions(string): """ Converts a compact string representation of an interaction to an interaction: 'CDCDDD' -> [('C', 'D'), ('C', 'D'), ('D', 'D')] """ interactions = [] interactions_list = list(string) while interactions_list: p1action = interactions_list.pop...
005bebe3dd4368af174d6e73c98757f2b486f974
667,182
def make_po_file_function_dict(pos, filefilter=lambda f: True): """Create a file, function dictionary from a list of proof obligations. Args: pos: list of proof obligations (primary or supporting) filefilter: predicate that specifies which c files to include Returns: dictionary that organ...
ea57ad2001c6a7f95d874fa5a41f7273630c7aa3
667,183
from pathlib import Path from typing import List def collect_app_bundles(source_dir: Path) -> List[Path]: """ Collect all app bundles which are to be put into DMG If the source directory points to FOO.app it will be the only app bundle packed. Otherwise all .app bundles from given directory are ...
50a4bf767eb0208045257a2ebf8a760ae7a5fc6d
667,184
def obter_exercito (unidade): """Esta funcao devolve o nome do exercito da unidade dada como argumento""" return unidade[3]
76c6318915bc017eecbefdd10df91d56e6be28b4
667,187
def UserOwnsProject(project, effective_ids): """Return True if any of the effective_ids is a project owner.""" return not effective_ids.isdisjoint(project.owner_ids or set())
a2fe6315835faea262c1774c82c48ff9e0f8ba0c
667,189
def flatten(nested_list): """Flatten a nested list.""" return [item for sublist in nested_list for item in sublist]
764df7f221cb48c60619e97f9b92f298a4ebad26
667,191
import random def randomword(length=12): """ Generate a string of random alphanumeric characters """ valid_chars = \ 'abcdefghijklmnopqrstuvyxwzABCDEFGHIJKLMNOPQRSTUVYXWZ012345689' return ''.join(random.choice(valid_chars) for i in range(length))
812a14f247562d8395077231c104eb5e939e8199
667,193
from typing import OrderedDict def _get_price_statistics(trading_day_feed): """Calculate and print the following data for each Symbol as a comma-delimiter string. Rows should be printed in alphabetical order based on Symbol i. Time: Most recent timestamp for that Symbol in YYYY-mm-dd HH:MM:SS format ...
9d44ec4a80581475784f08b3af42fcce98f3e6a5
667,200
def rectangle_clip(recta, rectb): """ Return the clipped rectangle of ``recta`` and ``rectb``. If they do not intersect, ``None`` is returned. >>> rectangle_clip((0, 0, 20, 20), (10, 10, 20, 20)) (10, 10, 10, 10) """ ax, ay, aw, ah = recta bx, by, bw, bh = rectb x = max(ax, bx) ...
a04265bc26620c99c2635681ccb0a759a081152b
667,202
def polygon_from_bbox(bbox): """ Generate a polygon geometry from a ESWN bouding box :param bbox: a 4 float bounding box :returns: a polygon geometry """ return [ [ [bbox[0], bbox[1]], [bbox[2], bbox[1]], [bbox[2], bbox[3]], [bbox[0], bbox[3]]...
e891c60f67474b318fa5c18c34df45632bcf2bd2
667,203
import re def simplify_string(string: str) -> str: """Remove special symbols end extra spaces. :param string: what is needed to simplify :return: simplified string """ simpl1 = re.sub(r'[^\w\d\-. ]', '', string) simpl2 = re.sub(r'[ ]+', ' ', simpl1) return simpl2
afee2b4680226e92baf58faa0e96f3ddb7ce473d
667,206
import re def normalize_target(target: str) -> str: """Normalize targets to allow easy matching against the target database: normalize whitespace and convert to lowercase.""" return re.sub(r"\s+", " ", target).lower()
8388b7eb4e3d2553bb9dd899609ec35718ea63eb
667,209
def get_dict_path(base, path): """ Get the value at the dict path ``path`` on the dict ``base``. A dict path is a way to represent an item deep inside a dict structure. For example, the dict path ``["a", "b"]`` represents the number 42 in the dict ``{"a": {"b": 42}}`` """ path = list(path) ...
2aa4930077258a6bac45717b2e2138ae8897a9a6
667,216
def hms_to_s(h=0, m=0, s=0): """ Get total seconds from tuple (hours, minutes, seconds) """ return h * 3600 + m * 60 + s
2f78dab3a2719d07004cee4621ce67624174030a
667,218
from typing import List def get_params(opcode: int) -> List[int]: """Get params from an `opcode`. Args: opcode (int): the opcode to extract params Returns: list: of length 0-2 """ if opcode < 100: return [] return [int(p) for p in str(opcode//100)]
5f91503909cad00e27c99078032cb994e2efbfde
667,219
def expense_by_store(transactions_and_receipt_metadata): """Takes a transaction df of expenses and receipt metadata and groups on receipt id, in addition to year, month and cat input: df (pd.DataFrame): dataframe of transactions to group and filter returns: df (pd.DataFrame): grouped datafra...
59f5c00326dd5f91024557b57e82af5ad1a0bd92
667,220
def __get_tweet_content_from_res(gh_res): """From the response object returned by GitHub's API, this function builds the content to be tweeted Args: gh_res (dict): A dictionary of repository details Returns: str: The string to be tweeted. """ tweet_content = gh_res["name"] if gh_res["langua...
50db59f21bce3638217de4132f376acc44542b7b
667,224
def protocol_type(request): """ used to parametrized test cases on protocol type :param request: pytest request object :return: protocol type """ return request.param
d316ffa6724f34bc609e6fafb15a3f0ae308badd
667,227
def continuous_fraction_coefs (a, b): """ Continuous fraction coefficients of a/b """ ret = [] while a != 0: ret.append( int(b//a) ) a, b = b%a, a return ret
1903f74f9bd12c2e4dbed150c2eb24d93baa18b9
667,231
def GroupBuildsByConfig(builds_timings): """Turn a list of BuildTiming objects into a map based on config name. This is useful when looking at waterfall groups (cq, canary, etc), if you want stats per builder in that group. Args: builds_timings: List of BuildTiming objects to display stats for. Returns...
91c9c8b5d0323550244a6fc08d507340a4db2adf
667,234
import ntpath def get_relpath(path): """ gets the relative path without file Args: path (string): path to the file Returns: string: the relative path """ return ntpath.split(path)[0]
462a51d1b2239549c6ffa49325a1c21c0c9cb047
667,235
def get_db(entity): """ Returns the #pony.orm.Database backing the #Entity instance *entity*. """ return entity._database_
012f05c638b41ed21cf6d717fc3b55926264efb9
667,238
def make_mission_id(mission_definition, specifics_hash): """ Returns the string mission_id which is composed from the mission_definition and specifics_hash. """ return "%s-%s" % (mission_definition, specifics_hash)
5b1d6817dfef08df61b7c372c921f5703186019f
667,241
import math def work(force, displacement, theta): """ Calculates the work done by the force while displacing an object at an angle theta Parameters ---------- force : float displcement : float theta : float Returns ------- ...
989d44fe8f7e64a755484bc95db2e44abaaae3f5
667,243
def string_attributes(domain): """ Return all string attributes from the domain. """ return [attr for attr in domain.variables + domain.metas if attr.is_string]
fbc26a13eb445b25dac4a18d84c4ed109b118894
667,244
def wordcount(text): """ Return the number of words in the given text. """ if type(text) == str: return len(text.split(" ")) elif type(text) == list: return len(text) else: raise ValueError("Text to count words for must be of type str or of type list.")
fb9df95826565fc5bdbb8f13cd66179a08cea8e3
667,245
def get_neighbor_top_left_corner_from_explore(direction): """ Return the relative offsets where the top left corner of the neighbor card would be situated, from an exploration cell. Direction must be one of "up", "down", "left", or "right". """ return {"l": (-2, -4), "d": (1, -2), "u": (-4, -1), "r": (-...
1f561be3e9ca5f47f388a967b6c9073a52c7931f
667,246
import imaplib def get_mail_by_uid(imap, uid): """ The full email as determined by the UID. Note: Must have used imap.select(<mailbox>) before running this function. Args: imap <imaplib.IMAP4_SSL>: the server to fetch Returns: Dictionary, with the keys 'flags', 'date_time', ...
d8ded0dedf04fb55ba33a6dd493055f745f52264
667,247
import decimal def round_int(dec): """Round float to nearest int using expected rounding.""" return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_DOWN))
0b6d0b48203e4c3d660bc5d6abd75b290af12c1a
667,248
def empty_config_path(tmp_path_factory): """Create an empty config.ini file.""" config_path = tmp_path_factory.getbasetemp() / "config.ini" config_path.touch() return config_path
67a783279b572e86dba615f68b48dc8e05331338
667,257
def resta_complejos(num1:list,num2:list) -> list: """ Funcion que realiza la resta de dos numeros complejos. :param num1: lista que representa primer numero complejo :param num2: lista que representa segundo numero complejo :return: lista que representa la resta de los numeros complejos. """ ...
9d7cc64b3e418494b2cd6c85180d379ed9384b1e
667,260
def Main(a, b): """ :param a: an integer :param b: an integer :return: a + b :rtype: int """ c = a + b return c
17228d0d17bb3f41c301ff3334d02eac709300bf
667,261
from typing import Mapping from typing import List def _mapping_to_mlflow_hyper_params(mp: Mapping) -> List[str]: """ Transform mapping to param-list arguments for `mlflow run ...` command Used to pass hyper-parameters to mlflow entry point (See MLFlow reference for more information) All mapping value...
c0d1fe9083ddf6fce29b98bd88de209a06a47f02
667,264
import click def confirm_yesno(text, *args, **kwargs): """Like ``click.confirm`` but returns ``Y`` or ``N`` character instead of boolean. """ default = "[N]" # Default is always N unless default is set in kwargs if "default" in kwargs and kwargs["default"]: default = "[Y]" confirm...
fad4c93214d06036769cf3da9d0060e43d759c99
667,271
def threshold_filter(elevation_series, threshold=5.0): """Filter elevation series by breaking it into vertical increments. Args: elevation_series (pd.Series): elevation coordinates along a path. threshold (float): Threshold beyond which a change in elevation is registered by the algorithm, in the u...
dce4f4f8e9c5d4eec02cedac72bb93cefe7ed502
667,273
def test_datadir(request, datadir): """ Inject the datadir with resources for the specific test function. If the test function is declared in a class then datadir is ClassName/FunctionName otherwise it is only FunctionName. """ function_name = request.function.__name__ if not request.cls: ...
1f27d8fd131f2d88b60e1c7a463c2f2876020550
667,276
def _l(self, paper, **_): """Display long form of the paper (all details)""" print("=" * 80) paper.format_term_long() print("=" * 80) return None
99c9611fe3f1f20a019b3dd03951b68f47cd078f
667,279
import json def serialize_json_data(data, ver): """ Serialize json data to cassandra by adding a version and dumping it to a string """ dataOut = data.copy() dataOut["_ver"] = ver return json.dumps(dataOut)
1e2bdc63204c7b64044056c15c34e7a4bb62e919
667,286
from typing import Callable def enforce_state(property_name: str, expected_value): """ A decorator meant for class member functions. On calling a member, it will first check if the given property matches the given value. If it does not, a value error will be thrown. """ def dec(func: Callable)...
58545341e29d13b9e4fd89a56bde0d8512546976
667,288
def get_headers(referer): """Returns the headers needed for the transfer request.""" return { "Content-Type": "application/json; charset=UTF-8", "X-Requested-With": "XMLHttpRequest", "Referer": referer }
3e7470a6344cd7b97f682974e8497bce0edc08cb
667,289
def getPointCoords(row, geom, coord_type): """Calculates coordinates ('x' or 'y') of a Point geometry""" if coord_type == 'x': return row[geom].x elif coord_type == 'y': return row[geom].y
35d15cebe418238e0826e272a670a4b3af701ae3
667,292