content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def remove_file(file_name):
"""
removes this file from disk.
:param file_name: <str> file path name.
:return: <bool> True for success.
:raises: <OSError> invalid file path.
"""
os.unlink(file_name)
return True | ef503857e3a6d429442b4f4b974c326717c4c7f0 | 624,767 |
def check_segment_segment_intersection(x1, y1, x2, y2, x3, y3, x4, y4):
""" Check if two segments overlap. If they do, return t, the time in the first line's 0 <= t <= 1parameterization at which they intersect """
denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if (denom == 0): return None
t = ((x... | 96f89ad8c667c501ca8eac26569d245691618593 | 624,768 |
def nodeid(node):
"""Given a node, tries to return a way to see where it was in the
source text"""
fname = 'UNKNOWN'
line = 'UNKNOWN'
try:
if node.line:
line = str(node.line)
except Exception:
pass
try:
if node.source:
fname = str(node.source... | a907a65ded2c0567318df9039321799beb16228e | 624,770 |
def seconds_until_start(start_time, current_time):
"""Return the number of seconds until start time"""
difference = start_time - current_time
return difference.seconds | 9bb93199c854be392970b789b7906e90f93e0aa2 | 624,771 |
def _format_color_dict(cd, format):
"""
format:
'RGB': list of (R,G,B) tuples
'HEX': list of #HEX strings
"""
if format == 'RGB':
# convert into a list of (R,G,B) tuples
return list(zip(*(cd[k] for k in 'rgb')))
else:
return cd['hex'] | cbcba93a1936cf2233ffebca9c17d0c7d6a95f7f | 624,772 |
def n_subsystems(request):
"""Number of qubits or qumodes."""
return request.param | af17deedd29ab69e31ec36c0de17ecc79ab67598 | 624,773 |
def compute_fuel(mass: int):
"""Read input module value and compute the fuel
Parameters
----------
mass : [int]
The mass of each module
Returns
-------
[int]
Fuel for each module based on mass
fuel = round(mass/3) - 2
"""
return round(mass // 3) - 2 | ba48aa08a3bec34250c750ed8295c20d666d42ba | 624,774 |
import base64
def img_stream_to_b64str(stream, urlsafe=False):
"""
Convert a byte stream of image file to Base64 encoded string.
:param stream: The byte stream of the file.
:param urlsafe: Trigger using URL-Safe format.
:return: Encoded Base64 string.
"""
if urlsafe:
stream_base64 ... | cc132c0e24f7153beb45ddbc8d66b82dedcc18c0 | 624,775 |
def distance_home(x, y):
"""
>>> distance_home(0, 0)
0
>>> distance_home(3, 3)
3
>>> distance_home(-3, 3)
3
>>> distance_home(0, 8)
4
"""
x, y = abs(x), abs(y)
steps = 0
while x != 0 or y != 0:
if y > x:
y -= 2
steps += 1
elif... | 20f795bb3bb74f82a50d570b21fd758642fc60e5 | 624,776 |
def get_theta_hat_bw_sum_cm2(theta_hat_bw_sum_cm1, theta_hat_bw_win_cm1, theta_hat_bw_win_cm2):
"""制御モードcmの夏期条件におけるM1スタンダードモード沸き上げ温度(℃)(27a-2)
Args:
theta_hat_bw_sum_cm1(float): 制御モードがファーストモードの場合の夏期条件におけるM1スタンダードモード沸き上げ温度
theta_hat_bw_win_cm1(float): 制御モードがファーストモードの場合の冬期条件におけるM1スタンダードモード沸き上げ温度
... | 45ef271423fa3fe5a4877a479b579e9ff7f3bda5 | 624,777 |
import os
import glob
import gzip
import tempfile
import tarfile
import re
import codecs
import shutil
def extract_output(output_dir):
"""Extract the text of the a1, a2, and sentence segmentation files from the
TEES output directory. These files are located within a compressed archive.
Parameters
---... | 81ace690b85acd409d104577002bd275b32ba3c8 | 624,778 |
def area(circle):
"""Get area of a circle"""
return circle.get('radius') ** 2 * 3.14159 | 5d64b5fcfe8d82bc994e2e12aeab90c276943fa5 | 624,780 |
def no_series():
"""
Formats error message for event with missing series.
:return: error message
:rtype: str
"""
error = "event(s) without a series"
return error | 02c57c15eee271e2ff667867caa3f242789e8eb7 | 624,781 |
def get_reference_source(lockin):
"""Get the reference source. Return either internal (1) or external (0).
args:
lockin (pyvisa.resources.gpib.GPIBInstrument): SRS830
returns:
(int): 1 for internal, 0 for external.
"""
return int(lockin.query("fmod?").split("\n")[0]) | 21c4dabba2312976be4cfbb1837af3ec83863bb0 | 624,782 |
import os
def find_bzr(path=None):
""" Return bzr root directory path, or None. """
if not path:
path = os.getcwd()
if not os.path.exists(path):
return None
while path:
if os.path.exists(os.path.join(path, '.bzr')) or \
os.path.exists(os.path.join(path, '.bzrignore')... | cb99468fe68185a1303ea4d1406340c9b33e2b01 | 624,783 |
def get_normalized_intensity(peak_intensity, normalization_factor):
""" Normalize using highest theoretical envelope intensity"""
normalized_intens = peak_intensity/normalization_factor
return normalized_intens | e54738c2f25d5a656db0d986353667b74dffe851 | 624,784 |
from datetime import datetime
def get_tag(tag=None):
"""
Simple helper function to create a tag for saving a file if one does not already exist.
This is useful because in some places we don't know whether we will have a tag or not,
but still want to save files.
Parameters
----------
tag ... | 5cecc708086dbcb1a7361ecf55dd015f9edaeedf | 624,785 |
def array_to_dict(rows, key="openstack_id"):
""" Convert a list of dicts into a dict based on key"""
result = {}
for row in rows:
key_value = row.pop(key)
result[key_value] = row
return result | 73e7697df11ff3cbff458e4fe7f434e458c296c8 | 624,786 |
def bevel_3d(point):
"""
Which of the eight corner plane(s) is point P outside of?
"""
corner_plane_code = 0
if (point[0] + point[1] + point[2]) >= 1.5:
corner_plane_code |= 0x01
if (point[0] + point[1] - point[2]) >= 1.5:
corner_plane_code |= 0x02
if (point[0] - point[1] + p... | 55de3488f4476a13359d024ca6a1438b2fc923fc | 624,787 |
from pathlib import Path
def data_path():
"""Return a path relative to the test data folder"""
this_file = __file__
return (Path(this_file).parent / 'data').resolve() | e2ef7d2c3eaa97c0640dadae4002d1c8a7440a52 | 624,788 |
def is_(t, x):
""" Check whether the type of a given x is a given type t.
"""
return type(x) is t | 275809e23e38a4785c3f7f7509305b72864db108 | 624,789 |
import os
def get_search_path(session):
"""
Return the complete data path used when searching for
data files.
"""
# Automatically add ./botocore/data to the
# data search path.
builtin_path = os.path.join(
os.path.dirname(
os.path.dirname(
os.path.abspa... | cf4b745fd479d2e136609a131df342fa2261472a | 624,790 |
import torch
def entropy(p, reduction='mean'):
"""
p: (..., n, n)
Returns: avg
Note: Max entropy of n x n matrix is n\log(n)
"""
n = p.size(-1)
eps = 1e-10
entropy = -(p * torch.log2(eps+p)).sum(dim=[-2,-1])
if reduction is None:
return entropy
elif reduction == 'sum':
... | ee1a466d1d0e2d9816e085db53261815388b5fc2 | 624,791 |
import socket
def dnsname(ip):
"""Returns the DNS hostname of the provided IP address if it's in DNS (PTR record)"""
try:
return socket.gethostbyaddr(ip)[0]
except:
return 'null' | 43ccd2b89aeadcc65a2d689532252fb28603b6f6 | 624,793 |
def complex_filter_set():
""" A filter set with 3 filter_blocks and a flag """
return {
'title': 'Test filter set',
'search_type': 'Variant',
'filter_blocks': [
{
'query': 'ALT=T&hg19.hg19_chrom=chr1',
'flags_applied': ['variant_chrom']
... | 8068606fb3c5fe0f4e432c6c9f019a78d0eb75e4 | 624,794 |
def get_right_end(read_seq, cigar, args):
"""
Gets the right end of the alignment, taking 'check_in_soft' number of
nucleotides from the softclip and check_in_match number of nucleotides
from the mapped part.
"""
# here I first calculate the length of the read and I
# substract the length of the cl... | 06dd075cecfea9c09862870c47fa5bedc6c030b7 | 624,795 |
import csv
def create_ipmi_host_services(robot, data_file):
"""Creates the ipmi host services
Arguments:
robot {ZRobot} -- Robot instance
data_file {str} -- Location of CSV file
Returns:
[str] -- List of host service names created
"""
hosts = []
with open(data_fi... | 9a26f90ae8cbf6c3c7dc0400d10f4098a34fff8f | 624,797 |
def _torch_sqrt(x, eps=1e-12):
"""
A convenient function to avoid the NaN gradient issue of :func:`torch.sqrt`
at 0.
"""
# Ref: https://github.com/pytorch/pytorch/issues/2421
return (x + eps).sqrt() | 42125036a77a67f95ec652097cbcf2ea8f66e308 | 624,798 |
def pytest_ignore_collect(path, config): # pylint: disable=unused-argument
"""Determine if this directory should have its tests collected."""
if config.option.functional:
return True
return config.option.integration_only | f11c7aa2b61607c90e25a2243054930877efad1a | 624,799 |
def _holt_init(x, xi, p, y, l, b):
"""Initialization for the Holt Models"""
p[xi.astype(bool)] = x
alpha, beta, _, l0, b0, phi = p[:6]
alphac = 1 - alpha
betac = 1 - beta
y_alpha = alpha * y
l[:] = 0
b[:] = 0
l[0] = l0
b[0] = b0
return alpha, beta, phi, alphac, betac, y_alpha | 6bc36eaf8972b94831b1675aea389127a8dc790f | 624,800 |
import pandas
def get_last_oid(csv):
"""Get last OID from CSV so we can continue where we left off"""
df = pandas.read_csv(csv)
return int(df.tail(1).OID) | a311beae75b14ecc937f0c85f77f3e3045fdf863 | 624,801 |
def first_differences(signal):
"""The mean of the absolute values of the first differences of the raw signal"""
# build the first differences list
first_diff = []
for i in range(0,len(signal)-1):
first_diff.append(abs(signal[i+1]-signal[i]))
fd_sum = sum(first_diff)
delta = float(fd_sum)/(len(signal)-1)
retur... | b0f2d95f945dc80541521fcb2a59ca704af73221 | 624,802 |
import os
def filter_pathext(val):
"""Extension of a path (including the '.')."""
return os.path.splitext(val or '')[1] | 9ecff6deb3031a5bc66c1af489882f9c21042f30 | 624,803 |
def extract_components_from_flow(flow):
"""Given a versionedFlowSnapshot object, extract out the processors
and create a list of tuples where each tuple is
(component name, component version)"""
extract = lambda p: (p["bundle"]["artifact"], p["bundle"]["version"])
return [ extract(p) for p in flow["... | 90e8099b53416d12c0912407a76c0fc938d114e0 | 624,804 |
from typing import Optional
def __construct_engine_url(dialect: str, driver: Optional[str], username: Optional[str], password: Optional[str],
host: Optional[str], port: Optional[str], database: Optional[str]) -> str:
"""dialect+driver://username:password@host:port/database"""
result... | 5bba5ae863169111aefa4a3ccc6f558dd1380877 | 624,805 |
import argparse
from datetime import datetime
import sys
def parse_args(args):
"""Argument parsing for run_covidnet_ct.py"""
parser = argparse.ArgumentParser(description='COVID-Net CT Train/Test/Infer Script')
parser.add_argument('-md', '--model_dir', type=str, default='models/COVID-Net-CT-A', help='Model... | b7bbb78702c403673af1c96313c495be58a2d52e | 624,807 |
import re
def format(changelog):
"""Clean up changelog formatting"""
changelog = re.sub(r"\n\n+", r"\n\n", changelog)
return re.sub(r"\n\n+$", r"\n", changelog) | 6514e96a050e14d8d461bfd8e966c780a2b67c00 | 624,808 |
def get_path_upload_avatar(instance, file) -> str:
""" Построение пути к файлу аватара, format: (media)/avatar/user_id/photo.jpg """
return f'avatar/user_{instance.id}/{file}' | 9df4e79245aaeabb688cae598bc460dff7edcf8a | 624,810 |
def my_extract(value, delim=',', index=0):
"""Split a given string and return value at given index position."""
return value.split(delim)[index] | 43c179f3468775fbcd2be942fa02f4fe0897eb5f | 624,811 |
import argparse
def parse_args():
""" Parses command line arguments
:return: parsed arguments
"""
parser = argparse.ArgumentParser(description='Audio stream classifier')
parser.add_argument('model')
parser.add_argument('--labels', nargs=2)
parser.add_argument('--frame_size', type=int, defa... | 0d0fa05dfe0bd1ba00440b6769769b4b8d0f1dd2 | 624,812 |
def parse_percent(val):
"""Turns values like "97.92%" into 0.9792."""
return float(val.replace('%', '')) / 100 | 5ae9c2d90cac68aec47fc624253b9c9fa3bf1d7a | 624,813 |
def log_target_types(all_logs=False, **kwargs):
"""
Log targets for log tasks. A log target defines the log types
that will be affected by the operation. For example, when creating
a DeleteLogTask, you can specify which log types are deleted.
:param bool for_alert_event_log: alert events traces... | 2345e25f394ae8be8ac1c4c4fdbb9e4c83e54b22 | 624,814 |
def get_node_availability(name,jlines):
""" calculates the node availability by reading the generated dump file
adding together the uptime of the node and returning the time
parms:
name - node name
jlines - list of already parsed dictionaries node archive
"""
begin = last = current = 0
up... | eceaa57d55a981834daf9b7e3035fabe53cf0e20 | 624,815 |
def mblg_to_mw_johnston_96(mag):
"""
Convert magnitude value from Mblg to Mw using Johnston 1996 conversion
equation.
Implements equation as in line 1654 in hazgridXnga2.f
"""
return 1.14 + 0.24 * mag + 0.0933 * mag * mag | f23acde1063c9c0f4c13a5d3679bf7e894fd6a00 | 624,816 |
from PIL import Image
import PIL.ImageOps
def invert_texture(inpath, outpath, workingImage, settings):
"""Inverts the colors on the texture specified"""
print("Inverting texture: " + inpath)
image = Image.open(inpath)
inverted_image = None
try:
inverted_image = PIL.ImageOps.invert(image)
... | dc53b5868c75321d25825944db63ce2d87a15827 | 624,817 |
import re
def contains_only_vowels(input_str):
"""Receives input string and checks if all chars are
VOWELS. Match is case insensitive."""
if re.search(r"^[aeiou]+$", input_str, re.IGNORECASE):
return True
else:
return False | 2d7a37483a16e2db0ce080a2428916676cb20293 | 624,818 |
def interactions(G, nbunch=None, t=None):
"""Return the list of edges present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
G : Graph opject
DyNetx graph object
nbunch : ite... | d6607c52e014dc4591152aa81d620a494b4582c5 | 624,821 |
def weasyl_sysname(target):
"""Return the Weasyl sysname for use in a URL for a given username."""
return ''.join(i for i in target if i.isalnum()).lower() | 6be503fda69ecf4ca27ebb43bde680373e40b84b | 624,823 |
def allsky_off_region(pix, pix_center, on_region_mask, size, nside=64):
""" All sky off region
"""
return ~on_region_mask | 0eb29a9080e41a8eb24b1ac206c079cf62ac72d4 | 624,824 |
def set_of_words2vec(vocab_list, input_set):
"""
句子转换为向量,如果字典中有这个词则将该单词置1,否则置0
:param vocab_list: 所有单词集合列表
:param input_set: 输入数据集
:return: 匹配列表[0,1,0,1...],其中 1与0 表示词汇表中的单词是否出现在输入的数据集中
"""
# 创建一个和词汇表等长的向量,并将其元素都设置为0
result = [0] * len(vocab_list)
# 遍历文档中的所有单词,如果出现了词汇表中的单词,则将输出的文档向... | a8460bd3a3b7ca45aea0cea4c9722c4514f678ed | 624,825 |
def by_date_range(analysis, from_timestamp, to_timestamp):
"""
Filters list of analysis objects with attribute "createdDate".
Returns a new list of analyses objects that were created between from_timestamp and to_timestamp
:param analysis:
:param from_timestamp: unix timestamp (float)
:param to_... | 580d250a2e71ccbfac0be9b7f3deabcc44de6264 | 624,826 |
def toggle_collapse_tab2(n, is_open):
"""
:return: Open top 10 games fact table on tab 2 if clicked.
"""
if n:
return not is_open
return is_open | a92d52fbda8161c6883f47d663766c63ac33b5d7 | 624,827 |
def deco(func):
"""
deco
@param func:
@return:
"""
def inner():
print('running target()')
return inner | 9e98a1571095aa87068d208c911a59b27a6b3c00 | 624,828 |
import torch
def log_bound_and_scale(scale, bounds):
"""
Scale, de-log, and bound
Args:
scale (torch.tensor): divide input by this value, then take exp
bounds (torch.tensor): tuple, clamp to (bounds[0], bounds[1])
"""
return lambda x: torch.clamp(torch.exp(x / scale), bounds[0]... | 55c6393924a0ec8abe8a953a9430618d5839b95c | 624,829 |
def make_progress_bar(title, value, rank, max_FAAB=100):
"""Makes progress bar with label and value
:param title: string label for progress bar
:param value: value for bar
:param rank: rank to label the value
:param max_FAAB: max FAAB budget if using faab
:return: html progress bar
"""
... | d5976c4b1dac2495f4b3779b51a343347c3757a1 | 624,832 |
def import_deep_distortion_by_type(defect_list: list,
fancy_defects: dict,
):
"""Imports the ground-state distortion found for a certain charge state in order to
try it for the other charge states.
Args:
defect_list (list):
... | 94bbb1588cddc18d43beb6abd29b4f606b83ee95 | 624,833 |
import struct
import binascii
def make_chunk(chunk_type, chunk_data):
"""Create a raw chunk by composing chunk type and data. It
calculates chunk length and CRC for you.
:arg str chunk_type: PNG chunk type.
:arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**.
:rtype: bytes
"""
out... | 19843007bdde2b74182c80a6b03404db131735f8 | 624,834 |
def create_groups(jobs):
"""Group jobs that will be executed in one step. This returns
a list of lists. Each list starts with the 'primary' job. This job is
the ONLY job that has to be executed. But note that when you submit jobs
to a cluster, all jobs of a group have to be submitted. Note that
the ... | e8d06055c922d2362e464c677fa2853f16a7f85b | 624,836 |
def get_version(c):
""" Get current project version from setuptools """
return c.local('python setup.py --version').stdout.strip() | 4a6e4ed3ca20425b806af1bbc13c79d44b4a53f6 | 624,837 |
def is_iterable(value):
# noinspection PyUnresolvedReferences
"""
Returns ``True`` if *value* is an iterable container (e.g. ``list`` or ``tuple`` but not a **generator**).
Note that :func:`is_iterable` will return ``False`` for string-like objects as well, even though they are iterable.
The same a... | 8666b84d9d41db4bafcdb1f6e2984e702b2a4eba | 624,838 |
def encrypt(plaintext, key, cipher):
"""
Using Vignere cipher to encrypt plaintext.
:param plaintext: plaintext to encrypt with given key and given cipher
:param key: the key is appended until it has same length as plaintext;
each character of the key decides which cipher to use to
... | 9aa3d75077f6ae8c7b033e4e979109f76767b483 | 624,839 |
from typing import List
import glob
import os
import re
def _sorted_checkpoints(
model_dir, checkpoint_prefix="checkpoint", use_modification_time=False
) -> List[str]:
"""
Private method discovers model checkpoint directories within the global model_dir,
returns a sorted list with directory paths.
... | 57864b53ac5936b265a21ea32ef00585c0fa9625 | 624,840 |
import inspect
def is_class(object):
"""Check if the given object is a class"""
return inspect.isclass(object) | a49a6d4ea7dd01070bb59d9f787e7eb2a9641a16 | 624,841 |
def init_guess_word(length):
"""
Returns the initial guess word state.
The guess word is initialised with underscores, one for each letter
of the target word.
Args:
length: the length of the target word
Returns:
The initialised guess word, a list of `length` underscores
... | 5e02354b31d93e934ca49fa488be7e8816635913 | 624,842 |
def gcp_histone_normalize(data_df, gcp_normalization_peptide_id):
"""Subtract values of gcp_normalization_peptide_id from all the other probes.
Remove the row of data corresponding to the normalization histone.
Assumes that all probes should be normalized to the same peptide id.
Args:
data_df ... | d7dc0b386f43851391f2834714ba778f748a6c16 | 624,843 |
def HHMM_to_dec_deg(HHMM):
"""Converts a string HHMM to decimal hours."""
return 15*(int(HHMM[0:2])+float(HHMM[2:4])/60.) | fb183f3f2935e9d104532285e560a6a4fe14233b | 624,844 |
def get_tagname(tags, tagid):
"""Get tag name from tag ID from extracted Ghost tags."""
for tag in tags:
if tag['id'] == tagid:
return tag['name'] | 97a434ebad9711b637b64f9e06c87f264e1f22f0 | 624,845 |
def aggregate_values_by_key(rdd):
"""Given an RDD in the form of:
``RDD[(0, 1), (0, 2), (1, 2)]``
Aggregate each key (first index in the tuple) into an RDD of
keys to lists of all values associated with the key.
Examples
--------
>>> x = sc.parallelize([("a", 1), ("b", 1), ("a", 2)])... | 9079b96f3e9e656b78c544f4c1a8ab1aa9d733ff | 624,847 |
def generate_num_processes_default(AUTOMS_NUM_PROCESSES):
""" Generates the default num processes parameter value to use using configured 'num processes' """
if AUTOMS_NUM_PROCESSES is None:
num_processes_default = 1
else:
num_processes_default = AUTOMS_NUM_PROCESSES
return num_proces... | b6c2109eaad9def8e4dcc3ea41726eed6d685cd3 | 624,848 |
def to_unit_vector(vector):
"""
Convert a vector to a unit vector.
Parameter
---------
vector: vector to convert (tuple(float, float)).
Return
------
unit_vector: a unit vector between 1 and -1 (tuple(int, int)).
Version
-------
Specification: Nicolas Van Bossuyt (v1. 10/... | 3271a4dcd3c7644cc3c4efd211b540028e4debff | 624,849 |
import six
def as_bool(val):
"""Converts an arbitary value into a boolean."""
if isinstance(val, bool):
return val
if isinstance(val, six.string_types):
if val.lower() in ('f', 'false', '0', 'n', 'no'):
return False
if val.lower() in ('t', 'true', '1', 'y', 'yes'):
... | 953dd42888115a7fdccf07c286a7261bd6a6d5d9 | 624,850 |
from typing import List
import numpy
def remove_size_zero_matrices(list_matrices: List[numpy.ndarray]) -> List[numpy.ndarray]:
"""
Removes size zero matrices from a list
:param list_matrices: A list of numpy arrays
:return: returns all matrices from the list that do not have a dimension of 0 in any i... | 27d8df4130b9a720435be3b9699afe106668d76a | 624,851 |
def Binary(string: str) -> bytes: # pylint: disable=invalid-name
"""constructs an object capable of holding a binary (long) string value."""
return string.encode() | fa3c70e6e63f8ebd611f0ba1ed93f8d7a321ac38 | 624,852 |
def populated_table(empty_table, request):
"""
Populate a table within the test database before executing test.
The table will have the same name as the test_function itself. Setup and teardown
of the database is handled by the unique_database fixture.
Args:
empty_table: pytest fixture that creates an e... | 2e018ed0c04510ed574b9b01cf4e30e44d035a9e | 624,853 |
def map(n, dep, arr, I = 0):
"""Remape la valeur n compris dans l'intervalle dep sur l'intervalle arr."""
(x, y) = dep
(i, j) = arr
res = ((n - x) * (j - i)) / (y - x) + i
if I == 1:
res = int(res)
return res | 4ebaa509727e6fba04a4d9b2e1384a6ddf7f3c5f | 624,854 |
from typing import Counter
def word_length_freq(text):
"""Returns the Count/Freq Distribution of Words by their length.
Useful for stylometric mendelhall curve
>>> word_length_freq(mytext)
"""
all_tokens_length = [len(token) for token in text.split()]
count_of_n_length_word = Counter(all_tok... | bee647775f179cdcf20d66b810c3ac30d979d2ad | 624,855 |
def get_ternary_label(df):
"""
get ternary label from nli labels
"""
nli2ternary = {"entailment": 1,
"contradiction": -1,
"neutral": 0, }
return df.label.apply(lambda x: nli2ternary[x]).values | 9f15b9bdcd09698ad3bd78eb49a9246c9f9d4b7f | 624,856 |
import subprocess
def run_cmd(cmd):
"""Run a command, capturing the output.
Note: with Python 3.7 we could simplify this using
(check=True, capture_output=True, text=True).
"""
print("\n>", *cmd)
proc = subprocess.run(cmd,
stdout=subprocess.PIPE, stderr=subprocess.PI... | 5848860b79fdd7a75416a69e90c5ed445c6fce5f | 624,857 |
def vectors_approx_equal(v1, v2): # pragma nocover
"""
Check whether the vectors are approximately equal.
This is used where there is VERY minor floating point differences
that can occur in VPython.
:param v1: Vector 1
:type v1: class:`vpython.vector`
:param v2: Vector 2
:type v2: clas... | 41be14e41ea0b7bcee4c8ad974b51dfc08a7d362 | 624,858 |
def getOutputFilename(runId, TRindex):
""""Return station classification filename"""
filename = "percentChange_run-{0:02d}_TR-{1:03d}.txt".format(runId, TRindex)
return filename | dd953408de6f5adaf81d50f9ad9e691233a624ff | 624,859 |
def find_image(text: str) -> int:
"""Function to find if pdf has image only page.
text: text version of pdf document
return: 1 if image was found, 0 otherwise
"""
list_of_pages = text.split('\x0c')[:-1]
page_number = 0
found_image = 0
while page_number < len(list_of_page... | 95022e1263c53290b64ce61d665a5c0e305dfcc7 | 624,860 |
import time
import sys
def decode(model, data, verbose=True):
"""
decode the dataset and compute sentence level acc. and BLEU.
"""
hypotheses = []
begin_time = time.time()
if type(data[0]) is tuple:
for src_sent, tgt_sent in data:
hyps = model.translate(src_sent)
... | c75409ab052900835621786215019af56b279c0c | 624,861 |
def paths_to_dot(paths, edge_legend=None, node_legend=None):
"""Given dependency paths, output in dot format for graphviz."""
if edge_legend is None:
edge_legend = {}
if node_legend is None:
node_legend = {}
edges = []
nodes = set()
for edge in paths:
style = ''
i... | 2831b7710817fc3d4cd5f4c9560a878f3755f8e7 | 624,862 |
def genDict():
"""
Fonction qui génère un dictionnaire pour permettre la compression.
:return dico: le dictionnaire contenant les caractères ASCII étendu et leur code en décimal.
"""
dico={}
for i in range(0,256):
dico.update({chr(i):i})
return dico | 56fad917e6fffd6af164d37617bab088f5fb1e4a | 624,863 |
def _totalValue(comb):
""" Total a particular combination of items
Args:
comb tuple of items in the form (item, weight, value)
Returns:
tuple (total value, total weight)
"""
totwt = totval = 0
for item, wt, val in comb:
totwt += wt
totval += val
return (totval, totwt) | 2e01a9ee807f6879f8df7a2fdd5a87d620a9e997 | 624,864 |
def default_income(time, dt, *args):
"""
Income method stub
:param time: current simulation time
:param dt: time step for which production limits are calculated
:param args: additional arguments
:return: 0
"""
return 0 | ff4a99f84364d8a3873ff38cbd08c3e9d0732db6 | 624,865 |
from datetime import datetime
def _match_to_dt(match):
"""
Build a datetime from a dictionary of information.
These infos were given by re.match.
>>> _match_to_dt({'Y': '2010', 'm': None})
datetime.datetime(2010, 1, 1, 0, 0)
"""
if not match:
# Case where empty dictionary of match... | 3017bb511982b30245837aa61e3d9040d4ac2bd7 | 624,867 |
import re
def isValid(text):
"""
Returns True if the input is related to jokes/humor.
Arguments:
text -- user-input, typically transcribed speech
"""
return bool(re.search(r'\b(hello|hi|how are you|how\'re you|how are things|how\'re things|what\'s up|what is up|what\'s happening|w... | 436b15ce44d082d24507c5bb1dde77cd4410c62e | 624,868 |
def _uno_struct__eq__(self, that):
"""Compares two UNO structs.
Referenced from the pyuno shared library.
"""
if hasattr(that, "value"):
return self.__dict__["value"] == that.__dict__["value"]
return False | 809999054960b352669c0c9ab96e8348ced24d81 | 624,869 |
import torch
import os
def read_matches_files(data_dir: str, matches_file: str) -> torch.Tensor:
"""Return a Tensor containing the ground truth matches
Read the file and keep only 3D point ID.
Matches are represented with a 1, non matches with a 0.
"""
matches = []
with open(os.path.join... | 959ef6f5cf6b591571707b883bcf3f2a8c1c0e05 | 624,870 |
def post_process(games, name, title):
"""add title to platforms data, remove trailing comma"""
# add platform info
games[name][4] += title
# remove trailing bar from release date info
games[name][0] = games[name][0].strip(" | ").strip()
# remove trailing comma from region info
games[name][... | 3359482fb29a265ea014b518f506c5accf5b6229 | 624,871 |
def avg(list):
"""Find average value in a list or list-like object"""
return sum(list) / len(list) | 6c2944b042fee4a080bff348bf056cce19d1ae77 | 624,872 |
from typing import Tuple
def nested(s: bytes, start: int) -> Tuple[bytes, int]:
"""
Return everything between start and a matching closing parenthesis
:param s:
:param start:
:return:
"""
depth = 1 # Because the function match eats the opening parenthesis
i = start
in_quo... | c2e15f1ef16ea9fc55599ebab128516fa34c87ba | 624,874 |
import json
def get_id_list_from_file(filename):
"""reads id list from json file"""
with open(filename,'r') as file:
id_list = json.load(file)
return id_list | b4422b9738bc4b28d05c18301a7dda4c4636879d | 624,875 |
import json
import os
def get_config_dict(config_fp, all_vars, this_file_dir):
"""
Description:
We use the 'json' library to get the config loaded
as a python dict. Also, we add the variables
'R_path', 'FEBA_dir' and 'this_dir' to all_vars.
The config file is 'barseqr_config_d... | a573a715bd117eeaccb2cbbb1657bdcb57d37d87 | 624,876 |
def distance(x, y):
""" Calculate the euclidean distance between two point in three dimensional space. """
return ((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2) ** 0.5 | b4ebd3831889b08d16e342d185782bb361e9c8ed | 624,880 |
def d_y_diffr_dy(x, y):
"""
derivative of d(y/r)/dy
equivalent to second order derivatives dr_dyy
:param x:
:param y:
:return:
"""
return x**2 / (x**2 + y**2)**(3/2.) | 8165fc947632b2dcd2d635d946abb6bb15940b57 | 624,881 |
import time
def timeAndDateStr():
""" A pretty current time and date timestring.
Looks like 12:34 2015/01/01"""
ttime = time.gmtime()
timestring = "%02.0d:%02.0d %02.0d/%02.0d/%02.0d" \
"" % (ttime[3],ttime[4],ttime[0],ttime[1],ttime[2])
return(timestring) | 5736b133b0b2372ccc6625961604fcde2efd94af | 624,882 |
def run(dfs: dict, settings: dict) -> dict:
"""Drop df from dfs"""
if 'dfs' not in settings:
raise Exception('Missing dfs param')
for df in settings['dfs']:
if df not in dfs:
raise Exception('Invalid dfs param')
dfs.pop(df)
return dfs | 95cb58ef2ed2d2dd4d7120b5f8a9d583257d2524 | 624,883 |
def _make_property(property, doc, return_typedoc, return_type):
"""Create a getter method with associated docstring.
Parameters
----------
property : `str`
Name of the property getter to be created.
doc : `str`
Description of this property.
return_typedoc : `str`
Type st... | c1178559ce132d5b2ba1a44d46104d25ad72a2d6 | 624,884 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.