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'], key=lambda f: f['duration'], reverse=True)
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 Yes or No (y/n):').lower() if userInput in list(AcceptableResponses.keys()): return AcceptableResponses[userInput] else: print(""" Invalid input - not recognized as yes or no \n [Proper response required to exit loop]""")
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 of Facebook friends. :type friend_list: list of pynder.models.friend.Friend :return: Friend's name. :rtype: str """ for friend in friend_list: if connection_id == friend.facebook_id: return friend.name return ''
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_cumsum = [increasing_numbers[0]] for e1, e2 in zip(increasing_numbers[:-1], increasing_numbers[1:]): inv_cumsum.append(e2 - e1) return inv_cumsum
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 return items[offset:end]
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(rptr, cptr, length): raise RuntimeError('memmove failed') return res
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.rename({'x_bins':'x','y_bins':'y'}) return downsampled
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: ValueError: ``real_ip`` must have 4 blocks separated with a dot. Args: real_ip (str): Full IPv4 address. Returns: str: ``real_ip`` with the last `byte` zeroed. """ anonymized_ip = real_ip.split(".") if len(anonymized_ip) != 4: raise ValueError("Bad format of the IP address '" + real_ip + "'") anonymized_ip[3] = "0" return ".".join(anonymized_ip)
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 // 3600)) seconds = seconds % 3600 if seconds > 59: out.append('%sm' % (seconds // 60)) seconds = seconds % 60 if seconds > 0: out.append('%ss' % seconds) return ' '.join(out)
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 the order: [red, green, blue] """ red_avg = sum([x.red for x in pixels])//len(pixels) green_avg = sum([x.green for x in pixels])//len(pixels) blue_avg = sum([x.blue for x in pixels])//len(pixels) return [red_avg, green_avg, blue_avg]
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") col_binary = col_string.replace("L", "0").replace("R", "1") row_num = int(row_binary, 2) col_num = int(col_binary, 2) return 8 * row_num + col_num
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' @register('projects_by_scm_type', 1) def projects_by_scm_type(): return {'git': 5, 'svn': 1} """ def decorate(f): f.__awx_analytics_key__ = key f.__awx_analytics_version__ = version f.__awx_analytics_description__ = description f.__awx_analytics_type__ = format f.__awx_expensive__ = expensive return f return decorate
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 correctly set `event_shape` (be careful). Args: z: Sample or samples from the variational distribution `q_distrib`. q_distrib: Variational distribution. p_distrib: Target distribution. Returns: tuple: Spatial KL divergence and log-likelihood of samples under q and under p (torch.Tensor) """ q_logprob = q_distrib.log_prob(z) p_logprob = p_distrib.log_prob(z) kl_dwise = q_logprob - p_logprob return kl_dwise, q_logprob, p_logprob
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 """ merged = [] intervals.sort(key=lambda x: x[0]) for i in range(len(intervals)): if not merged or intervals[i][0] > intervals[i - 1][1]: merged.append(intervals[i]) else: merged[-1][1] = max(merged[-1][1], intervals[i][1]) return merged
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 Block: #0<data> :param block: IEEE block. :type block: bytes | bytearray :return: (offset, data_length) :rtype: (int, int) """ # Function copied from pyVISA # copyright: 2014 by PyVISA Authors, see AUTHORS for more details. # license: MIT, see pyVISA LICENSE for more details. begin = block.find(b'#') if begin < 0: raise ValueError("Could not find hash sign (#) indicating the start of" " the block.") try: # int(block[begin+1]) != int(block[begin+1:begin+2]) in Python 3 header_length = int(block[begin + 1:begin + 2]) except ValueError: header_length = 0 offset = begin + 2 + header_length if header_length > 0: # #3100DATA # 012345 data_length = int(block[begin + 2:offset]) else: # #0DATA # 012 data_length = len(block) - offset - 1 return offset, data_length
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 finally: self._json = None return r return wrapper
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: method = words[0] uri = words[1] return { "method": method, "uri": uri }
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 mode (str): the file open mode, ie "r", "w" Returns: file: the new filehandle """ newhandle = open(path, mode) if fhandle: fhandle.flush() fhandle.close() return newhandle
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 otherwise. """ return True if board[int(position[0])][int(position[1])] == "-" else False
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 """ ffmiddles = { "mp3": " -codec:a libmp3lame -ac 2 -qscale:a 2 ", "wav": " -ac 2 -acodec pcm_s16le " } return(ffmiddles[ext_to.lower()])
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) previous_tag = tag names.append(name) else: if previous_tag == 'O': iob2_tags.append('B-' + tag) else: iob2_tags.append('I-' + tag) previous_tag = tag names.append(name) return names, iob2_tags
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 after which learning rate will adapt decay_factor: factor by which lr will be multiplied Returns learning rate as a function of lr and epoch_ix """ if ((epoch_ix > 0) and ((epoch_ix % step_size) == 0)): lr = lr * decay_factor return lr
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"] codes = [] for dict_entry in get_response["documents"]: for entity in dict_entry["entities"]: if "links" in entity.keys(): for link in entity["links"]: if link["dataSource"] in keep: codes.append( [ dict_entry["id"], entity["text"], entity["category"], entity["confidenceScore"], link["dataSource"], link["id"], ] ) return codes
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: pandas.DataFrame dataframe containing SportVU movement data that is converted to the single shooting court that follows shot log dimensions (-250-250, -47.5-422.5) """ # convert to half court scale # note the x_loc and the y_loc are switched in shot charts from movement data (charts are perpendicular) data['x_loc_copy'] = data['x_loc'] data['y_loc_copy'] = data['y_loc'] # Range conversion formula # http://math.stackexchange.com/questions/43698/range-scaling-problem data['x_loc'] = data['y_loc_copy'].apply(lambda y: 250 * (1 - (y - 0)/(50 - 0)) + -250 * ((y - 0)/(50 - 0))) data['y_loc'] = data['x_loc_copy'].apply(lambda x: -47.5 * (1 - (x - 0)/(47 - 0)) + 422.5 * ((x - 0)/(47 - 0))) data = data.drop(['x_loc_copy', 'y_loc_copy'], axis=1, inplace=False) return data
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(datapoint_lons, key=lambda x: abs(x - lon)) return lat_nearest, lon_nearest
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 converted into string object with the 'mm/dd/yy' format. """ values = list() for row in worksheet.iter_rows(min_row=2): db_row = list() for cell in row: if cell.is_date: db_row.append(cell.value.strftime('%x')) elif cell.data_type == cell.TYPE_STRING: db_row.append(cell.value.strip().replace('\'', '\'\'')) else: db_row.append(cell.value) values.append(db_row) return values
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.split('.')[1] trail_len = decimal_places - len(frac) return value + ''.join(['0'] * trail_len)
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 ------- dbic_values : dict A dictionary of relative BIC value comparisons, i.e. BICa - BICb for every a,b pair """ bics = [] ids = [] dbic_values = {} for key in saveresult: bics.append(saveresult[key]['BIC']) ids.append(int(saveresult[key]['ID'])) # extract all the ID and BIC pairs (includes reverse pairings) combo_list = list(itertools.permutations(ids)) combo_bic_list = list(itertools.permutations(bics)) # for each ID/BIC pair a,b, put BICa - BICb in a dictionary for i, combo in enumerate(combo_list): dbic_values['dBIC_' + str(combo[0]) + '_minus_' + str(combo[1])] = combo_bic_list[i][0] - combo_bic_list[i][1] return dbic_values
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 interval. cival (float, optional): The confidence level. It must be one of the following values. [99.9,99.5,99.0,95.0,90.0,85.0,80.0] The default value is 95 for 95% confidence interval. size (int, optional): The size of the sample to be generated. The default value is 100. Returns: float: A float value for Standard deviation. """ zvals = {99.9:3.291, 99.5:2.807, 99.0:2.807, 95.0:1.960, 90.0:1.645, \ 85.0:1.645, 80.0:1.282} zscore = zvals[float(cival)] sdev = math.sqrt(size)*(upperci-lowerci)/zscore return sdev
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 ('csv', 'xlsx', 'pdf', 'json'). :param ticker: The fund ticker symbol to ensure a unique file name when saved. :returns: The filename of the downloaded holdings file. """ r = requests.get(holdings_file_url, headers={'User-Agent': 'Mozilla/5.0'}, allow_redirects=True) filename = 'holdings-{}.{}'.format(ticker, file_extension) open(filename, 'wb').write(r.content) return filename
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 render the templates. """ # Need to add the current dir so we can use the Markdown files as templates env = jinja2.Environment( loader=jinja2.FileSystemLoader([str(templates_dir), "."], followlinks=True), extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols"], ) return env
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") # NOTE .csv file assumed to have column-headings line dateAtStartCount = 0 transcriptList = [] currentTranscriptLines = [] for line in inFile: frontOfLine = line[:6] if frontOfLine.count("/") == 2: dateAtStartCount += 1 if dateAtStartCount == 1: #ignore header line currentTranscriptLines = [line.strip()] else: transcriptList.append(currentTranscriptLines) currentTranscriptLines = [line.strip()] else: currentTranscriptLines.append(line.strip()) transcriptList.append(currentTranscriptLines) return transcriptList
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(pattern).sub(replacement, message) except: message = message.replace(pattern, replacement) return message
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: String - The default to be returned if the attribute does not exist, Default: None """ if hasattr(class_obj, attribute): return getattr(class_obj, attribute) else: return default
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: image: An instance of a PIL Image. tuple_wh: A tuple containing the (width, height) for resizing. preserve_aspect: A boolean that determines whether or not the resizing should preserve the image's aspect ratio. Returns: A resized copy of the provided PIL image. """ if preserve_aspect: img_cpy = image.copy() img_cpy.thumbnail(tuple_wh) return img_cpy else: return image.resize(tuple_wh)
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) """ terminator_regex = r";" limit_string = " LIMIT {} OFFSET {};".format(per_page, per_page * (page-1)) if not re.search(terminator_regex, sql): return sql + limit_string return re.sub(terminator_regex, limit_string, sql)
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 > 0: return "left" elif dx < 0: return "right" elif dy > 0: return "up" elif dy < 0: return "down" else: return ""
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` """ target = "" if target is None else "/{}".format(target) return "{}{}".format(route, target)
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) """ return datetime.utcfromtimestamp( cid/10000000.0 ).strftime("%Y-%m-%d")
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 (set): List of Token IDs """ special_token_id_tensor = torch.unique(torch.as_tensor(special_token_ids)).to( device ) return tensor[ ~tensor.unsqueeze(1).eq(special_token_id_tensor.unsqueeze(1)).any(1) ].tolist()
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 the log-likelihood for a bernoulli distribution. The negative is added because of our definition of cross-entropy. Parameters ---------- y_true : numpy array True, observed values. The outcome of an event (where 1 == success). y_pred : numpy array The predicted success probabilities. delta : float, optional A small, positive constant to offset predicted probabilities that are zero, which avoids log(0). Is ignored if delta = 0. The default is 1e-9. Returns ------- float The derivative of binary cross-entropy. """ # Compute the cross-entropy cost # To avoid log(0) errors (not necessary in most cases) ypred = y_pred.copy() if delta != 0: ypred[ypred <= delta] = delta ypred[ypred >= 1-delta] = 1-delta return -((y_true/ypred) - (1-y_true)/(1-ypred))
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 if available False otherwise """ if not host: host = '8.8.8.8' if not port: port = 53 #: Family and Type will be default with contextlib.closing(socket.socket()) as sock: sock.settimeout(timeout) with contextlib.suppress(socket.error): sock.connect((host, port)) return True return False
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 fields that either don't have line numbers (e.g., "ctx" and "names") or that are in the wrong position (e.g., "decorator_list" and "returns"). Then we choose the first field (i.e., the field with the highest line number) that actually contains a node. If it contains a list of nodes, we return the last one. """ ignored_fields = {"ctx", "decorator_list", "names", "returns"} fields = node._fields # The fields of ast.Call are in the wrong order. if isinstance(node, ast.Call): fields = ("func", "args", "starargs", "keywords", "kwargs") for name in reversed(fields): if name in ignored_fields: continue try: last_field = getattr(node, name) except AttributeError: continue # Ignore non-AST objects like "is_async", "level" and "nl". if isinstance(last_field, ast.AST): return last_field elif isinstance(last_field, list) and last_field: return last_field[-1] return None
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 to Hydra pickles to load. Returns ------- Dict[str, Any] Dict of loaded data, where the key is the loaded file name without its extension. """ loaded_data = {} for path in paths: name = pathlib.Path(path).parent.name with open(path, 'rb') as f: opened_pickle = pickle.load(f) loaded_data[name] = opened_pickle return loaded_data
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: str :returns: The decompressed list :rtype: list of float Examples: >>> _decompress("2x3.0 1x4.2 3x2.0") [3.0, 3.0, 4.2, 2.0, 2.0, 2.0] >>> _decompress("3x0 2x5 3x4") [0.0, 0.0, 0.0, 5.0, 5.0, 4.0, 4.0, 4.0] """ decompressed = [] for entry in indices.split(" "): if "x" in entry: counter, value = entry.split("x") else: counter = 1 value = entry decompressed.extend(int(counter) * [float(value)]) return decompressed
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's name and each value is a dictionary of attributes to be referenced. Dictionaries can also be nested, so a result here of {"case": {"parent": {"name": "joe"}}} allows you to reference {case.parent.name} in a reminder message. At the moment, the result here is of this structure: { "case": { ...key:value case properties... "parent": { ...key:value parent case properties... } } } """ result = {"case": {}} if case: result["case"] = case.case_properties() parent_case = case.parent if case else None result["case"]["parent"] = {} if parent_case: result["case"]["parent"] = parent_case.case_properties() return result
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 range(len(str2) - 1)} union = len(pairs1) + len(pairs2) hit_count = 0 for x in pairs1: for y in pairs2: if x == y: hit_count += 1 break try: return (2.0 * hit_count) / union except: if str1 == str2: return 1.0 else: return 0.0
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 index and `["cnt", "ratio"]` (for absolute and relative counts, respectively) in column index. """ nulls = df.isnull().sum() nulls = nulls.rename("cnt").to_frame() nulls["ratio"] = nulls / len(df) return nulls.sort_values("ratio", ascending=False)
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 <= 1: raise ValueError('"interest" must be a float between 0 and 1') for d in range(period): cash += cash * interest return cash
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: line = line.strip().split(",") predicted_ctr.append(float(line[0])) #predicted_ctr.append(float(line)) return predicted_ctr
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 string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). Returns ------- QUBO : dict The QUBO with ground states corresponding to a maximum weighted independent set. Examples -------- >>> from dwave_networkx.algorithms.independent_set import maximum_weighted_independent_set_qubo ... >>> G = nx.path_graph(3) >>> Q = maximum_weighted_independent_set_qubo(G, weight='weight', lagrange=2.0) >>> Q[(0, 0)] -1.0 >>> Q[(1, 1)] -1.0 >>> Q[(0, 1)] 2.0 """ # empty QUBO for an empty graph if not G: return {} # We assume that the sampler can handle an unstructured QUBO problem, so let's set one up. # Let us define the largest independent set to be S. # For each node n in the graph, we assign a boolean variable v_n, where v_n = 1 when n # is in S and v_n = 0 otherwise. # We call the matrix defining our QUBO problem Q. # On the diagnonal, we assign the linear bias for each node to be the negative of its weight. # This means that each node is biased towards being in S. Weights are scaled to a maximum of 1. # Negative weights are considered 0. # On the off diagnonal, we assign the off-diagonal terms of Q to be 2. Thus, if both # nodes are in S, the overall energy is increased by 2. cost = dict(G.nodes(data=weight, default=1)) scale = max(cost.values()) Q = {(node, node): min(-cost[node] / scale, 0.0) for node in G} Q.update({edge: lagrange for edge in G.edges}) return Q
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, float, str) converted to numeric type, if possible. """ try: return int(variable) except ValueError: try: return float(variable) except ValueError: return variable
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) List with building node ids without area parameter """ list_missing_area = [] for n in city.nodes(): if 'node_type' in city.nodes[n]: if city.nodes[n]['node_type'] == 'building': if 'area' not in city.nodes[n]: list_missing_area.append(n) return list_missing_area
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 = a2 * c1 - a1 * c2 c = a1 * b2 - b1 * a2 d = (- a * points[0].x - b * points[0].y - c * points[0].z) # equation of plane is: a*x + b*y + c*z = 0 # # checking if the 4th point satisfies # the above equation if(a * points[3].x + b * points[3].y + c * points[3].z + d == 0): return True return False
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 distinct values we can recurse on the half of the array which is smaller, all the time. For non-distinct values, we have to recurse on all elements. """ def rec_magic_index(arr, left, right): if right < left: return [] if right - left == 0: if arr[right] == right: return [right] else: return [] middle = (right + left) / 2 left_magic_indices = rec_magic_index(arr, left, middle) right_magic_indices = rec_magic_index(arr, middle + 1, right) return left_magic_indices + right_magic_indices return rec_magic_index(arr, 0, len(arr) - 1)
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 minimum_division: Width of the smallest division :param stretch_factor: Increase in subdivisions :param maximum_division: Maximum size of a cell :return: List containing width of subdivisions """ processed_width = 0 next_ = minimum_division left_side = [] right_side = [] while processed_width < width: remaining = width - processed_width if next_*2 <= remaining: left_side.append(next_) right_side.append(next_) processed_width += next_*2 else: if remaining <= maximum_division: left_side.append(remaining) processed_width += remaining else: left_side.append(remaining/2) right_side.append(remaining/2) processed_width += remaining next_ = min(next_ * stretch_factor, maximum_division) new_grid = left_side + right_side[::-1] return new_grid
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=action, next=next)
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 = artist.split(' x ')[0].strip() return artist
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 """ return len(str(value))
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 number of direct orbits and the second the number of indirect orbits. Returns ------- n_direct_tot : int The number of direct orbits n_indirect_tot : int The number of indirect orbits """ n_direct_tot = sum([n_orbits[0] for n_orbits in n_orbit_dict.values()]) n_indirect_tot = sum([n_orbits[1] for n_orbits in n_orbit_dict.values()]) return n_direct_tot, n_indirect_tot
07a9dbc11866b9710503ef8fe75297c14aa0b6c9
638,743