content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def reduce2scalar_seasonal_zonal( mv, seasons=seasonsyr, region=None, latmin=None, latmax=None, vid=None, gw=None ):
"""returns the mean of the variable over the supplied latitude range (in degrees).
The computed quantity is a scalar but is returned as a cdms2 variable, i.e. a MV.
The input mv is a cdms2 va... | 5716c69733062ba39a5083a10edb202b638bec51 | 42,142 |
def parallel(iterable, count, callable, *a, **kw):
"""
Concurrently fire C{callable} for each element in C{iterable}.
Any additional arguments or keyword-arguments are passed to C{callable}.
@type iterable: C{iterable}
@param iterable: Values to pass to C{callable}.
@type count: C{int}
... | 0f7d277d0c8719a4e1e00a9e4a4f988a7778ddb4 | 42,144 |
def create_user_object(uname, psswd,sub_u):
"""Return a User object with given information."""
return User(
username=uname,
password=pwd_context.hash(psswd),
sub_user=sub_u
) | aa8f6bf5197798fc98a1ea9dd977dcbe3982fe93 | 42,145 |
def myreplace(old, new, s):
"""Replace all occurrences of old with new in s."""
result = " ".join(s.split()) # firsly remove any multiple spaces " ".
return new.join(result.split(old)) | 4355251d3c52424041ce86b2449843c565beb301 | 42,146 |
import re
def need_analyzer(args):
""" Check the intent of the build command.
When static analyzer run against project configure step, it should be
silent and no need to run the analyzer or generate report.
To run `scan-build` against the configure step might be neccessary,
when compiler wrapper... | 8dc2f6cb3071cf3d8190261c4136670b2dec5b5a | 42,147 |
import torch
def angular_terms(Rca: float, ShfZ: Tensor, EtaA: Tensor, Zeta: Tensor,
ShfA: Tensor, vectors12: Tensor) -> Tensor:
"""Compute the angular subAEV terms of the center atom given neighbor pairs.
This correspond to equation (4) in the `ANI paper`_. This function just
compute t... | 56b8cb281bd862eab6a8e39a8e4947a46b495e7d | 42,148 |
def cookie_session_name() -> str:
"""
Retorna o nome do cookie para a sessão.
"""
return "ticket_session" | eaa4517b0635ea8e57d07a46d90c6bcdc3d044e8 | 42,149 |
def query():
"""Display search requests and pagination via GET"""
if not request.args.get("search"):
return redirect(url_for("index"))
if request.args.get("start") is None or int(request.args.get("start")) < 0:
start = 0
else:
start = int(request.args.get("start"))
query = ... | 82f6f2db5dede75f7e6df31f8681b298986a75ac | 42,150 |
import random
def select_a_genome():
"""
This function randomly selects a genetic operation from following options to produce a genome:
1. Crossover two randomly selected genomes
2. Random selection from available genomes
3. Latest genome
4. Best fitness ever
5. Mutate genome with highest ... | 9db4e137cab04209817198c8c7da13886b7b2650 | 42,151 |
from re import X
from re import I
def prep_qubits(qubits: list, n: int):
"""
Generate a quil program which prepares given qubits in a state representing number n.
:param n: the number to write
:param qubits: qubit indexes to write the number n
:return: circuit to write number n on given qubits.
... | 5ad6fe7ab67e7f6ac8d57d9f3d209d9bf4e7bf32 | 42,152 |
def plot_seq_label(ax, X, Fs=1, color_label=[], direction='horizontal',
fontsize=10, time_axis=False, print_labels=True):
"""Plot label sequence in the style of annotations
Notebook: C4/C4S5_Evaluation.ipynb
Args:
ax: Axis used for plotting
X: Label sequence
Fs: ... | 02d798b855f056a5118125f2609fb2d44eea6789 | 42,153 |
def _sqrt_symbolic_denest(a, b, r):
"""Given an expression, sqrt(a + b*sqrt(b)), return the denested
expression or None.
Algorithm:
If r = ra + rb*sqrt(rr), try replacing sqrt(rr) in ``a`` with
(y**2 - ra)/rb, and if the result is a quadratic, ca*y**2 + cb*y + cc, and
(cb + b)**2 - 4*ca*cc is 0... | bea440797224e546f0aac8c93590020041047f86 | 42,154 |
def blackNormalizeImage(a):
"""
Normalizes numarray to fit into an image format
that is values between 0 and 255.
"""
#Minimum image value, i.e. how black the image can get
minlevel = 0.0
#Maximum image value, i.e. how white the image can get
maxlevel = 200.0
#Maximum standard deviations to include, i.e. pixe... | ac3cd6d8ea34982756ad806dc0e365b10c788604 | 42,155 |
def create_mfcc(path, sr=None, offset=0, duration=None):
"""Create an mfcc from the passed path"""
wave = AudioSegment.from_wav(path)
mono = wave.channels != 1
if duration:
y, sr = librosa.load(path, sr=sr, mono=mono, offset=offset, res_type='kaiser_fast')
else:
y, sr = librosa.load(... | 442736b0a031c2fb7ce2ab95c13c5ecbd114d472 | 42,156 |
def maybe_pad(draw, regex, strategy, left_pad_strategy, right_pad_strategy):
"""Attempt to insert padding around the result of a regex draw while
preserving the match."""
result = draw(strategy)
left_pad = draw(left_pad_strategy)
if left_pad and regex.search(left_pad + result):
result = left... | 6e3a6f1481e9d432b63cc237e68f89035aa56588 | 42,157 |
import re
def parseSections (fd):
"""
Quick&Dirty parsing for GNU ld’s linker map output, needs LANG=C, because
some messages are localized.
"""
sections = []
# skip until memory map is found
found = False
while True:
l = fd.readline()
if not l:
break
... | f33c430e4f76f6913fd63fa5bea9b48111a87451 | 42,158 |
def from_year_fraction(date: float):
"""
this function takes a date in float as input and return datetime as output
Parameter:
--------
date: float such as 2000.02
Return:
--------
the corresponding datetime object
"""
if type(date).__name__ != 'float':
raise Ty... | d7d8c2412ff5dcb4ad10d508170c76964768b431 | 42,159 |
def even(value):
"""Simple validator defined for test purpose"""
return not (int(value) % 2) | 1774e55ef53799ff16f232c3ca51c322cadf1d54 | 42,160 |
def new_webui_log_file():
"""Create new logging files for web ui."""
ui_stdout_file, ui_stderr_file = new_log_files(
"webui", redirect_output=True)
return ui_stdout_file, ui_stderr_file | beef8637b9e14b20ab714dae42d7d9698a87eec0 | 42,162 |
from typing import Optional
def get_quarter_start(x: Optional[Date] = None) -> Date:
"""
Returns the quarter start as of the given date.
>>> get_quarter_start(Date(2017, 1, 1))
datetime.date(2017, 1, 1)
>>> get_quarter_start(Date(2017, 5, 31))
datetime.date(2017, 4, 1)
>>> get_quarter_sta... | 7a79dc9e01413dd6a802e30a89d5a52fd6dae71a | 42,163 |
def _compute_J(x, window_starts, L):
"""Compute the cost, which is proportional to the
difference between pairs of windows"""
# Get all windows and zscore them
N_windows = len(window_starts)
windows = np.zeros((N_windows, L))
for w in range(N_windows):
temp = x[window_starts[w]:window_s... | 0d035607d416d3e0cd23b0858ae869e04f1c5df5 | 42,164 |
def getAppLink(dic):
"""Returns the Link for Chapter Application Form.
dic -- Dictionary from the JSON with all values.
"""
return str(dic["content"]["$t"]).split(',')[3].split(' ')[2].strip() | 4525a9aa11a293666f14b22507ee1d8e67607cdd | 42,165 |
def test_parameter_3():
"""
Feature: Check the names of parameters.
Description: Check the name of parameter in init.
Expectation: No exception.
"""
class ParamNet(Cell):
def __init__(self):
super(ParamNet, self).__init__()
self.param_a = Parameter(Tensor([1], ms.... | 4f40fe29fa404a6a7d0231d97698cf1bfb22911b | 42,167 |
def veh_search_for_immediate_request(sim_time, prq, fleetctrl, list_excluded_vids=[]):
"""This function can be used to find pooling vehicles for an immediate service of a request.
:param sim_time: current simulation time
:param prq: PlanRequest to be considered
:param fleetctrl: FleeControl instance
... | 975200901be03626025f5483771cf30e82dab5b7 | 42,168 |
def rebase(df_: pd.DataFrame, base_year: int) -> pd.Series:
"""Rebase values to a given base year"""
base_values = (
df_.loc[df_.year.dt.year == base_year].set_index("iso_code")["value"].to_dict()
)
return round(100 * df_.value / df_.iso_code.map(base_values), 3) | 6483225b6f29b82f7c17db36d4d1aaad832abc59 | 42,169 |
def big_sliding_window(raster):
"""Creates 3D array organizing local neighbors at every index
Returns a raster of shape (L,W,9) which organizes (along the third
dimension) all of the neighbors in the original raster at a given
index, in the order [NW, N, NE, W, 0, E, SW, S, SE]. Outputs are
ordered... | 1d4592dbcd31bade5dde774f5814b6739229c323 | 42,170 |
def met_gfssdJ1_3sopt_tr50(P, Q, data_source, n, r, J=1, tr_proportion=0.5):
"""
FSSD-based model comparison test
* Use J=1 test location by default (in the set V=W).
* 3sopt = optimize the test locations by maximizing the 3-model test's
power criterion. There is only one set of test lo... | f41da6da3b64a9f926335381d84d3294ccbc6808 | 42,172 |
def find_permutation(s, pattern):
"""Find presence of any permutation of pattern in the text as a substring.
>>> find_permutation("oidbcaf", "abc")
True
>>> find_permutation("odicf", "dc")
False
>>> find_permutation("bcdxabcdy", "bcdxabcdy")
True
>>> find_permutation("aaacb", "abc")... | ba823208ed92fc3da9725081f3dfca87c5a47875 | 42,173 |
from typing import Callable
def crownibp_bound_propagation(
function: Callable[..., Nest[Tensor]],
*bounds: Nest[GraphInput]) -> Nest[LayerInput]:
"""Performs Crown-IBP as described in https://arxiv.org/abs/1906.06316.
We first perform IBP to obtain intermediate bounds and then propagate linear
bounds ... | ba6b572491cd8b807b75cb7fbeae85fd73787b81 | 42,174 |
def radioButtons(
widget,
master,
value,
btnLabels=(),
tooltips=None,
box=None,
label=None,
orientation=Qt.Vertical,
callback=None,
**misc
):
"""
Construct a button group and add radio buttons, if they are given.
The value with which the buttons synchronize is the ind... | 21aff75e25caf0d64c00b93b41018edb3fa2a3d3 | 42,175 |
def remove_plane(z, x, y):
"""Remove linear plane from z values. All need to have same shape!
Parameters
----------
z : [type]
[description]
x : [type]
[description]
y : [type]
[description]
"""
X_reg = np.vstack([x.flatten(), y.flatten(), x.flatten()*y.flatten()... | aa006f90158807caabef52cbe6884ed86fb3f4ae | 42,176 |
def preprocess_df(df: pd.DataFrame, userdict: str = None, jumanpp: bool = False) -> pd.DataFrame:
"""Perform preprocessing for given dataframe,
including, binarizing p/n labels to 1/0, normalization (JP), adding column of tokenized sentence.
"""
df = _binarize_pn(df)
if _check_lang(df) == 'ja':
... | f226ca7cdc87cbb394152989e837855b28928539 | 42,177 |
import torch
def get_model_predictions(data, model):
"""
Function to get prediction for a data point (datapoint being a tokenized text segment)
Input: data to predict, model to predict with
Output: prediction for input data
"""
output = model(torch.tensor([data['input_ids']]), attention_... | 06be220420a5bd556d9263ee05d56ddabc3f952f | 42,179 |
def p2p_gnuetella08():
"""
Returns the graph from: https://snap.stanford.edu/data/p2p-Gnutella08.html,
where we preprocess it to only keep the largest connected component
:return: undirected NetworkX graph
"""
graph = nx.read_edgelist(graph_dir + "p2p-Gnutella08.txt")
return graph.subgraph... | 0762b3ea1dcb19666c4c776d4fbfb1587254725c | 42,180 |
def object_lookup_command():
""" Sample query: querystring = {'filter':'subnet','count':'50','exact_subnet':'1.1.1.1'} """
querystring = {
'filter': 'subnet',
'count': '50',
'exact_subnet': demisto.args()['ip']
}
if not valid_ip(querystring['exact_subnet']):
return_error(... | facb66a246ad59eafb91510f4bcbdc33d0fb35ea | 42,181 |
def isObsMosaic(data, indx, mtype=MOSAIC_TYPES):
"""
Returns True or False if an observation is a mosaic of a
type listed in MOSAIC_TYPES.
data : Contains data from readObservations() in the DATA key
indx : Row number within data
mtype : A list of mosaic types
The typ... | abb6f92316ec00aae8c916ff486086d42c224110 | 42,182 |
import re
def most_probable_alleles(allele_list):
"""
Identify the most probable haplotype in a list
:param list allele_list: List of tuples of (allele, p_value)
:return: List of 2 most probable alleles in the group
:rtype: list[str]
"""
all_alleles = defaultdict()
# First collect all... | 6efd5a5063e5ee5541f05f8bb2036f3282cc16eb | 42,183 |
def bootstrap_freq_sweep_ci(df, quantity, replicate_identifier,
n_bootstrap, ci, estimator=np.mean):
""" Gets bootstrap confidence interval for an estimator of
frequency sweep (or time sweep) data. Boot strap can be either a
percentile bootstrap of an estimator of a studentized bootstra... | 1aa3db386dd3d437fd2ea7815d88840cb3d2912b | 42,184 |
def atcab_sha_hmac(data, data_size, key_slot, digest, target):
"""
Use the SHA command to compute an HMAC/SHA-256 operation.
Args:
data Message data to be hashed. (bytearray or bytes)
data_size Size of data in bytes. (int)
key_slot Slot key id to ... | 12abcb1c7eb42c8db22289885fa3aba4f6377105 | 42,185 |
def ra_parser(lines):
"""return a list from RA lines.
The RA (Reference Author) lines list the authors of the paper (or other
work) cited. RA might be missing in references that cite a reference group
(see RG line). At least one RG or RA line is mandatory per reference block.
All of the authors ar... | d34eefdeb1b33628ad9525160cb93bc9c0e1943e | 42,187 |
def load_markercolors():
"""
Returns a dictionary mapping sources of the E. coli data with standard colors
and glyphs. This ensures constant marking of data across plots.
"""
colors, _ = get_colors()
mapper = {
'Bremer & Dennis, 2008': {'m':'X', 'm_bokeh':'circle_dot'},
'Brunsch... | 5711f7b32b1dcb7b88681fdd437957482406d2af | 42,188 |
import requests
def get_Dna_Token(dnac):
"""
Intent-based Authentication API call
The token obtained using this API is required to be set as value to the X-Auth-Token HTTP Header
for all API calls to Cisco DNA Center.
:param: dnac
:return: Token STRING
"""
url = 'https://{}/dna/system/... | ab55d6969e9d5521aea108e499061a2670a331cb | 42,189 |
def un_map_pack_response_edition_modifier(response_modifier):
"""
Returns an un-map-packer to the given response modifier for message edition endpoints.
Parameters
----------
response_modifier : `None`, ``ResponseModifier``
The response modifier to un-map-pack if any.
Returns
... | 277ab1ec6d9c6ed3283bcdbde0842276c1940efb | 42,190 |
def _extract_non_mrjob_tags(cluster):
"""get tags from a cluster as a dict, excluding tags starting with
``__mrjob_``"""
return {k: v for k, v in _extract_tags(cluster).items()
if not k.startswith('__mrjob_')} | d0ef1066cd4f6b340d915a15ea9790dbca9ec74b | 42,191 |
def calc(diff, pool, torment=5, charmed=1):
"""
api call to get the probabilities of a dice pool.
"""
root = wodDice.PoolCalc(pool, diff, torment, charmed)
s = root.summary()
result = {
'pool': pool,
'diff': diff,
'torment': torment,
'charmed': charmed,
'F... | 432e3013ac452ae596f0269a769059c19fd8a4b1 | 42,192 |
def update_xml_for_new_img(current_ome_xml_str, new_xyzct, bf_dtype, is_rgb, pixel_physical_size_xyu=None, channel_names=None, perceputally_uniform_channel_colors=False):
"""Update dimensions ome-xml metadata
Used to create a new ome-xml that reflects changes in an image, such as its shape
If `current_ome... | 629c0d545560bce60e4666e90414bb0dc8e6961e | 42,193 |
from .. import url_name as _url_name
def url_name(context):
""" Returns URL name of the current request.
Example::
{% url_name as current_url_name %}
{% if current_url_name != 'auth_login' %}
<li>
<a href="{% url 'auth_login_next' request.get_full_path|urlencode %}">
... | f8d159f715e1054fa543f0d2ba1c795c5ea7f995 | 42,194 |
def lowest_common_ancestor(G, node1, node2, default=None):
"""Compute the lowest common ancestor of the given pair of nodes.
Parameters
----------
G : NetworkX directed graph
node1, node2 : nodes in the graph.
default : object
Returned if no common ancestor between `node1` and `node2`... | 39c0e53b823f9303cb11485bf0932ddfb5c33c2b | 42,195 |
def cross_entropy(prediction, target):
"""
prediction should be probabilities [N × C], target should be label index (0 ~ C-1)
:param prediction: size: [N, C]
:param target: size: [N]
:return:
"""
return F.cross_entropy(prediction, target) | b0afc3165d3dc3f36ab9ff712e8dcfb65ad683de | 42,196 |
import six
def resolve_class(classref):
"""Attempt to return a Python class for the input class reference.
If `classref` is a class or None, return it. If `classref` is a
python classpath (e.g., "foo.bar.MyClass") import the class and return
it.
Args:
classref: A fully-qualified Python p... | 5d6cea47b178bc217ff0ed9c8eb128641ce7dc25 | 42,197 |
def nms(bboxes, score_threshold, iou_threshold, sigma=0.3):
"""
:param bboxes:
假设有N个bbox的score大于score_threshold,那么bboxes的shape为(N, 6),存储格式为(xmin, ymin, xmax, ymax, score, class)
其中(xmin, ymin, xmax, ymax)的大小都是相对于输入原图的,score = conf * prob,class是bbox所属类别的索引号
:return: best_bboxes
假设NMS后剩下N个bbox,那么b... | 1a95bd0e3304dd7bff1953c061f5b1b18fc80c63 | 42,198 |
def QCLog_Meta():
"""QCLog_Meta() -> MetaObject"""
return _DataModel.QCLog_Meta() | 4d209a16efe053ca59eb0d23a50e4e521bc45fc0 | 42,199 |
def nice_Horizons(target, centre, epochs, id_type, refplane='earth'):
"""
Mike Alexandersen
Convenience function to reformat data returned by Horizons
Only require the inputs I actually want to vary.
Return in the format I actually want, not an astropy table.
"""
horizons_table = Horizons(t... | e3803f4886a10850199eeb2b8532a5a7db9ff103 | 42,200 |
import random
def policy_iteration(mdp,verbose=0):
"""Solves an MDP by policy iteration"""
U = {s: 0 for s in mdp.states}
pi = {s: random.choice(mdp.actions(s)) for s in mdp.states}
if verbose:
print("Initial random choice:",pi)
iter_count=0
while True:
iter_count+=1
... | eeb017febda3857c62a9c5b83dee440b40ea7f2d | 42,201 |
def _func_call_cache_key(func, arg_map_function, *args, **kwargs):
"""
Returns a cache key based on the function's module,
the function's name, a stringified list of arguments
and a stringified list of keyword arguments.
"""
arg_map_function = arg_map_function or force_text
converted_args =... | f4ecfa3fdb5848b43c0df4cefd0f88b5fc149da3 | 42,203 |
def thermal_conductivity_carbon_steel(temperature):
"""
DESCRIPTION:
[BS EN 1993-1-2:2005, 3.4.1.3]
PARAMETERS:
OUTPUTS:
REMARKS:
"""
temperature += 273.15
if 20 <= temperature <= 800:
return 54 - 0.0333 * temperature
elif 800 <= temperature <= 120... | cfeb40bcff2b2acb6bf8c60f1bea2b00f323207a | 42,204 |
def reshape_image(frame, model):
"""
reshape_image:
Reshaping the camera input frame to fit the model
"""
image = frame.copy()
image = tf.image.resize_with_pad( np.expand_dims(image, axis=0), model.input_dim[0], model.input_dim[1] )
input_image = tf.cast(image, dtype=tf.float32)
... | b2defbb91c90be58d28b6c40b6c7002cb5b88c49 | 42,205 |
import inspect
def _get_func_signature(func):
"""
Given a function or method, return its signature.
For example:
1 function::
def func(a, b='a', *args):
xxxx
get_func_signature(func) # 'func(a, b='a', *args)'
2 method::
class Demo:
def __init__(... | 39907227e724b33c9ec1f56fe2a91cda3ecd1d53 | 42,206 |
def get_password():
"""
:return: the password of the user (needed for lid)
"""
global _password
return _password | c08d5c41041d4807426092972a40589cff6e031c | 42,207 |
from typing import Callable
from typing import Tuple
def get_chosen_table_size(input_text: str, get: Callable[[str], QWidget]) -> Tuple[int, int]:
"""
Returns chosen table size from gui according to given input text
"""
if len(input_text) <= 0:
return (0, 0)
sizes, _ = get_potential_tabl... | 458176b796ed3312c6ec25bf8f1537bc5b6169d4 | 42,209 |
def get_scheme(url):
"""
Get the scheme from a URL, if the URL is valid.
Parameters:
url: A :term:`native string`.
Returns:
The scheme of the url as a :term:`native string`, or ``None`` if the
URL was invalid.
"""
try:
return urlparse(url).scheme
except Valu... | 40a400faa1f5924730a481d66c5f13eeee67a61b | 42,210 |
def fast_inverse_hadamard_transform(k, dist):
"""Performs inverse Hadamard transform."""
if k == 1:
return dist
dist1 = dist[0:k // 2]
dist2 = dist[k // 2:k]
trans1 = fast_inverse_hadamard_transform(k // 2, dist1)
trans2 = fast_inverse_hadamard_transform(k // 2, dist2)
trans = np.concatenate((trans1 +... | 88448b0fa8ea173c034adcc53d549b0b30f1323b | 42,211 |
def putListIntoInt(inList, base = 2):
"""takes a list of values and converts it into an int"""
string = "".join(str(i) for i in inList)
return int(string, base) | a73c3f64e44962a34d974098e0b04fe92395adc8 | 42,212 |
def parse_money(s: str, *, unit="円") -> int:
"""Parse amount of money en JPY.
The unit of string ("円" or "万円") can be chosen the to apply
the appropriate conversion to JPY units.
"""
if s == "-":
return 0
multipliers_by_unit = {"円": 1, "万円": 10000}
pattern = rf"(\d*[.]?\d+){unit}"
... | 8389c7eb1144d966ff5731ae6415bc7208e7e50f | 42,213 |
def false_pred():
"""Returns a predicate that always returns ``False``."""
def new_pred(*args):
return False
return new_pred | 07dcd2e8594bd27eb4d520b240a0e3e722c7bc79 | 42,214 |
def DeferredLightResolveAddShadowManager(builder, shadowManager):
"""This method is deprecated. Please switch to AddShadowManager."""
return AddShadowManager(builder, shadowManager) | 3e143ca583a5a0772a0246f8e34dae22acf3d4cd | 42,215 |
def calculate_speech_ratio(vad):
"""Calculate percentage of time when each speaker is active"""
speaker1 = np.sum(vad[:, 0]) / vad.shape[0]
speaker2 = np.sum(vad[:, 1]) / vad.shape[0]
speakers = speaker1 + speaker2
return np.array([[speaker1 / speakers, speaker2 / speakers], [speaker1, speaker2]]) | 81b7a1178bd23b1d4a4e024792da7eae8057efb3 | 42,216 |
def get_leaves(conn, category, attached_db="", tbl=""):
"""returns a list of 'category' objects in attached_db
[objectCode, objectLabel, Definition, 'sub-level']
"""
# create formatting shortcuts
def f(t):
return ('"%s"' % t.replace('"', '""')) if t != "" else t
def d(t):
return... | 3bb3570e9d9408011aa186aab39232d64a9c9cc2 | 42,217 |
def start_session(file_name='appdata.db', echo=False):
""" 既存のデータベースを使ってセッション開始 """
db_engine = create_engine('sqlite:///' + file_name, echo=echo)
metadata = Base.metadata
Session = sessionmaker(bind=db_engine)
return Session() | 29517df5edd27419a56892e02175c5b7b39affa3 | 42,218 |
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, str... | e5941b107d7368c5c1f8f91802089b9d0300d7c7 | 42,219 |
def density_angle(rho0: Density, rho1: Density) -> float:
"""The Fubini-Study angle between density matrices"""
rho1 = rho1.permute(rho0.qubits)
return fubini_study_angle(rho0.tensor, rho1.tensor) | 203701a38fdf0e5fe02bacaed78282d95d0e84ce | 42,220 |
def _covariance_diag(matrix, dof, mem_threshold=(10**9)/8):
"""
computes the sample covariance matrix from a 2d-array.
matrix should be demeaned before!
Computes an optimal shrinkage estimate of a sample covariance matrix
as described by the following publication:
Schäfer, J., & Strimmer, K. (... | ce5d448c0e3f053ace30ed7340d7c7cc8f549446 | 42,222 |
def get_index_of_quantile(dist_mat: np.ndarray, quantile: float):
"""Returns index of `quantile` in `dist_mat`.
Args:
dist_mat (np.ndarray): square distance matrix
quantile (float): quantile
Returns:
index (int): index of quantile
"""
flat_dist_mat = dist_mat.flatten()
... | 7eacf4bb431bc952c1ee859fe653b4e588cce7c4 | 42,223 |
def RefineBlock(high_inputs=None,low_inputs=None):
"""
A RefineNet Block which combines together the ResidualConvUnits,
fuses the feature maps using MultiResolutionFusion, and then gets
large-scale context with the ResidualConvUnit.
Arguments:
high_inputs: The input tensors that have the high... | c4e4e6883869af848de95be124205a3a0ac62011 | 42,224 |
import typing
def process_get_account_transactions(
status: int,
json: list,
network_type: models.NetworkType,
) -> typing.Sequence[models.Transaction]:
"""
Process the "/account/{public_key}/transactions" HTTP response.
:param status: Status code for HTTP response.
:param json: JSON data... | e52396610bc536fd7c2246205080f95a0358f282 | 42,225 |
import psi4
def psi4(input_data):
"""
Runs Psi4 in API mode
"""
# Insert API path if needed
psiapi = config.get_config("psi_path")
if (psiapi is not None) and (psiapi not in sys.path):
sys.path.insert(1, psiapi)
try:
except ImportError:
raise ImportError("Could not fi... | 66d4e0998441ef29d88d84a27e52417acfc115e0 | 42,226 |
import re
import functools
def in_struct(ln,FO,nesting=0):
"""Copy a top level structure over to the #define output, keeping track of
nested structures."""
if nesting == 0:
if re.match(r"(}.*);",ln):
FO.write(ln[:-1] + "\n\n");
return find_struct;
FO.write(ln + " \\\n"... | e538f1906c1e7f1817185d163f47bf4753993e97 | 42,227 |
import random
def __random_positions(max_position):
"""Generates two random different list positions given a max position.
The max position is exclusive.
...
Args:
max_position(integer): The maximum position
"""
[lhs, rhs] = random.sample(range(0, max_position - 1), 2)
return (lh... | ee35a6ed30400c885b7769962de483c34cc0ab41 | 42,228 |
def errorEllipse(fit, p1, p2, n=100):
"""
fit is a result from leastsqFit (dict)
p1, p2 are parameters name (str)
n number of point in ellipse (int, default 100)
returns ellipse of errors (x1, x2), computed from the covariance. The n values are centered
around fit['best']['p1'] and fit['best'][... | 377a687a43ad473c2107de3ac00ac71d8a0dc706 | 42,229 |
def app_info(app_name):
"""gets app info"""
app_path = app_installed(app_name)
try:
return readPlist(app_path + "/Contents/Info.plist")
except ExpatError:
return | d98289817310c5359f81e6dea822dda0be398525 | 42,231 |
def create_deployment(inputs,
labels,
blueprint_id,
deployment_id,
rest_client):
"""Create a deployment.
:param inputs: a list of dicts of deployment inputs.
:type inputs: list
:param labels: a list of dicts of depl... | 84b7a13c0ef6b67b20755bc92ecc6814db0be5b0 | 42,232 |
from typing import Dict
def _refine_projectlist(response: Dict, Translator=DataFields) -> ProjectList:
"""Parse the project list response.
Args:
response: Ganttic API response
Translator: Description of fields
Returns: project List Pydantic.
"""
return ProjectList(**response) | 77b77f3321e8f078087245fb1d18c62fa954e951 | 42,233 |
from typing import Union
from typing import IO
import click
from io import StringIO
from typing import cast
from pathlib import Path
from typing import TextIO
def parse(
in_data: Union[str, PathLike, IO],
encoding: str = "utf-8",
results_fname: str = _RESULTS_FNAME,
max_size: int = _MAX_SIZE,
) -> dic... | 0878a578e42b5e668315f9787784465cfd3ef162 | 42,234 |
import re
def split_sentences(text, delimiter="\n"):
""" Split a text into sentences with a delimiter"""
return re.sub(r"(( /?[.!?])+ )", rf"\1{delimiter}", text) | 7f69afaa8add8947073d1bf4133da145fba81cac | 42,236 |
def getFPSA3(ChargeSA):
"""The calculation of fractional charged partial negative surface areas
-->FPSA3
"""
temp=0.0
for i in ChargeSA:
temp=temp+i[2]
if temp == 0.0:
return 0.0
else:
return getPPSA3(ChargeSA)/temp | 88316a65865faee863ef07f9c01c49320fcbf030 | 42,237 |
def load_FF(data_files, parm_dict, h5_path, verbose=False, loadverbose=True,
average=True, mirror=False):
"""
Generates the HDF5 file given path to data_files and parameters dictionary
Creates a Datagroup FFtrEFM_Group with a single dataset in chunks
Parameters
----------
data_files : list
List of the \*.i... | 24cbd276dcc2a41e214eac8609d77b28f267ba9d | 42,238 |
def DoG1filter(a, sigma):
"""
Creates 2 1-D gaussian filters.
Parameters
----------
a : half-support of the filter.
sigma: standard deviation.
Notes
-----
2-D DoG filters can be contructed by combining 2 1-D DoG filters separably, in x and y directions
Refere... | bb63f5eb7fa4e4546d727a1443ee6209735e1ce8 | 42,239 |
def items_iterator(dictionary):
"""Add support for python2 or 3 dictionary iterators."""
try:
gen = dictionary.iteritems() # python 2
except:
gen = dictionary.items() # python 3
return gen | e3da23ad32f491958887f14aae1f4d34a5d58c4e | 42,240 |
def do_permutation(df_reference: pd.DataFrame,
df_future: pd.DataFrame,
seed: int) -> pd.DataFrame:
"""
Conducts a permutation test with the given reference classifications,
future classifications, and seed.
"""
# Permute the reference and future data.
np.... | 8abae83e0b43edcc7387319e9e4125e881370379 | 42,241 |
def control_game(cmd):
"""
returns state based on command
"""
if cmd.lower() in ("y", "yes"):
action = "pictures"
else:
action = "game"
return action | 669a7b4a9335719aa9176c32c9891f6d017a1bc0 | 42,242 |
def evaluate_metric(logger, pred_labels_list, gt_labels_list, label2class_list, test_classes):
"""
:param pred_labels_list: a list of np array, each entry with shape (n_queries*n_way, num_points).
:param gt_labels_list: a list of np array, each entry with shape (n_queries*n_way, num_points).
:param test... | 3cdc058d34713e92c463114d4b2217450edc75d9 | 42,243 |
import re
def answer_problem(problem):
""" 回答问题 """
problem_context = re.findall(r'(\d+)(\w+)(\d+)', problem)[0]
expression = '%s%s%s' % (problem_context[0], _operators[problem_context[1]], problem_context[2])
return int(eval(expression)) | c9f4ed16ae542ba7074c90264db86eccadd311cd | 42,244 |
def Extrema_Curve2dTool_Parabola(*args):
"""
:param C:
:type C: Adaptor2d_Curve2d &
:rtype: gp_Parab2d
"""
return _Extrema.Extrema_Curve2dTool_Parabola(*args) | df03eece6537847a8fc98dc04709fa403a73ef0c | 42,245 |
def _get_argnames_argvalues(argnames=None, argvalues=None, **args):
"""
:param argnames:
:param argvalues:
:param args:
:return: argnames, argvalues - both guaranteed to be lists
"""
# handle **args - a dict of {argnames: argvalues}
if len(args) > 0:
kw_argnames, kw_argvalues = ... | 4958f038f00fa17acb6930adc9fa406e8d96125c | 42,246 |
def clip(x, a_min, a_max):
"""Clip (limit) the values in an array. Given an interval, values
outside the interval are clipped to the interval edges.
Parameters
----------
x : tvm.Tensor
Input argument.
a_min : int or float
Minimum value.
a_max : int or float
Maximum ... | 45993469a5bab1474c5682a0e9a053507d4b01cb | 42,248 |
def sprints_needed(data):
""" sprints needed """
clus = StackCluster()
for j in range(data[1]):
clus.add_stack(True)
init = int(data[2] / max(data[0]) / data[1])
for j in range(data[1]):
sim = np.random.choice(data[0], init, replace=True)
for k in range(init):
... | 36caa57cf89ee9448b07d88efdde266de25755c1 | 42,249 |
import requests
def get_ipo_calendar(from_date: str, to_date: str) -> pd.DataFrame:
"""Get IPO calendar
Parameters
----------
from_date : str
from date (%Y-%m-%d) to get IPO calendar
to_date : str
to date (%Y-%m-%d) to get IPO calendar
Returns
-------
pd.DataFrame
... | 194319d01a4327037d1742dadeae97c37a9d7225 | 42,250 |
import timeit
def run_trial(rep, num):
"""Sleep for 100 milliseconds, 'num' times; repeat for 'rep' attempts."""
sleep = 'sleep(0.1)'
return min(timeit.repeat(stmt=sleep, setup = 'from time import sleep', repeat=rep, number=num)) | fcdcea9e63531b7de12ccbf27ab584829b8354b9 | 42,251 |
def cholesky(A):
"""
# A is positive definite mxm
"""
assert A.shape[0] == A.shape[1]
# assert all(A.eigenvals() > 0)
m = A.shape[0]
N = deepcopy(A)
D = ones(*A.shape)
for i in range(m - 1):
for j in range(i + 1, m):
N[j, i] = N[i, j]
D[j, i] = D[i, j]... | 593b9adcbdac3721e314a377b68982fb0d44d3c7 | 42,252 |
def apply_sprite(image, sprite,w,x,y, angle, ontop = True):
"""
image: array or image like object
sprite: array or image like object
w:int
x:int
y:int
"""
sprite = rotate_image(img = sprite, angle = angle, scale = 1.0)
sprite, y_final = adjust_sprite2head( sprite , w, ... | b8d32323f691732ef57b3a95d4b1da9c5fe1a6cb | 42,253 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.