content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def op_to_dunder_unary(op: str) -> str: """Return the dunder method name corresponding to unary op.""" if op == '-': return '__neg__' elif op == '+': return '__pos__' elif op == '~': return '__invert__' else: return op
f0606c7d29a5295fe30f055b0dc0b324d58c6528
669,869
from typing import List def int_version(name: str, version: str) -> List[int]: """splits the version into a tuple of integers""" sversion = version.split('-')[0].split('+')[0].split('a')[0].split('b')[0].split('rc')[0] #numpy #scipy #matplotlib #qtpy #vtk #cpylog #pyNastran # '...
a9b0bd338526486b465379e131ebd0bfdacd306a
669,870
def is_natural_number(*arr): """Check if the numbers are natural number (includes zero). :param arr: number array :return: True if are natural number, or False if not """ for n in arr: if n < 0: return False return True
4a5f11a5249c60df37638f63b416c252d2841603
669,872
from typing import FrozenSet def _overlap(set_a: FrozenSet, set_b: FrozenSet) -> bool: """Return True if there are overlapping items in set_a and set_b, otherwise return False. # Passes as both sets have element 'b' >>> _overlap(frozenset({'a', 'b'}), frozenset({'b', 'c'})) True # Fails as there...
876ca5939750a6e50b9f5532a5d501f211cebde0
669,873
async def read_root(): """Displays greeting message in homepage Returns: dict: a dictionary with greeting message """ return {"message": "✌"}
0acf629d948ec362865d5db099aad4d7a80999bb
669,876
def prefix(text: str): # NOTE: PEP 616 solved this in python version 3.9+ """ Takes the first word off the text, strips excess spaces and makes sure to always return a list containing a prefix, remainder pair of strings. """ segmented = text.split(' ', 1) # ensure a list of 2 elements unpacked i...
b451af96350aff60da4ef5c3c25b2df2592f75cb
669,879
def ifexists(total_pages, page_no): """ This function checks whether the given page number is in the specified range of total pages. :param total_pages: :param page_no: :return: True or False """ if page_no <= total_pages: return False return True
5f1c9022b89e38488dce74138e8d8341a9f09f9d
669,886
def NoShifter(*args, **kwargs): """ Dummy function to create an object that returns None Args: *args: will be ignored *kwargs: will be ignored Returns: None """ return None
87c18ef0b4c0b4a17005c707ad17cd193ccd97b7
669,890
def hpa_to_mmhg(pressure: int) -> int: """ Converts pressure in hpa to mmhg Args: pressure: pressure to convert Returns: pressure in mmhg """ return int(pressure * 0.75006156130264)
b8431e4f141cb1609b9ffceffd17ab4369439cd1
669,895
def unemployment_rate(earning, earning_new, unemployment): """ Args: earning: how much money the player earned last round earning_new: how much money the player earned this round unemployment: unemployment rate of the player had last round Returns: unemplo...
25f671212bc9b428a8c52f88a575ea36e1fc0178
669,897
from typing import Any def verify_assign_and_read(obj: Any, attr: str, value: Any) -> Any: """ Assign value to attribute, read and return result. Assert that values can be mutated and read before and after mutation. """ try: setattr(obj, attr, value) except AttributeError: rai...
b7ae561c3cee9d9f379a6c0883a6f3bdb5861768
669,900
import tqdm def find_stable_phases(all_compounds, criteria): """ find all compounds with e_above_hull within given range of zero args: all_compounds - returned from load_compounds (list of dicts) criteria - criteria for a stable phase in meV output: list of dicts of stable phas...
6ac9815b0b175536add3aba8ab43f592a3c21de3
669,901
def parse_channal_response(channel=dict()): """ Parse channel dict to extract key metadata, including: id, title, description, viewCount, videoCount, subscriberCount :param channel: a dictionary containing all metadata of a channel :return: """ result = {} result['id'] = channel['id'] ...
595c0fd592707eeee873c68ec5a5fa31c26816f3
669,902
import torch def azimuthal_average(image, center=None): # modified to tensor inputs from https://www.astrobetter.com/blog/2010/03/03/fourier-transforms-of-images-in-python/ """ Calculate the azimuthally averaged radial profile. Requires low frequencies to be at the center of the image. Args: ...
a40754537a58f07cf99f6b207be8a7f95d258c9f
669,904
def has_diff_value(dict_obj, key, value): """Returns True if dict_obj contains key, and its value is something other than value.""" return key in dict_obj and dict_obj[key] != value
d42a1dcde846ed0e615a0ad312355900cf3a0841
669,906
import re def isolate_punctuation(text): """ Isolate punctuation in a sentence. >>> split_punctuation('Hi there!') 'Hi there !' Args: text (str): Input sentence Returns: str: Output sentence with isolated punctuation """ text = re.sub('([.,!?()])', r' \1 ', text) tex...
381d2785f6f01a29afb4406c2240afd06a3b3ef9
669,908
def integral(shift, op, elements, accumulator): """ Inverse of derivative. Scans a list of elements using an accumulator. Returns the integral of the elements and the final state of the accumulator. ---------- shift : Shift of -1 is an exclusive scan and a shift of 1 is an inclusive scan. op : Opera...
67acc6fd66f5f2b6b3992dba999f485f05aeb4f3
669,909
def get_scaled(x, y, radius, image): """Scales x y and raius whose values are from 0 to 1 to int values.""" scaled_x = int(x*image.shape[1]) scaled_y = int(y*image.shape[0]) scaled_radius = int(radius*max(image.shape[1], image.shape[0])) return (scaled_x, scaled_y, scaled_radius)
a22776399beebb279ef07956f4ab6f318a81495b
669,911
import fnmatch def filename_match(filename, patterns, default=True): """Check if patterns contains a pattern that matches filename. If patterns is not specified, this always returns True. """ if not patterns: return default return any(fnmatch.fnmatch(filename, pattern) for pattern in patt...
42572c4d9c4b1e21f751be87dfab53fec87b891e
669,917
import math def truncate_floor(number, decimals): """Truncates decimals to floor based on given parameter Arguments: number {float} -- number to truncate decimals {int} -- number of decimals Returns: float -- truncated number """ return math.floor(number * 10 ** decimals)...
3f172b9947635662b59f2c5f31abb2cc13e31882
669,921
import random def convkey(x, left=False, right=False): """Turns a numerical salary value into a string preserving comparison.""" assert not (left and right) if left: appendix = '0' elif right: appendix = '9' else: appendix = '5' appendix += ''.join(chr(random.randrange(...
20b70b136caeed484ddbaa3d0b7f7691b8f38318
669,924
def _return_features(data, features): """Select specific raw features from the data :param data: The data set to manipulate. :param features: A list of ISXC 2012 IDS specific features. :return: List of data with just the chosen features in the order they were requested. """ process...
921ca5eaa514e19a0d97a3522f70b3c9297a440f
669,925
def return_module(module): """Mock for importlib.reload(). Returns argument.""" return module
b132269774d6faa0924fec264f756cd67b0b9c1b
669,927
def predict_proba_model(model, X_score): """Uses a trained scikit-learn model to predict class probabilities for the scoring data""" return model.predict_proba(X_score)[:, 1]
e1cde41ac300e49814b747749064bbc1d1c3a5a6
669,928
import pytz def localize_date(date, city): """ Localize date into city Date: datetime City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'.. """ local = pytz.timezone(city) local_dt = local.localize(date, is_dst=None) return local_dt
1b07cbe5abfe6f391d9c981002227e68120c43ac
669,932
def set_common_keys(dict_target, dict_source): """ Set a dictionary using another one, missing keys in source dictionary are reported""" keys_missing=[] for k in dict_target.keys(): if k in dict_source.keys(): dict_target[k]=dict_source[k] else: keys_missing.append(k)...
5bd4e6f53c1b6991b458c6140ed927be4866a93e
669,936
import torch def accuracy(logits, labels): """ Compute accuracy of given forward pass through network. Parameters: - - - - - logits: torch tensor output of single network forward pass labels: torch tensor ground truth class of each sample Returns: - - - - float s...
a9a5e4e298a1f20ae065dda3deb873fd3b77ca42
669,938
import random def duplicate(row, n=5): """ Duplicates (augments) the row by modifying the sale price :param row: pandas series :param n: how many duplicates to return :return: duplicates in list """ price = row['sales.price'] lower, higher = price * 0.9, price * 1.1 dupe_list = [] ...
ea80b5ae5c308e1260c153eb46b9c17bae376e80
669,941
def get_gtf_chromosomes(gtf_fn): """Return a set of chromosomes in gtf""" chrs = set() with open(gtf_fn, 'r') as reader: for line in reader: if line.startswith('#') or len(line.strip()) == 0: continue else: chrs.add(line.split('\t')[0]) ret...
23ca548068d29ed2c6d98f38f3a7be857582445d
669,942
def _adjmatType(adjMat): """(helper function) retruns <class 'int'> if the adjacency matrix is a (0,1)-matrix, and returns <class 'list'> if the adjacency matrix contains edge weights, and returns None if neither of the cases occurs. Args: adjMat (2D - nested - list): the adjacency matrix. ...
f57e3a97c6d759a564bcf0e546c67ee975caf4c7
669,943
def get_user_article_choice() -> int: """ Get user's choice on which article they want to view. :precondition: User's input must be an integer :postcondition: Successfully return user's input as an integer :return: User's choice of article number as an integer """ # Loop until there is val...
7f04ce42b7a673019f0ebd48fec426b443e8295a
669,946
from typing import List from typing import Optional import bisect def get_bucket(seq_len: int, buckets: List[int]) -> Optional[int]: """ Given sequence length and a list of buckets, return corresponding bucket. :param seq_len: Sequence length. :param buckets: List of buckets. :return: Chosen buck...
8a5db6dda3b87e015a0abdb1b4a380ed22df38b9
669,947
def Quantity(number, singular, plural=None): """A quantity, with the correctly-pluralized form of a word. E.g., '3 hours', or '1 minute'. Args: number: The number used to decide whether to pluralize. (Basically: we will, unless it's 1.) singular: The singular form of the term....
b206fca427a5674cd09d8fc334e1a00c54aa2cdd
669,952
from typing import List def smart_join(elements: List[str], sep: str) -> str: """ Uses regular join after filtering null elements from the initial list Parameters ---------- elements : List[str] list of /possibly null/ strings to join sep : str joining delimiter Returns ...
26e8ec7bea41ae6292fce7730003907643dec17a
669,954
def obscure_string(input_string): """ Obscures the input string by replacing all but the last 4 characters in the string with the character '*'. Useful for obscuring, security credentials, credit card numbers etc. Args: input_string A string of characters Returns: A new string where all but the l...
fd49f289fe6ae3fd1f7be73fcacdc968f5c47cf3
669,958
def WignerHsize(mp_max, ell_max=-2): """Total size of array of wedges of width mp_max up to ell_max Parameters ---------- ell_max : int mp_max : int, optional If None, it is assumed to be at least ell See Also -------- WignerHrange : Array of (ℓ, m', m) indices corresponding to...
0a2fd8618dd2099c09cbf1045aa2f5b52deb9ca1
669,960
def convert_spreadsheet_to_unix(val): """ This function converts a date from an Excel spreadsheet (which is an integer) into the number of seconds since the Unix epoch (which is also an integer). """ # Return answer .. return 86400 * (val - 25569)
134baa086389f7b4f76c4cbfb2f5037f83e08793
669,963
def compute_distribution_bounds(history, parameter, alpha, run): """Returns distribution bounds from pyabc posterior distribution. Parameters ---------- history : pyabc.smc An object created by :func:`pyabc.abc.run()` or :func:`respyabc.respyabc()`. parameter : str Paramete...
af4726d07210108340cea7c6335ec99a0c40cdb1
669,964
def balanced_eq(x, z, y): """Gradient of the max operator with tie breaking. Args: x: The left value z: The maximum of x and y y: The right value Returns: The gradient of the left value i.e. 1 if it is the maximum, 0.5 if they are equal and 0 if it was not the maximum. """ return (x == z...
896ce734e43dafd3c5084bc623b329bbc5a3b1f9
669,965
def unwrap(url): """Transform a string like '<URL:scheme://host/path>' into 'scheme://host/path'. The string is returned unchanged if it's not a wrapped URL. """ url = str(url).strip() if url[:1] == '<' and url[-1:] == '>': url = url[1:-1].strip() if url[:4] == 'URL:': url = url...
84510be907f933212b5f6747cc8d6635b72ad38b
669,971
def repr_dict(dict_obj): """Human readable repr for a dictonary object. Turns a dict into a newline delimited string. Intended use is for loading up sample specifications into the starting buffer of an editor :param dict_obj: type dict dictionary to format""" res = '' for k, v in dict_obj.iteritems...
085dabfde3c19712049a157cbea38ec64302ab93
669,974
from bs4 import BeautifulSoup import requests def fetch(session, url): """ Fetch a URL and parse it with Beautiful Soup for scraping. """ return BeautifulSoup(requests.get(url, stream=False).text, "html.parser")
7fb0c0dc01dcc021c50e7e7648febcf3d522fcec
669,975
import torch def get_simple_trajopt_cost(x_dim, u_dim, alpha_dim, dtype): """ Returns a set of tensors that represent the a simple cost for a trajectory optimization problem. This is useful to write tests for example @return Q, R, Z, q, r, z, Qt, Rt, Zt, qt, rt, zt where min ∑(.5 xᵀ[n] Q ...
fcbff16048c0d39d2cae71c15347ab2fedea1b11
669,976
def _range_representer(representer, node: range): """Represents a Python range object using the ``!range`` YAML tag. Args: representer (ruamel.yaml.representer): The representer module node (range): The node, i.e. a range instance Returns: a yaml sequence that is able to recreate a...
ac1cb8481d3eb3251303d87681de7ca5ebb12513
669,978
import pathlib import tempfile import zipfile def extract_archvie(archive_path: pathlib.Path) -> pathlib.Path: """ Extract a user data archive to a temporary directory. If the user supplied a path to an already unzipped archive, this is a no-op and will return the same path. Otherwise, the archive is...
b122f47225f25a644295011fdf6d46730acd07be
669,981
def return_characters(data: bytes) -> bytes: """ Characters that are used for telegram control are replaced with others so that it is easier to parse the message over the wire. Final character is never replaced. This function returns them to their original form. '\x1b\x0e' -> '\x0d' '\x1b\x...
20e633f6a9757595f3b19ac82d2d51feac95ffa9
669,987
def calculate_separate_operator_conditionals(expression: str) -> int: """Return the evaluation of the given infix arithmetic expression Note: integer division should truncate toward zero. Args: expression: A valid infix arithmetic expression containing only digits and operators in '+', '-'...
ffd3a75247d128eeb16c0b9cffef28597d014d80
669,988
def get_final_ranks(rank_probs): """Orders final rank probabilities into a list and trims decimal places. """ ranks = [] for team, prob_dict in sorted(rank_probs.items(), key=lambda x: -sum([i*p for i,p in enumerate(x[1].values())])): ranks.append({"team": team, "prob...
887da4da34574c3c966545d0781aca8cfb8131bd
669,990
def _sort_by_fitness(parameters, fitness): """Given a parameters and fitness array, returns the same arrays but sorted in ascending order of the fitness. Args: fitness (numpy array): As a numpy array, the values for the fitness. parameters (numpy array): As a numpy array, the values for the...
521c2b3425d39e4f23ff7902f94c0456bb60e930
669,992
from pathlib import Path import yaml def load_game_reource(game_tag: str, filename: str) -> dict: """Return specific game resource from `{filename}.yml` file.""" path = Path(f"incarn/resources/games/{game_tag}/{filename}.yml").read_text("utf8") return yaml.load(path, Loader=yaml.FullLoader)
74ec91e0a48f1f6b6ad2bcf44879ed77cb32eaa5
669,993
def _index_story(stories, title): """Returns index of title in story list returns -1 if not found Arguments: stories [Story] -- List of stories (Story) title str -- Story title to look for in list """ for i, story in enumerate(stories): if story == title: ret...
a924a600fae37b7de08eb7f6acc991b3401a5791
669,994
import math def principal_value(angle_in_radians: float) -> float: """ Ensures the angle is within [-pi, pi). :param angle_in_radians: Angle in radians. :return: Scaled angle in radians. """ interval_min = -math.pi two_pi = 2 * math.pi scaled_angle = (angle_in_radians - interval_min) ...
6fc57322bbe9c44b838bfdb4d9eb191d3c07faed
669,996
def desc_sort_list(list, key): """desc sort list of dicts for a given key.""" return sorted(list, key=lambda kev: kev[key], reverse=True)
ad89fe00334ffb15d3b2cc50893f207ab64dfaf7
669,997
import torch def to_onehot(target: torch.Tensor, num_classes: int) -> torch.Tensor: """ Convert given target tensor to onehot format :param target: `LongTensor` of `BxCx(optional dimensions)` :param num_classes: number of classes :return: """ size = list(target.size()) size.insert(1, num...
de12f78d4d1f29ea351da701bde10c7c5fb63592
670,000
import torch def dihedral( x0: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor, x3: torch.Tensor ) -> torch.Tensor: """Dihedral between four points. Reference --------- Closely follows implementation in Yutong Zhao's timemachine: https://github.com/proteneer/timemachine/blob/1a0ab45e605d...
50bce697366bf11dc4df23e45f18519d7f28cc6f
670,002
def conv2d(obj, filt): """ 2-D spatial convolution of an `Image` or `ImageCollection`. Parameters ---------- obj: `Image` or `ImageCollection` Object to convolve over filt: `Kernel` object Kernel object to convolve Example ------- >>> from descarteslabs.workflows im...
d24494baec44ada81f2bc5276e8c08b48baeaadc
670,003
from typing import Callable from typing import Any def to_string_gen(gen) -> Callable[[Any], str]: """ Accepts a string or a function that returns a string and returns a function that returns a string :param gen: either the string to be returned or a generator that accepts an element and returns a string...
411ab7a0c53dbdbe0489be1929d188692ae9bfab
670,005
def switchAndTranslate(gm1, gm2, v1, v2, wrapModulo): """ Transforms [v1,v2] and returns it such that it is in the same order and has the same middle interval as [gm1, gm2] """ assert(v1 < v2) # keep the same middle of the interval if (wrapModulo): gmMiddle = float(gm1 + gm2) / 2...
dd9ad5823d7e99a1ec22e55c46d8ec0040b5268b
670,006
def form_intro(pol_areas, description=None): """ Form the introduction line Parameters ---------- pol_areas: list of all the policy areas included in the reform used to create a description of the reform description: user provided description of the reform """ # these are all of...
79fbb4e30dcf3ffc31f1fb8924fa94db442e30ab
670,007
import struct def get_vbmeta_size(vbmeta_bytes): """Returns the total size of a AvbVBMeta image.""" # Keep in sync with |AvbVBMetaImageHeader|. AVB_MAGIC = b'AVB0' # pylint: disable=C0103 AVB_VBMETA_IMAGE_HEADER_SIZE = 256 # pylint: disable=C0103 FORMAT_STRING = ( ...
a863c4ca5e96d78deb401c962563c2de41187ae9
670,009
from datetime import datetime def get_current_month_name(month=None): """ get the current month name. if month is given then get the name of that month otherwise get this month name """ current_date = datetime.now() if month is not None: current_date = datetime(current_date.ye...
2bd07616aa517fe3c86b41c09e0dc469023900a6
670,012
def _compute_delta_t( data: dict, nodeid: str, event1: str, event1_pos: int, event2: str, event2_pos: int) -> float: """Compute time delta between two events :param dict data: data :param str nodeid: node id :param str event1: event1 :param int event1_pos: event1 position in stream ...
b8496b63c9dc93e3e9070c3c4ec89ca445a88dee
670,013
def interpolate(a0, a1, w): """ Interpolate between the two points, with weight 0<w<1 """ # return (a1 - a0) * w + a0 # Can make this smoother later return (a1 - a0) * ((w * (w * 6.0 - 15.0) + 10.0) * w * w * w) + a0
7de0195079fa95fdb4b9a8001f2076edc63cda2e
670,016
def time2str(time): """ returns utc time as hh:mm string """ minute = '0'+str(time.minute) if time.minute < 10 else str(time.minute) return str(time.hour)+':'+minute
382d73bb2b6d8951331e1396f30e0452eed6fe2b
670,018
import torch def argmin(x): """Deterministic argmin. Different from torch.argmin, which may have undetermined result if the are multiple elements equal to the min, this argmin is guaranteed to return the index of the first element equal to the min in each row. Args: x (Tensor): only supp...
6ff5546b96b964c93d92a1b2d507e5ada703c2fc
670,020
import json def buildJson(self, fields, values): """ Builds json :param fields: fields for json :param values: values for fields in json :return: json """ i = 0 data = {} for field in fields: data[field] = values[i] i += 1 json_data = json.dumps(data) retur...
6be7c05665b83eb6155ddc2eeb5a14179a0dc31a
670,022
def restore_field_information_state(func): """ A decorator that takes a function with the API of (self, grid, field) and ensures that after the function is called, the field_parameters will be returned to normal. """ def save_state(self, grid, field=None, *args, **kwargs): old_params = g...
d22c99d3b6aa6e7634f18c200a4c00585dbd5352
670,024
def get_list_subsets(object_list, subset_size): """ Breaks a larger list apart into a list of smaller subsets. :param object_list: The initial list to be broken up :param subset_size: The maximum size of the smaller subsets :return: A list of subsets whose size are equal to subset_size. The last sub...
09030c6fa6a8948ab809cea93261c67f8b77ccd4
670,026
import math def keypoint_rot90(keypoint, factor, rows, cols, **params): """Rotates a keypoint by 90 degrees CCW (see np.rot90) Args: keypoint (tuple): A keypoint `(x, y, angle, scale)`. factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image heigh...
f95f28fdca73f453ffe84e382f70fd5df619c1b5
670,027
def class_to_fqn(cls): """Returns the fully qualified name for cls""" return '%s.%s' % (cls.__module__, cls.__name__)
f7868a8c1cff11be01636a87914aa49c799f013a
670,029
def seqcomp(s1, s2): """ Compares 2 sequences and returns a value with how many differents elements they have. """ p = len(s1) for x,y in zip(s1, s2): # Walk through 2 sequences. if x==y: p -= 1 return p
1ef0e7fddc751225ba2030804b360daf8bf10abd
670,035
import torch def abs2(x: torch.Tensor): """Return the squared absolute value of a tensor in complex form.""" return x[..., -1] ** 2 + x[..., -2] ** 2
186387791dec899a775dc6d3bbb1987a5433898f
670,036
def get_features(words, word_features): """ Given a string with a word_features as universe, it will return their respective features : param words: String to generate the features to : param word_features: Universe of words : return: Dictionary with the features for document string """ ...
a78bd6a83b9b3ea340a22c8696778b289539dd78
670,041
def clip_box(box, shape): """ Clip box for given image shape. Args: box (array_like[int]): Box for clipping in the next format: [y_min, x_min, y_max, x_max]. shape (tuple[int]): Shape of image. Returns: array_like[int]: Clipped box. """ ymin, xmin, ymax, xm...
7cb329c630dc5eef47e87a8e32dab4d5a97739ae
670,044
def get_embedding_dict(filename): """ Read given embedding text file (e.g. Glove...), then output an embedding dictionary. Input: - filename: full path of text file in string format Return: - embedding_dict: dictionary contains embedding vectors (values) for all words (keys) """ ...
07d5501c1eb71114488af913d012d2511f4a5439
670,051
def week_cal(cal: str, current_day: int) -> str: """Function used to transform a HTML month calendar into a week calendar. Args: `cal`(str): the html calendar to transform. `current_day`(int): the current day to select the current week. Returns: `str`: the calendar transformed. ...
11cad36d9c92e38f10152b2c97039a9d5d16c344
670,052
def check_unique_scores(score_list): """Method that checks if the scores presented are unique. Returns true if only unique, false if there are duplicates""" return len(score_list) == len(set(score_list))
7e8aad11e8680a3c6339283a191227647095e643
670,057
def ReadFile(filename): """Returns the contents of a file.""" file = open(filename, 'r') result = file.read() file.close() return result
3d8700a50a511c578902142519011d6adf2ddded
670,058
def _subsample(name, indices, doc=""): """Create an alias property for slices of mesh data.""" def get(self): return self.vectors[indices] def set(self, value): self.vectors[indices] = value get.__name__ = name return property(get, set, None, doc)
be10649e75823da2b89a4fd01227d32b9535cf40
670,060
import requests import json def CoinNames(n=None): """Gets ID's of all coins on cmc""" names = [] response = requests.get("https://api.coinmarketcap.com/v1/ticker/?limit=0") respJSON = json.loads(response.text) for i in respJSON[:n]: names.append(i['id']) return names
206246314b8dab7c5d86ba6109a59e9060ad1ffa
670,062
def dot(a, b): """The dot product between vectors a and b.""" c = sum(a[i] * b[i] for i in range(len(a))) return c
5ba6e253a2408c79c9f1edd0e98a84904e966050
670,064
def extract_ligand_residues( pdb_hierarchy, ligand_code, atom_selection=None, only_segid=None): """ Extract the atom_group object(s) with given 3-character residue name. :param pdb_hierarchy: input model :param ligand_code: 3-letter residue ID :param atom_selection: optional flex.bool object ...
64442c29db5204c7b3510fd773638d4408c84722
670,065
import pickle def read_Docs(path): """ This function will return a list which includes documents as string format. Parameters: path: path for the pickle file we will provide. """ with open(path,'rb') as P: Docs = pickle.load(P) return Docs
e6209add58a8067430e0308f0cb24a04449f99f0
670,066
def molar_concentration_water_vapour(relative_humidity, saturation_pressure, pressure): """ Molar concentration of water vapour :math:`h`. :param relative_humidity: Relative humidity :math:`h_r` :param saturation_pressure: Saturation pressure :math:`p_{sat}` :param pressure: Ambient pressure :m...
e5d8a416bb1a598f84d9749c95cbb9d08013b805
670,072
def mean(values): """ Compute the mean of a sequence of numbers. """ return sum(values)/len(values)
d474df419d99a9de5d142284f5faa4a8e862d8e3
670,073
def build_dir_list(project_dir, year_list, product_list): """Create a list of full directory paths for downloaded MODIS files.""" dir_list = [] for product in product_list: for year in year_list: dir_list.append("{}\{}\{}".format(project_dir, product, year)) return dir_list
38683b30fac0b944f17a27351384066670afda11
670,074
def str_to_bool(s): """ Convert multiple string sequence possibilities to a simple bool There are many strings that represent True or False connotation. For example: Yes, yes, y, Y all imply a True statement. This function compares the input string against a set of known strings to see if it ...
b7483c833a62a39df852bdafc0a02b106f22d7a3
670,076
import six def optionalArgumentDecorator(baseDecorator): """ This decorator can be applied to other decorators, allowing the target decorator to be used either with or without arguments. The target decorator is expected to take at least 1 argument: the function to be wrapped. If additional argume...
f018db3ed927e33640ad2b4b570f9fd374834164
670,077
def unit_can_reach(unit, location): """ Return whether a unit can reach a location. Arguments: unit: the unit location: the location Returns: whether the unit can reach the location """ x, y = location return unit.partition[y][x]
6597ca30ea1041fd3f6dadf0f1f5e6e5b5ad2ae8
670,080
def smallest_square(n: int): """ returns the smallest int square that correspond to a integer example: smallest_square(65) returs 8 (8*8 = 64) """ n = abs(n) i = 0 while i**2 <= n: i += 1 if n - (i-1)**2 < i**2 - n: return i - 1 else: return i
c7c8d80d9cf70ac2a1e9c87ddaf2fb651307d763
670,082
from typing import List def split_lines(*streams: bytes) -> List[str]: """Returns a single list of string lines from the byte streams in args.""" return [ s for stream in streams for s in stream.decode('utf8').splitlines() ]
78104f09d44f7998035d37abc8dc80a2dc8c9385
670,083
def get_pred_text(eval_dict, example_ids, pred_starts, pred_ends, probs, use_official_ids=False): """Get text of predicted answers for a number of predicted starts, ends, and the corresponding example_ids. If use_official_ids is True, the returned dictionary maps from official UUIDs to predicted (answer text, p...
7651c651065a2f4b12fbc54b5b0e0426c9fcb8d8
670,085
import math def time_since(s): """compute time Args: s (float): the amount of time in seconds. Returns: (str) : formatting time. """ m = math.floor(s / 60) s -= m * 60 h = math.floor(m / 60) m -= h * 60 return '%dh %dm %ds' % (h, m, s)
87a3411515350d3d802df0e13532c2120736bd5b
670,086
def _get_euclidean_dist(e1, e2): """Calculate the euclidean distance between e1 and e2.""" e1 = e1.flatten() e2 = e2.flatten() return sum([(el1 - el2) ** 2 for el1, el2 in zip(e1, e2)]) ** 0.5
c29777c9f17a099d97984711f2f5d261c86276da
670,088
def is_block_structure_complete_for_assignments(block_data, block_key): """ Considers a block complete only if all scored & graded leaf blocks are complete. This is different from the normal `complete` flag because children of the block that are informative (like readings or videos) do not count. We on...
5974bef0449b019a68092a1e630bb4395513d270
670,090
import torch def log_density(x: torch.Tensor) -> torch.Tensor: """Computes the density of points for a set of points Args: x (torch.Tensor): set of points (N x D) Returns: torch.Tensor: density in # points per unit of volume in the set """ hypercube_min, _ = torch.min(x, dim=0) ...
237981f584b1f7f2db5ccd38b80e13b57b688b61
670,092
def unit_step(t): """ Takes time as argument and returns a unit-step function """ return 1*(t>=0)
3fc46c615250c905e3cb2f816550aaf435862427
670,093
def substitute(arg, value, replacement=None, else_=None): """ Substitute (replace) one or more values in a value expression Parameters ---------- value : expr-like or dict replacement : expr-like, optional If an expression is passed to value, this must be passed else_ : expr, optional...
6f3d8e0e72dc16c15cbb0c769d5bb1b14f17df27
670,098
def delete_elem(s, elem): """delete a item in set""" r = set(s) r.remove(elem) return r
7ec9d60a3e08a6279a9408bd521329db87b1506e
670,099
def readMDL(filename): """ Read the MDL file in ASCII and return the data. """ filehandle = open(filename,'r') data = filehandle.read() filehandle.close() return data
53a190912e7c0a3ad78706cdbc7b7a95981ecbd5
670,100