content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def parse_reply(param, reply):
"""
Returns a list of (value, cf) pairs for the Parameter param from a text
reply. Expected a single value (with an implicit CF of true) or a list of
value/cf pairs val1 cf1, val2 cf2, ....
"""
if reply.find(',') >= 0:
vals = []
for pair in reply.s... | df1f961075ab5e86b25012b1a950ad66892e2dc4 | 3,607,912 |
def agg_drug_data(file_path,file_name):
"""Create and write to disk a .csv file of aggregated drug data rows.
Args:
file_path: Path to csv file of drug data.
file_name: Name of the drug data file.
"""
# Read drug data frame
drug_df = pd.read_csv(r"{}\{}.csv".format(file_path,file_na... | f01db2e46d30e5102c44ddef03136409e44d5baa | 3,607,913 |
def view_queries():
"""Render the query catalog."""
queries = manager.list_queries()
return render_template(
'query/queries.html',
queries=queries,
manager=manager,
) | 4c06efb055fcfb9647c28a148f637373c4fcd0d9 | 3,607,914 |
def get_model_ref(data, name_weights):
"""
Returns model reference if found by model name and model weights pair. Returns None otherwise.
data - list of tuples (model_name, model_weights_path, model_ref)
"""
for x in data:
if name_weights == x[:2]:
return x[2]
return None | 8525d77c018ec696619161afb3fbb0342ff46a27 | 3,607,915 |
def make_serie(results, criteria, lang, is_time=False):
"""Create a serie for Flot from request"""
return {'label': labelize(criteria, lang),
'data': [(visit.key, visit.count)
for visit in results]} | 33101b0824dfa4979fdb1479d3f1f0ab23b72d80 | 3,607,916 |
def _bootstrap_sample(vel_data, v_table, samples, error):
"""Generate a Monte Carlo error sample of the differential distribution."""
# Generate some Monte Carlo samples where each element is perturbed by
# a Gaussian, sigma given by error.
index = np.random.random_integers(0, np.size(vel_data)-1, sampl... | eea62f2db0b4ed82f63324dab1add28459b3f90d | 3,607,917 |
def parse_punishment(argument):
"""Converts a punishment name to its code"""
punishments = {
"none": 0,
"note": 1,
"warn": 1,
"mute": 2,
"kick": 3,
"ban": 4
}
return punishments[argument.lower()] | 9ca9ad052c5636dd58f1b375296137de8b55712b | 3,607,918 |
def polygon_iou(list1, list2):
"""
Intersection over union between two shapely polygons.
"""
polygon_points1 = np.array(list1).reshape(4, 2)
poly1 = Polygon(polygon_points1).convex_hull
polygon_points2 = np.array(list2).reshape(4, 2)
poly2 = Polygon(polygon_points2).convex_hull
union_pol... | f3a84b480fc999d9a08db21148621320f1050e5a | 3,607,919 |
import re
def varnames2matlab(name, tmodel):
"""
Transforms reaction variable pairs from `('ACALD','ACALD_reverse_xxxxx')` to
`('F_ACALD','B_ACALD')` if it is a reaction, else leaves is as is
:return:
"""
reverse_regex = re.compile(r'(.+_reverse)_[a-f0-9]{5}')
new_name = name
if ... | d7dbf917b6d84d41fc825e912cd8817a22d02eba | 3,607,920 |
def get_total_fish(days):
"""
Returns a list of 7 elements containing the number of fish
that would be present after "days" days
"""
countdowns = {
0: 1,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 0,
8: 0,
}
fish_count = []... | ac2bb8d317ee6b9a7077429e55d0f2bf26f99ad2 | 3,607,921 |
from pathlib import Path
def _preconvert(item):
"""Preconverts objects from native types into JSONifyiable types"""
if isinstance(item, (set, frozenset)):
return list(item)
if isinstance(item, WrapModes):
return item.name
if isinstance(item, Path):
return str(item)
if calla... | 7ad7004f7b15de226fca14ae7f609bc04d920b94 | 3,607,922 |
def build_icon_from_cmap(cmap, width=24, height=24):
"""
Builds an icon representing the colormap
"""
data = zeros((width, height), uint8)
line = linspace(0, 255, width)
data[:, :] = line[:, newaxis]
img = toQImage(data)
img.setColorTable(cmap.colorTable(FULLRANGE))
return QIcon(QPix... | c3c33c143e6a6d75b836696c2fdba300556028e7 | 3,607,923 |
import socket
def http_proxy_connect(address, proxy, auth=None):
"""
Establish a socket connection through an HTTP proxy.
Arguments:
address (required) = The address of the target
proxy (required) = The address of the proxy server
auth (def: None) = A tuple of the userna... | f77b21647cf8141bc957c9e73ba847e5b0d9e3ee | 3,607,924 |
def lookup_wn(pos_tags, num_synsets):
"""Looks up the tokens on WordNet and annotates it with the first result
that is found. Returns a list of tuples with the word and the WordNet result."""
# To-do: incorporate named entities as fixed WordNet results, for
# example Celestial-Seasonings (organization) ... | 685367780d89bf043ba271036761602f904014be | 3,607,925 |
import configparser
def get_api_config(filename):
"""
Attempt to pull in twitter app API key and secret. If the key
and secret don't exist prompt for them.
Arguments:
filename -- name of the config file to try and parse
Returns:
config_api_store -- contains the twitter API key and s... | 8723e77f2cc30b9f102d141dd46b66a147ee67ef | 3,607,926 |
def make_sequences(texts, training_length = 50,
lower = True, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n'):
"""Turn a set of texts into sequences of integers"""
# Create the tokenizer object and train on texts
tokenizer = Tokenizer(lower=lower, filters=filters)
tokenizer.fit_o... | ac95162b90c7f6d8cafe3599b1a7ac2b78273ad1 | 3,607,927 |
import requests
def read_unit_test_coverage(ci_jobs, repository):
"""Read and process unit test coverage."""
log.info("Reading unit test coverage")
url = ci_jobs.get_console_output_url(repository)
report_type = None
if url is not None:
response = requests.get(url)
if response.statu... | bbbc1dd004d27bdf80a72ba51eacce8597ed6058 | 3,607,929 |
def fetch(fp, path):
"""Fetches an array from hdf5 file.
:param str fp: hdf5 file path.
:param str path: path inside the hdf5 file.
:returns: An :class:`numpy.ndarray` representation of the corresponding hdf5 dataset.
"""
with h5py.File(fp, 'r') as f:
return f[path][:] | 563c20b1d63b28b6594586b3e3b16b1e47ac8ad8 | 3,607,930 |
def infix_to_postfix(infix_str):
"""Convert Infix to Postfix notation."""
infix_list = infix_str.split()
opstack = Stack()
postfix_list = []
for token in infix_list:
if is_operand(token):
postfix_list.append(token)
elif token == '(':
opstack.push('(')
... | dfe99e0f4897fd67efb66524ae7872f85ce926bd | 3,607,931 |
from typing import Any
from typing import Dict
import enum
def to_dictionary(obj: Any) -> Dict[str, Any]:
"""Creates a dictionary representation of a class instance. The
keys are taken from the API description and may differ from language
specific variable names of properties.
Args:
obj: The ... | b95bfe624899ebfce8db78ef30298f52220a8a29 | 3,607,932 |
from typing import Dict
from typing import Set
def reverse_graph(graph: Dict[ArrayOrNames, Set[ArrayOrNames]]) \
-> Dict[ArrayOrNames, Set[ArrayOrNames]]:
"""Reverses a graph.
:param graph: A :class:`dict` representation of a directed graph, mapping each
node to other nodes to which it is con... | 543d634adcea4557c3c95d5e9bdb08250977a4ac | 3,607,933 |
def get_event_series_upload_path(series, filename):
"""Create upload path for an event series by primary key.
Required by model FileField/ImageField.
Args:
component (Series): Series object file is being added to.
filename (str): Filename of file.
Returns:
String of path and f... | b16996db081a1b3b1768e703fa916daee14c911c | 3,607,935 |
def stack_v3(x,
filters,
blocks,
bottleneck=False,
stride1=2,
expansion=4,
activation='leaky_relu',
bn_sync=BN_SYNC,
name=None):
"""A set of stacked residual blocks.
Arguments:
x: input tensor.
filters: integer, filters of the bottleneck layer in a block.... | bf037fd701f61168014163a57e47f03d56244aa6 | 3,607,937 |
from typing import Set
def dbc_dist(dbc_a: Openable, dbc_b: Openable) -> float:
"""
Calculate the "distance" between two DBC files, used for performance measuring. Compares only those
properties which physically influence the data on the wire, like signal bit position and size. Purely
semantic propert... | c1aa83219d16475670e0892dd49ca9bfa4459f7d | 3,607,939 |
def build_graph(x_placeholder, vocab_size, embedding_size, dropout_placeholder, sequence_length, filter_sizes,
num_filters, initW, pretrained=False, multichannel=False):
""" Build the computational graph for forward and backward propagation """
# Keeping track of l2 regularization loss
l2_l... | 1d48fef4d626f47bf92f855964d8e712c7015929 | 3,607,940 |
def get_sub_dataframe(data_df, boundaries_gdf, date_start, date_end, bin_sizes):
""" Returns count data inside the new york boroughs. """
df = data_df.copy()
#get data related only to PD_DESC_FILTER
if PD_DESC_FILTER is not None:
df = df[df['PD_DESC'] == PD_DESC_FILTER].copy()
#ge... | 5db6b1898c9e9dc190e2d8fb665e2e395fd87a0e | 3,607,941 |
def minspantree_helper(matrix, start_node, priority_queue, final_tree):
"""recursive helper function for question3()
inputs: adjacency dictionary, value of start node, priority queue, and final adjacency dict
output: final adjacency dict"""
# iterate through edges of start node
for tup in matrix[sta... | 9f0b56d7f2e60c269744ef265e531154cc87600a | 3,607,942 |
from typing import Optional
import tqdm
from datetime import datetime
from typing import Dict
from typing import Any
def describe(
config: Settings,
df: pd.DataFrame,
summarizer: BaseSummarizer,
typeset: VisionsTypeset,
sample: Optional[dict] = None,
) -> dict:
"""Calculate the statistics for ... | 4a1fee12d1946d7994a19937580d978afbc92e26 | 3,607,943 |
def square_root_with_type_annotations(x: float) -> float:
"""Computes the square root of x, using the Newton-Raphson method"""
return square_root(x) | 1facc3c44e00ba2ae71b43e478e4d4a7936ed46d | 3,607,944 |
def labrad_hdf5_get_parameters(dir_path, file_num, file_name):
"""
Get parameter settings from a labrad hdf5 file
Parameters
----------
dir_path : string
Usually this is "vault" directory
file_num : int
hdf5 file number. ex. '00033 - measurement_name.hdf5'
file_name : st... | 7b77073fdac63fd6e5d506d93566418d28a5dba7 | 3,607,945 |
def get_blue():
""" create a blue (friendly) actor """
# return name of actor, grazing speed, self defense
return 'Boar', 2 | d0776c362ff841dfdd635f089d6dac0c81d13993 | 3,607,946 |
def make_data_row(url, item_name, scrape_datetime, soup_result_item):
""" Returns dictionary """
# Dates and times
scrape_date = scrape_datetime.date().isoformat()
scrape_weekday = scrape_datetime.strftime('%A')
scrape_time = scrape_datetime.time().isoformat()
# Price data
product_size = so... | 356c76bd3c6b86b711c9964f2fe14b629942b3c2 | 3,607,947 |
def freq_to_wavenumber(freq, units_in='Hz', return_quantity=False,
units_out='cm-1'):
"""Converts frequency to wavenumber
Parameters
----------
freq : float
Frequency
units_in : str, optional
Units corresponding to ``freq``. Default is 'Hz'.
... | 2be9a318a63da98c9f3d0810d78d0f275cd5a721 | 3,607,948 |
def document_vector_gensim(doc):
"""Create document vectors by averaging word vectors. Remove out-of-vocabulary words."""
vocab_doc = [word for word in doc if word in gensim_vocab]
if len(vocab_doc) != 0:
return list(np.mean(gensim_embeddings.wv[vocab_doc], axis=0))
else:
retur... | 00274a8a7940c8e25821fd06013484a8a6568641 | 3,607,949 |
def const(a, b):
"""``const :: a -> b -> a``
Constant function.
"""
return a | 1b3e03d98ab495d1795d3e89d0a57728b1dcef47 | 3,607,950 |
def compute_wealth_moments(scf, bin_weights):
"""
This function computes moments (wealth shares, Gini coefficient,
var[ln(wealth)]) from the distribution of wealth using SCF data.
Args:
scf (Pandas DataFrame): pooled cross-sectional data from SCFs
bin_weights (Numpy Array) = ability wei... | 02b25221638b88ff8e63e1ad7d6eea05cd264d45 | 3,607,951 |
def photon_path(tau_max):
"""
This function tracks the path of photon exiting the core.
uncomment to get the mu and number of scattering.
"""
tau, mu = emit_photon(tau_max)
numOfScattered = 0
while tau >= 0:
tau, mu = scatter_photon(tau)
if tau > tau_max:
tau, mu ... | a7a994f718cfa8ea8d17081b56e144d32bbfd6d9 | 3,607,952 |
def make_issuing(vasp, idx):
"""
Populate variable fields in a certificate issued record
uses `fixtures/datagen/templates/no_cert.json` as template
"""
return make_unverified(vasp, idx, state="ISSUING_CERTIFICATE") | f42d4a9e58d629e4e40e571fe90f2451a86d6a2d | 3,607,953 |
def add_tages_ratio(uid, userid_grouped, flag):
""" 添加 tags 的比率 """
if flag == 0:
return -1
df = userid_grouped[uid]
if df.shape[0] == 0:
return -1
else:
return 1.0 * df[df['tags'] == ['None']].shape[0] / df.shape[0] | 2ea37f3ddc16654eb1a840ae4327e5acde8cbe39 | 3,607,954 |
def block3(x, filters, kernel_size=3, stride=1, groups=32, conv_shortcut=True, name=None):
"""A residual block.
Arguments:
x: input tensor.
filters: integer, filters of the bottleneck layer.
kernel_size: default 3, kernel size of the bottleneck layer.
stride: default 1, stride of the fi... | 214fa4bc19e6df639fe616f5c5f246d2cc1e5cfa | 3,607,955 |
import functools
def returns(*accepted_return_type_tuple):
"""
Validates the return type. Since there's only ever one
return type, this makes life simpler. Along with the
accepts() decorator, this also only does a check for
the top argument. For example you couldn't check
(<type 'tuple'>, <typ... | 16db31084cb284c45206580eba4f849017bb4ba0 | 3,607,956 |
import requests
def data_timestamp() -> pd.Timestamp:
"""Return the timestamp of the last commit to the .csv-file."""
r = requests.get(
r"https://api.github.com/repos/CSSEGISandData/COVID-19/commits",
params={
"path": r"csse_covid_19_data/csse_covid_19_time_series"
r"/t... | c36e6a69c152aefe70cb878660e9f6f7494713d0 | 3,607,957 |
import torch
def sharpness(predictions:list, total = True):
"""
Calculate the mean size of the intervals, called the sharpness (lower the better)
Parameters
----------
predictions : list
- predictions[0] = y_pred_upper, predicted upper limit of the target variable (torch.Tensor)
-... | 16c4fa826e9ffd4a42a3c987fc9fe6767feb9ebb | 3,607,958 |
def pause_scaling_group(request, log, tenantId, groupId):
"""
Pause a scaling group. This means that no scaling policies will get
executed (execution will be rejected). This is an idempotent operation -
pausing an already paused group does nothing.
"""
group = get_store().get_scaling_group(log... | 2d2299b7e8b3088252ee04768b90828367083f69 | 3,607,959 |
import json
import uuid
def new_annotation(request, document_id):
"""Adds a annotation, queried by document id.
Edits the text pack of a document, queried by id.
The function is accessible for users with 'edit_annotation' permission of the project and the owner of the project.
Args:
docum... | 6e34a6be660bf2b601bff150779e92b4aa57ee57 | 3,607,961 |
def get_conf_file():
"""Return the path to the conf file."""
return get_option("config") or get_conf_file_path() | 1de81ad59d64472bd4b685b8471c773af4aa99e0 | 3,607,962 |
import numpy
def parse_endl_covariance(covFile):
"""
Returns a list of (energy bins, covariance matrix, covariance_type, [enminmax]) tuples.
The list may be empty (some ENDL cov.xml files are empty).
"""
xdoc = cElementTree.parse(covFile)
root = xdoc.getroot()
ebins, covariances, covaria... | 53823296d82712b091681eda69b0f9bce498df10 | 3,607,963 |
def unique(new_cmp_dict, old_cmp_dict):
"""Return a list dict of
the unique keys in new_cmp_dict
"""
newkeys = set(new_cmp_dict)
oldkeys = set(old_cmp_dict)
unique = newkeys - oldkeys
unique_ldict = []
for key in unique:
unique_ldict.append(new_cmp_dict[key])
return unique... | d67d356185b44718e3be788e37340b97a29df352 | 3,607,964 |
import click
def common_gateway_options(func):
"""Supply common gateway options."""
func = click.option(
"-v",
"--protocol_version",
help="Protocol version of the gateway.",
default="2.2",
show_default=True,
)(func)
func = click.option(
"-s", "--persiste... | 7611356364201f357623a873f8e35a37cbf4ff9a | 3,607,965 |
from typing import Iterable
def klasify(sers: Iterable, klases: Iterable, args: Iterable=None):
"""
Convert each qb64 serialization ser in sers to instance of corresponding
klas in klases modified by corresponding arg in args.
Useful for converting iterable of CESR serializations to associated iterab... | 7fead9f6965f4ea24e08f734c529eb04b84d038e | 3,607,966 |
def render(template_name, **kwargs):
"""Функция рендеринга шаблонов"""
template = jinja_env.get_template(template_name)
return template.render(**kwargs) | df812e7857cfb79020cdca0a47b231c4e322f692 | 3,607,967 |
import asyncio
async def _createServer(host, port):
"""
Create async server that listens host:port, reads client request and puts
value to some future that can be used then for checks
:return: reference to server and future for request
"""
indicator = asyncio.Future()
async def _handle(r... | bbd21ede887ae93ba8127aa1bb0a9ff4264b8399 | 3,607,968 |
def interval(*intervals):
"""Decorate a function to be called by the bot every *n* seconds.
:param int intervals: one or more duration(s), in seconds
This decorator can be used multiple times for multiple intervals, or
multiple intervals can be given in multiple arguments. The first time the
funct... | 4d580cea0853228896c8dec2308a243376c56770 | 3,607,969 |
import re
def generate_ignore_character():
"""
生成删除无效字符的pattern和dict
:return:
"""
translate_list = const.USELESS_STRING_LIST
translate_dict = {items: '' for items in translate_list}
translate_dict = dict((re.escape(key), value) for key, value in translate_dict.items())
pattern = re.com... | d2d50f71ea22b4f7b397c0c87248ef540207ee2d | 3,607,970 |
def _exclude_swift_incompatible_define(define):
"""A `map_each` helper that excludes a define if it is not Swift-compatible.
This function rejects any defines that are not of the form `FOO=1` or `FOO`.
Note that in C-family languages, the option `-DFOO` is equivalent to
`-DFOO=1` so we must preserve bo... | 9ce87f52f8829636364e2671f59a0eb9e66f5a9b | 3,607,973 |
def get_user_url(username: str) -> str:
"""Get user page's URL.
"""
return f"{PREFIX}user/{username}" | 79e0d5220e6106d81e619a40bee0fc6682f2d064 | 3,607,974 |
def get_expected_data_from_company_referral(referral):
"""Returns company referral data as a dictionary"""
return {
'company_id': str(referral.company_id),
'completed_by_id': get_attr_or_none(referral, 'completed_by_id'),
'completed_on': format_date_or_datetime(referral.completed_on),
... | a8398a62c8042f87775cb767ef0a730dd37ce3f5 | 3,607,975 |
def get_prediction(id_, url=DEFAULT_URL):
"""
Get the predictions for a specific submission.
Parameters
----------
id_ : int
The id of the submission.
url : str
The url of the running Flask app.
Returns
-------
prediction : pd.DataFrame
"""
return pd.read_cs... | c2edf224a047b3c9f655b0f6b86fc089c86e9d0f | 3,607,976 |
def commands_almost_equal(command1: str, command2: str, delta: float = 1.0) -> bool:
"""Check if two commands are almost equal.
Almost equal means we allow numerical parts in the commands to differ by the defined delta.
Args:
command1 (str): first command.
command2 (str): s... | 4d75afadb2b6db5911a227d205c81f4cbfdc7f01 | 3,607,977 |
import re
def hex_color_code(value: str):
"""
Hex color validator
Example Result:
[#00ff00,
#fff]
"""
_hex_color_pat = r'#(?:[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})'
return re.findall(_hex_color_pat, value) | 760db0bd1b729b62171b6964d1615546e32dbe52 | 3,607,978 |
def get_charge_composition(charge):
"""Return the composition of a given charge (only H+).
Parameters
----------
charge : int
Peptide charge.
Returns
-------
pyteomics.mass.Composition
Composition of the change (H+).
"""
charge_composition = mass.Composition()
... | d76483b5ca43b25f50d6d779bf772a4fb2f2019c | 3,607,979 |
def parse_value(type, val):
"""
Parses a given OBD value of a given type (PID)
and returns the parsed value.
If the PID is unknown / not implemented a PIDParserUnknownError
will be raised including the type which was unknown
:param type:
:param val:
:return:
"""
if type in PARSER... | 2933b8125a4e2a67cd6089583712e42d0fe37361 | 3,607,980 |
import re
import logging
def parse(fqdn):
"""Parses an M-Lab FQDN into its constituent parts.
Args:
fqdn: str, an M-Lab FQDN e.g., ndt-iupui-mlab1-den05.mlab-oti.measurement-lab.org
Returns:
dict representing the constituent parts.
"""
# This regex *should* match all valid M-Lab ... | a05a7125b1818668dc681be460a326c2a5a2f065 | 3,607,981 |
def buffer_type(request):
"""
Fixture that yields types that support the buffer protocol.
"""
return request.param | afc79bf3ac5bfeb53fe9cb8de707b2f0a93ae6f8 | 3,607,982 |
def minargmin(sequence):
"""Returns the minimum value and the first index at which it can be
found in the input sequence."""
best = (None, None)
for (i, value) in enumerate(sequence):
if best[0] is None or value < best[0]:
best = (value, i)
return best | cf66ccd0dc76d3530fe7b2503bb3ed3b31c7ba61 | 3,607,983 |
import torch
def test(epoch, test_loader_mnist):
"""
Network evaluation, testing stage
"""
net.eval()
test_accuracy = 0
test_loss = 0
with torch.no_grad():
for idx, (img, target) in enumerate(test_loader_mnist):
output, _, _ = net(img)
loss = criterion(outpu... | 30f1c64505b13897ea05420d4db6722cfa2a2d96 | 3,607,984 |
def silent_preload(silent_file_path):
"""
Returns index,out
"""
# sfd = pyrosetta.rosetta.core.io.silent.SilentFileData(
# pyrosetta.rosetta.core.io.silent.SilentFileOptions()
# )
# sfd.read_file(silent_file_path)
silent_index = silent_tools.get_silent_index(silent_file_path)
s... | 0d7ca76ed3c8ad87e2f7b718abe6a8169002e8d5 | 3,607,985 |
def django_id_to_cloudsearch(s):
""" convert haystack ids to legal cloudsearch index field names """
return s.replace('.', '__') | e70a5961b5189b1177b5ba2adeac3287ca2fc091 | 3,607,986 |
import time
def validate_address(addr_spec, metrics=False):
"""
Given an addr-spec, runs the pre-parser, the parser, DNS MX checks,
MX existence checks, and if available, ESP specific grammar for the
local part.
In the case of a valid address returns an EmailAddress object, otherwise
returns ... | 4f762d7658261a5b514331bf79b7c4c8c009510d | 3,607,987 |
import signal
def input_to(getch, timeout=0.3):
"""Taking input from user."""
signal.signal(signal.SIGALRM, alarmHandler)
signal.setitimer(signal.ITIMER_REAL, timeout)
try:
text = getch()
signal.alarm(0)
return text
except AlarmException:
signal.signal(signal.SIGALR... | 823e27adec266d81f5f1760faea7f110c02e05a5 | 3,607,988 |
def get_data(self):
"""Generate the toothsaw vector
Parameters
----------
self : ImportGenToothSaw
An ImportGenToothSaw object
Returns
-------
vect: ndarray
The generated toothsaw vector
"""
time = linspace(start=0, stop=self.Tf, num=self.N, endpoint=False)
T... | aaaa6a58b5f383c5e20bce3b8a9f86c3bb23589e | 3,607,989 |
def _is_eqsine(opts):
"""
Checks to see if 'eqsine' option is set to true
Parameters
----------
opts : dict
Dictionary of :func:`pyyeti.srs.srs` options; can be empty.
Returns
-------
flag : bool
True if the eqsine option is set to true.
"""
if "eqsine" in opts:... | 3515a75eb2c0976198700e1fe068cd15b0017d8f | 3,607,990 |
from typing import Union
from datetime import datetime
def dividends(date: Union[str, datetime.date, None] = None, filter: str = ''):
"""
This call details upcoming dividend information and other corporate actions, such as stock splits, for IEX-listed
securities.
Records are added once known by the E... | 489f8a2b4904ae2e92ebcf8386769e0353f58f28 | 3,607,991 |
from cla_frontend.apps.status.tests.smoketests import SmokeTests
def smoketests_json(request):
"""
Run smoke tests and return results as JSON datastructure
"""
return JsonResponse(smoketest(SmokeTests)) | 72ba96fa2538cf60ce59ca6c067ea78eb558dbc0 | 3,607,992 |
def request_preemptible_resource_with_priority_in_parallel(preemptible_resource_port, priority_expr, stream_port):
"""Request for or preempt the resource in case of need with the given priority in parallel without delaying the current stream of data.
The less priority is higher. The priority must be specifi... | 4df26ccdcc79b1b0f913677cd84a1e5e9a1af3ab | 3,607,993 |
def get_title(unique_reasons, top_n_worst):
"""generate the report title"""
title_end = ""
if unique_reasons:
title_end = "uniquely bad"
else:
title_end = "worst"
title = "top %i %s" % (top_n_worst, title_end)
underline = util.write_underline(title)
return "%s\n%s\n" % (title... | 6e78fe2eeadd75421092f36c257bb79d3f93f2cd | 3,607,994 |
from typing import Callable
from typing import List
def generate_definition(cls: Callable) -> List[str]:
"""Generates a function signature from a pyDantic class object"""
# Fetch parameters
params = cls.__annotations__
return [
f"{name}: {data_type},"
if "Optional" not in data_type
... | 2e0a40875f78eb07733fa94fbadbd1d5ee06f2c7 | 3,607,995 |
def expressionToAST(ex):
"""Take an expression tree made out of expressions.ExpressionNode,
and convert to an AST tree.
This is necessary as ExpressionNode overrides many methods to act
like a number.
"""
return ASTNode(ex.astType, ex.astKind, ex.value,
[expressionToAST(c) fo... | 188de9b51e6f05a72f5efc094a64f1960d55b5fc | 3,607,996 |
import itertools
def _limited_walk(node, app):
"""Walk the tree like preorder, expand nodes iff placement is feasible."""
if node.check_app_constraints(app):
return itertools.chain(
[node],
*[_limited_walk(child, app) for child in node.children]
)
else:
retu... | 663a107264e33115f0cbacf1e791db4b662db991 | 3,607,997 |
def preprocessing(questions):
""" 对问题预处理
Args:
questions: 从数据库中获取的问题
Returns:
dictionary: 基于问题分词后构建的词典
texts: 分词后的问题
"""
# 1.分词,去除停用词
stoplist = set('的 ? ? 能 与 和 是'.split())
# 载入自定义词典
# 这里如果php调用就不能写相对路径啦,要写绝对路径才可以的
# jieba.load_userdict('../dict.txt')
... | 69f94ecdd33353a29f3dc703fd8bf134c76398e3 | 3,607,998 |
def get_qa_args() -> Namespace:
"""Get command line arguments"""
parser = ArgumentParser(description="Arguments for QA inference")
parser.add_argument("dataset", type=load_jsonl_dataset,
help="Path to the jsonlines dataset file")
parser.add_argument("--text-col-names", dest="text... | 040f9d668de345e65ce2bf77b992305797bd31d8 | 3,608,000 |
import shutil
def get_archive_name_and_format_for_shutil(path):
"""Returns archive name and format to shutil.make_archive() for the |path|.
e.g., returns ('/path/to/boot-img', 'gztar') if |path| is
'/path/to/boot-img.tar.gz'.
"""
for format_name, format_extensions, _ in shutil.get_unpack_formats(... | 152d68ea9613d7253f78c37ce85758a2c8bc67f9 | 3,608,001 |
def cosine_similarity(filename1, filename2):
"""
Wrapper around `bl_cosine_similarity` function.
Params:
- filename1 is the first file to use.
- filename2 is the second file to use.
Returns a dict {similarity, song1, song2} containing the computed cosine
similarity and the created ... | dcaa29212e9b491d605beb45dd3eedd56f671fc5 | 3,608,002 |
def label_candidates_db(labeler, cids_query, label_functions, apply_existing=False):
"""
This function is designed to label candidates and place the annotations inside a database.
Will be rarely used since snorkel metal doesn't use a database for annotations.
Important to keep if I were to go back towar... | e62389370f377697446a72be5896157b3cd03ee7 | 3,608,003 |
from datetime import datetime
def pickem_handler(event, context):
"""
Handles the requests from the `/pickem` command to the lambda function
that is responsible for handling API requests.
"""
## Uncomment this when I trigger from SNS
params = parse_qs(event['body'])
token = params['token'... | 2c37efc9e8f782e38708948eeec43e9c04cf8593 | 3,608,005 |
import base64
import binascii
import hashlib
def do_handshake(method, headers, transport, protocols=()):
"""Prepare WebSocket handshake. It return http response code,
response headers, websocket parser, websocket writer. It does not
perform any IO.
`protocols` is a sequence of known protocols. On suc... | 207e24a28836ea3ea01a8b667e421de0b39286ed | 3,608,006 |
async def get_all_people():
"""Get all people from the database."""
persons = await collection.find().to_list(1000)
return persons | 0a3aff3fe4c39c2e3fcfb3abb78d50c166df910f | 3,608,007 |
import inspect
def plugin(cls):
"""Decorator to register a class as a Shell extension object
This decorator can be used to register a class structure as a Shell
extension object. After registering the class it self it will also scan for
inner classes and register them as nested extension objects.
... | c788e5b84a05ea93570f66df36697f5c052c6f2a | 3,608,008 |
def count_words(text: str, tokenizer=None) -> int:
"""
Count number of words in a text.
Arguments:
---------
text: str
Text whose words are to be counted.
tokenizer: default=None
Object with a tokenize method. Either instantiated or not works. \
If tokenizer is available... | 98f3c3e1baa3cedaecb905dcc1fd2e2d9559a741 | 3,608,010 |
import fnmatch
def list_stacks(conn, name_filter='*', verbose=False):
"""List active stacks"""
states = FAILED_STACK_STATES + COMPLETE_STACK_STATES + IN_PROGRESS_STACK_STATES + ROLLBACK_STACK_STATES
s = conn.list_stacks(states)
stacks = []
for n in s:
if name_filter and fnmatch(n.stack_na... | 3e9de4b7c30969c0a0b904f77563ec440970bac1 | 3,608,011 |
def agg_maxabs_sign_at_n(m, n=1):
"""
Select the farest value from 0 between the mean of the n greater
values and the mean of the n lower values of array m
Aggregate before the normalization
:param m: array m, float or int
"""
m_ = np.copy(m)
m_.sort()
... | 4c62edde480776e6fda2e22e1d538849ce38c368 | 3,608,012 |
from typing import Tuple
def run() -> Tuple[Response, int]:
"""
This function implements Action Provider interface for launching an
action instance.
This function parses the request_id from a request body and from it
determines whether a new action should be launched or whether to
return the ... | 67608335fb2458448b5cf7d185d81abcc3af2275 | 3,608,013 |
from operator import add
def linear(m, c, x):
"""This function will calculate the y in y = m * x + c"""
print("LINEAR EQUATION %d * %d + %d" % (m, x, c))
return add(multiply(m, x), c) | f9dcfdd8a1359923a11effb4fb48a910ea3ed7a8 | 3,608,016 |
from datetime import datetime
async def UploadHandlerMem(request):
"""
POST handler that accepts uploads of files.
It does not store the content of the file, just creates entry in the dictionary to keep track of upload activity.
"""
# You cannot rely on Content-Length if transfer is chunked.
t... | 76b106418dcadc477b4571cd429f1cebce57b3a9 | 3,608,017 |
def translate_url(url, lang_code):
"""
Given a URL (absolute or relative), try to get its translated version in
the `lang_code` language (either by i18n_patterns or by translated regex).
Return the original URL if no translated version is found.
"""
parsed = urlsplit(url)
try:
match ... | 89ee11eb0a614121052011ed0b3de5a22c479bd4 | 3,608,018 |
def perspective(img, startpoints, endpoints, interpolation=Image.BICUBIC):
"""Perform perspective transform of the given PIL Image.
Args:
img (PIL Image): Image to be transformed.
startpoints: List containing [top-left, top-right, bottom-right, bottom-left] of the orignal image
endpoint... | d0ee2c38ae7675be6de5df153894d5ae51149cc6 | 3,608,019 |
def ray_to_Jonesvector(ode_sol, ne_extent, probing_direction = 'z'):
"""Takes the output from the 9D solver and returns 6D rays for ray-transfer matrix techniques.
Effectively finds how far the ray is from the end of the volume, returns it to the end of the volume.
Args:
ode_sol (6xN float): N rays... | 16cc88350f866a6394bb0e508641135e6b9f31bc | 3,608,020 |
def plot_missing_data(df, sample_rate):
"""[summary]
Args:
df ([type]): [description]
sample_rate ([type]): [description]
Returns:
[type]: [description]
"""
fig = msno.matrix(df.sample(sample_rate))
plot = fig.get_figure()
# plot = fig.savefig('Missing Data Matrix.p... | 064300948948234b65bd41dd6dcd437613cfed12 | 3,608,022 |
def is_unsupported(func):
"""
Checks whether the func is supported by dygraph to static graph.
"""
if any(func in m.__dict__.values() for m in BUILTIN_LIKELY_MODULES):
translator_logger.log(
2,
"Whitelist: {} is part of built-in module and does not have to be transformed... | 1945f3f954625a594d72a4096bbf1504036ec140 | 3,608,023 |
import collections
def recursive_dict_update(d, u):
"""Add all of the items of u into the d"""
for k, v in u.items():
if isinstance(v, collections.Mapping):
d[k] = recursive_dict_update(d.get(k, {}), v)
else:
d[k] = v
return d | 1fec47def1115a8a2938303c3868cf3af86b8c6c | 3,608,024 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.