content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _imported_module_paths() -> Iterator[PathLike]:
"""Yield absolute paths of the imported modules.
Loop over all the imported modules and try to get their absolute
file paths. If the path consists of all directories and no file,
then the implementation will break the loop and move on.
"""
... | 65,800 |
def clean_tmp_dir(days=3):
"""清理陆吾的临时文件夹,默认清理三天前的
Args:
days (int, optional): 要清理几天前的临时文件. Defaults to 3.
"""
timestamp = int(time.time())
days_timestamp = 86400 * days
cnt = 0
for dir_path in glob(os.path.join(LUWU_TMP_DIR_ROOT, "*")):
dir_timestamp = int(dir_path.split("/"... | 65,801 |
def to_json(value):
"""
Serialize a value as an HTML-safe JSON string.
The resulting value can be safely used inside a <script> tag in an HTML
document.
See http://benalpert.com/2012/08/03/preventing-xss-json.html for an
explanation of why JSON needs to be escaped when embedding it in an HTML
... | 65,802 |
def build_gene_compound_tissue_df(gene_compound_tissue_file, gene_file,
compound_file, tissue_file, output_dir):
"""
Build gene_compound_tissue table (description?)
@param gene_compound_tissue_file: [`str`] Path to the gene signature .csv file.
@param gene_file: [`str`] Path to the gene table .csv... | 65,803 |
def postprocess_question(text):
"""postprocess the output of question generation model for fair readable.
output.
Args:
text (text): generated question to be processed.
Returns:
str: clean readable text.
"""
output = text.replace("question: ", "")
output = output.strip()... | 65,804 |
def get_point_at_line_in_distance(p1, p2, distance):
"""
Get the coordinates of a point lying on the line p1 - p2 with
distance to point p1.
"""
linelength = math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
x = (distance / linelength) * (p2.x - p1.x) + p1.x
y = (distance / linelength) * (p... | 65,805 |
def export_removed_samples(args):
"""Export removed samples table."""
clarity_epp.export.sample.removed_samples(lims, args.output_file) | 65,806 |
def test_backprop_numberadder():
"""test that solved number adder will have zero forces with proper shape.
"""
import numpy as np
from crpm.ffn_bodyplan import read_bodyplan
from crpm.ffn_bodyplan import init_ffn
from crpm.dataset import load_dataset
from crpm.fwdprop import fwdprop
from... | 65,807 |
def macro_cons_gold_change():
"""
全球最大黄金 ETF—SPDR Gold Trust 持仓报告, 数据区间从 20041118-至今
:return: pandas.Series
"""
t = time.time()
res = requests.get(
JS_CONS_GOLD_ETF_URL.format(
str(int(round(t * 1000))), str(int(round(t * 1000)) + 90)
)
)
json_data = json.load... | 65,808 |
def _build_regression_coefficients(
response_vector_path, predictor_table_path,
tmp_indexed_vector_path, out_coefficient_vector_path,
out_predictor_id_list):
"""Calculate least squares fit for the polygons in the response vector.
Build a least squares regression from the log normalized ... | 65,809 |
def selection(population, n_best):
"""
"""
return sorted(population, key=fmgls, reverse=False)[:n_best] | 65,810 |
def unique_filter(posts: List[Post], _: ImgurConfig):
"""Filter out published posts."""
ids_list = [p.imgur_id for p in posts]
ids_in_db = set(Post.objects.filter(imgur_id__in=ids_list).values_list('imgur_id', flat=True))
return [
post for post in posts
if post.imgur_id not in ids_in_db
... | 65,811 |
def test_salt_client_none():
"""
Check SaltClient handles None values properly.
Args:
saltworker_client: (:obj:`src.workers.SaltBase`)
"""
system_params = {}
salt_config = {
'salt_states': None
}
saltworker_client = SaltBase(system_params, **salt_config)
assert sal... | 65,812 |
def clip_probs(original_probs):
"""
Makes sure probabilities are in certain range.
Rescale sum probabilities to 1.
"""
min_p = 1e-5
max_p = 1 - min_p
clipped_probs = np.clip(original_probs, min_p, max_p)
clipped_probs = clipped_probs / np.sum(clipped_probs)
return clipped_probs | 65,813 |
def parse_xml(file_path: str) -> Tuple[Article, ArticleComponentCheck]:
"""
Parse xml files
Parameters
----------
file_path: File name
Returns
-------
article: Article, component check: ArticleComponentCheck
"""
file_path = os.path.normpath(file_path)
tree = ET.parse(file_... | 65,814 |
def save_to_csv(normalized):
"""
Save data to csv file
"""
normalized.to_csv('cost_by_service.csv', index=False) | 65,815 |
def get_block_offset(default, vis, res):
"""Returns offset for selected visualization (vis). """
if vis.lower() == "hillshade":
return 1
elif vis.lower() == "shadow":
return 1
elif vis.lower() == "slope gradient":
return 1
elif vis.lower() == "multiple directions hillshade":
... | 65,816 |
def bbox_from_fast_rcnn(anchor, fast_rcnn):
""" Convert Fast-R-CNN-like representation relative to `anchor` to a `bbox`."""
anchor_height = anchor[...,SVHN.BOTTOM] - anchor[...,SVHN.TOP]
anchor_width = anchor[...,SVHN.RIGHT] - anchor[...,SVHN.LEFT]
anchor_y_center = 0.5 * (anchor_height) + anchor[...,SV... | 65,817 |
def test_write_image_diff_size_pil():
"""Writing out an image creates a file of a different size, if the file was generated by PIL originally."""
clean_file = CLEAN_PNG_LOCATION
dirty_file = "tests/dirtyImage_test_write_image_file_diff_size_pil.png"
clean_file_pil = "tests/cleanImagePIL.png"
with Im... | 65,818 |
def directional_variance(X, w):
"""向量集 X 在非零向量 w 方向上的方差"""
return sum(directional_variance_i(x_i, w) for x_i in X) | 65,819 |
def run_command(command, capture_output=True, log_error=True, env=None, timeout=None):
"""Execute shell command."""
if isinstance(command, str):
command = shlex.split(command)
logging.info("Executing command: " + " ".join(command))
try:
result = subprocess.run(
command, captu... | 65,820 |
def interactive(renderer):
"""
Parse user input, dump to stdout, rinse and repeat.
Python REPL style.
"""
_import_readline()
_print_heading(renderer)
contents = []
more = False
while True:
try:
prompt, more = ("... ", True) if more else (">>> ", True)
... | 65,821 |
def trpo_swimmer(ctxt=None, seed=1, batch_size=4000):
"""Train TRPO with Swimmer-v2 environment.
Args:
ctxt (metarl.experiment.ExperimentContext): The experiment
configuration used by LocalRunner to create the snapshotter.
seed (int): Used to seed the random number generator to prod... | 65,822 |
def get_job_data(job, average, qubit_idx, scale_factor):
"""
Retrieve data from a job that has already run.
"""
job_results = job.result(timeout=120) # Timeout after 120 s
result_data = []
for i in range(len(job_results.results)):
if average: # Get avg data
result_data.appe... | 65,823 |
def install_linter(folder: PurePath, linter: str):
"""Install linter as a dev package in the current virtual environment.
:param folder: project folder.
:param linter: linter to install."""
print("\nThis can take a while...")
try:
helpers.execute_subprocess(
["pipenv", "install"... | 65,824 |
async def performDrop(cls:"PhaazeDatabase", DBDropRequest:DropRequest) -> Response:
""" Used to drop/delete container from DB (automaticly deletes supercontainer if necessary) """
container_location = f"{cls.container_root}{DBDropRequest.container}.phaazedb"
#does not exist
if not os.path.isfile(container_locatio... | 65,825 |
def test_fuzzy_cmeans_predict():
"""
Test ability to classify new data.
"""
global features
global x_corr
global y_corr
# Generate slightly smaller new dataset, clustered tighter around seeds
xtest = np.zeros(0)
ytest = np.zeros(0)
cluster = np.zeros(0)
# Given this initia... | 65,826 |
def test_inorder_traverse(small_bst):
"""test if in order is sorting by value"""
collection = []
small_bst.in_order(collection.append)
# You can assume 'collection' has all the values by line 31
assert collection == [2, 6, 7, 8, 24, 25, 26] | 65,827 |
def chebyshev(a, b):
"""Chebyshev Distance
Arguments:
a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space.
b (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space.
Returns:
The distance between points a and b with L-... | 65,828 |
def delete_django_group(sender, group, **kwargs):
"""
Delete the internal Django group on delete.
"""
if group is not None:
try:
group.django_group.delete()
except:
pass | 65,829 |
def test_numpy_version():
"""
Checks for the correct NumPy version as per specification
"""
np_ver = np.__version__
assert(np_ver == "1.17.0")
print("Correct NumPy version found: " + np_ver) | 65,830 |
def convert_units(ds):
"""convert units for use in the preprocessor"""
try:
if ds.sftlf.units == "%":
print("converting sftlf units to fractional")
attrs = ds.sftlf.attrs
ds["sftlf"] = ds.sftlf * 0.01
attrs["units"] = 1
ds.sftlf.attrs = attrs
... | 65,831 |
def new_figure_manager_given_figure(num, figure):
"""
Create a new figure manager instance for the given figure.
"""
canvas = FigureCanvasPickle(figure)
manager = FigureManagerPickle(canvas, num)
return manager | 65,832 |
def get_rest_kwargs(service):
"""
REST API 呼び出しキーワード引数を取得する
Args:
service:
Returns:
"""
return service.execute_rest.call_args[1] | 65,833 |
def expand_url(url, protocol):
"""
Expands the given URL to a full URL by adding
the magento soap/wsdl parts
:param url: URL to be expanded
:param service: 'xmlrpc' or 'soap'
"""
if protocol == 'soap':
ws_part = 'api/?wsdl'
elif protocol == 'xmlrpc':
ws_part = 'index.php... | 65,834 |
def create_dict_searchers(g, v0: list, capture_range=0, zeta=None):
"""Create searchers (dictionary with id number as keys).
Nested: initial position, capture matrices for each vertex"""
# set of searchers S = {1,..m}
S = ext.get_set_searchers(v0)[0]
# create dict
searchers = {}
for... | 65,835 |
def get_generic_path_information(paths, stat_prefix=""):
"""
Get an OrderedDict with a bunch of statistic names and values.
"""
statistics = OrderedDict()
returns = [sum(path["rewards"]) for path in paths]
rewards = np.vstack([path["rewards"] for path in paths])
statistics.update(create_sta... | 65,836 |
def snake_case(string: str, bad_casing: Iterable[str] = ()) -> str:
"""return the snake cased version of a string. bad casings may be specified: if the bad casing is found, the word
is replaced with Titlecase:
Without bad_casing: SomeTimeOut_s -> some_time_out_s
With ['TimeOut'] as ... | 65,837 |
def generate_stop_ex_nb(entries, ts, stop, trailing, wait, first, flex_2d):
"""Generate using `generate_ex_nb` and `stop_choice_nb`.
## Example
Generate trailing stop loss and take profit signals for 10%.
```python-repl
>>> import numpy as np
>>> from vectorbt.signals.nb import generate_stop_e... | 65,838 |
def pack(header, s):
"""pack an string into MXImageRecord
Parameters
----------
header : IRHeader
header of the image record
s : str
string to pack
"""
header = IRHeader(*header)
s = struct.pack(_IRFormat, *header) + s
return s | 65,839 |
def inner_product(x, y):
"""Inner product."""
return x.dot(y) | 65,840 |
def get_continuous_cmap(hex_list, float_list=None, name=None):
"""
Creates and returns a color map that can be used in heat map figures.
If float_list is not provided, colour map graduates linearly between each color in hex_list.
If float_list is provided, each color in hex_list is mapped to the respect... | 65,841 |
def identity():
"""Which version of fabfile am I using"""
try:
import fab_support
version = f"fab_support version {fab_support._version.__version__}"
except ImportError:
version = "No fab_support to import"
print(f"Test fabfile {version}") | 65,842 |
def weighted_choice(choices=None, weights=None):
"""
Chooses an element from a list based on it's weight.
:Kwargs:
- choices (list, default: None)
If None, an index between 0 and ``len(weights)`` is returned.
- weights (list, default: None)
If None, all choices get e... | 65,843 |
def change_driver(node, driver):
"""Change driver module inplace"""
module_node = node.find('./attstr')
module_node.set("val", driver) | 65,844 |
def get_cell_doi_from_link(url):
""" Cell and ScienceDirect links have similar properties, but there are several different url
types for Cell abstracts and PDFs (much like biomedcentral).
Examples:
http://www.cell.com/pdf/0092867480906212.pdf --> 10.1016/0092-8674(80)90621-2
http://www.cell... | 65,845 |
def gcp_iam_folder_iam_policy_add_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""
Add new folder IAM policy.
Args:
client (Client): GCP API client.
args (dict): Command arguments from XSOAR.
Returns:
CommandResults: outputs, readable outputs and raw response... | 65,846 |
def test_list_serialization_dif_type() -> None:
"""
Tests packing and unpacking of lists with objects of different type
"""
list_ = [1, 2.0, "3", [4]]
pack_unpack_test(list_) | 65,847 |
def main():
"""Set up and run the worker.
For command-line usage see:
:command:`python -m nowcast.workers.make_ww3_current_file --help`
"""
worker = NowcastWorker(NAME, description=__doc__)
worker.init_cli()
worker.cli.add_argument(
"host_name", help="Name of the host to create the... | 65,848 |
def nn_capacity(dataframe, d_in, H, h_2, d_out, N):
"""
Takes a dataframe, the number of inputs, the number of nodes
for the first hidden layer, the number of nodes for the second
hidden layer, the number of outputs, and the total number of
datapoints as the input parameters and returns a trained
... | 65,849 |
def greedy_best_k_matching(smp, k=1, nodewise=True, edgewise=True,
verbose=False):
"""Greedy search on the cost heuristic to find the best k matchings.
Parameters
----------
smp: MatchingProblem
A subgraph matching problem.
k: int
The maximum number of solu... | 65,850 |
def main(
duration: int,
runtime_mode: str,
runner_mode: str,
start_messages: int,
num_of_agents: int,
number_of_runs: int,
output_format: str,
) -> Any:
"""Check http dialogues memory usage for multiple agents set."""
with with_packages(PACKAGES):
from aea_cli_benchmark.case... | 65,851 |
def build_examples_from_config(config, variables, product=True,
remove_duplicates=True):
"""Construct Test cases for a task.
Args:
config: raw dictionary configurary read in from scenario yml file.
variables: global and scenario lexicons.
Returns:
Formatted examples for... | 65,852 |
def moments_coords_central(coords, center=None, order=3):
"""Calculate all central image moments up to a certain order.
The following properties can be calculated from raw image moments:
* Area as: ``M[0, 0]``.
* Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}.
Note that raw moments ... | 65,853 |
async def test_intent_with_no_action_v1(fixture):
"""Test an intent with no defined action."""
mock_client, webhook_id = fixture
data = Data.v1
del data["result"]["action"]
assert "action" not in data["result"]
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.du... | 65,854 |
def google_logout():
"""Revokes token and empties session."""
if google.authorized:
try:
google.get(
'https://accounts.google.com/o/oauth2/revoke',
params={
'token':
google.token['access_token']},
)
e... | 65,855 |
def finalize_storage_construction(storage_manager, stamp_data, prior_recap, **kwargs):
"""
Parameters
----------
storage_manager :
stamp_data :
prior_recap :
**kwargs :
Returns
-------
"""
def produce_metadata_db_summary(final_recap):
... | 65,856 |
def region_overlap(
label_no: int,
label_img_outer: np.array,
label_img_inner: np.array,
overlap_thresh: int = 0.5,
) -> int:
"""Determine which two regions overlap in two label images.
Args:
label_no (int): Label number in the inner label image to look for overlap with.
label_i... | 65,857 |
def posthoc_letter_boxplot(df, Y_col, X_col, hue_col, X_order, hue_order, post_hoc = "tukey", alpha = 0.05,
fig_path = None, hue_palette = "YlGn", xtick_kwargs = {}, ytick_kwargs = {},
annotation_kwargs = {}, savefig_kwargs = {}):
"""
Function draws a grou... | 65,858 |
def set_up_ci_service():
"""If a framework project was created move it to project root."""
ci_service = '{{ cookiecutter.ci_service }}'
if ci_service == 'codeship-steps.yml':
LOG.info('Adding additional files for this CI setup ...')
ci_services_folder = join('_', 'ci-services')
shut... | 65,859 |
def calc_lambda_r(r, r1, r2, r3, r4, En):
"""
Mino time as a function of r (which in turn is a function of psi)
Parameters:
r (float): radius
r1 (float): radial root
r2 (float): radial root
r3 (float): radial root
r4 (float): radial root
En (float): energy
... | 65,860 |
def dbpull(context):
"""download DB from remote to local"""
_db_pull() | 65,861 |
def test_signed_vs_unsigned_comparisons(uint):
"""
cxx is a C++ irc eval bot (see http://www.eelis.net/geordi/)
<@disconnect3d> cxx << (uint64_t{1} > -1)
<+cxx> warning: comparison of integer expressions of different signedness:
'uint64_t' {aka 'long unsigned int'} and 'int'
# the -w ig... | 65,862 |
def br_person_anonymize():
""" Rules to anonymize a case file """
ANONYMOUS = "-"
# Standard anonymizers
from s3db.pr import pr_address_anonymise as anonymous_address, \
pr_person_obscure_dob as obscure_dob
# Helper to produce an anonymous ID (pe_label)
anonymous_id = ... | 65,863 |
def fmod(x, y):
"""
返回 ``x/y`` 的余数
"""
pass | 65,864 |
def pack_up_static_knapsack_2() -> Knapsack:
"""
[
Item(name='book', value=1, weight=1),
Item(name='food', value=2, weight=1),
Item(name='jacket', value=2, weight=2),
Item(name='water', value=6, weight=4)
]
"""
items = (
Item('water', 6, 4),
Item(... | 65,865 |
def set_job_threads(config_dict):
""" 根据配置信息和job_thread_manager.threads 的数量差来退出/增加线程
剩下的修改queue_name, interval
"""
tmp_jobs = job_thread_manager.threads.copy()
config = []
# 将config_dict转换格式为dicter = [{'queue':'q01', 'interval':6, }, ]
for queue_name, values in config_dict.items():
... | 65,866 |
def pos_tag(text,engine='old'):
"""
ระบบ postaggers
pos_tag(text,engine='old')
engine ที่รองรับ
* old เป็น UnigramTagger
* artagger เป็น RDR POS Tagger
"""
if engine=='old':
from .old import tag
elif engine=='artagger':
if sys.version_info < (3,4):
sys.exit('Sorry, Python < 3.4 is not support... | 65,867 |
def format_exception(exc_type, exc, tb, limit=None, chain=True,
_format_exception=traceback.format_exception):
"""Format a stack trace and the exception information.
This wrapper is a replacement of ``traceback.format_exception``
which formats the error and traceback received by XML-RP... | 65,868 |
def test_read_restricted_record_with_secret_link(
app, client, location, minimal_record, es_clear, identity_simple
):
"""Test access to a restricted record via a shared link."""
identity_simple.provides.add(authenticated_user)
service = current_rdm_records.records_service
record_data = minimal_recor... | 65,869 |
def gen_app_with_di_test() -> UserAppService:
"""依存解決を実行(テスト用)"""
def bind_repository(binder):
binder.bind(IUserRepository, to=UserInMemoryRepository(), scope=singleton)
class DatabaseModule(Module):
@provider
@singleton
def provide_repo(self, repo: IUserRepository) -> Use... | 65,870 |
def to_millis(seconds):
"""
Converts the time parameter in seconds to milliseconds. If the given time is negative, returns the original value.
:param seconds: (Number), the given time in seconds.
:return: (int), result of the conversation in milliseconds.
"""
if seconds >= 0:
return int... | 65,871 |
def var(input, axis=None, dtype=None, ddof=0, keepdims=False, name=None):
"""Variance across an axis.
Parameters
----------
input : tensor_like
Input tensor.
axis : int or None, default=None
Axis along which to reduce. If None, flatten the tensor.
Cannot be a `tf.Tensor`.
... | 65,872 |
def find_closest_pair_edges(edges_a, edges_b):
""" Find the edges in edges_a and edges_b that are closest to each other
"""
def length_func(pair):
e1, e2 = pair
return (calc_edge_median(e1) - calc_edge_median(e2)).length
pairs = [(e1, e2) for e1 in edges_a for e2 in edges_b]
return... | 65,873 |
def find_version():
"""Retrieve the version."""
constpy = Path("dataplaybook/const.py").read_text()
version_match = re.search(r"^VERSION = ['\"]([^'\"]+)['\"]", constpy, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.") | 65,874 |
def enforce_service_mode(services, FetcherClass, kwargs, modes):
"""
Fetches the value according to the mode of execution desired.
`FetcherClass` must be a class that is subclassed from AutoFallbackFetcher.
`services` must be a list of Service classes.
`kwargs` is a list of arguments used to make th... | 65,875 |
def test_initialization_from_existing_private_key():
"""Test that the initialization from an existing private key works correctly."""
private_key = _load_pem_private_key_from_path(path=PRIVATE_KEY_PEM_PATH)
assert private_key is not None, "The private key is not None after the loading!"
c = DefaultCrypt... | 65,876 |
def get_all_items():
"""
Get all items
"""
if DATASTORE == "DynamoDB":
response = table.scan()
if response['Count'] == 0:
return []
else:
return response['Items']
else:
# We want info_hash, peers, and completed.
items = []
... | 65,877 |
def escape_nl(msg):
"""
It's nice to know if we actually sent a complete line ending in
\n, so escape it for display.
"""
if msg != '' and msg[-1] == "\n":
return msg[:-1] + "\\n"
return msg | 65,878 |
def dmp_fateman_poly_F_2(n, K):
"""Fateman's GCD benchmark: linearly dense quartic inputs """
u = [K(1), K(0)]
for i in xrange(0, n-1):
u = [dmp_one(i, K), u]
m = n-1
v = dmp_add_term(u, dmp_ground(K(2), m-1), 0, n, K)
f = dmp_sqr([dmp_one(m, K), dmp_neg(v, m, K)], n, K)
g = dmp_... | 65,879 |
def noun(name: str, num: int) -> str:
"""
This function returns a noun in it's right for a specific quantity
:param name:
:param num:
:return:
"""
if num == 0 or num > 1:
return name + "s"
return name | 65,880 |
def extract_measurements_for_phase(scalars_for_samples):
"""Convert scalars to simplified dictionary. Returns only uptake and production rates.
:param scalars_for_samples: dictionary with lists of replicated scalars across samples
:return: list of dictionaries of format
{'id': <metabolite id (... | 65,881 |
def main(backend, user_messenger, **kwargs):
"""Entry function."""
# parse inputs
mandatory = {"ansatz", "operator"}
missing = mandatory - set(kwargs.keys())
if len(missing) > 0:
raise ValueError(f"The following mandatory arguments are missing: {missing}.")
ansatz = kwargs["ansatz"]
... | 65,882 |
def scrape_all():
"""Scrape data from four Mars websites and return dictionary of results."""
# Initiate headless webdriver for deployment
# Set up Splinter (prepping the automated browser)
executable_path = {"executable_path": ChromeDriverManager().install()}
browser = Browser("chrome", **executabl... | 65,883 |
def filters_from_params(params):
"""Returns a list of filters (filter context) built from parameters"""
filters = []
if params.get('f_list'):
filters.append(Q('terms', email_list=params['f_list']))
if params.get('f_from'):
filters.append(Q('terms', frm_name=params['f_from']))
if para... | 65,884 |
def run():
"""Run both of the programs"""
Premade_Army.start_time = time.time()
Premade_Army.main()
Premade_Army.end_time = time.time()
User_Army.start_time = time.time()
User_Army.main()
User_Army.end_time = time.time()
Premade_Army.duration = Premade_Army.start_time - Premade_A... | 65,885 |
def surface_weighted_three_modes(dp, n1, gm1, gsd1, n2, gm2,
gsd2, n3, gm3, gsd3):
"""
Discrete PDF for a lognormal distribution of particle size
for a 3-mode distribution weighted by surface.
:param dp: The particle diameters at which to evaluate
the PDF... | 65,886 |
def compareChecksum(msgBytes, checksumBytes):
"""Compute and compare Li-1 message checksum.
Args:
msgBytes: Raw message bytes.
checksumBytes: Checksum to compare against.
Returns:
A boolean of whether checksum matched or not.
"""
checksum = calc8bitFletcherChecksum(msgBytes)
... | 65,887 |
def get_assessor_dict(assessor_label, assessor_path):
"""
Generate the dictionary for an assessor from the folder in the queue
:param assessor_label: assessor label
:param assessor_path: assessor path on the station
:return: None
"""
assessor_dict = dict()
keys = ['project_id', 'subject... | 65,888 |
def test_impute_by_ordered_fill_forward_desc(spark_session):
"""Test fill forward with descending sort."""
schema = "date string, participant_id string, age integer, age_imputation integer"
# BACKWARDS OBSERVATION
expected_df_bkw = spark_session.createDataFrame(
data=[
("2020-01-02"... | 65,889 |
def nonSingletonsPostprocessing(absoluteBGTruth, nsRegionsBedFileName, nsConcordantFileName, nsDisCordantFileName,
kbp=10, print_first=False,
genome_annotation_dir=os.path.join(data_base_dir, 'genome-annotation')):
"""
Define concordant and discord... | 65,890 |
def token_literal(token_text: str):
"""
Generates an token lambda file which always returns the same value, this is
used for testing, and also as an example of how to write token managers
Parameters:
token_text(string): the token which should always be returned by the lambda
Return:
... | 65,891 |
def loop_through_addresses(addresses, recipients, header):
"""
Loop through all addresses.
:param addresses: user address input.
:param recipients: list to store all addresses.
:param header: message label (To, Bcc or Cc)
:return: email addresses.
"""
try:
for recipient in addres... | 65,892 |
def main():
""" MAIN """
args = setup()
reddit = praw.Reddit()
sub_exists(reddit, args.subreddit)
subreddit = reddit.subreddit(args.subreddit)
primaryFlairs = Counter()
secondaryFlairs = Counter()
titles = []
numberResults = 0
for submission in subreddit.search(args.query, ... | 65,893 |
def _rmse(y, y_hat):
"""RMSE"""
y_hat = y_hat.unsqueeze(1) if y_hat.dim() == 1 else y_hat
y = y.unsqueeze(1) if y.dim() == 1 else y
assert y.shape == y_hat.shape
assert y.dim() == 2
assert y.shape[-1] == 1
return torch.nn.functional.mse_loss(y, y_hat).pow(0.5) | 65,894 |
def get_number_as_words(n):
"""
Gets the integer number returns corresponding string words
:param n: integer
:return:
"""
if n == 0:
return zero
return normalize(abs(n)) | 65,895 |
def async_replace_list_data(
data: list | set | tuple, to_replace: dict[str, str]
) -> list[Any]:
"""Redact sensitive data in a list."""
redacted = []
for item in data:
new_value = None
if isinstance(item, (list, set, tuple)):
new_value = async_replace_list_data(item, to_repl... | 65,896 |
def role_exists(handle, name, **kwargs):
"""
checks if a role exists
Args:
handle (UcsHandle)
name (string): role name
**kwargs: key-value pair of managed object(MO) property and value, Use
'print(ucscoreutils.get_meta_info(<classid>).config_props)'
... | 65,897 |
def appliance_get_api(
self,
ne_pk: str,
url: str,
) -> dict:
"""Pass along a GET API call to an appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - appliance
- GET
- /appliance/rest/{nePk}/{url : (.*... | 65,898 |
def gen_subclasses(cls):
"""Recursively find all subclasses of cls"""
for sub_cls in cls.__subclasses__():
yield sub_cls
yield from gen_subclasses(sub_cls) | 65,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.