content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def masked_log_softmax(x, mask=None, dim=1): """ from https://gist.github.com/kaniblu/94f3ede72d1651b087a561cf80b306ca Performs masked softmax, as simply masking post-softmax can be inaccurate :param x: [batch_size, num_items] :param mask: [batch_size, num_items] :return: ...
a25f9bba4f09c76a661da4cc8d3cf12cc9a763db
671,714
def post_config_apache_felix_jetty_based_http_service(org_apache_felix_https_nio=None, org_apache_felix_https_nio_type_hint=None, org_apache_felix_https_keystore=None, org_apache_felix_https_keystore_type_hint=None, org_apache_felix_https_keystore_password=None, org_apache_felix_https_keystore_password_type_hint=None, ...
e2d45c0f065869bef0e3992d990f6e968ac7ffe6
671,715
def accuracy(labels, predictions): """ Returns the percentage of correct predictions in the set (labels, predictions). """ acc = 0 for label, pred in zip(labels, predictions): if label == pred: acc += 1 return acc / labels.shape[0]
b4f9f1c7273d8dc6894452fe6328e23f8df76b51
671,716
def left_pad_with_zeros(text: str, zeros_count: int) -> str: """ Pads a string with zeros from the left """ return (zeros_count * "0") + text
c85601e3221050afb07b524f1824f9d5753c53e8
671,717
def get_bg_styles(forecast_times): """ Функция получения кортежа с перечнем названий классов css для задания стилей ячеек таблиц Прогноза погоды в зависимости от времени дня (datetime) прогноза. Значения кортежа - два вида класса w_day и w_night для отображения "дневных" и "ночных" ячеек соответсвен...
d8a9343066a9beea1e710967137212dc07d4b8f9
671,718
def _generate_line(club, name_column_width): """ Generates a single line of output. :param Organization club: object holding information about club :param int name_column_width: width of name column :return: nicely formatted line of output :rtype: str """ name_column = str(club.name) + ":"...
a62417b4dcd339cc824a6c3a8a4f79dd19abb4c8
671,719
def __metro(soup): """ Gets the most read news from the Metropoles DF page :param soup: the BeautifulSoup object :return: a list with the most read news from the Metropoles DF Page """ news = [] container = soup.select('.m-title') for item in container: a = item.a title...
987514c2d82f568090f6edfda9538b12c98a50cb
671,720
def get_base_image(version_map, version): """Selects the appropriate base image from the version map. This function takes into account the .NET Core versioning story to determine the appropriate base image for the given version. It will select from within the same major version and only if the mino...
3641f3f6f1b86aab920f3a4ef7d292e219de94aa
671,721
import os import sys import platform def check_openmp(): """Do we compile with OpenMP? Store the result in WITH_OPENMP environment variable :return: True if available and not disabled. """ if "WITH_OPENMP" in os.environ: return os.environ["WITH_OPENMP"] == "False" elif "--no-openmp"...
0ecc1c6758d3f192d23c34f9883d00b870075bed
671,722
def _parse_date_string(dateString): """ Given a string containing a date, returns a tuple defining a date of the form (year, month, day, hour, minute, second) appropriate for constructing a datetime or timedelta """ # change underscores to spaces so both can be supported dateString = da...
5fa1fb0a1fa7d77624d6a86f2d6d911bd6662542
671,723
def count_scores(scores): """ 分段计数 :param scores: scores列表 :return: 分段计数结果列表 """ nums = [0]*10 for s in scores: c=int(s.score // 10) nums[c]+=1 return nums
de23f452fe51be6dc41aed4ff28dc92020d38de1
671,725
def distance(sim_hash, another, f): """ 计算两个simHash的距离 :param sim_hash: simHash值 :param another: 另一个simHash的值 :param f: simHash的bit位数 :return: 海明距离 """ x = (sim_hash ^ another) & ((1 << f) - 1) value = 0 while x: value += 1 x &= x - 1 return value
ca2f63891374ac7d19053747b3a1dec3091fe877
671,726
import copy def extend_object_field(base_obj, client_obj, field_name): """ :param base_obj: an object which has a property `field_name` that is a list :param client_obj: an object which has a property `field_name` that is a list. A copy of this object is returned with `field_name` modified :pa...
72cd1a7cb842f8536b1af809804950f8ffa9eb3a
671,727
def delete_article(db, articleid): """ Delete article """ delete = "delete from articles where id=?" return db.execute(delete, (articleid))
61d60c50d60495ad080891d68afe41f826f5e233
671,728
import os def standTextOut_Return(string): """ Will return the finished string so you can output it the way you want. """ width = os.get_terminal_size().columns result = "-" * width result = (result + "\n" + string.center(width)) result = (result + "\n" + ("-" * width)) return result
c15ae6ff9a38e3508abd6c0081109872088c7d0a
671,729
def is_linux(repository_ctx): """Returns true if the host operating system is linux.""" os_name = repository_ctx.os.name.lower() return os_name.find("linux") != -1
0a5aa6bce37e745402366c268a065c6a291f9636
671,730
from typing import Dict import collections def get_text_sections(paper_json, text_key) -> Dict: """ :param paper_json: The json :param text_key: the text_key - "body_text" or "abstract" :return: a dict with the sections """ body_dict = collections.defaultdict(list) for rec in paper_json[te...
f9689437db21a612a7f1912e21dd223d5f645832
671,731
def build_doi_url(doi): """ """ doi_url = 'https://doi.org/' doi_url = doi_url + str(doi) return(doi_url)
f5a52892d4f1bfc8eca9839165da56693bdddcb7
671,732
def json_serial(obj): """Serialize json. Args: obj (Any): A python object. Example: json.dumps(data, default=json_serial) """ if isinstance(obj, set): return list(obj) raise TypeError
23007faa4fa0085fec365ae85d21f9b049a42040
671,733
import math def get_auto_embedding_dim(num_classes): """ Calculate the dim of embedding vector according to number of classes in the category emb_dim = [6 * (num_classes)^(1/4)] ref: Ruoxi Wang, Bin Fu, Gang Fu, and Mingliang Wang. 2017. Deep & Cross Network for Ad Click Predictions. In Proceedings o...
9c91c8bf2d775d029349849c7efa56ba51714448
671,734
import argparse def get_parser(): """Set up and return argument parser.""" parser = argparse.ArgumentParser('dataset to datastore converters') parser.add_argument("in_fn", type=str, help="Input DataSet or DataStore") parser.add_argument("out_fn", type=str, help="Output DataSet or DataStore") retur...
9e9ccca417eed4461898091430479ec91e210245
671,735
import math def interpolate2dPoints( interpolation, x, x1, y1, x2, y2 ) : """This function interpolates y at x where x1 <= x <= x2 using interpolation.""" y = y1 if( y1 != y2 ) : if( x1 == x2 ) : # A why to handle a step function. y...
c4457d0d5baa65cb013bbbfa4879806a1d9d5945
671,736
def convert_retention_to_seconds(desired_retention, retention_unit): """Convert desired retention to seconds. :param desired_retention: The desired retention for snapshot schedule :param retention_unit: The retention unit for snapshot schedule :return: The integer value in seconds ...
40a6284faf85d005b96ae5aa55429259eafc6324
671,737
import importlib def _create_task( descriptor ): """ Creates a task object from a descriptor. @param descriptor Task descriptor @return Task instance """ # import the task module by name module = importlib.import_module( descriptor[ 'name' ].lower() ) # get the referenc...
c3230a79e694800841df8849ca044edc1441acdb
671,739
def _check_svg(data): """This simply checks the existence of the opening and ending SVG tags""" if b'<svg' in data and b'/svg>' in data: return 'image/svg+xml'
0bfb2dc57cc846108f8aef5a7531544fe1481688
671,740
from typing import List def _split(a: List[bytes], n: int) -> List[List[bytes]]: """ Splits a list into a list of n sub-lists. Assumes that len(a) % n == 0 :param a: the list to split :param n: number of parts to split the list into :return: a list containing the parts of the source list """ ...
922eebb3af3f578a7f5f957679519e2f138fb8be
671,741
import os def foo_updated_release(foo_release): """Return a package with updated single version.""" binpath = os.path.join('releases', 'foo-1.0', 'bin') with open(os.path.join(binpath, 'foo-1.0'), 'w'): pass return 'foo'
7f4dc450c6efcab8d26dce1ba6f708a9eaaef658
671,742
def is_equal_to_as_set(l1, l2): """ return true if two lists contain the same content :param l1: first list :param l2: second list :return: whether lists match """ # Note specifically that set(l1) == set(l2) does not work as expected. return len(set(l1).symmetric_difference(set(l2))) == 0
6e6e39de2c175610eb556b7b2fc586343f0bea76
671,743
def omega_to_w(omega, p, t): """ Convert pressure vertical velocity to geometric vertical velocity. Arguments: omega -- vertical velocity in pressure coordinates, in [Pa/s] p -- pressure in [Pa] t -- temperature in [K] All inputs can be scalars or NumPy arrays. Returns the vertical ve...
76166a6b6d1845cc2988fa2f8a2047aa01d14b9b
671,744
def possible_mine_limits(tallies): """return the total minimum and maximum possible # of mines across all tallied fronts returns (min, max)""" return (sum(f(tally) for tally in tallies) for f in (lambda tally: tally.min_mines(), lambda tally: tally.max_mines()))
40c87233c36e4dca9604ffc76fa667579ecce106
671,745
def AdjustPositiveRanks(positive_ranks, junk_ranks): """Adjusts positive ranks based on junk ranks. Args: positive_ranks: Sorted 1D NumPy integer array. junk_ranks: Sorted 1D NumPy integer array. Returns: adjusted_positive_ranks: Sorted 1D NumPy array. """ if not junk_ranks.size: return posi...
7e5b4ba0edefa266926905a62ec4f74f49a103c6
671,746
def line_goes_through_border(pos1, pos2, dest1, dest2, border, lower, upper): """ Test if the line from (pos1, pos2) to (dest1, dest2) goes through the border between lower and upper. """ try: m = (border - pos1) / (dest1 - pos1) except ZeroDivisionError: return False wall_closer...
aca4dae17f0e33dd3d643798cd289b598e8152be
671,747
def build_path(node): """ Builds a path going backward from a node Args: node: node to start from Returns: path from root to ``node`` """ path = [] while node.parent is not None: path.append(node.state) node = node.parent return tuple(reversed(path))
412810adeb21b58d2af88f4b700ee8c0cb11d899
671,748
def constant(wait_time): """ Returns a function that just returns the number specified by the wait_time argument Example:: class MyUser(User): wait_time = constant(3) """ return lambda instance: wait_time
cfd77e79770f79837bb5d2b05233b7581b825e5f
671,749
import torch def cudaw(obj, use_cuda=True): """Call .cuda on the object if cuda.is_available. by @jayanthkoushik. """ if torch.cuda.is_available() and use_cuda: obj = obj.cuda() return obj
9b758fb09f8c09a81a6b5001bb27ba5bf264a0b7
671,750
def api_handler(*, name=None): """ Decorator for API handlers with method names not matching their command names. :param name: Command name for the function :return: Wrapper function to set the name """ def predicate(func): func.__api_name__ = name if name else func.__name__...
5b33422ef82583606d3000940495c7beb91b92c6
671,751
def expand(buf): """ Returns a new bytearray containing the contents of buf expanded with space for parity bit on each byte. The parity bit is not set and is always zero. :param bytes buf: 168-bit key :rtype: bytearray """ out = bytearray(24) out[0] = buf[0] & 0xFE out[1] = (buf[0] ...
0923fa172c790824c3b9826fc74687f1c35f4b6c
671,752
import subprocess import sys def exec_isolated(code): """Compile and run code in seperate process. A mistake in the compiler will cause a segfault most of the time. Running it in a seperate process will prevent it from terminating this test program. """ s = subprocess with s.Popen(sys.execut...
9405b7eeefdb4f1edc6edf15c72d8e5a6e17783e
671,753
import numpy def are_collinear_and_consistent_direction(points): """ Examine two conditions: 1) All the points are on the same line (collinear), and 2) The vector from the first point to each point points at the same direction :returns: True if points satisfy two conditions described above ""...
8461ca67f0cd2b7554151981e08e3fd4c437205b
671,754
from os.path import getsize def getsize(filename): """The length of a file in bytes or 0 if te file does not exists""" try: return getsize(filename) except OSError: return 0
e355eda88ad144dd9cb5674be7a950ffad287071
671,755
import os def get_path() -> str: """Get the path to the templates directory.""" return os.path.dirname(os.path.abspath(__file__))
326f5c00fa32f9f082c3db94639601a36a109f5e
671,756
import pickle def load_sneden(whichdata): """ Loading the r-process isotopes from Sneden et al. 2008 (pickled in SMHR) """ assert whichdata in ['rproc','sproc','sneden'], whichdata _datadir = "/Users/alexji/smhr/smh/data/isotopes" datamap = {'rproc':'sneden08_rproc_isotopes.pkl', 'sproc...
24131465a9cee01bfb8385a5de31e524a0df0c47
671,757
def fetchUserPubKeys(conn): """ Returns array containing (discord_id, stellar_public_key) tuples """ c = conn.cursor() c.execute("SELECT user_id, stellar_account FROM users") return c.fetchall()
6411f14712643e38846600e8aa1de09a211f88f3
671,758
import sys def parsestar_old(starfile): """ This is a quite inefficient way of parsing a star file but does the job. The assumption below is that the star file has version headers that look like "# version xxxxx". This function gets the star file information from getparticles() and the result is pas...
2a76386911dba03474a95c494058f787ab6e2db7
671,759
def plot_shape(ax, xaxis, yaxis, zaxis, plot_3d, data, linewidth): """Plot shape and return line. Args: ax (matplotlib.axes.Axes): axis xaxis (int): indicate which data to plot on the x-axis (0 for x, 1 for y, 2 for z) yaxis (int): indicate which data to plot on the y-axis (0 for x, 1 f...
11a782d8035d7d0d931c94a189c9c261d33f8c3e
671,760
def _quote(expr: str) -> str: """Quote a string, if not already quoted.""" if expr.startswith("'") and expr.endswith("'"): return expr return f"'{expr}'"
345871b1e64dde937088da3aadb636e4fd54c2c1
671,761
def is_not_none(sample): """ Returns True if sample is not None and constituents are not none. """ if sample is None: return False if isinstance(sample, (list, tuple)): if any(s is None for s in sample): return False if isinstance(sample, dict): if any(s is ...
92a662f98021b0b50efb98565e43bce7f50e0775
671,762
def decodeString(s): """ :type s: str :rtype: str """ # Given an encoded string, return its decoded string. # The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. ...
7c2f430fdd0ca54abf95b38c13b4101d0f705db4
671,763
import sys def _allow_reckless_class_cheks(): """Allow instnance and class checks for special stdlib modules. The abc and functools modules indiscriminately call isinstance() and issubclass() on the whole MRO of a user class, which may contain protocols. """ try: return sys._getframe(3).f...
c1c6b29a246a58882543e3d8decd205e9926f2fb
671,764
def user_can_comment(user): """check if user has permission to comment :user: user to be check :returns: boolean """ return user.is_authenticated and user.has_perm('restaurants.can_comment')
a2a682092441a99b5763040bfa5bf0b9563651c5
671,765
import random def icecreamParlor3(m, arr): """ Uses randomness to find the 2 indeces This won't work on competitive programming submissions that test with large inputs. It's not optimal, but works on small inputs. """ N = len(arr) while True: first_one = random.randrange(N) ...
71e93aabb29ad417fc209a1f67f7911eff1b464c
671,766
def getEnrichementFractionFromDelta(desired_delta, reference_ratio = 0.011115): """ Calculates the enrichment fraction given a desired delta value using a reference ratio. """ ratio = (desired_delta / 1000. + 1) * reference_ratio fraction = ratio / (1 + ratio) return fraction
2bab2a5a532d7f4110e9eb88fbceffd2797074da
671,767
def typeddict(expected_k, expected_v): """Return a dictionary that enforces a key/value type signature. >>> tdict = typeddict(int, str) >>> mydict = tdict() >>> mydict[3] = 'three' But this fails: >>> mydict['3'] = 'three' """ class TypedDict(dict): def __setitem__(self, k, v)...
49360b914627aa26b5044f92a9a7fe2afd9aca01
671,768
def find_header_row(sheet, header_start): """ Finds the header row number in a sheet of an XLRD Workbook. :param sheet: Input sheet :param header_start: Header pattern (a substring of the first header) :return: Row number for the header row """ row_number = 0 for row in sheet.get_rows()...
5e8ab021884037dc87b8bc3d10f96da76a4e9c4f
671,769
from pathlib import Path from typing import Optional from typing import Dict import json def find_maybe_info_json(absolute_directory_path: Path) -> Optional[Dict]: """ Recursively search parent folders to find the closest info.json file. """ possible_info_json_path = absolute_directory_path.joinpath(...
3f738651d63bee17a76e4de7424893066f080d45
671,770
def pad(plaintext: bytearray, block_size=16): """PKCS#7 Padding""" num_pad = block_size - (len(plaintext) % block_size) return plaintext + bytearray([num_pad for x in range(num_pad)])
a522da6faa8898dc07da777bbe3656d6166133a3
671,771
import hmac import hashlib def sign(key, msg): """Make sha256 signature""" return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
e675801328df0ca9eb56cb9428896248112f730f
671,773
def get_dir(xy): """ |NW|N |NE| +--+--+--+ |W |C |E | +--+--+--+ |SW|S |SE| """ if xy == (0, 0): return "NW" elif xy == (0, 1): return "N" elif xy == (0, 2): return "NE" elif xy == (1, 0): return "W" elif xy == (1, 1): return "C" ...
4274dd1a381e0a790a47ed87586f6941ac6551ca
671,774
def lwrap(l, w=None): """docstring for lwrap""" result = [] o = w or '"' for elem in l: result.append(o + elem + o) return result
ec3d02000092b2c516b950f65fdda4136e1d3c98
671,776
def countChoices(matrix, i, j): """Gives the possible Numbers at a position on a sudoku grid. """ canPick = [True for _ in range(10)] # canPick[0] = False for k in range(9): canPick[matrix[i][k]] = False for k in range(9): canPick[matrix[k][j]] = False r = i//3 c = j//3 ...
081bd82119624933b562683126767df1d4fcbb08
671,777
def format_qnode(qnode: str) -> str: """Formats a qnode with the required prefix. "wd:" is prepended for qnodes and "wdt:" is prepended for pnodes. Args: qnode: Unformatted qnode. Returns: Formatted qnode. """ return f"wd:{qnode}" if qnode.startswith("Q") else f"wdt:{qnode}"
67a21c7c57d1c9bc657e336607f1b623d2203af3
671,778
def get_table_8(): """表 8 断熱性能の区分݆における日射取得性能の区分݇の暖房期の日射取得係数mu_H_j_k及び冷房期の日射取得係数mu_C_j_k Args: Returns: list: 表 8 断熱性能の区分݆における日射取得性能の区分݇の暖房期の日射取得係数mu_H_j_k及び冷房期の日射取得係数mu_C_j_k """ table_8 = [ (0.029, 0.027, 0.044, 0.048, 0.062, 0.061, 0.129, 0), (0.021, 0.022, 0.036, 0.039, 0...
270e56839d13e20b6aa8b56e1a201d23e703a5df
671,780
def address(corporation): """Get billing address of Apple subsidiary with given handle""" if corporation == 'AU': return """Apple Pty Limited Level 3 20 Martin Place Sydney South 2000 Australia""" elif corporation == 'CA': return """Apple Canada Inc. 120 Bremner Boulevard, Suite 1600 Toronto...
14975bf859e9daefc7fdc1997a58008ff07f738d
671,781
def get_note_freq(note: int) -> float: """Return the frequency of a note value in Hz (C2=0).""" return 440 * 2 ** ((note - 33) / 12)
d4b03d5b474d9d7f79dcb3cf374148d4a1ccbf18
671,782
import torch def step_dD(x): """Another example function defined on interval `[0, 1]`, discontinuous Parameters ---------- x : torch.Tensor coordinates for evaluation Returns ------- torch.Tensor function evaluations """ result = 1.0 for x_i in x: resu...
c9be4e58b14b2c368aa57b575de886b68201c358
671,784
def indexed(targets, tagset_size, start_id): """将targets中的数转化为在[T*T]大小序列中的索引,T是标注的种类""" batch_size, max_len = targets.size() for col in range(max_len-1, 0, -1): targets[:, col] += (targets[:, col-1] * tagset_size) targets[:, 0] += (start_id * tagset_size) return targets
1f6efdd88636c552c6c3e7ad9239c5b44eeb0a7e
671,785
def _tryConvertToInt(s): """ Try convert value from `s` to int. Returns: int(s): If the value was successfully converted, or `s` when conversion failed. """ try: return int(s) except ValueError: return s
016acfdf8b9f3ea5d65285bac3ce561940894f91
671,787
def process_single_text(raw_text, max_seq_length, encoder, BOS_token, EOS_token, PAD_token): """Processes a single piece of text. Performs BPE encoding, converting to indexes, truncation, and padding, etc. """ # BPE tokens = encoder.encode(raw_text) # Truncate max_le...
e311da299ebf947354ac1d5e2ac9ee383076357f
671,788
import torch def pad(input, bos_idx, eos_idx, padding_idx=0): """pad <START> and <EOS> input (LongTensor) of size batch_size, n_rounds, max_length """ # (1) 3D -> 2D tensor batch_size, n_rounds, length = input.size() input_2d = input.view(-1, length) real_lens = input_2d.ne(padding_idx).su...
b6fe6367f38ade6b1a02f1cea64bda6a0897d5eb
671,789
import re def parse_show_spanning_tree(raw_result): """ Parse the 'show spanning-tree' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show spanning-tree \ command in a dictionary of the form: :: { ...
804e50a5cbc35d9db93b3d769921925b55ee360c
671,790
import six import os def filesize(f): """Return the size of f in bytes""" if isinstance(f, six.string_types): return os.path.getsize(f) else: # For file-like object now_pos = f.tell() f.seek(0, 2) size = f.tell() f.seek(now_pos) return size
4dfe81ab86b337ef25ad47ba15f075a416f0c2e3
671,791
def make_backoffs(training, tagger_classes, backoff=None): """ Function for training and make chains of backoff tagger """ # Make a tagger using the previous one as a backoff for cls in tagger_classes: backoff = cls(training, backoff=backoff) return backoff
f46047bcab98ddb74e739d943d35935ae9d9369b
671,792
def propfind_mock(url, request): """Simulate a PROPFIND request.""" content = b""" <d:multistatus xmlns:d="DAV:" xmlns:cs="http://calendarserver.org/ns/"> <d:response> <d:href>/radicale/user@test.com/contacts/</d:href> <d:propstat> <d:prop> <d:sync-token>http://mo...
e7c73f5566274414e63d7b7dc58e761647c80ab3
671,793
def is_float(val): """Boolean function to say if this value is not a float.""" try: float(val) return True except ValueError: return False
a26257032e8e73b33147d261c5a4f95cf3a417f5
671,794
def problem_04_palindrome_product(digits): """ Problem 4: Determines the largest palindrome product of two numbers with set number of digits. Args: digits (int): The number of digits in the factors. """ result = 0 max_factor = int(1 * 10 ** digits) - 1 first_range = range(max_factor, 0,...
85a3a771c04fd41f57ea0ff19bb97e9d0106d88c
671,795
import json def publication_data(): """Load publication data file.""" with open('data/publications.json') as pubs: pubs = json.load(pubs) return pubs
6b6fa83bee574caa804237cdebcb2ed1188331cf
671,798
import requests def _check_for_gps_position_stream(glider_url,glider_stream,glider_method): """ Used to check if a desired stream is available. """ url = glider_url+"/metadata" req_gps_info_list = requests.get(url) metadata = req_gps_info_list.json() time_list = metadata['times'] param_lis...
01c06524dab7b98b07d4fa4e921f5478051f30cf
671,799
def make_rand_vector(dims, random_state): """ Generate a random unit vector. This works by first generating a vector each of whose elements is a random Gaussian and then normalizing the resulting vector. """ vec = random_state.normal(0, 1, dims) mag = sum(vec ** 2) ** .5 return vec / ma...
55228763c7457fecaf261b7af974f8187d249ccc
671,800
def _ExpandTabs(text, column, tabsize, mark_tabs=False): """Expand tab characters in a string into spaces. Args: text: a string containing tab characters. column: the initial column for the first character in text tabsize: tab stops occur at columns that are multiples of tabsize mark_tabs: if true,...
f921e362dfda42117ac925a836cca778ca9aeb87
671,801
from typing import Union from typing import Callable from typing import List from typing import Any import sys def _get_entrypoint_name( entrypoint: Union[Callable, str, None], args: List[Any] ) -> str: """Retrive entrypoint name with the rule: 1. If entrypoint is a function, use ``entrypont.__qualname__`...
e6651721fab58276bdc921fd1bf7844c00f8c0d7
671,803
def get_simulation_ids(metadata_df, rbymu, l): """ Handy function to use the metadata df (loaded by reading metadata csv) to filter desired sim ids """ return metadata_df[(metadata_df['rbymu']==rbymu) & (metadata_df['lambda']==l)]['sim_id']
6efc637d0db629b4168f76dc620834e3e14b6ed6
671,804
def find_in_dict(obj, key): """ Recursively find an entry in a dictionary Parameters ---------- obj : dict The dictionary to search key : str The key to find in the dictionary Returns ------- item : obj The value from the dictionary """ if key...
408a972b02780f19f9b01f35922c231032d798ee
671,805
def padding_rfam_genome_id_with_zeros(number): """ Adds a prefix of zeros to the number provided to generate a new Rfam genome id number: A number to add zeros to return: A 9 character long string of a number with a prefix of zeros """ zero_vector = "000000000" text_num = str(num...
7dc2322cd914868de39849c39d704568f8342264
671,806
def verify_dlg_sdk_proj_env_directory(path): """ Drive letter is not allowed to be project environment. Script checks in parent of 'path': a drive letter like C: doesn't have a parent. """ if(path.find(":\\")+2 >= len(path)): # If no more characters after drive letter (f.e. "C:\\"). return False else: return ...
a03d518124d874b6421ccc652da283302208a207
671,807
import logging def is_log_level_info(logger): """Return True if and only if log level is at least INFO. .. versionadded:: (cfdm) 1.8.9.0 .. seealso:: `log_level` :Parameters: logger: `logging.Logger` The logger in use. :Returns: `bool` Whether or not th...
b028a3a94fb23ead493590015abe8b98c24ffecd
671,808
def tagsDict_toLineProtocolString(pTagsDict:dict): """Converts a tags dictionnary to a valid LineProtocol string.""" retval = '' for lTagName in pTagsDict: lTagValue = pTagsDict[lTagName] # See https://docs.influxdata.com/influxdb/v1.7/write_protocols/line_protocol_tutorial/#special-characters if type(lTagV...
e2ab2972e62b9baede20977730ab250b279ddfb5
671,809
def clean_refvar(refvar: str) -> str: """Cleans refvar string of characters that cause issues for filenames. Args: refvar: A string representing a refvar. Returns: A cleaned string. """ refvar = refvar.replace(" ", "_") refvar = refvar.replace("/", "_") return refvar
b7f47f42f3db8b8af2cc7d08e68dc6f6b5a285e7
671,810
import os def get_list_of_metadata_csvs(metadata_dir): """ return all filepaths for files in the given directory that end with .csv """ fpaths = [] for fname in os.listdir(metadata_dir): if fname.endswith('.csv'): fpath = os.path.join(metadata_dir, fname) fpaths.ap...
1f7c2bda806cd6e656aa64ee84fb23090e83ee03
671,811
def load_hex_file(file_name): """ Loads a "HEX" file generated using the command: 'objcopy -O verilog firmware.elf firmware.hex' """ print("Loading 'HEX' from: " + file_name) # Load and parse HEX data sections = {} section = 0 # If no '@' is specified the code will end up at addr. ...
492b3d9c502233d558fe0c6244600249cf9eff56
671,812
def build_fmt_str_from_enum(enums): """Build formatted string from enum list. Parameters ---------- enums: array_like Array of enums. Returns ------- str Return the formatted string. """ formatted = "[" for e in enums: formatted += "'" + e.value.lower()...
1bbf09b811dcdd8f9cb19323bab6a62cf59a2e14
671,814
from numpy.random import uniform from numpy import insert from numpy import array from itertools import combinations from numpy import linalg def particle_positions( particle_number=2, first_particle_range=0.5, other_particle_range=1, particle_distance=50, ): """Generates multiple particle x- ...
b5b149658e15be4675bfd8bb18bf4cac256cb50b
671,815
import base64 def decode(x): """ Convenience function to decode Sponsor ID. """ return base64.urlsafe_b64decode(str(x)+'='*(-len(x)%4))
dc210a49797de230c4afc29fecdb6de717262d24
671,816
import os def commonprefix(args, sep="\\"): """ Return the common prefix string for a list of file paths. Typically used to remove that prefix to shorten the filename for display, i.e. to provide relative file paths. """ return os.path.commonprefix(args).rpartition(sep)[0]
46ee5c3b228437b82698ca0663e5252a889af85f
671,817
import os def num_restarts(): """ Number of times the current job was restarted. Determined by the environment variable ``ADAPTDL_NUM_RESTARTS``, or 0 if unset. This value is mainly informational, and is automatically set in AdaptDL-scheduled clusters. Returns: int: number of restarts...
f478708e50251a2ce0a883e116b7cb706300ca63
671,818
import os def read_files(directory, recursive): """Read all files in a directory.""" # (filename, data) entries = [] # Get absolute path, just in case working directory changes. directory = os.path.abspath(directory) # Recursively read all files. if recursive: for root, _, files ...
6ba20a9334035f9a59c2c89a9e49741110b3a5df
671,819
def make_markdown_links(config): """Make Markdown links table from configuration.""" if not config.links_data: return "" return "\n\n" + "\n".join( f"[{ln['key']}]: {ln['url']}" for ln in config.links_data )
7d0dba32b78ac234a16b5c2151625d13647eb0c9
671,820
def split_list(alist, wanted_parts=1): """Split a list to the given number of parts.""" length = len(alist) # alist[a:b:step] is used to get only a subsection of the list 'alist'. # alist[a:b] is the same as [a:b:1]. # '//' is an integer division. # Without 'from __future__ import division' '/' ...
dcb1ebc57f4291a81ae6af114fc262bc15a748cd
671,821
import re def sorted_alphanum(file_list): """sort the file list by arrange the numbers in filenames in increasing order :param file_list: a file list :return: sorted file list """ if len(file_list) <= 1: return file_list convert = lambda text: int(text) if text.isdigit() else text ...
6e0e98e3d22db2db4cc979d9230184033f8d6c94
671,822
def fix_morphemes(morphemes): """Remove all sequences of question marks in morpheme_break and morpheme_gloss values. These cause Internal Server Errors in the OLD. """ while '??' in morphemes: morphemes = morphemes.replace('??', '?-?') return morphemes
3b96468a03aa16feabb032fac16316bc55c87837
671,824
import os import yaml def load_list_of_plans_and_devices(path_to_file=None): """ Load the lists of allowed plans and devices from YAML file. Returns empty lists if `path_to_file` is None or "". Parameters ---------- path_to_file: str on None Full path to .yaml file that contains the l...
afe76d4ee13dbdb9adb06dee51e1de3c1e822f63
671,825