content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def make_feature_scale_factors():
"""Saves a dictionary of features->scale_factors such that each feature array can be mapped into [0,1]."""
X, y = make_X_and_y()
sqm = make_sqm_X()
scale_factors = {
"indoor_temp": np.max(X[:,:,0]),
"outdoor_temp": np.max(X[:,:,1]),
"gas_kwh": np... | 5,343,600 |
async def help_json(ctx: commands.Context, indent: int = 4) -> None:
"""
Create a dictionary with all the commands, convert it to a json file ans send it to the author
:param indent: (Optional) The number of spaces to indent the file.
"""
# Create the dictionary with the commands
commands_dict... | 5,343,601 |
def load_AUXTEL_image(image): # pragma: no cover
"""Specific routine to load AUXTEL fits files and load their data and properties for Spectractor.
Parameters
----------
image: Image
The Image instance to fill with file data and header.
"""
image.my_logger.info(f'\n\tLoading AUXTEL imag... | 5,343,602 |
def manhattan_loadings(
iteration,
gtf,
loadings,
title=None,
size=4,
hover_fields=None,
collect_all=False,
n_divisions=500,
):
"""modify hail manhattan plot"""
palette = [
'#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8... | 5,343,603 |
def check_para_vaild():
""" 检查参数options中的键(key)是否合法 """
global g_isdst
para_keylist = g_opts_dict.keys()
# 判断传入的参数的key是否是在给定的列表范围内
# (子列表判断)
if not is_sublist(para_keylist,g_all_optskey):
logger.error("Unknown options key found,please check...")
sys.exit(1)
# 判断是否包含必要的option
... | 5,343,604 |
def write():
"""Used to write the page in the app.py file"""
st.title("Italian Regional Cases")
cn.DATE_SPANS()
st.markdown(cn.HORIZONTAL_RULE, unsafe_allow_html=True)
regions = [
"Lazio", # 12
"Puglia", # 16
"Sicilia", # 19
"Basilicata", # 17
... | 5,343,605 |
def mirror_z(table, label):
"""Mirror the z-component of the vector.
Parameters
----------
label: string containing the name of the column you want to convert
"""
c = table.updDependentColumn(label)
for i in range(c.size()):
c[i] = opensim.Vec3(c[i][0], c[i][1], -c[i][2]) | 5,343,606 |
def preprocess_point(p, C):
"""Preprocess a single point (a clip).
WARN: NAN-preserving
Arguments:
p {ndarray} -- shape = (variable, C.joint_n, C.joint_d)
C {DDNetConfig} -- A Config object
Returns:
ndarray, ndarray -- X0, X1 to input to the net
"""
assert p.shape[1... | 5,343,607 |
def html_decode_raw(client, args):
"""
Same as html_decode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, html_decode_helper, copy=False)) | 5,343,608 |
def test_aggregate_per_slice(dummy_metrics):
"""Test extraction of metrics aggregation per slice: Selected slices"""
agg_metric = aggregate_slicewise.aggregate_per_slice_or_level(dummy_metrics['with float'], slices=[3, 4],
perslice=True,
... | 5,343,609 |
def link_to_existing_user_by_email_if_backend_is_trusted(backend, details, user=None, *args, **kwargs):
"""Return user entry with same email address as one returned on details."""
if user or not _is_trusted_email_backend(backend):
return
email = details.get('email')
if email:
# try to ... | 5,343,610 |
def _monthlyfile(yr, path, ppath, force, layer, ANfn, latmax, latmin, lonmin, lonmax):
"""
Function to proccess the monthl;y data into an annual file
args:
yr: int
year
path: str
dir to do the work in
ppath: str
processed path
"""
# ========== get the web address ==========
address = "ftp://anon-... | 5,343,611 |
def ingest_sessions(session_csv_path='./user_data/session/sessions.csv',
skip_duplicates=True):
"""
Inserts data from a sessions csv into corresponding session schema tables
By default, uses data from workflow_session/user_data/session/
:param session_csv_path: relative path of s... | 5,343,612 |
def get_global_threshold(image_gray, threshold_value=130):
""" 이미지에 Global Threshold 를 적용해서 흑백(Binary) 이미지객체를 반환합니다.
하나의 값(threshold_value)을 기준으로 이미지 전체에 적용하여 Threshold 를 적용합니다.
픽셀의 밝기 값이 기준 값 이상이면 흰색, 기준 값 이하이면 검정색을 적용합니다.
이 때 인자로 입력되는 이미지는 Gray-scale 이 적용된 2차원 이미지여야 합니다.
:param image_gray:
... | 5,343,613 |
def get_batch(src_gen, trgt_gen, batch_size=10):
"""
Return a batch of batch_size of results as in get_rotated_src_target_spirals
Args:
batch_size (int): number of samples in the batch
factor (float): scaling factor for the spiral
Return:
[torch.tensor,torch.tensor]: src and target b... | 5,343,614 |
def compute_crop_parameters(image_size, bbox, image_center=None):
"""
Computes the principal point and scaling factor for focal length given a square
bounding box crop of an image.
These intrinsic parameters are used to preserve the original principal point even
after cropping the image.
Args:... | 5,343,615 |
def input_fn_builder(input_file, seq_length, num_labels, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_lengt... | 5,343,616 |
def test_gf_matching_with_exception(get_mock):
"""Test GoogleFinance match with network exception
"""
gf_matcher = GoogleFinanceNameMatcher()
symbols = gf_matcher.match_by('apple', sleep=0)
assert get_mock.call_count == 3
assert symbols['apple'][0][0] == 'Apple Inc.'
assert symbols['apple'][... | 5,343,617 |
def get_user_by_username(username):
"""Return User by username"""
try:
return User.objects.get(username=username)
except User.DoesNotExist:
return None | 5,343,618 |
def init_logger() -> None:
"""Initialize logger, set log format and the base logging level."""
global logger
logger.remove()
logger.add(
sink=sys.stdout,
level=logging.INFO,
format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | " "<level>{level}</level> | " "<level>{message}</level... | 5,343,619 |
def get_xyz_to_rgb_matrix(name):
"""
XYZ to RGB の Matrix を求める。
DCI-P3 で D65 の係数を返せるように内部関数化した。
"""
if name != "DCI-P3":
xyz_to_rgb_matrix = RGB_COLOURSPACES[name].XYZ_to_RGB_matrix
else:
rgb_to_xyz_matrix\
= calc_rgb_to_xyz_matrix(RGB_COLOURSPACES[DCI_P3].primaries,
... | 5,343,620 |
def find_bordering_snapnums(
snap_times_gyr,
dGyr=.005,
tmin=None,
tmax=None):
""" """
## handle default maximum time
tmax = snap_times_gyr[-1] if tmax is None else tmax
## handle default minimum time
if tmin is None:
tmin = snap_times_gyr[0]
## remove dGyr so that... | 5,343,621 |
def maxIterationComb(N,k,l):
"""
title::
maxIterationComb
description::
Compute N!/k!l!(N-k-l)! (max iterations).
attributes::
N
Number of targets (graph size)
k
Number of human patrollers
l
Number of drones
returns::... | 5,343,622 |
def test_fail_retrieve_tokens(oauth2_connector, secrets_keeper):
"""
It should fail ig the stored state does not match the received state
"""
secrets_keeper.save('test', {'state': JsonWrapper.dumps({'token': 'the_token'})})
with pytest.raises(AssertionError):
oauth2_connector.retrieve_token... | 5,343,623 |
def create_project_details_list (project):
"""makes a projects details section for the html
Parameters
----------
project: HeatRecovery
A HeatRecovery object thats run function has been called
Returns
-------
dict
with values used by summary
"""
try:
costs =... | 5,343,624 |
def compute_cluster_top_objects_by_distance(precomputed_distances,
max_top_number=10,
object_clusters=None):
"""
Compute the most representative objects for each cluster
using the precomputed_distances.
Parameters
... | 5,343,625 |
def get_rpm_package_list():
""" Gets all installed packages in the system """
pkgstr = subprocess.check_output(['rpm', '-qa', '--queryformat', '%{NAME}\n'])
return pkgstr.splitlines() | 5,343,626 |
def validate_ints(*args):
""" validates that inputs are ints only """
for value in args:
if not isinstance(value, int):
return False
return True | 5,343,627 |
def smooth_l1_loss(y_true, y_pred):
"""
Computes the smooth-L1 loss.
Parameters
----------
y_true : tensor
Ground-truth targets of any shape.
y_pred : tensor
Estimates of same shape as y_true.
Returns
-------
loss : tensor
The loss, sumed over ... | 5,343,628 |
def get_class_occurrences(layer_types):
"""
Takes in a numpy.ndarray of size (nb_points, 10) describing for each point of the track the types of clouds identified at each of the 10 heights
times counting the number of times 8 type of clouds was spotted vertically.
and returns occrrences (binary) as th... | 5,343,629 |
def test_stream_targets_properties_specific():
"""
Tests an API call to get a specific stream target property by id
"""
response = stream_targets_instance.properties(stream_target_id, property_id)
assert isinstance(response, dict)
assert 'property' in response | 5,343,630 |
def parse_duration(datestring):
"""
Parses an ISO 8601 durations into a float value containing seconds.
The following duration formats are supported:
-PnnW duration in weeks
-PnnYnnMnnDTnnHnnMnnS complete duration specification
Years and month are not supported, values must... | 5,343,631 |
def knn(position, data_set, labels, k):
"""
k-近邻算法
:param position: 待分类点
:param data_set: 数据样本
:param labels: 标签集合
:param k: 取值
:return: 所属标签
"""
distance_list = []
for index, item in enumerate(data_set):
distance_list.append((
labels[index],
math.... | 5,343,632 |
def plot2Dseparation(u, file, **kwargs):
"""
Return nothing and saves the figure in the specified file name.
Args:
cmap: matplotlib cmap. Eg: cmap = "seismic"
lvls: number of levels of the contour. Eg: lvls = 100
lim: min and max values of the contour passed as array. Eg: lim = [-0.5, 0.5]
file: Name of the... | 5,343,633 |
def _cals(raw):
"""Helper to deal with the .cals->._cals attribute change."""
try:
return raw._cals
except AttributeError:
return raw.cals | 5,343,634 |
def generate_mlsag(message, pk, xx, kLRki, index, dsRows, mg_buff):
"""
Multilayered Spontaneous Anonymous Group Signatures (MLSAG signatures)
:param message: the full message to be signed (actually its hash)
:param pk: matrix of public keys and commitments
:param xx: input secret array composed of... | 5,343,635 |
def irnn_data_iterator(X, y, batch_size, math_engine):
"""Slices numpy arrays into batches and wraps them in blobs"""
def make_blob(data, math_engine):
"""Wraps numpy data into neoml blob"""
shape = data.shape
if len(shape) == 2: # data
# Wrap 2-D array into blob of (BatchWi... | 5,343,636 |
def naive_forecast(series, steps_ahead=3, freq='D', series_name='naive'):
"""
Function fits data into the last available observation value.
INPUT:
:param series: pandas Series of data,
:param steps_ahead: number of steps into the future to predict, default is 3,
:param freq: (str) representati... | 5,343,637 |
async def delete_original_path(request):
"""
After the processing of the whole data source, this api can be used to delete the original zip
correspoding to a particular username
"""
username = request.args.get("username")
if not username:
raise APIBadRequest("Username for this datasou... | 5,343,638 |
def demonstration():
"""
This will render a template that displays all of the form objects if it's
a Get request. If the use is attempting to Post then this view will push
the data to the database.
"""
#this parts a little hard to understand. flask-wtforms does an implicit
#call each time yo... | 5,343,639 |
def display_guessed_text(X: str, options: Dict, schemas: Optional[List[str]] = None):
"""Displays all the guessed values of TEXT for a given DNA (``X``), and for a list of schemas."""
st.info(dedent("""### Guess ❓ DNA ➡️ TEXT"""))
with st.container():
col1, col2 = st.columns([6, 1])
with col... | 5,343,640 |
def show_current_task():
"""
显示当前任务正在运行的任务
:return:
"""
try:
current_user_name = session["user_name"]
current_user = RedisService.get_user(current_user_name)
current_task = TaskService.get_working_tasks(user_id=current_user.id)[0]
if current_task:
hook_ru... | 5,343,641 |
def access_image(access_code:str):
"""
下载图像
post header : {
Content-Type: application/json,
access_token: access_token from vans-token-manager
client_id: client_id from vans-token-manager conf. create by developers.
}
:return:
"""
try:
from rsc.service.Ima... | 5,343,642 |
def decorate_xyi_ax(ax: Axes, tax: TernaryAxesSubplot, node_counts: Dict[str, int]):
"""
Decorate xyi plot.
"""
xcount, ycount, icount = _get_xyi_counts(node_counts)
text = "\n".join(
(
f"n: {xcount+ycount+icount}",
f"X-nodes: {xcount}",
f"Y-nodes: {ycount... | 5,343,643 |
def workaround_issue_20(handler):
"""
Workaround for
https://github.com/pytest-dev/pytest-services/issues/20,
disabling installation of a broken handler.
"""
return hasattr(handler, 'socket') | 5,343,644 |
def item_count(sequences, sequence_column_name):
"""
input:Dataframe sequences
"""
item_max_id = sequences[sequence_column_name].map(max).max()
return int(item_max_id) | 5,343,645 |
def bare_stft(x: Tensor, padded_window: Tensor, hop_size: int) -> Tensor:
"""Compute STFT of real 1D signal.
This function does not handle padding of x, and the window tensor.
This function assumes fft_size = window_size.
Args:
x: [..., n_sample]
padded_window: [fft_size], a window padde... | 5,343,646 |
def IsDragResultOk(*args, **kwargs):
"""IsDragResultOk(int res) -> bool"""
return _misc_.IsDragResultOk(*args, **kwargs) | 5,343,647 |
def set_config(args):
"""
get config from file and reset the config by super parameter
"""
configs = 'configs'
cfg = getattr(__import__(configs, fromlist=[args.config_file]),
args.config_file)
config = cfg.res50_config()
config['data_url'] = DATA_PATH
config['log_dir']... | 5,343,648 |
def excel_convert_xls_to_xlsx(xls_file_path='',xlsx_file_path=''):
"""
Converts given XLS file to XLSX
"""
try:
# Checking the path and then converting it to xlsx file
from xls2xlsx import XLS2XLSX
if os.path.exists(xls_file_path):
# converting xls to xlsx
... | 5,343,649 |
def save_info(filename, infos):
""" ===============
Save .text info
===============
Args:
:param: filename(str): filename(test.txt)
:param: infos(list): <teiHeader></heiHeader> contents
"""
filename = (os.getcwd() + filename).replace(".txt", "")
file = op... | 5,343,650 |
def load_model(fn=None):
"""Load the stored model.
"""
if fn is None:
fn = os.path.dirname(os.path.abspath(__file__)) + \
"/../models/model_default.h5"
return keras.models.load_model(fn) | 5,343,651 |
def aws_s3_bucket_objects(var):
"""
Creates aws_s3_bucket_object resources for all files in the given
source directory. This is using the "collections" API to create
a reusable function that generates resources.
"""
# Inputs.
yield variable.bucket()
yield variable.prefix(default="")
... | 5,343,652 |
def element_wise(counter_method):
"""This is a decorator function allowing multi-process/thread input.
Note that this decorator should always follow the decorator 'tag_maker'.
"""
def _make_iterator(*args):
"""Make a compound iterator from a process iterator and
a thread one.
N... | 5,343,653 |
def get_datacite_dates(prefix):
"""Get sumbitted date for DataCite DOIs with specific prefix"""
doi_dates = {}
doi_urls = {}
url = (
"https://api.datacite.org/dois?query=prefix:"
+ prefix
+ "&page[cursor]=1&page[size]=500"
)
next_link = url
meta = requests.get(next_li... | 5,343,654 |
def rate_answer():
"""
**Rates an already given answer**
**Args:**
* json:
* {"insight" : String with the name of the Insight
* "paper_id" : String with the paper_id which is in our case the completet link to the paper
* "upvote" : Boolean if the answe... | 5,343,655 |
def get_ip():
"""
Query the ipify service (https://www.ipify.org) to retrieve this machine's
public IP address.
:rtype: string
:returns: The public IP address of this machine as a string.
:raises: ConnectionError if the request couldn't reach the ipify service,
or ServiceError if there ... | 5,343,656 |
def update_plot(p1, p2, arrow, txt, ax, fig, reset_points, line):
"""
Given a line with an agent's move and the current plot, update
the plot based on the agent's move.
"""
l = line.strip()
if 'Agent score' in l:
txt.remove()
txt = plt.text(2, 33, 'Agent Score: {0:.2f}'.format(f... | 5,343,657 |
def upload_file_view(request):
"""Upload file page and retrieve headers"""
data = {}
global ROW_COUNT
if request.method == "GET":
return render(request, "pages/upload-file.html", data)
try:
if request.FILES:
csv_file = request.FILES['csv_file']
request.sessio... | 5,343,658 |
def get_user_by_login_identifier(user_login_identifier) -> Optional[UserSchema]:
"""Get a user by their login identifier.
:param str user_login_identifier: The user's login identifier, either their \
``email`` or ``display_name`` are valid inputs
:return: The discovered user if they exist
:rty... | 5,343,659 |
def main():
""" This program has RVR drive around in different directions.
"""
try:
rvr.wake()
# Give RVR time to wake up
time.sleep(2)
rvr.reset_yaw()
rvr.raw_motors(
left_mode=RawMotorModesEnum.forward.value,
left_duty_cycle=128, # Valid... | 5,343,660 |
def org_profile_post_delete_callback(sender, instance, **kwargs):
"""
Signal handler to delete the organization user object.
"""
# delete the org_user too
instance.user.delete()
safe_delete('{}{}'.format(IS_ORG, instance.pk)) | 5,343,661 |
def decode_fixed64(buf, pos):
"""Decode a single 64 bit fixed-size value"""
return decode_struct(_fixed64_fmt, buf, pos) | 5,343,662 |
def test_nameconflict(testdir):
"""tests that a name conflict raises an exception"""
testdir.makeconftest(dedent("""
from pytest_pilot import EasyMarker
colormarker = EasyMarker('color', mode="extender", allowed_va... | 5,343,663 |
def from_xfr(xfr, zone_factory=Zone, relativize=True):
"""Convert the output of a zone transfer generator into a zone object.
@param xfr: The xfr generator
@type xfr: generator of dns.message.Message objects
@param relativize: should names be relativized? The default is True.
It is essential that ... | 5,343,664 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the Smile switches from a config entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
entities: list[PlugwiseSwitchEntity] = []
for device_id... | 5,343,665 |
def test_read_csv():
""" blah """
text = io.StringIO('exercise,reps\nBurpees,20-50\nSitups,40-100')
assert list(read_csv(text)) == [('Burpees', 20, 50), ('Situps', 40, 100)] | 5,343,666 |
def compare_sql_datetime_with_string(filter_on, date_string):
"""Filter an SQL query by a date or range of dates
Returns an SQLAlchemy `BinaryExpression` that can be used in a call to
`filter`.
`filter_on` should be an SQLAlchemy column expression that has a date or
datetime value.
`date_stri... | 5,343,667 |
def get_users():
"""get_users() -> Fetch all users in the database"""
connect() # Connect
cursor.execute("SELECT * FROM users") # Select all users
item = cursor.fetchall()
users = []
for user in item:
users.append(format_user(user)) # Format the users
disconnect()
ret... | 5,343,668 |
def get_decoder_self_attention_bias(length):
"""Calculate bias for decoder that maintains model's autoregressive property.
Creates a tensor that masks out locations that correspond to illegal
connections, so prediction at position i cannot draw information from future
positions.
Args:
length: int length o... | 5,343,669 |
def copy_run_set_files(run_desc, desc_file, run_set_dir, run_dir, agrif_n=None):
"""Copy the run-set files given into run_dir.
The YAML run description file (from the command-line) is copied.
The IO defs file is also copied.
The file path/name of the IO defs file is taken from the :kbd:`output`
sta... | 5,343,670 |
def rollout_discrete(
x_grid: Tensor,
idx: Union[int, Tensor],
model: Model,
best_f: Union[float, Tensor],
bounds: Tensor,
quadrature: Union[str, Tuple] = "qmc",
horizon: int = 4,
num_y_samples: int = 10,
):
"""
continuous domain rollout, expectation estimated using (quasi) Mont... | 5,343,671 |
def get_accumulative_accuracies(test_loaders, taskcla, result_file, network_cls='resnet32'):
""" Confusion matrix with progressively more classes considered """
iter_model = iter_task_models(network_cls, taskcla, result_file)
accuracies = np.zeros((len(taskcla), len(taskcla)))
classes_so_far = 0.
fo... | 5,343,672 |
def readout_oper(config):
"""get the layer to process the feature asnd the cls token
"""
class Drop(object):
"""drop class
just drop the cls token
"""
def __init__(self, config):
if 'ViT' in config.MODEL.ENCODER.TYPE:
self.token_num = 1
... | 5,343,673 |
def report_asl(wsp):
"""
Generate a report page about the input ASL data
"""
page = wsp.report.page("asl")
page.heading("ASL input data")
md_table = [(key, value) for key, value in wsp.asldata.metadata_summary().items()]
page.table(md_table)
try:
# Not all data can generate a PWI... | 5,343,674 |
def stream_n_messages(request, n):
"""Stream n JSON messages"""
n = int(n)
response = get_dict(request, 'url', 'args', 'headers', 'origin')
n = min(n, 100)
def generate_stream():
for i in range(n):
response['id'] = i
yield json.dumps(response, default=json_dumps_defa... | 5,343,675 |
def read_covid():
"""Read parsed covid table"""
return pd.read_csv(_COVID_FILE, parse_dates=["date"]) | 5,343,676 |
def install_pip(python=sys.executable, *,
info=None,
downloaddir=None,
env=None,
upgrade=True,
**kwargs
):
"""Install pip on the given Python executable."""
if not python:
python = getattr(info, 'executable',... | 5,343,677 |
def set_config(cfg):
"""Picks up the settings from the config files and automatically decides between using Local vs AWS DynamoDB"""
if cfg.db.service == 'docker':
print("Running with Local DynamoDB...")
db_path = cfg.get('db').get('path') or None
User.Meta.host = db_path
else:
... | 5,343,678 |
def treat_deprecations_as_exceptions():
"""
Turn all DeprecationWarnings (which indicate deprecated uses of
Python itself or Numpy, but not within Astropy, where we use our
own deprecation warning class) into exceptions so that we find
out about them early.
This completely resets the warning fi... | 5,343,679 |
def define_network(*addr):
"""gives all network related data or host addresses if requested
addr = tuple of arguments netaddr/mask[nb of requested hosts]
"""
if len(addr) == 2:
# provides list of host-addresses for this subnet
# we do this by calling the generator host_g
host_g... | 5,343,680 |
def init_anim() -> List:
"""Initialize the animation."""
return [] | 5,343,681 |
def keep_digits(txt: str) -> str:
"""Discard from ``txt`` all non-numeric characters."""
return "".join(filter(str.isdigit, txt)) | 5,343,682 |
def test_repr(pip_Package):
"""Verifies the result returned from Package.__repr__()"""
assert pip_Package.__repr__() == "<Package(name=pip)>" | 5,343,683 |
def camel_case_split(identifier):
"""Split camelCase function names to tokens.
Args:
identifier (str): Identifier to split
Returns:
(list): lower case split tokens. ex: ['camel', 'case']
"""
matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier)
... | 5,343,684 |
def _ensure_meadowrun_sqs_access_policy(iam_client: Any) -> str:
"""
Creates a policy that gives permission to read/write SQS queues for use with
grid_task_queue.py
"""
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html#IAM.Client.create_policy
ignore_boto3_err... | 5,343,685 |
def get_subset(dframe, strata, subsetno):
"""This function extracts a subset of the data"""
df_subset = pd.DataFrame(columns=list(dframe)) #initialize
df_real = dframe.dropna() #get rid of nans
edges = np.linspace(0, 1, strata+1) #edges of data strata
for i in range(0, strata):
df_temp = df_... | 5,343,686 |
def create_logger(name: str) -> logging.Logger:
"""Create logger, adding the common handler."""
if name is None:
raise TypeError("name is None")
logger = logging.getLogger(name)
# Should be unique
logger.addHandler(_LOGGING_HANDLER)
return logger | 5,343,687 |
def main():
"""Entry point of Kalliope program."""
# create arguments
parser = argparse.ArgumentParser(description='Kalliope')
parser.add_argument("action", help="[start|gui|install|uninstall]")
parser.add_argument("--run-synapse",
help="Name of a synapse to load surrounded ... | 5,343,688 |
def _create_tree(lib_path, tree_object):
"""
Iterate through the elements in the tree_object and create a node module for each one.
:param lib_path: full path to the library where all nodes will be created
:param tree_object: ElementTree instance for the xml_file
:return: None
"""
for eleme... | 5,343,689 |
def do_mount(devpath, mountpoint, fstype):
"""Execute device mount operation.
:param devpath: The path of mount device.
:param mountpoint: The path of mount point.
:param fstype: The file system type.
"""
try:
if check_already_mounted(devpath, mountpoint):
return
mo... | 5,343,690 |
def say_hello():
""" Say hello """
return utils.jsonify_success({
'message': 'Hello {}! You are logged in.'.format(current_user.email)
}) | 5,343,691 |
def relu(x):
"""The rectifier activation function. Only activates if argument x is
positive.
Args:
x (ndarray): weighted sum of inputs
"""
# np.clip(x, 0, np.finfo(x.dtype).max, out=x)
# return x
return np.where(x >= 0, x, 0) | 5,343,692 |
def k_shortest_paths(G, source, target, k=1, weight='weight'):
"""Returns the k-shortest paths from source to target in a weighted graph flux_graph.
Parameters
----------
flux_graph : NetworkX graph
source : node
Starting node
target : node
Ending node
k : integer, o... | 5,343,693 |
def allowed_file(filename):
"""
Check the image extension
Currently, only support jpg, jpeg and png
"""
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS | 5,343,694 |
def __best_tour(previous: int, prices: np.ndarray, excess: float, best_solution: set, visited: np.ndarray) -> int:
""" Ищем в лучшем туре """
search = __search(best_solution, previous)
node, alpha = -1, maxsize
for edge in search:
temp = edge[0] if edge[0] != previous else edge[1]
if not... | 5,343,695 |
def classical_gaussian_kernel(k, sigma):
"""
A function to generate a classical Gaussian kernel
:param k: The size of the kernel, an integer
:param sigma: variance of the gaussian distribution
:return: A Gaussian kernel, a numpy array of shape (k,k)
"""
w = np.linspace(-(k - 1) / 2, (k - 1)... | 5,343,696 |
def collection_to_csv(collection):
"""
Upload collection value to CSV file
:param collection: Collection
:return: None
"""
print("collection_to_csv")
final_df = pd.DataFrame()
try:
dict4json = []
n_documents = 0
for document in collection.get():
result... | 5,343,697 |
def validate_hatch(s):
"""
Validate a hatch pattern.
A hatch pattern string can have any sequence of the following
characters: ``\\ / | - + * . x o O``.
"""
if not isinstance(s, six.text_type):
raise ValueError("Hatch pattern must be a string")
unique_chars = set(s)
unknown = (u... | 5,343,698 |
def iot_hub_service_factory(cli_ctx, *_):
"""
Factory for importing deps and getting service client resources.
Args:
cli_ctx (knack.cli.CLI): CLI context.
*_ : all other args ignored.
Returns:
iot_hub_resource (IotHubClient.iot_hub_resource): operational resource for
... | 5,343,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.