content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def convert_member(member_str): """ Convert member data from database to member id list :param member_str: Data from Class database :type member_str: str :return: a list of member id as integer :rtype: list >>> print(convert_member("1,2,50,69")) [1, 2, 50, 69] """ if (member_st...
fec4081104c3cb4574e255c8408164062a287963
25,256
import json def is_json_serializable(x): """ Check if an object is serializable by serializing it and catching exceptions :param x: :type x: :return: :rtype: """ try: json.dumps(x) return True except (TypeError, OverflowError): return False
204c0439416a778f6d017765c6c16d99c19ead91
25,257
def is_palindrome(s): """ What comes in: -- a string s that (in this simple version of the palindrome problem) contains only lower-case letters (no spaces, no punctuation, no upper-case characters) What goes out: Returns True if the given string s is a palindrome, i.e., r...
41409a3681c6f5c343f19fc53823415852243d45
25,258
import io def _load_text_file(path: str): """Load .vec file""" fin = io.open(path, 'rb') first_line = fin.readline().decode('utf8') vocab_size, embedding_size = map(int, first_line.split()) # init vocab list vocab_list = ['0'] * vocab_size # record start position of each line in file ...
139e39cf155a5c757dc8c6034c298b84881d54e7
25,259
def number_of_pluses_before_an_equal(reaction): """ Args: reaction (str) - reaction with correctly formatted spacing Returns (int): number_of - the number of pluses before the arrow `=>` Example: >>>number_of_pluses_before_an_equal("C6H12O6 + 6O2=> 6CO2 + 6H2O")...
f532ee41dee797d7c2ae1639fae9f1cb61c3f037
25,260
import random def generate_chromosome(min_length_chromosome, max_length_chromosome, possible_genes, repeated_genes_allowed): """ Function called to create a new individual (its chromosome). It randomly chooses its length (between min_length_chromosome and min_length_chromosome), and it randomly chooses genes amon...
aae0356538958bfe180b3f0abade7afd5dc2e7f7
25,261
def binary(x: int, pre: str='0b', length: int=8): """ Return the binary representation of integer x Input: x: an integer of any size pre: the prefix for the output string, default 0b length: length of the output in binary if its representation has smaller length defau...
287e5bb87f31b71ad7ccd1cf65fab729794eeef4
25,262
def calculate_median_stat(stats): """ Calculates the stat (key) that lies at the median for stat data from the output of get_stat_data. Note: this function assumes the objects are sorted. """ total = 0 keys = [k for k in stats.keys() if k != "metadata"] total = sum(stats[k]["numerators"]...
09e3f1b3059c36fe479a597de51243bb59b261d0
25,263
import torch def clip(tensor, min_tensor, max_tensor): """Imitate numpy's clip.""" clipped = torch.max(torch.min(tensor, max_tensor), min_tensor) return clipped
1b868f4a5518bc74cfed8835fa54f0d55195c3a9
25,264
import inspect def library(scope=None, version=None, converters=None, doc_format=None, listener=None, auto_keywords=False): """Class decorator to control keyword discovery and other library settings. By default disables automatic keyword detection by setting class attribute ``ROBOT_AUTO_KEYWO...
78b3a7c2423d0b594d5d8f4e564b929f2ef7148a
25,265
def false(*args): """ >>> false(1) False >>> false(None) False """ return False
cb960acdc5ddb7a2a54d1a69165fc684674b34fe
25,266
def get_pct_higher(df): """returns the percentage of the difference between ex1/ex2 closing prices""" # if exchange 1 has a higher closing price than exchange 2 if df['higher_closing_price'] == 1: # % difference return ((df['close_exchange_1'] / df['close_exchange_...
34eb491a666c5b83a70374f065f789a0559e8b4e
25,268
def reflection_normal(n1, n2): """ Fresnel reflection losses for normal incidence. For normal incidence no difference between s and p polarisation. Inputs: n1 : Refractive index of medium 1 (input) n2 : Refractive index of medium 2 (output) Returns: R : The Fresnel Doctests: ...
db3e1779628116ce2d82a91dada64aa2d8ff4463
25,269
import numpy def mut( chrom: int, all_max: list, all_min: list, prob_m: float, point_m: int, chi: list, ) -> list: """Apply random mutation to a member Parameters ---------- chrom : int The number of chromosomes a member has all_max : list The list of t...
d45a9598d8baef59014230d35586e2cd5afce583
25,270
def _get_oauth_url(url): """ Returns the complete url for the oauth2 endpoint. Args: url (str): base url of the LMS oauth endpoint, which can optionally include some or all of the path ``/oauth2/access_token``. Common example settings that would work for ``url`` would include: ...
e2f81f8fa0aab74c41eb253e1a7e2291ff96e334
25,271
def descr_bit_length(space, w_int): """int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() 6 """ val = space.int_w(w_int) if val < 0: val = -val bits = 0 while val: bits += 1 val >...
4a9ba13e91a2e398dc54ce2c157ac52faab93da3
25,273
def matchInIndex(node, index): """ :type node: mutils.Node :type index: dict[list[mutils.Node]] :rtype: Node """ result = None if node.shortname() in index: nodes = index[node.shortname()] if nodes: for n in nodes: if node.name().endswith(n.name())...
f010105cd02cd2dc699233431c2383b770ecea67
25,274
def ifiltermap(predicate, function, iterable): """creates a generator than combines filter and map""" return (function(item) for item in iterable if predicate(item))
26a89bc7df2bec825a372e0f1745ffba4bf63683
25,275
import sys def get_params(): """ Format arguments as command and args params """ temp = sys.argv[1:] cmd = temp[0] if '--' in temp[0] else '--run' args = temp[1:] if '--' in temp[0] else temp return { 'cmd': cmd, 'args': args, }
960e0e9e44d1b0591a310a7a1730877b85f8227a
25,278
import os def pip_url_kwargs(parentdir, git_remote): """Return kwargs for :func:`create_repo_from_pip_url`.""" repo_name = 'repo_clone' return { 'pip_url': 'git+file://' + git_remote, 'repo_dir': os.path.join(str(parentdir), repo_name), }
302b352737c306f61306d55df987104329b7668a
25,279
from pathlib import Path from typing import List def read_feastignore(repo_root: Path) -> List[str]: """Read .feastignore in the repo root directory (if exists) and return the list of user-defined ignore paths""" feast_ignore = repo_root / ".feastignore" if not feast_ignore.is_file(): return [] ...
57fa48fa61edfe9856d98171d54855a854c33743
25,281
from pathlib import Path import math def process(file: Path) -> int: """ Process input file yielding the submission value :param file: file containing the input values :return: value to submit """ heading = 90 east_west_pos = 0 north_south_pos = 0 instructions = [l.strip() for l...
3ba2c0a9fd4457ea2b49d6aca983123d8af45e04
25,282
import os def get_openpype_icon_path() -> str: """Path to OpenPype icon png file.""" return os.path.join( os.path.dirname(os.path.abspath(__file__)), "openpype_icon.png" )
027eab80e01269adf5c2ed6febfed68fb9850630
25,283
def calc_wildtype_point(wt, pwms, alleles, ev_couplings, start_pos=0): """Calculate immunogenicity and energy of the wildtype. Parameters ---------- ev_couplings : `EVcouplings` Read in e_ij binaries used for preparing input files. config : `ConfigParser` Configurations. Retu...
03c6b33ab0a5418322af3d25f6cd3efc65747ec7
25,284
def ensembl_gene_response(): """Return a response from ensembl gene api""" _response = [ { "description": ( "alpha- and gamma-adaptin binding protein " "[Source:HGNC Symbol;Acc:25662]" ), "logic_name": "ensembl_havana_gene", "version": 8, ...
f896fcd516d2e08a0219cf7db5f8492524328560
25,285
import six def makestr(s): """Converts 's' to a non-Unicode string""" if isinstance(s, six.binary_type): return s if not isinstance(s, six.text_type): s = repr(s) if isinstance(s, six.text_type): s = s.encode('utf-8') return s
99c5a3100effd4c75e34bfb6c021ff2fd5ebfdbf
25,286
def _nearest(pivot, items): """Returns nearest point """ return min(items, key=lambda x: abs(x - pivot))
b64eb1bb83895e56badb387067c9839e811d90b5
25,287
def give_same(value): """Return what is given.""" return value
92e0b8b3e6d40120fbe1d860ff74c220fbdfaec5
25,288
def process_mutect_vcf(job, mutect_vcf, work_dir, univ_options): """ Process the MuTect vcf for accepted calls. :param toil.fileStore.FileID mutect_vcf: fsID for a MuTect generated chromosome vcf :param str work_dir: Working directory :param dict univ_options: Dict of universal options used by almo...
083859b8ef25f8b0f1c89f0542286a692aef98c0
25,289
import itertools def get_feature_iter_func(flat): """ Helper function to determine what type of iteration to perform across two features. Takes `bool` as input. """ if flat: return lambda feature_names: itertools.combinations(feature_names, 2) else: return lambda feature_names:...
36d329b2a62f0374bfa0894eedd8f72e69d94239
25,290
def process_task(testcase: dict, values: dict): """Process testcase with values.""" for tcparam in testcase["params"]: if not tcparam.get("values"): for vvalue in values["values"]: if tcparam["id"] == vvalue["id"]: tcparam["value"] = vvalue["value"] ...
d4b1255820fe8aec8a770c9a38f2b4dd0c75d1d5
25,291
import platform import os import logging def default_ccache_dir() -> str: """:return: ccache directory for the current platform""" # Share ccache across containers if 'CCACHE_DIR' in os.environ: ccache_dir = os.path.realpath(os.environ['CCACHE_DIR']) try: os.makedirs(ccache_dir...
218340855bd7172aabcf7cf1eb461b4dfd637638
25,292
def insert(src, pos, s): """在src的pos处插入s""" before = src[:pos] after = src[pos:] return before + s + after
82b3bd2c46858623ccb51d5d6bbec1ef537a5c1e
25,293
def broadcast_proc(*procs, combine=None): """Combine two or more updaters into one. Input data is passed on to all of them, output is combined using combine(...) method or just assembled into a tuple if combine argument was omitted. combine -- should accept as many arguments as there are procs out...
102259473ea7ce98cc7514ab0052d5adf293909e
25,295
def answer(question): """ Evaluate expression """ if not question.startswith("What is"): raise ValueError("unknown operation") math = question[7:-1].replace("minus", "-").replace("plus", "+") math = math.replace("multiplied by", "*").replace("divided by", "/") math = math.split()...
ae5a0552549a59bcf879a7bb429903f8ac33084c
25,296
def retrieve_longest_smiles_from_optimal_model(task): """ From the optimal models that were trained on the full data set using `full_working_optimal.py`, we retrieve the longest SMILES that was generated. Parameters ---------- task : str The task to consider. Returns ------- ...
5692b6e5bf322b0a6df67f9ad5ac699429ba9711
25,297
def partition_sequences(k): """ Generates a set of partition_sequences of size :math:`k`, i.e. sequences :math:`(n_i)` such that :math:`\sum_{i=1}^k i n_i = k`.""" assert k >= 0, 'Negative integer.' def f(k, c, i): if k == 0: yield [0] * c elif i == k: yield [1...
fac5e4e061767bc539c9d5aebb670de8c69f1843
25,299
import re def all_collections(db): """ Yield all non-sytem collections in db. """ include_pattern = r'(?!system\.)' return ( db[name] for name in db.list_collection_names() if re.match(include_pattern, name) )
1b8220ac493036995695fc9ccf9ac74882677b4d
25,300
def single_line_paragraph(s): """Return True if s is a single-line paragraph.""" return s.startswith('@') or s.strip() in ('"""', "'''")
1e1febf21479b65920423268d93e5571de72b4ef
25,301
import os def clean_path(path, root=''): """ Returns given path in absolute format expanding variables and user flags. Parameters ---------- path : string Path to clean. root : string Alternative root for converting relative path. Returns ------- out : string ...
030d35ced383353e2a2542b1d6c4c11f097fc7e2
25,302
def join_name_with_id(stations, data): """ Performs a join on stations and pollution data :param stations: list of stations data for a specific date :param data: pollution data :return: list of joined data """ mapping = {name.lower().strip(): id_station for id_station, name in stations} ...
1dc8768d64ffa53a152052d6ab15bd36fb84dddb
25,303
def flatten_probs(probs, labels, ignore_index=None): """Flattens predictions in the batch.""" if probs.dim() == 3: # assumes output of a sigmoid layer B, H, W = probs.size() probs = probs.view(B, 1, H, W) B, C, H, W = probs.size() probs = probs.permute(0, 2, 3, 1).contiguous().vi...
515d0ffda912c60d5106881318410ba8f796662b
25,305
def makeStanDict(dobj, N_comp=2): """ convert from an MCMC data object to a dict for input to STAN""" return dict( N_comp = N_comp, N_band = dobj.n, nu_obs = dobj.freq_obs, flux = dobj.d, sigma = dobj.sig, z = dobj.z )
0e7c754937bb6bf7bd5be8dbbdea5015e9a13540
25,306
def num_words_tags(tags, data): """This functions takes the tags we want to count and the datafram and return a dict where the key is the tag and the value is the frequency of that tag""" tags_count = {} for tag in tags: len_tag = len(data[data['Tag'] == tag]) tags_count[tag] = le...
9c6fddfcbdd1958e1c43b9b9bf8750bacacc3a31
25,307
def change_possible(part): """Check if there is anything to permute""" if ':' not in part or (part.count(':') == 1 and ('http:' in part or 'https:' in part)): return False else: return True
d74359a518766eae0581de696049119848529ba3
25,308
def generate_pyproject(tmp_path): """Return function which generates pyproject.toml with a given ignore_fail value.""" def generator(ignore_fail): project_tmpl = """ [tool.poe.tasks] task_1 = { shell = "echo 'task 1 error'; exit 1;" } task_2 = { shell = "echo 'task 2...
a79d0f24a3edc9fa8689cd0c33cef9e8f8121252
25,309
def parseConfig(s): """Parses a simple config file. The expected format encodes a simple key-value store: keys are strings, one per line, and values are arrays. Keys may not have colons in them; everything before the first colon on each line is taken to be the key, and everything after is considered a spa...
259fdcef0eabeb410b2c2f79c50bb5985b5ce5f7
25,311
def parse_args(args): """ Parses the command line arguments. For now, the only arg is `-d`, which allows the user to select which database file that they would like to use. More options might be added in the future or this option might be changed. """ if args[0] == "-d": return ' '.join(...
b251103d2d73f63ff795ddad82de8040d8e81ec4
25,312
import json def make_ably_error_event(code, status): """Make a control event.""" return { 'event': 'error', 'data': json.dumps({ 'message':'Invalid accessToken in request: sarasa', 'code': code, 'statusCode': status, 'href':"https://help.ably.io/...
c88cb225cc0b6d2c5c9b14da818e65d19dbdb890
25,314
def msgs_features(msgs): """Feature extractor for a list of messages""" n_sents = sum(m['n_sentences'] for m in msgs) * 1.0 future = sum(len(m['lexicon_words'].get("disc_temporal_future", [])) for m in msgs) / n_sents return dict( polite=sum(m['politeness'] for m in msgs) / ...
263bca98df4ab4e3e167b5a565c15966069e42b4
25,315
import time import pandas def make_func(file_name): """Create function for testing. It is necessary because file_name should be constant for jitted function. """ def _function(): start = time.time() df = pandas.read_csv(file_name) return time.time() - start, df return _func...
1cf11058af2d1b00ac8cd640ef8a7e3efd7ece44
25,316
import torch def new_ones(tensor, size, dtype=None): """Return new tensor with shape.""" if dtype == 'long': dtype = torch.long elif dtype == 'uint8': dtype = torch.uint8 else: dtype = None if dtype is None: return tensor.new_ones(size) else: return tens...
2f8843a0a6bcb3493a1efce881c9e88d8a33cfa4
25,317
def get_binary2source_entity_mapping(source2binary_mapping_full): """ for each binary functions, aggregate all source functions mapping to this function""" binary2source_entity_mapping_simple_dict = {} binary2source_entity_mapping_line_dict = {} unresolved_binary_address = [] binary2source_function_...
8f75c8848b4d0c87b64cf1c0909f24e0a6866c91
25,318
def path_filter(path): # type: (str) -> str """ Removes the trailing '/' of a path, if any :param path: A parsed path :return: The parsed path without its trailing / """ return path[:-1] if path and path[-1] == "/" else path
4b449dfe2f840a25bec605464e6a8dbaeaf9afed
25,319
def generate_partial_word(word, correct_guess_list): """generates the word with all correctly chosen letters""" temp_partial_word = "" # for each letter either put a dash or a letter for i in range(len(word)): matches = False for letter in correct_guess_list: if letter == word[i]: temp_partial_word ...
35a1d1afe0262f0fd816c1e7978847b692136e05
25,320
import os def file_walker(filepath, extension=(".tiff", ".tif")): """Returns a list of filenames, which satisfy the extension, in the filepath folder :param filepath: path of the folder containing TIFF tiles :type filepath: str :param extension: Tuple of extensions which are searched for :type ex...
929564e9a9a425b99a3989b3e64408baab674d9b
25,321
from typing import Sequence from typing import Any def reverse_enumerate(iterable: Sequence[Any]): """ Enumerate over an iterable in reverse order while retaining proper indexes. Arguments: iterable: Iterable to enumerate over. """ return zip(reversed(range(len(iterable))), reversed(iter...
697c7e4ae2261b57c3f6d28ad4d0bc4bc9e1bcc9
25,323
import json def to_javascript(obj): """For when you want to inject an object into a <script> tag. """ return json.dumps(obj).replace('</', '<\\/')
2fba6a30eb19fd0b8fcc4295c3994ad6fa82b02f
25,324
def parse_years(years): """Parse input string into list of years Args: years (str): years formatted as XXXX-YYYY Returns: list: list of ints depicting the years """ # Split user input into the years specified, convert to ints years_split = list(map(int, years.split('-'))) ...
5296bd2f9e49a4a1689c813dd0e8641ea9a5c16f
25,326
def dict_from_string(s): """ Inverse of dict_to_string. Takes the string representation of a dictionary and returns the original dictionary. :param s: The string representation of the dictionary :return: [dict] the dictionary """ l = s.replace("[", "").replace("]", "").split("_") d = {x....
b16677d1d39cfe74b53a327e2bcd85b6f16ee8de
25,329
def get(columns, table): """ Format SQL to get columns from table Args: columns (tuple): column names table (str): table name to fetch from Returns: str: sql string """ columns = tuple([columns]) if isinstance(columns, str) else columns return "SELECT {c} FROM {t}".form...
7c4bacad2121f66782e551d440d602e381d77b89
25,330
def get_text(data): """ :param data: status as json dict :return: the full text of the status """ # Try for extended text of original tweet, if RT'd (streamer) try: text = data['retweeted_status']['extended_tweet']['full_text'] except: # Try for extended text of an original tweet, if...
f2a30578cff007ddc82f362d1b047b48a38ba71c
25,331
import inspect import functools def onetimemethod(method): """Decorator for methods which need to be executable only once.""" if not inspect.isfunction(method): raise TypeError('Not a function.') has_run = {} @functools.wraps(method) def wrapped(self, *args, **kwargs): """Wrapped m...
8133ee826ea57bbf05e01bac81757e22f0e4c072
25,333
def lcs_to_add(lcs,ref,Nb,Ne,dat,Mb,Me,add): """This routine takes the snake list, the reference file, the data file, and the add section from the tolerance file. Based on this information it merges any new tolerances into the add tolerance data structure. The new add tolerance data structure are retur...
983aa6a1cab71aa977c126805936f626edee603b
25,334
def nevergrad_get_setting(self): """Get a setting to trial from one of the nevergrad optimizers. """ method = self._method_chooser.ask() params = self._optimizers[method.args[0]].ask() return { 'method_token': method, 'method': method.args[0], 'params_token': params, ...
578a41bce432981b24cd84c70e9c2b2544e7bde7
25,335
import os import re def load_stage1_intfs(path): """Load interfaces of stage1 generated code. Parameters: path: str Filesystem path to read data from. Relative or absolute. No final pathsep. Example: "." for the current directory. Will be scanned for filenames of ...
e8b5b17eb0e95fbd85f01a87efb9869c875c5c20
25,336
from typing import Tuple import math def rotation_y_to_alpha( rotation_y: float, center: Tuple[float, float, float] ) -> float: """Convert rotation around y-axis to viewpoint angle (alpha).""" alpha = rotation_y - math.atan2(center[0], center[2]) if alpha > math.pi: alpha -= 2 * math.pi if...
785ee46456e373b28e5fcb4edd3a81a3e344abda
25,337
def sigma2Phi(sigma,i,overall_solution_space,reference_seq): """This takes in an amino acid and a position and returns the 1x19 binary indicator vector Phi""" AAchanges = [aa for aa in overall_solution_space[i] if aa!=reference_seq[i]] # these are all 19 possible AA changes (i.e. AAs that are not the reference ...
8a18168e1931ba6b49a367957bd5f4a07a424315
25,340
def _normalize(vec): """Normalizes a list so that the total sum is 1.""" total = float(sum(vec)) return [val / total for val in vec]
31ca018d688a5c28b89071e04049578737cd027d
25,344
def to_float(string): """Converts a string to a float if possible otherwise returns None :param string: a string to convert to a float :type string: str :return: the float or None if conversion failed and a success flag :rtype: Union[Tuple[float, bool], Tuple[None, bool]] """ try: r...
00f3e16765aad9dc79e73cb687676893a743cc7f
25,345
import argparse def get_args(): """ Grab CLI arguments. :return: CLI arguments dict. """ argp = argparse.ArgumentParser( description="Checks the replica lag of a MySQL Slave or returns OK if it's a Master" ) argp.add_argument('-H', '--hostname', action='store', required=False, de...
11c7a2462c9fd27c706b2084435c53ca9284f770
25,346
import re import os def get_project_directory() -> list: """ Returns project directory Returns: project_dir (list): path back to top level directory """ project_dir = re.split(r"\\|/", os.path.dirname(os.path.realpath(__file__))) + ['..', '..', '..'] ret...
14af81c1c7f79ca45bf688313eb2702ccf498a2d
25,347
def body_abs(df): """ 波动绝对值 :param df: :return: """ return abs(df['open'] - df['close'])
210a70c7c74b0a5001d92f67943c95e52c13af09
25,348
def month_add(date, months): """Add number of months to date""" year, month = divmod(date.year * 12 + date.month + months, 12) return date.replace(year=year, month=month)
8252e82f8b7dae41a6d3dee8e6bc58b00c376aa7
25,349
import os import argparse def get_args(): """ Allows users to input arguments Returns: argparse.ArgumentParser.parse_args Object containing options input by user """ def isFile(string: str): if os.path.isfile(string): return string else: rais...
7d5dcd4d493931d5ab63666cfce8735d28db222c
25,350
def obtain_Pleth(tensec_data): """ obtain Pulse Pleth values of ten second data :param tensec_data: 10 seconds worth of heart rate data points :return PlethData: Pulse Pleth unmultiplexed data """ PlethData = tensec_data[0::2] return PlethData
45159ae768aa8dfa0f67add0951fecb346a8557b
25,351
def R_to_r(R): """ Description: A function to scale down the autocorrelation function to a correlation function Input: :param R: Autocorrelation function of the signal Output: :return r: correlation function of the signal :rtype: ndarray """ r ...
951832bc9bc3e4817250c6f0473413b7a65b701d
25,352
def get_policy(crm_service, project_id, version=3): """Gets IAM policy for a project.""" policy = ( crm_service.projects() .getIamPolicy( resource=project_id, body={"options": {"requestedPolicyVersion": version}}, ) .execute() ) return policy
984f40daa2a5e5334d7aa1adb3920c56f7a13a9b
25,353
def get_log_data(lcm_log, lcm_channels, end_time, data_processing_callback, *args, **kwargs): """ Parses an LCM log and returns data as specified by a callback function :param lcm_log: an lcm.EventLog object :param lcm_channels: dictionary with entries {channel : lcmtype} of channels ...
6e2a57f04af2e8a6dc98b756ff99fab50d161ffe
25,354
from typing import OrderedDict def stats(arr): """ Return the statistics for an input array of values Args: arr (np.ndarray) Returns: OrderedDict """ try: return OrderedDict([('min', arr.mean()), ('max', arr.max()), ...
2243b48e129096c76461ea6a877a6b2a511d21d0
25,356
import uuid def generate_blank_record(): """ Generate a blank record with the correct WHO PHSM keys. Other objects requiring the same selection of keys descend from here. Returns ------- A blank record with keys in WHO PHSM column format. type dict. """ record = { ...
a4c2cc723d2b5d4e7ddcf173e0bf3a4b4587173e
25,358
from typing import Callable from typing import Iterable from typing import Optional from typing import Any def find(predicate: Callable, sequence: Iterable) -> Optional[Any]: """ Find the first element in a sequence that matches the predicate. ??? Hint "Example Usage:" ```python member = ...
32060a3bd3b578bb357e68dad626f71d0c8ea234
25,360
def get_final_values(iterable): """Returns every unique final value (non-list/tuple/dict/set) in an iterable. For dicts, returns values, not keys.""" ret = list() if type(iterable) == dict: return(get_final_values(list(iterable.values()))) for entry in iterable: if (type(entry) ...
466dd8542c87f8c03970ca424c608f83d326c2cb
25,361
def ko_record_splitter(lines): """Splits KO lines into dict of groups keyed by type.""" result = {} curr_label = None curr = [] i = 0 for line in lines: i+= 1 if line[0] != ' ': if curr_label is not None: result[curr_label] = curr fields = ...
c3a378dc01f0f2d2559fbe9a6eda4f5fb6183e68
25,362
def node_to_ctl_transform(graph, node): """ Return the *ACES* *CTL* transform from given node name. Parameters ---------- graph : DiGraph *aces-dev* conversion graph. node : unicode Node name to return the *ACES* *CTL* transform from. Returns ------- CTLTransform ...
bae6941fdea34b8481981269db7be4c6513553f8
25,363
def contains_str(cadena1, cadena2): """Comprueba que la primera cadena se encuentra contenida en la segunda cadena. Arguments: cadena1 {[str]} -- Cadena a encontrar cadena2 {[str]} -- Cadena base """ cad1 = cadena1.lower() cad2 = cadena2.lower() puntuacion = 0 punt...
e81bf557c3893e0f47ee4579a67b5e4c5125b19f
25,364
def yiq_to_rgb(yiq): """ Convert a YIQ color representation to an RGB color representation. (y, i, q) :: y -> [0, 1] i -> [-0.5957, 0.5957] q -> [-0.5226, 0.5226] :param yiq: A tuple of three numeric values corresponding to the luma and chrominance. :return: RGB ...
0ede6cfacc368a3d225fe40b0c3fe505f066233b
25,365
def read_y_n(inp): """ Takes user's input as an argument and translates it to bool """ choice = input(inp) if choice.lower() in ['y', 'yep', 'yeah', 'yes']: return True return False
cf1baee8d4b3e533ff0216c3d94e1bf6ed17a202
25,369
def delim() -> str: """80 char - delimiter.""" return '-' * 80 + '\n'
d74e847836632d3a7f7e2705d5b1dee0210d0161
25,371
def _synda_search_cmd(variable): """Create a synda command for searching for variable.""" project = variable.get('project', '') if project == 'CMIP5': query = { 'project': 'CMIP5', 'cmor_table': variable.get('mip'), 'variable': variable.get('short_name'), ...
439eee8b4e71ada16f586e992f194b434a5b1551
25,372
def django_db_fields(model): """ Return the fields actually stored for each table """ all_fields = set(model._meta.fields) for cls in model.__bases__: if getattr(cls,'_meta',None): all_fields = all_fields.difference(set(cls._meta.fields)) return all_fields
f4a538875b7dc527a12f090323749d2fa1e0501e
25,373
def from_aws_tags(tags): """ Convert tags from AWS format [{'Key': key, 'Value': value}] to dictionary :param tags :return: """ return {tag['Key']: tag['Value'] for tag in tags}
a58931a29302154cc01656ece403d1468db1a6ab
25,374
def geo_query(ds, ulx, uly, lrx, lry, querysize=0): """ For given dataset and query in cartographic coordinates returns parameters for ReadRaster() in raster coordinates and x/y shifts (for border tiles). If the querysize is not given, the extent is returned in the native resolution of dataset ds. ...
23f74093377889f6fd91f379d5292d5d61b9957f
25,377
def index_nearest_shape(point, r_tree, shape_index_dict): """Returns the index of the nearest Shapely shape to a Shapely point. Uses a Shapely STRtree (R-tree) to perform a faster lookup""" result = None if point.is_valid: # Point(nan, nan) is not valid (also not empty) in 1.8 geom = r_tree.nea...
08153395ec03d9f0496f3bc16a0a58c2e1d09d60
25,380
import time def timestamp_suffix(): """Generate a suffix based on the current time.""" return '-' + str(int(time.time()))
10dde6e7c5215f9859eb39ead7b7f88503973060
25,382
def example_globus(request): """Globus example data.""" return { 'identity_provider_display_name': 'Globus ID', 'sub': '1142af3a-fea4-4df9-afe2-865ccd68bfdb', 'preferred_username': 'carberry@inveniosoftware.org', 'identity_provider': '41143743-f3c8...
61c489bf3bdd66330c634326af895d0454a64406
25,383
def _verify_data_inputs(tensor_list): """Verify that batched data inputs are well-formed.""" for tensor in tensor_list: # Data tensor should have a batch dimension. tensor_shape = tensor.get_shape().with_rank_at_least(1) # Data batch dimensions must be compatible. tensor_shape[0].assert_is_compatib...
43ef710835370f1c348cf27a67df13e0c96bed18
25,384
def join_col(col): """Converts an array of arrays into an array of strings, using ';' as the sep.""" joined_col = [] for item in col: joined_col.append(";".join(map(str, item))) return joined_col
f6386d99e69e3a8c04da2d7f97aa7fb34ac9044c
25,386
def cint2lev(arr, cint): """Determines appropriate contour levels for a plt. arr -- The array that is about to be contoured cint -- The requested contour interval""" if cint <= 0.: return [] lb = arr.min() ub = arr.max() first = 0. while True: if first > lb: ...
baebdc0efee45685b616704d281eae0d9cfa3b57
25,387
def read_words_from_file(f): """ Reads a text file of words in the format '"word1","word2","word3"' """ txt = open(f).read() return list(map(lambda s: s.strip('"'), txt.split(",")))
669aeebd2cbfeb67cdc0cd65da2e58fdefa3bfe6
25,389