content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def image_ppg(ppg_np):
"""
Input:
ppg: numpy array
Return:
ax: 画布信息
im:图像信息
"""
ppg_deps = ppg.DependenciesPPG()
ppg_M = Matrix(ppg_np)
monophone_ppgs = ppg.reduce_ppg_dim(ppg_M, ppg_deps.monophone_trans)
monophone_ppgs = monophone_ppgs.numpy().T
fig, ax = p... | 714ccc3e294a5f02983a9aa384c2d6aa313ee4e5 | 3,639,369 |
def is_hex_value(val):
"""
Helper function that returns True if the provided value is an integer in
hexadecimal format.
"""
try:
int(val, 16)
except ValueError:
return False
return True | 6ba5ac1cfa9b8a4f8397cc52a41694cca33a4b8d | 3,639,370 |
from typing import Optional
def create_cluster(*, cluster_name: str) -> Optional[Operation]:
"""Create a dataproc cluster """
cluster_client = dataproc.ClusterControllerClient(client_options={"api_endpoint": dataproc_api_endpoint})
cluster = {
"project_id": project_id,
"cluster_name"... | 1657190a7605f28f3c4dd2f2dc6c32230fb44087 | 3,639,371 |
import math
def gc_cache(seq: str) -> Cache:
"""Return the GC ratio of each range, between i and j, in the sequence
Args:
seq: The sequence whose tm we're querying
Returns:
Cache: A cache for GC ratio lookup
"""
n = len(seq)
arr_gc = []
for _ in seq:
arr_... | 7118cc96d0cd431b720b099b399c64ee419df5aa | 3,639,372 |
def ParseVariableName(variable_name, args):
"""Parse a variable name or URL, and return a resource.
Args:
variable_name: The variable name.
args: CLI arguments, possibly containing a config name.
Returns:
The parsed resource.
"""
return _ParseMultipartName(variable_name, args,
... | 1073739195ca1bb0ac427e89e66525a7e7ada40b | 3,639,373 |
def index(request):
"""Home page"""
return render(request, 'read_only_site/index.html') | 623c0cdc3229d1873e50ebc3065ca1ba55da50e7 | 3,639,374 |
def parse_calculation_strings_OLD(args):
"""form the strings into arrays
"""
calculations = []
for calculation in args.calculations:
calculation = calculation.split("/")
foreground = np.fromstring(
",".join(calculation[0].replace("x", "0")), sep=",")
background = np.f... | 04c979cc09bd25d659dad0a96ca89b88b43267cb | 3,639,375 |
def find_border(edge_list) :
"""
find_border(edge_list)
Find the borders of a hexagonal graph
Input
-----
edge_list : array
List of edges of the graph
Returns
-------
border_set : set
Set of vertices of the border
... | 718a2b56438caf60d3ca4e3cd7419452c8fbbb63 | 3,639,377 |
from typing import Set
from datetime import datetime
def get_all_files(credentials: Credentials, email: str) -> Set['DriveResult']:
"""Get all files shared with the specified email in the current half-year
(January-June or July-December of the current year)"""
# Create drive service with provided credenti... | eb7e491cac08bada675f0d39414ae3d907686741 | 3,639,378 |
def _split_kwargs(model, kwargs, lookups=False, with_fields=False):
"""
Split kwargs into fields which are safe to pass to create, and
m2m tag fields, creating SingleTagFields as required.
If lookups is True, TagFields with tagulous-specific lookups will also be
matched, and the returned tag_fields... | f73cb84bab0889b51962ed3504b6de265831d18f | 3,639,379 |
def sliceResultToBytes(sr):
"""Copies a FLSliceResult to a Python bytes object. Does not free the FLSliceResult."""
if sr.buf == None:
return None
lib.FLSliceResult_Release(sr)
b = bytes( ffi.buffer(sr.buf, sr.size) )
return b | 0e2207a99749b4cd3df4b71ca7338de4c0ad6a06 | 3,639,380 |
def cycle_dual(G, cycles, avg_fun=None):
"""
Returns dual graph of cycle intersections, where each edge
is defined as one cycle intersection of the original graph
and each node is a cycle in the original graph.
The general idea of this algorithm is:
* Find all cycles which ... | a923a4cea0f1d158e6936a68e513bd2285ea6b15 | 3,639,381 |
def get_timebucketedlog_reader(log, event_store):
"""
:rtype: TimebucketedlogReader
"""
return TimebucketedlogReader(log=log, event_store=event_store) | 676e38a446f60dd8f2c90b38df572b2f5fc9c21e | 3,639,383 |
def get_database_name(url):
"""Return a database name in a URL.
Example::
>>> get_database_name('http://foobar.com:5984/testdb')
'testdb'
:param str url: The URL to parse.
:rtype: str
"""
name = compat.urlparse(url).path.strip("/").split("/")[-1]
# Avoid re-encoding the n... | 2916e5a5999aae68b018858701dfb5e695857f7f | 3,639,384 |
def get_tags():
"""
在这里希望根据用户来获取,和用户有关的tag
所以我们需要做的是,获取用户所有的post,然后找到所有的tag
:return:
"""
result_tags = []
# 找到某个用户的所有的文章,把所有文章的Tag都放在一块
def append_tag(user_posts):
tmp = []
for post in user_posts:
for tag in post.tags.all():
tmp.append(tag.ta... | 821ca1bb222e4fe15ea336282fed0eb172d460f9 | 3,639,385 |
def a_star_search(graph, start, goal):
"""Runs an A* search on the specified graph to find a path from the ''start'' node to the ''goal'' node.
Returns a list of nodes specifying a minimal path between the two nodes.
If no path exists (disconnected components), returns an empty list.
"""
all_nodes =... | f2eabef1e30f12460359ea45cbc089f8fb28e5f9 | 3,639,387 |
import click
def output_format_option(default: OutputFormat = OutputFormat.TREE):
"""
A ``click.option`` for specifying a format to use when outputting data.
Args:
default (:class:`~ape.cli.choices.OutputFormat`): Defaults to ``TREE`` format.
"""
return click.option(
"--format",
... | 9f73a8b8d270975d16ec9d3b2962f4fd61491aab | 3,639,388 |
def compute_errors(u_e, u):
"""Compute various measures of the error u - u_e, where
u is a finite element Function and u_e is an Expression.
Adapted from https://fenicsproject.org/pub/tutorial/html/._ftut1020.html
"""
print('u_e',u_e.ufl_element().degree())
# Get function space
V = u.functi... | c9fbd459ab1c3cd65fb4d290e1399dd4937ed5a2 | 3,639,389 |
def list_to_str(input_list, delimiter=","):
"""
Concatenates list elements, joining them by the separator specified by the
parameter "delimiter".
Parameters
----------
input_list : list
List with elements to be joined.
delimiter : String, optional, default ','.
The separato... | 4decfbd5a9d637f27473ec4a917998137af5ffe0 | 3,639,390 |
def strategy_supports_no_merge_call():
"""Returns if the current `Strategy` can operate in pure replica context."""
if not distribution_strategy_context.has_strategy():
return True
strategy = distribution_strategy_context.get_strategy()
return not strategy.extended._use_merge_call() # pylint: disable=prote... | dc2b609a52d7e25b372e0cd1a04a0637d76b8ec1 | 3,639,391 |
def is_group(obj):
"""Returns true if the object is a h5py-like group."""
kind = get_h5py_kind(obj)
return kind in ["file", "group"] | 37c86b6d4f052eab29106b9d51c17cdd36b1dc98 | 3,639,392 |
from bs4 import BeautifulSoup
def analyze_page(page_url):
""" Analyzes the content at page_url and returns a list of the highes weighted
words.json/phrases and their weights """
html = fetch_html(page_url)
if not html:
return
soup = BeautifulSoup(html, "html.parser")
word_counts = {}... | 55928add263defa51a171a2dfb20bffe6491430c | 3,639,393 |
from typing import Iterable
from typing import List
def load_config_from_paths(config_paths: Iterable[str], strict: bool = False) -> List[dict]:
"""
Load configuration from paths containing \*.yml and \*.json files.
As noted in README.config, .json will take precedence over .yml files.
:param config_... | 8e32c46e7e620ae02dffcc652b32bb0098a0a2b3 | 3,639,394 |
from typing import List
def sort_flats(flats_unsorted: List[arimage.ARImage]):
""" Sort flat images into a dictionary with "filter" as the key """
if bool(flats_unsorted) == False:
return None
flats = { }
logger.info("Sorting flat images by filter")
for flat in flats_unsorted:
fl =... | d0e3fe2c7e1a8f34cf7ed8f6985d3dd7bc82f3f1 | 3,639,395 |
import concurrent
import logging
def run_in_parallel(function, list_of_kwargs_to_function, num_workers):
"""Run a function on a list of kwargs in parallel with ThreadPoolExecutor.
Adapted from code by mlbileschi.
Args:
function: a function.
list_of_kwargs_to_function: list of dictionary from string to ... | 24b99f68ba1221c4f064a65540e6c165c9474e43 | 3,639,396 |
def show_project(project_id):
"""return a single project formatted according to Swagger spec"""
try:
project = annif.project.get_project(
project_id, min_access=Access.hidden)
except ValueError:
return project_not_found_error(project_id)
return project.dump() | 3f7108ec7cb27270f91517bef194f3514c3eb4e5 | 3,639,398 |
def pollard_rho(n: int, e: int, seed: int = 2) -> int:
"""
Algoritmo de Pollard-Rho para realizar a quebra de chave na criptografia RSA.
n - n da chave pública
e - e da chave pública
seed - valor base para executar o ciclo de testes
"""
a, b = seed, seed
p = 1
while (p == 1):
... | 4870627a5fca863d4110f3cadfdc1e7b618c2a48 | 3,639,399 |
import warnings
def _url_from_string(url):
"""
Generate actual tile url from tile provider definition or template url.
"""
if "tileX" in url and "tileY" in url:
warnings.warn(
"The url format using 'tileX', 'tileY', 'tileZ' as placeholders "
"is deprecated. Please use '... | f3d4393163e48a7949f3229c55ea8951411dcd63 | 3,639,400 |
import socket
def get_reverse_dns(ip_address: str) -> str:
"""Does a reverse DNS lookup and returns the first IP"""
try:
rev = socket.gethostbyaddr(ip_address)
if rev:
return rev[0]
return "" # noqa
except (socket.herror, socket.gaierror, TypeError, IndexError):
... | 58a27e25f7a9b11ab7dcddebeea743b7864f80f1 | 3,639,401 |
def abs_path(file_path):
"""
Returns the absolute path from the file that calls this function to file_path. Needed to access other files within aide_gui when initialized by aide.
Parameters
----------
file_path: String
The relative file path from the file that calls this function.
"""
... | 63e4a4b0c8fafb5920c78310fda90b119fd18104 | 3,639,402 |
def function(x: np.ndarray) -> float:
"""The ellipse function is x0^2 + 2 * x1^2 + 3 * x2^2 + ..."""
return np.linalg.norm(np.sqrt(np.arange(1, 1 + len(x))) * x) ** 2 | efe468177ff232d45d18385fa2744a9cf63739eb | 3,639,403 |
def replace_with_encoded_bits(one_hot_matrix, enum_val, add_value, last_col_index):
"""
Generate encoded bits for a categorical data value using one hot encoding.
:param one_hot_matrix: matrix representing the encoding of categorical data value to 1-hot encoding
:param enum_val: categorical data value,... | d5ee111d74071fdbaa3890b35a193aa9e24df745 | 3,639,404 |
def cosine_similarity(n_co_elements, n_first_element, n_second_element):
"""
Description
A function which returns the cosine similarity between two elements.
Arguments
:param n_co_elements: Number of co-elements.
:type n_co_elements: int
:param n_first_element: Size of the f... | ea35e47ecf3e77a95d535b0421afbe5f3a679817 | 3,639,405 |
def AddForwardEulerDynamicsConstraint(mp, A, B, x, u, xnext, dt):
"""
Add a dynamics constraint to the given Drake mathematical program mp, represinting
the euler dynamics:
xnext = x + (A*x + B*u)*dt,
where x, u, and xnext are symbolic variables.
"""
n = A.shape[0]
Aeq = np.hstack(... | e0070aa28b61833330706e3934cbfaa8eb1c1d1b | 3,639,406 |
import json
async def light_pure_rgb_msg_fixture(hass):
"""Return a mock MQTT msg with a pure rgb light actuator message."""
light_json = json.loads(
await hass.async_add_executor_job(load_fixture, "ozw/light_pure_rgb.json")
)
message = MQTTMessage(topic=light_json["topic"], payload=light_json... | 93156674ece713d6c9371f64840852a3d5d292b5 | 3,639,407 |
import csv
def make_header_names_thesaurus(header_names_thesaurus_file=HEADER_NAMES_THESAURUS_FILE):
"""
Get a dict mapping ideal domain-specific phrases to list of alternates.
Parameters
----------
header_names_thesaurus_file : str
Filepath.
Returns
-------
Dict of {'ideal phrase': ['alt_phrase0', 'alt_p... | 20f89be5dfbdf0feac5facddcaeeddb346d394a8 | 3,639,408 |
def split_train_valid_test(adata_here,
training_proportion=0.6,
validation_proportion=0.2,
test_proportion=0.2,
rng=None,copy_adata=False):
"""Split cells into training, validation and test
"""
... | ccff7c2b1372b74429bb6acb04df1dd66ad5c113 | 3,639,409 |
def index(request):
""" Main index. Editor view. """
# Render editor
body = render_to_string('editor.html', {})
data = {
'body': body
}
# Render page layout
return render(request, 'index.html', data) | bab60def7716ae11d328a95274d2ee7b6305dbaf | 3,639,411 |
def isUsdExt(ext):
""" Check if the given extension is an expected USD file extension.
:Parameters:
ext : `str`
:Returns:
If the file extension is a valid USD extension
:Rtype:
`bool`
"""
return ext.lstrip('.') in USD_EXTS | 5c2f7a48869c9ab4a94b4d8a84e892b76938e91a | 3,639,412 |
def _get_dflt_lexicon(a_pos, a_neg):
"""Generate default lexicon by putting in it terms from seed set.
@param a_pos - set of positive terms
@param a_neg - set of negative terms
@return list(3-tuple) - list of seed set terms with uniform scores and
polarities
"""
return [(w, POSITIVE, 1.... | b06a1f81629368447227a846ac3216220beaa77b | 3,639,413 |
def rct(target_t : Tensor, source_t : Tensor, target_mask_t : Tensor = None, source_mask_t : Tensor = None, mask_cutoff = 0.5) -> Tensor:
"""
Transfer color using rct method.
arguments
target_t Tensor( [N]CHW ) C==3 (BGR) float16|32
source_t Tensor( [N]CHW ) C==3 (BGR) float16|32
... | 87f350c3e8cef10ef2e3bc883457acf861ab064c | 3,639,415 |
def random_policy(num_actions):
"""
Returns a policy where all actions have equal probabilities, i.e., an uniform distribution.
"""
return np.zeros((num_actions,)) + 1 / num_actions | 9a95865cf3bc7634bc4bf033f343b5811ba40c9f | 3,639,416 |
def find_object(func, name, *args, **kwargs):
"""Locate an object by name or identifier
This function will use the `name` argumetn to attempt to
locate an object. It will first attempt to find the
object by identifier and if that fails, it will attempt
to find the object by name.
Since object... | 6ee8085d42883798c1f3ab5d0a7711af26b2b614 | 3,639,417 |
def CreateHSpline(points, multiple=False):
"""
Construct an H-spline from a sequence of interpolation points
Args:
points (IEnumerable<Point3d>): Points to interpolate
"""
url = "rhino/geometry/nurbscurve/createhspline-point3darray"
if multiple: url += "?multiple=true"
args = [point... | b5f7b2000dcce04a60087ab32956fa4701d1dadc | 3,639,422 |
def get_instance_embedding_loss(embedding,
instance_loss_type,
instance_labels,
crop_area,
crop_min_height,
num_samples=10,
simi... | ff1e08ea60f4c937fd44bec967eda37d6916ef00 | 3,639,423 |
def str_to_array(value):
"""
Check if value can be parsed to a tuple or and array.
Because Spark can handle tuples we will try to transform tuples to arrays
:param value:
:return:
"""
try:
if isinstance(literal_eval((value.encode('ascii', 'ignore')).decode("utf-8")), (list, tuple)):
... | d565021781a3c2c19c882073ddc6cbd24334b74a | 3,639,424 |
import inspect
def get_current_func_name():
"""for python version greater than equal to 2.7"""
return inspect.stack()[1][3] | 002d318bcab98639cab6c38317322f247a1ad0e0 | 3,639,425 |
def getParmNames(parmsDef):
"""Return a list of parm names in a model parm definition
parmsDef: list of tuples, each tuple is a list of parms and a time
constraint. Call with modelDict[modelname]['Parms].
Returns: List of string parameter names
Here's an example of how to remove unused parms f... | 785661200c388f23c5f38ae67e773a43fd8f57b3 | 3,639,426 |
def dict_merge(lft, rgt):
"""
Recursive dict merge.
Recursively merges dict's. not just simple lft['key'] = rgt['key'], if
both lft and rgt have a key who's value is a dict then dict_merge is
called on both values and the result stored in the returned dictionary.
"""
if not isinstance(rgt, ... | c939fed14ff10452663bc5a32247b21f6170897a | 3,639,427 |
def modified_zscore(x: np.ndarray) -> np.ndarray:
"""
Modified z-score transformation.
The modified z score might be more robust than the standard z-score because
it relies on the median for calculating the z-score. It is less influenced
by outliers when compared to the standard z-score.
Param... | 8f0933bf30ec55ba6305c9bd926437bb0715a938 | 3,639,428 |
def update_profile(email, username, name, bio, interest, picture=None):
"""更新 profile"""
db = get_db()
cursor = db.cursor()
# query user
user = get_user_by_email(email)
email = user['email']
profile_id = user['profile_id']
if profile_id is None:
# add profile
cursor.exe... | 0b13d81f9d36198d4660179eae7616d8f25ee37e | 3,639,429 |
import zlib
import marshal
def serialize(object):
"""
Serialize the data into bytes using marshal and zlib
Args:
object: a value
Returns:
Returns a bytes object containing compressed with zlib data.
"""
return zlib.compress(marshal.dumps(object, 2)) | 650cbc8937df5eae79960f744b69b8b12b623195 | 3,639,430 |
def logo_if(interp, expr, block, elseBlock=None):
"""
IF tf instructionlist
(IF tf instructionlist1 instructionlist2)
command. If the first input has the value TRUE, then IF runs
the second input. If the first input has the value FALSE, then
IF does nothing. (If given a third input, IF acts ... | 94f143f59fa02f059469f8f17a3ff11093110c84 | 3,639,431 |
import itertools
def select_model_general(
df,
grid_search,
target_col_name,
frequency,
partition_columns=None,
parallel_over_columns=None,
executor=None,
include_rules=None,
exclude_rules=None,
country_code_column=None,
output_path="",
persist_cv_results=False,
per... | 1c286b8cf922a50c1c1071aa0d0506b0cf102a6b | 3,639,432 |
def create_arma_sample(ar_order=1, ma_order=1, size=100):
"""Get a random ARMA sample.
Parameters
----------
ar_order, ma_order, size : int
Values for the desired AR order, MA order and sample size.
Returns
-------
An ARMA sample as a pandas Series.
"""
ar_coeff = np.linspa... | e859413cee0a20e51fc80aeffbb75b3ada83f010 | 3,639,433 |
def get_img(file_path, gray=False):
"""
获取输入图片
:param file_path: 图片文件位置
:param gray: 是否转换为灰度图
:return: img
"""
try:
img = Image.open(file_path)
if gray:
img = img.convert('L')
return img
except Exception:
print("不支持的图片格式")
return None | ac3ad78a1ce877905f550ebc43b7e9a6335fd762 | 3,639,434 |
from datetime import datetime
def working_days(days: int):
"""Return a list of N workingdays
Keyword arguments:
days -- days past
"""
dates = []
today = datetime.utcnow()
for i in range(days):
day = today - timedelta(days=i)
day = day.date()
dates.append(day)
... | 222002b53bcf536f7b31993a22424446fcce24cc | 3,639,435 |
def GetFile(message=None, title=None, directory=None, fileName=None,
allowsMultipleSelection=False, fileTypes=None):
"""
An get file dialog.
Optionally a `message`, `title`, `directory`, `fileName` and
`allowsMultipleSelection` can be provided.
::
from fontParts.ui import GetFi... | b81ba1e11764231c8c04164316e4ee55b0305044 | 3,639,436 |
def str_to_dtype(s):
"""Convert dtype string to numpy dtype."""
return eval('np.' + s) | e0ff793404af5a8022d260fde5878329abbac483 | 3,639,437 |
from typing import Callable
from typing import Tuple
def integrate_const(
f: Callable,
t_span: Tuple,
dt: float,
y0: np.ndarray,
method: str = 'runge_kutta4'
) -> Tuple[np.ndarray, np.ndarray]:
"""
A Python wrapper for Boost::odeint runge_kutta4 (the only one supported right now)
stepp... | e43479c829fd46e0f4cdd8c7918294577e91beed | 3,639,438 |
def cleanup(serialized):
"""
Remove all missing values. Sometimes its useful for object methods
to return missing value in order to not include that value in the
json format.
Examples::
>>> User(Serializable):
... def attributes():
... return ['id', 'name', 'bir... | 5e4bfd13408ec8272c4fc4e9a499349e13dd2798 | 3,639,439 |
import json
def PyValueToMessage(message_type, value):
"""Convert the given python value to a message of type message_type."""
return JsonToMessage(message_type, json.dumps(value)) | 576237ebbacb85ac4c51be8b5523f4f95cfcc019 | 3,639,442 |
from typing import Any
from typing import get_origin
def istype(obj: Any, annotation: type) -> bool:
"""Check if object is consistent with the annotation"""
if get_origin(annotation) is None:
if annotation is None:
return obj is None
return isinstance(obj, annotation)
else:
... | c1903ea2ec6c0b6b9006a38f7c0720c88987b706 | 3,639,443 |
import logging
import platform
def test_cand_gen(caplog):
"""Test extracting candidates from mentions from documents."""
caplog.set_level(logging.INFO)
if platform == "darwin":
logger.info("Using single core.")
PARALLEL = 1
else:
logger.info("Using two cores.")
PARALLE... | 44cf505a7eedef55e6322eafebfb92ad3b882697 | 3,639,444 |
def spending_from_savings(take_home_pay: float, savings: float) -> Decimal:
"""
Calculate your spending based on your take home pay and how much
you save. This is useful if you use what Paula Pant calls the anti-budget,
instead of tracking your spending in detail. This number can be used as
input fo... | da26cae052bd27efb11893440353d53e8b6aed89 | 3,639,445 |
def large_asymmetric_bulge(data):
"""
:param data: image data as array
:return: the width and location of the largest asymmetric bulge (if any) in the sequence
"""
# retrieve the lengths of the bars in the sequences (the counts) from the palindrome function
score, upper_half_counts, lower_half_c... | be7aef1cc6a2443de3ecff5099d6e28554544f7a | 3,639,447 |
import requests
def request(host, path, bearer_token, url_params):
"""Given a bearer token, send a GET request to the API.
Args:
host (str): The domain host of the API.
path (str): The path of the API after the domain.
bearer_token (str): OAuth bearer token, obtained using client_id an... | 8f322307bfc1cf48ff5e1a7e52df18e5c9dc7ddf | 3,639,448 |
def find_unique_distances(distance_ij: pd.Series) -> np.ndarray:
"""Finds the unique distances that define the neighbor groups.
:param distance_ij: A pandas ``Series`` of pairwise neighbor distances.
:return: An array of unique neighbor distances.
"""
unique_floats: np.ndarray = np.sort(distance_ij... | ca4d8252c4b79bd536a10a058ca5f75b9f39416e | 3,639,449 |
from typing import Dict
from typing import Any
def session(monkeypatch: pytest.MonkeyPatch) -> nox.Session:
"""Fixture for a Nox session."""
registry: Dict[str, Any] = {}
monkeypatch.setattr("nox.registry._REGISTRY", registry)
@nox.session(venv_backend="none")
def test(session: nox.Session) -> No... | 646403d4383c6e426d736bf55278e001db2a40e1 | 3,639,450 |
import yaml
def _load_yaml_with_clear_tag(stream):
"""Like yaml.safe_load(), but everything with a !clear tag before it
will be wrapped in ClearedValue()."""
loader = yaml.SafeLoader(stream)
loader.add_constructor('!clear', _cleared_value_constructor)
try:
return loader.get_single_data()
... | dec04cec96fae797250d1fb37491755ceaea399c | 3,639,451 |
def highlights(state_importance_df, exec_traces, budget, context_length, minimum_gap=0,
overlay_limit=0):
"""generate highlights summary"""
sorted_df = state_importance_df.sort_values(['importance'], ascending=False)
summary_states, summary_traces, state_trajectories = [], [], {}
seen_in... | 50c1dddaad88fa697f850380b215c2fb9e5f1a13 | 3,639,452 |
def draw_figure(canvas, figure, loc=(0, 0)):
"""
Draw a matplotlib figure onto a Tk grafica
loc: location of top-left corner of figure on grafica in pixels.
Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py
"""
figure_canvas_agg = FigureCanvasAgg(figure)
figure_canvas... | 02e4bc4a6cd475c63239170c0dae0648199c46b5 | 3,639,453 |
def find_struct(lines):
"""Finds structures in output data"""
struct = ''
name1 = ''
name2 = ''
seq1 = ''
seq2 = ''
result = []
for line in lines:
if line.startswith('; ========'):
break
if line.startswith('; ALIGNING'):
line = line.split()
... | b7f7e5c70fe0b1111f33e43a40bb9fdde4182b68 | 3,639,454 |
from typing import Callable
def chain(*fs: Callable) -> Callable:
"""
Compose given functions in reversed order.
Given functions f, g, the result of chain is chain(f, g) = g o f.
>>> def f(x: int) -> int:
... return x + 1
>>> def g(x: int) -> str:
... return str(x)
>>> chai... | 4956a955a760d5243988f8fc6fdb0303e3351704 | 3,639,455 |
def astra_fp_2d_fan(volume, angles, source_object, object_det):
"""
:param volume:
:param angles: degrees
:return:
"""
detector_size = volume.shape[1]
proj_geom = build_proj_geometry_fan_2d(detector_size, angles, source_object, object_det)
rec = astra_fp_2d(volume, proj_geom)
return... | 5114730387bd43585bb56a16e5e930491aa87fd2 | 3,639,456 |
from typing import Mapping
def get_remappings_prefix() -> Mapping[str, str]:
"""Get the remappings for xrefs based on the prefix.
.. note:: Doesn't take into account the semicolon `:`
"""
return _get_curated_registry()['remappings']['prefix'] | 02cb1bb1cfa4ffb177327442c6fb63c4fc3fa320 | 3,639,457 |
import json
def generate_schema():
""" schema generation from today filename dataset """
today = date.today().strftime("%d_%m_%Y")
complete_dataset = pd.read_csv(f"complete_dataset_{today}.csv")
json_schema = pd.io.json.build_table_schema(complete_dataset)
with open("json_schema_for_big_query.json... | 67dca17ddfae8f3530e8ced2a730c28657fa77ca | 3,639,458 |
def binary_truncated_sprt_with_llrs(llrs, labels, alpha, beta, order_sprt):
""" Used in run_truncated_sprt_with_llrs .
Args:
llrs: A Tensor with shape (batch, duration). LLRs (or scores) of all frames.
labels: A Tensor with shape (batch,).
alpha : A float.
beta: A float.
... | 4d4f67d1ad9407df1cf8bfdc0e4c5cf775fcc57b | 3,639,459 |
import time
def backoff(action, condition, max_attempts=40):
"""
Calls result = action() up to max_attempts times until condition(result) becomes true, with 30 s backoff. Returns a bool flag indicating whether condition(result) was met.
"""
timeout = 30
for attempt in range(max_attempts):
result = acti... | 93fe5ff9ee672073eb9eb4792572e41d4b4c3faa | 3,639,460 |
def get_file_info(repo, path):
"""we need change_count, last_change, nbr_committers."""
committers = []
last_change = None
nbr_changes = 0
for commit in repo.iter_commits(paths=path):
#print(dir(commit))
committers.append(commit.committer)
last_change = commit.committed_date... | 6ff99df399d35b79d0e2a5635b1e76e1f65fe0bd | 3,639,461 |
import requests
import urllib3
def retryable_session(session: requests.Session, retries: int = 8) -> requests.Session:
"""
Session with requests to allow for re-attempts at downloading missing data
:param session: Session to download with
:param retries: How many retries to attempt
:return: Sessio... | a57d2021077997ab14576df35b4e5ad9d281575e | 3,639,462 |
def apply_affine(x, y, z, affine):
""" Apply the affine matrix to the given coordinate.
Parameters
----------
x: number or ndarray
The x coordinates
y: number or ndarray
The y coordinates
z: number or ndarray
The z coordinates
affi... | b940c98da65a61cd46d2ad85ec33c791619341a0 | 3,639,463 |
def square_valid(board: Board, n: int, pawn_value: int, x: int, y: int) -> bool:
"""Check if the square at x and y is available to put a pawn on it."""
return (coordinates_within_board(n, x, y) and
square_playable(board, pawn_value, x, y)) | 725f65e64a8570e7483f103f0bf669cef3d7f1ef | 3,639,465 |
def epb2jd(epb):
""" Besselian epoch to Julian date.
:param epb: Besselian epoch.
:type epb: float
:returns: a tuple of two items:
* MJD zero-point, always 2400000.5 (float)
* modified Julian date (float).
.. seealso:: |MANUAL| page 76
"""
djm0 = _ct.c_double()
djm = ... | c5a9bcb422ab34ba0875d152cf8c39dda898e68b | 3,639,466 |
def one_hot_decision_function(y):
"""
Examples
--------
>>> y = [[0.1, 0.4, 0.5],
... [0.8, 0.1, 0.1],
... [0.2, 0.2, 0.6],
... [0.3, 0.4, 0.3]]
>>> one_hot_decision_function(y)
array([[ 0., 0., 1.],
[ 1., 0., 0.],
[ 0., 0., 1.],
... | a6eecff684ab926a46d746ca9c18e6b098308286 | 3,639,467 |
def combine_incomes(toshl_income, excel_income):
"""
Combines two data sources of incomes: toshl incomes and incomes from cashflow excel.
:param toshl_income: Preprocessed dataframe of toshl incomes (after cleaning and splitting)
:param excel_income: Raw excel income data
:return: Total income data
... | 31efb2d7b7420f3c71fcb12876cdc09d7ff748ec | 3,639,468 |
def generate_k(data_set, k):
"""
Given `data_set`, which is an array of arrays,
find the minimum and maximum for each coordinate, a range.
Generate `k` random points between the ranges.
Return an array of the random points within the ranges.
"""
centers = []
dimensions = len(data_set[0])
min_max = defaultdict(... | 1fd4eb6a825a0ca2b8e6b8200081ecfded351c7d | 3,639,469 |
import requests
def __ping_url(url: str) -> bool:
"""Check a link for rotting."""
try:
r = requests.head(url)
return r.status_code in (
requests.codes.ok,
requests.codes.created,
requests.codes.no_content,
requests.codes.not_modified,
)
... | e680cec006127bbe889dcab0291be3149f30d10e | 3,639,470 |
def get_all_list_data():
"""
Handles the GET request to '/get-all-list-data'.
:return: Json with all list data
"""
conn = get_db()
all_types = TypeDataAccess(conn).get_types(False)
all_tags = TagDataAccess(conn).get_tags()
all_groups = ResearchGroupDataAccess(conn).get_research_groups(F... | 4a4a942e054d301f936ae7993b04aff6c554f91c | 3,639,471 |
def truncate_range(data, percMin=0.25, percMax=99.75, discard_zeros=True):
"""Truncate too low and too high values.
Parameters
----------
data : np.ndarray
Image to be truncated.
percMin : float
Percentile minimum.
percMax : float
Percentile maximum.
discard_zeros : ... | c9f56e593255ae6261b6f709b725cc952accc884 | 3,639,472 |
def obtain_dcdb_to_drugbank(biana_cnx, unification_protocol, output_pickle_file):
"""
Obtain a dictionary {dcdb : drugbank}
"""
up_table = return_unification_protocol_table(biana_cnx, unification_protocol)
query = ('''SELECT DC.value, DB.value FROM externalEntityDCDB_drugID DC, {} U1, {} U2, exter... | 02b9d5b6ddb29974d551123e7bb12a7a6aca3ca4 | 3,639,473 |
def duo_username(user):
""" Return the Duo username for user. """
return user.username | 92b2bfd5f6f3027787db493880139a8564597946 | 3,639,474 |
import random
def random_number_list(data=[]):
""" Add random number between 0 and 9 (both inclusive) to a list """
for i in range( 0, list_length ):
# append a random int to the data list
data.append( random.randint(0, 10))
return data | 5a04409a40e1e65216579056f95024269da1fc5a | 3,639,475 |
def _matrix_method_reshape(df: pd.DataFrame) -> pd.DataFrame:
"""
Reshape df for matrix method and deal with missing values.
We first drop columns which contain all missing values, transpose
the dataframe and then fill the remaining missing values with zero,
to deal with missing items in some period... | 64989a6c61d1d891a3190cc1f6a36c98cf562775 | 3,639,476 |
import warnings
def sim_bursty_oscillator(T, Fs, freq, prob_enter_burst=.1,
prob_leave_burst=.1, cycle_features=None,
return_cycle_df=False):
"""Simulate a band-pass filtered signal with 1/f^2
Input suggestions: f_range=(2,None), Fs=1000, N=1001
Paramet... | ea408f91f6160114f0077bd441ea049f848d2da1 | 3,639,478 |
def visualize_percent_diff(df):
"""Creates a visualization of difference in percentage of tweets of a topic
across the entire US and returns the mean sentiment felt about the
topic across the entire US
Parameters:
-----------
df: pd.DataFrame
dataframe containing all tweets. Must conta... | d3f3404e5695a0191580f3df20eaf4c824d3e436 | 3,639,479 |
import six
import inspect
def basic_compare(first, second, strict=False):
"""
Comparison used for custom match functions,
can do pattern matching, function evaluation or simple equality.
Returns traceback if something goes wrong.
"""
try:
if is_regex(second):
i... | ee16806fd78f46c2bcf01a5263f6d0210c22f32a | 3,639,480 |
def parse_line(line,):
"""Return a list of 2-tuples of the possible atomic valences for a given line from
the APS defining sheet."""
possap = []
for valence, entry in enumerate(line[4:]):
if entry != "*":
possap.append((valence, int(entry)))
return possap | d27ed66cb35084c9927cae8658d7ea8a421c69a4 | 3,639,481 |
from datetime import datetime
def dashboard():
"""Получить статистику по сайту"""
user = get_user_from_request()
if not user.is_admin:
return errors.no_access()
users = User.select().count()
d = datetime.datetime.now() - datetime.timedelta(days=7)
active_users = User.select().where(... | 05363fd27ee6980258b7ea015a81e644799c5baa | 3,639,483 |
def dct(f, axis=-1):
"""
Compute the Discrete Cosine Transform over the specified axis.
:param f: The input array.
:param axis: Axis along which the DCT is computed. The default is over the last axis.
:return c: The computed DCT.
"""
# Size of the input along the specified axis.
... | 3e6cd65a3088d948fb81f61c25b2f590facb8351 | 3,639,484 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.