content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def compute_win_state_str_row(n_rows, n_cols, n_connects):
"""Each win state will be a string of 0s and 1s which can
then converted into an integer in base 2.
I assume that at the maximum n_rows = n_cols = 5, which means
that a 31 bit integer (since in Python it's always signed)
should be more th... | 5,331,000 |
def test_xi_transform_vgp_vs_gpr(gpr_and_vgp, xi_transform):
"""
With other transforms the solution is not given in a single step, but it should still give the same answer
after a number of smaller steps.
"""
gpr, vgp = gpr_and_vgp
assert_gpr_vs_vgp(gpr, vgp, gamma=0.01, xi_transform=xi_transfor... | 5,331,001 |
def hmac_sha512(key: bytes, data: bytes) -> bytes:
"""
Return the SHA512 HMAC for the byte sequence ``data`` generated with the
secret key ``key``.
Corresponds directly to the "HMAC-SHA512(Key = ..., Data = ...)" function
in BIP32
(https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#... | 5,331,002 |
def __scheduler_trigger(cron_time_now, now_sec_tuple, crontask, deltasec=2):
"""
SchedulerCore logic
actual time: cron_time_now format: (WD, H, M, S)
actual time in sec: now_sec_tuple: (H sec, M sec, S)
crontask: ("WD:H:M:S", "LM FUNC")
deltasec: sample time window: +/- sec: -sec... | 5,331,003 |
def gen_canvas_config() -> Dict:
"""Generates yaml config from user input for canvas interface
Returns
-------
Dict
canvas config dict
"""
# check for existing canvas config
if (
os.path.exists(CANVAS_CONF_PATH) and
(input("Delete existing canvas config and r... | 5,331,004 |
def retweet(tweet):
"""Attempts to retweet a tweet."""
t.statuses.retweet._id(_id=tweet["id"]) | 5,331,005 |
def get13FAmendmentType(accNo, formType=None) :
"""
Gets the amendment type for a 13F-HR/A filing - may be RESTATEMENT or NEW HOLDINGS.
This turned out to be unreliable (often missing or wrong), so I don't use it to get
the combined holdings for an investor. Instead I just look at the number of holdings... | 5,331,006 |
def tabs_to_cover_string(string):
"""
Get the number of tabs required to be at least the same length as a given string.
:param string: The string
:return: The number of tabs to cover it
:rtype: int
"""
num_tabs = int(np.floor(len(string) / 8) + 1)
return num_tabs | 5,331,007 |
def kl(p, q):
"""
Kullback-Leibler divergence for discrete distributions
Parameters
----------
p: ndarray
probability mass function
q: ndarray
probability mass function
Returns
--------
float : D(P || Q) = sum(p(i) * log(p(i)/q(i))
Discrete probability distribut... | 5,331,008 |
def ProcessDirectory(dirname, output_lines):
"""Processes a directory of batch sim files.
If directory contents are sufficiently old, appends to outfile comments
that describe the directory and a command to remove it.
Args:
dirname: Full Cloud Storage path of the directory, with trailing slash.
output... | 5,331,009 |
def map_uris(uris):
"""Map URIs from external URI to HDFS
:return:
"""
pkgs_path = __pillar__['hdfs']['pkgs_path']
ns = nameservice_names()
return map(lambda x: 'hdfs://{0}{1}/{2}'.format(ns[0], pkgs_path, __salt__['system.basename'](x)), uris) | 5,331,010 |
def delete_task(id: str, db: Session = Depends(get_db)) -> Any:
"""Delete a task"""
try:
todo_interactor = ToDoInteractor(db=db)
todo_interactor.remove(id=id)
return {"success": f"removed task: {id}"}
except HTTPException as e:
logger.exception(e)
raise HTTPException(... | 5,331,011 |
def get_body(name):
"""Retrieve the Body structure of a JPL .bsp file object
Args:
name (str)
Return:
:py:class:`~beyond.constants.Body`
"""
return Pck()[name] | 5,331,012 |
def is_available():
"""
Convenience function to check if the current platform is supported by this
module.
"""
return ProcessMemoryInfo().update() | 5,331,013 |
def test_dequeue(dq):
"""Test append to tail."""
dq.append(2)
assert dq.tail.val == 2 | 5,331,014 |
def render_path_spiral(c2w, up, rads, focal, zrate, rots, N):
"""
enumerate list of poses around a spiral
used for test set visualization
"""
render_poses = []
rads = np.array(list(rads) + [1.])
for theta in np.linspace(0., 2. * np.pi * rots, N+1)[:-1]:
c = np.dot(c2w[:3,:4], np.arra... | 5,331,015 |
def placeAnchorSourceToLagunaTX(
common_anchor_connections: Dict[str, List[Dict[str, Any]]]
) -> List[str]:
"""
The anchors are placed on the Laguna RX registers
We move the source cell of the anchor onto the corresponding TX registers
"""
anchor_to_source_cell = _getAnchorToSourceCell(common_anchor_connect... | 5,331,016 |
def sendEmailWithAttachment(subject, message, from_email, to_email=[], attachment=[]):
"""
:param subject: email subject
:param message: Body content of the email (string), can be HTML/CSS or plain text
:param from_email: Email address from where the email is sent
:param to_email: List of email reci... | 5,331,017 |
def post_example_form():
"""Example of a post form."""
return render_template("post-form.html") | 5,331,018 |
def validate(data):
"""Validates incoming data
Args:
data(dict): the incoming data
Returns:
True if the data is valid
Raises:
ValueError: the data is not valid
"""
if not isinstance(data, dict):
raise ValueError("data should be dict")
if "text" not in data ... | 5,331,019 |
def stripExtra(name):
"""This function removes paranthesis from a string
*Can later be implemented for other uses like removing other characters from string
Args:
name (string): character's name
Returns:
string: character's name without paranthesis
"""
startIndexPer=name.find('(')
start... | 5,331,020 |
def google_maps(maiden: str) -> str:
"""
generate Google Maps URL from Maidenhead grid
Parameters
----------
maiden : str
Maidenhead grid
Results
-------
url : str
Google Maps URL
"""
latlon = toLoc(maiden)
url = "https://www.google.com/maps/@?api=1&map_... | 5,331,021 |
def test_lin_norm_1():
"""Check that negative entries become 0."""
x = torch.ones((5, 5))
x[:, 0] = -1
x_normed = ei.lin_norm(x)
assert all(x_normed[:, 0] == 0)
for row in x_normed[:, 1:]:
assert all(row == 0.25) | 5,331,022 |
def format_signed(feature, # type: Dict[str, Any]
formatter=None, # type: Callable[..., str]
**kwargs
):
# type: (...) -> str
"""
Format unhashed feature with sign.
>>> format_signed({'name': 'foo', 'sign': 1})
'foo'
>>> format_signed({'na... | 5,331,023 |
def load_ligand(sdf):
"""Loads a ligand from an sdf file and fragments it.
Args:
sdf: Path to sdf file containing a ligand.
"""
lig = next(Chem.SDMolSupplier(sdf, sanitize=False))
frags = generate_fragments(lig)
return lig, frags | 5,331,024 |
def CMDpending(parser, args):
"""Lists pending jobs."""
parser.add_option('-b',
'--builder',
dest='builders',
action='append',
default=[],
help='Builders to filter on')
options, args, buildbot = parser.parse_args(a... | 5,331,025 |
def numpy_translation(xyz):
"""Returns the dual quaternion for a pure translation.
"""
res = np.zeros(8)
res[3] = 1.0
res[4] = xyz[0]/2.0
res[5] = xyz[1]/2.0
res[6] = xyz[2]/2.0
return res | 5,331,026 |
def make_crops(bids_folder, metadata_file, out_dir, out_file, new_size):
"""
Create a new dataset of crops from an existing dataset.
Given a folder of images, and a csv file containing the info
about the dataset, this function makes random crops of the images and
save them to disk
bids_folder: ... | 5,331,027 |
def sort_car_models(car_db):
"""return a copy of the cars dict with the car models (values)
sorted alphabetically"""
sorted_db = {}
for model in car_db:
sorted_db[model] = sorted(car_db[model])
return sorted_db | 5,331,028 |
def test_module(params) -> str:
"""Tests API connectivity and authentication'"
Returning 'ok' indicates that the integration works like it is supposed to.
Connection to the service is successful.
Raises exceptions if something goes wrong.
:return: 'ok' if test passed, anything else will fail the tes... | 5,331,029 |
def create(auto_remove: bool = False) -> Tuple[str, str]:
"""
Creates a database inside a docker container
:return: container name, database name
:rtype: Tuple[str, str]
"""
piccolo_docker_repository = PiccoloDockerRepository(auto_remove=auto_remove)
piccolo_docker_repository.create_contain... | 5,331,030 |
def get_by_id(db: Session, work_item_id):
"""Get a specified WorkItem and return it."""
workitem = db.get(WorkItem, work_item_id)
if workitem:
return workitem
if not workitem:
logger.debug("Item not found")
raise HTTPException(status_code=404, detail="Item not found") | 5,331,031 |
def evaluate(args, model, eval_dataset, tokenizer, step, prefix=""):
"""
Evaluation of model
:param args: input arguments from parser
:param model: pytorch model to be evaluated
:param eval_dataset: dataset used for evaluation
:param tokenizer: tokenizer used by the model
:param step: the cu... | 5,331,032 |
def main():
"""
Existing commands:
stop, start, cancel, show, set_work, set_password, set_user, year, day, list,
overtime (ot), public-holiday (public), projects
"""
# Parsing the data
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument('command', type=str)
... | 5,331,033 |
def test(path, shell, indent=2):
"""Run test at path and return input, output, and diff.
This returns a 3-tuple containing the following:
(list of lines in test, same list with actual output, diff)
diff is a generator that yields the diff between the two lists.
If a test exits with return co... | 5,331,034 |
def boot(configfile=None, use_argv=False):
"""Boot the environment containing the classes and configurations."""
setupdir = dirname(dirname(__file__))
curdir = getcwd()
if configfile:
pass # Already a string
elif use_argv and len(sys.argv) > 1:
configfile = sys.argv[1]
... | 5,331,035 |
def load_expected_results(file, pattern):
"""Reads the file, named file, which contains test results separated
by the regular expression pattern.
The test results are returned as a dictionary.
"""
expected = {}
compiled_pattern = re.compile(pattern)
with open(file) as f:
test = None... | 5,331,036 |
def play(index):
""" wiringpiによるソフトウェアトーン再生"""
melody_list = [
((262, 0.5), (294, 0.5), (330, 0.5), (349, 0.5), (392, 0.5), (440, 0.5), (494, 0.5), (525, 0.5)),
((525, 0.5), (494, 0.5), (440, 0.5), (392, 0.5), (349, 0.5), (330, 0.5), (294, 0.5), (262, 0.5)),
((262, 1), (294, 1), (330, 1)... | 5,331,037 |
def following(request):
"""View all posts from followed users"""
if request.method == "GET":
user = User.objects.get(pk=request.user.id)
following = user.follow_list.following.all()
# Post pagination: https://docs.djangoproject.com/en/3.1/topics/pagination/
posts = Post.objects.... | 5,331,038 |
def create_random_polygon(min_x, min_y, max_x, max_y, vertex_num):
"""Create a random polygon with the passed x and y bounds and the passed number of vertices; code adapted from: https://stackoverflow.com/a/45841790"""
# generate the point coordinates within the bounds
x = np.random.uniform(min_x, max_x, ... | 5,331,039 |
def document_hidden(session):
"""Polls for the document to become hidden."""
def hidden(session):
return session.execute_script("return document.hidden")
return Poll(session, timeout=3, raises=None).until(hidden) | 5,331,040 |
def delete_directory_files(directory_path):
"""
Method for deleting temporary html files created by
show in browser process.
"""
for file_object in os.listdir(directory_path):
file_object_path = os.path.join(directory_path, file_object)
if os.path.isfile(file_object_path):
... | 5,331,041 |
def cut_sounds(sound_directory, time):
"""Split file into specific time intervals.
Parameters
----------
sound_directory: str path to the directory for the audio file
time: str duration of the splits
Returns
-------
None
"""
target_path = f'{sound_directory}/split_{time}'
... | 5,331,042 |
def create_blueprint():
"""Creates a Blueprint"""
blueprint = Blueprint('Tasks Blueprint', __name__, url_prefix='/tasks')
blueprint.route('/', methods=['POST'])(tasks.create)
blueprint.route('/', methods=['PATCH'])(tasks.patch)
blueprint.route('/', methods=['GET'])(tasks.list)
return blueprint | 5,331,043 |
def gauss2d(sigma, fsize):
""" Create a 2D Gaussian filter
Args:
sigma: width of the Gaussian filter
fsize: (W, H) dimensions of the filter
Returns:
*normalized* Gaussian filter as (H, W) np.array
"""
#
# You code here
# | 5,331,044 |
def estimate_null_variance_gs(gs_lists, statslist, Wsq, single_gs_hpo=False,
n_or_bins=1):
"""
Estimates null variance from the average of a list of known causal windows
"""
statspaths = {h : p for h, p in [x.rstrip().split('\t')[:2] \
for x in open(sta... | 5,331,045 |
def create_model(config):
"""Create the score model."""
model_name = config.model.name
score_model = get_model(model_name)(config)
score_model = score_model.to(config.device)
score_model = torch.nn.DataParallel(score_model)
return score_model | 5,331,046 |
def at(addr):
"""Look up an object by its id."""
import gc
for o in gc.get_objects():
if id(o) == addr:
return o
return None | 5,331,047 |
def money_flow_index(close_data, high_data, low_data, volume, period):
"""
Money Flow Index.
Formula:
MFI = 100 - (100 / (1 + PMF / NMF))
"""
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume
)
catch_errors.check_for_period_error(close_data, peri... | 5,331,048 |
def get_variable_name(ds, args):
"""Tries to automatically set the variable to plot."""
if args.varn is None:
varns = set(ds.variables.keys()).difference(ds.coords)
if len(varns) == 1:
args.varn = varns.pop()
else:
errmsg = 'More than one variable in data set! Spe... | 5,331,049 |
def copytree(src, dst, symlinks=False, ignore=None):
"""
Copy all the contents of directory scr to directory dst.
:param src: String
Source directory.
:param dst: String
Destination directory.
:param symlinks: default False
:param ignore: default None
:return: None
"""
... | 5,331,050 |
def Get_Weights(dict_rank):
"""Converts rankings into weights."""
Weights = adapt.create_Weightings(dict_rank)
return Weights | 5,331,051 |
def load_client_model(models_path, config):
"""
Returns Pytorch client model loaded given the client model's path
"""
device = load_device()
client_hparams = config.get("client_hparams")
for needed_param in client_hparams.get("needed", []):
client_hparams[needed_param] = config.ge... | 5,331,052 |
def psisloo(log_likelihood):
"""
Summarize the model fit using Pareto-smoothed importance sampling (PSIS)
and approximate Leave-One-Out cross-validation (LOO).
Takes as input an ndarray of posterior log likelihood terms [ p( y_i | theta^s ) ]
per observation unit.
e.x. if using py... | 5,331,053 |
def test_pamap2_varyeps(dataset):
"""
This routine performs a series of tests on the PAMAP2 dataset varying epsilon
"""
eps=[500, 1000, 2000]
num_samples = 100000
minpts = 50
grid=(4,4,4,4)
timing_actual_results = []
timing_theoretical_results = []
Xfull=dataset
# Create sm... | 5,331,054 |
def rxdelim(content: str) -> Tuple[Optional[Pattern], Optional[Pattern]]:
"""
Return suitable begin and end delimiters for the content `content`.
If no matching delimiters are found, return `None, None`.
"""
tp = magic.from_buffer(content).lower()
for rxtp, rxbegin, rxend in DELIMITERS:
... | 5,331,055 |
def main():
"""loxberry plugin for solaredge PV API sends every 5 minutes the actual
power production value to the miniserver"""
# create file strings from os environment variables
lbplog = os.environ['LBPLOG'] + "/solaredge/solaredge.log"
lbpconfig = os.environ['LBPCONFIG'] + "/solaredge/plugin.cfg... | 5,331,056 |
def GenKeyOrderAttrs(soappy_service, ns, type_name):
"""Generates the order and attributes of keys in a complex type.
Args:
soappy_service: SOAPpy.WSDL.Proxy The SOAPpy service object encapsulating
the information stored in the WSDL.
ns: string The namespace the given WSDL-defined type ... | 5,331,057 |
def read_binary_stl(filename):
"""Reads a 3D triangular mesh from an STL file (binary format).
:param filename: path of the stl file
:type filename: str
:return: The vertices, normals and index array of the mesh
:rtype: Mesh
:raises: ValueError
"""
with open(filename, 'rb') as stl_file:... | 5,331,058 |
def exit_if_missing(token: str, org: str, assignment_title: str):
"""
Exit CLI program if missing any required values.
"""
if token is None:
typer.echo(
f'Must specify token key in .stoplightrc or with {TOKEN_OPTION_NAME} option', err=True)
raise typer.Exit(code=1)
if or... | 5,331,059 |
def validate_currency(currency, locale=None):
""" Check the currency code is recognized by Babel.
Accepts a ``locale`` parameter for fined-grained validation, working as
the one defined above in ``list_currencies()`` method.
Raises a `UnknownCurrencyError` exception if the currency is unknown to Babel... | 5,331,060 |
def test__rules__std_L003_process_raw_stack(generate_test_segments):
"""Test the _process_raw_stack function.
Note: This test probably needs expanding. It doesn't
really check enough of the full functionality.
"""
cfg = FluffConfig()
r = get_rule_from_set('L003', config=cfg)
test_stack = g... | 5,331,061 |
def create_plan(
session,
bucket,
s3_object_key,
job_identifier,
parameters,
template_url):
"""Shows a plan of what CloudFormation might create and how much it might cost"""
cfn_client = session.client('cloudformation')
template_summary = cfn_client.get_temp... | 5,331,062 |
def raise302(url):
"""
Return a temporary redirect status and content to the user.
"""
raise web.HTTPStatus('302 Found', [('Location', url)], ['']) | 5,331,063 |
def testing(model, t):
"""TODO: Docstring for testing.
:returns: TODO
"""
model.eval
test_set = trainSet2(t)
test_data = DataLoader(test_set, batch_size)
for x, y in test_data:
result = model(x)
print(result)
print(y)
break | 5,331,064 |
def monotonise_tree(tree, n_feats, incr_feats, decr_feats):
"""Helper to turn a tree into as set of rules
"""
PLUS = 0
MINUS = 1
mt_feats = np.asarray(list(incr_feats) + list(decr_feats))
def traverse_nodes(node_id=0,
operator=None,
threshold=None,
... | 5,331,065 |
def main():
"""Main function."""
syn = login()
args = get_args()
# In order to make >3 Entrez requests/sec, 'email' and 'api_key'
# params need to be set.
Entrez.email = os.getenv('ENTREZ_EMAIL')
Entrez.api_key = os.getenv('ENTREZ_API_KEY')
find_publications(syn, args) | 5,331,066 |
def pythonify_and_pickle(file, out_filename):
"""Convert all the data in the XML file and save as pickled files for
nodes, ways, relations and tags separately.
:param file: Filename (the file will be opened 4 times, so passing a file
object will not work). Can be anything which :module:`digest` ... | 5,331,067 |
def compute_inverse_volatility_weights(df: pd.DataFrame) -> pd.Series:
"""
Calculate inverse volatility relative weights.
:param df: cols contain log returns
:return: series of weights
"""
dbg.dassert_isinstance(df, pd.DataFrame)
dbg.dassert(not df.columns.has_duplicates)
# Compute inve... | 5,331,068 |
def log(msg):
"""
Since this script is used in cron and cron sends mails if there is
stdout, we print ordinarily.
"""
print(msg) | 5,331,069 |
def resattnet164(**kwargs):
"""
ResAttNet-164 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/model... | 5,331,070 |
def write_oldmos(fname, Cas, Cbs=None, mode='w'):
"""
Deprecated. May be deleted at some point.
Write MOs in Cfour OLDMOS format
That means packages of four MOs
C[0,0] C[0,1] C[0,2] C[0,3]
C[1,0] C[1,1] C[1,2] C[1,3]
C[2,0] C[2,1] C[2,2] C[2,3]
... ... ... ...
Format f... | 5,331,071 |
def test_retired_locale_redirects(base_url, slug, retired_locale):
"""Ensure that requests for retired locales properly redirect."""
resp = request("get", f"{base_url}/{retired_locale}{slug}")
assert resp.status_code == 302
slug_parts = slug.split("?")
expected_slug = slug_parts[0].lstrip("/")
e... | 5,331,072 |
def remove_ntp_system_peer(device, system_peer, vrf=None):
""" Remove ntp system peer config
Args:
device (`obj`): Device object
system_peer ('str'): System peer IP address
Returns:
None
Raises:
SubCommandFailure
"""
remove_config = ''... | 5,331,073 |
def stype(obj):
"""
Return string shape representation of structured objects.
>>> import numpy as np
>>> a = np.zeros((3,4), dtype='uint8')
>>> b = np.zeros((1,2), dtype='float32')
>>> stype(a)
'<ndarray> 3x4:uint8'
>>> stype(b)
'<ndarray> 1x2:float32'
>>> stype([a, (b, b)])
... | 5,331,074 |
def board2key(Z):
""" Turn a "Game of Life" board into a key.
"""
return(bin2hex(array2string(Z[1:-1, 1:-1].reshape((1, 512 * 512 * 4))[0]))) | 5,331,075 |
def CipherArray(Array = [[" "]," "], Random = 1):
"""
Array - array to coding
Key - Key number to coding
It's а function that encodes elements
Returns an array consisting of coded elements
"""
if (type(Array) != list):
raise TypeError("Неправильний формат масиву")
if (ty... | 5,331,076 |
def voltage(raw_value, v_min=0, v_max=10, res=32760, gain=1):
"""Converts a raw value to a voltage measurement.
``V = raw_value / res * (v_max - v_min) * gain``
"""
return (float(raw_value) / res * (v_max - v_min) * gain, "V") | 5,331,077 |
def extract_characteristics_from_string(species_string):
"""
Species are named for the SBML as species_name_dot_characteristic1_dot_characteristic2
So this transforms them into a set
Parameters:
species_string (str) = species string in MobsPy for SBML format (with _dot_ instead ... | 5,331,078 |
def _get_bzr_version():
"""Looks up bzr version by calling bzr --version.
:raises: VcsError if bzr is not installed"""
try:
value, output, _ = run_shell_command('bzr --version',
shell=True,
us_env=True)
... | 5,331,079 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Old way of setting up Terncy curtain.
Can only be called when a user accidentally mentions Terncy platform in their
config. But even in that case it would have been ignored.
"""
_LOGGER.info(" terncy curtain a... | 5,331,080 |
def register_blueprints(app: Flask):
"""注册需要的蓝图程序包到 Flask 程序实例 app 中"""
app.register_blueprint(auth_bp)
app.register_blueprint(oauth_bp)
app.register_blueprint(chat_bp)
app.register_blueprint(admin_bp) | 5,331,081 |
def C(source):
"""Compile at runtime and run code in-line"""
return _embed_or_inline_c(source, True) | 5,331,082 |
def normalize(x):
"""Standardize the original data set."""
max_x = np.max(x, axis=0)
min_x = np.min(x, axis=0)
x = (x-min_x) / (max_x-min_x)
return x | 5,331,083 |
def test_indefinite_freeze_attack(using_tuf=False):
"""
<Arguments>
using_tuf:
If set to 'False' all directories that start with 'tuf_' are ignored,
indicating that tuf is not implemented.
The idea here is to expire timestamp metadata so that the attacker
"""
ERROR_MSG = '\tIndefinite Fre... | 5,331,084 |
def _diff_bearings(bearings, bearing_thresh=40):
"""
Identify kinked nodes (nodes that change direction of an edge) by diffing
Args:
bearings (list(tuple)): containing (start_node, end_node, bearing)
bearing_thresh (int): threshold for identifying kinked nodes (range 0, 360)
Return... | 5,331,085 |
def update_holidays(cal: TextIOWrapper):
"""ics file from e.g., https://www.calendarlabs.com/ical-calendar/holidays/norway-holidays-62/"""
import_calendar(cal) | 5,331,086 |
async def request(method: str,
url: str,
params: dict = None,
data: Any = None,
credential: Credential = None,
no_csrf: bool = False,
json_body: bool = False,
**kwargs):
"""
向接口... | 5,331,087 |
def InflRate():
"""Inflation rate"""
return asmp.InflRate() | 5,331,088 |
def evaluate(FLAGS, y_test, y_score, n_class):
"""Evaluate the quality of the model
Args:
FLAGS (argument parser): input information
y_test (2D array): true label of test data
y_score (2D) array: prediction label of test data
n_class (int): number of classes
Returns:
... | 5,331,089 |
def author_single_view(request, slug):
"""
Render Single User
:param request:
:param slug:
:return:
"""
author = get_object_or_404(Profile, slug=slug)
author_forum_list = Forum.objects.filter(forum_author=author.id).order_by("-is_created")[:10]
author_comments = Comment.objects.filte... | 5,331,090 |
def get_predefined(schedule):
"""
Predefined learn rate changes at specified epochs
:param schedule: dictionary that maps epochs to to learn rate values.
"""
def update(lr, epoch):
if epoch in schedule:
return floatX(schedule[epoch])
else:
return f... | 5,331,091 |
def launch_ec2_instances(config, nb=1):
"""
Launch new ec2 instance(s)
"""
conf = config[AWS_CONFIG_SECTION]
ami_image_id = conf.get(AMI_IMAGE_ID_FIELD)
ami_name = conf.get(AMI_IMAGE_NAME_FIELD)
if ami_image_id and ami_name:
raise ValueError('The fields ami_image_id and ami_image_nam... | 5,331,092 |
def residual_error(X_train,X_test,y_train,y_test, reg="linear"):
"""
Plot the residual error of the Regresssion model for the input data,
and return the fitted Regression model.
-------------------------------------------------------------------
# Parameters
# X_train,X_test,y_train,y_test (np.arrays): G... | 5,331,093 |
def next_row(update, context):
"""Increase the row, append one if necessary."""
cid = update.message.chat_id
user = ClassDB.get_user(cid)
row = context.chat_data["row"] + 1
context.chat_data["col"] = 0
# append row when index exceeded
if row == len(user.temp_question.keyboard):
use... | 5,331,094 |
def ListMethods(dev):
"""List user-callable methods for the device.
Example:
>>> ListMethods(phi)
"""
dev = session.getDevice(dev, Device)
items = []
listed = builtins.set()
def _list(cls):
if cls in listed:
return
listed.add(cls)
for name, (args, d... | 5,331,095 |
def centerSquare(pil_img: Image.Image):
"""Adds padding on both sides to make an image square. (Centered)"""
pil_img = pil_img.convert('RGBA') # ensure transparency
background_color = (0, 0, 0, 0)
width, height = pil_img.size
if width == height:
return pil_img
elif width > height:
... | 5,331,096 |
def _convert_steplist_to_string(step_data):
"""Converts list of step data into a single string.
Parameters
----------
step_data : list
List of step data
Returns
-------
str
A space delimited string where every 6th value is followed by a newline.
"""
text = ''
for i, datum in enumerate(step_data):
... | 5,331,097 |
def get_global_public_delegated_prefix(project: Optional[str] = None,
public_delegated_prefix: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetGlobalPublicDelegatedPrefixResult:
"""
Returns the specif... | 5,331,098 |
def evol_indices(
out,
msa_data_folder,
msa_list,
protein_index,
theta_reweighting,
model_parameters_location,
computation_mode,
num_samples_compute_evol_indices,
batch_size,
device,
):
""" Compute evolutionary indices """
# Generate paths to output folders and make new ... | 5,331,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.