content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def update_yt_to_mlab_vector(field, ds, xkey, ykey, zkey,
cube_slice=np.s_[:,:,:]):
"""
Update a mayavi field based on a yt dataset.
Parameters
----------
field : mayavi vector field
The field to update.
ds : yt dataset
The dataset to get the data f... | a83326339f3aa13259a3102d1eac570de6399190 | 56,700 |
def get_colour_map_list():
"""Return the list of the available colormaps."""
return sorted(plt.cm.datad) | a70d1e8af694c7df8dbed8e1087f2096fe42b572 | 56,701 |
def forgot_password():
"""
If NOTIFICO_PASSWORD_RESET is enabled and Flask-Mail is configured,
this view allows you to request a password reset email. It also
handles accepting those tokens.
"""
# Because this functionality depends on Flask-Mail and
# celery being properly configured, we def... | cb00ffed8b7cdaa36dc433dfdc0a0c5d4fa7d42b | 56,702 |
def get_bound_mask(y_bound_mask):
"""
this method gets a bound_mask matrix
and returns the masks for each keypoint
:type y_bound_mask: int
: param y_bound_mask: a matrix of shape (#batch, #kpts)
where for each keypoint one
values is given:
0: no... | dcd363874c9a48ce9c3811a6c3b4f066eeab5d69 | 56,703 |
from typing import List
from typing import Tuple
from typing import Optional
import os
def _read_existing_krb5_conf_file_lines(locations: List[str]) -> Tuple[Optional[str], List[str]]:
""" Read in existing krb5 configuration file lines and return them """
for loc in locations:
if os.path.isfile(loc):
... | 3238c0cf35e699e02b4267fd80039ef9d4c26335 | 56,704 |
import torch
import tqdm
def runBestNet(train_dl, test_dl, best_test, outputPath , nfold , class_len , net, feature_name , test_len ):
""" Load the best net and test it on your test set
Attributes:
train_dl, test_dl: train(test) sets
best_test: the testing accuracy of best model
outp... | b217f80240044fcb3c0d05d92a41cc23e348cc09 | 56,705 |
from typing import Optional
import torch
def fit_circle_in_3d(
points,
*,
n_points: int = 0,
angles: Optional[torch.Tensor] = None,
offset: Optional[torch.Tensor] = None,
up: Optional[torch.Tensor] = None,
) -> Circle3D:
"""
Simple best fit circle to 3D points. Uses circle_2d in the
... | 305d4d76602c03037fe12832d62ccd32ea3ae1bd | 56,706 |
def predicate_contains_hello(x):
"""Predicate True when 'hello' is in value."""
return 'hello' in x | 884ef0a9a925865d5bd9093d52f1c248e498aa80 | 56,707 |
def index(request):
"""
index home page
:param request:
:return:
"""
# PC 版、手机版适配
user_agent = parse(request.META.get('HTTP_USER_AGENT', ''))
pc = user_agent.is_pc
# 判断是否登录用户
user = get_login_user(request)
# 默认的渲染列表,区分是否登录用户
if user is None:
sub_feeds = get_visi... | 42ff2de48bb7bc7e1de1413cd7c1590b5510fda4 | 56,708 |
def operation_name_check(operation_name, check_info, conditions, message_list):
"""
[概要]
OPERATION_NAMEのバリデーションチェックを行う
[引数]
operation_name : OPERATION_NAME
check_info : チェック情報
conditions : 条件名
message_list : メッセージリスト
[戻り値]
message_list : メッセージリスト
"""
if opera... | 13b0776dee4804bf80b6497a80f4fe3572bdddd6 | 56,709 |
import random
def get_message(response_type):
"""
Return a random string message from a given type
"""
if response_type in chat_responses:
return random.choice(chat_responses[response_type])
return random.choice(chat_responses['no_answer']) | 1472a3cb8bad09e050ad663a28f33f0833fada7e | 56,710 |
from typing import Union
def BM1(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
"""
J. Wojdyła, Z. Szkutnik, "Nonparamteric confidence bands in Wicksell's problem", Statistica Sinica28(2018), 93-113
"""
return 0.55 * 252 * (1 - x) ** 6 * x ** 2 + 0.45 * 252 * (1 - x) ** 2 * x ** 6 | 0acc6a80ec9f77c32cb6a4ac89d2cd244943cf61 | 56,711 |
def get_recent_trading_stocks():
"""获取最近一期处于交易状态的股票清单"""
df = fetch_minutely_prices()
return sorted(df.query('成交量>0').index.str.slice(2, 8).values) | 60649320b562fcc1e8db2d2c3557449e38c6068b | 56,712 |
def get_tile_url(xtile, ytile, zoom):
"""
Return a URL for a tile given some OSM tile co-ordinates
"""
return "http://tile.openstreetmap.org/%d/%d/%d.png" % (zoom, xtile, ytile) | 20af9f5b4065d96c285e6c4e5c64123f0343b659 | 56,713 |
def split_into_words_by_char_count(s, chunk_size, max_from_end=None):
"""
Split a string into an array of strings each of length at most chunk_size.
Try to split on whitespace if possible (possibly resulting in chunks of size
less than chunk_size), except if it would make the last word longer
than m... | ae3391536bd6e92f0c8ae9ce5cce76865485f689 | 56,714 |
import torch
import random
def train(input_variable, lengths, target_variable, mask, max_target_len, encoder, decoder, SOS,
encoder_optimizer, decoder_optimizer, batch_size, teacher_forcing_ratio, clip, device):
"""
Training function for one iteration
"""
# Zero gradients
encoder_optimiz... | 0919450361631d198e640d61f44795ae1a5f7e8d | 56,715 |
def set_arguments(self, _id):
"""
Set arguments
"""
args = list()
cwl_wf_url = {
"name": self.cwl_static_keys[0],
"description": self.cwl_static_keys[1],
"help": self.cwl_static_keys[1] + " for " + _id,
"type": self.cwl_static_keys[2],
"value": self.cwl_wf,
... | 7965d86438a43a44f40784805a09c4320233b2be | 56,716 |
import json
import torch
def invocations():
"""Do an inference on a single batch of data. In this sample server, we take data as CSV, convert
it to a pandas data frame for internal use and then convert the predictions back to CSV (which really
just means one prediction per line, since there's a single col... | 2523cc39b2b973069df643efaeaba2c07d779971 | 56,717 |
def get_implementation(plugin_identifier):
"""
Get a plugin implementation instance for the given plugin identifier.
The map of identifier to plugin class lives in `settings.DEMOCRACY_PLUGINS`.
:param plugin_identifier: Plugin identifier string
:return: An object instance deriving from `Plugin`.
... | d7dde285325a028fe69cd67ecf5f395e5eb81330 | 56,718 |
def step040():
"""
Matching, db <-> elastic, db is master
"""
logger.logMessage('Begin: matching work files')
sKey = ''
mKey = ''
def readFile(f):
line = f.readline().rstrip()
if line == '':
key = 'ZZZZZZZZZZZZZZZZZZZZZZZZZ'
return None,key
els... | bb212df93fa57e8e442f5b91b32cd716556e8f5d | 56,719 |
import json
def json_to_dict(json_file_path):
"""
Convert a .json file to a Python dictionary.
Parameters
----------
json_file_path: str
Path of the JSON file
Returns
-------
dictionary: dict
The original JSON file as a Python dictionary
"""
with open(json_fi... | d8ef47ab43c3477212795e795690bad4081e0321 | 56,720 |
def remove_outliers(df_raw):
"""
Removes outliers
:param df_raw:
:return:
"""
diff_secs_col = f.col("dropoff_datetime").cast("long") - f.col("pickup_datetime").cast("long")
df_raw = df_raw.withColumn("trip_duration_m", diff_secs_col / 60.0)
df_raw = df_raw.filter((f.col("tip_amount") >= ... | 4633c2ea512cd1fe92ad17a41d60775576604244 | 56,721 |
def get_audits():
"""Get OS hardening security limits audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
# Ensure that the /etc/security/limits.d directory is only writable
# by the root user, but others can execute and read.
audits.append(Direc... | f60d5b974b00ae3558dc0684a43f751930441472 | 56,722 |
def save_input(filename, values):
"""
# Save the input/printing parameters of the EFI measurement.
#
# Input
# =====
# `filename`: File name of the input parameters to save to.
# `values`: The input parameters to save, expect shape (`n_input`,).
"""
return np.savetxt(filename, values... | b8ad858cc97399d47d2ec111989453ced1cedcc7 | 56,723 |
from typing import Tuple
def send_initial_inference_request(
predict_service: prediction_service_pb2_grpc.PredictionServiceStub,
inputs: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]
) -> core.NetworkOutput:
"""Initial inference for the agent, used at the beginning of MCTS."""
input_ids, input_typ... | f49bd289c81cd4bc4adda3a32e5a649530a29031 | 56,724 |
def create_app() -> Flask:
"""Create a new API application."""
app = Flask('preview')
app.json_encoder = PreviewEncoder
app.config.from_pyfile('config.py')
Base(app)
auth.Auth(app)
# Set up the API.
app.register_blueprint(routes.api)
register_error_handlers(app)
# Add WSGI mid... | 09a38736f716c953b4a0500e862c0c44d32d38cb | 56,725 |
def list_all_usecase():
"""
Lists down all the Use cases that are supported in Feature Recommender module.
Returns
-------
DataFrame of all the supported usecases as part of feature exploration/recommendation
"""
odf_uni = df_input_fer.iloc[:, 3].unique()
odf = pd.DataFrame(odf_uni, col... | 3f2922bd759b75882014c375c01d68fb2ae60d30 | 56,726 |
def format_bases(bases):
"""
Generate HTML that colours the bases in a string.
Args:
bases: A string containing a genetic sequence.
Returns:
An HTML string.
"""
formatted = ''
for b in bases:
formatted += '<span class="base-{}">{}</span>'.format(b,b)
return forma... | a94f34a53178ceb5dd1640eaa8897a128c7c4d67 | 56,727 |
def zscores(a):
"""Converts a to zscores in each col, i.e. subtract mean and div by stdev."""
return (a - mean(a,axis=0)) / std(a, axis=0) | 2750b5575eb24d16cf5d65b27d23f123078968a4 | 56,728 |
import math
import random
def grid_template_list():
"""
List of lengths. Values can be a length, percentage, factor, etc
Examples:
grid-template-columns: 1093px 255px 1825px 12px 400px;
grid-template-columns: 1093px 10% 3fr;
"""
value_types = [_p_length_px, _percent, _p_length_fr]... | 4915ad3ce2ff3502c246b107787a0f1a6b6a7682 | 56,729 |
def Get_K_to_q(porb, asini):
"""
Returns the K_to_q conversion factor given an
orbital period and an observed asini.
The K is for the "primary" whereas asini is that
of the "secondary" star.
porb: Orbital period in seconds.
asini: Projected semi-major axis in lt-s.
>>> K_to_q = Get_K_t... | 47ca141173e07f02a417cf653c07abf22705572d | 56,730 |
def calculate_ECE(bin_means, proportion_correct, all_hist):
"""
Calculates Expected Calibration Error (Naeini et al. 2015). This is simply
the sum of the weighted average of each bin's accuracy / confidence difference.
Input:
bin_means - list means for the 10 bins
proportion_correct - l... | a51080be40c532c052a51c51132fc64193fc13a7 | 56,731 |
def compute_elipticities(xx, yy, xy):
"""Compute star elipticities from second momments."""
denom = xx + 2. * N.sqrt(xx * yy - N.square(xy))
e1 = (xx - yy) / denom
e2 = 2.0 * xy / denom
return e1, e2 | aa1b3d324d4b2fc20236ddb2f5a88d976f2e2d4f | 56,732 |
def solow_steady_state(g, n, s, alpha, delta):
"""
Steady-state level of capital stock (per unit effective labor).
Parameters
----------
g : float
Growth rate of technology.
n : float
Growth rate of the labor force.
s : float
Savings rate. Must satisfy `0 < s < 1`.
... | 51f34393761430388b91f9ff43a4eb0453d5d22d | 56,733 |
def daily_return(close, fillna=False):
"""Daily Return (DR)
Args:
close(pandas.Series): dataset 'Close' column.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
dr = (close / close.shift(1, fill_value=close.mean())) - 1
dr *= 10... | 98dc664d8f7aa2184637e02db1a8103a03af753d | 56,734 |
def get_vm_macs(vm_name, conn=LIBVIRT_CONNECTION):
"""Get VM mac addresses along with source network names"""
if not vm_exists(vm_name, conn):
return {}
vm_xml = _virsh_dumpxml(vm_name, conn)
return _get_vm_macs(vm_xml) | d81289894e26c082f77e7b587efe1b510ef55480 | 56,735 |
from typing import Callable
from typing import Union
from typing import Literal
from typing import Tuple
from typing import List
import itertools
import uuid
from pathlib import Path
import re
def __make_daybyday_interactive_timeline(
df: pd.DataFrame,
*,
geo_df: geopandas.GeoDataFrame,
value_col: str... | 73ef2901f44cd791f320a2167315e7d7a0481556 | 56,736 |
def pgettext(context, message, **variables):
"""Translates `message` given the `context`"""
return _translate('pgettext', context, message, **variables) | 8d159d6d1f0a9231f4d7b14c46c99bc02db5982b | 56,737 |
def create_credentials(account, username, password):
"""
Function to create new user credentials
Args:
account: Account type
username: New username
password: New password
"""
new_credential = Credential(account, username, password)
return new_credential | a237dea82d7a92d2e0306be9fb8c6d5f50577162 | 56,738 |
def match_dtypes(training_df,testing_df,target_name='TARGET'):
"""
This function converts dataframe to match columns in accordance with the
training dataframe.
"""
for column_name in training_df.drop([target_name],axis=1).columns:
testing_df[column_name]= testing_df[column_name].astype(tra... | c8fc3c6beb1a50c2d02c357355a12055543f4f87 | 56,739 |
def solver_2(dictionary, alphabet, words_to_solve, solved_letters = [], solved_numbers = [], print_progress = True, debug = False):
"""
This function aims to solve a CodeWord puzzle.
This function, in contrast to solver_1, considers
all the words in the puzzle together.
This fu... | 0be088b39cae8e1d6b0e170d4a2a6762ca97e51f | 56,740 |
import time
def get_page_by_random() -> Article:
"""Gets the contents and metadata of a random Wikipedia article.
:returns: the Article object representing the Wikipedia article.
"""
article_id, title = None, None
page_html = None
url = None
while page_html is None:
article_id... | 46710d7ad6f76f41d59bcfb060eb3cbde855bbce | 56,741 |
def _get_fixture_from_dict_fixtures(fixture):
"""Get value of fixture by key (fixture name) from dictionary of
executed fixtures."""
global dict_executed_fixtures
# extend executed fixtures using exist fixture in snapshot representation
if fixture.endswith("_snapshot"):
origin_obj = _get_fixture_from_dict... | 1bdd1b97b99f90cb84c7fa7c33cba82cfee92537 | 56,742 |
def variance_contrib(var_comp_lc, var_comp_qc, var_comp_cp, vz):
"""
Convert actual variance components to percent contributions (best if used
in conjunction with ``variance_components`` function).
Parameters
----------
var_comp_lc : array
The actual variance components from the 1st... | 490dc46afc1547b2f8c5e59bf506600451f80f2f | 56,743 |
def get_fitted_model(X_train, y_train) -> RandomForestClassifier:
""" Returns model trained on the provided data
:param X_train: training dataset for the model
:param y_train: labels for the training dataset
:return: Fitted Random Forest classifier model
"""
model = RandomForestClassifier(
... | 300432a11fc1cfe3eadc62dbf43f144020e231b8 | 56,744 |
def get_services(services):
"""
Get all services from the response and make the comma-separated string.
:param services: List of services.
:return: comma-separated list.
"""
return ', '.join(services) | 6c965dff4c85f772b41d10e12170547f156ee86e | 56,745 |
import torch
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Callable
def training_components(model: str, classifier_type: str, n_classes: int, learning_rate: float,
activation_function: str, l2_penalty: float,
device:... | efdfe82537e6c65e6ded46ffacc7d8f4f2b455df | 56,746 |
from typing import Union
def request_photo_and_submit(update: Update, context: CallbackContext) -> Union[str, int]:
"""заносит информацию о пользователе в БД"""
if update.message.text:
utils.send_message(update=update, context=context,
text="Необходимо отправить фото для сво... | 9ffefe475102552d47eb9d52212e27ac4ecd7eef | 56,747 |
def neck_resistance(mu, gamma, thcon, cp, nl, nr, rho, afreq):
"""
This function computes the neck resistance in an HR using the forulation
presented in Var der Aa (2010) eqs 2.6 and 2.7 in page 10.
Parameters
----------
mu (float): Dynamical viscosity of air (Ns / m2)
gamma (float):... | d17f7b923bdf1c773aa1d37ec2060d953d8151da | 56,748 |
def ref_and_res_to_scores(fileName=None, refPuncFileName=None, resPuncFileName=None):
"""
Get the scores by taking the reference punctuation and the restored punctuation
while skipping the first and the last word to generate scores
:param fileName: Consistent filename in format X_reference_punc.txt and ... | f7479288b504c6b2fbb42d2cc66d218946fc938f | 56,749 |
async def async_setup_entry(
hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities
):
"""Set up Picnic sensor entries."""
picnic_coordinator = hass.data[DOMAIN][config_entry.entry_id][CONF_COORDINATOR]
# Add an entity for each sensor type
async_add_entities(
PicnicSensor(picnic... | 3e26411db97999384cbb5cbd3ad4e127bec632f4 | 56,750 |
def invert_geostreamfunction(lapPhi, dims, BCs=['fixed', 'fixed'],
coords='latlon', f0=None, beta=None, optArg=None,
undef=np.nan, mxLoop=5000, tolerance=1e-6,
cal_flow=False, printInfo=True, debug=False):
"""
Inverting geost... | 5431f18da8829efbd92e2eeb18223a1b6f4e7233 | 56,751 |
def check_for_default_value_for_missing_params(missing_params, method_params):
"""
:param missing_params: Params missing from Rule
:param method_params: Params defined on method, which could have default value for missing param
[{
'label': 'action_label',
'name': 'action_parameter',
'fiel... | bad583976d4c88af93540c9d64f7b0711fd24e12 | 56,752 |
def svn_diff_hunk_reset_modified_text(*args):
"""svn_diff_hunk_reset_modified_text(svn_diff_hunk_t hunk)"""
return _diff.svn_diff_hunk_reset_modified_text(*args) | ef9dd4bf4afa8acc55ecea0fc783e6a4487a5215 | 56,753 |
import random
import string
def mock_tweet():
"""Generate some random tweet text."""
count = random.randint(70, 140)
return ''.join([random.choice(string.ascii_letters) for _ in range(count)]) | 1a8f9937408acaaaf2534be0721a8e3203525eb3 | 56,754 |
def davidson_solver(A, neigen, tol=1E-6, itermax = 1000, jacobi=False):
"""Davidosn solver for eigenvalue problem
Args :
A (numpy matrix) : the matrix to diagonalize
neigen (int) : the number of eigenvalue requied
tol (float) : the rpecision required
itermax (int) : ... | 655eb8f86373775d0dbc09c4bc2ada093b00408a | 56,755 |
def date_comparison(input_series, output_series):
""" Compare the start and end dates for the input and output series and
obtain the dates that completes the output series
:param input_series:
:param output_series:
:return:
"""
first_input = input_series['data']['first']
last_input = in... | 5910c2e3552d84a15e0b03bfb1dd97cf0cec0d66 | 56,756 |
def get_arc_info(a):
"""Get edge information about arc to draw it using graphviz
:param a: arc
:return: edge_id, src, target, edge_attribs
"""
assert isinstance(a, petrinet.Arc)
src_id, target_id = str(a.src._id), str(a.target._id)
_id = '{}->{}'.format(src_id, target_id)
attribs = {
... | 3c38d3984ae5312678cb39dcb287c1b36cce279b | 56,757 |
def Domain(min, max) -> type:
"""
Create a Type restricted to the specified domain
:param min: The lower bound of the domain
:param max: The upper bound of the domain
:return: A ValidatedType representing the specified domain
"""
return ValidatedType('Domain_{}-{}'.format(min, max), int, lam... | 576c455339ac6076dd7b3796aec2f85a58b71b77 | 56,758 |
import json
def parse_json(s, **kwargs):
"""Parse a JSON string into a dict."""
try:
nb_dict = json.loads(s, **kwargs)
except ValueError:
# Limit the error message to 80 characters. Display whatever JSON will fit.
raise NotJSONError(("Notebook does not appear to be JSON: %r" % s)[... | 3a7e6db0799f85cb0dd616a9fed2a2c11e3153f3 | 56,759 |
def longitud_palabra(palabra, n):
"""
-Recibe: una palabra y un numero entero positivo(n)
-Devuelve:
- True, si la palabra tiene longitud n
- False, en caso contrario
"""
return len(palabra) == n | 33065b4302cee42d3921d7b75344c12c43d54cd6 | 56,760 |
def get_iqr_mask(sub_arr, index, iqr_fact = 1.5, within=True):
"""
"""
# Mask to include only events within the IQR
q25, q75 = _get_iqr(sub_arr)
iqr = abs(q75 - q25)
if within:
mask = np.where((sub_arr > (q25 - iqr_fact * iqr)) & (sub_arr < (q75 + iqr_fact * iqr)))
... | 2dad376b3cc5d38c27903b57f29460b671c30e1f | 56,761 |
def retrieve_activities(start_time, end_time, activity_name):
"""
Retrieves all activities of a user between the time period or
based on requested appliance
"""
try:
if activity_name == "all":
# Retrieves all activities - for usage/wastage reports
records = ActivityLo... | 5261221bba397c5def80c69bfb91045db4d2e44e | 56,762 |
def run_cmd(command):
"""
:param command
:return A map based on pass / fail run info
"""
logger.info("Running: {0}".format(command))
try:
ret = subprocess.check_call(command, shell=True, env=os.environ)
return {'success': True, 'return': ret, 'exception': None}
except subproc... | 413e49f1afd485cc695ceb7ae3683a3572fb5472 | 56,763 |
import math
def ph(concentration):
"""Returns the pH from the hydronium ion concentration."""
return -math.log(concentration) | 46e59ed147006ac4cc3aaefea5b10c015a9e18b9 | 56,764 |
def user_home(request):
"""
用户主页
:param request:
:return:
"""
all_wechat_user = WeChatUser.objects.all()
reply = {
"wechat_users":all_wechat_user,
"username": request.user.username,
'active_class': 2
}
return render(request,"newadmin/user_home.html",reply) | ea68822474d7624dcbc14b881e08ca137e3603b3 | 56,765 |
import match as matchmod # avoid circular import issues
def subrepo(mctx, x):
"""``subrepo([pattern])``
Subrepositories whose paths match the given pattern.
"""
# i18n: "subrepo" is a keyword
getargs(x, 0, 1, _("subrepo takes at most one argument"))
ctx = mctx.ctx
sstate = sorted(ctx.subst... | 10f2f5798d516d7f87a2bc20965f2e8437ddeac8 | 56,766 |
def _app_or_default(app=None):
"""Returns the app provided or the default app if none.
The environment variable :envvar:`CELERY_TRACE_APP` is used to
trace app leaks. When enabled an exception is raised if there
is no active app.
"""
if app is None:
return getattr(_tls, "current_app",... | 4a5425ce8cb66ec95eaf970d965e4cb16811e3bc | 56,767 |
def add_details(img, screen_img, text, has_vision, has_finger, model_time):
""" add details to the screen image.
Args:
img : current cv2 read image.
screen_img : original cv2 read device image.
text : current text.
has_vision : bool
has_finger : b... | 8abfed6f079835ab5a4c8d78c67f72acf798e7b6 | 56,768 |
def migration_delete(context, id):
"""Deletes specified source."""
return db.migration_delete(context, id) | 359932913e0c857152066b4214c5cbd474e78924 | 56,769 |
def build_model(
voca_size=29331,
hidden_size=512,
lstm_layers_num=2,
batch_size=10,
max_epochs=200000,
retrain=False,
dump=False
):
"""
train a model with mini-batch gradient descend
"""
model = None
if not retrain:
try:
f... | 8752153088baf4c70c37f1a83dc06a2f0a88de1e | 56,770 |
from typing import Any
from typing import Dict
from typing import List
import tqdm
import os
def get_lightfm_predictions(
recommender: Any,
sparse_train: csr_matrix,
test: pd.DataFrame,
top_k: int,
split_test_users_into: int,
) -> Dict[int, List[int]]:
"""
get recommendations given a Light... | 079bbeeb3f6afbb5ae7bf5c041adb8b34d32037a | 56,771 |
def map_value_to_RGB_string(value: float) -> str:
"""Support function to join mapping value and converting to Ploty string"""
return create_RGB_string(map_value_to_RGB(value)) | b7a2d08bf9dcdbe3192f6ed88a12a02d2bf6fecd | 56,772 |
import torch
def rgb2hsv(rgb:Tensor):
"""Compute luminance of an RGB image.
Args:
rgb (tensor): rgb image (shape:(H,W,C))
Returns:
gray(tensor): gray-scale image(shape:(H,W))
Examples:
>>> import cv2
>>> img=cv2.cvtColor(cv2.imread('../../images/cat.jpg'),cv2.COLOR... | c3d203f15f1a1448698be423c1348460daaa096b | 56,773 |
def main():
""" диспетчер """
global B
print (f"Привет. Это игра в животных")
B = {}
while sess() and (input("\nПродолжаем? (да/нет) ")[0] == "д"): pass
return 0 | f04c271fb8e3f6fb56ec573554b601be84715c63 | 56,774 |
def reviews_with_id(review_id=None):
"""
reviews route to handle http methods for given review by ID
"""
review_obj = storage.get('Review', review_id)
if request.method == 'GET':
if review_obj is None:
abort(404, 'Not found')
return jsonify(review_obj.to_json())
... | 0473c01bc346b84b263951ade4af73304bc350f6 | 56,775 |
def log_linear_transform(timeSeries, alpha):
"""Returns a time series where {x, y(x)} becomes
{x, y'(x) = log y(x) + alpha x + c}"""
startPoint = timeSeries[0,0]
transform = map(lambda x,y: np.log(y) - alpha * (x-startPoint), timeSeries[:,0],timeSeries[:,1])
return np.transpose([timeSeries[:,0], np... | 1aa7c2c59707abc3f9c886ac53543b9d40925e79 | 56,776 |
def snap_PL(l: list, start: float = None, stop: float = None,
num_dims: int = None) -> list:
"""
Given a list `l` of PersLandscapeGrid types, convert them to a list
where each entry has the same start, stop, and num_dims. This puts each
entry of `l` on the same grid, so they can be added, av... | 6ddbff1021351a90918c966e5d750c89e417d526 | 56,777 |
def construit_AD_aleatoire(LSet,epsilon, nbatt):
""" LSet : LabeledSet
epsilon : seuil d'entropie pour le critère d'arrêt
"""
if(entropie(LSet) <= epsilon):
un_arbre= ArbreBinaire()
un_arbre.ajoute_feuille(classe_majoritaire(LSet))
else:
un_arbre= ArbreBinai... | 7f5d2bd32783054b280bf392cffad6f518bc861a | 56,778 |
def ms_nikud(key):
"""
Emulate the old Microsoft Windows behavior:
Unshifted - like a US keyboard with CAPS locked
Shifted - like level 1, except the top row gets the old-standard nikud
"""
ref_char = key.ref_chars[1]
unshifted = ref_char.upper()
try:
shifted = old_si1452_nikud[r... | fc26a4848b7061abb44bda3ff10a155ca83b57b5 | 56,779 |
import pathlib
import click
def cli(input, output, debug, max_workers):
"""Convert epub files to mobi.
If INPUT is a directory it converts all the epub files in a directory tree to mobi.
IF INPUT is an epub file it converts the file to mobi.
"""
if not debug:
logger.disable('epub2mobi')... | 598d12e24c2418265a3651a0b5d02aa5cb3e339f | 56,780 |
def wait_for_ready(restype, name, timeout=300, exit_on_err=False, _result_dict=None):
"""
Wait {timeout} for resource to be complete/ready/active.
Args:
restype: type of resource, which can be "build", "dc", "deploymentconfig"
name: name of resource
timeout: time in secs to wait for... | 56671a2e6b6f716f2dcbf3f8fc66ba91497cd9ea | 56,781 |
import os
def lasgrid(strPathInLAS, strPathOutASC, strAdlSwitches = None):
""" Function lasgrid
args:
strPathInLAS = input LAS file
strPathOutASC = output grid
strAdlSwitches = optional additional switches
Command Syntax:
"""
strSwitches = ''
if st... | fba8579b9e48f3c79d5d62e6311e97477ea54972 | 56,782 |
def hash_file(upload_context):
"""
Function run by HashFileCommand to calculate a file hash.
:param upload_context: PathData: contains path to a local file to hash
:return HashData: result of hash (alg + value)
"""
path_data = upload_context.params
hash_data = path_data.get_hash()
return... | 3819e9617e5726cf4178a8382eb22b0ec8bd7da0 | 56,783 |
def can_make_ransom_note(magazine, ransom):
"""
Checks if you can make a ransom note out of a magazine.
:param magazine:
The array of words in the magazine
:param ransom:
The array of words in the ransom note
:return:
True: You can make a ransom note out of the magazine
... | 00ce49f627eb28686c8ba2fe852f244e3eb94c86 | 56,784 |
import struct
import ctypes
def encipher(v, k):
"""
TEA coder encrypt 64 bits value, by 128 bits key,
QQ uses 16 round TEA.
http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html .
>>> c = encipher('abcdefgh', 'aaaabbbbccccdddd')
>>> b2a_hex(c)
'a557272c538d3e96'
"""
n=16 #qq use 16
delta = 0x9e3... | 57d01a534f645f2464d16e90201c2ed1d37c77b9 | 56,785 |
import os
def get_task_trackers(properties=None, hadoop_conf_dir=None, offline=False):
"""
Get the list of task trackers in the Hadoop cluster.
Each element in the returned list is in the ``(host, port)`` format.
``properties`` is passed to :func:`run_cmd`.
If ``offline`` is True, try getting the list of ... | acda1acc7926d24b668556a4828aa9d35f4e1842 | 56,786 |
def get_engine(db_url):
"""Connect to the database and engine
:param db_url: Database URL to connect to
:return: Database engine
"""
check_db_url(db_url)
return create_engine(db_url) | e1cc89a6e12c98ffedde194bd3e7aead5652f504 | 56,787 |
def get_attr_of_pset(_id, ifc_file):
""" Get all attributes of an instance by given Id
param _id: id of instance
return: dict of dicts of attributes
"""
dict_psets = {}
try:
defined_by_type = [x.RelatingType for x in ifc_file[_id].IsDefinedBy if x.is_a("IfcRelDefinesByType")]
... | 6de5772ee0b86894c0986a631c20042751e0eb3e | 56,788 |
from unittest.mock import call
def connect(srv_addr=None):
"""
load dbus-module into PA, lookup address and connect to the dbus interface
"""
# load dbus-module if not loaded already
if call('pactl list modules short | grep module-dbus-protocol', shell=True) == 1:
print('load dbus-module into PA')
check_c... | ffe9de3b8c14ff5208517773990a1c07416a2ace | 56,789 |
def transform_log_event(log_group, log_stream, event):
""" Turns the message into JSON if it isn't already, recognizing standard logging
formats; adds tracking fields.
"""
message = event.get('message', '').strip()
result = try_parse_json(message)
if not result:
result = try_pars... | 94634ba504118d4fc5ad9cdc19709fb76ae334d6 | 56,790 |
def read_FASTA(filename, SplitHeader=True):
""" Reads FastA file and returns a list of tuples, where first
part is a list of header elements and second seq as a string
read_FASTA('seqfile.fa', SplitHeader=True)
[(['gi', '1114567', 'gb', 'NC_00245'],
'ATATAGGCGCTTGGTGCGCGGCGGGCGCGGCTAGCAGCAC... | 4a641a709d32bf80d0c1cfe590653c55e12f2c5d | 56,791 |
import time
def timestamp2array(timestamps, t):
"""
把时间戳的序列中的每一个时间戳转成特征数组,考虑了星期和小时,
时间戳: numpy.datetime64('2013-07-01T00:00:00.000000000')
Args:
timestamps: 时间戳序列
t: 一天有多少个时间步
Returns:
np.ndarray: 特征数组,shape: (len(timestamps), ext_dim)
"""
vec_wday = [time.strptim... | 7f44c98cc94a43f30f80a8e3fd5cc45376c4f62c | 56,792 |
def active_matrix_from_angle(basis, angle):
"""Compute active rotation matrix from rotation about basis vector.
Parameters
----------
basis : int from [0, 1, 2]
The rotation axis (0: x, 1: y, 2: z)
angle : float
Rotation angle
Returns
-------
R : array-like, shape (3, ... | c007e8ab45c96fcf7a5f7c4af8ef0d3f51898750 | 56,793 |
def rebuild_paral_results(results):
"""Rebuild the correct way to store the results."""
scores = [results[i][0] for i in range(len(results))]
best_pars_info = [results[i][1] for i in range(len(results))]
times = [results[i][2] for i in range(len(results))]
return scores, best_pars_info, times | ae7a1ab996c49053332702b44482bc1b440aeee1 | 56,794 |
def create_device(name: str, device_type: xcrun.simctl.device_type.DeviceType, runtime: xcrun.simctl.runtime.Runtime):
"""Create a new device, returning the identifier."""
command = 'create "%s" "%s" "%s"' % (name, device_type.identifier, runtime.identifier)
device_id = _run_command(command)
# The devi... | 4a9045dd17bc87548cf61821f6ae398a89902e86 | 56,795 |
from typing import Dict
def retrieval_results_to_str(results: Dict[str, float], name: str):
""" retrieval results string """
return ("{:7s} | {:.3f} | {:.3f} | {:.3f} | {:.3f} | {:5.1f} | "
"{:5.1f} | {:6.3f}").format(name, *[results[a] for a in EVALKEYS]) | 24b805223c75ce9b0c2e678061a0d1d351b0ab69 | 56,796 |
import logging
import subprocess
def run_sandbox(game_name: str, seed: int, output_data_dir: str) -> int:
"""
Run an instance of the sandbox.
:param game_name: the name of the game
:param seed: the seed for the random module
:param output_data_dir: the name of the directory for the output data
... | cbe7413b890f5fb3e1c309c2551934632c637968 | 56,797 |
def format_tag(organization, standard, version, tag_name=None):
"""
Format a YAML tag.
"""
result = 'tag:{0}:{1}/{2}/'.format(
organization, standard, version)
if tag_name is not None:
result += tag_name
return result | 743ee05c37b4be8ef1bb6e995641f2641c5df95d | 56,798 |
from typing import Any
from typing import Tuple
def _validate_input(val: Any, args: 'ApplyMixtureArgs'
) -> Tuple[Any, 'ApplyMixtureArgs', bool]:
"""Validate args input and determine if we are operating on a
density matrix or a state vector.
"""
is_density_matrix = False
val_qi... | db4355d6f2f67272b10e918bb26e1d724d2a378f | 56,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.