content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def uniquify(seq, preserve_order=False):
"""Return sequence with duplicate items in sequence seq removed.
The code is based on usenet post by Tim Peters.
This code is O(N) if the sequence items are hashable, O(N**2) if not.
Peter Bengtsson has a blog post with an empirical comparison of other
... | 25502efa0931ed161f708ef5056df8e09cb45a39 | 481,091 |
def variable_match(series_1, series_2):
"""
Returns a binary series representing the equality of
pairwise elements in two series
:param series_1: pd.Series
:param series_2: pd.Series
:return: pd.Series
"""
return (series_1 == series_2) * 1 | 7c2b272513b6512e398060eb4aa4fef448a7e835 | 260,633 |
import textwrap
def _wrap_docstring(doc):
"""Helper function to wrap a docstring at 72 characters while
maintaining line breaks.
"""
return "\n".join(
["\n".join(textwrap.wrap(l, subsequent_indent=" "))
for l in doc.split('\n') if l]) | 3993687d579c532bf5db859213fabeca462591b0 | 319,216 |
import calendar
def get_month_week_number(day):
"""
Given a datetime object (day), return the number of week the day is
in the current month (week 1, 2, 3, etc)
"""
weeks = calendar.monthcalendar(day.year, day.month)
for week in weeks:
if day.day in week:
return weeks.index... | 964499d69f003e5a8c28758b18239307312e5f55 | 535,523 |
def quiesce(board, alpha, beta, evaluate):
"""Search for all moves that would lead to a capture of own piece.
A 'quiet' move is one that ends without a chance of capture.
Standing pat:
In order to allow the quiescence search to stabilize, we need to be able to
stop searching without necessarily... | a6dacde30de149d1aff63c01f32db296ffa14c91 | 129,938 |
def unzip(l):
"""Unpacks a list of tuples pairwise to a lists of lists:
[('a', 1), ('b', 2)] becomes [['a', 'b'], [1, 2]]"""
return zip(*l) | b1dec3ba48d37bef05e56542b5ff6cf2fb267269 | 444,698 |
def dict_item_to_string(key, value):
"""
inputs: key-value pairs from a dictionary
output: string 'key=value' or 'key=value1,value2' (if value is a list)
examples: 'fmt', 'csv' => 'fmt=csv' or 'r', [124, 484] => 'r=124,484'
"""
value_string = str(value) if not isinstance(value, list) else ','.jo... | 1ad44fd06216feea1ddff4f2b208f605f0f60cff | 195,111 |
def token_is_a(token1, token2):
"""Returns true if token1 is the same type as or a child type of token2"""
if token1 == token2:
return True
parent = token1.parent
while(parent != None):
if parent == token2:
return True
parent = parent.parent
return False | 8e5e2d1ebdaa7ede4a10d314c8285fea73952726 | 124,307 |
import re
def scrub_words(text):
"""Basic cleaning of texts."""
"""Taken from https://github.com/kavgan/nlp-in-practice/blob/master/text-pre-processing/Text%20Preprocessing%20Examples.ipynb """
# remove html markup
text=re.sub("(<.*?>)","",text)
#remove non-ascii and digits
text=re.s... | ed7224d56b02e10fc683a742f1c1313b2b243c26 | 65,911 |
import click
from pathlib import Path
def _ensure_relative_path(node_subdir: str) -> str:
"""Checks that the subdir path does not contain parent directory
navigator (..), is not absolute, and is not "peekingduck/pipeline/nodes".
"""
pkd_node_subdir = "peekingduck/pipeline/nodes"
if ".." in node_su... | 3de71977a9e0aafd76365a7a305561c7e0b53e63 | 319,213 |
def _javaMapToDict(m):
"""
Converts a java map to a python dictionary.
:param m: java map.
:return: python dictionary.
"""
result = {}
for e in m.entrySet().toArray():
k = e.getKey()
v = e.getValue()
result[k] = v
return result | 4ad45f37b8767bc5fab7b7547f42e47e374e86ba | 163,082 |
def pair(x, y):
"""Return a function that represents a pair."""
def get(index):
if index == 0:
return x
elif index == 1:
return y
return get | dddb156489b2fff860471f74fd7829752a31bee5 | 131,573 |
def _update_other_results(results, best):
"""Update the positions and provisional input_sets of ``results`` based on
performing the contraction result ``best``. Remove any involving the tensors
contracted.
Parameters
----------
results :
List of contraction results produced by ``_parse_... | d6beeae8734d886e817668abb51b776333ebf2d2 | 587,852 |
import yaml
def read_vibdata(vib_file):
"""Reads a yaml file containing the
vribational frequencies from a DFT calculation.
Parameters
----------
vib_file : (:py:attr:`str`):
File name
Returns
-------
vib_prop : :py:attr:`dict`
Dictionary of vibrational freqencies.
... | 31006173c40b9ad5edc27688aaad330bc7335bb9 | 578,156 |
def get_property_content(content, prefix):
"""Add the prefix to each object in the content and return the
concatenated string with "," as the separator.
Args:
content: the list containing property objects
prefix: the prefix before dcid, such as "dcs:"
Returns:
objects separated b... | 385955f38efdf35519e34fee0334d778335b5681 | 517,178 |
def generate_frequency_dict(data):
"""Generate a dictionary of all symbols (keys) with their number of appearances
(values) from data.
"""
dict_appearances = {}
for crrt_char in data:
if crrt_char in dict_appearances:
dict_appearances[crrt_char] += 1
else:
d... | 4ad0bea5b1251f138d240e8db2a805f60c384a61 | 435,844 |
def wt_lb_kg(wt):
"""Converts height from centimeter to squared meter
Parameters
----------
wt: double
weight in pound
Returns
-------
double
weight in kilogram.
Examples
--------
>>> wt_lb_kg(200)
90.8
"""
return wt * 0.454 | a6173dbcfe0361a06b10b00fb3b405e31daca325 | 392,585 |
def getFeatureId(feature):
"""
Return the ID of a feature
params:
feature -> a feature
"""
return feature["id"] | 8bdccc4166c67d9076f702d03414cb4f3e4e8a48 | 653,980 |
from datetime import datetime
def get_tm1_time_value_now(use_excel_serial_date: bool = False) -> float:
"""
This function can be used to replicate TM1's NOW function
to return current date/time value in serial number format.
:param use_excel_serial_date: Boolean
:return: serial number
"""
... | fc3154fafe991b517e3464ea783ad6b985ad06de | 111,182 |
def inverty(x, y, **kwargs):
"""Multiply y by -1"""
return x, -y | 0feaa5e6dab3a9225ced398a03b6a65b05e769fc | 427,247 |
def align_position2doc_spans(positions, doc_spans_indices, offset=0, default_value=-1,
all_in_span=True):
"""Align original positions to the corresponding document span positions
Parameters
----------
positions: list or int
A single or a list of positions to be alig... | 5c4b5755f59e72ddb579b83932ab341e8a9c62d0 | 467,072 |
def request_cert(session, domain_name, validation_domain):
"""Requests a certificate in the AWS Certificate Manager for the domain name
Args:
session (Session|None) : Boto3 session used to communicate with AWS CertManager
If session is None no action is performed
... | 8a6c5a0eff185d545edfe4a9aba9e4f93f0749ae | 159,518 |
from typing import Iterable
def get_components_of_message(data: str) -> Iterable[str]:
"""Returns the three components (origin, destination, message) of a data packet."""
data_list = data.split(',')
origin, destination, message = data_list
return origin, destination, message | cc01d0107ef456d8c7d8a9dd0e7c5068e189d665 | 98,762 |
def to_upper(string: str) -> str:
"""
Converts :string: to upper case. Intended to be used as argument converter.
Returns
-------
:class:`str`
String to upper case
"""
return string.upper() | 4decf6692745e9df10666756698e7a443df218f6 | 506,736 |
def filter_none(data, split_by_client=False):
"""This function filters out ``None`` values from the given list (or list of lists, when ``split_by_client`` is enabled)."""
if split_by_client:
# filter out missing files and empty clients
existing_data = [
[d for d in client_data if d ... | 7cc88ecdf7aba245f56598ee1094fed7c1f9f4f7 | 11,746 |
import errno
def read_no_interrupt(p):
"""Read from a pipe ignoring EINTR errors.
This is necessary because when reading from pipes with GUI event loops
running in the background, often interrupts are raised that stop the
command from completing."""
try:
return p.read()
except IOErro... | 0fed5b7655c73e1611915157a62ce7fbd2d5b379 | 563,459 |
import ipaddress
def get_prefix_protocol(prefix):
"""
Takes a network address space prefix string and returns
a string describing the protocol
Will raise a ValueError if it cannot determine protocol
Returns:
str: IPv4 or IPv6
"""
try:
ipaddress.IPv4Network(prefix)
... | 2aa24198eee51c966388c4e0de3416a4638027f7 | 124,668 |
import torch
from typing import Sequence
def crop(data: torch.Tensor, corner: Sequence[int], size: Sequence[int]) -> torch.Tensor:
"""
Extract crop from last dimensions of data
Args:
data: input tensor
corner: top left corner point
size: size of patch
Returns:
torch.Tensor: cropp... | 2f596db499e3b1d59475477e71a95e8a170242da | 23,838 |
def _dataset_ids_equal(dataset_id1, dataset_id2):
"""Compares two dataset IDs for fuzzy equality.
Each may be prefixed or unprefixed (but not null, since dataset ID
is required on a key). The only allowed prefixes are 's~' and 'e~'.
Two identical prefixed match
>>> 's~foo' == 's~foo'
>>> ... | a8eec519af5159041f5b81943f4ef0e478170507 | 268,714 |
def pie_pct_format(value):
""" Determine the appropriate format string for the pie chart percentage label
Args:
value: value of the pie slice
Returns:
str: formated string label; if the slice is too small to fit, returns an empty string for label
"""
return '' if value < 7 else '%.0f... | ac5e7f15fb12b383cfe99e3579dff9d1e2b84843 | 599,801 |
def get_name(model, index: int):
"""Get the input name corresponding to the input index"""
return model.inputs[index] | 6620098f8fb99b18a37aed4ca4f8a28f038c8c79 | 678,497 |
from typing import Dict
def get_opt_value(result_data: Dict, param_name: str) -> float:
"""A helper function to get parameter value from a result dictionary.
Args:
result_data: Result data.
param_name: Name of parameter to extract.
Returns:
Parameter value.
Raises:
K... | bc9c50934757f858973c06c2ddf6b0671b7d9740 | 153,895 |
import torch
def np2torch(array, dtype=None):
"""
Convert a numpy array to torch tensor convention.
If 4D -> [b, h, w, c] to [b, c, h, w]
If 3D -> [h, w, c] to [c, h, w]
:param array: Numpy array
:param dtype: Target tensor dtype
:return: Torch tensor
"""
d = array.ndim
perm =... | 1651ba975e9854fa8727b4019683cf0828a37d24 | 548,434 |
def parse_csv_data(csv_filename:str)->list:
"""
Functionality:
---------------
Takes a csv file and puts the data in a list of strings
so that they can be processed later
Parameters:
---------------
csv_filename : str
The name of ... | 319358a99174c17df8dcdcd6777237bd48be475b | 226,714 |
def journal(record):
"""
Turn the journal field into a dict composed of the original journal name
and a journal id (without coma or blank).
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "journal" in record:
# switch journal to objec... | 4714872865967e757bdc6c6e93a78cee1d64ab81 | 153,251 |
def binary_string_to_value(binary_string):
"""
Convert a binary string representing an unsigned int to a value
Args:
binary_string (str): The string to convert. e.g. "001010010"
Returns:
(int): the value of the binary string
"""
return int(binary_string, 2) | 075a4d1958ef9a1c409cfda7a7e71d533434f42e | 108,335 |
from typing import List
def replace_words_with_prefix_hash(dictionary: List[str], sentence: str) -> str:
"""
Replace words in a sentence with those in the dictionary based on the prefix match.
Intuition:
For each word in the sentence, we'll look at successive prefixes and see if we saw them before
... | bb46b0dc61eab2be358d44f8fb46782f867e3c30 | 24,990 |
def calc_montage_horizontal(border_size, *frames):
"""Return total[], pos1[], pos2[], ... for a horizontal montage.
Usage example:
>>> calc_montage_horizontal(1, [2,1], [3,2])
([8, 4], [1, 1], [4, 1])
"""
num_frames = len(frames)
total_width = sum(f[0] for f in frames) + (border_siz... | 8fe5de84d9b1bff9950690ec99f63e174f2f0d22 | 701,204 |
def _get_checksum_algorithm_set(payload_info_list):
"""Get set of checksum algorithms in use."""
return {d["checksum_algorithm"] for d in payload_info_list} | 76c86e66bc5778c6c2a85ccbc681be93ee6504dc | 324,665 |
import socket
def ipaddr_str(t):
"""Pass through a string provided it represents an ip address (not a host name) otherwise raise an exception"""
try:
socket.inet_aton(t)
except socket.error:
raise ValueError("IP address string not of the form nnn.nnn.nnn.nnn")
return t | 364dc5a6599cc3d420a8bbca817fd6a82ce89c2f | 411,037 |
def get_property_name(x: str) -> str:
"""Return message name of property in proto.
Args:
x (str): The name of property.
Returns:
str: Message name of property in proto .
"""
x_name = x[0].upper()
x_name += x[1:]
x_name += 'Property'
return x_name | 1abe7c040a7e64bb4df3a7726e6047492d2b7d2f | 302,989 |
def load_categories(file_name):
"""
Loads the category index from file. Each category label is
the name of a class specified on a separate line. The entry order
is the index of the class.
"""
labels = []
with open(file_name) as f:
labels = f.read().splitlines()
categories = {}
... | 54bcd375c2e5b9d5d9078d6f0a75b9cebce03702 | 668,891 |
def supports_ordinals(bv):
""" Check whether the BinaryView supports ordinal imports """
return bv.view_type == 'PE' | 5a2fb60385361dd958be2c1aee8641838b175f51 | 234,602 |
from datetime import datetime
def datetime_from_iso8601(date_str):
"""Convert ISO 8601 datetime string to datetime.
See `ISO 8601 (Wikipedia) <https://en.wikipedia.org/wiki/ISO_8601>`_.
Parameters
----------
date_str : str
Example: 2016-12-11T10:00:00.000Z
Return
------
dt :... | eca77d3a19449a810e6b399d0c876a2db1e1f015 | 170,923 |
def mae_expr(gray_only: bool = True) -> str:
"""Mean Absolute Error string to be integrated in std.Expr.
Args:
gray_only (bool, optional):
If both actual observation and prediction are one plane each.
Defaults to True.
Returns:
str: Expression.
"""
return 'x... | 98098d0412357f98721b4da645dadf9a688ab091 | 292,230 |
def struct2spglib(st):
"""Transform :class:`~pwtools.crys.Structure` to spglib input tuple (cell,
coords_frac, znucl).
"""
return st.get_spglib() | a8d2e08c7e17e507eb9b2992ae834009403bd4e9 | 671,060 |
def calc_answer(question, solution):
"""
Calculate the black and white pegs of a question
@param question: The question that is asked
@param solution: The secret solution
@return: black, white pegs
"""
q = question.lst()
s = solution.lst()
r = []
b = w = 0
for i in range(len(... | 08e06f00c80c0b8a411f82f7b5107c8770dc4b61 | 438,406 |
def extract_star_names(file):
"""Extracts star names from a text file
Arguments:
file {str} -- the path to the text file
Returns:
star_names {list} -- a list of star_names from text file
"""
names = open(file, 'r')
star_names = [line[:-1] for line in names.readlines(... | 182a7d101da130b0035d8d18a7ff0b9ae142e4d6 | 114,222 |
import torch
def l2_norm(input, axis=1):
"""l2 normalization.
Args:
input (torch.Tensor): The input tensor.
axis (int, optional): Specifies which axis of input to calculate the
norm across. Defaults to 1.
Returns:
Tensor: Tensor after L2 normalization per-instance.
... | 850e9c8424b8c315953062e224980ce74611682d | 505,263 |
import re
def frame_of(path):
"""
Get the frame number of a specific image path
:param path:
:return: frame as int
"""
frame = re.findall('.+[\._](\d{4,8})\.[A-Za-z]{3,4}', path)
if frame and len(frame) == 1:
return int(frame[0]) | b1604d172deae39772eeea79c753b1c0a58abfca | 229,122 |
def get_reverted_disk_rses_id_name_map(disk_rses_id_name_map):
"""Revert k:v to v:k"""
return {v: k for k, v in disk_rses_id_name_map.items()} | 51ea8b84a5d23f365b3e6a182b62ca586dae7009 | 626,008 |
def subtraction(a, b):
"""subtraction: subtracts b from a, return result c"""
a = float(a)
b = float(b)
c = b - a
return c | 0115222efc08588a12a6fbc1965441b83a7eaff0 | 699,510 |
def vector_to_dictionary(theta):
"""
Unroll all our parameters dictionary from a single vector satisfying our specific required shape.
"""
parameters = {}
parameters["W1"] = theta[:20].reshape((5,4))
parameters["b1"] = theta[20:25].reshape((5,1))
parameters["W2"] = theta[25:40].reshape((3,5)... | 1e945fe5850e90466622df82b0dfe9fe2de6c36f | 263,975 |
def merge_diffs(d1, d2):
"""
Merge diffs `d1` and `d2`, returning a new diff which is
equivalent to applying both diffs in sequence. Do not modify `d1`
or `d2`.
"""
if not isinstance(d1, dict) or not isinstance(d2, dict):
return d2
diff = d1.copy()
for key, val in d2.items():
... | 7314ad63a4679308d27bcff956c9b570d89df8a7 | 684,739 |
def path_to_filename(path):
""" Returns filename from path by keeping after last '\'
"""
return path.split("\\")[-1] | 645751dda77ac572940d4542228e8769b194de7c | 410,935 |
import requests
def get_stock_data(stock_symbol, start_date, end_date):
"""
Make an REST API call to the tiingo API to get historic stock data
Parameters
----------
stock_symbol : str
US stock market symbol
start_date : str
yyyy-mm-dd formated date that begins tim... | c32ac75581622a4694e8dca96ca87311500e09ec | 559,883 |
import torch
def logit(p):
"""
inverse function of sigmoid
p -> tensor \in (0, 1)
"""
return torch.log(p) - torch.log(1 - p) | 290d07606aa01c9837bfce6cdd411ec241ec4484 | 306,898 |
def is_terminal(depth, board):
"""
Generic terminal state check, true when maximum depth is reached or
the game has ended.
"""
return depth <= 0 or board.is_game_over() | 7678f3861e628b4e284725c52227b6277ff2f645 | 445,477 |
def handle_arguments(**mapping):
"""
Decorator that will remap keyword arguments.
Useful to support maya "short" and "long" form for function arguments.
ex: `cmds.ls(selection=True)` and `cmds.ls(sl=True)` are equivalent.
:param mapping: A mapping of argument short name by their long name.
:typ... | 440d67230ae3dd377a6d007234ac1dbda6a4df65 | 337,949 |
def _check_boolean(input, name):
"""Exception raising if input is not a boolean
Checks whether input is not ``None`` and if not checks that the input is a
boolean.
Parameters
----------
input: any
The input parameter to be checked
name: str
The name of the variable for prin... | b9fb435efc9a2b22384f570f0fa5d5462c07a6a9 | 675,769 |
def get_chart_size_range(length, padding):
"""Calculate the chart size range for a given axis based on the length and padding."""
return [length * padding, length * (1 - padding)] | 41e57b7f2f4066d14d6c82ef05b84d2ceda3b6f2 | 235,904 |
def _reduce_datetimes(row):
"""Receives a row, converts datetimes to strings."""
row = list(row)
for i in range(len(row)):
if hasattr(row[i], 'isoformat'):
row[i] = row[i].isoformat()
return tuple(row) | f6442cb04c2941f7b83271db430802f6decf51d9 | 385,078 |
def get_headers(dataframe):
"""Get the headers name of the dataframe"""
return dataframe.columns.values | 8276160a185dc1515da5910811b6b021279bc1f0 | 262,784 |
def get_category_from_topchart_url(url: str) -> str:
"""Return the category from an url.
Throws an error if the url isn't recognized.
"""
category = url.split("/")[3]
# check category
if category not in [
"films",
"series",
"jeuxvideo",
"livres",
"bd",
... | f32296ef176e70df0abf39d8391df394db6bc9d2 | 619,229 |
def read_lines_from_tar_file(tar_file):
"""
Read the tar file returning the lines
"""
txt = tar_file.read()
txt = txt.decode('utf-8')
return txt.splitlines() | 82c702a4c2fcdb9115774c32730a49f1b3280c8c | 98,828 |
def format_car(car):
"""Given a car dictionary, returns a nicely formatted name."""
return "{} {} ({})".format(
car["car_make"], car["car_model"], car["car_year"]) | 9719c1c1467b5f866a7b285d093e9bb3d3718ea4 | 526,785 |
def make_grid(area):
"""Make orchard grid given required area."""
height = 3
width = (area // height) + 1
return [[1] * width for _ in range(height)] | 7c6500c5927ea2ab5b4cc428f37edf0dc451fb2e | 338,678 |
import re
def fullmatch(regex, string, flags=0):
"""Emulate python-3.4 re.fullmatch()."""
matched = re.match(regex, string, flags=flags)
if matched and matched.span()[1] == len(string):
return matched
return None | 72de0abe5c15dd17879b439562747c9093d517c5 | 3,374 |
def list_or_int_or_float_or_str(value):
"""
Parses the value as an int, else a float, else a string. If the value
contains commas, treats it as a list of ints or floats or strings. Also
handles None, True, and False.
"""
if "," in value:
return [list_or_int_or_float_or_str(item) for item... | dcbe8aa414925a8771d1e8591e8aa1344ea2b8f3 | 185,698 |
def remove_prefix(text: str, prefix: str) -> str:
"""Remove prefix from string
:param str text: Text to remove prefix from
:param str prefix: Prefix to remoe
:return: Text with prefix removed if present
"""
if text.startswith(prefix):
return text[len(prefix):]
return text | c48060c156fc960a769f27151e3cef1549942842 | 329,110 |
import torch
def gaussian(window_size, sigma):
"""
Computer Gaussian.
"""
x = torch.arange(window_size) - window_size // 2
if window_size % 2 == 0:
x = x + 0.5
gauss = torch.exp((-x.pow(2.0) / (2 * sigma ** 2)))
return gauss / gauss.sum() | 7babdf151ffe3b8fef16f076ea31f57140aa385a | 312,344 |
def alphabet_of_cipher(symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
"""
Returns the list of characters in the string input defining the alphabet.
Notes
=====
First, some basic definitions.
A *substitution cipher* is a method of encryption by which
"units" (not necessarily characters) of plainte... | e7a7aed5006c35ac2aa42455dd97c1f95a2e2ca6 | 355,376 |
def flux_at_edge(X, min_value=0):
"""Determine if an edge of the input has flux above min_value
Parameters
----------
X: tensor or array
2D matrix to evaluate
min_value: float
Minimum value to trigger a positive result.
Returns
-------
result: bool
Whether or no... | 3cb29f64e6b9cdce0cb987d27af95b828e10475a | 86,930 |
def _build_css_asset(css_uri):
"""Wrap a css asset so it can be included on an html page"""
return '<link rel="stylesheet" href="{uri}" />'.format(uri=css_uri) | 450edf9a134ef6ce3f4b47445e3c26d00b41d45a | 346,243 |
def _train_dev_split(X, y, dev_ratio=0.25):
"""
This function spilts data into training set and development set.
"""
train_size = int(len(X) * (1 - dev_ratio))
return X[:train_size], y[:train_size], X[train_size:], y[train_size:] | a547cc105e6e89077dd99c43a50a77e6cc527259 | 641,353 |
def extract_output(line):
"""
Extract the index of the tree and the matched tree fragment from a line of Tregex outout.
"""
line = line.strip()
index = None
fragment = None
for k, c in enumerate(line):
if c == ':':
index = line[:k]
fragment = line[(k+1):].stri... | b47d8d317108d896f8144a29477a4f2d873cd4c1 | 498,979 |
def err_func(params, x, y, func, w=None, func_list=None):
"""
Error function for fitting a function
Parameters
----------
params : tuple
A tuple with the parameters of `func` according to their order of
input
x : float array
An independent variable.
y... | 421a98fca40ec666ff8843b701e1a59de6576933 | 380,593 |
import random
def select_random_subgraph(bqm, n):
"""Select randomly `n` variables of the specified binary quadratic model.
Args:
bqm (:class:`dimod.BinaryQuadraticModel`):
Binary quadratic model (BQM).
n (int):
Number of requested variables. Must be between 0 and `le... | c41823e1e5c664b14e33cc7d9ef26ea5599ae592 | 426,723 |
def diff_set(before, after, create_replaced=True):
"""Compare sets to get additions, removals and replacements
Return 3 sets:
added -- objects present in second set, but not present in first set
removed -- objects present in first set, but not present in second set
replaced -- objects that have the... | f61fab8c964c768c57f574061c5e0226de9f2771 | 101,600 |
import re
def alias_tpl(data):
"""Generates Mantle alias
Output:
@"postTime": @"post_time",
"""
name = data['original_name']
candidates = re.findall(r'(_\w)', name)
if not candidates:
new_name = data['name']
else:
new_name = re.sub(r'_(\w)', lambda x: x.group(1).upp... | 13e42ecffb27018e87acfd1919bb812603c50f4c | 93,416 |
def _append_y(clifford, qubit):
"""Apply a Y gate to a Clifford.
Args:
clifford (Clifford): a Clifford.
qubit (int): gate qubit index.
Returns:
Clifford: the updated Clifford.
"""
x = clifford.table.X[:, qubit]
z = clifford.table.Z[:, qubit]
clifford.table.phase ^= ... | ac2429e81590fcdb8f2821154b81165031a5ef26 | 566,940 |
def get_null_columns(train, null_threshold=0.4):
"""
finds columns with null values greater than threshold(default=0.4)
returns list of columns to be removed
"""
missingcol = train.columns[(train.isnull().sum() /
train.shape[0]) > null_threshold]
return missingcol | 7aefb259facdc8c2ae36b78a297e1937732c0e8f | 185,262 |
def turn_psql_url_into_param(postgres_url: str) -> dict:
"""
>>> turn_psql_url_into_param(
... 'postgres://USERNAME:PASSWORD@URL:PORT/USER?sslmode=SSLMODE') == {
... 'db_user':'USERNAME', 'db_password': 'PASSWORD', 'db_host': 'URL', 'db_port':
... 'PORT', 'db_name': 'USER', 'sslmode': 'SSLMODE'}
... | 6a25bea1c647e80114828e708f61b04b14c35327 | 493,431 |
def intToByte(i):
"""
int -> byte
Determines whether to use chr() or bytes() to return a bytes object.
"""
return chr(i) if hasattr(bytes(), 'encode') else bytes([i]) | e70741a85138e0ef82d828bf46bbce90252707e6 | 176,836 |
def split_sentence(s):
"""
Given a string, [s], split it into sentences.
# Arguments
* `s` (str) - a string to split.
# Returns
A list strings representing the sentences of the text. It is guaranteed
that each string is non-empty, has at least one whitespace character, and
both start... | c805e4c22e9136cb3d7e07e94a2be2301452c6e3 | 513,637 |
def get_curated_date(date):
"""
remove the seconds etc, e.g., 2018-07-15T16:20:55 => 2018-07-15
"""
return date.strip().split('T')[0] | 08fc369c7b33612b5460cd6ae155999d50cdd2fe | 540,230 |
def get_docker_base_image_name() -> str:
"""
Return a base name for docker image.
"""
base_image_name = "amp"
return base_image_name | 6b9e6d71e9d530430a1572fbc2f3d80f4aa39b80 | 550,084 |
def to_ms(ts):
"""
Returns an ms-formatted version of the specified tree sequence.
"""
output = ""
for tree in ts.trees():
length = tree.interval[1] - tree.interval[0]
output += "[{}]{}\n".format(length, tree.newick())
return output | 517ab1bbe1a0d5b2309375564ec7acbbd3f8c91d | 493,187 |
import random
def sample_from(weights):
"""returns i with probability weights[i] / sum(weights)"""
total = sum(weights)
rnd = total * random.random() # uniform between 0 and total
for i, w in enumerate(weights):
rnd -= w
if rnd <= 0: # return the smallest i such that
retu... | 084cc781ac6dd7ffe0df96bf23dfc00de7d5d4eb | 314,839 |
def clean_multiple_coordsets(protein):
"""
Deletes all but the first coordinate set of a protein.
"""
if len(protein.getCoordsets()) > 1:
for i in range(len(protein.getCoordsets())):
if i == 0:
pass
else:
protein.delCoordset(-1)
return ... | 70e0c9355394b78331b802c40369b98c74ed75f1 | 35,127 |
def hfsym(self, kcn="", xkey="", ykey="", zkey="", **kwargs):
"""Indicates the presence of symmetry planes for the computation of
APDL Command: HFSYM
acoustic fields in the near and far field domains (beyond the finite
element region).
Parameters
----------
kcn
Coordinate system re... | 27b4b9b262fc39afe159f7886e8a4a3854e4ef36 | 511,153 |
import math
def _pad(text, block_size):
"""
Performs padding on the given plaintext to ensure that it is a multiple
of the given block_size value in the parameter. Uses the PKCS7 standard
for performing paddding.
"""
no_of_blocks = math.ceil(len(text)/float(block_size))
pad_value = int(no_... | d5334e05924c2221c539d92e819e2188074faac8 | 642,374 |
def size(price_left=1, price_right=1, vol_left=1, vol_right=1, unit_size_left=1,
multiplier_left=1, multiplier_right=1):
"""Calculate volatility weighted size for each leg of pairs trade
Calculate the number of units for each leg of a pairs trade by
passing the price of both legs and optionally th... | 9f1752689da25b923093679b130d0a40142d0ca2 | 136,573 |
def string_contains_space(string):
"""
Returns true if string contains space, false otherwise.
"""
for char in string:
if char.isspace():
return True
return False | 2069afc7679c3b52606ba021f26aba9615ccdd9b | 117,349 |
def _Checksum(sentence):
"""Compute the NMEA checksum for a payload."""
checksum = 0
for char in sentence:
checksum ^= ord(char)
checksum_str = '%02x' % checksum
return checksum_str.upper() | d3932b8079d0fc78774c825746d46ac569e42e2e | 505,578 |
import time
def get_elapsed_time(start_time) -> str:
""" Gets nicely formatted timespan from start_time to now """
end = time.time()
hours, rem = divmod(end-start_time, 3600)
minutes, seconds = divmod(rem, 60)
return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds) | d75a1873254e1b1cc9ffc714e65d3a9ed95e5803 | 704,297 |
import json
def update_permissions_for_annotation(
gc, annotation_id=None, annotation=None,
groups_to_add=None, replace_original_groups=True,
users_to_add=None, replace_original_users=True):
"""Update permissions for a single annotation.
Parameters
----------
gc : gider_client... | e4e10862d3d11551197f281200497542a723f947 | 115,428 |
from typing import Sequence
def false_positive_rate(y_true: Sequence, y_pred: Sequence) -> float:
"""Calculates the false positive rate binary classification results.
Assumes that the negative class is -1.
"""
assert set(y_true).issubset({1, -1})
assert set(y_pred).issubset({1, -1})
false_pos... | 8668d01c2628062efef67b04c912ef315d37fa13 | 62,357 |
def fillNaToMode(data):
"""Iterates through NA values and changes them to the mode
Parameters:
dataset (pd.Dataset): Both datasets
Returns:
data (pd.Dataset) : Dataset with any NA values in the columns listed changed to the mode
"""
columns = ["MSZoning", "Functional", "Electrical", "Kitch... | 6d8ec04da66b7463e69fdda3ff6665b3ce2bbde8 | 632,886 |
def get_names_probs(predict_output, cat_to_name, class_to_idx):
"""Return the names and probabilities of the predicted classes
Args:
predict_output (obj): A ``torch.tensor`` object from typically with 2 tensors
cat_to_name (dict): A dictionary containing key to category mapping of each category in the cat_to_n... | 5b62aa1a98b4391733bcae2c02aa95663edcf11c | 270,811 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.