content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import operator def filter_prefix(candidates: set[str], prefix: str = '', ones_operator=operator.ge) -> int: """Filter a set of binary number strings by prefix, returning a single int. This function considers a set of candidate strings, which must encode valid binary numbers. They are iteratively filtere...
32480781186e0c347c954c3b63dc988274fb4f8d
676,828
import torch def precisionk(actual, predicted, topk=(1, 5)): """ Computes the precision@k for the specified values of k. # Parameters actual : `Sequence[Sequence[int]]`, required Actual labels for a batch sized input. predicted : `Sequence[Sequence[int]]`, required Predicted labels f...
1cb21a572b46f8f35396efb4e79df09ae51ebbfa
676,829
def image_size(img): """ Gets the size of an image eg. 350x350 """ return tuple(img.shape[1:: -1])
6df3b7cf05f6388930235603111572254fa89c10
676,832
def revcomp(s): """Returns the reverse compliment of a sequence""" t = s[:] t.reverse() rc = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N'} t = [rc[x] for x in t] return t
f0378f8595e6902bed46bda0b8689f34df34f07f
676,834
def relu(x, c = 0): """ Compute the value of the relu function with parameter c, for a given point x. :param x: (float) input coordinate :param c: (float) shifting parameter :return: (float) the value of the relu function """ return c + max(0.0, x)
b25cda42282ab723fa4448d378ece0f6519c1e2e
676,838
from pathlib import Path def is_notebook(path: Path) -> bool: """ Checks whether the given file path is Jupyter Notebook or not. Parameters ---------- path: Path Path of the file to check whether it is Jupyter Notebook or not. Returns ------ Returns True when file is Jupyter N...
b1400fb72af69204d62ef81f6abaa13a6859ba5a
676,850
def is_highlighted_ins(e): """Returns True if e matches the following pattern: <ins>highlighted</ins> text: See `fragment_chunks` comment for the details """ if len(e) != 0: return False if not e.text: return False if e.text != 'highlighted': return False i...
e5d60aef35f3085f3105fc23d3420200e36341bf
676,851
async def admin(mixer): """Generate an admin user.""" admin = mixer.blend('example.models.User', email='admin@example.com', is_super=True) admin.password = admin.generate_password('pass') return await admin.save(force_insert=True)
6c51b6849d5ae0dbbaac6e1efd53f0766ebf96fb
676,853
def bw24(x): """Return the bit weight of the lowest 24 bits of x""" x = (x & 0x555555) + ((x & 0xaaaaaa) >> 1) x = (x & 0x333333) + ((x & 0xcccccc) >> 2) x = (x + (x >> 4)) & 0xf0f0f return (x + (x >> 8) + (x >> 16)) & 0x1f
72ec0e3f920c79f37e2dd3cbd571e6bfe07eb92e
676,854
def project_data(samples, U, K): """ Computes the reduced data representation when projecting only on to the top "K" eigenvectors """ # Reduced U is the first "K" columns in U reduced_U = U[:, :K] return samples.dot(reduced_U)
a955adeaa6b45fd3d46cc3866e6acf414769692c
676,857
def ROStime_to_NTP64(ROStime): """ Convert rospy.Time object to a 64bit NTP timestamp @param ROStime: timestamp @type ROStime: rospy.Time @return: 64bit NTP representation of the input @rtype: int """ NTPtime = ROStime.secs << 32 # NTPtime |= nanoseconds * 2^31 / 1x10^9 NTPtime |= i...
4f0cb267ce37fee3671a705ff292c31c6d7e3f28
676,860
def reverse_dict(dictionary): """Reverse a dictionary. Keys become values and vice versa. Parameters ---------- dictionary : dict Dictionary to reverse Returns ------- dict Reversed dictionary Raises ------ TypeError If there is a value which is un...
f904adeee1e6ed25995d16a080c557dcbea5fa1e
676,866
def expp_xor_indep(p1, p2): """ Probability of term t1 XOR t2 being 1 if t1 is 1 with p1 and t2 is 1 with p2. t1 and t2 has to be independent (no common sub-term). Due to associativity can be computed on multiple terms: t1 ^ t2 ^ t3 ^ t4 = (((t1 ^ t2) ^ t3) ^ t4) - zipping. XOR: a b | r ...
d1f59639472c25d257776a8e8a420856e38cfdd8
676,869
def noOut(_): """Outputs nothing.""" return None
2eff0768a4861b023fa055b0a34c1ffae6988740
676,870
import torch def conv3x3(in_channel, out_channel, stride=1, padding=1,dilation=1, bias=True): """3x3 convolution with padding""" return torch.nn.Conv2d(in_channel, out_channel, kernel_size=(3,3), stride=(stride,stride), ...
f8eb7ceb844dd9527c9159e17209fbd547fc7dd9
676,871
def length_of_range(range): """Helper- returns the length of a range from start to finish in ms""" return range[1] - range[0]
d4a3a423c85310d3d679ffe97fc37ff88f406c7c
676,872
def listify(x, none_value=[]): """Make a list of the argument if it is not a list.""" if isinstance(x, list): return x elif isinstance(x, tuple): return list(x) elif x is None: return none_value else: return [x]
3382cf9389815737085d58d000c454e56b0ca906
676,873
def unique(iterable): """Return an iterable of the same type which contains unique items. This function assumes that: type(iterable)(list(iterable)) == iterable which is true for tuples, lists and deques (but not for strings) >>> unique([1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 1, 1, 2]) [1, 2, 3, 4] ...
c65a7e4f75d9678e28e70e4a1a2b2679a02bab8d
676,879
def qc_syntax_test(self): """ It verifies that wf.data contains the recomentated data structure to pass the rest of the QC test. Each parameter (for example, TEMP) and each index (for example, TIME) must have a column with the flags of the values (for example, TEMP_QC and TIME_QC). Returns ...
e151f3e407dcc43096903f82f5a15d614f6a4b2a
676,880
def modified(number, percent): """return the amount (or any other number) with added margin given by percent parameter (result has type float) """ if percent: return number * (100 + percent) / 100. else: return float(number)
7421d717caed71da840d0bae644a1f95d517777b
676,881
def print_bytearray(array: bytearray) -> str: """Outputs string of all bytes in HEX without any formatting. Parameters ---------- array : byte array The byte array to be printed. Returns ------- str A string representation of the byte array in HEX format. """ string...
1f672598153f676169d93c330e16c591794651b3
676,882
def get_row_nnz(mat, row): """Return the number of nonzeros in row. """ return mat.indptr[row+1] - mat.indptr[row]
a588e245763eb1cd237c9d2f71efacd7b27387c8
676,884
import torch def zero_out_col_span(xfft, col, start_row, end_row=None): """ Zero out values for all data points, channels, in the given column and row span. :param xfft: input complex tensor :param col: the col number to zero out value :param start_row: the start row (inclusive, it is zeroed ...
5a17aeb49abaee53c19cf8451657e13def7cc7eb
676,890
def weWantThisPixel(col, row): """ a function that returns True if we want # @IndentOk the pixel at col, row and False otherwise """ if col%10 == 0 and row%10 == 0: return True else: return False
7dfd084e845df8c927a31d9565ba386ed9132e1b
676,895
import calendar def date_to_dow(y, m, d): """ Gets the integer day of week for a date. Sunday is 0. """ # Python uses Monday week start, so wrap around w = calendar.weekday(y, m, d) + 1 if w == 7: w = 0 return w
2598df93dbf1b36f93af2b6e26f522cd6f60d328
676,903
def hi_to_wbgt(HI): """ Convert HI to WBGT using emprical relationship from Bernard and Iheanacho 2015 WBGT [◦C] = −0.0034 HI2 + 0.96 HI−34; for HI [◦F] Args: HI = heat index as an array """ WBGT = -0.0034*HI**2 + 0.96*HI - 34 return WBGT
f34a646a89b3da6d4fa2c068e4142ab86753aa9b
676,905
def shimbel(w): """ Find the Shimbel matrix for first order contiguity matrix. Parameters ---------- w : W spatial weights object Returns ------- info : list list of lists; one list for each observation which stores the shortest order between i...
86da578da800bb719d709bf31d9ffcc27aa19074
676,909
def counts_to_probabilities(counts): """ Convert a dictionary of counts to probalities. Argument: counts - a dictionary mapping from items to integers Returns: A new dictionary where each count has been divided by the sum of all entries in counts. Example: >>> counts_to_prob...
92974f6dafa0222995a77c336ab884fc34586dd3
676,914
def array_set_diag(arr, val, row_labels, col_labels): """ Sets the diagonal of an 2D array to a value. Diagonal in this case is anything where row label == column label. :param arr: Array to modify in place :type arr: np.ndarray :param val: Value to insert into any cells where row label == column l...
f4248a46253080407f2f6b569f99faf9a896937b
676,915
import json def _format_modules(data): """Form module data for JSON.""" modules = [] # Format modules data for json usage for item in data: if item.startswith('module_'): val_json = json.loads(data[item]) modules.append(val_json) return modules
1bc2cb303b1a1c116d33ed862006e99e8a378535
676,916
def get_sparkconfig(session): """ Returns config information used in the SparkSession Parameters ---------- session : SparkSession Returns ------- dict : Dictionary representing spark session configuration """ conf = session.sparkContext.getConf().getAll() return conf
147dec4dbe21781d0fff6e1484e3f3c8e35821eb
676,919
def stride_chainid_to_pdb_chainid(stride_chainid): """ Convert a STRIDE chainid to a PDB chainid. STRIDE uses '-' for a 'blank' chainid while PDB uses ' ' (space). So all this does is return the stride_chainid unless it is '-', then it returns ' '. Parameters: stride_chainid - the STRID...
137fdcc67557d9faa22c0b2496bc8f340a6f3206
676,920
def doc_to_labels(document): """ Converts document to a label: list of cluster ids. :param document: Document object :return: list of cluster ids. """ labels = [] word_to_cluster = document.words_to_clusters() cluster_to_id = {cluster:cluster_id for cluster_id, cluster in enumerate(docum...
71d6d521dc26012ddb169185473010a7ee6571f5
676,922
def _GetChangePath(change): """Given a change id, return a path prefix for the change.""" return 'changes/%s' % str(change).replace('/', '%2F')
c468f31c38903da50f8f950cdba3764ca29b26f9
676,924
import hashlib def list_hash(str_list): """ Return a hash value for a given list of string. :param str_list: a list of strings (e.g. x_test) :type str_list: list (of str) :returns: an MD5 hash value :rtype: str """ m = hashlib.md5() for doc in str_list: try: m....
e9b3c7fbdd05f63cdd92a3d20fec0c1ef971b532
676,925
def computeDelayMatrix(lengthMat, signalV, segmentLength=1): """ Compute the delay matrix from the fiber length matrix and the signal velocity :param lengthMat: A matrix containing the connection length in segment :param signalV: Signal velocity in m/s :par...
71ceaf48520c21f96f2de2ed38161cbb27e56c35
676,930
def present(ds, t0): """ Return clouds that are present at time `t0` """ # time of appearance tmin = ds.tmin # time of disappearance tmax = ds.tmax m = (tmin <= t0) & (t0 <= tmax) return m
1a36b390d232601f1d9c4c32e4d6d789fabeb135
676,931
def WI_statewide_eqn(Qm, A, Qr, Q90): """Regression equation of Gebert and others (2007, 2011) for estimating average annual baseflow from a field measurement of streamflow during low-flow conditions. Parameters ---------- Qm : float or 1-D array of floats Measured streamflow. A : f...
e02dc3ef384435d93eab7fdc6f96d60e98fe4c6f
676,934
from datetime import datetime def time_elapsed_since(start): """Computes elapsed time since start.""" timedelta = datetime.now() - start string = str(timedelta)[:-7] ms = int(timedelta.total_seconds() * 1000) return string, ms
6fba7d4cb7a7f3ec2241914b6b53f269b5e26ee0
676,942
import ipaddress def is_valid_ip(ip: str): """Return True if IP address is valid.""" try: if ipaddress.ip_address(ip).version == (4 or 6): return True except ValueError: return False
ab81c50164977d54bf10426149e78340ce461785
676,950
def get_user_id(user): """Return id attribute of the object if it is relation, otherwise return given value.""" return user.id if type(user).__name__ == "User" else user
7c9ef7e2511e6f111546994d08f9c699bcb7cbf3
676,952
def append_a(string): """Append "_a" to string and return the modified string""" string = '{}{}'.format(string, '_a') return string
7249063bbb9331de5163ef343399d51884312cd0
676,956
def disable_control_flow_v2(unused_msg): """Decorator for a function in a with_control_flow_v2 enabled test class. Blocks the function from being run with v2 control flow ops. Args: unused_msg: Reason for disabling. Returns: The wrapped function with _disable_control_flow_v2 attr set to True. """ ...
90998bc0400e1d8e0c267ca130f7e6a31f552470
676,960
def get_list_uniques(_list): """ This function returns the unique/s value/s of a given list. :param _list: List :return: List containing unique values. """ ret = [] for it in _list: if it not in ret: ret.append(it) return ret
126059fee80f2505ffdbf373228e476e6c6e3526
676,961
def vi700(b4, b5): """ Vegetation Index 700 (Gitelson et al., 2002). .. math:: VI700 = (b5 - b4)/(b5 + b4) :param b4: Red. :type b4: numpy.ndarray or float :param b5: Red-edge 1. :type b5: numpy.ndarray or float :returns VI700: Index value .. Tip:: Gitelson, A. A., Kaufm...
2e9bc9f8092e225711754b816e8b588dfbc462b4
676,967
import json def get_json(json_str, encoding='utf-8'): """ Return a list or dictionary converted from an encoded json_str. json_str (str): JSON string to be decoded and converted encoding (str): encoding used by json_str """ return json.loads(json_str.decode(encoding))
abedb4def38c8403872074f2de3cfaca31df5695
676,968
def joueur_continuer() -> bool: """ Cette fonction est utilisée pour demander au joueur s'il veut continuer ou non de piocher. Returns: bool: Retourne True si le joueur veut piocher, False sinon. """ continuer_le_jeux = input("Voulez-vous piocher? y ou n ") if continuer_le_jeux == "y": ...
36b29d5c4115b3a84edd4eba79f86813762aa492
676,972
def resend_strawpoll(jenni, input): """.resendstrawpoll - Resends the last strawpoll link created""" if hasattr(jenni.config, "last_strawpoll"): channel = input.sender if channel in jenni.config.last_strawpoll: return jenni.say(jenni.config.last_strawpoll[channel]) jenni.say("No ...
59f4399536fc23ccf124ca026929fa0ec64f3f11
676,975
import re def replaceTags(value, data_record): """ As efficiently as possible, replace tags in input string with corresponding values in data_record dictionary. The idea is to iterate through all of the elements of the data_record, and replace each instance of a bracketed key in the input string ...
88e1e2d6c279eb50a615e9a6648fa5d08f525f18
676,977
def LastLineLength(s): """Returns the length of the last line in s. Args: s: A multi-line string, including newlines. Returns: The length of the last line in s, in characters. """ if s.rfind('\n') == -1: return len(s) return len(s) - s.rfind('\n') - len('\n')
c2bd1a2973cc4c041cd56a75d1c0e44ce5b4eb88
676,978
def input_int(prompt: str, min_val: int = 1, max_val: int = 5) -> int: """Get an integer from the user""" while True: try: user_input = int(input(prompt)) if min_val <= user_input <= max_val: return user_input print("Value not within range. Try again!"...
15040b8110c8b0fb6c53e620a24d9c539369a486
676,980
import pathlib def get_test_cases(which_subset): """Return a list of test case files.""" assert which_subset in ("valid", "invalid") cwd = pathlib.Path(__file__).parent.resolve() test_dir = cwd / ".." / "demes-spec" / "test-cases" / which_subset files = [str(file) for file in test_dir.glob("*.yaml...
a6f90df366f222b37a90d818660624ec5b189a09
676,981
def is_info_hash_valid(data: bytes, info_hash: bytes) -> bool: """ Checks if the info_hash sent by another peer matches ours. """ return data[28:48] == info_hash
05443f7ede4c6bb85eb7d86d68239a3ef778e629
676,982
def dict_diff(a, b): """Returns the difference between two dictionaries. Parameters ---------- a : dict The dictionary to prefer different results from. b : dict The dictionary to compare against. Returns ------- dict A dictionary with only the different keys: v...
cfd20ce51d8bd7cb4f245819ba43813f0bbfa8bf
676,985
def read_ccloud_config(config_file): """Read Confluent Cloud configuration for librdkafka clients""" conf = {} with open(config_file) as fh: for line in fh: line = line.strip() if line[0] != "#" and len(line) != 0: parameter, value = line.strip().split('=', 1...
86ec495ad4c1d2b552b79d001add8aebf3cfe8a5
676,987
def trim_block(multiline_str): """Remove empty lines and leading whitespace""" result = "" for line in multiline_str.split("\n"): line = line.lstrip() if line != '': result += "%s\n" % line return result.rstrip()
9f38770d2c8c6728f035f14dd55a5bbd610c2117
676,988
def intersect_trees(tree1, tree2): """Shrink two trees to contain only overlapping taxa. Parameters ---------- tree1 : skbio.TreeNode first tree to intersect tree2 : skbio.TreeNode second tree to intersect Returns ------- tuple of two TreeNodes resulting trees c...
344ace1e867748f1db0b514b7b1339775cadbe4a
676,989
def filter_none(kwargs): """ Remove all `None` values froma given dict. SQLAlchemy does not like to have values that are None passed to it. :param kwargs: Dict to filter :return: Dict without any 'None' values """ n_kwargs = {} for k, v in kwargs.items(): if v: n_kwa...
0a753232fe09ebbe91a0ceadeba70eb2a6c7f7bb
676,990
def _quote(text): """Enclose the string with quotation characters""" return '\'{0}\''.format(text)
c7e0cc88bf4777026afe2d909cd4ceec9c78596a
676,991
def filter_by_year(df, filter_cat="conc_yy", year=1990): """Filter df by year, either with conception year ('conc_yy') or birth year ('dob_yy') """ df = ( df[df[filter_cat] == year] .groupby( [ "conc_yy", "conc_month", "dob_yy",...
2b3a06d2b7a572e983a3253a7db6c1c688c57b68
676,992
from pathlib import Path import shutil def get_config(repo_path: Path, filename: str) -> Path: """Get a config file, copied from the test directory into repo_path. :param repo_path: path to the repo into which to copy the config file. :param filename: name of the file from the test directory. :return...
4ac87766cd61e4202a3b73bd373009f8b6f52d34
676,993
def create_tag_cloud_html(tag_cloud_name, tags, level_weights): """Create HTML code for the tag cloud. ``tag_cloud_name`` is the CSS style name used for the generated tag cloud. It should be the same value as passed to ``create_tag_cloud_css``. ``tags`` and ``level_weights`` are the return values ...
7aa41dc9e92c6041a884e12957f3f29f7ff1bd06
676,995
def get_tables_from_mapping(source_table, dest_fields, source_dest_map): """ Obtain a petl tables from a source petl table and some mappings source_table: petl table dest_fields: list source_dest_map: dict Returns dest_table: petl table """ source_fields = list(source_table...
26eab2187e6a3c0729331750d5adb50c760155a8
676,996
def second(xs): """Grab the second item from a list-like thing.""" return xs[1]
3ec189fb8a7e17517bc04ea5ee52a84fc0c836b8
676,998
from typing import Callable import re def remove_link_ids() -> Callable[[str], str]: """Create function to remove link ids from rendered hyperlinks.""" def _remove_link_ids(render: str) -> str: """Remove link ids from rendered hyperlinks.""" re_link_ids = re.compile(r"id=[\d\.\-]*?;") ...
cbddaca54c205d54f8c2e1baba504c14d31e7676
677,000
def fails_if_called(test, msg="This function must not be called.", arguments=True): """ Return a new function (accepting any arguments) that will call test.fail(msg) if it is called. :keyword bool arguments: If set to ``False``, then we will not accept any arguments. This ca...
a234b141a8e24a74a15a98929aee02a181721f5c
677,002
def qualifiedClassName(obj): """ Utility method for returning the fully qualified class name of an instance. Objects must be instances of "new classes." """ return obj.__module__ + "." + type(obj).__name__
47b2f9b05b4132ced64bff1b840a1ec6bde55b53
677,004
import torch def pairwise_distance(node_feature): """ Compute the l2 distance between any two features in a group of features :param node_feature: a group of feature vectors organized as batch_size x channels x number_of_nodes """ batch_size = node_feature.shape[0] node_feature = node_fea...
ea3017dccb6b7c5b9364407af1218a741ce3a85c
677,006
def is_six_band(frequency: int) -> bool: """determines if a channel frequency is in the 6.0-7.125 GHz ISM band""" if frequency > 5900 and frequency < 7125: return True else: return False
0169d59720c6efee57fa8021a14d5117610d45b4
677,015
def setify(i): """ Iterable to set. """ return set(i)
c80798d64691333d54f4322b69897461f1243e58
677,016
from typing import Set def compute_number_of_edge_types( tied_fwd_bkwd_edge_types: Set[int], num_fwd_edge_types: int, add_self_loop_edges: bool ) -> int: """Computes the number of edge types after adding backward edges and possibly self loops.""" return 2 * num_fwd_edge_types - len(tied_fwd_bkwd_edge_type...
ce806bf83ac60d287eb49d97794ab77e8c4bd310
677,020
import re def uppercase_lowercase(a_string): """Assumes a_string is a string returns a boolean, True is a_string contains one upper case letter followed by lower case letters else False """ regex = "[A-Z][a-z]+" results = re.search(regex, a_string) return bool(results)
cd0623fd885b1f6d4833b901852985f4317e9156
677,021
def _get_mean_dist(data: list): """ Calculates the average euclidian distance matrix from prior training c-means. ----------------------------------------------------------------------------------- !!! For statistical evaluation !!! ------------------------------------------------------------------...
e192a9d406bf2da68933b3006a959b1f1b6401b4
677,022
def gray_augment(is_training=True, **kwargs): """Applies random grayscale augmentation.""" if is_training: prob = kwargs['prob'] if 'prob' in kwargs else 0.2 return [('gray', {'prob': prob})] return []
072ca5bcd47dfebf38e6777608cbf4d105eacc63
677,025
def winsorize_at_explicit_input(x, lower_bound, upper_bound): """ Winsorizes the array x at the lower_bound and upper_bound. :param x: a numpy array-like object :param lower_bound: a scalar for the lower bound :param upper_bound: a scalar for the upper bound :return: the winsorized array ""...
4aabf8a3fcc4f5b1ac301f69d622edc88d5923ed
677,026
def _parse_str_to_dict(x): """Convert "k1:v1,k2:v2" string to dict Args: x (str): Input string Returns: dict: Dictionary {"k1": "v1", "k2": "v2"} """ d = {} for p in x.split(","): if ":" in p: k, v = p.split(":") d[k] = v return d
5659b55900adddfd856a4c97d03406747a8e2603
677,030
def subject_tag_get_all(client, subject_id, session=None): """Get a list of tags for a specific subject.""" return client.subject_tag_get_all(subject_id=subject_id)
d6ed89494f98da75ae69c5c05e1565b97ff3f5a1
677,034
def _extract_fields_from_row(row, element): """Pluck data from the provided row and element.""" row_data = [] fields = row.find_all(element) for raw_field in fields: field = raw_field.text.strip() row_data.append(field) return row_data
081473db76f139eab4687b60f309801b40f1c69a
677,035
def normalize_brightness_dict(brightness_dict): """Usually the distribution of the character brightness for a given font is not as diverse as we would like it to be. This results in a pretty poor result during the image to ASCII art conversion (if used as-is). Because of this it's much better to normal...
fa857be51d983c96ec03856da252935eb44cb6be
677,036
def all_smaller(nums1: set, nums2: set) -> bool: """Return whether every number in nums1 is less than every number in num2. You may ASSUME that: - nums1 is non-empty - nums2 is non-empty - nums1 and nums2 contain only integers and/or floats >>> all_smaller({2}, {3}) True >>> all_...
0676797b13b61f16a892159410d024b326ca2eb5
677,041
def treasury_bill_price(discount_yield, days_to_maturity): """Computes price ot treasury bill""" return 100 * (1 - days_to_maturity / 360 * discount_yield)
339ea159edabd252a3f2cf3705226b7cc643cc19
677,043
import torch def _get_test_data(with_boundary=True, identical=True): """ Produces test data in the format [Batch size x W x H], where batch size is 2, W=3 and H=3. In the first batch the pixel at 3,2 is a boundary pixel and in the second pixel at 1,2 :param with_boundary: bool if true there i...
bcc6699c4b15305e9fb031b4fd60719be49be581
677,044
def _analyse_gdal_output(output): """ Analyse the output from gpt to find if it executes successfully. Parameters ---------- output : str Ouptut from gpt. Returns ------- flag : boolean False if "Error" is found and True if not. """ # return false if "Error" is ...
ede18bb90358211b7cbcab1eea3a36222553ce49
677,046
def normalized_current_date(datetime_col, min_date, max_date): """ Temporal feature indicating the position of the date of a record in the entire time period under consideration, normalized to be between 0 and 1. Args: datetime_col: Datetime column. min_date: minimum value of date. ...
2947aa4de2aa5e98ec9c33c51fbda8716ff13e37
677,050
def _is_permutation_winning(my, result, count): """判断是否匹配(排列方式) my: 排列数1 result: 排列数2 count: 匹配的位数 e.g.: my = [9,9,8,5,6,3,8] result = [2,0,3,5,6,4,9] count = 2 return is True """ s, e = 0, count #逐个切片 while e <= len(result): if my[s:e] == res...
db2f4658541b734ad346bc6a651c471551879cf6
677,051
import string import random def random_string_generator(size=10, chars=string.ascii_uppercase + string.digits): """ Generate a random string of `size` consisting of `chars` """ return ''.join(random.choice(chars) for _ in range(size))
836c182093f9e89c208d2db491cc889fc65efe22
677,052
import torch def sequence_mask(lengths, maxlen, dtype=None): """ Exact same behavior as tf.sequence_mask. Thanks to Dimitris Papatheodorou (https://discuss.pytorch.org/t/pytorch-equivalent-for-tf-sequence-mask/ 39036). """ if maxlen is None: maxlen = lengths.max() mask = ~(tor...
7c6101bc1256a09b9dadcdfc421115be3f60c46d
677,053
def ensure_list_or_tuple(obj): """ Takes some object and wraps it in a list - i.e. [obj] - unless the object is already a list or a tuple instance. In that case, simply returns 'obj' Args: obj: Any object Returns: [obj] if obj is not a list or tuple, else obj """ return [ob...
1b8e0365bc303f43f465feb77b88c2091bf943df
677,054
import requests def get_agents(url, agents_tag, headers): """Get the agents.""" req = requests.get(url + "/agents/", headers=headers) if req.status_code != 200: raise ValueError("Unable to get the token") return [a for a in req.json()["results"] if agents_tag in a["parameters"]["tags"]]
fb9991c0a417b78f13a8f6d814cd9db8966905e1
677,055
def section(name): """ Returns regex matching the specified section. Case is ignored in name. """ return r'(?<=\n)={2,} *' + fr'(?i:{name})' + r' *={2,}'
db0e196a3d3f095d4b0bd82ff9f3fc1c887ff6b6
677,059
import time import re def to_kubernetes_name(name, prefix=""): """ Returns a valid and unique kubernetes name based on prefix and name, replacing characters in name as necessary see https://kubernetes.io/docs/concepts/overview/working-with-objects/names/ """ unique_id = str(time.time()).replace("....
6cee3f8f9cc9ce8293ae3517ec66f38d55ccd9a2
677,060
def target_state(target_dict): """Converting properties to target states Args: target_dict: dictionary containing target names as keys and target objects as values Returns: dictionary mapping target name to its state """ if {} == target_dict: return None result = {} ...
642463e545924758eae99706f5bb018e63a4a398
677,066
def F_calc(TP, FP, FN, beta): """ Calculate F-score. :param TP: true positive :type TP: int :param FP: false positive :type FP: int :param FN: false negative :type FN: int :param beta: beta coefficient :type beta: float :return: F-score as float """ try: resu...
452894f75b9b3586ee686bb6d8cd5dcd71cbfeae
677,071
def title_case(sentence): """ Capitalize the first letter of every word. Parameters ---------------- sentence: string The sentence to be put into title case. Returns ---------------- capitalized: string The input string in title case. """ if sentence == sentenc...
1c886f4d6ca369313ee02d7e3d9b4d304032c2df
677,072
def testme(si): """Revert a string, filtering out the vowel characters""" so = ''.join([c for c in reversed(si) if c.lower() not in 'aeiouy']) return so, len(so)
ea90c3e95139b51f5854a32c3602607e26fd3a6a
677,075
import hashlib def get_md5(file: str) -> str: """ Get the md5code of file. :param file: The path of file. :return: The md5code of file """ m = hashlib.md5() with open(file, 'rb') as f: for line in f: m.update(line) md5code = m.hexdigest() return md5code
2a26ab60d6484f72e7e50ca1a01e8771916d1bb0
677,078
def mergeDicts(dict1, dict2): """Merge two dictionaries.""" res = {**dict1, **dict2} return res
32960e3b2a7b6864acf06d56cf6b0d7a0479b99c
677,084
def dict_keys_lower(d): """list of dictionary keys in lower case""" return list(map(str.lower, d.keys()))
9cb29394bbff0efd5ebc44f638290fd2d1bb3a94
677,087
def expand(x, y, cals, shown, length, width): """ Expand empty position with no bombs surrounded :param x: horizontal position :param y: vertical position :param cals: matrix of numbers :param shown: list of positions shown :param length: length of the board :param width: width of the bo...
bd834c9dfb604260cc9e5eba8b5cbc19458dd1ce
677,088
def get_batch_token_embeddings(layer_hidden_states, attention_mask, rm_special_tokens=False): """ remove padding and special tokens Args: layer_hidden_states: (N, L, D) attention_mask: (N, L) with 1 indicate valid bits, 0 pad bits rm_special_tokens: bool, whether to remove special tokens...
3945784b428df47adc628343c794271fb447e82a
677,091