content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_class_by_name(classes_dict, class_name, default): """ Get a class given its name. Parameters ---------- classes_dict : dict Dict with the form {class_name: class} class_name : str Class name. default: class Class to be used if class_name is not in classes_dict. ...
93b985cc53b15c9b68a207831eee4caf931681c9
638,840
def mse(df, y:str, yhats:list): """ Calculates Mean Squared Error. Args: df: pandas dataframe y: name of column with actual data yhats: list of column names with estimated data Returns: df: containing the MPE for each column """ columns_to_keep = yhats + [y] ...
e79bf058e5f7351f8fc7dd370e1672e1d7c002b4
638,844
def degree_to_order(degree): """Compute the order given the degree of a B-spline.""" return int(degree) + 1
c5e7229e350e810fe75c7697ebbb2ac2f90fd765
638,848
import types def copy_function(function, module=None, name=None): """ Copy a function and optionally change its name and module definition """ name = name if name else function.__name__ module = module if module else function.__module__ new_function = types.FunctionType( function.__co...
5cb87aa9fbb08915c4565d4b68c9cbb77cd25b99
638,851
import requests import imghdr def is_image(url) -> bool: """ Determine if it is an image of png or jpeg. Parameters ---------- url : str Target url. Returns ------- True or False: Return True if this url content is an image of png or jpeg else returns False. """ img = r...
4ad67187d09ac1d79d8d030d0120f3f06cd492b3
638,852
def slope_intercept_form(m, x, b): """ Handles the formula used for y=mx+b format to find slope """ m = float(m) x = float(x) b = float(b) return m * x + b
2f91902fb2eecf01e83e8c3c3331de01b776f2d3
638,853
from typing import Any from typing import Union def to_number(s: Any) -> Union[int, float]: """Cast the string representation of the given object to a number (int or float), or raise ValueError.""" try: return int(str(s)) except ValueError: return float(str(s))
de5261dbcd05f214f4f8fae40842f8a378d07d4e
638,861
def longest_range(index_list): """ select longest index range eg. [1, 0, 1, 1, 1] ==> (2, 5) @param index_list: list, element is 0 or 1 @return: a tuple (a, b). a is the range begin, and b is the range off end. """ range_list = [] begin = 0 for i in range(len(index_list) - 1): ...
6d9847a3fe8dfcc73b13dc1460cf4fe699c8ed5a
638,862
def openreadlines(filename, xform=None): """Open a file and return a list of all its lines. xform -- a function to run on all lines""" with open(filename, "r", encoding="utf-8") as infp: return [xform(x) if xform else x for x in infp]
2042d190d1c0606e310ec5f602c90f8e095a0d44
638,863
def set_dict_values(d, value): """ Return dict with same keys as `d` and all values equal to `value'. """ return dict.fromkeys(d, value)
6b52c95759ffd5b9286d96bbc3410b4df5534313
638,867
def check_http_code_in_output(http_code, error_message=None): """Create a callable to ensure that the given HTTP error code is present in the output of the response. Args: http_code (int): the HTTP error code to check. error_message (str, optional): the message that will be displayed if the...
cca1800b025d069096152cd494bcdd6cf6e92c5a
638,868
import torch def apply_tform(tform, verts): """ Applies a 4x4 rigid transform to a list of points :param tform: tensor (batch, 4, 4) :param verts: tensor (batch, N, 3) :return: """ verts_homo = torch.cat((verts, torch.ones(verts.shape[0], verts.shape[1], 1, device=verts.device)), 2) ne...
7a75d44e9a19165acbb370eea49a22e5d00bf42d
638,872
def _should_ignore(class_reference, property_name): """Check if a property should be ignored.""" if not hasattr(class_reference, "__deserialize_ignore_map__"): return False return class_reference.__deserialize_ignore_map__.get(property_name, False)
91868a403427779da1f803ae08e273f04e30f8e4
638,875
def checkstyle_source_to_error_type(source): """Convert a checkstyle error source to an error type """ class_name = source.split('.')[-1] if class_name.endswith('Check'): type = class_name[:-len('Check')] else: type = class_name return type
8a9e5502613a665efa3cefa84c7fc5fd3342cb46
638,876
def mpad(msg, size): """Pad a byte string to multiple of size bytes. """ amount = size - len(msg) % size return msg + b'\0' * amount
48f01ceccf7132fa8f8fbf5c52b0ddc8f3fec61d
638,884
import requests def getJsons(game_number, codes, api_version = "0.1", url = "https://np.ironhelmet.com/api"): """ Returns a list of values collected via the API :param str game_number: Number of the game you wish to visualize data from :param list co...
142a789b7578ef9ede98b70ea8dddec67afc0b66
638,886
def get_end_linenumber(text): """Utility to get the last line's number in a Tk text widget.""" return int(float(text.index('end-1c')))
8768a6ce777087ee1730b41efd9a41180672c33b
638,889
import re def _strip_time(desc): """Strips time from play description.""" return re.sub('^\([^)]+\)', '', desc).strip()
2c7ca2d8c2ddffe2f741123946fc7cc659e1447b
638,890
def find_digit_sum(num): """Return the sum of digits in num.""" num = str(num) digit_sum = 0 for char in num: digit_sum += int(char) return digit_sum
aeaaae9beec3f25c5fc697583dfe9575602a7574
638,891
def rgb2gray(rgb,biases = [1/3,1/3,1/3]): """ Calculate gray image value from RGB value. May include bias values to correct for luminance differences in layers. Parameters ---------- rgb : TYPE DESCRIPTION. biases : TYPE, optional DESCRIPTION. The default is [1/3,1/3,1/3]. ...
f182d48a45a154c3220877edb9342ca9142eaaae
638,892
import _operator def _basic_math_operation(df, new_column, column_1, column_2, op): """ Basic mathematical operation to apply operator on `column_1` and `column_2` Both can be either a number or the name of a column of `df` Will create a new column named `new_column` """ if not isinstance(colu...
de20b508a39fd18bf5cf1b8d37eefe3814c1ef18
638,895
import re def load_help(txtfile): """ Returns a list of strings split with ': ' """ with open(txtfile, 'r') as f: s = f.read() s = re.sub('\n',': ', s) li = s.split(': ') return li
4451d07e685eb95e51ff4be9197b6e0a1fc38527
638,897
def eV(E): """ Returns photon energy in eV if specified in eV or KeV. Assumes that any value that is less than 100 is in KeV. Parameters ---------- E : float The input energy to convert to eV Returns ------- E : float Energy converted to eV from KeV """ ...
bb1811163c223670822e28ac7be6f34bfcbae837
638,898
def sort_paper_list(paper_list): """Sort the paper list by paper year.""" keyfunc = lambda paper: paper['year'] sorted_paper_list = sorted(paper_list, key=keyfunc) return sorted_paper_list
f8b4e15d75bffda00207fe70abd9e080cf1758c4
638,903
def replaceStringBlocks(str, startId, endId, newContent): """ Replaces all string sections in blocks given by startId and endId tags by newContent. :param str str: Text content to be updated. :param str startId: Start identifier of the block to be replaced. :param str endId: End identifier of the block...
a1f7237d6eb0b135e46dd853b8371780dd33e5e4
638,907
def sliceFromString(sliceString): """Convert a text string into a valid slice object which can be used as indices for a list or array. >>> sliceFromString("0:10") slice(0,10,None) >>> sliceFromString("0::3") slice(0,None,3) >>> sliceFromString("-8:") slice(-8,None,None) """ slic...
1b8576647e3f0c9ba9355a3b3329f7ee971f76ed
638,909
def get_individual_decision_makers(decision_maker_list): """Return list of individual decision makers.""" individual_dms = [] for dm in decision_maker_list: individual_dms += dm.decision_makers return individual_dms
6b99c42955725f4292219f7f7a01e7530fece845
638,912
def _ByStartAndCreationTime(job): """Sort key that sorts jobs by start time, newest and unstarted first. All unstarted jobs will be first and sorted by their creation timestamp, all started jobs will be second and sorted by their start time. Args: job: googlecloudsdk.api_lib.run.job.Job Returns: Th...
f5c2d0c83e24242c75e2077d7c1179a6d329c9b9
638,914
import math def time_to_hhmmssmmm(time_value, decimal_separator="."): """ Format the given time value into a ``HH:MM:SS.mmm`` string. Examples: :: 12 => 00:00:12.000 12.345 => 00:00:12.345 12.345432 => 00:00:12.345 12.345678 => 00:00:12.346 83 => ...
844313561b6c307e24257d0e8fcc3a92945affb2
638,917
def _net_working_capital(column): """ Uses balance sheet to net working capital """ current_assets = column["Total current assets"] current_liabilities = column["Total current liabilities"] return current_assets - current_liabilities
6fe420c3c26c130775ae01c77ebc6ec69a76d182
638,918
import json def load_vocab(vocab_path): """ Load word -> index and index -> word mappings :param vocab_path: where the word-index map is saved :return: word2idx, idx2word """ with open(vocab_path, 'r') as f: data = json.loads(f.read()) word2idx = data idx2word = dict([(v, k) f...
b57002706bd36ad41b5085b12dbde8cf07338ffd
638,925
def get_enzyme_reactions(eid, db): """ For a given ec number return associated reaction ids :param eid: enzyme id format "EC-x.x.x.x" :param db: database dict :return: """ erids = [] if eid[:3] != "EC-": eid = "EC-{}".format(eid) for rid, react in db['reactions'].items(): ...
cc1dd189b57ecd8ec6572c4ddeb4cf1dabd0a33f
638,931
def computeRamp(f): """ The ramp function is defined as r(x) = f if f(x)>=0 0 if f(x)<0 which is equal to max(x, 0) """ return (f+abs(f))/2
967ac9d0dc130540a82de9c97fed07114cd2aebd
638,932
def mask_spec(spec, spec_thresh=0.9, offset=1e-10): """ mask threshold a spectrogram to be above some % of the maximum power """ mask = spec >= (spec.max(axis=0, keepdims=1) * spec_thresh + offset) return spec * mask
fc2b0524df68b9e6f960ee416afdd1ac528969bc
638,934
def get_mat_info(struct): """ Get some basic information of the structure, e.g. name, configuration Parameters ---------- struct: pymatgen.structure Returns ------- name: string The name of the structure configuration: list The configuration of t...
4deb66b551be31f2aaf412272f4250e330ff349b
638,938
def multiply(*args): """ :param args: This represents the group of ints that are to be multiplied :return: This returns the total product of all numbers that were multiplied """ total = 1 for arg in args: if type(arg) is int: total *= arg return total
821a12546712034f73d5a35c1b0acd98aa25f8ba
638,939
def collect(*args): """Collect arguments as a tuple :rtype: tuple :param args: tuple of arguments :return: args """ return args
394c9879f7bd7a3687131f658d2aaf842f94189c
638,940
def filtersubset(linking, el2kbid, gold_els): """ remove from linking and rom el2kbid all mentions that are not in gold_els """ newlinking = dict() new_el2kbid = dict() for kbid in linking.keys(): mentions = linking[kbid] for m in mentions: if m in gold_els: ...
8ccbfd4cbb775226191407a08c62915573649eb2
638,944
def _get_frequency_of_segment_in_list(seg, seg_list): """ Counts the frequency of a given segment or token in a list of segments/tokens. """ return seg_list.count(seg)
022dbe711da96a60323df0637d70b4ac34f47bc8
638,948
import re def match_device(device): """Matches device name and returns prefix, suffix""" match = re.match("(^/dev/x{0,1}[a-z]{0,1}d{0,1})([a-z]+)[0-9]*$", device) if not match: return None return match.groups()
bebde5e4a18f6112ed947e79f44da27c36c6cfab
638,949
def assure_tuple_or_list(obj): """Given an object, wrap into a tuple if not list or tuple """ if isinstance(obj, list) or isinstance(obj, tuple): return obj return (obj,)
2d5c3e5301d9e98b749faea508d8b3cc2804ca7d
638,950
def LoadData(data, multiline=False, source='<data>'): """Turn key=value content into a dict Note: If you're designing a new data store, please use json rather than this format. This func is designed to work with legacy/external files where json isn't an option. Only UTF-8 content is supported currently. ...
e443815f095fea639f51f5023e06a8a383324acd
638,952
import torch def collate_fn(data): """ Creates a mini-batch, overriding default_collate function in order to provide batches with input sorted by length. """ # sort such that input line lengths are in decreasing order # requirement for using torch.nn.utils.rnn.pack_packed_sequence data.sor...
7ba7ab5dd2b72ea7fd545d68ab484366ab72a046
638,953
def _exp_warn_msg(cls): """Generate a warning message experimental features""" pfx = cls if isinstance(cls, type): pfx = cls.__name__ msg = ('%s is experimental -- it may be removed in the future and ' 'is not guaranteed to maintain backward compatibility') % pfx return msg
e686537e12adb3de487b1ff898ec7de1342408cc
638,955
def prepare_chronotrack_result_json(text): """ :param text: string from /load-model that contains embedded json - assumed the callback function is an empty string :return: the embedded json (str) """ return text.lstrip("(").rstrip(");")
e085e87f6ccd2063012be6b571343a6a7221e120
638,957
from typing import Iterable import functools import operator def product(iterable: Iterable): """ Multiplies all elements of iterable and returns result ATTRIBUTION: code provided by Raymond Hettinger on SO https://stackoverflow.com/questions/595374/whats-the-function-like-sum-but-for-multiplication-...
9662680401fb63c96cef271959964039d08aa20c
638,967
def cipher_ca(text, d1, d2): """Caesar or Atbash encoding/decoding. Supply both dictionaries via d1 and d2""" result = '' for c in text: if c not in d1: result += c else: result += d2[d1.index(c)] return result
f0e3c08d51d08e4299c3ee57b27d42ebb3032fa1
638,969
def parse_user_data(user): """Parse the user's information into a dictionary.""" data = { "id": user.id, "email": user.email, "username": user.username, "active": user.active, "confirmed": user.confirmed_at is not None, "preferences": dict(user.preferences or {}),...
0c2a2c97304f5db21ad313ab8d74948da380c6ce
638,970
def djoin(*tup): """ Convenience method to join strings with dots :rtype: str """ if len(tup) == 1 and isinstance(tup[0], list): return '.'.join(tup[0]) return '.'.join(tup)
0c209cd026d15b2126918b0c280e5dcdbb143d9f
638,971
def achromat(power, Va, Vb): """Compute lens powers for a thin doublet achromat, given their V-numbers.""" power_a = (Va/(Va - Vb))*power power_b = (Vb/(Vb - Va))*power return power_a, power_b
78712dfbc63f08a44866a87d432ca9b82f01f069
638,972
def _make_env(environment): """Change from Docker environment to Kubernetes env Args: environment (dict): Docker-style environment data Returns: list: Kubernetes-style env data """ env = [] for key, value in environment.items(): env.append({"name": key, "value": value})...
ba3b149dbf27ecabb6287a7d067a0f242744cb7d
638,973
def find_proxy(ip,port,proxies): """ 根据ip,端口查找符合条件的代理 :param ip: 查询ip :param port: 查询端口 :param proxies: 查找的代理IP列表,类型[{'ip':<ip>,'port':<port>,...},...] :return:符合条件的代理数据 dict类型 {'ip':<ip>,'port':<port>,...} """ for i in proxies: if isinstance(i,dict): if i['ip']==ip a...
3c6ed7b19c9d9777843b5f9e892874a1701467eb
638,976
def _get_sv_callers(items): """ return a sorted list of all of the structural variant callers run """ callers = [] for data in items: for sv in data.get("sv", []): callers.append(sv["variantcaller"]) return list(set([x for x in callers if x != "sv-ensemble"])).sort()
b599880f4e1bb106dc68e7de835eedbe0995fbb6
638,977
import json def parse_acl_v2(data): """ Parses a version-2 Swift ACL string and returns a dict of ACL info. :param data: string containing the ACL data in JSON format :returns: A dict (possibly empty) containing ACL info, e.g.: {"groups": [...], "referrers": [...]} :returns: None if...
74aaf6e21c309eb52ccaba4ba0386d92f0395aa1
638,978
def check_numeric_indicator(var: str, index: str, messages: list) -> bool: """Checks that variable's numeric indicator is "0", "1" or "2". Parameters ---------- var : str Metadata variable in criteria. index : str Numeric indicator. messages : list Message to print i...
9bb5e742a9459a6ff5d93d9d21d92be2ace00cff
638,981
def defang_text(text): """ Function to normalize quoted data to be sql compliant :param text: Text to be defang'd :return: Defang'd text """ text = text.replace("'", "''") text = text.replace('"', '""') return text
36b70de8b6af691b3d9bc2c2e7be9cf3d50a6905
638,982
def get_process_metric(row, flag, ck_frame, metric, verbose=False): """ Returns the value for the given metric for a particular source :param row: the data frame row for the test :param flag: true if that's a production class; false if a test :param ck_frame: the frame with all the ck metrics :p...
1857be49afe06f5a3a06956378a7e551282c2ac7
638,983
def _IsLegacy(discovery_rest_url): """Returns whether the given discovery URL uses legacy discovery. Args: discovery_rest_url: a str containing a discovery URL for an API. Returns: True if the discovery URL is determined to be a legacy, otherwise False. """ if 'googleapis.com/$discovery' in discover...
53a8c8916a4298c2a6f73114c9f0354c1b863df4
638,984
def get_spec(field, query='', query_dsl=''): """Returns aggregation specs for a term of filtered events. The aggregation spec will summarize values of an attribute whose events fall under a filter. Args: field (str): this denotes the event attribute that is used for aggregation. ...
51baf7a7479913ea221c7d07d51744064f6417de
638,986
def max_length(obj): """ Return the maximum length of obj or any of its sublists, if obj is a list. otherwise return 0. @param object|list obj: object to return length of @rtype: int >>> max_length(17) 0 >>> max_length([1, 2, 3, 17]) 4 >>> max_length([[1, 2, 3, 3], 4, [4, 5]]) ...
a7c2fcbb80ef6074879443f0883943634efa52b0
638,989
def _compute_olympic_average(scores, dropped_scores, max_dropped_scores): """Olympic average by dropping the top and bottom max_dropped_scores: If max_dropped_scores == 1, then we compute a normal olympic score. If max_dropped_scores > 1, then we drop more than one scores from the top and bottom and ave...
b3f8df256f94efc729bd11e47810206a9d75e497
638,991
def robot_paint(grid, painted_locations, current, instruction_list): """Makes robot paint given location on grid. Updates and returns grid, painted_locations. """ painted_locations.add(current) if instruction_list[0] == 0: grid[current[0]][current[1]] = '.' elif instruction_list[0] == 1: ...
abcbb7b6d77fb5839f4a4e080fc1b3b9a46da18a
638,997
def _GetFormatCharForStructUnpack(int_width): """Gets the sample's integer format char to use with struct.unpack. It is assumed that 1-byte width samples are unsigned, all other sizes are signed. Args: int_width: (int) width of the integer in bytes. Can be 1, 2, or 4. Returns: The format char corre...
841fbf1b05075f5171267a89919ce461c4fd7c19
638,999
def get_keys_of_max_n(dict_obj, n): """Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c'] """ return sorted([ item[0] for item in sorted( d...
16b51090ac086a708deccf6876201857e06ef0fc
639,000
def accuracy_predicted_substation(**kwargs: dict) -> bool: """ Calculates whether the substation where the changes are predicted at corresponds to the substation with the label changes. Parameters ---------- **kwargs['Y_subchanged_idx'] : int The index of the substation where the 'true'...
6ba9e97e5c968b6d66cf18ab660dc3365521f077
639,001
def text_if_str(to_type, text_or_primitive): """ Convert to a type, assuming that strings can be only unicode text (not a hexstr) @param to_type is a function that takes the arguments (primitive, hexstr=hexstr, text=text), eg~ to_bytes, to_text, to_hex, to_int, etc @param hexstr_or_primitive in...
8b2bb308c17c44f0168c47c2abfc9ab08edc4410
639,004
def check_format(number='1989592KJAB'): """ Description ----------- Function to check format compliance of US phone numbers, namely the length should be exactly 11 digits, and the first digit must be with 1 :param number: Input phone number as a string :return: True if valid format, false if...
b3740d51599de9278be34ad788633569f1e171f1
639,005
def partition(array, low, high): """ This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot. """ pivot = array[high] i = low -...
318310e6e2e39d506fba79fe7839839d8b29ede4
639,008
def find_module(course, module_name): """ Uses module name to find the corresponding module """ for module in course.get_modules(): if module.name == module_name: return module
b7ae98bcd52d32b2687f5f780ba4a038f332f934
639,015
import requests def get_recent_kills(sysid): """ Retrieves recent metrics for specified system in list format for ease of parsing :param sysid: the integer value ID of the system to be checked :return: List of npc_kills, pod_kills, ship_kills for the specified system. """ interaction_list = [...
1011a87f55756874e91695856fb10ba241bdc85c
639,018
def convert_to_physical(a_coeffs, b_coeffs, logic_x, logic_y): """ Convert to physical coordinates from logical coordinates. Parameters ---------- a_coeffs : array Perspective transformation coefficients for alpha. b_coeffs : array Perspective transformation coefficients for bet...
a18602ce1276348926c86863ef33c67d7280176a
639,021
def split_seconds_human_readable(seconds): """ splits the seconds argument into hour, minute, seconds, and fractional_seconds components. Does no formatting itself, but used by format_seconds_human_readable(...) for formatting seconds as a human-redable HH::MM:SS.FRACTIONAL time. """ if isinstance(...
9cbb8588f27ded71c43a8803ab52db0603c2ad49
639,023
import inspect def has_required_functions(ref): """Validates if there are the required functions to configure and execute a spark program Parameters: ref (module): Python module that acts as entrypoint Returns: bool: True if has the required functions """ return (hasattr(ref, 'c...
b7998449723f57525d513a05961ec55ef3fcf294
639,024
import enum def _fromflagname(cls, name:str, default=...) -> enum.Enum: """Returns the flag enum from the the specified name when `default` argument is defined: returns `default` on invalid name otherwise: raises `KeyError` on invalid name """ if default is not Ellipsis: ...
f35c00d18be388b818f5ad289942e295bbbc0717
639,025
import requests def get_page(url: str, store_num: str= '095'): """ Given a Microcenter URL, return request object :param url: str, microcenter url :param store_num: str, store number as string, defaults to MO - Brentwood :return: requests.model.Response, html from url """ headers = { ...
02eb540cd26f9552b22c9ad305553080054df3d5
639,028
def _clang_copts(objc_fragment): """Returns copts that should be passed to `clang` from the `objc` fragment. Args: objc_fragment: The `objc` configuration fragment. Returns: A list of `clang` copts. """ # In general, every compilation mode flag from native `objc_*` rules should be...
59436298ecfbde75d0f90ba5f07811b328f42ff5
639,030
def create_pytest_param_str_id(f): # type: (...) -> str """ Returns an id that can be used as a pytest id, from an object. :param f: :return: """ if callable(f) and hasattr(f, '__name__'): return f.__name__ else: return str(f)
26fd71c0bf19da99d901e428e35daec1e4c4a0bb
639,032
import json def _GenerateCopyCommand(from_path, to_path, comment=None): """Returns a Dockerfile entry that copies a file from host to container. Args: from_path: (str) Path of the source in host. to_path: (str) Path to the destination in the container. comment: (str) A comment explaining the copy ope...
c1c5fb832cbde60f4ebed675b231a15166159673
639,044
def is_valid_git_refname(refname): """check if a string is a valid branch-name/ref-name for git Input: refname: string to validate Output: True if 'refname' is a valid branch name in git. False if it fails to meet any of the criteria described in the man page for 'git check-ref-format', al...
f5ea7057e202df0c821f3c7a52882cee6d95f6d3
639,048
def background_column(s, background=255, threshold=None): """Report whether all values in a column are the same.""" a = s.to_numpy() return (a[0] == a).all() and a[0] == background
2127a6c9dda865ff6d1ca0cb513b828e5bd8aaba
639,049
def _is_parsable_header(structure): """ Determines if a PDS4 header structure can be parsed into plain text. Header structures that can be displayed as text are: (1) Plain-text Headers (2) Headers that can be turned into plain-text via a parser """ return structure.is_header() and has...
ccc06066651c7babfd13970b2bb9dc78c0967c5a
639,052
def eta(z, x, beta): """ Eq. (6) from Ref[1] (coeffient of alpha) Note that 'x' here corresponds to 'chi = x/rho', and 'z' here corresponds to 'xi = z/2/rho' in the paper. """ return -6 * z / beta**2 / (1+x)
8af87428a80da9e8630aa6356215bd925482feaf
639,056
import importlib def class_from_dotted_path(dotted_path): """Loads a Python class from the supplied Python dot-separated class path. The class must be visible according to the PYTHONPATH variable contents. Example: ``"package.subpackage.module.MyClass" --> MyClass`` Args: dotted_path...
4888ea47ffe3395452550fe2109df53d500f75f9
639,057
def get_units_title(unit_type): """ Get the title for units """ units_title = "m" if unit_type == 'english': units_title = "ft" return units_title
d032f50661ad42aed97aff7f2b19ebb9d8ebc366
639,060
def crop_to_bottom_half(image): """Return only the bottom half of image.""" image = image.crop((0, image.size[1] / 2, image.size[0], image.size[1])) return image
7e8f7e106e483afdf26242de0963e1033bdf9720
639,062
def number_to_base(n, b): """ translates a decimal number to a different base in a list of digits Args: n: the decimal number b: the new base Returns: A list of digits in the new base """ if n == 0: return [0] digits = [] while n: digits.append(int...
103cf77bfaa03321e1d9cae04b4900f1faab5727
639,066
def traj_name_filter(traj, string): """ Filter out trajectories that have the given `string` in the `traj.traj_name` """ return string in traj.traj_name
33ceb6d04db30c87dfb2e6615c753c228dae1470
639,067
from enum import Enum def _defaultMetaSerialize(value): """ Is called by `json.dumps()` whenever it encounters an object it does not know how to serialize. Currently handles: 1. Any object with a `serialize()` method, which is assumed to be a helper method. 1. `numpy` scalars as well as `...
220d9d727248b7fa8f32210c11e8ee60ad2c2d69
639,068
import requests def get_income(acc, api_key): """ Return the income of the customer """ res = requests.get("https://api.td-davinci.com/api/customers/" + acc, headers={'Authorization': api_key}) res_data = res.json() data = res_data["result"] return data["totalIncome"]
06c098b964c8f0a39614a145e92ae66d60ca678e
639,071
def replace_dict_values(source, replacements): """Creates a copy of the source dictionary and replaces all values specified in a replacement list :param source: The source dictionary :param replacements: The replacements. This is a list of key/value tuples, where dots in the key describe the hierarchy ...
eb554ac21999155d7eaae94a877d9f81c8857c05
639,075
from datetime import datetime def change_date_format(date: str) -> str: """ Parsing "%Y-%m-%d to %m/%d/%Y """ datetime_object = datetime.strptime(date, "%Y-%m-%d") return datetime_object.strftime("%m/%d/%Y")
284910b267e87f4616b4d0e8aa4aefd3db9fcafe
639,078
def iflatten_instance(iterable, terminate_on_kls=(str,)): """Derivative of snakeoil.lists.iflatten_instance; flatten an object. Given an object, flatten it into a single depth iterable- stopping descent on objects that either aren't iterable, or match isinstance(obj, terminate_on_kls). Example: >>> print ...
3fd46a46ac04107ef490396c2ae92c7d2626a786
639,079
def jogador_pontuacao(jogador): """ Seletor do TAD jogador Devolve o valor da pontucao do jogador Argumentos: jogador -- jogador """ return jogador[1]
9cc54804212e89b576b333354f0db7ad06e28c90
639,082
import pkg_resources def package_filename(name: str) -> str: """Get fullpath of a package filename specified by the base filename. Args: name: base name of the package file Returns: Fullpath of the package file """ return pkg_resources.resource_filename('line_item_manager', ...
0b88de3ccc6bb644769bba50a58ea4a883387522
639,083
def pigment(depigm, incpigm, cga, anyga): """ any pigm abn (depig, inc pig, noncentral GA) Returns: 0, 1, 88 """ if depigm == 1 or incpigm == 1 or (anyga == 1 and cga == 0): return 1 elif depigm == 0 and incpigm == 0 and anyga == 0: return 0 else: return 88
e7b0d641d14dbeb85a56cb8677efa7d8a774400b
639,084
import random def exponential(value): """ Set retry time exponentially; per the "+ 1," begin at a minimum of one second. """ return random.random() * (2 ** value) + 1
a30c4bcf2d300b09ea9f1df293359098da8e85a7
639,086
def customer_2(accounts) -> str: """Get another customer address.""" return accounts[2]
65b5e9f0330cd5dd9777d4e7a90a17b81ec56064
639,088
def extract_state_fips(fips: str) -> str: """Extracts the state FIPS code from a county or state FIPS code.""" return fips[:2]
241bab8540c32c4e41597723bd42bc7b35a7d303
639,092
def kolibri_userinfo(claims, user): """ Fill claims with the information available in the Kolibri database """ claims["name"] = user.full_name return claims
29f64178481de1b06250c2171e5ea8c51170298c
639,096
import re def get_first_image(content): """Returns a url to the first image found in a html string.""" matches = re.findall(r'<img([^<]+)>', content) for match in matches: match_src = re.search(r'src="([^"]+)', match) if match_src: return match_src.group(1) return None
db3c9abf391d1f3e0350064e8655ac2460edc597
639,098