content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def GC_skew(seq, window=100): """Calculates GC skew (G-C)/(G+C) for multiple windows along the sequence. Returns a list of ratios (floats), controlled by the length of the sequence and the size of the window. Does NOT look at any ambiguous nucleotides. """ # 8/19/03: Iddo: added lowercase ...
1d6ce6e244de8991834f35b7b039af0594a6227a
635,940
def oxy_umolkg_to_ml(oxy_umol_kg, sigma0): """Convert dissolved oxygen from units of micromol/kg to mL/L. Parameters ---------- oxy_umol_kg : array-like Dissolved oxygen in units of [umol/kg] sigma0 : array-like Potential density anomaly (i.e. sigma - 1000) referenced to 0 dbar [kg/...
4398ce32cddffdbac2db2de417ed8d4f6c041630
635,941
def upsample_shape(input_shapes, scale): """ :param input_shapes: :param scale: :return: """ assert len(input_shapes) == 1, "not valid input shape for upsample layer" assert type(scale) is int input_shape = input_shapes[0] new_h = scale * input_shape[2] new_w = scale * input_sh...
a2938b1e86359f55d3af52a764082838e9e6eb7d
635,942
def get_exit_event(state, events): """Check if a given state has been exited at some point during an execution""" return next( ( e for e in events if e["type"].endswith("StateExited") and e["stateExitedEventDetails"]["name"] == state ), Non...
cf413dfff15b7060cc0d7f6b847231789071413d
635,943
def validate_comparison_operator(comparison_operator): """ Validate Comparison Operator for WebACL SizeConstraintStatement Property: SizeConstraintStatement.ComparisonOperator """ VALID_COMPARISON_OPERATORS = ( "EQ", "GE", "GT", "LE", "LT", "NE", ...
825a2f09cc2859613ef05c4da6c2e0b319291ac7
635,944
def get_device_name_prefix(device_name): """Return device name without device number. /dev/sda1 -> /dev/sd /dev/vda -> /dev/vd """ dev_num_pos = 0 while '0' <= device_name[dev_num_pos - 1] <= '9': dev_num_pos -= 1 return device_name[:dev_num_pos - 1]
486397ab516d13eccc3a88a0b8cad3df0e25329f
635,945
import re import html import json def extract_data(html_content): """ 提取历史文章数据: 1。 正则体术数据内容 2. html转义处理得到一个列表对象 3. 返回最近发布的10篇文章 :param html_content: :return: """ rex = "msgList = '({.*?})'" pattern = re.compile(pattern=rex, flags=re.S) match = pattern.search(html_content) ...
bd2b1b7c0d3c7ed479a8b373cc4a8a6b637b2687
635,946
import signal import os def kill_pid(pid): """Kills a process by its process id.""" try: # Unable to import 'module' # pylint: disable=E1101,F0401 return os.kill(pid, signal.SIGKILL) except ImportError: pass
7f8fd817165560b2963036fbeb8324ce5405bb83
635,947
import struct def calc_padding(fmt, align): """Calculate how many padding bytes needed for ``fmt`` to be aligned to ``align``. Args: fmt (str): :mod:`struct` format. align (int): alignment (2, 4, 8, etc.) Returns: str: padding format (e.g., various number of 'x'). >>> ca...
8144d8d61334d8126f7fdb2c8bc92f5c438a72ef
635,948
import logging def _FindClasses(class_object, *args): """Find all registered classes. A method to find all registered classes of a particular class. Args: class_object: The parent class. Returns: A list of registered classes of that class. """ results = [] for cls in class_object.classes: ...
0948742cbc59c2d86a544076eae6a69bdda8e2cd
635,950
def _fieldlogger_groundwater_settings(df, verbose=False): """Get default settings for groundwater observations Parameters ---------- df : pandas.DataFrame dataframe with observation point data Returns ------- name subname inputfield properties group """ if...
99abf10209ed4024e3aad3d69361ec17b549b944
635,951
def makeDOT(myFSA): """Return DOT representation for graphviz.""" buffer = "digraph fsa {\nrankdir=LR;\nnode [shape=doublecircle];\n" for i in myFSA.getFinalStates(): buffer = u" ".join((buffer, str(i))) buffer += u";\nnode [shape = circle];\n" for i in myFSA.states.keys(): val = my...
b01720db056a52e98d6c7c2221dac076668162c7
635,952
import re def gdpc(fastas, **kw): """ Function to generate gdpc encoding for protein sequences :param fastas: :param kw: :return: """ group = { 'alphaticr': 'GAVLMI', 'aromatic': 'FYW', 'postivecharger': 'KRH', 'negativecharger': 'DE', 'uncharger': '...
3ae27225e281599bd9845dd886bb1699d5e2ec0b
635,953
import re def dep_base(dep): """ Strip a dependency of version requirements, for example: dep_base('foo >= 1.2.3') == 'foo' :param dep: dependency to strip version from :return: dep stripped of version requirement (str) """ dep = str(dep) m = re.match(r'([^<>!=\s]+)\s*[<>!=]', de...
dcca1acb1fe8fc219266bac24314cbe723f56804
635,954
import argparse def valid_type(input: str) -> str: """Verify the input and output graph file types are supported. Used for argparse in argument_parsing() below. """ filetypes = {'net', 'gexf'} if input.split('.')[-1].lower() not in filetypes: msg = 'Unrecognized file format: \'{0}\'.'.fo...
e2eece7c8f41f3861140ba3b497c2016c49ec351
635,955
def is_simple_requires(requires): """ Return True if ``requires`` is a sequence of strings. """ return ( requires and isinstance(requires, list) and all(isinstance(i, str) for i in requires) )
d13c9fe631c32677fbf2be55fd7c048ed566f950
635,956
import math def simplify_U(theta, phi, lam): """Return the gate u1, u2, or u3 implementing U with the fewest pulses. U(theta, phi, lam) is the input gate. The returned gate implements U exactly, not up to a global phase. Return (gate_string, params, "OpenQASM string") where gate_string is one of ...
c9de34af0e81eac0f43091c177226098c0bdd385
635,957
import urllib3 def get_wikidata_item(wikidata_id: str) -> bytes: """Get Wikidata item structure.""" return urllib3.PoolManager().request( "GET", f"https://www.wikidata.org/wiki/Special:EntityData/Q{wikidata_id}.json", ).data
5461a3a2006b62677c378f90bf6e8a26fdda6735
635,958
import torch def get_targeted_classes(model, images, clip, a, b, k=5, case='avg'): """ Input: - model (pytorch model): bagnet model without avgerage pooling - images (pytorch tensor): a batch of preprocessed images, same context as model's images - k (int): get targeted classes based on top-K pr...
1c10c18df3fb79283cdf177f75641a65febdab70
635,959
def GWA_list_shrink(num_list): """Returns a string containing sorted abbreviated values e.g. [5, 8, 4, 3, 1] -> "1 3 to 5 8" Write to GWA file using ' '.join(GWA_sort(num_list))""" glist = sorted(num_list) glist.append(0) olist = [] n0 = glist[0] n1 = glist[0] for n in glist[1:]: ...
f550e18b660ca838d637c8320e515fe60eee3330
635,961
def src_dot_dst(src_field, dst_field, out_field, head_index=None): """ This function serves as a surrogate for `src_dot_dst` built-in apply_edge function. """ def func(edges): # If per_head is True then edges are defined per head. We will perform # multiplication per head edges[head_inde...
4e2227979008de33ee13fa546deb8771237aa1dd
635,962
def _sec2time(sec, n_msec=5): """ Convert seconds to "D days, HH:MM:SS.FFF" :param sec: number of seconds :param n_msec: number of milliseconds to use :return: string representing of time in human readable format """ if hasattr(sec, '__len__'): return [_sec2time(s) for s in sec] ...
ffd54eecfeb103ca4f0c7f8b12a4b304216fba60
635,963
import argparse import sys def parse_args(): """ Description: function 'parse_args' parses arguments from command-line and returns an argparse object containing the arguments and their values. Default values are 'False' if option is not listed in the command, else the option value is s...
41b9dd15ebfeaec171ae85e764ff1f7bf179e96c
635,964
import re def safe_name(string: str) -> str: """Returns 'string' with all non-alpha-numeric characters replaced by '_'.""" return re.sub("[^A-Za-z0-9]", "_", string)
77bd143a63cf63f6259c0dc27d848f628d65fd36
635,966
import re import os def GetRPMPackageInfo (package_name): """Return a list of: [version string, bool isInstalled""" pattern = re.compile(package_name) f = os.popen("rpm -q " + package_name); for line in f: if line.startswith(package_name): start = len(package_name) + 1 # increase by 1 to c...
b51ba4b4ab3cc365a8b07ff96dbcfbd7a63d1ca8
635,968
def catalan_recursive(n: int) -> int: """ Returns the nth catalan number with exponential time complexity. >>> catalan_recursive(5) 42 >>> catalan_recursive(10) 16796 >>> catalan_recursive(0) 1 >>> catalan_recursive(-5) 1 >>> catalan_recursive(1.5) -1 """ if not i...
75be80147f980b49beb42a559678264522e97109
635,969
from typing import Callable from typing import Any from typing import Sequence from typing import List def mapr( f: Callable[[Any], Any], collection: Sequence[Any]) -> List[Any]: """Recursive definition of map-like function. >>> mapr( lambda x:2**x, [0, 1, 2, 3, 4] ) [1, 2, 4, 8, 16] ...
7a90f02f6a038785412f39e7147d78b3c44f11e6
635,970
def reverse1(snippet): """Reverse first sequence. This does not change the calculated value. """ text = snippet if '0123456789;' in text: text = text.replace('0123456789;', '9876543210;') text = text.replace(r';\d*(\1\d*);', r';(\d*\1)\d*;') # [a9] to [9a] len = 10 - a tex...
c2a456cbb12bf8b350b35706a97ced006bc2973a
635,971
import random def randcoll(pool, dt): """ Generate random collection of 1-10 elements. :param Iterable pool: elements from which to choose :param type dt: type of collection to create :return Iterable[object]: collection of randomly generated elements """ valid_types = [tuple, list, set, ...
517aacd68450aed311fbc6445f0143dda341cd0a
635,972
def get_crop_specs(proposal, classifier): """Converts a crater proposal into cropping function arguments. """ lat = proposal[0] long = proposal[1] px = classifier.crater_pixels dim = classifier.input_dims #"Radius" of image r_im = proposal[2]*min(dim)/(2*px) #get four parameters ...
5cd80a9730aa450ac10aee09fa32731196216f21
635,973
import warnings def TrueSkill_Rating(self, mu=None, sigma=None): """Deprecated. Used to create a :class:`Rating` object. .. deprecated:: 0.2 Override :meth:`create_rating` instead. """ warnings.warn('Use TrueSkill.create_rating() instead', DeprecationWarning) return self.create_rating(mu...
135aca37790a113add16a228a1b1e14f85d22d9c
635,974
def update_c_delete_meta_lines(main, file): """ This update script deletes several meta lines :param file: Conan file path """ updated_global = False # noinspection SpellCheckingInspection line_deleting = [ "#!/usr/bin/env python", "#!/usr/local/bin/python", "# -*- cod...
c4ff47dcef03322a767d73378288844ce62c5290
635,975
from pathlib import Path import csv def get_fieldnames_from_csv_file(f_name, encoding='utf-8', newline='', delimiter=','): """ Возвращает список заголовков колонок CSV-файла. :param f_name: CSV-файл :param encoding: кодировка CSV-файла :param newline: newline: new...
5439593242c70fd05d8e4240d15b5b57dedf4f95
635,976
import click def _disable_delta_removes_check(f): """ Function to disable verification that delta removes are already in the DB. :param f: obj :return: options obj """ return click.option('--disable-delta-removes-check', default=False, is_flag=T...
13fd4c028edd85534ec9b777d668f3a83eafde82
635,977
def to_int(toks): """ Parser action for converting strings of digits to int. """ return int(toks[0])
82f9374de3b8fb2d4d4da200fe51e0bad0624e77
635,978
def _get_expression_from_node_if_one_exists( parsed_node, components_to_check): """This function first checks whether the parsed node represents the required angular component that needs to be derived by checking if its in the 'components_to_check' list. If yes, then it will return the expressi...
7ebe6111eda1f9619462be8d402e33a7aa36230e
635,979
import struct def architecture(): """ Check if host machine has 32-bit or 64-bit processor architecture """ return int(struct.calcsize('P') * 8)
7a2a0125fa8960607cd2a2264dd9c6d31ea705e2
635,980
def expand_modality_questions(answer: str, matched_word: str): """Create new questions for modality task with given information. Args: answer: Original answer to the question matched_word: The keyword which labeled the original question as modality Returns: dict of generated questi...
526c310920e2509efaf81c3a75379f866e5357cd
635,981
def lookupSortCategory(strCardName, dictLib): """"Figure out the card sort category based on the card name, look up in AllCards lib # in:card name # out: string category. I organize as White/Black/Blue/Green/Red/Colorless/Land/Gold/Unknown""" strSortCategory = "Unknown" dictCard = dictLib.get(strCar...
accfabc42e1be45f90993fc6effceffcd5492514
635,982
def get_clock_speed(cpu): """Gets clockspeed in GHz from given cpu data (returned by get_cpu)""" try: splitt = cpu.split(' ') #Quad-core ... GHz) hz_index = -1 counter = 0 for stri in splitt: lowered = stri.lower() if 'ghz' in lowered or 'mhz' in lowered: ...
7184cfd01a4837826203c938b1d2e68c06b58d03
635,983
import os def ParseNinjaDepsOutput(ninja_out): """Parse ninja output and get the header files""" all_headers = set() prefix = '..' + os.sep + '..' + os.sep is_valid = False for line in ninja_out.split('\n'): if line.startswith(' '): if not is_valid: continue if line.endswith('.h...
c443f565e046e4205fed8dda68d9680b5c0cb42d
635,984
def get_default_token(word2vec_model): """ Returns the token from a Word2Vec model to use as a default for end-of-sequence marking. """ return "." if "." in word2vec_model.vocab.keys() else word2vec_model.index2word[0]
3974935a21a841ae4a2855b8d05ca5870e1493a7
635,985
import json def scrapeNodesFromJsonCLightning(fp): """ scrape from 1ml json :param fp: file :return: Nodelist """ jsonObj = json.load(fp) nodeList = [] for i in range(0, len(jsonObj["nodes"])): try: nodeString = jsonObj["nodes"][i]['nodeid'] + "@" + jsonObj["nodes"]...
dfe0f48eb78593d7f22215d9776ae75bed0b00eb
635,986
import math def convert_to_cell_count(reading): """ Determined empirically from experiments in which platereader readings were compared to haemocytometer cell counts. """ R=reading e=math.e return 54927*(e**(1.83924751759787*R))
7743f70334139d5eaa2b7acd98ddc6dfeca6ee2b
635,987
import re def taintfilename(basename): """ Make a filename that is supposed to be a plain name secure, i.e. remove any possible path components that compromise our system. @param basename: (possibly unsafe) filename @rtype: string @return: (safer) filename """ # note: filenames contai...
d3eda1c388879427945b7cf88ade2c8144a52ca6
635,988
def instruction_list_to_easm(instruction_list: list) -> str: """Convert a list of instructions into an easm op code string. :param instruction_list: :return: """ result = "" for instruction in instruction_list: result += "{} {}".format(instruction["address"], instruction["opcode"]) ...
0181a9a1e7d5c7044cb2a707451767ce446a5266
635,989
def shuffle_lr(parts, pairs=None): """Shuffle the points left-right according to the axis of symmetry of the object. Arguments: parts {torch.tensor} -- a 3D or 4D object containing the heatmaps. Keyword Arguments: pairs {list of integers} -- [order of the flipped points] (defau...
40182414de58366075c99f8c474a255e56f3b342
635,990
def isasync(func): """ Decorator to mark a function "asynchronous": the caller receives a Future to get the result later on. The given callable _must return a Future_. If the object is remote, Pyro will take care of converting the Future to something remote. Note that for efficiency, if the object ...
e486d54885f48ef9fec10dfbf71e033f7b62e247
635,991
def watch_layer(layer, tape): """ Make an intermediate hidden `layer` watchable by the `tape`. After calling this function, you can obtain the gradient with respect to the output of the `layer` by calling: grads = tape.gradient(..., layer.result) """ def decorator(func): def wr...
a666d8c24c44b8f9fb2db0f941aad7825a8824e5
635,992
def format_text_table(data): """Format a list of dicts as text table""" def ljust_line(data): """ Left justify list elements and add `|` separators. :param data: List of strings :return: Line string """ sep = ' | ' left = '| ' right = ' |\n' ...
6bd5b2560f8724ac4fc09a062f611676608359aa
635,993
def plain_text(node): """ Return the plain text of a node with all tags ignored. This is needed where Doxygen may include refs but Sphinx needs plain text because it parses things itself to generate links. """ if node.tag == "sp": markup = " " elif node.text is not None: ma...
4f0f846e12e3ea870789b7c6490d281475612377
635,994
from typing import Callable def position_features(sentence: str, tokenizer: Callable, vocab: set) -> list: """Encodes the relative position of the tokens in :param sentence: as follows: - 0 for tokens at the beginning of the sentence; - 1 for tokens in the middle of the sentence; - 2 for tokens at t...
c809a8591278a6357370a2a42e698a5d055e5553
635,995
from typing import Callable def runge_kutta_method_o4(f: Callable[[float, float], float], y0: float, x: list[float], h: float, precission: int = 5) -> float: """Finds the value of y(x) for some ODE using Runge Kutta method (order 4). Params ------ f: Callable[[float, float], float] function r...
5f8f19bdf6e565b63d350888bd7b08f36f7d4ee7
635,996
import torch def farthest_point_sample(xyz, npoint): """ Input: xyz: pointcloud data, [B, N, 3] npoint: number of samples Return: centroids: sampled pointcloud index, [B, npoint] """ device = xyz.device batchsize, ndataset, dimension = xyz.shape centroids = tor...
9e2025f3cfe686a3975c581f21b6e5c64ace4648
635,997
import re def clean_for_filename(string): """ Cleans up string for use in filename """ string = re.sub(r"\[.*?]", "", string) # noqa: W605 string = re.sub('\s+', ' ', string) # noqa: W605 string = string.replace(' : ', ' - ') string = string.replace(':', '-') string = string.replace('&', 'an...
8bb33044b4e29afb780bbcb6e814df6267a3f543
635,998
import re def sanitize_json_file(json_file): """ I couldn't resist. Makes my job much more easier keeping the changes. Returns a string containing the file contents minus the comments. A comment is everything following a '//'. """ return re.sub(r"\s*\/\/.*", "", json_file.read_text())
73205b709bed6d8a8bdb1c5bc00cc663c7cc56a0
635,999
def prod(seq): """ return the product of all numbers in seq """ p = 1 for a in seq: p *= a return p
1a1d8c3cb020a0a2d738cafda25fc797a2b3c8a7
636,000
async def homepage(req): """Main page""" return ""
b6c45c3b603ddae48d99a2225304d4de0cd19138
636,001
def build_extensions(available_extensions): """ Builds websocket extensions header from the given extension values. Parameters ---------- available_extensions : `list` of `Any` Each websocket extension should have the following `4` attributes / methods: - `name`, type `str`. The...
dfdfaa0df96bace4b9f52eb5e45efdbdcca1f850
636,002
def _byte_pad(data, bound=4): """ GLTF wants chunks aligned with 4 byte boundaries. This function will add padding to the end of a chunk of bytes so that it aligns with the passed boundary size. Parameters -------------- data : bytes Data to be padded bound : int Length ...
e396b24078dcd487df2b9aea4a54669b90e8e624
636,003
def framework_supports_e_signature(framework): """ :param framework: framework object :return: Boolean """ return framework['isESignatureSupported']
bb7109e4f4bceea7f39e9d9e08bb47892b81f831
636,004
def sub_tracks(tlista, tlistb): """ :param tlista: :param tlistb: :return: """ stracks = {} for t in tlista: stracks[t.track_id] = t for t in tlistb: tid = t.track_id if stracks.get(tid, 0): del stracks[tid] return list(stracks.values())
934390fcc40a124e5f1e8242e4941ba4e8ea6f6f
636,005
def cal_pd_task_ind(pd_task): """ 计算产品研发中心资源投入到非产品事务的指标。 :param pd_task: 产品任务集 :return: 统计指标 """ _pd_sum = 0 _pd = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0} for _issue in pd_task: if _issue["updated"] is None: continue ...
a8b8a65c9c7cc58961f6d19b2ee7369f77156c22
636,007
import argparse import locale def parse_args(): """parse command line arguments and return them as Namespace""" parser = argparse.ArgumentParser( description='Generates a Seating Plan, e.g. for a class room, based on a CSV spread sheet and generates a PDF.') parser.add_argument('csvfile', help='the csv fil...
f03a7ab95f564b0d47a1e527b63b765a068299dd
636,008
import json def jsonhtml_renderer_factory(info): """Json renderer with text/html content type ExtJS form with file upload requires json response with text/html content type. See http://extjs.com/deploy/dev/docs/?class=Ext.form.BasicForm hasUpload(). """ def _render(value, system): """...
94a809c37d0b7a33b9d0afd1e44c4c5495294c9c
636,009
def freq_to_band(freq): """Convert given frequency in Mhz to a bandname (all regions)""" if freq >= 0.1357 and freq <= 0.1378: return "2200m" elif freq >= 0.472 and freq <= 0.479: return "600m" elif freq >= 1.8 and freq <= 2.0: return "160m" elif freq >= 3.5 and freq <= 4.0: ...
5107061981da71da18e4fa1443aefecd8add7c0c
636,010
def _FormatPythonDatetime(dt): """Make python datetime compatabile with git commit date args.""" return dt.replace(tzinfo=None).replace(microsecond=0).isoformat()
2353d3fb14e739206be3fb6cd154030f88c7376c
636,011
def celsius_to_fahrenheit(value: float) -> float: """ returns round((value * 1.8) + 32, 2) Convert celsius degrees to fahrenheit degrees. Up to 2 point over zero. :param value: celsius degrees :type value: float :returns: fahrenheit value :rtype: float :Example: ...
4a428712005936e8d30a1273a6be43e2a6a358d1
636,012
def _is_linear(expr, var): """ Returns true if the equation is linear in the variable. False otherwise """ poly = expr.as_poly(var) if poly: return poly.degree() == 1 return False
6b4980fd44f03f8c49c5ce5457fc43efe4c3288c
636,014
def _get_num_reads(ngs_alignment): """ Returns the number of reads in the template of an NCBI/NGS alignment Args: ngs_alignment (ngs.Alignment): aligned read Returns: int: the number of reads in the template """ if ngs_alignment.hasMate(): return(2) else: retur...
93a3e9076a758c0e0943b8d6b9426e9de463b52f
636,015
def binomial(n,k): """gibt den Binomialkoeffizienten (k aus n) an Quelle: http://hodge.mathematik.uni-mainz.de/~stefan/python/lehrerfortbildung2006.pdf, Folie 11 """ out=1 for i in range(1,k+1): out = (out*(n-i+1))//i return out
97e14b7191f51c743a3df7049b53b34e464afee7
636,017
def group(container, multiple=True): """ Splits a container into a list of lists of equal, adjacent elements. >>> from sympy.utilities.iterables import group >>> group([1, 1, 1, 2, 2, 3]) [[1, 1, 1], [2, 2], [3]] >>> group([1, 1, 1, 2, 2, 3], multiple=False) [(1, 3), (2, 2), (3, 1)] ...
27977e2e3096942121691fc2f7a0ca11f7541730
636,018
def show_square(number): """View that shows the square of the number passed by URL""" return f"Square of {str(number)} is: {(number * number)}"
6ca2d0abe709cf43c6dc5fa270f7b524ea56b56b
636,019
def Count(Spaces): """ returns tuples *(space, count)* where *count* states how often *space* occurs in *Spaces*. """ dummy = [tuple(sorted(x.items())) for x in Spaces] unique = set(dummy) result = [] for x in unique: result.append((dict(x), dummy.count(x))) return resu...
2412db01a117009ef3b984e2cd8b29ba3823135e
636,020
from typing import Tuple def rgba_to_html_string(rgba: Tuple[int, int, int, float]) -> str: """Create an HTML code from an RGBA tuple Parameters ---------- rgba : Tuple[int, int, int, float] | Tuple[int, int, int] RGB values and an optional alpha value between 0 and 1. Returns ------...
94f16f7c5d9694422a676cc179c9406cd016453b
636,021
def isTestDevice(serial_device): """ Determine if this instance is just a Test connection """ if serial_device == 'TEST': return True return False
894399d91e70d737b284795953f32b8c29f67bac
636,022
def augment_data(train_ds, data_augmentation): """ :param train_ds: raw train_ds :param data_augmentation: data augmentation sequence :return: an augmented training set """ print("Augmenting the train_ds") augmented_train_ds = train_ds.map(lambda x, y: (data_augmentation(x), y)) # augmen...
99330ac50babd57ef06d665d18a95bdbcba20485
636,023
import aiohttp async def get_tg_dm_player_json(): """ Helper function for pulling the top 10,000 AoE2 players' info. """ async with aiohttp.ClientSession() as session2: async with session2.get("https://aoe2.net/api/leaderboard?game=aoe2de&leaderboard_id=1&start=1&count=10000") as r: ...
75c59e34b5dc4d03f36b3e32ceb5decde09c6bf3
636,024
def bigScoop(PDFdata, Nbuffer=300): """ get model fits within Nbuffer of the best-fit model. """ lnprob = PDFdata['lnprob'] good = lnprob > lnprob.max() - Nbuffer PDFdata = PDFdata[good] # write the trimmed list return PDFdata
59bbafc74bc7245d3cb814b517d364c217840457
636,026
from typing import Tuple import argparse def get_command_line_parameters() -> Tuple[str, str]: """ Extracts the command line parameters. """ parser = argparse.ArgumentParser(description="Pyrallel: a way to explore Python concurrency/parallelism!.") parser.add_argument( "--problem-type", ...
15ff1bb8165587497841c5fcd1cbea9219433fa5
636,027
def copy_of(board): """ Returns a copy of a board """ copy = [] for row_num in range(10): row = [] for col_num in range(10): row.append(board[row_num][col_num]) copy.append(row) return copy
dc4f383455165f7b2cc9f7d7ec900485d4cf539e
636,028
import numpy as np def __min_total_cost_given_trans(mark_eq, ini, incidence_matrix, t): """ Searches the minimum total cost assumed by the marking equation starting from the initial marking and passing through the transition "t" Parameters -------------- mark_eq Marking equation i...
0ecc8118ecf87592ab250385f2d09ab4865ef968
636,030
def get_host(addr, is_ssl=False): """ return a correct Host header """ host = addr[0] if addr[1] != (is_ssl and 443 or 80): host = "%s:%s" % (host, addr[1]) return host
3d825120caa54709030f34a34a596f00ab285bd0
636,031
def validate_domain_to_record(domain): """ remove TLD part of validate domain record Args: domain: validate domain(include _acme-challenge.[input_domain] Returns: _acme-challenge.[input_domain_without_TLD] """ domain_list = domain.split('.')[:-2] if len(domain_list) > 0 and d...
241a1b573177f223594b4aa4d38665504d65301d
636,032
def _get_title(cfg, alias_1, attrs_1, alias_2=None, attrs_2=None, op_type='-'): """Get title for plots.""" if alias_2 is None: title = alias_1 if cfg['years_in_title']: title += f" ({attrs_1['start_year']}-{attrs_1['end_year']})" return title if attrs_2 is ...
bbfeeea71513b182a153b2b8327c12847252053f
636,033
def track_model_graph(model) -> dict: """Tracking Model Graph Data Meta-information Arguments: model (Torch-model): The model being tacked Returns: dict: """ model_metadata = {} try: for param_tensor in model.state_dict(): model_metadata[param...
dcb54b3e9cfe1c69c984d0b89c3de067a4380d57
636,034
def average_bmi(df): """ Returns average BMI, rounded to to d.p. """ return round(df.bmi.mean(), 2)
529771e226de6de1f58572a62054863a678ebfc4
636,035
def vmap_slice(array, indices): """Convenience function for indexing that differs along first dimension .""" return array[indices]
e392d7f79556c698ad9da541eb16970ea8ea848f
636,037
def get_mesh_cell_array(mesh, array_name): """Retrieve a cell array from the mesh.""" cell_data = mesh.GetCellData() return cell_data.GetArray(array_name)
d58ff0669d28011095bc448a44db9145aa12f166
636,038
def dist_to_str(dist): """format scipy-dist distribution """ dname=dist.dist.name dargs=dist.args # hack (shorted notation) dname = dname.replace("norm","N") if dname == "uniform": dname = "U" loc, scale = dargs dargs = loc, loc+scale # more natural sargs=",".j...
3414cf6106a93c59b320a91edf427d505341c90a
636,039
import aiohttp async def vkApiRequest(api_method: str, parameters, method_url="https://api.vk.com/method/") -> list[dict]: """ Асинхронный запрос """ async with aiohttp.ClientSession() as client: request = await client.request(method='POST', url=method_url+api_method, params=parameters) data =...
b9fb2b7fc32ff8c81ac352f11c98b6a9129ba0d2
636,041
import json def get_config_from_json(json_file): """ Get the config from a json file :param json_file: :return: config(dictionary) """ # parse the configurations from the config json file provided with open(json_file, 'r') as config_file: config_dict = json.load(config_file) return config_dict
1b400d0c6b8939ceadb729171a3bb2132a872f5c
636,043
import json def extract_first_geometry_fragment(geojson): """Given a geojson document, return a geojson geometry fragment marked as 4326 encoding. If there are multiple features in the document, just make a fragment of the first feature. This is what PostGIS's ST_GeomFromGeoJSON expects. :param g...
abf775647969d0eee0eb73877313510a236d26ac
636,044
import os import time def file_ready(file_path): """Check if file is ready.""" while not os.path.exists(file_path): # flush nfs cache by chowning parent to current owner parent = os.path.dirname(os.path.abspath(file_path)) os.chown(parent, os.stat(parent).st_uid, os.stat(parent).st_gi...
53f4b027a963cefb99df1bc3c1934111801e4a14
636,045
def count_orphan_resource_providers(db): """Count all orphan resource providers in the nova_api database.""" sql = '''\ SELECT COUNT(*) FROM nova_api.resource_providers rp JOIN nova.compute_nodes cn ON cn.hypervisor_hostname = rp.name WHERE cn.deleted = 0 AND rp.uuid != cn.uuid ...
18875ee9f6afd788198f9044397cec8a6383f05d
636,046
def traverse_map(input_map, right=3, down=1): """Travel down the input map by heading right and down a fixed amount each iteration. The map consists of clear ground '.', and trees '#'. The map repeats to the right infinitely. Get the number of trees that would be encountered travelling from the top ...
9844c795581e285f26e81258f19381efb0a705ba
636,047
def _date_to_string(d): """Make string of date in Nexus format Args: d (datetime): Date object Returns: String with date """ id = d.day im = d.month iy = d.year if im < 10: st = '0' + str(im) else: st = str(im) st = st + r'/' if id < 10: ...
3deb73805f5123f7b7c1cb92bde1169f573f6fae
636,048
def get_input(incoming): """Get input from Layer class or tensor Check if input is available via get_output() function or turn tensor into lambda expressions instead; Also try to fetch shape of incoming via get_output_shape(); Returns ------- : tensor Tensor with input : li...
d03a14cd30e998098e191feb3c6c2784d1261f02
636,050
def _quoted(arg): """Check if arguments to framework functions are wrapped in quotes. Args: arg (str): The target argument Returns: bool: True if `arg` is quoted """ return arg.startswith("\"") and arg.endswith("\"")
117d8bbd1e90a6fdaba8a22bcb62643cc98a7dfe
636,051
def cnmr_match_tag(text): """Detect Carbon NMR data from splitted spectral sample text param text:splitted spectral sample text return:string related to Carbon NMR data """ cnmr_data = [] for data_block in text: cnmr_patterns = ["13C NMR", "13C{1H}"] for pattern in cnmr_patterns:...
600b411e74e49ca083d7ced069a1e5c77bbb0288
636,053