content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ridgeTest(xArr, yArr):
"""
Desc:
函数 ridgeTest() 用于在一组λ上测试结果
Args:
xArr:样本数据的特征,即 feature
yArr:样本数据的类别标签,即真实数据
Returns:
wMat:将所有的回归系数输出到一个矩阵并返回
"""
xMat = np.mat(xArr)
yMat = np.mat(yArr).T
# 计算Y的均值
yMean = np.mean(yMat, 0)
yMat = yMat - yMe... | 96da9f5c94fd3fd8ae2fadd8ea107337fc7fe71e | 39,300 |
def gumbel_softmax(logits, temperature, hard=True):
"""Sample from the Gumbel-Softmax distribution and optionally discretize.
Args:
logits: [batch_size, n_class] unnormalized log-probs
temperature: non-negative scalar
hard: if True, take argmax, but differentiate w.r.t. soft sample y
Returns:
[bat... | 8b8b8aa357b4d399f3cb672d21c02087a7997165 | 39,301 |
def create_Walternating_layered_ansatz(qc: qiskit.QuantumCircuit,
thetas: np.ndarray,
num_layers: int = 1):
"""Create Walternating layered ansatz
Args:
- qc (qiskit.QuantumCircuit): init circuit
- thetas (np.ndarray): par... | 623a5adaec0e0f003fb17ca295274d809ef4511d | 39,302 |
def screen(corners, h=0.1):
"""
Creates a screen.
Parameters
----------
corners : np.ndarray
A (4 x 3) array that defines four corners of the screen.
h : float
A floating point number specifying the grid size.
Output
-------
grid : bempp.Grid
A structured gr... | 3080412baa596e4b15312911ac5ac3c6689b91bb | 39,303 |
def execute(sql, con, cur=None, params=None, flavor='sqlite'):
"""
Execute the given SQL query using the provided connection object.
Parameters
----------
sql : string
Query to be executed
con : SQLAlchemy engine or DBAPI2 connection (legacy mode)
Using SQLAlchemy makes it possi... | 694b9ef9c96768bcd5c845222ecf89a56b932dd4 | 39,304 |
def lower(s: "Stream[str]") -> "Stream[str]":
"""Computes the lowercase of a string stream.
Parameters
----------
s : `Stream[str]`
A string stream.
Returns
-------
`Stream[str]`
A lowercase string stream.
"""
return s.apply(lambda x: x.lower()).astype("string") | cf02e36d58f67a8269b496131e68135197af7873 | 39,305 |
def mean_feature(data, rolling_window, num):
"""Computes the mean for a given lag and its rolling window
Given a set number of lags in the past, a set rolling window and the input
dataset, computes the rolling average mean for the given window.
Parameters
----------
data: pd.Dataframe
... | 07e637b75eb5db6e1c53a5c6e6bb0aadc3fb18f9 | 39,306 |
def cmgListToWaterArray(stacks:list,product="MOD09CMG") -> "numpy array":
"""
This function takes a list of CMG .hdf files, and returns
a binary array, with "0" for non-water pixels and "1" for
water pixels. If any file flags water in a pixel, its value
is stored as "1"
***
Parameters
----------
stacks:list
... | 23663f3eb4f5e9fbcd556753261dd06831df1de0 | 39,307 |
def decode(packed_list):
"""
implement the function packed the string
"""
# Empty list of tuple
decode_str = ""
list_len = len(packed_list)
for i in range(list_len):
# element of packed list
str_tuple_count = packed_list[i]
# find number of counting from tuple
... | d6fe8de66ead935a14e99b069d3b416089d5a93d | 39,308 |
def travel_space_separated(curr):
"""Print space separated linked list elements."""
if curr is None:
return ""
print(curr.data, end=' ')
travel_space_separated(curr._next) | 19213588f06a569560b236563975bcd6cb5254a0 | 39,309 |
import urllib
import re
import os
def get_PDF_content(query_string, link):
"""
Gets all of the text from a PDF document
Parameters
----------
query_string : string
the query that generated the PDF document
link : string
the URL for the document
Returns
-------
... | 03e89c411a344699dc3de5911d089ff09ad43ba8 | 39,310 |
def _generate_subparser(parser, name, description=None, subcommand=False):
"""Helper function to return a subparser with the given options"""
subparser = parser.add_parser(
name,
description=description,
formatter_class=RawDescriptionHelpFormatter
)
if subcommand:
subpar... | e538f931e4ec0129f4b2416dc21d04d0afc0fc1d | 39,311 |
def identity_matrix(dim):
"""Construct an identity matrix.
Parameters
----------
dim : int
The number of rows and/or columns of the matrix.
Returns
-------
list of list
A list of `dim` lists, with each list containing `dim` elements.
The items on the "diagonal" are ... | dd37f0c7df41478e23dd26df727341a37a201ec1 | 39,312 |
def get_zscale(self):
"""Get the qcodes_colorbar scaling
:return: str "linear" or "log"
:raises: AttributeError
"""
if not hasattr(self, 'qcodes_colorbar'):
raise AttributeError("Axes object does not have a colorbar.")
if isinstance(self.qcodes_colorbar.formatter, ticker.LogFormatter):... | 4a2d43c219ed041b3b664bc8d4eff4663b60e18f | 39,313 |
def train_logistic_regression(X_train, y_train, X_val, y_val, min_coef=1, max_iter=2000):
"""
Logistic regression training algorithm on binary features
:param X_train: Pandas DataFrame of train set features
:param y_train: Pandas Series of train set binary target
:param X_val: Pandas DataFrame of v... | 801dc7ef3a60cdde68ef88a39163900cedf3cb7a | 39,314 |
def result2list(foo):
"""Convert from ParseResults to normal list."""
if isinstance(foo, ParseResults):
return [result2list(bar) for bar in foo]
else:
return foo | 03f4c34ed49b44407740fbae7dac9cbebab017db | 39,315 |
def cluster_shutdown(cluster):
"""
Shutdown an entire cluster, cancelling any spot
requests and terminating all instances in the cluster.
Also permanently deletes any record of the cluster.
RouteParams:
cluster: the name of a cluster
Returns:
A status code indicating success
... | 7c92e8ef8eba1ecd5545e843b0905b93b0a83754 | 39,316 |
def collect_jsonschema_errors(metadata, convention, bq_json=None):
"""Evaluate metadata input against metadata convention using JSON schema
returns False if input convention is invalid JSON schema
"""
# this function seems overloaded with its three tasks
# schema validation, non-ontology errors, ont... | 2b7f8b3aa0bfdd5d542376d9ce784c5055d239ad | 39,317 |
def kg2m3H2O_hot(kg):
"""kg -> m^3 (50 C hot water)"""
return kg/988.1 | 060b039db404014ab6cbea6aa5e416efc70aa8a2 | 39,318 |
def print_debug(name, *args, **kwargs):
"""Printing Debug
Function to display formatted output in decorator options
Args:
name: Name of Process [like "Function Source:"]
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
Returns:
called print fu... | 7e2db63afce608ee9be0ab93470050104891d6bd | 39,319 |
from typing import List
def feeder(url: str, archived: bool, archived_only: bool, verbose: bool) -> List[str]:
"""Create and return a list of urls according to the input."""
thread_urls = []
# list of thread urls
if url.endswith(".txt"):
with open(url, "r") as f:
thread_urls.extend... | d51f9f1b0f1af4ade834692febe77bca5c1b21c9 | 39,320 |
from typing import OrderedDict
import re
def convert_torch_resnet_weights_to_serialClassificationNet(model, state_dict, strict=True):
"""Convert resnet weights from torchvision to vega weights name."""
names = convert_names(model)
new_state_dict = OrderedDict()
for name in names:
state_name = ... | c827466270fdfce31b1a82f8352e17ac5e02d18e | 39,321 |
import sys
from textwrap import dedent
import re
import hashlib
def main(argv):
"""
Main program
"""
if len(argv) < 2:
print("Usage: {0} <input.cl>... <output.cpp>".format(sys.argv[0]),
file = sys.stderr)
return 2
with open(sys.argv[-1], 'w') as outf:
print... | a173ee2251bc2ccbe871abde77e393172cbdf7a6 | 39,322 |
import yaml
def load_yaml(file_path):
"""Load a yaml file into a dictionary"""
try:
with open(file_path, 'r') as file:
return yaml.safe_load(file)
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
return None | 3d4fa37794bc99c352959e49057d2e9cfb0d4c92 | 39,323 |
from typing import Set
def build_column(min_trays, max_trays, xD, xB):
"""Builds the column model."""
m = ConcreteModel('benzene-toluene column')
m.comps = Set(initialize=['benzene', 'toluene'])
min_T, max_T = 300, 400
max_flow = 500
m.T_feed = Var(
doc='Feed temperature [K]', domain=N... | 82029468a6817fc3c49c370d920421197c60a220 | 39,324 |
def coerce(fun):
"""Decorates a function and coerces each of the inputs of the function into a
Forward object.
Many of our functions would like to operate on Forward objects instead of raw
values. For example, __add__ might get an integer in the case of Forward('x', 5)
+ 2, but we want the 2 to be ... | 1fa28f6d12dabe6c2ca6ecfa05b567ee4d432608 | 39,325 |
def DatasetWithIndices(cls):
"""
Modifies the given Dataset class to return a tuple data, target, index
instead of just data, target.
"""
def __getitem__(self, index):
data, target = cls.__getitem__(self, index)
return data, target, index
return type(cls.__name__, (cls,), {
... | a8ccdaf26755e92f471c5b0dc330eab86f1b2a31 | 39,326 |
def hex_int_range(min=None, max=None, min_included=True, max_included=True):
"""Validate that the config option is an integer in the given range."""
return All(
hex_int,
Range(min=min, max=max, min_included=min_included, max_included=max_included),
) | 0d6feaf9c7086f6513e3658a1a857f853c4e5567 | 39,327 |
import requests
def execute_graphql_request(payload):
"""Execute queries and mutations on the GraphQL API."""
url = 'http://graphql:5433/graphql' # Should be moved to config file
headers = {'Content-Type': 'application/graphql'}
response = requests.post(url, headers=headers, data=payload)
status ... | d12d30722dccbdd8f1c89084e66f37ef3febf9d0 | 39,328 |
def s3_put(bucket_name, file_path, file_name, payload):
"""
Use for Uploading a file as StringIO object
:param str bucket_name: s3 bucket name
:param str file_path: string name, sub folders are allowed
:param str file_name: name that you need to be in destination S3 Bucket location
:param String... | 086ab5ce4a58cc76b214a75bbe56acb5d3265069 | 39,329 |
def add_contrastive_loss(hidden,
hidden_norm=True,
temperature=1.0,
tpu_context=None,
weights=1.0):
"""Compute the instance discrimination loss for the model.
Args:
hidden: hidden vector (`Tensor`) of shape (bsz... | 63c26c03b02b32277a1eb39417054a37d5e6c63f | 39,330 |
import time
def timed_call(f, args):
"""Call function f with arguments args and time its run time.
Args:
f: The function to call
args: The arguments to pass to f
Returns:
Return the result of the function call and how much time it takes as tuple e.g. (result, time).
"""
s... | e592ecdf5ebb4aa3391b2500b2a3a20d2faa9b40 | 39,331 |
def count_words(texts):
"""
Counts the words in the given texts, ignoring puncuation and the like.
@param texts - Texts (as a single string or list of strings)
@return Word count of texts
"""
if type(texts) is list:
return sum(len(t.split()) for t in texts)
return len(texts.split()) | f08cbb1dcac3cbd6b62829cf4467167ae9b7694e | 39,332 |
def train_circuit(circuit,n_params,n_cnots,X_train,Y_train,X_test,Y_test,optim,optimoptions,inference='wall_clock',rate_type='accuracy',**kwargs):
"""Develop and train your very own variational quantum classifier.
Use the provided training data to train your classifier. The code you write
for this challeng... | 5ef9cbb31bf89c81fdb98a335f85da7a6efe36ce | 39,333 |
def calvin_astgen(source_text, app_name, verify=True):
"""
Generate AST from script, return processed AST and issuetracker.
Parameter app_name is required to provide a namespace for the application.
Optional parameter verify is deprecated, defaults to True.
"""
cg, issuetracker = _calvin_cg(sou... | 63e9a9d169781174a7dfe2d415564160dd7f761f | 39,334 |
import os
import stat
import mimetypes
def file_response(request, filepath, block=None, status_code=None,
content_type=None, encoding=None, cache_control=None):
"""Utility for serving a local file
Typical usage::
from pulsar.apps import wsgi
class MyRouter(wsgi.Router):
... | d320f9071f3ed032698e480f5f04f83e121f3e2b | 39,335 |
def fit(*views):
""" Convenience method to both enable and apply natural fit width and
height constraints with one call. Useful mainly for Buttons and Labels.
You can provide several views, first view is returned. """
for view in views:
enable(view)
view.dock.fit()
return views[0] | a11a525874a46ae5748f6d516e7a652adea6f866 | 39,336 |
def get_subnetwork(project_id, context):
""" Gets a subnetwork name. """
subnet_name = context.properties.get('subnetwork')
is_self_link = '/' in subnet_name or '.' in subnet_name
if is_self_link:
subnet_url = subnet_name
else:
subnet_url = 'projects/{}/regions/{}/subnetworks/{}'
... | de0217b7a78d3278d6dbf70db10b4c270aff2b15 | 39,337 |
def TC_NTU(T1,T2,T3,T4,NTU):
"""
Outlet temperature of the cold side of the heat exchanger with given number of transfer units (for a counterflow heat exchanger only)
"""
C = (T1 - T2) / (T4 - T3)
if C<1:
E = (1 - exp((C - 1) * NTU)) / (1 - C*exp((C - 1) * NTU))
Ecold = E... | 0186026757d0ac8da45821315c38e0846ad328c0 | 39,338 |
def quadraticEval(a, b, c, x):
"""given all params return the result of quadratic equation a*x^2 + b*x + c"""
return a*(x**2) + b*x + c | cfb808435b50ec262ec14cd54cf9caf30f2bc4b8 | 39,339 |
def file_format_from_suffix(file_suffix: str) -> FileFormat:
"""Returns the file format associated with the file extension (`tfrecord`)."""
if file_suffix not in _FILE_SUFFIX_TO_FORMAT:
raise ValueError('Unrecognized file extension: Should be one of '
f'{list(_FILE_SUFFIX_TO_FORMAT.values()... | f6dc5bc65174d3154663c1dca043144a4577e42e | 39,340 |
def upgrade_tarball_install(config, new_tarball, preserve_old_install):
"""Performs an upgrade for an existing Scalyr Agent 2 that was previously installed using the tarball method.
@param config: The configuration for this agent.
@param new_tarball: The path to file containing the new tarball to install.
... | 87d91294a565881f0cf648d8b8396eff631a240f | 39,341 |
from typing import List
def grab_std_includes(headers: List[str], sources: List[str]) -> List[str]:
"""Grab all std includes from headers and sources"""
total_std_includes: List[str] = []
for header in headers + sources:
with open(header) as file:
lines = file.readlines()
... | d1ad1ffc6c53134c95002c88e591349f355f5473 | 39,342 |
def get_testcase_params():
"""
Returns the list of testcase parameters from the configuration file
:return: dict
"""
testcase_parameters = dict()
parameters = CONF_FILE.get_variable_list(cf.CFS_TESTCASE_PARAMETERS)
for param in parameters:
testcase_parameters[param] = CONF_FILE.get_... | 1b4d4fd704be348def8bedbec09c2380b2a35412 | 39,343 |
def job_get_script_list(request, biz_cc_id):
"""
查询业务脚本列表
:param request:
:param biz_cc_id:
:return:
"""
# 查询脚本列表
client = get_client_by_request(request)
script_type = request.GET.get('type')
kwargs = {
'bk_biz_id': biz_cc_id,
'is_public': True if script_type == '... | ccdf1a0d6c9b95ab229be30eab1ef67ed80a6dbf | 39,344 |
def stringdb_escape_text(text):
"""Escape text for database_documents.tsv format."""
return text.replace('\\', '\\\\').replace('\t', '\\t') | 5d41b0b224cb314141b669ff721896d04a2fe2e8 | 39,345 |
import logging
import tempfile
def process_impact_task(source_id, message):
"""Process an impact task."""
logging.info('Processing impact task for %s', source_id)
regress_result = ndb.Key(osv.RegressResult, source_id).get()
if not regress_result:
logging.error('Missing RegressResult for %s', source_id)
... | e0dd7311aece8970eb0e961384fd72cdd2f07194 | 39,346 |
import argparse
def parse_args():
"""
Parse command arguments.
"""
parser = argparse.ArgumentParser(description='validate data from starbust algo I for test (ex. chessboard test)')
parser.add_argument('path', help='path to starburst filtered file')
return parser.parse_args() | 544372e75b2dd56923883f13b6c7f3070ecc9e14 | 39,347 |
import sys
import traceback
def get_spyderplugins_mods(prefix, extension):
"""Import modules that match *prefix* and *extension* from
`spyderplugins` package and return the list"""
modlist = []
for modname in get_spyderplugins(prefix, extension):
name = 'spyderplugins.%s' % modname
try... | 6ac7df43d8d768673b46e26d99ba4d35f6f67029 | 39,348 |
import torch
def in_parallel(model, device_ids):
"""
Wraps a model in a DataParallel module such that it supports
an input dictionary for multiple inputs rather than kwargs.
"""
return RemoveStatePrefix(DictToKwargs(torch.nn.DataParallel(
KwargsToDict(model), device_ids)), 'module.modu... | acb707311ea2aff49ac33636565b69fb1643a8d2 | 39,349 |
def mean_ap(dist_mat, query_ids, gallery_ids, query_cams, gallery_cams):
"""Compute mean average precision (mAP)"""
dist_mat = dist_mat.cpu().numpy()
m, n = dist_mat.shape
query_ids = np.asarray(query_ids)
gallery_ids = np.asarray(gallery_ids)
query_cams = np.asarray(query_cams)
gallery_cams... | 05e79c4b4d0c0407a823c8c8985c7a3c51a8ceaf | 39,350 |
def check_account_age(key):
"""
Searches DynamoDB for stored user_id or account_id string stored by indicator creation
rules for new user / account creation
"""
if isinstance(key, str) and key != "":
return bool(get_string_set(key))
return False | e26a98eccefa32c2e5319bd550629818a68d8ccc | 39,351 |
def _is_cluster_volume(cluster_id, ebs_volume):
"""
Helper function to check if given volume belongs to
given cluster.
:param UUID cluster_id: UUID of Flocker cluster to check for
membership.
:param boto.ec2.volume ebs_volume: EBS volume to check for
input cluster membership.
:... | 331d4f2a441718dffb8c529b570b9d285ff1a162 | 39,352 |
def serialize_sqla(data):
"""Serialiation function to serialize any dicts or lists containing
sqlalchemy objects. This is needed for conversion to JSON format."""
# If has to_dict this is asumed working and it is used.
if hasattr(data, 'to_dict'):
return data.to_dict()
if hasattr(data, '__d... | d1f91dc42054bbe250d9145bc0c2223224b59be1 | 39,353 |
def friends(graph, user):
"""Returns a set of the friends of the given user, in the given graph"""
return set(graph.neighbors(user)) | 125c3cc21be4cc29f9ff6f0ff0bb60b35a1074ba | 39,354 |
import xml
def _ValueOrPlaceHolder(value_string, description):
"""Embeds a string inside an XML <value>...</value> element.
If the string is empty or None, an alternate string is used instead.
Args:
value_string: String to embed
description: String to be used if the value string is empty or None.
R... | c784a5adff28cb5fd9c30f5d30eee56e318c433f | 39,355 |
from typing import List
from typing import Tuple
from typing import Callable
def get_input_labels(
io_gratings: List[ComponentReference],
ordered_ports: List[Port],
component_name: str,
layer_label: Tuple[int, int] = (10, 0),
gc_port_name: str = "o1",
port_index: int = 1,
get_input_label_t... | d64f916a533e351d2a5a447daf0f0f204a7350e1 | 39,356 |
def process_NNC(chrom, positions, strand, edge_IDs, vertex_IDs, transcript_dict,
gene_starts, gene_ends, edge_dict, locations, vertex_2_gene, run_info):
""" Novel not in catalog case """
novelty = []
start_end_info = {}
gene_ID = find_gene_match_on_vertex_basis(vertex_IDs, strand, vert... | 066d208aa091e51885c5adff7497af2d6003383c | 39,357 |
def RLT(n, f):
"""run length transform of a function f"""
return prod(f(len(d)) for d in split("0+", bin(n)[2:]) if d != "") if n > 0 else 1 | e52cb3c806e2d0e8d0dd1e47082bacf090827799 | 39,358 |
def diagonal(a, offset=0, axis1=None, axis2=None, extract=True, axes=None):
"""
diagonal(a, offset=0, axis1=None, axis2=None)
Return specified diagonals.
If `a` is 2-D, returns the diagonal of `a` with the given offset,
i.e., the collection of elements of the form ``a[i, i+offset]``. If
`a` h... | e18a9ca2dcab7beb5891f701cdc0f26c3943f749 | 39,359 |
import argparse
def get_arguments():
"""
Defining the arguments available for the script
:return: argument parser
"""
parser = argparse.ArgumentParser()
# Ads setting
parser.add_argument("-bud", "--cum_budget", default=CUM_BUDGET,
help="Cumulative budget to be use... | 17fb27206306392568222f5246100de2dc80fec8 | 39,360 |
def _check_expression(text, allowed_variables=None):
"""
>>> allowed_variables = ["c1", "c2", "c3", "c4", "c5"]
>>> _check_expression("c1", allowed_variables)
True
>>> _check_expression("eval('1+1')", allowed_variables)
False
>>> _check_expression("import sys", allowed_variables)
False
... | 2b860082a1902d0ce3564f1ff6db9bd90457a5e6 | 39,361 |
import os
def build_exception_info(item_name, exc_type, exc_value, traceback):
"""Generate description info about exceptions."""
exc_info = None
if exc_type and (exc_type, exc_value, traceback) != pytest.item_status_info[item_name].get("exc_info", None):
if exc_type is AssertionError:
... | c22e9cc4cc3493718a96de417304c278be597ed9 | 39,362 |
from pathlib import Path
def build_algod_local_client(data_dir: Path) -> AlgodClient:
"""
Build the `algod` client to interface with the local daemon whose
configuration is at `data_dir`.
Args:
data_dir: the path with the network data
Returns:
the client connected to the local al... | b1921cd3eb3468ff1b6d556da7c436dce405021f | 39,363 |
def set_read_only(khoros_object, enable=True, msg_id=None, msg_url=None, suppress_warnings=False):
"""This function sets (i.e. enables or disables) the read-only flag for a given message.
:param khoros_object: The core :py:class:`khoros.Khoros` object
:type khoros_object: class[khoros.Khoros]
:param en... | 0a3849d3e589b668d465ac9d2bbd1d13fb346ed5 | 39,364 |
def reports_download(request, file_name):
"""Generic method for downloading files."""
try:
file_path = '%s/%s' % (MEDIA_ROOT, file_name)
fp = open(file_path, 'rb')
response = HttpResponse(fp.read())
fp.close()
mime_type, encoding = mimetypes.guess_type(file_name)
... | 8ce3124304d340a3ff4892ab1c63f90f38f9ee42 | 39,365 |
def bucket_sort(array: list[int]) -> list[int]:
"""
Time Complexity of Solution:
Worst Case: occurs when all the elements are placed in a single bucket.
The overall performance would then be dominated by the algorithm used to sort each
bucket. In this case, O(n log n), because of TimSort.
Avera... | 744165384ad1e562c0acd695e90676dcced8db79 | 39,366 |
def create_tokenizer_from_hub_module():
"""Get the vocab file and casing info from the Hub module."""
with tf.Graph().as_default():
bert_module = hub.Module(BERT_MODEL_HUB)
tokenization_info = bert_module(signature="tokenization_info", as_dict=True)
with tf.Session() as sess:
vocab_file, do_lower_... | 0782b6c66253ce053ef693b3dba9006fff2ce8e1 | 39,367 |
def get(package, plugin):
"""Get a given plugin"""
_import(package, plugin)
return _PLUGINS[package][plugin].func | e47d0c655d210515f7d1dae520f32943ea67f9d0 | 39,368 |
def read_paragraph_element(element):
"""Returns the text in the given ParagraphElement.
Args:
element: a ParagraphElement from a Google Doc.
"""
text_run = element.get('textRun')
if not text_run:
return ''
return text_run.get('content') | 96df0dc1c2ded0bdb1105bfacc4150c27f9e21c9 | 39,369 |
def telnet_read_eager(tn: ConnectionInformation, wf: object, current_output_log: [str], enable_removeLF: bool) -> str:
"""
Dealing with unread material.
"""
if tn.eof:
return False
try:
# current_output = tn.read_very_lazy() # Not recommended because it will be blocked.
cur... | d1d1a25b2345d2b1f0fcefe10d00c07b74051070 | 39,370 |
def parse_play(play):
"""
Parses formatted PLAY and returns ??? FIXME
"""
return None | 4e7375108594e24cbfd9eb1e723a4f91549ca69a | 39,371 |
def parse_int(integer, default=None):
"""提取整数,若失败则返回default值"""
try:
return int(integer)
except Exception, e:
return default | c064ab555763570515d97f403cf8a144f9598bc3 | 39,372 |
def ctd_sbe16digi_preswat(p0, t0, C1, C2, C3, D1, D2, T1, T2, T3, T4, T5):
"""
Description:
OOI Level 1 Pressure (Depth) data product, which is calculated using
data from the Sea-Bird Electronics conductivity, temperature and depth
(CTD) family of instruments.
This data product... | 3756752c661773bd74436311a278efdaa3d3913f | 39,373 |
import hashlib
def sha256(file: str):
"""
Reads a file content and returns its sha256 hash.
"""
sha = hashlib.sha256()
with open(file, "rb") as content:
for line in content:
sha.update(line)
return sha.hexdigest() | c6babc2939e25228df25827a5a0b383d6c68dd07 | 39,374 |
import logging
def make_div_share_variable(exposure_level=7, div_level=3):
"""Calculates the share of employment in a low diversification sector
Args:
exposure_level (int): min threshold for high exposure
div_leve (int): min threshold for low diversification
"""
_DIVISION_NAME_LOOKUP ... | a6b1ab48b40a4fd861f1d52faf5a83d00c35b08c | 39,375 |
def _user_has_perm(user, perm, obj):
"""
A backend can raise `PermissionDenied` to short-circuit permission checking.
"""
for backend in auth.get_backends():
if not hasattr(backend, 'has_perm'):
continue
try:
if backend.has_perm(user, perm, obj):
r... | bf5882e4fbef7b1d9fa1c971841565f43a6f2e93 | 39,376 |
def gcd(a, b):
""" Computes the greatest common divisor between the two numbers using
Euclid's algorithm.
"""
if b == 0:
return a
else:
return gcd(b, a % b) | 9ea816a44e1f3d117c621bf7841428d2d15e9c24 | 39,377 |
def rect_crop_2D(im, rect_spec):
"""following imageJ style rectangle specification"""
left, top, width, height = rect_spec
im_crop = im[top:top+height, left:left+width].copy()
return im_crop | 6af43a11eee580b537b236b57d063b3631465292 | 39,378 |
def encode_multipart_formdata(fields, files):
"""
@param fields: sequence of (name, value) elements for regular form fields.
@param files: sequence of (name, filename, value) elements for data to be
uploaded as files
@return: (content_type, body) ready for httplib.HTTP instance
"""
boun... | 70fc71f48eeb31e2dd41bb88cd060b00c5bb6e3a | 39,379 |
def coverage_err(y_true, y_pred):
"""
Coverage error:
For every sample, how far down the ranked list of predicted classes must we reach to get all
actual class labels? The average value of this metric across samples is the coverage error.
:param y_true: array of shape (n_samples, n_labels)
:par... | 4e28d7847714c47ab71473c1dbc0dfdef5e1653c | 39,380 |
def login(*args, **kwargs):
"""
Override view to use a custom Form
"""
kwargs['authentication_form'] = AuthenticationFormAccounts
return login_base(*args, **kwargs) | d3c7c926e7652254a927979451907a702ee1499a | 39,381 |
def _calculate_bearings(graph, nodes):
"""
Calculate the compass bearings for each sequential node paid in `nodes`. Lat/lon coordinates are expected to be
node attributes in `graph` named 'y' and 'x'.
Args:
graph (networkx graph): containing lat/lon coordinates of each node in `nodes`
... | 7ed04f75b12843a2f7a31a0bf384cb0b772d9f82 | 39,382 |
import uuid
import json
def fetch_perfmap(client_id=uuid.uuid4(), debug=False):
"""Grabs the perfmap information from the Fastly API endpoint
Returns:
json: the data to use for remaining perf data collection
"""
url = '/perfmapconfig.js?jsonp=FASTLY.setupPerfmap'
hostname = str(client_id)... | 8d3f71234582311f211f8899d591bf27db7666ec | 39,383 |
def lookup_capacity(lookup, environment, ant_type, frequency,
bandwidth, generation):
"""
Use lookup table to find the combination of spectrum bands
which meets capacity by clutter environment geotype, frequency,
bandwidth, technology generation and site density.
"""
if (environment, ant_ty... | 3bd132f97022acfe33c4bc6d706265e808679eae | 39,384 |
from typing import Any
def option(parser: Parser, otherwise: Any = None) -> Parser:
"""Create a parser that succeeds even when the given parser does not.
If nothing was parsed, then the value that was parsed is |otherwise|.
"""
def fn(parse_state):
"""Parse with parser, return value of None i... | dbc88037855b232881f0cdfe25d195d2985ef865 | 39,385 |
import json
def to_json(response):
""" Return a response as JSON. """
assert response.status_code == 200
return json.loads(response.get_data(as_text=True)) | 4fb4d62eb8b793363394b6d0759a923f90315072 | 39,386 |
def num(s):
"""This function is used to convert string to int or float."""
try:
return int(s)
except ValueError:
return float(s) | a3faae6fa4f166898b281f9e114fcff8abdcd2e3 | 39,387 |
from pathlib import Path
def equalize(request):
"""ヒストグラム平坦化関数"""
# キャッシュディレクトリを作成
cache_dir = Path(__file__).parent.joinpath('cache').joinpath('equalize')
cache_dir.mkdir(parents=True, exist_ok=True)
# 画像データをbase64形式で取得
base64image = request.POST.get('image')
# base64をバイナリデータに変換し、ヘッダーも同... | 18fd0b41baec1e49427238703f5345f9097c3ad3 | 39,388 |
def mutation_frequency(H, D):
"""
# ========================================================================
MUTATION FREQUENCY
PURPOSE
-------
Calculates the mutation frequency.
INPUT
-----
[INT] [H]
The number of haplotypes.
[2D ARRAY] [D]
A distance mat... | 688a0540be6e67834e3bdae527191f4275bae641 | 39,389 |
from datetime import datetime
def _parse_given(rtype: str, report: str, opts: [str]) -> (dict, int):
"""
Attepts to parse a given report supplied by the user
"""
try:
ureport = _HANDLE_MAP[rtype]("KJFK") # We ignore the station
ureport.update(report)
resp = asdict(ureport.data... | f9af0fadf16c37f9884ddb0d391e79878c55b87e | 39,390 |
def new_feature(signal):
"""Computes a new feature
Parameters
----------
signal : nd-array
Input from which new feature is computed
Returns
-------
float
new feature
"""
return np.mean(signal)-np.std(signal) | e85dd3edec1f824d64d645c0d32dfda751c52c4e | 39,391 |
import os
def __test_path(path, chk_type, nonexistent=None, not_ok_msg=None):
"""
Test a file path, to see if it is exists and is a file
:param path: path to filesystem object to check
:type chk_type: type to check for; __ISFILE or __ISDIR
:param nonexistent: message to display if nonexistent
... | b622b6c649e3833e789f17d9729447e8b82568a1 | 39,392 |
def SKPD_processing(Cov_MPMB, opt_str):
"""SKPD_processing
Kernel of the Sum of Kronecker Product Decomposition.
INPUT
Cov_MPMB: [N*Npol x N*Npol] covariance matrix
opt_str.
N: number of images
Npol: number of polarization... | bfd11c067acf0a71a3f00d99c43a63895281c9cd | 39,393 |
from typing import Optional
from typing import Tuple
def dhall_type(value: Property, name: str, types: Types, defs: Defs) -> Optional[Tuple[DhallType, Types]]:
"""Convert a property to a dhall type name. Also add newly discovered types to the list of types"""
_type: Optional[str] = None
# TODO: remove th... | 38a89eab99acef369f89f37d57036a2b857ddde4 | 39,394 |
def get_public_keys_of_user(session, user_id):
"""Retrieve all public keys for user.
Args:
session(models.base.session.Session): database session
user_id(int): id of user in question
Returns:
List of PublicKey model object representing the keys
"""
pkey = session.query(Publ... | ebb367bf8ed14f94d597bc4fc8942d6c51f3b0f2 | 39,395 |
def avgFriendDegree(v, Giant):
""" Calculate the average degree of the neighbors of a node"""
degSum = 0
for u in Giant.neighbors(v):
degSum += Giant.degree(u)
return degSum / Giant.degree(v) | 667213aeb0f66887c629aef784f83549ced7bdb6 | 39,396 |
def create_snapshot_if_not_exist(volume_id, tags, time_limit):
""" Create a snapshot of the volume in parameter only if any snapshot
exists for this volume_id and if it was created in the time delta
define by the difference between now and the time_limit value (in
minutes).
:param ... | 4b469243f935296068ad9a81eeeca5b0ee1717e0 | 39,397 |
def calculate_sigma_v(depths, gammas):
"""
Calculates the vertical stress
"""
depth_incs = depths[1:] - depths[:-1]
depth_incs = np.insert(depth_incs, 0, depth_incs[0])
sigma_v_incs = depth_incs * gammas
sigma_v = np.cumsum(sigma_v_incs)
return sigma_v | 22ab0582bf67935d6358bbccd37db0750ddb9976 | 39,398 |
def lon_lat_to_cartesian(lon, lat, radius=1):
"""
calculates lon, lat coordinates of a point on a sphere with
radius radius
"""
# Unpack xarray object into plane arrays
if hasattr(lon, 'data'):
lon = lon.data
if hasattr(lat, 'data'):
lat = lat.data
if lon.ndim != lat.nd... | 54fb3275b1a36a479f30feeaf50a87f0a0b25342 | 39,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.