content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_structure_index(structure_pattern,stream_index): """ Translates the stream index into a sequence of structure indices identifying an item in a hierarchy whose structure is specified by the provided structure pattern. >>> get_structure_index('...',1) [1] >>> get_structure_index('.[.].',1) ...
8f1def101aa2ec63d1ea69382db9641bf0f51380
678
def errorcode_from_error(e): """ Get the error code from a particular error/exception caused by PostgreSQL. """ return e.orig.pgcode
981b447d540e949834c10f4a05fb21769091b104
679
def get_avg_sentiment(sentiment): """ Compiles and returnes the average sentiment of all titles and bodies of our query """ average = {} for coin in sentiment: # sum up all compound readings from each title & body associated with the # coin we detected in keywords averag...
6a79c3d4f28e18a33290ea86a912389a5b48b0f3
681
import os def does_file_exist(path): """ Checks if the given file is in the local filesystem. Args: path: A str, the path to the file. Returns: True on success, False otherwise. """ return os.path.isfile(path)
38768ca739cf8a6f482bfb5d35cef397c70227c1
682
def listDatasets(objects = dir()): """ Utility function to identify currently loaded datasets. Function should be called with default parameters, ie as 'listDatasets()' """ datasetlist = [] for item in objects: try: if eval(item + '.' + 'has_key("DATA")') == True: ...
061d7c9287c6166b3e7d55449be49db30400ce56
683
import sys def get_argument(index, default=''): """ 取得 shell 參數, 或使用預設值 """ if len(sys.argv) <= index: return default return sys.argv[index]
c2c8d78b608745428a1d6b4d97b5081e1f0961e7
685
import re def clean_filename(string: str) -> str: """ 清理文件名中的非法字符,防止保存到文件系统时出错 :param string: :return: """ string = string.replace(':', '_').replace('/', '_').replace('\x00', '_') string = re.sub('[\n\\\*><?\"|\t]', '', string) return string.strip()
805023382e30c0d0113715cdf6c7bcbc8b383066
686
import os import importlib def build_model(master_config): """ Imports the proper model class and builds model """ available_models = os.listdir("lib/classes/model_classes") available_models = [i.replace(".py", "") for i in available_models] model_type = master_config.Core_Config.Model_Config....
3089df4094e211a0e5a7fe521bc08b2ca5ff23b0
687
def get_digits_from_right_to_left(number): """Return digits of an integer excluding the sign.""" number = abs(number) if number < 10: return (number, ) lst = list() while number: number, digit = divmod(number, 10) lst.insert(0, digit) return tuple(lst)
6b5626ad42313534d207c75d2713d0c9dc97507c
688
def rx_weight_fn(edge): """A function for returning the weight from the common vertex.""" return float(edge["weight"])
4c405ffeae306a3920a6e624c748fb00cc1ee8ac
689
def image_inputs(images_and_videos, data_dir, text_tmp_images): """Generates a list of input arguments for ffmpeg with the given images.""" include_cmd = [] # adds images as video starting on overlay time and finishing on overlay end img_formats = ['gif', 'jpg', 'jpeg', 'png'] for ovl in images_and_videos: ...
b210687d00edc802cbf362e4394b61e0c0989095
690
def f_not_null(seq): """过滤非空值""" seq = filter(lambda x: x not in (None, '', {}, [], ()), seq) return seq
a88eab0a03ef5c1db3ceb4445bb0d84a54157875
691
def calc_disordered_regions(limits, seq): """ Returns the sequence of disordered regions given a string of starts and ends of the regions and the sequence. Example ------- limits = 1_5;8_10 seq = AHSEDQNAAANTH... This will return `AHSED_AAA` """ seq = seq.replace(' ', '...
2c9a487a776a742470deb98e6f471b04b23a0ff7
692
from math import exp, pi, sqrt def bryc(K): """ 基于2002年Bryc提出的一致逼近函数近似累积正态分布函数 绝对误差小于1.9e-5 :param X: 负无穷到正无穷取值 :return: 累积正态分布积分值的近似 """ X = abs(K) cnd = 1.-(X*X + 5.575192*X + 12.77436324) * exp(-X*X/2.)/(sqrt(2.*pi)*pow(X, 3) + 14.38718147*pow(X, 2) + 31.53531977*X + 2*12.77436324) ...
e2feb6fa7f806294cef60bb5afdc4e70c95447f8
693
def _row_or_col_is_header(s_count, v_count): """ Utility function for subdivide Heuristic for whether a row/col is a header or not. """ if s_count == 1 and v_count == 1: return False else: return (s_count + 1) / (v_count + s_count + 1) >= 2. / 3.
525b235fe7027524658f75426b6dbc9c8e334232
695
def handle_storage_class(vol): """ vol: dict (send from the frontend) If the fronend sent the special values `{none}` or `{empty}` then the backend will need to set the corresponding storage_class value that the python client expects. """ if "class" not in vol: return None if vo...
a2747b717c6b83bb1128f1d5e9d7696dd8deda19
697
def dummy_sgs(dummies, sym, n): """ Return the strong generators for dummy indices Parameters ========== dummies : list of dummy indices `dummies[2k], dummies[2k+1]` are paired indices sym : symmetry under interchange of contracted dummies:: * None no symmetry * 0 ...
774203b62a0335f9bea176a1228673b2466324e3
699
def get_uniform_comparator(comparator): """ convert comparator alias to uniform name """ if comparator in ["eq", "equals", "==", "is"]: return "equals" elif comparator in ["lt", "less_than"]: return "less_than" elif comparator in ["le", "less_than_or_equals"]: return "less_th...
20c24ba35dea92d916d9dd1006d110db277e0816
700
def inorder_traversal(root): """Function to traverse a binary tree inorder Args: root (Node): The root of a binary tree Returns: (list): List containing all the values of the tree from an inorder search """ res = [] if root: res = inorder_traversal(root.left) re...
f6d5141cbe9f39da609bd515133b367975e56688
701
def make_count(bits, default_count=50): """ Return items count from URL bits if last bit is positive integer. >>> make_count(['Emacs']) 50 >>> make_count(['20']) 20 >>> make_count(['бред', '15']) 15 """ count = default_count if len(bits) > 0: last_bit = bits[len(...
8e7dc356ba7c0787b4b44ee8bba17568e27d1619
703
import re def normalize_number(value: str, number_format: str) -> str: """ Transform a string that essentially represents a number to the corresponding number with the given number format. Return a string that includes the transformed number. If the given number format does not match any supported one, r...
c22bff28fc6ef6f424d0e9b8b0358b327cd153c5
704
import os def is_regular_file(path): """Check whether 'path' is a regular file, especially not a symlink.""" return os.path.isfile(path) and not os.path.islink(path)
28ad19350d1a11b62e858aa8408cb29dc4d4c126
706
def LinkConfig(reset=0, loopback=0, scrambling=1): """Link Configuration of TS1/TS2 Ordered Sets.""" value = ( reset << 0) value |= ( loopback << 2) value |= ((not scrambling) << 3) return value
901fe6df8bbe8dfa65cd516ac14692594608edfb
708
def x_for_half_max_y(xs, ys): """Return the x value for which the corresponding y value is half of the maximum y value. If there is no exact corresponding x value, one is calculated by linear interpolation from the two surrounding values. :param xs: x values :param ys: y values corresponding to...
b18525664c98dc05d72a29f2904a13372f5696eb
709
import numpy as np def _from_Gryzinski(DATA): """ This function computes the cross section and energy values from the files that store information following the Gryzinski Model """ a_0 = DATA['a_0']['VALUES'] epsilon_i_H = DATA['epsilon_i_H']['VALUES'] epsilon_i = DATA['epsilon_...
925fb1e76bf23915385cf56e3a663d111615700d
710
def requestor_is_superuser(requestor): """Return True if requestor is superuser.""" return getattr(requestor, "is_superuser", False)
7b201601cf8a1911aff8271ff71b6d4d51f68f1a
711
def removeDuplicates(listToRemoveFrom: list[str]): """Given list, returns list without duplicates""" listToReturn: list[str] = [] for item in listToRemoveFrom: if item not in listToReturn: listToReturn.append(item) return listToReturn
8265e7c560d552bd9e30c0a1140d6668abd1b4d6
712
import json def importConfig(): """設定ファイルの読み込み Returns: tuple: str: interface, str: alexa_remote_control.sh path list: device list """ with open("config.json", "r", encoding="utf-8") as f: config = json.load(f) interface = config["interface"] ...
84f8fc0deec4aebfe48209b01d1a35f7373d31e6
715
import time def time_for_log() -> str: """Function that print the current time for bot prints""" return time.strftime("%d/%m %H:%M:%S - ")
0f964d5c827782ff8cc433e57bb3e78d0a7c7cba
716
def is_unique2(s): """ Use a list and the int of the character will tell if that character has already appeared once """ d = [] for t in s: if d[int(t)]: return False d[int(t)] = True return True
b1a1bdea8108690a0e227fd0b75f910bd6b99a07
719
def stations_by_river(stations): """Give a dictionary to hold the rivers name as keys and their corresponding stations' name as values""" rivers_name = [] for i in stations: if i.river not in rivers_name: rivers_name.append(i.river) elif i.river in rivers_name: contin...
66fd928415619d175b7069b8c3103a3f7d930aac
720
def inverse(a): """ [description] calculating the inverse of the number of characters, we do this to be able to find our departure when we arrive. this part will be used to decrypt the message received. :param a: it is an Int :return: x -> it is an Int """ x = 0 while a * x % 9...
2893d2abda34e4573eb5d9602edc0f8e14246e09
721
import random def random_param_shift(vals, sigmas): """Add a random (normal) shift to a parameter set, for testing""" assert len(vals) == len(sigmas) shifts = [random.gauss(0, sd) for sd in sigmas] newvals = [(x + y) for x, y in zip(vals, shifts)] return newvals
07430572c5051b7142499bcbdbc90de5abfcbd4d
722
def get_frameheight(): """return fixed height for extra panel """ return 120
3bd810eea77af15527d3c1df7ab0b788cfe90000
723
def default_heart_beat_interval() -> int: """ :return: in seconds """ return 60
58171c8fb5632aa2aa46de8138828cce2eaa4d33
724
from typing import OrderedDict import six def BuildPartialUpdate(clear, remove_keys, set_entries, field_mask_prefix, entry_cls, env_builder): """Builds the field mask and patch environment for an environment update. Follows the environments update semantic which applies operations in an ...
320c589cd45dcec9a3ebba4b295075e23ef805ed
728
def bycode(ent, group): """ Get the data with the given group code from an entity. Arguments: ent: An iterable of (group, data) tuples. group: Group code that you want to retrieve. Returns: The data for the given group code. Can be a list of items if the group code occu...
c5b92f2bbd1cd5bc383a1102ccf54031222d82c3
729
def is_depth_wise_conv(module): """Determine Conv2d.""" if hasattr(module, "groups"): return module.groups != 1 and module.in_channels == module.out_channels elif hasattr(module, "group"): return module.group != 1 and module.in_channels == module.out_channels
27127f54edbf8d0653cab6c7dbfb1448f33ecab4
730
import heapq def dijkstra(graph, start, end=None): """ Find shortest paths from the start vertex to all vertices nearer than or equal to the end. The input graph G is assumed to have the following representation: A vertex can be any object that can be used as an index into a dictionary. G is...
b2a1ee983534c0a4af36ae7e3490c3b66949609b
732
import math def bond_number(r_max, sigma, rho_l, g): """ calculates the Bond number for the largest droplet according to Cha, H.; Vahabi, H.; Wu, A.; Chavan, S.; Kim, M.-K.; Sett, S.; Bosch, S. A.; Wang, W.; Kota, A. K.; Miljkovic, N. Dropwise Condensation on Solid Hydrophilic Surfaces. Science Advances 2...
2098a762dd7c2e80ff4a570304acf7cfbdbba2e5
733
async def timeron(websocket, battleID): """Start the timer on a Metronome Battle. """ return await websocket.send(f'{battleID}|/timer on')
f1601694e2c37d41adcc3983aa535347dc13db71
734
import numpy def to_unit_vector(this_vector): """ Convert a numpy vector to a unit vector Arguments: this_vector: a (3,) numpy array Returns: new_vector: a (3,) array with the same direction but unit length """ norm = numpy.linalg.norm(this_vector) assert norm > 0.0, "vector ...
ae46bf536b8a67a1be1e98ae051eebf1f8696e37
735
import base64 def decode(msg): """ Convert data per pubsub protocol / data format Args: msg: The msg from Google Cloud Returns: data: The msg data as a string """ if 'data' in msg: data = base64.b64decode(msg['data']).decode('utf-8') return data
32e85b3f0c18f3d15ecb0779825941024da75909
736
def _validate_attribute_id(this_attributes, this_id, xml_ids, enforce_consistency, name): """ Validate attribute id. """ # the given id is None and we don't have setup attributes # -> increase current max id for the attribute by 1 if this_id is None and this_attributes is None: this_id = ma...
e85201c85b790576f7c63f57fcf282a985c22347
737
def filter_characters(results: list) -> str: """Filters unwanted and duplicate characters. Args: results: List of top 1 results from inference. Returns: Final output string to present to user. """ text = "" for i in range(len(results)): if results[i] == "$": ...
6b2ca1446450751258e37b70f2c9cbe5110a4ddd
738
from typing import Union from typing import SupportsFloat def is_castable_to_float(value: Union[SupportsFloat, str, bytes, bytearray]) -> bool: """ prüft ob das objekt in float umgewandelt werden kann Argumente : o_object : der Wert der zu prüfen ist Returns : True|False Exceptions : keine...
e3882c0e64da79dc9a0b74b4c2414c7bf29dd6c9
739
from operator import itemgetter def list_unique(hasDupes): """Return the sorted unique values from a list""" # order preserving d = dict((x, i) for i, x in enumerate(hasDupes)) return [k for k, _ in sorted(d.items(), key=itemgetter(1))]
0ba0fcb216400806aca4a11d5397531dc19482f6
740
import os def delete_files(dpath: str, label: str='') -> str: """ Delete all files except the files that have names matched with label If the directory path doesn't exist return 'The path doesn't exist' else return the string with the count of all files in the directory and the count of deleted ...
c8b95d9b14d698145667383bbfe88045330e5cb0
743
def get_neighbours(sudoku, row, col): """Funkcja zwraca 3 listy sasiadow danego pola, czyli np. wiersz tego pola, ale bez samego pola""" row_neighbours = [sudoku[row][y] for y in range(9) if y != col] col_neighbours = [sudoku[x][col] for x in range(9) if x != row] sqr_neighbours = [sudoku[x][y] for x in...
b10766fc8925b54d887925e1a684e368c0f3b550
744
def console_script(tmpdir): """Python script to use in tests.""" script = tmpdir.join('script.py') script.write('#!/usr/bin/env python\nprint("foo")') return script
be6a38bec8bb4f53de83b3c632ff3d26d88ef1c7
746
from typing import Optional from typing import TextIO from typing import Type import csv from pathlib import Path import sys def get_dialect( filename: str, filehandle: Optional[TextIO] = None ) -> Type[csv.Dialect]: """Try to guess dialect based on file name or contents.""" dialect: Type[csv.Dialect] = c...
91d21e5bb321e7deb1e4b8db445d5c51d8138456
748
def home(): """ Home interface """ return '''<!doctype html> <meta name="viewport" content="width=device-width, initial-scale=1" /> <body style="margin:0;font-family:sans-serif;color:white"> <form method="POST" action="analyse" enctype="multipart/form-data"> <label style="text-align:center;position:fixe...
d8a9c3449ac56b04ee1514729342ce29469c5c2f
751
def selection_criteria_1(users, label_of_interest): """ Formula for Retirement/Selection score: x = sum_i=1_to_n (r_i) — sum_j=1_to_m (r_j). Where first summation contains reliability scores of users who have labeled it as the same as the label of interest, second summation contains reliability scor...
8255fd3645d5b50c43006d2124d06577e3ac8f2d
752
import re def book_number_from_path(book_path: str) -> float: """ Parses the book number from a directory string. Novellas will have a floating point value like "1.1" which indicates that it was the first novella to be published between book 1 and book 2. :param book_path: path of the currently ...
087cb0b8cd0c48c003175a05ed0d7bb14ad99ac3
753
def intervals_split_merge(list_lab_intervals): """ 对界限列表进行融合 e.g. 如['(2,5]', '(5,7]'], 融合后输出为 '(2,7]' Parameters: ---------- list_lab_intervals: list, 界限区间字符串列表 Returns: ------- label_merge: 合并后的区间 """ list_labels = [] # 遍历每个区间, 取得左值右值字符串组成列表 for lab in list_la...
a9e99ec6fc51efb78a4884206a72f7f4ad129dd4
754
from typing import List def set_process_tracking(template: str, channels: List[str]) -> str: """This function replaces the template placeholder for the process tracking with the correct process tracking. Args: template: The template to be modified. channels: The list of channels to be used. ...
0cf720bd56a63939541a06e60492472f92c4e589
755
def read_dynamo_table(gc, name, read_throughput=None, splits=None): """ Reads a Dynamo table as a Glue DynamicFrame. :param awsglue.context.GlueContext gc: The GlueContext :param str name: The name of the Dynamo table :param str read_throughput: Optional read throughput - supports values from "0.1"...
5f789626cb3fc8004532cc59bdae128b744b111e
756
def fuzzyCompareDouble(p1, p2): """ compares 2 double as points """ return abs(p1 - p2) * 100000. <= min(abs(p1), abs(p2))
e2a93a993147e8523da0717d08587250003f9269
757
from typing import Dict from typing import List def prettify_eval(set_: str, accuracy: float, correct: int, avg_loss: float, n_instances: int, stats: Dict[str, List[int]]): """Returns string with prettified classification results""" table = 'problem_type accuracy\n' for k in sorted(stats...
5e5ba8ffa62668e245daa2ada9fc09747b5b6dd2
760
def find_roots(graph): """ return nodes which you can't traverse down any further """ return [n for n in graph.nodes() if len(list(graph.predecessors(n))) == 0]
7dbf755d2b76f066370d149638433c6693e8e7b9
762
def check_args(**kwargs): """ Check arguments for themis load function Parameters: **kwargs : a dictionary of arguments Possible arguments are: probe, level The arguments can be: a string or a list of strings Invalid argument are ignored (e.g. probe = 'g', level=...
3e25dc43df0a80a9a16bcca0729ee0b170a9fb89
763
import time def wait_for_sidekiq(gl): """ Return a helper function to wait until there are no busy sidekiq processes. Use this with asserts for slow tasks (group/project/user creation/deletion). """ def _wait(timeout=30, step=0.5): for _ in range(timeout): time.sleep(step) ...
7fe98f13e9474739bfe4066f20e5f7d813ee4476
764
def insert_node_after(new_node, insert_after): """Insert new_node into buffer after insert_after.""" next_element = insert_after['next'] next_element['prev'] = new_node new_node['next'] = insert_after['next'] insert_after['next'] = new_node new_node['prev'] = insert_after return new_node
e03fbd7bd44a3d85d36069d494464b9237bdd306
765
def classname(object, modname): """Get a class name and qualify it with a module name if necessary.""" name = object.__name__ if object.__module__ != modname: name = object.__module__ + '.' + name return name
af4e05b0adaa9c90bb9946edf1dba67a40e78323
766
def ceil(array, value): """ Returns the smallest index i such that array[i - 1] < value. """ l = 0 r = len(array) - 1 i = r + 1 while l <= r: m = l + int((r - l) / 2) if array[m] >= value: # This mid index is a candidate for the index we are searching for ...
689148cebc61ee60c99464fde10e6005b5d901a9
767
def show_table(table, **options): """ Displays a table without asking for input from the user. :param table: a :class:`Table` instance :param options: all :class:`Table` options supported, see :class:`Table` documentation for details :return: None """ return table.show_table(**options)
ec040d4a68d2b3cb93493f336daf1aa63289756e
771
import pickle def load_embeddings(topic): """ Load TSNE 2D Embeddings generated from fitting BlazingText on the news articles. """ print(topic) embeddings = pickle.load( open(f'covidash/data/{topic}/blazing_text/embeddings.pickle', 'rb')) labels = pickle.load( open(f'covidash/d...
de2f74c7e467e0f057c10a0bc15b79ee9eecb40f
773
import csv def read_q_stats(csv_path): """Return list of Q stats from file""" q_list = [] with open(csv_path, newline='') as csv_file: reader = csv.DictReader(csv_file) for row in reader: q_list.append(float(row['q'])) return q_list
f5bee4859dc4bac45c4c3e8033da1b4aba5d2818
777
from typing import Union from pathlib import Path from typing import Dict import json def read_json(json_path: Union[str, Path]) -> Dict: """ Read json file from a path. Args: json_path: File path to a json file. Returns: Python dictionary """ with open(json_path, "r") as fp:...
c0b55e5363a134282977ee8a01083490e9908fcf
780
def redact(str_to_redact, items_to_redact): """ return str_to_redact with items redacted """ if items_to_redact: for item_to_redact in items_to_redact: str_to_redact = str_to_redact.replace(item_to_redact, '***') return str_to_redact
f86f24d3354780568ec2f2cbf5d32798a43fdb6a
781
def gce_zones() -> list: """Returns the list of GCE zones""" _bcds = dict.fromkeys(['us-east1', 'europe-west1'], ['b', 'c', 'd']) _abcfs = dict.fromkeys(['us-central1'], ['a', 'b', 'c', 'f']) _abcs = dict.fromkeys( [ 'us-east4', 'us-west1', 'europe-west4', ...
10e684b2f458fe54699eb9886af148b092ec604d
782
def create_classes_names_list(training_set): """ :param training_set: dict(list, list) :return: (list, list) """ learn_classes_list = [] for k, v in training_set.items(): learn_classes_list.extend([str(k)] * len(v)) return learn_classes_list
0b30153afb730d4e0c31e87635c9ece71c530a41
784
def map_parallel(function, xs): """Apply a remote function to each element of a list.""" if not isinstance(xs, list): raise ValueError('The xs argument must be a list.') if not hasattr(function, 'remote'): raise ValueError('The function argument must be a remote function.') # EXERCISE:...
1fe75868d5ff12a361a6aebd9e4e49bf92c32126
785
def masseuse_memo(A, memo, ind=0): """ Return the max with memo :param A: :param memo: :param ind: :return: """ # Stop if if ind > len(A)-1: return 0 if ind not in memo: memo[ind] = max(masseuse_memo(A, memo, ind + 2) + A[ind], masseuse_memo(A, memo, ind + 1)) ...
03d108cb551f297fc4fa53cf9575d03af497ee38
786
def get_tone(pinyin): """Renvoie le ton du pinyin saisi par l'utilisateur. Args: pinyin {str}: l'entrée pinyin par l'utilisateur Returns: number/None : Si pas None, la partie du ton du pinyin (chiffre) """ # Prenez le dernier chaine du pinyin tone = pin...
fc0b02902053b3f2470acf952812573f5125c4cf
787
import os def downloads_dir(): """ :returns string: default downloads directory path. """ return os.path.expanduser('~') + "/Downloads/"
f8c328a3176a664387059ebf6af567d018bcd57e
790
def get_reddit_tables(): """Returns 12 reddit tables corresponding to 2016""" reddit_2016_tables = [] temp = '`fh-bigquery.reddit_posts.2016_{}`' for i in range(1, 10): reddit_2016_tables.append(temp.format('0' + str(i))) for i in range(10, 13): reddit_2016_tables.append(temp.format(...
e590ab35becbe46aa220257f6629e54f720b3a13
791
def _unpack(f): """to unpack arguments""" def decorated(input): if not isinstance(input, tuple): input = (input,) return f(*input) return decorated
245d425b45d9d7ef90239b791d6d65bcbd0433d5
793
import requests def fetch_url(url): """Fetches the specified URL. :param url: The URL to fetch :type url: string :returns: The response object """ return requests.get(url)
26198dbc4f7af306e7a09c86b59a7da1a4802241
794
def get_symbol_size(sym): """Get the size of a symbol""" return sym["st_size"]
b2d39afe39542e7a4e1b4fed60acfc83e6a58677
795
from pathlib import Path def get_parent_dir(os_path: str) -> str: """ Get the parent directory. """ return str(Path(os_path).parents[1])
3a6e518119e39bfbdb9381bc570ac772b88b1334
796
import re def searchLiteralLocation(a_string, patterns): """assumes a_string is a string, being searched in assumes patterns is a list of strings, to be search for in a_string returns a list of re span object, representing the found literal if it exists, else returns an empty list""" results = [] ...
0f751bae801eaee594216688551919ed61784187
797
def get_factors(n: int) -> list: """Returns the factors of a given integer. """ return [i for i in range(1, n+1) if n % i == 0]
c15a0e30e58597daf439facd3900c214831687f2
799
import numpy def read_mat_cplx_bin(fname): """ Reads a .bin file containing floating-point values (complex) saved by Koala Parameters ---------- fname : string Path to the file Returns ------- buffer : ndarray An array containing the complex floating-point values read...
f2761f4cd7031dc16cb2f9903fd431bc7b4212d8
801
def getChrLenList(chrLenDict, c): """ Given a chromosome length dictionary keyed on chromosome names and a chromosome name (c) this returns a list of all the runtimes for a given chromosome across all Step names. """ l = [] if c not in chrLenDict: return l for n in chrLenDict[c]: ...
aedf613484262ac5bd31baf384ade2eb35f3e1eb
802
import torch import math def positionalencoding3d(d_model, dx, dy, dz): """ :param d_model: dimension of the model :param height: height of the positions :param width: width of the positions :return: d_model*height*width position matrix """ # if d_model % 6 != 0: # raise ValueError("...
178dc3b86e3be0c9e799f5f0c658808f541f1eca
803
def _check_varrlist_integrity(vlist): """Return true if shapes and datatypes are the same""" shape = vlist[0].data.shape datatype = vlist[0].data.dtype for v in vlist: if v.data.shape != shape: raise(Exception("Data shapes don't match")) if v.data.dtype != datatype: ...
1b6fedd1222757c0bc92490be85d8030ee877842
804
import os def GetPID(): """Returns the PID of the shell.""" return os.getppid()
28e56a9d0c1c6c1d005c58f5c9fffeb3857d8877
805
def compute_MSE(predicted, observed): """ predicted is scalar and observed as array""" if len(observed) == 0: return 0 err = 0 for o in observed: err += (predicted - o)**2/predicted return err/len(observed)
e2cc326dde2ece551f78cd842d1bf44707bfb6db
806
def if_else(cond, a, b): """Work around Python 2.4 """ if cond: return a else: return b
4b11328dd20fbb1ca663f272ac8feae15a8b26d9
807
import re def get_tbl_type(num_tbl, num_cols, len_tr, content_tbl): """ obtain table type based on table features """ count_very_common = len([i for i, x in enumerate(content_tbl) if re.match(r'^very common',x) ]) count_common = len([i for i, x in enumerate(content_tbl) if re.match(r'^common',x) ]) count...
19c06766c932aab4385fa8b7b8cd3c56a2294c65
808
import unicodedata def normalize(form, text): """Return the normal form form for the Unicode string unistr. Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'. """ return unicodedata.normalize(form, text)
6d32604a951bb13ff649fd3e221c2e9b35d4f1a1
809
def box(type_): """Create a non-iterable box type for an object. Parameters ---------- type_ : type The type to create a box for. Returns ------- box : type A type to box values of type ``type_``. """ class c(object): __slots__ = 'value', def __init...
5b4721ab78ce17f9eeb93abcc59bed046917d296
810
def rssError(yArr, yHatArr): """ Desc: 计算分析预测误差的大小 Args: yArr:真实的目标变量 yHatArr:预测得到的估计值 Returns: 计算真实值和估计值得到的值的平方和作为最后的返回值 """ return ((yArr - yHatArr) ** 2).sum()
429dd6b20c20e6559ce7d4e57deaea58a664d22b
811
def get_language_file_path(language): """ :param language: string :return: string: path to where the language file lies """ return "{lang}/localization_{lang}.json".format(lang=language)
9be9ee9511e0c82772ab73d17f689c181d63e67c
812
import random def randbytes(size) -> bytes: """Custom implementation of random.randbytes, since that's a Python 3.9 feature """ return bytes(random.sample(list(range(0, 255)), size))
0ea312376de3f90894befb29ec99d86cfc861910
813
def path_to_model(path): """Return model name from path.""" epoch = str(path).split("phase")[-1] model = str(path).split("_dir/")[0].split("/")[-1] return f"{model}_epoch{epoch}"
78b10c8fb6f9821e6be6564738d40f822e675cb6
814
def removeString2(string, removeLen): """骚操作 直接使用字符串替换""" alphaNums = [] for c in string: if c not in alphaNums: alphaNums.append(c) while True: preLength = len(string) for c in alphaNums: replaceStr = c * removeLen string = string.replace(rep...
57d01d7c2a244b62a173fef35fd0acf1b622beed
815
def binary_to_string(bin_string: str): """ >>> binary_to_string("01100001") 'a' >>> binary_to_string("a") Traceback (most recent call last): ... ValueError: bukan bilangan biner >>> binary_to_string("") Traceback (most recent call last): ... ValueError: tidak ada yang diinput...
f22dd64027ee65acd4d782a6a1ce80520f016770
817
def tabindex(field, index): """Set the tab index on the filtered field.""" field.field.widget.attrs["tabindex"] = index return field
c42b64b3f94a2a8a35b8b0fa3f14fe6d44b2f755
818