content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import sys
import os
def get_openmp_flag(compiler):
"""Get openmp flags for a given compiler"""
if hasattr(compiler, 'compiler'):
compiler = compiler.compiler[0]
else:
compiler = compiler.__class__.__name__
if sys.platform == "win32" and ('icc' in compiler or 'icl' in compiler):
... | 0018d6bab02c6b519974471c8b1b0535f783dbf8 | 686,763 |
from typing import Sequence
def true_positive_rate(y_true: Sequence, y_pred: Sequence) -> float:
"""Calculates the true positive rate binary classification results.
Assumes that the negative class is -1.
"""
assert set(y_true).issubset({1, -1})
assert set(y_pred).issubset({1, -1})
num_positiv... | 9fbb6fc23d2e7670e001a4960bbf6056bb13c6c1 | 686,764 |
def summ_nsqr(i1, i2):
"""Return the summation from i1 to i2 of n^2"""
return ((i2 * (i2+1) * (2*i2 + 1)) / 6) - (((i1-1) * i1 * (2*(i1-1) + 1)) / 6) | bcd2263be6b5698f2997e0daac962c207e318fd0 | 686,765 |
def _cost_to_qubo(cost) -> dict:
"""Get the the Q matrix corresponding to the given cost.
:param cost: cost
:return: QUBO matrix
"""
model = cost.compile()
Q = model.to_qubo()[0]
return Q | 4b0691335a82ca8a32033619247b50c465dfbe9d | 686,766 |
import numpy
def mean_median(election_results):
"""
Computes the Mean-Median score for the given ElectionResults.
A positive value indicates an advantage for the first party listed
in the Election's parties_to_columns dictionary.
"""
first_party = election_results.election.parties[0]
data ... | 5612818ee865fc54febcd5550624998cd014b9ad | 686,767 |
from typing import Type
from typing import Callable
from typing import Dict
from typing import Any
import inspect
def _keyword_filter(type_: Type) -> Callable[[Dict[str, Any]], Dict[str, Any]]:
"""Create a filter to pull out only relevant keywords for a given type."""
params = inspect.signature(type_.__init__... | 13a01178653f8129fff2edc10c06c452460514e4 | 686,768 |
import random
def gen_not():
"""Randomly returns the string '!'"""
return '!' if random.randint(0, 1) else '' | 47f1716c3d2ccbb7cbc2fd8571f536c6e40d318d | 686,769 |
import copy
def get_equivalent_peo_naive(graph, peo, clique_vertices):
"""
This function returns an equivalent peo with
the clique_indices in the rest of the new order
"""
new_peo = copy.deepcopy(peo)
for node in clique_vertices:
new_peo.remove(node)
new_peo = new_peo + clique_ver... | 9e8897f85bbe9c34ef1637bd7526e92c6a3e31bf | 686,770 |
import subprocess
import os
def checkDocker():
"""Checks docker is installed and user is a member of the docker group.
Returns:
True if docker is installed and user is a member of the docker group
else False.
"""
try:
cmdArgs = ['docker', 'version']
subprocess.run(cmdA... | e43348ea279e29c3f2d5b5f37edce08b17a77336 | 686,771 |
def base_count(DNA):
"""Counts number of Nucleotides"""
return DNA.count('A'), DNA.count('T'), DNA.count('G'), DNA.count('C') | 64fb081fc5f510b3d55b4afb0c1f9c8b6ee89fb9 | 686,772 |
def alphabetical_value(name):
"""
Returns the alphabetical value of a name as described in the
problem statement.
"""
return sum([ord(c) - 64 for c in list(str(name))]) | 0f98fb1efc79f9ca29b87b1d5e0de35412f41ee2 | 686,773 |
def GetFilters(user_agent_string, js_user_agent_string=None,
js_user_agent_family=None,
js_user_agent_v1=None,
js_user_agent_v2=None,
js_user_agent_v3=None):
"""Return the optional arguments that should be saved and used to query.
js_user_agent_string... | 9e924d9311a9838cf2e09cd11ea7f3e957466610 | 686,774 |
def filter_api_changed(record):
"""Filter out LogRecords for requests that poll for changes."""
return not record.msg.endswith('api/changed/ HTTP/1.1" 200 -') | caa93f19ce00238786ae0c1687b7e34994b73260 | 686,775 |
def apply_decorators(decorators):
"""Apply multiple decorators to the same function. Useful for reusing common decorators among many functions."""
def wrapper(func):
for decorator in reversed(decorators):
func = decorator(func)
return func
return wrapper | acd1f6af5eb757aeb3e707e84d1893ebf049e2f0 | 686,776 |
def turn_weight_function_distance(v, u, e, pred_node):
"""
Weight function used in modified version of Dijkstra path algorithm.
Weight is calculated as the sum of edge length weight and turn length weight (turn length weight keyed by predecessor node)
This version of the function takes edge lengths keye... | c463f314877b9a40b428fcc9d4e26fae4eacccc6 | 686,777 |
from operator import ge
from operator import lt
def find_gas_diagnostics(diagnostics_list: list[str], gas_type: str) -> int:
"""Find diagnostic for gas type"""
gas_comparison = {"o2": ge, "co2": lt}
diagnostics_gas = diagnostics_list.copy()
n_bits = len(diagnostics_gas[0])
bit = 0
while len(di... | b5b5b652d334089d57249ebbcf458a4d49ef0ab9 | 686,778 |
import string
def LazyFormat(s, *args, **kwargs):
"""Format a string, allowing unresolved parameters to remain unresolved.
Args:
s: str, The string to format.
*args: [str], A list of strings for numerical parameters.
**kwargs: {str:str}, A dict of strings for named parameters.
Returns:
str, Th... | 53039d096b8600a11d5220c47c51ee36fe4e3eb9 | 686,779 |
def count_valid(orders: list, orders_per_page: int) -> bool:
"""
Function is checking fetch orders is less than orders per page.
"""
if len(orders) < orders_per_page:
return False
return True | e4a9a32485d563c492f4d00cb23192402495a717 | 686,780 |
import os
def parse_args(parser):
"""
Parse commandline arguments.
"""
parser.add_argument('-o', '--output', type=str, required=True,
help='Directory to save checkpoints')
parser.add_argument('-d', '--dataset-path', type=str, default='./',
help='Path... | fe46b45be0496d657a47912107987924d5b26d7f | 686,781 |
import numpy
def empty_array(shape, dtype=numpy.int16, ndv=-999):
"""
Return an empty (i.e. filled with the no data value) array of the given shape and data type
:param shape: shape of the array
:param dtype: data type of the array (defaults to int32)
:param ndv: no data value (defaults to -999)... | c7a6242a7569782745d5d284d2184504ca6b08d4 | 686,782 |
import collections
import functools
def unigram_modelling(original_tagged_corpus):
"""
Calculate unigram model of given corpus.
Returns tagged_corpus as (word,tag) list.
Returns tagged_corpus counts as ((word,tag),count) list.
Returns unigram counts.
Returns size of corpus.... | c282cbf26871b6f4e5c0ed13c7f261ae131195da | 686,783 |
def find_gcd(number1: int, number2: int) -> int:
"""Returns the greatest common divisor of number1 and number2."""
remainder: int = number1 % number2
return number2 if remainder == 0 else find_gcd(number2, remainder) | 966270f6299ebf2f95dfd0d867ce29ed8bb5ee89 | 686,784 |
def add_keywords(keyword_list, extra_keywords):
"""Adds extra_keywords list to the keyword_list"""
# check if datetime and category already exist in the
# keyword list
filtered_keywords = [k for k in keyword_list if not
(k.startswith('category:') or
k.... | 5ba6f30aae8a0c45ce2c34bfe47e7921f147e186 | 686,785 |
import subprocess
import json
def get_cf_entity_name(entity, guid):
"""
Retrieves the name of a CF entity from a GUID.
"""
cf_json = subprocess.check_output(
["cf", "curl", "/v3/" + entity + "/" + guid],
universal_newlines=True
)
cf_data = json.loads(cf_json)
return cf_da... | 947cf0cf2dc96410ff82eaac82fc6ac9a23ea210 | 686,786 |
def rect_area(r):
"""Return the area of a rectangle.
Args:
r: an object with attributes left, top, width, height
Returns:
float
"""
return float(r.width) * float(r.height) | bd78896dcfe1b128602218d961162efb23f1a612 | 686,787 |
def find_child(item, tag):
"""
find a child with specific tag
:param item: Node to be queried.
:type item: Node
:param tag: Tag to be queried
:type tag: String
:return:
:rtype:
"""
result = list(item.iterfind(tag))
if len(result):
return result[0].text
else:
... | dd60712656d10cceaf45f487f6b5d86eb0b8fec6 | 686,788 |
def ascii2int(str, base=10,
int=int):
""" Convert a string to an integer.
Works like int() except that in case of an error no
exception raised but 0 is returned; this makes it useful in
conjunction with map().
"""
try:
return int(str, base)
except:
... | c797e8d93dbbb653d738fc506577395931036cab | 686,789 |
import numpy
def get_constant_array(params,dt):
"""
Creates values array for runs of type constant.
"""
T = float(params['T'][0])
value = float(params['value'][0])
N = int(T/dt)
values_array = value*numpy.ones((N,))
return values_array | de50595a1fd4cf91ff83b12c79e2cac10adc5908 | 686,790 |
import re
def clean_text (text,langcode):
""" Automated cleaning of text.
"""
if langcode == 'en':
numbers = {'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
'5': 'five',
... | fc02f2eef40ad788df8ad3eb1404cd76d1106fab | 686,791 |
def create_chord_progression(a_train=False):
"""Creates a midi chord progression
Args:
a_train (bool, optional): Defaults at False. If True, returns chord progression for Take the A Train by Duke Ellington. Otherwise, returns standard 12-bar blues in C major.
Returns:
(int, int)[... | e187f06960292d915025063d56001579ef5cbb90 | 686,792 |
import itertools
def subsets(parent_set, include_empty=False, include_self=False):
"""
Given a set of variable names, return all subsets
:param parent_set: a set, or tuple, of variables
:return: a set of tuples, each one denoting a subset
"""
s = set()
n = len(parent_set)
for i in rang... | ca3dcbf620f8dc29e1f0a14ec4bf74abdbdeacd1 | 686,793 |
def remove_patients(df, n):
""" Remove all patients with < n valid values
Return the new database 'df'.
"""
cnt = df.count(axis=1, level=None, numeric_only=False)
index = [k for k in df.index.values if cnt[k] < n]
df = df.drop(index)
return df | 499df019376af68610cc476e3bc6fbe76c0efb3e | 686,794 |
def read_ubyte(buf):
"""
Reads an integer from `buf`.
"""
return ord(buf.read(1)) | 74fb5df1bac8b4e7d3f6d2c9dd96e938a8881a08 | 686,795 |
def read(filename):
"""simply read a file"""
op = open(filename)
data = op.read()
op.close()
return data | 4d0ac8fdd23f1ead9b1ebd7adc6360ab5add2ea9 | 686,796 |
def drop_unnecessary_features(df):
"""
Args:
df (pandas dataframe): the initial pandas dataframe
Returns
df (pandas dataframe): a dataframe where the unnecessary
features have been dropped
"""
df.drop(['updated', 'description', 'location', 'name', 'lang', 'url',
... | bde9e1b1a4cc1dd859585778553f1a23fbe0d105 | 686,797 |
from typing import Any
from typing import Optional
def _guess_crs_str(crs_spec: Any)->Optional[str]:
"""
Returns a string representation of the crs spec.
Returns `None` if it does not understand the spec.
"""
if isinstance(crs_spec, str):
return crs_spec
if hasattr(crs_spec, 'to_epsg')... | 11328ea9d1cc955faa63c37a64d115e8252b0c57 | 686,799 |
def db_factory(request):
"""
Create a database session upon a successful request to the home automation server.
This allows an SQLAlchemy session to be available in view code as ``request.db`` or ``config.registry.dbmaker()``.
:param request: an HTTP request object
:return: a database session
"... | d66b216d576b1c014a7bcdbde4e6c114d6b7337f | 686,800 |
from typing import Iterable
from typing import List
def unique_by(pairs: Iterable[tuple]) -> List:
"""Return a list of items with distinct keys. pairs yields (item, key)."""
# return a list rather than a set, because items might not be hashable
return list({key: item for item, key in pairs}.values()) | b88734701dcb46532e4a40695e56934bd24e03dd | 686,801 |
def area_of_polygon(x, y):
"""Calculates the area of an arbitrary polygon given its verticies"""
area = 0.0
for i in range(-1, len(x)-1):
area += x[i] * (y[i+1] - y[i-1])
return abs(area) / 2.0 | 003a7ffde3c1016113da0129583e92674eef8556 | 686,802 |
def get_list_word_more_frequent(word_list, limit=-1):
"""Get the list of words more frequent
Parameters
-----------
word_list: list of words
limit: limit number of words returned
Returns
--------
word_list: list of the words more frequent
"""
word_count = {}
for word in wor... | 416e08be8961086c761c90bbd15d61985724d969 | 686,803 |
import torch
def concat(batches, num=4):
"""
batches: [(C,W1,H1)]
"""
batches_list=[]
for j in range(len(batches) // num):
batches_list.append(torch.cat(batches[num*j:num*(j+1)], dim=2))
return torch.cat(batches_list,dim=1) | b2ef6a752fc097be015e1748345e353e2e02e155 | 686,804 |
def splitDataSet(dataSet, axis, value):
"""splitDataSet(通过遍历dataSet数据集,求出axis对应的colnum列的值为value的行)
Args:
dataSet 数据集
axis 表示每一行的axis列
value 表示axis列对应的value值
Returns:
axis列为value的数据集【该数据集需要排除axis列】
Raises:
"""
retDataSet = []
for featVec in dataSet:
#... | 176aafaa63bf9e79d208b7097633ec6b9f2920ef | 686,805 |
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
index_map = {}
for i in range(len(nums)):
num = nums[i]
pair = target - num
if pair in index_map:
return [index_map[pair], i]
index_map[num] = i
return ... | bfb4b55556377134969d3cdfcfeebecea8193ac4 | 686,807 |
def _set_default_max_rated_temperature(subcategory_id: int) -> float:
"""Set the default maximum rated temperature.
:param subcategory_id: the subcategory ID of the inductive device with missing
defaults.
:return: _rated_temperature_max
:rtype: float
"""
return 130.0 if subcategory_id =... | f2f86d899b9404622b3c01f89416c7e0c8cab393 | 686,808 |
def filter_tensor_and_static_args(args, static_argnums):
"""
Separate out the tensor and static args. Also, for the static args, store
the hash.
"""
tensor_args = []
static_args = []
static_args_hashed = []
for idx, arg in enumerate(args):
if idx not in static_argnums:
... | a5443fdf3e47d73c65f4ce3f1e05f7bdd459656c | 686,809 |
def __vertex_str__(self) -> str:
""" Display a Vertex """
return f"Vertex: ({self.X}, {self.Y}, {self.Z})" | 4a23dba65a1997bfe27570fac69032dc5bc12eef | 686,810 |
def SimpleMaxMLECheck(BasinDF):
"""
This function checks through the basin dataframe and returns a dict with the basin key and the best fit
m/n
Args:
BasinDF: pandas dataframe from the basin csv file.
Returns:
m_over_n_dict: dictionary with the best fit m/n for each basin, the key ... | db833f1f7d5fbe140ed0dc92ef99dc7ff138523c | 686,812 |
def type_parameter(x):
"""Get the type parameter of an instance of a parametric type.
Args:
x (object): Instance of a parametric type.
Returns:
object: Type parameter.
"""
return x._type_parameter | b6b19de3ebd91af9c2c8b866514786145ac61279 | 686,813 |
import re
def get_pkgver(pkginfo):
"""Extracts the APK version from pkginfo; returns string."""
try:
pkgver = re.findall("versionName=\'(.*?)\'", pkginfo)[0]
pkgver = "".join(pkgver.split()).replace("/", "")
except:
pkgver = "None"
return pkgver | 872c2acb284d9fc3165bb84e1b10ebb46e827738 | 686,815 |
def getBBox(df, cam_key, frame, fid):
"""
Returns the bounding box of a given fish in a given frame/cam view.
Input:
df: Dataset Pandas dataframe
cam_key: String designating the camera view (cam1 or cam2)
frame: int indicating the frame which should be looked up
fid: int ind... | dcbe5f8cc17c5913d712f543d01c5e8b71f741e4 | 686,816 |
def constituent_copyin_subname(host_model):
###############################################################################
"""Return the name of the subroutine to copy constituent fields to the
host model.
Because this is a user interface API function, the name is fixed."""
return "{}_ccpp_gather_const... | b752b590127a0421caa531daccc4fbdf61728abe | 686,817 |
import math
def het(rts):
"""
HET -- "Schedulability Analysis of Periodic Fixed Priority Systems"
http://ieeexplore.ieee.org/document/1336766/
--
See also: "Efficient Exact Schedulability Tests for Fixed Priority Real-Time Systems"
http://ieeexplore.ieee.org/document/4487061/
"""
def ... | 6ba4375df768e29a5079f81bbadca54dd1da4c4a | 686,818 |
def cal_proba_vector(sample, classification_model_fit):
"""Calculate the probability vector.
Usage:
:param: sample:A dataset that is a 2D numpy array
classification_model_fit: A classification model that has been fitted
:rtype:
"""
proba_vector = classification_model_fi... | 2869a0f6405f3778bb9b702d7c5bde4652dbebf6 | 686,819 |
import codecs
def check_encoding(stream, encoding):
"""Test, whether the encoding of `stream` matches `encoding`.
Returns
:None: if `encoding` or `stream.encoding` are not a valid encoding
argument (e.g. ``None``) or `stream.encoding is missing.
:True: if the encoding argument resolves... | d9957826e34ec55476fcf101ca013e206582cb33 | 686,820 |
def _make_tuple_tree(terms):
"""make tuples, so terms are hashable"""
def _make_tuple(branch):
if hasattr(branch, "__len__"):
return tuple([_make_tuple(t) for t in branch])
else:
return int(branch)
return _make_tuple(terms) | 9d41626295a0e4fc1a4199675f14dae2cd6aab03 | 686,821 |
import argparse
def parse_args():
"""
argparse initializer. Note that only output and log have default values.
"""
parser = argparse.ArgumentParser(description='Crawl NeurIPS Papers.')
parser.add_argument('--from_year', help='Starting year to crawl')
parser.add_argument('--to_year', help='Fina... | 8484ced6602d381cfd042f4c48636af3f5a43b07 | 686,822 |
def _list_distance(list1, list2, metric):
"""
Calculate distance between two lists of the same length
according to a given metric.
Assumes that lists are of the same length.
Args:
list1 (list): first input list.
list2 (list): second input list.
metric (str): 'identity' coun... | bd8b98a13d070b0123dc20792abd8485ae247082 | 686,823 |
import torch
from typing import Type
def count_module_instances(model: torch.nn.Module, module_class: Type[torch.nn.Module]) -> int:
"""
Counts the number of instances of module_class in the model.
Example:
>>> model = nn.Sequential([nn.Linear(16, 32), nn.Linear(32, 64), nn.ReLU])
>>> cou... | 28a4c8914fca34be8562802d2c337804cc3690d1 | 686,824 |
def get_all_layers(model):
""" Get all layers of model, including ones inside a nested model """
layers = []
for l in model.layers:
if hasattr(l, 'layers'):
layers += get_all_layers(l)
else:
layers.append(l)
return layers | 885159b8d91a53caed55be08503f6738bf114eeb | 686,825 |
def escape_markdown(raw_string: str) -> str:
"""Returns a new string which escapes all markdown metacharacters.
Args
----
raw_string : str
A string, possibly with markdown metacharacters, e.g. "1 * 2"
Returns
-------
A string with all metacharacters escaped.
Examples
-----... | 6e0518dcfe9a09a1be5846bd7da92ffccf2f6368 | 686,826 |
import os
def remove_upper_level_references(path):
"""Remove upper than `./` references.
Collapse separators/up-level references avoiding references to paths
outside working directory.
:param path: User provided path to a file or directory.
:return: Returns the corresponding sanitized path.
... | 9a6f13e410fe76c54c2c11bbfabb283094471326 | 686,827 |
import sys
def get_skip_bigrams(sent, k=2, bounds=False):
"""
get bigrams with up to k words in between
otherwise similar to get_ngrams
duplicates removed
"""
sb = set()
if type(sent) == type(''): words = sent.split()
elif type(sent) == type([]): words = sent
else:
sys.stderr.write('unrecognized input ty... | cca67e24d18ac738a08b919e873384d7508b861b | 686,828 |
import csv
def detect_csv_sep(filename: str) -> str:
"""Detect the separator used in a raw source CSV file.
:param filename: The name of the raw CSV in the raw/ directory
:type filename: str
:return: The separator string
:rtype: str
"""
sep = ''
with open(f'raw/{filename}',"r") as cs... | ad7b26dfd5194c26bd3b32d0bcb3590410a121d2 | 686,829 |
def matrix_to_listlist(weight):
"""transforms a squared weight matrix in a adjacency table of type listlist
encoding the directed graph corresponding to the entries of the matrix
different from None
:param weight: squared weight matrix, weight[u][v] != None iff arc (u,v) exists
:complexity: linear
... | 77693ebea7126d7fd1ce4a8acf9145f0b22446d3 | 686,830 |
def get_restraints(contact_f):
"""Parse a contact file and retrieve the restraints."""
restraint_dic = {}
with open(contact_f) as fh:
for line in fh.readlines():
if not line: # could be empty
continue
data = line.split()
res_i = int(data[0])
... | e61c825d25dc9fb50f10bd8091f98dd997d278cc | 686,831 |
def easy_name(s):
"""Remove special characters in column names"""
return s.replace(':', '_') | 7ce1ecaa22b84aa38f86d091740b5d669231ca90 | 686,832 |
import argparse
import os
def parse_args():
"""Parse input arguments"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-d', '--dataset_cfg', type=str,
help='Path to the dataset config filename')
parser.add_argument(
'-m', '--mode', type=str,
choices=['train',... | 508955c78e388cd5816ca6521fb46c094fd24ce2 | 686,833 |
def skymapweights_keys(self):
"""
Return the list of string names of valid weight attributes. For unpolarized
weights, this list includes only TT. Otherwise, the list includes all six
unique weight attributes in row major order: TT, TQ, TU, QQ, QU, UU.
"""
if self.polarized:
return ['T... | f7e69f39abfbb35bd12b44a838ce76f3145cdfe7 | 686,834 |
def one_lvl_colnames(df,cols,tickers):
"""This function changes a multi-level column indexation into a one level
column indexation
Inputs:
-------
df (pandas Dataframe): dataframe with the columns whose indexation will be
flattened.
tickers (list|string): list/string with the tickers (... | 2252916dd6199a4c87345fedb7bdf5103d2363df | 686,835 |
def has_imm(opcode):
"""Returns True if the opcode has an immediate operand."""
return bool(opcode & 0b1000) | 0aa7315f7a9d53db809ce1340c524400ead60799 | 686,836 |
from typing import Iterator
def second(itr: Iterator[float]) -> float:
"""Returns the second item in an iterator."""
next(itr)
return next(itr) | 74e85436ed9b763f262c94e3898455bd24d75028 | 686,837 |
def _run_subsuite(args):
"""
Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult.
This helper lives at module-level and its arguments are wrapped in a tuple
because of the multiprocessing module's requirements.
"""
runner_class, subsuite_index, subsuite, failfast = args
... | a51b0d7c3abed528ceaf3cbe16059e6e816074c6 | 686,838 |
def i_c(i_cn=0,i_cp=0):
"""
Collector current in a Bipolar Junction Transistor
Parameters
----------
i_cn : TYPE, optional
DESCRIPTION. The default is 0.
i_cp : TYPE, optional
DESCRIPTION. The default is 0.
Returns
-------
None.
"""
ic = i_cn + i_cp
ret... | a90ca28dc2a84049213493dd52360498bf44f330 | 686,839 |
from typing import List
import re
def parse_seasons(seasons: List[str]):
"""Parses a string of seasons into a list of seasons. Used by main and by collect_course_length main"""
parsed_seasons = []
for season in seasons:
if re.match("[0-9]{4}\-[0-9]{4}", season):
int_range = list(map(in... | 9dbc63cab1a0839360384aea8c4cdec88605d767 | 686,840 |
def _copy_dict(dct, description):
"""Return a copy of `dct` after overwriting the `description`"""
_dct = dct.copy()
_dct['description'] = description
return _dct | 557bc7da87069846c088983228079d3c762af69c | 686,842 |
def poly_from_box(W, E, N, S):
"""
Helper function to create a counter-clockwise polygon
from the given box.
N, E, S, W are the extents of the box.
"""
return [[W, N], [W, S], [E, S], [E, N]] | ed1bf13dfc2e9eb405789d98182338d576178124 | 686,843 |
def valfilterfalse(predicate, d, factory=dict):
""" Filter items in dictionary by values which are false.
>>> iseven = lambda x: x % 2 == 0
>>> d = {1: 2, 2: 3, 3: 4, 4: 5}
>>> valfilterfalse(iseven, d)
{2: 3, 4: 5}
See Also:
valfilter
"""
rv = factory()
for k, v in d.items... | d10f29e97946580f5f49dc928b2402c863c1617f | 686,844 |
def yxbounds(shape1, shape2):
"""Bounds on the relative position of two arrays such that they overlap.
Given the shapes of two arrays (second array smaller) return the range of
allowed center offsets such that the second array is wholly contained in
the first.
Parameters
----------
shape1 ... | 57cbba112224c87571d2e0ad7558946658f4b04d | 686,845 |
def get_sync_folder_path(file, config):
""" returns the folder our file is on,
from the configured folders we have
"""
result = 'path'
for folder in config.folders:
if folder['path'] + '/' in file:
result = folder['path']
break
return result | 922e55640ddec2c8d179138b237b4d1211a03a2c | 686,847 |
import argparse
def add_peak_args():
"""
quantify features using featureCounts
support input file: BAM + GTF/BED/GFF ...
"""
parser = argparse.ArgumentParser(
description='call peaks')
parser.add_argument('-i', '--bam', nargs='+', required=True,
help='BAM files, from IP sample'... | 1b000fb3692898eeda570a88bdfba80b9be80d88 | 686,848 |
import hashlib
def get_sign(data_dict, key):
"""
签名函数
:param data_dict: 需要签名的参数,格式为字典
:param key: 密钥 ,即上面的API_KEY
:return: 字符串
"""
params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False) # 参数字典倒排序为列表
params_str = "&".join(u"{}={}".format(k, v) for k, v in params_lis... | ea7ee65cd3ae72e19293dc851255bc0f3ad4b321 | 686,849 |
def parse_spec(spec, default_module):
"""Parse a spec of the form module.class:kw1=val,kw2=val.
Returns a triple of module, classname, arguments list and keyword dict.
"""
name, args = (spec.split(':', 1) + [''])[:2]
if '.' not in name:
if default_module:
module, klass = defaul... | 5ea1c05488e77e1c7dd76ed2ae332dbea460f0ff | 686,851 |
def fix_probs_2d(ps):
"""
Make sure probability distribution is 2d and valid
"""
ps /= ps.flatten().sum()
return ps | 806a0bc3512a9ab10a554e4054975a363dd9cb85 | 686,853 |
def features(runenvs):
"""
Information about the capabilities of the cluster.
show the user a list of available "features"
and additional computational nodes.
"""
output = {}
for runenv in runenvs:
if runenv['runenv'] in output:
output[runenv['runenv']].append(runenv['fea... | c1fae3ba8e8b5852a2af94d112b516f9793ca64c | 686,854 |
def max_toys(prices, k):
"""
prices is an array representing toy prices. k is an integer representing the amount Mark can spend. Returns the maximum number of toys someone can buy while remaining within budget.
"""
# sort priced array - python can do this for me
# a variable to check against k as it... | 709f0a96efd7864005285497da8983e66888cea9 | 686,855 |
def handle_returning_date_to_string(date_obj):
"""Gets date object to string"""
# if the returning date is a string leave it as is.
if isinstance(date_obj, str):
return date_obj
# if event time is datetime object - convert it to string.
else:
return date_obj.isoformat() | e1219cac077f29683ca1c7edbc12920037dd4bb6 | 686,857 |
import torch
def trace(values: torch.Tensor, keepdim=False) -> torch.Tensor:
"""
:param values: b x n x n
:param keepdim:
:return: b x 1 if keepdim == True else b
"""
return torch.diagonal(values, dim1=-2, dim2=-1).sum(-1, keepdim=keepdim) | 59c210c3e80ee36662b9b31b1286a6920eda2dd0 | 686,858 |
def getAtomNames(values):
"""
Assign to each value an atomname, O for negatives, H for 0 and N for
positives. This function is created for assign atomnames for custom pdbs
:param values: Collection of numbers to assing an atom name for
:type values: iterable
:returns: list ... | 63f0533ef9cc18467438ca5c48513992283d521a | 686,859 |
def event_loop_settings(auto_launch=True):
"""Settings for pyMOR's MPI event loop.
Parameters
----------
auto_launch
If `True`, automatically execute :func:`event_loop` on
all MPI ranks (except 0) when pyMOR is imported.
"""
return {'auto_launch': auto_launch} | 9fc1565c093cb85d2019a2453df998aa0e54c598 | 686,860 |
import statistics
def compute_metrics(qids_to_relevant_passageids, qids_to_ranked_candidate_passages,MaxMRRRank = 10):
"""Compute MRR metric
Args:
p_qids_to_relevant_passageids (dict): dictionary of query-passage mapping
Dict as read in with load_reference or load_reference_from_stream
p_q... | 5761bcf1e85208fa228b7bf74b029f95a1fb8ab1 | 686,861 |
def mate_in_region(aln, regtup):
""" Check if mate is found within region
Return True if mate is found within region or region is None
Args:
aln (:obj:`pysam.AlignedSegment`): An aligned segment
regtup (:tuple: (chrom, start, end)): Region
Returns:
bool: True if mate is within ... | 969acb9ce356bf0a20b381ffe494705a3de2b5e2 | 686,862 |
import argparse
def parse_arguments():
"""Parse the arguments passed by the user if invoked as main script
:return: args
:rtype: list
"""
parser = argparse.ArgumentParser(
description="Process user intention (add or remove new user")
parser.add_argument("action", choices=['add', ... | e5663c896f15671fcca95c6531aaf755151ed62a | 686,863 |
def format_query(query, params=None):
"""
Replaces "{foo}" in query with values from params.
Works just like Python str.format
:type query str
:type params dict
:rtype: str
"""
if params is None:
return query
for key, value in params.items():
query = query.replace('... | cd4c1d42f139a321980c329cdb45953519bd3164 | 686,864 |
def rename_dupe_cols(cols):
"""
Renames duplicate columns in order of occurrence.
columns [0, 0, 0, 0]
turn into [0, 1, 2, 3]
columns [name10, name10, name10, name10]
turn into [name10, name11, name12, name13]
:param cols: iterable of columns
:return: unique columns with digits increme... | 18e400609581c280f6a89babf5fd1f98ccab40a1 | 686,865 |
def find_all(soup, first, second, third):
"""
A simpler (sorta...) method to BeautifulSoup.find_all
:param soup: A BeautifulSoup object
:param first: The first item to search for. Example: div
:param second: the second aspect to search for. The key in the key:value pair. Example: class
:param th... | df3109571e9a11710a1ecc3f7b835ca019229a24 | 686,866 |
def add_suffix_to_parameter_set(parameters, suffix, divider='__'):
"""
Adds a suffix ('__suffix') to the keys of a dictionary of MyTardis
parameters. Returns a copy of the dict with suffixes on keys.
(eg to prevent name clashes with identical parameters at the
Run Experiment level)
"""
s... | 39c184a6d836270da873b4c2e8c33e9a1d29f073 | 686,867 |
def value_to_string(ast):
"""Remove the quotes from around the string value"""
if ast.value[:3] in ('"""', "'''"):
ast.value = ast.value[3:-3]
else:
ast.value = ast.value[1:-1]
return ast | 01308b44f404dd68b0e5fdd4c5cfa02a0e19ed3f | 686,868 |
def module_of (object) :
"""Returns the name of the module defining `object`, if possible.
`module_of` works for classes, functions, and class proxies.
"""
try :
object = object.__dict__ ["Essence"]
except (AttributeError, KeyError, TypeError) :
pass
result = getattr (object,... | 0adc87b309d466ba1f5f1f78ad50379397528fb2 | 686,869 |
import itertools
def nQubit_Meas(n):
"""
Generate a list of measurement operators correponding to the
[X,Y,Z]^n Pauli group
Input:
n (int): Number of qubits to perform tomography over
Returns:
(list) list of measurement operators corresponding to all combinations
... | ff3ed6a75d160d139e3192d8d5255d4afa2930a8 | 686,870 |
import copy
def make_all_strokes_dashed(svg, unfilled=False):
"""
Makes all strokes in the SVG dashed
:param svg: The SVG, in xml.etree.ElementTree format
:param unfilled: Whether this is an unfilled symbol
:return: The resulting SVG
"""
stroke_elements = [ele for ele in svg.findall('.//*[... | fe1a0e6aaf72ec53edfd93da948ae953a3e7ae3c | 686,871 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.