content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def stepinto():
"""
wrapper for stepDebugee, instruction into.
"""
return stepDebugee(True) | 25c94c8ed45518b1667cb303aa633a74f44cf698 | 3,619,700 |
def einsum_matmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.B where
the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
M <= N, and identity matrices are impl... | b5fb2fed515070172d7f6279d3ff5e3dbcc7db84 | 3,619,701 |
def place_review(request, place_id):
"""Create a place review for specified place.
Args:
request: auto-generated by django.
place_id: place identity defined by Google.
POST payloads:
review: review text for this user.
"""
if request.method != 'POST':
return HttpResp... | 1c882fce7a0e0ee375d358495a36d535ee754950 | 3,619,702 |
import logging
import traceback
import os
def eval_classif_cross_val_scores(clf_name, classif, features, labels,
cross_val=10, path_out=None,
scorings=METRIC_SCORING):
""" compute statistic on cross-validation schema
http://scikit-learn.org/... | 34716b39b118b15f1688650abac5b78cdfb83668 | 3,619,703 |
def part_2_min(guess, list_):
"""finds the position at which minimum fuel is used and returns the fuel amount"""
fuel_for_guess = part_2_fuel(guess, list_)
fuel_guess_up = part_2_fuel(guess + 1, list_)
fuel_guess_down = part_2_fuel(guess - 1, list_)
if (fuel_for_guess < fuel_guess_down) and (fuel_f... | 4ddec4ba164241491ad23494228b6f5c164c854a | 3,619,704 |
def fits2dict(fits_file,ext,par_list):
"""
'Converts' a FITS file to a Python dictionary, with a list of the original
FITS table's columns, of the user's choosing. Can use this for ANY FITS file,
but is meant for mkf/orb files in $OBSID_pipe folders from NICER, or event files
(be it from NICER-data ... | 99c0ce799aa92129fa598501d8b96e8369a5e8ee | 3,619,705 |
import os
def get_matplotlib_data():
""" Return 'mpl-data' folder name for matplotlib.
"""
mpl_data = os.path.join(
os.path.dirname(get_module_file_attribute("matplotlib")), "mpl-data"
)
if not os.path.isdir(mpl_data):
return None
suffix_start = mpl_data.find("matplotlib")
... | 26648864b9bdde8749fba3f0313c5c9aad68dd90 | 3,619,706 |
def vector_from_skew_matrix(skew_mat):
"""
Compute the skew-symmetric matrix,
known as the cross-product of a vector,
associated to the vector vec.
:param skew_mat: 3x3 skew-symmetric matrix
:return vec: 3d vector
"""
skew_mat = vectorization.expand_dims(skew_mat, to_ndim=3)
n_skew_... | 516e2ecf400af46c507d0b34830b3307b08fbbda | 3,619,707 |
import logging
import sys
def create_logger(level=logging.DEBUG):
"""Create a logger that emits JSON to stdout"""
logger = logging.getLogger()
logger.setLevel(level)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JSONFormatter())
logger.addHandler(handler)
# Add info_wi... | 40818748810d0e1eef3791c727379b4cf67e1b2f | 3,619,708 |
def mutelist(request):
"""
Edit mutelist entries
"""
mutelist = MuteList.objects.filter(user=request.user)
return _template_values(request,
page_title="edit mute list",
header="mutelist",
navbar='nav_account',
... | a8487cbfe8823b5e2266e3b4d8ca5bf166e2fbc9 | 3,619,709 |
def gen_path(base, code):
"""
Generate a path for give base path and code used in data generation
"""
#return os.path.join(base, code[:2], code[:3])
return base | e05790a740b7ab0f83ba5db020598c20d0f89520 | 3,619,710 |
def script_to_bech32(script: bytes, witver: int) -> str:
"""https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program"""
witprog = sha256(script)
return bech32.encode(network('hrp'), witver, witprog) | 1eea5867b8efa2709f78ab77127ca2f3c0d4865e | 3,619,711 |
import torch
def compute_ssim(
img0,
img1,
max_val=1.0,
filter_size=11,
filter_sigma=1.5,
k1=0.01,
k2=0.03,
return_map=False,
):
"""Computes SSIM from two images.
This function was modeled after tf.image.ssim, and should produce comparable
output.
Args:
img0: to... | 251fe5a1a0df9f06bc7d8b820d24486077489e9e | 3,619,712 |
from typing import List
from typing import Set
def sample_unique_molecules(model: DistributionMatchingGenerator, number_molecules: int, max_tries=10) -> List[str]:
"""
Sample from the given generator until the desired number of unique (distinct) molecules
has been sampled (i.e., ignore duplicate molecules... | 1d8e8aaa9f7b25fcb801e6b95ee8f1e33510f119 | 3,619,713 |
import numbers
import json
import base64
def encode(d):
"""Encode an object in a way that can be transported via Mesos attributes: first to
JSON, then to base64url. The JSON string is padded with spaces so that the base64
string has no = pad characters, which are outside the legal set for Mesos.
"""
... | b1018b9eba2f136f9281dcb936d0903290abd505 | 3,619,714 |
def get_detected_head(np_img_set, cascades):
"""Detects a head and returns HeadData depending on input.
Head data is scaled normalized, x, y, and radius go from 0 to 1.
depth is same as raw data"""
potential_boxes = _run_cascades(np_img_set.ir, cascades)
if(len(potential_boxes) == 0):
retu... | a3f1d10b20724db5816a10e587ee13c4a95af13a | 3,619,715 |
def create_csv(file_path):
"""
This function will create an index file with image paths and labels in csv format
obtained csv will have two columns path(path to acess the image),label(class of the image)
"""
images=[]
labels=[]
label_file=pd.DataFrame(columns=['path','label'],index=None)
... | 42582c2d4de22998674c3a4323b909100b358080 | 3,619,716 |
from sklearn.neighbors import KDTree
def knn_cond_mutual_information(x, y, z, k, standardize = True, dualtree = True):
"""
Computes conditional mutual information between two time series x and y
conditioned on a third z (which can be multi-dimensional) as
I(x; y | z) = sum( p(x,y,z) * log( p(z)*p... | c3f384d95b8345ca63bcfea3de06348fd9084814 | 3,619,717 |
import os
def get_downloader(start_date, end_date, every_min_bar):
"""returns a downloader closure for iex cloud
:param start_date: the first day on which dat are downloaded
:param end_date: the last day on which data are downloaded
:type start_date: str in format YYYY-MM-DD
:type end_date: str in... | 977f7eecd8e8edf534eacff58dbd41545c8e5d2f | 3,619,718 |
def kv_kernel(v1, v2, c=3):
""" Updated vertex kernel that multiples the dirac on the node
labels and a brownian bridge on the node attributes """
if isinstance(v1, int):
""" If just an integer, then no attr """
k_dirac = dirac(v1, v2)
k_brownian_bridge = 1
elif isinstance(v1, l... | b09bd5e14f1c07d51da96ac1928b0e44aa6c6a87 | 3,619,719 |
def update_contact(account_id=None, id=None, attributes=None, cursor=None):
"""
Update one contacts entry at database identified by Account ID and ID
:param account_id:
:param id:
:return: Particular dict
"""
if account_id is None:
raise AttributeError("Provide account_id as paramete... | eba802018fe162b929cb5cc7c004a0a2b923c6f5 | 3,619,720 |
from typing import Any
from typing import Dict
def validate_reserved_alias(_netid: str, client: ShrunkClient, alias: str) -> Any:
"""``GET /api/validate_reserved_alias/<b32:alias>``
Validate an alias. This endpoint is used for form validation in the frontend. Response format:
.. code-block:: json
... | 5cce18b6ada5f836b4a1d46deb09fa15c060f372 | 3,619,721 |
def _kl_normal_gp(n, gp, name=None):
"""Calculate the batched KL divergence KL(gp || n).
Args:
n: instance of a Normal distribution object.
gp: instance of a GaussianProcess distribution object.
name: (optional) Name to use for created operations.
default is 'kl_normal_gp'.
Returns:
Batchw... | eeb02f4a095601c6120693e2dd3c2b6d8ad21c1f | 3,619,722 |
def mahalanobis(u, v, VI):
"""
:purpose:
Computes the Mahalanobis distance between two 1D arrays
:params:
u, v : input arrays, both of shape (n,)
VI : the inverse of the covariance matrix of u and v
note that some arrays will result in a VI containing
very high v... | 6a26d889e838a8efb4bcab5a1e4f9b124746d94d | 3,619,723 |
def filter_tests(all_tests, arguments):
""" Will figure out which tests are to be run
Arguments:
all_tests (list of Test obj): all processed test objects
arguments (argument object): Contains arguments from argparse
returns:
list: All Test objects that are to be run
"""
pri... | 8c5da7061c29a1308aa8c075af42508a6fd55381 | 3,619,724 |
from typing import List
from typing import Tuple
def create_lidarbeam_arr(
sensor_pos: List[float],
sensor_heading: float,
max_range: float,
n_beams: int,
n_pts: int = 600,
resolution: float = None,
) -> Tuple[np.ndarray]:
"""Create all lidar beam points in the WORLD FRAME
:param sens... | 6cec1babce23c6362231c764f5484ce1e6289068 | 3,619,725 |
def is_user_blacklisted(user_id: int) -> bool:
"""
CHECK IF A USER IS BLACKLISTED
"""
return bool(
c.execute(
"""
SELECT blacklisted
FROM users
WHERE user_id=?
""",
(user_id,),
).fetchone()[0]
) | 76eb70ed968a46c2fb43e7dfa40233d0e67a6f39 | 3,619,726 |
def return_pitch_bend_tuple_dict(
tet, origin=0, size_of_semitone=SIZE_OF_SEMITONE
):
"""Returns a dictionary of form
(pitch_number: (12-tet midinum, pitch_bend))
Keyword args:
- origin: the 12 - tet pitch class from which the relevant pitches
will be calculated. (Should pro... | de1a8905a538d9b8e692d29d07e964932f37853d | 3,619,727 |
def third_function(x):
"""Third benchmark function.
Args:
x (int, float): Input.
Returns:
float: Output. :math:`sin(πx)`
"""
return x * np.sin(np.pi * x) | 2a19a139e6300175dacfd8551c6371c284855375 | 3,619,728 |
from typing import Counter
import math
def corpus_bleu(list_of_references, hypotheses, weights=(0.25, 0.25, 0.25, 0.25),
smoothing_function=None):
"""
:param references: a corpus of lists of reference sentences, w.r.t. hypotheses
:type references: list(list(list(str)))
:param hypothese... | 5b6c3100720d5a8d7402962df91ffd3d9a03e234 | 3,619,729 |
import requests
def fetch_project(name):
"""Return the loaded JSON data from PyPI for a project."""
url = 'https://pypi.python.org/pypi/{}/json'.format(name)
r = requests.get(url)
try:
return r.json()
except ValueError:
# has to *return* an error instead of raising one,
# c... | 135b3a018a8e430dc8722ae93caa3771da9e328b | 3,619,730 |
from typing import Union
from typing import Tuple
def SQuAD1(root: str, split: Union[Tuple[str], str]):
"""SQuAD1 Dataset
For additional details refer to https://rajpurkar.github.io/SQuAD-explorer/
Number of lines per split:
- train: 87599
- dev: 10570
Args:
root: Directory ... | 45ff73572df84063956854ca434bbe005d7db812 | 3,619,731 |
def a2str(a):
"""
formatting for 1 or 2 dimensional numpy arrays of booleans
"""
if len(a.shape) == 1:
return "".join(map(str, a))
elif len(a.shape) == 2:
return "\n".join(map(lambda row: "".join(map(str, row)), a)) | 589cbc72bc1c3379f74a924f14b304d91a517157 | 3,619,732 |
def find_PFd(A, B, Q, R, beta=.95):
"""
Taking the parameters A, B, Q, R as found in the `setup_matrices`,
we find the value function of the optimal linear regulator problem.
This is steps 2 and 3 in the lecture notes.
Parameters
----------
(A, B, Q, R) : Array(Float, ndim=2)
The ma... | 30c4085ba99eac914f718495589e37dace74e639 | 3,619,733 |
def _should_save_cookies(request):
""" Return True if cookies should be saved for a request """
# based on QNetworkReplyImplPrivate::metaDataChanged() C++ code
attr = request.attribute(
QNetworkRequest.CookieSaveControlAttribute,
QNetworkRequest.Automatic
)
return attr == QNetworkReq... | 3b24f363e8dfecf227eb16c8fdbf3138938be800 | 3,619,734 |
import json
def generate(data_path, registry):
"""generates templates based on arguments and configurations."""
if not current_folder_has_venv():
logger.warning(Text.no_virtual_environment_remainder)
with open(data_path / "category_tree.json", encoding="UTF-8") as file:
full_tree = json.... | 6d630513c317869603d23110f72839cd68975ffd | 3,619,735 |
from typing import Iterable
from typing import Optional
from sys import version
def get_latest_compatibility_result_by_version(
compatibility_results: Iterable[Optional[CompatibilityResult]]
) -> Optional[CompatibilityResult]:
"""Return the CompatibilityResult with the highest version number.
... | f050bead7a1df09c213f3627cde35b6ad6032c11 | 3,619,736 |
import signal
def get_maxima( series, N, start_date = None, stop_date = None, _sorted = True ) :
"""
Summary:
Function that determines the first N maxima of a pandas time series
Arguments:
series - pandas series
N - number of maxima
start_date - start date as DateT... | 7f006c3ce795b8ad46f2a30d718fbab51cfd7515 | 3,619,737 |
def ALMASplit(uv, target, err, FQid=1, outClass=" ", logfile = "", \
check=False, debug = False):
"""
Write calibrated data
Returns task error code, 0=OK, else failed
* uv = UV data object to clear
* target = Target source name source name or list of names
* ... | 716691629c4bac596a7831c397fb0da4dc7d9178 | 3,619,738 |
def get_latest_challenge_from_player_id(player, should_be_completed=False):
"""
Tries to find the latest challenge belonging to a player
param int player: The player ID to search the challenges for
param bool should_be_completed: If the challenge should already be completed or not
returns os3_rll.m... | 9408cde081714d3994dbc9286ca699354a5f3bd1 | 3,619,739 |
import torch
def runepisode(env, policy, episodesteps, render, windowlength=4):
"""Runs an episode under the given policy
Returns the episode history: an array of tuples in the form
(observation, processed observation, logprobabilities, action, reward, terminal)
"""
observation = env.reset()
... | ef50ac2b2afd6912d27930ae7b5a1101f3d31776 | 3,619,740 |
def lookup_linear_velocity(
frame,
reference=None,
represent_in=None,
outlier_thresh=None,
cutoff=None,
as_dataarray=False,
return_timestamps=False,
):
""" Estimate linear velocity of a frame wrt a reference.
Parameters
----------
frame: str or ReferenceFrame
The ref... | fb6ab94b4f5dea3a96e08bfc854bacaa3b14a34f | 3,619,741 |
def dispatch_slug_path(*views):
"""
Dispatch full path slug in iterating through a set of views.
Http404 exceptions raised by a view lead to trying the next view
in the list.
This allows to plug different slug systems to the same root URL.
Usages::
# in urls.py
path('<slug:slu... | 570402f4461aaf033bc8abafedbaae15c2ef7efd | 3,619,742 |
def applyFxToVolumes( ts, vols, fx, **kwargs ):
""" Apply a function on selected volumes of a timeseries.
'ts' is a 4d timeseries. It can be a NiftiImage or a ndarray.
In case of a ndarray one has to make sure that the time is on the
first axis. 'ts' can actually be of any dimensionality, but datasets ... | 32b24975292f228a28584f146023e051a5da4453 | 3,619,743 |
def getTrack ( tleFile, t_beg, t_end, dt_secs=60):
"""
Given a Two Line Element (TLE) file name, a time interval, returns
tuple with (lon,lat) coordinates of satellite ground track.
"""
dt = t_end-t_beg
n = 1 + int(dt.total_seconds() / dt_secs)
Dt = timedelta(seconds=dt_secs)
nymd =... | 26f82a409f9f01cc738b93b98b1affc6843332a3 | 3,619,744 |
def __read_dataset_item(path):
"""Reads data set from path returns a movie dict.
Parameters
----------
path : str
Absolute path of the MovieLens data set(u.data).
Returns
-------
rating_dict : dict
Returns a dict of users, movies and ratings.... | a87baecc5b0c28675bc715aab646bf41e4b40f96 | 3,619,745 |
import logging
import time
def wait_for_new_checkpoint(checkpoint_dir,
last_checkpoint=None,
seconds_to_sleep=1,
timeout=None):
"""Waits until a new checkpoint file is found.
Args:
checkpoint_dir: The directory in which check... | ee355f2e55cc8a714c6d4e523615b2508589f1df | 3,619,746 |
from scipy.stats import beta as beta_d
import matplotlib.pyplot as plt
def _beta_prior(k, n, r, a0=1, b0=1, plot=False):
"""Compute the posterior distribution of d given the input aggregates
Since the likelihood is given by a binomial distribution, its conjugate prior is a beta distribution.
However, the ... | 8961e7d39b42227a60e23284d9fbbdfb77d0c553 | 3,619,747 |
def get_data(data_fn, param):
"""Feed data_fn with param
"""
return data_fn(**merge_dicts(param["data"], param.get("shared", {}))) | 605e29d8e45967f3d938dd094c233d5b36ae6aa9 | 3,619,748 |
def get_heat_flow_3(matrix_temp: np.ndarray, param: Parameters) -> float:
"""
各部温度から断熱材+内装材伝導熱量を計算する
:param matrix_temp: 各部温度計算結果 (5,1), degC
:param param: 計算条件パラメータ群
:return: 断熱材+内装材伝導熱量, W/m2
"""
return param.C_2 * (matrix_temp[2] - matrix_temp[3]) | 9af08c218351d51bec890635abcce301cd83b8f1 | 3,619,749 |
def create_training_label(center, size, corners, resolution=0.50, scale=4,
x=(0, 90), y=(-50, 50), z=(-4.5, 5.5)):
"""Create training labels which satisfy the range of experiment"""
min_value = np.array([x[0], y[0], z[0]])
xyz_logical = judge_in_voxel_area(center, x, y, z)
center[:, 2] ... | be6139bc4b5665194afc890fcce474d3d13ce872 | 3,619,750 |
import urllib
import re
def proxy_list_from_free_proxy_list_net():
"""
will connect to https://free-proxy-list.net/
and will get the proxy list from that page
proxy format : ip address, port
"""
link = 'https://free-proxy-list.net/'
regex = '<td>(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})<... | 6f8721331024a85f5e406e36557ffdddacd7654d | 3,619,751 |
def adv_training(sess, inputs, labels):
"""Train and evaluates a model on adversarial examples
"""
adversarial_model = get_model(FLAGS.model_type, 'train_adv')
fgsm2 = FastGradientMethod(adversarial_model, sess=sess)
def attack(inputs):
return fgsm2.generate(inputs, **ADV_CONSTANTS.get_attack_details(FLA... | 088595fe5a7ab681f25ea7149017eba4555353cd | 3,619,752 |
def unifiable(cls):
""" Register standard unify and reify operations on class
This uses the type and __dict__ or __slots__ attributes to define the
nature of the term
See Also:
>>> class A(object):
... def __init__(self, a, b):
... self.a = a
... self.b = b
>>> un... | 48e4cbc5373dc445923e47c8c8f65e99a035b338 | 3,619,753 |
def kMeansInitCentroids(X, k):
"""
初始化 cluster centroids
:param X:
:param k:
:return:
"""
m = X.shape[0]
centroids = np.zeros((k, X.shape[1]))
m_arr = np.arange(0, m)
np.random.shuffle(m_arr)
rand_indices = m_arr[:k]
centroids = X[rand_indices, :]
return centroids | d6aa56fb1157ff9bdc2cf82bb7864b08ef471dc1 | 3,619,754 |
from typing import AnyStr
from typing import List
from typing import Dict
def get_metric_rating_max(metric: AnyStr,
start: AnyStr,
end: AnyStr,
tenant_id: AnyStr,
namespaces: List[AnyStr]) -> List[Dict]:
"""
... | 33971a0f846a0bcb40b0acf16b32fc62a5bfefb1 | 3,619,755 |
def generate_binary_random_number(size=1):
"""Generates a binary random number or array based on an uniform distribution.
Args:
size (int): Size of array.
Returns:
A binary random number or array.
"""
binary_array = np.round(np.random.uniform(0, 1, size))
return binary_array | 3833115e82b87a9773f53046d6dc6114febdc56f | 3,619,756 |
def make_class(any, base=data.module.YO, *args, **kwargs):
"""check base is correctly resolved to Concrete0"""
class Aaaa(base):
"""dynamic class"""
return Aaaa | d0729d5f50e656a2fd76eda02d7d07ebd4682162 | 3,619,757 |
from typing import Optional
def make_nbh_test(station: str) -> Optional[dict]:
"""Builds NBH test file for station"""
return make_forecast_test(avwx.Nbh, station) | 761db3a8587e852dd9048eb3dd12cc64ecd7e8c1 | 3,619,758 |
def get_manifest_indexes(manifest, channel, column):
"""Get the indices for channel and column in the manifest"""
channel_index = -1
for x in range(len(manifest["channels"])):
if manifest["channels"][x]["channel"] == channel:
channel_index = x
break
if channel_index == -1... | 63d82417b1e106d408866933bce776c272b2e77d | 3,619,759 |
from typing import List
def get_function_call(fn_to_call: ts.FunctionType, argument_names: List[str], fc: context.FunctionContext):
"""
DOES NOT COPY stack symbolic registers!
argument_names should be located in stack symbolic registers [argument_names]
RETURNS a stack symbolic register which th... | dace1b83478e8750518878ac0be77fb24393ef0f | 3,619,760 |
import re
def get_connection_ip_list(as_wmi_format=False, server=_DEFAULT_SERVER):
"""
Get the IPGrant list for the SMTP virtual server.
:param bool as_wmi_format: Returns the connection IPs as a list in the format WMI expects.
:param str server: The SMTP server name.
:return: A dictionary of th... | cef5272e0cdb348c6320ee209bb77a4d4c0fef7f | 3,619,761 |
def parse_training_args(args=None, ignore_unknown=False):
"""parser for training script"""
arg_populate_funcs = [training_args, custom_mlp_args]
arg_check_funcs = [process_training_args]
return parse_various_args(
args, arg_populate_funcs, arg_check_funcs, ignore_unknown
) | 93fdd653199873c9cb32b5f6b7f63ae22a21f057 | 3,619,762 |
import torch
def query_ball_point(radius, nsample, xyz, new_xyz):
"""
Input:
radius: local region radius
nsample: max sample number in local region
xyz: all points, [B, N, 3]
new_xyz: query points, [B, S, 3]
Return:
group_idx: grouped points index, [B, S, nsample]
... | e74992747103d11b6618ecf7daf035c4f83e9911 | 3,619,763 |
import math
def get_num_blocks(content_length, block_size=DEFAULT_BLOCK_SIZE):
"""
Split file of specified length into blocks
"""
return int(math.ceil(content_length / block_size)) | e39f20c48f4dbd4f4baaf150bd35122b49ad5b30 | 3,619,764 |
def is_bounded(coord, shape):
"""
Checks if a coord (x,y) is within bounds.
"""
x, y = coord
g, h = shape
lesser = x < 0 or y < 0
greater = x >= g or y >= h
if lesser or greater:
return False
return True | 0a0b6921fcdf285c89b5021d113585ff38255013 | 3,619,765 |
def analyze_centroid_area_history(files, num_frames_per_iteration=1800, key_format="from_to"):
"""
Given an array of file names,
get centroid area history iteratively over 30 mins of frames.
Args:
files ([type]): [description]
num_frames (int, optional): [description]. Defaults to 1800... | 69013ec6a9c5c802923d65fbe4294e1290331cfb | 3,619,766 |
def perp2coast(X1,X2,Y1,Y2,X0=0,Y0=0,hip=10000,deltahip=1000,units='m',side=1):
"""
INPUT:
X1: Initial point in X for compute slope
X2: Final point in X for compute slope
Y1: Initial point in Y for compute slope
Y2: Final point in Y for compute slope
X0: Point to colocate the slope in X
... | 9836150c3aa3d2c5cae9aec62d47401cbd542d02 | 3,619,767 |
def conv2d(input_, W_shape, name, reuse=False):
"""
name - layer name for variable scope W_shape - [height, width, input_layers, output_layers]
"""
# 在名称空间name下添加变量Variable,但最好传递一个reuse参数。
with tf.variable_scope(name, reuse=reuse):
# 对convolution层的权值参数 W 和 b 进行初始化
W_conv = tf.get_var... | e4ac8a798a49ed9ffc14f83b44704119f5f7f0fb | 3,619,768 |
import re
import requests
from bs4 import BeautifulSoup
import time
def get_one_postalcode(ps='00100', onSale=True):
"""
Perform the query on one postal code.
QUERY TESTED: 13.11.2019
:param ps: the postal code to query.
:param onSale: bool, if true do the query sales, if false do the query on ren... | fb0b070121878b5bf5304b9e1712e87e8195a771 | 3,619,769 |
def CV_ARE_SIZES_EQ(*args):
"""CV_ARE_SIZES_EQ(CvMat mat1, CvMat mat2) -> int"""
return _cv.CV_ARE_SIZES_EQ(*args) | b559f7e849c36b9f1683d8c0a2562aa5640a6b21 | 3,619,770 |
def sph2car(theta, phi, radius=1.0):
"""
Transform the spherical coordinate to cartesian 3D point.
:param theta: longitude
:type theta: numpy
:param phi: latitude
:type phi: numpy
:param radius: the radius of projection sphere
:type radius: float
:return: +x right, +y down, +z is fr... | 1397983ca6ae42280603109ad28f49f41361539c | 3,619,771 |
from re import T
def expand_range_spec(
spec: T.Union[int, str], min_value: int, max_value: int
) -> T.Set[int]:
"""Expands strings of the range specification format to RangingSet
objects containing the individual numbers.
Any whitespace is ignored. If an int is given instead of a string,
a set co... | c6a3c2550126cc4ff8d4553ef1471d0edfb9b3b3 | 3,619,772 |
from typing import Dict
import requests
def get_tasks_by_project_id(workspace_id: str, project_id: str,
api_key_header: Dict) -> Dict:
"""Get tasks associated with a given project ID and workspace ID.
This function returns a dictionary of tasks corresponding to a given
project ID and workspace ID... | 3141b04424c87408e1c155e31c81c8f87a5ee0d1 | 3,619,773 |
import glob
import os
def get_files(datadir, filename, format, size):
"""Get all file (names) with given name, size and format
"""
dir = check_dir(datadir)
pattern = dir + os.sep + filename + '_size=%d*.%s' % (size, format)
return glob.glob(pattern) | e0c3811ca03c2fb1436f331ebaa47cdd6867d474 | 3,619,774 |
def checksum_file(path: str) -> str:
"""
Gets the checksum of a file
Parameters
----------
path : str
The path to checksum
Returns
-------
string
Checksum
"""
message = PrettyStatusPrinter("Getting MD5 hash of " + path).print_start()
result = run_piped_comma... | 0a5747e1094348be042cec165509710661c3be84 | 3,619,775 |
from typing import Optional
def bool_to_int(bool_value: Optional[bool]) -> Optional[int]:
"""Cast bool to int value.
:param bool_value: some bool value
:return: int represenation
"""
if bool_value is None:
return bool_value
return int(bool_value) | fde6cda3dc8909638bb315451a09938224f2f306 | 3,619,776 |
def create_pool2d(pooling_params, ifm_expr):
"""Create a relay pooling operation"""
assert pooling_params.ifm.layout == "NHWC"
params = {
"pool_size": (pooling_params.size[0], pooling_params.size[1]),
"strides": (pooling_params.strides[0], pooling_params.strides[1]),
"padding": [0, 0... | 6f163a737993630f7af1264f609a74aee286c4d5 | 3,619,777 |
import socket
def send_msg(msg: bytes) -> bool:
"""Send a msg. Returns True on success, False otherwise"""
succeed = True
try:
# 1 second timeout
sock = socket.create_connection((c.HOSTNAME, c.PORT), timeout=1)
except Exception:
return False
try:
sock.send(msg)
... | b76698cf946b645825272c32771dfac792491840 | 3,619,778 |
def check_dwd_observations_parameter_set(
parameter_set: DWDObservationParameterSet,
resolution: DWDObservationResolution,
period: DWDObservationPeriod,
) -> bool:
"""
Function to check for element (alternative name) and if existing return it
Differs from foldername e.g. air_temperature -> tu
... | edc5b9ab3ae6c10db113e6a01d73467bd3d8ff0e | 3,619,779 |
def pobj_ident(l, r):
"""
Check if value of PObject `l`
is the same Python Object
as value of PObject `r`
"""
return mkbool(r.hasvalue and l.value is r.value) | f8c3d7b1867f9869083a41d211971674ed99f703 | 3,619,780 |
from typing import Any
def arghash(args: Any, kwargs: Any) -> int:
"""Simple argument hash with kwargs sorted."""
sorted_args = tuple(
x if hasattr(x, "__repr__") else x for x in [*args, *sorted(kwargs.items())]
)
return hash(sorted_args) | c3e95c63831c958bb2a52cabad9f2ce576a4fed8 | 3,619,781 |
from typing import Union
from typing import Optional
from typing import Sequence
def visualize_accuracy_grouped_by_probability(y_test: np.ndarray, labeled_class: Union[str, int],
probabilities: np.ndarray,
threshold: float = 0... | e9be1be8e5e650b2808fa31db80cfc9fb61e43bd | 3,619,782 |
import os
import re
def _applyReplacements(cfile, replacements):
"""Applies custom replacements.
Argument cfile is string.
Argument replacements is a list of dicts, with keys "match",
"replacement", and (optional) "is_regex"
"""
for rep in replacements:
if not rep.get('with_extension... | 647e541eee027de21e171be570a2abc60c889cf2 | 3,619,783 |
def run_workflow_stddft(config: DictConfig) -> PromisedObject:
"""Compute the excited states using simplified TDDFT using `config`."""
# Single Point calculations settings using CP2K
mo_paths_hdf5, energy_paths_hdf5 = unpack(calculate_mos(config), 2)
# Read structures
molecules_au = [change_mol_uni... | ac2f3c6f39765d555530329948aa21719436216c | 3,619,784 |
import os
import time
def dosim( inputfile, simname='', perfect=False, simargs='', verbose=False ):
""" Run the snana light curve simulator with the
given .input file """
SNANA_DIR = os.environ['SNANA_DIR']
SNDATA_ROOT = os.environ['SNDATA_ROOT']
simdir = os.path.abspath( os.path.join( SNDATA_RO... | 9c263601d7dd28fffe970f1ea22aa637ba3fe123 | 3,619,785 |
def build_resnet_fpn_gnbn_lowlevel_cbp10_backbone(cfg, input_shape: ShapeSpec):
"""
Args:
cfg: a detectron2 CfgNode
Returns:
backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
"""
bottom_up = build_resnet_gnbn_lowlevel_model_backbone(cfg, input_shape, gra... | 81ee7d331ab17bf47f8e252cfebd7a07045c62c9 | 3,619,786 |
import os
import json
import shutil
def run_batch_test(request):
"""
批量运行用例
:param request:
:return:
"""
kwargs = {
"failfast": False,
}
runner = HttpRunner(**kwargs)
test_case_dir_path = os.path.join(os.getcwd(), "suite")
test_case_dir_path = os.path.join(test_case_d... | a752bbf716668ed89d8d39f6f6bfae2dd949f7a2 | 3,619,787 |
import pickle
def load_db(fname, binp=True, keys=None ):
"""
Submodule to read the station database from file
Parameters
----------
fname : str
File name
binp : bool
Whether or not to use binary input
keys : List
Default None
If a list, then load database a... | 5c83b4c4d69ac7f196acc0803593cca87b484499 | 3,619,788 |
def _get_pcluster_version_from_stack(stack):
"""
Get the version of the stack if tagged.
:param stack: stack object
:return: version or empty string
"""
return next((tag.get("Value") for tag in stack.get("Tags") if tag.get("Key") == "Version"), "") | 86106e52ea6ef8780c8aa8f514e0708dd53fb8e3 | 3,619,789 |
import time
def condor_object(net):
"""Initialization of the condor object. The function gets a network in edgelist format encoded in a pandas dataframe.
Returns a dictionary with an igraph network, names of the targets and regulators, list of edges, modularity, and vertex memberships.
"""
t ... | a5b07ee8f8886baff9ae6b25f335d9c42343b3c0 | 3,619,790 |
import os
import subprocess
def RunNinjaCommand(args, root_dir=None):
"""Runs ninja quietly. Any failure (e.g. clang not found) is
silently discarded, since this is unlikely an error in submitted CL."""
command = [os.path.join(find_depot_tools.DEPOT_TOOLS_PATH, 'ninja')] + args
p = subprocess.Popen(command... | 8d0ed874102f35b5cfc83d8d1a67386f56b80def | 3,619,791 |
import json
def extract(spark, source):
"""Return an RDD[String]."""
rdd = spark.sparkContext.textFile(source)
return rdd.map(lambda x: json.loads(x)) | fef96d6cae65551a6879396ea699acfd2e4cda4b | 3,619,792 |
def _remove_leading_zeroes_in_field(string):
"""If blank-separated fields are integer, remove the leading zero."""
split = string.split(" ")
for i, field in enumerate(split):
if field.isdigit():
split[i] = f"{int(field)}"
return " ".join(split) | 48ba659b25809f19a0c3ed722d6201ffef73c409 | 3,619,793 |
def pstdev(data):
"""Calculates the population standard deviation."""
#: http://stackoverflow.com/a/27758326
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/n # the population variance
return pvar**0.5 | fd67040adf793c5ea4da4125fe007050af40bd1a | 3,619,794 |
def make_sharded_index(index_prefix: str, release_date: Date) -> str:
"""Make a sharded Elasticsearch index given an index prefix and a date.
:param index_prefix: the index prefix.
:param release_date: the date.
:return: the sharded index.
"""
return f'{index_prefix}-{release_date.strftime("%Y... | e9e8fa05efcff9868326d8e453f1379f5b134322 | 3,619,795 |
def optimise_acqu_func_additive(acqu_func, bounds, X_ob, func_gradient=True, gridSize=5000, n_start=1, nsubspace=12):
"""
Optimise acquisition function built on ADDGP model
:param acqu_func: acquisition function
:param bounds: input space bounds
:param X_ob: observed input data
:param func_grad... | c914d6290417cd77643537a848968aa43048524d | 3,619,796 |
def kmp(pattern, text):
"""Knuth-Morris-Pratt substring matching"""
pattern_length = len(pattern)
matched, subpattern = 0, [0] * pattern_length
for i, glyph in enumerate(pattern):
if i:
while matched and (pattern[matched] != glyph):
matched = subpattern[matched - 1]
... | 4f2a30a7a92d2e5890d9c257626c37201b281fec | 3,619,797 |
import os
def collect_files(data_dir, specific_issue_date,csv_importer_impl=CsvImporter):
"""Fetch path and data profile details for each file to upload."""
logger= get_structured_logger('collect_files')
if specific_issue_date:
results = list(csv_importer_impl.find_issue_specific_csv_files(data_dir))
else... | 5662eedd64644304c49d890268602c740339369c | 3,619,798 |
from datetime import datetime
def ssl_valid_time_remaining(hostname):
"""Get the number of days left in a cert's lifetime."""
expires = ssl_expiry_datetime(hostname)
return expires - datetime.datetime.utcnow() | 7820dde512fa505b82875fe4a88cf9e5915212c7 | 3,619,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.