content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_datetime(cube): """Extract the time coordinate from a cube in datetime format """ tcoord = cube.coord('time') tcoord_as_datetime = tcoord.units.num2date(tcoord.points) return tcoord_as_datetime
e9975950e2e7d32a9845e55e062d11d7fa7440f6
696,863
def secure_lookup(data, key1, key2 = None): """ Return data[key1][key2] while dealing with data being None or key1 or key2 not existing """ if not data: return None if key1 in data: if not key2: return data[key1] if key2 in data[key1]: return data[key1...
03316d8902572f9ece66229f45fcc68212120fa5
696,866
import re def pint2cfunits(value): """Return a CF-Convention unit string from a `pint` unit. Parameters ---------- value : pint.Unit Input unit. Returns ------- out : str Units following CF-Convention. """ # Print units using abbreviations (millimeter -> mm) s = "...
7527a76393553282e39800dd685fd7138e78b359
696,868
def _get_outcome(guess: str, solution: str) -> str: """Get outcome string for the given guess / solution combination Args: guess: the word guessed solution: puzzle solution Returns: 5-character string of: '0' = letter not present '1' = letter present but not...
843e7d2c38d3bd7e22b508581924ada0416adb84
696,870
def generate_save_string(dataset, embedding_name, random_state=-1, sample=-1.0): """ To allow for multiple datasets to exist at once, we add this string to identify which dataset a run script should load. Arguments: dataset (str) : name of dataset embedding_na...
975fc413d86af2b5b3f24f440100efdd4013c478
696,872
def getDiffElements(initialList: list, newList: list) -> list: """Returns the elements that differ in the two given lists Args: initialList (list): The first list newList (list): The second list Returns: list: The list of element differing between the two given lists """ fi...
a336d5f0c3073f3a656e0b79eaae2b117ba86899
696,873
def limit_stop_loss(entry_price: float, stop_price: float, trade_type: str, max_allowed_risk_percentage: int) -> float: """ Limits the stop-loss price according to the max allowed risk percentage. (How many percent you're OK with the price going against your position) :param entry_price: :param sto...
ad60d370fc44c43ea9398691c271465009f6d96e
696,876
def nearest_x(num, x): """ Returns the number rounded down to the nearest 'x'. example: nearest_x(25, 20) returns 20. """ for i in range(x): if not (num - i) % x: return num - i
5d8a9b6a77b9bec37517ca00fcc1d7a383aaaea1
696,878
def safe_join_existing_lab(lab_id, client): """ gets a lab by its ID only if it exists on the server """ if lab_id in client.get_lab_list(): return client.join_existing_lab(lab_id) return None
fe5ccc6fcb36fd90325a6156b3dff6d199d5ee8a
696,879
def pytest_report_collectionfinish(config, items): """Log how many and, if verbose, which items are tested in this shard.""" msg = "Running {num} items in this shard".format(num=len(items)) if config.option.verbose > 0: msg += ": " + ", ".join([item.nodeid for item in items]) return msg
e81d3663f60505543a1b554d36e2dee26b7107f9
696,880
def extract_gist_id(gist_string): """Extract the gist ID from a url. Will also work if simply passed an ID. Args: gist_string (str): Gist URL. Returns: string: The gist ID. Examples: gist_string : Gist url 'https://gist.github.com/{user}/{id}'. """ return gist_st...
7c93c5f78cc9c5dd1b1136a82e9359a20d31265f
696,881
from datetime import datetime def get_timestamp(detailed=False): """ get_timestamp - returns a timestamp in string format detailed : bool, optional, default False, if True, returns a timestamp with seconds """ if detailed: return datetime.now().strftime("%Y-%m-%d_%H-%M-%S") else: ...
264eb48f7c205a187bc08a9b9ad73fdab05a6acb
696,886
import string import random def get_rand_string(size=6, chars=string.ascii_uppercase + string.digits): """generates a random string. :param size: length of the string :param chars: string of charaters to chese form, by default a-zA-Z0-9 """ return ''.join(random.choice(chars) for _ in range(size))
655cad254414b265df30e160b6f4859f91680ed1
696,889
def flip(board): """Returns horizontal mirror image of board with inverted colors.""" flipped_board = dict() for square, piece in board.items(): flipped_board[(7 - square[0], square[1])] = piece.swapcase() return flipped_board
62e3bbbe33abdd2e2d4e1ce6eae9f992b0fd275a
696,890
import json def cat_to_name(file): """ Loads a json file with mapping from category to flower name Parameters: file: name of .json mapping file Returns: a python dictionary with mapping of categories to flower names """ with open(file, 'r') as f: cat_to_name = jso...
4545c9924c160665d984aee88d120f9648bf2f1e
696,894
def list_to_string(lst): """ convert a list to string format for config files """ return ",".join(map(str, lst))
c7eb44b84befb0d00fd72033e9cbcb50951c649c
696,897
def get_secs(t_string): """ From time_string like '00:00:35.660' returns the number of seconds respect to '00:00:00.000' returned value is float """ hours = t_string[0:2] minutes = t_string[3:5] secs = t_string[6:8] m_secs = t_string[8:12] secs_total = int(hours) * 3600 + int(...
2401adef97845e9d7d900baf882812ebf0acae58
696,901
def confirm(msg=None): """ Confirms the removal of the file with a yes or no input """ # Loop "forever" intended while True: confirm_input = input(msg if msg is not None else "Purge this directory (yes/no)?") if confirm_input.lower() in ["y", "yes"]: return True if confir...
c6023f9fb72b10953afd0dbbea73a4f03db67de2
696,902
def is_kevinshome(ctx): """check to see if invoking user is kevinshome""" return ctx.author.id == 416752352977092611
13f3bf234affe65c05f2b9cf9af89297ab5ef855
696,903
def mosaic_to_horizontal(ModelParameters, forecast_period: int = 0): """Take a mosaic template and pull a single forecast step as a horizontal model. Args: ModelParameters (dict): the json.loads() of the ModelParameters of a mosaic ensemble template forecast_period (int): when to choose the mod...
1776062056b9c4d56bbcb8db5972ce62b9eacf68
696,909
def add_log_level(logger, method_name, event_dict): """ Add the log level to the event dict. """ if method_name == "warn": # The stdlib has an alias method_name = "warning" event_dict["level"] = method_name return event_dict
c69627fcbf8c7b0ec5890b8752f1327b95bd5854
696,911
def _is_python_file(filename): """Check if the input file looks like a Python script Returns True if the filename ends in ".py" or if the first line contains "python" and "#!", returns False otherwise. """ if filename.endswith('.py'): return True with open(filename, 'r') as file_handle...
a6d99166c6b76c4ae0ad5f5036951986fd5a102b
696,912
def RANGE(start, end, step=None): """ Generates the sequence from the specified starting number by successively incrementing the starting number by the specified step value up to but not including the end point. See https://docs.mongodb.com/manual/reference/operator/aggregation/range/ for more detai...
3537e1e0cd28ae7d90e469a281ab373312fe075c
696,915
import six def _unicode_to_str(data): """ Utility function to make json encoded data an ascii string Original taken from: http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python :param data: either a dict, list or unicode string :ret...
ff637b4cad60833de6c448cc3807c4928b2a94da
696,916
import re def _line_type(line, delimiter=None): """Interpret a QDP file line Parameters ---------- line : str a single line of the file Returns ------- type : str Line type: "comment", "command", or "data" Examples -------- >>> _line_type("READ SERR 3") '...
cbc0f5f831a80b28ce9aee01049c90c65b962ff4
696,919
def get_intermediate_objective_suffix(suffix=""): """ Returns dictionary of dictionaries of suffixes to intermediate files. Dict contains: objective - initial(s) of corresponding objective(s) filesuffix - intermediate file/variable suffix Args (optional) : suffix - appends t...
b00395103d3d21749f4ce3fddc913a24289b4417
696,920
def ms_timestamp_to_epoch_timestamp(ts: int) -> int: """ Converts a milliseconds timestamp to an epoch timestamp :param ts: timestamp in miliseconds :return: epoch timestamp in seconds """ return int(ts / 1000)
1c27d9ef053f568bcf9e5e37309b3def5f4c8dd0
696,929
def intersection_line_plane(p0, p1, p_co, p_no, epsilon=1e-9): """ Copied from https://stackoverflow.com/questions/5666222/3d-line-plane-intersection p0, p1: Define the line. p_co, p_no: define the plane: p_co Is a point on the plane (plane coordinate). p_no Is a normal vector defining ...
42ea283d5a9798a706e713dda8599c3d33a05cec
696,930
def _convert_to_barycentric(point, simplex, coordinates): """ Converts the coordinates of a point into barycentric coordinates given a simplex. Given a 2D point inside a simplex (a line segment or a triangle), find out its barycentric coordinates. In the case of the line (1-simplex), this would be the poin...
d895325f8a605cefaa8ecd9e2cc4edd07690b932
696,933
from typing import Counter def is_anagram(word, _list): """ Checks if the given word has its anagram(s) on the given list of words. :param word: word :param _list: list of words :return a list of found anagrams """ word = word.lower() anagrams = [] for words in _list: ...
dc6da021ed46e5068f16608fb9f3f78fedeea4a8
696,942
def diagonal (line): """Indicates whether or not `line` is diagonal.""" return (line.p.x != line.q.x) and (line.p.y != line.q.y)
b5c64e983c429023ccd2c7e57bba59511567e2d5
696,943
def cleave(sequence, index): """ Cleaves a sequence in two, returning a pair of items before the index and items at and after the index. """ return sequence[:index], sequence[index:]
5f542de88eb4cd7496a2308c9625cc7db766c90c
696,944
def age_to_eye_diameter(age): """Calulates the size of an eye given an age Args: age (float): age of the observer Returns: D_eye (float): Best diameter of Eyepiece (mm) """ if age <= 20: D_eye = 7.5 elif ((age> 20) and (age<= 30)): D_eye = 7 elif ((a...
f67154b48ec3e246e6049bfcb89c67b908d896b9
696,945
def transform_zip(number): """Get rid of extended format ZIP code.""" zip_code = number.split("-")[0] return zip_code
9ef27547f501b6f77ffff0198a4965b3082c2c91
696,947
def flatten_list(list_): """ Flattens out nested lists and tuples (tuples are converted to lists for this purpose). Example: In [1]: flatten_list([1, [[2, 3], [4, 5]], 6]) Out[1]: [1, 2, 3, 4, 5, 6] """ items = [] for element in list_: if isinstance(element, (list, tuple)): ...
c914976b1ded7b43d6a2031ac51aca9299c6a2ce
696,948
def jetCollectionString(prefix='', algo='', type=''): """ ------------------------------------------------------------------ return the string of the jet collection module depending on the input vaules. The default return value will be 'patAK5CaloJets'. algo : indicating the algorithm type of the...
c77c2fd3afcccb1e62e1d92103ce677775fae0e4
696,952
import re def sanitize_tag_label(label_string): """Return string slugified, uppercased and without dashes.""" return re.sub(r'[-\s]+', '-', (re.sub(r'[^\w\s]', '',label_string).strip().upper()))
1fee28a86533a5fda3a34a647c445fdaa73e3c59
696,953
def strip_extension(input_string: str, max_splits: int) -> str: """Strip the extension from a string, returning the file name""" output = input_string.rsplit(".", max_splits)[0] return output
62c388fd1cf11883f9e2b0259fb9ec7632537bd2
696,954
import re def header(line): """ add '>' if the symbol is missing at the end of line """ line=line.strip() if re.match("##.*<.*", line) and line[-1:] != '>': line=line+'>' return line
b06488ff95d154836d622f55ebb5b26661d1fceb
696,957
def normalize_expasy_id(expasy_id: str) -> str: """Return a standardized ExPASy identifier string. :param expasy_id: A possibly non-normalized ExPASy identifier """ return expasy_id.replace(" ", "")
30107cd75cba116b977a001f3839b1e9f32395ce
696,959
def get_excel_column_index(column: str) -> int: """ This function converts an excel column to its respective column index as used by pyexcel package. viz. 'A' to 0 'AZ' to 51 :param column: :return: column index of type int """ index = 0 column = column.upper() column = column[::-1] for i in range(len(column...
a42b05e2c08c3a6611c066fa49153f6dade93728
696,962
def shift_conv(matchobj): """ Transform '(a<b)' into 'a * 2**b'. """ shift = 1 << int(matchobj.group(2)) formula = '{}*{}'.format(matchobj.group(1), shift) return formula
c17d4c8585e18cc99d9e70848a2f9e776a21cdf6
696,963
def convert_db_dict_into_list(db_dict): """Convert dictionary of processes into list of processes.""" db_list = [] for key in db_dict.keys(): assert key == db_dict[key]["@id"] db_list.append(db_dict[key]) return db_list
ce0d678ffef92a66f5ce988bf2b7143248a1a60d
696,964
def taskname(*items): """A task name consisting of items.""" s = '_'.join('{}' for _ in items) return s.format(*items)
c8283ea85818b3e3bac6ec5357439e8c944b05e8
696,969
import re def find_serial_number(show_ver): """ Find the serial number in show version output. Example: Processor board ID FTX1512038X """ match = re.search(r"Processor board ID (.*)", show_ver) if match: return match.group(1) return ''
37b678555caaa58c08c3629c5a1fd85bd024a862
696,973
from typing import Tuple def intersect(input_blocks: Tuple[int, int]) -> int: """Intersect tuple of input blocks to return air or stone Arguments: input_blocks {Tuple[int, int]} -- Two input blocks Returns: int -- Intersected block """ if input_blocks[0] == 0 or input_blocks[1] ...
f1a900d3421244b2754b2ec60fe527568fa76739
696,978
import struct def decode_string(binary_input): """Decode a binary uon string. Length of the string is encoded on the two first bytes, the string value is utf-8 encoded on the rest. Args: binary_input (bytes): a binary uon string Returns: tuple: uon string with the decoded value, ...
96a7857352d0530bf5ed896be1203e82b8540f5b
696,980
def get_single_key_value_pair(d): """ Get the key and value of a length one dictionary. Parameters ---------- d : dict Single element dictionary to split into key and value. Returns ------- tuple of length 2, containing the key and value Examples -------- ...
c4fb7a05aa74a69ebb55a867e23298748a919738
696,983
def _fconvert(value): """ Convert one tile from a number to a pentomino character """ return {523: 'U', 39: 'N', 15: 'F', 135: 'W', 23: 'P', 267: 'L', 139: 'Z', 77: 'T', 85: 'Y', 43: 'V', 33033: 'I', 29: 'X'}[value]
73900c0f76fd8ab50d92c9db049547c83ab1c5d0
696,984
def load_story_ids(filename): """ Load a file and read it line-by-line Parameters: ----------- filename: string path to the file to load Returns: -------- raw: list of sentences """ f = open(filename, "r") story_ids = [line[:-1] for line in f] f.close() return story_...
a97580467da036b687fa1de4179159c113cf1d1b
696,987
import six def make_model_tuple(model): """ Takes a model or a string of the form "app_label.ModelName" and returns a corresponding ("app_label", "modelname") tuple. If a tuple is passed in, it's assumed to be a valid model tuple already and returned unchanged. """ if isinstance(model, tuple):...
250586856243d6d019a45f0dc3f1b2a5eedf5dfb
696,990
import re def format_label_name(name): """ Format string label name to remove negative label if it is EverythingElse """ m = re.match("\[([A-Za-z0-9]+)\]Vs\[EverythingElse\]", name) if m is None: return name else: return m.group(1)
7fd5769314da849810b81a23ab32fe099ed600ae
696,993
def readFile(fileName): """Read a file, returning its contents as a single string. Args: fileName (str): The name of the file to be read. Returns: str: The contents of the file. """ fileContents = "" with open(fileName) as inputFile: fileContents = inputFile.rea...
7292b38ac46fb60a733bffeddb9c7ee8fa600e03
696,995
def regenerate_node(arbor, node): """ Regenerate the TreeNode using the provided arbor. This is to be used when the original arbor associated with the TreeNode no longer exists. """ if node.is_root: return arbor[node._arbor_index] root_node = node.root return root_node.get_node...
6c900050ed03f8dc175a7b584cba04d9519cb232
696,996
import torch def label2one_hot_torch(labels, C=14): """ Converts an integer label torch.autograd.Variable to a one-hot Variable. Args: labels(tensor) : segmentation label C (integer) : number of classes in labels Returns: target (tensor) : one-hot vector of the input label Shape: ...
f44170bc7c8a37ca1ccb9afb104c9786e11f8396
696,997
def get_shape_columns(shape): """Return the number of columns for the shape.""" try: return shape[1] except (IndexError, TypeError): return 0
48f5fb00248e7c51fb2c8e26e705b92d57f20d46
696,998
def formacion(soup, home_or_away): """ Given a ficha soup, it will return either the formacion table of the home team, or the away one. Args: soup (BeautifulSoup): Soup of the current match home_or_away (int): Either a 1(home team) or 0(away team) """ return soup.find('table', attrs...
9213eb269bbca0b5fd86ed9e5b5e43eef871dd4d
696,999
def _2D_ticks(x_num_ticks, y_num_ticks, env_config, type_): """ Generates the tick labels for the heatmap on a 2D-state environment Parameters ---------- num_ticks : int The total number of ticks along the axis env_config : dict The environment configuration file as a dict t...
e0b93f06c0d8161d3464ac396b592baa1dcd965f
697,002
def _splitDate(nymd): """ Split nymd into year, month, date tuple. """ nymd = int(nymd) yy = nymd/10000 mm = (nymd - yy*10000)/100 dd = nymd - (10000*yy + 100*mm ) return (yy,mm,dd)
0dca81925f6ea4e965962cd436444c3b78e05467
697,003
def get_values_greater_than(values, A): # O(N) """ From a ascendingly sorted array of values, get values > A >>> get_values_greater_than([1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121], 64) [121, 100, 81, 64] >>> get_values_greater_than([1], 1) [1] """ num_values...
a1599139be2823cdf05de88ef1cfdc0dd6eceb4c
697,005
def by_command(extractor, prefix=('/',), separator=' ', pass_args=False): """ :param extractor: a function that takes one argument (the message) and returns a portion of message to be interpreted. To extract the text of a chat message, use ``lambda msg: msg['text']``. :param prefix:...
db76383bcad80be4381bb26fb65f4594576248b8
697,008
def get_filename_from_path(file_path, delimiter="/"): """ Get filename from file path (filename.txt -> filename) """ filename = file_path.split(delimiter)[-1] return filename.split(".")[0]
b079ce15dd44e8db314fdd5cb354e3bf2cab8471
697,009
import time def loop(tasks=1, breaks=0, *args, **kwargs): """ Loop a function X amount of times :param tasks: Amount of times to loop the function :param breaks: The amount of time to wait between each loop. """ def wrapper(original_func, *args, **kwargs): for i in range(tasks): ...
6d682d7d980c7f17ad2ccc45c7a509b52cf23065
697,010
def add(first, second): """Return the sum of the two numbers.""" return first + second
2b9b604d4958579774e6c96eab2bea63506468df
697,011
import socket import re def inject_payload(conn: socket.socket, payload) -> bool: """ Inject a payload into the backdoor connection. :param conn: socket object connected to backdoor :param payload: payload to inject (usually a reverse shell) :return: boolean indicating success or failure """ ...
907df512f344288d076c1d1fed95aecfc016d413
697,014
def doublecomplement(i,j): """ returns the two element of (1,2,3,4) not in the input """ list=[1,2,3,4] list.remove(i) list.remove(j) return list
b4bb329b320b2b8c3e7b7648914636f96394b6d7
697,016
def yr_label(yr_range): """Create label of start and end years for aospy data I/O.""" assert yr_range is not None, "yr_range is None" if yr_range[0] == yr_range[1]: return '{:04d}'.format(yr_range[0]) else: return '{:04d}-{:04d}'.format(*yr_range)
c453d759a23dce169593afc64846e9560d9f1cb5
697,017
def setup_with_context_manager(testcase, cm): """Use a contextmanager to setUp a test case. If you have a context manager you like:: with ctxmgr(a, b, c) as v: # do something with v and you want to have that effect for a test case, call this function from your setUp, and it will s...
e2a67d9a9600203223a220eb0a5e40c96ae6166d
697,018
from typing import Tuple def hosting_period_get(month: int) -> Tuple[int, int]: """Determine the Hosting period for the current month.""" # In February only, Hosts begin on the 1st and 15th if month == 2: return (1, 15) # For all other months, Hosts begin on the 1st and 16th return (1, 16...
77d7bc84f969b8be0f4e81ddb26d96e0d7569561
697,022
def exclude_sims_by_regex(sims, regex): """Removes sims by using a regular expression. DESCRIPTION: Returns all sims that do NOT match the regular expression. ARGS: sims (iterable of strings): An iterable of strings contating candidate sim files regex (_sre.SRE_Pattern)...
e8ca8399430e7d0017e1fb621b38103eac678089
697,023
import pytz def http_date(dt): """ Convert datetime object into http date according to RFC 1123. :param datetime dt: datetime object to convert :return: dt as a string according to RFC 1123 format :rtype: str """ return dt.astimezone(pytz.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
20db2de2969216d201bc65227fb4b54e5c71a4c5
697,024
def build_telegram(name: str, message: str, title="Dr") -> str: """Generate a properly formatted telegram message body. Args: name: The recipient of this telegram message: The message to send this user title: The recipient's title Returns: A properly formatted string fo...
7d3af3b3a61a7f2f141be6f50e10199e340245d2
697,027
def train2rect(ratios, imagew, imageh): """ Takes in data used during training and transforms it into format matching the format outputted by darknet's valid function. """ xratio, yratio, wratio, hratio = ratios xmin = xratio*imagew - wratio*imagew/2 ymin = yratio*imageh - hratio*imageh/2 ...
7675df2c314088d6363bf40dff1aac04b22c61bf
697,028
def is_key_complete(key): """Returns true if the key is complete. Complete keys are marked with a blank symbol at the end of the string. A complete key corresponds to a full word, incomplete keys cannot be mapped to word IDs. Args: key (string): The key Returns: bool. Return tr...
ecf905f973fd14f1be21b1490ad8a18988397ab9
697,029
def acknowledgements(name, tag): """Returns acknowledgements for space weather dataset Parameters ---------- name : string Name of space weather index, eg, dst, f107, kp tag : string Tag of the space waether index """ swpc = ''.join(['Prepared by the U.S. Dept. of Commerce,...
f490fe6cd4f85baad6a097b71410bb014ec0394e
697,030
def rectangleOverlap(BLx1, BLy1, TRx1, TRy1, BLx2, BLy2, TRx2, TRy2): """ returns true if two rectangles overlap BL: Bottom left TR: top right "1" rectangle 1 "2" rectangle 2 """ return not (TRx1 < BLx2 or BLx1 > TRx2 or TRy1 < BLy2 or BLy1> TRy2)
96ea5aab6738f72587c5dd9db45598e291e68338
697,031
from typing import Tuple def _identify_missing_columns( schema_field_names: Tuple[str, ...], column_names: Tuple[str, ...], ) -> Tuple[bool, ...]: """Returns boolean mask of schema field names not in column names.""" return tuple(field_name not in column_names for field_name in schema_field_names)
c6ca296e5dd4d2271b06e5e3a21a3a8d716d76cd
697,033
import re def get_patient_uuid(element): """ Extracts the UUID of a patient from an entry's "content" node. >>> element = etree.XML('''<entry> ... <content type="application/vnd.atomfeed+xml"> ... <![CDATA[/openmrs/ws/rest/v1/patient/e8aa08f6-86cd-42f9-8924-1b3ea021aeb4?v=full]]> ...
0d80313b6c7305ec72c96e29269d15718e4105da
697,034
from typing import List def csv_to_ints(school_description: str) -> List[int]: """Convert a comma separated string of integers to a list of integers. Returns ------- list[int] The list of integers from the string of comma separated values. >>> csv_to_ints('3,8,0') [3, 8, 0] """ ...
199fe36a12ba5a95895110c0614761578bc786ca
697,040
def event_counter(json_, counter): """ takes a json and counts the number of events that happened during that game inputs ------ json__: events json counter: counter dictionary returns ----- counter: counter dict with counts """ for event in json_: event_type = event...
97a10f5f219cf383c419ba65764b4c9c3f47b5ec
697,043
import hashlib import base64 def calc_md5(string): """Generates base64-encoded MD5 hash of `string`.""" md5_hash = hashlib.md5() md5_hash.update(string) return base64.b64encode(md5_hash.digest()).strip(b"\n")
88135c92de48fe45888a4a4243cce13fcddceca8
697,044
def get_content(file): """Returns a string If file 'bruh' contains "Hellor" get_content("bruh") returns 'Hellor' """ file = open(file, "r") res = file.read() file.close() return res
ae86220be856e23ed143d77117a181054565eff0
697,045
def convert_to_float(frac_str): """ convert string of fraction (1/3) to float (0.3333) Parameters ---------- frac_str: string, string to be transloated into Returns ------- float value corresponding to the string of fraction """ try: return float(frac_str) except Valu...
4f4e2ad0e5eeee7a8cc54b8b724031a48a48d747
697,047
import re def parse_fst_session_event(ev): """Parses FST session event that comes as a string, e.g. "<3>FST-EVENT-SESSION event_type=EVENT_FST_SESSION_STATE session_id=0 reason=REASON_STT" Returns a dictionary with parsed "type", "id", and "reason"; or None if not a FST event or can't be parsed""" ...
e57cb2561e23ad89bb42559ae90c61c22d98e977
697,048
from typing import List def parse_input_file(file_path: str) -> List[List[int]]: """Parse a file with the following format: 21 22 24 12 7 21 23 Returns each line as integers in a nested list """ with open(file_path) as input_file: parsed_file = [list(map(int, line.split())) for li...
f281dbcc7c9dc70eab491b1a334e0cb0cc3e45e4
697,049
def unlines(line): """Remove all newlines from a string.""" return line.translate(str.maketrans('\n', ' '))
0c2079d9694a8c48f8ddf0a87696ea89a72b1dc3
697,050
def reencode(s): """Reencodes a string using xmlcharrefreplace.""" return s.encode('ascii', 'xmlcharrefreplace').decode()
ff5bd9c2ac6754bf76f3935c947a3081f83a6781
697,056
import random def distselect(weight_l): """Perform a weighted selection using the weights from the provided list. Return the selected index""" if not isinstance(weight_l, list): raise Exception("distselect requires a list of values") # Create a weight/index vector weight_v = [] tota...
8877c957cbd3c82f37f9bec948fb64c1c33dc341
697,060
import requests def retrieve_online_json(url:str) -> dict: """ This function downloads an online json file and returns it. :argument url: The url where to find the json file to retrieve. :return: A dictionary containing all the downloaded data. """ return requests.get(url).json()
d99d7219f91f2ab67bace1b0ef0d4e9c4201318e
697,062
import re def strip_markdown(s): """ Strip some common markdown out of the description, for the cases where the description is taken from the first paragraph of the text. """ s = re.sub("[\\[\\]]", "", s) s = re.sub("\(.*\)", "", s) return s
e10e02ec385990e908e4096272df40f3dccee364
697,064
def get_expression_samples(header_line): """ Parse header of expression file to return sample names and column indices. Args: header_line (str): Header line from expression file. Returns: act_samples (dict): Dictionary of {sample_name (str): sample_data_index (int)}. sample...
615ee0421b1efaf4ef45cab9610cea883f9636b1
697,066
def PyMapping_Check(space, w_obj): """Return 1 if the object provides mapping protocol, and 0 otherwise. This function always succeeds.""" return int(space.ismapping_w(w_obj))
f9d0644fc5f7bfeaa3c08b2c2596a4658b2e508b
697,075
def validate_field(field): """ Return field if it exists otherwise empty string :param field: string to validate :return: field: input string if not empty, empty string otherwise """ if field: pass else: field = '' return field
a7f631372914de355872063d80f40c586c098788
697,077
def linear_search(nums_array: list, search: int) -> int: """ Linear Search Algorithm Time Complexity --> O(N) :param nums_array: list :param search: int :return index: int """ for i in range(len(nums_array)): if search == nums_array[i]: return i return -1
a02db3d42d6b6f1b8b2a82940d3e17d69bbd41e7
697,079
import math def _acosd(v): """Return the arc cosine (measured in in degrees) of x.""" return math.degrees(math.acos(v))
2e31e36a33a4ac25f2b2548733138dcbf910028f
697,081
def sort_quick(data): """快速排序。 选择第一个元素为主元 `pivot`,其余元素若小于 `pivot`,则放入 `left_list`,否则放入 `right_list`。递归地对子列表调用 `sort_quick`,直至排序完成。 """ if len(data) <= 1: return data pivot = data[0] left_list = [] right_list = [] for i in data[1:]: # `data` 中至少有 2 个元素 if i < pivot...
edf1aabddc992aa04e0db6631011a498f7aa65be
697,082
import torch def finalize(s0, s1, s2): """Concatenate scattering of different orders. Parameters ---------- s0 : tensor Tensor which contains the zeroth order scattering coefficents. s1 : tensor Tensor which contains the first order scattering coefficents. s2 : tensor ...
f9c1bd7f9072b7e34c5e90ca1c245a98b9d7bf8c
697,085
def quarter_for_month(month): """return quarter for month""" if month not in range(1, 13): raise ValueError('invalid month') return {1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2, 7: 3, 8: 3, 9: 3, 10: 4, 11: 4, 12: 4}[month] # return (month + 2) // 3
559bb2d194753efa3c2ee18aee3040dba05a4f85
697,086
def is_equal(x, y, tolerance=0.000001): """ Checks if 2 float values are equal withing a given tolerance :param x: float, first float value to compare :param y: float, second float value to compare :param tolerance: float, comparison tolerance :return: bool """ return abs(x - y) < toler...
2773cb526d00149e735853310986b581e1eec1e8
697,088
def _find_seam_what(paths, end_x): """ Parameters ========== paths: 2-D numpy.array(int64) Output of cumulative_energy_map. Each element of the matrix is the offset of the index to the previous pixel in the seam end_x: int The x-coordinate of the end of the seam Returns ...
dcff07b965f17ffc2fb5b5607fc88338301ca076
697,093