content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from pkg_resources import iter_entry_points def mock_iter_entry_points_factory(data, mocked_group): """Create a mock iter_entry_points function.""" def entrypoints(group, name=None): if group == mocked_group: for entrypoint in data: yield entrypoint else: ...
6062ff151661d6523f3e3eb26928e905052b26e9
674,760
def isprime(number): """ Check if a number is a prime number number: The number to check """ if number == 1: return False for i in range(2, int(number**0.5) + 1): if number % i == 0: return False return True
ea644071a80ed9d467d025cfd6261783abb688c5
674,761
def import_class_by_path(class_path): """Import a class by its <module>.<name> path. Args: class_path: <module>.<name> for a class. Returns: Class object for the given class_path. """ classname = class_path.split('.')[-1] modulename = '.'.join(class_path.split('.')[0:-1]) mod = __import__(module...
a03ba0e25b70328ec7cc2ac044ed165ca30cfdf7
674,763
def avg(l): """Returns the average of a list of numbers.""" if not l: return None return sum(l)/len(l)
1d3ad50753796374dd73008dc1d3eb95432780c1
674,766
import re def clean_str(text: str) -> str: """ Args: text: A unicode string Returns: str: lowercased, sans punctuation, non-English letters """ RE_PREPROCESS = r'\W+|\d+' text = re.sub( RE_PREPROCESS, ' ', text.lower() ) text = re.sub(r"[^A-Za-z0...
d716c66d77ba73335f19d345879fa59f42277774
674,769
def NetworkSetSFANodeClass(sfa_node_class, network): """Replaces the field sfa_node_class of all layers with a specific node class. This function is useful, for example, to transform an SFA network into a PCA network. """ for i, layer in enumerate(network.layers): layer.sfa_node_class = sfa_node_cl...
e40b8be605c9b3f838298cd7c647194a0963a49f
674,772
import math import random def optimizar(dominio, temperatura = 10e32, tasa_enfriamiento = 0.95): """Algoritmo de optimización estocástica simulated annealing. Entradas: dominio (Dominio) Un objeto que modela el dominio del problema que se quiere aproximar. temperatura (float/int) Tem...
0ccb5bde943bc7c60127da0007e3adbd6af2c0a6
674,776
import torch def collate_fn(samples): """ collate_fn for SequentialMNIST. Args: samples: a list of samples. Each item is a (imgs, nums) pair. Where - imgs: shape (T, 1, C, H, W) - nums: shape (T, 1) And len(samples) is the batch size. ...
29a8b44a261d9db1de0b91c4f5eace64ee21d5fb
674,778
def utf8_encode(s: str) -> bytes: """Encodes a string with utf-8 and returns its byte sequence. Invalid surrogates will be replaced with U+FFFD. Args: s: A string to encode with utf-8. Returns: A utf-8 encoded byte sequence. """ s = s.encode("utf-16", "surrogatepass").decode("...
762588f0904eef539fa5f1648e060897e899f618
674,779
def subdirs(folderpath, pattern="*"): """ returns all sub folders in a given folder matching a pattern """ return [f for f in folderpath.glob(pattern) if f.is_dir()]
8fe701c0620dc28c24d448eae3a71632bf0817d6
674,781
def extract_keywords(lst_dict, kw): """Extract the value associated to a specific keyword in a list of dictionaries. Returns the list of values extracted from the keywords. Parameters ---------- lst_dict : python list of dictionaries list to extract keywords from kw : string keywo...
28b97459dca558e245fa552a18711d5f5ce7a802
674,782
def flatten_dict(input_dict): """Returns flattened dictionary given an input dictionary with maximum depth of 2 Args: input_dict (dict): `str → number` key-value pairs, where value can be a number or a dictionary with `str → number` key-value paris. Returns: dict: F...
171fcc9f45743ade1e2a624862c8bf93cc0da775
674,783
import re def remove_vowels(string=''): """ Removes the vowels from the given string. According to the rules the letters A, E, I, O, U are considered vowels. :param string: The input to remove vowels from :return: The given string without vowels """ return re.sub('a|e|i|o|u|y', '', string,...
965a2d2939da3b6b0cc97e1390bf17c71bf3182e
674,786
def header_check(file): """Checks whether the file has a header or not. Parameters ---------- file : str Filename or filepath of file to check Returns ------- int 1 if header is present 0 if not """ with open(file, "r", encoding="utf-8") as to_check: result ...
6213799704ff9a1a07fac072b0bd78d1d132675f
674,791
def build_parms(args): """Helper function to parse command line arguments into dictionary input: ArgumentParser class object output: dictionary of expected parameters """ readDir=args.dir outdir=args.outdir parms = {"readDir":readDir, "outdir":outdir} return(p...
4f731e89b2392dbb8ce13b78c57a3772486eca64
674,793
import re def strip_config_header(config): """Normalize items that should not show up in IOS-XR compare_config.""" config = re.sub(r"^Building config.*\n!! IOS.*", "", config, flags=re.M) config = config.strip() config = re.sub(r"^!!.*", "", config) config = re.sub(r"end$", "", config) return ...
93f733960a5b4231628aff1b26e1e2f9cdd63ec2
674,796
def get_item_relative_limit(page, per_page): """Get the maximum possible number of items on one page.""" return per_page
f6e9af997fbd36ca44229d974482451f79ab99b2
674,797
def p1(range_max, factor_list): """Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ range_min = 0 sum_multiples = 0 for num in range(...
eaa2937ff877e5f29c85b7dc3f27b188a9035635
674,799
import re def regex_search_list(data, regex): """ Allows you to search across a list with regex returns True if any match in the list. :param data: The element to search :param regex: The regex search string :return: True if any elements match, false if none match """ # Create the data int...
affa406083c0fdcc02df76783777d20676347622
674,800
from typing import Union def convert_strike(strike: Union[int, float]) -> Union[int, float]: """ Convert the type of the strike to an integer if it is an integer or float to 2 points if it is a float Note ---- This is only a type conversion """ if (strike - int(strike)) == 0: retur...
37082340550ef9b69e4770800d3186d58e991f2a
674,802
def string_is_equal_case_insensitive(subject: str, value: str) -> bool: """Case insensitive string is equal""" return subject.strip().lower() == value.strip().lower()
29de3ee6d78e6fb0abf2199ee3a1b690efb15401
674,803
def find_odd_occurred_number_sol2(nums): """ You are given an array of repeating numbers. All numbers repeat in even way, except for one. Find the odd occurring number. - This solution takes less space. - More details: https://youtu.be/bMF2fG9eY0A - Time: O(len(nums)) - Space: worst: O(len...
48bd4dba827606a01d092dc321bfed0d949e2386
674,805
from typing import List def route_ranks(scores: List[float]) -> List[int]: """ Compute the rank of route scores. Rank starts at 1 :param scores: the route scores :return: a list of ranks for each route """ ranks = [1] for idx in range(1, len(scores)): if abs(scores[idx] - scores[i...
06828f144d3cca13b01dde9bad104a648dbe71c5
674,809
def transformer(y, func=None): """Transforms target variable and prediction""" if func is None: return y else: return func(y)
9d90473b5aba83364902bd138cbe746fa3a3f409
674,811
import torch def split_stack(x, split_sizes, split_dim, stack_dim): """Split x along dimension split_dim and stack again at dimension stack_dim""" t = torch.stack(torch.split(x, split_sizes, dim=split_dim), dim=stack_dim) return t
63f0fdc7588baa392bf14e7b53f6881bbd16386e
674,815
import re def parse_int_sprintf_pattern(patt): """Parses the integer sprintf pattern and returns a function that can detect whether a string matches the pattern. Args: patt: a sprintf pattern like "%05d", "%4d", or "%d" Returns: a function that returns True/False whether a given stri...
c271df911ad8607f8bbd371c5acdd3ba8618959d
674,819
import re def getSender(email): """ Returns the best-guess sender of an email. Arguments: email -- the email whose sender is desired Returns: Sender of the email. """ sender = email['From'] m = re.match(r'(.*)\s<.*>', sender) if m: return m.group(1...
7fabda5eef256fb2256aa1af3bc23912e76472ab
674,821
def signed2unsigned(value, width=32): """ convert a signed value to it's 2 complement unsigned encoding """ if value >= 0: return int(value) else: return int(value + 2**(width) )
5d51a99445decc8ddf7a06ee73d54daa6502b85f
674,828
import struct def read_binary(fileObj, byteType='uint8', size=1): """A helper function to readin values from a binary file Parameters: ----------- fileObj : object a binary file object byteType : string, optional, default 'uint8' the type of readin values size : int, option...
68607ba14d21da017a01d1e7fb26e2b4d35491cc
674,829
def is_external_plugin(module_path): """ Returns true when the given module is an external plugin. Implementation note: does a simple check on the name to see if it's not prefixed with "kolibri.". If so, we know it's not an internal plugin. """ return not module_path.startswith("kolibri.")
b3058bf76882ce7f52518c993e9350d7b4fa9b24
674,835
def intersect(lst1, lst2): """intersection of two lists """ lst3 = [value for value in lst1 if value in lst2] return lst3
4f579dd6eea95871ffa544852b76feb2df25d036
674,836
from typing import Dict def prettify_data_filtering_rule(rule: Dict) -> Dict: """ Prettify the data filtering rule to be compatible to our standard. Args: rule: The profile rule to prettify Returns: rule dictionary compatible to our standards. """ pretty_rule = { 'Name': rule...
a4cbd2ea0a7ae2caca6e7dbe3d7665f9abd7094f
674,837
def identity(x): """Identity activation function. Input equals output. Args: x (ndarray): weighted sum of inputs. """ return x
86f6b926244b517023d34b76dbef10b4ae5dcfce
674,846
def _recipe_name(raw_configuration): """ Given a raw repository configuration, returns its recipe name. :param raw_configuration: configuration as returned by the SCRIPT_NAME_GET groovy script. :type raw_configuration: dict :return: name of the recipe ("format") """ name = raw_confi...
c030082623b157744bf057272f530583cb426561
674,848
import itertools def color_repeats(n=1): """Set up a cycle through default Plotly colors, repeating each n times""" color_list = ( ["#1f77b4"] * n # muted blue + ["#ff7f0e"] * n # safety orange + ["#2ca02c"] * n # cooked asparagus green + ["#d62728"] * n # brick red ...
c4c7d68bce476b9c4c6763323057594ea19a435c
674,853
def pybb_editable_by(post, user): """ Check if the post could be edited by the user. """ return post.is_editable_by(user)
16605a5176b824ae982b17943f2fba477ad9b661
674,854
def mean_squared_error_loss(inputs, targets): """ 平方差损失 Examples: >>> i = torch.randn(3, 5) >>> t = torch.randn(3, 5) # 与官方结果比较 >>> my_ret = mean_squared_error_loss(i, t) >>> official_ret = F.mse_loss(i, t, reduction='none') >>> assert torch.allclose(my_ret, off...
c424cbcffeb71ed34d5473704e788921385ac891
674,859
def _get_cost (route, solution, dists): """ This method is used to calculate the total distance associated to a route, once the sequence of its nodes has been changed using the 2-OPT algorithm. :param route: The interested route. :param solution: The nodesin the order in which they are visited....
37ccdecec3fc517346bacaac0a762b68f86d4cc5
674,860
def no_data_extractor(node, user): """Dummy function that collects no data for the NodeDataRegistry.""" return []
180b076859e21c05c4b39adb1de6c8896119f74b
674,861
def camel_case_from_underscores(string): """generate a CamelCase string from an underscore_string.""" components = string.split('_') string = '' for component in components: string += component[0].upper() + component[1:] return string
10e86e5079641d45e614c5e38da4e73032299fda
674,862
def easy_helloname(a): """Takes in a string representing a name and returns a new string saying hello in a very specific format, e.g., if the name is 'Dave', it should return 'Hello, Dave!'""" return 'Hello, {}!'.format(a)
37ac6517f700b148c712e94bc14ffe2d1c21a03c
674,863
import mimetypes def _GuessMimeType(magic_obj, file_name): """Guess a file's mimetype base on its extension and content. File extension is favored over file content to reduce noise. Args: magic_obj: A loaded magic instance. file_name: A path to the file. Returns: A mime type of |file_name|. "...
8b127a463e9659080cec2873a96e296f03dbd447
674,865
def convert_headers_to_environ(headers): """ Converts HTTP headers into WSGI environ variables. """ return { 'HTTP_' + key.replace('-', '_').upper(): value.strip() for key, value in headers.items() }
7fa0db7e2971d1318259e14ae269dc339e54d5b8
674,866
def expand_iterable(choices): """ Expands an iterable into a list. We use this to expand generators/etc. """ return [i for i in choices] if hasattr(choices, "__iter__") else None
4afef36052c818bce135294907207b65798a0a07
674,871
def int2list(num,listlen=0,base=2): """Return a list of the digits of num, zero padding to produce a list of length at least listlen, to the given base (default binary)""" digits = []; temp = num while temp>0: digits.append(temp % base) temp = temp // base digits.extend((listlen-len(digits))*[0]...
9f10135736aaaea2bf655774ea0a5453766e633f
674,873
def rate(e0, e1, n0, n1, nr, p): """ This equation is solved for p to determine the convergence rate when the reference solution is used to measure the error. y(p) = 0 determines the convergence rate. e0, n0 : Error and grid number for grid "0" e1, n1 : Error and grid number for grid "1" n...
1661abd1f867f65fe536bebd3ea319f002d2956a
674,874
from typing import Iterable from typing import Hashable from typing import Counter def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]: """ For the given iterable of object iterations, return an iterable of the most common object at each position of the inner iterations. E.g...
5a4705f1c6fc401ac1629239c2929cdc0b67e28d
674,876
def get_embedded(result_object, link_relation): """ Given a result_object (returned by a previous API call), return the embedded object for link_relation. The returned object can be treated as a result object in its own right. 'result_object' a JSON object returned by a previous API call. The ...
a41bb87a1c8a55c7e0be966032fbf959d69bda6e
674,878
def make_album(artist, title, tracks=0): """Build a dictionary containing information about an album.""" album_dict = { 'artist': artist.title(), 'title': title.title(), } if tracks: album_dict['tracks'] = tracks return album_dict
f94850ee837b0667f1eca61b5c7d8d49d6ca8491
674,880
import re def is_number_regex(s): """ Returns True is string is a number. """ if re.match("^\d+?\.\d+?$", s) is None: return s.isdigit() return True
fe1084bfcfc78594755f188d3033f92ca4ce5eae
674,883
def list_all_tables(conn, table_type=None): """Return a list with names of all tables in the database.""" if table_type is not None: sql_query = ( "show full tables where TABLE_TYPE = '{}';" .format(table_type)) else: sql_query = 'show full tables;' cursor = conn....
4d9ddba2e0f72c158415035a948c3f60b054b8cd
674,884
def _is_authenticated_query_param(params, token): """Check if message is authentic. Args: params (dict): A dict of the HTTP request parameters. token (str): The predefined security token. Returns: bool: True if the auth param matches the token, False if not. """ return para...
f60f0b326ef50e8feafbe91bb18df6b8bb7f55f9
674,888
def nohits_tag_from_conf(conf_file): """ Construct a 'nohits' tag from a fastq_screen conf file The 'nohits' tag is a string of '0' characters, with the number of zeroes equal to the number of 'DATABASE' lines in the conf file. For example: if there are 3 genomes in the file then the 'nohi...
d7f0836d0526733bda9c7b557c10e6157ac2586a
674,890
def fetch_cols(fstream, split_char=','): """ Fetch columns from likwid's output stream. Args: fstream: The filestream with likwid's output. split_car (str): The character we split on, default ',' Returns (list(str)): A list containing the elements of fstream, after splitting at...
f108eb94851f73c90503dbaf7ff69d86e18d268d
674,892
import re def get_event_id_from_url(event_url): """ :param event_url: chronotrack url (str) :return: event id contained in url, None if not present (int) """ event_regex = re.compile("event-([0-9]+)") match = event_regex.search(event_url) if match: return match.group(1) else: ...
be11ac3eb8f7565cd86b1a0ec2979f305c4572a9
674,893
import requests from bs4 import BeautifulSoup import re def get_opera_extension(extension_url): """ Get the file url, extension name and the version of the Opera extension """ response = requests.get(extension_url) html = response.text s = BeautifulSoup(html, "lxml") extension_version = s...
d09af3edb5e8718d10e73669341fca4e152d600c
674,894
def flat_dict(od, separator='_', key=''): """ Function to flatten nested dictionary. Each level is collapsed and joined with the specified seperator. :param od: dictionary or dictionary-like object :type od: dict :param seperator: character(s) joining successive levels :type seperator: str...
b77bcf9cc3c96c930a098512398cf01d3bff03db
674,896
def isModerator(forum, user): """Determines whether the given user is a moderator of this forum or not.""" if not forum.moderators: return False if not user: return False for mod in forum.moderators: if mod.user_id() == user.user_id(): return True return False
8664327c1e6207577c57cbf9253d295bd3f38bc3
674,906
from typing import List import glob def get_scripts_from_bin() -> List[str]: """Get all local scripts from bin so they are included in the package.""" return glob.glob("bin/*")
91594517a51197f191afb0418a5e25832fbb5cdf
674,907
def parse_singleline_row(line, columns): """ Parses a single-line row from a "net use" table and returns a dictionary mapping from standardized column names to column values. `line` must be a single-line row from the output of `NET USE`. While `NET USE` may represent a single row on multiple ...
52a24b3c6c00c89a44311a5dfdaf02e3fc6026a6
674,908
from typing import Sequence def mean(s: Sequence[float]) -> float: """Return the mean of a sequence of numbers""" return sum(s) / len(s)
e539681468af48364ef47b0e15b859346baba004
674,910
def get_bb_center(obj): """Return center coordinates of object bounding box.""" ((x0, y0, z0), (x1, y1, z1)) = obj.GetBoundingBox() xc = (x0 + x1)/2 yc = (y0 + y1)/2 return xc, yc
d620a99815b951f7bd927c5ffa055bc90842c745
674,914
def merge_l_t(l, lt): """ Merge a list of tuples lt, each of three values into three lists l. For example: [('a', 'b', 'c'), ('a', 'd', 'e')] -> [['a', 'a'], ['b', 'd'], ['c', 'e']] """ for t in lt: l[0].append(t[1]) l[1].append(t[2]) l[2].append(t[0]) return l
145c09bfbe1d351e7044a36622414fde610b8c1d
674,917
import socket import time def read_server_and_port_from_file(server_connection_info): """ Reads the server hostname and port from a file, which must contain 'hostname port'. Sleeps if the file doesn't exist or formatting was off (so you can have clients wait for the server to start running.) ...
92243aebd0e6ee21ab56550088d0e447fc6f8fed
674,918
import posixpath def join_uri(bucket, *key_paths): """ Compose a bucket and key into an S3 URI. The handling of the components of the key path works similarly to the os.path.join command with the exception of handling of absolute paths which are ignored. :param bucket: Bucket name :param key_path...
ff557e942e5d91380a8ca81414ab09a193a91f7a
674,919
def resultproxy_to_dict(resultproxy): """ Converts SQLAlchemy.engine.result.ResultProxy to a list of rows, represented as dicts. :param resultproxy: SQLAlchemy.engine.result.ResultProxy :return: rows as dicts. """ d, a = {}, [] for rowproxy in resultproxy: # rowproxy.items() retu...
3398ca1d19b3d23a793cf18c0beeb9923430410b
674,920
def server_side(connection, window_info, kwargs): """never allows a signal to be called from WebSockets; this signal can only be called from Python code. This is the default choice. >>> # noinspection PyShadowingNames ... @signal(is_allowed_to=server_side) ... def my_signal(window_info, arg1=None):...
4117c48728b28e3bb8eb90114f8d8749785c8768
674,922
import ntpath import posixpath def isabs_anywhere(filename): """Is `filename` an absolute path on any OS?""" return ntpath.isabs(filename) or posixpath.isabs(filename)
25a38d459a47dd6a16c7c783159eb75885ab491a
674,923
def list_to_str(block, delim=", "): """ Convert list to string with delimiter :param block: :param delim: :return: list_str """ list_str = "" for b in block: # print("processing:", block) if len(list_str) > 0: list_str = list_str + delim list_str = li...
26da3a41e0e15d0659fcd71a8bcb14fd9a328a6c
674,928
def pal_draw_condition_2(slope): """ Second draw condition of polygonal audience lines. The slope of the lines must be zero or positive Parameters ---------- slope : float Slope of the polygonal audience line. Returns ------- condition_2 : bool True if condition has...
d03a6318a9fc864940fc7087e934eea42597a9b3
674,931
import re def validate_fqdn(fqdn): """Checks a given string if it's a valid FQDN""" fqdn_validation = re.match( '(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$)', fqdn, ) if fqdn_validation is None: return False else: return True
078c8fed1bcd6ac0d001c8ec1ef33fd2211a7de3
674,934
from typing import OrderedDict def names_to_abbreviations(reporters): """Build a dict mapping names to their variations Something like: { "Atlantic Reporter": ['A.', 'A.2d'], } Note that the abbreviations are sorted by start date. """ names = {} for reporter_key,...
7668bd7c5c1eeafa1c1b689cfeb8f258a4c8b192
674,935
def get_subgrids(kgrids, params): """Returns subkgrids of multiple given sources """ sub_params = {} sub_summ = {} for source in kgrids: sub_params[source] = kgrids[source].get_params(params=params) sub_summ[source] = kgrids[source].get_summ(params=params) return sub_summ, sub_...
c93475152c1ceb518d1ab9eff1a64b6925afde68
674,936
from pathlib import Path def fullpath(path_or_str=''): """ Path: Expand path relative to current working directory. Accepts string or pathlib.Path input. String can include '~'. Does not expand absolute paths. Does not resolve dots. """ path = Path(path_or_str).expanduser() if not path.is_...
eea1f856dbe56e97fbf60d3b052540b56e70933e
674,937
from decimal import Decimal import datetime import six def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_text(strings_only=True). """ return isinstance(obj, six.integer_types + (type(None), f...
255e01aa14b4b7c854e404104748de8ff6fa0831
674,941
import math def calc_vo2(distance, time): """Calculate VO2 max based on a race result. Taken from Daniels and Gilbert. See, for example: * http://www.simpsonassociatesinc.com/runningmath1.htm * "The Conditioning for Distance Running -- the Scientific Aspects" Parameters ---------- distan...
81315946c3e428321237d291feeeab10f002d876
674,944
from typing import OrderedDict def dict_sort(in_dict: dict)-> OrderedDict: """ sort dict by values, 给字典排序(依据值大小) Args: in_dict: dict, eg. {"游戏:132, "旅游":32} Returns: OrderedDict """ in_dict_sort = sorted(in_dict.items(), key=lambda x:x[1], reverse=True) return OrderedDict(i...
b32187f78861c2f04c377030ecc45b1892ace708
674,947
def mc_to_float(value): """ Convert from millicents to float Args: value: millicent number Returns: value in float """ return float(value) / (100 * 1000)
9c72ca3b625a5caaaca8d1a73c2a96bf1117bf11
674,949
def get_exploding_values(list_of_values: list) -> tuple: """ This function will determine which value is the largest in the list, and will return a tuple containing the information that will have the largest percentage within the pie chart pop off. :param list_of_values: :return: A tuple of 'exp...
aebb9bf98c969871b99c4772ee55876431510b26
674,950
import string def safe_string(unsafe_str, replace_char="_"): """ Replace all non-ascii characters or digits in provided string with a replacement character. """ return ''.join([c if c in string.ascii_letters or c in string.digits else replace_char for c in unsafe_str])
683fc4937d6a8b9ad3deffa751652fd87daebca2
674,954
def arraylike(thing): """Is thing like an array?""" return isinstance(thing, (list, tuple))
78bebb4bddc3505ea1990af8a8a7ed25dfb504e2
674,955
def IssueIsInHotlist(hotlist, issue_id): """Returns T/F if the issue is in the hotlist.""" return any(issue_id == hotlist_issue.issue_id for hotlist_issue in hotlist.items)
31f48cb2c4eeddc450239edcf8d293e554cba265
674,956
from typing import Type from typing import Any import types from typing import List import inspect def get_all_subclasses_in_module( parent_class: Type[Any], module: types.ModuleType, exclude_private: bool = True, exclude_abstract: bool = False) -> List[Type[Any]]: """Returns all classes derived fro...
918a254cbae753d3002d11e5879890ab8f8aa30f
674,960
def tag(*tags): """Decorator to add tags to a test class or method.""" def decorator(obj): if len(getattr(obj, '__bases__', [])) > 1: setattr(obj, 'tags', set(tags).union(*[ set(base.tags) for base in obj.__bases__ if hasattr(base, 'tags') ...
5ea73a8d4169a25a79d91e3c5e9497d2fcf61999
674,967
def _round_pow_2(value): """Round value to next power of 2 value - max 16""" if value > 8: return 16 if value > 4: return 8 if value > 2: return 4 return value
35458a3a894df8fc579d027f72a6328ba8b8061d
674,973
def restricted(func): """ A decorator to confirm a user is logged in or redirect as needed. """ def login(self, *args, **kwargs): # Redirect to login if user not logged in, else execute func. if not self.current_user: self.redirect("/login") else: ...
e348aca0197800c2d7f7008c603488d7687fdb66
674,974
def binary_search_2(arr, elem, start, end): """ A method to perform binary search on a sorted array. :param arr: The array to search :param elem: The element to search :param start: start position from where to start searching :param end: start position till where to search :return: The in...
026742362d050e4aae3ff769f76f7b8eafaeab25
674,975
def get_data_from_epochs(epochs): """ epochs: mne.Epochs returns np array of shape (nb_epochs, sampling_rate*epoch_length) """ return epochs.get_data().squeeze()
620ec5ee06282cb3a7317442c1d03d949abf8597
674,976
def product_from_branch(branch): """ Return a product name from this branch name. :param branch: eg. "ceph-3.0-rhel-7" :returns: eg. "ceph" """ if branch.startswith('private-'): # Let's just return the thing after "private-" and hope there's a # product string match somewhere in...
7137290d6454cbe474d0ca571c326d442fcb1975
674,979
def pollution_grade(aqi: int) -> int: """Translate aqi levels to pollution grade.""" if aqi <= 50: return 0 elif 50 < aqi <= 100: return 1 elif 100 < aqi <= 150: return 2 elif 150 < aqi <= 200: return 3 elif 200 < aqi <= 300: return 4 else: return 5
e66405726ceb49acdca093caca9ac5cffd6d201b
674,980
def test_create_dataframe(data_frame, list_of_col): """ Testing whether a dataframe satisfy the following conditions: The DataFrame contains only the columns that you specified as the second argument. The values in each column have the same python type There are at least 10 rows in the DataFrame. ...
3b4e129641da92a907c50e21afd93feff632dcd2
674,983
def maybe_coeff_key(grid, expr): """ True if `expr` could be the coefficient of an FD derivative, False otherwise. """ if expr.is_Number: return True indexeds = [i for i in expr.free_symbols if i.is_Indexed] return any(not set(grid.dimensions) <= set(i.function.dimensions) for i in index...
acc21eb144ea24a6a96b56ceed12f81696430976
674,985
import re def row_skipper(file): """ Count how many rows are needed to be skipped in the parsed codebook. Parameters: file (character): File name of the parsed codebook Returns: count: The number of lines to be skipped """ with open(file, 'r') as codebook: count = 0 ...
3060ae59b3f9b378d144d8f85090adf5200d35f4
674,988
def select_year(movie_list:list, year:int): """ Select movies filmed in a specific year and returns a list of tuples (name, location) """ n_year_movies = [] for movie in movie_list: if year in movie: n_year_movies.append((movie[0],movie[-1])) print(f"Selected {len(n_year_movi...
95aa1c4a9fa6e163f6df734648a8caa077fdbdd4
674,991
import ast def robust_literal_eval(val): """Call `ast.literal_eval` without raising `ValueError`. Parameters ---------- val : str String literal to be evaluated. Returns ------- Output of `ast.literal_eval(val)', or `val` if `ValueError` was raised. """ try: retu...
7c5136d72354ad6018b99c431fc704ed761ea7db
674,993
def hasattr_explicit(cls, attr): """Returns if the given object has explicitly declared an attribute""" try: return getattr(cls, attr) != getattr(super(cls, cls), attr, None) except AttributeError: return False
ff16748ccdebe7f3ff76c117bc1284dc4eb5366c
674,995
def link_is_valid(link_info, query_words, mode="all"): """ Tests if a link is valid to keep in search results, for a given query :param link_info: a dict with keys "url" and "text" :param query_words: a list of query words :param mode: can be "all" (default), or "any" :return: True or False ...
78e98ea157a9d4fd93f6e53c832e24c9db06377d
675,003
def error_list (train_sents, test_sents, radius=2): """ Returns a list of human-readable strings indicating the errors in the given tagging of the corpus. :param train_sents: The correct tagging of the corpus :type train_sents: list(tuple) :param test_sents: The tagged corpus :type test_sen...
7e4f0aa722ccead0fe6104a7575ee474faf241e8
675,004
def pascal_case_to_snake_case(input_string): """ Converts the input string from PascalCase to snake_case :param input_string: (str) a PascalCase string :return: (str) a snake_case string """ output_list = [] for i, char in enumerate(input_string): if char.capitalize() == char: # if ...
62f710935cb2ff0feabbbaeffbb2320192720505
675,006
def to_dict(d): """ Convert EasyDict to python dict recursively. Args: d (EasyDict): dictionary to convert Returns: dict """ d = d.copy() for k, v in d.items(): if isinstance(d[k], dict): d[k] = to_dict(d[k]) return dict(d)
e6dcb313190b814100b1caacdbcef7383f72fc2d
675,010