content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def namespaceMotor(motor, namespace):
"""
Args:
motor:
namespace:
Returns:
"""
motor['name'] = namespaced(motor['name'], namespace)
motor['joint'] = namespaced(motor['joint'], namespace)
return motor | abd547308478205ddb5555a3c85953d1806fd72d | 3,595,566 |
def tsignals(trend, asbool=None, trend_reset=0, trade_offset=None, offset=None, **kwargs):
"""Indicator: Trend Signals"""
# Validate Arguments
trend = verify_series(trend)
asbool = bool(asbool) if isinstance(asbool, bool) else False
trend_reset = int(trend_reset) if trend_reset and isinstance(trend_... | 20eb97b4fa40ef9488d279d0204484a183be36c9 | 3,595,567 |
def _get_root_url(product_type, url_type='build'):
"""
Get root url
:param product_type: Type of product
:type product_type: String
:param url_type: Type of root dir (build|test)
:type url_type: String
:return: Root url
:rtype: String
"""
if product_type.startswith('public_')... | 13dfb743ae00975d0b1d7c08aa0ee3e4bc5d1501 | 3,595,568 |
import uuid
def is_uuid_like(val):
"""Return validation of a value as a UUID.
:param val: Value to verify
:type val: string
:returns: bool
"""
try:
return str(uuid.UUID(val)).replace('-', '') == _format_uuid_string(val)
except (TypeError, ValueError, AttributeError):
retur... | 01c8200d63e52ac197ba4a8d0f78721f7301f64d | 3,595,569 |
def _is_linear_eqn(eqn: jax.core.JaxprEqn, var_is_bound: VarIsBoundDict):
"""Identify if an eqn is a linear transformation of inputs that are bounds.
Args:
eqn: The equation to check.
var_is_bound: Dictionary indicating whether each variable represent a bound
or a Tensor.
Returns:
is_linear: bo... | fe10d7c2a3857cb064a597befd659799e67631b4 | 3,595,570 |
import struct
def fake_pyc_timestamp(buf):
"""
Reset the timestamp from a .pyc-file header to a fixed value.
This enables deterministic builds without having to set pyinstaller
source metadata (mtime) since that changes the pyc-file contents.
_buf_ must at least contain the full pyc-file header.... | 0b6bd2d37f8d25e48dc3d084b6642c33688a5533 | 3,595,571 |
def _get_greensf_group_name(hdffile):
"""
Return the name of the group containing the Green's function elements
:param hdffile: h5py.File of the greensf.hdf file
:returns: str of the group name containing the Green's Function elements
"""
if '/GreensFunctionElements' in hdffile:
return... | fa5a8c65cad63b3053d8b55af95c9c4547493793 | 3,595,572 |
import yaml
def from_yml(yml_string: str) -> dict:
"""Load the given YAML string into a dict
:param yml_string: YAML string to work on
:type yml_string: str
:return: dict representation of the given YAML string
:rtype: dict
"""
config: dict = yaml.safe_load(yml_string)
return config | 28868d568fa519e795df4a32ecae8608da6465d6 | 3,595,573 |
def Compute6(surface, volume, firstMoments, secondMoments, productMoments, multiple=False):
"""
Compute the VolumeMassProperties for a single Surface.
Args:
surface (Surface): Surface to measure.
volume (bool): True to calculate volume.
firstMoments (bool): True to calculate volume ... | 189c9f7ade1d51471d013b04254eb0d94b3005dd | 3,595,574 |
def get_olf(left_line):
"""parse out UNITS DIMENSIONS ELEMENT from input line"""
return [left_line << item for item in _OPTIONAL_LEFT_FIELDS] | 229f9211dc5dcec57c9278660d5ddade2881dcdc | 3,595,576 |
def send_to_custom_consumer(producer=None):
"""Send a custom message as per Scott's instructions."""
# For Celery the queue and routing key should match.
my_queue = Queue(name="text_queue", routing_key="text_queue")
message = {
"Body": {"Type": "environment", "Alias": "{{alias}}", "Properties":... | 33b6da4fd6bc6756c406fcb777587a1ab904e47b | 3,595,577 |
def get_non_refinement_pipeline(lagged):
""" Create 4-level pipeline without decompose operation """
node_lagged = PrimaryNode('lagged')
node_lagged.custom_params = {'window_size': lagged}
node_lasso = SecondaryNode('lasso', nodes_from=[node_lagged])
node_dtreg = SecondaryNode('dtreg', nodes_from=[... | db5129e152959b5fb11d14df77419e1f22b63018 | 3,595,578 |
import six
def marshal_load(fp, origin=None):
"""
Unserialize data serialized with :func:`marshal.dump`. This function
works across python versions. Marshalled code objects are returned as
instances of :class:`~pwnypack.bytecode.CodeObject`.
Arguments:
fp(file): A file or file-like object... | 86608f312e2d352198d32e21e89514bfae24cb46 | 3,595,580 |
def translate_exception(exc_info, initial_skip=0):
"""If passed an exc_info it will automatically rewrite the exceptions
all the way down to the correct line numbers and frames.
"""
tb = exc_info[2]
frames = []
# skip some internal frames if wanted
for x in range(initial_skip):
if t... | 61a2d927baad71eb27509896fb8d2f4ea124657f | 3,595,581 |
from typing import Union
from typing import List
def _write_aesurfs(model: Union[BDF, OP2Geom], name: str,
aesurfs_ids: List[int], ncards: int,
op2_file, op2_ascii, endian: bytes, nastran_format: str='nx') -> int:
"""
Word Name Type Description
1 ID I Identi... | 63f751cd0382e8f81d04a05ea7ab72fdf19794b9 | 3,595,582 |
import importlib
def is_rasa_x_installed():
"""Check if Rasa X is installed."""
# we could also do something like checking if `import rasax` works,
# the issue with that is that it actually does import the package and this
# takes some time that we don't want to spend when booting the CLI
return ... | 9438328b36ea15646fa311820f351c6e028738e8 | 3,595,583 |
def htmlentityreplace_errors(ex):
"""An encoding error handler.
This python codecs error handler replaces unencodable
characters with HTML entities, or, if no HTML entity exists for
the character, XML character references::
>>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace')
... | 7a82d29b17704515de617dda0b43aa0deaa92e18 | 3,595,584 |
def whole_mask2mask(whole_mask, bbox):
"""Convert an image-sized array of instance masks into a list.
Args:
whole_mask (array): array of shape (R, H, W)
bbox (array): Array of shape (R, 4)
Returns:
[(H_1, W_1), ..., (H_R, W_R)]
"""
if len(whole_mask) != len(bbox):
... | 397c57b1da61024128acdc1d6e8877cc0dd4f742 | 3,595,585 |
def hess(color, mag, binsize, **kw):
"""
Compute a hess diagram (surface-density CMD) on photometry data.
INPUT:
color
mag
binsize -- width of bins, in magnitudes
OPTIONAL INPUT:
cbin= -- set the centers of the color bins
mbin= -- set the centers of the magnitude b... | acb1c39a779644e84871250fdb05a88206a8a36e | 3,595,586 |
def compute_CCM(matrix, kernel="LZ"):
"""
Compute causal complexity estimates for all pairs of rows of input matrix
Estimates are derived as per 4 models: ETCP, ETCE, LZP and CCC
Parameters
----------
matrix : np.ndarray, 2d, uint32
MxN matrix, C(M,2) rowpairs, with each row of length ... | 21915d9ee34dce4e9f679ae48256d482a8efd78d | 3,595,587 |
def make_cgi_app():
"""
Generates the CGI application, with CGI we can't afford to serve static files with
werkzeug; that has to be done by the real server, eg. apache: see the cgi.htaccess
file in the site file (the one with settings.py).
"""
return application | 852922c25a81c01963d69dec1fd59f500ad0d720 | 3,595,589 |
def get_all_edits_of_user(request):
"""
Request for all edits of the user
:param request: current request of the server
:return: json-dict()
"""
ui_locales = get_language_from_cookie(request)
db_user = request.validated['user']
return user.get_textversions(db_user, ui_locales).get('edit... | 17e793e6746404190fe6b8fda868c7c15dc2d45e | 3,595,590 |
def get_objects_eligible_for_user(perm, user, exclude_existing=True):
"""Returns a list of eligible users that do not already have the
permission for `obj`.
"""
perm = utils.get_perm(perm)
model_class = perm.content_type.model_class()
if exclude_existing:
ct = ContentType.objects.get_fo... | bcf9e8a804070e847989aa51163f4ddbe8b57575 | 3,595,591 |
import string
import random
def generator(length):
"""Generate a random sequence of bytes
Args:
length (int): length
Returns:
bytes: random sequence of bytes
"""
letters = string.printable
return ''.join(random.choice(letters) for i in range(length)).encode() | e7a7f22ec3470e9bf45b0084fdc9da917c1f18fb | 3,595,593 |
import math
def latlng_index(lat, lng, mult=1 / 15):
"""Convert latitude and longitude to 'indexes'.
"""
# 'mult' = 1 / approx-bucket-size-in-deg
ilat = int(round((lat + 90.0) * mult))
mult = mult * math.cos(abs(lat) * math.pi / 180.0)
ilng = int(round((lng + 180.0) * mult))
return {'latI... | bd297216545dca725ec10c1a301251acd929fecf | 3,595,594 |
async def test_service_registration(aiohttp_server, config, db, loop):
"""Test the creation of a Service and the registration of its endpoint
"""
# Setup Kubernetes API mock server
routes = web.RouteTableDef()
# As part of the reconciliation loop started by ``controller.resource_received``,
# ... | a659f3f5c301fc72f4c2ff9cbef51301020022a1 | 3,595,598 |
import re
def marc21_to_copyright_date(self, key, value):
"""Get Copyright Date."""
copyright_dates = self.get('copyrightDate', [])
copyrights_date = utils.force_list(value.get('c'))
if copyrights_date:
copyright_per_code = {
'c': '©',
'p': '℗',
'©': '©',
... | 5db0fcc7f58f04257f55f388154f7cbe36f21ad9 | 3,595,599 |
from typing import List
from typing import Tuple
def prepare_image_choices(images: List[Image]) -> List[Tuple[str, Image]]:
"""
Returns image choices for the prompt.
:param list images: list of digitalocean.Image.Image instances
:return: list of 2-len tuples
"""
filtered_images = filter(lambda... | 53448ad0cf58feb9aa41e173d3dced8721b46ba5 | 3,595,600 |
import logging
def get_loglevel(loglevel):
""" Check valid log level supplied and return numeric log level """
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError("Invalid log level: %s" % loglevel)
return numeric_level | 017bc0be3e5feb890ccd7477bedb87d1077f1ef5 | 3,595,602 |
def get_past_month_detail_bill(request_session, start_date, end_date):
"""
Request detail bill of past month
:param request_session: Request session
:param start_date: The beginning date of bill
:param end_date: The last date of bill
:return:
status_key: str, The key of status code
... | 7586e8ca30f87ce0b1bc1c28212a9ea4043790e5 | 3,595,603 |
def parse(input):
"""Parse a TOML string or file."""
reader = Reader(input)
parser = Parser(reader)
return parser.runtime | 9711743d4bfa6cd1c6a13502eb8f8eb8635966bc | 3,595,604 |
def min(child):
"""
Returns min function of child. Not to be confused with :meth:`pybamm.minimum`, which
returns the smaller of two objects.
"""
return pybamm.simplify_if_constant(Function(np.min, child)) | e42ac9e9c6f9ce2f2b4d2aa68380dd636b691b31 | 3,595,605 |
def mean_relative_l2(prediction: np.ndarray, ground_truth: np.ndarray) -> float:
""" return the value of the error according to the mean relative L2 norm in the article"""
error_vector = prediction.reshape(ground_truth.shape) - ground_truth
total_displacement = npl.norm(ground_truth)
if -1e-5 < total_... | 88396812e213ed6d8b2c1c910f4df81b5c1abdf1 | 3,595,606 |
import tqdm
import time
def find_sources(sleep_time=1):
"""Scrapes the US Newspaper Listing websites to find URLs for local newspapers in
all 50 US states.
Parameters
----------
sleep_time : int
The amount of time to sleep in between states
Returns
-------
sources : list
... | b9a8d3a3d1607c8a0a34e9720869b60f0ba1f76a | 3,595,607 |
import tempfile
import shutil
def rm_local_tmp_dir(path):
"""Remove a local temp directory.
This is just a wrapper around shutil.rmtree(). Use it to indicate you are
certain that your executing code is operating on a local temp dir, not a
directory managed by the Django Storage API.
"""
path ... | eab3d254dec2e2892663db1cda1b5e6fd5b4b921 | 3,595,608 |
def get_cross_covariance(X, Y, Z, k):
"""
Code from: https://github.com/wittawatj/kernel-mod
Compute the covariance of the U-statistics for two MMDs
(Bounliphone, et al. 2016, ICLR)
Args:
X: numpy array of shape (nx, d), sample from the model 1
Y: numpy array of shape (ny, d), sample... | 1ab961ff6b3655c5b63fafedfeaa71aaf0a8c93c | 3,595,609 |
def default():
"""Default configuration for PPO."""
# General
algorithm = algorithms.PPO
num_agents = 30
eval_episodes = 30
use_gpu = False
# Environment
normalize_ranges = True
# Network
network = networks.feed_forward_gaussian
weight_summaries = dict(
all=r'.*', policy=r'.*/policy/.*', val... | 23a231463a0805ead03c2320dc3b78acd2cf3f3d | 3,595,610 |
import glob
def MNE_Read_EDF(path):
"""Read .edf exported from digitrack using MNE library.
Parameters
----------
path:str
directory of a folder containing the following files: sygnal.edf, unity_log.csv, digi_log.xml, digi_binary.1
This is usually the folder with the s... | 0ce494a8cdb98c5355570c507f3f6ec987976d8e | 3,595,611 |
def undo_stft_features_old(spectrogram, sample_rate=10000,
window_size=0.0512,
preemphasis_coeff=0.95, fft_size=512):
"""Undo the preprocessing operations
Inputs:
signal: 2D preprocessed spectrogram (np.ndarray)
sample_rate: sampling rate of signal (... | 5b3349870d9c824d9f5a72f5da395ae633c4fe56 | 3,595,612 |
def update_submit_handler(model_name, model_identifier,
model_identifier_int, title_field_name,
content, model, field_name,
is_autosave=False, image_orig=None):
"""Generic submit handler for the update functions."""
try:
if a... | 8ee35b3d8c099bf434a83ffa8e8bc63874e65cb9 | 3,595,613 |
def described_only_by_pk(model):
"""Helper function to determine if a model can be described uniquely by a
subset of it's fields apart from the primary key"""
return get_unique_fields(model) == ('pk',) | 45b8a5a9caf752f96d167d17ce39beb0cea8b327 | 3,595,614 |
from mspray.apps.main.utils import add_spray_data
def update_edited_records():
"""
Update edited records.
"""
count = 0
if FORM_ID:
data = fetch_form_data(FORM_ID, dataids_only=True, edited_only=True)
if not data:
return count
pks = [i["_id"] for i in data]
... | 710a718d91a48b4ad6221e297cee109820715f3e | 3,595,615 |
def split_by_p_tag(html):
"""
Return html splited by <p> tags
"""
soup = bs(html)
p_tags = []
for p_tag in soup.find_all(settings.CONTENT_MAIN_TAGS):
p_tags.append(unicode(p_tag))
return p_tags | 499dd8ba997f89be7a68f612a90bdb7e99c72309 | 3,595,616 |
def getConnectedVertices(dag, component):
"""
index -> OpenMaya.MFn.kMeshVertComponent
:param OpenMaya.MDagPath dag:
:param OpenMaya.MFn.kMeshVertComponent component:
:return: Initialized component(s), number of connected vertices
:rtype: tuple(OpenMaya.MFn.kMeshVertComponent, int)
"""
... | 29a71c8376a8477e1a77ae97b4d5b6f941e1a853 | 3,595,617 |
def find_d_max_diagonale(sequence_i, sequence_j, # pylint: disable=R0913
dist_func=entre_fenetres_audio, w_0=1, w_1=1, w_2=1):
"""
Trouver à partir de quelle distance de la diagonale
le résultat de la'algorithme dtw ne change pas
"""
valeur_distance = max(len(sequenc... | b3fde5b4540acaa96172c254c321b280a60d8145 | 3,595,618 |
def generate_discrete_swarm(
n_particles, dimensions, binary=False, init_pos=None
):
"""Generate a discrete swarm
Parameters
----------
n_particles : int
number of particles to be generated in the swarm.
dimensions: int
number of dimensions to be generated in the swarm.
bina... | 20ab5cc0d32d30d2778230fc442fffa83cc8b9eb | 3,595,619 |
import math
def re(R_est, R_gt):
"""Rotational Error.
:param R_est: 3x3 ndarray with the estimated rotation matrix.
:param R_gt: 3x3 ndarray with the ground-truth rotation matrix.
:return: The calculated error.
"""
assert (R_est.shape == R_gt.shape == (3, 3))
error_cos = float(0.5 * (np.trace(R_est.dot... | 6688d309ffe83b8831cd784b68c32e992eb55e6a | 3,595,620 |
from lal import MSUN_SI, C_SI
from .spins import component_spins
from .utils import magnitude_from_vector
from pesummary.utils.utils import iterator
import copy
def NRSur_fit(
mass_1, mass_2, a_1, a_2, tilt_1, tilt_2, phi_12, phi_jl, theta_jn, phi_ref,
f_low=20., f_ref=20., model=NRSUR_MODEL, fits=NRSUR_FITS,... | 041b0f680f269e312f54723aec7f0bf9b552a6f8 | 3,595,622 |
def instance_id():
"""Retrieve current Instance's ID."""
return utils('instance-id') | e9c7596404d2d8bf50cabfbb77d78defc7d82aae | 3,595,623 |
def plot_init():
"""
绘图初始化函数:
初始化绘图相关变量
Args:
Return:
cost_ploter -- 用于绘制cost曲线的变量
error_ploter -- 用于绘制error_rate曲线的变量
"""
# 绘制cost曲线所做的初始化设置
cost_ploter = Ploter(train_title_cost, test_title_cost)
# 绘制error_rate曲线所做的初始化设置
error_ploter = Ploter(train_title_er... | 25d54896f64ea135d7027c13d659570dbb5fb8bd | 3,595,624 |
async def create_git_bundle(platform, owner, repo, oid):
""" Create a git bundle via API """
data = {
'platform': platform,
'owner': owner,
'repo': repo
}
if oid:
data['oid'] = oid
res = await api_call('bundle', method='POST', data=data, compression_level=9)
re... | 198a87621d7d78b8c3d075a93be9739088037400 | 3,595,625 |
from typing import Callable
from typing import Any
def make_loss_fn(loss_type: str, active: bool) -> Callable[..., Any]:
"""Create active or passive loss function of given type."""
if active:
primary = lambda x: x.active
secondary = lambda x: x.passive
else:
primary = lambda x: x.passive
second... | dfa67e3a98d13d97336dc53a306dc53514ad34fb | 3,595,626 |
def entropy_map(model, normalize=True):
"""
Compute dictionary of positional entropies for
single-site frequencies in a CouplingsModel
Parameters
----------
model : CouplingsModel
Model for which entropy of sequence
alignment will be computed (based on
single-site freque... | 0e85f8a8d4eb75bae763b213541be16f55e90eef | 3,595,628 |
def checksum(steps_ahead: int, input_value: int) -> int:
"""Santa-checksum.
Sum the numbers which match values `steps_ahead` ahead in the list of input
digits.
raises:
ValueError: if input is negative.
"""
if input_value < 0:
raise ValueError("Can't checksum a negative value.")
... | e51f2e78af123e1425c4f3fb9dc8b9acc25dcca3 | 3,595,629 |
def lemmatizer(text):
"""Input: string of 1 or more words,
output: string of corresponding lemmas"""
lemmad = ''
wnl = WordNetLemmatizer()
lemma_list = [wnl.lemmatize(t) for t in word_tokenize(text)]
for lem in lemma_list:
lemmad = lemmad + lem + ' '
return lemmad | 3dd645e5a1383084f95b6b6309ce876d91fa343b | 3,595,630 |
def Kattis(problem):
"""
Returns a dictionary on the form {input: correct output} from Kattis.
"""
if problem == "hello":
return {"": "Hello World!\n"}
url = f"https://open.kattis.com/problems/{problem}/file/statement/samples.zip"
request = Request(url, headers={'User-Agent': 'Chrome Bro... | bf278cc7d20e2e3ef02bff118cf997f11b74c93b | 3,595,631 |
def _create_user(user_id, email):
"""Creates a new user. Returns the user_settings object."""
user_settings = get_user_settings(user_id, strict=False)
if user_settings is not None:
raise Exception('User %s already exists.' % user_id)
user_settings = UserSettings(user_id, email)
_save_user_s... | 5687a13bece0190880c65f417134ea6c423e8649 | 3,595,632 |
import random
def augment(imA, imB):
"""
Input day0 and day4 image of the same rat
An augmented version of both is returned
"""
#"3D" to 2D
imA = imA.reshape((256,256))
imB = imB.reshape((256,256))
# Define random deformation matrix
random_grid = np.random.rand(2, 3, 3)
... | 887b59510a7f3a3458d4a91542ae332d348c808b | 3,595,633 |
def partialEig(batch, S2, V, ratio = 1, solver = 'full', tol = None, max_iter = 'auto'):
"""
Fits a partial Eigendecomp after given old eigenvalues S2
and old eigenvector components V.
Note that V will be used as the number of old components,
so when calling truncated or randomized, will output a
specific number... | 67c6b40d5f8778a60d6b1a654edc1e462c682dee | 3,595,634 |
def mouse_y_to_tile(y):
"""Converts mouse y coordinates to board-space"""
return 4 * (y - top) / height | 518b9d1f5725873f248b4c4a4edb5ed845861f68 | 3,595,635 |
def uploading(coroutine):
"""Return a coroutine that takes arguments about uploading
cloudcast-related data, runs checks on them and makes a parameters
dictionary out of them. Then, it passes that dictionary to the
original coroutine, while awaiting it.
"""
@wraps(coroutine)
async def wrapp... | 0fd5155e3c856b56fd3dc055da1979d48c26244d | 3,595,636 |
from typing import OrderedDict
def obs_space_info(obs_space):
"""
Get dict-structured information about a gym.Space.
Returns:
A tuple (keys, shapes, dtypes):
keys: a list of dict keys.
shapes: a dict mapping keys to shapes.
dtypes: a dict mapping keys to dtypes.
"""
... | 27711cdba4fef46bd95b9b9240a5ca77700727b5 | 3,595,637 |
from typing import Union
import torch
from typing import Optional
def compute_hausdorff_distance(
seg_pred: Union[np.ndarray, torch.Tensor],
seg_gt: Union[np.ndarray, torch.Tensor],
label_idx: int,
distance_metric: str = "euclidean",
percentile: Optional[float] = None,
directed: bool = False,
... | d30f3781f7b58ff761c4bc263c09850f3c9fa2aa | 3,595,638 |
def initialize_mint(params: InitializeMintParams) -> TransactionInstruction:
"""Creates a transaction instruction to initialize a new mint newly.
This instruction requires no signers and MUST be included within the same Transaction as
the system program's `CreateInstruction` that creates the account being ... | 0a8842acca01bd48933a6551b5ed852595b660b9 | 3,595,639 |
def mocked_requests_get_404_text(*args, **kwargs):
"""Mock invalid response that returns non-json."""
json_response = "Not JSON"
return MockResponse(json_response, status.HTTP_404_NOT_FOUND) | 2c5c9e568c7abcc8707eb0d6f8610854b23f6e69 | 3,595,640 |
def count_marked_as_done(idx):
"""
:param idx:
:return:
"""
return idx | 1ffd0a3831ac80b2ba955bdb0b2f922b5375c84b | 3,595,641 |
def get_nan_audio():
"""
returns list of audio files to test in test_for_nan_values
"""
audio_files = [
"/mnt/disks/data_disk/home/dzubke/awni_speech/data/LibriSpeech/train-other-500/6689/64286/6689-64286-0001.wav",
"/mnt/disks/data_disk/home/dzubke/awni_speech/data/LibriSpeech/train-other-500/1... | 16ffd9457749044bf1f2d68069ec0e3d98116800 | 3,595,642 |
def mse(v: np.array, y: np.array) -> float:
"""
Calculates MSE of predicted values v against labels in y
:param v: m*1 vector
:param y: m*1 vector
:return: MSE of v
"""
return metrics.mean_squared_error(v, y) | 294086d61944cb7a81c00d90df0812c9419727ae | 3,595,643 |
def plot_grow2D_left(sim_array, final_size):
"""
This function will plot the sim_array into a matrix of size final_size. It will be plotted into the center of the rows, but the right column will be
on the right of the domain, so it's always growing on one side. It's basically the other-side alternate to the... | f11cf8669dc361eefed6036b58d9aa130141bbe8 | 3,595,645 |
def get_filter_params(request):
"""
Get the filter preferences provided by the user via the
HttpRequest and store them in the session.
@type request: HttpRequest
@param request: The HttpRequest provided by the client
@rtype: C{dict} of C{string} to C{string}
@return: A dictionary mapping qu... | 8a3d528da96d1f00ec55dac8f937ef52db84a529 | 3,595,646 |
def safe_column_name(name):
"""Generate SQL friendly column name"""
return '"{}"'.format(name).upper() | 495b54a94c4350a8f20df5a1416a5c8c10d7a559 | 3,595,647 |
def _setup_no_fallback(parser):
"""Add the option, --tox-pyenv-no-fallback.
If this option is set, do not allow fallback to tox's built-in
strategy for looking up python executables if the call to `pyenv which`
by this plugin fails. This will allow the error to raise instead
of falling back to tox'... | 3613ffee1ce6ccf1dffafcb33558b47d5e5e1d38 | 3,595,648 |
import re
def name_validalidation(name, context):
"""Function used to validate various names"""
if len(name.strip()) == 0 or not re.match("^[-a-zA-Z0-9_\\s]*$", name):
message = "Name shouldn't be empty. No special characters"
response = {
"message": message + " for " + context + "... | 56e759d40f1b6bb3a99437c1f976fbb9232ce6bf | 3,595,649 |
def particle_to_statearray(particles, size_of_system):
"""
Transforms the given state - represented as positions of all particles -
into an 1d state array
"""
array = np.zeros(size_of_system**2)
for p in particles:
array[p] = 1
return array | 049edaf1b3cbcf4c1fd3e463f795b7347ea0ef62 | 3,595,650 |
def word2vec():
"""Data service operation: execute a vector query on the specified word."""
query_word=preprocess(request.values.get('word'))
n_responses=int(request.values.get('n', '10'))
if query_word:
try:
a = model.wv.most_similar(positive=query_word, topn=5*n_responses)
... | 2bdbafa2620822245de17e012163410a81cf9d07 | 3,595,653 |
def column_name_list(columns):
"""
Gets a comma-separated list of column names.
:param columns: The list of columns.
:returns: A comma-separated list of column names.
"""
if not columns:
return ''
return ', '.join([column.name for column in columns]) | 7c40e420e55368454768d84229f959a11b5c00dd | 3,595,655 |
def make_0032():
"""World Server Addr Request(start)(s0031)"""
return "" | 17a166822b9d083c104c652abfc6a5c20cf1743c | 3,595,657 |
def adoption_fraction_i():
"""
Real Name: b'Adoption fraction i'
Original Eqn: b'0.2'
Units: b'Dmnl'
Limits: (None, None)
Type: constant
b''
"""
return 0.2 | af0707c7b3a3fae1636a18ba0c2931792142b273 | 3,595,659 |
def compress_size (size):
""" Compress binary array into integers comprising bits """
sim_t = np.bool8
sim_bits = 1
# Computes the best type to compress boolean data with `size`
for i in it.count():
nbytes = 1 << i
nbits = nbytes << 3
# If size cannot fit into bits
... | 262ec57da03e78e4182cfc48fd3e3d2c4f30727c | 3,595,660 |
def positiveaxis(axis, ndim):
"""Positive axis
Args:
axis(num): dimension index
ndim(num): number of dimensions
Returns:
num
"""
if axis < 0:
axis += ndim
if axis < 0 or axis >= ndim:
raise IndexError("axis out of range")
return axis | 3075c06cf5843027bc45e04e032798250924f8fd | 3,595,661 |
def dup_inner_isolate_real_roots(f, K, eps=None):
"""Internal function for isolation positive roots up to given precision."""
a, b, c, d = K.one, K.zero, K.zero, K.one
k = dup_sign_variations(f, K)
roots, stack = [], [(a, b, c, d, f, k)]
while stack:
a, b, c, d, f, k = stack.pop()
... | b3d460b479af65514732ae672c2babfd6014938a | 3,595,663 |
def add_schema_ownerships(spec, dbcontext):
"""
Add schema ownerships to an existing spec
One set of assumptions is made here: if a schema's name is the same as its owner and that
owner can login, then the schema is assumed to be a personal schema. This is an assumption
though, and ithe implication... | c4551c22760b3ec837b7f3cb2a83840c2bd46481 | 3,595,664 |
import math
def H(X, bins):
"""
Calculates the entropy of X.
If X is already discretised, set \ref bins to the amount of bins, aka states of X.
If X is not discretised, \ref bins will be used, to diskretise X into \ref bins states
@param X np vector
@param bins If X is already diskretised, a... | 27a51725728a7015bb606600f8ed4c53b4747ad8 | 3,595,665 |
def get_only_selection_from_ast(ast, desired_error_type):
"""Return the selected sub-ast, ensuring that there is precisely one."""
selections = [] if ast.selection_set is None else ast.selection_set.selections
if len(selections) != 1:
ast_name = get_human_friendly_ast_field_name(ast)
if sel... | 6f11376dd3d6f62caf9de7a954d75faaef2a68c2 | 3,595,666 |
def file_urls(source):
"""Parse URL information from imeji XML.
:param source: Path to a imeji collection metadata file in imeji XML format.
:return: dict of (md5sum, infodict) pairs.
"""
res = {}
items = ElementTree.parse(source)
for item in items.findall(qname('item')):
data = dic... | 23f8bfcc1a5cb94469606e4deccc59345e797625 | 3,595,667 |
def is_desired_workflow(run_json):
"""
Checks if this run is for the "Presubmit Checks" workflow.
"""
# Each workflow has a fixed ID.
# For the "Persubmit Checks" workflow, it is:
# https://api.github.com/repos/taichi-dev/taichi/actions/workflows/1291024
DESIRED_ID = 1291024
return run_j... | fc5d915fd3e7b8a62075b29fc9dbe8525fc4da0a | 3,595,669 |
def diarization_with_timing(diarization):
"""Process diarization output and extract speaker with time bounds"""
speech_start = np.empty(diarization.shape, dtype=bool)
speech_start[0] = True
speech_start[1:] = np.not_equal(diarization[:-1], diarization[1:])
segment_indexes = np.argwhere(speech_start)... | a0c9beb3582bcb3cb41fc48a07443b9c81556e96 | 3,595,670 |
import io
def read_sql_inmem_uncompressed(query, conn):
"""
Builds a dataframe from a query to a postgres database.
Parameters
----------
query : string
Sql query
conn : psycopg2.extensions.connection
Postgres database connection
Returns
-------
PandasDataframe
... | e9d7c508289843ac62899a0574c087a6b21e5e70 | 3,595,671 |
def format_codepoint(codepoint):
"""Format a codepoint (integer) to a USV (at least 4 hex digits)"""
usv = ''
if codepoint:
usv = f'{codepoint:04X}'
return usv | c3ac63ab0218ad90f7191507a825e95a4f4ab80c | 3,595,672 |
from datetime import datetime
def strf_delta(time_delta: datetime.timedelta, show_seconds: bool = True) -> str:
"""Formats timedelta into a human readable string."""
years, days = divmod(time_delta.days, 365)
hours, rem = divmod(time_delta.seconds, 3600)
minutes, seconds = divmod(rem, 60)
years_f... | 371f552a38c94a8cd2287cffc806324cf007d57a | 3,595,673 |
import heapq
def count(words=[], top=None, threshold=0, stemmer=None, exclude=[], stopwords=False, language=None, **kwargs):
""" Returns a dictionary of (word, count)-items, in lowercase.
Words in the exclude list and stop words (by default, English) are not counted.
Words whose count falls below ... | f378be25b4a22a3826876ab8ab71e34382ac7d92 | 3,595,674 |
def distance_meters(lonLat1, lonLat2):
"""
Calculate the distance in meters on a globe between two points
:param lonLat1:
:param lonLat2:
:return: distance in meters
"""
# GEOD.inv fails when Points are nearly equal
if norm2(lonLat1, lonLat2) < 1e-5:
return 0
lon1, lat1 = lo... | 5b84de63d107271d1dc91a64164ec34502ab3317 | 3,595,675 |
def compute_facial_encodings(
sess, images_placeholder, embeddings,
phase_train_placeholder, image_size,
embedding_size, nrof_images, nrof_batches,
emb_array, batch_size, paths,
):
""" Compute Facial Encodings
Given a set of images, compute the facial encodings of each face
... | 0d62e324f211194f82d4d11d4362be2dc6fb548a | 3,595,676 |
def lgauss_uncert_std_umf(x, params):
"""
Left Gaussian with uncertain standard deviation UMF
Parameters
----------
x :
numpy (n,) shaped array
The array like input x indicates the points from universe of
discourse in which the membership function would be eva... | 0275db207becf13a363990c43828d1fb7ec4f59b | 3,595,677 |
def read_dimensions(filename_or_stream: FilenameOrStream) -> Dimensions:
"""Return the dimensions of the image."""
image = Image.open(filename_or_stream)
return Dimensions(*image.size) | 011b25abf7420668ab63321a78921b7ed2b71b81 | 3,595,678 |
def compile(qasm_circuit, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, get_layout=False, format='dag'):
"""Compile the circuit.
This builds the internal "to execute" list which is list of quantum
circuits to run on different backends.
Args:
qasm_circuit (st... | 7ea81fdfe6bee09b25c9d7939609f321af79d4bd | 3,595,679 |
def logmap(x, x0):
"""
This functions maps a point lying on the manifold into the tangent space of a second point of the manifold.
Parameters
----------
:param x: point on the manifold
:param x0: basis point of the tangent space where x will be mapped
Returns
-------
:return: u: ve... | f098719a8ee108cbe27f33cc814c90cb21f8d0c0 | 3,595,680 |
import json
def register():
"""Register a new user.
Input:
* username: username
* password: password
Returns:
* result: success - registration is successful.
* result: failed - registration failed (user already exists).
"""
data = json.loads(request.get_data().decode('utf-8'))
... | 6df85b4d58f05ee01292f4a27ed94df0625217e8 | 3,595,681 |
def _is_single(obj):
"""
Check whether `obj` is a single document or an entire corpus.
Returns (is_single, new) 2-tuple, where `new` yields the same
sequence as `obj`.
`obj` is a single document if it is an iterable of strings. It
is a corpus if it is an iterable of documents.
"""
obj_... | 3de19634c062ed9a0e38fd43c01007c8974f3d77 | 3,595,682 |
import time
import json
def verify_bgp_neighbor(kafka_consumer, node, neighbor_address,
session_state=SESSION_STATE_ESTABLISHED,
timeout=VALIDATION_TIMEOUT):
"""Verify BGP session state."""
telemetry_encoding_path = "Cisco-IOS-XR-ipv4-bgp-oper:bgp/instances/inst... | b05fc1c98036870610f44d25bf7d0505083e3832 | 3,595,684 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.