content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def reversebits5(max_bits, num):
""" Like reversebits4, plus optimizations regarding leading zeros in
original value. """
rev_num = 0
shifts = 0
while num != 0 and shifts < max_bits:
rev_num |= num & 1
num >>= 1
rev_num <<= 1
shifts += 1
rev_num >>= 1
rev_... | ada43721780d512cda73c30d0279216b709501fc | 1,143 |
def rescale(img, thresholds):
"""
Linear stretch of image between two threshold values.
"""
return img.subtract(thresholds[0]).divide(thresholds[1] - thresholds[0]) | 76d5f56384f408e57161848ded85142e68296258 | 1,144 |
def X_n120() -> np.ndarray:
"""
Fixture that generates a Numpy array with 120 observations. Each
observation contains two float values.
:return: a Numpy array.
"""
# Generate train/test data
rng = check_random_state(2)
X = 0.3 * rng.randn(120, 2)
return X | 6c746c759c1113611ee19acfae5326de615821a8 | 1,145 |
def int_to_bytes(n: uint64, length: uint64) -> bytes:
"""
Return the ``length``-byte serialization of ``n`` in ``ENDIANNESS``-endian.
"""
return n.to_bytes(length, ENDIANNESS) | 135260207a65cff99770b8edc1cae3848f888434 | 1,147 |
import string
def upper_to_title(text, force_title=False):
"""Inconsistently, NiH has fields as all upper case.
Convert to titlecase"""
if text == text.upper() or force_title:
text = string.capwords(text.lower())
return text | 939515204b841c5443c5767da20712dff684d286 | 1,148 |
def pairwise_negative(true, pred):
"""Return p_num, p_den, r_num, r_den over noncoreferent item pairs
As used in calcualting BLANC (see Luo, Pradhan, Recasens and Hovy (2014).
>>> pairwise_negative({1: {'a', 'b', 'c'}, 2: {'d'}},
... {1: {'b', 'c'}, 2: {'d', 'e'}})
(2, 4, 2, 3)
... | 64ff19dc861abe9fbc68412a61906b54439aa864 | 1,149 |
def reptile_resurgence_links(tar_url, max_layer, max_container="", a_elem="a", res_links=[], next_url="", callback=None):
"""
爬虫层次挖掘,对目标 URL 进行多层挖链接
参数:目标 URL | 最大层数 | 爬取范围 | 爬取的a标签选择器 | 内部使用,返回列表 | 内部使用 下一个目标
"""
if next_url != "" and next_url[:4] in 'http':
res_links.append(next_url)
i... | a0fe56f4d1b0cd67b1918bf1db54cda6400fc2ca | 1,150 |
from typing import Tuple
def random_uniform(seed_tensor: Tensor,
shape: Tuple[int, ...],
low: float = 0.0,
high: float = 1.0,
dtype: dtypes.dtype = dtypes.float32):
"""
Randomly sample from a uniform distribution with minimum value `l... | 6ec691faa5e35788df8f1b0be839727163271ee8 | 1,151 |
from shapely import wkt
def pipelines_as_gdf():
"""
Return pipelines as geodataframes
"""
def wkt_loads(x):
try:
return wkt.loads(x)
except Exception:
return None
df_fossil_pipelines = load_fossil_pipelines().query("route==route")
# Manual transform to l... | b8f8817111e061db4160f524f13b005f6e8d8a3f | 1,152 |
def historico(
historia="",sintomas="",medicamentos=""
):
"""Histótia: Adicionar os relatos de doenças anteriores do paciente,\n incluindo sintomas antigos e histórico de doenças familiares
\n Sintomas: Descrever os atuais sintomas do paciente
\n Medicamentos: Remédios e tratame... | a5bdb6cc6d13c73845650ec8fcd1d18fc1e4feb2 | 1,153 |
def plot_beam_ts(obs, title=None, pix_flag_list=[], reg_interest=None,
plot_show=False, plot_save=False, write_header=None,
orientation=ORIENTATION):
"""
plot time series for the pipeline reduction
:param obs: Obs or ObsArray or list or tuple or dict, can be the object
... | eb9cd76d3e6b2a722c2d26dd7371cd2ed1716264 | 1,154 |
def get_qos():
"""Gets Qos policy stats, CLI view"""
return render_template('qos.html', interfaces=QueryDbFor.query_interfaces(device),
interface_qos=QueryDbFor.query_qos(device)) | 5e2557738aca2d67561961e10cd7229345cfd96c | 1,156 |
from typing import List
from typing import Callable
from typing import Any
def create_multiaction(action_name: str, subactions: List[str], description: str = '') -> Callable[[Context, Any], Any]:
"""Creates and registers an action that only executes the subactions in order.
Dependencies and allowation rules a... | 920f6696608e120e1218618dd96daa691e95e383 | 1,157 |
import numpy
def phase_amp_seq_to_complex():
"""
This constructs the function to convert from phase/magnitude format data,
assuming that data type is simple with two bands, to complex64 data.
Returns
-------
callable
"""
def converter(data):
if not isinstance(data, numpy.ndar... | ee6a88df5c226115a05a4e57501df73837f98ef5 | 1,158 |
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.svm import SVR
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
... | 9987edf48821d3c1a7164b0d5675da96b6319aa6 | 1,159 |
async def get_group_list_all():
"""
获取所有群, 无论授权与否, 返回为原始类型(列表)
"""
bot = nonebot.get_bot()
self_ids = bot._wsr_api_clients.keys()
for sid in self_ids:
group_list = await bot.get_group_list(self_id=sid)
return group_list | 2eae159381c48451fb776c8c46c15212aa431689 | 1,160 |
def _agefromarr(arr, agelist):
"""Measures the mean age map of a timeslice array.
:param arr: A timeslice instance's data array.
:param agelist: List of age sampling points of array.
:return:
:agemap: Light- or mass-weighted (depending on weight_type in the timecube()) mean metallicity of t... | ba1d31e94661022b8bed05cc36085ed0dbc38c94 | 1,162 |
def _build_timecode(time, fps, drop_frame=False, additional_metadata=None):
"""
Makes a timecode xml element tree.
.. warning:: The drop_frame parameter is currently ignored and
auto-determined by rate. This is because the underlying otio timecode
conversion assumes DFTC based on rate.
... | 9d85287795cf17c1d665b3620d59679183943bd7 | 1,163 |
def transform(nodes, fxn, *args, **kwargs):
"""
Apply an arbitrary function to an array of node coordinates.
Parameters
----------
nodes : numpy.ndarray
An N x M array of individual node coordinates (i.e., the
x-coords or the y-coords only)
fxn : callable
The transformat... | edc487b7f1b83f750f868ee446ecf2676365a214 | 1,164 |
import glob
def create_input(
basedir, pertdir, latout=False, longwave=False, slc=slice(0, None, None)
):
"""Extract variables from a given directory and places into dictionaries.
It assumes that base and pert are different directories and only one
experiment output is present in each directory.
... | 1bfda243bf6e11eee38cfb4311767c78f79589c2 | 1,165 |
import logging
def get_tax_proteins(tax_id, tax_prot_dict, prot_id_dict, gbk_dict, cache_dir, args):
"""Get the proteins linked to a tax id in NCBI, and link the tax id with the local db protein ids
:param tax_id: str, NCBI tax db id
:param tax_prot_dict: {ncbi tax id: {local db protein ids}}
:param ... | d3aaa32adbc1ad66e0a6bb2c615ffc0f33df9f00 | 1,166 |
def define_features_vectorizer(columns, training_data, testing_data = None, ngramrange=(1,1)):
"""
Define the features for classification using CountVectorizer.
Parameters
----------
column: String or list of strings if using multiple columns
Names of columns of df tha... | 9c29847620ba392004efdeac80f607bc86db2780 | 1,167 |
import html
def show_graph_unique_not_callback(n_clicks, input_box):
""" Function which is called by a wrapped function in another module. It takes
user input in a text box, returns a graph if the query produces a hit in Solr.
Returns an error message otherwise.
ARGUMENTS: n_clicks: a parameter of t... | a53112cf76acd2a02ccd1a251b0a439ea8b06c77 | 1,170 |
def _add_string_datatype(graph, length):
"""Add a custom string datatype to the graph refering.
Args:
graph (Graph): The graph to add the datatype to
length (int): The maximim length of the string
Returns:
URIRef: The iri of the new datatype
"""
iri = rdflib_cuba[f"_datatyp... | 65534a58257157c9cf8943b8f4ba3c3a39d8a5b2 | 1,171 |
def get_selected_shipping_country(request):
"""Returns the selected shipping country for the passed request.
This could either be an explicitely selected country of the current
user or the default country of the shop.
"""
customer = customer_utils.get_customer(request)
if customer:
if c... | 330ccf01ed261a3b669589ab3e550147f6086b0b | 1,172 |
def func_item_iterator_next(*args):
"""
func_item_iterator_next(fii, testf, ud) -> bool
"""
return _ida_funcs.func_item_iterator_next(*args) | ce4bb7516354c36fbb3548882ff45c64c8090381 | 1,173 |
def find_score_maxclip(tp_support, tn_support, clip_factor=ut.PHI + 1):
"""
returns score to clip true positives past.
Args:
tp_support (ndarray):
tn_support (ndarray):
Returns:
float: clip_score
Example:
>>> # ENABLE_DOCTEST
>>> from ibeis.algo.hots.score_... | 5b51bc8a09f8e7c93e9196bab8e0566c32d31ad9 | 1,174 |
import json
def create_sponsor():
"""
Creates a new sponsor.
---
tags:
- sponsor
summary: Create sponsor
operationId: create_sponsor
requestBody:
content:
application/json:
schema:
allOf:
- $ref: '#/com... | 70d78a05046b2a9e845176838ae85b7c6aef01f5 | 1,175 |
import shutil
def download_or_copy(uri, target_dir, fs=None) -> str:
"""Downloads or copies a file to a directory.
Downloads or copies URI into target_dir.
Args:
uri: URI of file
target_dir: local directory to download or copy file to
fs: if supplied, use fs instead of automatica... | ac7871adc2784a77246bbe9d1d5ae9c3d8b8443e | 1,176 |
from typing import Dict
from typing import Any
import yaml
def as_yaml(config: Dict[str, Any], **yaml_args: Any) -> str:
"""Use PyYAML library to write YAML file"""
return yaml.dump(config, **yaml_args) | 28c792504d7a6ccd7dbf040d516343e44e072b16 | 1,178 |
def retrieve(filen,start,end):
"""Retrieve a block of text from a file.
Given the name of a file 'filen' and a pair of start and
end line numbers, extract and return the text from the
file.
This uses the linecache module - beware of problems with
consuming too much memory if the cache isn't cleared."""
... | 1ead50be72c542551b2843e8a7fd59b98106f2ce | 1,179 |
def L1_Charbonnier_loss(predict, real):
"""
损失函数
Args:
predict: 预测结果
real: 真实结果
Returns:
损失代价
"""
eps = 1e-6
diff = tf.add(predict, -real)
error = tf.sqrt(diff * diff + eps)
loss = tf.reduce_mean(error)
return loss | 61b0183bf78914dc405290fc89e2ec875b9adfd7 | 1,180 |
def correction_byte_table_h() -> dict[int, int]:
"""Table of the number of correction bytes per block for the correction
level H.
Returns:
dict[int, int]: Dictionary of the form {version: number of correction
bytes}
"""
table = {
1: 17, 2: 28, 3: 22, 4: 16, 5: 22, 6: 28, 7: ... | 982f775172ed0fa148f0d618e4c521fc42e3883e | 1,181 |
def stash_rename(node_id, new_name):
"""Renames a node."""
return stash_invoke('rename', node_id, new_name) | 1fd1dd27bcab8db64e2fb39bf4301a3eb3d48035 | 1,182 |
from datetime import datetime
def get_fake_value(attr): # attr = (name, type, [dim, [dtype]])
""" returns default value for a given attribute based on description.py """
if attr[1] == pq.Quantity or attr[1] == np.ndarray:
size = []
for i in range(int(attr[2])):
size.append(np.rando... | 6a732c90946b58cc7be834193692c36c56bd83fc | 1,183 |
def find_x(old_time,omega,new_time):
"""
Compute x at the beginning of new time array.
"""
interp_omega=spline(old_time,omega)
x=interp_omega(new_time[0])**(2./3)
return x | 450af49dca9c8a66dc0b9a37abddb23afd9a9749 | 1,184 |
import struct
def _platformio_library_impl(ctx):
"""Collects all transitive dependencies and emits the zip output.
Outputs a zip file containing the library in the directory structure expected
by PlatformIO.
Args:
ctx: The Skylark context.
"""
name = ctx.label.name
# Copy the header file to the d... | e048afd34e1228490f879e10bf42105197053bd8 | 1,185 |
def repeat_interleave(x, arg):
"""Use numpy to implement repeat operations"""
return paddle.to_tensor(x.numpy().repeat(arg)) | 9677d48626460241751dde2dfe1ca70d31bab6e2 | 1,186 |
def quantize_arr(arr, min_val=None, max_val=None, dtype=np.uint8):
"""Quantization based on real_value = scale * (quantized_value - zero_point).
"""
if (min_val is None) | (max_val is None):
min_val, max_val = np.min(arr), np.max(arr)
scale, zero_point = choose_quant_params(min_val, max_val, ... | 55f36d84708b32accd7077dc59fa9321f074cd5a | 1,187 |
def EST_NOISE(images):
"""Implementation of EST_NOISE in Chapter 2 of Trucco and Verri."""
num = images.shape[0]
m_e_bar = sum(images)/num
m_sigma = np.sqrt(sum((images - m_e_bar)**2) / (num - 1))
return m_sigma | 8f8d68b25a88cc800b1a6685407072c29c47db7d | 1,188 |
def continue_cad_funcionario(request):
""" Continuação do Cadastro do Funcionário.
"""
usuario = request.user
try:
funcionario = Funcionario.objects.get(usuario=usuario)
except Exception:
raise Http404()
if funcionario and request.method == "POST":
form = FuncionarioForm(... | 626ffeefdeb98f6921b5b76832fd2b622f6d3a26 | 1,189 |
import re
def remove_words(i_list, string):
"""
remove the input list of word from string
i_list: list of words to be removed
string: string on the operation to be performed
"""
regexStr = re.compile(r'\b%s\b' %
r'\b|\b'.join(map(re.escape, i_list)))
o... | 59ac5c2660459f7d2def0d7958a002977a6ca643 | 1,190 |
from datetime import datetime
def save_user_time():
"""
Creates a DateTime object with correct save time
Checks if that save time is now
"""
save_time = datetime.utcnow().replace(hour=18, minute=0, second=0, microsecond=0)
return (save_time == (datetime.utcnow() - timedelta(hours=4))) | 3a16e5de6d912487ca0c46c48d039cf7d44a4991 | 1,191 |
def manage_rating_mails(request, orders_sent=[], template_name="manage/marketing/rating_mails.html"):
"""Displays the manage view for rating mails
"""
return render(request, template_name, {}) | 4afb288233bd4e1fe1b288e6872b522b993ae434 | 1,192 |
from typing import Optional
import time
from datetime import datetime
def cancel(request_url: str,
wait: Optional[bool] = False,
poll_interval: Optional[float] = STANDARD_POLLING_SLEEP_TIME,
verbose: Optional[bool] = False) -> int:
"""
Cancel the request at the given URL.
... | 9f9534c3114c42cfbc08330566244d8981659cdb | 1,193 |
def selected_cases(self):
"""Get a list of all grid cases selected in the project tree
Returns:
A list of :class:`rips.generated.generated_classes.Case`
"""
case_infos = self._project_stub.GetSelectedCases(Empty())
cases = []
for case_info in case_infos.data:
cases.append(self.c... | 27485e7d2244167c0e9766972856f2cb221f8813 | 1,194 |
import requests
import json
def create_whatsapp_group(org, subject):
"""
Creates a Whatsapp group using the subject
"""
result = requests.post(
urljoin(org.engage_url, "v1/groups"),
headers=build_turn_headers(org.engage_token),
data=json.dumps({"subject": subject}),
)
r... | b867046be5623a7e3857ae6ef0069d909db323c1 | 1,195 |
def compute_MVBS_index_binning(ds_Sv, range_sample_num=100, ping_num=100):
"""Compute Mean Volume Backscattering Strength (MVBS)
based on intervals of ``range_sample`` and ping number (``ping_num``) specified in index number.
Output of this function differs from that of ``compute_MVBS``, which computes
... | c5b163ec0f9b2807580c586a3e40ca81d0bcd6cb | 1,196 |
def set_image_exposure_time(exp_time):
"""
Send the command to set the exposure time per frame to SAMI.
Parameters
----------
exp_time (float) : the exposure time in seconds.
Returns
-------
message (string) : DONE if successful.
"""
message = send_command("dhe set obs.exptime ... | c01a12607b6554f29c63229eefe87c1bf81bc7e0 | 1,197 |
def stack_exists(client, stack_name):
""" Checks that stack was specified is existing """
cfn_stacks = client.list_stacks()
for cfn_stack in cfn_stacks["StackSummaries"]:
if cfn_stack['StackName'] == stack_name and "COMPLETE" in cfn_stack['StackStatus'] and "DELETE" not in cfn_stack['StackStatus']:
... | 8e9476b57300cb030ba5292f83060bb5ae652d19 | 1,199 |
def endorsement_services():
"""Return endorsement service list
Loads all defined service modules unless settings specifies otherwise
"""
global ENDORSEMENT_SERVICES
if ENDORSEMENT_SERVICES is None:
ENDORSEMENT_SERVICES = _load_endorsement_services()
return ENDORSEMENT_SERVICES | 543b6c86587a0da58a3e9b8d1756a6d763e60d6a | 1,200 |
def select(arrays, index):
"""
Index each array in a tuple of arrays.
If the arrays tuple contains a ``None``, the entire tuple will be returned
as is.
Parameters
----------
arrays : tuple of arrays
index : array
An array of indices to select from arrays.
Returns
-----... | 70109fbda58055d9712295dff261a95d99caac03 | 1,201 |
def waypoint(waypoint_id):
"""view a book page"""
wp = Waypoint.query.filter_by(id=waypoint_id).first()
options = Option.query.filter_by(sourceWaypoint_id=waypoint_id)
if wp is None:
abort(404)
return render_template('books/waypoint.html', book=wp.book_of, waypoint=wp, options=options) | 520883bdcb29f3e273f7836c4db128c859d9347f | 1,202 |
def encode_big_endian_16(i):
"""Take an int and return big-endian bytes"""
return encode_big_endian_32(i)[-2:] | c26557a6ac30f54746a8a5a1676cec22e3b3b197 | 1,203 |
from typing import List
import requests
from bs4 import BeautifulSoup
import re
def get_comments_from_fawm_page(
url: str,
username: str,
password: str,
) -> List[Response]:
"""Extract comments from a given FAWM page."""
response = requests.get(url, auth=(username, password))
response.encoding... | 68ec542bf909fc543c97836209c2803cd6e0f119 | 1,204 |
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
... | 6bbb3935e596d7d19669f5a0094f58542dd764d3 | 1,205 |
def get_supported_solvers():
"""
Returns a list of solvers supported on this machine.
:return: a list of SolverInterface sub-classes :list[SolverInterface]:
"""
return [sv for sv in builtin_solvers if sv.supported()] | b8fb9e9d780158ab0f45565c05e42fe47ae0d9f2 | 1,206 |
def _length_hint(obj):
"""Returns the length hint of an object."""
try:
return len(obj)
except (AttributeError, TypeError):
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return None
try:
hint = get_hint(obj)
excep... | 226ede41ec49fef4b43df92f425eb7f5135041ea | 1,207 |
def chimeric_data():
"""Example containing spanning + junction reads from single fusion."""
return _build_chimeric_data(
[('1', 300, 1, 'T2onc', 420, 1, 2, '100M2208p38M62S', '62M38S', 'R1'),
('1', 300, 1, 'T2onc', 420, 1, 1, '100M2208p52M48S', '48M52S', 'R2'),
('1', 301, 1, 'T2onc', 4... | 79277d820c0d3e28708d9ead49a55cbe4f51c4e3 | 1,208 |
def _get_merge_for_alias_key(database, key):
"""Return the Alias record of the merged player.
Allow for value.merge on the record with key srkey being any value.
Return the record if value.merge is None True or False.
Otherwise assume value.merge is integer and use it to retreive and
return a recor... | 2384e9db49af07512c86f58b5c9eb964f9e9b1b2 | 1,209 |
def get_bucket(self):
"""
Documentation:
---
Description:
Use bucket name to return a single S3 bucket object.
---
Returns:
bucket : S3 bucket
S3 bucket object
"""
# return
# 6 dictionary containing Name tag / EC2 instance obj... | 0d8ed3c8557e57fb8094524bc4cb4dcae09fe384 | 1,211 |
def euclidean_distance(x, y, weight=None):
"""Computes the Euclidean distance between two time series.
If the time series do not have the same length, an interpolation is performed.
Parameters
----------
x : nd-array
Time series x.
y : nd-array
Time series y.
weight: nd-arr... | 03a1cb557d7d295a6ebd89b0bd1dab937206c8e0 | 1,212 |
def path(artifactory_server, artifactory_auth):
"""ArtifactoryPath with defined server URL and authentication"""
def f(uri):
return artifactory.ArtifactoryPath(
artifactory_server + uri, auth=artifactory_auth
)
return f | 0eabd46b50812ce219affae5ce0d70ee66c7adc5 | 1,213 |
def get_outmost_polygon_boundary(img):
"""
Given a mask image with the mask describes the overlapping region of
two images, get the outmost contour of this region.
"""
mask = get_mask(img)
mask = cv2.dilate(mask, np.ones((2, 2), np.uint8), iterations=2)
cnts, hierarchy = cv2.findContours(
... | 73896a69809259f3bf395895097d1fb81e05706e | 1,214 |
from apex.parallel import DistributedDataParallel as apex_DDP
def check_ddp_wrapped(model: nn.Module) -> bool:
"""
Checks whether model is wrapped with DataParallel/DistributedDataParallel.
"""
parallel_wrappers = nn.DataParallel, nn.parallel.DistributedDataParallel
# Check whether Apex is instal... | e14b0b1c09c088b310574e4a772c7dc3bec83ddf | 1,215 |
def adminRecords(request):
"""
管理租赁记录
:param request:
:return: html page
"""
token = request.COOKIES.get('admintoken')
if token is None:
return redirect('/adminLogin/')
result = MysqlConnector.get_one('YachtClub', 'select adminname from admincookies where token=%s', token)
if... | 75a4d1da4e7556de46a455c1304cc80a5660c9ce | 1,216 |
def _make_fold(draw):
"""
Helper strategy for `test_line_fold` case.
The shape of the content will be the same every time:
a
b
c
But the chars and size of indent, plus trailing whitespace on each line
and number of line breaks will all be fuzzed.
"""
return (
draw... | 1488cafd51b7000ac0fe111b445fcc706876da00 | 1,217 |
import requests
def get_user_jwt() -> str:
"""
Returns:
str: The JWT token of the user
"""
login_data = check_login()
if not login_data:
token = requests.get(
'https://formee-auth.hackersreboot.tech/visitor').json()['token']
return token
if login_data:
... | 1e52921ba88dfefcf320895f98420a73af3f86ee | 1,218 |
def add_gradient_penalty(critic, C_input_gp, C_input_fake):
"""Helper Function: Add gradient penalty to enforce Lipschitz continuity
Interpolates = Real - alpha * ( Fake - Real )
Parameters
----------
critic : tf.Sequential
Critic neural network
C_input_gp : np.matrix
Criti... | e015cc7d5e168293c2dd741c95b38fc8aac4fbc8 | 1,220 |
from datetime import datetime
import pytz
def parse_airomon_datetime(airomon_dt: str) -> datetime:
"""Parse string used by airomon and also make timezone aware."""
aileen_tz = pytz.timezone(settings.TIME_ZONE)
try:
dt: datetime = datetime.strptime(airomon_dt, "%Y-%m-%d %H:%M:%S")
dt = dt.a... | fd91e09ebef4f8af55686d38ef3e763ec546a844 | 1,221 |
import array
def i2nm(i):
"""
Return the n and m orders of the i'th zernike polynomial
========= == == == == == == == == == == == == == == == ===
i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
n-order 0 1 1 2 2 2 3 3 3 3 4 4 4 4 4 ...
m-order 0 -1 1 -2 0 2 -... | 6da858f4cb58a10c480641ce736398d66baf0a7a | 1,222 |
from typing import Dict
from typing import Any
def update_ftov_msgs(
ftov_msgs: jnp.ndarray, updates: Dict[Any, jnp.ndarray], fg_state: FactorGraphState
) -> jnp.ndarray:
"""Function to update ftov_msgs.
Args:
ftov_msgs: A flat jnp array containing ftov_msgs.
updates: A dictionary contain... | f54150e5f310905e37820e225e8d29ab6d9e9717 | 1,223 |
from typing import Optional
def normalize_features(
current: np.ndarray,
previous: Optional[np.ndarray],
normalize_samples: int,
method: str = NORM_METHODS.MEAN.value,
clip: bool = False,
) -> tuple[np.ndarray, np.ndarray]:
"""Normalize features with respect to the past number of normalize_sam... | 8b18f12272eb92ae60631b0c4dcdb138a5596d44 | 1,224 |
def anim(filename, rows: int, cols: int ,
frame_duration: float = 0.1, loop=True) -> Animation:
"""Create Animation object from image of regularly arranged subimages.
+filename+ Name of file in resource directory of image of subimages
regularly arranged over +rows+ rows and +cols+ column... | 2ced01a961d05e6968c14023a935623bc2011069 | 1,225 |
def filter_factory(global_conf, **local_conf):
"""Standard filter factory to use the middleware with paste.deploy"""
register_swift_info('vertigo')
conf = global_conf.copy()
conf.update(local_conf)
vertigo_conf = dict()
vertigo_conf['devices'] = conf.get('devices', '/srv/node')
vertigo_co... | ca9c72f2237cfb2054ffc2b38038c75c96679ade | 1,226 |
import statistics
def get_review_score_fields(call, proposals):
"""Return a dictionary of the score banner fields in the reviews.
Compute the score means and stdevs. If there are more than two score
fields, then also compute the mean of the means and the stdev of the means.
This is done over all final... | bda5899a105942a456872d0bacadaf124832cd65 | 1,227 |
def tokenize(text):
"""
Tokenize and normalize
"""
tokens = nltk.word_tokenize(text)
lemmatizer = nltk.WordNetLemmatizer()
clean_tokens = [lemmatizer.lemmatize(w).lower().strip() for w in tokens]
return clean_tokens | 2485181433208ee871e881312400806539d5bc73 | 1,228 |
def _makeSSDF(row, minEvents):
"""
Function to change form of TRDF for subpace creation
"""
index = range(len(row.Clust))
columns = [x for x in row.index if x != 'Clust']
DF = pd.DataFrame(index=index, columns=columns)
DF['Name'] = ['SS%d' % x for x in range(len(DF))] # name subspaces
#... | 77fb59b0e385d51d06fac1ff64ba12331d514d1d | 1,229 |
def concatenate_constraints(original_set, additional_set):
"""
Method for concatenating sets of linear constraints.
original_set and additional_set are both tuples of
for (C, b, n_eq). Output is a concatenated tuple of
same form.
All equality constraints are always kept on top.
"""
C... | 6b0cc1c75d00ae7b3737638c45a21bc8c609ddb1 | 1,230 |
import signal
def _isDefaultHandler():
"""
Determine whether the I{SIGCHLD} handler is the default or not.
"""
return signal.getsignal(signal.SIGCHLD) == signal.SIG_DFL | 10b814bba12c04cbc6fec08c7783581876f56b6b | 1,231 |
import scipy
def downsampling(conversion_rate,data,fs):
"""
ダウンサンプリングを行う.
入力として,変換レートとデータとサンプリング周波数.
アップサンプリング後のデータとサンプリング周波数を返す.
"""
# 間引くサンプル数を決める
decimationSampleNum = conversion_rate-1
# FIRフィルタの用意をする
nyqF = (fs/conversion_rate)/2.0 # 変換後のナイキスト周波数
cF = (fs/conv... | add6768d32cc7675eaecf1e37c5d901f1244702a | 1,232 |
from typing import Union
def get_client_cache_key(
request_or_attempt: Union[HttpRequest, AccessBase], credentials: dict = None
) -> str:
"""
Build cache key name from request or AccessAttempt object.
:param request_or_attempt: HttpRequest or AccessAttempt object
:param credentials: credentials c... | 8d9a128b326a8ab7c320f73f49a313f30d6cd268 | 1,233 |
def loadMaterials(matFile):
"""
Loads materials into Tom's code from external file of all applicable materials.
These are returned as a dictionary.
"""
mats = {}
name, no, ne, lto, lte, mtype = np.loadtxt(matFile, dtype=np.str, unpack=True)
no = np.array(list(map(np.float, no)))
... | 650b04a27741777e5e344696e123d4fd669a5b28 | 1,234 |
def prepend_with_baseurl(files, base_url):
"""prepend url to beginning of each file
Parameters
------
files (list): list of files
base_url (str): base url
Returns
------
list: a list of files with base url pre-pended
"""
return [base_url + file for file in files] | 4c29b3e9230239c1ff8856c707253608ce2503cd | 1,235 |
def _loc(df, start, stop, include_right_boundary=True):
"""
>>> df = pd.DataFrame({'x': [10, 20, 30, 40, 50]}, index=[1, 2, 2, 3, 4])
>>> _loc(df, 2, None)
x
2 20
2 30
3 40
4 50
>>> _loc(df, 1, 3)
x
1 10
2 20
2 30
3 40
>>> _loc(df, 1, 3, inclu... | 1cc3c2b507ed18d18659fb097765ab450972c05a | 1,237 |
def compare_system_and_attributes_faulty_systems(self):
"""compare systems and associated attributes"""
# compare - systems / attributes
self.assertTrue(System.objects.filter(system_name='system_csv_31_001').exists())
self.assertTrue(System.objects.filter(system_name='system_csv_31_003').exists())
... | 459b853eba3a2705450ac9a33fe14844940bf4c8 | 1,238 |
def get_regions(contig,enzymes):
"""return loci with start and end locations"""
out_sites = []
enz_1 = [enz for enz in Restriction.AllEnzymes if "%s"%enz == enzymes[0]][0]
enz_2 = [enz for enz in Restriction.AllEnzymes if "%s"%enz == enzymes[1]][0]
enz_1_sites = enz_1.search(contig.seq)
enz_2_si... | b34cab04e0b790b01418555c74c4d810b7184e47 | 1,239 |
def getHighContrast(j17, j18, d17, d18):
"""
contrast enhancement through stacking
"""
summer = j17 + j18
summer = summer / np.amax(summer)
winter = d17 + d18
winter = winter / np.amax(winter)
diff = winter * summer
return diff | cd462aac5c0568f84d64f3020718ec601063044f | 1,240 |
def get_bounding_box(dataframe, dataIdentifier):
"""Returns the rectangle in a format (min_lat, max_lat, min_lon, max_lon)
which bounds all the points of the ´dataframe´.
Parameters
----------
dataframe : pandas.DataFrame
the dataframe with the data
dataIdentifier : DataIdentifier
... | 6989118af8db36cc38fd670f5cd7506859d2150e | 1,241 |
def get_file_download_response(dbfile):
"""
Create the HttpResponse for serving a file.
The file is not read our output - instead, by setting `X-Accel-Redirect`-
header, the web server (nginx) directly serves the file.
"""
mimetype = dbfile.mimeType
response = HttpResponse(content_type=mim... | 93f7e57daaec6a11e5241682ba976e8d68a91acf | 1,242 |
import time
def keyWait():
"""Waits until the user presses a key.
Then returns a L{KeyDown} event.
Key events will repeat if held down.
A click to close the window will be converted into an Alt+F4 KeyDown event.
@rtype: L{KeyDown}
"""
while 1:
for event in get():
... | 60ee6ad29c215585aef03237a23f15581deb8f5e | 1,243 |
from datetime import datetime
def create_comentarios_instancia(id_instancia):
"""
@retorna un ok en caso de que se halla ejecutado la operacion
@except status 500 en caso de presentar algun error
"""
if request.method == 'POST':
try:
values = json.loads( request.data.decode('8859') )
mensaje = va... | 58a49f4c76976bf0a13f07f6e6de73f358f34e4a | 1,244 |
async def osfrog(msg, mobj):
"""
Patch 7.02: help string was removed from Captain's Mode
"""
osfrogs = [
"Added Monkey King to the game",
"Reduced Lone Druid's respawn talent -50s to -40s",
]
return await client.send_message(mobj.channel, choice(osfrogs)) | f1b5907cad42d7e6d6021e447ab8cd6dd91429e5 | 1,246 |
def _add_normalizing_vector_point(mesh, minpt, maxpt):
"""
This function allows you to visualize all meshes in their size relative to each other
It is a quick simple hack: by adding 2 vector points at the same x coordinates at the
extreme left and extreme right of the largest .stl mesh, all the meshes a... | a60e1f0dd4bc6c60e40096cb4412b47a5a3d139a | 1,247 |
import numpy
def radii_ratio(collection):
"""
The Flaherty & Crumplin (1992) index, OS_3 in Altman (1998).
The ratio of the radius of the equi-areal circle to the radius of the MBC
"""
ga = _cast(collection)
r_eac = numpy.sqrt(pygeos.area(ga) / numpy.pi)
r_mbc = pygeos.minimum_bounding_ra... | 16008df64f999b615f855e92f727638813434e98 | 1,248 |
from datetime import datetime
def create_jwt(project_id, private_key_file, algorithm):
"""Create a JWT (https://jwt.io) to establish an MQTT connection."""
token = {
'iat': datetime.datetime.utcnow(),
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
'aud': project_id... | e365cc67a3587a64b38276ce95e8e0c389e54314 | 1,249 |
def games(engine1, engine2, number_of_games):
"""Let engine1 and engine2 play several games against each other.
Each begin every second game."""
engine1_wins = 0
engine2_wins = 0
draws = 0
for n in range(number_of_games):
if n % 2:
result = game(engine1, engine2, True)
... | f520a08214d1ad063f747b01582b2dbfc94d5d9e | 1,250 |
def tissue2line(data, line=None):
"""tissue2line
Project tissue probability maps to the line by calculating the probability of each tissue type in each voxel of the 16x720 beam and then average these to get a 1x720 line. Discrete tissues are assigned by means of the highest probability of a particular tissue t... | 3966f789e1093e11e4b31deda0f7d43f753007b0 | 1,251 |
def get_version(pyngrok_config=None):
"""
Get a tuple with the ``ngrok`` and ``pyngrok`` versions.
:param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
overriding :func:`~pyngrok.conf.get_default()`.
:type pyngrok_config: PyngrokConfig, optional
... | 256216926a6c91a8000f8b823202cde576af3a67 | 1,252 |
def stat_cleaner(stat: str) -> int:
"""Cleans and converts single stat.
Used for the tweets, followers, following, and likes count sections.
Args:
stat: Stat to be cleaned.
Returns:
A stat with commas removed and converted to int.
"""
return int(stat.replace(",", "")) | cb6b6035ab21871ca5c00d5d39d9efe87e0acc89 | 1,253 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.