content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def vertex_score(timeseries):
"""
A timeseries is anomalous if vertex score in hypergraph is greater than average score of observed anomalous vertex.
:return: True or False
"""
if vertex_centers.shape[0] <= 1:
update_vertex_param()
timeseries = np.array(timeseries)
test_data = timese... | 34995fe774dafd1b830875234b60680d5148bcdb | 49,900 |
def emergency_contact_list(request):
""" Renders emergency contact info page """
brothers = Brother.objects.exclude(brother_status='2').order_by("last_name")
context = {
'brothers': brothers,
}
return render(request, 'emergency-contact-list.html', context) | d9388ff409b61ab4bf9ba97b9221680e6e59be43 | 49,901 |
from pathlib import Path
from typing import Optional
from datetime import datetime
import os
def get_backup_path(p: Path) -> Optional[Path]:
"""Gets the backup path for a given path.
If the path we come up with already exists (highly unlikely), returns
``None``.
"""
basename = p.name
# e.g. "... | c8651ac29090d1f93172a8b4e5700ef9dfaf1e32 | 49,902 |
def create_user_records_bp(app):
"""Create user records blueprint."""
ext = app.extensions["invenio-rdm-records"]
return ext.user_records_resource.as_blueprint(
"bibliographic_user_records_resource"
) | 433f1d3681f8dc4dda36d38259085b59a3ab7b1b | 49,903 |
from typing import Any
import ctypes
def make_create_dataframe(
col_names: Any,
K: RuntimeTypeDescriptor = None
) -> Transformation:
"""Make a Transformation that constructs a dataframe from a Vec<Vec<String>>.
:param col_names: Column names for each record entry.
:type col_names: Any
:pa... | c885d984d98188489a25ba9a261b9d9aab946386 | 49,904 |
def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger:
"""TODO"""
return None | bc4704edd833d715a5b22e0d9d6a7a02b16da472 | 49,905 |
import pwd
import os
def conda_prefix(user=None):
"""
Get the conda prefix for a particular user (~/anaconda)
If user is None it defaults to /opt/anaconda
"""
if user == 'root':
return __salt__['grains.get']('conda:prefix', default='/opt/anaconda')
else:
if user is None:
... | c9fdaf431d1eee81f6a45d1ce6daefc9fea696c2 | 49,906 |
def filter_entropy(np_img, neighborhood=9, threshold=5, output_type="uint8"):
"""
Filter image based on entropy (complexity).
Args:
np_img: Image as a NumPy array.
neighborhood: Neighborhood size (defines height and width of 2D array of 1's).
threshold: Threshold value.
output_type:... | 5a067530172f0c7bec49f5d84d58ecf764e01e43 | 49,907 |
import os
def ProxyInfoFromEnvironmentVar(proxy_env_var):
"""Reads proxy info from the environment and converts to httplib2.ProxyInfo.
Args:
proxy_env_var: Environment variable string to read, such as http_proxy or
https_proxy.
Returns:
httplib2.ProxyInfo constructed from the environment string... | 8b21277de327f0bd80dc010ab23d5f979ec37a8e | 49,908 |
def getTechniqueData(technique=None):
"""
Returns injection data for technique specified
"""
return kb.injection.data.get(technique) | 99978be6985e49b69f4b4d2cd0376c6987f287ac | 49,909 |
import json
from datetime import datetime
def _deserialize_video(json_text):
""" Parses JSON and deserializes it into a list of YouTubeResult objects. """
results = []
parsed_json = json.loads(json_text)
items = parsed_json["items"]
for item in items:
result = YouTubeResult()
... | ba1f4d3d0afb7edca0d52a472f54be6b4db2c2ba | 49,910 |
def interval(lower_, upper_):
"""Build an interval."""
if lower_ <= upper_:
return lower_, upper_
return None | 3dd1b0c04c9cad8e5f8a69e5c348f07a7542fe7b | 49,911 |
import json
async def apiDiscordCommandsDelete(cls:"WebIndex", WebRequest:Request) -> Response:
"""
Default url: /api/discord/commands/delete
"""
Data:WebRequestContent = WebRequestContent(WebRequest)
await Data.load()
# get required vars
guild_id:str = Data.getStr("guild_id", "", must_be_digit=True)
comman... | 6dcd16ada18c75515c27592a3f687b288a3a6495 | 49,912 |
import logging
def _parse_amiga_props(amiga_props, offset_x):
"""Convert AmigaFont properties into yaff properties."""
if amiga_props.tf_Style & _FSF_COLORFONT:
raise ValueError('Amiga ColorFont not supported')
props = {}
# preserve tags stored in name field after \0
name, *tags = amiga_pr... | d279f2525f1b0eb75d04dc1cdbc09db472cf71c2 | 49,913 |
import torch
import copy
def flow_to_trafo_PnP(*args, **kwargs):
"""
input:
real_br: torch.tensor torch.Size([2])
real_tl: torch.tensor torch.Size([2])
ren_br: torch.tensor torch.Size([2])
ren_tl: torch.tensor torch.Size([2])
flow_mask: torch.Size([480, 640])
u_map: torch.S... | 245e396b4c9096340e29394a31357cc8e5aa7727 | 49,914 |
def Ha_plot(ax):
"""Plot the Ha line and bandpass."""
ax.axvspan(Ha - 0.678, Ha + 0.678, color='tab:blue', alpha=.5)
ax.axvspan(6545.495, 6556.245, color='tab:blue', alpha=.5)
ax.axvspan(6575.934, 6584.684, color='tab:blue', alpha=.5)
ax.axvline(Ha, color='red', ls='dashed')
ax.set_xlim(6544.49... | 8c29b093c4c1b101fe0fc720a936a4b9f9b80882 | 49,915 |
def ikev2scan(ip, **kwargs):
"""Send a IKEv2 SA to an IP and wait for answers."""
return sr(IP(dst=ip) / UDP() / IKEv2(init_SPI=RandString(8),
exch_type=34) / IKEv2_payload_SA(prop=IKEv2_payload_Proposal()), **kwargs) | 30a999d0da7ea62e10e333e4bfceea28447f19f4 | 49,916 |
def usb_get_strings(*args):
"""
usb_get_strings(context, device) -> (return_code, manufacturer, description, serial)
Return device ID strings from the usb device.
The parameters manufacturer, description and serial may be NULL or
pointer to buffers to store the fetched strings.
Use this fun... | 515844cc5651d5121ab09b3adee53f2f03b586be | 49,917 |
def set_avatar_url():
"""
设置用户头像信息
1. 获取参数,avatar, user_id,request.filter.get('avatar')
2. 检验参数存在
3. 读取图片数据,data= avatar.read()
4. 调用七牛云接口,上传用户头像
5. 保存用户头像信息到数据库
6. 拼接用户头像图片的完整路径,七牛云外链域名+图片文件名
7. 返回结果
:return:
"""
# 获取参数
user_id = g.user_id
avatar = request.files... | 8523bcbcaef28368fed14c84a3a4705d654eb4cb | 49,918 |
import imtools
import viewer
import os
import sys
def showSegmentation(
segmentation,
voxelsize_mm=np.ones([3, 1]),
degrad=4,
label=1,
smoothing=True,
vtk_file=None,
qt_app=None,
show=True,
resize_mm=None
):
"""
Funkce vrací trojr... | 2124b25a87fb2c10ede0bb2750885b27713b171e | 49,919 |
def fetch_links(html):
"""
Fetch all links on a given page and return their hrefs in a list
"""
elements = html.cssselect('a')
return [e.get('href') for e in elements if e.get('href') is not None] | f97f610e5baeb3e3b304c3093a5e27fc0b8de551 | 49,920 |
def isolines_style(value=RANGE_LABEL_KEY, top=11, cat=None, palette='pinkyl', size=None, opacity=0.8,
stroke_color='rgba(150,150,150,0.4)', stroke_width=None):
"""Helper function for quickly creating an isolines style.
Based on the color category style.
Args:
value (str, optional... | 889ed4543152ea197448a301c8be49d04ebc2ecf | 49,921 |
import sys
def generate_html(html_name: str = "default_name"):
"""
format html_string and output html file
:param html_name: save html file name
:return: html_string
"""
if len(test_record_instance.test_record_list) == 0 and len(test_record_instance.error_record_list) == 0:
raise HTMLE... | 374644144bfb8e486beb26ab80aff3c38cbc00b1 | 49,922 |
import requests
def nlp_answer(question: str = "人工智能") -> str:
"""
智能问答
https://ownthink.com/robot.html
:param question: word in chinese
:type question: str
:return: indicator data
:rtype: list or dict or pandas.DataFrame
"""
url = 'https://api.ownthink.com/bot'
params = {
... | 4947917c54862dd0bf38706c8091573e177c8b7c | 49,923 |
def load_eia861_state_total_sales(
pudl_out: pudl.output.pudltabl.PudlTabl
) -> pd.DataFrame:
"""
Read and format EIA 861 sales by state and year.
Args:
pudl_out: Used to access
:meth:`pudl.output.pudltabl.PudlTabl.sales_eia861`.
Returns:
Dataframe with columns `state_id_... | 5e40bfafcda31285583e50e5f4c66006635d1f8b | 49,924 |
def echo_handler(ex, *args, **kwargs):
"""
Example error handler which echoes the exception and the arguments.
"""
argstring = ','.join(['%s' % arg for arg in args])
return '%s/%s/%s' % (ex.message, argstring, kwargs) | 29ca4f7663e9c3bf1893bf3f4ab84c8744827ec3 | 49,925 |
import os
import glob
def get_onnx2ncnn_path() -> str:
"""Get onnx2ncnn path.
Returns:
str: A path of onnx2ncnn tool.
"""
wildcard = os.path.abspath(
os.path.join(
os.path.dirname(__file__), '../../../build/bin/onnx2ncnn'))
paths = glob.glob(wildcard)
lib_path = p... | 66fd84d1b351dfae00e6ebe91484ee253166630a | 49,926 |
def find_media(args, src_api, dest_api, dest_project):
""" Finds existing media in destination project. Returns media that need to be created and ID
mapping between source and destination medias.
"""
media = []
media_mapping = {}
if args.skip_media:
logger.info(f"Skipping media due t... | 5289fbda897de9812b07fda38fce8f958f14634b | 49,927 |
def list_host_deployment_info(package_name, environment, version=None,
revision=None, apptypes=None):
"""Give all deployment information for a given package
deployed to hosts for given (or all) application types
and in given environment
"""
dep_info = (Session.qu... | 6f6a1b1800ac2aebf0ec8cce201f1e967fe9c524 | 49,928 |
def _predict(group, model):
"""internal use """
# generate arrays and interpolate components onto the unknown x array
xdat, ydat = get_arrays(group, model.arrayname)
if xdat is None or ydat is None:
raise ValueError("cannot get arrays for arrayname='%s'" % arrayname)
spectra = interp(xdat, ... | 71b5c1d43f2c6d0d9ae3d420b9eb8cf7e4c0f904 | 49,929 |
def computer_quals(predictions, n_alleles):
"""Computes GQ and QUAL values from a set of prediction probabilities."""
## GQ is prob(GQ) / prob(all genotypes)
## GQ is rounded to the nearest integer to comply with the VCF spec
index, gt = get_max_index(predictions, n_alleles)
gq = int(np.around(ptrue... | 25156e145a48e39d5d397bf3b1c415bf1188a557 | 49,930 |
from typing import OrderedDict
def parse_surveyvars_spss(spss_file, lgr=logger):
"""Extracts dat metadata from CDC YRBS SPSS files
Extracts the survey questions and responses from the
CDC YRBS SPSS file.
Args:
spss_file: SPSS file path
Returns:
survey_vars: an OrderedDict with s... | 0615f44121e7e04e78741cd8e6a7d95a96317568 | 49,931 |
from typing import Type
def false_only(t: Type) -> ProperType:
"""
Restricted version of t with only False-ish values
"""
t = get_proper_type(t)
if not t.can_be_false:
if state.strict_optional:
# All values of t are True-ish, so there are no false values in it
retu... | e04510724636db35c347d817fbadef01dfd8da70 | 49,932 |
def make_timevect(num, step, start=0.0, dtype=None):
"""
Return a linearly spaced time vector.
Remark: using this method is preferable to ``numpy.arange(start, start + num * step, step``
which may yield an incorrect number of samples due to numerical inaccuracy.
Parameters
----------
num :... | bc417bb09323f1b8a70c4a8665cab5cc79fda799 | 49,933 |
import uuid
def repr_tree(tree, viz, current_node, rec_depth, color_map, parameters):
"""
Represent a subtree on the GraphViz object
Parameters
-----------
tree
Current subtree
viz
GraphViz object
current_node
Father node of the current subtree
rec_depth
... | 02bfa986d85fe3fb2cccc90b7c8c34ce190949b0 | 49,934 |
import typing
def get_object_versions(object_id: int) -> typing.List[Object]:
"""
Returns all versions of an object, sorted from oldest to newest.
:param object_id: the ID of the existing object
:return: the object versions
:raise errors.ObjectDoesNotExistError: when no object with the given
... | dd1a71f8de9cc075238a52d1f2f473870f66add7 | 49,935 |
def _transform_xml(xml, xslt_path):
"""
Converts the xml document from one metadata schema to another
"""
xslt_file = open('{0}/../misc/tools/{1}'.format(ROOT_PATH, xslt_path))
xslt_root = etree.parse(xslt_file)
transform = etree.XSLT(xslt_root)
return transform(xml) | 20562e5e93c49925c00e669a49d40990252113fd | 49,936 |
def load_parser(d):
"""
For loadclass = 'POINTLOAD', 'LINELOAD' or 'AREALOAD'
LINELOAD "B2141" "5F" TYPE "POINTF" DIR "GRAV" LC "LL_0.5" FVAL 15 RDIST 0.4
LINELOAD "B2109" "6F" TYPE "UNIFF" DIR "GRAV" LC "DL" FVAL 0.7
LINELOAD "C7" "GF" TYPE "TEMP" LC "THN" T -10
AREALO... | 0562dad9dbf82d4b791eed280546a977b07fbad8 | 49,937 |
def neuron_create(num_inputs, activation, bias, layer_id, neuron_id):
"""
Create a neuron.
:param num_inputs: input dimension
:param activation: activation function.
:param bias: bias for this activation.
:param layer_id:
:param neuron_id:
:return:
"""
return {'weights': np.zeros... | de88130876fae85fd60fa167e5f4945d6906e3a7 | 49,938 |
import json
def load_config(config_name):
"""
Loads a json config file and returns a config dictionary.
:param config_name: the path to the config json
"""
with open(config_name) as config_file:
config = json.load(config_file)
return config | 5920d21c67133d2d106863910fdd8db95efc94e6 | 49,939 |
import math
import logging
def lowres_initial_dem_splines_fit(
lowres_dsm_from_matches: xr.Dataset,
lowres_initial_dem: xr.Dataset,
origin: np.ndarray,
time_direction_vector: np.ndarray,
ext: int = 3,
order: int = 3,
):
"""
This function takes 2 datasets containing DSM and models the
... | b8e322d8720359ea7fb2d9d0c8f78ce8968b7a99 | 49,940 |
def test_bitext(input_path1, input_path2, output_path1, output_path2):
"""
Test the reconstruction of a bilingual corpus passing it through Tokenizer/Multitext pipeline.
Example:
text.test_bitext('data/en-fr/test.en-fr.en', 'data/en-fr/test.en-fr.fr', 'data/en-fr/test.en-fr.en-bi', 'data/en... | 4210fdd025cfb6fb7db687c32ea7896e1dd6a7ef | 49,941 |
def apply_pca(X, n_pc):
"""
Applying PCA
"""
U, S, V = pca(X)
Z = project_data(X, U, n_pc)
# attempt to recover the original structure (and later render it again):
X_recovered = recover_data(Z, U, n_pc)
return X_recovered | 8934fbb9185d286c21e638ceed592a2df8022c59 | 49,942 |
from robot.parsing.builders import get_model
def collect_errors(source):
"""
:return list(Error)
"""
# TODO: Check if we should provide a curdir.
model = get_model(source, curdir=None)
errors_visitor = ErrorsVisitor()
errors_visitor.visit(model)
return errors_visitor.errors | 13a83b017f09c304b056f8f332fc0c1efb1800bd | 49,943 |
import json
import urllib3
def get_wordlist():
"""Returns default HarSanitizer wordlist."""
hs = HarSanitizer()
try:
if WORDLIST_PATH[:4] == "http":
wordlist_json = json.loads(urllib3.urlopen(WORDLIST_PATH).read())
wordlist = hs.load_wordlist(wordlist=wordlist_json)
else:
wordlist = h... | 0d46bd460e43b44fa34fae5946611530ea9149e2 | 49,944 |
def load_fraud(n_rows=None, verbose=True):
"""Load credit card fraud dataset.
The fraud dataset can be used for binary classification problems.
Arguments:
n_rows (int): Number of rows from the dataset to return
verbose (bool): Whether to print information about features and labels
... | 6e1bdd3aa2b7f4885e2d1108ce733a7b9140d9a6 | 49,945 |
def args_to_int(args: list) -> tuple:
""" Convert augs to int or return empty """
try:
return tuple([int(i) for i in args])
except ValueError:
return () | 1585e4c80f9637d5b1773e04c92b2f477092dd7a | 49,946 |
from typing import Dict
def update_variables_with_types(*, variables: Dict[VarName, VarDecl], types: Dict[VarName, VarType]) -> Dict[VarName, VarDecl]:
"""
:raises TypingError:
"""
updated: Dict[VarName, VarDecl] = {}
for name, decl in variables.items():
if decl.type is None:
... | d804c83e1c03b8a013655866d8e524925d6efcbc | 49,947 |
import unittest
def suite():
"""A testsuite that has all the Flask tests. You can use this
function to integrate the Flask tests into your own testsuite
in case you want to test that monkeypatches to Flask do not
break it.
"""
setup_path()
suite = unittest.TestSuite()
for other_suite ... | c9a0715cfa580b30e849ee730eb30a7b6c195406 | 49,948 |
def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
header_filter, extra_arg, extra_arg_before, quiet,
config):
"""Gets a command line for clang-tidy."""
start = [clang_tidy_binary]
if header_filter is not None:
start.append('-hea... | 227664a3045111e4c0c944710e88910dfcf78d13 | 49,949 |
def natsort_key(s, number_type=int, signed=False, exp=False):
"""\
Key to sort strings and numbers naturally, not lexicographically.
It also has basic support for version numbers.
For use in passing to the :py:func:`sorted` builtin or
:py:meth:`sort` attribute of lists.
Use natsort_key just lik... | a07c55d1fcb45dba9a44c00895ee536674b1c1d7 | 49,950 |
import numbers
def _check_sample_weight(sample_weight, X, dtype=None):
"""Validate sample weights.
Note that passing sample_weight=None will output an array of ones.
Therefore, in some cases, you may want to protect the call with:
if sample_weight is not None:
sample_weight = _check_sample_we... | 56de0d9cc91fe1c46f38294ac58d0108c18486ff | 49,951 |
def get_by_name(opname, operators):
"""Return operator class instance by name.
Parameters
----------
opname: str
Name of the sklearn class that belongs to a TPOT operator
operators: list
List of operator classes from operator library
Returns
-------
ret_op_class: class
... | 29692c00ae034c391582ab7dd40a1d728406e73f | 49,952 |
import math
def snrm2(x, dims, mnl = 0):
"""
Returns the norm of a vector in S
"""
return math.sqrt(sdot(x, x, dims, mnl)) | c3ef4e3d23233637fb6969aace06a6db5480e8b8 | 49,953 |
import time
import json
def get_tweets(count = 800, output_file=None,verbose=True):
"""
Pulls Tweets from Authenticated Twitter User
Twitter API maxes out at 800 or input count number
"""
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKE... | 97f23c3c6611f9103caeb0c3b65fd0699116ca88 | 49,954 |
def import_pkg_operation():
"""This function imports the primary package and returns ``True`` when successful."""
return True | e78efc086d7060fd95f1d1da76585c2dbbfcee76 | 49,955 |
def extract():
""" extract data from MongoDB """
# connect mongodb container of the same composer from python
client = pymongo.MongoClient("mongodb")
# get database
db = client.tweets_stream_db
# get collection
collection = db.tweet_stream_json
return collection | 7c3a85ac3238d5eb2f943d1f2112765541b4e760 | 49,956 |
def run_cmd(command, **kwargs):
""" Runs a command and returns an array of its results
:param command: String of a command to run within a shell
:returns: Dictionary with keys relating to the execution's success
"""
cwd = kwargs.get('cwd', None)
try:
ret = check_call(command, shell=Tru... | 21ba41a7fe2a1e889122ee7928350b61e880e330 | 49,957 |
def generate_group_expected_result(group_config) -> dict:
"""Generate expected result for groups"""
expected_result = {
'group_visible': not group_config['ui_options']['invisible'],
'editable': not group_config['read_only'],
"content": group_config['default'],
}
if group_config['... | c48c60f36ff4e370b7da6484e823ebff2d957217 | 49,958 |
import os
import multiprocessing
def run_device_analysis_pool(task_func, device_names, processes=None, cwd=None,
walltime=3600):
"""
Use a multiprocessing.Pool to run a device-level analysis task
over a collection of device names. The task_func should be
implemented as pi... | a106537fe7d156a87fea79fe64212ad954aa1943 | 49,959 |
def get_sub_text_from_xml_node( xmlnode, _text=None ):
"""
Concatenates the content at and under the given ElementTree node, such as
text = get_sub_text_from_xml_node( xmlnode )
"""
if _text == None:
_text = []
if xmlnode.text:
_text.append( xmlnode.text )
for nd in xm... | 620200d5ba782f5696c720ba4da722204783bd17 | 49,960 |
import os
import scipy
def resample_to_shape(source_file, region, sp_res, grid, prefix=None,
nan_value=None, dest_nan_value=None, variables=None,
shapefile=None):
"""
Resamples images and clips country boundaries
Parameters
----------
source_file : str
... | c239e549ea09a0fe246de55cc220da09d8005c53 | 49,961 |
def group_dates(dates):
"""
Groups list of given days day by day.
:param dates: List of dates to group.
:type dates: list
:return:
"""
days = []
times = []
for elem in dates:
if elem.date() not in days:
days.append(elem.date())
times.append([elem.ti... | 35ff8c2da3e4a27eb065afe630814e29eb06df7d | 49,962 |
def sum_normalization(X, types):
"""
Normalize decision matrix using sum normalization method.
Parameters
----------
X : ndarray
Decision matrix with m alternatives in rows and n criteria in columns
types : ndarray
Criteria types. Profit criteria are represented ... | 7a70e44962e5f15e71d286c971a5b0e3540da23a | 49,963 |
def make_colormap(seq):
"""Return a LinearSegmentedColormap with colors defined as the sequence.
The sequence red to blue can be defined as:
`make_colormap(['red', 'blue'])`
or equivalently
`make_colormap([(1,0,0), 'blue'])`
For more control over color transitions, floats can be included after... | 290315a670b1df6addfa2f04f95bb605d5c4f2ca | 49,964 |
def do_magick_identify(input_file):
"""The different informations of an image.
:param input_file: The input file.
:type input_file: jfscripts._utils.FilePath
:return: A directory with the keys `width`, `height` and `colors`.
:rtype: dict
"""
def _get_by_format(input_file, format):
... | ef982e7c20f5023d0d90bf1dbc51fd82791aaa58 | 49,965 |
def is_asciidoc(path):
"""Returns true if the given path is an Asciidoc file."""
# NOTE: Only checking the extension for now.
if path.endswith(".txt"):
return True
return False | be7fd1994e21b3e540f7bdb6cc7da74753491644 | 49,966 |
def svn_client_args_to_target_array2(*args):
"""
svn_client_args_to_target_array2(apr_getopt_t os, apr_array_header_t known_targets,
svn_client_ctx_t ctx, svn_boolean_t keep_last_origpath_on_truepath_collision,
apr_pool_t pool) -> svn_error_t
"""
return _client.svn_client_args_to_target_ar... | a591462fd26ccd249726d187d6264428883a6383 | 49,967 |
def originProblem():
"""
Logic grid puzzle: 'origin' in CPpy
Based on... to check originally, currently part of ZebraTutor
Probably part of Jens Claes' master thesis, from a 'Byron...' booklet
"""
person = ['Mattie', 'Ernesto', 'Roxanne', 'Zachary', 'John']
age = ['109', '110', '111', '112'... | 634517806e5c7087c27dfceaf89c978a49668d39 | 49,968 |
import multiprocessing
def do_fiteach(save_cube=None, save_pars=None, show_plot=False):
"""Fits a cube with a gaussian for later use"""
if save_cube is None:
save_cube = 'test.fits'
test_sigma = 10 # in pixel values, each pixel is CDELT3 thick
make_test_cube((100,10,10), save_cube,
... | d9fa03e9340040bf5bbdd458a6ea291cab924331 | 49,969 |
def prev(y):
"""Reverses next() function from super_cipher.py.
next() generates the next keystream according to the following bit mapping:
current triplet -> next possible triplet : current bit -> next possible bit
0 000 --> (0 000, 4 100) : 0 --> (0, 1)
1 001 --> (0 000, 4 100) : 1 --> (0, 1)
... | bc1b50ebb016b76327c93ba7f6aef2f6cd63b453 | 49,970 |
def is_runtime_path_valid(path):
""" Returns True if the given path is a valid runtime path, False
otherwise.
"""
try:
_parse_from_path(path)
return True
except InvalidMetadata:
return False | d32b5b49dc800ae68644ed7f6c8ee5dc5830a82c | 49,971 |
def list_role_privileges(role, web_session=None):
"""Lists all privileges of a role.
Args:
role (str): The name of the role.
web_session (object): The webserver session object, optional. Will be
passed in by the webserver automatically
Returns:
The generated shell reque... | ab6170b1c9bf048013932b2e9408836c4809ca38 | 49,972 |
from pathlib import Path
def radar_factory(num_vars, frame='circle'):
"""Create a radar chart with `num_vars` axes.
This function creates a RadarAxes projection and registers it.
Parameters
----------
num_vars : int
Number of variables for radar chart.
frame : {'circle' | 'polygon'}
... | c8361c6429f74399d5bd7f967b09e1f65144b8c3 | 49,973 |
def replaceShapes(path, controls=None, remove=True):
"""
Replaces all the the given control shapes with controls of the same name in the given path file.
If no controls given, will use selected. If none selected, will use all controls in the scene.
Args:
path (string): Path to Maya file to refe... | 10f6e3d40f96493487b27815017a153f511abec3 | 49,974 |
from typing import Dict
from typing import Any
def generator_run_to_dict(generator_run: GeneratorRun) -> Dict[str, Any]:
"""Convert Ax generator run to a dictionary."""
return {
"__type": generator_run.__class__.__name__,
"arms": generator_run.arms,
"weights": generator_run.weights,
... | 83805a3458d5db740019af7e907c96ca69430068 | 49,975 |
import six
def preprocess_data_for_dqn(data, reward_model="sparse"):
"""
Creates n_students traces of (s,a,r,s') tuples which can be loaded into the experience replay buffer.
Each student yields one trace
:param data:
:param reward_model: "dense", "sparse" or "semisparse".
If "sparse", then re... | bb1e6ada6bc6e7d3228b73e1fb1e1b3158daf4bc | 49,976 |
def find_layer_of_feature(feature, layer_notation='conv'):
"""
This function find the layer correspondent to the given feature in a certain embedding.
It returns the layer name of the feature.
There are two different notations:
- The used by the FNE: vgg16_model/relux_y
- The used by the vgg16 ... | 2c07811c667f795511b32bf914e9810f4e5ae77b | 49,977 |
import os
def get_default_regions():
"""
Current order of precedence
- AWS_DEFAULT_REGION overrides everything else
- region_args come next
- fall back to us-east-1 I guess
"""
env_region = os.environ.get('AWS_DEFAULT_REGION', None)
regions = []
if env_region is not None and env_... | 1e53f4f594b04bbe25aef387913630e515ce5b49 | 49,978 |
def connect():
"""Page for connecting to the pi."""
return(str(connect_to_pi.delay({'r': ['VS1_GT1']}))) | ab2c10bb83393cc49582f3c62573cb603a7aa1f6 | 49,979 |
import os
import logging
import sys
def install_platformio_core():
""" update platformio version """
cwd = os.getcwd()
python_path = os.path.join(cwd, "platformio_core", "python.exe")
pip_path = os.path.join(cwd, "platformio_core", 'get-pip.py')
cmd = "{0} {1} --no-warn-script-location".format(py... | 49fc5f8d88d06f674d620c01588e85b1ef4f4f2a | 49,980 |
from typing import Tuple
def _vector_sample_perturbations(
theta: ArrayTree, key: PRNGKey, std: float,
num_samples: int) -> Tuple[ArrayTree, ArrayTree, ArrayTree]:
"""Sample a perturbation with positive and negative pair."""
def _fn(key: PRNGKey) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
pos =... | 368d10e14dd3069f193c89e9b287216c690dc5ee | 49,981 |
def solution_detail(request, solution_id):
"""
:param request:
:param solution_id:
:return:
"""
solution_id = solution_id
solution_item = Solution.objects.get_solution_by_id(solution_id)
if not solution_item:
raise Http404
# 获取关键词
solution_keywords = solution_item.keyword... | e17bf56ec9567ea63d25a886737c9f7bb104a022 | 49,982 |
def _execute_query(sql_raw, params, qry_type):
""" Handles executing queries based on the `qry_type` passed in.
Returns False if there are errors during connection or execution.
if results == False:
print('Database error')
else:
print(results)
You cannot use `if no... | 80c0a76ecbc4b01b2b9f31923a3356de19ad4251 | 49,983 |
def index(page=None):
"""
preview_data = Preview.query.all()
# print(preview_data) # [<Preview 17>]
first_preview_id = Preview.query.order_by(Preview.id.asc()).first().id # <Preview 17>
# first_preview_id = Preview.query.order_by(Preview.id.asc()) # sql
# print(first_preview_id.id)
return... | f509ce04b2e6aba3b4bfca5b3dba42ceb80aaa36 | 49,984 |
def conv2d_w(x, W):
"""conv2d returns a 2d convolution layer with full stride."""
# return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
return wavecomp_ops_module.wave_conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') | cce0312dad3d684af6ef202941aca0b36f40b001 | 49,985 |
def interpolate_colors(colors, flat=False, num_colors=256):
""" given a list of colors, create a larger list of colors interpolating
the first one. If flatten is True a list of numers will be returned. If
False, a list of (r,g,b) tuples. num_colors is the number of colors wanted
in the final list """
... | cbcd22544623019d268e2f2b887cfcfbee1821b0 | 49,986 |
def vcv_cart2local(vcv_cart, lat, lon):
"""Transforms a VCV from the Cartesian to the local reference frame. If
only a column vector of variances is supplied then they are assumed to be
uncorrelated and only the column vector of variances is returned.
See Section 4.4.1 of the DynAdjust User's Guide v1.... | 22d9b0fded345c1758fc84c53d28ef6a29607ebb | 49,987 |
def create_instance(test_id, config, args):
"""
Invoked by TestExecutor class to create a test instance
@test_id - test index number
@config - test parameters from, config
@args - command line args
"""
return TestSessions(test_id, config, args) | 34053bc31d6592ae58341fa8350f6e01bca27b1c | 49,988 |
def process_decoded_keypoints_2d(decoded_tensors,
keypoint_names_2d,
include_keypoint_scores_2d,
common_module=common):
"""Processes decoded 2D keypoint tensors.
Args:
decoded_tensors: A dictionary for decoded te... | f9aa19913c89ebe1f18c5378849cb39238623236 | 49,989 |
def compute_propagation(w, phi):
"""
Propagation term
"""
# Compute derivatives x and y
wx = compute_derivative(w, np.array([[-1, 1]]))
wy = compute_derivative(w, np.array([[-1], [1]]))
# Get max and min of wx
wx_max = np.maximum(wx, 0)
wx_min = np.minimum(wx, 0)
# Get max ... | 73ae5d3733af4f23576c18986a630214595df0de | 49,990 |
import tqdm
def dict2PCA(fit_dict, test_dict=None, dim=2, pca=None):
"""
Dimensionality Reduction by PCA with dict data
example of dict data is below:
fit_dict = {"aa": [[ndarray with shape (Na, D)]],
"bb": [[ndarray with shape (Nb, D)]],...}
Args:
... | 049a28f8bfec27dd00c9390e83b2a7b301ca0b86 | 49,991 |
def totree(expr):
"""Simplifies ``expr`` (:py:class:`Expr <histbook.expr.Expr>`) to contain only constants (:py:class:`Const <histbook.expr.Const>`), names (:py:class:`Name <histbook.expr.Name>` and :py:class:`Predicate <histbook.expr.Predicate>`), and function calls (:py:class:`Call <histbook.expr.Call>`)."""
... | f24e224994398819d417d52a6f0974329f30898f | 49,992 |
def decimal_to_short(code):
"""
Convert an ICD9 code from decimal format to short format.
"""
parts = code.split(".")
parts[0] = _zero_pad(parts[0])
return "".join(parts) | 9c5eb5391ffeae52c474ea807eb2c22af633d05a | 49,993 |
def total() -> int:
"""
:return: int: Return sum of number of grains in each of the 64 squares, i.e. 2^64 - 1
"""
# The sum of the geometric series 1 + 2 + 4 + 8... 64 terms is 2^64 - 1
return 2**64 - 1 | 4322456aaff1417354d4b5224594dab9b3c05508 | 49,994 |
import hashlib
def normalize_property_ref(value: rdltypes.PropertyReference, owner_node: node.Node) -> str:
"""
Hash of relative path from owner of the property to the target component's
property
"""
path = "%s->%s" % (value.node.get_rel_path(owner_node), value.name)
md5 = hashlib.md5(path.enc... | 0455d48baef30088259839a746010261d7d6d0b8 | 49,995 |
def needs_db(function):
""" A function wrapper that provides access to the database. """
@wraps(function)
def wrapper(*args, **kwargs):
db_session = Session()
output = function(db_session, *args, **kwargs)
db_session.close()
return output
return wrapper | a9c535639e0ddab56d487d956de15be5fcfe08e1 | 49,996 |
def deluser(name, username, **kwargs):
"""
Remove a user from a group
Args:
name (str):
The name of the group to modify
username (str):
The name of the user to remove from the group
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Ex... | 863dcc1848372c1dbeac712b6c5b2b8d3219035b | 49,997 |
import sys
def unambig_variants(variants, idos_list):
"""Create 'unambiguos' variants for a stop name that equals a city name, depending
on the type of the stop (bus, train or city public transit)."""
# get the right additions list
additions = ADDITIONS.get(idos_list, ADDITIONS['MHD'])
if len(vari... | 3882bb0a7a27184acf4f3907bc5f0d46e3b2820e | 49,998 |
import msvcrt
import os
import threading
def run(challenges, timeout, seed, logfunc):
""" Challenge launcher for replay services
This will setup fds for all challenges according to:
https://github.com/CyberGrandChallenge/cgc-release-documentation/blob/master/newsletter/ipc.md
Args:
challenge... | fd012753701fa381e75fe6841a8d8e7920d3a470 | 49,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.