content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
from typing import Dict
import functools
def run_filters(df: pd.DataFrame, req_filters: FilterMap,
opt_filters: FilterMap = None) -> Tuple[pd.Series, Dict[str, pd.Series]]:
"""
Runs a list of filters on the input dataframe, returning a dictionary of Boolean Series
... | 933969819b5aa63dc1db23f6623802852c7c1682 | 74,200 |
from typing import Callable
from re import T
from typing import Optional
def wrap_exceptions(
fn: Callable[[], T], context: Optional[ParserRuleContext] = None
) -> T:
"""
Wrap the given call to `fn` in a proper try/except block to convert as many
exceptions as possible to WizardError.
"""
try... | 5cbc5627ddcdd878c214d7cd876bd09d321f1748 | 74,201 |
def generate_selected_torsions(input_json):
"""Identify torsions that can be driven.
Parameters
----------
input_json: str,
JSON file name to the output json of generate.py (prepared as if for an OptimizationDataset)
The data in the json file should be a list of {'initial_molecules': [.... | 52d9f89bd783f91e9dda64397d5ecd39c62e925f | 74,202 |
import multiprocessing
import tqdm
def mean(data, block_shape=None, n_threads=None, mask=None, verbose=False, roi=None):
""" Compute the mean of the data in parallel.
Arguments:
data [array_like] - input data, numpy array or similar like h5py or zarr dataset
block_shape [tuple] - shape of the... | 115beccc01453ed97bc9fc1e4e9d698f73d9bd84 | 74,203 |
import types
import re
from textwrap import dedent
async def bot_added(message: types.Message, state: FSMContext):
"""
Пользователь добавляет бота и мы ждём от него токен
"""
token = re.findall(token_pattern, message.text)
async def on_invalid_token():
await message.answer(dedent("""
... | 465a5ddbe8b7ca2c197cceaa59e9bd09a2252a65 | 74,204 |
from datetime import datetime
def interface():
"""Kies het weerstation, de begindatum en de einddatum
Returns:
df, het weerstation, begindatum en einddatum (laatste drie als string)
"""
mode = st.sidebar.selectbox(
"Modus (kies HELP voor hulp)", ["doorlopend per dag", "aantal keren", ... | b5ecbd61820dc991870844fa28c678ac3c47805f | 74,205 |
def Ads(line):
"""Decode Automatic Device Status (ADS)."""
try:
fields = ADS_RE.match(line).groupdict()
except TypeError:
return
TimeUtc(fields)
result = {
'msg': 'ADS',
'talker': fields['talker'],
'id': fields['id'],
'alarm': fields['alarm'],
'time_sync_method': util.M... | 475382b82d4cb048b61fd56ccd5e91c8263dab7b | 74,206 |
import os
def create_graph(posts_df, fb_group_df, domain_df,
GRAPH_DIRECTORY, SCIENTIFIC_TOPIC, DATE):
"""Create the bipartite graph with the facebook groups and the domain names.
The edges represent the fact that this group has shared the URL coming from this domain."""
bipartite_graph... | 80f63aebff8f0504d5d090bc02a363a83572cfbc | 74,207 |
def vertical_relative_vorticity(od):
"""
Compute vertical component of relative vorticity.
.. math::
\\zeta =
\\frac{\\partial v}{\\partial x}
-\\frac{\\partial u}{\\partial y}
Parameters
----------
od: OceanDataset
oceandataset used to compute.
Returns
... | acbee12299b0a6732148f800c499129005e9f60a | 74,208 |
def get_documentation(path=""):
"""
create documentation as simple HTML, using the supplied path, which is interpreted as the project root.
The documentation will be surroundeded with very basic HTML boilerplate, i.e. you probably do not want to
use this method, which is a wrapper around get_documentat... | 7422c1730e88a32b3649c9f004109ff10cdd2e7d | 74,209 |
def import_cbisddsm_training_dataset(label_encoder):
"""
Import the dataset getting the image paths (downloaded on BigTMP) and encoding the labels.
Originally written as a group for the common pipeline. Later amended by Adam Jaamour.
:param label_encoder: The label encoder.
:return: Two arrays, one ... | 16cb020e67486c9d613080cc422d9bdb3d09d7e6 | 74,210 |
def _py_lazy_and(cond, b):
"""Lazy-eval equivalent of "and" in Python."""
return cond and b() | 872f382ac72d8253c61043dfe146d05775b4748d | 74,211 |
def get_response_ctx_view(func):
"""
add only the response object with the view function.
"""
response_param = signature(func).parameters.get('response', None) \
or signature(func).parameters.get('res', None)
is_response = True if response_param is not None else Fals... | b63472497d12203eaa3291e24ed5661d35bbf41f | 74,212 |
def vit_b_p16(pooling_arch=None, distilled=False, num_classes=1000, dropout_ratio=0., image_size=224, early_stride=None):
""" ViT-Base (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-1k weights fine-tuned from in21k @ 224x224, source https://github.com/google-research/vision_transfor... | a998bb1e44cdbfb09a14871592c3afc71f2d24f8 | 74,213 |
def find_gt(a, x):
"""Locate the leftmost value greater than x"""
i = bisect_right(a, x)
if i != len(a):
return i
raise ValueError | aa70fe51d590887a26720c49cdb55f74e8da1bb6 | 74,214 |
async def cringo_stat_embed(user: DiscordUser) -> Embed:
"""Return a big ol' embed of Cringo! stats"""
s = await CringoStatistic.get_by_discord_user(user)
if s.plays == 0:
embed = c.crimbed(
title='Hold up—',
descr="You haven't played any games of CRINGO yet!",
... | 027612631bf9516c43983cbccb3701a97b8e6876 | 74,215 |
def create_design_matrix(long_form,
specification_dict,
alt_id_col,
names=None):
"""
Parameters
----------
long_form : pandas dataframe.
Contains one row for each available alternative, for each observation.
specifica... | f405ca442d2b1a9d173f1982632861ac4694013b | 74,216 |
def transform(sample):
"""Sample is an ordered dictionary of dataset elements"""
image, label = sample["images"], sample["labels"]
image = augment(image=image)["image"]
return image, label | 30a23eab8be5fea5e407343a19fb4fa14d10e104 | 74,217 |
def get_matrices(src):
"""Reads the STIX and returns a list of all matrices in the STIX"""
matrices = src.query([
stix2.Filter('type', '=', 'x-mitre-matrix'),
])
return matrices | 41c97b4cdf16cb07378463c53d20499736362126 | 74,218 |
def split_dataset(dataset):
""" split dataset into train, test, validate """
dataset_train, dataset_test, dataset_validate = train_test_split(dataset, test_size=0.2, random_state=0)
return dataset_train, dataset_test, dataset_validate | 9dfe9de512d2c162aae9bffca6d27ff67748a34d | 74,219 |
from typing import Dict
def validate(incorporation_json: Dict):
"""Validate the Incorporation filing."""
if not incorporation_json:
return Error(HTTPStatus.BAD_REQUEST, [{'error': babel('A valid filing is required.')}])
msg = []
err = validate_offices(incorporation_json)
if err:
m... | 290a776ba6e034f1fc14c9d659f5710395514817 | 74,220 |
def get_y_var(plot_spec: pd.Series):
"""
Return the observable which should be plotted on the y-axis
Arguments:
plot_spec: A single row of a visualization df
Return:
observable which should be plotted on the y-axis
"""
y_var = "" # default value
if ptc.Y_VALUES in plot_spec.... | 2864417304a27375f51c4e91a61b2935316f8b1a | 74,221 |
def load_providers_to_delete():
"""
Build a list of Sources that need to be deleted from the Koku provider database.
The primary use case where this is when the Koku API is down and the Source has
been removed from the Platform-Sources backend. Additionally this is also needed
to re-load the proce... | 970f7eca3aec00ab25ba3c0661ba8d5cf7b8df63 | 74,222 |
from datetime import datetime
def decode_datetime(encoded_datetime):
"""Decode a DateTimeField parameter from a string to a python datetime.
Args:
encoded_datetime: A string in RFC 3339 format.
Returns:
A datetime object with the date and time specified in encoded_datetime.
Raises:
ValueError: ... | 2b2b7ca6ece65f6b6f480d5c8c47a18897b52614 | 74,223 |
def test_strain_bias(data,
value,
sample='sample',
strain='t2onc_type',
samples=None,
incl_neg=True):
"""Tests if a given property is biased towards a specific mouse strain.
Test is performed using a Fisher... | 43f4a1fd2f62eb5cfccc30993ec2f5bd34d7124d | 74,224 |
def beadplot_serial(lineage, features, args, callback=None):
""" Compute distance matrices and reconstruct NJ trees """
# bootstrap sampling and NJ tree reconstruction, serial mode
trees, labels = clustering.build_trees(features, args, callback=callback)
if trees is None:
# lineage only has one ... | c515f325950dea6275cf6c6123ec6b359434c2a9 | 74,225 |
def hermite_fft(a, n=None, axis=-1):
"""hermite_fft(a, n=None, axis=-1)
inverse_hermite_fft(a, n=None, axis=-1)
These are a pair analogous to real_fft/inverse_real_fft, but for the
opposite case: here the signal is real in the frequency domain and has
Hermite symmetry in the time domain. So here it... | 962abd336e77e94efa972c4c70ac3cfdeadf24c5 | 74,226 |
def get_negatives(all_contexts, vocab, counter, K):
"""返回负采样中的噪声词。
Defined in :numref:`sec_word2vec_data`"""
# 索引为1、2、...(索引0是词表中排除的未知标记)
sampling_weights = [counter[vocab.to_tokens(i)]**0.75
for i in range(1, len(vocab))]
all_negatives, generator = [], RandomGenerator(sampl... | 40eb2454530a0f3c3aec419a0c3f99fcb89e825d | 74,227 |
import torch
def calc_iou_tensor(box1, box2):
"""Calculation of IoU based on two boxes tensor, Reference to https://github.com/kuangliu/pytorch-ssd."""
N = box1.size(0)
M = box2.size(0)
be1 = box1.unsqueeze(1).expand(-1, M, -1)
be2 = box2.unsqueeze(0).expand(N, -1, -1)
# Left Top & Right Bot... | efff3eafc8dc33aee5e1f3e5cca9266421e4197e | 74,228 |
def _type_to_type_string(object_type):
"""Converts a type to a serializable string.
Parameters
----------
object_type: type
The type to convert.
Returns
-------
str
The converted type.
"""
if (issubclass(object_type, unit.Unit) or
f'{object_type.__module__}... | d392182cae4c07ba06dd9e5383946f235ee4a4ac | 74,229 |
def get_id(obj, context):
"""Get record id."""
pid = context.get('pid')
return pid.pid_value if pid else missing | 24f9f62483713fe27117e746ddb39895ce492398 | 74,230 |
def conditional(Xnew, X, kern, f, full_cov=False, q_sqrt=None, whiten=False):
"""
Given F, representing the GP at the points X, produce the mean and
(co-)variance of the GP at the points Xnew.
Additionally, there my be Gaussian uncertainty about F as represented by
q_sqrt. In this case `f` represen... | 02f4c7acad1a68079a2807ea8398efa203d0d2f2 | 74,231 |
def node_to_description(name, session=session, debug=False):
"""
Get the description of an protein node
:param name: name of the node
:param session: neo4j session
:param debug: just return the query
:return: a string (the description of the node)
"""
query = "match (n{name:'%s'}) return n.description" % name
... | 07bdbfe4966edb45ffb916af3f1758728a76cf30 | 74,232 |
async def nb2chan(
token: str = Depends(get_api_key),
qq: str = None,
msg: str = None,
):
"""Define fastapi query.
openapi docs at: /docs
```bash
http -v "http://.../nb2chan/?Token=DEMO_TOKEN&qq=123&msg=hello world"
# send Token via HEADERS
http -v "http://.../nb2chan/?qq=123&msg=... | 74366735a84ba81c78e6ee3a5aab4b734cf333b5 | 74,233 |
def parse_id(hardware_id):
"""Parse Nuki ID."""
return hex(hardware_id).split("x")[-1].upper() | 483fb1c7a864242335288f53653c461a50eab638 | 74,234 |
def _load_level(handler, level, pathtable):
"""
Loads level and builds appropriate type, handling softlinks if necessary
"""
if isinstance(level, tables.link.SoftLink):
# this is a link, so see if target is already loaded, return it
pathname = level.target
node = level()
else... | 9f833b57b51fe0fac75c0d5f2a64c87cf3c7510e | 74,235 |
def unfreezeTransformations():
"""Unfreeze selected objects translation.
Returns:
True: If succeed.
"""
sel = om2.MGlobal.getActiveSelectionList()
for s in range(sel.length()):
obj = sel.getDagPath(s)
fnTrans = om2.MFnTransform(obj)
rp = fnTrans.rotatePivot(om2.MSpac... | 628cb99aec1e3a8ff9593f468cc9fa5e97707aed | 74,236 |
from typing import Dict
from typing import Any
from typing import OrderedDict
def sort_dict(item: dict) -> Dict[str, Any]:
"""
Sort nested dict
Input: {"b": 1, "a": {"c": 1,"b": 2}, "c": "c_st[ring]"}
Output: OrderedDict([
('a', OrderedDict([('b', 2), ('c', 1)])),
('b', 1),
('... | 0f4c042df4ea2f00dbda249f9d2c7c3488824559 | 74,237 |
def create_handle_decorator(registry, filter=Always()):
"""
Create a key handle decorator, which is compatible with `Registry.handle`,
but will chain the given filter to every key binding.
:param filter: `CLIFilter`
"""
assert isinstance(filter, CLIFilter)
def handle(*keys, **kw):
... | 2d75f400099a6362c73cddebd024ad1c21756482 | 74,238 |
def filter_term_freqs(term_freqs, where):
"""
Subset term-freqs of a dataframe by specified filters.
"""
# Build a new dataset with just the index.
index = (
term_freqs.index
.to_frame(index=False)
)
index_cols = index.columns
# Run the user-provided filter on this i... | 08113cfce8fb4a29b4def72749b80330164e092c | 74,239 |
import json
def load_dict(filename):
"""
Loads a dictionary stored in JSON format
:param filename:
:return:
"""
data = json.load(open(filename))
return data | 88f286417bbdd43d4499e83750c92843a9f6231a | 74,240 |
def Main(operation, args):
"""
:param operation:a
:param args:
:return:
"""
# 'init' has to be invokded first after deploying the contract to store the necessary and important info in the blockchain
if operation == 'init':
return init()
if operation == 'name':
return name... | f4d5d085c9dc3c18459c90b8d9dd36653b176e68 | 74,241 |
from typing import Optional
def stream_type(stream_type_str: Optional[str]) -> Optional[StreamType]:
"""Converts a string with a command stream type to the corresponding type.
Args:
stream_type_str (str): The string with the command stream type.
Returns:
Optional[StreamType]: The type of... | 0691d224063557cb4f685fa9c31af8d1368edc58 | 74,242 |
def getStorageElementEndpoint(seName):
""" Get endpoints of a StorageElement
:param str seName: name of the storage element
:returns: S_OK() or S_ERROR
for historical reasons, if the protocol is SRM, you get 'httpg://host:port/WSUrl'
For other protocols, you get :py:meth... | 9ca3f6c02f1b2a133dc39711daa40c096240c8c7 | 74,243 |
def lift(fn=None, prior=None):
"""
Given a stochastic function with param calls and a prior distribution,
create a stochastic function where all param calls are replaced by sampling from prior.
Prior should be a callable or a dict of names to callables.
Consider the following Pyro program:
... | 8c80dccd18173b420752c6a87a57690779986c8e | 74,244 |
from typing import Union
from pathlib import Path
from typing import AsyncGenerator
def exchange_pack(
git_repo: Union[Path, str],
pack_type: str,
input_stream: AsyncGenerator[bytes, None]) -> AsyncGenerator[bytes, None]:
"""
Used to exchange packs between client and remote.
:para... | 1bed4611947850a7e231e54f036735e2d2e51c3c | 74,245 |
def message_to_request(msg: bytes) -> TestRequest:
"""Convert message encoded by common.encode_message to request."""
url, case_id, submission_id = common.decode_message(msg.decode("utf-8"))
# We assume here, that data is valid, because it was generated by our code,
# and not by user... so we skip error... | bc899dbececd523702a9846b11adc8ae87179b77 | 74,246 |
def call_cells_mapping(df_reads,df_pool):
"""Determine count of top barcodes, barcodes prioritized if barcode maps to given pool design
"""
guide_info_cols = [SGRNA,GENE_SYMBOL,GENE_ID]
# map reads
df_mapped = (pd.merge(df_reads,df_pool[[PREFIX]],how='left',left_on=BARCODE,right_on=PREFIX)
... | 016118584558cc293bfb8c936326f9afb1da69ce | 74,247 |
def nWaveRiseTime(pmax, patm=101e3, csnd=341, lamb=6.8e-8):
"""
Calculate N-wave rise time
Parameters
----------
pmax -- N-wave overpressure amplitude in Pa
patm -- atmospheric pressure in Pa
csnd -- speed of sound in m/s
lamb -- air molecular mean free path in m
Returns
------... | cbcae9d8e3ddaeb6daab5a02a722cd7302ebf562 | 74,248 |
def remove_whitespace(string):
""" Removes leading spaces, trailing spaces, and empty lines from a string.
:param string: string to clean up
:type string: str
:rtype: str
"""
empty_line = app.LINE_START + app.maybe(app.LINESPACES) + app.NEWLINE
trailing_spaces = app.LINESPACES ... | 8fadf491fd1e2710708076214566c0d64a236f88 | 74,249 |
import ssl
import os
def getRemoteJar(urlOrPath, destPath):
"""Fetch URL to local path or just return absolute path."""
urlp = urlparse(urlOrPath)
if urlp.scheme == '':
return (os.path.abspath(urlOrPath), 'local')
else:
echo2('Retrieving %s to %s.' % (urlOrPath, destPath))
try:... | 2b3d649775962154af9c10acd4f2768ac68fab11 | 74,250 |
import os
import json
def load_json_file_bert(period: str, index: str) -> dict:
"""
Marc's loading function using a template.
"""
json_filename = os.path.join(
BERT_DIR,
PROTOCOL_FILE_TEMPLATE % (period, index, 'json'))
with open(json_filename) as json_file:
session = json... | 69fff0e929c68c7fb6239493463d89edbd687f14 | 74,251 |
def _bp_static_url(blueprint):
""" builds the absolute url path for a blueprint's static folder """
u = u'%s%s' % (blueprint.url_prefix or '', blueprint.static_url_path or '')
return u | 3d5e68c411c804aec7ca7dbd68633cb75370761a | 74,252 |
import os
def check_key(file, key_type, log):
""" Check if file exist, empty, or over max size and correct format"""
# element[0][1] start of file; element[-1][0] is size of file
KEY_TYPE = {
"rsa": [
"RSA private key",
"-----BEGIN RSA PRIVATE KEY-----",
"-----E... | c0b39601fb735125d49587118a4d219f434cd03f | 74,253 |
def reduce_dims(array, axis=0):
"""
Reduce array dimensions at given axis
Note: If trying on image array please check if expand_dims
is used by you during image preprocessing and axis too.
Parameters
----------
array: numpy nd array
axis : int or tuple of ints
Position in the ... | b018bf72ef200e1d30bb6f58f9567a97172b7fc2 | 74,254 |
from datetime import datetime
def jam_mei_context_processor(request):
"""
Essa função é chamada no fim do processamento de cada view
"""
ctx = dict(
super_template='admin/base.html',
debug=settings.DEBUG,
now=datetime.now(),
valores_sugeridos = OfertaDeTurma.objects.all... | d4353b113b81cc872d1255ac0ece5fe3cf0bebd7 | 74,255 |
from sys import path
def send_email(to, context, template_dir):
"""Render given templates and send email to `to`.
:param to: User object to send email to..
:param context: dict containing which needs to be passed to django template
:param template_dir: We expect files message.txt, subject.txt,
me... | 7308d43a2a5bee10e2755cb912c12bc7b329c2ba | 74,256 |
def selectable(label, selected, *args, **kwargs):
""" Selectable line.
This widget marks the whole line as selectable. To add widgets to `selectable`,
simply append them using `orr_same_line`:
```python
c.orr_same_line([
c.selectable("Selectable", False),
c.text("Extra text"),
... | 65b4aea6d59223630a513daffead7f80b074089b | 74,257 |
def mc_maximum_curvature(magnitudes):
"""
calculates magnitude of completeness using maximum
curvature method.
citation: ???
:param catalog : pandas.Series
:param method : str
"""
minimum = round(magnitudes.min(), 2)
bins = np.arange(start=minimum, stop=10, step=0.1)
hist, edg... | 7a0194e50e704893ab67455cc2bdf62e79610c19 | 74,258 |
def self_advection(
grid: grids.Grid,
dt: float,
physics_specs: physics_specifications.NavierStokesPhysicsSpecs,
advection_module: AdvectionModule = modular_advection,
**kwargs
) -> ConvectFn:
"""Convection module based on simultaneous self-advection of velocities."""
advect_fn = advection_modul... | f7d4260401bd317a7d0daf761006992030a8b259 | 74,259 |
def create_model(flags, model_name, inp, rng):
"""Creates model given model_name."""
new_rng, init_rng, drop_rng = jax.random.split(rng, num=3)
if model_name == 'gcn':
features = [flags.hid_dim, flags.num_classes]
model = models.GCN(features, flags.drop_rate, 'PReLU')
init = model.init({'params': init... | 3d01fe1a1b04276e94e61591a1221e77fbf15ec4 | 74,260 |
from datetime import datetime
import json
def execute(_start_time: str, _stop_time: str, public_key: str = None, tableName: str = "sps30_output"):
"""
Function that fetches data entries from database. If public_key is provided data is encrypted and then encoded.
If no key is provided the data is only enco... | c7a63451f631e634b8c5fba0714445a383229411 | 74,261 |
import glob
def csv_to_listofDF(path):
"""
This function gets the path to csv files, reads all the csv files in, converts them to dataframes,
adds distric_id as a column and saves them in a list
Parameters
-------------
path: The path to CSV files
"""
files = glob.glob(... | db13832373f14a46febff8cef610dfa5937149e5 | 74,262 |
def o2sat(s, pt):
"""
Calculate oxygen concentration at saturation. Molar volume of oxygen
at STP obtained from NIST website on the thermophysical properties of fluid
systems (http://webbook.nist.gov/chemistry/fluid/).
Parameters
----------
s : array_like
Salinity [pss-78]
pt :... | f3ed1c4da26b58116142fad8ed452e33a17d37dd | 74,263 |
from typing import Sequence
from pathlib import Path
from typing import Optional
import logging
import click
import itertools
def main( # pylint: disable=C0103
input_files: Sequence[Sequence[Path]],
db: Optional[Path] = None,
tagfile: Optional[Path] = None,
tag: Optional[Sequence[str]... | 52374d054b8f34427f28751f3fe8eeec9ecaed0a | 74,264 |
def plot_trace(
data,
var_names=None,
coords=None,
divergences="bottom",
figsize=None,
textsize=None,
lines=None,
combined=False,
kde_kwargs=None,
hist_kwargs=None,
trace_kwargs=None,
):
"""Plot samples histograms and values.
If `divergences` data is available in `sa... | ab9e0e4bab782c0f667acbd0157293cc11b64913 | 74,265 |
def ijk_ljk_to_ilk(A, B):
"""
Faster version of einsum np.einsum('ijk,ljk->ilk', A, B)
I.e A.dot(B.T) for every dimension
"""
res = np.zeros((A.shape[-1], A.shape[0], B.shape[0]))
[np.dot(A[:,:,i], B[:,:,i].T, out=res[i,:,:]) for i in range(A.shape[-1])]
res = res.swapaxes(0, 2).swapaxes(0,... | caf14f5e820b7fb3e15b9041afbee00ae5b77f1f | 74,266 |
from typing import Callable
import re
def to_markdown(text: str, docformat: str = 'numpy,google', *,
module: pdoc.Module = None, link: Callable[..., str] = None,
# Matches markdown code spans not +directly+ within links.
# E.g. `code` and [foo is `bar`]() but not [`code... | 3ff3580ce254dd0b68ccc48efd9418cfc22c832f | 74,267 |
def view():
"""Returns the app in a nice template for use at awesome-panel.org"""
pn.config.sizing_mode = "stretch_width"
template = pn.template.FastListTemplate(
main_max_width="1024px",
)
select_continent = pn.widgets.Select(name="Continent", options=CONTINENTS, value=CONTINENTS[0])
... | e2e9537418c48adcf8ac3ecb24e9f08082f964b0 | 74,268 |
from typing import Callable
from typing import Mapping
from typing import Any
def py_function_dict_output(
transform: Callable[..., Mapping[str, tf.Tensor]],
inp: Any,
signature: Mapping[str, tf.TensorSpec],
) -> Mapping[str, tf.Tensor]:
"""Wrap a user python function returning a dictionary of tensors... | e550bbbb8f360c35e432ac65c388f70e12712c1b | 74,269 |
def Following(field, dist, fromPt=None):
"""The 'following F [from X] for D' specifier.
Specifies 'position', and optionally 'heading', with no dependencies.
Allowed forms:
following <field> [from <vector>] for <number>
If the 'from <vector>' is omitted, the position of ego is used.
"""
if fromPt is None:
... | db12f71b0e411a0e1144c6537491911c1757180a | 74,270 |
from bs4 import BeautifulSoup
def __parseHTML(pages_html: list) -> list:
"""Function to parse raw HTML filings from EDGAR, and return a structured
list of dictionaries with filing information.
Arguments:
pages_html {list} -- Raw HTML of listings pages.
Returns:
list -- Struct... | bcfe11de5b8df910ca0d98f3aab8edc99e062ae6 | 74,271 |
def hadoop_fs_ls(stdout, stderr, environ, *args):
"""Implements hadoop fs -ls."""
if mock_hadoop_uses_yarn(environ) and args and args[0] == '-R':
path_args = args[1:]
recursive = True
else:
path_args = args
recursive = False
return _hadoop_fs_ls('ls', stdout, stderr, env... | e348aaa247fee11394e5495579c5275b53dfa5a9 | 74,272 |
def get_encoding(header):
"""File out encoding."""
for line in header:
if line.lstrip().startswith("Content-type"):
for entry in line.split(";"):
if entry.strip().startswith('charset'):
return entry.split('=')[1].strip()
return ENCODING | 40ba875fdb99562a3eb985b877d7334162d87882 | 74,273 |
def prune_scalar_nodes(einsum_node):
"""
Remove the scalar input nodes of a einsum_node.
Args:
einsum_node: An fused einsum node.
Return:
both the scalar and the pruned einsum node.
"""
in_subs, out_subs, _ = parse_einsum_input(
(einsum_node.einsum_sub... | a4553937710b31a50a62ea24c2f4664dc5127cbd | 74,274 |
def web_color_to_hex(name: Text) -> int:
"""Convert the color from web color name to hexadecimal."""
return hex_to_hex(web.colors[name]) | 7581085b3bbbb8786584d04224730b5304189108 | 74,275 |
def analyze_personality():
"""個人のテキストをクエリとし,PersonalityInsightsから性格パラメータを取得する.
Returns:
dict: Big 5のパラメータ. keyは{'ope', 'con', 'ext', 'agr', 'emo'}
"""
with open('apikey.txt', 'r') as f:
api_key = f.read()
authenticator = IAMAuthenticator(api_key)
personality_insights = Personal... | 9ad9da76785d8c82ade354621d0faaade144bf45 | 74,276 |
def calcSquareInnerProduct(modes1, modes2):
"""Returns the square inner product (SIP) of fluctuations [SK02]_.
This function returns a single number.
.. [SK02] Kundu S, Melton JS, Sorensen DC, Phillips GN: Dynamics of
proteins in crystals: comparison of experiment with simple models.
Bi... | e0ce8543870f48f505b1fa1d30739362476c720c | 74,277 |
def skip_line_comment(prefix):
"""
Given comment prefix this function returns a parser that skips line
comments. Note that it stops just before the newline character but
doesn't consume the newline. Newline is either supposed to be consumed by
'space' parser or picked up manually.
"""
return... | 8bdfb5ca9a565411fba2292465fd0c8e3d352fb3 | 74,278 |
import argparse
import textwrap
from pathlib import Path
import sys
def parse_args():
"""Process command-line arguments."""
description = """Extract parsers from the file."""
arg_parser = argparse.ArgumentParser(
description=textwrap.dedent(description), fromfile_prefix_chars="@"
)
arg_pa... | 4793e60fd2fd05067908bd1ae01be55e218825f7 | 74,279 |
import re
def awik(phenny, input):
"""Search for something on Apertium wiki or
point another user to a page on Apertium wiki (supports pointing)"""
origterm = input.groups()[1]
if "->" in origterm or "→" in origterm:
return
if not origterm:
return phenny.say('Perhaps you meant ".... | 3e07bbdf6e28f14a1dd0d2b639c9487822cf7f31 | 74,280 |
def moments(filename,samples):
"""
M = first moments, counting down from number of samples to 2
MM = second moments
"""
f = open(filename,'r')
lines = f.readlines()
T = np.zeros((len(lines),len(str.split(lines[0]))))
c = 0
for l in lines:
m = str.split(l)
for n in ran... | 880d737f5c37dbe0096dfaed8cf8103484739b45 | 74,281 |
def extract_exchange(raw_data, exchange):
"""
Extracts flow value and direction for a given exchange.
Returns a float or None.
"""
search_value = JSON_MAPPING[exchange]
interconnection = None
for datapoint in raw_data:
if datapoint['nombre'] == search_value:
interconnect... | f429bdf05d5ecaccc8541a57500059a6b16e7f58 | 74,282 |
import math
def toECEF(latitude, longitude, altitude=0.0):
"""
Returns ECEF coordinates as x,y,z in meters.
latitude: Latitude in radians
longitude: Longitude in radians
altitude: Altitude in meters, defaults to 0
"""
n = N(latitude)
cos_lat = math.cos(latitude)
return (n+altitude)*cos_lat*math.cos(... | 00336400e139e701eeeb9f2aa6ce47ade2696691 | 74,283 |
from typing import List
import inspect
def get_class_names(module) -> List[str]:
"""Get class names of a module."""
ans = []
for m in inspect.getmembers(module):
if inspect.isclass(m[1]):
ans.append(m[0])
ans.sort()
return ans | 4ae36e8823f28d00693eac3d70affe7f0591a745 | 74,284 |
def magnetic_form_factor(element, Qmag=0.):
"""
Read Magnetic form factor table, calculate <j0(|Q|)>
Analytical approximation of the magnetic form factor:
<j0(|Q|)> = A*exp(-a*s^2) + B*exp(-b*s^2) + C*exp(-c*s^2) + D, where s = sin(theta)/lambda in A-1
See more about the approximatio here: https... | 88dfa1ff7bcb8c6665bc516247191c818e7fbc4b | 74,285 |
def init_provider():
"""Init provider factory loader."""
return dict(DGI=DGI) | 50a89477d4db4628bcc5c1ce151baa8a3c6a83f9 | 74,286 |
import os
def detect_canonical_issues(base_dir, newspapers):
"""Parse a directory structure and detect newspaper issues to be imported.
NB: invalid directories are skipped, and a warning message is logged.
:param base_dir: the root of the directory structure
:type base_dir: IssueDir
:param newsp... | 8ecbcb53c8d3e0ca0af01092be3624acf97a572c | 74,287 |
def batch_global_rigid_transformation(Rs, Js, parent, rotate_base=False):
"""
Computes absolute joint locations given pose.
rotate_base: if True, rotates the global rotation by 90 deg in x axis.
if False, this is the original SMPL coordinate.
Args:
Rs: N x 24 x 3 x 3 rotation vector of K joi... | 432e4d2224c27f01e45b5fe69b9e23584c9c95bd | 74,288 |
def available_clouds():
""" list of regions configured for the current cloud
for argparse suggestions """
try:
clouds = config_proxy.CLOUDS
return clouds.keys()
except (ConfigurationError, AttributeError):
return None | cbca28783cf393c0f895cf9580aacc41b6c28679 | 74,289 |
def last_model_in_path(model, path):
"""
Walk ``path`` beginning at ``model`` and return the last model in the path.
:param model: A :ref:`declarative <sqla:declarative_toplevel>` class.
:param str path: The path itself.
"""
# TODO(roman): Check if old comments in this function are still releva... | 6e812642d091af8fe14afba5554c78d9a36fd1e6 | 74,290 |
import yaml
import time
import copy
def heatmap(data_config):
"""Generate heatmap based on the tile scores
Creates a heatmap for the given column, using the color palette `viridis` to set a fill value
- the color ranges from purple to yellow, for scores from 0 to 1.
Args:
data_config (string... | 14a51c8736bb9a9413be1bc87acd72e04b8e90e2 | 74,291 |
def do_upload(app, fh, actual_freq_display=None, verbosity=0):
"""Perform a data upload for the named module
app: The name of the uploader module that will upload the file, or it's
registered dashboard_loader.models.Uploader object
fh: A file-like object representing the the file to be uploaded.
actual_freq_d... | 8a7ca70b9f2b871cfc9d3b1b7c2ad01191da8233 | 74,292 |
from typing import List
from typing import Tuple
def get_slices(all_texts_df: pd.DataFrame,
slice_length: int = 25,
overlap_percent: float = 0) -> pd.DataFrame:
"""
Split the given pandas DataFrame into many slices.
Parameters
----------
all_texts_df: pd.DataFrame :
... | fcfac23da3882b1507d4c0214468b99983b61ee2 | 74,293 |
def object_hook(data):
"""
detects the type of a JSON object, imports the class
of that type and calls `to_dict`
"""
if '_type' in data:
obj = None
obj_type = data['_type']
klass = _import_type(obj_type)
if hasattr(klass, 'from_dict'):
obj = klass.from_di... | a5b29a49a9f5cff5aafc1e775f5b127ba7cc61a0 | 74,294 |
import math
def create_pose(camR, scale=0, angle_deg=0):
"""Compute rotation matrix from viewpoint vertex and inplane rotation """
rot = camR.reshape(3,3)
transform = np.eye(4)
rodriguez = np.asarray([0, 0, 1]) * (angle_deg * math.pi / 180.0)
angle_axis = expm(np.cross(np.eye(3), rodriguez))
t... | 1a864d83c47c9c869a9cc039221e0b4943d7493a | 74,295 |
def configure_publisher_install(request):
"""Render publisher install tab"""
ctxd = {
"i18n": {
"title": ugettext_lazy(
"configure_publisher_install.title"
), # 'Install or Upgrade Publisher'
"fields": {
"pickfile": {
... | 3fe0fc88795437c00fb188624c485fc01271ac37 | 74,296 |
from datetime import datetime
import argparse
def parse_date(date_string: str) -> datetime.date:
"""Helper to parse a datetime.date from the command line."""
try:
return datetime.datetime.strptime(date_string, "%d-%m-%Y").date()
except ValueError:
raise argparse.ArgumentTypeError(f"Not a v... | 0e507525e2ecdd6ecf431b72493e623313606b8f | 74,297 |
import os
def read_cif_folder(path=os.getcwd(),
recursive=True,
store=False,
log=False,
comments='',
extras='',
logfile_name='read_cif_folder_logfile'):
"""
Method to read in cif files from ... | f8d7087eb87f2bc44815271ef5cb464ee8152010 | 74,298 |
def root():
"""Main page renders the index.html page"""
return render_template( "index.html", username=app.config['BASIC_AUTH_USERNAME'], passwd=app.config['BASIC_AUTH_PASSWORD'] ) | 15c4a225f3a358d20b7c4369d8458b1cbde09285 | 74,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.