content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import numpy import logging def magspec(frames,NFFT): """Compute the magnitude spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). :param frames: the array of frames. Each row is a frame. :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-p...
4eefb368c894e318d9bedbdfe50a031dd41d9c30
639,928
from typing import Generator def render_text(gen: Generator): """YAML renderer""" def totext(doc): """Convert a single document into text""" txt = '# {0}\n### Studente S{1:02d}:_________________________\n{2}\n\n'.format( doc['title'], doc['seed'], doc['description']) for qu...
2199e0d18f75c08f4aef77e58239cfa217f562a0
639,930
from unittest.mock import Mock def get_mock_remote(): """Return a mock remote.""" mock_remote = Mock() async def async_create_remote_control(during_setup=False): return mock_remote.async_create_remote_control = async_create_remote_control return mock_remote
ac19652d0190dbf9a914481849e8e6bd77437247
639,931
def get_daily_mean_voltages(data): """ Get daily average voltage for each channel. Returns positive voltages """ return data.loc[:, data.columns.str.startswith('voltage')].mean().abs()
27d2f9812067346aedc79df0c914113dc3f8b47d
639,932
def _get_baseline_value(baseline, key): """ We need to distinguish between no baseline mode (which should return None as a value), baseline mode with exceeded timeout (which is stored as None, but should return 0). """ if key in baseline: return 0 if baseline[key] is None else baseline[k...
55b34f172cda091705d6d766f45b0cbc445a500a
639,933
def list_tree(connector, base, level=0): """Helper to print a tree.""" result = [] if level == 0: result.append(base) for name, uid in sorted(connector.listCollection(base)): result.append('%s %s' % (uid, connector[uid].type)) if uid.endswith('/'): result.extend(list_...
609284ed8ca847c4235b057c404a256922913951
639,934
import unicodedata def get_unicode_nde_str(string_of_chars): """ Get a unicode normalized string (NFKD). Also the string is decoded (UTF8) and encoded (ASCII). Arguments: :param str: string Return: unicode string """ return unicodedata.normalize('NFKD', string_of_chars.decode...
05f30376154c548f98477c26309f4953b310b764
639,935
import torch def test(network, loss_function, test_set, batch_size_test, device="cpu"): """ Tests a model in a test set using the loss function provided. (Please note that this is not to be used for testing with a compatibility loss function.) Args: network: The model which is undergoing...
e0541ffbf3509d79402e8da203f906b80369f598
639,936
def get_config(self,dst_name=''): """ Gets the current configuration file of the router to current ``result`` folder. Default ``dst_name`` is ``juniper.conf.gz`` """ return self.get_file('/config/juniper.conf.gz',dst_name)
5ab07d46dbc1f71b0dafb4242743430adb80c30b
639,937
def completeCube(hdf, colour, group): # ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ """ Check that a requested cube is all there (data, var, wht). """ if (colour+'_Cube_Data' not in group.keys()) or \ (colour+'_Cube_Variance' not in group.keys()) or \ (colour...
fe40c3b24a74b9072e74b8cc37f49b0264355a77
639,938
def maybe_center(do_center, image): """Possibly center image data from [0,1] -> [-1, 1]. This assumes the image tensor is scaled between [0, 1]. Args: do_center: To do the centering or not. image: [0, 1] Scaled image to be centered. Returns: A possibly centered image. """ if do_center: re...
55887eca3d2e0f6d6e57fe991aeaafef0bc7cac2
639,939
def default_freeze_dataset_task_spec(dtool_config): """Provide default test task_spec for FreezeDatasetTask.""" return { 'dtool_config': dtool_config, 'stored_data': True, }
01bbfeda926f39d870dd6a9d849a1142b71ef2cd
639,940
def strip_hydrogen(atoms, bonds): """ Remove hydrogens from the atom and bond tables. """ atoms = atoms[atoms['element'] != 'H'] bonds = bonds[bonds['start'].isin(atoms['atom']) & bonds['end'].isin(atoms['atom'])] return (atoms, bonds)
0117122d92dc260ac3136603b9af1daa39a36593
639,941
import torch def entropy(probs): """ Computes the entropy of a normalized probability distribution. """ return -(torch.log(probs) * probs).sum(dim=-1)
81f35db846e3b63bd421ed0cfb9c6da6533aa21e
639,942
import tempfile import os import tarfile import hashlib def extractFWimage(path, imageType): """ extracts the bmc image and returns information about the package @param path: the path and file name of the firmware image @param imageType: The type of image the user is trying to flash. H...
724ea6487bf3a62de4dd26a88d4aae743afa4071
639,943
def parse(s): """ Parses an encoded string and outputs it as a dictionary object. """ return {k:v for k, v in (kv.split('=') for kv in s.split(';') if len(kv.split('=')) == 2)}
b315986e3aacd31add2f4d3f5e323d64f9222f8c
639,944
def get_best(algorithm_states, key='return_unp', operation='max'): """Return the best run among several as measured by `key` and the `operation` """ best_id = 0 best_return = 0 for i, s in enumerate(algorithm_states): if max(s['stats'][key]) > best_return: best_return = max(s...
154331ca9ad9c2d61fb3389632492ea8f022e832
639,945
import os import yaml def _load_case_study_definition(self): """ Load data from case study definition file into a Python dict. If users did not provide a definition file as a config argument, the default definition from the WaterTap techno-economic database is used. """ source_file = self.con...
3ba7154202f848ccf07be5ec4b8b21f63a3b01ab
639,946
def construct_address(host, port, route, args): """ {host}:{port}{route}?{'&'.join(args)} :param str host: '172.0.0.1' :param str port: '5000' :param str route: '/store/file/here' :param list[str] args: ['a=b', 'c=d'] """ return f"http://{host}:{port}{route}?{'&'.joi...
27079a2a1430f4a9a855ad0e34b362c9178c17dc
639,947
import math def l2_normalizer(vector): """ fungsi untuk normalisasi L2 terhadap vektor dalam matrix :param vector: :return: """ denom = sum([item**2 for item in vector]) return [(item / math.sqrt(denom)) for item in vector]
9bc0e474cf8fe0611dd922c98907a117e2dfde55
639,948
def create_callback_data(*args): """Crea una stringa a partire dai vlaori (arbitrari) in entrata, che verranno separati da ;""" return ";".join(str(i) for i in args)
dfc6e977af351892c1c5df0234aa897a8b621e77
639,949
import math def make_quant(basis): """ return the quant function, preconfigured with the basis basis starts with a 1, is monotonically increasing, it defines a geometrically extendable range with a ratio of the last/first numbers >>> qE12(1.6) 1.5 >>> qE12(1.6,1) 1.8 >>> qE...
79d2b60ebeb534e5230f1d641096c1453628ef53
639,950
def get_repo_name(url: str) -> str: """ Get the name of the repo. :param url: The URL on which the name of the repo will be retrieved. :return: The name of the repo. """ return url.split('https://github.com/')[1].split('/')[1]
d2f7c14e424b0233b6867ae8311b4177c379b61a
639,951
import errno def retry_when_interrupt(f, *a, **kw): """ Call C{f} with the given arguments, handling C{EINTR} by retrying. @param f: A function to call. @param *a: Positional arguments to pass to C{f}. @param **kw: Keyword arguments to pass to C{f}. @return: Whatever C{f} returns. ...
99b544c07651c2b5c117c6fc9da04c832de51f8f
639,952
def first(the_iterable, condition=lambda x: True): """ Finds first item in iterable that meets condition """ for i in the_iterable: if condition(i): return i return None
bd29454b5f8e12a93613a9e3c2ac899509a59a2d
639,953
def beta_moments(mean, sd): """Calculates the moments of a beta distribution based on mean and sd as they are more intuitive inputs More info on beta: https://en.wikipedia.org/wiki/Beta_distribution Inputs: mean - a float - the chosen mean of the distribution sd - a float ...
0acae4962c5118d368399e03023fc32ca0cebfeb
639,954
import glob import os def get_satfile_list(satdir, date, l_gpm): """ Get a list of satellite files. Parameters: =========== satdir: str Path to satellite data directory. date: str Date, format YYYYMMDD l_gpm: bool Is this GPM or TRMM? Returns: ======== ...
3f904c53a68e8b9a05d80e159bada1ceb7bf7e49
639,955
def squeeze_samples(x): """ Reshape negative samples into the batch dimension """ if len(x.shape) == 5: b, n, c, w, h = x.shape x = x.reshape(b*n, c, w, h) elif len(x.shape) == 3: b, n, h = x.shape x = x.reshape(b*n, h) return x
5145ad01cdac815175041170418ffc431615fd1f
639,956
def find_in_response(resp, query): """ check if HTTP response contains 'to_find' string returns True if found, False otherwise """ return True if query in resp else False
6db2ea14371f5a9ab17aabccd4b83c0539f725f9
639,958
def minMaxMoy(liste): """ définis le minimum le maximum et la moyenne des éléments d'une lise""" min=liste[0] max=liste[0] l=len(liste) somme=0 for i in range(0,l): if liste[i]<min: min=liste[i] if liste[i]>max: max=liste[i] somme=somme+liste[i] ...
0a8961444633f479b1a075968e5a3788e3283a22
639,959
def explode_duplicate_pos(request): """ Setup dataframe for positive testing of explode with duplicates """ return request.param
f2294c7ace13bdce545862e5f434bab9e2d49f78
639,960
def revert_rate_user_revs_query(user, project, args): """ Get revision history for a user """ return []
95444d8a9d24530b87406e355a0bf2cb9126b2b6
639,961
import os import errno def root_check(): """ Simple root gate :return: errno.EACCESS if not running as root, None if running as root """ if os.geteuid() != 0: return errno.EACCES return None
d4291c3fe5affa9b3f5bb108b02bd9b3f61825a0
639,962
def _find_nbv_triangles(animal_obj): """ Returns all triangles in an animal mesh that contain no boundary vertices. Parameters ----------- animal_obj : Animal() object Initialized with regular coordinates and triangulation set/updated. Returns ------- list of triples of floats ...
be2685bd2a52e26d374cc4d56021e7ee5764dce1
639,963
def rst_title(title, symbol="="): """ ===== title ===== """ stroke = symbol * len(title) return "\n".join([stroke, title, stroke])
d8ff3565294f4e0f068fab4345799fbe0e6db0a3
639,964
import math def get_page_number_from_post(post_id:int) -> int: """Calculate the page number of a given post by assuming each game thread page has 30 posts. Args: post_id (int): The ID of the post of interest. Returns: int: The page number of the input post. """ page_number = ...
d9497a8bcbcf6df15208755b66aa8f498cf7b14d
639,966
def get_matrix_diff_coords(indices): """returns coordinates for off diagonal elements""" return [(i,j) for i in indices for j in indices if i != j]
88b86ab2f8ae715540726957ee15d22b026ab344
639,967
from functools import reduce def r(dataset, pFunc, axis=0): """ Reduce over array pFunc is X x Y -> R """ if bool(axis): dataset = dataset.T return reduce(pFunc, dataset)
ab1eea631a8197b59cf068172e754fd6ed7e985c
639,968
import re def searchstr(str_): """Clean up a string for use in searching.""" if not str_: return '' str_ = str_.lower() for pat in [r'\(.*\)$', r'\[.*\]', '{.*}', "- .* -", "'.*'", '".*"', ' (- )?(album|single|ep|official remix(es)?|soundtrack|ost)$', r'[ \(]f(e...
d591657ba2f7711babcc910c079580d118881a66
639,969
def move_curr(df, index, dir): """ move row up or down by one :df: pd.DataFrame :index: str of int :dir: one of ['up', 'down'] """ row_ind = list(df.index).index(int(index)) if (row_ind == 0 and dir == 'up') or (row_ind == len(df)-1 and dir == 'down'): return df if dir == 'up...
e355b4f1d2c6d7edbd491ba02040243df272eb22
639,970
def parse_rawstring(s): """ It parses reference strings contained in some fields. These strings contain references to :class:`genes.molecule` instances, and one of its atoms """ molecule, res_or_atom = s.split('/') molecule = molecule.strip() try: res_or_atom = int(res_or_atom) ...
6872e8930d803100a11e09c600e75a3fddc5e168
639,971
def valid_node_sequence(r1, r2): """ arr.: 150 175 575 600 route: [O]---150--->[A]---25--->[B]---400--->[A']---25--->[B'] tw: [0 ,180) [20 ,200) [300,600) [320,620) e. arr.: 150 100 450 40...
5cf349b06f8ba0b7d9dc9c0b63127b476195c10c
639,972
import re def reFindNext ( v, pos, pattern, bodyFlag, reFlags = None ): """ reFindNext: use re.search() to find pattern in a Leo outline. v the vnode to start the search. pos the position within the body text of v to start the search. pattern the search string bodyFlag true: search body text. false: se...
d9e6bef6aed3a75f6d4b53e7f52868fef9cf1896
639,974
import uuid def get_temp_path(): """ Get a universally unique temporary filename. """ return f'/tmp/distex-{uuid.uuid1().hex}'
ff67c639875767d9e4ea5c2e1046800dc5df4a96
639,975
def _parallel_predict(estimator, X, index): """Private function used to compute (proba-)predictions within a job.""" if hasattr(estimator, 'predict') : predictions = estimator.predict(X) elif hasattr(estimator, 'transform') : predictions = estimator.transform(X) else : ...
0d0bffbfedf4f95d328445cfb37bb845afab2860
639,976
def dice_parser(text): """ A basic dice parser that takes a string of the type: x_1 D y_1 + x_2 D y_2 + .... x_n D y_n and converts it into two lists of dice amount and dice type Parameters: ----- text: string contains the text we want to parse Returns: ----- ...
0d419b8ae994881c1fc1bcf19c9caa64ed9baa86
639,978
def attachEvidence(uuid: str, prim_id: str): """ attach evidence to a primitive""" return "", 415
412e517c7a6419d8104ba556e6f3ffc0cace2781
639,980
from typing import List def station_by_name(station_list: List[dict], station_name: str) -> int: """Returns the current index of a station. The starting point is the name of the station. If no station with this name exists, -1 is returned. """ for index, station in enumerate(station_list): if...
7378fd072a1a1d5d8795f04c585ee88faf03a164
639,981
import json def example_filter(request): """ Filters out reports with a 'document-uri' not from included.com. """ report = json.loads(request.body) doc_uri = report.get('document-uri', '') if doc_uri.startswith('http://included.com'): return True return False
608411887a3328b82d53e476c169047828d0736c
639,982
def locate_basic_impl(xv, x, n): """ This function ... :param xv: :param x: :param n: :return: """ jl = -1 ju = n while ju - jl > 1: jm = (ju + jl) >> 1 if x < xv[jm]: ju = jm else: jl = jm return jl
36ad6a558c556a9366a8a5ec0d587374323c3920
639,983
def is_comma(alist): """ check is a comman exists in a string :param alist: list of strings :return: logical """ for item in alist: if "," in item: return True
776d265a9489b5e7d89a4a7f1de6101f33c325fd
639,984
def getInterfaceByName(cgx,site_id,element_id,name): """ get Interface json object by using the interface name """ res = cgx.get.interfaces(site_id=site_id,element_id=element_id) if not res.cgx_status: print(res.cgx_content) raise ValueError(f"Can't retrieve interface {name}") fo...
5fd030ea1dd7b443b356c020f1711b972ae237f0
639,985
def get_dimensions(corners): """ Get the dimension of a position based on the distance of its corners. This is used to determine the feild of view of a zoom :param corners: list containing 4 points with (x,y) values :return: (x,y) dimension of the position """ x0, y0 = corners[0] x1, y1 ...
68beaaf1931a615205ee0032cbc52d2adae3f72b
639,986
def _int(i, fallback=0): """ int helper """ # pylint: disable=broad-except try: return int(i) except BaseException: return fallback
02cad3260b0c0b8615abb3c17f1d402791c5aff4
639,987
from typing import Any def licenseInfo(): """ licenseInfo() -> Shows information about licenses used by nuke. @return: None """ return Any
9e8f51e436d8cb3b1b35f903972db378862a6fa3
639,988
import torch def tensor2onehot(labels): """Convert label tensor to label onehot tensor. Parameters ---------- labels : torch.LongTensor node labels Returns ------- torch.LongTensor onehot labels tensor """ eye = torch.eye(labels.max() + 1) onehot_mx = eye[la...
dd605d8731eab658e609d94e04716a9221a48357
639,989
def startswith(prefix): """ Create a function that checks if the argument that is passed in starts with string :param str prefix: string to check the start for :return func startswith_function: a function that checks if the argument starts with the specified string """ def string_starts_...
47e0967ce9864743f412070ba1e016f83fe708ed
639,990
def parse_limit(parses): """ parse the limit number :param parses: :return: """ if "limit" in parses.keys(): if type(parses["limit"]) is not int: raise Exception("SQL limit incorrect") else: return " LIMIT " + str(parses["limit"]) return ""
6c30dea5ac1efa29db06859aebd13a19095f18b5
639,991
def _answer(result, line): """Answer the question as best as we can""" msgs = [u"Q: {}".format(result["Input"][1])] del result["Input"] for pod_type in ["Result", "Solution", "Derivative"]: if pod_type in result: msgs.append(u"A: {}".format(result[pod_type][1])) return '...
a41cc92b5e9734dc4f5f116a8e8b4a06b03641a5
639,992
import math def log_activation(x): """ Returns the log of x. """ return math.log(x)
22a00c2e07c58ace7bbe670935ebc0f48aa60a89
639,993
import os def get_output_dir(imgs, config): """Determines the corresponding output directory for an image sequence. The automatically named output directory will be used to store the data generated from an image sequence and is not created if nonexisting. Args: imgs (list): An image sequ...
02b62527b95ff58cba26d4e4fa93e86f57ef8cdd
639,994
def _not(value): """ Usage example: `_not(_equal(...))`. """ if hasattr(value, '__call__'): return lambda v: not value(v) else: return lambda v: not v
ebe3861829f09e78129f40fab7ec85967e14e702
639,995
import math def convtransp_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Utility function for computing output of transposed convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(h_w) is not tuple: h_w = (h_w, h_w) if type(kernel_size) is n...
441576a77f639f22f71a5a54ff4aeb2bd584d7df
639,996
def abitrary_address(): """An unspecific Ethereum address for multiple use cases Meant to be used where ever any address is required but must not fulfill special requirements. """ return "0x5757957701948584cc2A8293857D89b19De44f0F"
db53e2eb30e872f0c0718ceadde2573375f2a8db
639,997
def normalize_whitespace(sent): """Substitutes extra contiguous whitespaces with a single whitespace""" return ' '.join(sent.strip().split())
bd3a44c59aaf53df1fc46e83f626aea51b2b133f
639,998
import io import errno def slow_pi(): """ Returns ``True`` if the local hardware is a Raspberry Pi with a slow processor, specifically a BCM2835. This is used to determine defaults for the simulation's processing. """ try: cpu = '' with io.open('/proc/cpuinfo', 'r') as f: ...
552214871ba6b0c2b241ba207b92fe6eaa2f9c08
639,999
def multiply_two_strs(str1, str2): """assume these two strings are in the form of int, and return the result as int. """ return str(int(str1) * int(str2))
7a7b696ac53a03fef72af52835122e3a03b25b51
640,000
def _size_crop(width, height): """Performs a cropping resize.""" return ("-vf", r"scale=max({height}*(iw/ih)\,{width}):max({width}/(iw/ih)\,{height}),crop={width}:{height}".format(width=width, height=height),)
d14b8db50494c46577b13af596defb0364f2c6cc
640,001
def order_entries(files): """Re-order the file entries, if an order is given.""" order = files.get("order") files = files.get("entries", []) if order: files_ = files.copy() keys = [f["key"] for f in files] def get_file(key): idx = keys.index(key) keys.pop...
5f910875bbe912ba0b8ecfc9e8df74a25e0fa667
640,002
def Firefox(): """PC--Firefox""" Agent = "User-Agent:Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1" return Agent
7a5416fdd61bcce7189d1950ff9e918e1e76ef93
640,003
import multiprocessing def is_forkserver_enabled(): """ Return True if current multiprocessing start method is forkserver. """ return multiprocessing.get_start_method(allow_none=True) == 'forkserver'
4228bd0ce70137a4751b7db4def5d4f91758eca2
640,004
import socket def is_valid_ipv4(ip_str): """ Check the validity of an IPv4 address """ try: socket.inet_pton(socket.AF_INET, ip_str) except AttributeError: try: # Fall-back on legacy API or False socket.inet_aton(ip_str) except (AttributeError, socket.error): ...
1860eb48bca95f48e914ac3e8c8de021f79c74f3
640,006
import sqlite3 from typing import Callable from typing import Optional def sql_binary_search( connection: sqlite3.Connection, table: str, column_value: str, column_index: str, fun_compare: Callable[[float], bool], *, lower_bound: bool = True, ) -> Optional[int]: """ Helper function...
dc800b081c78b8c97b6f9a315ce4ed39ae5ae555
640,008
import re def basedn_to_domain(basedn): """ Convert an LDAP base DN "dc=example,dc=com" into a DNS domain "example.com". """ if not isinstance(basedn, str): raise TypeError("basedn is expected to be a string") basedn = basedn.lower() expr = re.compile(r'^(dc=[a-z0-9-]+)(, *dc=[a-z0-9-...
39db835b764100fa1b3292a3c4a5f983c29492d9
640,010
import torch def iou_score(bboxes_a, bboxes_b): """ bbox_1 : [B*N, 4] = [x1, y1, x2, y2] bbox_2 : [B*N, 4] = [x1, y1, x2, y2] """ tl = torch.max(bboxes_a[:, :2], bboxes_b[:, :2]) br = torch.min(bboxes_a[:, 2:], bboxes_b[:, 2:]) area_a = torch.prod(bboxes_a[:, 2:] - bboxes_a[:, :2],...
38bd6ca64a0cc6721c825c16cbabebc45be53c66
640,011
from bs4 import BeautifulSoup def render_paper_headings(paper_soup): """ Remove dropbox paper styles from the headings and adjust the visual style to improve readability as much as possibile. It defers table formatting to the appropriate module. """ for title in paper_soup.find_al...
593ba272a713d9cce192170d2ed9e0f6e2837d53
640,012
def iou(box_a, box_b, norm): """Apply intersection-over-union overlap between box_a and box_b """ xmin_a = min(box_a[0], box_a[2]) ymin_a = min(box_a[1], box_a[3]) xmax_a = max(box_a[0], box_a[2]) ymax_a = max(box_a[1], box_a[3]) xmin_b = min(box_b[0], box_b[2]) ymin_b = min(box_b[1], b...
e5f4ba0da67f92e732b90183eeba87df34dc33ae
640,013
def getReportPath(job, reportType): """ Return the filename for the error report. Does not include the folder to avoid conflicting with the S3 getSignedUrl method. """ path = 'submission_{}_{}_{}_report.csv'.format(job.submission_id, job.file_type.name, reportType) return path
8fb2b34be8ce615120387bdee48b6855d97d0d60
640,014
def filter_paths(md_files, exclude_dirs): """ Exclude paths presented in exclude_dirs :param md_files: A list of md files :param exclude_dirs: A list of directories to be excluded from processing :return: A list of md files to be process after excluded paths """ return filter(lambda x: not a...
4b1c9ad88ad8939284f9bf9afcca2e78debcf146
640,016
def warmup_lines_to_chop(benchmark, warmup): """Returns the number of lines to be excluded from final measurements. """ # The main benchmark emits its own line. lines_to_chop = warmup # Each of the child benchmarks emit their own line. lines_to_chop += warmup * len(benchmark.children) # hhv...
74b92f52e9279818136cb6dde6e093892592ece5
640,019
def durationString(start, end): """Returns a relative time based on stop-start (duration) time.""" seconds = end-start # first math. seconds = (round(seconds)) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) minutes = (minutes) hours = (hours) days ...
0401b58248fb6b3d5412896d28d23eae0a5a5b52
640,020
def get_build(cloudbuild, image_project, build_id): """Get build object from cloudbuild.""" return cloudbuild.projects().builds().get(projectId=image_project, id=build_id).execute()
937e4977a1c1cba1527b20b53cd0f8829ef5e939
640,021
def get_fabric_ip_networks(cfmclient, fabric_uuid=None): """ Get a list of IP networks from the Composable Fabric. :param cfmclient: :param fabric_uuid: UUID of fabric :return: list of IP address dict objects :rtype: list """ path = 'v1/fabric_ip_networks' if fabric_uuid: pat...
7e9e5cbc5da247e8048c57a2aef18e887090a9c4
640,022
def num_odd(n, m, indices): """returns the number of odds after indices flips""" # initialize variables row, col = [False] * n, [False] * m # iterate through indices for r, c in indices: row[r] ^= True col[c] ^= True return sum(rows ^ colm for rows in row for colm in col)
021104aeea22e0f4044b78eb2cbcc15666674ec9
640,023
def readmsa(alnfile): """ Read alignment file """ nvars = 0 # number of transcript variants alnresult = [] # read file with open(alnfile, 'r') as f: for row, line in enumerate(f): if line[:7] == 'CLUSTAL': # skip the first row pass elif line == '...
3820e734e1768ac24c5231e940a42ef6269531cc
640,024
import base64 def np_to_json(obj, prefix_name=""): """Serialize numpy.ndarray obj :param prefix_name: unique name for this array. :param obj: numpy.ndarray""" return {"{}_frame".format(prefix_name): base64.b64encode(obj.tostring()).decode("utf-8"), "{}_dtype".format(prefix_name): obj.dtype...
f9de47cf1c52df52808e9c8a39262478f1ddcf1b
640,025
from pathlib import Path from typing import Callable import logging def get_data(cache_path: Path, function: Callable, argument: str) -> bytes: """ Get some data from the cache if cache file exists, otherwise get it using function and store it to the cache. """ if cache_path.exists(): with...
19261430b6b3683076ca4c0f0bac365f9523fedc
640,026
def label_gen(index): """Generates label set for individual gaussian index = index of peak location output string format: 'a' + index + "_" + parameter""" # generates unique parameter strings based on index of peak pref = str(int(index)) comb = 'a' + pref + '_' cent = 'center' sig = ...
dba6b35777ec3d1c4db16498b0dfc7dd8c6ebaa7
640,027
def get_changed_rows(origin: list, modified: list): """ Get a slice of changed rows for first to last one """ if len(modified) > len(origin): ext_origin = origin + [' '] * (len(modified) - len(origin)) else: ext_origin = origin changed_offsets = list( offset for offset, (...
d46aadd2d0ce06dd20965ea6f447f5511a932b2a
640,028
from datetime import datetime def attributes_dict_example(): """ Retuns a example dict with some different attributes :return: dict with attributes :rtype: dict """ attributes = dict() attributes.update({"ex:individual attribute": "Some value"}) attributes.update({"ex:int value": 99})...
dc07394690d3ce26792e0d388026cf70d5f4441e
640,029
def deg_min_sec(degrees = 0.0): """Format RA Decl output from astropy to CASA style Author: Jeremy Smith """ if type(degrees) != 'float': try: degrees = float(degrees) except: print(f'\nERROR: Could not convert {type(degrees)} to float.') return 0 ...
46cba43ea31b815341d07218ea680c3da79c78f6
640,030
def check_comparison(function, within_column_clause, returns_boolean, compare_value): """Because Oracle and MS SQL do not want to know Boolean and functions return 0/1 or the string 'TRUE', we manually have to add a comparison, but only if the function is called inside the where-clause, not in the select c...
32e92a40584c4c282b6689afaa2f275b5e1b0d82
640,031
def max_level_test_input_data(): """ input data to test json_normalize with max_level param """ return [ { "CreatedBy": {"Name": "User001"}, "Lookup": { "TextField": "Some text", "UserField": {"Id": "ID001", "Name": "Name001"}, ...
3423d779d202624ee641f2c5b02fa5627f2330bd
640,032
def set_arg(obj, arg): """ Pass an argument """ if not hasattr(obj, '__call_arguments'): obj.__call_arguments = [] obj.__call_arguments += [arg] return obj
c9466a1a9f27337cbac47cf22b4522dce3ec2870
640,033
import socket def get_default_ip(): """ Return the first IP address of the current machine if available. """ available_ips = list( set( [ i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None) if i[4][0] not in ("127.0.0.1", "::1") ...
865acd24f4a268dceae8d2abb6ff1e09a0f723e7
640,034
import time def start_timing(): """ This closure function calculates the elapsed time in seconds since its initialization each time it is invoked. Example # Initialize elapsed_time = start_timing() time.sleep(1) # Get elapsed time et = elapsed_time() """...
e836c52effe25ff3d27082a56cb3cac7c31090aa
640,035
import os def cvs2vectors_command(mallet, vectors, output=False): """The command for creating a binary vector file from a text vector file. Each line in vectors looks like "ID LABEL FEAT1 FEAT2...".""" # I am not sure what token-regex does since I thought it was only important # for creating vectors s...
c5c0a2b8d39adc11b44df9932f814cf12f01efaa
640,036
from typing import List def compute_forgetfulness(correctness_trend: List[float]) -> int: """ Given a epoch-wise trend of train predictions, compute frequency with which an example is forgotten, i.e. predicted incorrectly _after_ being predicted correctly. Based on: https://arxiv.org/abs/1812.05159 """ if...
b9a591350bcfabefef0593a744d39d47e5828113
640,037
import heapq def generate_negatives_from_same_time(related_words, num_of_words, year, models_manager, distance_metric, affected_words=None): """ find the words that changed the least during the given year """ before_year = year - 1 after_year = year + 1 if...
2e5841682a2abb26441212eec4a44169b1bbdb94
640,038
import cmath import math def op_tan(x): """Returns the tangent of this mathematical object.""" if isinstance(x, list): return [op_tan(a) for a in x] elif isinstance(x, complex): return cmath.tan(x) else: return math.tan(x)
e2acd28cce9de4c58bb446addf81d7cab4ebae17
640,040