content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mixlogistic_invcdf(y, *, logits, means, logscales, mix_dim,
tol=1e-8, max_bisection_iters=60, init_bounds_scale=100.):
"""
inverse cumulative distribution function of a mixture of logistics, via bisection
"""
if _FORCE_ACCURATE_INV_CDF:
tol = min(tol, 1e-14)
ma... | 5,358,400 |
def FormatException(exc_info):
"""Gets information from exception info tuple.
Args:
exc_info: exception info tuple (type, value, traceback)
Returns:
exception description in a list - wsgi application response format.
"""
return [cgitb.handler(exc_info)] | 5,358,401 |
def cli(**cli_kwargs):
""" Run a model with a specific pre-transform for all tiles in a slide (tile_images)
\b
Inputs:
input_slide_image: slide image (virtual slide formats compatible with openslide, .svs, .tif, .scn, ...)
input_slide_tiles: slide tiles (manifest tile files, .tiles.csv)
... | 5,358,402 |
def trackers_init(box, vid_path, image):
"""Initialize a single tracker"""
tracker = cv2.TrackerCSRT_create()
tracker.init(image, box)
return tracker, cv2.VideoCapture(vid_path) | 5,358,403 |
def parse_comment(comment: str, env: Env) -> None:
"""Parse RLE comments and update user environment accordingly.
Parameters
----------
comment: str
RLE comment to parse.
env: `dict` [str, `Any`]
Environment dictionary generated by ``parse_file``.
Notes
-----
This funct... | 5,358,404 |
def get_image(id: Optional[int] = None,
name: Optional[str] = None,
slug: Optional[str] = None,
source: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetImageResult:
"""
Get information on an image for use in other resource... | 5,358,405 |
def _infer_added_params(kw_params):
"""
Infer values for proplot's "added" parameters from stylesheets.
"""
kw_proplot = {}
mpl_to_proplot = {
'font.size': ('tick.labelsize',),
'axes.titlesize': (
'abc.size', 'suptitle.size', 'title.size',
'leftlabel.size', 'r... | 5,358,406 |
def test_bot_extra_mode_args(mockbot, ircfactory, caplog):
"""Test warning on extraneous MODE args."""
irc = ircfactory(mockbot)
irc.bot._isupport = isupport.ISupport(chanmodes=("b", "k", "l", "mnt", tuple()))
irc.bot.modeparser.chanmodes = irc.bot.isupport.CHANMODES
irc.channel_joined("#test", ["Al... | 5,358,407 |
def create_table_description(config: ConfigLoader):
""" creates the description for the pytables table used for dataloading """
n_sample_values = int(config.SAMPLING_RATE * config.SAMPLE_DURATION)
table_description = {
COLUMN_MOUSE_ID: tables.Int16Col(),
COLUMN_LABEL: tables.StringCol(10)
... | 5,358,408 |
def get_target_rank_list(daos_object):
"""Get a list of target ranks from a DAOS object.
Note:
The DaosObj function called is not part of the public API
Args:
daos_object (DaosObj): the object from which to get the list of targets
Raises:
DaosTestError: if there is an error ob... | 5,358,409 |
def find_global_best(particle_best=[]):
"""
Searches for the best particle best to make it the global best.
:param particle_best:
:return:
"""
best_found = None
for particle in particles_best:
if best_found is None:
best_found = copy(particle)
elif particle... | 5,358,410 |
def test_should_invoke_main_nuki_nukis(monkeypatch, project_dir):
"""Should create a project and exit with 0 code on cli invocation."""
monkeypatch.setenv('PYTHONPATH', '.')
test_dir = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'..',
'fixtures/fake-repo-tmpl-nukis',
... | 5,358,411 |
def extract_handler(args: argparse.Namespace) -> None:
"""
Save environment variables to file.
"""
result = env_string(map(parameter_to_env, get_parameters(args.path)), args.export)
with args.outfile as ofp:
print(result, file=ofp) | 5,358,412 |
def rename_to_monet_latlon(ds):
"""Short summary.
Parameters
----------
ds : type
Description of parameter `ds`.
Returns
-------
type
Description of returned object.
"""
if "lat" in ds.coords:
return ds.rename({"lat": "latitude", "lon": "longitude"})
el... | 5,358,413 |
async def test_api_state_change_push(opp, mock_api_client):
"""Test if we can push a change the state of an entity."""
opp.states.async_set("test.test", "not_to_be_set")
events = []
@op.callback
def event_listener(event):
"""Track events."""
events.append(event)
opp.bus.async_... | 5,358,414 |
def payments_reset():
""" Removes all payments from the database """
Payment.remove_all()
return make_response('', status.HTTP_204_NO_CONTENT) | 5,358,415 |
def get_smallerI(x, i):
"""Return true if string x is smaller or equal to i. """
if len(x) <= i:
return True
else:
return False | 5,358,416 |
def _ParseSourceContext(remote_url, source_revision):
"""Parses the URL into a source context blob, if the URL is a git or GCP repo.
Args:
remote_url: The remote URL to parse.
source_revision: The current revision of the source directory.
Returns:
An ExtendedSourceContext suitable for JSON.
"""
#... | 5,358,417 |
def decrypt_and_verify(message, sender_key, private_key):
"""
Decrypts and verifies a message using a sender's public key name
Looks for the sender's public key in the public_keys/ directory.
Looks for your private key as private_key/private.asc
The ASN.1 specification for a FinCrypt message reside... | 5,358,418 |
def add_obstacle(pos: list) -> None:
"""Adds obstacles"""
grid[pos[0]][pos[1]].passable = False | 5,358,419 |
def find_best_margin(args):
""" return `best_margin / 0.1` """
set_global_seeds(args['seed'])
dataset = DataLoader(args['dataset'], args)
X_train, X_test, X_val, y_train, y_test, y_val = dataset.prepare_train_test_val(args)
results = []
for margin in MARGINS:
model = Perceptron(feature_... | 5,358,420 |
def get_user_balances(userAddress):
"""
:param userAddress:
:return:
"""
try:
data = get_request_data(request) or {}
from_block = data.get("fromBlock", int(os.getenv("BFACTORY_BLOCK", 0)))
ocean = Ocean(ConfigProvider.get_config())
result = ocean.pool.get_user_balanc... | 5,358,421 |
def unfold(raw_log_line):
"""Take a raw syslog line and unfold all the multiple levels of
newline-escaping that have been inflicted on it by various things.
Things that got python-repr()-ized, have '\n' sequences in them.
Syslog itself looks like it uses #012.
"""
lines = raw_log_line \
... | 5,358,422 |
def metis(hdf5_file_name, N_clusters_max):
"""METIS algorithm by Karypis and Kumar. Partitions the induced similarity graph
passed by CSPA.
Parameters
----------
hdf5_file_name : string or file handle
N_clusters_max : int
Returns
-------
labels : array of shape (n_sam... | 5,358,423 |
def test_puller_create_ok(started_puller):
"""
Create a PullerActor with a good configuration
"""
assert is_actor_alive(started_puller) | 5,358,424 |
def run(args):
"""Builds a training data set of physics model errors based on the
parameters supplied by the CLI.
:param args: The command line arguments
:type args: argparse.Namespace
"""
logger.info('Loading input DataFrame...')
input_df = pd.read_parquet(args.input_path)
logger.info(... | 5,358,425 |
def _mcs_single(mol, mols, n_atms):
"""Get per-molecule MCS distance vector."""
dists_k = []
n_atm = float(mol.GetNumAtoms())
n_incomp = 0 # Number of searches terminated before timeout
for l in range(0, len(mols)):
# Set timeout to halt exhaustive search, which could take minutes
r... | 5,358,426 |
def new_transaction():
"""
新的交易
:return:
"""
values = request.get_json()
# 检查 POST 请求中的字段
required = ['sender', 'recipient', 'amount']
if not all(k in values for k in required):
return 'Missing values', 400
# 创建新的交易
index = blockchain.new_transaction(values... | 5,358,427 |
async def get_favicon():
"""Return favicon"""
return FileResponse(path="assets/kentik_favicon.ico", media_type="image/x-icon") | 5,358,428 |
def geocentric_rotation(sphi, cphi, slam, clam):
"""
This rotation matrix is given by the following quaternion operations
qrot(lam, [0,0,1]) * qrot(phi, [0,-1,0]) * [1,1,1,1]/2
or
qrot(pi/2 + lam, [0,0,1]) * qrot(-pi/2 + phi , [-1,0,0])
where
qrot(t,v) = [cos(t/2), sin(t/2)*v[1], sin(t/2)*v[... | 5,358,429 |
def get_price_sma(
ohlcv: DataFrame,
window: int = 50,
price_col: str = "close",
) -> Series:
"""
Price to SMA.
"""
return pd.Series(
ohlcv[price_col] / get_sma(ohlcv, window),
name="Price/SMA{}".format(window),
) | 5,358,430 |
def map_to_closest(multitrack, target_programs, match_len=True, drums_first=True):
"""
Keep closest tracks to the target_programs and map them to corresponding
programs in available in target_programs.
multitrack (pypianoroll.Multitrack): Track to normalize.
target_programs (list): List of availabl... | 5,358,431 |
def train_naive(args, X_train, y_train, X_test, y_test, rng, logger=None):
"""
Compute the time it takes to delete a specified number of
samples from a naive model sequentially.
"""
# initial naive training time
model = get_naive(args)
start = time.time()
model = model.fit(X_train, y_tr... | 5,358,432 |
def helperFunction():
"""A helper function created to return a value to the test."""
value = 10 > 0
return value | 5,358,433 |
def app_config(app_config):
"""Get app config."""
app_config['RECORDS_FILES_REST_ENDPOINTS'] = {
'RECORDS_REST_ENDPOINTS': {
'recid': '/files'
}
}
app_config['FILES_REST_PERMISSION_FACTORY'] = allow_all
app_config['CELERY_ALWAYS_EAGER'] = True
return app_config | 5,358,434 |
def ts(timestamp_string: str):
"""
Convert a DataFrame show output-style timestamp string into a datetime value
which will marshall to a Hive/Spark TimestampType
:param timestamp_string: A timestamp string in "YYYY-MM-DD HH:MM:SS" format
:return: A datetime object
"""
return datetime.strptim... | 5,358,435 |
def align_to_screenshot(
text_block,
screenshot_path,
output_path=None,
show_text=True,
show_guide_lines=True,
show_bounding_boxes=False,
):
"""
Given a `eyekit.text.TextBlock` and the path to a PNG screenshot file,
produce an image showing the original screenshot overlaid with the ... | 5,358,436 |
def test_mock_given_message(uqcsbot: MockUQCSBot):
"""
Test !mock works for given text.
"""
uqcsbot.post_message(TEST_CHANNEL_ID, f'!mock {LONG_MESSAGE}')
messages = uqcsbot.test_messages.get(TEST_CHANNEL_ID, [])
assert len(messages) == 2
assert messages[-1]['text'].lower() == LONG_MESSAGE.l... | 5,358,437 |
def test_get_deck_private_saved(client: TestClient, deck1):
"""Unauthenticated users must not be able to access private decks via show_saved"""
response = client.get(f"/v2/decks/{deck1.id}", params={"show_saved": True})
assert response.status_code == status.HTTP_403_FORBIDDEN | 5,358,438 |
def test_list_unsigned_int_min_length_nistxml_sv_iv_list_unsigned_int_min_length_1_1(mode, save_output, output_format):
"""
Type list/unsignedInt is restricted by facet minLength with value 5.
"""
assert_bindings(
schema="nistData/list/unsignedInt/Schema+Instance/NISTSchema-SV-IV-list-unsignedIn... | 5,358,439 |
def boxes(frame, data, f, parameters=None, call_num=None):
"""
Boxes places a rotated rectangle on the image that encloses the contours of specified particles.
Notes
-----
This method requires you to have used contours for the tracking and run boxes
in postprocessing.
Parameters
--... | 5,358,440 |
def process_states(states):
"""
Separate list of states into lists of depths and hand states.
:param states: List of states.
:return: List of depths and list of hand states; each pair is from the same state.
"""
depths = []
hand_states = []
for state in states:
... | 5,358,441 |
def upload_county_names(url, gcs_bucket, filename):
"""Uploads county names and FIPS codes from census to GCS bucket."""
url_params = get_census_params_by_county(['NAME'])
url_file_to_gcs(url, url_params, gcs_bucket, filename) | 5,358,442 |
def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
"""
Perform uniform spatial sampling on the images and corresponding boxes.
Args:
images (tensor): images to perform uniform crop. The dimension is
`num frames` x `channel` x `height` x `width`.
size (int):... | 5,358,443 |
def plot_xr_complex_on_plane(
var: xr.DataArray,
marker: str = "o",
label: str = "Data on imaginary plane",
cmap: str = "viridis",
c: np.ndarray = None,
xlabel: str = "Real{}{}{}",
ylabel: str = "Imag{}{}{}",
legend: bool = True,
ax: object = None,
**kwargs,
) -> Tuple[Figure, Ax... | 5,358,444 |
def imread(filename, imread=None, preprocess=None):
"""Read a stack of images into a dask array
Parameters
----------
filename: string
A globstring like 'myfile.*.png'
imread: function (optional)
Optionally provide custom imread function.
Function should expect a filename a... | 5,358,445 |
def _set_mode_commands(emacs_state: Dict) -> List[str]:
"""Extract & set the current `-mode` commands."""
defined_commands = emacs_state.get(DEFINED_COMMANDS_KEY, [])
context.lists["user.emacs_mode_commands"] = _extract_mode_commands(defined_commands) | 5,358,446 |
def importPredictions_Tombo(infileName, chr_col=0, start_col=1, readid_col=3, strand_col=5, meth_col=4, baseFormat=1,
score_cutoff=(-1.5, 2.5), output_first=False, include_score=False, filterChr=HUMAN_CHR_SET,
save_unified_format=False, outfn=None):
"""
We... | 5,358,447 |
def recommend_with_rating(user, train):
"""
用户u对物品i的评分预测
:param user: 用户
:param train: 训练集
:return: 推荐列表
"""
rank = {}
ru = train[user]
for item in _movie_set:
if item in ru:
continue
rank[item] = __predict(user, item)
return rank.iteritems() | 5,358,448 |
def nl_to_break( text ):
"""
Text may have newlines, which we want to convert to <br />
when formatting for HTML display
"""
text=text.replace("<", "<") # To avoid HTML insertion
text=text.replace("\r", "")
text=text.replace("\n", "<br />")
return text | 5,358,449 |
def get_page_state(url):
"""
Checks page's current state by sending HTTP HEAD request
:param url: Request URL
:return: ("ok", return_code: int) if request successful,
("error", return_code: int) if error response code,
(None, error_message: str) if page fetching failed (timeout... | 5,358,450 |
def unique(list_, key=lambda x: x):
"""efficient function to uniquify a list preserving item order"""
seen = set()
result = []
for item in list_:
seenkey = key(item)
if seenkey in seen:
continue
seen.add(seenkey)
result.append(item)
return result | 5,358,451 |
def date_is_older(date_str1, date_str2):
"""
Checks to see if the first date is older than the second date.
:param date_str1:
:param date_str2:
:return:
"""
date1 = dateutil.parser.parse(date_str1)
date2 = dateutil.parser.parse(date_str2)
# set or normalize the timezone
target_t... | 5,358,452 |
def shorten_namespace(elements, nsmap):
"""
Map a list of XML tag class names on the internal classes (e.g. with shortened namespaces)
:param classes: list of XML tags
:param nsmap: XML nsmap
:return: List of mapped names
"""
names = []
_islist = True
if not isinstance(elements, (lis... | 5,358,453 |
def list_select_options_stream_points():
""" Return all data_points under data_stream """
product_uid = request.args.get('productID', type=str)
query = DataStream.query
if product_uid:
query = query.filter(DataStream.productID == product_uid)
streams_tree = []
data_streams = query.many(... | 5,358,454 |
def test_add_edit_token_with_wrong_swapped_for(globaldb):
"""Test that giving a non-existing swapped_for token in the DB raises InputError
This can only be unit tested since via the API, marshmallow checks for Asset existence already
"""
# To unit test it we need to even hack it a bit. Make a new token... | 5,358,455 |
def func2():
"""
:type: None
:rtype: List[float]
"""
return [math.pi, math.pi / 2, math.pi / 4, math.pi / 8] | 5,358,456 |
def get_playlist_name(pl_id):
"""returns the name of the playlist with the given id"""
sql = """SELECT * FROM playlists WHERE PlaylistId=?"""
cur.execute(sql, (pl_id,))
return cur.fetchone()[1] | 5,358,457 |
def weight(collection):
"""Choose an element from a dict based on its weight and return its key.
Parameters:
- collection (dict): dict of elements with weights as values.
Returns:
string: key of the chosen element.
"""
# 1. Get sum of weights
weight_sum = sum([value for va... | 5,358,458 |
def procyon(path,dirname):
"""
calls the procyon decompiler from command line
"""
process = subprocess.Popen(["java","-jar", common.rootDir + "/lib/procyon/procyon-decompiler-0.5.30.jar", path, "-o ", dirname+"2"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
try:
while True:
line = process.stdout.readli... | 5,358,459 |
def knnsearch(y, x, k) :
""" Finds k closest points in y to each point in x.
Parameters
----------
x : (n,3) float array
A point cloud.
y : (m,3) float array
Another point cloud.
k : int
Number of nearest neighbors one wishes to compute.
... | 5,358,460 |
def test_model_constraint():
""" A retrieval with just the model constraint should converge
to the model constraint. """
Grid0 = pyart.io.read_grid(pydda.tests.EXAMPLE_RADAR0)
""" Make fake model grid of just U = 1 m/s everywhere"""
Grid0.fields["U_fakemodel"] = deepcopy(Grid0.fields["corrected... | 5,358,461 |
def segmentation_gaussian_measurement(
y_true,
y_pred,
gaussian_sigma=3,
measurement=keras.losses.binary_crossentropy):
""" Apply metric or loss measurement incorporating a 2D gaussian.
Only works with batch size 1.
Loop and call this function repeatedly over each sa... | 5,358,462 |
def default_check_tput(exp, metrics, case, scores=default_target_score,
real_bw=0):
"""The default test case for tput metrics unless overridden by the user.
Scoring semantics: Suppose a test is N seconds long. Not all flows
necessarily start or end at the same time. However, we assum... | 5,358,463 |
def set_lr(optimizer, lr):
""" set learning rate """
for g in optimizer.param_groups:
g['lr'] = lr | 5,358,464 |
def load_AACHEN_PARAMS(AHCHEN_h5_file, log_file_indicator):
"""
This module extract parameters trainded with the framework https://github.com/rwth-i6/returnn
and the neural network proposed in the mdlsmt demo structure.
Args:
AHCHEN_h5_file: file in format hdf5 generated with https://github... | 5,358,465 |
def prep_doc_id_context( doc_id: str, usr_first_name: str, usr_is_authenticated: bool ) -> dict:
""" Preps context for record_edit.html template when a doc_id (meaning a `Citation` id) is included.
Called by views.edit_record() """
log.debug( 'starting prep_doc_id_context()' )
log.debug( f'doc_id, `... | 5,358,466 |
def request_pull(repo, requestid, username=None, namespace=None):
"""View a pull request with the changes from the fork into the project."""
repo = flask.g.repo
_log.info("Viewing pull Request #%s repo: %s", requestid, repo.fullname)
if not repo.settings.get("pull_requests", True):
flask.abort... | 5,358,467 |
def make_matrix(points: List[float], degree: int) -> List[List[float]]:
"""Return a nested list representation of a matrix consisting of the basis
elements of the polynomial of degree n, evaluated at each of the points.
In other words, each row consists of 1, x, x^2, ..., x^n, where n is the degree,
... | 5,358,468 |
def verify(request, token, template_name='uaccounts/verified.html'):
"""Try to verify email address using given token."""
try:
verification = verify_token(token, VERIFICATION_EXPIRES)
except VerificationError:
return redirect('uaccounts:index')
if verification.email.profile != request.u... | 5,358,469 |
def set_logger(logger: logging.Logger) -> None:
"""
Removes all other loggers, and adds stream_handler and file_handler to the given logger
This is being used for sanic logging, because for some weird reason sanic does not allow you
to pass in a custom logging object. Instead, you have to modify their ... | 5,358,470 |
def run_train(params: dict) -> Tuple[threading.Thread, threading.Thread]:
"""Train a network on a data generator.
params -> dictionary.
Required fields:
* model_name
* generator_name
* dataset_dir
* tile_size
* clf_name
* checkpoints_dir
* summaries_dir
Returns prefetch thr... | 5,358,471 |
def request(url, method='GET', headers=None, original_ip=None, debug=False,
logger=None, **kwargs):
"""Perform a http request with standard settings.
A wrapper around requests.request that adds standard headers like
User-Agent and provides optional debug logging of the request.
Arguments t... | 5,358,472 |
def AddDestAddressGroups(parser):
"""Adds a destination address group to this rule."""
parser.add_argument(
'--dest-address-groups',
type=arg_parsers.ArgList(),
metavar='DEST_ADDRESS_GROUPS',
required=False,
hidden=True,
help=(
'Dest address groups to match for this rul... | 5,358,473 |
def adjust_seconds_fr(samples_per_channel_in_frame,fs,seconds_fr,num_frame):
"""
Get the timestamp for the first sample in this frame.
Parameters
----------
samples_per_channel_in_frame : int
number of sample components per channel.
fs : int or float
sampling frequency.
... | 5,358,474 |
def create_parser():
"""
Construct the program options
"""
parser = argparse.ArgumentParser(
prog="xge",
description="Extract, transform and load GDC data onto UCSC Xena",
)
parser.add_argument(
"--version",
action="version",
version="%(prog)s {v}".format(... | 5,358,475 |
def add_header(unicode_csv_data, new_header):
"""
Given row, return header with iterator
"""
final_iterator = [",".join(new_header)]
for row in unicode_csv_data:
final_iterator.append(row)
return iter(final_iterator) | 5,358,476 |
def get_most_energetic(particles):
"""Get most energetic particle. If no particle with a non-NaN energy is
found, returns a copy of `NULL_I3PARTICLE`.
Parameters
----------
particles : ndarray of dtyppe I3PARTICLE_T
Returns
-------
most_energetic : shape () ndarray of dtype I3PARTICLE_... | 5,358,477 |
def parse_file(path):
"""Parses a file for ObjectFiles.
Args:
path: String path to the file.
Returns:
List of ObjectFile objects parsed from the given file.
"""
if sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# Assume Linux has GNU objdump. This ... | 5,358,478 |
def stack(tup, axis=0, out=None):
"""Stacks arrays along a new axis.
Args:
tup (sequence of arrays): Arrays to be stacked.
axis (int): Axis along which the arrays are stacked.
out (cupy.ndarray): Output array.
Returns:
cupy.ndarray: Stacked array.
.. seealso:: :func:`n... | 5,358,479 |
def winning_pipeline(mydata,mytestdata,myfinalmodel,feature_selection_done = True,myfeatures =None,numerical_attributes = None):
"""
If feature _selection has not been performed:
Function performs Cross Validation (with scaling within folds) on the data passed through.
Scales the data with Robu... | 5,358,480 |
def calc_single_d(chi_widths, chis, zs, z_widths, z_SN, use_chi=True):
"""Uses single_m_convergence with index starting at 0 and going along the entire line of sight.
Inputs:
chi_widths -- the width of the comoving distance bins.
chis -- the mean comoving distances of each bin.
zs -- the mean re... | 5,358,481 |
def test_info__pkg_not_found(reset_sys_argv, capfd):
"""Ensure the error message when a package is not found."""
sys.argv = ["py-info", "some-random-non-existant-package"]
commands.info()
out, err = capfd.readouterr()
assert not out
assert "The package some-random-non-existant-package was not ... | 5,358,482 |
def ppo(
client, symbol, timeframe="6m", col="close", fastperiod=12, slowperiod=26, matype=0
):
"""This will return a dataframe of Percentage Price Oscillator for the given symbol across the given timeframe
Args:
client (pyEX.Client): Client
symbol (string): Ticker
timeframe (string... | 5,358,483 |
def ellipse(x, y, width, height, fill_color="", stroke_color="", stroke_width=-1):
"""Draws an ellipse on the given coordinate with the given width, height and color
Args:
x (float): Horizontal coordinate.
y (float): Vertical coordinate.
width (float): Width of the ellipse.
heig... | 5,358,484 |
def getRandomCoin():
""" returns a randomly generated coin """
coinY = random.randrange(20, int(BASEY * 0.6))
coinX = SCREENWIDTH + 100
return [
{'x': coinX, 'y': coinY},
] | 5,358,485 |
def is_success(msg):
"""
Whether message is success
:param msg:
:return:
"""
return msg['status'] == 'success' | 5,358,486 |
def scrape_data(url):
"""
scrapes relevant data from given url
@param {string} url
@return {dict} {
url : link
links : list of external links
title : title of the page
description : sample text
}
"""
http = httplib2.Http()
try:
status, response = http.request(url)
except Exception as e:
return None... | 5,358,487 |
def list_strip_comments(list_item: list, comment_denominator: str = '#') -> list:
"""
Strips all items which are comments from a list.
:param list_item: The list object to be stripped of comments.
:param comment_denominator: The character with which comment lines start with.
:return list: A cleaned... | 5,358,488 |
def guess_number(name):
"""User defined function which performs the all the operations and prints the result"""
guess_limit = 0
magic_number = randint(1, 20)
while guess_limit < 6: # perform the multiple guess operations and print output
user_guess = get_input... | 5,358,489 |
def start(start_running_time, coins_for_benchmark, df_simulation, positions_history, capital_history):
"""
function "get statistics" was build before in version one. and this function arrange the dataframe to
be sent to "get statistics" correctly. acc = [{date_time,capital},..],benchmark = [{date_time,capit... | 5,358,490 |
def writerformat(extension):
"""Returns the writer class associated with the given file extension."""
return writer_map[extension] | 5,358,491 |
def index_like(index):
"""
Does index look like a default range index?
"""
return not (isinstance(index, pd.RangeIndex) and
index._start == 0 and
index._stop == len(index) and
index._step == 1 and index.name is None) | 5,358,492 |
def zplsc_c_absorbtion(t, p, s, freq):
"""
Description:
Calculate Absorption coeff using Temperature, Pressure and Salinity and transducer frequency.
This Code was from the ASL MatLab code LoadAZFP.m
Implemented by:
2017-06-23: Rene Gelinas. Initial code.
:param ... | 5,358,493 |
def contrastive_img_summary(episode_tuple, agent, summary_writer, train_step):
"""Generates image summaries for the augmented images."""
_, sim_matrix = agent.contrastive_metric_loss(
episode_tuple, return_representation=True)
sim_matrix = tf.expand_dims(tf.expand_dims(sim_matrix, axis=0), axis=-1)
with s... | 5,358,494 |
def main():
"""Main program driving measurement of benchmark size"""
# Establish the root directory of the repository, since we know this file is
# in that directory.
gp['rootdir'] = os.path.abspath(os.path.dirname(__file__))
# Parse arguments using standard technology
parser = build_parser()
... | 5,358,495 |
def estimate_quintic_poly(x, y):
"""Estimate degree 5 polynomial coefficients.
"""
return estimate_poly(x, y, deg=5) | 5,358,496 |
def add(A, B):
"""
Return the sum of Mats A and B.
>>> A1 = Mat([[1,2,3],[1,2,3]])
>>> A2 = Mat([[1,1,1],[1,1,1]])
>>> B = Mat([[2,3,4],[2,3,4]])
>>> A1 + A2 == B
True
>>> A2 + A1 == B
True
>>> A1 == Mat([[1,2,3],[1,2,3]])
True
>>> zero = Mat([[0,0,0],[0,0,0]])
>>> B... | 5,358,497 |
def hindu_lunar_event(l_month, tithi, tee, g_year):
"""Return the list of fixed dates of occurrences of Hindu lunar tithi
prior to sundial time, tee, in Hindu lunar month, l_month,
in Gregorian year, g_year."""
l_year = hindu_lunar_year(
hindu_lunar_from_fixed(gregorian_new_year(g_year)))
da... | 5,358,498 |
def plot_featdrop_single(drop_curve, chance_level, font=20, title_font=30, title="Place Holder", single=True, verbose=False):
"""Plots a single feature dropping cure
Parameters:
-----------
single: bool
if True it will make a new figure within the function, defaults to True
""... | 5,358,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.