content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def create_train_val_set(x_train, y_train): """[summary] Parameters ---------- x_train : [type] [description] y_train : [type] [description] """ x_val = x_train[:10000] partial_x_train = x_train[10000:] y_val = y_train[:10000] partial_y_train = y_train[10000:] ...
843dfdc3315dbccc31c0ae0c12b658c5b5a6aeca
634,808
import re def textPreprocessing(text): """ Rimozione dei caratteri speciali e conversione in minuscolo :param text: testo da preprocesssare """ text = text.lower() # conversione in minuscolo text = re.sub(r"['\",.;:_@#()”“’—?!&$\n]+\ *", " ", text) # conversione dei caratteri speciali in uno spazio text = ...
a860f2b38400d9b64c5ac7e4309fc8561f0ed40b
634,809
def construct_feed_dict(placeholders, u_features, v_features, u_features_nonzero, v_features_nonzero, support, support_t, labels, u_indices, v_indices, class_values, dropout, u_features_side=None, v_features_side=None): """ Function that creates feed dictionary wh...
cb4dfe4c548aba68e255b95e53f914777c32c04e
634,810
import requests def put_object(self, *args, **kwargs): """Upload small file. Requests pre-signed URL from CosmosID's API. Uses it to upload file to S3.""" data = dict(kwargs) upload_body = data.pop('Body') resp = None url_ = requests.get(self.surl, json=data, headers=self.header) if u...
42388a18fa8c43ad4df9209f8b8d59cee87ce99e
634,812
import os def get_file_info(filepath): """Return a file's directory and name for a file path. :param filepath: Path to file :type filepath: string :returns: File directory and file name :type: tuple """ filedir, filename = os.path.split(filepath) # filedir is an empty string when fil...
fedb2410f111751113f9bcab1066420b845f2505
634,813
def critical_events_in_outputs(healthcheck_outputs): """Given a list of healthcheck pairs (output, healthy), return those which are unhealthy. """ return [healthcheck for healthcheck in healthcheck_outputs if healthcheck[-1] is False]
38a36b0f2d3d42fb5e86ebf0ab69efbe121b576a
634,814
def align_origin(origin, w, h, align=('left','top')): """Calculates size of text box and returns an origin as if aligned from the given origin. Accepted alignments are: left, center, right top, center, bottom""" if align==('left','top'): return origin aligns = {'left': 0, 'center':...
2fbc673a309c73177251107016e7e2c8a42f469e
634,815
import inspect def _build_transform_name(lag, tfm, *args) -> str: """Creates a name for a transformation based on `lag`, the name of the function and its arguments.""" tfm_name = f'{tfm.__name__}_lag-{lag}' func_params = inspect.signature(tfm).parameters func_args = list(func_params.items())[1:] # re...
38efdf4a815a33a1d6620f16b475068b77c9d475
634,816
def decode_segment_flags(sflags: str) -> int: """Map readelf's representation of segment flags to ELF flag values.""" return ((int('R' in sflags) << 2) | (int('W' in sflags) << 1) | (int('E' in sflags)))
0cadd529840f86c1f4db5e023a0dc43a8b1c12c9
634,817
import json def pretty_literal(content, indent=2, replace_null=True): """Given content comprised of literals, render them line-by-line json lib is used instead of pretty print because subjectively it looks better """ # create a mostly-foolproof serialisation of the object content = json.dumps(con...
76a67aeab1ab1e241adc18b5d9e7999455b05ef7
634,818
def append_default_columns(start, num): """appends num string to a list as col_[index]""" columns = [] for i in range(start, num): columns.append("col_" + str(i + 1)) return columns
067e0f5f372f47ee16884e8dd34ce6ceef5e72d1
634,819
def _GetFailedRevisionFromCompileResult(compile_result): """Determines the failed revision given compile_result. Args: compile_result: A dict containing the results from a compile. Please refer to try_job_result_format.md for format check. Returns: The failed revision from compile_results, or None i...
c30a537102a785ddf2d93a98fd3e16c552048215
634,820
import urllib.request def read_url(url): """Send a GET request to a given URL and read the response. References ---------- - https://docs.python.org/3/howto/urllib2.html - https://docs.python.org/3/library/http.client.html#httpresponse-objects """ with urllib.request.urlopen(url) as res...
9b84ac0969a38b39a689780f4aa2d89108b0e6c5
634,821
def name(request): """Fixture function""" name_value = request.config.option.test_config print(name_value) return True
29286bd82118c1186c192e77e86c48b6a5fc4f8e
634,822
def k_func(h,s_H,s_K,g,n,alpha,phi,delta,k): """args:     h     (float): Human capital     s_h   (float): Investments in human capital     s_k   (float): Investments in physical capital     g     (float): Growth in technology     n     (float): Growth rate of population/labour force     delta (float): Depreciation ...
732fbea0c3c7ef2e710593f6825574a0577f1313
634,823
def agenda_format_day( number_of_days_before, date_start, cfg_today, cfg_tomorrow, cfg_in_days, ): """ Formats the string who indicates if the event is today, tomorrow, or else in an arbitrary number of day. Args: number_of_days_before (int): The number of days before th...
770fd712d0a6bf56ca8ae80132b40bc4802e4f34
634,824
import uuid def _gen_random_token(): """ Generate a random uuid4 token """ return uuid.uuid4().hex
7b17f2248b50155955a544aaab895720a20245ef
634,825
def minmax(x): """ Returns a tuple containing the min and max value of the iterable `x`. .. note:: this also works if `x` is a generator. >>> minmax([1, -2, 3, 4, 1, 0, -2, 5, 1, 0]) (-2, 5) """ (minItem, maxItem) = (None, None) for item in x: if (minItem is None) or (item < m...
f2127bf8cb6d444d97f23b147590d94265b5480c
634,826
def timepoints_beta_top( beta_w, time_w, percentage): """ beta_w: time_w: percentage: """ #Find treshold beta_index = [0]*len(beta_w) beta_ranked = [0]*len(beta_w) for i, x in enumerate(sorte...
b65314c124e0e7defa4d60c270847b9521722634
634,827
import argparse def parse_args(): """Script arguments parser.""" parser = argparse.ArgumentParser() parser.add_argument( "--mode", default="create", type=str, choices=["create", "delete", "auth"], help="Working mode", ) return parser.parse_args()
c933f1ea746d4d268b2b5c01ce791533e5a91fee
634,828
def daily_return(t_df): """ add daily return column to the data frame """ dlyr = t_df['Close'].shift(1) / t_df['Close'] - 1 t_df['Daily Return'] = dlyr * 100 return t_df
b6a1d8e5dee0dfaa4226e8c63ccc45fb7ee9f95c
634,829
import argparse def cli_to_args(): """ converts the command line interface to a series of args """ cli = argparse.ArgumentParser(description="") cli.add_argument('-input_dir', type=str, required=True, help='The directory that contains all the emojis to til...
735366548a4bc3058690c0060b2d84ccccd7d57d
634,830
def count_entities(entities, project=None, locale=None): """Count the number of entities (i.e. source strings) with the given project and/or locale.""" count = 0 for ent in entities: if (project is None or project == ent["project"]) and ( locale is None or locale == ent["locale"] ...
84d3c9837f6d8f1826bd81322628879fb960c387
634,831
import struct def read_spectrum(filestream, n): """Reads n mz and intensity pairs from existing .sbd filestream. Assumes double precision for mass and single for intensity. Returns: Tuple:tuple of mz and intensity vectors """ mzs = struct.unpack("<%dd" % n, filestream.read(8 * n))...
69727085c671d43a6be53f2af7623fe8108c1560
634,832
def clear_text(text, dictionary): """ func-deleter of special symbols :param text: input string :param dictionary: dictionary of delimeters :return: clear text """ new_text = '' text = text.lower() for key, values in dictionary.items(): text = text.replace(key, values) ...
89e3ac353a92bff8ac129f89ddeda6e1e77b46c2
634,834
import inspect def get_test_name(): """ return the name of the calling function after removing leading test_ prefix""" testname = inspect.stack()[1][3] if testname.startswith("test_"): testname = testname[5:] return testname
59672426ef5a5f1db39a69e09d589e5c1d9042da
634,835
def get_reputation(seguidores, seguindo): """calculate reputation of user""" try: return (seguidores / (seguidores + seguindo)) except ZeroDivisionError: return 0.0
3a4e94a6f832088257440ced9eeb4bb37ca81306
634,836
def crop_image(new_width, new_height, image): """ Method to crop a given input image to new width and height specifications given. Args: new_width: Width of the cropped image new_height: Height of the cropped image image: Image object to be processed Returns: The croppe...
26b447955785b988b1ff39c3199df0de8469a9a4
634,837
import pytz def local_time_obj(time, course): """ Get a Datetime object in a course's locale from a TZ Aware DT object.""" if not time.tzinfo: time = pytz.utc.localize(time) return time.astimezone(course.timezone)
27e916cbeff884d90ed4d9f5adc7ebb67ffe9866
634,838
from typing import Sequence def moving_average(source: Sequence[float], window_size: int): """ Compute a simple moving average from a source list. Arguments: source: The source list of data from which to compute the moving average. window_size: The size of the moving average to com...
83f7d3f2e20f143749e21eb4fc4ac1afa2d452e1
634,840
import logging import os def _should_allocate_port(pid): """Determine whether to allocate a port for a process id. Args: pid: int. The process ID. Returns: bool. Whether or not to allocate a port to the process. """ if pid <= 0: logging.info('Not allocating a port to inva...
71f9127893e6b32aabe2e2124d94df63f496deef
634,841
def create_feature_vector(data): """ :param data: list of one mongodb row :return: numerical list of features """ # info for normalization data_info = { "age": {"norm": 98}, "nr_person_hurt": {"norm": 3}, "nr_vehicles": {"norm": 4} } feature = [ float(data...
7c1d9465c27ebe7862b1a06e92bc941b7f0db212
634,842
def remove_sleepEDF(mne_raw, channels): """Extracts CHANNELS channels from MNE_RAW data. Args: raw - mne data strucutre of n number of recordings and t seconds each channels - channels wished to be extracted Returns: extracted - mne data structure with only specified channels """ extra...
1a96c6aff2ce8ab2c4706ebd367b318ad0562745
634,843
def minimum_grade(parsed_list, passing_grade, overall_min=True): """ This function calculates the minimum grade from the given grades. :param parsed_list: the parsed list of the grades :param passing_grade: the grade passing threshold :param overall_min: True, when calculating the minimum of all th...
2ffbecd3177964ae89be8bedf8ee7a0884affea0
634,844
def detect_faces(image, cascade, scale_factor, min_neighbours): """ Detect faces visible on the image. :param cascade: cascade object used for detection :param image: analyzed image :param scale_factor: subsequent detections scaling coefficient :param min_neighbours: minimum detection neighbours...
973d08e53c8ba58efab72855b52ba012f88c08c5
634,845
def mk_state_eqc_name(L): """In : List of states (in each eql class) Out: single state names by bashing the states separated by "_". Helper for min_dfa. Given a list of states, bash the state names together separated by an underscore. This is useful when 'verbose mode' state na...
230e1b89d4f790fe4fc741f0af56a6ba22880a53
634,846
import tempfile import os def get_temp_path(suffix='',name=None,nest=False,only_dir=False): """Return absolute path to a temporary file.""" if nest: f = tempfile.NamedTemporaryFile() f.close() dir = os.path.join(tempfile.gettempdir(),f.name) os.mkdir(dir) else: dir ...
454bf50867b58e524b2b867f69903f7713a81869
634,848
def cuberoot(x): """Finds the cube root of x""" return x**(1./3.)
64adfcc3307c42c86677c0cc405099150b92d1b6
634,849
import os def parse_extension(filepath): """ Parse file extension and return format string to make other bits aware which format driver should be used """ extension = os.path.splitext(filepath)[1][1:] extensions_dict = {"netcdf": ['nc'], "mitiff": ['mitiff'], ...
e26c76381ddca37a57b04c267dbb12fb88aa0ec5
634,850
def u_func(model,c,p_h): """ class utility function returns utility for given consumption level and housing quality stated as housing price Args: model: class attributes c: consumption p_h: housing quality stated as housing price Returns: uti...
d20d19f91d358ac62b2fd94e206d0541ae44dd0b
634,851
def config_args_missing_params(request): """ Returns Missing Keys""" return request.param
ac0cb9f7bd7ebfae20b7aa3484bb53f14aaa764e
634,852
def strip_tags(body): """Delete the first and last line if they full of hashtags. Also strip every line of unnecessary whitespaces.""" lines = body.split('\n') # remove last line if full of hashtags for word in lines[-1].split(): if word[0] != '#': break else: del li...
c05d7874cad5f76668e78b55911688afdb1865e3
634,853
def createProtein(element): """ Create dictionary representation of Protein element from Percolator XML output """ defns = element.nsmap[None] #default namespace protein = {} protein["ID"] = element.get("{{{}}}protein_id".format(defns)) protein["q-value"] = float(element.find("{{{}}}q_v...
42eb7283d61eaad68cd8e01e7a1ad0f3d4d930f6
634,855
def jdn_to_rjd(jdn: int) -> int: """Return Reduced Julian Day (RJD) number from Julian day number (JDN). :param jdn: Julian day number (JDN). :type jdn: int """ return jdn - 2400000
73abaa1138983fadf7203a0a634e4526cc87205f
634,856
def list_values(keys, dictionary): """Returns `dictionary` values orderd by `keys`. >>> d = {'1': 1, '2': 2} >>> list_values(['1', '2', '3'], d) [1, 2, None] """ return [key in dictionary and dictionary[key] or None for key in keys]
9427c8f553355579405bd3e6e98fd5af3abb207e
634,857
def get_params_fit(data_pt, params_fix): """Returns the fitted parameters a specific data point depends on.""" data_pt_params = ( ( data_pt.get_fitting_parameter_names() | data_pt.get_fixed_parameter_names() ) - params_fix ) return data_pt_params
5bb33377ac6e99537617997c9ac37e69fa73981b
634,858
def _re_word_boundary(r): """ Adds word boundary characters to the start and end of an expression to require that the match occur as a whole word, but do so respecting the fact that strings starting or ending with non-word characters will change word boundaries. """ # we can't use \b as it c...
bdd97d11f610c11380323ecacd9351d0be1c29a4
634,859
import argparse def parameter_parser(): """ A method to parse up command line parameters. By default it gives an embedding of the Facebook food network. The default hyperparameters give a good quality representation and good candidate cluster means without grid search. """ parser = argparse.Argume...
b10a284904114ea204d688c87f3eaa4ebadfefa4
634,861
def _n(self, paper, collection): """Exclude the paper from the collection""" collection.exclude(paper) return True
5a20e4190d0f1a0a68840c9c85a6c0937ff08600
634,862
import re def split_documents_by_feature_value(input_dict): """ Split Annotated Document Corpus by conditions with features and values. :param adc: Annotated Document Corpus :param feature_condition: split condition. :param discard_filtered_out default-false: discard documents that do not fulfil...
2eec11d18110f5602be189131c6a9d55e39bd524
634,863
def get_properties(schema): """ Return the three properties we have to enforce for this schema. Returns tuple of (enforce, default, and required), where enforce is a custom function, default is the default value for this attribute, and required is a boolean. """ if isinstance(schema, dict): ...
e0dbe110138aad66277b68c8b1f896dd66f735a0
634,864
from typing import Optional def _get_reasonable_file_label(uri: str) -> Optional[str]: """ Get a label for the dataset from a URI.... if we can. >>> uri = '/tmp/some/ls7_wofs_1234.nc' >>> _get_reasonable_file_label(uri) 'ls7_wofs_1234.nc' >>> uri = 'file:///g/data/rs0/datacube/002/LS7_ETM_NBA...
1d01642355bf1ba557fd67bf14cfaf7351373cda
634,865
import re import operator def tokens_with_special_characters(errors_summary): """ References: :func:`get_errors_summary` Args: errors_summary (dict): Returns: dict: sorted dictionary """ errors = list(errors_summary.keys()) special_characters = [] for error in...
23eec2e58d397a15b98c71add531f95982a1d264
634,866
def parse_weather(path:str, log): """ Parses weather data file. """ assert isinstance(path, str), 'File path must be a string!' result = [] with open(path, 'rt') as file: next(file) # skip header for index, line in enumerate(file): log.info(f'{line.strip()}') ...
7005eef3bd3c13e7fbb930febb5688f390a3b697
634,867
import os def get_version_info(): """Extract version information as a dictionary from version.py.""" version_info = {} with open(os.path.join("refcycle", "version.py"), 'r') as f: version_code = compile(f.read(), "version.py", 'exec') exec(version_code, version_info) return version_inf...
0cf70bdc682f6c9239fc9e1d4598ec1520f68ad7
634,868
def format_year(year): """Formats a year to a "yyyy" format if input is less than 100. Args: year: user input year Returns: A ValueError if the input is not a digit, or the year in yyyy format. """ if not(year.isdigit()): raise ValueError if(len(year) != 4): ...
b837db55afcddf21474b99fbafef868d846bf533
634,869
def evaluate_game(mine, yours): """Determine who won the game based on the two strings mine and yours_lc. Returns three booleans (win, draw, void).""" ### Return with void at True if any input is None try: mine_lc = mine.lower() yours_lc = yours.lower() except AttributeError: ...
80b246d8569e9186b7b40fe75e052b320a710f81
634,870
def build_tokens_paddings_from_ids(text_ids, max_seq_length, cls_id, pad_id): """Build token types and paddings, trim if needed, and pad if needed.""" ids = [] paddings = [] # [CLS]. ids.append(cls_id) paddings.append(1) # A. len_text = len(text_ids) ids.extend(text_ids) paddi...
360a3b34d8192b45e3c842b0df56370815e208f9
634,871
def merge(nums1, nums2): """ Merge two given sorted arrays by merge sort :param nums1: first array :type nums1: list[int] :param nums2: second array :type nums2: list[int] :return: merged array :rtype: list[int] """ result = [] i = j = 0 while i < len(nums1) and j < len(...
4ec45d0c65bb85f45d9b8266bba268ace22177f6
634,872
def is_audit_type(*args): """This audit is included in the specified kinds of audits. :param *args: List of AuditTypes to include this audit in :type args: List[AuditType] :rtype: Callable[Dict] """ def _is_audit_type(audit_options): if audit_options.get('audit_type') in args: ...
8ad52d1313f3529f8bb2aef10ccbbf31d0f2dfba
634,873
def eye(dimension): """return identity matrix as `list` of "vectors" (lists themselves)""" m = [dimension * [0] for i in range(dimension)] # m = N * [N * [0]] fails because it gives N times the same reference for i in range(dimension): m[i][i] = 1 return m
85ce3b2e3f5d274a6fdce16bac078c59fb377960
634,874
def count_blocks(documents): """ Counts the total number of blocks in a list of documents Args: documents(metadata.MetaDocument): The list of documents Returns: int: Size of the list """ return sum([len(doc.blocks) for doc in documents])
947a051478a2202c5880a678cdf6ab7fd4a33958
634,875
def get_day_offset(day, number): """ Returns an integer representing the day number shifted by the given amount """ day -= number if day < 0: day += 7 return day
6713f43144993f14b56626539bf2f10f17fd722d
634,876
import os def getOutputnameFromInputname(inname): """ replace the extension .F with .f90 """ basename, extension = os.path.splitext(inname) outname = "%s.%s" % (basename, "f90") return outname
a05d1f656783c65f61a1bf6528f9d8e6ce16134b
634,877
def default_representer(dumper, data): """Default representer""" return dumper.represent_str(str(data))
1503fd802355d68161c01f7c1ba6cdf7b88535eb
634,879
def comma_str(n, decimal_spaces=0): """ :param n: 수치 (문자열 또는 수치형) :param decimal_spaces: 소수점 자리수 """ try: if n is None: return None if decimal_spaces > 0: n = float(n) else: n = int(float(n)) if isinstance(n, int): retu...
0d1e77849c95728ba6767d5afc830414633dbd9c
634,880
def singleton(name: str) -> object: """ Factory function to return a string singleton. :param name: The name of the singleton. """ name = str(name) class Singleton: _singleton = None def __new__(cls): if Singleton._singleton is None: Singleton._singleton = super().__new__(cls) return Singleton._...
1c108b670fb159d7c27ce1d9bb073561f4815000
634,881
import pathlib import subprocess def create_index( path:str): """Checks if a .fai or .bai file exists else creates one with samtools. path """ if pathlib.Path(path).suffix == '.fa' or pathlib.Path(path).suffix == '.fasta': if not pathlib.Path(path+'.fai').is_file(): subproc...
4702de2bcca089450ef070b0697ae3ba21b0718e
634,882
def is_logged_in(soup): """ checks from code snippet whether user is logged in phpbb signatures Not Logged in <a href="./ucp.php?mode=login" title="Anmelden" accesskey="x" role="menuitem"> <i class="icon fa-power-off fa-fw" aria-hidden="true"></i><span>_log on message_</span> ...
5aa165ac70110eb46316841bcf3a91145a5f39f1
634,883
import uuid def generate_uuid(length): """Generates hex uuid with customized length. Example: d9f3a7e8 Args: length (int): number of digits of uuid """ return str(uuid.uuid4().hex)[:length]
f3526392cb968bc1eb6ccdf84f262a34320960eb
634,884
import re def normalize_whitespace(string): """Normalize whitespace in string Deletes consecutive spaces and newlines """ return re.sub("\n+", "\n", re.sub(" +", " ", string))
88d6ece45f2d1c538fcde17e6ed26f4cea617aaf
634,885
def get_api_key(filepath): """Read a local file with your API key.""" api = [] with open(filepath) as f: for line in f: api.append(line.strip()) assert len(api) == 1, "API key should be only one line long." return api[0]
26ebc04945d561a73e09a546d65da922444dcff5
634,886
def clean_pct_col(x): """ Converts percent column to numeric, replacing ND with NA. """ if isinstance(x, float) or isinstance(x, int): return x elif 'ND' in x or '< LOQ': x = 0 else: x = x.replace('%', '') return float(x) # x = x.replace('%', '') # if 'ND' in...
a0fb4385622cc9d6b77bcaf96ba22ed49e5f5806
634,887
def count_non_ascii_chars(file_path: str) -> int: """Counts non ascii characters and returns their amount. Args: file_path: the pathname (absolute or relative to the current working directory) of the file to be opened. Returns: amount of non ascii characters. """ amount = ...
7401779ddab968b9793f988fd04d90043a95ce5a
634,888
def ema(values, n): """Calculates actual value of exponential moving average of given series with certain length. :param values: list of floats :param n: int ema length :return: float actual ema value """ ema_list = [] sma = sum(values) / n multiplier = 2 / (n + 1) # EMA(current) =...
0c2aacf516423a2fbf1f7844db985aa6a0b70d06
634,889
def sample_var_var(std, n): """ The variance of the sample variance of a distribution. Assumes the samples are normally distributed. From: //math.stackexchange.com/q/72975 `std`: Distribution's standard deviation `n`: Number of samples """ return 2.0 * std ** 4 / (n - 1.0)
12b86fdfd244255d0e0df58633ebf1e2cd249e8a
634,890
from datetime import datetime import time def convert_date_to_timestamp(argument): """ helper to create the timestamp :param argument: :return: """ argument = argument.replace('Z', '') argument = argument.replace('T', ' ') d = datetime.strptime(argument, '%Y-%m-%d %H:%M:%S') unix...
d03400f73c3b7c6afdd7874443492e8596ae0def
634,892
import argparse def arg_parse(): """ Parse arguements to the detect module """ parser = argparse.ArgumentParser(description='Food Recognition System') parser.add_argument("--image", "-i", dest='image', help="Path of image to perform detection upon", type=str) parser...
1c3e5db1a7069187fe5d08e111035809517de645
634,893
def load_table_file(path_table, encoding='utf-8') -> dict: """テーブルを読み取ってインスタンス生成""" # ファイル読み取り try: with open(path_table, mode='r', encoding=encoding) as f: lines = [line.strip() for line in f.readlines()] except UnicodeDecodeError: try: with open(path_table, mode...
640fb65c8be1d1d355c448799484c4a54f9c5d9e
634,894
def cached_func(f): """ Used for cache property funcs in class to work with Jinja2. """ func_name = f.__name__ property_name = "_%s" % func_name def wraps(self): if not hasattr(self, property_name): setattr(self, property_name, f(self)) return getattr(self, property_...
a4aa161a5dec6c4e73a74deaef1ee507d3a975de
634,895
def seek_other_edu_child(nodes, source, exclude, block): """ Recursive function to find some child of a node which is an EDU and does not have the excluded ID :param nodes: dictionary of IDs to NODE objects :param source: the source node from which to traverse :param exclude: node ID to exclude as t...
382b253c97e4dc543f89ccf812436c3b72791d86
634,897
import os def try_list_dir(d): """ Return a list of files in a directory """ try: return os.listdir(d) except BaseException: return []
9821dcb42a0f7133ecd9da5ed1773642bc99887f
634,898
import re def is_input(line): """ Determines whether or not a read in line contains an uncommented out \input{} statement. Allows only spaces between start of line and '\input{}'. """ #tex_input_re = r"""^\s*\\input{[^}]*}""" # input only tex_input_re = r"""(^[^\%]*\\input{[^}]*})|(^[^\%]*\\in...
90c1781b4b1355458fd79aa39b14987ec080840f
634,899
def cleanwrap(func): """ Wrapper for Zotero._cleanup """ def enc(self, *args): """ Send each item to _cleanup() """ return (func(self, item) for item in args) return enc
431aa3f731835d3f9e3520932a6b97479b93da85
634,900
def prepare_time0s(exps_df, dbg_prnt=False): """ We take situations in which Group = Time0 and make the short of that row also Time0 Args: exps_df (DataFrame): Should contain cols 'Group', 'short' """ # if Group = Time0, it is a Time0, even if "short" has a different d...
61838d812ae359b7501caa018fbdda253fa7c6c6
634,901
def DoSlash(sDirName): """Add a tailing slash if missing. """ return sDirName if sDirName[-1]=="/" else sDirName+"/"
a61b8cc4b901ebf69ac5223c642c42d347160faf
634,902
def create_bucket_list(domain, affixes=[]): """ Create a set of buckets based on a domain name and a list of affixes. Note: This will be very large. Args: domain (str): Domain to add affixes to, such as google.com regions (list): List of AWS regions to query against. affixes (...
519d33445f022b475385bf1b99efd5a00c1fe464
634,903
import secrets def get_random_number(min: int, max: int) -> int: """ Gets a random number between min and max inclusive. """ rand = secrets.SystemRandom() return rand.randint(min, max)
51c247f09521afa9257b3b347ec7b566e2474569
634,904
from typing import OrderedDict import copy def filter_entries(d, p): """Separate the new entries from the old/previously created ones""" new = OrderedDict() old = OrderedDict() for k, v in d['ipam'].items(): for s in v['schema']: # check if there is a previous allocation for the cu...
ace10f76f82d02c1a8c4a58b856dcd0ecb0e57e9
634,905
import math def round_decimals_up(number, decimals=2): """ Returns a value rounded up to a specific number of decimal places. """ if not isinstance(decimals, int): raise TypeError("decimal places must be an integer") elif decimals < 0: raise ValueError("decimal places has to be 0 o...
5a5a305d81b05e25437d96d7d45e7902df2a2494
634,906
def get_minmax_size(bbox): """Get aspect ratio of bbox""" ymin, xmin, ymax, xmax = bbox width, height = xmax - xmin, ymax - ymin min_size = min(width, height) max_size = max(width, height) return min_size, max_size
2a1cdf69901e29d31df242826302ca3a3842ceea
634,907
def check_inputstring(inputstring): """check data integrity""" return inputstring
c8f2d04795f870443c99c4fddb65df7f75d9e3d2
634,908
import os def path_a_in_b(a, b): """ Not considering symbolic links... be careful with them. """ aa = os.path.normpath(a) bb = os.path.normpath(b) return aa.startswith(os.path.abspath(bb) + os.sep) or aa == bb
36331b9f4bd89ae290fee1e3d67714f9642267f0
634,909
from typing import List def disjunction_for_group(lines: List[str]) -> int: """ Returns the number of questions one group answered "yes" to, given the lines of input for that group. """ assert all(line.isalpha() for line in lines) return len(set(c for c in "".join(lines)))
d83ab53da86e67e98448d3f5d99cf4174bb62204
634,910
import logging def get_logger(name): """Set logger configs with name. :param name: :return: """ log_format = '%(asctime)s - %(name)8s - %(levelname)5s - %(message)s' logging.basicConfig(level=logging.INFO, format=log_format, filename='setup.log'...
30c98813331c392b344bcc71ab8011890891aca3
634,911
import optparse def scanOptions(): """Handle all options, remove them from sys.argv.""" global g_option_fn # This automatically implements the -h (--help) option. parser = optparse.OptionParser() add = parser.add_option add('-a', action='store_true', help='all (default)') add('-c', action=...
8afc1438fc7325456663902fd962e0286e777815
634,912
def split_bytes(ary: bytes, length: int) -> list[bytes]: """バイト配列をlengthごとに区切る""" return [ary[i: i + length] for i in range(0, len(ary), length)]
823c3e24b3334df6720589a992a4d6690f526d7b
634,913
def computeLastHitValues(blocks): """ given the query length and 'blacks' sting from a last hit return the: match length the blocks string looks something like this: "73,0:1,15,0:1,13,0:1,9" where integer elements indicate lenghts of matches and colon separated elements ...
7223e9d79a6cda29603d662d0c35f099ec11cdf2
634,914
import itertools def xor(message, key): """Return ``message`` XOR-ed with ``key``. Args: message (bytes): Plaintext or cyphertext to be encrypted or decrypted. key (bytes): Encryption and decryption key. Returns: Plaintext or cyphertext as a byte string. """ return bytes(m...
81e4a38aa55db4c97ef37810dee89013f4db1c74
634,918
import itertools def product(l1, l2): """ Returns all possible combinations of entries in two arrays Args: l1 -- list<str> l2 -- list<str> Returns: iterable """ return itertools.product(l1, l2)
b7bd8e67f52cf95c0fd4d489597be5fa83bcad3d
634,919