content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _check_molecule_format(val):
"""If it seems to be zmatrix rather than xyz format we convert before returning"""
atoms = [x.strip() for x in val.split(";")]
if atoms is None or len(atoms) < 1: # pylint: disable=len-as-condition
raise QiskitNatureError("Molecule format error: " + val)
# An x... | d546251f02c6ee3bfe44256edff439ba4d3b4c31 | 2,418 |
def measure_area_perimeter(mask):
"""A function that takes either a segmented image or perimeter
image as input, and calculates the length of the perimeter of a lesion."""
# Measure area: the sum of all white pixels in the mask image
area = np.sum(mask)
# Measure perimeter: first find which p... | f443b7208c8c452480f0f207153afc5aa1f11d41 | 2,419 |
from typing import Any
from unittest.mock import Mock
def mock_object(**params: Any) -> "Mock": # type: ignore # noqa
"""creates an object using params to set attributes
>>> option = mock_object(verbose=False, index=range(5))
>>> option.verbose
False
>>> option.index
[0, 1, 2, 3, 4]
"""
... | 52140b52d29a424b3f16f0e26b03c19f4afbb0b4 | 2,421 |
def get_words(message):
"""Get the normalized list of words from a message string.
This function should split a message into words, normalize them, and return
the resulting list. For splitting, you should split on spaces. For
normalization, you should convert everything to lowercase.
Args:
... | dec592d3574da70c27368c4642f5fa47d23b5225 | 2,422 |
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
if sum - root.val == 0 and root.left is None and root.right is None:
return True
else:
return self.hasPathSum(root.left, sum - root.val) or sel... | ffab5b8205aa9785c86ac365bd6e854319138627 | 2,424 |
def _(node: IntJoin, ctx: AnnotateContext) -> BoxType:
"""All references available on either side of the Join nodes are available."""
lt = box_type(node.over)
rt = box_type(node.joinee)
t = union(lt, rt)
node.typ = t
return t | c5d2c94f58c019399ebfcc431994ab339f317b0c | 2,425 |
import json
def detect_global_table_updates(record):
"""This will detect DDB Global Table updates that are not relevant to application data updates. These need to be
skipped over as they are pure noise.
:param record:
:return:
"""
# This only affects MODIFY events.
if record['eventName... | 43d9cd6558b0e935a4e195e80932104699564230 | 2,426 |
from typing import List
import warnings
def fix_telecined_fades(clip: vs.VideoNode, tff: bool | int | None = None,
thr: float = 2.2) -> vs.VideoNode:
"""
A filter that gives a mathematically perfect solution to fades made *after* telecining
(which made perfect IVTC impossible). Thi... | d28b78bdb65ffc0c1d354fbbde25391d7ce389b1 | 2,427 |
from typing import Union
from typing import Optional
from io import StringIO
def compare_rdf(expected: Union[Graph, str], actual: Union[Graph, str], fmt: Optional[str] = "turtle") -> Optional[str]:
"""
Compare expected to actual, returning a string if there is a difference
:param expected: expected RDF. C... | f2e128e1c43c5c207e99c30bb32c14f4c4b71798 | 2,429 |
def start_engine(engine_name, tk, context):
"""
Creates an engine and makes it the current engine.
Returns the newly created engine object. Example::
>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/project_root")
>>> ctx = tk.context_empty()
>>> engine = sgtk.platform.... | bb755d359f5a950aa182545803de0a1ca4d6aaee | 2,430 |
def parse_vaulttext(b_vaulttext):
"""Parse the vaulttext.
Args:
b_vaulttext: A byte str containing the vaulttext (ciphertext, salt,
crypted_hmac).
Returns:
A tuple of byte str of the ciphertext suitable for passing to a Cipher
class's decrypt() function, a byte str of the salt, and a byte str... | 1b1b6e2aaf1893401d93f750248892ffebae26a6 | 2,431 |
import sqlite3
def does_column_exist_in_db(db, table_name, col_name):
"""Checks if a specific col exists"""
col_name = col_name.lower()
query = f"pragma table_info('{table_name}');"
all_rows = []
try:
db.row_factory = sqlite3.Row # For fetching columns by name
cursor = db.cursor()... | 90abc20c9643e93641e37c0e94fd504cbcf09928 | 2,432 |
import hmac
def make_secure_val(val):
"""Takes hashed pw and adds salt; this will be the cookie"""
return '%s|%s' % (val, hmac.new(secret, val).hexdigest()) | 6b29f5f3a447bca73ac02a1d7843bdbb6d982db9 | 2,433 |
import random
def get_ad_contents(queryset):
"""
Contents의 queryset을 받아서 preview video가 존재하는 contents를 랜덤으로 1개 리턴
:param queryset: Contents queryset
:return: contents object
"""
contents_list = queryset.filter(preview_video__isnull=False)
max_int = contents_list.count() - 1
if max_int ... | 233d1e5f736a9cff38731dd292d431f098bee17a | 2,434 |
def Image_CanRead(*args, **kwargs):
"""
Image_CanRead(String filename) -> bool
Returns True if the image handlers can read this file.
"""
return _core_.Image_CanRead(*args, **kwargs) | f82e31860480611baf6a5f920515466c0d37acab | 2,435 |
def flatten(lst):
"""Flatten a list."""
return [y for l in lst for y in flatten(l)] if isinstance(lst, (list, np.ndarray)) else [lst] | 0aed241d06725dee9a99512ab2ea5c3f6c02008d | 2,436 |
def calc_mean_score(movies):
"""Helper method to calculate mean of list of Movie namedtuples,
round the mean to 1 decimal place"""
ratings = [m.score for m in movies]
mean = sum(ratings) / max(1, len(ratings))
return round(mean, 1) | 6f837ff251e6221227ba4fa7da752312437da90f | 2,437 |
def srun(hosts, cmd, srun_params=None):
"""Run srun cmd on slurm partition.
Args:
hosts (str): hosts to allocate
cmd (str): cmdline to execute
srun_params(dict): additional params for srun
Returns:
CmdResult: object containing the result (exit status, stdout, etc.) of
... | 2e339d90c2de4b1ae81f7e4671c1f726a725a68c | 2,438 |
def COSclustering(key, emb, oracle_num_speakers=None, max_num_speaker=8, MIN_SAMPLES=6):
"""
input:
key (str): speaker uniq name
emb (np array): speaker embedding
oracle_num_speaker (int or None): oracle number of speakers if known else None
max_num_speakers (int): maximum number of clusters to ... | a3b967251683da1e29004a937625d7006a0519ed | 2,439 |
import torch
def gauss_distance(sample_set, query_set, unlabeled_set=None):
""" (experimental) function to try different approaches to model prototypes as gaussians
Args:
sample_set: features extracted from the sample set
query_set: features extracted from the query set
query_set: feat... | b7583988d79d70bda9c3ab6ee0690042645ed714 | 2,440 |
def make_mps_left(mps,truncate_mbd=1e100,split_s=False):
"""
Put an mps into left canonical form
Args:
mps : list of mps tensors
The MPS stored as a list of mps tensors
Kwargs:
truncate_mbd : int
The maximum bond dimension to which the
mps shoul... | f2de408b82877050bf24a822c54b4520dad40f2e | 2,441 |
def word_after(line, word):
"""'a black sheep', 'black' -> 'sheep'"""
return line.split(word, 1)[-1].split(' ', 1)[0] | cfa16244d00af8556d7955b7edeb90bac0a213ba | 2,442 |
def domain_in_domain(subdomain, domain):
"""Returns try if subdomain is a sub-domain of domain.
subdomain
A *reversed* list of strings returned by :func:`split_domain`
domain
A *reversed* list of strings as returned by :func:`split_domain`
For example::
>>> domain_in_domain([... | cb1b3a3f899f13c13d4168c88ca5b9d4ee345e47 | 2,443 |
def polygon_from_boundary(xs, ys, xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, xtol=0.0):
"""Polygon within box left of boundary given by (xs, ys)
xs, ys: coordinates of boundary (ys ordered increasingly)
"""
xs = np.asarray(xs)
ys = np.asarray(ys)
xs[xs > xmax-xtol] = xmax
xs[xs < xmin+xt... | 4e75cd8b11038432224836b427658226d4c820d7 | 2,444 |
def is_degenerate(op, tol=1e-12):
"""Check if operator has any degenerate eigenvalues, determined relative
to mean spacing of all eigenvalues.
Parameters
----------
op : operator or 1d-array
Operator or assumed eigenvalues to check degeneracy for.
tol : float
How much closer tha... | 2d2672c711c1e4320de151484cdeb7463cf0abd8 | 2,445 |
def _get_skip_props(mo, include_operational=False, version_filter=True):
"""
Internal function to skip mo property if not to be considered for sync.
"""
skip_props = []
for prop in mo.prop_meta:
mo_property_meta = mo.prop_meta[prop]
if mo_property_meta is None:
continue
... | dd24798c84f47a954eb324092c3cfb46c23a062e | 2,446 |
def generate_split_problem():
"""Generates a 'Split' problem configuration.
Returns (environment, robot, start configuration, goal configuration)."""
walls = [rectangle(0, 400, 0, 10), rectangle(0, 400, 290, 300),
rectangle(0, 10, 0, 300), rectangle(390, 400, 0, 300),
rectangle(18... | a2a3ab0495dcf5a109ed2eb2e92bb0db424edd53 | 2,447 |
def problem_generator(difficulty=3):
"""
This function generates mathematical expressions as string. It is not very
smart and will generate expressions that have answers the lex function
cannot accept.
"""
operators = ["/", "*", "+", "-"]
numeric_lim = difficulty * 7
output = ""
... | f1859784a065a22adb83c33d46623fcafa470096 | 2,448 |
from typing import Tuple
import math
def logical_factory_dimensions(params: Parameters
) -> Tuple[int, int, float]:
"""Determine the width, height, depth of the magic state factory."""
if params.use_t_t_distillation:
return 12*2, 8*2, 6 # Four T2 factories
l1_dista... | 95846f5f58e5c342ca81b3f51a9bacfb31bf777a | 2,449 |
def data():
"""
Data providing function:
This function is separated from create_model() so that hyperopt
won't reload data for each evaluation run.
"""
d_file = 'data/zinc_100k.h5'
data_train, data_test, props_train, props_test, tokens = utils.load_dataset(d_file, "TRANSFORMER", True)
... | 354ace6fdfc9f8f9ec0702ea8a0a03853b8d7f49 | 2,451 |
def mongos_program(logger, job_num, executable=None, process_kwargs=None, mongos_options=None): # pylint: disable=too-many-arguments
"""Return a Process instance that starts a mongos with arguments constructed from 'kwargs'."""
args = [executable]
mongos_options = mongos_options.copy()
if "port" not ... | a342db697d39e48ea0261e5ddfd89bdd99b6dced | 2,453 |
def markerBeings():
"""标记众生区块
Content-Type: application/json
{
"token":"",
"block_id":""
}
返回 json
{
"is_success":bool,
"data":
"""
try:
info = request.get_json()
# 验证token
token = info["token"]
i... | 20b73bec5f6c27e365a90fe466e34445592f2bd3 | 2,454 |
def get_charges_with_openff(mol):
"""Starting from a openff molecule returns atomic charges
If the charges are already defined will return them without
change
I not will calculate am1bcc charges
Parameters
------------
mol : openff.toolkit.topology.Molecule
Examples
---------
... | fa539ef60fda28a4983d632830f3a8ea813f5486 | 2,455 |
def parse_mdout(file):
"""
Return energies from an AMBER ``mdout` file.
Parameters
----------
file : os.PathLike
Name of Amber output file
Returns
-------
energies : dict
A dictionary containing VDW, electrostatic, bond, angle, dihedral, V14, E14, and total energy.
... | 9310b0220d4b96b65e3484adf49edebda039dfad | 2,456 |
from propy.AAComposition import GetSpectrumDict
from typing import Optional
from typing import List
def aa_spectrum(
G: nx.Graph, aggregation_type: Optional[List[str]] = None
) -> nx.Graph:
"""
Calculate the spectrum descriptors of 3-mers for a given protein. Contains the composition values of 8000 3-mers... | dfd657452fda009c4420566f1456dc4bd32271ac | 2,457 |
import hashlib
def get_click_data(api, campaign_id):
"""Return a list of all clicks for a given campaign."""
rawEvents = api.campaigns.get(campaign_id).as_dict()["timeline"]
clicks = list() # Holds list of all users that clicked.
for rawEvent in rawEvents:
if rawEvent["message"] == "Clicked ... | 641836d73b2c5b2180a98ffc61d0382be74d2618 | 2,458 |
def multi_label_column_to_binary_columns(data_frame: pd.DataFrame, column: str):
"""
assuming that the column contains array objects,
returns a new dataframe with binary columns (True/False)
indicating presence of each distinct array element.
:data_frame: the pandas DataFrame
... | ab626530181740fc941e8efbbaf091bc06f0a0d8 | 2,459 |
def _GetBuilderPlatforms(builders, waterfall):
"""Get a list of PerfBuilder objects for the given builders or waterfall.
Otherwise, just return all platforms.
"""
if builders:
return {b for b in bot_platforms.ALL_PLATFORMS if b.name in
builders}
elif waterfall == 'perf':
return bot_pl... | f6d7e636bcbd941b1dde8949c68be295e0aef227 | 2,462 |
def meeting_guide(context):
"""
Display the ReactJS drive Meeting Guide list.
"""
settings = get_meeting_guide_settings()
json_meeting_guide_settings = json_dumps(settings)
return {
"meeting_guide_settings": json_meeting_guide_settings,
"mapbox_key": settings["map"]["key"],
... | 46d8d20fcb2bd4dacd45a510f51eaea292da0da6 | 2,463 |
import multiprocessing
def generate_input_fn(file_path, shuffle, batch_size, num_epochs):
"""Generates a data input function.
Args:
file_path: Path to the data.
shuffle: Boolean flag specifying if data should be shuffled.
batch_size: Number of records to be read at a time.
num... | abf9dd66000eca392344f9663fa8418b9e596098 | 2,464 |
import numpy
def amp_phase_to_complex(lookup_table):
"""
This constructs the function to convert from AMP8I_PHS8I format data to complex64 data.
Parameters
----------
lookup_table : numpy.ndarray
Returns
-------
callable
"""
_validate_lookup(lookup_table)
def converter(... | dea38027654a5a2b6ab974943dbdc57b36835a8e | 2,465 |
from operator import concat
def combine_aqs_cmaq(model, obs):
"""Short summary.
Parameters
----------
model : type
Description of parameter `model`.
obs : type
Description of parameter `obs`.
Returns
-------
type
Description of returned object.
"""
g... | bbc6ba6faf0f580d35674a912c245349d00d2a95 | 2,466 |
def read_1d_spikes(filename):
"""Reads one dimensional binary spike file and returns a td_event event.
The binary file is encoded as follows:
* Each spike event is represented by a 40 bit number.
* First 16 bits (bits 39-24) represent the neuronID.
* Bit 23 represents the sign of spike ... | 034d6de1e38734fcfe131027956d781752163c33 | 2,468 |
def _parse_step_log(lines):
"""Parse the syslog from the ``hadoop jar`` command.
Returns a dictionary which potentially contains the following keys:
application_id: a string like 'application_1449857544442_0002'. Only
set on YARN
counters: a map from counter group -> counter -> amount, or None... | 251b0e89157a1c3fa152cbf50daa5e0b10e17bcc | 2,469 |
import re
def is_regex(regex, invert=False):
"""Test that value matches the given regex.
The regular expression is searched against the value, so a match
in the middle of the value will succeed. To specifically match
the beginning or the whole regex, use anchor characters. If
invert is true, th... | 0db71b3dae2b2013650b65ecacfe6aed0cd8366b | 2,470 |
def get_obj(obj):
"""Opens the url of `app_obj`, builds the object from the page and
returns it.
"""
open_obj(obj)
return internal_ui_operations.build_obj(obj) | f6deddc62f7f3f59ab93b553c64b758340b5fa6c | 2,471 |
def process(frame):
"""Process initial frame and tag recognized objects."""
# 1. Convert initial frame to grayscale
grayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# For every model:
for model, color, parameters in (
(MODEL_FACE, (255, 255, 0), {'scaleFactor': 1.1, 'minNeighbors': ... | c0c977d522f292d6cbb03c4e64eabc3d11342e0f | 2,472 |
from datetime import datetime
def tzoffset():
"""UTC to America/New_York offset."""
return datetime.timedelta(hours=5) | 05e883eeae63ad1dd7b287dd0b331b13b11b8cd1 | 2,473 |
def KICmag(koi,band):
"""
Returns the apparent magnitude of given KOI star in given band. returns KICmags(koi)[band]
"""
return KICmags(koi)[band] | 767ff04c9319acd698daa05f084e8ee9c456a628 | 2,475 |
from typing import List
def list_to_decimal(nums: List[int]) -> int:
"""Accept a list of positive integers in the range(0, 10)
and return a integer where each int of the given list represents
decimal place values from first element to last. E.g
[1,7,5] => 175
[0,3,1,2] => 312
... | 7727ce610987fc9da03a5e23ec8674d1deb7c7f0 | 2,476 |
def str_to_bool(v):
"""
:type v: str
"""
return v.lower() in ("true", "1") | 3eb7ae9e1fe040504ea57c65ed1cbd48be9269cf | 2,477 |
def home_event_manager():
"""
Route for alumni's home
:return:
"""
if "idUsers" in session and session["UserTypes_idUserTypes"] == 2:
return redirect("/events")
else:
session.clear()
return redirect("/login") | 7facf96fbd5d8bbcb7fb867cac7a150a31185dde | 2,478 |
import hashlib
def md5_encode(text):
""" 把數據 md5 化 """
md5 = hashlib.md5()
md5.update(text.encode('utf-8'))
encodedStr = md5.hexdigest().upper()
return encodedStr | b08f656f5ab0858accfbf54e03d95635a3598e13 | 2,480 |
from typing import Counter
def _ngrams(segment, n):
"""Extracts n-grams from an input segment.
Parameters
----------
segment: list
Text segment from which n-grams will be extracted.
n: int
Order of n-gram.
Returns
-------
ngram_counts: Counter
Contain all the ... | 580cad34eb03359988eb2ce6f77dad246166b890 | 2,481 |
def build_varint(val):
"""Build a protobuf varint for the given value"""
data = []
while val > 127:
data.append((val & 127) | 128)
val >>= 7
data.append(val)
return bytes(data) | 46f7cd98b6858c003cd66d87ba9ec13041fcf9db | 2,482 |
import re
def python_safe_name(s):
"""
Return a name derived from string `s` safe to use as a Python function name.
For example:
>>> s = "not `\\a /`good` -safe name ??"
>>> assert python_safe_name(s) == 'not_good_safe_name'
"""
no_punctuation = re.compile(r'[\W_]', re.MULTILINE).sub
... | 463d7c3bf4f22449a0a1c28897654d3ccb5e94cb | 2,483 |
def hash_bytes(hash_type: SupportedHashes, bytes_param: bytes) -> bytes:
"""Hash arbitrary bytes using a supported algo of your choice.
Args:
hash_type: SupportedHashes enum type
bytes_param: bytes to be hashed
Returns:
hashed bytes
"""
hasher = get_hash_obj(hash_type)
ha... | 8f9c05fd050e6f89d6bc5213c03f4002cc341cb0 | 2,484 |
def analyze(osi, num_inc=1, dt=None, dt_min=None, dt_max=None, jd=None):
"""
Performs an analysis step.
Returns 0 if successful, and <0 if fail
Parameters
----------
osi
num_inc
dt
dt_min
dt_max
jd
Returns
-------
"""
op_type = 'analyze'
if dt is None:... | 6c748a49c5e54cf88a04002d98995f4fd90d5130 | 2,485 |
from typing import Any
import importlib
def load_class(path: str) -> Any:
"""
Load a class at the provided location. Path is a string of the form: path.to.module.class and conform to the python
import conventions.
:param path: string pointing to the class to load
:return: the requested class obje... | c6ae2cd20f71a68a6ec05ef5693656d0db7f2703 | 2,486 |
def dcg_at_k(r, k, method=0):
"""Score is discounted cumulative gain (dcg)
Relevance is positive real values. Can use binary
as the previous methods.
Example from
http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf
# >>> r = [3, 2, 3, 0, 0, 1, 2, 2, 3, 0]
# >>> dcg_... | a52b2e3735461ea7749f092aa35cfe8a55f33e3f | 2,487 |
def metric_section(data_model, metric, level) -> str:
"""Return the metric as Markdown section."""
markdown = markdown_header(metric["name"], level=level, index=True)
markdown += markdown_paragraph(metric["description"])
markdown += definition_list("Default target", metric_target(metric))
markdown +... | 6c02e707b6de7c2d89e7eb590d3d9252f13ae9b7 | 2,488 |
def MAKEFOURCC(ch0: str, ch1: str, ch2: str, ch3: str) -> int:
"""Implementation of Window's `MAKEFOURCC`.
This is simply just returning the bytes of the joined characters.
`MAKEFOURCC(*"DX10")` can also be implemented by `Bytes(b"DX10")`.
Args:
ch0 (str): First char
ch1 (str): Second ... | 91afd9dcc8f1cd8c5ef167bdb560c8bf2d89b228 | 2,491 |
def sort_configs(configs): # pylint: disable=R0912
"""Sort configs by global/package/node, then by package name, then by node name
Attributes:
configs (list): List of config dicts
"""
result = []
# Find all unique keys and sort alphabetically
_keys = []
for config in configs:
... | 5c05214af42a81b35986f3fc0d8670fbef2e2845 | 2,492 |
def _add_student_submit(behave_sensibly):
"""Allow addition of new students
Handle both "good" and "bad" versions (to keep code DRY)
"""
try:
if behave_sensibly:
do_add_student_good(
first_name=request.forms.first_name,
last_name=request.forms.last_n... | 780b0e667a841b51b1b64c8c8156cebda3d586e9 | 2,495 |
def _get_table_reference(self, table_id):
"""Constructs a TableReference.
Args:
table_id (str): The ID of the table.
Returns:
google.cloud.bigquery.table.TableReference:
A table reference for a table in this dataset.
"""
return TableReference(self, table_id) | e92dc5fbeac84b902e50d5302539503246c39f30 | 2,496 |
def get_present_types(robots):
"""Get unique set of types present in given list"""
return {type_char for robot in robots for type_char in robot.type_chars} | 75c33e0bf5f97afe93829c51086100f8e2ba13af | 2,498 |
def _deserialize_row(params, mask):
"""
This is for stochastic vectors where some elements are forced to zero.
Such a vector is defined by a number of parameters equal to
the length of the vector minus one and minus the number of elements
forced to zero.
@param params: an array of statistical pa... | 004775ef669ce7698570091c7212912d0f309bee | 2,499 |
import re
def ruru_old_log_checker(s):
"""
古いログ形式ならTrue、そうでないならFalseを返す
:param s:
:return:
"""
time_data_regex = r'[0-9]{4}\/[0-9]{2}\/[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}'
# るる鯖新ログ形式なら1つ目のdiv:d12150で時刻が取得可能。そうでないなら取得不可
time_data = re.search(time_data_regex, str(s.find('div', class_='d... | 54f6a94dab98ef6947496b8e1f95401d99424ee2 | 2,500 |
def scale_z_by_atom(z, scale, copy=True):
"""
Parameters
----------
z_ : array, shape (n_trials, n_atoms, n_times - n_times_atom + 1)
Can also be a list of n_trials LIL-sparse matrix of shape
(n_atoms, n_times - n_times_atom + 1)
The sparse activation matrix.
scale : arra... | b87368c1ea8dcd18fcbfd85ef8cde5450d5fcf33 | 2,502 |
def index():
"""
example action using the internationalization operator T and flash
rendered by views/default/index.html or views/generic.html
if you need a simple wiki simply replace the two lines below with:
return auth.wiki()
"""
if auth.is_logged_in():
# # if newly registered us... | d48d29ee65ddf064dc2f424f2be9f46da23cbd4a | 2,503 |
def compute_classification_metrics_at_ks(is_match, num_predictions, num_trgs, k_list=[5,10], meng_rui_precision=False):
"""
:param is_match: a boolean np array with size [num_predictions]
:param predicted_list:
:param true_list:
:param topk:
:return: {'precision@%d' % topk: precision_k, 'recall@... | 189a6491e1b5d8e3bf8869586b69667eb1b9d9c9 | 2,504 |
def compute_dose_median_scores(null_dist_medians, dose_list):
"""
Align median scores per dose, this function return a dictionary,
with keys as dose numbers and values as all median scores for each dose
"""
median_scores_per_dose = {}
for dose in dose_list:
median_list = []
for ... | ec23f186c10a6921cdae9d4965a51343dc78011e | 2,506 |
def generate_converter(name, taskdep, **options) :
"""
taskdep 是执行该程序之前应该执行的任务
task_html_generator 表示的是能够生成html的任务,我们需要从这个任务中提取result
taskname是生成的任务名
"""
converter = options.get('converter',
Pandoc("-f", "html", "-t", "markdown", "--wrap=none"))
flowdep = options.g... | 3e60abfcdabfb0c35ff8b9692b21b27af2300da8 | 2,507 |
def symmetric_product(tensor):
"""
Symmetric outer product of tensor
"""
shape = tensor.size()
idx = list(range(len(shape)))
idx[-1], idx[-2] = idx[-2], idx[-1]
return 0.5 * (tensor + tensor.permute(*idx)) | 4f96ab5f0bd41080352b1e5e806b6a73b3506950 | 2,508 |
import torch
def prep_image(img, inp_dim):
"""
Function:
Prepare image for inputting to the neural network.
Arguments:
img -- image it self
inp_dim -- dimension for resize the image (input dimension)
Return:
img -- image after preparing
"""
... | 4f32717cb06b32cab2e0b92d3a24a9a665baf27b | 2,509 |
async def auth_check(request):
"""
No-op view to set the session cookie, this is used by websocket since the "Set-Cookie" header
doesn't work with 101 upgrade
"""
return json_response(status='ok') | 60419c8d32bbc41525ebf44d4d7bcabe8a117df0 | 2,510 |
def check_constraint(term_freq,top_terms,top_terms_test_freq):
"""
Check the constraint 12%-30% for the test set
term_freq is the dictionnary of all term frequencies
top_terms is the list of terms we care about (first 300?)
top_terms_freq is an array of frequency of top terms in test set.
RETURN... | d2b31c68d1a8cd1a7d8471818cc46de943496aaa | 2,511 |
import pytz
def predict_split(history, prediction_length=7*24, hyperparameters={}):
"""
This function predicts a time series of gas prices by splitting it into a
tren and a residual and then applying a feature pipeline and predicting
each of them individually.
Keyword arguments:
history -- th... | 025d4b753754ad18a04b46f95002f9ab54ccd9bd | 2,514 |
def SFRfromLFIR(LFIR):
"""
Kennicut 1998
To get Star formation rate from LFIR (8-1000um)
LFIR in erg s-1
SFR in Msun /year
"""
SFR = 4.5E-44 * LFIR
return SFR | 4adf401bbf2c6547cea817b52eb881531db8c798 | 2,515 |
def inc_group_layers(n_list, d_list, c_list):
"""
Helper function for inc_tmm. Groups and sorts layer information.
See coh_tmm for definitions of n_list, d_list.
c_list is "coherency list". Each entry should be 'i' for incoherent or 'c'
for 'coherent'.
A "stack" is a group of one or more cons... | 1b25975169839e54feae58f98b5de98916c51541 | 2,516 |
def get_heater_device_json():
""" returns information about the heater in json """
return '{\n "state" : "' + _pretty_state_identifier(brew_logic.heater_state) + '",\n "overridden" : "' + str(brew_logic.heater_override).lower() + '"\n }' | 3997e9eee7cbb058adf4900b571c8458e2464e19 | 2,517 |
def rfc_deploy():
"""This function trains a Random Forest classifier and outputs the
out-of-sample performance from the validation and test sets
"""
df = pd.DataFrame()
for pair in pairs:
# retrieving the data and preparing the features
dataset = gen_feat(pair)
dataset.drop(['Open', 'High', '... | 86c4aa5f44d23cce83f6cc9993c0e10cd124c423 | 2,518 |
def get_block(block_name):
"""Get block from BLOCK_REGISTRY based on block_name."""
if not block_name in BLOCK_REGISTRY:
raise Exception(NO_BLOCK_ERR.format(
block_name, BLOCK_REGISTRY.keys()))
block = BLOCK_REGISTRY[block_name]
return block | 10b86c5045496a865907ef2617b2994d03f1312d | 2,519 |
from pathlib import Path
import yaml
def _determine_role_name(var_file: Path) -> str:
"""
Lookup role name from directory or galaxy_info.
"""
if var_file.is_file():
role_path: Path = var_file.parent / ".."
name = str(role_path.resolve().name)
meta_path: Path = role_path / 'meta... | 59e6d60234cc7988fe6c3005176f1c89cac5b60d | 2,520 |
def coco17_category_info(with_background=True):
"""
Get class id to category id map and category id
to category name map of COCO2017 dataset
Args:
with_background (bool, default True):
whether load background as class 0.
"""
clsid2catid = {
1: 1,
2: 2,
... | f64be8c09b3372ad75826a6bfdc8a2f0bc4f9e25 | 2,523 |
def example_miller_set(example_crystal):
"""Generate an example miller set."""
ms = miller.set(
crystal_symmetry=example_crystal.get_crystal_symmetry(),
indices=flex.miller_index([(1, 1, 1)] * 8 + [(2, 2, 2)]),
anomalous_flag=False,
)
return ms | 516eca404544d8f8af8dd664488006c67bef03b8 | 2,525 |
async def get(req):
"""
Get a complete analysis document.
"""
db = req.app["db"]
analysis_id = req.match_info["analysis_id"]
document = await db.analyses.find_one(analysis_id)
if document is None:
return not_found()
sample = await db.samples.find_one({"_id": document["sample... | e52598d27b73dd9ef5d24aba196f97f85fb47214 | 2,526 |
from typing import Union
from typing import Mapping
from typing import Any
def get_cube_point_indexes(cube: xr.Dataset,
points: Union[xr.Dataset, pd.DataFrame, Mapping[str, Any]],
dim_name_mapping: Mapping[str, str] = None,
index_name_pa... | b1f5eb134ab7119589b54c45b95065c2f57348dc | 2,527 |
def auto_add():
"""
自动添加
1 查找所有amis文件
2 更新记录
3 记录按照app组织,生成dict
4 为每个app生成auto_urls.py
:return:
"""
amis_json_file_list = get_amis_files()
cnt = update_rcd(amis_json_file_list)
aml_app_dict = get_rcd_by_app_name()
add_needed_auto_urls(aml_app_dict)
add_urls_needed(... | 17b6026f56793f3a6f76446145b7f65a6fe29a5a | 2,528 |
from pathlib import Path
from typing import Optional
def _get_configs(cli_args: CLIArgs, project_root: Path) -> Configs:
"""
Deal with extra configs for 3rd party tool.
Parameters
----------
cli_args
Commandline arguments passed to nbqa
project_root
Root of repository, where .... | d9ef190a99b06f2d17bbc336ace86061ea215d97 | 2,529 |
from sklearn.preprocessing import RobustScaler
def robust_standardize(df: pd.DataFrame, excluded_colnames: list = None) -> pd.DataFrame:
"""
Applies the RobustScaler from the module sklearn.preprocessing by
removing the median and scaling the data according to the quantile
range (IQR). This transforma... | 0727ce390e773405a221c6fb3248ddd5d40445b2 | 2,532 |
import math
def meanStdDev( valueList, scale ):
"""Compute the mean and standard deviation of a *non-empty* list of numbers."""
numElements = len(valueList)
if numElements == 0:
return(None, 0.0)
mean = float(sum(valueList)) / numElements
variance = 0
for value in valueList:
variance += math.pow( value - ... | 2970ae1e4382092eb67219373aa26b9ca75226a3 | 2,533 |
def audience_filter(digest, audience):
"""Check whether the current audience level should include that digest."""
return get_split(
digest,
[
{
"key": "audience_{}".format(idx),
"size": 1.0
} for idx in range(0, 100)
]
) < audie... | 811e4e94e68901bfeaedabfec5e16a30de55408c | 2,534 |
def request_specific_data2num(batch_data):
"""
input: next_batch_requestable request_specific_data[slot].
change the data into processable type for tensorflow
:param batch_data: 一个 batch 的训练数据
:return: 直接输入request-specific tracker 模型计算的数据
"""
batchsize_request = len(batch_data)
x_usr = ... | e8a5b414f00e43755719dfadc0b089177cb67152 | 2,535 |
def points_from_x0y0x1y1(xyxy):
"""
Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1]
"""
[x0, y0, x1, y1] = xyxy
return "%s,%s %s,%s %s,%s %s,%s" % (
x0, y0,
x1, y0,
x1, y1,
x0, y1
) | 8a7d766145dc31e6619b290b8d96a95983f9cc01 | 2,536 |
def get_columns(invoice_list, additional_table_columns):
"""return columns based on filters"""
columns = [
_("Invoice") + ":Link/Sales Invoice:120", _("Posting Date") + ":Date:80", _("Status") + "::80",
_("Customer") + ":Link/Customer:120", _("Sales Person") + ":Link/Sales Person:100",
_("AR Status") + "::75", ... | c9849e62d401ec5cc8de52d266a39eccf4b4dbe8 | 2,537 |
def one_norm(a):
"""
Return the one-norm of the matrix.
References:
[0] https://www.mathworks.com/help/dsp/ref/matrix1norm.html
Arguments:
a :: ndarray(N x N) - The matrix to compute the one norm of.
Returns:
one_norm_a :: float - The one norm of a.
"""
return anp.max(anp.... | c3e1c83d3776dda8ffa82b9b36d26866f390f6cc | 2,538 |
def remove_nan_inf(df, reindex=True):
"""
Removes all rows that have NaN, inf or -inf as a value, and then optionally
reindexes the dataframe.
Parameters
----------
df : pd.DataFrame
Dataframe to remove NaNs and Infs from.
reindex : bool, optional
Reindex the dataframe ... | 3b9339f2ee1315eac458925e5be5279e147d5c7d | 2,539 |
def contingency_table(seg, gt, ignore_seg=[0], ignore_gt=[0], norm=True):
"""Return the contingency table for all regions in matched segmentations.
Parameters
----------
seg : np.ndarray, int type, arbitrary shape
A candidate segmentation.
gt : np.ndarray, int type, same shape as `seg`
... | 47284bb5aaa492b6cbc50794c8ccd8a1e63676b4 | 2,540 |
def get_basic_track_info(track):
"""
Given a track object, return a dictionary of track name, artist name,
album name, track uri, and track id.
"""
# Remember that artist and album artist have different entries in the
# spotify track object.
name = track["name"]
artist = track['artists'... | 925f7bb00482e946ad7a6853bac8b243d24145c7 | 2,541 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.