content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def init_obj_discrete(env_fn_discrete):
"""
Instantiate a PolicyWithValue class object
"""
MyNet = PolicyWithValue(
policy_net = 'mlp',
env = env_fn_discrete,
normalize_observations=False
)
return MyNet | 1562319bcf87fb690554d216a2ef9c6a49115873 | 40,512 |
def new_norm(graphs_, bl_feat):
"""Normalize graph function uniformly"""
newnorm = dict(zip(bl_feat, [0] * 5))
for attr in bl_feat:
for gs in graphs_:
for g in gs:
tmp = max(nx.get_node_attributes(g, attr).values())
if tmp > newnorm[attr]:
... | 64f1583ddbe8db04ab110ac71a78f287e0c46af2 | 40,513 |
def in6_and(a1, a2):
"""
Provides a bit to bit AND of provided addresses. They must be
passed in network format. Return value is also an IPv6 address
in network format.
"""
return _in6_bitops(a1, a2, 1) | 501e8029aa7926eded96740ce15f5e3e96b66f0c | 40,514 |
def send_data(socket_path, data):
"""Send data to the socket path.
The send method takes serialized data and submits it to the given
socket path.
This method will return information provided by the server in
String format.
:returns: String
"""
with UNIXSocketConnect(socket_path) as s... | 5cb7caa55943093dcf4b951068cbeab2b9a76c8a | 40,515 |
import functools
def nim(heaps, game_type, output=True):
"""
Computes next move for Nim, for both game types normal and misere.
if there is a winning move:
return tuple(heap_index, amount_to_remove)
else:
return 0, 0
- mid-game scenarios are the same for both game types
>>> ... | 3f39792d0d30335b8b6915fb3c73d76beb4740f4 | 40,517 |
import ctypes
def get_positions(p_state, idx_image=-1, idx_chain=-1):
"""Returns a `numpy.array_view` of `shape(NOS, 3)` with the components of each spins position.
Changing the contents of this array_view will have direct effect on the state and should not be done.
"""
nos = system.get_nos(p_state, ... | ce783050d8ea44738e7febf7a8cd0ae079a067f6 | 40,518 |
def image_dataset_from_tfrecords(globs,
tag,
image_shape,
batch_size = 0,
shuffle = True,
repeat = -1):
"""Loads images from sharded TFRecord files.
A... | 6e72f4d98ee7adfa45dd6b2dbebc9abc0fcfb4d8 | 40,519 |
def get_writer(_):
"""
Returns the writer class.
"""
return LunrWriter | 972cbe7eaa1a0102acae3c5776395b11c7f792c8 | 40,520 |
def test_logo():
"""
Plot the GMT logo as a stand-alone plot.
"""
fig = Figure()
fig.logo()
return fig | 25b9e05536981bb6c77ca557b9f7601f088311dc | 40,521 |
def SRL32(init=0, has_shiftout=False, has_ce=False):
"""
Configure a Slice as a 32-bit shift register
[I, A[5]] -> O
@note: SRL32's can be chained together using SHIFTOUT and SHIFTIN.
In that case, an SRL32 does not generate any output.
"""
if isinstance(init, IntegerTypes):
i... | 706d7ade96e18c7f47236d0bb2be386faf136ae4 | 40,523 |
def compute_peak_valley(rip: DataStream,
rip_quality: DataStream,
fs: float = 21.33,
smoothing_factor: int = 5,
time_window: int = 8,
expiration_amplitude_threshold_perc: float = 0.10,
... | e794f9f49bbec301901970cc1c9700b16943bce3 | 40,524 |
def WaveguideConnect(port1: "DevicePort",port2: "DevicePort",
rad: float = 3):
"""
Simple waveguide connector for two ports. Given a start port and an
end port, the function attempts to connect the ports using
a sequence of straight lines (sequencer command S), 90 degrees bends
... | baf7d48b6cc0e27ea9a1b0797bd781260670e62c | 40,525 |
def convert_title(original_title):
"""Remove underscores from string"""
new_title = original_title.replace("_", " ").title()
new_title = new_title.replace("Api", "API")
return new_title | 34e6441bda4ae1cfe0c092b407c6b0579fe3277f | 40,526 |
import types
def type_from_outputs(outputs):
"""
:param outputs: [ Theano Variable ]
:returns: pykit return type
"""
result_types = [map_type(v.type) for v in outputs]
if len(outputs) > 1:
result_type = types.Tuple(result_types)
else:
result_type, = result_types
... | e30efe5b8b7083a61ac63976a690579d0981f277 | 40,528 |
from typing import OrderedDict
def analyze_sentiment(text, **kwargs):
"""
Analyzing Sentiment in a String
Args:
text_content The text content to analyze
"""
if not text:
return "Syntax: /analyze_sentiment <your text here>"
client = language_v1.LanguageServiceClient()
# Av... | b0ce560e778366c68bb8efec1e27f035d40508d0 | 40,529 |
def abbreviate_for_xray(payload: dict) -> dict:
"""
If the payload includes a file, the file is translated
to just it's name and size instead of including the
whole file.
"""
for k in payload.keys():
v = payload.get(k)
if isinstance(v, File):
v = {"type": v.type, "siz... | f46eab117e41b5ed257250d00e64da3b85041f7a | 40,530 |
def get_version(release):
""" Given x.y.z-something, return x.y
On ill-formed return verbatim.
"""
if '.' in release:
sl = release.split(".")
return '%s.%s' % (sl[0], sl[1])
else:
return release | 520438d5ca260caf27df31c4742d9da8c31f3218 | 40,531 |
def arrays_shape(*arrays):
"""Returns the shape of the first array that is not None.
Parameters
----------
arrays : ndarray
Arrays.
Returns
-------
tuple of int
Shape.
"""
for array in arrays:
if array is not None:
shape = array.shape
... | e9e6a4876b938934c843386dffc58f0eccfb20a3 | 40,532 |
def get_coords_2d(obj, P):
"""
calculate the image (2d) coordinates of the 3d bounding box
of an object.
"""
bbox3 = get_coords_3d(obj)
# Rl = obj.Rl
# height = obj.height
# width = obj.width
# length = obj.length
# x = obj.x
# y = obj.y
# z = obj.z
# bbox = np.array(... | 6a0c079addab8a4379f7eafcb90094bdb8188383 | 40,533 |
def setPanicProperty(prop, value):
"""
Method to write global properties
It manages compatibility with PANIC <= 6 using PyAlarm properties
"""
print('setPanicProperty(%s, %s)' % (prop, value))
r = get_tango().get_property('PANIC',[prop])[prop]
o = get_tango().get_class_property('PyAlarm',[p... | 34ba09d338d4ff91a3df7b868f0e662c4119ae35 | 40,534 |
import math
def gridSquare(eastings, northings, squaresize):
"""Returns the appropriate National Grid Reference including 100km letters.
eastings: in metres between 0 and 700000
northings: in metres between 0 and 1300000
squaresize: in kilometres, valid values are 100,10,5,1,0.5,0.1,0.01,0.001
""... | 4149b49c426c895798dcf55a7973370764f06f03 | 40,535 |
def findGenSubClasses(superclass):
"""Find all Generator sub-classes of a certain class, e.g. ODEsystem."""
assert isinstance(superclass, str), \
"findGenSubClasses requires a string as the name of the class to search for subclasses."
subclasslist = []
sc = eval(superclass)
for x in theGe... | a0510e3eb67297483f99ce0326e6be9fe05f211b | 40,536 |
def PSQRT(N, C, M, A):
"""
PSQRT finds the first m + 1 coefficients of the square-root power series
$$ (c_0 + c_1 \, z + \cdots + c_n \, z^n) ^{0.5} = a_0 + a_1 \, z +
+ a_2 \, z^2 + \cdots $$
p. 32
"""
A[0] = SQRT(C[0])
TA = 2 * A[0]
A[1] = C[1] / TA
A[2] = (C[2] - A... | f6a9d11adc39e8b345c859c187c88d5f786837d8 | 40,539 |
def load_manga(f):
""" Load manga object by query manga_id into g.manga
"""
@wraps(f)
def wrapper(manga_id, *args, **kwargs):
manga = Manga.query.get(manga_id)
if not manga:
return jsonify({
'code': 404,
'message': 'Not Found'
}), 4... | 53b71245ca84466cbde8dec3f28414b9d167bfe9 | 40,542 |
def pln_reflection_basis(pt_coord, pln_pt, pln_normal):
"""
Symétrie mirroir, en 3D, par rapport à un plan.
Le plan est défini par une normale et un point contenu dans ce plan.
"""
# ? laisser la possibilité d'utiliser directement un np.array ou une liste
# ? pour donner les coordonnées pour plu... | aa6269ce06337b8dbcda50a232e521ed663af22e | 40,543 |
import asyncio
def global_bluetooth_lock():
"""Initialize the global bluetooth lock inside the current event loop."""
global GLOBAL_BLUETOOTH_LOCK # pylint: disable=global-statement
if GLOBAL_BLUETOOTH_LOCK is None:
GLOBAL_BLUETOOTH_LOCK = asyncio.Lock()
return GLOBAL_BLUETOOTH_LOCK | 6494062b3ae2a7718725d83b25a4866288c0085d | 40,544 |
def max_profit(prices):
"""
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock),
design an algorithm to find the maximum profit.
Note that you cannot s... | 056dff9d2ad4af9d38f2ce0f1ad27c1c0df69121 | 40,545 |
def intrinsic_photo_all(
request,
category_id='all',
filter_key='all',
template="intrinsic/photo_all.html",
extra_context=None):
""" View judgements in images with each image taking up a block and the
list of photo categories on the left """
entries = Photo.objects.... | d74ef53fbb16a4f574408f60e4ec7e281220f004 | 40,546 |
def get_authenticated_api_session(username, password):
"""
:return: an authenticated api session
"""
session = MoJOAuth2Session(
client=LegacyApplicationClient(
client_id=settings.API_CLIENT_ID
)
)
session.fetch_token(
token_url=get_request_token_url(),
... | 98fec31770dc73e714b6b80062a8ee218cf23c9d | 40,547 |
def add_customer_invoice(customer_invoice_data):
"""
添加信息
:param customer_invoice_data:
:return: None/Value of user.id
:except:
"""
return db_instance.add(CustomerInvoice, customer_invoice_data) | 4f8ae6dfacfcb1c1b0b94a7143b045fe60988987 | 40,548 |
def model_as_json(bot_entries):
""" Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB
@param
bot_entries (list) list of sub-lists
@returns
json_list (list) list of modeled dictionaries
"""
... | e18d4c29cdeda950bd0b32db5354f197e38f27ff | 40,550 |
def encompasses_broadcastable(b1, b2):
"""
Parameters
----------
b1
The broadcastable attribute of a tensor type.
b2
The broadcastable attribute of a tensor type.
Returns
-------
bool
True if the broadcastable patterns b1 and b2 are such that b2 is
broad... | 297a709a4f27de85952f48d112013001a7b6b433 | 40,551 |
import types
import numba
def get_key_dict_overload(arr):
"""returns dictionary and possibly a byte_vec for multi-key case
"""
# get byte_vec dict for multi-key case
if isinstance(arr, types.BaseTuple) and len(arr.types) != 1:
n_bytes = 0
context = numba.targets.registry.cpu_target.tar... | f833eb66ecca66394d0322cb41903695212bff29 | 40,552 |
def week():
"""Get latest weekly ranks."""
url = f"{BASE_URL}/week/index.htm"
return utils.get_ranks(url, SELECTOR, parser) | d5bcf3244ecd55f126af9b17db7c33187d1474fa | 40,554 |
def cone(toplexes, subcomplex, coneVertex="*"):
"""Construct the cone over a subcomplex. The cone vertex can be renamed if desired. The resulting complex is homotopy equivalent to the quotient by the subcomplex."""
return toplexes + [spx + [coneVertex] for spx in subcomplex] | 6b1328a2f7c32988666b0c7039efd0ce6ecdffef | 40,555 |
from typing import Any
async def read_item(
*,
con: AsyncIOConnection = Depends(db.get_con),
item_id: UUID,
current_user: schemas.User = Depends(auth.get_current_active_user),
) -> Any:
"""
Get item by id.
"""
item = await crud.item.get(con, id=item_id)
if not item:
raise H... | 8dbc91c0e17e84ed99b3e74e719e12da0f8b1d75 | 40,556 |
from typing import List
async def get_max_power(
token: str,
cups: str,
distrubutor_code: int,
start_date: str,
end_date: str,
authorized_nif: str = None,
) -> List[MaxPower]:
"""Search the maximum power and the result will appear in kW
Args:
token (str): Bearer token
... | 7a4d5d99f8927be64582333453cbacd90b5c93ac | 40,557 |
import logging
def filter_remove_keyword_images(keywords_set, keyword_list, use_lemma=True):
"""Filter keyword-image pairs removing all images with keywords in the specified list.
NOTE: this should be used instead of `filter_remove_images` to remove all
image instances associated with remove keyword, inc... | cce733abd5d224ceb66d2e2645b06d6c4e6dc237 | 40,558 |
def replace(correct, guess, correct2):
"""
Find out if your guess is in the correct answer or not, if yes, put it into your answer
"""
ans = ''
i = 0
for ch in correct:
if guess == ch:
ans += correct[i]
else:
ans += correct2[i]
i += 1
# for i i... | aacd9142599cc815a5526350c96b4db09b74777d | 40,559 |
def V_morse_1dof(x, par):
"""
Parameters
----------
x : TYPE
independent variable value of the potential energy function.
par : TYPE
parameters of the potential energy function.
Returns
-------
V : TYPE
potential energy of the 1 DOF morse oscillator system ... | 8f91a99af2e8b755b2756c8820f0fe044da1999a | 40,560 |
def broadcastable(shape_1, shape_2):
"""Returns whether the two shapes are broadcastable."""
return (not shape_1 or not shape_2 or
all(x == y or x == 1 or y == 1
for x, y in zip(shape_1[::-1], shape_2[::-1]))) | 9a968fdee4a401b5f9cee42286de7553afa02183 | 40,561 |
import json
from datetime import datetime
def getAccount():
"""
API has been changed to accept only POST requests. Path of API has been changed.
Now the body of POST must be
{
"username" : 17BECXXXX,
"password" : password
}
"""
# First check if query is okay or not
dat... | 3976aa5b30ee90e11396269149d2b752bfbd35db | 40,562 |
def mesos_cluster_memory_resource_total_range(cluster_id, start, end):
"""mesos集群内存总量, 单位MB"""
step = (end - start) // 60
prom_query = f"""
max by (cluster_id) (bkbcs_scheduler_cluster_memory_resource_total{{cluster_id="{cluster_id}"}})
""" # noqa
resp = query_range(prom_query, start, end, ... | b551c6d4430e3d6bb11d5869801143a3ad794215 | 40,563 |
def bipartite_sets(bg):
"""Return two nodes sets of a bipartite graph.
Parameters:
-----------
bg: nx.Graph
Bipartite graph to operate on.
"""
top = set(n for n, d in bg.nodes(data=True) if d['bipartite']==0)
bottom = set(bg) - top
return (top, bottom) | 618756dbfa87dc0b5d878545fa5395c4a122c84c | 40,564 |
def find_mqtt_topic(name: str) -> str:
"""
Based on the button name find the corresponding mqtt command
"""
if name == BUTTON_SHUFFLE:
return PHONIEBOX_CMD_PLAYER_SHUFFLE
if name == BUTTON_SCAN:
return PHONIEBOX_CMD_SCAN
if name == BUTTON_REWIND:
return PHONIEBOX_CMD_PLAY... | 6856c45c5b2f9d7ac446988f55838ce6fd6601e0 | 40,568 |
def next(aList, index):
""" Return the index to the next element (compared to the element
with index "index") in aList, or 0 if it already is the last one.
Useful to make a list of loop.
"""
return (index+1) % len(aList) | d3bae9776d32cf1f52bb325cb0a7d9f3ff622d6c | 40,569 |
def load_shp_data(path, drivername='ESRI Shapefile'):
"""
Returns shp file dataset
Parameters
----------
path : str
Path to shp file
drivername : str, optional
ogr driver name (default: 'ESRI Shapefile')
Returns
-------
shp : object
shp data object
"""
... | 4a8c05c950f7245f0322a71467fcd77f8872c583 | 40,570 |
def test_rshift_into_node(clear_default_graph):
"""Test the node rshift operator with an INode as target.
Note that OutputPlug >> INode is tested in the plug tests."""
@Node(outputs=["marker"])
def Node1():
return {"marker": None}
@Node(outputs=[])
def Node2(marker):
return {}
... | daec45c84656a298c4492a89aba589d44a519b45 | 40,571 |
def htmlize(widget):
"""
Jinja filter to render a widget to a html string
"""
html = widget.render(widget)
try:
html = html.decode('utf-8')
except Exception:
pass
return html | a6c4aeac2bc27aeaaccbe78b893ca33181234169 | 40,572 |
def parallel_pre_compile_op(job: TbeJob):
"""
Parallel pre compile op
:param job:
:return:
"""
compute_op_info_list = get_compute_op_list(job.content)
if len(compute_op_info_list) != 1:
job.error("Invalid op compute num ({}) in pre compile op".format(len(compute_op_info_list)))
... | 52f4291c176293e56879701242183a21beb36c94 | 40,574 |
def transformFromOutputMatrix(curveMatrix=None, transformType='locator', showLocalAxis=True):
"""create a connected transform for each output.outputMatrix"""
curveMatrix = (mc.ls(curveMatrix, type='prCurveMatrix') or
mc.ls(sl=True, type='prCurveMatrix') or
[None])[0]
tr... | 896b011473f0c2b599dd5c88335d3a9d705045a2 | 40,575 |
def search_sensor_id(endpoint: str) -> int:
""" Retrieve list of connected sensors from:
Integration: VMware Carbon Black EDR (Live Response API).
Command: cb-list-sensors.
Args:
endpoint: Endpoint name - hostname/IP
Returns:
str: sensor id if found else empty string... | 2ef2fe246f379fef4d5288199ffbb272de00ff81 | 40,576 |
import time
def get_packing_recipe(args, sequence_lengths):
"""Given program arguments and a list of sequence lengths return the packing recipe.
A "packing recipe" primarily consists of a set of strategies "strategy_set" and the "mixture"
which states how many times each one of these strategies should be... | 16378a0f33e7fd2f4d0d7411b628d882178a3715 | 40,577 |
def _merge_block(internal_transactions, transactions, whitelist):
"""
Merge responses with trace and chain transactions. Remove non-whitelisted fields
Parameters
----------
internal_transactions : list
List of trace transactions
transactions : list
List of chain transactions
... | b60c9cde133d97ac84b2899956a15a72c720bbaa | 40,578 |
from typing import Type
from re import T
def parse_item(location: str, item_type: Type[T], item_name_for_log: str = None,
file_mapping_conf: FileMappingConfiguration = None,
logger: Logger = default_logger, lazy_mfcollection_parsing: bool = False) -> T:
"""
Creates a RootParser()... | ca0eb0cc35edc850d64027ef0e5ce77e50fbd841 | 40,581 |
from re import T
from operator import ne
def tpow(x: T.Tensor, a: float) -> T.Tensor:
"""
Elementwise power of a tensor x to power a.
Args:
x: A tensor.
a: Power.
Returns:
tensor: Elementwise x to the power of a.
"""
return ne.evaluate('x**a') | 21c249561fdbac398dca6d0f0cb2b4655cde7ba7 | 40,582 |
def get_last_price(base,quote, return_price_only):
"""
Args:
'DOT', 'USDT'
"""
tickers = spot_api.list_tickers(currency_pair=f'{base}_{quote}')
assert len(tickers) == 1
t = tickers[0]
if return_price_only:
return t.last
logger.info(f"GET PRICE: {t.currency_pair} | last={... | 42921f8eebce8ce59506305444ee4c4bfe2be851 | 40,583 |
import hashlib
def decrypt_lsa_key_nt5(lsakey, syskey):
"""
This function decrypts the LSA key using the syskey
"""
dg = hashlib.md5()
dg.update(syskey)
for i in xrange(1000):
dg.update(lsakey[60:76])
arcfour = RC4(dg.digest())
deskey = arcfour.encrypt(lsakey[12:60])
return... | 90243119f42a0df473fe1f9c1028808295ba660d | 40,585 |
def __iot_policy_version_exists(cleaner, iot_policy_name, iot_policy_version_id):
"""
Verifies if a policy version exists. This is should be replaced once iot supports Waiter objects for policy
deletion.
:param cleaner: A Cleaner object from the main cleanup.py script
:param iot_policy_version_id: C... | e45954b0f02b04081d30c0cec61c36f26d04acfb | 40,586 |
from typing import Callable
def milne_predictor_corrector_method(f: Callable[[float, float], float],
y0: float,
x: list[float],
h: float,
yl: list[float]) -> float:
"... | 9e8b10bb5689a906c1f3f7774138ea5f3203e06e | 40,587 |
def value_at_risk_percent(df: pd.DataFrame, t: int, period=10, alpha=0.95, price_col='Close'):
"""Calculates the Value at Risk (VaR) of time period
"""
# t must be bigger than 2 to evaluate percentile
if t-period+2 < 0:
var_df = df.iloc[1:t+1]
else:
var_df = df.iloc[t-period+1:t+1]
... | 37fa5e3bfdcafbd9dbb25bb6e056c4c8639990b0 | 40,588 |
from pathlib import Path
def read_xml(f: Path) -> ElementTree.Element:
"""Read an XML file and return the root"""
with open(f, "r") as xml_file:
return ElementTree.XML(xml_file.read()) | 9a145aeb2d5c7e79825984cc75fc53bd1d89c209 | 40,589 |
def dcg_score(y_true, y_score, k=10, gains="exponential"):
"""Discounted cumulative gain (DCG) at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
Predicted scores.
k : int
... | e7c3cc8a2c31b173cf19cfd2b19c8a37f9aa9345 | 40,590 |
from pathlib import Path
def get_resource_file(resource_name):
"""
:param resource_name: The name of the resource file placed in `SFUTranslate/resources` directory
:return: an object of `pathlib.PosixPath` which can be directly opened or traversed
"""
return Path(get_resources_dir(), resource_name... | fe3b8f289cd2e2a06dfb0e42a15707152dd6e946 | 40,591 |
def _conv_number(number, typen=float):
"""Convert a number.
Parameters
----------
number
Number represented a float.
typen :
The default is ``float``.
Returns
-------
"""
if typen is float:
try:
return float(number)
except:
... | f34bd409c78f25e2179e4f72a6e039ff04432392 | 40,592 |
def is_simple_path(G: nx.Graph, path: VertexList) -> bool:
"""Is the path simple in the graph?
Args:
G: input graph
path: Ordered sequence of vertices
Returns:
True if the path is simple in the graph
"""
return is_walk(G, path) and len(path) == len(set(path)) | d276ff9176c44ae630f59b6274f26cec6d4036e5 | 40,593 |
from datetime import datetime
def str_to_datetime(sdt: str) -> datetime:
"""try convert str to datetime with DATETIME_TYPE format until no exception"""
if sdt:
for k in DATETIME_TYPE:
try:
return datetime.strptime(sdt, k.value)
except:
pass
... | 8d945c7fa5e7ddbd7c58e6a9cfc110b474c4615f | 40,595 |
def remove_virtual_slot_cmd(lpar_id, slot_num):
"""
Generate HMC command to remove virtual slot.
:param lpar_id: LPAR id
:param slot_num: virtual adapter slot number
:returns: A HMC command to remove the virtual slot.
"""
return ("chhwres -r virtualio --rsubtype eth -o r -s %(slot)s "
... | 2c6f14949910865f3a60c0016b4587088441572e | 40,596 |
from datetime import datetime
def daily_quota(day=None):
"""Return the daily quota for a given day.
:param day: date object (defaults to today)
"""
if day is None:
day = datetime.today()
if HAPPY_HOUR_START <= day and day < HAPPY_HOUR_END:
return HAPPY_HOUR_QUOTA
elif day.wee... | 9d5f67834e1e6cd43b85b0b85a1af4f73521eeaa | 40,597 |
import json
def dict_to_bytestring(dictionary):
"""Converts a python dict to json formatted bytestring"""
return json.dumps(dictionary).encode("utf8") | 31e201d87e92075d6078450ad019cc51f474f9d4 | 40,598 |
def login():
"""
Login user to ZenType account.
"""
r = request.get_json()
user_email = r.get('email', None)
user_password = r.get('password', None)
userDO = UserAuth.find_user_and_validate_password(
email=user_email,
password=user_password
)
if userDO is not None:
# if the user was created successfu... | 7dcb2e6bdd3d67f1f4a83c2c0c62e8901d291dae | 40,599 |
from typing import Literal
def DataClass(name, columns, constraint=None):
"""
Use the DataClass to define a class, but with some extra features:
1. restrict the datatype of property
2. restrict if `required`, or if `nulls` are allowed
3. generic constraints on object properties
It is expected... | 4305c5f85ead063b0bf4e71235333cbc43a3cef1 | 40,600 |
def _run_prop_dos(
frequencies, mode_prop, ir_grid_map, ir_grid_points, num_sampling_points, bz_grid
):
"""Run DOS-like calculation."""
kappa_dos = KappaDOS(
mode_prop,
frequencies,
bz_grid,
ir_grid_points,
ir_grid_map=ir_grid_map,
num_sampling_points=num_samp... | ec031e31eb752cbe4cfd7219255382f4be325bb2 | 40,601 |
def load_data(database_filepath):
"""
Read the input database to create and return separate numpy arrays for
messages, category values, and names of categories respectively
"""
# creating sqlite engine to interact with database
engine = create_engine('sqlite:///'+database_filepath)
df =... | 115f9a72534aa8a528b15decf9373ee73e05dc10 | 40,602 |
import warnings
def Client(**kwargs):
"""Get a SoftLayer API Client using environmental settings.
Deprecated in favor of create_client_from_env()
"""
warnings.warn("use SoftLayer.create_client_from_env() instead",
DeprecationWarning)
return create_client_from_env(**kwargs) | 8d59c34ffba44de2254cf63297553c49240dd7f0 | 40,603 |
def _merge_candidate_name(src, dest):
"""Returns the formatted name of a merge candidate branch."""
return f"xxx-merge-candidate--{src}--{dest}" | a08b6d4b57385bc390e649448ce264cffd5a1ffa | 40,604 |
def feature(enabled=True, default_rule=True, conditions=True, operator=None):
"""Generates feature structure like parsed JSON from server"""
return {
'key': fake.word(),
'variantSalt': fake.word(),
'enabled': enabled,
'offVariantKey': fake.word(),
'rules': [rule(default_... | 4f7f76304e1dadbb75107beb246359b64f3d800f | 40,605 |
import pandas
def to_datetime(
arg,
errors="raise",
dayfirst=False,
yearfirst=False,
utc=None,
box=True,
format=None,
exact=True,
unit=None,
infer_datetime_format=False,
origin="unix",
):
"""Convert the arg to datetime format. If not Ray DataFrame, this falls
bac... | a14bfea0c0e60fe7094cffb3482101ddabeb1c02 | 40,606 |
def cv_process(data=None, current_column=1, potential_column=0, area=5, reference='she', thermo_potential=0, export_data=False, save_dir='processed', **kwargs):
"""
Processes cyclic voltammetry data
Can either process pre-loaded data or load and process data files. If called with no arguments, loads and processes a... | 8a2c26fb84d92e45b49072e3ca76e1112625110c | 40,607 |
def OpenNormalFVFile(fv_file, type_str):
"""
Open a normalized frequency vector file and check to make sure it's valid.
The first line of a valid normalized FV file contains the number of vectors
in the file followed by the char ':' and an optional char 'w'.
Subsequent lines contain an optional we... | a0c8ce05adf8b59204a31abf74bc480c4d6eb878 | 40,608 |
import torch
import itertools
import time
def td3(env_fn, actor_critic=core.MLPActorCritic, ac_kwargs=dict(), seed=0,
steps_per_epoch=4000, epochs=100, replay_size=int(1e6), gamma=0.99,
polyak=0.995, pi_lr=1e-3, q_lr=1e-3, batch_size=100, start_steps=10000,
update_after=1000, update_every=50, ... | ea9d322f7180289de34faea66bda5526466d0121 | 40,609 |
def meta(condition):
"""Return a class with a subclassing relation defined by condition.
For example, a dataclass is a subclass of `meta(dataclasses.is_dataclass)`,
and a class which name starts with "X" is a subclass of
`meta(lambda cls: cls.__name__.startswith("X"))`.
Arguments:
conditio... | d10937c24181dc3c259267b469e772dc29ffad7e | 40,610 |
def queue_once_key(name, kwargs, restrict_to=None):
"""
Turns a list the name of the task, the kwargs and allowed keys
into a redis key.
"""
keys = ['qo', name]
# Restrict to only the keys allowed in keys.
if restrict_to is not None:
restrict_kwargs = {key: kwargs[key] for key in res... | 4db9b257716ca7c24b4943bb99e2e7de82a38aff | 40,611 |
def get_outliers(training_data, unlabeled_data, number=10):
"""Get outliers from unlabeled data in training data
Returns number outliers
An outlier is defined as the percent of words in an item in
unlabeled_data that do not exist in training_data
"""
outliers = []
total_feature_count... | 40747dccd40d538cbca87b128db1664b828c08b0 | 40,612 |
def is_cdn_cache_hit(response):
"""Checks the response for evidence of a cache hit on the CDN."""
return is_cloudfront_cache_hit(response) | 9593941226299a2bee129d8fb05210587cc36abd | 40,613 |
def mms_feeps_energy_table(probe, eye, sensor_id):
"""
This function returns the energy table based on
each spacecraft and eye; based on the table from:
FlatFieldResults_V3.xlsx
from Drew Turner, 1/19/2017
Parameters:
probe: str
probe #, e.g., '4' for MMS4
... | 56e88802a553d56aedff92ef0d251d8dc1c98c3c | 40,614 |
def load_jets(hdf5):
"""load_jets(hdf5) -> jets
Loads a list of Gabor jets from the given HDF5 file, which needs to be open for reading.
**Parameters**:
``hdf5`` : :py:class:`bob.io.base.HDF5File`
An HDF5 file open for reading
**Returns**:
``jets`` : [:py:class:`bob.ip.gabor.Jet`]
The l... | a44ae133560ed9e1abc6a2eb29e62dd0b07e8927 | 40,615 |
import math
def build_label_vector(label_dict_list, n_xgrids, n_ygrids, mean_lwh,
xlim=(0.0, 70.0), ylim=(-50.0,50.0), zlim=(-10.0,10.0)):
""" Build the ground-truth label vector
given a set of poses, classes, and
number of grids.
Input:
label_dict_lis... | e5b88aaf2b24fe662ef77bdf2ea1958398023839 | 40,616 |
def get_all_admins_chat_ids():
"""
List all chat ids of admin
"""
session = Session()
admins_chat_ids = [admin.chat_id for admin in session.query(Admin)]
session.close()
return admins_chat_ids | d34b56857da99859da3d38dacc42c4ad8d133001 | 40,617 |
def decorator_with_args(decorator_to_enhance):
"""
This is decorator for decorator. It allows any decorator to get additional arguments
"""
def decorator_maker(*args, **kwargs):
def decorator_wrapper(func):
return decorator_to_enhance(func, *args, **kwargs)
return decorator_... | 1af073daf9e9ac9a8834f3a1484bdfa293b1b2bb | 40,618 |
def get_k_model(Te0, alpha, ni_Al_profile, shot, Ew_fwhm=1300., delta_a=0.06, delta_h=0.01, ne=0.8, num_cores=16):
"""
"""
# Load threshold data from the supplied shot
MST_data = data.load_ME(shot, direction='horizontal')
MST_data = data.load_ME_horiz(MST_data)
Ec_map = MST_data['thresholds'][:,... | 9596a6664df7bd431dd571ad32d0db07b44472da | 40,619 |
def drop_by_activity(df: pd.DataFrame):
"""Drops non-active players from the dataframe. Active players are those
players who have at least one killmail per month that resulted from their
use of a combat-based Frigate-class ship type, for a minimum of 12 months
or more.
Examples
--------
Exa... | 5dd39657553f920736ffdc20edafee34d2a5e159 | 40,620 |
from datetime import datetime
def login(userObj):
"""
If you are using the Auth module and want to track login times as part of the userObj, use this
to set the appropriate state of the user objects last_login field, can be used in conjunction with
``Mojo.Auth.Helpers.login_assistant()`` to round-off ... | a1ce67aee064f3277715724c6a18ea3fd430e7fa | 40,621 |
def generate_intervals(nelements):
"""
Generates all possible permutations of lists that access elements from
boths ends of a list without accessing the middle, and one permutation
that accesses ALL elements of a list.
"""
intervals = list()
for i in range(0, nelements):
interval = l... | 06098fbff3342c369b7334e4447cdf9b3ef1a0ab | 40,622 |
import re
def find_subtype(meta_dict):
"""Find subtype from dictionary of sequence metadata.
Args:
`meta_dict` (dict)
dictionary of metadata downloaded from genbank
Returns:
`subtype` (str)
RSV subtype as one letter string, 'A' or 'B'.
"""
subtype = ''
if '... | 130b8ed61f117a786cf5f5ae49fc75e8b074ef2e | 40,623 |
def multihop_sampling(src_nodes, sample_nums, neighbor_table):
"""根据源节点进行多阶采样
Arguments:
src_nodes {list, np.ndarray} -- 源节点id
sample_nums {list of int} -- 每一阶需要采样的个数
neighbor_table {dict} -- 节点到其邻居节点的映射
Returns:
[list of ndarray] -- 每一阶采样的结果
"""
sampling_re... | 9a6e86ba0daf99ec257ebce3ff2f0609abb42aa6 | 40,624 |
from typing import Union
from typing import Mapping
from typing import Callable
def gen_random_series(
size: int,
dtype: str = "object",
na_ratio: float = 0.0,
str_max_len: int = 100,
random_state: Union[int, np.random.RandomState] = 0,
) -> pd.Series:
"""
Return a randomly generated Panda... | 407945cbaccc2b0b3cc146d3f47d43d64cea1af8 | 40,625 |
def extract_gff3_fields(primer_info):
"""
The gff3 file is a format to annotate locations on a genome.
The gff3 annotations requires locations on the genome, this was not required for creating the primers.
This function computes these locations and prepares the data for the gff3 file
:param primer_i... | 4e8f0fbfc3bff136b3c03d4a2c35648491d42fba | 40,626 |
def flip_label(target, ratio, pattern=0):
"""
Induce label noise by randomly corrupting labels
:param target: list or array of labels
:param ratio: float: noise ratio
:param pattern: flag to choose which type of noise.
0 or mod(pattern, #classes) == 0 = symmetric
int = asymme... | 4c2242b2914c245091a3441082c5887bf840c617 | 40,627 |
def retrieve_stripe_checkout_session(subscription):
"""This function returns a Stripe Checkout Session object or raises an
error when the session does not exist or the API call has failed."""
stripe.api_key = settings.STRIPE_API_SECRET_KEY
return stripe.checkout.Session.retrieve(subscription.stripe_sess... | 306fd92a5f7b0a8be890e7e41bf217aa61facbf6 | 40,628 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.