content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def bytes_packet(_bytes, termination_string=']'):
"""
Create a packet containing the amount of bytes for the proceeding data.
:param _bytes:
:param termination_string:
:return:
"""
return '{}{}'.format(len(_bytes), termination_string) | 7f0d6356ec7afccac8e1865765f7f356ee783644 | 639,659 |
def all_besides_none_equal(*args):
"""Return True if all of the (non-None) elements are equal"""
non_none = list(filter(lambda x: x is not None, args))
for i, arg in enumerate(non_none):
if i + 1 < len(non_none) and arg != args[i + 1]:
print(arg)
return False
return True | 4f906bc579af2489ed1243a1d0054570c539a909 | 639,660 |
import math
def compute_rows_columns(num_wells):
"""Convert 96->(8,12), 384->(16,24), etc."""
a = math.sqrt(num_wells / 6)
n_rows = int(round(2 * a))
n_columns = int(round(3 * a))
return n_rows, n_columns | 4effef41bf38e358a695e667841a3e7817dda849 | 639,661 |
def skip_zone_record(zone_record):
"""Whether a zone record should be skipped or not.
Records are skipped if they are empty or start with
a # (indicating a comment).
:param zone_record: Full zone record, including the command (e.g. ADD).
:returns: True if the record should be skipped, false otherw... | 873545c501df3b5753dae62c0da0bfe655a60fdf | 639,664 |
def map_value(value, min_, max_):
"""
Map a value from 0-1 range to min_-max_ range.
"""
return value * (max_ - min_) + min_ | 9b5e083304d4476b223b156a32105b3bfb776cb5 | 639,665 |
def check_influxdb_response(response):
"""Check if the response from influxdb is correct.
InfluxDB normally responds with a 404 on GET to /, but also allow other
non-server-error response codes to allow for that behaviour to change.
"""
return response.code < 500 | b36397785f4cedcef19b05a3f4ed6e59f6b88cab | 639,667 |
def dop2str(dop: float) -> str:
"""
Convert Dilution of Precision float to descriptive string.
:param float dop: dilution of precision as float
:return: dilution of precision as string
:rtype: str
"""
if dop == 1:
dops = "Ideal"
elif dop <= 2:
dops = "Excellent"
el... | 2f9050eb8f3967f299d16377d5e56f2804e15293 | 639,668 |
def get_complexity(data):
"""
Gets the complexity of the given trial data -- the number of degrees of
freedom that are active, or under control of the subject.
"""
return int(len(data['active_classes'])/2) | 778ff4c5c617afff8a19770fe46afc1c2d6b607f | 639,671 |
def prepare_feed_dict(placeholders, images, labels, batch_size, use_generated_data, idx=0):
"""Return the feed dict per batch with the input data."""
idx = idx * batch_size
if use_generated_data:
return {
placeholders[0]: images
}
return {
placeholders[0]: images[idx:... | b91cabacca5db8fc05bf0c4451886f67ac2bbf62 | 639,672 |
def list2str_str(list):
"""Convert list to a single string. Inverse of str2list."""
return ''.join([str(i) + '\n' for i in list]) | 2020d77f8ccb26af71b5d690df6965970f049045 | 639,678 |
from typing import Union
def format_indexing_element(indexing_element: Union[int, slice]) -> str:
"""Format an indexing element.
This is required mainly for slices. The reason is that string representation of slices
are very long and verbose. To give an example, `x[:, 2:]` will have the following index
... | 5b1e281fc503fcefa94835c3dbf1cd41abfa6588 | 639,680 |
def indent_string(the_string, indent_level):
"""Indents the given string by a given number of spaces
Args:
the_string: str
indent_level: int
Returns a new string that is the same as the_string, except that
each line is indented by 'indent_level' spaces.
In python3, this can be done ... | d366395d81d6d9295a40c6a4894bd847d92c62d5 | 639,683 |
def getSamplerFun(sampler, distributions):
"""
get distributions' function by class sampler.
Inputs:
sampler : sampler class, pydpm._sampler.Basic_Sampler;
distributions : [str] list of distributions;
Outputs:
funcs : {str: fun}, dict of distributions' functions;
... | d58c48f1b07884f6b3db43e2d0582099baaff846 | 639,685 |
def line_intersects_segment(line, line_segment):
"""Returns the intersection the Line and LineSegment or None if they do
not intersect.
This function is useful for splitting polygons by a straight line.
"""
linesegform = line_segment.to_line()
if line.is_parallel_to(linesegform):
retur... | 90739c66a3fa9abd0d360fdaf1807a3c27713f0a | 639,686 |
import math
def calc_haversine_distance(p1, p2):
"""calculate haversine distance between two points
# formula info
# https://en.wikipedia.org/wiki/Haversine_formula
# http://www.movable-type.co.uk/scripts/latlong.html
Args
p1: tuple of (longitude, latitude) format containing int or float... | b90aa7be6aaf96ec379403d0b73f593db13dc4f4 | 639,690 |
def is_pow2(n):
"""
Check whether a number is power of 2
Parameters
----------
n: int
A positive integer number
Returns
-------
bool
"""
return n > 0 and ((n & (n - 1)) == 0)
# Solution 2
# return math.log2(n) % 1 == 0 | 6f386513eb4931339faf61c2552a3a8b7cde3053 | 639,692 |
import difflib
def gen_ndiff(a, b):
"""
Return a binary diff result of the byte sequence as a YARA signature.
:param list a: First buffer representing code block as hexlified bytes.
:param list b: Second buffer representing code block as hexlified bytes.
:return: YARA compliant hex string sequen... | f5f251fbf7f11ac2c90ab48a8a9108715eb5c3d9 | 639,696 |
def allocated_size(allocation_unit, requested_size):
"""
Round ``requested_size`` up to the nearest ``allocation_unit``.
:param int allocation_unit: The interval in ``bytes`` to which
``requested_size`` will be rounded up.
:param int requested_size: The size in ``bytes`` that is required.
:... | f25a55f3cf96194c5357e106642b89f6aefba65c | 639,699 |
def rotate_word(s, r):
"""
Rotate each char in a string by through the alphabet by the given amount.
Wrap around to the beginning (if necessary).
"""
r_s = ''
for c in s:
num = ord(c)
r_num = num + r
r_c = chr(r_num)
r_s += r_c
return r_s | 64d19c0cece0c57b2806d8e547944fee6fb3b0d5 | 639,700 |
def default_cmdline_options(config):
"""
Return default command line options required for every run of terraform.
Args:
config: dictionary containing all variable settings required
to run terraform with
Returns:
cmdline_options: list of command-line arguments to run
... | 85f3e74049ae744f4a5b46eb382f293a3c9126d6 | 639,704 |
from datetime import datetime
def utcnow_timestamp_ms() -> int:
"""UTC timestamp in milliseconds.
Returns:
timestamp (int): UTC time in milliseconds
"""
return int(datetime.utcnow().timestamp() * 1000) | bb8e5700c5e2a180e7a49e20e997f0a7d8958cc0 | 639,705 |
def genty_repeat(count):
"""
To use in conjunction with a TestClass wrapped with @genty.
Runs the wrapped test 'count' times:
@genty_repeat(count)
def test_some_function(self)
...
Can also wrap a test already decorated with @genty_dataset
@genty_repeat(3)
@g... | 968b30740174f3b40532be0992aa7e7467463436 | 639,706 |
def time_string(seconds):
"""Returns time in seconds as a string formatted HHHH:MM:SS."""
s = int(round(seconds)) # round to nearest second
h, s = divmod(s, 3600) # get hours and remainder
m, s = divmod(s, 60) # split remainder into minutes and seconds
return "%2i:%02i:%02i" % (h, m, s) | 24635313218b40646fcefd9b1e5d11d294736696 | 639,709 |
def get_input_output_filenames_from_args(args):
"""Return strings inserted to input and output filenames."""
input_filename = args.input_filename
output_filename = args.output_filename
if args.input_output_filename is not None:
input_filename = args.input_output_filename
output_filename ... | ec955bc6f3d872abbb14b6734b2c1abcb9b676cf | 639,711 |
def humanise_seconds(seconds):
"""
Takes `seconds` as an integer and returns a human readable
string, e.g. "2 hours, 5 minutes".
"""
units = []
unit_table = [('hour', 3600), ('minute', 60)]
for unit in unit_table:
quotient, seconds = divmod(seconds, unit[1])
if quotient:
... | c2f6e1395699efa585102288f791011ac45affaa | 639,712 |
def v_str(v_tuple):
"""turn (2,0,1) into '2.0.1'."""
return ".".join(str(x) for x in v_tuple) | 479dd7d1af4a9f23a49ff7d0fe7bdcc9b8bc4411 | 639,713 |
def suffix_opt(opt_arg=''):
"""
return suffix for backup file
"""
suffix = ''
if len(opt_arg) != 0:
suffix = '.' + opt_arg
return suffix | 0a099756bb0b6054ff1c50faad5f44976c82a398 | 639,714 |
import itertools
def nonzero_entries(array, eps=1e-7):
"""Extracts sparse [(value, *indices), ...] array representation.
Args:
array: The numpy array to obtain a sparse representation for,
eps: Threshold magnitude. Entries <= `eps` are skipped.
Returns:
List of (coefficient, index0, ..., indexN) tu... | 42967a7ee827f91a963d69a412754aec2319af3c | 639,718 |
def flatten_batch_X(X):
""" Flattens images """
return X.reshape(len(X), -1) | 8a4499c72d7a36ae0c545a855713ebc2e12a0559 | 639,721 |
def read_mol_dict(file):
"""
Read dict of molecules from file.
Returns
-------
molecules : :class:`dict` of :class:`dict`
Dictionary of molecule definitions with `key` = name.
"""
with open(file, 'r') as f:
lines = f.readlines()
molecules = {}
for line in lines:
... | a435dfea35d8e88587dfa782575c13fd420426ca | 639,725 |
from json import load
import logging
def read_json(filename):
"""
Reads input from a JSON file and returns the contents.
:param str filename: Path to JSON file to read
:return: Contents of the JSON file
:rtype: dict or None
"""
try:
with open(filename) as json_file:
re... | 6f0b4589207430f3325eef4536640711e684df89 | 639,730 |
import re
def filter_location(location):
""" (str) -> str
Filter input string from such characters as
parentheses and blank symbols
>>> filter_location("United Kingdom {(UK)}")
'United Kingdom'
"""
location = re.sub("[(].*?[)]", "", location)
location = re.sub("[{].*?[}]", "", location... | d7a8d2f3ea5a9900aac2df2e601963f8e43da86f | 639,731 |
def serialize_primitive(obj, spec, ctx):
""" Serialize a primitive value. """
return ctx.dumpval('', obj) | 63be72a1e8959a75f5b623fa7938e8a369191b54 | 639,734 |
def assert_interrupt_signal(library, session, mode, status_id):
"""Asserts the specified interrupt or signal.
Corresponds to viAssertIntrSignal function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param mode: How... | f55af51b3bddd3c113223d1ce9ac94a4d20d64ad | 639,739 |
def build_reagent_vectors(portion_reagents, portion_chemicals):
"""Write the reagents in a vector form, where the vectors live in the complete portion basis
The basis is spanned by all chemicals in all reagents in the portion (sans solvent)
:param portion_reagents: a list of all reagents in the portion
... | f8d12ef19e84111dde7a40fa5d1113b4f423ab6f | 639,745 |
def translate(tile, offset):
"""
Move a tile. This returns a moved copy; the original is unchaged.
Parameters
----------
tile : tuple
containing y and x slice objects
offset : tuple
translation, given as ``(y, x)``
Returns
-------
tile : tuple
a copy; the in... | 0a43b48147dd2782e8d994da487a3ea020e20006 | 639,747 |
def get_finegrained_count(text, gender_dct):
"""
Count the number of female, male, and neutral gendered words in a string, given the
gender dict.
"""
text = text.lower()
f_count = 0
m_count = 0
n_count = 0
for line in text.split('\n'):
words = line.split(' ')
for word... | fb5e0cdb0768d3b56892431d032e642fb37211f5 | 639,748 |
def to_dict(X):
"""Make dict-like.
Parameters
----------
X : dict
"""
if hasattr(X, "items"):
return X
elif X is None:
return {None: None}
else:
return {None: X} | 758307c47a04b3d4e5da8ae7768ee35df5e035c0 | 639,750 |
def CommonChecks(input_api, output_api):
"""Presubmit checks run on both upload and commit.
This is currently limited to pylint.
"""
checks = []
blimp_tools_dir = input_api.PresubmitLocalPath()
def J(*dirs):
"""Returns a path relative to presubmit directory."""
return input_api.os_path.join(blimp... | 8c87d4ba84b6bf647f73139344ed6d8e29716b1b | 639,753 |
def decrypt(m,d,n):
"""
Returns decrypted message.
Parameters:
m (int): encrypted message
d (int): private key
n (int): modulus
Output:
decrypted message in numeral form
"""
return(pow(m,d,n)) | f06814403f680b60c36f992eb93900d1a70312df | 639,754 |
def remove_padding(data: bytes, block_n_bytes: int) -> bytes:
"""Removes 0x80... padding according to NIST 800-38A"""
if len(data) % block_n_bytes != 0:
raise ValueError("Invalid data")
for i in range(len(data) - 1, -1, -1):
if data[i] == 0x80:
return data[:i]
elif data[... | 74e904d01448ac9a04b245cb6f8e94bc8a39b67c | 639,769 |
def freq_wise_bmm(a, b):
"""
Parameters
----------
a: (..., n_freq, n_channels_1, n_channels_2)
op 1
b: (..., n_channels_2, n_freq, n_frames)
op 2
Returns
-------
The batch matrix multiplication along the frequency axis,
then flips the axis back
Tensor of shape (... | e54c684106cca842b72b8b2522836815b14aa6ac | 639,773 |
import math
def get_code_len(class_range, mode=0):
"""
Get encode length
:param class_range: angle_range/omega
:param mode: 0: binary label, 1: gray label
:return: encode length
"""
if mode in [0, 1]:
return math.ceil(math.log(class_range, 2))
else:
raise Exception('On... | ff053e24b9cca0cc5298cdd665ac9bd5a6612847 | 639,777 |
def mergesort(input_list):
""" Takes in a list and splits it into halves recursively, then compares
parts of the list to each other and merges them sorted into another list
"""
output = []
if len(input_list) > 1:
mid = len(input_list) // 2
first_half = input_list[:mid]
second... | 9f13c283c8997ef544035998faae4750af899332 | 639,780 |
def logical_right_shift(n: int , shifted_by: int)-> str:
"""
Take in 2 positive integers.
'n' is the integer to be logically right shifted 'shifted_by' times.
i.e. (number >> shifted_by)
Return the shifted binary representation.
"""
if n < 0 or shifted_by < 0:
raise ValueError('The ... | d213f60bba3e41ca9c2e9e7fed85aca1c7757da3 | 639,783 |
def _first_label(label_list):
""" Find first non-blank label """
llist = [lobj.get_text().strip() for lobj in label_list]
for label_index, label_text in enumerate(llist):
if label_text not in [None, '']:
return label_index | b6e49ea2c9c1847ae5efb098a2e6d2b3903524a8 | 639,785 |
import logging
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if not isinstance(number, int):
logging.error("Invalid input type. Should be integer.")
... | d142e4c4ad86815284bde71ca23ff20e47fe7bf3 | 639,786 |
import math
def utilityY(c1,c2,rho):
"""Compute the utility of the young agents
Args:
c1 (float): consumption of the young generation
c2 (float): consumption of the old generation
rho (float): discount parameter
Returns:
(float): utilit... | 6efd01d4a8f85a61f05eb12efca31b63f9f8aeaf | 639,790 |
import operator
def _sortIssues(issues):
"""
Helper function from _formatIssues(). Sort a list of issues by issue number and then by comment
creation date.
GIVEN:
issues (list) -- nested list of issues and their comments
RETURN:
new_issues (list) -- the given 'issues' list, but sorte... | c43e388c07b398b9532b97c2ea73b22f8e96d428 | 639,791 |
def time_to_string(time: int) -> str:
"""Convert time to string representation
Args:
time (int): Time in seconds
Returns:
str: Time in MM:SS format
"""
if time < 0:
raise ValueError("Negative integer not supported")
return "%02d:%02d" % (time // 60, time % 60) | 3d6f639467c216e9fe9cec3b89e65f617cd89cba | 639,793 |
def rgb_hex_to_rgb_list(hex_string: str):
"""Return an RGB color value list from a hex color string."""
return [
int(hex_string[i: i + len(hex_string) // 3], 16)
for i in range(0, len(hex_string), len(hex_string) // 3)
] | f760ae986a1d98d4bc159e88d1c84776cebb6947 | 639,794 |
import binascii
def bytes_to_hex(seq):
"""Converts seq from byte array to hex string"""
return str(binascii.hexlify(bytes(seq)), 'ascii') | 7c332852a066d738719db0fbe4ae7466f0973e7a | 639,795 |
def check_inequality(left_version, right_op, right_version, **_):
"""
Checks for version compatibility when the dependency for
'left_version' has specified an explicitly disallowed version
Args:
left_version (packaging.version.Version):
The version on the left side of the comparison... | 8e783c265d04c06b85f3676f4c168b934f260f4e | 639,796 |
def thermal_energy(particles):
"""
Returns the total internal energy of the (gas)
particles in the particles set.
>>> from amuse.datamodel import Particles
>>> particles = Particles(2)
>>> particles.u = [0.5, 0.5] | units.ms**2
>>> particles.mass = [1.0, 1.0] | units.kg
>>> particles.th... | 91aad749b8523ca8adfc4e8951d3b774b9222c5f | 639,799 |
def ensure_existence(f):
""" Ensures that method is not marked as non_existent
Parameters
----------
f Method
Raises
------
NotImplementedError if the method is marked as non existent
Returns
-------
Method f
"""
if getattr(f, 'not_existing', False):
raise Not... | 18410fe298fcb5dab3114dea1632010d4778417c | 639,802 |
from typing import Dict
from typing import List
def get_evaluations(data: Dict[int, List[int]]) -> Dict[int, float]:
"""
Turns a dictionary with float lists into a dict with mean values.
:param data: Input dictionary with float lists
:return: Output dictionary with float mean values
... | c986e360d6434871baf08d18abc6cb1ffa03547f | 639,803 |
def has_all_dims(dp_or_event, dims):
"""
Tests if `dims`'s are all in a certain datapoint or event
"""
return dims.items() <= {d.key: d.value for d in dp_or_event.dimensions}.items() | 435374511a4d57c07374f1038a6821b837164edc | 639,805 |
def compound_noun_list(token):
"""Find compound nouns.
:param token: token for which to generate potential compound nouns
:type token: :class:`spacy.token`
:return: list of potential compounds
:rtype: [string]
"""
nouns = [token.text]
for nc in token.lefts:
if nc.dep_ == "compou... | 9bb3bae0f3b9cb1fd13a82c39f9d2123d179da17 | 639,806 |
def find_num_player_in_group(group):
"""
find the number of players in a group
:param group: A Group object
:return: number of players in the group
"""
players = group.players.all()
return (len(players)) | 3a1f470bf64fe9409237da7afe1c0692a7b68d53 | 639,808 |
import json
async def _sendLambdaRequest(session, lambdaUrl, anomalyServiceObj):
"""
Async method to send anomaly detection request to lambda
:param session: ClientSession instance for aiohttp
:param lambdaUrl: AWS Lambda invocation endpoint
:param anomalyServiceObject: Dict containing parameter d... | 46403e12d0bd277f893c0c5d3e2547ddc8acadd7 | 639,811 |
def csv_to_list(x):
"""Converts a comma separated string to a list of strings."""
return x.split(",") | 55b97bb93ac6315718ad5b140650be39083c6714 | 639,815 |
def nbAlternatives(instance):
""" Returns the number of alternatives of the instance.
:param instance: The instance.
:type instance: preflibtools.instance.preflibinstance.PreflibInstance
:return: The number of alternatives of the instance.
:rtype: int
"""
return instance.nbAlternatives | 2a03cb1c2718e7ecd82d7df3003805fa032cd01a | 639,819 |
def do_selective_backprop(
epoch: int,
batch_idx: int,
start_epoch: int,
end_epoch: int,
interrupt: int,
) -> bool:
"""Decide if selective backprop should be run based on time in training.
Returns true if the current ``epoch`` is between ``start_epoch`` and
``end_epoch``. Recommend that... | cb5978058da64cab8f3af22acc66bbea1b850f4a | 639,820 |
def extract_CA_coords(helices, model, verbose=False):
"""get CA coordinates for rach residue in each helix
input: helix list, each helix is list of its residues in format (chain, ('', resnum, ''))
output: list of helices, each helix is list of CA coords (Biopython Vector class) of its residues
"""
print('Extracti... | b62f3cc7564f6aa3f8d0eead4132c78e732af7ee | 639,822 |
import typing
from pathlib import Path
def valid_voice_dir(voice_dir: typing.Union[str, Path]) -> bool:
"""Return True if directory exists and has an onnx file"""
voice_dir = Path(voice_dir)
return voice_dir.is_dir() and (len(list(voice_dir.glob("*.onnx"))) > 0) | 7291a79e8f648251ef5ca3cb6b8c51cf6fe90b24 | 639,823 |
def get_most_sold_item(df):
"""Return a tuple of the name of the most sold item
and the number of units sold"""
most_sold_df = df.groupby(['Item'])['Units'].sum()
return (most_sold_df.idxmax(), most_sold_df.loc[most_sold_df.idxmax()])
pass | 0e641279bc47c62b91a82c46749828e6e375e748 | 639,825 |
def function1(a,b):
"""This is a function which will calculate average of two numbers.""" #docstrings
average = (a+b)/2
#print(average)
return average | 3e4c40fd0cfa135dd8b6388c158df0f77e2a8f08 | 639,827 |
def prc_rerouted(XMLDataFrame, XMLDataFrameRef):
"""
Compute the % of rerouted vehicles
"""
# diffPaths = pd.concat(
# [XMLDataFrame["itineraire"], XMLDataFrameRef["itineraire"]]
# ).drop_duplicates(keep=False)
# nChangedPaths = diffPaths.count()
# nGeneratedVeh = XMLDataFrameRe... | 33e6ac0f783ab7d049095a4d671af718913a23a1 | 639,828 |
def _isLinked(self):
"""Return True if another record links to this record"""
if len( self._inx.iref_by_sect[self.uid].a.keys() ) == 0:
return False
for k in self._inx.iref_by_sect[self.uid].a.keys():
if len( self._inx.iref_by_sect[self.uid].a[k] ) > 0:
return True
return False | 6241ec666bc422c51017397b279f208d8a1a2963 | 639,829 |
import hashlib
def _md5_of_file(path):
"""Compute and return the MD5 sum of a flat file. The MD5 is returned as a
hexadecimal string.
"""
md5 = hashlib.md5()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
md5.update(chunk)
return md5.hexdigest(... | c73b38b2f33732a488edac92493dfa993f4a293c | 639,835 |
def read_file(filename) -> str:
"""Read the contents of the file into a string
:param filename: path to the file to be read
:return: string will contents of the file
"""
with open(filename, 'r', encoding='utf-8') as file_content:
return file_content.read() | f97462388e8eb488247aaf63705c2c9e66ae51eb | 639,836 |
def query_successful(api_response):
"""This function reviews the API response from the Community API to verify whether or not the call was successful.
:param api_response: The response from the API in JSON format
:type api_response: dict
:returns: Boolean indicating whether or not the API call was succ... | 278c8d15c3903d72056c3df49faec3fcfe8eb025 | 639,838 |
def crop_image_to_bounding_box(img, bnd_box):
"""Crops the given image to the given bounding box"""
result = img[bnd_box[0][1] : bnd_box[1][1] + 1, bnd_box[0][0] : bnd_box[1][0] + 1]
return result | 27d5d780f9712d72e973cb3de816b04e2ab3ec72 | 639,839 |
from typing import Tuple
import secrets
import hmac
import hashlib
def get_nonce_and_hash() -> Tuple[str, str]:
"""
Get a secure random nonce and a hmac of that nonce
"""
nonce: str = secrets.token_hex(32)
nonce_hash: str = hmac.HMAC(
bytes.fromhex(nonce), digestmod=hashlib.sha256
).he... | 3ad700c8a7b731cb751699a1a2812cbcd0e1a44b | 639,842 |
import torch
def accuracy(y_pred: torch.Tensor, y: torch.Tensor) -> float:
"""
Return predictive accuracy.
Parameters
---
y_pred: torch.Tensor (BATCH, NUM_CLASS)
Predicted values.
y: torch.Tensor (BATCH,)
Real class values.
"""
return (y_pred.argmax(dim=1) == y).float(... | ce109660d411afe31620bd5d4010276e93921ae3 | 639,843 |
def min(self, parameter_min):
"""
It returns the minimum value of a parameter and the value's indexes.
Parameters
----------
parameter_min: str
Name of the parameter.
Returns
-------
min_dict: dict
Dictionary with the following format:
{
... | 5f71e69bc1525ce94a626b742c2df7ef45b5e85a | 639,846 |
def estimate_fuse_passengers(fus_nb, FLOORS_NB, PASS_PER_TOILET, cabin_area,\
MASS_PASS, pass_density):
""" The function evaluates the number of passengers members on board in
case of an unconventional aircraft with fuselage.
Source : passengers density is defined averaging... | 65385f644302acde58ed2cf575f119ec210bc1ed | 639,851 |
from typing import Dict
import requests
def google_oauth2_info() -> Dict:
"""Return Google's spec for their OAuth endpoints."""
resp = requests.get("https://accounts.google.com/.well-known/openid-configuration")
info = resp.json()
return info | 46e8c5c0fefbfbc18e6045560f5ebc7157726194 | 639,852 |
from typing import OrderedDict
def events_v2_data(alert, routing_key, with_record=True):
"""Helper method to generate the payload to create an event using PagerDuty Events API v2
Args:
alert (Alert): Alert relevant to the triggered rule
routing_key (str): Routing key for this PagerDuty integr... | dcc80d5640bd969b757ce01f9100c86551760f36 | 639,855 |
from typing import Dict
from typing import List
def dict_to_list(data: Dict[str, Dict]) -> List[Dict]:
"""Convert a dictionary to a list of 1-element dictionaries.
"""
return [{k: v} for k, v in data.items()] | fbc29d06963f25ab7a6472e3d27ba357ff314b09 | 639,862 |
def _rk12_step(func, y0, dt):
"""Improved Euler-Integration step to integrate dynamics.
Args:
func: Function handle to time derivative.
y0: Current state.
dt: Integration step.
Returns:
Next state.
"""
dy = func(y0)
y_ = y0 + dt * dy
return y0 + dt / 2. * (dy + func(y_)) | dc138f371c1ddd75190449a80d8565f117ce2406 | 639,863 |
from pathlib import Path
def fixture_fixtures_path() -> Path:
"""Path to dir with fixture files"""
return Path("tests/fixtures") | f290a5c38bb6f5b4b79733e80f41e603e3382b75 | 639,864 |
def msg2dict(msg):
"""Convert a generic ROS message into a dictionary (un-nested)
:param msg: ROS message to convert
:rtype: dict
"""
return {k: getattr(msg, k) for k in msg.get_fields_and_field_types().keys()} | 52803702efc2ea804337eb53f4c28782c3ffa424 | 639,868 |
def srcds_functional(**filter_):
"""Enable SRCDS functional testing for a test case
This decorator will cause the test case to be parametrised with addresses
for Source servers as returned from the master server. The test case
should request a fixture called ``address`` which is a two-item tuple
of... | 7ce110aaccffcb0dd6a1e55d5613fcc5871f5aad | 639,871 |
import difflib
def get_close_matches_icase(word, possibilities, *args, **kwargs):
"""Case-insensitive version of difflib.get_close_matches"""
lword = word.lower()
lpos = {p.lower(): p for p in possibilities}
lmatch = difflib.get_close_matches(lword, lpos.keys(), *args, **kwargs)
return [lpos[m] fo... | 42b211f41a004af1eb52761f126badb5f8187977 | 639,872 |
def pascal2snake(string: str):
"""String Convert: PascalCase to snake_case"""
return ''.join(
word.title() for word in string.split('_')
) | 96a3aa31cbb13bdc0ac801909225e71d3094b947 | 639,877 |
def data_classification_level(dsv):
"""Returns the data classification level of the calculated data sensitivity value."""
if dsv < 15:
return 1
elif 15 <= dsv < 100:
return 2
elif 100 <= dsv < 150:
return 3
else:
return 4 | 074c1f6432f73674462aa58d2ee361238bb308ef | 639,879 |
def apply_styles(graph, styles):
"""
Apply the styles to a Graphviz graph.
"""
graph.graph_attr.update(
('graph' in styles and styles['graph']) or {}
)
graph.node_attr.update(
('nodes' in styles and styles['nodes']) or {}
)
graph.edge_attr.update(
('edges' in styl... | 3c81d8778b81144de28e59a30bdc2fbf14af8358 | 639,880 |
import pickle
def load_arrays(name):
"""Load arrays from file."""
with open(name, 'rb') as file:
coords = pickle.load(file)
edof = pickle.load(file)
dofs = pickle.load(file)
bdofs = pickle.load(file)
elementmarkers = pickle.load(file)
boundaryElements = pickle.... | ffde1bc81dfe3121aef9cc70bfe00922e22d2d21 | 639,881 |
def read_translated_file(filename, data):
"""Read a file inserting data.
Arguments:
filename (str): file to read
data (dict): dictionary with data to insert into file
Returns:
list of lines.
"""
if filename:
with open(filename) as f:
text = f.read().repl... | 423f111730335b0fcf4d9178b3cd5e6cda4e0d1f | 639,885 |
def not_better_than_after(minimal, n_iter):
"""Return a stop criterion that returns True if the error is not less than
`minimal` after `n_iter` iterations."""
def inner(info):
return info['n_iter'] > n_iter and info['loss'] >= minimal
return inner | cccc50da383f53da61c35bf000d1ac7431ef3107 | 639,888 |
def int_or_None(val):
"""converter that casts val to int, or returns None if val is string 'None'"""
if val == 'None':
return None
else:
return int(val) | a385f16302edc98024680ced44e18e95c2c33795 | 639,889 |
def create_test_partition(df, N_batch):
"""
Creates a partition of the dataset into a single test set.
Parameters
----------
df : pandas dataframe
Dataframe corresponding to the dataset.
split_ratio : float
Training sample percentage, must be between 0 and 1.... | ef80c0beb7abdeb95d1344bb530b7ce47a3243f8 | 639,893 |
def dist_interval(v, mi, ma):
"""
Distance from v to interval [min,max]
"""
if v < mi:
return mi - v
if v > ma:
return v - ma
return 0 | bf8329658c7e59469f2c48bdf1c4200a06edbb81 | 639,894 |
def prune_nones(mydict):
"""
Remove keys from `mydict` whose values are `None`
:arg mydict: The dictionary to act on
:rtype: dict
"""
# Test for `None` instead of existence or zero values will be caught
return dict([(k, v) for k, v in mydict.items() if v != None and v != 'None']) | 6b61303733a81781fb0e243178b8b549476b3727 | 639,895 |
def str_to_act(env, actions):
"""
Simplifies specifying actions for the scripted part of the agent.
Some examples for a string with a single action:
'craft:planks'
'camera:[10,0]'
'attack'
'jump'
''
There should be no spaces in single actions, as we use spaces to ... | 44b62aa04be845b00ad72678bf2402384483742d | 639,898 |
def namedModule(name):
"""
Return a module given its name.
"""
topLevel = __import__(name)
packages = name.split(".")[1:]
m = topLevel
for p in packages:
m = getattr(m, p)
return m | d588d30b7854f01ee64b6d6eb6455bb0bfff4719 | 639,899 |
def add_(string = ''):
"""
Add an _ if string is not empty
"""
s = ''
if string:
s = string + '_'
return s | 1f8f4c1e41eda3ae2d86338c8fd7077d6450eef4 | 639,900 |
import json
def load_json_schema(filename=None):
""" Loads the given schema file """
if filename is None:
return
with open(filename) as schema_file:
schema = json.loads(schema_file.read())
return schema | f313bba5e3549d5ae161e5ec7a962e92e4e2d96f | 639,903 |
def proc_create_query(prname, prtext, argslist=None):
"""Base method for creating procedure with given name, body and args."""
prtext = prtext.replace("'", "''")
TEMPLATE = """
CREATE OR REPLACE FUNCTION {prname}({argstext}) RETURNS VOID AS'
{prtext}'
LANGUAGE plpgsql;
"""
argstext =... | c767b5d30dae427d9b559313cfbede4618bfb5db | 639,904 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.