content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def make_seqs(a, b): """ Makes mutliple sequences of length b, from 0 to a. The sequences are represented as tuples with start and stop numbers. Note that the stop number of one sequence is the start number for the next one, meaning that the stop number is NOT included. """ seqs = [] x = 0 while x < a: x2 = x + b if x2 > a: x2 = a seqs.append( (x, x2) ) x = x2 return seqs
5a8963572f2ce0d0baf85a99b2614f2c25ce9bde
230,954
def assume_in_vitro_based_enzyme_modification_assertions(ac): """ write a JTMS assumption specifying that in vitro-based evidence is acceptable @param ac:bool True if action is to assert!, False if action is to retract!, None to get the representation of the assumption @returns: a string representation of the appropriate JTMS assumption """ rep = "(accept-in-vitro-based-enzyme-modulation-assertions)" if ac == True: return "(assume! '%s 'dikb-inference-assumption)" % rep elif ac == False: return "(retract! '%s 'dikb-inference-assumption)" % rep else: return rep
a6bd257c257220bb719a29dda43b93b127a2c75d
452,856
def truncate(name: str, length: int = 50) -> str: """ Truncates a string and adds an elipsis if it exceeds the specified length. Otherwise, return the unmodified string. """ if len(name) > length: name = name[0:length] + "..." return name
7d00f1ce67029cfabc5dfb95da3a2f97d0beb578
256,929
from typing import List def extensions_to_glob_patterns(extensions: List) -> List[str]: """Generate a list of glob patterns from a list of extensions. """ patterns: List[str] = [] for ext in extensions: pattern = ext.replace(".", "*.") patterns.append(pattern) return patterns
a04ed356bfa5db7c0210b86dff832d32bfef6dbf
8,713
import itertools def zip_longest(*collections, **kwargs): """:yaql:zipLongest Returns an iterator over collections, where the n-th iterable contains the n-th element from each of collections. Iterates until all the collections are not exhausted and fills lacking values with default value, which is null by default. :signature: collection.zipLongest([args], default => null) :receiverArg collection: input collection :argType collection: iterable :arg [args]: collections for zipping with input collection :argType [args]: chain of collections :arg default: default value for lacking values, can be passed only as keyword argument. null by default :argType default: any type :returnType: iterator .. code:: yaql> [1, 2, 3].zipLongest([4, 5]) [[1, 4], [2, 5], [3, null]] yaql> [1, 2, 3].zipLongest([4, 5], default => 100) [[1, 4], [2, 5], [3, 100]] """ return itertools.zip_longest( *collections, fillvalue=kwargs.pop('default', None))
a618433c5b4d66127d0bdac4d6bfa53304a91a00
602,414
import types def isfunc(x): """Returns True if x is a function.""" return isinstance(x, types.FunctionType)
54597ccd7480da9e6fa602cdd764febfdc9cbba7
381,687
import re def intcomma(value, ndigits=None): """Converts an integer to a string containing commas every three digits. For example, 3000 becomes "3,000" and 45000 becomes "45,000". To maintain some compatibility with Django's intcomma, this function also accepts floats. Args: value (int, float, string): Integer or float to convert. ndigits (int, None): Digits of precision. Returns: str: string containing commas every three digits. """ try: if isinstance(value, str): float(value.replace(',', '')) else: float(value) except (TypeError, ValueError): return value if ndigits: orig = "{0:.{1}f}".format(value, ndigits) else: orig = str(value) new = re.sub(r"^(-?\d+)(\d{3})", r'\g<1>,\g<2>', orig) if orig == new: return new else: return intcomma(new)
e61569657989dedecc8c2f01d5f9ec960ed63073
373,182
def read_edge_list(path): """Read edge list in KONECT format.""" with open(path, 'r') as f: edge_list = set() for line in f: if not line.lstrip().startswith("%"): # ignore comments e = line.strip().split() edge_list.add((int(e[0]) - 1, int(e[1]) - 1)) # 0 index return list(edge_list)
54af1afc7ff55cd768b890d72eed176b82e4de9b
172,653
def filter_none_values(dict): """Return dictionary with values that are None filtered out""" return {k: v for (k, v) in dict.items() if v is not None}
3c14ad9a339f928be71e7ed88dfd93ff012d30d0
459,509
def inh2o2pascal(inh2o): """convert pressure in inches of water to Pascals""" return (inh2o * 1.0) / 0.00401865
a5ccacf016fd14cc826161e60ee8137404af5738
277,292
def velocity_transformation(frame_velocity: float, observed_velocity: float) -> float: """ Computes the velocity transformation for a given frame velocity and observed velocity. The frame velocity is the velocity of the new frame relative to this frame. The observed velocity is a velocity measured in this frame. The returned velocity is the velocity of the observed velocity in the new frame. Expects velocity as a multiple of c, i.e. velocity_in_mps = c * velocity. """ return (observed_velocity - frame_velocity) / ( 1 - frame_velocity * observed_velocity )
970b3392ee658afef81451cd31a9d31330169d41
249,106
import random def random_sequence( length ): """Return a random string of AGCT of size length.""" return ''.join([ random.choice( 'AGCT' ) for i in range(int( length ))])
288d09c4173fdafbdb8529f2318e38b306d4d552
358,427
def get_image_value(x, y, img): """Get pixel value at specified x-y coordinate of image. Args: x (int): horizontal pixel coordinate y (int): vertical pixel coordinate img (numpy.ndarray): image from which to get get pixel value Returns: float: pixel value at specified coordinate """ return img[y][x]
466815a7d84ae76ece32f1da01d2a103086e1e67
670,311
def decode_int(pool_im, coord): """Helper function that returns uint8 that was encoded in pool_im tile starting at pixel at coord. """ bin_cint = '' for i in range(8): bin_cint += str(pool_im[ coord[0], coord[1]+i, 0 ] - pool_im[ coord[0]+1, coord[1]+i, 0 ]) return int(bin_cint, 2)
6aa7ea82ab151ba175c0817ac895278095e83f0f
371,662
def fibonacci(n): """Given a positive int n, uses recursion to return the nth Fibonacci number.""" if n == 1 or n==2: return 1 elif n <= 0: return 0 else: return (fibonacci(n-1) + fibonacci(n-2))
1071009c3209f4a1b518829b41b60f0ecaa4abd5
201,420
def cver_t(verstr): """Converts a version string into a tuple""" if verstr.startswith("b"): return tuple([0,0,0,0]+list(cver_t(verstr[1:]))) return tuple([int(x) for x in verstr.split(".")])
73b4abd456551e678f44c0f940ad8d055993a345
691,660
import io def get_message_data(msg): """Returns ROS1 message as a serialized binary.""" buf = io.BytesIO() msg.serialize(buf) return buf.getvalue()
7173cd596c0f0be3be31dfcf580260fe025ebcb0
477,021
from typing import Type from typing import Any import typing def _is_list(field: Type[Any]) -> bool: """Returns True when the given type annotation is list[...].""" return typing.get_origin(field) is list
491b764a4255312f1cf89e740293650c89a8fd82
424,635
def get_actual_objname(full_object_name): """Given a object string full name (e.g 0&0&DEFINING_ORIGIN), returns its name (e.g DEFINING_ORIGIN). """ return full_object_name.split('&')[2]
e0dd644a16a1c6865e2354b36d2466661939d131
558,286
def create_listing_date(data): """Create listing date feature.""" data['Data_annuncio'] = (data['Riferimento e data annuncio'] .str.split('-') .str[-1] .str.strip() .astype('datetime64[D]')) return data
3d5698b948b7d16d87cc190114f5e6a887349821
143,817
def safe_compare_dataframes(first, second): """Compare two dataframes even if they have NaN values. Args: first (pandas.DataFrame): DataFrame to compare second (pandas.DataFrame): DataFrame to compare Returns: bool """ if first.isnull().all().all(): return first.equals(second) else: nulls = (first.isnull() == second.isnull()).all().all() values = (first[~first.isnull()] == second[~second.isnull()]).all().all() return nulls and values
1e0ce9c9de03973c7c0448ba0fafd25f399cda04
166,939
def merge_dicts(*dicts): """Merge two or more dicts, later ones replacing values of earlier ones. Note that only shallow copies are made of the dicts. @b Examples ``` a = dict(a=1, b=2, c=3) b = dict(c=-3, d=-4) c = merge_dicts(a, b) # Result: dict(a=1, b=2, c=-3, d=-4) ``` """ result = {} for d in dicts: result.update(d) return result
ade27bf5279671ba16af8b1f8ca9dfe881ed9e4b
166,310
import json def load_transition_types(transitions_uri): """Loads a transition .json file and returns a dictionary mapping transition ids to their types. transitions_uri - path to a .json file with the format { "modify_landscape_structure": "restoration", ... } returns a dictionary whose keys and values are found in the transitions json file""" transitions_file = open(transitions_uri) transitions_string = transitions_file.read() transition_dictionary = json.loads(transitions_string) return transition_dictionary
776f5dd548ac0bb7f4447a24623751f8faca7baf
611,370
import math def dist_calc(x, y): """Returns a distance calcultion fuction from a static (x, y)""" def func(x1, y1): return math.sqrt(math.pow(x1-x, 2) + math.pow(y1-y, 2)) return func
7a55c4b00c2a72eb64f1468b650d6195a791b32a
568,867
def add_value(attr_dict, key, value): """Add a value to the attribute dict if non-empty. Args: attr_dict (dict): The dictionary to add the values to key (str): The key for the new value value (str): The value to add Returns: The updated attribute dictionary """ if value != "" and value is not None: attr_dict[key] = value return attr_dict
93728d08c8cbaacc34b62f0437a5c4d2d0cc6ddc
521,527
def scilabel(value, precision=2): """Build scientific notation of some value. This is dedicated to use in labels displaying scientific values. Args: value (float): numeric value to format. precision (int): number of decimal digits. Returns: str: the scientific notation the specified value. """ man, exp = f'{value:.{precision}e}'.split('e') exp = int(exp) return fr'{man}\times 10^{{{exp}}}'
f0f2dcdbdb4d24f594c75381e8daf6a947eac0aa
367,094
def align16(address): """ Return the next 16 byte aligned address. """ return (address + 0x10) & 0xFFFFFFF0
e330b3eca5ab0997ec3f8b743486237572033929
339,813
import textwrap import html def pretty_text(data): """Unsescape the html characters from the data & wrap it""" if data is not None: return textwrap.fill(html.unescape(html.unescape(data)), width=60) else: return ""
f5baf58394b8578b26ad3cb95aff26867bc5f748
31,692
def isB(ner_tag: str): """ We store NER tags as strings, but they contain two pieces: a coarse tag type (BIO) and a label (PER), e.g. B-PER :param ner_tag: :return: """ return ner_tag.startswith("B")
b24752ccb3a83936157fa7a7e73b5591bc64a625
79,980
from typing import Iterable def flatten_iterable(its: Iterable, deep: bool = False) -> list: """ flatten instance of Iterable to list Notes: 1. except of str, won't flatten 'abc' to 'a', 'b', 'c' demo: [[[1], [2], [3]], 4] if deep is True: flatten to [1, 2, 3, 4] if deep is False, flatten to [[1], [2], [3], 4]. """ res = [] for it in its: if isinstance(it, str): res.append(it) elif isinstance(it, Iterable): if deep: res += flatten_iterable(it, True) else: res.extend(it) else: res.append(it) return res
4c17d75a7dde4d0b9002dedea2938deacfef813f
687,371
def canonicalShape(shape): """Calculates a *canonical* shape, how the given ``shape`` should be presented. The shape is forced to be at least three dimensions, with any other trailing dimensions of length 1 ignored. """ shape = list(shape) # Squeeze out empty dimensions, as # 3D image can sometimes be listed # as having 4 or more dimensions for i in reversed(range(len(shape))): if shape[i] == 1: shape = shape[:i] else: break # But make sure the shape # has at 3 least dimensions if len(shape) < 3: shape = shape + [1] * (3 - len(shape)) return shape
0f11a7298253fe9655846a663f5761cd17ae2880
681,045
def path2linkTuple(pathString): """ Converts a path expressed as a sequence of nodes, e.g. [1,2,3,4] into a tuple of link IDs for use with the Path object (see path.py), in this case ((1,2),(2,3),(3,4)) """ # Remove braces pathString = pathString[1:-1] # Parse into node list nodeList = pathString.split(",") # Now create tuple linkList = list() prevNode = nodeList[0] for i in nodeList[1:]: curNode = i linkID = '(' + prevNode + ',' + curNode + ')' linkList.append(linkID) prevNode = i return tuple(linkList)
e2a8cbe4f6a5918fa6acd1766618a6862190acce
513,908
def emphasis(text): """Returns a text fragment (tuple) that will be emphasized when displayed.""" return ('emphasis', text)
de47483ea93d954af33eb5329090a1d0334c289a
401,621
import math def atan_deg(value): """ returns atan as angle in degrees """ return math.degrees(math.atan(value) )
ad7f79e4ebbfc364bddb5f20afd01b8cf70f9c08
30,400
import torch def make_creep_tests(stress, temperature, rate, hold_times, nsteps_load, nsteps_hold, logspace = False): """ Produce creep test input (time,stress,temperature) given tensor inputs for the target stress, target temperature, loading rate Args: stress: 1D tensor of target stresses temperature: 1D tensor of target temperature rate: 1D tensor of target rates hold_times: 1D tensor of hold times nsteps_load: number of time steps to load up the sample nsteps_hold: number of time steps to hold the sample logspace (optional): log space the hold time steps """ nbatch = stress.shape[0] nsteps = nsteps_load + nsteps_hold stresses = torch.zeros(nsteps, nbatch) times = torch.zeros_like(stresses) temperatures = torch.zeros_like(stresses) for i, (s,t,lr,T) in enumerate(zip(stress,hold_times,rate,temperature)): stresses[:nsteps_load,i] = torch.linspace(0, s, nsteps_load) stresses[nsteps_load:,i] = s times[:nsteps_load,i] = torch.linspace(0, s / lr, nsteps_load) temperatures[:,i] = T if logspace: times[nsteps_load:,i] = torch.logspace(torch.log10(times[nsteps_load-1,i]), torch.log10(t), nsteps_hold+1)[1:] else: times[nsteps_load:,i] = torch.linspace(times[nsteps_load-1,i], t, nsteps_hold+1)[1:] return times, stresses, temperatures
9f252018c078158ffc7615aec5a194ced914f17f
127,401
def find_layer_id(layers_range, router_id): """ Find layer id of the router. Parameters ---------- layers_range : [type] list of router id range router_id : int [description] Returns ------- int layer id """ for itr, layer_range in enumerate(layers_range): if router_id in layer_range: return itr
49b800369f5c2b4c9854e5afb7e3d742875f9b46
179,083
def is_not_to_keep(is_under_a_day, index): """ Return if we should keep this based on if the duration is less than a day. :param is_under_a_day: :param index: :return: to keep or not """ index += 1 return not is_under_a_day[index]
ba4e16dfd3fd2f7382f27a4692b45b5b729c4afc
238,722
from typing import List def open_uniform_knot_vector(n: int, order: int) -> List[float]: """ Returns an open uniform knot vector for a B-spline of `order` and `n` control points. `order` = degree + 1 Args: n: count of control points order: spline order """ nplusc = n + order nplus2 = n + 2 knots = [0.] for i in range(2, nplusc + 1): if (i > order) and (i < nplus2): knots.append(knots[-1] + 1.) else: knots.append(knots[-1]) return knots
9ab62ea4ca3264c29c7c413084887e8c06172a13
180,647
def _write_a_tikz_coordinate(name, xy, num_fmt): """Write a TikZ coordinate definition. Parameters ---------- name : str TikZ coordinate identified / name. xy : list or tuple of floats (x, y)-coordinates. num_fmt : str Specification of the numbers format, e.g. '.4f'. Returns ------- str TikZ coordinate definition without newline char. """ fmt_str = "{:" + num_fmt + "}" tex_str = "\\coordinate ({:s})".format(name) tex_str += " at (" tex_str += ", ".join(map(fmt_str.format, xy)) tex_str += ");" return tex_str
5917bbe0fd97ff632a3ff8376f20b43ebdccbd5b
567,052
def abs2(src, target): """ compute the square absolute value of two number. :param src: first value :param target: second value :return: square absolute value """ return abs(src - target) ** 2
275e015bca3cae2f737b284f40861b3136936109
690,527
def process_to_dict(process): """Return nested dicts for the nested namedtuples of a process.""" # These lines are sort of like a deep version of _asdict(). stages = [stage._asdict() for stage in process.stages] for stage in stages: stage['progress_items'] = [pi._asdict() for pi in stage['progress_items']] stage['actions'] = [act._asdict() for act in stage['actions']] stage['approvals'] = [appr._asdict() for appr in stage['approvals']] process_dict = { 'name': process.name, 'description': process.description, 'applicability': process.applicability, 'stages': stages, } return process_dict
306e565fdaad76fa956e8706a9d2b605bce32a96
597,011
def parse_cfg(cfgfile): """ Takes a configuration file Returns a list of blocks. Each block describes a layer (usually) in the neural network to be built. Block is represented as a dictionary in the list """ file = open(cfgfile, 'r') # store the lines in a list lines = file.read().split('\n') # get rid of the empty lines lines = [x for x in lines if len(x) > 0] # get rid of comments lines = [x for x in lines if x[0] != '#'] # get rid of fringe whitespaces lines = [x.rstrip().lstrip() for x in lines] # To parse the files, we're going to create a key/value pair, and then # store each pair in a Python list block = {} blocks = [] # Now that we collapsed the config file, let's go through each line for line in lines: # This marks the start of a new block based on the CFG filename, i.e. [convolutional] if line[0] == "[": # If block is not empty, this means we're still building the previous block dict. # Since we're in an obviously new block with the "[", the first time through we'll # need to send the current block to the list, and empty the current block dictionary # so it can receive the next values. This is how we separate dict items for our list. if len(block) != 0: # Add the current block info to the list blocks.append(block) # Reset the block block = {} # Store in a key called 'type' the text of the line minus the brackets, # deleting any trailing characters. Since we cleared the block earlier the first time # through (denoted by the "["), the first layer of the block will always be a type # that is a text value of layer type block["type"] = line[1:-1].rstrip() else: # Since we're somewhere in the block where we're not figuring out layer type, # split the line pairs into a tuple of key and value using "=" as the break point key, value = line.split("=") # Converting the CFG key value pairs into block keys with values block[key.rstrip()] = value.lstrip() # This is so the last time through the loop the last block gets added blocks.append(block) return blocks
63feb42367ba00ab9a14073d6f34761d73378206
190,384
def parse_org_members(members_json): """ Extract what we need from Github orgs members listing response. """ return [{'login': member['login']} for member in members_json]
038eadc48a01bf5579acf0e8d6fcd3bba66a3623
103,206
import six def right_strip00(the_string): """Remove '\x00' bytes from the right end of a byte-string.""" assert isinstance(the_string, six.binary_type) return the_string.rstrip(bytes(b'\x00'))
fa5cad2716d24c2a0a67e42e7f0e9db0bb12a2fa
218,749
def overrides(interface_class): """ To be used as a decorator, it allows the explicit declaration you are overriding the method of class from the one it has inherited. It checks that the name you have used matches that in the parent class and returns an assertion error if not """ def overrider(method): """ Makes a check that the overrided method now exists in the given class :param method: method to override :return: the class with the overriden method """ assert method.__name__ in dir(interface_class) return method return overrider
e5264baf1c5a5d97b354a4db3b3a49ccb580c082
631,308
def calc_ineffdate(row, date_dict: dict): """Calculates the date a given SFHA was deemed ineffective based on whether the SFHA resides inside 2+ different LOMRs. Parameters ---------- row : Pandas Series A row of a pandas DataFrame date_dict : dict A dictionary of FLD_AR_IDs and all the LOMR EFF_DATEs associated with each. The EFF_DATEs should be ordered chronologically. Returns ------- pandas.Timestamp The timestamp a polygon went ineffective, or None """ fema_id = row["FLD_AR_ID"] adopt_date = row["EFFDATE"] ineff_date = None try: idx = date_dict[fema_id].index(adopt_date) try: ineff_date = date_dict[fema_id][idx+1] except IndexError: # The polygon has the most recent ADOPTDATE of all the LOMRs that # touch the polygon, and therefore doesn't have an INEFFDATE pass except KeyError: # The polygon was not duplicated pass return ineff_date
3c0c6b44d4917fc1341e6e0f6247c50363980571
195,273
def get_header(context, header_name): """Return all response header values that've been set for header_name.""" return [header[1] for header in context.headers if header[0] == header_name]
cc2fba51f028aa76b8864376d8010099de56cc50
627,748
def format_error(error_code, message): """ Converts an error_code and message into a response body """ return {"errors": [{"code": error_code, "message": message}]}
70319669a5504cf1b6c07cdc9ef1de5f04437f20
264,451
def get_location(local_dictionary:dict) -> str: """ Description: Function which gets the local location from the returned local dictionary from covid_API_request Arguments: local_dictionary {dict} : dictionary containing 3 sub dictionary's: 'data' (containing all covid data requested), 'lastUpdate', 'length', 'totalPages' Returns: local_location {str} : string value containing the name of the local location """ local_location = str(local_dictionary['data'][0]['areaName']) return local_location
eee208b97e1a8ac64e4bfe5eaa48f45600a67c34
383,774
def indent(string: str) -> int: """Count the indentation in whitespace characters. Args: string (str): text with indents Returns: int: Number of whitespace indentations """ return sum(4 if char == "\t" else 1 for char in string[: -len(string.lstrip())])
0a58beace80f6f3c5298ca2179f0fbbc40247362
363,108
import re def clean_identifier(identifier: str) -> str: """Removes all whitespaces from the identifier.""" return re.sub(r'\s+', '', identifier)
5a92edeab99e29c31752cfd452187793c88f444d
407,576
def by_newlines(*parts): """return parts joined by newline characters - Unix style""" return '\n'.join(parts)
16945a617456a2b82e6e814c0e40a188c716b10d
543,086
import re def get_include_count(f): """Get number of #include statements in the file""" include_count = 0 for line in f: if re.match(r'\s*#\s*include', line): include_count += 1 return include_count
b85b0c2c0c9d6ee1ec209ea2aef93fc62c296a02
112,218
def length_vector_sqrd_xy_numba(a): """ Calculate the squared length of the vector, assuming it lies in the XY plane. Parameters ---------- a : array XY(Z) components of the vector. Returns ------- float: The squared length of the XY components. """ return a[0]**2 + a[1]**2
e1dd9a5830e09318295ee79b2c5235e97059b05e
319,547
def crop(image, x, y, w, h): """ Crop image to given position and size """ image = image[y : y + h, x : x + w] return image
31c6cc695e632ee3c9ae58750e7ba3c5fe31ac7b
207,799
def ts_to_ms(ts): """ Convert second timestamp to integer millisecond timestamp """ return int(ts * 1e3)
2d4435eecc6eb68d3d4644195bc3eccdd212f970
316,862
def divide(x: float, y: float) -> float: """Divide :math:`x` by :math:`y` Arguments --------- x : float First number y : float Second number. Raises ------ ZeroDivisionError: If the denominator is zero Returns ------- float x / y """ if abs(y) < 1e-12: raise ZeroDivisionError("Cannot divede by zero") return x / y
2279f1fe2063a7bcc8a9086eb800fe5f2c01db99
223,040
def shave_batch_LFs(inLFs, border=(3, 3)): """ Shave the input light field by a given border. :param inLFs: a batch of input light fields of size: [B, H, W, S, T, C] :param border: border values :return: shaved light field """ h_border, w_border = border if (h_border != 0) and (w_border != 0): shavedLFs = inLFs[:, h_border:-h_border, w_border:-w_border, :, :, :] elif (h_border != 0) and (w_border == 0): shavedLFs = inLFs[:, h_border:-h_border, :, :, :, :] elif (h_border == 0) and (w_border != 0): shavedLFs = inLFs[:, :, w_border:-w_border, :, :, :] else: shavedLFs = inLFs[:, :, :, :, :, :] return shavedLFs
dfd85adada5a6027224093c2a2f89bd950b4c711
394,743
def is_df( df): """is_df Test if ``df`` is a valid ``pandas.DataFrame`` :param df: ``pandas.DataFrame`` """ return ( hasattr(df, 'to_json'))
fe5c111e8883ff64e3b63602e57aaa793ef710fa
42,721
def detect_missing_leap_days(ts_data): """Detect if a time series has missing leap days. Parameters: ----------- ts_data (pandas DataFrame) : time series """ feb28_index = ts_data.index[(ts_data.index.year % 4 == 0) & (ts_data.index.month == 2) & (ts_data.index.day == 28)] feb29_index = ts_data.index[(ts_data.index.year % 4 == 0) & (ts_data.index.month == 2) & (ts_data.index.day == 29)] mar01_index = ts_data.index[(ts_data.index.year % 4 == 0) & (ts_data.index.month == 3) & (ts_data.index.day == 1)] if len(feb29_index) < min((len(feb28_index), len(mar01_index))): return True return False
34cd6fe34c48982ceb2f2a7cc8182cd175912080
317,774
from typing import List from typing import Union from typing import Dict from typing import Any def tweaks_for_actions(actions: List[Union[str, Dict]]) -> Dict[str, Any]: """ Converts a list of actions into a `tweaks` dict (which can then be passed to the push gateway). This function ignores all actions other than `set_tweak` actions, and treats absent `value`s as `True`, which agrees with the only spec-defined treatment of absent `value`s (namely, for `highlight` tweaks). Args: actions: list of actions e.g. [ {"set_tweak": "a", "value": "AAA"}, {"set_tweak": "b", "value": "BBB"}, {"set_tweak": "highlight"}, "notify" ] Returns: dictionary of tweaks for those actions e.g. {"a": "AAA", "b": "BBB", "highlight": True} """ tweaks = {} for a in actions: if not isinstance(a, dict): continue if "set_tweak" in a: # value is allowed to be absent in which case the value assumed # should be True. tweaks[a["set_tweak"]] = a.get("value", True) return tweaks
9b77b84bd007fe47fd63741f9662ae99d8c9695f
444,232
def file2tuple(thing): """ Function that converts a filename to a tuple of the type: (filename,string containing file) Input can be filename or tuple with filename and content in a string. """ if isinstance(thing,tuple): # it is a tuple with filename and content in a string filename,string = thing output = (filename.split('/')[-1],string) else: # it is a filename filename = thing file = open(filename) output = (filename.split('/')[-1],file.read()) file.close() return output
a62babbb2d2ebaf6e9cd845868fe707af09ff17c
143,199
def normalize_stats(stats): """Normalize frequency statistics.""" return dict((chr(k) if k < 256 else k, v if v else 1) for k, v in stats.items())
15953d48f1a99c349096957235ec1986e66b6b11
383,577
def decode_test_run(test_run): """ Function to decode test_run name into sequence of training parameter values :param test_run: :return: patience, learning rate, minimal learning rate, anneal rate """ x = test_run.split("lr.") patience = int(x[0][1:]) lr = float(f"0.{x[1][:-1]}") y = x[2].split("a") mlr = float(f"0.{y[0]}") anneal_rate = float(f"0{y[1]}") print("Training parameters:\n" f"patience: {patience}\n" f"learning rate: {lr}\n" f"minimal learning rate: {mlr}\n" f"anneal rate: {anneal_rate}\n") return patience, lr, mlr, anneal_rate
e1f7028d8ab104e548ba6cd517763351d5b6ed48
261,872
import pickle def load_CIFAR_batch(filename): """ load single batch of cifar """ with open(filename, 'rb') as f: datadict = pickle.load(f, encoding='latin1') X = datadict['data'] Y = datadict['labels'] return X, Y
cab8293d1c38bd90ba03074d95c62d4fb96d8460
185,562
def calc_check_digit(number): """Calculate the check digit. The number passed should not have the check digit included.""" s = sum((9 - i) * int(n) for i, n in enumerate(number)) return str((11 - s) % 11 % 10)
85a0b09e7777be767bc3787e185adbd3cc7ad6cc
97,188
def example_func(param1, param2): """Example function with types documented in the docstring Args: param1 (int): The first parameter param2 (str): The second parameter Returns: bool: The return value. True for success, False otherwise. """ print(param1) print(param2) return True
2bc46e4cb686cc926383b145ae7b8a7b3ed948c8
96,949
def common_shape(arrays): """ Infers the common shape of an iterable of array-likes (assuming all are of the same dimensionality). Inconsistent dimensions are replaced with `None`. """ arrays = iter(arrays) shape = next(arrays).shape for array in arrays: shape = tuple(a if a == b else None for a, b in zip(shape, array.shape)) return shape
49e2c4a1666ec0a821b9abeef3e1738eaeb22f5c
457,518
from typing import List def getLongestCommonPrefix(strs: List[str]) -> str: """ >>> getLongestCommonPrefix(["abc_aaa","abc_bb","abc_aaaa"]) 'abc_' >>> getLongestCommonPrefix(["b","abc_bb","abc_aaaa"]) '' >>> getLongestCommonPrefix([]) '' """ l = len(strs) if l == 0: return "" else: m = min(map(len, strs)) if m == 0: return "" for i in range(0, m): common = strs[0][i] for s in strs: if s[i] != common: return strs[0][0:i] return strs[0]
23da396c3eb176b8aeb577eed73c5ccd7d1cbc1b
127,750
def _escape_underscore(text): """ Internal utility to escape any TeX-related underscore ('_') characters in mpl strings """ return text.replace('_', '\_')
ca9d7b55d96d35983e03ccb3337aff810e66356b
463,858
def lang(name, comment_symbol, multistart=None, multiend=None): """ Generate a language entry dictionary, given a name and comment symbol and optional start/end strings for multiline comments. """ result = { "name": name, "comment_symbol": comment_symbol } if multistart is not None and multiend is not None: result.update(multistart=multistart, multiend=multiend) return result
e1e89caf4bb595e61a94df1ee70d33c39e75f486
688,778
import hashlib def create_hash_id(input): """ Creates hash identifier. Parameters ========== input : str Input to be hashed to form an identifier. Returns ======= hash_id : str Identifier formed by hashing the inputs. """ input_bytes = bytes(input, encoding="utf-8") hash_id = hashlib.sha224(input_bytes).hexdigest() return hash_id
e9319728a58b9afc947bb2ddc6fc3701d7ec861a
586,177
def generate_number_lines(number_of_lines=6, start=0, end=20): """ Generates number lines as a tool for practicing mathematics such as addition or subtraction. :param number_of_lines: Specify the number of lines to have on the page :param start: start value for the number line as an integer :param end: end value for the number line as an integer :return: contents of the latex document as a string """ lines = [r'\documentclass[letterpaper]{article}', r'\usepackage{geometry}', r'\geometry{landscape,a4paper,total={170mm,257mm},left=10mm,right=10mm,top=30mm}', r'\usepackage{tikz}', r'\usepackage{amsmath}', r'\usetikzlibrary{arrows}', r'\begin{document}', r'\pagenumbering{gobble}', r'\begin{LARGE}', r''] numbers = ','.join([str(x) for x in range(start, end + 1)]) for _ in range(number_of_lines): lines.append(r'') lines.append(r'{\Large $-$}') lines.append(r'\begin{tikzpicture}') lines.append(r'\draw[latex-latex, thick] ' + '({},0) -- ({},0) ;'.format(start - 1, end + 1)) lines.append(r'\foreach \x in {' + numbers + '}') lines.append(r'\draw[shift={(\x,0)},color=black, thick] (0pt,3pt) -- (0pt,-3pt);') lines.append(r'\foreach \x in {' + numbers + '}') lines.append(r'\draw[shift={(\x,0)},color=black, thick] (0pt,0pt) -- (0pt,-3pt) node[below] ') lines.append(r'{\textbf{\x}};') lines.append(r'\end{tikzpicture}') lines.append(r'{\Large $+$}') lines.append(r'\\') lines.append(r'\vspace*{50px}') lines.append(r'') lines.append(r'\end{LARGE}') lines.append(r'\end{document}') return '\n'.join(lines)
173aae03162e5d5717078e872051bc11e1e56057
632,848
def union(list_a: list, list_b: list) -> list: """Return the union of two lists""" if list_a is None: list_a = [None] if list_b is None: list_b = [None] return list(set(list_a) | set(list_b))
4cc4c7fd6214a281115def00ae52a80f6194fd69
103,420
import typing import fnmatch def get_s3_files_for_pattern(client, pattern: str) -> typing.List[str]: """Get a list of S3 keys given a potential wildcard pattern (e.g., 's3://bucket/a/b/*/*.jpg')""" segments = pattern.replace("s3://", "").split("/") bucket = segments[0] keypat = "/".join(segments[1:]) prefix = "/".join( segments[ 1 : 1 + next((i for i, s in enumerate(segments[1:]) if "*" in s), len(segments)) ] ) keys = [] for page in client.get_paginator("list_objects_v2").paginate( Bucket=bucket, Prefix=prefix ): if "Contents" not in page: break keys.extend( [ e["Key"] for e in page["Contents"] if (e["Key"] != prefix or e["Key"] == keypat) ] ) return [f"s3://{bucket}/{key}" for key in keys if fnmatch.fnmatch(key, keypat)]
5a371aad8a512934f98911b2ff0ea2c3924645dc
501,683
def convert_to_iris(dict_): """Change all appearances of ``short_name`` to ``var_name``. Parameters ---------- dict_ : dict Dictionary to convert. Returns ------- dict Converted dictionary. Raises ------ KeyError :obj:`dict` contains keys``'short_name'`` **and** ``'var_name'``. """ dict_ = dict(dict_) if 'short_name' in dict_: if 'var_name' in dict_: raise KeyError( f"Cannot replace 'short_name' by 'var_name', dictionary " f"already contains 'var_name' (short_name = " f"'{dict_['short_name']}', var_name = '{dict_['var_name']}')") dict_['var_name'] = dict_.pop('short_name') return dict_
79e915c95532440ea155adc78a9642375d388a5b
437,367
def make_altaz_frame(location, time): """ Turns location and time into altaz frame :param location: astroplan.observer object :param time: astropy.Time object :returns: Altaz frame """ return location.altaz(time)
906f5f7735248341d33817b8dfb232740bc3246a
264,255
import math def filter_none(mongo_dict): """Function to filter out Nones and NaN from a dict.""" for key in list(mongo_dict.keys()): val = mongo_dict[key] try: if val is None or math.isnan(val): mongo_dict.pop(key) except Exception: continue return mongo_dict
6853a7153f98466dc00d262bfaf4a63db1b0cd5c
11,581
def _options_choose_characters(player): """Return the options for choosing a character. The first options must be the characters name (5 are allowed by player). The other nodes must be reached through letters: C to create, D to delete. """ options = list() characters = player.db._playable_characters if len(characters) < 5: options.append( { "key": "c", "desc": "Create a new character.", "goto": "create_character", }) if len(characters) > 0: options.append( { "key": "d", "desc": "Delete an existing character.", "goto": "delete_character", }) options.append( { "key": "_default", "desc": "Login to an existing character.", "goto": "choose_characters", }) return tuple(options)
d72c08bf9a2cb7ebfc7d4e6d13a94e1189d0d2f9
586,561
def feature_normalize(X, mean=None, sigma=None): """ returns a normalized version of X where the mean value of each feature is 0 and the standard deviation is 1. This is often a good preprocessing step to do when working with learning algorithms. the normalization is processed separately for each feature :param X: numpy array of shape (m,n) Training data :return: X_norm, mu, sigma X_norm matrix(m,n) - Normalised Feature matrix mu matrix(1,n) - mean of individual features sigma matrix(1,n) - standard deviation of individual features """ if mean is None: mean = X.mean(0) if sigma is None: sigma = X.std(0) X_norm = (X - mean) / sigma return X_norm, mean, sigma
81342428799f5ac8d1815b54400e8eb4d7cc302b
694,919
def _format_node(e): """ Internal function to format a node element into a dictionary. """ ignored_tags = [ "source", "source_ref", "source:ref", "history", "attribution", "created_by", "tiger:tlid", "tiger:upload_uuid", ] node = {"id": e["id"], "lat": e["lat"], "lon": e["lon"]} if "tags" in e: for t, v in list(e["tags"].items()): if t not in ignored_tags: node[t] = v return node
17885312c86fbe731976cd7866a3597d3b05de9e
259,889
import logging def __cmp_published__(x, y): """A custom ``cmp()`` which sorts descriptors by published date. :rtype: int :returns: Return negative if x<y, zero if x==y, positive if x>y. """ if x.published < y.published: return -1 elif x.published == y.published: # This *shouldn't* happen. It would mean that two descriptors for # the same router had the same timestamps, probably meaning there # is a severely-messed up OR implementation out there. Let's log # its fingerprint (no matter what!) so that we can look up its # ``platform`` line in its server-descriptor and tell whoever # wrote that code that they're probably (D)DOSing the Tor network. logging.warn(("Duplicate descriptor with identical timestamp (%s) " "for bridge %s with fingerprint %s !") % (x.published, x.nickname, x.fingerprint)) return 0 elif x.published > y.published: return 1
06c72dd0f914ba2d6fba38d17fffff554e523d90
315,935
def scriptable(fn): """Decorator to register operation for scripting.""" fn.scriptable = True fn.script_args = fn.__annotations__ return fn
6a4b62e6effa59941c24beac7fee4a1b34f0cb8d
197,789
def is_reverse_related(field): """ Test if a given field is a reverse related field. :param DjangoField field: A reference to the given field. :rtype: boolean :returns: A boolean value that is true only if the field is reverse related. """ return 'django.db.models.fields.reverse_related' in field.__module__
025c6a4fec1c527ff0e081bee4c6372a9c5dfc74
202,642
def FlagBelongsToRequiredGroup(flag_dict, flag_groups): """Returns whether the passed flag belongs to a required flag group. Args: flag_dict: a specific flag's dictionary as found in the gcloud_tree flag_groups: a dictionary of flag groups as found in the gcloud_tree Returns: True if the flag belongs to a required group, False otherwise. """ flag_group = flag_dict.get('group', None) flag_group_properties = flag_groups.get(flag_group, {}) return flag_group_properties.get('is_required', False)
79f36d76c78d7ac54d38954a4559a23b15e92b70
145,352
def get_table_4(air_type): """表4 外皮の内側にある空気層の熱抵抗 Args: air_type(str): 空気層の種類 'AirTight'(面材で密閉された空気層)または'OnSiteNonConnected'(他の空間と連通していない空気層)または 'OnSiteConnected'(他の空間と連通している空気層) Returns: float: 外皮の内側にある空気層の熱抵抗 """ R_dict = {'AirTight': 0.09, 'OnSiteNonConnected': 0, 'OnSiteConnected': 0} try: return R_dict[air_type] except KeyError: raise ValueError(air_type)
66f28b535f9ef69525cf1e74e0af4bbf155ec458
32,511
from typing import Collection def iscollection(eo_object): """ Helper to check whether an EOObject is a collection. """ return issubclass(eo_object.real_type, Collection)
7f80f76fb0efdc9098eb324b729f41d753842668
359,175
import json def to_json_string(obj): """Convert object as a JSON string.""" return json.JSONEncoder(indent=2).encode(obj)
5e6377365ec5f5a2550533af733b3c5babbd81fa
668,170
def forcerange(colval): """Caps a value at 0 and 255""" if colval > 255: return 255 elif colval < 0: return 0 else: return colval
d0895fcf53788eb3a09a400576f2f6fc472ec654
654,138
def ensure_pymongo(obj): """If obj is wrapped by motor, return the internal pymongo object :param obj: a pymongo or motor client, database, or collection :returns: pymongo client, database, or collection """ if obj.__class__.__module__.startswith("pymongo."): return obj if obj.delegate.__class__.__module__.startswith("pymongo."): return obj.delegate raise TypeError("Neither a pymongo nor a motor object")
d617b8db535cd3f8bf882da8a2c31f37dc922af6
70,470
from typing import Dict from typing import List def add_toggle_completion( toggle_outcomes: Dict[str, Dict[str, bool]], subtasks: List[str]): """Create toggled outcomes/completions mapping for each toggle-able subtasks. e.g. >>> toggle({}, ['Click A', 'Click B', 'Click C']) >>> { 'Click A': {'Click B': False, 'Click C': False}, 'Click B': {'Click A': False, 'Click C': False}, 'Click C': {'Click A': False, 'Click B': False} } """ for subtask in subtasks: toggle_outcomes.update({ subtask: {s: False for s in subtasks if s != subtask} }) return toggle_outcomes
383ca79ee47cb6d095c74d5f88dc25f06cf60702
119,727
def get_crash_id(line): """ Takes a raw CSV line and returns a crash_id :param str line: The raw CSV line :return str: The Crash ID """ try: return line.strip().split(",")[0] except Exception as e: print("Error: " + str(e)) return ""
68188ff4290173deddd3608ceb0534ce6ca2df18
31,203
def has_isolated_transposition(source, image): """Check whether a, b exist, with a -> b and b -> a""" f = dict(zip(source, image)) for s, i in zip(source, image): if f[i] == s: return True return False
b856370161ff918bbbf679b1dd366aa2f563ff51
87,872
def airbnb_js_data() -> dict: """ Returns a fake JS data for the Airbnb classes """ return { 'layout-init': { 'api_config': { 'key': 'api_key', } }, 'reduxData': { 'homePDP': { 'listingInfo': { 'listing': { 'listing_amenities': [ { 'id': 1, 'name': 'Breakfast' }, { 'id': 2, 'name': 'TV' }, ], 'id': '777', 'photos': [ { 'sort_order': 2, 'large': 'image_2' }, { 'xx_large': 'image_3' }, { 'sort_order': 1, 'x_large': 'image_1' }, ], 'name': 'test_name', 'person_capacity': 3, 'location_title': 'City, Region, Country', 'one': { 'two': { 'three': 'result' } }, 'sectioned_description': { 'description': 'test_description' } } } } } }
387cc5fbc5d846036277372ab8fdf302c6adc37a
439,556
def ensure_tz_UTC(df): """ Function to ensure that the tzinfo of a data frame is in UTC :param df: a pandas data frame with datetime_index :returns: the dataframe with df.index.tzinfo='UTC' """ # ensure tzinfo is in UTC if (str(df.index.tzinfo)=='None'): #print('The time stamp is provided is tz naive. It is assumed that the times provided are in UTC') df=df.tz_localize(tz='UTC') else: #print('The provided time zone of the data is '+str(df.index.tzinfo)+'. This is now converted to a tz aware time stampe in UTC') df.index=df.index.tz_convert('UTC') return df
4e8fb68dc648b32138dda66a415c9c5e660665f1
637,473
def drop_titles(tree, titles_to_drop): """ Walk the tree and drop any nodes whose titles are in `titles_to_drop`. """ def _drop_titles(subtree): new_children = [] for child in subtree["children"]: if child["title"] in titles_to_drop: continue else: new_child = _drop_titles(child) new_children.append(child) subtree["children"] = new_children return subtree return _drop_titles(tree)
99a1abeca91751703de1626251e8aa4ca115d41e
80,455
def dig2phys(signal, dmin, dmax, pmin, pmax): """ converts digital edf values to analogue values :param signal: A numpy array with int values (digital values) or an int :param dmin: digital minimum value of the edf file (eg -2048) :param dmax: digital maximum value of the edf file (eg 2048) :param pmin: physical maximum value of the edf file (eg -200.0) :param pmax: physical maximum value of the edf file (eg 200.0) :returns: converted physical values """ m = (pmax-pmin) / (dmax-dmin) physical = m * signal return physical
291199109b1318e4b8c24c90f456bd72cc21003b
249,298
def guess_beta_parameters(guess, strength=5): """Given a `guess` of the mean of a beta distribution, calculate beta distribution parameters such that the distribution is skewed by some `strength` toward the `guess`. :param guess: guess of the mean of the beta distribution :type guess: float :param strength: strength of the skew, defaults to `5` :type strength: int :return: beta distribution parameters (alpha, beta) :rtype: (float, float) """ alpha = max(strength * guess, 0.1) beta = max(strength - alpha, 0.1) return alpha, beta
c29b7162a6613dfad326868831b862a00fdf08c4
247,640
def _get_branching(container, index): """ Returns the nearest valid element from an interable container. This helper function returns an element from an iterable container. If the given `index` is not valid within the `container`, the function returns the closest element instead. Parameter --------- container: A non-empty iterable object. index: The index of an element that should be returned. Returns ------- object The closest possible element from `container` for `index`. Example ------- The `container` can be an arbitrary iterable object such as a list:: l = ['a', 'b', 'c'] c1 = _get_clamped_index(l, 5) c2 = _get_clamped_index(l, 1) c3 = _get_clamped_index(l, -4) The first call of the function using an index of 5 will return element 'c', the second call will return 'b' and the third call will return 'a'. """ maximal_index = len(container) - 1 minimal_index = 0 clamped_index = min(maximal_index, index) clamped_index = max(minimal_index, clamped_index) return container[clamped_index] # except HttpError as e:
5bdb1d45ba5e91a767564a7bd246cda558e10882
148,226
import random def get_imbalanced_data(training_data, img_num_per_cls): """Get a list of imbalanced training data, store it into im_data dict.""" im_data = {} for cls_idx, img_id_list in training_data.items(): random.shuffle(img_id_list) img_num = img_num_per_cls[int(cls_idx)] im_data[cls_idx] = img_id_list[:img_num] return im_data
42383dffc3f69b2a8620b010c73081ee4c64d3e3
206,925