content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def aspect_ratio(a): """ Returns the ratio of the width to height of rectangle a. """ if a is None: return 0 (x, y, w, h) = a return float(w) / h
295fc5857e39ebac0c760f109693b80cb5f46494
571,318
from six import string_types def isarray(value): """Is the value a container, like tuple, list or numpy array?""" if isinstance(value,string_types): return False if hasattr(value,"__len__"): return True else: return False
993bc48aae4a429b4e28f54eb55921bd813884dd
571,319
import random def completed_number(prefix, length): """ 'prefix' is the start of the CC number as a string, any number of digits. 'length' is the length of the CC number to generate. Typically 13 or 16 """ ccnumber = prefix # generate digits while len(ccnumber) < (length - 1): digi...
74ba141d2a9daa79395ffd0227fa5ef9d3a72973
571,322
from pathlib import Path def get_first_dir(cwd: Path, glob: str = "*"): """ Return first directory of pattern `glob`. """ for d in cwd.glob(glob): if d.is_dir(): return d raise OSError(str(cwd))
84bf5234c32e4b471a532f5c87675a7a3edd1b8e
571,324
def marginal_thiele_scores_remove(marginal_scorefct, profile, committee): """ Return marginal score decreases from removing one candidate from the committee. The function returns a list of length `num_cand` where the i-th entry contains the marginal score decrease when removing candidate i. Candida...
800eec4c29f369885bf8fd66ac2bd63edf7f4169
571,326
from typing import Mapping def translate_characters(name: str, char_map: Mapping[str, str], casefold: bool = True) -> str: """Translate characters in the name to different characters. :param name: The name to modify. :param char_map: A translation map...
cef8a709f1e2e36647c41afde716a0b627caba61
571,328
import json def read_symmetry_params(body_part_json): """ Reads from a JSON formatted file the body symmetry parameters. Args: body_part_json (json): a JSON formatted file specifying the body part forming the axis of the symmetry (anchor) and the symmetrical body parts around ...
e430f900f9c5b99c4d3c811e0175c5db21b6d880
571,331
def dict_to_cookie(cookie_dict): """Convert a dict into a string cookie""" attrs = [] for (key, value) in cookie_dict.items(): attrs.append("%s=%s" % (key, value)) return "; ".join(attrs)
fd84a7ec0de57436b11f8b14f97bb7b321eabbcc
571,332
def get_rolling_mean(values, window): """Return rolling mean of given values, using specified window size.""" # deprecated return pd.rolling_mean(values, window=window) return values.rolling(window = window, center = False).mean()
03d4e921e53ef42e36481b7afed795d734876a0c
571,333
def path_split(path): """Split the svn pathname PATH into a pair, (HEAD, TAIL). This is similar to os.path.split(), but always uses '/' as path separator. PATH is an svn path, which should not start with a '/'. HEAD is everything before the last slash, and TAIL is everything after. If PATH ends in a slash,...
d9a4a91cf4903dc79ffafdb862c8b1567cfbd819
571,337
def check_action_valid_for_executor(module, action): """ Checks if the action specified is valid for the executor and can be executed """ if getattr(module, action, None) is None: return False else: return getattr(module, action).__dict__.get('function_exposed_to_action_executor', False)
46af0dca2bb1f5e6c683fe93ad9ba030f54ba8c4
571,340
def collect_default_successors(start_state): """ Collect the default successor states. NOTE: The start state also evaluated as a successor! NOTE: This function is necessary for expression validation! :param start_state: the start state of the searching :return: the set of default successor state...
740ef64fc848b2a76d1bf82594acaea5db549b02
571,344
def HandleRepairStatus(line_parts): """Given turn line_parts into a set of notes about the repair job. Args: line_parts: Iterable of ExtractLabStatusParts() results. Returns: Set of single word strings which describe a given repair job. """ repair_notes = set() noop = True # Did this repair job ...
7b9cf7c7ce893c5c1533380085f961ba4d20e0bc
571,345
import functools def lazy_property(fn): """A property decorator that caches the returned value.""" key = fn.__name__ + "_cache_val_" @functools.wraps(fn) def _lazy(self): """Very simple cache.""" if not hasattr(self, key): setattr(self, key, fn(self)) return getatt...
7ea8d0679b268b2db34193f0c0d52a1f1814b6fa
571,347
def rank_similarities(similarities, restaurant_ids): """Combine similarities list with respective restaurant_ids, and rank them by similarity. Args: similarities (list): cosine similarities compared with target (first) restaurant restaurant_ids (list): restaurant_ids corresponding to similariti...
e63ced81cd3d23776f3ffd4af9546ee94bee4257
571,349
def check_sw_status_admin(supported_nodes, output): """Check if a node is in OPERATIONAL status""" lines = output.splitlines() for line in lines: line = line.strip() if len(line) > 0 and line[0].isdigit(): node = line[0:10].strip() if node in supported_nodes: ...
125c9febfe0fb12115b763f636a7a0235fbad35b
571,350
def is_prime(number): """ This function calculates if the number is prime or not Args: number(int): Number to check for prime Returns: bool: True if prime False otherwise Raises: ValueError: Value Error is raised when the argument to this function is not an integ...
7d1104414d1b429e5c1767f6e6bc4dd145854c22
571,354
def get_instructor(rec): """Gets instructor from a course record. :param record: Dictionary containing the course record. :returns: TBD if instructor doesn't exist. None if instructor has invalid format. Instructor first name and last name if it exists. """ ...
8c2bf9791846015266cb427f0d8409fbee9de125
571,355
def compute_strain_components_from_dx(dudx, dvdx, dudy, dvdy): """ Given a displacement tensor, compute the relevant parts of the strain and rotation tensors. Rot is the off-diagonal element of the rotation tensor Rot has native units radians/year. Here we return radians per 1000 yrs (easier to interpre...
b2e7aa47b34c64a69e7dba0204b84a45286bafdc
571,358
def BuildCampaignCriterionOperations(campaign_operations): """Builds the operations needed to create Negative Campaign Criterion. Args: campaign_operations: a list containing the operations that will add Campaigns. Returns: a list containing the operations that will create a new Negative Campaign ...
0d89f192ae859cd3c06e55f9ddfca3b00a4645e9
571,359
import collections def reverse_map( applicable_label_dict, label_vocab = None): """Flip parenthood dict to map parents to children. Args: applicable_label_dict: e.g. output of get_applicable_label_dict. label_vocab: e.g. output of inference_lib.vocab_from_model_base_path Returns: collectio...
6b48c3e86ef33c17873001d7c4433ccee1c47a39
571,364
def EliminateAtoms(initial_residue, atoms2eliminate): """This function gets a residue and a list of atomnames to eliminate from the residue. It returns the residue without the atoms.""" atoms2eliminate = " OR ".join(atoms2eliminate) mutated_residue = initial_residue.select('not (name {})'.format(atoms2e...
8a9d3bfb8064edde70b313bbff7da34967b6b60e
571,372
import torch def unique(input_, return_inverse=False, return_counts=False, axis=None): """Wrapper of `torch.unique`. Parameters ---------- input_ : DTensor Input dense tensor. return_inverse : bool, optional If True, return the indices also, by default False return_counts : bo...
49f6a496ae14ea5ae707113df73d593ebe408c00
571,375
def weight_set_pair(first: set, second: set, mapped_items_weights: dict) -> float: """ The function calculates weighted average of the common items from two sessions based on the dict with items and their weights. Parameters ---------- first : set unique items from the set A ...
4b5da6e2a603074989c0967d1aa018c3ad317c70
571,378
def csv_to_dataframe(pd, path, index=None): """ Read csv file and convert to dataframe. :param pd: Pandas package :param path: String path to csv file :param index: Index of col to use for indexing :return: Data Frame Object """ if index is not None: return pd.read_csv(path, inde...
5de74c029aad166840b8ef990345ffb206809487
571,382
def set_paths_chemkin_files(my_path): """ Set the absolute path to required files on the current machine. *** only required if using chemkin files**** Parameters ------- my_path : str path where all the imput files are located Returns ------- ...
80ff69da6dd9c7e3dbf449824af56f204ffbf968
571,383
import hashlib def computeContentChecksum(algo, content): """Compute digest of ``content`` using ``algo``. Supported hashing algorithms are SHA256, SHA512, and MD5. :raises ValueError: if algo is unknown. """ if algo not in ['SHA256', 'SHA512', 'MD5']: raise ValueError("unsupported hash...
e6c7dc5ac6d0777bfb869dc4621f66ee66a25d82
571,386
def nanoToSec(nano): """Convert nanoseconds to seconds""" return int(nano / 10**9)
9132670e3f33bea64f17970ed0fbd378d3a486cc
571,388
def elevation_change(elevation): """ :param elevation: A list of elevation points (floating point format) Description: Calculates and returns the differences in elevation between two points. This is completed for all sequential pairs in a list. Returns deltaElev which is a listing of elevation changes. This ...
fad93636979098f492355da595a4972579ee95b5
571,391
def compare_versions(first, second): """ Compare two versions with format `X.Y.Z`. :param first: first version string :param second: second version string :returns: 0 if equal, <0 if first < second, >0 if second < first """ first = list(map(int, first.split('.'))) second = list(map(int,...
714b80773a70fddec7a4ac2c1e964888fbdd0651
571,392
def process_state(term, valid_transitions): """Process a state and return next state.""" try: return valid_transitions[term] except KeyError as error: raise KeyError(f"Indefinition , Invalid Transition: {error}.")
998fe6eba2ee34672e57609cb0b44656a07ece66
571,394
import yaml def load_yaml(path_file: str): """Transform a yml to dict""" yaml_file = open(path_file, "r") return yaml.load(yaml_file, yaml.Loader)
b9106d87edac045dcebfa03f59b514d950b5bbab
571,397
from typing import List def convert_coordinate(size: tuple, box: List) -> tuple: """Convert coordinate from xywh to x_center, y_center, width, height Arguments: \n `size` (tuple): size of image \n `box` (List): box coordinate \n Returns:\n `tuple`: new yolo coordinate """ dw ...
a5db82b2c0b8af17b8ccd9a288e8d0e44ebef1a3
571,401
def get_group_recommendations(users, recommendations): """function to get the history of recommendations done to a group of users :param users: list of ids of users :param recommendations: dataframe of recommendations for all users :return: data frame of recommendation for the specific group of users ...
9d96fc3e34da43cde89026f6d8398d20912a8a5d
571,402
def string_to_nat(b): """Given a binary string, converts it into a natural number. Do not modify this function.""" if b == "": return 0 else: return 2 * string_to_nat(b[:-1]) + int(b[-1])
8b96ad5101676058273c3dda8cef6eb1aa3dbb8e
571,403
def closeEnough(tolerance, length, string): """ tolerance: the tolerance of the string length length: the target length string: the string to evaluate """ if(abs(len(string) - length) <= tolerance): return True else: return False
379a0023aae362f30abb22a960d90790b6f7cf62
571,406
def split_sequence_evenly(seq, size): """ >>> split_sequence_evenly(list(range(9)), 4) [[0, 1], [2, 3, 4], [5, 6], [7, 8]] >>> split_sequence_evenly(list(range(18)), 4) [[0, 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12, 13], [14, 15, 16, 17]] """ newseq = [] splitsize = 1.0 / size * len(seq...
ddfd6be958d153eb45404f79bc56fad146f1a134
571,409
def _RectangleArea(rectangle): """Get the area of a rectangle as returned by _GetRectangle, above.""" # Width and height are the last two items in the 5-tuple. return rectangle[3] * rectangle[4]
a933a920285a8691016bd3049bc9e38dfcf350fc
571,411
def update_append_score(score: int, char: str) -> int: """Return updated score with appended character""" scores = {")": 1, "]": 2, "}": 3, ">": 4} return (score * 5) + scores[char]
d0c6a6047cb0f1014cf8123bb0f9a5722e3ab214
571,412
import linecache def convert_stack(stack, include_func_start_lineno=False): """Converts a stack extracted using extract_stack() to a traceback stack. Args: stack: A list of n 5-tuples, (filename, lineno, name, frame_globals, func_start_lineno). include_func_start_lineno: True if function start line...
c97f0e550d23510f003f1bd090475b9534b04a90
571,415
def get_master_members(master_session, aws_region, detector_id): """ Returns a list of current members of the GuardDuty master account :param aws_region: AWS Region of the GuardDuty master account :param detector_id: DetectorId of the GuardDuty master account in the AWS Region :return: dict ...
c690e2b01a8ea50e6bf7f65bcaf63eba466c09b7
571,417
import ipaddress def subnet_contains_ipv4(ip_address: str, subnet: str): """subnet_contains Check if ip address in subnet Arguments: ip_address {str} -- string subnet {str} Returns: bool """ return ipaddress.ip_address(ip_address) in ipaddress.ip_network(subnet)
5beb38047e1a99e143e28ce99e5035a5aa67b44e
571,418
from typing import Sequence from typing import List from typing import Tuple def search_sub_seq(s1: Sequence, s2: Sequence) -> List[Tuple[int, int]]: """ Searches all occurrences of sequence s1 in s2, :param s1: First sequence. :type s1: Sequence :param s2: Second sequence. :type s2: Sequence...
ef29454bed263dbb7456623f0e5d4254010a6a8e
571,419
def clean_table_data(table): """ Cleans the table data and stores it in a list of data. Parameter: table: html-table extracted using bs4 Returns: alldata: list of all data extracted """ alldata = list() for row in table.findAll("tr")[1:]: data = [] celllist ...
03203fe500979afa41d79d44678adc8a11b7ac5d
571,420
def get_n_matched_associations(feedback: str) -> int: """ Return the number of matched associations in the feedback of a single submission. """ total_matches = feedback.count("Matched") class_matches = feedback.count("Class Matched") attr_matches = feedback.count("Attribute Match") + feedback.co...
fbab8893eee201196a9e1c10afcc53186937ac4c
571,424
def show_spark_df(df, n=20, truncate=True, vertical=False): """ Show DataFrame as str, useful for logging. Notes ----- Reimplemented from: https://spark.apache.org/docs/2.4.5/api/python/_modules/pyspark/sql/dataframe.html#DataFrame.show """ if isinstance(truncate, bool) and truncate: ...
efdfb03b9a6f8cfcf9bc939ea7957275e284e9c7
571,426
def distance_to_next_divisor(num: int, den: int) -> int: """ Returns `delta`, the smallest non-negative integer which must be added to `num` such that `(num + delta) % den == 0`. Example: `num = 5, den = 5: delta = 0`. `num = 6, den = 5: delta = 4`. `num = 5, den = 6: delta = 1`. """ return (de...
129aef7884119897dafab0c52b3b606f83163018
571,428
def int_to_weekday(weekday_int, is_abbreviated=False): """ Convert int weekday to string value. 0 == Monday, 1 == Tuesday, etc. :param is_abbreviated: if True will return the two letter weekday abbreviation. Otherwise, will return full weekday name. ...
72e09e51bbc2295cc9edc14b8aff28a91b15c547
571,434
def get_max_text_width(fm, texts): """Get maximum width of texts from given list :param QtGui.QFontMetrics fm: FontMetrics instance :param iterable texts: list of texts :return: maximum text width :rtype: int """ return max(map(fm.width, texts))
5dad7ca0c101521380aa5f2b50820ff9e795e6ef
571,443
from typing import Dict import yaml def render_template(template: str, values: Dict, extra_labels: Dict) -> str: """Given a yaml of a K8s Job, replace template values and add extra labels to the pod spec""" extra_labels = extra_labels or {} values = values or {} # Replace keys using our templating la...
d5fdbcaa420d4e385094eee2bf1e11da355ce30b
571,444
def get_class_index(d): """Get class name and index from the whole dictionary E.g., '{'index': 'data/Deploy/KLAC/KLAC0570/KLAC0570_12.jpg', 'prediction': ..., 'label': ...}' ==> (str) 'KLAC0570' """ return d['index'].split('/')[-2]
1954f7184d248ac181a727cac180190813f92c50
571,448
def get_service_value(v, s, c): """Get service value. Returns a specified value from a given Portainer service. Args: v: Key for the service value s: Portainer service name c: Lisf of containers Returns: Service value. """ return list(map(lambda x: x[v], fi...
0d6f6cbba1113b2ad81f4cb89e9a2db7dad6f7fe
571,455
def get_secret_value(sess, *, secret_id): """ Retrieve a secret from Secrets Manager. """ client = sess.client("secretsmanager") return client.get_secret_value(SecretId=secret_id)["SecretString"]
b91a5bee3161b16e6c8f599298382803dabed04b
571,456
def _dicts_intersect(d1, d2): """True iff d1 and d2 have a key in common >>> assert _dicts_intersect({1:0, 2:0}, {2:0}) >>> assert _dicts_intersect({2:0}, {1:0, 2:0}) >>> assert not _dicts_intersect({1:0, 3:0}, {2:0}) >>> assert not _dicts_intersect({2:0}, {1:0, 3:0}) """ if len(d2) < len(d...
a9231ae6d2afd9dddfda846d7c6bcfc30622a3e6
571,458
def get_L_BB_DHW_ba2_d_t(L_dashdash_ba2_d_t): """1時間当たりの浴槽追焚時におけるバックアップボイラーが分担する給湯熱負荷 (MJ/h) (28) Args: L_dashdash_ba2_d_t(ndarray): 1 時間当たりの浴槽追焚時の太陽熱補正給湯熱負荷(MJ/h) Returns: ndarray: 1 時間当たりの浴槽追焚時におけるバックアップボイラーが分担する給湯熱負荷(MJ/h) """ return L_dashdash_ba2_d_t
74ebcb2203d5d622c9f4b6f058534aeffa51caa3
571,459
import asyncio async def measure_response_time(session, url): """ Fetching an url by performing GET request. Measure the response time. :param aiohttp.ClientSession session: All requests in one session, for connection pooling. :param str url: Full URL for request. :return dict: Dict containing mea...
7442b4cb16df8eef25169558af9f3a779f0ccc98
571,460
def ignore_exception(exc): """ Used with @retrying.retry to igmore exceptions in a retry loop. ex. @retrying.retry( retry_on_exception=ignore_exception) It does verify that the object passed is an exception """ return isinstance(exc, Exception)
8349c8e8d349035c663d76a1011d829ad1497b99
571,461
from typing import List def get_items_from_string(string: str, separator: str = ',', remove_blanks: bool = True) -> List[str]: """ Returns a list of items, separated by a known symbol, from a given string. """ items = [item.strip() if remove_blanks else item for item in string.split(separator)] if...
ec6cc6f57c91ce3f701f21301141a6122086c65e
571,462
def safe_max(values): """Calculate max, but if given an empty list return None.""" values = list(values) # In case this is a complex type, get a simple list. if not values: return None else: return max(values)
4f7977d0e429fa26a4f728feac5a2fcb553fb48e
571,465
def headers_to_dict(headers): """ Converts a sequence of (name, value) tuples into a dict where if a given name occurs more than once its value in the dict will be a list of values. """ hdrs = {} for h, v in headers: h = h.lower() if h in hdrs: if isinstance(hdrs[...
afe5473cd237a108e0fc0416d28404e4c85d34ac
571,470
def get_id(element) -> str: """ Return the ID of an event or series. :param element: event or series :type element: dict :return: ID of element :rtype: str """ if "id" in element: return element["id"] elif "identifier" in element: return element["identifier"] el...
c225c01775480a20799316302955680ba4d17573
571,472
def asTuple(self): """ Returns the vector as a tuple. """ print("Warning: VBase4.asTuple() is no longer needed and deprecated. Use the vector directly instead.") return tuple(self)
a5750196110e1f8bcb071d3b6aac0cc311678267
571,475
import json def send(s, req): """Sends a JSON formatted request and returns the response. This will wait/block until a response is received or timeout occurs Args: s (socket): socket to send request over req (dict): request to convert to json and send over socket Returns: di...
951368ac5b581ddaaa3736dd3a0dca87bb902cd9
571,480
import re def verify_email(email): """ This function validates the given email using regular expression. Args: email: Email to be verified. Returns: True if email format is correct otherwise False. """ email_rule = r"^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$" return re.s...
99e27d71660d67ddb50d4d6ba759496e053fdaa9
571,481
def boxoverlap(a,b,criterion="union"): """ boxoverlap computes intersection over union for bbox a and b in KITTI format. If the criterion is 'union', overlap = (a inter b) / a union b). If the criterion is 'a', overlap = (a inter b) / a, where b should be a dontcare area. """ x1...
c3334f337775b4e49460ced4cd3ec9dfc06f964c
571,482
from typing import Optional from typing import Tuple from typing import cast def _qid_shape_from_args(num_qubits: Optional[int], qid_shape: Optional[Tuple[int, ...]] ) -> Tuple[int, ...]: """Returns either `(2,) * num_qubits` or `qid_shape`. Raises: Va...
3062b24830a6913fc2de491df14075ebe49bd75d
571,483
import socket def ip2str(address): """ Print out an IP address given a string Args: address (inet struct): inet network address Returns: str: Printable/readable IP address """ return socket.inet_ntop(socket.AF_INET, address)
151e3f58720cd97d63daef1b9be298aefc66bfd1
571,484
def line_to_type(fobject_or_string, d_type=str, no_split=False): """ Grab a line from a file like object or string and convert it to d_type (default: str). Parameters ---------- fobject_or_string : object A file like object or a string containing something that is to be converted to a s...
3c500336a6e6b9331c4ddc8a48995959a433a34e
571,485
def get_cipd_pkg_url(name, ver): """Returns URL to a package in CIPD web UI.""" return 'https://chrome-infra-packages.appspot.com/p/%s/+/%s' % (name, ver)
d287051bc7b1bee848d5e3f5d9bab2ca2d727576
571,487
def get_name_for_predict_column(columns): """ Get a unique name for predicted column. """ # As of now, the predicted column will take the form # constant string + number # The constant string is fixed as '_predicted' k = '_predicted' i = 0 # Try attribute name of the form "_id", "_i...
af58e2da722c47f52526ead5e9812b14b0136acd
571,491
import json def read_schema(path): """Read a single schema file and return the parsed JSON content. Aborts if the JSON file could not be decoed.""" with open(path, "r") as f: try: schema = json.load(f) except json.decoder.JSONDecodeError as e: exit("Invalid schema f...
3cf773f2a99664e4616db0d75fb45dc316df67fd
571,500
def array_search(l, val): """ Returns the index of `val` in `l`. """ try: return l.index(val) except ValueError: return False
2641f19b463253cf832411dd16b9ae28f63f95fd
571,501
def getMismatchedIndices(bboxes, aligned_indices): """ compute the indices of the bounding boxes that do not appear in any of the head-person pairs (matched by the hungarian algorithm) :param bboxes: bounding boxes :param aligned_indices: matched indices of bounding boxes :return: list of indice...
f9fb49c1665d211b82bf9057d3654456b0f358a7
571,502
def precision(tp,fp): """Computes precision for an array of true positives and false positives Arguments: tp {[type]} -- True positives fp {[type]} -- False positives Returns: [type] -- Precision """ return tp / (tp+fp+1e-10)
f58e533acc733750aaea1763fabec8ad37bffb88
571,504
import re def remove_tags(raw): """ Removes the <doc> tags remaining from wikiExtracted data :param raw_html: html/text content of a file with many docs :return: only text from raw_html """ cleanr = re.compile('<.*?>') cleantext = re.sub(cleanr, ' ', raw) return cleantext
62a191cedcea0f64c0628ac968d81a6989125d42
571,507
def parse_chunks(chunks): """Parse chunks and extract information on individual streams.""" streams = [] for chunk in chunks: if chunk["tag"] == 2: # stream header chunk streams.append( dict( stream_id=chunk["stream_id"], name=chun...
9c1b02201762bbd0508c116e586c6829ed64c179
571,513
def find_parts_to_upload(part_status): """ Given a string of the form "1001110", where 1 and 0 indicate a status of completed or not, return the part numbers that aren't completed. """ return [i+1 for i,c in enumerate(part_status) if c=='0']
5f7766ebe3f8f7cb97ff1d035d7d761abaca4ad7
571,514
import json def is_json(json_object): """ Check if value is json""" try: json.loads(json_object) except: return False return True
cd5361a1a8c9eac46aa95c205c42bae4d24a7f4f
571,529
def bsdchecksum(infile): """Compute BSD checksum as defined by https://en.wikipedia.org/wiki/BSD_checksum :param infile: File location to query :type infile: filepath :return: Calculated checksum :rtype: str """ with open(infile, "rb", buffering=5) as f: checksum = 0 byte =...
4b57cb51510e8bb8889255e9e61f72a66c41bb15
571,530
def _multi_itemgetter(items): """Like operator.itemgetter, but the callable always returns a sequence of lookup values (regardless of items' length) see https://docs.python.org/2/library/operator.html#operator.itemgetter """ return lambda obj: tuple(obj[item] for item in items)
e6591ec1c44b5970d5add381a3df6bd10d4c4b5c
571,532
def color_dist_sq(x,y): """ Simple squared euclidean distance for color tuples """ return (x[0]-y[0])**2 + (x[1]-y[1])**2 + (x[2]-y[2])**2
f30102207e3a4fb1368db4782137d900e209156f
571,536
def weighted_mean(points, weights): """ Compute the weighted mean. """ return (points * weights).sum()
2f476f2b6272206c572c15cf32f82343e6fa532e
571,537
def _get_line_parms(line, directive, sep_by_spaces=False, nparms_min=None, nparms_max=None): """ Take directive line and return parms and possible warning text lines. :param line: the line to parse [string] :param directive: the directive [string, e.g., '#SERIAL'] :param sep_by_spaces: False if parm...
3d348c50adf4bf9fad93d09542cf1d873deefc3e
571,539
from typing import List def get_percentile_like(xs: List[float], min_amount: float) -> float: """ Get the minimum value so that the sum of bigger values makes min_amount. Parameters ---------- xs : List[float] min_amount : float Returns ------- float """ xs = sorted(xs, r...
d20d09e5c85c584d6ae2a20d7073a33185fbee2d
571,540
def get_photo_page(photo_info): """ Get the photo page URL from a photo info object """ ret = '' if photo_info.get('urls') and photo_info['urls'].get('url'): for url in photo_info['urls']['url']: if url.get('type') == 'photopage': ret = url.get('text') return ...
89969ca801be2ade95b8eb2e5a3bcb0c8e2898b9
571,541
import csv def read(source): """Read TSV from the source.""" reader = csv.DictReader(source, delimiter='\t', quoting=csv.QUOTE_NONE) return tuple(book for book in reader)
23afc4339c1d08c037462e9438f4914fdcb57d27
571,543
def typed_line(line, parser): """Parse one line of the dataset into a typed (user, item, rating) triplet.""" user, item, rating = parser(line) return int(user), int(item), float(rating)
ff4af8d270500ecd08013761267cdbcf927e3859
571,546
def flatten(xs): """Returns collection [xs] after recursively flattening into a list.""" if isinstance(xs, list) or isinstance(xs, set) or isinstance(xs, tuple): result = [] for x in xs: result += flatten(x) return result else: return [xs]
ff7dee8dc2c0a2f4624c406f51ad60df6ae52c97
571,550
def verify_setup_command(cmd): """ Verify the setup command. :param cmd: command string to be verified (string). :return: pilot error code (int), diagnostics (string). """ ec = 0 diagnostics = "" return ec, diagnostics
1e5cba884047e4a13d3c08749e62ab7a34f8d932
571,557
def _DistributeRanks(low, high, rank_count): """Compute evenly distributed ranks in a range""" bucket_size = (high - low) // rank_count first_rank = low + (bucket_size + 1) // 2 return list(range(first_rank, high, bucket_size))
67ffb8d3ff1fb27a083013f37d73b12d5a1ed236
571,559
from typing import List def get_activity_prefix(version: str, activity: str) -> List[str]: """Get the prefix for the version + activity.""" # Each activity is versioned, so have the activity/version path. return [ 'content', activity, version, ]
86116794a07ddc5a6ce9a2fbd0cdd2f0f13b3633
571,560
def _get_outlier_cols(confounds_columns): """Get outlier regressor column names.""" outlier_cols = { col for col in confounds_columns if "motion_outlier" in col or "non_steady_state" in col } confounds_cols = set(confounds_columns) - outlier_cols return sorted(outlier_cols), ...
3fb1fadb0e1621f5d65d25d31b12715afab7107d
571,561
def findall(root, tag, namespace=None): """ Get all nodes by tag and namespace under Node root. """ if root is None: return [] if namespace is None: return root.getElementsByTagName(tag) else: return root.getElementsByTagNameNS(namespace, tag)
8f8dce4440389df7243f19b4ef2e7e3872a03d11
571,564
def map2dict(darray): """ Reformat a list of maps to a dictionary """ return {v[0]: v[1] for v in darray}
6354353c53cb46c025bfc78110dc4b8b678f984b
571,565
def route_path(route_name, request, *elements, **kw): """ This is a backwards compatibility function. Its result is the same as calling:: request.route_path(route_name, *elements, **kw) See :meth:`pyramid.request.Request.route_path` for more information. """ return request.route_path(...
60603c91037caca0694beeb49cf923872a506c5e
571,566
def get_surface_with_error(inv, contrast, porod_const, extrapolation=None): """ Get surface with uncertainty """ return inv.get_surface_with_error(contrast=contrast, porod_const=porod_const, extrapola...
c9600eb4d60506273250ad3cbde6a5b355c7b1bc
571,567
from typing import Tuple def aspect_ratio(width: int , height: int) -> Tuple[int, int]: """ Function to calculate aspect ratio for two given values. Args: width (int): width value height (int): height value Returns: Tuple[int, int]: ratio of width to height """ def gc...
3ee89d5630c91fc2144b4fcce0207c2413f5a5db
571,568
import gzip import json def read_optimization_inputs(input_json_gz): """ Read data generated by 01_generate.py Returns ------- optimization_inputs: dict Dictionary for selected torsions, has this structure: [ { 'cmiles_identifiers': { "ca...
63605e07e1580f50b9568c9c5613133040e218e1
571,571
def split_pathlib(path, separator=":"): """ Split a pathlib object :param path: Pathlib object :param separator: Character used to split :return: Parts of the path (before & after split character) """ path = str(path) components = path.split(separator) return components
bf54ca3fede1f67aad38d580a69540d94d9f63fa
571,572
import csv def csv_to_dicts(file, header=None): """Reads a csv and returns a List of Dicts with keys given by header row.""" with open(file) as csvfile: return [row for row in csv.DictReader(csvfile, fieldnames=header)]
efaefa52154962671b37e0c15a956c2cc2b5f39e
571,575