content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_all_preconditions(action_set):
"""
Returns a set of all preconditions for the actions in the given set
"""
all_precons = set()
for a in action_set:
all_precons.update(a.precondition)
return all_precons | 1697c2d013b07bbfc24ca6273d16523eb1d83acf | 3,625,300 |
def confusionmatrix(tt, tp, gn=['', '', ''], plot=False, title='',
cmm='Blues', fontsize=20, ylabel='True', xlabel='Prediction'):
"""
Calculates and/or plots the confusion matrix for machine learning algorithm
results.
:type tt: list[float]
:param tt: Real targets.
:type t... | 47e16c6df881e18f6cdf3317a5db575453269b9c | 3,625,301 |
def _to_string(*args: Object) -> Object:
"""Convert an integer to a string"""
if len(args) != 1:
return Error("It must recieve one parameter")
number: Object = args[0]
if not isinstance(number, Integer):
return Error("It must be an integer")
return String(str(number.value)) | 397a3deae6464602e04732e940e65a87f9976261 | 3,625,302 |
from typing import Optional
def compose_conformers(*conformers: Optional[Conformer]) -> Optional[Conformer]:
"""
Return a single conformer which is the composition of the input conformers.
If a single conformer is given, return the conformer.
"""
conformers = tuple(filter(None, conformers))
... | 7f6b2856ea1cc79d287a864b9ff07d8fc15a69ed | 3,625,303 |
def model_fn_builder(config: Configs, tasks,
num_train_steps, pretraining_config=None):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params):
"""The `model_fn` for TPUEstimator."""
log("Building model...")
is_training = (mode == tf.estimat... | 6eced6c3f1ffd6ad01ef1ff8c65096ea1cbf7ce6 | 3,625,304 |
def get_ul_inds(udeg, ls):
"""
"""
# Turn `ls` into a slice
if isinstance(ls, integers):
ls = slice(ls, ls + 1)
if isinstance(ls, slice):
# List of indices user is accessing
inds = []
# Fill in the `None`s
if ls.start is None:
ls = slice(0, ls... | 49132020728129ca0288047f998b06a567b78164 | 3,625,305 |
def f_line(x, m, b):
"""
Line fit with equation y = mx + b
Parameters
----------
x : array
x values
m : float
slope
b : float
y-intercept
Returns
-------
y : array
y values
"""
y = m*x + b
return y | daf437461c2e8723a824e4083794d1f6ea6b368b | 3,625,306 |
def extractLostInTranslation(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Third Prince Elmer' in item['tags']:
return buildReleaseMessageWithType(item, 'Third Prince Elmer', vol, chp, frag=fr... | ed7802c168626e5d87a7dcade175ff1b8a54fd54 | 3,625,307 |
import random
def determinize(perspective: cs.Perspective, mode=0) -> GameState:
"""Determinize the given perspective into a deterministic state.
The mode parameter determines the way in which determinization happens.
"""
if mode == 0:
is_declarer = perspective.player == perspective.declarer
... | 6964a75dbafb784ea6e1ef9d0c03fdc774d3881e | 3,625,308 |
def parse_value(file, section, key):
""" Read ini file and returns unique value
:param file: File to be parsed
:type file: str
:param section: Section targeted
:type section: str
:param key: Parameter to be read
:type key: str
:return: Read value
:rtype: str
"""
config = Con... | f3658f28323a19836f41da86527c35a99dcffe1a | 3,625,309 |
def demo_JmE(X, Y, DPiters=1000):
"""
Explore the posterior of our model.
"""
""" Create expert shell """
expert = MixtureOfExperts.experts.IndpendentRBF(input_dim=X.shape[1], output_dim=Y.shape[1],
process_mean='Constant', ard=True)
expert._p... | e7957d72dbb575d87cb5cb83f857432b40d98071 | 3,625,310 |
from bs4 import BeautifulSoup
import json
def magazineluiza_parser(html):
"""
Parser for magazineluiza.com.br.
There's an attribute with a JSON containing all the info we need when
the item is available. When it isn't, we must retrieve the info from
another JSON, one much less complete (without b... | 634f38ce32662594a9f14e8d27d835205317591a | 3,625,311 |
def getDistance(sensor):
"""
Return the distance of an obstacle for a sensor.
The value returned by the getValue() method of the distance sensors
corresponds to a physical value (here we have a sonar, so it is the
strength of the sonar ray). This function makes a conversion to a
distance value ... | d00b1d201fb59939d2b8a2e57bfa35588780b6d5 | 3,625,312 |
import warnings
def sjoin(
left_df,
right_df,
how="inner",
predicate="intersects",
lsuffix="left",
rsuffix="right",
**kwargs,
):
"""Spatial join of two GeoDataFrames.
See the User Guide page :doc:`../../user_guide/mergingdata` for details.
Parameters
----------
left_... | aa27217a006d2cfc77ff1012ed1814f059da1717 | 3,625,313 |
def compute_BtBinv(B, C):
"""Create block inverses.
Helper function that creates inv(B_i.T B_i) for each block row i in C,
where B_i is B restricted to the sparsity pattern of block row i.
Parameters
----------
B : {array}
(M,k) array, typically near-nullspace modes for coarse grid, i.... | 65871a8bb1a4491aa3a7bc1b112ea1312717bd49 | 3,625,314 |
import random
def fixed_onepoint(p_0, p_1):
"""
Given two individuals, create two children using one-point crossover and
return them. The same point is selected on both genomes for crossover
to occur. Crossover points are selected within the used portion of the
genome by default (i.e. crossover do... | 1db8157bbd3434c91fe82c64221a56c53bb56b36 | 3,625,315 |
def get_pipeline_ids(db_name='./grades.sqlite3'):
"""
:param db_name:
:return:
"""
with lite.connect(db_name) as con:
cur = con.cursor()
result = cur.execute("SELECT pipeline_id FROM students")
try:
resut = (ids[0] for ids in result.fetchall())
except Exc... | 7091d6098b33bbfbfba00f3e134b4d23b07f3b34 | 3,625,316 |
def update_individual_metadata(ts):
"""Update individual metadata in ts object.
Returns new list of individuals with updated metadata
"""
individuals = []
oldname = None
i = 0
for ind in ts.individuals():
popindex = ts.nodes()[ind.nodes[0]].population
popname = ts.population... | 4cfaf24fc4e68203e8206163fcb0686ac9fd9692 | 3,625,317 |
def get_trt_logger():
"""
Get the global TensorRT logger created by Polygraphy.
Returns:
trt.Logger: The TensorRT logger.
"""
global TRT_LOGGER
if TRT_LOGGER is None:
TRT_LOGGER = trt.Logger()
return TRT_LOGGER | 06ca9e41932f936c3b31ae210de040954916816c | 3,625,318 |
from pathlib import Path
import torch
def _convert_rx101_to_mobile(
model_path: str,
num_classes: int,
output_path: str or Path = "./rx101_optimized_scripted1.ptl",
):
"""Function handling conversion of MSCG-Net Rx101 Models
:param model_path:
:param num_classes:
:param output_path:
:... | a8b92ca86d893266b5eab5ebe8a03112ffa74d1f | 3,625,319 |
from datetime import datetime
def unify_index_info_couch_dates_fmt(index_info):
"""Applies standardization to secondary keys 'date' type keys.
@param index_info: is a index data to workout for
"""
clean_info = {}
index_keys = [key for key in index_info.iterkeys()]
for index_key in index_keys:... | 3ae4ba10be563082ae60a0636ff5a1b4e464ff97 | 3,625,320 |
def stellar_dist(row: pd.Series, push: float) -> pd.Series:
"""Calculate the fluxes for the stellar objects at a given distance.
For use with pandas.DataFrame.apply(). Requires the columns:
- 'distance'
- 'radio'
- 'optical_in_mJy'
Args:
row: The pd.Series object containing... | 401ce8b51df995b3e62a025750d5a0871c6e3b3f | 3,625,321 |
import platform
def mysql_config_path():
"""
根据平台查询mysql配置文件
:return:
"""
_platform = platform.system()
print('当前平台为:{}'.format(_platform))
mysql_config = None
if _platform == 'Darwin':
mysql_config = "/Users/yuxiang/Documents/Developer/WeChat/baixiaotu-mini/sqlconfig.json"
... | c24632e4262ea1cfb903492b5d261a8cd5cbcd8e | 3,625,322 |
import collections
def calculate_case_distances(
graph: nx.DiGraph, case: Case, *, additional_attributes: "list[str]" = []
) -> "dict[str, float]":
"""
Extracts the distances between the current graph and a given case across trace,
time, and the additional attributes provided.
Arguments:
... | 3e7383a983d611564edfa0689d22595e38ef83d6 | 3,625,323 |
import numpy
def index_to_position(index, nelx, nely):
"""
Convert the index of a element to the centroid of the element
"""
return numpy.array([(index % nelx)+.5, index/nelx+.5]) | 1402251581df9e346097dbd561ef5f782f18da1e | 3,625,324 |
import http
def imdb(inp, api_key=None):
""".imdb <movie> -- gets information about <movie> from IMDb"""
if not api_key:
return None
content = http.get_json("https://www.omdbapi.com/", t=inp, apikey=api_key)
if content["Response"] == "Movie Not Found":
return "movie not found"
e... | 44fb0e2d4ae7940c4fc59c2788062072420a3b5b | 3,625,325 |
import os
def get_api_key(api_file):
""" Return an API key from the user's home directory """
with open('{_home}/.{_api_file}'.format(_home = os.path.expanduser('~'),
_api_file = api_file)) as f:
return f.read().replace('\n', '') | 0819cfe693478b24a827d12b448ccd1ab274271e | 3,625,326 |
def smooth(sig, window_size):
"""
Apply a uniform moving average filter to a signal.
Parameters
----------
sig : ndarray
The signal to smooth.
window_size : int
The width of the moving average filter.
Returns
-------
ndarray
The convolved input signal with the... | f91cbbeff3402c730d7b4f711c05c1992eed9e3a | 3,625,327 |
def filter_by_oid_alt(instructions, oid):
""" For a given list of instructions and an Order ID,
return the list of instructions that reference that Order ID.
:param instructions: list of instructions
:type instructions: list or tuple
:param oid: Order ID
:type oid: int
:return: list of inst... | c7d6b1cfd2218adfba1612bf42ac19a15e98e776 | 3,625,328 |
def get_sequence_lineage(request, upi):
"""
Internal API.
Get the lineage for an RNA sequence based on the
classifications from all database cross-references.
"""
try:
queryset = Xref.objects.filter(upi=upi).select_related('accession')
results = queryset.filter(deleted='N')
... | 2339a648a5bf12b033dd9fdfb86f667ce6b92210 | 3,625,329 |
import requests
def get_function_fb_graph():
"""Get call - facebook."""
return requests.get('http://graph.facebook.com') | 38f790a006a3d8de981e66936e50b7be743e4d1b | 3,625,330 |
def mat_to_pose_wxyz(mat):
"""Convert matrix to pos and wxyz quaternion."""
p = mat[:3, 3].tolist()
p += tra.quaternion_from_matrix(mat).tolist()
return np.array(p) | a98da080207daeec40657bf57fd5c44c1063d780 | 3,625,331 |
def setDefaultCompressionCodecName(compressionCodecName):
"""
:param compressionCodecName: java.lang.String
"""
return _java_type_.setDefaultCompressionCodecName(compressionCodecName) | 8b8fbad360826c9a4a11e0e7b2c18ae473ea1e03 | 3,625,332 |
def do_ajax_update_no_effect(parser, token):
"""
Updates a target div by binding a onclick event to a link which uses jquery.metadata to parse for the target div and data source url
"""
try:
args_list = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "... | 61fd3dcc3a176b70c9b670bc91f0f055a6f8f84d | 3,625,333 |
def standardize_rows(M):
""" Distribute the rows of the cost matrix normally to allow for accurate comparisons of error and description
cost. """
rv = np.matrix(M)
for i in range(rv.shape[0]):
mean = np.mean(M[i, :])
stdev = np.std(M[i, :])
rv[i, :]= (M[i, :]- mean)/stdev
ret... | dd3abb0eebc15dd72c9b64b66217018c0295bd9f | 3,625,334 |
def refine_group_join_event_msg(ctx: EventMsg) -> _GroupJoinEventMsg:
"""某人进群事件"""
if not isinstance(ctx, EventMsg):
raise ContextTypeError('Expected `EventMsg`, but got `%s`' % ctx.__class__)
if ctx.EventName == EventNames.ON_EVENT_GROUP_JOIN:
return _GroupJoinEventMsg(ctx)
return None | 4cd23b709e4d68e813d99d9ffd59a18b7cd87331 | 3,625,335 |
def parse_dlna(dlna_server):
"""
Return a dict of title: url from dlna
"""
res = [
s
for s in upnpclient.Device("http://{}/rootDesc.xml".format(dlna_server)).services
if s.name == "ContentDirectory"
][0].Browse(
ObjectID="2$8",
BrowseFlag="BrowseDirectChildren... | 77eeed8cd2200cfa96c76e15b444cc511eb8c5f3 | 3,625,336 |
import random
import pickle
def sax_optimization(locator, data, time_series_len, BOUND_LOW, BOUND_UP, NGEN, MU, CXPB, start_gen, building_name):
"""
A multi-objective problem set for three objectives to maximize using the DEAP library and NSGAII algorithm:
1. Compound function of accurracy, complexity and... | f224e6039a30a444f94e3730acfa318344e384dc | 3,625,337 |
def randomize_and_play_circuit(n_gates: int, init_state: str = "z"):
"""
:param n_gates: the depth of the circuit
:param init_state: starting position on the bloch sphere
:return:
"""
state = init_state
for ind in range(n_gates):
state = play_clifford(cliffords[np.random.randint(0, ... | c82620401fd9510c1d8b425613c013cd4cb831cc | 3,625,338 |
def pair(dice):
"""Score the given roll in the 'Pair' category"""
counts = dice_counts(dice)
for i in [6, 5, 4, 3, 2, 1]:
if counts[i] >= 2:
return 2*i
return 0 | 1076e00dd877e0381d990a4abe4942dd24c533fb | 3,625,339 |
def get_data_for_fit(expt, mask):
"""
exlucdes pre-bleach frame (T[0]) from the array
Parameters
----------
data: aicsimageio.aics_image.AICSImage
mask: np.ndarray
Returns
-------
data_for_fit: np.ndarray
"""
norm_inside = _norm_extract(expt, mask)
data_for_fit = norm_... | e6a02374f2d141f88beb5cc3157272af3424aafa | 3,625,340 |
def gen_docker_image_reference():
"""Generating a docker image reference including image ID.
returns the docker image reference and image ID"""
image_id = 'sha256:some-long-fake-id-with-numbers-{}'
docker_image_refrence = 'this.is.some.fake.{}/registry:{}@{}'.format(
fauxfactory.gen_alpha().lowe... | 1b10c10992efdb991b5ea97b734d07e53181f647 | 3,625,341 |
def add_anomaly_data(egg_data: pd.DataFrame) -> pd.DataFrame:
"""
Given a dataframe of egg data, add a column for each anomaly metric, and populate it with the
results of running the breakpoint analysis on each row
Args:
egg_data (pd.DataFrame): the dataframe containing the egg temperature data
... | 74a65f25275e816eb4cf59c3a6aa11daa30ea41e | 3,625,342 |
import struct
def set_wm_strut_partial(window, left, right, top, bottom, left_start_y,
left_end_y, right_start_y, right_end_y, top_start_x,
top_end_x, bottom_start_x, bottom_end_x):
"""
Sets the partial struts for a window.
:param window: A windo... | b6da1a199d1ca3194efee425c6f704d03093c28e | 3,625,343 |
def get_connection(database_name: str):
"""Hakee yhteyden tietokantaan ja palauttaa sen.
"""
return connection | 9970b6e9804806c3fb7e97b40f66ef8e20a280c6 | 3,625,344 |
def generate_graph_seq2seq_io_data(
df, x_offsets, y_offsets, add_time_in_day=True, add_day_in_week=False, scaler=None
):
"""
Generate samples from
:param df:
:param x_offsets:
:param y_offsets:
:param add_time_in_day:
:param add_day_in_week:
:param scaler:
:return:
# x: ... | 0140bdbe039748b1b1690e30b179154c7adaf6f4 | 3,625,345 |
def execute(cmd, stderr_to_stdout=False, stdin=None, cwd=None):
"""Execute a command in the shell and return a tuple (rc, stdout, stderr)"""
if stderr_to_stdout:
stderr = STDOUT
else:
stderr = PIPE
p = Popen(cmd, shell=False, bufsize=0, close_fds=True, stdin=stdin, stdout=PIPE, stderr=s... | db50c409e0fd24003c304d1f1d27e8341913fd84 | 3,625,346 |
import random
def get_random_number_with_zero(min_num: int, max_num: int) -> str:
"""
Get a random number in range min_num - max_num of len max_num (padded with 0).
@param min_num: the lowest number of the range in which the number should be generated
@param max_num: the highest number of the range i... | bdc9f192286262566d2b2a87e8124abdf745ecbd | 3,625,347 |
from typing import List
import torch
def cluster_props(all_props: List[CollisionProp]) -> dict:
""" Many provided properties are overlapping -- some subsumes some others, cluster them for later usage.
:return: a dict of central points -> sorted props in decreasing order of their epsilons
"""
d = defau... | 44fefaeb620caf7eb6f66ec0e35052df8396fea6 | 3,625,348 |
from comtypes.automation import VARIANT
def COMMETHOD(idlflags, restype, methodname, *argspec):
"""Specifies a COM method slot with idlflags.
XXX should explain the sematics of the arguments.
"""
paramflags = []
argtypes = []
# collect all helpstring instances
# We should suppress docstr... | 0686af6b9adf193320a3bff57b5a1bb8c7b29c15 | 3,625,349 |
def _validate_rpc_ip(rpc_server_ip):
"""Validates given ip for use as rpc host bind address.
"""
if not is_valid_ipv4(rpc_server_ip):
raise NetworkControllerError(desc='Invalid rpc ip address.')
return rpc_server_ip | 24defd4633d13b1bed2d53ec9663e6abcc05b904 | 3,625,350 |
def normalize_data(df):
"""Normalizes a dataframe."""
scaler=MinMaxScaler()
df[FEATURE_NAMES] = scaler.fit_transform(df[FEATURE_NAMES])
return df | 1a718dc75d451269e0b5c83e5d10a0a1631b9728 | 3,625,351 |
def hex_to_root(hex_string: str) -> Root:
"""
Convert hex string to trie root.
Parameters
----------
hex_string :
The hexadecimal string to be converted to trie root.
Returns
-------
root : `Root`
Trie root obtained from the given hexadecimal string.
"""
return ... | d5685289a3474cc6af6c8436822c4b6cefa0b835 | 3,625,352 |
def redis_connection():
"""
Returns a redis connection from one of our pools.
"""
pool = ConnectionPoolManager.connection_pool(**CONNECTION_KWARGS)
return Redis(connection_pool=pool) | 08a1484b1406f5d5935a6caa057d0f537b645f02 | 3,625,353 |
def count_simple(a, alphabet_len):
"""Counts items in a. """
result = zeros(alphabet_len, Int)
for i in ravel(a):
result[i] += 1
return result | e6c0629175bd90d8942e05f8177e3ffbf1944699 | 3,625,354 |
import os
import requests
def titanic(refresh=False):
"""
Usage: [arg1]:[refresh=False(default)/True - True if the file should be downloaded and refreshed again from intenet]
Type: Supervised - Classification
Name: Titanic
Target variable: Survived
Description: Sample Dataset
Returns: Pand... | e7e528f21dd839a68d3ca4644d0dc7a0e375c303 | 3,625,355 |
def verify_error_db_redis(dut, table, **kwargs):
"""
Verify error db using redis cli
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param :dut:
:param :table:
:param :route:
:param :mask:
:param :ifname:
:param :nhp:
:param :operation:
:param :rc:
:param :result: ... | 5e158d717aee4a7c0cae570547a70070a4a352b8 | 3,625,356 |
def _select_manager(backend_name):
"""Select the proper LockManager based on the current backend used by Celery.
:raise NotImplementedError: If Celery is using an unsupported backend.
:param str backend_name: Class name of the current Celery backend. Usually value of
current_app.extensions['celery... | d12de5e954a4d0b0d64c39f515a5736fb341ad8d | 3,625,357 |
import warnings
def ivim_model_selector(gtab, fit_method='LM', **kwargs):
"""
Selector function to switch between the 2-stage Levenberg-Marquardt based
NLLS fitting method (also containing the linear fit): `LM` and the Variable
Projections based fitting method: `VarPro`.
Parameters
----------... | 58aaf65baed294b344a3eae0e42f8f049ca34d6a | 3,625,358 |
def temperature():
"""
Raspberry Pi temperature
"""
return render_template("temperature.html") | 6ccdf487f1760e812c83d75140e0b8653813f71d | 3,625,359 |
import math
def convert_size_bytes_to_human_readable_format(size_bytes):
"""
Converts a size in bytes to a human readable format.
:param size_bytes: The size in bytes
:return: Bytes converted to readable format
"""
if size_bytes == 0:
return "0B"
size_name = ("B", "KiB", "MiB", "G... | b14d345e5990e431997adeba09b5cee701f83fd0 | 3,625,360 |
def activate(client, name, file_=None):
"""Activate a model view.
Args:
client (obj):
creopyson Client.
name (str):
View name.
`file_` (str, optional):
Model name. Defaults is current active model.
Returns:
None
"""
data = {"name... | cd928a364261e9f73cecbafc010f8eff2c5a39ab | 3,625,361 |
def delete_table(userId, id):
"""
Deletes a table from the db. Only can be called via the saved_search.html
"""
try:
savedSearch = SavedSearch.objects(id=id).first()
tableName = savedSearch.name
doDelete = True
message = tableName+" deleted successfully!"
if saved... | bb13d1c40157e2457adb31c94a58bbe421771e48 | 3,625,362 |
def _get_heatmap(job_name, build_number, builds, group_field, count_skips, project=None):
"""Run the aggregation to get the Jenkins heatmap report"""
# Get the run IDs for the last 5 Jenkins builds
build_min = build_number - (builds - 1)
build_max = build_number + 1
build_range = [str(bnum) for bnum... | 7652ca6cb5e573a88c2eb8ca2949d71ebf8004e0 | 3,625,363 |
def control_4_5_ensure_route_tables_are_least_access(regions):
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
offenders_links = []
control = "4.5"
description = "Ensure routing tables for VPC peering are least access"
scored = Fals... | aa1f4e57703877e33a85f7f412bd00be9761310e | 3,625,364 |
def kiv_pred(df: Kerneldict, lam: float, xi: float, stage: int) -> np.ndarray:
"""Kernel instrumental variable prediction."""
n = len(df["y1"])
m = len(df["y2"])
brac = make_psd(df["K_ZZ"]) + lam * np.eye(n)
W = np.linalg.solve(brac, df["K_XX"]).T @ df["K_Zz"]
brac2 = make_psd(W @ W.T) + m * xi * make_psd(... | 8ada371e3596631af4b2cfb0b2f7af35e7e75461 | 3,625,365 |
def _query_multi_armed_bandit_probabilities():
"""Get query results.
Queries above BANDIT_PROBABILITY_QUERY and yields results
from bigquery. This query is sorted by strategies implemented."""
client = big_query.Client()
return client.query(query=BANDIT_PROBABILITY_QUERY).rows | 181a38cd4602830c68ccd008d0ae857ea36ee86d | 3,625,366 |
from datetime import datetime
import logging
import json
def check_jobs():
"""Check if various jobs have been running.
The following URL parameters can be provided:
- names:
- Comma separated list of names of tasks to check.
- seconds (default 3600)
- How many seconds are allowed since last completio... | ffb6da52342eb28cfc811918fb62dd7dede5f4e6 | 3,625,367 |
def med(data, mw=24, sf=16, sigma=5.0):
"""
Median baseline correction
Algorith described in:
Friedrichs, M.S. JBNMR 1995 5 147-153.
Parameters:
* data Array of spectral data.
* mw Median Window size in pts.
* sf Smooth window size in pts.
* sigma Standard-deviation of Gaus... | 0c00f8740b61b5706f5be275e3a6cba9594cb1fa | 3,625,368 |
def raoult_liquido(fraccion_vapor, presion_vapor, presion):
"""Calcula la fraccion molar de liquido mediante la ec de Raoult"""
return fraccion_vapor * presion / presion_vapor | bd15f53ee74ef3dc1925ee3da7133a9c3f455333 | 3,625,369 |
def deletePlayers():
"""Remove all the player records from the database."""
dbcursor = connect()
dbcursor.execute("TRUNCATE players")
return 1 | 57fb88118faec5b7a4836f176c210786a57bd5bd | 3,625,370 |
def recursepath(path, reverse=False):
# type: (Text, bool) -> List[Text]
"""Get intermediate paths from the root to the given path.
Arguments:
path (str): A PyFilesystem path
reverse (bool): Reverses the order of the paths
(default `False`).
Returns:
list: A list of... | a00286a2933eac2a5e8115fe9bb9bfd6de4d0c64 | 3,625,371 |
def pack_items(arrays, key_encoding="utf-8"):
"""
Packs the specified items by computing the relevant file offsets
and return the list of ItemDescriptors and the overall size of the
file.
"""
num_items = len(arrays)
# We store the keys in sorted order in the key block.
sorted_keys = sort... | da01e3e8662fa925c94c642ecfb771e7d880ac10 | 3,625,372 |
def list_datasets():
"""Returns the list of available FiftyOne datasets.
Returns:
a list of :class:`Dataset` names
"""
# pylint: disable=no-member
return sorted(foo.DatasetDocument.objects.distinct("name")) | 727d397f2e2e6d62b7faa7e76b75f0b78ba71c62 | 3,625,373 |
def wayPointDistribution(rx, ry, ryaw, s):
"""
:param rx:
:param ry:
:param ryaw:
:param s:
:return: generate the efficients of the reference line
"""
x_list = []
y_list = []
theta_list = []
s_list = []
for i in range(len(rx)):
if 20 * i > (len(rx) - 1):
break
x_list.append(rx[20 * i])
y_list.app... | 0813888ae810a617804af8129baa38c8f388aed2 | 3,625,374 |
import bottleneck as bn
def rolling_median_(a, n, axis = 0, data = None, instate = None):
"""
Equivalent to rolling_median(a) but returns also the state.
For full documentation, look at rolling_median.__doc__
"""
state = instate or dict(vec = None)
return _data_state(['data','vec'],_rolli... | c3d3a3ad892bbe2fe39d7ad7823d10d8bed38fca | 3,625,375 |
def implemented_motifs():
"""
Returns
-------
List strings of all implemented motif definitions
"""
return ['Sheet', 'Gamma', 'Herringbone',
'Sandwich'] | 63564c7e1b3e7e5f8f6b93354a3e268a79e9c5de | 3,625,376 |
def left(direction):
"""rotates the direction counter-clockwise"""
return (direction + 3) % 4 | f8136385e5fec11bf26a97f77e336b04ce783571 | 3,625,377 |
def union(list1, list2):
"""Union of two lists, returns the elements that appear in one list OR the
other.
Args:
list1 (list): A list of elements.
list2 (list): A list of elements.
Returns:
result_list (list): A list with the union elements.
Examples:
>>> union([1,2,3... | 983e96ceb4f4eeb2b4b2d96362a0977be0cb2222 | 3,625,378 |
def render_analytics_code():
"""
Renders the new google analytics snippet.
"""
return {
'ANALYTICS_TRACKING_ID': getattr(settings, 'ANALYTICS_TRACKING_ID',
'UA-XXXXXXX-XX'),
'ANALYTICS_DOMAIN': getattr(settings, 'ANALYTICS_DOMAIN', 'auto')
} | e88e928ce43b91eef5fc3b85a8af54d6fd5b0224 | 3,625,379 |
import urlparse
def valid_proxy(proxy):
"""Return 1 if the proxy string looks like a valid url, for an
proxy URL else return 0."""
scheme, netloc, url, params, query, fragment = urlparse.urlparse(proxy)
if scheme != 'http' or params or query or fragment:
return 0
return 1 | f3e9bddd49eb5fa31260876343a15c2b7b5bf7af | 3,625,380 |
def oauth2_from_dict(oauth2_dictionary: dict):
"""
The function converts a dictionary of OAuth2 to a OAuth2 object.
:param oauth2_dict: A dictionary that contains the keys of a OAuth2.
:type oauth2_dict: dict
:rtype: ibmpairs.authentication.OAuth2
:raises Exception: if not a di... | 66d36c6dc2f6eaf6b87907854bdc8e9c59864749 | 3,625,381 |
import os.path
def export_file(isamAppliance, file_id, filename, check_mode=False, force=False):
"""
Exporting a common log file
"""
ret_obj = {'warnings': ''}
if force is True or (os.path.exists(filename) is False):
if check_mode is False: # No point downloading a file if in check_mode
... | fc74b0104029b1cd837ba3096843b1760b6f45f2 | 3,625,382 |
def _initiate_pipeline_stop(
mlmd_handle: metadata.Metadata,
pipeline_uid: task_lib.PipelineUid) -> metadata_store_pb2.Execution:
"""Initiates a pipeline stop operation.
Upon success, MLMD is updated to signal that the pipeline given by
`pipeline_uid` must be stopped.
Args:
mlmd_handle: A handle t... | 87c857e10d95cd79cd22460f8ee3c613d8d1dc1f | 3,625,383 |
def slot_schedule_difference(old_schedule, new_schedule):
"""Compute the difference between two schedules from a slot perspective
Parameters
----------
old_schedule : list or tuple
of :py:class:`resources.ScheduledItem` objects
new_schedule : list or tuple
of :py:class:`resources.Sc... | fbc21d67e2738131246c62f1ccc7b539fef44c9c | 3,625,384 |
def drive_cancellation_seq(
drive_op_code, ramsey_qubit_names, operation_dict,
sweep_points, n_pulses=1, pihalf_spacing=None, prep_params=None,
cal_points=None, upload=True, sequence_name='drive_cancellation_seq'):
"""
Sweep pulse cancellation parameters and measure Ramsey on qubits the
... | 5140bb2a97f34d45bc29d164cee725907f756682 | 3,625,385 |
def generate_inputs(generate_calc_job_node, fixture_localhost, generate_structure, generate_kpoints_mesh):
"""Create the required inputs for the ``ProjwfcCalculation``."""
entry_point_name = 'quantumespresso.pw'
inputs = {'structure': generate_structure(), 'kpoints': generate_kpoints_mesh(4)}
parent_ca... | 25d15d6123a5ab1c5f26a050cfe1925cb185b127 | 3,625,386 |
import re
def list_all_links_in_page(source: str):
"""Return all the urls in 'src' and 'href' tags in the source.
Args:
source: a strings containing the source code of a webpage.
Returns:
A list of all the 'src' and 'href' links
in the source code of the webpage.
"""
retu... | f17f2ac2724fcfdd041e2ad001557a0565b51e00 | 3,625,387 |
def resp_delete_successfully(msg):
"""Response 202"""
response = jsonify({
'message': f'{msg} delete successfully.'
})
response.status_code = 202
return response | 449585ee86d16c41f4a0ee5f2cee9276ca39e8d4 | 3,625,388 |
import math
def embedding_column_v2(categorical_column,
dimension,
combiner='mean',
initializer=None,
max_sequence_length=0,
learning_rate_fn=None,
embedding_lookup_device=No... | aa776edad95892fd7e1f74810497e078dd561649 | 3,625,389 |
def synthesize_data():
"""
synthesize the (block, program) pairs
:return: train_shape, train_prog, val_shape, val_prog
"""
# == training data ==
data = []
label = []
n_samples = [5000,
30000, 5000, 5000, 5000, 10000,
5000, 5000, 5000, 5000, 30000,
... | 41a254326e116dcc9f0942ba984e549c0ed52540 | 3,625,390 |
from bs4 import BeautifulSoup
def parse_predict_data(html: str) -> list[tuple]:
"""Returns the following tuple: (week, (away_data, home_data))
"""
predict_meta = FTE_PREDICT_STATS
parsed = []
soup = BeautifulSoup(html, HTML_PARSER)
# build field processor based on predict metadata
field... | b1edfa0ced51fce0dad8b2182a375643eee3a0d0 | 3,625,391 |
def get_direction(source, destination):
"""Find the direction drone needs to move to get from src to dest."""
lat_diff = abs(source[0] - destination[0])
long_diff = abs(source[1] - destination[1])
if lat_diff > long_diff:
if source[0] > destination[0]:
return "S"
else:
... | 224a8df79cbafbcf1eed8df522ab7f58cc93598d | 3,625,392 |
import sys
def verifyPicklingCompatibility(otherPythonVersion):
"""
Check a provided python version string versus the present instance string for pickling safety.
:param otherPythonVersion: other version string
:return: True is safe, False otherwise
"""
if otherPythonVersion is None:
... | 1b5e2a9cb350f8a223b78cfed0a1ebaddb9d346e | 3,625,393 |
def newAction(
parent,
text,
slot=None,
shortcut=None,
icon=None,
tip=None,
checkable=False,
enabled=True,
checked=False,
):
"""Create a new action and assign callbacks, shortcuts, etc."""
a = QtWidgets.QAction(text, parent)
if icon is ... | a58e20293bca2888360151cb9ef905c3c4a17f5e | 3,625,394 |
def _echelon_form(M, iszerofunc=_iszero, simplify=False, with_pivots=False,
dotprodsimp=None):
"""Returns a matrix row-equivalent to ``M`` that is in echelon form. Note
that echelon form of a matrix is *not* unique, however, properties like the
row space and the null space are preserved.
Parame... | c6e0f1afe21432c18ef4da705074f9c348cc4da5 | 3,625,395 |
import os
def maybe_make_dirs(path):
"""Creates the sub directories leading up to the given file.
Args:
path: The path to a file (i.e., the last word in the path is assumed to be a
file, not a directory).
Returns:
The path generated.
"""
dirname = os.path.dirname(path)
if dirname and not f... | ab0ecd06080d4d07ff23477ef401fe75283f1b1a | 3,625,396 |
def div23():
"""
Returns the divider 22222222222222222222222
:return: divider23
"""
return divider23 | 61dbccd02231227e60c5ac70787cb473c5c6ca45 | 3,625,397 |
from datetime import datetime
import pytz
def datetime_to_timestamp(dt):
"""Converts a `datetime.date` or `datetime.datetime` to milliseconds since
epoch.
Args:
dt: a `datetime.date` or `datetime.datetime`
Returns:
the number of milliseconds since epoch
"""
if type(dt) is dat... | 328b1aaa45477cc9f6502b8a8210f174b4ececc3 | 3,625,398 |
def get_specific_dummies(df, col_map=None, prefix=None, suffix=None, return_df=True):
""" Given a mapping of column_name: list of values, one hot the values
in the column and concat to dataframe. Optional arguments to add prefixes
and/or suffixes to created column names.
Example col_map: {'foo':['... | 98f2adcd49a59c4c9774e166019aedf9e59d9939 | 3,625,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.