content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def is_gzipped(filename): """ Returns True if the target filename looks like a GZIP'd file. """ with open(filename, 'rb') as fh: return fh.read(2) == b'\x1f\x8b'
b1afb5b9cddc91fbc304392171f04f4b018fa929
617
def get_keys_from_file(csv): """Extract the credentials from a csv file.""" lines = tuple(open(csv, 'r')) creds = lines[1] access = creds.split(',')[2] secret = creds.split(',')[3] return access, secret
eccf56c52dd82656bf85fef618133f86fd9276e6
620
from typing import Union def metric_try_to_float(s: str) -> Union[float, str]: """ Try to convert input string to float value. Return float value on success or input value on failure. """ v = s try: if "%" in v: v = v[:-1] return float(v) except ValueError: return str(s)
6b0121469d35bc6af04d4808721c3ee06955d02e
623
import shutil def disk_usage(pathname): """Return disk usage statistics for the given path""" ### Return tuple with the attributes total,used,free in bytes. ### usage(total=118013599744, used=63686647808, free=48352747520) return shutil.disk_usage(pathname)
c7a36e2f3200e26a67c38d50f0a97dd015f7ccfa
625
import numbers def ensure_r_vector(x): """Ensures that the input is rendered as a vector in R. It is way more complicated to define an array in R than in Python because an array in R cannot end with an comma. Examples -------- >>> ensure_r_vector("string") "c('string')" >>> ensure_r_vector(1) 'c(1)' >>> ensure_r_vector(list("abcd")) "c('a', 'b', 'c', 'd')" >>> ensure_r_vector((1, 2)) 'c(1, 2)' """ if isinstance(x, str): out = f"c('{x}')" elif isinstance(x, numbers.Number): out = f"c({x})" elif isinstance(x, (tuple, list)): mapped = map(lambda l: str(l) if isinstance(l, numbers.Number) else f"'{l}'", x) concatenated = ", ".join(mapped) out = f"c({concatenated})" else: raise NotImplementedError( f"'ensure_r_vector' is not defined for dtype {type(x)}" ) return out
14fdeb6bf73244c69d9a6ef89ba93b33aa4a66d8
629
def locate_all_occurrence(l, e): """ Return indices of all element occurrences in given list :param l: given list :type l: list :param e: element to locate :return: indices of all occurrences :rtype: list """ return [i for i, x in enumerate(l) if x == e]
95b662f359bd94baf68ac86450d94298dd6b366d
636
from typing import List def format_count( label: str, counts: List[int], color: str, dashed: bool = False ) -> dict: """Format a line dataset for chart.js""" ret = { "label": label, "data": counts, "borderColor": color, "borderWidth": 2, "fill": False, } if dashed: ret["borderDash"] = [5, 5] return ret
40f5aee7ad5d66f57737345b7d82e45a97cf6633
638
def get_valid_segment(text): """ Returns None or the valid Loki-formatted urn segment for the given input string. """ if text == '': return None else: # Return the converted text value with invalid characters removed. valid_chars = ['.', '_', '-'] new_text = '' for char in text: if char in valid_chars or char.isalnum(): new_text += char return new_text
423c1764b590df635b0794bfe52a0a8479d53fbf
639
def positive_dice_parse(dice: str) -> str: """ :param dice: Formatted string, where each line is blank or matches t: [(t, )*t] t = (0|T|2A|SA|2S|S|A) (note: T stands for Triumph here) :return: Formatted string matching above, except tokens are replaced with their corresponding values in the 4-tuple system, (successes, advantages, triumphs, despairs) """ return dice.replace("0", "(0, 0, 0, 0)")\ .replace("T", "(1, 0, 1, 0)")\ .replace("2A", "(0, 2, 0, 0)")\ .replace("SA", "(1, 1, 0, 0)")\ .replace("2S", "(2, 0, 0, 0)")\ .replace("S", "(1, 0, 0, 0)")\ .replace("A", "(0, 1, 0, 0)")
5b266a4025706bfc8f4deabe67735a32f4b0785d
642
def GetVerificationStepsKeyName(name): """Returns a str used to uniquely identify a verification steps.""" return 'VerificationSteps_' + name
e50e9bd7b586d8bbfaf8902ce343d35d752948a4
646
import codecs import logging def read_file(file_path): """ Read the contents of a file using utf-8 encoding, or return an empty string if it does not exist :param file_path: str: path to the file to read :return: str: contents of file """ try: with codecs.open(file_path, 'r', encoding='utf-8', errors='xmlcharrefreplace') as infile: return infile.read() except OSError as e: logging.exception('Error opening {}'.format(file_path)) return ''
13a72bc939021e3046243ed9afc7014cb403652a
647
def _list_subclasses(cls): """ Recursively lists all subclasses of `cls`. """ subclasses = cls.__subclasses__() for subclass in cls.__subclasses__(): subclasses += _list_subclasses(subclass) return subclasses
4cebf48916c64f32fcd5dfff28ecde7a155edb90
649
def rho_MC(delta, rhoeq=4.39e-38): """ returns the characteristic density of an axion minicluster in [solar masses/km^3] forming from an overdensity with overdensity parameter delta. rhoeq is the matter density at matter radiation equality in [solar masses/km^3] """ return 140 * (1 + delta) * delta**3 * rhoeq
f28e382cfcf661199728363b3ebe86f25e92760c
654
def is_ascii(string): """Return True is string contains only is us-ascii encoded characters.""" def is_ascii_char(char): return 0 <= ord(char) <= 127 return all(is_ascii_char(char) for char in string)
cd3aeddcad7610de83af6ec5a67ecbac95f11fd8
655
def summary(task): """Given an ImportTask, produce a short string identifying the object. """ if task.is_album: return u'{0} - {1}'.format(task.cur_artist, task.cur_album) else: return u'{0} - {1}'.format(task.item.artist, task.item.title)
87387c47e90998c270f6f8f2f63ceacebd4cdc78
658
from typing import List def build_graph(order: int, edges: List[List[int]]) -> List[List[int]]: """Builds an adjacency list from the edges of an undirected graph.""" adj = [[] for _ in range(order)] for u, v in edges: adj[u].append(v) adj[v].append(u) return adj
86bdd0d4314777ff59078b1c0f639e9439f0ac08
660
def calculate(cart): """Return the total shipping cost for the cart. """ total = 0 for line in cart.get_lines(): total += line.item.shipping_cost * line.quantity return total
4b6d9bd94ce3a5748f0d94ab4b23dab993b430e4
666
def format_perm(model, action): """ Format a permission string "app.verb_model" for the model and the requested action (add, change, delete). """ return '{meta.app_label}.{action}_{meta.model_name}'.format( meta=model._meta, action=action)
12f532e28f685c2a38a638de63928f07039d44c8
668
import math def normal_to_angle(x, y): """ Take two normal vectors and return the angle that they give. :type x: float :param x: x normal :type y: float :param y: y normal :rtype: float :return: angle created by the two normals """ return math.atan2(y, x) * 180 / math.pi
c6f5b5e2952858cd3592b4e0849806b0ccd5de78
670
import socket def is_open_port(port): """ Check if port is open :param port: port number to be checked :type port: int :return: is port open :rtype: bool """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind(("127.0.0.1", port)) except socket.error: return False return True
df81cc942f39d00bbdb8cb11628666a117c9788f
672
def build_attribute_set(items, attr_name): """Build a set off of a particular attribute of a list of objects. Adds 'None' to the set if one or more of the objects in items is missing the attribute specified by attr_name. """ attribute_set = set() for item in items: attribute_set.add(getattr(item, attr_name, None)) return attribute_set
2cee5922463188a4a8d7db79d6be003e197b577f
673
def get_elk_command(line): """Return the 2 character command in the message.""" if len(line) < 4: return "" return line[2:4]
550eda4e04f57ae740bfd294f9ec3b243e17d279
674
def safe_div(a, b): """ Safe division operation. When b is equal to zero, this function returns 0. Otherwise it returns result of a divided by non-zero b. :param a: number a :param b: number b :return: a divided by b or zero """ if b == 0: return 0 return a / b
68e5bccbe812315b9a1d27a1fa06d26d5339d6fd
675
def shouldAvoidDirectory(root, dirsToAvoid): """ Given a directory (root, of type string) and a set of directory paths to avoid (dirsToAvoid, of type set of strings), return a boolean value describing whether the file is in that directory to avoid. """ subPaths = root.split('/') for i, subPath in enumerate(subPaths): dir = '/'.join(subPaths[:i+1]) if dir in dirsToAvoid: return True return False
afc92111f57031eb1e2ba797d80ea4abc2a7ccd0
676
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
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
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
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 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
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
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 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
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
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 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
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
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 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
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
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 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 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 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 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
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
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 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 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 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
def hook_name_to_env_name(name, prefix='HOOKS'): """ >>> hook_name_to_env_name('foo.bar_baz') HOOKS_FOO_BAR_BAZ >>> hook_name_to_env_name('foo.bar_baz', 'PREFIX') PREFIX_FOO_BAR_BAZ """ return '_'.join([prefix, name.upper().replace('.', '_')])
b0dabce88da8ddf8695303ac4a22379baa4ddffa
822
def readline_skip_comments(f): """ Read a new line while skipping comments. """ l = f.readline().strip() while len(l) > 0 and l[0] == '#': l = f.readline().strip() return l
c4b36af14cc48b1ed4cd72b06845e131015da6c6
823
def _verify_weight_parameters(weight_parameters): """Verifies that the format of the input `weight_parameters`. Checks that the input parameters is a 2-tuple of tensors of equal shape. Args: weight_parameters: The parameters to check. Raises: RuntimeError: If the input is not a 2-tuple of tensors with equal shape. Returns: The input `weight_parameters`. """ if len(weight_parameters) != 2: raise RuntimeError("Incorrect number of weight parameters. Expected " "2 tensors, got {}".format(len(weight_parameters))) if weight_parameters[0].shape != weight_parameters[1].shape: raise RuntimeError("Expected theta and log alpha parameter tensor " "to be same shape. Got shapes {} and {}" .format(weight_parameters[0].get_shape().as_list(), weight_parameters[1].get_shape().as_list())) return weight_parameters
9ec018c66d48e830250fd299cd50f370118132cc
824
def _crc16_checksum(bytes): """Returns the CRC-16 checksum of bytearray bytes Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html Initial value changed to 0x0000 to match Stellar configuration. """ crc = 0x0000 polynomial = 0x1021 for byte in bytes: for i in range(8): bit = (byte >> (7 - i) & 1) == 1 c15 = (crc >> 15 & 1) == 1 crc <<= 1 if c15 ^ bit: crc ^= polynomial return crc & 0xFFFF
2b00d11f1b451f3b8a4d2f42180f6f68d2fbb615
825
def is_bond_member(yaml, ifname): """Returns True if this interface is a member of a BondEthernet.""" if not "bondethernets" in yaml: return False for _bond, iface in yaml["bondethernets"].items(): if not "interfaces" in iface: continue if ifname in iface["interfaces"]: return True return False
521186221f2d0135ebcf1edad8c002945a56da26
827
def extract_paths(actions): """ <Purpose> Given a list of actions, it extracts all the absolute and relative paths from all the actions. <Arguments> actions: A list of actions from a parsed trace <Returns> absolute_paths: a list with all absolute paths extracted from the actions relative_paths: a list with all relative paths extracted from the actions """ absolute_paths = [] relative_paths = [] actions_with_path = ['open', 'creat', 'statfs', 'access', 'stat', 'link', 'unlink', 'chdir', 'rmdir', 'mkdir'] for action in actions: # get the name of the syscall and remove the "_syscall" part at the end. action_name = action[0][:action[0].find("_syscall")] # we only care about actions containing paths if action_name not in actions_with_path: continue # we only care about paths that exist action_result = action[2] if action_result == (-1, 'ENOENT'): continue path = action[1][0] if path.startswith("/"): if path not in absolute_paths: absolute_paths.append(path) else: if path not in relative_paths: relative_paths.append(path) # get the second path of link if action_name == "link": path = action[1][1] if path.startswith("/"): if path not in absolute_paths: absolute_paths.append(path) else: if path not in relative_paths: relative_paths.append(path) return absolute_paths, relative_paths
94aaf8fef1a7c6d3efd8b04c980c9e87ee7ab4ff
833
import re def only_letters(answer): """Checks if the string contains alpha-numeric characters Args: answer (string): Returns: bool: """ match = re.match("^[a-z0-9]*$", answer) return bool(match)
32c8905294f6794f09bb7ea81ed7dd4b6bab6dc5
841
def _InUse(resource): """All the secret names (local names & remote aliases) in use. Args: resource: Revision Returns: List of local names and remote aliases. """ return ([ source.secretName for source in resource.template.volumes.secrets.values() ] + [ source.secretKeyRef.name for source in resource.template.env_vars.secrets.values() ])
cf13ccf1d0fffcd64ac8b3a40ac19fdb2b1d12c5
842
import re def re_identify_image_metadata(filename, image_names_pattern): """ Apply a regular expression to the *filename* and return metadata :param filename: :param image_names_pattern: :return: a list with metadata derived from the image filename """ match = re.match(image_names_pattern, filename) return None if match is None else match.groups()
1730620682f2457537e3f59360d998b251f5067f
843
def mark_task(func): """Mark function as a defacto task (for documenting purpose)""" func._is_task = True return func
9f0156fff2a2a6dcb64e79420022b78d1c254490
846
def make_slack_message_divider() -> dict: """Generates a simple divider for a Slack message. Returns: The generated divider. """ return {'type': 'divider'}
9d0243c091065056a29d9fa05c62fadde5dcf6f6
847
def _stringify(item): """ Private funtion which wraps all items in quotes to protect from paths being broken up. It will also unpack lists into strings :param item: Item to stringify. :return: string """ if isinstance(item, (list, tuple)): return '"' + '" "'.join(item) + '"' if isinstance(item, str) and len(item) == 0: return None return '"%s"' % item
7187b33dccce66cb81b53ed8e8c395b74e125633
853
def _get_tree_filter(attrs, vecvars): """ Pull attributes and input/output vector variables out of a tree System. Parameters ---------- attrs : list of str Names of attributes (may contain dots). vecvars : list of str Names of variables contained in the input or output vectors. Returns ------- function A function that takes a System and returns a list of name value pairs. """ def _finder(system): found = [] for attr in attrs: parts = attr.split('.') # allow attrs with dots try: obj = system for p in parts: obj = getattr(obj, p) found.append((attr, obj)) except AttributeError: pass for var in vecvars: if var in system._outputs: found.append((var, system._outputs[var])) elif var in system._inputs: found.append((var, system._inputs[var])) return found return _finder
fb96025a075cfc3c56011f937d901d1b87be4f03
854
def replace_string(original, start, end, replacement): """Replaces the specified range of |original| with |replacement|""" return original[0:start] + replacement + original[end:]
c71badb26287d340170cecdbae8d913f4bdc14c6
861
def dictionarify_recpat_data(recpat_data): """ Covert a list of flat dictionaries (single-record dicts) into a dictionary. If the given data structure is already a dictionary, it is left unchanged. """ return {track_id[0]: patterns[0] for track_id, patterns in \ [zip(*item.items()) for item in recpat_data]} \ if not isinstance(recpat_data, dict) else recpat_data
d1cdab68ab7445aebe1bbcce2f220c73d6db308f
862
def _module_exists(module_name): """ Checks if a module exists. :param str module_name: module to check existance of :returns: **True** if module exists and **False** otherwise """ try: __import__(module_name) return True except ImportError: return False
8f3ed2e97ee6dbb41d6e84e9e5595ec8b6f9b339
868
def normal_shock_pressure_ratio(M, gamma): """Gives the normal shock static pressure ratio as a function of upstream Mach number.""" return 1.0+2.0*gamma/(gamma+1.0)*(M**2.0-1.0)
30d0a339b17bab2b662fecd5b19073ec6478a1ec
871
def get_ical_file_name(zip_file): """Gets the name of the ical file within the zip file.""" ical_file_names = zip_file.namelist() if len(ical_file_names) != 1: raise Exception( "ZIP archive had %i files; expected 1." % len(ical_file_names) ) return ical_file_names[0]
7013840891844358f0b4a16c7cefd31a602d9eae
873
def decode_field(value): """Decodes a field as defined in the 'Field Specification' of the actions man page: http://www.openvswitch.org/support/dist-docs/ovs-actions.7.txt """ parts = value.strip("]\n\r").split("[") result = { "field": parts[0], } if len(parts) > 1 and parts[1]: field_range = parts[1].split("..") start = field_range[0] end = field_range[1] if len(field_range) > 1 else start if start: result["start"] = int(start) if end: result["end"] = int(end) return result
1a1659e69127ddd3c63eb7d4118ceb4e53a28ca0
885
def _nonempty_line_count(src: str) -> int: """Count the number of non-empty lines present in the provided source string.""" return sum(1 for line in src.splitlines() if line.strip())
ad2ac0723f9b3e1f36b331175dc32a8591c67893
886
def _dump_multipoint(obj, fmt): """ Dump a GeoJSON-like MultiPoint object to WKT. Input parameters and return value are the MULTIPOINT equivalent to :func:`_dump_point`. """ coords = obj['coordinates'] mp = 'MULTIPOINT (%s)' points = (' '.join(fmt % c for c in pt) for pt in coords) # Add parens around each point. points = ('(%s)' % pt for pt in points) mp %= ', '.join(points) return mp
cdea05b91c251b655e08650807e3f74d3bb5e77b
889
def binary_distance(label1, label2): """Simple equality test. 0.0 if the labels are identical, 1.0 if they are different. >>> from nltk.metrics import binary_distance >>> binary_distance(1,1) 0.0 >>> binary_distance(1,3) 1.0 """ return 0.0 if label1 == label2 else 1.0
2c4eaebda2d6955a5012cc513857aed66df60194
890
def apply_function(f, *args, **kwargs): """ Apply a function or staticmethod/classmethod to the given arguments. """ if callable(f): return f(*args, **kwargs) elif len(args) and hasattr(f, '__get__'): # support staticmethod/classmethod return f.__get__(None, args[0])(*args, **kwargs) else: assert False, "expected a function or staticmethod/classmethod"
374be0283a234d4121435dbd3fa873640f2b9ad1
898
def make_file_iterator(filename): """Return an iterator over the contents of the given file name.""" # pylint: disable=C0103 with open(filename) as f: contents = f.read() return iter(contents.splitlines())
e7b612465717dafc3155d9df9fd007f7aa9af509
902
def pad_in(string: str, space: int) -> str: """ >>> pad_in('abc', 0) 'abc' >>> pad_in('abc', 2) ' abc' """ return "".join([" "] * space) + string
325c0751da34982e33e8fae580af6f439a2dcac0
908
def extend_params(params, more_params): """Extends dictionary with new values. Args: params: A dictionary more_params: A dictionary Returns: A dictionary which combines keys from both dictionaries. Raises: ValueError: if dicts have the same key. """ for yak in more_params: if yak in params: raise ValueError('Key "%s" is already in dict' % yak) params.update(more_params) return params
626db0ae8d8a249b8c0b1721b7a2e0f1d4c084b8
910
def get_rdf_lables(obj_list): """Get rdf:labels from a given list of objects.""" rdf_labels = [] for obj in obj_list: rdf_labels.append(obj['rdf:label']) return rdf_labels
2bcf6a6e8922e622de602f5956747955ea39eeda
919
def get_request_list(flow_list: list) -> list: """ 将flow list转换为request list。在mitmproxy中,flow是对request和response的总称,这个功能只获取request。 :param flow_list: flow的列表 :return: request的列表 """ req_list = [] for flow in flow_list: request = flow.get("request") req_list.append(request) return req_list
a70e0120ef2be88bd0644b82317a2a0748352c6c
922
def _B(slot): """Convert slot to Byte boundary""" return slot*2
97f13e9fd99989a83e32f635193a0058656df68b
925
def union(l1, l2): """ return the union of two lists """ return list(set(l1) | set(l2))
573e3b0e475b7b33209c4a477ce9cab53ec849d4
931
def get_start_end(sequence, skiplist=['-','?']): """Return position of first and last character which is not in skiplist. Skiplist defaults to ['-','?']).""" length=len(sequence) if length==0: return None,None end=length-1 while end>=0 and (sequence[end] in skiplist): end-=1 start=0 while start<length and (sequence[start] in skiplist): start+=1 if start==length and end==-1: # empty sequence return -1,-1 else: return start,end
b67e0355516f5aa5d7f7fad380d262cf0509bcdb
934
def middle(word): """Returns all but the first and last characters of a string.""" return word[1:-1]
257a159c46633d3c3987437cb3395ea2be7fad70
940
import re from pathlib import Path import json def load_stdlib_public_names(version: str) -> dict[str, frozenset[str]]: """Load stdlib public names data from JSON file""" if not re.fullmatch(r"\d+\.\d+", version): raise ValueError(f"{version} is not a valid version") try: json_file = Path(__file__).with_name("stdlib_public_names") / ( version + ".json" ) json_text = json_file.read_text(encoding="utf-8") json_obj = json.loads(json_text) return {module: frozenset(names) for module, names in json_obj.items()} except FileNotFoundError: raise ValueError( f"there is no data of stdlib public names for Python version {version}" ) from None
02775d96c8a923fc0380fe6976872a7ed2cf953a
942
def calc_dof(model): """ Calculate degrees of freedom. Parameters ---------- model : Model Model. Returns ------- int DoF. """ p = len(model.vars['observed']) return p * (p + 1) // 2 - len(model.param_vals)
ccff8f5a7624b75141400747ec7444ec55eb492d
947
import functools def skip_if_disabled(func): """Decorator that skips a test if test case is disabled.""" @functools.wraps(func) def wrapped(*a, **kwargs): func.__test__ = False test_obj = a[0] message = getattr(test_obj, 'disabled_message', 'Test disabled') if getattr(test_obj, 'disabled', False): test_obj.skipTest(message) func(*a, **kwargs) return wrapped
56d42a1e0418f4edf3d4e8478358495b1353f57a
956
from typing import Any import itertools def _compare_keys(target: Any, key: Any) -> bool: """ Compare `key` to `target`. Return True if each value in `key` == corresponding value in `target`. If any value in `key` is slice(None), it is considered equal to the corresponding value in `target`. """ if not isinstance(target, tuple): return target == key for k1, k2 in itertools.zip_longest(target, key, fillvalue=None): if k2 == slice(None): continue if k1 != k2: return False return True
ff5c60fab8ac0cbfe02a816ec78ec4142e32cfbf
957