content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def canonical_version(versionstr, release_type='python-service'):
"""Given a version string verify it is in the canonical form."""
errors = list(validate_version(versionstr, release_type))
if errors:
raise ValueError(errors[-1])
return versionstr | caa578f41b7046e88a9a174221d9d1af9b378955 | 41,500 |
def CircAperture(Fin, R, x_shift = 0.0, y_shift = 0.0):
"""
*Inserts a circular aperture in the field.*
:param R: radius of the aperture
:type R: int, float
:param x_shift: shift in x direction (default = 0.0)
:param y_shift: shift in y direction (default = 0.0)
:type x_shift: int, floa... | bad700cd1e1c8f8767ab52b1444d4088ca30f6b2 | 41,501 |
import re
def extract_access_token(request):
"""
Get the access token using Authorization Request Header Field method.
Or try getting via GET.
See: http://tools.ietf.org/html/rfc6750#section-2.1
Return a string.
"""
auth_header = request.META.get('HTTP_AUTHORIZATION', '')
if re.compi... | 6c6d36bdd4965796bacdca7d13a2fc6ef2189299 | 41,502 |
def param_is_numeric_and_simple(p):
"""
Test whether a parameter is numeric and, if it is a string, that it doesn't
contain scientific or uncommon notation.
:param p: An input parameter
:return:
"""
if isinstance(p, str):
return str_is_numeric(p)
else:
return param_is_num... | 3e85671d84d865767c306199c98f1c1c2b151a29 | 41,503 |
def DefineNor(height, width):
"""
Generate Nor module
I0 : Array(width, Bit), I1 : Array(n, Bit) -> O : Array(n, Bit)
"""
T = Array(width, Bit)
class _Nor(Circuit):
assert height > 1 and height <= 4
name = 'Nor%dx%d' % (height, width)
if height == 2:
IO ... | b7de2c1f5af67d96aed3e840f20bcce9d3ac4023 | 41,504 |
def HMA(data, period=16):
"""
Hell's Moving Average
HMA indicator is a common abbreviation of Hull Moving Average.
The average was developed by Allan Hull and is used mainly to identify the current market trend.
Unlike SMA (simple moving average) the curve of Hull moving average is considerably s... | 604bc4da85d3cb5220db6460caf84f90ff8cc401 | 41,505 |
import torch
def create_input(shape):
"""Create a random input tensor."""
return torch.rand(shape).float() | 88a907bae19882a4a7c1a0b819eb0deccb065752 | 41,506 |
def input_thing():
"""输入物品信息"""
name_str, price_str, weight_str = input('物品名称,价格,重量: ').split()
return name_str, int(price_str), int(weight_str) | d48452a942263ae522e93474c6cc4a5cdd9e097c | 41,507 |
def perpendicular_vector(R, max_alt):
"""
Generates a viewing and tangent vectors
perpendicular to a sphere of radius R
"""
return np.array([0, R+max_alt*2, 0]).reshape(3, 1), \
np.array([0.0, 0, 0]).reshape(3, 1) | 5a08c9d935d05ccee99666627a359ee5c6163147 | 41,508 |
import base64
import time
def enroll(video):
"""
Params:
video: base64 encoded data
"""
try:
setup_directories()
content = base64.b64decode(video)
filename = frappe.session.user+".mp4"
OUTPUT_VIDEO_PATH = frappe.utils.cstr(frappe.local.site)+"/private/files/user/"+filename
with open(OUTPUT_VIDEO_PATH,... | 6bc989f656f123613b85d61f3217f39a0a5d993f | 41,509 |
def nonzero_maximum_box(input: Image, flag_dst: Image, destination: Image = None) -> Image:
"""Apply a maximum filter (box shape) to the input image.
The radius is fixed to 1 and pixels with value 0 are ignored.
Note: Pixels with 0 value in the input image will not be overwritten in the
output im... | a28e2fe91e712ca95ed66670465e72033d756a7e | 41,510 |
def linear_layer(input_tensor, classes, train,
summary=False, rf=1, data_format="NCHW"):
"""Builds a logit layer that we apply the softmax to, with variables
Args:
input_tensor: input tensor
classes: Number of classes to classify in the output
train: If we want to train this layer or no... | d297314d5af49065f19fda689939d6216fe34734 | 41,511 |
import os
def upload(filename, uri, extra={}):
""" Upload object to S3 uri (bucket + prefix), keeping same base filename """
s3 = boto3.client('s3')
s3_uri = uri_parser(uri)
bname = os.path.basename(filename)
uri_out = 's3://%s' % os.path.join(s3_uri['bucket'], os.path.join(s3_uri['key'], bname))
... | bb355a64d95df97554d35f0e1bab76b12baa7b19 | 41,512 |
def get_information(key):
"""
Obtains a variety of runtime information about CMSElemental.
"""
key = key.lower()
if key not in __info:
raise KeyError(f"Information key '{key}' not understood.")
return __info[key] | bfe75ac86a9231629fbf3472cbdddfd1e4015787 | 41,513 |
import string
import random
def gene_text(number=6):
"""生成随机字符"""
source = string.ascii_letters+string.digits
return ''.join(random.sample(source,number)) | 40970c8b938797243d7626ebad48e78116df657a | 41,514 |
from typing import Tuple
from typing import Dict
import logging
def parse(message: str, scenario: Scenario) -> Tuple[Actions, object, Dict]:
"""Attempts to parse the player action into an action, target and arguments.
Args:
message - the incoming message from the player-action socket.
scenari... | fe7b06606bf7d680a3056f3aa5cef3f850caaa62 | 41,515 |
def gen_snippet(snippet, config):
"""Renders a config snippet.
"config" represents the portion of the YAML
file applicable to this snippet"""
template = ENV.get_template(snippet + ".j2")
return template.render(config=config) | cb740b483204b7c49647414ae24145475a0d9b6f | 41,516 |
import requests
from bs4 import BeautifulSoup
from datetime import datetime
def get_info_from_notice(notice):
"""
# 글 제목, 글 작성자
if(str(notice).find('font')!=-1):
print('정상작동')
title = notice.find('font').text
else:
print('에러')
writer = notice.find('td', attrs={'class'... | a063bc6cbbcc18dc49c5141d235373e65deed810 | 41,517 |
def update_param_name(param_name):
"""
Takes an abbreviated name and expands it so the user can type DISP or
DISPLACEMENT and get the same answer
Parameters
----------
param_name : str
the parameter name to be standardized (e.g. DISP vs. DIPLACEMENT)
.. todo:: not a complete list
... | 8ac9809faacfd50f46b583cc996144b93d26540a | 41,518 |
def thead(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", transl... | aa288162d200733761d3b84f81234fb1b05dfe7d | 41,519 |
from typing import Union
from typing import Type
def get_msf_session_id(session_name: str, plan_execution_id: Union[Type[int], int]) -> str:
"""
Get a Metasploit session ID by the defined session name
:param str session_name: Session name provided in input file
:param int plan_execution_id: ID of the... | 27ba07da3c7330cf752a02b9737f153e258d3a25 | 41,520 |
def compute_margin(
input_fn, root_dir, model_config, sess=None,
batchsize=50, dataset_size=50000):
"""Compute the margins of a model on all input data.
Loads a given model from given directory and load the parameters in the given
scope. Iterates over the entire training dataset and computes the upper bo... | 717e9a3cf03ab4f7594a4f082a7cc2699b0bd75b | 41,521 |
def in_notebook():
"""Determine whether code is running in a Jupyter Notebook shell.
Returns
-------
ip : bool
True if running in a notebook shell, False otherwise
"""
try:
# See https://stackoverflow.com/questions/15411967
shell = get_ipython().__class__.__name__
... | f3b77ecb41c40b8bc8f558441374fc35949c331d | 41,522 |
import tokenize
from operator import getitem
import math
def groupby_agg(
ddf,
gb_cols,
aggs_in,
split_every=None,
split_out=None,
dropna=True,
sep="___",
sort=False,
as_index=True,
):
""" Optimized groupby aggregation for Dask-CuDF.
This aggregation algorithm only sup... | 67635be47d6495f75e57649ca565dd454143853a | 41,523 |
def put_op(form):
"""Annotation for a callable function specifying that it is a PUT :class:`Op`."""
return op.Put(form) | c90562f01a64bed25a576ea503f65e93feb0f7aa | 41,524 |
def str_to_tstamp(time_value):
""" Convert date string to timestamp
Args:
time_value (Union[str, int]): date string in any format supported by dateutils.parser.parse
Returns:
int: timestamp
"""
if type(time_value) is int:
# If we got int - consider it being timestamp already
... | 758216ec302d87adff5be5673c89476f164c053f | 41,525 |
def merge_UserInput_with_SourceDF(user_df: pd.DataFrame, source_df: pd.DataFrame):
"""
Reads the user feature dataset and merges that to the end of the source dataset. Removes the duplicates
found in the source with the users dataset. It returns a tuple. first element is the merged dataset
and the secon... | a5c16112a43985ae9c56ff017a825ea126e2ad52 | 41,526 |
from datetime import datetime
def get_effective_data_length(user_code, span_min=10, best_effort=False, exclude_capped=False,
start_time=None, end_time=None, min_num_samples=100):
"""
To compute the length of the data by the user, based on `ActionLog`. Our system establishes
a connection (from app ... | 9307e0b142775430f088249f9ae37ef3b549c875 | 41,527 |
def lorenz_curve(data: pd.Series) -> pd.Series:
"""
Calculates the values for the lorenz curve of the data.
For more information see online `lorenz curve
<https://en.wikipedia.org/wiki/Lorenz_curve>`_.
Args:
data: sorted series to calculate the lorenz curve for
Returns:
the va... | 0a430c60f61addb286d0d29c9358906d810bae12 | 41,528 |
from typing import Iterable
def cut_solid(solid, cutter):
"""
Performs a boolean cut of a solid with another solid or iterable of solids.
Args:
solid Shape: the Shape that you want to cut from
cutter Shape: the Shape(s) that you want to be the cutting object
Returns:
Shape: the... | 44f2f039a4bbeba986f4195f9294369f11f59531 | 41,529 |
def pad_bitmap(bitmap, left, top, right, bottom, value, debug=False):
""" Pads a bitmap with pixels on each side. The new cells are applied the value
:param bitmap: A numpy array
:param left: The number of pixels that should be added to the left
:param top: The number of pixels that shou... | a755dedb1482cc47853378f015d4c12de73a0d36 | 41,530 |
def _find_stub_degree(branch, bus_id):
"""Find degree of stubbiness, and stub branches.
:param pandas.DataFrame branch: branch DataFrame from Grid object.
:param int bus_id: index of bus to find subbiness of.
:return: (*tuple*) -- tuple containing:
stub_degree (*int*) -- How stubby (non-negativ... | 4036fb131674401441ac5387923a78a37378ace2 | 41,531 |
def add_data_to_list(twitter_return):
"""
Extract the data from the twitter_return dictionary and place in a list
"""
twitter_dict = twitter_return ['response_dict']
# Grab the twitter data
twitter_data_list=twitter_dict['data']
return twitter_data_list | 9e2a2a5e22926b604856c1ec1ae20ebf765b8610 | 41,532 |
def get_issue_by_url_seg(url_seg, url_seg_issue):
"""
Retorna um número considerando os parâmetros ``iid`` e ``kwargs``.
- ``url_seg``: string, contém o seguimento da URL do Journal;
- ``url_seg_issue``: string, contém o seguimento da URL do Issue,.
"""
journal = get_journal_by_url_seg(url_seg... | 8b7f167a0bebf7cd4484a4da24df142e70c60cad | 41,533 |
def negentropy(p):
"""
Entropy which operates on vectors of length N.
"""
# This works fine even if p is a n-by-1 cvxopt.matrix.
return np.nansum(p * np.log2(p)) | 90b271589ba25d86420ad8413cd83fa304d75d24 | 41,534 |
def check_n_files(subject, collector, keep, n_file=1):
"""
Organise download path per subject for the two sessions.
If the number of total file is not the same as expected, drop the subject.
Parameters
----------
subject: str
Subject ID.
collecter: dict
Dictionary collecti... | 56e9ec830d573b8fc8f5c50c1b6bc126a44653a7 | 41,535 |
import os
def load_data():
"""Load and return example data.
Returns:
log (List[List[str]]): example log.
"""
# file path
absPath = os.path.abspath(__file__)
fileDir = os.path.dirname(absPath)
code = os.path.dirname(fileDir)
data = os.path.join(code, "data")
# load the f... | 2bbb54acb387dd2446a39851ad472d2be1cd6013 | 41,536 |
from spynoza.nodes.utils import get_scaninfo
import tempfile
import nipype.pipeline as pe
import nipype.interfaces.fsl as fsl
import os.path as op
def curate_EPI_space(moco_target):
"""curate_EPI_space doubles the amount of timepoints of the
moco target if it has only one. This is mandatory for the AFNI moco... | 273827490a1c41fec2e9fa0df60701d038b2a045 | 41,537 |
def create_resource_id_tag(**kwargs):
""" create tag via resource id """
session = kwargs.get('session', {})
resource_id = kwargs.get('resource_id', {})
tag_name = kwargs.get('tag_name', {})
tag_value = kwargs.get('tag_value', {})
try:
tag_session = session.get_client_session(service='ec... | 2eef38417ce22520267f31b1b24297f914e2392a | 41,538 |
def ErrorReset(*args):
"""ErrorReset()"""
return _gdal.ErrorReset(*args) | ea013beb93eed6f2d7f91f1a9d1cab5e6692769f | 41,539 |
from typing import Dict
def get_noise_range_pcts(db_range_exps: dict, length: float) -> Dict[int, float]:
"""Calculates percentages of aggregated exposures to different noise levels of total length.
Note:
Noise levels exceeding 70 dB are aggregated and as well as noise levels lower than 50 dB.
Re... | 723c7e45a24c149df6f5f19b3f8aabb1f8d5b184 | 41,540 |
def update_info():
"""
用户信息更新
"""
username = request.get_json()['username']
email = request.get_json()['email']
password = request.get_json()['password']
words_book = request.get_json()['words_book']
words_num = request.get_json()['words_num']
words_num = int(words_num) if words_num ... | d997cf23ec0320b4b583f35431df11877116ecd2 | 41,541 |
def read_terminals(terminals_file=DEFAULT_TERMINALS_FILE):
"""Returns all terminals in order that they are coded in file_train. """
terminals = read_json(terminals_file)[:50000 - 1]
return [EMPTY_TOKEN] + terminals + [UNKNOWN_TOKEN] | 6514a760f4ed2a49be97230ce6315c0d8bc27d8c | 41,542 |
def _sync_engagement_db_dataset_to_coda(engagement_db, coda, coda_config, dataset_config, cache, dry_run=False):
"""
Syncs messages from one engagement database dataset to Coda.
:param engagement_db: Engagement database to sync from.
:type engagement_db: engagement_database.EngagementDatabase
:para... | e56e967a96348760119e9194909fdbd2ae65d6fb | 41,543 |
def group_by_first(pairs):
"""Return a list of pairs that relates each unique key in the [key, value]
pairs to a list of all values that appear paired with that key.
this documentation should state why this should normally be used; what should this func normally be used for?
Arguments:
pairs -- a se... | 430f6cb9c8c3fc0b6f6b5078f383c5bbb7420dfe | 41,544 |
def accepts_environment(func):
"""Allows defining an action function that accepts only theTrailEnvironment and doesn't accept a context.
Example:
@accepts_environment
def action_function_taking_only_environment(trail_env):
# Do something with trail_env
pass
"""
@wraps(func)
... | 8d6ce250e6bd22e6ec110aded195dfd63e4fe286 | 41,545 |
def film_layer(incoming, gamma, beta, name='film'):
"""
FiLM layer
:param incoming: incoming tensor
:param gamma: incoming gamma
:param beta: incoming beta
:param name: (string) name scope
:return:
"""
with tf.name_scope(name):
# get shape of incoming tensors:
in_shap... | 0617da38dabe08cdbde762b20f2f1d9f75d9256c | 41,546 |
def _score_lcs(target_tokens, prediction_tokens):
"""Computes LCS (Longest Common Subsequence) rouge scores.
Args:
target_tokens: Tokens from the target text.
prediction_tokens: Tokens from the predicted text.
Returns:
A Score object containing computed scores.
"""
if not target_tokens or not pr... | 666cc0761d0bbd221ccd09106d16073c323d42d1 | 41,547 |
def reshape_t(x, shape):
"""Work around fact that x.reshape(()) doesn't work"""
if shape != ():
return x.reshape(shape)
else:
return x[0] | 579a63afd05ff86093903e160db16266e2bb2125 | 41,548 |
import ctypes
def make_shared_array(np_array: np.ndarray) -> mp.Array:
""" shared array"""
flat_shape = int(np.prod(np_array.shape))
shared_array_base = mp.Array(ctypes.c_float, flat_shape)
shared_array = np.ctypeslib.as_array(shared_array_base.get_obj())
shared_array = shared_array.reshape(np_arr... | 4b1f7ff98c82506c5f04631f4d2211d4e8ca990c | 41,549 |
def _create_core_state_space(optim_paras, options):
"""Create the core state space.
The state space of the model are all feasible combinations of the period,
experiences, lagged choices and types.
Creating the state space involves two steps. First, the core state space is created
which abstracts f... | 6f33032212e61d69e11a616f132961f6f70ae373 | 41,550 |
def mean_coherencegram(perievent_lfp1, perievent_lfp2, dt, window, fs, extend=0.3):
""" Computes the mean coherence over time between perievent slices
(e.g. "coherencegram" because it's a combination of a coherence and a spectrogram)
Parameters
----------
perievent_lfp1 : nept.AnalogSignal
... | 1d98c7b47f6775bfd51935e8d194d464e9f9833a | 41,551 |
def calc_n_max_vehicle(n2v_g_vmax, v_max):
"""Calc `n_max3` of Annex 2-2.g from `v_max` (Annex 2-2.i). """
return n2v_g_vmax * v_max | 457562edce05aebf7d7b870a232b4e0a01df5055 | 41,552 |
import math
def log_average_miss_rate(prec, rec, num_images):
"""
log-average miss rate:
Calculated by averaging miss rates at 9 evenly spaced FPPI points
between 10e-2 and 10e0, in log-space.
output:
lamr | log-average miss rate
mr | miss r... | ab323e409bf18ee6a1853a49adce063d2432bf98 | 41,553 |
def get_access_token(session=None, username=None, password=None):
""" Get the access token from the server.
Return a (access_token, refresh_token) pair.
"""
if session is None:
session = get_authenticated_session(username, password)
# Request the authorization server for the code.
re... | 4bd54bf3118b0ba5ae76c087e767cf1705ee153c | 41,554 |
async def approve_application(uid: str, username=Depends(auth_handler.auth_wrapper)):
"""
Approve an Application
Require: Admin-write
"""
logger.debug(f"{username} trying to offer (approve) an ApplicationForm")
permission_ok = Access.is_admin_write(username)
if not permission_ok:
lo... | 627d8e8dec04a7b06ed134b1a1d386260e029d49 | 41,555 |
def gelu_jit(x):
"""OpenAI's gelu implementation."""
return gelu(x) | 36540583715daaeae9190b421276b013f2182a9a | 41,556 |
import os
def read(fname):
"""Utility function to read the README file. Used for the long_description"""
return open(os.path.join(os.path.dirname(__file__), fname)).read() | 098fd12e1e0692b0a1f19b233d92d37146f1d079 | 41,557 |
def query_st_production(jobs: list[PackJob]) -> list[tuple[int, int, int]]:
"""Fetch production w.r.t time
:returns: list[tuple[product_code, pack_code, production]]
"""
result = None
cond = []
for job in jobs:
cond.append(
sa.and_(
*[
S... | d809ff10daaebae1cf89f1f4fab30510cc17ea4c | 41,558 |
import random
def rnd_position(seq, rates, model, mean_logs, sd_logs, sample=None):
"""Generates a list of mutation/indel sites by applying a random process specified by the model parameter."""
try:
N_positions=[pos for pos, char in enumerate(seq) if char == 'N'] # finding position of N in the seq, it will be us... | 98c8bda46f1f9a59c38071da4840e78e18ccba50 | 41,559 |
def savecompanyrow(table, companyrow, thecompany=None):
"""
:param table:
:param companyrow:
:param thecompany:
:return:
"""
sqlstring = """
UPDATE Company SET
ID=?,
CompanyName = ?,
WebAddress = ?,
StreetAddress1 = ?,
StreetAddress2 = ?,
City = ?,
State =... | 452b0d0b7931b9f81ad190c94da7405c47e9e416 | 41,560 |
def filt_by_filetype(filetypes, value):
"""
filt the urls of filetypes
"""
for ftype in filetypes:
if value.endswith(ftype):
return True
return False | 2844d554b5d15a232e416e623529c18c41f5b1ef | 41,561 |
import unittest
def test_suite():
"""Discover unittests"""
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('str_analysis', pattern='*tests.py')
return test_suite | 351d2f09e9fcd0e709d04ed3af5283cd7d94768d | 41,562 |
def compute_zero_mask(imgarr, iterations=8, ext=0):
"""Find section from image with no masked out pixels and max total flux"""
if isinstance(imgarr, str):
img_mask = fits.getdata(imgarr, ext=0)
else:
img_mask = imgarr.copy()
img_mask[img_mask > 0] = 1
img_mask = ndimage.binary_erosi... | 2e63a9156ebb00c217d3587c446cc393b815c9c3 | 41,563 |
import datetime
from aiida.backends.djsite.db.models import DbSetting
from aiida.backends.sqlalchemy.models.settings import DbSetting
from aiida.backends.sqlalchemy import get_scoped_session
from sqlalchemy import func
from pytz import utc
from sqlalchemy.dialects.postgresql import TIMESTAMP
def get_most_recent_daemo... | eabdc6a05ecd1538a94e418075418fba3d1b3981 | 41,564 |
def get_conf(base_dir):
"""
Get the actual configuration, built by merging the repository conf into the
global user conf.
"""
user_conf = get_user_conf()
repos_conf = get_repository_conf(base_dir)
configspec_fname = op.join(THIS_DIR, 'confspec.ini')
merged_conf = configobj.ConfigObj(conf... | db8e9c0a617a8bae853bb75bb05bf9fd405ce646 | 41,565 |
import codecs
import os
import re
def get_metadata(package, field):
"""
Return package data as listed in `__{field}__` in `init.py`.
"""
init_py = codecs.open(os.path.join(package, '__init__.py'), encoding='utf-8').read()
return re.search("^__{}__ = ['\"]([^'\"]+)['\"]".format(field), init_py, re.... | 3074f9a450cbdea30ccd8158ad95585f770fb244 | 41,566 |
def dla102x(**kwargs):
"""
DLA-X-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the mo... | 9f807b9f1dce546d925f1ce160ca4f723f3d6662 | 41,567 |
def is_valid_iyr(iyr: str) -> bool:
"""
(Issue Year) - four digits; at least 2010 and at most 2020.
:return: Status of field (true = valid).
:rtype: bool
"""
iyr = int(iyr)
if iyr < 2010 or iyr > 2020:
return False
return True | 943e2aad621b10d9b37b0a7c44363ddb5f90b245 | 41,568 |
def conv_transpose3d_ncdhw(inputs, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1, out_dtype="float32"):
"""Convolution transpose 3d NCDHW layout
Args:
-----------------------------
inputs : GraphNode
shape [batch, channel, depth, height, width]
weight : Gra... | 955d04906ac66a169c062c7d59985f28181baddd | 41,569 |
import os
import io
def build_readme_files_dict(app, repository, changeset_revision, metadata, tool_path=None):
"""
Return a dictionary of valid readme file name <-> readme file content pairs for all readme files defined in the received metadata. Since the
received changeset_revision (which is associated... | e5508b91728d4dc3d8140effd3e655309e906310 | 41,570 |
async def vif_get_lock_by_uuid(cluster_id: str, vif_uuid: str):
"""Get VIF Lock by UUID"""
try:
session = create_session(
_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()
)
vif: VIF = VIF.get_by_uuid(session=session, uuid=vif_uuid)
ret = dict(success=True... | 44015081a31982b7f4da3fbd8bca89569cee01c2 | 41,571 |
def text_to_data(input_data, encoding='utf8'):
""" Converts text data into (N,8) numpy array of bits"""
# Convert to data to a list of bytes, represented as integers
data_binary_stream = [int(x) for x in bytearray(input_data, encoding)]
# Convert into numpy array of uint8 and convert to row vector
d... | 1f89aa4916122cbc804524f4bcceb8d5eb5a3daf | 41,572 |
from typing import Union
def group_bounding_box(
group: Union[hou.EdgeGroup, hou.PointGroup, hou.PrimGroup]
) -> hou.BoundingBox:
"""Get the bounding box of the group.
:param group: The group to get the bounding box for.
:return: The bounding box for the group.
"""
group_type = utils.get_gro... | d9e7257bdca7a35de3e1f598a73ea5bffd76c530 | 41,573 |
from typing import Tuple
from typing import Dict
from typing import List
def get_dimorder(dimstring: str) -> Tuple[Dict, List, int]:
"""Get the order of dimensions from dimension string
:param dimstring: string containing the dimensions
:type dimstring: str
:return: dims_dict - dictionary with the di... | 18efb512595a82df0eae1434de33cdddb83b193b | 41,574 |
def determine_variable_usage(root, args, symbols, closure_vars):
"""The helper function for calling the dedicated visitor."""
visitor = PyVariableUsage(args, symbols, closure_vars)
visitor.visit(root)
return visitor.status | 1460ac691b23c1d80f3c8014855ecadd6be617a8 | 41,575 |
def read_number_of_states(dpomdp_file):
"""Returns the number of states in a Dec-POMDP problem
Keyword arguments:
dpomdp_file -- path to problem file in the .dpomdp format
"""
with open(dpomdp_file) as file:
for line in file:
if line.startswith('states:'):
return int(line.split(':')[1])
raise V... | 688a3a239d457637791d35f5be612ed0d155c94e | 41,576 |
def max_dd_std_ratio(x:pd.DataFrame) -> float:
"""
"""
return max_drawdown(x) / (np.std(x) * np.sqrt(252)) | 797d0b300c04b5976d2f4a7fcf95f74599342d31 | 41,577 |
def hasshmem(type):
"""Return true iff |type| is shmem or has it buried within."""
class found: pass
class findShmem(TypeVisitor):
def visitShmemType(self, s): raise found()
try:
type.accept(findShmem())
except found:
return True
return False | cb79cb2c479cebaeac777716b77956a754cd65fe | 41,578 |
def run_stdout(
name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel="debug",
use_vt=False,
ignore_retcode=False,
keep_env=None,
):
"""
Run :py:func:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a
container
name
Container nam... | 71158227cc29595ce526eeb7946584085b3baccc | 41,579 |
from datetime import datetime
def get_stats(uid, start_date, end_date):
""" Get weather data for the specified weather period """
db = get_db()
rows = db.get_stats(start_date=start_date, end_date=end_date, uid=uid)
if len(rows) == 0:
return
plot = {}
col_names = rows[0]._asdict().ke... | cf07acc90cdad03f6d35b50c83456eedc63ea269 | 41,580 |
def distance(woolrgb, cpixel):
""" ricerca il blocco di lana colorata piu' vicino al colore del pixel """
r = cpixel[0]
g = cpixel[1]
b = cpixel[2]
did = 0
dmin = 255*255*3
for i in woolrgb:
dr = r - woolrgb[i][0]
dg = g - woolrgb[i][1]
db = b - woolrgb[i][2]
... | d6247e40ba12a271dc6784f71088ad0e838c600a | 41,581 |
def AptGetPathToConfig(vm):
"""Returns the path to the mongodb config file."""
return '/etc/mongodb.conf' | 114cb896ece163f57a73cbe21fe376e53aa33782 | 41,582 |
import os
def make_paths(sheet_list):
"""
Тихий ужас... Функция парсит формат файла с путями.
"""
PKM = { "InMarker" : "In",
"OutMarker" : "Out" } # Part kind markers
PTM = { "DirMarker" : "Dir",
"NameMarker" : "Fname",
"TypeMarker" : "Ftype" } # Part typ... | f662c4b783d350bec818aaa597667beb2ca4e4e6 | 41,583 |
def dict_to_ht_metadata(metadata_dict):
"""
Converts the incoming metadata dictionary into a list of metadata json
objects usable by HyperThought endpoints.
Parameters
----------
metadata_dict
The metadata dictionary that will be converted to a list of metadata
json objects
... | 163c565cb511c86cd8c5c055e782cfb48c79b1ff | 41,584 |
def get_filepath_wo_ext(file_spec):
"""
Get file path without extension
Parameters
----------
file_spec : DataStruct
The function use attributes output_dir and fname_wo_ext for construct file path
Returns
-------
out : str
Constructed file path
"""
return file_... | 6ef9d329292769a3f163678915ff696ef3b8fe1a | 41,585 |
import sys
import json
def add_setup_data(queries, E, output, words1, words2, index1, index2, k, lang1,
lang2, categories_path):
"""Outputs setup data for CLIME session.
For each word in [queries], the following information is stored:
- [k] nearest neighbors in language 1 using [index ... | e58e54a8750ea8f8d6a7ea0b65c2b1a8c92e9e1b | 41,586 |
from pydantic import BaseModel # noqa: E0611
def get_dist_params(model: BaseModel = None, data: pd.DataFrame = None, exploration_time: int = 10):
"""
Dynamic plot for plotting beta distributions for a,b values given in a_b_lists.
Parameters
----------
model: NormalDistributionModel or BetaDistrib... | a891196696e811017e3b3986aa783bdf86c50f93 | 41,587 |
def terraform_variable(var):
"""
Ask terraform console for a variable value.
:param var: terraform var to look up
:type var: str
:return: Terraform's output
:rtype: str
"""
return terraform_value('var', var) | ad4c7c47d9fc33f2e6a3c040688c3baecd464696 | 41,588 |
def pot_frequencies(script_str, geoms, grads, hessians, run_path):
""" Calculate the frequencies (need to replace)
all input here are dictionaries (like potentials)
"""
# Initialize hr freqs list
hr_freqs = {}
for point in geoms.keys():
_, proj_freqs, _, _ = frequencies(
... | ce4c1442c800148b7ab0beef062599f468aed6df | 41,589 |
def add_translation_to_file(prev_signs, signs_vocab, prev_transcription, transcription_vocab, prev_tr,
translation_lengths, long_trs, very_long_trs, translation_vocab, prev_text,
prev_start_line, prev_end_line, signs_file, transcription_file, translation_file,
... | e18dcb075c4373ec07f1507c60d70a5128859f03 | 41,590 |
def np_polyfit(train_X, train_Y, poly_degree):
"""
调用numpy.polyfit()方法拟合数据
:param train_X: 训练集的X矩阵
:param train_Y: 训练集的Y向量
:param poly_degree: 多项式次数
:return: 拟合的信息
"""
result = np.polyfit(train_X, train_Y, poly_degree)
picture = np.poly1d(result)
# print(result)
return pictur... | f4e6f5fe0ed019618e82a5b060151e39a7d95520 | 41,591 |
from typing import Optional
def render_environment_variables(instance: Entity) -> Optional[str]:
"""
render the environment variable elements by combining the jinja template
from an entity with the arguments from an Entity
"""
variables = getattr(instance.__definition__, "env_vars")
if not var... | 01c6874bd9c318c01e57221519e4bb81e2d9b21d | 41,592 |
import os
def mkdirs(pathname):
"""
mkdirs - create a folder
"""
try:
if os.path.isfile(pathname):
pathname = justpath(pathname)
os.makedirs(pathname)
except:
pass
return os.path.isdir(pathname) | c342c707786053fb5f456e8a2415fa74a4e4ecd1 | 41,593 |
def read_image_files(image_files, image_shape=None, crop=None, use_nearest_for_last_file=True):
"""
:param image_files:
:param image_shape:
:param crop:
:param use_nearest_for_last_file: If True, will use nearest neighbor interpolation for the last file. This is used
because the last fil... | 3a18c3123e507876e6dcc45d8e6a31435413ef58 | 41,594 |
def prob_double_roll(x, n):
""" Expected probabilities for the sum of two dice."""
# For two n-sided dice, the probability of two rolls summing to x is
# (n − |x−(n+1)|) / n^2, for x = 2 to 2n.
return (n - abs(x - (n+1))) / n**2 | 30d891203a09807ce9dcd16c3f9c05cddef00b1c | 41,595 |
from typing import List
def extract_features(
doc: List[str], window: int = 2, max_n_gram: int = 3
) -> List[List[str]]:
"""
Extract features for CRF by sliding `max_n_gram` of tokens
for +/- `window` from the current token
:param List[str] doc: tokens from which features are to be extracted from... | 4546c5c8206d4dd144c40ed3a9306342642f0a44 | 41,596 |
def _sum_two_blocks(block0, block1, vol):
"""Helper function that beats two blocks against each and finds summation
of the resulting product.
"""
b0 = vol[block0]
b0 = b0 - b0.mean()
b1 = vol[block1]
b1 = b1 - b1.mean()
CC = np.sum(b0 * b1)
lags = []
for n in xrange(block0.nd... | bd0299e58fe524255bb35f3ee6839049802ed432 | 41,597 |
import re
def get_isni_bio(existing, author):
"""Returns the isni bio string if an existing author has an isni listed"""
auth_isni = re.sub(r"\D", "", str(author.isni))
if len(existing) == 0:
return ""
for value in existing:
if hasattr(value, "bio") and auth_isni == re.sub(r"\D", "", s... | 19de26974d34102573f7c5b02317eb23075ebec0 | 41,598 |
def cost_of_connection(connection_distance, hourly_heat_flow, order=24):
"""
function estimating the cost of transmission lines.
:param connection_distance: distance of the pipe in meters.
:type connection_distance: float.
:param hourly_heat_flow: hourly heat flow in MW.
:type hourly_heat_flow:... | 5c244f1fc4c1fcd0559fd3eaefa35daa93e45530 | 41,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.