content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_dask_workers(
dask_client, # pylint: disable=redefined-outer-name,unused-argument
):
"""Test the dask_workers function."""
assert utilities.dask_workers(dask_client, cores_only=True) == len(
dask_client.ncores()) # type: ignore
assert utilities.dask_workers(dask_client, cores_only... | 30,900 |
def dispatch_for_binary_elementwise_apis(x_type, y_type):
"""Decorator to override default implementation for binary elementwise APIs.
The decorated function (known as the "elementwise api handler") overrides
the default implementation for any binary elementwise API whenever the value
for the first two argumen... | 30,901 |
def grid(mat, i, j, k):
"""Returns true if the specified grid contains k"""
return lookup(k, [ mat[i + p][j + q] for p in range(3) for q in range(3) ]) | 30,902 |
def test_azurecli_binary_isfile(host):
"""
Tests if az binary is a file type.
"""
assert host.file(PACKAGE_BINARY).is_file | 30,903 |
def get_list_channels(sc):
"""Get list of channels."""
# https://api.slack.com/methods/channels.list
response = sc.api_call(
"channels.list",
)
return response['channels'] | 30,904 |
def error_handler(error):
"""エラーメッセージを生成するハンドラ"""
response = jsonify({ 'cause': error.description['cause'] })
return response, error.code | 30,905 |
def display_results(
matches: Sequence[Match], pattern: str, line_number: bool, files_with_matches: bool,
):
"""Display matches as a colorfull table.
"""
files = {match.file for match in matches}
if files_with_matches: # Just print filenames
for file in files:
print(MAGENTA + fi... | 30,906 |
def test_uuid():
"""Tests that hug's text validator correctly handles UUID values
Examples were taken from https://docs.python.org/3/library/uuid.html"""
assert hug.types.uuid('{12345678-1234-5678-1234-567812345678}') == UUID('12345678-1234-5678-1234-567812345678')
assert hug.types.uuid('12345678-12... | 30,907 |
def search_records(
name: str,
search: TextClassificationSearchRequest = None,
common_params: CommonTaskQueryParams = Depends(),
include_metrics: bool = Query(
False, description="If enabled, return related record metrics"
),
pagination: PaginationParams = Depends(),
service: TextCla... | 30,908 |
def guess_udic(dic,data):
"""
Guess parameters of universal dictionary from dic, data pair.
Parameters
----------
dic : dict
Dictionary of JCAMP-DX, acqu, proc and spectrum parameters.
data : ndarray
Array of NMR data.
Returns
-------
udic : dict
Univers... | 30,909 |
def matchPosAny (msg, pos, rules, subrules):
"""Indicates whether or not `msg` matches any (i.e. a single) `subrule`
in `rules`, starting at position `pos`.
Returns the position in `msg` just after a successful match, or -1
if no match was found.
"""
index = -1
for rule in subrules:
... | 30,910 |
def _save_rpg(rpg, output_file):
"""Saves the RPG radar file.
Notes:
"""
dims = {'time': len(rpg.data['time'][:]),
'range': len(rpg.data['range'][:]),
'chirp_sequence': len(rpg.data['chirp_start_indices'][:])}
rootgrp = output.init_file(output_file, dims, rpg.data, zlib=Tru... | 30,911 |
async def load(ctx, module: str):
"""Load a cog located in /cogs"""
author = str(ctx.message.author)
module = module.strip()
try:
bot.load_extension("cogs.{}".format(module))
output.info('{} loaded module: {}'.format(author, module))
loaded_extensions.append(module)
awai... | 30,912 |
def test_get_function_code_all():
"""Test get_function_code_all"""
function = {
"name": "code_test",
"code": {"start": ["line 1"], "mid": ["line 2"], "end": ["line 3"]},
}
assert functions.get_function_code("start", function) == [" line 1"]
assert functions.get_function_code(... | 30,913 |
def channelBox(*args, **kwargs):
"""
This command creates a channel box, which is sensitive to the active list.
Returns: `string` (the name of the new channel box)
"""
pass | 30,914 |
def compute_accuracy(model, loader):
"""
:param model: a model which returns classifier_output and segmentator_output
:param loader: data loader
"""
model.eval() # enter evaluation mode
score_accum = 0
count = 0
for x, y, _, _ in loader:
classifier_output, _ = model(x)
... | 30,915 |
def create_base_query_grouped_fifo(rse_id, filter_by_rse='destination', session=None):
"""
Build the sqlalchemy queries to filter relevant requests and to group them in datasets.
Group requests either by same destination RSE or source RSE.
:param rse_id: The RSE id.
:param filter_by_rse: ... | 30,916 |
def then(state1, state2):
"""
Like ``bind``, but instead of a function that returns a statetful action,
just bind a new stateful action.
Equivalent to bind(state1, lambda _: state2)
"""
return bind(state1, lambda _: state2) | 30,917 |
def get_skyregions_collection(run_id: Optional[int]=None) -> Dict[str, Any]:
"""
Produce Sky region geometry shapes JSON object for d3-celestial.
Args:
run_id (int, optional): Run ID to filter on if not None.
Returns:
skyregions_collection (dict): Dictionary representing a JSON obejct
... | 30,918 |
def construct_sru_query(keyword, keyword_type=None, mat_type=None, cat_source=None):
"""
Creates readable SRU/CQL query, does not encode white spaces or parenthesis -
this is handled by the session obj.
"""
query_elems = []
if keyword is None:
raise TypeError("query argument cannot be N... | 30,919 |
def sitemap_xml():
"""Default Sitemap XML"""
show_years = retrieve_show_years(reverse_order=False)
sitemap = render_template("sitemaps/sitemap.xml",
show_years=show_years)
return Response(sitemap, mimetype="text/xml") | 30,920 |
def test_geo_value():
"""
Test geo values.
"""
lib.backup_and_restore(
lambda context: put_values(lib.SET, "key", GEO_VALUES),
None,
lambda context: check_values(lib.SET, "key", GEO_VALUES)
) | 30,921 |
def remove_property(product_id, property_id):
"""
Remove the property
"""
property = db.db.session.query(TypeProperty).\
filter_by(product_id = product_id, product_property_id = property_id).first()
try:
db.db.session.delete(property)
db.db.session.commit()
except Exception as e:
db.db.session.rollback()... | 30,922 |
def plot_result(data, xlabel, ylabel, title, output_filename):
"""plot the results similar to the figures in our paper
:param data: The input data sets to plots. e.g., {algorithm_epsilon: [(test_epsilon, pvalue), ...]}
:param xlabel: The label for x axis.
:param ylabel: The label for y axis.
:param ... | 30,923 |
def format_solution_table_calc(solution, node_ids_to_nodes):
"""
:type solution: dict[int, list[int]]
:type node_ids_to_nodes: dict[int, int]
:rtype: dict[int, str]
"""
new_solution = {}
for (color, path) in solution.items():
new_path = []
for p in path:
back_p = ... | 30,924 |
def hashable(func):
"""Decorator for functions with numpy arrays as input arguments that will benefit from caching
Example:
from midgard.math import nputil
from functools import lru_cache
@nputil.hashable
@lru_cache()
def test_func(a: np.ndarray, b: np.ndarray = None)
do_something... | 30,925 |
def parse_args():
"""
Parse input arguments. Helps with the command line argument input.
"""
parser = argparse.ArgumentParser(description='Faster R-CNN demo')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',
default=0, type=int)
parser.add_argu... | 30,926 |
def at_export_ex():
"""
Similarly, :func:`at_export() <planar.at_export>` can be used to export any
Numpy ndarray data to a CSV file. This will open a simple GUI dialog box
asking for the location where the CSV file needs to be saved::
import arraytool.planar as planar
planar.at_ex... | 30,927 |
def _volume_operation(ctx, vca_client, operation):
"""
attach/detach volume
"""
vdc_name = get_vcloud_config()['vdc']
vdc = vca_client.get_vdc(vdc_name)
vmName = get_vapp_name(ctx.target.instance.runtime_properties)
if ctx.source.node.properties.get('use_external_resource'):
volu... | 30,928 |
def GetServerSupplicantInfo(TestCaseID):
"""
Gets the RADIUS Server Information and
Supplicant name for given test and load them into Env file
Parameters
----------
TestCaseID : str
Returns
-------
Pass(1)/Fail(-1) : int
"""
if dutInfoObject.DUTEAPMethod == "TL... | 30,929 |
def object_hash(fd, fmt, repo=None):
""" Function to read the content of a open file, create appropiate object
and write the object to vcs directory and return the hash of the file"""
data = fd.read()
# choosing constructor on the basis of the object type found in header
if fmt == b'com... | 30,930 |
def read_from_pdf(pdf_file):
"""
读取PDF文件内容,并做处理
:param pdf_file: PDF 文件
:return: pdf文件内容
"""
# 二进制读取pdf文件内的内容
with open(pdf_file, 'rb') as file:
resource_manage = PDFResourceManager()
return_str = io.StringIO()
lap_params = LAParams()
# 内容转换
device =... | 30,931 |
def _descending(dbus_object):
"""
Verify levels of variant values always descend by one.
:param object dbus_object: a dbus object
:returns: None if there was a failure of the property, otherwise the level
:rtype: int or NoneType
None is a better choice than False, for 0, a valid variant level,... | 30,932 |
def _is_avconv():
"""
Returns `True` if the `ffmpeg` binary is really `avconv`.
"""
out = _run_command(['ffmpeg', '-version'])
return out and isinstance(out, strtype) and 'DEPRECATED' in out | 30,933 |
def countries(request):
"""
Returns all valid countries and their country codes
"""
return JsonResponse({
"countries": [{
"id": unicode(code),
"name": unicode(name)
} for code, name in list(django_countries.countries)]
}) | 30,934 |
def get_reads(file, reads=None):
"""
Get the read counts from the file
"""
if not reads:
reads={}
# get the sample name from the file
sample=os.path.basename(file).split(".")[0]
reads[sample]={}
with open(file) as file_handle:
for line in file_handle:
... | 30,935 |
def generate_monomer(species, monomerdict, initlen, initnames, tbobs):
"""
generate a PySB monomer based on species
:param species: a Species object
:param monomerdict: a dictionary with all monomers linked to their species id
:param initlen: number of the initial species
:param initnames: name... | 30,936 |
def convert_bert_tokens(outputs):
"""
Converts BERT tokens into a readable format for the parser, i.e. using Penn Treebank tokenization scheme.
Does the heavy lifting for this script.
"""
logging.info("Adjusting BERT indices to align with Penn Treebank.")
mapped_outputs = [] # Will hold the fin... | 30,937 |
def load_proto_message(
config_path: AnyPath,
overrides: Sequence[str] = tuple(),
*,
msg_class=None,
extra_include_dirs: Sequence[pathlib.Path] = tuple(),
) -> ProtoMessage:
"""Loads message from the file and applies overrides.
If message type is not give, will try to guess message type.
... | 30,938 |
def main() -> NoReturn:
"""
Prepare dataset splits - training, validation & testing splits
Compute ner distributions in our dataset. Based on this distribution
and whether we want to keep certain notes grouped (e.g by patient)
we assign notes to a split, such that the final ner type distribution
... | 30,939 |
def calculate_iou(ground_truth_path, prediction_path):
""" Calculate the intersection over union of two raster images.
Args:
ground_truth_path (str): Path to the ground truth raster image.
prediction_path (str): Path to the prediction raster image.
Returns:
float: The intersection ov... | 30,940 |
def bokeh_scatter(x,
y=None,
*,
xlabel='x',
ylabel='y',
title='',
figure=None,
data=None,
saveas='scatter',
copy_data=False,
**kwargs):
... | 30,941 |
def rulesActionsHandler(args):
""" Check rule action and execute associates functions.
:param args: Rule action
:return: Return result from the executed functions.
"""
if 'get' == args.action:
# get rule arguments :
# - id:
# type: int
# args num... | 30,942 |
def _check_new_accessions(newfiles: List[Union[NewFiles, PepFiles, SubFiles]]) -> None:
"""Runs new accession checker on new entries and displays the result to the
user.
Args:
newfiles: list of NewFiles, PepFiles and/or SubFiles objects.
"""
for f in newfiles:
if f:
cli... | 30,943 |
def superposition_training_mnist(model, X_train, y_train, X_test, y_test, num_of_epochs, num_of_tasks, context_matrices, nn_cnn, batch_size=32):
"""
Train model for 'num_of_tasks' tasks, each task is a different permutation of input images.
Check how accuracy for original images is changing through tasks us... | 30,944 |
def json2dict(astr: str) -> dict:
"""将json字符串转为dict类型的数据对象
Args:
astr: json字符串转为dict类型的数据对象
Returns:
返回dict类型数据对象
"""
return json.loads(astr) | 30,945 |
def get_con_line(in_path, out_path):
"""draw contour line given a numpy array
Parameters:
in_path: path of input numpy
out_path: path of output figure
Returns:
None
"""
z = np.load(in_path)
z = np.squeeze(z)
xlist = np.linspace(0, z.shape[0], z.shape[0])
ylist = ... | 30,946 |
def any(wanted_type=None):
"""Matches against type of argument (`isinstance`).
If you want to match *any* type, use either `ANY` or `ANY()`.
Examples::
when(mock).foo(any).thenReturn(1)
verify(mock).foo(any(int))
"""
return Any(wanted_type) | 30,947 |
def test_import_python_file_for_first_time(clean_repo, mocker, files_dir: Path):
"""Test that importing a python file as module works and allows for
importing of module attributes even with module popped from sys path"""
SOME_MODULE = "some_module"
SOME_MODULE_FILENAME = SOME_MODULE + ".py"
SOME_FU... | 30,948 |
def p_html_href(p):
"""html_href : HREF COLON CTESTR snp_href_quad
| empty""" | 30,949 |
def specplot_mel_spec(mel_spec,
vmin=-5,
vmax=16000,
rotate=True,
size=512 + 256,
**matshow_kwargs):
"""Plot the log magnitude spectrogram of mel spectrogram."""
# If batched, take first element.
#if len(mel_spec.shape) == 2:
# mel_spec = mel_spe... | 30,950 |
def list_top_level_blob_folders(container_client):
"""
List all top-level folders in the ContainerClient object *container_client*
"""
top_level_folders,_ = walk_container(container_client,max_depth=1,store_blobs=False)
return top_level_folders | 30,951 |
def keyword_encipher(message, keyword, wrap_alphabet=KeywordWrapAlphabet.from_a):
"""Enciphers a message with a keyword substitution cipher.
wrap_alphabet controls how the rest of the alphabet is added
after the keyword.
0 : from 'a'
1 : from the last letter in the sanitised keyword
2 : from the... | 30,952 |
def plt_to_img(dummy: any = None, **kwargs) -> PIL.Image.Image:
"""
Render the current figure as a (PIL) image
- Take dummy arg to support expression usage `plt_to_img(...)` as well as statement usage `...; plt_to_img()`
"""
return PIL.Image.open(plot_to_file(**kwargs)) | 30,953 |
def _escape_char(c, escape_char=ESCAPE_CHAR):
"""Escape a single character"""
buf = []
for byte in c.encode('utf8'):
buf.append(escape_char)
buf.append('%X' % _ord(byte))
return ''.join(buf) | 30,954 |
def get_syntax_error(error, logging_type="critical"):
"""logging error and after that raise SyntaxError"""
try:
_e = "Call from %s:%s" % (sys._getframe().f_back.f_code.co_name,sys._getframe( 1 ).f_lineno )
utils.logs.log(error=_e, logging_type=logging_type)
except Exception:
pass
... | 30,955 |
def error_log_to_html(error_log):
"""Convert an error log into an HTML representation"""
doc = etree.Element('ul')
for l in error_log:
if l.message.startswith('<runtrace '):
continue
el = etree.Element('li')
el.attrib['class'] = 'domain_{domain_name} level_{level_name} ty... | 30,956 |
def get_scheduler(optimizer, opt):
"""Return a learning rate scheduler
Parameters:
optimizer -- the optimizer of the network
opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.
opt.lr_policy is the name of learning... | 30,957 |
def gen_colors(count, drop_high=True):
"""Generate spread of `count` colors from matplotlib inferno colormap"""
# drop the top end of the color range by defining the norm with one
# element too many
cvals = range(0, count + drop_high)
# and dropping the last element when calculating the normed value... | 30,958 |
def validate_branch():
"""Checks the branch passed in against the branches available on remote.
Returns true if branch exists on remote. This may be subject to false
postivies, but that should not be an issue"""
output = subprocess.run(["/usr/bin/git", "ls-remote",
CUR... | 30,959 |
def train_PCA(data, num_components):
"""
Normalize the face by subtracting the mean image
Calculate the eigenValue and eigenVector of the training face, in descending order
Keep only num_components eigenvectors (corresponding to the num_components largest eigenvalues)
Each training face is represent... | 30,960 |
def test_client():
"""
A fixture that initialises the Flask application, saves the current application context for the duration of a single
test and yields a testing client that can be used for making requests to the endpoints exposed by the application
"""
test_app = create_app(DATABASE_NAME='test_... | 30,961 |
def main():
"""
example:
"he made the van this challenge ." vs. "the van made he this challenge ."
"""
# counterbalance both forms of verb as different forms are the contrast
vbds = [
'brought',
'made',
'built',
'gave',
'showed',
]
nouns_s = get... | 30,962 |
def test_2():
"""
Situation : This test will check the time complexity of the drop
aspect.
Rows with age > 50 will be dropped, so around half of the
rows will be dropped.
The drop aspect should work in O(number_of_rows *
average_byt... | 30,963 |
def count_revoked_tickets_for_party(party_id: PartyID) -> int:
"""Return the number of revoked tickets for that party."""
return db.session \
.query(DbTicket) \
.filter_by(party_id=party_id) \
.filter_by(revoked=True) \
.count() | 30,964 |
def test_limits(client):
"""Make sure that requesting resources with limits return a slice of the result."""
for i in range(100):
badge = client.post("/api/event/1/badge", json={
"legal_name": "Test User {}".format(i)
}).json
assert(badge['legal_name'] == "Test User {}"... | 30,965 |
def link_cohort_to_partition_group(cohort, partition_id, group_id):
"""
Create cohort to partition_id/group_id link.
"""
CourseUserGroupPartitionGroup(
course_user_group=cohort,
partition_id=partition_id,
group_id=group_id,
).save() | 30,966 |
def unzip(zip_file_path, output_dir):
"""
Unzip the given file into the given directory while preserving file permissions in the process.
Parameters
----------
zip_file_path : str
Path to the zip file
output_dir : str
Path to the directory where the it should be unzipped to
... | 30,967 |
def add_service_context(_logger, _method, event_dict):
"""
Function intended as a processor for structlog. It adds information
about the service environment and reasonable defaults when not running in Lambda.
"""
event_dict['region'] = os.environ.get('REGION', os.uname().nodename)
event_dict['se... | 30,968 |
def get_player_stats():
"""
Get all the player stats
returns dict of dicts: ->
{ player_id: {
name -> str gamertag,
discord -> str discord,
rank -> int rank,
wins -> int wins,
... | 30,969 |
def get_data(data_x, data_y):
"""
split data from loaded data
:param data_x:
:param data_y:
:return: Arrays
"""
print('Data X Length', len(data_x), 'Data Y Length', len(data_y))
print('Data X Example', data_x[0])
print('Data Y Example', data_y[0])
train_x, test_x, train_y, test_y... | 30,970 |
async def api_download_profile() -> str:
"""Downloads required files for the current profile."""
global download_status
assert core is not None
download_status = {}
def update_status(url, path, file_key, done, bytes_downloaded, bytes_expected):
bytes_percent = 100
if (bytes_expecte... | 30,971 |
def cumulative_segment_wrapper(fun):
"""Wrap a cumulative function such that it can be applied to segments.
Args:
fun: The cumulative function
Returns:
Wrapped function.
"""
def wrapped_segment_op(x, segment_ids, **kwargs):
with tf.compat.v1.name_scope(
Non... | 30,972 |
def read_pet_types(
skip: int = 0,
limit: int = 100,
db: Session = Depends(deps.get_db),
current_user: models.User = Depends(deps.get_current_active_superuser)
) -> Any:
"""
Read pet types
:return:
"""
if not crud.user.is_superuser(current_user):
raise HTTPExc... | 30,973 |
def get_approves_ag_request():
"""Creates the prerequisites for - and then creates and returns an instance of - ApprovesAgRequest."""
# Creates an access group request and an approver (required to create an instance of ApprovesAgRequest).
agr = AccessGroupRequest(reader=None, ag=None, justification=MAGIC_STRING)
a... | 30,974 |
def currency_history(
base: str = "USD", date: str = "2020-02-03", api_key: str = ""
) -> pd.DataFrame:
"""
Latest data from currencyscoop.com
https://currencyscoop.com/api-documentation
:param base: The base currency you would like to use for your rates
:type base: str
:param date: Specific... | 30,975 |
def compute_aggregate_scores(path_to_results: str, ignore_tasks: List[str] = None) -> None:
"""Computes aggregate scores from a given results file (generated from a previous call to
`run_senteval`) at path_to_results`. Tasks can be ignored (e.g. their score will not be computed
and therefore not contribute ... | 30,976 |
def get_service_legacy(default=None):
"""Helper to get the old {DD,DATADOG}_SERVICE_NAME environment variables
and output a deprecation warning if they are defined.
Note that this helper should only be used for migrating integrations which
use the {DD,DATADOG}_SERVICE_NAME variables to the new DD_SERVI... | 30,977 |
def test_workload_rbd_cephfs_minimal(
workload_storageutilization_05p_rbd, workload_storageutilization_05p_cephfs
):
"""
Similar to test_workload_rbd_cephfs, but using only 5% of total OCS
capacity. This still test the workload, but it's bit faster and (hopefully)
without big impact on the cluster i... | 30,978 |
def get_met_data():
"""
Taken from Tensorflow tutorial on time series forecasting:
https://www.tensorflow.org/tutorials/structured_data/time_series
"""
zip_path = tf.keras.utils.get_file(
origin='https://storage.googleapis.com/tensorflow/tf-keras-datasets/jena_climate_2009_2016.csv.zip'... | 30,979 |
def get_drives():
"""A list of accessible drives"""
if os.name == "nt":
return _get_win_drives()
else:
return [] | 30,980 |
def run_once(sql, dbname, print_rows):
"""Run sql statement once on database
This is the default run mode for statements
"""
with connections[dbname].cursor() as cursor, timer(dbname):
cursor.execute(sql)
if print_rows:
rows = fetch_dicts(cursor)
for row in rows:... | 30,981 |
def _ref_tier_copy(source_eaf: Type[Eaf] = None,
target_eaf: Type[Eaf] = None,
source_tier_name: str = "",
target_tier_name: str = "",
target_parent_tier_name: str = "",
override_params: Dict[str, str] = {}):
"""
Copy... | 30,982 |
def push_phy_link():
"""
make a query to fetch the phyLink table and serverNIC table, and concatenation them into a entry where the
flow_info is default.
"""
default_flow = list()
cursor.execute("SELECT * FROM phyLink")
links_dps = cursor.fetchall()
for link_dp in links_dps:
#e... | 30,983 |
def test_url_message_init_with_text_must_raise_error():
"""Test the `URLMessage` type initialization with text must raise error"""
with pytest.raises(ValidationError):
_ = UrlMessage(
title="URL #1",
url="This is a text",
) | 30,984 |
def fibonacci(length=10):
"""Get fibonacci sequence given it length.
Parameters
----------
length : int
The length of the desired sequence.
Returns
-------
sequence : list of int
The desired Fibonacci sequence
"""
if length < 1:
raise ValueError("Sequence le... | 30,985 |
def readForecast(config, stid, model, date, hour_start=6, hour_padding=6, no_hourly_ok=False):
"""
Return a Forecast object from the main theta-e database for a given model and date. This is specifically designed
to return a Forecast for a single model and a single day.
hour_start is the starting hour f... | 30,986 |
def main() -> None:
"""Read jupyterblack CLI arguments."""
run(sys.argv[1:]) | 30,987 |
def get_direct_hit_response(request, query, snuba_params, referrer):
"""
Checks whether a query is a direct hit for an event, and if so returns
a response. Otherwise returns None
"""
event_id = normalize_event_id(query)
if event_id:
snuba_args = get_snuba_query_args(
query=u'... | 30,988 |
def CXLayer(qc, qreg, order):
"""
Applies a layer of CX gates onto the qubits of register
qreg in circuit qc, with the order of application
determined by the value of the order parameter.
"""
if order:
qc.cx(qreg[0], qreg[1])
else:
qc.cx(qreg[1], qreg[0]) | 30,989 |
def get_env_var(var_name: str) -> Any:
"""Get envronment var or raise helpful exception.
:param var_name: Name of environment variable to get.
:raises: ImproperlyConfigured if environment variable not found.
"""
dotenv.load_dotenv()
try:
return os.environ[var_name]
except KeyError... | 30,990 |
def _canonicalize_clusters(clusters: List[List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]:
"""
The data might include 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters containing the
... | 30,991 |
def remove_outliers(matches, keypoints):
"""
Calculate fundamental matrix between 2 images to remove incorrect matches.
Return matches with outlier removed. Rejects matches between images if there are < 20
:param matches: List of lists of lists where matches[i][j][k] is the kth cv2.Dmatch object for im... | 30,992 |
def err_comp(uh, snap, times_offline, times_online):
"""
Computes the absolute l2 error norm and the rms error
norm between the true solution and the nirom solution projected
on to the full dimensional space
"""
err = {}
w_rms = {}
soln_names = uh.keys()
# ky = list(uh.keys())[0]
... | 30,993 |
def calc_stock_state(portfolio,code:int,date:datetime,stocks,used_days:int):
"""
状態を計算
- 株価・テクニカル指標・出来高の時系列情報
- 総資産、所持株数
Args:
stocks: 単元株数と始値、終値、高値、低値、出来高を含む辞書を作成
used_days: 用いる情報の日数
"""
stock_df=stocks[code]['prices']
date=datetime(date.year,date.month,date.day) #co... | 30,994 |
def lowercase_words(words):
"""
Lowercases a list of words
Parameters
-----------
words: list of words to process
Returns
-------
Processed list of words where words are now all lowercase
"""
return [word.lower() for word in words] | 30,995 |
def convert_images_to_arrays_train(file_path, df):
"""
Converts each image to an array, and appends each array to a new NumPy
array, based on the image column equaling the image file name.
INPUT
file_path: Specified file path for resized test and train images.
df: Pandas DataFrame being... | 30,996 |
def get_projection_matrix(X_src, X_trg, orthogonal, direction='forward', out=None):
"""
X_src: ndarray
X_trg: ndarray
orthogonal: bool
direction: str
returns W_src if 'forward', W_trg otherwise
"""
xp = get_array_module(X_src, X_trg)
if orthogonal:
if direction == 'forwar... | 30,997 |
def _standardize_df(data_frame):
"""
Helper function which divides df by std and extracts mean.
:param data_frame: (pd.DataFrame): to standardize
:return: (pd.DataFrame): standardized data frame
"""
return data_frame.sub(data_frame.mean(), axis=1).div(data_frame.std(), axis=1) | 30,998 |
def test_reset_password(client):
"""Test password reset requests."""
# Create user and login
USER1 = dict(USER)
USER1[LABELS['VERIFY']] = False
r = client.post(config.API_PATH() + '/users/register', json=USER1)
data = {LABELS['NAME']: 'user1', LABELS['PASSWORD']: 'pwd'}
r = client.post(confi... | 30,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.