content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def all_wheels_must_be_on_track(all_wheels_on_track):
""" Return low factor if car doesn't have all its wheels on the track """
if not all_wheels_on_track:
wheel_factor = 1e-3 # hard code multiplier rather than making it
# continuous since we don't know the width of
... | ef66d84e3d0c22a193efbaece33dc6102e62ef44 | 606,448 |
def comment(_str):
"""
Create a ANSYS comment
"""
return "! %s"%(_str) | dc44ada06cb47dc62b850349ae5b759cb7a35e8d | 606,451 |
import copy
def copy_images(images):
"""
Copies images and returns the new instances.
The new images also have copied calculators.
Parameters
----------
images: list
List of ase atoms images to be copied.
"""
new_images = []
for image in images:
calc = image.get_c... | c34588b049a40e7e55da76a85cff4c6e7396265e | 606,455 |
def rename(imgName, char):
"""
Helper function for renaming output files
"""
title = imgName.split(".jpg")[0]
newTitle = "{}_{}.jpg".format(title, char)
return newTitle | b8449b5ccfd9fc82c58e9cf3d8b765fbe362a1f1 | 606,457 |
def _escape_xref(xref_match):
"""Escape things that need to be escaped if they're in a cross-reference.
"""
xref = xref_match.group()
xref = xref.replace('/', '%2F')
xref = xref.replace('?', '%3F')
xref = xref.replace('#', '%23')
return xref | a47bb3cbc0855064570c0c44d9ef524a5e13d51e | 606,459 |
def bpm_sync(bpm, quarter_notes):
"""
Turns a BPM value and a length given in beats into a frequency usable by a modifier.
:param bpm: Beats Per Minutes
:param quarter_notes: Length of LFO cycle in quarter notes
:return: frequency in Hz
"""
return bpm / 60.0 / quarter_notes | cb0169cc4349a50d665a2f8bff7975d7e03836f4 | 606,460 |
import math
def getPoint(t, R, Rr, E, N):
""" Get a point on a cycloid with the given parameters
t: parameter
R: major radius
Rr: rolling radius
E: eccentricity
N: number of pins """
psi = math.atan2(math.sin((1-N)*t), ((R/(E*N))-math.cos((1-N)*t)))
x = (R*math.cos... | 781a04022e9ccfe5c25190b1c5e378cb137e1a6c | 606,461 |
def _get_coord_affine(ndim):
"""Compute target coordinate based on a homogeneous transformation matrix.
The homogeneous matrix has shape (ndim, ndim + 1). It corresponds to
affine matrix where the last row of the affine is assumed to be:
``[0] * ndim + [1]``.
Notes
-----
Assumes the follow... | ae7d231a901682d50903256a656094448b87a81a | 606,464 |
import re
def clean_html_from_string(raw_html):
""" This function receives an HTML string of a text, and retrieves a clean string of its content.
Args:
raw_html: An HTML format text
Returns:
(string). A clean text string
"""
if not raw_html:
return None
clean_r = re.c... | 93429fb88da5142478a965efe2f44763c5619d26 | 606,466 |
def users_in_same_organization(user_one, user_two):
"""Returns true if the two users passed in belong to the same organization."""
if not hasattr(user_one, 'organization') or not hasattr(user_two, 'organization'):
return False
return user_one.organization == user_two.organization | 2f7b21d52fa61aaa3c9d3f817c8f9bea7b7f62c7 | 606,467 |
def calculate_countdown__mod(count: int, index: int, duration: int) -> int:
"""
把周期任务通过取模的方式平均分布到 duration 秒 内执行,用于削峰
:param count: 任务总数
:param index: 当前任务索引
:param duration: 执行周期
:return: 执行倒计时(s)
"""
return max(index, 1) % max(duration, 1) | 0f3c363cf7756f77d32da1092048e464394e4d31 | 606,472 |
def parse_id(id_value: str) -> dict:
"""
Parse the id_value into its component parts.
:param id_value:
The id value to parse.
:return:
A dictionary containing the parts of the id including the prefix,
uuid, and checksum.
"""
if len(id_value.split('-')) != 8:
temp... | 5ecca75d89949fd6ed7db328a3c6c603db174e4a | 606,473 |
def comp_cols(comps):
"""Return columns corresponding to the average composition
:comps: str
:returns: list str
"""
return ["<comp({})>".format(c) for c in comps] | ab8afc1c69d4e26f1febbd8791fd3825d002a14d | 606,474 |
def rk4_update(dynamics_fun, state, num_updates, delta_t, t=None):
"""Applies num_update Runge-Kutta4 steps to integrate over delta_t. Returns update: delta_state"""
def get_update(update):
dt = delta_t / num_updates
current_state = state + update
k1 = dt * dynamics_fun(current_state)
... | 6bb2a1db9c830186bd472c5404f510c9b98da20d | 606,477 |
def get_seq_diff(seq_tuple):
"""Returns the difference between two TCP sequence numbers."""
(seq_min, seq_max) = seq_tuple
if None in (seq_min, seq_max) or 0 in (seq_min, seq_max):
return None
# Seq wrap-around
diff = seq_max - seq_min
if diff < 0:
diff += 2 ** 32
return ... | cdb18eedcf563e245a1f42cdd4cfb7131b073acf | 606,478 |
def get_height(clust):
"""Return height for given cluster"""
# Is this an endpoint? The the height is just 1
if not clust.left and not clust.right:
return 1
# Otherwise the height is the same of the heights of each branch
return get_height(clust.left) + get_height(clust.right) | f2b32a27cda7858dced6c40c931c5fe56de23ee0 | 606,479 |
def add_comma_separation(input: int) -> str:
"""Adds comma-separation for thousands to an integer."""
return f'{input:,.0f}' | e340a4959b711ee9437e8dec2e2d4363a4920728 | 606,482 |
from bs4 import BeautifulSoup
def prettify_html(html: str) -> str:
"""
Create beautiful HTML using BeautifulSoup
:param html: The input raw HTML
:return: The beautiful HTML
"""
soup = BeautifulSoup(html)
return soup.prettify() | f18372007fb4d8468da6ff81f0a31a900e3b6612 | 606,484 |
from typing import Tuple
import pathlib
def _parse_github_path(path: str) -> Tuple[str, str, str]:
"""Parse the absolute github path.
Args:
path: The full github path.
Returns:
repo: The repository identifiant.
branch: Repository branch.
path: The inner path.
Raises:
ValueError: If the ... | 6bd6c24451dde2cf5c695c4267195c85500e9f18 | 606,488 |
import re
def is_url_valid(url: str) -> bool:
"""
Check if the URL is a valid comment URL.
Args:
url: The URL to check.
Returns:
True if the URL is a valid comment URL, False otherwise.
"""
pattern = r"https://www\.deviantart\.com/comments/\d+/\d+/\d+"
return bool(re.ma... | 11bf80c7ffb99ae666f88b652770d52ee4632660 | 606,490 |
def Dot(v1, v2):
""" Returns the Dot product between two vectors:
**Arguments**:
- two vectors (sequences of bit ids)
**Returns**: an integer
**Notes**
- the vectors must be sorted
- duplicate bit IDs are counted more than once
>>> Dot( (1,2,3,4,10), (2,4,6) )
2
Her... | 733d21f9b9795991bdad96710020b86ae6f2b036 | 606,491 |
def iodp_sample_names(df):
"""
Convert expedition, hole, section, type, interval to sample name in format:
exp-hole-type-sect-interval
Parameters
___________
df : Pandas DataFrame
dataframe read in from .csv file downloaded from LIMS online database
Returns
--------------
... | 56ac28ba3c26438c6443de7a527abc0ecf0b2988 | 606,495 |
def adjusted_legth_text(text, length):
"""Returns a text padded with spaces on the right to match a length
:param text: Text to pad
:type text: str
:param length: Desired length with padding
:type length: int
:return: Padded text
:rtype: int
"""
if len(text) < length:
return text + "".join([" " for _ in ra... | 9a28158988a2caf16f245e6cb1c1ee429206ab46 | 606,496 |
def get_content_infos(requests_obj, show_id):
"""
Retrieves some informations for the content to beautify output,
specifically description and well formatted name
"""
infos_url = "https://www.vvvvid.it/vvvvid/ondemand/" + show_id + "/info/"
json_file = (
requests_obj["session"]
.... | a280970a7f8aaa7b9eebb5e3063d1116cfdbcb5f | 606,497 |
def search_event(query, hits, n_total_hits, query_time_ms, source_id=None):
"""Format the properties of the ``search`` event.
:param query: a dictionary that specifies the query and it's options
:type query: dict
:param hits: a list of the returned hits. Each item in the list should
co... | 97115fb12aed5eefb80c70b96b919086e9434650 | 606,498 |
import torch
def mask_to_label(mask, classes):
"""
Returns the combined masks, i.e. label for a mask based on the color classes.
Arguments:
mask {torch.Tensor} -- mask tensor [shape = (B, N, H, W) ; B = Batch Size, N = Number of Classes]
classes {torch.Tensor} -- color classes tensor [sha... | 117dcc67460717993890ae557de5bdcc9e6ca3d6 | 606,499 |
from typing import Dict
from typing import Any
from datetime import datetime
def capture_config(**kwargs) -> Dict[str, Any]:
"""
Capture arguments for the current experiment and add timestamps.
Parameters
----------
kwargs: Dict
Arguments for the current experiment.
Returns
-----... | e1f301b12e7a5f904c4d498bc23af857adcd7844 | 606,501 |
def plural(n):
"""Utility function to optionally pluralize words based on the value of n.
"""
if n == 1:
return ''
else:
return 's' | bfd70987f63ee6e5ab5c58c5b0a61bdff8385785 | 606,513 |
def config_parser_to_dict(config):
"""
Translates the items in the config parser object to dict.
:param config: RawConfigParser
:return: Dictionary with the contents
:rtype: dict
"""
contents = {}
for section in config.sections():
contents.update({section: {item[0]: item[1] for... | b093af16a4b775b1b0eb8e7d8f2ff603f2257827 | 606,514 |
def invoke_transitive(proto_compile_rule, name_suffix, kwargs):
"""Invoke a proto_compile rule using kwargs
Invoke is a convenience function for library rules that call proto_compile
rules. Rather than having to do the same boilerplate across many different
files, this function centralizes the logic o... | b38ae11f03640855f4439e867120d8f8cb1de00e | 606,518 |
def callable_get(collection, key, default=None, args=[]):
"""Get item from collection. Return collection applied to args, if it is callable"""
result = collection.get(key, default)
if callable(result):
return result(*args)
return result | e7798baf2c6958a71876cfbbc1d959c7d7b68f14 | 606,519 |
def funstr2schema(funstr: str) -> dict:
"""
A `funstr` is a functional-string, containing information
of a schema in one string, written in a certain way.
Explinations:
Let funstr = (a:x, b:y) -> f:x. (c:x) -> g. (f:x, g:y) -> h:y
(:x, :y) -> f mening that f is ex... | 79fd5234d3aed37e5ae97f73ec82a175bbe54963 | 606,520 |
def _sparse_ftrs_values(ftr_name):
"""Returns the name of the values for sparse feature `ftr_name`"""
return f"{ftr_name}_values" | 9f1085dccbc787a034399ef5bb47c8d094a70e0f | 606,522 |
def calcInstrNoiseSq(photParams):
"""
Combine all of the noise due to intrumentation into one value
@param [in] photParams is an instantiation of the
PhotometricParameters class that carries details about the
photometric response of the telescope.
@param [out] The noise due to all of these sou... | 43f4ecb8f896b8b368ec773ea5ddc730f58f8138 | 606,525 |
def read_chroms(directory, genome_name):
"""
Read a tab-delimited text file with list of chromosomes and their sizes.
Args:
directory (str): directory of the file location (ex: '/Users/kimm/')
genome_name (str): name of reference genome (ex: 'dm3', 'mm10', 'hg38', 'hg19', etc.)
... | 73236c263a66c74c53dd3005ffd16e27fe7b9e50 | 606,527 |
import re
def _sanitize_value(value):
"""Sanitizes a value into a valid BigQuery label value."""
return re.sub(r'[^\w-]+', '', value.lower().replace('/', '-'))[0:63] | 022d414d4291b97adddb8f3efa4a983333837cac | 606,529 |
def results_to_changemodel(fitted_models, start_day, end_day, break_day,
magnitudes, observation_count, change_probability,
curve_qa):
"""
Helper method to consolidate results into a concise, self documenting data
structure.
This also converts any s... | bdf966994cebb0ce9c581ff5dcfe30259fa84b90 | 606,530 |
def collatz_conjecture(n):
"""
Collatz Conjectures are a mathematical phenomenon where every number following a set of processes ends up becoming one.
The processes are:
Start with a number n > 1. Find the number of steps it takes to reach one using the following process: If n is even, divide it by 2. If n is odd... | d22778ea1cc4db0fa1b0cb2a76b8d4ac42df860b | 606,536 |
import re
def cleanReason(reason: str) -> str:
"""
Converts data form of similarity reason (e.g. `bills-nearly_identical`) to a more readable form (e.g. `nearly identical`)
Args:
reason (str): The similarity reason in its data form
Returns:
(str): The similarity reason in its reada... | 3e38bad7b0f13350145e546bc1173c8cd990745c | 606,541 |
import math
def squaredims(n):
"""Given an integer, calculate the factorization n = a * b, where |a - b| <= 2, a <= b
>>> squaredims(100)
(10, 10)
"""
a = math.floor(math.sqrt(n))
b = math.ceil(n / a)
return a, b | 83114d870d320ee96826282a5f0cdffa04e87f75 | 606,542 |
def is_alarms_table(table):
""" True if table of alarms notifications """
phrase = 'alarm'
return phrase == table.short_title[:len(phrase)].lower() | 9d6d2d5ff2bb34fd834ce57262b1f740aa28b023 | 606,547 |
import json
def manifest_get_data(to_path,key_name,attribute):
"""
Extract an attribute value from the manifest of an integration
:param to_path: the output path to integration md files
:param key_name: integration key name for root object
:param attribute: attribute to get data from... | c273cf5b769843f7de00041dd208fd0139bbb149 | 606,552 |
def load_list(fname: str):
"""Plain text list loader. Reads from file separated by newlines, and returns a
list of the file with whitespaces stripped.
Args:
fname (str): Name of file to be read.
Returns:
List[str]: A stripped list of strings, using newlines as a seperator from file.
... | bc863105c011c676d81e2c87c52b39e3c9bfcfbc | 606,553 |
import toml
import logging
def _parse_conf(conf_file: str):
"""Parses the incoming toml config file"""
try:
conf = toml.load(conf_file)
except Exception as e:
logging.warning(f"Failed to decode TOML file: {e}. Using chrome as browser.")
return "chrome", "", "", "", ""
else:
... | af5e659305210db6f74a1e99870506034a6bc4d9 | 606,555 |
import re
def stripXML(text):
"""
Remove XML annotation from a string.
"""
text = re.sub(r'<[^>]*>', '', text)
text = re.sub(r'\s+', ' ', text)
text = text.strip()
return text | 41204d697bd986a51c9b1bf28ac0fae1813b0a33 | 606,556 |
def find_header_size(filename):
"""Script to find the header size of a filterbank file
Args:
filename (str): Name of file
Returns size of header in Bytes (int)
"""
# open datafile
filfile=open(filename,'rb')
# go to the start of the file
filfile.seek(0)
#read some region l... | f48e5785661dbefc626c61bccef433191ad44c81 | 606,559 |
import binascii
def hexlify_bksl(data):
"""Encode bytes into an hexadecimal string with backslashes"""
hexstr = binascii.hexlify(data).decode('ascii')
return ''.join('\\x' + hexstr[i:i + 2] for i in range(0, len(hexstr), 2)) | b24c0ced39477e003fc74efb65a1e9de666e3e79 | 606,561 |
def _createSetProperty(pName):
"""Internal method to create a SetXXX() method where XXX == pName."""
propName = pName
def setProperty(self, value):
return self.SetPropertyWithName(propName, value)
return setProperty | 355a48bb989955c25bcb8f81af7f869f1788ad18 | 606,562 |
def read_public_key(public_key_path: str) -> str:
"""Loads the public key from file or raises a `RuntimeError`.
:param public_key_path: Path to the public key.
"""
with open(public_key_path, 'r') as file:
public_key_lines = [i for i in file.readlines() if i]
if len(public_key_lines... | bd4f26f8870aad5bc7c982786e1e4cc188d970f6 | 606,564 |
def delete_items_by_index(list_, index_list, copy=False):
"""
Remove items from ``list_`` at positions specified in ``index_list``
The original ``list_`` is preserved if ``copy`` is True
Args:
list_ (list):
index_list (list):
copy (bool): preserves original list if True
Exa... | dcfde91eb96f297e778c15f96791e6ba0baba9dd | 606,565 |
def get_doppler_params_output_format(keys):
"""Set a canonical output precision for frequency evolution parameters.
This uses the same format (`%.16g`) as
the `write_FstatCandidate_to_fp()` function of
`lalapps_ComputeFstatistic_v2`.
This assigns that format to each parameter name in `keys`
wh... | 9631786f38204c01fc411745c31531a1c8070f71 | 606,566 |
def pascals_triangle(n):
"""The first n rows of pascal's triangle"""
out = [[1]]
L = [1]
for i in range(1,n):
t = [0] + L
for i in range(len(L)):
t[i] += L[i]
L = t
out.append(L)
return out | a98bcbf0aa62303f274617bf43ce6c502f8143dc | 606,569 |
def shape_expectation_failed(prefix, suffix, tensors:dict):
"""
Automated message generation for assertion errors on tensor shapes.
:param prefix: Prepended message string
:param suffix: Appended message string
:param tensors: a dictionary with string labels as ids and the tensors as values,
ten... | d649502daa67830cb1bdd1f4a9a7eefa5aa4b401 | 606,573 |
def calc_precision(score_dict):
"""
Compute precision metric from the score dictionary
inputs:
score_dict dictionary with the keys 'TP', 'FP' and 'FN'
output:
precision float with the precision value
"""
precision = float(score_dict["TP"]) / float(score_dict["TP"] + sc... | b4368dd1d118bab1f726365b67c31446e8b5df00 | 606,574 |
def fibo_iter(num):
"""Iterative Fibo."""
if num == 0:
return 0
second_to_last = 0
last = 1
for _ in range(1, num):
second_to_last, last = last, second_to_last + last
return last | 14bf0a638d7c10c9ef6913d24d886732dd78cb28 | 606,579 |
import copy
def get_topic_node_args(node_data):
"""
Returns (source_id, title) from node_data dictionary.
"""
node_data = copy.deepcopy(node_data)
source_id = node_data.pop('source_id')
title = node_data.pop('title')
license = node_data.pop('license')
return source_id, title | 2227005db477d4720555631de9ff493d6c6f959a | 606,581 |
import math
def nCr(n, r):
"""
Number of combinations of a set of size n of distinct objects
choosing r objects.
:param int n:
:param int r:
:return int:
"""
result = math.factorial(n) \
/ math.factorial(n-r) / math.factorial(r)
return result | 6c8050c41df4df3cccdb771f4bccd27a57c01c8f | 606,583 |
def trigram_examples(scope="function"):
"""Trigram examples for test"""
trigram_examples = {
"Peter": ["$$P1", "$Pe1", "Pet1", "ete1", "ter1", "er$1", "r$$1"],
"prepress": [
"$$p1",
"$pr1",
"pre1",
"rep1",
"epr1",
"pre2",
... | 97b18a6d084b29b5f730c3a776495d7a6b82fd40 | 606,591 |
def locked(func):
"""Decorator which locks self.lock."""
def nested(self, *args, **kwargs):
self.lock.acquire()
try:
return func(self, *args, **kwargs)
finally:
self.lock.release()
return nested | 776debeaa6f5c0c7becf76069816b2f067a27ca2 | 606,596 |
def get_tide_station(stations):
""" Prompts user to select a NOAA station from a list.
Displays a list of NOAA tide station ID & descritions, and prompts
user to select one unless only on station is present. Returns the
selected (or sole) station ID and station description, or None if
user declin... | c3afd8d8171c3bb2d1407e9d56a86318928531cb | 606,600 |
def partition_shape_multipliers(
shape,
partition_shape):
"""
Given an array shape and a partition shape, determine for each dimension
how many times the partition's extent can fit in the shape's extent.
Returns a list of multipliers: for each dimension one.
"""
rank = len(shap... | 15d98f03f30e6f98665e35612b0e81831c95f746 | 606,601 |
from typing import List
def cleanup_files(files: List[str]) -> List[str]:
"""Remove redundant directory paths and root them"""
last = None
result = []
for path in sorted(files, reverse=True):
if last is not None:
if path.endswith("/") and last.startswith(path):
con... | 88310f1f471310f694c7b80ff5a50952d9971c0a | 606,602 |
import unicodedata
def asciify(text):
"""
A wonderful function to remove accents from characters, and
discard other non-ASCII characters. Outputs a string of only ASCII
characters.
>>> print(asciify('ædœomycodermis'))
aedoeomycodermis
>>> print(asciify('Zürich'))
Zurich
>>> prin... | aa0119ed87ed89caed917d06babe857b813f6b54 | 606,603 |
def disable() -> dict:
"""Disables database tracking, prevents database events from being sent to the client."""
return {"method": "Database.disable", "params": {}} | 63fbc4ae50cfae5075966d52b1a0f60fcc5fa404 | 606,604 |
def create_ssl_config(certfile=None, keyfile=None, cafile=None, check_hostname=True, secure=True, ssl_context=None):
"""
Choose CertificateManager settings
:param certfile: path of certfile - contains public key
:param keyfile: path of keyfile - contains private key
:param cafile: path of cafile - c... | 44872cd0d8bb9c660f85b1328ab61a13abfc210f | 606,605 |
import glob
def count_jobs(path):
"""Count number of directories in workdir
"""
return len(glob.glob(path)) | b16e49676af57f86963d94a7e08c17b0fb5584c7 | 606,609 |
def parabolic(sample_array, peak_index):
"""
Quadratic interpolation for estimating the true position of an
inter-sample local maximum when nearby samples are known.
Parameters
----------
sample_array : array_like (1D)
Array of samples.
peak_index : int
Index for the loca... | 36d72cc7dd7749cf78627fc3b5a5e67c2f5ac571 | 606,611 |
def get_publish_token(package_name: str):
"""
parses the package_name into the name of the token to publish the package.
Example:
@google-cloud/storage => google-cloud-storage-npm-token
dialogflow => dialogflow-npm-token
Args:
package: Name of the npm package.
Returns:
... | 21fcf1b9276de35a92e9e3fa4c6bde1a993b93ad | 606,612 |
def apply_masks(spectrogram, masks):
"""
Takes in a signal spectrogram and apply a set of T-F masks to it to recover
the sources.
Inputs:
spectrogram: Numpy array of shape (T, F) containing the complex
spectrogram of the signal to mask.
masks: Numpy array of shape (T... | d72bbf64e389c1061dc3f83b59cc5fd627f2f3bc | 606,613 |
def _GetRieDiskInfoMessage(disk_index, host, port, magic):
"""Returns the hashed text for import/export disk information.
@type disk_index: number
@param disk_index: Index of disk (included in hash)
@type host: string
@param host: Hostname
@type port: number
@param port: Daemon port
@type magic: string... | f51e28a0b8b3e6a0ea9ae34a924cf1799ac650f2 | 606,614 |
def _argsort(y_score, k=None):
"""
Returns the indexes in descending order of the top k score
or all scores if k is None
"""
ranks = y_score.argsort()
argsort = ranks[::-1]
if k is not None:
argsort = argsort[0:k]
return argsort | 8ee0e2dcb9359c66308707fc9c2dabeb488273aa | 606,616 |
def compare_ccatParse(ref, ccatParse):
"""Compare a parsing code (ccat-parse) to a reference.
Wildcard (*) accepted.
A parsing code is a 8-char word:
person (1=1st, 2=2nd, 3=3rd)
tense (P=present, I=imperfect, F=future, A=aorist, X=perfect, Y=pluperfect)
voice (A=active, M=middle, P... | 81ff6471baa3ba19dcef30cf5aa16b84284dbf45 | 606,623 |
import re
def has_cjk(text):
"""
infer if chinese (unihan), korean (hangul) or japanese (hirgana) characters are present
:param text:
:return:
"""
# CJK, Hirgana, Katana. Unified Ideagoraphs. Hangjul.
search = re.search("[\u3000-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af]... | 3bfead3194d10bdd4ad082920242396da29791f3 | 606,624 |
def convert_ids_to_toks(token_ids, tokenizer):
"""
Convert tokens id to tokens word
:input:
token_ids: tokens id
tokenizer: tokenizer from Huggingface
"""
special_tokens = tokenizer.special_tokens_map_extended.values()
results = []
for tok_ids in token_ids:
tok_wo... | c3543ac7193b8210fce8f7815c903fc6765ef4fd | 606,625 |
def generate_absolute_parameter(parameter_values):
"""Generate parameters list for absolute parameter type."""
return parameter_values | 0d9d587f17e5ef7d2f3c89a3ae03bf7eafb9ae78 | 606,626 |
import re
def _get_location_url(raw):
""" Extract device description url from discovery response
raw -- raw discovery response
return -- location url string
"""
t = re.findall('\n(?i)location:\s*(.*)\r\s*', raw, re.M)
if len(t) > 0:
return t[0]
return '' | a0c4a882f41d70e6a7b4dcea0e0d79100c48ca14 | 606,629 |
def lorentzian_one(x, fwhm, mu):
"""
Returns a Lorentzian line shape at x with FWHM fwhm and mean mu
"""
return 1.0 / (1+4*((x-mu)/fwhm)**2) | 8eead5fbce5a94addda30e266e36417533b6134a | 606,631 |
from typing import List
from typing import Dict
from typing import Tuple
def generate_text_n_input_ontology_indices(
text_fields: List[str], forte_data_fields_dict: Dict[str, str]
) -> Tuple[str, Dict[str, Tuple[int, int]]]:
"""
Retrieve ontologies from data fields and concatenate them into text.
Also... | acbe9d4595a586eaf2340ea965ad3463749b8658 | 606,636 |
def makeFilenameFromNodePath(nodePath):
"""
Make filename from node path.
Parameters:
nodePath: a list of node names (path from root node to specific node)
return value is a full path for the filesystem. e.g. "folder1/folder2/file.pickle"
"""
baseFilename = ",".join(nodePath)
extension ... | 6770c3c6b0e832bf7ad971e99504659e5a39aa28 | 606,638 |
def overflow(keyword):
"""Validation for the ``overflow`` property."""
return keyword in ('auto', 'visible', 'hidden', 'scroll') | e9825260cee76e44bb629efafb18c4f956e944ff | 606,639 |
import random
def amb(
pitch_center=40,
pitch_range=6,
pulse=120,
rhythm=0.0,
detune=0.0,
repeat=0.5,
memory=5,
length=24,
):
"""Simple version of Larry Polansky's Anna's Music Box as a function."""
# start with empty lists for both pitch and duration
my_pitches = []
m... | c99c462ad485b9f8f9557ceb2615ae5f639a7df5 | 606,643 |
def replace_capture_group(group_match_object, group_alternatives_set_list):
"""
Replace a capture group match object with a back reference.
Appends the capture group's alternatives (as a set)
to the supplied list of sets of capture group alternatives.
"""
group_alternatives_string = group_match_object.gr... | 442d321db85267698c7ca246caac080fb970c597 | 606,645 |
def _map_locations_ids_to_resource_names(client, location_ids):
"""Converts a list of location IDs to resource names.
Args:
client: an initialized GoogleAdsClient instance.
location_ids: a list of location ID strings.
Returns:
a list of resource name strings using the given locatio... | 5ab8087888767a117f05dfb2a4ec6f15920ab180 | 606,646 |
def _rstrip_location_id(device_dict):
"""Strips location_id down to base hex value with no trailing zeroes."""
return device_dict['location_id'].split()[0].rstrip('0') | fda90dcc158da0e92c8818adee7ff6dc9852fa6c | 606,647 |
def chi2(a, b, sigma):
""" Chi squared of two vectors """
return (((a - b) / sigma)**2).sum() | 2899401a20403432c12e59580dd1f758c659abb2 | 606,648 |
def dest(region):
"""Extract the destination part of a region triple"""
return (region[1], region[2]) | f1e0842dda2173d0a1b640b767b610a693b5ca3d | 606,653 |
def getcookies(cookiejar, host, path):
"""Get a dictionary of the cookies from 'cookiejar' that apply to the
given request host and request path."""
cookies = {}
for cdomain in cookiejar:
if ('.' + host).endswith(cdomain):
for cpath in cookiejar[cdomain]:
if path.star... | 9ed614440bdf20b7a74fc0b3baac4b0fa891600b | 606,655 |
def __firstMatch(matches, string):
""" Takes in a list of Match objects and returns the minimal start point among
them. If there aren't any successful matches it returns the length of
the searched string.
"""
starts = map(lambda m: len(string) if m is None else m.start(), matches)
return min(starts) | be4b8ca3b893371e9207db5340a195b244d214fd | 606,659 |
def find_in_string(sub, string):
"""Check if a substring is contained in another string.
:param sub: Substring
:type: str
:param string: String which is checked if the substring is contained
:type: str
:return: Result if the substring is contained in the string
:rtype: boolean
"""
... | e16567e39f29771d98b2a8280fb0a066d21db20f | 606,661 |
def get_columns_by_label(labels, samplecol, filters=[], querystr=None):
"""Get sample columns according to a condition from a set of labels
Args:
labels: dataframe matching sample labels to conditions/factors
samplecol: name of column holding sample/file names
filters: tuples containing ... | 3838838fe32d6dbd9abc75dd5442b5bb1e65638b | 606,668 |
from datetime import datetime
import pytz
def now_in_timezone(tz):
"""
tz should be tzdata identifier, e.g. America/New_York
"""
return datetime.now(pytz.timezone(tz)) | a25c2b8a10e56204e0e2129bf180afc261db0c9c | 606,669 |
def pgcd(a, b): #http://python.jpvweb.com/mesrecettespython/doku.php?id=pgcd_ppcm
"""Retourne le pgcd de a et b. Version etendu du pgcd avec le 1er coef
de bezout (pour inversion modulaire de a).
>>> pgcd(35, 21)
7
>>> pgcd(2016, 1996)
4
"""
r, u = a, 1
rp, up = b, 0
while rp !=... | 75143e0e38384c2a655e6e1aeb3abeff4566aadb | 606,675 |
def coerce_to_str(obj):
"""
Coerce a constant VBA object (integer, Null, etc) to a string.
:param obj: VBA object
:return: string
"""
# in VBA, Null/None is equivalent to an empty string
if ((obj is None) or (obj == "NULL")):
return ''
else:
return str(obj) | bf40a26581d84691db6753494b0140dec5094e33 | 606,676 |
def checkDone(mousePress, doneButton):
"""Check if DONE button is clicked. If yes, return TRUE"""
if doneButton.clicked(mousePress):
return True
else:
return False | cee94caea10ee95863e4eac67a33b2e6664e9e3b | 606,678 |
def SanitizeSQL(sql):
"""Convert singled quotes to dual single quotes, so SQL doesnt terminate the string improperly"""
sql = str(sql).replace("'", "''")
return sql | e267178ac9e36a980e4bc61361e81c3450e7bbf5 | 606,688 |
import unicodedata
def strip_accents(s: str) -> str:
"""
Remove accents from given string:
Example: strip_accents("Málaga") -> Malaga
Args:
s: str - string to process
Returns:
string without accents
"""
return "".join(
c for c in unicodedata.normalize("NFD", s) if ... | 3523f16bd9a72b96ee1fe3c809f1caaf3f0d7495 | 606,690 |
def remove_falsey_values_in_array(lst: list):
"""Removes falsey values such as 0, '', False, None from the list.
Examples:
>>> list_with_falsey = [0, 1, False, 2, '', ' ', 3, 'a', 's', 34, None]\n
>>> remove_falsey_values_in_array(list_with_falsey)\n
[1, 2, ' ', 3, 'a', 's', 34]
... | ff80a3a2cbeca522071508aad36c5bc9c64c2ed2 | 606,692 |
def revision_list_to_obsoletes_dict(revision_list):
"""Args: revision_list: list of tuple tuple: PID, SID, OBSOLETES_PID,
OBSOLETED_BY_PID.
Returns: dict: Dict of obsoleted PID to obsoleting PID.
"""
return {
pid: obsoletes_pid
for pid, sid, obsoletes_pid, obsoleted_by_pid in rev... | 9016e33ccb486ede79b37f9eec21769bd70f5f1a | 606,694 |
import base64
def decode_dcc_upload_contents(contents, encoding='utf-8'):
""" decodes the content returned by a dcc.Upload component's callback
:param contents: a string with a comma separating the content type and the
encoded content
:param encoding: the encoding convention of the en... | 222e392003417e8f7c846dbbcba77eb90f6845eb | 606,696 |
def list_intersect(a, b):
""" Intersection of two lists
"""
return list(set(a).intersection(set(b))) | 8a098435a9f112f84ee026dc7a5183b7743db0c3 | 606,700 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.