content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def compute_gaussian_kl(z_mean, z_logvar): """Compute KL divergence between input Gaussian and Standard Normal.""" return 0.5 * torch.mean( torch.square(z_mean) + torch.exp(z_logvar) - z_logvar - 1, [0])
41cda8f84c7bf74a86c398ee38f5e65195e6b2fb
611,851
def startswith(value: str, arg: str): """ Check if a value starts with some string """ return value.startswith(arg)
c1e10dff11ed678261bdd80ad0c7e320c0a1d741
611,859
def omp_get_place_num_procs(place_num : int): """ The omp_get_place_num_procs routine returns the number of processors available to the execution environment in the specified place. Parameters ---------- place_num : int """ return 1
0000575714d0a2cfb6d02c05ee169b3f4da14b2e
611,860
import string import itertools def standardize_col(col: str) -> str: """Standardize a column for Snowflake table. (1) Replaces spaces with underscores, trims leading & trailing underscores, forces upper-case (2) Replaces special characters with underscores (3) Reduces repeated special charact...
78a84d8d6951d7fe58645e32e34ec69ea3aeac64
611,863
def get_common_xs(entries): """Return a mask of where there are Xs in all routing table entries. For example ``01XX`` and ``XX1X`` have common Xs in the LSB only, for this input this method would return ``0b0001``:: >>> from rig.routing_table import RoutingTableEntry >>> entries = [ ...
f60e8c4dd0cf5b6b719115f72228f0d91e5c65c0
611,864
from typing import List def depth_items(list_: List, d: int) -> int: """ Return the number of elements of <list_> that are at depth <d>. Precondition: Cannot have depth of 0 (i.e. d = 0) >>> depth_items([1, [2, [3]]], 2) 2 >>> depth_items([1, [2, 3, 4, 5, 6, [3, 4, 5]]], 2) 6 >>>...
422a9df060c9bd6a80d0ebd7544598235524cf69
611,865
def hept_pyramid(s: int, n: int) -> int: """Make a pyramid with a polygonal shaped base. Args: s: polygonal shape n: height/side length of the pyramid Returns: int: number of canon balls needed to make the pyramid """ pyramid = (3 * n ** 2 + n ** 3 * (s - 2) - n * (s - 5)) ...
bbc361fc87f4e17e0b612bc5a9a3521668c38c81
611,866
def _stats_data_to_summary(stats_data): """Converts StatsMinute/StatsHour/StatsDay into a dict.""" return (i.to_dict() for i in stats_data)
9574a35da44b23a821f838218b1355c6a138d7e4
611,868
def target_event(event_type, payload=None): """Creates Target event :param event_type: (str) Event type, required :param payload: (dict) Event payload, optional """ event = {} if not payload: payload = {} event["type"] = event_type for key in payload.keys(): event[key] = ...
3ea484b73509e32b393fb136d463f19fb20c165e
611,873
import datetime def subtract_one_month(t): """Return a `datetime.date` or `datetime.datetime` (as given) that is one month later. Note that the resultant day of the month might change if the following month has fewer days: >>> subtract_one_month(datetime.date(2010, 3, 31)) datetime.d...
78afcf1197b5779731c71a7141034b671f76cbd9
611,876
import math def compute_sigma_psi(xi, Q, r=math.sqrt(0.5)): """ Computes the frequential width sigma for a Morlet filter of frequency xi belonging to a family with Q wavelets. The frequential width is adapted so that the intersection of the frequency responses of the next filter occurs at a r-ban...
42074fcbcff8a0721f461244c5dd751884e4e0fb
611,882
def create_mask(im,head): """ Create the mask using the image and the saturation level set in the header """ # Create the mask # mask=1 bad # mask=0 good try: saturate = head['saturate'] except: saturate = 60000.0 mask = im > 0.9*saturate return mask
20490098c4ed8f3ad038ab132169d821424b3262
611,884
import torch def rotation_matrix(angle): """Gets a transformation matrix for 2D rotation.""" angle = torch.as_tensor(angle).to(torch.float32) mat = torch.eye(3, device=angle.device) mat[0, 0] = angle.cos() mat[0, 1] = angle.sin() mat[1, 0] = -angle.sin() mat[1, 1] = angle.cos() return ...
d5884e835d3ccd773f0989284ba612e9c36ea4b7
611,887
import pathlib def missing_options_file(tmpdir, request): """Return a path to an config file that is valid, but missing expected options (commented out below). Remove the file when a test is finished with it. """ data_dir = pathlib.Path(str(tmpdir)) missing_options_file = data_dir.joinpath...
c2896e6e4f4997cb2ee94270acf634ad559550b2
611,892
from typing import Optional from pathlib import Path import tempfile def mktmp( prefix: Optional[str] = None, suffix: Optional[str] = None, separator: str = "-", dir: Optional[Path] = None, ) -> Path: """ Makes a temp file. A wrapper for `tempfile.mkstemp`. """ if prefix is not None: ...
8bc1cb9448b497073defc7890fa85f3c0532e00c
611,894
def settings_root(likelihood_name, prior_name, ndim, **kwargs): """ Returns a standard string containing information about settings. Parameters ---------- likelihood_name: str prior_name: str ndim: int prior_scale: float or int dynamic_goal: float, int or None nlive_const: int ...
8ca7d16eeebac5885227132028a078e706e584e7
611,895
def reverse_words_in_string(text): """Reverse the words in a string.""" reversed_words = reversed([word for word in text.split('.')]) return '.'.join(reversed_words)
fe2c6ec1a251987a4bf8f54ca4808cfe6aa3a404
611,898
def detect_outlier_channels(data_frame_with_relative_ranges): """ Detects outliers for relative weight ranges. :param data_frame_with_relative_ranges: pandas data frame with column name "relative ranges" :return: list of output channels that have very large weight ranges """ Q1 = data_frame_with...
1729180d12be8972e65aac90c62cf87e9478b60d
611,899
from typing import Any import re def can_be_parsed_as_float(value: Any) -> bool: """Checks whether a value can be parsed as a float. can_be_parsed_as_float(45) -> False can_be_parsed_as_float(1.1) -> True can_be_parsed_as_float("1.1") -> True can_be_parsed_as_float("-1.1") -> True can_be_pars...
3a9d95962a7cb17c447a5d8a60b1d9d92983b9ab
611,900
def is_test_file_name(file_name): """ Returns whether the given file name is the name of a test file. Parameters ---------- file_name : `str` A file's name. Returns ------- is_test_file_name : `bool` """ if file_name == 'test.py': return True if...
775cfe393deaf439f17b304b4aa0652d43d2a4b9
611,903
def _get_lock_speed(postgame, de_data): """Get lock speed flag.""" if de_data is not None: return de_data.lock_speed if postgame is not None: return postgame.lock_speed return None
629cff33d180ef777d793bc2be2f9a3e7877481d
611,904
def infer_task_type(df): """ Infer the likely fine-tuning task type from the data """ CLASSIFICATION_THRESHOLD = 3 # min_average instances of each class if sum(df.prompt.str.len()) == 0: return "open-ended generation" if len(df.completion.unique()) < len(df) / CLASSIFICATION_THRESHOLD:...
6352922b8d21623a2658fa8423137e385e0546d3
611,905
def GetText(node): """Dig out node text Args: node: DOM node Returns: text: stripped concatenation of all TEXT_NODEs """ if not node: return None text = [] for child in node.childNodes: if child.nodeType == child.TEXT_NODE: text.append(child.data) elif child.nodeType == child...
b0069c8920ddaef0cffe7d9abaea879829f3af5b
611,907
import json def load_umi_template_objects(filename): """Reads Args: filename (str): path of template file Returns: dict: Dict of umi_objects """ with open(filename) as f: umi_objects = json.load(f) return umi_objects
bd7d3abcaf0f2fd88bcf90d49d5a31052a743e31
611,913
def get_totals_across_years(df, tract_col, data_col): """Get the sum and average of a datapoint across all years for a given geography. Parameters ---------- df : pandas df Dataframe where each row contains a datapoint by year by geography, e.g. columns = ['year', 'tract', 'num_evictio...
2ce857e1a83b9f980cc3c2b6dc9379a7ee852fff
611,915
def extract_media_url(media): """extracts the url of a media item: an image post, or an image within a gallary I extract the data from the first items in "display_resources" instead of the standard "display_url" because this is the lowest resolution available """ return media["display_resources"][0...
90cd87eaf398f362df3e359dcf94e9a9e9a0313c
611,919
def TestCaseToName(test_case): """Converts a python.unittest to its gsutil test-callable name.""" return (str(test_case.__class__).split('\'')[1] + '.' + test_case._testMethodName)
b7f1e11ca62b865a82cc936c398081806370e6d4
611,920
def bin_retweet_count(retweets: float) -> str: """Fcn to bin retweet counts via if-else statements, rather than cut() function, to compare performance of computation in Class 5. Arguments: - retweets: number of retweets in millions Returns: - categorical variable groupin...
c438f16c2e56486a4d093da69b03cf5989019389
611,923
import calendar def ndays(year: int, month: int) -> int: """Wrapper around calendar.monthrange that returns only the days in the specified yearmonth. Args: year (int): The year month (int): The month Returns: int: The n days in the year-month """ _, ndays = calendar.monthra...
4c63fbafa79f54bde5fd57de52e2984c0343a4e4
611,925
def split_params(params): """Splits a parameter vector for a batch of gabors into individual parameter vectors.""" n_samples = params.shape[0]//7 x = params[:n_samples].astype('float32') y = params[n_samples:2*n_samples].astype('float32') theta = params[2*n_samples:3*n_samples].astype('float32')...
f22e8b6527f8b27006b1426df0e2de8ab0755de2
611,927
def filter_nan_str(x): """Filter 'nan' values as string from a list of strings""" if not isinstance(x, list): return x else: return [y for y in x if y.lower() != 'nan']
15da13a1356092d145d5893fa35ac8d0a679eff0
611,929
import torch def mu_law_decode(encoded, bits=8): """ Perform inverse mu-law transformation. """ mu = 2**bits - 1 # Invert the quantization x = (encoded / mu) * 2 - 1 # Invert the mu-law transformation x = torch.sign(x) * ((1 + mu)**(torch.abs(x)) - 1) / mu return x
8ec1e646df0454ca7891c68ecac1f47bb0529615
611,932
def make_adder(n): """ usage: Add2=make_adder(2) Add2(3) -> 5 """ return lambda x,n=n: x+n
ee1f9dfe76ee798299444e3090ebddb974f5e2ea
611,934
from typing import List from pathlib import Path def read_test_files(files: List[str]) -> List[str]: """Read the given files which contain a list of tests (removing comments) and return a list of test names.""" tests = [] for path in files: path = Path(path) try: with path...
b46e3cacc80d5d86a33072307726fd83b31efbc2
611,938
def dragon_encode(input_data) -> str: """ Takes an initial state (the input_data) and then applies these transformations: - Call the data you have at this point "a". - Make a copy of "a"; call this copy "b". - Reverse the order of the characters in "b". - In "b", replace all instances of 0 with ...
3c9d2fcc3e17a9f9198129fcbc9307dbd1732dd0
611,944
def pixelsize(info_dict): """ Computes the pixel size in m/pixel Parameters ----------- info_dict: dictionnary Returns ------- pixelsize: float size of the pixel in meter/pixel """ # Pixel length (m/pix) pixsize = info_dict['cameras'][info_dict['channel']]['Photo...
c73f81152a48e8d9211d558b60453ef0bd37f639
611,946
import math def Range(value, max_value): """Constrains value to [-max_value, max_value] range""" if abs(value) > max_value: value = math.copysign(max_value, value) return value
6b248ca65882e52b799f30a26cf5d9c8a1acf4de
611,947
def get_text_as_string(self) -> str: """ Returns the entire text of the editor as a single string. Linebreak characters are used to differentiate between lines. :param self: Texteditor-Class :return: String """ return "\n".join(self.line_string_list)
ce4c9a3d627c56bffa52f5ec6715c6ea2f88aa9f
611,949
def partition(lst, n): """ Slices a list into n nearly-equal-length-partitions """ division = len(lst) / float(n) return [lst[int(round(division * i)): int(round(division * (i + 1)))] for i in range(n)]
0edaad717e9ff393542cf5a9b905c4eb104be76d
611,952
import re def remove_spaces(s): """Remove spaces around punctuation""" s = re.sub(r'\s+([.,;?])', r'\1', s) return s
3026b7f22ff1e67fb5a54d426e4bd9307c9652be
611,955
def is_swap(score0, score1): """Returns whether one of the scores is double the other.""" # BEGIN PROBLEM 5 "*** REPLACE THIS LINE ***" if (min(score0,score1)*2)==max(score0,score1): return True else: return False # END PROBLEM 5
452155b70ebb0d201420497f73e98f0263a0ef26
611,956
def eval_guess(chosen, guess): """Check if the number guessed by the user is the same as the number chosen by the program. Parameters: chosen (int>=0): Number chosen by the program. guess (int>=0): Number guessed by the user. Returns: (str): Hint to help the user in the next gues...
0e78ea9a06d89962d31cf3987fdb658d30bc79be
611,957
from typing import Set def get_authors_by_keyword(keyword: str, graph=None, authors=None) -> Set[str]: """Get authors for whom the search term is a substring. :param pybel.BELGraph graph: A BEL graph :param keyword: The keyword to search the author strings for :param set[str] authors: An optional set...
380d91cba6ed020266bc316bb3a1415f8f47dd29
611,959
from typing import Union import difflib def find_similar_word(word : str, template_word : Union[list,set]) -> str : """ Find similar word in template_word using difflib Return the most similar word if there are no close matches return word. """ tmp = difflib.get_close_matches(word, template_word) ...
2d0e449c2fd6027ab87afe742e8a5e91a972634e
611,960
def anytype(val=None): """any value""" return val
e9c14278c5edf4d6414b4609c56b2c8676ef43df
611,963
def _underlying_variable_ref(t): """Find the underlying variable ref. Traverses through Identity, ReadVariableOp, and Enter ops. Stops when op type has Variable or VarHandle in name. Args: t: a Tensor Returns: a Tensor that is a variable ref, or None on error. """ while t.op.type in ["Identity"...
c2d48b61e7236d1b28f0f905fd3d32429dcb1776
611,964
def max_value(tab): """ Brief : computes the maximum value Args : tab : a list of numeric value Return : the maximum value of a table Raises : Value error if input tab is ot a list Value error if input list is empty """ if not (isinstance(tab, list)):#on ...
b3becce6da594f5c07ea42439c9a40e02ac4cce0
611,967
from datetime import datetime def get_today_date() -> str: """Return a string representing today's date suitable in documentation.""" # fmt: off month_mapping = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "...
44a16b7de1a52d4832e796c8c70a8bf0e775c485
611,969
import re def _label_parser(note_list): """Converter function for manipulating the internal "included" and "notes" columns. Parameters ---------- note_list: list A list of notes, coming from the Dataframe's "notes" column. Returns ------- asreview_new_notes: list A list o...
90c83a2285446ac45a6223664cef42048db9952a
611,970
from numbers import Number def _is_number(x): """ True if x is numeric i.e. int or float """ return isinstance(x, Number)
d76a946c45d3faeb5659ec3b2de512f03c0a5f4a
611,976
def write_encrypted_file(filename, encrypted_data): """ Write an encrypted bytestring to file """ filename = filename + '.enc' with open(filename, "wb") as file: file.write(encrypted_data) return filename
5035ec0c249a949f959eea593f22d0f8a09a1e87
611,981
import re def strtr(s: str, repl: dict) -> str: """Replace substrings in 's' matching 'repl' keys with corresponging values """ pattern = '|'.join(map(re.escape, sorted(repl, key=len, reverse=True))) if repl: return re.sub(pattern, lambda m: repl[m.group()], s) else: return s
dbf8b647d618cc4d2f7387e16d09680368eb886c
611,987
import re def uncolour(text): """ Remove ANSI color/style sequences from a string. The set of all possible ANSI sequences is large, so does not try to strip every possible one. But does strip some outliers by other ANSI colorizers in the wild. Those include `\x1b[K` (aka EL or erase to end of line...
7bebb21708c6af0943e3c925efe0345a69dc6928
611,990
def saveResult(timer, currentAttribute, totalAttribute, currentResult): """ Save the current result in currentAttribute and append to totalAttribute Parameters ---------- timer : Timer instance Pointer to the common timer instance currentAttribute : Array-like Attribute fo...
ed9ba79b0cd04f500b679cda07981e1339f28fcf
611,993
def parse_composed_of(value): """Parse composed_of option.""" if value is None: return [] return [x.strip() for x in value.split()]
df87125db898e87b8a1f833c4eccea7474a67065
611,995
def _CalculateNumElement(mol, AtomicNumber=6): """ **Internal used only** Calculation of specific type of atom number in a molecule Calculation of element counts with atomic number equal to n in a molecule :param mol: molecular :type mol: rdkit.Chem.rdchem.Mol :param AtomicNumber: ...
f21ce64f6d0b7c7997f65c3e1359bf4b5f70d0ea
611,999
import typing def is_generic_tuple(tp): """Returns true if `tp` is a parameterized typing.Tuple value.""" return tp not in (tuple, typing.Tuple) and getattr(tp, "__origin__", None) in ( tuple, typing.Tuple, )
ba3e0a4b31286c681a06b94bfaccb33b2432c889
612,000
def count_failed_students(student_scores): """Count the number of failing students out of the group provided. :param student_scores: list - containing int student scores. :return: int - count of student scores at or below 40. """ non_passing = 0 for score in student_scores: if score <=...
a88e3918e3dd81ebaaeb2184f5cbaf291f00a42e
612,002
def csv_path(name): """ Shortcut function to get the relative path to the directory which contains the CSV data. """ return "./data/%s" % name
63618fdab0ee1dbe411007ad20aaad8a8649a0c3
612,004
def find_argument(inp): """ Find the start of the Arguments list. """ line = next(inp) count = 1 while 'Arguments' not in line: line = next(inp) # We assume we're going to find this within two lines of the original # location of the input # - stop looking if we ...
d789843de75db8b449437d9579b8a21f72427326
612,006
def key_path(key_pair): """ Return the hexadecimal key path from a key pair using the public key. Arguments: - `key_pair`: A :class:`libnacl.public.SecretKey` instance. """ return key_pair.hex_pk().decode()
3f9e6f53120b254781564d98a80e0d8d59facf58
612,007
import re def angle_udf(angle): """Converts DMS notation to degrees. Return None if not in DMS or degrees notation.""" if not angle: return None dms = re.match(r'(-?\d*).(-?\d*)\'(-?\d*)"', angle) if dms: return int(dms[1]) + int(dms[2]) / 60 + int(dms[3]) / (60 * 60) degrees = r...
857934299ff9b936b6ca19c54aa2f1a001ccca53
612,010
def decode(s): """ Replace null bytes in a string """ return s.replace('\x00', '').replace('\0', '').replace('\000', '')
0bf01e4e50d5f320cfd506438640ba438e37abf3
612,012
def get_last_aws_update(event_details): """ Takes as input the event_details and returns the last update from AWS (instead of the entire timeline) :param event_details: Detailed information about a specific AWS health event. :type event_details: dict :return: the last update message from AWS :r...
b047cb2019847f511764c7539382250152f39dd8
612,013
import dateutil.parser as dp def convert_date_time_epoch(datetime:str) -> int: """Convert Datetime into epoch""" parsed_t = dp.parse(datetime) t_in_seconds = parsed_t.timestamp() return int(t_in_seconds)
0d8ffdaa8ef182016709c036d5ab0e12228e4b97
612,020
def _remapLanguageCode(code): """ Remap certain language codes to others, per the localization team """ if code == "zh-Hans": # Simplified Chinese code = "zh_CN" elif code == "zh-Hant": # Traditional Chinese code = "zh_TW" return code
9d3184aae0f6902d4b129a1eee07c46a8c13e562
612,023
def _xml_get(e, name): """ Returns the value of the subnode "name" of element e. Returns None if the subnode doesn't exist """ r = e.find(name) if r is not None: return r.text return None
3fd3a27ad5cfa3bb58645bc58d9c78530e021a4c
612,025
import torch def latin_hypercube(n_pts, dim, dtype=None, device=None): """Latin hypercube with center perturbation.""" X = torch.zeros(n_pts, dim, dtype=dtype, device=device) centers = (1.0 + 2.0 * torch.arange(0.0, n_pts, dtype=dtype, device=device)) / float(2 * n_pts) for i in range(dim): # Shuffle...
036c4c6585ed10e09390a49fb765e0332987c9b8
612,028
def get_report_prompts(connection, report_id, closed=None, fields=None): """Get the collection of prompts and their respective definitions from a report. Args: connection: MicroStrategy REST API connection object. report_id (str): Unique ID of the report you wish to extract info...
4fb143cd82b056a412decef6015c8ec3044e7986
612,030
import random def randChar() -> str: """Generates a random character from the alphabet. Takes no parameters. Returns --------- A string of length one containing a letter """ letters = 'abcdefghijklmnopqrstuvwxyz' return random.choice(letters)
e9f31521424cce68b9725040dbb963ca10714da9
612,035
def distance_xy(point1, point2): """ This function takes 4 arguments representing 2 points in cartesian coordinates and returns the Euclidean distance between the points: d(point1, point2) = sqrt((point1_x - point2_x)^2 + (point1_y - point2_y)^2) : param point1 : pair of values representing hori...
378a972215cdb5cb2c4db213a443a50f719d66b5
612,036
def get_total_ticket_comments(ticket): """ Return the total number of comments for the given ticket """ total_comments = 0 for comment in ticket.comments.all(): total_comments += comment.count() return total_comments
1ccde8209775fc31e722f150349fdd5e8d594254
612,040
def attribute_match(one, two): """Find a matching attribute in two Features.""" tags = { "proteinId", "protein_id", "transcriptId", "transcript_id", "name", "Name", "ID", "locus_tag", "Parent", "protein_source_id", } common ...
14c169536a2388fa400d282e118ea782d630a1b6
612,041
from typing import List def mysql_dump_command( url: str, port: int, username: str, password: str, database: str, tables: List[str] = [], ) -> List[str]: """ Generate a command to dump a database. The resulting command can be used by subprocess.call() with the stdout attribute set to a file object...
9f347fed24a048601d3e94d7e3198b520f70c957
612,043
def toindex(col, row): """ Calculates the index number from the Excel column name. Examples: >>> from sphinxcontrib import exceltable >>> exceltable.toindex('A', 1) (0, 0) >>> exceltable.toindex('B', 10) (1, 9) >>> exceltable.toindex('Z', 2) (25, 1) >>> exceltable.toindex('AA', 27...
ddc81fefd3259276900e7e9831a6270b63eb1af6
612,050
import re from datetime import datetime def parse_ref_date(line): """ This function parses ref_date string format into date time format. :param line: line containing reference date :type line: str :returns: reference date in date time format. """ if re.match(r'Ref_date:(.*)', line, re...
ba43ac5371f5323572797610c606e4e5710eacf6
612,051
def no_duplicates(passphrase): """Checks if passphrase doesn't contain duplicated words.""" return len(passphrase) == len(set(passphrase))
e11485d5181dcb7938860af59106a3858444cf85
612,053
def parse_entry(entry): """ Parse entry value and return int, float, str, or bool. Return None if the value is '='. """ if entry[0] == '=': return None if entry[0].isdigit(): # int or float if '.' in entry or 'e' in entry: # float return float(entry) else: ...
151f89d7276df5ced51f97185dd0e871d140db04
612,054
def generate_tclloader_platother(platform): """ Generate platform-specific other files. :param platform: Platform type (i.e. subdirectory of target/product). :type platform: str """ if platform in ("bbry_sdm660", "bbry_sdm636"): others = ["dspso.bin", "BTFM.bin", "abl.elf"] elif pla...
05872118448e1cb42e3a4c7029ef8e1994df9a5e
612,056
def get_uri(raw): """ Extract URI of edition. @param raw: json object of a Libris edition @type raw: dictionary """ return raw["@id"].split("/")[-1]
1304cb9a3ab053ebbcb669848b9d257e8ba97c00
612,061
def zipsame(*seqs): """ Performes a zip function, but asserts that all zipped elements are of the same size :param seqs: a list of arrays that are zipped together :return: the zipped arguments """ length = len(seqs[0]) assert all(len(seq) == length for seq in seqs[1:]) return zip(*seqs)
fbbcb1d2ed1a8038dc77ee6702d12810a10853c8
612,067
import torch def _flip_path(path, path_lens): """Flips label sequence. This function rotates a label sequence and flips it. ``path[b, t]`` stores a label at time ``t`` in ``b``-th batch. The rotated matrix ``r`` is defined as ``r[b, t] = path[b, t + path_lens[b]]`` .. :: a b c d . ....
61e6c815da3b917562f6054ab2f0fce1af37b0e3
612,069
def getlenDict(data, keys=None): """Get len of a dict of lists""" l = 0 if keys == None: keys = data.keys() for i in keys: l += len(data[i]) return l
369b8a32b59cbbfc60df512279c8758224a08fab
612,073
def server_error(exception): # pylint: disable=unused-argument """Internal Server Error :return: "Server error" """ return "Server error"
f2fcd433e54c1cddef853a8588e3e92c416984b1
612,074
import hashlib def fingerprint_from_raw_ssh_pub_key(key): """Encode a raw SSH key (string of bytes, as from `str(paramiko.AgentKey)`) to a fingerprint in the typical '54:c7:4c:93:cf:ff:e3:32:68:bc:89:6e:5e:22:b5:9c' form. """ fp_plain = hashlib.md5(key).hexdigest() return ':'.join(a+b for a,b ...
3501e8085c929cfecbd7e1419ea8b550d367f52f
612,077
def txt_to_string(text_file_path): """Read text file as string""" f = open(text_file_path, 'r') txt_string = '' while True: single_line = f.readline() if single_line == '': break txt_string += single_line f.close() return txt_string
a3ecc61f9e03b534f36c9ac4138470b66cd8388a
612,082
def get_agent_deployment_script (api, configuration, api_version, api_exception, platform, dsm_proxy_id = None, validate_certificate = None, activate = None, computer_group_id = None, policy_id = None, relay_id = None, relay_proxy_id = None): """ Obtains an agent deployment script from Deep Security Manager accordi...
014a41ae97b9d4f19a75202b467df506a35fe30a
612,085
import random def rand_string(min, max) -> str: """Returns a randomly-generated string, of a random length. Args: min (int): Minimum string length to return, inclusive max (int): Maximum string length to return, inclusive """ int_gen = random.randint string_length = int_gen(min,...
9635c92e7937ce8bc2f0bc2f369f6fca160e563e
612,086
import hashlib import binascii def verify_password(stored_password, provided_password): """Verify a stored password against one provided by user""" salt = stored_password[:64] stored_password = stored_password[64:] pwdhash = hashlib.pbkdf2_hmac('sha512', provided_password.encode('u...
c355fcee3e9934bf7ad3b996c9e96f668e9a3679
612,088
def process_gpus_total_for_job(job): """Calculate the total number of GPUs needed by a job.""" if job.tres_per_node: return job.tres_per_node["gpu"] * job.nodes if job.tres_per_task: return job.tres_per_task["gpu"] * job.tasks if job.tres_per_job: return job.tres_per_job["gpu"] ...
19c7959b6061143abac216fb047370e240ad3eec
612,089
def get_unique_in_order(iterable): """ Get unique elements in order or appearance in iterable. :param iterable: iterable; :return: list; """ unique_in_order = [] for x in iterable: if x not in unique_in_order: unique_in_order.append(x) return unique_in_order
69f2396dc3e2b677040fd6dc3f16871cbea391b8
612,091
def gyroWordToFloat(word): """Converts the 16-bit 2s-complement ADC word into appropriate float. Division scaling assumes +-250deg/s full-scale range. Args: word - 16-bit 2's-complement ADC word. Return: float """ if word & 0x8000: return float((word ^ 0xffff) +...
b88003473dd8cb0e28cc1d9aa0c006cfd90f7e68
612,092
from typing import Tuple def check_bounds( point: Tuple[float, float, ], bottom_left: Tuple[float, float, ], top_right: Tuple[float, float, ], ) -> bool: """ Check if a given point is within the bounds of 4 sides :param top_right: the top right of the bounding rectangle :param bottom_left:...
4d133c261bb9e71edcdfb66c156eed052346ecc8
612,093
import random def generate_password(length): """Generate a password of a desired length with numbers, symbols, upper and lowercase letters""" if length < 4: raise ValueError('length must be 4 or greater') lower_chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', ...
8fb47ef138f0cfc334edc9caf55cdc4cc3111559
612,096
def vel_space(lam, lam0): """ Convert a maximum absorption wavelength to a velocity using the relativistic Doppler formula Args: lam: maximum absorption wavelength lam0: rest-frame absorption wavelength Returns: v: ejecta velocity """ z = lam / lam0 return 3e5 *...
7713faea281dfee4bfba4d6c35279100d64fc4f0
612,097
def is_exc_info_tuple(exc_info): """Determine whether 'exc_info' is an exc_info tuple. Note: exc_info tuple means a tuple of exception related values as returned by sys.exc_info(). """ try: errtype, value, tback = exc_info if all([x is None for x in exc_info]): return Tru...
a635e74ee434432528ee141b7e2cfb9653e17d00
612,099
from math import sqrt def euclidean_dist(p1, p2): """Euclidean distance of two 2D points.""" return sqrt((p1.x-p2.x)**2 + (p1.y-p2.y)**2)
8b823c79ce8ce2134646be36ba04d7e54b8713f1
612,103
def num_bps(paired_region): """Return number of base pairs (=Length) of paired_region paired_region -- PairedRegion object """ return paired_region.Length
b1baaaf1bd7d019e9ce49d1237e071c8a502d183
612,104
def _inside_interval(start, end, date): """Checks if the given date is inside the interval or not" :param start: the start date of the interval :param end: the end date of the interval :param date: the date to check :returns: True if it is inside, False otherwise """ return (date >= start a...
7b750d602c03b3ec9fae3ff244051ed08cb817e1
612,108
def int_64_to_128(val1, val2): """Binary join 128 bit integer from two 64bit values. This is used for storing 128bit IP Addressses in integer format in database. Its easier to search integer values. Args: val1 (int): First 64Bits. val2 (int): Last 64Bits. Returns: int: IP ...
7952abd158942ee3bbe94416897b13f500738113
612,109