content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import subprocess
def get_rpm_package_list():
""" Gets all installed packages in the system """
pkgstr = subprocess.check_output(['rpm', '-qa', '--queryformat', '%{NAME}\n'])
return pkgstr.splitlines() | 3ffddefe7e3859f4bc76ae5581b89338c376e03f | 3,649,000 |
def validate_ints(*args):
""" validates that inputs are ints only """
for value in args:
if not isinstance(value, int):
return False
return True | e56ebf78e072731188b2c8282289d307fcfaabdf | 3,649,001 |
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 all elements f... | dcf18b7d14feecdbc8b6637ccc3d35ff1880f9d2 | 3,649,002 |
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... | 20c611089a50751e6a6b1d0ebaedc02474b04443 | 3,649,003 |
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... | 4fce243684fd2305198ae49693327a110f781a1d | 3,649,004 |
import math
from functools import reduce
import operator
from typing import Counter
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(... | 137f87c6a63fbafd3140694386dfd418108ad5b9 | 3,649,005 |
def _cals(raw):
"""Helper to deal with the .cals->._cals attribute change."""
try:
return raw._cals
except AttributeError:
return raw.cals | a08273a559b780022c04fe5d5d60a71c600fd481 | 3,649,006 |
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... | 5a6b6726d3d0f78929b2551b8720bfbbb39471eb | 3,649,007 |
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... | 1b64edb39ab986d2e850ec5329fb2ed8ae5cd136 | 3,649,008 |
import os
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 ... | d92379c3fa1f58656a059029fb6555fce298ccbc | 3,649,009 |
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... | 17e798069d40bf5644b0ca0b4ffbd9ecea53aafd | 3,649,010 |
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... | 09e0077232343e46db606b9a3642bfb5d6b17a69 | 3,649,011 |
from rsc.service.ImageService import ImageService
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.
}
:r... | d1ac9efd9e4ba7c7fb9f63d2f0d188e09367fee9 | 3,649,012 |
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') | 20d688aedad9e771362d97ad9cac391e7dbfac32 | 3,649,013 |
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) | 9bcb64ff3389ef34ed297bca4f55b4de66ac5966 | 3,649,014 |
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... | ccefbdc55478de91640a322735dd02f87a185578 | 3,649,015 |
def IsDragResultOk(*args, **kwargs):
"""IsDragResultOk(int res) -> bool"""
return _misc_.IsDragResultOk(*args, **kwargs) | 87e4c1968b3e5d7adbdc4cfb393481fca647beba | 3,649,016 |
import os
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
confi... | 22ac7d7c0562a5098a8e32fa4b27c9a756471f68 | 3,649,017 |
from xls2xlsx import XLS2XLSX
import os
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
if os.path.exists(xls_file_path):
# converting xls to xlsx
... | 0718c5039cc19fa54d7320698d9d1f81106ff788 | 3,649,018 |
import os
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) | 267e0bbc082948bc6b47d593aa28248646f4c61f | 3,649,019 |
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... | 44c00b9a40b7dba53dcfaac52bc866341a924d01 | 3,649,020 |
import requests
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 = re... | 2b75cdfbb7c5f7085ab95f22ec601fbccdac07ea | 3,649,021 |
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... | 5efc00e015d2127f91462348050f2d445530690d | 3,649,022 |
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 ... | d560c90986cc99be3ad07c0099743821104e514a | 3,649,023 |
import ast
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:.... | 579b4f218fc17eae9b8595e916571e24eba27cb5 | 3,649,024 |
import csv
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']
r... | 62d76c398aee02a61a3dd8dd7ac1251367786c9c | 3,649,025 |
from typing import Optional
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 discover... | 821ba79ed56ec9b918dbec60af91e9b472cdb689 | 3,649,026 |
def decode_fixed64(buf, pos):
"""Decode a single 64 bit fixed-size value"""
return decode_struct(_fixed64_fmt, buf, pos) | 298df6d28f77132bac6d9924b9628af5efa940b5 | 3,649,027 |
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 ... | cc3aa11a8ff3dff6cf0609c3527daa193602b522 | 3,649,028 |
from datetime import datetime
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
... | 2938872ffdd3e30c2d364ae30e3a93fa560e55ef | 3,649,029 |
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()
return users | e294406af8abbd0fa813beeadcd8b01552e4d206 | 3,649,030 |
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... | a5de0984715cbc07c16c0ab5a5dc24edb7ca7602 | 3,649,031 |
from typing import Union
from typing import Tuple
import torch
import math
from re import X
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:... | c400e0042a4ec236030d7e5d19615441b4cc0456 | 3,649,032 |
import itertools
import torch
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))... | 3b10f89b80318c3bb2776af3d336c2b87d2a623e | 3,649,033 |
import copy
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 =... | 36d682851e24535b7b000ae1b343bb90ca2077d6 | 3,649,034 |
import json
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=j... | ea8ec1dd939cc43baa3367696f44956b2aafa780 | 3,649,035 |
def read_covid():
"""Read parsed covid table"""
return pd.read_csv(_COVID_FILE, parse_dates=["date"]) | fd99256808be1772106260b1da47850de0584adb | 3,649,036 |
import sys
import os
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 = geta... | 2c010be3baba35883ce1bb3003c8e6b184506845 | 3,649,037 |
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... | 905cf702fda005645c608b9dadb84f3659d991c1 | 3,649,038 |
from typing import List
def init_anim() -> List:
"""Initialize the animation."""
return [] | 121fff8b4102c2961449d970307e762bd983bdbe | 3,649,039 |
def keep_digits(txt: str) -> str:
"""Discard from ``txt`` all non-numeric characters."""
return "".join(filter(str.isdigit, txt)) | 34387003ea03651dd2582b3c49f1095c5589167b | 3,649,040 |
import re
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])|$)', ... | f212bbe5cc33cb31bea023f726abf60a1491b7df | 3,649,041 |
from typing import Any
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_po... | 6bafad83dcf0ed82eac626ad36b9d73416757f37 | 3,649,042 |
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_... | c1657cbce23bb222f68bc5b7efe3fe54dfcc26bd | 3,649,043 |
import logging
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 | c4c888345586718f8b476368ef118656d9650469 | 3,649,044 |
def say_hello():
""" Say hello """
return utils.jsonify_success({
'message': 'Hello {}! You are logged in.'.format(current_user.email)
}) | 52c0f572c0bd521a3ab12f1781d39c37130a78d3 | 3,649,045 |
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) | 61b7a4ce252c72dd69251a8783c572c8128a01c5 | 3,649,046 |
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... | 68918c78b1f33c07cd3494286a00b1c020256b56 | 3,649,047 |
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 | 635f89b33c9150b5d7b68415bb85bb8c1d644d1f | 3,649,048 |
from sys import maxsize
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 e... | 9e6ebc1b19c15e31edb4cd1421599c3ed6b9fb90 | 3,649,049 |
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)... | e1a94134e465f72a7d49e8bb950eb7a8ba97ac54 | 3,649,050 |
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... | 5d62e0fe1eebb190be47a05d822b8714d396125f | 3,649,051 |
import six
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)
... | 4ddf056dab2681759a462005effc4ae5488a4461 | 3,649,052 |
from azure.cli.core.commands.client_factory import get_mgmt_service_client
from azure.cli.core.profiles import ResourceType
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 o... | a38ae4a7fedaf8dcbaccba0873e4f519cb51af17 | 3,649,053 |
def filter_example(config, example, mode="train"):
"""
Whether filter a given example according to configure.
:param config: config contains parameters for filtering example
:param example: an example instance
:param mode: "train" or "test", they differs in filter restrictions
:return: boolean
... | 9c49990fe36c0a82d0a99a62fe810a19cd5a8749 | 3,649,054 |
def _dict_flatten(data):
"""Return flattened dict of input dict <data>.
After https://codereview.stackexchange.com/revisions/21035/3
Parameters
----------
data : dict
Input dict to flatten
Returns
-------
fdata : dict
Flattened dict.
"""
def expand(key, valu... | a1db4a552ced44efa45fe4f86fbfe04871463356 | 3,649,055 |
def merkleroot(elements):
"""
Args:
elements (List[str]): List of hashes that make the merkletree.
Returns:
str: The root element of the merkle tree.
"""
return Merkletree(elements).merkleroot | cd5d1e530fda62f9b92a51a03f5fd2cbbe6a9e62 | 3,649,056 |
def category_start(update, context):
"""Separate function for category selection to filter the options with inline keyboard."""
update.message.reply_text(
"Choose a Group",
reply_markup=create_category_inline(trx_categories.keys(), "group_sel"),
)
return CATEGORY_REPLY_CHOOSE_TRX_OPTS | cfc299d8b81785d8418bfb4c280cf88e4137448b | 3,649,057 |
import argparse
import functools
import sys
import collections
import csv
def betatest():
"""Main Function Definition"""
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('--host',\
required=True,\
help="site hostname")
parser.... | f5c211571aa4e4f63d07ff9b237b4697817e346e | 3,649,058 |
def create_player(mode, race, char_name):
""" Create the player's character """
# Evil
if mode == 2:
if race == 1:
player = character.Goblin(char_name, 1, app)
elif race == 2:
player = character.Orc(char_name, 1, app)
elif race == 3:
player = chara... | 30e143f0cca1053d6e10df0c438065747611e4af | 3,649,059 |
def _get_item(i, j, block):
"""
Returns a single item from the block. Coords must be in block space.
"""
return block[i, j] | 45a12ecb3959a75ad8f026616242ba64174441fc | 3,649,060 |
def calculate_potentials_python(volume, mass, volume_material_mass, mass_material_mass):
""" Easy to read python function which calculates potentials using two Python loops
Still uses NumPy for the rote math.
"""
potentials = np.zeros(len(volume), dtype=np.float32)
for volume_i, volume_coord in enu... | 73395d31bb470ac96b0c05a140fe6e77f56e2d88 | 3,649,061 |
def rect2sphericalcoord3D(
v: list[Number, Number, Number]
) -> list[float, float, float]:
"""Does a 3D coordinate transform
from rectangular to spherical
coordinate system
p = The length of the hypotenuse
or the magnitude of the
vector
theta =... | 8be197341e576465af389f8e20aea25a59fc3d1e | 3,649,062 |
def GetAssignmentByKeyName(key_name):
"""Gets the assignment with the specified key name."""
return Assignment.get_by_key_name(key_name) | a14b9a2033bb995d53219568278d298f305861d7 | 3,649,063 |
def fit_integer_type(n, is_signed=True):
"""Determine the minimal space needed to store integers of maximal value n
"""
if is_signed:
m = 1
types = [np.int8, np.int16, np.int32, np.int64]
else:
m = 0
types = [np.uint8, np.uint16, np.uint32, np.uint64]
if n < 2 ** (8... | bd9ebd447893509b1144a32bac9f9757988b4a60 | 3,649,064 |
def admin_userforms_order_by_field(user_id):
""" Set User's forms order_by preference
"""
if not g.is_admin:
return jsonify("Forbidden"), 403
data = request.get_json(silent=True)
if not 'order_by_field_name' in data:
return jsonify("Not Acceptable"), 406
field_names = [ field['na... | 4d92dc6f9d562a91509ec2b03aff75c4bc376ead | 3,649,065 |
def check_all_rows(A):
"""
Check if all rows in 2-dimensional matrix don't have more than one queen
"""
for row_inx in range(len(A)):
# compute sum of row row_inx
if sum(A[row_inx]) > 1:
return False
return True | e39f4ca3e401c02b13c5b55ed4389a7e6deceb40 | 3,649,066 |
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
def extract_largest_connected_region(vtk_im, label_id):
"""
Extrac the largest connected region of a vtk image
Args:
vtk_im: vtk image
label_id: id of the label
Return:
new_im: processed vtk image
"""
fltr ... | c9510da15b4d3cade331aa3b9b3625af5706e417 | 3,649,067 |
import subprocess
import sys
def _run_cli_cmd(cmd_list):
"""Run a shell command and return the error code.
:param cmd_list: A list of strings that make up the command to execute.
"""
try:
return subprocess.call(cmd_list)
except Exception as e:
print(str(e))
sys.exit(1) | 473d28ec5469ff195b716edfe32723e2379303f3 | 3,649,068 |
def group_set_array_data_ptr(d):
"""
call view%set_external_data_ptr
hide c_loc call and add target attribute
"""
# XXX - should this check the type/shape of value against the view?
# typename - part of function name
# nd - number of dimensions
# f_type - fortran type
# shape... | 36a18ca9099edf24d37386103f111bde7753ed46 | 3,649,069 |
from typing import cast
def releaseTagName(version: Version) -> str:
"""
Compute the name of the release tag for the given version.
"""
return cast(str, version.public()) | 9f8e350a42e2b50657a87e89e592ae340ba3ee96 | 3,649,070 |
import time
def get_calibrated_values(timeout=10):
"""Return an instance of CalibratedValues containing the 6 spectral bands."""
t_start = time.time()
while _as7262.CONTROL.get_data_ready() == 0 and (time.time() - t_start) <= timeout:
pass
with _as7262.CALIBRATED_DATA as DATA:
return C... | 69e5921b3e487ab3f3c3abbae8a2b237eb75b033 | 3,649,071 |
def customizable_admin(cls):
"""
Returns a customizable admin class
"""
class CustomSearchableAdmin(BaseAdmin):
form = customizable_form(cls)
def __init__(self, *args, **kwargs):
super(CustomSearchableAdmin, self).__init__(*args, **kwargs)
# add the custom field... | dc6ced817b78b7cbf31cbf788d28fcff421d6b02 | 3,649,072 |
def restoreIm(transformeddata, pca, origshape, datamean, datastd):
"""Given a PCA object and transformeddata that consists of projections onto
the PCs, return images by using the PCA's inverse transform and reshaping to
the provided origshape."""
if transformeddata.shape[0] < transformeddata.shape[1]:
... | ce8713648b166f7ce35bb47df33a6b99e2de8687 | 3,649,073 |
import random
import sys
def ga_multi(gene_info, ga_info):
"""Main loop which sets DEAP objects and calls a multi objective EA algorithm.
Parameters
-------
gene_info, GeneInfo class
See respective class documentation.
ga_info, GAInfo class
See respective class documentation.
... | 60bd65e90800cfa855b061d0cf5f431e1cac944e | 3,649,074 |
def sample(population, k=None):
"""Behaves like random.sample, but if k is omitted, it default to
randint(1, len(population)), so that a non-empty sample is returned."""
population = list(population)
if k is None:
k = randint(1, len(population))
return random_sample(population, k) | 46f7f3365c4574ed9cb09b54f25e30ff23fb3b8d | 3,649,075 |
def dense_to_one_hot(array, class_num, dtype_, axis=-1):
"""
this function offer a method to change the numpy array to one hot like base on axis
as we know array dims_size in axis should be 1
keep_shape
:param array: a numpy array, data type should be int
:param class_num: one hot class number
... | a045fefd6d397de9aa1e7a25f7788ab10bcf7c94 | 3,649,076 |
def add_momentum_ta(df, high, low, close, volume, fillna=False):
"""Add trend technical analysis features to dataframe.
Args:
df (pandas.core.frame.DataFrame): Dataframe base.
high (str): Name of 'high' column.
low (str): Name of 'low' column.
close (str): Name of 'close' column... | 76239057526272874c34eb4250f642745dfc9990 | 3,649,077 |
def get_experiment_type(filename):
"""
Get the experiment type from the filename.
The filename is assumed to be in the form of:
'<reliability>_<durability>_<history kind>_<topic>_<timestamp>'
:param filename: The filename to get the type.
:return: A string where the timesptamp is taken out fro... | e1853a95d034b8f9e36ca65f6f5d200cbf4b86dc | 3,649,078 |
from typing import Any
def async_check_significant_change(
hass: HomeAssistant,
old_state: str,
old_attrs: dict,
new_state: str,
new_attrs: dict,
**kwargs: Any,
) -> bool | None:
"""Test if state significantly changed."""
if old_state != new_state:
return True
if old_attrs... | 2a3f91923f187a601b80a28aa750060dc0760e65 | 3,649,079 |
import warnings
def array2string(a, max_line_width=None, precision=None,
suppress_small=None, separator=' ', prefix="",
style=np._NoValue, formatter=None, threshold=None,
edgeitems=None, sign=None):
"""
Return a string representation of an array.
Paramet... | ab40c565d058a6836fbc9778ae0d8ceb5c3d6a99 | 3,649,080 |
def registered_types():
""" list of registered types """
return list(Registry.types.get_all().keys()) | 50ed8fd4d586d660e2dc48e01e9cd462b346f47e | 3,649,081 |
from typing import Dict
def is_retain_bg_files(config: Dict[str, ConfigVO] = None) -> bool:
"""
在拉取新的壁纸前,是否保留旧的壁纸
"""
key = const.Key.Task.RETAIN_BGS.value
vo = config.get(key) if config else dao.get_config(key)
return vo and vo.value | 69fd845479c0afbc6d6b215d0680d7f6a9c35096 | 3,649,082 |
import pytz
def getAwareTime(tt):
"""
Generates timezone aware timestamp from timezone unaware timestamp
PARAMETERS
------------
:param tt: datatime
timezome unaware timestamp
RETURNS
------------
:return: datatime
timezone aware timestamp
... | 1b286c92c7f5d8f0ff48d77296489fbd358c14ce | 3,649,083 |
def xdfs(request, tmpdir, vol_name, dos_format):
"""return (xdf_file, xdf_size_spec, vol_name) for various disks"""
size = request.param
if size == "880K":
file_name = tmpdir / "disk.adf"
size = ""
else:
file_name = tmpdir / "disk-" + size + ".hdf"
size = "size=" + size
... | 0a9878ffe020ba1438844e000be5b9e4a8b2825a | 3,649,084 |
def nfvi_get_networks(paging, callback):
"""
Get a list of networks
"""
cmd_id = _network_plugin.invoke_plugin('get_networks', paging,
callback=callback)
return cmd_id | 432bd6a69e25cc7a80aa77b2a58fe99b0947b9a0 | 3,649,085 |
def get_fasta(uniprot_id):
"""Get the protein sequence for a UniProt ID as a string.
Args:
uniprot_id: Valid UniProt ID
Returns:
str: String of the protein (amino acid) sequence
"""
# Silencing the "Will be moved to Biokit" message
with ssbio.utils.suppress_stdout():
r... | 295a5bd30d3e0feaf99ecab7fa975c67f8b06248 | 3,649,086 |
def split_path(path, minsegs=1, maxsegs=None, rest_with_last=False):
"""
Validate and split the given HTTP request path.
**Examples**::
['a'] = split_path('/a')
['a', None] = split_path('/a', 1, 2)
['a', 'c'] = split_path('/a/c', 1, 2)
['a', 'c', 'o/r'] = split_path('/a/c/o... | d3824ebd63b784dadaf0a97e75049f79d1077ded | 3,649,087 |
def get_purchases_formset(n_forms=0):
"""
Helper method that returns a Django formset for a dynamic amount of Purchases. Initially `n_forms` empty
forms are shown.
"""
return modelformset_factory(Purchase, fields=('amount', 'fruit'), extra=n_forms) | b49ec71aef56eabb1781039af947ff510242925a | 3,649,088 |
async def git_pull():
"""
Pulls any changes down from github and returns the result of the command.
_> changed: str
"""
cmd = Popen(["git", "pull"], stdout=PIPE)
out, _ = cmd.communicate()
out = out.decode()
return out | ed32677a22b0f75c23af618f18833b5fc46bb3dc | 3,649,089 |
def inverse_word_map(word_map):
""" Create an inverse word mapping.
:param word_map: word mapping
"""
return {v: k for k, v in word_map.items()} | 4048a21ea1c75791a92d57ee0a440a6c9d31b6b9 | 3,649,090 |
def get_coalition_wins_sql_string_for_state(coalition_id,state_id):
"""
:type party_id: integer
"""
str = """ select
lr.candidate_id,
c.fullname as winning_candidate,
lr.constituency_id,
cons.name as constituency,
lr.party_id,
lr.max_votes,
(lr.max_vot... | 76fb0704779e20e8a53ca80dc17c969f1e455d20 | 3,649,091 |
import numpy
def computeAPLSF(data):
"""
Compute the LSF kernel for each chip
"""
index = 2047
## define lsf range and pixel centers
xlsf = numpy.linspace(-7.,7.,43)
xcenter = numpy.arange(0,4096)
## compute LSF profiles for each chip as a function of pixel
raw_out2_a = raw(xlsf,xcenter,data.lsfcoef... | 5cd46d9feec10dd0a4eff1a5fe44e241bfeed539 | 3,649,092 |
def login():
"""Log in a registered user by adding the user id to the session."""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
error = None
user = User.query.filter_by(name=username).first()
if user is None:
... | 067b202e81d947589c0fe2262372856084b28e35 | 3,649,093 |
def _timedeltaformat(value, include_ms=False):
"""Formats a timedelta in a sane way.
Ignores sub-second precision by default.
"""
if not value:
return NON_BREAKING_HYPHEN + NON_BREAKING_HYPHEN
total_seconds = value.total_seconds()
suffix = ''
if include_ms:
ms = int(round(total_seconds-int(total_... | 5c40caa1bd2e005746a44b1767eb4c3ed29b1603 | 3,649,094 |
def get_viame_src(url):
"""
Get image src from via.me API.
"""
END_POINT = 'http://via.me/api/v1/posts/'
tmp = url.split('/')
viame_id = tmp[-1][1:]
address = END_POINT + viame_id
result = httpget(address)['response']['post']
return result['thumb_300_url'] | 52b23fb64b30c97ef70b683e0176f88f8730e5c9 | 3,649,095 |
def Geom_BSplineCurve_MaxDegree(*args):
"""
* Returns the value of the maximum degree of the normalized B-spline basis functions in this package.
:rtype: int
"""
return _Geom.Geom_BSplineCurve_MaxDegree(*args) | 32729754ca89ce719b81f28fbf3f3c5ea5eb70eb | 3,649,096 |
import torch
def iou_score(pred_cls, true_cls, nclass, drop=(), mask=None):
"""
compute the intersection-over-union score
both inputs should be categorical (as opposed to one-hot)
"""
assert pred_cls.shape == true_cls.shape, 'Shape of predictions should match GT'
if mask is not None:
a... | d38871f339b2126d418a7fca53fbfd874e263aa2 | 3,649,097 |
def check_args(source_path, args):
"""Checks lengths of supplied args match or raise an error.
Lists can have only one element where they are automatically extended.
Args:
source_path(list(str)): List of source_paths supplied to turbiniactl.
args(list(list)): List of args (i.e. name, source, partitio... | 23d50e875ac908b0ee3afd4521b1a2660843ffc6 | 3,649,098 |
from datetime import datetime
import calendar
import warnings
import requests
import zipfile
def futures_dce_position_rank(date: str = "20160104") -> pd.DataFrame:
"""
大连商品交易日每日持仓排名-具体合约
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/rcjccpm/index.html
:param date: 指定交易日; e.g., "20200511"
:t... | 3c4fa81a2fef317210be915f437c0885f5fcbbbd | 3,649,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.