content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _try_path(basedir: P, rel: str):
"""
Returns content of file basedir/rel if it exists, None if file not found, or throws an exception
"""
if not rel:
raise RuntimeError("Got invalid filename (empty string).")
if rel[0] == "/":
full_path = P(rel)
else:
full_path = base... | 5,321,300 |
def training():
"""
Function used to train the Multilayer Perceptron model.
:return: Nothing, just creates a file with the model parameters
"""
np.random.seed(42)
data = safe_opener(csv_file)
X_train, X_test, y_train, y_test = data_manipulation(data, False)
# Creation of the networ... | 5,321,301 |
def read_dataframe_legacy(dataset: zarr.Array) -> pd.DataFrame:
"""Reads old format of dataframes"""
# NOTE: Likely that categoricals need to be removed from uns
warn(
f"'{dataset.name}' was written with a very old version of AnnData. "
"Consider rewriting it.",
OldFormatWarning,
... | 5,321,302 |
def parse_code_str(code_str) -> ast.AST:
"""Parses code string in a computation, which can be incomplete.
Once we found something that leads to error while parsing, we should handle it here.
"""
if code_str.endswith(":"):
code_str += "pass"
try:
return ast.parse(code_str)
except... | 5,321,303 |
def fibonacci_list(n):
"""
用列表缓存中间的计算结果
:param n: n>0
:return
"""
lst = [0, 1, 1]
while len(lst) < n + 1:
ln = len(lst)
lst.append(lst[ln - 1] + lst[ln - 2])
return lst[0] if n < 0 else lst[n] | 5,321,304 |
def install(parameters):
"""Build capnpc-java from source."""
drydock_src = parameters['//base:drydock'] / get_relpath()
if (drydock_src / 'capnpc-java').exists():
return
def get_var_path(name):
cmd = ['pkg-config', '--variable=%s' % name, 'capnp']
path = scripts.execute(cmd, c... | 5,321,305 |
def assert_array_almost_equal(
x: Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray],
y: Tuple[float, float, float, float],
):
"""
usage.scipy: 1
"""
... | 5,321,306 |
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
result = []
count = 0
newline = []
result2 = []
count2 = 0
for a in range(len(line)):
result.append(0)
for a in range(len(line)):
result2.append(0)
for num in line:... | 5,321,307 |
def _perc(a, b):
"""
Funzione di utility: fa il rapporto tra "a" e "b", ritornandone la percentuale a due cifre
"""
return 'N/A' if b == 0 else round(100.0 * a / b, 2) | 5,321,308 |
def max_run_time(t):
"""Limit the runtime of a code segment.
If a block of code runs for more than `t` seconds, kill it. This
only works on unix platforms; on Windows, there will be no time
limit.
Use within a with statement, e.g.
with max_run_time(5):
potentially_long_fu... | 5,321,309 |
def shift_left_bit_length(x: int) -> int:
""" Shift 1 left bit length of x
:param int x: value to get bit length
:returns: 1 shifted left bit length of x
"""
return 1 << (x - 1).bit_length() | 5,321,310 |
def save_reconstructions(reconstructions, out_dir):
"""
Saves the reconstructions from a model into h5 files that is appropriate for submission
to the leaderboard.
Args:
reconstructions (dict[str, np.array]): A dictionary mapping input filenames to
corresponding reconstructions (of ... | 5,321,311 |
def testLoadedWithoutModeRegModel(opt, model, testset,reg):
"""Tests a model over the given testset."""
model.eval()
test_queries = testset.get_test_queries()
all_imgs = []
all_captions = []
all_queries = []
all_queries1=[]
all_target_captions = []
if test_queries:
# compute test query features
... | 5,321,312 |
def test_message(sqs):
"""Testing the upload queue"""
proj = generate_proj()
from ndingest.ndqueue.cleanupqueue import CleanupQueue
CleanupQueue.createQueue(proj)
cleanup_queue = CleanupQueue(proj)
supercuboid_key = "kasthuri11&image&0&0"
cleanup_queue.sendMessage(supercuboid_key)
fo... | 5,321,313 |
def samPareto(a=3.0, size=None): # real signature unknown; restored from __doc__
"""pareto(a, size=None)
Draw samples from a Pareto II or Lomax distribution with
specified shape.
The Lomax or Pareto II distribution is a shifted Pareto
distribution. The classical Pareto distribution can be
obt... | 5,321,314 |
def ripple_carry_add(A, B, cin=0):
"""Return symbolic logic for an N-bit ripple carry adder."""
if len(A) != len(B):
raise ValueError("expected A and B to be equal length")
ss, cs = list(), list()
for i, a in enumerate(A):
c = (cin if i == 0 else cs[i-1])
ss.append(a ^ B[i] ^ c)
... | 5,321,315 |
def svn_stream_invoke_readline_fn(*args):
"""svn_stream_invoke_readline_fn(svn_stream_readline_fn_t _obj, void * baton, char const * eol, apr_pool_t pool) -> svn_error_t"""
return _core.svn_stream_invoke_readline_fn(*args) | 5,321,316 |
def cli():
"""Parse and return command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'file',
nargs='?',
default='/home/sam/notes/2020-08-28_5.md',
help='reading list file for reading/writing markdown notes'
)
args = parser.parse_args()
... | 5,321,317 |
def get_function_contents_by_name(lines: List[str], name: str):
"""
Extracts a function from `lines` of segmented source code with the name `name`.
Args:
lines (`List[str]`):
Source code of a script seperated by line.
name (`str`):
The name of the function to extract... | 5,321,318 |
def create_linux_process_time():
"""
Uses :mod:`ctypes` to create a :func:`time.process_time`
on the :samp:`'Linux'` platform.
:rtype: :obj:`function`
:return: A :func:`time.process_time` equivalent.
"""
import ctypes
from ctypes.util import find_library
import errno
CLOCK_PROC... | 5,321,319 |
def get_json(obj, indent=4):
"""
Get formatted JSON dump string
"""
return json.dumps(obj, sort_keys=True, indent=indent) | 5,321,320 |
def to_kelvin(value, initial_unit = "c"):
"""Convert temperature units to Kelvin.
This is an internal intermediate method to convert all
provided values to the same intermediate unit, which
greatly simplifies exposed calculation methods.
Internally, this is also mainly used to simplify
ideal gas cal... | 5,321,321 |
def create_pooling_layer(pooling_type,
window_size,
stride_size,
num_gpus,
default_gpu_id):
"""create pooling layer"""
scope = "pooling/{0}".format(pooling_type)
if pooling_type == "max":
pooling_laye... | 5,321,322 |
def move_subtrees_r(source: Path, target: Path, first: bool = True):
"""Recursive tree merge."""
if first:
target.mkdir(exist_ok=True)
path_attr = 'rename'
else:
path_attr = 'replace'
subtree: Path
for subtree in source.glob('*'):
target_path = target / subtree.name
... | 5,321,323 |
def PlotConfusionMatrix(cm, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
if n... | 5,321,324 |
def avgwig(file1, file2, fileout):
""" Given two wig files of same structure, output the average of both as a wig file
:param file1: first wig file
:param file2: second wig file
:param fileout: wig file (no extension) that outputs the average of the two input files
"""
with open(file1, "r") as... | 5,321,325 |
def gen_phi(n):
"""
Generates a n-sized random i.i.d. sample from the uniform distribution U(-1,1).
Uses inverse cdf transformation.
:param n: size of the sample
:return: a n-length array
"""
#cdf_x = np.random.rand(n)
#x = 2 * cdf_x - 1
x = np.random.chisquare(2, n)
return x | 5,321,326 |
def parse_url(url):
"""
Parses as RawSocket URL into it's components and returns a tuple:
- ``isSecure`` is a flag which is ``True`` for ``rss`` URLs.
- ``host`` is the hostname or IP from the URL.
and for TCP/IP sockets:
- ``tcp_port`` is the port from the URL or standard port derived fro... | 5,321,327 |
def build_operation(id, path, args, command="set", table="block"):
"""
Data updates sent to the submitTransaction endpoint consist of a sequence of "operations". This is a helper
function that constructs one of these operations.
"""
if isinstance(path, str):
path = path.split(".")
retu... | 5,321,328 |
def test_to_analyze_get_morphes_by_tags():
"""
Core Test: analyze using get_morphes_by_tags()
:return:
"""
global komoran
global str_to_analyze
morphes = komoran.get_morphes_by_tags(str_to_analyze, tag_list=['NNP', 'NNG', 'SF'])
assert isinstance(morphes, list)
assert len(morphes)... | 5,321,329 |
def downloadBlob(bucket_name, source_blob_name, destination_file_name):
"""Downloads a blob from the bucket."""
# bucket_name = "your-bucket-name"
# source_blob_name = "storage-object-name"
# destination_file_name = "local/path/to/file"
bucket = storage_client.bucket(bucket_name)
blob = bucket.b... | 5,321,330 |
def test_delete_user_negative():
"""
DELETE /users/{user_id}
Requirements: F-1
"""
created_user = {"name": "Daniel Snod", "status": "Confirmed", "id": "3g42j3743jj"}
# Use a test client configured for testing
with flask_app.test_client() as test_client:
endpoint = '/api/users... | 5,321,331 |
def test_retrieved_date(mock_osp):
"""
Syllabus#retrieved_date should return the log date.
"""
path = mock_osp.add_file(log={'date': 'now'})
syllabus = Syllabus(path)
assert syllabus.retrieved_date == 'now' | 5,321,332 |
def generate_password(length=50):
"""Generate a password."""
alphabet = string.ascii_letters + string.digits
return "".join(secrets.choice(alphabet) for i in range(length)) | 5,321,333 |
def visual_estimator(possible_heights, visual_sigma, visual_height):
"""Computes the visual estimate.
Parameters
----------
visual_sigma: ``float``
Standard deviation of the visual estimate.
possible_heights: ``ndarray``
Numpy array containing all the possible heights of
the... | 5,321,334 |
def whiten(x, source=None):
"""Mean and sd normalizes x column-wise relative to summary statistics
from source. Uses x itself by default"""
if source is None: source = x
means = np.mean(source, axis=0)
stddevs = np.std(source, axis=0)
return (x - means[None, :]) / stddevs[None, :] | 5,321,335 |
def poly_smooth(x, y, aperture, axis=0, N=3):
"""Smoothar *data* med hjalp av *N* te gradens polynom, langs med
*axis* [=0].
Invariabler
*x*
x-varden for data som skall smoothas
*y*
y-varden for data som skall smoothas
*aperture*
hur manga samp... | 5,321,336 |
def process_use(self):
"""
Process the ``use`` attribute which contains a list of task generator names::
def build(bld):
bld.shlib(source='a.c', target='lib1')
bld.program(source='main.c', target='app', use='lib1')
See :py:func:`waflib.Tools.ccroot.use_rec`.
"""
use_not = self.tmp_use_not = set()
self.... | 5,321,337 |
def gen_img_kpts(image, human_model, pose_model, human_sort, det_dim=416, num_peroson=2):
"""
:param image: Input image matrix instead of image path
:param human_model: The YOLOv3 model
:param pose_model: The HRNet model
:param human_sort: Input initialized sort tracker
:param det_dim: The input... | 5,321,338 |
def deep_skipthought(
dictionary,
epoch = 5,
batch_size = 16,
embedding_size = 256,
maxlen = 100,
ngram = (1, 4),
):
"""
Train a deep skip-thought network for text similarity
Parameters
----------
dictionary: dict
format {'left':['right']}
epoch: int, (default=5)... | 5,321,339 |
def PythonPanelKnobChanged(widget):
"""None"""
pass | 5,321,340 |
def compute_min_refills(distance: int, tank: int, stops: list):
"""
Computes the minimum number of gas station pit stops.
>>> compute_min_refills(950, 400, [200, 375, 550, 750])
2
>>> compute_min_refills(10, 3, [1, 2, 5, 9])
-1
Example 3:
>>> compute_min_refills(200, 250, [100, 150])
... | 5,321,341 |
def list_orders():
"""Shows a list of orders.
Requires administrator privileges.
"""
return render_template('order/orders.html', orders=Order.get_all()) | 5,321,342 |
def draw(layer, event):
"""Draw with the currently selected label to a coordinate.
This method have different behavior when draw is called
with different labeling layer mode.
In PAINT mode the cursor functions like a paint brush changing any
pixels it brushes over to the current label. If the back... | 5,321,343 |
def dkim_record_responder(query):
"""Provide empty DKIM key to all potential lookups."""
return TXT(query.name, "v=DKIM1; p=") | 5,321,344 |
def create_default_randomizer_pend() -> DomainRandomizer:
"""
Create the default randomizer for the `PendulumSim`.
:return: randomizer based on the nominal domain parameter values
"""
from pyrado.environments.pysim.pendulum import PendulumSim
dp_nom = PendulumSim.get_nominal_domain_param()
... | 5,321,345 |
def find_cursor(source):
"""Return (source, line, col) based on the | character, stripping the source."""
source = source.strip()
i = source.index('|')
assert i != -1
l = pyparsing.lineno(i, source)
c = pyparsing.col(i, source)
return source.replace('|', ''), l, c | 5,321,346 |
def make_provider(provider_type: str, **kwargs) -> provider.StorageProvider:
"""Make a StorageProvider from a provider type. Call with the arguments
you would normally provide to the specific implementation's constructor.
make_provider("azure", account_name="...", ...)
Args:
provider_type (str... | 5,321,347 |
def nearest(arr, val):
"""
Locate the element in the given array 'arr' which is
closest to the specified value 'val'.
"""
return arr[np.abs(arr-val).argmin()] | 5,321,348 |
def bookmarked_posts():
"""Manage a user's bookmarked posts."""
current_user = User.get_user_from_identity(get_jwt_identity())
if request.method == "GET":
page = request.args.get("page", 1, type=int)
per_page = request.args.get("per_page", 20, type=int)
posts = current_user.bookmark... | 5,321,349 |
def get_sip_flags(target_config):
""" Return the SIP platform, version and feature flags. target_config is
the target configuration.
"""
sip_flags = []
# If we don't check for signed interpreters, we exclude the 'VendorID'
# feature
if target_config.py_version < 0x030000 and not target_co... | 5,321,350 |
def preview(ui_file):
""" Preview the .ui file. Return the exit status to be passed back to the
parent process.
"""
from PyQt6.QtWidgets import QApplication
from .load_ui import loadUi
app = QApplication([ui_file])
ui = loadUi(ui_file)
ui.show()
return app.exec() | 5,321,351 |
def analize_image(path):
"""Analizes a file, returning True if it contains nudity."""
image = cv2.imread(path)
if image is None:
return False
return analize_numpy_array(image) | 5,321,352 |
def calc_pow_ref_sublhn(city, tes_cap=0.001, mod_boi=True,
boi_size=50000, eta_boi=0.95,
use_eh=False):
"""
Calculate reference electric heat generator load curve by solving thermal
and electric energy balance with reduced tes size (for sublhn)
(+ used ene... | 5,321,353 |
def replace_cfs(df, location):
"""Replace the CFS data for this year!"""
pgconn = get_dbconn('coop', user='nobody')
cursor = pgconn.cursor()
coop = XREF[location]['climodat']
today = datetime.date.today() + datetime.timedelta(days=3)
dec31 = today.replace(day=31, month=12)
cursor.execute("""... | 5,321,354 |
def _plot(
ambient_temperatures: List[float],
collector_input_temperatures: List[float],
data_type: str,
guess_function: Callable,
mass_flow_rates: List[float],
results: List[np.ndarray],
solar_irradiances: List[float],
y_data: List[float],
wind_speeds: List[float],
) -> None:
""... | 5,321,355 |
def create_L(rank):
"""
L matrix for the calculus of the l2 norm of a column of H in the smoothness criteria
(see Kimura, T., & Takahashi, N. (2017). Gauss-Seidel HALS Algorithm for Nonnegative Matrix Factorization with Sparseness and Smoothness Constraints. IEICE Transactions on Fundamentals of Electronics... | 5,321,356 |
def _complete_sum(dnf):
"""
Recursive complete_sum function implementation.
CS(f) = ABS([x1 | CS(0, x2, ..., xn)] & [~x1 | CS(1, x2, ..., xn)])
"""
if dnf.depth <= 1:
return dnf
else:
v = dnf.splitvar
fv0, fv1 = dnf.cofactors(v)
f = And(Or(v, _complete_sum(fv0)),... | 5,321,357 |
def invert_dict(d):
"""Invert dict d[k]=v to be p[v]=[k1,k2,...kn]"""
p = {}
for k, v in d.items():
try:
p[v].append(k)
except KeyError:
p[v] = [k]
return p | 5,321,358 |
def daten_einlesen(request):
""" wird von url aufgerufen und ruft standalone-Fkt auf """
aus_alter_db_einlesen()
return HttpResponseRedirect('/veranstaltungen') | 5,321,359 |
def _get_filtered_object_queryset(filter_params_raw, user_id=None, object_type='CITATION'):
"""
Parameters
----------
params : str
Returns
-------
:class:`.QuerySet`
"""
# We need a mutable QueryDict.
filter_params = QueryDict(filter_params_raw, mutable=True)
if object_ty... | 5,321,360 |
def _salfun(rt,dt):
"""Calculate salinity from conductivity and temperature variables.
Calculate the salinity in the Practical Salinity Scale 1978 (PSS-78)
from auxiliary variables related to conductivity and temperature.
:arg float rt: Square root of the conductivity ratio, unitless.
:arg... | 5,321,361 |
def Es_case_B(x, y, z, gamma):
"""
Eq.(9) from Ref[1] with no constant factor e*beta**2/rho**2.
Note that 'x' here corresponds to 'chi = x/rho',
and 'z' here corresponds to 'xi = z/2/rho' in the paper.
"""
if z == 0 and x == 0 and y == 0:
return 0
beta2 = 1-1/gamma**2
b... | 5,321,362 |
def rmse(img_true, img_test):
"""Returns Root Mean-Squared Error score between two Numpy arrays
Args:
img_true: Image, numpy array of any dimension
img_test: Image, numpy array of any dimension
Returns:
Computed RMSE score
Raises:
NumpyShapeComparisonException: if shap... | 5,321,363 |
def enhance_color(img, r=None, severity=1):
"""
adjust the colour balance of an image, in
a manner similar to the controls on a colour TV set. An enhancement
factor of 0.0 gives a black and white image. A factor of 1.0 gives
the original image.
"""
if r is None:
severity = abs(severi... | 5,321,364 |
def test_try_resume_from_non_existing_checkpoint(tmpdir):
"""Test that trying to resume from non-existing `resume_from_checkpoint` fails with an error."""
model = BoringModel()
trainer = Trainer(resume_from_checkpoint=str(tmpdir / "non_existing.ckpt"))
with pytest.raises(FileNotFoundError, match="Abort... | 5,321,365 |
def test_changed_variable_type(sdk_client_fs: ADCMClient):
"""Change config variable type for upgrade
:param sdk_client_fs:
:return:
"""
with allure.step('Create upgradable hostprovider with change variable type'):
bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, 'hostprovider')... | 5,321,366 |
def states(*state_names, **state_configs):
""" returns a dictionary with state names as keys and state configs as values """
if not all(isinstance(s, str) for s in state_names):
raise MachineError(f"all state names in 'states' should be of type 'str'")
if not all(isinstance(s, dict) for s in state_c... | 5,321,367 |
def delayed_notify(reminder):
"""Register an at job that generates a notification."""
os_notify = {
'Linux': _delayed_notify_nix,
'Darwin': _delayed_notify_mac
}[platform.system()]
os_notify(reminder) | 5,321,368 |
def find_best_matching_haplotypes(candidates, truths, ref):
"""Assigns genotypes to each variant to best match truths.
See the module-level documentation for general information on how this
algorithm works.
Args:
candidates: list[nucleus.protos.Variant]. A list of candidate variants, in
coordinate-s... | 5,321,369 |
def _documents_for(locale, topics=None, products=None):
"""Returns a list of articles that apply to passed in topics and products.
"""
# First try to get the results from the cache
documents = cache.get(_documents_for_cache_key(locale, topics, products))
if documents:
statsd.incr('wiki.face... | 5,321,370 |
def handle(pattern :str):
"""
Used as a descriptor.
"""
def wrapper(func):
set_handle_func(pattern, func)
return func
return wrapper | 5,321,371 |
def test_custom_provider(monkeypatch):
"""Tests that a custom provider can be passed when creating an IBMQ
device."""
mock_provider = "MockProvider"
mock_qiskit_device = MockQiskitDeviceInit()
with monkeypatch.context() as m:
m.setattr(ibmq.QiskitDevice, "__init__", mock_qiskit_device.mocke... | 5,321,372 |
def caterpillar_plot(
hddm_model=None,
ground_truth_parameter_dict=None,
drop_sd=True,
keep_key=None,
figsize=(10, 10),
columns=3,
save=False,
path=None,
format="png",
y_tick_size=10,
):
"""An alternative posterior predictive plot. Works for all models listed in hddm (e.g. '... | 5,321,373 |
def setup_device(device):
"""
Performs initialisation on the device.
"""
try:
# Gets around "Resource busy" errors
device.detach_kernel_driver(0)
except Exception:
pass
device.set_configuration() | 5,321,374 |
def validate_name_correctness(name):
"""Validate name does not contains invalid values"""
name_to_validate = name.strip().lower()
names_includes = ["*"]
for invalid in names_includes:
if invalid in name_to_validate:
raise ValueError(u"Name contains unsupported symbol '{}'"
.for... | 5,321,375 |
def scan_local_network(ip):
"""
Scan local network.
Args:
ip (str): Destintaion IP
"""
arp_layer = sc.ARP(pdst=ip)
ether_layer = sc.Ether(dst='ff:ff:ff:ff:ff:ff')
arp_request = ether_layer / arp_layer
answered, _ = sc.srp(arp_request, timeout=10)
if answered:
print... | 5,321,376 |
def tearing_jh_task(det_name):
"""JH version of single sensor execution of the tearing task."""
import siteUtils
from bot_eo_analyses import glob_pattern, bias_filename, tearing_task
run = siteUtils.getRunNumber()
acq_jobname = siteUtils.getProcessName('BOT_acq')
flat_files = siteUtils.depende... | 5,321,377 |
def _ToolBar_InsertLabelTool(self, pos, id, label, bitmap, bmpDisabled=wx.NullBitmap, kind=wx.ITEM_NORMAL, shortHelp="", longHelp="", clientData=None):
"""
Old style method to insert a tool in the toolbar.
"""
return self.InsertTool(pos, id, label, bitmap, bmpDisabled, kind,
s... | 5,321,378 |
def getExtExp(ho_ex_data, ho_ex_date, save_path, LENGTH):
"""
根据pro_ext_cls()函数的输出,获取类别和对应的一组平均map
"""
all_date = np.load('./BikeNYC/MinMax/normal_date.npy', allow_pickle=True)[0]
all_data = np.load('./BikeNYC/MinMax/normal_data.npy', allow_pickle=True)[0]
test_date_array = np.load('./BikeNY... | 5,321,379 |
def forward(request):
"""Forward email."""
mbox, mailid = get_mail_info(request)
if request.method == "POST":
url = "?action=forward&mbox=%s&mailid=%s" % (mbox, mailid)
form = ForwardMailForm(request.user, request.POST)
status, resp = send_mail(request, form, url)
if status:
... | 5,321,380 |
def _do_delete(del_url, api_name):
"""Helper to do HTTP DELETE.
Note: A response code of 404(NOT_FOUND) is treated as success to keep
_do_delete() idempotent.
"""
is_success = True
try:
r = requests.delete(del_url, timeout=_REQUEST_TIMEOUT_SECS)
if r.status_code == requests.codes.not_found:
p... | 5,321,381 |
def bool2str(value):
# type: (Any) -> str
"""
Converts :paramref:`value` to explicit ``"true"`` or ``"false"`` :class:`str` with permissive variants comparison
that can represent common falsy or truthy values.
"""
return "true" if str(value).lower() in truthy else "false" | 5,321,382 |
def relu(x):
"""Rectified linear activation function.
@param x: input matrix/vector.
@return: elementwise relu"""
return np.maximum(x,0) | 5,321,383 |
def _upper(string):
"""Custom upper string function.
Examples:
foo_bar -> FooBar
"""
return string.title().replace("_", "") | 5,321,384 |
def main():
"""Run all self-tests, raising an exception if any of them fail."""
render_pictures_test.main()
skimage_self_test.main() | 5,321,385 |
async def test_interview_events(multisensor_6):
"""Test Node interview events."""
node = multisensor_6
assert node.interview_stage is None
assert node.ready
assert not node.in_interview
event = Event(
type="interview started",
data={
"source": "node",
"ev... | 5,321,386 |
def downstream_Mn(Mn, gamma=defg._gamma):
"""
Args:
Mn: param gamma: (Default value = defg._gamma)
gamma: (Default value = defg._gamma)
Returns:
"""
return np.sqrt((1.+.5*(gamma-1.)*Mn**2)/(gamma*Mn**2-.5*(gamma-1.))) | 5,321,387 |
def log_string_dimension(string, name='Arial', size=14, logw=logger.debug):
"""Log width, height of string in font name / size."""
from tkinter.font import Font
tkfont = Font(family=name, size=size)
logw(f"(width, height) of '{string}': "
f"{(tkfont.measure(string), tkfont.metrics('linespace'))}... | 5,321,388 |
def detect_type(indicator):
"""Infer the type of the indicator.
Args:
indicator(str): The indicator whose type we want to check.
Returns:
str. The type of the indicator.
"""
if re.match(ipv4cidrRegex, indicator):
return FeedIndicatorType.CIDR
if re.match(ipv6cidrRegex, i... | 5,321,389 |
def plot_trajectories(trajectories, problem, get_weights, set_weights):
"""Plot optimization trajectories on top of a contour plot.
Parameters:
trajectories (List(nn.Module))
problem (dict)
get_weights (Callable[[], Tuple[float, float]])
set_weights (Callable[[float, float], Non... | 5,321,390 |
def escape_sql_string(string: str) -> str:
"""
Escapes single quotes and backslashes with a backslash and wraps everything between single quotes.
"""
escaped_identifier = re.sub(r"(['\\])", r"\\\1", string)
return f"'{escaped_identifier}'" | 5,321,391 |
def _round_to_base(x, base=5):
"""Round to nearest multiple of `base`."""
return int(base * round(float(x) / base)) | 5,321,392 |
def input_thread(input_list):
"""Thread that waits for an input."""
input()
input_list.append(True)
print(colored("Interrupting. Please wait.", 'green')) | 5,321,393 |
def cards_search():
"""Return a dummy cards list."""
head = {'Content-Type': 'application/json; charset=utf-8',}
return (resp['cards_search'], head) | 5,321,394 |
def mysqlpdo(editor):
"""Copies PHP code to connect to the active MySQL connection using PDO, to the clipboard.
"""
# Values depend on the active connection type
if editor.connection:
conn = editor.connection
if conn.driver.name == "MysqlNativeSocket":
params = {
... | 5,321,395 |
def get_player_stats(username: str, **kwargs) -> ChessDotComResponse:
"""
:param username: username of the player.
:returns: ``ChessDotComResponse`` object containing information about the
plyers's ratings, win/loss, and other stats.
"""
return Resource(
uri = f"/player/{user... | 5,321,396 |
def build(
subps: _SubParsersAction, parents: Optional[List[ArgumentParser]] = None
) -> None:
"""Return a command-line parser for the download subcommand.
:param subps: ArgumentParser.subparser
:param parents: additional Parser objects
The download subcommand takes specific arguments:
-t, ... | 5,321,397 |
def perspective(image, src, dst, w, h):
"""
Image percpective transform function.
:param image: input image
:param src: original image corners points array
:param dst: output image corners points array
:param w: image width
:param h: image height
:return: result image
""... | 5,321,398 |
def test_create_codeableconcept_term(engine):
""" """
context = SearchContext(engine, "Task")
params = (
("code", "http://acme.org/conditions/codes|ha125"),
("code", "http://terminology.hl7.org/CodeSystem/task-performer-type|"),
("code", "|performer"),
("code:text", "Performe... | 5,321,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.