content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def common_lens(cube_list):
"""
Give the common lenses of a list of pySNIFS cubes
@param cube_list: input list of datacubes
@return: inters: list of the lenses common to all the cubes of the list
"""
inters = cube_list[0].no
for i in xrange(1,len(cube_list)):
inters = filter(lambda x... | 5,296,700 |
def save_connections():
"""save servers to list"""
ManageConnectionsDialog(0).exec_() | 5,296,701 |
def protected(Authorize: AuthJWT = Depends()):
"""
We do not need to make any changes to our protected endpoints. They
will all still function the exact same as they do when sending the
JWT in via a headers instead of a cookies
"""
Authorize.jwt_required()
current_user = Authorize.get_jwt_s... | 5,296,702 |
def sin(x: DNDarray, out: Optional[DNDarray] = None) -> DNDarray:
"""
Compute the trigonometric sine, element-wise.
Result is a ``DNDarray`` of the same shape as ``x``.
Negative input elements are returned as ``NaN``. If ``out`` was provided, ``sin`` is a reference to it.
Parameters
----------
... | 5,296,703 |
def list(lst: 'Optional[List_[PythonValue]]' = None) -> PythonValue:
"""Returns a List wrapped into a PythonValue"""
return PythonValue(List(lst=lst)) | 5,296,704 |
def set_user_settings(name: str, value: object) -> None:
"""Set current user's settings parameter of specified name to provided value."""
UsersRepository.set_user_settings(get_current_user(), name, value) | 5,296,705 |
async def set_consumer_to_infernal_job(engine, job_id, consumer_ip):
"""
Update the infernal_job table to register the consumer who will run the job
:param engine: params to connect to the db
:param job_id: id of the job
:param consumer_ip: ip address of the consumer
:return: id or none
"""
... | 5,296,706 |
def get_recursively(search_dict: dict, field: str) -> list:
"""Take a dict with nested lists and dicts,
and searche all dicts for a key of the field
provided.
https://stackoverflow.com/a/20254842
Args:
search_dict (dict): Dictionary to search
field (str): Field to search for
R... | 5,296,707 |
def askDestination():
"""
prompts user for backup directory and sets it to destination
:returns: new destination
"""
location = filedialog.askdirectory()
# validation
p = Path(location)
if not p.exists() or not p.is_dir() or location == '':
return bm.destination
bm.set_dest... | 5,296,708 |
def get_hostip(req=None, log=None):
"""Look up the IP address for a given requested interface name.
If interface is not given, do some magic."""
global _hostip # pylint: disable=W0603
if _hostip:
return _hostip
AF_INET = netifaces.AF_INET
# We cre... | 5,296,709 |
def test_devices(api, utils):
"""This is a BGPv4 demo test script with router ranges"""
config = api.config()
tx, rx = config.ports.port(
name="tx", location=utils.settings.ports[0]
).port(name="rx", location=utils.settings.ports[1])
config.options.port_options.location_preemption = True
... | 5,296,710 |
def time_series_sum_of_reoccurring_values(x):
"""
Returns the sum of all values, that are present in the time series
more than once.
:param x: the time series to calculate the feature of
:type x: pandas.Series
:return: the value of this feature
:return type: float
"""
retu... | 5,296,711 |
def promote_numeric_to_real(stage: ImportStage, value: ir.Value) -> ir.Value:
"""Promotes the value to RealType."""
return d.PromoteNumericOp(d.RealType.get(), value).result | 5,296,712 |
def main():
"""
usage: BEP032Viewer.py [-h] [-S] [-Se] [-Su] [-Ss] pathToDir
positional arguments:
pathToDir Path to the folder to show
optional arguments:
-h, --help show this help message and exit
-S, --show show dir structure
-Se, --show_experiments... | 5,296,713 |
async def make_photo():
"""Photo from web camera.
"""
loop = asyncio.get_running_loop()
img, _ = await loop.run_in_executor(app.ps_executor, get_png_photo)
if img:
result = StreamingResponse(
png_img_to_buffer(img), media_type="image/png"
)
else:
result = HTTP... | 5,296,714 |
def test_id_not_found_get(flask_client):
"""Tests GET with an ID not found"""
response = flask_client.get(f"/msg-scheduler?id=-10")
assert response.status_code == 404 | 5,296,715 |
def get_adj_matr(graph):
"""
Function to create an adjacency matrix representation of a graph.
arg:
graph - (dict) of 'nodes' : [], 'edges' : []
returns:
pd.DataFrame with entry i,j representing an edge from node i to node j
"""
n = len(graph['nodes'])
adj_matr = pd.DataFrame... | 5,296,716 |
def _test_sqlite3_db(db_path):
"""Very basic test for validity of database."""
# Check for file existance and if it's a sqlite3 db
if isfile(db_path):
try:
conn = sqlite3.connect(db_path)
# TODO: If we really care, do a more thorough check
# If it has the homesn... | 5,296,717 |
def get_resourcesize(path):
"""指定されたリソースの標準サイズを返す。"""
dpath = os.path.basename(os.path.dirname(path))
fpath = os.path.splitext(os.path.basename(path))[0]
key = "%s/%s" % (dpath, fpath)
if key in SIZE_RESOURCES:
return SIZE_RESOURCES[key]
else:
return None | 5,296,718 |
def all_files_from(dir, ext=''):
"""Quick function to get all files from directory and all subdirectories
"""
files = []
for root, dirnames, filenames in os.walk(dir):
for filename in filenames:
if filename.endswith(ext) and not filename.startswith('.'):
files.append(... | 5,296,719 |
def get_title(url: str):
""" Get the Title of the web page and generates markdown formated link"""
html_source = requests.get(url).text
title = re.findall('<title>(.*?)</title>', html_source)[0].strip()
return f"[{title}]({url})" | 5,296,720 |
def pow_4_of(number):
"""
fourth power of number
helper function from lalsimulation/src/LALSimIMRPhenomD_internals.h
"""
pow2 = pow_2_of(number)
return pow2 * pow2 | 5,296,721 |
def item_cost_entry() -> float:
"""Return the sum of all user entries."""
print('\nENTER ITEMS (ENTER 0 TO END)')
subtotal: float = 0.0
while True:
cost: float = float(input('Cost of item: '))
if cost == 0:
break
else:
subtotal += cost
return... | 5,296,722 |
def set_token(token):
"""
Set the token for the Nexus environment.
:param token: The token is a string given by Nexus or a connected service.
"""
storage.set("token", token) | 5,296,723 |
def mark_duplicates(job, config, name, input_bam):
"""Run Picard MarkDuplicates
:param config: The configuration dictionary.
:type config: dict.
:param sample: sample name.
:type sample: str.
:param input_bam: The input_bam file name to process.
:type input_bam: str.
:returns: str -- Th... | 5,296,724 |
def test_cancel_compatibility_completed_plan(app):
"""
well I don't know if it's an appropriate case. it's probably not
"""
app.authorization = ("Basic", ("broker", "broker"))
test_data = deepcopy(test_plan_data)
response = app.post_json("/plans", {"data": test_data})
assert response.status ... | 5,296,725 |
def prometheus_cleanup_worker(pid):
"""Aggregate dead worker's metrics into a single archive file."""
from prometheus_client import multiprocess
multiprocess.mark_process_dead(pid) # this takes care of gauges
prom_dir = os.environ['prometheus_multiproc_dir']
worker_files = [
'histogram_{}.d... | 5,296,726 |
def normalize_tokens(tokens):
"""
The OP-1 gets confused with multiple line segments in one command.
This fixes that by splitting multiple segments into separate commands.
Convert from e.g.:
["l", "20", "20", "20", "-20", "10", "10"]
To:
["l", "20", "20", "l", "20", "-20", "l", "10", "10"]
... | 5,296,727 |
def agentcli():
"""
Execute agent related actions
"""
pass | 5,296,728 |
def full_train_and_test(filename):
"""
Uses the entire dataset for both training and testing.
Returns the testing accuracy.
"""
table, cumulative, dataset, index_to_name = train(filename)
preds, targets = test(table, cumulative, dataset, index_to_name)
n_correct, n_total = accuracy(preds, t... | 5,296,729 |
def _read_attachment(fp, has_arg=False, debug=False):
""" Reads an ATTACHMENT block.
"""
target, arg, header, data = _read_block(fp, has_arg=False, debug=debug)
d = dict(header=header,
data=data,
threshold=0.0)
lr = [s.strip() for s in RE_ARROW.split(target)]
if len(... | 5,296,730 |
def mmd2_rbf(X, t, p, sig=0.1):
"""
Computes the l2-RBF maximum mean discrepancy (MMD) for X given t.
http://www.jmlr.org/papers/volume13/gretton12a/gretton12a.pdf -- Eq3
"""
it = np.where(t==1)[0]
ic = np.where(t==0)[0]
Xc = X[ic]
Xt = X[it]
if list(Xc.shape)[0] == 0.0 or list(Xt.... | 5,296,731 |
def render(gs: game.VisibleGameState, actions: List[game.Action] = None) -> str:
"""
Pretty fuckin hacky...
"""
screen = [[" "] * WIDTH for _ in range(HEIGHT)]
# Talon:
talon_height_offset = 0
for i, card in enumerate(reversed(game.bitmask_to_cards(gs.talon))):
left_offset = WIDTH -... | 5,296,732 |
def togglePyConsole(self, item, user_ns):
"""
toggles a toplevel window with an ipython console inside.
self is an object we can stick the pythonWindow attribute on
item is a checkedmenuitem
user_ns is a dict you want to appear as locals in the console
"""
if item.get_active():
if... | 5,296,733 |
def train_model(model, images, angles, batch_size, learning_rate=1e-4):
"""
Train the model using Adam optimizer and generator
"""
# Split training and validation
X_train, X_test, y_train, y_test = train_test_split(images, angles, test_size=0.1)
# Generator
train_generator = data_generator(... | 5,296,734 |
def evaluate_srnpdj(gt, pred, K=25):
"""
Parameters:
gt: np.array([N, ...])
ground truth array of binary labels (integers)
pred: np.array([, ...])
same shape as ground truth
Returns:
srnpdj_N6: np.array(shape=[N, 6])
for each paired item in (gt, pr... | 5,296,735 |
def ajax_delete():
"""
客户删除
:return:
"""
ajax_success_msg = AJAX_SUCCESS_MSG.copy()
ajax_failure_msg = AJAX_FAILURE_MSG.copy()
# 检查删除权限
if not permission_customer_section_del.can():
ext_msg = _('Permission Denied')
ajax_failure_msg['msg'] = _('Del Failure, %(ext_msg)s', ... | 5,296,736 |
def limiteQtdTurmasPorAlunoFormEtapa2(modelo, y):
""" Alunos de formulario sao matriculados em no maximo uma turma. """
for k in y:
turmas = []
for t in y[k]:
turmas.append(y[k][t])
modelo.solver.Add(sum(turmas) <= 1) | 5,296,737 |
def cleanup(number_of_days, path):
"""
Removes files from the passed in path that are older than or equal
to the number_of_days
"""
time_in_secs = time.time() - (number_of_days * 24 * 60 * 60)
for root, dirs, files in os.walk(path, topdown=False):
for file_ in files:
full_pa... | 5,296,738 |
def check_maximum_clients(onion_service_dir, start=False):
"""Gets the current number of clients (.auth files in the given Tor Onion Service directory)
and checks if this number is below the maximum clients allowed.
An official maximum number for clients per Onion Service from Tor wasn't found. Manual
t... | 5,296,739 |
def compute_clustering_metrics(y_true: List, y_pred: List) -> List[float]:
"""
Computes ARI, NMI, goldInstance, sysInstance, goldClusterNum
and sysClusterNum between predicted and gold labels
Args:
y_true: Iterable, ground truth labels
y_pred: Iterable, labels from your clusterizer
... | 5,296,740 |
def plot_wind_capacity_factors(wind_bubble='YPS'):
"""Plotting wind capacity factors for a given wind bubble"""
# Class containing model data
data = ModelData()
df = pd.read_hdf(os.path.join(os.path.dirname(__file__), os.path.pardir, '2_input_traces', 'output', 'dataset.h5'))
df_d = df.lo... | 5,296,741 |
def _open_url(url: str):
"""Opens url, creates BeutifulSoup object and waits.
:param url: url to get
:type url: str
:return: BeautifulSoup object
"""
opener = build_opener()
opener.addheaders = [
('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firef... | 5,296,742 |
def test_combining_digmontage_forbiden_behaviors():
"""Test combining different DigMontage objects with repeated names."""
rng = np.random.RandomState(0)
fiducials = dict(zip(('nasion', 'lpa', 'rpa'), rng.rand(3, 3)))
dig1 = make_dig_montage(
**fiducials,
ch_pos=dict(zip(list('abc'), rng... | 5,296,743 |
def steps_pow_frac(
n,
x=1,
k=1,
m=9,
d=4,
a=-4,
b=5,
c=1):
"""
Generate steps for `step_sort()` (Shell sort).
These are of the form: x(k) = (m ** (k + 1) // d ** k + a) // b + c
with some initial value.
With `x=1, k=1, m=9, d=4, a=-4... | 5,296,744 |
def square(vx=1.0, vy=0, wz=0.8, t=16):
"""
Generate square trajectory, starting and ending at origin.
"""
time_points = range(t)
speed_points = (
# Get set
(0, 0, 0, 0),
# Walk forward and then turn left
(vx, 0, 0, 0),
(vx, 0, 0, 0),
(0, 0, 0, wz),
... | 5,296,745 |
def crypto_adapter(adapter):
"""Modify an adapter to disable non-crypto symbols.
``crypto_adapter(adapter)(name, active, section)`` is like
``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
"""
def continuation(name, active, section):
if not include_in_crypto(name):
... | 5,296,746 |
def get_ann_dir(
encoder_type: Encoder.Types,
code_lang: str,
query_langs: Optional[List[str]]=None,
run_id : Optional[str]=None
) -> Path:
"""
Returns the path to the .ann index files for a specific type
of model under the configured root checkpoint directory
"""
... | 5,296,747 |
def test():
"""Test function"""
x = ask()
print(x)
print(x ^ [False]) | 5,296,748 |
def coerce(expr: Node, target_type: Type, source_type: Type, context: TypeInfo,
is_wrapper_class: bool = False, is_java: bool = False) -> Node:
"""Build an expression that coerces expr from source_type to target_type.
Return bare expr if the coercion is trivial (always a no-op).
"""
if is_tr... | 5,296,749 |
def check_surrounded(string):
""" Check if the string as a whole is surrounded by brackets
:param string: The string to check.
:return: True if it is surrounded.
"""
length = len(string)
if length <= 1:
return False
counter = 0
for idx in range(length):
char = string[id... | 5,296,750 |
def test_edit_invalid_path_arg(main, nocolorcapsys):
"""Test that the usage information is displayed when a file that
does not exist is entered and not the following when running with an
the editor positional argument:
- ``config``
- ``include``
- ``exclude``
- ``styles``
:param main: ... | 5,296,751 |
def make_message(name):
"""Constructs a welcoming message. Input: string, Output:string."""
message = "Good morning, %s! Nice to see you."%name
return message | 5,296,752 |
def format_time(sec: float) -> str:
"""Return formatted time in seconds."""
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
return "%d h %d m %d s" % (h, m, s) | 5,296,753 |
def file_path_pair(config, section):
"""Return input and output file paths for a config section."""
input_obj = config[section]['input']
if isinstance(input_obj, str):
input_path = get_file_path(config, input_obj)
else:
input_path = []
for path in input_obj:
input_pat... | 5,296,754 |
def CheckForBadCharacters(filename, lines, error):
"""Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that... | 5,296,755 |
def get_name_candidates_from_email(parsed_text):
"""
Gets possible combination of names from the email address
:param parsed_text: (unicode string) parsed text from the resume.
:return: a list of possible combination of names.
"""
banned = ['the', 'and']
string_list = []
list_name_data =... | 5,296,756 |
def spot_price_difference():
"""返回 DOT 火币,币安,okex,抹茶,uniswap,heco交易所现货价格的最大价差
@@@
### description
> finished
### args
None
### return
status code: **200**
```json
[
{
"dex": "huobi",
"price": 100,
... | 5,296,757 |
def view_eco(key):
"""View existing eco."""
eco = ECO.get_by_key(key)
users = User.query.all()
projects = Project.query.all()
variables = {
'eco': eco,
'users': users,
'projects': projects
}
return render_template('eco/view_eco.html', **variables) | 5,296,758 |
def require_minimum_pandas_version():
""" Raise an ImportError if Pandas version is < 0.23.2
"""
minimum_pandas_version = (0, 23, 2)
# pandas is an optional dependency
# pylint: disable=import-outside-toplevel
try:
import pandas
have_pandas = True
except ImportError:
... | 5,296,759 |
def fetch_accounts(clientCard):
"""
Function to return the accounts owned by the account holder that is linked to the bank card they
used to login into the website, and associated information.
Args:
clientCard (int): Bank card used for login
Returns:
accounts_modified (list): List w... | 5,296,760 |
def get_classifier_training_job_from_model(classifier_training_job_model):
"""Gets a classifier training job domain object from a classifier
training job model.
Args:
classifier_training_job_model: ClassifierTrainingJobModel. Classifier
training job instance in datastore.
Returns:
... | 5,296,761 |
def Three_D(masked_image, centers, plot):
"""
3D plot function
Parameters
----------
masked_image : np.array - image array
centers : np.array - centers of a cluster
plot : bool - to plot?
"""
# define number of points to visualize
poi... | 5,296,762 |
def makeModel(filenum=FILENUM):
"""
:param str file_num:
:return libsbml.Model:
"""
url = makeURL(filenum)
response = requests.get(url).content
document = tesbml.readSBMLFromString(response.decode("utf-8"))
return document.getModel() | 5,296,763 |
def random_sequences(num_seqs, average_length):
"""
@arg num_seqs: The number of sequences to return.
@arg average_length: The expected length of each sequence. (the lengths are actually distributed according to a Poisson distribution).
@return: A list of random sequences.
"""
import numpy.rando... | 5,296,764 |
def tone3_to_tone(tone3):
"""将 :py:attr:`~pypinyin.Style.TONE3` 风格的拼音转换为
:py:attr:`~pypinyin.Style.TONE` 风格的拼音
:param tone3: :py:attr:`~pypinyin.Style.TONE3` 风格的拼音
:return: :py:attr:`~pypinyin.Style.TONE` 风格的拼音
Usage::
>>> from pypinyin.contrib.tone_convert import tone3_to_tone
>>> to... | 5,296,765 |
def part1(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int:
"""
Consider the validity of the nearby tickets you scanned. What is your
ticket scanning error rate?
"""
fields, tickets = parse(stdin)
groups = valid_groups(fields)
invalid_values = [
value
for ticket in ... | 5,296,766 |
def model_setup(path: Path | dict[str, T.Any], out_dir: Path, gemini_root: Path = None):
"""
top-level function to create a new simulation FROM A FILE config.nml
Parameters
----------
path: pathlib.Path
path (directory or full path) to config.nml
out_dir: pathlib.Path
directory... | 5,296,767 |
def image_update(client, image_id, values, purge_props=False):
"""
Set the given properties on an image and update it.
:raises NotFound if image does not exist.
"""
return client.image_update(values=values,
image_id=image_id,
purge_props... | 5,296,768 |
def get_new_map(trace):
"""
Returns the new MAP model from exoplanet after sampling the posterior.
Parameters
----------
trace : arviz.data.inference_data.InferenceData
Information on the trace of all fitted parameters used in the model sampling, including the posterior values, log_likeliho... | 5,296,769 |
def encodeMorse(sequence: str) -> str:
"""
Encodes the given string to Morse Code
Morse code is case-insensitive and traditonally Capital Letters are used
Lower cases are converted to Upper cases
Every Character code is seperated by a single space between them
A space in the se... | 5,296,770 |
def brightness(image):
"""Change brightness of image randomly (maximum 30%)"""
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
scale = 1.0 + np.random.uniform(-0.3, 0.3)
hsv[:,:,2] = hsv[:,:,2] * scale
return cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) | 5,296,771 |
def engine_switch_test(self,checkstatus=''):
""" Verifies the number of route engines present within the device.
If more than 1 is present attempts to connect to the back up route-engine to verify functionality
Test will fail if >1 RE present and backup RE is not reachable.
check_status=True causes th... | 5,296,772 |
def _parse_vertex_tuple(s):
"""Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k' ...)."""
vt = [0, 0, 0]
for i, c in enumerate(s.split('/')):
if c:
vt[i] = int(c)
return tuple(vt) | 5,296,773 |
def __create_clicks_for_statements(up_votes, statement_uid, users, is_up_vote):
"""
:param up_votes: Int
:param statement_uid: Statement.uid
:param users: {Users.nickname: User}
:return: [ClickedStatement]
:param is_up_vote: Boolean
"""
tmp_firstname = list(first_names)
new_clicks_f... | 5,296,774 |
def get_pct_on_clutter_map_rhi(filename, polarization):
"""
get_pct_on_clutter_map_rhi grabs and returns clutter map point percentage occurrences and clutter map
masks from daily HSRHI clutter maps (in either H or H and V polarizations).
Parameters
----------
filename: str
full path... | 5,296,775 |
def test_find_simple(fragment):
"""Ensure find() and find_one() return expected results."""
# Find, with a depth of 0 by default.
result = list(fragment.find(ast.Text))
assert result == [ast.Text('Hello Earth!')]
# Find, with unrestricted depth.
result = list(fragment.find(ast.Text, depth=-1))
... | 5,296,776 |
def tfidf_transform(tfidf_vectorizer, corpus_data, cuda0):
"""
Apply TFIDF transformation to test data.
Args:
vectorizer_train (object): trained tfidf vectorizer
newsgroups_test (ndarray): corpus of all documents from all categories in test set
Returns:
X_... | 5,296,777 |
def RunAllDir(dir_string, method, no_glob, param):
"""
Run 'method' on the pinballs in all directories which start with the string 'dir_string'.
Uses os.path.walk() to run the method on all pinballs in each directory (or directories).
@param dir_string string used to determine directories to process
... | 5,296,778 |
def or_(*args):
""" Trick operator precedence.
or_(foo < bar, bar < baz)
"""
value = DummyAttr()
for elem in args:
value |= elem
return value | 5,296,779 |
def plot_image(data=None, mode='imshow', backend='matplotlib', **kwargs):
""" Overall plotter function, converting kwarg-names to match chosen backend and redirecting
plotting task to one of the methods of backend-classes.
"""
if backend in ('matplotlib', 'plt'):
return MatplotlibPlotter.plot(da... | 5,296,780 |
def project_to_ids_UNSC(Tokenizer, data, max_seq_length=512):
"""
Function to map data to indices in the albert vocabulary, as well as
adding special bert tokens such as [CLS] and [SEP]
Args:
Tokenizer (bert.tokenization.albert_tokenization.FullTokenizer):
tokenizer class for bert token... | 5,296,781 |
def unite_stresses(dict_filenames, output_filename):
""" Unites some dictionaries into one.
1. dict_filenames - list of dictionary filenames, needed to unite.
2. output_filename - output dictionary filename
"""
united = lib.load_stresses_file(dict_filenames[0])
for fn in dict_filenames[q:]:
... | 5,296,782 |
def test_sku_listing(monkeypatch, actor_mocked, context_mocked):
"""Tests whether the rhsm library can obtain used SKUs correctly."""
context_mocked.add_mocked_command_call_with_stdout(CMD_RHSM_LIST_CONSUMED, 'SKU: 598339696910')
attached_skus = rhsm.get_attached_skus(context_mocked)
assert_fail_descr... | 5,296,783 |
def stop():
"""
Stop all the cluster running containers
"""
cli_stop() | 5,296,784 |
def download_pretrained_checkpoint(data_config: DatasetConfiguration, cache_folder: os.PathLike) -> str:
"""Utility function to download a pre-trained checkpoint from the original repository.
Parameters
----------
data_config : DatasetConfiguration
The configuration identifying the dataset for ... | 5,296,785 |
def voigtMath(x, alpha, gamma):
"""
Function to return the Voigt line shape centered at cent with Lorentzian
component HWHM gamma and Gaussian component HWHM alpha.
Creates a Voigt line profile using the scipy.special.wofz, which returns
the value of the Faddeeva function.
WARNING
scipy.sp... | 5,296,786 |
def get_installation_coordinates_google(dir_in, key_google, fn_out=None):
""" Gets installation coordinates using googlemaps api
:param dir_in: <string> path to directory with downlaoded installation data file
:param key_google: <string> google api key
:param fn_out: <string> name output file. If None, ... | 5,296,787 |
def diag_dump(
enode, list='', daemon='', level='', file='',
_shell='vtysh',
_shell_args={
'matches': None,
'newline': True,
'timeout': None,
'connection': None
}
):
"""
Display diagnostics dump that supports diag-dump.
This function runs the following vtysh ... | 5,296,788 |
def save_transformer_locally(model_name="bert-base-uncased", save_path=".", is_tf=False):
"""save
anyone you can find from here: https://huggingface.co/models
"""
# to use AutoModel, need to install pytorch: pip3 install torch torchvision or pip install torch torchvision
from transformers import Aut... | 5,296,789 |
def _merge_pcaps(exp_dir):
"""Merges all the pcaps in the experiment directory."""
pcaps = {}
for d, f in all_files(exp_dir, regex=r'.*\.pcap$'):
if d == exp_dir:
continue
if f not in pcaps:
pcaps[f] = []
pcaps[f].append(os.path.join(d, f))
procs = []
... | 5,296,790 |
def randomizeCarVelocities(nCars, vMax):
"""This function takes integers nCars, and vMax. It then returns an array
of of random integers from 0 to vMax. The array is of length nCars.
No integers in the returned array are the same."""
carVelocities = []
for i in range(nCars):
randomVelocity =... | 5,296,791 |
def get_absl_log_prefix(record):
"""Returns the absl log prefix for the log record.
Args:
record: logging.LogRecord, the record to get prefix for.
"""
created_tuple = time.localtime(record.created)
created_microsecond = int(record.created % 1.0 * 1e6)
critical_prefix = ''
level = record.levelno
if... | 5,296,792 |
def delete_zcs_container(session, zcs_container_id, return_type=None,
**kwargs):
"""
Deletes a Zadara Container Services (ZCS) container. The container must
first be stopped. This action is irreversible.
:type session: zadarapy.session.Session
:param session: A valid zada... | 5,296,793 |
def numStationsNotIgnored(observations):
""" Take a list of ObservedPoints and returns the number of stations that are actually to be used and
are not ignored in the solution.
Arguments:
observations: [list] A list of ObservedPoints objects.
Return:
[int] Number of stations that ... | 5,296,794 |
def _next_and_end(cls: "StateMirror") -> "StateMirror":
"""Add "Next" and "End" parameters to the class.
Also adds the "then()" and "end()" helper methods.
"""
def _validate_next(instance, attribute: attr.Attribute, value: Any):
if value is not None and instance.End is not None:
rai... | 5,296,795 |
def jf_mcma_lb(sample: np.ndarray, ref_size=None, c=None, delta=0.05, mode=None, mc_size=10000) -> float:
"""
A function calculates the lower bound using Monte-Carlo M_alpha method.
For more details, please check the paper:
"A New Confidence Interval for the Mean of a Bounded Random Variable"
... | 5,296,796 |
def define_template(title, page):
"""
Adds a template defined in the :param page:.
@see https://en.wikipedia.org/wiki/Help:Template#Noinclude.2C_includeonly.2C_and_onlyinclude
"""
global templates
global redirects
# title = normalizeTitle(title)
# check for redirects
m = re.match('... | 5,296,797 |
def before_start(sender, headers, **kwargs):
"""
Create a Task object before the task actually started,
set the task object status to be PENDING, with the signal
after_task_publish to indicate that the task has been
sent to the broker.
Note: we do not test the connection here, as this signal
... | 5,296,798 |
def test_paragraph_extra_43b():
"""
Test case extra 43b: Paragraph with code span with newline inside
"""
# Arrange
source_markdown = """a`code 
 span`a"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):a:]",
"[icode-span(1,2):code \a&\a&\a#xa; span:`::]",
... | 5,296,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.