content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def can_translate(user): """Checks if a user translate a product""" return user.permissions['perm_translate']
c6797346d8bd61637927af808bb9355a9220a91e
702,590
import torch def mask_finished_scores(score, flag): """ If a sequence is finished, we only allow one alive branch. This function aims to give one branch a zero score and the rest -inf score. Args: score: A real value array with shape [batch_size * beam_size, beam_size]. flag: A bool ar...
87d5d8fb45a44c54cd690280ce0baf0c4fe8dab5
702,597
import itertools def args_combinations(*args, **kwargs): """ Given a bunch of arguments that are all a set of types, generate all possible possible combinations of argument type args is list of type or set of types kwargs is a dict whose values are types or set of types """ def asset(v): ...
8e90ce285322bd17a97e4bdb75e230f7015f4b2d
702,598
def RGBStringToList(rgb_string): """Convert string "rgb(red,green,blue)" into a list of ints. The purple air JSON returns a background color based on the air quality as a string. We want the actual values of the components. Args: rgb_string: A string of the form "rgb(0-255, 0-255, 0-255)". Returns: ...
f94650ed977b5a8d8bb85a37487faf7b665f2e76
702,600
import six def _metric_value(value_str, metric_type): """ Return a Python-typed metric value from a metric value string. """ if metric_type in (int, float): try: return metric_type(value_str) except ValueError: raise ValueError("Invalid {} metric value: {!r}". ...
39a3b0e5bfe2180e1897dd87872f8e08925e8847
702,601
def getMDistance(plug): """ Gets the MDistance value from the supplied plug. :type plug: om.MPlug :rtype: om.MDistance """ return plug.asMDistance()
43cd8dfd2c698ad1cc88771c2c69f3b5e502f202
702,604
def splitFragP(uriref, punct=0): """split a URI reference before the fragment Punctuation is kept. e.g. >>> splitFragP("abc#def") ('abc', '#def') >>> splitFragP("abcdef") ('abcdef', '') """ i = uriref.rfind("#") if i >= 0: return uriref[:i], uriref[i:] else: ...
cc179fd8f064f3e87f18a9968f6f98ff0d584eb6
702,608
import yaml import re def create_kubeconfig_for_ssh_tunnel(kubeconfig_file, kubeconfig_target_file): """ Creates a kubeconfig in which the Server URL is modified to use a locally set up SSH tunnel. (using 127.0.0.1 as an address) Returns a tuple consisting of: - the original IP/Serve...
39c85681486abda0008a040ad13a37032fc182b5
702,611
def get_lines_from_file(loc): """Reads the file and returns a list with every line. Parameters: loc (str): location of the file. Returns: list: list containing each of the lines of the file. """ f = open(loc) result= [line.replace("\n", "") for line in f] f.clo...
c05101b94e459346adae553e31d25d46a8475514
702,616
def GetBuildShortBaseName(target_platform): """Returns the build base directory. Args: target_platform: Target platform. Returns: Build base directory. Raises: RuntimeError: if target_platform is not supported. """ platform_dict = { 'Windows': 'out_win', 'Mac': 'out_mac', 'Li...
0bbbad4de3180c2ea51f5149cc3c2417a22b63e9
702,618
from pathlib import Path def dir_files(path, pattern="*"): """ Returns all files in a directory """ if not isinstance(path, Path): raise TypeError("path must be an instance of pathlib.Path") return [f for f in path.glob(pattern) if f.is_file()]
5dbeeec6fe72b70381afb52dcbbea55613a37d49
702,620
def _norm_args(norm): """ Returns the proper normalization parameter values. Possible `norm` values are "backward" (alias of None), "ortho", "forward". This function is used by both the builders and the interfaces. """ if norm == "ortho": ortho = True normalise_idft = Fals...
e781c894c9d333fdbdf326120b1417b44dfc5181
702,622
import torch def all_pair_iou(boxes_a, boxes_b): """ Compute the IoU of all pairs. :param boxes_a: (n, 4) minmax form boxes :param boxes_b: (m, 4) minmax form boxes :return: (n, m) iou of all pairs of two set """ N = boxes_a.size(0) M = boxes_b.size(0) max_xy = torch.min(boxes_a[:...
1ca948e4a16016efa694d97c4829fcdfbc29e20d
702,623
def builddict(fin): """ Build a dictionary mapping from username to country for all classes. Takes as input an open csv.reader on the edX supplied file that lists classname, country, and username and returns a dictionary that maps from username to country """ retdict = {} for cours...
ddf9272e0da6616abd0495b7b159807a36a83dcc
702,628
import collections def node_degree_counter(g, node, cache=True): """Returns a Counter object with edge_kind tuples as keys and the number of edges with the specified edge_kind incident to the node as counts. """ node_data = g.node[node] if cache and 'degree_counter' in node_data: return no...
08c08f240e3170f4159e72bc7e69d99b69c37408
702,631
async def get_account_id(db, name): """Get account id from account name.""" return await db.query_one("SELECT find_account_id( (:name)::VARCHAR, True )", name=name)
3dd6b46abd8726eb34eb4f8e1850dc56c3632e5c
702,632
from typing import Any def is_a_string(v: Any) -> bool: """Returns if v is an instance of str. """ return isinstance(v, str)
f729f5784434ef255ea9b2f0ca7cdfbf726e7539
702,634
def str_to_dict( text: str, /, *keys: str, sep: str = ",", ) -> dict[str, str]: """ Parameters ---------- text: str The text which should be split into multiple values. keys: str The keys for the values. sep: str The separator for the values. Returns ...
0b34ea1b47d217929fd9df760231f4786150e661
702,640
def get_data_type(name): """Extract the data type name from an ABC(...) type name.""" return name.split('(', 1)[0]
7565b30e1e2469de929b377fde1f186d28080f94
702,644
def moving_average(time_series, window_size=20, fwd_fill_to_end=0): """ Computes a Simple Moving Average (SMA) function on a time series :param time_series: a pandas time series input containing numerical values :param window_size: a window size used to compute the SMA :param fwd_fill_to_end: index ...
d71931867c419f306824e8b240a9b1bb3fff2fdd
702,645
from pathlib import Path from typing import Sequence def load_input(path: Path) -> Sequence[int]: """Loads the input data for the puzzle.""" with open(path, "r") as f: depths = tuple(int(d) for d in f.readlines()) return depths
35472eadcd2deefbbae332b3811be7d731cb2478
702,646
def set_accuracy_83(num): """Reduce floating point accuracy to 8.3 (xxxxx.xxx). :param float num: input number :returns: float with specified accuracy """ return float("{:8.3f}".format(num))
fd1818a81ea7a78c296a85adc3621ab77fbad230
702,650
def load_file(path): """Loads file and return its content as list. Args: path: Path to file. Returns: list: Content splited by linebreak. """ with open(path, 'r') as arq: text = arq.read().split('\n') return text
348d57ab3050c12181c03c61a4134f2d43cd93cd
702,656
from typing import Type import enum def _enum_help(msg: str, e: Type[enum.Enum]) -> str: """ Render a `--help`-style string for the given enumeration. """ return f"{msg} (choices: {', '.join(str(v) for v in e)})"
e53762798e0ecb324143ee4a05c4152eaf756aad
702,657
from typing import OrderedDict def array_remove_duplicates(s): """removes any duplicated elements in a string array.""" return list(OrderedDict.fromkeys(s))
ea5a0d620139e691db99f364c38827abe39a16f5
702,658
import socket def get_ipv4_for_hostname(hostname, static_mappings={}): """Translate a host name to IPv4 address format. The IPv4 address is returned as a string, such as '100.50.200.5'. If the host name is an IPv4 address itself it is returned unchanged. You can provide a dictionnary with static map...
fd28106380c6a6d2c353c0e8103f15df264117ef
702,660
def season_ts(ds, var, season): """ calculate timeseries of seasonal averages Args: ds (xarray.Dataset): dataset var (str): variable to calculate season (str): 'DJF', 'MAM', 'JJA', 'SON' """ ## set months outside of season to nan ds_season = ds.where(ds['time.season'] == season)...
6d5b0ddc39762ceca42de6b9228c38f4bf365cd0
702,661
def getSubString(string, firstChar, secondChar,start=0): """ Gives the substring of string between firstChar and secondChar. Starts looking from start. If it is unable to find a substring returns an empty string. """ front = string.find(firstChar,start) back = string.find(secondChar,front+1) if ...
c845c3c31abce7ed8064cfd16e455c27f1aac806
702,662
def factorial_iter(num: int) -> int: """ Return the factorial of an integer non-negative number. Parameters ---------- num : int Raises ------ TypeError if num is not integer. ValueError if num is less than zero. Returns ------- int """ if not ...
36ec433bf02bdef0770f9f9b86feff9afa995eb3
702,663
def update_Q(Qsa, Qsa_next, reward, alpha, gamma): """ updates the action-value function estimate using the most recent time step """ return Qsa + (alpha * (reward + (gamma * Qsa_next) - Qsa))
f5f54d8e8b9f67c1145d967fd731ea37a4aa1e57
702,664
def get_diff(l1, l2): """ Returns the difference between two lists. """ diff = list( list(set(l1) - set(l2)) + list(set(l2) - set(l1)) ) return diff
16b2083fcd4f61cb86c563ea6773b64e6fbe6006
702,668
def identical_prediction_lists(prev_prediction_list, curr_prediction_list): """ Check if two predictions lists are the same :param prev_prediction_list: list Last iterations predictions :param curr_prediction_list: list current iterations predictions :return: bool false = not identical, true = ident...
b74140acb3c5529fb804710d4fd3bfd64bb4f009
702,669
def reverse_domain_from_network(ip_network): """Create reverse DNS zone name from network address (ipaddress.IPv4Network)""" prefixlen = ip_network.prefixlen if prefixlen % 8: return ip_network.reverse_pointer # classless else: return ip_network.network_address.reverse_pointer[(4 - (pr...
0b0b7bb6bc72cae6625e9bd024c9692253d55c88
702,682
from bs4 import BeautifulSoup def get_anchor_href(markup): """ Given HTML markup, return a list of hrefs for each anchor tag. """ soup = BeautifulSoup(markup, 'lxml') return ['%s' % link.get('href') for link in soup.find_all('a')]
ec75f36e0b14a1d20452a1b6c1233d789c03cd6b
702,683
async def get_asterisk_chan(response_json): """Get the Asterisk Channel from the JSON responses""" if response_json["type"] in ["PlaybackStarted", "PlaybackFinished"]: return str(response_json.get("playback", {}).get("target_uri")).split(":")[1] else: return response_json.get("channel", {})....
951ccc3cdea92cfb630eb24bbd9e2f2333a72f1e
702,684
def massage_error_code(error_code): """Massages error codes for cleaner exception handling. Args: int Error code Returns: int Error code. If arg is not an integer, will change to 999999 """ if type(error_code) is not int: error_code = 999999 return error_code
c9c42e71aa4684e79078673baa9a7ecfe627a169
702,687
import random def randomPartition(elems: list, bin_sizes: list) -> list: """ Randomly partition list elements into bins of given sizes """ def shuffleList(elems): random.shuffle(elems) return elems elems = shuffleList(elems) partition = [] start, end = 0, 0 for bin...
52d1d16639fa0a4566423255bb29c123879282cb
702,688
def pre_process(line): """ Return line after comments and space. """ if '#' in line: line = line[:line.index('#')] stripped_data = line.strip() return stripped_data
63640048cb07376fb73b62cb6b6d2049adec5c17
702,689
def file_tag_from_task_file(file: str, cut_num_injs: bool = False) -> str: """Returns the file tag from a task output filename. Args: file: Filename of task file with or without path. cut_num_injs: Whether to not include the number of injections per redshift bin. """ file_tag = file.rep...
2ba0180c1a06f4ae6e47659e3598c2207cca5642
702,691
import torch def cmc_score_count( distances: torch.Tensor, conformity_matrix: torch.Tensor, topk: int = 1 ) -> float: """ Function to count CMC from distance matrix and conformity matrix. Args: distances: distance matrix shape of (n_embeddings_x, n_embeddings_y) conformity_matrix: bin...
5c3d31a6455e1d8c7694a2117637e9e51478bb21
702,692
import threading def simple_thread(func, daemon=True): """ Start function in another thread, discarding return value. """ thread = threading.Thread(target=func) thread.daemon = daemon thread.start() return thread
870102cf07b92b7cdd56960a7c6da5d8521ee233
702,695
def add_gms_group( self, group_name: str, parent_pk: str = "", background_image_file: str = "", ) -> bool: """Update appliance group in Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - group - POST ...
c92cd932070913af2b98608822ad03ff4a59506e
702,697
def func_split_token(str_token): """ Splits a VCF info token while guarenteeing 2 tokens * str_token : String token to split at '=' : String * return : List of 2 strings """ if str_token: lstr_pieces = str_token.split("=") i_pieces = len(lstr_pieces) if i_...
581b7729ab8dba6f3032b6f1f3bf9bc7dd17c67e
702,698
def populate_sd_dict(herbivore_list): """Create and populate the stocking density dictionary, giving the stocking density of each herbivore type.""" stocking_density_dict = {} for herb_class in herbivore_list: stocking_density_dict[herb_class.label] = herb_class.stocking_density return stoc...
87a0b9375a5a419557443506522ab2cf8d34c308
702,701
from typing import List import pathlib def get_files( catalog: str, recursive: bool, suffix_markup: str, extension: str ) -> List[str]: """ Осуществляет поиск в каталоге и выдает список путей найденных файлов. По-умолчанию, recursive = False, ищет файлы только в каталоге. extension и suffix_marku...
99f6d591b0548aafb654d05b94271a6d9ae243b6
702,703
def pnchunk(darray, maxsize_4d=1000**2, sample_var="u", round_func=round, **kwargs): """ Chunk `darray` in time while keeping each chunk's size roughly around `maxsize_4d`. The default `maxsize_4d=1000**2` comes from xarray's rule of thumb for chunking: http://xarray.pydata.org/en/stable/dask.html#chun...
770bc7465168d89bf85800e01d1fcbb8fa0af663
702,708
import errno def _convert_errno_parm(code_should_be): """ Convert the code_should_be value to an integer If code_should_be isn't an integer, then try to use the code_should_be value as a errno "name" and extract the errno value from the errno module. """ try: code = int(code_should_be)...
949c9f17539d885a0fc4a51f3358fc3695c42e22
702,711
def _add(x): """ Add all elements of a list. :param x: List to sum :return: Sum of all elements in the input list """ return sum(x)
19d42b51dbd07a992f3256b8b0d69c1f4043fa89
702,715
def _assign_link_resids(res_link, match): """ Given a link at residue level (`res_link`) and a dict (`match`) specifying to which resids the res_link nodes map, create a correspondence dict that maps the higher resolution nodes to the resids specified in` match`. Each `res_link` node by defi...
cfb315a15ebba6e086f340dc7e6db27eadee1d2b
702,716
def checkrows(sudoku): """ Checks if each row contains each value only once """ size = len(sudoku) row_num = 0 for row in sudoku: numbercontained = [False for x in range(size)] for value in row: # if placeholder, ignore it if value in range(size): ...
3266eb936b0f3f1e22bd16cd40fbf61753876ce1
702,720
def list_is_unique(ls): """Check if every element in a list is unique Parameters ---------- ls: list Returns ------- bool """ return len(ls) == len(set(ls))
a0bc92c2e00b48d80af39020622f31059845fc94
702,721
def compute_transpose(x): """ given a matrix, computes the transpose """ xt=[([0]*len(x)) for k in x[0]] for i, x_row in enumerate(x): for j, b in enumerate(x_row): xt[j][i]=x[i][j] return xt
22988bc9802deaf1bc07182a5e85c56d54c94436
702,724
def extract_mocha_summary(lines): """ Example mocha summary lines (both lines can be missing if no tests passed/failed): ✔ 3 tests completed ✖ 1 test failed """ passes, fails = 0, 0 for line in lines: if line and line[0] == '✔': passes = int(line.split()[1]) elif ...
53d671c3d18f0421cbb512835a84f71a9588f947
702,727
def factorial(n): """ Returns the factorial of n. e.g. factorial(7) = 7x6x5x4x3x2x1 = 5040 """ answer = 1 for i in range(n, 1, -1): answer = answer * i return answer
98c0530e4e0f1de8c1c0f622e7d62a5feb042bcb
702,730
def vfun(self, parr="", func="", par1="", con1="", con2="", con3="", **kwargs): """Performs a function on a single array parameter. APDL Command: *VFUN Parameters ---------- parr The name of the resulting numeric array parameter vector. See *SET for name restrictions. ...
dba87cb721ba79a797c357160a2ebed425b3239f
702,731
def reverse_colors(frame): """ Reverse the order of colors in a frame from RGB to BGR and from BGR to RGB. """ return frame[:, :, ::-1]
210deca283c373d02c0d114daad2e23ba822b3ab
702,732
from typing import Optional def algo_parts(name: str) -> tuple[str, Optional[int]]: """Return a tuple of an algorithm's name and optional number suffix. Example:: >>> algo_parts('rot13') ('rot', 13) >>> algo_parts('whirlpool') ('whirlpool', None) """ base_algo = name.r...
c3231da2bc3f96091b6f07d38fdd2caa414e59a1
702,734
def calculate_rsi(analysis_df, column, window): """ Calculates relative stength index. Args: analysis_df: Pandas dataframe with a closing price column column: String representing the name of the closing price column window: Integer representing the number of periods used in the RSI ...
7c32751bc4aeb5583caa69397f1c19b88a208039
702,736
def has_slide_type(cell, slide_type): """ Select cells that have a given slide type :param cell: Cell object to select :param slide_type: Slide Type(s): '-', 'skip', 'slide', 'subslide', 'fragment', 'notes' :type slide_type: str / set / list :return: a bool object (True if cell should be select...
edb1323331317d53502179fe357c151a5b59af0b
702,737
import sqlite3 def query(x,db,v=True): """ A function that takes in a query and returns/ prints the result""" conn = sqlite3.connect(db) curs = conn.cursor() my_result = list(curs.execute(x).fetchall()) curs.close() conn.commit() if v is True: print(my_result) return my_result
8b914224429bdfd8d167327bf6cc0e3afaf94b3c
702,739
def build_url(selector, child_key, parent_key): """Return url string that's conditional to `selector` ("site" or "area").""" if selector == "site": return "https://%s.craigslist.org/" % child_key return "https://%s.craigslist.org/%s/" % (parent_key, child_key)
f8f00d4f9d20c3312f2b36d014365dbcf08242bc
702,740
def sieve_of_eratosphenes(n: int) -> list[int]: """ Finds prime numbers <= n using the sieve of Eratosphenes algorithm. :param n: the upper limit of sorted list of primes starting with 2 :return: sorted list of primes Integers greater than 2 are considered good input that gives meaningful ...
4dbfdffe0ff6e360361daccdcd39fb7fb3d09a03
702,743
def recovery_secret_to_ksk(recovery_secret): """Turn secret and salt to the URI. >>> recovery_secret_to_ksk("0123.4567!ABCD") 'KSK@babcom-recovery-0123.4567!ABCD' """ if isinstance(recovery_secret, bytes): recovery_secret = recovery_secret.decode("utf-8") # fix possible misspellings...
a8832a9e970e4728dcb5f779fd4463abf142e69e
702,746
import click from datetime import datetime def validate_end_date(ctx, param, value): """ Validator for the 'click' command line interface, checking whether the entered date as argument 'start_date' is later than argument 'end_date' and 'end_date' argument is later than current date. """ # option w...
b1416fdc614aad53ffab537275b7ae2cb15eddce
702,747
def string_pair_list_to_dictionary_no_json(spl): """ Covert a mongodb_store_msgs/StringPairList into a dictionary, ignoring content :Args: | spl (StringPairList): The list of (key, value) to pairs convert :Returns: | dict: resulting dictionary """ return dict((pair.first, pair.s...
fdcaa23eed195d389456a6ceb0fdde2d06d932d6
702,749
import re def sanitize(inStr): """Hide any sensitive info from the alert""" # Key-value pairs of patterns with what to replace them with patterns = { "https\:\/\/oauth2\:[\d\w]{64}@gitlab\.pavlovia\.org\/.*\.git": "[[OAUTH key hidden]]" # Remove any oauth keys } # Replace each pattern ...
62c55f7d0af7c458d66e426fc9366c8ec84379df
702,750
def get_techniques_of_tactic(tactic, techniques): """Given a tactic and a full list of techniques, return techniques that appear inside of tactic """ techniques_list = [] for technique in techniques: for phase in technique['kill_chain_phases']: if phase['phase_name'] == tact...
15efe8788bc4e45170f9d02c452482422ec8cf9f
702,751
import torch def make_positions(tensor, padding_idx, onnx_trace=False): """Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. """ mask = tensor.ne(padding_idx).long() return torch.cumsum(mask, dim=1) * mask + padding_idx
f59fad86a23ff76f184c0dd6a21a92722f4817f5
702,755
import typing def ark(row: typing.Mapping[str, str]) -> str: """The item ARK (Archival Resource Key) Args: row: An input CSV record. Returns: The item ARK. """ ark_prefix = "ark:/" if row["Item ARK"].startswith(ark_prefix, 0): return row["Item ARK"] return ark_pre...
ea428fcddf26a5bfdad3ec1c4906e765b72b1f47
702,758
import math def is_mc_multiplier(multiplier, modulus): """ Checks if multiplier is a MC multiplier w.r.t. modulus. :param multiplier: an integer in (0, modulus). :param modulus: a prime number. :return: True if multiplier is a MC multiplier w.r.t. modulus. """ return (modulus % multiplier)...
6d210f8de081ae0a468692b2f93e5145170917e9
702,760
def readToTuple(f_path): """Reads in a two-col file (tab-delim) and returns a list of tuples""" f = open(f_path) ls = [] for l in f: if l.startswith("#"): continue ls.append(tuple(l.strip().split("\t"))) return ls
726d1b4a4682c4e11afbf59e342340e0cf5ccc63
702,761
def increment_ctr(ctr): """ Increments one the counter. Parameters ---------- ctr : string Counter Returns ------- incremented_counter : string Incremented Counter """ ctr_inc_int = int.from_bytes(bytes.fromhex(ctr), byteorder="big") + 1 return bytes.hex(c...
0ef04e10283f02b6b7df46cf196493a3ad4a95c8
702,766
def himmelblauConstraintOne(solution): """First restriction Args: solution (Solution): Candidate solution Returns: bool: True if it meets the constraint, False otherwise """ return (26 - (solution[0] - 5) ** 2 - solution[1] ** 2) >= 0
f5878d2573559b78fee3b434d537a380abb5e2c8
702,772
def create_ip_list(addr0, n_addrs): """Creates list of IP multicast subscription addresses. Args: addr0 (str): first IP address in the list. n_addrs (int): number of consecutive IP addresses for subscription. Returns: addr_list (list): list of IP addresses for subscription. """...
e29b5c4b9f9ec0dc46916977e4a54bb77a9e74a6
702,775
from typing import OrderedDict def get_form_errors(form): """ Django form errors do not obey natural field order, this template tag returns non-field and field-specific errors :param form: the form instance """ return { 'non_field': form.non_field_errors(), 'field_specific': Or...
056597492d24dc406c9d952f5cb56c14d0a75fff
702,786
from typing import List from typing import Dict def get_vrf_group(files_list: List[str]) -> Dict[str, List[str]]: """ Group files by VRF name. """ groups = {} for filename_path in files_list: filename_path = filename_path.replace("\\", "/") # print(filename_path) if "show" i...
348f1c10f4bd054ca2f45f36b5420a971b52e4cf
702,788
def scr_total( bscr, scr_op ): """ This function simply adds the SCR_Op to the BSCR """ return bscr + scr_op
7d1711f75abae59b79cf62f6e64daeb7e4c556eb
702,789
import re import six def load_tff_dat(fname, processor=None): """Read a tff.dat or dff.dat files generated by tff command Parameters ---------- fname : file or str File, or filename processor: callable or None A final output processor, by default a tuple of tuples is returned ...
55f9ba3915c2d31cb83b8ea26de996f8f29e5e43
702,790
from typing import List def is_luhn(string: str) -> bool: """ Perform Luhn validation on input string Algorithm: * Double every other digit starting from 2nd last digit. * Subtract 9 if number is greater than 9. * Sum the numbers * >>> test_cases = [79927398710, 79927398711, 7992739871...
92253489a18efc902198d5eb3fb93a06a74a3246
702,791
import glob def patternMatch(pattern, dir='./'): """ :pattern: A file pattern to match the desired output. Input to a glob, so use traditional unix wildcarding. :dir: The directory to search. :returns: list of matching files in the target directory """ files = [] files = glob.glob(dir+pa...
d5e9b1d531cdfa3ebca3baea2b8e273621df3357
702,793
def removeBottomMargin(image, padding): """Remove the bottom margin of width = padding from an image Args: image (PIL.Image.Image): A PIL Image padding (int): The padding in pixels Returns: PIL.Image.Image: A PIL Image """ return image.crop((0, 0, image.width, image.height - padding))
69cd12d6c3ed0b857bae3f42c34e9754fa3620f3
702,794
def get_syst ( syst , *index ) : """Helper function to decode the systematic uncertainties Systematic could be - just a string - an object with index: obj [ibin] - a kind of function: func (ibin) """ if isinstance ( syst , str ) : return syst elif syst and hasattr ( syst , '...
37b2b39245587da16345752e02759d2c94c93415
702,800
def find_projects(company_name, project_list): """returns list of projects associated with company_name :param company_name: name of company to return projects for :type company_name: str :param project_list: list of projects as dictionaries :type project_list: list :return: list """ re...
e2e193aa103bec6620fb17679ff02de92c3f299e
702,803
def test_retrieve_and_encode_simple(test_client, test_collection_name): """Test retrieving documents and encoding them with vectors. """ VECTOR_LENGTH = 100 def fake_encode(x): return test_client.generate_vector(VECTOR_LENGTH) # with TempClientWithDocs(test_client, test_collection_name, 100)...
4fb6b1ea0278575ff53778dbefe8fb4f12a9abc2
702,810
def scale_from_internal(vec, scaling_factor, scaling_offset): """Scale a parameter vector from internal scale to external one. Args: vec (np.ndarray): Internal parameter vector with external scale. scaling_factor (np.ndarray or None): If None, no scaling factor is used. scaling_offset (...
c7f2471d2a7776f8756d709d0288163aab3594ae
702,816
def get_nth_combination( iterable, *, items: int, index: int, ): """ Credit to: https://docs.python.org/3/library/itertools.html#itertools-recipes Examples: >>> wallet = [1] * 5 + [5] * 2 + [10] * 5 + [20] * 3 >>> get_nth_combination(wallet, items=3, index=...
6ed186d260ca86c0f16d383576e69402d079ed9b
702,820
def capped(value, minimum=None, maximum=None, key=None, none_ok=False): """ Args: value: Value to cap minimum: If specified, value should not be lower than this minimum maximum: If specified, value should not be higher than this maximum key (str | None): Text identifying 'value' ...
663a63041699f4e4f52886adbd49423bf52c0282
702,828
def row(ctx): """Get this cell's row.""" return ctx["cell"].row
4cfc89daa3ca771359acd762d716316209ca0eb4
702,829
def above_the_line(x_array, x1, x2): """ Return states above a specified line defined by (x1, x2). We assume that a state has only two coordinates. Parameters ---------- x_array: `np.array` A 2-d matrix. Usually, an embedding for data points. x1: `np.array` A list or array ...
d20b5d462b7254a93f7896b592ae25eae26075a7
702,831
import torch def _add_embedding_layer(model_1, model_2): """ Returns an embedding layer with a weight matrix of the follwing structure: [MODEL_1 EMBEDDING MATRIX ; MODEL_2 EMBEDDING MATRIX] """ result_layer = torch.nn.Embedding( model_1.num_embeddings, model_1.embedding_dim + model...
2b4f4f3e36d56c57302cdcbf07c6cbbdb5165e11
702,833
def to_undirected(graph): """Returns an undirected view of the graph `graph`. Identical to graph.to_undirected(as_view=True) Note that graph.to_undirected defaults to `as_view=False` while this function always provides a view. """ return graph.to_undirected(as_view=True)
96ceb4e2d7dbe2a9c120b8e1ac7cad0ef2b2c6ae
702,836
from typing import MutableMapping from typing import Any def remove_keys( _dict: MutableMapping[str, Any] | None, keys: list[str] ) -> MutableMapping[str, Any]: """Remove keys from a dictionary.""" if not _dict: return {} new = dict(_dict) for key in keys: new.pop(key, None) re...
7a0ee8482eea69b0be7f7ecfd41355206adcf01c
702,841
import struct def read64(f): """Read 8 bytes from a file and return as an 64-bit unsigned int (little endian). """ return struct.unpack("<Q", f.read(8))[0]
4a055188bd9db074ca3807771d779eccb25e5484
702,843
import re def contain_static(val): """ Check if URL is a static resource file - If URL pattern ends with """ if re.match(r'^.*\.(jpg|jpeg|gif|png|css|js|ico|xml|rss|txt).*$', val, re.M|re.I): # Static file, return True return True else: # Not a static f...
9b69c0e8c69f9a97abbea82855d0c387de2a381a
702,844
def get_min(statistical_series): """ Get minimum value for each group :param statistical_series: Multiindex series :return: A series with minimum value for each group """ return statistical_series.groupby(level=0).agg('min')
c032f2f834cfe298a6c9f98c9116aaf354db0960
702,847
import unicodedata import re def unaccented_letters(s: str) -> str: """Return the letters of `s` with accents removed.""" s = unicodedata.normalize('NFKD', s) s = re.sub(r'[^\w -]', '', s) return s
e75b8929f8bd800ad4c79ae5688dea1067c351c5
702,859
import glob def get_lists_in_dir(dir_path): """ Function to obtain a list of .jpg files in a directory. Parameters: - dir_path: directory for the training images (from camera output) """ image_list = [] for filename in glob.glob(dir_path + '/*.jpg'): image_list.append(filename...
c59701c5c8327569a5efe68c2751b0568de0498e
702,872
def walk_links_for_node(node, callback, direction, obj=None): """ Walks the each link from the given node. Raising a StopIteration will terminate the traversal. :type node: treestruct.Node :type callback: (treestruct.Node, treestruct.Node, object) -> () :type direction: int :type obj: Any ...
a92cb831945a537c55ff4c014eedcb17b26ddd96
702,873
import configparser def get_config_parser(filepath): """Create parser for config file. :param filepath: Config file path :type filepath: str :return: configparser.ConfigParser instance """ config_parser = configparser.ConfigParser(interpolation=None) # use read_file() instead of read() to...
224f524c60161bc45b1324b26eeb6d4715c43054
702,874
def load_id_map(id_file): """ Load a ids file in to a barcode -> coordinate dictionary. """ id_map = {} with open(id_file, "r") as fh: for line in fh: bc, x, y = line.split("\t") id_map[bc] = (int(x), int(y)) return id_map
cd2c0635496209c3e19597fa45ae4f486779ceac
702,875