content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import warnings
def astype(x, dtype, var, stacklevel=3):
"""Return `x` or a copy of `x`, with its type converted to `dtype`.
`var` is the name of `x` as seen by users of a public API, which may be
used in a warning message. `stacklevel` corresponds to the number of frames
to skip when reporting the wa... | cc769b17958b663c22ac4f7e5fc884ef88d64edc | 61,785 |
import jieba
def _jieba_extract(addr, sequential):
"""基于结巴分词进行提取"""
result = Pca()
pos = 0
truncate = 0
def _set_pca(pca_property, name, full_name):
"""pca_property: 'province', 'city' or 'area'"""
in_order = True
if sequential:
property_orders = [ 'province', ... | fe77f48801409aa59ae8159e1ba240c2d249fe1e | 61,786 |
def get_trader_violation(model, trader_id, trade_type):
"""Get trader violation"""
if (trader_id, trade_type) in model.V_TRADER_TOTAL_OFFER.keys():
return sum(model.V_CV_TRADER_OFFER[trader_id, trade_type, i].value
for i in range(1, 11))
else:
return 0.0 | 1ef4822345bd16e17d0b351148275a288fc281a5 | 61,788 |
def compute_pm_hull_vertices(image):
"""Get PyMunk vertices that enclose the alpha channel of a given RGBA image."""
alpha = np.array(image)[:,:,3]
nonzero_points = cv2.findNonZero(alpha)
hull = cv2.convexHull(nonzero_points).squeeze()
# Flip the y-axis since it points up in PyMunk
hull[:, 1] = ... | ae89d3c945840cb529a056d39048cb5a9b9b7b79 | 61,789 |
def to_yaml(template, clean_up=False, long_form=False):
"""
Assume the input is JSON and convert to YAML
"""
data = load_json(template)
if clean_up:
data = clean(data)
return dump_yaml(data, clean_up, long_form) | 08d5a55f57025fe4c171ac8a26fc75d333bc47d6 | 61,790 |
def _ccd_product_from_pixel(pixel):
"""Creates a ccd-product for a given pixel
Runs the ccd operation on a pixel and converts the results into a dataset
Args:
pixel: An xArray dataset with dimensions latitude, longitude, and time with dims of 1x1xt
Returns:
An xArray dataset with the ... | de1f0c57cce5ea26cc6c09e56ecc142c79852b7c | 61,791 |
def doc_metadata(metadata_filename):
"""
"""
data = pd.read_csv(metadata_filename, usecols=['doc_id', 'year','title'])
return data | f57f8874c46267835556f00703b9602c74fe421f | 61,792 |
def GetAtomicWeightsForFingerprint(refMol, probeMol, fpFunction, metric=DataStructs.DiceSimilarity):
"""
Calculates the atomic weights for the probe molecule
based on a fingerprint function and a metric.
Parameters:
refMol -- the reference molecule
probeMol -- the probe molecule
fpFunct... | 33ed51e80215027d0f5b4318789edced6926ea10 | 61,793 |
def read_skeleton(filename):
"""
Imports the data from the given .skel file
Parameters:
filename (string): The name of the .skel file
Return:
(Array, Array, Array): The skeleton joints, the joints radius and the skeleton bones
"""
with open(filename) as file:
joint... | aa6d94cd4cf4e32419f26bb354697de245440994 | 61,794 |
def patched_connect(sock, address):
"""
Intercepting function for _socket.socket.connect
returns _socket.socket.connect's result
"""
hostname, port = address[:2]
if hostname not in dns_cache:
dns_cache[hostname] = resolve(hostname, port)
hostname = dns_cache[hostname]
return og_c... | a6149e9a6e00e3de96173497b8d7bbf3c6d239e0 | 61,795 |
def readCsvIntoDataframe(source, csv_schema, csv_header=False):
"""
Params:
source: String. Path of source csv file to read.
csv_schema: StructType. Data schema.
csv_header: Boolean. Set true if file inlcudes header. False
by default.
"""
validateInput(source,... | 074e538c228c8f117f54ffcd3588ac1b11df43f4 | 61,796 |
def shorter(item):
"""Make a string shorter.
item -- a unicode string."""
if len(item) > 2:
return item[:-2] + u'\u2026' # ellipsis
return item | d3d9f678c5055e43f2120c1779bbd41066c8684d | 61,797 |
def patchedOpenExcepRasingMockSteam(monkeypatch):
"""
A fixture that creates an open stream that raises a ValueError when read from.
Streams indicate they have been closed by raising a ValueError.
"""
def raiser(self):
raise ValueError
monkeypatch.setattr(MockStream, "closed", False)
... | 80072e4650539aeee0f481ffc41770f500881b70 | 61,798 |
def route_con(lst):
"""
Функция для получения списка лучшего пути
:param lst: list -- список кортежей лучшего пути
:return result: list -- список лучшего пути
"""
result = []
for elem in range(len(lst)):
if elem == 0:
result.append(lst[elem][0])
result.append(... | dae6a3613c5908615b1504b9960a6981d84b3224 | 61,799 |
def minibatch_discriminator(x):
""" Computes minibatch discrimination features from input tensor x"""
diffs = K.expand_dims(x, 3) - \
K.expand_dims(K.permute_dimensions(x, [1, 2, 0]), 0)
l1_norm = K.sum(K.abs(diffs), axis=2)
return K.sum(K.exp(-l1_norm), axis=2) | 6aca40e80c5b86d291251adec1457f715a77ee45 | 61,800 |
def parse_module_descriptors(raw_json: bytes) -> list[ModuleDescriptor]:
"""Parse the JSON output of `go list -m`."""
if not raw_json:
return []
module_descriptors = []
for raw_module_descriptor in ijson.items(raw_json, "", multiple_values=True):
if raw_module_descriptor.get("Main", Fal... | 750af019899f554cd2cb8b8043360d3893850837 | 61,801 |
from typing import Any
from typing import Tuple
from typing import Optional
import numbers
import torch
def _parse_array_or_scalar_like_pair(actual: Any, expected: Any) -> Tuple[Optional[Exception], Optional[_ParsedInputs]]:
"""Parses an scalar-or-array-like pair.
Args:
actual: Actual array-or-scalar... | eadfa0b9de6cd419bdf657a3b66207d0ac052b7c | 61,802 |
def atomic(session=default_session):
"""
with atomic(): # None
pass
with atomic(session): # Session
pass
@atomic # Callable
def x():
pass
@atomic(session): # Session
def x():
pass
"""
if (
not isinstance(session, (Session, scoped_session... | 909160c1f67c3af61d81139a5776a64fa171eaa5 | 61,803 |
import mpmath
def var(k, theta):
"""
Variance of the gamma distribution.
"""
k = mpmath.mpf(k)
theta = mpmath.mpf(theta)
return k * theta**2 | 9dbbc299f41810555dd379dfcc3dd6f16daa74a5 | 61,804 |
def count_newlines_fast(path: Pathlike):
"""
Counts newlines in a file using buffered chunk reads.
The fastest possible option in Python according to:
https://stackoverflow.com/a/68385697/5285891
(This is a slightly modified variant of that answer.)
"""
def _make_gen(reader):
b = re... | 6c79bb00834685e00cb201d31ca61637b0c0a94f | 61,805 |
def current_date_int():
"""
获取当前时间日期 int值
不使用时间api,直接进行字符串解析,执行效率高
:return: 日期int值
"""
date_int = 0
# 首先获取str
today = current_str_date()
# 手动比系统a时间pi快
today_array = today.split("-")
if len(today_array) == 3:
date_int = int(today_array[0]) * 10000 + int(today_array[1])... | 8a2425f64b39ece46b5e2ee1088f9d8d690e25a7 | 61,807 |
import signal
def _timeout(seconds):
"""Decorator for preventing a function from running for too long.
Inputs:
seconds (int): The number of seconds allowed.
Notes:
This decorator uses signal.SIGALRM, which is only available on Unix.
"""
assert isinstance(seconds, int), "@timeout(... | afa077719853ed132cd0ca92225bbbe555371c0f | 61,809 |
import asyncio
def listen_properties_changed(bus, callback):
"""Create a future for a PropertiesChanged signal listener.
Args:
bus: The system bus object to use.
callback: The callback function to run when signal is received.
Returns:
Integer rule id.
"""
return bus.addM... | 1c6685eac1bb9419d95cb3e32409b247714b365c | 61,810 |
import select
def get_hadoop_conf_dir():
"""
Gets the shared hadoop conf directory using:
1. Start with /etc/hadoop/conf
2. When the stack is greater than HDP-2.2, use /usr/hdp/current/hadoop-client/conf
3. Only when doing a RU and HDP-2.3 or higher, use the value as computed
by conf-select. This ... | 27ac913d5ad34772bef51a6befb3f685390ef7cd | 61,813 |
from typing import Sequence
from typing import Iterable
import functools
def generate_aggregate_pubkeys(validators: Sequence['ValidatorRecord'],
vote_data: 'SlashableVoteData') -> Iterable[BLSPubkey]:
"""
Compute the aggregate pubkey we expect based on
the proof-of-custody i... | 478cdb3ab19c75b0e2fe042248cdbbb1cf251ebf | 61,816 |
def get_dimensions(unit):
"""get the set of basis units"""
if hasattr(unit, 'dimension'):
return unit.dimension
if isinstance(unit, Mul):
return Mul.fromiter([get_dimensions(arg) for arg in unit.args])
if isinstance(unit, Pow):
base, exp = unit.as_base_exp()
return Pow(ge... | a564a6d1369f19d4830cdbffdf7240e3f362248a | 61,817 |
from typing import Tuple
def mutual_information(
indices_a: np.ndarray, indices_b: np.ndarray
) -> Tuple[float, float]:
""" Mutual Information
Parameters
----------
indices_a : array-like, shape(n_samples)
Symbolic time series.
indices_b : array-like, shape(n_samples)
Symbol... | 4aaf38a01257a8de8b052eb07e3a9ca9bcac6945 | 61,818 |
import json
def validate_token(func):
"""Decorator for validating the JWT token required for API requests."""
@wraps(func)
def wrapper(*args, **kwargs):
"""Tries to decode the JWT token using the SECRET KEY.
Executes the original function if token is valid.
Otherwise ret... | 43b5427cc8edd8d2639634411f60ca6b61586891 | 61,819 |
def get_node_properties(node_ids, **options):
"""Get properties associated with nodes."""
fields = options.pop('fields', None)
functions = {
'type': 'labels(n)',
}
if fields is not None:
prop_string = ', '.join([f'{key}:{functions[key]}' if key in functions else f'{key}:n.{key}' for... | bbd107aa07fa7d84891f83fa7c531e7bc66e2ae3 | 61,821 |
def reverse(insts):
"""
Reverse the order of instances.
This function should be passed to :meth:`InstanceSet.select` without any
argument.
>>> insts = InstanceSet('prediction_result_path').select(reverse)
"""
return list(reversed(insts)) | 44c63fc05015bb4eb5bed9bfdb3cdd4fbd456226 | 61,823 |
def destination(φ1: float, λ1: float, α: float, d: float):
"""Destination point, provided origin, bearing, and distance.
This is the solution to the "first" (or "forward") geodetic problem,
assuming a spherical Earth.
Parameters
----------
φ1, λ1 : float
initial latitude, longitude
... | 7d128cfa7a529eb7d9598f7aff8d8bbebbec5e8f | 61,824 |
def create_volumes(kname, cname):
"""
Creates volume bindings for Kraken name `kname` and container name `cname`.
"""
volumes = {}
# Mount configuration directory. This is necessary for components which
# populate templates and need to mount the populated template into the
# container.
... | d4db9bcd77efeb852f016834d571fb698f70d78d | 61,825 |
def double_pend(
y: list,
t: float,
m_1: float,
l_1: float,
m_2: float,
l_2: float,
g: float
) -> list:
"""
Calculate one step for coupled pendulums.
Args:
y: (theta_1, theta_d_1, theta_2, theta_d_2) at this timestep.
t: Time (unused).
m_1: Mass 1.
... | 386384102ddf1ff3d1a44452da6b5586b25398f6 | 61,826 |
import functools
def ClientOnly(f):
"""A decorator that asserts _IS_CLIENT."""
@functools.wraps(f)
def Wrapper(*args, **kwargs):
assert _IS_CLIENT
return f(*args, **kwargs)
return Wrapper | ae48c4347d160a0b04cabb2ee1080210f42288f5 | 61,827 |
def read_var_def(line: str, type_word: str = None, fun_only: bool = False):
"""Attempt to read variable definition line"""
if type_word is None:
type_match = NAT_VAR_REGEX.match(line)
if type_match is None:
return None
else:
type_word = type_match.group(0).strip()... | 4f388ec192d0f39690ba004ef9a208f53afca84a | 61,828 |
def get_user_by_api_key(api_key):
"""Looks up a user by an API key.
Args:
api_key: API key.
Returns:
A user dictionary.
Raises:
KeyError: If the specified user is not found.
"""
if not api_key:
raise KeyError('User not found by API key')
user = _db.users.fi... | 9d5dfc740398481bb9008c26181541f845321a88 | 61,829 |
def tanh(X):
"""an activation function which outputs the value between (-1,1)"""
if isinstance(X,np.ndarray):
return (2.0/(1.0+np.exp(-(2*X))))-1
else:
X=np.array(X)
return tanh(X) | dc774769242e4414243b6370d3b087b611b1d01d | 61,832 |
from typing import Optional
from typing import Mapping
from typing import Any
def char_key_value_linear_source_from_params(
params: Parameters,
*,
input_namespace: str = "input",
eval_context: Optional[Mapping[Any, Any]] = None,
) -> KeyValueLinearSource[str, str]:
"""
Get a key-value source b... | ac3eb4d529d75780b8793432229ed1bbb4fdc2b9 | 61,833 |
def get_train(opt):
"""Get training dataset for KDD 10 percent"""
return _get_adapted_dataset(opt, "train") | 591023b39b162682b2c396e8298bc8c0e492c5cb | 61,834 |
def sort_by_time(raw_folded, pdc_channels, return_indices=False):
""":param pdc_channels (tuple of lightkurve.FoldedlightCurve)"""
sort_idx_raw = np.argsort(raw_folded.time_original)
sort_idx_pdc = np.argsort(pdc_channels[0].time_original)
apply_indices_to_light_curve(raw_folded, sort_idx_raw)
for ... | c59c02651b60afc5b65079a10958f771ff32f887 | 61,835 |
def register_deserializer(instance, **options):
"""
registers a new deserializer or replaces the existing one.
if `replace=True` is provided. otherwise, it raises an error
on adding a deserializer which is already registered.
:param AbstractDeserializerBase instance: deserializer to be registered.... | 1e5ac3f1e26b1920ad23be1df2ba9aba74aedec9 | 61,836 |
import numpy
def maximum(input, labels=None, index=None):
"""
Find the maxima over an image at specified subregions.
Parameters
----------
input : ndarray
N-D image data
labels : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int... | f280c5b83ac191c208c799a59e5c483dcd4aaad5 | 61,837 |
def getViolationFromAria2(ariaViolation, constraint, violationList):
"""Descrn: Make a constraint's violation object in the input violation list given an Aria2
violation analysis object.
Inputs: Aria2 violation analysis object, NmrConstraint.DistanceConstraint, NmrConstraint.ViolationList
Outpu... | f89718bb8a2b767e51e9efa657768327548822f1 | 61,838 |
def enforce_connectivity(image, outside):
"""
Function to filter out any objects not connected to the largest
cluster in image.
Inputs:
image (np.ndarray) : Binary input raster with 1's corresponding
to hydrodynamically active areas, which get mapped to high
resolution, a... | 90e6f4fb7d8133ba2f2c8ad88d12951e4e221669 | 61,839 |
def psnd_chlA_vi(imgData, wave, mask=0, bands=[-1,-1]):
"""
Function that calculates the Pigment Sensitive Normalized Difference for Chlorophyll A.
This functions uses bands 675 and 800 nm. The closest bands to these values will be used.
Citation: Blackburn, G.A. 1998. Spectral indices for estimating p... | 9c27a09a6c83d31526dce83b50a23e5acdc3fb2c | 61,840 |
def test_request_without_setting_receive():
"""
If Request is instantiated without the receive channel, then .body()
is not available.
"""
def app(scope):
async def asgi(receive, send):
request = Request(scope)
try:
data = await request.json()
... | a1e3cc5dd59a20537ae66d8f1d575ef43f99136a | 61,841 |
def fraction_of_death_40():
"""
Real Name: b'fraction of death 40'
Original Eqn: b'0.4'
Units: b'dmnl'
Limits: (None, None)
Type: constant
b''
"""
return 0.4 | c4dd46a565660acf07273a58002cc9b2cbf94bc8 | 61,842 |
def test_video_file():
# type: () -> str
""" Fixture for test video file path (ensures file exists).
Access in test case by adding a test_video_file argument to obtain the path.
"""
return get_absolute_path("resources/testvideo.mp4") | c5a582ed4e4d1fdd52cdb026e86834626fc3678c | 61,843 |
def write_ometiff(filepath, img,
scalex=0.1,
scaley=0.1,
scalez=1.0,
dimorder='TZCYX',
pixeltype=np.uint16,
swapxyaxes=True,
series=1):
"""ONLY FOR INTERNAL TESTING - DO NOT USE!
This f... | 61068659dfadedebec258644c188d57b2d95731e | 61,847 |
def mnist8m_data():
"""
Loads and returns data of MNIST8M dataset for all digits.
Returns
-------
data : list
A list of length = 1, where each element is a dictionary which contains ``train_outputs``,
``train_inputs``, ``test_outputs``, ``test_inputs``, and ``id``
References
... | 4302159bc205c9deb4c7fcdf04610246b07fdfd7 | 61,848 |
from typing import Dict
import pathlib
def dir_parser(path_to_dir: str) -> Dict[str, Dict[str, str]]:
"""
Parses the given directory, and returns the path, stem and suffix for files.
"""
files = pathlib.Path(path_to_dir).resolve().glob("*.*")
files_data = {}
for file in files:
files_... | 3b6c0ac172ad863470d492aa99713fab3ecf5d99 | 61,849 |
def logsumexp(x):
"""
Compute log(sum(exp(x))) avoiding over/underflow
"""
x = np.asarray(x)
m = x.max()
return np.log(np.sum(np.exp(x - m))) + m | f4fe60c804c7e97fec56050f43a42deadd4cdd2c | 61,851 |
def GetConfig(user_config):
"""Load and return benchmark config.
Args:
user_config: user supplied configuration (flags and config file)
Returns:
loaded benchmark configuration
"""
config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME)
if FLAGS['ycsb_client_vms'].present:
co... | 8fdcc5944252dfbbdc2fd5bd7dda7595c86396f0 | 61,852 |
def is_left(element1, element2):
"""Is element2 on the left of element1.
Args:
element1: XML element1 dump from UI.
element2: XML element2 dump from UI.
Returns:
Whether element2 is on the left of element1.
"""
[e1_x1, e1_y1, e1_x2, e1_y2] = get_element_bounds(element1)
[e2_x1, e2_y1, e2_x2, e... | e14ccc4c44b5fc1d5a282cf8e156ffa3bcda4cb1 | 61,853 |
def return_error_response():
"""Return error response sample"""
return make_response(jsonify({}), 403) | fa07ffc6c049962b129671a498a88f532b6be3ad | 61,854 |
import inspect
def is_redefined_dataclass_with_slots(old: type, new: type) -> bool:
"""Return True if `new` is the `old` dataclass redefined with `__slots__."""
# Must both be dataclasses.
if "__dataclass_fields__" not in old.__dict__ or "__dataclass_fields__" not in new.__dict__:
return False
... | c5c760bca752c0458139419f3c8e519ed8adad66 | 61,855 |
def get_total_characters(data):
"""
data - list
example:
data = [
[16,1027791027,993,GLORIA,MASTON,9,09/22/1938,F,W,*********7,*L**IA,******,**/**/****,F,*,8,2,0],
[16,1027791028,2412,GEORGE,MASTON,10,09/22/1938,M,W,*********8,*E**GE,******,**/**/****,M,*,8,2,0]
... | d1163615ee860be7991cce837f798eaf2d7d3781 | 61,856 |
def pyreq_rm_all_samples(httpreq_handler: HTTPRequestHandler, project_id: int, locale: str):
"""
Remove all samples in a locale of NLU model in Mix project by querying API endpoint
with DELETE method using "requests" package
API endpoint
::
DELETE f"nlu/api/v1/nlu/<PROJECT_ID>/interactions?... | e7db3dc160eda49f79922f6e639211f0aa90ceb0 | 61,857 |
def places(client, request,
geojson=None,
bbox=None,
buffer=None,
filter_category_ids=None,
filter_category_group_ids=None,
filters_custom=None,
limit=None,
sortby=None,
dry_ru... | 4b05a8d2f2d867517ca5b2b7a333eb4c46fa657b | 61,858 |
import numpy
def read_tmqm_properties(csvfile,xyzfile):
"""Reads the csv and xyz files comprising the tmqm dataset.
Args:
csvfile(str): Filename of the tmqm dataset csv file.
xyzfile(str): Filename of the tmqm dataset xyz file.
Returns:
numpy.ndarray: Numpy array of named propert... | 3161d437bd5288b0abdfcbcbb382cdfc2801f608 | 61,859 |
from .GSL import GSL as gsl
def gsl():
"""
The GSL package manager
"""
# grab the protocol
# and generate a facility
return gsl() | 469819fe050b9b17174c34ae5a99cf0ec22de8a0 | 61,860 |
def reference_selection_dop(target_position,receivers):
""" select reference receiver with lowest dop"""
dop_references = []
H_references = []
for idx in range(len(receivers)):
dop,H = calc_dop(target_position,receivers,receivers.keys()[idx])
dop_references.append(dop)
H_refere... | d5d2f9d311d8f0f831b0a5a7a793a5f22d42a844 | 61,861 |
import pickle
def BRN_fourier_integrand_splines(links, unwrap, Nvals=None, rvals=None, Bprop=None):
"""Return normalized, real space Green's function G(R;Rmax) for kinked WLC using
spline integration.
Parameters
----------
kvals : (29999,) array-like
k values for which to compute G(k; N) ... | ff5e483985787d955c137721196733866a84aa88 | 61,862 |
from lmfit import Parameters
from typing import OrderedDict
def residual_PM_IG_gamma(value_dict, time, f, data=None, weight=None, eps=None):
"""
derived the residual between model and data given params_local.
inputs:
value_dict dictionary with parameters, or lmfit.parameters instance.
... | 2844a38831753caea5cab77dcc89d8af78173a12 | 61,863 |
def merge_all(lst, strategy="smart", renderer="yaml", merge_lists=False):
"""
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupd... | 1fd328f85a91599bf9956219a7256d477cb54480 | 61,864 |
from typing import Optional
def __parseGregorian(date_str: str) -> Optional[str]:
"""Tries to parse the given string as a gregorian date.
Return the string 'DD.MM.YYYY' on success, `None`else.
Args:
date_str (str): The string to parse
Returns:
Optional[str]: The string 'DD.MM.YYYY' o... | 49c6dc46efa7367fde35d9937351d86db265e067 | 61,866 |
def ecc_overview():
"""
For lack of a better alternative redirect users to the main page
"""
return redirect(url_for('main.screen')) | c94242b9a1ed5f869bb8f0c1290de9c26843eaf2 | 61,867 |
def bprop_scalar_sign(x, out, dout): # pragma: no cover
"""Backpropagator for `scalar_sign`."""
return (zeros_like(dout),) | 138aa2813a62ac5f198b972882b158ef20707f31 | 61,868 |
from typing import List
def calculateFourCornersProduct(tiles: List[Tile]) -> int:
"""
Finds 4 corners tiles and multiplies IDs
"""
fourCornersProduct: int = 1
for i in range(len(tiles)):
top, bottom, left, right = False, False, False, False
for j in range(len(tiles)):
if i == j:
... | 74b7b934b176168206b95f36adcccb0c3789233a | 61,869 |
from typing import Union
import re
import random
async def urnotgod(ctx: Context) -> Union[Message, str]:
"""Responds with a variety of messages that oppose a person who claims to be god."""
if re.search(r"\b(i( )?('| a)?( )?m g( )?o( )?d)\b",
ctx.message.content.strip().lower()):
a... | c22356553d140c2abc8fc13e87605bc5c37cf87b | 61,870 |
def SiteParameters():
"""Create the site parameters for this site.
Returns:
dict containing SiteParameters for ChromeOS.
"""
# Chrome OS site parameters.
site_params = config_lib.DefaultSiteParameters()
# Helpers for constructing Chrome OS site parameters.
manifest_project = 'chromiumos/manifest'
... | 28a9a6f79ac319fecdfe5ef3ee861d34b5dfa442 | 61,871 |
import reproject
def project_to_header(fitsfile, header, **kwargs):
"""
Reproject an image to a header. Simple wrapper of
reproject.reproject_interp
Parameters
----------
fitsfile : string
a FITS file name
header : pyfits.Header
A pyfits Header instance with valid WCS to ... | 3a8719677dd7a1e2e8280a14d40a81f5850a54cf | 61,872 |
def fetch_tae_df(preprocess=False):
"""
Fetch the `tae`_ dataset from OpenML and add `fairness_info`.
It contains information from teaching assistant (TA) evaluations.
at the University of Wisconsin--Madison.
The prediction task is a classification on the type
of rating a TA receives (1=Low, 2=... | 7dbb4fe32f280d0d6e1a3fef5ddbd805c1d3f293 | 61,875 |
def filter_data(data):
"""
Filters data for years after 2010 and data originating
from Syria.
Inputs:
data (pd.DataFrame): Input data with column "Year" and "Origin"
Returns:
data (pd.DataFrame): Filtered data
"""
if 'Origin' in data.columns:
data = data[(data.Year >... | 2daf6fbd815fcea9dd3c2712363cd99cdca62a34 | 61,876 |
def parse(tokens):
"""
Every time you generate a statement, backtrack to see if you have completed
an application.
"""
revlist = list(reversed(tokens))
stack = []
line = linecount(revlist)
col = 1
for tok in revlist:
col += 1
try:
if type(tok) == int:
... | 6d0b8b8efba06d9cf85c15bf6ad8b3bb002a733d | 61,877 |
def _mask_relv_scores(relv_scores, doc_masks):
"""
fill padded sentences with score of -np.inf for ranking purpose.
:param relv_scores: d_batch * max_ns_doc
:param doc_masks: d_batch * max_ns_doc
:return:
d_batch * max_ns_doc
"""
relv_mask = np.full_like(relv_scores, -np.inf)
... | 61bafb6b312e8d109fad4d97edc286adf631a986 | 61,878 |
def ridge(func, xlims, ylims, ds, *fargs, **kwargs):
"""Ridge detection
"""
x1, x2, A = repulsion_rate(func, xlims, ylims, ds, *fargs, plot=False, newfig=False, output=True, **kwargs)
X1, X2 = np.meshgrid(x1, x2)
V1, V2 = func([X1, X2], *fargs)
Ay, Ax = np.gradient(A, ds)
return x1, x2, (V2*Ax-V1*Ay)/(V1*... | 7cdcb2b1b75cb53aad2689c1e778495e492256e7 | 61,879 |
def strrep(strg,x):
""" A função retorna uma string com n repetições;
str, int -> str """
return strg*x | 6e3d59666778af9db781a11e6f48b61010e7de4d | 61,880 |
from datetime import datetime
def get_steps(image):
"""Get build steps for msan-libs-builder."""
timestamp = datetime.datetime.utcnow().strftime('%Y%m%d%H%M')
upload_name = 'msan-libs-' + timestamp + '.zip'
steps = build_base_images.get_steps([
'base-sanitizer-libs-builder',
'msan-libs-builder',... | bcb1be0a03f111f7448e60aeed1f4975447bd135 | 61,881 |
import collections
def get_top_n(predictions, n=10):
"""Return the top-N recommendation for each user from a set of predictions.
Args:
predictions(list of Prediction objects): The list of predictions, as
returned by the test method of an algorithm.
n(int): The number of recommendat... | 581da4680f5a122f2af86473ddd927353d4c579f | 61,883 |
def list_data_sources(*args, **kwargs):
"""
List all available data sources to use the hash_search API
Variables:
None
Arguments:
None
Data Block:
None
Result example:
[ <list of sources> ]
"""
return make_api_response(sorted(sources.keys())) | 25e7e371e5e43ccf874f1ab064fc8245a99d6884 | 61,884 |
def connect_to_mc_testing_db(forced_db_name='testing'):
"""
Get a DB object that is connected to the testing M&C database.
Parameters
----------
forced_db_name : str
Database name to use.
Returns
-------
DB object
An instance of the `DB` class providing access to the te... | a40ed3d9f61d1f1cac48761e114950ab7a2b84d0 | 61,885 |
def action_dispatcher(decoy: Decoy) -> ActionDispatcher:
"""Return a mock in the shape of an ActionDispatcher."""
return decoy.mock(cls=ActionDispatcher) | c7b7b28cc3454a71db25e61062f54ef801cbd677 | 61,886 |
import time
def get_token(session):
"""
Checks to see if there's a valid token for the current session and/or
whether an existing token is expired.
If expired, it grabs the refresh token.
"""
token_valid = False
token_info = session.get("token_info", {})
# Checking if the session a... | 2f14c9dd04285bdcb2c357095c5d631760afa8f0 | 61,887 |
from re import T
def leakyrelu_forward(input, negative_slope=0.1):
"""
forward pass of LeakyReLU
"""
out = T.leakyrelu(input, negative_slope)
return out | 8ee793d521be7911f028352f14a057626870d8e8 | 61,888 |
from typing import cast
import warnings
def register_type(
type_: type,
*,
widget_type: WidgetRef = None,
return_callback: ReturnCallback | None = None,
**options,
):
"""Register a ``widget_type`` to be used for all parameters with type ``type_``.
Parameters
----------
type_ : typ... | bdd933a4cc7fdfb8df31ea5cf804c34377d9cf85 | 61,889 |
from io import StringIO
def mixed_types_structured():
"""
Fixture providing hetergeneous input data with a structured dtype, along
with the associated structured array.
"""
data = StringIO(
(
"1000;2.4;alpha;-34\n"
"2000;3.1;beta;29\n"
"3500;9.9;gamma;12... | 7b489f526139d5012112169cf2ad4610df985038 | 61,890 |
def redirect_back(default='web.index', **kwargs):
"""
If next is not none, redirect next, if not, redirect index page
"""
for target in request.args.get('next'), request.referrer:
if not target:
continue
if is_safe_url(target):
return redirect(target)
return r... | b254e79d6d45dedcae5a9d5f5b022b28b8617d9e | 61,891 |
def take(n, iterable):
""" Yield n items of iterable.
Args:
n: an integer
iterable: an iterator
Returns:
A generator of the items.
Used by:
033, 044, 046
"""
return islice(iterable, n) | 5986d37ac38e7c7c3c635340aef367322b158044 | 61,892 |
def build_driver(executable_path: str = None, options: Options = None, headless=True, timeout=20) -> webdriver:
"""
Build Chrome driver instance
:param executable_path: str
:param options: Options
:param headless: bool
:param timeout: int
:return: webdriver
"""
kwargs = {}
if e... | e8c81398af59794ccf72010a5a450285ef95f401 | 61,893 |
def leaky_relu_gradient_op(node_A, node_B, alpha, ctx=None):
"""Computes the gradient of the ReLU function.
Parameters:
----
node_A : Node
LeakyRelu input.
node_B : Node
Previous gradient node.
alpha : float
LeakyRelu alpha
Returns:
----
A new Node instanc... | 86d3a045af456b52802fde94f29d941448c7b7b6 | 61,894 |
def getFssMaskLoss(cbsd_grant, constraint):
"""Gets the FSS mask loss for a FSS blocking protection constraint.
Args:
cbsd_grant: A CBSD grant of type |data.CbsdGrantInfo|.
constraint: The protection constraint of type |data.ProtectionConstraint|.
The constraint defines the FSS out of band left part,... | 270f883a3c002b7932caea5225296c32b6e906f6 | 61,895 |
def get_adversarial_data(dataset = "gtsrb",set_type = "Test_fgsm"):
"""
Get the numpy arrays of the dataset for test
Params:
set_type:
Test_fgsm -> Test set + adversarial examples from FGSM
Test_jsma -> Test set + adversarial examples from JSMA
Returns:
x_s... | e878cb16a531123680a26048f4d9953abad03378 | 61,896 |
def task_build():
"""Create full distribution."""
return {
'actions': ['python -m build'],
'task_dep': ['gitclean', 'mo', 'docs'],
} | 7112ab22031299207dfb9c14d2482ef52e975f89 | 61,897 |
def serve_pil_image(pil_img):
"""
see:
https://groups.google.com/forum/?fromgroups=#!topic/python-tornado/B19D6ll_uZE
http://stackoverflow.com/questions/7877282/how-to-send-image-generated-by-pil-to-browser
"""
img_io = cStringIO.StringIO()
pil_img.save(img_io, 'JPEG', quality=70)
... | 745c32a195208b0bda7300b2a92e0b7e987d50a4 | 61,898 |
def _feature_dtype(feature):
"""Returns a representation of a Feature's type as a tensorflow dtype."""
if feature.type == schema_pb2.BYTES:
return tf.string
elif feature.type == schema_pb2.INT:
return tf.int64
elif feature.type == schema_pb2.FLOAT:
return tf.float32
else:
raise ValueError('Fea... | c1be2ef5eb2c4074d1118cd6c944ed34a505fd39 | 61,899 |
def read_images_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesBinary(const std::string& path)
void Reconstruction::WriteImagesBinary(const std::string& path)
"""
images = {}
with open(path_to_model_file, "rb") as fid:
num_reg_i... | 33c4237eec1820b114b391c495231cb52103bf70 | 61,900 |
import yaml
def load_file(filename):
"""
TBD
Args:
tbd
Returns:
tbd
"""
docs2 = []
vars = {}
varrefs = {}
with open(filename, 'r') as stream:
try:
docs = yaml.load_all(stream)
except yaml.YAMLError as exc:
print(exc)
do... | 2796ebb9d05be46df64215baf841e8fbe8c16a7c | 61,901 |
def get_positions(structure):
"""Wrapper to get the positions from different structure classes"""
try: # ASE structure
return structure.get_scaled_positions()
except AttributeError:
try: # diffpy structure
return structure.xyz
except AttributeError:
raise Va... | 6428139131de02b577925be9499668642a11a69c | 61,902 |
def _get_files(table, match):
"""
Return a consistently-ordered set of files for a given container query.
"""
pipeline = [
{'$match': match },
{'$unwind': '$files'},
{'$sort': {'files.name': 1}},
{'$group': {'_id':'$_id', 'files': {'$push':'$files'}}}
]
result =... | b352cb4c436f05bea31c6441b016d051125d7cbf | 61,903 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.