content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def op_elem_vec_names(vecs, elem_op_labels, op_label_abbrevs):
""" TODO: docstring """
if op_label_abbrevs is None: op_label_abbrevs = {}
return [op_elem_vec_name(vecs[:, j], elem_op_labels, op_label_abbrevs) for j in range(vecs.shape[1])] | 7621f05b0ec544e4f1dff5e1c1e245da672598a5 | 48,900 |
def pdist(x, y, z, index, dmax=8.0):
"""
Pairwise distance computation for points in cartesian space.
Does return distance vectors.
"""
dmax2 = dmax**2
m = len(x)
n = m*(m - 1)//2
dx = np.empty((n, ), dtype=np.float64)
dy = dx.copy()
dz = dx.copy()
dr = dx.copy()
atom0 =... | fcb12aea28e980783270a2eb69698b1bbb68c94d | 48,901 |
def ss(inlist):
"""
Squares each value in the passed list, adds up these squares and
returns the result.
Usage: lss(inlist)
"""
ss = 0
for item in inlist:
ss = ss + item * item
return ss | 3760d84641178d836d2b62a5377dfa09e2861e40 | 48,902 |
def make_pre_build_hook(extra_compiler_config_params):
"""Return a pre-build hook function for C++ builders.
When called, during graph build, it computes and stores the compiler-config
object on the target, as well as adding it to the internal_dict prop for
hashing purposes.
"""
def pre_build_... | 2f45d1702c073a29451fed6efc6a266fe264a41d | 48,903 |
def melfrequencies_mel_filterbank(
num_bands, freq_min, freq_max, num_fft_bands
):
"""Returns centerfrequencies and band edges for a mel filter bank
Parameters
----------
num_bands : int
Number of mel bands.
freq_min : scalar
Minimum frequency for the first band.
freq_max : s... | 84b6583dfbe80dc258ee6d7d532ff9d6362640ca | 48,904 |
def get_commit_link(repo_name: str, commit_sha: str) -> str:
"""
Build a commit URL for manual browser access using full repository name and commit SHA1
:param repo_name: full repository name (i.e. `{username}/{repoanme}`)
:param commit_sha: 40 byte SHA1 for a commit
:return: A commit URL
"""
... | a1cf8d30f3e5c5ce3c5fefc719cca7c1c4d92331 | 48,905 |
import string
import random
def create_short_link(db: Session, link: schemas.ShortLink):
"""Create and add a new short link
"""
chars = string.ascii_letters + string.digits
random_string = ''.join(random.choice(chars) for i in range(8))
new_short_link = models.ShortLink(
short_link_path =... | 476e160cddcb5553ee045b2204c36d624b1f1fc5 | 48,906 |
import os
def find_local_raw_5minute_file(station_id=None, month_unix_sec=None,
top_directory_name=None,
raise_error_if_missing=True):
"""Finds raw 5-minute file on local machine.
This file should contain 5-minute METARs for one station-month.
... | 054f87e50064816b216957366b359e7a83d713bd | 48,907 |
def username(user_id):
"""
Find the user name associated to a user ID.
"""
return UserIndex.instance().username(user_id) | 085c56ddd9cf3ffe44d51c7a2576d02617ab948d | 48,908 |
def get_sqr_levels():
"""Get the sawtooth levels and take out the even harmonics to get square levels."""
saw_levels = get_saw_levels()
levels = []
for i in range(len(saw_levels)):
n = i + 1
level = saw_levels[n] if n % 2 != 0 else 0
levels.append(level)
return levels | cc57c8c66440550bea525920dd85fab520ea1550 | 48,909 |
def load_temporal_statistics(keys):
"""Load statistical features of the lifted data, computed over the
temporal domain at each spatial point.
Parameters
----------
keys : list(str)
Which data set(s) to load. Options:
* {var}_min : minimum of variable var
* {var}_max : maximu... | 8dd61e54352607f0fd80bf0a4d7f18360caa562f | 48,910 |
import re
def parse_gpu_info_lines(gpu_lines):
"""Parses the gpu info from 2 lines cut out from the nvidia-smi result.
Args:
gpu_lines (list of strings): Two nvidi-smi lines representing current gpu info.
Returns:
Tuple: Gpu id ('gpuX') and a dict with gpu info.
"""
gpu_id = 'gp... | 689eae75e2000f6ee0189cd3fdac16d1bd7149a4 | 48,911 |
import os
def get_file_list(csv_dir, entity):
"""Get list of CSV files for a given entity"""
csv_file_list = os.listdir(csv_dir)
file_list = []
for file in csv_file_list:
if entity in file:
file_list.append(file)
return file_list | 98528b02e58c8d3eb9afddd27b3cd883a7453d72 | 48,912 |
from typing import Iterable
from typing import Dict
from typing import List
import pprint
import json
def submit_batch_detection_api(images_to_detect: Iterable[str],
task_lists_dir: str,
detector_version: str,
account: str,
... | 97960a093960127917436c8e66a2afa3129a17e1 | 48,913 |
def fill_between_angle(arr, s, e, center=None, is_radian=True):
"""Fill Between ``s`` and ``e``.
Args:
arr (np.ndarray) : Input array.
s (Number) : Start angle of fill.
e (Number) : End angle of fill.
center (tuple) : Center coor... | 61f2d234d071c0b29e14f87d42046db5307d8dcb | 48,914 |
import requests
def export(request, project_id):
"""get the status of train job sent to custom vision
@FIXME (Hugh): change the naming of this endpoint
@FIXME (Hugh): refactor how we store Train.performance
"""
project_obj = Project.objects.get(pk=project_id)
train_obj = Train.objects.g... | d76a012106cb9438c1f10a1376c8c0476abe864b | 48,915 |
def convert(data, in_format, out_format):
"""Call TogoWS for file format conversion.
Arguments:
- data - string or handle containing input record(s)
- in_format - string describing the input file format (e.g. "genbank")
- out_format - string describing the requested output format (e.g. "fasta")
... | 3048e603bce3991d512502c49dd4dc953ee548a3 | 48,916 |
from dexbot.strategies.external_feeds.price_feed import PriceFeed
def test_get_external_market_center_price(monkeypatch, ro_worker):
""" Simply test if get_external_market_center_price does correct proxying to PriceFeed class
"""
def mocked_cp(*args):
return 1
monkeypatch.setattr(PriceFeed,... | 84cbb0fed8187e9f070643b981e3f6c71430f7fd | 48,917 |
import tqdm
def sort_by_labels(github_repo, pr_nums):
"""Sorts PR into groups based on labels.
This implementation sorts based on importance into a singular group. If a
PR uses multiple labels, it is sorted under one label.
The importance order (for the end-user):
- breaking changes
- highli... | 8e3293d18ed7b1e38d7b56eb0479d203a7f8ec35 | 48,918 |
def _get_submodel(model, name):
""" Return the first occurence of a sub-model. Search is performed by
model name.
"""
if not isinstance(model, CompoundModel):
return model if model.name == name else None
for m in model.traverse_postorder():
if m.name == name:
return ... | e2c72ad0cac949ed89b04e448ca20f4445ea190d | 48,919 |
from dateutil import tz
import os
import shutil
def run(bam_file, data, out_dir):
""" Run SignatureGenerator to create normalize vcf that later will be input of qsignature_summary
:param bam_file: (str) path of the bam_file
:param data: (list) list containing the all the dictionary
f... | 1a5380ab50b2b9917c4d24152ec5680ef51b3f79 | 48,920 |
def to_ascii(x):
""" Converts a 0-indexed integer to the corresponding Excel-style column name """
x += 1
result = []
while x:
x, rem = divmod(x-1, 26)
result[:0] = ascii_uppercase[rem]
return ''.join(result) | 16c44817b60034fb0600fcb55ef583412f05c6ba | 48,921 |
def step(stripped, pos, prev):
"""
Move along the path one or two steps (if ducking under), at location pos, and previous given.
Return new location, plus the number of steps (1 or 2) that was taken.
"""
(x, y) = pos
tile = stripped[pos]
dx, dy, steps = direction(pos, prev)
if tile == "... | 26f38e9010d1189aa3b8a9c25c5e1337b665f5f8 | 48,922 |
import os
def read_data(absfile: str) -> pd.DataFrame:
"""
Read Raw Data.
"""
assert os.path.exists(absfile)
return pd.read_excel(absfile,
names=[
'Time', 'Temp', 'pH', 'DO', 'Elecon', 'Turbidity', 'CODMn', 'NH3N', 'TP', 'TN'
]) | 846f8ca61027e18789164f59ad78d3fe12f0fc63 | 48,923 |
def validate_actions(data):
"""
Validate an Action configuration dictionary, as imported from actions.yml,
for example.
The method returns a validated and sanitized configuration dictionary.
:arg data: The configuration dictionary
:rtype: dict
"""
# data is the ENTIRE schema...
cle... | 327c90b0a02efb5148f5486a2a07eb962070cf5c | 48,924 |
def load_model_from_tarball_stream(
tarball_stream, gpg_home_dir=None, run_model_validation=True
) -> SerializableModel:
"""Load a model from a tarball stream
Args:
tarball_stream: a readable stream
gpg_home_dir: home directory for gpg to verify signed model (e.g. path/to/.gnupg)
... | 68fff3882029e05a24a516d84e14a2b8d5d3820e | 48,925 |
def TChA_LoadTxt(*args):
"""
TChA_LoadTxt(PSIn const & SIn, TChA ChA)
Parameters:
SIn: PSIn const &
ChA: TChA &
"""
return _snap.TChA_LoadTxt(*args) | de1e91f11ae4ce4206cb0ac3e09fb9b98e370ede | 48,926 |
from pathlib import Path
def init_default_parser() -> ArgumentParser:
"""Creates the default argument parser.
:returns: an ArgumentParser with the default options.
"""
version = "1.1.0"
parser = ArgumentParser()
parser.add_argument(
"target_path",
help="path to the xml fi... | e62fd60e5a735c1ce98f58dceff976b18b8d271d | 48,927 |
def msi_file_finder(pth):
"""
Return True if pth represents a msi file file.
"""
return bool(pth.fname.endswith('.msi.txt')) | 35c0d0dac72d44cbdd6f87b280a70917d264db0c | 48,928 |
from typing import List
from typing import Dict
def get_flat_tree(dependencies: List, package_map: Dict[str, str]) -> Dict:
"""Parse yarn list json dependencies and add them locked version
Example:
{
"package@1.2.3": {
"name": "package",
"version": "1.2.3",
dependencies: {
... | 7d95c7f8c2c2648df7348b70c3c6c5edb620fbed | 48,929 |
def windows_start(args, version):
"""
:type args: WindowsIntegrationConfig
:type version: str
:rtype: AnsibleCoreCI
"""
core_ci = AnsibleCoreCI(args, 'windows', version, stage=args.remote_stage, provider=args.remote_provider)
core_ci.start()
return core_ci.save() | e5774933e6a72407e2201c287a02ac49b2b90d6b | 48,930 |
from typing import Any
import logging
def load_spacy_model(model_name: str = CONFIG["spacy_model"]) -> Any:
"""
Loading Spacy model for name entity recognition.
Pre-trained models should be downloaded in advance by `python -m spacy download <model_name>`
"""
logging.info("Loading pre-trained model... | 08888c6dfbb0ba7e22216ac313c07bafdbd08019 | 48,931 |
def create_message(account, subject, body, to_recipients):
"""
Consolida os elementos mais básicos para a criação de
um objeto de mensagem a ser gerenciado externamente
pelo usuário ou por demais funções neste módulo.
Em linhas gerais, o código neste bloco instancia a
classe Message() da biblio... | f691ec6b5cc130a0610f78374a559c156857dafe | 48,932 |
def client_from_parameters(
base_url: str,
password: str,
team_name: str,
username: str,
verify_ssl: bool = True,
concourse_api_version=None,
):
"""
returns a concourse-client w/ the credentials valid for the current execution environment.
The returned client is authorised to perform... | 957737da5daa3d6ae192bee01971eaa5de6bccd8 | 48,933 |
def get_k2_epic_catalog():
"""
Parameters
----------
Returns
-------
"""
global k2_epic_table
if k2_epic_table is None:
catalogs = Vizier.get_catalogs(huber2016)
k2_epic_table = catalogs[0] # This is the table with the data
k2_epic_table.add_index('EPIC')
r... | a678e94442936f4246dbf51a1350d14b4bea1d46 | 48,934 |
import warnings
def bandpass_unit_conversion(
freqs, weights=None, output_unit=None, input_unit=u.uK_RJ, cut=1e-10
):
"""Unit conversion from input to output unit given a bandpass
The bandpass is always assumed in power units (Jy/sr)
Gain weights below cut are removed.
Parameters
----------
... | 1ee62b4a2fdc7f535939c754e9f9e1e9a364ebcc | 48,935 |
import http
import os
import json
def get_bearer_token():
"""
Creates the bearer key in order to perform requests from the Green Invoice API.
Since a new key has to be generated at least every 30 mim, this function will be used many times.
:return: request's bearer login token.
"""
conn = htt... | 892d0fd398db773dd742cd5a889ab69313bed31e | 48,936 |
def CheckIssueClosed(issue_id):
"""Checks if a given issue is closed. Returns False when in doubt."""
try:
return GetIssueState(issue_id) == 'closed'
except IssueTrackerQueryException:
# When we can't be sure we return false
return False | 230aabd098c8ae782c6584e467c7eadeac2137d9 | 48,937 |
import itertools
def get_accuracy_and_plot_confusion(y_correct, y_pred, classes, plot=True, title='Confusion matrix'):
"""Return the accuracy of the prediction and plot the corresponding confusion matrix if desired"""
if plot:
cm = confusion_matrix(y_correct, y_pred)
plt.imshow(cm, interpolati... | 199f7c9e8cdd2c0c28f41856f4e00aa4ca4381f4 | 48,938 |
import os
def fetch_spm_auditory(data_dir=None, data_name='spm_auditory',
subject_id='sub001', verbose=1):
"""Function to fetch SPM auditory single-subject data.
Parameters
----------
data_dir: string
Path of the data directory. Used to force data storage in a specified... | 345557349918c4584c2a9d53e7a75e495256ef7e | 48,939 |
def random_stochastic_function(x, delta):
"""
Creates a random stochastic function that adds a value between
[-delta, delta]
Parameters
============
x: the input value.
delta: defines the range
"""
return (np.random.random_sample() * 2 * delta) - delta | 601253016610e44dbff3a1a31c46c103f1fcd9d2 | 48,940 |
def _converter(val):
""" """
lval = val.lower()
if lval in ENABLE_STRINGS:
return True
if lval in DISABLE_STRINGS:
return False
return val | f76b415e8a29aea539a5681c8aae1b652c680eb1 | 48,941 |
def cagr(qf_series: QFSeries, frequency=None):
"""
Returns the Compound Annual Growth Rate (CAGR) calculated for the given series.
Parameters
----------
qf_series: QFSeries
series of returns of an asset
frequency: Frequency
Frequency of the timeseries of returns;
if it i... | bbe931a516805ec3b6e2f868e5cec96c6b205a07 | 48,942 |
from typing import Callable
from typing import Optional
import io
import struct
def decrypt_sun_message(sdm_meta_read_key: bytes,
sdm_file_read_key: Callable[[bytes], bytes],
picc_enc_data: bytes,
sdmmac: bytes,
enc_file_d... | aaee4cdb8e1ea39909df541be4a44befede2efcc | 48,943 |
def head_pos(raw, param_compute_amplitudes_t_step_min,
param_compute_amplitudes_t_window,
param_compute_amplitudes_ext_order,
param_compute_amplitudes_tmin,
param_compute_amplitudes_tmax, param_compute_locs_t_step_max,
param_compute_locs_too_close, ... | 37fb24e2fb1fd2032c0f5e04f1b4c63ebeecc447 | 48,944 |
def line_intersect(line_a, line_b) -> bool:
"""
Check if two line segments intersect
@param line_a A tuple (Vector2, Vector2) representing both end points
of line segment
@param line_b Same as `line_a`
"""
# line_a and line_b have the same end point
if (line_a[0] == line_b[0] or
... | a88ded2ee993d113c0b2c77e62403d6375250c06 | 48,945 |
def parseNum(num):
"""0x is hex, 0b is binary, 0 is octal. Otherwise assume decimal."""
num = str(num).strip()
base = 10
if (num[0] == '0') & (len(num) > 1):
if num[1] == 'x':
base = 16
elif num[1] == 'b':
base = 2
else:
base = 8
return int(num, base) | fc49b0a536a64ddf58e9ea5a36759e03f17de0a5 | 48,946 |
def compute_with_trace(*args):
"""Do Dask compute(), but with added Eliot tracing.
Dask is a graph of tasks, but Eliot logs trees. So we need to emulate a
graph using a tree. We do this by making Eliot action for each task, but
having it list the tasks it depends on.
We use the following algorit... | 19d241457055241dc8d6c34042fd4e4e3fe3db32 | 48,947 |
def read_mem(addr, size):
"""Read a chunk of memory."""
buf = create_string_buffer(size)
memmove(buf, addr, size)
return buf.raw | 5274b4e2a844e0daef63fe5c203529268dff73bf | 48,948 |
def get_ranges(headervalue, content_length):
"""Return a list of (start, stop) indices from a Range header, or None.
Each (start, stop) tuple will be composed of two ints, which are suitable
for use in a slicing operation. That is, the header "Range: bytes=3-6",
if applied against a Python string, ... | 042cc2147e9d63da6133e9d6212a8c572a9ffe9b | 48,949 |
def families_dipoles():
"""."""
return ['B'] | cca7010c86e56ef39c84cd82c960d6c2238f65ec | 48,950 |
from typing import Optional
from typing import List
from typing import Tuple
import httpx
async def get_currencies_rates( # noqa: WPS234
api_key: Optional[str],
base_currency: str = BASE_CURRENCY,
) -> List[Tuple[str, float]]:
"""Get currencies rates from remote server.
Args:
api_key: servic... | 04b29a9aaa0304c55fb822600a422edc71aa00e1 | 48,951 |
def mon_vm_sync(task_id, sender, vm_uuid=None, log=LOG, **kwargs):
"""
Create or synchronize zabbix host according to VM.
"""
assert vm_uuid
vm = log.obj = Vm.objects.select_related('dc', 'slavevm').get(uuid=vm_uuid)
log.dc_id = vm.dc.id
if vm.is_slave_vm():
logger.info('Ignoring VM... | 84eceb2163337cccb5d49bb0888885ca1669d919 | 48,952 |
import pkg_resources
import re
from datetime import datetime
def get_emissions(infile, outfile=None, fuelin=None, emisin=None):
"""Get emissions estimates with FINN
Args:
infile (str) - path to input file
outfile (str) - optional path to output file. If None, then this is
construc... | e252e5947f30d979f1ced3938ef70ebae7d5e1c9 | 48,953 |
def pad_subword_sequence(subword_seq, max_seq_length):
""" The subword sequence (graphemic / phonetic) can be of variable length. In order to store
this data in a numpy array, one pads and masks the subword dimension to the max sequence
length.
subword_seq: numpy array with dimensions (grap... | cb84a10b20cf30bcfb58d0250e7aeb20dc405e98 | 48,954 |
def program_to_instrument_name(program_number):
"""Converts a MIDI program number to the corresponding General MIDI
instrument name.
Parameters
----------
program_number : int
MIDI program number, between 0 and 127.
Returns
-------
instrument_name : str
Name of the inst... | 03065bb232183a190286974556552abc065c17fe | 48,955 |
import sqlite3
def recordcomfort():
"""Record comfort-score today"""
# User reached route via GET (as by clicking a link or via redirect)
if not request.method == "POST":
pass
# User reached route via POST (as by submitting a form via POST)
else:
pass
# DB connection and cursor... | fc89c86121b71fd023affaa329d65b8e194082cb | 48,956 |
def GetLatestAFDOFile(cpv, arch, buildroot, gs_context):
"""Try to find the latest suitable AFDO profile file.
Try to find the latest AFDO profile generated for current release
and architecture. If there is none, check the previous release (mostly
in case we have just branched).
Args:
cpv: cpv object fo... | 472309dc9754f0f21f6bedbd189dad35bab4beda | 48,957 |
def HadamardTest(P: QuantumCircuit, U: QuantumCircuit, U_active_qubits: list, shots: int = 10000):
"""
:param shots: the number of measurement
:param U: Testing state generation circuit
:param U_active_qubits:
:param P: Pauli matrix
:return: Re(<x|P|x>)
"""
p_size = len(P.qubits)
u_s... | 4c429c028499f4d3ec32fb6eacb8def54d65c422 | 48,958 |
def get_entry_points(config):
"""Process the [entry_points] section of setup.cfg.
Processes setup.cfg to handle setuptools entry points. This is, of course,
not a standard feature of distutils2/packaging, but as there is not
currently a standard alternative in packaging, we provide support for them.
... | 17287ec89f33bede790266e37ef456aadfcbc765 | 48,959 |
from typing import List
def __define_matriz(tamanho: int) -> List[List]:
"""
Metodo de definicao da matriz.
:return: Matriz em forma de lista
"""
_matriz = __cria_matriz_quadrada(tamanho)
return _matriz | 9f200fedfe44e5fe46686c452a84c301b88dde0f | 48,960 |
def logout():
"""User logout route."""
do_logout()
return redirect(url_for('auth.index')) | 834488be7a2b5c2a4a49e2250c1b653b2a73b9b7 | 48,961 |
def _maybe_expand_labels(labels, predictions):
"""If necessary, expand `labels` along last dimension to match `predictions`.
Args:
labels: `Tensor` or `SparseTensor` with shape
[D1, ... DN, num_labels] or [D1, ... DN]. The latter implies
num_labels=1, in which case the result is an expanded `labels... | 596895c71ef3709c3f811a93f69006cd99358b3d | 48,962 |
import torch
def quat_loss_geodesic(q1, q2):
"""
Geodesic rotation loss.
Args:
q1: N X 4
q2: N X 4
Returns:
loss : N x 1
"""
q1 = torch.unsqueeze(q1, 1)
q2 = torch.unsqueeze(q2, 1)
q2_conj = torch.cat([ q2[:, :, [0]] , -1*q2[:, :, 1:4] ], dim=-1)
q_rel ... | d1e327901853e9806707411fe6b80f9e88a18881 | 48,963 |
def _expectation(p, mean1, none1, mean2, none2, nghp=None):
"""
Compute the expectation:
expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n)
- m1(.), m2(.) :: Constant mean functions
:return: NxQ1xQ2
"""
return mean1(p.mu)[:, :, None] * mean2(p.mu)[:, None, :] | 4f177a1a850ae5d4ac7d3de96cdf5374ab9f09ba | 48,964 |
def get_accuracy(y_true, y_predicted):
"""Compute the accuracy for given predicted class labels.
Parameters
----------
y_true: numpy array
The true class labels of shape=(number_points,).
y_predicted: numpy array
The predicted class labels of shape=(number_points,).
Returns
... | c88a6b51021c9e01133852fa84c6f434043391a5 | 48,965 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
with Configurator(settings=settings) as config:
config.include("pyramid_chameleon")
config.include(".routes")
init_database()
config.scan()
return config.make_wsgi_app() | fbdbb1f859dcf8a77bb9a1050582e3fe3b7501bc | 48,966 |
def make_motif(desc, full_name, rep_list, seq_left, seq_right, rep_type, chromosome, start, end, unmapped, mapq,
min_flank, min_flank_complex, min_rep):
"""
Make motif for config file.
:param desc: str - motif description
:param full_name: str - motif full name
:param rep_list: list(R... | 143fef642ca31109dc97f09734cc231dc591f466 | 48,967 |
def get_connections(network):
"""
Function creates a dictionary with agent id's as a key and adjacent nodes as a value.
:param network: object of graph
:type network: networkx.classes.graph.Graph
"""
return {agent_id: list(adj_agents.keys()) for (agent_id, adj_agents) in network.adjacency()} | fa614b599c577de5c2554818366159e918c1335b | 48,968 |
def run_length_encode(mask):
"""
Descripition: Convert mask image into run-length enconde.
Args
-----
mask: A simple of gray image. The simple consists of digital signals(1 and 0).
Returns
--------
rle: A list of positions which encoded by run-length.
"""
signals = np.... | 601f6a0291e3207e063369a83c2224d714be607b | 48,969 |
def cube_attack(f, X, y, eps, n_trials, p=0.5, deltas_init=None, independent_delta=False, min_val=0.0, max_val=1.0):
""" A simple, but efficient black-box attack that just adds random steps of values in {-2eps, 0, 2eps}
(i.e., the considered points are always corners). The random change is added if the loss dec... | 4a847e423fc0005299c98abb19151b1a4c54ae97 | 48,970 |
def svn_utf_initialize(*args):
"""svn_utf_initialize(apr_pool_t pool)"""
return _core.svn_utf_initialize(*args) | 3eba24046428ca05463051c316eea63031e38006 | 48,971 |
def update_profile(request):
"""Update a user's profile view."""
profile = request.user.profile
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES)
if form.is_valid():
data = form.cleaned_data
profile.website = data['website']
profile.phone_number = data['phone_number']
pro... | 837515216c090c4b00d25251a771a79c44bdc1b2 | 48,972 |
def compute(data, ncols, alg, compress=False, n_power_iter=0):
"""
Compute separable NMF of the input matrix.
:param data: Input matrix
:type data: numpy.ndarray
:param ncols: Number of columns to select
:type ncols: int
:param alg: Choice of algorithm for computing the columns.
One of... | 4f8ebae39d8210bf434e50d6c5499e14f48e3535 | 48,973 |
def prox_owl(v, w):
"""Proximal operator of the OWL norm dot(w, reversed(sort(v)))
Follows description and notation from:
X. Zeng, M. Figueiredo,
The ordered weighted L1 norm: Atomic formulation, dual norm,
and projections.
eprint http://arxiv.org/abs/1409.4271
"""
# wlog operate on ab... | f00864f647c2c716197adad5edf3ed7255a52233 | 48,974 |
def get_repo(path="."):
"""
Returns a git repo from the specified path
:param path: is the optional path to the git repo
:return: git.Repo representing the input path
"""
return git.Repo(path) | 0d8ca9b7a7f62fc63969410b3826c0874c2cea3e | 48,975 |
from mapc2p import mapc2p
import numpy as np
from clawpack.visclaw import colormaps
def setplot(plotdata):
"""
Plot solution using VisClaw.
"""
plotdata.clearfigures() # clear any old figures,axes,items data
plotdata.mapc2p = mapc2p
# Figure for contour plot
plotfigure = plotdata.n... | ba7c20401297af0125b8bcdc1fe71019c2a516ca | 48,976 |
def disclaimers():
"""Sign-in disclaimer."""
return render_template("disclaimers.html", routes_to=url_for(request.args["routes_to"])) | c2c01f0b7b971417cc9871d82de10109715a03aa | 48,977 |
def meta_name(file_name):
"""Generate the name of the meta file"""
return "{}.json".format(file_name) | fc168d19c145c4f93fb8d92e3c0daa109aad31b6 | 48,978 |
def has_down(pdgid):
"""Does this particle contain a down quark?"""
return _has_quark_q(pdgid, 1) | 6d7bb949491b1a6da0d56c486bb6b17d5ecf2d92 | 48,979 |
import json
import pkgutil
def _JMS_to_Flavio_VII(C, parameters):
"""From JMS to flavio basis for class VII, i.e. flavour blind operators."""
d = {}
dtrans = json.loads(pkgutil.get_data('wilson', 'data/flavio_jms_vii.json').decode('utf8'))
for cj, cf in dtrans.items():
d[cf] = C.get(cj, 0)
... | 24bad69a4c194aa26f93f361622b55b6b673d8cc | 48,980 |
import os
def static_file(path):
"""
apps/static下静态文件获取(本视图函数只针对apps/static下的图片),apps/static下其他可以直接哟你flask默认的
注意:图片获取路由(apps/static下)
参数w,h可指定图片大小
:param path:原图片路径
:param w:获取的宽
:param h:获取的高
:return:w和h都大于0则返回相应尺寸图片; w和h都等于0则返回原图; 其中一个值大于0则返回以这个值为基础等比缩放图片
"""
w = str_to_num(... | b277004aeafefdab207fa851f94151ac8a7b7d77 | 48,981 |
def _get_land_fraction(cube, fx_variables):
"""Extract land fraction as :mod:`dask.array`."""
land_fraction = None
errors = []
if not fx_variables:
errors.append("No fx files given.")
return (land_fraction, errors)
for (fx_var, fx_path) in fx_variables.items():
if not fx_path... | 23378e363d1cdf64523dd460bb6e0943a58d1e31 | 48,982 |
def datasets_startswith(names):
"""
Return a list of strings with dataset names that begin with the given
names.
:param names:
String or tuple of strings.
:return:
List of strings.
"""
# Load dict with info about all the datasets.
info_datasets = load_info_datasets()
... | 6fa239d4515efb50b4f91d7f80d1d13eeec95c7d | 48,983 |
def get_pid_uid_sequences(infile, max_len=5000):
"""
Fetch a hierarchical dictionary with keys [pid][uid] and values which are sequences of actions
:param infile:
:param max_len: maximum length of sequence to store
:return: hierarchical dictionary with keys [pid][uid] and values which are np.ndarray... | 79dc6598137422dabe01375af09dc4dbbf5b6f3c | 48,984 |
import os
def load_darshan_header():
"""
Returns a CFFI compatible header for darshan-utlil as a string.
:return: String with a CFFI compatible header for darshan-util.
"""
curdir, curfile = os.path.split(__file__)
filepath = os.path.join(curdir, 'data', 'darshan-api.h')
# filepath = os.... | c136debfd59bea3925bf63bd1a1221d6316bb093 | 48,985 |
def randomDatabaseName() -> str:
"""
Generate a unique string for use as a database name.
"""
return f"d{uuid4().hex}" | 79ff0dc75c7e6aa3c849253a0d847f3cb2afefce | 48,986 |
def concat_body_paragraphs(body_candidates):
"""
Concatenate paragraphs constituting the question body.
:param body_candidates:
:return:
"""
return ' '.join(' '.join(body_candidates).split()) | a0faaa0ae0be0cda007c2af1f6e47f3b745862b3 | 48,987 |
def home(request):
"""docstring for home"""
return render(request,"home.html",{}) | 437c43886f4c52e62b7a07f5f35878591ca4bfd1 | 48,988 |
def AlbersUsaProjection():
"""
Create function to project coordinates using an Albers USA projection.
"""
# Based on D3's AlbersUSA projection
# https://github.com/mbostock/d3/blob/master/src/geo/albers-usa.js
# http://spatialreference.org/ref/esri/usa-contiguous-albers-equal-area-conic/
lo... | a473bffa8dd64badf10dd179a2a04dc42d9247c8 | 48,989 |
from keras.preprocessing.sequence import pad_sequences
def _build_generator(X_list, y_list, batch_size, timesteps, input_size, shuffle, positive_weight):
"""
Build looping generator of training batches. Will return the generator and the number of batches in each epoch.
In each epoch, all samples are rando... | ef9edc0d43faeaae12ed45bb54ab1e5d278d6ad4 | 48,990 |
import os
import json
def read_annotation_file(annotation_file_path):
"""
Read all the annotation information from annotated json file
:param annotation_file_path: dir which contains all annotated json file
:return: final_annotation: a dictionary contains all information
"""
final_annotation_d... | 201082f107291289d4e2133534b67cf8b08cab34 | 48,991 |
def merge_tables(version=''):
"""
given hdf5s, pivot and merge them at the same time
"""
df_merged = merge_duplicates_and_pivot(df=None, version=version)
# Fluid balance OUT == hourly urine
df_merged['vm32'] = df_merged['vm24']
output_path = mimic_paths.merged_dir + version + '/reduced/merge... | ec6328709d645a27b94519d3cbf4d2af0ebe8558 | 48,992 |
import tempfile
import json
def get_fuzzer_stats(stats_filestore_path):
"""Reads, validates and returns the stats in |stats_filestore_path|."""
with tempfile.NamedTemporaryFile() as temp_file:
result = filestore_utils.cp(stats_filestore_path,
temp_file.name,
... | 03f934069b987c782910cf8164fcb184ac1685b2 | 48,993 |
import os
import re
def check_package_files(ports):
"""Check port package.sh file for required properties.
Args:
ports (list): List of all ports to check
Returns:
bool: no errors encountered
"""
all_good = True
for port in ports:
package_file = f"{port}/package.sh"
... | cbac6b16fd26b103cd1435861d75e6624545131d | 48,994 |
import array
def imu(draw,
header=header(),
orientation=quaternion(),
orientation_covariance=array(elements=float64(), min_size=9, max_size=9),
angular_velocity=vector3(),
angular_velocity_covariance=array(elements=float64(), min_size=9, max_size=9),
linear_acceleration... | 9e7c240e9d2690891c8915e835457a9fc9af1c36 | 48,995 |
def combine_sample_standard_deviation(As, n = None, u = None, v = None):
"""Computes the combined sample standard deviation of a group of
`measured_value`s.
Let:
* `g = len(As)`.
* `u_i = As[i].quantity`.
* `s_i = As[i].uncertainty`.
* `n_i = As[i].samples`.
* `n` denote the combined sample ... | f3ddb6006c62fdc93b29444049a19d51725f9f72 | 48,996 |
def hash_password(pwd):
"""
https://passlib.readthedocs.io/en/stable/index.html
:param pwd:
:return:
"""
return _pwd_context.hash(pwd) | b17bec236389fd45762822e482d63766734b6c9a | 48,997 |
import re
def matchNumbersOnly(value):
"""Match strings with numbers and '.' only."""
if re.match('^[0-9.]+$', value):
return True
return False | 04d782431b79e78f93269c662c747d1f7348c9ec | 48,998 |
import re
import mimetypes
import os
import requests
def upload_attachment(page_id, file, comment):
"""
Upload an attachment
:param page_id: confluence page id
:param file: attachment file
:param comment: attachment comment
:return: boolean
"""
if re.search('http.*', file):
re... | 7bb5eef7fd0031a93f89b259c035b5a6c5ac0ff3 | 48,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.