content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def step(x, b):
"""
The step function for ideal quantization function in test stage.
"""
y = torch.zeros_like(x)
mask = torch.gt(x - b, 0.0)
y[mask] = 1.0
return y | 5,324,900 |
def encode_intended_validator(
validator_address: Union[Address, str],
primitive: bytes = None,
*,
hexstr: str = None,
text: str = None) -> SignableMessage:
"""
Encode a message using the "intended validator" approach (ie~ version 0)
defined in EIP-191_.
Supply t... | 5,324,901 |
def _ip_desc_from_proto(proto):
"""
Convert protobuf to an IP descriptor.
Args:
proto (protos.keyval_pb2.IPDesc): protobuf of an IP descriptor
Returns:
desc (magma.mobilityd.IPDesc): IP descriptor from :proto:
"""
ip = ip_address(proto.ip.address)
ip_block_addr = ip_address(... | 5,324,902 |
def inheritdocstrings(cls):
"""A class decorator for inheriting method docstrings.
>>> class A(object):
... class_attr = True
... def method(self):
... '''Method docstring.'''
>>> @inheritdocstrings
... class B(A):
... def method(self):
... pass
>>> B.method.__do... | 5,324,903 |
def get_totd_text():
"""
Get the text for the Top of the Day post.
:return: The body for the post.
"""
sections = []
# Most Upvoted Posts
top_submissions = sorted([submission for submission in get_reddit().subreddit("all").top("day", limit=5)], key=lambda x: x.score, reverse=True)
items... | 5,324,904 |
def check_checkpoints(store_path):
"""
Inputs
1) store_path: The path where the checkpoint file will be searched at
Outputs
1) checkpoint_file: The checkpoint file if it exists
2) flag: The flag will be set to True if the directory exists at the path
Function: This function takes in the store_path and check... | 5,324,905 |
def dump_ensure_space(file, value, fun_err=None):
"""
Only dump value if space enough in disk.
If is not enough space, then it retry until have space
Note: this method is less efficient and slowly than simple dump
>>> with open("test_ensure_space.tmp", "wb") as f:
... dump_ensure_space(f, "... | 5,324,906 |
def store_images(input, predicts, target, dataset='promise12'):
"""
store the test or valid image in tensorboardX images container
:param input: NxCxHxW
:param predicts: NxCxHxW
:param target: NxHxW
:return:
"""
N = input.shape[0]
grid_image_list = []
for i in range(N):
... | 5,324,907 |
def snmptable(ipaddress: str, oid: str, community: str = 'public',
port: OneOf[str, int] = 161, timeout: int = 3,
sortkey: Optional[str] = None
) -> OneOf[List[Dict[str, str]], Dict[str, Dict[str, str]]]:
"""
Runs Net-SNMP's 'snmptable' command on a given OID, converts ... | 5,324,908 |
def GetFile(message=None, title=None, directory=None, fileName=None, allowsMultipleSelection=False, fileTypes=None):
"""Ask the user to select a file.
Some of these arguments are not supported:
title, directory, fileName, allowsMultipleSelection and fileTypes are here for compatibility reasons.
"""
default_f... | 5,324,909 |
def lda_recommend(context_list):
""" With multiprocessing using Dask"""
print("Recommending")
topn = 500
sleep(0.2)
vec_bow = id2word_dictionary.doc2bow(context_list)
# This line takes a LONG time: it has to map to each of the 300 topics
vec_ldamallet = ldamallet[vec_bow]
# Convert the q... | 5,324,910 |
def grids_skf_lr(data_x, data_y, grid_params, weight_classes=None, scv_folds=5):
"""
:param data_x:
:param data_y:
:param grid_params:
:param weight_classes:
:param scv_folds:
:return:
"""
if weight_classes is None:
weight_classes = {0: 1, 1: 1}
m_log = LogisticRegressio... | 5,324,911 |
def zeros(rows, cols, fortran=True):
"""Return the zero matrix with the given shape."""
order = "F" if fortran else "C"
cparr = cp.zeros(shape=(rows, cols), dtype=cp.complex128, order=order)
return CuPyDense._raw_cupy_constructor(cparr) | 5,324,912 |
def check_if_dataframe(obj):
"""Checks if given object is a pandas DataFrame."""
if not isinstance(obj, pd.DataFrame):
raise TypeError(
f"Provided object ({type(obj).__name__}) is not a pandas.DataFrame"
) | 5,324,913 |
def runCmd(cmdString, verbose=False):
"""Thin wrapper around subprocess.run() for clean error reporting."""
try:
if verbose:
sys.stderr.write("Running command: %s\n" % cmdString)
sys.stderr.flush()
subprocess.run(cmdString, shell=True)
except subprocess.CalledProcessE... | 5,324,914 |
def compute_trapezoidal_approx(bm, t0, y0, dt, sqrt_dt, dt1_div_dt=10, dt1_min=0.01):
"""Estimate int_{t0}^{t0+dt} int_{t0}^{s} dW(u) ds with trapezoidal rule.
Slower compared to using the Gaussian with analytically derived mean and standard deviation, but ensures
true determinism, since this rids the rand... | 5,324,915 |
def test_adjacency_k_brute_connect():
"""
Adjacency Matrix k-Nearest Neighbors test
"""
# import data
data = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
# set default parameters
n_neighbors = 5
algorithm = 'brute'
method = 'knn'
# sklearn adjacency matrix
... | 5,324,916 |
def test_ssm_provider_find_parameter(boto_fs):
"""
Should find the specific entry in the provider
"""
config_file = 'config.yaml'
session.aws_profile = None
session.aws_region = 'us-east-1'
boto_fs.create_file(config_file, contents=f"""
kms:
arn: {KEY_ARN}
parameters:
- name: '... | 5,324,917 |
def vavrycuk_psencik_hti(vp1, vs1, p1, d1, e1, y1,
vp2, vs2, p2, d2, e2, y2,
phi, theta1):
"""
Reflectivity for arbitrarily oriented HTI media, using the formulation
derived by Vavrycuk and Psencik [1998], "PP-wave reflection coefficients
in weakly aniso... | 5,324,918 |
def test_config_set_min(ursadb: UrsadbTestContext) -> None:
""" Sanity check that minimal values are enforced """
assert "error" in ursadb.request('config set "query_max_edge" 0;') | 5,324,919 |
def request_set_endorser(handle: RequestHandle, endorser_did: str):
"""Set the endorser on a prepared request."""
endorser_p = encode_str(endorser_did)
do_call("indy_vdr_request_set_endorser", handle, endorser_p) | 5,324,920 |
def test_spawn_args(spawn, shell):
"""
Test that the arguments for Pexpect spawn are correct.
"""
shell.connect()
spawn.assert_called_with(
'test connection command',
env={'TERM': 'dumb'},
echo=False,
use_poll=True,
)
shell = Shell(
'', spawn_args={'... | 5,324,921 |
def concatenate_time_series(time_series_seq):
"""Concatenates a sequence of time-series objects in time.
The input can be any iterable of time-series objects; metadata, sampling
rates and other attributes are kept from the last one in the sequence.
This one requires that all the time-series in the lis... | 5,324,922 |
def test_Device_unit():
"""Test unit setter and getter of Device class."""
dev = Device('dev1')
assert dev.unit is None
dev.unit = 'mV/Pa'
assert dev.unit == 'mV/Pa' | 5,324,923 |
def setup_database_node(*args):
"""Provisions database services in one or list of nodes. USAGE: fab setup_database_node:user@1.1.1.1,user@2.2.2.2"""
for host_string in args:
# Frame the command line to provision database
cmd = frame_vnc_database_cmd(host_string)
# Execute the provision d... | 5,324,924 |
def deeplink_url_patterns(
url_base_pattern=r'^init/%s/$',
login_init_func=login_init,
):
"""
Returns new deeplink URLs based on 'links' from settings.SAML2IDP_REMOTES.
Parameters:
- url_base_pattern - Specify this if you need non-standard deeplink URLs.
NOTE: This will probably clos... | 5,324,925 |
def read_words():
"""
Returns an array of all words in words.txt
"""
lines = read_file('resources/words.txt')
words = []
for line in lines:
words.extend(line.split(' '))
return words | 5,324,926 |
def lynotename(midinote):
"""Find the LilyPond/Pently name of a MIDI note number.
For example, given 60 (which means middle C), return "c'".
"""
octave, notewithin = midinote // 12, midinote % 12
notename = notenames[notewithin]
if octave < 4:
return notename + "," * (4 - octave)
else:
... | 5,324,927 |
def check_object(o):
""" Test that o is a valid object identifier."""
if not (isinstance(o, URIRef) or \
isinstance(o, Literal) or \
isinstance(o, BNode)):
raise ObjectTypeError(o) | 5,324,928 |
def json_serial(obj):
"""
Fallback serializier for json. This serializes datetime objects to iso
format.
:param obj: an object to serialize.
:returns: a serialized string.
"""
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
return str(obj) | 5,324,929 |
def main():
"""
loads the resources and launches the app
:return: None
"""
app = QtWidgets.QApplication(sys.argv)
load_resources()
controller = NoiceController()
controller.show()
sys.exit(app.exec_()) | 5,324,930 |
def deepgreen_deposit(packaging, file_handle, acc, deposit_record):
"""
Deposit the binary package content to the target repository
:param packaging: the package format identifier
:param file_handle: the file handle on the binary content to deliver
:param acc: the account we are working as
:par... | 5,324,931 |
def _scrub_participant_table(path_to_data):
"""Scrub PII from the given participant table."""
path = os.path.join(path_to_data, "participant.csv")
with open_for_csv(path, 'r') as input, open("{}.0".format(path), 'w') as output:
reader = csv.reader(input)
writer = csv.writer(output)
h... | 5,324,932 |
def get_library_file(instrument, detector, filt, pupil, wfe, wfe_group,
library_path, wings=False, segment_id=None):
"""Given an instrument and filter name along with the path of
the PSF library, find the appropriate library file to load.
Parameters
-----------
instrument : str... | 5,324,933 |
def html_mail(sender='me@mail.com', recipients=['them@mail.com'],
html_content='<p>Hi</p>', subject='Hello!',
mailserver='localhost'):
""" html_mail takes input html, sender, recipents and
emails it in a mime type that will show as text or html on
the recipients mail reader.
... | 5,324,934 |
def gotu(input_path: str) -> biom.Table:
"""Generate a gOTU table based on sequence alignments.
"""
profile = workflow(input_path, None)['none']
return profile_to_biom(profile) | 5,324,935 |
def read_data_megset(beamf_type):
""" Read and prepare data for plotting."""
if beamf_type == 'lcmv':
settings = config.lcmv_settings
settings_columns = ['reg', 'sensor_type', 'pick_ori', 'inversion',
'weight_norm', 'normalize_fwd', 'use_noise_cov',
... | 5,324,936 |
def collect_user_name():
""" Returns the username as provided by the OS. Returns a constant if it
fails.
"""
try:
uname = getpass.getuser()
except Exception as e:
logger = logging.getLogger(__name__)
msg = "Failed to collect the user name: error was {}.".format(e)
log... | 5,324,937 |
def get_dataframe() -> pd.DataFrame():
"""Dummy DataFrame"""
data = [
{"quantity": 1, "price": 2},
{"quantity": 3, "price": 5},
{"quantity": 4, "price": 8},
]
return pd.DataFrame(data) | 5,324,938 |
def get_node_mirna(mirna_name, taxid, psi_mi_to_sql_object):
"""
This function sets up a node dict and returns it. If the node is already in the SQLite database it fetches that node from the db, so it won't be inserted multiple times.
"""
# Testing if the node is already in the database
node_dict =... | 5,324,939 |
def generateEndOfQuiz(filename):
"""This method takes a name of file and appends '++' to the very end of the file which is recognised as
end of template by IS.MUNI ROPOT parser.
Args:
filename (string): Name of file where end of template for IS.MUNI ROPOT will be appended to its very end.
"""
... | 5,324,940 |
def Web(website, system_id, address, page, params = {}):
"""Routine for connecting to website that is hosting the database"""
data = ''
params['systemid'] = system_id
params = urllib.urlencode(params)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
try:
... | 5,324,941 |
def generate_output_file_name(input_file_name):
"""
Generates an output file name from input file name.
:type input_file_name: str
"""
assert isinstance(input_file_name, str)
output_file_name = input_file_name + ".gen.ipynb"
return output_file_name | 5,324,942 |
def prefixed_field_map(name: str) -> Mapper:
"""
Arguments
---------
name : str
Name of the property.
Returns
-------
Mapper
Field map.
See Also
--------
field_map
"""
return field_map(
name,
api_to_python=add_signed_prefix_as_needed,
... | 5,324,943 |
def a_star(grid, start, end):
"""A-star algorithm implementation"""
# open and closed nodes
open_nodes = []
closed_nodes = []
# Create a start node and an goal node
start_node = Node(start, None)
goal_node = Node(end, None)
# Add the start node
open_nodes.append(start_no... | 5,324,944 |
def update_wf_library(pulses, path):
"""
Update the waveform library in-place.
Parameters
------------
pulses : iterable of pulse object to update
e.g. [X90(q1), X(q1), Y90(q1), Y(q1), X90(q2), X(q2), Y90(q2), Y(q2), ZX90_CR(q1, q2)]
path : path to base name of files to update e.g. /pat... | 5,324,945 |
def generate_charts_and_data() -> None:
"""Generate and print the data used in the cool extras section.
Save the relevant charts in the cool extras folder.
"""
graph = get_dataset_data.get_song_graph_from_decades(DECADES)
print('Most similar attributes:',
most_similar_continuous_attr(gra... | 5,324,946 |
def is_water(residue):
"""
Parameters
----------
residue : a residue from a protein structure object made with PDBParser().
Returns
-------
Boolean
True if residue is water, False otherwise.
"""
residue_id = residue.get_id()
hetfield = residue_id[0]
return hetfield[0... | 5,324,947 |
def _step(context, url):
"""
:type context: HackedContext
"""
context.driver.get(url) | 5,324,948 |
def import_all_item_types():
"""
Imports all eve item types. This should only be called once when the database is initially set up.
:param self:
:return:
"""
client = EsiClient()
page_count = client.get_page_count("/v1/universe/types/")
logger.info("{} pages of items to download".format... | 5,324,949 |
def gelu(input_tensor):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
input_tensor: float Tensor to perform activation.
Returns:
`input_tensor` with the GELU activation applied.
"""
cdf = 0.5 * (1.0 + tf.erf(input_tens... | 5,324,950 |
def index():
""" Route for signing the policy document or REST headers. """
request_payload = request.get_json()
if request_payload.get('headers'):
response_data = sign_headers(request_payload['headers'])
else:
credential = [c for c in request_payload['conditions'] if 'x-amz-credential'... | 5,324,951 |
def create_template_bridge(self):
"""Return the template bridge configured."""
if self.config.template_bridge:
templates = self.app.import_object(
self.config.template_bridge, 'template_bridge setting')()
else:
from sphinx.jinja2glue import BuiltinTemplateLoader
te... | 5,324,952 |
def scan(basedir, scanner=SCANNER):
"""Scan basedir, return Fileset models, log warning for broken sets"""
logger = getLogger(__name__)
scanners = scanner.values()
for filesetinfo in detect_filesets(basedir, scanners):
try:
fileset = make_fileset(filesetinfo)
except BrokenFil... | 5,324,953 |
def getIcons(xml):
"""
Print out all icons found in xml
"""
doc = minidom.parse(xml)
node = doc.documentElement
fdroidNode = doc.firstChild
counter = 0
icon = fdroidNode.getElementsByTagName("icon")
iconsnames = []
for iconlocation in icon:
iconsObj = icon[counter].firstChi... | 5,324,954 |
def test_one_no_min_limit_correct_number():
"""Parse a limited number."""
args = CommandArgs()
number = args.add_argument("number")
number.max_limit = None
result = args.parse(None, "120")
assert bool(result)
assert result.number == 120 | 5,324,955 |
def make_answer(rdtype, answers=None, additionals=None, authorities=None):
"""For mocking an answer. We make an answer without any message (what would
normally come over the network, to be parsed. We instead make a blank
object for the sake of test complexity, and later attach the appropriate\
rrsets to... | 5,324,956 |
def consolidate_payoff_results(period, reporter_configuration, simulation_output, score_map, priority_based):
"""
Gather per-run metrics according to a simulation result.
:param resolved_per_reporter: Resolved issues per priority, including a priority detail.
:param period: Description of the period.
... | 5,324,957 |
def write_sentence_tabs(t, f, fmt=3):
"""writes a sentence in export format
and does NOT write the #EOS
"""
for n in t.terminals:
if n.parent:
parent_id = n.parent.id
else:
parent_id = '0'
extra = ''
if hasattr(n, 'secedge') and n.secedge is no... | 5,324,958 |
def artPuttyCtx(*args, **kwargs):
"""
This is a context command to set the flags on the artAttrContext, which is the base context for attribute painting operations.
Returns: None
"""
pass | 5,324,959 |
def single_ray_belief_propagation(
S,
ray_voxel_indices,
ray_to_occupancy_accumulated_pon,
ray_to_occupancy_messages_pon,
output_size
):
"""Run the sum product belief propagation for a single ray
Arguments
---------
S: tensor (M,) dtype=float32
The depth probability distribut... | 5,324,960 |
def cse_postprocess(cse_output):
""" Perform CSE Postprocessing
:arg: output from SymPy CSE with tuple format: (list of ordered pairs that
contain substituted symbols and their replaced expressions, reduced SymPy expression)
:return: output from SymPy CSE where postprocessing... | 5,324,961 |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Configure the sensor platform for home assistant."""
scan_interval = hass.data[DATA_KEY]
_LOGGER.info("scan interval= %s", scan_interval)
lightwave_devices = [
LightwaveEnergy("CURRENT_USAGE", scan_interval),
Lightwav... | 5,324,962 |
def lap(j, s, alpha):
""" Laplace coefficient """
def int_func(x):
return np.cos(j*x)/(1. - (2.*alpha*np.cos(x)) + alpha**2.)**s
integral = integrate.quad(int_func, 0., 2.*np.pi)[0]
return 1./np.pi*integral | 5,324,963 |
def calendar_add():
"""Adds a calendar to the database according to the infos in POST data.\
Also creates the calendar in google calendar service if no google_calendar_id is present in POST data.
"""
calendar_name = request.form["calendar_name"]
std_email = request.form["std_email"]
google_... | 5,324,964 |
def proportional_allocation_by_location_and_activity(df, sectorcolumn):
"""
Creates a proportional allocation within each aggregated sector within a location
:param df:
:param sectorcolumn:
:return:
"""
# tmp replace NoneTypes with empty cells
df = replace_NoneType_with_empty_cells(df)
... | 5,324,965 |
def Console():
""" Factory method that returns the Console object most appropriate for the current OS envrionment. """
if os.name == "posix":
return POSIXConsole()
elif os.name == "nt":
return NTConsole()
else:
raise NotImplementedError("Console support not implemented for OS '{... | 5,324,966 |
def handle_set_ms(msg, value):
"""
Handles an incoming 'set_<on/off>_ms' MQTT message.
:param msg: The incoming MQTT message
:type msg: paho.mqtt.client.MQTTMessage
:param value: The value to set the output to
:type value: bool
:return: None
:rtype: NoneType
"""
try:
ms =... | 5,324,967 |
def tests():
"""
Run Python unit tests.
"""
with settings(warn_only=True):
local('createdb elections14test')
local('nosetests') | 5,324,968 |
def prepare_target():
"""
Creates a example target face
:return: list of RFTargetVertex
"""
# size = 2
# target = [
# rfsm.RFTargetVertex(0, 0, 0, -size, -size),
# rfsm.RFTargetVertex(0, 1, 1, -size, size),
# rfsm.RFTargetVertex(1, 1, 1, size, size),
# rfsm.RFTarg... | 5,324,969 |
def data_fixture():
"""Fixture data."""
data = json.loads(load_fixture("data.json", "evil_genius_labs"))
return {item["name"]: item for item in data} | 5,324,970 |
def vectorize(sentence, idf_weight, vocab, convey='idf'):
"""
idf_weight: {word: weight}
vocab: {word: index}
"""
vec = np.zeros(len(vocab), dtype=np.float32)
for word in sentence:
if word not in vocab:
continue
if convey == 'idf':
vec[vocab[word]] += idf_... | 5,324,971 |
def ln_s(orig, new, verbose=False, force=False):
"""Create symbolic link.
Parameters:
-----------
orig: string
Name of original file
new: string
Name of new, to be created, link
verbose: bool
Verbose output
force: bool
If True, link creation is forced even if... | 5,324,972 |
async def director_v2_service_mock(
aioresponses_mocker: AioResponsesMock,
) -> AioResponsesMock:
"""mocks responses of director-v2"""
# computations
create_computation_pattern = re.compile(
r"^http://[a-z\-_]*director-v2:[0-9]+/v2/computations$"
)
get_computation_pattern = re.compile(... | 5,324,973 |
def test_validation_unset_type_hints():
"""Test that unset type hints are handled correctly (and treated as Any)."""
@my_registry.optimizers("test_optimizer.v2")
def test_optimizer_v2(rate, steps: int = 10) -> None:
return None
config = {"test": {"@optimizers": "test_optimizer.v2", "rate": 0.1... | 5,324,974 |
def get_online_featurestore_connector(featurestore=None):
"""
Gets a JDBC connector for the online feature store
Args:
:featurestore: the feature store name
Returns:
a DTO object of the JDBC connector for the online feature store
"""
if featurestore is None:
featurestore ... | 5,324,975 |
def detect_iterative(scales,
counts,
background,
exposure,
output_fits,
output_regions,
debug_output_folder,
overwrite):
"""Run an iterative multi-scale source detection... | 5,324,976 |
def run():
"""requirement for 1F"""
stations = build_station_list()
inconsistent_list = inconsistent_typical_range_stations(stations)
station_names = []
print(len(inconsistent_list))
# convert a list of inconsistent station objects to a list of their names
for n in range (len(inconsistent_li... | 5,324,977 |
def create_multipoint_geometry(u, v, osr_spref):
"""
wrapper; creates multipoint geometry in given projection
Parameters
----------
u : list of numbers
input coordinates ("Rechtswert")
v : list of numbers
input coordinates ("Hochwert")
osr_spref : OGRSpatialReference
... | 5,324,978 |
def validate_features_library(features_extraction_library_name):
"""Returns the injected features extraction library"""
validate_importing_features_extraction_library(features_extraction_library_name) | 5,324,979 |
def _CheckChromeRevOption(_option, _opt_str, value, parser):
"""Validate the chrome_rev option."""
value = value.strip()
if value not in constants.VALID_CHROME_REVISIONS:
raise optparse.OptionValueError('Invalid chrome rev specified')
parser.values.chrome_rev = value | 5,324,980 |
def extract_zip(fpath):
"""
Extracts zip file into the containing directory.
"""
with ZipFile(fpath, 'r') as zip_ref:
for m in tqdm(
iterable=zip_ref.namelist(),
total=len(zip_ref.namelist()),
desc='Extracting `{}`'.format(os.path.split(fpath)[1]))... | 5,324,981 |
def log_format_elk(app_name, port, ip, elk_sign="elk"):
"""
:param app_name: 要建立索引的名称
:param elk_sign: 需要添加的过滤关键词
:return:
"""
"""
获得Elastic Search的 Handler
:return:
"""
handler = logstash.TCPLogstashHandler(ip, port=port, version=1, message_type=app_name)
# 添加filter,只发送erro... | 5,324,982 |
def open_tif_image(input_path):
# type: (function) -> np.array
"""Function to open tif images.
Parameters:
input_path (string) = path where the image file is located;
return
np.array of the tif image"""
# get the image_path.
image_path = input_path
# rea... | 5,324,983 |
def check_is_valid_torchvision_architecture(architecture: str):
"""Raises an ValueError if architecture is not part of available torchvision models"""
available = sorted(
name
for name in torchvision.models.__dict__
if name.islower()
and not name.startswith("__")
and call... | 5,324,984 |
def get_icd(url: str) -> requests.Response:
"""Get an ICD API endpoint."""
return requests.get(url, headers=get_icd_api_headers()) | 5,324,985 |
def evaluate(words,labels_pred, labels):
"""
labels_pred, labels, words: are sent-level list
eg: words --> [[i love shanghai],[i love u],[i do not know]]
words,pred, right: is a sequence, is label index or word index.
Evaluates performance on test set
"""
# true_tags = ['PER', 'LOC', 'ORG', 'PERSON', 'person', ... | 5,324,986 |
def getApproximateArialStringWidth(st: str) -> float:
"""Calculate rough width of a word in a variable width font.
By https://stackoverflow.com/users/234270/speedplane
Args:
st (str): The string you need a width for
Returns:
float: The rough width in picas
To make sure that the na... | 5,324,987 |
def prepare_text(input_string):
"""Converts an input string into a list containing strings.
Parameters
----------
input_string : string
String to convert to a list of string.
Returns
-------
out_list : list
List containing the input string.
"""
# ... | 5,324,988 |
def update(ctx):
"""Update asset."""
pass | 5,324,989 |
def TDF_Tool_TagList(*args):
"""
* Returns the entry of <aLabel> as list of integers in <aTagList>.
:param aLabel:
:type aLabel: TDF_Label &
:param aTagList:
:type aTagList: TColStd_ListOfInteger &
:rtype: void
* Returns the entry expressed by <anEntry> as list of integers in <aTagList>.... | 5,324,990 |
def img(header, body=None):
"""Alternate to Markdown's image tag. See
http://octopress.org/docs/plugins/image-tag/ for usage."""
attrs = re.match(__img_re, header).groupdict()
m = re.match(__img_re_title, attrs['title'])
if m:
attrs['title'] = m.groupdict()['title']
attrs['alt'] = ... | 5,324,991 |
def conexao_bd():
"""
Função que se conecta a um banco de dados MySQL
"""
# Pedido de senha caso o acesso ao BD necessite
# caso contrario so dar ENTER
conexao = sql.connect(
host='localhost',
user='root',
password=senha
)
cursor = conexao.cursor()
return c... | 5,324,992 |
def test_map_class_pass_4(example_results, tmpdir, read_image):
""" Make a map with reasonable inputs, --before, --after, --qa,
--predict-proba switches
"""
image = tmpdir.join('classmap.gtif').strpath
runner = CliRunner()
result = runner.invoke(
cli,
['-v', 'map',
'--ro... | 5,324,993 |
def fill_bin_content(ax, sens, energy_bin, gb, tb):
"""
Parameters
--------
Returns
--------
"""
for i in range(0,gb):
for j in range(0,tb):
theta2 = 0.005+0.005/2+((0.05-0.005)/tb)*j
gammaness = 0.1/2+(1/gb)*i
text = ax.text(theta2, gammaness, "... | 5,324,994 |
def main(args=None):
"""
Console script for grumpy_tools.
The default command `grumpy run` will ran if no other selected.
It mimics the CPython options, when possible and applicable.
Please take a look on `grumpy run --help` for its implemented options.
Example: all the following lines outputs... | 5,324,995 |
def secure_account(account):
"""A utility function that secures accounts.
It just generates a PBKDF2 encrypted password hash.
"""
account['password'] = pbkdf2_sha256.encrypt(
account['password'],
rounds=20000,
salt_size=16
) | 5,324,996 |
def main():
""" Print out all of the options available to ForceBalance. """
options = None
tgt_opts = [None]
if len(sys.argv) == 2:
options, tgt_opts = parser.parse_inputs(sys.argv[1])
out = []
out.append("# ForceBalance input file generated by MakeInputFile.py")
out.append("# The oc... | 5,324,997 |
def blackbody1d(temperature, radius, distance=10*u.pc,
lambda_min=2000, lambda_max=10000, dlambda=1):
"""
One dimensional blackbody spectrum.
Parameters
----------
temperature : float or `~astropy.units.Quantity`
Blackbody temperature.
If not a Quantity, it is assume... | 5,324,998 |
def expm1_op_tensor(x):
"""
See :func:`oneflow.expm1`
"""
return Expm1()(x) | 5,324,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.