content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def gcd(a,b): """returns g = gcd(a,b)""" while b != 0: q, r = divmod(a,b) a,b = b, r return a
36289bb9628f5937cea77b52372379d9f807ad4b
650,850
def fallback(*candidates): """ :param candidates: :return: First argument which is not None """ for i in candidates: if i is not None: return i
67d78e3c6ed5064cc75501f576ec9a1427598959
650,852
def _find_relevance(log_ttd, log_lift, R, lambda_): """From `pyLDAvis._prepare.py`, optimised""" relevance = lambda_ * log_ttd + (1 - lambda_) * log_lift return relevance.T.apply(lambda topic: topic.nlargest(R).index) # ZW: return relevance.T.apply(lambda s: s.sort_values( # ascending=False).index)....
1e624bbb87d0042abfd5b877e46199891cd6de69
650,853
import warnings def summarize_byterate_df(dataframe, readwrite, timestep=None): """ Calculate some interesting statistics from a dataframe containing byte rate data. """ assert readwrite in ['read', 'written'] if timestep is None: if dataframe.shape[0] < 2: warnings.warn("...
155b45da98f6980bed4da69d86101aa4971b3255
650,854
def _module_dir(lock_filename): """Returns module dir from a full 'lock_filename' path. Args: lock_filename: Name of the lock file, ends with .lock. Raises: ValueError: if lock_filename is ill specified. """ if not lock_filename.endswith(".lock"): raise ValueError( "Lock file name (%s) h...
a6f38371cee760211732b182546466047de44499
650,855
import numpy import math def get_spherical_coordinates(xyz): """Compute spherical coordinates (r, theta, phi) for X,Y,Z point. :param array xyz: column vector (3 row x 1 column numpy array) :return: tuple of r, theta, phi for input coordinate """ r = numpy.linalg.norm(xyz) if 0 == r: ...
f0c2bcd5d86a8635ca6b6c3e629ece85235352c0
650,858
def construct_link_dossierbehandelaar_query(graph_uri, bericht): """ Construct a SPARQL query for linking a dossierbehandelaar to a bericht. :param graph_uri: string :param bericht: dict containing properties for bericht :returns: string containing SPARQL query """ q = """ PREFIX e...
a4616b80efb74bca4dc7647c9ed3929e58035cf6
650,859
def menu(): """Mostra menu de opções e retorna a selecionada.""" opções = { '1': 'Cadastra aluno', '2': 'Entrada de notas', '3': 'Dados aluno', '4': 'Ver extrato geral', '5': 'Exportar dados dos alunos' # Novas opções podem ser adicionadas aqui! } while Tr...
c8aadddd49844cd3a71b427ba4ff1629cc0b8ca4
650,861
def is_port_range(port): """ If ports are specified and as a port range, then validate whether the ranges are the same length. This is only used when creating destination NAT rules. """ if isinstance(port, str) and '-' in port: start_port, end_port = map(int, port.split('-')) ret...
827926ca37a0348f3e71dd79c51fce3bba58eb93
650,862
def summer_clearsky(summer_times, albuquerque): """Clearsky irradiance for `sumer_times` in Albuquerque, NM.""" return albuquerque.get_clearsky(summer_times, model='simplified_solis')
ac4a349d3dcba7043afcca041279b35c7ea9aa18
650,863
import importlib import os import sys import imp def import_from_directory(library, path): """Import a library from a directory outside the path. Parameters ---------- library: string The name of the library. path: string The path of the folder containing the library. """ ...
5b8c5bc22f384368ebcb715f5a5f7436bde92dd2
650,864
from typing import Dict from typing import Any def build_validation(validator) -> Dict[str, Any]: """Builds and returns a fake validator response object.""" if validator == "lookml": return { "validator": "lookml", "status": "failed", "errors": [ { ...
5c7cc5a9fc4f486162d1a94775eee4e4e992adc7
650,865
def tok2line( tokens ): """ Turns a list of tokens into a line that can be parsed again """ elems = [ str(t.value) for t in tokens ] if tokens[0].type == 'LABEL': elems[0] = elems[0] + ':' return ' '.join( elems )
dab7c29cac41518c5f327e712647ee8a4932ec29
650,866
import numpy def stats(gridc, gridx, gridy, ivar, pvar, divc): """Velocity correction in x and y direction. Arguments --------- gridc : grid object (cell center) Grid contaning data in cell center gridx : grid object (x-direction) Grid containing data in x-direction gridy : gr...
e53fc58479bd644e064dd4330877bf6ecff6dfb1
650,867
def quoteStr(s, addQuotes=False, quoteDouble=False, quoteSingle=True): """ s (str) -- Source string parameter. Options: - addQuotes (bool|str) -- Add quotes around result string (default: False, don't quote). - quoteSingle (bool) -- Quote single quotes ('), default is True. - quoteDouble (bool) ...
399ef818107e5409211348aa64386bbc2a24113c
650,868
import shlex def parse_bed_track(line): """Parse the "name" field of a BED track definition line. Example: track name=146793_BastianLabv2_P2_target_region description="146793_BastianLabv2_P2_target_region" """ fields = shlex.split(line) # raises ValueError if line is corrupted assert fields[...
0a01dec05aec13d73e38388e8e87b817f52e58f3
650,869
from typing import List import sys def smallest_difference(a: List[int], b: List[int]) -> int: """Return the smallest absolute difference between any pairs in two arrays of numbers. First, sort the arrays then search for the pair. Idea: Advancing the pointer to the larger value only makes the difference l...
7cae56bb17c6c86fe78c5c043deff3fbb2964a11
650,870
from typing import List def parameter_order(config) -> List[str]: """ Return the order in which the parameters occur in the given dockerfile. This is needed for optimising the order in which the images are built. """ order = list() for line in config.dockerfile: order += [ ...
4f02e4c04c9afb936699323714d3d9c2e0cc2317
650,871
import json def read_config(filepath): """ Read the config from a given config file. :param filepath: The path to the config file. :type filepath: str :return: The json deserialized list. :rtype: list """ file = open(filepath, 'r') file_content = file.read() config_list = json...
eb5bf005b021fcbd7300a0d9325d8e4e34a22215
650,873
import math def jump_search(collection, item): """ :param collection : 탐색을 진행할 배열 :param item : 탐색을 진행할 키(key) 값 ;return : 키 값이 있는 위치(index), 없을 경우 None """ n = len(collection) step = int(math.floor(math.sqrt(n))) prev = 0 while collection[min(step, n)-1] < item: prev = ste...
684fa16b0e775fa983cb366eb4d64f743f279a94
650,874
def value_of(what): """ Converts a string, such as True, Yes, ... to its real value. """ if what in ["TRUE", "True", "Yes", "OK"]: return True if what in ["FALSE", "False", "None"]: return False if what == "Unknown": return None try: return int(what) excep...
8f4fbc875ff9a039e8115381ef1a4513f78a41d9
650,875
import re from functools import reduce def predict(input, type, unigram_count, bigram_count, bigram_prob, bigram_freq, total_word, total_vocab, total_bigram): """ predict - function to compute bigram probability of the input sentence Inputs: input : str Sentence unigram_count : defaultdict bigram_count : ...
b8f09fb6b823055e1e96385546d104221624ca49
650,876
def rarity_scores(dataset, vocab): """ Less likely (more rare) sentences are more difficult. @returns rarity_scores: scores to be ranked by rank_scores """ train_data, dev_data = dataset src_vocab, tgt_vocab = vocab.src, vocab.tgt train_scores = [] for (src_sent, tgt_sent) in train_data: ...
b0bf9f2a81b6352a7d45ca8bc94e386b4c526e25
650,877
import pandas def extract_file(filepath): """ Reads in a csv file containing time and voltage data, and returns the data in list format :param filepath: A String representing the path to the ECG data (csv file) :returns: Lists containing time and voltage values, respectively """ dataframe = p...
415adb7970d6cdbad55b5aaf7ef67d8d12a72ac0
650,878
from datetime import datetime def get_time() -> dict: """ Info: Returns the time in different ways via a dictionary/ Usage; get_time() Returns: dict """ time = datetime.now() return { 'millisecond': time.microsecond, 'second': time.second, ...
2fbcd1a64d99f174ce4e3ac889895d3d7f73f8bb
650,879
def sample_proxs(z, y, step=1): """ computes prox_(step * f)(z) where f(z) = 0.5 * (z - y) ** 2 """ return (z + step * y) / (1 + step)
83dbb236a207a8eb9b27a235de89d6a1da334208
650,880
def to_dictionary(words): """ Helper function to convert list of words into a dictionary. """ return dict([(word, True) for word in words])
f5af7e5d4a2789e8a53f1dc1b443a3acae2aa32b
650,882
def years_in_row(df, year_col='year', groupby=None, info_bank=None, out='pct'): """ average years in row patients are observed, for different start years Example: >>> years = years_in_row(df, year_col='aar', out='pct') """ years = df[year_col].unique() min_year = min(years) max_year...
9e6d6e6b62506ddf0c7dc10312fb99456bbfbe28
650,883
from datetime import datetime import uuid def transform_request(req): """Transform request to object to store NOTE: This method is not safe """ ts = datetime.utcnow().isoformat() req["created"] = ts req["modified"] = ts req["dt_id"] = str(uuid.uuid4()) req["processGroups"] = [] re...
16bdf7b94956a023bf0d09b9315f923b63fdf2e7
650,884
def get_info_link(content, html=False): """Return info popover link icon""" return ( '<a class="sodar-info-link" tabindex="0" data-toggle="popover" ' 'data-trigger="focus" data-placement="top" data-content="{}" {}>' '<i class="iconify text-info" data-icon="mdi:information"></i>' ...
66e0d514c9c0b892d906db21ee2dbb3631fb6394
650,885
def predict_fn(input_data, model): """Preprocess input data We implement this because the default predict_fn uses .predict(), but our model is a preprocessor so we want to use .transform(). """ features = model.transform(input_data) return features
1dacc879eaf9fde53fd96758a2c23dc83a59b5fa
650,886
def get_doodle_answer_lines(votes, summarize, is_last): """Return the user names for a doodle answer. Try to compress as many usernames as possible into a single line. e.g.: Arne, Test1, Test2, Test3, wtfoktesttesthey, Test4, Test5, rofl, ... """ threshold = 30 votes_displayed = 0 ...
9aa34cad28d416aa4f8f41893c082f723424de19
650,887
def python_format(a, prec, align=''): """Format an array into standard form and return as a string. args: a: the array prec: the precision to output the array to align: anything that can go before the . in python formatting """ format_ = (f' {{:{align}.{prec}E}}' * a.shape[1] + ...
bc5027370843ec2e921da9b9c619d216109c3cec
650,888
def get_file_less_ext(full_filename): """ Returns filename without extension""" dirs = full_filename.split("/") parts = dirs[len(dirs) - 1].split(".") if len(parts) == 1: filename = parts[0] else: filename = None for i in range(len(parts) - 1): if filename == None...
7123d55ff43fcf53d682b8e8cfd9423daec223a1
650,889
import os def make_new_folder(*paths): """Cria diretório caso ele ainda não exista e retorna o path correspondente.""" folder_path = os.path.join(*paths) if not os.path.exists(folder_path): os.makedirs(folder_path) return folder_path
4efbc4c422245114a0155223c369766f3bae93c6
650,890
import pickle def dump_pickle(objs, paths, filenames): """ """ for obj, path, filename in zip(objs, paths, filenames): out_pkl = open( f'{path}\\{filename}.pkl', 'wb' ) pickle.dump(obj, out_pkl) out_pkl.close() return None
7784c14ba7143af0a83cc2e40a8219072c163636
650,891
import re def is_image_set_grouped(pipeline): """ Report if the pipeline will group image sets. Returns **True** if image sets will be grouped. * pipeline: a list where each item is a line from a CellProfiler `*.cppipe` file. """ is_grouped_bool = False for line in pipeline: ...
1e0a102c1adc26cf5d44d357b4663c3bfb2a5327
650,892
def make_hook(timing, stage, fn): """Inner decorator for making a function usable as a hook.""" planterbox_hook_timing = getattr(fn, 'planterbox_hook_timing', set()) planterbox_hook_timing.add((timing, stage)) fn.planterbox_hook_timing = planterbox_hook_timing return fn
b6824a47ba18a07de8e26922981f10c6b2c19f97
650,893
def _makeLongRA(myRADeg): """Make a long RA string, i.e. in style of long XCS names """ hours=(myRADeg/360)*24 if hours<10: sHours="0"+str(hours)[0] else: sHours=str(hours)[:2] mins=float(str(hours)[str(hours).index("."):])*60 if mins<10: sMins="0"+str(...
5b70c5f67c84dfb721754d33a67053524a4f7208
650,894
def login_payload(opts): """ Build payload for the auth api query """ body = { "password": opts.password, "applicationId": opts.applicationId, "accountName": opts.accountName } return body
3c088454ec8bee3f5d851de27e64825e7de97a7e
650,895
import struct def read_uint32(buffer: bytearray) -> int: """ Read an unsigned 32-bit integer, read bytes are consumed. """ res, = struct.unpack('<I', buffer[:4]) del buffer[:4] return res
2977916a05fd65e32f3543f4ad0ca14f371b212c
650,896
def standardize_feature(data, feature_name, group_by=None): """ Standardize one feature either by all instances or grouped variable :param data: pd dataframe :param feature_name: feature to be standardized :return: """ if group_by is not None: standardized_feature = data[feature_name...
08b8e49042efe36c9c739dd795958f729dc1b9aa
650,897
import sqlite3 def get_AttributesFromTable(database, table): """ Retourne le nom des attributs et leur type, d'une table d'une base de donnée - database = la base de donnée - table = la table >> get_AttributesFromTable("BDD.db", "emp") """ connection = sqlite3.connect(database) cursor...
6f258dd5a3675a3b0ebeb2f16952128a7ae09522
650,898
import math def atan2(x, y): """Get the arc tangent of x, an angle in radians. The signs of x and y are used to determine what quadrant the angle is in. The range of result values is [-π, π] """ return math.atan2(x, y)
f4fd7da227becee6cc0d16117d02eae6e352e6e1
650,899
def get_test_data_df(X,size: int = 1): """Generates a test dataset of the specified size""" num_rows = len(X) test_df = X.copy() while num_rows < size: test_df = test_df.append(test_df) num_rows = len(test_df) return test_df[:size].reset_index(drop = True)
359cd4a367985294f765df6205ddaf705d6b36a7
650,901
import yaml from typing import OrderedDict def setup_yaml(): """ https://stackoverflow.com/a/8661021 """ def represent_dict_order(self, data): return self.represent_mapping( 'tag:yaml.org,2002:map', data.items()) yaml.add_representer(OrderedDict, represent_dict_order)
c2270cc559594037bfd068ae4bca3734698f4cac
650,902
def calc_cl_backw_tf(resultss): """ Calculates the overall Backward Transfer of a CL sequence of tasks, which are seperated in two metrics :param resultss: Matrix containing identical pandas DataFrames in each cell. Rows contain evaluations for one task :return: Remembering: Negative backward transfer; ...
527785b2385d961e1ead65c73683ddbd8cc68895
650,903
def get_segment_times(csv_df, breaks=None, no_energy=False, music=False, noise=False): """ Filter an InaSeg output CSV of segmented time ranges. The parameters `no_energy`, `music`, and `noise` are optional bools which filter for the "noEnergy", "music", "noise" labels in segmented time ranges. The...
130b2da85ba9c28f1aea709bd5b297c7cdb63f53
650,904
from datetime import datetime def is_current(record,year): """ Utility function to check whether a record is valid for the current year. Since records contain different information about dates, as appropriate, there are multiple conditions that must be tested. a) if a record contains only a YEAR,...
7c8f7689fb0169895d9d6bbb1db902b730f23879
650,906
def apply_formatter(formatter, *args, **kwargs): """ Used by QAbstractModel data method Configures a formatter for one field, apply the formatter with the new index data :param formatter: formatter. If can be None/dict/callback or just any type of value :param args: :param kwargs: :return: ...
1a7b5294845b86cdf64d3985bf8e6a12734fe2ce
650,907
from typing import List def readable_list(seq: List[str]) -> str: """ Return a grammatically correct human readable string (with an Oxford comma). All values will be quoted: [foo, bar, baz] becomes "foo," "bar," and "baz" """ # Ref: https://stackoverflow.com/a/53981...
7a006c9026cb9f52fd710b8c40cdfd0a4d0b33ae
650,909
import re def _grep_prop(filename, prop_name): """ Look for property in file :param filename: path to file and file name. :param prop_name: property to search for in file. :return: property value or None. """ fdata = open(filename, "r").read() obj = re.search("^{0} = ['|\"](.+)['|\"]$"...
7e604f0a1069ee93bee0486802a2d516318fef4b
650,910
def q_zero(bits=8): """ The quantized level of the 0.0 value. """ return 1 << (bits - 1)
bb4ea5bfb8a7e31b125195e17cc2412eb27d9589
650,911
def rounding(v): """Rounding for pretty plots""" if v > 100: return int(round(v)) elif v > 0 and v < 100: return round(v, 1) elif v >= 0.1 and v < 1: return round(v, 1) elif v >= 0 and v < 0.1: return round(v, 3)
61c0590c00628692eadfa56bae70ecaa1ee054b0
650,912
from typing import Union def object_type(object_ref: Union[type, object]) -> type: """Get type of anything. Args: object_ref (type, object): Object or type Returns: type: Type of given object """ return object_ref if isinstance(object_ref, type) else type(object_ref)
bd306913e8e884c89fa5dec863ee316a5d0f1456
650,914
def _read_params(test_file_name): """Return expected errors, warnings, and return value for test file.""" with open(test_file_name) as f: exp_ret_val = 0 exp_errors = [] exp_warnings = [] for index, line in enumerate(f.readlines()): ret_mark = "// Return:" ...
3ee6278505ffe062b19ff7fdd0846e0de320dd48
650,915
from datetime import datetime def date_str_from_datetime_str(datetime_str): """Convert a datetime string to a date string, e.g. 2020-07-04 12:00:00 to 2020-07-04""" try: return datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d") except ValueError: return datetime_str
7337bbc3e93e431924d2d1d4b27d291ce3e355c6
650,917
import contextlib import socket def _unused_tcp_port(): """Find an unused localhost TCP port from 1024-65535 and return it.""" with contextlib.closing(socket.socket()) as sock: sock.bind(("127.0.0.1", 0)) return sock.getsockname()[1]
e54f76b990e215b7991464b3acea8c97c7000db7
650,918
def calculate_max_series(series): """ Calculate the maximum of a series :param series: list of values where we want to know the maximum of. :return max(series): highest value in the series """ assert type(series) is list and len(series) != 0 return max(series)
de8ba05f580e2de4ca6e0737e5db61352bf1e266
650,919
def taiko(map_id, beatmap, mods, combo, n300, n100, nmiss): """Get pp for a Taiko play.""" return None
4967a4870ff9ce951bcba9d074c09e4cb2e17d5f
650,920
def cdr(env, args): """Returns body of the list. Cdr is defined if and only if its argument is not atomic: (cdr (quote (e1 e2))) = (e2) """ return args.car().eval(env).cdr()
c0c884394f9a9915ab26dcc7cb5209b51324748b
650,921
def check_jing(fd1, fd2, fd3, fd4, fd5) -> str: """检查最近5个分段走势是否构成井 井的定义: 12345,五段,是构造井的基本形态,形成井的位置肯定是5,而5出井的 前提条件是对于向上5至少比3和1其中之一高,向下反过来; 并且,234 构成一个中枢。 井只有两类,大井和小井(以向上为例): 大井对应的形式是:12345向上,5最高3次之1最低,力度上1大于3,3大于5; 小井对应的形式是: 1:12345向上,3最高5次之1最低,力度上5的力...
e0cda65413a898eac845c380254433d2a81ca824
650,922
def calc_fib(n): """Calculates the nth fibonacci number""" cache = { 0: 0, 1: 1 } def fib(n): nonlocal cache if n in cache: return cache[n] res = fib(n-1) + fib(n-2) cache[n] = res return res return fib(n)
dfc69d1b413d2283b64f90143c75131cce9ae732
650,924
from typing import List def parentheses_status_eliminate(string: str) -> str: """Check is expression string has balanced parentheses (using stack elimination). In every iteration, the innermost brackets get eliminated (replaced with empty string). If we end up with an empty string, our initial one was ba...
9cfd7d6c2fb25e0e98fa8f9dd770a51b65d2b982
650,925
def query_transform(context, include_page=False, **kwargs): """ Returns the URL-encoded querystring for the current page, updating the params with the key/value pairs passed to the tag. E.g: given the querystring ?foo=1&bar=2 {% query_transform bar=3 %} outputs ?foo=1&bar=3 {% query_transform ...
4e1361b174a910dd5e2fceef2eaec5bbbf89387b
650,926
def kequivalent(springs, config): """ Given a list of spring constant values and their configuration, returns the equivalent spring constant """ if config == 'parallel': return sum(springs) elif config == 'series': return 1 / sum((1 / n for n in springs)) else: raise...
e8fcb140dc916fd218f622ca7b85b1915895f71c
650,927
def titleize(text: str): """ Capitalizes all the words in the `text`. """ return " ".join(i.strip().lower().capitalize() for i in text.split())
61dbdb5c0c94d397c8b29bdf3c206950a6fd3183
650,928
def _select_cells(adata, group): """ Slice the data horizontally. """ cell_selector = (adata.obs['memento_group'] == group).values return adata.X[cell_selector, :].tocsc()
153139cbe8f7052f8c2b5f67fe2b51fe13b778ba
650,929
def _df_str_extract_assign_to_colnames(df, column, sep, col_names, regex_strs, prefixes=None, suffixes=None, global_prefix="^", global_suffix="$"): """ extract column names and assign to the dataframe adapted from https://stackoverflow.com/a/45377776 :param df: dat...
89c3bbb19f2d0b1e7dfddfba95d8fe18044f1335
650,930
import os def fix_path(path): """ Get an absolute path (while expanding ~). :param path: a filesystem path :type path: str :returns: an absolute path :rtype: str """ return os.path.abspath(os.path.expanduser(path))
71d83bf1127ad96c5727126eac76639832407b12
650,932
import os def get_data_dir() -> str: """ 获取cnews的文件路径,其中包含本任务需要的数据。 :return: """ current_dir = os.path.dirname(__file__) root_dir = os.path.abspath(os.path.join(current_dir, os.pardir, os.pardir, os.pardir)) data_dir = os.path.join(root_dir, "data_source", "cnews") return data_dir
5b78738fb2a82ba72f9373fc42d620baa0cb759b
650,933
def gradcheck_wrapper_triangular_input(op, *args, upper=False, idx=0, **kwargs): """Gradcheck wrpper for functions that take lower or upper triangular matrices as input. They require a modified function because the finite-difference algorithm for calculating derivatives does not preserve the triangular pro...
9376728708e8922047062bfaf6d20698f8717838
650,934
from math import copysign, fabs, fmod, isfinite, isinf, isnan def remainder(x, y): """Difference between x and the closest integer multiple of y. Return x - n*y where n*y is the closest integer multiple of y. In the case where x is exactly halfway between two multiples of y, the nearest even value of...
e601abf20e94ddb4fcd7bbb09d36c116fd32336d
650,935
def ArchForAsmFilename(filename): """Returns the architectures that a given asm file should be compiled for based on substrings in the filename.""" if 'x86_64' in filename or 'avx2' in filename: return ['x86_64'] elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename: return ['x86']...
ad8c7698e9fce72021cc05a093b9fd2063fd3280
650,936
def format_xyz_coord(element,xyz,tinker=False): """ Print a line consisting of (element, x, y, z) in accordance with .xyz file format @param[in] element A chemical element of a single atom @param[in] xyz A 3-element array containing x, y, z coordinates of that atom """ if tinker: return "%...
3d5e9c4292393bf055e757c293ff96d52020b944
650,937
from typing import Optional from typing import Set def split_int_set_str(ints: Optional[str]) -> Optional[Set[int]]: """ tuple_list: "1,2,4" """ if ints is None: return None if len(ints) == 0: return set() ints_list = ints.split(",") ints_set = set(map(int, ints_list)) return ints_set
031a74cc6d26584a5cfcb050cac016e4446fb43d
650,939
import torch def uncertainty_separation_parametric(mu, var): """Total, epistemic and aleatoric uncertainty based on a parametric (normal) variance measure M = length of input data x, N = number of distributions Args: mu: torch.tensor((M, N)): E(y|x) for M x and N distr. var: torch.t...
35211b6b7d66cce2a5fa2c62b35fde4c38bdaed2
650,940
import re def get_num_results(html): """Returns None if result size too large or Int if size is known.""" pattern = re.compile(r'Ihre Suche hat ([0-9]+) Treffer ergeben') match = pattern.search(html) if match is not None: return int(match.group(1)) match = re.search('Trefferanzahl von 200 ...
98d53aad11d757ec5c208cb285435c5b7c374114
650,942
import os def is_cached_current(original, cached): """Compare a file and the processed, cached version to see if the cached version is up to date. """ return (os.path.exists(cached) and os.stat(cached).st_mtime >= os.stat(original).st_mtime)
b3ff5141f17a383e6cf07df3ec49317b1f06c9b8
650,944
import warnings def state_is_exclusive_source_of_other_state(trans_df, state_name, start_col, end_col): """True if at least one state is only accessible from `state_name`.""" def tgt_states(df, src_lct_name): """Get the states which can originate from `src_lct_name`. Exclude the `src_...
7687d52d865e1d5c0c67d1477f25fdfe77da03b2
650,945
def unset_nth_bit(n: int, i: int) -> int: """ Unset the n-th bit. >>> bin(unset_nth_bit(0b11111111, 0)) '0b11111110' >>> bin(unset_nth_bit(0b11111110, 0)) '0b11111110' """ return n & ~(1 << i)
b8d23d849ac06e34df0c79846d85adf87e8e3fe2
650,946
def _get_category_bounds(category_edges): """Return formatted string of category bounds given list of category edges""" bounds = [ f"[{str(category_edges[i])}, {str(category_edges[i + 1])})" for i in range(len(category_edges) - 2) ] # Last category is right edge inclusive bounds.appe...
6891a29d3a20ebd9c6f84e700a39fe55db3e8134
650,947
def rma(data, length): """Rolled moving average Arguments: data {list} -- List of price data length {int} -- Lookback period for rma Returns: list -- RMA of given data """ alpha = 1 / length romoav = [] for i, _ in enumerate(data): if i < 1: romo...
a852c85efec5262bd17c38651db8798667865b7d
650,949
def numberSeparators(number, separator=' '): """ Adds a separator every 3 digits in the number. """ if not isinstance(number, str): number = str(number) # Remove decimal part str_number = number.split('.') if len(str_number[0]) <= 3: str_number[0] = str_number[0] e...
b0f56403708bc489b94b83f7f8bcffe6db29b564
650,950
def youtube_mocker(mocker): """Return a mock youtube api client""" return mocker.patch("videos.youtube.build")
d00a93fdd722ec3a75d5979d1aae7fecf29ea38d
650,952
import numpy def stride_hood(a, window=(3, 3)): """ Return views into array over a given neighbourhood window :param a: ndarray :param window: window shape :param edge_mode: method to expand array to fit window :param constant_values: if edge mode is 'constant', value to use :return: views...
a847fa0c5be2198c4fe30c2f822fee648876de41
650,953
def twoNumberSum(array, targetSum): """ twoNumberSum finds the two numbers whose sum is equals to targetSum with the binary search strategy. array: the collection of numbers that can sum the target number. targetSum: the target number to find. returns a list with the two nu...
16737c859a76267729571526847bbaa098d8d8a0
650,955
def getContinuousRuns(x): """ Given a 1D array, find all of the continuous runs of 1s, and count the numbers with a certain length :param x: 1D array :returns Runs: A frequency distribution dictionary of the form {length:counts} """ Runs = {} (IN_ZEROS, IN_ONES) = (0, 1) stat...
b6fea1eee29bf4eb8c947e55de34410298a13fc6
650,956
def recursion_invertor(text: str) -> str: """Инвертирует строчку рекурсивно.""" if len(text) == 0: return text else: return recursion_invertor(text[1:]) + text[0]
1583778c8cc48809b050594a928dd4a34c0e21b2
650,957
def __append_data_to_list(target_list: list, row: str) -> list: """ Append data from row of source file to list of data. Returns: list of data. """ row = row.replace('\n', '') row_splitted = row.split(':')[1].split(' ') rowlist = [] for i in range(1, len(row_splitted)): str_...
812ce0377f5a253efc256458b2fb603448c232a8
650,958
import os import zipfile def path_zip_file(data_dir): """Creates ``coutwildrnp.zip`` if it does not exist and returns the absolute file path.""" path = '{}/white-gemini-iv.zip'.format(data_dir) if not os.path.exists(path): with zipfile.ZipFile(path, 'w') as zip: for filename in ['w...
c947de9c2a47aad7288d80c847f41c4bf25c42b9
650,959
def ask_value(message): """ Ask user to type some value. Ask again if no answer. Arguments: - message (string): message to display Return (string): value typed by user """ answer = input(message) if answer == '': return ask_valu...
ae937cc38c2f7402548f43465f6210a2a64dea66
650,960
def get_eval_code(args_str, function): """ Invokes function below implementation. :param args_str: eg: 'a=True, b=False' :param function: to be tested :return: code to run. """ return function.__name__ + '(' + args_str + ')'
6d350146e0a39750fbc8cf536215a5e95a12c233
650,962
from typing import Tuple from typing import List def version_str_sortkey(vers_str: str) -> Tuple[List[int], List[int]]: """Sort version strings according to the numeric order""" parts = vers_str.split('_') return ([int(x) for x in parts[0].split('.')], [int(x, 16) for x in parts[1:]])
815a13934a8083f23eb90f843451501b54042870
650,963
def reversebits4(max_bits, num): """ A classic and simple bit reversal algorithm.""" rev_num = 0 for _ in range(max_bits): rev_num |= num & 1 num >>= 1 rev_num <<= 1 rev_num >>= 1 return rev_num
154fce00496621b3733c91027f3b0ee2dad877e3
650,964
import re def decode(encoded_string): """Return plain string.""" response = [] groups = re.findall(r"(\d+[a-zA-Z\ ]|[a-zA-Z\ ])", encoded_string) for item in groups: if len(item) > 1: count = item[:-1] char = item[-1] response.append(char * int(count)) ...
02deff2ac4acee8cafe1c743515a90f1ff9c9b23
650,965
import torch def bbox_transform_opr(bbox, gt): """ Transform the bounding box and ground truth to the loss targets. The 4 box coordinates are in axis 1""" bbox_width = bbox[:, 2] - bbox[:, 0] + 1 bbox_height = bbox[:, 3] - bbox[:, 1] + 1 bbox_ctr_x = bbox[:, 0] + 0.5 * bbox_width bbox_ctr_y = ...
f5026be3a77db4d82f8f5e63717995bb0f791665
650,966
def create_macro_dict(xs_micro): """Create a dictionary with two group cross-section""" xs_macro = {} for t, d1 in xs_micro.items(): xs_macro[t] = {} for r, d2 in d1.items(): temp = [] xs_macro[t][r] = {} for n, v in d2.items(): temp.append...
df9407c29e784c2694973765610850adc6ac8ed9
650,967
def box_surface(a, b, c): """ Computes the surface area of a cuboid. a,b,c -- Edge lengths of the cuboid. returns surface area """ return 2.0 * (a * b + b * c + c * a)
ae1814a700ff184fa64f58094a5d60ed42e163ff
650,968
def get_ip_from_raw_address(raw_address: str) -> str: """ Return IP address from the given raw address. >>> get_ip_from_raw_address('91.124.230.205/30') '91.124.230.205' >>> get_ip_from_raw_address('192.168.1.15/24') '192.168.1.15' """ return raw_address.rsplit('/')[0]
07d9fa9ae41f0c84e109d925114f56a1efccbe66
650,969