content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def stemmer(stemmed_sent):
"""
Removes stop words from a tokenized sentence
"""
porter = PorterStemmer()
stemmed_sentence = []
for word in literal_eval(stemmed_sent):
stemmed_word = porter.stem(word)
stemmed_sentence.append(stemmed_word)
return stemmed_sentence | 96337684deb7846f56acf302d1e0d8c8ab9743dd | 3,657,500 |
def _queue_number_priority(v):
"""Returns the task's priority.
There's an overflow of 1 bit, as part of the timestamp overflows on the laster
part of the year, so the result is between 0 and 330. See _gen_queue_number()
for the details.
"""
return int(_queue_number_order_priority(v) >> 22) | e61d6e1d04551ce55a533bfe7805f3358bb8d0ca | 3,657,501 |
def test_generator_aovs(path):
"""Generate a function testing given `path`.
:param path: gproject path to test
:return: function
"""
def test_func(self):
"""test render pass render layer and AOV particularities
"""
assert path in g_parsed
p = g_parsed[path]
... | a67b8f741a19f4d3733ab35699ef11a713e283b5 | 3,657,502 |
from typing import Union
def delimited_list(
expr: Union[str, ParserElement],
delim: Union[str, ParserElement] = ",",
combine: bool = False,
min: OptionalType[int] = None,
max: OptionalType[int] = None,
*,
allow_trailing_delim: bool = False,
) -> ParserElement:
"""Helper to define a de... | d1ac80f138a21ee21ecf76f918f1c7878863f80c | 3,657,503 |
def get_minion_node_ips(k8s_conf):
"""
Returns a list IP addresses to all configured minion hosts
:param k8s_conf: the configuration dict
:return: a list IPs
"""
out = list()
node_tuple_3 = get_minion_nodes_ip_name_type(k8s_conf)
for hostname, ip, node_type in node_tuple_3:
out.a... | 9a93ddcd025e605805a9693dd14d58c92f53dc42 | 3,657,504 |
def calculate_ri(column):
"""
Function that calculates radiant intensity
"""
return float(sc.h * sc.c / 1e-9 * np.sum(column)) | eac136f520ebbad0ea11f506c742e75fc524c4bb | 3,657,505 |
def find_kw_in_lines(kw, lines, addon_str=' = '):
"""
Returns the index of a list of strings that had a kw in it
Args:
kw: Keyword to find in a line
lines: List of strings to search for the keyword
addon_str: String to append to your key word to help filter
Return:
i: In... | 4b50c4eaecc55958fca6b134cc748d672c78d014 | 3,657,506 |
def delete_group(current_session, groupname):
"""
Deletes a group
"""
projects_to_purge = gp.get_group_projects(current_session, groupname)
remove_projects_from_group(current_session, groupname, projects_to_purge)
gp.clear_users_in_group(current_session, groupname)
gp.clear_projects_in_group... | 1a27cec1c3273bb56564587823ad04565867277f | 3,657,507 |
def label_smoothed_nll_loss(lprobs, target, epsilon: float = 1e-8, ignore_index=None):
"""Adapted from fairseq
Parameters
----------
lprobs
Log probabilities of amino acids per position
target
Target amino acids encoded as integer indices
epsilon
Smoothing factor between... | eb09b7dd5c800b01b723f33cd0f7a84ae93b3489 | 3,657,508 |
def ParseFieldDefRequest(post_data, config):
"""Parse the user's HTML form data to update a field definition."""
field_name = post_data.get('name', '')
field_type_str = post_data.get('field_type')
# TODO(jrobbins): once a min or max is set, it cannot be completely removed.
min_value_str = post_data.get('min_v... | 73030f1757ebccf0f9d7710d24b11bf82c8b46c8 | 3,657,509 |
import os
import time
async def get_museum_session_key() -> str:
"""
Retrieve a session key for the MuseumPlus service, generating a new
one if necessary.
:returns: Session key
"""
# We might have an active session key stored locally.
key_path = get_session_key_file_path()
try:
... | 02890e4e67150cc3ce859861f28db1cbe1657837 | 3,657,510 |
import re
def parse_date(regexen, date_str):
"""
Parse a messy string into a granular date
`regexen` is of the form [ (regex, (granularity, groups -> datetime)) ]
"""
if date_str:
for reg, (gran, dater) in regexen:
m = re.match(reg, date_str)
if m:
... | a141cad6762556115699ca0327b801537bab1c7e | 3,657,511 |
def PreNotebook(*args, **kwargs):
"""PreNotebook() -> Notebook"""
val = _controls_.new_PreNotebook(*args, **kwargs)
return val | 1974d3ed08a6811a871f7e069c4b74b97cb32e35 | 3,657,512 |
def user_voted(message_id: int, user_id: int) -> bool:
"""
CHECK IF A USER VOTED TO A DETECTION REPORT
"""
return bool(
c.execute(
"""
SELECT *
FROM reports
WHERE message_id=? AND user_id=?
""",
(message_id, user_id),
... | baddfb69470699d611c050b6732d553f4f415212 | 3,657,513 |
import io
def get_values(wsdl_url, site_code, variable_code, start=None, end=None,
suds_cache=("default",), timeout=None, user_cache=False):
"""
Retrieves site values from a WaterOneFlow service using a GetValues request.
Parameters
----------
wsdl_url : str
URL of a servi... | 57b9cbfbf713f5ac858a8d7a36464aae2a657757 | 3,657,514 |
def GetDot1xInterfaces():
"""Retrieves attributes of all dot1x compatible interfaces.
Returns:
Array of dict or empty array
"""
interfaces = []
for interface in GetNetworkInterfaces():
if interface['type'] == 'IEEE80211' or interface['type'] == 'Ethernet':
if (interface['builtin'] and
... | 829cc1badf5917cc6302847311e5c8ef6aeebc11 | 3,657,515 |
def get_v_l(mol, at_name, r_ea):
"""
Returns list of the l's, and a nconf x nl array, v_l values for each l: l= 0,1,2,...,-1
"""
vl = generate_ecp_functors(mol._ecp[at_name][1])
v_l = np.zeros([r_ea.shape[0], len(vl)])
for l, func in vl.items(): # -1,0,1,...
v_l[:, l] = func(r_ea)
r... | d987e5ceb28169d73ec23aaac2f7ab30a5e881c7 | 3,657,516 |
def search_transitions_in_freq_range(freq_min, freq_max, atomic_number,
atomic_mass, n_min=1, n_max=1000,
dn_min=1, dn_max=10, z=0.0,
screening=False, extendsearch=None):
"""
-------------------------... | bd5fc3873909ce3937b6e94db9f04edb94dab326 | 3,657,517 |
async def test_async__rollback():
"""Should rollback basic async actions"""
state = {"counter": 0}
async def incr():
state["counter"] += 1
return state["counter"]
async def decr():
state["counter"] -= 1
async def fail():
raise ValueError("oops")
try:
w... | 54cc780b01190bfd2ea2aacc70e62e8f0b3dfa64 | 3,657,518 |
import time
import json
def _solve_checkpoint_challenge(_bot):
"""Solve the annoying checkpoint_challenge"""
# --- Start challenge
time.sleep(3)
challenge_url = _bot.last_json['challenge']['api_path'][1:]
try:
_bot.send_request(
challenge_url, None, login=True, with_signature=F... | 5114ac1c49eecf174a994f4b487e1d8a30d4f907 | 3,657,519 |
import requests
def is_referenced(url, id, catalog_info):
"""Given the url of a resource from the catalog, this function returns True
if the resource is referenced by data.gouv.fr
False otherwise
:param :url: url of a resource in the catalog
:type :url: string"""
dgf_page = catalog... | 15cfa64979f2765d29d7c4bb60a7a017feb27d43 | 3,657,520 |
import glob
import functools
def create_sema3d_datasets(args, test_seed_offset=0):
""" Gets training and test datasets. """
train_names = ['bildstein_station1', 'bildstein_station5', 'domfountain_station1', 'domfountain_station3', 'neugasse_station1', 'sg27_station1', 'sg27_station2', 'sg27_station5', 's... | 8642c5a10a5256fb9541be86676073c993b2faf8 | 3,657,521 |
def adjust_learning_rate(optimizer, step, args):
"""
Sets the learning rate to the initial LR decayed by gamma
at every specified step/epoch
Adapted from PyTorch Imagenet example:
https://github.com/pytorch/examples/blob/master/imagenet/main.py
step could also be epoch
... | 359e2c5e0deb1abd156b7a954ecfae1b23511db2 | 3,657,522 |
def sigmoid(z):
"""sigmoid函数
"""
return 1.0/(1.0+np.exp(-z)) | 80187d3711d18602a33d38edcc48eaad5c51818f | 3,657,523 |
def beamformerFreq(steerVecType, boolRemovedDiagOfCSM, normFactor, inputTupleSteer, inputTupleCsm):
""" Conventional beamformer in frequency domain. Use either a predefined
steering vector formulation (see Sarradj 2012) or pass your own
steering vector.
Parameters
----------
steerVecType : (one... | f747122b0dff9a7b966813062b93a1cab8a91f3f | 3,657,524 |
from typing import IO
def createNewPY():
"""trans normal pinyin to TTS pinyin"""
py_trans = {}
input_pinyin_list = IO.readList(r'docs/transTTSPinyin.txt')
for line in input_pinyin_list:
line_array = line.split(',')
py_trans[line_array[0]] = line_array[1]
return py_trans | e2bd5007cc217f72e3ffbeafd0ff75e18f8ec213 | 3,657,525 |
import re
def search_wheelmap (lat, lng, interval, name, n):
"""Searches for a place which matches the given name in the
given coordinates range. Returns false if nothing found"""
# Calculate the bbox for the API call
from_lat = lat - interval
to_lat = lat + interval
from_lng = lng - int... | 88dfbf973fbd4891a4d8bf955335177ca3654016 | 3,657,526 |
from typing import Dict
def get_entity_contents(entity: Dict) -> Dict:
"""
:param entity: Entity is a dictionary
:return: A dict representation of the contents of entity
"""
return {
'ID': entity.get('id'),
'Name': entity.get('name'),
'EmailAddress': entity.get('email_addre... | 3c9e133bf80bc4d59c6f663503b5083401acc4e0 | 3,657,527 |
def t68tot90(t68):
"""Convert from IPTS-68 to ITS-90 temperature scales,
as specified in the CF Standard Name information for
sea_water_temperature
http://cfconventions.org/Data/cf-standard-names/27/build/cf-standard-name-table.html
temperatures are in degrees C"""
t90 = 0.9... | 87ff55a196f01b8f1afd78381e7d012eafa079fa | 3,657,528 |
def get_sort_accuracy_together(fake_ys, y):
"""
Args:
fake_ys (np.ndarray): with shape (n_results, n_sample,).
y (np.ndarray): with sample (n_sample,).
Returns:
corr (np.ndarray): with shape (n_result,)
"""
y_sort = np.sort(y)
y_sort2 = np.sort(y)[::-1]
fake_ys =... | 4ba4810057bb936fdb5a94669796b0a260eeee49 | 3,657,529 |
def random_account_number():
"""
Generate random encoded account number for testing
"""
_, account_number = create_account()
return encode_verify_key(verify_key=account_number) | d662dc0acdc78f86baf2de998ab6ab920cc80ca0 | 3,657,530 |
def get_recommendation_summary_of_projects(project_ids, state, credentials):
"""Returns the summary of recommendations on all the given projects.
Args:
project_ids: List(str) project to which recommendation is needed.
state: state of recommendations
credentials: client credentials.
"""
recommen... | 68cd42e4465bbdc85d88b82cb345b64a4ec1fec8 | 3,657,531 |
def selection_filter(file_path):
"""
获得经过filter方法获得的特征子集
f_classif, chi2, mutual_info_classif
"""
df = pd.read_csv(file_path)
delete_list = ['id']
df.drop(delete_list, axis=1, inplace=True)
feature_attr = [i for i in df.columns if i not in ['label']]
df.fillna(0, inplace=True)
# ... | d6f6848c499f2d4899828e1e1bd0fb0ffe930186 | 3,657,532 |
def _process_voucher_data_for_order(cart):
"""Fetch, process and return voucher/discount data from cart."""
vouchers = Voucher.objects.active(date=date.today()).select_for_update()
voucher = get_voucher_for_cart(cart, vouchers)
if cart.voucher_code and not voucher:
msg = pgettext(
'... | ec15f13607cee7e4bdd2e16f9a44904638964d36 | 3,657,533 |
def is_insertion(ref, alt):
"""Is alt an insertion w.r.t. ref?
Args:
ref: A string of the reference allele.
alt: A string of the alternative allele.
Returns:
True if alt is an insertion w.r.t. ref.
"""
return len(ref) < len(alt) | 17d7d6b8dfdf387e6dd491a6f782e8c9bde22aff | 3,657,534 |
from typing import Optional
def identify_fast_board(switches: int, drivers: int) -> Optional[FastIOBoard]:
"""Instantiate and return a FAST board capable of accommodating the given number of switches and drivers."""
if switches > 32 or drivers > 16:
return None
if switches > 16:
return Non... | 27c0dca3e0421c9b74976a947eda5d6437598c01 | 3,657,535 |
import struct
def encode_hop_data(
short_channel_id: bytes, amt_to_forward: int, outgoing_cltv_value: int
) -> bytes:
"""Encode a legacy 'hop_data' payload to bytes
https://github.com/lightningnetwork/lightning-rfc/blob/master/04-onion-routing.md#legacy-hop_data-payload-format
:param short_channel_id... | 51fda780036fdcbb8ff1d5cd77b422aaf92eb4fd | 3,657,536 |
def extract_all_patterns(game_state, action, mask, span):
""" Extracting the local forward model pattern for each cell of the grid's game-state and returning a numpy array
:param prev_game_state: game-state at time t
:param action: players action at time t
:param game_state: resulting game-state at tim... | 06e44c871a14b7685ca5dd165285cfe2c7076b85 | 3,657,537 |
import os
def wrapper_subcavities(final_cavities, cav_of_interest, grid_min, grid_shape, cavities, code, out, sourcedir, list_ligands,
seeds_mindist = 3, merge_subcavs = True, minsize_subcavs = 50, min_contacts = 0.667, v = False,
printv = False, print_pphores_subcavs = False, export_subcavs = False, gridspace = 1.... | 94751b892b473d818f27f431420aa7de726c91d3 | 3,657,538 |
import os
def generate_datafile(lists_of_systems, output_dir, filename):
"""
take in a list of lists which contains systems
generate one input data file per list
"""
result = []
for index, list_of_sys in enumerate(lists_of_systems):
output_filename = filename + "_" + str(index)... | 70024dc2c1420b9fbff312856b8bb48ee645e772 | 3,657,539 |
def cond(*args, **kwargs):
"""Conditional computation to run on accelerators."""
return backend()['cond'](*args, **kwargs) | 969307c62bd4a2eef6b16dffff953910524cc3c1 | 3,657,540 |
import os
def get_testfile_paths():
"""
return the necessary paths for the testfile tests
Returns
-------
str
absolute file path to the test file
str
absolute folder path to the expected output folder
"""
testfile = os.path.join(os.path.dirname(os.path.dirname(__file_... | f1cb8d29c70c686fbca43175637f44b7c5342180 | 3,657,541 |
def singleton(cls):
"""Decorator that provides singleton functionality.
>>> @singleton
... class Foo(object):
... pass
...
>>> a = Foo()
>>> b = Foo()
>>> a is b
True
"""
_inst = [None]
def decorated(*args, **kwargs):
if _inst[0] is None:
_inst[... | 4ae64aeaaba1b838232e4d7700d692dcc109be6d | 3,657,542 |
import inspect
def _with_factory(make_makers):
"""Return a decorator for test methods or classes.
Args:
make_makers (callable): Return an iterable over (name, maker) pairs,
where maker (callable): Return a fixture (arbitrary object) given
Factory as single argument
"""
de... | 5841e80129b212bba2c6d0b1f89966fa0d5ce152 | 3,657,543 |
import time
def timeItDeco(func):
""" Decorator which times the given function. """
def timing(*args, **kwargs):
""" This function will replace the original function. """
# Start the clock
t1 = time.clock()
# Run the original function and collect results
result = fun... | 9c59a512a9cf9eac190af4a88dbf8ccab2069f55 | 3,657,544 |
def apply_haste(self: Player, target: Player, rules: dict, left: bool) -> EffectReturn:
"""
Apply the effects of haste to the target:
attack beats attack
"""
# "attack": {"beats": ["disrupt", "area", "attack"], "loses": ["block", "dodge"]}
if left:
# Remove attack from the attack: loses ... | 0186fe8553cb89c73d9a3cfae35048cd465b9859 | 3,657,545 |
def get_mean_cube(datasets):
"""Get mean cube of a list of datasets.
Parameters
----------
datasets : list of dict
List of datasets (given as metadata :obj:`dict`).
Returns
-------
iris.cube.Cube
Mean cube.
"""
cubes = iris.cube.CubeList()
for dataset in datase... | 492b5df11252beb691c62c58005ce2c3c1dcb3b8 | 3,657,546 |
async def gen_unique_chk_sum(phone, message, first_dial):
"""Generates a checksum in order to identify every single call"""
return blake2b(
bytes(phone, encoding="utf-8")
+ bytes(message, encoding="utf-8")
+ bytes(str(first_dial), encoding="utf-8"),
digest_size=4,
).hexdigest... | c85076f4fd1e2814116ece59390bebb9f398a4f6 | 3,657,547 |
def getQtipResults(version, installer):
"""
Get QTIP results
"""
period = get_config('qtip.period')
url_base = get_config('testapi.url')
url = ("http://" + url_base + "?project=qtip" +
"&installer=" + installer +
"&version=" + version + "&period=" + str(period))
reques... | 4ae01b33a2eed23a8d3ad7b7dd1d5a3bcc8d5ab8 | 3,657,548 |
def scaled_softplus(x, alpha, name=None):
"""Returns `alpha * ln(1 + exp(x / alpha))`, for scalar `alpha > 0`.
This can be seen as a softplus applied to the scaled input, with the output
appropriately scaled. As `alpha` tends to 0, `scaled_softplus(x, alpha)` tends
to `relu(x)`.
Note: the gradient for this ... | 526c5169b1ac938e3f645e96dc7e65bb4acf64b5 | 3,657,549 |
def get_choice(options):
"""Devuelve como entero la opcion seleccionada para el input con mensaje message"""
print(options)
try:
return int(input("Por favor, escoja una opción: "))
except ValueError:
return 0 | 32e95e0113650d0b94449e5e31e7d8156ae85981 | 3,657,550 |
def _listminus(list1, list2):
"""
"""
return [a for a in list1 if a not in list2] | 3f05d8bfd4169d92bb51c4617536b54779b387c9 | 3,657,551 |
import pytesseract
from pdf2image import convert_from_bytes
def pdf_to_hocr(path, lang="fra+deu+ita+eng", config="--psm 4"):
"""Loads and transform a pdf into an hOCR file.
Parameters
----------
path : str, required
The pdf's path
lang: str, optional (default="fra+deu+ita+eng")
Su... | 9619d45dc418f07634fd161f1dff50b4cf334e21 | 3,657,552 |
import httpx
async def fetch_cart_response(cart_id: str) -> httpx.Response:
"""Fetches cart response."""
headers = await get_headers()
async with httpx.AsyncClient(base_url=CART_BASE_URL) as client:
response = await client.get(
url=f'/{cart_id}',
headers=headers,
)
... | 2d2da772b257b43beda78f3b08c42c914c01f00d | 3,657,553 |
from sys import stdout
import logging
from typing import Protocol
def checkHardware(binary, silent=False, transaction=None):
"""
probe caffe continuously for incrementing until missing id
structure:
[
{ "id": 0,
"name": "..",
"log": ["..", "..", "..", ... ]
},
... | be13049d6d790410430de8a507ceefc61f276eec | 3,657,554 |
def is_namespace_mutable(context, namespace):
"""Return True if the namespace is mutable in this context."""
if context.is_admin:
return True
if context.owner is None:
return False
return namespace.owner == context.owner | f5303e75b975a1ba51aa39c608ec5af339917446 | 3,657,555 |
def get_schularten_by_veranst_iq_id(veranst_iq_id):
""" liefert die Liste der zu der Veranstaltung veranst_iq_id passenden Schularten """
query = session.query(Veranstaltung).add_entity(Schulart).join('rel_schulart')
query = query.reset_joinpoint()
query = query.filter_by(veranst_iq_id=veranst_iq_id)
return q... | 4c18b2fe73b17752ee2838815fa9fde8426a7ccb | 3,657,556 |
def get_station_freqs(df, method='median'):
"""
apply to df after applying group_by_days and group_by_station
"""
#df['DATE'] = df.index.get_level_values('DATE')
df['DAY'] = [d.dayofweek for d in df.index.get_level_values('DATE')]
df['DAYNAME'] = [d.day_name() for d in df.index.get_level_values(... | aebc1a2486c48ff2d829fc70f1f2c4b38bd3017b | 3,657,557 |
def faster_symbol_array(genome, symbol):
"""A faster calculation method for counting a symbol in genome.
Args:
genome (str): a DNA string as the search space.
symbol (str): the single base to query in the search space.
Returns:
Dictionary, a dictionary, position-counts pairs of sym... | a1bbf70a211adcee14573534b62b4a4af5abdebd | 3,657,558 |
def crosswalk_patient_id(user):
""" Get patient/id from Crosswalk for user """
logger.debug("\ncrosswalk_patient_id User:%s" % user)
try:
patient = Crosswalk.objects.get(user=user)
if patient.fhir_id:
return patient.fhir_id
except Crosswalk.DoesNotExist:
pass
r... | 1424d5fdc3917d76bd0e8905b44e261068fad4f5 | 3,657,559 |
def makeArg(segID: int, N, CA, C, O, geo: ArgGeo) -> Residue:
"""Creates an Arginie residue"""
##R-Group
CA_CB_length = geo.CA_CB_length
C_CA_CB_angle = geo.C_CA_CB_angle
N_C_CA_CB_diangle = geo.N_C_CA_CB_diangle
CB_CG_length = geo.CB_CG_length
CA_CB_CG_angle = geo.CA_CB_CG_angle
N_CA_C... | 4539d48e37e7bacd637300136799b8f7b3dc635d | 3,657,560 |
import json
import traceback
import tempfile
import os
import sys
def uploadAssignment(req, courseId, assignmentId, archiveFile):
""" Saves a temp file of the uploaded archive and calls
vmchecker.submit.submit method to put the homework in
the testing queue"""
websutil.sanityCheckAssignmentI... | 03ae93e3d65a84b11115a520555b6b87bc3ec443 | 3,657,561 |
def shows_monthly_aggregate_score_heatmap():
"""Monthly Aggregate Score Heatmap Graph"""
database_connection.reconnect()
all_scores = show_scores.retrieve_monthly_aggregate_scores(database_connection)
if not all_scores:
return render_template("shows/monthly-aggregate-score-heatmap/graph.html",
... | 4bf26e21c7d76be96395fce43228ee0a80930e4e | 3,657,562 |
import requests
def run(string, entities):
"""Call a url to create a api in github"""
# db = utils.db()['db']
# query = utils.db()['query']
# operations = utils.db()['operations']
# apikey = utils.config('api_key')
# playlistid = utils.config('playlist_id')
# https://developers.google.com/youtube/v3/docs/pla... | 6a3a9899e8081c655e9a7eabc3e96f103a77a6bd | 3,657,563 |
def gamma(surface_potential, temperature):
"""Calculate term from Gouy-Chapmann theory.
Arguments:
surface_potential: Electrostatic potential at the metal/solution boundary in Volts, e.g. 0.05 [V]
temperature: Temperature of the solution in Kelvin, e.g. 300 [K]
Returns:
float
"""
product = sc.elementary_charg... | b8996f01bb221a5cd2f6c222d166a61f1759845f | 3,657,564 |
def calculate_mask(maskimage, masks):
"""Extracts watershed seeds from data."""
dims = list(maskimage.slices2shape())
maskdata = np.ones(dims, dtype='bool')
if masks:
dataslices = utils.slices2dataslices(maskimage.slices)
maskdata = utils.string_masks(masks, maskdata, dataslices)
m... | 4935cacb3689b844ab119ec3b24b9e59b7db7ec3 | 3,657,565 |
def Range(lo, hi, ctx = None):
"""Create the range regular expression over two sequences of length 1
>>> range = Range("a","z")
>>> print(simplify(InRe("b", range)))
True
>>> print(simplify(InRe("bb", range)))
False
"""
lo = _coerce_seq(lo, ctx)
hi = _coerce_seq(hi, ctx)
return R... | cb9cf3a334ba8509a54226c86c555257092a0951 | 3,657,566 |
import numpy
def quantile(data, num_breaks):
"""
Calculate quantile breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
def scipy_mquantiles(a, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, limit=()):
""" function copi... | 24486e39fcefb9e6cf969067836d1793b9f4a7c8 | 3,657,567 |
def extract_conformers_from_rdkit_mol_object(mol_obj, conf_ids):
"""
Generate xyz lists for all the conformers in conf_ids
:param mol_obj: Molecule object
:param conf_ids: (list) list of conformer ids to convert to xyz
:return: (list(list(cgbind.atoms.Atom)))
"""
conformers = []
for i i... | 821977c0be57441b5146c9d5ef02a19320cf5b91 | 3,657,568 |
def create_embedding(name: str, env_spec: EnvSpec, *args, **kwargs) -> Embedding:
"""
Create an embedding to use with sbi.
:param name: identifier of the embedding
:param env_spec: environment specification
:param args: positional arguments forwarded to the embedding's constructor
:param kwargs... | 70f4651f5815f008670de08805249d0b9dfc39e9 | 3,657,569 |
def _init_allreduce_operators(length, split_indices):
""" initialize allreduce communication operators"""
indices = split_indices[0]
fusion = split_indices[1]
op_list = ()
j = 0
for i in range(length):
if j <= len(indices)-1:
temp = indices[j]
else:
temp =... | 91f752e049394b27340553830dce70074ef7ed81 | 3,657,570 |
def get_valid_fields(val: int, cs: dict) -> set:
"""
A value is valid if there's at least one field's interval which contains it.
"""
return {
field
for field, intervals in cs.items()
if any(map(lambda i: i[0] <= val <= i[1], intervals))
} | 3016e78637374eadf7d0e2029d060538fea86377 | 3,657,571 |
import glob
import re
def load_data_multiview(_path_features, _path_lables, coords, joints, cycles=3, test_size=0.1):
"""Generate multi-view train/test data from gait cycles.
Args:
_path_features (str): Path to gait sequence file
_path_lables (str): Path to labels of corresponding gait sequen... | 574ca69bf6a6637b4ca53de05f8e792844e134bb | 3,657,572 |
def T_ncdm(omega_ncdm, m_ncdm):
# RELICS ONLY?
"""Returns T_ncdm as a function of omega_ncdm, m_ncdm.
... | c3db4e4d2ac226f12afca3077bbc3436bd7a0459 | 3,657,573 |
import logging
from datetime import datetime
import subprocess
def main(config: Config, dry_run: bool = False) -> int:
"""
Main entrypoint into the program. Takes specified snapshots if they don't exist and deletes old entrys as specified.
:param config: The backup manager configuration.
:param dry_r... | f3cf6967458c082f78cd47a4d5793a1fa8e130a2 | 3,657,574 |
import binascii
def generate_initialisation_vector():
"""Generates an initialisation vector for encryption."""
initialisation_vector = Random.new().read(AES.block_size)
return (initialisation_vector, int(binascii.hexlify(initialisation_vector), 16)) | 4c05067d86cbf32de7f07b5d7483811c46307b64 | 3,657,575 |
def assign_score(relevant_set):
"""Assign score to each relevant element in descending order and return the score list."""
section = len(relevance[0])//3
score = []
s = 3
for i in range(3):
if s == 1:
num = len(relevance[0]) - len(score)
score.extend([s]*num)
... | 76a43780e1d1f37f7e0220ff0a0ca2ec484dd036 | 3,657,576 |
def visualize_img(img,
cam,
kp_pred,
vert,
renderer,
kp_gt=None,
text={},
rotated_view=False,
mesh_color='blue',
pad_vals=None,
no_text=Fals... | eb182cdd4042595abfba3c399c20fd5bba0ca352 | 3,657,577 |
import os
def _check_file_type_specific_bad_pattern(filepath, content):
"""Check the file content based on the file's extension.
Args:
filepath: str. Path of the file.
content: str. Contents of the file.
Returns:
failed: bool. True if there is bad pattern else false.
tota... | fe8817f77f5596d8c51173ab3dc48ef8c02f8bcb | 3,657,578 |
import socket
import requests
from sys import version
def _update(__version__, __code_name__, language, socks_proxy):
"""
update the framework
Args:
__version__: version number
__code_name__: code name
language: language
socks_proxy: socks proxy
Returns:
True... | a35b9115e4c123aa771de238cac576a1df8532c1 | 3,657,579 |
import scipy
def conv_noncart_to_cart(points, values, xrange, yrange, zrange):
"""
:param points: Data point locations (non-cartesian system)
:param vals: Values corresponding to each data point
:param xrange: Range of x values to include on output cartesian grid
:param yrange: y
:param zrang... | cba013444ecdbd4abec14008dc6894e306244087 | 3,657,580 |
import urllib
import json
def createColumnsFromJson(json_file, defaultMaximumSize=250):
"""Create a list of Synapse Table Columns from a Synapse annotations JSON file.
This creates a list of columns; if the column is a 'STRING' and
defaultMaximumSize is specified, change the default maximum size for that... | 9eba1d44a9fec8e92b6b95036821d48d68cd991b | 3,657,581 |
from typing import Callable
from re import T
from typing import Optional
import warnings
def record(
fn: Callable[..., T], error_handler: Optional[ErrorHandler] = None
) -> Callable[..., T]:
"""
Syntactic sugar to record errors/exceptions that happened in the decorated
function using the provided ``er... | e538c51aeb4234aa85d90d9978d228bf0f505aac | 3,657,582 |
import torch
def bbox_overlaps_2D(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
"""
# 1. Tile boxes2 and repeate boxes1. This allows us to compare
# every boxes1 against every boxes2 without loops.
# TF doesn't have an equivalent to... | 86920dac357285b3681629474ed5aaad471ed7f8 | 3,657,583 |
def decoder(data):
"""
This generator processes a sequence of bytes in Modified UTF-8 encoding
and produces a sequence of unicode string characters.
It takes bits from the byte until it matches one of the known encoding
sequences.
It uses ``DecodeMap`` to mask, compare and generate values.
... | 217f52081a476ef1c48d2d34d020ec6c7c9e1989 | 3,657,584 |
def calculate_exvolume_redfactor():
"""
Calculates DEER background reduction factor alpha(d)
See
Kattnig et al
J.Phys. Chem. B, 117, 16542 (2013)
https://doi.org/10.1021/jp408338q
The background reduction factor alpha(d) is defined in Eq.(18)
For large d, one can use the limiting express... | 3583e1526f1636feaa86a77c7f5ba51d816abe26 | 3,657,585 |
def get_successors(graph):
"""Returns a dict of all successors of each node."""
d = {}
for e in graph.get_edge_list():
src = e.get_source()
dst = e.get_destination()
if src in d.keys():
d[src].add(dst)
else:
d[src] = set([dst])
return d | 1ec7b0ab8772dc738758bb14fe4abd5dd4b9074e | 3,657,586 |
def readDataTable2o2(request):
"""Vuetify練習"""
form1Textarea1 = request.POST["textarea1"]
template = loader.get_template(
'webapp1/practice/vuetify-data-table2.html')
# -----------------------------------------
# 1
# 1. host1/webapp1/templates/webapp1/practice/vuetify-data-table2.... | 01688c20fa5057829338bbd76520a7b0510923ad | 3,657,587 |
from .sigma import decode_cf_sigma
from .grid import decode_cf_dz2depth
def get_depth(da, errors="raise"):
"""Get or compute the depth coordinate
If a depth variable cannot be found, it tries to compute either
from sigma-like coordinates or from layer thinknesses.
Parameters
----------
{erro... | 048208629eef6e5ecf238212e7a865e5fbaea993 | 3,657,588 |
def route53_scan(assets, record_value, record):
"""
Scan Route53
"""
for i, asset in enumerate(assets):
asset_type = asset.get_type()
if asset_type == 'EC2' and record_value in (asset.public_ip, asset.private_ip):
assets[i].dns_record = record['Name'].replace('\\052', '*')
... | eccbb2d716ef7b5dd713e7fbbd210c246c97347d | 3,657,589 |
import requests
def process_language(text):
"""
Fetch from language processing API (cloud function)
:param text:
:return:
"""
# The language processing seems to fail without acsii decoding, ie remove emoji and chinese characters
request = {
"text": text.encode("ascii", errors="ign... | d5b164cf0722093988f7cbb3f93ef62bc7c98758 | 3,657,590 |
def to_int(text):
"""Text to integer."""
try:
return int(text)
except ValueError:
return '' | d870ee05c3117111adcf85c91038b19beaf9585b | 3,657,591 |
import os
import json
import tokenize
def parse_commonsense_reasoning_test(test_data_name):
"""Read JSON test data."""
with tf.gfile.Open(os.path.join(
FLAGS.data_dir, 'commonsense_test',
'{}.json'.format(test_data_name)), 'r') as f:
data = json.load(f)
question_ids = [d['... | b3d83a93ecece3813a558dfc7c5eb7757e153974 | 3,657,592 |
def flooding(loss, b):
"""flooding loss
"""
return (loss - b).abs() + b | c34eedf0421b60e27bd813381ff7dfe96a3912eb | 3,657,593 |
def CreateConditions(p,avec,bvec,indexgenerator=CreateLyndonIndices):
"""This creates the set of equations using by default the Lyndon Basis elements.
Parameters
----------
p : the considered order
avec: The set of symbols to use for the first operator.
bvec: The set of symbols to use for the s... | 61ed4373d18a730838110865c8d4334176427bc4 | 3,657,594 |
def with_conf_blddir(conf, name, body, func):
"""'Context manager' to execute a series of tasks into code-specific build
directory.
func must be a callable taking no arguments
"""
old_root, new_root = create_conf_blddir(conf, name, body)
try:
conf.bld_root = new_root
conf.bl... | b01af0d8a44ad432020cc800f334f4de50b5036d | 3,657,595 |
def many_to_one(clsname, **kw):
"""Use an event to build a many-to-one relationship on a class.
This makes use of the :meth:`.References._reference_table` method
to generate a full foreign key relationship to the remote table.
"""
@declared_attr
def m2o(cls):
cls._references((cls.__nam... | 528f6391535a437383750346318ac65acaa8dfdc | 3,657,596 |
import sqlite3
def get_cnx(dbname=None, write=False):
"""Return a new connection to the database by the given name.
If 'dbname' is None, return a connection to the system database.
If the database file does not exist, it will be created.
The OS-level file permissions are set in DbSaver.
"""
if... | f2e3cc300fa4cb122a9fe4705d41878332929702 | 3,657,597 |
def nir_mean(msarr,nir_band=7):
"""
Calculate the mean of the (unmasked) values of the NIR (near infrared) band
of an image array. The default `nir_band` value of 7 selects the NIR2 band
in WorldView-2 imagery. If you're working with a different type of imagery,
you will need figure out the appropri... | 7ba6ea8b7d51b8942a0597f2f89a05ecbee9f46e | 3,657,598 |
def decode(invoice) -> LightningInvoice:
"""
@invoice: is a str, bolt11.
"""
client = CreateLightningClient()
try:
decode_response = client.call("decode", invoice)
assert decode_response.get("error") is None
result = decode_response["result"]
assert result["valid"], ... | c713ec8708214312b84103bceb64e0876d23bc29 | 3,657,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.