content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import functools
def _map_windows(
df, time, method="between", periodvar="Shift Date", byvars=["PERMNO", "Date"]
):
"""
Returns the dataframe with an additional column __map_window__ containing the index of the window
in which the observation resides. For example, if the windows are
[[1],[2,3]], a... | 31b4780ba7f67dde12dcc75af9abbcf88a1b269a | 3,629,900 |
def unpack_context(msg):
"""Unpack context from msg."""
context_dict = {}
for key in list(msg.keys()):
key = str(key)
if key.startswith('_context_'):
value = msg.pop(key)
context_dict[key[9:]] = value
context_dict['msg_id'] = msg.pop('_msg_id', None)
context_d... | 03c42f2e137e219dd15591588d28cf3be897e2fa | 3,629,901 |
def concat_cols(*args):
"""
takes some col vectors and aggregetes them to a matrix
"""
col_list = []
for a in args:
if isinstance(a, list):
# convenience: interpret a list as a column Matrix:
a = sp.Matrix(a)
if not a.is_Matrix:
# convenience: al... | ca0731bdd35909ec544e76b80dce73ef96863a7a | 3,629,902 |
import sys
import random
def accuracy_analogy(wv, questions, most_similar, evalVocab, topn=10, case_insensitive=True,usePhrase=True, sample=0):
"""
Compute accuracy of the model. `questions` is a filename where lines are
4-tuples of words, split into sections by ": SECTION NAME" lines.
See questions-w... | 6e0af67d04cdb09ccd5c490018bfcba17dfbd908 | 3,629,903 |
def gen_connected_locations(shape, count, separation, margin=0):
""" Generates `count` number of positions within `shape` that are touching.
If a `margin` is given, positions will be inside this margin. Margin may be
tuple-valued. """
margin = validate_tuple(margin, len(shape))
center_pos = margin ... | 9432d4df6e6b1bc5ff2fe762e240f051c07ae81e | 3,629,904 |
import warnings
def transp():
"""
Instantiates the Transp() class, and shows the widget.
Runs only in Jupyter notebook or JupyterLab. Requires bqplot.
"""
warnings.simplefilter(action='ignore', category=FutureWarning)
return Transp().widget | f8f86eab3e428ebdee2be5a2fc83fe3bd3d61702 | 3,629,905 |
def oidc_supported(transfer_hop: DirectTransferDefinition) -> bool:
"""
checking OIDC AuthN/Z support per destination and source RSEs;
for oidc_support to be activated, all sources and the destination must explicitly support it
"""
# assumes use of boolean 'oidc_support' RSE attribute
if not tr... | 5bb49689b75e1329e2dda5a813ecbd11a346541e | 3,629,906 |
import os
def find_jest_configuration_file(file_name, folders):
"""
Find the first Jest configuration file.
Jest's configuration can be defined in the package.json file of your project,
or through a jest.config.js, or jest.config.ts, we only search the last two files.
"""
debug_message('find ... | 710ff3ba2b9aa24d504f9e51a102ca7083e295c6 | 3,629,907 |
import sympy
def replace_heaviside(formula):
"""Set Heaviside(0) = 0
Differentiating sympy Min and Max is giving Heaviside:
Heaviside(x) = 0 if x < 0 and 1 if x > 0, but
Heaviside(0) needs to be defined by user.
We set Heaviside(0) to 0 because in general there is no sensitivity. This
done ... | d1aff5e4a2dd68ba53ced487b665e485dab4b54d | 3,629,908 |
import click
import time
def check_enrolled_factors(ctx, users):
"""Check for users that have no MFA factors enrolled"""
users_without_mfa = []
msg = (
f"Checking enrolled MFA factors for {len(users)} users. This may take a while to avoid exceeding API "
f"rate limits"
)
LOGGER.i... | 6ab747684d4b39622149b2ead072b1fd1ac2fc6a | 3,629,909 |
def entry_cmp(sqlite_file1, sqlite_file2):
"""
Compare two sqlite file entries
in zookeeper to know the ordering
"""
seq_id1 = _get_journal_seqid(sqlite_file1)
seq_id2 = _get_journal_seqid(sqlite_file2)
return sequence_cmp(seq_id1, seq_id2) | d6ff9ee5e3aad62c096ed17106fb56d10b9d7de8 | 3,629,910 |
import functools
def fill_cn(bcm, n_metal2, max_search=50, low_first=True, return_n=None,
verbose=False):
"""
NOTE: Most likely broken - still need to extend to polymetallic cases
Algorithm to fill the lowest (or highest) coordination sites with 'metal2'
Args:
bcm (atomgraph.AtomGrap... | 8b4ac05e0abbadc34f154e4917959627600dcf0d | 3,629,911 |
import functools
def _clear_caches_after_call(func):
"""
Clear caches just before returning a value.
"""
@functools.wraps(func)
def wrapper(*args, **kwds):
result = func(*args, **kwds)
_clear_caches()
return result
return wrapper | cdc0342230d09d86021aafb23e4ae883dd30fee0 | 3,629,912 |
import os
def is_dicom(filename):
"""Returns True if the file in question is a DICOM file, else False. """
# Per the DICOM specs, a DICOM file starts with 128 reserved bytes
# followed by "DICM".
# ref: DICOM spec, Part 10: Media Storage and File Format for Media
# Interchange, 7.1 DICOM FILE MET... | 014c15481224413d6757c950a0888fb60e0f94d5 | 3,629,913 |
import random
import _bisect
def choices(population, weights=None, cum_weights=None, k=1):
"""Return a k sized list of population elements chosen with replacement.
If the relative weights or cumulative weights are not specified,
the selections are made with equal probability.
"""
n = len(populatio... | 1161b6c43fb54b32e54bf3c45d81abfa1c7261d8 | 3,629,914 |
def summarize(text: str) -> str:
"""Summarizes the text (local mode).
:param text: The text to summarize.
:type text: str
:return: The summarized text.
:rtype: str
"""
if _summarizer is None:
load_summarizer()
assert _summarizer is not None
tokenizer = get_summarizer_tok... | cc3fbee1ef27332733915d27758cdcaf045cd2c8 | 3,629,915 |
def linreg(array, dim=None, coord=None):
"""
Compute a linear regression using a least-square method
Parameters
----------
x : xarray.DataArray
The array on which the linear regression is computed
dim : str, optional
The dimension along which the data will be fitted. If not precised,
the first dimension wi... | 27ff54eccf92b3e1924316d022aeaac5abdb0bb3 | 3,629,916 |
import pkg_resources
def _gte(version):
""" Return ``True`` if ``pymongo.version`` is greater than or equal to
`version`.
:param str version: Version string
"""
return (pkg_resources.parse_version(pymongo.version) >=
pkg_resources.parse_version(version)) | f92d062d2d2ff37184bd7bd5740c8c586bf3e521 | 3,629,917 |
def read_data(path, format="turtle"):
"""
Read an RDFLib graph from the given path
Arguments:
path (str): path to a graph file
Keyword Arguments:
format (str): RDFLib format string (default="turtle")
Returns:
rdflib.Graph: a parsed rdflib.Graph
"""
g = rdflib.Grap... | 31965e0ccc43d873ce06e248ab9e771227b54aba | 3,629,918 |
def exact_change_recursive(amount,coins):
""" Return the number of different ways a change of 'amount' can be
given using denominations given in the list of 'coins'
>>> exact_change_recursive(10,[50,20,10,5,2,1])
11
>>> exact_change_recursive(100,[100,50,20,10,5,2,1])
4563
... | f18cd10802ba8e384315d43814fcb1dcd6472d78 | 3,629,919 |
from numpy import diff, where, array
def detectGap(date, gapThres):
"""
Detects gap in a date vector based on the user defined threshold.
Parameters
----------
date: list
Dates in UTCDateTime format to detect gaps within.
gapThres: float
Threshold in seconds over which to ... | 5cdbeb42d4110469b1a619118e014a0984bdc6c6 | 3,629,920 |
def enum(*sequential, **named):
"""
Enum implementation that supports automatic generation and also supports converting the values
of the enum back to names
>>> nums = enum('ZERO', 'ONE', THREE='three')
>>> nums.ZERO
# 0
>>> nums.reverse_mapping['three']
# 'THREE'
"""
enums = di... | 804801e5b94f0e559283deecdc808aea0446fb63 | 3,629,921 |
import warnings
import warnings
from dolo.algos.steady_state import find_steady_state
from dolo.numeric.extern.lmmcp import lmmcp
from dolo.numeric.optimize.newton import newton
def deterministic_solve(
model,
exogenous=None,
s0=None,
m0=None,
T=100,
ignore_constraints=False,
maxit=100,
... | d12b50a53e4c03cba4d1e1980c9b0eac41412311 | 3,629,922 |
def find_check_string_output( # type: ignore
ctx, class_name, method_name, as_python=True, fuzzy_match=False, pbcopy=True
):
"""
Find output of `check_string()` in the test running
class_name::method_name.
E.g., for `TestResultBundle::test_from_config1` return the content of the file
`./co... | 33b8c0d8ebd7399ef63a870f88ddfdfca671b686 | 3,629,923 |
from re import T
def index():
""" Dashboard """
if session.error:
return dict()
mode = session.s3.hrm.mode
if mode is not None:
redirect(URL(f="person"))
# Load Models
s3mgr.load("hrm_skill")
tablename = "hrm_human_resource"
table = db.hrm_human_resource
if ADM... | a19e62b3c3541b05bb066b54f91b46e9a1566c91 | 3,629,924 |
import requests
import os
import hashlib
def call_movebank_api(params):
"""
Authenticate with Movebank API and return the Response content
"""
response = requests.get('https://www.movebank.org/movebank/service/direct-read',
params=params,
auth=(os.getenv("MBUSER"),
os.getenv("MBPASS"))
)
if response.sta... | 5828508075e4ab09b053b79416b9db11bf1ba6b8 | 3,629,925 |
def Vfun(X, deriv = 0, out = None, var = None):
"""
expected order : r1, r2, R, a1, a2, tau
"""
x = n2.dfun.X2adf(X, deriv, var)
r1 = x[0]
r2 = x[1]
R = x[2]
a1 = x[3]
a2 = x[4]
tau = x[5]
# Define reference values
Re = 1.45539378 # Angstroms
re = 0.9625247... | 4b8b666c60900355a8a215728ae53feb37dd8313 | 3,629,926 |
def all_events(number=-1, etag=None):
"""Iterate over public events.
.. deprecated:: 1.2.0
Use :meth:`github3.github.GitHub.all_events` instead.
:param int number: (optional), number of events to return. Default: -1
returns all available events
:param str etag: (optional), ETag from a... | 0b620e00ceffe93b7a6bdf579f031942222d3f10 | 3,629,927 |
def mock_datetime(monkeypatch: MonkeyPatch) -> FakeDatetime:
"""Mocks dt.datetime
Returns:
FakeDatetime(2021, 3, 20)
"""
fake_datetime = FakeDatetime(2021, 3, 20)
fake_datetime.set_fake_now(dt.datetime(2021, 3, 20))
monkeypatch.setattr(dt, "datetime", FakeDatetime)
return fake_dateti... | 2b0bbc1b62f80636ea1622fcf4cfa6abfbda929b | 3,629,928 |
def Normalize(v):
"""
Normalizes vectors so length of vector is 1.
Parameters
----------
v : 2D numpy array, floats
Returns
-------
2D numpy array, floats
Normalized v.
"""
norm = np.zeros(v.shape[0])
for i, vector in enumerate(v):
norm[i] = np.linalg.norm(v... | f68bf8bfd2999b8755c3ace00154377fa19fe04c | 3,629,929 |
import requests
def get_instance_details(instance_id):
"""
Returns json detail of specific instance on slate
:return: json object of slate instance details
"""
query = {"token": slate_api_token, "detailed": "true"}
instance_detail = requests.get(
slate_api_endpoint + "/v1alpha3/instanc... | 77476be1de353079fdbca2b041b49b604e59929b | 3,629,930 |
def admin_lexers(request):
"""Form to configure lexers for file extensions."""
formset = AdminLexersFormSet.for_config()
if request.method == 'POST':
formset = AdminLexersFormSet.for_config(request.POST)
if formset.is_valid():
formset.save()
messages.success(request... | ef56353c0d25ebb4b5eb59dd1dad356a443b5a70 | 3,629,931 |
def ignore_module_import_frame(file_name, name, line_number, line):
"""
Ignores the frame, where the test file was imported.
Parameters
----------
file_name : `str`
The frame's respective file's name.
name : `str`
The frame's respective function's name.
line_number : `in... | 048283ec4a6aa0b1e51aadc033c0438ff125b102 | 3,629,932 |
import copy
import os
def validate_args(args):
"""
Validate parameters (args) passed in input through the CLI.
If necessary, perform transformations of parameter values to the simulation space.
:param args: [dict] Parsed arguments.
:return: [dict] Validated arguments.
"""
# note: input ... | 50be941326e149a1bc0baa99f688a09b627a68b7 | 3,629,933 |
def knapsack(val,wt,W,n):
"""
Consider W=5,n=4
wt = [5, 3, 4, 2]
val = [60, 50, 70, 30]
So, for any value we'll consider between maximum of taking wt[i] and not taking it at all.
taking 0 to W in column 'line 1' taking wt in rows 'line 2'
two cases ->
* cur_wt<=total wt in that c... | d030a57e8c7040cbd1f7a3556f21d599ac049428 | 3,629,934 |
def CNN_model_basic(img_height, img_width,OPTIMIZER):
"""
This is a customized function for generating a Keras model built-in Keras module
with pre-defined parameters and model architecture.
Parameters
-----------------
img_height,img_width = input image dimensions
OPTIMIZER = keras o... | f1123f2dfd07915d91eb68895a35a67d8f65e99b | 3,629,935 |
def get_filter_df(df, filter_col, targets, greater_than=True):
"""
Filter dataframe based on target column
Returns dataframe
"""
if filter_col in ["transactions", "category"]:
df_filter = get_filter_indicator_df(df, filter_col, targets)
elif filter_col == "rating":
if greater_th... | 6e8ad5c9efe65142dcb8d8f842e0b81a2946251b | 3,629,936 |
def filter_graph(graph, n_epochs):
"""
Filters graph, so that no entry is too low to yield at least one sample during optimization.
:param graph: sparse matrix holding the high-dimensional similarities
:param n_epochs: int Number of optimization epochs
:return:
"""
graph = graph.copy()
g... | 04af2804e208b8ce582440b2d0306fe651a583b0 | 3,629,937 |
def create_file_with_maximum_util(folder_file):
"""
from a folder with multiple .xls-files, this function creates a file with maximum values for each traffic counter
based on all .xls-files (ASFINAG format)
:param folder_file: String
:return: pandas.DataFrame
"""
# collect all .xls files as ... | 67a41549d00f4230b24fe0c45a5b4184912fe3ff | 3,629,938 |
def join_detectionlimit_to_value(df, **kwargs):
"""Put sign and numeric value together. For example: "<" + "100" = "<100")."""
df['Value'] = np.where(df['Value_sign'].isnull(), df['Value_num'], df['Value_sign'] + df['Value_num'].astype(str))
return df | d8b83ff4412408379e3c37a94b5c8b98eb8e129e | 3,629,939 |
def read_data(datapath, metadatapath, label_key='Schizophrenia'):
"""read_data
:param datapath: path to data file (gene)
:param metadatapath: path to meta data file of patients
:output x: data of shape n_patient * n_features
:output y: label of shape n_patients, label[i] == 1 means that the pat... | 5c0d72f6d4f0ae75befe6bb760ee6a1034cc85a3 | 3,629,940 |
def show(tournament, match_id):
"""Retrieve a single match record for a tournament."""
return api.fetch_and_parse(
"GET",
"tournaments/%s/matches/%s" % (tournament, match_id)) | ef168fd4c7ab06e0091bb9797ef953e1ec720a45 | 3,629,941 |
import json
def get_Frequency(ids):
"""
Restituisce la frequenze presente sul DB con un ID specifico
"""
db = Database()
db_session = db.session
data = db_session.query(db.frequency).filter(db.frequency.id == ids).all()
data_dumped = json.dumps(data, cls=AlchemyEncoder)
db_session.c... | 0f07c926626f0c5eb6fb6cdf14c81469fff6a108 | 3,629,942 |
import torch
def ycbcr_to_rgb_jpeg(image):
""" Converts YCbCr image to RGB JPEG
Input:
image(tensor): batch x height x width x 3
Outpput:
result(tensor): batch x 3 x height x width
"""
matrix = np.array(
[[1., 0., 1.402], [1, -0.344136, -0.714136], [1, 1.772, 0]],
d... | 3dcd8aaa32d7d558e8aa27a5f7f65ee85a105941 | 3,629,943 |
from sys import path
def gen_dist_train_test(train_df, test_df, pivot_table, gen_se_dist, gen_pro_cli_dist, external_info):
"""generate dist information on training data, merge the distribution with both training data and test data
The Data flow should look like this:
train_df ==> pivot_table ==> gen... | 35ec8b30679d41a53b88d07d98262adeecb32d7f | 3,629,944 |
def get_global_step(hparams):
"""Returns the global optimization step."""
step = tf.to_float(tf.train.get_or_create_global_step())
multiplier = hparams.optimizer_multistep_accumulate_steps
if not multiplier:
return step
return step / tf.to_float(multiplier) | 82440d93ecae202ced3fbbc98e7d0033e9fc0af4 | 3,629,945 |
import os
def search_file():
"""
Fonction effectuant une recherche récursive dans les dossiers de l'utilisateur
à l'aide de la commande LINUX 'find'
"""
if "username" not in session:
return redirect("/")
if request.method == "POST":
search = request.form['sb']
res=[]
... | 47d97dce7ff4d31a1c3d6328e95b36887bc4f8e4 | 3,629,946 |
def getValues(astr, begInd=0):
"""
Extracts all values (zero or more) for a keyword.
Inputs:
astr: the string to parse
begInd: index of start, must point to "=" if the keyword has any values
or ";" if the keyword has no values. Initial whitespace is skipped.
Returns a duple consisting of:
a tu... | adf37a9e8ef31ea5ff09d3c33836243cc2f0f49d | 3,629,947 |
def rev_find(revs, attr, val):
"""Search from a list of TestedRev"""
for i, rev in enumerate(revs):
if getattr(rev, attr) == val:
return i
raise ValueError("Unable to find '{}' value '{}'".format(attr, val)) | 6b9488023d38df208013f51ed3311a28dd77d9b8 | 3,629,948 |
def untempering(p):
"""
see https://occasionallycogent.com/inverting_the_mersenne_temper/index.html
>>> mt = MersenneTwister(0)
>>> mt.tempering(42)
168040107
>>> untempering(168040107)
42
"""
e = p ^ (p >> 18)
e ^= (e << 15) & 0xEFC6_0000
e ^= (e << 7) & 0x0000_1680
e ^... | 4118b55fd24008f9e96a74db937f6b41375484c3 | 3,629,949 |
def single_run(var='dt', val=1e-1, k=5, serial=True):
"""
A simple test program to do PFASST runs for the heat equation
"""
# initialize level parameters
level_params = dict()
level_params[var] = val
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['collocatio... | eba87530288fd600aec0ea349794d2b123c33ba4 | 3,629,950 |
def tofloat(img):
"""
Convert a uint8 image to float image
:param img: numpy image, uint8
:return: float image
"""
return img.astype(np.float) / 255 | 8e51259e478d30c8cfa01fb397ba022ca071c018 | 3,629,951 |
def get_session() -> requests_cache.CachedSession:
"""Convenience function that returns request-cache session singleton."""
if not hasattr(get_session, "session"):
get_session.session = requests_cache.CachedSession(
cache_name=str(CACHE_PATH), expire_after=518_400 # 6 days
)
... | d2b5f1be76c4a35adbede1a1bb280bf9ad43b06e | 3,629,952 |
def parse_html(html):
"""
Take a string that contains HTML and turn it into a Python object structure
that can be easily compared against other HTML on semantic equivalence.
Syntactical differences like which quotation is used on arguments will be
ignored.
"""
parser = Parser()
parser.fe... | 923cec59495b9e5e80c00e8af532040ec49a95fe | 3,629,953 |
from typing import List
def get_atomic_num_one_hot(atom: RDKitAtom,
allowable_set: List[int],
include_unknown_set: bool = True) -> List[float]:
"""Get a one-hot feature about atomic number of the given atom.
Parameters
---------
atom: rdkit.Chem.rdchem.At... | e323aa738321970ff49f555a41dea66d5280c328 | 3,629,954 |
from datetime import datetime
def ds_to_1Darr(varname,ds,srate='reg',dataw='notrend'):
"""
var is a string, varibale name from the ds
# choose how much data wrangling to do : remove mean or remove mean and trend
dataw = 'nomean' or 'notrend'
# choose the sampling rate: raw/unchanged or regular 1... | 4d5faa04a7c1a0bc0fdf29c3be0fe8a534953615 | 3,629,955 |
import inspect
def fs_check(**arguments):
"""Abstracts common checks over your file system related functions.
To reduce the boilerplate of expanding paths, checking for existence or ensuring non empty values.
Checks are defined for each argument separately in a form of a set
e.g
@fs_check... | 655e9eacc5557e1d71e301f9672ea8013450dca3 | 3,629,956 |
def old_pgp_edition(editions):
"""output footnote and source information in a format similar to
old pgp metadata editor/editions."""
if editions:
# label as translation if edition also supplies translation;
# include url if any
edition_list = [
"%s%s%s"
% (
... | 633fd75c82d02893e82bebb1d1d8fe3ba1d19c72 | 3,629,957 |
def ConstructApiDef(api_name,
api_version,
is_default,
base_pkg='googlecloudsdk.third_party.apis'):
"""Creates and returns the APIDef specified by the given arguments.
Args:
api_name: str, The API name (or the command surface name, if different).
... | b7b73e386d97d9195c64f6d3de9d642c0708fb9c | 3,629,958 |
def L2struct_array(L,dtype={'names':('score','col','S_init','tree'),'formats':('f4','S10000','S10000','S10000')}):
"""
Convert list output from extract_elite to structured Numpy array.
Contracts initial conditions string with tree string. Converts column string to int (after removing brackets).
Inputs:
L: li... | b53982b190ae392db4187073247ebe5a94c7a19f | 3,629,959 |
def build_model(x_train_text, x_train_numeric, **kwargs):
"""Build TF model."""
max_features = 5000
sequence_length = 100
encoder = preprocessing.TextVectorization(max_tokens=max_features,
output_sequence_length=sequence_length)
encoder.adapt(x_train_text.values)
... | 2ddc501d1a73527b57da20cb90ce8d47d82f1996 | 3,629,960 |
def find_group(name):
"""Make a special case of finding a group.
NB This uses ambiguous name resolution so only use it for a casual match
"""
return root().find_group(name) | d69646dba11c9b7925ac403453100b13ea874a98 | 3,629,961 |
def multiplicar(a, b):
"""
MULTIPLICAR realiza la multiplicacion de dos numeros
Parameters
----------
a : float
Valor numerico `a`.
b : float
Segundo valor numerico `b`.
Returns
-------
float
Retorna la suma de `a` + `b`
"""
return a*b | 2d1a56924e02f05dcf20d3e070b17e4e602aecf6 | 3,629,962 |
import pkg_resources
def email_vertices():
"""Return the email_vertices dataframe
Contains the following fields:
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 1005 non-null int64
1 dept 1005 non-null int64
... | 5ccba798717b69c367befb4bf3ab92d9d2fab37a | 3,629,963 |
def pascal_row(n):
"""returns the pascal triangle row of the given integer n"""
def triangle(n, lst):
if lst ==[]:
lst = [[1]]
if n == 1:
return lst
else:
oldRow = lst[-1]
def helpRows(lst1, lst2):
if lst1 == [] or lst2 == [... | 030fe3e574f4261c862a882e7fdeee836a1dffb7 | 3,629,964 |
def _apply_homography(H: np.ndarray, vdata: np.ndarray) -> tuple :
"""
Apply a homography, H, to pixel data where only v of (u,v,1) is needed.
Apply a homography to pixel data where only v of the (u,v,1) vector
is given. It is assumed that the u coordinate begins at 0.
The resulting vector (x,y,z) is normali... | 3f83dc9da32d03da8c35aabbdee8603264b31918 | 3,629,965 |
import logging
def asts(repo):
"""A dict {filename: ast} for all .py files."""
asts = {}
for src_fn, src in repo._calc('source_contents').iteritems():
try:
ast = pyast.parse(src)
except:
#if their code does not compile, ignore it
#TODO should probably be... | 46c912fd48832c68a0a441e33cf249a0fff14951 | 3,629,966 |
import re
def is_matching_layer(layer):
"""Returns true if the name of the given layer meets the criteria for
processing."""
return (
re.match(LAYER_PREFIX_TO_MATCH, layer.name()) and
re.match(f'.*{LAYER_SUBSTRING_TO_MATCH}.*', layer.name()) and
re.search(SUFFIX_CLEANABLE, layer.na... | e07c271f99db60ce06bff5d39ee91478937d272e | 3,629,967 |
def parse_call_no(field: Field, library: str) -> namedtuple:
"""
Parses call number data per each system rules
Args:
field: call number field, instance of pymarc.Field
library: library system
Returns:
"""
if library == "bpl":
callNo_data... | f5c787acfaa360315a4f49bf825410762d812e51 | 3,629,968 |
from re import A
def ni(num,tem):
""" num: density cm^-3 """
b = zeros( Aij.shape[0] + 2 , dtype='float64')
b[-1] = 10
# this line is REALLY STUPID, but for some pointless reason linalg experiences
# precision errors and thinks that A is singular when it is obviously not.
if tem > 30:
... | 83e5d918752c1241ce5e6917824526f5726edad2 | 3,629,969 |
def _parse_example_configuration(config, regexps):
"""
Parse configuration lines against a set of comment regexps
Args:
config(_io.TextIOWrapper): Example configuration file to parse
regexps(dict[str, list[tuple[re.__Regex, str]]]):
Yields:
str: Parsed configuration lines
"... | 86ff5db080f12dc624feb4ce20dcf659dcc2cb49 | 3,629,970 |
def readCosmicRayInformation(lengths, totals):
"""
Reads in the cosmic ray track information from two input files.
Stores the information to a dictionary and returns it.
:param lengths: name of the file containing information about the lengths of cosmic rays
:type lengths: str
:param totals: na... | 3d20f9e4763050169008875eb12195ec135030f4 | 3,629,971 |
import re
def get_package_version():
"""get version from top-level package init"""
version_file = read('pyshadoz/__init__.py')
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
... | 35d16c607ccbf9b0102e47cccf77e532269aea38 | 3,629,972 |
def setup_default_abundances(filename=None):
"""
Read default abundance values into global variable.
By default, data is read from the following file:
https://hesperia.gsfc.nasa.gov/ssw/packages/xray/dbase/chianti/xray_abun_file.genx
To load data from a different file, see Notes section.
Param... | b024fa2517b5578f8ee077eecd00fecf6583819d | 3,629,973 |
def resolve_conflicts2_next(pid):
"""
update page number to db
update kapr to db
flush related cache in redis
"""
user = current_user
assignment_id = pid + '-' + user.username
# find if this project exist
assignment = storage_model.get_conflict_project(mongo=mongo, username=user.use... | 092ac06d78357e8ddfba18e0c775a8293e4603c4 | 3,629,974 |
def load_dataset(datapath):
"""
Load dataset at given datapath. Datapath is expected to be a list of
directories to follow.
"""
inFN = abspath(join(dirname(__file__), datapath))
return rs.read_mtz(inFN) | 02ab263a13b9118d3943031e5165c943cc0c529f | 3,629,975 |
def displace_vertices(vertices, directions, length=1., mask=True):
"""
Displaces vertices by given length along directions where mask is True
Parameters
----------
vertices: (n, d) float
Mesh vertices
directions: (n, d) float
Directions of displacement (e.g. the mesh normals... | a3481b8ac7366279207dee36b0ce7723276aec56 | 3,629,976 |
def point_in_poly(x,y,poly):
"""" Ray Casting Method:
Drawing a line from the point in question and stop drawing it when the line
leaves the polygon bounding box. Along the way you count the number of times
you crossed the polygon's boundary. If the count is an odd number the point
must be inside. ... | a13be4c712a4705829780dbfc847467d45897552 | 3,629,977 |
def can_comment(request, entry):
"""Check if current user is allowed to comment on that entry."""
return entry.allow_comments and \
(entry.allow_anonymous_comments or
request.user.is_authenticated()) | 04bcd019af083cff0367e236e720f4f7b00f7a65 | 3,629,978 |
def tianqin_psd(f, L=np.sqrt(3) * 1e5 * u.km, t_obs=None, approximate_R=None, confusion_noise=None):
"""Calculates the effective TianQin power spectral density sensitivity curve
Using Eq. 13 from Huang+20, calculate the effective TianQin PSD for the sensitivity curve
Note that this function includes an ex... | ac211b96aff1d1bf2eeb8685944274820217d295 | 3,629,979 |
def __get_request_body(file: BytesIO, file_path: str, repo_url: str) -> dict[str, str]:
"""Creates request body for GitHub API.
Parameters:
file_path: path where file is to be uploaded (e.g. /folder1/folder2/file.html)
file: File-like object
repo_url: url of SuttaCentral editions repo
... | 270ddaccde3f78c25849eccf3b5060d558f17d59 | 3,629,980 |
from typing import Union
import struct
def _write_header(buf: Union[memoryview, bytearray],
dtype: np.dtype,
shape: tuple):
"""
Write the header data into the shared memory
:param buf: Shared memory buffer
:type buf: bytes
:param dtype: Data format
:type dt... | 4719f145e8e189d1c2b285b3ec33bfa5b4a8865f | 3,629,981 |
def _padright(width, s):
"""Flush left.
>>> _padright(6, u'\u044f\u0439\u0446\u0430') == u'\u044f\u0439\u0446\u0430 '
True
"""
fmt = u"{0:<%ds}" % width
return fmt.format(s) | d9333650a76fb8861f576f5e5f17c1929392c210 | 3,629,982 |
def single(mjd, hist=[], **kwargs):
"""cadence requirements for single-epoch
Request: single epoch
mjd: float or int should be ok
hist: list, list of previous MJDs
"""
# return len(hist) == 0
sn = kwargs.get("sn", 0)
return sn <= 1600 | 8734916221f0976d73386ac662f6551c25accfc3 | 3,629,983 |
def accuracies(diffs, FN, FP, TN, TP):
"""INPUT:
- np.array (diffs), label - fault probability
- int (FN, FP, TN, TP) foor keeping track of false positives, false negatives, true positives and true negatives"""
for value in diffs:
if value < 0:
if value < -0.5:
FP+=1
... | 001cebd169589f9f1494d9833c1fc49d8ba9964b | 3,629,984 |
from typing import Optional
import torch
from typing import Tuple
def group_te_ti_b_values(
parameters: np.ndarray, data: Optional[torch.Tensor] = None
) -> Tuple[np.ndarray, Optional[np.ndarray]]:
"""Group DWI gradient direction by b-values and TI and TE parameters if applicable.
This function is necessa... | e393085659667d2e916ca31d62811823a5bbba9f | 3,629,985 |
def compress(s):
"""param s: string to compress
count the runs in s switching
from counting runs of zeros to counting runs of ones
return compressed string"""
#the largest number of bits the compress algorithm can use
#to encode a 64-bit string or image is 320 bits
#I tested the penguin and ... | 7a937503d27a240b1cc867b72e6db458e7626355 | 3,629,986 |
def data_scaling(Y):
"""Scaling of the data to have pourcent of baseline change columnwise
Parameters
----------
Y: array of shape(n_time_points, n_voxels)
the input data
Returns
-------
Y: array of shape(n_time_points, n_voxels),
the data after mean-scaling, de-meaning a... | 94b550386b8411a96b9ccd3f5e93098560c327e1 | 3,629,987 |
def _process_normalizations(model_dict, dimensions, labels):
"""Process the normalizations of intercepts and factor loadings.
Args:
model_dict (dict): The model specification. See: :ref:`model_specs`
dimensions (dict): Dimensional information like n_states, n_periods, n_controls,
n_... | 852eec42ec9813bf642cafa89fc2460c1af1a010 | 3,629,988 |
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
return versioned_static_func(path) | 5eace52819755f01300a90007a0853766c57e1b1 | 3,629,989 |
def calculate_estimated_energy_consumption(motor_torques, motor_velocities,
sim_time_step, num_action_repeat):
"""Calculates energy consumption based on the args listed.
Args:
motor_torques: Torques of all the motors
motor_velocities: Velocities of all the motors.... | 00fbfd10e21de3fd7ce4b66dd369228951f77f62 | 3,629,990 |
def affine_to_shift(affine_matrix, volshape, shift_center=True, indexing='ij'):
"""
transform an affine matrix to a dense location shift tensor in tensorflow
Algorithm:
- get grid and shift grid to be centered at the center of the image (optionally)
- apply affine matrix to each index.
... | 3851647c791ab6b663a34b32bf2faa60e595c527 | 3,629,991 |
import json
def get_item_details(args, doc=None, for_validate=False, overwrite_warehouse=True):
"""
args = {
"item_code": "",
"warehouse": None,
"customer": "",
"conversion_rate": 1.0,
"selling_price_list": None,
"price_list_currency": None,
"plc_conversion_rate": 1.0,
"doctype": "",
"na... | d8f70e3d978a19af0739d7b0b03d0a845eb670c7 | 3,629,992 |
from typing import Type
def _get_store(cls: Type[BaseStore]) -> BaseStore:
"""Get store object from cls
:param cls: store class
:return: store object
"""
if jinad_args.no_store:
return cls()
else:
try:
return cls.load()
except Exception:
return... | d223a1354c67eb9e6603b07e890258600bd24412 | 3,629,993 |
async def connections_send_message(request: web.BaseRequest):
"""
Request handler for sending a basic message to a connection.
Args:
request: aiohttp request object
"""
context = request.app["request_context"]
connection_id = request.match_info["conn_id"]
outbound_handler = request... | 4e5e7d736ee93e1c6817a003c4c9412fd6603781 | 3,629,994 |
import json
def load_json(path: str):
"""Load json file from given path and return data"""
with open(path) as f:
data = json.load(f)
return data | d165d087c78a0ba88d318a6dbe8b2ac8f9a8c4b5 | 3,629,995 |
def process():
"""
The main function which responds to the html form submission.
The Flask server has it under the /process address.
"""
# 1. Obtain inputs from the webpage
code = request.form.get('Python_Code', '', type=str)
graph = request.form.get('Figure_Parameters', '', type=str)
... | 51f30dc54d7a507a68523859b4bfdbbc6934fc36 | 3,629,996 |
import functools
def check_admin_access(func):
"""Wrap a handler with admin checking.
This decorator must be below post(..) and get(..) when used.
"""
@functools.wraps(func)
def wrapper(self):
"""Wrapper."""
if not auth.is_current_user_admin():
raise helpers.AccessDeniedException('Admin acce... | e4f96f5f82d9d8fefcfff56ba28f317ec73e9272 | 3,629,997 |
def genericSearch(problem, fringe, heuristic=None):
"""
A generic search algorithm to solve the Pacman Search
:param problem: The problem
:param fringe: The fringe, either of type:
- Stash, for DFS. A Last-In-First-Out type of stash.
- Queue, for BFS. A First-In-First-Out type of stash.
... | 1628cfbbb6d39e0aebf01dc738ee49afdf2e79ae | 3,629,998 |
def post_processing(
predicted: xr.Dataset,
) -> xr.DataArray:
"""
filter prediction results with post processing filters.
:param predicted: The prediction results
"""
dc = Datacube(app='whatever')
#grab predictions and proba for post process filtering
predict=predicted.Predicti... | db57d3ab72984ecf497809df39c3032db57710c4 | 3,629,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.