content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def orGate(argumentValues): """ Method that evaluates the OR gate @ In, argumentValues, list, list of values @ Out, outcome, float, calculated outcome of the gate """ if 1 in argumentValues: outcome = 1 else: outcome = 0 return outcome
5c36bbba85c86307b8e22ff1b097d26f2f3f7d11
652,007
def organize_edges(edges, borders=None, default_border='land'): """ Organize edges in to various collections specified by borders. Required Arguments ------------------ * edges : List of edges of the form (node_number, node_number, ... , edge_type) The sort...
e89f7e3d840ec6d593f6da9dfa3235cb6cffc238
652,008
def leftcommonsubstring(s1: str, s2: str) -> int: """Size of the common start of two strings. "foo", "bar" => 0, "built", "build" => 4, "cat", "cats" => 3""" for (i, (c1, c2)) in enumerate(zip(s1, s2)): if c1 != c2: return i return min(len(s1), len(s2))
ea5205182626ef94bd090efca0ef74234a39a300
652,009
def isstrlessthan(string, length): """Checks if string is below length""" return len(string) < length
a3da55155f8a9784ea3a3e5d504884907cbf5757
652,010
import re def extract_function_code(code_chunk): """ Returns only the code of the function, without the funciton definition line or the docstring Parameters: code_chunk (str): A chunk of code. Returns: function_code (str): The code of the function. """ # Remove the function ...
9e3905b99f1066f34821a5402c8725750fb2dcac
652,013
def remove_u_score(col): """ This functions help to remove the "_" present in a specific text Parameters ---------- col Analysis column containing "_" present gets replaced along with upper case conversion Returns ------- String """ col_ = col.split("_") bl = [] f...
0cb3cfab9befdb8d6f355cec2d7117a10c731e1f
652,014
def calc_inference_loss(config,criterion,pred_heatmap,gt_heatmap,offset_criterion=None,pred_offset=None,gt_offset=None): """ calculate the loss for testing in one iteration """ # pred_heatmap (4 dim): n_batch,n_landmark,heatmap_size,heatmap_size # gt_heatmap (4 dim): n_batch,n_landmark,heatmap_s...
18d91c41f1e07ed5e71bc019755113243aafc573
652,015
import re def _clean(text): """ Cleans the text: Lowercasing, trimming, removing non-alphanumeric""" return " ".join(re.findall(r'\w+', text, flags=re.UNICODE)).lower()
ff3496a0fcae32ed1ecb7ceb106bbe60c1da25ea
652,016
def solve(in_array): """ This set matches up the three-point triangles present in the image into a 4-4 grid, with the triangles in the corners, so that the center is empty :param in_array: input array :return: expected output array """ prediction = list() corners = [-1,-1,-1,-1] # to...
46e6c92d0f8e498b2717c5edff76cf414322cadb
652,017
import json def read_config_file(filename): """ Read the json configuration file and return a map with the config entries """ with open(filename) as json_file: json_input = json.load(json_file) return json_input
2a94d44f1c204980049b7b865869e4f39af8cc68
652,018
def dim_col(d: int) -> str: """ Name of an dimension columns. Parameters ---------- d Dimension number. Returns ------- name: str Dimension name. Example ------- >>> from rle_array.testing import dim_col >>> dim_col(1) 'dim_1' """ return f"d...
e4f76bdba041535993aaea1ba613f1596d8e32e9
652,019
def proxy_list(client): """ list all the proxy configuration present on etcd """ backend_names = set() frontend_names = set() for _, meta in client.api.get_prefix('/traefik/backends'): ss = meta.key.decode().split('/') name = ss[3] backend_names.add(name) for _, meta...
fc90e4404086502ace249eeda7e89401cdcb1b20
652,020
import os def find_default_soundfont(): """ look through /usr/share for the first thing ending with *.sf[2,3] """ for dirpath,dirnames,filenames in os.walk('/usr/share'): for f in filenames: if f.endswith(".sf2") or f.endswith(".sf3"): return "0:0:%s"%os.path.jo...
3dd7fc6fbcb99a6cfa270ba13b85641291a7ddcd
652,022
import json def insert_workspace(cursor, organization_id, specification): """workspace情報登録 Args: cursor (mysql.connector.cursor): カーソル organization_id (int): オーガナイゼーションID specification (Dict)): ワークスペース情報のJson形式 Returns: int: ワークスペースID """ # insert実行 c...
8b14b21dc34198c36816a957f352bc97083f77c8
652,023
import requests def get_sitemap(url): """ :param Site map url: :return: Site map content """ get_url = requests.get(url) if get_url.status_code == 200: return get_url.text else: print('Unable to fetch sitemap: %s.' % url)
74f97a4878e3b422726396afc4bfb555ebd9fe64
652,024
import math def s1diff(a,b): """Angle from a to b in an anticlockwise direction.""" if b < a: b += 2*math.pi return b - a
222c0b0ee661ac881582d2478bae9633b9e0d33f
652,026
def wms_colors(): """ Color options usable by thredds wms """ return [ ('SST-36', 'sst_36'), ('Greyscale', 'greyscale'), ('Rainbow', 'rainbow'), ('OCCAM', 'occam'), ('OCCAM Pastel', 'occam_pastel-30'), ('Red-Blue', 'redblue'), ('NetCDF Viewer', 'nc...
9d95cb4f46d06bb8e15801c5b213f8a2f40ecf65
652,027
def is_file_acceptable_for_install_add(filename): """ ASR9K, CRS: .pie, .tar NCS6K: .smu, .iso, .pkg, .tar NCS4K: .iso .pkg ASR9K-X64: .iso, .rpm, .tar ASR900: .bin """ acceptable_file_types = ['.pie', '.rpm', '.tar', '.smu', '.iso', '.pkg', '.bin'] return any(ext in filename for ext...
d447578ef402806f8128fcd3f59fd846f568a563
652,030
def convert_length_in_minutes_to_hr_min_str(length_minutes=0): """ Convert minutes into something like 02h03m if given 123. Note that both hr and min are 0-padded """ hour = length_minutes // 60 minutes = length_minutes % 60 return "%02dh%02dm" % (hour, minutes)
606d8aa79302c255cc9188a0629f5e6fd3a9e37e
652,031
def check_type(dictionary): """ Checks if the lesson type is correct: lecture, online, seminar or workshop. If it is, returns True. Otherwise, returns the wrong lesson types. """ all_types = {"lecture", "online", "seminar", "workshop"} days = list(dictionary.values()) # didnt want to write...
6389d72bb37472225e4593a6bbbdab2ac3c34ac1
652,032
def solve_linear_system_LU(matrix, syms): """ Solves the augmented matrix system using LUsolve and returns a dictionary in which solutions are keyed to the symbols of syms *as ordered*. The matrix must be invertible. Examples ======== >>> from sympy import Matrix >>> from sympy.abc im...
f96eb0cc5511e9707a439a373c46e7e804912845
652,033
def PyDateTime_GET_DAY(space, w_obj): """Return the day, as an int from 1 through 31. """ return space.int_w(space.getattr(w_obj, space.newtext("day")))
1b750b59ba776ca13aa262ab7e1ec5c605900bfa
652,034
def kl_divergence(mu, logvar): """ from https://github.com/1Konny/Beta-VAE/blob/master/solver.py """ batch_size = mu.size(0) assert batch_size != 0 if mu.data.ndimension() == 4: mu = mu.view(mu.size(0), mu.size(1)) if logvar.data.ndimension() == 4: logvar = logvar....
977ea0feda092d0e56d5cda841454e9a8a347da4
652,035
def freeze_parameters(model): """ Freezes all parameters from a given model. Args: model (any of nff.nn.models) """ for param in model.parameters(): param.requires_grad = False return model
666b265cc2ad680cccd22d8c13df6dd4a465974a
652,036
def varname(variable, startmarker, endmarker): """Variable filter that returns the variable name without the marking punctuation. .. note:: Currently this function simply returns *variable* unchanged, no matter what *\*marker*’s are set to. :rtype: String :return: Variable name with the sup...
0907bb4f995b74d150fcdcf98c0c1921647079e1
652,037
def power_rule(mod, g, p): """ **Expression Name**: StorNewLin_Power_Capacity_MW **Defined Over**: STOR_NEW_LIN_OPR_PRDS The power capacity of a new storage project in a given operational period for the storage project is equal to the sum of all power capacity-build of vintages operational in t...
8b8425c15fbd0d6ae619fbb77d38c7d374b38271
652,038
def get_stats(stat_int_list: list) -> list: """Return a list of stats in play. Argument(s): stat_int_list: list -- list of stat indices """ stat_list = [] for stat in stat_int_list: if stat == 0: stat_list.append("Hunger") elif stat == 1: stat_list.appen...
22d36dcd5cb7736c1591e635ad49650c2e51fcc5
652,039
def rename_classes(schema): """ rename future class names to get rid of https://w3id.org/cwl/salad """ for item in schema: item['name'] = item['name'].split('#')[-1] return schema
5edd29e1daf45800cb8ce5f03aab63915169df7d
652,040
def convert_numeral(string: str) -> str: """ Convert a assembly numeral into a hexadecimal numeral :param string: A string representation of a simpSim numeral :return: Hexadecimal representation of the numeral """ return_num: int = 0 is_pointer: bool = string.startswith("[") and string.endsw...
e50fa5a11fe19129a8edeedce3058ce6dfa0c96f
652,041
import string import random def generateCharacters(charCount): """Generates ASCII lowercase random characters""" # https://www.educative.io/edpresso/how-to-generate-a-random-string-in-python letters = string.ascii_lowercase result = "".join(random.choice(letters) for i in range(charCount)) return ...
d309e42c2692c017305eb348bc7263e255911154
652,042
def _pair_members_to_new_node(dm, i, j, disallow_negative_branch_length): """Return the distance between a new node and decendants of that new node. Parameters ---------- dm : skbio.DistanceMatrix The input distance matrix. i, j : str Identifiers of entries in the distance matrix to...
c195be1a682d6ff6d7c347338f7d641f67a59f73
652,043
def _sym_solve(Dinv, M, A, r1, r2, solve, splu=False): """ An implementation of [1] equation 8.31 and 8.32 References ---------- .. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point optimizer for linear programming: an implementation of the homogeneous a...
ed306a13e55e5d63c626e280153e38d282dca943
652,044
def valid_group(group, yvarname): """ """ # make sure we have at least 100 values num_valid = group[yvarname].notnull().sum() if num_valid < 100: return False # make sure all the answers aren't the same counts = group[yvarname].value_counts() most_common = counts.max() ...
2eb784fb4fed8455a802cf028fec6a42a686a6d8
652,045
def root_app(expr): """Returns the pair (r, args) such that expr = r(*args) Arguments: - `expr`: an expression """ root = expr args = [] while root.is_app(): args.append(root.arg) root = root.fun #The arguments were collected in reverse order args.reverse...
500c3626cb777af28c4e58832d3ceb98751c873b
652,046
def get_file_download_details(file_response): """ Return the download_link from the file_response. Used for updating the message with a download button. """ download_link = file_response['file']['url_private_download'] return download_link
a875a14d29c20322b9efe2d986118c37498e4b04
652,047
def percentage(f): """ Return the percentage version of a float f """ return round(f * 100, 3)
cea866f21134d7d1ccc5a16c4d631c1b6d681a84
652,048
from pathlib import Path def create_module_scratch(module_name): """Create a scratch that is easily found (by developers) and removed, and doesn't clutter up the working directories. """ path = Path("~").expanduser() for path_part in ".idaes", "_scratch", module_name: path = path / path_pa...
32ba13f647805e26488cb8191afa40d5d1a02eb1
652,049
def recall(recs, truth, k=None): """ Compute recommendation recall. """ nrel = len(truth) if nrel == 0: return None if k is not None: nrel = min(nrel, k) recs = recs.iloc[:k] ngood = recs['item'].isin(truth.index).sum() return ngood / nrel
2b17beda9e4a408158ed280455d8e91fb457dd04
652,051
import torch def translation_error(pose_pred, pose_target): """ Angular error for rotation matrix :param pose_pred: shape (b, 3, 4), estimated pose :param pose_target: shape (b, 3, 4), target pose :return: float >>> import torch >>> pose_pred = torch.tensor([[1.0, 0, 0, 1], [0, 1, 0, 1],...
3ee46c5fa89fbaa4ed78be329d56f62bf95ec8d1
652,052
import re def clean_email_body(html_body: str): """Clean email body of various unwanted text noise/spam Cleans the following: + html tags + HTML reserved characters / character entities + ??? + non-ascii characters + Python bytes literal if stored improperly :param...
67e0b1a775f96b52f374acb9b518800a3cf210c9
652,053
def _replace_match(text, match, replacement): """Expands a regexp match in the text with its replacement. Args: text: str. The text in which to perform the replacement. match: re.MatchObject. A match object that applies to "text". replacement: str. The string to replace the match wit...
a813704d4ed2d77d0f8150abe5e2917f22b93cb9
652,054
def vert_to_string(*args): """Converts list of vertices to string""" return "v %10.8f %10.8f\n" % tuple(args)
0488efb6754870bb4fff5a190b4f87fe858b6fca
652,055
def parse(css): """Parse a CSS style into a dict.""" result = {} for declaration in css.split(";"): if declaration: key, value = declaration.split(":") result[key] = value.strip() return result
1feb5d015565920717f33536acfb2b4b81a0c261
652,056
def strip_whitespace(string_value): """ Return the input string without space, tab, or newline characters (for comparing strings) """ return ''.join( [c for c in string_value if c != ' ' and c != '\n' and c != '\t'] )
6cc68b1692bb39c66e5f09e2db009cd726526531
652,057
def amgxwrapper_poisson_read_runtimes(*filepaths): """Read the runtimes to solve the system for multiple runs. Parameters ---------- filepaths : tuple of strings or pathlib.Path objects Path of the files to read. Returns ------- runtimes : list of floats The runtimes. ...
dd5244b06737268d02dd4dc9496ae136c32e9a71
652,058
import re import os import sys def get_nends(ifiles): """Determines whether the dataset is paired-end or single-end. If paired-end data, checks to see if both mates (R1 and R2) are present for each sample. If single-end, nends is set to 1. Else if paired-end, nends is set to 2. @params ifiles list[<st...
dcd24a1309cf3778661e05046bbc65004ebe6748
652,059
def set_device_orientation_override(alpha: float, beta: float, gamma: float) -> dict: """Overrides the Device Orientation. Parameters ---------- alpha: float Mock alpha beta: float Mock beta gamma: float Mock gamma **Experimental** """ return { ...
2113001cc29327fbadcb053c3270e32a6384ea82
652,060
def load_movies(path_movies='movies.csv'): """ Returns a dictionary mapping item_id to item_name and another dictionary mapping item_id to a list of genres """ data = {} genreMap = {} with open(path_movies, encoding = "utf8") as f_data: for line in f_data: parts = line.st...
ed0ea02ae2a676c5ff3e03f5f7bd01ec9505faca
652,061
from typing import Callable import random def HitorMiss2(f: Callable[[float], float], a: float, b: float, c: float, d: float, n: int) -> float: """f: [a, b]->[c, d]""" k = 0 # 命中 c, d = min(c, 0), max(d, 0) S = (d - c) * (b - a) # for _ in range(n): x = r...
591e9098d00bb012983f19d165535dc074765d2f
652,062
def fib_iter(n): """[summary] Works iterative approximate O(n) Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n must be positive integer' fib_1 = 0 fib_2 = 1 sum = 0 if n <= 1: return n ...
1732da8939de9ed474c69977d3cfe5e69aa4b682
652,063
import json import requests import os def geom_type(in_geojson, encoding="utf-8"): """Returns the geometry type of a GeoJSON object. Args: in_geojson (dict): A GeoJSON object. encoding (str, optional): The encoding of the GeoJSON object. Defaults to "utf-8". Returns: str: The geo...
88095bda5b968ad9cee3b792af39fab4871dc844
652,064
def preprocess_features(california_housing_df): """ Prepares input features from California housing data set. @california_housing_df: A Pandas DataFrame expected to contain data from the California housing data set. @Returns: A DataFrame that contains...
d423a946fef021b505b84af7846b9a8b63eb4948
652,065
def define_XS_Spacing(bankfull_depth, bed_slope, default_spacing=300): """ source https://hecrasmodel.blogspot.com/2008/12/samuels-equation-for-cross-section.html :param bankful_depth: avg channel depth (avg bank elev to chan invert ) in ft. :param bed_slope: slope of channel. :return: """ t...
bf892144f14de2ad0cd04348d383edaa39a70215
652,066
def label_smoothing(x_onehot, epsilon=0.1): """ Label smoothing for one-hot type label. Args: x_onehot: Tensor with shape [..., depth] epsilon: float, default 0.1 The smoothing factor in range [0.0, 1.0]. Returns: Tensor with same shape as x_onehot, and its value ha...
78aaca96e940e244a6f12d97aa9bc246f2186269
652,067
def input_numbers(): """ Спрашивает у пользователя три числа и приводит введённые пользователем строки к числовому формату, проводит проверку типов и возвращает список длин отрезков и результат проверки типов введенных пользователем данных :return: list Список чисел; bool False - пользователь ввёл текс...
72a0b4025ae26a9c3300b2736db7e4df82ab1657
652,068
from datetime import datetime def get_offset(input_offset): """ Get the offset depending on the current day """ offset = 0 if input_offset[0] == "+": offset = int(input_offset[1:]) elif input_offset[0] == "-": offset = - int(input_offset[1:]) if input_offset == "+0" and dat...
c1f798df61bccefc057d832d0dd53fa69639c8f0
652,069
def _char_class_escape(m) -> str: """ regular expression are removed prior to matching with one exception: whitespace characters within character class expressions (charClassExpr) are not removed. """ match_str = m.group(0) return match_str if match_str[0] == '[' and match_str[-1] == ']' else ''
ba61129ff0e0b1d33c74def4bf596da5fac7d772
652,070
def yesno(value, icaps=True): """ Return 'yes' or 'no' according to the (assumed-bool) value. """ if (value): str = 'Yes' if icaps else 'yes' else: str = 'No' if icaps else 'no' return str
9bff0a577c81c900159d9650e78a75c6869e94b9
652,071
def geojson_line(): """ Returns ------- dict: GeoJSON-style LineString geometry object. Coordinates are in grid coordinates (Affine.identity()). """ return { 'type': 'LineString', 'coordinates': ((2, 2), (4, 4)) }
802c9ec778e79976de5776dc05956f04c265a8e7
652,072
import os import pickle def get_all_encodings(): """Results in finding encodings.""" encodings = {} names = [] for i in os.listdir('knownpeeps/'): name = i.replace('.pickle','') with open('knownpeeps/'+i, 'rb') as handle: encodings[name] = pickle.load(handle) names.append(name) return enco...
39368ba5e892d87ddf188e369317e699af74832c
652,073
def side_nav_dates(posts): """ . """ posts.sort(key=lambda d: d['date']) dates = list() new_posts = list() current_year = None current_month = None first_post = True for post in posts: year = post['date'].year month = post['date'].month str_year = post['date'].str...
00a2b68866e2ca797143b7d278c61a1efa74964a
652,074
def current_position_argument(argt): """ current argument in the tracker """ argv, pos = argt return argv[pos]
bdb59e1d45c8d13b5abe6415ee928d2c1fbb73e9
652,075
import sys def parsed_and_bounded_arg(i, max, min, parse): """ Returns parsed and bounded arg from argv. The `parse` parameter is a single-argument function which is called with the arg. The output of this function is only returned if it is between min and max. If parse fails or arg is not w...
0c2802df7d3e27aa7bf0baf4c263236f4663f1d4
652,077
def pretty_warning(msg, *args, **kwargs): """ Monkey patch for warnings.formatwarning """ return str(msg) + '\n'
cf45addb6e5af631edee7745dde962874a0c14df
652,078
def parse_species(species_data): """Iterate over list of species at each site.""" parsed_species_data = [] quality_list = [] for species in species_data: if species["@AirQualityBand"] != "No data": species_dict = {} species_dict["description"] = species["@SpeciesDescripti...
202d373de69c15f7d0521c5b5fac2ac34ed7466a
652,079
def generate_result(guess, solution): """ returns result string for guess if solution is the word being guessed""" unmatched_chars = set() return_string_array = [0, 0, 0, 0, 0] for i, (g, s) in enumerate(zip(guess, solution)): if g == s: return_string_array[i] = 2 else: ...
e1283b7af8359def5224e96628200e1cbb038336
652,080
def get_utt_id(segment): """ Gives utterance IDs in a form like: en_4156-a-36558-37113 """ return "{}-{}-{}-{}".format(segment.filename, segment.channel, int(segment.begin * 100), int(segment.end * 100),)
bfb8507a17e4a35f6daa0df8eebf06141d47f1a0
652,081
import re def GetCipdPackagePath(pkg_yaml_file): """Find CIPD package path in .yaml file. There should one line in .yaml file, e.g.: "package: chrome_internal/third_party/android_sdk/internal/q/add-ons" or "package: chromium/third_party/android_sdk/public/platforms" Args: pkg_yaml_file: The yaml file ...
9a2fcf348b98b7d8d8bc905f28e71d112a8393cf
652,082
import uuid def get_adapter_mac(): """ Returns the MAC address for the current network adapter """ rmac = uuid.getnode() # Check if valid MAC or a fake one before proceeding if (rmac >> 40)%2: mac = "00:00:00:00:00:00" else: # Convert MAC into typical hex notation ...
c240f6aa9ab92febe67097d5a6490929cabd27c9
652,083
def specific_gravity_to_gravity_points(sg, vol_gal): """Convert specific gravity to gravity points Parameters ---------- sg : float Specific gravity. vol_gal : float Wort volume, in gallons. Returns ------- gravity_points : float Gravity points. """ ...
f26ca42921ea44fd35573b93bebb5d5408dec377
652,084
def split_fullname(fullname: bytes): """ Split full backend string name into (namespace, box_id) tuple. >>> split_fullname(b'name.space.box_id') [b'name.space', b'box_id'] """ return fullname.rsplit(b'.', maxsplit=1)
81c274f96d9161cfda446516d7968c50239ebcb1
652,085
def _evaluate_results(results): """ Evaluate resulting assertions. Evaluation is OK if all assertions are true, otherwise it is KO Parameters ---------- results: list(bool) List of all assertion execution results. Returns ------- str 'OK' if all assertions are true, 'K...
331a5a46ec2e0b40197f28ba0a1f00000999077a
652,086
def next_id(schedules): """Return the next available integer (as a string) in the list of schedules keys (do not fills holes) :param schedules: the schedules :type schedules: dict :returns: the ID of the next schedule :rtype: str""" ids = schedules.get('schedules', {}).keys() if not ids: ...
c048b7af90141bb1dc741c0d9eaedf7ed88d1c09
652,087
def routing_min_distance_cost_function(travel_time, travel_distance, current_node_index): """computes the customized section cost for routing (input for routing functions) :param travel_time: travel_time of a section :type travel time: float :param travel_distance: travel_distance of a section :typ...
c02a1a65d641ee4b3314ac624e709a159469d996
652,088
def sec_to_str(sec): """ Return a nice string given a number of seconds, such as 21:53. Takes into account hours, minutes, and seconds. """ s = "" if sec < 0: return "Unknown" hours = sec / 3600 min = (sec % 3600) / 60 sec = sec % 60 if hours: ...
25497dee3fe8e0898f69d0f545133f3f85c7aab0
652,089
def CreateZoneRef(resources, data): """Create zone reference from object with project and zone fields.""" return resources.Parse( None, params={'project': data.project, 'zone': data.zone}, collection='compute.zones')
7a974499626582e98301e8b020a7e0ca248f2532
652,090
def is_ns(seq): """Ns filter If there exists an ambiguous base (N call) then the read is discarded. """ if 'N' in seq: return True else: return False
f2291d35b40a37c7ff838768fee33796a03f45f6
652,091
def cost_of_equity_growth(div, Mv, g): """ Calculates the cost of capital or equity shareholder required rate of return for an investment in which dividend is expected to grow at a constant growth rate (dividend is about to be paid) parameters: ----------- d = dividend per share. Mv = ex-dividend share pri...
6ccc1b8d42e5b6f89dc22a4362eb8d6a10b898b3
652,092
def fibonacci_recursive(nth_nmb: int) -> int: """An recursive approach to find Fibonacci sequence value. YOU MAY NOT MODIFY ANYTHING IN THIS FUNCTION!!""" def fib(_n): return _n if _n <= 1 else fib(_n - 1) + fib(_n - 2) return fib(nth_nmb)
55cd530db0dab8b4bb3049865c70d16d5b9b90aa
652,093
import ipaddress def ip_math_rule(ip_addr, server_host): """ check target ip math server_host rule :param ip_addr: target ip address :param server_host: server_config host rule :return: """ if '/' in server_host: ip_set = ipaddress.IPv4Network(server_host, strict=False) for...
4862a045657996bd1b0313c86057e74db0cf5df2
652,094
def _bfs_neighbor_query(sampling_direction): """ Generate the Cypher neighbor sampling query for a batch of nodes. Args: sampling_direction (String): indicate type of neighbors needed to sample. Direction must be 'in', 'out' or 'both'. Returns: The cypher query that samples the neighbor...
bd0621deea7112ef29f8090ad04da023f69b1d9e
652,096
def formx(v, form=None): """ convert a value into a string with a type of value. """ if isinstance(v, int) and form == "hz": return "{} kHz".format(v) elif isinstance(v, int) and form == "sec": return "{} sec".format(v) elif isinstance(v, int) and form == "pff": if v == 0...
8af8ed5501025862af3dfb6b1f3e41638b526ed5
652,097
def get_ground_truth(reader_study, display_set, question): """Get the ground truth value for the display_set/question combination in reader_study.""" ground_truths = reader_study.statistics["ground_truths"] return ground_truths[display_set][question]
e541eedfab9c46d325ffb328c573961053ef15c5
652,098
import numpy def running_mean_past(x, N): """ Take the running mean of list x, over N past elements.""" # Shift list N elements to the right and take the cumulative sum. cumsum = numpy.cumsum(numpy.insert(x, 0, [x[0] for i in range(N)])) # cumsum[N:] is cumulative sum, shifted N elements to the left. ...
1c3c3e7ee03a8a6913cc9c5047a417884fc080dc
652,099
import six import itertools def _assert_non_empty(iterable): """Assert that next exists and fetch it.""" first_elem = six.next(iterable, None) assert first_elem is not None, first_elem return itertools.chain([first_elem], iterable)
371e2cededc5f5db6928bb871ed091a34b5a6243
652,100
def parse_raw(sql, filePath): """ Read corpora with spark""" df = sql.read.csv( filePath, header=False, mode="DROPMALFORMED" ) return df
d0373fa06d05435fd11838a7d0437dbee354cc87
652,101
def find_columns(num): """Build the table headings for the assignment sections""" return ' '.join([str(i) for i in range(1, num + 1)])
f5f2a35cd91edb3cff5c7b1b3b523e85ebc42e81
652,102
def verify_interval_in_state_vector(statevector, start, finish): """ Verifies if there is at least one non zero entry in a given interval in the state vectors cells, and returns true if positive :param statevector: state vector to be processed :param start: start of the interval ...
31a49b6d3bec7f4cf5eded4197802f1d2ca94304
652,103
import os def create_local_path(file, data_dir): """ Creates local path from file database entry. If subdirectories do not exist, they will be created. The file path will be: data_dir/<5 ctime digits>/<file_type>/<file_name> E.g. /data/pysmurf/15647/tuni...
148a7b50056e3649ccaf3b0fa4731c74421ea152
652,104
def absolute_latencies(relative_latencies): """ Compute absolute delay + stride for a each in a stack of layers. Arguments: ---------- relative_latencies: list of tuples each tuple is (rel_delay, rel_stride) Returns: -------- absolute_latencies: list of tuples each tupl...
f96384586f81b7d47dbe32f608f5f343eee91e13
652,105
import re def replace_line(line_old, line_num, px, step=None): """Replace values in line""" # Get values in string values = re.findall(b'\d+.?\d+', line_old) # Byte string to numbers um_old = int(float(values[0].decode('utf8'))) px_old = int(values[1].decode('utf8')) px_size = px_old/um_o...
c9601e951ff8796d39fd5dad61e2da20e0855d89
652,106
def format_version(value, hero_version=False): """Formats integer to displayable version name""" label = "v{0:03d}".format(value) if not hero_version: return label return "[{}]".format(label)
5b8822b209c643e4891ea1043613fc83645d8006
652,107
import os import glob def infer_read_file_name(baseread, seakread): """ Find other read filenames (ex. R1, R2, R3, R4) in the directory based on Read 1 filename """ basename = os.path.basename(baseread) path = os.path.dirname(os.path.realpath(baseread)) testname = glob.glob(path + '/*' + o...
8afaeca74d3b55ddb5e8d71a1a6ccf8b1defe4b8
652,108
def convertWQElementsStatusToWFStatus(elementsStatusSet): """ Defined Workflow status from its WorkQeuueElement status. :param: elementsStatusSet - dictionary of {request_name: set of all WQE status of this request, ...} :returns: request status Here is the mapping between request status and it GQE...
e1cf9b39b7eb3d4edb2c912cce049d4608dc5168
652,109
def get_file_line_count(filename): """ Get the line count for the specified file """ with open(filename) as f: return sum(1 for _ in f)
85b8d93bed8aa517696abcb910a79c3d2c46b169
652,110
import copy def flatten_dict(data: dict, delimiter: str = "/") -> dict: """ Overview: flatten the dict, see example Arguments: data (:obj:`dict`): Original nested dict delimiter (str): Delimiter of the keys of the new dict Returns: - (:obj:`dict`): Flattened nested dict...
c3109116e6a486af748db787a77c833f6fc3c93b
652,114
import json def pretty_print_json_string(json_string): """ This method takes as input a json string and converts it to a pretty printed json string Return: Pretty formatted JSON string """ parsed_json = json.loads(json_string) return json.dumps(parsed_json, indent=3, sort_keys=Tr...
a0ef1a7f46b4657308f329dd80ff1819e558216b
652,115
def lowpass_filter_trace(tr, filter_order=5, number_of_passes=2): """ Lowpass filter. Args: tr (StationTrace): Stream of data. filter_order (int): Filter order. number_of_passes (int): Number of passes. Returns: StationTrace: Filtered...
dfc654860da13d9aef9f063be7afc0f0d2e70f63
652,116
def Policy_Inputs(UI): """TAKES THE NUMERIC POLICY VALUES AND CONVERTS THEM INTO STRINGS FOR USE IN THE RULES Args: UI: UI class so that relevant attributes can be pulled Returns: policy_input: dictionary of Policy names to their current string values """ PolicyDicts = UI....
dab60df8c937a24bf7db3bf1d81a413253b72633
652,117
def graphFindCycleMultipleRoots(roots, childrenFunction): """Find a cycle in the graph if it exists root - a starting node childrenFunction - a function from node to a list of children returns None, or a list of nodes in a cycle """ not_circular = set() def check(node, above=()): ...
10c947b7301f7930b7eb1cf706f877ac9f2e468f
652,118