content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y): """ Converts a quadratic Bezier curve to a cubic approximation. The inputs are the *x* and *y* coordinates of the three control points of a quadratic curve, and the output is a tuple of *x* and *y* coordinates of the four control points of the cubic cur...
fb62e1ae1ffe3d062c66e3b323905427f3bd6831
663,429
import requests def send_sms(sid, token, src, dest, text): """ src and dest are str and need the country prefix like +30 returns response in text form """ host = 'https://tadhack.restcomm.com' endpoint = '/restcomm/2012-04-24/Accounts/' + sid + '/SMS/Messages.json' url = host + endpoint ...
215329f98a165e246003f3dd3397bb3ae578c3fb
663,430
import random def split_num_into_parts(total, k): """Split the total number into k parts (somewhat randomly).""" while True: sum_so_far = 0 return_list = list() for index in range(0, k-1): avg_remaining_val = (total - sum_so_far) / (k - index) val = random.r...
979a0c8e3f909add2db91c77b2b35303a45b162b
663,431
def current_iteration(parent_iteration, child_iteration): """ :param parent_iteration: :param child_iteration: :return: """ return str(parent_iteration) + '-' + str(child_iteration)
e200e15b0b0ba98cf23c28554094942dd1e69f0c
663,432
import numpy def position_count(dct): """ the number of positions in this tuple dictionary """ pos_cnt = numpy.shape(list(dct.values()))[1] if dct else None return pos_cnt
c18c44031bb84b675c049a63c9634e3cec97a044
663,433
from typing import List from typing import Optional def parse_xlets(xlet: List[dict]) -> Optional[List[str]]: """ Parse airflow xlets for V1 :param xlet: airflow v2 xlet dict :return: table list or None """ if len(xlet) and isinstance(xlet[0], dict): tables = xlet[0].get("tables") ...
31fd909b3d479bdb2dcc9b6c9a92eeb754522d22
663,434
def cut_intensity(image, min=None, max=None): """ Args: image (np.array): min ([type]): [description] max ([type]): [description] """ image_cut = image.copy() if min is not None: image_cut[image_cut < min] = min if max is not None: image_cut[image_cut > ...
b7e4b537c53c068b0f42e35a16f82e9360528893
663,435
def let_user_pick(options: list) -> int: """ Present a list of options to the user for selection. Parameters ---------- options : list A list of options to be printed and user to choose from. Returns ------- int The index of the users selection. """ print("Plea...
f51e33e5364b52bc5663dbf631c2090c35cc4818
663,436
import string def filter_term(term, vocabulary): """If a word is not present in a vocabulary, check whether its lowercased or capitalized versions are present. If not and word is not a punctuation sign, then it is OOV. Otherwise, it is replaced by different case. Punctuation signs are omitted completely. ...
df2e014a9eff141f1e3baef7440b6ca70e7482c0
663,437
def score(buyer): """ Prints calculated score with decision of loan approval. Calculates credit score with individual component scores from class creditRating to determine loan approval. ... Argument -------- buyer : object object from class creditRating Return --------- ...
e45d3ae290f3d75bb9d147a7ede04d12f56c462b
663,438
def boost_nmhc(group, nmhc, med_max_mhc): """ Return a fraction of boost based on total number of MHCs stimulated by peptides from the IAR. :param group::param pandas.core.frame.DataFrame group: The IAR under review. :param float nmhc: The total boost amount allotted to this criterion. :param tuple...
cffbf67858b90d65c9b5d174401bd26ba82ac01b
663,439
def load_sentences(filepath): """ Given a file of raw sentences, return the list of these sentences. """ with open(filepath, 'r') as myfile: sentences = [line for line in myfile if line != '\n'] return sentences
8b136f5be7d15f10a1f1326deb661213b3b07679
663,440
def get_ssl_subject_alt_names(ssl_info): """ Return the Subject Alt Names """ altNames = '' subjectAltNames = ssl_info['subjectAltName'] index = 0 for item in subjectAltNames: altNames += item[1] index += 1 if index < len(subjectAltNames): altNames += ', ' ret...
ce38761c452d9704bdbe3309bdfa1bb46eb9a92a
663,441
def propose(prop, seq): """wrapper to access a dictionary even for non-present keys""" if seq in prop: return prop[seq] else: return None
95e0a64599fc2da29ba4d35cfb8fb24f165af5c6
663,442
import argparse def pasee_arg_parser() -> argparse.ArgumentParser: """Parses command line arguments.""" parser = argparse.ArgumentParser( prog="pasee", description="Pasee Identity Manager", epilog="All options, if given, take precedence over settings file.", ) parser.add_argume...
c020edbaa0ba0f7d9dedc399b3d7a679fa6f1297
663,443
import platform def get_platform(): """Gets the current platform.""" # We need to handle the platform a bit differently in certain cases. # Otherwise, we simply return the value that's given here. plat = platform.system().lower() if plat == "darwin": # 'macos' is the term that is being u...
2838ff6f8c2bbaeb2e1a3e264a9c0c312d06494e
663,445
import logging import os def process_conclusion( last_image_file: str, conclusion: bytes, ) -> str: """Process the "conclusion" of an emulator session. An emulator session's _conclusion_ is the 532 bytes of sector data that the Apple supplied along with its command to end the emulation session (see the...
8f1cb443e11c5234ec86b7ca3aa8c7c6eece910c
663,446
def piece_length(size): """ Calculate the ideal piece length for bittorrent data. Piece Length is required to be a power of 2, and must be larger than 16KiB. Not all clients support the same max length so to be safe it is set at 8MiB. Args ----------- size: int - total bits of all ...
ff24857c6a5fbf7dadfad7db533df2a8c2a08945
663,447
def update_lifecycle_test_tags(lifecycle, test, tags): """Returns lifecycle object after creating or updating the tags for 'test'.""" if not lifecycle["selector"]["js_test"]: lifecycle["selector"]["js_test"] = {test: tags} else: lifecycle["selector"]["js_test"][test] = tags return lifecy...
cb347e84eb4b9a11ab78ff138aed46526aa54e79
663,448
import os def find_in(path, s, suffix='txt'): """Search through `path` and its children for the first occurance of a file with `s` in its name. Returns the path of the file or `None`. """ for root, _, files in os.walk(path): for f in files: if s in f and f.endswith(suffix): ...
4dc7aaa19042b8e893014424a9d289582deaf425
663,449
def determine(userChoice, computerChoice): """ This function takes in two arguments userChoice and computerChoice, then determines and returns that who wins. """ if(userChoice == "Rock" and computerChoice == "Paper"): return "computer" elif(userChoice == "Rock" and computerChoice...
7a819a80c37da22f5a752bcb3c26953c27472fe7
663,450
from datetime import datetime import pytz def is_in_the_future(dt): """ Is this (UTC) date/time value in the future or not? """ if dt > datetime.now(pytz.utc): return True return False
4334e31472548ab35b291c333ccf3b13061e3fc9
663,451
def ensure_tuple(tuple_or_mixed, *, cls=tuple): """ If it's not a tuple, let's make a tuple of one item. Otherwise, not changed. :param tuple_or_mixed: :return: tuple """ if isinstance(tuple_or_mixed, cls): return tuple_or_mixed if tuple_or_mixed is None: return tuple...
d7d6ca13a86391f4777da2716d5d9e4fe242698e
663,452
def _interp_evaluate(coefficients, t0, t1, t): """Evaluate polynomial interpolation at the given time point. Args: coefficients: list of Tensor coefficients as created by `interp_fit`. t0: scalar float64 Tensor giving the start of the interval. t1: scalar float64 Tensor giving the end of...
600cc5e39b8859f9e1a65e49e609030f09f88eec
663,453
def GALEX_Level_Chisq(level_params, image): """ Fit flat plane to the image to find level :param level_params: :param image: :return: """ level = level_params['level'].value chi = image - level chisq = chi**2.0 return chisq
4eaf7f093f4ad1ccad31e4676b13b0ef99bd37ac
663,454
from functools import reduce def foldl(function, acc, xs): """Reduces a sequence with a function in a left-associative manner. It is helpful to visualize the left-fold as the following transformation. foldl f acc [1, 2, 3, 4, 5] + f / \ ...
d8904aa2d0af9abc028e7a91a610c8d43575e281
663,455
import json def write_json(file_path, json_obj): """Write JSON string. # Arguments file_path: `str`<br/> the absolute path to the JSON string. json_obj: `dict`<br/> a dictionary # Returns flag : bool True if saved successfully False...
3f212d2271e3b29e68d64510974b4ad1c50f7a99
663,456
def is_dom_red(color): """ ***NOTE: This needs to be updated and improved upon later Currently, this just checks to see if the red value in an image is the most prominent - there is definitely a better version of this available :param color: bgr values of the provided image :return: True if...
4adda73363496f65a6a0a06f7a138e79b06c78db
663,458
def mean(array): """ Función para calcular la media, dando relevancia a los valores más pequeños. :param array: lista de elementos a hallarle la media :type array: list :rtype: float :return: mean """ total = len(array) sum_elem = 0 for elem in array: sum_el...
5d9e64cb32f9d5f1ded543c591a441059f3ebf41
663,459
def _remove_features_from_large_corpus_model(document_term_matrix, type_ids, features): """Removes features from large corpus model. This private function is wrapped in :func:`remove_features()`. Args: document_term_matrix (pandas.DataFrame): A document-term matrix. type_ids (dict): A dict...
5eb260e6adedc53ebf929cc37ce3720378138af4
663,460
def close_one_row(series, close_today_first): """ 平当前一行 对今昨按指定要求先后平仓 :param series: :param close_today_first: 是否先平今 :return: """ ss = [] # 选择先平今还是平昨,先平的放循环前面 if close_today_first: fields = ['TodayPosition', 'HistoryPosition'] else: fields = ['HistoryPosition',...
6168f28e55c232a1a4fd07b2b95c44f49d5927eb
663,461
from datetime import datetime import re def has_sig_with_timestamp(ts, text): """ Returns an re.Match object corresponding to a user signature with the timestamp given by ts. Returns None if a match is not found. Example timestamp: 2022-05-03T00:54:18Z Example signature: [[User:ASDF|FDSA]...
9e64aeb02f22759e2f2cd39e22417ab316f10674
663,463
import importlib import re def _load_protocol_adapter(name): """Load protocol module from name""" package = None if __name__ == "__main__": package = "arcomm" else: package, _ = __name__.split(".", 1) path = ".".join((package, "protocols", name)) module = importlib.import_mod...
4654f6afecdb40031944a91f6ebca4974b2766a8
663,464
def broken_6(n): """ What comes in: A positive integer n. What goes out: Returns the sum: 1 + 1/2 + 1/3 + ... + 1/n. Side effects: None. """ total = 0 for k in range(1, n + 1): total = total + 1 / k return total
17e86195d68c531c63f748f91ec39dc04414b01e
663,465
def fantasy_pros_column_reindex(df): """Adds columns that are missing from Fantasy Pros tables and reorders columns Some tables are missing stats (no passing stats for RBs) so this will fill in the gaps and have '0' as the value for any missing column :param df: cleaned dataframe object resul...
cb846d31d9d6952650cab17cf6528d06ad9a0198
663,466
def no_comment_row(x_str): """ Tests if the row doesn't start as a comment line. """ return x_str[0] != "#"
798580a7dffaa22d17c389108d02050fedaebb51
663,467
def density(w, **kwargs): """Compute density of a sparse vector. Parameters ---------- w : array-like The sparse vector. Returns ------- float The density of w, between 0 and 1. """ if hasattr(w, "toarray"): d = float(w.nnz) / (w.shape[0] * w.shape[1]) e...
7fdd1c81cab679be8ac326aa86045cf6188fa60e
663,468
def id_from_uri(uri: str) -> str: """Get the item ID from URI address.""" return uri.rstrip("/").split("/")[-1]
e568df78c9c1b2a46501d4300d705b48467584a1
663,469
def get_supported_platforms(): # noqa: E501 """Get list of supported contest platforms Get list of supported daily fantasy contest platforms # noqa: E501 :rtype: List[str] """ return ["Draftkings", "Fanduel"]
7e837df8309d3b8b997b0b53564a59e223e752c9
663,470
def gen_model(model_name, image_tag, timeout, num_of_workers): """ Generates the Sagemaker model that will be loaded to the endpoint instances. """ model = { "SagemakerModel": { "Type": "AWS::SageMaker::Model", "Properties": { "ModelName": model_name, ...
9cac78d8c864edce7aabef5e4d86c51827a3c31c
663,471
import requests def post_nadlan_historic_deals(keyvalue): """take keyvalue from body or df fields and post to nadlan.gov.il deals REST API historic deals""" url = 'https://www.nadlan.gov.il/Nadlan.REST/Main/GetAllAssestHistoryDeals' r = requests.post(url, json=str(keyvalue)) if r.status_code != 20...
647ce57d42e5ee2724666c8b8f8a255c1f05c11e
663,472
import pickle def unpickle(file): """Unpickle something (in this case tf-id).""" with open(file, "rb") as source: return pickle.load(source)
b1fe2af493a642155d1558b506682adf2e02a034
663,473
def noise_remove_cv2(image, k): """ 去除图片的噪点 :param image: :param k: :return: """ def calculate_noise_count(img_obj, w, h): """ 计算邻域非白色的个数 """ count = 0 width, height = img_obj.shape for _w_ in [w - 1, w, w + 1]: for _h_ in [h - 1, ...
9455854146ea9c71ea15df8be2282c5a0a5e4853
663,474
def get_recommendations(sp, tracks): """ Get recommendations from a list of Spotify track ids. :param sp: Spotify OAuth :param tracks: list of Spotify track ids :return: list of tracks """ data = [] for x in tracks: results = sp.recommendations(seed_tracks=[x]) # default api lim...
d09b68bcc7ab1d947d954a62539e2505285bde9f
663,475
def lammps_copy_files(job): """Check if the submission scripts have been copied over for the job.""" return job.isfile("submit.pbs")
9d801d379155f02b93389252fd3352712f55fb2c
663,476
def encode_count_header(count): """ Generate a header for a count HEAD response. """ return { "X-Total-Count": count, }
43cb0ae99f696e10e0240364e5dc8067783084eb
663,478
def round_up(n: int, div: int): """Round up to the nearest multiplier of div.""" return ((n + div - 1) // div) * div
7ade722fa1354d67e4a7b4df453ae545c8b78135
663,479
def _bmz(pHI,pFA): """recursive private function for calculating A_{MZS}""" # use recursion to handle # cases below the diagonal defined by pHI == pFA if pFA > pHI: return _bmz(1-pHI, 1-pFA) if pFA <= .5 <= pHI: return (5-4*pHI)/(1+4*pFA) elif pFA < pHI < .5: retu...
69291e07a7c6567502109d7b1b3cfc517662e220
663,480
import random def set_montys_stage(stage, player_guess): """Create list of valid choices for monty to choose from.""" montys_stage = [] for index, item in enumerate(stage): if index == player_guess: continue else: montys_stage.append(index) random.shuffle(montys...
77906beb085f376b82bbba88effc37b939d120e2
663,483
import random from datetime import datetime def get_line(): """ Returns a string with the current timestamp and a random event chosen from a list of events at random """ random.seed(datetime.utcnow().microsecond) dt = datetime.utcnow()\ .strftime('%Y-%m-%d %H:%M:%S.%f') event =...
32f4ee88b0748ba08a7e3c7e0c331b1d20fdbbd6
663,484
import math def arc_chord_length(radius: float, sagitta: float) -> float: """Returns the chord length for an arc defined by `radius` and the `sagitta`_. Args: radius: arc radius sagitta: distance from the center of the arc to the center of its base """ return 2.0 * math.sqrt(2.0 ...
a174476f1c28db0c2b37c8a6fa0f7660d899c578
663,485
def exists(args, premise, verbose=True): """Check whether token with these keywords exists.""" for token in premise.tokens: # Default: match, turns false as soon as mismatch in keyword is found all_match = True # Iterate through arguments... for arg in args...
ac9789ecc3d3a37cbd05741ebdfe62794f0bb937
663,487
def ff_pso_config( psofly, omega_start: float, omega_end: float, omega_step: float, # need to update for tomo and FF exposure_time: float, speed_scale: float= 1.0, # 0: slowest speed possible, 1: fastest speed possible, 0~1: linear interpolation camera_m...
a56c062d94384a633005f6b6f6f752f5b8c5a197
663,488
def _auto_fn(name): """default dialect importer. plugs into the :class:`.PluginLoader` as a first-hit system. """ if "." in name: dialect, driver = name.split(".") else: dialect = name driver = "base" try: if dialect == "firebird": try: ...
0715594cdefe9e9d5fd2b8456abb2b17aab8f139
663,489
def num_coeffs(l): """The number of coefficients (i.e. different "order" terms) at a given degree, l 2*l + 1 """ return 2*l + 1
6b927b31402e1328f86a87e8e10d4e80df7d6ee5
663,490
from typing import Dict from typing import AnyStr from typing import Any def update_dictionary_keys_with_prefixes(input_dict: Dict[AnyStr, Any], prefix: AnyStr): """Adds a prefix to the keys of a dictionary.""" output_dict = dict((prefix + key, value) for (key, value) in input_dict.items()) return output_...
530d806de5a839318729f14c2e1c57a173509ed8
663,491
def div2D(v1,v2): """Elementwise division of vector v1 by v2""" return (v1[0] / v2[0], v1[1] / v2[1])
59415639346e89c5aed230caea807e8662c2f1ff
663,492
import time def manage_changed(wrapped): """ Decorator which causes a cookie to be set when a setter method is called.""" def changed(session, *arg, **kw): session.accessed = int(time.time()) session.changed() return wrapped(session, *arg, **kw) changed.__doc__ = wrapped.__doc_...
6f7d2d278df6dfc7af73bf65977b5683f68be47d
663,493
def get_factorial(x): """ Computes factorial of x :param x: int :return: int """ if x < 0: raise ValueError("Input must be positive, but {} was given") factorial = 1 for value in range(1, x + 1): factorial *= value return factorial
bc5a40f48d1e09085bc5b3d8a3766e1919dfcb92
663,494
def get_visual_selection(lines, start, end): """Split an arbitrary selection of text between lines Args: lines (list): Lines of text to be processed start (tuple): Coordinates of the start of a selection in format (line, char) end (tuple): Coordinates of the en...
56936f17a5d23455a8df4f99519d02cf700697aa
663,495
def druckumrechner(inHG): """ Umwandlung von inHG in mBar :param inHG: int, float or None :return: float or None """ if isinstance(inHG, (int, float)): mbar = inHG * 33.86389 mbar = round(mbar, 2) return mbar else: return None
549b3efde43d55b360eac8aac4271f948600b299
663,496
import os def check_file_size(log, files): """ Check if file is empty or greater than IFWI/BIOS file""" bios_size = os.path.getsize(files[0]) for file in files: filesize = os.path.getsize(file) if filesize != 0: if not (filesize <= bios_size): log.critical("\n...
18b329f39f610d5f609bff1d744df2f0a13fbfdf
663,497
def default_collate(batch): """ Default collate function, used for ParlAIDataset and StreamDataset """ new_batch = [] for b in batch: idx = b[0] if type(b[1]) is list: ep = b[1][0] else: ep = b[1] new_batch.append((idx, ep)) return new_...
acb5292ef117e7668a3d377ef0df4e3fc069f376
663,499
import subprocess import os def create_sub_process(cmd): """ Create a child process that executes a specific command """ proc = subprocess.Popen( cmd, cwd=os.getcwd(), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ...
15b0d2d0fcd7beeb86c7367704cfc59ad9a45d43
663,500
def _format_content(password, salt, encrypt=True): """Format the password and salt for saving :arg password: the plaintext password to save :arg salt: the salt to use when encrypting a password :arg encrypt: Whether the user requests that this password is encrypted. Note that the password is sav...
8b4199950d728f85e3bd08309e55dd42174d1552
663,501
def user_says_yes(message=""): """Check if user input is either 'y' or 'n'. Returns a boolean.""" while True: choice = input(message).lower() if choice == "y": choice = True break elif choice == "n": choice = False break else: ...
b5ac454facc1ae7496b42c06fbe73776cae8bfca
663,502
import sys import os def get_default_download_dir(): """ Refered to NLTK toolkit approach https://github.com/nltk/nltk/blob/8e771679cee1b4a9540633cc3ea17f4421ffd6c0/nltk/downloader.py#L1051 """ # On Windows, use %APPDATA% if sys.platform == "win32" and "APPDATA" in os.environ: homedir...
87197af801d0d269678b6540665253fd677ff550
663,504
def analyze_user(user, verbosity, error_level): """analyze AD user object user -- user object to be analyzed verbosity - NAGIOS verbosity level - ignored error_level - ignored Returns the Nagios error code (always 0) and error message (user defn) """ return 0, '{principal name:%s, display...
ec1b3e074d20c9667cf4015cb988f697fad98c7f
663,505
import hashlib def _encrypt_md5(one_string): """ md5($pass)方式加密 """ _md5 = hashlib.md5(one_string).hexdigest() return _md5
216d0c6add16413b5385a61a69dbc362d8570c71
663,506
def makespan(sol={}): """Returns the makespan of a solution (model 1's objective function).""" return sol["makespan"]
22e5ec2e2457032f1a653bbafb08f213c54f8eda
663,508
from typing import Tuple def printable_field_location_split(location: str) -> Tuple[str, str]: """Return split field location. If top-level, location is returned as unquoted "top-level". If not top-level, location is returned as quoted location. Examples: (1) field1[idx].foo => 'foo', 'field1[id...
100a05ed2188a4a21d783835591d04588f93a947
663,509
def replace_string_chars(s1, pos, s2): """ Replace characters in a string at the specified string position (index). @param s1: Input string for replacement. @param pos: Input string index of replace. @param s2: - Replacement string. @return: New resulting string. """ len2 = len(s2) i...
3544fd1d8b608efd0b6ec3a177ccb9c54356a8f7
663,510
def backward_prop(data, labels, params, forward_prop_func): """ Implement the backward propagation gradient computation step for a neural network Args: data: A numpy array containing the input labels: A 2d numpy array containing the labels params: A dictionary mapping parameter ...
6d286138a8c0989c2f3d5784f494210f54c5140a
663,511
def point_inside_polygon_interior_sanity_check(n_vertices, poly_x_pts, poly_y_pts, test_x, test_y): """ We use this function to verify shapely.geometry's correctness. This fn only works correctly on the interior of an object (not on the boundary). Ray casting: Draw a virtual ray from anywhere outside t...
2b1446d1c7e762c29659eadc518115efd408a5b0
663,512
def survivor(tracks, track): """ eye of the tiger """ root = [t for t in tracks if t.ID == track.root] if root: return 1 if root[0].t[0] <= 30 else 0 return 0
bed57deba9f30ae84c96f71337eb3fb6a12807fc
663,513
def dummy(): """A dummy handler.""" assert True return True
a2e9aa17455b83318e2a53fb17a22e007e9863f4
663,514
def path_as_0_moves(path): """ Takes the path which is a list of Position objects and outputs it as a string of rlud directions to match output desired by Rosetta Code task. """ strpath = "" for p in path: if p.directiontomoveto != None: strpath += p.directiontomove...
6423f7c4c46fc79cd38cdddb3d367411ef9a05d4
663,515
import ast def _to_dict(contents): """Parse |contents| as a dict, returning None on failure or if it's not a dict.""" try: result = ast.literal_eval(contents) if isinstance(result, dict): return result except (ValueError, TypeError): pass return None
4e9acba2e247c72dc7927e37087415e5606d6b73
663,516
def user_event_feedback(msg): """ last unknow event """ return True
51032362b774c6cff66c36630b623e7c6089e3c1
663,518
import uuid def gen_id(): """ Generate high probability unique ID for DynamoDB. """ return uuid.uuid1().int >> 90
0136b14ecb9bcb523e8f73f3faf7a026beec8724
663,519
def get_variable_values_sorted(variable): """ Return a list of sorted values for given attribute, if all its values can be cast to int's. """ if variable.is_continuous: return [] try: return sorted(variable.values, key=int) except ValueError: return variable.values
e76bc49c94da322b5d66243847fe3faf03d7bf20
663,520
def _Error(message, code=400): """ Create an Error framework :param message: :param code: :return: """ return { "error" : message, "code" : code }
d363b728ca8d891c479ff67b8c72ec24fd57a456
663,521
import click from typing import Union from typing import Any from typing import List from typing import Tuple from pathlib import Path def validate_path_pair( ctx: click.core.Context, param: Union[click.core.Option, click.core.Parameter], value: Any, ) -> List[Tuple[Path, Path]]: """ Validate a pa...
d6267479828546e395e6691b2495b807ca24e79a
663,524
def indent(*args) -> str: """Return joined string representations of objects with indented lines.""" text = '\n'.join(str(arg) for arg in args) return '\n'.join( (' ' + line if line else line) for line in text.splitlines() if line )[2:]
957dec3b0dd73931681414bfa16b30a92349e50d
663,525
import platform def is_darwin(): """Determines if the system is a Mac.""" return platform.uname()[0] == 'Darwin'
c963a2bf3123056cb85ffa4de189c094a69a063c
663,526
import re def strip_non_numbers(data): """ gets rid of all non-number characters """ non_numbers = re.compile(r"\D") return non_numbers.sub("", data)
5879a1d6eafcee449268c04de44720935a44c23e
663,528
def clean_isbn(isbn): """List of digits in ISBN""" digits = set("0123456789") return [int(x if x in digits else 10) for x in isbn.translate(None, " -")]
548270a846c12f7f239d9826892d69301bf58590
663,529
def explode(pkt, *args): """This function takes a dict object and explodes it into the tuple requested. It returns None for any value it doesn't find. The only error it throws is if args is not defined. Example: pkt = {'a':0, 'b':1} 0, 1, None = pdcomm.explode(pkt,...
bffc0caebd2652be0bc53473c8fee0d3a683f03a
663,530
def get_rating(input_rating): """ Returns stars iTunes rating""" if input_rating: return (int(input_rating)/100)*5 else: return input_rating
110efc21f2a97dcb80ccdf06dc6c4947b2a6c64d
663,531
import platform import socket def inspect_execution_env(): """Returns a dict describing the current execution environment :returns: :rtype: dict """ return { 'python.version': platform.python_version(), 'hostname': socket.gethostname() }
6b8c6695f533bed50b302cdc4937f7c2bcce5399
663,532
def get_f_min(f_max, cents_per_value, v_min, v_max): """ This function takes in a y value max and min, a maximum frequency and a y scale parameter in units of cents/y value, and returns the minimum frequency that fits to such a scale. Cents are a logarithmic unit of tone intervals (https://en.wikipedia.org/...
c2e92d0f2aa63f8553d85d9fb0bdcf79156deff1
663,533
def dup_strip(f): """ Remove leading zeros from ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys.densebasic import dup_strip >>> dup_strip([0, 0, 1, 2, 3, 0]) [1, 2, 3, 0] """ if not f or f[0]: return f i = 0 for cf in f: if cf: brea...
f72a3e78ea14f42e61118502eff981ed98250eae
663,534
def likedislike_manager(queryset, ip_address, likedislike, request): """ baraye behine kardane code(dry) """ if queryset.likedislike == 'like' and likedislike == 'like': queryset.delete() elif queryset.likedislike == 'dislike' and likedislike == 'dislike': queryset.delete() elif ...
ecb5d6c1825d7c4fac246467ff6feaf60b5704e8
663,535
def decompose_sequence(move_sequence): """ Decomposes a move sequence like "R U R' U R U U R" to something that can be executed by our hardware. Returns decomposed sequence as a string. """ moves = move_sequence.split(' ') decomposed_sequence = '' for move in moves: current_move =...
7069b2a284db5c5254646c8e132815bc6d2a06c7
663,536
from typing import Tuple def _hue_to_rgb(hue: float) -> Tuple[int, int, int]: """ Take hue between 0 and 1, return (r, g, b). """ i = int(hue * 6.0) f = (hue * 6.0) - i q = int(255 * (1.0 - f)) t = int(255 * (1.0 - (1.0 - f))) i %= 6 return [ (255, t, 0), (q, 255...
f2195e8829eb30fe33c850df7ba2335c0e8ca5f2
663,537
def PortfolioBacktestingRolling(portfolio): """ function to count number of breaches for a portfolio """ return None
2b40b05322f5a450edec6b0283b75c507aa97468
663,538
def column_to_list(data, index): """Return a list with values of a specific column from another list Args: data: The list from where the data will be extracted index: The index of the column to extract the values Returns: List with values of a specific column """ column_list = [] ...
95a953b8da13ae04e755a2755ec6feebc447bd20
663,540
import itertools import operator def group_versions(versions): """Group versions by `major.minor` releases. Example: >>> group_versions([ Version(1, 0, 0), Version(2, 0, 0, 'rc1'), Version(2, 0, 0), Version(2, 1, 0), ]) ...
2d047c2650a11e96329a3dec870a9904d98d5c18
663,541
def _get_weighted_average(results): """ Computes the weighted average results :param results: An ordered dictionary with result_name as key and (weight, value) as value (or list of (w, v)) :return: A dictionary with result_name as key, and the weighted value as value """ weighted_average = {...
f90ab04de1fbb30ac1162199cec6015a4d101de9
663,542
def get_century(dates_list): """ Get the Century from both start and end dates. dates = [period_start_date, period_end_date] """ centuries = [] for date in dates_list: if " BCE" in date: century = int(date[:-4][:-2]) + 1 centuries.append(-century) elif " ...
068312da0a6b0ef09d6b43d58abe7fd17bb3a4ec
663,543