content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def find_point_of_region(vor, ireg): """Return the index of point within region ireg. Args: vor (Voronoi): Voronoi object. ireg (int): index of region. Returns: int: index of the Voronoi point for region ireg. """ for ip, iregx in enumerate(vor.point_region): if ir...
7ea3fd05edf5331e16f913e909c995911555fc67
474,791
import torch def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor: """Convert 3d vector of axis-angle rotation to 4x4 rotation matrix Args: angle_axis (torch.Tensor): tensor of 3d vector of axis-angle rotations. Returns: torch.Tensor: tensor of 4x4 rotation matrice...
461779558e8cf06e05a018253961e4756ada1a47
52,576
def promptChoice(prompt): """ Returns the numerical choice of a prompt. Otherwise returns None. """ try: return int(input(prompt)) except ValueError: return None
6301bda8ebecfa49e7451e6a996607fcae7bca9c
559,797
def gradient_descent(f, initial_guess, n_steps, step_size, plotting_cb): """ Run gradient descent to optimize the cost function f. args: f: a function taking a single jnp.array of decision variables and returning a tuple (cost, cost_gradient) initial_guess: a starting point for t...
99a22cf3f93a2c54d4d39f16f2f29374cf20c5c1
180,074
def get_spectral_w(w_pars,energy): """ Return spectral weight of an event Parameters ---------- w_pars: parameters obtained with get_spectral_w_pars() function energy: energy of the event in GeV Returns ------- float w """ E0 = w_pars[0] index = w_pars[1] index_w =...
9a9d9479a8f62ac007dddee1f1bf742ddce44bec
649,878
from datetime import datetime def date_delta(y1, m1, d1, y2, m2, d2): """ Return timedelta object of two date, eg: d = date_delta(2015, 3, 2, 2016, 3, 2) """ y1, m1, d1 = int(y1), int(m1), int(d1) y2, m2, d2 = int(y2), int(m2), int(d2) d1 = datetime(y1, m1, d1, 0, 0, 0) d2 = datetime(y...
f54f55cbfc8558fc5d1e7077e0b29b5d023fafbb
118,864
import torch def DotScorer(dec_out, enc_outs, **kwargs): """ Score for query decoder state and the ith encoder state is given by their dot product. dec_outs: (trg_seq_len x batch x hid_dim) enc_outs: (src_seq_len x batch x hid_dim) output: ((trg_seq_len x) batch x src_seq_len) """ sc...
79a56c45d83ca3f525191c089900c49095917fa3
529,998
from typing import Optional def optional(variable: Optional[object], default: object): """ Optional parameter that is default if None. """ return default if variable is None else variable
57ec55f83a89f558ea3fbec35e820e3950f88af5
398,875
import struct def two_ints_to_long(intl, inth): """ Interpert two ints as one long """ longint = struct.pack(">I", inth) + struct.pack(">I", intl) return struct.unpack('>q', longint)[0]
c503e00f1ed934ad22590b942be85b7fd877bb47
693,756
def get_shapefile_record_name_from_location(shapefile_record_names_df, location): """ Get the shapefile record name for the location given. Args: shapefile_record_names_df (pandas DataFrame) : dataframe of shapefile record names and the associated locations location (str) ...
46e52c302736a77a549046cb15243ff375136cb6
97,060
def parse_comma_list(s): """Parse comma-separated list in env var to Python list.""" if not s.strip(): return [] return [b.strip() for b in s.split(',')]
d1fbe2e4ad0b0cfb84636798fa5c146142c9114a
354,172
def 取最大数(数值列表): """ 传入要对比的列表,如(1,2,3),返回里面最大的数字 :param 数值列表: (1,2,3) :return: 3 """ return max(数值列表)
111eba5c9c37e7656ca410447e1ac5a3f0041ea7
40,239
import random def uniform_crossover(dna1, dna2): """randomly crossover genes between dna1 and dna2""" child1 = [] child2 = [] for ind in range(len(dna1)): p = random.random() if p < 0.5: child1.append(dna1[ind]) child2.append(dna2[ind]) else: ...
9c72b7b43f41f76c3d00c3430f398ae7e44a0e70
433,511
def get_prefix_length(oracle): """Finds the length of the prefix that mysterious_encrypt adds to the plaintext before encrypting.""" # Encrypt two different ciphertexts ciphertext_a = oracle.encrypt(b'A') ciphertext_b = oracle.encrypt(b'B') # Since the stream ciphers encrypts bit by bit, the prefix...
9f884797c2cdc25fca0b8bde39f5b9700eb5372b
597,284
def config_file(tmpdir_factory): """Creates a sample looker.ini file and returns it""" filename = tmpdir_factory.mktemp("settings").join("looker.ini") filename.write( """ [Looker] # API version is required api_version=3.1 # Base URL for API. Do not include /api/* in the url base_url=https://host1.lo...
749e80a61af42a7940b9251c7f326185224d8160
243,642
def listDistInts(refSeqs, querySeqs, self=True): """Gets the ref and query ID for each row of the distance matrix Returns an iterable with ref and query ID pairs by row. Args: refSeqs (list) List of reference sequence names. querySeqs (list) List of query sequence n...
da589e1f24bcacdcc607bf889a1fba0a2ceb25dc
558,381
def parse_sam_region(string): """Parse 1-based genomic region string into 0-based tuple.""" if not string: return () parts = string.strip().split(":") if len(parts) == 1: chrom = parts[0] return (chrom,) else: chrom = parts[0] positions = parts[1].split("-") ...
5c3a0c1b4033e02c2e94b10933ae96bcbca27b00
265,909
def recover_bad_token(stream: str) -> str: """Pull the leading non-whitespace string off the input stream""" return stream.split(' ')[0]
f3726aa6826b741eaedcdc9be430efbfa5e83ca2
427,176
import re def split_alpha_number(symbol): """ 分离字母开头,然后接数字的情况,如果后面有别的字符会被截断 print(split_alpha_number("TF1703.CFE")) ('TF', '1703') :param symbol: :return: """ pattern = re.compile(r'([A-Za-z]+)(\d+)') match = pattern.match(symbol) if match: return match.group(1, 2) ...
70688acbe7c6a09504dd3b1c4881b24f2ee64715
91,257
import base64 def backend_internal_api_token(testconfig): """ Returns the token for the internal api. The token is 'username: password' encoded in base64, where username and password are defined in the backend-internal-api secret """ return base64.b64encode( f'{testconfig["threescale"]...
8e6c78327ef79ecf3e0893fb9b715c3e7d456337
196,810
def _element_in_child_template(root, e): """ detect if the element is trapped inside a nested bind: tag relative to e :type root: UIElement :type e: UIElement :rtype: bool """ return any(x.typeid.startswith('bind:template') for x in root.path_to(e))
05d1497653766f057771d923276f5c586834bac6
459,284
def set_default_schedule(chronos_job): """ Given a chronos job, return a new job identical to the first, but with the schedule replaced with one that will set the job to run now. :param chronos_job: a chronos job dictionary suitable for POSTing to Chronos :returns: the chronos_job parameter...
900617b0befdf6e31b8e84714e2dba4604eea762
329,168
def are_all_0(lists, index): """Check if the values at the same index in different list are all to 0. :param list lists: a list of lists to check the value in. :param int index: the index of the values to check in the lists. :returns: True if all the values at the index in the lists are set to 0, Fals...
1fe4f8777618eed459907b2995170691be639e5b
47,506
def get_damage(attacker, defender): """Get damage dealt by attacker to defender.""" damage = attacker['Damage'] - defender['Armor'] return damage if damage > 0 else 1
3bb570cb84b2a54a9c6e209eb0db152eae6b17c8
599,079
def diminuir(num, porcentagem): """ -> Calcula o valor reduzido de uma determinada porcentagem :param num: numero que será acrescido da porcentagem :param porcentagem: valor da porcentagem a ser calculada :return: o resultado do cálculo """ resultado = num - (num * (porcentagem / 100)) r...
c4515886adb6be846710b964dccc6c55ce982ab9
588,644
def cents_to_dollars(cents): """ Convert cents to dollars. :param cents: Amount in cents :type cents: int :return: float """ return round(cents / 100.0, 2)
dc0d33c34de70b1591a82d8195848418a6ef2fed
495,833
def conv_lin(a, b=1.0, c=0.0, inverse=False): """Simple linear transform will I think store parameters against each sensor then they are handy >>> conv_lin(4,2,3) 11 >>> conv_lin(11,2,3.0,True) 4.0 >>>""" if inverse is False: return a * b + c else: ...
a41d3254c933f59a5fb24253dcebc684a4211108
676,303
import random def random_index(seed, N): """ Args: seed - initial index, N - maximum index Return: A random index between [0, N] except for seed """ offset = random.randint(1, N-1) idx = (seed + offset) % N assert(seed != idx) return idx
72394a6687265234b131524fdb37583c6f56105b
393,527
def plur_sing(count, word, suffix=None): """ Conditionally add an 's' for example, if count isn't 1. """ if suffix is None: suffix = "s" return f"{count} {word}{suffix * (count != 1)}"
519651c1b020619cc3c0ace4d76e47fb57eae17b
571,206
def date_convert_RU(date, short=False): """ Convert date object to string in Russian with month name: '2018-01-06' -> '1 июня'. :param date: date object <datetime.date> :param short: set to True to get abbreviated month name, use for graph labels. :return: date <string> """ months_ru = ['января', 'февраля', 'м...
cc7a292dd95d8a328d1fe87c7f8dce3c55ba471d
231,934
def process_data(data: str) -> tuple[str, dict[str, str]]: """ Process one row of template, then an empty line, then rows of rules Returns: tuple[str, dict[str, str]]: (template, rules-dict) where rules-dict looks like {'CH':'B', 'HH':'N', ...} """ template, _, rules_lines = data.pa...
a0c66cf7d1c12edaa1610fea8bdd43e61c5ba0ca
500,112
def _is_water_file(f): """ Is this the filename of a water file? :type f: str :rtype: bool >>> _is_water_file('LS7_ETM_WATER_144_-037_2007-11-09T23-59-30.500467.tif') True >>> _is_water_file('createWaterExtents_r3450_3752.log') False >>> _is_water_file('LC81130742014337LGN00_B1.tif'...
2a4171c5a121a16d635ab7c7469f1092310c7d60
508,778
import time async def with_ratelimit(client, method, *args, **kwargs): """ Call a client method with 3s backoff if rate limited. """ func = getattr(client, method) response = await func(*args, **kwargs) if getattr(response, "status_code", None) == "M_LIMIT_EXCEEDED": time.sleep(3) ...
7ba1d295b770d217a10e6d74a7ea9e47c4c60615
211,576
from typing import Any def validate_data_type(point_type: int, value: Any) -> bool: """ Validate data type,1:number,2:str,3:boolean,4: datetime, 5:location :param point_type: data point type :param value: value :return: True if valid else False """ validate_result = True if (point_type...
72aa4dc642a7a9a8d8e365a176a880ae732fb31f
155,518
def rivers_with_station(stations): """Takes a list of stations and returns a set of all the rivers in alphabetic order upon which those stations are located""" rivers = set() for station in stations: rivers.add(station.river) rivers = sorted(rivers) return rivers
d0c6579906a7d4063ee979aa219d273cfc5b6099
566,289
def doc_label_name(context_type): """ Takes a string `context_type` and makes that a standard 'label' string. This functions is useful for figuring out the specific label name in metadata given the context_type. :param context_type: A type of tokenization. :type context_type: string :retu...
da6e18ad15a40c7898b9617208038ca7a8528973
288,150
def can_loop_over(maybe): """Test value to see if it is list like""" try: iter(maybe) except: return 0 else: return 1
7dc0b759f7287c7722c98687aa715b768c7b47ad
526,925
def list_eval_keys(prefix='kitti'): """List the keys of the dictionary returned by the evaluate function.""" return [ prefix + '-EPE(occ)', prefix + '-EPE(noc)', prefix + '-ER(occ)', prefix + '-ER(noc)', prefix + '-inf-time(ms)', prefix + '-eval-time(s)', prefix + '-occl-f-...
1d3b195a95789d7ec5c818056072a60dc1e0b16b
143,961
import copy def resample_list(spec_to_resample, specList, **kwargs): """ Resample a single EchelleSpectrum or Spectrum1D object into a EchelleSpectrumList object. Useful for converting models into echelle spectra with multiple orders. Parameters ---------- spec_to_resample: EchelleSpectru...
4ef582f164965189d40f01185143069b5bdf551c
382,042
def value_to_bitval(value, bits=8, min=0, max=1): """ Converts a value to a bits-bit number for range min to max :param value: (float) value to convert :param bits: (int) number of bits of resolution :param min: (float) minimum of range :param max: (float) maximum of range :return: (int) value...
48979fdf737e5c4ab3dcde72104b7a7035f6173f
260,817
def calc_doublelayer_dielectric_capacitance(eps_fluid, lamb, Cdl): """ Total capacitance due to Debye layer and surface capacitance (Stern layer or dielectric coating) units: F/m^2 Notes: Adjari, 2006 - "The overall capacitance per unit area in the Debye-Huckel limit" Inputs: ep...
95f4c5abf7eaf4478fc120f633ca9c7f32d88a1e
532,804
def submit(jobs, job_attributes={}, serial=False, dump_job=True): """ lets you submit multiple jobs serial to each other or in parallel Args: jobs (:obj:`list` or `tuple` :obj:`Job`): jobs to submit job_attributes (dict): effective overrides to all job attributes serial (bool): if True ...
d9eb4ca69d4fd6528385a14c21729d987fe21cd9
185,739
import random def generate_number() -> int: """Generate a random number from 1 to 10. Returns: int: Random number. """ return random.randint(1, 10)
f9d4c000bc1e0103f0548924b326c0fa7c27700c
107,982
def pad_bounds(bounds, percent=0): """Pad the bounds by a percentage Parameters ---------- bounds : list-like of (west, south, east, north) percent : int, optional percent to pad the bounds Returns ------- (west, south, east, north) """ xmin, ymin, xmax, ymax = bounds ...
b2c94bb5da16efef629bde0d61d361a005b06565
612,773
def has_ext(filename, ext): """ >>> has_ext('test.mp3',['opus','mp3','aac']) True >>> has_ext('test.mp4',['opus','mp3','aac']) False >>> has_ext('test.opus.gz',['opus','mp3','aac']) False >>> has_ext('test.1.OPUS',['opus','mp3','aac']) True """ return filename.split(".")[-1]...
672c77eab94a15bee226fce9037feea73a83584c
518,451
def is_prefix(x, pref) -> bool: """Check if pref is a prefix of x. Args: x: Label ID sequence. pref: Prefix label ID sequence. Returns: : Whether pref is a prefix of x. """ if len(pref) >= len(x): return False for i in range(len(pref)): if p...
ec34e3e08d9ea5822481d1eaf70f1c72caf2e6d2
516,739
import re def remove_whitespace(some_string): """Remove whitespace and punctuations from a string""" some_string = some_string.lower() splitter = r'[\; \, \* \n \.+\- \( \) - \/ : \? \ — \' \’]' parts = re.split(splitter, some_string) new_string = ''.join(parts) return new_string
929d702e7c96830c867a928d3461b09e7b41f1d0
201,055
def lauegroup_to_lattice(lauegroup): """Convert a Laue group representation (from pointless, e.g. I m m m) to something useful, like the implied crystal lattice (in this case, oI.)""" # this has been calculated from the results of Ralf GK's sginfo and a # little fiddling... # # 19/feb/08 ad...
57d7e6851675785b55339046416af35b5cecf6e0
240,668
def _plural_s(cnt, word): """Return word in plural if cnt is not equal 1""" if cnt == 1: return word return '%ss' % word
fa9f5a319caacfaacf1acf4ae02942691a34d0c0
515,636
from typing import List def make_ngrams(text: str, n: int) -> List[str]: """Turn a term string into a list of ngrams of size n :param text: a text string :type text: str :param n: the ngram size :type n: int :return: a list of ngrams :rtype: List[str]""" if not isinstance(text, str): ...
a574e78a9873a6f2dbbc3643197a9f23d72d84ab
83,913
def _divisible_slice(perm, divisor, start_index): """Check if a three digit slice of a permutation is divisible by divisor""" perm_slice = perm[start_index:start_index + 3] number = int(''.join(perm_slice)) return number % divisor == 0
2698381efd0e7f720f474eb57dc25bc6b8f25dac
476,468
def calculate_reliability(data): """ Calculates the reliability rating of the smartcab during testing. """ success_ratio = data['success'].sum() * 1.0 / len(data) if success_ratio == 1: # Always meets deadline return ("A+", "green") else: if success_ratio >= 0.90: return ("A", "green") elif success_ratio...
d1c9ad7bba220beeae06c568cfd269aaaebfb994
1,545
import tempfile def get_temp_filename(mode="w+b", buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None) -> str: """Get temp filename e.g j.sals.fs.get_temp_filename(dir="/home/rafy/") -> '/home/rafy/tmp6x7w71ml' Args: mode (str, optional): [description]. Defaults...
6ee213a5d2acf782b4ac24b2581bfcd733a23156
116,559
def last_elem_in_list(working_list): """ returns the last element of a list. """ return working_list[-1]
c6bb6c538b2474a504358dc4a51f6a3537e11388
242,592
def parse_email_remediation_key(key): """Returns the tuple (message_id, recipient) for the key created using create_email_remediation_key.""" return key.split(':', 1)
495eff306e89ada4430bc4995d96fb88e0c4f032
645,900
def decdeg2dms(dd): """ Convert decimal degrees to deg,min,sec """ is_positive = dd >= 0 dd = abs(dd) minutes, seconds = divmod(dd * 3600, 60) degrees, minutes = divmod(minutes, 60) degrees = degrees if is_positive else -degrees return (degrees, minutes, seconds)
f369e4f17960238cbb070e6e000dbb24dcba9011
582,167
def getAllContribsOutputStrFromSpectraOutput( spectraOutput, energyFmt=None, intensityFmt=None ): """ Gets a str to write all contributions to spectraOutput (e.g. fragA-S-3p contribution) Args: spectraOutput: (GenSpectraOutput object) This contains all information for a generated spectrum energyFmt: (Str, optio...
03b10fa3bcdc9a0458478da0b602a8eaaa770d33
51,031
def find_indexes(s, ch='\n'): """Finds all instances of given char and returns list of indexes """ return [i for i, ltr in enumerate(s) if ltr == ch]
b94bfcf277de7e10f2adee0aabc441b20bc18467
434,008
def comma_synonyms(f, e): """ Expands comma separated words as synonyms. For example: ('house, home') -> ('house'), ('home') :param f: :param e: :return: """ if ',' in e: parts = list(filter(lambda x: x, map(lambda x: x.strip(), e.split(',')))) if len(parts) > 1: ...
0c5966c191fc87c01d0bd7dccf6f071d0672f5b7
532,515
def hash_table_size(item, tablesize): """ A hashing technique that involves 1. Converting the characters in a string to a list of ordinal values 2. Get the sum of the list 3. Get the remained by doing a modulo using tablesize item - string tablesize """ ordinal_list = [ord(i)...
cf47a023c35693681485331878dfd3eb9164a7bf
9,448
def _isIterable(maybeIterable): """Is the argument an iterable object? Taken from the Python Cookbook, recipe 1.12""" try: iter(maybeIterable) except: return False else: return True
bd1e60aa5eba5dcbfe3433531d26a671dd65f9eb
218,088
def _grad_nll(p, gp, y): """ Given parameters and data, compute the gradient of the negative log likelihood of the data under the george Gaussian process. Parameters ---------- p : array GP hyperparameters gp : george.GP y : array data to condition GP on Returns ...
600f22945036454621860d2289fcfdd9a29fdd1e
637,081
def get_doc_info(result): """Get the index, doc_type, and id associated with a document. Parameters ---------- result : dict A document from an Elasticsearch search result. Returns ------- dict A dictionary with keys 'index', 'doc_type', and 'id', containing the nam...
f4eb4b235c75d53862974e8937ca5c845b2734c5
145,383
def format_percentage(number): """ Formats a number into a percentage string :param number: a number assumed to be between 0 and 1 :return: str """ return '{}%'.format(round(number * 100))
5736b141b316d2de63804ddb248a45d9e4748ba4
669,440
import re def you_to_yall(text: str) -> str: """Convert all you's to y'all.""" pattern = r'\b(y)(ou)\b' return re.sub(pattern, r"\1'all", text, flags=re.IGNORECASE)
1a3ee7ebf2394f84ad296e18da789dff8ca50a12
7,860
import re def run(text, meta): """Remove refs from the text. Returns text with a regex substitution and unchanged META.""" pat = re.compile(meta.get("ref_regex", "[[(]*ref:[0-9a-f]+[])]*")) text = pat.sub("", text) return text, meta
5ff0034a9269594b994819f7c9df2719f9d009f1
583,530
import hashlib def md5hash(filename, size=50000): """ Helper function to calculate MD5 hash of the file contents (up to a given number of bytes). @param filename file path of file to process @param size the maximum number of bytes to read """ f = open(filename, 'rb') data = f.read(siz...
59891ca50f72e8d3c62504887b0c1480a0753345
613,975
def is_scheduler_like(thing): """ Test if an object can be used as a scheduler. :meta private: """ # Pytorch doesn't have a unified inheritance class for these things. # So we call it a scheduler if it has a "step" attribute that itself is callable return callable(getattr(thing, "step", None...
224c1696798df17b11812aa1cfcf0cd79f3f3afe
516,674
from typing import Any from typing import Union from typing import List from typing import Sequence def _list_convert(x: Any) -> Union[Any, List[Any]]: """Converts argument to list if not already a sequence.""" return [x] if not isinstance(x, Sequence) else x
79a913305a931378e2cb2b8f46a74f1381850ac4
44,112
def clean_string(s): """ Clean all the HTML/Unicode nastiness out of a string. Replaces newlines with spaces. """ return s.replace('\r', '').replace('\n', ' ').replace('\xa0', ' ').strip()
04568d67be1c966eec1ba7cb09ac7303667f66d6
152,224
def get_expected_log_files_dict(base_out): """ :param base_out: Base path structure for log files. For example, if the expected path for the log is 'work/step.path/log/step.conda_info.txt', the argument should be 'work/step.path/log/step'. :type base_out: str :return: Returns dictionary with ex...
95046fca053fc3da9c03989e79a88e88d4daaec8
562,319
from pathlib import Path def data_paths(root): """Get the paths for the processed data Note: This first requires that you use `frame`'s cli to preprocess the framenet data into json files. Args: root: root path to the json preprocessed data Raises: `ValueError`: if t...
4d5a0d460b7af8de2d22fc1a709974163dd8c23b
496,886
def is_string(value): """Check if the value is actually a string or not""" try: float(value) return False except ValueError: if value.lower() in ["true", "false"]: return False return True
7cb61dcb81c6baa824a1537fd6c94f2b237c0669
128,917
def is_present(marks, text): """ return True, if all marks present in given text """ return all([mark in text for mark in marks])
0ea198520b1e46f1c9b26a9533e0785140348776
70,873
def get_frame(path): """Get frame for animation from text file.""" with open(path) as file: return file.read()
4b5d7a55d85004f757acdedaf3bdc68d59d84cf8
543,553
def format_timestamp(timestamp): """ Format a timestamp to a string. """ return timestamp.strftime('%Y-%M-%d %H:%M:%S')
fad6ae95f4745e4a13bd5ea9667ed0dc370413d8
380,108
def join(string, iterable, *, on_empty=None): """ A functional version of ``str.join()`` providing more flexibility via the ``on_empty`` parameter. Arguments are not checked. :param string: :param iterable: :param on_empty: :return: """ if on_empty == 'drop': return string....
8e61d544914f76b5b8f1c2023fe6c3d1d5fa1106
535,043
def snake_case_to_camel_case(string): """Converts a snake case string to a camel case string.""" result = '' capitalize = True for c in string: if c == '_': capitalize = True else: result += c.upper() if capitalize else c capitalize = False return result
fa34d39760a3f7760b94b3bdb3bf4fd6cf9f5262
173,154
def Kml(nodes): """Returns a tuple representing a KML Document node. Args: nodes: Iterable of child nodes representing top-level KML objects. Returns: Tuple for pyfo to produce the <kml> node. """ return ('kml', ('Document', nodes), dict(xmlns='http://www.opengis.net/kml/2.2'))
c8863135e7ea2e806da4070766d5fe510e1bc87e
557,964
def count_vars_vcf(vcf_path): """ Counts the number of variants in a VCF file. """ in_file = open(vcf_path) num_records = 0 for line in in_file: if line.startswith('#'): continue num_records += 1 return num_records
053316c4aae21fe75e96d31a9563dc499b5dea71
113,612
def row_check_tile_direction(row,direction,index) : """Returns the value of the first tile encountered when moving from index in the direction given and the position of this tile. "-1" is a wall""" taille = len(row) currentPosition = index if direction =="left" : currentPosition -= 1 whi...
dbbdfa03639eafd2a784eb65553282706bde729a
309,900
from typing import IO import csv def startfile_csv(ARG_filewriter: IO): """Writes the header for the .csv suncalc results file. Parameters ---------- ARG_filewriter : IO The file writing IO object. Returns ------- csvwriter : csv._writer The IO object formatted specif...
f28eb1466b8945acc424635a5c1cd56d2a0d7cd3
592,140
def get_jssimporter(recipe): """Return the JSSImporter processor section or None.""" processors = [processor for processor in recipe["Process"] if processor.get("Processor") == "JSSImporter"] if len(processors) == 1: result = processors.pop() else: result = None ret...
79135db06159fcf3d30bc2f0c1dbf6493a475fd3
302,891
def catalan_dynamic(n: int) -> int: """ Returns the nth catalan number with polynomial time complexity. >>> catalan_dynamic(5) 42 >>> catalan_dynamic(10) 16796 >>> catalan_dynamic(0) 1 >>> catalan_dynamic(-5) 1 >>> catalan_dynamic(1.5) -1 """ if not isinstance(n, ...
0b33dd7e9d32653d7c3109232de3a127baf4c88b
472,550
def epsIndicator(frontOld, frontNew): """ This function computes the epsilon indicator :param frontOld: Old Pareto front :type frontOld: list :param frontNew: New Pareto front :type frontNew: list :return: epsilon indicator between the old and new Pareto fronts :rtype: float "...
8ec7b18b36a32b963c148aa7592557c2724bde0d
686,534
import string def extract_prefix(name): """Return the library or sample name prefix Arguments: name: the name of a sample or library Returns: The prefix consisting of the name with trailing numbers removed, e.g. 'LD_C' for 'LD_C1' """ return str(name).rstrip(string.digits)
892fe3b74ee42918244aa4bb83e362d7f316d050
391,598
def positive_cap(num): """ Cap a number to ensure positivity :param num: positive or negative number :returns: (overflow, capped_number) """ if num < 0: return 0, abs(num) else: return num, 0
577f1b82979424e405e9e7b7ce06a905619b96e7
549,237
from typing import Sequence from typing import Tuple from typing import Optional def get_fan_in_fan_out( shape: Sequence[int]) -> Tuple[Optional[int], Optional[int]]: """Returns (fan_in, fan_out) of a weight variable of the given shape.""" if not shape: return None, None if len(shape) < 1: return 1,...
231372e76b549ffd44482b0835634bbb29c07a49
574,492
def get_end_connection(road): """ Returns the intersection that is connected to the end of the road :param road: The road that the intersection is connected to :type road: Road :return: the intersection that is connected to the end of the road """ return road.get_end_connection()
795a672d8dc297fbcf1a36e10761e032ca2a7f1f
182,596
import struct def inet_aton(string): """inet_aton(string) -> packed 32-bit IP representation Convert an IP address in string format (123.45.67.89) to the 32-bit packed binary format used in low-level network functions.""" a, b, c, d = map(int, string.split(".", 3)) return struct.pack("BBBB", a, b...
0dddf2bcd48eb1596c6a9677ac589998c472fba0
165,837
def validate_sequence_characters(sequence): """ Validates that the sequence passed into it consists only of A, T, G and Cs. """ sequence = set(sequence.upper()) allowed = ['A', 'T', 'G', 'C'] for s in sequence: try: assert s in allowed return True except A...
9fa5e8aa14685c4e98d7cec1df264968137f8257
516,492
import logging def _check_downsampling_mismatch(downsample, num_pooled_features, output_layer_size): """ If downsample is flagged True, but no downsampling size is given, then automatically downsample model. If downsample flagged false, but there is a size given, set downsample to true. Parameter...
3ecd17596cccf3c84542dcd8c7ab7c9e35c2e65f
438,287
def fastaRecordSizer(recordLines): """ Returns the number of charcters in every line excluding: the first (header) line whitespace at the start and end of lines """ size=0 for i in range(1,len(recordLines)): size+=len(recordLines[i].strip()) return size
328b2e6fca07098616ba305520c7c64d754d4225
625,387
def get_accel_y(fore_veh, back_veh, ego_vy, idm_model): """ A wrapper around IDM, given a front and a back vehicle (and the absolute speed), and a longitudinal driver model, this function returns the desired acceleration of the back vehicle. Arguments fore_vehicle: A vehicle object, f...
847cc4c7ed02bb27dcfb0bfed966ad2699cd90b6
645,215
def check_direct(element, list_to_check): """ Returns a boolean indicating whether the direct should be update. Inputs: - element: direct that needs to be checked; - list_to_check: operational mode or pb_type and port of the direct to select. """ interconnect = element.getpa...
4ace09e83cbdbf9999402373e986916fa5592905
366,986
def ceildiv(a: int, b: int) -> int: """Safe integer ceil function""" return -(-a // b)
9dabd15a396fd1e3c743074d56081d5181a17775
528,125
import pathlib def unique_directories(files): """Returns a list of directories (pathlib.Path objects) for the files passed without repetitions.""" return list({pathlib.Path(x).parent for x in files})
326ed8b251b21fb36f03c5ddc7edd0b18918e868
49,297
def delete_nth(order, max_e): """Create new list that contains each number at most N times.""" counting = {x: 0 for x in order} final = [] for i in order: if counting[i] < max_e: counting[i] += 1 final.append(i) return final
4125728945022026e8969c47c50b5312b651e0c3
542,801
def blank_line(sROIID_, sComment_, iIndexCount_): """ Return correctly sized filler line for when extract is not possible. """ iCommaCount = 2 * iIndexCount_ + 1 return f'"{sROIID_}"{"," * iCommaCount}{sComment_}'
f86a4296c34bf71d527f9d34264a8c1730ef3a15
491,401
def dict_map_leaves(nested_dicts, func_to_call): """ Applies a given callable to the leaves of a given tree / set of nested dictionaries, returning the result (without modifying the original dictionary) :param nested_dicts: Nested dictionaries to traverse :param func_to_call: Function to call on th...
42139741a5a0e3dca7b0662086e0dbe1c16f6c8b
543,309