content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_flagellum(idx, phase, phase_speed, translation, rotation,
flag_radius, longitude_grid, azimuth_grid):
"""
:param phase_speed: integer; will be multiplied by default frequency
:param longitude_grid: how man
:param azimuth_grid: number of grid points (integer)
:return:
... | a4742ae6deacb2a4e7fcf8a181c96d3e3479dac9 | 3,614,609 |
from typing import Literal
def _pretty_print_literal(literal: Literal):
"""Render a literal."""
return render_literal_value(literal.value) | 986a98bb39a60af7e13efba89a66281408fd9855 | 3,614,610 |
def make_point(x, y, as_geom=False):
"""
Make a GeoJSON point.
if as_geom, then return a shapely geometry instead.
"""
geojson = {"type": "Point", "coordinates": [x, y]}
return geometry.shape(geojson) if as_geom else geojson | 551c85fb1bb531b10e1540ebcef141d95ea1ee55 | 3,614,611 |
from datetime import datetime
import json
def two_week_working_hour(dept_info):
"""
convert workingHour into two week's everyday slot
"""
today = datetime.datetime.today()
weekday = today.weekday()
workingHour = json.loads(dept_info.workingHour)
schedule = []
for i in range(14):
... | a7afa25a2912e2917da9e5a86f5407c7b4d8e9cf | 3,614,612 |
import functools
import operator
def bot_has_role_permissions(perm1: hikari.Permissions, *perms: hikari.Permissions) -> Check:
"""
Prevents the command from being used if the bot is missing any of the required role
permissions.
Args:
perm1 (:obj:`hikari.Permissions`): Permission to check for.... | 38baaeedd08998dac996eb984c5d8b49b9726d09 | 3,614,613 |
def make_data(T, fs):
"""
Function to make data
args:
T: time
fs: sampling rate
return:
t: number of samples
x: data
"""
nsamples = int(T * fs)
t = np.linspace(0, T, nsamples, endpoint=False)
a = 0.025
f0 = 550.0
x = 0.07 * np.sin(2 * np.pi * 1.2 *... | 9d76554e27008825d2999ba9a3582ed411c2afc5 | 3,614,614 |
def parse_veh_comp(xmldoc):
"""parses the vehicle composition from the VISSIM data
:param xmldoc: input VISSIM xml
:type xmldoc: xml.dom.minidom.Document
:return: relevant VISSIM vehicleComposition data
:rtype: dict of list of dict
"""
veh_cmp_d = dict() # local vehicle co... | 195b2c8dcbd055d5c8e8fdb4f6b68f360c60c961 | 3,614,615 |
def obscore_loader_gama_sdss(fname):
"""
This is a specutils loader which adds obscore information to a SDSS spectra
in the GAMA survey
"""
spec = Spectrum1D.read(fname, format="SDSS-I/II spSpec")
spec.meta["obscore"] = {}
obscore = spec.meta["obscore"]
hdr = spec.meta["header"]
ob... | 95ca112ba6de00d3ad920b02d3f8dab26989fff8 | 3,614,616 |
from typing import NamedTuple
def get_conn(config: NamedTuple) -> connector.MySQLConnection:
"""
Accept parsed configuration data and create mysql connector
:param config:
:return:
"""
return connector.connect(
host=config.db.host,
database=config.db.database,
user=config.db... | 03ae0c3c2239806d5dbd54c9e1c02dba621919d1 | 3,614,617 |
import time
def uniq_table_id():
"""Return a unique table ID based on the current time in ms.
Returns:
str: in format `U<timestamp_ns>`
"""
return f'U{time.time_ns()}' | cffe47d5e8dfff192e2a754347534e02d4ba6a68 | 3,614,618 |
import inspect
def _get_real_env_hack_hack_hack():
"""
Get the real, currently-being-configured libtbx.env environment.
This is not libtbx.env, because although libtbx.env_config.environment.cold_start
does:
self.pickle()
libtbx.env = self
the first time there is an "import libtbx... | f0fe71b5c0a3922300f9d6d81aeb6057e39dd4c3 | 3,614,619 |
from mapproxy.srs import bbox_equals
def wms_query_eq(expected, actual):
"""
>>> wms_query_eq('bAR=baz&foo=bizz&bbOX=0,0,100000,100000', 'foO=bizz&BBOx=-.0001,0.01,99999.99,100000.09&bar=baz')
True
>>> wms_query_eq('bAR=baz&foo=bizz&bbOX=0,0,100000,100000', 'foO=bizz&BBOx=-.0001,0.01,99999.99,100000.1... | fd4e7ff53c5cc0b6e5545775e47092b743635917 | 3,614,620 |
def split_dataframe_by_position(df, splits):
"""
Takes a dataframe and an integer of the number of splits to create.
Returns a list of dataframes.
"""
dataframes = []
index_to_split = len(df) // splits
#print(index_to_split)
start = 0
end = index_to_split
for split in range(split... | 7536920125fa33fafd420c4fe7ef24aff2fa6ff3 | 3,614,623 |
def address_in_network(ip: str, net: str) -> bool:
"""Is an address in a network
"""
# If IP and net mask are not compatible, return False
if is_ipv6(ip) != is_ipv6(net):
return False
# Convert ips to int
i_ip = ip_to_bits(ip)
total_bits = 32 if not is_ipv6(ip) else 128
netpart... | 2bd77242cc458680076c49ddff0d5dcb215d6999 | 3,614,624 |
def get_service_url(host, port, path=constants.PATH):
"""
Construct a service URL from host, port and path
:param host: (string) the service host (aka server) IP
:param port: (int) port on which to connect to the service
:param path: (string) API endpoint (default to /mnist/classify/)
:return: (... | b0ef07f50866a87c4e5b3e85bd179db1fd46fab0 | 3,614,625 |
def eigcov(data):
"""
Return eigen values and vectors of covariance matrix
"""
eigenValues, eigenVectors = np.linalg.eig(np.cov(data))
idx = eigenValues.argsort()[::-1]
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]
return eigenValues, eigenVectors | 5355d40fc006a8ebeb6f566998666feb7e533c6b | 3,614,626 |
import torch
def index_relation_types(dataset):
"""Classify relations into 1-N, M-1, 1-1, M-N.
According to Bordes et al. "Translating embeddings for modeling multi-relational
data.", NIPS13.
Adds index `relation_types` with list that maps relation index to ("1-N", "M-1",
"1-1", "M-N").
"""... | 639059ecf319ce367a62db64edc1efebc8ef5050 | 3,614,627 |
def init_celery(celery, app):
"""
initial celery object wraps the task execution in an application context
"""
celery.config_from_object(celeryconfig)
class ContextTask(celery.Task):
def __call__(self, *args, **kwds):
with app.app_context():
return self.run(*args... | 1331438c9b6cb01bf96dcf7465d7444fbb985937 | 3,614,628 |
import logging
def _validate(submission):
"""
Validates submission against a set of rules.
"""
title = submission.title.lower()
if ShowerThought.objects.filter(post_id=submission.id).exists():
# sometimes posts are chosen for two days because they fall right on the cusp
logging.war... | c95944036cbb45e7acf024f1966dcbf3c4b980d9 | 3,614,629 |
def java_tokenize(snippets, labels=None):
"""
This function parses a list of java code snippets into a list of lists of tokens.
Args:
snippets: Java code snippets in a list of strings.
labels: (Default value = None) a list of labels for code snippets
Returns:
X: a list of lists of... | dc38ad8f3e070917865007b5e2cccdebf18afaa6 | 3,614,631 |
from typing import Union
from typing import Dict
from typing import Any
from typing import List
from typing import Mapping
def _get_instance_shape(
instance_dict: Union[TaggedDict, Dict[str, Any]]
) -> Union[List[int], None]:
"""Get the shape of an ASDF instance from its tagged dict form.
Parameters
... | db69deffc213a7120969fa0444a0ad42b0a44823 | 3,614,633 |
def decode_cobs(in_bytes):
"""Decode a string using Consistent Overhead Byte Stuffing (COBS).
Input should be a byte string that has been COBS encoded. Output
is also a byte string.
A cobs.DecodeError exception will be raised if the encoded data
is invalid."""
if isinstance(in_bytes, s... | 32ebeec26f1a72960514d9670502dca4b1e761e2 | 3,614,634 |
def validate_enum(datum, schema, **kwargs):
"""
Check that the data value matches one of the enum symbols.
i.e "blue" in ["red", green", "blue"]
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
kwargs: Any
Unused kwargs
"""
retur... | 689fef653b757435d45e76afbf16245d0d53839f | 3,614,635 |
import pprint
def plot_fleur_sn(node, show_dict=False, **kwargs):
"""
This methods takes any single AiiDA node and starts the standard visualization for
if it finds one
"""
plot_nodes, workflow_name, _ = classify_node(node)
if show_dict:
pprint(plot_nodes[0])
try:
plotf ... | a11c4ebe9fc8d3dcfec851b7541836f265f414ed | 3,614,636 |
def create_user(user_data, status=200):
"""Create a new user throught the API"""
user_data = user_data
res = app.post_json('/v1/users',
user_data,
status=status,
expect_errors=status != 200)
return res | d52e80b2c34d0a816c04ff7a021231b749e04e39 | 3,614,639 |
def get_google(
query, n_answers=3, best_so=False, mute=False, break_on_best=False
):
"""
Prints links to the top hits on google given a search query (str)
and returns a link to the top one.
:param query: str, search query
:param n_answers: int, number of max results to get
:param best_so: ... | 3f1fb739a10506232c24576ebb2231468384cbcd | 3,614,640 |
def eval_triangle(x, h, n):
"""
Compute triangle histogram for given latent variables
Input:
x [num_batch, num_latent] latent values
h [num_latent, num_tri] triangle heights
n [num_tri] number of triangles to use
x is broadcasted to [num_batch, num_latent, num_tri] (replicated nu... | e3df13591c4409a5071dc4f495495490f6544291 | 3,614,641 |
def makePartialJac(spec_pair, varnames, select=None):
"""Use this when parameters have been added to a modified Generator which
might clash with aux fn argument names. (E.g., used by find_nullclines).
'select' option (list of varnames) selects those entries from the Jac of the varnames,
e.g. for con... | e7f4cc1a902dae15232073a98786da35a9e7d4b6 | 3,614,642 |
import re
def get_valid_filename(s):
"""Sanitize string to make it reasonable to use as a filename.
From https://github.com/django/django/blob/master/django/utils/text.py
Parameters
----------
s : string
Examples
--------
>>> print get_valid_filename(r'A,bCd $%#^#*!()"\' .ext ')
... | a8161a16d0bd8ad0c5d9ff20c56b52fbdba2d859 | 3,614,643 |
def merge_lists(config, path, base, nxt):
""" a list strategy to merge lists """
for i in range(len(nxt)):
base[i]=my_merger.merge(base[i], nxt[i])
return base | 78dd343a41895253b46a4baaa6350ad7538b8142 | 3,614,644 |
def normalize_shape(shape):
"""Normalize a shape ``tuple`` or ``array`` to a shape ``tuple``.
Parameters
----------
shape : tuple of int or ndarray
The input to normalize. May optionally be an array.
Returns
-------
tuple of int
Shape ``tuple``.
"""
if isinstance(s... | e7b874a2aeeed662678fea68d0f49e3085984f38 | 3,614,645 |
def getLogger(name: str, event_handlers=[]):
"""Creates a logger with .
:type name: str
:param name: the name of the logger to be constructed.
:type event_handlers: list
:param name: list of event handlers
:rtype: :class:`logging.Logger`
:returns: Logger created.
"""
return logger... | 0b9a797f281a4c1406a94525fdafb27a527beafb | 3,614,646 |
def main(inmap, medianfilter):
"""Load input paramters, remove cosmic rays and NaNs,
then make all off-limb pixels zero, and clean up limb,
rotate map and do a cosine correction.
"""
## Load configuration file
config = ConfigParser()
config.read("config.ini")
## Rotate
inmap = inmap.... | 034a6be4edf9bbe2c13ec7b8c47420a74c705b41 | 3,614,648 |
def clean_data(data: DataFrame) -> DataFrame:
"""
Clean the titanic data by converting all the data
into int64s.
Drops the passenger id since it does not contribute
to survivability.
We drop the ticket attribute since the vast majority of them
are unique, which makes it tough to convert th... | 25529dafd51bbb44759678f5a7dfe9d32bb328ea | 3,614,649 |
def get_days_where_1percent_plus_of_requests_lead_to_errors():
"""Return days which more than 1% of requests lead to errors."""
conn = psycopg2.connect("dbname=news")
cur = conn.cursor()
cur.execute(days_which_more_than_1percent_of_requests_lead_to_errors)
results = cur.fetchall()
conn.close()
... | 5d1bc225185710de64ac05410ce4c3e699502c2c | 3,614,650 |
import torch
def warp(x, flow):
"""
x: [B, C, H, W] (im2)
flo: [B, 2, H, W] flow
"""
n, c, h, w = x.size()
# mesh grid
w_grid = torch.linspace(0., w-1, w).view(1, 1, 1, w).expand(n, 1, h, w).cuda()
h_grid = torch.linspace(0., h-1, h).view(1, 1, h, 1).expand(n, 1, h, w).cuda()
grid ... | d362228b3b7c21ca1037f4eba8dd081a256e41bc | 3,614,651 |
import numpy
def utils_fft(series):
"""
Computes the inverse fast foyer transform.
Parameters
Input
series : array_like
Output
The transformed array.
"""
return numpy.fft.fft(series) | a9c9dd3b405b7ef185125576386ac9fc008ea76f | 3,614,652 |
from typing import Union
def not_operator(a: PrimitiveExpression) -> Union[HTCBool, Undefined, Error]:
"""
Logical not operator as defined by classad specification.
.. code:: python3
parse("!False").evaluate() # result: HTCBool(True)
"""
return a.__htc_not__() | 2cf5ba61d7cc169c6fa9922a2be418497d70a8bf | 3,614,653 |
def BackwardElimination(x, y, Threshold):
"""
This function apply a backard elimination for a linear regression model, based on P Value level.
Argument:
----------
- x: pandas dataframe
The dependent variables
- y: pandas dataframe
The independent variable
... | 0835efdccbd0404be5e333467732017ee7520649 | 3,614,655 |
def ListToString(list_items):
"""Convert a list of items into a unicode string of a comma-separated."""
str_list = [unicode(v) for v in list_items]
return u', '.join(str_list) | 79fa415561dd55380f84d3f238c0c33ef350bfec | 3,614,656 |
import re
def load_primers_as_re(primer_fasta, mm, rc=False):
"""Load primers as regular expressions.
Read primer file and record all specified sequences.
"""
primers = set()
in_handle = open(primer_fasta, "rU")
reader = fastaReader(in_handle)
count = 0
for record in reader:
i... | 19bc389b975d3eed2cbc4de7489cdefadd891a32 | 3,614,658 |
from typing import Literal
from typing import List
def get_foot_marker(foot: Literal["left", "right"]) -> List[str]:
"""Get the names of all markers that are attached ot a foot (left or right)"""
sensors = ["{}_fcc", "{}_toe", "{}_fm5", "{}_fm1"]
return [s.format(foot[0]) for s in sensors] | 518fbb3f68cbf8622b2bf1fa85f9ecae8008c456 | 3,614,659 |
def get_price_history(data, date, beta_window, sid, benchmark):
"""
Create a DataFrame containing the data for the necessary sids within that time frame
"""
if not beta_window:
history_index = data.index.searchsorted(date)
history_index_start = data.index.searchsorted(data[data[sid] != 0... | cddb1e59dbc783e4b36c0246e1d90e78169c6445 | 3,614,660 |
import six
def _validate_string(s, accept_none = False):
"""
A validation method to convert input s to string or raise error if it is not convertable
"""
if s is None and accept_none :
return None
try:
if isinstance(s,list):
return [six.text_type(item) for item in s]
elif isinstance(s,dict):
return ... | 0c7b20884a27714acb0c16bddcbc113bd3a8c60e | 3,614,661 |
from .Geocode import Geocode
def geocode(**kwds):
"""A factory for Geocode"""
return Geocode(**kwds) | 6e28b21e47a9801de3ac21f9c23aabebf4b30b88 | 3,614,662 |
def mfn_multiply_slepc(mat, vec,
fntype='exp',
MFNType='AUTO',
comm=None,
isherm=False):
"""Compute the action of ``func(mat) @ vec``.
Parameters
----------
mat : operator
Operator to compute function ac... | b40109e0578f5d7991d04994944d5566e543ff1a | 3,614,663 |
def sdffile2selfies_lst(sdf):
"""convert sdffile into a list of SELFIES strings.
Args:
sdffile: str, file
Returns:
selfies_lst: a list of SELFIES strings.
"""
smiles_lst = sdffile2smiles_lst(sdf)
selfies_lst = list(map(smiles2selfies, smiles_lst))
return selfies_lst | 38027842a6900c44658d365e15669e21afb476c2 | 3,614,664 |
import json
import base64
def get_gl_handle(schema, vineyard_id, engine_hosts, engine_config):
"""Dump a handler for GraphLearn for interaction.
Fields in :code:`schema` are:
+ the name of node type or edge type
+ whether the graph is weighted graph
+ whether the graph is labeled graph
+ the... | 0ea81c5d09013e55272582825b541ad3df4d9336 | 3,614,665 |
def has_single_gpu() -> bool:
"""Return whether there is only a GPU available."""
return get_available_gpus_number() == 1 | 32c186b538020ff9b14ca6fde4c61ce724d33cd4 | 3,614,666 |
def is_config_or_test(example, scan_width=5, coeff=0.05):
"""Check if file is a configuration file or a unit test by :
1- looking for keywords in the first few lines of the file.
2- counting number of occurence of the words 'config' and 'test' with respect to number of lines.
"""
keywords = ["unit ... | 0e2823897b72a916afd9672beed904190bb2c1c2 | 3,614,667 |
def ParseVariationsCmdFromFile(filename):
"""Parses commandline switches string into internal representation.
Same as ParseVariationsCmdFromString(), except the commandline switches
string comes from a file.
"""
with open(filename, 'r') as f:
data = f.read().replace('\n', ' ')
return ParseVariationsCmd... | a74fe9a015622d30132ad16bae646f5ff8651db9 | 3,614,668 |
def select_period(xr_data: xr.DataArray, period: TimePeriod) -> xr.DataArray:
"""Function to temporally subset an xarray dataset from a tuple of
start date and end date
"""
return xr_data.sel(time=slice(period.start, period.end)) | b785137f3bea5bf55e3f1065db37e6f9884e0e2b | 3,614,669 |
def process_snr(procstatus, dscfg, radar_list=None):
"""
Computes SNR
Parameters
----------
procstatus : int
Processing status: 0 initializing, 1 processing volume,
2 post-processing
dscfg : dictionary of dictionaries
data set configuration. Accepted Configuration Keywor... | 798c04ad55f4290875bb1ebec0a0540339503804 | 3,614,670 |
from typing import List
from pydantic import BaseModel # noqa: E0611
def norm_router(synset_mappings: dict[str, list], category_mappings: dict[str, list]):
"""Generate node-normalization router."""
router = APIRouter()
def normalize_one(curie):
"""Get normalizer response for CURIE."""
if... | 4aff9b580037b7d82ac0d94e90cb7a94a098c078 | 3,614,671 |
def generate_trappingtable(data):
"""Generates master table of when each plot has been sampled or missed.
Input: Pandas Dataframe with the containing the following columns
plot - plot number
period - portal project period code, unique for each month of trapping
yr - year sample occured
mo - mon... | 0d1bf0345ffd5aeb48f5ba7718d4aa8b203ebf16 | 3,614,674 |
def get_by_slug(*, db_session, slug: str) -> Plugin:
"""Fetches a given plugin or creates a new one."""
return db_session.query(Plugin).filter(Plugin.slug == slug).one_or_none() | 7c1db90a9afb52e6ef3e208c2835ae01ec39f180 | 3,614,675 |
import json
def get_payment_url(order_id):
"""This method will pass order data (customer details, item data)
to the GetUrl API (iCredit) and get payment url
:param order_id: Sales Order No.
:return: payment url(iCredit) (String)"""
try:
order = frappe.get_doc("Sales Order", order_id)
icredit_settings = fra... | 49b51fefb7c4dd548feda9d63f9fca7a4e5438dc | 3,614,677 |
import torch
def estimate_snn(model_dat, do_print=True):
"""estimate direct effects in identified structural form
using PyTorch AD automatic differentiation
forcasting y is done by reduced form since it is already solved for dy
structural form:
dy = my @ dy + mx @ dx
mx, my is a linea... | 22c8680b084371b48c543e06ea138d207a6b392f | 3,614,678 |
def plot_var(
data_frame,
x_var="flow",
y_var="CO_TP",
label_var="mpr",
pivot="distance",
x_label="Flow [veh/m]",
y_label="CO2 %",
t_label="Distance [m]: ",
legends=[r"0 \%", r"10 \%", r"20 \%", r"30 \%", r"40 \%"],
fnt_size={"fontsize": 16},
x_size=5,
y_size=7.5,
tra... | f0c02e2d1c704935bd88220e5ddbac78ce1bc792 | 3,614,679 |
from typing import Optional
from typing import Tuple
async def decide_content_and_extension(
accept_header: Optional[str] = None, accept_language_header: Optional[str] = None
) -> Tuple[str, str, str]:
"""Return content_language, content_type and extension based on request."""
# Default content-type/conte... | c35b898c2810113bc016acb36abcc65714c3760f | 3,614,680 |
def score_segmented_edges(pred_seg, pred_edges, lbl_seg, lbl_edges):
"""
Find the precision & recall scores for a set of predictions tied to
segments within a volume. Each predicted segment is mapped to its
maximally overlapping segment within the label segments.
"""
overlaps, pred_ids, lbl_ids ... | 3b69a820916258b5e1d417d70b87c99cd6826021 | 3,614,681 |
import json
def bundle_to_json(fh):
"""
Convert the received HG10xx data stream (a mercurial 1.0 bundle created using hg push from the
command line) to a json object.
"""
# See http://www.wstein.org/home/wstein/www/home/was/patches/hg_json
hg_unbundle10_obj = readbundle(get_configured_ui(), fh... | c99b7311b7844549e8f1d754ed5c7f74bb0ff2cf | 3,614,682 |
def rotate_velocities(a,d,mua,mud):
"""eq 3.68, """
mu = return_muicrs(a,d,mua,mud)
mugal = np.dot(return_gaia_Agprime(),mu) # eq. 3.68
# solve for positions
ricrs = return_ricrs(a,d)
rgal = np.dot(return_gaia_Agprime(),ricrs)
# implement eq 3.63
ell,b = np.arctan2(rgal[1],rgal[0])... | 49d4edb52f5dffa64232db3fba0475db9a1b61f5 | 3,614,683 |
import logging
def open_api(version):
"""
:param version:
:return:
"""
def fn(method):
@wraps(method)
def wrapper(*args, **kwargs):
openClass = get_api(version)
code, msg = openClass.check_header()
if code != 0:
return response_js... | 2bda139c6d85268030cd2477d7e6f874b781a968 | 3,614,685 |
from typing import Iterable
import calendar
def calc_eomday(year, month):
"""end of month day"""
if isinstance(year, Iterable):
assert isinstance(month, Iterable)
return np.array([calendar.monthrange(y, m)[-1] for y, m in zip(year, month)])
else:
return calendar.monthrange(year, mo... | ef9adb0ee054a51d9ad39e5ddb0e2ce5fb7465be | 3,614,686 |
import json
def prepare_clean_listing_record(listing_serializer_record):
"""
Clean Record
Sample Record (record_json) after clean
{
"id": 316,
"title": "JotSpot 28",
"description": "Jot things down",
"unique_name": "ozp.test.jotspot.28",
"description_short": "Jot stuff d... | 7330b24f90345be14966f28d61e7665b0785a9e6 | 3,614,687 |
def retrieve_path_dict(parse_tree, path):
"""
retrieves the parameter values of an path instance
:param parse_tree: the json parse tree of the swagger document
:param path: path value of the dict to find
:return:
"""
keys = path.split("/")
my_tree = parse_tree
for key in keys:
... | f1d1163b15d2d114b1024650f4e459e6142f513e | 3,614,688 |
def has_shape(data, shape, allow_empty=False):
"""
Determine if a data object has the provided shape
At any level, the object in `data` and in `shape` must have the same type.
A dict is the same shape if all its keys and values have the same shape as the
key/value in `shape`. The number of keys/val... | f04add860bb6b886bb693ddc85b3d4877245d749 | 3,614,689 |
from typing import List
def get_unmatched(repo_path: str, language: str, original_commit: str, translated_commit: str) -> List[PropEntry]:
"""
Get all original key values that have not been translated.
:param repo_path: Path to repo.
:param language: The language identifier (i.e. 'ja')
:param orig... | 4fe4540f901bbaff010ec09c3b55ecbffa42c7da | 3,614,690 |
def Pendulum(a0=0, v0=0):
"""
Main function for calling matplotlib animation
a0: float
starting angle (rad)
v0: float
starting angular velocity
"""
aVec = [a0]
vVec = [v0]
fig, ax = plt.subplots(figsize=(12,12))
line, = ax.plot([0, np.sin(aVec[0])], [0, np.cos(aVec[0])])
ax.set_xlim(-1.2,1.2)
... | 7350d08002018a385f7674a4ce6dafac0b5c4c21 | 3,614,693 |
import requests
def metrics(self, **kwargs):
"""
History of your Blockfrost usage metrics in the past 30 days.
https://docs.blockfrost.io/#tag/Metrics/paths/~1metrics~1/get
:param return_type: Optional. "object", "json" or "pandas". Default: "object".
:type return_type: str
:returns A list o... | bc53dcb7024373dd1f99acadcfbc9902b2810218 | 3,614,694 |
def build_word_pattern(word, language):
"""Given a word and a language, calculate the word pattern and the number of unique character is has."""
pattern = ""
unique = 0
char_map = {}
for char in word:
if char not in char_map.keys():
char_map[char] = unique
unique += 1... | deaffe957935cc9659e9b88e8908bb56c8a3ffad | 3,614,695 |
def plot_spectra_by_type(frequency, spectra, classes, title=''):
"""Plot mean spectrum with its variance for a given class.
Parameters
----------
frequency : pandas Series, shape (n_freq_points,)
Frequencies for which the Raman spectra were acquired.
spectra : pandas DataFrame, shape (n_sp... | ccdf36c05da7d68f3d0e27560921cddb0c1b94a0 | 3,614,697 |
def RR_calc(classes, TOP):
"""
Calculate Global performance index (RR).
:param classes: confusion matrix classes
:type classes: list
:param TOP: number of positives in predict vector per class
:type TOP: dict
:return: RR as float
"""
try:
class_number = len(classes)
... | 814a11c339b25dc687d537efd3244ddad9c0f8fd | 3,614,698 |
def isctime(sys, strict=False):
"""
Check to see if a system is a continuous-time system
Parameters
----------
sys : LTI system
System to be checked
strict: bool (default = False)
If strict is True, make sure that timebase is not None
"""
# Check to see if this is a con... | 02825d5664a066966ff4763b7edb7401b6dd14af | 3,614,699 |
def stddev(data, ddof=0):
"""Calculates the population standard deviation
by default; specify ddof=1 to compute the sample
standard deviation."""
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/(n-ddof)
return pvar**0.5 | 3ec3576aa14965b98d9ef44a3d77b69d9a2913a6 | 3,614,700 |
def build_model_with_cfg(
model_cls,
variant: str,
pretrained: bool,
default_cfg: dict,
model_cfg= None,
feature_cfg= None,
pretrained_strict: bool = True,
pretrained_filter_fn = None,
pretrained_custom_load = False,
kwargs_filter = None,
... | 4d127be55ecbc557c5a146ecf87d23307cb785e5 | 3,614,701 |
def load_data_and_labels_lemonde(filepathXml):
"""
Load data and label from Le Monde XML corpus file
the format is ENAMEX-style, as follow:
<sentence id="E14">Les ventes de micro-ordinateurs en <ENAMEX type="Location" sub_type="Country"
eid="2000000003017382" name="Republic of France">France</E... | a1d624d12a1f4ceda49c62cb2608f48301e62dd2 | 3,614,702 |
def view_user_issues(username):
"""
Shows the issues created or assigned to the specified user.
:param username: The username to retrieve the issues for
:type username: str
"""
if not pagure_config.get("ENABLE_TICKETS", True):
flask.abort(
404,
description="Tic... | dfbbc5932080a7e0fa18ebb04d2b553fe57d9862 | 3,614,703 |
def i0(x):
"""
Modified Bessel function of the first kind, order 0.
Usually denoted :math:`I_0`. This function does broadcast, but will *not*
"up-cast" int dtype arguments unless accompanied by at least one float or
complex dtype argument (see Raises below).
Parameters
----------
x : ... | 665861f872be896553b2b57f5de8ca09b6dc7bfb | 3,614,704 |
def generate_registers_sifive_clic0_clicintip(intr, addr):
"""Generate xml string for riscv_clic0 intip register for specific interrupt id"""
return """\
<register>
<name>clicintip_""" + intr + """</name>
<description>CLICINTIP Register for interrupt id """ + ... | d3260a11f670a90affaf0284c2f74afac9f6c4a4 | 3,614,705 |
import json
import time
def close_poll():
""" Closes a poll. """
form = DeletePost()
if form.validate():
try:
post = SubPost.get(SubPost.pid == form.post.data)
except SubPost.DoesNotExist:
return json.dumps({'status': 'error', 'error': _('Post does not exist')})
... | 1514e0430f808a6e9e9a7f0b377767bdc2436c2b | 3,614,706 |
def TUInt_JavaUIntToCppUInt(*args):
"""
TUInt_JavaUIntToCppUInt(uint const & JavaUInt) -> uint
Parameters:
JavaUInt: uint const &
"""
return _snap.TUInt_JavaUIntToCppUInt(*args) | 3d845fab201781d2d23a7d5d6dab2cedc94863cf | 3,614,707 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
if hass.data[DOMAIN].get(DISPATCHERS) is not None:
for cleanup in hass.data[DOMAIN][DISPATCHERS]:
cleanup()
if hass.data[DOMAIN].get(DATA_DISCOVERY_INTERVAL) is not None:
hass.dat... | bc862de99608e8f8668ddf5d22bc4cb526277447 | 3,614,708 |
def extract_pdbs(input_filelines):
""" Given a list of lines from SSM output txt, returns a list of upper case PDBs
The input file should have a range of lines enumerating the PDBS that looks like this:
.....
.....
## Structure Nres Nsse RMSD Q-score
1 PDB 5cxv... | 52270f03ba2a4eca6308327583467bc391346bea | 3,614,709 |
def result():
"""Route to results page after submitting form on index page"""
# declare form from form.py
form = pathToVideo()
# user option selections from form saved as sessions to be accessible via different routes
session['firstPath'] = form.firstPathSelect.data
session['secondPath'] = form... | c4f73bbdd749360c99d64d9106020b61da904235 | 3,614,710 |
def is_conv2d(module):
"""Determine Conv2d."""
# depth-wise convolution not in pruned search space.
return isinstance(module, Conv2d) and not is_depth_wise_conv(module) | db7b1d883900a532e183332998ade2723d98f681 | 3,614,711 |
def make_date(d_str: str) -> Date:
""" Returns new Date instance from given date string
REQUIRES: d_str is in format 'yyyy-mm-dd'
"""
year = int(d_str[:4])
month = int(d_str[5:7])
day = int(d_str[8:])
return Date(year, month, day) | ea09489abba828edcdbc33ff545bf09b88b019ec | 3,614,712 |
def get_device_id():
""" GEt unique id for device"""
flash_id = '{0:x}'.format(esp.flash_id())
manufacturer = flash_id[-2:]
device_id = flash_id[2:4] + flash_id[0:2]
return (manufacturer, device_id) | 1f7ecc90b8ef6c844d64ee7acab79c69e7727a07 | 3,614,713 |
import torch
def view_complex_native(x: torch.FloatTensor) -> torch.Tensor:
"""Convert a PyKEEN complex tensor representation into a torch one using :func:`torch.view_as_complex`."""
return torch.view_as_complex(x.view(*x.shape[:-1], -1, 2)) | 14e74f1c8b5e6de673c962e4381e74026d3d3db2 | 3,614,714 |
def cross_corr_norm(patch_0, patch_1):
"""
Returns the normalized cross-correlation between two same-sized image
patches.
Parameters :
patch_0, patch_1 : image patches
"""
n = patch_0.shape[0] * patch_0.shape[1]
# Mean intensities
mu_0, mu_1 = patch_0.mean(), patch_1.... | 213100b174993baa07ea685b23541d3dfe49ace8 | 3,614,715 |
from datetime import datetime
def datetime_to_W3CDTF(dt):
"""Convert from a datetime to a timestamp string."""
return datetime.datetime.strftime(dt, W3CDTF_FORMAT) | debdce838987c8815fec977761f760a4fba62aa1 | 3,614,717 |
def get_device_value_oid(ip, oid, community_string="public"):
"""
Get value from specified device with OID
Args:
ip: The device's IP address
oid: SNMP OID
community_string: The community string for the network. Usually 'public' or 'private'
Returns:
... | bf5ecb3519fca3d2d6343e35a540d37a70e698e6 | 3,614,718 |
def get_flip_set(index):
"""Make flip set"""
n = 1
while n <= index:
n *= 2
def get(n, j):
if j <= 1:
return {b for b in range(j)}
n_half = n // 2
if j < n_half:
return get(n_half, j)
f = {b + n_half for b in get(n_half, j - n_half)}
... | 3174b9bab59ae67e9f869fddd9c0a6669f742a45 | 3,614,719 |
def cosineDistance(a, b):
""" Calculates the cosine distance between lists of numbers `a` and `b`.
Args
---
`a : float[]` The first list of floats (or ints)
`b : float[]` The second list of floats (or ints)
Returns
---
`distance : float` The distance between `a` and `b`
"""
n =... | a697e17c2483441995c3a04652edd2bcac287539 | 3,614,720 |
def tensor2sparse(tensor):
"""Convert pytorch tensor to sparse csr matrix."""
return sparse.csr_matrix(tensor.detach().cpu().numpy()) | dbd33450abd534eafa48fdae896afefcf6bdefad | 3,614,721 |
from typing import Any
from typing import Callable
import click
def optional(*decls: str, nilstr: bool = False, **attrs: Any) -> Callable[[FC], FC]:
"""
Like `click.option`, but no value (not even `None`) is passed to the
command callback if the user doesn't use the option. If ``nilstr`` is
true, ``-... | dae9c0b60d4d7f0bdbab4966e30f8b237c6af17a | 3,614,722 |
def get_model_base() -> dict:
"""The base model for running a WLTC experiment.
It contains some default values for the experiment
but this model is not valid - you need to override its attributes.
:return: a tree with the default values for the experiment.
"""
instance = {
"unladen_ma... | cfa1bb87a6f6ffb6c88863a27d75fd9bf2a13cff | 3,614,723 |
def triplet_loss(y_true:tf.Tensor, y_pred:tf.Tensor, alpha:float = 0.2):
"""
-- Explanation :
this function compares the triplet loss ()
-- Args:
y_true -- true labels,
y_pred -- python list containing three objects:
anchor -- the encodings for the anchor images, of shape (None, 12... | c46161f5253a9969110d2867c309982d1f1db119 | 3,614,724 |
def x_view_function():
""" underspecified library view """
return Response(1.234) | a85460fd90978277cfc5c9c4253e2d056c8115c2 | 3,614,725 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.