content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def filter_lines(infile,outfile,wind,nskip=0) : """ Read from input linelist file, output comments and lines falling in windows of [w1,w2] to outfile Args : infile (str) : name of input file outfile (str) : name of output file wind (list of [w1,w2] pairs) : list of window ranges ...
e6b5687f8cc18732fc5b2add132d4bad88d3e3a7
657,017
def read_file_as_str(filepath): """ Reads the file content Args: filepath (str): File to read Returns: str : File contents in string """ with open(rf"{filepath}") as fd: content = fd.read() return content
515d3316485d9608fdb63b447a562b6175a902e0
657,018
def tile_key(layer, coord, format): """ Return a tile key string. """ name = layer.name() tile = '%(zoom)d/%(column)d/%(row)d' % coord.__dict__ ext = format.lower() return str('%(name)s/%(tile)s.%(ext)s' % locals())
7307c97bec1743818243530342655346d5f0cd4f
657,019
def numpy_fixlen_strings(x): """ Returns new array with strings as fixed length >>> from numpy import rec >>> x = rec.array([(1, 'Alice', 100), (2, 'Bob', 200)], ... dtype=[('id', 'i8'), ('name', 'O'), ('amount', 'i8')]) >>> numpy_fixlen_strings(x) # doctest: +SKIP rec.array([(1,...
34b3470b65ccbb3a38e62247138c2ce16b79bd33
657,020
import os def package_scripts_directory(): """ Get the package scripts directory Returns str The path to the directory containing the package scripts """ module_directory = os.path.dirname(__file__) script_directory = os.path.join( module_directory, 'package_script...
203a1a4f983e43dc7e00c275a58a08fe612fe386
657,021
from typing import List from typing import Any from typing import Tuple def index_2d(seqs: List[List[Any]], target: Any) -> Tuple[int, int]: """Finds the first index of a target item within a list of lists. Args: seqs: The list of lists to search. target: The item to find. Raises: ...
2129616317c090bde73c56a7420574e0fd2e3208
657,024
def get_count(results): """Creates a dictionary, word being the key, and word count being the value""" counts_dict = dict() for word in results: counts_dict[word] = counts_dict.get(word, 0) + 1 return counts_dict
2ceb1fcf08704b6a5feb579a6ad1ada2cb33ba7d
657,026
def _get_furniture_info(furniture_obj_filepath): """obj file parser""" with open(furniture_obj_filepath, "r", encoding="utf-8") as f: lines = f.readlines() axis2width = {} for line in lines: if line.split()[0] == "###": axis2width[line.split()[2]] = float(line.split()[3]) ...
09f568aa83a1992a157696091edf37eb8e72ae48
657,027
import os def get_fixture_name(filename): """Strips extension from filename when building fixtures dict key.""" return os.path.splitext(filename)[0]
8cf968e153ee60267c37e37e48d215bf0d7c4304
657,029
import struct def memory_read(dev_file: str, address: int, length=1) -> tuple: """ reads bytes from a rc2f memory file @param dev_file: the memory to use @param address: where to read @param length: how many bytes to read @return: the read bytes as a tuple @rtype: tuple """ with op...
3afa015e4eb9d5702d0fa483f04b3f1c4f261567
657,031
def is_the(t): """Whether t is of the form THE x. P x.""" return t.is_comb('The', 1)
9497390fb75047db4a7fc35fe41a1e0b63af3177
657,033
def parse_annotation(txt_file, prefix='annotation'): """Parse Prokka summary text file.""" results = {} with open(txt_file, 'rt') as txt_fh: for line in txt_fh: line = line.rstrip() key, val = line.split(":") results[f'{prefix}_{key}'] = val.lstrip() return re...
bdc83519fa9c2d0bc771d2db3f2f08f7017b04e4
657,034
def sanitize_input(input_data): """ check if input is of alphanumeric characters """ if input_data.isalpha() == False: return False
c3c7f0c59f5998087a3d6cfb40fb4d28f8a47a42
657,035
def get_modeling_realm(uid): """ return modeling realm """ return uid.modeling_realm
c18525805d70735d13d98efa975b1e106d2fdd3b
657,036
def prefixing(prefix, stem, space): """ Add the prefix to the stem based on the space that has been chosen Parameters ---------- prefix : str A prefix string stem : str A stem string space : str The type of space chosen by user Returns ------- list ...
50791ce3d2c3abf7ecd6845a503ba0e0b7072a8f
657,037
import sys def build_index(old_index, sermons): """Run checks, assign IDs, build final document.""" audio_to_old = {d['audio']: d for d in old_index['sermons']} new_id = max((d['id'] for d in old_index['sermons']), default=0) sermon_list = [] nupdated = 0 audio_to_new = {} for sermon in se...
21062776fa9465c3a021b2bf5edc32ff8e7e8b68
657,039
def add_documents(dict, preprocessed_collection): """ Update dictionary from a collection of documents Notes: input collection must be an iterator (iterable of iterable) of preprocessed documents """ return dict.add_documents(preprocessed_collection)
05031ec28bd11baa133f3494aa22710b2deef5e3
657,040
def dt_to_str(dt, fmt='%Y-%m-%d %H:%M:%S'): """ datetime转换为字符串 :param dt: datetime :param fmt: 字符串格式 :return: """ return dt.strftime(fmt)
e92537766c4da60bfbfa6bdbd824b9320aafa758
657,041
def isuser(username: str, server: str) -> bool: """Always returns true, because no jwt is given. There is no way to determine if a user exists or not here. """ return True
c10c4ecee7b83f6f9f145ce42282da8ad040396a
657,042
def slau_inp_matr(): """ Функция возвращает матрицу, введённую пользователем с клавиатуры. Returns ------- a : [[float, float, ...], [float, float, ...], ...] Матрица, введенная пользователем """ while True: try: m = int(input('Сколько будет ст...
fbacb4ba76d09de78c9f59cbe17c4d7af04a6a32
657,043
def length(database): """Computes the total number of tuning entries""" num_tuning_entries = 0 for section in database["sections"]: num_tuning_entries += len(section["results"]) return num_tuning_entries
eb82ca660593d8bc17fac3fab5cba67411e7cf15
657,045
import math def traffic_count(tracks_msg, size, list_classes, polygon_mask_first_and_second, first_list, second_list, up_count, down_count, car_head_passtime, car_speed): """ 统计通过碰撞线的数量。 :param tracks_msg: 追踪话题 :param size: (x, y) :param list_cla...
49ad08ef0abef6539b35e12600b17e1f43bf2485
657,046
def hello(): """Some Comment""" return 'Hello, greetings from different endpoint'
a56f607a78ed4db48675f48bb6d2ab4047cd1138
657,047
def eval_e_x_polarized_using_e_x_unpolarized(e_x_unpolarized): """Decorator function for computing e_x for spin polarized case. The spin-scaling relation for exchange energy is used: e_x(rhoa, rhob) = 0.5 * (e_x(2*rhoa) + e_x(2*rhob)) Args: e_x_unpolarized: function to evaluate exchange energy density ...
ea79e88a541331d2aee80dc4b558135d1b5887ea
657,048
def minRefuelStops_DP( target_distance: int, start_fuel: int, stations: list[list[int]] ) -> int: """1-D Dynamic Programming DP_table[num_stops] the furthest distance (== max gas) that we can get with num_stops times of refueling. So for every station, stations[i], if the curre...
af445b1af66e2758eb5a7f9ac0032a90b60963db
657,049
def mlf_to_dict(inmlf): """ loads htk-style mlf file into dictionary """ label_dict = {} mlf_length = len(inmlf) mlf_idx = 1 while mlf_idx < mlf_length: mlfline = inmlf[mlf_idx].rstrip() assert '.lab"' in mlfline segname = mlfline.split(".lab")[0].lstrip('"') mlfline ...
44c42dfe1e0f4331fe2469bff1896d580c9d13c4
657,050
def find_intersection(val, arr): """ The x locations for the horizontal line segments""" lower, upper = -1, 0 for a in arr: if a > val: return lower-0.5, upper+0.5 lower += 1 upper += 1 return lower, upper
47782350272387aa0ec9fffce7b1b1af1ad84ec0
657,051
import torch def generate_grids(fh: int, fw: int) -> torch.Tensor: """generates grids using given feature map dimension Args: fh (int): height of the feature map fw (int): width of the feature map Returns: torch.Tensor: fh x fw x 2 as x1,y1 """ # y: fh x fw # x: fh x ...
50e22caa38522f9f369e745fa025927eee472413
657,052
def fund_name_from_manager_list(fund_code, achievement_list): """每个管理者都会管理很多基金,找到当前这个基金并返回名字""" for fund in achievement_list: if fund.get("fund_code") == fund_code: return fund["fundsname"] return ""
2e04ae9c0853bd67b51b4a62b2645c5066f4d312
657,053
def normalize(position): """ Accepts the 'position' of random precision, and returns the block which contains that position Params ------- position: tuple of the len(3) then Returns: ------- block_position: tuple of ints of len(3) """ x, y, z = position x, y, z = (int(round(x))...
3f22b5350183876d9a0da8f76bbf9cd67b8d38cb
657,055
def even_chars(st): """ Finds all the even characters in a string. :param st: string value. :return: a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than two characters or longer than 100 characters, the function should return "invalid str...
9883e3e480767ead87973d6001615876eb69c993
657,056
def preprocess_y_data(df): """Preprocess the dependent variable Args: df ([type]): whole dataframe containing both x and y and all one hot encoded input Returns: [type]: One inter and one text output + onehot encode in one column """ df['Sentiment'] = df['Positive'...
db36840d1e2e66bc11f998e4694e6ebc1178b2a2
657,057
import subprocess def run_command(args): """Runs a program from the command line and returns stdout. Args: args: Command line to run, as a list of string parameters. args[0] is the binary to run. Returns: stdout from the program, as a single string. Raises: Exception: the program exit...
8a8b8c5a0e8029274eb5729f3003eadb39dc60a1
657,058
def genes(dlib, labels): """ Extract genes at each position """ gl = {} for design in dlib: for x in dlib[design]: if x.startswith('g'): m = x.split('_') gid = 'g_'+m[0] if gid not in gl: gl[gid] = {} gl[...
d68713dac6f38032927fe133cafd9ca48e95aa3f
657,059
def factorial(x): """ [Definition] 对x做阶乘,return each element's factorial of x,x: 1-dimension ndarray [Category] 数论 """ return 'factorial(%s)' %x
6562c81da66e93982e54b4509498ef5856df63cc
657,061
def not_yet_found(input_site, d_tracker): """if site has not yet been found, return True, else False""" if input_site not in set(d_tracker.keys()): return True # not yet else: return False
4e78d8c000ff67303982d3a31fbc3af22e1d5f6c
657,062
import os import tempfile def get_workspace(test_id='test') -> str: """ Return a temporary workspace for the tests. """ workspace_root = os.environ.get("PLIST_TO_HTML_TEST_WORKSPACE_ROOT") if not workspace_root: # if no external workspace is set create under the build dir workspace_root = ...
f7699d660bfe04b391cf5dfe4e450f8e48edc6e0
657,063
def get_num_shards(path): """Get number of shards in sharded dataset.""" return int(path.split('@')[-1])
aac36b741cae2eb9fec605ddcc05e35afb78e844
657,064
import os def _c_optimizations_required(): """ Return a true value if the C optimizations are required. This uses the ``PURE_PYTHON`` variable as documented in `use_c_impl`. """ pure_env = os.environ.get('PURE_PYTHON') require_c = pure_env == "0" return require_c
dc5e052cff5976fac0579c9b91494d94cba39e98
657,065
def _get_value_indices(names1, names2, lookups): """ >>> _get_value_indices(['foo', 'bar', 'baz'], ['foo', 'bar', 'baz'], ... ['bar', 'foo']) [1, 0] >>> _get_value_indices(['foo', 'bar', 'baz'], ['FOO', 'bar', 'baz'], ... ['bar', 'FOO']) [1, 0] >>> _...
1251056d1b6e72b75c97273fcaee05be12ec1de5
657,066
def get_db_fav_users(ref, read_db): """ Each fav list that we want to change will require a fetch of the current db details. """ ffset = set() ff_recs = read_db.get_favs_for_story(ref) if ff_recs: ffset = {int(x.code) for x in ff_recs} ff_recs = None return ffset
a898512c17281c91476a7328d4627362fc0d7501
657,067
def _str2hours(datetime_string): """Converts excel datetime format to decimal hours. Parameters ---------- datetime_string : (string) Returns ------- time_in_hours : (float) """ # If over 24 hours, will convert 'date HH:MM:SS' to 'HH:MM:SS' # and store number of h...
986088ce995387746aea2cd71267d3a77adf283f
657,068
def byte_to_human(size): """Transform the size in bytes into the appropriate unit of measurement. :param int size: Size in bytes. :return: Actual size in B/KB/MB/GB. :rtype: str """ try: size = int(size) except ValueError: return (0, "B") um = "B" if size < pow(2, 2...
0cb578eb7415030576cf65dd3ddc3f5dd0b35e08
657,069
def from_submission_status_annotations(annotations): """ Convert back from submission status annotation format to a normal dictionary. Example:: submission_status.annotations = from_submission_status_annotations(submission_status.annotations) """ dictionary = {} for key, value in annot...
faee99cb8359634e796595258df084bbd7ed762d
657,070
def get_all_(gen): """ An advanced fucntion using generator to get all entry eids. """ i = gen() eids = [] try: while True: eids.append(i.next()) except StopIteration: pass finally: return eids
26abf510a86e88ed3b97c69d2ff7bed9e54feaf1
657,071
def set_version(zodb_root, version): """ Sets the version """ zodb_root['database_version'] = version return zodb_root
60fdce9c19124ab5e60df982d761e2055f8bba3f
657,072
def check_sum(card_number): """ This function will return true if the sum of all digits in the string card_number is evenly divisible by a magic_number, 10 :param card_number: str :return: bool """ total = 0 magic_number = 10 for i in range(0, len(card_number)): if card_number[i...
0f5581a48aa7bbaeb18af5832ed471a1eb69ad03
657,073
def flattenList(S): """ Convert a multi-dimensional list, into 1-dimensional """ if S == []: return S if isinstance(S[0], list): return flattenList(S[0]) + flattenList(S[1:]) return S[:1] + flattenList(S[1:])
51ebb32d8560c23c340fca7238977e3b26e45f23
657,074
def get_patched_apps(themes, plugins, apps): """ Patches in the active themes and plugins to the installed apps list provided by settings.py """ return plugins['active'] + [ # Theme first so it has template priority! themes['active'] ] + apps
f767857d2e2384bacf7fd58196e6103a29029cb4
657,075
def P(seq, text): """片段在整体文本中的概率""" # return text.count(seq) / C(wordLen(text), len(seq)) return text.count(seq) / len(text)
999df8a81d500ed393e662a4040233180ebda67d
657,076
import math def permutations_calculator(n, r=1): """Returns the full range of permutations for the instance's edges. This is used by the solve method to exhaust the permutations generator without going over the maximum number of permutations.""" return int((math.factorial(n)) / (math.factorial(n - r)))
fec7855e2e649d31e1ced172445905d1e484d1f2
657,077
def align_data(data_frame, partial_order): """ :param data_frame: pandas data frame with column names :param partial_order: partial order :return: pandas data frame aligned w.r.t partial order """ partial_order = partial_order columns_titles = [var for var_set in partial_order for var in var...
2416ebbe14094a3f87bf4c05d4a47ed2441def3d
657,078
import random def sort_by_lenght(words): """ (basic DSU example) 1. Build a list of tuples with word lenght and a random number as sort keys 2. (reverse) sort the list 3. Extract the (now sorted) elements of the original sequence """ l = [] for w in words: l.append((len(w), ran...
8c72b4ea7def6a31eb07d4f81ef11161cd12657c
657,079
def always_translate(word, T): """ Always translate like there is no default language. Restore the state of T before returning. @param word: Word or text translate. @param T: The usual "T" translator. @return: The text translated. """ current_languages = T.current_languages try: ...
ba63624b36c756dac44af7d7dda1bae7fa53448c
657,080
def euler_problem_2(n=4000000): """ Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four milli...
31b5601162e98fbd02b19fb2ec09aac7de85eae4
657,081
import pytz from datetime import datetime def convert_to_utc(localtime, timeformat): """Convert local time of Europe/Brussels of the API into UTC.""" if localtime is None: return None if timeformat is None: timeformat = "%Y-%m-%dT%H:%M:%S" localtimezone = pytz.timezone("Europe/Brussels...
58adffc2843bfc88a7f0f9b7bb9becec93cd67bc
657,082
def half(x: float) -> float: """Half the value""" return x / 2.0
da3ec8aeca71e88055fd9cd2d73d4e6290b16f35
657,083
def get_valid_init_tree(trees): """Returns first NewickTree entry that is not NoTree""" for i in range(len(trees)): if trees[i] == "NoTree": continue else: return trees[i]
69841abe1e8720c42104a961e8165306b399f710
657,084
import sys import unittest def find_test(): """ The layer support in :class:`nose2.plugins.layers.Layers` optionally supplies the test case object to ``testSetUp`` and ``testTearDown``, but ``zope.testrunner`` does not do this. If you need access to the test, you can use an idiom like this:: ...
9ae1426dec6dede49a03ded0afebe97bdd8ec0d4
657,085
def dict_remove_none(_dict): """ Removes key-value pairs from a dictionary where the value is `None`. Does not handle nested dictionaries. :param _dict: `dict` :returns: `dict` """ return {k: v for k, v in _dict.items() if v is not None}
1a3fe2478c1945aa5cadb29f15602820e742d354
657,087
def lovibond_to_srm(lovibond: float) -> float: """ Convert from Degrees Lovibond color system to Standard Reference Method (SRM) color system. """ return 1.3546 * lovibond - 0.76
306907abaa1ccc5bd3f8f94c560b72571851425f
657,088
def abs(x): """Absolute value""" return abs(x)
34570bb1f75211a95e74f749c5a7259ba6631535
657,089
import random def fermat_primality_test(p, s=5): """ a^(p-1) ? 1 mod p Input: prime candidate p and security paramter s Output: either p is a composite (always trues), or p is a prime (with probability) """ if p == 2: return True if not p & 1: # if p is even, number ca...
9df8d1bbc16c885006ffeb5585b3c30ddf2895ae
657,090
def parser_shortname(parser_argument): """Return short name of the parser with dashes and no -- prefix""" return parser_argument[2:]
9827697680cab831f0c0a435e743955a3ede1859
657,091
def retrieve_actor(world, bp_regex, role_name): """ Retrieves the actor from the world with the given blueprint and the role_name. Args: world: The instance of the simulator to retrieve the actors from. bp_regex: The actor's blueprint to be retrieved from the simulator. role_name: T...
ffda48e81ee56ccee1ab2ee2dac851b5035f381b
657,092
import numpy def mean_average_precision(logits, target): """ Compute mean average precision. :param logits: 2d array [batch_size x num_clicks_per_query] :param target: 2d array [batch_size x num_clicks_per_query] :return: mean average precision [a float value] """ assert logits.shape == ta...
d1ce8c00fd6089f49dee4e7523440936a6cb1426
657,093
def part1(depths): """ Count the number of times a depth measurement increases from the previous measurement How many measurements are larger than the previous measurement? """ depth_increases = 0 previous_depth = depths[0] for depth in depths: if depth > previous_depth: ...
56c5dd124d1dfa83ff5aaf6c5570e96fa38cafd7
657,094
def sumascii(a: str): """Convert a to code points, then sum""" return sum(bytes(a, encoding="utf-8"))
d675856a9d2504692f08bab3a2cb22e56b28ecb3
657,095
import torch def convert_to_one_hot(index, action_size): """ Converts a given input to a one hot vector Parameters ---------- index: int index of the one size: int size of tensor Returns ------- torch.tensor output tensor one hot """ one_hot_action = torch.zeros((1, action_size)) one_hot_action[0]...
ced45e296c9856eddaf9d94dbe59348cb456bb4d
657,096
import functools import asyncio def asyncTestOfProcess(asyncProcessFunc=None) : """ The asyncTestOfProcess **decorator** expects as an *argument* an async coroutine which runs a long running asynchronous *process* to be tested. The asyncTestOfProcess *decorates* another async coroutine containing the *test...
314c1004b4b11f771d7d36712b324db9d987b70e
657,097
def tree_search(branching_list, start=[[]], branch_index_test=lambda x: True, member_test=lambda x: True, combination_func=None): """ A general tool for figuring out all the ways to combine a bunch of lists. Say we have branching_list = [['a', 'b'], ['c', 'd']]. Then tre...
bf3d944cffcf7592b7d7ff2f44aed536d8fc9875
657,098
import json import base64 def base64_to_dict(byte_string): """ :param byte_string: base64 encoded string :type byte_string: str :return: python dictionary decoding of byte_string :rtype dict """ return json.loads(base64.b64decode(byte_string).decode('utf-8'))
9258a648ea1021e0a45dbf13535c3a9d300c503f
657,099
def get_placesWithMissingTokens(t, net, marking): """ Get places with missing tokens Parameters ---------- t Transition to enable net Petri net marking Current marking """ placesWithMissing = set() for a in t.in_arcs: if marking[a.source] < a.weig...
4d606c82f888d63425db8ead36f5bbf8413cadfe
657,100
from pathlib import Path def create_task_name(path: Path, base_name: str): """Create the name of a task from a path and the task's base name. Examples -------- >>> from pathlib import Path >>> create_task_name(Path("module.py"), "task_dummy") 'module.py::task_dummy' """ return path.a...
5b9b2e84c3f0a08eab41ac851ed3b3f66cc45b47
657,101
import os def get_images(file_path): """ Description: Get file_names from a certain directory and store them into a list. :param file_path: file_path :return: put all file_names in a list """ if r'/' != file_path[-1]: file_path += r'/' images = [] path_dir = os.listdir(file_pat...
5b5b48abfb32bd34c695ba6f4ed427ca3c7a1940
657,102
def parse_latitude(value): """ Parse latitude in the form "S10" or "N10". """ latsign = {'N': 1, 'S': -1} if "N" in value or "S" in value: return latsign[value[0]] * float(value[1:3])
bad86ed72c3fd2609412cfcdb8d2ac030ddb73e9
657,103
def strict_false(): """Strict false boolean """ return False
6d40f1822d6d166599dbc33618aae794a36c2dbe
657,104
from typing import List def build_uri(scheme: str, loc: str, paths: List[str] = [], **kwargs) -> str: """ Used to build URIs :param scheme: scheme e.g. http in http://google.com/ :param loc: netloc e.g. google.com in http://google.com/ :param paths: a list of paths e.g. ["example", "path"] in http...
e2d03f675c5a91631edbc185c7bebca54284b882
657,105
import torch def clamp(x, min=float("-inf"), max=float("inf")): """Cet value after clamp.""" return torch.clamp(x, min=min, max=max)
0bc051e732a26b9abd5dfa2fa89f19dcf41b12c5
657,106
def getreads(alignfile): #verified """ function to build a dictionary of all reads. input: gap1.sam and rri.sam from gapanalysis.py and gapfilter.py these two types of input are automatically detected. returns readsdict: {readid:[alignment lines], ...} """ readsdict={} header = [] ...
bcdd4bc36e6728ac0b5801696c2e1b66dc92289b
657,107
def series(*resistors): """Calculate an equivalent resistory value for series resistors. Given resistor values as input, assume they are put in series in a circuit, and return the equivalent resistor value as if they were a single resistor. """ return sum(resistors)
55223cbc69845c2b2fce366d1747cb77a1405e16
657,108
import requests def list_station_measurment_types(station_name): """ Given a station name from GLOS (input), return all time series measurement types available at this station. Returns a list of these names. """ response = requests.get("https://seagull-api.glos.org/api/v1/obs-datasets.geojson") ...
a6be46c8a3f20d59e2840cc537c04575452662b0
657,109
def route(path): """ Decorator for a simple bottle-like web framework. Routes path to the decorated method, with the rest of the path as an argument. """ def _route(f): setattr(f, '__route__', path) return f return _route
c0218d370cac0325d9cde002b929ef7920eeb36a
657,110
def _Backward2c_P_hs(h, s): """Backward equation for region 2c, P=f(h,s) >>> "%.8f" % _Backward2c_P_hs(2800,5.1) '94.39202060' >>> "%.9f" % _Backward2c_P_hs(2800,5.8) '8.414574124' >>> "%.8f" % _Backward2c_P_hs(3400,5.8) '83.76903879' """ I=[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2...
e572c215c9ca8e2676c2b04fe9ef09ea338dbd02
657,112
def _get_mins_and_secs_str_from_secs(delta): """ Returns minutes and seconds from a seconds number """ mins = round(delta / 60) secs = round(delta-mins*60) if (secs == 60): mins += 1 secs -= 60 time_text = (f"{mins} minute" if mins > 0 else "") + ("s" if mins > 1 else "") + \ ...
7593e168e6de90eb00bcc8844ae66e268c531a7b
657,113
import re def unfilter_reply(message): """ This undoes the phrase mangling the central code does so the bot sounds more human :P """ # Had to write my own initial capitalizing code *sigh* message = "%s%s" % (message[:1].upper(), message[1:]) # Fixes punctuation message = message.repla...
84db4f1434608d7df56ec6e21e32d5a2f036c2e2
657,115
def calculate_external_jumps(alignments): """ Count number of times the (smallest) source index aligned to target word x is not adjacent or identical to any source word index aligned to the next target word index x+1 Target words which do not have any source word aligned to it are ignored >>> calculate_...
6dd8e220490a96e9a2899eed56dcf299ae21fb45
657,116
def number_of_retweeted_tweets(user_id, node_collection): """---""" query = {'_id': user_id} attr = node_collection.find_one(query) return len(attr['retweeted_tweets'])
9ee2ca5d6a11fec690cb3a0c203126cbf9dea5de
657,118
def isPalindrome(word): """[Simple function checking if word is a palindrom] Args: word ([String]): [Word we want to check if is a palindrom] Returns: [Bool]: [If is palindrom True if not False] """ return word == word[::-1]
18f4aad54c5af535af19ad34dd3c273cac8e2da2
657,119
def setAllFiltersToDiscard(): """ Set All Filter States to Discard (17) (0 bytes) Returns empty byte string (this command needs no extra data). """ return b''
66457b5ce61b7754db3677124ada2e44e1ea93c9
657,120
import click def PromptIf(arg_name, arg_value): """ https://stackoverflow.com/a/49603426 """ class Cls(click.Option): def __init__(self, *args, **kwargs): kwargs['prompt'] = kwargs.get('prompt', True) super(Cls, self).__init__(*args, **kwargs) def handle_parse_result(...
c64cb72355bf62f8cb14fff8d0d8a42be9e746d4
657,121
def catch_error(list_like): """ if none of the options are true, something has gone wrong :param list_like: a list_like of bools :return: true if at least one is true, else returns false """ for b in list_like: if b: return True return False
77521db384a822968a878c836c59d78203ced499
657,122
from typing import Counter def plurality_value(examples: list): """ Returns the most common classification in a list of examples. :param examples: list of dictionaries with examples as entries, must contain the key "classification" :return: str, most common classification """ return C...
caa07726075e45c3bdec5041d55a56f9f6342164
657,123
import json def pack_message(routing_id, message): """ Pack a routing id and Message into a mutlipart zmq message. Parameters ---------- routing_id : str The zmq socket identity to place first in the message. message : Message The Message object to serialized into the multipart m...
e7ba6aa223c5779dd7d93bc1747bc1624b163909
657,124
def _to_product_identifiers(search_res): """ Returns ------- A list of str, constructed from `(obs_collection, obs_id, productFilename)` tuples, that can identify cached lightcurve file,s if any. """ return list( map( lambda e: e["obs_collection"] + "/" + e["obs_id"] + "/...
7b16f69976e6d0dc4769fe6d50adfb7c2df527db
657,125
def sorted_subsets(self, A): """ :param self: :param A: List of unique values :return: List of all subsets """ def rec(A): if len(A) == 1: return [[A[0]]] s = [[A[0]]] t = rec(A[1:]) for x in t: s.append(s[0] + x) return s + t ...
799f3f69d4450aef6169c8b54c7a83d22a81151a
657,126
def retry(value, multiplier=1.5, max_value=100000): """Creates callable that increases resource value on retries. This function is intended for use with resources, especially memory (mem_mb). Parameters ---------- value : int The value that will be multiplied on retries. This v...
b3faa378ab57d17f3ae642204bead127f43b94bd
657,127
def check_distance_residue(AA, H): """ Parameters ---------- AA : amino acid from a protein structure object made with PDBParser(). H : hetero residue from a protein structure object made with PDBParser(). Returns ------- distance : the smallest distance between the two residues (i...
3e3ffc8d8b3aaa028040fa49a0d843795b059706
657,128
import os import uuid def getCookieSecret(dir): """Used to remember users who are currently logged in.""" filename = os.path.join(dir, 'cookie-secret') if os.path.exists(filename): with open(filename, mode='rb') as fh: cookieSecret = fh.read() else: cookieSecret = uuid.uuid...
b3edb39fe16e0f71cffd6c4b6bf967d145bd2441
657,129
import os def listfiles(path): """List files in directory""" files = [] for file in os.listdir(path): if os.path.isfile(os.path.join(path, file)): files.append(file) return files
1997d0fd4b26c0b9c6b30306682f135fcce75d1d
657,131