content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import copy
def scsg_step(net, optimizer, train_loader, test_loader, loss_function, inner_iter_num, args):
"""
Function to updated weights with a SCSG backpropagation
args : net, optimizer, train_loader, test_loader, loss function, number of inner epochs, args
return : train_loss, test_loss, grad_norm... | 6e7f70c0642734bdc0d76e7fa7d9f1db718cde1b | 67,100 |
def to_pyvista_line(line_set: LineSet, as_tube=True, radius=None,
spline=False, n_interp_points=1000):
"""Create pyvista PolyData for 1D lines
Args:
line_set:
as_tube (bool):
radius (float): radius of the tube
spline: NotImplemented
n_interp_points: N... | 2b08a04cab5c604cd8889e9463a11a7b7ec42f73 | 67,101 |
def calc_exec_time(block):
"""
calculate the total time to execute all observing blocks by exp. time.
Excludes any read out time and overheads.
:param block: The observing Block document.
:type block: Dict
:rtype: int
"""
if "parameters" not in block:
return 0
exp1 = 0
... | deaf6649173de784a77601da4ef4df1b7c10cb93 | 67,102 |
def count_terms_v2_KEGG(ans_set, assoc_dict):
"""
count the number of terms in the study group
GOid2NumANs_dict: key=GOid, val=Num of occurrences
GOid2ANs_dict: key=GOid, val=ListOfANs
count_n: Integer(Number of ANs with a GO-term in assoc_dict and obo_dag
:return: Tuple(dict, dict, int)
"""... | 8716da136cd6752e55c5dc35110370af13a2b764 | 67,103 |
from typing import Dict
from typing import Any
def create_bot_utterance(message: Dict[Text, Any]) -> BotUttered:
"""Create BotUttered event from message."""
bot_message = BotUttered(
text=message.pop("text", None),
data={
"elements": message.pop("elements", None),
"qui... | f6d880edce11408493c616958cd874f9ac85b66a | 67,104 |
import pkg_resources
def get_example_data():
""" Get default path to experimental crystal ovelap populaiton data
Returns
-------
data_path : str
path to example lobster data
"""
data_path = pkg_resources.resource_filename(__name__, 'data/lobster')
return data_path | a04a47e3f70a9735c2badf32da13a6119c82c418 | 67,105 |
def get_page_content(code_lan, num_of_path, path):
"""
By passing the language code and path,
is return the page content object
"""
# Inside any page it saved the path with this format
url = "url_{}.{}".format(num_of_path, code_lan)
# Create a list of pages
list_pages = [ page for page... | 3d9a9148ef15f376a2a5ab3a1b50ded589531b4c | 67,106 |
from typing import Callable
import time
from typing import Any
def per_user_ratelimit(
max_requests: int,
period: float,
login_res: str = sign_in_page,
get_ratelimited_res: Callable[[float], str] = (
lambda left: f"Too many requests, wait {left} sec"
),
) -> Callable[[Callable], flask.Resp... | 2f3c1e6e15fcfca99ae66e92dd0af4614ba1e02a | 67,107 |
def _nondim_resist_braginskii(hall, Z, field_orientation):
"""
Dimensionless resistivity — Braginskii.
Braginskii, S. I. "Transport processes in a plasma." Reviews of plasma
physics 1 (1965): 205.
"""
allowed_Z = [1, 2, 3, 4, np.inf]
Z_idx = _check_Z(allowed_Z, Z)
# fixing overflow err... | 5ca98cce84907d056d29149c81167d09e8675a09 | 67,108 |
import signal
def smooth_data(df, window_length=21, polyorder=5):
"""
Apply a Savitzky-Golay filter spectrograms contained in DataFrame.
Column 'x' remains unchanged"""
x = df.x
smoothed = signal.savgol_filter(df, window_length=window_length, polyorder=polyorder, axis=0)
df_smoothed = pd.DataF... | 42b64263cc3604d7c9a23342b4dd75711fa686f2 | 67,109 |
def attributes(*args):
"""
a decorator to add an "attribute" to an action, which can be used
as a filtering mechanism to control what actions in given task are run.
If we have the following in tasks.init_data:
@attributes('test', 'dev')
def action_020_a_little_data()... | f03acfd500171f529f8ea0ec8e391dfd15cac092 | 67,110 |
import math
def ts_winp(a, b, env=None):
"""Win probability of player a over b given their trueskill ratings.
Formula found at https://github.com/sublee/trueskill/issues/1#issuecomment-244699989"""
if not env:
env = trueskill.global_env()
epsilon = trueskill.calc_draw_margin(env.draw_probabili... | 2a01c965db005f5f99e84e4583e5978dfac274b1 | 67,111 |
def _construct_sparse_tensors_for_sparse_features(features, tensor_dict):
"""Merges SparseTensors of indices and values of SparseFeatures.
Constructs new dict based on `tensor_dict`. For `SparseFeatures` in the values
of `features` expects their `index_key`s and `index_value`s to be present in
`tensor_dict` ma... | 07e8713a334a023f0c1ff43cc583337a69355416 | 67,112 |
def _check_limits(val, lb=None, ub=None, lb_ge=False, ub_le=False):
""" Returns True where lb < (or <=) val < (or <=) ub
"""
if lb_ge:
lb_op = np.greater_equal
else:
lb_op = np.greater
if ub_le:
ub_op = np.less_equal
else:
ub_op = np.less
if (lb is not None) ... | 3a3c54fb56a8b2ff06375c2276a5a011be11b9db | 67,113 |
def kml_response(kml_map):
"""
Args:
kml_map (KMLMap): KMLMap object
Returns:
Response: a Flask Response with proper MIME-type.
"""
return Response(kml_map.get_kml(), mimetype=kml_map.MIME_TYPE) | b101eb985873e75df6da07e69d5fc11928c95de3 | 67,114 |
def _parse_instructors(details):
"""
Extract instructor names from the course detail page
Args:
details(Tag): BeautifulSoup Tag for course details
Returns:
list of dict: List of first & last names of each instructor
"""
try:
instructors = details.findAll(
"... | 3dc4f4ddf62dc9dae894d218e249a279941eca5f | 67,115 |
def create_LeNet(img_dim, n_labels):
"""
Create CNN with LeNet Architecture
- Set 1: Conv2D - Actication - Pooling
- Set 2: Conv2D - Activation - Pooling
- Set 3: Flatten - Fully Connected - Activation
- Set 4: Output layer for classification
Input:
- img_dim: size of the inpu... | 7d6ebbc30da10fb50394bd96010cbbfa69faec29 | 67,116 |
import random
def convert_labels(read_dataset, write_dataset, percent, no_sentences_to_enable):
"""
Takes a file and randomly enables no_sentences_to_enable of them.
:param read_dataset: file to read from
:param write_dataset: file to write to
:param percent: percent to enable (used to calculate t... | 31acbb1a4146bcf4f09a15ed3d89794f90654a44 | 67,117 |
import six
import os
def downloadFile(url, path):
"""
Downloads micro architecture specifications from internet
:param url: url of the website hosting the specifications
:param path: Path of download directory
"""
from six.moves.urllib.request import urlopen # pylint: disable=import-error
from six.mov... | 94081e74968783fb4bd7cd5d5fb9c2507e979c47 | 67,118 |
def subject_member_find(context, subject_id=None, member=None,
status=None, include_deleted=False):
"""Find all members that meet the given criteria.
Note, currently include_deleted should be true only when create a new
subject membership, as there may be a deleted subject membershi... | 07b2a431392c3d54560943e87d2226ef3e9c3b1f | 67,119 |
def reporthook(t):
"""https://github.com/tqdm/tqdm"""
last_b = [0]
def inner(b=1, bsize=1, tsize=None):
"""
b: int, optionala
Number of blocks just transferred [default: 1].
bsize: int, optional
Size of each block (in tqdm units) [default: 1].
tsize: int, opt... | 35ea69d974de5fa31c2ca910d1db09659b5bda23 | 67,120 |
def endpoint_to_kwarg(
endpoint_name,
type_id
):
"""recast endpoint_name to **kwarg pair
TODO: this is kinda hacky, move to class/enum?
Args:
endpoint_name (str): name of endpoint
type_id (int): EVE Online ID
Returns:
dict: kwarg pair
"""
kwarg_pair = {... | c3f8889cee31167b67a4df33a2b56f5be5643f7e | 67,121 |
def psse_to_df(file):
"""
Convert a PSS/E xlsx export to DataFrame.
"""
return excel_to_df(file, offset_row=1, offset_col=0, ) | fc3257594a55d7aba45d08fa6cae0794fb403162 | 67,122 |
def transform_point(point: (int, int), transform_metadata: TransformMetadata):
"""
:param point: point in original plane
:param M: transformation matrix
:return: prints point that point is transformed to in new plane
"""
a = np.array([np.array([point], dtype='float32')])
cur = cv2.perspectiv... | dffd0367c6af5b948612018ba6aee7c9b9593e2a | 67,123 |
def compute_possible_positions(start, grid):
"""
Get all possible position that are in the grid and are not walls
"""
possible = []
for direct in DIRECTIONS:
px, py = start[0] + direct[0], start[1] + direct[1]
if 0 <= px < len(grid[0]) and 0 <= py < len(grid):
if grid[py... | f855032fb31edd81d3293a645fd7ee7a785daabb | 67,124 |
def get_changed_docs():
""" Function to fetch docs which very whose notificatons have not been sen to the users. """
try:
client = MongoClient(host,port)
db=client[changes_db]
col=db[changes_collection]
docs=col.find({"status": "unnotified"})
client.close()
return docs
except Exception as e:
print "Fa... | aa1a51cc580455e4dd7e31781bb20bdf40a46615 | 67,125 |
def isCSERelative(uri:str) -> bool:
""" Check whether a URI is CSE-Relative. """
return uri is not None and uri[0] != '/' | 70384d58d9f00c20233ccb46ab9d8e8ec7dcf22c | 67,126 |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
#Returning the number when it is less or equal to 1
if number <= 1:
return number
my_divsor = 2
my... | 541d7f2460532ba86c7a960b15c3b5629c2f4e94 | 67,127 |
def xml_pretty(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | 9c2e65d107ec5ba89ba2f4b5f929fbc06bb5da70 | 67,128 |
def be_in(a, b, msg=None):
"""
Asserts **ARG1 in ARG2**
"""
return contain(b, a, msg) | 99ebf628f12af52ded3c4629832ce6f83db306e2 | 67,129 |
import functools
def needs(*things):
"""An injector that injects the requested dependences into a function's
arguments.
If the dependency has "."s in the name, only the last segment will be used,
and "-" will be replaced with "_".
"""
things_parameter_names = {
requirement.rsplit("."... | ab0852b530d153cb07104c5fe8bf9e1a772e47fe | 67,130 |
def reverse_translate(protein_sequence, randomize_codons=False, table="Standard"):
"""Return a DNA sequence which translates to the provided protein sequence.
Parameters
----------
protein_sequence
A sequence string of aminoacids, e.g. "MVKK..."
table
Genetic code table to use (e.g. '... | 123848bb83111e774013900f3d3b9a4ab0572735 | 67,131 |
def unindent(line, from_row, to_row, count=1):
"""
Unindent text of the `Line` object.
"""
current_row = line.document.cursor_position_row
line_range = range(from_row, to_row)
def transform(text):
remove = ' ' * count
if text.startswith(remove):
return text[len(re... | 3befe045bd7b1a78ee2f675a66410a745046c346 | 67,132 |
def get_image(mol, atomset, name):
"""Save image of the SMILES for vis purposes"""
hcolor = colors.to_rgb('green')
if atomset is not None:
# highlight the atoms set while drawing the whole molecule.
img = MolToImage(mol, size=(600, 600), fitImage=True, highlightAtoms=atomset, highlightColor=... | 6baa202b2ce78f7db60dc8ff44fdd0a5625a9f26 | 67,133 |
from bs4 import BeautifulSoup
def parse_page_deb(page, source, version, prefix):
"""Parses a Debian deb HTML page and return URLs.
"""
html = BeautifulSoup(page, 'html.parser')
elements = [x.select('a')[0].get_text() for x in html.select('tr')[3:-1]]
elements = list(filter(lambda x: not x.endswith... | 45f93c811172bfdb308dcd59dc16cc5e1f3ed87f | 67,134 |
def removal_dispatcher(template, in_iterables, removal_iterables):
"""First iterates through the list of iterables 'removal_iterables'. Stores
each output from these iterables for later. Then iterates through the list
'in_iterables', removing any output which is present in the output of
'removal_iterabl... | bb7b5f9d61af262f92c92be077d2101cfafefec1 | 67,135 |
import sys
def main():
"""Console script for tally_ho.
***Next steps: Create the command line implementation
Print tables
Functionalize and test argparse setup
Create homebrew formula
Test, check coverage, tag release
"""
cfg_handler = ConfigHandler()
cfg_handler.load_config()... | c37c1a14c640b97719212483246fad0c7970acf3 | 67,136 |
import typing
from typing import Union
from typing import Dict
from typing import Any
def List(
attributes: dict = {},
children: list = [],
class_: str = None,
color: str = None,
dark: bool = None,
dense: bool = None,
disabled: bool = None,
elevation: typing.Union[float, str] = None,
... | 1e6899897c1b75229dfbd1641f445d2663b232b2 | 67,137 |
from datetime import datetime
def dict_more_modules_log_by_filter(
shop_id: int,
module_ids: list,
operator_ids: list,
from_date: datetime,
end_date: datetime,
):
"""
查询多种模块的操作记录
:param shop_id:
:param module_ids:
:param operator_ids:
:param from_date:
:param end_date:
... | 2c5fa6d263b2073bee0d8f6efcc3bd12d41767ab | 67,138 |
import argparse
def parse_args():
"""parse the arguments"""
parser = argparse.ArgumentParser(
description='Converts .raw images to different formats supported by '
'BIOS', epilog="""Example:
$ %(prog)s -g 9 -o image.tandy image.raw
""")
parser.add_argument('filename', metavar='<filename>'... | 4b8cfab1779c2e79b9ddf30aa71233d38ed71a03 | 67,139 |
from zenmapCore_Kvasir.ScriptMetadata import get_script_entries
def script_metadata():
"""
Load nmap script metadata into a dictionary
"""
try:
except ImportError, e:
return dict(error="Cannot load zenmap python library: %s" % (e))
scr_mdata = get_script_entries(settings.nmap_scriptdi... | 01d6cde1257c991647bba2586a10bd357b5646b5 | 67,140 |
from . import database
from .api import api
import os
def create_app(config=None):
"""Perform set up for the backend."""
app = Flask(__name__, instance_path="/app/data", instance_relative_config=True)
app.config["SATS_DB"] = os.path.join(app.instance_path, "sats.db")
app.config["PASSES_DB"] = os.path... | d04973b3726b97a81bd1dad24dc524c3c47983d6 | 67,141 |
def set_new_bounds(new_bounds_file):
"""
Takes in a RD and BAF file.
Returns:
upper_bounds, lower_bounds
"""
upper_bounds = []
lower_bounds = []
#load in file
cols=(1,2,5,6)
X=np.loadtxt(new_bounds_file, usecols=cols)
goodRows = np.logical_and(X[:,2] != -1, X[:,3] != -1)
#Create weighted histogram of poi... | b6a0ab83d567f4a7d7af1c845d477425cbb1e416 | 67,142 |
import collections
def eval_metrics(X, y, mapping, clf, metrics, kfolds=5):
"""
Compute metrics.
"""
kf = KFold(n_splits=kfolds, shuffle=True)
output = collections.defaultdict(list)
y_dist = compute_y_dist(y)
for train_index, test_index in kf.split(X):
X_train, X_test = X[train_ind... | 9ab9dbcdafca3689ebd9052fded5ba6cf3a8fb27 | 67,143 |
from datetime import datetime
import random
def create_processed_items(n_items=10):
"""Generates fake processed items."""
now = datetime.now()
td = timedelta(minutes=3)
return [{
'time_of_quake': convert_to_datetime((now - td * i).isoformat()),
'url': f'https://www.eqx.com/{i + 1:03d}.... | 74f841992c03032c4006f3bc324fc046fbc60224 | 67,144 |
def create_channel_event(
project_id: str, location: str, channel_id: str, event_id: str
) -> str:
"""Creates a channel event.
Args:
project_id: The GCP project ID.
location: The location of the channel.
channel_id: The user-defined channel ID.
event_id: The user-defined even... | f14104d0eb67994f1c12b8fc109c87fbb37912b5 | 67,145 |
def MaslUrl(target_url: str, mask_domain: str, keyword: str) -> str:
"""
Function mask the url with given domain and keyword
"""
url = Shortner(target_url)
return f"{mask_domain}-{keyword}@{urlparse(url).netloc + urlparse(url).path}" | d2ed005f7bc352e84482c0fee1ab2954caf4438b | 67,146 |
import smtplib
import getpass
def setup():
"""Email Setup"""
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(CZAR_USERNAME, getpass("Enter password for {0}:".format(CZAR_EMAIL)))
return server | 384a686cbe614ef19530eb4396b830c576b8b96c | 67,147 |
from typing import Callable
import functools
def thread_exception_decorator(callback: Callable, *callback_args, **callback_kwargs):
"""
多线程异常回调处理装饰器
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwarg... | 2afb4e0fbb8487fcffd9fcf8788426b3ca75b77a | 67,148 |
def db_get_streamer_nickname(channel: str) -> str:
"""Returns channel nickname, if not found it returns the channel's name
"""
cursor.execute(
"SELECT nickname FROM nicknames "
"WHERE channel=?",
(channel.lower(),)
)
data = cursor.fetchall()
if not data:
nickname ... | 85b75c799dce36086e34fd1eecd9c3ffa2961295 | 67,149 |
def patch_byte(*args):
"""patch_byte(ea_t ea, ulong x) -> bool"""
return _idaapi.patch_byte(*args) | 3cc0a0cee71ee5cc613fb4fc66c4758b22ee97d4 | 67,150 |
def delete(id):
"""
This function deletes an existing review
:param id: id of review to delete
:return: 200 on successful delete, 404 otherwise
"""
response = Response.query.filter_by(id=id).one_or_none()
if response is not None:
db.session.delete(response)
db.session.co... | 3b3e5a9686ea779125d81e04f66186b8d2f1ade6 | 67,151 |
def test_aggregate_gets_records_states(configured_test_manager):
"""Inside the aggregate, we should be able to get values from the states of the manually passed in records."""
@aggregate(["output"])
def small_aggregate(record, records):
total = 0
for r in records:
total += r.sta... | 81e91e38a1eeb751f31fab5388514832def094d0 | 67,152 |
def _transition_up(skip_connection, block_to_upsample, filters_to_keep):
"""Performs upsampling on block_to_upsample by a factor 2 and
concatenates it with skip_connection."""
layer = layers.Conv2DTranspose(filters_to_keep,
kernel_size=3,
... | 51db327fa0b7f2232de8731102f281af251bbc02 | 67,153 |
import os
import csv
def read_formula_tsv(formula_type, tsv_names, groupby_list, folder_config=FORMULA_FOLDER_CONFIG, html_escape=False):
"""
Read a formula tsv file by formula_type[slt/latex] and then by its tsv_name[XXX.tsv]
Return a Python dictionary object which is grouped by the field names ... | e6b1b8b42c29068de48be0095e1868ae614b55f1 | 67,154 |
import itertools
def get_words(docs, selections):
"""
Gets the selected words in the provided documents.
:param docs: the document to analyze
:param selections: the words selected in the documents
:return: a dictionary with the documents and for each a list of
the selected words
"""
i... | 2c0396ac8de4eae19113e46c51a7e07ff9d4d85f | 67,155 |
import socket
import sys
def getaliases(host):
"""Checks for aliases of the given hostname (cname records)
returns a list of alias targets
will return an empty list if no aliases
"""
cnames = []
error = None
try:
answers = dns.resolver.query(host, 'cname')
except dns.exception... | 01d284b19fcbd331032ddd461885b388d0e598d6 | 67,156 |
from bs4 import BeautifulSoup
import urllib
def get_paper_detail_from_paperlist_page(paper_list_url):
"""
get the all papers' session name, title and abs link from paper list url
:param paper_list_url:
:return:
"""
r = Request(paper_list_url, headers={'User-Agent': 'Mozilla/5.0'})
content ... | 44e33a2f7e82e88738415d3ca852e84c31d82d89 | 67,157 |
def Vec3_nrow():
"""Vec3_nrow() -> int"""
return _simbody.Vec3_nrow() | 713f0a7b9dc26efb2113cf74b63fb06a56f52ea9 | 67,158 |
def unquote(text, exceptions=''):
"""Unquote a text but ignore the exceptions.
>>> unquote('foo%23bar')
'foo#bar'
>>> unquote('foo%23bar', ['#'])
'foo%23bar'
"""
if not text:
if text is None:
raise TypeError('None object cannot be unquoted')
else:
retu... | f149fb57be05d2768c7be692e5838a71a061f702 | 67,159 |
import os
import json
def get_table():
"""
Loads a lightweight lambda table for use in unit tests to reduce
initialization time, and make unit tests insensitive to changes in the
default lambda table.
"""
data_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
... | 1a75391668503412c4b2ad7d92291c6924ddbc35 | 67,160 |
def generate_ns_record_parameters(**kwargs):
"""Generates parameters for 'NS' records."""
return generate_dns_record_parameters(record_type='NS',
validate_record_as='domain-name',
**kwargs) | 0f67369473042c15c657c3d8d324c2568e5a100f | 67,161 |
from typing import Tuple
def distance_nb_moves(pos_1: Tuple[int, int], pos_2: Tuple[int, int]):
"""
:param pos_1:
:param pos_2:
:return: The number of moves to move from pos_1 to pos_2
"""
# We calculate the number of moves to do in diagonal
x_init, y_init = pos_1
x_final, y_final = po... | 949ff9994eecfaf4b0285318f9a2373d935b6ab0 | 67,162 |
def try_get_uuid(value):
"""
gets the uuid object of given value.
it returns None if value is not a valid uuid string.
:param str value: value to get uuid instance from it.
:rtype: uuid.UUID
"""
try:
return get_uuid(value)
except Exception:
return None | 0953891bd76c4406c78c3f24f430bcaf832ea01a | 67,163 |
from typing import Optional
def luhn(base: str, num_only: Optional[bool] = False,
allow_lower_case: Optional[bool] = False) -> int:
"""Return the Luhn check digit for the given string.
Args:
base(str): string for which to calculate the check digit
num_only(bool): allow only digits in... | 5d78e57d42b7406838e89bffde6a2d249b9a80a5 | 67,164 |
def useful_person_for_subjects(
person_main_topics: list,
scopus_topics: list,
k_relevant: int = 1) -> bool:
"""
Get possibility status use person for subject
Args:
person_main_topics:
scopus_topics: topics list in ScopusScienceTopicSearch class format
k_relev... | df567a755dc6a5f4df57ed3654f407fb27655cd5 | 67,165 |
import os
import fnmatch
def allfiles(dir, pattern="*"):
"""
Return list<string> all files in subtree dir, optionally matching
a pattern spec like "*.java"
"""
dir = uniformpath(dir)
if not os.path.isdir(dir): # must be file
return [dir]
matching_files = []
for root, subFolder... | 74b5e5e03677604d5d6279042782043cd6111154 | 67,166 |
from typing import Any
def text_one_of(x: str) -> Parser:
"""Parses any of the characters in `x`."""
@parser
def g(c: Cursor, a: Any):
options = [literal(ch.encode(c.encoding)) for ch in x]
return choice(*options)(c, a)
return g | 9ac4d35df1b35425dc241a370e8cbd3eb4311886 | 67,167 |
import json
import os
def run(seq, args=None):
"""
expects `seq` to be a stream of midi events in form: [(time, [status_byte, data_bytes+])*]
"""
# load config
with open(constants.config_path) as config_file:
config = json.load(config_file)
model_config = config["model"]
inference_config = ... | ee179082e0601fb80ea3ac851c61cf3bd53033ec | 67,168 |
def collapsed_velocities_from_ring_vortices(
points,
back_right_vortex_vertices,
front_right_vortex_vertices,
front_left_vortex_vertices,
back_left_vortex_vertices,
strengths,
ages=None,
nu=0.0,
):
"""This function takes in a group of points, and the attributes of a group of
ring... | 9af4ffaf1dc26b8a3e1dcc1b8cceb353ba0071ca | 67,169 |
from typing import Match
def _get_match():
"""Function used to return a Match instance."""
return Match(in_port=80, dl_src='01:02:03:04:05:06',
dl_dst='01:02:03:04:05:06', dl_vlan=1,
dl_vlan_pcp=1, dl_type=1,
nw_tos=1, nw_proto=1,
nw_src='192... | c6bd5f3f60c552373b88be918186697a42d4e10d | 67,170 |
def NumIsolatedLoads():
"""(read-only) Number of isolated loads"""
return lib.Topology_Get_NumIsolatedLoads() | cbcc2fc1735afbbcaf11283a4af7bf21fd2f007e | 67,171 |
import re
def get_ver():
"""format check"""
with open("./fitgrid/__init__.py", "r") as stream:
fg_ver = re.search(
r".*__version__.*=.*[\"\'](?P<ver_str>\d+\.\d+\.\d+\S*)[\'\"].*",
stream.read(),
)
if fg_ver is None:
msg = """
fitgrid.__init__.py m... | 70d6e7c1938751cf260d666c7bfab10fe1356cd0 | 67,172 |
def update_event(name):
"""updates the time for a single event identified by the name passed in via the URL path
"""
global apiInstance
return apiInstance.update_event(name,request.args.get('weekdayTime'),request.args.get('weekendTime')) | 3df1e8848f639347aeb1429a9664ad2548ce6815 | 67,173 |
def set_user_settings():
"""
Gets the user's name and email address so the recommendations could be sent
"""
if APP_ENV == "development":
USER_NAME = input("Please enter your name: ")
RECIEVE_ADDRESS = input("Please enter your email address: ")
else:
USER_NAME = NAME
... | 21cdddb9beb2641fb3d0189cd47ce42e66f8f8c7 | 67,174 |
import unicodedata
import string
def normalize(word):
""" Remove special characters
"""
return "".join(c for c in unicodedata.normalize('NFKD', word) if c in string.ascii_letters).lower() | a9e9df9163a1e1869b24f46dd781851e522f8313 | 67,175 |
def get_hpa(gasprice, hashpower):
"""gets the hash power accpeting the gas price over last 200 blocks"""
hpa = hashpower.loc[gasprice >= hashpower.index, 'hashp_pct']
if gasprice > hashpower.index.max():
hpa = 100
elif gasprice < hashpower.index.min():
hpa = 0
else:
hpa = hpa... | aef3195b11ea411af8871f0925dc115aa52b7d4e | 67,176 |
def format_line_obj(line_obj, ordered_attributes, delimiter):
"""Formats an object into delimited string
If attribute not found, a ':(' will be inserted instead
"""
return str(delimiter).join((str(line_obj.__dict__.get(attr, ':(')) for attr in ordered_attributes)) | be7da1fa6bd080047bdd235d332b72e770dcfa48 | 67,177 |
def create_input_dataflow(dataset_type: DatasetType, filename: str, shuffle: bool = False) -> DataFlow:
"""Create dataflow from a single dataset with a unified output structure:
Dict[dataset: str, idx: List[int, int], timestamps: List[float, float], clouds: List[np.ndarray, np.ndarray],
transform: np.ndarra... | e5292f98c55fc9c2c499f45d71e693a834ff76a3 | 67,178 |
def _write_igas(parameters, verbose):
"""Write gas zones."""
out = []
if "zones" not in parameters:
return out
ngtypes = {
"initial_gases": 0,
"injection_gases": 0,
}
for key in ngtypes:
if key in parameters["zones"]:
ngtypes[key] = len(parameters["z... | 33416ef778f94c8415ab6935d585a1ae7eb446ca | 67,179 |
import requests
from bs4 import BeautifulSoup
import re
def process_entry(link):
"""
Retrieve data of single entry.
:param link: string for link to entry
:return entry_dict: dictionary of data about entry
"""
entry_dict = {}
# Retrieve the article and create a soup
... | ac16920bbb897f23d2116acdff9385df4a96540d | 67,180 |
import pickle
def loadArray(fileName):
"""Load pickled ndarray"""
logger.debug("Loading Mat: %s" % fileName)
pklFile = open(fileName, 'rb')
array = pickle.load(pklFile)
pklFile.close()
return array | 30cb950396d2fab9b133531278af1ed5c8bc3d22 | 67,181 |
def status():
"""
Retrieve the status of the PRNG
:return: True if the PRNG is seeded enough, false otherwise
"""
return _lib.RAND_status() | f6bf9a0c62d6bd3ea75cece1e14c7f6c13a8e804 | 67,182 |
def rcts_cnf_fs(
rct_infos, thy_info, run_prefix, save_prefix,
hbond_cutoffs=None, nprocs=1):
""" set reactant filesystem stuff
"""
rct_cnf_fs = ()
for rct_info in rct_infos:
mod_thy_info = tinfo.modify_orb_label(
thy_info, rct_info)
# Build filesys for ini... | f3898e32b2034ffa3391f930172862e93dc7f60e | 67,183 |
import torchvision
def resnet50_fasterRCNN(num_classes, pretrained = True):
"""Faster-RCNN architecture construction, whose backbone
is a Resnet50.
Keyword arguments:
- num_classes: number of classes
"""
backbone = resnet50_pt(pretrained)
backbone.out_channels = 2048
anchor_gener... | fbb238200b497e650bd1ee84862812fecfde9f58 | 67,184 |
from typing import Optional
import shutil
def search_default(tool_name: str) -> Optional[str]:
"""
默认搜索
:param tool_name: 要搜索的工具
:return: 搜索成功返回搜索结果,否则None
"""
result = shutil.which(str.encode("utf-8"))
return result | fdd15e55490caeea618c7f4147a987d5ece565c3 | 67,185 |
def get_line_number2(value, matrix):
"""
Function used to get the line number of a value in a array.
Parameters
-------------
value : 'float'
Value of interest.
matrix : 'numpy.ndarray'
Vector with the value of interest.
Returns
------------
Index
"""
for i, line in enumerate(matrix, 1):
... | ed888704f0a29c903c32d806c1bed0a0f172e68f | 67,186 |
def _b2Vec2Array_frompointer(*args, **kwargs):
"""_b2Vec2Array_frompointer(b2Vec2 t) -> _b2Vec2Array"""
return _Box2D._b2Vec2Array_frompointer(*args, **kwargs) | 80a952a6081d2b94a7785f18d39d3b61c2054e67 | 67,187 |
def build_fast_index_structures(mapit, csize):
"""
:param mapit:
:param csize:
:return:
"""
# Default: all positions masked (1), all positions not conserved
# Set position to 0 (unmask) if the position is conserved
consmask = np.ones(csize, dtype=np.bool)
for block in mapit:
... | 43bc6e99d78e2f38a29aac85f24a32784c813e40 | 67,188 |
from typing import Optional
def get_category(category: UnitCategoryModel) -> Optional[UnitCollectionModel]:
"""
Gets the given collection of measurement quantities for the given
dimensionality of measurement.
"""
res = algorithms.find(lambda c: c.unit_type == category, _models)
return res | d150490a5da59f9cf31461a8cd7ebc797d9669ac | 67,189 |
def get_username(details, user=None, *args, **kwargs):
"""Return an username for new user. Return current user username
if user was given.
"""
if user:
return {'username': user.username}
warn_setting('SOCIAL_AUTH_FORCE_RANDOM_USERNAME', 'get_username')
warn_setting('SOCIAL_AUTH_DEFAULT_... | 73dd04b83d26f57d39ffffe5fdbda23a0966e9bf | 67,190 |
from typing import Generator
def create_circuit(depth: int) -> LearningCircuit:
"""
Create a circuit which is equivalent to the one introduced in PennyLane's tutorial:
https://pennylane.ai/qml/demos/tutorial_variational_classifier.html
"""
def prepare_state(circuit: LearningCircuit) -> None:
... | 28ad2253a48a0328389008cd0d679179f537a857 | 67,191 |
import collections
def get_families(fonts):
"""Group fonts into families, separate into hinted and unhinted, select
representative."""
family_id_to_fonts = collections.defaultdict(set)
families = {}
for font in fonts:
family_id = noto_font_to_family_id(font)
family_id_to_fonts[family_id].add(font)
... | 16046b4a7869e194d3a1ac5485e104e687f07d10 | 67,192 |
def pyramid(n):
"""
Write a function that when given a number >= 0,
returns an Array of ascending length subarrays.
Note: the subarrays should be filled with 1s
:param n:
:return:
"""
result = []
if n is None or n == 0:
return result
for n in range(1, n + 1):
re... | 0d63f8fdfe5c4263ebe4e6730e67219a353e5a0f | 67,193 |
def _arg1_attr(identifier):
"""Determine the attribute name for the first argument."""
return TIME_ID if identifier.startswith('t') \
else EVENT_INSTANCE_ID | ff4149a3dde1cdee77b285c52f71de8ffbd7b963 | 67,194 |
def double_exp_rv(a=1, b=1, pa=0.5):
"""
Double exponential distribution, with scale a with
probability pa, and -b with probability (1 - pa), possibly
time-dependent.
Double exponential distribution, with probability distribution
- for ``x`` in ``[0, inf)``, ``pdf(x) = pa*exp(-a*x)*a``
... | 47b250948160fb9e10836dff9796b9f2ec7fe0aa | 67,195 |
import math
def cross_track_distance(lon1, lat1, lon2, lat2, lon3, lat3, d13):
"""
Usage
-----
Angular cross-track-distance of a point (lon3, lat3) from a great-circle path between (lon1, lat1) and (lon2, lat2)
The sign of this distance tells which side of the path the third point is on.
Para... | 12a8073f0e3619d509caba2687e272b13a7aa190 | 67,196 |
def get_application_model():
"""
Return active Appliation model. Use settings to override active model.
"""
try:
app_label, model_name = oauth_api_settings.APPLICATION_MODEL.split('.')
except ValueError:
raise ImproperlyConfigured("APPLICATION_MODEL must be in the form of 'app_label.... | 310fb9f67fb8ae02f5a15c9bc0f4861e01fd9a53 | 67,197 |
def set_advective_derivative(g):
"""
Set how the stencil for the second derivative will be called. Here g is a string
Typically,
ad_i u = g(i, u)
"""
global ad
ad = Function(g)
return ad | 38b501ccd2332f3c54767f8a935f071872d3643d | 67,198 |
from re import M
def WrapTbSignal(signal, tb):
"""Wrap a model signal with a corresponding testbench wrapper."""
if type(signal) is M.BitsSignal:
return BitsTestbench(signal, tb)
elif type(signal) is M.ListSignal:
return ListTestbench(signal, tb)
elif type(signal) is M.BundleSignal:
... | effdec5f1aa93a2472e68fe42d6ee6531be0dc2e | 67,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.