content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def getLanguage(langcode):
"""Returns the full name of the language referred to by its two-letters
language code.
"""
if languages.has_key(langcode):
return languages[langcode]
else:
raise RuntimeError("cannot find language with code " + str(langcode)) | 51,100 |
def get_images(username):
"""
Retrieves image history for given username
:return: resp: (json) All the pathways to the images the user has previously uploaded
"""
resp = []
for image in ImPath.query.filter_by(username=username):
if (is_valid_image_path(image.impath)):
with ... | 51,101 |
def magma_zgeqrf_gpu(m, n, A, ldda, tau, dT):
"""
QR factorization (gpu interface, upper triangular R is inverted).
"""
info = c_int_type()
status = _libmagma.magma_zgeqrf_gpu(m, n, int(A), ldda,
int(tau), int(dT),
ctyp... | 51,102 |
def otf2psf(otf, shape):
"""
Convert optical transfer function (OTF) to point-spread function (PSF).
Compute the Inverse Fast Fourier Transform (ifft) of the OTF array and
creates the PSF array that is not influenced by the OTF off-centering.
By default, the PSF array is the same size as the OTF arr... | 51,103 |
async def table_create_rooms_switches(db: aiosqlite.Connection) -> None:
"""This function creates the rooms_switches table in database"""
query = """CREATE TABLE IF NOT EXISTS rooms_connections (
id integer NOT NULL PRIMARY KEY,
area_name text NOT NULL,
room_number integer NOT NULL,
... | 51,104 |
def inventreeInstanceName():
""" Returns the InstanceName settings for the current database """
return InvenTreeSetting.get_setting("InstanceName", "") | 51,105 |
def get_deposit_addresses(args=None):
"""Get deposit addresses."""
# Parameters to pass to the API
api_params = {
'asset': args.asset,
'method': args.method,
}
if args.new:
api_params['new'] = args.new
res = query_api('private', 'DepositAddresses', api_params, args)
... | 51,106 |
def predict(sentence: str) -> [str]:
"""
Lemmatize a given sentence
:param sentence: sentence to lemmatize
:return: lemmatized sentence
"""
lemmatizer = WordNetLemmatizer()
word_list = nltk.word_tokenize(sentence)
return [lemmatizer.lemmatize(w) for w in word_list] | 51,107 |
def test_conversion_bc_company_from_colin(app, session, legal_type):
"""Assert that an existing bc company(LTD, ULC, CCC) incorporation is loaded corrrectly."""
# setup
identifier = 'BC0000001'
colind_id = 1
filing = copy.deepcopy(CONVERSION_FILING_TEMPLATE)
# Change the template to be LTD, ULC... | 51,108 |
def is_nominal_tolerance_met(data : pd.DataFrame, criteria_nominal : list = [], nominal_tolerance : list = []):
"""
Checks that the tolerances for categorical columns are met. The tolerance is defined as the sum of the maximum frequency deviation
between groups for each categorical column passed in criteri... | 51,109 |
def field(type_hint=None, # type: Union[Type[T], Iterable[Type[T]]]
nonable=GUESS, # type: Union[bool, Type[GUESS]]
check_type=False, # type: bool
default=EMPTY, # type: T
default_factory=None, # type: Callable[[], T]
validators=None, ... | 51,110 |
def test_limit_by_resource_and_method():
""" Test using a custom key_func - one which creates different buckets by resource and method
"""
def get_key(req, resp, resource, params) -> str:
user_key = get_remote_addr(req, resp, resource, params)
return f"{user_key}:{resource.__class__.__name_... | 51,111 |
def test_create_github_helper(gh):
"""Create an instance of github_helper"""
assert gh is not None | 51,112 |
def pdoo_wrap(doo_obj, total_budget, nu_max=1.0, rho_max=0.9, K=2, C_init=0.8, tol=1e-3,
POO_mult=0.5, Randomize=False, return_history=False):
""" Wrapper for running PDOO optimisation. """
# pylint: disable=too-many-locals
total_budget = total_budget * doo_obj.eval_cost_single_point_normalise... | 51,113 |
def chi2(sp, pars):
"""
Given a spectrum and some parameters, calculate the chi^2 value
"""
pars = list(pars) + [0]
return ((sp.specfit.get_model_frompars(sp.xarr, pars) -
sp.specfit.spectofit)**2 /
(sp.specfit.errspec**2)
).sum() | 51,114 |
def handle_workflow_recover() -> tuple:
"""Attempts to recover workflows
"""
if 'workflows' in session:
known_workflows = session['workflows']
else:
known_workflows = []
found_workflow_ids = []
if known_workflows:
for one_workflow_id in known_workflows:
workin... | 51,115 |
def cartesian2spherical(xyz):
"""
Transform cartesian coordinates (x, y, z)
in spherical coordinates. The function only returns
the (theta, phi) pair since
the magnetisation is fixed at zero Temperature
(the r-component is constant) and is
fully characterised by two degrees of freedom.
(... | 51,116 |
def dict_list_select(dict_list, keys, default_value='', include_conditions={}, exclude_conditions={}):
"""
Transforms a list of dictionaries into a new list of dictionaries that only
includes the specified keys. List entries that are missing key(s) will
get the default value assigned.
"""
# Ma... | 51,117 |
def route_hardware_function(api_version: str, function: str):
"""Can be used to execute standard UOS IO functions."""
if api_version not in API_VERSIONS:
return jsonify(
ComResult(
False,
exception=f"'{function}' not supported in api version {api_version}.",
... | 51,118 |
def froms_to_imports(path):
"""Change the 'from X import Y' statements in PATH to 'import X.Y'.
e.g.
rope froms-to-imports mypackage/mymodule.py
"""
project = rope.base.project.Project(".", ropefolder=".clirope")
resource = project.get_resource(path)
pymodule = project.get_pymodule(res... | 51,119 |
def write_ip_list_file(file_name, ips, port=None):
"""write list of ips into a file
:param file_name: fine name
:param ips: list of ips
:param port: default port(Default value = None)
"""
with open(file_name, 'w') as f:
if port:
content = ["{} {}".format(ip, port) for ip i... | 51,120 |
def transfer_outgoing_connections(src, dst):
"""Connect outgoing connections from `src` to `dst`
Connections that cannot be made are ignored.
Arguments:
src (str): Absolute path to source node
dst (str): Absolute path to destination node
"""
for destination in cmds.listConnection... | 51,121 |
def AutoML_format(dataset_name, raw_dataset_path, label_name, image_format="png",
is_regression=False, output_dir="datasets"):
"""
AutoML format
https://github.com/codalab/chalab/wiki/Help:-Wizard-%E2%80%90-Challenge-%E2%80%90-Data
Currently, only regression and multiclass classifica... | 51,122 |
def calculate_ci(patICDList, version=ELIXHAUSER):
"""
Calculate comorbidity index
"""
if version not in CI_MAP:
raise ValueError("Unsupported comorbidity index")
patCCMap = _calculate_comorbidity_score(patICDList, CI_MAP[version])
return sum(patCCMap.values()) | 51,123 |
def _map_spectrum_weight(map, spectrum=None):
"""Weight a map with a spectrum.
This requires map to have an "energy" axis.
The weights are normalised so that they sum to 1.
The mean and unit of the output image is the same as of the input cube.
At the moment this is used to get a weighted exposure... | 51,124 |
def predict(processed_input):
"""Function to predict dog breed using the available model
Args:
processed_input (torch 4D tensor): transformed and preprocessed image
Returns:
breed_pred (str): name of the predicted breed
class_prob (float): probability of... | 51,125 |
def reproduce(
n_epochs=457, batch_size=128, log_dir="/tmp/run", device="cuda", debug_loader=None
):
"""Training script with defaults to reproduce results.
The code inside this function is self contained and can be used as a top level
training script, e.g. by copy/pasting it into a Jupyter notebook.
... | 51,126 |
def getChannels(server: utils.HikVisionServer):
"""
It is used to get the properties of streaming channels for the device
"""
return utils.getXML(server, "Streaming/channels") | 51,127 |
def has_valid_zip(zip_path):
"""
Return True if valid zip exists.
Parameters
----------
zip_path : str
absolute path to zip
Returns
-------
bool :
True if valid zip exists at path
"""
if os.path.isfile(zip_path):
if zipfile.is_zipfile(zip_path):
... | 51,128 |
def is_help_command(command):
"""
Checks that the user inputted command is a help command, which will not go over the wire.
This is a command with -h or --help.
The help functionality is triggered no matter where the -h appears in the command (arg ordering)
:param command: a list of strings repres... | 51,129 |
def click_position(hwd, x_position, y_position, sleep):
"""
鼠标左键点击指定坐标
:param hwd:
:param x_position:
:param y_position:
:param sleep:
:return:
"""
# 将两个16位的值连接成一个32位的地址坐标
long_position = win32api.MAKELONG(x_position, y_position)
# win32api.SendMessage(hwnd, win32con.MOU... | 51,130 |
def _holoviews_chart():
"""## Dashboard Orders Chart generated by HoloViews"""
data = _get_chart_data()
line_plot = data.hvplot.line(
x="Day", y="Orders", width=None, height=500, line_color="#007BFF", line_width=6,
)
scatter_plot = data.hvplot.scatter(x="Day", y="Orders", height=300).o... | 51,131 |
def api_user_required(f):
"""A decorator for APIs that require a logged-in user."""
@wraps(f)
def decorated(*args, **kwargs):
if not are_logged_in():
return Response("API requires logged-in user", 401)
return f(*args, **kwargs)
return decorated | 51,132 |
def consume_queue(queue, cascade_stop):
"""Consume the queue by reading lines off of it and yielding them."""
while True:
try:
item = queue.get(timeout=0.1)
except Empty:
yield None
continue
# See https://github.com/docker/compose/issues/189
ex... | 51,133 |
def fitGMM_patch_post_process( centre_patch_intensity, n_samples=1000, max_dist_thresh=10, min_area_pair=0, max_area_pair=10000):
""" Fits an n-component mixture to a 2d image to resolve closely overlapping centroids
This function simplifies the calling and wraps `fit_2dGMM` so we directly give the input image... | 51,134 |
def clean_objs(release_version, debug):
"""
清除编译产物
@param release_version:版本号
@param debug:调试使能
"""
print("清除编译产物")
os.chdir("../src/")
os.system("make clean")
os.system("rm -f ../pack/learning_platform/learning_platform_runtime/bin/AIService") | 51,135 |
def plot_summary_steady(path, show=False):
"""
Plot a summary plot for steady-state model runs.
Parameters
----------
path: string
path to the modelling results. Subfolder must be "input_files"
containing the input files and "output_files" containing the
output_files.
sh... | 51,136 |
def generate(pTable, proxyService):
"""
for rows without candidates in subject cells,
try to deduce candidates from the object properties in the same row
-> add CEA candidates for subject columns and the respective cell_pair candidates
"""
# get subject columns
subj_col_ids = pTable.getSubj... | 51,137 |
def plot_barcode(preds, labels):
"""Plot a visualization showing inliers and outliers sorted by their prediction of novelty."""
# the bar
x = sorted([a for a in zip(preds, labels)], key=lambda x: x[0])
x = np.array([[49,163,84] if a[1] == 1 else [173,221,142] for a in x])
# x = np.array([a[1] for a ... | 51,138 |
def StartOfInterval(intervalVar:NexVar) -> NexVar:
"""Creates the new event. Copies the start of each interval of the specified interval variable to the result."""
return NexRun("StartOfInterval", locals()) | 51,139 |
def validate(pack_manifest):
"""
Validates a manifest, raising an exception if the manifest is invalid
Arguments
pack_manifest -- pack manifest object to validate
Raises
jsonschema.ValidationError -- if the pack manifest doesn't follow the schema
CircularDependencyError -- ther... | 51,140 |
def is_global(host: str) -> bool:
"""
>>> assert not is_global("127.0.0.1")
>>> assert not is_global("192.168.20.168")
>>> assert is_global("211.13.20.168")
>>> assert is_global("google.com")
"""
if host == "localhost":
return False
try:
address = ipaddress.ip_address(hos... | 51,141 |
def make_tweet(quantity, ticker, asset_description, price, tx_date, tx_time, instrument, trade_type):
"""Create and return a new instance of a Tweet object."""
tweet = Tweet(quantity, ticker, asset_description, price, tx_date, tx_time, instrument, trade_type)
return tweet | 51,142 |
def run_seq(cmd):
"""Run `cmd` and yield its output lazily"""
p = subprocess.Popen(
cmd, shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
# make STDIN and STDOUT non-blocking
fcntl.fcntl(p.stdin, fcntl.F_SETFL, os.O_NONBLOCK)
fcntl... | 51,143 |
def macd():
"""
MACD-平滑异同平均
:return:
"""
# 计算并输出 security_list1 的 MACD 值
macd_dif, macd_dea, macd_macd = MACD(
security_list1, check_date='2017-01-04', SHORT=12, LONG=26, MID=9)
print(macd_dif[security_list1])
print(macd_dea[security_list1])
print(macd_macd[security_list1])
... | 51,144 |
def rescale_laplacian(laplacian):
"""
Scale graph Laplacian by the largest eigenvalue of normalized graph Laplacian,
so that the eigenvalues of the scaled Laplacian are <= 1.
Args:
laplacian: Laplacian matrix of the graph
Returns:
Return a scaled Laplacian matrix.
"""
try:... | 51,145 |
def download_source(src_version):
"""
Загрузка архива с исходным кодом требуемой версии nginx
Возвращает имя скаченного файла
:param src_version:
:return file_name:
"""
logger.info("Downloading nginx src...")
file_name = "nginx-{}.tar.gz".format(src_version)
url = "{}/{}".format(conf... | 51,146 |
def get_function_signature(uplevels=0):
"""
RETURNS the calling function signature, at runtime.
"""
uplevels += 1
funcname = get_function_name(uplevels)
params = get_function_parameters_and_values(uplevels)
params = ", ".join(["{}={}".format(*i) for i in params])
sig = "{}({})".format(... | 51,147 |
def debug() -> None:
"""
Print out start up debug information if this is a debug .exe
"""
if 'DEBUG' in sys.executable: # rF2headlightsDEBUG.exe
from configIni import CONFIG_FILE_NAME
from readJSONfile import read_file
conf_file = os.path.abspath(CONFIG_FILE_NAME)
try:
... | 51,148 |
def test_find_and_replace(target_env):
"""
Tests that versions are updated and ignored versions are not
"""
manifest_data = {
"versions": {
"arborist": "quay.io/cdis/arborist:2020.07",
"aws-es-proxy": "quay.io/cdis/aws-es-proxy:0.8",
"ambassador": "quay.io/dat... | 51,149 |
def get_logfile_fullpath(fingerprint_result_dir, procmon_csv:str, fingerprint_file_csv:str, fingerprint_reg_csv:str)->str:
"""
>>> fingerprint_result_dir = 'c:/fingerprint'
>>> procmon_csv = 'procmon-logfile'
>>> fingerprint_file_csv = 'test_c_files'
>>> fingerprint_reg_csv = 'test_registry'
>>>... | 51,150 |
def multivariate_multiply(m1, c1, m2, c2):
""" Multiplies the two multivariate Gaussians together and returns the
results as the tuple (mean, covariance).
Examples
--------
.. code-block:: Python
m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]],
... | 51,151 |
def make_initial_state():
"""
Create an initial state dictionary.
"""
return { 'geogrid' : 'waiting',
'ingest' : 'waiting',
'ungrib' : 'waiting',
'metgrid' : 'waiting',
'real' : 'waiting',
'wrf' : 'waiting',
'output': 'waiting... | 51,152 |
def xliff_import_confirm(request, xliff_dir):
"""
Confirm the XLIFF import and write changes to database
:param request: The current request (used for error messages)
:type request: ~django.http.HttpRequest
:param xliff_dir: The directory containing the xliff files
:type xliff_dir: str
:r... | 51,153 |
def test2():
"""
Using some real data now
"""
tickers = ['IBM', 'TSLA', 'GOOG', 'AAPL', 'MSFT']
stock_returns = np.matrix([get_real_stock_returns(ticker) for ticker in tickers])
weights, returns, risks = optimal_portfolio(stock_returns)
print weights
plt.ylabel('mean')
plt.xlabel... | 51,154 |
def generate_gaps_time_series(nt, nx, ny, pct, gaps_type):
""" Generate gaps on time series of modeled fields.
Input:
- pct: percentage of gaps to be generated
- gaps_type: type of gaps, can be:
- 'random': randomly distributed gaps across time series
- 'corr'... | 51,155 |
def leave_feedback():
"""Оставить отзыв"""
json = request.get_json()
if "text" in json:
Feedback.create(text=json["text"], user=get_user_from_request())
Telegram(current_app.config).notify_admin_channel(
"Пользователь %s оставил отзыв: %s"
% (get_user_from_request().... | 51,156 |
def test_preview_mode():
""" Test downloading three bands of L1C
"""
evalscript = """
//VERSION=3
function setup() {
return {
input: [{
bands: ["B02", "B03", "B04"],
units: "DN"
}],
output: {... | 51,157 |
def get_control_panel(control_panel_arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetControlPanelResult:
"""
AWS Route53 Recovery Control Control Panel resource schema .
:param str control_panel_arn: The Amazon Resource Name (ARN) of the cluster.... | 51,158 |
def zeros(shape: Sequence[int],
dtype: Optional[Type[np.number]] = None,
backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor:
"""Return a Tensor of shape `shape` of all zeros.
The Tensor has one dangling Edge per dimension.
Args:
shape : Shape of the array.
dtype, optiona... | 51,159 |
def staff_required(
function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url="login"
):
"""Decorator for views that checks that the logged in user is a staff/admin,
redirects to the log-in page if necessary."""
actual_decorator = user_passes_test(
lambda user: user.is_active and user.is... | 51,160 |
def from_Peppercorn_restingset_reaction(reaction, restingsets):
""" Converts a condensed Peppercorn PepperReaction object to an equivalent
DNAObjects RestingSetReaction object. This function requires as an argument a
dict mapping Peppercorn RestingSet objects to equivalent DNAObject RestingSets.
"""
if rea... | 51,161 |
def test_CodeEntropy_parser_isNAtomArray(dataContainer_protein):
"""
sanity check for pulling atom selection boolean from MDAnalysis.Universe.select_atom
"""
ref = array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.... | 51,162 |
def mock_stripe_checkout(monkeypatch):
"""Fixture to monkeypatch stripe.checkout.* methods"""
mock = Mock()
mock.Session.create.return_value.url = "https://example.net/stripe_checkout/"
monkeypatch.setattr(stripe, "checkout", mock)
return mock | 51,163 |
def milliseconds():
"""
Current time in milliseconds (UTC).
"""
return int(time.time() * 1000) | 51,164 |
def test_dispatch_responses():
"""
MessageSenderMixin._dispatch_responses() Test plan:
-Ensure False returned if pre_dispatch_responses hook returns false
-Ensure False returned if post_dispatch_responses hook returns false
-Catch invalid response from hpit on [message][id]
-Catc... | 51,165 |
def fit_wave_interval(wave, old_sampling, new_sampling, new_size = None):
"""
Produces an array of wavelengths between two values and with a given number
of elements.
Parameters
----------
wave : np.ndarray, list
List or ndarray with initial wavelength and final wavelength e.g.:
... | 51,166 |
def make_network_from_structural_and_functional(structural_edges, functional_edges):
"""
Combine structural and functional dataframes to get a deduplicated dataframe of edges
:param structural_edges: pandas DataFrame including columns ['source_content_id', 'destination_content_id']
:param functional_edg... | 51,167 |
def deribit_fetch_market_price_data_request_failed(error_code):
"""Request to deribit.com failed while trying to fetch candlestick price data"""
raise RuntimeError(f'Fetching candlestick price data: request to deribit.com failed.\n'
f'Exception when calling deribit API: '
... | 51,168 |
def parse_arguments(args):
"""
Parse the arguments from the user
"""
parser = argparse.ArgumentParser(
description= "HAllA's Clustering using hierarchical clustering and Silhouette score.\n",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
"-v","--ve... | 51,169 |
def DefineRulesTo_computeCMSforSims( pr, Ddata, simsOut = 'simsOut', mutPops = AllPops,
mutAges = AllAges, mutFreqs = AllFreqs, nreplicas = 100, scen2nreplicas = {},
thinExt = '', thinSfx = '', sampleSize = 120, pop2sampleSize = {},
... | 51,170 |
def num_k_of_n(n: int, k: int) -> int:
"""Return number of combinations of k elements out of n."""
if k > n:
return 0
if k == n:
return 1
return math.factorial(n) // (math.factorial(k) * math.factorial((n - k))) | 51,171 |
def list_datasets(dataDirectory, projectDirectory='.', pattern=None):
"""Convenience function to list existing datasets in the project
Parameters
----------
dataDirectory : string
location of the project data
projectDirectory : string (default ``.``)
location of the data directory
... | 51,172 |
def new_graph():
"""Make graph to play with."""
return Graph() | 51,173 |
def quicklooks_1panel(file, field, config, image_directory=None, **kwargs):
"""
Quciklooks, produces a one panel image using a QVP object NetCDF file.
Parameters
----------
file : str
File path to the QVP NetCDF file
field : str
String of the radar field
config : str
... | 51,174 |
def density(args):
"""
%prog density bedfile ref.fasta
Calculates density of features per seqid.
"""
p = OptionParser(density.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
bedfile, fastafile = args
bed = Bed(bedfile)
sizes = S... | 51,175 |
def plot(title, x_label, y_label, x_data, y_data, color, font_styles=dict(fontsize=20, fontweight='bold'), legend=True):
"""
plots data for given values
:param legend: whether to display the legend or not
:param title: heading of the plot
:param x_label: label of X-axis
:param y_label: label of ... | 51,176 |
def test_get_pipeline_parameters_source_with_step(notebook_processor):
"""Test that the function gets the correct pipeline parameters source."""
notebook = nbformat.v4.new_notebook()
cells = [
("1", {"tags": ["pipeline-parameters"]}),
("0", {"tags": ["step:test"]}),
("1", {"tags": ["... | 51,177 |
def subtract_mean_batch_reward(population):
"""Returns new Population where each batch has mean-zero rewards."""
df = population.to_frame()
mean_dict = df.groupby('batch_index').reward.mean().to_dict()
def reward_for_sample(sample):
return sample.reward - mean_dict[sample.batch_index]
shifted_samples = ... | 51,178 |
def norm(x):
"""Calculate the Euclidean norm of a vector x."""
return np.sqrt(np.dot(x, x)) | 51,179 |
def test_contributor(app, db):
"""Test contributor schema."""
valid_full = {
"person_or_org": {
"name": "Caesar, Julius",
"type": "personal",
"given_name": "Julius",
"family_name": "Caesar",
"identifiers": [{
"scheme": "orcid",
... | 51,180 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_palo_alto_wildfire package"""
reload_params = {"package": u"fn_palo_alto_wildfire",
"incident_fields": [],
"action_fields": [],
"function_params": [u"artifact_id", u"artifact... | 51,181 |
def setup_nbserver_config():
""" Uploads a config file for each notebook server
MUST RUN AFTER THE SUPERVISORD LAUNCHES ONCE WITH ALL NBSERVERS
"""
template_dir = os.path.join(os.path.curdir, 'templates')
jinja_env = Environment(loader=FileSystemLoader(template_dir))
template = jinja_e... | 51,182 |
def min_number_in_rotated_array(r_nums):
"""
:param r_nums:rotated arrat
:return: min number
"""
if not r_nums:
return None
left = 0
right = len(r_nums)-1
while left < right:
mid = (left + right) // 2
if r_nums[mid] == r_nums[right] == r_nums[left]:
ri... | 51,183 |
def create_cond_node(return_name_ids, pred, true_func, false_func):
"""
Create `fluid.layers.cond(pred, true_fn, false_fn)` to replace
original `python if/else` statement.
"""
# TODO(Aurelius84): should replace the api hard code.
cond_api = gast.parse('fluid.layers.cond').body[0].value
true_... | 51,184 |
def scatter_columns(A):
"""
Performs the reverse operation as gather_columns. Thus, each prow receives
the prow'th row-slice of A.
If A had local shape(grid[0] * m_l, n_l), thre result has local shape
(m_l, n_l). If the number of local rows in A is not an even multiple
of grid[0] an error is thrown.
"""
... | 51,185 |
def digitos(valor):
"""Resulta em uma string contendo apenas os dígitos da string original."""
return ''.join([d for d in valor if d.isdigit()]) | 51,186 |
def from_Point(ros_pt):
"""From ROS Point to Klamp't point"""
return [ros_pt.x,ros_pt.y,ros_pt.z] | 51,187 |
def greedy():
"""A greedy distribution."""
def sample_fn(key: ArrayLike, preferences: ArrayLike):
probs = _argmax_with_random_tie_breaking(preferences)
return _categorical_sample(key, probs)
def probs_fn(preferences: ArrayLike):
return _argmax_with_random_tie_breaking(preferences)
def log_prob_fn... | 51,188 |
def plot_chi_squared_values(star):
"""Plot the chi-squared value for each transition and pair to look for
excess.
star : `varconlib.star.Star`
An instance of `varconlib.star.Star` to be plotted.
"""
pairs_to_use = ('4652.593Cr1_4653.460Cr1_29',
'4652.593Cr1_4653.460Cr1... | 51,189 |
def GibbsSampler(dna_list, k, t, N, mode = 'v1', repeat=20):
"""Input a list of Dna sequence, out put the best set of motifs.
The motifs are generated by Gibbs sampling and optimized by comparing
hamming or entropy scores. Mode 'v1' returns kmer by weighted probability;
mode v2 returns the most probabl... | 51,190 |
def subparser_hook(subparsers):
""" Hook to add subparser for this command. """
subparser = subparsers.add_parser("tail", description=__doc__, help=main.__doc__)
subparser.set_defaults(func=main)
add_config(subparser)
add_environment(subparser)
subparser.add_argument(
"-f",
"--fo... | 51,191 |
def read_input_h5(h5):
"""
Reads astra inpu5 from h5
See: write_input_h5
"""
d = {}
for g in h5:
d[g] = dict(h5[g].attrs)
# Convert to native types
for k, v in d[g].items():
d[g][k] = native_type(v)
return d | 51,192 |
def to_half_life(days):
"""
Return the constant [1/s] from the half life length [day]
"""
s= 24 * 3600 * days
return -math.log(1/2)/s | 51,193 |
def fit_on_batch(model, x, y, loss_fn, optimizer, metrics=["loss", "acc"]):
"""Trains the model on a single batch of examples.
This is a training function for a basic classifier. For more complex models,
you should write your own training function.
NOTE: Before you call this, make sure to do `model.tr... | 51,194 |
def get_longest_common_substring(text_a, text_b):
"""Find longest common subtring."""
# isjunk=None, a='', b='', autojunk=True
seqMatch = SequenceMatcher(None, text_a, text_b, autojunk=False)
#Also:
# autojunk = True (default)
# isjunk = None (deafult), same as: lambda x: False;
# or return... | 51,195 |
def check_destroy_descriptor_set_layout(test, device, descriptor_set_layout):
"""Checks that the next vkDestroyDescriptorSetLayout command call atom has
the passed-in |device| and |descriptor_set_layout| handle value.
"""
destroy_descriptor_set_layout = require(test.next_call_of(
"vkDestroyDescr... | 51,196 |
def from_group(group, time_index=False, absolute_time=False, scaled_data=True):
"""
Converts a TDMS group object to a DataFrame. DataFrame columns are named using the channel names.
:param group: Group object to convert.
:param time_index: Whether to include a time index for the dataframe.
:param a... | 51,197 |
def build_snapshot_command(ctx, snapshot_name_dir, modules=[], active=True):
"""Builds a basic shell command that can be used to provision an environment
with the minitrino CLI. Used for snapshot purposes."""
command_string = build_command_string(modules)
create_snapshot_command_file(command_string, sn... | 51,198 |
def get_model(source, data_only=False, curdir=None):
"""FIXME: Documentation missing.
Mention TestSuite.from_model when docs are written.
"""
tokens = get_tokens(source, data_only)
statements = _tokens_to_statements(tokens, curdir)
return _statements_to_model(statements, source) | 51,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.