content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
def make_networks(
spec: specs.EnvironmentSpec,
hidden_layer_sizes: Tuple[int, ...] = (256, 256)) -> SACNetworks:
"""Creates networks used by the agent."""
num_dimensions = np.prod(spec.actions.shape, dtype=int)
def _actor_fn(obs):
network = hk.Sequential([
hk.nets... | 8e6d37034b0739570ed52bb275747756fab54bbc | 68,174 |
def dict_to_xml(dict):
"""Convert dict to xml.
Args:
dict (dict): Dictionary.
Returns:
str: Return a XML representation of an dict.
"""
return dicttoxml(dict).decode() | 093c035057e26074944363777d16f3a7598561e5 | 68,175 |
def select_following(userid, otherid, limit=None, backid=None, nextid=None):
"""
Returns the users whom the specified user is following.
"""
return select_followed(userid, otherid, limit, backid, nextid, following=True) | 0c734bd3a320cdf297ef107eb7be51ceeb9c4bb7 | 68,176 |
import re
def author_url_to_author_id(url: str) -> int:
"""
Converts an author url into an author id.
:param url: str
:returns int, author id
"""
raw_author_str = url.replace("https://www.goodreads.com/author/", "")
author_rgx = r".*show\/(\d+)\..*"
return int(re.search(author_rgx, ra... | a02b4debbfb11a21fa7d38db94181f95628e9c74 | 68,177 |
def gf_ddf_zassenhaus(f, p, K):
"""Cantor-Zassenhaus: Deterministic Distinct Degree Factorization
Given a monic square-free polynomial `f` in `GF(p)[x]`, computes
partial distinct degree factorization `f_1 ... f_d` of `f` where
`deg(f_i) != deg(f_j)` for `i != j`. The result is returned as a
... | 0316f13dfded75fbccbf792ec9f94458d45797e8 | 68,178 |
import pathlib
import warnings
def parse_table_input_file(in_dfs):
""" Returns a tuple
(instrument name list, creation date list, instr from name list, instr from metadata list)
"""
try:
# Select the Input Files df from the dictionary
df = in_dfs['Input Files']
# Select... | b1da2ff19d1f16a37596e5aa3f2897569dff4172 | 68,179 |
import configparser
def connect(connection_name: str) -> cx_Oracle.Connection:
"""returns an Oracle connection by reading a config file in your F drive"""
config = configparser.ConfigParser()
config.read(f'F:/{connection_name}.ini')
details = config['details']
dsn_tns = cx_Oracle.makedsn(details['hostname'], det... | 49ae3b4021808f06bef2b094501d5b4a6d29e5e6 | 68,180 |
def totales_productos():
"""
Ventas Totales por Productos
"""
producto = request.vars.producto
form = SQLFORM.factory(
Field('producto', 'integer', label='Producto', default=producto, widget = SQLFORM.widgets.autocomplete(
request, db.maestro.alias, id_field=db.maestro.id, mode=1... | 2048e4e7b8a2530e9e5a8cfb3272013cff727849 | 68,182 |
from sympy.utilities.lambdify import lambdify
def sympy2casadi(sympy_expr, sympy_var, casadi_var):
"""
Transforms a sympy expression into a casadi function.
Parameters
----------
sympy_expr : sympy expression
sympy_var : list of sympy symbols
casadi_var : list of casady ... | d61051eb81a582438e893ad90fff1e4ba0377f7a | 68,183 |
import functools
def wrap_unauthorized(f):
"""Wrap a function to expect an unauthorized failure."""
@functools.wraps(f)
def wrapper(*args, **kwargs):
try:
f(*args, **kwargs)
except lib_exc.Forbidden:
pass
else:
raise AssertionError("The test was ... | a8cc6a9dd3aad6b39da6450eab3aeb4da78ebcac | 68,184 |
def testForStrayPoints(contour):
"""
There should be no stray points.
Data structure:
(x, y)
"""
contour = wrapContour(contour)
if len(contour) == 1:
pt = contour[0].onCurve
pt = (pt.x, pt.y)
return pt
return None | dc88ab4fa46ecf0d55100ae1d8fc416a3d411df4 | 68,185 |
def tableToDataFrame(table):
"""Converts a vtkTable to a pandas DataFrame"""
if not isinstance(table, vtk.vtkTable):
raise PVGeoError('Input is not a vtkTable')
num = table.GetNumberOfColumns()
names = [table.GetColumnName(i) for i in range(num)]
data = dsa.WrapDataObject(table).RowData
... | be4a749d90f0038d8e1eb3d483cef41a8b6e8620 | 68,186 |
from enum import Enum
from typing import Union
import json
def export_dataset_as_avro(
connect_info: Client, *, url: str, dataset_name: str, fs_type: Enum
) -> Union[JsonDict, bool]:
"""
Takes a connect info object and writes the corresponding avro file to specified url for
specified dataset. By defau... | 30976a4c76ee835c615764322a049ed239846319 | 68,187 |
def signup():
"""
Sign-up user for a ZenType account.
"""
r = request.get_json()
user_email = r.get('email', None)
user_password = r.get('password', None)
userDO = UserAuth.create_new_user(
email=user_email,
password=user_password
)
if userDO is not None:
# if the user was created successfully, give ... | 0a66bab211d7d94d9360f75610e42e799fd6d7b0 | 68,188 |
def _FormAdj_w(a1, a2):
"""
transform eisensteinInteger a1+a2*w -> form 1+3*(x+y*w)
"""
if a1 % 3 == 0:
if a2 % 3 == -1 or a2 % 3 == 2:
return a1 - a2, a1
else:
return a2 - a1, -a1
elif a1 % 3 == 1:
if a2 % 3 == 1:
return a2, a2 -a1
... | f9c5561e46225786fa5250a6be90d77ef2bd7aad | 68,189 |
def handle_pushes(payload: dict) -> dict:
"""Handles push webhook events
:param payload: the payload of the POST request coming from the webhook
:type payload: dict
:returns: an empty widget because no widget is created for pushes
:rtype: dict
"""
if payload['ref'] == 'refs/heads/master':
... | cea03b3eb099716aa4089fc47874e39ffb186400 | 68,190 |
def tstfunc2(*args, **kwargs):
""" a function, that returns a unique result for every call """
rslt = mk_signature(args, kwargs), next(ctr2)
print("Func(%s, %s) => %s" % (args, kwargs, rslt))
return rslt | c24cde839c9f7ab00ad74f7065b68e010d530d5f | 68,191 |
def _cytomine_parameter_name_synonyms(name, prefix="--"):
"""For a given parameter name, returns all the possible usual synonym (and the parameter itself). Optionally, the
function can prepend a string to the found names.
If a parameters has no known synonyms, the function returns only the prefixed $name.
... | 4d8d58571b03182cf31546c370fda81e2caf5800 | 68,192 |
def read_alignment_file(path, trg_lengths, src_lengths):
"""
read flat alignment file
:param path: path to alignment file
:param trg_lengths: array of target lengths (for each sentence)
:param src_lengths: array of source lengths (for each sentence)
:return: array of alignments (unprocessed)
... | d0433b1375e7b7774521316643f48e921587a372 | 68,194 |
def get_deps():
"""Write the result of the bazel query `query` against protobuf to
`out_file`."""
cc_files_output = bazel_query(BAZEL_DEPS_PROTOC_LIB_QUERY)
cc_files = [
name[len(PROTOBUF_CC_PREFIX):] for name in cc_files_output
if name.endswith('.cc') and name.startswith(PROTOBUF_CC_PREFIX)]
p... | 0e83b429c4f59a48f28a6da704cdd25250aee24a | 68,195 |
import cmath
def _angles_for_ZYZ(input_gate):
"""Finds and returns the angles for ZYZ rotation matrix. These are
used to change ZYZ to other combinations.
Parameters
----------
input_gate : :class:`qutip.Qobj`
The gate matrix that's supposed to be decomposed should be a Qobj.
"""
... | 5e3ff37e8528498e0781486e86b7e938b2330ab0 | 68,196 |
from typing import Dict
def __create_lookup_table(root: __Node) -> Dict[str, str]:
"""
Given the root node of huffman tree, uses dfs to assign code words (bit string) to symbols
Parameters
----------
root : __Node
The root node of huffman tree
Returns
-------
Dict[str, str]
... | c73baa919407090cb5def79101870248d84846ea | 68,197 |
import itertools
def phi1k_local_2vN(ind, Ek_grid, fk, hfkp, hfkm, E, Tba, si):
"""
Constructs Phi[1](k) corresponding to local approximation at Ek_grid[ind].
More precisely, generates local approximation kernels L1 and L0, Phi[1](k) = L0(k)Phi[0],
L1(k)Phi[1](k) = L0p(k)Phi[0], L0 = L1^{-1}L0p.
... | 1a023cab70d729041540eea227e5ef5b2ee966fb | 68,198 |
def player_page(map_code):
"""Page for listing other maps made by author of a map."""
maps_listing_page = map_model.find_maps_by_map_author(map_code)
return jsonify({
'maps': maps_listing_page
}) | 7ad0af658a75d1aee4683ffc7675b1b9b548e298 | 68,199 |
def get_current_branch_name():
"""查询当前分支名
:rtype str
:return 当前分支名
"""
return run_cmd(GitCommand.branch_abbrev).strip() | bce89806b5ee399f51d48966d5218948fe8719f9 | 68,200 |
def zeros_like(img, dtype=None):
"""
:param img: reference image
:param dtype: desired data type (optional)
:return: an Image with the same shape and header, filled with zeros
Similar to numpy.zeros_like(), the goal of the function is to show the developer's
intent and avoid doing a copy, whic... | d3744a04afc30e0e6e0dd78e2816c7c42337aad3 | 68,201 |
async def get_present_godly_training_description(message_content: str, message: discord.Message) -> str:
"""Returns the embed description for the lb_omega event"""
user_name_end = message_content.find("** !")
user_name_start = message_content.rfind('**', 0, user_name_end) + 2
user_name = message_conten... | 5c73d2fe4f8e03ace19c2265300c79df51404cde | 68,202 |
import attr
def _binary_attrs(stamp_default, is_bootstrap = False):
"""Attributes allowed in haskell_binary and haskell_test rules."""
return dicts.add(
toolchains_attrs,
proto_attrs,
settings.attributes,
compile_srcs_options.attrs,
runfile_attrs,
dependency_att... | 3a848cb60dd4dca6a3d4a4a136024efee503b918 | 68,203 |
def pos(number: int) -> int:
"""Used for indexing."""
return 0 if number < 0 else number | 5b4745f067855234fab4f0eb9bc3e8a10d324341 | 68,204 |
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
i, j = action
if not 0 <= i < len(board)\
or not 0 <= j < len(board[0]):
raise ValueError("This is not a valid position on the board")
result_board = deepcopy(board)
result_b... | e422ad7fd5044680686fd66db3ef3485bea96b62 | 68,205 |
def array2df(X_train, feature_names):
"""Convert np array to df, use with correlation matrix"""
return pd.DataFrame(X_train, columns=feature_names) | 55a02a697820157520798d726f890bd0745d905b | 68,206 |
from typing import OrderedDict
def _web_edit_enerpi_encryption_key(key_file_lines):
"""
Return dict for user edition of encryption key
Make Ordered dict like:
==> [(section_name,
OrderedDict([(VARIABLE, (VALUE, 'text', comment=None))])]
:param key_file_lines: Text lines of encryption ... | b0acf82e7c6a2b0755839c09151aa6c7fdb7cfe9 | 68,207 |
def loadData(path, bins, string):
"""Load binned data into a Pandas.DataFrame where first column is datetime,
each columns represent a bin and name each column according to a list of
floats in argument.
Args:
path : string
path to datafile
bins : list
List of floats ... | dc8e9819f4b57be36e4fa1c09aa05eec3f10ca69 | 68,208 |
def time_reversal_asymmetry_statistic(x, lag):
"""
This function calculates the value of
.. math::
\\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} - x_{i + lag} \cdot x_{i}^2
which is
.. math::
\\mathbb{E}[L^2(X)^2 \cdot L(X) - L(X) \cdot X^2]
... | 51e4ca243a67acb3194a52c1a2b27d6b13ea7c41 | 68,210 |
def main(return_outputs=False):
"""main"""
return parse_command(command_depth=0, return_outputs=return_outputs,
**MAIN_CMD_SPEC) | a689b086b0be6b9113733e720740dd323730d78a | 68,211 |
import torch
from typing import Optional
def graclus_cluster(row: torch.Tensor, col: torch.Tensor,
weight: Optional[torch.Tensor] = None,
num_nodes: Optional[int] = None) -> torch.Tensor:
"""A greedy clustering algorithm of picking an unmarked vertex and matching
it wit... | 636f0ad04443db615bee1afaf241f58145767a28 | 68,212 |
def predict_flow(in_planes: int, out_planes: int = 2, bias: bool = False):
""" Convenience function for 3x3 conv2d with same padding """
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1, padding=1, bias=bias) | c2dc742201a22e84a22e70d2de66e83eaf59d043 | 68,213 |
def delete(k):
"""Returns an Anon instance which performs a deletion, using either
__delitem__ or __delattr__ as appropriate. If neither deletion
operator makes sense then an exception is raised. Note that the
following are the valid ways to call this function.
delete(anon[idx])
delete(anon.nam... | 5200d05939fc3aaec4092f0772da8da00dadaa58 | 68,214 |
def read_prot(filepath):
"""
This function accepts the filepath of a protein to align, ignores the first line
(proceeded by '>' char), strips newlines, and returns the protein as a single string.
"""
seq = ""
with open(filepath) as f:
for line in f:
if not line.startswith(">"... | e09fab92fca28601d5c92d927ceddccaaf1f5569 | 68,215 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/names<br/>"
f"/api/v1.0/tobs"
) | edda28124ba8d1eac1fc6bc6931b92743dad0ca5 | 68,217 |
def display_user():
"""
Function to display existing user
"""
return User.display_user() | 86b39c7463f9ce92428b042a1042602c3206c410 | 68,218 |
def test_apply_return_literal(val):
"""
Test unification codepath for scalars and MaskedType
makes sure that numba knows how to cast a scalar value
to a MaskedType
"""
def func(row):
x = row["a"]
y = row["b"]
if x is not NA and x < 2:
return val
else:... | 0a55bbd4fe569ad6be7494024a11030b627ad9e4 | 68,219 |
def aumentar(valor, bonus, view=False):
"""
-> Realiza o calculo de aumento sálarial e retorna seu valor
:param valor: Valor do dinheiro
:param bonus: Porcentagem do bônus
:param view: Verifica se formata ou não o valor
:return: Retorna valor com aumento sálarial
"""
return moeda(valor +... | e7bec1c3ad7d2666401d95457e20c410612aadd7 | 68,220 |
import torch
def polar_transformer(U, out_size, device, log=True, radius_factor=0.707):
"""Polar Transformer Layer
Based on https://github.com/tensorflow/models/blob/master/transformer/spatial_transformer.py.
_repeat(), _interpolate() are exactly the same;
the polar transform implementation is in _tr... | edd5d08ef9a3312622ffce69a69d1f2e7d7199c7 | 68,221 |
def CSMToBinary(D, Kappa):
"""
Turn a cross-similarity matrix into a binary cross-simlarity matrix
If Kappa = 0, take all neighbors
If Kappa < 1 it is the fraction of mutual neighbors to consider
Otherwise Kappa is the number of mutual neighbors to consider
"""
N = D.shape[0]
M = D.shape... | 6937ea6cfd97d1ced8eabb80c757e09d8985a1c0 | 68,223 |
def is_android_project(dirpath):
"""determines if a given directory is an Android Project.
looks for settings.gradle files.
Args:
dirpath: path of the directory.
Returns:
bool: True if file is in diretory, False otherwise.
"""
return "settings.gradle" in [f for f in listdir(dirp... | 6620f451d298b8ca979517b751d2a24d3cae4488 | 68,224 |
def put_ldap_user_schema(
api_client,
ldap_user_base=None,
ldap_user_id_attribute=None,
ldap_user_list_filter=None,
**kwargs
): # noqa: E501
"""Set LDAP user schema settings # noqa: E501
Set LDAP user schema settings # noqa: E501
This method makes a synchronous HTTP request by defau... | c835c17a4e526bfaa98702cade600b773d26353f | 68,225 |
def get_final_winning_proposal_ready():
""" For cool-off period: tries to find final proposal (available in cool-off when all instances have been
evaluated), if none can be found returns 404 """
process_id = int(request.args.get('process-id'))
utils.validate_backend_process_id(process_id)
if cool_o... | 38e2dfeb362ad6294dca6aadfa47c4d4e66bfecf | 68,226 |
def help():
"""Devolve a pagina de Ajuda"""
window_id = str(get_window_id())
set_base_context(window_id)
ctx_dict = get_context(window_id)
ctx_dict['window_id'] = window_id
ctx_dict['name'] = 'help'
ctx_dict['title'] = 'Ajuda'
code = """
<textarea rows="30" class="small-12 larg... | 56f1357166b8b96f69057bab153d3c8d46e95949 | 68,229 |
def get_action_html(action):
"""
Get a html respresentation of the Action
:param action: Model, Action model instance
:returns: String, html description of an Activity Action
"""
return render_to_string('action.html', {'action': action}) | 4fba30d16a5c488db249ec1e416cf8e59153581c | 68,230 |
def ifconfig():
"""
:return: network mode (AP/STA), ifconfig tuple
"""
if NW_IF is None:
return '', ("0.0.0.0", "0.0.0.0", "0.0.0.0", "0.0.0.0")
nw_mode = 'STA'
if_tuple = NW_IF.ifconfig()
if if_tuple[0] == if_tuple[2]:
nw_mode = 'AP'
return nw_mode, if_tuple | a0bb6bf38c993d56801b99a6027f43715b66fce4 | 68,231 |
def _postprocess_for_report(usage_types, missing_values, unusual_changes):
"""Post-process the output of `_detect_anomalies` in order to facilitate
composing final e-mails with anomaly reports.
"""
unusual_changes_ = _filter_out_ack(unusual_changes)
anomalies_ = _merge_by_type(usage_types, missing_v... | 3387328539634b540302c145eb2c4ad50ca5c951 | 68,232 |
from typing import Optional
def cache_put_all(connection: 'Connection', cache_info: CacheInfo, pairs: dict,
query_id: Optional[int] = None) -> 'APIResult':
"""
Puts multiple key-value pairs to cache (overwriting existing associations
if any).
:param connection: connection to Ignite ... | 0931e6b118e0861860bc6c10a019a03a89aaffd8 | 68,233 |
def get_style(forecolor, bold):
"""Generate a style for specified forecolor and has bold or not
:param forecolor: the name of the forecolor.
:param bold: has bold or not.
:return: a style, an :class:`XFstyle` object.
"""
# https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/Style.py
# https:... | 86b806f82480127dd6911c90919cfd140233cd03 | 68,234 |
def extract_neighborhoods_distributed(
spots,
segments,
radius,
ratio=None,
nblocks=10,
cluster_kwargs={},
):
"""
Distribute ``extract_neighborhoods`` with dask
Parameters
----------
spots : string
The filepath to the spots data on disk
segments : ndarray (e.g. z... | 8d1cfa724c5ba921919441501b739c1dda50850a | 68,235 |
def _create_table_query(table_name: str) -> str:
"""Build SQL query to create metrics table."""
return (
f"CREATE TABLE IF NOT EXISTS {table_name}("
f" id SERIAL PRIMARY KEY,"
f" page_url TEXT,"
f" http_code SMALLINT,"
f" response_time INT,"
f" time... | 427bf61a475c0f012b0242880400d1573ae8bbd1 | 68,236 |
def fetch_error_status_from_state_db(port, state_db):
"""Fetch the error status from STATE_DB and return them in a list.
Args:
port: the port whose error status will be fetched.
None represents for all ports.
Returns:
A list consisting of tuples (port, description) and sorted b... | bf4d7537202dd9101630831b1a7cef5d789f101b | 68,237 |
import numpy
def _get_generators_for_reducing_second_m35(diag_entries_first_m35,
einsum_spec, rep_action):
"""Builds the generators for canonicalizing the 2nd 35-irrep."""
gens = _get_residual_symmetry_of_matrix_diagonal(diag_entries_first_m35)
m = numpy.zeros([len(ge... | b9ca2b3d66aab6aaebf055d5724c3716a0e817d8 | 68,238 |
def count_instance_attributes(listInst):
"""Return the number of attributes across all instances, or None if the
instances differ in the number of attributes they contain.
>>> listInst = [Instance([1,2,3],True), Instance([4,5,6],False)]
>>> count_instance_attributes(listInst)
3
>>> count_instance_attributes([In... | 8fa925d9900973a1e535e7b5a33d2f5fc1f89009 | 68,239 |
def basis_string_pn(basis):
""" basis_string_pn(basis) -> name
Takes basis specified as tuple (basis_name_p, beta_p,
basis_name_n, beta_n) and converts to string for use in filename.
"""
return "%s-%.3f-%s-%.3f" % basis | 3c57bc21314dc944f3025b5e992ec9f6dcb0c1dd | 68,240 |
def to_binary(df, variable_names):
"""
Recode specified variables of dataframe to binary; any positive value is
set to 1 and all other values are set to 0. This replaces the existing
column(s).
Parameters
----------
df : pandas DataFrame
dataframe containing variables to be reco... | 604b5a84a7ade73b9e569fa4d238f32e9039acee | 68,241 |
import csv
def validate(args, limit_to=None):
"""Validate an input dictionary for Finfish Aquaculture.
Parameters:
args (dict): The args dictionary.
limit_to=None (str or None): If a string key, only this args parameter
will be validated. If ``None``, all args parameters will be
... | 8d609f5cef6253a014562c12904e8edc84a03a13 | 68,242 |
def id_values_map(dataset_path, id_field_names, field_names, **kwargs):
"""Return mapping of feature ID to attribute value or tuple of values.
Notes:
There is no guarantee that the ID value(s) are unique.
Use ArcPy cursor token names for object IDs and geometry objects/properties.
Args:
... | 1fe3568be059ef0090ef37c03dd93d17ae9ded9b | 68,243 |
from typing import Union
from typing import Dict
from typing import List
from typing import Optional
def convert_lat_long(obj: Union[Dict, List, None, str]) -> Optional[Coordinates]:
"""Convert a coordinate pair as a dict, list, or string into a pair of floats, if valid"""
if not obj:
return None
... | c19fb908d04650ee8de706db4bb1d936da335dab | 68,245 |
def _separate_sentiment_scores(sentiments):
""" want separate positive versus negative sentiment scores"""
pos_sum = 0.0
neg_sum = 0.0
neu_count = 0
for sentiment_score in sentiments:
if sentiment_score > 0:
pos_sum += (float(sentiment_score) +1) # compensates for neutral words that are counte... | f00f812806faae2bcdcb4a2402fdf665bbfa0dcf | 68,246 |
from typing import Optional
def download_file(url: str, destination: str, timeout: Optional[int] = None,
silent: Optional[bool] = False) -> str:
"""
Downloads file by given URL to destination dir.
"""
file_name = get_file_name_from_url(url)
file_path = join(destination, file_name... | 6da1204f6db15df4d5bc677aea3d3b6f243694ef | 68,247 |
def get_http_body(http_request):
"""Given a HTTP request, return the body."""
return http_request.split("\r\n\r\n")[1] | 4a11c97f0eeddac933e8b311d9c1cfda6e61674c | 68,248 |
def JNMF(data, n_components, init='svd', method='Euclidean', maxIter=10000, verbose=True):
"""Joint Non-negative matrix factorisation.
https://github.com/mstrazar/iONMF/blob/master/ionmf/factorization/model.py for similar
Parameters
----------
data : dict,
data = {
... | 6656d674d0788cf42795f7bb03007484f3ab41c9 | 68,249 |
def query_reverse(viewname, kwargs=None, query_kwargs=None):
"""
Custom reverse to add a query string after the url
Example usage:
url = my_reverse('my_test_url', kwargs={'pk': object.id}, query_kwargs={'next': reverse('home')})
"""
url = reverse(viewname, kwargs=kwargs)
if query_kwargs:
... | 648912377db3d9f3592731c4956f99b7f5b848ec | 68,250 |
def efficientnet_b4(override_params=None, **kwargs):
"""
Constructs a EfficientNet-B4 model.
"""
model_name = 'efficientnet_b4'
blocks_args, global_params = get_model_params(model_name, override_params)
model = EfficientNet(blocks_args, global_params, **kwargs)
return model | 1563854aba2e7ba78a53d0edbbb3f06cf231c5f0 | 68,251 |
def inf_set_max_ea(*args):
"""
inf_set_max_ea(_v) -> bool
"""
return _ida_ida.inf_set_max_ea(*args) | c86134aa293dcd68b699d673eeaffa9994d34366 | 68,253 |
import numpy
def column_period(c:numpy.ndarray, thresh:int=0):
"""
Guess the periodicity of a column of (image) data
Parameters
----------
c : ndarray
Column of data (e.g. pixel values)
thresh : int
Optional threshold (default: 0)
Returns
-------
p : int (or float... | 0f6821832f4e6309da8e8130de27ba9eb7fbf5d4 | 68,254 |
def parse_gn_flags(gn_lines):
"""
Parse lines of GN flags into dictionary
"""
gn_args = {}
for line in gn_lines:
name, var = line.strip().partition("=")[::2]
gn_args[name.strip()] = var.strip()
return gn_args | 98d8f91e9defea1484a569deb70fb7cc62b2c743 | 68,256 |
def swap_suits(cards):
"""
Swap suits to remove most symmetries.
"""
cards_need_swap = cards
new_suit = 5
while cards_need_swap.shape[0] > 0:
suit = cards_need_swap[0,1]
cards[cards[:,1] == suit, 1] = new_suit
new_suit += 1
cards_need_swap = cards[cards[:,1] < 5]
... | 53b60a6719d7dcb9c1b0b74345f331536e77e0fe | 68,257 |
def DeleteNode(pListHead, pToBeDeleted):
"""
在O(1)时间内删除链表结点
:param pListHead:
:param pToBeDeleted:
:return:
"""
if not pListHead or not pToBeDeleted:
return None
if pToBeDeleted.next_ != None:
# 要删除的节点后有节点
pToBeDeleted.val = pToBeDeleted.next_.val
pToBeDe... | 41bfc3ed1c0d6a2eb796e2d4e2170888a907367c | 68,259 |
def st_status(user):
"""
Displays the status text.
"""
return get_st_context(user) | e5112dfcb9c7bb2c316c15a34fdc195718686da7 | 68,260 |
def validate_cnpj(cnpj, autopad=True):
"""Check whether CNPJ is valid. Optionally pad if too short."""
cnpj = clean_id(cnpj)
# all complete CNPJ are 14 digits long
if len(cnpj) < 14:
if not autopad:
return False
cnpj = pad_cnpj(cnpj)
elif len(cnpj) > 14:
return ... | 41afd824310c92e75bb9ac0bb9ea4537e274f99d | 68,261 |
def make_ps_model(src_vocab, tgt_vocab, emb_size=256, hidden_size=512, dropout=.3, pad_idx=0, embedding_matrix=None):
"""
Create pointer softmax seq2seq model from given parameters and pass it to GPU
"""
if embedding_matrix is not None:
err_msg = 'Embedding matrix has inconsistent dimensions'
... | ee6dbf0837acf530bfd8c35f2d40c4a70235043a | 68,262 |
import json
def get_segment_data_marker(segment, with_marker=None):
"""
Get openpype track item tag created by creator or loader plugin.
Attributes:
segment (flame.PySegment): flame api object
with_marker (bool)[optional]: if true it will return also marker object
Returns:
di... | cf37d624fd7a0765c4616b5848418f4719035c21 | 68,263 |
def orthogonal(shape, scale=1.1, name=None):
"""
From Lasagne. Reference: Saxe et al., http://arxiv.org/abs/1312.6120
"""
flat_shape = (shape[0], np.prod(shape[1:]))
a = np.random.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
# pick the one with the correct sh... | 93122ef41c3278012860ec715f92abaab40c9653 | 68,264 |
def cqt_to_mcft(sig_cqt,fbank_scale_rate):
"""
This function receives the time-frequency representation (CQT)
of an audio signal (complex in general) and generates a 4-dimensional
representation (scale,rate,frequency,time) by 2d filtering based
on the cortical part of Chi's auditory model.
Inpu... | d109efd60373a478dbb18fb0bf8b05b21152e510 | 68,265 |
def relbw_pdf_func(x, m, gamma):
"""Calculate the relativistic Breit-Wigner PDF.
Args:
x: value(s) for which the CDF will be calculated.
m: Mean value
gamma: width
Returns:
`tf.Tensor`: The calculated PDF values.
Notes:
Based on code from this [github gist](... | 135dd085c4e30bd3e9b20516d14c695e4bc5d3f4 | 68,266 |
def partition_index(is_missing: np.ndarray) -> np.ndarray:
"""
Reshuffle the index with index of observed measurement
first.
For example:
is_missing = [True, False, True, False]
partition_index(is_missing) returns:
np.array([1, 3, 0, 2])
Parameters:
----------
is_missing : li... | dccc6b7e74a90958480ee7408919b4fd0a216d4d | 68,268 |
from typing import Dict
def _lower_to_native_backend(
model: QuantizedGraphModule,
qconfig_map: Dict[str, QConfigAny]
) -> QuantizedGraphModule:
""" Lower a quantized reference model (with reference quantized operator patterns)
to the native backend in PyTorch (fbgemm/qnnpack), both backends shares th... | 4ce101fce1d0f372518cae6e10aec615c8e60108 | 68,269 |
def from_json(data: JsonDict) -> AttributeType:
"""Make an attribute type from JSON data (deserialize)
Args:
data: JSON data from Tamr server
"""
base_type = data.get("baseType")
if base_type is None:
raise ValueError("Missing required field 'baseType'.")
for primitive in Primit... | 0d85ee57ca148607f0d19501377c52a82df5f558 | 68,270 |
from typing import Iterable
from typing import Callable
from typing import Union
from typing import Tuple
def group_and_apply(
df: pd.DataFrame,
group_by_cols: Iterable[str],
apply_fn: Callable,
output_meta: Union[pd.DataFrame, pd.Series, dict, Iterable, Tuple],
num_dask_partitions: int=1,
use... | 9e78526877dd3d91eed7852312f61e663c89d29e | 68,271 |
from wmiexec import WMIEXEC
from wmiexec import WMIEXEC
def execute_cmd(
cmd_str,
ipaddr,
username,
password,
download_url,
domain="",
share="ADMIN$",
noOutput=False,
):
"""execute command"""
try:
except ImportError:
download_file(download_url + "/wmiexec.py")
... | bf8dc66baebcb721c9cf47519d5e521fa0d764fb | 68,272 |
def dist_score(param_list, meta):
"""
Measure delta between USE endcodings
Param 1 - First encoding from text
Param 2 - Second ecoding from text
"""
# data = {
# 'op': 'dist_score',
# 'encoding': [param_list[0], param_list[1]]
# }
# return USE_API.post(data)['score']
... | 8aadbf024ef0cf03d3c8b9539f170023390f9951 | 68,274 |
from typing import Tuple
def scale_minmax(x: np.ndarray, xrange: tuple = None) -> Tuple[np.ndarray, bool]:
"""
Minmax scaling to [0,1].
Parameters
----------
x
Numpy array to be scaled.
xrange
Tuple with min and max data range.
Returns
-------
Scaled array and boo... | 5186c0a8f0ab039599b622fa0f6f619597838bd7 | 68,275 |
def procrustes_align(base_embed, other_embed):
"""
Align other embedding to base embeddings via Procrustes.
Returns best distance-preserving aligned version of other_embed
NOTE: Assumes indices are aligned
"""
basevecs = base_embed.m - base_embed.m.mean(0)
othervecs = other_embe... | 88773c1bc1939ddb2811e0622315a76d9d39775f | 68,276 |
def format_wal_properties(body: Json) -> Json:
"""Format WAL properties.
:param body: Input body.
:type body: dict
:return: Formatted body.
:rtype: dict
"""
result: Json = {}
if "allowOversizeEntries" in body:
result["oversized_ops"] = body["allowOversizeEntries"]
if "logfil... | 7e9b7b2a1a4b69a7d2ca2dfb93938b5121149c90 | 68,277 |
def model_fn(features, labels, mode, params):
"""Estimator のためのモデル定義メソッド
# メソッドの構成は以下のとおり
# 1. Keras の Functional API 経由でモデルの設定を記述
# 2. Tensorflow を使って,学習・評価時の損失関数を定義
# 3. Tensorflow を使って,学習時のオペレータ・オプティマイザを定義
# 4. Tensorflow の tensors として予測値を取得
# 5. 評価用のメトリクスを生成
# 6. 予測値・損失関数・学習オペ... | 361b129513843700da179b6b7b9f9471a8f004ea | 68,278 |
def forcing_accumulator(temperature):
""" The accumulated forcing for each observation
and doy in the (obs, doy) array.
"""
return temperature.cumsum(axis=0) | 4813d7cb019001b038ef71c143c9e3db696af9ca | 68,279 |
import base64
def FormatVariable(message, output_value=False):
"""Returns the variable message as a dict with a shortened name.
This method first converts the variable message to a dict with a shortened
name and an atomicName. Then, decodes the variable value in the dict if the
output_value flag is True.
... | 844a31c5778896520393c2c18ec2887b3d9a8004 | 68,281 |
def _make_body_from_sub_request(sub_request):
"""
Content-Type: application/http
Content-ID: <sequential int ID>
Content-Transfer-Encoding: <value> (if present)
<verb> <path><query> HTTP/<version>
<header key>: <header value> (repeated as necessary)
Content-Length: <value>
(newli... | c0abceabd8e0047326e0ab2f5e30f6e7dcd4702f | 68,282 |
def floor(x,unit=1):
""" Returns greatest multiple of 'unit' below 'x' """
return unit*int(x/unit) | b289bf714eb3ecf23072533a51badeac43743686 | 68,283 |
import six
import json
def http_response_json(dict_data, encoding='utf-8'):
"""
返回json数据
:param encoding:
:param dict_data:
:return:
"""
# ensure_ascii=False,用来处理中文
try:
if six.PY3:
# if isinstance(dict_data, binary_type):
# dict_data =
... | 543993c2a3ade164ee138dfd66c06bcef3db0cfd | 68,284 |
def gen_vault_response_kv1(file_contents):
"""
Provides the vault response for a given processed configuration file
"""
def _gen_vault_repsonse(file_contents=file_contents, secret_key=""):
if secret_key != "":
vault_response = {"data": {secret_key: file_contents}}
else:
... | fa9fdda0ac28d2bea2cea4bb4fd24456c1013c2d | 68,285 |
def active_contour_loss(gt, pr, w_region=1.0, w_region_in=1.0, w_region_out=1.0):
"""
length term
"""
x = pr[:,1:,:,:] - pr[:,:-1,:,:]
y = pr[:,:,1:,:] - pr[:,:,:-1,:]
delta_x = x[:,1:,:-2,:]**2
delta_y = y[:,:-2,1:,:]**2
delta_u = K.abs(delta_x + delta_y)
length = K.mean(K.sqrt(d... | 161beb5a56c5a817cd14e860b1843baabb709c60 | 68,286 |
import requests
def get_repository(repo_name):
"""
Fetches a github repository. Receives a repository full name. E.g.
'h3nnn4n/garapa'
"""
auth = get_auth()
result = requests.get(
f'https://api.github.com/repos/{repo_name}',
auth=auth
)
rate_limit_update(result.header... | 766f6d2fbf065750ce0167be4cb830020caa8cd8 | 68,287 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.