content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Any from typing import Optional import operator def _ensure_int(item: Any, item_name: Optional[str] = None) -> int: """Ensure a variable is an integer. Parameters ---------- item : Any Item to check. item_name : str | None Name of the item to show inside the err...
329a7b0a2b190c858595b6cb43eea633f342ec30
639,909
import socket def get_ip_hostname(node): """ Takes in either a hostname or an IP address and returns (ip, hostname). Note if IP is given both values will be the same, i.e. we don't actually care about finding the hostname if user specified an IP""" if '.' in node: return (node, node) ...
902a017b08044c01d68a955afbaa3d7e79bc415a
639,911
def Total_Dots(link): """ Function to calculate the Total Number of Dots in a URL """ dot='.' count=0 for i in link: if i==dot: count+=1 return count
ca669c57c7d22743b2b530b77d31101d9cdb0a91
639,912
def kappa_no_prevalence_calc(overall_accuracy): """ Calculate kappa no prevalence. :param overall_accuracy: overall accuracy :type overall_accuracy : float :return: kappa no prevalence as float """ try: result = 2 * overall_accuracy - 1 return result except Exception: ...
d143b67eeff0de5f5b01d2129861437c5c33f463
639,913
def wdwd_obj(X, y, W, C, beta, offset, eta): """ Objective function for DWD. """ d = y * (X.dot(beta) + offset) + eta return sum(W / d) + C * sum(eta)
13a5e828c8b8c36cd9a7dc66238339cc5fa21493
639,917
def etree_to_dict(t): """Convert etree to dictionary""" d = {t.tag : map(etree_to_dict, t.iterchildren())} d.update(('@' + k, v) for k, v in t.attrib.iteritems()) d['text'] = t.text return d
b430058370124e1b5e1100d3b8269f9b6b613805
639,918
def _find_sa_sess(decorated_obj): """ The decorators will by default use sqlalchemy.db to find the SQLAlchemy session. However, if the function being decorated is a method of a a class and that class has a _sa_sess() method, it will be called to retrieve the SQLAlchemy session that ...
5c2bf6c12afa0022a6439b7359558d9daed85000
639,921
from typing import BinaryIO def read_batch_from_end(byte_stream: BinaryIO, *, size: int, end_position: int) -> bytes: """ Reads batch from the end of given byte stream. >>> import io >>> byte_stream = io.BytesIO(b'Hello\\nWorld!'...
151be9c5b06bc36379f2848a9d995dd4b85f9aa3
639,925
def rivers_with_station(stations): """receives list of station obhjects and returns a list of names of rivers that have at least one station on""" rivers = set() for station in stations: rivers.add(station.river) return rivers
fdf415d5a3a88f6d4ac94069a623c38c48294b4d
639,926
def replace(node, **kw): """Equivalent to namedtuple's _replace. When **kw is empty simply returns node itself. >>> o = BinOp(Add(), NumberConstant(2), NumberConstant(3)) >>> o2 = replace(o, op=Sub(), left=NumberConstant(3)) >>> print(o, o2) (2 + 3) (3 - 3) """ if kw: vals =...
63f2872c08ce6a63f6280c9bf25d2deca4f5d932
639,927
def get_daily_mean_voltages(data): """ Get daily average voltage for each channel. Returns positive voltages """ return data.loc[:, data.columns.str.startswith('voltage')].mean().abs()
27d2f9812067346aedc79df0c914113dc3f8b47d
639,932
def _get_baseline_value(baseline, key): """ We need to distinguish between no baseline mode (which should return None as a value), baseline mode with exceeded timeout (which is stored as None, but should return 0). """ if key in baseline: return 0 if baseline[key] is None else baseline[k...
55b34f172cda091705d6d766f45b0cbc445a500a
639,933
import torch def test(network, loss_function, test_set, batch_size_test, device="cpu"): """ Tests a model in a test set using the loss function provided. (Please note that this is not to be used for testing with a compatibility loss function.) Args: network: The model which is undergoing...
e0541ffbf3509d79402e8da203f906b80369f598
639,936
def get_config(self,dst_name=''): """ Gets the current configuration file of the router to current ``result`` folder. Default ``dst_name`` is ``juniper.conf.gz`` """ return self.get_file('/config/juniper.conf.gz',dst_name)
5ab07d46dbc1f71b0dafb4242743430adb80c30b
639,937
def completeCube(hdf, colour, group): # ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ """ Check that a requested cube is all there (data, var, wht). """ if (colour+'_Cube_Data' not in group.keys()) or \ (colour+'_Cube_Variance' not in group.keys()) or \ (colour...
fe40c3b24a74b9072e74b8cc37f49b0264355a77
639,938
def maybe_center(do_center, image): """Possibly center image data from [0,1] -> [-1, 1]. This assumes the image tensor is scaled between [0, 1]. Args: do_center: To do the centering or not. image: [0, 1] Scaled image to be centered. Returns: A possibly centered image. """ if do_center: re...
55887eca3d2e0f6d6e57fe991aeaafef0bc7cac2
639,939
def default_freeze_dataset_task_spec(dtool_config): """Provide default test task_spec for FreezeDatasetTask.""" return { 'dtool_config': dtool_config, 'stored_data': True, }
01bbfeda926f39d870dd6a9d849a1142b71ef2cd
639,940
def strip_hydrogen(atoms, bonds): """ Remove hydrogens from the atom and bond tables. """ atoms = atoms[atoms['element'] != 'H'] bonds = bonds[bonds['start'].isin(atoms['atom']) & bonds['end'].isin(atoms['atom'])] return (atoms, bonds)
0117122d92dc260ac3136603b9af1daa39a36593
639,941
import torch def entropy(probs): """ Computes the entropy of a normalized probability distribution. """ return -(torch.log(probs) * probs).sum(dim=-1)
81f35db846e3b63bd421ed0cfb9c6da6533aa21e
639,942
def construct_address(host, port, route, args): """ {host}:{port}{route}?{'&'.join(args)} :param str host: '172.0.0.1' :param str port: '5000' :param str route: '/store/file/here' :param list[str] args: ['a=b', 'c=d'] """ return f"http://{host}:{port}{route}?{'&'.joi...
27079a2a1430f4a9a855ad0e34b362c9178c17dc
639,947
def get_repo_name(url: str) -> str: """ Get the name of the repo. :param url: The URL on which the name of the repo will be retrieved. :return: The name of the repo. """ return url.split('https://github.com/')[1].split('/')[1]
d2f7c14e424b0233b6867ae8311b4177c379b61a
639,951
import errno def retry_when_interrupt(f, *a, **kw): """ Call C{f} with the given arguments, handling C{EINTR} by retrying. @param f: A function to call. @param *a: Positional arguments to pass to C{f}. @param **kw: Keyword arguments to pass to C{f}. @return: Whatever C{f} returns. ...
99b544c07651c2b5c117c6fc9da04c832de51f8f
639,952
def first(the_iterable, condition=lambda x: True): """ Finds first item in iterable that meets condition """ for i in the_iterable: if condition(i): return i return None
bd29454b5f8e12a93613a9e3c2ac899509a59a2d
639,953
def beta_moments(mean, sd): """Calculates the moments of a beta distribution based on mean and sd as they are more intuitive inputs More info on beta: https://en.wikipedia.org/wiki/Beta_distribution Inputs: mean - a float - the chosen mean of the distribution sd - a float ...
0acae4962c5118d368399e03023fc32ca0cebfeb
639,954
def find_in_response(resp, query): """ check if HTTP response contains 'to_find' string returns True if found, False otherwise """ return True if query in resp else False
6db2ea14371f5a9ab17aabccd4b83c0539f725f9
639,958
import math def get_page_number_from_post(post_id:int) -> int: """Calculate the page number of a given post by assuming each game thread page has 30 posts. Args: post_id (int): The ID of the post of interest. Returns: int: The page number of the input post. """ page_number = ...
d9497a8bcbcf6df15208755b66aa8f498cf7b14d
639,966
import re def searchstr(str_): """Clean up a string for use in searching.""" if not str_: return '' str_ = str_.lower() for pat in [r'\(.*\)$', r'\[.*\]', '{.*}', "- .* -", "'.*'", '".*"', ' (- )?(album|single|ep|official remix(es)?|soundtrack|ost)$', r'[ \(]f(e...
d591657ba2f7711babcc910c079580d118881a66
639,969
import re def reFindNext ( v, pos, pattern, bodyFlag, reFlags = None ): """ reFindNext: use re.search() to find pattern in a Leo outline. v the vnode to start the search. pos the position within the body text of v to start the search. pattern the search string bodyFlag true: search body text. false: se...
d9e6bef6aed3a75f6d4b53e7f52868fef9cf1896
639,974
def dice_parser(text): """ A basic dice parser that takes a string of the type: x_1 D y_1 + x_2 D y_2 + .... x_n D y_n and converts it into two lists of dice amount and dice type Parameters: ----- text: string contains the text we want to parse Returns: ----- ...
0d419b8ae994881c1fc1bcf19c9caa64ed9baa86
639,978
from typing import List def station_by_name(station_list: List[dict], station_name: str) -> int: """Returns the current index of a station. The starting point is the name of the station. If no station with this name exists, -1 is returned. """ for index, station in enumerate(station_list): if...
7378fd072a1a1d5d8795f04c585ee88faf03a164
639,981
import json def example_filter(request): """ Filters out reports with a 'document-uri' not from included.com. """ report = json.loads(request.body) doc_uri = report.get('document-uri', '') if doc_uri.startswith('http://included.com'): return True return False
608411887a3328b82d53e476c169047828d0736c
639,982
def get_dimensions(corners): """ Get the dimension of a position based on the distance of its corners. This is used to determine the feild of view of a zoom :param corners: list containing 4 points with (x,y) values :return: (x,y) dimension of the position """ x0, y0 = corners[0] x1, y1 ...
68beaaf1931a615205ee0032cbc52d2adae3f72b
639,986
import torch def tensor2onehot(labels): """Convert label tensor to label onehot tensor. Parameters ---------- labels : torch.LongTensor node labels Returns ------- torch.LongTensor onehot labels tensor """ eye = torch.eye(labels.max() + 1) onehot_mx = eye[la...
dd605d8731eab658e609d94e04716a9221a48357
639,989
def startswith(prefix): """ Create a function that checks if the argument that is passed in starts with string :param str prefix: string to check the start for :return func startswith_function: a function that checks if the argument starts with the specified string """ def string_starts_...
47e0967ce9864743f412070ba1e016f83fe708ed
639,990
def _answer(result, line): """Answer the question as best as we can""" msgs = [u"Q: {}".format(result["Input"][1])] del result["Input"] for pod_type in ["Result", "Solution", "Derivative"]: if pod_type in result: msgs.append(u"A: {}".format(result[pod_type][1])) return '...
a41cc92b5e9734dc4f5f116a8e8b4a06b03641a5
639,992
import math def log_activation(x): """ Returns the log of x. """ return math.log(x)
22a00c2e07c58ace7bbe670935ebc0f48aa60a89
639,993
import math def convtransp_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Utility function for computing output of transposed convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(h_w) is not tuple: h_w = (h_w, h_w) if type(kernel_size) is n...
441576a77f639f22f71a5a54ff4aeb2bd584d7df
639,996
def normalize_whitespace(sent): """Substitutes extra contiguous whitespaces with a single whitespace""" return ' '.join(sent.strip().split())
bd3a44c59aaf53df1fc46e83f626aea51b2b133f
639,998
def _size_crop(width, height): """Performs a cropping resize.""" return ("-vf", r"scale=max({height}*(iw/ih)\,{width}):max({width}/(iw/ih)\,{height}),crop={width}:{height}".format(width=width, height=height),)
d14b8db50494c46577b13af596defb0364f2c6cc
640,001
def order_entries(files): """Re-order the file entries, if an order is given.""" order = files.get("order") files = files.get("entries", []) if order: files_ = files.copy() keys = [f["key"] for f in files] def get_file(key): idx = keys.index(key) keys.pop...
5f910875bbe912ba0b8ecfc9e8df74a25e0fa667
640,002
import socket def is_valid_ipv4(ip_str): """ Check the validity of an IPv4 address """ try: socket.inet_pton(socket.AF_INET, ip_str) except AttributeError: try: # Fall-back on legacy API or False socket.inet_aton(ip_str) except (AttributeError, socket.error): ...
1860eb48bca95f48e914ac3e8c8de021f79c74f3
640,006
import sqlite3 from typing import Callable from typing import Optional def sql_binary_search( connection: sqlite3.Connection, table: str, column_value: str, column_index: str, fun_compare: Callable[[float], bool], *, lower_bound: bool = True, ) -> Optional[int]: """ Helper function...
dc800b081c78b8c97b6f9a315ce4ed39ae5ae555
640,008
def getReportPath(job, reportType): """ Return the filename for the error report. Does not include the folder to avoid conflicting with the S3 getSignedUrl method. """ path = 'submission_{}_{}_{}_report.csv'.format(job.submission_id, job.file_type.name, reportType) return path
8fb2b34be8ce615120387bdee48b6855d97d0d60
640,014
def warmup_lines_to_chop(benchmark, warmup): """Returns the number of lines to be excluded from final measurements. """ # The main benchmark emits its own line. lines_to_chop = warmup # Each of the child benchmarks emit their own line. lines_to_chop += warmup * len(benchmark.children) # hhv...
74b92f52e9279818136cb6dde6e093892592ece5
640,019
def get_build(cloudbuild, image_project, build_id): """Get build object from cloudbuild.""" return cloudbuild.projects().builds().get(projectId=image_project, id=build_id).execute()
937e4977a1c1cba1527b20b53cd0f8829ef5e939
640,021
def get_fabric_ip_networks(cfmclient, fabric_uuid=None): """ Get a list of IP networks from the Composable Fabric. :param cfmclient: :param fabric_uuid: UUID of fabric :return: list of IP address dict objects :rtype: list """ path = 'v1/fabric_ip_networks' if fabric_uuid: pat...
7e9e5cbc5da247e8048c57a2aef18e887090a9c4
640,022
import base64 def np_to_json(obj, prefix_name=""): """Serialize numpy.ndarray obj :param prefix_name: unique name for this array. :param obj: numpy.ndarray""" return {"{}_frame".format(prefix_name): base64.b64encode(obj.tostring()).decode("utf-8"), "{}_dtype".format(prefix_name): obj.dtype...
f9de47cf1c52df52808e9c8a39262478f1ddcf1b
640,025
def label_gen(index): """Generates label set for individual gaussian index = index of peak location output string format: 'a' + index + "_" + parameter""" # generates unique parameter strings based on index of peak pref = str(int(index)) comb = 'a' + pref + '_' cent = 'center' sig = ...
dba6b35777ec3d1c4db16498b0dfc7dd8c6ebaa7
640,027
from typing import List def compute_forgetfulness(correctness_trend: List[float]) -> int: """ Given a epoch-wise trend of train predictions, compute frequency with which an example is forgotten, i.e. predicted incorrectly _after_ being predicted correctly. Based on: https://arxiv.org/abs/1812.05159 """ if...
b9a591350bcfabefef0593a744d39d47e5828113
640,037
import cmath import math def op_tan(x): """Returns the tangent of this mathematical object.""" if isinstance(x, list): return [op_tan(a) for a in x] elif isinstance(x, complex): return cmath.tan(x) else: return math.tan(x)
e2acd28cce9de4c58bb446addf81d7cab4ebae17
640,040
def get_label_filter(input_labels): """ Allow labels input to be formatted like: -lb key1:value -lb key2:value AND -lb key1:value,key2:value Output: key1:value,key2:value :param list(str) input_labels: list of labels, like, ['key1:value1', 'key2:value2'] or ['key1:value1,key2:valu...
787ce61c130432065c7d0f50e06fe1f3903dfd59
640,041
from typing import Optional from datetime import datetime import pytz def date_from_string(dtstr: str, fmt: str, timezone: str) -> Optional[datetime]: """Get datetime object from a date string. Args: dtstr: input date string fmt: datetime format string timezone: time zone string Return...
d114d9cb366ad70c89b38f16bbf80123d2dcd9f9
640,048
def AioNodeNameFromMotorNickname(motor): """Returns AIO node name for the specified motor.""" return 'kAioNodeMotor' + motor.capitalize()
12715b7b0273dac38a19e82ac9192205d7283c11
640,053
def get_rc(sequence): """Returns the reverse complement of sequence. Sequence may only contain letters A, C, G, or T (in uppercase).""" table = ['A', 'C', 'G', 'T'] sequence = list(sequence) for key, value in enumerate(sequence): sequence[key] = table[3 - table.index(value)] return...
43a180ca00d406230d42d0ecb157591208d531be
640,055
def _is_part_dsn(msg): """ Receive a MIME part and returns True if it is a DSN False is returned otherwise """ if len(msg) <= 1: return False if msg[1].get_content_type() != 'message/delivery-status': return False return True
31f6f8472676abfc0e94add96c47111cf19a4a74
640,056
def join_s3_uri(bucket, key): """ Join AWS S3 URI from bucket and key. :type bucket: str :type key: str :rtype: str """ return "s3://{}/{}".format(bucket, key)
9c5af83aea0f4a56996f29597dad91f232ba7c20
640,057
def lustre_ost_id(fsname, ost_index): """ Return the Lustre client ID """ return "%s:%s" % (fsname, ost_index)
582845e7762f8705d930a023a296dc68344d41b0
640,060
def default_authority(pyramid_request): """ Return the test env request's default authority, i.e. 'example.com' Return the default authority—this automatically has a `__world__` group """ return pyramid_request.default_authority
69310c71e6592d79bd5cfbe5821c09bd60807efa
640,065
from typing import Dict from typing import Any from typing import Tuple from typing import Sequence def prepare_kwargs( kwargs: Dict[str, Any] ) -> Tuple[Sequence[str], Sequence[Any], Sequence[str]]: """Create three sequences from the provided kwargs. The first sequence is the keys of the kwargs. The second seque...
4c08d4572a2f8764abd70da15d7c716bf55a9360
640,068
def ne(x, y): """Not equal""" return x != y
9e8f60889705122d0a6f98febdc689983a9e4cbf
640,071
def remove_anchor(url: str) -> str: """ Removes anchor from URL :param url: :return: """ anchor_pos = url.find('#') return url[:anchor_pos] if anchor_pos > 0 else url
fa10c7af5b86dcc41c79d054a4df249fa570e61b
640,075
def admin2_urlname(view, action): """ Converts the view and the specified action into a valid namespaced URLConf name. """ return 'admin2:%s_%s_%s' % (view.app_label, view.model_name, action)
1d95fccdb1a9abae1322087fdaf52061c12a4ac4
640,076
def get_kmer_from_index(kmax, index): """ takes a number (essentially base 4) and returns the kmer it corresponds to in alphabetical order eg. AAAA = 0*1 CA = 4*4 + 0*1 GC = 3*4 + 1 * 1 """ bases = 'ACGT' out = '' for k in range(kmax - 1, -1, -1): face, index = divmod...
5a9467a99af5e3a301b5ac60d3088a4e3da92586
640,078
from typing import Tuple from typing import Dict def bbox_to_geojson(bbox: Tuple) -> Dict: """Return bbox geojson feature.""" return { "geometry": { "type": "Polygon", "coordinates": [ [ [bbox[0], bbox[3]], [bbox[0], bbox[...
b708410cbeee3ec40e33b24e02d8927693c8e764
640,080
def permute_data(x, pe_dir): """ This function permutes data of the tensor x of size (batch, n_channels, 1st_size, ..., nth_size) so that the PE direction become the first dimension (except the batch and n_channels dimensions). :param x: the tensor of size (batch, n_channels, 1st_size, ..., nth_size) ...
28ca89520f32203636465b44e263ee9f95da4491
640,085
def is_pandigital(n_str, k): """Verify number is pandigital.""" if len(n_str) == k and set(n_str) == set('123456789'[:k]): return True else: return False
98a6140d0e0e49cdb19013dae8bd180c7975e72e
640,086
import itertools def construct_game_queries(base_profile, num_checkpts): """Constructs a list of checkpoint selection tuples to query value function. Each query tuple (key, query) where key = (pi, pj) and query is (p1's selected checkpt, ..., p7's selected checkpt) fixes the players in the game of diplomacy ...
1ffa16ebfd04f468cbde6db264ba33373c1b1d05
640,089
from typing import Callable from typing import List from typing import OrderedDict def order_json(data, sort_fn: Callable[[List[str]], List[str]] = sorted): """Sort json to a consistent order. When you hash json that has the some content but is different orders you get different fingerprints. .. cod...
657f932d54111405ee9ac606346d2b7cc02391eb
640,090
import gzip def smart_open(path, *args, **kwargs): """Opens files directly or through gzip depending on extension.""" if path.endswith('.gz'): return gzip.open(path, *args, **kwargs) else: return open(path, *args, **kwargs)
57c40c5e1eaa4db03629b9cad22cc1a0e7601be0
640,097
def tcp_traceflow(frame, *, data_link): """Trace packet flow for TCP. Args: frame (pcapkit.protocols.pcap.frame.Frame): PCAP frame. Keyword Args: data_link (str): Data link layer protocol (from global header). Returns: Tuple[bool, Dict[str, Any]]: A tuple of data for TCP reass...
b23ffa745e962c9501030024620c70e069061116
640,099
from typing import Tuple def ip_port_hostname_from_svname(svname: str) -> Tuple[str, int, str]: """This parses the haproxy svname that smartstack creates. In old versions of synapse, this is in the format ip:port_hostname. In versions newer than dd5843c987740a5d5ce1c83b12b258b7253784a8 it is hostname_...
a5cf4eeb9c085c693ae66bb5a1a55586942948b7
640,100
def ConstantTimeIsEqual(a, b): """Securely compare two strings without leaking timing information.""" if len(a) != len(b): return False acc = 0 for x, y in zip(a, b): acc |= ord(x) ^ ord(y) return acc == 0
f2c12ba1ca50737ea3d219f952dc7d917bcd7385
640,102
import math def make_ids(n: int, prefix: str = "id_"): """ Return a length ``n`` list of unique sequentially labelled strings for use as IDs. Example:: >>> make_ids(11, prefix="s") ['s00', s01', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10'] """ if n < 1: ...
14b5651b7d8208d75936d769427700f2bd4dfaef
640,106
import math def generate_IDF(corpus, corpus_dict, total_queries): """ Function to generate IDF for all the words in the vocab. :param corpus: Corpus of words in the queries. :param corpus_dict: Mapping of query number and its corpus. :param total_queries: Total number of queries. :return idf_d...
7ac0724c7b95f0ba2261934fccea5e89be7d3717
640,108
import re def truncate(text, max_len=250, suffix="..."): """ Truncate a text string to a certain number of characters, trimming to the nearest word boundary. """ stripped = text.strip() if len(stripped) <= max_len: return stripped substr = stripped[0:max_len + 1] words = " ".jo...
537e90638400c6c53b9fa82068f2c3dfbcaae179
640,113
def coding_problem_08(btree): """ A unival tree (which stands for "universal value") is a tree where all nodes have the same value. Given the root to a binary tree, count the number of unival subtrees. Example: >>> btree = (0, (0, (0, None, None), (0, (0, None, None), (0, None, None))), (1, None, N...
76ffd44b8483757c5e967ae70f6261d820f17ec2
640,115
def get_first_years_performance(school): """ Returns performance indicator for this school, as well as an indicator (1-5; 3 is average, 1 is worse, 5 is better) that compares the school to the national average. """ performance = {} ratio = school['renondb'].strip() # bolletje compare...
a5bd840059bfc423a9646e404a2e17829c14ce4c
640,117
from typing import List def prepend_escape_character(escape_character_list: List[str], keyword: str) -> str: """Add escape character. If the argument 'keyword' contains the characters specified in 'escape_character_list', an escape character is added to the target character. Args: escape_cha...
650d93053b01c1583a0af7498f5a8290556e4a21
640,118
def timetostr(dtime): """ Convert datetime into a string """ return dtime.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
d68933261615b4398667fea7ac2b180c7c4d96c2
640,119
def ngrams(input, n): """ Creates a set of strings with 'n' words :param input: The string to be split :param n: integer :return: set of strings with 'n' words """ input = input.split(' ') output = [] for i in range(len(input) - n + 1): output.append(input[i:i + n]) retu...
79b812393c5eaa6bf58eee334620eadee3bc71ae
640,120
def add2(x, y): """ Add up two numbers """ return x + y
a04a3ef369cf3734d88bd40beb7291427644c53d
640,121
def scale(v, num): """ :param v: The vector we want to scale :param num: Scale amount :return: vector scaled by num """ a, b, c = v return (a*num, b*num, c*num)
d5da3484e67443e1f1ec38ab73a41dacfc81691c
640,122
def has_cyber_observable_data(instance): """Return True only if the given instance is an observed-data object containing STIX Cyber Observable objects. """ if (instance['type'] == 'observed-data' and 'objects' in instance and type(instance['objects']) is dict): return Tru...
95851ddbaee6c9844412fd28fb85fdd8b0d5af67
640,124
def package_url(package_name): """Return fully-qualified URL to package on PyPI (JSON endpoint).""" return "https://pypi.python.org/pypi/%s/json" % package_name
8ecc47be770bd7108d0ca1e7f78348bfbfed9791
640,125
def factorial(num: int) -> int: """ >>> factorial(7) 5040 >>> factorial(-1) Traceback (most recent call last): ... ValueError: Number should not be negative. >>> [factorial(i) for i in range(10)] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] """ if num < 0: raise ...
9c5c7d9b963a67cae08355c61b0e83fb3e8aefe0
640,127
def sub_with_none(v1,v2): """ Substract treating None as zero """ p1 = v1 is None p2 = v2 is None if p1 and p2: return None elif p1: return -v2 elif p2: return v1 else: return v1 - v2
44df881adc0b1b464eb3b39907880f057a75debc
640,129
def make_depth_safe(cube): """ Make the depth coordinate safe. If the depth coordinate has a value of zero or above, we replace the zero with the average point of the first depth layer. Parameters ---------- cube: iris.cube.Cube Input cube to make the depth coordinate safe Ret...
06bb9ce9732a51337f7ccd758ffdb72a6cf765e7
640,130
def __access_member_by_string(x, member): """ Return the result of x.#member or x.#member() where member is the name of the function/variable. :param x: Element to operate on :param member: Function or value member :return: """ action = getattr(x, member) if callable(action): ...
20efb5e0eeccdfebb2a72a201732d24fa89472b3
640,135
def sponsors_benefit_is_complete(orm, sponsor, name): """Return True - benefit is complete, False - benefit is not complete, or None - benefit not applicable for this sponsor's level """ if orm.BenefitLevel.objects.filter(level=sponsor.level, benefit__name=name).exists(): try: ...
4be095eec96da78168d1dcabc6f60b4dabaf6e29
640,138
import json def transform_kval_json_str(st): """ BQ + python transforms hist `values` attribute from {"k": v} => [{'key': k, 'value': v}]. This undoes this. """ d = json.loads(st) values = d.pop("values") values_dct = {str(d["key"]): d["value"] for d in values} d["values"] = values...
cd468e7ed88edfb4b3ef655082c1f6da925e03bf
640,139
def overlap(a, b, min_length=3): """ Return length of longest suffix of 'a' matching a prefix of 'b' that is at least 'min_length' characters long. If no such overlap exists, return 0. """ start = 0 # start all the way at the left while True: start = a.find(b[:min_length], start) # look for b's suffx in a...
7c488fedb8be32174d55f6cd3ac572c4abd03f36
640,141
def halve_res_quick(array): """ Halves the resolution of the input 2D array, e.g. from 0.5km to 1km, by averaging every 2x2 grid of pixels into 1 pixel. :param array: 2D numpy array of data. :return: 2D numpy array with half the resolution of the input array. """ # Define ne...
23eadd26c2891852dfa776f2b894299fdaa188f3
640,142
def uniquify(s, delimiter=";"): """ Helper function It simplifies a delimited string with redundant fields if one unique field exist, a string is returned otherwise a list of the unique elements from the string is returned """ s = s.split(delimiter) s = list(set(s)) if len(s)==1: return s[0] ...
731c3b0fa4f77ff1b325906404363eaab9582090
640,144
def args_from_id(id, arg_ranges): """Convert a single id number to the corresponding set of arguments""" args = list() for arg_range in arg_ranges: i = id % len(arg_range) id = id // len(arg_range) args.append(arg_range[i]) return tuple(args)
32d696148ea8ff78f1db2b0a95cbe9c3c69ef79d
640,145
def extract_headers(event): """ Returns the headers from the request The format is: a dict of {name: value_list} where value_list is an iterable of all header values. Supports regular and multivalue headers. """ headers = event.get('headers') or {} multi_headers = (event.get('multiValueHea...
042258e528bf5172c06fedb01b3bb4a199657db4
640,146
def interval_overlap_length(i1,i2): """Compute the length of overlap of two intervals. Parameters ---------- i1, i2 : pairs of two floats The two intervals. Returns ------- l : float The length of the overlap between the two intervals. """ (a,b) = i1 (c...
a22fdd3cf76a503700055bc4077ef9584b6b394b
640,149
import base64 def _urlsafe_b64encode(s: bytes) -> bytes: """ Base 64 URL safe encoding with no padding. :param s: input str to be encoded :return: encoded bytes """ return base64.urlsafe_b64encode(s).rstrip(b"=")
50b007c54f516b4ccc3b48ca89b10bed3853517a
640,153
def myTwistFunction(Epsilon): """User-defined function describing the variation of twist as a function of the leading edge coordinate.""" RootTwist = 0 TipTwist = -2 return RootTwist + Epsilon * TipTwist
98531342166f17258357d08b468e90fd44127ecb
640,155
import re def as_size(size): """ Return a size string as an integer """ if isinstance(size, (int, float,)): return int(size) # exact size in a string m = re.match(r'^\d+$', size) if m: return int(size) # gigabytes m = re.match(r'^([\d\.]+)gb?$', size, flags=re.I) ...
267fc4b70e331200eb824d80187a59c86bd447a9
640,159
def thermal_time_constant_as_considered_load(TauR, dTOr, dTOi, dTOu, n): """ Returns the average oil time constant in minutes (for a given load) As per IEEE C57.91-2011 TauR = Thermal time constant at rated load dTOr = Top oil rise at rated load dTOi = Top oil rise initial dTOu = Top oil rise ul...
9412a33a04bee3b28b785e2c9965ffef81c92aaa
640,161