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) [1, 0] >>> get_structure_index('.[[...],..].',1) [1, 0, 0] >>> get_structure_index('.[[...]...].',2) [1, 0, 1] >>> get_structure_index('.[[...]...].',3) [1, 0, 2] >>> get_structure_index('.[[...]...].',4) [1, 1] >>> get_structure_index('.[[...]...].',5) [1, 2] >>> get_structure_index('.[[...]...].',6) [1, 3] >>> get_structure_index('.[[...]...].',7) [2] """ structure_index = [0] current_stream_index = 0 for p in structure_pattern: if p == '[': structure_index.append(0) elif p == '.': if current_stream_index == stream_index: return structure_index structure_index[-1] += 1 current_stream_index += 1 elif p == ']': structure_index.pop(-1) structure_index[-1] += 1 else: raise Exception('Invalid character in structure pattern: %s' % repr(p)) raise Exception('Provided stream index does not exist in the provided structure pattern')
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 average[coin] = sum([item['compound'] for item in sentiment[coin]]) # get the mean compound sentiment if it's not 0 if average[coin] != 0: average[coin] = average[coin] / len(sentiment[coin]) return average
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: datasetlist.append(item) except AttributeError: pass return datasetlist
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.model_type model_class = None if model_type in available_models: model_class_module = importlib.import_module("lib.classes.model_classes." + model_type) model_class = getattr(model_class_module, model_type) else: print("Error: model type not available. Check lib/classes/model_classes/ for available models", flush=True) return False model = model_class(master_config) if master_config.Core_Config.Reload_Config.reload: reload_path = master_config.Core_Config.Reload_Config.reload_path if master_config.Core_Config.Reload_Config.by_name: model.load_weights(reload_path + "model_and_config/final_model_weights.h5", by_name=True) else: model.load_weights(reload_path + "model_and_config/final_model_weights.h5") return model
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: filename = ovl['image'] # checks if overlay is image or video is_img = False for img_fmt in img_formats: is_img = filename.lower().endswith(img_fmt) if is_img: break # treats image overlay if is_img: duration = str(float(ovl['end_time']) - float(ovl['start_time'])) is_gif = filename.lower().endswith('.gif') has_fade = (float(ovl.get('fade_in_duration', 0)) + float(ovl.get('fade_out_duration', 0))) > 0 # A GIF with no fade is treated as an animated GIF should. # It works even if it is not animated. # An animated GIF cannot have fade in or out effects. if is_gif and not has_fade: include_args = ['-ignore_loop', '0'] else: include_args = ['-f', 'image2', '-loop', '1'] include_args += ['-itsoffset', str(ovl['start_time']), '-t', duration] # GIFs should have a special input decoder for FFMPEG. if is_gif: include_args += ['-c:v', 'gif'] include_args += ['-i'] include_cmd += include_args + ['%s/assets/%s' % (data_dir, filename)] # treats video overlays else: duration = str(float(ovl['end_time']) - float(ovl['start_time'])) include_args = ['-itsoffset', str(ovl['start_time']), '-t', duration] include_args += ['-i'] include_cmd += include_args + ['%s/assets/%s' % (data_dir, filename)] # adds texts as video starting and finishing on their overlay timing for img2 in text_tmp_images: duration = str(float(img2['end_time']) - float(img2['start_time'])) include_args = ['-f', 'image2', '-loop', '1'] include_args += ['-itsoffset', str(img2['start_time']), '-t', duration] include_args += ['-i'] include_cmd += include_args + [str(img2['path'])] return include_cmd
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(' ', '') regions = [tuple(region.split('_')) for region in limits.split(';')] return '_'.join([seq[int(i)-1:int(j)] for i,j in regions])
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) if K < 0: cnd = 1. - cnd return cnd
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 vol["class"] == "{none}": return "" if vol["class"] == "{empty}": return None else: return vol["class"]
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 commuting * 1 anticommuting n : number of indices in base form the dummy indices are always in consecutive positions Examples ======== >>> from sympy.combinatorics.tensor_can import dummy_sgs >>> dummy_sgs(range(2, 8), 0, 8) [[0, 1, 3, 2, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 5, 4, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 7, 6, 8, 9], [0, 1, 4, 5, 2, 3, 6, 7, 8, 9], [0, 1, 2, 3, 6, 7, 4, 5, 8, 9]] """ if len(dummies) > n: raise ValueError("List too large") res = [] # exchange of contravariant and covariant indices if sym is not None: for j in dummies[::2]: a = list(range(n + 2)) if sym == 1: a[n] = n + 1 a[n + 1] = n a[j], a[j + 1] = a[j + 1], a[j] res.append(a) # rename dummy indices for j in dummies[:-3:2]: a = list(range(n + 2)) a[j:j + 4] = a[j + 2], a[j + 3], a[j], a[j + 1] res.append(a) return res
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_than_or_equals" elif comparator in ["gt", "greater_than"]: return "greater_than" elif comparator in ["ge", "greater_than_or_equals"]: return "greater_than_or_equals" elif comparator in ["ne", "not_equals"]: return "not_equals" elif comparator in ["str_eq", "string_equals"]: return "string_equals" elif comparator in ["len_eq", "length_equals", "count_eq"]: return "length_equals" elif comparator in ["len_gt", "count_gt", "length_greater_than", "count_greater_than"]: return "length_greater_than" elif comparator in ["len_ge", "count_ge", "length_greater_than_or_equals", \ "count_greater_than_or_equals"]: return "length_greater_than_or_equals" elif comparator in ["len_lt", "count_lt", "length_less_than", "count_less_than"]: return "length_less_than" elif comparator in ["len_le", "count_le", "length_less_than_or_equals", \ "count_less_than_or_equals"]: return "length_less_than_or_equals" else: return comparator
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) res.append(root.data) res = res + inorder_traversal(root.right) return res
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(bits)-1] if last_bit.isdigit(): count = int(last_bit) return count
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, return the given string. :param value: the string :param number_format: number format with which the value is normalized :return: the normalized string """ if number_format == 'COMMA_POINT' or number_format == 'Comma Point': nor_str = re.sub(pattern=',', repl='', string=value) elif number_format == 'POINT_COMMA' or number_format == 'Point Comma': nor_str = re.sub(pattern=',', repl='.', string=re.sub(pattern='\.', repl='', string=value)) elif number_format == 'SPACE_POINT' or number_format == 'Space Point': nor_str = re.sub(pattern='\s', repl='', string=value) elif number_format == 'SPACE_COMMA' or number_format == 'Space Comma': nor_str = re.sub(pattern=',', repl='.', string=re.sub(pattern='\s', repl='', string=value)) elif number_format == 'NONE_COMMA' or number_format == 'None Comma': nor_str = re.sub(pattern=',', repl='.', string=value) else: nor_str = value return nor_str
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 the x values :return: """ if len(xs) != len(ys): raise ValueError("xs and ys must be of equal length") half_max_y = max(ys) / 2 for i in range(len(xs)-1): if ys[i+1] >= half_max_y: x_dist = xs[i+1] - xs[i] y_dist = ys[i+1] - ys[i] y_offset = half_max_y - ys[i] if y_offset == 0: return xs[i] else: x_offset = y_offset / y_dist * x_dist return xs[i] + x_offset return None
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_i']['VALUES'] xi = DATA['xi']['VALUES'] final_E = DATA['Final_E']['VALUES'] Energy_range = np.linspace(epsilon_i, final_E, 200) u = Energy_range/epsilon_i gg = (1+2/3*(1-1/(2*u))*np.log(np.e+(u-1)**(1/2))) g = ((u-1)/u**2)*((u/(u+1))**(3/2))*((1-1/u)**(1/2))*gg Cross_sections = 4*np.pi*(a_0**2)*((epsilon_i_H/epsilon_i)**2)*xi*g return(Energy_range, Cross_sections)
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"] if not interface: return False arc_path = config["arc_path"] devices = config["device_list"] return (interface, arc_path, devices)
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: continue big_list = [] for n in rivers_name: lists = [] for y in stations: if n == y.river: lists.append(y.name) elif n != y.river: continue lists = sorted(lists) big_list.append(lists) dictionary = dict(zip(rivers_name, big_list)) dicti = {} for key in sorted(dictionary): dicti.update({key : dictionary[key]}) assert dicti != {} return dicti
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 % 97 != 1: x = x + 1 return x
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 effective order of clear -> remove -> set. Leading and trailing whitespace is stripped from elements in remove_keys and the keys of set_entries. Args: clear: bool, If true, the patch removes existing keys. remove_keys: iterable(string), Iterable of keys to remove. set_entries: {string: string}, Dict containing entries to set. field_mask_prefix: string, The prefix defining the path to the base of the proto map to be patched. entry_cls: AdditionalProperty, The AdditionalProperty class for the type of entry being updated. env_builder: [AdditionalProperty] -> Environment, A function which produces a patch Environment with the given list of entry_cls properties. Returns: (string, Environment), a 2-tuple of the field mask defined by the arguments and a patch environment produced by env_builder. """ remove_keys = set(k.strip() for k in remove_keys or []) # set_entries is sorted by key to make it easier for tests to set the # expected patch object. set_entries = OrderedDict( (k.strip(), v) for k, v in sorted(six.iteritems(set_entries or {}))) if clear: entries = [ entry_cls(key=key, value=value) for key, value in six.iteritems(set_entries) ] return field_mask_prefix, env_builder(entries) field_mask_entries = [] seen_keys = set() for key in remove_keys: field_mask_entries.append('{}.{}'.format(field_mask_prefix, key)) seen_keys.add(key) entries = [] for key, value in six.iteritems(set_entries): entries.append(entry_cls(key=key, value=value)) if key not in seen_keys: field_mask_entries.append('{}.{}'.format(field_mask_prefix, key)) # Sorting field mask entries makes it easier for tests to set the expected # field mask since dictionary iteration order is undefined. field_mask_entries.sort() return ','.join(field_mask_entries), env_builder(entries)
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 occurs multiple times. """ data = [v for k, v in ent if k == group] if len(data) == 1: return data[0] return data
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 a dictionary, indexed by vertices. For any vertex v, G[v] is itself a dictionary, indexed by the neighbors of v. For any edge v->w, G[v][w] is the length of the edge. The output is a pair (D,P) where D[v] is the distance from start to v and P[v] is the predecessor of v along the shortest path from s to v. Original by David Eppstein, UC Irvine, 4 April 2002 http://code.activestate.com/recipes/119466-dijkstras-algorithm-for-shortest-paths/ >>> G = DirectedGraph({'s':{'u':10, 'x':5}, 'u':{'v':1, 'x':2}, 'v':{'y':4}, 'x':{'u':3, 'v':9, 'y':2}, \ 'y':{'s':7, 'v':6}}) >>> distances, predecessors = dijkstra(G, 's', 'v') >>> sorted(distances.items()) [('s', 14), ('u', 8), ('v', 9), ('x', 5), ('y', 7)] >>> sorted(predecessors.items()) [('s', 'y'), ('u', 'x'), ('v', 'u'), ('x', 's'), ('y', 'x')] """ distances = {} # dictionary of final distances predecessors = {} # dictionary of predecessors (previous node) queue = [] # queue heapq.heappush(queue, (0, start)) while len(queue) > 0: distance, node = heapq.heappop(queue) if node in distances and distance > distances[node]: continue if node == end: break # Loop through neighbours edges = graph.edges(node, distance=distance) for neighbour, length in edges.items(): total = distance + length if neighbour in distances: if total >= distances[neighbour]: continue distances[neighbour] = total predecessors[neighbour] = node heapq.heappush(queue, (total, neighbour)) return distances, predecessors
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 2020, 6 (2), eaax0746. https://doi.org/10.1126/sciadv.aax0746""" l_y = math.sqrt(sigma / (rho_l*g)) bond = r_max**2 / l_y**2 return bond
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 norm must be greater than 0" if norm: return this_vector/numpy.linalg.norm(this_vector) else: return this_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 = max(xml_ids) + 1 # the given id is None and we do have setup attributes # set id to the id present in the setup elif this_id is None and this_attributes is not None: this_id = this_attributes[name] # the given id is not None and we do have setup attributes # -> check that the ids match (unless we are in over-write mode) elif this_id is not None and this_attributes is not None: if (this_id != this_attributes[name]) and enforce_consistency: raise ValueError("Expect id %i for attribute %s, got %i" % (this_attributes[name], name, this_id)) return this_id
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] == "$": continue elif i + 1 < len(results) and results[i] == results[i + 1]: continue else: text += results[i] return text
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 >>> is_castable_to_float(1) True >>> is_castable_to_float('1') True >>> is_castable_to_float('1.0') True >>> is_castable_to_float('1,0') False >>> is_castable_to_float('True') False >>> is_castable_to_float(True) True >>> is_castable_to_float('') False >>> is_castable_to_float(None) # noqa False """ try: float(value) return True except (ValueError, TypeError): return False
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 files. Args: dpath Type: string Description: Directory path label Type: string Description: Store characters or name that could be matched with name of files in the directory. If match are true the file will not be deleted. Returns: Type: string Description: The 'The path doesn't exist' string or the string with the count of all files in the directory and the count of deleted files. """ directory = os.path.abspath(dpath) print(directory) # Test whether the path exists if not os.path.exists(dpath): return "The path doesn't exist" else: # Make list of files files = os.listdir(directory) all_files_count = len(files) delete_files_count = 0 for file in files: if file.find(label) == -1: os.remove(directory + "\\" + file) delete_files_count += 1 return "All files: {} Delete files: {}".format(all_files_count, delete_files_count)
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 range(9) if x//3 == row//3 for y in range(9) if y//3 == col//3 if x!=row or y!=col] return row_neighbours, col_neighbours, sqr_neighbours
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] = csv.excel_tab file_path = Path(filename) if file_path.suffix == ".txt": pass elif file_path.suffix == ".csv": if filehandle: dialect = csv.Sniffer().sniff(filehandle.read(4 * 1024)) filehandle.seek(0) else: sys.stderr.write("Error: File does not have the ending csv or txt.\n") sys.exit(2) return dialect
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:fixed;top:0;bottom:0;width:100%;background-position:center;background-size:cover;background-image:url(https://blog.even3.com.br/wp-content/uploads/2019/04/saiba-como-e-por-que-fazer-crachas-para-eventos-1.png)"> <br /><br /> <h1>Cara-crachá</h1> <h3 id="processing" style="display:none">Processando...</h3> <input type="file" name="file" onchange="processing.style.display='block';this.form.submit()" style="display:none" /> </label> </form> </body> '''
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 scores of users who have labeled it differently Args: users (list): List of users where each element is a tuple of the form (uid, ulabel, f1 score) label_of_interest (int): Label under consideration (left hand summation of formula) Returns (int): 1 = select the subject id, 0 = don't select """ left_sum, right_sum = 0, 0 threshold = 2.0 for user in users: uid, ulabel, f1_score = user if ulabel == label_of_interest: left_sum += f1_score else: right_sum += f1_score if left_sum - right_sum >= threshold: return 1 else: return 0
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 parsed book :return: book number """ num = int(re.findall(r'[0-9]{2}', book_path)[-1]) return num / 10
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_lab_intervals: for s in lab.split(','): list_labels.append(s.replace('(', '').replace(')', '').replace(']', '')) list_lab_vals = [float(lab) for lab in list_labels] # 取得最大最小值的索引 id_max_val = list_lab_vals.index(max(list_lab_vals)) id_min_val = list_lab_vals.index(min(list_lab_vals)) # 取得最大最小值的字符串 lab_max_interval = list_labels[id_max_val] lab_min_interval = list_labels[id_min_val] # 如果右边界限的值为+Inf,则改为')', 其他为']' l_label = '(' if lab_max_interval == '+Inf': r_label = ')' else: r_label = ']' label_merge = l_label + lab_min_interval + ',' + lab_max_interval + r_label return label_merge
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. Returns: The modified template. """ tracking = "" for channel in channels: tracking += " ULong64_t {ch}_processed = 0;\n".format(ch=channel) tracking += " std::mutex {ch}_bar_mutex;\n".format(ch=channel) tracking += " auto c_{ch} = {ch}_df_final.Count();\n".format(ch=channel) tracking += " c_{ch}.OnPartialResultSlot(quantile, [&{ch}_bar_mutex, &{ch}_processed, &quantile](unsigned int /*slot*/, ULong64_t /*_c*/) {{".format( ch=channel ) tracking += ( "\n std::lock_guard<std::mutex> lg({ch}_bar_mutex);\n".format( ch=channel ) ) tracking += " {ch}_processed += quantile;\n".format(ch=channel) tracking += ' Logger::get("main - {ch} Channel")->info("{{}} Events processed ...", {ch}_processed);\n'.format( ch=channel ) tracking += " });\n" return template.replace("{PROGRESS_CALLBACK}", tracking)
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" to "1.5", inclusive. :param str splits: Optional number of input splits - defaults to the SparkContext default parallelism. :rtype: awsglue.dynamicframe.DynamicFrame """ connection_options = { 'dynamodb.input.tableName': name, 'dynamodb.splits': str(splits or gc.spark_session.sparkContext.defaultParallelism) } if read_throughput: connection_options['dynamodb.throughput.read.percent'] = str(read_throughput) return gc.create_dynamic_frame_from_options(connection_type='dynamodb', connection_options=connection_options)
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.keys()): accuracy_ = stats[k][0]/stats[k][1] accuracy_ = accuracy_*100 table += k table += ' ' table += '{:.2f}%\n'.format(accuracy_) return '\n' + set_ + ' set average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'.format( avg_loss, correct, n_instances, accuracy) + table + '\n'
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='l0', etc.) Invalid argument names are ignored (e.g. 'probes', 'lev', etc.) Returns: list Prepared arguments in the same order as the inputs Examples: res_probe = check_args(probe='a') (res_probe, res_level) = check_args(probe='a b', level='l2') (res_level, res_probe) = check_args(level='l1', probe=['a', 'b']) # With incorrect argument probes: res = check_args(probe='a', level='l2', probes='a b') : res = [['a'], ['l2']] """ valid_keys = {'probe', 'level'} valid_probe = {'a', 'b', 'c', 'd', 'e'} valid_level = {'l1', 'l2'} # Return list of values from arg_list that are only included in valid_set def valid_list(arg_list, valid_set): valid_res = [] for arg in arg_list: if arg in valid_set: valid_res.append(arg) return valid_res # Return list res = [] for key, values in kwargs.items(): if key.lower() not in valid_keys: continue # resulting list arg_values = [] # convert string into list, or ignore the argument if isinstance(values, str): values = [values] elif not isinstance(values, list): continue for value in values: arg_values.extend(value.strip().lower().split()) # simple validation of the arguments if key.lower() == 'probe': arg_values = valid_list(arg_values, valid_probe) if key.lower() == 'level': arg_values = valid_list(arg_values, valid_level) res.append(arg_values) return res
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) busy = False processes = gl.sidekiq.process_metrics()["processes"] for process in processes: if process["busy"]: busy = True if not busy: return True return False return _wait
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 # so save it, and continue searching for a smaller candidate on the # left side. i = m r = m - 1 else: # This mid index is not a candidate so continue searching the right # side. l = m + 1 return i
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/data/{topic}/blazing_text/labels.pickle', 'rb')) if '</s>' in labels: labels.remove('</s>') embeddings = embeddings[:len(labels), :] return embeddings, labels
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: data = json.load(fp) return data
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', 'europe-west3', 'europe-west2', 'asia-east1', 'asia-southeast1', 'asia-northeast1', 'asia-south1', 'australia-southeast1', 'southamerica-east1', 'asia-east2', 'asia-northeast2', 'europe-north1', 'europe-west6', 'northamerica-northeast1', 'us-west2', ], ['a', 'b', 'c'], ) _zones_combo = {**_bcds, **_abcfs, **_abcs} zones = [f'{loc}-{zone}' for loc, zones in _zones_combo.items() for zone in zones] return zones
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: Modify the list comprehension below to invoke "function" # remotely on each element of "xs". This should essentially submit # one remote task for each element of the list and then return the # resulting list of ObjectIDs. return [function.remote(x) for x in xs]
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)) return memo[ind]
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 = pinyin[-1] # Déterminer s'il s'agit d'un type numérique if tone.isdigit(): return tone else: return None
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(str(i))) return reddit_2016_tables
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 = [] for pattern in patterns: regex = pattern match = re.search(regex, a_string) if match: results.append((match, match.span())) return 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 from the file See Also -------- write_mat_cplx_bin Example ------- >>> buf = read_mat_cplx_bin('test/file_cplx.bin') >>> buf array([[ 0.00000000e+00 +0.00000000e+00j, 0.00000000e+00 +0.00000000e+00j, 0.00000000e+00 +0.00000000e+00j, ..., 0.00000000e+00 +0.00000000e+00j, 0.00000000e+00 +0.00000000e+00j, 0.00000000e+00 +0.00000000e+00j], [ 0.00000000e+00 +0.00000000e+00j, 4.97599517e-09 +9.14632536e-10j, 5.99623329e-09 -1.52811275e-08j, ..., 1.17636354e-07 -1.01500063e-07j, 6.33714581e-10 +5.61812996e-09j, 0.00000000e+00 +0.00000000e+00j], ..., [ 0.00000000e+00 +0.00000000e+00j, -1.26479121e-08 -2.92324431e-09j, -4.59448168e-09 +9.28236474e-08j, ..., -4.15031316e-08 +1.48466597e-07j, 4.41099779e-08 -1.27046489e-08j, 0.00000000e+00 +0.00000000e+00j], [ -0.00000000e+00 +0.00000000e+00j, 0.00000000e+00 +0.00000000e+00j, 0.00000000e+00 +0.00000000e+00j, ..., 0.00000000e+00 +0.00000000e+00j, 0.00000000e+00 +0.00000000e+00j, 0.00000000e+00 +0.00000000e+00j]], dtype=complex64) """ kcplx_header_dtype = numpy.dtype([ ("width", "i4"), ("height", "i4") ]) f = open(fname, 'rb') kcplx_header = numpy.fromfile(f, dtype=kcplx_header_dtype, count=1) shape = (kcplx_header['height'], kcplx_header['width']) #print kcplx_header tmp = numpy.fromfile(f, dtype='float32') f.close() real_tmp = (tmp[0:kcplx_header['height']*kcplx_header['width']]).reshape(shape) imag_tmp = (tmp[kcplx_header['height']*kcplx_header['width']:]).reshape(shape) #print tmp #print 'array = {}'.format(len(tmp)) return real_tmp + 1j*imag_tmp
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]: l.append(chrLenDict[c][n]) return l
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("Cannot use sin/cos positional encoding with " # "odd dimension (got dim={:d})".format(d_model)) pe = torch.zeros(d_model, dx, dy, dz) # Each dimension use half of d_model interval = int(d_model // 6) * 2 div_term = torch.exp(torch.arange(0., interval, 2) * -(math.log(10000.0) / interval)) pos_x = torch.arange(0., dx).unsqueeze(1) * div_term pos_y = torch.arange(0., dy).unsqueeze(1) * div_term pos_z = torch.arange(0., dz).unsqueeze(1) * div_term pe[0:interval:2, :, :, :] = torch.sin(pos_x).T.unsqueeze(2).unsqueeze(3).repeat(1, 1, dy, dz) pe[1:interval:2, :, :, :] = torch.cos(pos_x).T.unsqueeze(2).unsqueeze(3).repeat(1, 1, dy, dz) pe[interval:int(interval * 2):2, :, :] = torch.sin(pos_y).T.unsqueeze(1).unsqueeze(3).repeat(1, dx, 1, dz) pe[interval + 1:int(interval * 2):2, :, :] = torch.cos(pos_y).T.unsqueeze(1).unsqueeze(3).repeat(1, dx, 1, dz) pe[int(interval * 2):int(interval * 3):2, :, :] = torch.sin(pos_z).T.unsqueeze(1).unsqueeze(2).repeat(1, dx, dy, 1) pe[int(interval * 2) + 1:int(interval * 3):2, :, :] = torch.cos(pos_z).T.unsqueeze(1).unsqueeze(2).repeat(1, dx, dy, 1) return pe
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: raise(Exception("Data types don't match")) return True
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_uncommon = len([i for i, x in enumerate(content_tbl) if re.match(r'^uncommon',x) ]) count_rare = len([i for i, x in enumerate(content_tbl) if re.match(r'^rare',x) ]) count_very_rare = len([i for i, x in enumerate(content_tbl) if re.match(r'^very rare',x) ]) count_unknown = len([i for i, x in enumerate(content_tbl) if "known" in x]) count_feats = [count_very_common,count_common,count_uncommon,count_rare,count_very_rare,count_unknown] if num_cols>3 and sum(count_feats) > num_cols+5: tbl_type = 'table type: vertical' elif ((all(i <2 for i in count_feats) and num_tbl<=5) or num_cols>4) and len_tr>2: tbl_type = 'table type: horizontal' else: tbl_type = 'table type: vertical' return tbl_type
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__(self, value): if not isinstance(value, type_): raise TypeError( "values must be of type '%s' (received '%s')" % ( type_.__name__, type(value).__name__, ), ) self.value = value c.__name__ = 'Boxed%s' + type_.__name__ return c
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(replaceStr, '') if preLength == len(string): break return string
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 diinputkan >>> binary_to_string("39") Traceback (most recent call last): ... ValueError: bukan bilangan biner >>> binary_to_string(1010) Traceback (most recent call last): ... TypeError: bukan string """ if not isinstance(bin_string, str): raise TypeError("bukan string") if not bin_string: raise ValueError("tidak ada yang diinputkan") if not all(char in "01" for char in bin_string): raise ValueError("bukan bilangan biner") return "".join([chr(int(i, 2)) for i in bin_string.split()])
f22dd64027ee65acd4d782a6a1ce80520f016770
817
def tabindex(field, index): """Set the tab index on the filtered field.""" field.field.widget.attrs["tabindex"] = index return field
c42b64b3f94a2a8a35b8b0fa3f14fe6d44b2f755
818