content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import inspect def _called_from_instance_init(instance, calling_frame): """ Helper to check a calling_frame is in an instance's __init__ """ from_init = inspect.getframeinfo(calling_frame).function == "__init__" from_this = calling_frame.f_locals.get('self') is instance return from_init and from_this
116602a31c452560da64015b4364350c47c454d9
208,019
import platform def is_windows() -> bool: """Return whether the user is using a Windows machine or not. Returns ------- :rtype: bool """ if platform.system() == 'Windows': return True return False
91cae1734edd8e2a39c01a191f8381f340a899c2
353,994
import six def sorted_files(pdict): """ Returns the file_summary information sorted in reverse order based on duration :param pdict: profile dict :return: sorted list of file_summary dicts """ return sorted([v['file_summary'] for k, v in six.iteritems(pdict) if k != 'summary'], ...
3135561bd68cdc0018c1b904f8a6b47dc4a96468
18,052
def getYN(text=''): """Prompts user for yes or no input. accepts y,Y,yes,Yes,YES,n,N,no,No,NO. returns 'y' for yes and 'n' for no. other inputs prompt user to re-enter a response""" AcceptableResponses={'y':'y','yes':'y','n':'n','no':'n'} while 1: print(text) userInput=input('Please select Y...
1690647c4141fd0df4eb14c4997f1717ef22d641
467,722
def trans_matrix(M): """Take the transpose of a matrix.""" n = len(M) return [[ M[i][j] for i in range(n)] for j in range(n)]
142baf4664d84e10ab68fe094c4eac510abbcf44
684,701
def get_connection_name(connection_id, friend_list): """ Given a mutual friends' ID, check the given list of Facebook friends and extract the name. :param connection_id: Connection's (mutual friend) Facebook ID. :type connection_id: str :param friend_list: List ...
bfe9e4e9ffb7dadbe7305ed0a3fb5d3b28b193c4
263,767
def _get_elem_at_rank(rank, data, n_negative, n_zeros): """Find the value in data augmented with n_zeros for the given rank""" if rank < n_negative: return data[rank] if rank - n_negative < n_zeros: return 0 return data[rank - n_zeros]
6517ccc434e86640141278e049a8ff62b4faa8d2
683,737
def calculate_distance(a, b): """Helper function to calculate the distance between node a and b.""" (x1, y1) = a (x2, y2) = b return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
a0b23177009e842df010cc3d3b43a21b92803411
376,554
import calendar def daysinmonth(yyyy,mm): """ return number of days in month given yyyy,mm """ return calendar.monthrange(yyyy,mm)[1]
df6391ab08911024d3e649211baec18e74c956d8
139,045
def tostring(s): """ Convert the object to string for py2/py3 compat. """ try: s = s.decode() except (UnicodeDecodeError, AttributeError): pass return s
be284dcbcca4ec267c45bdec75a6c9214e6940bd
128,222
from typing import List from typing import Union def inverse_cumulative_sum(increasing_numbers: List[Union[int, float]]): """ inverse function of cumulative sum :param increasing_numbers: ([number]) [1,3,6] :return: ([number]) [1,2,3] """ if not increasing_numbers: return [] inv_cums...
a52fbc66adfd76229a0843e1c89f482a54f977c1
211,344
from typing import List from typing import Any from typing import Optional def paginate( items: List[Any], offset: int = 0, limit: Optional[int] = None ) -> List[Any]: """ Mimic the behavior of database query's offset-limit pagination """ end = limit + offset if limit is not None else None ret...
f400df1a28feb772d81b28a89fe742bc38053875
572,081
import ctypes def ctypes2buffer(cptr, length): """Convert ctypes pointer to buffer type.""" if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)): raise RuntimeError('expected char pointer') res = bytearray(length) rptr = (ctypes.c_char * length).from_buffer(res) if not ctypes.memmove(rpt...
04da7b4a76479976c49695364441d14374fc10df
331,147
def crop_image_to_bounding_box(img, bnd_box): """Crops the given image to the given bounding box""" result = img[bnd_box[0][1] : bnd_box[1][1] + 1, bnd_box[0][0] : bnd_box[1][0] + 1] return result
27d5d780f9712d72e973cb3de816b04e2ab3ec72
639,839
def is_lookml(dashboard): """Check if a dashoard is a LookML dashboard""" return dashboard.model is not None and '::' in dashboard.id
39cbfeedecf12bf5060596c9188392c62aedf6cf
82,314
def downsample_ds(normlogSAR, downsample_factor=5): """Spatially downsample an xarray DataArray or Dataset. """ downsampled = normlogSAR.groupby_bins('x',len(normlogSAR.x)/downsample_factor).mean(dim='x').groupby_bins('y',len(normlogSAR.y)/downsample_factor).mean(dim='y') downsampled = downsampled.renam...
f6e17c9c22ce7eb3a95700d4915636c93cca2fb3
606,725
def anonymize_ip(real_ip: str) -> str: """ Sets the last byte of the IP address `real_ip`. .. note:: It is a good step but it may be possible to find out the physical address with some efforts. Example: If the input is "595.42.122.983", the output is "595.42.122.0". Raises...
f4ca8a072f295f6b06ac14712b84fe765a57d823
621,447
def format_time(seconds): # type: (int) -> str """ Return *seconds* in a human-readable format (e.g. 25h 15m 45s). Unlike `timedelta`, we don't aggregate it into days: it's not useful when reporting logged work hours. """ out = [] if seconds > 3599: out.append('%sh' % (seconds // 36...
0ae814e3dd0fd31ba4eb2ab1b55f6ed6419fb280
525,630
def get_average(pixels): """ Given a list of pixels, finds the average red, blue, and green values Input: pixels (List[Pixel]): list of pixels to be averaged Returns: rgb (List[int]): list of average red, green, blue values across pixels respectively Assumes you are returning in th...
2cae3992f3a7a3d0d9ef3feb84221a4964221bbf
692,405
def get_seat_ID(seat_string: str) -> int: """Take in seat string and calculate its ID. Args: seat_string (str): self-explantory Returns: int: seat ID """ row_string = seat_string[:-3] col_string = seat_string[-3:] row_binary = row_string.replace("F", "0").replace("B", "1")...
1bdad136d90441c05bd0b9ddaec365433b4bb1c8
256,715
import math def _c3857t4326(t1, t2, lon, lat): """ Pure python 3857 -> 4326 transform. About 12x faster than pyproj. """ xtile = lon / 111319.49079327358 ytile = math.degrees( math.asin(math.tanh(lat / 20037508.342789244 * math.pi))) return(xtile, ytile)
f146149a102b1155f9d391719387e6ce43e73bf0
376,250
def register(key, version, description=None, format='json', expensive=None): """ A decorator used to register a function as a metric collector. Decorated functions should do the following based on format: - json: return JSON-serializable objects. - csv: write CSV data to a filename named 'key' ...
3eebeb5c792ea84949b2880b624b74c6f537e44f
481,368
import torch def kl_divergence_mc( q_distrib: torch.distributions.Distribution, p_distrib: torch.distributions.Distribution, z: torch.Tensor ): """Elementwise Monte-Carlo estimation of KL between two distributions KL(q||p) (no reduction applied). Any number of dimensions works via broadcasting and correc...
1a1c0a14f13f4ed705608f37b2c4f00f67a1cbaa
670,406
from typing import List def merge(intervals: List[List[int]]) -> List[List[int]]: """ Time complexity: O(N * log(N)) Space complexity: O(N) Parameters ---------- intervals : List[List[int]] input intervals Returns ------- merged : List[List[int]] merged intervals ...
01e13470fb88cd3bb8efec9430692d9d4512c1f2
319,403
def parse_ieee_block_header(block): """ Parse the header of a IEEE block. Definite Length Arbitrary Block: #<header_length><data_length><data> The header_length specifies the size of the data_length field. And the data_length field specifies the size of the data. Indefinite Length Arbitrary ...
8f06d3d375d45712cdc1c45c8f01fd7bb8a3388f
493,123
def resets_json(fn): """ Decorator that resets cached device info json Usage: @resets_json def modify_device(self): pass """ the_fn = fn def wrapper(self, *args, **kwargs): try: r = the_fn(self, *args, **kwargs) except: raise final...
c80934349480bc916ce8bb68b3ec378a01750c77
253,917
def _read_request_line_dict(line): """Return a dict containing the method and uri for a request line""" # Split the line into words. words = line.split(" ") method = "GET" # If the line contains only one word, assume the line is the URI. if len(words) == 1: uri = words[0] else: ...
c7e2800143dc1aff3135cb6d13f724da186ff1ed
492,259
def reopen_to(fhandle, path, mode): """ close a filehandle and return a new one opened for the specified path and mode. example: sys.stdout = reopen_to(sys.stdout, "/tmp/log.txt", "w") Parameters: fhandle (file): the file handle to close (may be None) path (str): the new path to open ...
17eb5da556899e80962866b9229d3cde478ec7df
670,191
def _position_is_empty_in_board(position, board): """ Checks if given position is empty ("-") in the board. :param position: Two-elements tuple representing a position in the board. Example: (0, 1) :param board: Game board. Returns True if given position is empty, False otherw...
dda9166588cdeaf81f5c17c57bedc81b856a0ce5
601,821
def ffmpeg_middle(ext_to): """ Function to get ffmpeg command middle section to convert to a given file extension. Parameter --------- ext_to: string filetype to convert to Returns ------- ffmiddle: string ffmpeg command middle section """ ffmidd...
aa89f14ecaf53a049b393e71c24629bf2956117d
565,071
def capitalise(string: str) -> str: """Capitalises the first character of a string""" if not len(string): return '' return string[0].upper() + string[1:]
f8cb687d61dd60ac068cac724b88e0ed04cbe51c
611,040
def get_name_dir(name): """Construct a reasonable directory name from a descriptive name. Replace spaces with dashes, convert to lower case and remove 'content' and 'Repository' if present. """ return name.lower().replace(' ', '-').replace('-content', '')\ .replace('-repository', '')
1de53f36e8cbfa31c2292ff9b252d286b54ec2e1
296,626
def output_to_IOB2_string(output): """ Convert Stanford NER tags to IOB2 tags. """ iob2_tags = [] names = [] previous_tag = 'O' for _, tup in enumerate(output): name, tag = tup if tag != 'O': tag = 'E' if tag == 'O': iob2_tags.append(tag) ...
1b31df0b72fff2317f3658c6c085d8ae86f03e9a
681,728
def step_decay(epoch_ix, lr, step_size=10, decay_factor=0.5): """ Defines 'step_decay'-type learning rate schedule, to be used in keras.Callbacks.LearningRateScheduler. Input epoch_ix: index of epoch lr: current learning rate step_size: positive interger, number of episodes afte...
43608166f5610d349db6ef78354d9d8853dd77ad
514,600
def process_nlp_response(get_response): """ This function takes as input an NLP GET response and returns a list of concept codes. Input: get_response - A list of GET responses Output: codes - A list of concept Codes """ keep = ["ICD9CM", "ICD10CM", "RXNORM", "SNOMEDCT_US", "SNOMED", "NCI"]...
0afb8a28664d51fdbed7a670afbac817795901f1
658,401
def getFingerPrintOnCount(A): """ Input: Iterable having boolean values 0 or 1 Output: Count of number of 1 found in A """ count = 0 for i in A: if(i == 1): count += 1 return count
d5cfebcd440826c0502b46e0cc75cc434efb1c7b
656,870
def half_full_to_half(data): """ Convert single half court movement to shot log dimensional movement Parameters ---------- data: pandas.DataFrame dataframe containing SportVU movement data that is converted to a single half court (x_loc < 47) Returns ------- data: panda...
8cd178ae6ce26c7762cdad4887ab3bbab089f8bf
560,982
def get_numeric_columns(df): """get all numeric columns' names Parameters ---------- df : [pandas.DataFrame] the dataset Returns ------- list list of numeric column names """ numeric_cols = df.select_dtypes("number").columns.tolist() return numeric_cols
7d4d0b4fc42f89c5ec28e1c02074a84af2935999
379,167
def filter_by_ids(original_list, ids_to_filter): """Filter a list of dicts by IDs using an id key on each dict.""" if not ids_to_filter: return original_list return [i for i in original_list if i['id'] in ids_to_filter]
c411fbb21bbd9828a389f0ca89b98983c4a81200
240,268
def _is_or_is_not(bool_value): """Produces display text for whether metadata is applicable to artifact. Args: bool_value: a BoolValue instance. Returns: A str with value "is" if bool_value is True, else "is not". """ return "is" if bool_value else "isn't"
23a141a8eee7c63c592c0676217c8559bf585369
216,256
def find_nearest_datapoint(lat, lon, ds): """Find the point in the dataset closest to the given latitude and longitude""" datapoint_lats = ds.coords.indexes["latitude"] datapoint_lons = ds.coords.indexes["longitude"] lat_nearest = min(datapoint_lats, key=lambda x: abs(x - lat)) lon_nearest = min(dat...
ffc106e0ac092ce32d0e499369898f2139ac9ab9
648,919
def get_values(worksheet, start_row=1): """ Get the values stored in the cells from the second row onwards. Returns a list of each row of the worksheet as a list i.e. [ [row2_col1_value, row2_col2_value, ... ], [row3_col1_value, ... ], ... ]. Cells that contain a datetime object as the value will be con...
879ce3307ecfb73f599039d0cce5086453ca1ed4
551,263
def _create_padded_message(message: str) -> str: """Create padded message, used for encrypted responses.""" extra = len(message) % 16 return (16 - extra) * "0" + message
616b36648a1f4d39354fd5978d532a97edd7e156
669,064
def get_member_profile_image_upload_path(instance, filename): """ Construct the upload path for a given member and filename. """ return str("member/{0}/profile-images/{1}").format(instance.user.id, filename)
8b6486e881ac487a128a882f8b624c0ef445f467
188,953
def AveragePool(self, name, in_t, attrs): """ Create and add AveragePool op to Graph """ out_t = self.layer(op="AveragePool", name=name, inputs=[in_t], outputs=[name], attrs=attrs)[0] out_t.name = "{}_out_0".format(name) return out_t
bbfefb9f0d63021d12bd57f2023d08a4bb360fa3
499,797
import math def format_float(number, decimal_places): """ Accurately round a floating-point number to the specified decimal places (useful for formatting results). """ divisor = math.pow(10, decimal_places) value = number * divisor + .5 value = str(int(value) / divisor) frac = value.sp...
e7aaa92025284489075ce053319c27310bb96a00
704,662
import itertools def relative_bics(saveresult): """ This convenience function calculates all the relative BIC comparisons from an AFINO save result. Parameters ---------- saveresult : dict An AFINO save result dictionary. Can be restored from a previous save file Returns ----...
d84516b75103991f6ac4aa26552890cfc19c8616
212,178
def load_vocab(vocab_file): """ :param vocab_file: one character per line :return: labels: list of character """ labels = [] with open(vocab_file, "r", encoding="utf-8") as f: for line in f: line = line.strip() labels.append(line) return labels
d7cebbcdd529d11f8db5fe4d7d2e4c6300c0c023
577,176
import math def ci_to_sd(lowerci, upperci, cival=95.0, size=100): """ Converts Confidence interval to Mean and Standard deviation. Parameters: lowerci (float, required): The lower bound of the confidence interval. upperci (float, required): The upper bound of the confidence ...
76bb3b0d905501cfdb3edc6b41e425f6df997ace
411,839
import requests def download_holdings_file(holdings_file_url, file_extension, ticker): """Download a holdings list file (CSV, Excel, PDF, Json) from a URL and save it locally. :param holdings_file_url: The URL from which the holdings file can be downloaded. :param file_extension: The expected file type (...
b48d3bcd5b11c147cb5e2492b6020e7d0f028bc9
247,827
import yaml def load_yaml_file(filename): """Loads dictionary from yaml file. Args: filename: file to read from Returns: Dict """ with open(filename) as f: contents = yaml.load(f, Loader=yaml.FullLoader) return contents
a6e70c21d4f0001f301c519409abdf12a42d71b5
659,477
import jinja2 def make_jinja_env(templates_dir): """ Create the default Jinja environment given the template folder. Parameters ---------- templates_dir : str or pathlib.Path The path to the templates. Returns ------- env : jinja2.Environment The environment used to r...
79d03ae0aeaf7dafed04001e44b2446756313444
662,749
def readRawChats(inFile): """ Reads .csv file and split into transcripts by splitting on the Timestamp which includes the Date. The returned transcriptList is a list-of-lists where each "outer" list item contains information about a single chat. """ inFile = open(inFile, "r") # N...
8e16bb290e2c613ccd3c00148293f55d01de128a
410,172
def read_in(path): """Read in a file, return the str""" with open(path, "r") as file_fd: return file_fd.read()
e9b407ef45aefd2efaf47fdb729ef71130c4e163
85,216
import re def apply_correction(message, pattern, replacement): """ Replaces all occurences of pattern in message with replacment. It tries to treat the pattern and replacement as regular expressions, but falls back to string replace if that fails. """ try: message = re.compile(patter...
359857f7394a98b872031cd9692ee188fd8018dd
215,651
def get_configuration_attribute(attribute, class_obj, default=None): """ Look for an attribute in a class and return if present Otherwise return the specified default :param attribute: String - Name of attribute to look for :param class_obj: Class - Class to look for attribute :param default: S...
5ae51ad5ff2b34733501eb4f2c97d36a2382d9a3
136,216
def resize_image(image, tuple_wh, preserve_aspect=True): """Resizes an instance of a PIL Image. In order to prevent un-intended side effects, this function always returns a copy of the image, as the resize function from PIL returns a copy but the thumbnail function does not. Args: ima...
8446233e07061b7145f02ed34c126fc0afa25d81
275,947
def parse_item_and_prep(item_and_prep): """Parse an ingredient listing into the food item and preparation instructions.""" components = [i.strip() for i in item_and_prep.split(',')] return components[0], ' '.join(components[1:])
1660b2f677855d873e1683b69cad4b079a13f0c1
287,213
import re def format_sql_query(sql: str, page: int, per_page: int) -> str: """ Formats an sql query with the required limit and offset. :param sql: original sql query (string) :param page: number of the current page (int) :param per_page: number of records per page (int) :return: (str) ""...
863b0801d61963a36f68f639457e55f8d17d1dd7
337,012
def get_move(old_i, new_i): """ Returns a string corresponding to the move between two positions of a tile old_i: a tuple representing the old index of the tile new_i: a tuple representing the new index of the tile """ dx = new_i[0] - old_i[0] dy = new_i[1] - old_i[1] if dx > ...
56189e7853d79ad6cd7ac79bc9a8c3571b3175ec
560,889
def build_endpoint(route, target=None): """Build a REST endpoint string by joining route and target. Args: route (:obj:`str`): Route part of endpoint. target (:obj:`str`, optional): Target part of endpoint. Defaults to None. Returns: :obj:`str` ...
9f22fdb79926407b052a5d1c28dbeea81de4c502
291,834
from datetime import datetime def cid_to_date(cid): """Converts a cid to date string YYYY-MM-DD Parameters ---------- cid : int A cid as it is generated by the function ``utils.create_cid()`` Returns ------- str A string formated date (e.g. YYYY-MM-DD, 2018-10-01) """...
ab919f9cfd5c56f6fb6b65cbae8731687fc42faf
708,289
def parse_game_features(s): """ Parse the game features we want to detect. """ game_features = ['target', 'enemy', 'health', 'weapon', 'ammo'] split = list(filter(None, s.split(','))) assert all(x in game_features for x in split) return [x in split for x in game_features]
de436221f5749484b0fa6767eb55c99502f4aaa3
198,591
import torch def skip_special_tokens(tensor, device, special_token_ids): """Filters out special tokens by ids in the given 1D tensor. Adapted from https://stackoverflow.com/a/62588955 Args: tensor (tensor): PyTorch Tensor device (str): Device, usually "cpu" or "cuda:0" token_ids ...
804e200286e53b9c07d93fa10059b4be1b1720ca
332,412
def cross_entropy_binary_der(y_true, y_pred, delta=1e-9): """ The derivative of binary cross-entropy. The derivative of the cross-entropy function (i.e. derivative of the error output) with respect to the predicted value (y_pred). The value inside the brackets is the value of the derivative of ...
58eb19301901b3ded417cd75b48da026eaed1f3e
531,473
import contextlib import socket def check_connection(host=None, port=None, timeout=None): """Checks whether internet connection is available. :param host: dns host address to lookup in. :param port: port of the server :param timeout: socket timeout time in seconds :rtype: bool :return: True i...
8cd42f7039407633c37ccb40c60a230f47dc0695
197,755
def mps_to_mph(mps): """ Convert meters per second to miles per hour (floats) """ return mps / 0.44704
ba56b3ae78f9f82e73ef204058ee4d0508547212
515,932
import ast def _get_last_child_with_lineno(node): """ Return the last direct child of `node` that has a lineno attribute, or None if `node` has no such children. Almost all node._field lists are sorted by the order in which they appear in source code. For some nodes however, we have to skip some ...
6ab189384f596edb4017c3f0be3a1a34cface69b
149,104
def set_dont_care(key, parkeys, dont_care): """Set the values of `key` named in `dont_care` to 'N/A'.""" key = list(key) for i, name in enumerate(parkeys): if name in dont_care: key[i] = 'N/A' return tuple(key)
017c93495c8d165688ece6e5721aa5cf4408454f
242,991
def _capitalize_first_letter(word): """ Capitalizes JUST the first letter of a word token. Note that str.title() doesn't work properly with apostrophes. ex. "john's".title() == "John'S" """ if len(word) == 1: return word.upper() else: return word[0].upper() + word[1:]
30fbc276c238dcb601b4da7d7ed99007f9de26c4
436,256
def sum_hours(entries): """Return the sum total of get_total_seconds() for each entry.""" return sum([e.get_total_seconds() for e in entries])
1522bb65b3fc5bbe73360f9efc3362681fbe9c93
612,756
def boost(d, k=2): """Given a distance between 0 and 1 make it more nonlinear""" return 1 - (1 - d)**k
2dcead669de9c3781ab5c85d8a72e445130628c5
358,671
def imul_cupydense(cpd_array, value): """Multiply this CuPyDense `cpd_array` by a complex scalar `value`.""" return cpd_array.__imul__(value)
2b70d367e6395637942ea9d5d6c553390c3da36f
513,221
def _get_shock_sds(params, info, dimensions): """Create the array of standard deviations of the shocks in transition functions.""" return params[info["shock_sds"]].reshape(-1, dimensions["n_states"])
6c60e35190f814b52f0950723ea7927f05960a45
224,991
from typing import List import pathlib from typing import Dict from typing import Any import pickle def _open_hydra_pickles(paths: List[pathlib.Path]) -> Dict[str, Any]: """Open pickles in directory of Hydra log and return dict of data. Parameters ---------- paths : List[pathlib.Path] Paths t...
fc5b187549251fc7aba7e711b64551e254bfde8d
662,755
def get_formatted_name(first_name, last_name): # Describe the function """Return a full name, neatly formatted.""" # The names are joined into full name formatted_name = first_name + ' ' + last_name # return the value, don't do anything with it yet return formatted_name.title()
7fa7a9eb576458322ecebe07b3bab9c92f9b9d05
540,031
def _decompress(indices): """ Convert a str representing a sequence of entries into a list. :param indices: One line in the custom input data that represents a sequence of entries in a list. See module docstring for information on the file format. :type indices:...
04f41a88efc6b2579c957412cf459d2435fd2e46
413,670
def collector_url_from_hostport(host, port): """ Create an appropriate collector URL given the parameters. """ return ''.join(['http://', host, ':', str(port), '/api/v1/spans'])
75367231b2c4e1b1131b84e04303f1b99e48d992
228,106
def _read_file(path): """reads a file given by path, removes trailing white spaces, tabs and new lines and returns result""" with open(path) as attrib: data = attrib.read() return data.rstrip(' \t\n\r')
681805d92bb8d731adcabe593d921c23b37f1ad5
199,237
def get_message_template_params(case): """ Data such as case properties can be referenced from reminder messages such as {case.name} which references the case's name. Add to this result all data that can be referenced from a reminder message. The result is a dictionary where each key is the object'...
013a3224194ce9abc97ea828398d2ab251cbb258
309,278
def strike_a_match(str1, str2): """Implements Dice Bi-Grams metric. str1, str2: str Input values in unicode. Returns ------- float A similarity score normalized in range [0,1]. """ pairs1 = {str1[i:i + 2] for i in range(len(str1) - 1)} pairs2 = {str2[i:i + 2] for i in r...
4665d675536e30a7a529dbca7b26c7cf8ae389dc
196,727
def get_null_stats(df): """ Function that will return count (absolute and relative) of null values in each column in `df`. Parameters ---------- df : pandas.DataFrame DataFrame on which this function will operate. Return ------ pandas.DataFrame with `df.columns` as row ...
aca977692497682b1360998f646034cbed841477
584,658
def is_preview_request(request): """ Return true if this is a request for a task preview """ return ('assignmentId' not in request.GET or request.GET['assignmentId'] == 'ASSIGNMENT_ID_NOT_AVAILABLE')
19901bf095159eeb0208f16da85b5568cc0fe087
455,709
def future_value(interest, period, cash): """(float, int, int_or_float) => float Return the future value obtained from an amount of cash growing with a fix interest over a period of time. >>> future_value(0.5,1,1) 1.5 >>> future_value(0.1,10,100) 259.37424601 """ if not 0 <= interest...
a2a69434c78f29ee15e6c4e00b65746c0327dac5
609,660
def read_submission_file(f_sub_name): """ Reads in a submission file Parameters ---------- f_sub_name : submission file name Returns ------- predicted_ctr : a list of predicted click-through rates """ f_sub = open(f_sub_name) predicted_ctr = [] for line in f_sub: ...
e7d0a6282a5ec8d9d45b0a31372ec4eaec2ff339
238,170
def maximum_weighted_independent_set_qubo(G, weight=None, lagrange=2.0): """Return the QUBO with ground states corresponding to a maximum weighted independent set. Parameters ---------- G : NetworkX graph weight : string, optional (default None) If None, every node has equal weight. If a s...
21b2ebeca0a4f84523c0d0712c5add9c5b0ca9e2
559,242
def scraped_table_to_list(table): """Convert the scraped table to a multidimensional list. Args: table: table to scrape Returns: data scraped from soup of table """ return [[cell.text for cell in row.find_all(['th', 'td'])] for row in table.find_all('tr')]
c1de9a932cedc60d6b272cceebcce1f6c45e37e6
149,060
from typing import Union def numify(variable: str) -> Union[int, float, str]: """Attempts to convert 'variable' to a numeric type. If 'variable' cannot be converted to a numeric type, it is returned as is. Args: variable (str): variable to be converted. Returns variable (int, fl...
a61b2b714318dc6eef8e82040e8d3ccbfbe439ef
221,971
def get_list_b_nodes_without_area(city): """ Returns list of building node ids without area parameter. Requires osm call to generate city obejct, first! Parameters ---------- city : object City object generated with osm call Returns ------- list_missing_area : list (of ints...
c592054fc2283fa8ea490fb49f776484e313fcfa
569,966
def is_coplanar(points): """Check if 4 points lie on the same plane""" a1 = points[1].x - points[0].x b1 = points[1].y - points[0].y c1 = points[1].z - points[0].z a2 = points[2].x - points[0].x b2 = points[2].y - points[0].y c2 = points[2].z - points[0].z a = b1 * c2 - b2 * c1 b = a...
404a275dbaa829c797d6cd52f2e761083940110f
474,420
def first_word(sentence): """Return first word of a string.""" try: return sentence.split(' ', 1)[0] except: return None
c7938a06b7f6ae4169b622863ed8285e173f34a0
631,286
def magic_index(arr): """ 8.3 Magic Index: A magic index in an array A [ 0... n -1] is defined to be an index such that A[i] = i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A. FOLLOW UP What if the values are not distinct? For d...
3f89d0c2ce8f9fbfb7c268e49e7a074a360201a2
512,443
import typing def discretize_layer(width: float, stretch_factor: float = 1.3, minimum_division=0.001, maximum_division=0.2) \ -> typing.List[float]: """ Creates a subdivision of the material to be used for the discretization. :param width: Width of the material to be subdivided :param minimu...
405c04635e5b895c6dbca013d3edd7e83564161e
313,856
from pathlib import Path def ensure_file(file_path: Path) -> Path: """Ensure that file exists""" file_path.parent.mkdir(parents=True, exist_ok=True) file_path.touch(exist_ok=True) return file_path
80bfadc9fea62f5982a8666325ff041a7029901a
345,350
def get_response(action, next): """Returns a fairly standard Twilio response template.""" response = """<?xml version="1.0" encoding="UTF-8"?> <Response> {action}<Redirect method="GET">{next}</Redirect> </Response>""" return response.format(action=ac...
55cf089fa806d57eff530e0f6f8121b08a52a2b6
319,501
def _primary_artist(artist): """ Utitlity function that tries to only get the main artist of a song. Example: "Tyler featuring Xyz" would just return "tyler" """ artist = artist.casefold() artist = artist.split('featuring')[0].strip() artist = artist.split('/')[0].strip() artist = a...
5d3214b4fec24552487a75a53f3abd3516efcdbd
186,639
from typing import Any def to_len(value: Any) -> int: """Get the length of a value. The value is converted to string and the number of characters in the resulting string is returned. Parameters ---------- value: any Value whose length is returned. Returns ------- int """ ...
9980653b8e6682019ac19a317b67b8f7f9138714
111,004
def print_square(num: int = 20) -> str: """Output the square of a number.""" result = num ** 2 return f"The square of {num:.2} is {result:.2}."
29aefdbedcd8c05a71a1b72beae48ed9ce0c6954
126,367
def m21_midievent_to_event(midievent): """Convert a music21 MidiEvent to a tuple of MIDI bytes.""" status = midievent.data + midievent.channel - 1 return (status, midievent.pitch, midievent.velocity)
3950b4e6715ac4de2dbdcc2d87d5cf51387a220c
703,261
def calc_tot_orbits(n_orbit_dict): """Calculate the total number of direct and indirect orbits in n_orbit_dict. Parameters ---------- n_orbit_dict : dictionary A dictionary where each key is an object in the system and each value is a tuple of 2 values. The first represents the numb...
07a9dbc11866b9710503ef8fe75297c14aa0b6c9
638,743