content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _prepare_shape_for_expand_dims(shape, axes): """ Creates the expanded new shape based on the shape and given axes Args: shape (tuple): the shape of the tensor axes Union(int, tuple(int), list(int)): the axes with dimensions expanded. Returns: new_shape(tuple): the shape wit...
b7851761c84c9fef40a82099a63cba0d3e68085f
688,436
import torch def init_control(ctrl_obj, env, live_plot_obj, rec, params_general, random_actions_init, costs_tests, idx_test, num_repeat_actions=1): """ Init the gym env and memory. Define the lists containing the points for visualisations. Control the env with random actions for a number of steps. Args: ct...
57b1b94afb5fd3772fc57c56e393fd88a1769055
688,440
def create_keyword_string(command_string): """Creates the keyword string. The keyword string is everything before the first space character.""" cmd_str = command_string.split(" ")[0] return cmd_str
2f12eb133a187b3f3fc376a1203bfb2c6b94e6d8
688,442
def normalize_azimuth(azimuth): """Normalize azimuth to (-180, 180].""" if azimuth <= -180: return azimuth + 360 elif azimuth > 180: return azimuth - 360 else: return azimuth
18392629573b0a89d97f737e264ce5cf708a619e
688,443
def real_calculate_check_digit(gs1_value): """ Calculate the check digit without specifying the identifier key. :param gs1_value: GS1 identifier. :return: Check digit. """ multipliers = [] counter = 0 total = 0 for i in reversed(range(len(gs1_value))): d = gs1_value[i] ...
a8526c18358e68ef4ecf08d6385e40420f17679c
688,444
import hashlib def make_epoch_seed(epoch_tx_count, ledger_count, sorted_ledger, address_from_ledger): """ epoch_tx_count = number of transactions made in a given epoch ledger_count = the total number of ledger entries in the ledger database. sorted_ledger = iterable that returns the nth ledger item. M...
d97915fdd6def978e72c443682a21628219c54cd
688,450
def change_list_value(array: list, value_old: str, value_new: str) -> list: """ Returns a given list with a changed value. """ for index, value in enumerate(array): if value == value_old: array[index] = value_new return array
1213c2407566360aa39393dfd1a837ef6aa12323
688,452
import json def load_clusters(infile): """ Loads clusters in a sparse format from a JSON file. Parameters ---------- infile : str The JSON file containing sparse cluster information. Returns ------- list of set of tuple of int The sets are clusters, the tuples are the...
cf7a418aa68f30fdbb42fe51ab758bad0d507775
688,455
def inclusion_one_default_from_template(one, two='hi'): """Expected inclusion_one_default_from_template __doc__""" return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)}
ecf3b4a300753a55972b21da4c8dec8e230edaf2
688,456
def build_metric_link(region, alarm_name): """Generate URL link to the metric Arguments: region {string} -- aws region name alarm_name {string} -- name of the alarm in aws Returns: [type] -- [description] """ url = 'https://{}.console.aws.amazon.com/cloudwatch/home?...
00c79ec9a1aa66ceee91d8bdae93ae78fcd1d804
688,464
def vector_multiply(vector_in, scalar): """ Multiplies the vector with a scalar value. This operation is also called *vector scaling*. :param vector_in: vector :type vector_in: list, tuple :param scalar: scalar value :type scalar: int, float :return: updated vector :rtype: tuple ""...
975178f4bcaa0348c7fb26f8f1d72ef80995bcfe
688,465
def load_meta(meta_file): """Load metadata file with rows like `utt_id|unit_sequence`. Args: meta_file: Filepath string for metadata file with utterance IDs and corresponding quantized unit sequences, separated by pipes. Input unit sequences should be separated by spaces. Returns: ...
cdb76ebe61baaf162d953ef8f36a526c68d629e3
688,472
def _module_name(*components): """Assemble a fully-qualified module name from its components.""" return '.'.join(components)
014650c55113e8632ac7872e12c73d1b2f2da46f
688,473
from typing import Tuple def find_prefix(root, prefix: str) -> Tuple[bool, int]: """ Check and return 1. If the prefix exsists in any of the words we added so far 2. If yes then how may words actually have the prefix """ node = root # If the root node has no children, then return Fals...
aa8d7aec5c158e7fe0df3d31e73bfe53b183dedf
688,474
from PIL import ImageFile as PillowImageFile import zlib import struct def get_pillow_attribute(file, pil_attr): """ Returns an attribute from a Pillow image of the given file, file a file. wrappable by Pillow. Must be open pil_attr the attribute to read. return the attrib...
195927484249535d6c097a3132d7b251b4c75305
688,480
def find_check_run_by_name(check_runs, name): """ Search through a list of check runs to see if it contains a specific check run based on the name. If the check run is not found this returns 'None'. Parameters ---------- check_runs : list of dict An array of check runs. This can be an ...
bc8f20ab6b60ee331115bef226ea89709bf4dbc0
688,482
def count_words(item): """Convert the partitioned data for a word to a tuple containing the word and the number of occurances. """ word, occurances = item return word, sum(occurances)
d0587dbca4b8eb7f0817119f392db6079efd579d
688,483
import torch def randomized_argmax(x: torch.Tensor) -> int: """ Like argmax, but return a random (uniformly) index of the max element This function makes sense only if there are ties for the max element """ if torch.isinf(x).any(): # if some scores are inf, return the index for one of the ...
115423d3da3770e1247f8980a09e193d9c37e934
688,485
from typing import Literal def compatible_operation(*args, language_has_vectors = True): """ Indicates whether an operation requires an index to be correctly understood Parameters ========== args : list of PyccelAstNode The operator arguments language_has_vectors : bo...
7fe422dab78fac2aa06d67cdac3ce00eed7e4cc6
688,487
from typing import Dict from typing import Any def _get_player_pts_stat_type(player_pts: Dict[str, Any]) -> str: """ Helper function to get the stat type within the pulled player points. Will be either 'projectedStats' or 'stats'. """ unique_type = set([list(v.keys())[0] for v in player_pts.values...
fe6560a7bb8096810ed56b4a2334997823103a27
688,488
def formatEdgeDestination(node1, node2): """ Gera uma string que representa um arco node1->node2 Recebe dois inteiros (dois vértices do grafo), e o formata com a notação de aresta a->b onde a é o vértice de origem, e b o de destino. Args: node1 (int): número de um dos vértices ligados à ar...
517997fb634b0c9c12fc61d1e582f584786c6196
688,489
def make_response(response): """ Make a byte string of the response dictionary """ response_string = response["status"] + "\r\n" keys = [key for key in response if key not in ["status", "content"]] for key in keys: response_string += key + ": " + response[key] + "\r\n" response_strin...
c3ed39fdce286dbc1462258a31395818b58668cb
688,490
def repetition_plane(repetitions, n=8): """ :param int repetitions: Number of times a chess position (state) has been reached. :param int n: Chess game dimension (usually 8). :return: An n x n list containing the same value for each entry, the repetitions number. :rtype: list[list[in...
fd73daa9ba178e810acbcc1428a26175c2daf6d7
688,491
def line_from_text(content='', some_text=[]): """ returns the first line containing 'content' :param content: :param some_text: list of strings :return: line containing text """ matching_line = '' for line in some_text: if line.find(content) >= 0: matching_line = line...
51fb74d92440e0521c87cdfd441ba3421a675cf3
688,494
import torch def batch_matrix_norm(matrix, norm_order=2): """ normalization of the matrix Args: matrix: torch.Tensor. Expected shape [batch, *] norm_order: int. Order of normalization. Returns: normed matrix: torch.Tensor. """ return torch.norm(matrix, p=norm_order, dim=...
8e26db83d49ce6886866ca9e53df0ad10628c5b8
688,495
def _jaccard(a, b): """ Return the Jaccard similarity between two sets a and b. """ return 1. * len(a & b) / len(a | b)
0d744b71b4b6fbc0530631aa7daad206349a63d9
688,497
def compute_grade(questions_coeff, questions_grade): """ Compute a grade from grade for each question (/2) and associated coefficients :param questions_coeff: list of coefficients for each question :param questions_grade: list of grade for each question """ assign_grade = 0 sum_coeff = ...
5f2b194017f96248c6a68ae46b9a810d0e5d671a
688,498
def _do_step(x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha): """ An implementation of [1] Equation 8.9 References ---------- .. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point optimizer for linear programming: an implementation of the homog...
0c38e2f18f7c934d910c024c23d35e13660eec08
688,500
def bgr_to_rgb(color: tuple) -> tuple: """Converts from BGR to RGB Arguments: color {tuple} -- Source color Returns: tuple -- Converted color """ return (color[2], color[1], color[0])
c8d121e43034b441ac38342d005e308cec8d02ee
688,501
def get_run_data_from_cmd(line): """Parser input data from a command line that looks like `command: python3 batch_runner.py -t benders -k cache -i s6.xml -v y -r 0` and put it into a dict. """ words = line.split(" ")[3:] word_dict = {} for (i, word) in enumerate(words): if word.sta...
cb29a4be45abebb463e96fc4f36938ebdb2f6e52
688,503
def slurp(fname: str) -> str: """ Reads a file and all its contents, returns a single string """ with open(fname, 'r') as f: data = f.read() return data
f94e6140eb79e25da695afe2f4bd44a1e96cf55c
688,509
def create_img(height, width, color): """ Creates an image of the given height/width filled with the given color PARAMS/RETURN height: Height of the image to be created, as an integer width: Width of the image to be created, as an integer color: RGB pixel as a tuple of 3 integers re...
d2f5b3d881c75e2f2b9664584748439d8b7e5ae9
688,513
import zipfile def _NoClassFiles(jar_paths): """Returns True if there are no .class files in the given JARs. Args: jar_paths: list of strings representing JAR file paths. Returns: (bool) True if no .class files are found. """ for jar_path in jar_paths: with zipfile.ZipFile(jar_path) as jar: ...
828e078e33ef129ab151346611fbe0a9be8bf739
688,516
import torch def process_sequence_wise(cell, x, h=None): """ Process the entire sequence through an GRUCell. Args: cell (DistillerGRUCell): the cell. x (torch.Tensor): the input h (tuple of torch.Tensor-s): the hidden states of the GRUCell. Returns: y (torch.Tensor)...
520889174cd83b6fb598a78f9fbec6018d0dc8bb
688,517
import csv def file_to_position_depths(file_path): """Get the position and depths from one file. Read into memory as a dictionary with (lat, lon) as the key and depth as the value.""" # create the dictionary result = {} # read the position and depth data from the input csv file with open(fil...
461b9eac168795e4259f38800caa9c29fe620dec
688,518
def serialize_email_principal(email): """Serialize email principal to a simple dict.""" return { '_type': 'Email', 'email': email.email, 'id': email.name, 'name': email.name, 'identifier': email.identifier }
d6b821f735ff28d007286ef6523be9f17fade928
688,520
def dates_to_str(dates): """Transforms list of dates into a string representation with the ARRAY keyword heading. Parameters ---------- dates: list Returns ------- dates: str """ heading = 'ARRAY DATE' footing = '/' res = [heading] + [d.strftime('%d %b %Y').upper() for d in...
7f50569322bd06a38b9d1a4229ba25afdd244307
688,528
def create_ordered_list(data_dict, items): """Creates an ordered list from a dictionary. Each dictionary key + value is added to a list, as a nested list. The position of the nested item is determined by the position of the key value in the items list. The returned list is the dictionary ordered on...
929538546a2f8d2ebbcb22c2eac6effc87769339
688,529
def convert_size_in_points_to_size_in_pixels(size): """ 6pt = 8px = 0.5em 7pt = 9px = 0.55em 7.5pt = 10px = 0.625em 8pt = 11px = 0.7em 9pt = 12px = 0.75em 10pt = 13px = 0.8em 10.5pt = 14px = 0.875em 11pt = 15px = 0.95em 12pt = 16px = 1em 13pt = 17px = 1.05em 13.5pt = 18px...
1c5be5557a6b32dee96f3f4ed6238f2e3e6475d0
688,531
def scaleto255(value): """Scale the input value from 0-100 to 0-255.""" return max(0, min(255, ((value * 255.0) / 100.0)))
fdf0ba0717df4c85fc055c1b8bc2590a22c4bd09
688,538
def receivables_turnover(revenue, average_receivables): """Computes receivables turnover. Parameters ---------- revenue : int or float Revenue average_receivables : int or float Average receivables for the period Returns ------- out : int or float Receivables tu...
0b88bf43cc7d8c3513534db82b4ae54964eefb42
688,539
import pathlib def get_files(extensions): """List all files with given extensions in subfolders :param extensions: Array of extensions, e.g. .ttl, .rdf """ all_files = [] for ext in extensions: all_files.extend(pathlib.Path('cloned_repo').rglob(ext)) return all_files
c8b697c555ec49866f0e2dba6166415d69df22a4
688,542
from typing import Union from typing import List from typing import Tuple def flatten(xs: Union[List, Tuple]) -> List: """ Flatten a nested list or tuple. """ return ( sum(map(flatten, xs), []) if (isinstance(xs, list) or isinstance(xs, tuple)) else [xs] )
e520fb245e5a681ca446f50c7bb4fd55cfaedc18
688,543
import csv def read_csv(filepath, encoding='utf-8'): """ This function reads in a csv and returns its contents as a list Parameters: filepath (str): A str representing the filepath for the file to be read encoding (str): A str representing the character encoding of the file Returns: ...
aee38a14ca7194c7040b6e8652ad9d43b10e0144
688,544
def subtract_year(any_date): """Subtracts one year from any date and returns the result""" date = any_date.split("-") date = str(int(date[0])-1) + "-" + date[1] + "-" + date[2] return date
b5183d66931cfcc374384868ee646c551e12dd40
688,546
import re def remove_whitespace(s, right=False, left=False): """ Remove white-space characters from the given string. If neither right nor left is specified (the default), then all white-space is removed. Parameters ---------- s : str The string to be modified. right : bool ...
8bc8e9efbdb726878814c538f07d390c11a1a3d3
688,547
def compact(text, **kw): """ Compact whitespace in a string and format any keyword arguments into the resulting string. Preserves paragraphs. :param text: The text to compact (a string). :param kw: Any keyword arguments to apply using :py:func:`str.format()`. :returns: The compacted, formatted ...
66c095b7cf180dc2db7e83a306e6d9bb8af0cecc
688,552
def parse_ingredients(raw_ingredients): """Parse individual ingredients from ingredients form data.""" ingredients = [] for ingredient in raw_ingredients.split("\r\n"): if ingredient: ingredients.append(ingredient) return ingredients
e76e6dc4183c147870f12f2c4af7b05ae8c1847f
688,554
def read(metafile): """ Return the contents of the given meta data file assuming UTF-8 encoding. """ with open(str(metafile), encoding="utf-8") as f: return f.read()
82135a6b680803c01cb9263e9c17b4c3d91d4516
688,557
import hashlib def get_ftp_md5(ftp, remote_file): """Compute checksum on remote ftp file.""" m = hashlib.md5() ftp.retrbinary(f'RETR {remote_file}', m.update) return m.hexdigest()
dc8bc74daba3262c56c969c480e5c1d5e112f2aa
688,560
def usd(value): """ Format value as USD """ return f"${value:,.2f}"
41e53fc59e6d679080a5cf86ce077c49d48d5375
688,563
def get_batch(file_h5, features, batch_number, batch_size=32): """Get a batch of the dataset Args: file_h5(str): path of the dataset features(list(str)): list of names of features present in the dataset that should be returned. batch_number(int): the id of the batch to be re...
0529b24644a23fd92bccb539b976edf799adc16a
688,565
import random def randhex() -> str: """Returns random hex code as string""" return "#" + "".join(random.choices("ABCDEF123456", k=6))
8edf53c33bd1264de85616ab836abf652e3d95fe
688,571
def split_byte_into_nibbles(value): """Split byte int into 2 nibbles (4 bits).""" first = value >> 4 second = value & 0x0F return first, second
082f0526001e5c7b2b6093861250a5d2c2634cf7
688,573
def _count_spaces_startswith(line): """ Count the number of spaces before the first character """ if line.split("#")[0].strip() == "": return None spaces = 0 for i in line: if i.isspace(): spaces += 1 else: return spaces
79276ac710bf290baeeb84a4a064e03308ea6548
688,576
from typing import Iterable def get_proc_name(cmd): """ Get the representative process name from complex command :param str | list[str] cmd: a command to be processed :return str: the basename representative command """ if isinstance(cmd, Iterable) and not isinstance(cmd, str): cmd = ...
f737faf2866083fd2bbaf65e52effe84a8e86cbc
688,579
import socket def is_port_open(port_num): """ Detect if a port is open on localhost""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) return sock.connect_ex(('127.0.0.1', port_num)) == 0
8ee5e4674a2c4444448208d0e8194809665c8014
688,584
from typing import Union from pathlib import Path from typing import Tuple def get_paths(base_path: Union[str, Path]) -> Tuple[Path, Path]: """ Get fsh input and output paths from base path. :param base_path: Base path :return: FSH input path, FSH output path """ return ( Path(base_pa...
6b4ac2a24a5cdbaec8b39c7232d1cbd14aeb2770
688,585
import json def inline_json(obj): """ Format a python object as JSON for inclusion in HTML. Parameters: obj: A python object that can be converted to JSON. Returns: An escaped :term:`native string` of JSON. """ return json.dumps(obj).replace("</script", r"<\/script").replace(...
a0062821cd61674b182e41c913bb248b6ade7a35
688,588
def readCols(cols_file): """ Read a .cols file (normally correspondingly to a .dm file) and return two dictionaries: word:index and index:word. In the .cols file, the line number is used as index. :param cols_file: str -- file path to a list of words (words' line numbers are their index) :return: {i...
8dc1b9ffb1f339f76aea30675f3b73ace21c51cf
688,590
def get_invalid_user_credentials(data=None): """ Returns error response for invalid user credentials :param str data: message :return: response :rtype: object """ response = {"status": 401, "message": "Invalid user credentials.", "data": data} return response
67ee7eec77997a207041d56457c806083d718e14
688,594
from typing import Mapping def item_iter(obj): """ Return item (key, value) iterator from dict or pair sequence. Empty seqence for None. """ if obj is None: return () if isinstance(obj, Mapping): return obj.items() return obj
3572377a4debf0e0346f2423f29a527b2e903543
688,597
import torch def mean_std_integrand(fx, px): """Compute the expectation value and the standard deviation of a function evaluated on a sample of points taken from a known distribution. Parameters ---------- fx: torch.Tensor batch of function values px: torch.tensor batch of PDF...
11be2e474090d9c29adf1f4f75db39c54537e51e
688,599
def start_ind(model, dbg=False): """ equation 1 in the paper (called i_0): returns the first index of the w vector used in the random power law graph model """ assert model.gamma > 2 #if gamma=2, this returns 0 num_nodes = model.num_nodes max_deg = model.max_deg avg_deg = model.avg_deg ...
aa8483b666d81840c20ec693fed389529d8c7aac
688,600
import base64 import six def serialize(obj): """Serialize the given object :param obj: string representation of the object :return: encoded object (its type is unicode string) """ result = base64.urlsafe_b64encode(obj) # this workaround is needed because in case of python 3 the # urlsafe_b...
c7a7d2362d6c4cc194495af77d5f09991ed4b2ed
688,604
import requests from bs4 import BeautifulSoup def create_soup(url): """ This function takes a url and creates a soup for us to work with""" html = requests.get(url).text soup = BeautifulSoup(html, "html5lib") return soup
87012f1838281e4c82fc71176ec2095301e5c4fc
688,608
def rad2equiv_evap(energy): """ Converts radiation in MJ m-2 day-1 to the equivalent evaporation in mm day-1 assuming a grass reference crop using FAO equation 20. Energy is converted to equivalent evaporation using a conversion factor equal to the inverse of the latent heat of vapourisation (1 ...
7780ca2fc42cbbb1814aa5899aa1c2294453f45d
688,609
import json def to_sentiment_json(doc_id, sent, label): """Convert the sentiment info to json. Args: doc_id: Document id sent: Overall Sentiment for the document label: Actual label +1, 0, -1 for the document Returns: String json representation of the input """ j...
0c8e699df6649a2c5205bbba817cc0bcbe70768f
688,610
def get_top_matches(matches, top): """Order list of tuples by second value and returns top values. :param list[tuple[str,float]] matches: list of tuples :param int top: top values to return """ sorted_names = sorted(matches, key=lambda x: x[1], reverse=True) return sorted_names[0:top]
53fc953fe528833b8dbf6e4d8ffc6f3437f3b565
688,617
from typing import Set from typing import Tuple from typing import Dict from typing import List def partition(tags: Set[Tuple[str, int, int]], no_frames: int, cost_table: Dict[str, float] = dict(), default_cost: float = 1, penalty: float = 2) -> List[int]: """partition() takes annotations of each frame, penal...
4bfbe8fe96c41adb09aaaed1475238d6e8458fde
688,623
def GetCounterSetting(counter_spec, name): """ Retrieve a particular setting from a counter specification; if that setting is not present, return None. :param counter_spec: A dict of mappings from the name of a setting to its associated value. :param name: The name of the setting of interest. :retur...
86e06b7c023d401150ca3ecaf16dfbbf2ed53288
688,627
def jaccard_similariy_index(first, second): """ Returns the jaccard similarity between two strings :param first: first string we are comparing :param second: second string we are comparing :return: how similar the two strings are """ # First, split the sentences into words tokenize_firs...
43b33620b5c2b93386c297b7131b482189fcac18
688,628
def scale(score, omax, omin, smax, smin): """ >>> scale(2871, 4871, 0, 1000, 0) 589 """ try: return ((smax - smin) * (score - omin) / (omax - omin)) + smin except ZeroDivisionError: return 0
b24373f6cc22fb14a3e7873b242f9ee24a3bafa1
688,630
def add_prefix_un(word): """ :param word: str of a root word :return: str of root word with un prefix This function takes `word` as a parameter and returns a new word with an 'un' prefix. """ prefix = 'un' return prefix+word
f454c3e787b5e64eae55ef86cdc03e1e8b8bb064
688,631
from typing import List import re def parse_dot_argument(dot_argument: str) -> List[str]: """ Takes a single argument (Dict key) from dot notation and checks if it also contains list indexes. :param dot_argument: Dict key from dot notation possibly containing list indexes :return: Dict key and possibl...
cf002a9f8eeca9f54641c5f54145228c9ce65dfd
688,633
def apply_building_mapping(mapdict, label): """ Applies a building map YAML to a given label, binning it into the appropriate category. """ for category in mapdict: #print(mapdict, category, label) if label in mapdict[category]['labels']: return category return "house"
d04c8b012975fa76ed08a1bd160c1322ecaeb3af
688,636
def preprocess_text(raw_text,nlp): """ Preprocesses the raw metaphor by removing sotp words and lemmatizing the words Args: raw_text: (string) the original metaphor text to be processed nlp: (spacy language object) """ tokens=[] for token in nlp(raw_text): if not token.is_...
6b65f6f97a54980fdb310cf61a98564cfb67f172
688,638
def get_major_version(version): """ :param version: the version of edge :return: the major version of edge """ return version.split('.')[0]
c17e1b23872a25b3ce40f475855a9d1fe4eef954
688,639
def ordinal(number): """ Get ordinal string representation for input number(s). Parameters ---------- number: Integer or 1D integer ndarray An integer or array of integers. Returns ------- ord: String or List of strings Ordinal representation of input number(s). Return a string if inpu...
dcd914cbb313859779347c652c4defbaa4d7983d
688,641
import re def remove_accents(text): """Removes common accent characters.""" text = re.sub(u"[àáâãäå]", 'a', text) text = re.sub(u"[èéêë]", 'e', text) text = re.sub(u"[ìíîï]", 'i', text) text = re.sub(u"[òóôõö]", 'o', text) text = re.sub(u"[ùúûü]", 'u', text) text = re.sub(u"[ýÿ]", 'y', te...
e0f80556aff358f8dc1f9f20a43ce00ca190407a
688,642
def cluster_list(list_to_cluster: list, delta: float) -> list: """ Clusters a sorted list :param list_to_cluster: a sorted list :param delta: the value to compare list items to :return: a clustered list of values """ out_list = [[list_to_cluster[0]]] previous_value = list_to_cluster[0] ...
5ebde99189c7a9008cf1c362d18f7dff9b2617c0
688,646
def external_pressure(rho, g, d): """Return the external pressure [Pa] at water depth. :param float rho: Water density [kg/m^3] :param float g: Acceleration of gravity [m/s/s] :param float d: Water depth [m] """ return rho * g * d
1b2aea7030561e17f331be0f04b1cfd85072a862
688,647
def get_node_composer_inputs(equivalent_quantity_keys, parsed_quantities, quantity_names_in_node_dict): """ Collect parsed quantities for the NodeCompoer input. When multiple equivalent quantities are found, the first one found in the equivalent_quantity_keys is chosen. """ inputs = {} for...
e907eb8887c5aedee7fece6e0b3c573e602eddcc
688,650
def sort_words(arguments, words): """ Takes a dict of command line arguments and a list of words to be sorted. Returns a sorted list based on `alphabetical`, `length` and `reverse`. """ if arguments.get('--alphabetical', False): words.sort() elif arguments.get('--length', False): ...
a6c0af4fe254c24d0f6d977e3ff80457ca4da2f0
688,651
def source_from_url(link): """ Given a link to a website return the source . """ if 'www' in link: source = link.split('.')[1] else: if '.com' in link: source = link.split('.com')[0] else: source = link.split('.')[0] source = source.replace('https...
b7b3a88dc4093ba2e793911fb53f14891d22b554
688,654
def _check_type(type_, value): """Return true if *value* is an instance of the specified type or if *value* is the specified type. """ return value is type_ or isinstance(value, type_)
4ff8ce08d75f6256939f98a20b9e85181ee5492d
688,655
import importlib def get_callback_class(hyperparams): """ Get one or more Callback class specified as a hyper-parameter "callback". e.g. callback: stable_baselines3.common.callbacks.CheckpointCallback for multiple, specify a list: callback: - utils.callbacks.PlotActionWrapper ...
1714c5109b278adac6030e2d788800189ff09ebd
688,656
def area_under_curve(x, y): """Finds the area under unevenly spaced curve y=f(x) using the trapezoid rule. x,y should be arrays of reals with same length. returns: a - float, area under curve""" a = 0.0 for i in range(0, len(x) - 1): # add area of current trapezium to sum ...
25f872927add3c74d325b1bf1e2e96c9bef9fdca
688,657
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) because the number of calculations performed depends on the size of num. Space Complexity: Space complexity is also O(n) becuase newman_conway_nums array to store sequence valu...
e595fd25e5ed6718339431b20e22b00ae504e5be
688,659
def _get_position_precedence(position: str) -> int: """Get the precedence of a position abbreviation (e.g. 'GK') useful for ordering.""" PLAYER_POSITION_PRECEDENCE = { "GK": 1, "LB": 2, "LCB": 3, "CB": 4, "RCB": 5, "RB": 6, "LDM": 7, "CDM": 8, ...
b86795e5b21f5238e534eca84f5b9a1c683bb5b6
688,661
def v1_deep_add(lists): """Return sum of values in given list, iterating deeply.""" total = 0 lists = list(lists) while lists: item = lists.pop() if isinstance(item, list): lists.extend(item) else: total += item return total
005297fc36dec4dbe471229a100ce822955ff36b
688,666
def ngrams(sequence, N): """Return all `N`-grams of the elements in `sequence`""" assert N >= 1 return list(zip(*[sequence[i:] for i in range(N)]))
096a7ed58667889d0be62aa4e0b44133c753c921
688,668
def pollutants_per_country(summary): """ Get the available pollutants per country from the summary. :param list[dict] summary: The E1a summary. :return dict[list[dict]]: All available pollutants per country. """ output = dict() for d in summary.copy(): country = d.pop("ct") ...
88261062fb238a5eea9d01909f0b2be0363ed1f8
688,669
import string def read_cstring(view, addr): """Read a C string from address.""" s = "" while True: c = view.read(addr, 1) if c not in string.printable: break if c == "\n": c = "\\n" if c == "\t": c = "\\t" if c == "\v": c = "\\v" if c == "\f": c ...
7f9fbbe8ca2ae4023ee581bacac1110cc0995e09
688,670
def _format_time(time_us): """Defines how to format time in FunctionEvent""" US_IN_SECOND = 1000.0 * 1000.0 US_IN_MS = 1000.0 if time_us >= US_IN_SECOND: return '{:.3f}s'.format(time_us / US_IN_SECOND) if time_us >= US_IN_MS: return '{:.3f}ms'.format(time_us / US_IN_MS) return '{...
c57feca13b599b0fdd99f34b615ce19b8ea49e60
688,677
def product_turnover(units_sold_in_period, average_items_stocked_in_period): """Return the product turnover (or sell through rate) for a product based on units sold versus items stocked. Args: units_sold_in_period (int): Number of units of product X sold in the period. average_items_stocked_in_...
4603628db9cfbc7558d4838015faa22b3b2cee86
688,678
def fib_n_efficient(n): """Efficient way to compute Fibonacci's numbers. Complexity = O(n)""" a = 0 b = 1 for i in range(n - 1): c = a + b a = b b = c print(b) return b
c203681738d1ba71eff91920194f1a8bf5d4258a
688,680
def _get_single_reg(asm_str): """returns a single register from string and check proper formatting (e.g "r5")""" if len(asm_str.split()) > 1: raise SyntaxError('Unexpected separator in reg reference') if not asm_str.lower().startswith('r'): raise SyntaxError('Missing \'r\' character at start...
d01f7e3e9c73ff48ed13386c5aa8c602595fcd39
688,682
def is_valid_boolean(val): """ Checks if given value is boolean """ values = [True, False] return val in values
0491c1565e96ca7349137eacd4551fb75bed97ee
688,685
def massage_data(raw_data): """ Preprocess the data for predictions """ raw_data.rename(index=str, columns={"whether he/she donated blood in March 2007": "label"}, inplace=True) # generate features for year for time columns for x, y in zip(['time_years', 'recency_years'], ['Time (months)', 'Recen...
4950d59f628be33b5cf319636faa11c5d5936644
688,688