content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def nested_sum(t): """Computes the total of all numbers in a list of lists. t: list of list of numbers returns: number """ total = 0 for nested in t: total += sum(nested) return total
44d9fa3e0a6011c74f23a002e86bef13b0c52e72
32,634
def oscar_calculator(wins: int) -> float: """ Helper function to modify rating based on the number of Oscars won. """ if 1 <= wins <= 2: return 0.3 if 3 <= wins <= 5: return 0.5 if 6 <= wins <= 10: return 1.0 if wins > 10: return 1.5 return 0
31350d7ab5129a5de01f1853588b147435e91ab2
675,299
def decode_MAC(MAC_address): """ Returns a long int for a MAC address @param MAC_address : like "00:12:34:56:78:9a" @type MAC_address : str of colon separated hexadecimal ints @return: long int """ parts = MAC_address.split(':') if len(parts) == 6: value = 0 for i in range(6): shift = 8*(5-i) value += int(parts[i],16) << shift return value else: raise RuntimeError("Invalid MAC address: %s" % MAC_address)
6a4b2500ee438710781e8ac9906ee17738ed3c8b
295,702
import operator import importlib def load(path): """ Loads a module member from a lookup path. Paths are composed of two sections: a module path, and an attribute path, separated by a colon. For example:: >>> from pgshovel.utilities import load >>> load('sys:stderr.write') <built-in method write of file object at 0x10885a1e0> """ module, attribute = path.split(':') return operator.attrgetter(attribute)(importlib.import_module(module))
eaa1534384d2bef079e8ba57ee93d1cfaed827af
436,234
def calculateHorizontalForce(qwind, span): """ :param qwind: Obciążenie wiatrem prostopadłe do lini cięgna [N/m] :param span: Rozpiętość pozioma cięgna (długość w rzucie "z góry") [m] """ return (qwind * span) / 2
51040df0f170704e0d19bdfb273aecfc96551a4c
548,378
def shorten(text, length, add="..."): """Shortens the provided text if it's longer than the length. If it's longer, add is appended to the end.""" if text is None: return "" shortened = text[:length - len(add)] if shortened != text: return shortened + add return shortened
16850aff41e4c7f292a6ad9335d31cc378726206
169,331
def is_private(obj): """Return True if object is private.""" if obj is not None: return isinstance(obj, str) and obj.startswith('_')
648c0b765c4f96f7687d97a6ec18779778642648
624,981
import torch def torch_transform(g, a, normals=None): """ Applies the SE3 transform Args: g: SE3 transformation matrix of size ([1,] 3/4, 4) or (B, 3/4, 4) a: Points to be transformed (N, 3) or (B, N, 3) normals: (Optional). If provided, normals will be transformed Returns: transformed points of size (N, 3) or (B, N, 3) """ R = g[..., :3, :3] # (B, 3, 3) p = g[..., :3, 3] # (B, 3) if len(g.size()) == len(a.size()): b = torch.matmul(a, R.transpose(-1, -2)) + p[..., None, :] else: raise NotImplementedError b = R.matmul(a.unsqueeze(-1)).squeeze(-1) + p # No batch. Not checked if normals is not None: rotated_normals = normals @ R.transpose(-1, -2) return b, rotated_normals else: return b
b069587880ba832d6e00ec1f099eac02d1b1f929
484,938
import sqlite3 def connect_evals(fname): """Opens exclusive connection to a sqlite3 database. Parameters ---------- fname : `str` file name of sqlite3 database Returns ------- connection : `sqlite3.Connection` Connection object to a sqlite database """ conn = sqlite3.connect(fname, isolation_level = 'EXCLUSIVE') conn.execute('BEGIN EXCLUSIVE') return conn
87cc66b42a011da27ebf7db085c72912504e8264
194,001
def cast_image(image, dtype): """Casts an image into a different type # Arguments image: Numpy array. dtype: String or np.dtype. # Returns Numpy array. """ return image.astype(dtype)
ad34f24d2ca6525c4dab19fc62c59e3e2f4aaee3
497,124
from typing import Mapping from typing import Any def find_renamed(items_before: Mapping[Any, Any], items_after: Mapping[Any, Any]): """ Split before/after mappings into added/removed/renamed Rename detection is based on the mapping keys (e.g. uuids) """ uuids_before = {uuid for uuid in items_before.keys()} uuids_after = {uuid for uuid in items_after.keys()} renamed_uuids = {uuid for uuid in uuids_after & uuids_before if items_before[uuid] != items_after[uuid]} added_items = [items_after[uuid] for uuid in uuids_after - uuids_before - renamed_uuids] removed_items = [items_before[uuid] for uuid in uuids_before - uuids_after - renamed_uuids] renamed_items = [(items_before[uuid], items_after[uuid]) for uuid in renamed_uuids] return added_items, removed_items, renamed_items
420cfe482c901e5118dad430d736e688bd5745f9
160,740
def H(path): """Head of path (the first name) or Empty.""" vec = [e for e in path.split('/') if e] return vec[0] if vec else ''
da618dfe64ed6b30b23ddb9d528458e80e7a8708
584,944
def recast_to_supercell(z, z_min, z_max): """Gets the position of the particle at ``z`` within the simulation supercell with boundaries ``z_min`` y ``z_max``. If the particle is outside the supercell, it returns the position of its closest image. :param z: :param z_min: :param z_max: :return: """ sc_size = (z_max - z_min) return z_min + (z - z_min) % sc_size
2d144a656a92eaf3a4d259cf5ad2eadb6cfdf970
534
def _kafka_parse_broker(broker): """ `broker` is a string of `host[:port]`, return a tuple of `(host, port)` """ host_and_port = broker.split(":") host = host_and_port[0] port = "9092" if len(host_and_port) == 2: port = host_and_port[1] return (host, port)
f738137fa50f66e58736e0cfb200860f6cd8411b
286,330
def _convert_method_arg(method): """ Convert argument `method` to a function that can be called after resampling or reindexing a DataFrame. If `method` is a string such as 'ffill' or 'bfill' then it will be converted to a function. Otherwise if `method` is itself a callable function, then it will be used directly. For example, the string 'ffill' is converted to a lambda-function `func` so that `func(df.resample(rule))` actually performs the chained function-call `df.resample(rule).ffill()` :param method: String or callable function. :return: Callable function. """ if method == 'ffill': # Forward fill. func = lambda x: x.ffill() elif method == 'bfill': # Backward fill func = lambda x: x.bfill() elif method == 'linear': # Linear interpolation. func = lambda x: x.interpolate(method='linear') elif method == 'quadratic': # Quadratic interpolation. func = lambda x: x.interpolate(method='quadratic') elif method == 'mean': # Averaging which is useful in downsampling. func = lambda x: x.mean() elif callable(method): # Use the provided callable method directly. func = method else: # Raise exception because of invalid arg. msg = 'arg `method` must either be a valid string or a callable function.' raise ValueError(msg) return func
3d7897ff82d0fde788c34756ebd8737736d7f4e8
597,817
def add_to_list(a_list: list, element: object): """ Attempts to append element to a list. If already contained, returns 0. Else 1. """ if element not in a_list: a_list.append(element) return 1 return 0
a6490d0cbdd9a422a491906413046bce27dd6855
92,590
def splitDataSet(dataSet, axis, value): """ 按照给定特征划分数据集 :param dataSet: 待划分的数据集 :param axis: 划分数据集的特征的维度 :param value: 特征的值 :return: 符合该特征的所有实例(并且自动移除掉这维特征) """ retDataSet = [] for featVec in dataSet: if featVec[axis] == value: reducedFeatVec = featVec[:axis] # 删掉这一维特征 reducedFeatVec.extend(featVec[axis + 1:]) retDataSet.append(reducedFeatVec) return retDataSet
3cfddeeec479e369b35fd4910e2a7cd6e0e7d2f7
692,533
from typing import Dict from typing import Any from typing import Tuple from typing import Optional def deconstruct_entry(ServiceNowCMDBContext: Dict[str, Any]) -> Tuple[str, Optional[str], Optional[str], Optional[str], Optional[str], Optional[str]]: """ deconstruct_entry Extracts device relevant fields from a log entry. :type ServiceNowCMDBContext: ``Dict[str, Any]`` :param ServiceNowCMDBContext: ServiceNowCMDB.Record :return: Tuple where the first element is the name or None, the second element is the sys class name or None, the third element is the sys_id or None, the fourth element is the asset display value or None, the fifth element is the asset link or None, and the final element is the asset value or None. :rtype: ``Tuple[Optional[str], Optional[str], Optional[str], Optional[int], Optional[str], Optional[str]]`` """ name = ServiceNowCMDBContext.get("Attributes", {}).get("name") sys_class_name = ServiceNowCMDBContext.get("Attributes", {}).get("sys_class_name") sys_id = ServiceNowCMDBContext.get("Attributes", {}).get("sys_id", "Unknown") asset_display_value = ServiceNowCMDBContext.get("Attributes", {}).get("asset", {}).get("display_value") asset_link = ServiceNowCMDBContext.get("Attributes", {}).get("asset", {}).get("link") asset_value = ServiceNowCMDBContext.get("Attributes", {}).get("asset", {}).get("value") return sys_id, name, sys_class_name, asset_display_value, asset_link, asset_value
bbaf018fac969ceb6b753ea0f8429254ca6daf3a
241,619
def get_max_row_column(train, val, test): """Returns the total number of rows, columns from train, validation and test arrays in COO form.""" r = max(max(train[:, 0]), max(val[:, 0]), max(test[:, 0])).astype(int) + 1 c = max(max(train[:, 1]), max(val[:, 1]), max(test[:, 1])).astype(int) + 1 return r, c
43f07cc68f5b4dcee2503ffb0d704ad599407efd
643,847
from typing import Union def manipulate_reward(shift: Union[int, float], scale: Union[int, float]): """Manipulate reward in every step with shift and scale. Args: shift: Reward shift. scale: Reward scale. Return: Manipulated reward. """ if shift is None: shift = 0 if scale is None: scale = 1 return lambda reward, action, state, done: (reward - shift) / scale
a486f32dc07b92ac4204a39cdcd86e96fa1810e6
556,752
def print_summary(api, campaign_id): """Print a campaign summary.""" summary = api.campaigns.summary(campaign_id=campaign_id) print("Campaign Summary:") print(f"\tName: {summary.name}") print(f"\tStatus: {summary.status}") print(f"\tLaunch Date: {summary.launch_date}") print(f"\tCompleted Date: {summary.completed_date}") print(f"\tTotal Users: {summary.stats.total}") print(f"\tTotal Sent: {summary.stats.sent}") print(f"\tTotal Clicks: {summary.stats.clicked}") return True
66b2e41d06db64ba79a3b9b5bcb6f4265995cab7
495,911
def separate_ctrlpts_weights(ctrlptsw): """ Divides weighted control points by weights to generate unweighted control points and weights vector. This function is dimension agnostic, i.e. control points can be in any dimension but the last element of the array should indicate the weight. :param ctrlptsw: weighted control points :type ctrlptsw: list, tuple :return: unweighted control points and weights vector :rtype: list """ ctrlpts = [] weights = [] for ptw in ctrlptsw: temp = [float(pw / ptw[-1]) for pw in ptw[:-1]] ctrlpts.append(temp) weights.append(ptw[-1]) return [ctrlpts, weights]
c283a6ae3e9ad7642ebe78d5ca1756757e988eaf
189,881
def _MakeSampleSeconds(sample_times): """Helper to convert an array of time values to a tr157 string.""" deltas = [str(int(round(end - start))) for start, end in sample_times] return ','.join(deltas)
63a0eb16f100fea6ce589cbe8b94896796470abb
248,963
def add_permission_request(response, original_message): """ Changes the response card to ask for location permissions and adds to the output speech to alert user to enable location settings for app. """ permission_card = { "type": "AskForPermissionsConsent", "permissions": [ "read::alexa:device:all:address:country_and_postal_code" ] } permission_message = ( "To get your country's currency automatically, please enable location " "permissions for crypto price in your alexa app" ) response['response']['card'] = permission_card new_message = '. '.join([original_message, permission_message]) response['response']['outputSpeech']['text'] = new_message return response
abeff68c7c704dc94beee3c4d416436fe0d24ecc
460,612
from typing import Optional from typing import Dict from typing import Any from typing import Iterable def get_value(dictionnary: Optional[Dict[str, Any]], key_list: Iterable[str]) -> Any: """Get nested value from Dict. Returns None if one of the keys is absent""" if dictionnary is None: result = None else: head, *tail = key_list if len(tail) == 0: result = dictionnary.get(head) else: result = get_value(dictionnary.get(head), tail) return result
67f9a5e800b0235ae93878f5d86edfc09afdbf5f
552,284
import yaml def load_yaml(yaml_path): """Load the yaml|json file Returns: A dict which contains the config info """ with open(yaml_path, 'r') as f_config: config_dict = yaml.full_load(f_config) return config_dict
d6f2b02aedd98cc13b49aae676596d945d7a3c98
313,260
def either(a, b): """ :param a: Uncertain value (might be None). :param b: Default value. :return: Either the uncertain value if it is not None or the default value. """ return b if a is None else a
3fd2f99fa0851dae6d1b5f11b09182dbd29bb8c1
709,371
import operator def most_recent_assembly(assembly_list): """Based on assembly summaries find the one submitted the most recently""" if assembly_list: return sorted(assembly_list, key=operator.itemgetter('submissiondate'))[-1]
1d7ecf3a1fa862e421295dda0ba3d89863f33b0f
4,327
def canonicalize(uncanonical): """ takes a stitch invention and permutes the #i indices such that forall j and k, if j<k then the first instance of #j always comes before the first instance of #k """ res = uncanonical i = 100 while i >= 0: res = res.replace('#'+str(i), f'#_#_{i}#_#_') i -= 1 # go in decreasing order so #100 doesnt get rewritten by #1 etc # get ordering of first instance of each ivar ivars = [] for ivar in res.split('#_#_'): if ivar.isdigit() and ivar not in ivars: ivars.append(int(ivar)) i = 100 while i >= 0: if i in ivars: # for example if #2 was the first ivar to appear then itd get rewritten to #0 res = res.replace(f'#_#_{i}#_#_', '#' + str(ivars.index(i))) i -= 1 # go in decreasing order so #100 doesnt get rewritten by #1 etc return res
fdeccc95dd61d4973b623665d4b45098a37eeed6
144,029
import socket def free_port() -> int: """ Return free port on the localhost. Returns ------- int Free port number on the localhost. """ sock = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM) sock.bind(("localhost", 0)) port: int _, port = sock.getsockname() sock.close() return port
014440699686f00322a2dd1466b9df7ad3b6c649
398,124
def get_collection_keys(cleaned_zot_files): """ Gets the collection (folder) id keys for each entry in the cleaned Zotero files """ col_keys = [] if 'collections' in cleaned_zot_files['data'].keys(): if len(cleaned_zot_files['data']['collections']) > 1: for i in cleaned_zot_files['data']['collections']: col_keys.append(i) elif len(cleaned_zot_files['data']['collections']) == 1: col_keys.append(cleaned_zot_files['data']['collections'][0]) else: pass return col_keys
52274c04a3c9ec0e9218914a36fdd33418e4aaa6
657,846
def rho2_rho1(M1, gamma): """Density ratio across a normal shock (eq. 3.53) :param <float> M1: Mach # before the shock :param <float> gamma: Specific heat ratio :return <float> Density ratio r2/r1 """ n1 = (gamma + 1.0) * M1 ** 2 d1 = 2.0 + (gamma - 1.0) * M1 ** 2 return n1 / d1
d61eaee3d66e5478a5db93bde784c510ce9137a4
618,164
import itertools def labeledBeamerFrames(pdfInfos): """Given a PDFInfos object, detect whether the PDF contains beamer \frame{}s with [label=name]s. For every named frame, return a pair (name, list_of_pages) in a list. If the PDF does not contain corresponding named link targets (with names like 'name', 'name<1>', 'name<2>' etc.), returns an empty list.""" result = [] names = pdfInfos.names() for name in names: pages = [] for subframe in itertools.count(1): page = names.get(name + b'<%d>' % subframe) if page is None: break pages.append(page) if pages: result.append((name, pages)) print("%d pages out of %d belong to labeled beamer slides." % ( sum(len(pages) for name, pages in result), pdfInfos.pageCount())) return sorted(result, key = lambda name_pages: name_pages[1][0])
332fb3eb1717a27dc1d90f65c8bf317c7f580acb
454,866
def adjust_asymp_with_chronic(asymp_column, chronic_column): """ Remove asymptomatic flag for people with chronic disease Parameters ---------- asymp_column : A boolean array storing people with asymptomatic infection chronic_column : A boolean array storing people with chronic disease Returns ------- out : Updated asymptomatic array """ new_asymp_column = asymp_column.copy() new_asymp_column[chronic_column == 1] = 0 return new_asymp_column
7848b09c36ee183e6a884647326822ab6f254ac5
634,021
from typing import Callable import functools def cached_property(func: Callable) -> property: """Customized cached property decorator Args: func: Member function to be decorated Returns: Decorated cached property """ return property(functools.lru_cache(None)(func))
ff40239f95825d8a3acb6090ffc28dd479d727f8
139,679
def dfdb(B, E): """ B is the base E is the exponent f = B^E partial df/dB = E * B**(E-1) """ out = E * (B**(E-1)) return out
89047a198028320ecd2cbfac26064db6af8a784b
39,008
def check_keys(in_dict): """Checks which keys are present within the input dictionary This function looks within the input dictionary and checks which keys are contained within it. Then, with these keys, it generates a list containing these keys and returns this list as output. Parameters ---------- in_dict : dict Gives the patient information Returns ------- list Contains the keys within the dictionary """ my_keys = list(in_dict.keys()) return my_keys
e38c1853b2a73a35c5b615e35980e2b6921825a4
642,860
def _GetClearedFieldsForUrlRewrite(url_rewrite, field_prefix): """Gets a list of fields cleared by the user for UrlRewrite.""" cleared_fields = [] if not url_rewrite.pathPrefixRewrite: cleared_fields.append(field_prefix + 'pathPrefixRewrite') if not url_rewrite.hostRewrite: cleared_fields.append(field_prefix + 'hostRewrite') return cleared_fields
bc0a4e3e068ebcdcf96b5e6f5cb6cdc0facd02e2
219,973
def xl_col_to_name(col, col_abs=False): """Convert a zero indexed column cell reference to a string. Args: col: The cell column. Int. col_abs: Optional flag to make the column absolute. Bool. Returns: Column style string. """ col_num = col if col_num < 0: raise ValueError("col arg must >= 0") col_num += 1 # Change to 1-index. col_str = "" col_abs = "$" if col_abs else "" while col_num: # Set remainder from 1 .. 26 remainder = col_num % 26 if remainder == 0: remainder = 26 # Convert the remainder to a character. col_letter = chr(ord("A") + remainder - 1) # Accumulate the column letters, right to left. col_str = col_letter + col_str # Get the next order of magnitude. col_num = int((col_num - 1) / 26) return col_abs + col_str
11ebb0e82847e5a1cddeace375a5a0cc3f30bf1b
660,410
import torch def is_gpu_available() -> bool: """Check if GPU is available Returns: bool: True if GPU is available, False otherwise """ return torch.cuda.is_available()
a56cdd29dfb5089cc0fc8c3033ba1f464820778a
674,458
def _get_in_response_to(params): """Insert InResponseTo if we have a RequestID.""" request_id = params.get('REQUEST_ID', None) if request_id: return { 'IN_RESPONSE_TO': request_id, **params, } else: return params
8179ea86346d8eb13d1613fc43e875d2ab9cc673
385,220
def RoundUpRestricted(in_value:int, given_dim:int =100, isBidrectional:bool =True): """ This function return the smallest value that satisfies the rule [in_value % (given_dim * dimension_multiplier) = 0] :param in_value:int: given value :param given_dim:int=100: desired step size :param isBidrectional:bool=True: sets the dimension_multiplier to 1 or 2 """ try: dimension_multiplier = 2 if isBidrectional else 1 allowed_dim_products = given_dim * dimension_multiplier if((in_value%allowed_dim_products) != 0): while(in_value > allowed_dim_products): allowed_dim_products += allowed_dim_products return allowed_dim_products else: return in_value except Exception as ex: template = "An exception of type {0} occurred in [ContentSupport.RoundUpRestricted]. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) print(message)
79cda7b977420cc0678e4e1eaa36cb43e2ccef47
336,622
from pathlib import Path import hashlib def get_binary_hash(path: Path) -> str: """Return the MD5 hash of the given file.""" hasher = hashlib.md5() with path.open("rb") as f: for chunk in iter(lambda: f.read(4096), b""): hasher.update(chunk) return hasher.hexdigest()
610ebcb981696637ec7df5dc8bf9825779d52e9f
439,929
import six def merge(*dictionaries): """Recursively merge one or more dictionaries together. Conflict resolution: - Dictionary values are recursively merged. - List values are added together. - Sets are combined with `__or__` (equivalent of set.union). - Everything else, the right-most value wins. - If values are type mismatches in the above resolution rules, raise ValueError. Args: *dictionaries (list(dict)): Dictionaries to be merged. Returns: dict: The merged dictionary. """ answer = {} for d in dictionaries: for k, v in six.iteritems(d): # If the value is not yet found in the answer, then # simply add it and move on. if k not in answer: answer[k] = v continue # If the values are both lists, append them to one another. if isinstance(answer[k], list): if not isinstance(v, list): raise ValueError('Attempt to merge a list and non-list.') answer[k] = answer[k] + v continue # If the values are both sets, take their union. if isinstance(answer[k], set): if not isinstance(v, set): raise ValueError('Attempt to merge a set and non-set.') answer[k] = answer[k] | (v) continue # If the values are both dictionaries, merge them recursively # by calling this method. if isinstance(answer[k], dict): if not isinstance(v, dict): raise ValueError('Attempt to merge a dict and non-dict.') answer[k] = merge(answer[k], v) continue # These are either primitives or other objects; the right-hand # value wins. answer[k] = v return answer
d3c52a3bdb1331c8e1e0801079d6b19f8c18153a
353,352
def link_easy(sid): """ Creates an html link to a dataset page in Easy. :param sid: a dataset id :return: link to the page for that dataset """ prefix = 'https://easy.dans.knaw.nl/ui/datasets/id/' return '<a target="_blank" href="{}{}">{}</a>'.format(prefix, sid, sid)
f329ac256e459bf79572b8686a1b6be003efccae
695,279
def shorten_str(text: str, width: int = 30, suffix: str = "[...]") -> str: """Custom string shortening (`textwrap.shorten` collapses whitespace).""" if len(text) <= width: return text else: return text[: width - len(suffix)] + suffix
9b41b35222bdbdc528ab64aae05bb52851561ebb
604,503
def index_dictionary(dictionary: dict, n=0): """Get the value given a dictionary and an index. Raises an IndexError if out of bounds.""" if n < 0: n += len(dictionary) for i, key in enumerate(dictionary.keys()): if i == n: return dictionary[key] raise IndexError('ERROR: Index out of bounds in dictionary.')
b1871701c0890c18e95f9c0aa3a6cdebd51ce03a
297,812
def _title_to_snake(src_string): """Convert title case to snake_case.""" return src_string.lower().replace(" ", "_").replace("/", "-")
ff0e56d48be19ed1ab7404978acf1eef146dcdf3
540,121
def distance(point1, point2): """Return the calculated distance between the points. Manhattan distance. """ x0, y0 = point1 x1, y1 = point2 return abs(x1 - x0) + abs(y1 - y0)
d99157e3f661035772330e92b0e19df2d6d6cc40
370,304
def _zone(index): """Chooses a GCP zone based on the index.""" if index < 6: return 'us-central1-a' elif index < 12: return 'us-east1-b' elif index < 18: return 'us-east4-c' elif index < 24: return 'us-west2-a' else: raise ValueError('Unhandled zone index')
9d5a86ce022530e59301f82e73cf3bc90cf6df87
657,809
import sympy def integer_partitions(target, nb_ele): """ return all possible ways to sum to target using nb_ele, allowing 0 to be one of the element for example, integer_partitions(4, 2) returns ([0,4], [4,0], [1,3], [3,1], [2,2]) """ if target == 0: return [[0] * nb_ele] ans = [] for i in range(nb_ele): for part in sympy.utilities.iterables.ordered_partitions(target, m=i+1): arr = [0] * (nb_ele - (i + 1)) + part for j in sympy.utilities.iterables.multiset_permutations(arr): ans.append(j) return ans
248c21e4031bcad66f0f39f0751775aad0e309d1
252,047
from datetime import datetime def parse_time(x): """Extract hour, day, month, and year from time category.""" DD = datetime.strptime(x, "%Y-%m-%d %H:%M:%S") time = DD.hour day = DD.day month = DD.month year = DD.year return time, day, month, year
d7ad14106b08d3f39767db8fe00f34fec4290a9d
192,335
def _transform_opt(opt_val): """Transform a config option value to a string. If already a string, do nothing. If an iterable, then combine into a string by joining on ",". Args: opt_val (Union[str, list]): A config option's value. Returns: str: The option value converted to a string. """ if isinstance(opt_val, (list, tuple)): return ','.join(opt_val) else: return opt_val
2ade412fda106122e2d170fdd7ae819c47997b4f
553,672
def get_texture_type(dimensions): """Get texture type by dimensionality.""" assert 1 <= dimensions <= 3 return eval('GL_TEXTURE_{}D'.format(dimensions))
d730e55fe0df79dc645d3170a514a040e50f4546
462,104
import csv def rows_in_csv(filename): """Helper function to quickly count the number of rows in the passed csv file.""" with open(filename, encoding="UTF8", mode="rt") as f: reader = csv.reader(f) count = 0 for _ in reader: count += 1 return count - 1
955dbe18ea92e0df76b749ec707d86e9b8dcd94c
179,547
import re def clean_regex(text): """ Clean contraction from the text Parameters ---------- text: string Text lines of string Return ------ string Cleaned contraction """ clean_dict = { r"i'm": r"i am", r"he's": r"he is", r"she's": r"she is", r"that's": r"that is", r"what's": r"what is", r"where's": r"where is", r"\'ll": r" will", r"\'ve": r" have", r"\'re": r" are", r"\'d": r" would", r"won't": r"will not", r"can't": r"can not", r"I've": r"I have" } for each in clean_dict: text = re.sub(each, clean_dict[each], text) return text
107df5223360573c4d33193b1ae5c7f24ce2cc42
260,607
def get_cluster_proportions(adata, cluster_key="cluster_final", sample_key="replicate", drop_values=None): """ Input ===== adata : AnnData object cluster_key : key of `adata.obs` storing cluster info sample_key : key of `adata.obs` storing sample/replicate info drop_values : list/iterable of possible values of `sample_key` that you don't want Returns ======= pd.DataFrame with samples as the index and clusters as the columns and 0-100 floats as values """ adata_tmp = adata.copy() sizes = adata_tmp.obs.groupby([cluster_key, sample_key]).size() props = sizes.groupby(level=1).apply(lambda x: 100 * x / x.sum()).reset_index() props = props.pivot(columns=sample_key, index=cluster_key).T props.index = props.index.droplevel(0) props.fillna(0, inplace=True) if drop_values is not None: for drop_value in drop_values: props.drop(drop_value, axis=0, inplace=True) return props
fd0b50d9b07b62441a4f45bb93aacd7bb0360b66
457,971
import decimal def create_update_item_input(item): """Return input for DynamoDB `update_item()` operation on `item` setting `isRecent` to `1`. Parameters ---------- item : dict DynamoDB `Deal` item to update Returns ------- dict Input for DynamoDB `update_item` operation """ return { 'Key': {'id': item['id']}, 'UpdateExpression': 'SET isRecent=:r', 'ExpressionAttributeValues': { ':r': decimal.Decimal(1) }, 'ReturnValues': 'UPDATED_NEW' }
f1af37865ea3934b927247c5bc7f35b156db461c
344,654
def application(environ, start_response): """Serve the button HTML.""" with open('wsgi/button.html') as f: response_body = f.read() status = '200 OK' response_headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(response_body))), ] start_response(status, response_headers) return [response_body.encode('utf-8')]
97f1f793f234dbd3c29e9c4a791a224ba32c984b
707,586
def get_input(prompt): """Modified raw input that requires a non-empty response.""" res = None while not res: res = input(prompt) return res
ed15f5b39de0f16477ba2091574812c8a9e6ee75
445,601
def getType(item) : """Attempt to determine what type of value a string represents""" item = item.strip() if not item : return "NULL" if item[0] == "$": return "$" if item.strip("0123456789,.") : return "STR" return "NUM"
423fbef0922339c469b313ba76ef7e6c43b3c9d7
594,339
def is_skill(pos): """ Takes some string named pos ('QB', 'K', 'RT' etc) and checks whether it's a skill position (RB, WR, TE). """ return pos in ['RB', 'WR', 'TE']
4f41be47ecd75528f86c73c16a08a0308f7616d6
372,733
def get_modified_files_list(diff): """Get list of modified or newly added files list""" file_list = [] for file in diff["files"]: if file["status"] == "modified" or file["status"] == "added": file_list.append(file["filename"]) return file_list
9219d0e4f41ee9aa9b64e0a9867a6a90c679dc02
82,836
def _as_list(list_str, delimiter=','): """Return a list of items from a delimited string (after stripping whitespace). :param list_str: string to turn into a list :type list_str: str :param delimiter: split the string on this :type delimiter: str :return: string converted to a list :rtype: list """ return [str.strip(item).rstrip() for item in list_str.split(delimiter)]
2cfa1939fd3964a7282254cb80a7b1bb4a48b7b0
313,474
import requests import json def custom_ws_perm_maker(user_id: str, ws_perms: dict): """ Returns an Adapter for requests_mock that deals with mocking workspace permissions. :param user_id: str - the user id :param ws_perms: dict of permissions, keys are ws ids, values are permission. Example: {123: "a", 456: "w"} means workspace id 123 has admin permissions, and 456 has write permission :return: an adapter function to be passed to request_mock """ def perm_adapter(request): perms_req = request.json().get("params")[0].get("workspaces", []) ret_perms = [] for ws in perms_req: ret_perms.append({user_id: ws_perms.get(ws["id"], "n")}) response = requests.Response() response.status_code = 200 response._content = bytes( json.dumps({"result": [{"perms": ret_perms}], "version": "1.1"}), "UTF-8" ) return response return perm_adapter
86837c953dafd6b96f70de79c64ce72b6997e0cc
658,328
def get_nested_answers(nested_questions): """Takes a list of question-sets; returns a list of answers.""" return [question['answers'] for qset in nested_questions for question in qset['questions']]
ce96953bd114bc814d72ec01caf625810b02096f
405,666
import torch def square_distance(xyz1, xyz2): """ Compute the square of distances between xyz1 and xyz2. Parameters ---------- xyz1 : torch.tensor [B, C, N] xyz tensor xyz2 : torch.tensor [B, C, M] xyz tensor Return ------ distances : torch.tesnor [B, N, M] distances between xyz1 and xyz2 """ # base: https://github.com/WangYueFt/dgcnn/blob/master/pytorch/model.py inner = -2*torch.matmul(xyz1.transpose(2, 1), xyz2) xyz_column = torch.sum(xyz2**2, dim=1, keepdim=True) xyz_row = torch.sum(xyz1**2, dim=1, keepdim=True).transpose(2, 1) square_dist = torch.sqrt(xyz_column + inner + xyz_row) return square_dist
741b91bd51d111d3831a8139dc5e8a425b8571e0
432,021
import bisect def find_lt(array, x): """Find rightmost value less than x. Example:: >>> find_lt([0, 1, 2, 3], 2.5) 2 **中文文档** 寻找最大的小于x的数。 """ i = bisect.bisect_left(array, x) if i: return array[i - 1] raise ValueError
7cde3a9e5a5c899d1c9fedc9ec5aa20705f7bd26
140,640
def jaccard(graph, lda_topics): """ Builds a function to estimate Jaccard Similarity w.r.t. intermediary topics (from topic graph) in lda_topics. """ Q_it = set(x[0] for x in lda_topics if graph.has_node(x[0]) and graph.node[x[0]]['is_intermediary']) def jaccard_similarity(P): if not P or not Q_it: return 0.0 P_it = set(x[0] for x in P if graph.has_node(x[0]) and graph.node[x[0]]['is_intermediary']) #print P_it, Q_it, float(len(P_it & Q_it)) / len(P_it | Q_it), P_it & Q_it return float(len(P_it & Q_it)) / len(P_it | Q_it) return jaccard_similarity
d33f0d2b72c2e76fd681a30655bfb07ae48d88a5
390,643
def extractDidParts(did): """ Parses and returns a tuple containing the prefix method and key string contained in the supplied did string. If the supplied string does not fit the pattern pre:method:keystr a ValueError is raised. :param did: W3C DID string :return: (pre, method, key string) a tuple containing the did parts. """ try: # correct did format pre:method:keystr pre, meth, keystr = did.split(":") except ValueError as ex: raise ValueError("Malformed DID value") if not pre or not meth or not keystr: # check for empty values raise ValueError("Malformed DID value") return pre, meth, keystr
e106f197321e0686a5091ba03681f1e2a9752ba4
549,985
def IsTryJobResultAtRevisionValid(result, revision): """Determines whether a try job's results are sufficient to be used. Args: result (dict): A dict expected to be in the format { 'report': { 'result': { 'revision': (dict) } } } revision (str): The revision to ensure is in the result dict. """ return result and revision in result.get('report', {}).get('result', {})
1515c82d2673139fb0fec01e662ca62057f715de
83,503
def plato_to_sg(deg_plato): """ Degrees Plato to Specific Gravity :param float deg_plato: Degrees Plato :return: Specific Gravity :rtype: float The simple formula for S.G. is: :math:`\\text{SG} = 1 + 0.004 \\times \\text{Plato}` The more precise calculation of SG is: :math:`\\text{SG} = \\frac{Plato}{258.6 - \\big(\\frac{Plato}{258.2} \\times 227.1\\big)} + 1` Source: * http://www.learntobrew.com/page/1mdhe/Shopping/Beer_Calculations.html """ # noqa return (deg_plato / (258.6 - ((deg_plato / 258.2) * 227.1))) + 1.0
135d9a5cf0c982ae71c158997b1182ab8b627609
233,420
def identify_cat_con(df,threshold=0.05): """ Heuritic identification of continuous and categorical data Parameters: ----------- df: pd.DataFrame threshold: float, [0,1], default=0.05 Ratio of unique values vs total number of values Returns: -------- con_data: list of column names of continuous variables cat_data: list of column names of categorical variables """ cat_data = [] con_data =[] for col in df.columns: colcount = df[col].nunique()/df[col].count() if colcount<=threshold: cat_data.append(col) else: con_data.append(col) return con_data,cat_data
5a3e1a7343f21c8e51d2f2a343002f2914d1fedc
430,690
def get_digit(number, digit): """ Given a number, returns the digit in the specified position, for an out of range digit returns 0 """ digit_sum = 0 for i in range(digit): # Accumulate all the other digits and subtract from the original number digit_sum += number - ((number // 10**(i+1)) * 10**(i+1) + digit_sum) return digit_sum // 10**(digit-1)
67ba5dbffb0ad5bdf2a8f7d59970428a1195e868
591,139
from io import StringIO def configObj2Str(cobj): """Dump a Configobj instance to a string.""" outstr = StringIO() cobj.write(outstr) return outstr.getvalue()
c71f47f5b6b1e4641b7c07091ce98dc665aa9edf
306,402
def parse_logs_align_isize(fname): """Parse _isize_table.txt Inputs: fname - filename of table Returns: data - dictionary of insert size data """ data = {'percent': {}, 'readcnt': {}} with open(fname, 'r') as f: file_data = f.read().splitlines()[2:] for l in file_data: fields = l.split('\t') data['percent'][int(fields[0])] = 100.0 * float(fields[1]) data['readcnt'][int(fields[0])] = float(fields[2]) return data
28043418fabf9a4a0f515aa00ba556ff91fd0165
235,354
def parse_description(description): """Return the parameter name and unit from the parameter description :param description: A description containing a parameter name and unit :type description: string :returns: Name and units of a parameter :rtype: tuple >>> description = "Temperature, water, degrees Celsius" >>> parse_description(description) ('Temperature', 'degrees Celsius') """ name = description.split(",")[0] units = description.split(",")[-1].strip() return name, units
471ae0af756ed8bfaa052acb0422c80733911572
544,303
def PROP_GEOMETRICA_ESTADIO_I(H, B_F, B_W, H_F, A_SB, ALPHA_MOD, D): """ Esta função calcula as propriedades geométricas no estádio I. Entrada: H | Altura da viga | m | float B_F | Base de mesa superior da seção | m | float B_W | Base de alma da seção | m | float H_F | Altura de mesa superior da viga | m | float A_SB | Area de aço na seção tracionada | m² | float ALPHA_MOD | Relação entre os modulos | | float D | Altura útil da seção | m | float Saída: A_C | Área de concreto no estádio 1 | m² | float X_I | Centro geometrico da viga no estádio 1 | m | float I_I | Inércia da viga no estádio 1 | m^4 | float """ A_C = (B_F - B_W) * H_F + B_W * H + A_SB * (ALPHA_MOD - 1) X_I = ((B_F - B_W) * ((H_F ** 2) / 2) + B_W * ((H ** 2 ) / 2) + A_SB * (ALPHA_MOD - 1) * D) / A_C I_I = ((B_F - B_W) * H_F ** 3) / 12 + (B_W * H ** 3) / 12 + (B_F - B_W) * H_F * (X_I - H_F / 2) ** 2 + B_W * H * (X_I - H / 2) ** 2 + A_SB * (ALPHA_MOD - 1) * (X_I - D) ** 2 return A_C, X_I, I_I
72f7872c8958c40dea76bccaca6c0cf2779d35dd
543,762
import io def remove_multiple_newlines_in_txt(txt: str) -> str: """ This function will remove multiple, sequential newlines in text (str) data. :param txt: a str containing the text to be cleaned. :return: a str containing the text with multiple, sequential newlines removed. """ clean_txt = '' # convert the text string into a buffer so that we can read lines. txt_buffer = io.StringIO(txt) last_line = True # initialize to True so that on our first pass through the loop we'll get the first line. next_line = txt_buffer.readline() while next_line: stripped_next_line = next_line.strip() # was our previous line also a new line? if last_line: # strings in Python are "falsey" so '' will not pass. # no, was not a newline... add the current line to our cleaned text. clean_txt += next_line else: # yes, our previous line was a newline... is our current? if stripped_next_line: # must have content... write it out. clean_txt += next_line # set last_line to our current line (stripped version) and then grab the next line. last_line = stripped_next_line next_line = txt_buffer.readline() return clean_txt
9b1be808c4253b0f2b58b1985b10417a65b7cdeb
45,184
def count_params(model): """ Count number of trainable parameters in PyTorch model """ num_params = sum(p.numel() for p in model.parameters() if p.requires_grad) return num_params
fe6505100a8ffeb5365d96eb21656cc30b8777d8
457,663
def countif(n, func): """ return number of items in n having a non-zero return from func """ n = [1 for i in n if (func(i))] return sum(n)
afd95d4e6d0838f0e11c373ab46f5b08db4f5b77
250,404
def zigzag(value: int) -> int: """Zig-zag encode a parameter to turn signed ints into unsigned ints. Zig-zag encoding is required by Geometry commands that require parameters, and the number of parameters will be (number_of_commands * number_of_arguments). For more information about this technique, check out: https://developers.google.com/protocol-buffers/docs/encoding#types Args: value: the integer value to encode Returns: The encoded representation of the value. """ return (value << 1) ^ (value >> 31)
1bd49a0955493360423cb32a19e4ff6cf8fc80ca
449,617
def split_int(i, p): """ Split i into p buckets, such that the bucket size is as equal as possible Args: i: integer to be split p: number of buckets Returns: list of length p, such that sum(list) = i, and the list entries differ by at most 1 """ split = [] n = i / p # min items per subsequence r = i % p # remaindered items for i in range(p): split.append(int(n + (i < r))) return split
2aedf0a008d91f1635aa1117901ae525fbdb7d7e
681,234
def quantile(x, percentile): """ Returns value of specified quantile of X. :param list or tuple x: array to calculate Q value. :param float percentile: percentile (unit fraction). :return: Q value. :rtype: int or float :raise ValueError: when len of x == 0 """ if x: p_idx = int(percentile * len(x)) return sorted(x)[p_idx] else: raise ValueError('len of x == 0')
c14e3271e1bf0d361de34a58179f1a4a5d428e40
277,209
def set_car(pair, val): """Set car of the pair.""" pair.car = val return pair
d50f0b3719bc12f41ef9ca41a3ceeb467d7d4526
497,524
def maybe_single(sequence): """ Given a sequence, if it contains exactly one item, return that item, otherwise return the sequence. Correlary function to always_iterable. >>> maybe_single(tuple('abcd')) ('a', 'b', 'c', 'd') >>> maybe_single(['a']) 'a' """ try: (single,) = sequence except ValueError: return sequence return single
65685fa1e58d265638fdbff7fa002062e74ed0b0
286,106
def _make_unique(key, val): """ Make a tuple of key, value that is guaranteed hashable and should be unique per value :param key: Key of tuple :param val: Value of tuple :return: Unique key tuple """ if type(val).__hash__ is None: val = str(val) return key, val
65d746276f635c129aa0a5aeb9b9f467453c0b2a
708,533
def has_relative_protocol(uri): """Return True if URI has relative protocol '//' """ start = uri[:2] if start == '//': return True return False
40c37b5f7ec6ea6de2ed02b742b2f2d0b149bc32
654,118
def diameter(d_2): """Calculate internal diameter at the start angle. :param d_2 (float): diameter of the impeller at section 2 [m] :return d (float): diameter [m] """ d = round(1.1 * d_2, 3) return d
b2fe808e0cd9aee81bfe29d7fb35f643710e5a43
128,390
import time import random def _generate_name(name): """ Generate names for tested objects where you can probably tell at a glance which objects were created by which executions of the unittests. """ return 'test-%s-%s-%s' % (time.strftime('%Y%m%d%H%M%S'), random.randint(0, 999), name)
7a182f3f810e9391c3290b0d283164afaf1fe5f0
315,524
import socket def is_open_port(port): """ Check if a port is open (listening) or not on localhost. It returns true if the port is actually listening, false otherwise. :param port: The port to check. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('127.0.0.1',port)) return result == 0
4eb8f52744cc7f330dd101b613d5db4ab8d0d0fc
700,661
def are_all_strings_in_text(text, list_of_strings): """ :param text: output from convert_pdf_to_text :type text: list of str :param list_of_strings: a list of strings used to identify document type :type list_of_strings: list of str :return: Will return true if every string in list_of_strings is found in the text data :rtype: bool """ for str_to_find in list_of_strings: if str_to_find not in text: return False return True
a4ef6a2067e85fdc97c767881f26f9188c1f55ef
598,173
def words_and_tags_from_wsj_tree(tree_string): """Generates linearized trees and tokens from the wsj tree format. It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449. Args: tree_string: tree in wsj format Returns: tuple: (words, linearized tree) """ stack, tags, words = [], [], [] for tok in tree_string.strip().split(): if tok[0] == "(": symbol = tok[1:] tags.append(symbol) stack.append(symbol) else: assert tok[-1] == ")" stack.pop() # Pop the POS-tag. while tok[-2] == ")": tags.append("/" + stack.pop()) tok = tok[:-1] words.append(tok[:-1]) return str.join(" ", words), str.join(" ", tags[1:-1]) # Strip "TOP" tag.
e3871547254d33d5ab99cf1ec685b291db620a0f
596,515
def pyx_is_cplus(path): """ Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False. """ for line in open(path, 'rt'): if line.startswith('#') and '=' in line: splitted = line.split('=') if len(splitted) != 2: continue lhs, rhs = splitted if lhs.strip().split()[-1].lower() == 'language' and \ rhs.strip().split()[0].lower() == 'c++': return True return False
d8ad5c7884453a5dc3cec6b340d8fa5ac3094cb3
30,006
import copy def hill_climb(nsteps, start_node, get_next_node): """Modular hill climbing algorithm. Example: >>> def get_next_node(node): ... a, b = random.sample(range(len(node)), 2) ... node[a], node[b] = node[b], node[a] ... plaintext = decrypt(node, ciphertext) ... score = lantern.score(plaintext, *fitness_functions) ... return node, score, Decryption(plaintext, ''.join(node), score) >>> final_node, best_score, outputs = hill_climb(10, "ABC", get_next_node) Args: nsteps (int): The number of neighbours to visit start_node: The starting node get_next_node (function): Function to return the next node the score of the current node and any optional output from the current node Returns: The highest node found, the score of this node and the outputs from the best nodes along the way """ outputs = [] best_score = -float('inf') for step in range(nsteps): next_node, score, output = get_next_node(copy.deepcopy(start_node)) # Keep track of best score and the start node becomes finish node if score > best_score: start_node = copy.deepcopy(next_node) best_score = score outputs.append(output) return start_node, best_score, outputs
1474cd2eb150295b18282d8cf651b2d38277e836
445,335
import pickle def get_byte_length(value): """Return the byte length of the pickled value.""" return len(pickle.dumps(value))
855c0fc26267babcbf2e0f79f6fc4c7ba84cd886
331,335
def dot_product(d1, d2, default_value=0): """Calcualte the dot product for the intersection of two dictionary objects. If the key does not exist in d2, default_value is used instead. """ return sum(map(lambda x: float(d1[x]) * float(d2.get(x, default_value)), d1.keys()))
144dd4bbd5ebac8bcafe316bcecba53516f840a5
389,189
def editable(el): """ Return editable part of UML element. It returns element itself by default. """ return el
5686e9eef8ba3e7bc10539d9b3494faa8e1130d4
188,983
def get_available_metrics() -> list: """Get list of available metrics.""" metrics = [ "NSE", "MSE", "RMSE", "KGE", "Alpha-NSE", "Pearson r", "Beta-NSE", "FHV", "FMS", "FLV", "Peak-Timing", ] return metrics
f872fa5411b2038ee2ccdd153508fd7d0acabdc5
593,576
def is_collection(obj): """ Return whether the object is a array-like collection. """ for typ in (list, set, tuple): if isinstance(obj, typ): return True return False
291fefe89accb27ba029d9ff195806df8f55f19d
239,385