content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def countDuplicate(numbers): """ Count Duplicated Number in a list :type numbers: interger_array :return: interger Examples: >> countDuplicated([1,2,1,2,3,4,4]) 3 >> countDuplicated([1,2,3,4]) 0 """ count = 0; dCount = {} # Detect Non Unique Numbers for n in nu...
0cff645dcbefebad75e7c0ef94c537cd318b9eec
601,007
def aggregate_fields(df, list_of_fields, separator, agg_field_name): """ Join multiple columns of a dataframe into a single column. Args: df (pandas df) list_of_fields (list of strings): columns from df to aggregate separator (string): string separator to use in the aggregation ...
b5527c58e6290033b4e1a554dfa2572be5b3f54a
601,008
def DefaultOccurrenceRanking(occurrence): """Default function for ranking an occurrence. Note: The default behavior works for component classifier and for project classifier, it works for cpp callstack class ranking. Args: occurrence (Occurrence): a collection of indices where some "name" occured in...
b4b8b764fc074e0969088720d3025397eade2208
601,010
def simple_linear_regression(x_arr, y_arr): """Performs a simple linear regression Args: x_arr: An array containing all of the x values of the points y_arr: An array containing all of the y values of the points. This should be the same length as the x_arr. Returns: A tuple (a, b) ...
931e1e8bf87b1f074df510bf4e5cd4af7d568ba0
601,013
def _lambda_ps(_, a, b, c): """Phase space factor.""" return (a - b - c) ** 2 - 4.0 * b * c
e8d5e4be63eca1350841a414917b527b17ec481c
601,016
def to_bool(value): """ Convert a value to boolean :param value: the value to convert :type value: any type :return: a boolean value :rtype: a boolean """ if value is None: return None if isinstance(value, bool): return value elif isinstance(value, str): i...
9d89edeb5254e69884dee121e0639e7c9a7dba1a
601,020
def _group_by_size_histogram_data(dataframe, group_by_key): """Returns a histogram of the number of elements per group. If you group by sequence_name, the dictionary you get returned is: key: number of predictions a sequence has value: number of sequences with `key` many predictions. Args: dat...
8f0e101ffbbb9f8967e08517790ac68cbaedd040
601,021
def generate_path(paths): """Generate path string from path list""" path_str = "" for path in paths: if path_str == "": path_str = str(path) else: path_str += "->" + str(path) return path_str
8108d4ea1d403697d9cb7027735ae8f8f9ea5b8c
601,025
def calculate_thermal_params(input_dict): """ Calculates the mass and surface area of a battery by calculating from its current parameters the mass / specific energy and volume / specific energy ratios. If module_capacity and module_surface_area are provided, battery surface area is calculated by s...
dfec02f4d3dac7496759e8dd51a9a0f4f11f5a21
601,026
def contains(list1, list2): """ Check if some elements of list1 appear in list2 Return the intersection of the two lists """ return [ it1 for it1 in list1 if it1 in list2 ]
f5676a2ce9c42ceb935caa8c09810df7f216db9e
601,028
def set_column_text_len(dat, col_name): """ Get number of words in selected columns for each record """ dat['{}TokensLength'.format(col_name)] = dat[col_name].str.split(" ").str.len() return dat
eabc939c51656280ed0e87eb54225e36dae9b52d
601,031
def blend_color(a, b, ratio) -> tuple: """Blends and returns the mix of colors a and b to a given ratio. Note: ratio argument must be a 3-float sequence.""" return ( int(a[0] + (b[0] - a[0]) * ratio[0]), int(a[1] + (b[1] - a[1]) * ratio[1]), int(a[2] + (b[2] - a[2]) * ratio[2]) ...
772ebfd4933d4da00f4c7b3fe56a91474b3ae600
601,032
import json def input_fn(request_body, request_content_type): """ Deserialize and prepare the prediction input """ if request_content_type == "application/json": request = json.loads(request_body) else: request = request_body return request
aa90af182e93cb08a07858ccbaf9b35cefe4243a
601,034
import math def factoradic_to_index(factoradic): """ Convert a factoradic to the index.""" value = 0 for idx in range(len(factoradic)): value += factoradic[idx] * math.factorial(idx) return value
4396e5a312f8c5e221a2cc8bd634d41861e35cf2
601,039
import importlib def multi_live_bridge(plugin, item_id, item_module, **kwargs): """Bridge between main.py file and each channel modules files Args: plugin (codequick.script.Script) item_id (str): Multi live TV channel menu to build (e.g. auvio) item_module (str): Channel module (e.g. ...
b3a907c286d115d6430d6e6d62f5b222881215b5
601,041
import math def logfactorial(n, k=0): """calculate the log of factorial n: log(1) + ... + log(n). optional argument: k (default 0) to calculate log(n!/k!) assumes n and k are non-negative integers. If k>n, the result is 0, not an error. Examples: >>> round(math.exp(logfactorial(5)),5) 120...
2f7e217b5aa0311dfcd5e5d86e9b14c232101861
601,044
def find_kth(arr, k): """ Finds the kth largest element in the given array arr of integers, :param: arr unsorted array of integers :param: k, the order of value to return :return: kth largest element in array :rtype: int """ # sanity checks # if this is not a valid integer or float,...
a01861748353f61fb018e24ba786766ba266c410
601,047
def is_testcase(func): """ Returns true if the given function is a testcase. :param func: Function object. :return: True if the function is decorated with testcase. """ return hasattr(func, "__testcase__")
98baa5fdbfbab32eabf5ec97844457f27b230ab7
601,054
import torch def normalize(x, axis=-1): """Normalizing to unit length along the specified dimension. Args: x: pytorch Variable Returns: x: pytorch Variable, same shape as input """ x = 1. * x / (torch.norm(x, 2, axis, keepdim=True).expand_as(x) + 1e-12) return x
261a83f71d514d47f16d5f13c9be18f185c2053f
601,056
def get_seq_identity_bytes(seq: bytes, other_seq: bytes) -> float: """Return the fraction of amino acids that are the same in `seq` and `other_seq`. Examples: >>> get_seq_identity(b'AAGC', b'AACC') 0.75 """ assert len(seq) == len(other_seq) return sum(a == b for a, b in zip(seq, oth...
5b4d06f4172304171450b76a0debb19b9e006bfe
601,058
from typing import Any def get_logging_id(obj: Any) -> Any: """Returns logging ID for object. Arguments: obj: Any object Returns: 1. `logging_id` attribute if `obj` does have it, or.. 2. `__qualname__` attribute if `obj` does have it, or.. 3. `str(obj)` """ return...
9e441a232462ff577b2aaef4ac075fdd5a56a85d
601,059
def find_namespaced_pods(namespace, job_name, api_client): """find pod by namespace and job name Args: namespace (str) - job_name (str) - api_client (CoreV1Api) - Returns: str - Name of the pod if found """ api_response = api_client.list_names...
54c090d243aafb9b0c1c75477ca2b1cabe38a3f2
601,061
def updated_querystring(context, key, value): """Take the current GET query and update/add an entry""" current_query = context["request"].GET.copy() current_query[key] = value return context["request"].path + "?" + current_query.urlencode()
73cb508f61dbecad83ca3cdb72ecb849ead36e51
601,065
def get_heroku_connect_table_name(model_cls): """ Return the table name (without schema) associated with a model class. Args: model_cls: A connected model class object Raises: LookupError: if no table name is associated with the given class """ # strip schema and quotes from _...
c8aa1dcde43b3fb668d8bc9507df2de4069404c7
601,068
def find_exec_in_executions(searched_exec, executions): """ Search if exec is contained in the executions. :param searched_exec: Execution to search for. :param executions: List of executions. :return: Index of the execution, -1 if not found.. """ for i, existing_exec in enumerate(executions...
6d2dd2931742a1395a81462643afdbef2b49087e
601,069
def send_api_data(apiuser_with_custom_defaults, simple_sig_auth_credentials): """ Pytest fixture. Returns a helper function that sends API data via the provided `api_client`, to the provided `url`, with the given `req_body`, via the given HTTP `method`. An API user is created and used for authentica...
797c613be310ddfb1c75032281249473b9f6eea4
601,070
import math def timer_needs_paint(time_remaining, time_max, dt): """ Returns true if a tick of dt will necessitate a paint of the timer, where the time left was time_remaining """ if time_max < float("inf") and time_max > 0: time_remaining_fraction = time_remaining/time_max new_tim...
c0ebff8b644f285cfa491646a6ca8d2361040aff
601,072
def an3d(self, kywrd="", key="", **kwargs): """Specifies 3-D annotation functions APDL Command: /AN3D Parameters ---------- num Unique number assigned as each annotation is applied to a model. These numbers are applied sequentially, although when an annotation entity is del...
f37b28dc870a1310709c8e77107c36c44acc4877
601,076
import re def dewikify(input_text): """ Dewikify a wikified string. Args: input_text (str): wikified text ([[word]]s [[be|are]] [[write|written]] [[like]] [[this]]) Returns: str: unwikified text (words are written like this) """ #https://regex101.com/r/yB0pZ6/...
f06327752b96512c59c2b0866bd3ee55e0ed8285
601,077
def own_commit(repo, commit): """Return true iff commit appears to be from the repo owner.""" return not commit.author or commit.author == repo.owner or commit.author.login == 'web-flow'
21b33d0c8b62d5e5e546ac1b5067754188747588
601,082
def getValidStates(Array, currentPos): """ A valid move is consider: UP : A[i-1][j] DOWN : A[i+1][j] LEFT : A[i][j-1] RIGHT: A[i][j+1] but with the condition the cell isn't marked with 1 (WALL) or isn't out of bounds Returns a tuple int Array containing the possible M...
df62c6d66b25923006e2aae42bd68ab58e26a2ce
601,084
from typing import Tuple def get_wires_of_gate(gate: Tuple): """Get index bit that gate act on Args: gate (qiskit.QuantumGate): Quantum gate Returns: numpy arrray: list of index bits """ list_wire = [] for register in gate[1]: list_wire.append(register.index) retu...
e98fffc2a0b77e4d396c5d4cebe6484c033205b0
601,086
def bast_annotations_to_list(annotation): """Given an annotation file, return a list of them.""" result = [] with open(annotation) as ann: for line in ann: result.append(line.split(' ')[1].strip()) return result
8c3bced3268264b146dee8e474e4710e6df9d2df
601,090
def check_test() -> bool: """ Verify that testing is functional Returns ------- bool Default to true """ return True
1ccd497a2625ce7e45ff296a3d5886055e02a938
601,095
from pathlib import Path def name2ncc_path(name: str, src_dir: Path, extension: str): """Resolve a NCC data archive path from a kernel name.""" path = src_dir / f"{name}{extension}" if path.is_file(): return path # Some of the benchmark sources are dataset dependent. This is reflected by ...
a897f793292480375fdfc06ffc2729a052b9bedc
601,096
from typing import Union from typing import MutableMapping from typing import Any import pathlib import yaml import toml def read_adfh_file(file: str) -> Union[MutableMapping[str, Any], str]: """Parse an ADFH file into dict. Args: file: Path to ADFH file. Returns: Tuple either with the d...
a7e7b971e8f1cdff91cf5dfb5e61c7ae64a63541
601,097
def makedocstr(parent_class, subclass_method): """ Compose a string (to be used as doc string) from a method's doc string in a parent class and an additional doc string in a subclass version of the method. @param parent_class: class object for parent class. @param subclass_method: method object...
eddfb32afab3169e9e16a46f92cbe831225e1bc7
601,103
import math def percentile(vals, percent): """ Calculates the interpolated percentile given a sorted sequence and a percent (in the usual 0-100 range).""" assert vals, "Empty input sequence." percent /= 100.0 k = (len(vals)-1) * percent f = math.floor(k) c = math.ceil(k) if f == c: return vals[i...
e251f776a0832e9191e1864ac9e647da737d9f02
601,108
import re def remove_integration(s: str) -> str: """Search for integration values in cell and strip them""" return re.sub(r"(1|2|3)H,\s?", "", s)
657d7553c128cb14ba67eaf9cb7bd32100e40c76
601,110
import random def assign_random_coordinates(node_tuple_list, max_x_coordinate, max_y_coordinate): """ @param node_tuple_list a list with entries of the form (v, x, y) or (v), where v is a node number and x,y are coordinates, if present @return a modified node_tuple_list in which tuples with no ...
1bd4e0c985938e00d609acf931f149168546de31
601,111
def financial_measures(record: dict): """ Function to move values from `prov_measure` to `value_usd` for financial measures. prov_subcategory values are replaced with 1 for coding. Parameters ---------- record : dict Input record. Returns ------- type Record with `...
b838f5d398f1a28186f1b7ae5e3e7b29cbac76a6
601,113
def _get_custom_eval_config() -> dict: """ Custom eval file for computing hota with minimal output. See trackeval/eval.py for more informations about config Returns: dict : config file """ eval_config = { "USE_PARALLEL": False, "NUM_PARALLEL_CORES": 8, "BREAK_ON_ERRO...
a2f918093165ac850ca55ce72a67e4164d812f77
601,119
def uv60_to_xy(u60, v60): # CIE1960 to CIE1931 """ convert CIE1960 uv to CIE1931 xy coordinates :param u60: u value (CIE1960) :param v60: v value (CIE1960) :return: CIE1931 x, y """ denominator = (((6 * u60) / 2) - (12 * v60) + 6) if denominator == 0.0: x, y = 0.0, 0.0 else: ...
5d4fe7d30446a2a9f3396c56c7a7cc3250fd6e7d
601,120
def linear_skew(phenotypes, selection_gradient): """Transforms the phenotype data to match the given selection gradient and stores them as gpm.data.phenotypes. Parameters ---------- selection_gradient : float, int. (default=1) The selection gradient defines the slope of the phenotype-fitness fu...
d3bb72e9b3acbf7501f3d31b98631bf67e36e4b1
601,121
import string import random def get_random_string(length): """Generate a random string from lowercase ascii letters.""" letters = string.ascii_lowercase return ''.join(random.choices(letters, k=length))
dce81f939b3ffe5e5413f59ac341fbcf24b1f010
601,122
def ifdel(dictt, key): """ If a key is in a dictionary delete it. Return [modified] dictionary. """ try: del dictt[key] return(dictt) except: return(dictt)
887ae388851b4e0e8a67e4f1713a7dcaf2ffa1ac
601,123
import platform def get_python_version() -> str: """ Python version string """ return "{} [{}, {}]".format( platform.python_version(), platform.python_build()[0], platform.python_compiler(), )
979a8efab507f7a7e3353cfff9e278fa904825c5
601,124
def parse_encode_donor(data): """Parse a python dictionary containing ENCODE's donor metadata into a dictionary with select donor metadata :param data: python dictionary containing ENCODE' donor metadata :type s: dict :return: dictionary with parsed ENCODE's donor metadata :rtype: dic...
0504ab97e3194275b9766854acb2bfca55779341
601,125
def is_match(i: int, j: int, seq1: str, seq2: str) -> bool: """True if the sequences match at positions i, j; False otherwise. """ return seq1[i-1] == seq2[j-1]
09c18ba4324782d2e07230379e141c2efd7d6273
601,130
def asList( o ): """Convert to a list if not already one""" if not isinstance( o, list ): return list(o) return o
c12dc6d712cc182d274f28b07544ac55f20f99e5
601,131
def func_name(f): """ Return a human readable version of the function's name. """ if hasattr(f, '__module__'): return "%s.%s" % (f.__module__, getattr(f, '__name__', f.__class__.__name__)) return getattr(f, '__name__', f.__class__.__name__)
d838f805f54936744df64ef6a26e86725ddce8f3
601,132
def _extract_cc_info(proto_cc_info): """A map function to extract the `CcInfo` from a `SwiftProtoCcInfo`. Args: proto_cc_info: A `SwiftProtoCcInfo` provider. Returns: The `CcInfo` nested inside the `SwiftProtoCcInfo`. """ return proto_cc_info.cc_info
d67602e0987f8b3cc450fc8148b89df28d2c9fc9
601,133
from typing import List from typing import Tuple from typing import Union def __shift_interval_by(intervals: List[Tuple[float, float]], weight: Union[int, float]): """ Shift the intervals by a weight """ return [[x + weight, y + weight] for [x, y] in intervals]
738298d2a38119ead4aeec7beff63c1dccae8fd4
601,138
def is_function(name): # type: (str) -> bool """ Return True if a serializer/deserializer is function. A function is prefixed with '::' so that the IDL generated code calls it as a function instead of as a class method. """ return name.startswith("::")
e7aa3a55b775aee3373efa33b5e0f6e32637d65a
601,139
def optiWage(A,k,alpha): """Compute the optimal wage Args: A (float): technology level k (float): capital level alpha (float): Cobb Douglas parameter Returns: (float): optimal wage """ return A*(1-alpha)*k**alpha
848ada4c0466576f7df08e42f666d3ff264f841c
601,145
def calculate_area(nodes: list): """ Calculates area of a section. :param nodes: Nodes list. The coordinates of each corner of a section. :return: Area of the section. """ _nodes = nodes.copy() # Add the first node to the list _nodes.append(_nodes[0]) # Number of nodes _n = len...
f1bc15cf7d9ea20b912df1e4587b1e679bd5210f
601,153
import logging def CreateGsutilLogger(command_name): """Creates a logger that resembles 'print' output. This logger abides by gsutil -d/-D/-DD/-q options. By default (if none of the above options is specified) the logger will display all messages logged with level INFO or above. Log propagation is disabled....
dd37c56ed224d00578fba850fda1cd113aefb55f
601,155
import functools def skipIfNoService(services): """ A decorator for skipping tests if the provider does not implement a given service. """ def wrap(func): """ The actual wrapper """ @functools.wraps(func) def wrapper(self, *args, **kwargs): provi...
5d308bf5ea3b7fd907f90ffa9a13b4cc10b6fdc4
601,157
import itertools def _group_multiplexed(sample_list): """Group samples sharing the same reads file.""" grouped = itertools.groupby(sample_list, key=lambda x: x.path) return {key: list(group) for key, group in grouped}
e883091563162bdceda1c95f3c937593660a89e0
601,159
def add_vec3_vec3(va, vb): """Return the sum of given vec3 values. >>> va = [1,5,-2] >>> vb = [-10,4,6] >>> add_vec3_vec3(va, vb) [-9, 9, 4] """ assert type(va) == list assert type(vb) == list vv = [ None for _ in range(3) ] for row in range(3): vv[row] = va[row] + vb[...
360bc090ad463b1c8898cacfbacbe4b653326967
601,161
def _top_module(module_name): """Return the name of the top level module in the hierarchy.""" if module_name[0] == '.': return '%LOCAL_MODULE%' return module_name.split('.')[0]
bf9321c004f983507aa405c83a9ce5776b1b713f
601,163
from typing import Iterable def listify_nested_iterables(iterable): """Recursively convert iterables to lists. Recursively exhaust iterables into lists. Careful if you have iterables you do not want to accidentally listify. We only handle strings. Args: iterable (iterable): An iterable whose...
9cc00282e1407f0aa9854697a15253ede16fcc2a
601,166
from typing import Callable def _cxml_element_func(tagname: str) -> Callable: """ Generate a function to extract text from an XML element. Returns a function which retrieves the text element associated with a certain xml tag from an xml root element. Can be used like a partial: .. code-bloc...
7142073f46258f28ef9ab911bcd65cc67ffc391e
601,169
from typing import Any def vertex_property(G, vproperty: str, idx: int) -> Any: """ Get vertex (node) property from graph Parameters ---------- G: Graph vproperty: str Vertex property name idx: int Vertex index Returns ------- Any Vertex proper...
90b3164d3b5917b8b4a5b5570856345e2ec68b8d
601,172
def combine_filters(*filters): """Combines all the filters passed in.""" def combined(elem, doc): for f in filters: f(elem, doc) return combined
f4ee94d3150da72ba5228737bc98e70233083ce6
601,175
def null_experiment(args, model_iter_fn, model, example_inputs): """ A no-op experiment useful for making sure TorchBenchark alone works properly. """ return []
267c6204233070562efe38334ccad31a6834bf62
601,181
def tribonacci_recursive(n): """ Uses recursion to calculate the nth tribonacci number Args: n: the number Returns: nth tribonacci number """ if n <= 1: return 0 elif n == 2: return 1 else: return tribonacci_recursive(n - 1) + tribonacci_recursive...
cf43f058d91d6e08b4c84d37ef498e0ed1b0e403
601,184
def int_to_state(p, state_number): """ Converts integer to array of fermion-configuration Args: p - dictionary that contains the relevant system parameters state_number - integer corresponding to state Returns: statelist - fermion configuration """ # convert integer to s...
20c875510e5d3900cb4f35111c23c67e60db1fb2
601,186
def read(path, mode='rt'): """Read a file and return its content.""" try: with open(path, mode) as fp: return fp.read() except Exception as e: return f'FILE ERROR: {e}, path {path!r}'
58b4c5d8939271e187196277453cda052a6e7f68
601,188
import math def calc_turn_value(us, them, current_yaw): """ Calc turn speed required to steer 'us' towards 'them'.""" dx = them[0] - us[0] dz = them[1] - us[1] yaw = -180 * math.atan2(dx, dz) / math.pi difference = yaw - current_yaw while difference < -180: difference += 360 while ...
76bb6a1bcf082c63857fa2cce351404a9df663a6
601,189
def get_common_movies(first_actor_credits, second_actor_credits): """ Takes two arrays of actor credits, first_actor_credits and second_actor_credits Returns an array of movies that are common to both actors """ common_movies = [] for first_movie in first_actor_credits: for second_movie in second_actor_...
a90d8105ddc58fa24a65ee8f6bacae8fbbc01f54
601,190
import ssl def _ssl_opts(rpc_opts): """ Given a dict of config options returned by _rpc_opts, return a dict of options which can be passed to the ssl module. """ ssl_opts = { 'ca_certs': rpc_opts['ca'], 'keyfile': rpc_opts['client_key'], 'certfile': rpc_opts['client_cert'],...
561a7a4a89ede36391535f868fa63aaad5a03940
601,194
def constituent_copyout_subname(host_model): ############################################################################### """Return the name of the subroutine to update constituent fields from the host model. Because this is a user interface API function, the name is fixed.""" return "{}_ccpp_update_...
3961e4e2f864ba687304999bf0aa62404d9d36a1
601,197
def square_image(image): """ Squares a PIL Image """ width, height = image.size if width == height: return image size = min(width, height) extra_width = width - size extra_height = height - size # define the box left = extra_width / 2 right = left + size up...
72a2fa2d0bf99e17433569ef14fca32f951c2d34
601,201
from typing import List def ligands_from_file(fname: str) -> List[str]: """ Load a list of ligands from file. """ with open(fname, 'r') as f: return [line.strip().zfill(8) for line in f.readlines()]
e6e6b9b092162203bb31eea7c1345a99ca1f53ee
601,202
from typing import List import re def _remove_lines(txt: str) -> str: """ Remove lines of separating characters long at least 20 characters. """ txt_tmp: List[str] = [] for line in txt.split("\n"): if re.match(r"^\s*[\#\-><=]{20,}\s*$", line): continue txt_tmp.append(li...
7009756b5204239c503478e7251ccd586146b65b
601,206
def line_number(file_path, text): """Return line number of the text in the file""" with open(file_path, "r") as lines: for line_number, line in enumerate(lines): if text in line: return line_number + 1 raise RuntimeError(f"Can not find {text} in {file_path}")
9bfdcea3be6b0f380132e17c2ad7b0f56bc6a26c
601,207
from math import asin, atan2, cos, log, pow, sin, sqrt def calcLatLon(northing, easting): """ This function converts northings/eastings to latitude and longitudes. It is almost entirely based upon a function written by Tom Neer found in November 2017 at his blog: http://www.neercartography.com/con...
c598ee37ac52a8afe95c1fdd6f871b57aed175e0
601,210
import math def predict_prob(length=1.0, gap_width=1.0): """ Predicts the probability that the needle will hit one of the two parallel lines. length and gap_width can be scalars or arrays. """ L = length D = gap_width if L > 2 * D: return ( (D * ( ...
d2778c501436351f87254fe69c0ad01591a7d52d
601,213
def line_words(S, W, text_words, i): """Return list of words line (S[I]: index of first word in i-th line).""" j = i + 1 w_i = (range(S[i], S[j]) if j in S else range(S[i], max(W.keys()) + 1)) return [text_words[k-1] for k in w_i]
d7d52e6ec567f00104eb73bba2e4cc66f28df951
601,216
import pkgutil def module_exists(modname): """Checks if a module exists without actually importing it.""" return pkgutil.find_loader(modname) is not None
113856468d154ee862347f2821a7dfa0213b1728
601,218
def _read_gold_conllu_simplified(gold_file): """ Reads in the gold annotation from a file in CoNLL-U format. WARNING: Does not read in extra edges in 9th column! Returns: - tags: a String list containing one sequence tag per line. E.g. [B-Kochschritt, L-Kochschritt, U-Zutat, O] ...
d864d59dac52e85b0e61afdf8998ec4630bde18b
601,219
from typing import Optional def _round_filters(filters: int, width_coefficient: Optional[float], depth_divisor: float) -> int: """ Calculate and round number of filters based on width coefficient multiplier and depth divisor. Args: filters: number of input filters. width_coefficient: widt...
93ce763ba61fb7e3c4ee708c62e7b240f7a9384d
601,223
from typing import Dict def _check_pyl_trainer_config(config: Dict) -> Dict: """ Checks the trainer config for pytorch lightning and adds default values for missing required entries :param config: a dictionary with key:values required by the init_trainer function :return: dictionary with trainer confi...
a25cad1ecbc48c449bdd25d7145e00dc46d3bfbe
601,225
def _cal_cutoff_position(length, thickness, keyIdx): """Returns cutoff indices of keyIdx-centred truncated list Args: length: `int`, length of a list thickness: `int`, cutoff thickness - number of slices keyIdx: `int`, index of the key slice Returns: a tuple of two `int` """ left_block = (th...
9feabea00240ec1e0d510b622f97a6fa9f918e6f
601,226
def complement(G,create_using=None,name=None): """ Return graph complement of G. Parameters ---------- G : graph A NetworkX graph create_using : NetworkX graph Use specified graph for result. Otherwise a new graph is created. name : string Specify name for new gr...
c272220857e2ff650d33d171c9c7f7e2a75fb9fd
601,228
def arbitary_function(**kwargs): """A function which will return what is passed.""" return kwargs
241ac80bf30b62f1ca5e389010e412d78a6b0f8e
601,229
def row_to_matrix(row, nkeys_per_row): """Convert keymap definition in a row to a matrix for easier indexing. Args: row: a list of key definitions. ncols_per_row: a list of numbers indicating number of keys in each row. The sum should add to the length of `row`. """ assert sum(nkeys_per_row) == l...
8ea2e41d65872f2ebf7d819d324666f0c748912d
601,230
def check_rule_counters(duthost): """ Check if Acl rule counters initialized Args: duthost: DUT host object Returns: Bool value """ res = duthost.shell("aclshow -a")['stdout_lines'] if len(res) <= 2 or [line for line in res if 'N/A' in line]: return False else: ...
a08e543f0a527c41c6167d50382f0606464d1874
601,232
async def _get_post_id(db, author, permlink): """Get post_id from hive db.""" sql = """SELECT id FROM hive_posts WHERE author = :a AND permlink = :p AND is_deleted = '0'""" post_id = await db.query_one(sql, a=author, p=permlink) assert post_id, 'invalid auth...
f3d806fe48c04ca28549abf800d9a957f9f220aa
601,233
import random def uniformly_random( num_tasks, num_resources, rng_seed=None, verbose=False): """Random scheduling algorithm. Parameters ---------- num_tasks : int Number of tasks num_resources : int Number of resources rng_seed : int [default=No...
ecfd4748727348c65c08913087de8faf04406968
601,235
def to_pymetis_format(adj_mat): """Transform an adjacency matrix into the pymetis format. Parameter --------- adj_mat: Adjacency matrix. Returns ------- xadj, adjncy, eweights: Parameters for pymetis. """ xadj = [0] adjncy = [] eweights = [] n_rows = adj_mat.shape[0] ...
f1923fc5e5cf964522713f702ca0c2b5fd08b1ec
601,240
def remove_null_clickout(df): """ Remove all the occurences where the clickout reference is set to null (Item to predict) """ df = df.drop(df[(df['action_type'] == "clickout item") & (df['reference'].isnull())].index) return df
1d85db766bc6adb0db66334e0a80cd53ae91b649
601,241
def standardize_positions(s: str) -> str: """Standardizes position names Args: s (str): the position string Returns: str: the standardized string """ mapping = {'Def': 'DST', 'Defense': 'DST', 'DEF': 'DST', 'def': 'DST', 'dst': 'DST', 'PK': 'K', 'Kicker': 'K'} std = mappin...
44261362e6846b3310dd0b3078cfdb9aacdb6182
601,242
def highlight_min_max(s, min_color="#5fba7d", max_color="#e67575"): """ Highlights the max and min value in each column of the dataframe. :param s: the series to be processed :param min_color: color for highlighting the min value :param max_color: color for highlighting the max value :returns: ...
c37679fe69e79b3f7f2d277dfc6f9a32c104684a
601,246
import collections def analyze_results(import_dict_objects, type_hint_objects): """ Analyze the differences between _import_structure objects and TYPE_CHECKING objects found in an init. """ def find_duplicates(seq): return [k for k, v in collections.Counter(seq).items() if v > 1] if list...
4e3294584a81097cfc26ca7d497c39b1a1a8e38a
601,250
from typing import Iterable def is_iter(obj): """ Check if an object is an iterable. Args: obj: Object Returns: boolean """ return isinstance(obj, Iterable) and not isinstance(obj, str)
652afcff1228dbc80d5115d1ea583373fc1b941f
601,251
def shift(list, default): """ Shift items off the front of the `list` until it is empty, then return `default`. """ try: return list.pop(0) except IndexError: return default
aa195045909bf76cb29f2d918447691f8c2d323e
601,252
def generate_latex_anchor(label_id): """Generates a LaTeX label with the given ID""" return "\\anchor{%s}" % label_id
36e4fcc4a3759e7edddba367e1b2b56bf8750c25
601,257
def binary_search(lis, elem, start, end): """ Return index of matched position of elem in lis between index start and end (inclusive) or return -1 :param lis: Sorted list :param elem: element to search """ assert 0 <= start <= end < len(lis) if end == start: # If there is only one el...
7b903803b38aa23b2c124a6e23dc14b9bb1c8e28
601,259